sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
991a89bc0f9e4bad4c05327cb4d2a4cbc5bb03591ac26b9fc6d12c72bc2c88b0 | Python | 1,022 | 30 | from enum import Enum
class Operator(str, Enum):
ADD = "Add"
SUBTRACT = "Subtract"
DIFFERENCE = "Absolute Difference"
MULTIPLY = "Multiply"
DIVIDE = "Divide"
AVERAGE = "Average"
MINIMUM = "Minimum"
MAXIMUM = "Maximum"
STDEV = "Standard Deviation"
INVERT = "Invert"
COMPLEMENT... |
8949e4953d0c115a383067321b9d270b4c4a927494d3a4ca6ab41fc04f38d902 | Python | 1,026 | 36 | import tempfile
import os
import numpy
import numpy.testing
import h5py
from deeprank.tools.sparse import FLANgrid
def test_preserved():
beta = 1E-2
data = numpy.array([[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.1, 0.0],
[0.0, 0.0, 0.0, 0.0],
... |
bbbe9ebd0acc77424845998bd5ae87d6a59a73c2d89816c805c191aa2a417edd | Python | 1,027 | 22 | import pytest
from pathlib import Path
from imctools.io.txt.txtparser import TxtParser
class TestTxtParser:
def test_read_invalid_suffix(self):
with pytest.raises(FileNotFoundError):
TxtParser('file.unsupported_suffix')
def test_read_ometiff(self, raw_path: Path):
txt_file_path =... |
f0cd93fd375f493d2a2452014e57c1aef28e150bfdd76c15a6de0d31ab885dea | Python | 1,027 | 29 | from __future__ import absolute_import
import numpy as np
from scipy.fftpack import fft2
from scipy.ndimage import sum as nd_sum
def rps(img):
assert img.ndim == 2
radii2 = (np.arange(img.shape[0]).reshape((img.shape[0], 1)) ** 2) + (
np.arange(img.shape[1]) ** 2
)
radii2 = np.minimum(radii2, ... |
f928f8583a48e5b41eea65a5734c83c2d1e300c4a02177fe87d9398a26f1f17d | Python | 1,029 | 29 | import glob
import os
import shutil
model_Dir = './Model'
dir = './Model_HPC'
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir)
filesin_model = [x for x in glob.glob(model_Dir+'/*') if os.path.isfile(x)]
for f in filesin_model:
shutil.copy2(f, dir)
for x in ['Mods', 'morphologies']:
shutil.copy... |
4997389086c93ce55c6a263f236aef448954ff78885722463d13448302e52f41 | Python | 1,032 | 43 | import matplotlib
import matplotlib.cm
import numpy as np
def DepthNorm(depth, maxDepth=1000.0):
return maxDepth / depth
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def up... |
5f22a78a497af211d8da25682e6b86291cbb888c3884a3d7f279b65514c7a0f6 | Python | 1,033 | 33 | import torch
import numpy as np
from src.models.tabular.base import BaseModel
class PTBaseModel(BaseModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_network()
self.feats_con_ids = []
if self.hparams.continuous_cols:
self.feats_con_ids = np.ar... |
213e6290c2ddc79a22ad5837ac2ae2046763a9b2dd32a30f97a7e09154a2fa87 | Python | 1,035 | 38 | #!/usr/bin/env python2
# code extracted from Daniel Kim's ATAQC module (run_ataqc.py)
import os, sys, re, gzip
def getFileHandle(filename, mode="r"):
if (re.search('.gz$',filename) or re.search('.gzip',filename)):
if (mode=="r"):
mode="rb";
return gzip.open(filename,mode)
else:
... |
748fb75d35f77c1fae6c9615634a5eb9fb1545dadb38b8c77d2371141e737bab | Python | 1,035 | 38 | from datetime import datetime
import numpy as np
import pytest
import pysteps
def test_read_timeseries_mch():
pytest.importorskip("PIL")
date = datetime.strptime("201505151630", "%Y%m%d%H%M")
data_source = pysteps.rcparams.data_sources["mch"]
root_path = data_source["root_path"]
path_fmt = data... |
0d02ccc6dfe6bc3af6aa369871cde8b6fedb3568e065b4324ca007d0cc29841c | Python | 1,038 | 36 | import pytest
import numpy as np
from pysteps import feature
from pysteps.tests.helpers import get_precipitation_fields
arg_names = ["method", "max_num_features"]
arg_values = [("blob", None), ("blob", 5), ("shitomasi", None), ("shitomasi", 5)]
@pytest.mark.parametrize(arg_names, arg_values)
def test_feature(method,... |
2dadf8ca09455358800d539d6c30a8ecb9e7e5b40b00b198763e3682066ceae0 | Python | 1,040 | 41 | from Bio import SeqIO
import csv
import os
# get the average % homology of all alignments
def get_percent(aln_seq, ref_seq):
count_similar = 0
for i, j in zip(aln_seq, ref_seq):
assert j != "-"
if i == j:
count_similar += 1
similarity = float(count_similar/len(ref_seq))
return similarity
#-----... |
6a1b8eb4afe3d50ebb1056fb93a1ac3531bdb5dc686f947bbef438ff8584be16 | Python | 1,041 | 43 | '''
This script take fastq from SRA and add 1 and 2 to first and second reads.
'''
import os
import HTSeq
sra_numbers = [
"SRR13197374_trim_R1.fastq" ,"SRR13197373_trim_R1.fastq", "SRR13197372_trim_R1.fastq",
"SRR13197374_trim_R2.fastq" ,"SRR13197373_trim_R2.fastq", "SRR13197372_trim_R2.fastq",
]
# di... |
2937fab3b3fa5544392acac27b6788d3cec006d0a1e0e1f9b444c17f5ff258e3 | Python | 1,042 | 40 | """
NIDM-Experiment Python API
--------------------------
Python API to create, query, read, and write NIDM-Experiment documents.
"""
from .Acquisition import Acquisition
from .AcquisitionObject import AcquisitionObject
from .AssessmentAcquisition import AssessmentAcquisition
from .AssessmentObject import AssessmentO... |
e913de62a50981edc09ebff29480b7241064d12efa91c3af6e940a48ee678caa | Python | 1,044 | 34 | import torch
from src.models.tabular.base import BaseModel
class WDBaseModel(BaseModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_network()
self.feats_all_ids = list(self.hparams.column_idx.values())
self.feats_cat_ids = []
if self.hparams.cat_em... |
54769fe72d8fb16de454863f265f5502a18992686d8e427256fe77d892264578 | Python | 1,045 | 30 | from scipy import stats
from matplotlib.lines import Line2D
import numpy as np
'''
This script was used to calculate the slope of the curve # ATP molecules vs time, and gives the rate of ATP production.
GCG
8.11.23
'''
seed_number = 10
f = open('linear_regression_all_M1.txt','w')
for i in range(seed_number):
pri... |
f41950d48abaccb4461b00ab27a719b73d22e7638b0c085d15eab10d227533c7 | Python | 1,046 | 30 | import torch.nn as nn
import torchvision.models as models
from exceptions.exceptions import InvalidBackboneError
class ResNetSimCLR(nn.Module):
def __init__(self, base_model, out_dim):
super(ResNetSimCLR, self).__init__()
self.resnet_dict = {"resnet18": models.resnet18(pretrained=False, num_clas... |
cdfd993dbd54536c75896a8213f5ceaab95faa01c16b6d5e9c643c8399566e07 | Python | 1,049 | 22 | import pytest
from pathlib import Path
from imctools.io.ometiff.ometiffparser import OmeTiffParser
class TestOmeTiffParser:
def test_read_invalid_suffix(self):
with pytest.raises(FileNotFoundError):
OmeTiffParser('file.unsupported_suffix')
def test_read_ometiff(self, analysis_ometiff_pat... |
8efdba502e426be5145ab63cf75278ea4095f29db88f37e6a08712a7fd01a59c | Python | 1,052 | 30 | def replace_layer_recursive(model, old_layer, new_layer):
for name, layer in model._modules.items():
if layer == old_layer:
model._modules[name] = new_layer
return True
elif replace_layer_recursive(layer, old_layer, new_layer):
return True
return False
def r... |
c753cdc009e38d1a242545514165e8f857346fa73094b3b0c97b4669553a268b | Python | 1,054 | 30 | """Setup for the locCSN package."""
with open('README.md') as f:
README = f.read()
import setuptools
setuptools.setup(
author="Xuran Wang",
author_email="xuranw@andrew.cmu.edu",
name='locCSN',
license="MIT",
description='locCSN is a python package for local cell specific networks.',
versio... |
da70e8e249a4b367c9842c29462c6dad3b884f0122898a71d2b8c7b69ade41c9 | Python | 1,056 | 34 | import pytest
from click.testing import CliRunner
from GANDLF.entrypoints.verify_install import new_way, old_way
from . import CliCase, run_test_case
# This function is a place where a real logic is executed.
# For tests, we replace it with mock up, and check if this function is called
# with proper args fo... |
c8fed63be1ca434396fac181a689518f4ffffa08407772b4884ec4e8046955b8 | Python | 1,058 | 31 | from unittest import TestCase
import numpy as np
from numpy.testing import assert_equal
import scipy.sparse as sp
from .clustering import normalized_cut
class ClusteringTest(TestCase):
def test_normalized_cut_without_singletons(self):
adj = [[0, 2, 1, 0], [2, 0, 0, 1], [1, 0, 0, 2], [0, 1, 2, 0]]
... |
32cdaba13645e0ab59a3082c85a02ada867e928b62897e948ba7de2af4d2167f | Python | 1,066 | 36 | import numpy as np
import matplotlib.pyplot as plt
# Define parameters
dt = 0.1 # time step
t = np.arange(0, 1000, dt) # time vector
V0 = -70 # initial potential
Vr = -70 # reset potential
theta = -50 # threshold potential
tau = 20 # membrane time constant
g = 1.5 # input conductance
# Define input current
I =... |
04affa7cd4cab92991e2b770447301d23f17176905b9633761d167ac684f07ee | Python | 1,067 | 25 | # https://github.com/CellProfiler/CellProfiler/issues/2226
#
# '''test_version - test the version number and other information
# '''
#
# import unittest
#
# import cellprofiler.utilities.version
#
#
# class TestVersion(unittest.TestCase):
# def test_01_01_test_version_number(self):
# '''Check that the versi... |
4e1be4d5e41205d2e556ae3244ade07108bba1073672e937c58138dfbb7363e7 | Python | 1,068 | 38 |
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
# options for initializing HistAuGAN
class opts:
input_dim = 3
num_domains = 7
log_train_img_freq = 100
log_val_img_freq = 100
d_iter = 3
lambda_rec = 10.
lambda_cls = 1.
lambda_cls_G = 5.
def augment(x: tor... |
38bd5e5136d82bcfe68b3c7087dcc6957ba355042e3a94095c2e47a61103ed18 | Python | 1,069 | 27 | import os
path = './exprs/backup'
for expr_name in os.listdir(path):
if expr_name.startswith('.') or not ('cifar10_' in expr_name and 'resnet' in expr_name):
continue
expr_dir = os.path.join(path, expr_name)
for ckpt_name in os.listdir(expr_dir):
if ckpt_name.startswith('.'):
... |
b6e05d5550725700cfc5bf2503c6ad10001a8e11f0d55b9840d42c33505f6960 | Python | 1,074 | 34 | """Shared JSON-shape validators parameterized by error type."""
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from typing import Any, cast
ErrorFactory = Callable[[str], Exception]
def require_mapping(
value: object, field: str, error: ErrorFactory
) -> Mapping[str,... |
fd7d985841cae2115a3f5dcb1010febc8c3051486024424b713921c8c7b82410 | Python | 1,075 | 14 | from typing import Annotated, Optional, Union
from pydantic import Field, validate_call, ConfigDict
from cellprofiler_library.types import ImageGrayscale, ObjectLabelsDense, ImageBinary
from cellprofiler_library.functions.image_processing import image_to_objects
@validate_call(config=ConfigDict(arbitrary_types_allowed... |
01f55a1661c306eca568ae8ddd90342b33b8830dd6a07f56b4d46f5094a22d82 | Python | 1,078 | 35 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Run sensor array optimization for the 2D case. Save the results of the optimization
to the folder passed as command-lie parameter to this script. The folder should
exist and be empty.
"""
#%% Imports
import sys
import numpy as np
from megsimutils.arrays import noise_m... |
3f9c6c75fad597c7bd7f3a083039c3d31d94d1c305b5b91b5f8d09fe2d9cd477 | Python | 1,078 | 36 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Run sensor array optimization for the 3D case. Save the results of the optimization
to the folder passed as command-lie parameter to this script. The folder should
exist and be empty.
"""
#%% Imports
import sys
import numpy as np
from megsimutils.arrays import noise_m... |
f63e9f0ee6c155160aab13dbd90531a11688237816528e849849f011ea6de6fe | Python | 1,078 | 32 | # This file is part of pyunicorn.
# Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors
# URL: <https://www.pik-potsdam.de/members/donges/software-2/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or publi... |
027309ff1e011dda8f6b3f8f2a2bd878b3084c32361b8adeeb937fce4af5c754 | Python | 1,080 | 30 | #!/usr/bin/env python
from samplebase import SampleBase
class SimpleSquare(SampleBase):
def __init__(self, *args, **kwargs):
super(SimpleSquare, self).__init__(*args, **kwargs)
def run(self):
offset_canvas = self.matrix.CreateFrameCanvas()
while True:
for x in range(0, sel... |
5326cedf50fd28093d8b323900f7a3f10d1338c3c8d4e87d77224beb4a99b9ae | Python | 1,080 | 43 | from __future__ import division
from threading import Thread, Event
try:
from queue import Queue
except ImportError:
from Queue import Queue
class FileQueue(object):
def __init__(self, dataset, batch_size, capacity, shuffle=False):
inputs = Queue(capacity // batch_size)
stopper = Event(... |
5c738ce1bb85bfe8cc63e721fc6daf111db248c8bc46afec98f3148e6d95d617 | Python | 1,085 | 43 | #
# nate berry
# 2023-04-01
#
# ---------------------------------------------------------
# NOTES:
# - this file import the EEG and COM data and stores it as an *.npz
# file for use in subsequent scripts
#
# ---------------------------------------------------------
# ------------------------------------------... |
69c7fe6ec0891f661dbcae102196c9e70090a95c0a66e2360ca7267300e0f8a0 | Python | 1,085 | 48 | #!/usr/bin/env python
"""Extract first N groups of a hdf5 to a new hdf5 file.
Usage: python {0} <hdf5 input file> <hdf5 output file> <number of groups to write>
Example: python {0} ./001_1GPW.hdf5 ./001_1GPW_sub10.hdf5 10
"""
import sys
import h5py
USAGE = __doc__.format(__file__)
def check_input(args):
if le... |
81e261a43ef5e879e9a050c16af888966bca8f1c3bb157e8649c591f467c6007 | Python | 1,085 | 37 | #!/usr/bin/env python3
import os
import unittest
import logging
import shutil
import tempfile
import ciftify.config
from ciftify.utils import run
from pytest import raises
from unittest.mock import patch
import pytest
def get_test_data_path():
return os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data'... |
3c84ece2f3cf7cc70b173363ed4b19561dbf78632d65ab77108b5c85328b8e76 | Python | 1,086 | 41 | #!/usr/bin/env python3
from .ioutils import IOManager
class Pipeline(IOManager):
def __init__(
self,
timeseries,
root_dir,
path_elements,
file_parameters,
save_index=True,
*args,
**kwargs,
):
"""Constructions output directory according t... |
18cb1f248153f850f6cb029a75e5db8e4588ec5c6de9b20a5e4e891780690780 | Python | 1,088 | 27 | # This file is part of pyunicorn.
# Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors
# URL: <https://www.pik-potsdam.de/members/donges/software-2/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or publi... |
903aebda9de34ff181d88bad2286d0f24304704cf413ca3b76cde8b3583ca379 | Python | 1,088 | 40 | import numpy.testing
import pytest
import skimage.data
import skimage.morphology
import cellprofiler_core.image
import cellprofiler.modules.morphologicalskeleton
instance = cellprofiler.modules.morphologicalskeleton.MorphologicalSkeleton()
@pytest.fixture(
scope="module",
params=[
(skimage.data.came... |
122dfc67bc133e5e73ce2a9b42c3d9645e62ebe69fe3d94c5b528a00a937794a | Python | 1,090 | 44 | # Copyright (C) 2025 Severin Strobl <git@severin-strobl.de>
#
# SPDX-License-Identifier: MIT
#
# Exact calculation of the overlap volume of spheres and mesh elements.
# http://dx.doi.org/10.1016/j.jcp.2016.02.003
"""Exact calculation of the overlap volume and area of spheres and mesh elements.
Supported primitives
--... |
d83fd12c7103d1e64c9bbf4e6c5045e5b9c3d6be0646c0f6b9ad9a711412f091 | Python | 1,091 | 38 | # This file is part of pyunicorn.
# Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors
# URL: <https://www.pik-potsdam.de/members/donges/software-2/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or publi... |
4d793eaaac6f3e464cd651ac355c3dbe0f07201b83b5e1429340acf5a5b8ba8a | Python | 1,092 | 35 | from tempfile import mkstemp
import os
import h5py
from deeprank.models.variant import PdbVariantSelection
from deeprank.domain.amino_acid import *
from deeprank.generate.DataGenerator import DataGenerator
from deeprank.models.environment import Environment
def test_get_grid_center():
environment = Environment(... |
1c70777e79262c42defb56f08076a235da9ec792262c2d38b28efd63eb9ac4ec | Python | 1,095 | 29 | import torch
import torch.nn.functional as F
import torch.nn as nn
class ContrastiveLoss(torch.nn.Module):
def __init__(self, margin=2.0):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, output1, output2, label):
euclidean_distance = F.pa... |
52a19a5ecfe5b57446def970f2562b30e39ad0c97e279403c2d8958174a1e745 | Python | 1,095 | 29 | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .encoder import BiLstmEncoder
from .classifier import AttClassifier
from torch.autograd import Variable
from torch.nn import functional, init
class MGLattice_model(nn.Module):
def... |
2e9f2b6ac3847df0c5268bea14d41108623a1982176015bdc4fdbea9dceed489 | Python | 1,098 | 35 | from .cluster import Cluster
from .notelifneuron import NoteLIFNeuron
class NoteCluster(Cluster):
'''
classdocs
'''
def __init__(self, neutype, neunum):
'''
Constructor
'''
Cluster.__init__(self, neutype, neunum)
def createClusterNetwork(self):
for i in ra... |
730f4c3cac736e0d63b564d79fc5d8e024e6255eefff70f3eceb2effba0aefc1 | Python | 1,098 | 37 | import torch
def global_pool_nlc(
x: torch.Tensor,
pool_type: str = 'token',
num_prefix_tokens: int = 1,
reduce_include_prefix: bool = False,
):
"""Apply global pooling to tensor in NLC format.
Args:
x: Input tensor in (batch, length, channels) format.
pool_typ... |
7b3036b9e4fc205662d4d9da53bc9ef0e02a378f8378f08a10c804e489f4371b | Python | 1,099 | 36 | import warnings
import numpy as np
from pdb2sql import StructureSimilarity
from deeprank.targets import rmsd_fnat
def __compute_target__(decoy, targrp):
"""Calculate DOCKQ.
Args:
decoy(bytes): pdb data of the decoy
targrp(hdf5 file handle): HDF5 'targets' group
"""
tarname = 'DOCKQ'... |
e3768d19c8296a99020beec95acc2b033d152384140d34d7294772e91ffbdbf9 | Python | 1,100 | 32 | from __future__ import absolute_import
import centriole.kirsch
import scipy.misc
import numpy as np
import numpy.testing
import unittest
class TestKirsch(unittest.TestCase):
def test_01_01_kirsch(self):
#
# Test a maximum at all possible orientations
#
r = np.random.RandomState([or... |
279091182b0bcb2eb5bb62e0d1d1c24f57982d5c2b1a5b7432553582d1507ac6 | Python | 1,103 | 27 | from enum import Enum
# Catrgoty string for the AreaOccupied/VolumeOccupied measurement
C_AREA_OCCUPIED = "AreaOccupied"
# # Measurement feature name format for the AreaOccupied/VolumeOccupied measurement
class MeasurementType(str, Enum):
AREA_OCCUPIED = "AreaOccupied"
VOLUME_OCCUPIED = "VolumeOccupied"
... |
1a32a1297be4e1494ae2b0fb4a51bac8c416377201c998525e04e12f060245a0 | Python | 1,105 | 32 | #!/usr/bin/env python3
# Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera
#
# 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
... |
4e0290f5fbc9df7fb161a9ae8b9b367aed27db897c97526fecabc9a2a877ac68 | Python | 1,106 | 43 | #!/usr/bin/env python
'''Change the pixdim4 value and xyzt_units value in the header of a nifti file
Usage:
EditHeader.py <Nifti file> <TR_value> <xyzt_units>
Argument(s):
<Nifti file> A nifti file
<TR_value> This is the TR that will be substituted in the field "pixdim4" in the header
<xyzt_units> This is the va... |
e608968fff1a2cdcc2c6325df21946dbe8ffc28cd091c60876c0fe247a4c70ff | Python | 1,106 | 47 | from enum import Enum
class SkeletonMeasurements(str, Enum):
"""The trunk count feature"""
NUMBER_TRUNKS = "NumberTrunks"
"""The branch feature"""
NUMBER_NON_TRUNK_BRANCHES = "NumberNonTrunkBranches"
"""The endpoint feature"""
NUMBER_BRANCH_ENDS = "NumberBranchEnds"
"""The neurite length fe... |
eb1ba3a1ae4455516e8acb7f9e2ed800804f7905c425f01166d487000107f169 | Python | 1,108 | 34 | import os
from setuptools import setup
from setuptools import find_packages
with open('README.md') as f:
readme = f.read()
with open('requirement.txt') as f:
requirements = f.readlines()
setup(
name='cryspnet',
version='0.1',
description='CRYSPNet: Crystal Structure Predictions via Neural Netwo... |
93c86933671e382efa8b55a576de1ed4f0ec55e226e4346b579908af141f0421 | Python | 1,110 | 34 | """
@author: Johanna Rahm
Research group Heilemann
Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M.
Handle data loading of ImageBinner Jupyter Notebook.
"""
from skimage import io
import pandas as pd
class Data():
def __init__(self):
self.movies = [] # list of tif mov... |
d64c35906767daaf4372b3ed9aacc5649d777ff38f2cd4bca4ceb080c5d21a77 | Python | 1,110 | 24 | import rvt.blend
# read blender combinations from file
blender_combinations = rvt.blend.BlenderCombinations()
blender_combinations.read_from_file(file_path=r".\settings\default_blender_combinations.json")
# print all combinations names
print(blender_combinations.combinations_names())
# select specific combination, r... |
b885a0bed42afea7788c7bf4ab7fb128378651c5d78ac9a9c5bb9278926e9df2 | Python | 1,114 | 46 | # Copyright (C) 2014 SWIPO Project
#
# Authors (this file):
# Stefan Schinkel <stefan.schinkel@gmail.com>
"""
Provides Simple test for the treatment of complex admittances
in resistive networks.
"""
import numpy as np
from pyunicorn import ResNetwork
res = ResNetwork.SmallTestNetwork()
resC = ResNetwork.SmallComp... |
1b8cc415987710eb4cdc0b9d65a157e40c69647d5e6eb10185c7d35a276c10a1 | Python | 1,119 | 36 | import prov.model as pm
from .Acquisition import Acquisition
from ..core import Constants
class MRAcquisition(Acquisition):
"""
Default constructor, creates a session activity and links to project object
:param session: a session object
"""
# constructor
def __init__(self, session, attribut... |
eb82d4cbdc09fa3826bac1c770803223ffa32d53340003bab740332301fc799f | Python | 1,119 | 33 | import prov.model as pm
from ..core import Constants
from ..experiment.Core import Core, getUUID
class ProcessExecution(pm.ProvActivity, Core):
"""Class for NIDM-Workflow ProcessExecution Objects.
Default constructor uses empty graph with namespaces added from
NIDM/Scripts/Constants.py. Additional altern... |
afb9880acf3773ef53e6e5788d6b913f7d3c5440aa7386d27b06eed4b6cb0394 | Python | 1,120 | 36 | import prov.model as pm
from .Acquisition import Acquisition
from ..core import Constants
class PETAcquisition(Acquisition):
"""
Default constructor, creates a session activity and links to project object
:param session: a session object
"""
# constructor
def __init__(self, session, attribu... |
2d46d05a9badb5db7e0eb815dad27f5494ad56f52dd307c75b78cafe1b712f6a | Python | 1,122 | 32 | #!/usr/bin/python
# -*- coding: utf8 -*-
from setuptools import find_packages,setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="deepevent",
version="0.4",
author="Lempereur Mathieu",
author_email="mathieu.lempereur@univ-brest.fr",
description="Dee... |
e567057a758027f48299aa56ab44d5985a14f8ff9bcf8c1fbf424b852a3c1682 | Python | 1,122 | 30 | import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tfd = tfp.distributions
def squared_dist(x):
"""Efficiently computes the squared pairwise distance between the element of the vector x."""
expanded_a = tf.expand_dims(x, 1)
expanded_b = tf.expand_dims(x, 0)
distances = tf.... |
f23484537c96bbf8b9d5e3f73e89e7a4d16c45d9e33b726ed4f97c6d0374e45c | Python | 1,124 | 51 | from visual_coding_2p_analysis.l0_analysis import L0_analysis
from allensdk.core.brain_observatory_cache import BrainObservatoryCache
MANIFEST_FILE = '/allen/aibs/technology/allensdk_data/platform_boc_pre_2018_3_16/manifest.json'
def generate_events(n):
boc = BrainObservatoryCache(manifest_file=MANIFEST_FILE)
... |
7e4949a5e7139b453c4610b9b1ffffa702392719355f6f4bf0d2ade489a790bf | Python | 1,125 | 26 | import argparse
# config the parameters
parser = argparse.ArgumentParser(description='Train the EDOF network')
parser.add_argument('--dirc_data', default='', dest='dirc_data')
parser.add_argument('--dirc_ckpt', default='', dest='dirc_ckpt')
parser.add_argument('--dirc_pretrain', default='', dest='dirc_pretrain... |
84ad86644bc2bf1291b994f03f4767bf530d22ad3c39558410edc07ef6435466 | Python | 1,125 | 32 | #!/usr/bin/env python3
# Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera
#
# 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
... |
97052557776f86f728936e4ff114c188982c5afaa0613c15d70b2a285d165cbb | Python | 1,126 | 35 | """
Functions associated with legacy python
"""
def cmp(a, b):
return int((a > b)) - int((a < b))
def equals(a, b, encoding_a="utf-8", encoding_b="utf-8"):
"""
Purpose: Used primarily for equality comparisons between bytes and str but can be used for any type
:param a: any python type, including by... |
3160a9d80d4decbcf1a3a6c8a4509dd2624c8da11960608adf0f07a52ab75c7a | Python | 1,127 | 31 | class SettingsGroup:
"""A group of settings that are managed together in the UI.
Particulary useful when used with a RemoveSettingButton.
Individual settings can be added with append(), and their value
fetched from the group using the name given in append.
"""
def __init__(self):
self.s... |
a18b5953eb3214d543ba48fce8d26cc787000e1c10970a08979f5f2bbdffa3da | Python | 1,130 | 28 | import sys
import os
# Repo root on sys.path so `import dragen...` and `import tests.scenarios...` resolve regardless
# of how pytest is invoked (bare `pytest`, `python -m pytest`, from any cwd).
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import pytest
from dragen.utilities.Input... |
eeee3ba631c89caef87897cab96fbb92a06bf17faf1742e5c208cbe7ae8e9a2d | Python | 1,132 | 37 | from enum import Enum
class DistanceMethod(str, Enum):
ADJACENT = "Adjacent"
EXPAND = "Expand until adjacent"
WITHIN = "Within a specified distance"
class Measurement(str, Enum):
NUMBER_OF_NEIGHBORS = "NumberOfNeighbors"
PERCENT_TOUCHING = "PercentTouching"
FIRST_CLOSEST_OBJECT_NUMBER = "First... |
7cc5722aa02dac918bbcc652f14e40695ed5a107e6a7db9d0c4007916efc8ac4 | Python | 1,133 | 36 | import h5py
import numpy as np
import matplotlib.pyplot as plt
def create_hdf5_generator(db_path, batch_size):
db = h5py.File(db_path)
db_size = db['spectra'].shape[0]
while True:
for i in np.arange(0, db_size, batch_size):
spectra = db['spectra'][i:i+batch_size]
labels_id... |
f7db43e54306810cbc5bdcb4f7a38fc5b3a9afbf7c5585950f1ea7ed36d195f4 | Python | 1,133 | 51 | import os
import pytest
from ..jsonldutils import to_newformat
@pytest.fixture
def filename():
ldfile = os.path.join(
os.path.dirname(__file__), "data", "protocols", "protocol1.jsonld"
)
cwd = os.getcwd()
ldfile = ldfile.replace(f"{cwd}/", "")
return ldfile
def test_jsonld(filename):
... |
f95e8425b77dcee13e7c7ea3bb871039930144f1a00146b975df4ff92ba0a7a4 | Python | 1,134 | 37 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Run sensor array optimization for the 3D case. Save the results of the optimization
to the folder passed as command-lie parameter to this script. The folder should
exist and be empty.
"""
#%% Imports
import sys
import numpy as np
from megsimutils.arrays import noise_m... |
8fe7cc02a1efcf230c4176f649fed4ae7938a10df5a53fa0fcd5dfdcaf8d3387 | Python | 1,137 | 35 | """
Author: "Keitaro Yamashita, Garib N. Murshudov"
MRC Laboratory of Molecular Biology
This software is released under the
Mozilla Public License, version 2.0; see LICENSE.
"""
from __future__ import absolute_import, division, print_function, generators
from . import logger
from . import symmetry
from . import fi... |
a533dbd80c00ffeb961f3998628502f486ba14e73cc35bfaf63d1394056b8838 | Python | 1,137 | 24 | from pathlib import Path
from imctools.io.imc.imcparser import ImcParser
class TestImcParser:
def test_read_imc_folder(self, analysis_ometiff_path: Path):
imc_folder_path = analysis_ometiff_path / '20210305_NE_mockData1'
parser = ImcParser(imc_folder_path)
ac_data = parser.get_acquisition... |
88296f652ed4794b5be148d22bbd98cc89072f9f173cd0e6e3fb190ae24984e9 | Python | 1,139 | 33 | from cellprofiler_core.constants.worker import ED_STOP, ED_SKIP
from ..pipeline import RunException
class PipelineEventListener:
"""listen for pipeline events, communicate them as necessary to the
analysis manager."""
def __init__(self, handle_exception_fn):
self.handle_exception_fn = handle_exc... |
ed6a233137288f921118a91334f91d8eb45ab2cebfd759754e74f1f80dd117aa | Python | 1,140 | 40 | import numpy as np
import matplotlib.pyplot as plt
# Define parameters
dt = 0.01 # time step
t = np.arange(0, 100, dt) # time vector
Cm = 0.1 # membrane capacitance
Vth = 1 # spike threshold
Vreset = 0 # reset potential
V0 = 0.5 # initial potential
tau_ref = 2 # refractory period
I = np.zeros(len(t))
I[500:1500... |
796ec1d964e98c26f5cbc8217f3f71dae4b073ea716e6cc077260eaad42e56c4 | Python | 1,141 | 30 | import numpy
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler_core.modules.injectimage
import cellprofiler_core.pipeline
import cellprofiler_core.workspace
def test_init():
image = numpy.zeros((10, 10), dtype=float)
x = cellprofiler_core.modules.injectimage.InjectImage(... |
79c280619cca745deb97af119b09631f35995d1b103bcdc2107186bf99967172 | Python | 1,146 | 38 | from enum import Enum
class FilterMethod(str, Enum):
"""Minimal filter - pick a single object per image by minimum measured value"""
MINIMAL = "Minimal"
"""Maximal filter - pick a single object per image by maximum measured value"""
MAXIMAL = "Maximal"
"""Pick one object per containing object by ... |
b8864c1cd8c4137cbae4309a4a100daf5dbf8bb7bd81bd9a2aa93d3530d5082d | Python | 1,147 | 34 | #!/usr/bin/env python3
# Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera
#
# 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
... |
cb937fab687ad2e81879713be957268f818e985b52aedf5fb62f65db7b7ffabb | Python | 1,147 | 34 | #!/usr/bin/env python3
# Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera
#
# 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
... |
5098170c343a1d90aded8529046f1f955f45a1e805bb372006b1d3c10a59090c | Python | 1,148 | 28 | # This hardware definition is to implement 5-CSRTT with specified hardare/circuit boards below:-
# 1)Five poke(five_poke)
# 2)Single Nose poke(reward_port)
# 3)House Light(house_light)
# 4)Speaker
# 5)Stepper Motor based Peristaltic pump/Syringe pump(syringe_pump)
from devices import *
board = Breakout_1_2... |
a2de37bb71206937b1c6e88bdf1804fa4ee6461a5e1289637848a7d80242d287 | Python | 1,148 | 34 | #!/usr/bin/env python3
# Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera
#
# 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
... |
02a93e378e4f4d9c5b76fa4084156b5af6cb6519a8fd2be1ecbbf177108aab39 | Python | 1,149 | 45 | # -*- coding: utf-8 -*-
from functools import partial
import numpy as np
import pytest
from pysteps.tests.helpers import get_precipitation_fields
default_dtypes = dict(
fmi="double",
knmi="double",
mch="double",
opera="double",
saf="double",
mrms="single",
)
@pytest.mark.parametrize("source... |
29874e47c2a16fc669d5d71a8fc6451d7ead29da5ded65e312a4e6d9f6f40483 | Python | 1,151 | 47 | import logging
import os
from reproschema._version import __version__
#
# Basic logger configuration
#
def get_logger(name=None):
"""Return a logger to use"""
return logging.getLogger("reproschema" + (".%s" % name if name else ""))
def set_logger_level(lgr, level):
if isinstance(level, int):
p... |
cbbfecba5423d58cfbe31429263e7360bbae9bb80feae7f343614ec3b6a67b35 | Python | 1,152 | 42 | #!/usr/bin/env python
from samplebase import SampleBase
class PulsingColors(SampleBase):
def __init__(self, *args, **kwargs):
super(PulsingColors, self).__init__(*args, **kwargs)
def run(self):
self.offscreen_canvas = self.matrix.CreateFrameCanvas()
continuum = 0
while True:
... |
d5d7d100091a48674f8387be48ba6da74c7c0d8d953265f7c627a9f1946e434f | Python | 1,152 | 49 | import os
from .....utilities.pathname import url2pathname
from .._file_image import FileImage
class URLImage(FileImage):
"""Reference an image via a URL"""
def __init__(
self,
name,
url,
rescale_range=None,
metadata_rescale=False,
series=None,
index=N... |
4b99a8e9d37f1f2c6cb964d7436f6a64dd9863becce0059ba50d8468540f7340 | Python | 1,155 | 55 | import pyabf
import numpy as np
def load_data(path, sweeps=None, channels=None):
"""
Given a current_folder and a filename it returns an array t, a float dt and
an array data=[datapoint, sweep, channel]
"""
abf = pyabf.ABF(path)
if channels is None:
channels = abf.channelList
i... |
6d75f2cb4b2e3267343f76e3ee87475585f5f30fbe219e8cbb572c78543d17b5 | Python | 1,157 | 31 | # -*- coding: utf-8 -*-
"""
Implementation of functions to clip gradients
"""
from typing import Optional
import torch
from GANDLF.grad_clipping.adaptive_gradient_clipping import adaptive_gradient_clip_
def dispatch_clip_grad_(
parameters: torch.Tensor,
value: float,
mode: Optional[str] = "norm",
norm... |
1218582dcf7ceacd973fbc4009b80b6fb3d5836549b943df6da5aa626606c582 | Python | 1,159 | 27 | from setuptools import find_packages
from setuptools import setup
with open("./requirements.txt", "r", encoding="utf-8") as fh:
install_requires = fh.read()
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
install_requires=install_requires,
packages=find_packages... |
83c7b6d9b0cc976e5e9005259d38e5acff3f6b6ce787849e3d478fe7a267bd49 | Python | 1,159 | 44 | from enum import Enum
class MorphFunction(str, Enum):
"""Morphological operations available in the Morph module."""
BRANCHPOINTS = "branchpoints"
BRIDGE = "bridge"
CLEAN = "clean"
CONVEX_HULL = "convex hull"
DIAG = "diag"
DISTANCE = "distance"
ENDPOINTS = "endpoints"
FILL = "fill"
... |
2b2ee9d291eade31be51908daa46eb9d82ff92d7b03c212859bcb69cc81bb83c | Python | 1,162 | 40 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
ce025d6bdc5c935ec70d681e39c352ad8a278218edee5c8f570e3d225027dec9 | Python | 1,162 | 32 | # import matplotlib
# matplotlib.use("Agg") # needed for plotting on travis
def test_pattern_factory():
""" Test hopfield_network.pattern_tools """
import neurodynex3.hopfield_network.pattern_tools as tools
pattern_size = 6
factory = tools.PatternFactory(pattern_size)
p1 = factory.create_checkerb... |
1c64f2bdc74eeedc086f2c4dd5a8369e230cab4e56fadbef349d0e96c940ecf2 | Python | 1,163 | 41 | import re
class FilterPredicate(object):
def __init__(self, symbol, display_name, function, subpredicates, doc=None):
self.symbol = symbol
self.display_name = display_name
self.function = function
self.subpredicates = subpredicates
self.doc = doc
def __call__(self, *ar... |
514969376044ecffab78e295074f8827820f5812a91950378b30758b31a5364b | Python | 1,163 | 25 | import pyControl.hardware as _h
class Breakout_1_2(_h.Mainboard):
def __init__(self):
# Inputs and outputs.
self.port_1 = _h.Port(DIO_A='X1', DIO_B='X2' , POW_A='Y7' , POW_B='Y8' , POW_C='Y11', UART=4)
self.port_2 = _h.Port(DIO_A='Y3', DIO_B='Y4' , POW_A='X4' , POW_B='X18', POW_C='Y12... |
ad57bfd39e192d6a61917cd679631be1f942c0f2ccf5480ded4e1e8962f4edcf | Python | 1,163 | 37 | import re
import logging
from deeprank.models.forcefield.param import VanderwaalsParam
_log = logging.getLogger(__name__)
class ParamParser:
LINE_PATTERN = re.compile(r"^NONBonded\s+([A-Z0-9]{1,4})((\s+\-?[0-9]+\.[0-9]+){4})\s*$")
@staticmethod
def parse(file_):
result = {}
for line in... |
9e7883fde54994eccd8b19b0dd88c21d232c5f4a407ef97ba9755a8da3395ed0 | Python | 1,165 | 48 | import tensorflow as tf
from .layer import GradientLayer
class PINN:
def __init__(self, network):
self.network = network
self.grads = GradientLayer(self.network)
def build(self):
# equation input: (t, x)
TY_eqn = tf.keras.layers.Input(shape=(2,))
prefactor_eqn = tf... |
446f06fe8dfb9f0eaf811fd8c2a4c0d38352c6503e8c7fbd0cf28c46ea0fd705 | Python | 1,166 | 35 | from __future__ import absolute_import
import numpy
def outline(labels):
"""Given a label matrix, return a matrix of the outlines of the labeled objects
If a pixel is not zero and has at least one neighbor with a different
value, then it is part of the outline.
"""
output = numpy.zeros(label... |
12c2284d6ab6a5b22b7c1200fa85e12de114aed6472c8cee4f24a3927c839fbe | Python | 1,167 | 38 | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
ls_r2=[]
ls_mae = []
ls_rmse ... |
34f1d966a379aa039f76bf3b76543641bf81443e74690008ae6ac3fcb1d2a499 | Python | 1,168 | 37 | from .._alphanumeric import Alphanumeric
class Name(Alphanumeric):
"""
A setting that provides a named object
"""
def __init__(self, text, group, value="Do not use", *args, **kwargs):
self.__provided_attributes = {"group": group}
kwargs = kwargs.copy()
if "provided_attributes"... |
a3b4bd6f4f18e887c1bcae751ebafe2296afe9b0ee863f658b9c6a172ed893de | Python | 1,170 | 37 |
ALL_AMINO_ACIDS = "all" # tells the forcefield that it should match any amino acid
class ResidueClassCriterium:
def __init__(self, class_name, amino_acid_names, present_atom_names, absent_atom_names):
self.class_name = class_name
self.amino_acid_names = amino_acid_names
sel... |
3520a904c50697754f5d08438e9da6e91957ec2e36801609ac97bc9d07a12016 | Python | 1,173 | 46 | import tensorflow as tf
import numpy as np
from ipdb import set_trace as st
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from ipdb import set_trace as st
import png
import cv2
from skimage.color import rgb2ypbpr, ypbpr2rgb
ch_dim=1
dtype = tf.float32
def apply_std(ycc, std):
ycc_tmp = np.tran... |
e17bf17f7a18cf8c3fe97833df149bdd779860170369f57b84fec6548690fbf9 | Python | 1,173 | 48 | import tensorflow as tf
from .layer import GradientLayer
class PINN:
def __init__(self, network):
self.network = network
self.grads = GradientLayer(self.network)
def build(self):
# equation input: (t, x)
TY_eqn = tf.keras.layers.Input(shape=(2,))
prefactor_eqn = tf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.