sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
8e4428fcd080122fb79a2ae594558ddf99fa8c7680c44a2a48c9ff646cae6162
Python
1,174
32
# -*- 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...
a41d9c19d4a3950479ef7e66a6be2273ce1bc0a18d52dcff8a6abb1408eca607
Python
1,174
38
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches time = np.arange(0., 3.0, 0.001) stim = np.ones(time.shape) duration = 0.25 intervals = np.arange(0.25, 5., duration * 3) base_freq = 5 for i, interval in enumerate(intervals): stim[(time >= interval) & (time < interval + dura...
d65cda1eef8e68e6b6ee2296db936abfb25edb9ed8355673406244b9611f3f0a
Python
1,174
34
""" Misc utils Hacked together by / Copyright 2020 Ross Wightman """ import argparse import ast import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, nam...
68694f51b56b1a9e45b7007c6985d3e903ce48b1ce1482f4185cfe0fb9fcc391
Python
1,175
48
from qtpy.QtWidgets import QMessageBox import numpy as np def safe_toarray(tab): """ Returns an ndarray from a ndarray or a sparse matrix """ if not isinstance(tab, np.ndarray): return tab.toarray() else: return tab def error_json_format(show=True): """ Print a message er...
bd45841d857810ef2e2c28f3e9a9d84c69e116bbc36a0d7fb32b35a6f9580b3b
Python
1,176
35
import prov.model as pm from ..core import Constants from ..experiment.Core import Core, getUUID class ProcessSpecification(pm.ProvEntity, Core): """Class for NIDM-Workflow Process Objects. Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py. Additional alternate con...
0f0eee65710765e283c0349cbf2a82211cc3d8e0e3a64c8f94c08a7d530e833f
Python
1,178
40
import torch.nn as nn from modules.clones import clones from modules.sublayer_connection import SublayerConnection from modules.layer_norm import LayerNorm class EncoderLayer(nn.Module): "Encoder is made up of self-attn and feed forward (defined below)" def __init__(self, size, self_attn, feed_forward, dropo...
28d9bb7d98c5cde6862dc23f778cabb3e0ede0a548050c7aa05a40562aa7a093
Python
1,181
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) TW_eqn = tf.keras.layers.Input(shape=(2,)) prefactor_eqn = tf...
a0739379af63f9ec3d9587e02d4951ec9162a45a403b4212e5fcccc5223cd147
Python
1,183
37
""" Command-Line script used to compute ARI (Adapted Rand-Index) error for input segmentations It takes as parameters: 1. paths to segmentations to evaluate 2. path to ground truth segmentation 3. path to output file where results will be stored Then: 1. opens the input segmentations and the ground truth segmentati...
5f571d62510521bf07fce13e7f7b7a25a2ff0e0bce5cfa1b566119d594d15123
Python
1,186
22
import subprocess import os def filterBackgroundSites(bedtools_path, sample_path, control_path, outfile): output_folder = os.path.dirname(outfile) if not os.path.exists(output_folder): os.makedirs(output_folder) sample_noHeader = os.path.join(os.path.dirname(sample_path), 'sample_noHeader.txt') ...
6a672a6a0fbccbe14cfe891baad0b69f8c9522a567ecf742817fedef7b591316
Python
1,186
45
import sys import json import pandas import gemmi csv_in, json_out = sys.argv[1:] df = pandas.read_csv(csv_in) ret = {} for x in df.to_dict(orient="records"): metal = gemmi.Element(x["Metal"]).name ligand = gemmi.Element(x["Ligand"]).name l = ret.setdefault(metal, {}).setdefault(ligand, []) modes = [] ...
52f709eb970f6eea707f77cab93839edfd2dc8ac3bf11f2541ee4ff79d5d7160
Python
1,188
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...
389ef657eeee8fb63fe503393ee5fbf0890dd882e4cd6b09e7430969735e7fb5
Python
1,192
42
import os import subprocess try: from importlib.metadata import PackageNotFoundError, version except ImportError: # pragma: no cover from importlib_metadata import PackageNotFoundError, version # type: ignore def _get_version_from_git() -> str: """Derive the package version from git tags when package m...
5052dd885a61ac3a716a0ceefc4a73374420d2ea051eb11ba32c97d067974078
Python
1,193
65
# Copyright (C) 2026 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_TET_VERTICES = np.array( ( (-np.sqrt(3)...
ff5e1654322186daa98543790d42c9f48cef00b6a78665a213cac4e41afadd25
Python
1,194
37
import tempfile import os import h5py import numpy from deeprank.domain.amino_acid import alanine, serine from deeprank.features.dbnsfp import __compute_feature__, REVELSCORE_FEATURE_NAME from deeprank.models.environment import Environment from deeprank.models.variant import PdbVariantSelection def test_dbnsfp(): ...
9c39ebf516430d1b8bbc24ec990ef21c70983e846773e7bc9e7de45699bc89e6
Python
1,196
37
import os import sys import types from ..preferences import get_plugin_directory class PluginImporter(object): def find_module(self, fullname, path=None): if not fullname.startswith("cellprofiler.modules.plugins"): return None prefix, modname = fullname.rsplit(".", 1) if prefi...
b067e6877d746ebe4010679615274d4e15ab9d5d804a1055b1e244ed4e43944a
Python
1,198
55
import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, out_dim=10, in_channel=1, img_sz=28, hidden_dim=256): super(MLP, self).__init__() self.in_dim = in_channel*img_sz*img_sz self.linear = nn.Sequential( nn.Linear(self.in_dim, hidden_dim), #nn...
53dfb88b33afa1c789babe361ef7d40bc9a5268fbfd975a0e5718762213b839f
Python
1,200
51
class FASTQ_File(object): def __init__(self, name, id = None): from . import Database as db self._name = FASTQ_File.clean_FASTQ_file_name(name) self._reverse_complement = False if id == None: db.add_FASTQ_file(self) else: self._id = id @prope...
cb1c89054649c319a00b4a92eb1bad6ada9275f83e3db5ea8e7a4dc47f155e17
Python
1,201
47
import json import os.path import pytest from jsonschema.exceptions import ValidationError from imskaper.validations import validate_config as validate # import validations.validate_config as validate path = os.path.join( "tests", "test_config.json" ) with open(path) as config_file: config = json.load(confi...
c30f29581abaaff0d8c1ef031cb64cda83d79893885302a8944350ff8c9d2b3a
Python
1,202
39
# -*- coding: utf-8 -*- """ Add Conv Block for MSDNet """ def add_conv_block( Conv, BatchNorm, in_channels=1, out_channels=1, kernel_size=3, dilation=1, last=False, ): """ Adds a convolution block to a neural network. A convolution block consists of a convolutional layer and a batc...
7cce68c9a881b9321a97c04aefe3d577a1739cf616a7b757e1289dcb64aaacdc
Python
1,204
31
import cv2 import numpy as np def overlay_map(image, gradmap, rescale_max=None, split_signs=False): image = np.squeeze(image) image = (image - np.min(image)) / (np.max(image) - np.min(image)) image = (image * 255).astype(np.uint8) image = np.dstack([image, image, image]) gradmap = np.squeeze(grad...
9b549655cfbc8e545f821e77a5a92d7b6f5e030df18e0a0f5abe84c94ed39854
Python
1,204
32
import csv import math import os import sys # extracting the secondary structure from the STRIDE output files. input_path = "../../data/PSICOV/secondary_structure/" #input multiple sequence aligments path output_path = "../../output/output_PSICOV/second_struc.csv" #list of STRIDE files: protein_list = os.listdir(in...
1784e633118a69cd6e69054e1d9ee8d7dd1cb792efbaca1a89974718dd97c97a
Python
1,206
47
from loadDataSet import importLabels def getClass (classLine): clas = classLine.split(': ')[-1].replace('\n', '') return clas labels = importLabels() start = 1500 fileLog = 'serial-20230126-091049.log' fileRes = 'STMResults.csv' flog = open(fileLog, 'r') fres = open(fileRes, 'w') fres.write("Correct label, ...
7f7e2666122366482b93b9775a68a713c81e19b5b735a1e3bfaaca80dddcb187
Python
1,207
33
import torch as th from torch import nn import torch.nn.functional as F from torch.autograd import Variable from depthwise import DepthwiseNet from torch.nn.utils import weight_norm import numpy as np class ADDSTCN(nn.Module): def __init__(self, target, input_size, num_levels, kernel_size, cuda, dilation_...
bb0ac02f2cb8a7c8746bca7e3525386d1ad1f07472913f4968c5da1c5df1eafc
Python
1,207
57
from attr import dataclass @dataclass class AEMetricLogger: recon_loss: float = 0 latent_loss: float = 0 counter: int = 0 def update( self, recon_loss: float, latent_loss: float, ) -> None: self.recon_loss += recon_loss self.latent_loss += latent_lo...
82aa03b851b4f62cf879efc431e05fc7e6a434eba0e00bd8969620c84dfc817a
Python
1,212
47
import pandas as pd from rdkit import Chem from rdkit import DataStructs import matplotlib.pyplot as plt import molvs as mv from rdkit.Chem import RDKFingerprint import numpy as np from tqdm import tqdm import os from multiprocessing import Pool, cpu_count import math import time import itertools import datetime from ...
5a314bcf58cfa8d88131dac97999fa82ed1896f023fda3ce17b380634ae60cd9
Python
1,214
39
#!/usr/bin/env python from samplebase import SampleBase import time class GrayscaleBlock(SampleBase): def __init__(self, *args, **kwargs): super(GrayscaleBlock, self).__init__(*args, **kwargs) def run(self): sub_blocks = 16 width = self.matrix.width height = self.matrix.height...
0b6d87a80104c2e5ec7bbc00223c31176e22ceceff60266ce2f6ecdebbc9df81
Python
1,215
38
from __future__ import annotations from dataclasses import InitVar, dataclass, field from pathlib import Path from types import TracebackType from typing import IO, Any, Optional @dataclass class Reporter: output: Optional[IO[str]] = field(init=False) output_file: InitVar[str | Path | None] def __post_in...
25c11d88ef7c8628ffc98c0aef4482367934dd5280cf295a6f6e4eb7f7a7f086
Python
1,217
41
import os.path import weakref import importlib.resources images = os.path.join("data", "images") resources = str(importlib.resources.files("cellprofiler").joinpath(images)) image_cache = weakref.WeakValueDictionary() app = None def get_builtin_image(name): import wx # If we're not running in a GUI enviro...
c8d73046df9d47102dbdb9ba349e2af6bd1a28ff21ffd638492255ceadfcf497
Python
1,220
35
import numpy as np import numpy_groupies as npg from .form_feature_extraction import FormFeatureExtraction def extract_features(segmentation, image, form_features=None): features = FormFeatureExtraction(segmentation).get_features(form_features) group_idx = segmentation.flatten() # Prepend mean color to...
23e205eb4a9550856f3fae32f0de174f2081d1d67df5b4c747884d4d280975ce
Python
1,221
35
from .adabelief import AdaBelief from .adafactor import Adafactor from .adafactor_bv import AdafactorBigVision from .adahessian import Adahessian from .adamp import AdamP from .adamw import AdamWLegacy from .adan import Adan from .adopt import Adopt from .lamb import Lamb from .laprop import LaProp from .lars import La...
2f9fe066d40a76bb2f536aa5209ac42fe2dab77f65fafb151e390d12a7526cba
Python
1,221
37
import prov.model as pm from .Acquisition import Acquisition from ..core import Constants class AssessmentAcquisition(Acquisition): """ Default constructor, creates a session activity and links to project object :param session: a session object """ # constructor def __init__(self, session, ...
4c0e3511ab41bb0019e0385f4e7abcb09273c5da2ff5f04dfe3ee0f61bcc25ea
Python
1,221
55
import os import pathlib import click import cellprofiler_core.commands CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX") class Command(click.MultiCommand): def get_command(self, context, name): try: name = f"cellprofiler_core.commands._{name}_command" imported_module = __i...
da36ac40c2cdee6b5b996e82cec4dc1bfe369bb453338792c9ed5efd396dd53d
Python
1,226
24
# -*- 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...
e28e45e009ecf06a8e48ed7650d2e61d2f70698a8277dcc43bb0f7d9a2847a8c
Python
1,226
38
from ...external.tifffile import TiffFile, imsave, parse_kwargs def imread(fname, dtype=None, **kwargs): """Load a tiff image from file. Parameters ---------- fname : str or file File name or file-like-object. dtype : numpy dtype object or string specifier Specifies data type of arr...
8b2d60e8436174f2bf6af85cba0cdac0badba9abf72f68c3d0a6fd0d4e73a997
Python
1,227
44
import torch import torch.nn as nn class LeNet(nn.Module): def __init__(self, out_dim=10, in_channel=1, img_sz=32): super(LeNet, self).__init__() feat_map_sz = img_sz//4 self.n_feat = 50 * feat_map_sz * feat_map_sz self.conv = nn.Sequential( nn.Conv2d(in_channel, 20, 5...
6ed22966d9eb6c97dc09902a7a300b976b3c69639afa8cb755c2b4a5ef8622af
Python
1,228
28
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import gzip import os import scipy.io import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--directoryPath", dest="dir", help="Directory path for files to convert from 10x to a gene expression matrix",type=str) arg...
e3e8cebf9a38f0852103d6d45dd72d6a58dbf102c13a1ff1c6ccf051e025d3fe
Python
1,229
45
import collections class TrieNode: # Initialize your data structure here. def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): current = self.ro...
256ae172d0e23969ab21f3a97b631bbff0fe847dbda396f5ace878b5d8b18a9e
Python
1,230
33
""" Visualize the sampling volume, 2D or 3D. Read the data from the folder given as a parameter. If the output folder given as a second parameter, also save the images there. """ import sys import numpy as np from mayavi import mlab from megsimutils import read_opt_res from megsimutils.viz import _plot_anatomy, _plot_...
257f0cf0d0b25a641ed4f5eeef83ad8f78c2207946781003277284bae0d9f824
Python
1,233
24
import glob import cv2 as cv import numpy as np from models.epu import EPUNet from models.subnetworks import Subnet from tensorflow.keras.metrics import AUC test = [cv.imread(img) for img in glob.glob("../data/banapple/test/*.jpg")] labels = np.asarray([1 if "apple" in img.split("/")[-1] else 0 for img in gl...
6c3fafad3f000ccf53a7f6f62395cc4412700a0d1a71faf87f2c35353207b704
Python
1,233
30
import pandas as pd def reshape_to_multicolumn(data: pd.DataFrame) -> pd.DataFrame: """Split column names like `fast_030` into one level `fast` and an additional level `030`.""" cols = data.columns.get_level_values(level=0) cols_paradigms = [] cols_configurations = [] for col in cols: if no...
7148a66f1fa7da31d6ed22fa1296279b7edc368ec7329156a944b92ae04b6fd5
Python
1,234
52
""" Command-Line script used to preprocess input datasets It takes as parameters: 1. path to input dataset 2. path to output dataset Then: 1. opens the input dataset 2. stretches intensity values to span the [0,1] range 3. converts to 8-bit format 4. stores output dataset in specified path """ import h5py import i...
438ae8af4b19d09342fe5f4b7b3cb53eea1f3b6af722e0e85b813ee0176b960d
Python
1,235
40
import pdb import torch from DT_for_WDN_leak_localization.inference.noise import ObservationNoise from DT_for_WDN_leak_localization.inference.observation import ObservationModel from DT_for_WDN_leak_localization.network import WDN from DT_for_WDN_leak_localization.preprocess import Preprocessor class TrueData(): d...
edb7e4033b90f71421730c0bff398ed0ea95c6ad5fd582346a3a2b9fe09f6db7
Python
1,235
31
from ._workspace_view_row import WorkspaceViewRow from ..artist import MODE_HIDE from ..artist import MODE_LINES from ..artist import MaskData from ..utilities.workspace_view import bind_data_class class WorkspaceViewMaskRow(WorkspaceViewRow): """A row of controls for controlling masks""" def __init__(self, ...
d0db8907f3dc6da0b72212a90a4fd70ea32da4179e7066c9478a20410e0d865c
Python
1,237
40
import torch import torch.nn.functional as F from torch.nn.parameter import Parameter class ExU(torch.nn.Module): def __init__( self, in_features: int, out_features: int, ) -> None: super(ExU, self).__init__() self.in_features = in_features self.out_features = ...
a2f59a1891159d84cc30fb17f5477f837e24883cbce0236d0d1176d37527ef21
Python
1,238
23
import os import argparse parser = argparse.ArgumentParser( prog='PolyA_comparison', description='Execute circRNA-sponging pipeline in parallel for totalRNA and reference PolyA data to determine false positive circRNA detection rates') parser.add_argument('-p', '--polyA', help='...
9537d028d9697587ae50f1a70c30b5c75b46c66fd8ad721664991b8651da7604
Python
1,239
40
import torch import torch.nn as nn import torch.nn.functional as F class FocalLoss(nn.Module): def __init__(self, classes, alpha=None, gamma=2, size_average=True, device=None): super(FocalLoss, self).__init__() if...
fc5cf8dcc78fc4f1abed4f9790cd7eb6fbd47974a7e8bfc6cb54ee58eee8b5eb
Python
1,239
39
from ._setting import Setting class HiddenCount(Setting): """A setting meant only for saving an item count The HiddenCount setting should never be in the visible settings. It should be tied to a sequence variable which gives the number of items which is the value for this variable. """ def _...
2747c48e101b875e88102866ff7867078addbf2195117ba5b89e9d1000ca2dc0
Python
1,240
31
# -*- 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...
0110252118dd71bd31c7cbeb5a3fdcca97f57073433bb35c8193677aae80b413
Python
1,242
34
from unittest import TestCase import numpy as np from numpy.testing import assert_equal from .form_feature_selection import FormFeatureSelection from ..datasets import MNIST from .algorithm import slic_fixed data = MNIST('data/mnist') slic = slic_fixed(num_segments=100, compactness=5, max_iterations=10) class Form...
3120889c17a4adbc76b29910e7ae5fad3339e494eab56100e9c3cdc0dfad07ea
Python
1,242
47
class Conf(): ''' classdocs ''' def __init__(self, neutype="LIF", task="MusicLearning", dt=0.1): ''' Constructor ''' self.neuron_type = neutype self.task = task self.dt = dt self.notesMap = {} self.GenreMap = {} self.RunTimeState =...
f40fb037a4d0aeb964027677999332f85200bac939191810b3cbbe82950d545b
Python
1,246
67
from sc3D import SpatialOmicArray import numpy as np em = SpatialOmicArray("data/data_test.h5ad", store_anndata=True) em2 = SpatialOmicArray( "data/DLPFC.h5ad", tissue_id="layer_guess", pos_id="spatial", array_id="z", z_space=30, store_anndata=True, ) def test_sc3D(): assert len(em.all_c...
89a15c1b57f57cae5d63744240366db1aed6d74a64a9e02cabfe0e5dd88d0c02
Python
1,247
40
from unittest import TestCase import time from .queue import PreprocessQueue from .mnist import MNIST from ..pipeline import preprocess_pipeline_fixed from ..segmentation import slic_fixed, extract_features_fixed data = MNIST('data/mnist') segmentation_algorithm = slic_fixed( num_segments=100, compactness=5, max_...
121c4207ffd0ba28c05ce4cfc8f22db3768fd505b7be01f3141afe6a50d01bdd
Python
1,250
33
#!/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 ...
22cb1a61afba87fb1ad81fb4188079b3385f1e3633bb5768f3f5661cbdd0f91d
Python
1,251
36
import cv2 import matplotlib as mpl import matplotlib.cm as cm import numpy as np def disp_img_to_rgb_img(disp_array: np.ndarray): disp_pixels = np.argwhere(disp_array > 0) u_indices = disp_pixels[:, 1] v_indices = disp_pixels[:, 0] disp = disp_array[v_indices, u_indices] max_disp = 80 norm =...
345ae8ff14cad96e92a853aa1b9f1e484da8d6acf9b258aadbdbd3a2e119e161
Python
1,251
44
import csv import os from pathlib import Path from shutil import copytree, rmtree import pytest from click.testing import CliRunner from ..cli import main def test_reproschema2redcap(tmpdir): runner = CliRunner() with runner.isolated_filesystem(): # Copy necessary test data into the isolated filesy...
5c2300778fc8cd52b350d3e44188b0e6a3119a988dcf581fc8fc8a9c4adbd806
Python
1,253
32
import random from itertools import combinations from torch.utils.data.sampler import SequentialSampler, RandomSampler from torchmeta.utils.data.dataset import CombinationMetaDataset __all__ = ['CombinationSequentialSampler', 'CombinationRandomSampler'] class CombinationSequentialSampler(SequentialSampler): def...
ecdd505974d3fe6afff737c83ac7f769c5bd847ea9398d2d9bbc0b471894cf8c
Python
1,253
42
import re from deeprank.models.forcefield.top import TopRowObject class TopParser: VAR_PATTERN = re.compile(r"([^\s]+)\s*=\s*([^\s\(\)]+|\(.*\))") LINE_PATTERN = re.compile( r"^([A-Z0-9]{3})\s+atom\s+([A-Z0-9]{1,4})\s+(.+)\s+end\s*(\s+\!\s+[ _A-Za-z0-9]+)?$") NUMBER_PATTERN = re.compile(r"\-?[0-...
0650f00c0b8f087d0e7f2aef09519556e520f72a5223c113e507f71767f97704
Python
1,254
45
# 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 pathlib import subprocess import sys import tempfile import pyperf def main() -> None: bench...
1c1b275d404f9a841964722b5811382f68ad44874e683ea6129a9fcc2f241439
Python
1,256
24
import multiprocessing if __name__ == "__main__": # important to enable freeze_support when creating an executable (i.e. via pyinstaller): # https://docs.python.org/3.9/library/multiprocessing.html#multiprocessing.freeze_support # # allows multiprocessing on Windows after freeze: # https://github.c...
d1f426c453e8c9e64016dcb6fb9b5d2a9bc57a4c46b206f6201f49c1747fe4f8
Python
1,256
46
import numpy as np import matplotlib.pyplot as plt # Define parameters dt = 0.1 # time step t = np.arange(0, 100, dt) # time vector tau = 10 # membrane time constant Rm = 1 # membrane resistance Vth = 1 # spike threshold Vreset = 0 # reset potential V0 = 0.5 # initial potential g_leak = 0.1 # leak conductance ...
f556d8fee881732e0700c0f9c24c32e7e1a68374cf314613eef2847036bf451e
Python
1,256
63
#!/usr/bin/env python2 import sys,glob,gzip,os # axt format: http://genome.ucsc.edu/goldenPath/help/axt.html if len(sys.argv)!=3: print '<chr size file> <output file> Run under the dir of gzipped Axt files, presumably one for each target chr but that doesn\'t matter' sys.exit() chrsize={} with open(sys.argv[1]) a...
29ad2a5b7a5d415d5d924e78faadd29d5126eee47baf8cc084a12189ede841df
Python
1,258
40
import numpy as np def diag_indices(n, k=0): rows, cols = np.diag_indices(n) if k < 0: return rows[-k:], cols[:k] elif k > 0: return rows[:-k], cols[k:] else: return rows, cols def unband_matrix(banded_matrix, symmetric=True, lower=True): """ Assumes banded_matrix...
5efb2dbba3fd26e4bee3bd6c909a67bb07f7e7bef25694f94b7edc9d9949c227
Python
1,259
44
import os.path as osp import pytest from ptsa.extensions.edf import EDFFile @pytest.fixture def edffile(): """Using a section of EEG data obtained from https://www.teuniz.net/edf_bdf_testfiles/ """ here = osp.realpath(osp.dirname(__file__)) fname = osp.join(here, 'data', 'eeg.edf') edf = EDF...
468a35f61ee8cb5c19598a2d678ee8faf0a6e95ca7fc2a45db7f123abea6d2f1
Python
1,260
46
import numpy as np import matplotlib.pyplot as plt # Define parameters dt = 0.1 # time step t = np.arange(0, 100, dt) # time vector tau = 10 # membrane time constant Rm = 1 # membrane resistance Vth = 1 # spike threshold Vreset = 0 # reset potential V0 = 0.5 # initial potential g_leak = 0.1 # leak conductance ...
bdbeea0d33db2708149479620a1f621837557522ac98e2659e934b855a42f56f
Python
1,260
45
import json class HeadlessConfiguration: """ This class functions as a configuration set for headless runs. The default config class is wx-based, which means we have to replace it here with this psuedo-replacement that has the same interface """ def __init__(self): self.__preferences ...
eb1e42ca811c2d45a9dfdeb86e573eda3325bce5f19e63e1ffcec26073efcabd
Python
1,262
51
from traitlets import TraitType class BoundingBox(TraitType): default_value = None def get(self, obj, cls=None): value = super().get(obj, cls) if value is not None: return ",".join(str(v) for v in value) return value def validate(self, obj, value): if isinst...
6d918fb9f6e63f9fa696c6c0779a663222a25bd6425101311af8c7e547606272
Python
1,266
37
import torch import torch.nn as nn import torch.autograd as autograd class GradientLayer(nn.Module): def __init__(self, model): super(GradientLayer, self).__init__() self.model = model def forward(self, x): x.requires_grad_(True) c = self.model(x) # Compute first orde...
5574fa1817e8c2d179b8d2e49078ba1e3254f6653e0d3c8a5c071f177aaf3cbd
Python
1,267
43
import pytest from click.testing import CliRunner from GANDLF.entrypoints.debug_info 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 for di...
fb482e4511dd68373639b3062cd4585337cb4768852472e5f7c78c3f227263fa
Python
1,270
41
## Adapted from: https://github.com/cyh1112/GraphNormalization import torch.nn as nn import torch class GraphNorm(nn.Module): """ Param: [] """ def __init__(self, num_features, eps=1e-5, affine=True, is_node=True): super().__init__() self.eps = eps self.num_features = num_...
68d421ffdf631ff01e0f1da075b4d3a4c05b8ad0a2070cfaef83c143cfb55b50
Python
1,272
54
import sys import importlib.resources import cellprofiler.icons cp_image = None def get_cp_image(): """The CellProfiler icon as a wx.Image""" global cp_image if cp_image is None: import wx try: cp_image = cellprofiler.icons.image_cache["CellProfiler"] except KeyErr...
2e0e8822d2d3746d04659aaaeba9114c858089e70479ea403b895c7a8faccfed
Python
1,273
39
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Apr 11 10:48:57 2018 @author: saskiad """ import numpy as np import pandas as pd import core from allensdk.core.brain_observatory_cache import BrainObservatoryCache import scipy.ndimage as ndi save_path = core.get_save_path() manifest_path = core.get_...
c16101fd7192be9e37821e6ae49c43fa1cb9a2481a165b71e37203b6195fa469
Python
1,273
40
#!/usr/bin/env python import time from samplebase import SampleBase from PIL import Image class ImageScroller(SampleBase): def __init__(self, *args, **kwargs): super(ImageScroller, self).__init__(*args, **kwargs) self.parser.add_argument("-i", "--image", help="The image to display", default="../.....
802ca03dad3f183bfddfa78144637b821e15b4459d1dc145da4ab7c5dbf9977a
Python
1,274
53
import csv import glob import math import os import scipy.io as sio import matplotlib.colors as colors import numpy as np import scipy.io.wavfile as wavfile import scipy.ndimage import scipy.special import skimage import skimage.filters import skvideo.io import torch from PIL import Image from torch.utils.data import ...
cf18f5f8b331543b35602c0421e46db8e3f77394f8cc317b91ee2510953e5bc0
Python
1,274
43
from enum import Enum from centriole.bg_compensate import MODE_AUTO, MODE_DARK, MODE_BRIGHT, MODE_GRAY class IntensityChoice(str, Enum): """Choice of how to calculate the illumination function""" REGULAR = "Regular" BACKGROUND = "Background" class RescaleIlluminationFunction(str, Enum): """The illumin...
d96e8e294f409a84a6523fe9246e62bb379d945d1ce14c211c64c7ca81394916
Python
1,275
34
# -*- coding: utf-8 -*- """ Created on Fri Feb 16 10:32:36 2018 @author: danielm """ import numpy as np def trial_response_significance(sweep_events,num_shuffles=10000): # inputs: # sweep_events: 2D numpy array (num_sweeps X frames_per_sweep) # outputs: p-values for each sweep (1D numpy...
834f37d83b63535a9ab463b7fe2dd99c1d10ea365d56762b792cb813a5fff315
Python
1,278
26
def test_neurons_type(): """Test if NeuronX and NeuronY constructors are callable""" from neurodynex3.neuron_type import neurons a_neuron_of_type_X = neurons.NeuronX() a_neuron_of_type_Y = neurons.NeuronY() assert a_neuron_of_type_X is not None, "Constructor NeuronX did not return an instance" a...
e88f408df1d5825f158918de3c23379c2b661aae74c73b730fbbf5ce1fa496ca
Python
1,278
59
import numpy as np import scipy.integrate as spint def pendulum(x,t): return [ x[1], -np.sin(x[0]) - 0.05*x[1], ] def lorenz_model(x, t): return [ 10 * (x[1] - x[0]), x[0] * (28 - x[2]) - x[1], x[0] * x[1] - 8 / 3 * x[2], ] def MM_Kinetics(x, t): ret...
b75995dfef500faac5d6f192903fce665f632075946bae7858c982ffff3925b3
Python
1,280
61
''' adapted from https://github.com/all-umass/ManifoldWarping ''' ''' helper functions for generating synthetic data ''' import numpy as np from numpy.random import randn, uniform, normal def add_noise(data, noise_stdv): return data + normal(scale=noise_stdv,size=data.shape) # 2-d data generation functions # def...
d393b5585ddf6eb5c3a12e1187ec0aff7adeef86ea9a90e413f815c820973de7
Python
1,280
34
import numpy as np import torchvision.transforms as transforms np.random.seed(0) def simclr_transform(size, s=1): color_jitter = transforms.ColorJitter(0.8 * s, 0.8 * s, 0.8 * s, 0.2 * s) return transforms.Compose([transforms.RandomResizedCrop(size=size), transforms.RandomHoriz...
709888bd5d334fe6f482bad79ef166f0d38e5e05f670f806a3273c7dd9fd7181
Python
1,281
56
from .wrap_torch import ( sgd, asgd, adam, adamw, adamax, # sparseadam, rprop, adadelta, adagrad, rmsprop, radam, nadam, ) from .wrap_monai import novograd_wrapper from .thirdparty import ademamix_wrapper, lion_wrapper, adopt_wrapper global_optimizer_dict = { "sgd"...
398351a4fc18e8b9915883afde80e983beb97b1e0a9f9f252e0250d362517247
Python
1,282
38
''' ========== Test the Python implementation of CS-CORE IRLS ========== ''' import numpy as np import time from CSCORE.CSCORE_IRLS import CSCORE_IRLS # Test 1: a pair of independent data # use ind_gene_pair from the R CS-CORE package counts = np.genfromtxt('data/ind_gene_pair_counts.csv', deli...
a0ea6923518f04e876f4c0a36d9ad37ea4b8fa914dfbc8d8eceec6b0e992d9b2
Python
1,282
39
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 12 14:39:14 2020 @author: nozais """ import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="Functionnectome", url="https://github.com/NotaCS/Functionnectome", version="0.1.1", ...
9444105caef0ac332b0863bfb51e8bcea59115c5eba227786f07721f094a2308
Python
1,284
37
import tempfile import os import h5py import numpy from deeprank.features.secondary_structure import __compute_feature__, SECONDARY_STRUCTURE_FEATURE_NAME from deeprank.models.variant import PdbVariantSelection from deeprank.models.environment import Environment from deeprank.domain.amino_acid import arginine, alanin...
12f368fa1e335d869987548db462c1067a8dc50202aea80ff61fc1692f84cc7f
Python
1,286
48
from breaststudies.models import BasicModel import breaststudies.models.monai_mods as nets class SwinUNETR(BasicModel): def __init__(self, in_ch, out_ch, roi_size, spatial_dims = 3, patch_sizes = ( (1,2,2), (1,2,2), 2, 2), ...
9b23f1350985a038f39fceb576b7b454bfb423bfea934c23226825067ad01e12
Python
1,286
43
"""Run Rscript with the local core, preserving the published dependency pin.""" from __future__ import annotations import os import re import subprocess import sys import tomllib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def main() -> int: rust = ROOT / "packages/r/src/rust" manif...
794ab027805c41a94ed634d0e10daa09aebc828c9a31a66231943858315732bd
Python
1,288
35
# ImageFile must be initialized before ImagePlane from ._image_file import ImageFile from ._image_plane import ImagePlane from ._image_set_channel_descriptor import ImageSetChannelDescriptor from ._listener import Listener from ._pipeline import Pipeline from .dependency import Dependency from .dependency import ImageD...
87a6991e26381773e387cd9a5646b1763ed2bf3ee1ede768e8380c0a2db74317
Python
1,288
57
"""Configuration classes for flask/heroku.""" import os from dataclasses import dataclass from flask.cli import load_dotenv load_dotenv() @dataclass class Config: """Configuration class This class contains all of the global configuration variables needed for the AFIDs validator. Ideally, variables suc...
fe1e05227e485e02a1f1e728311978fd3a814296d8e25caf99edb912e9e07b6a
Python
1,288
32
######nii2npy import numpy as np import os np.set_printoptions(threshold=np.inf) from dipy.io.image import load_nifti, save_nifti from PIL import Image path_src = "data_prepro" path_tgr = "data_prepro_tmp" ### each group was converted to npy file independently; The directory tree can be see in "data_origial...
3765ddbc58fef4ffa5fbfdc4e489ea4817a73b416b8bbdf5649f51fd84044598
Python
1,290
45
""" Author: Mingjian He <mh1@stanford.edu> Testing function for loading data in tests/test_*.py """ import pathlib from importlib.util import find_spec from scipy.io.matlab import loadmat def test_anchor_func(): """ Anchor function for locating this .py file """ return def get_test_path(): """ Find th...
475d07e4085a14f603c4d496ab9b29f2734768d300549c08a50cce9eb28d8e19
Python
1,290
36
builtin_modules = { "align": "Align", "groups": "Groups", "images": "Images", "loaddata": "LoadData", "metadata": "Metadata", "namesandtypes": "NamesAndTypes", } all_modules: dict = {} svn_revisions: dict = {} pymodules: list = [] badmodules: list = [] do_not_override = ["set_settings", "create_...
5229f8e0f0e502ce0e3845444ec4d7dc6edf72c72b9acf167cb7700f597a8db4
Python
1,290
32
""" MIT License Copyright (c) 2022 Pawan Goyal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
be4b8321e5fb96b48ad36be23b39ae71acdc2095a46820b9d545d7bb475ba5d7
Python
1,294
18
from devices._poke import _Poke class Six_poke(): # 6 IR beams, each with LED. def __init__(self, ports, rising_event_1 = None, falling_event_1 = None, rising_event_2 = None, falling_event_2 = None, rising_event_3 = None, falling_event_3 = None...
e6cefec1d2e28c466a336fb50534677e83f4741f761e1cbd3ca526a6d7f420f9
Python
1,294
32
"""Training task abstractions for timm. This module provides task-based abstractions for training loops where each task encapsulates both the forward pass and loss computation, returning a dictionary with loss components and outputs for logging. """ from timm.loss import LOSS_TYPES, MULTI_LABEL_LOSS_TYPES, create_clas...
f81f64a1c9d3c8a8186c31fe2e13f85c8f9645bbb48856fcdbc9409a9621d6da
Python
1,294
46
import torch from .optimizer import SGD, Adam, AdamW from .nc_runner import NCRunner from .ncssl_runner import NCSSLRunner OPTIMIZER_DICT = { 'SGD':SGD, 'Adam':Adam, 'AdamW':AdamW, } RUNNER_DICT = { 'NC':NCRunner, 'NCSSL':NCSSLRunner, } def build_optimizers(models, cfg): """Build an optimize...
2fcaa592042cd6ba1710f1d3c12d04feb9ea17a809c71ffbe0a2c0401036461c
Python
1,296
46
import os import pytest import pysteps from pysteps.tests.helpers import smart_assert pytest.importorskip("pyproj") pytest.importorskip("osgeo") root_path = pysteps.rcparams.data_sources["fmi_geotiff"]["root_path"] filename = os.path.join( root_path, "20160928", "201609281600_FINUTM.tif", ) precip, _, m...
d6788658b794386e97d07b855b2a5b34ad55439c6a4b20b2d38cc93e3aacde77
Python
1,296
39
from machine import UART from array import array import pyb class Dfplayer(): def __init__(self, uart=1, timeout=1): self.uart = UART(uart, 9600) self.uart.init(9600, bits=8, parity=None, stop=1, timeout=timeout) self.cmd_bytes = array('B', [0x7E, 0xFF, 0x06, 0, 0, 0, 0, 0, 0, 0xE...
4a08247f30af7a8ae6e61571846d7e5aa8cb32cd2f79bde5e41b060a6a558ff3
Python
1,298
43
import numpy as np import sklearn.metrics def cal_f1(x,y): return 2.0 * x * y / (x + y + 1e-20) def calc_evaluation(y_ans,y_pred): def softmax(x): return np.exp(x)/np.sum(np.exp(x),axis=0) y_prob = [softmax(y) for y in y_pred] y_pred = np.array([np.argmax(i) for i in y_prob]) y_...
76f109a9cd85aa24df1d538b2479b80c8e172adb9b7b8ef38eb3c031e21a4d30
Python
1,298
43
import os import sys import inspect import filecmp from itertools import islice def checkFolderEquality(folder1, folder2): """ Given two folders, check if there are the same number of files, that the names of files are the same, and that the files with the same names are the same. """ folder1_...
2ae85679a58a5f4566e1b491f0247a7f5e0be19d460e784ed08fc4d435f67539
Python
1,299
46
import tensorflow as tf import matplotlib.pyplot as plt def serialize_array(array): array = tf.io.serialize_tensor(array) return array def parse_tfr_element(element): data = { 'label_multilabel': tf.io.FixedLenFeature([], tf.string), 'label_quantif': tf.io.FixedLenFeature([], tf.string), ...
f627c1bb5b8ca7f8f0d74af792af8bef1dfb612f3b2ec54c4b2569a8e7797b4c
Python
1,299
44
""" 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 import unittest import numpy import pandas import json impor...