sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
6e8f2c028361cf1108c46dc1bfd2e4eb08ae9bbae6d2cde1f39760d96be3d44e
Python
2,009
61
import commot as ct import scanpy as sc import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns import sys import gc import ot import pickle import anndata from scipy import sparse from scipy.stats import spearmanr, pearsonr from scipy.spatial import distance_matrix impor...
b417a450430f2e01d9419e92cb34942ccd87cb7010815fb39390f46def0575b5
Python
2,009
55
## Script for simulating data according to the distance based rule at the synapse level. # See main paper and tutorials/1_simulation for details. import pickle from pathlib import Path import torch from sbi.inference import prepare_for_sbi, simulate_for_sbi from consbi.simulators import RuleSimulator, peters_rule_su...
ec030cf8eaf2128fe7e4c16bcc603aa8b3db7996ad0ccdb15af1392b159656cb
Python
2,011
67
#!/usr/bin/env python3 import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def read_text(path: Path) -> str: return path.read_text(encoding="utf-8") def extract_package_version() -> str: text = read_text(ROOT / "clipkit" / "version.py") match = re.search(r'__versio...
f97dc2a4b8647a3a4f808406c765b52037421074828a6b27c603182d96fe1a70
Python
2,011
56
# from keras.preprocessing.text import Tokenizer # from keras.preprocessing import sequence import logging from collections import Counter from torchtext.data.utils import get_tokenizer import torch from torchtext.vocab import Vocab from torch.nn.utils.rnn import pad_sequence class TorchTokenizer(): def __init__(...
c2ee45548c5f4e7dd187be5a85560f7b1a7af175ea5c82e8a657ff984f0293f9
Python
2,015
55
# -*- coding: utf-8 -*- """ Created on Thu May 19 13:39:59 2022 @author: fhu14 """ ''' This module handles high level operations related to parsing through and analyzing a large number of results. This includes os and shutil level operations ''' #%% Imports, definitions import os, shutil, json from .table_ops import...
ebaee951d58b8eefd23b6984654876a80d948e9b73792c528b60f4caaa2ac171
Python
2,022
57
import sys sys.path.append('versatile_diffusion') import os import numpy as np import torch from lib.cfg_helper import model_cfg_bank from lib.model_zoo import get_model from torch.utils.data import DataLoader, Dataset from lib.model_zoo.vd import VD from lib.cfg_holder import cfg_unique_holder as cfguh from lib.cfg_...
af64019e5e5d948d6aff8c557142a654edac9d23f964b225ce52f015fcad61bf
Python
2,023
72
from model.builders.JAMA_builders import any_cancer_JAMA import os from copy import copy, deepcopy filename = os.path.basename(__file__) data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0}} training_splits = [0,1,4,6,7,9] number_reports = ...
227558d477b3a68780d309a784ea7fef7168e1e10b8dabda1a2c2dd087537f37
Python
2,027
58
## Script for simulating data according to the distance based rule at the neuron level. # See main paper and tutorials/1_simulation for details. import pickle from pathlib import Path import torch from sbi.inference import simulate_for_sbi from sbi.utils import BoxUniform from consbi.simulators import DistanceRuleSi...
9eaf4b6bdbc7312e3fbcd5c3d194a320972e48b3676101c890cab57dc26c565b
Python
2,029
53
import csv import os import pandas as pd def compute_IOU(rec1,rec2): """ 计算两个矩形框的交并比。 :param rec1: (x0,y0,x1,y1) (x0,y0)代表矩形左上的顶点,(x1,y1)代表矩形右下的顶点。下同。 :param rec2: (x0,y0,x1,y1) :return: 交并比IOU. """ left_column_max = max(rec1[0],rec2[0]) right_column_min = min(rec1[2],...
44d503266236ba280b59b92f56042d4a3ca9ea853b9861607afce607c324118c
Python
2,030
60
import os import cv2 import h5py import numpngw import numpy as np import scipy.ndimage as ndimage def save_pairs_segmentation(data_path, save_root): h5_data = h5py.File(data_path, "r") test_data = h5_data["test"] train_data = h5_data["train"] _save_pairs(test_data, save_root, "test") _save_pairs...
5d42713e2052227b2bd046347f089b363b7f0d9e66f849d40f74f93201297453
Python
2,030
53
import numpy as np import random class ExpCentralCrop2d: """ Crop the 2D numpy [c, h, w] and mask [h, w] in a sample The d should be randomly sampled """ def __init__(self, output_size, padding=0, include_lax_tensor=False, training=True): assert isinstance(output_size, (int, list, tuple))...
49692e9bd5d949c5f8f3d263f0cf1fa3aa5f3407bc292940f5c9ec28a0be8eda
Python
2,032
56
import numpy as np import torch from torch.utils.data import DataLoader def random_worker_init_fn(worker_id): """ Initialize random state for each DataLoader worker process. This function is called when a worker process starts. It sets up the dataset's random state based on the worker's seed to ensur...
b680c2bbea3d21bc802e67daaa4f650b07229a79deddf920364e321bbc22525a
Python
2,032
66
import multipagetiff as mtif import numpy as np import logging log = logging.getLogger(__name__) try: import iocbio_deconvolve as iocbio # IOCBIO deconvolve except ModuleNotFoundError as e: msg = f"{e.msg}\n\n" \ "The iocbio deconvolve python wrapper was not found.\n"\ "Probably, you need ...
ceb4f106748b54a5604d4cd9db18260a3d77b05343687d10cfbd0a63081ecab0
Python
2,034
81
# -*- coding: utf-8 -*- """ Functions for loading test data setss """ import os.path as op from pkg_resources import resource_filename import numpy as np from sklearn.utils import Bunch _res_path = resource_filename('snf', 'tests/data/{resource}') def _load_data(dset, dfiles): """ Loads `dfiles` for `dset` ...
55ef37b25eed789ed71d6d04310ad4bc87ebc5be2a5dbd4ebddaa92545d0b934
Python
2,035
70
import pytest import matlab.engine import numpy as np import scipy from numpy.testing import assert_allclose from pystoi.stoi import N_FRAME, NFFT, FS ATOL = 1e-5 eng = matlab.engine.start_matlab() eng.cd('matlab/') def test_hanning(): """ Compare scipy and Matlab hanning window. Matlab returns a N+2 si...
aa5bbd99cb11401de3b8211691cc8e038073a610dc4d5cd7f1ee5a45bcc459ca
Python
2,035
68
import os from pprint import pprint def read_lists_from_file_separate(file_path): with open(file_path, 'r') as file: content = file.read() lines = content.splitlines() lists = [] current_list = [] for line in lines: if line.strip() == '': if current_list: # append on...
b6ba1e0ef500f06959c51f4ef9484d682b13b36a0c4e774d0636174f65784d96
Python
2,042
69
import numpy as np import torch import PIL from PIL import Image def imresize(im, size, interp='bilinear'): """ Function for image resizing with given interpolation method """ if interp == 'nearest': resample = Image.NEAREST elif interp == 'bilinear': resample = Image.BILINEAR ...
138dea1cbf8b1f0861234b926fc8094e970ecd6b0570a6001cab6d17d40bc308
Python
2,048
86
import numpy as np import pytest import torch from Bio.PDB import Atom, Chain, Model, Residue, Structure from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment from selbstaufsicht.utils import rna2index from selbstaufsicht.models.self_supervised.msa.transforms import MS...
b19aae0ca2357cb757f514ce84f3f22d5d2ec04a67e42683423eb75f80b3f92b
Python
2,048
51
import h5py import numpy as np import torch.utils.data as data class StackOverflowDataset(data.Dataset): """StackOverflow dataset""" __train_client_id_list = None __test_client_id_list = None def __init__(self, h5_path, client_idx, datast, preprocess): """ Args: h5_path (s...
82412dd937568e5c0ee2c3adb6e6403702c15ca7d3c0ca53eb08d22c38665e6b
Python
2,050
56
# Copyright (c) 2020-present Joindbre.com # Authors: Patricia Maraver. # # This program is free software: you can redistribute it and/or modify # it under the GNU Affero General Public License version 3 # as published by the Free Software Foundation. # You should have received a copy of the Server Side Public Lic...
a824f29b837ff2d86c4d347b3d7095647eb3535541ed62c60345a1a9ff0ba1dd
Python
2,050
38
import numpy as np def tabGeneration(resfile,Yhat_pred,list_ids,window,threshold_presence): ''' This function writes the tabular file for the output ''' classes = {3:"RT",4:"GAG",5:"ENV",6:"INT",7:"AP",8:"RNASEH"} longNormal = {3:1000,4:3000,5:2000,6:2000,7:1000,8:1000} print("Wri...
f509d20d26b8f10288eb2b7e5c880b15408e80814ebc32d2e77f06db4f5a739c
Python
2,056
62
import numpy as np class Uniform: def __init__(self, rand_min, rand_max): self.rand_min = rand_min self.rand_max = rand_max def get_random_values(self, output_shape): rand_values = np.random.uniform(self.rand_min, self.rand_max, size=output_shape) return rand_values class Ga...
894563268ed38fb2a9cfe1b51048473a80622d22aaeeddf6ba8179942f95f7f7
Python
2,059
69
# run with # python setup.py build_ext --inplace import sys nrn_srcdir = "." #mingw = 1 mingw = 0 instdir = "/raid/zyc/code_for_dhs_paper/install" if nrn_srcdir[0] != '/' : # TODO: is this right? nrn_srcdir = '../../../../../../' + nrn_srcdir from distutils.core import setup from distutils.extension import Ex...
cd49584b4e792e8f0f9194dd797d858df1c4a5975911fab99fd018de25bd5367
Python
2,063
69
# run with # python setup.py build_ext --inplace import sys nrn_srcdir = "." #mingw = 1 mingw = 0 instdir = "/raid/zyc/code_for_dhs_paper/install" if nrn_srcdir[0] != '/' : # TODO: is this right? nrn_srcdir = '../../../../../../' + nrn_srcdir from distutils.core import setup from distutils.extension import Ex...
bd3889ec5a45c7dd0273fa2f4a9bd4354bb2ce3dd48013cffc6bcc337678265b
Python
2,064
54
import math import torch import torch.nn as nn from functools import partial, reduce from operator import mul import torch.nn.functional as F import numpy as np from timm.models.layers import trunc_normal_ from models.vit_3d import VisionTransformerND, ConvStem3D from models.layers.stmixer import STMixer class LNGrow...
677b77392b11f33aa9ff292be0ed2f28474d6b261894f0727025e78934c64a70
Python
2,068
53
############################################ # imports ############################################ from abc import ABC, abstractmethod from typing import Any from oligo_designer_toolsuite.database import OligoDatabase ############################################ # Scorer Base Class #################################...
a27207b46c02b0e31034369ac03737db85168fa84e8b6b57fef25414f3f172a5
Python
2,068
54
""" subsample slices for MICCAI 2020 Reconstruction project. """ import numpy as np import random from scipy.ndimage.interpolation import shift class RandomSample: """ Subsample the 3D numpy [c, h, w, d] by slice max number. """ def __init__(self, perturbation=False): self.sample_size_propabi...
2fae701d4b2667e409ebd94d92b60d20b82c3fb8bfba6059e78b738e10e3279f
Python
2,069
52
import discharge_summary_parser as dsp from semquery import SemEHRES import utils def analyse_corpus(q, doc_type, full_text_field, reg_exp, output_file): es = init_es_inst() dsp.analyse_discharge_summaries(es, q, doc_type=doc_type, full_t...
b0eb7449e1c3a3b58975a90b0dc0ff0de9ae160ccb19fba5b3fe363c7f3607a2
Python
2,074
55
#!/usr/bin/env python # # The MIT License # # Copyright (c) 2011 Seoul National University. # # 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 limitati...
2919fb5b6c234d063efdabea6ba991ebd71339dcf33e55625880f2de01bb673c
Python
2,077
56
import jax import jax.numpy as jnp from functools import partial ''' u: [usize, udim] lb: [udim] rb: [udim] out: [usize+2, udim] ''' roll_db_funs = {2: jax.jit(lambda u, lb, rb: jnp.concatenate([jnp.tile(lb, [3,1]), u[:-1,:]], axis = 0)), 1: jax.jit(lambda u, lb, rb: jnp.concatenate([jnp.tile(lb, [2,1]...
0c70bf58578290b9c04e418e9862602fd9a68780a1190cff7cad513b0237e281
Python
2,079
63
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np from mmpose.datasets.builder import PIPELINES from .top_down_transform import TopDownRandomFlip @PIPELINES.register_module() class HandRandomFlip(TopDownRandomFlip): """Data augmentation with random image flip. A child class of TopDownRandomF...
41af9ad108d558fb5ba173ea0fe3a7cf83bd585514f25b94a4c061586e3f3400
Python
2,079
57
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
7c14f783fc7012cee11b015735e71f3dc6e75dcdd4da3488e5a14be4beb4aa72
Python
2,080
70
"""Custom formatting for CLI help and error messages.""" import argparse import sys import textwrap class ArgumentParser(argparse.ArgumentParser): """Enhanced argument parser with better formatting.""" def __init__(self, **kwargs): super().__init__( formatter_class=HelpFormatter, ...
5fc926a3fcbaba4722bdfcdea783cbffb3fc906059bb7eae4ff6051ffa2d44c3
Python
2,082
63
import argparse import os import librosa import numpy as np def process_utterance(wavscp, utt2spk, audio_dir, wav_dumpdir, segment, tgt_sr=24000): uid, _, phns, notes, syb_dur, phn_dur, keep = segment.strip().split("|") utt2spk.write("{} {}\n".format(uid, "opencpop")) # apply bit convert, there is a kn...
0bf310ff752bd85c1b1cacd29576465a6585bd400b0e4b1d7abdb6b8ba08f506
Python
2,084
45
from fedml_api.distributed.split_nn.message_define import MyMessage from fedml_core.distributed.server.server_manager import ServerManager from fedml_core.distributed.communication.message import Message class SplitNNServerManager(ServerManager): def __init__(self, arg_dict, trainer, backend="MPI"): super...
f12a51bd6f9aba069f4162d9e47db6f4fc90bcf538722887d62aa48119f4319f
Python
2,086
75
''' Author: ---- Date: 2022-04-09 14:24:09 LastEditors: ---a LastEditTime: 2022-09-05 14:46:08 ''' import torch import torch.nn as nn import torch.nn.functional as F class Gramian(nn.Module): r""" Enforcing weight matix to be orthogonal by restricting Gramians """ def __init__(self) -> None: s...
9c487bc01f069866ca4c4f6344a38bdca1d088b6d624325deaa1ce5015099e46
Python
2,090
55
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from torch import Tensor, nn class FCEmbedding(nn.Module): """Fully-connected multi-layer neural network to be used as embedding network.""" de...
a0bc48430e7532562d37e8816ebc8a4d793306822fbcd13f77880944cb79e246
Python
2,090
63
import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import SubsetRandomSampler class BaseDataLoader(DataLoader): """ Base class for all data loaders """ def __init__(self, dataset, batch_size, shuffle, validat...
aae0b37d86858e69ac36e5779c5268672f3e8986c36e7c9c4f3c953e3ffedd91
Python
2,090
78
import pickle from pathlib import Path import torch from sbi.inference import simulate_for_sbi from sbi.utils import BoxUniform from consbi.simulators import ( RuleSimulator, default_rule, default_rule_constrained_two_param, default_rule_linear, default_rule_linear_constrained_2p, dso_linear_t...
3a88e67d0ba84a460de987876349ff17291370ff7b251d7fe6a109ad8fe7574e
Python
2,091
61
#!/usr/bin/env python from __future__ import division from __future__ import print_function import os import sys import vcf import argparse TUMOR_SAMPLE = "TUMOR" THRESHOLD = 1.3 def filter_strelka(input_fh): input_vcf = vcf.Reader(input_fh, strict_whitespace=True) output_vcf = vcf.Writer(sys.stdout, templ...
dc26e4f4e65426ddad52083b6ffccd3ed0135b20039b369f52b8ca1057e648e4
Python
2,091
47
#!/usr/bin/env python # -*- coding: utf-8 -*- # McNemar's test source: https://machinelearningmastery.com/mcnemars-test-for-machine-learning/ import statsmodels.stats.contingency_tables as sm """ @input - truth values of the predictions of the first model (List); truth values of the predictions of the second m...
47ae83eb983f8c9cd71ba0b96bfd4c178b561fc141fb4c55b22a7a8b68b3134b
Python
2,097
61
#------------------------------------------ # Compute all folial widths and perimeters # 1 Feb 2023 #------------------------------------------ '''Compute and save gyral measurements for all subjects in the dataset''' import json import numpy as np import pandas as pd import gyri as gy from convert_polygons_to_shapel...
f4b021fd6964dfedc4244599a6b104bcdd64589d8ca119bf7efdf761e083e70d
Python
2,098
58
from skimage import filters from skimage.io import imread from flystim import util import numpy as np class Image: """Image class.""" def __init__(self, image_name): self.image_name = image_name self.image_path = util.get_resource_path(image_name) def load_image(self): """ Return...
326e9cd82823540355aa67d5e74021d357a72e6d1df14ed0bb400630ae48e0a1
Python
2,099
81
#!usr/bin/env python #coding:utf-8 """ @author: Haidong Zhang @contact: haidong_zhang14@yahoo.com @time: 2020/12/10 18:23 @project: MalariaDetection @description: """ from keras.layers import * #For adding convolutional layer from keras.layers import Dense, ZeroPadding2D, BatchNormalization, Activation...
a7a52aa7911e001bb919e6c101e11014f238601e80cf08b11416a21534df46b8
Python
2,100
53
import cv2 import numpy as np def picdil(n, stencil, img): kernel = np.ones((25,12), np.uint8) # ============================================================================= # kernel2 = np.ones((0,1), np.uint8) # img_dilated = cv2.erode(img.copy(), kernel, iterations = 1) # img_dilated = cv2.dil...
e7dd3a1748b9ec4ed72bfb4f5c89285989f89686fbb3a5cdc35a8c2df2fe3825
Python
2,106
59
import sys import numpy as np import sklearn.linear_model as skl import argparse parser = argparse.ArgumentParser(description='Argument Parser') parser.add_argument("-sub", "--sub",help="Subject Number",default=1) args = parser.parse_args() sub=int(args.sub) assert sub in [1,2,5,7] nsd_features = np.load('data/extract...
0ca420ce3e73d1d4b16f4b7cc436448c078df6fa75ad7e93ac69580e9b623bd3
Python
2,111
53
import argparse import logging import os import sys import numpy as np import torch import wandb sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) from fedml_api.standalone.hierarchical_fl.trainer import Trainer from fedml_experiments.standalone.fedavg.main_fedavg import add_args, load_data...
73c8ba3329d60e5a10a3d793b83b67bd416390ddb709bd41481de01f521e0206
Python
2,115
64
# Copyright (c) 2023 IBM Research. All Rights Reserved. # # Code accompanying a manuscript entitled: # "On the visual analytic intelligence of neural networks" from random import randint, choice from PIL import Image, ImageDraw from constants import NUM_IMAGES, MAX_COLOR_INTENSITY class BaseGenerator(): ...
5a73d33a921f527064df302587e047bb468c5fff1b140d564e7d63efab9092fe
Python
2,119
47
# Copyright (c) 2020-present Joindbre.com # Authors: Patricia Maraver. # # This program is free software: you can redistribute it and/or modify # it under the GNU Affero General Public License version 3 # as published by the Free Software Foundation. # You should have received a copy of the Server Side Public Lic...
239042d3964c701daae3bfda2617c131d7bb631f936930d8630d6919500c0947
Python
2,121
55
# Module containing functions used to validate input parameters # # Author: Fernando García Gutiérrez # Email: fgarcia@fundacioace.org def checkInputType(input_var_name: str, input_var: object, valid_types: list or tuple): """ Check if the input variable is in the allowed types ("valid_types"). """ if n...
c280cdff61f57481d5113d97cabd47976598d152527aac6747fddc2b167eb7f4
Python
2,122
56
class VerticalMultiplePartyLogisticRegressionFederatedLearning(object): def __init__(self, party_A, main_party_id="_main"): super(VerticalMultiplePartyLogisticRegressionFederatedLearning, self).__init__() self.main_party_id = main_party_id # party A is the parity with labels self.pa...
3c6872d0e3ac3b09a85e5dbc54a9a167ef42efbe138868460738ad9ac178f7c8
Python
2,124
62
import json from pathlib import Path import numpy as np import pandas as pd from DeepSlice import DSModel EXAMPLE_DIR = Path("examples/example_brain/GLTa") REFERENCE_PREFIX = EXAMPLE_DIR / "MyResults" def test_example_brain_predictions_match_reference(tmp_path): output_prefix = tmp_path / "PR80Results" m...
ddb1f12084f5dff852a9c8f5598936921fe75873c13753fa872aabee23b09143
Python
2,125
60
import logging from abc import abstractmethod from mpi4py import MPI from ..communication.mpi.com_manager import MpiCommunicationManager from ..communication.mqtt.mqtt_comm_manager import MqttCommManager from ..communication.observer import Observer class ServerManager(Observer): def __init__(self, args, comm=...
fd581aa4a1888c6bc835dad2945050788c62ad989f7718e3a9ccbe861963c88d
Python
2,126
61
import math from basicstat import * def readbf(runnames, min_ess = 10): logz_idx = 2 meanlog_idx = 3 varlog_idx = 5 npoint_idx = 6 ess_idx = 7 runs = [] for run in runnames: with open(run, 'r') as infile: x = [[float(y) for y in line.rstrip('\n').split()] for line in i...
99b87d26b15be95e24f3aacc8c73796f5ea03bbef5f4fa19d91dc7873dc06aa5
Python
2,127
66
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmpose.models.backbones.tcformer import TCFormer def test_tcformer(): with pytest.raises(TypeError): # Pretrained arg must be str or None. TCFormer(pretrained=123) # test load pretrained weights model = TCFor...
ae100da6e95f58097543388730628a9c2410948c876abe119ce83e535e005e31
Python
2,127
71
import argparse import matplotlib.pyplot as plt import pandas as pd from graphrepr.wilcoxon import ( get_best_models_for_reprs, get_validation_results, load_all_preds, mse, plot_pval, test_representations_df, ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_a...
2198a728e322dc4d0d0926bd53e15570fbf8cd7b4aa09af1bdaf1944b07b3bdb
Python
2,129
65
#!/usr/bin/env python3 """A setuptools based setup module. See: https://packaging.python.org/guides/distributing-packages-using-setuptools/ """ import setuptools from brainstat import __version__ as brainstat_version with open("README.rst", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools....
e9ffa193aed7249d4d6f40ecbf3dce2d421f5d46ced40c5a3e46cb4e8da15ffa
Python
2,129
56
from model_v0 import * from deprecated.solver_v1 import Solver from fold import * from util import Timer dataset_path = "/home/francishe/Downloads/ANI-1ccx_clean_shifted.h5" gammas_path = "/home/francishe/Downloads/gammas_50_5_extend.h5" cv_root = "/home/francishe/Downloads/cv_inflect/" target_type = ['cc', 'pe'] fol...
37fd6d552d6b5d1566324b7549200dff520f2623fe525134b4dc1a71272933ba
Python
2,131
64
from model.builders.builders import build_full_network import os filename = os.path.basename(__file__) from copy import copy, deepcopy vocab_size = 20000 data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}} training_splits = [0,1,4,6,...
0380277b12a906d551cfa5e6119ed864115b427d85b7f818280d60431b69e927
Python
2,132
45
from mpi4py import MPI from fedml_api.distributed.turboaggregate.TA_Aggregator import FedAVGAggregator from fedml_api.distributed.turboaggregate.TA_Trainer import FedAVGTrainer from fedml_api.distributed.turboaggregate.TA_decentralized_worker_manager import TA_ClientManager def FedML_init(): comm = MPI.COMM_WOR...
eb7f3780490a13d3a2ba2b1a8945f4ff83dd5d60b86b903cd9dc3d81f34ae29f
Python
2,132
72
# -*- coding: utf-8 -*- # Copyright 2020 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Vector quantize codebook modules. This code is modified from https://github.com/ritheshkumar95/pytorch-vqvae. """ import torch from parallel_wavegan.functions import vector_quantize, vector_quantize_str...
adf04bcb11224d80bf2f48dbc3663d902b3c2b581d2d94c065b5cf23e893d6e1
Python
2,133
51
import multipagetiff as mtif import argparse import logging import os from . import utils import numpy as np from ..deconvolution import deconvolve # ========================================= def main(*args, **kwargs): parser = argparse.ArgumentParser(description="Deconvolve one stack.\ Example: pycro...
1f8f36e2c5386a5352c7ac7a3ce8d60e05e0664563e9e7ddaa5ce103ef7adec2
Python
2,134
75
#!usr/bin/env python #coding:utf-8 """ @author: Haidong Zhang @contact: haidong_zhang14@yahoo.com @time: 2020/12/10 17:53 @project: MalariaDetection @description: """ from keras.layers import * #For adding convolutional layer from keras.layers import Flatten #For flattening max pooled layer values...
932b4d59b063e5c31f6f3ecff0b27cca207983638dcc5425481bed3ac8674bae
Python
2,134
64
from model.builders.builders import build_full_network import os filename = os.path.basename(__file__) from copy import copy, deepcopy vocab_size = 20000 data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}} training_splits = [0,1,4...
e5104d8897dfc229d045cab64fdfeac6c45071c215f949268be4dd7984600bec
Python
2,135
55
import torch def vectorize_weight(state_dict): weight_list = [] for (k, v) in state_dict.items(): if is_weight_param(k): weight_list.append(v) return torch.cat(weight_list) def load_model_weight_diff(local_state_dict, weight_diff, global_state_dict): """ load rule: w_t + clip...
3f33e45ce8272761b4660aa9c7c05c172b5ac98d003e96b8a47a7b10ecadc82c
Python
2,138
75
#!usr/bin/env python #coding:utf-8 """ @author: Haidong Zhang @contact: haidong_zhang14@yahoo.com @time: 2020/12/10 17:53 @project: MalariaDetection @description: """ from keras.layers import * #For adding convolutional layer from keras.layers import Flatten #For flattening max pooled layer values...
484945d11c9c2cd5dd63406d30fd19dfc7f9ed92f327bd87114652fc3c8d8385
Python
2,140
58
####################################################################### # Software License Agreement (AGPL-3 License) # # OpenViBE SDK Test Software # Based on OpenViBE V1.1.0, Copyright (C) Inria, 2006-2015 # Copyright (C) Inria, 2015-2017,V1.0 # # This program is free software: you can redistribute it and/or modify ...
99710e8852585395f53d61cc931f61aa4481065acf89a56770edc0eec08fc28f
Python
2,140
66
import os import time import ujson as json import numpy as np import pandas as pd import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader class MySet(Dataset): def __init__(self): super(MySet, self).__init__() self.content = open('./json/json').readlines() ind...
110cad2abd7e71d318c56487f0c4d0931d8854f6c7f02d5fddd9d4d8da92596a
Python
2,142
52
#!/usr/bin/env python3 """ The spatial attack is a very special attack because it tries to find adversarial perturbations using a set of translations and rotations rather then in an Lp ball. It therefore has a slightly different interface. """ import torchvision.models as models import eagerpy as ep from foolbox import...
21e9bba263e88fdbc2563fe35e81083396b6e28e1da48fc9887a3972cce009ba
Python
2,142
76
import pytest from pathlib import Path from clipkit.clipkit import execute from clipkit.files import FileFormat from clipkit.modes import TrimmingMode from clipkit.settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS here = Path(__file__) @pytest.mark.integration class TestCodonOut(object): def test_simpl...
8abc02cb7793722918ca93b3d2964d9985ff243243f9b532dd240f571ac55df1
Python
2,146
76
# -*- coding: utf-8 -*- """MNIST dataset for testing""" __author__ = "Sean Benson" __copyright__ = "MIT" import torch from torch.utils.data import Dataset import h5py import matplotlib.pyplot as plt import numpy as np from scipy.signal import resample_poly _factors = [(3, 1), (3, 1), (3, 1)] def array_to_color(arra...
aedfa3f9d9b3ce6c405d04b7fe9894364e385636ac7238a7ec39bac9789c16df
Python
2,146
47
import argparse import pathlib from exsclaim.pipeline import Pipeline # Path to/ Name of Query JSON, used if no command line argument is supplied # If no file extension (.json) is supplied, path will be assumed to be: # path/to/exsclaim/query/<QUERY>.json QUERY = "nature-haadf-ag-nanoparticles" # First letter of tool...
7be93d3cc1f7aab19531f4c01756acee6c05e026b900dd24cf1201260d7b519c
Python
2,147
77
# -*- coding: utf-8 -*- """MNIST dataset for testing""" __author__ = "Sean Benson" __copyright__ = "MIT" import torch from torch.utils.data import Dataset import h5py import matplotlib.pyplot as plt import numpy as np from scipy.signal import resample_poly _factors = [(3, 1), (3, 1), (3, 1)] def array_to_color(arr...
9ca8707c1b6d246f37db0747d7a2c7c36deaf45e9f4270f6ca4561d7ac4247b6
Python
2,150
55
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import tabulate def load_gmv_corr_with_ad() -> pd.DataFrame: return pd.read_csv("./metadata/data_processed/gmv_corr_with_ad_stats.csv") def load_risk_table(seed, risk) -> pd.DataFrame: df_ = pd.read_csv(f"./metadata/d...
a33450875af9cb9d438ec79772d710a1b412c76e2befbfd9c986f137c3eebf91
Python
2,161
56
import numpy as np class ExpRandomCrop3d: """ Crop the 3D numpy [c, h, w, d] and mask [d, 2] in a sample """ def __init__(self, output_size, padding=0, training=True): assert isinstance(output_size, (int, list, tuple)) if isinstance(output_size, int): self.output_size = (o...
cc52e0b8d91c4b2daa26d898df0a143806f901245e30c8e5f014d0222570daa0
Python
2,162
78
# -*- coding: utf-8 -*- # Copyright 2020 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Causal convolusion layer modules.""" import torch class CausalConv1d(torch.nn.Module): """CausalConv1d module with customized initialization.""" def __init__( self, in_channels,...
e92c308932206c03a93eff83ba6fc65608b47084baff152739315fdbd6b3cba9
Python
2,162
56
import numpy as np import pandas as pd def get_cluster_statistics(words: pd.DataFrame) -> dict: """ Calculates some general clustering features (see return-description). :param words: pd.DataFrame containing a column "cluster" with np.NAN for words without a cluster and an integer for words within a c...
33a718cff9853298621daa702c22b7689684ab1079eb9d4310f7f0cbe5b6d354
Python
2,164
55
# Copyright (c) OpenMMLab. All rights reserved. from ..builder import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module() class FastRCNN(TwoStageDetector): """Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_""" def __init__(self, backbone, ...
821dcf4d73a608792a4fdc734a62c0f14843a2f3a3d7caf1278c15c7ca1c52dc
Python
2,164
69
# Copyright (c) OpenMMLab. All rights reserved. import tempfile from unittest.mock import MagicMock import pytest from numpy.testing import assert_almost_equal from mmpose.datasets import DATASETS from tests.utils.data_utils import convert_db_to_output def test_deepfashion_dataset_compatibility(): dataset = 'De...
7e2205b97f9fd275586c6182ff5367db4501296953116438dd547bc85b7f841a
Python
2,167
77
""" This module provides property calculation functionality for oligonucleotides. """ from ._property_base import BaseProperty from ._property_calculator import PropertyCalculator # Export calculation functions for use by filters and scorers from ._property_functions import ( calc_detect_oligo, calc_dg_second...
321526e7fef12ff37428f34bead59f22c9ba23f09ffdd983aca456159a619ccc
Python
2,169
67
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) from abc import abstractmethod, ABCMeta from typing import Optional, Tuple from torch import nn, Tensor class BaseWra...
2db4a12623d662e5c83d051a2c65660cd5292c4cf3a3e996588800aa52409c7e
Python
2,170
70
# Copyright (c) OpenMMLab. All rights reserved. from unittest.mock import MagicMock import pytest from mmcv import Config from numpy.testing import assert_almost_equal from mmpose.datasets import DATASETS from tests.utils.data_utils import convert_db_to_output def test_deepfashion_dataset(): dataset = 'DeepFash...
a41197c3c9fbe6a3bc6844efe281636c6794c1ef7794d04e25b80583dcd5786a
Python
2,171
71
import sys import os import pandas as pd import numpy as np import logging from tqdm import tqdm from utils import setup_custom_logger def getThresholdValue(matrix_Arr, quantile): flatten = [] for row in matrix_Arr: for val in row: flatten.append(float(val)) #print("Data size : ", len(f...
4ed80eb06eb25d074b3942a60e9a4582c6e094f0b77934f21a496e29cd68e04c
Python
2,175
58
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.runner import BaseModule class SELayer(BaseModule): """Squeeze-and-Excitation Module. Args: channels (int): The input (and output) channels of the SE layer. ratio (int):...
dcc1ba1d8c1c79d7361b737f261ab9422c057b2ebd987b2a2914c2eeccb3255b
Python
2,176
70
import torch import torch.nn as nn import torch.nn.functional as F # Swish https://arxiv.org/pdf/1905.02244.pdf --------------------------------------------------------------------------- class Swish(nn.Module): # @staticmethod def forward(x): return x * torch.sigmoid(x) class Hardswish(nn.Module):...
1d0e6734eaa5e1cf4715060df5d8799d11d0424d239087515754862132bbd00b
Python
2,178
66
import torch import torch.nn as nn import torch.nn.parallel import numpy as np from torch.nn.parameter import Parameter class rational(nn.Module): def __init__(self): super(rational, self).__init__() print('rational!!!!!!!!!!!!!!!!!!!!!!!!!!!!') self.a0 = Parameter(torch.FloatTens...
72dfc21f6a407f6d2e906d92a3d29fee2c6f7416bc1d2c1638eea6997b785bdd
Python
2,179
85
import os.path as osp import numpy as np import numpy.random as npr import PIL import cv2 import torch import torchvision import xml.etree.ElementTree as ET import json import copy import math def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: ...
3b2805b943c6e0889d9588eb1ad4d74d4949c6ea0bae3578f01508d2ca700b61
Python
2,180
79
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Dataaugmentation import copy #rdkit import rdkit from rdkit import Chem from rdkit.Chem import rdMolDescriptors from rdkit.Chem import Descriptors from rdkit.Chem import AllChem from rdkit import DataStructs #List of hydroxyl groups in the molecule def list_of_hydroxy...
2a7133c392da6be3175d45469a7aa78afbc7004afce0a630dfea474f622e755b
Python
2,181
64
import argparse import logging import os import socket import sys import numpy as np import psutil import setproctitle import torch sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) # add the FedML root directory to the python path from fedml_api.distributed.base_framework.algorithm_api imp...
6ff90968119916d3e45a56b62d92fbe418335bda25444b59420c31416fc6f95b
Python
2,181
68
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) import torch from torch_geometric.transforms import Compose from torch_geometric.datasets import QM9 as QM9_geometric f...
e369d7c89e328123c826e6d26b0ef16e9d4792b7e919b501ef254ecd7fdface4
Python
2,182
59
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> """ Builder for ODE solvers. """ from torch import Size, Tensor, nn from sbi.samplers.ode_solvers.base import NeuralODE, NeuralODEFunc from sbi.samplers...
e252cd3908c5a7f6717c99b10ac2cb2bd2177b17516b7612492f41dd6ec11165
Python
2,184
74
import json import sys class Message(object): MSG_ARG_KEY_OPERATION = "operation" MSG_ARG_KEY_TYPE = "msg_type" MSG_ARG_KEY_SENDER = "sender" MSG_ARG_KEY_RECEIVER = "receiver" MSG_OPERATION_SEND = "send" MSG_OPERATION_RECEIVE = "receive" MSG_OPERATION_BROADCAST = "broadcast" MSG_OPER...
7301ef9d9eafa6c304d5903fbff1c1c2a276be18b6df89e664f96fe3ad582534
Python
2,188
56
import numpy as np class RandomCrop3d: """ Crop the 3D numpy [c, h, w, d] and mask [h, w, d] in a sample """ def __init__(self, output_size, padding=0, training=True): assert isinstance(output_size, (int, list, tuple)) if isinstance(output_size, int): self.output_size = (o...
62242566ec9cf5f1d522cec0d8eeeb902dff2b8c9899ffe720169931d813f23d
Python
2,190
46
import logging from fedml_api.standalone.hierarchical_fl.client import Client from fedml_api.standalone.fedavg.fedavg_trainer import FedAvgTrainer class Group(FedAvgTrainer): def __init__(self, idx, total_client_indexes, train_data_local_dict, test_data_local_dict, train_data_local_num_dict, args, device, model)...
a655feeff5becf6fc2c09bfba01c91d0549577a333a4ce27fed04b2d173063c1
Python
2,192
53
import logging from .message_define import MyMessage from ....fedml_core.distributed.communication.message import Message from ....fedml_core.distributed.server.server_manager import ServerManager class BaseCentralManager(ServerManager): def __init__(self, args, comm, rank, size, aggregator): super().__i...
c0afe0573d46f55b5d19245e14db99bc8c805c3750feb1270f164875c9bb5ac9
Python
2,192
69
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed # under the Apache License Version 2.0, see <https://www.apache.org/licenses/> from __future__ import annotations import pytest import torch from sbi.simulators.linear_gaussian import diagonal_linear_gaussian, linear_gaussian @py...
a05c6ac216cfd6541d5a8650a918a836458a3c1b56f8ade3e9f4452f86568dfa
Python
2,193
60
import torch """ FedNova Optimizer comm_helper implementation cited from https://github.com/JYWa/FedNova/tree/master """ def flatten_tensors(tensors): """ Reference: https://github.com/facebookresearch/stochastic_gradient_push Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of sa...
9ea5eef4668f0e4df57f0e161411793418684d38a54389edf7ebc2a4314198ee
Python
2,198
69
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) import pytest from pytest import mark try: import NNPOps nnpops_available = True except ImportError: nnpo...
02ed42bf8ec9b562ef14acb8a216d1f802ae324931eb868c338cc2ee78125661
Python
2,200
76
from model.builders.JAMA_builders import any_cancer_JAMA import os from copy import copy, deepcopy filename = os.path.basename(__file__) data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}} training_splits = [0,1,4,6,7,9] number_repo...
40fed9e29fe1cc693148f54a774cf1332aa63225fcd202170c2611eddd0ea3ba
Python
2,200
76
from model.builders.JAMA_builders import any_cancer_JAMA import os from copy import copy, deepcopy filename = os.path.basename(__file__) data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}} # training_splits = [0,1,4,6,7,9] # number_...