sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
278f08ab0a9b66ba15f66c7254546c2293c07d9f8d629ac0a2a1ecdeb3f992a3 | Python | 922 | 31 | import os
import sys
import inspect
import filecmp
from itertools import islice
def checkFolderEquality(folder1, folder2):
"""
Given two folders, check if there are the same number of files,
that the names of files are the same, and that the files with the same
names are the same.
"""
folder1_... |
49a40b6f38005288ae439590d57dbd535ac2770823752da981267edbd05a5c33 | Python | 922 | 33 | import numpy as np
AALETTER = [
'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', 'X']
AANUM = len(AALETTER)
AAINDEX = dict()
for i in range(len(AALETTER)):
AAINDEX[AALETTER[i]] = i + 1
INVALID_ACIDS = set(['U', 'O', 'B', 'Z', 'J', '*'])
MAXLEN = 1024
def ... |
b7d2fa7e4cafff72c5e5e66b513eb3240ae5cd6709acd37bfd015dde0ca17f78 | Python | 922 | 38 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtDBus classes and ... |
0b35b11a2cb07c7126163a71d814a460de0260ed1e40b217b21ce453b0552199 | Python | 923 | 32 | """
Variant: numpy (direct NumPy / wofz — no lmfit object construction)
``_gaussian_eval`` evaluates the area-normalised Gaussian analytically.
``_voigt_eval`` calls ``scipy.special.wofz`` (Faddeeva function) directly.
This is the simplest non-trivial speedup: identical maths, zero Python
object overhead per call.
"... |
5b4c2c833fa61513e4d56e788330b4086ac46d0a12eeb2bf40566dfee2ea4777 | Python | 923 | 28 | import nibabel as nib
import numpy as np
from skimage.filters import frangi
# 输入输出文件
in_file = "/mnt/f/BIDS/demo_BIDS/derivatives/xfm/sub-AFib0241/ses-baseline/T1w_filterNLM2.nii.gz"
out_file = "//mnt/f/BIDS/demo_BIDS/derivatives/xfm/sub-AFib0241/ses-baseline/T1w_frangi.nii.gz"
# 读取 NIfTI
img = nib.load(in_file)
data... |
5eaf4f5fc2e0a6e5d17d28ea6f69a19280f8c485e3ae5c6c0e6b1e18e7dfcf48 | Python | 923 | 25 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Henrik Zunker
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
684524ade9b44805176130dfc57adddf826fac5b27bad8a0c1348e9114b74f32 | Python | 923 | 33 | import pandas as pd
from brainways.utils.pls_analysis import get_results_df_for_pls, pls_analysis
def test_pls_analysis():
results_df = pd.DataFrame(
[
{
"cond": condition,
"animal_id": animal_id,
"is_parent_structure": False,
"i... |
bb6b7506f0fbaee9de1f15fb2fe363af52a466a32b48678a3423df50295cd271 | Python | 923 | 25 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Maximilian Betz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
cb3aa6c170c6354e9043eef4fd98ba8a0922f66e52b3acd7e00e484b5b5c1e62 | Python | 923 | 31 | # This script split dataset into training and testing at given ratio,
# results are stored in databatch folder
import os
import random
import argparse
def main(args):
datapath = args.datapath
ratio = args.ratio
names = os.listdir(datapath)
random.shuffle(names)
nsamples = len(na... |
dc9236a5758cc835220c8b4ea31cd05707a52a7eb1cc5da807df57d71707ee19 | Python | 923 | 25 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Martin J. Kuehn
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
fed1cfa604cce9b98b464ce95a05dd8d5bd5dc321199a5405bdaeac8709f6cbf | Python | 923 | 25 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Daniel Abele
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... |
c985d2c972f063daaf8c7a83e0a99e5bab6c9e43f2ae0d4b3f183b8c7d2a54b1 | Python | 924 | 28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.T... |
eea3722ed3af7f6618d360132179c544cd675076ac4e858336c6836688c25311 | Python | 924 | 20 | # data/load_data.py
import pandas as pd
from config.paths import DATA_DIR, SPLIT_DIR
def _suffix_from_mode(mode):
suffix_map = {"full": "", "cpss": "_sub", "stroke_relevant": "_sr"}
if mode not in suffix_map:
raise ValueError(f"Unknown mode: {mode}. Use 'full', 'cpss', or 'stroke_relevant'.")
retur... |
02e8d3703e6def3817ad6d5c7f3377adb3996daddac031ba71218796291a350d | Python | 925 | 28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys='surface_vtk_fib.zip')
tmp_dir = tempfil... |
d1231ff91b17a6692bd18b1c916a32db793061698903a6b7ca273f9ab56a7ae0 | Python | 925 | 24 | import torch
import torch.nn as nn
class DynamicTanh(nn.Module):
def __init__(self, normalized_shape, channels_last=True, alpha_init_value=0.5):
super().__init__()
self.normalized_shape = normalized_shape
self.alpha_init_value = alpha_init_value
self.channels_last = channels_last
... |
ef3465decf0689211fa80389d0f7c97de60f01fd6c693d796592b590ea08fe62 | Python | 925 | 21 | # -*- coding: utf-8 -*-
"""This sub-package provides various volumetric filter kernels and structure elments
A set of linear filters can be applied to the data using
:mod:`~ClearMap.ImageProcessing.Filter.LinearFilter`.
Because its utility for cell detection the difference of Gaussians filter
is implemented directl... |
34fb8b02bdd583d8d1cd774e2a4ef85fc49ce475a038f08f05991b055a2b680e | Python | 926 | 31 | """ Collapse long edges """
import SVMTK as svm
from pathlib import Path
if __name__ == "__main__":
print("Start ",__file__)
outdir = Path("results")
outdir.mkdir(exist_ok=True)
shark = svm.Surface("../Data/mech-holes-shark.off")
print("Number of edges before: {}".format( shark.num_edges()) )
#... |
3c44f9e4150a9461e70b40e9f218433bac34dc961109a9ad52ffdbe98acac230 | Python | 926 | 35 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 18:35:31 2019
@author: Yoshi
"""
def scale_calculator(width):
# Creates a variable, scale
scale = 1
# Checks if the image is less than 1500 pixels wide
if width < 1500:
# Finds the minimum integer multiplier until width is at... |
7378b31f71cdd2988348ad51bd2bd1346fd539239b17f58ce558555cc56f3265 | Python | 926 | 34 | # Copyright (C) 2018-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.apps import AppConfig
class EngineConfig(AppConfig):
name = "cvat.apps.engine"
def ready(self):
from django.conf import settings
from . import default_settings
... |
9844d89b426005b3aa9ee3757a3fd7d5ff713ae370246da8e12228887c72a19e | Python | 926 | 41 | #!/usr/bin/env python
"""
Read some whitespace separated data from stdin and pretty print it so that
the columns line up.
"""
import sys
def main():
pad = "\t"
align = None
if len(sys.argv) > 1:
pad = " " * int(sys.argv[1])
if len(sys.argv) > 2:
align = sys.argv[2]
rows = [line.s... |
22944cc38f3c25b4ca5397709a391143d46f1c1112a731c534b147fad473d4f2 | Python | 927 | 37 | """Branding assets for the ChemGraph Streamlit UI."""
from pathlib import Path
_UI_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_ASSET_DIR = _UI_DIR / "assets"
_LOGO_DIR = _PROJECT_ROOT / "logo"
LOGO_IMAGES = (
_ASSET_DIR / "chemgraph-logo.png",
_LOGO_DIR / "chem... |
d3a79f3398b504d1e526460201933f0a4033208da9eaa32ef78e02b83c2950f5 | Python | 929 | 27 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['atlas.zip'])
tmp_dir = tempfile.Tempor... |
a2ff92f6a35e2565c2d70b1202b2853e2bee36e2fc6051abc47650a8be3b4703 | Python | 930 | 26 | from typing import Callable, Dict, Tuple
from qtpy.QtWidgets import QMessageBox, QPushButton, QVBoxLayout, QWidget
class TpsWidget(QWidget):
def __init__(self, controller):
super().__init__()
self.controller = controller
self.reset_button = QPushButton("Reset")
self.reset_button... |
0b11bcf7c972404865cc4871d0bfb28247452c1a43c374fe5953eef9f4fc8e2f | Python | 931 | 29 | import numpy as np
from typing import Union, Optional, Dict, List
from ..visualization.images import figure2img
__all__ = []
def register(obj):
__all__.append(obj.__name__)
return obj
@register
def log_figure(
logger,
tag: str,
figure,
global_step: Optional[int] = None,
... |
e172346eced51143c3fafbece14fa099755fd80294fe3cfb8a5c1af7792056fa | Python | 931 | 29 | """
Variant: lmfit-objects (baseline / "before" state)
Creates a fresh ``lmfit.models.GaussianModel`` or ``VoigtModel`` Python
object on **every single call** to ``_gaussian_eval`` / ``_voigt_eval``.
This matches the original production code before the direct-NumPy rewrite
and provides the slowest reference point in ... |
5b04797003bb9785682837c3015968309762fbcc07d6f92be4f2b9a53bfb334e | Python | 932 | 35 | from typing import Optional
import numpy as np
import skimage.io as io
import torch
from torch import Tensor
def imread(image_path: str, pin_memory: Optional[bool] = False) -> Tensor:
"""
Imports an image from file and returns in torch format
:param image_path: path to image
:param pin_memory: saves... |
ab93a38189ebf54255fe01d26f1e3851750dc0bf733c3e662a08e4b48e30bbbe | Python | 932 | 30 | #!/usr/bin/env python3
"""Prepare binary classification datasets for each artifact type."""
import logging
from artifact_identification.data_preparation import BinaryModelDataPreparer
def main():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.get... |
c339ff53be1b1762500cf5d0747e95eadf1716da05f0550ff40333a1375a03bc | Python | 932 | 41 | """Test I/O."""
import logging
import unittest
import pytest
from yasa.io import (
is_pyriemann_installed,
is_sleepecg_installed,
set_log_level,
)
logger = logging.getLogger("yasa")
levels = ["debug", "info", "warning", "error", "critical"]
class TestIO(unittest.TestCase):
"""Test IO functions."""... |
e41fda667dd0f1627510e4b48d7d15a30ebdc97162290e4830df8a68298dd857 | Python | 933 | 24 | # Copyright (c) 2026 Rohit Jena. All rights reserved.
#
# This file is part of FireANTs, distributed under the terms of
# the FireANTs License version 1.0. A copy of the license can be found
# in the LICENSE file at the root of this repository.
#
# IMPORTANT: This code is part of FireANTs and its use, reproduction, or
... |
7003ec02c5f1a1214326686e24ef450a252517dba27e93efeadd5c09683059bc | Python | 934 | 41 | import sys
from .internals import *
import numpy as np
from typing import Union
# grab module
__pub = sys.modules['pubplot']
def bonferroni(p: Union[list[float], np.ndarray]) -> np.ndarray:
'''
'''
return np.clip(np.array(p) * len(p), 0, 1)
def bonferroni_holm(p: Union[list[float], np.ndarray]) -> n... |
05f3c25d4812359eea833c2e8b6c8f9f25e83eaa7e6594cc2e4496b3859118e1 | Python | 935 | 34 | import sys
import numpy as np
import matplotlib.pyplot as plt
def plot_transmembrane_potential(t, v):
plt.plot(t, v, label="Vm", c="black", linewidth=1.0)
plt.xlabel("t (ms)",fontsize=15)
plt.ylabel("V (mV)",fontsize=15)
plt.title("Action potential",fontsize=14)
plt.legend(loc=0,fontsize=14)
plt.show()
#plt.sav... |
adb45a27c8c06e7529cf79361eace3cfdaab9e31d5527546944c2a3a0fa27cce | Python | 935 | 16 | from testsetclass import TestsetClass
class IDISP(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['pxylene', 'F22f', 'undecan1', 'octane1', 'pc22', 'ant', 'F22l', 'undecan2', 'h2', 'octane2', 'F14l', 'antdimer', 'F14f']
self.exp_values = {'0': -9.15, '1': -60.28, '2': ... |
6216868c8d9e6b0ea41fa1aa2875c808f747536506e12d76a926d951a1ca8599 | Python | 936 | 35 | """
If we have trained a multi-gpu TF 1.x model and want to use it for
training or prediction on a single GPU, we need to convert it.
Usage: python multigpu_to_singlegpu.py path_to_model target_GPU
"""
from tensorflow.keras.models import load_model
import sys
import os
import dannce.engine.ops as ops
import dannce.en... |
bb281e5f650362e9391b3d38cf5e2f3e669c259b0ff38431fa0b6413dc140d74 | Python | 937 | 29 | # Copyright (c) OpenMMLab. All rights reserved.
def nlc_to_nchw(x, hw_shape):
"""Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor.
Args:
x (Tensor): The input tensor of shape [N, L, C] before convertion.
hw_shape (Sequence[int]): The height and width of output feature map.
Retur... |
e82967caf054774887ec81751362d25e420e4143579cf81aa08b112ee7888e8d | Python | 937 | 28 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... |
2558290d66c2e3fea25067bcbaf4a4a53442b4130826f765639b654c2b34009d | Python | 938 | 26 | import torch.nn as nn
class Net(nn.Module):
def __init__(self, input_size, hidden_sizes, dropout_rate, activation_fn):
super(Net, self).__init__()
layers = []
layers.append(nn.Linear(input_size, hidden_sizes[0]))
layers.append(activation_fn())
layers.append(nn.Dropout(dropou... |
eba972acb94abc04b3b54fb1fe7b34563f22fef7012a743ff839fbd0f7f6d142 | Python | 938 | 33 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
"""Test Dask auxiliary functions"""
from connectome_manipulator.processing import BatchInfo
def test_grouping():
"""Test grouping of batches for target payload"""
batches = [
... |
057a3caba17f244d472926139b4e248c09c42597a68fb739bce22563a4263706 | Python | 939 | 27 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['bundles.zip'])
tmp_dir = tempfile.Temp... |
9918e3c03408bc6f2b89234f2728e6aac8a19ad63c4176337f73ab3cd21bfefa | Python | 939 | 32 | import pandas as pd
import csv
import time
def process_posts(posts):
post = posts.replace("'","").strip("[").strip("]")
post = post.split(", ")
post = post[:20]
return post
def get_all_tweet():
df = pd.read_csv('./user_post.csv')
all_tweet_list = []
for index, row in df.iterrows():
... |
00ca3378edf7f507579127898acdce602089b9e739c7a9666b40ebdc5fbebef6 | Python | 940 | 28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.T... |
290aa32dc0c17c1114a925e92989a00985b8e752d6fc6bc19fa02bf2af8efd32 | Python | 940 | 28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tracking.zip'])
tmp_dir = tempfile.Tem... |
3e2f9b8e1f4b46a2bce7f610a34cc685201fceec116b3ad256786190da2d64be | Python | 940 | 29 | from PUMI.engine import FuncPipeline, NestedNode as Node
from PUMI.utils import concatenate
@FuncPipeline(inputspec_fields=['par1', 'par2', 'par3', 'par4', 'par5', 'par6', 'par7', 'par8', 'par9', 'par10'],
outputspec_fields=['concat_file'])
def concat(wf, fname='parfiles.txt', **kwargs):
"""
Con... |
57420b30bd2b0902cfca6253a72e7a7fe7ab0ea6cbb5a004570dd186684b6619 | Python | 940 | 27 | from datetime import timedelta
from kaapana.operators.KaapanaBaseOperator import KaapanaBaseOperator
from kaapana.blueprints.kaapana_global_variables import DEFAULT_REGISTRY, KAAPANA_BUILD_VERSION
class MyIvimFittingOperator(KaapanaBaseOperator):
def __init__(
self,
dag,
name="... |
17d303a4cabb66935f3939f402d7e27100ce2a3c21c157dccd2fd6ea50884345 | Python | 941 | 36 | import sys
import time
import getopt
from slice_dataframe import slice_dataframe
############################################################################
# section 15 : chopgems
#############################################################################
# usage
def gem_xy_usage():
print("""
Usage : GEM_toolk... |
5631d7c3e13b6d8d4f2a343c165d3e1e4f438d6c25338018c21b4b9d96fb8a97 | Python | 941 | 31 | # 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.
from fairseq.data import data_utils
from . import BaseWrapperDataset
class PadDataset(BaseWrapperDataset):
def __init__(self, dataset, ... |
ad665b2297e4142fd1dac20232eb4ebcd54dc31c6cba71637be62ea3bc4d0bbb | Python | 942 | 9 | """A sub-package that contains pipelines, which perform a set of tasks represented by a special :py:class:`~corelay.plugboard.Slot` type called
:py:class:`~corelay.pipeline.base.Task`. :py:class:`~corelay.pipeline.base.Task` slots can be filled with a special
:py:class:`~corelay.plugboard.Plug` type called :py:class:`~... |
c1936b19da2abfbc6febd334ace01ced3bfde1b5694e07d4e53a54b8ac1e6cea | Python | 942 | 30 | import json
import os
import os.path as osp
from argparse import ArgumentParser
from tqdm import tqdm
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--dataset_name', type=str)
args = parser.parse_args()
path = 'tmp/scores/{}'.format(args.dataset_name)
if not osp.exists(p... |
c555f11ec07dd9bcb3f68cb540396cc63fb077980969d88e2cb3c4625caf7030 | Python | 942 | 27 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['connectivity.zip'])
tmp_dir = tempfile... |
0cc0a96c19e3bdc2e441e265e355992dd81ead9770b31a46523f05f209ac4f92 | Python | 943 | 31 | # dataset settings
# We only use SUN RGB-D dataset for cross-dataset evaluation
dataset_type = 'SUNRGBDDataset'
data_root = 'data/sunrgbd/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='Mul... |
36367eaed1d78257f74250c7d17b36fefe2d503b1075f0175542d1dcd4eed370 | Python | 943 | 23 | from setuptools import build_meta as _orig
prepare_metadata_for_build_wheel = _orig.prepare_metadata_for_build_wheel
build_wheel = _orig.build_wheel
build_sdist = _orig.build_sdist
get_requires_for_build_sdist = _orig.get_requires_for_build_sdist
def get_requires_for_build_wheel(config_settings=None):
from packag... |
56816400187fa40241d92eb99eaa39bbab212b6405adb1406b958f23d65c5150 | Python | 943 | 23 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import timm
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
def get_model(name):
assert name == 'convnext_... |
727b1636a98c839e0c0443d72e46efa4c2d640873069c6dafe8e4b540835f7f2 | Python | 943 | 25 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Daniel Abele, Maximilian Betz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complian... |
cb3065121b1d82e2aaad0733e1025a17ffe07537e035d9bf7d7c836d9b0f1387 | Python | 943 | 36 | import pytest
from eir import train
from eir.setup import config
from eir.target_setup.target_label_setup import (
MergedTargetLabels,
gather_all_ids_from_output_configs,
set_up_all_targets_wrapper,
)
from eir.train_utils.utils import get_run_folder
@pytest.fixture()
def create_test_labels(
create_te... |
5fe0cb7bff1d31a5ed15f596f9359f085e26e312e8ae1d7f43005c26ffe495c0 | Python | 945 | 37 | """Clips a triangular mesh."""
import SVMTK as svm
from pathlib import Path
if __name__ == "__main__":
print("Start ",__file__)
outdir = Path("results")
outdir.mkdir(exist_ok=True)
surface = svm.Surface("../Data/lh-pial.stl")
# The surface must be without self-intersections.
surface.repair... |
80a620c322547acd674d7a62ede172eb8cfda74a35ad052946480c11e2dcea3a | Python | 945 | 35 | import numpy as np
import configparser
from pathlib import Path
import matplotlib.pyplot as plt
import os
from PIL import Image, ImageTk
# 3dv file name
data_name= r'614711-19203-1'
#Path of the 3dv file
data_path=Path(r'C:\Maziar Mirsalehi\3dv files')
# Create a directory to save images
output_direct... |
b52c7aa7213e0fc104578cf6a0890bc22883ff53643667abf2a216516b8139cc | Python | 945 | 34 | # File: /scripts/analysis/pca_clustering.py
"""Perform PCA and hierarchical clustering on processed EMG/EEG data.
Input:
../../data/processed/EMG_EEG_strength.csv
Output:
../../results/tables/pca_clustering_results.csv
Dependencies:
pandas, scikit‑learn (see docs/parameters.md)
"""
import pandas as pd
fr... |
cf0408d2f3b52555d37a3310c0deff02037b37e05f4da182b1ad7914f8482c92 | Python | 945 | 29 | from eir.models.input.omics.omics_models import (
al_omics_model_configs,
al_omics_model_types,
al_omics_models,
get_omics_model_class,
get_omics_model_init_kwargs,
)
from eir.setup.input_setup_modules.common import DataDimensions
def get_omics_model_from_model_config(
model_init_config: al_om... |
2e7168e2e5e2611e9465ead2571a296e0840152e3d05fe7fa828deb34acf87d6 | Python | 946 | 42 | import torch
from torch import nn
import math
import nltk
import pandas as pd
def accuracy(output, labels):
preds = output.max(1)[1].type_as(labels)
correct = preds.eq(labels).double()
correct = correct.sum()
return correct / len(labels)
def init_weights(m):
if type(m)==nn.Linear:
nn.init.... |
355bc5db997bf07deee4c7b6d0a03957dd6a5740747f1ba528db8e2775adb499 | Python | 946 | 26 | import pandas as pd
import numpy as np
from pathlib import Path
import json
#calculates the error for every column
def diff(sim_path, test_path):
sim_data = pd.read_csv(sim_path, sep = " ")
test_data = pd.read_csv(test_path, sep = " ")
result = {}
for key in sim_data:
if (sim_data[key].dtype == 'object'):
... |
5ab78f04d5e04b741f0d3666e7695e525806c20c93c64717e0651e67aafc4b50 | Python | 946 | 33 | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# ----------------------------------------------------------------------... |
663467738853f0833edf8b40ae20b6b6e2a57d83bce52fde4962b36c539f4565 | Python | 946 | 25 | #############################################################################
# Copyright (C) 2020-2025 MEmilio
#
# Authors: Henrik Zunker
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
e91305ea0ba36e88a8a2bc0ac129b9db3539c2808e1cae82316f1dd238773b09 | Python | 946 | 30 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: GM
@edited: CD
"""
import transforms.transforms as tfs
def load_transforms(args,random_chance=1):
# s determins random offset factor. If random_chance==0 (e.g. during testing), then we want no random offset.
if random_chance==0:
s=0
else:
... |
1a295f5587068c904c89701e2938a054358ef6a02c5c9af56d81e88056c72c1b | Python | 947 | 37 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
__version__ = '0.0.1'
#path_root = os.path.abspath(os.path.dirname(__file__))
#with open(os.path.join(path_root, "README.md")) as f:
# long_description = f.read()
# currently, the installation relies on the... |
4cb936eff61f6eb4287571cebc64cc207dfdf7d07e337f7dfcebcda9c6807741 | Python | 947 | 33 | import torch
def save(path, model, optimizer, **kwargs):
model_state = None
optimizer_state = None
if model is not None:
model_state = model.state_dict()
if optimizer is not None:
optimizer_state = optimizer.state_dict()
torch.save(
dict(model_state=model_state,
... |
b451ab0db377b3c272c859859c53e01ddaac095a541341c658c623810ba799ce | Python | 947 | 32 | import os
import logging
from datetime import datetime
def setup_logger(output_dir, name="harvest"):
"""Set up logger for the project."""
log_file = os.path.join(output_dir, f"{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
# Create handlers
c_handler = logging.StreamHandler()
f_handl... |
e29b069a82da09cc39d37b6b6d0e5f2c096a71472104e6299d3c3b1f0b86ff58 | Python | 947 | 28 | # Copyright (c) OpenMMLab. All rights reserved.
import logging
from mmcv.utils import get_logger
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is s... |
ac22e568c1556521a119ad7a124d215e9a1ecd89fb70f0eb8f2dc8cba51dbe41 | Python | 948 | 43 | import torch
from torch import nn
import math
import nltk
import pandas as pd
def accuracy(output, labels):
preds = output.max(1)[1].type_as(labels)
correct = preds.eq(labels).double()
correct = correct.sum()
return correct / len(labels)
def init_weights(m):
if type(m)==nn.Linear:
nn.init.... |
e3c276d47085415185a93e3b88145d9f341c2f0a4223f5db0ad284bf2a583910 | Python | 949 | 32 | #!/usr/bin/python3
import os
import numpy as np
from nibabel.testing import data_path
import nibabel as nib
import matplotlib.pyplot as plt
import sys
dist_group = sys.argv[1]
aseg = sys.argv[2]
target = sys.argv[3]
dist_filename = os.path.join(data_path, dist_group)
dist = nib.load(dist_filename)
dist_data = dist.... |
09ed4a70ed4ac992cd322118161ecfd240e6bd8ed161f83a16f6fd8ef63fcac0 | Python | 950 | 42 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
import sys
import subprocess
# local inputs
from ..io.get_filename import get_filename
def extract_main_component(file_in, file_out):
"""Extract main component.
This function removes unconnected parts found in a surface mesh and returns... |
1314f98b86a1318bfd5519047502a04a8cf5e7f2865d65e5d19367d49a24bc4b | Python | 950 | 27 | import unittest
from bidsphysio import bids_stub
class TestBidsPhysio(unittest.TestCase):
def test_bids_stub_single_extension(self):
pname = "/path/to/file/sub-01_task-rest_bold.nii"
expected_stub = "sub-01_task-rest"
self.assertEqual(bids_stub(pname), expected_stub)
def test_bids_stu... |
4ba3e7457c9472d78e83df70adb7403949ff35011f96dff7f973f01e222cd470 | Python | 950 | 31 | import os
from multiprocessing import Pool
from step2_defacing.step2_defacing import Defacing
from util.config_vars import config
def process_defacing(filepath: str) -> None:
"""Defaces the file from filepath with four defacing methods.
Args:
filepath (str): Filepath to be defaced.
"""
Defac... |
7c559ce6b5b0953f6cbe6f3f6e60a07af67251e4889071c46275ba7b861e5aec | Python | 950 | 44 | """# Hotdog or not app
Demo app to upload an image and classify if it's an hotdog or not.
"""
import pathlib
from enum import Enum
from magicgui import magicgui
class HotdogOptions(Enum):
"""All hotdog possibilities."""
Hotdog = 1
NotHotdog = 0
@magicgui(main_window=True, layout="form", call_button=... |
ba210a23c734ec8a7e6b72d5bc4633e5d10ae08ba2f0c39bbee29422e3ad3127 | Python | 950 | 30 | import torch
from utils import common_functions as c_f
from losses.large_margin_softmax_loss import LargeMarginSoftmaxLoss
class CosFaceLoss(LargeMarginSoftmaxLoss):
"""
Implementation of https://arxiv.org/pdf/1801.07698.pdf
"""
def __init__(self, *args, margin=0.35, scale=64, **kwargs):
sup... |
dcc6ffbeecc70d4a62edd714b828cec34c6db565d3af0c4c378068d8a3c0f9d7 | Python | 951 | 38 | #!/usr/bin/env python
"""
Find regions of first bed file that overlap regions in a second bed file. This
program performs a base-by-base intersection, so only runs of bases that are
covered in both of the inputs will be output.
usage: %prog bed_file_1 bed_file_2
"""
from bx.bitset_builders import binned_bitsets_from... |
e0a32bb45ce0d1e6e3301cfa895939882df886cf49d11123d85fecd3ee973583 | Python | 951 | 38 | import logging
from pathlib import Path
import numpy as np
import numpy.typing as npt
import scipy.io
from brainways.project.info_classes import MaskFileFormat
def export_mask(
data: npt.NDArray[np.int64], path: Path, file_format: MaskFileFormat
) -> None:
if not path.parent.exists():
path.parent.mk... |
edef8d9b59edd63e78c6615b7ef9b54bd77b93fdd5ba9c2391d1364597869367 | Python | 951 | 35 | import numpy as np
from impedancefitter.cpe import cpe_ct_model, cpe_ct_w_model
from impedancefitter.utils import get_equivalent_circuit_model
omega = 2.0 * np.pi * np.logspace(1, 8, num=20)
def test_cpe_RCT():
"""Test CPE in parallel with charge-transfer resistance."""
k = 1e-7
alpha = 0.9
Rct = 10... |
f110be60a546fdd80c18157eaf4c6a385218170f44c61e697eddb56c3940f962 | Python | 951 | 39 | """ Random utility functions """
from functools import wraps
# Things that get exposed from * import
__all__ = [
"constantly", "complement", "identity", "thread",
"execute_fn_with_args_and_or_kwargs"
]
def thread(arg, *fns):
if len(fns) > 0:
return thread(fns[0](arg), *fns[1:])
else:
... |
fcfd72fc774e5ba99b51b850e3e32df49f09f72e99c9315cf05bd68a6f2ddd80 | Python | 951 | 32 | from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text(encoding="utf-8")
setup(
name="prsedm",
version="1.3.0",
description=(
"PRSedm (Polygenic Risk Score Extension for Diabetes Mellit... |
017cc94330ec6a69ed4563a9ff67a53f2687d0a08648a07935f1f738ec3cb71b | Python | 952 | 30 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.T... |
0a99061ac34ca3799eea924667ebd017d7c564d4ff3a62a109d74e7d27aa8734 | Python | 953 | 32 | import subprocess
import sys
import yaml
script= 'enrichments/response_vs_spont.py'
script_ZETA = 'enrichments/responseZETA_vs_spont.py'
pathpath = 'PATHS/filepaths_carlen.yml'
with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile)
sys.path.append(pathdict['code']['workspace'])
from pfcmap.python impor... |
a08214398179dfe1d59de781b7759e9ecd060bfc0a56349e197086fa3ca48c67 | Python | 953 | 30 |
import pathlib
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
from helper_functions.get_dendritic_current import get_dendritic_current
from helper_functions import __file__
MODULE_BASE = pathlib.Path(__file__).parent.parent
if __name__ == '__main__':
data_folder = MODULE_BASE.joinpath... |
d317faa9319ca5d989a67e79c395a0c125cfb011d369e2ed8950ae2087309a26 | Python | 955 | 34 | import numpy as np
def get_session_info(session):
if session == 't17.2024.04.15':
block_nums = [5,6,7,8,9,10,11,12,13]
num_test_trials = 1
trials_to_remove = {}
elif session == 't17.2024.04.16':
block_nums = [9,10,11,12,13]
num_test_trials = 1
trials_to_remove... |
2ea2d0d45c667015c6e0aaab050080a4fbefbbcade431bfb4cc283da4a01ebac | Python | 956 | 28 |
from ._gui import App, APP_STATE
from PySide6 import QtWidgets
from bread.data import Segmentation, Microscopy, Lineage, SegmentationFile
def main():
app = QtWidgets.QApplication([])
window = App()
# APP_STATE.set_segmentation_data(Segmentation.from_h5('docs/source/examples/data/colony003_segmentation.h5'))
# ... |
56fdbbcf9cdaa9e0a53031ebdff1365a921c9c7563e5c8337df58d1c03e92763 | Python | 956 | 33 | """
This module is an example of a barebones writer plugin for napari.
It implements the Writer specification.
see: https://napari.org/stable/plugins/guides.html?#writers
Replace code below according to your needs.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Sequence... |
7e0cb558f661fe166de580dc7a6289f543204073cfed17508e8ba07687b7d52d | Python | 956 | 43 | import json
import asyncio
import grpc.aio
from thalamus import thalamus_pb2
from thalamus import thalamus_pb2_grpc
async def main():
async with grpc.aio.insecure_channel('localhost:50050') as channel:
await channel.channel_ready()
stub = thalamus_pb2_grpc.ThalamusStub(channel)
request = thalamus_pb2.... |
8813152255bcae2c4a7b8260f27239586efc1fd48b649f5dbc862c1b2749cbfa | Python | 957 | 30 | import pandas as pd
label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/botometer-feedback-2019/label.csv')
split = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/botometer-feedback-2019/split.csv')
user = pd.read_csv('./user_feature.csv')
user_list = list(user['id'])
del_list = []
bool_label = ... |
b0fcb5a6320d63ea4ae181c69f1d3ea74d2457231640196a0003ac3f70495493 | Python | 957 | 30 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from functools import cached_property
import torchvision.models
import cvat_sdk.auto_annotation as cvataa
class TorchvisionFunction:
_label_type = "any"
def __init__(self, model_name: str, weights_name: str = "DEFAULT", **kwargs) -> None... |
c2ca2263650cab61ef281281ee927ee2a198c827e17dffcbe06067d1dfb74787 | Python | 957 | 42 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
from nipype.interfaces.freesurfer.preprocess import MRIConvert
# local inputs
from ..io.get_filename import get_filename
def mgh2nii(file_in, path_output, out_type="nii"):
"""MGH2NII.
This function converts a volume file ... |
6b77d37f2ae86491755a8b54b6a35e4bcc24308c4f691adbbf0865ebb217f27f | Python | 958 | 23 | import os
from argparse import ArgumentParser
parser = ArgumentParser(description='Grab info for filter')
parser.add_argument('-p','--path',help='Path to out folder',required=True)
args = parser.parse_args()
if args.path.endswith('/'):
pathway=args.path[:-1]
files=os.listdir(args.path)
holdme=[]
with open('combine... |
43145289728e3d7ebdcb720db2838ffbdd959728db7774283a7aa7b9d4ee6027 | Python | 960 | 32 | from torch import nn
from torch.nn.modules.loss import _Loss
__all__ = ["JointLoss", "WeightedLoss"]
class WeightedLoss(_Loss):
"""Wrapper class around loss function that applies weighted with fixed factor.
This class helps to balance multiple losses if they have different scales
"""
def __init__(se... |
6c6fa7f92fad874e0a7d1c79d8dfae55c7c340a6c3362f35faf24d86573ecacb | Python | 960 | 23 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Agatha Schmidt, Henrik Zunker
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complian... |
76aacb76c1c58c32b84321fb924e90a49dda2c0ea92759f877d67f64e7358729 | Python | 960 | 29 | from ._ai_assist import AiAssistProposal
from ._ai_assist import AiAssistSession
from ._geometry import shape_to_xyxy_bbox
from ._osam_session import OsamSession
from ._shape_builders import MASK_REQUIRED_SHAPE_TYPES
from ._shape_builders import Detection
from ._shape_builders import assign_available_group_ids
from ._s... |
ae40f6ed63a621b351a2b34fa154165867a346ef7460657fc869f13766b5c3ff | Python | 960 | 33 | """Example script for comparing two groups.
"""
import numpy as np
from osl_dynamics.analysis import statistics
n_subjects_group1 = 24
n_subjects_group2 = 8
n_subjects = n_subjects_group1 + n_subjects_group2
n_features = 10
# Simulate data
group1 = np.random.randn(n_subjects_group1, n_features)
group2 = np.random.... |
34b2a3028714dd56a589ee57f25680b1025db3f12cf56d4f10cc3b774eb7090b | Python | 961 | 36 | #read_dataset_by_folder.py
#reads a dataset from a dataset folder
import mmsdk
import os
import argparse
from mmsdk import mmdatasdk
from os import listdir
from os.path import isfile, join
parser = argparse.ArgumentParser(description='Reading dataset by files')
parser.add_argument('path', metavar='path', type=str,
... |
4e6663a0dbc7fbf90ebd2f76c6c8755b706f5ebfe9f7c3be4f4a8955fcde5676 | Python | 961 | 31 | import unittest
from PUMI.engine import NestedWorkflow
from PUMI.engine import BidsPipeline
import os
from pipelines.rpn_signature import rpn, collect_predictions
# todo rename test_fst to rpn
class TestFsl(unittest.TestCase):
def test_fsl(self):
project_root = os.path.dirname(os.path.dirname(os.path.abs... |
36e99db3833dead7d3735e827bb78d23bfe6ec3195fd385b31a7a1c97a02d47b | Python | 962 | 44 | #!/usr/bin/env python
"""
Read a MAF and print counts and frequencies of all n-mers
(words composed on n consecutive alignment columns)
TODO: reconcile this and maf_mapping_word_frequency.py
usage: %prog n < maf_file
"""
import string
import sys
from bx.align import maf
def __main__():
motif_len = int(sys.ar... |
533983527d6d682bd69f42c95113675fb964f99c0593f699b61c73ad76f4cd97 | Python | 962 | 37 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
from cvat_sdk.api_client import apis, models
from cvat_sdk.core.proxies.model_proxy import (
ModelCreateMixin,
ModelDeleteMixin,
ModelListMixin,
ModelRetrieveMixin,
ModelUpdateMixin,
build_m... |
ad460f41ef5ef633bb42e80cd8b05bf59d249859564e4d1a41aff328d58781e7 | Python | 962 | 11 | from brainscore_vision import benchmark_registry
from .benchmark import _Islam2021Dimensionality
benchmark_registry['Islam2021-shape_v1_dimensionality'] = lambda: _Islam2021Dimensionality("V1", "shape")
benchmark_registry['Islam2021-texture_v1_dimensionality'] = lambda: _Islam2021Dimensionality("V1", "texture")
benchm... |
b4944b992a594246c88625303c523e7db3b62c0eb218a32190ca65e9bd49bf92 | Python | 962 | 37 | # Amino acid conversion mappings
AMINO_ACID_1TO3 = {
'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'C': 'CYS',
'Q': 'GLN', 'E': 'GLU', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE',
'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO',
'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL'
}
AMINO_ACI... |
2d0c09e83e44dcc84184b1b1bfc93ae34771fc9f32a935254e37012bf13ff28d | Python | 964 | 27 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 19:49:54 2024
@author: Artur Klepaczko
"""
import numpy as np
from radiomics import shape2D
import SimpleITK as sitk
def get_shape_feature_vector(image_2d: np.ndarray):
image = sitk.GetImageFromArray(image_2d)
mask = image_2d > 0
mask = sitk.GetImageFromAr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.