sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
86c19cee0f101904d3fb87fcb60cf700ce6ac12720e853b405274b491744be95 | Python | 1,417 | 43 | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import TYPE_CHECKING, Collection
from pip._vendor.cachecontrol.adapter import CacheControlAdapter
from pip._vendor.cachecontrol.cache import DictCache
if TYPE_CHECKING:
from pip._vend... |
625ca6b65a8b32aab1ef53128a85701c2b334ca168fb67a4834dca2b35892d2e | Python | 1,418 | 48 | """Generate heatmaps of activation thresholds, using Seaborn's FacetGrid.
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.
RU... |
8aff98c575197b8cfb5b9dd06566349dd89c578dc01ac232800aeca0dded41bf | Python | 1,419 | 54 | """
=============
Masked Arrays
=============
Arrays sometimes contain invalid or missing data. When doing operations
on such arrays, we wish to suppress invalid values, which is the purpose masked
arrays fulfill (an example of typical use is given below).
For example, examine the following array:
>>> x = np.array(... |
68b32ed42ac07363c9d304416735e75dbac2040125dab4d0b58f807e5b250fe1 | Python | 1,420 | 40 | import os
from setuptools import setup, find_packages
def get_version():
directory = os.path.abspath(os.path.dirname(__file__))
init_file = os.path.join(directory, 'bermol', '__init__.py')
with open(init_file) as f:
for line in f:
if line.startswith('__version__'):
delim... |
1d01c7c300e469946e6d6e933e6c70fac94014d823abbd39d0b6701fca477c51 | Python | 1,421 | 49 | # Autogenerated by configen, do not edit.
# If encountering an error, please file an issue @
# https://github.com/romesco/hydra-lightning
# fmt: off
# isort: skip_file
# flake8: noqa
# Hydra + Lightning
from dataclasses import dataclass
from dataclasses import field
from typing import Any
from typing import Callable
fr... |
118cf2537981bbb018e5c1def307bf5ae6569895b575569f3ba3368d2f18d9e4 | Python | 1,422 | 47 | """Plot the compound nerve action potential (CNAP).
The recorded SFAPs are produced for every fiber when a model contains a
recording cuff, identified within the model.json configuration file. The user
may pass in specific fiber indices or choose to compound across all fibers.
The copyrights of this software are owne... |
157421e9598692e1a40762004f863ed95e54683d8b094363419e9a99f05aa3cd | Python | 1,425 | 41 | import numpy as np
from pandas import PeriodIndex
import pandas._testing as tm
class TestFactorize:
def test_factorize_period(self):
idx1 = PeriodIndex(
["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],
freq="M",
)
exp_arr = np.array([0, 0, 1, 1,... |
40323c4d658b902b90f5c28a9a1e8da836b5de39e4cb35152e9d67f8457e3120 | Python | 1,426 | 62 | import numpy as np
def square_bounding_box(bounding_box) -> np.ndarray:
x1, y1, x2, y2 = bounding_box
width = x2 - x1
height = y2 - y1
if width > height:
delta = width - height
y1 -= delta // 2
y2 += delta - delta // 2
else:
delta = height - width
x1 -= de... |
1e0ac39ae9212b17507d4db9db70a435dc4dee9e7c8e954e80630dc3cd66f27f | Python | 1,427 | 51 | """Configuration file for pytest."""
import os
import shutil
import pytest
import pkg_resources as pkg
import numpy as np
from fooof.core.modutils import safe_import
from fooof.tests.utils import get_tfm, get_tfg
plt = safe_import('.pyplot', 'matplotlib')
###########################################################... |
e122bbe6c09edbdc5b460404d5942d3079ca52e65801fddb4a964eadf7f52006 | Python | 1,427 | 38 | from __future__ import annotations
import typing as t
from .encoding import base64_decode as base64_decode
from .encoding import base64_encode as base64_encode
from .encoding import want_bytes as want_bytes
from .exc import BadData as BadData
from .exc import BadHeader as BadHeader
from .exc import BadPayload as BadP... |
568c40fb25e8c3f0918a4275b659e2d4fb0000e4f50f65fc3ed4d9c893864175 | Python | 1,428 | 50 | import pytest
from pandas import (
DataFrame,
Series,
)
import pandas._testing as tm
class TestDataFrameSetItem:
def test_isetitem_ea_df(self):
# GH#49922
df = DataFrame([[1, 2, 3], [4, 5, 6]])
rhs = DataFrame([[11, 12], [13, 14]], dtype="Int64")
df.isetitem([0, 1], rhs)
... |
918ef283b26dca7fd1065a33c1ee94a50bedc0f6cf7294c2d01dbbb36191a3bb | Python | 1,428 | 53 | from . import util
import numpy as np
import pytest
from numpy.testing import assert_allclose
class TestISOC(util.F2PyTest):
sources = [
util.getpath("tests", "src", "isocintrin", "isoCtests.f90"),
]
# gh-24553
@pytest.mark.slow
def test_c_double(self):
out = self.module.coddity.c_... |
bc6061742793a18659e760314afaf2aa26233d0f48c29fc805b048ec61a6ad60 | Python | 1,430 | 58 | # %%
import mne
import utility_funs as uf
from sys import argv
from autoreject import AutoReject
# 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 = '../results/au... |
ab77953666d62461bf4b40e2b7f4b7028f2a42acffe4f6135c500a0597b9cabe | Python | 1,431 | 61 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
class InfinityType:
def __repr__(self) -> str:
return "Infinity"
def __hash__(self) -> int:
return hash(repr(self... |
69c90f62e5555fbe02fa80fe9ef66ca2908ca76658de16c37db9009f4c44ebbf | Python | 1,432 | 52 | #!/usr/bin/env python3
# Script to assemble a loompy file from the
# experiment GSE114725. Two files are required
# and provides as first and second positional arguments
# (1) file containing the raw counts as downloaded from
# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE114725
# and (2) a cluster-id to cell... |
91da017a2075c115a5ce94e198b28c10d3c27a65f1f9ed0da49e9cf8b573d795 | Python | 1,432 | 37 | import logging
from dataclasses import dataclass
from util.trace import Trace
logger = logging.getLogger("grimace_box."+__name__)
@dataclass(frozen=True)
class FileType:
template: str
glob_pattern: str
FILE_TYPES = {
"top_video": FileType("{prefix}top_{recording_number}.avi", "*top_*.avi"),
"front... |
bded48bf0dab61832012010e90650bfbf26be7dbec81fc87bc5b4c61db5ea362 | Python | 1,432 | 33 | # 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 unittest
from antismash.detection.... |
18ca05c9d045fe476969128fa0ce5c97932f8aab9544b57266d7e9e7ed7a8e0d | Python | 1,433 | 20 | #: list of lorem ipsum words used by the lipsum() helper function
LOREM_IPSUM_WORDS = """\
a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at
auctor augue bibendum blandit class commodo condimentum congue consectetuer
consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus
d... |
e7e811cdd05f93617ca8867fbf35259c8fafa351ec021d85e4160950437efa6d | Python | 1,433 | 62 | """
Templates for invalid operations.
"""
from __future__ import annotations
import operator
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from pandas._typing import npt
def invalid_comparison(left, right, op) -> npt.NDArray[np.bool_]:
"""
If a comparison has mismatched types an... |
ab3343f650de74d5385bf692fd6120a3dc744ee86049de2c9482fb02347d02ed | Python | 1,434 | 50 | """Loosely based on gist.github.com/MantasVaitkunas/7c16de233812adcb7028."""
import os
import warnings
__licence__ = "BSD (3 clause)"
# TODO: Add docstrings
def get_github_repo(app, path):
"""TODO."""
if path.endswith(".ipynb"):
return app.config.github_nb_repo, "/"
return app.config.github_repo... |
72a4f95c01b3349fc805c9320e5d1252f33bfc9c76c27d0c50e3e6716edbaf77 | Python | 1,436 | 58 | import sys
import importlib
"""Stub versions of optional submodules which may fail to clone."""
class Shim(object):
def __init__(self):
self.is_shim = True
class version(Shim):
def get_version(self):
return None
class simplewrap(Shim):
class Wrapper(object):
def __init__(self):
self.width ... |
a9b0900802e0c3088ea18360663c346a9a0c7720473daa9eef4494c321c3314f | Python | 1,436 | 50 | ##########################################################################
# NSAp - Copyright (C) CEA, 2019
# 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.html
# for details.
##########... |
fb7bb4d9a9f8a0c2c282ba3b15995aaea132aaa094d64801b65a46e5341595da | Python | 1,436 | 59 | import scipy.signal as sig
def butter_filter(x, cutoff, btype, output='sos', order=3, fs=44100):
"""Applies a Butterworth filter to the signal.
Parameters
----------
x : array
The signal to be filtered
cutoff : float
The cutoff frequency. If btype is 'bandpass' or 'bandstop', cutof... |
85d83f3bebfbddc092ac88fab8ba33d4d471818b4e20b3acf2638f29d0e81149 | Python | 1,437 | 57 | """
pandas._config is considered explicitly upstream of everything else in pandas,
should have no intra-pandas dependencies.
importing `dates` and `display` ensures that keys needed by _libs
are initialized.
"""
__all__ = [
"config",
"detect_console_encoding",
"get_option",
"set_option",
"reset_opt... |
e93ba81b726bd54e33d69377e888c214586f93346f868b8bf95ee349047b78fb | Python | 1,437 | 47 | import pandas as pd
def connection_set(path):
df = pd.read_csv(path)
print(len(df))
df = df[df["protein1"].le(df["protein2"])]
print(len(df))
output_file = "table/unlog_transform/concise/control_HALF.csv"
df.to_csv(output_file, index=False)
return path
def find_missing_connections(file1, ... |
4fb87ae1d1bd7b9c431b42953b2f4ef135f2aede515919d358df625dfdda1b26 | Python | 1,439 | 61 | """
Interface wraps quantum function as a numpy function
"""
from typing import Any, Callable
from functools import wraps
from ..cons import backend
from .tensortrans import general_args_to_numpy, numpy_args_to_backend
Tensor = Any
def numpy_interface(
fun: Callable[..., Any],
jit: bool = True,
) -> Callab... |
9e77b87a404068ef616c141b97f8d49256637ba1ebf6778e5e06fc259669340e | Python | 1,439 | 48 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run a Flask REST API exposing one or more YOLOv5s models
"""
import argparse
import io
import torch
from flask import Flask, request
from PIL import Image
app = Flask(__name__)
models = {}
DETECTION_URL = "/v1/object-detection/<model>"
@app.route(DETECTION_URL, meth... |
6145f08aed63738dfe9eabe5c60b83cb7ebfe5692b36a3f271881d403f7556ae | Python | 1,440 | 47 | import numpy as np
import torch
import torch.nn.functional as F
from torch_geometric.data import Batch
def predict(
model,
data_loader,
device,
task_type='classification',
return_embeddings=False):
model.eval()
torch.set_grad_enabled(False)
all_predictions = []
... |
946a51daf9c085bb329b60d48f2f9f0bb13ebab521990d454389ef5c8503ec15 | Python | 1,440 | 46 | import trimesh
from numpy.testing import assert_allclose
import pytest
import cedalion
import cedalion.dataclasses as cdc
import cedalion.xrutils as xrutils
def test_normal_normalization():
# normal vectors have length 1
sphere_orig = trimesh.creation.icosphere(4)
# mesh with scaled normal vectors
s... |
c2cbec4870c65b1b05c30aa19a4a443d5267526baf343c11970da6c4dadcdd9e | Python | 1,440 | 44 | from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from ..._metadata_models.gui.tilt_series_set import GuiTiltSeriesSet
from ..._metadata_models.gui.tilt_series import GuiTiltSeries
class QTiltSeriesItem(QListWidgetItem):
def __init__(self, tilt_series: GuiTiltSeries, *args, **kwargs):
super().__in... |
da7f9afad50a9e015c9aad185685c15aed93b32bc4d89fda3d805df5ecf9079d | Python | 1,441 | 43 |
import numpy as np
import os
import sys
mouse_id = sys.argv[1]
os.system(f"mkdir -p {mouse_id}/data/responses_test/")
os.system(f"mkdir -p {mouse_id}/data/images_test/")
tiers = np.load(f"{mouse_id}/meta/trials/tiers.npy")
test_ids = np.where(tiers == "test")[0]
frame_image_id = np.load(f"{mouse_id}/meta/trials/fr... |
fb610749cc68da37c4435a2a9e7950ff678ebed0089fc3b692b05abde4b09a3b | Python | 1,442 | 48 | from __future__ import annotations
from functools import reduce
import numpy as np
from pandas._config import get_option
def ensure_decoded(s) -> str:
"""
If we have bytes, decode them to unicode.
"""
if isinstance(s, (np.bytes_, bytes)):
s = s.decode(get_option("display.encoding"))
ret... |
1bc65682ee6ac5829fbc59c23f05f62c0da88200d8e4cbcbd2c778d196ac665a | Python | 1,443 | 54 | """ Creates a list of Ca2+ spike times from a dendritic ca CSV file
Author: Drew B. Headley
"""
import pandas as pd
import numpy as np
def load_caspks_csv(fpath):
"""
Loads a CSV file that contains calcium spike times from the nexus segment
converts them to a numpy array of integer simulation time steps... |
ae4407030d3069e3dff7a354d275092310ac7bc0a2d32801ba38b8dac905e935 | Python | 1,443 | 37 | import scanpy as sc
# Load in data
adata = sc.read_h5ad(snakemake.input.rna_anndata) # type: ignore
# Filter for quality control on general values
# The lambda function sets the observation row x to be filtered the variable in
# quotes by the value input by the snakemake params value
# Threshold below a given mitoc... |
1403e8cacdeb45e83e7842511dc248bf2ed42f41a414f306c8e7e418f1bb1c7e | Python | 1,446 | 36 | import sys
sys.path.append("../../../../")
sys.path.append("../")
from api.music_engine_api import EngineAPI
import os
if __name__=="__main__":
#----------------------------------Init------------------------------#
musicEngine = EngineAPI()
musicEngine.cortexInit()
#----------------------------Learnin... |
8dedcf0547cf10a628e12999b316fa1285e60faf75c24c537796f847fd8a15b6 | Python | 1,446 | 51 | """Validators for common data structures."""
from typing import List, Optional
import pint
import xarray as xr
def _assert_dims_and_coords(
array: xr.DataArray, dimensions: List[str], coordinates: List[str]
):
for dim in dimensions:
if dim not in array.dims:
raise AttributeError("Missing... |
9904d1d9c7531168881f86a7c30a2febb1812847b2ee6a32299a766c92c7d52d | Python | 1,449 | 50 | from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from fonticon_mdi6 import MDI6
from qtpy.QtWidgets import (
QFileDialog,
QPushButton,
QWidget,
)
from superqt.fonticon import icon
from ._data_wrappers import MM5DWriterWrapper, MMTensorstoreWrapper
if TYPE_CHEC... |
24ea04653c2bb6fee345a5c1920490280134e323727c59861f1aa91e2187bcbd | Python | 1,450 | 50 | """Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
# /!\ This version compatibility check section must be Python 2 compatible. /!\
import sys
# Copied from pyproject.toml
PYTHON_REQUIRES = (3, 9)... |
c1a2daec39b5ec285d85992420b9e790867cb8b03f18dcb63958f6860dcf26ca | Python | 1,452 | 52 | import torch
import matplotlib
import matplotlib.pyplot as plt
import os
matplotlib.style.use('ggplot')
def save_model(epochs, model, optimizer, criterion):
"""
Function to save the trained model to disk.
"""
torch.save({
'epoch': epochs,
'model_state_dict': model.state... |
fb4941f8cc3e8333383297be4910a3fb0e02e90c4b7e9dc11fae54fc35542cd6 | Python | 1,452 | 41 | import numpy as np
from pandas.core.dtypes.common import is_scalar
import pandas as pd
import pandas._testing as tm
class TestSearchsorted:
def test_searchsorted_string(self, string_dtype):
arr = pd.array(["a", "b", "c"], dtype=string_dtype)
result = arr.searchsorted("a", side="left")
a... |
f0d75fff6674ed202aacdd28a24bc7d0f0c098408654991489e7aa49acf66914 | Python | 1,455 | 58 | import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas import (
Categorical,
DataFrame,
)
# _is_homogeneous_type always returns True for ArrayManager
pytestmark = td.skip_array_manager_invalid_test
@pytest.mark.parametrize(
"data, expected",
[
# empty
... |
4e2635c3cd9d42ce5f3566ee3272813302b834cefb1ebfb0b2877112649d5235 | Python | 1,456 | 47 | import argparse
import os
import hydra.utils
import torch
from hydra import compose, initialize
from pyg_ase_interface import PYGAseInterface
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run PyG molecule optimization")
parser.add_argument("--molecule_path", type=str, help="database... |
aa93ba8746df503336f305fc87ecacbc1ec90bd78d250410bd28d6b9a7b47fc4 | Python | 1,456 | 52 | import yaml
from tqdm.contrib.concurrent import process_map
from skimage.util import img_as_ubyte
from skimage.io import imsave
import nrrd
from skimage.transform import rescale, resize
from CrystalTracer3D.segment import *
from CrystalTracer3D.util import *
from CrystalTracer3D.plot import *
with open('config.yml',... |
551336cc4f1507518b86ad40ee6d8ab3c07f5c7180b01999887c2e5958e2a50e | Python | 1,457 | 63 | import sys
import os
import numpy as np
sys.path.append('../stats')
#from surfproc import patch_color_attrib, smooth_surf_function
from brainsync import normalizeData
#from dfsio import readdfs, writedfs
from scipy import io as spio
BFPPATH = '/home/ajoshi/coding_ground/bfp'
BrainSuitePath = '/home/ajoshi/BrainSuite... |
d5fdd9b216a253f309434ab5245e277c0117352df9c888fdc53ff892ac989a70 | Python | 1,458 | 53 | """
benchmark MPSCircuit on tf and jax backend
"""
import time
import numpy as np
import tensorcircuit as tc
def Hamiltonian(c: tc.MPSCircuit, n: int):
e = 0.0
for i in range(n):
e += -c.expectation_ps(z=[i])
return -tc.backend.real(e)
def vqe(params, n):
circuit = tc.MPSCircuit(n)
circ... |
f37c11784076adc9ed319e552ddedab1c6984a39ff90b765402ab120bc5690f3 | Python | 1,461 | 45 | from __future__ import annotations
import functools
from time import perf_counter, sleep
from typing import TYPE_CHECKING, Callable, TypeVar
if TYPE_CHECKING:
from typing_extensions import ParamSpec
T = TypeVar("T")
P = ParamSpec("P")
def retry(
wait: float, stop_after_delay: float
) -> Callable[[C... |
467cec627e300c8c1cdd523822e86a61d863ffcd1863c11be44690c4bbf29643 | Python | 1,462 | 55 |
from molmap.feature.fingerprint import Extraction as fext
from molmap.feature.descriptor import Extraction as dext
import pandas as pd
import numpy as np
from tqdm import tqdm
tqdm.pandas(ascii=True)
def calculate(npy_file_name, batch_cal_fuc, M, N, chunksize, n_jobs, dtype):
datapath = './data/cid_smil... |
998f85e6fa4737258e5c8cb157a8f32bbb7faacc3997c8601b86ec68fabdc745 | Python | 1,462 | 45 | import torch
import torch.nn as nn
from config import AdaLiConfig
from myutils.common import heaviside
def adali_backward(grad_output: torch.Tensor, x: torch.Tensor, alpha: float, beta: float):
#边界已由handleConfig函数处理好
#根据边界和alpha, beta更新梯度
left = AdaLiConfig['Vth'] - AdaLiConfig['Left'][0]
ri... |
187686ab7196875940b871f555fa1ece9d6191f107c4c953aa50e159e441aef2 | Python | 1,463 | 47 | ##
# This script primarily uses seaborn, a Python data visualization library.
# https://seaborn.pydata.org
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import os
import glob
# Define directories for input data and output figures
data_dir = ('path to permutation results')
save_dir =... |
d5e3698d455d3d000dbc8a189dbe8a5df50f4cbdddbe649cb0188537e4187f74 | Python | 1,464 | 76 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import umap
def umaprgb(vals,):
rgb = umap.UMAP(n_components = 3).fit_transform(vals)
mx = rgb.max(axis = 0 ).reshape(1,-1)
mn = rgb.min(axis = 0 ).reshape(1,-1)
rgb = (rgb - mn) / (mx - mn)
return rg... |
15e6aab6b5b205fe6ec80adc988d03d9efdfefadda48ca605374267435defad0 | Python | 1,466 | 49 | import os
import pytest
import tempfile
from . import util
class TestAssumedShapeSumExample(util.F2PyTest):
sources = [
util.getpath("tests", "src", "assumed_shape", "foo_free.f90"),
util.getpath("tests", "src", "assumed_shape", "foo_use.f90"),
util.getpath("tests", "src", "assumed_shape"... |
f88b8f22f8c4cfb5fcfaac675b2d67a39846d969253e7eaa111926410fa002fd | Python | 1,466 | 37 | import numpy as np
import pytest
from pandas import DataFrame
import pandas._testing as tm
class TestSwapAxes:
def test_swapaxes(self):
df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
msg = "'DataFrame.swapaxes' is deprecated"
with tm.assert_produces_warning(FutureWarnin... |
9b390a7cf464b37c9dce5aab8586d10fd7e9daae70af9dcf7bdef632f6c02c80 | Python | 1,468 | 35 | import cv2
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dataset", type=str, default="HCP_TASK")
parser.add_argument("-c", "--classs", type=str, default="6")
argv = parser.parse_args()
if(argv.dataset == "HCP_TASK"):
sourceDir = "fullPathToTheWorkingFolder... |
684b663e7c181027ba75043567b146d34f86049d28a14aa80b304ce70fab985c | Python | 1,469 | 51 | from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any
from qtpy.QtCore import QObject, Signal
from ._slackbot_process import SlackBotProcess
logging.basicConfig(
filename=Path(__file__).parent / "slackbot.log",
level=logging.INFO,
format="%(asctime... |
826e2882b489157c578af68241303526079a529cd6d1dc04c1961b5a7e9cab1f | Python | 1,469 | 39 | """ Conv2d w/ Same Padding
Hacked together by Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional
from .padding import pad_same, get_padding_value
def conv2d_same(
x, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, stride: Tuple[i... |
e34b3c32ec8fb19d49b7540ba727d739d768e6d4692f59251eddada7e6f87736 | Python | 1,471 | 61 | ## Compute Bulk 100kb
## Compute Bulk Mb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
celltype_ls = ['Ex'+str(i) for i in range(1,17)]
meta_data = pd.read_csv('mBC_meta_data.csv',index_col=0)
chr = 2
print(meta_data.iloc[:5,:])
print(meta_data.shape)
ind = meta_data['celltype'].isin(cel... |
19573cbd2628d23fa66a29bc6f872d7523cd915f09066b5d9aea3f9dfb4bd0c8 | Python | 1,472 | 41 | from cedalion.dataclasses.geometry import PycortexSurface, TrimeshSurface
import trimesh.creation
from cedalion import units
import numpy as np
from numpy.testing import assert_allclose
def test_pycortex_geodesic_distance_on_sphere():
"""Test geodesic distance calculation of PycortexSurface on a spherical mesh.
... |
06e0b807c00f9a8313cc71c37a8f0ee03ea9cca619c881fb2dac3a841f24cc05 | Python | 1,473 | 39 | r"""
This module is a collection of wrapper functions for loss functions used in m6Anet training
"""
import torch
from torch.nn import BCELoss
def binary_cross_entropy_loss(y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
r'''
Wrapper for binary cross entropy loss in PyTorch
Args:
... |
48dbc26ba2d7a3ee15f76066e80d5164f5f07c376ede14d62e37bcfc3dd7c28f | Python | 1,475 | 39 | from io import StringIO
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import ExtensionArray
class BaseParsingTests:
@pytest.mark.parametrize("engine", ["c", "python"])
def test_EA_types(self, engine, data, request):
if isinstance(data.dtype... |
5729efd4631f2a3580a3026615e739e3a4aa290582407c212a918090a60e2ec2 | Python | 1,476 | 60 | import random
import torch
import numpy as np
def set_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmar... |
6da05c99d650e192cfeb87779567db6a3cb17ae887d1326826a1f2efee2e6618 | Python | 1,476 | 49 | """Tools for visualizing signal quality metrics and masks."""
import matplotlib.pyplot as p
import numpy as np
import cedalion.vis.colors as colors
def plot_quality_mask(
mask,
cb_label: str,
bool_labels=["TAINTED", "CLEAN"],
true_is_good=True,
figsize=(12, 10),
):
"""Plot a boolean quality ... |
76bd77ebe77a864486fe096214b1c1138d060bb6db235ca3217eb0b92c2df19c | Python | 1,476 | 55 | import numpy as np
from spike_tools import data_preprocessing, estimate_spikes #download spike_tools package from https://github.com/jewellsean/FastLZeroSpikeInference
from matplotlib import pyplot as plt
from scipy.io import savemat
from scipy.io import loadmat
import pickle
import sys
"""
parse input arguments:
[1]... |
d51b7aa1faa57f74d40b8195ff1ef0416327954ea5643a4f130157cb36995722 | Python | 1,476 | 45 | """Count words in a training corpus or other file or directory of files."""
import os
import argparse
def count_words(fname):
"""Count words in a file.
:param fname: name of file to count words in
:return: number of words in the file
"""
with open(fname, 'r') as infile:
wordcount = 0
... |
8d9f7f1370ffa0de3a90ef9cc96185ec8a3b089b6d863728c8085629b9a38809 | Python | 1,477 | 36 | import torch
from .rk_common import _ButcherTableau, RKAdaptiveStepsizeODESolver
_DORMAND_PRINCE_SHAMPINE_TABLEAU = _ButcherTableau(
alpha=torch.tensor([1 / 5, 3 / 10, 4 / 5, 8 / 9, 1., 1.], dtype=torch.float64),
beta=[
torch.tensor([1 / 5], dtype=torch.float64),
torch.tensor([3 / 40, 9 / 40],... |
0212f8d489eb3b744077dfc9683f2ae0385837593366891b94a4d412a6582eee | Python | 1,478 | 46 | from datetime import datetime
import wandb
import hydra
from omegaconf import DictConfig, open_dict
from .dataset import dataset_factory
from .models import model_factory
from .components import lr_scheduler_factory, optimizers_factory, logger_factory
from .training import training_factory
from datetime import datetime... |
9f4dd3a3898eb8b90af9a06a06c5b7ba3d65083d8aacaf04c80d196c151c53cc | Python | 1,480 | 51 | #!/usr/bin/env python3
"""
Test ownership was introduced in https://github.com/pytorch/pytorch/issues/66232.
As a part of enforcing test ownership, we want to maintain a list of existing PyTorch labels
to verify the owners' existence. This script outputs a file containing a list of existing
pytorch/pytorch labels so t... |
24f5e6f8b7d802372d9f9d1f0087f738df052e2acdd5a488d6f13f5f9f2907de | Python | 1,484 | 45 | """
Protocol code for training session of color perception task.
Imports from protocol.py
Himanshu Aggarwal
himanshu.aggarwal@inria.fr
November 2021
"""
from psychopy import visual
from protocol import (make_stim_sequence_random, load_stim_sequence,
show_init_screen, show_end_window,
... |
56422bb344dea28c9054803bde02eb833698e8d95b23f62e187cd8696eabe8e0 | Python | 1,484 | 53 | import numpy as np
from scipy.interpolate import interp1d
def sharpen_templates(fname_templates, fname_out=None):
templates = np.load(fname_templates)
n_units, n_times, n_channels = templates.shape
mcs = templates.ptp(1).argmax(1)
t_range = np.arange(n_times)
templates_new = np.zeros_like(temp... |
0bda8cc71e027347b3d65564f04f351342f1cf31de76eaac9ff9568ec1978042 | Python | 1,486 | 40 | #!/usr/bin/env python
# extract the information from the json file
# Usage: python ccs_prep_bids_json2txt.py -i input.json -o output.txt -key SliceTiming -f "%.8f"
# Ting Xu
import os, sys
import argparse
import json
import numpy as np
if __name__=='__main__':
NoneType=type(None)
# Argument
parser=argpars... |
5bd0630a9fe5f165389007d92bdbbc39037d7c0379a1e6a4a69c7b073255199b | Python | 1,489 | 41 | from rna3db.tabular import read_tbls_from_dir
from rna3db.parser import parse_fasta, write_fasta
from pathlib import Path
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Extracts chains with no hits from a .tbl file."
)
parser.add_argument("input_path", ty... |
694981984c79458da9aae1ad7e4216bb2d7f41e9485dd743085dfff643eaf9ea | Python | 1,491 | 41 | from pathlib import Path
import napari
from .._qt.tilt_image_excluder import TiltImageExcluderWidget
from .._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet
class RelionTiltImageExcluderWidget(TiltImageExcluderWidget):
def __init__(
self,
viewer: napari.Viewer,
... |
710accaf531842fe4b652e44df836e99daaa78af21bdc37a76e2d14da799e86a | Python | 1,492 | 53 | import numpy as np
from pandas import (
DataFrame,
Series,
period_range,
)
import pandas._testing as tm
def test_iat(float_frame):
for i, row in enumerate(float_frame.index):
for j, col in enumerate(float_frame.columns):
result = float_frame.iat[i, j]
expected = float_... |
0362fb757ddb0a4dd191771899b4a316607044f295bd0604b2524807bbb07be4 | Python | 1,494 | 45 | from __future__ import annotations
from pymmcore_plus import CMMCorePlus
from pymmcore_widgets import DefaultCameraExposureWidget
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QHBoxLayout, QLabel, QToolBar, QWidget
from micromanager_gui._widgets._snap_live_buttons import Live, Snap
class _SnapLive(QToolBar)... |
4149e2bba52ac01bbe4cb174c4eed8bda21f2a4cb4140ed68396d80078f27b6f | Python | 1,495 | 57 | """Main file executed when the package is run as a module
"""
# from python
import click
# from other modules
from big_scape.cli import cluster_cli as cluster
from big_scape.cli import query_cli as query
from big_scape.cli import dereplicate_cli as dereplicate
from big_scape.cli import benchmark_cli as benchmark
from... |
9cc4329abe21b37d93a95a3901b0ab99c24486f3d487bc57965bb2ab0b252e24 | Python | 1,495 | 50 | """
requests._internal_utils
~~~~~~~~~~~~~~
Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""
import re
from .compat import builtin_str
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.c... |
0f2c6711f3d4bc98154a1ad3e58b6e2c9a1e64117d1326fd3a407243b7f606ea | Python | 1,496 | 53 | """Creates and saves the sound cues for the experiment"""
import ipdb
import numpy as np
import soundfile as sf
SRATE = 48000
def make_one_wave(duration, frequency, srate=SRATE):
"""Makes one sine wave with the given duration, frequency
and sampling rate"""
x = np.linspace(0, duration, np.int(duration * ... |
91e68e37834240b03013290e97a5103815fa36ed65f8bf3bc566116be42c19c6 | Python | 1,496 | 50 | import torch
from torchvision.models import vit_b_16, ViT_B_16_Weights
class GrimaceScoreModel(torch.nn.Module):
def __init__(self, device="cuda"):
super(GrimaceScoreModel, self).__init__()
self.device = device
self.base_model = vit_b_16(weights=None)
self.base_model.heads = torc... |
4f3e379471f7a57ba20c8b8cf64c81728bba08d2ca437a96852a394b152549c7 | Python | 1,497 | 62 | """
Implements abstract class for meta-reinforcement learning environments.
"""
from typing import Generic, TypeVar, Tuple
import abc
ObsType = TypeVar('ObsType')
class MetaEpisodicEnv(abc.ABC, Generic[ObsType]):
@property
@abc.abstractmethod
def max_episode_len(self) -> int:
"""
Return... |
8c9edbec08d3e976f6c467b75708bbb0227e419dc57fc8077776d8d3c04218d2 | Python | 1,502 | 48 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import polars as pl
from ..create_cdm_folders import CreateCdmFolders
from .etl_base import BigQueryEtlBase
class BigQueryCreateCdmFolders(CreateCdmFolders, BigQueryEtlBase):
def __init__(
self,
**kwargs,
):
super().__in... |
58a4f5235e48c37edbaa4801958d61d7f29bfe0b354267bc5b2df04ebd28a7dd | Python | 1,504 | 51 | from __future__ import annotations
from typing import Any, TYPE_CHECKING
from functools import partial
import pytest
import numpy as np
if TYPE_CHECKING:
from collections.abc import Callable
AR = np.array(0)
AR.setflags(write=False)
KACF = frozenset({None, "K", "A", "C", "F"})
ACF = frozenset({None, "A", "C", ... |
61746189ef90b0b128d07e9362a3c0aec3dc95356dce6da8af29627458ebc1c4 | Python | 1,505 | 46 | import scipy.io as scio
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal
import torch
import matplotlib.colors as mcolors
scale = 1.2
version = 1
EEG_m = np.array(torch.load(f'./result/I_subregion_{version}_{scale}.pt').cpu())
EEG_c1 = np.load('./dataset/data_awake_1ug.np... |
8c127ccdbecca71e5e6dca85f37c6ba4ef7831a782a4d18755ff5cbc337624b8 | Python | 1,505 | 55 | """Main entry point."""
from __future__ import annotations
from pip._vendor.platformdirs import PlatformDirs, __version__
PROPS = (
"user_data_dir",
"user_config_dir",
"user_cache_dir",
"user_state_dir",
"user_log_dir",
"user_documents_dir",
"user_downloads_dir",
"user_pictures_dir",
... |
eda8452854da4b56d9a4d9565b5514655d4e95c5659cde5e4a191c22c44c0752 | Python | 1,505 | 48 | # Copyright 2024 RADar-AZDelta
# SPDX-License-Identifier: gpl3+
import polars as pl
from ..create_cdm_folders import CreateCdmFolders
from .etl_base import SqlServerEtlBase
class SqlServerCreateCdmFolders(CreateCdmFolders, SqlServerEtlBase):
def __init__(
self,
**kwargs,
):
super()._... |
bc4a4d2e46f70aa2c235fe778bf54ce2678a3bee56f222077d0001d3ad6db977 | Python | 1,506 | 60 | from numpy import tri
import pandas as pd
import sys
import numpy as np
sys.path.append("../")
social = None # pd.read_csv("somePath/SOCIAL_run1_TAB.txt", sep='\t')
procedures = social["Procedure"].to_numpy()
types = social["Type"].to_numpy()
trialOnsetTimes = social["ExperimenterWindow.OnsetTime[Block]"].to_numpy()
... |
fc79282326cd250144a4869a7c7bc3d50d27c7f53d27668bf2e6a5730869e45b | Python | 1,510 | 39 | import pandas as pd
import pandas._testing as tm
def test_relabel_no_duplicated_method():
# this is to test there is no duplicated method used in agg
df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4]})
result = df["A"].agg(foo="sum")
expected = df["A"].agg({"foo": "sum"})
tm.assert_series_e... |
0cfeb7beb17a6c857e41106c2756693ec2b3faef74e8f87c33afdb88f133049b | Python | 1,511 | 46 | import pytest
from numpy import array
from . import util
import platform
IS_S390X = platform.machine() == "s390x"
@pytest.mark.slow
class TestReturnCharacter(util.F2PyTest):
def check_function(self, t, tname):
if tname in ["t0", "t1", "s0", "s1"]:
assert t("23") == b"2"
r = t("ab... |
d09a55f9810309afc9142ea86cac66c02e43811f1d97f5dba077ee74fdb7c1a2 | Python | 1,511 | 49 | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from model import FeatureMapContrast, TransformerClassifier
import yaml
# Load config
with open("configs/config.yaml") as f:
config = yaml.safe_load(f)
de... |
60ab82051b027dac1ff9542ee1b4d2e3d635db808a84ce6a604ba4b138a04edc | Python | 1,512 | 49 | from ._em_model import ExpectationMaximizationModel
from ._em_model_core import (
align_dynamics,
differential_kinetic_test,
DynamicsRecovery,
latent_time,
rank_dynamical_genes,
recover_dynamics,
recover_latent_time,
)
from ._steady_state_model import SecondOrderSteadyStateModel, SteadyState... |
2fadf93bae052112060ee82a537d88ec4567d1896f3436deff492a065cd90e49 | Python | 1,514 | 50 | from typing import List, Set, Dict, Tuple
class OMEinsumTreeSAOptimizer(object):
def __init__(
self,
sc_target: int = 20,
betas: Tuple[float, float, float] = (0.01, 0.01, 15),
ntrials: int = 10,
niters: int = 50,
sc_weight: float = 1.0,
rw_weight: float = 0.... |
9c2bacfabedd21ed02b142e991b0da734db0d02a1cbb80be53a8689108025a66 | Python | 1,516 | 64 | import sys
import os
import numpy as np
sys.path.append('../stats')
#from surfproc import patch_color_attrib, smooth_surf_function
from brainsync import normalizeData
#from dfsio import readdfs, writedfs
from scipy import io as spio
#%%
def get_connectivity(data, labels, label_ids):
#%%
if type(data) == st... |
ac6b4c41d5fa695fc36dc40d7dff5be3e3db26a855599c8b8f10e84cabfd1230 | Python | 1,517 | 53 | """
======================================================================
Convert_csv2dic.py
Author: Yasuhiro Tsubo (tsubo@fc.ritsumei.ac.jp)
Version 1.0: 2024.07.15
Version 2.0: 2024.08.28
* Modified to additionally output DATAID_indextable.csv
Paper:
Yasuhiro Tsubo and Shigeru Shinomoto,
Nondifferentiable activit... |
7c99b98c03a860951b42709efdf2cd9a33ff84166ae637bc3325e614d1df9f5d | Python | 1,518 | 41 | from pathlib import Path
import napari
import typer
from napari.settings import get_settings
from napari.utils.notifications import NotificationSeverity
from .relion_tilt_image_excluder import RelionTiltImageExcluderWidget
from .._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet
from .._utils.relion imp... |
80abadfcce3da7ae726d0ba7d9274c47c97c1be0bfb890b5b6003cb81a4884a9 | Python | 1,518 | 49 | from .lifneuron import LIFNeuron
import math
class TitleLIFNeuron(LIFNeuron):
'''
classdocs
'''
def __init__(self, tau_ref=0, vthresh=5, Rm=2, Cm=0.2):
'''
Constructor
'''
LIFNeuron.__init__(self, tau_ref, vthresh, Rm, Cm)
def updateCurrentOfLowerAndUpperLayer(sel... |
2faf1a851807703cf920d5926b7ba7fc7fdbf25bccd8dbc139b0afa038600b9b | Python | 1,519 | 55 | import numpy as np
import os
import parmap
import scipy
def remove_small_and_zero_units(fname_templates, fname_spike_train, CONFIG):
#
try:
threshold = CONFIG.clean_up.min_ptp
except:
threshold = 3
#
#templates = np.load(os.path.join(fname_templates,"templates_init.npy")... |
7816e4903fc1a51ff4226fc43b9aaecc220fd7f355c3076e9fed1d6ae01237f0 | Python | 1,521 | 44 | from pathlib import Path
import pytest
from nablaDFT.dataset import ASENablaDFT, PyGNablaDFT
@pytest.mark.download
def test_pyg_download_path(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
dirpath = "./datasets/nablaDFT/train"
PyGNablaDFT(dirpath, "dataset_train_tiny", "train")
assert (Path(tmp_... |
abd2d9854a761d7695430e304b12b4554e19f73eb6588d76afd8afb19bb480e8 | Python | 1,522 | 60 | """
Though Index.fillna and Series.fillna has separate impl,
test here to confirm these works as the same
"""
import numpy as np
import pytest
from pandas import MultiIndex
import pandas._testing as tm
from pandas.tests.base.common import allow_na_ops
def test_fillna(index_or_series_obj):
# GH 11343
obj = i... |
ff93d717b9958a5bb54b8109bfb17e5cc608a33e3490191d4ace1127c8d355d2 | Python | 1,522 | 46 | from pandas import (
Index,
NaT,
date_range,
)
def test_is_monotonic_with_nat():
# GH#31437
# PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex,
# in particular never be monotonic when we have NaT
dti = date_range("2016-01-01", periods=3)
pi = dti.to_perio... |
951fdd29951e684b1d7eb2c42a2f84115a17e919ba55cde1f135a26d4958328a | Python | 1,524 | 62 | ## Compute Bulk 100kb
## Compute Bulk Mb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#celltype_ls = ['In'+str(i) for i in range(1,9)]
celltype_ls = ['In3', 'In5', 'In6', 'In7', 'In8']
meta_data = pd.read_csv('mBC_meta_data.csv',index_col=0)
chr = 1
print(meta_data.iloc[:5,:])
print(meta_... |
52313671eae953ac00c7fda6c55b813a3608dca1ebfe8f07a182a2142cf4170c | Python | 1,525 | 56 | import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
nwires, nlayers = 6, 3
qubits = [cirq.GridQubit(0, i) for i in range(nwires)]
symbols = sympy.symbols("params_0:" + str(nlayers * nwires * 2))
circuit = cirq.Circuit()
for i in range(nwires):
circuit.append(cirq.H... |
77b705354ae87dd2d787d4fff511b712ccf55ce8a159640d973e4b6f4cade9d3 | Python | 1,525 | 87 | import os
import tempfile
import numpy as np
nd = np.array([[1, 2], [3, 4]])
scalar_array = np.array(1)
# item
scalar_array.item()
nd.item(1)
nd.item(0, 1)
nd.item((0, 1))
# tobytes
nd.tobytes()
nd.tobytes("C")
nd.tobytes(None)
# tofile
if os.name != "nt":
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.