sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
6a6e377fcfba891d26c32d5521dc6459cdb2b69e5d9a6725abcf1b4042fd2367
Python
903
32
import os.path import urllib.parse from ..module import Module from ..pipeline import ImagePlane as ImagePlane from ..utilities.pathname import pathname2url class SettingValidation(Module): """A fake module for setting validation""" @staticmethod def get_image_plane_details(modpath): if modpath[...
74f4a5f6ba98a42cc18a0d096118003de530dfba2b73a3f1df4b464745b8761a
Python
903
34
from contextlib import nullcontext from functools import wraps from typing import Callable, Optional, Tuple, Type, TypeVar, Union, overload, ContextManager import torch __all__ = ["LayerType", "PadType", "nullwrap", "disable_compiler"] LayerType = Union[str, Callable, Type[torch.nn.Module]] PadType = Union[str, int...
65b35989098138835b86f88b2b0d22f8758ead1918bd5381a85f8bc7e6614a39
Python
904
31
""" Test enhanced version 4 multi-scale topographic position (e4MSTP) Copyright: 2025 Research Centre of the Slovenian Academy of Sciences and Arts 2025 University of Ljubljana, Faculty of Civil and Geodetic Engineering """ import rvt.default import rvt.blend # Prepare input data for test dem_path = r"c:\test...
6c9dc8608384101aee20637e1ded7c15367522b55c97cad268bffef5d66099c3
Python
904
29
class Grid: def __init__(self): self.x_location_of_lowest_x_spot = None self.y_location_of_lowest_y_spot = None self.x_spacing = None self.y_spacing = None self.rows = None self.columns = None self.vert_lines_x = None self.vert_lines_y = None s...
73c8dd921537a27024675820e9880b0f90bd09c26ffc4af76d5326c1305455c3
Python
904
36
''' adapted from https://github.com/all-umass/ManifoldWarping ''' ''' miscellaneous utilities ''' import numpy import scipy import sys import time from ManinetCluster_python.distance import L2 def pairwise_error(A,B,metric=L2): ''' sum of distances between points in A and B, normalized ''' return metric.pairwis...
93396725dcfca31e37dd3dc9e3e0baaf3cb3f179461faa1f11375d9104e9de81
Python
909
34
from enum import Enum # Decimation Method for Earth Mover's Distance class DecimationMethod(str, Enum): KMEANS = "K Means" SKELETON = "Skeleton" class Feature(str, Enum): F_FACTOR = "Ffactor" PRECISION = "Precision" RECALL = "Recall" TRUE_POS_RATE = "TruePosRate" FALSE_POS_RATE = "FalsePo...
62e4d02ea49ff487192f6c2deba6db5758ac637ef81027d6e2fd5c32cc6a047d
Python
910
32
class SRM: def __init__(self, tau_s, tau_r, v_reset, v_th, v_init=0.0): self.tau_s = tau_s self.tau_r = tau_r self.v_reset = v_reset self.v_th = v_th self.v = v_init self.s = 0.0 self.r = 0.0 self.weight = np.random.normal(loc=0.0, scale=1.0) s...
60f14baca6615ad8ad9883119ffd890428557f5bc7501088cb4cb9e1e6ea5c97
Python
913
33
default_settings = { "lstm1_hidden_units": 512, "lstm2_hidden_units": 256, "lstm3_hidden_units": 128, "trainer": { "checkpoint_path": "../checkpoints/simulation_study", "max_to_keep": 1, "default_lr": 5e-4, "memory": False, }, "local_amortizer_settings": { ...
2574c37d7d49b8fd30031071b507acb44b1e0ca66dc50384480fb7c1e964a2eb
Python
915
36
from sklearn.naive_bayes import GaussianNB from loadDataSet import getDataset from saveClassifiers import saveBayesClasificator; import numpy as np import time X_train, X_test, y_train, y_test = getDataset() gnb = GaussianNB() gnb.fit(X_train, y_train) start = time.time() for i in range(10): y_pred = gnb.predict(...
d751092823bfc0c188786ffc2268524e1c35552f8726255b8a08333286067981
Python
915
23
""" This model defines a custom flatten layer that is used in the model architecture. --- Written by AlexKaz 07/07/19 --- """ import torch.nn as nn class Flatten(nn.Module): """ Class Flatten is a wrapper class for a flattening layer that is necessary in a classification / regression CNN model, right bef...
e7b6ebf6a7949928d7b42a4ca03679235dc28b2a83b87894eefff8870a0f827b
Python
916
36
from traitlets import Bool, Integer, default from mrHARDI.base.application import mrHARDIConfigurable _flags = dict( lsqr=( {'DTIConfiguration': {'use_lsqr': True}}, "Use least-square error" ), prediction=( {'DTIConfiguration': {'predicted_signal': True}}, "Output the reconstructed...
3b8aeec3a667b928b24562483685557dc936c54b9c485e3a1cf856d9b8b13fcf
Python
917
41
# 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 import numpy as np import overlap import pyperf UNIT_HEX = overlap.Hexahedron( np.array( ( ...
fdb70acf29173cdfccd33cae450b755dc0732243c481c197f30dd95aa6d1d0d9
Python
918
27
import torch.nn as nn import torch import math from torch.autograd import Variable class PositionalEncoding(nn.Module): "Implement the PE function." def __init__(self, d_model, dropout, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) # C...
1e8e352b9810a184e93f6e0213a1cd38eddecdb85a12031a89a26279930b01a8
Python
921
32
import tkinter as tk class CreateToolTip(object): ''' create a tooltip for a given widget ''' def __init__(self, widget, text='widget info'): self.widget = widget self.text = text self.widget.bind("<Enter>", self.enter) self.widget.bind("<Leave>", self.close) def enter(self, event=None): x = y = 0 x,...
cf83426ed3f12433b91cf2e9f73430557260c3ce189606a6bc502110a4f852f9
Python
921
36
import warnings from .base import BaseEventReader, BaseRawReader, BaseReader from .binary import BinaryRawReader from .edf import EDFRawReader from .eeg import EEGReader from .events import CMLEventReader from .hdf5 import H5RawReader from .index import JsonIndexReader from .localization import LocReader from .netcdf ...
1bb613b59a40319c5f406a337e11a1b060af86398301f6371e8962c5553bc2ca
Python
922
32
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
f377329d57c2307cc22cc980d76ac16cba789d513258709eda7417a898a1fa6f
Python
922
29
import os from tempfile import mkdtemp from shutil import rmtree import h5py from nose.tools import ok_, eq_ from deeprank.models.variant import PdbVariantSelection, VariantClass from deeprank.targets.variant_class import __compute_target__ from deeprank.models.environment import Environment from deeprank.domain.amin...
ce2e45c5c3163ed2ec60519d6ca69567b6c09614f6d637714fca286c08e7553c
Python
923
36
#!/usr/bin/env python2 import sys,os if len(sys.argv)!=3: print '<gappedpeak file> <track name>' sys.exit() infile,outfile=sys.argv[1:] id=1 fout=open(outfile,'w') with open(infile) as fin: for line in fin: lst=line.rstrip().split('\t') fout.write('{0[0]}\t{0[1]}\t{0[2]}\tscorelst:[{0[12]},{0[13]},{0[14]}],i...
35173cc1ca01388a580c24af98c7d3da179bf71e90c58311d8319a910796ddf1
Python
924
20
from ._end_run import EndRun from ._event import Event, CancelledException, PipelineLoadCancelledException from ._file_walk_ended import FileWalkEnded from ._file_walk_started import FileWalkStarted from ._ipd_load_exception import IPDLoadException from ._load_exception import LoadException from ._module_added import M...
6f12e05a943ebfd700d7a80e6a9b8eb67fd289a9c6d6c866a4c9bc4564ed60c2
Python
926
33
from .datasets import build_transform, build_dataset, get_mnist_data, get_fashion_data, \ get_cifar10_data, get_cifar100_data, get_imnet_data, get_dvsg_data, get_dvsc10_data, \ get_NCALTECH101_data, get_NCARS_data, get_nomni_data from .utils import rescale, dvs_channel_check_expend from .hmdb_dvs import HMDBDV...
3cabb3881a932e608cead626c03cc18ff8858346b68335e9ebb197ba4ff59f20
Python
927
25
from ._range import Range class FloatRange(Range): """A setting that allows only floating point input between two constrained values """ valid_format_text = "%s must be a floating-point number" def __init__(self, text, value=(0, 1), *args, **kwargs): """Initialize an integer range te...
e467587f082a17e0bc47c8a723b31cba6bf181dc6b74a7d42b16ca8158e1229d
Python
928
28
import numpy as np import matplotlib.pyplot as plt interval = 0.001 time = np.arange(0., 1.0, interval) freq = 5. signal = np.sin(time * 2 * np.pi * freq) + np.sin(time * 2 * np.pi * 2 * freq) * 0.4 events = time[(signal > 0.5) & (np.roll(signal, -1) <= 0.5)] fig = plt.figure() fig.set_size_inches(5.5, 2.5) ax = fig....
7438596d28e5533954e1f103484dced65821c02610411a7c9466c8ad5fe687a8
Python
930
49
from .data.utils import ( onehot_seq, pool_anndata, SeqDataset, get_splits, shan_ent, fdr, get_group_name, seq_list_to_conv, align_conv_filters, save_meme, read_meme, to_z, get_activations, create_alignment_df, generate_alignment_graph, plot_alignment_grap...
d86458da5cba8471fdd8206ae24375f6377bb0655927a82f060284377bba33a8
Python
932
25
import numpy as np from scipy.stats import kstest def log_likelihood_normed(dt, mask_spikes, u, r): lent = mask_spikes.shape[0] n_spikes = np.sum(mask_spikes, 0) n_spikes = n_spikes[n_spikes > 0] log_likelihood = np.sum(u[mask_spikes]) - dt * np.sum(r) + np.sum(n_spikes) * np.log(dt) log_likelihoo...
35bb4bc6d20ce1dbfeb96be2ce713e8d2bc83aceb82bba2de82b4ec19cfc1e98
Python
933
33
from traitlets import Integer from mrHARDI.base.application import mrHARDIConfigurable class ParticleFilteringConfiguration(mrHARDIConfigurable): def _validate(self): pass def serialize(self, *args, **kwargs): pass max_crossing = Integer( None, allow_none=True, help="Max...
b2762dd267bb0d6e6914422be96e5a4573afc2be9a3ffb049023665a98c6b8eb
Python
933
40
import torch import csv import numpy as np import matplotlib.pyplot as plt # %matplotlib inline def write_csv(file_name, data): with open(file_name, "w") as f: writer = csv.writer(f) writer.writerows(data) def read_csv(data_file_path): data = [] with open(data_file_path, 'r') ...
164c6c461178abc0d1d0bbd9e9c2689cf07ebf84783444bdc283a4b2f1a270c9
Python
935
33
"""Top-level pytest configuration. Registers the sybil-based documentation-example collector so every ``.. code-block:: python`` block in ``docs/*.rst`` is executed as a pytest case during a normal ``pytest`` run. ``pytest_collect_file`` is a session-wide hook: pytest only consults it for files it actually walks, so ...
a203e67be9278c3f745fea88fb1ec640a918ebaf6a7658643d5ee5189c25a871
Python
935
30
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection class GradCAMElementWise(BaseCAM): def __init__(self, model, target_layers, use_cuda=False, reshape_transform=None): super( GradCAMElementWis...
2d645c7cc46eb668b5719a64b85fe4828588294acf7de67fb8de34dbec76b5e7
Python
937
39
class SettingEditedEvent: """Represents an attempt by the user to edit a setting """ def __init__(self, setting, module, proposed_value, event): self.__module = module self.__setting = setting self.__proposed_value = proposed_value self.__event = event self.__accept...
7ad8000fdfcd6a7d4b724d510c8dd4ba3953a85653af4c6d2b74c072fb44cbd9
Python
937
29
import pathlib import urllib import logging from cellprofiler_core.constants.image import FILE_SCHEME, PASSTHROUGH_SCHEMES from cellprofiler_core.utilities.image import is_file_url LOGGER = logging.getLogger(__name__) def pathname2url(path): """Convert the unicode path to a file: url""" lower_path = path.low...
a3df6304677f7d339fa68d40cf48c6d33e20819bb8c886c3bff5e1605728b5b2
Python
937
25
import torch import torch.nn as nn import torch.nn.functional as f from torch.nn import init class InterpolationLayer(nn.Module): def __init__(self, size=None, scale_factor=None, mode='nearest'): super(InterpolationLayer, self).__init__() self.interp = nn.functional.interpolate self.scale_...
ca0fe2e6da36d8d77d8536a4691c68f542106516161696af2629a397924e371e
Python
938
33
from enum import Enum class Scope(str, Enum): GLOBAL = "Global" ADAPTIVE = "Adaptive" class OtsuMethod(str, Enum): TWO_CLASS = "Two classes" THREE_CLASS = "Three classes" class Method(str, Enum): OTSU = "Otsu" MINIMUM_CROSS_ENTROPY = "Minimum Cross-Entropy" ROBUST_BACKGROUND = "Robust Bac...
c3613c2ed99cbfb1ae7752d33aa0f89992838d036fc4c5092e8f5e6f4c2fb191
Python
939
40
import click from ..__main__ import pass_environment @click.group("pipeline") @pass_environment def command(context): pass @command.command("measurements", help="returns measurements extracted by the pipeline") @pass_environment def measurements(context): pass @command.command("run", help="executes the p...
7e74df65b95621bd6f615cc18e3e0560ab96828aa28844f57106076d94a256be
Python
940
26
import numpy as np class IFSFA: def __init__(self, tau_m, tau_w, a, b, delta_T, v_reset, v_th, v_init=0.0, n_neurons=50): self.tau_m = tau_m self.tau_w = tau_w self.a = a self.b = b self.delta_T = delta_T self.v_reset = v_reset self.v_th = v_th self.v...
c0063309de2dd3f5f45b6f26302827bdf30418dc2b9744e7c00f8b33b6b932e6
Python
942
36
from ._schemas import InputParameters, OutputParameters from argschema import ArgSchemaParser import argparse from . import __version__ class ArgSchemaParserPlus(ArgSchemaParser): def __init__(self,*args,**kwargs): parser = argparse.ArgumentParser() parser.add_argument('--version', action='...
cd48b23c87ee14506c575aa4ab69488db4da089fee052680d0155f9a05d5fb9f
Python
943
27
import torch import torch.nn as nn from collections import OrderedDict class MetaModule(nn.Module): """ Base class for PyTorch meta-learning modules. These modules accept an additional argument `params` in their `forward` method. Notes ----- Objects inherited from `MetaModule` are fully compa...
2b08bf9a1879205ceaedcf7b8bd555a7e015e728dffc933995fc4667df38cf80
Python
945
37
import numpy.testing import skimage.color import skimage.morphology import cellprofiler_core.image import cellprofiler.modules.medialaxis instance = cellprofiler.modules.medialaxis.MedialAxis() def test_run(image, module, image_set, workspace): module.x_name.value = "example" module.y_name.value = "MedialA...
0337035161a6e24bd4b56b51ec242fa7de36c3e953ca76d8ca203962fca7f760
Python
947
35
import torch import torch.nn as nn from models.aggregators import BaseAggregator from models.aggregators.model_utils import GraphTransformerLayer class LAMIL(BaseAggregator): def __init__(self, num_classes): super(BaseAggregator, self).__init__() self.num_classes = num_classes self._fc1 =...
db644bd3fb24a6a9abd9e1f63792ebe592db658b8ba3631f84252b6b8b4f0836
Python
947
27
import torch def fasterrcnn_reshape_transform(x): target_size = x['pool'].size()[-2 : ] activations = [] for key, value in x.items(): activations.append(torch.nn.functional.interpolate(torch.abs(value), target_size, mode='bilinear')) activations = torch.cat(activations, axis=1) return activ...
99001c20097d83f35a5d14b420ef00588ae029f475ed5ed4622acc0885ca35c9
Python
948
38
import tensorflow as tf class GradientLayer(tf.keras.layers.Layer): """ Custom layer to compute 1st and 2nd derivatives for Fick's law of diffusion """ def __init__(self, model, **kwargs): """ Args: model: keras network model. """ self.model = model ...
b2d449e318ab2f671c0acc260e2ab51b9a7dd69796db777a4be366925f3ae83f
Python
948
32
import numpy as np # define SRM model class SRM: def __init__(self, tau_s, tau_r, v_reset, v_th, v_init=0.0, n_neurons=50): self.tau_s = tau_s self.tau_r = tau_r self.v_reset = v_reset self.v_th = v_th self.v = v_init self.n_neurons = n_neurons self.s = np.ze...
90b1c9bf2b91b94a4bee16fd4e4fd1faa1a27bbe2a1fdeeba5db38eec14d4e32
Python
949
30
import numpy as np class IFSFA: def __init__(self, tau_m, tau_w, a, b, delta_T, v_reset, v_th, v_init=0.0): self.tau_m = tau_m self.tau_w = tau_w self.a = a self.b = b self.delta_T = delta_T self.v_reset = v_reset self.v_th = v_th self.v = v_init ...
309d6e7c9190f9981f6164e0ee8e1ff88cfbf1ded2622cb137b313f1b9cd0dac
Python
950
35
from typing import Union import torch import torch.nn.functional as F def get_modelbase_final_layer(final_convolution_layer: str) -> Union[object, None]: """ This function returns the final convolution layer based on the input string. Args: final_convolution_layer (str): The string representing t...
f72ea69064282298a28a3e48bc847509eba9f6de3373f12df62c31db1c130323
Python
950
32
""" ClinicalASL - Clinical Arterial Spin Labeling processing pipeline Main pipeline script for processing ASL MRI data. Repository: https://github.com/JSIERO/ClinicalASL Author: Jeroen Siero Institution: UMC Utrecht (University Medical Center Utrecht), The Netherlands Contact: j.c.w.siero@umcutrecht.nl Description: ...
08542ac9ab9fa28f07b8c0d1f336a74efc367b6f6d9e9dbbc04d303efdb5c459
Python
951
44
""" Command-Line script used to print segmentation information: - number of segments"nsegments - average segment size - minimum segment size - maximum segment size - standard deviation in segment size - average number of segment slices - minimum number of segment slices - maximum number of segment slices - data type -...
98a361738577d432356aaab644793ad568986e8c4ac3f05028fc5d32363a751d
Python
952
19
import pyControl.hardware as _h class Breakout_1_0(_h.Mainboard): def __init__(self): # Inputs and outputs. self.port_1 = _h.Port(DIO_A='X1' , DIO_B='X2', DIO_C='X5', POW_A='Y8', POW_B='Y4', POW_C='Y2', DAC=1, UART=4) # Jumper required to use either DAC/DIO_C or ...
fb268086315e77af15d3adfc6070b86b14e1b0758296aa1beeb7da2cd7700863
Python
952
27
import csv import os # count the number of seqs per gene alignment for each sequence similarity group: groups = ["20","40","60","80","100"] min_seqs = "10" with open("../../output/output_PSICOV/seq_counts.csv", "w", newline='\n', encoding='utf-8') as counts_table: writer = csv.writer(counts_table) writer.writero...
32d7f236a20369c6218bc1687754dea171baa478a0e81993c6ef904492572cfe
Python
954
25
from torchio.transforms.intensity_transform import IntensityTransform from torchio.data.subject import Subject from torchio.data.image import ScalarImage class TemplateNormalizeBase(IntensityTransform): """The Base class to apply template-based normalization techniques. Args: target (str): The target...
4f555b5895b893c655a99c1b63baab5a32ae6bd03d88831730fd27202c0a8211
Python
954
30
import numpy as np # define Izhikevich model class Izhikevich: def __init__(self, a, b, c, d, v_init=-65.0, u_init=0.0): self.a = a self.b = b self.c = c self.d = d self.v = v_init self.u = u_init self.num_ops = 0 # initialize operation counter ...
702a023440957a9533754f9d7debf2883923693c1f29c115d80d4193fd003727
Python
954
39
from ase.db import connect import torch x, pos, y = [], [], [] # 80%的MD steps with connect('../../iso17/reference.db') as conn: # 可以设置select(limit=1)做测试 for row in conn.select(): x.append(torch.tensor(row['numbers'])) pos.append(torch.tensor(row['positions'])) y.append(torch.tensor(row...
ee6505d7873eb21649fac43be2f1ddfd03316bb994419b3156c054f9b0d786ab
Python
956
36
import numpy as np from helper import calcW class Coeff(object): def __init__(self,n,deltaT,Y_grid): self.n = n self.aA = np.zeros(self.n) self.bA = np.zeros(self.n) self.cA = np.zeros(self.n) self.deltaT = deltaT self.Y_grid = Y_grid self.deltaY = Y_grid[1...
d65bc879d1257126ef9c11d7ce832fd7da30b855e9f0f367cd1446f4733989f0
Python
958
37
"""Compatibility shim for the historical SWIG layout. External lab code imports these symbols as:: from ptsa.extensions.circular_stat.circular_stat import ( circ_diff, circ_mean, compute_f_stat, compute_zscores, ... ) In the pybind11 build the compiled module is ``_circular_stat``; this file just re-...
5b1e7fc38aec53ab988b7c5fbc50293475dc272187becaab58c226cd2c9ff8bb
Python
961
35
import numpy as np from utils import save_images, load_ground_truth filenames, _, _ = load_ground_truth("dataset/images.csv") n = len(filenames) def gen_randn_images(): # Gaussian distribution images = np.zeros((n, 299, 299, 3)) for i in range(n): img = np.random.randn(1, 299, 299, 3) img = ...
625befc502f9020cf378fe48ec4d1bb83eeb346c596e4218ff4684be6f115815
Python
964
31
# this script crops the batch simulation list based on the log with succesful completes # Results is to do list with uncompleted simulations folder = 'SDC20221011_invitroCA1pyrs5/' completeInputlist = folder+'runlistopt.csv' completed_log = folder+'wsubrun.pbs.log52028414' with open(completeInputlist,'r') as f: in...
6e35439ae65740fbc5e8a21c21d92a44164f8378e5a6c622fd31545c01fe8188
Python
965
60
class TestFileCollectionDisplay: def test_update_value(self): pass def test_update_ui(self): pass def test_set_update_function(self): pass def test_initialize_tree(self): pass def test_add(self): pass def test_modify(self): pass def test_...
b08f5bbdf71ff015ed4b5284e9bbb298d5e72a3fb0140a6cc83ab1a302362f36
Python
965
38
"""empty message Revision ID: 56d89145adbb Revises: 7b4e00130929 Create Date: 2021-10-13 16:52:58.961413 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "56d89145adbb" down_revision = "7b4e00130929" branch_labels = None depends_on = None def upgrade(): # ...
49657606867340dee3ffeba7112c56bf3f9370a6155c0d7ac05693d646ec5528
Python
967
44
__all__ = ['imread', 'imsave'] from ...util.dtype import convert try: import imread as _imread except ImportError: raise ImportError("Imread could not be found" "Please refer to http://pypi.python.org/pypi/imread/ " "for further instructions.") def imread(fname, d...
4a4ba46f2e71634b73f5e1a07ee3124d453f5ff000824a58d33ecb24619e3494
Python
967
31
"""Tools for working with NIDM-Experiment files""" import click from nidm.experiment.Query import GetMergedGraph from nidm.experiment.tools.click_base import cli # adding click argument parsing @cli.command() @click.option( "--nidm_file_list", "-nl", required=True, help="A comma separated list of NID...
9d209a7891f0d5e2bcc07835202406f64351374abf2c9a7145b419bd66965df9
Python
967
32
#taken from this StackOverflow answer: https://stackoverflow.com/a/39225039#taken import requests def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params = { 'id' : id }, stream = True) t...
00cb1bdab60542f5a833b2a4d8dc1b4ab536210ff74979144748c0b9a5023122
Python
968
32
import json import statistics data = [] with open("datasets/random_clusters.txt") as fp: lines = [line.strip() for line in fp.readlines() if line.strip() != ""] for i in range(0, len(lines), 8): ar = [] for j in range(i, i + 8): ar.append(int(lines[j].split("#match: ")[1])) ...
69d3dc0e835ffbb56ba8046963f740c97b1ad6363c7d8e2e091daf75caa1dfa4
Python
968
34
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 9 17:45:19 2018 @author: Nikolai M Chapochnikov functions to import and preprocess the activity data, like the ORN data, the LN data, the additional odors data, the EC50 etc.. and export them here so that one can immediatly import the hdf5 when o...
26b1dfe9eb45432097789dbe8f45c63ebf2725d73ae2a8f8136ba2545b1ed590
Python
969
27
import sys sys.path.append("../") from api.music_engine_api import EngineAPI import os if __name__=="__main__": musicEngine = EngineAPI() musicEngine.cortexInit() input_path = "../testData/" #--------------------learning process---------------# for composerName in os.listdir(input_path): ...
4b4680f58e689cd4a9cb37b97f48ff352632fc87855cac3c941e66a7aec5e9ad
Python
969
20
import torch from model import UNet, UNet_Pruning from ptflops import get_model_complexity_info in_channels = 3 out_channels = 3 origin_kernel_channels = 64 pruning_kernel_channels = 32 with torch.cuda.device(0): model_origin = UNet(in_channels, out_channels, origin_kernel_channels) model_pruning = UNet_Pruning(i...
0f648173072dd36f8f5fdcf76cc7f0837843be8957b01c55524a55c8036e3fe9
Python
970
31
X_AUTOMATIC_EXTRACTION = "Extract from image file headers" X_MANUAL_EXTRACTION = "Extract from file/folder names" X_IMPORTED_EXTRACTION = "Import from file" X_ALL_EXTRACTION_METHODS = [ X_MANUAL_EXTRACTION, X_IMPORTED_EXTRACTION, ] XM_FILE_NAME = "File name" XM_FOLDER_NAME = "Folder name" DTC_TEXT = "Text" DTC_...
bb2de0b5fbbd7c91f87922f4acdff0c6e13d5e7385b574e8be88e1145e2614d4
Python
973
22
import pytest from pathlib import Path from imctools.io.mcd.mcdparser import McdParser class TestMcdParser: def test_read_invalid_suffix(self): with pytest.raises(FileNotFoundError): McdParser('file.unsupported_suffix') def test_read_imc_mcd(self, raw_path: Path): mcd_file_path =...
460d12d068382f259b41e608e401ee9352961d3f3d413202977c7af0279f3673
Python
974
27
import numpy as np def calc_granger_causality_likelihood_ratio_p(x, maxlag): from scipy import stats from statsmodels.regression.linear_model import OLS from statsmodels.tsa.tsatools import lagmat2ds from statsmodels.tools.tools import add_constant # Taken from statsmodels.tsa.stattools.grangerca...
5b7657df0f8c6af9970fa626c7efecdc15d376c97c98bc070baa48a57f279866
Python
974
29
import numpy as np # define IFSFA model class IFSFA: def __init__(self, tau_m, tau_w, a, b, delta_T, v_reset, v_th, v_init=0.0, n_neurons=50): self.tau_m = tau_m self.tau_w = tau_w self.a = a self.b = b self.delta_T = delta_T self.v_reset = v_reset self.v_th ...
fbc8f282dbb692ed9a9923d767de4065360fa2a9b0d4edf0587d9aa5cb1c7858
Python
974
25
from pydantic import BaseModel, Field, model_validator from typing_extensions import Self, Optional class NestedTraining(BaseModel): stratified: bool = Field( default=False, description="this will perform stratified k-fold cross-validation but only with offline data splitting", ) testing: ...
e165d61a2e8ce2b501d70afa9593244376a59e9823576311363049e889210a86
Python
976
30
import torch from breaststudies.data import BaseDataModule, BreastDataset, BreastDatasetLR, BreastDataset2D, BreastUKADatasetLR class BreastDataModule(BaseDataModule): Dataset = BreastDataset label2rgb = torch.tensor([ [0,0,0], # Background ...
f2ca3490953d0be1abc362b800774c15d695610b2123bdf03d144a0259e13e50
Python
981
36
from nose.tools import eq_, ok_ from deeprank.models.variant import PdbVariantSelection from deeprank.domain.amino_acid import alanine, valine, glutamine, glycine, methionine def test_instance(): pdb_ac = "1AK4" chain_id = "A" residue_number = 10 wt_amino_acid = alanine var_amino_acid = glutamin...
ef70cd23d7ac0b1935959e0e48f116c602b752641ac0cfed0b06ffbf5544359f
Python
985
22
import numpy as np def get_score_n_best_consecutive(selected_results, window, score_col): selected_results = selected_results.groupby('lr').mean().reset_index().sort_values(by='lr') best_idx = 0 best_score = 0 for i in range(len(selected_results) - window): curr_score = selected_results.iloc[i:...
9c6ec1d131affffc083198cdcafcbc6cde06527a3af2a5bf1dab8a08a7fab4bc
Python
988
31
""" ClinicalASL - Clinical Arterial Spin Labeling processing pipeline ASL Look-Locker correction module. Repository: https://github.com/JSIERO/ClinicalASL Author: Jeroen Siero Institution: UMCU (University Medical Center Utrecht), The Netherlands Contact: j.c.w.siero@umcutrecht.nl Description: Little utility fu...
f0ac1af3468a36cfa20e4628fe56014075bead9c4f6747d9d599a482b5d051c0
Python
989
23
import logging def set_log_level(log_level, subprocess=False): """Set the logging package's log level based on command-line options""" try: if log_level.isdigit(): logging.root.setLevel(int(log_level)) else: # str, e.g. str(logging.INFO) -> '20' OR 'INFO' logging.root.se...
3607329380c2bda7b70be193f7a67d956c845aac7c87fe1f583aff10f3d7ce4e
Python
990
22
# -*- 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...
eac8a35f3cbff82d926a09db99c464ce3fb2388077600fb30eb854112794ebb1
Python
990
31
# Copyright (c) OpenMMLab. All rights reserved. # from .eval_hooks import DistEvalHook, EvalHook from .eval_metrics import (accuracy, fuzziness, calculate_confusion_matrix, f1_score, precision, precision_recall_f1, recall, support) from .mean_ap import average_precision, mAP from .multilabel_...
7c89b9b4873d6cf1e1692068ed0def433bbc5729ae76628d0b47d57b4632d83d
Python
992
30
from setuptools import find_packages, setup # requirements = [] # with open("requirements.txt", "r") as f: # for line in f: # requirements.append(line) setup( name="etspredict", version="0.1.0", description="code for edge time series + prediction project", url="https://github.com/juaml/etspr...
e5dd16dc2555f1a4556899fe5a4ff8dbc2232b99572b4062d0663677ee744c0f
Python
992
21
import numpy as np from imctools.io.utils import reshape_long_2_cyx def test_reshape_long_2_cxy(nrow=10, ncol=20): """Tests data reshaping based on some ad hoc test data """ chan_4 = 1 test_longdat = np.array([[i % ncol, int(i / ncol), i, chan_4] for i in range(nrow * ncol)]) img = reshape_long...
ca852870bf8608f5cfb72c56d075f72ebaf99eb0f63093a61ea1d9aca503e6f5
Python
993
36
import os from pathlib import Path from shutil import copytree, rmtree import pytest from click.testing import CliRunner from ..cli import main def test_reproschemaui2redcap(tmpdir): runner = CliRunner() with runner.isolated_filesystem(): # Copy necessary test data into the isolated filesystem ...
7e83d9047b04d6ebd4ac22ec9747a209aeb86f9a01db2f21a20a8a9bf4f7e01d
Python
996
21
from ._medialaxis import medialaxis from ._combineobjects import combineobjects from ._expandorshrinkobjects import expand_or_shrink_objects from ._fillobjects import fillobjects from ._enhanceedges import enhanceedges from ._threshold import threshold from ._closing import closing from ._opening import opening from ._...
95efbe42dbf7273dc3ce4bd315e16bc89233115d2bfecd8b5010f850ba953d5e
Python
997
31
from ..functions.file_processing import save_object_image_crops, save_object_masks def savecroppedobjects( input_objects, save_dir, export_as="masks", input_image=None, file_format="tiff8", nested_save=False, save_names={"input_filename": None, "input_objects_name": None}, volumetric=Fa...
3b48d7542896b7ccccbd686284bff2110a7af48d29b4c2bef2f162a87260003e
Python
1,000
25
# -*- 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...
6e95260b147d10c26e5b4c7c607472e965354629c50d43ebb1e11a394af6c44e
Python
1,000
33
# 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...
9558fe82ad00a05550d4368801bdd0556cbd464178a80ef551e705acb0659812
Python
1,000
44
import skimage.color from ._url_image import URLImage class MonochromeImage(URLImage): """Provide a monochrome image, combining RGB if needed""" def __init__( self, name, url, series, index, channel, rescale_range=None, metadata_rescale=False, ...
c7c76c844711c300faec07e0261588290465306732572061b98184ca8046a320
Python
1,000
56
""" pysteps.utils.arrays ==================== Utility methods for creating and processing arrays. .. autosummary:: :toctree: ../generated/ compute_centred_coord_array """ import numpy as np def compute_centred_coord_array(M, N): """ Compute a 2D coordinate array, where the origin is at the center....
00e27025a325c89f573815c3e39ae93340b38e4d5faa0fe899a97bb5b81dff30
Python
1,002
29
import ot import torch import numpy as np def compute_sq_dist_mat(X_1, X_2): '''Computes the l2 squared cost matrix between two point cloud inputs. Args: X_1: [n, #features] point cloud, tensor X_2: [m, #features] point cloud, tensor Output: [n, m] matrix of the l2 distance between ...
19b183aee85d2774c8f7f5604000c6cf2f4b409ec3f61e8cb7643309780d0b16
Python
1,002
37
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter class LinReLU(torch.nn.Module): __constants__ = ['bias'] def __init__( self, in_features: int, out_features: int, ) -> None: super(LinReLU, self).__init__() ...
816af080aab3654faf45e1f152b62f05b1a38bb3d62348b7052758fb52001fe2
Python
1,003
36
#!/usr/bin/env python from samplebase import SampleBase class GrayscaleBlock(SampleBase): def __init__(self, *args, **kwargs): super(GrayscaleBlock, self).__init__(*args, **kwargs) def run(self): max_brightness = self.matrix.brightness count = 0 c = 255 while (True): ...
83af4323a2f851681ec6f74409b56e3f9051d4b1558200c57f6c23ddc49747e0
Python
1,003
44
"""Datamonger Python reference client.""" from datamonger._api import cite_data, data_info, fetch_artifact, fetch_data, list_data from datamonger._cache_management import cache_clean, cache_info from datamonger._models import ( CacheCleanResult, CacheEntry, CacheInfo, DataInfo, DatasetData, Dat...
5fed7cafa09cf9f876b8d1d065fffa575fabe2e86bf59c72f8308655518e5f34
Python
1,004
37
from ._monochrome_image import MonochromeImage class MaskImage(MonochromeImage): """Provide a boolean image, converting nonzero to True, zero to False if needed""" def __init__(self, name, url, series, index, channel, ...
74ed1f7b95fc71dde4a9a670409d94b7cd6fb116e29c46f7bbfa834d061a62e7
Python
1,004
38
"""empty message Revision ID: eef891c5c783 Revises: Create Date: 2019-11-14 13:59:33.903467 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "eef891c5c783" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
6e9a9b6dd41aa2e88c133044b964477c71d3e7b2487172d79856bdaafdd05fca
Python
1,006
34
import os class ConfigBase(object): RAW_DATA_PATH = "./data/raw/" TRAIN_DATA_FILE = "train.tsv" VALID_DATA_FILE = "valid.tsv" UNSUP_DATA_FILE = "unsup.tsv" SPLIT_RANDOM_SEED = 0 add_vocab_file = "data/add_vocab.txt" class ConfigTripleClassification(ConfigBase): RAW_DATA_FILES = ["UC.xlsx",...
3aab3e05305ea3cb0759ee3a584180fd78f08dbf5a4fa24630a8ea77d4ad0839
Python
1,008
31
import torch def memory_usage(device): """ Check memory usage in pytorch """ print(torch.cuda.get_device_name(device)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(device)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(device)/1024**3,...
c3650daa07d363968909cbb36a84132c6b995622328038ae98155dd77f8a43a8
Python
1,009
38
import tempfile import shutil import os from deeprank.models.metrics import TensorboardBinaryClassificationExporter, OutputExporter test_entries = ["entry0", "entry1"] test_outputs = [[0.0, 0.1], [2.03, -1.0]] test_targets = [1, 0] def test_tensorboard_class_output(): tmp_dir_path = tempfile.mkdtemp() try...
a6226c1c9eacf37ca4507d6bea6aa104df96f236d021505291bb15702b7156f7
Python
1,011
27
# simple blending test import rvt.default import rvt.vis import rvt.blend layers = rvt.blend.BlenderCombination() input_dem_path = r"test_data\TM1_564_146.tif" layers.add_dem_path(dem_path=input_dem_path) output_blend_path = r"test_data\test_blend.tif" dict_arr_res = rvt.default.get_raster_arr(input_dem_path) input_d...
5153279484f82e294b0219d1c99c2410aca56a781ca3f4d33fef1c098bda4d56
Python
1,013
28
import numpy as np import tensorflow.keras.backend as K def categorical_dice_coefficient(class_idx, name): def dice_coef(y_true, y_pred): yt_argmax = K.argmax(y_true) yp_argmax = K.argmax(y_pred) yt_class = K.cast(K.equal(yt_argmax, class_idx), K.floatx()) yp_class = K.cast(...
48cfb0748864ca9c11291abfa2df9481acd5fb3c7d7a49398f0b94c148f901fe
Python
1,015
43
"""Public semantic error taxonomy.""" from datamonger._errors import ( ArtifactIntegrityError, ArtifactSelectionError, ArtifactUnavailableError, CacheError, DatamongerError, DecodedIntegrityError, DecodeError, OfflineError, RegistryError, RegistryIntegrityError, RegistryOffl...
b8c12def84e4cec2630e36fa6036f3f24eae08362ad5fc4233fef81c5449ca79
Python
1,017
32
import os import zipfile import urllib.request import dropbox def download_and_extract(url, target_dir, tmp_name): print("> Downloading segmentations..", flush=True) try: # Remove the zip file os.remove(tmp_name) except: pass try: # Download the segmentat...
d0a077439ea5d4e6fab0dbd380ccdd867c13c7834da450a4fabdb7dd5ed54f14
Python
1,017
33
import json import os.path import random import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.gen import tornado.httpclient from model import CNNPredictionModel, RobertaPredictionModel from handler import IndexHandler from tornado.options import define, options def...
fb00583f1480de543ebbfa8d56f6d61a7a26d455ae77570146a74a861f38587a
Python
1,018
33
from nose.tools import eq_ from deeprank.models.pssm import Pssm from deeprank.models.residue import Residue from deeprank.parse.pssm import parse_pssm def test_parse_old(): with open("test/1AK4/pssm/1AK4.PSSM", 'rt') as f: pssm = parse_pssm(f) eq_(len(pssm), 310) for residue, record in pssm.ite...
5fe3e83fda5459a9bb28c20c0553dcfaaaeb8540d5715611f07d7eeb9eee80f8
Python
1,022
44
import numpy as np import scipy from matplotlib import pyplot as plt def F_function(theta): return np.sqrt(3)/(4.0*np.pi)*np.log((1+theta**(1.0/3.0))**3/(1.0+theta)) + 3.0/(2.0*np.pi)*np.arctan((2.0*theta**(1/3)-1.0)/(np.sqrt(3))) + 1.0/4.0 def calcN_AB(r1,r2,r3): """ r1: radius of disk electrode r...