sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
a67fa091782cba6662d97d50cc1552c038275cce6d0cb1240e0dbe4d972fa984 | Python | 1,213 | 36 | from PyQt5.QtWidgets import QGraphicsView
from PyQt5 import QtCore
class QGraphicsViewMT(QGraphicsView):
mouseMoved = QtCore.pyqtSignal()
mouseEntered = QtCore.pyqtSignal()
mouseLeft = QtCore.pyqtSignal()
mouseClicked = QtCore.pyqtSignal()
"""
Custom QGraphicsView with mouse tracking and enter/... |
b4b8dc65b139f6c2cfef3fdd2e8215855a30bd7f97e3fa0eb4f5cef6e3fd6514 | Python | 1,213 | 40 |
# interference model
import numpy as np
import Utility
n = 45
angle_shift = 0
grid_scale = 10
# store the 2d grid patterns in each of 45-by-45 locations
grid_pattern_array = np.zeros((n, n, n, n))
for loc_x in list(range(0, n)):
for loc_y in list(range(0, n)):
orientation = 0 + angle_shift
wave1... |
33c5d13131f8e7526ee2400556bff8a0e6c0e393977e3d72f410387d04f5d389 | Python | 1,214 | 53 | # -*- coding: utf-8 -*-
import os.path
def add_filename_suffix(filename, suffix):
"""
This function adds a suffix to the filename, keeping the extension.
For example, if filename is test.nii.gz and suffix is "new",
the returned name will be test_new.nii.gz
Parameters
----------
filename:... |
a0f4449b4fe2068a6b6d35afa0a13f18adb212b4cfadcaf0de76aa2ebb564755 | Python | 1,214 | 39 | import setuptools as st
with open("README.md", "r") as fh:
long_description = fh.read()
st.setup(
name="pyfocus",
version="0.7",
author="Nicholas Mancuso, Ruth Johnson",
author_email="nicholas.mancuso@med.usc.com, ruthjohnson@ucla.com",
description="Fine-map transcriptome-wide association stu... |
c4afa3a94111e2776f4258f5e4e9fa75f35c85527fd813742a28a1bd83a8e694 | Python | 1,214 | 32 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
'''
CUDA核函数实现SOMA计算,使用python setup.py install来进行编译安装
注意:
1、要正确设置环境变量CUDA_HOME,在本机中为:/usr/local/cuda,在Pytorch的setuptool源码中会根据CUDA_HOME去寻找编译工具nvcc
2、要正确设置CUDA相关的编译工具路径以及要链接的CUDA库的路径,涉及两个环境变量PATH和LD_LIBRARY_PATH
3、如果需要支持half,... |
d42bf3000c4281d6b02b7f2849e6b0b5474f252f1866e8296b7125831aaaa147 | Python | 1,214 | 32 | import torch
from .base_reducer import BaseReducer
from .mean_reducer import MeanReducer
class MultipleReducers(BaseReducer):
def __init__(self, reducers, default_reducer=None, **kwargs):
super().__init__(**kwargs)
self.reducers = torch.nn.ModuleDict(reducers)
self.default_reducer = (
... |
fd910f1c71b31028610e638e382d79237df4259bf24a2f33535acec66f0e5a63 | Python | 1,214 | 38 | import os.path as osp
import numpy as np
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from pygod.models import DONE
from torch_geometric.utils import to_dense_adj
from torch_geometric.data import Data
import scipy.sparse
from pygod.utils import gen_attribute_outliers, gen_structure_out... |
7b182e3b5c19ad0c20434c855492b74b148801de6896279cf76c71d400963ff7 | Python | 1,215 | 51 | from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional, Tuple
from brainways.utils.dataclasses import dataclass_eq
@dataclass(frozen=True)
class BrainwaysParams:
atlas: Optional[AtlasRegistrationParams] = None
affine: Optional[AffineTransform2DParams] = None
... |
b5a1bf3087c7727395f6a6365e44ea7e618612a41c9cba3a5e05621fab16ac35 | Python | 1,215 | 49 | # -*- coding: utf-8 -*-
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as nb
def get_gaussian(input_file, path_output, mu=0, sigma=1):
"""Get gaussian.
Creates a NIfTI volume with Gaussian noise as voxel intensities and saves a
nifti volume with matrix s... |
c23c054aaadbb3f9011c593801192be7f11f9d3a442c5bfa18693e931ccbd911 | Python | 1,215 | 33 | #!/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... |
dd9e666071006d3bb490860c692be77579b08c6392bd70bc9e4f986907309029 | Python | 1,215 | 47 | """# Jupyter notebooks and magicgui
This example shows magicgui widgets embedded in a jupyter notebook.
The key function here is `use_app("ipynb")`.
You can also [get this example at github](https://github.com/pyapp-kit/magicgui/blob/main/docs/examples/notebooks/magicgui_jupyter.ipynb).
```python hl_lines="4-5"
imp... |
f830e390cc20e3d0852d51fbe75cc09e6acfdc8799906f9de73a6c852342b18b | Python | 1,215 | 37 | import numpy as np
from neuralib.spikes import CASCADE_MODEL_TYPE, cascade_predict
from neuralib.suite2p import get_neuron_signal, Suite2PResult
from neuralib.util.verbose import print_save, print_load
__all__ = [
'DEFAULT_CASCADE_MODEL',
'get_neuron_cascade_spks'
]
DEFAULT_CASCADE_MODEL: CASCADE_MODEL_TYPE ... |
09042a84e69fd2303e77c1276f5f1ff7920018672eca3e460526b0110d88f700 | Python | 1,216 | 48 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to normalize gradients bvecs.
"""
import argparse
import logging
import numpy as np
from scilpy.io.utils import (assert_inputs_exist, assert_outputs_exist,
add_overwrite_arg, add_verbose_arg)
from scilpy.gradients.bvec_bval_tools ... |
b61a49fbdc3d18398201bd46a347439698f3bd09f2252d6a7153f2d8c7c0a4d3 | Python | 1,216 | 36 | """
PyTorch Hub models
Examples:
import torch
model = torch.hub.load('FZJ-INM1-BDA/celldetection', 'ginoro')
"""
import celldetection as cd
from torch.nn import Module
from torch import device as _device
from typing import Optional, Union
def ginoro(
pretrained: bool = True,
pretrained_stric... |
cc9a472af353f11eb02a199b729c5e48cfad00584272074a7d642cafd8a13a23 | Python | 1,216 | 53 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# In[12]:
import unitvelo as utv
import anndata
import scvelo as scv
import numpy as np
import os
import argparse
import time
TLS_path = '/VeloVAE/data/processed/TLS.h5ad'
TLS = anndata.read_h5ad(TLS_path)
velo_config = utv.config.Configuration()
velo_config.R2_ADJ... |
e79d16aeb12266de86c9d06c9e762c848e170dd5b93d03c8a05bb6cb7e8f540a | Python | 1,216 | 42 | from copy import deepcopy
from unittest.mock import MagicMock
import numpy as np
from eir.data_load.data_preparation_modules import prepare_bytes
from eir.setup.schemas import ByteInputDataConfig
def test_prepare_bytes_data():
test_input = np.array(list(range(100)))
test_input_copy = deepcopy(test_input)
... |
282e92a370c0a74112d044b8dcfd5c2802438da239b3eea99b3691b5fb8056bc | Python | 1,217 | 36 | # -*- coding: utf-8 -*-
import numpy as np
from scilpy.gradients.gen_gradient_sampling import (generate_gradient_sampling,
energy_comparison)
def test_generate_gradient_sampling():
# Note. On a normal computer:
# Time for 1 shell, 6 samples: 0:00:00.01348... |
5df6dab39ad9cf540e5c6a7e243c831dfdae3ca6aff539b864e1acdc0544450e | Python | 1,217 | 20 | from testsetclass import TestsetClass
class BHDIV10(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['ed9', 'ed7', 'ed1', 'ed6', 'ed8', 'ts5', 'ts2', 'ts3', 'ts4', 'ed3', 'ed4', 'ed5', 'ed2', 'ed10', 'ts8', 'ts1', 'ts6', 'ts7', 'ts9', 'ts10']
self.exp_values = {'0': 25.... |
1540fde8b242a56546481b88fc08b1fe9bb551b5f116fd55e9b3ec6d91de57e0 | Python | 1,218 | 47 | import requests
import obspy
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
### Start running the model first:
### FLASK_ENV=development FLASK_APP=app.py flask run
def read_data(mseed):
data = []
mseed = mseed.sort()
for c in ["E", "N", "Z"]:
data.append(mseed.sel... |
348ed79335488977900c232284f340751ca377a05da563faba1a79226a322984 | Python | 1,218 | 38 | import numpy as np
from napari_debcr._widget import (
DeBCRQWidget
)
# capsys is a pytest fixture that captures stdout and stderr output streams
def test_debcr_q_widget(make_napari_viewer, capsys):
# make viewer and add an image layer using our fixture
viewer = make_napari_viewer()
viewer.add_image(np... |
7527fae2b30a447b9fa3be9383a6010d14347242d62a654acdc6468a24bade65 | Python | 1,218 | 31 | # Copyright 2024 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
ab418503db5a3e492cf28c28003240300752d39dcc70dab0aa48c37a1ae4cae1 | Python | 1,218 | 41 | import math, re, time, subprocess, datetime
def sec2time(s):
days = math.floor(s/86400)
s -= days*86400
hours = math.floor(s/3600)
s -= hours*3600
minutes = math.ceil(s/60)
return f'{days}-{hours:02d}:{minutes:02d}'
def time2sec(t):
x = re.split('-|:', t)
x = [ int(k) for k in x ]
... |
d8dad3fcb802dfcfe63a4343ba99a8c06243a6ce27a6611c59734ef73f963bda | Python | 1,218 | 38 | import os
import mrcfile
import pandas as pd
import shutil
from scipy.ndimage import distance_transform_edt
import numpy as np
directory = "/gpfs/group/grotjahn/bbarad/Final_Dataset/TgGSK/"
datasets = ["GE1", "GE2", "GF1", "GF2", "GT1", "GT2", "GT3","GT4","GT5"]
# datasets = ["GE1"]
postfix = ".AVV_rh12.csv"
for data... |
66d07ca5d7f8cb4d2744c831da90074517be155f2e9a38d7f49d0d06d4f85300 | Python | 1,219 | 34 | #!/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=['others.zip', 'tractometry.zip'])
tmp_d... |
7d7eea92f7ec62e81a577d6857744aafaf23bd06feecd029d231ca6da5732090 | Python | 1,219 | 36 | import os.path
import pytest
from mmsplice.vcf_dataloader import SplicingVCFDataloader
from mmsplice import MMSplice, predict_all_table
from mmsplice.utils import read_vep, max_varEff
from scipy.stats import pearsonr
vep_output = 'variant_effect_output.txt'
@pytest.mark.skipif(not os.path.isfile(vep_output),
... |
e193a6c90173937d0a4d9158dd844f055da25f426ae8664ed73960e2cdce5b45 | Python | 1,219 | 41 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.mo... |
4398d3ad01b1484911c2da25fd129e7bd93c93eb734d6755b4e44084a4a63485 | Python | 1,220 | 40 | from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from mobius.mobius_model import p_veridical
def main():
p = argparse.ArgumentParser()
p.add_argument('--out', default='outputs', help='Output folder')
p.add_argument('--alpha',... |
c176aab0aef13f741656a28130d89108e1941e5c7c13818bb39b1e4a8c3f4826 | Python | 1,220 | 45 | import zipfile
from pathlib import Path
import gdown
from aislib.misc_utils import ensure_path_exists
def download_google_drive_file(
url: str, output_path: Path, overwrite: bool = False
) -> None:
if output_path.exists() and not overwrite:
return
if "/d/" in url:
url = _parse_google_url... |
58b3bc17d2b7e9f812c17a4875a8502c0268abaef8a7444fdf34f93c9d7aabd2 | Python | 1,221 | 39 | # Copyright (C) 2023 Intel Corporation
#
# SPDX-License-Identifier: MIT
import requests
import requests.utils
from django.conf import settings
from rest_framework import status
from rest_framework.exceptions import APIException
from cvat import __version__
_CVAT_USER_AGENT = f"CVAT/{__version__} {requests.utils.defa... |
5bb0ce57685a0ebf4094789ad21328105364972bb4bd18f732f7370068f2d214 | Python | 1,221 | 41 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.mo... |
5eba5b03bba7cec96bba12edf4c69d117bedc1eada0f0f3ac93224e230e2b944 | Python | 1,221 | 39 | import os
import numpy as np
import pandas as pd
def load_all_data(folder_path: str):
X_list, y_list = [], []
for filename in os.listdir(folder_path):
if filename.endswith(".xlsx") or filename.endswith(".xls"):
radius = float(os.path.splitext(filename)[0])
df = pd.rea... |
990244f86b26f1348b5ced090a71464d950074ef178e5e492994af240591b24f | Python | 1,221 | 45 | """Utility for recursively converting objects to JSON-serialisable
Python types."""
import math
from typing import Any
import numpy as np
def json_serialize(obj: Any) -> Any:
"""Recursively converts obj to a JSON-serialisable Python type.
numpy scalars become int or float, numpy arrays become lists, and
... |
d7187ac897a1a81288fb0f022458cb552c66af36cca113e53c5fe6d942c18c97 | Python | 1,221 | 35 | import numpy as np
import pytest
from brainscore_vision import load_dataset
@pytest.mark.private_access
def test_existence():
assert load_dataset('Seibert2019') is not None
@pytest.mark.private_access
class TestSeibert:
def test_dims(self):
assembly = load_dataset('Seibert2019')
# neuroid: ... |
3b803f8c294422fbeef19e0165e02a9a0050c9e32c0fc539759f683ef952ab55 | Python | 1,222 | 34 | # Source: https://github.com/neuraloperator/neuraloperator/blob/main/neuralop/layers/embeddings.py
import torch
from torch import nn
class SinusoidalEmbedding2D(nn.Module):
def __init__(self, num_channels, max_positions=None, endpoint=False):
"""SinusoidalEmbedding2D applies a 2d sinusoidal positional enc... |
873a2ead2bbcb10f8f8743c5ff1adab784606d41e411e080bae719edc1aee1bd | Python | 1,222 | 38 | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='DeepInteract',
version='1.1.0',
description='A geometric deep learning pipeline for predicting protein interface contacts.',
author='Alex Morehead',
author_email='acmwhb@umsystem.edu',
license='GNU Public License, ... |
ed1e2be04de226624c8b04ae94d45293ba1a571892094f62b285374ab79b3ca5 | Python | 1,222 | 44 | # -*- coding: utf-8 -*-
"""
Relief plot on surface mesh
In the following script, a contrast is plotted as a relief on a corresponding
surface mesh. The contrast data is filtered by a sigmoid function.
"""
# external inputs
import numpy as np
import nibabel as nb
from nibabel.freesurfer.io import read_geometry
from n... |
67156788c4fdd5f517d1ff1064198ec8844b67ddad53bc50cff91bd4c1362724 | Python | 1,223 | 41 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.mo... |
bd23d9aea15eaa72bbdc915a97dc25a3803706fbaa0bc172bde6ebb814992e4b | Python | 1,223 | 34 | import subprocess
import sys
import yaml
script_calc = 'enrichments/calc_statsdict.py'
script_plot = 'enrichments/plot_enrichments.py'
script_calc_ctrl = 'enrichments/calcctrlEnrichments_area_layer_recid.py'
script_plot_ctrl = 'enrichments/plot_ctrlEnrichments.py'
script_polarization = 'enrichments/enrichment_polariza... |
d108730b450e0b0afe799c1239a8dc7fe7b12d42170359d6bf0b236b1c4c943c | Python | 1,223 | 33 | import os
import json
import torch
os.environ['CUDA_VISIBLE_DEVICE'] = '1'
import pandas as pd
import numpy as np
from tqdm import tqdm
from pathlib import Path
from transformers import *
pretrained_weights = 't5-small'
tokenizer = T5Tokenizer.from_pretrained(pretrained_weights)
model = T5EncoderModel.from_pretrained(... |
1376869c0383a1c106f208a7c0b45b07aa0ca303eeaca473cad84a9b3da73c70 | Python | 1,224 | 41 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, auc, roc_curve
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.mo... |
39adcaca4a3db846779f192398b8d111fa04944f1470a1209cfa26fb181cff8d | Python | 1,224 | 39 | _base_ = [
'RepLKNet_upernet.py',
'../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_80k.py'
]
# model settings
model = dict(
decode_head=dict(
num_classes=19,
align_corners=True),
auxiliary_head=dict(
num_classes=19,
... |
494a752da0b4422c465d4c907a9828f27bbeacdd6e86f4838e3d9d4d9a39126a | Python | 1,224 | 48 | import typing
import pathlib
import platform
DIR = pathlib.Path(__file__).resolve().parent
try:
#New resource import
import importlib
import importlib.resources
def get_path(arg1: typing.Any, arg2: str = None) -> str:
if arg2 is None:
return str(DIR / arg1)
try:
with importlib.resources.p... |
59d4d1f57855adf7c58a796a59126c9c716d3f0fad1e24e261dc62815625ef52 | Python | 1,224 | 40 | # -*- coding: utf-8 -*-
"""
Flash T2s fitting
The script applies the nighres t2s fitting module to a data set.
"""
# python standard library inputs
import os
# external inputs
import nibabel as nb
from nighres.intensity import flash_t2s_fitting
# local inputs
from fmri_tools.io.get_filename import get_filename
# ... |
73f0d9c2d1dd4bc7c9e8c1988982631db2af7b8155a4a36c578ec9d082c6c66d | Python | 1,225 | 33 | """
Fitting A/B test framework for ProjectionProcessor.
Goal
----
Compare alternative non-linear fitting backends (lmfit/leastsq, lmfit/TRF,
scipy, VarPro, iminuit, ...) against the current baseline on *real* fit
inputs captured during normal MuscleX runs.
Key components
--------------
- ``adapters.base`` : ``FitCas... |
e086597b24d38ac2394e7c0e7709dced8cc62c80ea6a8ddef4909fc4c00665b4 | Python | 1,225 | 61 | """
Utility functions for models
"""
import copy
from torch import nn
def extract_name_kwargs(obj):
"""
"""
if isinstance(obj, dict):
obj = copy.copy(obj)
name = obj.pop('name')
kwargs = obj
else:
name = obj
kwargs = {}
return (name, kwargs)
def ge... |
6cc22c09d08c3bc3a9c13f9c3d0b66e3110df54ffbe5295914ecfc5b90e39d6a | Python | 1,226 | 33 | import os
import json
import torch
os.environ['CUDA_VISIBLE_DEVICE'] = '0'
import pandas as pd
import numpy as np
from tqdm import tqdm
from pathlib import Path
from transformers import *
pretrained_weights = 't5-small'
tokenizer = T5Tokenizer.from_pretrained(pretrained_weights)
model = T5EncoderModel.from_pretrained(... |
75fe85e4d604aab7366f6355da7aded1a3bc69ee5bb3a3f977a85f7b54748823 | Python | 1,226 | 35 | """# Nested progress bars
Example using nested progress bars in magicgui.
"""
import random
from time import sleep
from magicgui import magicgui
from magicgui.tqdm import tqdm, trange
# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in
# interactive use in IPython), then they fal... |
c67ec9c062043efebd17ae276c5c2dacf423538d60464ffd7c4e52504405f407 | Python | 1,226 | 45 | from .stack_corr import infer, correct, warp
__all__ = ["infer", "correct", "warp"]
def main():
"""Main entry point for the stack-corr CLI."""
import click
from .logger import setup_logger, set_log_level
@click.group()
@click.option(
"--log-level",
type=click.Choice(
... |
3c294b52fdd67d51427ea6d7e00a83c035d9bf613b3b3db93a1b4e9a46722bb6 | Python | 1,227 | 36 | import os, sys, gzip
from pathlib import Path
from typing import List, Callable, Dict, Union, Iterator, Optional, Any
from contextlib import contextmanager
@contextmanager
def read_maybe_gzip(filepath:Union[str,Path]):
if isinstance(filepath, Path): filepath = str(filepath)
is_gzip = False
with open(filepa... |
63fc89b7ed3eaf8414dd4ce7091889efb13a9cb447e7e4493a46ff38fe9ef0f9 | Python | 1,227 | 46 | # -*- coding: utf-8 -*-
"""Test filename utilities."""
import pytest
from fmri_tools.io.filename import get_filename, natsort
@pytest.fixture
def filenames():
"""Test data for get_filename."""
return [
("/home/test/test_data.nii", ".nii"),
("/home/test/test_data.nii.gz", ".nii.gz"),
... |
75f72283ae2d2155ba225c7585c2d4cd023c31d73f9d4e34dee2e208ec5b2b33 | Python | 1,227 | 27 | """Step 5: statistical comparison, feature structure, and decoding.
The MATLAB pipeline's last analysis stage (``doStats``, ``featureCorrelation``,
``doLDA``, ``doClassification``, called from ``MEApipeline.m``) asks four
questions of a finished run's metric tables:
1. **Comparison** — does a metric differ by age or ... |
dce4c84986f06c9228486915417af6e6d85f9670a29810677a09f835af1387a4 | Python | 1,227 | 40 | # Copyright (c) DP Technology.
# 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.
"""isort:skip_file"""
import importlib
import os
from unicore import registry
from unicore.optim.unicore_optim... |
df01c13879a6d2f57981782f93aa15abfd80df979cb175b665b2615603589e87 | Python | 1,227 | 42 | """Deprecated compatibility shim for ALCF model loading.
Construction now lives in ``chemgraph.models.endpoints.alcf`` behind the shared
OpenAI-compatible protocol builder. Prefer
``chemgraph.models.loader.load_chat_model``.
The ``_normalize_alcf_model`` helper is re-exported for one release.
"""
from __future__ imp... |
29a6891ab5111ea7ab30eb89989958bec66373f4f578d465c4982e98cb6360e9 | Python | 1,228 | 28 | from brainscore_vision import model_registry
from brainscore_vision.model_helpers.brain_transformation import ModelCommitment
try:
from .model import get_bibtex, get_layers, get_model, get_model_list
except ImportError:
import importlib.util
from pathlib import Path
_MODEL_PATH = Path(__file__).resolv... |
6d73e4e6cdb29591afbaaf270ff3d5ba4f15b321d2cd542ea2680195d40b7c36 | Python | 1,228 | 38 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import json
from pathlib import Path
import torch
from ultralytics.utils import LOGGER, TORCH_VERSION
def torch2torchscript(
model: torch.nn.Module,
im: torch.Tensor,
output_file: Path | str,
met... |
799c71427234e6632a8751a76976a10560e2f13a975e76c86fc6da4d800cab90 | Python | 1,228 | 46 |
import h5py
import os
import yaml
import pandas
import numpy as np
tablepath = 'config/datatables/allrecs_allprobes.xlsx'
sheet = 'lick_selection'
df = pandas.read_excel(tablepath, sheet_name=sheet)
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
allowed_bool = ~df['usable_gen'].isin(['-','?'])
... |
83fe5964fd6f476d34f7eda3fcb86f857d6132262ce32a67a35d7a18167bace1 | Python | 1,228 | 38 | """Coordinated deletion across readable sessions and graph checkpoints."""
from __future__ import annotations
from chemgraph.memory.store import SessionStore
def delete_durable_session(
store: SessionStore,
session_id: str,
) -> bool:
"""Delete checkpoints first, then transactionally remove readable rec... |
14951ca58f01dccc27bb3621027c39f1bac8aa9440c1d3881789d8c5be877677 | Python | 1,229 | 32 | import setuptools
import os
with open("README.md", "r") as fh:
long_description = fh.read()
here = os.path.abspath(os.path.dirname(__file__))
about = {}
print(here)
with open(os.path.join(here, 'impedancefitter', '__version__.py'), mode='r', encoding='utf-8') as f:
exec(f.read(), about)
setuptools.setup(
... |
1dc44712fb4507b8792e797ea3aeb9c36ac7fb9fdac8dea85e33c9a614ea1cdd | Python | 1,229 | 36 | """
Dual-ResNet3D: Dual-modality fusion ResNet3D model
Uses two ResNet3D-18 branches (T2 and FLAIR) for late fusion
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet3d import ResNet3D18
class DualResNet3D(nn.Module):
"""
Dual-ResNet3D:
- Dual input (T2W and FLAIR)
- T... |
3d7a0de982c33d1e3b14e01c90a477695a4d53619f517b855262386cc139ae3b | Python | 1,229 | 38 | # Copyright (c) DP Technology.
# 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 unicore.data import data_utils
from . import BaseWrapperDataset
class PadDataset(BaseWrapperDataset):
... |
940c235d32bd2f20fd318f85f07a2a1334ad403250b3b9bd0105dd80e5291264 | Python | 1,229 | 55 | """Get inferred parameters.
"""
from sys import argv
if len(argv) != 3:
print("Please pass the number of states and run id, e.g. python 3_get_inf_params.py 8 1")
exit()
n_states = int(argv[1])
run = int(argv[2])
#%% Import packages
print("Importing packages")
import os
import pickle
import numpy as np
from... |
ff2a3c8ebdc43737072d82bc7357907da2d2704e396d8a53b85f796640a45671 | Python | 1,229 | 37 | #!/usr/bin/python
#########################################
# Author: Yunjiang Qiu <serein927@gmail.com>
# File: merge_map.py
# Create Date: 2015-10-09 12:27:31
#########################################
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='')
parser.add_argumen... |
e8e1b2028def5e1ca0d4c13cea11bf2acd4d530039dff31c3f27d9943bddb4e5 | Python | 1,230 | 30 | """ChemEmbed — metabolite identification from MS/MS spectra via molecular embeddings.
A convolutional network predicts a 300-dimensional mol2vec embedding from a
spectrum, which is then matched by cosine similarity against a reference
database of pre-computed embeddings.
The trained models and the reference database ... |
f28d2f22a0122eeadca71804a8a68dfbff68d5020617ad066e0c69d3727fabd1 | Python | 1,230 | 60 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# In[12]:
import anndata
import numpy as np
from deepvelo.utils import velocity, velocity_confidence, latent_time, update_dict
from deepvelo.utils.preprocess import autoset_coeff_s
from deepvelo.utils.plot import statplot, compare_plot
from deepvelo import train, Consta... |
fd706c4f300ef1cc58a717965688f7be80bc20f8621e5c0a828c3d0a8ce1986d | Python | 1,230 | 31 |
# model.py - ResNet-50 구현 예시
from brainscore_vision.model_helpers.check_submission import check_models
import functools
import torchvision.models
from brainscore_vision.model_helpers.activations.pytorch import PytorchWrapper
from brainscore_vision.model_helpers.activations.pytorch import load_preprocess_images
def ge... |
0256599ebbc7dd90cc54accafc3e0ae322b3a448b50f3ac06037a1a923f507b6 | Python | 1,231 | 33 | from .features_generators import get_available_features_generators, get_features_generator, \
morgan_binary_features_generator, morgan_counts_features_generator, rdkit_2d_features_generator, \
rdkit_2d_normalized_features_generator, register_features_generator
from .featurization import atom_features, bond_feat... |
a9c8721becd8b7f44732923019529ed1432c46564bfc0d44160d217a0a4d3efb | Python | 1,231 | 53 | from pathlib import Path
import nibabel as nib
def get_full_case_id(cid):
try:
cid = int(cid)
case_id = "case_{:05d}".format(cid)
except ValueError:
case_id = cid
return case_id
def get_case_path(data_path,cid):
# Resolve location where data should be living
# data_path... |
02e445ac2e768cb32703d13f7571ca0d1fa67e9274202e694eb030fdc27c736f | Python | 1,232 | 27 | import sys, os
#sys.path.insert(0, 'Desktop/master/bin/pyXdPhysmaster/spikepy')
#from spike.file import FileInterpreter, Trial
#sys.path.insert(0, '/Users/leonardengmann/Desktop/master/bin/pyXdPhysmaster/')
#import pyXdPhysmaster as xd
import xdphys as xd
class ExampleText(xd.Stimulation):
def __init__(self):
... |
67bf29e4d7ad9549dcdf1bac85ed91db13e78a7b1647fedbdb85bf7369566ff9 | Python | 1,232 | 50 | """Plot power maps and coherence networks for each state.
"""
from sys import argv
if len(argv) != 3:
print("Please pass the number of states and run id, e.g. python 6_plot_networks.py 8 1")
exit()
n_states = int(argv[1])
run = int(argv[2])
#%% Import packages
print("Importing packages")
import os
import n... |
d76464705a1e190df6af0d8244ab297f95cefdf3e49b3674e09ab1ba57d33a7f | Python | 1,232 | 45 | import zipfile
from pathlib import Path
import gdown
from aislib.misc_utils import ensure_path_exists
def download_google_drive_file(
url: str, output_path: Path, overwrite: bool = False
) -> None:
if output_path.exists() and not overwrite:
return
if "/d/" in url:
url = _parse_google_url... |
1b51d8a2af734f1a67be34ab5f4c6e0f6658ecc97ffe4149ae4fd1019265f1a5 | Python | 1,233 | 56 | """Plot results.
"""
#%% 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 5_plot_results.py 1")
exit()
id = int(argv[1])
# Check results directory exists
results_dir = f"results/run{i... |
8c8f2417ac4139ee6a311ce2bba14f79a30a1beefd5f152ca44f410ff0422bdd | Python | 1,233 | 45 | import glob
import os
import nilearn
nilearn.EXPAND_PATH_WILDCARDS = True
import importlib
import myreporting
import numpy as np
import pickle
import pathlib
import fire
import sys
sys.path.insert(0,'..')
import contrasts
data_path = f"../bids_dataset/derivatives"
def main(task, subject):
target_affine = np.d... |
f938f95517813261849821fb57c41a23f92411121e1468b476438601c7bbf591 | Python | 1,233 | 34 | import sys
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def plot_data (data):
plt.grid()
plt.plot(data[:,0], data[:,1], label="PMJ Delay tuning - NminPMJ=60", c="black", linewidth=2.0, marker='o')
plt.xlabel(r"$R_{PMJ}$ ($M \Omega$)",fontsize=15)
plt.ylabel("PMJ delay (ms)",fo... |
0ed6debd13beef1f76beb05003a6220dc6afc5e025fefb9ee16047efde9de2fd | Python | 1,234 | 36 | #!/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
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.TemporaryDirectory()
def test_help_option(script_runner):
ret... |
db08cc1569b617e8542bc161b75b5072158afed46957f5041a18c6f343a12184 | Python | 1,234 | 37 | # coding: utf-8
"""Tests for dual GPU+CPU support."""
import os
import platform
import pytest
from sklearn.metrics import log_loss
import lightgbm as lgb
from .utils import load_breast_cancer
@pytest.mark.skipif(
os.environ.get("LIGHTGBM_TEST_DUAL_CPU_GPU", "0") != "1",
reason="Set LIGHTGBM_TEST_DUAL_CPU_... |
114af05cc203fe4bdcf409ac93c4c9c852c8a90f664bd419998dc6df2d13c1ec | Python | 1,235 | 33 | import os
import json
import torch
os.environ['CUDA_VISIBLE_DEVICE'] = '0'
import pandas as pd
import numpy as np
from tqdm import tqdm
from pathlib import Path
from transformers import *
pretrained_weights = 'roberta'
# tokenizer = RoBERTaModel.from_pretrained(pretrained_weights)
# model = RoBERTaModel.from_pretraine... |
d27a0641371522921d681af6a29e274a97ba6d1e24853ec50a5685f01dec23f7 | Python | 1,235 | 18 | raw={}
raw["words"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSI/language/CMU_MOSI_TimestampedWords.csd'
raw["phonemes"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSI/language/CMU_MOSI_TimestampedPhones.csd'
highlevel={}
highlevel["glove_vectors"]='http://immortal.multicomp.cs.cmu.edu/CMU-MOSI/language/CMU_MOSI_Tim... |
de4e2ee5003a573d46d107b65c5b36f9c28a9a4bd11200840961d54b5d348598 | Python | 1,235 | 39 |
import os
import pandas as pd
import json
def load_dataset_splits(config, data_dir, transfer = False):
if transfer :
selected_datasets = config['dataset_transfer']
else :
selected_datasets = config['dataset_pretrain']
datasets = selected_datasets if isinstance(selected_datasets, list) els... |
19dc1d335166ede674f6939ca57c3c891ffb7f734dd7387c2121659628d10ded | Python | 1,236 | 45 | import unittest
import torch
import torch.testing as ptt
from deepdwi import lsqr
from deepdwi.dims import *
if __name__ == "__main__":
unittest.main()
devices = [torch.device('cpu')]
if torch.cuda.is_available():
devices.append(torch.device('cuda'))
class TestLsqr(unittest.TestCase):
def Ax_setup(sel... |
8ca8a8d270acea5a585d58723780eb837ade54d2ba1ad85bf230828fd6433973 | Python | 1,236 | 35 | #!/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... |
8d160e042dca40bd903fad5634abfe5a6959b81e14ebcfc9f7473f64e6ca014a | Python | 1,236 | 41 | import os
import glob
import nibabel as nib
import numpy as np
folder1 = "/mnt/f/BIDS/SVD_BIDS/derivatives/fdt/sub-SVD0029/ses-03/bedpostX_input.bedpostX3"
folder2 = "/mnt/f/BIDS/SVD_BIDS/derivatives/fdt/sub-SVD0029/ses-03/bedpostX_input.bedpostX1"
output_folder = "/mnt/f/BIDS/SVD_BIDS/derivatives/fdt/sub-SVD0029/ses-... |
bffb959c4cd3e92564f27c9dee1c70a64314a86ad26f7733b1672092f67731e3 | Python | 1,236 | 19 | """Describe existing OXPHOS leading edges; no new hypothesis tests."""
import csv
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def read(p):
with (ROOT/p).open() as f:return list(csv.DictReader(f))
ids={r['symbol']:r['gene_id'] for r in read('tables/transcriptomics/gene_mapping.csv') if r['selected... |
154fcf5a620fbbc4bc4d589799ee0104ba412102ca3762ee0a365c66c295a728 | Python | 1,237 | 33 | import numpy as np
import os
import pandas as pd
from pathlib import Path
from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet
from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set
def collect_stimuli(data_dir):
stimulus_set = pd.read_csv(data_dir... |
1fa6c82eb98302c2fe690220d1e6dae800bd9154899612fb184079f6de433a78 | Python | 1,238 | 50 | import pandas as pd
import pytest
from pyment.data.dataset import Dataset
class _ConcreteDataset(Dataset):
def to_tensorflow_generator(self, *args, **kwargs):
pass
@pytest.fixture
def dataset():
labels = pd.DataFrame(
{
'image_path': ['/a', '/b', '/c', '/d'],
'target... |
715f799e2a55f0b7f991b434197a17718694a4e85e2bc7c47c5486114db2193a | Python | 1,238 | 38 | from transformers import PretrainedConfig
class EnformerConfig(PretrainedConfig):
model_type = "enformer"
def __init__(
self,
dim = 1536,
depth = 11,
heads = 8,
output_heads = dict(human = 5313, mouse= 1643),
target_length = 896,
attn_dim_key = 64,
... |
c109b2dd0b89f61dfa351bb68d09070611f2b7bfa59ffb59f44ed18daa36b92d | Python | 1,238 | 40 | from pytest import approx
from brainscore_vision.metrics.value_delta import ValueDelta
class TestValueDelta:
def test_perfect_score(self):
metric = ValueDelta()
value_delta = metric(1.25, 1.25)
assert value_delta == 1
def test_middle_score(self):
metric = ValueDelta()
... |
58d5098f4deef4e3c1c7d08c9e451d1c5136c7b065db09b93c57dd68ded88506 | Python | 1,239 | 62 | '''Help functions.
'''
# Anwar O. Nunez-Elizalde (Jan, 2016)
#
# Updates:
# Anwar O. Nunez-Elizalde (Apr, 2020)
#
#
import numpy as np
with_tqdm = True
try:
from tqdm import tqdm
except ImportError:
with_tqdm = False
pass
##############################
# helper functions
##############################
... |
bdd6b5f4a6a1be84c04ed0ad875849297fbf1401a93bf303aa49b7fc42323249 | Python | 1,239 | 39 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 27 15:35:54 2022
@author: Artur Klepaczko
"""
from skimage.feature import graycomatrix, graycoprops
import numpy as np
feature_names = ['dissimilarity', 'contrast', 'correlation', 'energy', 'homogeneity', 'ASM']
distances = [1, 3, 5]
angles = [0, np.pi/4, np.pi/2, 3*np... |
fed01f5c5b137a2de3ab627203e513575f87a1aa05f14719e98624f3726c6144 | Python | 1,239 | 34 | import os
import json
import torch
os.environ['CUDA_VISIBLE_DEVICE'] = '5'
import pandas as pd
import numpy as np
from tqdm import tqdm
from pathlib import Path
from transformers import *
pretrained_weights = 't5-small'
tokenizer = T5Tokenizer.from_pretrained(pretrained_weights)
model = T5EncoderModel.from_pretrained(... |
717c68ba5da7b7f3144eebff5405fb92dd922f06272782b87afb2369d4f33d45 | Python | 1,240 | 38 | from pathlib import Path
from brainways.utils.cell_detection_importer.brainways_cell_detection_importer import (
BrainwaysCellDetectionsImporter,
)
def test_find_cell_detections_file(mock_subject_documents, tmpdir):
document = mock_subject_documents[0]
csv_path = (
Path(tmpdir)
/ f"{Path(... |
8a53a739ec323d27c1ed77c12bf65c55a4865ac4332678f44b3b357a50b4d1d3 | Python | 1,240 | 45 | #!/usr/bin/env python
"""Tests for `magicgui._qt` module."""
import pytest
from qtpy import API_NAME, QtCore
from qtpy import QtWidgets as QtW
from magicgui import event_loop, widgets
@pytest.mark.skipif("PyQt" in API_NAME, reason="Couldn't delete app on PyQt")
def test_event():
"""Test that the event loop mak... |
009f6fe44f81afd8e96671c2327d839eecea2bc64a40f0c5123ac099043fa13a | Python | 1,241 | 44 | from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="deepdefacer",
packages=['deepdefacer'],
version="2.1.2",
author="Anish Khazane",
author_email="akhazane@stanford.edu",
description="Automatic Removal of Facial Features ... |
27d270913b7ea000c19059872ef7927bc5a4571ac83fda61b8a808bae3622e18 | Python | 1,241 | 44 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tree.py — 打印指定目录(默认当前目录)的树状结构
用法:
python tree.py [路径]
例:
python tree.py .
"""
import os
import sys
def print_tree(path: str, prefix: str = "") -> None:
"""
以树状结构打印给定路径下的所有文件和文件夹。
参数:
path — 要遍历的目录路径
prefix — 用于递归时的行首前缀,内部自动管理缩进和分... |
85186c2f77e1c4520cd68c787d0900d48e3fb76dac1c5b287ead04851d5e8b65 | Python | 1,241 | 41 | import os
import numpy as np
import pandas as pd
import scanpy as sc
import anndata as ad
os.chdir("/data/wuqinhua/phase/covid19/datasets")
adata = ad.read_h5ad('./pre_data/13_Stephenson_2021/haniffa21_Stephenson_2021.h5ad')
adata
csv_data = pd.read_csv('./pre_data/13_Stephenson_2021/dict_Stephenson.csv')
sample_ids... |
a49f18f39af41f96c81ef26325508beae60f27b862a4aeb47aba7f725db6325c | Python | 1,241 | 33 | #!/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... |
f8dbb9ea4a30076de8003ec8e8145f674803b7fcf554aa8e86c269cc506e7d80 | Python | 1,241 | 41 | import numpy as np
from types import GeneratorType
from itertools import chain, izip_longest
def unique(iterable):
"""Return unique values from iterable."""
seen = set()
return [i for i in iterable if not (i in seen or seen.add(i))]
def binarize_sparse(a, dtype=np.int32):
"""Return array where maximu... |
ac5eec25d0b5a134360376de07642bc42af768016741dd651177b5f928a78c09 | Python | 1,242 | 42 | import ntac
from ntac import Ntac, FAFBData
import os
from os.path import join
import numpy as np
# first download the flywire data we'll need for this example. This will be cached in ~/.ntac/flywire_data
ntac.download_flywire_data(verbose=True)
# This is where the data lives:
base_path = join(os.path.expanduser("... |
b707fb259b9b0e701eb599da8d418d6a389348c64c51069bb49e2890b857f5e9 | Python | 1,242 | 40 | """Utilities for padding NIfTI images to a target shape."""
import nibabel as nib
import numpy as np
def pad_nifti_image_if_necessary(
image: nib.Nifti1Image, target_shape: tuple[int, int, int]
) -> nib.Nifti1Image:
"""Pads image to target_shape along any axis that falls short of it,
distributing padding... |
e84e8d3d38cb4b0517e95d640e44827b3553675f745bdd7d12db8ef1f7958ab3 | Python | 1,242 | 53 | """
Autoencoder systems.
DB van de Pavert, RR van de Leur and MB Vessies
"""
import torch.nn as nn
from ecgxai.utils.exceptions import ModelOutputShapeMismatchException
from ecgxai.systems.base_system import BaseSystem
class AE(BaseSystem):
def __init__(
self,
encoder_class: nn.Module,
... |
00d4d4ccdfded32cbffe662b925f145844dc4b6af1d7e6b21e3b3cb8d428b981 | Python | 1,243 | 36 | import os
import scanpy as sc
import pandas as pd
import anndata as ad
os.chdir("/data/wuqinhua/phase/covid19/datasets")
adata = ad.read_h5ad('./pre_data/20_Zhu_2020/sce.h5ad')
submatrix_block = adata.raw.X[:15, :25].toarray()
adata.X = adata.raw.X
csv_data = pd.read_csv('./pre_data/20_Zhu_2020/dict_Zhu.csv')
sample... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.