sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
2fba82c5fe6c65bbc0e38d642dc59edf2c5775c6197c0b4e899279022f945f84 | Python | 3,138 | 101 | #!/usr/bin/env python3
import argparse
import os
import random
import shutil
import sys
from shutil import copyfile
UTT_PREFIX = "no7singing"
DEV_LIST = ["13", "14", "26", "28", "39"]
TEST_LIST = ["01", "16", "17", "27", "44"]
def train_check(song):
return (song not in DEV_LIST) and (song not in TEST_LIST)
def... |
82543b2bdfb3fe9a3b1ac6c47361967ab7aae082d67249c371a97d7e764f3c11 | Python | 3,139 | 90 | #!/usr/bin/env python
""" Expermiental Python Server backend test """
import logging
import os
import sys
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root_dir)
sys.pycache_prefix = os.path.join(root_dir, "dist", "pycache", "backend")
netron = __import__("source")
third_par... |
3fffe1a2b98b0143e2de86de7b9b5b7c96891d84f9d1721dfc9ad5919066ba77 | Python | 3,140 | 87 | import sys
sys.path.append("..")
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import utils
from metrics import calculate_kl as KL_DIV
import config_bayesian as cfg
from ..misc import ModuleWrapper
class BBBConv2d(ModuleWrapper):
def __init__(self... |
8f6ba8d44cff25d99467812edf9d8dbd2d521cad204bcc87889f82cdcb1c39f5 | Python | 3,144 | 76 | from configparser import ConfigParser
from distutils.util import strtobool
def str2bool(x: str):
return True if strtobool(x)==1 else False
####
# CONFIG KEYS
utils_section = "UTILS"
# data config:
data_section = "DATA"
csv_section = "CSV"
# model config:
params_section = "PARAMS"
optimizer_section = "OPTIMIZER"
#... |
fe650a16e55477ed5824cf4360f9fa851e3e392fed757598f8741a42c8d1ec91 | Python | 3,145 | 107 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# Created at:
# EMBL-HH
# Author:
# Grzegorz Chojnowski - gchojnowski@gmail.com
# =============================================================================
import os
import string
import... |
e86c44cc9bd4574f8dfd72aa8eadf17b0dbb6c854141f17d25254be96a1a0ded | Python | 3,157 | 98 | from typing import Tuple, Union, List
import eagerpy as ep
import foolbox as fbn
import foolbox.attacks as fa
from foolbox.devutils import flatten
from foolbox.attacks.fast_minimum_norm import FMNAttackLp
import pytest
import numpy as np
from conftest import ModeAndDataAndDescription
def get_attack_id(x: Tuple[FMNAt... |
4bb11306222f9f1db2c6a2894d798be50eaec875714715f5a3f7e1c8b6745a12 | Python | 3,160 | 76 | from models.med import BertConfig, BertModel
from transformers import BertTokenizer
import torch
from torch import nn
import torch.nn.functional as F
from models.blip import create_vit, init_tokenizer, load_checkpoint
class BLIP_ITM(nn.Module):
def __init__(self,
med_config = 'c... |
81675db8daf6cd2bd09fa8020376398cb08ed0ce1e44134c3f6a41683ffeda77 | Python | 3,167 | 96 | # 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... |
a0d1000615316ebe0a9132f62b9e2f661a693d65a250d5dde40ed985d40d7340 | Python | 3,171 | 81 | import numpy as np
from .common_func import crop
class RandomCrop:
"""
Crop the 2D numpy [c, h, w] and mask [h, w]/[c, h, w] in a sample
"""
def __init__(self, output_size, padding=0, training=True):
assert isinstance(output_size, (int, list))
if isinstance(output_size, int):
... |
d7aa13dcecd22264f7ea4215db37de98953592671b1eb921e6fed8a4e8255ebc | Python | 3,174 | 97 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
from mmcv import Config
from ...builder import DATASETS
from .topdown_coco_dataset import TopDownCocoDataset
@DATASETS.register_module()
class TopDownOCHumanDataset(TopDownCocoDataset):
"""OChuman dataset for top-down pose estimation.
"Pose2Se... |
9fed9823ee0543a9a91dff2bf1d5ac6d5cdb62a78606daed878df7fcb09cd87e | Python | 3,176 | 97 | import requests
import shutil
import zipfile
import tarfile
import os
import logging
from .common import sha256_hash, home_directory_path
FOLDER = ".foolbox_zoo/weights"
def fetch_weights(weights_uri: str, unzip: bool = False) -> str:
"""Provides utilities to download and extract packages
containing model w... |
dfb987885e26557d14841dd7828e8b7f2ffcdecbc1a2757b3cd4229a754c07ac | Python | 3,179 | 92 | import numpy as np
import sys
import matplotlib.pyplot as plt
class config_params():
pass
COLOR_CLUSTER = np.array([239,67,182])/256.0
COLOR_DISTRIBUTED = np.array([10,153,20])/256.0
NUMBER_OF_RUNS_DIST = 50
DISTRIB_SYNS_RANGE = list(range(0,101,25))+[110,120,125,130]+list(range(140,241,25))
NUMBER_OF_RUNS_CLUSTE... |
b919dc734df128f128e88f27f6032fb2f3250b62800965769c18c4878349968a | Python | 3,180 | 92 | # Copyright (c) 2023 IBM Research. All Rights Reserved.
#
# Code accompanying a manuscript entitled:
# "On the visual analytic intelligence of neural networks"
import math
import numpy as np
class Point():
def __init__(self, x, y=None):
if y is None and not (isinstance(x, tuple) or isinstance(x,... |
fef3801b8b3bb2f421ef736aaab313e97109cad8662814641d95b85a8c32aeea | Python | 3,180 | 82 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/11 16:17
@project: MalariaDetection
@description:
"""
from keras.models import Sequential #For initialising the model
from keras.layers import Conv2D, Add, Dropout, DepthwiseConv2D #For ... |
25d43c711482674a9738d03b119ada13c6ff74b352f1d615d8e52f16af2ad6c2 | Python | 3,186 | 98 | from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
name = '$f = sin(u) - cos(u)$'
def original_function(x):
return np.sin(x) - np.cos(x)
# Define the cubic function to fit
def cubic_function(x, a, b, c, d):
return a*x**3 + b*x**2 + c*x + d
def fix_x_in_range(xmin, xmax):
... |
6362128341775a0a18cc693c39887b4d290b61e639b9831db28a062fe8883840 | Python | 3,188 | 88 | import torch
from typing import List
def distance_matrix(msa: torch.Tensor, verbose: bool, process_id: int) -> torch.Tensor:
"""
Creates symmetric distance matrix, containing the hamming distance between each pair of sequences.
Args:
msa (torch.Tensor): MSA [num_seq, len_seq].
verbose (bo... |
a075c6f6531b2405d8fccc2d1970643e079379b54344e75ce27a827bbe37ec42 | Python | 3,188 | 97 | from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt
from oligo_designer_toolsuite.config._general_models import BlastnHitParameters, BlastnSearchParameters
from oligo_designer_toolsuite.config._types import FilesFastaReferenceDatabaseT, VCFReferenceDatabaseT
class... |
cb4d218c3d4f8f338de46347af0edc35244039d0037d9fdc07aa005e400b5482 | Python | 3,188 | 85 | import torch
from torch import nn
try:
from fedml_core.trainer.model_trainer import ModelTrainer
except ImportError:
from FedML.fedml_core.trainer.model_trainer import ModelTrainer
class MyModelTrainer(ModelTrainer):
def get_model_params(self):
return self.model.cpu().state_dict()
def set_mo... |
e7682b63de1704a809a99ae7be408604d623496e55c9e572e77d294b1dacbc17 | Python | 3,191 | 94 | from contextlib import contextmanager
from typing import Generator
import pathlib
import tempfile
import unittest
import zipfile
from ..util import UUID
class CustomAssertions(unittest.TestCase):
def assertREAppearsOnlyOnce(self, text, only_once, msg=None):
appears_once_re = \
(f'(?s)^(?:(?!{... |
df70649338a3365e4615d82e23abc3faa15ce8dcb923b66869b613a1a41b3bfe | Python | 3,192 | 85 | import cv2
import os
import numpy as np
xml_head = '''<?xml version="1.0"?>
<annotation>
<folder>VOC2007</folder>
<filename>{}</filename>
<path>{}</path>
<source>
<database>unknow</database>
</source>
<size>
<width>{}</width>
<height>{}</height>
<d... |
c974db01a25c54ee53090e8ac9750fe821070b5dbf8d2a6cb906bb14fb984567 | Python | 3,194 | 99 | import pytest
import numpy as np
from clipkit.warnings import (
warn_if_all_sites_were_trimmed,
warn_if_entry_contains_only_gaps,
)
from clipkit.helpers import SeqType
from clipkit.msa import MSA
class TestWarnings(object):
@pytest.mark.parametrize(
"header_info, seq_records, should_warn",
... |
1f3e3b17798bfb6f74b29a2866dbde75490ef126d8524c4b0283560732f80130 | Python | 3,196 | 80 | ############################################
# imports
############################################
from typing import Any
import pandas as pd
from oligo_designer_toolsuite.database import OligoDatabase
from oligo_designer_toolsuite.utils import check_if_key_in_database
from ._scorer_base import BaseScorer
#######... |
47f57a16c5025436485c9f899ff676e2318b4ae464c2ebd906932007e3790faa | Python | 3,197 | 73 | # 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... |
7b88d16e563204e757cda7c41a71798174280a5b15862ded5cf3dea5d3a9a88b | Python | 3,197 | 103 | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
from mmcv.runner import BaseModule
from ..builder import build_shared_head
class BaseRoIHead(BaseModule, metaclass=ABCMeta):
"""Base class for RoIHeads."""
def __init__(self,
bbox_roi_extractor=None,
... |
4c114bd6861f22228be46fdd08c0b1fb5d456e185f1ebd64d76c4b12b7bafaae | Python | 3,198 | 96 | import pytest
import matlab.engine
import numpy as np
import scipy
from numpy.testing import assert_allclose
from pystoi.stoi import stoi
from pystoi.stoi import FS, N_FRAME, NFFT, NUMBAND, MINFREQ, N, BETA, DYN_RANGE
RTOL = 1e-4
ATOL = 1e-4
eng = matlab.engine.start_matlab()
eng.cd('matlab/')
def test_stoi_good_fs(... |
3474b432c83dea06a706bb29d74cc73ee58f54939c9585b0f955ccc2015ba024 | Python | 3,202 | 111 | import numpy as np
import tensorflow as tf
import random as python_random
import os
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return ... |
f007fa1363e370b80befc826a857f330495892149e8f681d49b9cd35244ff9be | Python | 3,202 | 98 | import os
import sys
import math
import pytest
import unittest
import numpy as np
import torch
import torch.nn as nn
import utils
from models.BayesianModels.Bayesian3Conv3FC import BBB3Conv3FC
from models.BayesianModels.BayesianAlexNet import BBBAlexNet
from models.BayesianModels.BayesianLeNet import BBBLeNet
from mod... |
42a62208eb749d12890ef55002e004132f2d6d10ea3cb884e83b29fd3417cfb4 | Python | 3,206 | 83 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/11 16:17
@project: MalariaDetection
@description:
"""
from keras.models import Sequential #For initialising the model
from keras.layers import Conv2D, Add, Dropout, DepthwiseConv2D #For ... |
943fc336c3859f0ec8c27cdb33eb9cd530c4c526a649b47b421c204af150b47d | Python | 3,207 | 70 | import numpy as np
import matplotlib.pyplot as plt
from importlib import reload
import sys
sys.path.insert(2,'support')
import functions
reload(functions)
import functions as f
import parameters
reload(parameters)
import parameters as p
direc = sys.argv[0].split('script')[0]+'data/'
plasticity_type = sys.argv[1]
n_sim... |
ccfb327d73af4ab813c13daf55a0e668dffb0378a9927272d1ad52ea698d85e5 | Python | 3,207 | 81 | from torch.nn import CrossEntropyLoss, MSELoss
from transformers import BertModel, PreTrainedModel, BertConfig, load_tf_weights_in_bert
from transformers.modeling_outputs import Seq2SeqSequenceClassifierOutput, SequenceClassifierOutput
import torch.nn.functional as F
from model.bert_model_utils import BertPreTrainedMod... |
1678038946d4d15cc6d597e087100e16825f6ee03190d5702253717325e97692 | Python | 3,208 | 105 | from typing import Union, Tuple, Any, Optional
import eagerpy as ep
from ..models import Model
from ..criteria import Misclassification
from ..distances import l2
from ..devutils import atleast_kd, flatten
from .base import MinimizationAttack
from .base import get_criterion
from .base import T
from .base import ra... |
bdb28ecd67426a7a07d9724ddc04987da84dd9238fa8007f212be349df39a714 | Python | 3,208 | 109 | import argparse
import os
import shutil
UTT_PREFIX = "ofuton"
DEV_LIST = [
"chatsumi",
"my_grandfathers_clock_3_2",
"haruyo_koi",
"momiji",
"tetsudou_shouka",
]
TEST_LIST = [
"usagito_kame",
"my_grandfathers_clock_1_2",
"antagata_dokosa",
"momotarou",
"furusato",
]
def train_c... |
fa0afd17228cca6bfaed4a472f85cfe817474881d54b311515fa86395f40b79e | Python | 3,208 | 99 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 10:36:14 2020
@author: bariskuru
"""
import seaborn as sns, numpy as np
import os
from grid_poiss_input_gen import inhom_poiss
from grid_trajs import grid_population, draw_traj
from pearsonr_ct_bin import ct_a_bin, pearson_r
import matplotlib.py... |
3a4c61644b4ec28c83b9f1aab4a3b75ff9886903c306eaf405a0783a3fb82c01 | Python | 3,210 | 102 | import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import numpy as np
import re
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import sys
sys.path.append("../Hegemon/")
sys.path.append("../")
import StepMiner as smn
import HegemonUtil as hu... |
5b50f4e287314812bae28369430628a1f19cb547f6ce87d463421b9e00fbe715 | Python | 3,213 | 77 | import torch
import torch.nn as nn
from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer
from layers.SelfAttention_Family import ProbAttention, AttentionLayer
from layers.Embed import DataEmbedding
class Model(nn.Module):
"""
Informer with Propspare attention in O(LlogL... |
cc3df5dec4133fdf30761e7ef92679db7e379ee727ea8d49327535ac061e8fcf | Python | 3,213 | 92 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/10 16:04
@project: MalariaDetection
@description:
"""
import glob
import os
import numpy as np
from PIL import Image
class Dataset(object):
def __init__(self, path, dataset='dataset1')... |
d9f28fbafbf265c175b875edc6dcc414a3108ea4a1cc2057992106a690dc9b76 | Python | 3,215 | 102 | # Copyright (c) OpenMMLab. All rights reserved.
import asyncio
import os
import shutil
import urllib
import mmcv
import torch
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector)
from mmdet.utils.contextmanagers import concurrent
from mmdet.utils.profiling impor... |
d1185e2eebc4fb87ba732ab903db6d07a264d71e9ff9cb41b1ae26c1e28f30e6 | Python | 3,222 | 108 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmpose.core import (aggregate_scale, aggregate_stage_flip,
flip_feature_maps, get_group_preds, split_ae_outputs)
def test_split_ae_outputs():
fake_outputs = [torch.zeros((1, 4, 2, 2))]
heatmaps, tags... |
2731e27d54bc5075a0bd2cd770580ea949ecfd46c112c81594bb9d9684c4614c | Python | 3,226 | 83 | import sys
sys.path.append("..")
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from metrics import calculate_kl as KL_DIV
from ..misc import ModuleWrapper
class BBBConv2d(ModuleWrapper):
def __init__(self, in_channels, out_channels, kernel_size,
... |
29ccb0e9272d02794edc8416701f0c181f54bbe6ed33d72856f9b47c98b2bc77 | Python | 3,231 | 105 | import argparse
import math
import os
import pandas as pd
import numpy as np
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader
from teeth_dataset import TeethDataset, RandomRemoveTeethTransform, UnitSurfTransform
from teeth_nets import MonaiUNet
import utils
from vtk.util.numpy_support im... |
8aafead1ee319b266bedba0fbde28af560556157b83f0822303a0e9f2bb6506c | Python | 3,232 | 86 | # Author: Fabi Prezja <faprezja@fairn.fi>
# Copyright (C) 2023 Fabi Prezja
# License: MIT License (see LICENSE.txt for details)
import tensorflow as tf
import numpy as np
from PIL import Image, ImageFilter
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def variable_gaussian_blur ( img , max_radiu... |
2dbbaf7de966c5d7479add2453591735e7365a2a1f06f3e63cca73637840f649 | Python | 3,233 | 86 | import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from absl import app, flags, logging
import sys
sys.path.append('../')
from jax.config import config
import tensorflow as tf
import os
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false'
tf.config.set_visible_devices... |
1f7fb527ea25ccba59b3f38dde8469af535454843be3743b9996d8c23322251f | Python | 3,234 | 101 | import argparse
import os
import shutil
UTT_PREFIX = "csd"
DEV_LIST = ["046"]
TEST_LIST = ["047", "048", "049", "050"]
def train_check(song):
return not test_check(song) and not dev_check(song)
def dev_check(song):
for dev in DEV_LIST:
if dev in song:
return True
return False
def ... |
50245e63de5e628e1b426ab55fdd44abfc7bc3e8e3d6f33715157327b50d4943 | Python | 3,236 | 83 | # 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 os.path import join, exists
from pytest import mark, raises
import torch
from torchmdnet.utils import make_splits
... |
96d53e4630f4defa8244854d092b9df247575ccf74288ba4fef8ca433929952a | Python | 3,236 | 87 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/13 15:42
@project: MalariaDetection
@description:
"""
from keras.layers import * #For adding convolutional layer
from keras.layers import MaxPooling2D #For adding max pooling layer
from k... |
560d3874a2f3a0ed4cb21efde35eb341a20395c1f716e23b8f33e06264b30f4f | Python | 3,238 | 110 | from typing import Union, Optional, Any
import numpy as np
import eagerpy as ep
from ..devutils import atleast_kd
from ..distances import Distance
from .base import FlexibleDistanceMinimizationAttack
from .base import Model
from .base import Criterion
from .base import T
from .base import get_is_adversarial
from .ba... |
69c5a34b894a7771606114b391f1f6ab0e45c078b49fb90f24ea3e35394dc1b7 | Python | 3,239 | 92 | # 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/>
import pytest
import torch
from torch import eye, ones, zeros
from torch.distributions import MultivariateNormal, Normal, kl_divergence
from sbi.diagnost... |
59ccb5446052508dc043fe4b23f2825346454a1d7624b0a47bd4845552f79c07 | Python | 3,241 | 145 | import os
import pprint
import subprocess
import logging
import random
import json
import numpy as np
import torch
_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class AttrDict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def get_device():
return _device
... |
cd11f24245ea89ccdf17405f59f92233b8ba904adf5f88db51c38aa7af505f21 | Python | 3,245 | 92 | from entity_centric_es import EntityCentricES
import json
from mimicdao import get_mimic_doc_by_id, get_doc_types, get_doc_dates
import utils
from os.path import isfile, join
from os import listdir
_f_yodie_anns = './sample_anns/'
def do_index_mimic(line, es, patients):
ann_data = json.loads(line)
doc_id = ... |
1f50e7f7f8f7da747c26752b64773a418dc0789824aa0de7dded822612441340 | Python | 3,248 | 86 | """
Generalized perspective projection
See:
https://csc.lsu.edu/~kooima/articles/genperspective/index.html
"""
import numpy as np
from flystim import normalize, rotx, roty, rotz
class GenPerspective:
def __init__(self, pa, pb, pc, pe=(0, 0, 0), near=0.0001, far=1000, fly_pos=(0, 0, 0), horizontal_flip=False):
... |
8e50cc724f0f2f4a5f8e4e405030732765bda480283ab2f9f67011b06326c0bb | Python | 3,250 | 72 | import os
import cv2
import numpy as np
import scipy.io as scio
from csutil import util
if __name__ == '__main__':
root_dir = 'E:/Zhu/ETreg/newdata/HUA3/'
stackdir = root_dir + '/TOM/stack/ori/'
TEMs_reg_config_dir = root_dir + '/reg_config/TEMs/'
TOM_reg_config_dir = root_dir + '/reg_config/TOM/'
... |
c538ebec6ba5165c144ea8f2f6f06e4ff76189382f63fb76f579834039738b07 | Python | 3,252 | 83 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch
from ..builder import BBOX_CODERS
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class YOLOBBoxCoder(BaseBBoxCoder):
"""YOLO BBox coder.
Following `YOLO <https://arxiv.org/abs/1506.02640>`_, this coder divide... |
0aab2d26a9ac2612af154a2b32e5b414b9ea20efaf89b3a8d50650eacd10e8b4 | Python | 3,253 | 110 | from scipy.optimize import minimize
from scipy.stats import poisson, norm
import numpy as np
import matplotlib.pyplot as plt
def photon_count(img, gain, offset=100):
"""remove the offset and divide by gain.
The output image is rounded to int values"""
norm_img = np.round((img.astype(float)-100)/gain).ast... |
918a8a710ecd03a1f65a4f66fe2ee9e58a94070a6f5cab8dd9b6688c3afb955c | Python | 3,253 | 78 | """
Fig 5e with and without the lexical predictability control (Reviewer 1, 1.3).
Fig 5e reports the proportion of the unique semantic neural variance in IFG-Tri
that SFM representations absorb:
delta = (ref - low) / ref
`ref` is the mean IFG-Tri unique semantic R^2 against the non-semantic
interpretable feature... |
8608b7abb729243923d0cfdecfad2bae171e606151280ac949e80e99ee02806f | Python | 3,255 | 92 | """Scripts used to analyse bcftools roh output."""
import sys
import argparse
from itertools import islice
from operator import itemgetter
def list_mean(list):
"""Calculate the mean of a list with numbers."""
mean = float(sum(list)) / float(len(list))
return mean
def get_roh_regions(roh_file):
"""Cr... |
c8eb5f58ba9fe88c8171ca7069f313a9f78504bfbe1f9f4638835cde31c03034 | Python | 3,257 | 114 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmdet.models.roi_heads.roi_extractors import GenericRoIExtractor
def test_groie():
# test with pre/post
cfg = dict(
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2),
out_channels=256,
featm... |
f6bbbc0e93265a78543c5de832e08e5e25aa522b25652d3cdfb7d82c2a8b1299 | Python | 3,261 | 105 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
from collections import Sequence
from pathlib import Path
import mmcv
from mmcv import Config, DictAction
from mmdet.core.utils import mask2ndarray
from mmdet.core.visualization import imshow_det_bboxes
from mmdet.datasets.builder import build_... |
730fff949aa8b09f25919ec747fbf6d7ff44b93b6d417ab99128922d1ce18299 | Python | 3,263 | 103 | #!/usr/bin/env python
# -*- coding: UTF-8 -*
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from lv import louvainModularityOptimization
from defs import Control
from embed import multilevel_embed
from refine_model import GCN, GraphSage
from utils import read_graph, setup_custom_logger,loadDataSet,n... |
d0d4a563815b739d86d1641727f72a3a31ed5ce5cdeab40a8cb375f4061a1403 | Python | 3,271 | 84 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.cnn.bricks import build_plugin_layer
from mmcv.runner import force_fp32
from mmdet.models.builder import ROI_EXTRACTORS
from .base_roi_extractor import BaseRoIExtractor
@ROI_EXTRACTORS.register_module()
class GenericRoIExtractor(BaseRoIExtractor):
"""Extr... |
3b4ae85e5b91b5228fcb9cc066a3b2be7d386a07fe240f4061138d94f52df404 | Python | 3,277 | 100 | import vtk
import numpy as np
class LinearSubdivisionFilter:
InputData = None
Output = None
NumberOfSubdivisions = 1
def SetInputData(self, polydata):
self.InputData = polydata
def GetOutput(self):
return self.Output
def SetNumberOfSubdivisions (self, subdivisions):
self.NumberOfSubdivisions = subdivi... |
1018ce5a3a3b57ddae0bf1080aa3324720e769ce80b812e7bc22112a9d015c3c | Python | 3,282 | 64 | """Public shared-kernel replay on moving, permuted mixed-size molecular batches."""
import pytest
import torch
from conftest import CAFFEINE_FILE, TAXOL_FILE, load_mol
from aimnet.calculators import AIMNet2Calculator
pytestmark = [pytest.mark.gpu, pytest.mark.weights]
@pytest.mark.parametrize("model", ["aimnet2", ... |
3357362d55180412c57a86f38e211aaa78162e34b401ed300f61963432e9311b | Python | 3,284 | 102 | """
Generate high-frequency predictions and aggregate them using hard or soft majority voting.
This script runs inference on a dataset and saves aggregated 30s-predictions for each subject.
Usage: see run.md in config folder
The script:
1. Loads the trained model specified in the config
2. Runs inference on the data... |
e802a20568a33f7d9d1882463dda0022a40789ce0b88a6bdb71a9606939c7fc5 | Python | 3,285 | 93 | import os
import sys
import numpy as np
import h5py
import scipy.io as spio
import nibabel as nib
import scipy as sp
from PIL import Image
import argparse
parser = argparse.ArgumentParser(description='Argument Parser')
parser.add_argument("-sub", "--sub",help="Subject Number",default=1)
args = parser.parse_args()
su... |
35e54e25615ed36016412455555f5c274be612ff17c36b8adc07741970246ad5 | Python | 3,287 | 92 | from __future__ import annotations
from typing import MutableMapping, Iterator, TypeVar, Generic, Dict, Optional, Callable, Set
_VT = TypeVar("_VT")
_ST = TypeVar("_ST")
class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):
"""
A class wrapping a dict with string keys in a read-only fashion. P... |
ed6648fc316730ef14efbc638f843cc434d1b6b86a12c3365c81ddedef6caa3c | Python | 3,287 | 86 | import torch
from torch import nn
try:
from fedml_core.trainer.model_trainer import ModelTrainer
except ImportError:
from FedML.fedml_core.trainer.model_trainer import ModelTrainer
class MyModelTrainer(ModelTrainer):
def get_model_params(self):
return self.model.cpu().state_dict()
def set_mo... |
b9510ed4b8ceb3ae03cec6d0181fa8100c0cfba189c982b65cf878f05dba47d5 | Python | 3,290 | 101 | import requests
import xml.etree.ElementTree as et
import traceback
import json
import utils
from os.path import join
import os
europepmc_full_text_url = 'http://www.ebi.ac.uk/europepmc/webservices/rest/{}/fullTextXML'
europepmc_search_url = 'http://www.ebi.ac.uk/europepmc/webservices/rest/search?' \
... |
0f457c04101d9a0bfa9dfa435c7ae63483a853e40420a7521ccbe4b0af7f5ec1 | Python | 3,291 | 91 | # translate coco_json to xml
# 使用时仅需修改21、22、24行路径文件
import os
import time
import json
import pandas as pd
from tqdm import tqdm
from pycocotools.coco import COCO
def trans_id(category_id):
names = []
namesid = []
for i in range(0, len(cats)):
names.append(cats[i]['name'])
na... |
5fed4def9ec9f043c8c5d1ec1075acafffa7a5c431b1cf2791965af309484525 | Python | 3,292 | 65 | #!/usr/bin/env python3
# Author: Francois Aguet
import argparse
import os
import subprocess
import contextlib
from datetime import datetime
@contextlib.contextmanager
def cd(cd_path):
saved_path = os.getcwd()
os.chdir(cd_path)
yield
os.chdir(saved_path)
def get_cmd(args):
cmd = os.path.join(fastqt... |
9bff97f6b07ba6b76c62617d0c6bd3bb8151ea269488f3ae348cc604e9bd3eeb | Python | 3,295 | 102 | import torch
import numpy as np
#from mpi4py import MPI
import socket
import argparse
import os
import json
import subprocess
from hps import Hyperparams, parse_args_and_update_hparams, add_vae_arguments
from utils import (logger,
local_mpi_rank,
mpi_size,
maybe_... |
b5df3a94c01c438e17d8ddc67884f1b7abd97a709063f16759894fcf2e49c144 | Python | 3,295 | 100 | import sys,traceback
import os
from p4.var import var
import p4.func
def invoke_editor(extractedTraceback):
p4.func.writeInColour("\nWhere do you want to go? ...\n", colour="blue")
te = extractedTraceback
for teItemNum in range(len(te)): # te is a traceback.extract_tb() result
theTeItem = te[teIt... |
3887768b344348046e16344e3a6fdaf2c8533ea823511f1efddc6212435b364d | Python | 3,297 | 105 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import json_tricks as json
from mmcv import Config
from xtcocotools.cocoeval import COCOeval
from mmpose.datasets.builder import DATASETS
from .bottom_up_coco import BottomUpCocoDataset
@DATASETS.register_module()
class BottomUpAicDataset(BottomUpCocoD... |
5f2da425506cfa027332e5ea38458dcae1210288fc6519a3763a05c5e4e2b38b | Python | 3,297 | 141 | #! /usr/bin/env python
import os
import re
import sys
import argparse
BEG=0
END=1
CN=2
VCF_CHR=0
VCF_BEG=1
VCF_END=2
VCF_SIZ=3
VCF_CNV=4
VCF_FILTER=5
VCF_PROG=6
VCF_INFO=7
RAW_NAME=2
# supposedly a[0] <= b[0];
def ov ( a, b ):
if a[BEG] > b[BEG]:
raise Exception ('ov wrong tuple'+str(a)+','... |
102c9544d001b186f92a77b3a47064d652a978ca560a043e9b13ab3fb52cc514 | Python | 3,299 | 84 | import torch
from torch import nn
try:
from fedml_core.trainer.model_trainer import ModelTrainer
except ImportError:
from FedML.fedml_core.trainer.model_trainer import ModelTrainer
class MyModelTrainer(ModelTrainer):
def get_model_params(self):
return self.model.cpu().state_dict()
def set_mo... |
20f7b01dce7ef5201fc41965c1f847ee3eb35fc477c59bf1def494d42f436106 | Python | 3,301 | 92 | """
This class tests that you can properly pickle fit objects.
The old version used the reference datasets, but I think this isn't necessary;
it is totally reasonable just to use synthetic data, since this is cleaner
and requires less overhead (making this file easier to read).
"""
from numpy.testing import assert_equ... |
49bb5c40056a884cd85c55ec4cf6e7674d20abfde10fefa44ab533c199f8bdee | Python | 3,304 | 71 | import os.path
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random
class UnalignedDataset(BaseDataset):
"""
This dataset class can load unaligned/unpaired datasets.
It requires two directories to host training images from... |
07c02eeced39a080078e187526325c858ef3aeeb701d904c0397c9740ecb997e | Python | 3,309 | 91 |
import pandas as pd
from os.path import dirname, join
import numpy as np
import gcsfs
fs = gcsfs.GCSFileSystem(project='profile-notes')
input_dir = 'radiology-impressions-derived-data'
dir_path = dirname(dirname(__file__))
import logging
class ManualLabels():
def __init__(self, outcome = 'any_cancer', text = ... |
95c16c6fbd706bc9d13bd2dd712f96d76ed62c03f257f57f3b37954e731b2918 | Python | 3,312 | 92 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch.nn as nn
from ..builder import LOSSES
from .utils import weighted_loss
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def gaussian_focal_loss(pred, gaussian_target, alpha=2.0, gamma=4.0):
"""`Focal Loss <https://arxiv.org/abs/1708.0... |
13912c1558465b5da870d898a8d0e409a2c5632e121349fe1e5d08cd4b2670b8 | Python | 3,313 | 87 |
import h5py
import numpy as np
val_ids = ['Breast_TCGA-A7-A13E-01Z-00-DX1_3',
'Prostate_TCGA-G9-6363-01Z-00-DX1_11',
'Breast_TCGA-AR-A1AS-01Z-00-DX1_11',
'Prostate_TCGA-G9-6356-01Z-00-DX1_6',
'Kidney_TCGA-B0-5711-01Z-00-DX1_11',
'Prostate_TCGA-G9-6356-01Z-00-DX1_2',
'Liver_TCGA-18-5592-01Z-00-DX1_2',
'Liver_TC... |
9a0aa659989f4779e972cfbca01738f0443cd41347d9b7fb6a6b2d8f049d052e | Python | 3,315 | 85 | import numpy as np
import pickle
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]
# Load ROI Masks
with open('data/regression_weights/subj{:02d}/vdv... |
d2bc1ebe32fe5c66298988c3fe92f6f59561a07349339178b50ecf1dd8bdc87d | Python | 3,316 | 91 | import glob
import shutil
import os
import pandas as pd
import logging
import paramiko
df = pd.read_excel('2_list.xlsx', skiprows = 1)
empiar_ids = df['EMPIAR_ID']
# empiar_ids = ['10467', '10495', '10682']
SOURCE_ADDRESS = '/gpfs/alpine/bif135/scratch/ashwind/CryoEM/data_curation/'
DESTINATION_ADDRESS = '/bml/CryoEM... |
0515d6d694e7deeb4cb4c7747486f1a644435b8ba79d3e01c03065a289b89c61 | Python | 3,318 | 94 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import xavier_init
from ..builder import HEADS
from ..utils.geometry import rot6d_to_rotmat
@HEADS.register_module()
class HMRMeshHead(nn.Module):
"""SMPL parameters regressor head of simple baseli... |
e9f9e38bbeeeed430ad30546988bd303b8d8d7ea649851322954dfc3b69d70a5 | Python | 3,318 | 103 | import numpy as np
import jax.numpy as jnp
import jax
from einshape import jax_einshape as einshape
import pickle
from functools import partial
import os
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false'
import sys
sys.path.append('../')
sys.path.append('../data_preparation/')
sys.path.append('../data_preparation... |
0ab3acea9df923623de36071e956a703e3dd402df63b40f9874279912bab87ce | Python | 3,319 | 98 | #https://mapie.readthedocs.io/en/stable/examples_regression/2-advanced-analysis/plot_nested-cv.html#sphx-glr-examples-regression-2-advanced-analysis-plot-nested-cv-py
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import randint
from sklearn.ensemble import RandomForestRegressor
# from sklearn.metr... |
4d3e5c852be969eed76248c38e4d3fdec890145421233d4de9a1ee4f04428398 | Python | 3,320 | 68 | """
Implements the knowledge distillation loss
"""
import torch
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taking a teacher model prediction and using it as additional supervision... |
f0a4d9ae1d365744247b2d65c8f71c89ffc9e15e7907d9b4a4867c1f1602a596 | Python | 3,322 | 79 | import pathlib
import unittest
import zipfile
from .test_parse import TEST_DATA
from .testing_utilities import CustomAssertions
from ..util import get_root_uuid, get_nonroot_uuid, camel_to_snake
class CamelToSnakeTests(unittest.TestCase):
def test_camel_to_snake(self):
some_types_n_formats = [
... |
2f98dde8a5e4d1c375a8a4bce30bae1240c7ec7f7fe3d609214b123add6e1f05 | Python | 3,324 | 115 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
from typing import List, Optional, Tuple
from torch import Tensor
from torch.nn import Module
from torch_geometric.explain.algorithm.gnn_explainer import (
GNNExplainer_ as GNNExplainer,
)
from serenityff.charge.gnn.utils import Cust... |
7dd1217395af79c109928c51db53613ae60e4d23469b6585df724a46ccd013f6 | Python | 3,324 | 102 | # 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 yaml
from os.path import dirname, join
import torch
from torch_geometric.data import Dataset, Data
def load_ex... |
02f20d703c763cca74a9c428adb4700d628781af251e0d9dbe870dec2ae716aa | Python | 3,326 | 88 | import os
import numpy as np
import h5py
import torch
from torchvision.utils import save_image
import onnxruntime
import maths_new
import utils.helpers
CONFIG_PATH = './configs'
def main(args):
config = utils.helpers.load_config(CONFIG_PATH, args.config)
data_path = os.path.normpath(confi... |
437264c8d720d22149934b0be867c1d4233f8439a2b5cd37d2f4facb4aa97823 | Python | 3,327 | 113 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
from mmpose.core.post_processing.nms import (nearby_joints_nms, nms, oks_iou,
oks_nms, soft_oks_nms)
def test_soft_oks_nms():
oks_thr = 0.9
kpts = []
kpts.append({
'keypoi... |
54140d1ba05792fb1e94095cb7517bec38e3df6453712b020e6979f4f3f11dfe | Python | 3,330 | 84 | import torch
from torch import nn, optim
class HostTrainer(object):
def __init__(self, client_index, device, X_train, X_test, model_feature_extractor, model_classifier, args):
# device information
self.client_index = client_index
self.device = device
self.args = args
# tra... |
a29d7bcb5f75afdbd869787f05e52223d97260a0d7d48589e2d0926ced0c0e10 | Python | 3,331 | 118 | import argparse
import json
import os
import shutil
import random
import librosa
import miditoolkit
import numpy as np
from espnet2.fileio.score_scp import SingingScoreWriter
"""Generate segments according to structured annotation."""
"""Transfer music score into 'score' format."""
def makedir(data_url):
if os... |
ab63f47e3217336a3215d3bcdb0002c8d384d89d36478b29a138ff9fe59e7d73 | Python | 3,331 | 94 | #!/usr/bin/env python
from os import path
project_dir = path.dirname(path.abspath(__file__))
default_ref_dir_bac = path.join(project_dir, "default_files", "bacteria",
"bac_ref")
default_ref_dir_arc = path.join(project_dir, "default_files", "archaea",
"arc_ref"... |
be0d326108912f37ed0836744802a9e627aee7868ed8c45544a3619cd1adc177 | Python | 3,333 | 84 | import argparse
from typing import Dict
import pandas as pd
# noinspection PyUnresolvedReferences
import matplotlib_setup
# noinspection PyUnresolvedReferences
import osgeo_setup
import argparse_def
import reference_data_utils
from models.abstract import input_data
from scope_utils import Extent
from reference_data_u... |
7c1bb30b5be79b83e6e711814e7e2d3d9b852e2396f958046bbe06db4aeef5c1 | Python | 3,338 | 79 | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source... |
8af3b1cd86a23f77e29041e729487f51ec7590dd049b2087fe7eead1b96a8684 | Python | 3,338 | 79 | import tensorflow.compat.v1 as tf
import numpy as np
def compute_pairwise_distances(x, y):
"""Computes the squared pairwise Euclidean distances between x and y.
Args:
x: a tensor of shape [num_x_samples, num_features]
y: a tensor of shape [num_y_samples, num_features]
Returns:
a distance matrix of di... |
dc91b21f304db0ff16a80e73b94080cf7d602635e805b3b16754b7f585c2c33d | Python | 3,339 | 80 | import os, sys
import argparse
import torch
from connectomics.utils.system import init_devices
from connectomics.config import load_cfg, save_all_cfg
from connectomics.engine import Trainer
from connectomics.config import get_cfg_defaults, save_all_cfg, update_inference_cfg
from connectomics.engine import Trainer
imp... |
1f3837c3346d660007e13e7e80ca70ab510dec44ae330426617dfc99b8afc3f9 | Python | 3,340 | 121 | import argparse
import os
import shutil
UTT_PREFIX = "pjs"
DEV_LIST = [
"pjs002",
"pjs0012",
"pjs022",
"pjs032",
"pjs042",
"pjs052",
"pjs062",
"pjs072",
"pjs082",
"pjs092",
]
TEST_LIST = [
"pjs007",
"pjs017",
"pjs027",
"pjs037",
"pjs047",
"pjs057",
"p... |
3ad769acc370b95baa87e20fd545b84b95e6522a8653bc1abd4c5a252f1e2628 | Python | 3,340 | 107 | import dataclasses
import typing
from osgeo import osr
from geotransformations import pix_to_geo
from scope_utils import Scope, Extent
_T = typing.TypeVar("_T")
@dataclasses.dataclass
class WithSrs(object):
srs: typing.Union[str, osr.SpatialReference]
@dataclasses.dataclass(init=False)
class GeoreferencedDat... |
ca2d69a558401a8587bdbf21862848bf96634d10ce26dc225676c64d6d61826c | Python | 3,341 | 118 | # 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/>
import warnings
from typing import TYPE_CHECKING
from sbi.inference.abc import MCABC, SMCABC
from sbi.inference.trainers.base import (
NeuralInferenc... |
cf5a1fc688265eb9891835781a6de173fa05163ac9c10ccdb18e50e3c8cf9c1c | Python | 3,342 | 89 | import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from simple_mlps.datas import ParcellationData
from simple_mlps.simple_models import _MLP_Surv
class NNSurvLoss(nn.Module):
def __init__(self, bins: torch.Tensor):
self.bins = bins
self.bin_centers = (bins[0, 1:] + bin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.