sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
0912182c882b1855e68fd13006fc33e99b728676f606779e856016767aaa0f95 | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat4(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
3b5e8ac48e457f697718ea535d65620c6e8588fd628e7bccc7edeb637067f9d1 | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat3(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
80ac434a1bfa693439be55009a85a9e8b020315b92e6838445024ea5ff40903a | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat7(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
ae88dbaf4c07a2b9f69787917e156275e61202f08d08e82c4f957c4f17290709 | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat5(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
b2eb2dc1fea0744da2979573b5f3ad774939cf8caafe5d912c08e06c69cb791c | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat2(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
db5f50d21edded7beed250f51b961044224012b941ac7ad5ddb8c87241944f48 | Python | 374 | 13 | var.verboseRead = 0
read('d.nex')
d = Data()
print("\n") # put in a couple of spaces
ret = d.compoChiSquaredTest(verbose=1)
print("""
The p4 output above is there because 'verbose' was turned on. For
programmatic usage, you would want to turn it off. In that case you
can get the numbers from the list of lists that th... |
ec555803c58037911832283bf4d1fa0f3e71b3116f8a1ec6fc94ebb444da56b0 | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat1(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
fd86822595ab1722a570db39f92a7b069bc3bc29693758f6aa29ed9090e392e5 | Python | 374 | 15 | import numpy as np
import torch
from metric.dice import one_cls_dice
def dice_cat6(output, target, misc):
"""
Calculate dice for all channels.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:return:
"""
... |
24c547474e3555af1f2cf94af2f338ef373f45b17da53e229d39645d4242432c | Python | 375 | 10 | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
class BaseAssigner(metaclass=ABCMeta):
"""Base assigner that assigns boxes to ground truth boxes."""
@abstractmethod
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
"""Assign boxes ... |
7dbab903b9cd50f3e4a073bef320c7a2ebc61ece18bac3916fff085c39a159e3 | Python | 375 | 12 | """Backend utilities for :mod:`keras2c`.
This module exposes the Keras API used throughout the project. By keeping the
backend import in a single place it becomes easier to switch to a different
deep learning framework in the future. Currently TensorFlow's Keras
implementation is used which requires TensorFlow 2.x.
"... |
5f4f8bb2e394e0b84b02d665076a39dabc60b0ed109d187a8fb6d0c1f37ebb28 | Python | 382 | 11 | # Copyright (c) OpenMMLab. All rights reserved.
from .builder import build_filter
from .gaussian_filter import GaussianFilter
from .one_euro_filter import OneEuroFilter
from .savizky_golay_filter import SavizkyGolayFilter
from .smoothnet_filter import SmoothNetFilter
__all__ = [
'build_filter', 'GaussianFilter', '... |
0374ce5f2d724e9a72931fc7d803ab5a2d18fc37020a77f6e99f058b03340309 | Python | 383 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .distributed_sampler import DistributedSampler
from .group_sampler import DistributedGroupSampler, GroupSampler
from .infinite_sampler import InfiniteBatchSampler, InfiniteGroupBatchSampler
__all__ = [
'DistributedSampler', 'DistributedGroupSampler', 'GroupSampl... |
ae7ef7e2a1bba0bb27b97f34498c169c0c5b078c7e1fa1cfcc1568d321c2bfd8 | Python | 383 | 19 | # Read in the tree and the data
read('t.nex')
t = var.trees[0]
read('d.nex')
# Make a Data object and attach it to the tree.
t.data = Data()
# Define the model. This is the Juke-Cantor model with no among-site
# rate variation.
t.newComp(free=0, spec='equal')
t.newRMatrix(free=0, spec='ones')
t.setPInvar(free=0, val... |
a62eb1ee3973b6342f40f9477572a440d23a384521279e9e64ead391001cddf2 | Python | 386 | 16 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 21 14:59:42 2022
@author: Daniel
"""
import numpy as np
import os
def read_binary(file_path, input_type=np.int16):
return np.fromfile(file_path, dtype=input_type)
if __name__ == '__main__':
example_file = r'D:\mizuseki\extracted\ec016.665.tar\ec016.665\ec01... |
1130e455f54bc45803a4f4cbd80b95fa40249df786856d8dffdaf26181c48fcf | Python | 387 | 21 | """Logging and sending output to stdout code"""
import os
import sys
# Disable
def blockPrint():
sys.stdout = open(os.devnull, "w")
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
class Printer:
"""Print things to stdout on one line dynamically"""
def __init__(self, data):
sys.st... |
19da9b381858d2ab1d43d98d6049909f51ff2cc6676367397d91bddbbce7833c | Python | 387 | 13 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 17:20:44 2021
@author: fhu14
"""
from .data_loader import data_loader
from .h5handler import per_molec_h5handler, per_batch_h5handler,\
compare_feeds, total_feed_combinator
from .feed_saver import save_feed_h5
from .feed_loader import load_combined_fold
from .gamm... |
2755760fe6626c3b248ffe6f571ebed6d7d5ffc70f3e789d0d871529922aff9d | Python | 387 | 10 | # Copyright (c) OpenMMLab. All rights reserved.
# flake8: noqa
import pytest
def test_old_fashion_registry_importing():
with pytest.warns(DeprecationWarning):
from mmpose.models.registry import BACKBONES, HEADS, LOSSES, NECKS, POSENETS # isort: skip
with pytest.warns(DeprecationWarning):
from... |
60d0654ea603db605f64e58521364d6e6ecadef6ebe92e6dd55fd3a812737cd1 | Python | 390 | 16 | checkpoint_config = dict(create_symlink=False, interval=1)
# yapf:disable
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
custom_hooks = [dict(type='NumClassCheckHook')]
dist_params = dict(backend='nccl')
log_level =... |
cc7b3b73f50bb5cecea41909177899ecb885751cb6af4e3526e2dca31cd1f27e | Python | 390 | 13 | from distutils.core import setup
setup(
name='daart',
version='0.0.0',
description='a collection of tools for analyzing behavioral data',
author='matt whiteway',
author_email='',
url='http://www.github.com/themattinthehatt/daart',
# install_requires=[
# 'numpy', 'matplotlib', 'sklea... |
bb9cc55851c55ae3692fd53e7d4431aec42a69a24294b7a6340c1477429dae37 | Python | 391 | 19 | class MyMessage(object):
"""
message type definition
"""
# message to neighbor
MSG_TYPE_INIT = 1
MSG_TYPE_SEND_MSG_TO_NEIGHBOR = 2
MSG_TYPE_METRICS = 3
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER = "sender"
MSG_ARG_KEY_RECEIVER = "receiver"
"""
message payl... |
223876920869da86e2d2fc37b27dea3672ad7b8fd81aed2c0c545cda67e85bb0 | Python | 394 | 16 | var.warnReadNoFile = 0
var.verboseRead = 0
read('protein.nex')
a = var.alignments[0]
a.recodeDayhoff()
#a.writePhylip(None)
read('(((A:0.4, (B:0.4, C:0.4):0.05):0.05, D:0.4):0.1, E:0.4, F:0.4);')
t = var.trees[0]
t.data = Data()
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGamma... |
3ed475134ebcb4122352c8e6e444b1d40cea9997644838603113e1309ec3fedb | Python | 394 | 15 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
def command_to_shell_file(command: str, filename: str) -> None:
"""
Writes a string to a .sh file
Args:
command (str): string to be written
filename (str): path to file
"""
with open(filename, "w") as ... |
bee7e11af33db7c3e287d14e37ebe481155c83e0c3193ba1d8279ea0f7824fa3 | Python | 397 | 12 | from IPython import get_ipython
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
import traceback
from p4.interactive.excepthook import invoke_editor
te = traceback.extract_tb(tb)
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
invoke_editor(te)
# Tell IPython to use it for... |
b4111a1544c8d4a220d760149ecda0de19918e82dc88bbf9cce679c31cde6aa2 | Python | 398 | 14 | ls = LeafSupport('../input.nex')
# Defining a tax set will create a list of stabilities using only
# quartets or triplets defined by the members of set. This allows the
# user to investigate any set of taxa and there relative stabilities.
ls.defineTaxSet(['Eusthenoperon','Baphetes', 'Megalocephalus',
... |
80995a87e2baff57403750911d8b6381c109708fbf8309248af7cbf0ab2c5780 | Python | 399 | 12 | from os.path import join
import logging
def save_prediction(directory, info, y_pred, y_test, model_name, training=False):
if training:
file_name = join(directory, model_name + '_traing.csv')
else:
file_name = join(directory, model_name + '_testing.csv')
logging.info("saving : %s" % file_nam... |
9ead880938587f49fea6b8671384bce3f95be93e988a5bc80effdfa13a383aae | Python | 399 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .anchor import * # noqa: F401, F403
from .bbox import * # noqa: F401, F403
from .data_structures import * # noqa: F401, F403
from .evaluation import * # noqa: F401, F403
from .hook import * # noqa: F401, F403
from .mask import * # noqa: F401, F403
from .post_pr... |
1d325e790f3761fd3edc6e94c4f16eb77ea44ed57bf688c8d4070fab9e5fb739 | Python | 400 | 16 | from setuptools import setup, find_packages
setup(
name='attention',
version='5.0.0',
description='Keras Attention Layer',
author='Philippe Remy',
license='Apache 2.0',
long_description_content_type='text/markdown',
long_description=open('README.md').read(),
packages=find_packages(),
... |
6db583332528caedc09efb7067deb337b203b73e96f6c4cfb66812aa35275771 | Python | 402 | 31 | # M_RNN
#RNN_HID_SIZE = 64
#IMPUTE_WEIGHT = 0.3
#LABEL_WEIGHT = 1
# GRU_D
#RNN_HID_SIZE = 100
#IMPUTE_WEIGHT = 0.3
#LABEL_WEIGHT = 1
# RITS_I
#RNN_HID_SIZE = 108
#IMPUTE_WEIGHT = 0.3
#LABEL_WEIGHT = 1
# BRITS_I
#RNN_HID_SIZE = 64
#IMPUTE_WEIGHT = 0.3
#LABEL_WEIGHT = 1
# RITS
RNN_HID_SIZE = 100
IMPUTE_WEIGHT = 3
LAB... |
87f26db7f2e0f2f6a60b07bcebc1a4698e2b6fe1d0687579e153018f770046a3 | Python | 403 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .bbox import * # noqa: F401, F403
from .camera import * # noqa: F401, F403
from .evaluation import * # noqa: F401, F403
from .fp16 import * # noqa: F401, F403
from .optimizers import * # noqa: F401, F403
from .post_processing import * # noqa: F401, F403
from .u... |
25c61a74ed3516cc4f15781a185c3d7b4b4ee8846d6676b39b0d08454246c09f | Python | 408 | 13 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from packaging import version
_torch_version_meshgrid_indexing = version.parse(
torch.__version__) >= version.parse('1.10.0a0')
def torch_meshgrid_ij(*tensors):
if _torch_version_meshgrid_indexing:
return torch.meshgrid(*tensors, indexing='... |
d596f8cb37a2fb0de63468d83a22a9332eb7b81c1b837db92b5e4fcd2ee3a0eb | Python | 408 | 16 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
"""Classes and functions used by different submodules."""
from .exceptions import ExtractionError, NotInitializedError
from .io import command_to_shell_file
from .rdkit_typing import Atom, Bond, Molecule
__all__ = [
ExtractionError,
... |
34adca183edb663d82392a3ff661668fd37beb007d04f41d3788e49620835c28 | Python | 409 | 16 | read('../noTRuberNoGapsNoAmbiguities.nex')
a=var.alignments[0]
tList = []
print("Doing bootstrap ...")
for i in range(200):
b = a.bootstrap()
dm = b.compositionEuclideanDistanceMatrix()
t = dm.njUsingPaup()
tList.append(t)
tt = Trees(tList, taxNames=a.taxNames)
tp = TreePartitions(tt)
t = tp.consensus(... |
4e40fbfa490702d4ab62f7f063144bab70f8c9e2d4b8c69e94f728e7e659e794 | Python | 410 | 10 | from .base import Model # noqa: F401
from .base import TransformBoundsWrapper # noqa: F401
from .pytorch import PyTorchModel # noqa: F401
from .tensorflow import TensorFlowModel # noqa: F401
from .jax import JAXModel # noqa: F401
from .numpy import NumPyModel # noqa: F401
from .wrappers import ThresholdingWrapp... |
c602d3c58c47ddbb636b52f47207538db6871b1c7e3de1bfc845b6d2edab0724 | Python | 410 | 16 | import tensorflow_federated as tff
only_digit = False
def download_and_save_federated_emnist():
emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(cache_dir='./', only_digits=only_digit)
"""
Or with Tensorflow dependencies, you can run this to process the data from Tensorflow locally:
```
pyth... |
5f5d914ba423a7b065b4397d6cdb94bbc46ec90d59b579413e34db81b1a3b2a2 | Python | 411 | 9 | # 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 sbi.samplers.vi.vi_divergence_optimizers import (
get_VI_method,
get_default_VI_method,
)
from sbi.samplers.vi.vi_quality_control import get_... |
5fea25c0399ab4c7b772593f37e0b8f957f306fef48d6c018e33ebb531d69a35 | Python | 412 | 10 | # Copyright (c) OpenMMLab. All rights reserved.
from .bbox_nms import fast_nms, multiclass_nms
from .matrix_nms import mask_matrix_nms
from .merge_augs import (merge_aug_bboxes, merge_aug_masks,
merge_aug_proposals, merge_aug_scores)
__all__ = [
'multiclass_nms', 'merge_aug_proposals', 'me... |
c1ef67cb4b7b5c2bde1af991e6b070d8460802ec2469dc6e9d78d8d5c52ba864 | Python | 412 | 16 | import numpy as np
import os
from PIL import Image
#The same for all subjects
images = np.load('data/processed_data/subj01/nsd_test_stim_sub1.npy')
test_images_dir = 'data/nsddata_stimuli/test_images/'
if not os.path.exists(test_images_dir):
os.makedirs(test_images_dir)
for i in range(len(images)):
im = Image... |
1153155e2b481b841ed6879a9e0bd4347095f3135a6a08dd61dff98987d42334 | Python | 413 | 14 | import torch
import numpy as np
def transform_list_to_tensor(model_params_list):
for k in model_params_list.keys():
model_params_list[k] = torch.from_numpy(np.asarray(model_params_list[k])).float()
return model_params_list
def transform_tensor_to_list(model_params):
for k in model_params.keys():... |
8187578992116c4787a2b585fd5f97d286860ddc517f11e2233faeb995ae7b16 | Python | 413 | 16 | """
ASGI config for exsclaim_gui project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_... |
a7c3f9257aca51461a78e062fa7de13542c2c185396f71a075d965cb06d967cb | Python | 413 | 16 | """
WSGI config for exsclaim_gui project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_... |
d27d13832fc17aa0ef7a8b3e0c5e65e825cb07832d2285d43b0bf36bc4723f2e | Python | 413 | 14 | import numpy as np
import torch
def transform_list_to_tensor(model_params_list):
for k in model_params_list.keys():
model_params_list[k] = torch.from_numpy(np.asarray(model_params_list[k])).float()
return model_params_list
def transform_tensor_to_list(model_params):
for k in model_params.keys():... |
d2b2ac736bc551f237dcfad94314ef08a8062bd320b76bebaa73b1d649d9bbdd | Python | 415 | 14 | read("../../K_thermus/noTRuberNoGapsNoAmbiguities.nex")
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=0, val=0.0)
m = Mcmc(t, nChains=1, runNum=0, sampleInterv... |
36b6b774f02f2250724d249b79a84a763efd13654ce9bd1fbd9d02f4e91893f6 | Python | 419 | 14 | # 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 sbi.samplers.mcmc.init_strategy import (
IterateParameters,
proposal_init,
resample_given_potential_fn,
sir_init,
)
from sbi.samplers... |
5522906cdb1f4f7b4c2e807190de997a5f8ce9cb844105ed505210e5aeac1277 | Python | 420 | 14 | # Imports #
from Classes.Menu import MenuBase
class ConfigureScreen(MenuBase):
def __init__(self,**kwargs):
super(ConfigureScreen,self).__init__(**kwargs)
self.protocol = 'PRL'
self.protocol_name = 'Probabilistic Reversal Learning'
self.protocol_title_label.text = self.protocol_na... |
a57cd024396e2b48a412cd40f404d8f3946d7457d45bb4fe45b62e74c9bde923 | Python | 420 | 21 |
class MyOVBox(OVBox):
def __init__(self):
OVBox.__init__(self)
def initialize(self):
print('Initialize Hello World Script')
# nop
return
def process(self):
# print the string specified in the box configuration.
# 'Message' is the name of the config entry.
print(self.setting['Message'])
de... |
ba7e7fa138510ddf948354ce2213e76492c5fb7bf417923cde271e48df4839cb | Python | 421 | 15 | class Compose(object):
""" Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
"""
def __init__(self, transforms):
self.transforms = transforms
self.type = "my_transform"
self.version = "v0.1"
def __... |
1391686fd34c1279adac166d9c0ce48f5dc232fc89b40a53703766719a9442ce | Python | 426 | 15 | #!/usr/bin/env python
import os
def tab_complete_on_conda_env_activation():
base = (os.environ['CONDA_PREFIX'])
fp = os.path.join(base,
'etc/conda/activate.d/activate-replay-completion.sh')
payload = 'if [ -n "${BASH_VERSION-}" ]; then\nsource tab-replay\nfi\n'
with open(fp, 'w')... |
15e51931ec2ec780250c401b892c69b0b18f064fe4a49bf6c5531b385d3829f7 | Python | 426 | 12 | from .dataset import GEOMDataset, GEOMDataset_PackedConf, \
rdmol_to_data, smiles_to_data, preprocess_GEOM_dataset, get_GEOM_testset, preprocess_iso17_dataset
__all__ = ["GEOMDataset",
"GEOMDataset_PackedConf",
"rdmol_to_data",
"smiles_to_data",
"prepro... |
cc88abef7058b3b9473c0fbc8447f373e77ca30d60ef1e392c888c0362b571dd | Python | 428 | 17 | var.warnReadNoFile = 0
var.verboseRead = 0
nTax = 5
taxNames = list(string.ascii_uppercase[:nTax])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=400)
d = Data([a])
t = func.randomTree(taxNames=taxNames)
t.data = d
c1 = t.newComp(free=1, spec='specified', val=[0.1, 0.2, 0.3])
t.newRMatrix(free=1... |
16aaf25526d8560d5fd23420e14eaa1139ab00feef2d50268516531adcd550ae | Python | 429 | 15 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 14:16:26 2022
@author: fhu14
Investigation of the effects on total energy if orbital energies are
shifted by some arbitrary constant. This is done by modifying the
corresponding SKF files
"""
from .skf_energy_shift import shift_set_eners
from .energy_analysis impor... |
675f8e681588b7cd5d5e8889404fc2bde2f6aa50f047dd9f1e16b927ceacb0ff | Python | 431 | 19 | var.verboseRead = 0
read('t.nex')
t = var.trees[0]
read('d.nex')
t.data = Data()
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setPInvar(free=1, val=0.0)
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=1.0)
t.optLogLike()
# If I wanted to save the tree (with branch lengths, of course), I ... |
da1f7d18297801a1f51adc378ec998a5908618234aef7984f2cec1f3eb77789a | Python | 432 | 14 | # import all gumpy submodules that should be loaded automatically
import gumpy.classification
import gumpy.data
import gumpy.signal
import gumpy.utils
import gumpy.features
import gumpy.split
# fetch into gumpy-scope so that users don't have to specify the entire
# namespace
from gumpy.classification import ... |
c4339098f9f7fc3bed4dd7323bf5370ef3db84c3dd22aa1d88f95dd1212e94a1 | Python | 433 | 21 | class MyMessage(object):
"""
message type definition
"""
# server to client
MSG_TYPE_S2C_INIT_CONFIG = 1
MSG_TYPE_S2C_INFORMATION = 2
# client to server
MSG_TYPE_C2S_INFORMATION = 3
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER = "sender"
MSG_ARG_KEY_RECEIVER = "rece... |
a5210d923fd0393631137ef2d55625517dbbeee4ef74a5b58f94fce260bc1f44 | Python | 434 | 15 | class Homochrome:
def __init__(self, axis=-1):
"""
Just select one channel for labels. For instance, from (X, Y, Z, 3) to (X, Y, Z).
"""
self.axis = axis
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sample['misc']
if mask.sha... |
f04f7a39613fbc5f31442b750f4622a8bf63643a15f37f9c23909be2c49e278a | Python | 435 | 16 | from setuptools import find_packages, setup
# python setup.py install
setup(name='pywinEA2',
version='0.0.1',
license='MIT',
description='Package with implementations of genetic algorithms.',
author='Fernando García Gutiérrez',
author_email='fegarc05@ucm.es',
packages=find_packages... |
df498f4879f30b14d584b15f4504bf153e2b72191e41760bf817413171379deb | Python | 436 | 22 | # -*- coding: utf-8 -*-
import pytest
from snf import datasets
@pytest.fixture(scope='session')
def simdata():
data = datasets.load_simdata()
assert all(k in data for k in ['data', 'labels'])
assert len(data.data) == 2
return data
@pytest.fixture(scope='session')
def digits():
data = datasets.... |
f454a4705f88c628f7815dbc421545823b3a9d813aeaeaf7fe9fa5c7154277cb | Python | 436 | 12 | import torch
from torch.nn import functional as F
def bce_loss(output, target, misc, weight=None):
if weight is None:
return F.binary_cross_entropy(output, target)
else:
assert len(weight) == len(
torch.unique(target)), "The weight array should as the same size as target label type... |
7f9d357e0ddaa6736e7cab8ff777b0ce11513ca763f0d94af63ad1acd5c88625 | Python | 438 | 12 | class BaseClientWorker(object):
def __init__(self, client_index):
self.client_index = client_index
self.updated_information = 0
def update(self, updated_information):
self.updated_information = updated_information
print(self.updated_information)
def train(self):
# c... |
a0fee0aacff38920f4c7d4973305834cbda03b392244fa2e13fd7fc20bdc5b82 | Python | 439 | 19 | import pytest
import usqc.util as util
import itk
import numpy as np
def test_bounded_region():
ref_img = itk.image_from_array(np.zeros((50,50)))
r = itk.ImageRegion[2]()
r.SetIndex([-10, 20])
r.SetUpperIndex([30, 49])
z = util.bounded_region(ref_img, r)
idx1 = z.GetIndex()
idx2 = z.G... |
a9f0f34e296771153fecae4366c1f2c972ed1b90c7fd76abfd5d5bb516f60dee | Python | 444 | 14 | # -*- coding: utf-8 -*-
"""
Aliases for easier compatibility with the SNF toolbox written in R
"""
from . import compute as _compute, metrics as _metrics
affinityMatrix = _compute.affinity_matrix
calNMI = _metrics.v_measure_score
concordanceNetworkMNI = _metrics.nmi
estimateNumberOfClustersGivenGraph = _compute.get_n... |
d1ffda23e90d40141860295bac4c7e691b770c73427a1d76906939f00eb492ac | Python | 444 | 11 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 19:40:04 2021
@author: fhu14
"""
from .ani1_interface import get_ani1data, get_ani1data_boosted
from .fold_generator import generate_folds, save_folds
from .precompute import compute_graphs_from_folds, single_fold_precompute, precompute_gammas, precompute_gammas_per_fo... |
725dc3fc7a64503a93f687587f660a607d83f729e7343e582d11f12190ec5418 | Python | 446 | 15 | read('t.nex')
t = var.trees[0]
var.alignments.append(func.newEmptyAlignment(dataType='dna', symbols=None, taxNames=t.taxNames, length=300))
d = Data()
t.data = d
c1 = t.newComp(free=1, spec='specified', val=[0.0, 0.2, 0.3])
t.newRMatrix(free=1, spec='specified', val=[1.2, 6.5, 1.3, 9.8, 1.1, 1.0])
t.setPInvar(free=1, ... |
b698d45fab7a301b2badc242f3b17fdf17688fb6c49cad16e1e0cb775be335a1 | Python | 446 | 15 | import multipagetiff as mtif
import ants
import numpy as np
def load_with_ants(image_path, reorient='IAR'):
"""Load an image with ANTS using the expected reorientation for tiff files.
Arguments:
reorient: Orientations are specified as a string of 3 letters. See ANTs doc for detail.
Return:
... |
dc0208f6a6aa86a12dbc87af01d2b0809dc796322bbae051872791ce8d8fd71a | Python | 447 | 10 | from .coconet import CoCoNetDataset
from .combined import CombinedDataset
from .dummy import DummyDataset
from .inference import InferenceDataset
from .kfold_cv_downstream import KFoldCVDownstream
from .rna_ts_label import challData_lab
from .xfam import XfamDataset
from .zwd import ZwdDataset
__all__ = ['XfamDataset'... |
e490edb86901a9f2cd1cfcb5d6899856ff1adcd6c821f7f87f4a049a44d6f4bb | Python | 448 | 21 | read("recoded.nex")
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=1, val=0.2)
m = Mcmc(t, nChains=4, runNum=0, sampleInterval=10, checkPointInterval=5000)
m.pr... |
08de558e633d8d8b27ebe2ab059f9fd6ec82e55b05200b0129c61e23c2718e87 | Python | 450 | 14 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
# from .attention_extraction import Extractor
# from .training import Trainer
# from .utils import ChargeCorrectedNodeWiseAttentiveFP, NodeWiseAttentiveFP, MolGraphConvFeaturizer, get_graph_from_mol
# __all__ = [
# MolGraphConvFeaturiz... |
9dba07f9eb8449e15383875ce31d354d23d852d0f026eea8f8134b111452ddee | Python | 451 | 21 | import torch
from daart import losses
def test_kl_div_to_std_normal():
mu = torch.zeros(1, 1)
logvar = torch.zeros(1, 1)
kl = losses.kl_div_to_std_normal(mu, logvar)
assert kl == 0
mu = torch.ones(1, 1)
logvar = torch.zeros(1, 1)
kl = losses.kl_div_to_std_normal(mu, logvar)
assert k... |
5ddaf601ac8604502b04470f575be3ecacd34b20e711d2c9120da558917fac47 | Python | 452 | 9 | if __name__ == "__main__":
from precompute_driver import precompute_folds
from DatasetGeneration import process_settings_files
current_default_file = "example_configs/refactor_default_tst.json"
current_settings_file = "2500_cc_reproduction/dset_2500_cc/dset_settings.json"
s_obj, opts = process_... |
7ca0b5475e34d0ba1dc058e5c6ad08a7d3034507588984da2e2ae512eb06148e | Python | 452 | 10 | # 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 torchmdnet.priors.atomref import Atomref, LearnableAtomref
from torchmdnet.priors.d2 import D2
from torchmdnet.pri... |
98d4dccc0ba9a2c283efd151f49d80d352f260199089d4cb3afca6adc8137237 | Python | 454 | 20 | import collections
# in python3.6 logging.handlers should be imported here for tff
import logging.handlers
import numpy as np
import tensorflow as tf
import tensorflow_federated as tff
tff.federated_computation(lambda: 'Hello, World!')()
gld_23k_train, gld_23k_test = tff.simulation.datasets.gldv2.load_data(4, 'cache... |
d5054b605472334b25a3b9566a3d103ad644c790c5e32f91b1f9a0b9987927f6 | Python | 454 | 9 | if __name__ == "__main__":
from precompute_driver import precompute_folds
from DatasetGeneration import process_settings_files
current_default_file = "example_configs/refactor_default_tst.json"
current_settings_file = "20000_cc_reproduction/dset_20000_cc/dset_settings.json"
s_obj, opts = proces... |
25d20b29bacab79b2b104efb3eafc7de8a7f86d5a120b3a4cf4ec5bc633ffede | Python | 455 | 23 | # Read checkPoints from an MCMC.
# Read them in ...
cpr = McmcCheckPointReader(theGlob='*')
# A table of acceptances
cpr.writeProposalAcceptances()
# Compare splits using average std deviation of split frequencies
#cpr.compareSplitsAll()
# or between only two checkpoints ...
#cpr.compareSplits(0, 1)
# How was swapp... |
2ed27131c24ac5e93ead06300b3ef226eccfab753c0f4b1e55325cc2beadbd73 | Python | 455 | 16 | iteration_list = []
loss_list = []
f_read = open("413", 'r')
f_write = open("PUSHSUM-id413.txt", 'w+')
iteration_index = 0
data_points = f_read.readlines()
for i in range(len(data_points)):
if data_points[i][0:6] == 'regret':
temp_data = data_points[i].strip('\n').split(',')
loss = float(temp_data... |
5f1d366ccc00854587e4a433927ae8a9f5603482b2f4f57728eb0a23cbeb9684 | Python | 455 | 11 | import h5py
import cv2
import numpy as np
path = 'E:/Zhu/ETreg/code/segmentation/pytorch_connectomics/dataset/output/result.h5'
outputdir = 'E:/Zhu/ETreg/code/segmentation/pytorch_connectomics/dataset/output/img/'
dataset = h5py.File(path, 'r')
for key in dataset.keys():
imgdatasets = np.array(dataset[key])
for... |
5fe3a61aa2ddf72a78e0ed7f523502f26b33790567d5a562a255480292c94a0d | Python | 455 | 12 | # Imports
from Classes.Menu import MenuBase
class ConfigureScreen(MenuBase):
def __init__(self, **kwargs):
super(ConfigureScreen, self).__init__(**kwargs)
self.protocol = 'PR'
self.protocol_name = 'Progressive Ratio'
self.name = self.protocol + '_configscreen'
self.protocol_... |
6b9a62fb2ab225a90e4162012893abb403eeb2dea8dd6123eebaf38222fba6e0 | Python | 456 | 15 | from clipkit import clipkit
from clipkit.files import FileFormat
trim_run, stats = clipkit(
# raw_alignment=">1\nA-GTAT\n>2\nA-G-AT\n>3\nA-G-TA\n>4\nAGA-TA\n>5\nACa-T-\n",
input_file_path="tests/integration/samples/simple.fa",
# output_file_path="./programmatic-temp.phylip",
# output_file_format=FileFo... |
34c5a2dd65500c508a0fcd0a37c9e551585dc6ca261918f3448a4eba6151cf8d | Python | 458 | 22 | """
pytest tests for the Trainer class.
"""
import pytest
import os
import sys
from unittest.mock import patch
# Fixtures
@pytest.fixture
def mock_init(monkeypatch):
monkeypatch.setenv("DTORROOT", os.getcwd())
def test_trainer_instantiate(mock_init):
testargs = ["prog", "--load_json", "config/mnist.json"]
... |
40581dd9e29166b934b2a1549a03c93a559fdaa152c7b832c1768ca5d0269731 | Python | 458 | 13 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 16:43:18 2021
@author: fhu14
In the future, can expose more models for use
"""
from .spline_model_backend import fit_linear_model, SplineModel, JoinedSplineModel
from .spline_backend import Bcond, spline_linear_model, construct_joined_splines,\
spline_new_xvals, p... |
0c90b6857b3c3bfee302e9d17ca24ae2463756c1985e1b99e5dd4904fd5c5a48 | Python | 461 | 22 | #! /usr/bin/env libtbx.python
# -*- coding: utf-8 -*-
# =============================================================================
# Created at:
# EMBL_HH
# Author:
# Grzegorz Chojnowski - gchojnowski@gmail.com
# =============================================================================
def bash_blue(s):
... |
afb272e7862e8ae55f932a6ff83b2c8c7590f7c6724dd30e6b1a2d5095c7b8d4 | Python | 462 | 12 | # Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors.
from pathlib import Path
_this = Path(__file__).parent
TEST_ARCHIVE = _this / "test_archive.zip"
TEST_CHARGES_JSON = _this / "test_charges_phenol.json"
TEST_C6_JSON = _this / "test_c6_phenol.json"
TEST_DIPOLE_JSON = _this / "test_dipole_... |
08b70d1de5499179cde30181385f05cb1c9abe212c6bee5e5d4028fea1636eaf | Python | 465 | 21 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmpose.models.backbones import I3D
def test_i3d_backbone():
"""Test I3D backbone."""
model = I3D()
model.train()
vids = torch.randn(1, 3, 16, 112, 112)
feat = model(vids)
assert feat.shape == (1, 1024, 2, 3, 3)
model = I3... |
6b038afb912f36b563f38db7db5c5de8962db12b8c17aeb499bbc7e90942b9cc | Python | 465 | 23 | import abc
class ABCEnvironment(metaclass=abc.ABCMeta):
"""
Abstract/skeleton class for alternative
environments that the animal can traverse.
"""
@abc.abstractmethod
def __init__(self):
pass
@abc.abstractmethod
def sample_uniform(self):
"""
Sample a location ... |
3afefba04e04ee39eb9d03b0b3dc0eaae371d875f7c2cfb38c4735212dc78e07 | Python | 467 | 19 | """__init__.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under MIT License
https://github.com/f0uriest/keras2c
"""
from . import keras2c_main
from .keras2c_main import k2c
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
__author__ = "Rory Conlin"
__copyright__ = "Copyright 2019, Rory Conli... |
910b73b509900066feda3c2138e82f5f12e7e68c485cfcc68b260b707bf6b983 | Python | 468 | 21 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 4 13:00:34 2022
@author: Daniel
"""
import os
dire = r'C:\Users\Daniel\repos\phase_coding\data\tempotron\batch5'
file_names = os.listdir(dire)
for f in file_names:
extension = f.split('.')[-1]
f_split = f.split('_')
if len(f_split) == 8:
continue
... |
a89b21beefd2eaf4664c9d771ac79cd2a9e0f3220d8311ebabf41a1c367ddaf4 | Python | 468 | 18 | nTax = 11
taxNames = list(string.ascii_uppercase[:nTax])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=200)
d = Data([a])
t = func.randomTree(taxNames=taxNames)
t.data = d
t.newComp(free=0, spec='specified', val=[0.4, 0.3, 0.0])
t.newRMatrix(free=0, spec='specified', val=[2., 3., 4., 5., 6., 7.... |
046a0af6233ea4907fb4fc37fa83aac16d80332280b50ecf0e0e4f1a5d376e1e | Python | 470 | 17 | import torch.nn as nn
class VFLFeatureExtractor(nn.Module):
def __init__(self, input_dim, output_dim):
super(VFLFeatureExtractor, self).__init__()
self.classifier = nn.Sequential(
nn.Linear(in_features=input_dim, out_features=output_dim),
nn.LeakyReLU()
)
se... |
16292a31b020832e4e8a044845b4c615e5b93c87d3cca59eb53d0a951aa9cbc8 | Python | 471 | 17 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import collect_env as collect_base_env
from mmcv.utils import get_git_hash
import mmdet
def collect_env():
"""Collect the information of the running environments."""
env_info = collect_base_env()
env_info['MMDetection'] = mmdet.__version__ +... |
5c767469022ce55852d2e3fbadd303e4334f70c5b2e59e4f214e72b22bd906cd | Python | 474 | 19 | # 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/>
"""Utility functions for input/output."""
import os
from pathlib import Path
def get_project_root():
return Path(__file__).parent.parent.parent.abs... |
4e808287d1faf74b12c0b48b90f97a9d622c69ace824a3acb79f300c2931ee8b | Python | 477 | 22 | import os
import sys
import numpy as np
w_file = sys.argv[-3]
src_filename = sys.argv[-2]
save_file = sys.argv[-1]
w = np.load(w_file)
src_file = open(src_filename, "r")
nweights = w.shape[0]
out_lines = []
for i, line in enumerate(src_file.readlines()):
if i == 0:
continue
val = w[(i - 1) % nweight... |
7f1f89660eb340f166b1475b91c898f6091653c5d4f94f233b047ca5308b3244 | Python | 477 | 11 | from outputfiles.plot import plotHisto
import mysrc.constants as cst
df = plotHisto(cst.root_dir / "raw_data" / 'Algeria_ASAP_2d_data.csv',
'Bouira', 'NDVI')
df = plotHisto(cst.root_dir / "raw_data" / r'histo_data_from_db_query.csv',
'Bouira', 'rad')
df = plotHisto(cst.root_dir / "raw_data" / r'hist... |
65f9223f12f1a9f81de1ccf324f6371b3375c503511f1a91e1edf9f62408178e | Python | 478 | 18 | import numpy as np
class Squeeze:
def __init__(self, axis=0):
"""
Squeeze any image if axis dimension is not 1. For instance, from (1, X, Y, Z) to (X, Y, Z).
"""
self.axis = axis
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sample['... |
d8fd79c11852df2794fde5719309b016a6302e950549f28a501b112424e77900 | Python | 478 | 19 | import subprocess
from setuptools import setup, find_packages
try:
version = (
subprocess.check_output(["git", "describe", "--abbrev=0", "--tags"])
.strip()
.decode("utf-8")
)
except:
print("Failed to retrieve the current version, defaulting to 0")
version = "0"
setup(
name... |
a24ef6e2c83c027836242db247cda774bf90b10a14c99113ff49bd93124aa138 | Python | 479 | 24 | import abc
class BaseTopologyManager(abc.ABC):
@abc.abstractmethod
def generate_topology(self):
pass
@abc.abstractmethod
def get_in_neighbor_idx_list(self, node_index):
pass
@abc.abstractmethod
def get_out_neighbor_idx_list(self, node_index):
pass
@abc.abstractm... |
d98099bb7cd97f15dfbe9f81d5eb8b68877fa4e37981753cf251d9e53be47b5a | Python | 482 | 16 | import numpy as np
class ReplaceTensor:
def __init__(self, image_label, mask_label):
"""
Unsqueeze any image if axis dimension is not 1. For instance, from (X, Y, Z) to (1, X, Y, Z).
"""
self.image_label = image_label
self.mask_label = mask_label
def __call__(self, sa... |
7764379dd2a662321586993b6fb6236223ed86a2dfde57a22ea6dda624bb2179 | Python | 483 | 16 |
def dice_loss_multilabel(input, target, class_weights=None, n_classes=1):
if class_weights is None:
class_weights = [1]
smooth = 1.
loss = 0.
for c in range(n_classes):
iflat = input[:, c].view(-1)
tflat = target[:, c].view(-1)
intersection = (iflat * tflat).sum()
... |
83ca3b896249b490bf4fec43db580d8bc5bc8e3dac621e85bd3784a7e6b3a3c4 | Python | 486 | 13 | # Config for SmoothNet filter trained on Human3.6M data with a window size of
# 8. The model is trained using root-centered keypoint coordinates around the
# pelvis (index:0), thus we set root_index=0 for the filter
filter_cfg = dict(
type='SmoothNetFilter',
window_size=8,
output_size=8,
checkpoint='htt... |
86ae1be477aaf1207129191cad0e254244a7827a5e3a601c411098642a2bb17d | Python | 487 | 17 | import pandas as pd
from simple_mlps.datas import ParcellationData
root = './results/exp_ids_mlp'
os.makedirs(root, exist_ok=True)
def test():
for _exp in range(5):
for stage in ('train', 'valid', 'test'):
pd = ParcellationData(_exp, stage=stage)
rid = pd.rid[pd.index_list]
... |
4b0183979620554569cfdfe0b18570f6a06131023bcca0283b078bd1ca26affa | Python | 488 | 21 | class MyMessage(object):
"""
message type definition
"""
# message to neighbor
MSG_TYPE_INIT = 1
MSG_TYPE_SEND_MSG_TO_NEIGHBOR = 2
MSG_TYPE_METRICS = 3
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER = "sender"
MSG_ARG_KEY_RECEIVER = "receiver"
"""
message payl... |
9c663c74e439b96fd92a051a984fe30ffe45d3fa73b1ed9396ab3f37b2deece0 | Python | 489 | 17 | import numpy as np
import torch
from models.ltp import Model
from dtor.datasets.dataset_mnist import MNIST3DDataset
model = Model(prelim=64)
model.load_state_dict(torch.load("results/model-mnist-fold0.pth", map_location=torch.device('cpu')))
model.eval()
data = MNIST3DDataset(tr_test="test")
for n in range(5):
f... |
c5f2f447a03962c8d7be502ed4ff1d82590d17a9c56b8511ca5d21c126d734b7 | Python | 489 | 26 | import torch
import numpy as np
import lpips
from .. import nputils
from ..log_service import print_log
from .eva_base import base_evaluator, register
@register('null')
class null_evaluator(base_evaluator):
def __init__(self, **dummy):
super().__init__()
def add_batch(self,
**dumm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.