sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
b582dd1c83766e4a00bd0b1b330c984ac31599a086cdf894888d2aef9c579bca | Python | 1,432 | 39 | """When dealing with large files that require segmentation, it's necessary to process them in chunks."""
import argparse
import jieba
from tqdm import tqdm
def segment_text(input_file, output_file, batch_size=10000):
with open(input_file, 'r', encoding='utf-8') as f:
total_lines = sum(1 for _ in f)
... |
ca5a747f96fc9a0b8fc4759595aff63f25f5f601bd7d8abec3125bde618a6753 | Python | 1,432 | 42 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
0565777022ef528629bfa3184c9d56526c32e6fbf41a2871e171cf5fe3b0617e | Python | 1,433 | 65 | from pathlib import Path
import click
import SimpleITK as sitk
from tqdm import tqdm
def _process_patient(input_file: Path, output_file: Path):
image = sitk.ReadImage(input_file)
# Initial closing pass
output = sitk.BinaryFillhole(image, fullyConnected=True)
sitk.WriteImage(output, output_file)
@c... |
6d7cd67dda39bd73efd3f4d1296b5a3addeac6fdb32d6efcc2678654599949ea | Python | 1,433 | 43 | # Author: Youzhi Luo (yzluo@tamu.edu)
# Updated by: Anmol Anand (aanand@tamu.edu)
import copy
from dig.auggraph.method.GraphAug.constants import *
base_reward_gen_conf = {
BATCH_SIZE: 32,
INITIAL_LR: 1e-4,
FACTOR: 0.5,
PATIENCE: 5,
MIN_LR: 1e-7,
MAX_NUM_EPOCHS: 200,
PRE_TRAIN_PATH: None,
... |
e1dd6647a213c68bc5e83ead79c6c140a82c09c42232296424ff486e5d6ba2ae | Python | 1,435 | 38 | import pytest
import geomstats.backend as gs
from geomstats.test_cases.geometry.complex_riemannian_metric import (
ComplexRiemannianMetricTestCase,
)
class SiegelMetricTestCase(ComplexRiemannianMetricTestCase):
def test_tangent_vec_from_base_point_to_zero(
self, tangent_vec, base_point, expected, ato... |
b5fee91866db847ba6ce048b495ab166504ad6fd30ec81b7513a10ce5f68a06f | Python | 1,436 | 47 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
requirements = (
'numpy', 'opencv-python', 'einops', 'solt==0.1.8', 'tqdm', 'scikit-learn', 'pandas', 'sas7bdat', 'pyyaml', 'matplotlib', 'coloredlogs==14.0', 'nibabel', 'torchio')
setup_requirements ... |
96916a9b276a2346ac14823493a4690a9a3c392445fac3cb5d7cca697c39de27 | Python | 1,437 | 43 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
e6ee6491ba51537c0852d85bdfd8999a2ca25d904b01ef7e4122e5a6b335a0b4 | Python | 1,437 | 43 | import os
import numpy as np
from dival import get_standard_dataset
from dival.evaluation import TaskTable
from dival.measure import PSNR, SSIM
from dival.reference_reconstructors import get_reference_reconstructor
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
IMPL = 'astra_cuda'
np.random.seed(0)
# %% data
dataset = ge... |
049d2e9ae63b9e92e71f76590ee0937c82a4ea49e7f060cb6a131bbc279bc4ec | Python | 1,438 | 53 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Detect criteria for transitions in placement."""
def should_transfer(func, parent_func):
"""Determines if a transfer should occur from collaborator to aggregator.
Args:
func (function): The current function.
pa... |
34e79bb905936e0c5ba2c4e46b198d580b6c9c24cb40260ace3a032bc7f80b70 | Python | 1,439 | 64 |
# one hot encoder for a single amino acid
alphabet = AA_LIST_ALPHABETICAL
def atom_to_oh(atom):
atom_to_idx = dict(zip(PDB_ATOMS, list(range(len(PDB_ATOMS)))))
oh = np.zeros(len(PDB_ATOMS))
oh[atom_to_idx[atom]] = 1
return oh
def oh_to_atom(oh):
atom_idx = np.where(oh==1)[0][0]
idx_to_ato... |
9cdc1b10b1e44c2c55a85059f44f2fed8f66c7d707909de91f60b338eb89f2c2 | Python | 1,440 | 40 | from dival.datasets import Dataset
class ReorderedDataset(Dataset):
"""
Dataset that reorders the samples of another dataset by specified index
arrays for each part.
"""
def __init__(self, dataset, idx):
"""
Parameters
----------
dataset : `Dataset`
Dat... |
5951b44849ee70b22b2f640507b2ebbbd4c54046320450d9046aa15ce6f3a939 | Python | 1,441 | 39 | """
Calculate the wave directions per wave and channel,
based on the spatial gradient of wave trigger times.
"""
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
CLI = argparse.ArgumentParser()
CL... |
068624016875b4ee17907c3ffc9486b6fb9e1f436ec811705f6a76e27619d6e9 | Python | 1,442 | 50 | import pytest
from geomstats.geometry.spd_matrices import (
SPDAffineMetric,
SPDEuclideanMetric,
SPDLogEuclideanMetric,
SPDMatrices,
)
from geomstats.learning.mdm import RiemannianMinimumDistanceToMean
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.learning.mdm... |
8347b83bb33e000f55b2366093203cd816a610bf5864672a3218d6250c0f2a34 | Python | 1,442 | 39 | """
Calculate the wave propagation velocity for each wave and channel.
"""
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_path
CLI = argparse.ArgumentParser()
CLI.add_argumen... |
962e5a4c07a4706dff109bcddbf9c8daa096adade32b0c1a11a64bff4726951f | Python | 1,442 | 52 |
from sleepy.processing.processor import Algorithm
from sleepy.processing.parameter import Parameter
import numpy as np
class Percentile(Algorithm):
def __init__(self):
self.name = "Percentile Algorithm"
self.durationLow = Parameter(
title = "Lower bound for duration interval [sec]",... |
7ea1cd17845fbf87a26dd506bef20468f10611d9a3f80d80dc7cdb4e8140c286 | Python | 1,443 | 47 | import httpx
import zipfile
import io
import os
import sys
import shutil
import time
from typing import Optional
# Used by Github Action runners to upgrade sqlite version to 3.42.0
DLL_URL = "https://www.sqlite.org/2023/sqlite-dll-win64-x64-3420000.zip"
DOWNLOAD_TIMEOUT_SECONDS = 30
DOWNLOAD_RETRIES = 5
def download... |
3ae4b68204fc85c89585f648806244a50e20fd9155a89b4c5da03a1f420b2872 | Python | 1,444 | 60 | import torch
def test_EqGraphLoss():
from mlspm.losses import GraphLoss
# fmt:off
node_classes_ref = [
torch.Tensor([0, 1, 1]).long(),
torch.Tensor([1, 1, 0, 0]).long()
]
edges_ref = [
torch.Tensor([
[0, 1],
[1, 2]
]).long(),
torch.... |
d0ba9bbf4cf44f842c8a1f0e0175bddcc22e93c6456372b573d8cd3037d3576e | Python | 1,444 | 55 |
def find_individual(id, ind_list):
for ind in ind_list:
if ind.id == id:
return ind
class Evolution_individual:
def __init__(self, genome, id=None, score=None, mate_chance=None):
self.id = id
self.genome = genome
self.score = score
self.mate_chance = mate... |
148d3fde9323f75f2b565c29060aabcba01e16ac2b062b6f000a9a29e1764bc7 | Python | 1,445 | 52 | import geomstats.backend as gs
from geomstats.test.data import TestData
from .manifold import ManifoldTestData
from .riemannian_metric import RiemannianMetricTestData
def gaussian(x, mu, sig):
a = (x - mu) ** 2 / (2 * (sig**2))
b = 1 / (sig * (gs.sqrt(2 * gs.pi)))
f = b * gs.exp(-a)
l2_norm = gs.sqrt... |
4dfea2c1059955589e349c88aae43dd241a86d39c7280321b59bd39aa05943f6 | Python | 1,445 | 50 | import pytest
from geomstats.information_geometry.beta import (
BetaDistributions,
BetaDistributionsRandomVariable,
BetaMetric,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test.random import RandomDataGenerator
from geomstats.test_cases.information_geometry.beta import (... |
a799af09eb5a57a89cc4aa24b02556ab3dbd224461ae7573919fedcd03f20556 | Python | 1,446 | 48 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
1b8089e2bcdf83012c63baabfb553ffc8699a6eb2a603a48b945b180549c7e8e | Python | 1,448 | 47 | """Plot a grid on H2 with Poincare Disk visualization."""
import matplotlib.pyplot as plt
import geomstats.backend as gs
import geomstats.visualization as visualization
from geomstats.geometry.hyperboloid import Hyperboloid
def main(left=-4.0, right=4.0, bottom=-4.0, top=4.0, grid_size=32, n_steps=512):
"""Plot... |
c3fee5075ae5b242eeb47329b4dafbaa92db2e0501949bf3fc2af2ce17175f48 | Python | 1,448 | 35 | # Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openfl.interface.aggregation_functions.core import AggregationFunction
class AggregateHealthMetrics(AggregationFunction):
"""Aggregation logic for Smokers Health analytics."""
def call(self, local_tensors, *... |
dde8e5bdb9a10aa007929a067f2db4768a4300ead1aeca36d4285393b510d305 | Python | 1,448 | 47 | import pickle, logging
import numpy as np
from util import config_logger
logger = config_logger(logging.getLogger(__name__))
def load_expression(filename):
if filename.suffix == '.pkl':
with open(filename, 'rb') as f:
expr = pickle.load(f)
elif filename.suffix in ['.txt', '.tsv']:
expr = np.loadtxt(filen... |
ee3dc06bb3c9ddd4aa49cf065e0012a8354e309bf72b98315e6dd8dfc315c438 | Python | 1,449 | 45 | #!/usr/bin/env python
import json
import sys
import nibabel as nib
import numpy as np
def get_shell_vols(dwi: str, shells: str, bval: str, out_nii: str) -> None:
# Load relevant data
dwi_nii = nib.load(dwi)
dwi_data, dwi_affine = dwi_nii.get_fdata(), dwi_nii.affine
dwi_shape = dwi_nii.shape
with... |
0305fefde63bb34b543488bdc38c5b06f210134c2807ea925ee1f010e3bab7c1 | Python | 1,451 | 49 | #!/usr/bin/env python
from subprocess import Popen, PIPE
import os
import re
class ValgrindWrapper:
vg_path = None
disable_var = "BCINT_TEST_NO_VALGRIND"
def __init__(self, command, vglog_file):
self.command = command
self.vglog_file = vglog_file
if self.vg_path == None:
... |
dcaaafa13c7a2136b88f59853f08e197403c9dd3c420a4e9727418017d5c7d20 | Python | 1,451 | 42 | import dynfc as dyn
from numpy import zeros, triu_indices, sqrt, sum, square, multiply
from scipy.stats import zscore
import numpy as np
def cofluct(series, size, k=1):
"""Run cofluctuation analysis for BOLD signal.
Args:
series (double): BOLD signal array for all parcels/voxels in the format [N, Tma... |
38ad4ff4197a6f1125ecce73b925da7412258b4f035dd69427f495b4db211f87 | Python | 1,452 | 48 | import random
import pytest
from geomstats.geometry.euclidean import Euclidean, EuclideanMetric
from geomstats.geometry.spd_matrices import SPDMatrices
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.geometry.euclidean import (
CanonicalEuclideanMetricTestCase,
Euclide... |
77d188522fd0d9973b901906fccfa17abce0e081d1a800d9f7fb54a828db5906 | Python | 1,452 | 42 | """
Check whether the input data representation adheres to the stage's requirements.
Additionally prints a short summary of the data attributes.
"""
import numpy as np
import argparse
from pathlib import Path
import quantities as pq
from utils.io_utils import load_neo
CLI = argparse.ArgumentParser()
CLI.add_argument... |
8f6659673099c4ff5591e4ff57b12bcee28eb1a38e4703f9740be21a12ebf71f | Python | 1,452 | 39 | import pytest
import numpy as np
from reinvent_plugins.components.comp_reaction_filter import Parameters
from reinvent_plugins.components.comp_reaction_filter import ReactionFilter
@pytest.mark.parametrize(
"reaction_type, expected_results",
[
("selective", [0.0, 0.0]),
("nonselective", [0.0... |
98fccc5a05e578a6a345da02bc3d5cb80333ad69c8ca183aba41477723cc780b | Python | 1,452 | 49 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
68158b7628463bd24a8edf6005225745386b103691c0a19bfeee3133bba7128c | Python | 1,453 | 42 | """REINVENT4
Namespace setup and backward compatibility
"""
import sys
from reinvent import models
from reinvent.version import *
from reinvent.models.libinvent.models import vocabulary # not sure why needed
# support compatibility with older model files
PATH_MAP = (
# R3
("reinvent_models.reinvent_core",... |
a45e27a29e210d05e10e9fdb802ce2d1b238e1d7cc35838acb07cd017844ac9d | Python | 1,453 | 39 | """
Calculate the wave directions per wave and channel,
based on the spatial gradient of wave trigger times.
"""
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
CLI = argparse.ArgumentParser()
CL... |
71e24e5e60aebb1ba098bbd0c5a2d9a8b851ba4d84a7b27a70e2791ba01305fe | Python | 1,456 | 51 | from pathlib import Path
import pytest
import torch
from reinvent.runmodes.TL.run_transfer_learning import run_transfer_learning
from reinvent.runmodes.utils.helpers import set_torch_device
from reinvent.models.meta_data import check_valid_hash
@pytest.fixture
def setup(tmp_path, json_config, pytestconfig):
dev... |
0488657baf3eb769d3f08ca7d1e16f966f8432c3cffe0a70ddd33c685effc432 | Python | 1,458 | 33 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
"""
Shared utilities for loading models from saved formats (checkpoints and packages).
"""
import os
from typing import List
from nequip.model.utils import _COMPILE_MODE_OPTIONS
def _check_compile_m... |
17ab22f4495e3085e5567d688e6482a0d69e3885615ff69f1ab776c1a57aa023 | Python | 1,459 | 31 | """Record associations must survive papers reporting several unrelated antigens."""
import polars as pl
import pytest
from vdjdb.corpus.query import receptor_lift
def test_receptor_lift_keeps_epitope_chain_and_species_on_the_same_record():
records = pl.DataFrame({
'record_id': ['a', 'b', 'c', 'd'],
... |
7c5721704c7c0be139ed90beb53dd9f40f27bdc130bd03b374b7b31e8b142aba | Python | 1,463 | 68 | import collections
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import predictive_coding as pc
import analysis_utils as au
def plot(df):
df = au.nature_pre(df)
g = au.nature_relplot(
data=df,
x='pc_learning_rate',
y='Mean of t... |
64615235b50d565b9a4964f62889747782415122e1a838f1a1ccf7534696aa4f | Python | 1,465 | 53 | # Copyright (C) 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""FlowerDataLoader module."""
import os
from openfl.federated.data.loader import DataLoader
class FlowerDataLoader(DataLoader):
"""Flower Dataloader
This class extends the OpenFL DataLoader to provide functionality for
loadi... |
30220d4df12f8ddca61f222eebf892d42126012f494d89bf408e802a00708531 | Python | 1,468 | 30 | from Bio.SeqUtils.ProtParam import ProteinAnalysis
def parser(sample):
try:
analyse = ProteinAnalysis(str(sample).replace('U', 'S'))
aa_dict = analyse.count_amino_acids()
num_amino_acids = '%d' % (sum(list(aa_dict.values())))
molecular_weight = '%.3f' % (analyse.molecular_weight()... |
40e71984eb54e7c77b8fb57a26a62da82e3ddbdb72bf997e60e3c8c5446823d3 | Python | 1,469 | 54 | # -*- coding: utf-8 -*-
import os
import argparse
import logging
import numpy as np
# use this format to tell the parsers
# where to insert certain parts of the script
# ${imports}
def parse_args():
# Argument Parser
parser = argparse.ArgumentParser()
# my args
parser.add_argument("--verbose", action... |
d7f6adbfb39bac3d9504faf4962df48ae3b871326397368baaffc67aefe2b891 | Python | 1,469 | 40 | """
Calculate the wave directions per wave and channel,
based on the spatial gradient of wave trigger times.
"""
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_path
CLI = arg... |
10f8ca010d8cfdabc2a5fafa93a321b5e8ac8cf5bce6ff448e8ba1689a7bd758 | Python | 1,470 | 43 | """
Calculate the number of triggers involved in each wave.
"""
import numpy as np
import argparse
import pandas as pd
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
CLI = argparse.ArgumentParser()
CLI.add_argument("--data", nargs='?', type=str, required=True,
help... |
44e8217d453d5329df530c4b52ad2d86b0fba4513c95415bdf658b94223c07c6 | Python | 1,470 | 40 | """
Calculate the wave directions per wave and channel,
based on the spatial gradient of wave trigger times.
"""
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_path
CLI = ar... |
ad5609643b9060dc42f86d29178c8bde5de7f98d21511827a7f4749e0c2b1692 | Python | 1,470 | 37 | import sys
sys.path.append(' /home/kusch/Documents/project/co_simulation/TVB-NEST-proof/lib/soft/lib/python3.8/site-packages/')
from neurolib.models.aln import ALNModel
from neurolib.utils.loadData import Dataset
import matplotlib.pyplot as plt
import scipy
import neurolib.utils.functions as func
ds = Dataset("gw")
mo... |
cb769e4a0e6f65336103659802d8d0b756f1222f2113c501b23b7bc3d203eb95 | Python | 1,470 | 32 | """Gradient nonlinearity correction (GNC): spatial unwarping, with a choice of
backend ('gradunwarp' or 'tortoise').
Computes a single geometric warp (per scan) from the scanner's gradient
coefficient file and applies it either as a standalone pre-eddy correction
(for topup/eddy to operate on geometrically-correct dat... |
038f90041ad8be709ac97448f270b8a879ef4825ccfe3d045428b8d3bc0e2f57 | Python | 1,471 | 23 | # Author: Javier Sanchis <javier.sanchis@ua.es>
# Copyright 2023 Javier Sanchis
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to u... |
be6d3a2804f3fb511b6e73aa24b98627ca197b1e134c5270effb374947da874a | Python | 1,471 | 47 | """Prepare and process graph-structured data."""
from Bio import AlignIO
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor
def build_window_trees(file_path, n_windows=106):
"""Load data from fasta files.
Parameters
----------
n_windows : int
Number of windows... |
8a756d093a9fc6d0c9d1e94797b8f05ad7d8ab1cf793182802f7a0b756f22285 | Python | 1,472 | 33 | import unittest
from reinvent.chemistry.library_design.reaction_definitions.standard_definitions import (
StandardDefinitions,
)
from tests.chemistry.fixtures import default_reaction_definitions
class TestStandardDefinitions(unittest.TestCase):
def setUp(self):
with default_reaction_definitions() as ... |
2903d9dc2c8a0d1546b2e6e007307b14cadd1c8b8dd48dfb7d18b365b813eac7 | Python | 1,476 | 50 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import argparse
from utils import logger
import os
from .classification import arguments_classification, build_classification_model
SUPPORTED_TASKS = [
name.lower()
for name in os.listdir(".")
if os.p... |
4ff1a8b5e93e7e9bc5f6cdb60184a315070ae6d27beb138ce66d71c0425a7d7f | Python | 1,476 | 51 | """Plot the result of online K-means, i.e. optimal quantization.
This is online K-means of the von Mises Fisher distribution
on the sphere using online k-means clustering of a sample.
"""
import logging
import os
import matplotlib.pyplot as plt
import geomstats.visualization as visualization
from geomstats.geometry... |
c726b8961f731abc9eb3a0b48c058dfc53d94d3bb16800722c7e17df28cdd717 | Python | 1,476 | 54 | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("HISTORY.rst") as history_file:
history = history_file.read()
requirements = [
"numpy>=1.21.0",
"torch>=1.11.0",
]
test_requiremen... |
5d8254d25bd17f47c9f365ea3f5255f47c98c21792ee87a12f2543af4b4bf4da | Python | 1,477 | 71 | from MazeHeader_PyCMD import ArdComm
import time
Comm = ArdComm(115200,verbose=True)
Comm.ReceiveData()
Comm.ActivateAllWells()
Comm.ReceiveData()
Comm.Reset()
Comm.ReceiveData()
# for ii in [0,1,2,3,4,5]:
# if 0:
# Comm.ActivateWell(ii)
# x=Comm.ReceiveData()
# print(x)
# time.sleep... |
9e2a390928862a8b29ee92410993910c0f05aac9e0117cf6d23d8568c4c1cf76 | Python | 1,478 | 44 | import sys
import os
import pandas as pd
from make_local_connectivity_scorr import *
from binfile_parcellation import *
from group_mean_binfile_parcellation import *
from group_binfile_parcellation import *
from make_image_from_bin import *
from make_image_from_bin_renum import *
from time import time
path_outmaps = s... |
13b4f440517ae982222230809e23cf27e2ab796c686656fce2602731c9b8c3d4 | Python | 1,481 | 47 | # Copyright (C) 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import torch
from copy import deepcopy
import torchvision
train_dataset = torchvision.datasets.MNIST(
"files/",
train=True,
download=True,
transform=torchvision.transforms.Compose(
[
torchvision.transf... |
24e29d020aacbe30fc030c2b945a32de4b20ac7a66acb92c1f3ed4ab51d4e8d3 | Python | 1,481 | 53 | import flammkuchen as fl
import numpy as np
import imageio as io
import pathlib
class Spines:
def __init__(self):
"""Spine annotation data processing
"""
self.spines_fn = None
def open(self, spines_fn : str):
"""Saves path to object
Args:
spines_fn ... |
10675524023d9f30f5f0e048bc7df0795569a175aabc71cc36eebe276a561c99 | Python | 1,482 | 46 | """Tests for discovery and isolation of external SanPy plugins."""
from pathlib import Path
import pytest
import sanpy
from sanpy.interface.bPlugins import bPlugins
def test_invalid_user_plugin_does_not_stop_discovery(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
)... |
21da74d7eb467b5a78212875b3805981f5a47d2a0b8b9a622dae857e66029bdb | Python | 1,482 | 28 |
import shutil
from pathlib import Path
import config
from data.dataset import BratsTest
im_name = 'Subject_009_slice_76_T1.png'
res_folder = Path('/home/mans/Downloads/to_overleaf')
res_folder.mkdir(exist_ok=True)
dataset = BratsTest(None, None, None)
expnames = ['UNet-202209-Brats313-256-geoaug-imaug-valid-lr5.0e-... |
cc1dbbcab2e7864e0425d808fe900afcb0bbc7eb1d30de9b78dc0de0ede68302 | Python | 1,482 | 51 | """Unit tests for errors."""
import pytest
import geomstats.backend as gs
import geomstats.errors
from geomstats.geometry.euclidean import Euclidean
from geomstats.geometry.spd_matrices import SPDMatrices
from geomstats.test.test_case import TestCase
class TestBackends(TestCase):
def test_check_belongs(self):
... |
cc373802b4fd2e3990c3e18c6d5fc6849f6fa7af2781bf45dfb8cae1a6b4ed77 | Python | 1,482 | 43 | """
Calculate the number of triggers involved in each wave.
"""
import numpy as np
import argparse
import pandas as pd
from utils.io_utils import load_neo, save_plot
from utils.parse import none_or_str
CLI = argparse.ArgumentParser()
CLI.add_argument("--data", nargs='?', type=str, required=True,
h... |
c91f09ce33e63ac0fae50031cbbf4a8cae5e660696f6e14411c7338511821092 | Python | 1,484 | 42 | # Generated by Django 4.1.1 on 2022-12-07 11:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_M... |
dc5d61de0ce683ebe92957dbcc25a4ee667a1a5545ae78947de582410a98b090 | Python | 1,484 | 52 | from collections import defaultdict
class DataStore(dict):
"""Centralized store for HNN session data."""
def __init__(self):
super().__init__(
{
"simulated_data": defaultdict(lambda: dict(net=None, dpls=list())),
"experimental_data": defaultdict(lambda: dic... |
6661cf9b1b87b3241459b0cf3652bde86326a51f7ad1c5b68ccd35e8ff76aae7 | Python | 1,486 | 46 | """The start method DataLoader workers are launched with.
Python 3.14 made forkserver the Linux default. A forkserver worker is sent the
dataset over a socket, and under torch's file_descriptor sharing strategy each
tensor goes as its own descriptor, past the 256 that forkserver accepts. The
in-memory dataset `run_tra... |
9a9e10149451238c85493ee0c08de0bfa3d27ad16d7e45182c81a8081eaf2dbb | Python | 1,488 | 45 |
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from mlspm.datasets import download_dataset
# # Set matplotlib font rendering to use LaTex
# plt.rcParams.update({
# "text.usetex": True,
# "font.family": "serif",
# "font.serif": ["Computer Modern Roman"]
# })
if __name__ == "... |
67af55061f69fb34c1340ea6c23883ca78a33133e4406c87fc5733f317c0dda9 | Python | 1,490 | 43 | import geomstats.backend as gs
from geomstats.test.test_case import TestCase
class SubRiemannianMetricTestCase(TestCase):
def test_inner_coproduct(
self, cotangent_vec_a, cotangent_vec_b, base_point, expected
):
result = self.space.metric.inner_coproduct(
cotangent_vec_a, cotangent... |
85d9f0ae62fbcc14ee2d0b1b62a5a594d1fc8f7bf9ac02b01433821568cf60f5 | Python | 1,490 | 57 | import numpy as np
from numpy.testing import assert_raises
from gemmr.sample_size.univariate_correlations import *
from gemmr.sample_size.univariate_correlations import _cohen_pearson_sample_size
def test_pearson_sample_size():
rs = (.1, .3, .5)
res = pearson_sample_size(rs)
for r in rs:
assert r ... |
3b7ea0c9ad71c53db072f65bbc63e9269f4d9689abcafe66c36dedb671deed79 | Python | 1,491 | 41 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
ef3c105144d00368666cd1ef0b6983911ab7e3547bbe911e1247c876106e17ef | Python | 1,492 | 55 | import matplotlib.pyplot as plt
'''
This class creates a dynamically updating matplotlib line plot
'''
class updating_matplotlib_plot():
#Suppose we know the x range
min_x = 0
max_x = 10
def __init__(self):
#Set up plot
plt.ion()
self.figure, self.ax = plt.subplots()
... |
e6af9a53310b558a824960481d15d8d0a5507bde605b97be7349c29cbab077f6 | Python | 1,493 | 42 | from brian2.units import *
from brian2.core.clocks import defaultclock
""" Fixed parameters required by the equations """
tau_Cl = 100.*ms # removal rate of chloride ions in excitatory cells; healthy 0.1s | epilepsy 0.5s or 1.0s, page 88, Aussel
Ek = -100.*mV # resting potential of pot... |
a005eea5a24c39f3e1abdb6d679bd0d04ce4c0a3fba13fa26218caf309499fde | Python | 1,494 | 56 | import re
import sys
import chromadb_rust_bindings
import requests
from packaging.version import parse
import chromadb
def build_cli_args(**kwargs):
args = []
for key, value in kwargs.items():
if isinstance(value, bool):
if value:
args.append(f"--{key}")
elif valu... |
e371ecd9bf9a66121492f130dec92df10cf85ae4cbce76e4c399c9699c0e2162 | Python | 1,494 | 41 | """
Check whether the input data representation adheres to the stage's requirements.
Additionally prints a short summary of the data attributes.
"""
import numpy as np
import argparse
from utils.io_utils import load_neo
CLI = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDe... |
026ed31c5eb499ec5018bbd3a5206c60e7f3361bc47b83385a5538dfb1f381ef | Python | 1,495 | 54 | from overrides import override
from typing import Any, Callable, TypeVar, Dict, Optional
from uuid import UUID
from chromadb.api.types import (
Embeddings,
Metadatas,
Documents,
URIs,
IDs,
CollectionMetadata,
Where,
WhereDocument,
)
from chromadb.quota import QuotaEnforcer, Action
from ... |
b161cbe8f48ca197c8e591f41c39dc7671b7c66d9721e39a5e09be8c50a84819 | Python | 1,495 | 38 | from PymoNNto.Exploration.Network_UI.TabBase import *
class scatter_tab(TabBase):
def __init__(self, x_var, y_var, title='Scatter', timesteps=500):
super().__init__(title)
self.x_var = x_var
self.y_var = y_var
self.timesteps=timesteps
def add_recorder_variables(self, neuron_gr... |
6400495e0026393cf5b4dfc09d6d1b93d27aab014bb11d88a115b3447201d803 | Python | 1,498 | 48 | import sys,os
import miscFuncs
maskedRefFaFileName, maskFileDir, winSize = sys.argv[1:]
winSize = int(winSize)
os.system("mkdir -p %s" %(maskFileDir))
maskedGenome = miscFuncs.readFa(maskedRefFaFileName)
def getMaskedRuns(seq, winSize):
inRun = False
runs = []
for i in range(len(seq)):
if inRun:
... |
16f8321380a8c34e136a9003b62c7e8abbbdbffae545bd50a4a0d6669d4e90fa | Python | 1,499 | 53 | import random
import pytest
from geomstats.geometry.product_hpd_and_siegel_disks import (
ProductHPDMatricesAndSiegelDisks,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.geometry.product_manifold import ProductManifoldTestCase
from geomstats.test_cases.geometry.riemann... |
84e4037a6cb8c73dcde6162393556fd163028f1c80a30f4d592bbebf22476d8d | Python | 1,501 | 51 | from abc import abstractmethod
from typing import Any, Dict, Generic, Protocol, TypeVar
from typing_extensions import Self
import json
T = TypeVar("T", covariant=True)
class JSONSerializable(Protocol[T]):
"""A generic interface for objects that can be serialized to JSON"""
def to_json_str(self) -> str:
... |
24b479152ca78c64d717e9622b51b3b1fb64300d904b77019a9d82100d720e40 | Python | 1,503 | 53 | import shutil
from dig.sslgraph.dataset import TUDatasetExt
def test_TUDatasetExt():
## semisupervised
# NCI1
root = './dataset/TUDataset'
dataset = TUDatasetExt(root, name='NCI1', task='semisupervised')
assert len(dataset) == 4110
assert dataset.num_features == 37
assert dataset[0].x.size... |
8417e848073e8e1e403b3a8542d8156ff05dc4cfa9286a1b2f8d69f6c30cc245 | Python | 1,504 | 46 | from __future__ import annotations
import logging
import torch
from reinvent.models import ModelAdapter
from reinvent.runmodes import RL
from reinvent.runmodes.RL.validation import SectionLearningStrategy
logger = logging.getLogger(__name__)
def setup_reward_strategy(config: SectionLearningStrategy, agent: ModelA... |
4314f7141eb0a7e50757327c999f0479cd39bed7de5b29f3609758eff2472e4c | Python | 1,505 | 63 | from __future__ import annotations
import functools as ft
from typing import TYPE_CHECKING
from snakebids.paths._templates import spec_func
from snakebids.paths._utils import BidsPathSpec, find_entity, get_spec_path, load_spec
# <AUTOUPDATE>
# The code between these tags is automatically generated. Do not
# manually... |
1e4a37f2c25f4fd39a38a55ebc047af49ce588ef71324896d009512094e7fa9f | Python | 1,507 | 58 | from .basevtkhandler import BaseVTKHandler
class STLHandler(BaseVTKHandler):
"""
Handler for .STL files.
"""
from vtk import vtkSTLReader, vtkSTLWriter
from vtk import vtkPolyData
_data_type_ = vtkPolyData
_reader_ = vtkSTLReader
_writer_ = vtkSTLWriter
@classmethod
def read... |
9a5670e3f4406d04000efc7f37e12ab8519709bf3bb07ba6ad0e4f6afceb0577 | Python | 1,507 | 46 | import random
import hydra
import yaml
from omegaconf import OmegaConf
import pickle
from common.utils import proc_targets, load_metadata
from prognosis.utils import *
@hydra.main(config_path="../prognosis/configs/config_train.yaml")
def main(cfg):
wdir = os.environ['PWD']
if not os.path.isabs(cfg.meta_root)... |
7697dfab93b0042b98c4178cc27b201a5ccf50c4c8cb76c0c987a07c02a9e1e1 | Python | 1,508 | 44 | import pytest
import geomstats.backend as gs
from geomstats.test.random import RandomDataGenerator
from geomstats.test.test_case import TestCase
from geomstats.test_cases.metric_geometry.point_set import PointTestCase
class RandomGroveDataGenerator(RandomDataGenerator):
def __init__(self, space, topology):
... |
25e48edc633dafa7c4dcf90fae3ed447f8751e156e035574da1eab165b15f9e7 | Python | 1,510 | 39 | import os, shutil
# find normal CXR images from the metadata csv file
file = open(file='path/to/CheXpert-v1.0-small/train.csv', mode='r')
header = file.readline()
normal_cxr_cases = list()
records = file.readlines()
for record in records:
this_record = record.split(',')
if this_record[4] is not "":
if... |
853bad51a397134b3a38967c3c5d93e5349459f43d4cb2b188b6419e54782d81 | Python | 1,510 | 44 | import pandas as pd
import os
# List of input files and output files
input_files = [
"CD16p_Mono_nominal_P_value_2.txt",
"CL_Mono_nominal_P_value_2.txt",
"CM_CD8_nominal_P_value_2.txt",
"DN_B_nominal_P_value_2.txt",
"EM_CD8_nominal_P_value_2.txt",
"Fr_II_eTreg_nominal_P_value_2.txt",
"Fr_II... |
09aa1f5ac399790d0491076b8a75891ca7242a5ba38e57bbf98810aebb0845d4 | Python | 1,511 | 60 | import neurodecode
import numpy as np
from neurodecode.triggers import TriggerDef
tdef = TriggerDef('triggerdef_16.ini')
DATA_DIRS = [r'D:\data\MI\rx1\train']
CHANNEL_PICKS = [5, 6, 7, 11]
'''"""""""""""""""""""""""""""
Epochs and events of interest
"""""""""""""""""""""""""""'''
TRIGGERS = {tdef.LEFT_GO, tdef.RIGH... |
834aa1a197d4b5866549ee2844da437af72335002ea82a0ef542d5c07134e1ef | Python | 1,511 | 57 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 11:54:30 2023
@author: egemo
"""
from .utils import get_device
from torch import arange
class core:
"""
Easy way to broadcast var change would be to modify these placeholders.
At the moment, all those are shadowed
"""
batch_... |
653073a7dd8bc9d6b97dfbdc3c2b263db8164cddcdffa683212129bcaef5ab53 | Python | 1,513 | 62 | from Purkinje_morpho_1 import Purkinje_Morpho_1
from neuron import h,gui
import multiprocessing
from Purkinje_morpho_1_number import number_ind_1
import numpy as np
import matplotlib.pyplot as plt
Hines = h.CVode()
Hines.active(0)
spines_on = 0 # switch between 0 (no spines) and 1 (spines)
stimdata = dict()
stimdata... |
ad288cedbffc23c8be22ea5262973bd5a513888fd5d6ee730409ce6dd636cb64 | Python | 1,513 | 62 | from Purkinje_morpho_1 import Purkinje_Morpho_1
from neuron import h,gui
import multiprocessing
from Purkinje_morpho_1_number import number_ind_1
import numpy as np
import matplotlib.pyplot as plt
Hines = h.CVode()
Hines.active(0)
spines_on = 1 # switch between 0 (no spines) and 1 (spines)
stimdata = dict()
stimdata... |
2b7b4d55b4496db56ecb8b60eb3e2f86cdae7f8fa08135a7bc97674c96b75903 | Python | 1,516 | 71 | from .confparams import conf
from .logging_utils import (
LOGGING_QUEUE,
TMP_LOG_FILE,
init_logger,
manage_exception,
setup_logging_queue,
wrap_entrypoint,
)
from .py_utils import (
Episode,
H5DatasetProxy,
IdtrackeraiError,
LengthCalibration,
Timer,
assert_all_files_exis... |
4a6ba2b771b7f481abd9edcb4497c878bb57f64b86d8431c13790b413fe443e1 | Python | 1,516 | 44 | # Author: Guoqing Bao
# School of Computer Science, The University of Sydney
# Date: 2019-12-12
# GitHub Project Link: https://github.com/guoqingbao/Pathofusion
# Please cite our work if you found it is useful for your research or clinical practice
from django.shortcuts import render
from django.core.paginator import ... |
4e0ccd4c1e739c7873f5c28eb946a1576a37ee65fafb8a3ef16454a365781162 | Python | 1,516 | 39 |
# -*- coding: utf-8 -*-
#
#
# PyRates software framework for flexible implementation of neural
# network models and simulations. See also:
# https://github.com/pyrates-neuroscience/PyRates
#
# Copyright (C) 2017-2018 the original authors (Richard Gast and
# Daniel Rose), the Max-Planck-Institute for Human Cognitiv... |
b35c41b228c86ca9444c9d6f400d9c465802432bb390f90ea1a27ba3d26f574b | Python | 1,518 | 45 | """Attachable function definitions for ChromaDB collections.
This module provides function constants that can be attached to collections
to perform automatic computations on collection data.
Example:
>>> from chromadb.api.functions import STATISTICS_FUNCTION
>>> attached_fn = collection.attach_function(
.... |
2c924e405a041f717e623e933bb078aed5f5d36c822cf51a87107a72d2d98716 | Python | 1,519 | 54 | import random
import pytest
from geomstats.geometry.product_positive_reals_and_poincare_disks import (
ProductPositiveRealsAndComplexPoincareDisks,
)
from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.geometry.product_manifold import ProductManifoldTestCase
from geomstats.tes... |
46d789a4cb3cecf09f8146514d8a844ad93ca65a4f6891f1e6e73377241e6e1c | Python | 1,519 | 33 | import tensorflow as tf
def frequency_masking(mel_spectrogram, frequency_masking_para, frequency_mask_num):
fbank_size = mel_spectrogram.get_shape().as_list()
n, v = fbank_size[0], fbank_size[1]
for i in range(frequency_mask_num):
f = tf.cast(tf.random.uniform(shape=(), maxval=frequency_masking_p... |
66d583357423290754a0961c444774a8f245b039216ad1e4056f0be3ec2eb483 | Python | 1,521 | 44 | from nltools.mask import create_sphere, roi_to_brain
from nltools.data import Brain_Data
import numpy as np
import pandas as pd
def test_create_sphere():
# Test values update to reflect the fact that standard Brain_Data mask has few voxels because ventricles are 0'd out
a = create_sphere(radius=10, coordinat... |
dca59638c7be53dc4b986a92ce7c1936f451cd11c76049f01606d202b889bdf8 | Python | 1,521 | 43 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 15:25:17 2018
@author: ngritti
"""
from deeprest.rawDataClass import rawData
from deeprest.modelClass import modelRest
import time, os, glob
##%%
'''
create model and train on the input dataset of the train_model function
'''
paramFileModel = o... |
3108fda1a3d27ec269f70c350ea562280b0bab4e52a29f24b2859a88a7b68490 | Python | 1,522 | 47 | # -*- coding: utf-8 -*-
#
#
# PyRates software framework for flexible implementation of neural
# network models and simulations. See also:
# https://github.com/pyrates-neuroscience/PyRates
#
# Copyright (C) 2017-2018 the original authors (Richard Gast and
# Daniel Rose), the Max-Planck-Institute for Human Cognitive... |
b6a0f114915e180b0b39760ca0c91843feddfd629784a87d0df97eb2d9f41f19 | Python | 1,522 | 75 | import time
import numpy as np
from brian2 import (
StateMonitor,
SpikeMonitor,
defaultclock,
prefs,
NeuronGroup,
run,
Synapses,
plot,
ms,
mV,
float32,
set_device,
device,
)
import matplotlib.pyplot as plt
from globparams import *
set_device('cpp_standalone', clean=Tr... |
0f574093941f441e67d8d1735a00ad5a6c44c3ee42e9f01133558587639695d3 | Python | 1,524 | 52 | '''
Description:
Author: voicebeer
Date: 2020-10-31 02:52:59
LastEditTime: 2020-10-31 03:04:46
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.manifold import TSNE
class FeatureVisualize(object):
'''
Visualize features by TSNE
'''
def __init__(self, f... |
5aff304e0f995b355b76873bdf37641229b36bdd7ad0a5d47741b58b4b6c62bf | Python | 1,525 | 60 | """
EXPERIMENTAL: Manage video overlays that display visual information on top of image source streams.
Author: Tal Eisenberg, 2021
"""
import video_system
# TODO:
# - way to choose overlays
overlays = {}
def is_point_in_bounds(p, frame):
px, py = p
return px >= 0 and px < frame.shape[1] and py >= 0 and py... |
cf5ec30a71d982158ac76dd8841c00d1594ed1a526c80bd667c08bc73f06351e | Python | 1,525 | 45 | import pytest
import geomstats.backend as gs
from geomstats.test_cases.geometry.pullback_metric import PullbackDiffeoMetricTestCase
def univariate_fisher_rao_dist(point_a, point_b):
mean_a = point_a[..., 0]
mean_b = point_b[..., 0]
sigma_a = point_a[..., 1]
sigma_b = point_b[..., 1]
sdiff_mean =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.