sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
d4e7a22b302681be03c183cfa929c486673c3eed81cde09194302df2c814e40f
Python
3,417
102
""" To analyze 'elements' inserted into backbones in the style of sarah's paper """ import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from RiboGraphViz import LoopExtruder, StackExtruder from scipy.cluster.hierarchy import ward, fcluster, dendrogram from scipy.spatial.distance...
d97d5ce7c9b69d260ed66f3f75e32d7892cc42d6021a90909efa88ae5bba29e7
Python
3,417
95
# Utility functions for mocking comms and its methods from typing import Dict, List, Callable, Union from unittest.mock import MagicMock from medperf.exceptions import CommunicationRetrievalError def mock_comms_entity_gets( mocker, comms: MagicMock, generate_fn: Callable, comms_calls: Dict[str, str],...
baffed0b1e0f1109d1f0e80d842ee86bfc8e12a865df3ed8095245e7fb7f1ad5
Python
3,418
95
import tsgm import keras import numpy as np try: import tensorflow_probability as tfp from tensorflow_probability import sts DEFAULT_TREND = sts.LocalLinearTrend() DEFAULT_SEASONAL = tfp.sts.Seasonal(num_seasons=12) DEFAULT_MODEL = sts.Sum([DEFAULT_TREND, DEFAULT_SEASONAL]) has_tensorflow = T...
bd8e96421c8982acf18fb7a4bd9a76d150865931a701fc922e8b9b06afaeee9b
Python
3,418
88
""" This scripts runs the regional attribution experiment. Dependencies: - outputs/graphtrip/weights/ Outputs: - outputs/graphtrip/regional_attributions/ Author: Hanna M. Tolle Date: 2025-05-31 License: BSD 3-Clause """ import matplotlib matplotlib.use('Agg') # Set non-interactive backend import sys sys.path.appen...
d22a71aadc17fbdbfa8ec56bd0d6e8a5a3b37fafbd812142b173997a17486c01
Python
3,420
122
import sys import os import torch import numpy as np import csv class Logger(object): def __init__(self, fpath=None, mode='w'): self.console = sys.stdout self.file = None if fpath is not None: self.file = open(fpath, mode) def __del__(self): self.close...
48b91616f70b87cd25a104ddb138146ac57bf456e8f60317821a51a949367c2e
Python
3,421
112
import os import pytest from kgx.transformer import Transformer from tests import RESOURCE_DIR, TARGET_DIR from kgx.config import get_logger from tests.integration import ( check_arango_container, clean_arango_slate, ARANGO_CONTAINER_NAME, DEFAULT_ARANGO_URL, DEFAULT_ARANGO_USERNAME, DEFAULT_A...
17486789f0879964ba88b10caeaea0786ea51057d1907852e90830701979b478
Python
3,422
98
## 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 import torch.nn as nn imp...
74f263f5094dd8e0a72d55415df68ecf44204526a1fa90266aac922fdeee94ba
Python
3,422
101
import nibabel as nib import numpy as np import glob import matplotlib.pyplot as plt from skimage.filters import threshold_otsu import re import os from scipy.ndimage.filters import gaussian_filter1d def get_section_means(file_list:list, correction_factors=None): """Find and ssort section files""" otsu_me...
9582c8895b70cff09dd72ef0452efdfeb04e8b5cb179dd32246be20fe9abe4c0
Python
3,422
98
from django.http import Http404 from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from drf_spectacular.utils import extend_schema from .models import ModelResult from .serializers import ModelResultSerializer, ModelResultDetailSerializer f...
583caff290dc78c5ec5eafe8bc66fc5cea2498a0be29fd54c16a57a90d6d708a
Python
3,424
86
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Union import torch from mmengine import ConfigDict from mmengine.structures import InstanceData from scipy.optimize import linear_sum_assignment from torch.cuda.amp import autocast from mmseg.registry import TASK_UTILS from .base_assigner import...
070513c5d5e93750d7b97e04344b0bde19e89f7ba539a6d562666eba5b06f611
Python
3,425
93
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 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("...
b94b8a26e3018092d8670f47f6e0b4979f0394ec7adbba06d2086fff41e72c38
Python
3,425
110
from __future__ import absolute_import from __future__ import print_function import pytest from keras.models import Model, Sequential from keras.layers import Dense, Input def test_layer_trainability_switch(): # with constructor argument, in Sequential model = Sequential() model.add(Dense(2, trainable=Fa...
ed14c981983c307ba617820b58176adcfef104bbdcf1837702050a93b7284a4d
Python
3,425
105
from typing import Any, Dict from hypothesis import given, note, settings, strategies import xgboost as xgb from xgboost import testing as tm from xgboost.testing.params import ( exact_parameter_strategy, hist_cache_strategy, hist_multi_parameter_strategy, hist_parameter_strategy, ) from xgboost.testi...
03e4916049b0064eaad01fd799c1cde09bfeb1c5bea64b90a30a269cc6e0ca83
Python
3,426
111
import os import ray from ray import tune from ray.tune import CLIReporter from ray.tune.schedulers import ASHAScheduler from ocpmodels.common.flags import flags from ocpmodels.common.registry import registry from ocpmodels.common.utils import build_config, setup_imports # this function is general and should work f...
3c7e2abdd152938c4fd64ee3349f6b80566ae240fea02f3faf10ae1c66f6f79e
Python
3,426
87
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import shap import pickle import seaborn as sns from sklearn.metrics import roc_curve, precision_recall_curve, auc from sklearn.metrics import roc_auc_score, average_precision_score from sklearn.metrics import precision_recall_curve, matth...
5ed575aec352471a5e61209cd12d615f7597fe066b5307680fdcc06e042ed037
Python
3,427
81
import numpy as np import matplotlib.pyplot as plt import os from grid_cell.ploter import scatter_torus_ploter from grid_cell.manifold_fitter import GP_Fitter, Avg_Fitter, label_mesh from grid_cell.gkr import GKR_Fitter from sklearn.decomposition import PCA from umap import UMAP from global_setting import * ##########...
fb74ea0702755352cf2f10573b67ef2a85ec7b5ca2d636229895d4a2011f102c
Python
3,428
103
from __future__ import annotations import random import numpy as np import pytest import torch from pymatgen.core import Lattice, Structure from chgnet.data.dataset import StructureData, get_train_val_test_loader from chgnet.graph import CrystalGraph lattice = Lattice.cubic(4) species = ["Na", "Cl"] coords = [[0, 0...
7f3adfe5abca88172c89b1835e2141ea72c95df6eec606a61bde61b80fe830b4
Python
3,429
114
import numpy as np import math import sys from tqdm import tqdm SEED = 1717 np.random.seed(SEED) EPSILON = sys.float_info.epsilon def transform(y, num_terms=6, bandwidth_term=1/2): B = bandwidth_term exp = np.exp(-B * y**2) terms = [] for i in range(num_terms): terms.append(exp * (y)**i / m...
a982bd0a0c1b6d644d2fba18ec6f863301342352baae6358f0d405ad85f123b1
Python
3,430
120
# pytest unit tests for sct_qc import pytest import logging import json import os from spinalcordtoolbox.scripts import sct_qc, sct_deepseg from spinalcordtoolbox.utils.sys import sct_test_path logger = logging.getLogger(__name__) @pytest.mark.sct_testing def test_sct_qc_no_checks(): """Run the CLI script with...
fa917de5eff4e85bdfc9fa5a18cf5fe28d5c7b6bcce1a5e5e98dad8fde418aa3
Python
3,430
116
from django.db import migrations, models from catmaid.control.volume import update_volume_meta_information forward = """ SELECT disable_history_tracking_for_table('catmaid_volume'::regclass, get_history_table_name('catmaid_volume'::regclass)); SELECT drop_history_view_for_table('catmaid_volume'::r...
c3e909930e0249f9b7fb68ee6613258987d37d0cc67e6664f38f9947cd634da0
Python
3,431
56
from models import RescorlaWagnerModel, DualSystems from trainers import Trainer import pandas as pd import torch from datasets import load_dataset import os experiments = [ #{'name': 'horizon1', 'agent': 'centaur', 'path': 'wilson2014humans/simulation0.csv', 'model': RescorlaWagnerModel(num_options=2)}, #{'na...
7ff1a5f1b6a87e422268de4f25ddbac5347fdc00cb5e923e7f169d95fb5adbc2
Python
3,433
120
import typer from typing import Optional from pathlib import Path import medperf.config as config from medperf.decorators import clean_except from medperf.commands.view import EntityView from medperf.entities.report import TestReport from medperf.commands.list import EntityList from medperf.commands.compatibility_test...
9fbc4f36e301e4090106064905f71cbacb5d6ce1d41120a39ece4efe26d18aca
Python
3,435
92
############################################################################## # Obsolete import # Need to check if this script is still useful for the project ############################################################################## import time import numpy as np import pytraj as pt from Nearl import utils de...
ad8767e751d984d254eb2dc8e09b67776f647f462d50c3d285a1cf1dc66f3579
Python
3,436
95
import torch from src.metrics_and_losses import (per_prop_mse, per_prop_stable_mse, per_prop_r2) import os import numpy as np class Checkpointing: def __init__(self, property_names, model, artefact_dir, model_type, smoothing_...
b55bb4223caf8c99bb427a4f98d6a580d9c40b3426d8e3517f8fb09e0d9c17b3
Python
3,436
100
# Copyright (c) OpenMMLab. All rights reserved. import logging import os from argparse import ArgumentParser import requests import yaml as yml from mmseg.utils import get_root_logger def check_url(url): """Check url response status. Args: url (str): url needed to check. Returns: int, ...
e124da0faa4839521ca6f4e39c9cf6abfd3b07383606d8d115b9f4d71e854148
Python
3,437
90
#!/usr/bin/env python3 # ############################################################################# # Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> # All rights reserved. # # This source code is licensed under both the BSD-style license (found in the # LICENSE file in the root directory of this source t...
6b1f99e42174bdb068b5ca732058f9801fcc855fb997eb323debfce223d5a192
Python
3,438
95
# FCN model # when tuning start with learning rate->mini_batch_size -> # momentum-> #hidden_units -> # learning_rate_decay -> #layers import tensorflow.keras as keras import tensorflow as tf import numpy as np import time from utils.utils import save_logs from utils.utils import calculate_metrics class Classifier_CNN...
a48b60d61d904a34b0fe26074f31efd14699b22247b17b54d990aac03426d240
Python
3,441
81
from pyxtal import pyxtal from p_tqdm import p_map from sklearn.model_selection import train_test_split from pymatgen.core import Structure from pymatgen.core.lattice import Lattice def structure_to_str(structure): # 转换pymatgen结构为pyxtal结构 px_structure = pyxtal() px_structure._from_pymatgen(structure) #...
273f9a567f1d44878c1e5df4c2320c7d6f87083bf3f03e2c7fd7a8337eb4dad5
Python
3,443
110
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler import mne # MNE for EEG signal processing # --------------- For raw EEG data (e.g., .edf, .set, .bdf files) ---------------- # def load_eeg_raw(file_path, file_format='edf'): """ Loads raw EEG file using MNE. Suppor...
7244bda755d1a93bfb3b48ba3f0cbc07c3194954e23cc540bb2ba486c8924531
Python
3,447
122
import re import numpy as np from pyalfe.data_structure import Modality, Orientation def detect_modality(series_desc, seq, contrast_agent, te): """This function applies a set of rules to detect the modality Parameters ---------- series_desc: str Dicom Series Discription Attribute. seq: ...
a026b7ba37f1e08c58801de1fa8632d44f7be8eb5162c3021f04792672f3d9dc
Python
3,449
112
"""Display-time rendering for whole-session time-binned metrics. The binned values are drawn as bars spanning the bins they summarize, stacked under the trace they were reduced from. Both panels share the ``time (s)`` dimension, so bokeh links their axes and zooming the bars zooms the trace with them -- which is what ...
39e80232062b7c6742e126d11b6419e36c43b0d63c43e771ae810d7f755db566
Python
3,452
89
DOCS = """ train the model on the a dataset (gabor or mnist) or show the model learns to represent the data and predict the input Current figures: figure 2. """ from dataset import Digit from model import ShallowMLP from experiment.utils import set_seed, init_model, Logger, Trainer, Checkpointer import torch import to...
1b35d83d47417e000935c992e7f4193c277254f8d4592c36452370a46500bdb3
Python
3,455
98
""" Collection of examples for using xgboost.spark estimator interface ================================================================== @author: Weichen Xu """ import sklearn.datasets from pyspark.ml.evaluation import MulticlassClassificationEvaluator, RegressionEvaluator from pyspark.ml.linalg import Vectors from ...
45877a488a788cf554ee3c8d1268cb47b958db2051cd5354df552ddfb30a57b0
Python
3,455
113
import math import random import torch import torch.nn.functional as F from ._base import register_transform def _extend_mask(mask, chain_nb): """ Args: mask, chain_nb: (L, ). """ # Shift right mask_sr = torch.logical_and( F.pad(mask[:-1], pad=(1,0), value=0), (F.pad(chain...
bb4e9cdd343860176a617d9c8426ad71c3684f4975a5069c48591fd2fe41c362
Python
3,455
102
import igraph as ig from igraph import Graph import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt from utils import generate_labels import os # vertices = [[5,8],[6,7],[2,9],[2,5],[0,7],[2,9]] # number_of_graph_vertices = 10 # number_of_vertices_labels = 6 def generate_del...
db7d05157951e7c21db68b557cb554f669f273cb09e74d79f75047eb9bdac09c
Python
3,457
121
import numpy as np class SimpleTransformer: """ SimpleTransformer is a simple class for preprocessing and deprocessing images for caffe. """ def __init__(self, mean=[128, 128, 128]): self.mean = np.array(mean, dtype=np.float32) self.scale = 1.0 def set_mean(self, mean): ...
4019b8f9d2cf9807e62c7fec52e911db80b9eb2166d2e176d2a9138553b210ca
Python
3,459
72
import pandas as pd from experiment import * import h5py import numpy as np if __name__ == "__main__": min_angle = params["min_angle"] max_angle = params["max_angle"] conf = params["confidence_threshold"] for species, tracking_directory in expt.directory["tracking", "eyes"].items(): if specie...
d4c7e324a18fa6c736fdf31c777c1da7564c8cf42f4ec467fb361c0eb3496a21
Python
3,459
112
""" This file is part of the Firmware project to interface with small Async or Neuromorphic chips Copyright (C) 2022 Willian Soares Girao - University of Groningen Copyright (C) 2023 Ole Richter - University of Groningen This program is free software: you can redistribute it and/or modify it under ...
339573d86c46bb8d5effaf0704414163f7c0d4488f15fe3a0f64e14018bb82c5
Python
3,460
98
# -*- coding: utf-8 -*- import json from .common import CatmaidApiTestCase class LogsApiTests(CatmaidApiTestCase): log_rows = [ [ 'test2', 'create_neuron', '2012-07-22T16:50:57.758000+00:00', 5290...
145c9220047a1cd0d2d23add2948b06f4a548a767c8ce4fc35716a4f5ac3084c
Python
3,461
80
import os.path import argparse from typing import Any, Dict, List def model_trainer( model: Any, save_dir: str, train_data: Any, valid_data: Any, metrics: List[Any], score_name: str, transformers: List[Any], text: str, args: argparse.Namespace, n_epoch: int = None, patience...
6b5b87f968b45d0274456b2747cd018a519db6137cd951dc03cc21babde78fdc
Python
3,461
99
import logging from pathlib import Path import numpy as np import sqlmodel as sqlm import torch from torch.utils.data import DataLoader, TensorDataset, random_split from torch.utils.tensorboard.writer import SummaryWriter from tqdm import tqdm from typer import Typer from DiastereomericResolutions.main.training impor...
1dfb49cc40c8117d59ea4994bfa583b87384671ab6e95d7c1c1a3f8d3690ad2a
Python
3,463
110
_base_ = [ '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] crop_size = (512, 512) 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, size=cr...
dfd9b5076ba64e6af0d3f2da121249e317ed63521966f442b1181ef2d79a54d4
Python
3,463
84
"""Network tests for the PANTHER family download. The pipeline uses FTP (ftp.pantherdb.org), but FTP is often blocked by HPC firewalls. PANTHER also exposes the same files over HTTP; these tests check both endpoints. Run with: uv run pytest --network tests/datahandlers/test_pantherfamily.py """ import ftplib import ...
2874a5e89484ff262d60e459949da70a5ecaf5585ee81dc909599ceeffc4f041
Python
3,464
106
"""Tests for various command line options.""" import pytest from cwltool.utils import versionstring from .util import get_data, get_main_output, needs_docker def test_version() -> None: """Test --version.""" return_code, stdout, stderr = get_main_output(["--version"]) assert return_code == 0 assert...
dc04c073c600a0f624eaf41e9a0a3d6c96805d3894b7e43c5f192a3a959c81a7
Python
3,464
108
# -*- coding: utf-8 -*- """ Created on Tue Sep 24 16:16:30 2024 @author: AC """ import pandas as pd from sklearn.model_selection import train_test_split from xgboost import XGBClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_auc_score, roc...
e226b534b9758854ae5555ad9005f074e7309d14a0ba6f7216aa83dc88e45767
Python
3,466
111
_base_ = [ '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] crop_size = (512, 512) 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, size=cr...
1b2eba2d0be409fd2c083a7b13164ebf11e2e72cb6d563f9be3cdf4bb157ef48
Python
3,467
109
"""Regression tests for NaN-containing pure-Python multitaper windows.""" import os import sys import unittest import numpy as np from scipy.signal.windows import dpss # Run directly from the repository without installing a package. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from multitaper_spec...
8c1a51252fdfcf0b7fc524ef83acf41c0ab27c92d92040bf92a2eeeeefa2e320
Python
3,467
94
import pyoxigraph from src.babel_utils import make_local_name, pull_via_urllib from src.metadata.provenance import write_concord_metadata from src.prefixes import EC, RHEA def pull_rhea(): pull_via_urllib("https://ftp.expasy.org/databases/rhea/rdf/", "rhea.rdf.gz", subpath="RHEA", decompress=True) class Rhea: ...
c2204dc3f3e3816eb5d2d9fa29b75e29378c91f96644a0db14176f39fc52b731
Python
3,467
97
# -*- coding: utf-8 -*- import json from catmaid.control.annotation import _annotate_entities from catmaid.models import ClassInstance, Log from .common import CatmaidApiTestCase class NeuronsApiTests(CatmaidApiTestCase): def test_rename_neuron(self): self.fake_authentication() neuron_id = 233 ...
346633b5b140d0722465e4713c437d450f798bbb0a72504d9026ebb7a1cee850
Python
3,468
113
""" paq2py Read PAQ file (from PackIO) into python Lloyd Russell 2015 """ import numpy as np import seaborn as sns def paq_read(file_path=None, plot=False): """ Read PAQ file (from PackIO) into python Lloyd Russell 2015 Parameters ========== file_path : str, optional full path to file ...
9e68ab19ff4174946122b3b641f56b0dfefb093232fdbcf4a8c5ab3f54f328ba
Python
3,468
108
#!/usr/bin/env python3 import numpy as np import pickle class History: def __init__(self, csvpath=None, warmup=0): ''' warmup: `int` Write only if `self.count > warmup`. Useful if unknown columns appear after the first row. ''' self.data = dict() # Data c...
ac00ae6869ebd3f72a7ac611d68bbadee5a294c1d070a61971b3aaa96c0c781c
Python
3,468
80
# def evaluatePrediction(region, sam, sigAlign, label, genome, model, weight, kmerWindow=80, signalWindow=400, # modBase = ['AT', 'TA']): # alignment = getAlignedReads(sam = sam, region = region, genome=genome, print_name=False) # refSeq = alignment['ref'] # all_scores, modCount...
44f633e10cf224a7fa37a1a131172e800d3a6849436c5f9f01070b5d6462bac9
Python
3,469
88
from transformers import TrainingArguments, AutoModelForCausalLM, AutoTokenizer from trl import SFTTrainer, DataCollatorForCompletionOnlyLM from datasets import load_dataset import pandas as pd import argparse import torch if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-...
ab8b9d6cbeb8e38478d0d0dab9271a24092c3e6646755ce30e9c18bef47ca600
Python
3,469
80
# -*- coding: utf-8 -*- import json from django.http import HttpRequest, JsonResponse from catmaid.models import UserRole, ChangeRequest from catmaid.control.authentication import requires_user_role @requires_user_role(UserRole.Browse) def list_notifications(request:HttpRequest, project_id = None) -> JsonResponse:...
e43b070a141c9e9ecf411592accd3d79c7fb83b1a95f7355d5150faaef863f18
Python
3,469
81
import logging from collections import OrderedDict from collections.abc import Sequence import numpy as np from ..utils.validation import validate_peak_windows logger = logging.getLogger(__name__) def compute_psth_peak_and_area( psth_mean: np.ndarray, timestamps: np.ndarray, sampling_rate: float, p...
9d7f12f34954a1639623ecf847c0317ad57b6cec0661652644da144e6387b828
Python
3,470
98
# 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...
3f198f6d0b74634d8e3e3012b5d9c86a9eaf0b683fde16d84b88693ab00afa58
Python
3,473
98
import glob import os import numpy as np from PIL import Image root_path = 'data/' img_suffix = '.tif' seg_map_suffix = '.png' save_img_suffix = '.png' save_seg_map_suffix = '.png' src_img_train_dir = os.path.join(root_path, 'AV_groundTruth/training/images/') src_img_test_dir = os.path.join(root_path, 'AV_groundTruth...
ddcbbf989dd8b82433889d615557b757a6f24fcb51db33d7e40972fddb3990e4
Python
3,473
90
# pytest unit tests for sct_label_utils import pytest import logging import numpy as np from spinalcordtoolbox.image import Image from spinalcordtoolbox.types import Coordinate from spinalcordtoolbox.utils.sys import sct_test_path from spinalcordtoolbox.scripts import sct_label_utils, sct_create_mask logger = loggi...
0f71feb6983f305c012fcb4bd18da745af6d488f5716ee185eb12f697b7c3e6d
Python
3,474
102
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule from mmseg.registry import MODELS from ..utils import resize from .aspp_head import ASPPHead, ASPPModule class DepthwiseSeparableASPPModule(ASPPModule): """Atrous Spati...
c88629242f697cb21c7231fde852c3352175596f7eb1d8e8ea4f4a58ebf35907
Python
3,478
94
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Optional, Union import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmseg.registry import MODELS @MODELS.register_module() class OhemCrossEntropy(nn.Module): """OhemCrossEntropy loss. This func is modif...
17fe5ce2275d2098bce2a062818deb3bd55fd42f763827c229fb6672ac863c6c
Python
3,481
115
import csv import numpy as np def createManualSpikeSortingLog( sessions, filename, minimumPresenceRatio=0.9, maximumRefractoryPeriodViolationRate=0.5, maximumAmplitudeCutoff=0.1, maximumProbabilityValue=0.05, returnEntries=False, targetUnitQuality='high', ): """ """ all...
2ff4202653e36cba7f25f74bb70dc5edc937306e747549abc80986a7e55c4707
Python
3,482
87
""" Concatenates multiple 3D atlases into a single 4D volume. Author: Hanna Tolle Date: 21.12.2024 License: BSD-3-Clause """ import os import glob import nibabel as nib import numpy as np import argparse def concat_atlases(atlas_dir: str, output_dir: str, receptor_names: list): """ Concatenates multiple 3D at...
411033a479b5840e2c05d0bbfc0cde020c1f74c9d330dbace801abd1536b0f89
Python
3,482
112
_base_ = [ '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] crop_size = (512, 512) 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, size=cr...
14a8ddbfd4e39d596e3b3e9357299d704fe00a49ac61da4e917d051f707a87bf
Python
3,483
66
# 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...
cc8950d1349400369ea51c3b3573ac48718c864047873ace825bb943064ab36e
Python
3,483
111
""" Extract static/dynamic featuresfor single residue classification """ import os, sys, argparse import numpy as np import nearl import nearl.data from collections import OrderedDict from nearl.io.traj import MisatoTraj nearl.update_config( verbose = False, debug = False, # verbose = True, # debug = T...
20336b75b9105b7c8159c03b2e70be3a5e5d1eaea22c349f9a2396312997dc3f
Python
3,488
56
# 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...
f60b9a72889181ca7842f8fc795d76622ecd238a1d8238b9bb85f2df60bdd39b
Python
3,488
92
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 from datasets import load_dataset import matplotlib as mpl test_data = load_...
1b1ed70b5a70711f936ee0b21beff3150534610225be2676394a5ba4a7fce30e
Python
3,491
120
""" ================================================ Comparison of Picard-O and FastICA on faces data ================================================ This example compares FastICA and Picard-O: Pierre Ablin, Jean-François Cardoso, Alexandre Gramfort "Faster ICA under orthogonal constraint" ICASSP, 2018 https://arxiv...
74ad7805f948ae98c6c1b733203964289675309617722284e20570f1433270c8
Python
3,491
125
"""MLCube handler file""" import os import yaml import typer import shutil from preprocess import Preprocessor from check import Checker from statistics import Stats app = typer.Typer() class PreprocessTask(object): """ Task for preprocessing the data Arguments: - data_path: data location. """ ...
86c40bf870c87fa08e89add3c16f6d9d810ccbc006f48cd70293de2b5215bb18
Python
3,491
117
from __future__ import annotations import base64 import pathlib from typing import Annotated import typer from zndraw.schemas import ( OffsetPage, ScreenshotListItem, ScreenshotResponse, ) from .connection import ( PasswordOpt, RoomOpt, TokenOpt, UrlOpt, UserOpt, cli_error_handle...
78cfb5f47b13d4fdb7b6306d434966d4a2b004cc09630a8b6d0d979fde4c44a4
Python
3,492
117
from __future__ import annotations from typing import Optional from heudiconv.utils import SeqInfo def create_key( template: Optional[str], outtype: tuple[str, ...] = ("nii.gz",), annotation_classes: None = None, ) -> tuple[str, tuple[str, ...], None]: if template is None or not template: ra...
1c81e15be76061938a293ddc319f615da0f91ba97ea5ba40c4cf353fe6dc6a67
Python
3,494
111
_base_ = [ '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] crop_size = (512, 512) 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, size=cr...
46ec10adfef9fe08db14994914751a5d2364eff41704fac960164da8c2add3fc
Python
3,494
110
import json import numpy as np from copy import deepcopy def forceFortranOrder(funcname): old_func = getattr(np, funcname) def new_func(*args, **kwargs): kwargs['order'] = 'F' return old_func(*args, **kwargs) setattr(np, funcname, new_func) class Specification: def __init__(self, par...
b671d594005f12acc0dbab5e42a665544caa90f323f11811a7984d5f694b3da9
Python
3,494
105
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 11:04:51 2024 @author: AC """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, precision_...
35eb7546cb89b9ea27d7822eb6ef81fc46082e69f59b846e8d8cd91253328094
Python
3,497
102
import numpy as np import torch import torch.nn as nn from scipy import linalg from tqdm import tqdm from basicsr.models.archs.inception import InceptionV3 def load_patched_inception_v3(device='cuda', resize_input=True, normalize_input=False): # we may ...
6003a98d551edba33a290abb104b0aba3923952b264b23b3ae0e32503c035b5e
Python
3,498
103
# -*- coding: utf-8 -*- # tests/test_doctests.py ################################################################################ # EncoderMap: A python library for dimensionality reduction. # # Copyright 2019-2024 University of Konstanz and the Authors # # Authors: # Kevin Sawade # # Encodermap is free software: you c...
37d0bf7c73181a988cf7331fc10d485dd4f0d6b33f914dae4227d158b5e60e42
Python
3,499
141
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from Bio import Phylo import pandas as pd import matplotlib.pyplot as plt from itertools import combinations from copy import deepcopy def read_tree(file): return Phylo.read(file, "newick") def write_tree(tree, file): Phylo.write(tree, file, 'newick') def ...
a0a8a5d81ebed42f89ef20eda344105dd20a5b38b73403183835454e021f5ed5
Python
3,499
73
# 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...
abe7d61b45852838593795ab8681b693caa9d4ae08276a1cbfb38b77efdd51c9
Python
3,500
108
"""bluepyopt.optimisations tests""" import bluepyopt.optimisations import bluepyopt.ephys.examples.simplecell import pytest import numpy import deap.tools @pytest.mark.unit def test_DEAPOptimisation_constructor(): "deapext.optimisation: Testing constructor DEAPOptimisation" simplecell = bluepyopt.ephys.e...
2e5e6714ac1358de9fecc5fb8c5aea2b56d915ebb71793c2de295918fdab17e2
Python
3,502
123
""" 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 published by the Free Software Foundation. ...
ffdf9817a74c49ec8af653d1170d4aaf85b5fd55e19ec04298b672eba42326d3
Python
3,504
71
import pandas as pd from sklearn.preprocessing import QuantileTransformer from dataAnalysis.Constants import * import torch def count_cbc_cases(data): comp_data = data.query("~(WBC.isnull() & HGB.isnull() & MCV.isnull() & PLT.isnull() & RBC.isnull())", engine='python') unique_data = ...
e01114ecfbfd848ff111c4be0b9b7f0ac459f4b25182e23bf9e64e69e0877999
Python
3,505
83
""" This script is used to distribute the motion curves among different sets and map between curves and subjects within the val and test splits. - run this script (from iml-dl/.) with: python -u ./projects/motion-simulation/preprocessing/data_split_motion_curves.py --input_dir folder_with_motion_data --outp...
8f80c645968a91bc23e122ec7f2957cff4738d98f3fa92e19960caedb3a42434
Python
3,506
106
# Input/Output with the Python Subprocess module # Author: David Young, 2020 """File management using underlying system commands accessed through the Python :mod:`subprocess` module. """ import os import subprocess from magmap.io import libmag def compress_file(path_in, path_out=None): """Compress a file or fil...
bb071460ce0dcc81bf3952d9cfc2011f3743cd3192bb735370f3c32f51060c72
Python
3,507
84
# -*- coding: utf-8 -*- """ Created on Wed Sep 24 12:39:51 2024 @author: AC """ import pandas as pd from pathlib import Path # Set pandas display options pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) # Load the CSV file into a DataFrame data_dir = Path("D:/ownClou...
c0f0c29be9d0a88bbb5641e71363b1d9314819d348204d8ddcdb793224508b26
Python
3,507
164
import serial import pathlib as pl HANDSHAKE = bytes('h', 'utf-8') ON = bytes('p', 'utf-8') OFF = bytes('z', 'utf-8') RESET = bytes('r', 'utf-8') commands = { 'signal' : bytes('s', 'utf-8'), 'connect': bytes('c', 'utf-8'), 'release': bytes('r', 'utf-8') } class Microcontroller(): """...
28e4afeaa3984c3d9a68444315d8087d8e26ab1041978a3a1d8b52fd565004e9
Python
3,508
111
import numpy as np import matplotlib.pyplot as plt import pingouin as pg import hickle as hkl import os from scipy import stats from sklearn.linear_model import LogisticRegression from grid_cell.lole import LOLE, LOCF from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from grid_cell.grid_...
991e7907b4101ecd8511b33f1fc11a4904181e679ba898959ea879b4e15e414f
Python
3,508
100
import argparse import glob import os.path as osp from gather_models import get_final_results from mmengine import Config from mmengine.fileio import dump def parse_args(): parser = argparse.ArgumentParser( description='Gather benchmarked models train results') parser.add_argument('config', help='tes...
fe8a7238b973d87d7f83b35c2d2d657a2ff4b4fc402de6eb81950ae563ba5090
Python
3,508
95
import os from glob import glob import shutil import argparse import json from typing import Union from bdpy.dataset.utils import download_file as bdpy_download_file FIGSHARE_URL_PREFIX = 'https://figshare.com/ndownloader/files/' FIGSHARE_FALLBACK_PREFIX = 'https://ndownloader.figshare.com/files/' def main(cfg): ...
f42cdae59dd48a17b4a7bf972dde43189c8e726d64da4598f4d2b5c0407d89bb
Python
3,509
119
import copy import warnings import numpy as np import torch import torch.nn as nn from torch_geometric.data import Batch, Data from torch_geometric.loader import DataLoader from .warmup import GradualWarmupScheduler # customize exp lr scheduler with min lr class ExponentialLR_with_minLr(torch.optim.lr_scheduler.Exp...
4b1a7cc15307d7ac3890f746404bbc9664f839ed72650692f7f382258ad5dd43
Python
3,510
101
from medperf import config from medperf.account_management.account_management import get_medperf_user_data from medperf.entities.ca import CA from medperf.entities.training_exp import TrainingExp from medperf.entities.cube import Cube from medperf.utils import ( get_pki_assets_path, generate_tmp_path, dict_...
63075b150a01ae4b9d9e61d1dc5f51cdf2bf052b4fecf214b2503cf67f955bf7
Python
3,510
139
import sys import os import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn import svm def main(): # total arguments n = len(sys.argv) print("Total arguments passed:", n) print("Run folder: " + str(os.getcwd())) cwd = os.getcwd() # Arguments ...
232fee5127ee1d8691be14f11618eff7de459ae8564d09b5d3a866f20bd6523d
Python
3,511
83
# pytest unit tests for spinalcordtoolbox.utils.shell import os import sys import pytest from stat import S_IEXEC from spinalcordtoolbox.utils import shell def test_parse_num_list_inv(): assert shell.parse_num_list_inv([1, 2, 3, 5, 6, 9]) == '1:3;5:6;9' assert shell.parse_num_list_inv([3, 2, 1, 5]) == '1:3;...
9561342d266af72375aadceb4bd117ab2bf96c5240e43021c572781e3170f249
Python
3,511
125
import uuid from typing import Optional, Tuple from fastapi import Request from starlette.middleware.wsgi import WSGIMiddleware from medperf.dashboard.preparation_dashboard import build_app from medperf.entities.cube import Cube from medperf.utils import sanitize_path MIN_SEARCH_LENGTH = 2 SEARCH_DEBOUNCE_MS = 300 ...
4a874e5482a5b10b87fa333ea204e005bcc1e865aae59edf0959f04de0ac2252
Python
3,512
119
import numpy as np import cupy as cp from scipy.stats import norm def calc_wtx_corr(wtx1, wtx2, l): corr_max = -cp.inf shift_max = 0 for i in range(l*2-1): shift = i-(l-1) corr = cp.corrcoef(wtx1[l:-l], wtx2[l+shift:-l+shift])[0, 1] if corr > corr_max: corr_max = corr ...
f351bc23b7da8cb01373c07bdd4f5786ce51c30f1656e957f1f6051920d3bfa4
Python
3,514
105
# Generated by Django 2.1.5 on 2019-02-14 03:02 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_fo...
827fea756e60e38ef43f4f860604838de683426bb9a13bdecaa45aeab92bb405
Python
3,516
85
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from .base_pixel_sampler import BasePixelSampler from .builder import PIXEL_SAMPLERS @PIXEL_SAMPLERS.register_module() class OHEMPixelSampler(BasePixelSampler): """Online Hard Example Mining Sampler...
21e111fbe83d8df42dc75b190132e2b7c0b75efc194314ffdd2cb8f9cc6209dd
Python
3,517
82
"""Mixin of contract tests for :mod:`guppy.utils.dandi_search`. The contract is what has to hold of any archive the search reads, so it is bound twice: once to the in-memory stand-in in ``test_dandi_search.py`` and once to the real DANDI Archive in ``test_dandi_search_live.py``. Everything here is about the shape of w...
afaa4109cb926485af12e84101d86e635cb0d4b3f355481d7959ee612e6a32c6
Python
3,519
94
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # -*- coding: utf-8 -*- # pyre-strict import itertools import unittest from typing import List, Tuple import numpy as np import torch from fvcore.nn import update_bn_stats from torch import nn class TestPreciseBN(unittest.TestCase): def se...
3dfaad3957a6b5761ef8fabcdd24d8be8252c3fbc8d5f98ca08a286adca4044e
Python
3,520
112
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
6843b8423790b5182ae887aa5093d8916f00de3f163dcca1a58ee863b152cade
Python
3,520
129
import random import unittest from soccertrack.metrics import ap_score, iou_score, map_score class TestMetrics(unittest.TestCase): def test_iou_score_1(self): bbox_det = [10, 10, 20, 20] bbox_gt = [10, 15, 20, 20] iou = iou_score(bbox_det, bbox_gt) ans = 0.5 self.assertEq...