sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
79c3dd27e08cf076da699a0651fc1ca0eba8d1e233eda12afb1f302f43d959b1 | Python | 1,711 | 69 | import numpy as np
import pytest
from pandas import Series
import pandas._testing as tm
def test_mask():
# compare with tested results in test_where
s = Series(np.random.default_rng(2).standard_normal(5))
cond = s > 0
rs = s.where(~cond, np.nan)
tm.assert_series_equal(rs, s.mask(cond))
rs =... |
3d85309d55d25bd7d758ae2f40c543a605a58eec515be6a611643033c0ff5192 | Python | 1,713 | 47 | from CrystalTracer3D.segment import *
from CrystalTracer3D.io import *
from CrystalTracer3D.band import *
import yaml
from sklearn.neighbors import KDTree
from tqdm.contrib.concurrent import process_map
from skimage.measure import regionprops
import pandas as pd
with open('../vessel_density_local/config.yml', 'r') as... |
5dd419992b4198f22cf2df77b63c7aa4eec19b78286c068e3569057141da19ab | Python | 1,713 | 51 | from __future__ import annotations
import typing as t
from contextvars import ContextVar
from werkzeug.local import LocalProxy
if t.TYPE_CHECKING: # pragma: no cover
from .app import Flask
from .ctx import _AppCtxGlobals
from .ctx import AppContext
from .ctx import RequestContext
from .sessions ... |
674690f919f13a7433a7e491c3cb1e7c01fc5f2052963d8d5d9c0e9478a76df6 | Python | 1,713 | 59 | """
Backend register
"""
from typing import Any, Dict, Text, Union
import tensornetwork as tn
try: # old version tn compatiblity
from tensornetwork.backends import base_backend
tnbackend = base_backend.BaseBackend
except ImportError:
from tensornetwork.backends import abstract_backend
tnbackend =... |
f9ea211a0fa8f5ad18e3b3059dbcad38d8e6598a308bc0de744758bcb649a857 | Python | 1,713 | 50 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Functions for downloading pre-trained DiT models
"""
from torchvision.datasets.utils import download_url
import torch
... |
2c0c13d03639caa958876d2134c611d7e38abbc03d18dc3e4db51f23ca6f8253 | Python | 1,714 | 54 | from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
compilers = ['MIPSFCompiler']
class MIPSFCompiler(FCompiler):
compiler_type = 'mips'
description = 'MIPSpro Fortran Compiler'
version_pattern = r'MIPSpro Compilers: Version (?P<version>[^\s*,]*)'
executables = {... |
380c0b6bb2d536910ef71ea9b3e92626ce3b7222cd597a153fd68a9b3accada6 | Python | 1,715 | 61 | """Plot the waveform used for stimulation.
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.com/wmglab-duke/ascent.
RUN THIS FROM REPOSITORY ROOT
"""... |
b549662fdf484f8a6b58663559e7897e3f3b21abda3a207f6a875da062e91c06 | Python | 1,716 | 62 | """Plot the waveform used for stimulation.
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.com/wmglab-duke/ascent.
RUN THIS FROM REPOSITORY ROOT
"""... |
01a8035aac1e6b6c8159fd74282f69b4180ca4c8f12a9f3200102687e3503959 | Python | 1,718 | 70 | """
pygments.console
~~~~~~~~~~~~~~~~
Format colored console output.
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
esc = "\x1b["
codes = {}
codes[""] = ""
codes["reset"] = esc + "39;49;00m"
codes["bold"] = esc + "01m"
codes["faint... |
39d3d2416f9d587c4d1e4c6ae5c65c11ec20128528c4ddbc372bea27a8998115 | Python | 1,719 | 53 | # coding: utf-8
# See notebook:
# https://github.com/paninski-lab/yass-examples/blob/master/batch/multi_channel.ipynb
"""
Splitting large files into batches where every batch has n
observations from m channels using BatchProcessor.multi_channel
"""
import os
from yass.batch import BatchProcessor
path_to_neuropixel... |
d1ceba5f27964abd49f4666775cef79595fea397c5bc495a4968320e64ebbf53 | Python | 1,721 | 64 | import time
from dev_utils import read_fcon1000_data
from ker_reg_utils import kernel_regression_choose_gamma
import numpy as np
# ### Set the directorie
# s for the data and BFP software
# In[2]:
BFPPATH = '/ImagePTE1/ajoshi/code_farm/bfp'
FSL_PATH = '/usr/share/fsl/5.0'
# study directory where all the grayordinate f... |
115e1ba89d027614070188af78e55a3a15d56a91a76a3e60a41ca9271d9e4652 | Python | 1,723 | 41 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..functional import cutoff_function, softplus_inverse
"""
computes radial basis functions with exponential Bernstein polynomials
"""
class ExponentialBernsteinRadialBasisFunctions(nn.Module):
def __init__(self, num_basis_... |
3d40c15b0d04899e9d75bb892db7c054a2510176d948b64409be0954ddecd1f5 | Python | 1,724 | 64 | import glob
import os
import sys
import h5py
import numpy as np
#from dfsio import readdfs, writedfs
from scipy import io as spio
from tqdm import tqdm
#from surfproc import patch_color_attrib, smooth_surf_function
sys.path.append('../stats')
from brainsync import normalizeData
from get_connectivity import get_conne... |
c10d27e759fc4df260ad0c5f09af8d246b9a780fb5421e4ac7327b315d2adecf | Python | 1,724 | 46 | import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self, weight=None):
"""
Initialize the DiceLoss module.
Args:
weight (Tensor, optional): Optional class weights (not used in this implementation,
but can be extended ... |
fba87b7f83475a6740d3466364f8589a0cc1849b7725e7e64e7a2db668ff1403 | Python | 1,724 | 67 | """SQLModel database schema and utilities for calcium imaging analysis.
This package provides a complete SQLModel-based database schema for storing
and querying calcium imaging analysis data. It includes models for hierarchical
data organization (Experiment → Plate → Well → FOV → ROI) and tools for visualization
and e... |
0731ff44d8be55d2615cb96db81eccbe9f43f9b594fe3fc43c2dddeda25f54f3 | Python | 1,727 | 50 | # -*- coding: utf-8 -*-
import csv
import numpy as np
def calc_score(answer_list, pt_fdbk_list):
"""
Calculate the final score of the participant based on the number of
correct answers.
"""
answer = np.array(answer_list)
pt_fdbk = np.array(pt_fdbk_list)
score_list = np.where(answer == pt_... |
647a8d1d3296f8185c5c42605033f38c54061136fb32b1ed4f592cb3747ac92e | Python | 1,728 | 46 | """
Protocol code for training session of motion perception task.
Imports from protocol.py
Himanshu Aggarwal
himanshu.aggarwal@inria.fr
January 2022
"""
from psychopy import visual
from protocol import (take_input, convert_deg_to_pix,
show_init_screen, present_run, extend_to_all_fields,
... |
80a062e898586fb253da010da230467a6949aa7fc300b31565a79d1c5bc2892e | Python | 1,728 | 71 | from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
import sys
if sys.version_info < (3, 10):
from typing_extensions import ParamSpec, TypeVar
else:
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
T = TypeVar("T")
LANG_CONFIGS: dict[str, dict[str, f... |
f7989402e5917dc809e926b217c02a79666cd63e5bb6b23e47ee8d9cbbc28cdb | Python | 1,729 | 54 | #===========================================================================
# embedded_stf.py
# 2009.09.14
# Don't modify this file unless you know what you are doing!!!
#===========================================================================
"""
embedded_stf.py
starting code to embed wxPython into the stf applic... |
222cf7ec3f24b4c17c31047f06bfcab20b0223e0067e3de8882bc745887bf80c | Python | 1,730 | 67 | # %%
import mne
import utility_funs as uf
from sys import argv
# config
# load data and set channel names, montage
data_dir = '/Users/kbas/sci_data/harmonicity_modulation/'
p = int(argv[1])
data_id = uf.participant_fname(p)
fname = data_dir + data_id + '.bdf'
ar_path = 'autoreject'
ica_path = '../results/ica/'
ch_eog... |
83de41e42075552dc7583b7306c6a3a602335c45fd32dcb57752950d3afe5347 | Python | 1,731 | 45 |
import json
def output_controller(operations_graph):
output = []
# for operation in operations_log['MCQ_1hop.json']['Which of the following binds to the drug Leucovorin? 1. CAD 2. PDS5B 3. SEL1L 4. ABCC2 5. RMI1']:
# print(len(operations_graph))
index = 0
operation = operations_graph[0]
while... |
932832bac915e8f5298155edfb67b7f5224457e7f2ab1192e353817d1eea58b0 | Python | 1,732 | 46 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import logging
from ..create_omop_db import CreateOmopDb
from .etl_base import BigQueryEtlBase
class BigQueryCreateOmopDb(CreateOmopDb, BigQueryEtlBase):
def __init__(
self,
**kwargs,
):
super().__init__(**kwargs)
d... |
a17fdcc1e4dca4a776ef2c0df7be8a098a60d2815eefb31e0d6aa7449430551a | Python | 1,732 | 61 | import pytest
from pandas import (
DatetimeIndex,
date_range,
)
from pandas.tseries.offsets import (
BDay,
DateOffset,
Day,
Hour,
)
class TestFreq:
def test_freq_setter_errors(self):
# GH#20678
idx = DatetimeIndex(["20180101", "20180103", "20180105"])
# setting w... |
5b494f3d155936830d374828eac1685ed574bea9393e01d69df980d17f5207ea | Python | 1,734 | 60 | """
perfect sampling vs. state sampling
the benchmark results show that only use perfect/tensor sampling when the wavefunction doesn't fit in memory
"""
import time
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("jax")
# tf staging is too slow
def construct_circuit(n, nlayers):
c = tc.Circuit(... |
31731b29a7100de93f7af3c0b4783bb3883d82dc518bbaec26271d3d2fb30dcc | Python | 1,736 | 67 | # coding: utf-8
# See notebook:
# https://github.com/paninski-lab/yass-examples/blob/master/batch/multi_channel_apply_memory.ipynb
"""
Applying transformations to large files in batches:
BatchProcessor.multi_channel_apply lets you apply transformations to
batches of data where every batch has observations from every... |
8a2b2dd84a7326f0d5221300c57abc8859d306c89901dea2a65c5f98d6e83729 | Python | 1,737 | 70 | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import logging
from argparse import ArgumentParser
from typing import TYPE_CHECKING
from pip._vendor import requests
from pip._vendor.cachecontrol.adapter import CacheControlAdapter
from pip._vendor.... |
8f8482beb7be11a18efbb220fef66ea1a44b17f8f01ec928177a6237fd2bc8d5 | Python | 1,737 | 41 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..functional import cutoff_function, softplus_inverse
"""
computes radial basis functions with overlap Bernstein polynomials
"""
class OverlapBernsteinRadialBasisFunctions(nn.Module):
def __init__(self, num_basis_function... |
f4f8daee9c23e724c422b2800a0b5761323a13dcd86e59274cf3291fefe0c434 | Python | 1,737 | 54 | from typing import Optional
from napari.viewer import Viewer
from .imc_controller import IMCController
from .imc_widget import IMCWidget
def napari_get_reader(path):
if isinstance(path, list):
if any(not IMCController.is_imc_file(p) for p in path):
return None
elif not IMCController.is_i... |
8ea42636d7086f21c6ca5a5339123eb6c9f177c695fbff8aa12dcbc49456636d | Python | 1,740 | 54 | """
Functions related to tracking
"""
import os
import pandas as pd
from communication import experiment_folder_in_path
def print_FL_plan(FL_plan_dict):
""" Print FL plan
:param FL_plan_dict: dict, FL plan
"""
print('\n========\nFL plan:\n========\n')
for k, v in FL_plan_dict.items():
pr... |
1782e270b3e9bffd188b722f18045fc517e97b90db5e093ea6ecbb148936c9f0 | Python | 1,741 | 50 | #! /usr/bin/env python
##########################################################################
# NSAp - Copyright (C) CEA, 2016 - 2018
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.... |
71b8147ee135124778446a4fa910d761289820a30bcf112940914e959a9179e4 | Python | 1,742 | 64 | """ Generate count series using point process times
Author: Drew B. Headley
"""
import numpy as np
import pandas as pd
def ser_pt(pts, step_len, win_lim):
"""
Produces a times series that is binned counts of a point process
Parameters
----------
pts : numeric array-like, N length
the ti... |
294f304dd028fe6f67aca3ad274ed091dbcc97af90331b3fc71d85f470f1527e | Python | 1,745 | 56 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Example of running StarCraft2 with RLlib PPO.
In this setup, each agent will be controlled by an independent PPO policy.
However the policies share weights.
Increase the level of parallelism by changing --... |
64b62b9c0a982f2e5e8134950b7f4a7c2fa3caba71681686a5ad5fbcc254d784 | Python | 1,745 | 46 | import argparse
from .frequencies import count_ngrams
from .vecs import Vectors
def render_wordcount(wordcount):
if wordcount > 10000000000:
prettycount = '{: >6}B'.format(int(wordcount / 1000000000))
elif wordcount > 10000000:
prettycount = '{: >6}M'.format(int(wordcount / 1000000))
elif ... |
a10b7884d2dd0470a4cddaae8c0c3474109ad1d8bd3f329c0a4027a3603840bf | Python | 1,746 | 52 | import numpy as np
from shap.links import identity
from shap.utils._masked_model import _build_fixed_output
class MaskedModelSuite:
sample_count = 100
mask_count = 100
output_count = 4
def setup(self):
rng = np.random.default_rng(0)
self.batch_positions = np.arange(self.mask_count + ... |
0698867252c758322cd773da9fffe9213987aab7a5ed5ac9842d2312f752849e | Python | 1,747 | 43 | import os
if 'NUMBA_THREADING_LAYER' not in os.environ:
# Prefer OpenMP (fork-safe with llvm-openmp) over TBB (not fork-safe).
# Falls back to workqueue (serial but safe) if OMP is unavailable.
# TBB is listed last because it causes warnings when joblib forks.
os.environ['NUMBA_THREADING_LAYER_PRIORITY'... |
f876cc0d64e5dcb14b0e1b2bce6f3ca2f7f7cef8899461d3dc92266633d19ce9 | Python | 1,747 | 50 | """
Generate a msgpack file, _chinese_mapping.msgpack.gz, that maps Traditional
Chinese characters to their Simplified Chinese equivalents.
This is meant to be a normalization of text, somewhat like case-folding -- not
an actual translator, a task for which this method would be unsuitable. We
store word frequencies us... |
4fd2fef0a7220b8e7f697922e0fee1c7e2ce1e9617253e5ec6066fc84a64d932 | Python | 1,748 | 53 | import os
import tempfile
import numpy as np
import xarray as xr
import cedalion.io as cio
def create_dummy_Adot():
"""Create a dummy Adot matrix for testing."""
channels = ["S" + str(i) + "D" + str(j) for i in range(14) for j in range(30)]
channel = np.random.choice(channels, 100)
num_verts = np.rand... |
8961d7c80c34964f52726a5c831678b9f6b98925e9188bed8fd3ec00495f5052 | Python | 1,750 | 65 | """
Event handling function module
Contains functions for processing UI events and interactions
"""
def on_button_press(app, label):
"""
Simulate the visual effect of a button press
Args:
app: The application instance
label: The label control that was pressed
"""
# Simulate the... |
67af4561263a4109d900974856513e236240904bad45b76f6435e59badf76279 | Python | 1,751 | 54 | import os
def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'random', 'bi... |
d9dd04b4f25960fdd7444e82eab7c95ba42c3e51680f1aa03b5c8fc4e6da884d | Python | 1,754 | 54 | """
Check the numpy version is valid.
Note that a development version is marked by the presence of 'dev0' or '+'
in the version string, all else is treated as a release. The version string
itself is set from the output of ``git describe`` which relies on tags.
Examples
--------
Valid Development: 1.22.0.dev0 1.22.0.... |
c9c1d07aaf5f4bf77bf6dfbb3684a8de99790a7e51206f49268fd359ec552172 | Python | 1,759 | 56 | import os
import unittest
from datetime import datetime
from unittest.mock import MagicMock, patch
os.environ["GITHUB_TOKEN"] = "test_token"
from delete_old_branches import delete_old_tags
@patch("delete_old_branches.delete_branch")
@patch("gitutils.GitRepo._run_git")
class TestDeleteTag(unittest.TestCase):
de... |
d2bc484de8e90afce706be1bacdacdccb292ddd1b3bff7b4bed5f816f71bf090 | Python | 1,761 | 73 | from typing import List
import numpy as np
from sklearn import metrics
from tensorflow.keras.callbacks import History
def calculate_sensitivity(tp, fn):
return tp / (tp + fn)
def calculate_specificity(tn, fp):
return tn / (tn + fp)
def calculate_accuracy(tp, tn, y):
return (tp + tn) / len(y)
def ca... |
e2498fa193a89c27cc6cb5c096eb1e7ad4335e312afff2368632fdf4695c07b8 | Python | 1,761 | 55 | from hypothesis import given
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
import numpy as np
from numpy import ndarray
from scipy.sparse import csr_matrix
from scvelo.core import l2_norm
# TODO: Extend test to generate sparse inputs as well
class TestL2Norm:
@given(
... |
07bca03bc8b6eba2a553920de6d8a78a0aa69cd7f964632aed71b92f6abb0d1f | Python | 1,762 | 75 | from typing import List
class WeightedMeter:
def __init__(self, name: str = None):
self.name = name
self.count = 0
self.sum = 0.0
self.avg = 0.0
self.val = 0.0
def update(self, val: float, num: int = 1):
self.count += num
self.sum += val * num
s... |
e8ca0b77f0014bb585510d46fdbd3205dbb3356031ed452aa11f4890d558ba8f | Python | 1,763 | 40 | import numpy as np
def calculate_similarity_matrix(beta_series):
"""
Computes a Fisher-z transformed correlation matrix for a beta series[cite: 352].
Input: (trials x voxels) array.
"""
corr_matrix = np.corrcoef(beta_series)
# Clip to avoid infinity in arctanh and apply Fisher r-to-z [cite: 352... |
624ec20bbfd6ef9053d6c08f327226482459cd1ec73ec11d4b47586df778d1ac | Python | 1,764 | 63 | """Path utility helpers for CLI tasks."""
from __future__ import annotations
import logging
import shutil
from pathlib import Path
logger = logging.getLogger(__name__)
def get_path(path: str | Path, resolve: bool = False) -> Path:
"""Convert to Path object, optionally resolving to absolute path."""
if not... |
8d737a9396e1822306f74cd7a0b42231c3ddf1be67a427cf28b7a791548d7677 | Python | 1,764 | 64 | import numpy as np
import os
from yass.correlograms_phy import compute_correlogram
def remove_high_xcorr_peaks(save_dir,
fname_spike_train,
fname_templates,
sampling_rate,
threshold=5,
... |
ef200f43c600d4e6c4e2e9d0023da81eb75dbb1ae5a1d4777978d2783d96085f | Python | 1,764 | 77 | # %%
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
peaks = pd.read_csv('../results/csv/mismatch_peaks.csv')
# %%
m1_peaks = peaks[peaks.mismatch == 'mismatch_1']
m1_peaks
# %%
fig, axs =plt.subplots(ncols=2, nrows=2, figsize=(12,8), sharex=True)
# mmn amplitude
sns.violinplot(m1_peaks, x=... |
c1693a185bb14e98e8820086b6091c789a2d8b8a558e5e3f7c7417a4d39a4988 | Python | 1,766 | 61 | # -*- coding: utf-8 -*-
from ._parser import parse, parser, parserinfo, ParserError
from ._parser import DEFAULTPARSER, DEFAULTTZPARSER
from ._parser import UnknownTimezoneWarning
from ._parser import __doc__
from .isoparser import isoparser, isoparse
__all__ = ['parse', 'parser', 'parserinfo',
'isoparse'... |
38c36a9e365e0b0cb986cb7f4e701eb3b79a543ff8d013b87ddeafbb7230b879 | Python | 1,768 | 72 | """
Streaming 6Dof from QTM
"""
import asyncio
import xml.etree.ElementTree as ET
import pkg_resources
import qtm
QTM_FILE = pkg_resources.resource_filename("qtm", "data/Demo.qtm")
def create_body_index(xml_string):
""" Extract a name to index dictionary from 6dof settings xml """
xml = ET.fromstring(x... |
95c9991afe6c2873a7143fd1cd9c2f9464a3d7d31e03ee6b08ca5d7f64a0c3b6 | Python | 1,768 | 48 | from __future__ import annotations
from typing import Collection, Generic, Iterable, Iterator
from ..structs import CT, RT, RequirementInformation
class Criterion(Generic[RT, CT]):
"""Representation of possible resolution results of a package.
This holds three attributes:
* `information` is a collecti... |
967fe3690b602e545448563adbbca21c6da00fb020697cd129a12515587b7c34 | Python | 1,768 | 57 | from __future__ import annotations
from typing import TYPE_CHECKING, Collection, Generic
from ..structs import CT, RT, RequirementInformation
if TYPE_CHECKING:
from .criterion import Criterion
class ResolverException(Exception):
"""A base class for all exceptions raised by this module.
Exceptions deri... |
4b98df3cee18a8eafc80995a16815fd726f94b52e3a98536f78383e516686190 | Python | 1,769 | 64 | import unittest
import tempfile
import runpy
import sys
import io
from contextlib import redirect_stderr
from pathlib import Path
from rna3db.utils import read_json
class TestCommandPipeline(unittest.TestCase):
mmcif_path = Path(__file__).parent / "test_data" / "mmcifs"
tbls_path = Path(__file__).parent / "... |
9d919ed3536cb99992f3c70caaaf1f1856ca97eba6be65a35ddf011a64778d3a | Python | 1,769 | 65 | import numpy as np
import pytest
from pandas._libs import lib
import pandas.util._test_decorators as td
import pandas as pd
import pandas._testing as tm
def assert_block_lengths(x):
assert len(x) == len(x._mgr.blocks[0].mgr_locs)
return 0
def cumsum_max(x):
x.cumsum().max()
return 0
@pytest.mark... |
b7cdf62a1531a58b4e7ee49aac61a3583586654430e746f7d534b72db8ceacbe | Python | 1,769 | 67 | """Click parameters for the BiG-SCAPE Benchmark CLI command"""
# from python
import click
from pathlib import Path
# from other modules
from big_scape.benchmarking.benchmark import run_bigscape_benchmark
from big_scape.diagnostics import init_logger, init_logger_file
import big_scape.enums as bs_enums
# from this mo... |
4c60bb7eeb6979549ab6d2e631311a9a3816c19dfbfd553c15aa3b39314ff48c | Python | 1,771 | 48 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers.unmap_predictor import UnmapPredictor
from .layers.convnext import ConvNeXtV2Block
class ConvNeXtLSTM(nn.Module):
def __init__(self, window_size: int = 2048, bin_size: int = 4, nr_tracks=1, use_map: bool = False):
super().__ini... |
db33316f7b1cd5249536c9549f2bc183924017ad4da5435f3133319af320761a | Python | 1,772 | 44 | """
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 ... |
be2c32b65db49cb78e8eff57e3a244c00f431ef65efa66a6c3b30609e0e265e3 | Python | 1,774 | 68 | """Handle optional dependency imports.
Inspired from pandas: https://pandas.pydata.org/
"""
from __future__ import annotations
import importlib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from types import ModuleType
# A mapping from import name to package name (on PyPI) when the package name
# is diffe... |
20a6814f4b3a98d0ea9ca4e9b9572193189c7bfbb9696fbd5e2406ab6a5cd88f | Python | 1,775 | 49 | """
sphinx extension for conditional toc
"""
import re
from sphinx.directives.other import TocTree
# adpoted from https://stackoverflow.com/a/46600038
def setup(app):
app.add_directive("toctree-filt", TocTreeFilt)
return {"version": "1.0.0"}
class TocTreeFilt(TocTree):
"""
Directive to notify Sphi... |
456af33069c2d0fb66a5848592f084eebd65951f3c827717b826a400084513ec | Python | 1,775 | 57 | """
baseline calculators for physical systems
"""
import numpy as np
def TFIM1Denergy(
L: int, Jzz: float = 1.0, Jx: float = 1.0, Pauli: bool = True
) -> float:
# PBC
# nice tutorial: https://arxiv.org/pdf/2009.09208.pdf
# further investigation on 1 TFIM solution structure is required
# will fail... |
a91f08b267f8d0c9768a6a6a8c6ce32f68be091c864f15d512fcd040c9097c9a | Python | 1,776 | 54 | import pytest
from numpy import array
from . import util
@pytest.mark.slow
class TestReturnInteger(util.F2PyTest):
def check_function(self, t, tname):
assert t(123) == 123
assert t(123.6) == 123
assert t("123") == 123
assert t(-123) == -123
assert t([123]) == 123
a... |
d47bb176c6695f0cbb1f612c0f76c45e04be789e0001f9a83df6f6235c966113 | Python | 1,776 | 45 | import time
from typing import List
import cv2
import numpy as np
import torch
from grimace.frame_quality_model import FrameQualityModel
from grimace.preprocessing.image import crop_image_to_square, average_channels
class FrameQualityScorer:
def __init__(self, frame_quality_model: FrameQualityModel):
se... |
0ff911132ebbb2fa3a6bfacb1d0bc8665cfcc4b449759a69a905dc3d0d358e19 | Python | 1,778 | 69 | """
preprocess
"""
from typing import Union
import abc
import torch as tc
import numpy as np
class Preprocessing(abc.ABC, tc.nn.Module):
def forward(
self,
curr_obs: Union[tc.LongTensor, tc.FloatTensor],
prev_action: tc.LongTensor,
prev_reward: tc.FloatTensor,
prev_done: t... |
285becf3ce789fee68685bad0a261c15d09c26187670efb0b53f52c8a4b78e03 | Python | 1,778 | 57 | import torch
import torch.nn as nn
from captum.attr import IntegratedGradients
# Mock GNNModel to simulate the issue
class MockGNNModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(10, 1)
def forward(self, x, edge_index):
# Check if edge_index was expande... |
2c4efd93e415ca564c5c4582a827f9506d00e8502971e33f391a87e6eec20771 | Python | 1,778 | 54 | from pathlib import Path
import cv2
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 BufferVideoWriter(QueueProcess):
@Trace.trace(logger)
def __init__(self, vide... |
20d74e890ecca305cbafa6517828aad09ca451e16f456a1cc64ddffa2964f6fd | Python | 1,780 | 55 | import numpy as np
import pytest
from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas import (
Categorical,
Timedelta,
)
import pandas._testing as tm
def test_cast_1d_array_like_from_scalar_categorical():
# see gh-19565... |
64c9127e9c85c9d94b481949f30e05fc2bd6fb0fdb7a4b368921eda21d7773d8 | Python | 1,780 | 46 | """Defines ASCENT Exceptions.
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.com/wmglab-duke/ascent
"""
class MorphologyError(Exception):
"""E... |
9b22d03433d90dd56aecf3635d6520918dccf897733f9309359d4f13f0a13442 | Python | 1,783 | 49 | import sys
import pytest
import platform
from numpy.f2py.crackfortran import (
_selected_int_kind_func as selected_int_kind,
_selected_real_kind_func as selected_real_kind,
)
from . import util
class TestKind(util.F2PyTest):
sources = [util.getpath("tests", "src", "kind", "foo.f90")]
@pytest.mark.sk... |
c16010c2fa84aefe97a8a5773ae1ed8b375abec0c18bf22a28ca88fad809c5b7 | Python | 1,785 | 72 | #!/usr/bin/env python3
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import umap
import sys
import os.path as osp
import argparse as arp
from ssplots import *
seldict = {
"Neurons_59" : "#d076af",
"Oligos_5" : "#0b73b4",
"Neurons_22" : "#eee54c",
"E... |
07ca5b7c2a6c868d96ff28ccd161ebfb2a8e1ee3f69821ac79cb41484803e2c1 | Python | 1,786 | 51 | """One way to compare GitHub logins across the greenlight guard, and who greenlight is.
The guard reads logins from two GitHub APIs that spell the same account differently:
GraphQL renders a GitHub App's login bare while REST appends `[bot]`. Every comparison
has to go through ``normalize_login`` or the two spellings ... |
4906e092bc709ff197d88f2a83c2799d881de172368c0327983a266c67ba24fe | Python | 1,786 | 71 | from __future__ import annotations
import json
import subprocess
import sys
from enum import Enum
from pathlib import Path
from typing import NamedTuple
# From: https://docs.github.com/en/rest/reference/checks
class GitHubAnnotationLevel(str, Enum):
NOTICE = "notice"
WARNING = "warning"
FAILURE = "failur... |
2a1654b42b7abb02275abbdf2df5a210cf2bb304dc8de7d333a1f48d3f3914a1 | Python | 1,788 | 59 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Example of running StarCraft2 with RLlib QMIX.
This assumes all agents are homogeneous. The agents are grouped and assigned
to the multi-agent QMIX policy. Note that the default hyperparameters for
RLlib QM... |
579497a8f32b29d9e6bea666db942493686129ce9cacc090f603d372c718103d | Python | 1,794 | 54 | from snakemake.script import snakemake
import pandas as pd
import numpy as np
import typing
from scipy.signal import resample, savgol_filter
from tqdm.auto import tqdm
import matplotlib.pyplot as plt
tqdm.pandas()
from helper import *
# read dataframes and params
raw_data = pd.read_pickle(snakemake.input.raw_data)
st... |
76be8d7f247b545ddbb3115031375d0596947799e4b887ae2b62b16882e78983 | Python | 1,795 | 51 | import sys, pandas
file_location = sys.argv[1]
sample_name = file_location.rsplit("/", 1)[1]
header_regions_qc = [
"Median",
"Coverage10x",
"Coverage15x",
"Coverage20x",
"Coverage30x"
]
stats = pandas.read_csv(file_location+"_qcstats.txt", sep=",", header=None, names=header_regions_qc)
samtool... |
bb2915bdbbfb464cdb79593460761b8d9da73f653eb6894e178caf0ee03266b3 | Python | 1,795 | 60 | from .solvers import FixedGridODESolver
from .rk_common import rk4_alt_step_func, rk3_step_func, rk2_step_func
from .misc import Perturb
class Euler(FixedGridODESolver):
order = 1
def _step_func(self, func, t0, dt, t1, y0):
f0 = func(t0, y0, perturb=Perturb.NEXT if self.perturb else Perturb.NONE)
... |
e3bf9ddbdc40eaacd9627774f2505a28adf28fd68167d4ca928aa082e1a5d684 | Python | 1,795 | 49 | import numpy as np
import pandas.util._test_decorators as td
from pandas import (
DataFrame,
Timestamp,
)
import pandas._testing as tm
class TestToNumpy:
def test_to_numpy(self):
df = DataFrame({"A": [1, 2], "B": [3, 4.5]})
expected = np.array([[1, 3], [2, 4.5]])
result = df.to_n... |
7922fd2cbdfb2cabf530fff00250fe04d847cfb3947e57e779f6bfc81429a47d | Python | 1,796 | 33 | #!/usr/bin/env python3
"""Deterministic regeneration of manuscript Figures 1-2 from the stated equations.
Fig 1: closed-form horizon eRRH_C(v) (ADM; T=1, g0=0.2, dmax=1, d0=0, tau_max=10).
Fig 2: design-level Fisher-information ranks (3,3,3,4,4,5) as reported."""
import numpy as np
import matplotlib
matplotlib.use('Agg... |
976abf9f7cc14fdf0ebc8e2057b5d9399302be8e78c6033d7eb07234a0ac6f25 | Python | 1,796 | 56 | # Arithmetic tests specific to DatetimeIndex are generally about `freq`
# rentention or inference. Other arithmetic tests belong in
# tests/arithmetic/test_datetime64.py
import pytest
from pandas import (
Timedelta,
TimedeltaIndex,
Timestamp,
date_range,
timedelta_range,
)
import pandas._testing... |
ff59f191c698944655ba80f071af7bd007938deaa2f4f36edec364a29c5b61f6 | Python | 1,798 | 62 | """Examples for using the included code."""
import logging
import numpy as np
import bids
import utils
import import_data as imda
logging.basicConfig(level=logging.INFO)
def importing_source_data():
"""Directly importing/loading the source data.
This is what was used in the related study.
"""
try... |
be5b2e9b229c27b6fc11d24a38d539b71080df8ccc6a8283bc0d0a99cb8ff175 | Python | 1,799 | 51 | import pytest
import pandas.core.dtypes.concat as _concat
import pandas as pd
from pandas import Series
import pandas._testing as tm
def test_concat_mismatched_categoricals_with_empty():
# concat_compat behavior on series._values should match pd.concat on series
ser1 = Series(["a", "b", "c"], dtype="categor... |
e312a376708e50ebb1578f6a732516975c35527c48f2c9b373d4931b8c5a702f | Python | 1,799 | 48 | import numpy as np
def parse_prt_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
conditions = {}
current_condition = None
reading_intervals = False
for line in lines:
line = line.strip()
# Skip non-relevant lines
if any(lin... |
5606399c2eb8518ba28744174206ef7c092272bdafa413ec4d51e09807c581ae | Python | 1,803 | 59 | # tiny-imagenet-200/
# ├── train/
# │ ├── n01443537/
# │ │ ├── images/
# │ │ │ ├── n01443537_0.JPEG
# │ │ │ ├── n01443537_1.JPEG
# │ │ │ └── ...
# │ │ └── ...
# │ ├── n01558993/
# │ └── ...
# ├── val/
# │ ├── images/
# │ │ ... |
916657141021f1fc61e5625701ea725284cf92b07acf3b2fc10308f79fd24dde | Python | 1,803 | 52 | from typing import Optional
from qtpy.QtCore import QObject, Qt, Signal
from qtpy.QtGui import QColor, qGray
from qtpy.QtWidgets import QColorDialog, QMenu, QPushButton, QWidget, QWidgetAction
class ColorPicker(QPushButton):
class Events(QObject):
color_changed = Signal(QColor)
def __init__(self, pa... |
f8a085e85bb1c689f2c0e8ee6ff9491ea2123f0605c14e344238cc4037a9372c | Python | 1,803 | 41 | import numpy as np
import pandas as pd
import scanpy as sc
import polars as pl
import pyranges as pr
# Read in rna observation data
rna = sc.read_h5ad(snakemake.input.merged_rna_anndata)
# Port cell data from final RNA atlas to cisTopic pseudobulked
cell_df = rna.obs
# Metadata specific column names
sample_value = s... |
a4a56605feeb104481d3c359007d797d2a62ed8b2c30ecfcc44212abab0dacba | Python | 1,804 | 54 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
from typing import Any, cast
import polars as pl
from ..data_quality_dashboard import DataQualityDashboard
from .etl_base import SqlServerEtlBase
class SqlServerDataQualityDashboard(DataQualityDashboard, SqlServerEtlBase):
def __init__(
s... |
c6ffd37ad594845955a68836dd0cf284c62c49ca29b3f38eb162001a798a749f | Python | 1,804 | 62 | """
Unopinionated display configuration.
"""
from __future__ import annotations
import locale
import sys
from pandas._config import config as cf
# -----------------------------------------------------------------------------
# Global formatting options
_initial_defencoding: str | None = None
def detect_console_en... |
f739c1cfa1f6ac0f7ad73242d9fa49d57f97044c50d4093e5e8f759623c6da49 | Python | 1,804 | 101 | """
"""
from campy.cameras import unicam
import os
import time
import logging
import sys
import numpy as np
from collections import deque
import csv
import imageio
def LoadSystem(params):
return params["cameraMake"]
def GetDeviceList(system):
return system
def LoadDevice(cam_params):
return cam_params["dev... |
f5cfedcb9341d0ead59ecc00827b2595328754ee592c58faf0f520b3f2ba4b9b | Python | 1,805 | 68 | """ Permute the times of a point processes
Author: Drew B. Headley
"""
import numpy as np
from numpy import random
def permute_pt(pt):
"""
Permutes a point process by randomly reordering their intervals.
Returned process has the same number of points and interval distribution.
Parameters
------... |
76c109c77cfe1cae25446432dc9809525c67a7a749b3d950a6a03802d45557a3 | Python | 1,806 | 43 | import pandas as pd
import numpy as np
# Read the expression data
expression_df = pd.read_csv('CT2_log/euclidean/table/expression.csv')
# Read the candidate genes list
candidate_genes_df = pd.read_csv('CT2_log/euclidean/final_candidate/candidate_genes.csv')
# Calculate overall mean and median expression across all g... |
f15bee0b42dfe074f7d6a3fb527e458135282f7e46173e77115398be6cd6fd76 | Python | 1,806 | 58 | #!/usr/bin/env python3
import os
import subprocess
import sys
COMMON_TESTS = [
(
"Checking that torch is available",
"import torch",
),
(
"Checking that MKL is available",
"import torch; exit(0 if torch.backends.mkl.is_available() else 1)",
),
]
GPU_TESTS = [
(
... |
74bd93bd5bd44a8d6ae6b2e8cbfde33f0ed034937d2bc5cac104f54f370e70df | Python | 1,807 | 55 | import numpy as np
def duplicate_soft_assignment(fname_template_soft_assignment,
threshold=0.7, units_in=None):
# load soft assignment
tmp = np.load(fname_template_soft_assignment)
probs_all = tmp['probs_templates']
units_all = tmp['units_assignment']
# number of uni... |
436b6e8e346716dd466fede0a9038cc6e6e9c6573ffef526f028a890ab0222d6 | Python | 1,808 | 48 | def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative va... |
4be11065c75b9a4098d176c841f98c9f1d7af4f28950e3ebcddb479f45fd63c3 | Python | 1,810 | 54 | import yaml
from skimage.transform import rescale
from tqdm.contrib.concurrent import process_map
from skimage.io import imsave
from skimage.util import img_as_ubyte
from CrystalTracer3D.intensity import *
from CrystalTracer3D.io import *
from CrystalTracer3D.segment import *
from CrystalTracer3D.util import *
from Cr... |
2769c7918d01807a1b380f260394ea4aa80e7b00f04ad43f60f9e9a5d6f69604 | Python | 1,815 | 55 | # coding: utf-8
# See notebook:
# https://github.com/paninski-lab/yass-examples/blob/master/batch/single_channel.ipynb
"""
Splitting large file into batches where every batch contains n
observations from 1 channel
"""
import os
from yass.batch import BatchProcessor
path_to_neuropixel_data = (os.path.expanduser('~/... |
59b34cb74a29743d264b090f985f39a93a4c3628e7ca5e4a324a62f2a99259b5 | Python | 1,816 | 57 | # Copyright (C) 2008,2009,2011,2013 Bernd Feige
# This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING).
"""
idircache class for repeated case-independent searches in large directories
"""
__author__ = "Dr. Bernd Feige <Bernd.Feige@gmx.net>"
import os
class idircache(object):
def __init__(sel... |
b8653c2099716c3d2a97cf317e08f84ed54edca027e431915bbe7030855fa7d5 | Python | 1,816 | 64 | import torch.nn as nn
from .shifted_softplus import ShiftedSoftplus
from .spherical_linear import SphericalLinear
from .swish import Swish
"""
Pre-activation residual block
"""
class ResidualBlock(nn.Module):
def __init__(
self,
order,
num_features,
clebsch_gordan=None,
m... |
40025a7bb4b67fc9f5fb3204eda8d017e6fa05fdf09381f7a19e05fb0a1a9ada | Python | 1,818 | 68 | """Utilities for testing fooof."""
from functools import wraps
from fooof import FOOOF, FOOOFGroup
from fooof.synth import gen_power_spectrum, gen_group_power_spectra
from fooof.core.modutils import safe_import
plt = safe_import('.pyplot', 'matplotlib')
##############################################################... |
e66b4c2f53aca5d0dbb164a1c357ec0eaf77a60da99ae506481aef41641c0a08 | Python | 1,819 | 85 | from pandas.core.dtypes.common import (
is_any_real_numeric_dtype,
is_array_like,
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_complex,
is_complex_dtype,
is_datetime64_any_dtype,
is_datetime64_dtype,
is_datetime64_ns_dtype,
is_datetime64tz_dtype,
is_dict_like,
is_... |
41f6e67531626738d21cc5e232b7788e809153a45a6ed43dcc870fa1568722eb | Python | 1,822 | 90 | """
requests.compat
~~~~~~~~~~~~~~~
This module previously handled import compatibility issues
between Python 2 and Python 3. It remains for backwards
compatibility until the next major version.
"""
import sys
# -------
# urllib3
# -------
from pip._vendor.urllib3 import __version__ as urllib3_version
# Detect whic... |
9ea69821d0b84dd5cba9251fab46773449f416676665921b81299e409f69a868 | Python | 1,822 | 50 | from __future__ import annotations
import pytest
from textstat import textstat
from ..backend import resources
@pytest.mark.parametrize(
"text, float_output, expected",
[
(resources.EMPTY_STR, True, 1.0),
(resources.EMPTY_STR, False, "0th and 1st grade"),
(resources.EASY_TEXT, True, 4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.