sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
631cad94da149f841f745b41257e86fe52450d44dbbb34e082b8c88e9e03e8dd | Python | 1,486 | 55 | """ Create 3D mesh with two conforming edge helixes inside """
import SVMTK as svm
import numpy as np
from pathlib import Path
if __name__ == "__main__":
print("Start ",__file__)
surf = svm.Surface();
outdir = Path("results")
outdir.mkdir(exist_ok=True)
cube = svm.Surface()
sphere = svm.... |
b7184e0b314cb38474d0beed9b9cc0c891fee75b92323d97b5295cf4c6a83ce7 | Python | 1,486 | 31 | from brainscore_vision.model_helpers.check_submission import check_models
import functools
import timm
import torch
from huggingface_hub import hf_hub_download
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_i... |
297d408410c9ca72c83bcbe2b0d546be4df551fc58db870eb383dc97f5afbffc | Python | 1,488 | 57 | """Generate the code reference pages."""
from pathlib import Path
import mkdocs_gen_files
nav = mkdocs_gen_files.Nav()
mod_symbol = ""
root = Path(__file__).parent.parent
src = root
for path in sorted(src.rglob("*.py")):
if path.relative_to(src).parts[0] != "nelpy":
continue
module_path = path.rel... |
c808ce81e0322a8c7f1d0affdf778adb370b5c40c57b7b656b3f84c6ff35ebc3 | Python | 1,488 | 54 | """Rename rest volumes"""
import os
import nibabel as nb
import numpy as np
import glob
import subprocess
ROOT = '/Users/sebastiandresbach/data/s1Anfunco/Nifti'
# Set subjects to work on
subs = ['sub-15', 'sub-16', 'sub-17', 'sub-18']
# subs = ['sub-14']
subs = ['sub-05', 'sub-06', 'sub-07', 'sub-09', 'sub-10', 'sub... |
03f1e3517924bb67b6a9a7ac12d262678da614e90526a32cff27982470fc9418 | Python | 1,489 | 40 | import argparse
import torch
from model import ProTact
from utils.data import get_data
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Predict the Contact map.")
parser.add_argument("--left_pdb", type=str, help="Left pdb file path.")
parser.add_argument("--right_pdb", type=str, h... |
0e8529719b6d147b526cfb67e1aaffd08b331ed1db461585e685ba8838b97117 | Python | 1,489 | 61 | #!/usr/bin/env python
"""
Chops alignments in a MAF file to piece of a specified length. A random set of
non overlapping chunks of exactly the specified chop length will be produced
usage: %prog [options] < maf > maf
-l, --length: Chop to exactly this length in columns (default 100)
"""
import random
import sys
fr... |
5db1e98a1e269dcf07ed1954ba20bd7e40da7762eba3258922e87915594c91c9 | Python | 1,489 | 50 | """DyNeMo regression spectra."""
import os
import pickle
import numpy as np
from osl_dynamics.data import Data
from osl_dynamics.inference import modes
from osl_dynamics.analysis import spectral
def get_data(name, rename):
os.system(f"osf -p by2tc fetch data/{name}.zip")
os.makedirs(rename, exist_ok=True)
... |
29223a35f2b06af59b2b8a7a84d962673c59092f9cbc2c1bfadca271e834d772 | Python | 1,490 | 65 | from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
from torch import nn
if TYPE_CHECKING:
from eir.setup.input_setup_modules.common import DataDimensions
@dataclass
class LinearModelConfig:
"""
:param fc_repr_dim:
Number of output nodes in the first and only hidden l... |
c3db1460335f9c8cea3e0668cdaa101b2c70f57dd03ac49c32239ff3a76d14cf | Python | 1,490 | 48 | from timeit import default_timer
import torch
import os
import glob
from pathlib import Path
from raw_data_handling import single_case_handling
def handle_npy_files(
folder_paths=['/mnt/research/compbiolab/Ehsan/DeepCardioSim/cardiac_models/electrophysio/data/npy/'],
chunk_size=6000):
CHUNK_SIZE =... |
fab765e039eb2803b0f897a82f9592a4d7e4c6f3c6bc619211d7bc35a05ebaf4 | Python | 1,490 | 51 | import logging, datetime
import logging.config
# Folder to store log file in
NEMS_LOG_ROOT = '/tmp/nems'
# Filename to save log file in
NEMS_LOG_FILENAME = datetime.datetime.now().strftime('NEMS %Y-%m-%d %H%M%S.log')
# Format for messages saved to file
NEMS_LOG_FILE_FORMAT = '[%(relativeCreated)d %(thread)d %(name)s... |
fee66e3c7c24fff94956c023f716bd2dbe6fc3547bf7769ec2cd1e3c6b6f3b1e | Python | 1,490 | 61 | """
nelpy minimal (min) API
=======================
``nelpy`` is a neuroelectrophysiology object model and data analysis suite
based on the python-vdmlab project (https://github.com/mvdm/vandermeerlab),
and inspired by the neuralensemble.org NEO project
(see http://neo.readthedocs.io/en/0.4.0/core.html).
"""
from .co... |
3ff922c9129360eb41089d958020fc2405d2eb5ac5a24bf05cefd5bc8f88d5e9 | Python | 1,491 | 43 | from collections.abc import Sequence
from typing import Any
from pydantic import BaseModel, create_model
from eir.setup.schemas import InputConfig, TabularInputDataConfig
def create_tabular_model(
name: str,
cat_columns: Sequence[str],
con_columns: Sequence[str],
) -> type[BaseModel]:
fields: dict[s... |
55c6b95c1efd72f124fe360e352ef4b7daf5c1f5e70e608da6b1679c520aacce | Python | 1,491 | 53 | """Plots radial summaries of each molecule's most important predicted properties."""
from pathlib import Path
import pandas as pd
from tqdm import tqdm
from admet_ai.plot import plot_radial_summary
def plot_radial_summaries(
data_path: Path,
save_dir: Path,
image_type: str = "pdf",
) -> None:
"""Pl... |
b50b0dbd5f7e9c470a15a2eec1b6cb8d66d7827671c5f8140dfc4e87e6fc5c68 | Python | 1,491 | 51 | from h5py import File
from os.path import isfile
__all__ = ['GenericH5']
class GenericH5:
def __init__(self, filenames, keys, cache=False):
"""Generic hdf5 dataset.
Basic interface for a set of hdf5 files.
Examples:
>>> import celldetection as cd
... from glob im... |
b860a7a687c959f599601b9c40caf04fdc8e4a911001a6521b4d7426fea4b352 | Python | 1,491 | 55 | """ impyute.dataset.corrupt """
import numpy as np
class Corruptor:
""" Adds missing values to a complete dataset.
Attributes
----------
data: np.ndarray
Matrix of values with no NaN's that you want to add NaN's to.
thr: float (optional)
The percentage of null values you want in y... |
2b06ed5560e658b5d51fd5aa5a198a19c6019ced41ec7894c48a014909eb7e05 | Python | 1,492 | 42 | # src/train/bootstrap_evaluate.py
from __future__ import annotations
import json, numpy as np, torch
from pathlib import Path
from src.config import C
from src.utils.data_utils import load_data
from src.utils.metrics import masked_rmse_mm
from src.models.regression_model import RegressionModel
N_BOOT = 1000
RES_DIR... |
79652fe3e758181637bace13ef3b85afe9646008cd0842caf0ed5fbdf75520da | Python | 1,492 | 50 | from __future__ import annotations
import asyncio
from collections.abc import Callable
from magicgui.widgets.protocols import BaseApplicationBackend
class ApplicationBackend(BaseApplicationBackend):
_timer_handle: asyncio.TimerHandle | None = None
def _mgui_get_backend_name(self):
return "ipynb"
... |
491be204cbee49ab8d7cf5c08c41eda887e1836eeb9dfb1407dad1908f9a95d9 | Python | 1,493 | 46 | from scipy.stats.qmc import Sobol, scale
import numpy as np
import pandas as pd
import os
# Set number of dimensions and samples
dim = 25
seednum = 42
n_samples = 65536 # Initial samples 2^16
output_file = "sobol_samples_Hab6_local.csv"
# Extract mean and sd of weights in the desired order
means = np.array([0.0556... |
7626c28fe6a6ebbecf7cc0912a3d73c09393c75dcd58a26b70974d7bf88ad3ee | Python | 1,493 | 46 | from scipy.stats.qmc import Sobol, scale
import numpy as np
import pandas as pd
import os
# Set number of dimensions and samples
dim = 25
seednum = 42
n_samples = 65536 # Initial samples 2^16
output_file = "sobol_samples_Rew1_local.csv"
# Extract mean and sd of weights in the desired order
means = np.array([0.0804... |
ccf2d67ded49b688b6c288a9aae102d8e296ba221f55cc77f71a11a94a735041 | Python | 1,493 | 46 | from scipy.stats.qmc import Sobol, scale
import numpy as np
import pandas as pd
import os
# Set number of dimensions and samples
dim = 25
seednum = 42
n_samples = 65536 # Initial samples 2^16
output_file = "sobol_samples_Rew6_local.csv"
# Extract mean and sd of weights in the desired order
means = np.array([0.0146... |
f8ed4aaf59c88c25c9dc9dddd652a7c0ec88db779ccf4eee7a8ed3320a3c79d2 | Python | 1,493 | 45 | #!/usr/bin/env python
"""
HAL module for emulating a laser.
Hazen 04/17
"""
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.amplitudeModule as amplitudeModule
class NoneLaserFunctionality(amplitudeModule.AmplitudeFunctionality):
def __init__(self, **kw... |
6b17726a5ce6aa5768aea698a5b7b65ea87eb3edc0cefbb986a78e3f79bf410d | Python | 1,495 | 41 | import numpy as np
import glob
import pickle
import csv
######################## How to add a new parameter to pickle files #########
directory='C:/Users/vlewitus/Documents/Python Scripts/Pickle/'
pattern = directory+'*.pickle'
outfnames = glob.glob(pattern)
E2_value_file=directory+'E2values.csv'
file_E2_dict={}
with ... |
b4a91c0182f5b49af5412e08ddd5d3c56607c731fcf5059c1ec2c51775c16f22 | Python | 1,495 | 69 | #!/usr/bin/env python3
# Use this script for convenience when making tutorials
# for readthedocs/sphinx.
#
# Run on a tutorial python file like this
#
# ./mk-include tutorial.py prefix
#
# the script will extract all comments from the
# tutorial script starting with
#
# # (N)
#
# where N is whole number. For each such... |
24c407b61cb32943dc3510e4a0b6f7bd26859a9ef7ea59ef9f728246dba3627a | Python | 1,496 | 59 | import typing
import asyncio
import logging
import argparse
from .motion_capture import XsensWidget
from ..config import *
from ..qt import *
UNHANDLED_EXCEPTION: typing.List[Exception] = []
def exception_handler(loop: asyncio.AbstractEventLoop, context: typing.Mapping[str, typing.Any]) -> None:
"""
Logs unhand... |
66050d6020ad21821a36555feb866313c196977cd793df9dbc190026eccb4a83 | Python | 1,496 | 60 | # -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import pdb
class SharedDropout(nn.Module):
def __init__(self, p=0.5, batch_first=True):
super(SharedDropout, self).__init__()
self.p = p
self.batch_first = batch_first
def extra_repr(self):
s = f"p={self.p}"
... |
73e366d2a407ffe18b646883681d65c4506efab4845da6e0d8fb4bd7b421134a | Python | 1,497 | 39 | import numpy as np
import pandas as pd
from typing import Tuple
from . import ELA_Network_functions
#-----------------------------------------------------------------------------------
# ②calc if SS for all states
#-----------------------------------------------------------------------------------
#-----------------... |
0b854bb5741578e290185c3ad5ca5d92881085b03a86bd370d49cf9e21464585 | Python | 1,498 | 39 | import logging
from brainscore_core.supported_data_standards.brainio.assemblies import NeuronRecordingAssembly
from brainscore_vision import data_registry, stimulus_set_registry, load_stimulus_set
from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3, load_stimulus_set_from_s3
_logger... |
a31f73e3b2b20158b23b1a8c9d86c47658df0e6a4c47256289155dce5b2e0e13 | Python | 1,499 | 42 | from .exception_hook import ExceptionHook
from typing import Iterator, List, TypeVar, Iterable, Dict
import random
from itertools import zip_longest, islice
A = TypeVar('A')
def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]:
"""
Takes an iterator and batches the invididual instanc... |
54525b5b0bc347c53f5d363892f085347069c6ede68d260d234824cb426b0b2d | Python | 1,500 | 41 | import torch
from kornia.color import rgb_to_grayscale
from kornia.feature import HardNet, LAFDescriptor, laf_from_center_scale_ori
from .sift import SIFT
class DoGHardNet(SIFT):
required_data_keys = ["image"]
def __init__(self, **conf):
super().__init__(**conf)
self.laf_desc = LAFDescriptor... |
38959cd4f16c60d49d9661a4bdbc6b9909243ed53a5a4f120286cea6a969b1f7 | Python | 1,501 | 54 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from typing import Protocol
from uuid import uuid4
from django.conf import settings
from django.utils.timezone import now
class WithUUID(Protocol):
uuid: str
class RequestTrackingMiddleware:
def __init__(self, get_response):
self... |
916f8eef93ad694e4845bed8195e1eb2099cfa976b5a680792ec28dcb46e9995 | Python | 1,501 | 41 | #!/usr/bin/env python
"""
Emulated filter wheel.
Hazen 04/14
"""
import storm_control.sc_hardware.baseClasses.illuminationHardware as illuminationHardware
class NoneFilterWheel(illuminationHardware.AmplitudeModulation):
"""
Filter wheel emulator.
"""
def __init__(self, parameters = None, parent = No... |
e2082dd9570a356ff57b08f699729640cf984b820f2996af5051796fd7f2e1b4 | Python | 1,502 | 46 | from copy import deepcopy
from pathlib import Path
from eir.experiment_io.input_object_io_modules.input_io_utils import (
load_input_config_from_yaml,
)
from eir.experiment_io.io_utils import load_dataclass
from eir.setup.input_setup_modules.setup_omics import (
ComputedOmicsInputInfo,
DataDimensions,
... |
00208cbb83c85fb9dccd9568b1d95b826c9d1c9990edef296eb306911715b783 | Python | 1,503 | 34 | import torch
import torch.nn as nn
import s3prl.hub as hub
from transformers import Wav2Vec2Model, HubertModel
class PretrainedSpeechModels_hf(nn.Module): # using pretrained speech models from huggingface
def __init__(self, pretrained_model, pretrained_name, final_feat_dim):
super().__init__()
... |
77581b8217e25c9ace51f7356fccd1a07ed2962d0f74aae2491f1001750565f1 | Python | 1,503 | 44 | # -*- coding: utf-8 -*-
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from typing import Type
class MLPBlock(nn.Module):
def _... |
9272f9c741d3437d052543aaba68fa49e32a75bc480d0c363369408a2abbeb5e | Python | 1,503 | 49 | # Source: https://github.com/neuraloperator/neuraloperator/blob/main/neuralop/layers/normalization_layers.py
import torch
import torch.nn as nn
class AdaIN(nn.Module):
def __init__(self, embed_dim, in_channels, mlp=None, eps=1e-5):
super().__init__()
self.in_channels = in_channels
self.em... |
5d37d2955500815c0734eba2566c0736aabc2c73c758f0802e2b3cfe0f01e50d | Python | 1,504 | 38 | # ==================================================================================================
# Author: Lucas Berg @bergolho
# Date: 10/11/2023
# Script to combine the ALG and FIBERS file into a single one.
# --------------------------------------------------------------------------------------------------
# Dep... |
2614daf90a7ca6ada096c28b367828b758966a414a3b18db15481d26727b5d7c | Python | 1,505 | 57 | # %%
from data_loading import load_dataset_graph
import torch
from deepcardio import Trainer
from deepcardio.losses import LpLoss, H1Loss
dltrain, dltest, data_processor = load_dataset_graph(
folder_path='./data', train_batch_sizes=[10], test_batch_sizes=[10])
device = 'cuda' if torch.cuda.is_available() else 'cp... |
960bae21adfbda5cb8763209e930dcd7e2a908b8af557a58bf09413e431223d4 | Python | 1,505 | 41 | import os
import tarfile
from os.path import join
import glob
import argparse
versions = 9 # 3lights*3albedos
intrinsics = 3 # rendering; albedo; normals
parser = argparse.ArgumentParser()
parser.add_argument('--set', type=str, default='train', help='should add to train, val or test datasets')
parser.add_argumen... |
b30ad76d0f2cf3035f2ec20599c1697ba3c41b8aad0f42084cec6030c3c483bf | Python | 1,505 | 48 | import json
from pathlib import Path
import numpy as np
from eir.experiment_io.input_object_io_modules.input_io_utils import (
load_input_config_from_yaml,
)
from eir.experiment_io.io_utils import load_dataclass
from eir.setup.input_setup_modules.setup_array import (
ArrayNormalizationStats,
ComputedArray... |
21e9205da4bcd2d8e4addca6d9298d851331e5de54c610641eead80a7db18d13 | Python | 1,506 | 39 | import torch_geometric
import torch
from torch_geometric.nn import GCNConv, FastRGCNConv
class GNN_classifier(torch.nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim=256, activate="relu"):
super().__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self... |
4c97d42e128c441a09a4646f9d7abb940f5036208b9f0c85591ab64730997892 | Python | 1,507 | 57 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as nb
def mask_ana(t1, mask, background_bright=False):
"""Mask ana.
This function masked an image with a corresponding binary mask by
multiplication. The masked volume is saved in the... |
802a1c8bf5fddee4820d183b0fad3f7651b281f53f5e3b9a8384c0d1c99cd5fd | Python | 1,507 | 46 | #!/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=['mrds.zip'])
tmp_dir = tempfile.Tempora... |
58ffb4c7c933b0e18945c0b213007662d3fc53901927b3b057b6ae5fd5574df3 | Python | 1,508 | 44 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors:
#
# 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 License.
# You may... |
b59e1b8380834a767f06f2ce1c937edba7887b89aea4f24512cada428329603a | Python | 1,508 | 41 | """Opt-in integration coverage for real MACE-MP inference."""
import json
import math
import os
from pathlib import Path
import pytest
from chemgraph.schemas.ase_input import ASEInputSchema
from chemgraph.tools.ase_tools import run_ase
@pytest.mark.skipif(
os.environ.get("CHEMGRAPH_TEST_MACE") != "1",
reas... |
025f98744ec44e91d60b9502fa788ad281945900f8a7c4528bd3e93419eebfd0 | Python | 1,509 | 59 | import cv2
import numpy as np
def calculate_l0_norm(image1_path, image2_path):
# 读取图像
image1 = cv2.imread(image1_path)
image2 = cv2.imread(image2_path)
# 计算L0范数
l0_norm = np.count_nonzero(image1 != image2)
return l0_norm
def calculate_l2_norm(image1_path, image2_path):
# 读取图像
image1 ... |
05dc2dede3a84e6aaab192661d3bb3f394913adfb7ca616b042afa37ea33ef65 | Python | 1,509 | 49 | # Copyright (c) OpenMMLab. All rights reserved.
import collections
from ..builder import PIPELINES
from mmcv.utils import build_from_cfg
@PIPELINES.register_module()
class Compose(object):
"""Compose multiple transforms sequentially.
Args:
transforms (Sequence[dict | callable]): Sequence of transform... |
54e0d750bae9d447dfcf7f9e055fa50067cd3280b31f804bfb963941c345b8cf | Python | 1,509 | 45 | """Randomly samples molecules from a dataset."""
from pathlib import Path
import pandas as pd
from tap import tapify
def sample_molecules(
data_path: Path,
save_path: Path,
num_molecules: int,
max_smiles_length: int | None = None,
smiles_column: str = "smiles",
random_state: int = 0,
) -> N... |
ac7459de691617fb6a1e2f6d0c2d48e7a6d118a17d1db9eef6c68a06643db6b5 | Python | 1,509 | 54 | from typing import Optional
import numpy as np
__all__ = ['image_time_per_trial',
'moving_average']
def image_time_per_trial(image_time: np.ndarray,
lap_time: np.ndarray,
signal: np.ndarray,
act_mask: Optional[np.ndarray] = None) ... |
eefc2a9a89aa4ca95915ac6d17b283c3f40e44d7f8840cbd75545d087775ba99 | Python | 1,509 | 42 | """Collection of plotting utilities for NEMS objects.
Contents
--------
fitter.py : Plot error vs fit iteration, prediction vs target, etc.
layers.py : Layer-specific visualizations, like `stp_input_output`.
model.py : Whole-model plots, like `plot_model`.
tools.py : Helper functions for formatting m... |
fec9b7e993a0963b003a6bff86be5e2e31aab69c0b86cbecc45ffa83901425b9 | Python | 1,509 | 41 | # 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
import sys
from pathlib import Path
# Insert sys.path modification and mock code here
sys.path.insert(0, str(Path(__... |
5b9c4c590570770cb18c0d85385417e0d3d9e86063f306c49d2cc03736464641 | Python | 1,510 | 35 | import numpy as np
import torch
from torch.utils.data import Sampler
class BalancedBatchSampler(Sampler):
def __init__(self, original_dataset, subset_dataset):
super(BalancedBatchSampler, self).__init__(data_source=subset_dataset)
self.original_dataset = original_dataset
self.subset_datase... |
a2c252128ad11e381eb761a554a2be42f5515f8cbf758a1afab613739b3a37bb | Python | 1,510 | 27 | from losses.angular_loss import AngularLoss
from losses.arcface_loss import ArcFaceLoss
from losses.base_metric_loss_function import BaseMetricLossFunction, MultipleLosses
from losses.circle_loss import CircleLoss
from losses.contrastive_loss import ContrastiveLoss
from losses.cosface_loss import CosFaceLoss
from losse... |
880127730cdb8bfb434aee80dc606b538d1733082076de8f35e83ccfa2316900 | Python | 1,511 | 48 | """Example code for plotting power maps from the state/mode covariances inferred
on time-delay embedded training data.
"""
import os
import numpy as np
from osl_dynamics.analysis import power, post_hoc
def get_data(name, output_dir):
if os.path.exists(output_dir):
print(f"{output_dir} already downloaded... |
95fcea86520f37b82d4cdca582c1195810cb77a75b384935ce168a5964697caf | Python | 1,511 | 44 | """Utility functions for ADMET-AI."""
from pathlib import Path
import pandas as pd
def load_and_preprocess_data(data_path: Path, smiles_column: str = "smiles") -> pd.DataFrame:
"""Preprocess a dataset of molecules by removing missing SMILES and setting the SMILES as the index.
:param data_path: Path to a C... |
2b0944a736b3baf1b6880a66b09c2320636795e3a9104220df71e2227f072aae | Python | 1,512 | 34 | from distutils.util import convert_path
from pkg_resources import parse_requirements
from setuptools import find_packages, setup
requirements_filepath = convert_path("requirements.txt")
with open(requirements_filepath, "r") as f:
requirements = [str(requirement) for requirement in parse_requirements(f)]
setup(
... |
65d16b1aa8ff96f6c436d0dca7f048cd44ce9d12945f46ff860690b56130bc61 | Python | 1,512 | 52 | #!/usr/bin/env python
"""
Read a maf file from stdin and write out a new maf with only blocks having all of
the passed in species, after dropping any other species and removing columns
containing only gaps. By default this will attempt to fuse together any blocks
which are adjacent after the unwanted species have been... |
7287fb880de4d15af02360c85935800fcf4d7c10364d7dd6d71f9ac63bd87e81 | Python | 1,512 | 40 | """Download the shared example dataset used by the MATLAB and Python test pipelines.
Mirrors ``downloadExampleData.m`` (Dropbox source only).
"""
from __future__ import annotations
import urllib.request
from pathlib import Path
from typing import Callable
DROPBOX_LINKS = {
"exampleData.csv": "https://www.dropbo... |
860adb8c8dddb2393d468f682791d3d24938aa64ecc4624e8a30d62929412589 | Python | 1,512 | 38 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS
from ultralytics.utils import ASSETS, WEIGHTS_DIR, checks
# Shared test constants for model, config, data source, and environment info
MODEL = WEIGHTS_DIR / "path with spaces" / "yolo26n.pt" #... |
b41b1130ea0a097cc4ebec2ffea7efc7e1860fca4f0b36eaca8613688d207ec0 | Python | 1,514 | 48 | #!/usr/bin/python
#
## @file
#
# Load the appropriate application icon.
#
# Hazen 02/13
#
from PyQt5 import QtCore, QtGui
## QAppIcon
#
# HAL icon class.
#
class QAppIcon(QtGui.QIcon):
## __init__
#
# Load the HAL-9000.ico file.
#
def __init__(self):
QtGui.QIcon.__in... |
34da36b5d240d0aee0123ee1fad890ed3bf6e99f4166bd294c3b0c0593491540 | Python | 1,515 | 52 | """Single-agent MCP example over HTTP.
Connects to ChemGraph's built-in MCP server running on a remote ALCF
compute node via HTTP (streamable_http transport with port forwarding).
Usage
-----
# 1. Start the MCP server on a compute node (see README.md)
# 2. Set up SSH port forwarding to the compute node
# ... |
b71c539f50c805e9012e05d1fa56004ece5da56914acc7f078600eeee17360c9 | Python | 1,515 | 44 | """This file shows how to use YASA in combination with Visbrain.
"""
import numpy as np
from visbrain.gui import Sleep # type: ignore reportMissingImports
from yasa import spindles_detect, sw_detect
# Load the data and hypnogram
data = np.load("data_full_6hrs_100Hz_Cz+Fz+Pz.npz").get("data")
ch_names = ["Cz", "Fz", ... |
8522a5ea194da5cdc1eaac0c883f95f02b0171afc12d6154ac8ba3a2ac692b4f | Python | 1,516 | 45 | import numpy as np
from tqdm import tqdm
from rsatoolbox.util.searchlight import get_volume_searchlight
import rootutils
rootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
from src.utils import batched_pearsonr
def evaluate_similarity_sl(map_1, map_2, mask, radius, threshold):
# Implemen... |
877585231d06f55f7d1feda1b3771496de75c21eb21b9a6504a5c49754c5eb14 | Python | 1,516 | 42 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from http import HTTPStatus
from unittest.mock import MagicMock, patch
from django.test import TestCase
from cvat.apps.engine.models import Project
from cvat.apps.iam.models import User
from cvat.apps.webhooks.models import WebhookDelivery, Webhook... |
219a08f3b304f2202d92f184c8e03c2f9eafb4dbc193ae50889a61db33f85658 | Python | 1,517 | 51 | """Plot a comparison of the speed of ADMET-AI version for large-scale ADMET prediction."""
from pathlib import Path
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
FIGSIZE = (14, 10)
matplotlib.rcParams["font.size"] = 28
plt.rcParams["font.weight"] = "bold"
plt.rcParams["a... |
486d95acfce843e363153e1384cfd7e5cddd2c5011c0880a01b9fd06acca0d3b | Python | 1,517 | 50 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 15 18:06:30 2022
@author: tianj
"""
import torch
import torch.autograd as autograd
# MSE Loss
def MSELoss(yhat,y):
#pdb.set_trace()
return torch.sum((yhat-y)**2)/(2*y.shape[0])
# Potential cortical region loss function
def MSELossCortical(yhat,y... |
cd99b8584b143a5e651e740684b8a38e2cbde7943628b9531340dd2496ccea60 | Python | 1,517 | 55 | """Ollama endpoint (own-client protocol).
Ollama keeps its existing client (``load_ollama_model``), which validates the
requested model against the curated catalog. Local models need no API key.
"""
from __future__ import annotations
from chemgraph.models.endpoints.base import (
CredentialPolicy,
EndpointSpe... |
91de6703fd00121be1cc02397058f1e356fe4fcb2d66c22d12a24238b561ece3 | Python | 1,518 | 38 | #!/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=['lesions.zip'])
tmp_dir = tempfile.Temp... |
875edb391f82851b4a499705f1fff8bd0967a4ed727cf69f2d4e9474083ec2de | Python | 1,520 | 46 | import os
import sys
import traceback
from django.conf import settings
from django.db import migrations
from cvat.apps.engine.log import get_migration_logger
def delete_previews(apps, schema_editor):
migration_name = os.path.splitext(os.path.basename(__file__))[0]
with get_migration_logger(migration_name) a... |
e09d80d7236bc9942735734b97cb96aabccb2b960a5953821b1795f6c185ce36 | Python | 1,520 | 40 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class PatchMixConLoss(nn.Module):
def __init__(self, temperature=0.06):
super().__init__()
self.temperature = temperature
def forward(self, projection1, projection2, labels_a, labels_b, lam, index, args):
... |
5a330bae64674386a611349a7bb7e505914d05227f63c500c08b1bfb086857cb | Python | 1,521 | 49 | # coding: utf-8
"""Find the path to LightGBM dynamic library files."""
import ctypes
from os import environ
from pathlib import Path
from platform import system
from typing import List
__all__: List[str] = []
def _find_lib_path() -> List[str]:
"""Find the path to LightGBM library files.
Returns
-------... |
6fd28092ebe5e5502b666a49e9b3bda5dfe387541d520a78a1c62b04bc81d7dc | Python | 1,521 | 40 | from __future__ import annotations
from typing import cast
from labelme._label_flags import compile_label_flags
def test_compile_label_flags_none_is_empty() -> None:
assert compile_label_flags(label_flags=None) == {}
def test_compile_label_flags_keeps_the_flag_keys_of_a_valid_pattern() -> None:
compiled =... |
8e8ee8a712647cc6491e85e4c6185afa535c1a1f648533891a12c9d57dd0981e | Python | 1,522 | 43 | #!/usr/bin/env python3
import os
import subprocess
from pathlib import Path
from glob import glob
from tqdm import tqdm
WORKFLOW_DIR = os.environ["WORKFLOW_DIR"]
OPERATOR_IN_DIR = os.environ.get("OPERATOR_IN_DIR", "get_input")
OPERATOR_OUT_DIR = os.environ.get("OPERATOR_OUT_DIR", "dicom_to_nifti")
BATCH_DIR = os.path... |
f3bbd8f8dde42278b39688f1edaf5b458f34886a61c48861feba7991f5306906 | Python | 1,522 | 54 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
import datetime
def get_thickness_fsurf(path, sub):
"""Get thickness fsurf.
This function calculates the cortical thickness using freesurfer. Old files
are moved to the freesurfer trash folder tagged with a date string as
suffix. ... |
4c270e8f0bc5dcad80c23c14ad3bba0fc929c4adbffdde642446d6b08e08de8b | Python | 1,523 | 70 | """Dual estimation.
In this script we estimate subject-specific means and covariances
given the group-level model.
"""
#%% Run ID and output directories
import os
from sys import argv
# We get the run ID from the command line arguments
if len(argv) != 2:
print("Please pass a run id, e.g. python 4_dual_estimatio... |
ed0ecdb62ee92a66c9c271db6de570be2178a909721ca0aadf74dbd5106b5d01 | Python | 1,523 | 67 | import asyncio
import logging
LOGGER = logging.getLogger(__name__)
PROCESSES = set()
def cleanup():
if not PROCESSES:
return
LOGGER.warn('%d subprocesses still running', len(PROCESSES))
for process in set(PROCESSES):
process.kill()
class ProcessWrapper:
def __init__(self, underlying: asyncio.subproc... |
5a25592f85457c6b1ee2bfc89d52d2b5f2cd23d3fbb68bc582617ee7b829f27d | Python | 1,525 | 25 | from testsetclass import TestsetClass
class TAUT15(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['3b', '9b', '6a', '3c', '3d', '5a', '10b', '4b', '1a', '7b', '8a', '2a', '6b', '9a', '5c', '3a', '10a', '5b', '6d', '6c', '1b', '4a', '2b', '8b', '7a']
self.exp_values = ... |
c084880b0cfae3d6daf26f9ff6c4d676a95ec61dc86048939d0fe82bfe0b7108 | Python | 1,525 | 52 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import django_rq
from django.conf import settings
from rq.job import Job
from rq_scheduler import Scheduler
from cvat.apps.redis_handler.redis_migrations import BaseMigration
from cvat.apps.webhooks.models import Webhook
_SEND_WEBHOOK_FUNC_NAME = "... |
0e2336de2954623979ee994b08107ba79be67521c3d60df6591d46cd0e0f371e | Python | 1,526 | 53 | """
Upsampling registered statistical maps to match segmentation and layering
"""
import os
import glob
import subprocess
# Set data path
ROOT = '/Users/sebastiandresbach/data/s1Anfunco/Nifti'
# Set subjects to work on
subs = ['sub-12']
for sub in subs:
runs = sorted(glob.glob(f'{ROOT}/{sub}/ses-0*/func/{sub}... |
3db5134cc9b5e8933f76f6889ba085534cde0f0e8478ca2fb05711d573352302 | Python | 1,526 | 48 | """
artifact_identification - EEG Artifact Detection with DLCNN and Rule-Based Methods
=====================================================================================
This package implements end-to-end EEG artifact detection using a Deep
Lightweight 1D Convolutional Neural Network (DLCNN) together with literatur... |
68c62a2dd0bafe464c2d27af29e8beeacc981765047d9ba22f33efade4c28301 | Python | 1,526 | 50 | from .base import WaveformBenchmarkDataset
class ISC_EHB_DepthPhases(WaveformBenchmarkDataset):
"""
Dataset of depth phase picks from the
`ISC-EHB bulletin <http://www.isc.ac.uk/isc-ehb/>`_.
"""
def __init__(self, **kwargs):
citation = (
"Münchmeyer, J., Saul, J. & Tilmann, F.... |
e745a576dc8f40123fd5510a43ca6ba54c2adfa3d8c10538da970122690a7bb4 | Python | 1,526 | 32 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# # Time series plot for theory_train and experiment_train
experiment_train = np.load('fig4b_experiment.npy')
theory_train = np.load('fig4g_theory.npy')
indices_num_val_sum = np.arange(0, len(theory_train), 1)
time_da... |
0a12a572ca82554f090794e05b1e0336ad3a7f1619eca8a9614c1f3021664227 | Python | 1,527 | 37 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'cross_section_plot.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_xSection(object):
def setupUi(self, xSection):
xS... |
8233c3ee89a1ae11cf3c2370c4a306425dd2ba687601c307e273ad536e68300a | Python | 1,527 | 52 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 16:42:29 2020
@author: Yoshi
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
def best_angle_calculator(log_frequencies,polar_coordinates):
# Disable Spyder plot window
plt.ioff()
# Empty list for storing... |
9659f425d09ca79714586d9630e2121d6c998b3db75b68b3a01c7679ab2fce46 | Python | 1,527 | 54 | # -*- coding: utf-8 -*-
# external inputs
import numpy as np
from scipy.stats import gamma
def hrf_spm(TR, p=(6, 16, 1, 1, 6, 0, 32)):
"""An implementation of spm_hrf.m from the SPM distribution. The code is
taken from [1]_.
Parameters
----------
TR : float
Repetition time in s.
p : ... |
a030d52790c3d18b4a8f817c82b85402d48fb9491b922fe2b7d4e516a386f771 | Python | 1,527 | 43 | import os
import numpy as np
import pandas as pd
import scanpy as sc
os.chdir("/data/wuqinhua/phase/covid19/datasets")
samples = ["NS0A", "NS0B","NS1A", "NS1B","TP6A", "TP6B","TP7A", "TP7B","TP8B", "TP9B","TS2A", "TS2B","TS3A", "TS3B","TS4A", "TS4B","TS5A", "TS5B"]
all_adatas = []
for sample in samples:
adata = s... |
9e0c1bcbb06959c5c2360c572f527b5808c60ec2bb22448339531fbccf67e20c | Python | 1,528 | 43 | import numpy as np
from fairodds_auc import fair_odds_auc, equalized_odds_gap
def test_zero_geo_recovers_auc():
# Perfect separation and each group has both classes -> EO = 0
y_true = np.array([0, 1, 0, 1])
y_score = np.array([0.1, 0.9, 0.2, 0.8])
race = np.array(["A", "B", "B", "A"]) # each race has one 0 and ... |
c208e6e4128077e5dba31392398e3ceee16d309004c9deab2f9c7bb485357e34 | Python | 1,528 | 52 | from __future__ import annotations
import pytest
from PySide6 import QtGui
from PySide6 import QtWidgets
from pytestqt.qtbot import QtBot
from labelme._utils import new_icon
from labelme._widgets._empty_state import EmptyStateWidget
def _ignore_click() -> None:
return
@pytest.fixture()
def empty_state(*, qtbo... |
dc5fbc8491e098508bce19d21f51680396d84c067a7bb3b2b3740ca0b0491d23 | Python | 1,528 | 48 | """
Adopted from AllenNLP:
https://github.com/allenai/allennlp/tree/v0.6.1/allennlp/common
Functions and exceptions for checking that
AllenNLP and its models are configured correctly.
"""
from torch import cuda
from utils import logging
logger = logging.init_logger() # pylint: disable=invalid-name
class Conf... |
8a732f82a6acf562a11277438c32c8b78510616ef6c489c899cb4d961eccaf66 | Python | 1,530 | 45 | import os, shutil, tarfile
from os.path import join
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--imgdir', type=str, default='dataset', help='path to dataset')
args = parser.parse_args()
dist_arch_train = tarfile.open(join(args.imgdir, 'train.tar'), mode='w') ## create arc... |
b8a2b0ed2bd7ed871e56158d91dfb77bddb26fde35fa82aaa7842f105a2d852c | Python | 1,530 | 41 | import numpy as np
import scipy as sp
import SimpleITK as sitk
import skimage.registration
class Registration:
def __init__(self):
pass
def TranslationRegITK(fixed_image, moving_image):
# Convert to ITK object
if isinstance(fixed_image, np.ndarray):
fixed_image = sitk.GetImageFro... |
c2a56860abbaff33ffe874ef35808506f8fd3b8c4142996d6cff8861899602d8 | Python | 1,530 | 42 | import numpy as np
import nibabel as nib
from utilities.data_simulation.GenerateData import GenerateData
from WrapImage.nifti_wrapper import save_nifti_file
def save_bval_bvec(filename, values):
if filename.endswith('.bval'):
# Convert list to a space-separated string for bval
values_string = ' '.... |
b99276bd5c6a91e8e71bb2c5db8294074a9c5844f8032aa038ea0873316a77ad | Python | 1,531 | 44 | """
Shared loss functions for EEG artifact detection models.
Authors: Evans Nyanney, Parthasarathy D Thirumala, Shyam Visweswaran, Zhaohui Geng
Year: 2025
License: MIT
"""
import tensorflow as tf
def focal_loss_with_class_weights(alpha=0.25, gamma=2.0, class_weights=None):
"""
Focal loss with optional class... |
9a134a0bb7502f2d8e8a5cbe2ebfb7a2a23869bd18434f8bb16503d5916cd11d | Python | 1,532 | 40 | from qtpy.QtWidgets import QHBoxLayout, QPushButton, QVBoxLayout, QWidget
class CellViewerWidget(QWidget):
def __init__(self, controller):
super().__init__()
self.controller = controller
self.set_2d_mode_button = QPushButton("2D View Mode")
self.set_2d_mode_button.setCheckable(Tr... |
fa364ecc29b2bd3868014ad5915e703496021cd9367d861edb12cf7273c3435e | Python | 1,532 | 55 | import subprocess
import tempfile
from pathlib import Path
from typing import Optional
from dti.utils import create_mask, mri_number_of_frames
from gmri2fem.utils import with_suffix
def eddy_correct(
dti,
topup_b0_mean,
acq_params,
output: Path,
multiband_factor: int = 1,
nthreads: int = 1,
... |
81da1d44f33727d2018253800c48f91f320eb2cde48bb8940631fbbb34effc44 | Python | 1,533 | 73 | # -*- coding: utf-8 -*-
"""
Generate 1D ODC
This script creates a one-dimensional ODC pattern.
"""
# external inputs
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import correlate
from numpy.fft import fft
# local inputs
from fmri_tools.simulation.odc import odc_1d
# 1D parameters
N_sim = 10... |
a8a76ec247ea54cfb4729a7b57888e0eb1bfc0ca512997e18717dc2ad0df558a | Python | 1,533 | 42 | import json
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.TemporaryDirectory()
def test_help_op... |
f40e9dad818a7554aa037064e43d66e4b02a0eaa30122eda64971ecb948988df | Python | 1,533 | 46 | from setuptools import find_packages, setup
def read(path):
with open(path, 'r') as f:
return f.read()
long_description = read('README.md')
setup(
name='kb_python',
version='0.30.2',
url='https://github.com/pachterlab/kb_python',
author='Kyung Hoi (Joseph) Min',
author_email='phoeni... |
27e97944ac8f6d8b7ac0063a800688defe0b9290d0e1b53cf7e3261a860e54cf | Python | 1,534 | 51 | import Functional_Fusion.reliability as rel
import Functional_Fusion.atlas_map as am
from Functional_Fusion.dataset import DataSetMDTB
from OptimalBattery.global_config import data_dir,save_dir
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import gamma
# define atlas and di... |
4e42dd6fda237167ba4babce6b6def04dc0e74783b657da059145d76eb693769 | Python | 1,534 | 48 | """
Adopted from AllenNLP:
https://github.com/allenai/allennlp/tree/v0.6.1/allennlp/common
Functions and exceptions for checking that
AllenNLP and its models are configured correctly.
"""
from torch import cuda
from flair.utils import logging
logger = logging.init_logger() # pylint: disable=invalid-name
clas... |
12682a2b03e3f39e234ea6b507f863fafeddff070b4e6f1cc7266f0dd319840d | Python | 1,535 | 56 | from __future__ import annotations
import uuid
import time
from typing import Any
REQUIRED_MESSAGE_KEYS = {
'message_id',
'sender',
'recipient',
'content',
}
def validate_message(message: dict[str, Any]) -> None:
"""Validate the generic Academy message envelope."""
if missing := REQUIRED_ME... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.