sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
3e17a3c78277403654f26fc6ace22cb4d2be4de98dece06b3e6da239cbd77fcf | Python | 1,930 | 68 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class MultiAgentEnv(object):
def step(self, actions):
"""Returns reward, terminated, info."""
raise NotImplementedError
def get_obs(self):
"""Returns all agent observations in ... |
e72617cd26a1b15568b9ab0eb21bb2654ab5e338661dd5ee23c310d010826af6 | Python | 1,930 | 80 | """
Created on Nov 24, 2025
Plot Histograms of MEPs and TEPs
@author: mning
"""
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
featDir = rf"R:\Staff Folders\Matthew Ning\TEP_ML\DATA\FeatureStores"
figSaveDir = r"C:\Users\mning\Documents\CNBS_Projects\TRT_iT... |
c176c7739ec6644d8590d2e274630d19e8ee556deae64253e33a8bb750a48c01 | Python | 1,932 | 61 | import snapatac2 as snap
import pandas as pd
import numpy as np
import scanpy as sc
# Import the samples
samples = snakemake.params.samples
atac_anndata = snakemake.input.atac_anndata
# Import metadata
metadata = pd.read_csv(snakemake.input.metadata_table)
# Reset the index for the samples
metadata = metadata_table.s... |
e96672d42ec6daf3694a8d7ae46640a111468b2f4e3202b280020460d6a543e6 | Python | 1,932 | 72 | """
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
from pandas import DataFrame
import pandas._testing as tm
pytestmark = pytest.mark.filterwarnings(
"ignore:Passing a BlockManager to DataFrame:Depr... |
2ebfc162622d9eccb861329c8943d8f7249f1c72369ecad8b2e4a65478e2e7ca | Python | 1,933 | 58 | #!/usr/bin/python
import sys
import os
import commands
import time
import csv
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
if len(sys.argv) != 8:
print 'Incorrect number of arguments:', len(sys.argv)
print 'Usage:', sys.argv[0], '<tf_name> <encoded_... |
95d3ef0949708c753f4bdf04d88490a77e0aa89cc93e93c798320a2782bea98a | Python | 1,933 | 71 | """
Quantum machine learning related data preprocessing and embedding
"""
from typing import Any, Optional, Sequence, Tuple
import numpy as np
from ..cons import backend, dtypestr
from ..gates import array_to_tensor
Tensor = Any
def amplitude_encoding(
fig: Tensor, nqubits: int, index: Optional[Sequence[int]]... |
bd3e0d5d9f876b6f1cffc865ea2c6a7159b0cb616cf040c092bff8363b47f263 | Python | 1,933 | 68 | """
Stabilizer Circuit Benchmark
"""
from time import time
import numpy as np
import tensorcircuit as tc
tc.set_dtype("complex128")
clifford_one_qubit_gates = ["H", "X", "Y", "Z", "S", "SD"]
clifford_two_qubit_gates = ["CNOT", "CZ", "SWAP"]
clifford_gates = clifford_one_qubit_gates + clifford_two_qubit_gates
def g... |
c87d5cc6db9313812ca4b47a15451c9136bbd9ad39e4eb0b46b14629a9066342 | Python | 1,933 | 71 | from src.utils import get_lr
from src import constants
image_size = (64, 64)
batch_size = 32
base_lr = 3e-4
frame_stack_size = 16
config = dict(
image_size=image_size,
batch_size=batch_size,
base_lr=base_lr,
min_base_lr=base_lr * 0.01,
ema_decay=0.999,
train_epoch_size=72000,
num_epochs=[3... |
531a1b4ba0e17e8ab2e1b9e802e3252cef1a72936b0831ac616978bc66c33bc4 | Python | 1,934 | 61 | import numpy as np
import pytest
from pandas import (
Index,
Series,
Timedelta,
timedelta_range,
)
import pandas._testing as tm
class TestTimedeltaIndex:
def test_misc_coverage(self):
rng = timedelta_range("1 day", periods=5)
result = rng.groupby(rng.days)
assert isinstanc... |
aaeb859294b9220a2724349bf7f3e8e1e3b75a2e7095c34aabbdb710c60be8db | Python | 1,935 | 57 | import numpy as np
from pandas import DataFrame
import pandas._testing as tm
def test_head_tail_generic(index, frame_or_series):
# GH#5370
ndim = 2 if frame_or_series is DataFrame else 1
shape = (len(index),) * ndim
vals = np.random.default_rng(2).standard_normal(shape)
obj = frame_or_series(val... |
78bcb980a85b76febf401e110ed1b379babed53dbcd3524ad1a723fca8dd8711 | Python | 1,936 | 52 | import torch
import torch.nn.functional as F
from omegaconf import DictConfig
from .base import BaseModel
class E2EBlock(torch.nn.Module):
'''E2Eblock.'''
def __init__(self, in_planes, planes, roi_num, bias=True):
super().__init__()
self.d = roi_num
self.cnn1 = torch.nn.Conv2d(in_plan... |
8928dfffdc2990f9bec5e6cacd7f63a854647e11247c896a093ccf7cea3e4e0f | Python | 1,937 | 57 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 08:05:03 2023
@author: hill103
this script defines forms used in Drug Search page
"""
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField, RadioField, HiddenField
from wtforms.validators import InputRequired
... |
18bfdaa3ac7b953cd7b0a11ecb0d1a3eab5b9f07c926bd69ddf1210b378f9f5d | Python | 1,938 | 52 | import numpy as np
import torch
def deduplicate_gpu(spike_index_torch, energy_torch,
recording_shape, channel_index,
max_window=5):
#os.environ["CUDA_VISIBLE_DEVICES"] = str(CONFIG.resources.gpu_id)
# find device
device = spike_index_torch.device
# initialize e... |
359da0ef8aa04a7d49e1fe7124d2d0d2f3340cc7863f77f8956dae960a291978 | Python | 1,939 | 76 | """
compilation utilities in tensorcircuit
"""
import tensorcircuit as tc
c = tc.Circuit(3)
c.rx(0, theta=0.2)
c.rz(0, theta=-0.3)
c.ry(1, theta=0.1)
c.h(2)
c.cx(0, 1)
c.cz(2, 1)
c.x(0)
c.y(0)
c.rxx(1, 2, theta=1.7)
c0, _ = tc.compiler.qiskit_compiler.qiskit_compile(
c,
compiled_options={"optimization_level... |
717f1e03dc39a91b31ffde16ba402fac753f310ac5556f05522f446c71dd6258 | Python | 1,939 | 85 | from __future__ import annotations
import pytest
from .. import resources
from textstat.backend import selections
@pytest.mark.parametrize(
"text, syllable_threshold, lang, expected",
[
(
"The quick brown fox jumps over the lazy dog",
2,
"en_US",
set(),... |
e5d92315ad24d006890f4ffeaa345b96a0872422962866dbf3b45572369fd786 | Python | 1,939 | 52 | import numpy as np
from pyglet.window import key
# individual agent policy
class Policy(object):
def __init__(self):
pass
def action(self, obs):
raise NotImplementedError()
# interactive policy based on keyboard input
# hard-coded to deal only with movement, not communication
class Interactive... |
683e9911a7b79414d51dbc9e65b90b1000d9efb890a63da52637961f459cfc91 | Python | 1,944 | 80 | 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 = [
'MGC_Type',
'term',
'estimate',
'std.error',
'statistic',
... |
9560548c045d9f3d6597755126af4a57cb0a26263789b1288c434c832b2a93fd | Python | 1,945 | 58 | from ._automated_readability_index import automated_readability_index
from ._chars_per_word import chars_per_word
from ._coleman_liau_index import coleman_liau_index
from ._crawford import crawford
from ._dale_chall_readability_score import dale_chall_readability_score
from ._dale_chall_readability_score_v2 import dale... |
0296306111e4e921376e12dc8268ce661508f337c8e5fa83735f07293d75f7e1 | Python | 1,948 | 64 | import numpy as np
import pytest
from pimms import numpy_utils
def test_position_in_list_finds_matching_position_with_python_lists():
assert numpy_utils.position_in_list([1, 2, 3], [[0, 0, 0], [1, 2, 3]]) is True
def test_position_in_list_returns_false_when_absent():
assert numpy_utils.position_in_list([1,... |
37d0ec1b8f5022cf093b245c2bcc8b4d926f7e3fad494f2240f98ca305c7da45 | Python | 1,949 | 58 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
397c2fec59f60309ca3626a12479e3b6f68a2e776f54bbfffb33be96d955f6a2 | Python | 1,953 | 75 | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
"""
The cache object API for implementing caches. The default is a thread
safe in-memory dictionary.
"""
from __future__ import annotations
from threading import Lock
from typing import IO, TYPE_CHECKING, MutableMapping
if TYPE_CHECK... |
72e27a05ba34ef79601049a18ebdfde0f78cf901665ccf828bec267ec77b1f98 | Python | 1,954 | 67 | import typing as t
from threading import local
if t.TYPE_CHECKING:
import typing_extensions as te
from .core import Context
_local = local()
@t.overload
def get_current_context(silent: "te.Literal[False]" = False) -> "Context": ...
@t.overload
def get_current_context(silent: bool = ...) -> t.Optional["Co... |
aa4142908e4a3628da5f64aead5a2296786d0456e2b262c14b84b21326cd5d9f | Python | 1,954 | 74 | import numpy as np
import pytest
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import BaseMaskedArray
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
arrays += [
pd.array([0.141, -0.268, 5.895, N... |
8e991f5ffe05c1a1c8fb068708714cb37af6946aa2234aad33f28df91006b9b0 | Python | 1,955 | 44 | import jax
import jax.numpy as jnp
import jax.random as random
def get_update_SWAG(debug=False):
def update_SWAG(n, params, params_SWA, params_Sq):
params_flat = jax.flatten_util.ravel_pytree(params)[0]
params_SWA = (n*params_SWA+params_flat) / (n+1)
params_Sq = (n*params_Sq+params_fl... |
229cb37a5fe1e6253f0cc27fbe75d48100b7f2e303327eda754a5649e1102c51 | Python | 1,957 | 84 | import numpy as np
import numba as nb
from numpy.random import PCG64
from timeit import timeit
bit_gen = PCG64()
next_d = bit_gen.cffi.next_double
state_addr = bit_gen.cffi.state_address
def normals(n, state):
out = np.empty(n)
for i in range((n + 1) // 2):
x1 = 2.0 * next_d(state) - 1.0
x2 =... |
3fd591ecd36cc30354dc1a6c84371f7a038949a3ae0b5fd2cd7a17f5913c1db1 | Python | 1,957 | 95 | """Tests for FOOOF core.modutils.
Note: decorators (that are in modutils) are currently not tested.
"""
from fooof import FOOOF
from fooof.core.modutils import *
###################################################################################################
#######################################################... |
29761f70c4577bd74c2b360a8a2f8b4a33a09c0802f613d12c76e0e037fbc476 | Python | 1,958 | 55 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
ff361cb4d2b346a964fe6bab4cd973ae3bb514524bed56bf223aaa77b8a2da55 | Python | 1,958 | 6 | import re
# generated by scripts/generate_identifier_pattern.py
pattern = re.compile(
r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎... |
00b692d0b0271a0d058ba9a04a80be9f5a66ed1159c69e9957eee5f3a7beca4a | Python | 1,962 | 71 | # -*- coding: utf-8 -*-
"""
This script apply diffusion embedding on gradient distance matrix.
Input:
- lh_input_matrix, rh_input_matrix:
the input gradient distance matrices generated by
CBIG_SPGrad_generate_gradient_matrix.m
- output_dir:
the output directory to save the results.
... |
d191d81426003ae14000a200e1beab21d9469bb3f3a58f2a958c0b847fbb55db | Python | 1,964 | 55 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
74a09c844c3c78e6e2d25a064f1f75ba70719bfed41a5537bff16314c76ac183 | Python | 1,965 | 71 | # -*- coding: utf-8 -*-
"""
This module offers general convenience and utility functions for dealing with
datetimes.
.. versionadded:: 2.7.0
"""
from __future__ import unicode_literals
from datetime import datetime, time
def today(tzinfo=None):
"""
Returns a :py:class:`datetime` representing the current day... |
ddfc9559190d0273949eef2bd0edf00bcb9f107206f92a9485c2dfdfcaa6132f | Python | 1,967 | 55 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib_venn import venn2
from scipy.stats import fisher_exact, hypergeom
# 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 ... |
22b87a1bc396073aa347d002f1326dd2001cd3fa2648709bec203a68e3e8d54d | Python | 1,969 | 60 | # %%
from importlib import reload
import utility_funs as uf
import pandas as pd
import pickle
import matplotlib.pyplot as plt
reload(uf)
jitters = [f"j{i}" for i in range(8)]
mismatches = [f'mismatch_{i}' for i in range(1,4)]
# %%
# load evoked potentials
f = open("../results/evokeds.p", "rb")
ev = pickle.load(f)
f.... |
870ede215e217e323eb16f964d306acec91b3186a461a56a8bcb145271d775d3 | Python | 1,970 | 67 | from pathlib import Path
from typing import Optional, List, Sequence
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QListWidgetItem, QListWidget, QSizePolicy
class QTiltImageItem(QListWidgetItem):
def __init__(self, tilt_image_file: Path):
super().__init__()
self.file = tilt_image_file
... |
40bdaf7842e14db11f6370edd18a96edc5ea9564157c73642519a942c1891b87 | Python | 1,971 | 50 | #replace this code with code to read inputs from file, normalize, and sort into lists
import tensorflow as tf
import numpy as np
import pulse2percept as p2p
import random
def parse_inputs(inputsfile):
inputlist = []
infile = open(inputsfile, "r")
data = infile.readlines()
infile.close()
for line in... |
71fb200495b2b71518213f992f796c294541bba2d37868ec4f011f0084de3e52 | Python | 1,971 | 56 | import argparse
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 gimmemotifs.motif import MotifConfig, read_motifs
from genomepy import Genome
import scanpy as sc
import mycelloracle
p... |
bdaebef3ba642d5b5ead476ad2540897bc0d4d4aafdb234b3ed5ae8e0af11d5f | Python | 1,971 | 39 | import os
import numpy as np
import pandas as pd
path = r'E:\ABIDE-fmriprep_BIDS\ABIDE\data\derivatives\fmriprep'
phenotypics = pd.read_csv(r'C:\Users\100063082\Desktop\prepare_ADHD200_ABIDE_phenotypics\Phenotypic_V1_0b_preprocessed1.csv')
sub_ids = phenotypics['SUB_ID'].values
group = phenotypics['DX_GROUP'].values
s... |
be53823d7953e58b7ecb7e349c794605dad8d3f90836a363ed150330f6f1ad0e | Python | 1,971 | 58 | """
Interactive display of surface FastSRM results and Glasser atlas in the browser
Authors: Ana Luisa Pinho
Created: May 2021
Compatibility: Python 3.7
"""
import os
import numpy as np
from nilearn.surface import load_surf_data
from nilearn.datasets import fetch_surf_fsaverage
from nilearn.plotting import plot_s... |
049b569d4a54269b090740c7f8a71222e886e896169c295f8d39d9d615960f70 | Python | 1,974 | 47 | #!/usr/bin/env python
# *- coding: utf-8 -*-
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 textwidth=79:
"""[License: GNU General Public License v3 (GPLv3)]
idat-tools: tools for manipulating IDAT files
Copyright (C) 2024 Youri Hoogstrate
This program is free software: you can redistribute i... |
19d0d674acd6aa42268ddc33b950705b626f23b68cce93d5f10ca1c56809a348 | Python | 1,975 | 77 | """
Patched ``BZ2File`` and ``LZMAFile`` to handle pickle protocol 5.
"""
from __future__ import annotations
from pickle import PickleBuffer
from pandas.compat._constants import PY310
try:
import bz2
has_bz2 = True
except ImportError:
has_bz2 = False
try:
import lzma
has_lzma = True
except Im... |
59ce71c3dcb8dea70c62a74e8daf8a6f5868abe569c743252194366d518fca81 | Python | 1,975 | 72 | """
Sets up a template for conformer search class. Uses run as main method.
Should return a list of atoms, conformer geometries, charges, and energies.
"""
from abc import abstractmethod, ABC
from dataclasses import dataclass
import logging
from typing import List
logger = logging.getLogger(__name__)
class BaseCon... |
4085fce5f7c2c0cbedcd7b4b91678f15092ca3f995b487df5a96e0cb8ca4133d | Python | 1,976 | 60 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.arrays import BooleanArray
from pandas.tests.arrays.masked_shared import ComparisonOps
@pytest.fixture
def data():
"""Fixture returning boolean array with valid and missing data"""
return pd.array(
[True, Fa... |
5865f4b310ad88037b26c35d6726626f347c6a99bfea8632eb6496ad596c7e5b | Python | 1,976 | 54 | import logging
import sys
VERBOSE_LEVEL_NUM = 15
SUBPROCESS_LEVEL_NUM = VERBOSE_LEVEL_NUM -1
def make_logger():
# Add new logging level between DEBUG and INFO
logging.addLevelName(VERBOSE_LEVEL_NUM, "VERBOSE")
def verbose(self, message, *args, **kws):
if self.isEnabledFor(VERBOSE_LEVEL_NUM):
... |
f7ce5e1601e5f9a88c67225eea6a601850ee160ac9878adfef83a71cdcc2ae66 | Python | 1,976 | 50 | import torch
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def train(epoch, num_epochs, model, criterion, device, train_loader, optimizer, model_type, single_channel_idx: int = 0):
"""Training logic for a single epoch."""
model.train()
y_true = []
... |
7b942b072545566eab1196dd4a27d8041098f9ccd3cd6659e72ecec9facf92cc | Python | 1,977 | 76 | import io
import numpy as np
import pytest
from pandas.compat import is_platform_windows
import pandas as pd
import pandas._testing as tm
from pandas.io.excel import ExcelFile
from pandas.io.excel._base import inspect_excel_format
xlrd = pytest.importorskip("xlrd")
if is_platform_windows():
pytestmark = pytes... |
3e4af05ef4c1f320e459bb9732f3a8b3661f525ef9416de9f0973a2a5bc08d9b | Python | 1,979 | 70 | import torch
from torch.utils.data import Dataset
import numpy as np
from anndata import AnnData
def split_data(
adata: AnnData,
percent: float,
sample_obs: str,
layer = ['spliced','unspliced']
):
"""
Split the dataset for training and validation
Parameters
----------
adata
... |
938b8193db4ea2e60426a9ec439a4c3073a217aac8c50ed7db99634cef46da31 | Python | 1,979 | 50 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import logging
from ..create_omop_db import CreateOmopDb
from .etl_base import SqlServerEtlBase
# pylint: disable=too-few-public-methods
class SqlServerCreateOmopDb(CreateOmopDb, SqlServerEtlBase):
def __init__(
self,
**kwargs,
... |
4a5db6e1708d2bf971f8dea4f617974bf836fdbc26a82249c8a0efee913f1d0c | Python | 1,980 | 69 | import pytest
from pandas import (
DatetimeIndex,
Series,
Timestamp,
date_range,
)
import pandas._testing as tm
pytestmark = pytest.mark.filterwarnings(
"ignore:Setting a value on a view:FutureWarning"
)
@pytest.mark.parametrize(
"cons",
[
lambda x: DatetimeIndex(x),
lamb... |
595d2fc4dedc76e6d7e6a9e06fe18e6e717ea3f296e30a26b7c13ec1de4ffafe | Python | 1,980 | 75 | """
Cli Argparser Utility helpers for CLI tasks.
"""
from __future__ import annotations
import argparse
from abc import ABC, abstractmethod
try:
from collections.abc import Callable # Python 3.11+
from typing import Any, Required, TypedDict
except ImportError:
from collections.abc import Callable # n... |
e62d4d0671529588f2e5f6553f1e165b85170c463ed94af495fc88db922996b2 | Python | 1,981 | 44 | import torch
import numpy as np
import pandas as pd
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from model_scripts.classifier import MLP
path_results = r'' #here, enter the path where results have been saved
atlas = 'AICHA' #choose atlas (AICHA, AAL)
... |
f7a3bff355c7005405559a57f9833b3d55f3a0828bf0fa27b546ef114ec8c336 | Python | 1,981 | 61 | import torch
import torch.nn.functional as F
from utils import measure
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
def train_batch(edges, labels, rep_model, agg_model, lr, Hg, X, agg_mode, weight_decay):
rep_model.train()
agg_model.train()
optimizer = torch.optim.Adam(list(rep_... |
07f0bb1ae03dd8eb16b7d6bb277edebd56cd215d9dbf50077220c3aa7321486e | Python | 1,983 | 67 |
import os
import imageio
import math
from subprocess import Popen
import sys
import time
import multiprocessing as mp
recDate = "20191030"
expt = "mouse11"
chunkLengthInFrames = 3000
numCams = 6
# Get metadata from video (assuming all cameras are the same)
basedir = os.path.join('D:\\',recDate,expt,'raw','Camera')
o... |
7c8ab317d2d9b374cb9bb248e2d124e09c64ca7996a99e53c9d0a6735dac190b | Python | 1,987 | 55 | from hypothesis import (
assume,
example,
given,
strategies as st,
)
import numpy as np
import pytest
from pandas._libs.byteswap import (
read_double_with_byteswap,
read_float_with_byteswap,
read_uint16_with_byteswap,
read_uint32_with_byteswap,
read_uint64_with_byteswap,
)
import p... |
32151a77477e0a17550f361c869296c18dbe52b6320936586bfef825d4bd8d6b | Python | 1,988 | 66 | import sys
import os
from pathlib import Path
from PySide6 import QtGui
from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QApplication, QSplashScreen
from app.model.grimace_recorder_model import GrimaceRecorderModel
# Show splashscreen before the big module imports to show the user that something's hap... |
724d694a014289b47a1c385a0595c87085056077f67e4a0a3ef5a0cae8ed0f9c | Python | 1,994 | 69 | """Counts the number of dendritic spike events from files
Author: Drew B. Headley
"""
import numpy as np
import pandas as pd
from .load_dendevt_csv import load_dendevt_csv
from .seg_dendevt import seg_dendevt
from .ser_seg_dendevt import ser_seg_dendevt
def count_dendevt_files(
dend_fname,
dt,
win_ser,
... |
f2e368a1c7d8e1a01efbe86fd8a53f78b259d70e86def14c864081601863ad06 | Python | 1,994 | 42 | # 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 tempfile import TemporaryDi... |
32a4dcf897f08ac0a813a27e13b8a71cd5b20587b212b623de53980a2d4a3502 | Python | 1,995 | 46 | """
Code for creating a multiagent environment with one of the scenarios listed
in ./scenarios/.
Can be called by using, for example:
env = make_env('simple_speaker_listener')
After producing the env object, can be used similarly to an OpenAI gym
environment.
A policy using this environment must output actions in ... |
00069762b765d77e6957da710c03a9bf9e8f58e4ec4d07de89b655161f0d6ec5 | Python | 1,996 | 56 | from __future__ import annotations
import os
# This is a temporary fix due to a `DeprecationWarning` from the `qtconsole` package:
# """DeprecationWarning: Jupyter is migrating its paths to use standard platformdirs
# given by the platformdirs library. To remove this warning and
# see the appropriate new directories... |
560981d169ae6205ec64d39ed1071945a6fc8f2326c11a8384db48f95e85225f | Python | 1,996 | 32 | import sys
'''This file aims to collect performance on test data with the optimal parameter set for each TF'''
mode = sys.argv[1]
if mode == "collect_best":
out_file = open("../out/performance_100_filters.txt", "w")
out_file.write("\t".join(["tf", "RCmodel", "canonical", "RCaugmented", "double"]) + "\n")
f... |
e8b4e3bce5d12935187e80db42fb55f254bc25763685c86e250d3cbadd1f3c4e | Python | 1,997 | 74 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import logging
import traceback
from typing import Tuple, cast
import polars as pl
from ..achilles import Achilles
from .etl_base import BigQueryEtlBase
class BigQueryAchilles(Achilles, BigQueryEtlBase):
"""
BigQuery implementation that runs t... |
0e813a0df8ca90828626d4541bcbaf04d34604ebe8a956672fc26bfc8d6f38b4 | Python | 1,999 | 77 | import functools
import numpy as np
import pytest
from pandas.compat import is_platform_windows
import pandas as pd
import pandas._testing as tm
pytest.importorskip("odf")
if is_platform_windows():
pytestmark = pytest.mark.single_cpu
@pytest.fixture(autouse=True)
def cd_and_set_engine(monkeypatch, datapath):... |
68edd882402884bb0bcc2350eef8c8c1da4550ccf470f2db72ebb12248ee37be | Python | 1,999 | 64 | """Tests for the NumpyVersion class.
"""
from numpy.testing import assert_, assert_raises
from numpy.lib import NumpyVersion
def test_main_versions():
assert_(NumpyVersion('1.8.0') == '1.8.0')
for ver in ['1.9.0', '2.0.0', '1.8.1', '10.0.1']:
assert_(NumpyVersion('1.8.0') < ver)
for ver in ['1.7... |
d8acb5deae21bbccb85aef5edefd83a488c436084ed3e3d5c4da9ec0141e8722 | Python | 2,001 | 50 | """
Protocol code for training session of optimism bias.
Imports from protocol.py
Author:
Swetha Shankar, Himanshu Aggarwal
himanshu.aggarwal@inria.fr
March 2022
"""
from os.path import join
from os import sep, getcwd
from psychopy import visual, data
import glob
import pandas as pd
from protocol import (take_input, ... |
8bc02ce86ece5ff3adfedd53200c9c9142cda5f3a65d36d33c820f6544328ead | Python | 2,002 | 50 | from .lifneuron import LIFNeuron
import math
class TempoLIFNeuron(LIFNeuron):
'''
classdocs
'''
def __init__(self, tau_ref=0.5, vthresh=5, Rm=2, Cm=0.2):
'''
Constructor
'''
LIFNeuron.__init__(self, tau_ref, vthresh, Rm, Cm)
def setPreference(self):
# Gaus... |
d0cb1efe4b02747b0441cef7227ee4105a9f1ac722ef37a148d3ce09d03ac91a | Python | 2,002 | 72 | from abc import ABCMeta,abstractmethod
from conf.conf import configs
from Modal.cluster import *
class Layer():
'''
classdocs
'''
_metaclass_ = ABCMeta
def __init__(self, neutype):
'''
Constructor
'''
self.neutype = neutype
self.groups = {}
@abstractmeth... |
7844a755343c2778812f6e1b58ab7b4e61f10b914988b64ca4a8f0d55dfbeaa6 | Python | 2,004 | 62 | import pytest
import pandas as pd
import pandas._testing as tm
class TestDatetimeIndexFillNA:
@pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"])
def test_fillna_datetime64(self, tz):
# GH 11343
idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"])
exp = p... |
39bd0d08ae2a46b6f2d5088b6b8ecf0e969bbc965a0b51bde876cf10c830b02a | Python | 2,013 | 67 | """
comparison between expectation evaluation with/wo lightcone simplification
"""
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("jax")
tc.set_contractor("cotengra")
def brickwall_ansatz(c, params, gatename, nlayers):
n = c._nqubits
params = K.reshape(params, [nlayers, n, 2])
for j in... |
ceb4a14990114ac5942e85c8e6d756ab081948b43ebbfdf134f4b972907841b6 | Python | 2,014 | 85 | from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
from pandas.core.dtypes.common import is_list_like
if TYPE_CHECKING:
from pandas._typing import NumpyIndexT
def cartesian_product(X) -> list[np.ndarray]:
"""
Numpy version of itertools.product.
Sometimes faster ... |
375b39ce9cb458bf78df10ea88e3fdbf8869177f0e7322883b3b8030a277af97 | Python | 2,015 | 81 | 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 = [
'reaction',
'reaction-name',
'term',
'estimate',
'std.erro... |
a289496f5e5dfdcafac4702fa88c0238f3a6e3a5ed4ef0e44414e56303097fb3 | Python | 2,015 | 54 | from pathlib import Path
work_dir = Path("/workdir")
data_dir = work_dir / "data"
sensorium_dir = data_dir / "sensorium_all_2023"
configs_dir = work_dir / "configs"
experiments_dir = data_dir / "experiments"
predictions_dir = data_dir / "predictions"
new_mice = [
"dynamic29515-10-12-Video-9b4f6a1a067fe51e15306b9... |
0486b49b3fc9f3a36e39b530d942328cb60a526f15ddbd37e2926b4e4bc5fac0 | Python | 2,016 | 74 | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import configparser
import os
from paste.deploy import loadapp
from gunicorn.app.wsgiapp import WSGIApplication
from gunicorn.config import get_default_config_file
def get_wsgi_app(config_uri, name=None, defaul... |
960632a385bc95bdb6c2c631d84941041d1cbd236505582e7300732f8ddd7f31 | Python | 2,016 | 53 | from __future__ import annotations
from pip._internal.models.format_control import FormatControl
# TODO: This needs Python 3.10's improved slots support for dataclasses
# to be converted into a dataclass.
class SelectionPreferences:
"""
Encapsulates the candidate selection preferences for downloading
and... |
4d9c216c44dbde414e03dfa9fac64b7098f37dab9dcac5eacd1d5f62720a5733 | Python | 2,017 | 50 | import numpy as np
def data_transfer(B_txt, A_txt):
"""
Aim:读取训练数据,并将其转换为可以处理的形式
@param B_txt:Before processing -txt
@param A_txt:After processing -txt
@return:After processing -data
"""
with open(B_txt, 'r') as f: #'dataA_B.txt'
data_all =[]
data_1 = []
data_2 = []... |
5c29a9f04f08e8139e358179f478d214076fd6133d59a0ef97c5034b5d3fd39a | Python | 2,017 | 64 | import pytest
from numpy import array
from . import util
class TestReturnLogical(util.F2PyTest):
def check_function(self, t):
assert t(True) == 1
assert t(False) == 0
assert t(0) == 0
assert t(None) == 0
assert t(0.0) == 0
assert t(0j) == 0
assert t(1j) == ... |
787854466314c5997af7f60ae1dc6e6841439d63fcf621f8753926f633ed71a0 | Python | 2,018 | 72 | from __future__ import annotations
import glob
import logging
import shlex
import shutil
import sys
from collections.abc import Iterable # noqa: TC003
from importlib.metadata import PackageNotFoundError, version
from cli.lib.common.utils import run_command
logger = logging.getLogger(__name__)
def pip_install_pac... |
3f1d288a7a95e55ba0abe638e53c86385178a5df807682743b53a289e2294010 | Python | 2,025 | 67 | import abc
from typing import Type
import numpy as np
import torch
from src import constants
class ResponseNormalizer:
def __init__(self, mouse: str):
std = np.load(
str(constants.sensorium_dir / mouse / "meta" / "statistics" / "responses" / "all" / "std.npy")
)
threshold = ... |
7e5a8ba6fcf1d94a85e9dda1c9c1f799ecbc7400382801d4c6bd1c9d41b9564f | Python | 2,028 | 65 | import os
import sys
from typing import Optional
import pytest
from anndata import AnnData
import scvelo as scv
@pytest.fixture(scope="session")
def dentategyrus_adata(tmpdir_factory):
path_to_file = tmpdir_factory.mktemp("dentategyrus").join("adata.h5ad")
_ = scv.datasets.dentategyrus(file_path=path_to_fi... |
235d7ef5a2c501beb18d83f7e3d27b91b86ce183058e043fa53b9f6f3de4417e | Python | 2,029 | 65 | import csv
import os
from tqdm import tqdm
import scipy as sp
import numpy as np
import scipy.io as spio
def read_oasis3_data(csv_fname,
data_dir,
reg_var_name='Age',
num_sub=5,
reg_var_positive=1,
len_t... |
6bc659102acf45f7ec6ecd14ca0791e3bfdf394959a699f1f903ecb2b217b41d | Python | 2,032 | 77 | """ Functions for converting from DOS to UNIX line endings
"""
import os
import re
import sys
def dos2unix(file):
"Replace CRLF with LF in argument files. Print names of changed files."
if os.path.isdir(file):
print(file, "Directory!")
return
with open(file, "rb") as fp:
data = ... |
7fa1c9c5f26bc5bfcc715a7e366ddd16bc9f8ddd6c8038576095689c6a754517 | Python | 2,032 | 58 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
0aed4d6ab640037d53561ae62c0dbc8156ca877531f1b172db4c7bb8409bd497 | Python | 2,035 | 61 | import sys
import numpy as np
from aicsimageio import AICSImage
from pylibCZIrw import czi as pyczi
from pathlib import Path
# Generalized dynamic iteration
def iterate_planes(czi, doc):
"""
Dynamically iterate through YX planes in an array based on axes_order.
Args:
array (numpy.ndarray): The da... |
33746df512aea7012aef5263c694056d43bb58a48eb8b7d1d6c9113366be85b2 | Python | 2,036 | 67 | r"""
Building the required library in this example requires a source distribution
of NumPy or clone of the NumPy git repository since distributions.c is not
included in binary distributions.
On *nix, execute in numpy/random/src/distributions
export ${PYTHON_VERSION}=3.8 # Python version
export PYTHON_INCLUDE=#path to... |
6426faf67e423ca3d137d9b5c5547919595873ef359552a2ef8a00d37a818c8f | Python | 2,036 | 66 | import sys
import scipy
import numpy as np
import pandas as pd
import scanpy as sc
import matplotlib.pyplot as plt
import seaborn as sns
adata = sc.read_h5ad(snakemake.input.merged_rna_anndata)
sc.pl.umap(
adata,
color='cell_type',
legend_loc='on data',
show=False
)
plt.savefig(snakemake.output.course... |
fee84d57399cde6098def111ac542ef235192b754d8c83567ac994353b0d0f73 | Python | 2,036 | 57 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
a4d25fe271712e901e2b1941522d86123d1ad888f59e2918d1469b4ca5deb13e | Python | 2,037 | 55 | from __future__ import annotations
from typing import TYPE_CHECKING, Collection, Generic
from .structs import CT, KT, RT, RequirementInformation, State
if TYPE_CHECKING:
from .resolvers import Criterion
class BaseReporter(Generic[RT, CT, KT]):
"""Delegate class to provide progress reporting for the resolve... |
897e0375c1978cb6c6c700ada918d66d68dfd4644e3a549eee7b3a53873f0649 | Python | 2,038 | 67 | """
Visualize the contraction path generated by cotengra for a TensorCircuit circuit.
Requires `cotengra` and `matplotlib`.
"""
import cotengra as ctg
import matplotlib.pyplot as plt
import tensorcircuit as tc
def main():
# 1. Define a quantum circuit
n = 12
c = tc.Circuit(n)
# Apply some layers of ... |
cdbbef1a2b36d041b1984825f64b7cd4a10d1a2f04dd59f7f6afb4dc3c94d22e | Python | 2,039 | 68 | """ Entrainment of dendritic events with respect to an ongoing rhythm
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 .ph_seg_dendevt import ph_seg_dendevt
from .ph_rhym_... |
9a25d8fecb5002a5de1e053214c12d5e2a98f04b85e48facebca183e081f022e | Python | 2,040 | 72 | import argparse
import os
import numpy as np
import pandas as pd
import scipy.spatial as spatial
from utils import convert_distance_to_adjacency
def get_args():
parser = argparse.ArgumentParser(
description="Compute distance matrix from SNP matrix"
)
parser.add_argument(
"--vcf_files",
... |
2f725a417f043e091bcfc62d37e77888d02a606872c58188aa360101ad5d140c | Python | 2,042 | 74 | """Convert a W&B sweep YAML file to bash commands and optionally execute them.
python sweep_converter.py sweep.yaml --dry # just show commands
python sweep_converter.py sweep.yaml # actually run them
"""
import itertools, json, subprocess, sys
from pathlib import Path
try:
import yaml # pip install p... |
c7d79b72d7f2bc2005a4c4e5309e58c7070d601ce382aeb325a2a4366efcaf83 | Python | 2,042 | 61 | """
pygments.styles
~~~~~~~~~~~~~~~
Contains built-in styles.
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pip._vendor.pygments.plugin import find_plugin_styles
from pip._vendor.pygments.util import ClassNotFound
from pip._ven... |
3d6f39be82ec45d3799d4361f92701fdaa1e5d063370f1e0fad49c379f7d7ff6 | Python | 2,043 | 79 | import gc
import sys
from collections.abc import Iterator
from pathlib import Path
import pytest
from sqlmodel import Session, create_engine, select
from cali.runner import CaliRunner
from cali.sqlmodel import (
FOV,
ROI,
DetectionSettings,
Experiment,
)
THREADS = 1
MODEL = "cpsam" # cellpose4
# MOD... |
41370b4a464ae66ccd52d5d18a27db0475767f1541241e26f8f6685a46c7caca | Python | 2,043 | 50 | import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenario
class Scenario(BaseScenario):
def make_world(self):
world = World()
# add agents
world.agents = [Agent() for i in range(1)]
for i, agent in enumerate(world.agents):
... |
b334900105c605ad231a52359b8d14bd1e29e90441fa4887b9eee117b2bf8cbe | Python | 2,043 | 67 | """Average dendritic events within electrotonic quantiles
Author: Drew B. Headley
"""
import numpy as np
def mean_dendevt(seg_df):
"""
For each segment's dendritic event time series it is averaged across segments
with the same electrotonic quantile.
Parameters
----------
seg_df : dataframe
... |
d3930798f0fe0ba630f943a76b8212b07bcf425cfe48fdcedf9a35a99567560c | Python | 2,043 | 95 | import uuid
import os
import utils
if __name__ == "__main__":
_uuid = str(uuid.uuid4())
nwires, nlayer, nitrs, timeLimit, isgpu, minus, path, nbatch = utils.arg(qml=True)
if isgpu == 0:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
else:
import tensorflow as tf
gpu = tf.config.lis... |
e0873e988d81f6b9a19e3c9dbbd933c75eac72efbf9668a861f8c4872f26cd3e | Python | 2,043 | 46 | import numpy as np
from .gwdt_impl import gwdt_impl
def gwdt(img:np.ndarray, structure:np.ndarray=None) -> np.ndarray:
"""
Gray-weighted distance transform
This algorithm finds the weighted manhattan distance from the background
to every foreground point. The distance is the smallest sum of image val... |
8c6abfa2eba7413577cf35ff72b97d902557db3b64d69eb631ca83d965519c09 | Python | 2,044 | 93 | from __future__ import annotations
from typing import TYPE_CHECKING
from pandas.plotting._matplotlib.boxplot import (
BoxPlot,
boxplot,
boxplot_frame,
boxplot_frame_groupby,
)
from pandas.plotting._matplotlib.converter import (
deregister,
register,
)
from pandas.plotting._matplotlib.core impo... |
3024d2e7e166967512abef0f8dcf225b968b909699278ec1639cd433151af4c9 | Python | 2,047 | 71 | import anndata as ad
import scvi
import scanpy as sc
import torch
import pandas as pd
import scipy
import numpy as np
import sys
print(torch.cuda.is_available())
scvi.settings.seed = 0
torch.set_float32_matmul_precision('high')
# Read in AnnData atlas object
adata = ad.read_h5ad(sys.argv[1])
adata.X = scipy.sparse.... |
43db5d3ac1f833ce9b9a388da2f1e0230987a3d19b45ce26b1eeb31db850de25 | Python | 2,048 | 63 | # coding: utf-8
import torch
from .spherical_harmonics_any_order import Y0, Y1, Y2, Y3, Y4, Y5, Yl
"""
This returns a list of all spherical harmonics (up to order L)
derived from the input unit vectors u. For up to L=5, this
function is optimized to reduce the number of floating point
operations. When L>5 is request... |
1cd1a664467cb6f86e26b79f089710ca15a9e81c526f7c19cec373f9b5a54f80 | Python | 2,049 | 71 | """
YASS init file, it contains setup for the package.
Summary: the only way to set global configuration is to create a first session
and pass the desired config, also, make sure that list_devices is not executed
before creating the first session. So do not create sessions here or use
list_devices here, since it will ... |
35ecccd7f8e40b79a63da3d8679ad930a971047665e8e5ae623067a8aea0ecbb | Python | 2,051 | 62 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 17 16:54:12 2019
@author: wanxiang.shen@u.nus.edu
Combining a set of chemical features with the 2D (topological) distances between them gives a 2D pharmacophore. When the distances are binned, unique integer ids can be assigned to each of these pha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.