sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
b4f610785efa6dcc7c0a864fc4bdd9cd546a0f2907c3ed351dd6b4f1a5e10154
Python
1,795
61
import numpy as np from pysteps.noise import fftgenerators from pysteps.tests.helpers import get_precipitation_fields PRECIP = get_precipitation_fields( num_prev_files=0, num_next_files=0, return_raw=False, metadata=False, upscale=2000, ) PRECIP = PRECIP.filled() def test_noise_param_2d_fft_filt...
91acc1a9805b8cac2f6afd477551d8269855dd5526619f40734021469e2740da
Python
1,796
54
import tensorflow as tf class ResidualUnit(tf.keras.layers.Layer): def __init__(self,units,activation='tanh',kernel_initializer='he_normal',**kwagrs): super().__init__(**kwagrs) self.activation = tf.keras.activations.get(activation) self.main_layers = [ tf.keras.layers.Dense(un...
1bfec3167a83455a1117c3abe5b53fa49fc6b5d444b3ab62b7347700e67c0857
Python
1,797
28
def test_filter_spike_trains(): """Test filtering of spike train dict""" import neurodynex3.tools.spike_tools as spike_tools from brian2 import ms from brian2 import ms st0 = [0, 1, 2] * ms st1 = [10, 11] * ms st2 = [2, 3, 4, 5] * ms spike_trains = dict() spike_trains[0] = st0 sp...
b0d655482c2aa399f72dc6e0c4de60df203fc53d575c4721279fd58a486f77ab
Python
1,798
54
import tensorflow as tf class ResidualUnit(tf.keras.layers.Layer): def __init__(self,units,activation='tanh',kernel_initializer='he_normal',**kwagrs): super().__init__(**kwagrs) self.activation = tf.keras.activations.get(activation) self.main_layers = [ tf.keras.layers.Dense(un...
fed92652ddb875feb6b8b97d14c1cddc1a550986d21e9844c5beda4c1f764d57
Python
1,798
59
from __future__ import annotations import json from pathlib import Path import numpy as np import pandas as pd from datamonger import FetchResult, Registry, SparseDataset, fetch_data ROOT = Path(__file__).resolve().parents[3] SELECTOR = ROOT / "registry" / "releases" / "proof-0001" / "selector.json" def _registry...
3a7acb2de757609cb68b3a106063fe7b4d7bb7dd82907e03dbc93a415f4009a4
Python
1,800
39
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import SAINT class WDSAINTModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = SAINT( column_idx=self.hparams.column_idx, ...
583190410e979cdd695c52cbb4d3296d312c305bd2116575916429fb088b75aa
Python
1,800
49
import numpy as np import os.path as osp import scipy.io def roi(list_of_labels): """Mask for the selection of the region of interest in the surface template. Args: list_of_labels (list): list with the file name (.mat) containing the region of interest (from both L and R hemispheres) ...
9c51e7e217698d725a3ef9e94b27cf0315a077b5178b47d45203ea125dba0826
Python
1,802
36
# coding=utf-8 """ ErodeImage module for the CellProfiler library. This module contains the core algorithms for morphological erosion operations. """ from pydantic import validate_call, ConfigDict, Field from typing import Union, Tuple, Annotated from cellprofiler_library.types import ImageAny, StructuringElement fr...
15d09cea7f8b303151307f9d3ace37ae225d853068940d478a8d014d5dd2cf2e
Python
1,806
61
import numpy as np import sys sys.path.append('..') from functions.def_ROIs_EarlyVisualAreas import roi from functions.individual_variability import grab_data def generate_eccentricity_mask(path): """ Generate a mask for eccentricity values between 1 and 8. Args: path (str): path to the data ...
693a4f7c13ce682b860279ecb12da3103d697ac4886420eb25756b998b2b9584
Python
1,806
58
""" tools.py - cpfigure tools that do not depend on WX """ import io import centriole.cpmorphology import imageio import matplotlib import matplotlib.figure import matplotlib.transforms import numpy def figure_to_image(figure, *args, **kwargs): """Convert a figure to a numpy array""" # # Save the figure...
e0cf54864eedd6e66fbdf17cd4f81f38630cb74084cc4ea97cb1becf6f466a4b
Python
1,806
53
# 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...
02ae44d0596c3ceb8f8b43f37e4f2705c32a22efa82033242b8ed19fa27b6a6e
Python
1,809
48
#!/usr/bin/env python # (This is an example similar to an example from the Adafruit fork # to show the similarities. Most important difference currently is, that # this library wants RGB mode.) # # A more complex RGBMatrix example works with the Python Imaging Library, # demonstrating a few graphics primitives and i...
754236f89cef7b78ec8f950aadcd84df0e4e2f99eb71fa306f1f31e6e7ca6067
Python
1,809
90
import numpy import numpy.random import numpy.testing from cellprofiler_core.image import Image class TestImage: def test_multichannel(self): x = numpy.zeros((224, 224, 3), numpy.float32) image = Image(x) assert image.multichannel def test_volumetric(self): x = numpy.zeros(...
17b61d771d83da21e975289039d7db3d2b46f29bc0d501438b551284350f627f
Python
1,810
67
import os from Utils.cal_utils import readfq # 遍历文件夹及其子文件夹中的文件,并存储在一个列表中 # 输入文件夹路径、空文件列表[] # 返回 文件列表Filelist,包含文件名(完整路径) def get_filelist(dir, Filelist): if os.path.isfile(dir): Filelist.append(dir) # # 若只是要返回文件文,使用这个 # Filelist.append(os.path.basename(dir)) elif ...
4d2c676f1dfbf80ae8788694352df0c9beddb4c4f7e14d59ec9cb1fdf2d37726
Python
1,812
42
import numpy as np class HH: def __init__(self, n_neurons=50, v_init=-65.0, n_init=0.3177, m_init=0.0529, h_init=0.5961): self.v = np.full(n_neurons, v_init) self.n = np.full(n_neurons, n_init) self.m = np.full(n_neurons, m_init) self.h = np.full(n_neurons, h_init) self.C = ...
f66741dc5b7b9ae0a402b4dc11e6ecf83cfbfcfb60dd866c74bd6a92bf4aff4a
Python
1,812
37
# coding=utf-8 """ DilateImage module for the CellProfiler library. This module contains the core algorithms for morphological dilation operations. """ from pydantic import validate_call, ConfigDict, Field from typing import Union, Tuple, Annotated from cellprofiler_library.types import ImageAny, StructuringElement ...
de3153b2d0f3cbe42a8c456bfd6cfcecb933dea1519525db8eee14df2a21134c
Python
1,813
63
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_almost_equal from pysteps.tests.helpers import get_precipitation_fields from pysteps.verification import ensscores precip = get_precipitation_fields(num_next_files=10, return_raw=True) np.random.seed(42) # rankhist test_...
b5f1fdd60626771d835fdab862543ca7c7e85154986a741257bd2fe035d579b2
Python
1,814
34
from simulate import SimulationDataset import torch import numpy as np # 设置模拟的次数ns(运行很快,可以设大数值)、force种类sim、节点数目n、时间数目nt sim = 'spring' ns, nt, n, dim = 10, 1000, 10, 2 # 预定义的六种force下的超参数,包括时间间隔dt、时间数目nt、节点数目n和维度dim sim_sets = [{'sim': 'r1', 'dt': [5e-3], 'nt': [1000], 'n': [4, 8], 'dim': [2, 3]}, {'sim': ...
b551697f49289ee32c17367fdfce3cb7dbae1a7d4bdfcdd47f68b82f293d2efb
Python
1,815
66
""" Module that implements watershed functionality as a two stage process where 1. watershed is performed per-slice, in a 2D domain, obtaining the fragments mask 2. watershed is performed at a volume level, in a 3D domain, and uses the previously generated fragments mask """ import numpy as np import waterz import z...
b6fa52713937b95478258b6b9426a36811bc807a2760fc0ffb3f025e6428279c
Python
1,815
62
# -*- 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...
cf68008b34ef4dfa69844b5735674b47288c27d11f9fa9ebef4aa2ba22108af4
Python
1,818
51
# -*- coding: utf-8 -*- """ Created on Fri May 31 15:16:20 2019 @author: Xiaoxuan Jia """ import numpy as np from scipy import signal import matplotlib.pyplot as plt #The periodogram can be efficiently computed using the fast Fourier transform (FFT). # There is a variety of methods, such as Welch and Blackman-Tukey m...
ff168254a13bf4bef8366ea3ad3d9bc3902173b86aaf7785140ba4dd58293429
Python
1,821
50
import centriole.cpmorphology import matplotlib import matplotlib.collections import numpy import scipy.ndimage class OutlineArtist(matplotlib.collections.LineCollection): """An artist that is a plot of the outline around an object This class is here so that we can add and remove artists for certain outl...
80d458f562eaed74524bd2c353549b0acd95a29c52d6e1d9d04ed98632f3c5af
Python
1,822
53
# 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...
e6ee671882d893a1f7af4936f8c6c8dda68c0f23914df9074da537ee32a22119
Python
1,823
68
""" java.py - CellProfiler-specific JVM utilities """ import logging import os import scyjava import cellprofiler_core.preferences LOGGER = logging.getLogger(__name__) def start_java(): """Start CellProfiler's JVM via Javabridge JVM parameters are harvested from preferences and the environment variabl...
4fec66604f3fdb5c291421f91db093007bb993903dfb904bdd3a144a9383c4f6
Python
1,824
56
from typing import Literal import numpy from ..functions.object_processing import ( watershed as library_watershed, ) # Simple wrapper for the object_procceing watershed function def watershed( input_image: numpy.ndarray, mask: numpy.ndarray = None, watershed_method: Literal["distance", "intensity", ...
9906fd5a4cb2a0602b91896e4c29a733dbd305e0da452b93d88d40238444c104
Python
1,828
56
import yaml import pickle import os def recover_config(modelDir: str, outputFile: str) -> bool: """ This function recovers the configuration file from a model directory. Args: modelDir (str): The model directory with the configuration file and the model. outputFile (str): The output file ...
28df700416d81fb6699f5de6a2b23c541565f689fb0da99c78da995ff29337a4
Python
1,829
64
from .._subscriber import Subscriber from ..._validation_error import ValidationError class ListSubscriber(Subscriber): """ Stores name provider names as a list """ def __init__( self, text, group, value=None, can_be_blank=False, blank_text="Leave blank...
c0bd63d55346fa9f08a3ebd1f2360dcdca0ce98f80da12387a12cb18baccf62a
Python
1,829
58
""" DilateObjects ============= **DilateObjects** expands objects based on the structuring element provided. This function is similar to the "Expand" function of **ExpandOrShrinkObjects**, with two major distinctions- 1. **DilateObjects** supports 3D objects, unlike **ExpandOrShrinkObjects**. 2. In **ExpandOrShrinkO...
52d881821ec05ddb9104c907b2fd8bd2eec56b23827da079f2a146355206b243
Python
1,833
31
from pydantic import Field, validate_call, ConfigDict from typing import Annotated, List, Union, Optional from ..opts.colortogray import ImageChannelType from ..types import Image2DColor, Image2DGrayscale from ..functions.image_processing import combine_colortogray, split_hsv, split_rgb, split_multichannel @validate_...
e91a9a4bdbf82de20351ff203c11f886004296fe20df6ab2caea2b163b20c4ff
Python
1,835
57
# -*- coding: utf-8 -*- """ pysteps.tracking.interface =========================== Interface to the tracking module. It returns a callable function for tracking features. .. autosummary:: :toctree: ../generated/ get_method """ from pysteps.tracking import lucaskanade from pysteps.tracking import tdating _t...
b84e85f69b5af25545e8a8ec6e0190c5244dde498c8386533167971630a4cb57
Python
1,836
35
import brian2 as b2 from neurodynex3.brunel_model import LIF_spiking_network print("b2.__version__={}".format(b2.__version__)) def test_LIF_spiking_network(): """Test LIF spiking network: simulate_brunel_network(short pulse, 1ms, default values)""" rate_monitor, spike_monitor, voltage_monitor, idx_monitored_...
ef8ab84ec0158a58210c0813d11ebc2c595af27705d5f891fff63b979b585408
Python
1,838
63
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for metal.py""" from __future__ import print_function from __future__ import unicode_literals from __future__ import division import logging from rdkit import Chem from molvs.metal import MetalDisconnector from molvs.standardize import standardize_smiles loggi...
a3899609c586a676c9875f77dd3149e8817492ba282c3bee0b2230af227b0632
Python
1,839
58
""" ClinicalASL - Clinical Arterial Spin Labeling processing pipeline ASL T1-from-M0 computation 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: This module...
422188337bdf88d4a9ef1b8dada20ddecf6dfb64012953f12bde763b8c7d0954
Python
1,841
48
import numpy as np import os.path as osp import scipy.io def roi(list_of_labels): """Mask for the selection of the region of interest in the surface template. Args: list_of_labels (list): list with file names of visual areas masks ( .mat), from both L and R hemispheres to be merged to...
9a280a42dd6ef52120fce0abdcd4272581af1ccd210c9f516a9c111572b0e5a8
Python
1,844
57
import numpy as np import matplotlib.pyplot as plt import scipy.signal as spsn def butter_lowpass(highcut, fs, order=5): nyq = 0.5 * fs high = highcut / nyq b, a = spsn.butter(order, high, btype='low') return b, a def butter_highpass(lowcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq ...
80f1d68a90c549196a6b227ba1a5302e6eabf8d761779672831598a70b2e2df1
Python
1,845
57
# Inheritaed from open-mmlab/mmclassification # Modified by Hangyu LIN # import json import logging from collections import defaultdict import torch.distributed as dist from .logging import get_logger def get_root_logger(log_file=None, log_level=logging.INFO): """Get root logger. Args: log_file (st...
780392a52f16df1209d5e8dce7dd49fafc0d1c26e32aebc8c53b43d5c32ffe27
Python
1,846
63
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import TDBG import os import re # get the name of the folder cwd2 = os.path.split(os.getcwd())[1] print(str(re.findall("\d+", cwd2))) cwd2int = int("".join(filter(str.isdigit, cwd2))) npzfile = f"temptest{cwd2int}.npz" print(npzfile) # ---------------...
649c1127a3a67c29e1059fdf4a40acf39ab81f2f240ebdfb849d4ef405752cde
Python
1,847
48
import numpy as np import os.path as osp import scipy.io def roi(list_of_labels): """Mask for the selection of the region of interest in the surface template. Args: list_of_labels (list): list with file names of visual areas masks ( .mat), from both L and R hemispheres to be merged to...
6035300e219e36dc25f5801f82fdcefc35951aabf0bc0497750ae02203761174
Python
1,848
31
import tensorflow as tf import config def _parse_function(filename, label): filename = config.DATA_DIR + '/' + filename image_string = tf.read_file(filename) image_decoded = tf.image.decode_jpeg(image_string, channels=3) image_height = tf.shape(image_decoded)[0] image_width = tf.shape(image_decoded...
66b20a49e312a8ae5b2bdfb242284c16bdeb7fee06acc985b84e9cae470a576f
Python
1,850
71
from functools import partial from numpy import (apply_along_axis, diag, eye, flip, isclose, trace, zeros, moveaxis) from numpy.linalg import eigh def vec_to_tens(dt, convention=(0, 1...
0b50e7444f95fd1ced654483504f824c6818cc13bf759a8b08b886f64f12dfba
Python
1,853
59
import numpy as np from scipy import signal from scipy.io import wavfile from load import load_filter def filter_wavfile(wavpath, outwavpath, lfilter_path, rfilter_path): """Apply sensimetrics filters to a WAV file, saving out a filtered version. Parameters ---------- wavpath : str Path t...
3e89c9e5a1d7a0339841b57939c10adb4b746782a96acfa7ce01429811167af9
Python
1,854
50
import dotenv import hydra from omegaconf import DictConfig import pyrootutils # load environment variables from `.env` file if it exists # recursively searches for `.env` in all folders starting from work dir dotenv.load_dotenv(override=True) # project root setup # searches for root indicators in parent dirs, like "...
c388891de832d71aa72257c938300517a6cab0dae935cbcf1fc81d48ce11a001
Python
1,854
48
import os from ._multichoice import MultiChoice from .._validation_error import ValidationError from ..text import Directory class SubdirectoryFilter(MultiChoice): """A setting that indicates which subdirectories should be excluded from an operation The subdirectory filter holds a collection of subdirectori...
05c0e473d3b00972e1fad4c053eccd40b684fe24265d37a7dac43977fe6b5be6
Python
1,857
74
""" Module that implements utility functions: - volume reading wrapper to handle h5 and tiff volumes - volume writing wrapper to handle h5 and tiff volumes """ import os import h5py import imageio import pathlib import numpy as np def ensure_dir(dpath): head, tail = os.path.split(dpath) if not os.path.exis...
228f9e591dc22eb9e9da849995dcbd75fa6c854202f08eb0568a6dd3627980ba
Python
1,857
60
import csv import math import os import sys def get_alignment(lines): alignment = [] seq = "" for line in lines: if ">" in line and len(seq) != 0: alignment.append(seq) seq = "" elif ">" not in line: seq = seq + line if len(seq) != 0: alignment.append(seq) return alignment in...
e7a55093e176410e3bb1ac0f4760be3d1ddd741a28373ce1ebaddfa391ec1d19
Python
1,857
51
#!/usr/bin/python3 def coex(dt, dc, **ka): """Performs co-expression analyses for all gene pairs. Performs parallel computation with multiple processes on the same machine. Model for co-expression between genes i & j: X_i=gamma*X_j+alpha*C+epsilon, epsilon~i.i.d. N(0,sigma**2). Test statistic: conditional...
db35f53d2d43c69ff7ecf44f111421e7c8c7d3d1d0959f91b7f883c7b1780f19
Python
1,858
55
import math import torch import torch.nn as nn import torch.nn.functional as F from modules.clones import clones def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) \ / math.s...
74a6af99c13b70bb7d8adc1b572f3a63fa46d364644ec2d354f10a22257a06a1
Python
1,859
74
#!/usr/bin/env python3 import os import sys from itertools import product import numpy as np from etspredict.job_submission import HTCSubmissionTemplate subjects = list( # np.loadtxt(os.path.join("..", "non_na_subjects.txt"), dtype=str) np.loadtxt(os.path.join("..", "remaining.txt"), dtype=str) ) session...
5a19af8f1ef4ad3de5ce5852581d0b8b4a864671d4816af2fadf46635e812c31
Python
1,861
56
import os from unittest import TestCase from config import ENDOSTROKE_DIR from pathlib import Path import numpy as np import matplotlib.pyplot as plt from .gendostroke import load_nifti, get_files_patient_path, calculate_total class LoadingDataTest(TestCase): def test_load_nifti(self): files = [f for f i...
bfae105a7af11a7f52ec7fcf08e639baa3e2219a7deca41a6f2805cecb0ccc28
Python
1,861
53
from main import run import sys import subprocess import argparse parser = argparse.ArgumentParser() parser.add_argument('--visible_gpus', type=str, default="", help='Determines the CUDA devices visible to ' + 'the script. A string of comma ' + ...
feaa5ea6b868f69bab0dbf614d14fc1018f58992ddedbcff6cc012742bcde46c
Python
1,864
50
from ._multichoice import MultiChoice from ...constants.setting import get_name_provider_choices class SubscriberMultiChoice(MultiChoice): """A multi-choice setting that gets its choices through providers This setting operates similarly to the name subscribers. It gets its choices from the name providers...
6e4b9ada58bb593a933a69a86141f8398432487a440bbc1257fcf50aa2b4711e
Python
1,865
71
# -*- 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...
a21dd11066ca94c01cf7083c687cad1b40e64a9dbd31ead2e72b76d2d4746926
Python
1,866
61
from ._setting import Setting from ._validation_error import ValidationError class Coordinates(Setting): """A setting representing X and Y coordinates on an image """ def __init__(self, text, value=(0, 0), *args, **kwargs): """Initialize an integer range text - helpful text to be display...
9ee137fe5ef27720fb29135a6a414f1824a49acc24e109229dcced6e4ad38d8d
Python
1,869
74
#!/usr/bin/env python3 import os import sys from itertools import product import numpy as np from etspredict.job_submission import HTCSubmissionTemplate subjects = list(np.loadtxt("subjects_hcp_aging.txt", dtype=str)) missing_subs = list(np.loadtxt("missing_subs.txt", dtype=str)) subjects = [x for x in subjects i...
1a102afaec7a8ff839337f0f133b64edb08cf6a7213b4cd0bbfd096671a7c9b7
Python
1,870
74
class Alignment(object): def __init__(self, method, parameters, library_templates, \ statistics = {}, id = 0): self._method = method self._parameters = parameters self._library_templates = library_templates self._statistics = statistics from . import Database as db...
5a73efe81a37dc53a8ed4f9775eb95305a90a6661bbbdfc7eb41080fc93bea5a
Python
1,873
67
from qutip import* import numpy as np from qutip.qip.circuit import QubitCircuit, Gate from qutip.qip.operations import phasegate, rx, gate_sequence_product, cnot, sqrtswap, csign from scipy import optimize,integrate list = [ [[1,3]], [[3,2]], [[2,4]], [[4,6]], [[6,5]] ] ; depth = 6 ; width = 1 ; num_qubit_total = ...
8bf0aa710076ca4836051f2cca617bc7f8e21e1719a7f26f8afd5ca910a8bb3a
Python
1,876
53
"""Smoke tests: the package imports, the quickstart runs, Predict_cord returns the documented output, and Fit_cord is reproducible under a fixed seed.""" import os import subprocess import sys import numpy as np import pandas as pd import scanpy as sc import torch ROOT = os.path.dirname(os.path.dirname(os.path.abspat...
8d4deab72ada045f02b9cc1712af5b5ae05e5362dc70a9826d1305194d94fc32
Python
1,876
60
from multiprocessing import cpu_count from os.path import basename from traitlets import Dict, Float,Integer from mrHARDI.base.application import (mask_arg, mrHARDIBaseApplication, output_prefix_argument, ...
98a6fe0d98562336dff25f071a1b0a5178d9a1bc95b79451ca025166cde5b377
Python
1,876
50
import prov.model as pm from .AcquisitionObject import AcquisitionObject from ..core import Constants class AssessmentObject(AcquisitionObject): """Class for NIDM-Experimenent generic AssessmentAcquisitionObject-Level Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Const...
3e0dca3a828a7a00e9b3f605f86f9d24c9f8e6f781ba1c4cd5a85016e3dd0de2
Python
1,877
70
import json import tensorflow as tf import os import datetime as dt import pandas as pd import numpy as np from lib.regional_data_builder import rescale_df # functions to save and load optimization steps def load_steps(save_dir, optimizer): try: file = open(save_dir+'optimiser_results.json', 'r') ...
69140e81512afd4459edd17a6c55800d8352fa8aca569d827239faaccb6fdc82
Python
1,879
55
import os import os.path as osp from numpy.testing import assert_equal import pytest def get_rhino_root(): """Return where the root directory structure is for data. Works by checking some common places and looking for ``/etc/hostname``. """ data_roots = [ '/', # rhino '/Volumes/rhino...
73daf50d2be2010e99f5f47cbf37c43e00600bb16330be641d6217eefc11f1fb
Python
1,880
60
from typing import Generator from numpy import less_equal, clip from numpy.ma import clump_masked, clump_unmasked, masked_array from mrHARDI.compute.utils import value_closest, value_first def serialize_fsl_args(args_dict, separator="\n", bool_as_flags=False): base_string = "" if bool_as_flags: base...
95c87c90abfc1968f2aa45d7e85e4a80d151eb46d2aa60364329b50073cf2ff0
Python
1,880
92
from enum import Enum from typing import Union import torch class Format(str, Enum): NCHW = 'NCHW' NHWC = 'NHWC' NCL = 'NCL' NLC = 'NLC' FormatT = Union[str, Format] def get_spatial_dim(fmt: FormatT): """Return spatial dimension indices for a given tensor format. Args: fmt: Tenso...
da8358cec77250b812fbe9b5bdf98df1f29a497aa4ed39bc4ec5f6aab088f175
Python
1,880
63
#!/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np import sys import getopt from scipy import signal import researchdata1258 subj = 20 startsec = 60 endsec = False task = False helptext = 'usage: {} -p participant -s startsec -f noiseredfile.tsv -t task -m -h'.format(sys.argv[0]) helptext = helptex...
3ddc026c6c7f96af98321ec052c9b4258ee35514b2dc95ec0610d67b10455735
Python
1,882
50
import dotenv import hydra from omegaconf import DictConfig import pyrootutils # load environment variables from `.env` file if it exists # recursively searches for `.env` in all folders starting from work dir dotenv.load_dotenv(override=True) # project root setup # searches for root indicators in parent dirs, like "...
90c4b7c18e895df0375c34a5ff0541a787e599edb7232e2d5330dfca23586cb3
Python
1,884
55
import pandas as pd import splitter as sp import pair_generation_top as pg import os from sklearn.model_selection import KFold import numpy as np def make_dir(file_name): ouput_path = file_name + '/' try: os.mkdir(ouput_path) except OSError as error: print(error) return ouput_path...
0e12fa21f09a7abf4c73dc3921853cd7e30a6973855046d3fcf914bf4606e3c2
Python
1,886
56
# 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...
40c3325213d3e20ef7ff469d310bcb231c553ea5a1ab36c8afc343f08d4b6f22
Python
1,887
40
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import TabTransformer class WDTabTransformerModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = TabTransformer( column_idx=self.hpa...
9f4d941caeccd190ba7461642fc276eb80996b3085badcc8080c5fb73b2375dd
Python
1,889
49
from cellprofiler_core.preferences import INTENSITY_MODE_LOG from cellprofiler_core.preferences import INTENSITY_MODE_NORMAL from cellprofiler_core.preferences import get_default_colormap from cellprofiler_core.preferences import get_intensity_mode from ._workspace_view_row import WorkspaceViewRow from ..artist import...
712e22bd095229607325d3bf57ed7fd7a4d4215507dcddab06b93bbb096d1f19
Python
1,892
52
# 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...
7070851cef9b3d2a2f75e314fdc459de002c9ceb51beced6499ac6bf545d4196
Python
1,893
55
# -*- 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...
e402b6e596f92f8bc1d82f1e5632aa5cb9ef59c7c05a71dc07b2095e7a410918
Python
1,894
56
import os import argparse import sys import logging import pandas as pd def create_csv(data_path): """This function expects `data_path` to be structured in a certain way: it should contain a list of folders: each one contains a 'image.nii.gz'. """ input_data = [] for subjectID in os.listdir(data_p...
f133d8ed9cd94a78819ea28a652df6f4c6b63f579d3a91b548d6f6888e9e37ce
Python
1,897
56
""" ClinicalASL - Clinical Arterial Spin Labeling processing pipeline ASL control/label interleaving 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: Function for ...
a7848b7a2e1d5e0abd1b2239196e727da969aadd1fcf2f12b42165416da05537
Python
1,899
62
"""Plugin modules - redirect module loads to the user's plugin directory. """ # These examples: # http://blog.dowski.com/2008/07/31/customizing-the-python-import-system/ # http://www.secomputing.co.uk/2009/05/importing-python-packages-in-memory.html # were helpful when writing this code. import glob import imp import...
f472b8d13a4fdc5607dda88d29ac88f5ba85feb95dc080e662b59cfe15dbf98a
Python
1,899
56
import re from .._text import Text from ..._validation_error import ValidationError class Alphanumeric(Text): """A setting for entering text values limited to alphanumeric + _ values This can be used for measurement names, object names, etc. """ def __init__(self, text, value, *args, **kwargs): ...
7775ee35975352960991b8f99562690d27e95d9d5607827326263f521baec955
Python
1,901
74
#!/usr/bin/env python import os import h5py import deeprank.generate def clean_dataset(fname, feature=True, pdb=True, points=True, grid=False): # name of the hdf5 file f5 = h5py.File(fname, 'a') # get the folder names mol_names = f5.keys() for name in mol_names: mol_grp = f5[name] ...
7ea692f8c0dc641d8fd49abcecdedfc465130464a5314bb6a87ad611c88a27a0
Python
1,901
73
import os import subprocess import sys from typing import List from test_utils import PY_PACKAGE, ROOT, cd, print_time, record_time class TypeCheckPaths: """The paths mypy runs on.""" MYPY = ( # core "python-package/", # tests "tests/python/generate_models.py", "tests...
e4106cd9f6a84e424f19f26f13dfd6cd46e649880952eaf6b19114a281627b3d
Python
1,901
47
import importlib from tensorflow.keras.models import Model from tensorflow.keras.layers import Dropout, Dense from tensorflow.keras.optimizers import Adam from utils.losses import earth_movers_distance class Nima: def __init__(self, base_model_name, n_classes=10, learning_rate=0.001, dropout_rate=0, loss=earth_m...
ecfeddf46916ac44fb48e0cec0b2e8d95412251cbd691970ebafe9507095f72b
Python
1,901
54
import numpy as np from numpy import pi,linspace import cmath, random from pylab import * from training_data import * from forward_backward import * def mean_fidelity(X): total_fidelity = 0 ; for i in range(size_train): phiout, _ = forward_th(X, train_psi[i]) ; total_fidelity = total_fidel...
155db5510ec2e12dc0965577dc03afa1dea97aaf1b6d1e7f9f30e6bc384ad8ff
Python
1,903
56
import numpy as np import torch from lib.graph import grid_tensor def reshape_square(x, channels=None): # transform to numpy if isinstance(x, torch.Tensor): x = x.cpu().detach().numpy() N = x.size if channels is None: # assumes that there is just one one channel dimension = N ...
95fdfb73cbb534f6c9d6a9a0ea601696148a896ac8f31f75f0a75124c9c3ab4a
Python
1,903
122
import numpy as np """Uses the data from https://search.r-project.org/CRAN/refmans/GeDS/html/coalMining.html""" coal_mining_data = { "disasters": np.array( [ 5, 4, 1, 0, 4, 3, 4, 0, 6, 3...
6ba8dc635665f354f491637bd7e03c3aba9fe9d574aa791099681755ee016e4c
Python
1,904
63
# -*- 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...
373bab007d8f9909064a1cb1ca0752f09fb4e68ddd471a019cb937065a4a6cee
Python
1,905
54
""" Command-Line script used to clean segmentations produced by the automatic segmentation pipeline. It takes as parameters: 1. the minimum segment size 2. the minimum number of segment slices 3. boolean indicating if relabeling is requested 4. path to output segmentation Then: 1. it removes all segments that are s...
680e22964d64315a3c41e1915fd488e1e0d7833eb7f8f93d98c0d7f1e4568c7c
Python
1,905
63
""" RemoveHoles =========== **RemoveHoles** fills holes smaller than the specified diameter. This module works best on binary and integer-labeled images (i.e., the output of **ConvertObjectsToImage** when the color format is *uint16*). Grayscale and multichannel image data is converted to binary by setting values bel...
dbfe5c91deaeacf571fd3156811078c3b3e00264ce558c6c8d00111be272b6de
Python
1,905
63
""" Step Scheduler Basic step LR schedule with warmup, noise. Hacked together by / Copyright 2020 Ross Wightman """ import math import torch from typing import List, Tuple, Union from .scheduler import Scheduler class StepLRScheduler(Scheduler): """ """ def __init__( self, opt...
4f29b3adbe166e987345676ac36e19f433b7c183b2c165b0c18a584668dc8353
Python
1,906
72
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.testing import assert_array_almost_equal from pysteps.extrapolation.semilagrangian import extrapolate def test_semilagrangian(): """Test semilagrangian extrapolation with number of timesteps.""" # inputs precip = np.zeros((8, 8)) pre...
dcaeaed3d40d601bba212358e59ce992f8cec98031a1072c4410354b3b42d879
Python
1,906
42
import os import torch import random import numpy as np from PIL import Image import torchvision.transforms as transforms import datasets.data_util as data_util from pathlib import Path from DSEC.dataset.provider import DatasetProvider def DSECEvents(dsec_dir, nr_events_data=1, delta_t_per_data=50, nr_events_window...
892d640ccbec9e96157aaf40e235cc6f75d3529a0bf27f8866bde6ce6cdb5f95
Python
1,910
63
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for normalize.py""" from __future__ import print_function from __future__ import unicode_literals from __future__ import division import logging from rdkit import Chem from molvs.normalize import Normalizer logging.basicConfig(level=logging.DEBUG) def normal...
a502f791740f26760def51219d4bcd1f124cc4990d5fd8dd87dbf7cee8857f83
Python
1,916
64
#!/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 ...
f1db5efe271aa869794756e966b0055f977a32f2aad9c22baa6f2ff96158695b
Python
1,917
50
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup if os.path.exists('README.rst'): long_description = open('README.rst').read() else: long_description = '''MolVS is a molecule validation and standardization tool, written in Python using the RDKit chemistry framework. Buildi...
04932f3c4d626654334152c48e7c138913fbf0d8bf764cd45f9460764e6648b1
Python
1,924
63
"""empty message Revision ID: a0928ce2eee6 Revises: 11230bf660dc Create Date: 2021-10-13 16:19:02.318876 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "a0928ce2eee6" down_revision = "11230bf660dc" branch_labels = None depends_on = None def upgrade(): # ...
a41ede3e4230e62a908b46bc32e8e791ea94380e826a4ce81d0bfc260d15cefc
Python
1,925
55
from __future__ import annotations from dataclasses import dataclass from typing import Optional import pytest from nidm.experiment.tools.rest import RestParser from nidm.util import urlretrieve from ..conftest import BrainVol @dataclass class OpenNeuro: files: list[str] project_uri: str @pytest.fixture(sco...
554243b59245528689fc5b0193fecf126aca68637b8905495f06b457ad040451
Python
1,926
55
""" alignReads """ import subprocess import os import logging logger = logging.getLogger('root') logger.propagate = False def alignReads(cores, BWA_path, genome_path, read1, read2, outfile): sample_name = os.path.basename(outfile).split('.')[0] output_folder = os.path.dirname(outfile) if not os.path.ex...
dab3066a7f21b276062a2c4111a87001dabff5aa7070199da9dd213e79fd7712
Python
1,926
47
import torch from torch.utils.data import Sampler from torch._six import int_classes as _int_classes class SequentialSubsetSampler(Sampler): """Samples elements sequentially given a list of indices, Arguments: indices (sequence): a sequence of indices """ def __init__(self, indices): ...
9c539bfa249e1e85689b0561f21297e1cbf1753e83b4784f2dc566fd06f4329a
Python
1,927
48
import itertools import json import warnings from pathlib import Path from typing import Union import pandas as pd from .base import BaseReader class LocReader(BaseReader): """ Reads a localization file ("localization.json") and returns the data it contains as a flat DataFrame. Nested fields in the JSON...
791d5219c84a7d2e8d78d319883b04497f9dceed9108eac642b19c9b05fe3fde
Python
1,930
41
from src.models.tabular.widedeep.base import WDBaseModel from pytorch_widedeep.models import TabFastFormer class WDTabFastFormerModel(WDBaseModel): def __init__(self, **kwargs): super().__init__(**kwargs) def build_network(self): self.model = TabFastFormer( column_idx=self.hparam...
1465f07331cc8b623fe0fb26352f786eaf00a375c93417b8edc88707a1a26551
Python
1,933
57
# -*- 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...
a40aa841e6f457e7ae9651f03fb7b6777fc7ef5c15430db7e9c87ca63ba9bcbe
Python
1,933
82
import pdb import torch import torch.nn as nn class BaseForwardModel(nn.Module): def __init__( self, ): super(BaseForwardModel, self).__init__() pass def forward( self, num_samples: int, pars: torch.Tensor, ): pass class ...
52affcf82aeb034e597fb025b86e3626856821d27097d73ac899ede241a7db8f
Python
1,935
50
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 13 15:50:27 2018 @author: saskiad snippet from nicain """ from allensdk.brain_observatory.locally_sparse_noise import LocallySparseNoise as LocallySparseNoiseBase from allensdk.core.brain_observatory_cache import BrainObservatoryCache import allen...
aec2fc5e014f89dbb634c080b51648761cf23259b9ba4b8ae43b360e740e309c
Python
1,937
64
#!/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 ...