sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
b6f3fbc14df850df35cfb26cc64f9ee495629f01ddbf2f1657f15d1f6f108c0f | Python | 7,074 | 150 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 09:50:15 2015
@author: takeiyuichi
"""
# -*- coding: utf-8 -*-
#mne-pythonでの解析環境を構築するためのスクリプト
#次のprocessはkg_preprocessing_141009.py
#必要なのは、MEGのraw data, MRIスライスデータもしくはfreesurfer済みデータ、
#covarianceをルームデータから計算する場合はroomデータ、被験者の一覧を記述したsubject_setting.txtファイル
#subject_set... |
fad73f970a2943d7a5618fc7d099ac6e037b3dda04e26a4e3f54bcc851f0afb4 | Python | 7,075 | 172 | """
script to apply the model
"""
import os
import shutil
import sys
import itk
import numpy as np
import torch
import json
from networks.unet_three_d import UNet3D
from networks.unet_two_and_a_half_d import UNet25D
from utilities import printdt, pad_to_patch_size, denoise_volume_gaussian, denoise_slice_gaussian
from t... |
617f4cbb16d2b102694e739b1188e25832d6b0008b7e93a4922e5e9af8ef2f6e | Python | 7,076 | 227 | #!/usr/bin/env python
"""
MetaWIBELE: pfam2go module
Summary GO annotation info based on Pfam2GO file
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 So... |
db02083425ade9dd4b5daf27c3ff582c0574dc88e61279167c4cd2d8fffd10df | Python | 7,076 | 174 | import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
from unsloth import FastLanguageModel
import transformers
from datasets import load_dataset
import os
import argparse
def randomized_choice_options(num_choices):
choice_options = list(map(chr, range(65, 91)))
return np.random.choice(choice... |
0d68744d29e25996bf3bcdff1a6921ab23817865d90273a64c58af69802af1ed | Python | 7,079 | 185 | import os
import numpy as np
import random
import pandas as pd
from PIL import Image
from tqdm import tqdm
from dataset_utils import crop_and_resize, combine_and_mask
################ Paths and other configs - Set these #################################
cub_dir = '/u/scr/nlp/CUB_200_2011'
places_dir = '/u/sc... |
dd17e6009478fb06f1ae7393692cb4d0b109968e32926313122878f8c7be1a36 | Python | 7,082 | 198 | """Base class for recording extractors."""
import logging
import multiprocessing as mp
from abc import ABC, abstractmethod
from multiprocessing.sharedctypes import Synchronized
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
# Per-worker handle on the shared "samples done" count... |
ed1dbd04463788b3effc0198504e15d08a6787714daa05ff63b519a9eccd940d | Python | 7,082 | 213 | #!/usr/bin/env python2.7
import os, sys
import sys
import datetime
import subprocess as sp
import multiprocessing as mp
import shlex
import datetime
import re
from collections import defaultdict
from contextlib import contextmanager
argmax = (lambda d : max(d, key=(lambda x : d[x])))
argmin = (lambda d : min(d, k... |
564bbe00851468758a149406c4d8f3f581b8b9fcf55ce39f88442434a3432626 | Python | 7,085 | 250 | # pytest unit tests for spinalcordtoolbox.labels
import logging
import numpy as np
import pytest
import spinalcordtoolbox.labels as sct_labels
from spinalcordtoolbox.image import Image, zeros_like
from spinalcordtoolbox.utils.sys import sct_test_path
from spinalcordtoolbox.types import Coordinate
from .test_image im... |
5f25855d5bcbe59972da5f5649dc87d6726afb63c632f6ab24f25222eeaaeb74 | Python | 7,088 | 214 | import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, random_split
from torchvision.datasets import EMNIST
import os
from datetime import datetime
import time
from dfa_lib_python.dataflow import Dataflow
... |
83888867437f5a4a6e383b495b0becf217278a8798518591e7a617b1d1307487 | Python | 7,089 | 188 | from jaxkineticmodel.load_sbml.sbml_load_utils import get_global_parameters
from jaxkineticmodel.load_sbml.sbml_model import SBMLModel
import os
import jax
import numpy as np
import pandas as pd
from scipy.stats import qmc
## contains parameter initializations within bounds and some helpers for generating synthetic ... |
0718ca380e354cb909789d9085974b71b12ad34e00d0f5368e35fd3decb0f7b4 | Python | 7,090 | 180 | #!/usr/bin/env python3
import os
import time
import numpy
from tempfile import TemporaryDirectory
import logging
logger = logging.getLogger(__name__)
import h5py
#Needed for multithreading:
from queue import Queue
from threading import Thread, Event
import multiprocessing
class Reader(Thread):
"""Thread executin... |
1190143a5113597de0b951449f05ebfa305a0d85bbb323b105d1fb65a10cc7b3 | Python | 7,090 | 173 | import logging
import pyoxigraph
from src.babel_utils import parse_rdf_literal, pull_via_urllib
from src.categories import CELL_LINE
from src.metadata.provenance import write_download_metadata
from src.prefixes import CLO, ORPHANET
from src.util import LoggingUtil, Text
logger = LoggingUtil.init_logging(__name__, le... |
aa351eaf49b5a111fe1923a25b4616b153aa709302620badba9d7e8b1baff282 | Python | 7,091 | 201 | import glob
import os
import ants
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from brainbuilder.qc.validate_interp_error import calculate_regional_averages
from scipy.stats import pearsonr, spearmanr
def calculate_2d_average(fingerprint_3d_df, fingerprint_2d_df, conve... |
0e75cf46d3e1b4e96e1726472af0bedf3757b2c24c70cc98161e051c163beace | Python | 7,092 | 206 | from __future__ import annotations
import numpy as np
import torch
from torch import Tensor, nn
class Fourier(nn.Module):
"""Fourier Expansion for angle features."""
def __init__(self, *, order: int = 5, learnable: bool = False) -> None:
"""Initialize the Fourier expansion.
Args:
... |
2184b4565b1ca5f28a2bd4733999305616df575fe8aa41280cb60ee5d4a94a18 | Python | 7,094 | 134 | # import cProfile, pstats
# pr = cProfile.Profile()
# pr.enable()
# test the performance of methods depending on the number of datapoints
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
import os
from grid_cell.sphere_manifold import Circle_Manifold, get_circle_mesh
from grid_cell.ori_tuning_ma... |
8e5a5a3ba9c4b369b70d0f8084540ad4d849b1cb3085e83c7db4976f7639ca9e | Python | 7,094 | 189 | import numpy as np
import torch.nn as nn
import os,shutil,torch
import matplotlib.pyplot as plt
from utils.config import opt
from load_data import IMG_Folder
from model import ScaleDense
from scipy.stats import pearsonr,spearmanr
from sklearn.metrics import mean_absolute_error
class AverageMeter(object):
"""Comput... |
9614a28f3c0587185395aa80e9e10b1a4e1f4b1ee16788df27168292c91b220c | Python | 7,094 | 174 | """Unit tests for src/model/glom_diff.py.
Exercises diff_cliques against hand-built before/after glom-dict states.
Test groups
-----------
Basic classification (pure_new / expanded / merged / unrelated):
The four mutually exclusive buckets that diff_cliques produces. Each test
constructs a minimal before/afte... |
ccebca01c8913669857f1051b02c852b2bd91c9e9cea5a0a7a0b8801f0693a00 | Python | 7,094 | 146 | import torch
import numpy as np
import argparse
import os
import sys
import time
import datetime
from ts2vec import TS2Vec
import tasks
import datautils
from utils import init_dl_program, name_with_datetime, pkl_save, data_dropout
def save_checkpoint_callback(
save_every=1,
unit='epoch'
):
assert unit in (... |
d7215d150af4175dd71bc6aef717001c3b2b203d14a8376a117c12f68eb8889e | Python | 7,098 | 200 | _base_ = ['../_base_/default_runtime.py', '../_base_/datasets/ade20k.py']
custom_imports = dict(imports='mmdet.models', allow_failed_imports=False)
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,... |
feceec02afaac716b2fc2a26300ead03aa4a7e915bc65a2d52803a3b000d0d74 | Python | 7,098 | 146 | """Find DOID xrefs that join two distinct diseases into one clique.
`remove_overused_xrefs` catches a target claimed by two or more subjects, which is the shape an ICD
family code has. It cannot catch the other shape: a single DOID term asserting an xref to an
identifier that belongs to a *different* disease -- a synd... |
c08f117c60aa1434cbaa3cca7b8fecb65244e8f02f9df80b820004ea8940323b | Python | 7,106 | 216 | """
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 torch
from torch_scatter import scatter
from ..initializers import he_orthogonal_init
from .base_layers import Dense, Resi... |
b8930f89ce0e9e8b39755b43779fbe7293e6b7b13989938709f98d4b73d7714a | Python | 7,108 | 170 | import holoviews as hv
import numpy as np
import panel as pn
import pytest
from guppy.frontend.artifact_removal import (
PreprocessingReviewView,
build_artifact_review_page,
build_preprocess_view_page,
load_pair_traces,
load_preprocessed_traces,
)
from guppy.utils._hdf5_io import write_hdf5
from gu... |
f33d195fb32968380ff0cbc252772a20f22872b12de6ff7906080e2dc657a718 | Python | 7,109 | 220 | """Camera geometry with flexible position/target specification.
Cameras can use either direct coordinates or CurveAttachment for position/target.
For session cameras (viewport state), direct coordinates are typical.
For cinematic cameras (in vis.geometries), CurveAttachment enables path animation.
"""
import typing a... |
ecc5bbfcf78d20b53d143287454f206fd0d52b6596a5472a3514a615f80d5dff | Python | 7,111 | 219 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 14:27:23 2023
@author: ingvieb
"""
from glob import glob
import shutil
import datetime
import SimpleITK as sitk
import numpy as np
import nibabel as nib
import json
import os
def createParameterMap(file, regType):
with open(file, "r") as f:
param_dict ... |
fe2b6eca0313bbfc0d4857f528cc9c06fdf83a642e4579f52ba761d6a6b5a942 | Python | 7,111 | 184 | """
Author : Alexis Lebrun (PhD. student)
School : Université Laval (Qc, Canada)
This module provides unsupervised learning models for vibrational spectra cluster analysis.
"""
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from matplotlib import pyplot as plt
import... |
1940993ec9f2f77469e37dcf06dbbef53f855f77b66ed0fa14bddc7173318b68 | Python | 7,112 | 212 | """Xgboost pyspark integration submodule for helper functions."""
# pylint: disable=fixme
import inspect
import logging
import os
import sys
import uuid
from threading import Thread
from typing import Any, Callable, Dict, Optional, Set, Type, Union
import pyspark
from pyspark import BarrierTaskContext, SparkConf, Sp... |
62f68202c5deda2810b272cee7c765050608aa49665a97b44bb853e7c946d421 | Python | 7,114 | 200 | import pytest
from zndraw.exceptions import (
BookmarkNotFound,
FigureNotFound,
InvalidCredentials,
InvalidPayload,
NotAuthenticated,
NotInRoom,
ProblemDetail,
ProblemError,
ProblemType,
RoomNotFound,
UsernameExists,
UserNotFound,
problem_responses,
)
class TestPro... |
50cee201a639cf7664a5bf196d933fabec5737bc09210ede6b5d986b3ffe1671 | Python | 7,116 | 213 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the... |
5bb9dd02a390cfceaec984beddb083fcbd9ce4f97e47d98145b527b08c93dcfd | Python | 7,116 | 250 | from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum, auto
import numpy as np
from dante.utils import Tracker
class BuiltInSyntheticFunction(Enum):
ACKLEY = auto()
RASTRIGIN = auto()
ROSENBROCK = auto()
GRIEWANK = auto()
MICHALEWICZ = auto()
SCHW... |
fc83189043c4b0de75600a56ef19f455f34490b471819687ba3cd5a7bcb3a6ed | Python | 7,120 | 211 | from dataclasses import dataclass
import ase
import numpy as np
from rdkit import Chem
from .calculators import MaceSimilarityCalculator
from .hydrogenation import NATURAL_VALENCES
from .hydrogenation_deterministic import build_xae_molecule
from .sascrorer import calculateScore
@dataclass
class BaseReport:
comp... |
7d3af0f9e5d45b98899671effaae8d5af734f4924041d009c48c8cf036c443f7 | Python | 7,121 | 224 | """E2E tests for @internal (server-side) extension execution.
@internal extensions are registered at startup and executed by the in-process
TaskIQ worker. The full path is:
vis.run(extension) -> submit_task -> TaskIQ -> execute_extension
-> ZnDraw(url, room_id) -> extension.run(vis)
"""
import ase
import pytest
... |
744272ffd2a19e6f2e169a75553317c09bf1fcf68c65f76d0b3c3c34e5c949b8 | Python | 7,122 | 237 | #*******************************************************#
# Classes used as configuration files
#*******************************************************#
class datasetConfig:
'''
Class for defining dataset parameters: shape, split ratio, augumentation etc.
'''
'''
Labes_csv_path: Root directory w... |
66a323b159e00756c81fe1507b85df5ca466a804d6f6b7987e43f1e40e992121 | Python | 7,127 | 293 | import numpy as np
from frozendict import frozendict
from numpy import typing as npt
"""
Adapted from https://github.com/ehoogeboom/e3_diffusion_for_molecules/blob/main/qm9
"""
BONDS1 = frozendict(
{
"H": {
"H": 74,
"C": 109,
"N": 101,
"O": 96,
... |
b349609a814f1aee606e9131b899f6d37602fbb3f8e35b19647e6234747b933e | Python | 7,127 | 242 | #!/usr/bin/env python
"""
MetaWIBELE: ddi_DOMINE_ann module
Assign domian description involved in DDI
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 So... |
c65c66ef0aab1ac9d2e264862bcb2e23617057a5a5d065287db65a822c8301a2 | Python | 7,128 | 196 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_norm_layer
from torch import Tensor
from mmseg.registry import MODELS
from mmseg.utils import ConfigType, SampleList
from ..utils imp... |
73eed1f15050c2c98966bd21f8356996344a9cb676d30c9187482442839a9ec1 | Python | 7,130 | 276 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 30 20:24:25 2024
@author: Andrei Istudor andrei.istudor@gmail.com
"""
import pandas as pd
import numpy as np
# import av
import cv2
from os import path, remove
import sys
def loadVideo(videoFile):
frames = []
cap = cv2.VideoCaptu... |
a027eee602c745e7a483efe6a8857c6bb4e0d33bafec420d7e323187109e2f9f | Python | 7,132 | 225 | """CLI auth commands: login, status, logout."""
from __future__ import annotations
import time
import webbrowser
from datetime import UTC, datetime
import httpx
import typer
from zndraw.state_file import StateFile, TokenEntry
from .connection import (
EXIT_CLIENT_ERROR,
EXIT_CONNECTION_ERROR,
PasswordO... |
dd36ac9821f1d88f65d5fd4fb60ada7c92706bba403e0893424173a4b1bf5fc1 | Python | 7,132 | 186 | # Machine learning for MagellanMapper
# Author: David Young, 2017, 2019
"""Machine learning and output for MagellanMapper.
"""
from collections import OrderedDict
from enum import Enum
from typing import Any, Callable, Dict, Sequence, Tuple
import numpy as np
import pandas as pd
from magmap.settings import config
fr... |
3b7310e2a3d7f26673d9d15de86bd1574c1d27b63d9b71e1aa9cc869a9c3f239 | Python | 7,135 | 182 | import numpy as np
from scipy.stats import vonmises
import matplotlib.pyplot as plt
from global_setting import *
def exponential_gradient_fill(diagonal, alpha=0.5):
'''
diagonal (2D array): array of shape (n_sample, 10) representing the diagonal for each sample
alpha (float): the exponential decay rate
... |
d1b1093b5b67167e68a0b29c0ae37e382d2d26de4d95784c095143fcb5213414 | Python | 7,136 | 210 | #!/usr/bin/env python
"""
Parse training log
Evolved from parse_log.sh
"""
import os
import re
import extract_seconds
import argparse
import csv
from collections import OrderedDict
def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_lis... |
77320f39cff64a23eb278d786b0aaeb834983f11f9fa1b0e60a5ae615f13cc5a | Python | 7,138 | 160 | import json
import shutil
from pathlib import Path
from unittest.mock import patch
import holoviews as hv
import numpy as np
import pytest
from guppy.analysis.io_utils import read_hdf5
from guppy.analysis.standard_io import read_transients_from_hdf5
from guppy.frontend.visualization_dashboard import VisualizationDash... |
fb60bada9cbe5efcec11d871e357ef225d6b96eaaafd7096b8c0184084835210 | Python | 7,148 | 190 | """E2E tests for register_job / register_extension convenience API.
Covers:
- register_job(cls, room='@global')
- register_extension(cls, public=True) deprecated shim
- register_job(cls, public=True) deprecated parameter
- ValueError when both room and public are specified
- Global extension visibility from any room
-... |
35458891dbd3dfb4bc76518de5949dbd50e4966fbc2af63176e744ec7550f475 | Python | 7,149 | 205 | #!/usr/bin/env python
#
# DL-based motion correction for dMRI/fMRI
#
# Copyright (c) 2025 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import torch
import torch.nn as nn
from monai.networks.blocks import Warp
# -----------------------------
# Some helper function
# ------------------... |
9d6fcd5ad0b91324df5b973f12d7d94817c93f7ab2a7363152f95dca39a07bae | Python | 7,151 | 198 | import os
import logging
from medperf.entities.cube import Cube
from medperf.entities.dataset import Dataset
from medperf.entities.execution import Execution
from medperf.utils import generate_tmp_path, remove_path
import medperf.config as config
from medperf.exceptions import ExecutionError, CommunicationError, Clean... |
5964e09628e281bf920e6a1d19bea9e4d4ca6de626b7e5c2545be8f2905bebac | Python | 7,152 | 217 | import os
import torch
import random
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from utils import *
from const import *
from random import shuffle
from model import *
from sklearn import metrics
from dataset import MyTestDataset
from torch_geometric.loader import DataLoader
from sklearn.me... |
de3ab0c669daa138d26d210cd0bcf1b46176c8c092e6aee08ef78ab70ba8aa79 | Python | 7,160 | 204 | # Copyright (c) OpenMMLab. All rights reserved.
# Source: https://github.com/openai/CLIP.
IMAGENET_TEMPLATES = [
'a bad photo of a {}.',
'a photo of many {}.',
'a sculpture of a {}.',
'a photo of the hard to see {}.',
'a low resolution photo of the {}.',
'a rendering of a {}.',
'graffiti o... |
bbfe4f339204ef9c54fdb7b97175c67f532c3bdc2e50bac55fc9195fc88de7e5 | Python | 7,162 | 205 | # SPDX-License-Identifier: Apache-2.0
'''
This script contains helper functions which are used by cityscapes_loader.py in duc-validation.ipynb
'''
import logging
import math
import os
import random
import time
from PIL import Image
from datetime import datetime
import cv2 as cv
import mxnet as mx
import numpy as np
... |
5321f0296911978dd298337aec8d7fcdb16a682ea1419aa6c4af6bd82c383128 | Python | 7,163 | 239 | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib.ticker as ticker
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
EV_list = [
25,
100,
500,
1000,
]
plt.figure... |
80aac5de4b3682bd8de8d46d6e266786f27df4e9f83be348e7f6ed9be72e8b2a | Python | 7,168 | 195 | import json
import os
import platform
import subprocess
import tempfile
import numpy
import pytest
import xgboost
from xgboost import testing as tm
class TestCLI:
template = '''
booster = gbtree
objective = reg:squarederror
eta = 1.0
gamma = 1.0
seed = {seed}
min_child_weight = 0
max_depth = 3
task = {task}
mod... |
c8334c8558beb4f950b2060705a23b3f026a90b0b27139482bb22296cc4fb536 | Python | 7,170 | 153 | # Generate events files for task-shortvideos
# This script reads raw behavior data files from d_beh for task-shortvideos, extracts time stamps and design information, and stores them in new *events.tsv files accompanying BOLD files.
# For more information, please see README.md and the associated paper (Jung et al., 2... |
37fac606e3798cef4c1eb327287994d4846ecf1d6d1c87b455f86d825be5d8e1 | Python | 7,171 | 157 | # Tests for datahandlers/ensembl.py
import csv
import json
import logging
import os
import pytest
import requests
from apybiomart import find_datasets
from src.datahandlers.ensembl import pull_ensembl
logging.basicConfig(level=logging.INFO)
def read_biomart_file(biomart_file):
"""
Reads a BioMart output fi... |
ee54eba85139c8a8c788c7d8fb524547415acab0e16a8b903cf8d62843087c25 | Python | 7,171 | 212 | """E2E test: Guest can authenticate, create a room, and write/read frames via REST.
Uses a real uvicorn server via the http_client fixture (which starts the server).
All interaction is through the REST API only (no Socket.IO).
"""
import uuid
import ase
import msgpack
import pytest
from httpx import AsyncClient
fro... |
27dd7fa648244624119f2413e70b7aa5186655498e0ac7b6c681881615e5db1a | Python | 7,173 | 203 | from collections import OrderedDict
import torch
import torch.nn.functional as F
from torch import nn
class GninaNetwork2017(nn.Module):
"""
Gnina network model for 2017.
Notes
-----
This code block is adopted from the following link:
https://github.com/gnina/models/blob/master/acs2018/defau... |
1be2051bbc1c0c826299ba75c1cf1117562a9c28310cf746bcbe8729d7bb4425 | Python | 7,176 | 179 | # -*- coding: utf-8 -*-
# tests/test_notebooks.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 ... |
9d42507fb380de1bc708ff3747c2a9158ad4e7e06ce5925bd3b1e5baa63104cc | Python | 7,176 | 221 | import logging
import os
from typing import Optional
from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse
import medperf.config as config
from medperf.account_management import get_medperf_user_data
from medperf.commands.aggregator.submit import SubmitAggregat... |
42d6d41acc43c9485e31aa545a133871ccfb08a523fcdb62519d5ffe025b3fb9 | Python | 7,181 | 155 | # 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... |
3c1845961f753ab700d62a848dd12fc2dae020b7989ef44200741d1cc1cfafad | Python | 7,182 | 192 | """Unit test for the source-impact report CLI, end to end on synthetic data.
A fixture lays down two anatomy datasets in a temporary intermediate root:
- ``EXISTING`` — stands in for the current Babel set (four singleton cliques).
- ``NEWSOURCE`` — the source under evaluation, with concord rows chosen so that adding
... |
e4cdb21cdded399f3b2566de91ae25bfc810174cdf31c577f4393e3c25fc1270 | Python | 7,184 | 242 | import os
import numpy as np
from . import printit, utils
try:
from . import all_actions
except ImportError:
printit("Warning: Could not import all_actions submodule. Please check if the package is compiled correctly.")
__all__ = [
# Single frame methods
"frame_voxelize",
"frame_observation",
# Traj... |
ebe79afe53385da7b4720b6d11c22cb0d9f8aa50296b710ae5f9e77dfa82cf6a | Python | 7,186 | 185 | from ipaddress import IPv4Address, IPv4Network
from CybORG.Shared import Observation
from CybORG.Simulator.Actions.ConcreteActions.LocalAction import LocalAction
from CybORG.Simulator.State import State
class ControlTraffic(LocalAction):
"""Abstract parent class of all actions that control traffic."""
def __i... |
721e52810afc9a37485d807c38bd528c20a74e248df321c3ed3c5a83aee67bc8 | Python | 7,187 | 216 | import os
# Enable MPS fallback for unsupported operations early (like linalg_qr in LSTM)
# This must be set before importing PyTorch for the first time
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
# For TimeGAN compatibility, check if we should disable MPS entirely
if os.environ.get("DISABLE_MPS_FOR_TIMEGAN", "0"... |
0cb2f446a7f56399314908fdb065c1b37bd86c3e36f5faa66d636ebd66dbf29b | Python | 7,188 | 120 | import logging
import panel as pn
logger = logging.getLogger(__name__)
class Sidebar:
"""Panel sidebar component containing step labels, action buttons, and progress bars.
Parameters
----------
template : panel.template.base.BasicTemplate
The Panel template whose ``sidebar`` area will recei... |
476576655cf085a6f488a5b5f14d67a4030e2ffec8b4f6bf48a8d75c3b11a045 | Python | 7,188 | 149 | #!/usr/bin/env python
#
# Compute adapted Spinal Cord Occupation Ratio (aSCOR) from spinal cord and spinal canal masks.
# morphometrics.
#
# Copyright (c) 2025 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
import os
import textwrap
import logging
import itertools
import numpy... |
cf608101875e295f0684f1d9615ec05e2ac96193a88103fb47fc16d9265ed37a | Python | 7,197 | 342 | import pickle as pkl
import mne
import numpy as np
import pandas as pd
import h5py
import os
import re
import sys
import yaml
import multiprocessing
import gc
#from scipy.io import loadmat
from glob import glob
from progressbar import Bar, ETA, Percentage, ProgressBar
from joblib import Parallel, delayed
from optpar... |
d47be74f0b177c069fc615dfaace67efd077e011d26a6bb172bdfe0d8181cb10 | Python | 7,198 | 220 | import logging
from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse
from medperf.account_management import get_medperf_user_data
from medperf.entities.model import Model
from medperf.entities.benchmark import Benchmark
from medperf.commands.model.associate imp... |
72f68cec3c15dab08f169fb152df49a56f11a92e64239d0adf5957a6d3b29671 | Python | 7,204 | 203 | import os
import pandas as pd
import torch
import numpy as np
from nnfabrik.builder import get_data
from neuralpredictors.training import eval_state, device_state
from neuralpredictors.data.datasets import FileTreeDataset
def model_predictions(model, dataloader, data_key, device="cpu"):
"""
computes model pr... |
a42b4a6d5c391910c919d86c9d800370c08523a4b7b69ab33ff9c52ad80a088c | Python | 7,204 | 185 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import matplotlib as mpl
import os
from multiprocessing import Pool
def load_and_sort_data(file_path):
"""Load data and sort by specified layer order"""
layer_order = ['conv1_1', 'conv1_2', 'conv2_1', 'conv2_2', 'conv... |
cfdc3df3339a3f0d9db62a52c2ddade261b08d6a5eaec85a7be7b3066b1e8ea5 | Python | 7,204 | 184 | import numpy as np
class DecisionMaker:
def __init__(self):
"""
Initialize the decision-making module for autonomous driving.
The system uses YOLO model outputs to make real-time decisions.
"""
# State dimensions: [class_id, distance_bin, speed_bin]
self.state_space ... |
e7032fbfa049aa3634d86def7507cd28685e796f5aa58052689b43f0d13375b9 | Python | 7,204 | 177 | import os
import shutil
import argparse
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.tensorboard
from torch.nn.utils import clip_grad_norm_
from tqdm.auto import tqdm
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
from rde.utils.misc import BlackHole, l... |
3864c07b29aa311faf88768b8fd6cf292fdc8bd804eaf99ebecb7debc2cb828c | Python | 7,206 | 167 | # Note that this code is adapted from the BioBERT github repo:
# https://github.com/guidoajansen/biobert/tree/87e70a4dfb0dcc1e29ef9d6562f87c4854504e97/biobert/biocodes
import argparse
import itertools
parser = argparse.ArgumentParser(description='')
parser.add_argument('--token_test_path', type=str, help='')
parser... |
ef08d13dc0a06f0acd493936b1bb9b918352ad3b3ff8aeb17add2eb986d0039b | Python | 7,207 | 219 | """Tests for unified StateFile (replaces PID files + tokens.json)."""
from __future__ import annotations
import json
import stat
from datetime import UTC, datetime
import pytest
from zndraw.state_file import ServerEntry, StateFile, TokenEntry
@pytest.fixture
def state_file(tmp_path):
"""StateFile backed by a ... |
a09ddba7cd639723a7423bc3c6b4eb252b5daeb8d4b5868a1fed9457c873a4e4 | Python | 7,209 | 166 | '''
Main entry point for running sacred experiments.
Author: Hanna M. Tolle
License: BSD 3-Clause
'''
import sys
sys.path.append('../')
import os
from typing import Dict
import argparse
from time import time
import neptune
from neptune.integrations.sacred import NeptuneObserver
from sacred.observers import FileStora... |
97411c72798769b590af21a5dd1c71c8a68ba2a5c860629ef73c664f1b18dfb8 | Python | 7,213 | 171 | import shutil
from pathlib import Path
import numpy as np
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
@pytest.mark.parametrize(
"step3_fixture_name, expected_recording_site, expected_ttl",
[
... |
ae7a21080a149dc6fe2bebdf49e39e1fbbab50b0b922a5539030e3ea26fc5dd5 | Python | 7,217 | 213 | import uuid as uuid_mod
from datetime import UTC, datetime
from uuid import UUID
from sqlalchemy import (
CheckConstraint,
Column,
ForeignKey,
Index,
String,
TypeDecorator,
UniqueConstraint,
column,
func,
)
from sqlalchemy.types import DateTime
from sqlmodel import Field, SQLModel
... |
3336260f187fe190892440077837be1025940cf7920ec243c48850b19342cdfe | Python | 7,224 | 209 | import numpy as np
import cupy as cp
import copy
from .conv import *
class iSeqSingle:
Wact = None
Wpos = 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
... |
c8646ded9b20386b81449e55e59ac488dd4a67df169e5ab98274a3c2e8225815 | Python | 7,227 | 58 | #!/bin/python
import truster
import os
path_parent = os.path.dirname(os.getcwd())
lunarc = "config_files/lunarc_config.json"
modules = "config_files/software_modules.json"
crispri = truster.Experiment("crispri", lunarc, modules)
crispri.register_sample(sample_id = "Seq254_14", sample_name = "AA_h6_L1_CRISPRi_LacZ_LV... |
1e52723326aab5af0ecefb1c78b73bf2c5f5143f74c95813aeb048793396450d | Python | 7,228 | 228 | #!/usr/bin/env python
"""
MetaWIBELE: mspminer_msp module
Summary MSPs information from MSPminer
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 Softwar... |
001323daf9dbfde9deb6fd2c92922ec20a59c8b49616f88d97e16bf81cb46fe8 | Python | 7,230 | 193 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List, Tuple
import torch
import torch.nn as nn
from mmcv.cnn import build_norm_layer
from torch import Tensor
from mmseg.models.decode_heads.sep_aspp_head import DepthwiseSeparableASPPHead
from mmseg.models.losses import accuracy
from mmseg.models.uti... |
bab0771b41448c81647f304f70cedc9f2c3e8272c2eb09c798eaf8739f8fa4e7 | Python | 7,231 | 217 | #!/usr/bin/env python
from __future__ import annotations
from argparse import ArgumentParser
import logging
import os
import sys
from typing import Optional
from .. import __version__
from ..main import workflow
lgr = logging.getLogger(__name__)
def main(argv: Optional[list[str]] = None) -> None:
logging.basic... |
86eb5344aefcc4c12ba56601e3c7ed51c0c9df72e90330f412147003d2621645 | Python | 7,234 | 231 | """Single Objective CMA-es class"""
"""
Copyright (c) 2016-2022, 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... |
1493cce15977157f32dc169ec6f2ca27e01a5e7df13bb61567e12cecc6cc1f71 | Python | 7,237 | 194 | import numpy as np
import pytest
from guppy.analysis.standard_io import (
read_freq_and_amp_from_hdf5,
write_freq_and_amp_to_hdf5,
)
from guppy.analysis.transients_average import average_transients_for_group
# ── average_transients_for_group ──────────────────────────────────────────────
@pytest.fixture
def... |
cc993fcba35f7d47d15c53fdd5cefcb8375b4e96e3c513629f4cb250b59ec23d | Python | 7,239 | 217 | import numpy as np
import lmfit
import scipy.stats as st
class MeltCurveModel(lmfit.Model):
def __init__(self, *args, **kwargs):
self.T = kwargs['T']
if 'f_margin' in kwargs.keys():
self.f_margin = kwargs['f_margin']
self.kB = 0.0019872
self.nan_policy = 'omit'
... |
909c69b6dad25388fb25e93b966f9f9e0d51643d54dbef4a1f02b6b37dd59107 | Python | 7,241 | 231 | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib.ticker as ticker
import numpy as np
EV_list = [
25,
100,
500,
1000,
]
# avg of 100 runs
optimal_mean = [
-20_556,
-108_539,
-2_764_761,
-11_034_490
]
optimal_std = [
6_191,
24_080,
... |
9299e0e518f99db8d1044d7a05065c816b5691545f92035c75213740fd24328b | Python | 7,241 | 203 | import argparse
import time
from typing import List, Tuple
import cv2
import loguru
import numpy as np
import onnxruntime as ort
logger = loguru.logger
def parse_args():
parser = argparse.ArgumentParser(
description='PP_Mobileseg ONNX inference demo.')
parser.add_argument('onnx_file', help='ONNX fil... |
ada588d22911929a47d3db99480e648ddca10014f60c69ad3ed23afa4cf5a99c | Python | 7,241 | 187 | from scipy.interpolate.interpnd import NDInterpolatorBase, _ndim_coords_from_arrays
from scipy.spatial import cKDTree
import numpy as np
class NearestNDInterpolator(NDInterpolatorBase):
"""NearestNDInterpolator(x, y).
Nearest-neighbor interpolator in N > 1 dimensions.
.. versionadded:: 0.9
Methods
... |
b63d7676564cb9517c5cdb12c752698019b45df0f2bef2b60c8cabc9b7efdcaa | Python | 7,242 | 190 | #!/usr/bin/env python
#
# Display bvecs
#
# Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
import numpy as np
from spinalcordtoolbox.utils.sys import init_sct, printv, set_loglevel, LazyLoader
from spinalcordtoolbox.utils.shell ... |
e0ec37f84f78d2a762391d9296edb4595d01bd5fde0e4a93746a202620678042 | Python | 7,242 | 154 | import warnings
import numpy as np
import pytest
from guppy.analysis.binned_metrics import compute_bin_edges, compute_binned_metrics
class TestComputeBinEdges:
def test_exact_multiple(self):
# 10 s at 5 s bins divides evenly into two whole bins.
np.testing.assert_allclose(compute_bin_edges(start... |
12a19e7eab66a0bb2115494e71e6fd58cd070b876a8f20e7e63835fca6641dd6 | Python | 7,245 | 193 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Dict, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmengine.model import BaseModule, ModuleList, Sequential
from torch import Tensor
class DAPPM(BaseModule):
"""DAPPM module in `DDRN... |
1cdb3dc1f210bc90e9f7ee03520b4e6107bd34ea63f9c39f5b7addbfec4a59f6 | Python | 7,247 | 181 | # -*- coding: utf-8 -*-
from fengshen.models.model_utils import add_module_args
from transformers import PegasusForConditionalGeneration, PegasusConfig
from pytorch_lightning import Trainer, loggers, LightningModule
from pytorch_lightning.callbacks import LearningRateMonitor
from tokenizers_pegasus import PegasusToke... |
cb9734eeb3f34fa928121ac979ecb797b9a15c141a72ca84ae2ed53016721c8d | Python | 7,251 | 137 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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 cop... |
71b180f955f6ab2a2eaffb3d4208e8bfb9edda53f6d1e60b340bb095a0600aee | Python | 7,260 | 189 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
from pathlib import Path
from typing import Optional, Union
import mmcv
import numpy as np
import torch
from mmengine import Config
from mmengine.registry import init_default_scope
from mmengine.runner import load_checkpoint
from mmengine.utils import mkd... |
f3f117fcfdd7a4f7b73aa386df53353218ba31c36ef3dc078763910753c3d393 | Python | 7,261 | 197 |
import numpy as np
from scipy.ndimage.filters import gaussian_filter
conv1_isort_all = [[13,5,6,15,10,12,2,12,1,3,9,14,7,0,11,4],
[0,13,15,8, 14,2,11,9,7,5,1,4,6,12,3,10],
[10,9,4,12,6,7,14,11,10,3,5,2,13,15,0,1],
[14,3,0,4,5,12,11,10,6,7,8,9,13,15,1,2],
[11,3,15,10,8,6,12,2,13,5,4,7,... |
613edf7649849eb36ddb0d1a8f29fa52ef91f8ac78190ea23e97e676b00cb6fb | Python | 7,266 | 195 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-ignore-all-errors
import copy
import unittest
from fvcore.common.param_scheduler import (
CompositeParamScheduler,
ConstantParamScheduler,
CosineParamScheduler,
LinearParamScheduler,
StepParamScheduler,
)
class TestCompositeScheduler(uni... |
508010bc13585163c6398f601f95b1e850634475eabb39b896b0b0a3c9ae2f6f | Python | 7,267 | 188 | """
Perform benchmarking on the pre-trained models.
"""
import os, sys, time, io
import argparse, random, json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from scipy.stats import p... |
2ac1d00167f6de713d2bd1d1a737c2a3284f3671b5e47d4d78d169cf49a734f0 | Python | 7,271 | 216 | import inspect
import sympy
class Mechanism:
"""
Abstract base class for a reaction mechansism
"""
param_names: dict[str, str]
modifiers: list['Mechanism']
param_names_modifiers: dict[str, str]
def __init__(self, **kwargs):
# Initialize the parameter names
try:
... |
d9c365a150b348fda72f30457d7b4b88c8db12a3cc656b2a6f1f20a2528663c8 | Python | 7,278 | 189 | from scipy.interpolate.interpnd import NDInterpolatorBase, _ndim_coords_from_arrays
from scipy.spatial import cKDTree
import numpy as np
class NearestNDInterpolator(NDInterpolatorBase):
"""NearestNDInterpolator(x, y).
Nearest-neighbor interpolator in N > 1 dimensions.
.. versionadded:: 0.9
Methods
... |
aa3af36a2e505206713d2cd741b0bf13da5947db253c21cfde0fe4bf7cabf4d0 | Python | 7,279 | 184 | import os
import sys
import torch
import numpy as np
from minimodel import data, model_builder, metrics
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mouse_id', type=int, default=1, help='mouse id')
parser.add_argument('--ineuron', type=int, default=1, help='index of neuron')
parser.set_de... |
c9dfef3d524d3eab9afad2353886de10bf8dbd5044973af287f3204168e935a8 | Python | 7,279 | 190 | import os
import cv2
import numpy as np
from scipy.io import loadmat
db = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
db[0]['mname'], db[0]['datexp'], db[0]['blk'] = 'L1_A5', '2023_02_27', '1'
db[1]['mname'], db[1]['datexp'], db[1]['blk'] = 'L1_A1', '2023_03_06', '1'
db[2]... |
8cd6cf7f6fa1dc7ca1516025b0619beb0f2dd8a4e3fe9b694a1f6939a76461f2 | Python | 7,280 | 233 | import torch
from torch import nn
from lib.models import (
fusion_models,
table_models,
)
from lib.models.image_models import (
resnet,
resnet2p1d,
pre_act_resnet,
wide_resnet,
resnext,
vit_3d,
)
def get_module_name(name):
name = name.split(".")
if name[0] == "module":
... |
6ff59e383367b6609f93bdcbe82e90391339b0a4cb25f498d6512b010a4fc90a | Python | 7,283 | 195 | import os
import logging
import numpy as np
import keras
from keras import ops
import typing as T
import seaborn as sns
import matplotlib.pyplot as plt
import tsgm.types
import tsgm.utils
logger = logging.getLogger('monitors')
logger.setLevel(logging.DEBUG)
def _to_numpy(tensor):
"""Convert tensor to numpy ar... |
f40b376e073100635992119d88c773b375d4aeaa8630b36b785484c01c82369b | Python | 7,283 | 195 | 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_l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.