sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
eb0f2bc65b370ef5ee3d530e29dc0ebd66a4126fe4b9ac2e69f240c02b1fe3e8
Python
1,721
47
# Copyright 2020 The Lucent Authors. 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 ...
dacce81c0fb3ab858e8177b27a57c2f4a1e80bf567b22ee8bf7eee10935067f9
Python
1,724
49
import traceback import click import numpy as np import xarray as xr from ..utils.decorators import error_handler from .ica_utils import compute_pca_ica def chunk_pca_ica(dataset: str, chunk_int: int, chrom_subset=None, n_slices=36): areas = xr.open_zarr(dataset, group=f'chunk_{chunk_int}').areas.sel(chromatophor...
29bb373620dde3dd804298e54d77cff481d3886011a3ac36dd7dba8a1aaf767f
Python
1,726
48
from typing import Sequence, Union import numpy as np import scipy.stats from .registry import registry @registry.register_metric('mse') def mean_squared_error(target: Sequence[float], prediction: Sequence[float]) -> float: target_array = np.asarray(target) prediction_array = np.asarra...
716e6c3200241d59f91f465c7880645ff01a420f4e21a1ae2ab1e045eb99a1a1
Python
1,726
58
import os import re import pandas as pd # data_dir = os.path.dirname(__file__) class GMT(): # genes_cols : start reading genes from genes_col(default 1, it can be 2 e.g. if an information col is added after the pathway col) # pathway col is considered to be the first column (0) def load_data(self, filenam...
393d419152e673d9d3fe70cb9597d3da5305af46e48b742450e2c0153b0792d9
Python
1,727
51
import unittest from unittest.mock import patch from pyecharts import options as opts from pyecharts.components import Table from pyecharts.globals import CurrentConfig, NotebookType def _gen_table() -> Table: table = Table() headers = ["City name", "Area", "Population", "Annual Rainfall"] rows = [["Bri...
a2f4e43684716d23e529c4c7c2085a5b2c8dbc9fa28dfc250b66c5ed90db465b
Python
1,727
28
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.3,0.4), fb_multiplier=(0.3,0.0), er_multiplier=(0.01,0.0...
c1667eb2b3ed16a02d1330009d6ccaad6bca2b5f757d681b81719031c2458138
Python
1,727
53
""" (tips: if the Non-local type you select is **non_local_concatenation** or **non_local_dot_product** (without Softmax operation), you may need to normalize NL_MAP in the visualize code) """ import numpy as np import cv2 import math import os def vis_nl_map(img_path, nl_map_path, vis_size=(56, 56)): dst_dir = n...
ca772959af3e98c9dbfe649bfca47481f63b9ee28ffb0f4c8c27e42320783722
Python
1,727
26
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.35,0.4), fb_multiplier=(0.25,0.0), er_multiplier=(0.01,0...
d8de02681a2210ba6ac4f1fb8f5ac30647616c627d8bd7f5b3e684a8270276d9
Python
1,727
58
from math import exp, lgamma, log import numpy as np from scipy.special import betainc, betaln import loompy class Trinarizer: """ Compute trinarization probability per cluster """ def __init__(self, f: float = 0.2) -> None: self.f = f self.p_half_vectorized = np.vectorize(self.p_half) def fit(self, ds: loo...
ababdc9f2a0111a73472cea916be6fd5d7d86363eb506e01fcc24c6479c47eac
Python
1,728
35
from argschema import ArgSchema, ArgSchemaParser from argschema.schemas import DefaultSchema from argschema.fields import Nested, InputDir, String, Float, Dict, Int from ...common.schemas import EphysParams, Directories, WaveformMetricsFile class MeanWaveformParams(DefaultSchema): samples_per_spike = Int(required...
61d7270fb653120f4837af48e05eda2b943d77525e824807bf97904cb9ede924
Python
1,729
28
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.35,0.4), fb_multiplier=(0.25,0.0), er_multiplier=(0.01,0...
77fadd317ec42a881112fff42797b269b570b5455cb16807032b98dff7f890ad
Python
1,729
60
import unittest from pyecharts.commons.utils import remove_key_with_none_value from pyecharts import options as opts class TestGraphicComponent(unittest.TestCase): def test_graphic_group(self): group = opts.GraphicGroup( graphic_item={"item": 1}, is_diff_children_by_name=False, ...
02263c70dc8510b46b624196e050ca2057972918d6ac798f87e3bbc4e0a79198
Python
1,730
46
import re import warnings from pathlib import Path from typing import Literal, Union import rst_to_myst def get_change_log_for(version: Union[str, Literal['latest']] = 'latest', history_path: Union[str, Path, None] = None): regex_pattern = r'(\d+\.\d+\.\d+)\s+\(\d{4}-\d{2}-\d{2}\)\s*-+\s*' if history_path is...
3a95d671e6ed0fd2ad1681b1e71b6fb61a1311bd20e2c38ed31f582ca5fa7fe5
Python
1,732
56
"""Acquisition functions for Bayesian Optimization.""" import numpy as np from scipy.stats import norm def UCB(preds, uncert, h_param=0.2, **kwargs): return preds + h_param * uncert def LCB(preds, uncert, h_param=0.01, **kwargs): return preds - h_param * uncert def EI(preds, uncert, h_param=0.01, **kwargs...
7347800446a8e33ddf57e116d616c2bbe9b1a22e724288a1533a3ea23250b6c0
Python
1,732
70
from PyQt5.QtCore import QEvent from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QFrame from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QListWidget from PyQt5.QtWidgets import QPlainTextEdit from mdt.gui.utils import TimedUpdate class CollapsablePanel(Q...
fcc9d0ac4fe1fd1629efaca19da2dee66d1f07889d20f1055203f274a3feb301
Python
1,732
55
from argschema import ArgSchemaParser import os import logging import subprocess import time import glob import numpy as np from ...common.utils import read_probe_json, get_repo_commit_date_and_hash def run_median_subtraction(args): print('ecephys spike sorting: median subtraction module') commit_date, comm...
547c10dac26dbee92c85e6caf7203236e088ed7b7f760404e015da132ce87509
Python
1,733
53
import unittest from pyecharts.render.display import HTML, Javascript class TestDisplay(unittest.TestCase): def test_display_html(self): html_content = "<p>hello world<p/>" obj = HTML(html_content) self.assertEqual(obj.data, html_content) self.assertEqual(obj.__html__(...
845763bc6fb15df15ff1a06478b98a33a688774de1f75baa20337ba505ed6236
Python
1,733
54
# 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 torch import numpy as np from examples.textless_nlp.gslm.unit2speech.tacotron2.text import ( EOS_TOK, SOS_TOK, code_to_seq...
40b759b9f4aa9c07e346a371b651149ae180bd7dafcbd63fe92ca0fea11e3297
Python
1,734
55
"""Persistence helpers for dashboard state.""" from __future__ import annotations import json import logging from pathlib import Path from src.persistence.app_paths import config_file_path, legacy_repo_file_path logger = logging.getLogger(__name__) def state_file_path() -> Path: """Return the file path used f...
ce3826e3bdca3a488cba33f48e7d390d6a9746ed5361875b90d66831168e147f
Python
1,734
53
import jax.numpy as jnp import numpy as np from laplacian_testcase import LaplacianTestCase from folx import forward_laplacian class TestComplexFwdLapl(LaplacianTestCase): def test_parts(self): x = np.random.randn(10) W1 = np.random.randn(10, 10) W2 = np.random.randn(10, 10) def ...
461c58f9180dab18dc150dd5e3ef6755c7a22c69b4800b0b1fe7a8be45ed6327
Python
1,735
50
import pytest import folx.interpreter as interpreter_mod class _DummyPrimitive: def __init__(self, result): self.result = result def get_bind_params(self, params): assert params == {'x': 1} return self.result def test_split_bind_params_accepts_legacy_tuple(monkeypatch): monkeyp...
c1d7bf5413337407bdfcd4c41e0d8dafe0dc2038b4047e56dcaae4ed52716678
Python
1,735
58
# # 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 # import os import numpy as np import scipy.io from MLPerf_cal_images import get_cal_fns ...
3fdc29a8476c69aae40f1ea52797f90a2a50c219257a6d28288583f3a26f1195
Python
1,736
62
#!/usr/bin/env python3 # 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 unittest import torch from examples.speech_recognition.data import data_utils class DataUtilsTest(unittest.Tes...
bd5fa97410be8efdb60804dda04646ff9487e543c5efb23f0fa16c3d0a739445
Python
1,736
64
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil #from glob import glob from vlpp.utils import gzipd, run_matlab, TPL_PATH, add_suffix, run_shell from vlpp.operation import ImgStatsFromAtlas def main(): for d in ["baker", "stats"]: os.mkdir(d) tags = { "bakerDir": "${b...
396b4ba912f63c30cf51ebcd040835d49a74bff9f69cfc11bd69f1c6c94ff11f
Python
1,738
58
import sys import os import shutil import logging import gensim.downloader as api from gensim.downloader import base_dir logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") logger = logging.getLogger("test-downloader-api") logger.info(sys.version.replace("\n", " ")) if os.path....
49d4c76a890ec3534815ece9795a6553d2edcf6b68d5429e1beefdb270dcd1a2
Python
1,738
40
import matplotlib.pyplot as plt import numpy as np labels = ['3', '5', '7'] cellpose_means = [8.31, 7.09, 5.56] jsta_means = [6.01, 5.26, 4.77] genesegnet_means = [12.31, 10.99, 9.32] seg_joint_gene_means = [14.56, 13.46, 11.23] # Ours colors = ['#4DBBD5', '#E64B35', '#00A087', '#3C5488'] x = np.arange(le...
9301e1592e0177b18469dd32ac6fae7d7b25b17945704f8c270df3fc872d22f4
Python
1,740
48
import unittest from unittest.mock import patch from pyecharts.charts import MapGlobe from pyecharts.faker import Faker from pyecharts.globals import CurrentConfig, NotebookType class TestMapGlobeChart(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_map_base(self, fake_wri...
90e41905d067db2ca2a4353f07e0b13afac7a363c0e6a0bcebf02591b4e81f58
Python
1,741
59
# @license # Copyright 2024 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...
e27f11a20d28821e46a0620cefdfab59178fb7ab18b46f580f117bbdda69dd76
Python
1,741
40
import matplotlib.pyplot as plt import numpy as np labels = ['3', '5', '7'] cellpose_means = [17.66, 15.32, 13.23] jsta_means = [30.35, 25.33, 18.76] genesegnet_means = [50.66, 28.99, 22.33] seg_joint_gene_means = [54.65, 29.77, 25.49] # Ours colors = ['#4DBBD5', '#E64B35', '#00A087', '#3C5488'] x = np.ar...
01d26165ad881a116c6dda8cffe257a017741a49e437f2e5d0f41259d97d4ec7
Python
1,742
63
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple filters for image processing or filtering lists""" import os from pathlib import Path from typing import Any, Optional from .models import Cell def filter_none(value: Optional[Any]) -> bool: """Returns True if value is not None""" return value is not ...
63f8eed99a2be4fad66693c74e7770db32be96f9c02167811d1a581419014d33
Python
1,743
41
import matplotlib.pyplot as plt import numpy as np labels = ['3', '5', '7'] cellpose_means = [28.13, 24.12, 19.66] jsta_means = [26.98, 23.66, 20.45] genesegnet_means = [31.05, 27.13, 23.44] seg_joint_gene_means = [32.87, 28.17, 25.31] # Ours colors = ['#4DBBD5', '#E64B35', '#00A087', '#3C5488'] x = np.ar...
ba04c7a86080e223f814748e8903399fe25a28fbbe9ee033313b9248a9757ba6
Python
1,744
50
import ast import logging import unittest from pathlib import Path from GMXMMPBSA.exceptions import MMPBSA_Error from GMXMMPBSA.utils import topology_mismatch_error ROOT = Path(__file__).resolve().parents[1] class Phase6MessageTest(unittest.TestCase): def test_topology_mismatch_includes_paths_and_counts(self):...
5c52125ccd59e62add3a94346c5779510e92c63d2e84c9b5477f7810955f6d3b
Python
1,745
54
# 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 unittest import torch import torch.nn as nn from fairseq.modules import ConvTBC class TestConvTBC(unittest.TestCase): def test_c...
9fb7ed073b45be4bd03292c1b6f0bb10a4a3f531d3b19341cee0e0549debdd54
Python
1,745
59
# -*- coding: utf-8 -*- """ Created on Tue Jun 3 10:11:20 2025 @author: mayc06 """ #find plume odor value odor = max(0,self.dset[self.t,plmy,plmx]) # perform adaptive compression codor = odor/(odor+self.beta+self.A) valve = 0 if codor > 0.5: valve = 1 # update adaptation value self.A = self.A + (o...
e704f88427d5cfec641bb990f46e31314d6b773722c65dc41b4ee4358f1b7e4e
Python
1,745
34
import numpy as np import loompy from openTSNE import initialization from cytograph.embedding import art_of_tsne def pull_towards_levels(X: np.ndarray, pull_levels: np.ndarray, \ min_force: float = 0.6, max_force: float = 0.95) -> np.ndarray: """ Alternative initialization method fo...
9ec8d3445e4525b8ca9a30454c5171f2b4a4c3546b01ffbb497f70bd1e566a7b
Python
1,746
50
# # 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 ..generic_device import NormalError from simulator.backend...
b23c0b7cac223da285de80461873196e2e60c0e0ddce776f858cc4b0777059af
Python
1,748
49
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
d713b95325c2ecee9da41621e0c4c15b5dce982ebb2ff935d0c114a64431304d
Python
1,749
30
from predify.modules import PCoderN from predify.networks import PNetSeparateHP from torch.nn import Sequential, ReLU, ConvTranspose2d class PVGG16SeparateHP(PNetSeparateHP): def __init__(self, backbone, build_graph=False, random_init=False, ff_multiplier=(0.35,0.4), fb_multiplier=(0.25,0.0), er_multiplier=(0.01,0...
2b115084583bd9f8fae3ff6aae605a608762ce57472cfec5bc723345bb4c0ea8
Python
1,752
50
# # 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 ..generic_device import NormalError from simulator.backend...
68d5a9587bfd96f1e4dda9767102bda38e12188a62895838172dc0575cbcfe30
Python
1,752
42
from contextlib import redirect_stderr from io import StringIO import unittest from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch from scripts import run_example_docs_symlink_spike as spike class ExampleDocsSymlinkSpikeTest(unittest.TestCase): def test_missing_mkdocs...
642edf149e02f05a3d6e54159da190e72796a1cc1ffd1648c24d136a6284ff1e
Python
1,753
47
import matplotlib.pyplot as plt import numpy as np import loompy from .colors import colorize, colors75 def buckets(ds: loompy.LoomConnection, out_file: str = None) -> None: plt.figure(figsize=(21, 7)) plt.subplot(131) buckets = np.unique(ds.ca.Bucket) colors = colorize(buckets) bucket_colors = {buckets[i]: co...
0bb962f416fe4cce6ebfefc23e0a18ed8ce348213bc2356ccd9b81e9c84ad821
Python
1,755
42
import argparse def main(args): import glob import random import numpy as np import json import itertools with open(args.input_path, 'r') as json_file: json_list = list(json_file) fixed_list = [[int(item) for item in one.split()] for one in args.position_list.split(",")] ...
fcf3ed38541dd3b06de309ce59397220cf29c1d788704454705122f6fb37734d
Python
1,756
53
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch from mattergen.diffusion.data.batched_data import SimpleBatchedData, _batch_edge_index, collate_fn def test_collate_fn(): state1 = dict(foo=torch.ones(2, 3), bar=torch.ones(5, 2)) state2 = dict(foo=torch.zeros(3, 3), bar=t...
be30cdd2e730f30f2f2bdc89b92f010955e877cb30140b7170dc1eacb3672473
Python
1,757
31
import numpy as np from .utils import _log_exp_converter from .utils import _logit_logistic_converter from .utils import _arctanh_tanh_converter # py.test precimed/common/utils_test.py -k test_converters def test_converters(): epsval = np.finfo(float).eps minval = np.finfo(float).min maxval = np.finfo(fl...
d25b77585e4407349fca99157d81dd2c7bc89d6ac18182f70f5e31f43978d292
Python
1,757
56
# @license # Copyright 2018 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...
b6a48bd25d0956f24441a87b089ec63c08c8288b0b01d764ef61ac4b8a9f2688
Python
1,758
57
import unittest from pathlib import Path from tempfile import TemporaryDirectory from GMXMMPBSA.tester import run_process class TestOutputValidation(unittest.TestCase): def _run(self, root, command, expected=('result.dat',), skip=False): return run_process( root, 'Synthetic test',...
fd33768091bf77c7970f2849a89803d3d3c91c7b1a5633023247da0c61cbec4a
Python
1,758
77
import re import numpy as np CFG_FILENAME = 'config.yml' DEFAULT_ID = 'main' N_INIT = 1 INIT_SIZE = None TRAILING_DIGITS = re.compile('.*?([0-9]*)$') ACTION_VERB_TO_NOUN = dict( sample='sample', align='alignment', label='labeling', evaluate='evaluation', aggregate='aggregation', parcellate='par...
4e38448a0b7f47bc78bbdd62da05b0c40af3ff2fe29af9f3dcaaee04aae15780
Python
1,759
42
from __future__ import annotations from typing import TYPE_CHECKING from poetry.factory import Factory from tests.mixology.helpers import add_to_repo from tests.mixology.helpers import check_solver_result if TYPE_CHECKING: from poetry.core.packages.project_package import ProjectPackage from poetry.reposito...
69b3004b822c8e3837949dc70a3a2a17d049c1f65c08d48306e1abf42362c99c
Python
1,760
59
import sys from collections.abc import Iterable from typing import Literal from rich.console import Console from rich.progress import track as track_base from tqdm.auto import tqdm as tqdm_base from scvi import settings def track( sequence: Iterable, description: str = "Working...", disable: bool = Fals...
99d4418fee3e3dffb31235210c2a34a643ed0127c24feb127119972b3ca16706
Python
1,761
51
""" Unit tests for src/processing/photometry_metadata.py. """ import pandas as pd from src.processing.photometry_metadata import extract_mouse_name, get_column_titles class TestExtractMouseName: """Tests against filenames drawn from actual example data.""" def test_extracts_from_example_photometry_path(self...
a86dbf52fb42c1145063af716420a0bc9edcdf9f96525d3e85d6cb842af13fa2
Python
1,761
62
import os import time import numpy as np import pandas as pd from sklearn import metrics from tqdm import tqdm def train_ML(model, args, dataset=None): acc_list = [] recall_list = [] f1_list = [] auc_list = [] prec_list = [] time_list = [] print("Repeat 5 fold cross-validation for %s tim...
8e08dec095a64f513b9ae0047dfa77acc4e06f163b285c2b976f866792da6a45
Python
1,762
17
import pandas import numpy expected_snp = pandas.Series(["rs940550", "rs6650104", "rs6594028", "rs9701055", "rs7417504", "rs12082473", "rs3094315", "rs3131971", "rs61770173", ], dtype=str) expected_effect = pandas.Series(["C", "T", "T", "A", "T", "A", "A", "T", "A"], dtype=str) expected_non_effect = pandas.Series(["G"...
172ad01fb235bc1d2bfedbac255163f9dffd8046cad72f6addedacf13b52bae0
Python
1,763
49
# 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 torch import torch.nn as nn class BeamableMM(nn.Module): """This module provides an optimized MM for beam decoding with attention...
764016bb68eb85b856397238291bbe131fd3a560852f90b65f56c75a9eebc4a4
Python
1,763
46
import os import shutil import subprocess from pathlib import Path import nibabel as nib import numpy as np def dice_score(y_true, y_pred): intersect = np.sum(y_true * y_pred) denominator = np.sum(y_true) + np.sum(y_pred) f1 = (2 * intersect) / (denominator + 1e-6) return f1 def run_tests_and_exit_...
cde1077f57394d6902983327723b71779b8ff6e2b87d049e2a4f7ad832bbe4ab
Python
1,764
34
# Source code: # https://github.com/zbmed-semtec/doc2vec-doc-relevance-training/blob/main/code/train_model/train.py # This file includes the modifications to the source codes according to this project! import time import logging import utilities as utilities def run(best_params, args): # 1) Load the trainin...
5b0b007104390b8606d563df5a3809422befae72b8bf94560403f76b2c381918
Python
1,765
54
#!/usr/bin/env python3 """Validate disk-backed analyzer success or its explicit dependency guard.""" from __future__ import annotations import argparse import json from pathlib import Path from GMXMMPBSA import API def validate(result: Path) -> dict: record = {"result": str(result.expanduser().resolve()), "mod...
944ba1ffb38641992a7af7736d8f9ca0807022d248071a8d37ecbea89f770fc0
Python
1,765
65
# 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 functools import tempfile import torch def spawn_and_init(fn, world_size, args=None): if args is None: args = () wit...
f94b88d665b6359510cb02a1788fa9391c6cc4d2db0a5eb047930194206b514c
Python
1,765
54
import itertools import joblib import numpy as np 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 from mentor import _rw...
9c44f491b70667f91e6dd1c167cb643d891dccf467c04d0375b9d7a4c1e51e0e
Python
1,768
57
""" TransUNet classification-oriented adaptation. Important: TransUNet is originally a segmentation architecture. This implementation is a clean classification baseline inspired by a CNN+Transformer encoder-decoder design, adapted for image-level GI disease classification. Design: - CNN stem for local...
c3388390d86509137c280a8ffef114ced0b2922f4b71d5bf6b7e51fa39e81f29
Python
1,770
45
import cv2 import cmapy from PIL import Image import numpy as np from msi_visual.utils import normalize_image_grayscale, image_histogram_equalization class AvgMZVisualization: def __init__(self): pass def predict(self, img): processed_img = img / img.sum(axis=-1)[:, :, None] ...
172665a5e1e4b575813b4653c96d2b8923c2b49bffda8af47c3bc45c83e5655c
Python
1,771
49
import os import numpy as np import pickle import matplotlib.pyplot as plt import torch from dadi_simulators import * from sbi import analysis datadir = snakemake.params.datadir posteriordir = snakemake.params.posteriordir n_train = snakemake.params.n_train simulator = MODEL_LIST[snakemake.params.demog_model](snakema...
81f0e4b8fd099cb1f7fc6c22f4a27d8abc1795b04257d1dd83f7407a0237197e
Python
1,771
47
from typing import Callable, List, Optional import numpy as np import torch from pytorch_grad_cam import GradCAMPlusPlus from pytorch_grad_cam.utils.image import scale_cam_image class RefineCAM: """ Meta-method for aggregating CAMs from multiple layers. This methods works very well for denoising ea...
8213bb8f1a4ef5ce2e2876bb9c64e848c36495fa97d31c1e51fc38af73315b9d
Python
1,771
57
import numpy as np import joblib from msi_visual.utils import normalize class BaseDimReduction: def __init__(self, model, start_bin=0, end_bin=None): self.k = 3 self.model = model self.start_bin = start_bin self.end_bin = end_bin self._trained = False de...
12b6cda417b4be50538dc11d61a94778e0d8db2afacafc44e7454e75ba9639fb
Python
1,772
56
# @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...
34540175ebf6a3ea1f2ad261829a1f313ca8db5a9ffbe8a5c8e2a9e4620f13ec
Python
1,772
48
import novae from ._utils import adata_small as adata def test_init_prototypes(): model = novae.Novae(adata, num_prototypes=20) prototypes = model.swav_head._prototypes.data.clone() model.init_prototypes(adata) assert (model.swav_head._prototypes.data != prototypes).all() def test_preserve_cluster...
6d6b96f53484f62aee94fd1de8f2dc591f35f2745c277ebe328dcb23e8fcb8a7
Python
1,772
56
from beartype.typing import Any, Dict from lightning_utilities.core.rank_zero import rank_zero_only from omegaconf import OmegaConf from src.utils import pylogger log = pylogger.RankedLogger(__name__, rank_zero_only=True) @rank_zero_only def log_hyperparameters(object_dict: Dict[str, Any]) -> None: """Controls ...
c99d4672a47514666828230c4d83e4d56670eeb24e85c05bb13c0e819aa1fad2
Python
1,772
55
# -*- coding: UTF-8 -*- """GOEA term-scoring algorithms. >>> from goatools.goea.algorithms import get_algorithm >>> get_algorithm('classic') """ __copyright__ = "Copyright (C) 2010-present, H Tang et al., All rights reserved." from goatools.goea.algorithms.base import GoeaAlgorithm, GoeaAlgoResult, GoeaConte...
c4b4392a4ccf218ee0efa9f2f9c878606c6459f6b489235eaf47367231890de3
Python
1,773
51
# 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 uuid from typing import Dict, Optional from torch import Tensor class FairseqIncrementalState(object): def __init__(self, *args,...
feba9cd3bc4637339716e68fb798ad1f666405f6be91d72105d5b865f660a1d0
Python
1,773
41
#!/usr/bin/env python3 """Coluna de DIFERENCA Pb - Ge para a Tabela 6 (antiga 4), ao lado da razao. Mesmo conjunto e mesma estatistica da razao publicada: as 1462 estruturas com gap (nao metalicas, gap > 0), agrupadas pelo haleto e pelo cation B do nome, mediana do gap por grupo. O script so aceita gravar se reproduzi...
79382a79544a4b92b5311c4065df275e9152752be828e796cf60839c7ee39b78
Python
1,774
44
import papermill as pm import os import shutil print(os.getcwd()) censor_region = 'above' output_dir = 'OUTPUTS/notebooks' os.makedirs(output_dir, exist_ok=True) for censor_split in [0.1, 0.5, 0.9]: print(f'Running MLP notebooks for split {censor_split}') pm.execute_notebook(input_path='omit_mlp.ipynb', ...
1366a6d92ade08d2fe02975aa8ea212b93455382e37e304698cab04aa9590b5a
Python
1,775
49
"""Defaults for find_enrichment parseargs to be used in tests.""" __copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" import os import collections as cx # pylint: disable=too-few-public-methods class ArgsDict(object): """Defaults for find_enric...
16af8458f608da734653a14fc7bb596944cc91d3e49a78192e92bc9cf1525a23
Python
1,775
52
import numpy as np import scipy.sparse as sp def sparse_to_tuple(sparse_mx): """Convert sparse matrix to tuple representation.""" def to_tuple(mx): if not sp.isspmatrix_coo(mx): mx = mx.tocoo() coords = np.vstack((mx.row, mx.col)).transpose() values = mx.data shape =...
525587b9f589010901e3ae8716781c19fb1ed22326157c63b7c33b9f53c04e26
Python
1,776
54
import Levenshtein as ld def levenshtein_distance(string1: str, string2: str) -> int: """Generates the edit distance between two strings using the Levenshtein distance. Args: string1 (str): The first string. string2 (str): The second string. Returns: int: The Levenshtein distance b...
e7f369ce7f7c48b212aa8a47da10777524c10d556cfe2b8264177e3494cd38a7
Python
1,776
52
# 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 by applicable law or a...
1cc843aaa2270e1ae4eca7509745012128b484ec9c213e45a9ef7dc337e94b5e
Python
1,777
55
"""Persistence helpers for app settings.""" from __future__ import annotations import json import logging from pathlib import Path from src.persistence.app_paths import config_file_path, legacy_repo_file_path logger = logging.getLogger(__name__) def settings_file_path(app_type: str) -> Path: """Return the JSO...
42c3f1717ba4d6bd434dd9be5197ee5a12c3f3e5be7629e8f62979dfb4c8a4c7
Python
1,777
62
def pytest_addoption(parser): """Register custom CLI options for the test suite.""" parser.addoption( "--internet-tests", action="store_true", default=False, help="Run tests that retrieve stuff from the internet. This increases test time.", ) parser.addoption( "--...
8528a7a2b5f8a492087c6f87a217e1e5c2c79cac78273eca149b397a23f93fc1
Python
1,779
52
import pandas as pd import numpy as np import string import joblib from sklearn import datasets,preprocessing def make_nodetable(): _index = ['A','B','C','D','E','F','G','H','I'] _labels = [2,2,1,2,1,1,1,2,1] _genenames = ['GENE_AAA','GENE_BBB','GENE_CCC','GENE_DDD','GENE_EEE','GENE_FFF','GENE_GGG','GENE_H...
f94af9b92116e6312b2c6692a5300fd2c38009182cd9d99bc290e34e841aad0b
Python
1,780
55
import argparse import neuroglancer import neuroglancer.cli import neuroglancer.random_token if __name__ == "__main__": cube_size_meters = 10e-6 ap = argparse.ArgumentParser() neuroglancer.cli.add_server_arguments(ap) args = ap.parse_args() neuroglancer.cli.handle_server_arguments(args) viewe...
fa31c1f22f52c7aabe128534fab9536ac9207f4bbb717530af0b6929102402fb
Python
1,780
46
from pathlib import Path from typing import Literal, Union from rnalysis.utils import installs, io, parsing class FeatureCountsRunner: TEMPLATES_DIR = Path(__file__).parent.parent.joinpath('data_files/r_templates') def __init__( self, kwargs: dict, output_dir: Path, r_installation_folder: Union[str,...
fa2a855d6f5716672d4a2e1dcecc52b644024a4fc3742d7b5fda2f3a16796865
Python
1,781
60
from argschema import ArgSchemaParser import os import logging import time import numpy as np from .id_noise_templates import id_noise_templates from ...common.utils import write_cluster_group_tsv, load_kilosort_data def classify_noise_templates(args): print('ecephys spike sorting: noise templates module') ...
2fa9e7f3ca1fba4c5639ff51e3d20e93fce58cde027ebd3e22dc0303b677f3b4
Python
1,782
55
import hydra from beartype.typing import List from lightning import Callback from lightning.pytorch.loggers import Logger from omegaconf import DictConfig from src.utils import pylogger log = pylogger.RankedLogger(__name__, rank_zero_only=True) def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]:...
99ae824a3e1735cb9deea1fcc6a57f55432432dcda3c151aac3c1f4521bbc32c
Python
1,783
58
import sys,getopt,random,subprocess import pandas as pd try: opts, args = getopt.getopt(sys.argv[1:],"hi:o:w:b:",["ifile=","ofile="]) except getopt.GetoptError: print ('windows_MBB.py -i <input csv file> -o <output> -w <window size> -b <block size>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('wind...
dae87fea0944e2dae82537c905abea073f1c74e79de6816cb73612b4b9655f05
Python
1,783
51
import click import numpy as np from skimage.measure import regionprops def max_consecutive_zero_streak(arr): """Return the maximum number of consecutive zeros in a 1D array.""" max_streak = 0 current_streak = 0 for val in arr: if val == 0: current_streak += 1 max_strea...
e025f14764f8d37a0f2d2ff46fd4774e5c59a4f1c7083ca00ee358106485d9c3
Python
1,783
64
import lightning as L from anndata import AnnData from torch_geometric.loader import DataLoader from ..module import CellEmbedder from . import NovaeDataset class NovaeDatamodule(L.LightningDataModule): """ Datamodule used for training and inference. Small wrapper around the [novae.data.NovaeDataset][] "...
79b839e85e5505248f302ab5abad4144af6d650735b82c2837c3eada1fc6467c
Python
1,784
58
#!/usr/bin/env python3 # 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. """ Count the number of documents and average number of lines and tokens per document in a large file. Documents should ...
2fbf95b6792addff561a64afc77e54eba5343943df72ddd0f2c208b7badc2ba6
Python
1,785
57
# 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): fairseq wrapper class for all dataset you defined: mostly MMDataset. """ from collections import OrderedDict from torch.util...
58fff66f66b3a32300f14362e67d35711a7da3c37c3e24802cdbc373f50d58df
Python
1,785
45
import numpy as np import tqdm import math from msi_visual.extract import tsfdata import sqlite3 from msi_visual.extract.base_msi_to_numpy import BaseMSIToNumpy class BrukerTsfToNumpy(BaseMSIToNumpy): def get_regions(self, input_path: str): tsf = tsfdata.TsfData(input_path) conn =...
93c03e6d420951ba470e39f3edf0131bf838688f930435e97067eb4e1652bed8
Python
1,785
59
import os import sys import pathlib import subprocess if len(sys.argv) < 2: print("No path to original / hi-res icon provided") raise SystemExit if len(sys.argv) > 2: print("Too many arguments") raise SystemExit originalPicture = sys.argv[1] if not (os.path.isfile(originalPicture)): print(f"There...
eab3420e125cc2de119639915dcdaa7adbfee83316ca56f7c8ba4b84b46d6e50
Python
1,785
41
#!/usr/bin/env python3 """Gap de um .EIG do SIESTA, valido tambem com spin-orbit. Diferenca que importa: sem polarizacao cada banda cabe 2 eletrons e n_occ = N/2; com spin-orbit as bandas sao espinores e cabem 1, logo n_occ = N. Usar N/2 num calculo SOC devolve um numero plausivel e ERRADO -- e a mesma classe de armad...
0d389cd461612f41e18cc19eaa7a637348bf19edbfbec718be2759666ad2cefe
Python
1,787
57
import torch from sklearn import metrics import torch.nn.functional as F def logit_BCE(preds, labels): if labels.size()[1]==1: y = labels.type(torch.int64) y_one_hot = torch.zeros(labels.size()[0],2).cuda() # y_one_hot = torch.zeros(labels.size()[0],2) y_one_hot = y_one_hot.scatt...
4118a8836ed46b4a2eff74e4e879cb52e6bf9a38bba8a2c6d4e7d2471a7f5340
Python
1,787
95
"""Ported from the deleted src/tests/test_predictions.py (entities layer). Re-targeted at the live d3text.utils.merge_tokens. """ from d3text.utils import merge_tokens def test_merging_without_gold_standard() -> None: tokens = ( "[CLS]", "genetic", "analysis", "of", "the"...
543f7d6df1e71a375f764fde1617f1b61c17b1e6df369ac66ee46db246d06d58
Python
1,787
51
import os import subprocess from Bio import PDB # Please replace the following path MGLTOOLS_PYTHON = "/home/wjh/autodocktools/mgltools_x86_64Linux2_1.5.6/bin/MGLpython2.5" PREPARE_RECEPTOR_SCRIPT = "/home/wjh/autodocktools/mgltools_x86_64Linux2_1.5.6/MGLToolsPckgs/AutoDockTools/Utilities24/prepare_receptor4.py" cla...
bfb0d6642ab1e1c5e934c782539dcd087f488bfa85cdcdc7dbf38bd8ff290f15
Python
1,787
55
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Collection from collections.abc import Iterable from collections.abc import Mapping from packaging.utils import NormalizedName from poetry.core.packages.package import Package def ...
f590a465b44b28415ec70317d5bde0430e986cd617797c666f967bae34917327
Python
1,787
56
# 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 enum import Enum, EnumMeta from typing import List class StrEnumMeta(EnumMeta): # this is workaround for submitit pickling leading ...
3f5e27bbdb013053ec9adef32fa7e8002b5fa6fffa6221eb6acbfba9a5cd93fa
Python
1,788
64
import glob import os from typing import List, Optional, Tuple import logging import numpy as np import torchvision.transforms.functional as TF import PIL from PIL import Image from torchvision.datasets import VisionDataset logger = logging.getLogger(__name__) class PathDataset(VisionDataset): def __init__( ...
ff5e626bb234ad5a8be6ba5482d69e6a88257c76cd3d970949538e09b14e27f7
Python
1,788
67
import mdtraj as md import numpy as np import sys def get_rmsd_dssp(traj, ref_state, n_excl=0): """Compute RMSD (CA only) and DSSP.""" # Restrict to CA atoms, excluding n_excl residues on each side atom_indices = traj.topology.select( f"name CA and (resid >= {n_excl} and resid <= {traj.n_residues -...
8748d12a07f4d12044fc927f0af8d97239189c24f9c3c9614baa6586cc5eaa2e
Python
1,791
48
import re from pathlib import Path import tifffile as tiff import numpy as np # Directory containing composite TIFFs input_dir = Path("/Volumes/Expansion/Harvard/NIC/LucilleTwo/Project_neuroLSD/20250613_HeLa-Ctrl-ASAH1_EndoLysoStains/20250613_HeLa-Ctrl-ASAH1_EndoLysoStains_MIPs") output_dir = Path("/Volumes/Expansion/...
c3bdc749a41305dd40ab5a8414269a1c593d7012f7fbbc71a265c1b52809b29b
Python
1,791
54
# 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 dataclasses import dataclass, field from fairseq import file_utils from fairseq.data.encoders import register_bpe from fairseq.dataclass...
4eb313fdf251de00765a8756cd353b3f465b40ee574cdbc551f6a1fb0b59f5d1
Python
1,792
66
"""Constants used by multiple modules. Defined here to avoid circular imports. """ from functools import partial import crowsetta import numpy as np import soundfile from evfuncs import load_cbin from scipy.io import loadmat # ---- audio files ---- AUDIO_FORMAT_FUNC_MAP = { "cbin": load_cbin, "flac": soundfi...
60f3306c3e66cb36eb78a5a9a50b070f97d074dbce7c2888199b902823eb4e66
Python
1,792
40
import os import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument("system", type=str, help="Name of the system") parser.add_argument("seed", type=str, help="Random seed") args = parser.parse_args() epsilon = 1e-3 small_step = 0.1 big_step = 0.2 first_half = np.arange(-3.0, -1.6 + eps...