sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
14d5fe66b58d48df42d71b55f379f318e0804eb46eabf016fad6b4a79bd96081
Python
2,868
81
import json from tqdm import tqdm import os import argparse label2desc={'true':'是','false':'不是'} def load_data(file_path,is_training=False): with open(file_path, 'r', encoding='utf8') as f: lines = f.readlines() result=[] for line in tqdm(lines): data = json.loads(line) ...
2b3bdcbc68a8d44c473a12083118685e96f2ce4b40a887cbbf728caf2b64f230
Python
2,868
93
_base_ = [ '../_base_/datasets/cityscapes_1024x1024.py', '../_base_/default_runtime.py', ] # The class_weight is borrowed from https://github.com/openseg-group/OCNet.pytorch/issues/14 # noqa # Licensed under the MIT License class_weight = [ 0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, 1.0489, 0.87...
b77017c60d72c42f09c72c319c8005fa9d857750d1f28d58a152a7e0151b9e2a
Python
2,868
93
_base_ = [ '../_base_/datasets/cityscapes_1024x1024.py', '../_base_/default_runtime.py', ] # The class_weight is borrowed from https://github.com/openseg-group/OCNet.pytorch/issues/14 # noqa # Licensed under the MIT License class_weight = [ 0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, 1.0489, 0.87...
2a0bd817e9f73e0223501b8081621b47d53c02c503bfc072108fd6cdc1d11971
Python
2,875
97
import os import yaml import argparse import numpy as np from utils import get_file_basename class Statistics: def __init__(self, data_path, params_file, out_path): """A class wrapper for calculating the statistics of the prepared dataset. The following statistics are calculated: ' ...
0030219bb770a183bf1427675df7d7b39a4dc9e9b4254589356251ba4d43460b
Python
2,878
94
import os from medperf.exceptions import InvalidArgumentError, InvalidEntityError from medperf.tests.utils import calculate_fake_file_hash import pytest from medperf.comms.entity_resources import sources, utils import synapseclient # prefixes DIRECT = sources.DirectLinkSource.prefix SYNAPSE = sources.SynapseSource.pre...
2705889bbd31024ef042f7abf0b2862bef81e126444b9d4b5e0c5b534fcf9069
Python
2,878
90
_base_ = [ '../_base_/models/setr_mla.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] crop_size = (512, 512) data_preprocessor = dict(size=crop_size) norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( data_preprocessor=data_preproce...
7d2d351c0e3cc0253f98470254be2f665da0851f433c7d3c6285afa1ed3b1ce1
Python
2,878
96
#!/usr/bin/env python # # Compute flow from velocity encoding (VENC) sequence, based on the MRI phase image. More details in: https://mriquestions.com/what-is-venc.html # # Copyright (c) 2023 Polytechnique Montreal <www.neuro.polymtl.ca> # License: see the file LICENSE import sys from typing import Sequence from textw...
6c76b7ac5edf5731502adeebb80ce69972675c5d9bbd019ed536a163adfcabb3
Python
2,880
85
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import shutil from unittest import TestCase import torch from mmengine.structures import PixelData from mmseg.evaluation import DepthMetric from mmseg.structures import SegDataSample class TestDepthMetric(TestCase): def _demo_mm_inputs(self,...
faf6970e00a671102263015e2edd7cd437081e194042296ff7cbee91ec06f9be
Python
2,882
68
"""Unit tests for the settings GuPPy remembers between launches.""" import json import pytest from guppy.settings import load_settings, remember_root_folders, remembered_root_folders @pytest.fixture def roots(tmp_path): """An input root folder and an output root folder that both exist on disk.""" input_roo...
74747d22376b2e89d74e44b01c57afb47b970974e4c44874c27e5c8bd57d3fc5
Python
2,884
98
"""Room-update feed delivery is scoped to authorized viewers. These tests drive `broadcast_room_update` directly (no socket client), which keeps the assertions isolated to the routing logic — the MockSioServer captures emit calls and the tests check which rooms received the event. """ from uuid import uuid4 import p...
a9e92836d2359efa8f722fa127b144ff8e8c820bd4d77fa73880042a6b7dc837
Python
2,884
78
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dash import Input, Output, callback import base64 import os from PIL import Image # cropping images before plotting splitstree graphs. def crop_image(image_path): im = Image.open(image_path) right, lower = im.size left, upper = 0,0 h1, h2 = 150,...
6f91d0fec73556be412c7efa0086e002ea74bbb9d8f1d8ecd8c53c8cb9833dbd
Python
2,885
85
import torch.nn as nn import torch import torch.nn.functional as F import numpy as np import pandas as pd import os import random import mlflow import sys from torch.backends import cudnn def get_device(cfg): device = torch.device( "cuda:{}".format(cfg.train.device_ids[0]) if torch.cuda.is_available() ...
851d4b95432a84c23c9b3c8924f2863c992b9ab3bc2db6b528150455545c4556
Python
2,885
102
import pytest import base64 import uuid import medperf.config as config from medperf.commands.certificate.submit import SubmitCertificate from medperf.exceptions import CleanExit, MedperfException from medperf.tests.mocks.certificate import TestCertificate from medperf.enums import CryptoKeyType PATCH_SUBMIT = "medpe...
7a5fc06d0801c09d0954e9e949b7c24384cbdb4e7e7a1bd71c12775d37c206f0
Python
2,886
61
# parse config files import json def parse_json_config(json_file): with open(json_file) as f: decoded_dict = json.loads(f.read()) # check if we have all the arguments: assert("transcript_counting" in decoded_dict) assert("isoform_parameters" in decoded_dict) assert("alignment_parameters" i...
76c806406ad3e8d737403cb0716db8b7a0e6e068b8c6d73ce23939c9c178c927
Python
2,888
99
import random import numpy as np import pandas as pd import os import torch def set_seed(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':16:8' torch.manual_seed(seed) torch.cuda.manual_seed(seed) ...
085b653b41c0ae22dc625fd12d4d6bcabf1ee1ad78091e4267ea7508352fa164
Python
2,889
72
import numpy as np def ellipse_params(c, width=1.177): a = np.diag(c).sum() b = np.sqrt(np.square(c[0, 0] - c[1, 1]) + 4 * np.square(c[0, 1])) u2 = (a + b) / 2 v2 = (a - b) / 2 cu = width * np.sqrt(u2) cv = width * np.sqrt(v2) theta = np.arctan((u2 - c[0, 0]) / c[0, 1]) * 180 / np.pi re...
d918257d52b9a306777a7e8fd898bdbb9e1f3abcb73600770a102ec9eb80a0ff
Python
2,889
77
from copy import deepcopy from CybORG.Shared import Observation from CybORG.Simulator.Actions import Action from CybORG.Shared.Session import VelociraptorServer from CybORG.Simulator.State import State class Monitor(Action): """ Collects events on hosts and informs Blue Agent. This action runs automatically...
3badc5a49da5f9c09332b435cf606b4da122831b67343cae8a37b24a27b64fd7
Python
2,890
92
from django.utils import timezone from rest_framework import serializers from benchmarkdataset.models import BenchmarkDataset from benchmarkmodel.models import BenchmarkModel from .models import ModelResult class ModelResultSerializer(serializers.ModelSerializer): class Meta: model = ModelResult ...
82ac77d266cf8de5f2a2d1be3aedd23c4ebc90657b2c8e159a9c634b3c8b6a57
Python
2,891
88
import torch import torchvision import numpy as np import tqdm import Adversarial_Observation as AO def trainModel(model, train_loader, optimizer, loss, epoch, filename): """ Trains the model using the provided data loader, optimizer, and loss function for one epoch. Saves the training loss to the specifie...
91c3e5995e37ba79b1a3ad803463d419b653e42f74ed3b5fe68c05e4bf1df870
Python
2,892
83
import subprocess import numpy as np import os import argparse # Setup argument parser parser = argparse.ArgumentParser(description="Run script with custom iterations") parser.add_argument('--N', type=int, default=5, help='Number of iterations') # Parse arguments args = parser.parse_args() # Use the argument num_ite...
17b7c0f82199582b6b1eb6b965aab3cd015b45a0a24161bbe80598436342e266
Python
2,893
92
import logging import subprocess import sys from collections.abc import MutableMapping from io import StringIO from pathlib import Path from typing import cast from cwl_utils.types import CWLObjectType from cwltool.context import RuntimeContext from cwltool.factory import Factory from cwltool.workflow_job import Work...
72d0e9b644be47e68585c8bf2bf8ffdda6e5689716673de5d989cca8f36cd3e0
Python
2,893
65
# pytest unit tests for sct_apply_transfo import pytest import logging import numpy as np from spinalcordtoolbox.image import Image from spinalcordtoolbox.scripts import sct_apply_transfo from spinalcordtoolbox.utils.sys import sct_test_path logger = logging.getLogger(__name__) @pytest.mark.sct_testing @pytest.ma...
45e8c5f529d4b61343bc6b86a9acfe98ef5e5a40339eb5d34d2ff8b39cd6dada
Python
2,894
80
import numpy as np import gc import pytest import xgboost as xgb from hypothesis import given, strategies, assume, settings, note import sys import os # sys.path.append("tests/python") # import testing as tm from xgboost import testing as tm parameter_strategy = strategies.fixed_dictionaries( { "max_dept...
87587f170616d469e2c5cf6f37846e2ed220204719d5e05efd4b2fad60a3acc8
Python
2,894
77
baseFileName = './shellScripts/sparse100_10class_noise_' baseSimTag = 'sparse100_10class_noise_' def generateCommand(trial_num=0, num_trials=10, learning_rate=0.001, sim_tag='default', exc_hid_rat=0.5, epochs=30, log_file='example.log', w1_std=-1, w1_s...
950469561fde12d9cb940b80e544f55fc82df8812cfef453d72118458b0ed689
Python
2,894
67
import holoviews as hv import numpy as np import pytest from holoviews.streams import RangeXY from guppy.visualization.shading import shade_trace from guppy_test_data import resolve_plot # A flat trace long enough to need shading, carrying a single one-sample artifact spike. # 200,000 samples at 0.01 s spacing span t...
dffa9d837239f95990fc2306d3d6bb66ff9e4c56126f9d6474c33b9833e08cfe
Python
2,894
77
baseFileName = './shellScripts/sparse095_10class_noise_' baseSimTag = 'sparse095_10class_noise_' def generateCommand(trial_num=0, num_trials=10, learning_rate=0.001, sim_tag='default', exc_hid_rat=0.5, epochs=30, log_file='example.log', w1_std=-1, w1_s...
ebfbfee224aed869662bc563895c00e856afa1393cfff4c48e4c4c05e0a0b001
Python
2,896
85
from cryptography.hazmat.primitives import serialization import yaml from distutils.dir_util import copy_tree import os import tomllib import tomli_w import base64 from cryptography.hazmat.primitives.serialization import ( load_pem_private_key, Encoding, PublicFormat, ) from cryptography import x509 def g...
b57a32537414c5690b73beb2a29edb9dfa44f853f741a592a0a82cc9d0007c0c
Python
2,898
91
import typer import medperf.config as config from medperf.decorators import clean_except from medperf.commands.certificate.client_certificate import GetUserCertificate from medperf.commands.certificate.server_certificate import GetServerCertificate from medperf.commands.certificate.submit import SubmitCertificate from...
9d30d7e59db8a0879dea68de6585f5c1418f5b59bf24d663f3db39029232cf3d
Python
2,899
89
import itertools import os from src.babel_utils import ThrottledRequester def chunked(it, size): """Wraps an iterable, returning it in chunks of size: size""" it = iter(it) while True: p = tuple(itertools.islice(it, size)) if not p: break yield p def lookup(meshes): ...
ca6f9affdb8de5a1a549478502d5438dbe1a4de565f65d1da7bb286ff81b8710
Python
2,902
100
import torch import torch.nn as nn import torch.nn.functional as F from .resnet import conv3x3x3, conv1x1x1, get_inplanes, ResNet class PreActivationBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super().__init__() self.bn1 = nn.BatchNo...
e21d173aabed65e8c6568238720fd0555c9975cfe0c77663dbec02945c2f4681
Python
2,902
101
from __future__ import annotations from rest_framework.permissions import BasePermission from benchmarkmodel.models import BenchmarkModel from benchmark.models import Benchmark from .models import Certificate from django.db.models import OuterRef, Subquery class IsAdmin(BasePermission): def has_permission(self, r...
82f853d6ea416606e7a1871143cda4dc72cf47640eebeca2e96118748d290b59
Python
2,903
95
import functools from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are 'none', 'mean' and 'sum'. Returns: Tensor: Reduced loss tensor. """ reduction_en...
5eab90232444426bcfd36d142b4a32e83e9c940be1c019b2233bc590af073c45
Python
2,905
75
"""Query list of all contributors and reviewers in a release""" import json import re import sys import requests from sh.contrib import git if len(sys.argv) != 5: print(f'Usage: {sys.argv[0]} [starting commit/tag] [ending commit/tag] [GitHub username] ' + '[GitHub password]') sys.exit(1) from_com...
76db6992b93d2cb3a5d68f146b424eec1d35a97e88a5bf4df86cf0e6c7169e76
Python
2,905
65
#!/usr/bin/env python """ extract dvars and fd info from fmriprep_confounds_timeseries calculate mean and append it with BIDS data """ __author__ = "Heejung Jung, Owen Collins" __copyright__ = "Spatial Topology Project" __credits__ = [""] # people who reported bug fixes, made suggestions, etc. but did not actually wri...
36c401c4bcd1b4f61dccfa2c5dc672cffc29fda6f4ddad363dff6714238bf3b5
Python
2,906
82
import shutil import pytest from medperf.commands.certificate.delete_client_certificate import DeleteCertificate from medperf.tests.mocks.certificate import TestCertificate from medperf.exceptions import CleanExit from medperf import config from medperf.enums import CryptoKeyType PATCH_DELETE = "medperf.commands.certi...
8eacf4cdbb29c6fe13225e7f189dea99d70b91ab2dae199907e28e6be5b587d7
Python
2,908
74
# -*- coding: utf-8 -*- """ This is a custom version of the postgresql_psycopg2 adaptor that overrides last_insert_id so that it works with inherited tables. Instead of using pg_get_serial_sequence, this finds the default value of the primary key for the table and parse out the sequence name from that. As of May 2015...
154231d41948d91bee6efff463057146e7754082d9cb45b4b8ab4e08c9f1049b
Python
2,910
93
""" Validate model predictions output for BraTS-MEN-RT and BraTS-Path 2024. """ import os from glob import glob import numpy as np import pandas as pd import SimpleITK as sitk import yaml from cnb_tools import validation_toolkit as vtk def check_image_dims(path): base_size = np.array([182, 218, 182]) image ...
687b4052f682f646712bfc8e68c06ced93b6b6be3ac9a9c7848306872aee072f
Python
2,913
131
# -*- coding: utf-8 -*- """ Mapping the CATMAID datamodel to a graph database Each project has its own annotation graph. - Can I point from one graph to the vertex of another graph? - Classes could be derived from Ontologies http://bioportal.bioontology.org/ """ import time from bulbs.model import Node from bulbs.p...
6a9e2aad38bd2e9f16eb2c72c1b813722191341f2226b3cfe2839aaba065b497
Python
2,913
111
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import math from typing import Optional import torch from ..initializers import he_orthogonal_init class Dense(torch.nn.Module): """ ...
4382c316e9269ef4052051612b25787ba6455935f6c29423c2acb02f6837af1a
Python
2,915
56
# scans_list = sorted(glob.glob('sub-*/**/*scans*.tsv', recursive=True)) # for scan_fname in scans_list: # # NOTE: Step 1: Get the scans.tsv using datalad # run_command(f"datalad get {scan_fname}") # print(f"datalad get {scan_fname} ") # # Check if scans_file is not empty and unlock it using git annex #...
4f0037bad70dabb4dd95e9f80d386174b164213df3440f02b3c0327e2b06832e
Python
2,915
55
# 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...
e39f58ca617be3852d0adb16c94407c07afe300a44b0d4193b65643472b53eb6
Python
2,916
97
""" Contains functions for initialising models and loading their default configurations. Depends on: ./model_configs.json. Licence: BSD-3-Clause Author: Hanna M. Tolle """ import os from typing import Dict import json import models def init_model(model_type: str, params: Dict = {}): """Initialises model.""" ...
076e2a3f5b3c59a6c63fcbbd7cbf2d35abfe2e61e3365f01678fb606f05e239d
Python
2,919
83
# Copyright 2013 Google Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the foll...
1ab144f471460d5b02d96531e9283721486fd0c483b46c18c64b722050467609
Python
2,922
79
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import io import random import pytest import requests import torch from ase.build import add_adsorbate, fcc111 from ase.optimize import BFGS...
21360bf1a9da23d573b84a7581c4082b9bc06363ec0ee56c80cb287723d14fed
Python
2,923
68
# SPDX-License-Identifier: Apache-2.0 from cpuinfo import get_cpu_info import ort_test_dir_utils import onnxruntime import onnx import os from shutil import rmtree import tarfile import test_utils def has_vnni_support(): return "avx512vnni" in set(get_cpu_info()["flags"]) def run_onnx_checker(model_path): ...
51da08ccb0d444e99cc2748b10f16137587371634f15b5b39ebbbaa0d5e61c9c
Python
2,923
83
#!/usr/bin/python import logging import os import shutil import sys from isorefiner.common import get_version, run_command logger = logging.getLogger(__name__) def main(args): try: # Set variables raw_bam_files = [os.path.abspath(_) for _ in args.bam] raw_genome_file = os.path.ab...
f09491c104f05c4cf3fcd9aafb8fd7973fb200861e3b6ee0d3a278ac4209a226
Python
2,923
65
from ipaddress import IPv4Address from CybORG.Shared import Observation from CybORG.Simulator.Actions.Action import RemoteAction from CybORG.Simulator.HostEvents import NetworkConnection from CybORG.Simulator.State import State class Portscan(RemoteAction): def __init__(self, session: int, agent: str, ip_address...
c40a8d13632c2fac486d0716938b50752cee54f7f28502f6daddc1fcf4409d56
Python
2,925
98
import os from kgx.source.sssom_source import SssomSource from kgx.transformer import Transformer from tests import RESOURCE_DIR from tests.unit import load_graph_dictionary def test_load1(): """ Read a SSSOM formatted file. """ t = Transformer() source = SssomSource(t) g = source.parse( ...
2c5c56d9f9cf00bce8ccf701fd3be41af4ceda7290755254aa8fe47687fed857
Python
2,926
87
# -*- coding: utf-8 -*- from django.db import migrations, models forward_history = """ SELECT disable_history_tracking_for_table('nblast_similarity'::regclass, get_history_table_name('nblast_similarity'::regclass)); SELECT drop_history_view_for_table('nblast_similarity'::regclass); ALTER TABLE...
7c8650b5e1f4f01f2c22c982cf98da9866187f6864cf6aae288aef1be4bad047
Python
2,926
75
"""Context-Aware Implicit Neural Representations to Compress Earth Systems Model Data DEVELOPED AT: Department of Chemical Engineering University of Utah, Salt Lake City, Utah 84112, USA DIRECTOR: Prof. Salah A Faroughi DEVELOPED BY: ...
f1c15576a4d59b79d4288c46ff01485f0573e01fd1c56bbe896d6904d280faf6
Python
2,926
104
from __future__ import annotations from typing import Optional import pydicom as dcm from heudiconv.utils import SeqInfo scaninfo_suffix = ".json" def create_key( template: Optional[str], outtype: tuple[str, ...] = ("nii.gz",), annotation_classes: None = None, ) -> tuple[str, tuple[str, ...], None]: ...
199e67b574cef9c6078d5217d62fa226b64fc20b9ee01fc1bca24942a0065390
Python
2,929
71
import sys from pathlib import Path import numpy as np import types sys.path.append(str(Path(__file__).resolve().parents[1])) from eigenstrapping.datasets import get_surface_examples def test_get_surface_examples_download(tmp_path, monkeypatch): sample_data = "1 2 3\n4 5 6\n" calls = [] def fake_downloa...
18e40fdf1ded6eb2202199d1e21f3bc98774fe4620f964df55f34c6ebe12dc4a
Python
2,931
102
#!/usr/bin/env python import argparse import boto3 from jinja2 import Environment KEY_NAME = 'single_cell_opt.pem' HEAD_INSTANCE_NAME = 'single_cell_opt_head' WORKER_INSTANCE_NAME = 'single_cell_opt_worker' hosts_template = ''' [neuron-optimizer-head] {{ head_public_ip }} [neuron-optimizer-worker] {% for ip in wo...
674eb477e8213cb19640deabc4ead50e496eb67b772882eefeb735b84ec6bf83
Python
2,931
79
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import math import scienceplots import matplotlib.gridspec as gridspec from functools import reduce import torch import math from scipy import stats centaur_70b = torch.load('../generalization/results/generalization_full_log_l...
ab9552cd43d24879d8fb31172e2beef449bff2657a74d18fa58ca1f2d2cad28e
Python
2,931
87
import numpy as np from scipy.spatial import KDTree import nearl import nearl.featurizer import nearl.io from nearl.features import Feature # Result is a 4*9 (36 dimensions) contact map # Rows (protein) : C, N, O, S # Columns (ligand) : C, N, O, F, P, S, Cl, Br, I PROT_MAP = {6: 0, 7: 1, 8: 2, 16: 3} LIG_MAP = {6: ...
b6a3574bfface6a7f463166e927a75a0052f483228144deb0ab53a56f96b9fb9
Python
2,931
113
# Author: Huaxu Yu """ mzpkl.py - pickle utilities for MassCube This module defines the pkl format the raw files in MassCube: 1. Structure of the pickle file format. 2. Convert the raw data to pickle file. """ # imports import pickle def convert_MSData_to_mzpkl(d, output_dir: str = None): """ Convert the...
6214fdc676a3b971f9b7b5c12cff7e30336334a24027dd42b36b2a986605733a
Python
2,940
117
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.8 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2, 6, 0): def swig_import_helper(): from os.path impo...
c2b04b7596c44392dd9039356799affa074bbd1dbf9f36a9ca15b9853f288719
Python
2,941
132
# src/zndraw_joblib/schemas.py from __future__ import annotations from datetime import datetime from typing import TYPE_CHECKING, Any, Generic, TypeVar from uuid import UUID from pydantic import BaseModel, Field from zndraw_joblib.models import TaskStatus if TYPE_CHECKING: from zndraw_joblib.models import Provi...
b1af7a04f75585a3b5976b631053c1d4eba58c621fe40b920617f4840b7bfa4a
Python
2,944
83
#!/usr/bin/env python """Pipeline to import a series of RAW files from mesoSPIM and export to TIFs. Designed to import RAW files output by the mesoSPIM microscope and export to a TIF format that the BigStitcher ImageJ/FIJI plugin can stitch together. Assumes that files are in the format, `<chl>_<tile-coords>.raw` in a...
f6e78534c94e8d533e1a055e1ec2e97f66ab8310ba5ea9cca85b7a035c2e2506
Python
2,944
85
## Restormer: Efficient Transformer for High-Resolution Image Restoration ## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang ## https://arxiv.org/abs/2111.09881 import numpy as np import os import argparse from tqdm import tqdm import torch.nn as nn import torch im...
22bc26d64e596711e43bff550d6e91d76afd0c2105debeabbd22479ad1f71a0a
Python
2,946
82
import torch import numpy as np from utils import run_forward from ablate import ablate def evaluate(model, loader, args, ab_type=None, ab_level=None): model.eval() acc = {} # dictionary to store accuracies # Forward pass to get predictions with torch.no_grad(): for batch_i, batch in enu...
92e9c408d816bda7973463a57923efea467b4d346c368bdc85df961af887fdf2
Python
2,946
91
norm_cfg = dict(type='BN', requires_grad=True) data_preprocessor = dict( type='SegDataPreProcessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_val=0, seg_pad_val=255) model = dict( type='EncoderDecoder', data_preprocessor=data_preprocessor, pre...
4984ece027c3ad7be6e7861dc547bd71ecd8b6ba86c80024caa726b885aa4fa1
Python
2,947
94
#!/usr/bin/env python3 import os import sys import argparse from glob import glob import csbdeep.io parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--baseDir", help="directory in which all your network will live", default='models') parser.add_argument("--n...
5c96fed1aa4ecd1da268d9d9499af537f9d35ebd5b268b935f78a34200ca8d70
Python
2,947
94
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import logging from collections import deque from pathlib import Path from typing import Optional import torch from torch_geometric.data imp...
c20b1f8d67879882f7fa37e2474818c7d76ab76704692e57742fa1ffdac5c745
Python
2,948
80
import matplotlib.pyplot as plt from datasets import load_dataset import numpy as np from transformers import pipeline import torch from sklearn.manifold import MDS import seaborn as sns import scienceplots embeddings = [] colors = [] feature_extractor = pipeline("feature-extraction", framework="pt", model="answerdo...
d4e7bfdd602a2aae5d252ce11e6312086f92054bc442ae957089731bf5775c7d
Python
2,948
85
from rest_framework import serializers from .models import Dataset from user.serializers import UserSerializer class DatasetFullSerializer(serializers.ModelSerializer): """A private serializer. used for users who are permitted to see "sensitive" information. This serializer is also used for POST""" class...
186b8f8c79fa7f739d14879e5e124895a0fb88fc2ade3b36b68db885510b5805
Python
2,949
94
from transformers import TrainingArguments from trl import SFTTrainer, DataCollatorForCompletionOnlyLM from unsloth import FastLanguageModel from datasets import load_dataset import pandas as pd import argparse import torch def full_log_likelihoods(logits, labels): with torch.no_grad(): logits = logits.float().cpu(...
6f3ddd3ae30a0912795d753d90f32a6a2259f93c3dcc7f1573e33e86fd520700
Python
2,949
58
# 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...
1dbfdcee3d565f02bb995f9783d2a5bddce315ecc3948862b9d41c42d44948b8
Python
2,951
82
#!/usr/bin/python # -*- coding: utf-8 -*- # Create a project and stack associated HDF5 file with additional # data such as labels, meshes etc. import os.path as op import h5py from contextlib import closing import numpy as np from django.conf import settings project_id = 3 stack_id = 4 filepath = settings.HDF5_ST...
7c79fa86a09343e531dd7971c3d614e24e82783768b9619c94847575df2f65c5
Python
2,951
81
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import ConvModule, build_norm_layer from mmseg.registry import MODELS from ..utils import Upsample from .decode_head import BaseDecodeHead @MODELS.register_module() class SETRUPHead(BaseDecodeHead): """Naive upsampling head and P...
d8e1a705a8bcc165a19a8b30ce1c5a88ae4d1ec09a2b779c532edc1a0562c490
Python
2,951
87
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp from functools import partial import numpy as np from detail import Detail from mmengine.utils import mkdir_or_exist, track_progress from PIL import Image _mapping = np.sort( np.array([ 0, 2, 259, 260, 415, 324, 9, 258, ...
ad6e6bb97a1c5596cac348768781eaa1b6d6bff9dbf4ab22300bf5bf5030e0e3
Python
2,954
87
## Restormer: Efficient Transformer for High-Resolution Image Restoration ## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang ## https://arxiv.org/abs/2111.09881 import numpy as np import os import argparse from tqdm import tqdm import torch.nn as nn import torch i...
7234655c05764a554c9c5a592cfa069e4469d1a0db5d0b2361b5d4f1eb372b76
Python
2,955
97
import argparse import pathlib import json import glob from load_aokvqa import load_aokvqa def eval_aokvqa(dataset, preds, multiple_choice=False, strict=True): if isinstance(dataset, list): dataset = { dataset[i]['question_id'] : dataset[i] for i in range(len(dataset)) } if multiple_choice is False...
9b0bd4b1eec9a0ced5abef8f19efa1323b06d2951a5bf3ac8723481694ab5f1a
Python
2,955
95
import pytest import tsgm import numpy as np import keras def test_vae(): seq_len = 32 feat_dim = 1 latent_dim = 4 model_type = tsgm.models.architectures.zoo["vae_conv5"] architecture = model_type(seq_len=seq_len, feat_dim=feat_dim, latent_dim=latent_dim) encoder, decoder = architecture.enc...
038be6bbcd63c0105adaf39ac49bd6babc26e0d24df99b790c6e84081895cd66
Python
2,957
86
import socket import time import panel as pn import pytest from playwright.sync_api import expect from guppy.frontend.frontend_utils import scanPortsAndFind from guppy.orchestration.store_labeling import build_store_labeling_template @pytest.fixture(scope="session") def store_labeling_server_url(panel_extension, ui...
f2a868e2711e7aaf3d4de4392b109b10cbb580238866535c56cd693c855477ed
Python
2,958
97
"""Plane geometry for ZnDraw.""" from pydantic import Field from .base import ( BaseGeometry, ColorProp, InteractionSettings, PositionProp, RotationProp, ScaleProp, Size2DProp, ) class Plane(BaseGeometry): """Flat rectangular plane geometry with customizable dimensions. Planes a...
22bac12be351e20cc21929b2a6f0fbb14a1ae0f3948a064c80a42d28828b8578
Python
2,963
78
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmseg.models.decode_heads import FCNHead from mmseg.structures import OHEMPixelSampler def _context_for_ohem(): return FCNHead(in_channels=32, channels=16, num_classes=19) def _context_for_ohem_multiple_loss(): return FCNHead( ...
5bbfca1c3c13b8152d032c42d4b6e1b58aef4332a86b44e154268a99a1bea607
Python
2,963
80
# pytest unit tests for sct_compute_mtr import pytest import logging import numpy import nibabel as nib from spinalcordtoolbox.image import Image from spinalcordtoolbox.scripts import sct_compute_mtr from spinalcordtoolbox.utils.sys import sct_test_path logger = logging.getLogger(__name__) @pytest.mark.sct_testing...
855851680181bc2231da026e6236d1949722e2c9238160374c22e309c91addc0
Python
2,963
92
import pytest from medperf.commands import utils as utils_module PATCH_UTILS = "medperf.commands.utils.{}" class DummyConfig: def __init__(self): self.active_profile = { "certificate_authority_id": 1, "certificate_authority_fingerprint": "abc", } @pytest.fixture def prof...
47ab037f123e031d2d6f3a5e7afa9dfab727adef2cd87f498b492781c6f96dd6
Python
2,965
85
from django.db import migrations forward = """ -- Re-create all triggers associated with history tracking on a particular -- live table (if it has a history table). This function has to be called -- after a live table was changed (e.g. a column was added or remove). CREATE OR REPLACE FUNCTION reload_h...
abd99322e6b99fe9de9375bd0d87f519a7d83fa864ac145eccc69111e837d243
Python
2,968
75
import numpy as np import pandas as pd from sklearn.metrics import r2_score import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # df = pd.read_csv('DMPNN_Random_Split.csv') # print(len(df)) # r2_list = [] # for seed in range(1, 10): # sub_df = df[df[f'split{seed}'] == 'train'] # print(len(su...
de5a8126d54ff64e26cd84963e0fabb2836243ea0201e0e2f5b510826ee6779f
Python
2,968
75
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-strict import torch def smooth_l1_loss( input: torch.Tensor, target: torch.Tensor, beta: float, reduction: str = "none" ) -> torch.Tensor: """ Smooth L1 loss defined in the Fast R-CNN paper as: :: | ...
f833d6197a3f31424b2ed3e01b57de49f886341ffcc026584ce03d229cb77dff
Python
2,968
76
"""Unit tests for `src.babel_utils.norm()`, the CURIE prefix renamer. `norm()` is what turns a source's spelling of another vocabulary's prefix into Babel's (`config.yaml: disease_xref_prefixes`). A prefix it fails to rename is not an error -- the un-renamed CURIE still reaches `glom()`, joins nothing, and fuses every...
6545dd0ba0765c8b71df9226995a839f9f301993fec4f07b6c96eb5682ab2492
Python
2,970
97
"""Main Graupner-Brunel STDP example script""" import numpy import bluepyopt as bpop import stdputil def gbParam(params): """Create the parameter set for Graupner-Brunel model from an *individual*. :param individual: iterable :rtype : dict """ gbparam = dict( theta_d=1.0, theta_...
22a5d68b0f0c02a7f55eed2480267900af3c02bb96057ee55c7212c2014d3df7
Python
2,973
94
import torch from torch import nn class Fire_Block(nn.Module): def __init__(self, in_channels, sequeeze_channels): super().__init__() self.squeeze = nn.Sequential( nn.Conv3d(in_channels, sequeeze_channels, kernel_size=1), nn.ReLU(inplace=True), ) self.expand...
c033984298957318cffe77faf0fa777213b13a289871596523df2eb8e6cd12f3
Python
2,973
77
import torch import torch.nn as nn from nnunet_mednext.network_architecture.custom_modules.custom_networks.UTNet.utnet import UTNet as UTNet_Orig from nnunet_mednext.training.network_training.nnUNet_variants.architectural_variants.nnUNetTrainerV2_noDeepSupervision import \ nnUNetTrainerV2_noDeepSupervision from nnu...
521585de747ed2cb3630bed210c5447833dec741027bd2d9c1d498b9c5bd4fb9
Python
2,974
84
# -*- coding: utf-8 -*- """ Getting Started --------------- Quick introduction to brain maps and eigenmodes =============================================== Patterns on the cortical surface or in the subcortex ("brain maps") more often than not express with smoothness - spatial autocorrelation. Accounting for this in ...
dec4ec73257a04ba9515399e71872d579658e79fb151c2be4d9a26d339d0ff40
Python
2,977
88
import pandas as pd def adding_label(df): """ Adds normalized and binary labels based on the 'PAMPA' column. Parameters: - df (pd.DataFrame): Input DataFrame with a 'PAMPA' column. Returns: - pd.DataFrame: DataFrame with added label columns. """ if 'PAMPA' not in df: raise Va...
25411314e3bb36824c35ffbd7070679229d544cd66e8b755cdbcb7f2de865cb8
Python
2,980
92
import os import zipfile import typing as T import hashlib import logging import tarfile import urllib import urllib.request logger = logging.getLogger('utils') logging.basicConfig() logger.setLevel(logging.DEBUG) def _archive_type(file: str) -> str: _, ext = os.path.splitext(file) if ext in EXTRACTORS.key...
4b5700c17872309065ddcb933039db88b6296f1b4fcfe3a7c377887925f1e969
Python
2,980
75
import torch import math import matplotlib.pyplot as plt import seaborn as sns import scienceplots import matplotlib.gridspec as gridspec import numpy as np hermes = torch.load('../results/custom_metrics_full_log_likelihoods_unsloth-Hermes-3-Llama-3.1-70B-bnb-4bit.pth') nemotron = torch.load('../results/custom_metrics...
6bd9e1ffa3d2b3d13e499c863d997011d012412f977b983a7c9ca5fb56747edb
Python
2,980
87
import unittest from provdbconnector.exceptions.database import InvalidOptionsException, AuthException from provdbconnector import Neo4jAdapter, NEO4J_USER, NEO4J_PASS, NEO4J_HOST, NEO4J_BOLT_PORT from provdbconnector.prov_db import ProvDb from provdbconnector.tests import AdapterTestTemplate from provdbconnector.test...
9f3cc6de19da26ef887b26c4cb739d906448afe401848947eb56daf320b04f4d
Python
2,980
84
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Benchmark(models.Model): BENCHMARK_STATUS = ( ("PENDING", "PENDING"), ("APPROVED", "APPROVED"), ("REJECTED", "REJECTED"), ) BENCHMARK_STATE = ( ("DEVELOPMENT", "DEVEL...
9d1c13ecaa2427631225b0a176d181689b8fd54b6dc020fbf75bf79620957ac9
Python
2,981
88
"""Tests for interaction constraints.""" from typing import Optional, Sequence, Union import numpy as np from .._typing import FeatureNames from ..core import DMatrix from ..training import train from .utils import Device def run_interaction_constraints( # pylint: disable=too-many-locals tree_method: str, ...
670886ae96a03c96c7ce74adc6c5b3bb03777366c9530a6eb0666d6966b28e90
Python
2,982
72
""" 这是基于hugging face社区开源的框架accelerate制定的基础量化推理方案 该框架主要实现了int8、int4量化,以及cpu或者disk offload 实现了用低存储,小设备运行大模型 具体可以见wiki:http://wiki.team.idea.edu.cn/pages/viewpage.action?pageId=31464125 """ import time from transformers import AutoModelForCausalLM, AutoTokenizer import bitsandbytes as bnb from bitsandbytes.nn import Linea...
c241e7d5f6e1dbf104cd36f634870b445793f59d4686ee926112992adb77648e
Python
2,986
66
import torch import torch.nn.functional as F from fengshen.models.transfo_xl_denoise.tokenization_transfo_xl_denoise import TransfoXLDenoiseTokenizer from fengshen.models.transfo_xl_denoise.modeling_transfo_xl_denoise import TransfoXLDenoiseModel from fengshen.utils import top_k_logits, get_masks_and_position_ids def...
fe66585fc18c576883509a8b8567911c594ad4feb6badf83b762052c1f894fc8
Python
2,986
92
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import argparse import copy import logging from typing import List import submitit from ocpmodels.common.flags import flags from ocpmodels....
6378dae90e285fa94e4a90e92c7d233f3ec22e1225aeae6168b3ba91673a7a9a
Python
2,988
90
## Restormer: Efficient Transformer for High-Resolution Image Restoration ## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, and Ming-Hsuan Yang ## https://arxiv.org/abs/2111.09881 import numpy as np import os import cv2 import math def calculate_psnr(img1, img2, border=0): # img1 ...
142f294b8110d536d72a7f0d91934db5e0856b2cf46308c6fc97c05b57766690
Python
2,990
78
#!/usr/bin/env python # Noise2Void - 2D Example for SEM data from n2v.models import N2VConfig, N2V import numpy as np from csbdeep.utils import plot_history from n2v.utils.n2v_utils import manipulate_val_data from n2v.internals.N2V_DataGenerator import N2V_DataGenerator from matplotlib import pyplot as plt import urlli...
f37a50512a0af57920766724c65a9333baa5733d3297257a7b6068f410ce5915
Python
2,993
69
from __future__ import division from sciunit import Score import numpy import math from sciunit.utils import assert_dimensionless from quantities import nA class ZScore_depolblock(Score): """ Z scores. Float indicating standardized difference from reference means for current threshold (Ith), and equilibriu...
ffc3a85b2be2455fe4c5f4c669aed6b2a2d21b876747629c37973aaffe2253bc
Python
2,995
71
import ssm from ssm.util import find_permutation def fit_glmhmm_em(prior_config: dict, n_session, inpts, true_choices, true_latent=[]): """ Fit a Generalized Linear Model-Hidden Markov Model (GLM-HMM) to the given choices and inputs. Args: prior_config (dict): Dictionary containing prior hyperpar...