sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
60eec1084e132b1ade54ea2830f0571c40ddf28ca5fb6eaea726c7bc83880cbf | Python | 727 | 30 | import dask.array as da
from distributed import Client, LocalCluster
from sklearn.datasets import make_regression
import lightgbm as lgb
if __name__ == "__main__":
print("loading data")
X, y = make_regression(n_samples=1000, n_features=50)
print("initializing a Dask cluster")
cluster = LocalCluster... |
b598cbc881a105a6725af600057692afcfaa68ce9aebb038e7b86e50867efede | Python | 727 | 21 | import click
from _cli import LazyGroup
@click.group(
cls=LazyGroup,
lazy_subcommands={
"collect": "i2m.collect_mesh_data.collect",
"concentrations2mesh": "i2m.concentrations_to_mesh.concentrations2mesh",
"tissue-concentrations": "i2m.voxel_center_minimization.map_evaluation_data_to_m... |
26d43b7893468f250a51cb3604dccc9aa00b51d0496f62e369620ad01968ef34 | Python | 728 | 28 |
import networkx as nx
import numpy as np
import os
from tqdm import tqdm
# edge_path=r'/data2/whr/lyh/baseline2/Twibot-22/edges.npy'
# edge_index=list(np.load(edge_path))
# edges=[]
dataset_name='Twibot-22'
edge_path=r'/data2/whr/lyh/baseline2/Twibot-22/edges.npy'
edge_index=list(np.load(edge_path))
edges=[]
datas... |
f25cdd1ff9cb433569f097c2aafa615e7b0961c24a25518493c4897bcd13cd66 | Python | 728 | 29 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from cvat.apps.engine.models import Project
from cvat.apps.iam.models import User
from cvat.apps.webhooks.models import Webhook, WebhookContentTypeChoice
def make_webhook(
_type: str,
events: str,
owner: User,
project: Project | Non... |
081453c5d6f23096fee8f29c61278620a4b974ff4201f0bf5456dc506e60a074 | Python | 729 | 25 | """# Simple progress bar
A simple progress bar demo with magicgui.
"""
from time import sleep
from magicgui import magicgui
from magicgui.tqdm import trange
# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in
# interactive use in IPython), then they fall back to the standard termi... |
1dad4665813959c99eb2d5a5a6b18deac5c4c26b8d79d2ad6b53248dc6288a67 | Python | 729 | 28 | """Utility functions for tests."""
import os
import pytest
from qtpy import _parse_version
def using_conda():
return os.environ.get("USE_CONDA", "Yes") == "Yes"
def not_using_conda():
return os.environ.get("USE_CONDA", "No") == "No"
def pytest_importorskip(module, **kwargs):
"""
Skip the test i... |
5f003f4c5ee7140d229ebbed36e8f056462ea93c1beedbf34977e10ee4af2a5f | Python | 729 | 30 | import dask.array as da
from distributed import Client, LocalCluster
from sklearn.datasets import make_blobs
import lightgbm as lgb
if __name__ == "__main__":
print("loading data")
X, y = make_blobs(n_samples=1000, n_features=50, centers=3)
print("initializing a Dask cluster")
cluster = LocalCluste... |
96e0c7a9f3619d0134fc73e0e3a05b59ca31b3129262c6cfbc78e73d4985c1bd | Python | 729 | 24 | import pytest
from pytest import approx
from brainscore_vision import load_benchmark, load_model
@pytest.mark.private_access
class TestExist:
def test_benchmark_loads(self):
benchmark = load_benchmark('Cowley2026.V4-pls')
assert benchmark is not None
assert benchmark.identifier == 'Cowley... |
4a8fab636025bf265006096bdd4b194334049cac5ac8e762bda0b8af95b7f31e | Python | 730 | 16 | from pydantic import BaseModel, Field
from typing import List, Optional
class AtomsData(BaseModel):
"""AtomsData object inherited from Pydantic BaseModel. Used to store atomic data (from ASE Atoms object or QCElemental Molecule object) that cannot be parsed via LLM Schema."""
# Optional is equivalent to... |
d1db7c8877990d87bb558164605cfa8e5a3b1188ad2e0cc99f0e5b8e0e02d656 | Python | 730 | 23 | import numpy as np
from dipy.utils.optpkg import optional_package
IMPORT_ERROR_MSG = "PyTorch 2.1.2 is required to run this script. Please " + \
"install it first. See the official website for more " + \
"info: " + \
"https://pytorch.org/get-started/locally/" #... |
35f56971c8fcec0d67170860f067eb0839e3765082c310f497fc14f000f2ca44 | Python | 731 | 28 | import librosa
import soundfile as sf
import sys, os, glob
from typing import Union
def get_opt(opt: str, default: Union[bool, str] = False) -> Union[bool, str]:
'''
'''
for k in sys.argv[1:]:
if(k[0:len(opt)] == opt): return k[len(opt)+1:]
return default
if __name__ == '... |
35f925145d50936c59f2ba8fc0b846cc2a5078de2710b97624029544f1db58fe | Python | 731 | 28 | import tensorflow as tf
from ..config import TF_COMPLEX
def cnormsq(inputs: tf.Tensor) -> tf.Tensor:
"""
Args:
inputs: The input tensor, :math:`V`.
Returns:
An output tensor that performs elementwise absolute value squared operation, :math:`f(V) = |V|^2`.
"""
return tf.cast(tf.s... |
d81fb460d0f4e05ac41299fe50447e00a2d005bcb4e3f1b8822253ef9b3f46fb | Python | 732 | 18 | # Copyright (C) 2021-2022 Intel Corporation
#
# SPDX-License-Identifier: MIT
from rest_framework.parsers import BaseParser
class TusUploadParser(BaseParser):
# The media type is sent by TUS protocol (tus.io) for uploading files
media_type = "application/offset+octet-stream"
def parse(self, stream, media... |
f53e8de0641d816546d3cee67c145b4922d0e3f9272d42ec887d0590f4870f11 | Python | 732 | 20 | import torch.nn.functional as F
# Determine maximum height and width
# The mask's have the same height and width
# since they mask the image.
max_height = max([img.size(1) for img in image_batch])
max_width = max([img.size(2) for img in image_batch])
image_batch = [
# The needed padding is the difference between ... |
cf5f4ef798391e2a9b522944358f54b6897d08e6b25df33afdfb876fcd285d51 | Python | 733 | 34 | # -*- coding: utf-8 -*-
"""TODO"""
class SpikeDelay:
"""TODO"""
def __init__(self, delay):
"""TODO"""
self.delay = delay
self._clock = None
self._delay_buffer = [[]] * self.delay
def set_delay(self, delay):
"""TODO"""
if delay == self.delay:
r... |
61effa62047c6701e3dd105deedea3f072b0ad232ef290dd36cc72ce15ab7e71 | Python | 734 | 27 | import torch.nn as nn
import torch.optim as optim
class Classifier(nn.Module):
def __init__(self, data_shape, init_dropout):
super(Classifier, self).__init__()
self.data_shape = data_shape
self.init_dropout = init_dropout
self.layers = nn.Sequential(
nn.Dropout(p=init_drop... |
9a029d474441de9c4273f9ab360d5e9331597c78f513b05e1a7234fd69641492 | Python | 734 | 27 | import mmcv
import os
import numpy as np
import cv2
res_path = 'nfs/results/test-ensemble-res'
path_names = ['nfs/saves/test-ensemble']
weights = [1]
reweights = [w/sum(weights) for w in weights]
file_names = os.listdir(path_names[0])
for name in file_names:
for idx, (path_name, w) in enumerate(zip(path_names... |
0a89d4aefd0f10b5f2d39e1e1aa6cd8904450618365fea103bd7f66a1d22a527 | Python | 735 | 26 | # Copyright (C) 2023 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from django.apps import AppConfig
class QualityControlConfig(AppConfig):
name = "cvat.apps.quality_control"
def ready(self) -> None:
from django.conf import settings
from . import def... |
6b65e92f30aa59ea5d68b1d22b12be6fbb7e204bef1c7230f7287309debd4544 | Python | 735 | 27 | # Generated by Django 4.2.13 on 2024-07-12 19:06
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("quality_control", "0001... |
2f090cf9ff697329bc613a91868ec99f1b01a2d55302d0ee0fd40f98d481edb1 | Python | 736 | 24 | import numpy as np
from impyute.ops import matrix
from impyute.ops import util
def _add_one(x):
""" """
return x + 1
def _square(x):
return x * x
def test_thread():
assert 10 == util.thread(3, _square, _add_one)
assert 100 == util.thread(3, _square, _add_one, _square) #4
assert 82 == util.thr... |
a2989dce0c90fd211943afb009de8a8151baa59973e8c92052ef79663279680a | Python | 737 | 32 | hiddenimports = [
"fabio.edfimage",
"fabio.adscimage",
"fabio.tifimage",
"fabio.marccdimage",
"fabio.mar345image",
"fabio.fit2dmaskimage",
"fabio.brukerimage",
"fabio.bruker100image",
"fabio.pnmimage",
"fabio.GEimage",
"fabio.OXDimage",
"fabio.dm3image",
"fabio.HiPiCi... |
a41f2c9bbc65c031bb5088b9cac7f5f5b9dba9d170e51bd0db82fac8e334543c | Python | 737 | 37 | """Example script for calculating static power spectra.
"""
print("Setting up")
import numpy as np
from osl_dynamics.analysis import static
from osl_dynamics.data import Data
from osl_dynamics.utils import plotting
# Load data
data = Data(
[
f"/well/woolrich/projects/uk_meg_notts/eo/natcomms18/src_rec/su... |
e2aa8b06a72728507d784338111a246da2fb41d53ad2f034505301ea9e019786 | Python | 737 | 33 | #!/usr/bin/env python
"""
Writes compressed data from a wiggle file by chromosome.
usage: %prog score_file < wiggle_data
"""
import sys
import bx.wiggle
from bx.binned_array import BinnedArray
def main() -> None:
scores: dict[str, BinnedArray] = {}
with open(sys.argv[1]) as f:
for i, (chrom, pos, ... |
005ee3b33ff64448f09870bc4575ff2700f75666ea162b2ba40e871d963253d3 | Python | 738 | 25 | from musclex.modules.QuadrantFolder import QuadrantFolder
def test_slow_path_invalidates_all_fold_dependent_images():
qf = QuadrantFolder.__new__(QuadrantFolder)
stale_keys = (
"avg_fold",
"BgSubFold",
"BgFold",
"mask",
"resultImg",
"resultBg",
"resultFo... |
27892d6e4165f5c3940fc7f54a01082796071d1c7be9f94f3d82476ef3da122e | Python | 738 | 26 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtSensors classes a... |
2b8c5addaaa69e403d09a867b94724d4227e0e5f8d60ebf50f1157a6e2855f13 | Python | 738 | 22 | '''Test the ogo command line interface for calib midways'''
import unittest
import subprocess
class TestMindwaysCLI(unittest.TestCase):
'''Test the ogo command line interface for calib midways'''
def test_can_call_mindways_help(self):
'''Can call `ogo calib mindways --help`'''
command = ['og... |
6c7e9b3e6a1778a2aa9a96e02e878bcc163049618aba85eb349b1297b7c31d61 | Python | 740 | 22 | '''Test the ogo command line interface for calib standard'''
import unittest
import subprocess
class TestStandardCLI(unittest.TestCase):
'''Test the ogo command line interface for calib standard'''
def test_can_call_standard_help(self):
'''Can call `ogo calib standard --help`'''
command = ['... |
31e04ebff308f2bb147a776b59319404fd7dfd722bebecdd4adc25068e49a0fc | Python | 741 | 27 | import pandas as pd
label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/botometer-feedback-2019/label.csv')
main_user = pd.read_csv('./user_feature.csv')
user = main_user.loc[0:len(main_user)-1]
user_list = list(user['user_id'])
del_list = []
bool_label = []
for i,r in label.iterrows():
if r[1] == '... |
f7d74ba0f3206249e0869edcedca704b08c7a143eafc747ed91100222c39eef0 | Python | 741 | 40 | import numpy as np
from impedancefitter.double_shell import double_shell_model
omega = 2. * np.pi * np.logspace(0, 12, num=30)
# for cole_cole_model
c0 = 1.
em = 10.
km = 1e-6
kcp = 0.5
ecp = 60
kmed = .1
emed = 80
p = 0.1
dm = 5e-9
Rc = 5e-6
# for double shell
Rn = 0.8 * Rc
ene = 15.0
kne = 1e-6
knp = .5
enp = ... |
2a40a961eb833f98d1c427144496e77bf93eed9ab5937d68ab66851e9ab2831f | Python | 742 | 30 | """ impyute.contrib.count_missing.py """
import numpy as np
from impyute.ops import matrix
def count_missing(data):
""" Calculate the total percentage of missing values and also the
percentage in each column.
Parameters
----------
data: np.array
Data to impute.
Returns
-------
... |
51570c2ef0a9d8e56e9c53c8c1096671f2fb3254a05995367bcc657b6068f248 | Python | 742 | 30 | # torch imports
import torch
import torch.nn as nn
def get_1D_kernels_k33(x, xi, scale=1):
"""function calculating the 1D kernel functions given the bond length
x corresponds to the input, xi is the reference structure)
"""
xl = torch.maximum(x, xi)
xs = torch.minimum(x, xi)
drker33 = scale... |
7075c07258b030aeafd2b599782d9fc432772855dd67dcf8a4f88cf39a1a31ed | Python | 742 | 34 | from pathlib import Path
from typing import Optional
import click
from tqdm import tqdm
from brainways.project.brainways_project import BrainwaysProject
@click.command()
@click.option(
"--project",
type=Path,
required=True,
help="Brainways project path.",
)
@click.option(
"--new-images-root",
... |
5b7e33cc97e1b4df08f25ebb86d33b56272cf7f56c8ebae4ec36144291647274 | Python | 743 | 35 | import pytest
from tests.helpers.run_command import run_command
@pytest.mark.slow
def test_debug_default():
command = ["scripts/train.py", "debug=default"]
run_command(command)
def test_debug_limit_batches():
command = ["scripts/train.py", "debug=limit_batches"]
run_command(command)
def test_debu... |
6e9e026dc71e179a4a95ae9d0ebdf36fded9d4fb7cb9fbabc642c3b810c37c5b | Python | 744 | 30 | # Generated by Django 4.2.1 on 2023-06-23 19:26
from django.db import migrations, models
def forwards_func(apps, schema_editor):
Issue = apps.get_model("engine", "Issue")
issues = Issue.objects.all()
for issue in issues:
issue.updated_date = issue.created_date
Issue.objects.bulk_update(issu... |
0b44ea925ea1da8820daedab8b5e63c376cd6fbdd5a3d8e178008accea5a8057 | Python | 745 | 29 | """noxfile.py."""
import nox
nox.options.default_venv_backend = "uv"
@nox.session(python=["3.10", "3.11", "3.12"])
def tests(session: nox.Session) -> None:
"""Test session."""
session.install("pytest~=8.3", "pytest-cov~=5.0")
session.install(".")
session.run("python", "-m", "pytest", *session.posarg... |
6a98996b463191e896afc201583ddfed6385f8b0d5718428dcef8c36b7809019 | Python | 745 | 30 | import argparse
import os
import os.path as osp
import time
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.metrics import f1_score
import pandas
import json
import torch_geometric.transforms as T
from torch_geometric.nn import ChebConv, GCNConv # noqa
from tqdm import tqdm
parser = argpar... |
a1144705d2bf2969980c764580fca9771604f7ecaa6a7db9a8cece3c3408b321 | Python | 745 | 24 | import scanpy as sc
import pandas as pd
import anndata as ad
import numpy as np
import logging
logging.basicConfig(level=logging.INFO)
adata = sc.read_h5ad("/data/wuqinhua/phase/LungCancerCell/Lung_CancerCell.h5ad")
logging.info("read_over")
sc.pp.scale(adata, max_value=10)
sc.tl.pca(adata, svd_solver='arpack')
sc.pp.... |
37af094e4818db77625605407d2d88a393a74a68cad6283449de2f9ac9ba9834 | Python | 746 | 31 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from types import SimpleNamespace as namespace
import cvat_sdk.auto_annotation as cvataa
import cvat_sdk.models as models
import PIL.Image
def create(s: str, i: int, f: float, b: bool) -> cvataa.DetectionFunction:
assert s == "string"
asse... |
b8d598a555e1503b5e8902235d7961a4908ebce51526a3c5dff7df6d5de87caf | Python | 747 | 17 | from nets.deeplabv3_plus import DeepLab
from nets.resnet import resnet50, resnet101
from utils import EvalCallback
input_shape = [256, 256]
num_classes =6
VOCdevkit_path = '../dataset/vaihingen256/VOCdevkit'
save_dir = 'logs'
log_dir = os.path.join(save_dir, "loss_" + str(time_str))
with o... |
fe631165c0ac3df5a01c8ee6116854d9cd12e617e6d71bfa92e4d43180889f58 | Python | 747 | 31 | # torch imports
import torch
import torch.nn as nn
def get_1D_kernels_k33(x, xi, scale=1):
"""function calculating the 1D kernel functions given the bond length
x corresponds to the input, xi is the reference structure)
"""
xl = torch.maximum(x, xi)
xs = torch.minimum(x, xi)
drker33 = s... |
16bdbe7bac61e1de3f1e58971ddaee601394e91074efce75fc730d64e3bea233 | Python | 748 | 23 | from .gino import GINO
def initialize_GINO_model(n_fno_modes):
model = GINO(
in_channels=5, # [ploc_bool, D_iso, ef_vector]
out_channels=1,
gno_coord_dim=3,
gno_coord_embed_dim=16,
gno_radius=0.1,
gno_transform_type='linear',
fno_n_modes=[n_fno_modes, n_fno_... |
28ef40e6533714cf9a6b9572789052003404df8e17c2a6eb6ddf96ce0cf28584 | Python | 748 | 20 | from dtiplayground.dmri.common.tools.base import ExternalToolWrapper
class DTIAverage(ExternalToolWrapper):
def __init__(self,binary_path= None, **kwargs):
super().__init__(binary_path, **kwargs)
self.binary_path=None
if binary_path is not None:
self.binary_path=binary_path
... |
c1b869504bf99434a82dbfc2174adb8b95b21b125b8eeb2fe0272fc1551aab9b | Python | 748 | 25 | import warnings
try:
from .ANTs.ANTs import ANTsRegistrator
except ImportError:
warnings.warn(
"ANTS package not found. If you want to use it, please install it using 'pip install antspyx'"
)
from .niftyreg.niftyreg import NiftyRegRegistrator
try:
from .elastix.elastix import ElastixRegistra... |
00a71e920baa4e81f63d58ff210f0b396d4cb4683414f5202955d9fe4ee2443f | Python | 749 | 26 | import os
import json
import numpy as np
import pandas as pd
from json import JSONEncoder
from subprocess import check_call
###########################################################
# section1 : common functions
###########################################################
class General_Encoder(JSONEncoder):
def d... |
45233f5cb1ba73eb5d076314417627ee34f084b89089a8304011579fffff82f1 | Python | 749 | 13 | import os
import ClearMap.Settings as settings
filename = os.path.join(settings.ClearMapPath, 'Test/Data/ImageAnalysis/cfos-substack.tif');
import ClearMap.Visualization.Plot as plt
import ClearMap.IO as io
data = io.readData(filename, z = (0,26));
import ClearMap.ImageProcessing.BackgroundRemoval as bgr
dataBGR = bgr.... |
9244e898842a6f7891cd6c4d624b5442289f6188cda999e3c541a9bca5f33327 | Python | 749 | 19 | from .data import *
class ListCorpus(Corpus):
def __init__(
self,
train: List[FlairDataset],
dev: List[FlairDataset],
test: List[FlairDataset],
name: str = "listcorpus",
targets: list = [],
):
# In this Corpus, we set train list to be our target to train, we keep self._train the same as the Class Corpus... |
cb0d133c8fbfa81724b52ef5b4e6060e7deb9720d9380b9082d66104d6c6d723 | Python | 749 | 24 | import obspy
import pytest
import seisbench.models as sbm
import seisbench.util as sbu
@pytest.mark.parametrize("norm", ["std", "peak"])
def test_annotate_eqtp(norm):
# Tests that the annotate/classify functions run without crashes and annotate produces an output
model = sbm.EQTP(
sampling_rate=2000,... |
4163100bd3d46b5e68728241c932d675727c022f3b5675164fdaf40499064b06 | Python | 750 | 25 | from __future__ import annotations
import math
import numpy as np
import pytest
from numpy.typing import NDArray
@pytest.fixture(params=[math.pi / 6, -math.pi / 6], ids=["+30deg", "-30deg"])
def rotated_rectangle_angle(*, request: pytest.FixtureRequest) -> float:
return request.param
@pytest.fixture
def rotat... |
7a356cf52c3949a97f6723c38db39f51f388493c1d35347bce734e8c381c84cc | Python | 750 | 21 | import numpy as np
from tqdm import tqdm
def randomize_sequences(X):
lenghts = [len(x) for x in X]
long_seq = np.concatenate(X)
Y = np.random.choice(long_seq, size=(len(X),np.mean(lenghts).astype(int)))
#y = np.random.permutation(np.concatenate(X))
#cumlens = np.insert(np.cumsum(lenghts), 0,0)
... |
858d2fbf3439f0ddf83f559c753833025c278e10a3e9513a356a355f95e4466c | Python | 750 | 27 | """SGCN runner."""
from sgcn import SignedGCNTrainer
from param_parser import parameter_parser
from utils import tab_printer, read_graph, score_printer, save_logs, read_st_graph
def main():
"""
Parsing command line parameters.
Creating target matrix.
Fitting an SGCN.
Predicting edge signs and savi... |
2b7c0950966336686dd50bc269eb449d2dec6072b6114b95d65f3f8668fb19ab | Python | 751 | 45 | #-*- coding:utf-8 -*-
u'''
embedding youtube video to sphinx
usage:
First of all, add `sphinxcontrib.youtube` to sphinx extension list in conf.py
.. code-block:: python
extensions = ['sphinxcontrib.youtube']
then use `youtube` directive.
You can specify video by video url or video id.
.. code-block:: rst
... |
533992de6024ce342df1cd8d9c39f6771b91db889919e75599bed0bee68a6e6f | Python | 751 | 22 | """Minimal smoke tests for predictor module.
This file previously contained a syntax error due to an incomplete import.
Conda's byte-compilation reported it but did not fail the build. We keep a
very small executable snippet here so packaging/import checks succeed cleanly.
"""
from .predictor import predict_lncrna #... |
e8afcf0fd780d2d4c08161ad9f91a42eb6f489cfb55689dcc3d3885d969e0d67 | Python | 751 | 25 | from __future__ import annotations
from collections.abc import Iterable
from PySide6 import QtCore
from ._shape import Shape
class ShapeClipboard(QtCore.QObject):
availability_changed = QtCore.Signal(bool)
def __init__(self, *, parent: QtCore.QObject | None = None) -> None:
super().__init__(parent... |
0234d3b705e93ae4b85b0ddd3a70c1857066462c3954382c7d3444a0ca606194 | Python | 752 | 24 | #!/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=['filtering.zip'])
tmp_dir = tempfile.Te... |
d7291529db6cea1a086782d13b0809dd63e71ee8b229ad3efe92022251b6d0fd | Python | 752 | 33 | # Copyright 2014 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import random
from nab.detectors.base import AnomalyDe... |
17b057d58513cbb1ac79b9b37d823b5bbfd862ed0ad36a12fdddb3b0f4310f9a | Python | 753 | 34 | import sys
from pathlib import Path
p_dir = str(Path(__file__).absolute().parents[1])
if p_dir not in sys.path: sys.path.insert(0, p_dir)
import random
import time
import torch
import nibabel as nib
import numpy as np
import pandas as pd
def brainage_month_to_class(month):
if type(month) == np.ndarray:
... |
536e85e311ea2099dc434c2b60bc71c625066514edeed172c398f15626e79747 | Python | 753 | 35 | # -*- coding: utf-8 -*-
"""Surface smoothing."""
import os
from .. import execute_command
from ..io.filename import get_filename
__all__ = ["mris_smooth"]
def mris_smooth(file_in, file_out, n_iter):
"""Smooth surface tesselation.
Parameters
----------
file_in : str
File name of input surfa... |
c047b83e148e0199e05fee784be4b5262e078ef3939a5b56bb76435bd7e47947 | Python | 753 | 24 | import subprocess
import sys
import yaml
script_calc = 'stability/get_transition_stats_per_rec.py'
script_plot = 'stability/plot_stability.py'
scripts = [script_calc,script_plot]#
pathpath = 'PATHS/filepaths_carlen.yml'
with open(pathpath, 'r') as myfile: pathdict = yaml.safe_load(myfile)
sys.path.append(pathdict['c... |
35f8798b038e129779728a06775c350db5dd6306fe1f5f6c88f006adccb1a660 | Python | 754 | 18 | from distances_calculation import *
fold = r"/Users/benjaminbarad/Dropbox (Scripps Research)/Grotjahn Lab/Data/Surfaces/Lam2_TS1/" # output will be also written there
base_filename = "distance_calculation"
segmentation_file = "TS1_surf.labels.mrc"
lbl_mem1 = 1
lbl_mem2 = 3
log_file = '{}{}.distances_and_thicknesses_c... |
214a9c78796427cd1f3b7966c520e5dc3deaae13a5a824cc210d6d7e20d211cd | Python | 755 | 24 | import obspy
import pytest
import seisbench.models as sbm
import seisbench.util as sbu
@pytest.mark.parametrize("norm", ["std", "peak"])
def test_annotate_phasenet(norm):
# Tests that the annotate/classify functions run without crashes and annotate produces an output
model = sbm.Skynet(
sampling_rate... |
59fe10bef92ba2b399b0d36ac52fe35e3f9aa5af483f719742740e271582f0ed | Python | 755 | 20 | import os
from conans import ConanFile
class GlmConan(ConanFile):
name = "glm"
version = "master"
generators = "txt"
url="https://github.com/g-truc/glm"
description="OpenGL Mathematics (GLM)"
license = "https://github.com/g-truc/glm/blob/manual/copying.txt"
exports = ["FindGLM.cmake", "lib_... |
e8fc32ea3f4d7ce9d7ac4a94be832f16ef6af727b9a4890129518f22fc26323c | Python | 755 | 30 | """Package used for testing the deferred import error mechanism."""
# See https://github.com/spyder-ide/qtpy/pull/387/
from qtpy._utils import getattr_missing_optional_dep
from .optional_dep import ExampleClass
_missing_optional_names = {}
try:
from .optional_dep import MissingClass
except ImportError as er... |
0b6210e8954dc3552d44ea1850e00180ce2629bbc567166ccc5286a4df4de21e | Python | 756 | 26 | # -----------------------------------------------------------------------------
# Copyright 2020 Antonio Valentino
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPositioning classes and functi... |
df24099e87e7a9aeac906613eb1df4f9797e6cc132770968ac47ca3938b1e654 | Python | 756 | 22 | import subprocess
import sys
import yaml
script = 'connectivity_correlations/harris_vs_enrichment_ENHequalaxes.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 import settings as S
#setk... |
02354cfd47b7043fed5187af87711d7dc4a79602078c9d48bb0f23140d8a7170 | Python | 757 | 27 | """Pydantic configuration for train/validation splitting."""
from pydantic import BaseModel
from ..data.dataset import Dataset
class DataSplitConfiguration(BaseModel):
"""Configuration for splitting a dataset into train/validation."""
training_fraction: float
def split(self, dataset: Dataset) -> tuple... |
e64f73b7c50e51bb921486120de98d54d93d22c6ca2bedcdcff50edf1ff65bf9 | Python | 758 | 21 | import torch
import torch.nn as nn
from models import *
class Net1(nn.Module):
def __init__(self, input_dim, num_class, bottle_neck, fc_layer_num, prob_drop):
super(Net1, self).__init__()
fc_layer = [nn.Linear(input_dim, bottle_neck), nn.ReLU(), nn.Dropout(p=prob_drop)]
for i in r... |
32e498222740c9bb973e8692329a060bf23559e05016d2a278001401620090f4 | Python | 759 | 27 | import torch
from torch.utils.data import Dataset
class BotDataset(Dataset):
def __init__(self, name, args):
self.name = name
self.train_idx = torch.load(args.path + "train_idx.pt")
self.val_idx = torch.load(args.path + "val_idx.pt")
self.test_idx = torch.load(args.path + "... |
c4cefed3b91bbb657d433b8d9a55a44f7382181439ed35993ea0e216d8a944b2 | Python | 760 | 27 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtPdfWidgets classe... |
cda668d7fa2699ac4dbfb983ef1a5d4a898d178b3c9a939c0954d7b298349dc6 | Python | 760 | 22 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from .predict import YOLOEVPDetectPredictor, YOLOEVPSegPredictor
from .train import YOLOEPEFreeTrainer, YOLOEPETrainer, YOLOETrainer, YOLOETrainerFromScratch, YOLOEVPTrainer
from .train_seg import YOLOEPESegTrainer, YOLOESegTrainer, YOLOESegTrainerFro... |
f4fd513b1bc56dc62fd2876fb31dcc5859cf8d16dd9df324a546f975826389fa | Python | 760 | 27 | # Copyright (c) DP Technology.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from functools import lru_cache
from unicore.data import BaseWrapperDataset
class KeyDataset(BaseWrapperDataset):
def __init__(self, dataset, key):
se... |
64076de9be82d9e547d0077a3cb274a79642eef3ab04a10b70de5a91d9747693 | Python | 761 | 32 | from setuptools import setup, find_packages
setup(
name="ouroboros",
version="0.1",
packages=find_packages(),
install_requires=[
'six==1.17.0',
'tqdm==4.67.1',
'dill==0.3.9',
'pyarrow==19.0.0',
'pandas==1.5.3',
'scipy==1.13.1',
'matplotlib==3.9.4'... |
bbd7897862882baa42ff426b48bafed3b22151a27424248feefbdce99bf3f32c | Python | 761 | 31 | import os
import numpy as np
from typing import Union, Sequence, Callable, List, Optional
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import napari
PathOrPaths = Union[str, Sequence[str]]
ReaderFunction = Callable[[PathOrPaths], List['napari.types.LayerData']]
def get_reader(path: "PathOrPaths") -> Optiona... |
ce650178adb363a19d1763b7c648c49a08f1d631dcf614b14f62d846bb706bca | Python | 761 | 14 | from brainscore_vision import model_registry
from brainscore_vision.model_helpers.brain_transformation import ModelCommitment
from .model import get_model, get_layers
# region_layer_map intentionally omitted -> framework auto-selects the best candidate
# layer per region (V1/V2/V4/IT) via LayerSelection on the public ... |
12f9680e35e48230f388971f2c640327074d7811b7d3386187edb928f8bf80f4 | Python | 762 | 41 | #!/usr/bin/env python
"""
Pass through blocks from a maf file until a certain number of columns
have been passed.
usage: %prog -c cols < maf > maf
"""
import sys
from optparse import OptionParser
from bx.align import maf
def __main__():
parser = OptionParser()
parser.add_option("-c", "--cols", action="sto... |
31556d03da92096688c4e2736fe8d96d7367a118218768afeb4e8ef654374bb3 | Python | 762 | 49 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from .model import (
Annotation,
Annotation2D,
AnnotationReference,
AnnotationReferenceType,
AnnotationType,
AttributeSpec,
Cuboid,
Dataset,
Ellipse,
Interval,
Label,
LabelCatalog,
Mask,
Points,... |
64902e927143eb2b128a7c2248b97a9c5bb045f9a6a39ff6d76fc687d0277d2d | Python | 762 | 26 | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides low-level multimedi... |
efc056581e8131fd51b0c8b5d555402f04184986c8a67b71d5b68c2655813ec8 | Python | 762 | 25 | #!/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... |
5cbd0c4698ebcfcdf54458a4bfd2ad04ec776b3d683621f9c3f9b752cc0bc5e3 | Python | 763 | 40 | from datetime import datetime
from typing import NamedTuple
import matplotlib.pyplot as plt
import numpy as np
class RigScreenCalibrate(NamedTuple):
rig_type: str
screen_type: str
date: datetime
value: np.ndarray
RIG_1 = RigScreenCalibrate(
'rig1',
screen_type='asus',
date=datetime(year... |
15d4327bc9ccfc3d4b4c1583fe94bdc24c29771cabe7886ec0c5d200adad98c5 | Python | 764 | 29 | """# Quantities with pint
Pint is a Python package to define, operate and manipulate physical quantities:
the product of a numerical value and a unit of measurement.
It allows arithmetic operations between them and conversions
from and to different units.
https://pint.readthedocs.io/en/stable/
"""
try:
from pint ... |
2e0fe44fb30d70cf64fa61f514588e905c09769a810e8b32eae7661df98f9ced | Python | 764 | 21 | from __future__ import annotations
from pathlib import Path
import pytest
from labelme import _locale
from tools.artifact_install_smoke import _check_packaged_resources
def test_check_packaged_resources_rejects_corrupt_translation(
*, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# A truncated... |
442ed8d0f4e52fc19da2d49f244053946d33eb58da81da3055911f617248392d | Python | 765 | 19 | import math
def scaled_kaiming_init(data, fan_in, scale=1):
kaiming_bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
data.uniform_(-scale * kaiming_bound, scale * kaiming_bound)
def half_kaiming_init(data, fan_in, scale=1, bounds=None):
kaiming_bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
if... |
631c12af0d580a464c4f306235b30c88d7ec60db995cf50d64ef2fd8084963e4 | Python | 765 | 25 | # Created by David Coggan on 2024 06 26
import pytest
from pytest import approx
from brainscore_vision import benchmark_registry, load_benchmark
from brainscore_vision import load_model
@pytest.mark.parametrize('region', ['V1', 'V2', 'V4', 'IT'])
def test_benchmark_registry(region):
assert f'tong.Coggan2024_fMRI... |
b1a3af9fcde4e265993ed117ea2f607df7af4f29c2293d7e70581015ac2895c6 | Python | 766 | 24 | """Tests for mcmlnet.training.optimization.optimizer module."""
import os
import pytest
import torch
from dotenv import load_dotenv
from hydra import compose, initialize_config_dir
from mcmlnet.training.optimization.optimizer import main
load_dotenv()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUD... |
400862243af4d64d702395ac5c4f78e7e3add64e52ba9211f48633d2c766b9ea | Python | 767 | 28 | import numpy as np
class TestIVIMFit2D:
def __init__(self):
self.b_values = None
self.signals = None
self.supervision = {'D': None,
'Dp': None,
'f': None,
'S0': None}
@staticmethod
def estimation_... |
51ffe50409a72200d90df2c3afc3ccdc351ed5bf156070c813ef1e6648a2c560 | Python | 767 | 23 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import numpy as np
import torch
from segment_anything import sam_model_registry, SamPredictor
class ModelHandler:
def __init__(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.sam_checkpoint... |
5c7aa3029a35baa9c9e32304f4cdf741bd32978120e913128bcfe200a02f880b | Python | 767 | 33 | import os
_DEFAULT_ROOT_DIRNAME = "CellAgentChat_outputs"
_SUBDIRS = {
"models": "models",
"conversion_rates": "conversion_rates",
"cci": "cci",
"perturbation": "perturbation",
"distributions": "distributions",
}
def _project_root():
return os.path.dirname(os.path.dirname(__file__))
def ar... |
1eb5133f00f148d3f3750ebd01ce4e7fdaf8e4df08f5adbccc41c27260c8b150 | Python | 768 | 28 | #!/usr/bin/env python3
import arbor as A
from arbor import units as U
import matplotlib.pyplot as plt
# Create a single segment morphology
tree = A.segment_tree()
tree.append(A.mnpos, (-3, 0, 0, 3), (3, 0, 0, 3), tag=1)
# Create (almost empty) decor
decor = (
A.decor()
.paint("(all)", A.density("hh"))
.p... |
cd148c3bec2eb4991ff4885e207429513514b763be7083cc8d1e8647dcaac47a | Python | 769 | 25 | from psychopy import event
from psychopy.constants import FINISHED, PLAYING
def sleeping(win, pink_noise):
sleeping = True
while sleeping:
win.flip()
keys = event.getKeys()
if pink_noise.status == FINISHED:
pink_noise.seek(0)
pink_noise.play()
if "space"... |
facb0105e9df8a77e6bf84df2cb22e2eb47bd928bf460ebbb8b48979b5657d4d | Python | 769 | 24 | from sklearn.ensemble import RandomForestClassifier
import torch as th
import sys
sys.path.append("..")
sys.path.append("../..")
from utils import set_global_seed
from utils.eval import evaluate_on_all_metrics
def train():
train_data = th.load("train_data.pt")
train_label = th.load("train_label.pt")
valid_... |
6254dc8680bd22f5fe38d289e33b8bd0b27c172b3e096af65d1735646f290943 | Python | 770 | 21 | import warnings
warnings.filterwarnings("ignore", message="It is not recommended to directly access")
import torch.nn as nn
from .MultiHeadAttentionFusion import MultiHeadAttentionFusion
class EnhancedFusionModule(nn.Module):
def __init__(self, feat_views, feat_dim, num_heads=4, fusion_type='concat', device=None)... |
c7a512f89adec02ced06c88ed7c3752ebf3c12d853ad9d6167d6abc63379a002 | Python | 770 | 25 | from pathlib import Path
from typing import Final
from augment_images import perform_augmentation
INPUT_ROOT: Final[Path] = Path(R'D:\TexturesKTH-44-48-60\3')
OUTPUT_ROOT: Final[Path] = Path(R'D:\TexturesKTH-44-48-60-Augmented')
RES: Final[int] = 112
# NUM_AUGMENTATIONS: Final[dict] = {'1': 10, '2': 5, '3': 10}
NU... |
09d5c98e44c3cab8d16ee61eb9542932e16f5b353fee15873980f28f0679c5f4 | Python | 771 | 34 | # Written by Yixiao Ge
import warnings
import faiss
import torch
from ..utils import to_numpy, to_torch
__all__ = ["label_generator_kmeans"]
@torch.no_grad()
def label_generator_kmeans(features, num_classes=500, cuda=True):
assert num_classes, "num_classes for kmeans is null"
# k-means cluster by faiss
... |
204d78172279c172c6584fcf7c3617a6d0d1ff286316c064acd4bf1e92dc3312 | Python | 771 | 27 | # -----------------------------------------------------------------------------
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# ----------------------------------------------------------------------... |
320833cfae087b0a0ffb50793e321cf672ede5896f14802defb98e4c88f300e9 | Python | 772 | 31 | import argparse
import os
import os.path as osp
import time
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.metrics import f1_score
import pandas
import json
import torch_geometric.transforms as T
from torch_geometric.nn import ChebConv, GCNConv # noqa
from tqdm import tqdm
import ijson
pa... |
9892fadca50e03a2156279a4476f93600971822adab8f10c461687fd071d7dc5 | Python | 772 | 17 | import unittest
import base
class Test(base.BaseScriptTest, unittest.TestCase):
command_line = "./scripts/maf_extract_ranges.py ${inverval_file} 0"
input_inverval_file = base.TestFile("80082367 80083066")
input_stdin = base.TestFile(filename="./test_data/maf_tests/mm8_chr7_tiny_no_index.maf")
output_... |
d2c6b57156230a8f1eb190505be71370b05c0f2659d5669588c85f6934b2415b | Python | 773 | 26 | import sys, os
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
base_path = os.path.abspath(".")
exe_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else base_path
if base_path not in sys.path:
sys.path.insert(0, base_path)
from ui.welcome_window import WelcomeWindo... |
456136de28ebb1921bb7cca39e3f53852dea2c1e5b7b53205db0526ebf66e6a9 | Python | 774 | 28 | import setuptools
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setuptools.setup(
name="YMS",
long_description=long_description,
long_description_content_type='text/markdown',
version="1.2.14",
author="Yarin Bekor, Shan... |
5c0078c5b7fd5180e02715fb0c78d9baca53959661ea186bad0c08acd40193b1 | Python | 774 | 31 | import os
from lasagna.utils.path_utils import getHomeDir
def get_lasagna_pref_dir():
"""
Returns the path to lasagna preferences directory.
If it does not exist it creates it and then returns the path
"""
pref_dir = getHomeDir() + '.lasagna'
if not os.path.exists(pref_dir):
os.makedi... |
cac5a229d6b10a90e33623668fe694a1f7ccbad91540b11fcd8d42b635a5c374 | Python | 774 | 24 | #!/usr/bin/python3
import sys, os
if getattr(sys, 'frozen', False):
bundle_dir = sys._MEIPASS
else:
bundle_dir = os.path.dirname(os.path.abspath(__file__))
print( 'bundle dir is', bundle_dir )
print( 'sys.executable is', os.path.dirname(sys.executable) )
print(f"Arguments count: {len(sys.argv)}")
for i, arg i... |
d02a9a2e3bf8ce9d3480822c4c53b23f8b0d6af385c3c7fa8eb882bebb8b6067 | Python | 774 | 17 | # Image Paths - FIXED (low-res) and MOVING (high-res)
FIXED_IM_PATH = '/hdd/yang/data/kidney_seg/LADAF-2020-27_left/25.08um/normalised'
MOVING_IM_PATH = '/hdd/yang/data/kidney_seg/LADAF-2020-27_left/2.58um/normalised'
FIXED_RES = 25.08
MOVING_RES = 2.58
REGISTRATION_LIST = '/hdd/yang/code/hipct_registration/registrati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.