sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
334574fa43ce44698b736d36280577855c3b51be7843968a8e1c51bd929083ee | Python | 4,462 | 113 | """
Color code removal filter, implemented as a codec
Should be usable for writing to a file, for example:
>>> from spinalcordtoolbox.utils import csi_filter
>>> csi_filter.register_codec()
>>> with open('some_file', 'w', encoding='csi-filter') as some_file:
... some_file.write('Some \x1b[1mBRIGHT\x1b[m text\n')
... |
854b81740e8327ee49b4fe963b1a65b428ab701fb1fff0d008f4d3f16b0a9d0f | Python | 4,463 | 124 | # -*- coding: utf-8 -*-
import cv2
import os
import numpy as np
import pandas as pd
import time
import modules.functions as functions
import modules.morphology as morphology
from skimage.util import img_as_ubyte
from skimage import feature
from scipy.spatial.distance import cdist
def fill( # Fill hole... |
2dfd27da70bddc86e2f738fecd484022e7a2aeae69f14d9c5eea90041bb1b32b | Python | 4,464 | 143 | # YAML Input/Output
# Author: David Young, 2020
"""YAML file format input/output."""
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union
import yaml
from magmap.io import libmag
if TYPE_CHECKING:
import pathlib
def _filter_dict(d: Dict, fn_parse_val: Callable[[An... |
802b66c3e3b98348d8b75cc0a5d2a4fa61a0ba3916bfd2edb6c456d99ff3b3b7 | Python | 4,464 | 170 | from pathlib import Path
import numpy as np
import tqdm
from ase import build
from ase.calculators.singlepoint import SinglePointCalculator
from ase.constraints import FixAtoms
from ocpmodels.datasets.lmdb_database import LMDBDatabase
DB_NAME = "ase_lmdb.lmdb"
N_WRITES = 100
N_READS = 200
def cleanup_asedb() -> No... |
00108546c2ea45e4bb44c9afc47b4a391c25ba824d17313a3c2e9c2924c6ce48 | Python | 4,469 | 119 | """
data fetchers
"""
import os.path as op
from pathlib import Path
import shutil
from pkg_resources import resource_filename
from eigenstrapping.datasets import utils
import numpy as np
from neuromaps import datasets, images
import nibabel as nib
from nilearn.datasets.utils import _fetch_file
def fetch_data(*, na... |
8afab577fb6ff1c9bcad7beb8dcf96ad63fa1d07f872c26c98206f1427a215a1 | Python | 4,469 | 124 | import scanpy as sc
import numpy as np
import pandas as pd
import h5py
###
###
### reading expression data
###
###
filename = "ppfctx_snRNAseq_processed_data_2024_05_16.h5seurat"
with h5py.File(filename, "r") as f:
cols = np.array(f["assays"]["RNA"]['features'])
indices = np.array(f["cell.names"])
age_li... |
a812b925b78e9cdaba00d5b2c23fdab025a6bbac4c56a45f51a862a2be210013 | Python | 4,469 | 138 | import json
from pathlib import Path
import torch
import torch.utils.data as data
from .loader import VideoLoader
def get_class_labels(data):
class_labels_map = {}
index = 0
for class_label in data['labels']:
class_labels_map[class_label] = index
index += 1
return class_labels_map
... |
aa6b93a01506b6a0e874565e47b6bb02e18e6e39259f657b3a28a3dc62b26df2 | Python | 4,469 | 125 | #!/usr/bin/env python
# Simple local Python 3 HTTP(S) server with CORS support. The first argument is
# the port to listen on. To enable HTTPS, provide the path to a certificate
# file and a key file. A fourth argument can be a path to the directory
# you want to serve.
#
# To create a local self-signed certificate (l... |
c3200a6d1a56601cb99ddd011b5ad73e235333b7ed5ad3b8d24327b72ef7570e | Python | 4,470 | 128 | import logging
from pathlib import Path
import ase.io as ase_io
import numpy as np
import typer
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
from simgen.integrators import IntegrationParameters
from simgen.manifolds import Multi... |
38f77deb3c9b6f47d6d15fb45c8fcc4f07262a96f0f88bb2d704aea401673b77 | Python | 4,471 | 126 | from neurolib.utils.loadData import Dataset
from neurolib.models.aln import ALNModel
import matplotlib.pyplot as plt
import neurolib.utils.functions as func
import neurolib.utils.stimulus as stim
import numpy as np
import scipy.io as sio
from scipy import signal
# adding varx to the system path
import sys
sys.path.ins... |
4774e1cf9d7832f9043ca2657a04eab2e086fc3adc161f3f89c55ecddcb33edb | Python | 4,472 | 105 | import time
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
def compute_max_sim(src_df, tgt_df):
start_time = time.time()
src_mols = [Chem.MolFromSmiles(smiles) for smiles in src_df.SMILES]
src_... |
70d5542a27122b84b7a4d295387f0beba94a3c4d3c7617917eb9268cd6521f80 | Python | 4,472 | 100 | """
Benchmark the data throughput of the Data Extraction from the HDF5 dataset.
"""
import time, os, json, argparse
from nearl.io.dataset import Dataset
def benchmark_dataset_method(dset, exit_point=None, **kwargs):
st = time.perf_counter()
st_total = time.perf_counter()
print(f"Started benchmarking ...")
data... |
b1aa0c0cc0628209f00826c3d1807b12d542f892505cad52727868b787c9685b | Python | 4,475 | 133 | import logging
from pathlib import Path
import ase.io as ase_io
import numpy as np
import typer
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.integrators import IntegrationParameters
from simgen.manifolds import LinePrior, MultivariateGaussianPrior
from simgen.particle_filtering import Par... |
647734eabeb2c1531c14ca267465e14d60d9c815627e929eeec958f031f49613 | Python | 4,477 | 95 | from create_dataset import *
from utils import *
from PDFN import PDFN
from options import *
from saver import resume, save_img_single
from tqdm import tqdm
def get_parameter_number(model):
total_num = sum(p.numel() for p in model.parameters())
trainable_num = sum(p.numel() for p in model.parameters... |
e4a75c23ccc85253af9961506740b34b6214e1365c95bdfc88fc0bef6dabf978 | Python | 4,478 | 130 | # Copyright (c) OpenMMLab. All rights reserved.
"""Modified from https://github.com/open-
mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py."""
import argparse
import json
from collections import defaultdict
import matplotlib.pyplot as plt
import seaborn as sns
def plot_curve(log_dicts, args):
i... |
fb91157f680b94cbf8b460bd939d115faae11b0cb6bc7ec7a7384471bccc262b | Python | 4,480 | 99 | import numpy as np
import os
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from global_setting import *
# Generate synthetic binary classification data
np.random.seed(42)
# Define two class centers (representing two spatial locations)
cl... |
29d5806f16d84c898f4843d7880305e2b2b254bc294e750b2b72155a7526b4b4 | Python | 4,483 | 131 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import json
import logging
from collections import defaultdict
import numpy as np
import torch
import nltk.... |
02ce581ddef360114b520d3e7708680d258da141c972685b16893bdfe64112ca | Python | 4,485 | 127 | import json
import logging
import msgpack
from asgiref.sync import async_to_sync
from celery import current_app
from channels.generic.websocket import WebsocketConsumer
from channels.layers import get_channel_layer
logger = logging.getLogger(__name__)
def get_user_group_name(user_id):
return f"updates-{user_id... |
a58d6d30004bc6bc1081542caf596f43e560bc0833a039c12a4207511c20513a | Python | 4,485 | 100 | # pytest unit tests for sct_dmri_denoise_patch2self
import pytest
from dipy.data.fetcher import read_bvals_bvecs
from spinalcordtoolbox.utils.sys import sct_test_path
from spinalcordtoolbox.image import Image, add_suffix
from spinalcordtoolbox.scripts import (sct_dmri_concat_b0_and_dwi,
... |
f28d484091e96cfc4a567ab2783b460a5190d4ad3572f06f893df762ec034643 | Python | 4,486 | 113 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras.applications import imagenet_utils as utils
from keras.models import Model
from keras.layers import Input, Lambda
def test_preprocess_input():
# Test image batch with float and int image input
x = np.random.uniform(0, 255, ... |
8aa93adf7cc2271bf55d0622885a5bf3b62c784fe9b860f0fca15079d5cb0d66 | Python | 4,487 | 127 | import glob
import os
import shutil
import numpy as np
from PIL import Image
def check_maskid(train_imgs):
for i in train_masks:
img = Image.open(i)
print(np.unique(np.array(img)))
def reformulate_file(image_list, mask_list):
file_list = []
for idx, (imgp,
maskp) in enumer... |
3aff21862e997dc21ffac9edbfd386050d2493c6806a0f725e3b0dfb203ae242 | Python | 4,488 | 106 | import pytest
import h5py
from .common import TestCase
def is_aligned(dataset, offset=4096):
# Here we check if the dataset is aligned
return dataset.id.get_offset() % offset == 0
def dataset_name(i):
return f"data{i:03}"
class TestFileAlignment(TestCase):
"""
Ensure that setting the file... |
ba21a7dd85be0d1cf9d97755c38242eddd8197e9c4ec65ae602e41fc281df707 | Python | 4,488 | 100 | from sklearn.metrics import precision_recall_curve
from sklearn.metrics import auc, average_precision_score
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import f1_score
from torchmetrics import AUROC
from sklearn.metrics import roc_auc_score
import pandas as pd
from sklearn import metrics
import n... |
ca42ff934b4579aff4f830480a2722fcf0ccd55a1c6f8f750e5cd6324c4944ed | Python | 4,488 | 109 | from typing import Optional
import torch
import numpy as np
from ase.calculators.calculator import Calculator, all_changes
from oa_reactdiff.trainer.potential_module import PotentialModule
from torch_geometric.data import Data
def onehot_convert(atomic_numbers):
"""
Convert a list of atomic numbers into an on... |
cabc1404b4f3703592c4c4668a4d146cf21c8fcca3bf1c6e17df037ba5627887 | Python | 4,489 | 154 | import time
from fastapi import Form, APIRouter, Depends, Request
from fastapi.responses import JSONResponse, StreamingResponse
from queue import Empty
import medperf.config as config
from medperf.web_ui.common import (
check_user_api,
)
from medperf.web_ui.schemas import EventBase
import anyio
router = APIRouter(... |
75d1d3c7a69cd72a2aa352fc310a611f75304a0015f447e9e34cfc94c8018124 | Python | 4,490 | 155 | """
2.5D U-NET IMPLEMENTATION
"""
import torch
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels = in_channels
if in_channels == 3:
self.conv0 = nn.Conv2d(in_channels, out_channels=1, kernel_s... |
cd2b2ca03bdf5a603919240567a2103bb724736aeba5a470e806bd39a73e6e23 | Python | 4,490 | 168 | """Various utilities used by the library"""
import time
import warnings
from typing import List, Union
import numpy as np
import scipy.interpolate as interpolate
def format_time(value: float) -> str:
"""Convert time to nicer format"""
if value <= 0.005:
return f"{value * 1000000:.0f}us"
elif valu... |
0d784a1e656936ac0cab39618ba897780334ad3aa877f08edebe16b1606b38d7 | Python | 4,492 | 113 | from ipaddress import IPv4Address
from CybORG.Shared import Observation
from CybORG.Shared.Session import RedAbstractSession
from CybORG.Simulator.Actions.Action import RemoteAction
from CybORG.Simulator.State import State
class PhishingEmail(RemoteAction):
""" The green agent action that represents the green age... |
7f4f032c4fe9ac97c9ff7faa3f2b4c252aa4b97f6c76f4bac5c0396c9daecaa2 | Python | 4,493 | 114 | import panel as pn
import pytest
from guppy.frontend.sidebar import Sidebar
@pytest.fixture
def sidebar(panel_extension):
"""Build a BootstrapTemplate + Sidebar."""
template = pn.template.BootstrapTemplate(title="Test")
return Sidebar(template=template)
class TestSidebar:
@pytest.mark.parametrize(
... |
b55fc50875cc2047453e1f2bfa2a8e9de00f900a453a6daa1a75fc13e5f17206 | Python | 4,494 | 139 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import resize
from .decode_head import BaseDecodeHead
from .psp_head import PPM
@MODELS.register_module()
class UPerHead(BaseDecodeHead):
"""Unified Pe... |
487edfc367c935a8ff6ac42136fe4016a773ab5387e659e1af95b4a39bac3499 | Python | 4,497 | 141 | import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_conv_layer
from mmengine.model import BaseModule
from mmseg.registry import MODELS
class UpSampleBN(nn.Module):
""" UpSample module
Args:
skip_input (int): the input feature
o... |
a5f90ce321cec643fc6ad648db95b536eeb73e8602fe78c52b8198e565b8090c | Python | 4,502 | 132 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import json
def load_json_as_table(metadata_row, filename):
"""Load JSON file and convert to long format table."""
filepath = metadata_row['path'] + '/' + filename
... |
7ef7b0bbcdf4f74f6f16059963e7882eaeec5c1828b8137dace3e8eebb782b66 | Python | 4,503 | 129 | import logging
from pathlib import Path
import ase.io as ase_io
import numpy as np
import typer
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
from simgen.integrators import IntegrationParameters
from simgen.manifolds import Multi... |
1e5f31debe48737b46dee0cdc849b53c3a01010ae7a28fcecc5b7ac601058eea | Python | 4,505 | 120 | import unittest
from unittest.mock import patch
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Descriptors
from DiastereomericResolutions.main.solvent_reps import (
_get_cosmo_reps,
_get_solvent_weight,
calculate_solvent_system_representations,
)
class TestSolventRe... |
f5ba4eb97c19bd98fedede920a9f34dd4db6f0c140c759c41f6e0a4b779fb055 | Python | 4,505 | 108 | # Our proposed model CNN + LSTM
import tensorflow.keras as keras
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
import time
from utils.utils import save_logs
from utils.utils import calculate_metrics
class Classifier_ENCODER:
def __init__(self, output_directory, input_shape, nb_classe... |
a5d9cb31e85ebf462248658a1d9b2a50617dd0bbec73d6e21dcc5613a9223357 | Python | 4,506 | 116 | import os
import math
import numpy as np
from PIL import Image
from .utils import mkdir_p
class HTML:
def __init__(self, web_dir, title):
self.title = title
self.web_dir = web_dir
self.img_dir = os.path.join(self.web_dir, 'images')
mkdir_p(self.img_dir)
self.doc = '<!DOCT... |
780213737d6ae02913637a071b65f7b9ec21b4616a3a1b0072dbacf191f834c1 | Python | 4,508 | 123 | import pandas as pd
import numpy as np
from scipy.spatial import Delaunay
import igraph as ig
from igraph import Graph
import os
import argparse
import random
from multiprocessing import Pool, cpu_count
from scipy.sparse import lil_matrix, coo_matrix
from vf2 import PatternChecker
from concurrent.futures import Process... |
121c6f3ceed7f302365a820baabe35ad2cb9f55558278b0c3c8214006cc02ff9 | Python | 4,510 | 130 | import argparse
import os
from xmlrpc.client import boolean
from src.utils import *
from src.models import exp1, exp2, exp3, exp4, exp5, prospective, siriraj, shap, lyo, interpretable
from src.dataset.preprocess import *
def get_parser():
"""
Generate a parameter parser
"""
# parse parameters
pars... |
069d340d8b9dc5ea4c153133d2cc94992bce00f6556c2a4ab413b8e4032fdc1f | Python | 4,512 | 136 | """Pure-predicate tests for can_read / can_edit / can_manage."""
from uuid import UUID, uuid4
from zndraw.access import (
GroupRole,
ShareAccess,
ShareContext,
Visibility,
can_edit,
can_manage,
can_read,
)
class _Room:
def __init__(
self,
*,
visibility: Visibi... |
488f321275852bed1fe1925891ab115e2854d7f50dbd42196f903dd419364933 | Python | 4,512 | 154 | from medperf.tests.mocks.benchmark import TestBenchmark
import pytest
from medperf.entities.execution import Execution
from medperf.commands.benchmark.submit import SubmitBenchmark
from medperf import config
PATCH_BENCHMARK = "medperf.commands.benchmark.submit.{}"
NAME_MAX_LEN = 20
DESC_MAX_LEN = 100
BENCHMARK_INFO ... |
24ad65d5058b61167b9a9962bf38cbb44420370a1a562d9f24c016bcdabc8750 | Python | 4,514 | 112 | # -*- coding: utf-8 -*-
import json
from django import forms
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.shortcuts import redirect
from formtools.wizard.views import SessionWizardView
from catmaid.models import (
Stack, StackMirror, Project, ProjectStack, S... |
7b258b09ec0d06b97d3fe35f5d2b63025287bceba62a13a8199b8b133ab9c28a | Python | 4,515 | 100 | import shutil
from pathlib import Path
import pandas as pd
import pytest
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import STUBBED_TESTING_DATA
SESSION_SUBDIR = "csv/sample_data_csv_1"
# No control channel in the store_ids map — mirrors the consistency test for n... |
a111c5693eb29d54f4a014f5504456ee135c5321d79815e86c21609b5a742d9c | Python | 4,515 | 110 | # pytest unit tests for spinalcordtoolbox.math
import os
import datetime
import numpy as np
import nibabel as nib
import pytest
import spinalcordtoolbox.math as sct_math
from spinalcordtoolbox.image import Image
VERBOSE = int(os.getenv('SCT_VERBOSE', 0))
DUMP_IMAGES = bool(os.getenv('SCT_DEBUG_IMAGES', False))
de... |
11beffa40a793d05eec20c61da87312e9bef4c86ed8861a7df685dae574aac61 | Python | 4,517 | 138 | #!/usr/bin/env python
"""
MetaWIBELE: maaslin2_annotator module
Summary maaslin2 annotation
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software wit... |
b1a6b69b67aeaf38361c2688aef587b013b64e6b2d0341f685ae6eecf35a456d | Python | 4,517 | 94 | from create_dataset import *
from utils import *
from PDFN import PDFN
from options import *
from saver import resume, save_img_single
from tqdm import tqdm
def get_parameter_number(model):
total_num = sum(p.numel() for p in model.parameters())
trainable_num = sum(p.numel() for p in model.parameter... |
2ffa84708454b24e7ff8a8b6fe8c8cc1a571b114c8ccc4297a4279c3952a5d35 | Python | 4,520 | 119 | from rest_framework import serializers
from django.utils import timezone
from benchmark.models import Benchmark
from dataset.models import Dataset
from .models import BenchmarkDataset
from utils.associations import (
validate_approval_status_on_creation,
validate_approval_status_on_update,
should_auto_appr... |
a75560a8c5a04524f31cc45b6e3c66c0c4afa02c8f38233f39d960bd52c9fa62 | Python | 4,521 | 88 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
23567225361a3c99a108230ae7fe49a4be21e4dd724e7b0f066303b486d47c5e | Python | 4,523 | 132 | import os
import shutil
import time
from medperf import config
from medperf.config_management import read_config, write_config, ConfigManager
from .utils import full_folder_path
def override_storage_config_paths():
for folder in config.storage:
setattr(config, folder, full_folder_path(folder))
def ini... |
f3639acfac853821e8d379cad4f2aad47e3912d18e67b893f3bbe8c276a61e9a | Python | 4,524 | 131 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule
from mmengine.utils.dl_utils.parrots_wrapper import SyncBatchNorm
from mmseg.models.decode_heads import DepthwiseSeparableFCNHead, FCNHead
from .utils import to_cuda
def test_fcn_h... |
f4d8b25ba3c91c565bf89e3be546ac5e494124f2b82521419bd06fc0c8199bc9 | Python | 4,524 | 114 | #!/usr/bin/python
import logging
import os
import sys
from isorefiner.common import get_version, run_command
logger = logging.getLogger(__name__)
def main(args):
try:
# Set constant variables
prefix = "isorefiner"
mapping_based_tools = ["bambu", "espresso", "isoquant", "stringtie... |
2b545c6c2fae62d367942b7b5ad3a38e05885b9ec0b0557fdfcbde91262a874b | Python | 4,526 | 130 | #!/usr/bin/python
import logging
import os
import shutil
import sys
from isorefiner.common import get_version, run_command, func_with_log
logger = logging.getLogger(__name__)
def main(args):
try:
# Set variables
raw_bam_files = [os.path.abspath(_) for _ in args.bam]
raw_genome_fi... |
132444723e332e43a829133b1ad41d7a664e443d16afc2d9f8041050f9500f9e | Python | 4,527 | 119 | from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch.nn import Module
from torch import Tensor
from torch.nn.parameter import Parameter
from models.helpers import generic_scan, generic_scan_with_states
from module.tau_trainers import TauTrainer, get_tau_trainer_class
from omegaco... |
082ab84707d51e4819227e78d605b3d29c06c739a7eaefa54250108f72793545 | Python | 4,533 | 120 | import tensorflow as tf
import tensorflow_probability as tfp
class CovMLP(tf.keras.Model):
"""
A multi-layer perceptron model for estimating the covariance matrix.
Attributes:
input_dim (int): Dimension of the input vector.
output_dim (int): Dimension of the output vector. The output is th... |
489efcc7703a5a0bea5fc4a8dcd53fbf0e7aeaff4f7db2158bdae7e057d242d3 | Python | 4,533 | 115 | from typing import Tuple, List, Union
from skimage import io
import SimpleITK as sitk
import numpy as np
import tifffile
def convert_2d_image_to_nifti(input_filename: str, output_filename_truncated: str, spacing=(999, 1, 1),
transform=None, is_seg: bool = False) -> None:
"""
Read... |
68536792bad0484b655467723e26c1e3cd3eff9afaf85271468ff3b79a7eb8fd | Python | 4,534 | 150 | """Get stats out of ipyparallel's tasks.db"""
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as... |
ce1dfb47b6be49e0443209dce1c3b6b5c85796f4e2c08e2720043b41d70512f0 | Python | 4,538 | 98 | # -*- coding: utf-8 -*-
from django.db import models, migrations
from datetime import datetime
import django.core.validators
import catmaid.fields
import django.contrib.gis.db.models.fields
import catmaid.control.user
from django.conf import settings
from django.utils import timezone
import taggit.managers
remove_ins... |
0129e0188812e82985191415d6b466104408baf88c5646f12c34fb2d72f53af6 | Python | 4,539 | 147 | import sys
import re
import datetime as dt
from . import term
def log(message):
'''Prints a timestamped message.'''
print(term.cyan(dt.datetime.now().strftime('%H:%M:%S') + ' | ') + message)
def warning(message):
'''Prints a warning message.'''
print(term.yellow('warning: ') + message)
def error(... |
6cfa098a5e82772277169c2b0b89ab3983c4b16763b0a4792fbc699325aedee8 | Python | 4,539 | 147 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 27 14:50:20 2023
@author: ingvieb
"""
import SimpleITK as sitk
import numpy as np
import nibabel as nib
import json
import os
from tkinter import *
def LMRtoElastixPoints(filepath, fixedAge, movingAge):
with open(filepath) as file:
openFile = json.load(fil... |
87ee0058c6ee834f064ee6454665a95afe30f17a0c3239878b2e90b0cc1e5985 | Python | 4,541 | 127 | import sys
import torch
import numpy as np
from Adversarial_Observation.BirdParticle import BirdParticle
import pandas as pd
class PSO:
def __init__(self, starting_positions: torch.Tensor, cost_func: callable, model: torch.nn.Module,
w: float = 1.0, c1: float = 0.8, c2: float = 0.2, minclamp: floa... |
65a8d8653762583bfbbddbe07894038d8fd662eb2591f54b42dd1b3a27fd0d36 | Python | 4,542 | 119 | #!/usr/bin/env python
"""Pivot bin/eval/compute_model_stats.py's long-format CSV into a workbook shaped
like manuscripts/Poison26/260914_ModelStats.xlsx: one sheet per dataset, one block
per architecture, six columns per block (the {standard, standard+aug, fgsm,
fgsm+aug, pgd, pgd+aug} clean-test combinations), and one... |
f1481d9923f54e40704a30a96856ea3bf0611d30cf45b91b220dce83bbe34678 | Python | 4,543 | 123 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
0dfa6eac584916c2398642cd522072bd34f284b34db994a5d88567aaf03a3974 | Python | 4,545 | 126 | """Test sandboxjs.py and related code."""
import logging
import os
import shutil
import threading
from pathlib import Path
from typing import Any
import pytest
from cwl_utils import sandboxjs
from cwl_utils.types import CWLFileType
from cwltool.factory import Factory
from cwltool.loghandler import _logger, configure... |
c2c613d2a17d0d76e0c8785a90c2238b0135f0ac4edf8bf1cd42bde7a1f77d7e | Python | 4,555 | 137 | import sys
import pytest
import numpy as np
import marshal
from keras.utils.generic_utils import custom_object_scope
from keras.utils.generic_utils import has_arg
from keras.utils.generic_utils import Progbar
from keras.utils.generic_utils import func_dump
from keras.utils.generic_utils import func_load
from keras impo... |
eb7c8a44397862979e0eb83015d529895d3d7e054c86d470e0ee2d0b6c378a62 | Python | 4,556 | 113 | import logging
import os
from e3nn import o3
def check_args(args):
"""
Check input arguments, update them if necessary for valid and consistent inputs, and return a tuple containing
the (potentially) modified args and a list of log messages.
"""
log_messages = []
# Directories
# Use work... |
5db3bbb052e39d518dbbb30cb1510fe466662c95e15e904e34e563de48469e27 | Python | 4,558 | 117 | import os
import sys
from dataclasses import dataclass, field
from typing import Optional
from transformers import HfArgumentParser, TrainingArguments, set_seed
from unsloth import is_bfloat16_supported
from unsloth import UnslothTrainer, UnslothTrainingArguments
from unsloth import FastLanguageModel
from trl import Da... |
1a692e0893ae1021eecb07e2969e09dac7f5cdd9b144489bfccfd78ac2b01127 | Python | 4,560 | 88 | import torch
import torch.nn as nn
from layers.embedder import PackedBert
class CodePrompt(nn.Module):
def __init__(self, args) -> None:
super().__init__()
self.prompt_num = args.prompt_num
self.prompt_embeddings = nn.Embedding(self.prompt_num, args.hidden_size)
def forward(self, batc... |
2a80e0de732dc4a97986512cd466ad63dde0ba49990254c79b0d7a58839fd6e1 | Python | 4,562 | 122 | from typing import Optional
from medperf.exceptions import InvalidArgumentError
from medperf.commands.mlcube.submit import SubmitCube
from medperf.commands.asset.submit import SubmitAsset
class SubmitModel:
@classmethod
def run(
cls,
name: str,
operational: bool,
container_conf... |
b7d7587f3fd8340af483046b5d4118e5a8bde0f82174e8cf4e91db4443a6a3e2 | Python | 4,563 | 145 | import pytest
from medperf.exceptions import (
InvalidCertificateAuthorityError,
InvalidCertificateError,
MedperfException,
)
from medperf import certificates as certs
from medperf.tests.mocks.certificate import TestCertificate
from medperf.tests.mocks.ca import TestCA
from medperf.tests.mocks.cube import T... |
db014bfd0a9a889f3ec21147e702950cf9eb6f889494d52d1a21372a22156956 | Python | 4,563 | 143 | #!/usr/bin/env python3
"""
Aggregate unblinding for the CICADA locked held-out 11-mm smoothing review.
Reads the completed blinded scoring CSV and the separate private unblinding key.
Prints aggregate agreement only; does not print subject IDs, task names, or IC
numbers.
All material remains PRIVATE human-subject-der... |
243461f2b92cbfb7fc6ae00456c380cc22232745d75f8b61291d92570b4d18a7 | Python | 4,564 | 121 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
8a7625ac4a2d0321e58b23c8b46dcf984877b11678deffa73db60e7785910a95 | Python | 4,564 | 153 | """Tests for bug fixes from the 2026-03-03 SKILL.md design."""
from __future__ import annotations
import json
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from zndraw.cli_agent import app
from zndraw_joblib.schemas import TaskResponse
from .conftest import invoke_cli
if TYPE_CHECKING:
... |
a76219bf06d6fa47d45d61ac3a018d6d8f15d5c53156b8b3467be5dcf2563d8a | Python | 4,564 | 115 | def parse_cp_features(
feature: str, channels: list = ["DNA", "RNA", "AGP", "Mito", "ER", "mito_tubeness"]
):
"""Parses a CellProfiler feature string into its semantic components.
This function will take a feature string and return a dictionary containing its semantic components,
specifically: the compa... |
277e23a296df9938c1bdd1fadf8446c63ab06373b99c69fe95fa411f36b65a30 | Python | 4,568 | 131 | """Scope-filtered room listing tests."""
import pytest
from helpers import (
_register_and_login,
create_room_via_api,
create_test_user_in_db,
get_user_id,
)
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_list_rooms_union(client: AsyncClient) -> None:
token_a = await _register_... |
1856d35c0a66d0804fa8ddced89bf8565ef24fd35728a9f979cda5f6cac7e8b4 | Python | 4,570 | 135 | import torch
from torch.nn import L1Loss, MSELoss
from merlinth.losses.pairwise_loss import mse
class L2:
def __init__(self, mask_image=False):
super(L2, self).__init__()
self.mask_image = mask_image
if not self.mask_image:
self.loss_ = MSELoss()
else:
self.... |
417c261e721e5c7c68765cac3e202ee4a9e2c741dcc3ed1246ce4a3f5a7628c7 | Python | 4,570 | 145 | import numpy as np
import cupy as cp
import copy
from .conv import *
class iSeq:
W = None
H = None
V = None
U = None
max_iter = None
tolerance = None
z_th = None
k = None
l = None
cost = None
Vmax = None
Wlim = None
Hlim = None
def __init__(self, V, k, ... |
58216a0594c187b6e94eeeb106a1cf57cf03f58ebc1d2db4909fa8c2a98f8f59 | Python | 4,570 | 99 | # # measure the localling decoding performance on different data. Run generate_processed_exp_data.py first
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from grid_cell.linear_regression import fit_a_line, output_params, draw_line
import hickle as hkl
import os
from sklearn.decompositio... |
eacb8576c40796302ca2ca18196d850c021b723b95ef6a94eb070e4db0f18787 | Python | 4,570 | 130 | import torch # type: ignore
import torch.utils # type: ignore
from torchvision import models, transforms # type: ignore
import pandas as pd # type: ignore
import numpy as np # type: ignore
from code_files.utils import ( # type: ignore
set_seed,
worker_init_fn
)
from code_files.preprocessing import ( # type: ... |
6959fe8e21d0b7dd3a8201d0bc01e17465850907b8db70e5043b13f51e080e3a | Python | 4,572 | 112 | from csbdeep.internals.blocks import conv_block2, conv_block3
from csbdeep.utils import backend_channels_last
from csbdeep.utils.tf import keras_import
from n2v.nets.blurpool import MaxBlurPool2D
K = keras_import('backend')
Conv2D, MaxPooling2D, UpSampling2D, Conv3D, MaxPooling3D, UpSampling3D, Cropping2D, Cropping3D... |
8c328d474cdeb0b15400fdc2187307b4afdaa0c96eeccad2b41956ff48251339 | Python | 4,572 | 107 | import shutil
from pathlib import Path
import pandas as pd
import pytest
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import STUBBED_TESTING_DATA
SESSION_SUBDIR = "csv/sample_data_csv_1"
STORE_ID_TO_STORE_LABEL = {
"Sample_Control_Channel": "control_region",
... |
d10664ee83fc25ac69e0209336b140338ea5022f35e101b3dabb39cd752353a9 | Python | 4,573 | 152 | """Get stats out of ipyparallel's tasks.db"""
from __future__ import print_function
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesse... |
9f974365429532a68bfa0ea5c98f52bdc3418d91c376ab59200bf032b8d4ebfe | Python | 4,575 | 157 | from typing import List, Set, Dict, Optional
import inflection
from cachetools import cached
from kgx.config import get_logger
from kgx.graph.base_graph import BaseGraph
from kgx.utils.kgx_utils import get_toolkit, get_cache, get_curie_lookup_service
from kgx.prefix_manager import PrefixManager
ONTOLOGY_PREFIX_MAP: D... |
b7f0bab966c5508e36789cb1e86b714b790faf2e9af25169add711c2a57dc4c4 | Python | 4,575 | 152 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from mmengine.dataset import ConcatDataset, RepeatDataset
from mmengine.registry import init_default_scope
from mmseg.datasets import MultiImageMixDataset
from mmseg.registry import DATASETS
init_default_scope('mmseg')
@DATASETS.register_module(... |
c5d45c772278cc0fbf7ccac6271f1612e4c07bf9678b6bff246d82cee18db24a | Python | 4,576 | 128 | import os
import logging
from medperf.commands.model.submit_util import ContinueAssetSubmission
from medperf.comms.entity_resources import resources
import medperf.config as config
from medperf.entities.asset import Asset
from medperf.exceptions import InvalidArgumentError
from medperf.utils import get_file_hash, remo... |
9c99ae431ced6e3a3d8d6742af0b2259f44c8868ccfea0501ed412c373dc4bbd | Python | 4,578 | 129 | """Tests for CLI auth commands."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from zndraw.cli_agent import app
from zndraw.state_file import StateFile
if TYPE_CHECKING:
from typer.testing import CliRunner
def test_auth_login_opens_browser(
... |
776c229120021f3e0b1e0f2049969e3f70ccadd43f6481337c629b25e29726ec | Python | 4,579 | 131 | """Generic vocabulary-partitioning tests for all entries in VOCABULARY_REGISTRY.
For every registered vocabulary, two tests run automatically:
test_ids_non_empty
Each compendium's write_X_ids() must produce at least one identifier.
test_no_id_in_multiple_compendia
No identifier may appear in more tha... |
c8193949c743dfbea638a1a7b8fa433462e24857af7777108a3ec35da746099b | Python | 4,582 | 128 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
from dash import html, Input, Output, callback
import os
def get_available_options(meta, searched_options, **conditions):
meta = pd.DataFrame(meta)
all_options = list(meta[searched_options].unique())
# sorting options for conis... |
cf260654405d0687c9383f786a6080cb0c1578470cefc9ec46892e06a1c7c01c | Python | 4,586 | 116 | from luna.paths import LunaPaths
from luna import candidate_info, dataset
from luna.ct import Ct
from luna.prepcache import LunaPrepCacheApp
from torch.utils.data import DataLoader
from Utils.models import *
from Utils.TrainModelLUNA import *
from Utils.config import *
from tqdm import tqdm
import matplotlib.pyplot as... |
ca856ee2e6f7066a4a54272949beff02cc620527e2d77e781e6f658095bab30c | Python | 4,587 | 128 | # Generated by Django 2.1.7 on 2019-02-20 18:16
import django.contrib.postgres.fields
from django.db import migrations, models
forward = """
SELECT disable_history_tracking_for_table('nblast_similarity'::regclass,
get_history_table_name('nblast_similarity'::regclass));
SELECT drop_history_view_f... |
205f8520b7b45a0cf7f5e5ab678ec37918bc36b1e2f92b5b2e4a872e0e1cf204 | Python | 4,590 | 142 | """Share-link REST + permission-compose tests."""
import pytest
from helpers import (
_register_and_login,
create_room_via_api,
create_test_user_in_db,
)
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_create_and_use_view_link(client: AsyncClient, session) -> None:
owner = await _re... |
7ffeb7d41a7f7931b1f70431b8e224a7cd2349d01497655d08e5ffdc93776abb | Python | 4,591 | 98 | import os
from dotenv import load_dotenv
import openai
from test_get_all_repo import get_repos
from bs4 import BeautifulSoup
import markdown
import re
import time
# Load environment variables
load_dotenv()
TOKEN = os.getenv('TOKEN')
# Set up the OpenAI API client
openai_api_key = os.environ["OPENAI_API_KEY"]
# 过滤文本中链接... |
e3e5a588da867833ff22308e7495a4bb211651fa61d919e2f75568638702cb28 | Python | 4,592 | 125 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# pyre-strict
# pyre-ignore-all-errors[2,33]
from collections import defaultdict
from typing import Any, Counter, DefaultDict, Dict, Optional, Tuple, Union
import torch.nn as nn
from torch import Tensor
from .jit_analysis import JitModelAnalysi... |
fb26f9719c6506241de4ce61a7762e3897490074a8d0206566ea3082b2901552 | Python | 4,593 | 143 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmengine.model import BaseModule
from torch import Tensor
from mmseg.registry import MODELS
from mmseg.utils import OptConfigType
class BasicBlock(BaseModule):
"""Basic block fr... |
ae4cac9b947ae467552486840f3f291106328f2ddcef4da0c3a410c48d9be943 | Python | 4,595 | 123 | from medperf.containers.parsers.parser import Parser
from medperf.exceptions import InvalidContainerSpec
from medperf.enums import ContainerTypes
import logging
class SimpleContainerParser(Parser):
def __init__(self, container_config: dict, allowed_runners: list):
self.container_config = container_config
... |
ecc34c8f7c5c34c823b831d3424ac44950bd5a0d21c2cc7f45ae35d01fceffbd | Python | 4,596 | 144 | # Standard Library Imports
import copy
import locale
import os
# Third Party Imports
import matplotlib.pyplot as plt
import MDAnalysis as md
import numpy as np
import tensorflow as tf
# Encodermap imports
import encodermap as em
molname = "diubi"
# ######################### Load data #########################
# ... |
46563c1db0360d3e277d53677710b1f130fdc9f35ca503fbbe776b6ee217abd3 | Python | 4,597 | 82 | import numpy as np
import gpflow
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from gpflow.utilities import positive
from gpflow import Parameter
from grid_cell.gaussian_wishart.src.likelihoods.BaseWishartLikelihood import WishartLikelihoodBase
class FactorizedWishartLikelihood(Wishar... |
99acb8bb42b15de315bd40c4a423085ead124db9b831ba5f9f9ca1d0670584e7 | Python | 4,597 | 124 | import shutil
from pathlib import Path
import pytest
from guppy.testing import compare_output_folders
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import TESTING_DATA, event_ts_offset_for, recording_start_for
CONSISTENCY_CASES = [
(
"SampleData_Neuropho... |
b605b560031c6bd8db3203fd98caec3059985c2022cb28453a3a701a49a7e18b | Python | 4,597 | 123 | import ftplib
import pyoxigraph
from src.babel_utils import parse_rdf_literal, pull_via_ftp
from src.prefixes import CHEMBLCOMPOUND
def pull_chembl(moleculefilename):
fname = get_latest_chembl_name()
if fname is not None:
# fname should be like chembl_28.0_molecule.ttl.gz
# Pull via ftp is g... |
832c630981c2b48d45874ebdcd13caa6f6f76d444769e02e023e8a3551cb06c2 | Python | 4,598 | 99 | # pytest unit tests for sct_detect_compression
import os
import pytest
import tempfile
import nibabel
import numpy as np
import pandas as pd
from spinalcordtoolbox.utils.sys import sct_test_path
from spinalcordtoolbox.scripts import sct_detect_compression
def test_sct_detect_compression_check_missing_input_segmenta... |
5eadf0da8535484104d388990e478d26b709a7c503a392a87a6de9a63c895ce6 | Python | 4,601 | 120 | from medperf import config
from medperf.entities.certificate import Certificate
from medperf.utils import get_pki_assets_path, remove_path
from medperf.account_management import get_medperf_user_data
from medperf.enums import CryptoKeyType
import os
import base64
import logging
def _check_and_clean_certificate_corrup... |
0c1123a53409461e103f1979c4e974daf3bf16f9c5f0de29ac33245562ba03cd | Python | 4,602 | 109 | #!/usr/bin/env python
from mincepie import mapreducer, launcher
import gflags
import os
import cv2
from PIL import Image
# gflags
gflags.DEFINE_string('image_lib', 'opencv',
'OpenCV or PIL, case insensitive. The default value is the faster OpenCV.')
gflags.DEFINE_string('input_folder', '',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.