sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
86ab4def8348054ceea6d2558b239417c64bd97e910c3285f8a512cb9fd67263
Python
2,223
89
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil from glob import glob from vlpp.utils import gzipd, run_shell, run_matlab, TPL_PATH PARTICIPANT = "${participant}" def seg_spm12(img, spmDir): for d in ["mask", "transform"]: os.mkdir(d) tags = { "anat": gzipd(img), ...
a3c287e15eab358d38ddce999f855268bbc013e897e9ebe0639cfe21be1f4162
Python
2,225
70
from torch import nn import torch.nn.functional as F ''' https://blog.csdn.net/yiran103/article/details/100063021 ''' class BlazeBlock(nn.Module): def __init__(self, inp, oup1, oup2=None, stride=1, kernel_size=5): super(BlazeBlock, self).__init__() self.stride = stride assert stride in [1,...
dfa1f98abbdce3fbd5681f184dcdbad3df02abeb067810822d6defe00b2dc133
Python
2,225
63
import logging from pathlib import Path from .. import common, config from .. import predict as predict_module from ..common.logging import config_logging_for_cli, log_version logger = logging.getLogger(__name__) def predict(toml_path): """make predictions on dataset with trained model specified in config.toml ...
0ebfd80053341917620e7c07debbf8e897f9f4fddbec34c9af8178736e9bc3a7
Python
2,226
79
# Copyright (c) Facebook, Inc. and its 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. # author: adefossez import math import torch as th from torch.nn import functional as F def sinc(t): """sinc. :...
7ca4395bfebb5c0d0f4b0a38b08ccc6ffbddca03e8794ff099b76e0ebf7c8f13
Python
2,227
73
import jax import jax.numpy as jnp import numpy as np from folx import ForwardLaplacianOperator jax.config.update('jax_enable_x64', True) def brute_force_laplacian(fn): def laplacian(x): H = jax.hessian(fn)(x) f = jax.grad(fn)(x) return jnp.trace(H), f return laplacian def test_de...
0a84bdc91d20a8e5f687a4e634948bade59304f77a3588e987687d2039408a47
Python
2,228
82
""" Utility functions to manipulate image data. """ import cv2 import numpy as np import dask.array as da def normalize(image: np.ndarray) -> np.ndarray: """ Normalize an image to the range [0, 1]. Parameters: image (np.ndarray): The input image. Returns: np.ndarray: The normalized image. """ retur...
364631a1faa11ae55d05567396806fcc63758222f486c7a641b1ead3193c44e7
Python
2,229
79
import os from copy import deepcopy from os.path import dirname import numpy as np base_dirname = dirname(dirname(__file__)) filename = os.path.basename(__file__) task = 'classification_binary' selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv' data_base = {'id': 'ALL', 'type': 'prostate_paper', ...
ba4983630490dfb3187a8e077fed8b327102e79b09e157e34f3466e2fa2c9f70
Python
2,229
78
"""`d3text.excepthook`: the context an exception carries must reach the user. `add_note` is where this package puts the line that names the file or the setting a third-party exception could not name itself. stackprinter's hook renders only the traceback, so on the console -- the one path those notes were written for -...
e97ecc828a2fca105c2a04f848dbf20fbc1a052f2a7104c481dd5d968c3e3128
Python
2,231
53
## Wrapper for crystalgrw.cli.evaluate.main ## import argparse import torch import torch.multiprocessing as mp from crystalgrw.cli.evaluate import run_eval def main(rank, world_size, cfg): run_eval(rank, world_size, cfg) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument(...
c1009119d0b1253b4ce5b7363101ad9ccf94e59d2ef41230dbed8f46528b7675
Python
2,236
73
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created template # Author_and_contribution: Thomas Chartrand; created script import argparse parser = argparse.ArgumentParser(description="Calculate Matthew's correlation coefficient (scikit-learn)") parser.add_argument( "-l", "--labels...
6453f34411e55fd85b92f9e3153625773738cf16433c4589d0e517c0f0335b56
Python
2,238
76
import gradio as gr import os from utils.foldseek_util import get_struc_seq ROOT_DIR = __file__.rsplit("/", 3)[0] #################################################### # gradio blocks # #################################################### def upload_pdb_button(visible: bool = True...
fba1a086e23a8b4da6bc2ca948a4e8996878791dabd39f84f84598e343d0d433
Python
2,238
100
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
05f47cd2523fba9028a9bdf745c39c3a41d0aca86d4d0c1e692628ab8d68e54b
Python
2,240
66
# # Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with # Sandia Corporation, the U.S. Government retains certain rights in this software. # # See LICENSE for full license details # from ..idevice import EmptyDevice from ...backend import ComputeBackend xp = ComputeBackend() c...
5420f16d5f55e822003eee066c0d8b84d43850c2974cdae968863046d82df854
Python
2,240
65
from ... import options as opts from ... import types from ...charts.chart import Chart from ...globals import ChartType class Liquid(Chart): """ <<< Liquid >>> The liquid chart is mainly used to highlight the percentage of data. """ def __init__( self, init_opts: ...
88d6837eb0b83ded1b972033e1ea8eb97208d73ce6b8acb42fd041d176cb7efc
Python
2,241
63
# 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. """ TODO (huxu): a general fairseq criterion for all your pre-defined losses. """ from fairseq.criterions import FairseqCriterion, register_c...
c9bb4373d2b9fd6070fedf730eb4db50895f47ad0c6d641af85f2d188ef098d9
Python
2,241
71
from argschema import ArgSchemaParser import os import logging import subprocess import time import shutil import numpy as np import io, json, os from .create_settings_json import create_settings_json from ...common.utils import get_repo_commit_date_and_hash def run_npx_extractor(args): print('ecephys spike so...
f6fe7befbf0ed64a678adc10b636d5f3f3254ad0710157260b3014eaa20f1ea2
Python
2,241
68
"""Implementation of utilities to load a pretrained Enformer model in Trix.""" from typing import Callable, Tuple import haiku as hk import jax.numpy as jnp from nucleotide_transformer.enformer.features import FEATURES from nucleotide_transformer.enformer.heads import UNetHead from nucleotide_transformer.enformer.mo...
5d0788ae33d7f06521359c638d68bfd1eefda48d3465d168a7c0cd8cedd70cf6
Python
2,242
63
import jax.numpy as jnp import pytest from oneqmc.types import Nuclei from oneqmc.wf.orbformer.orbitals import generate_spd_orbitals @pytest.mark.parametrize( "nuclei,max_charge,max_orbitals,expected", [ ( # H2 Nuclei(jnp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), jnp.array([1.0, 1.0]), ...
6719cf28b26ba5a42a5c419d90f4e4dce6716d10db9e756addea82189a05d02f
Python
2,242
73
import cv2 import time import glob import numpy as np import cmapy import time import cv2 from PIL import Image from msi_visual.normalization import spatial_total_ion_count, total_ion_count, median_ion from sklearn.metrics.pairwise import pairwise_distances import numpy as np def core_sets(data, Np): ...
174403a6db90cc18a5a179e55fae1fa838549d5a2626cde71b038baed604c1d7
Python
2,244
73
import numpy as np import argparse from celltype_ibl.models import mlp_classifier as mlp_probe from celltype_ibl.utils.ultra_data_util import get_ultra_wvf_acg_pairs from celltype_ibl.params.config import ULTRA_DATA_PATH import os import re def extract_seed_and_epoch(checkpoint_path): # Use regular expressions to...
8909500d6dd8e677ecee5f5c591a45c57433932bc38b6eaf494d8cfa23c3a29f
Python
2,245
61
# # Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with # Sandia Corporation, the U.S. Government retains certain rights in this software. # # See LICENSE for full license details # from .idac import IDAC from .quantizer_dac import QuantizerDAC, SignMagnitudeDAC class DAC(IDAC)...
1d31fca84fd531a7a5073f45f78abe92d5718d09e021a762ef823e6a9cef6a5d
Python
2,247
72
"""Bidirectional GRU on counts matrix.""" import warnings import torch import medaka.architectures.base_classes as base_classes class GRUModel(base_classes.CountsMatrixModel): """Implementation of bidirectional GRU model in pytorch.""" def __init__( self, num_features=10, num_class...
97c9497f1055e393be35a7272ced59bfb7155b8a9421ea71be920f81000976da
Python
2,247
70
from argschema import ArgSchemaParser import os import logging import time import numpy as np import pandas as pd from ...common.utils import load_kilosort_data from .extract_waveforms import extract_waveforms, writeDataAsNpy from .waveform_metrics import calculate_waveform_metrics def calculate_mean_waveforms(args...
dffff59263a9600c65bc327feb9a09755c91fe397dbc5f9625ed05d59906e10d
Python
2,247
79
import os from copy import deepcopy from os.path import dirname import numpy as np base_dirname = dirname(dirname(__file__)) print(base_dirname) filename = os.path.basename(__file__) task = 'classification_binary' selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv' data_base = {'id': 'ALL', 'type':...
e0fee1478fd7a3076b0032487719a0ec3e99e9021f08bd227ab3b34257884b49
Python
2,247
79
import torch import wandb from utils.data.dataholder import DataHolder from utils.data.misc import to_batch def training_step_func(self, data: DataHolder, i: int) -> torch.Tensor: """ Training step: based on node-level conditional point cloud diffusion model Parameters: - data: input data batch ...
fc4ce7e088b0d261fea7d2b478cd181dac97b27b929226ec670b0e9ae58eebec
Python
2,251
79
import os C4_COLORS = { "PkC_ss": [28, 120, 181], "PkC_cs": [0, 0, 0], "MLI": [224, 85, 159], "MFB": [214, 37, 41], "GrC": [143, 103, 169], "GoC": [56, 174, 62], "laser": [96, 201, 223], "drug": [239, 126, 34], "background": [244, 242, 241], "MLI_A": [224, 85, 150], "MLI_B":...
0ad1781aaa2ff69b6146bb6bce04e493d17dbc7ecc560a0907b59c38b64f43ca
Python
2,252
54
"""Shared pytest fixtures for the pgmpy test suite. Example models and datasets are normally fetched from Hugging Face through ``pgmpy.utils.hf_hub.read_hf_file``. To keep the test suite self-contained and free of network access, the autouse fixture below redirects that single byte-fetch seam to local fixture files co...
0b2c838b2ce494f2f300cd39393d8eb3597a8fd63c484b6b47c5bf9981cd17df
Python
2,252
65
from os.path import join import matplotlib.patches as mpatches import numpy as np import pandas as pd from matplotlib import pyplot as plt from scipy.optimize import curve_fit from config_path import PROSTATE_DATA_PATH from setup import saving_dir def sigmoid(x, L, k, x0): b = 0. y = L / (1 + np.exp(-k * (x...
495e5b0b16d0a461c986edc896e659d55ba4024015baeac3cafbfd8f5a2ec67a
Python
2,253
81
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os from fairseq import options from examples.noisychannel import rerank_options, rerank_utils def score_lm(args): using_nbest =...
b134144c1497488746d7d4a08ec47f3206378c06880e742a11638a0f211022ab
Python
2,253
77
import time import RPi.GPIO as GPIO class mainprogram: #Main while loop condition keepalive = True #DEFINE NUMBER OF BUTTONS AND ORDER IN ARRAY buttonarray = ['movefast','moveslow','buttontohome','relativeALL','relativeAP','relativeMV','relativeDV','buttonaction','miscbuttonC','miscbuttonD','miscbutto...
7c4cf2cd950c7f443b64f577b57aafc927af801bb0fe8188e9fc33e17227e0b1
Python
2,254
32
"""Utilities for machine learning on genomics data. See README for a brief description of the programs, See the documentation (which you can build) for a specification, and see doc/demos/osknExample.ipynb for a demonstration notebook. """ # Version specification: # Versions are named as [major].[minor].[patch] # A m...
771a60ee033eb0fb48037fc82684b2b7f2ac6936da65201dade68a7545bcd055
Python
2,255
58
#!/usr/bin/env python3 """Preprocess Simulation raw data only (no training loop).""" from __future__ import annotations import argparse import os import sys from pathlib import Path from hydra import compose, initialize_config_dir from omegaconf import OmegaConf ROOT = Path(__file__).resolve().parents[...
51e2c14270b5bb7ab74ae381fa80619544b403b320644c7d033337805de76429
Python
2,257
77
from collections import namedtuple from math import ceil from typing import Optional import jax import jax.numpy as jnp __all__ = () EWMState = namedtuple("EWMState", "step params buffer mean var sqerr", defaults=6 * [None]) # type: ignore def init_ewm( max_alpha: float = 0.999, decay_alpha: float = 10.0,...
d35edd67706448d49c79ddce2f9255652b2457914ac22bad7a7042468eb01e21
Python
2,257
65
__author__ = 'Robbert Harms' __date__ = '2017-06-19' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class PlottingFrame: def __init__(self, controller, plotting_info_viewer=None): super().__init__() self._controller = controller self._plotting_info_...
8cc59e445d6bacedad317cbce859e5e426720394f7f4b3a04d0564c6275504da
Python
2,259
61
# 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 typing import Dict, Optional import torch import torch.nn as nn import torch.nn.functional as F from fairseq import utils from torch imp...
17c1786a87e0c4a069893bccb643a811cc2647dc78b1b7c4a68ba107807dd014
Python
2,260
71
#!/usr/bin/env python3 # -*- encoding: utf8 -*- import argparse import itertools import os import re import sys from pathlib import Path import whisper from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument("--wavs", type=str) parser.add_argument("--lids", type=str) parser.add_argument("--dst"...
74b98fe8d4482a06bc124240d9b8b9aa5ef6010d704279da5214f24c94cac0d4
Python
2,260
85
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [ # "ngff-zarr[tensorstore]", # "numpy", # "tensorstore", # ] # /// import os import pathlib import shutil import zipfile import ngff_zarr as nz import numpy as np import tensorstore as ts THIS_DIR = os.path.absp...
977249c954ea03650094b1bda3dc05a03cbdcf553b01838b5796ff090906b857
Python
2,260
77
import itertools import joblib import numpy as np import pandas as pd import os import unittest from numpy import testing from sklearn import datasets, preprocessing #from matplotlib import pyplot from mentor import _cluster as cluster from mentor import _datasets as datasets from mentor import _metrics as metrics fr...
3ee56b5dc267d0e244fdc540de1de483e4aaa1ad08c1fa227c13e945100e7207
Python
2,262
66
from ... import options as opts from ... import types from ...charts.basic_charts.geo import GeoChartBase from ...commons.utils import OrderedSet, JsCode from ...exceptions import NonexistentCoordinatesException from ...globals import ChartType class LMap(GeoChartBase): """ <<< LMap(leaflet) coordinate system...
709c619e15ab154f4504e490a0c860d291ca38ed7719583faa0d56812a054b1f
Python
2,262
65
from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score import numpy as np import pandas as pd from tqdm import tqdm import warnings warnings.filterwarnings('ignore') from .encode_structure import * from .model import * from .utils import * import pickle def get_contact_data(da...
268fe01459dc29d13a0b8f391abedfe7841bb93fd3d82934d236e3fa3b17fd7a
Python
2,264
57
# @license # Copyright 2021 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
d0d038d81819fec71414bfdfe0533a0b257b427507889e7c4049a31f6e8f60c9
Python
2,264
82
#!/usr/bin/env python3 -u # 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. """ Implement unsupervised metric for decoding hyperparameter selection: $$ alpha * LM_PPL + ViterbitUER(%) * 10...
e3745374b508d248f155879182105abcfabcfe752ce42897c532c68492ca048c
Python
2,265
68
from torch.utils.data import DataLoader import lightning.pytorch as pl from typing import Union, Optional from pathlib import Path from rinalmo.data.alphabet import Alphabet from rinalmo.data.downstream.ribosome_loading.dataset import RibosomeLoadingDataset from rinalmo.utils.download import download_ribosome_loadin...
d0915ae1b78d0db68f30cc3f336b24de28ff0a7a6b6bc2b111ea2a51734522ad
Python
2,267
57
import torch import torch.nn as nn import torch.nn.functional as F from core.modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d class Decoder(nn.Module): def __init__(self, num_classes, backbone, BatchNorm): super(Decoder, self).__init__() if backbone == 'resnet' or backbone == 'drn'...
0573efa2caea1a24fd584a9368fb9f480734e84eef5e60e7c059a45fbe77bdeb
Python
2,268
81
# -*- coding: utf-8 -*- import os from glob import glob from .utils import run_shell, gzipd, run_matlab, TPL_PATH def applyWarpImageMultiTransform(_input, ref, mat, output=None): if not output: output = "tmp.nii.gz" cmd = "WarpImageMultiTransform 3 {0} {1} {2} -R {3} --use-BSpline" run_shell(cmd...
5e3b287d103c3f2da94d8cab00893365f78ff97d3b5687d89401002ea263f7f0
Python
2,268
64
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import csv from pathlib import Path def main(args): """ `uid syn ref text` """ in_root = Path(args.generation_root).resolve...
724f0bb92ffb7629c3e45a56a7aea4e0d4ef7d299634ddf7b3d018acc3acbbe0
Python
2,268
70
"""Save and load behaviour settings between a DataFrame and JSON.""" import json import logging import os from typing import Any import pandas as pd logger = logging.getLogger(__name__) def save_behaviour_static_inputs(dataframe: pd.DataFrame, filename: str | os.PathLike[str]) -> None: """Save behaviour settin...
b027e15d0f3b7f9a633fe7e978e3e9e136caba336fd9c17e47bb3f0019d650f1
Python
2,268
93
import argparse from pathlib import Path import anndata import scanpy as sc from anndata import AnnData import novae MIN_CELLS = 50 DELAUNAY_RADIUS = 100 def preprocess(adata: AnnData, compute_umap: bool = False): sc.pp.filter_genes(adata, min_cells=MIN_CELLS) adata.layers["counts"] = adata.X.copy() sc...
a2a15e1e8e3854947b1ab9c45783ec5f7e492e24f88132a5c10e11432d7f54a5
Python
2,269
68
""" Run before training: dataset task gate, model task×dataset gate, and a forward shape dry-run. Standalone package: Simulation + unet + dynamic_segmentation_CID only. """ from __future__ import annotations from typing import Union import torch from omegaconf import DictConfig from models.build import ...
c480a70ffb70ced3a9623e5728b33f76f7e2c41869342f57933ca450f5b511e8
Python
2,271
48
import pandas as pd from preprocessor.MembraneCurrentPreprocessor import MembraneCurrentPreprocessor from preprocessor.AxialCurrentPreprocessor import AxialCurrentPreprocessor class Preprocessor: """ Represents a class responsible for preprocessing simulation data to prepare and transform current data (me...
2363af683f41201cde86d78c8038134c150de762495bf7acd085163a9803d6d4
Python
2,273
55
import os import threading from configparser import ConfigParser from . import credentials_provider from .futures import run_on_new_thread class BossCredentialsProvider(credentials_provider.CredentialsProvider): def __init__(self): super().__init__() self._lock = threading.Lock() self._cr...
e0d54e5f3e2b2566caabe42b434ad3d413639c3a00d51c6b57518fa74704ec27
Python
2,275
73
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from importlib import import_module @dataclass(frozen=True) class AppDefinition: app_id: str label: str module_path: str | None class_name: str | None qt_supported: bool = False descripti...
5cead3508445e508599dc8cd6c3468f1a1f7c56ccc5300b50b03203726db9f7d
Python
2,276
83
from __future__ import annotations from typing import TYPE_CHECKING from typing import Any import pytest from poetry.publishing.hash_manager import HashManager if TYPE_CHECKING: from pathlib import Path from pytest_mock import MockerFixture from tests.types import FixtureDirGetter @pytest.fixture d...
7f9626178f674ead0aa7a72281900b03e93abd9aa40f7eca48461e1130b02590
Python
2,276
66
#!/usr/bin/env python """ This script will query a SMRTLink instance based on a provided set of credentials, and pull a variety of run metrics for longitudinal tracking. Notably, if an output file of the same name exists, it will filter results by existing metrics to enable it to run quickly as new runs are introduced...
5c4dfd626ec078946258570c53caa63cab02dd442a7086ed36cb7f9821b4a101
Python
2,277
62
"""Tests for vak.predict.predict module.""" from unittest import mock import pytest import vak.cli.predict import vak.config import vak.common.constants import vak.common.paths @pytest.mark.parametrize( "audio_format, spect_format, annot_format, model_name, predict_function_to_mock", [ ("cbin", None,...
8a2db7e5439ec485d9b0ae56456e3d064be51dbc812a74078055b79584c4faae
Python
2,277
65
import numpy as np import pytest import torch import scvi.external.velovi._module as velovi_module_module from scvi.data import synthetic_iid from scvi.external.velovi import VELOVI from scvi.external.velovi._module import VELOVAE @pytest.mark.optional def test_velovi(): n_latent = 5 adata = synthetic_iid() ...
20b8761a006b72640cbf3d20f703c1cc842c3891b52a5983fe60144774abb873
Python
2,279
67
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
a1e064629813d00c3f84074ac3b5c0a11c46b69ede0ecc9041d328cbdf68d30f
Python
2,280
77
import pandas as pd from pgmpy.base import DAG from pgmpy.datasets._base import BaseSimulatedDataset from pgmpy.models import LinearGaussianBayesianNetwork class LinearGaussianSCM(BaseSimulatedDataset): """ Simulates a dataset from a random Linear Gaussian SCM. The random graph and its Gaussian paramete...
7359cd003126bd30f516e267717b295a407f5f2b2c905d59f6296cc503c09a65
Python
2,281
78
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
00c07c86463faec14b481203c9a630320388f7e3d33b7bda1b05ca3570315f38
Python
2,283
63
# This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import shutil import tempfile import unittest from typing import Optional class TestFileChunker(unittest.TestCase): _tmpdir: Optional[str] = None _tmpfile: Optional[str] = Non...
88579fb7a638b639d7b2b617eaf1a7c477bcacd0dc13dcec34cde57874e6dfac
Python
2,283
71
#!/usr/bin/env python import sys import os import numpy if "DEBUG" in sys.argv: sys.path.insert(0, "..") sys.path.insert(0, "../../") sys.path.insert(0, ".") sys.argv.remove("DEBUG") import unittest from metax.DataSet import DataSet from metax.DataSet import DataSetFileUtilities from metax.DataSet im...
1c18e15730f36196d044944ae351e9e9bbb295d704230dd414943b7334c7b399
Python
2,284
75
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import contextlib import logging import numpy as np from fairseq.data.data_utils import numpy_seed from . import BaseWrapperDataset logger...
74347da7855e81c5a2632890bf9047f3abd4b37a65e093daf04dccd2580ea36a
Python
2,285
85
from __future__ import annotations import pytest from poetry.utils import patterns @pytest.mark.parametrize( ["filename", "expected"], [ ( "markdown_captions-2-py3-none-any.whl", { "namever": "markdown_captions-2", "name": "markdown_captions", ...
9f0e41a72a15a7c9007a4b06a40455eb35b6e4956a793612fa9fdb7f5110e0f7
Python
2,287
71
import os.path as op from fetpype.pipelines.full_pipeline import ( create_full_pipeline, create_rec_pipeline, create_seg_pipeline, create_surf_pipeline, ) from fetpype.workflows.utils import ( init_and_load_cfg, ) import pytest import itertools # 1. initialize will add config_path the config search...
a919c59ab6a625521bc00a1ef58d6ff41fa63e002ccbd2a94d7b86a931a3f01b
Python
2,287
85
from screeninfo import get_monitors import tkinter as tk def center_window_on_screen(window): """ Center a Tkinter window on the screen. Parameters: - window (tk.Tk|tk.Toplevel): The window to center. """ window.update_idletasks() # Update "idle" tasks to get updated dimensions x, y = w...
80168784e22232598c06d7ad459aa44c1cf326c1ac4bf8a90e7e5e9ef5c6315e
Python
2,288
70
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import logging from pathlib import Path from collections import defaultdict import pandas as pd from torchaudio.datasets impo...
e2259b3bd5b19d9235a786e8e3fa94e7dde0251ac82d0fccfd01893c976bbfc2
Python
2,289
73
#!/usr/bin/env python # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
50d3824b1927ddc1f8860ad075faeb63bd97f859ce3369eefefab168679e4b81
Python
2,290
59
import igraph as ig import leidenalg import numpy as np from scipy.sparse.csgraph import connected_components from scipy.stats import mode from sklearn.neighbors import NearestNeighbors from sklearn.preprocessing import LabelEncoder import loompy class PolishedSurprise: def __init__(self, min_cells: int = 20, graph...
2d3b47a8aefa5b89dd76c3057dd9d690b81ce734f388c20380abde44601fa553
Python
2,291
65
from collections.abc import Hashable import numpy as np from pgmpy.structure_score.log_likelihood_gauss import LogLikelihoodGauss class BICGauss(LogLikelihoodGauss): r""" BIC structure score for Gaussian Bayesian networks. This score penalizes the Gaussian log-likelihood to discourage overfitting. The ...
4519dbe77d8b2588672434cac42ca256932c1d714ed3ada3bbed6d27764f3e75
Python
2,291
57
from typing import Sequence import jax import numpy as np from ..molecule import Molecule from .analysis import ScoreMatchingDensityModel, get_dft_grid from .operators import AutoDiffDerivativeOperator, NumericallyStableKSPotentialOperator def create_npz_density_file( density_model: ScoreMatchingDensityModel, ...
9c489c67ff733b1a9f09c7a2ec484fb17151e243810f34df0e8c09cacc51e11f
Python
2,291
74
from collections import OrderedDict import torch import spacestream.models as models def get_slowfast_model(arch_name, trained, **kwargs): """ Inputs: arch_name : (string) name of deep net architecture. trained : (boolean) whether or not to load a pretrained model. Outputs: mo...
7147ef15f5d03779b7c7dfd1f43ffb2adfd888bfb257a4a2436de2c5c7e4b902
Python
2,292
67
import glob import os from PyQt5.QtCore import QObject, pyqtSignal from mdt.gui.utils import UpdateDescriptor __author__ = 'Robbert Harms' __date__ = "2015-08-20" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class SharedState(QObject): state_updated_signal = pyqtSignal(str) def __init__(...
9b2013b58bb678e12dd567b140af3e4ebaf50301dc01506466f614e6b81352ff
Python
2,292
87
from __future__ import annotations from typing import TYPE_CHECKING from typing import Any import pytest from poetry.core.packages.package import Package from poetry.__version__ import __version__ from poetry.factory import Factory from poetry.repositories import RepositoryPool from poetry.utils.env import EnvManag...
12dcb8461fe1a604a9b56d8cd7c8659a9e4f0d08c55f9757ef9f8352f9b828d9
Python
2,293
69
"""A paper curated under several BRENDA references is split as one paper.""" import importlib.util import pathlib from brenda_references.sampling import SPLITS, entity_holdout_splits _SCRIPT = ( pathlib.Path(__file__).resolve().parents[2] / "scripts/generate_splits.py" ) def _load_generator(): """The gener...
b1294c6d2c8aaf58a8457c70350c0c15ee51d63f9159c0a2cf97c9a8ee6b04d8
Python
2,294
79
import numpy as np from scipy.stats import entropy import matplotlib import pandas as pd from scipy.stats import gaussian_kde min_n = 100 max_n = 0 def get_model_bit_scores(model_name, min_n, max_n): all_seq_score_list = [] f = open("./outputs/" + model_name, 'r') for line in f: line ...
4c0512813547b69069bd4f56ce783683a571a564bb32db27a0e0b22ac0abd667
Python
2,295
82
import gzip import io import pandas from .. import Utilities def try_parse(string, fail=None): try: return float(string) except Exception: return fail; def skip_na(key, value): skip = (not value or value == "NA") return skip def skip_non_rsid_value(key, value): return not "rs" in...
9c78116f13907423e71c135db8ae46955261f3aeb4b2b3e49734e1e8dee6004e
Python
2,296
105
"""Functions for surface creation.""" # Author: Oualid Benkarim <oualid.benkarim@mcgill.ca> # License: BSD 3 clause from vtk import (vtkTriangleFilter, vtkVertexGlyphFilter) from .mesh_elements import get_edges from ..vtk_interface.wrappers import BSPolyData from ..vtk_interface.decorators import w...
641979551ce17642ad05cfbc449f248e2ce34857bace0e1f066c1ef6a81c3c96
Python
2,297
62
"""Tests for ``aestetik.utils.utils_transcriptomics``.""" from __future__ import annotations import anndata import pytest from aestetik.utils.utils_transcriptomics import preprocess_adata # preprocess_adata uses scanpy's seurat_v3 HVG flavor, which calls # `from skmisc.loess import loess`. We need scikit-misc to (a)...
0bda4ec9a0d0b9a1ce0f107f51e6840b6741ab01714ff2222e9d336ad8fc45c8
Python
2,298
68
from collections.abc import Hashable import numpy as np from pgmpy.structure_score.log_likelihood_cond_gauss import LogLikelihoodCondGauss class BICCondGauss(LogLikelihoodCondGauss): r""" BIC structure score for Bayesian networks with mixed discrete and continuous variables. This score penalizes the co...
7946b33562040236dc8d69ccb25cfbbb75236522b4bc9f37e78c4d938ad28113
Python
2,298
70
#%% import os import subprocess from tqdm import tqdm from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed NUM_WORKERS = 14 DATA_DIR = "/home/thulasiseetha/research/dataset/curated/ChordomaMR/data/" # Skull stripping, Tissue segmentation and radiomics feature extraction def execute_co...
35841f4f4ce1807cf9565dd5b895d768ba86f7663f50e8589a68c8570fb43b5f
Python
2,301
86
from typing import Sequence, TypeVar import jax import jax.numpy as jnp import jax.tree_util as jtu from jaxtyping import Array, ArrayLike, PyTree T = TypeVar('T', bound=PyTree[ArrayLike]) def _is_leaf_pytree(x) -> bool: return jtu.treedef_is_leaf(jtu.tree_structure(x)) def tree_scale(tree: T, x: ArrayLike) -...
ff3ac1160aaa489c1cd9453d3687fb2c92ad00f85799456baafb8efb9af50e80
Python
2,302
69
import unittest import jax import jax.numpy as jnp from folx import batched_vmap class BatchedVmapTest(unittest.TestCase): def test_single_argument(self): def fn(x): return jnp.sin(x).sum() x = jax.random.normal(jax.random.PRNGKey(42), (10, 3)) y = jax.vmap(fn)(x) f...
47fcbf9026e191b871914d95f194eabe3cd8ef06de4eab2290736c2c18c689a2
Python
2,303
54
import re from pathlib import Path import qdarkstyle from rnalysis.exceptions import InvalidTypeError, InvalidValueError from rnalysis.utils import settings FONTPLACEHOLDER = '$FONTPLACEHOLDER' FONTSIZEPLACEHOLDER = '$FONTSIZEPLACEHOLDER' PATHPLACEHOLDER = '$PATHPLACEHOLDER' STYLESHEETS = {'base': None, 'light': qda...
377e15389fb5a9e345e5b6109edcb0241c59bbcc5c0dc9a07401f7ce49a991ff
Python
2,304
69
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
aed8244e98b2fad384c038c0cba120741b6249f26a4b431dd48acd51f86e2ce6
Python
2,304
60
from typing import Callable, List, Optional, Tuple from pytorch_grad_cam.base_cam import BaseCAM from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget import torch import numpy as np """ Weights the activation maps using the gradient and Hessian-Vector product. This method (https://arxiv.org/abs/2501...
6398ab051271994f9a3a3bccb8c0faca02ba56943ed145108ee3f56522fbde23
Python
2,306
68
"""Converts a Neuroglancer state to display a cross-section cube.""" import argparse import neuroglancer import neuroglancer.cli import neuroglancer.coordinate_space if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument( "--cube-size", type=neuroglancer.coordinate_space.pa...
c90b011a7e00250e9f147a1192f30e7916cf3ce00c2d897af6c253936fa51166
Python
2,307
87
import numpy as np # Colours and types Types = np.array(["T4", "T5"]) Type_colours = np.array(["#17becf", "#ff7f0e"]) Subtypes = np.array(["T4a", "T4b", "T4c", "T4d", "T5a", "T5b", "T5c", "T5d"]) Subtype_colours = np.array( [ "#1f77b4", "#9edae5", "#98df8a", "#bcbd22", "#d6...
cdd9240882c58e1746c495317b427fec5b411a80f8410fe67dce5dbfba64c02d
Python
2,309
57
import torch.nn as nn import torch ''' https://github.com/qiulinzhang/SPConv.pytorch ''' class SPConv_3x3(nn.Module): def __init__(self, inplanes, outplanes, stride=1, ratio=0.5, reduction=16): super(SPConv_3x3, self).__init__() self.inplanes_3x3 = int(inplanes*ratio) self.inplanes_1x1 = in...
5b028a25c5a64620198032738068cdb66950393caf9e6e998082b19b6de1d3b0
Python
2,311
75
import vtk, qt, slicer from math import sqrt, cos, sin from .CircleEffect import AbstractCircleEffect class AbstractDrawEffect(AbstractCircleEffect): def __init__(self, sliceWidget): # keep a flag since events such as sliceNode modified # may come during superclass construction, which will # invoke o...
7dd49eee8b8f29f684f27b00d5bb502a47c4df3ddfc51dbf525a16ef8d982cea
Python
2,311
74
import networkx as nx import numpy as np import pytest from pgmpy.base import DAG from pgmpy.example_models import load_model from pgmpy.metrics import FisherC SEED = 42 N_SAMPLES = 1_000 EDGE_PROB = 0.1 # probability of an edge in the lower triangle def _random_dag_with_same_nodes(model, rng, edge_prob: float = E...
716651fda59d17c465c6efa6bdf09ae12864d4b372c1a6c61119c3318a71f991
Python
2,312
88
import numpy as np # Colours and types Types = np.array(["T4", "T5"]) Type_colours = np.array(["#17becf", "#ff7f0e"]) Subtypes = np.array(["T4a", "T4b", "T4c", "T4d", "T5a", "T5b", "T5c", "T5d"]) Subtype_colours = np.array( [ "#1f77b4", "#9edae5", "#98df8a", "#bcbd22", "#d6...
db2b8cb203da624597716c21042cecf9240a3578c289383f9c5117ed1ae100e3
Python
2,312
63
#!/usr/bin/env python """Regenerate `data/bacteria.txt` from ncbitax's bacterial species/genus index. The previous `bacteria.txt` had no generation script anywhere in history and had not moved since 2024-09-16; this replaces it wholesale with names drawn from NCBI's own taxonomy dump (species + genus rank, division Ba...
ec91e817bcd487893d5d6a23967429b7bbbf0604a645de1f66514a5b71b2abbb
Python
2,313
66
from collections.abc import Hashable from pgmpy.structure_score.log_likelihood import LogLikelihood class AIC(LogLikelihood): r""" AIC structure score for discrete Bayesian networks. AIC balances discrete log-likelihood against model complexity using a sample-size independent penalty. The local scor...
49c2e227c879143ec37cc000c13958d90b777a5612d13d83fa57d5b615da7b83
Python
2,314
90
import numpy as np # Colours and types Types = np.array(["T4", "T5"]) Type_colours = np.array(["#17becf", "#ff7f0e"]) Subtypes = np.array(["T4a", "T4b", "T4c", "T4d", "T5a", "T5b", "T5c", "T5d"]) Subtype_colours = np.array( [ "#1f77b4", "#9edae5", "#98df8a", "#bcbd22", "#d6...
9ae0d3cc20612536d81aa6ff95936d807afdcb4014267f799eae986cde4185af
Python
2,314
90
import numpy as np # Colours and types Types = np.array(["T4", "T5"]) Type_colours = np.array(["#17becf", "#ff7f0e"]) Subtypes = np.array(["T4a", "T4b", "T4c", "T4d", "T5a", "T5b", "T5c", "T5d"]) Subtype_colours = np.array( [ "#1f77b4", "#9edae5", "#98df8a", "#bcbd22", "#d6...
33c9b00ade8d10580ea596b109266baeff1f0fa98c1db7084bac8495865da2d5
Python
2,315
67
from typing import Optional import torch __all__ = ["one_hot"] # adapted from kornia, https://github.com/kornia/kornia/blob/master/kornia/utils/one_hot.py def one_hot( labels: torch.Tensor, num_classes: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, eps: float =...
3436df2f2f5b496caed4f83cc4b98fb899c3ae63206fb2793c868398fa143ee4
Python
2,316
49
"""Run the unchanged Local SVG parser against repository fixtures and Lite output.""" import json from pathlib import Path import subprocess import tempfile import unittest import cv2 import numpy as np from generate_svg_parity_fixture import ROOT, local_harness class LiteSvgParityTests(unittest.TestCase): def t...
5cb9765bef7d3e4f6f86cfcc6f30b2e346371c51c076239d3a89077248a3126d
Python
2,317
66
from ... import options as opts from ... import types from ...charts.chart import Chart3D from ...globals import ChartType from ...options import InitOpts, RenderOpts class Lines3D(Chart3D): """ Lines 3D """ def __init__( self, init_opts: types.Init = InitOpts(), render_opts: ...
ae1b0b2370b3138410a9d2e7c44c9d73f2ea2d810c77db4c66a9de8bc7643de0
Python
2,317
68
# _ _ # | | | | # ___ __ _ __ _ ___| |_ ___ ___ | |___ # / __/ _` |/ _` / __| __/ _ \ / _ \| / __| # | (_| (_| | (_| \__ \ || (_) | (_) | \__ \ # \___\__,_|\__,_|___/\__\___/ \___/|_|___/ ''' A Convergent Amino Acid Substitution identif...
4993c11d9ed4ab71c37e0a03188916d91c052eed31d76b387e5c5fd98606e461
Python
2,318
64
import jax import jax.numpy as jnp import numpy as np from jax.experimental import enable_x64 from oneqmc.laplacian.folx_laplacian import ForwardLaplacianOperator from oneqmc.physics import loop_laplacian def test_dense_forward_laplacian(): key = jax.random.PRNGKey(42) key, subkey = jax.random.split(key) ...