sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
3134bb2a6386a0e064e538bc898ea4d57723f1eb82e170e5edec4972a00a01be | Python | 628 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class YOLOF(SingleStageDetector):
r"""Implementation of `You Only Look One-level Feature
<https://arxiv.org/abs/2103.09460>`_"""
def __init__(self,
... |
5b4541e7019601a10b429f6c3d2929d36c3720ea819b96468d15525339d361a8 | Python | 628 | 21 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import Registry, build_from_cfg
BBOX_ASSIGNERS = Registry('bbox_assigner')
BBOX_SAMPLERS = Registry('bbox_sampler')
BBOX_CODERS = Registry('bbox_coder')
def build_assigner(cfg, **default_args):
"""Builder of box assigner."""
return build_from_cf... |
f99b1327b0c7cc9d3e41f8426bed88be3c66aad044b725b8086f60c1ad172470 | Python | 628 | 13 | import os
os.system('python train_poly_segments.py --train_dir ../../data/elastic_pend/trainset.npy \
--test_dir ../../data/elastic_pend/validationset.npy \
--gpu_id 0 \
--ckpt neurvec_pend \
--epoch 500 \
... |
8955bfeb4eabfabd83cb5e1ecada7ae8eb921a8001fc005336b85ea599c807dd | Python | 629 | 19 | import pathlib
import matplotlib
from matplotlib.font_manager import fontManager
from consbi.simulators.poisson_glm import get_prior_dist, poisson_glm
# Define paths
BASE_PATH = pathlib.Path(__file__).parent.parent
DATA_PATH = BASE_PATH.joinpath("data")
RESULTS_PATH = BASE_PATH.joinpath("results")
# Add fonts
fontM... |
3a29af7cbad3d923084939854744ef9f6655ee8e73d2f66dcc56f8e4940a02b3 | Python | 631 | 23 | import torch
import torch.nn as nn
import torch.nn.Functional as F
class Concat(nn.Module):
def __init__(self, inmodel, n_extra, n_output):
super(Concat, self).__init__()
self.cnn = inmodel
self.cnn.fc = nn.Linear(
self.cnn.fc.in_features, 20)
self.fc1 = nn.Lin... |
16c5249779043e870acafa05e0d9f0759be964e719d247f15dea419226a841f8 | Python | 634 | 23 | import os
import glob
dt="Negtivate"
gpu="1"
files=os.listdir( "train_data_20220824/step_2/"+dt+"/")
for file in files:
if os.path.exists("D:/YS/M_D/Updata_2/evaluation/train_data_20220824/CAM/"+dt+"/"+file):
print("continue",end=" ")
print(file)
continue
else:
... |
576c1cf2c48bcaef376afb6744695b3dd88ded21e2832d704f70656cbe4608fd | Python | 634 | 22 | # Copyright (c) OpenMMLab. All rights reserved.
executor_cfg = dict(
name='Test Webcam',
camera_id=0,
camera_max_fps=30,
nodes=[
dict(
type='MonitorNode',
name='monitor',
enable_key='m',
enable=False,
input_buffer='_frame_',
... |
9f2aaac4f6276499b665de4c18d11edefdfd25df0f244240e8d64b7413f66864 | Python | 634 | 27 | import xgboost as xgb
import numpy as np
model_name = 'brits_i'
impute = np.load('./{}_data.npy'.format(model_name)).reshape(-1, 48 * 35)
label = np.load('./{}_label.npy'.format(model_name))
data = np.nan_to_num(impute)
n_train = 3000
print(impute.shape)
print(label.shape)
from sklearn.ensemble import RandomFores... |
b36910344f57c421bf7d1d6b8a5d7db3e1a99c272b87d8f7b16d90ef43d0a0a7 | Python | 634 | 16 | # import os
from serenityff.charge.gnn.attention_extraction.extractor import Extractor
# from serenityff.charge import Extractor
# sdf_file = "../test132_train/combined_test.sdf"
# sdf_file = "./sdf_explain.sdf"
sdf_file = "/cluster/work/igc/mlehner/test146_combine/combined_multi.sdf"
# model_path = "./example04_mode... |
4c6b04335843723201e5aa383ead280ec908fb2b3f437924987d34b6d8511026 | Python | 635 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class FSAF(SingleStageDetector):
"""Implementation of `FSAF <https://arxiv.org/abs/1903.00621>`_"""
def __init__(self,
backbone,
... |
d2a45efae618f8ec25518ca6f96e944d626dc7a8d3e67a6ad9feabe13a526719 | Python | 635 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class FCOS(SingleStageDetector):
"""Implementation of `FCOS <https://arxiv.org/abs/1904.01355>`_"""
def __init__(self,
backbone,
... |
06b696731c624b01ff0d167f23873e36857053fb7a9857b384b98207fb1b2530 | Python | 636 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class ATSS(SingleStageDetector):
"""Implementation of `ATSS <https://arxiv.org/abs/1912.02424>`_."""
def __init__(self,
backbone,
... |
131cd2bf4de127844c141b6fde03b4126b4e993e00488b523e74cf6905315010 | Python | 636 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class PAA(SingleStageDetector):
"""Implementation of `PAA <https://arxiv.org/pdf/2007.08103.pdf>`_."""
def __init__(self,
backbone,
... |
692a17bf60dee3150b3c3d71953306710a2b648d353a8eb6ed0667722016f685 | Python | 636 | 27 | import sys
nTrees = 15
nSites = 400
fIn = file('siteLikes')
fOut = file('siteLikes.txt', 'w')
fIn.readline() # skip the first line
fOut.write('Tree\t-lnL\tSite\t-lnL\n')
for i in range(nTrees):
for j in range(nSites):
aLine = fIn.readline()
if not aLine:
print('no workee! Ran out of l... |
d71b36cde94f30ccc84c12799b0de73fc2c56ed939d2cd85c92895d1ec835466 | Python | 636 | 21 | import numpy as np
class Unsqueeze:
def __init__(self, axis=0, apply_to_label=False):
"""
Unsqueeze any image if axis dimension is not 1. For instance, from (X, Y, Z) to (1, X, Y, Z).
"""
self.axis = axis
self.apply_to_label = apply_to_label
def __call__(self, sample)... |
35890d99765bf2ef931af5455a8261d21dc4484e54b99e4daefad49a13b7598e | Python | 641 | 23 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
from mmdet.datasets import DATASETS
def test_xml_dataset():
dataconfig = {
'ann_file': 'data/VOCdevkit/VOC2007/ImageSets/Main/test.txt',
'img_prefix': 'data/VOCdevkit/VOC2007/',
'pipeline': [{
'type': 'LoadImageFrom... |
1031601187ca0a810fdc105ffcc4d4210f45dad6b924ef57e8ab74a1a706782c | Python | 642 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class FOVEA(SingleStageDetector):
"""Implementation of `FoveaBox <https://arxiv.org/abs/1904.03797>`_"""
def __init__(self,
backbone,
... |
5375e3a0b64bab1986e4429a1937b73f6d465427fba2d56b2b3bdf4b2909f3ec | Python | 643 | 23 | """
This module provides classes for generating oligo sequences, custom genomic regions, and loading genomic data via FTP.
"""
from ._ftp_loader import BaseFtpLoader, FtpLoaderEnsembl, FtpLoaderNCBI
from ._genomic_region_generator import (
CustomGenomicRegionGenerator,
EnsemblGenomicRegionGenerator,
NcbiGe... |
0ba14783817aa54e0abb54a16bad89bd6931e0a81dd8503c86c2ac571e9d84ec | Python | 644 | 24 | import os, sys
from rdkit import Chem
from rdkit.Chem import Descriptors
root = os.path.dirname(os.getcwd())
with open(root + "/data/db_sets.csv", "r") as f_in:
with open(root + "/data/db_sets_mw.csv", "w") as f_out:
for line in f_in:
line = line.rstrip()
items = line.split(",")
... |
0dfab95088d9be00f7ef603e2c1fd56265a9b67c209ef7a408e022836c69d273 | Python | 645 | 15 | from collections import defaultdict
with open(snakemake.input[0]) as fin:
best_hits = defaultdict(dict)
for line in fin:
qseqid, sseqid, _, _, _, _ = line.split()
qseqgen, sseqgen = qseqid.rsplit("_", 1)[0], sseqid.rsplit("_", 1)[0]
best_hits[qseqid][sseqgen] = sseqid
with open(snakema... |
bf00065961b236639595154c4c3cbc513c7c59cd5abf0341fe8e1a216f8a9bb4 | Python | 645 | 15 | from collections import defaultdict
with open(snakemake.input[0]) as fin:
best_hits = defaultdict(dict)
for line in fin:
qseqid, sseqid, _, _, _, _ = line.split()
qseqgen, sseqgen = qseqid.rsplit("_", 2)[0], sseqid.rsplit("_", 2)[0]
best_hits[qseqid][sseqgen] = sseqid
with open(snakema... |
58d1036964451e54ad77e50f295dfa6d2ed8dc26e3f69ab5c1f13dd120f8b62a | Python | 647 | 24 | import sys
# import 'numpy' first to load system libraries
# TODO: remove when https://github.com/lightgbm-org/LightGBM/issues/7355 is resolved
import numpy as np # noqa: F401
import lightgbm as lgb # noqa: F401
sys.stdout.write("testing Python imports\n")
# modules that shouldn't be imported by default
lazy_impo... |
9e3b3ed8dd38ceef0922c0a7c8dc4d6f6cf5f9fa2e2dcf2938c87fc25aa37ba7 | Python | 647 | 30 | import glob
import PIL.Image
import os
import argparse
def resave_img(path,type):
files = sorted(glob.glob(os.path.join(path, '**/*.'+type),recursive=True))
for file in files:
im = PIL.Image.open(file).convert('RGB')
im.save(file)
if __name__ == "__main__":
parser = argparse.ArgumentPar... |
010bdd0333d470e00b628e6310fe55a03dead5046497e2005be072075076eb91 | Python | 648 | 25 | import torch.nn as nn
import numpy as np
from abc import abstractmethod
class BaseModel(nn.Module):
"""
Base class for all models
"""
@abstractmethod
def forward(self, *inputs):
"""
Forward pass logic
:return: Model output
"""
raise NotImplementedError
... |
a7d6e9d9153709b95ab451e31a5d65af14924d8a0ad6e1131ae6676c104dbec0 | Python | 648 | 25 | import logging
from .helpers import SeqType
from .settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .msa import MSA
logger = logging.getLogger(__name__)
def warn_if_all_sites_were_trimmed(msa: "MSA") -> None:
if msa.is_empty:
logger... |
907774c9632dd0da5da306f839df49eb50297a8125db16c4ce222189c3e68dc8 | Python | 654 | 15 | # Copyright (c) OpenMMLab. All rights reserved.
from .base_bbox_coder import BaseBBoxCoder
from .bucketing_bbox_coder import BucketingBBoxCoder
from .delta_xywh_bbox_coder import DeltaXYWHBBoxCoder
from .distance_point_bbox_coder import DistancePointBBoxCoder
from .legacy_delta_xywh_bbox_coder import LegacyDeltaXYWHBBo... |
477fc50331b6815e38a156ec94ff8b45751ae9200ccb8116c6c3681baeac6b1d | Python | 655 | 22 | import numpy as np
class Squeeze:
def __init__(self, axis=0, apply_to_label=False):
"""
Squeeze any image if axis dimension is not 1. For instance, from (1, X, Y, Z) to (X, Y, Z).
"""
self.axis = axis
self.apply_to_label = apply_to_label
def __call__(self, sample):
... |
8cd85e3a46e04d68d2b456f67ac04c63189fd756118a2ecb2caa80f637b708bd | Python | 655 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class RetinaNet(SingleStageDetector):
"""Implementation of `RetinaNet <https://arxiv.org/abs/1708.02002>`_"""
def __init__(self,
backbone... |
a11e179339cecb1d49dc8701e19cb1ca3fd701c764933bd53bfb3caf8a9d9d87 | Python | 655 | 22 | read('../../noTRuberNoGapsNoAmbiguities.nex')
d = Data()
# Unconstrained likelihood
d.calcUnconstrainedLogLikelihood2() # Installs the result in d.unconstrainedLogLikelihood
unc = d.unconstrainedLogLikelihood
n = Numbers('mcmc_sims_0', col=1, skip=1000)
print('Original unconstrained log like is %s' % unc)
print('Here ... |
68d29a2d3b9f1d3e3510b77c4aa5896d84c110c482996722a06511ee6c68ce73 | Python | 657 | 18 | # -*- coding: utf-8 -*-
#File Name : StimulationsCodes.py
#Created By :
## Stimulation codes
# Avoid the declaration of new stimulation (added in new tab here). Only Stimulation contains gdf in original list is really standard...
Poly_stimulation = {
'OVPoly_Down' : 0x10001, #Useless use 'OVTK_GDF_Down'
'OVPoly_... |
20ae289864b4147d6bad994a5399952b3ebd6c59f9002b2c9459dc4efe8564e9 | Python | 658 | 20 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class VFNet(SingleStageDetector):
"""Implementation of `VarifocalNet
(VFNet).<https://arxiv.org/abs/2008.13367>`_"""
def __init__(self,
... |
92872ad8508ae3c8f47aa53cfb05907fd2ac65103c948f84699694dc37024594 | Python | 658 | 28 | import pandas as pd
import numpy as np
def mean_squared_error(x: pd.Series, y: pd.Series) -> float:
diff: np.ndarray = y - x
sq_diff: np.ndarray = diff ** 2
res = sq_diff.mean()
return res
def mean_percent_error(x: pd.Series, y: pd.Series) -> float:
mpe_p = (y - x) / x
mpe_p = mpe_p[mpe_p.i... |
9341b5d0f627129e1f601a57f4071355112e552047fb55f76fde809b7591333b | Python | 660 | 20 | ls = LeafSupport('../input.nex')
# A group of taxa is defined like so. Defining a group will create a
# list of stabilities based on the quartets or triplets defined by the
# boundary of the group, i.e. only quartets that have one side in the
# group and the other outside the group will be included. This will
# make i... |
356b610e3066b6aa72b2e938f12b65b37def447a19607afa0ed5e89cdeb607f1 | Python | 662 | 22 | read('../../noTRuberNoGapsNoAmbiguities.nex')
d = Data()
# Unconstrained likelihood
d.calcUnconstrainedLogLikelihood2() # Installs the result in d.unconstrainedLogLikelihood
unk = d.unconstrainedLogLikelihood
n = Numbers('mcmc_sims_0', col=1, skip=1000)
print('Original unconstrained log like is %s' % unk)
print('Here ... |
b566eeb06719f5c067f6d12cee3fa5ae2c42a5a32f48aac8cba4f730ba38941e | Python | 663 | 19 | read('../A_NavidiAlignFromYang/navidiSSRNA.nex')
a = var.alignments[0]
print('%20s %7s%7s%7s%7s%7s' % ('species', 'T', 'C', 'A', 'G', 'G + C'))
for i in range(len(a.sequences)):
s = a.sequences[i]
c = a.composition([i]) # comp of an individual sequence
print('%20s ' % s.name, end=' ')
for b in [3, ... |
d049e167afc44d3f3dcfb9772a1c8d5b988f51ca127e2466260480973e32c2ad | Python | 663 | 23 | import os
import pandas as pd
from sklearn.model_selection import train_test_split
root = os.path.dirname(os.getcwd())
D = pd.read_csv(root + "/data/data_ml.csv")
print(D.shape)
train, test = train_test_split(D, stratify=D["kinase"], test_size=0.3, random_state=42)
cpds_train_set = train["inchi_key"].values
to_move... |
601454d7cd29fba83d1df17ead5bfd8c09cbf4f3adf1b732474b2c08a6224ffc | Python | 665 | 21 | '''Convert a list of polygons to a shapely multipolygon'''
from shapely.geometry import Polygon, MultiPolygon
def convert_polygons_to_shapely_multipolygons(polygons):
'''Convert a list of polygons to a shapely multipolygon
Parameters
----------
polygons : list of list of float
List of polygons. The first ... |
44836252a1721b61556bac6478e1e417a54762f92347683be14ee61c512d06e6 | Python | 668 | 26 | import os
import shutil
from pathlib import Path
def get_dftbplus_executable() -> str:
dftbplus_exec_path = shutil.which("dftb+")
if dftbplus_exec_path is None:
dftbplus_exec_path = os.environ.get("DFTBPLUS_EXEC_PATH")
if dftbplus_exec_path is None:
raise ValueError("Could not find dftb+... |
d389dc2a57677e02f239c58b54bce69391c83762f1fe2bf0d2bc521bf33acb2f | Python | 668 | 22 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'exsclaim_gui.settings')
try:
from django.core.management import execute_from_command_line
except... |
55a8f1d6796b4b7a644d4e3e40288a1d34bbabfca4ff6eed27fdfbc9e89b5001 | Python | 669 | 20 | var.warnReadNoFile = 0
var.verboseRead = 0
nTax = 4
taxNames = list(string.ascii_uppercase[:nTax])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=500)
d = Data([a])
read('((A:0.4, B:0.4), C:0.4, D:0.4);')
t = var.trees[0]
t.data = d
c1 = t.newComp(free=1, spec='specified', val=[0.25, 0.2, 0.3])
c... |
cd2ef871cf1ccbf4d9ea50cf99bf7c05baa41fbb1aa0d0342bae1d43669b26fe | Python | 669 | 25 | theRunNum = 0
read('../../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=4, runNum=theRunNum... |
e26b008793e23e72526ea6683302cd20c6bc809a7e76f8ff993b96485cb6c93c | Python | 670 | 24 | class MyMessage(object):
"""
message type definition
"""
# client-oriented message
MSG_TYPE_C2S_SEND_FEATURE_AND_LOGITS = 3
# server-oriented message
MSG_TYPE_S2C_INIT_CONFIG = 1 # send
MSG_TYPE_S2C_SYNC_TO_CLIENT = 2 # send
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER ... |
01c6b9d0bbf3853cebf4104af371f4cbff6ad2c64d6543f07e0a47571e226886 | Python | 671 | 21 | from osgeo import gdal
import typing
_T = typing.TypeVar("_T")
def pix_to_geo(x: _T, y: _T, geotransform: typing.Tuple[float, float, float, float, float, float]) -> typing.Tuple[
_T, _T]:
x_geo = geotransform[0] + x * geotransform[1] + y * geotransform[2]
y_geo = geotransform[3] + x * geotransform[4] + y... |
5ca3a1d79311b96c3ac33a4351a444e07a7f905e81b8d5fab16105214443a5c5 | Python | 671 | 26 | import os
import glob
import argparse
import torch
from tqdm import tqdm
import numpy as np
import random
import math
import utils
def main(args):
surf = utils.ReadSurf(args.surf)
surf = utils.GetUnitSurf(surf)
utils.WriteSurf(surf, args.out)
if __name__ == '__main__':
parser = argparse.ArgumentParser(de... |
9a4c066c4781a9c2db43f32763b264d4cacd91662ef77df53b5da5930c6c9dca | Python | 673 | 28 | import copy
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
##############
# cfg_holder #
##############
@singleton
class cfg_unique_hold... |
30989a41cba6132c272cb18767212c5fae839db4da229ff91cceb598afe3cf63 | Python | 674 | 24 | import torch
class ToTensor:
def __init__(self, mask_type="long", training=True):
"""
Convert numpy array to Torch.Tensor
"""
self.training = training
self.mask_type = mask_type
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sa... |
daa77864db91cb576a1e6f9971fcd6a47568a2a0e7b776b979f9f0268b4cc1df | Python | 674 | 24 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmdet.models.utils import SELayer
def test_se_layer():
with pytest.raises(AssertionError):
# act_cfg sequence length must equal to 2
SELayer(channels=32, act_cfg=(dict(type='ReLU'), ))
with pytest.raises(Assertio... |
a505aa6b6ccee773ce2ca29f7d870115ac3730cee589fc48a23e8b86a7749869 | Python | 676 | 16 | # Copyright (c) OpenMMLab. All rights reserved.
from .base_sampler import BaseSampler
from .combined_sampler import CombinedSampler
from .instance_balanced_pos_sampler import InstanceBalancedPosSampler
from .iou_balanced_neg_sampler import IoUBalancedNegSampler
from .ohem_sampler import OHEMSampler
from .pseudo_sampler... |
67c6d2ee7f2b73d263152f393d3d9f756b4a0ca321e75e135589ca5aa0a8b3c5 | Python | 678 | 24 | import pandas as pd
import urllib.parse
import requests
SERVER_URL = "https://npclassifier.gnps2.org/"
#SERVER_URL = "http://mingwangbeta.ucsd.edu:6541"
def test_heartbeat():
request_url = "{}/model/metadata".format(SERVER_URL)
r = requests.get(request_url)
r.raise_for_status()
def test():
df =... |
161d7dca526d30ba5e8f5320f06631f625b1338448a1263996fd14a5dbc53053 | Python | 681 | 24 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.runner.hooks import HOOKS, Hook
@HOOKS.register_module()
class CheckInvalidLossHook(Hook):
"""Check invalid loss hook.
This hook will regularly check whether the loss is valid
during training.
Args:
interval (int): Checki... |
1846d09ee83c01d4e8b5b4c34f8f58845ad7ce375bb93dcc1d5fc85c18e8811a | Python | 682 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class AutoAssign(SingleStageDetector):
"""Implementation of `AutoAssign: Differentiable Label Assignment for Dense
Object Detection <https://arxiv.org/abs/... |
780fb4ad34d00c99378017e82e1ed52b998615be24ab044de0c38d52ad38663c | Python | 682 | 10 | # To use gdal from command line open OSGeo4W Shell
# cd V:\foodsec\Projects\ECMWF-SEAS5\asap download 2024 06 06 p
# v:
# gdalinfo ecmwf-51_2024_06_6.nc
# gdal_translate NETCDF:"ecmwf-51_2024_06_6.nc":tprate ecmwf-51_2024_06_6.tif
# gdal_translate -ot Float32 -scale 3.181800470872867e-07 9.71067713749883e-12 -a_nodata ... |
ec6baffdc771f1a5f8653d457d8218be8117c78da3861541343b85ac67cc3a7b | Python | 684 | 23 | import os
def dir_img_rename(imgdir):
imglist = os.listdir(imgdir)
imglist = sorted(imglist)
for i in range(len(imglist)):
imgoldname = imgdir + imglist[i]
imgnewname = imgdir + str(i).zfill(4) + '.tif'
try:
os.rename(imgoldname, imgnewname)
except Exception as ... |
c29ea39a5126bc58a3f8916451b019b69b05cc951e96b031924509b53a08be4a | Python | 686 | 20 | from os.path import join, realpath, dirname
BASE_PATH = dirname(realpath(__file__))
DATA_PATH = join(BASE_PATH, 'data')
RUN_PATH = join(BASE_PATH, 'run')
LOG_PATH = join(BASE_PATH, 'logs')
# CNLP_LOG_PATH = join(LOG_PATH, 'cnlp_testing')
CNLP_LOG_PATH = join(LOG_PATH, '_gcp_revision')
PARAMS_PATH = join(RUN_PATH, '... |
4d9d90c220bf2fece67dcf2617ef23d5ba1ad0e91ec20196a2ab63420ac23ec7 | Python | 687 | 19 | import time
class print_time:
def __init__(self, obj=None, enter_msg=None, exit_msg=None):
self.enter_msg = enter_msg if obj is None else "Starting to {}".format(obj)
self.exit_msg = exit_msg if obj is None else "Successfully {}!".format(obj)
def __enter__(self):
print("\n" + self.ent... |
8ee55abd7aaf395cdd676a8a0b330cb0d9794167e05f004371647af3cf456623 | Python | 687 | 21 | var.verboseRead = 0
var.warnReadNoFile = 0
taxNames = list(string.ascii_uppercase[:5])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=3000)
d = Data([a])
read('(A:0.3, B:0.3, C:0.3, D:0.3, E:0.3);')
t = var.trees[0]
t.data = d
c1 = t.newComp(free=0, spec='specified', val=[0.4, 0.1, 0.1])
c2 = t.ne... |
45028d7b19db66c8c45173df9d52b2c1138c204317f4b13452ac4433fc93f0bf | Python | 689 | 22 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class NASFCOS(SingleStageDetector):
"""NAS-FCOS: Fast Neural Architecture Search for Object Detection.
https://arxiv.org/abs/1906.0442
"""
def __... |
e8ad4e07502c4823c9c9658e205277d02995969dae3cf8c1a6b574fad519430b | Python | 691 | 24 | import numpy as np
from matplotlib.patches import PathPatch
from matplotlib.path import Path
def polygon_patch(polygon, **kwargs):
'''
Make a matplotlib patch from a shapely polygon
replaces descartes
adapted from https://github.com/geopandas/geopandas/issues/1039#issuecomment-748625852
Parameters
--------... |
68f5a8418aa430a623ff57a7e096a3bb58ce0364b9c137f4d952ee0dbcd8ac20 | Python | 692 | 28 | """
module for testing/outputting RIDs used for each fold in Weibull models.
"""
import pandas as pd
FI_ADNI = 'metadata/data_processed/weibull_model_adni.csv'
df = pd.read_csv(
FI_ADNI,
usecols=['RID'] + [f'Fold{i}' for i in range(5)],
dtype={'RID': str}
)
root = './results/exp_ids_weibull'
os.makedi... |
e00d6682d4b0115e9f340f2cc2a22ddf1e1528cdcbebc289514d34215bee7bc0 | Python | 692 | 14 | # Copyright (c) OpenMMLab. All rights reserved.
from .body3d_h36m_dataset import Body3DH36MDataset
from .body3d_mpi_inf_3dhp_dataset import Body3DMpiInf3dhpDataset
from .body3d_mview_direct_campus_dataset import Body3DMviewDirectCampusDataset
from .body3d_mview_direct_panoptic_dataset import \
Body3DMviewDirectPano... |
56c214feaa609e9043e5cbafef0f184a23bdf68e127eb046827dd4a48442ec81 | Python | 693 | 20 | class MyMessage(object):
# server to client
MSG_TYPE_S2C_INIT_CONFIG = 1
MSG_TYPE_S2C_SYNC_MODEL_TO_CLIENT = 2
# client to server
MSG_TYPE_C2S_SEND_MODEL_TO_SERVER = 3
MSG_TYPE_C2S_SEND_STATS_TO_SERVER = 4
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER = "sender"
MSG_ARG_KEY_RECE... |
eb28327c2ad8d14f307e088b6bd3a4107e4fd6cd210ff42a904f2f40634d3172 | Python | 696 | 27 | import numpy as np
import pandas as pd
import sklearn.metrics
__all__ = ['rmse', 'mpe', 'correlation', 'r_2']
def rmse(y_true: pd.Series, y_pred: pd.Series):
return np.sqrt(sklearn.metrics.mean_squared_error(y_true,y_pred))
def mpe(y_true: pd.Series, y_pred: pd.Series):
min_value: float = 0.1
filtered ... |
de32f86d184eef10df80bfcb30627cae5f34a228757ab21e30ff0e810f1b9b77 | Python | 697 | 26 | from pytorch_lightning.loggers import TensorBoardLogger, CSVLogger
class SuperLogger:
def __init__(
self,
save_dir="",
tensorboard=True,
csv=True,
):
self.tensorboard = tensorboard
self.csv = csv
self.logger_dict = {
"csv": CSVLogger(save_dir... |
87dd93f03c3a7d1dfb25ce52564924215258a44942c8cc83c70d7bd78b6fa813 | Python | 701 | 27 | read('../../noTRuberNoGapsNoAmbiguities.nex')
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
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)
t.setModelComponen... |
396203428b6c24f26fc0f2449d4d57b8a5d50d2c4f2bae990620a0c29c7d6d16 | Python | 702 | 28 | # Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors.
"""Test `serenityff.charge.utils.rdkit_typing`."""
import pytest
from rdkit import Chem
from serenityff.charge.utils.rdkit_typing import Atom, Bond, Molecule
@pytest.fixture()
def test_mol() -> Molecule:
return Chem.AddHs(Chem.MolF... |
ab85334110eabc9ebd0b496918e3615dd03c3ea47c2a32b02d78c68603e0d0b2 | Python | 704 | 21 | """
Setup file for EEG-LTT.
Use setup.cfg to configure your project.
This file was generated with PyScaffold 4.1.1.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: https://pyscaffold.org/
"""
from setuptools import setup
if __name__ == "__main__":
try:... |
6f1722edb1e8d25e9c01944e4fe9d1b88d1b74bc9d1c3b0eda9e8d61647e0c9d | Python | 706 | 24 | import torch
class ToTensor:
def __init__(self, mask_type="long", training=True):
"""
Convert numpy array to Torch.Tensor
"""
self.training = training
self.mask_type = mask_type
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sa... |
e74d416b02741c96e9b16efa92e45144960e2c9135d7c6f252216f0cc1209bee | Python | 709 | 23 | import numpy as np
from metric.dice import one_cls_dice
def dice_sparse2d(output, target, misc=None):
"""
Calculate dice for each critical slices, and average.
: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]
... |
d3d9e12538350397a270d1fe02ab10090487af758b0b943f6544cb303e2d280c | Python | 710 | 22 | # Copyright (c) OpenMMLab. All rights reserved.
from .bfp import BFP
from .channel_mapper import ChannelMapper
from .ct_resnet_neck import CTResNetNeck
from .dilated_encoder import DilatedEncoder
from .fpg import FPG
from .fpn import FPN
from .fpn_carafe import FPN_CARAFE
from .hrfpn import HRFPN
from .nas_fpn import N... |
d0d11cffa731b089708ff7a06cde9d09abce51dd64c59cd17495d11e6ca2e24d | Python | 715 | 25 | taxNames = list(string.ascii_uppercase[:7])
for i in range(6):
t = func.randomTree(taxNames)
t.name = 't%i' % (i + 1)
var.trees.append(t)
tt = Trees(taxNames=taxNames)
dm = tt.topologyDistanceMatrix('wrf')
dm.writeNexus()
try:
import p4.scqdist
print("\nQuartet distances from scqdist")
dm = tt... |
20128500daee7664b0f193f778a25fb3d14dc50fcbd3fff5227dc2c82a58093f | Python | 716 | 21 | import torchvision.transforms.functional as F
class NormalizeChannel(object):
"""Normalize a tensor volume with mean and standard deviation estimated
from the sample itself.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, training=True):
self.train... |
2d0c451b68f3e94524f48bfbe6037fa590a8d8fb1d9e561453f0986dc50cf063 | Python | 716 | 21 | import torchvision.transforms.functional as F
class NormalizeChannel(object):
"""Normalize a tensor volume with mean and standard deviation estimated
from the sample itself.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, training=True):
self.train... |
4573b4d34825f138053c6de2bddf4e8a817a5d873b7860cba2ff04bb1e4c5314 | Python | 717 | 25 | from setuptools import setup
from os import path
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'requirements.txt')) as f:
requirements = f.read().splitlines()
setup(
name='phase_to_r... |
74a0c14ac3c82d43537a2e7d5a0b22cc3eec8832e6ed5a2e2e0d79ce44006541 | Python | 719 | 28 | import requests
import pandas as pd
import json
SERVER_URL = "http://localhost.ucsd.edu:4857"
def test_api():
url = "{}/api/smart3/search".format(SERVER_URL)
# Preparing request
peaks_df = pd.read_csv("./swinolide.csv", sep=None)
data = {}
data["peaks"] = json.dumps(peaks_df.to_dict(orient="recor... |
64a40bdeacfac5085d55f6b50e68fd62fd55f5a04e6c302889154e25c055b156 | Python | 720 | 14 | # Copyright (c) OpenMMLab. All rights reserved.
from .anchor_generator import (AnchorGenerator, LegacyAnchorGenerator,
YOLOAnchorGenerator)
from .builder import (ANCHOR_GENERATORS, PRIOR_GENERATORS,
build_anchor_generator, build_prior_generator)
from .point_generator... |
e0f8d1f224717f38ba05610a1c7accaabc4bd7a5c951c6dff2a993b40f012791 | Python | 722 | 20 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 16:26:41 2021
@author: fhu14
init file for the module package containing all the models used by the
network.
"""
from .input_layer_DFTB import Input_layer_DFTB
from .input_layer_DFTB_val import Input_layer_DFTB_val
from .input_layer_hubbard import Input_layer_hubbar... |
57ca83fca88b53ce6bd446a33adae7cfd09b037539fdd7ce0af5ccc4a3f71a13 | Python | 724 | 29 | # -*- coding: utf-8 -*-
"""
Created on Thu May 19 15:28:00 2022
@author: fhu14
"""
"""
Module for generating the figures for the paper; there will be a separate
function for each figure and the paths will be hard-coded so that
there is no ambiguity about what is being referenced
There will be a lot of dependence on... |
201d34dde91b75497a09560ca17d1c312917a3f386152f603ad65c03b487bdc1 | Python | 726 | 23 | import torch
from imblearn.metrics import specificity_score
def specificity_weighted(output, target):
"""
Specificity = TN / (TN + FP)
:param output: Batch x Channel x ....
:param target: Batch x ....
:return:
"""
with torch.no_grad():
if len(output.shape) == (len(target.shape) + 1... |
2f4110f3c8a2681aa643e37570fa2e2e504aded7bb17509fe6336e016d2ac127 | Python | 726 | 23 | import torch
from imblearn.metrics import sensitivity_score
def sensitivity_weighted(output, target):
"""
Sensitivity = TP / (TP + FN)
:param output: Batch x Channel x ....
:param target: Batch x ....
:return:
"""
with torch.no_grad():
if len(output.shape) == (len(target.shape) + 1... |
36e8e7521da2b2ba8e14fa62363e24f15fb1b9ea85b59828874a9d4cce59b18d | Python | 729 | 43 | from abc import ABC, abstractmethod
class BaseModel(ABC):
@abstractmethod
def reset(self):
pass
@abstractmethod
def reset_mu(self, batch_size):
pass
@abstractmethod
def set_img_batch(self, img_batch):
pass
@abstractmethod
def set_label_batch(self, label_batch... |
b61ebe96cb4de4e80afade45c773d8641ad7f435a07959f43489ad1608a9f59b | Python | 729 | 20 | import torchvision.transforms.functional as F
class NormalizeInstanceChannel(object):
"""Normalize a tensor volume with mean and standard deviation estimated
from the sample itself.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, training=True):
se... |
5142970cda178cedadc020a4537f94e2ac94f74d825f1de10ee5a2bcb96607ad | Python | 734 | 17 | import jax
import jax.numpy as jnp
from collections import namedtuple
def generate_sin(xs, amp, period, phase):
return amp * jnp.sin(xs * 2 * jnp.pi / period + phase)
generate_sin_batch = jax.jit(jax.vmap(generate_sin, [None, 0, 0, 0], 0))
def generate_sin_base(xs, amp, period, phase, base):
return base + ge... |
059392361f153211736b20e3fac4a1bf83deb2fe82647f1e999b17ec198054c6 | Python | 735 | 29 | from torch.utils.data import Dataset
from Bio import AlignIO
from ..utils import rna2index
class InferenceDataset(Dataset):
"""Dataset for inference, without ground-truth"""
def __init__(self, fasta_files, transform=None):
self.transform = transform
self.token_mapping = rna2index
se... |
88d2dd132d6bc8af6c49e8d43384f9bc400725deecbbed8cea468a8488294809 | Python | 736 | 24 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="rat-simulator",
version="1.2.0",
author="Vemund S. Schoyen",
author_email="vemund@live.com",
description="A rat in an environment simulator",
long_description=long_description,
lon... |
40783af0a7486c6bded871de6688088ecedaf61a09a4aa076a71b8e59f2b3bf0 | Python | 737 | 23 | import numpy as np
from metric.hausdorff95 import hausdorff95
from metric.dice import one_cls_dice
def hd_sparse2d(output, target, misc=None):
"""
Calculate dice for each critical slices, and average.
:param output:Output dimension: Batch x Channel x X x Y (x Z) float
:param target:Target dimension: ... |
793fc26f4fb1f515326504cde477d3502354cdbe630f6c6f341f4d4c586f4830 | Python | 737 | 21 | import tensorflow.keras as keras
import tensorflow.keras.backend as K
import tensorflow.keras.initializers as initializers
class LinearLayer(keras.layers.Layer):
def build(self, input_shape):
self._a = self.add_weight(name="A", shape=[input_shape[1] if len(input_shape) >= 2 else 1],
... |
9659c81408492f1bd3dd572aa7a03fe27a705d07abf341d353f36a246d24b1a3 | Python | 739 | 20 | import torchvision.transforms.functional as F
class NormalizeInstance(object):
"""Normalize a tensor volume with mean and standard deviation estimated
from the sample itself.
:param mean: mean value.
:param std: standard deviation value.
"""
def __init__(self, training=True):
self.trai... |
d191efcf79b7f3ad772accb34eb00bc6c0909bee41d35f37bb19ebc062f27080 | Python | 739 | 25 | import torch.nn as nn
import torch.nn.functional as F
#artifacts learning
class Net1(nn.Module):
def __init__(self):
super(Net1, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(2,128,11,stride=1,padding=5),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(... |
eaf28ab25eb0a2d8b3a7a411dc4b6800580883b1104446e54930d051a8835322 | Python | 739 | 33 |
import sys
import gzip
import collections
def xopen(f):
return (gzip.open if f.endswith(".gz") else open)(f)
sites = collections.OrderedDict()
files = sys.argv[1:]
def key(toks):
return (toks[0], toks[1], toks[3], toks[4])
def anynonref(gts):
return any(gt.startswith(("0/1", "1/1")) for gt in gts)
he... |
7f8eda5e2a2ed5e3bdb1ed0615750627114033e6d79c8a408a28d074ec5f061d | Python | 748 | 19 | import torch
from torchmdnet.models.model import load_model
class External:
def __init__(self, netfile, embeddings, device="cpu"):
self.model = load_model(netfile, device=device, derivative=True)
self.device = device
self.n_atoms = embeddings.size(1)
self.embeddings = embeddings.re... |
a575fb58fffe11604412e9d7cf6103506c9c7dc3c2f0cf5cd055b26dc6a8d06b | Python | 748 | 21 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_SAMPLERS, build_sampler
from .base_sampler import BaseSampler
@BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
"""A sampler that combines positive sampler and negative sampler."""
def __init__(self, pos_sampler, ne... |
dc379327d9b5ba2b37287fd1542f57afefef06ad2cb1185490bbf86fd319ada0 | Python | 748 | 24 | import torch
class ToTensor:
def __init__(self, mask_type="long", training=True):
"""
Convert numpy array to Torch.Tensor
"""
self.training = training
self.mask_type = mask_type
def __call__(self, sample):
image, mask, misc = sample['image'], sample['mask'], sa... |
4e04500119feb531284e9cc68fc394c227b9be5c1d1817213b954c5d8663aa7b | Python | 750 | 19 | read('t.nex')
t1 = var.trees[0]
t2 = var.trees[1]
# See page 532 in Felsenstein
print("The 'symmetric distance' = ", t1.topologyDistance(t2, metric='sd'))
print("The 'weighted Robinson Foulds distance' = ", t1.topologyDistance(t2, metric='wrf'))
ret = t1.topologyDistance(t2, metric='bld')
print("The 'branch score' =... |
f5ed2495e4b43bff9a16be2c8aee8c4eac48649f53d9b9748487769e11613a49 | Python | 750 | 26 | from typing import Type, Union
import warnings
import datetime
import unittest
import logging
import os
import pandas as pd
import numpy as np
from mri_surv.statistics.other_dementia import reversion_stats
log_file = os.path.join(os.path.abspath("./logs"),
"cohort.log")
with o... |
c512e850e1f07620c3a5c3bbe5eee3930182a40d5844a1ad68ffd1505696bd9f | Python | 752 | 16 | # Copyright (c) OpenMMLab. All rights reserved.
from .nms import nearby_joints_nms, oks_iou, oks_nms, soft_oks_nms
from .one_euro_filter import OneEuroFilter
from .post_transforms import (affine_transform, flip_back, fliplr_joints,
fliplr_regression, get_affine_transform,
... |
abbe073fb02df20184158ba692da1b439ff4d003bfae822900d8a1275bbcdc29 | Python | 754 | 22 | import logging
import logging.config
from pathlib import Path
from tmp.utils import read_json
def setup_logging(save_dir, log_config='logger/logger_config.json', default_level=logging.INFO):
"""
Setup logging configuration
"""
log_config = Path(log_config)
if log_config.is_file():
config =... |
2055cceb4ba880e59d3c52c4ae5bb4556aa347977e395feb34af52bb75c380e0 | Python | 755 | 23 | from data.data_access import Data
import logging
from matplotlib import pyplot as plt
# params= {'type': 'claims', 'params': {'data_type': 'seq' }}
# params= {'type': 'claims', 'params': {'data_type': 'seq' }}
# params= {'type': 'claims', 'params': {'data_type': '3gram_freq' }}
params= {'type': 'manual_label', 'params... |
ef03fda0e7096a941f78e97478107d397b6208363eb3bb90835ec752e3ac8dc8 | Python | 755 | 33 | from typing import List, Union, TYPE_CHECKING
from pydantic import BaseModel
from .backend import keras
if TYPE_CHECKING:
from .backend import keras as _keras_typing # noqa: F401
class LayerIO(BaseModel):
"""Input/output details for a layer."""
name: str
pointer: str
inputs: Union[str, List[str... |
012d948c3b8cba04e6fdfd304a5a4f1375bbe793dcb7a2e42ffd14b0fb972882 | Python | 761 | 27 | from ..builder import DETECTORS
from .sparse_rcnn import SparseRCNN
@DETECTORS.register_module()
class QueryInst(SparseRCNN):
r"""Implementation of
`Instances as Queries <http://arxiv.org/abs/2105.01928>`_"""
def __init__(self,
backbone,
rpn_head,
roi_he... |
426f261b4e2dc6cb8b5ee87727b3ba2b236fbe710c14d209eee064963245df80 | Python | 761 | 17 | with open(snakemake.input[0]) as fin, open(snakemake.output[0], "w") as fout:
current_qseqid = None
for line in fin:
qseqid, sseqid, _, qcovhsp, scovhsp, _ = line.split()
qcovhsp, scovhsp = float(qcovhsp), float(scovhsp)
qseqgen, sseqgen = qseqid.rsplit("_", 1)[0], sseqid.rsplit("_", 1)[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.