sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
2e3224edfe302c1b6a58f98507546e643445657334d6b9a0968ad8c5d7ab5230
Python
2,587
82
# 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 from collections import OrderedDict import torch from fairseq.data import LanguagePairDataset, TokenBlockDataset from fairse...
e09460cd914f0a7d5d191be5927372a5d1bb399191a9513aa8e0ebef75fa3412
Python
2,588
86
#!/usr/bin/env python # ENCODE DCC Count signal track generation # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_lib_common import ( log, ls_l, mkdir_p, rm_f, run_shell_cmd, strip_ext_ta) def parse_arguments(): parser = argparse.ArgumentParser( prog='ENCODE DCC...
0892aa01f9c81780d0572eb86aa7b1f96ef82e50d6d9ee2035e81ecdf9cfd29f
Python
2,592
61
import xmltodict from pathlib import Path #define class with cz parsing functions class CzParser(): """ Object containing parsed metadata for a CZ WSI. Use the method `get_regions()` to obtain a dictionary containing the coordinates, width, and height of each annotated rectangle, as well as the point c...
0975d558d8702f3d3c21d7e84cba094f98f70396f24f5063df8d8f9bc9b4c6c1
Python
2,592
70
import logging import shutil from pathlib import Path from .. import config from .. import train as train_module from ..common.logging import config_logging_for_cli, log_version from ..common.paths import generate_results_dir_name_as_path logger = logging.getLogger(__name__) def train(toml_path): """train model...
88e69d2c8a2608198c193f5c1982d759330c23406bad9b4bf1e85be66df2fa5d
Python
2,592
66
"""Read annotations in GAF, GPAD, Entrez gene2go, or text format.""" __copyright__ = "Copyright (C) 2018-2019, DV Klopfenstein. All rights reserved." __author__ = "DV Klopfenstein" from goatools.anno.genetogo_reader import Gene2GoReader from goatools.anno.gaf_reader import GafReader from goatools.anno.gpad_reader imp...
c032470c92bc42bef77de2f4861fcdede43462eb2cd73d2d3fb5bdfbe9df7206
Python
2,592
88
# 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 pathlib import Path from typing import List, Optional from examples.speech_to_text.data_utils import S2TDataConfigWriter def gen_confi...
94fde1ae79e760c5cfd69c134440a1255f0bef6ca6e99b38a0b3ffc95dbb6e16
Python
2,593
76
import numpy as np from sklearn.decomposition import non_negative_factorization from matplotlib import pyplot as plt from collections import defaultdict from scipy.stats import entropy def segment_visualization(visualization: np.ndarray, number_of_bins_for_comparison: int = 5): bins = np.linspace(0, 255, ...
ffb88b7ddc3a14e4939ede3436fed67c4702de6ecce31390c5d8681a585e3986
Python
2,594
53
from pathlib import Path from numpy.testing import assert_array_equal import pytest import pylossless as ll @pytest.mark.parametrize("clean_ch_mode", [None, "drop", "interpolate"]) def test_rejection_policy(clean_ch_mode, pipeline_fixture): """Test the rejection policy.""" rejection_config_path = Path("tes...
fbc340f197dd13e8ad7959965558b5c8b747ac78e7039cfc975134e1b2c6018f
Python
2,595
74
from typing import Callable, Any, Optional import torch from torchvision import transforms class Augmentation: """ Class for image augmentation technique. Parameters ---------- transform : Callable[[torch.Tensor], torch.Tensor] Transformation function to apply to the image tensor. na...
4a074f5578093e40d622e29ee230b0c687a2b96a3ab1073c1ec540fe2be8d29b
Python
2,596
75
from __future__ import annotations from abc import ABC from abc import abstractmethod from typing import TYPE_CHECKING from typing import Any from packaging.utils import canonicalize_name from poetry.core.constraints.version import parse_constraint from poetry.config.config import Config from poetry.repositories.rep...
56597d5447d1180d20bfee5ccb7e049d339a8319ce72c22ee34232878126441f
Python
2,596
75
#!/usr/bin/env python3 # MIT License # # Copyright 2022 Broad Institute # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use...
0a56e4dbb75cc23ac4bdb85f9141ec995b5f29f3baa57317e5cb8479a2a485b0
Python
2,597
85
# # 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 # """Core interface.""" from abc import abstractmethod, ABCMeta class ICore(metaclass=ABCMeta): ...
18346f8f253e11e783f145125ed4a779fbe39d541d5aebfbffab84829a7759e0
Python
2,597
66
import torch import math import numpy as np from torch_scatter import scatter def gaussian_kld(q_mu, q_sigma, p_mu, p_sigma, batch_idx): kld = torch.log(p_sigma / q_sigma) \ + 0.5 * (q_sigma**2 + (q_mu - p_mu)**2) / (p_sigma**2) \ - 0.5 return scatter(kld, batch_idx, dim=0, reduce='sum'...
29a2a3cc430a95e1ef0aaebba8a2560a5edc681b825b93e7cd4e3dc19cc026f7
Python
2,597
69
from typing import List import numpy as np import loompy import logging from cytograph.preprocessing import div0 class FeatureSelectionByDeviance(): def __init__(self, n_genes: int = 2000, mask: List[str] = None) -> None: """ Args: n_genes Number of genes to select mask O...
50ab709c128af7341336251d22f55dc0f9279f19109f3fd3552dfa0f5ab903d1
Python
2,599
80
# 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 unicodedata import sacrebleu as sb from fairseq.dataclass import ChoiceEnum SACREBLEU_V2_ABOVE = int(sb.__version__[0]) >= 2 class...
c779abcb787f54e09151da0fcf7db78a9a99b4345163da4aeb2d369ccab58611
Python
2,601
85
# # 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 from PIL import Image from torchvision import transforms f...
88956deb066cceddec6773ca240cc49a3eb5ac3761a841238cab0b122b51dc0c
Python
2,603
70
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html from sphinx.application import Sphinx from pathlib import Path # -- Path setup -------...
f07d715cf1d3138e7304cc3d86db7108f264cfb13da2d96026d524b45b2da53c
Python
2,603
63
#! /usr/bin/env python import os import logging from metax import __version__ from metax import Logging from metax import Exceptions from metax import Utilities from metax.misc import FeatureMatrix def _run(args, subset=None, append=None): logging.info("Loading expressions") manager = FeatureMatrix.build_manag...
2f6bf90a29d2f0a8e99fdb8ddf86ccba1bd4070c1496255df9f67379bd6ee000
Python
2,604
82
from __future__ import annotations from typing import Any import pytest from packaging.utils import NormalizedName from packaging.utils import canonicalize_name from poetry.core.constraints.version import Version from poetry.inspection.info import PackageInfo from poetry.repositories.cached_repository import Cached...
d0d4b610841ec711a79fceea59fefcbad8c807198004aa23fd35852e5cdee82f
Python
2,604
58
"""For getting colors based on grouping characteristics.""" __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" class GrouperColors(object): """Groups the user GO ids under other GO IDs acting as headers for the GO groups.""" # hdrcol = '#1...
d412a77e6a6b4269170aaef39a5b3c7786348781d9eb07b558bd956a0f77b45c
Python
2,604
88
import numpy as np from torchvision import transforms # from npyx.c4.waveform_augmentations import GaussianNoise class AmpJitter(object): """Rescales waveform amplitude by some small factor""" def __init__(self, lo=0.9, hi=1.1): """ Args: lo: float the low end of ...
1b42e2784a83de10791c72ec9727f2cb19b26d98ca3d445fac1f9d379620363b
Python
2,605
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 torch import torch.nn as nn class LayerSelect(nn.Module): """Compute samples (from a Gumbel-Sigmoid distribution) which is used a...
6cf4bf2c65225eecbca406a84f47335a52c07697da7fce7abe224f4c1d03eb77
Python
2,607
87
import haiku as hk import jax import jax.numpy as jnp from ..types import ( ElectronConfiguration, ModelDimensions, MolecularConfiguration, RandomKey, WavefunctionParams, ) from ..utils import update_pytree __all__ = () def init_wf_params( rng: RandomKey, example_mol_conf: MolecularConfigura...
3fa8bf2ada151393e1d294ae9ebbf303e26452eec81caa27fca13eedbfc4ee88
Python
2,608
87
# Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors import numpy as np from MDAnalysis.analysis.rdf import InterRDF import MDAnalysis as mda import os import argparse import sys def compute_rdf_xxx_hoh(universe, out_path:str=None, start:int=1000): """ Compute RDF between O atoms in ...
376485fdaae2eb6629222be37d1fd60cb5a3f306a15b66d284bfaa3dac9bfe74
Python
2,609
88
from enum import Enum import numpy as np from pydantic import BaseModel, Field, model_validator from pydantic.types import ( NonNegativeInt, NonNegativeFloat, PositiveInt, PositiveFloat, DirectoryPath, ) from typing import List, Union, Dict, Any, Optional class DimOrder(str, Enum): xyz = "xyz"...
d1599c2d7c6ab6da7eda615e8841977d94af03d8f76fe7bcaee6f69f8b34ccd3
Python
2,609
64
import os import pandas as pd def load_default_mapping(mapping_name: str) -> pd.DataFrame: """ Load a default DataFrame based on a known string key (e.g. 'reactome'). You can add more options if you have multiple defaults. Example usage: df = load_default_mapping('reactome') """ base_d...
628d33e3eefdbca16f0836d31ade45659c2e90e828696c91fee43268b1f9af41
Python
2,610
93
import torch import numpy as np from scipy.signal import get_window import librosa.util as librosa_util def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window fu...
7eca06d705c1a3a9568ce661febc12c375112f84fa4eb799de3de2ee0079d311
Python
2,611
151
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """Note that importing this module has two side effects: 1. It sets the environment variable `PROJECT_ROOT` to the root of the explorers project. 2. It registers a new resolver for OmegaConf, `eval`, which allows us to use `eval` in our config fi...
cd20b75f74f287c575cbdb830507132aeaf67c5fd69a8e6391c8ea0368bd6d3b
Python
2,611
65
import colorsys import matplotlib.colors as mc import matplotlib.colors as mcolors import matplotlib.pyplot as plt import numpy as np import seaborn as sns def __cmap_or_cmap_from_color(cmap: mcolors.Colormap | str, dark_or_light: str = 'dark', reversed: b...
5f9ed626274d04620883296400954e9546889162d9f10b43582342c3c60d0cea
Python
2,613
71
#!/usr/bin/env python3 # Florian Bénitière 16/03/2025 # Script to generate a .parquet file by merging all batch-level Parquet files import os import sys import pandas as pd import subprocess import psutil # System and process utilities from math import floor # For rounding down numbers from collections import Coun...
37d0010e707e7bc9f7c3dc65b316df8e03621d31b700d6729325c270c200456a
Python
2,614
69
from TrainingAlgos import * from data_funcs import * import collections class SV(TrainingAlgo): """ Fully supervised training using the binary cross-entropy as loss. """ def __init__(self, rec_params, REC_MODEL, batch_size=20, n_sampl...
df1e7410b1fee99bf426517a43846f051be0a06e09f32755998ad46c14df3d82
Python
2,614
72
# Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors import torch from datastructures.Graphs import Graph from utilities.Scatter import scatter_sum as scatter from utilities.Utilities import scalar_product def get_norms(graph: Graph): q_norm = torch.linalg.norm(graph.quads, dim=[-1, -2...
766b64ec3da12517f7d5a0d7902544f31a9ad3abb0e046fbddcced1c9ae4cf29
Python
2,615
91
# 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 examples.textless_nlp.gslm.speech2unit.pretrained.utils import ( get_and_dump_features, ) def get_p...
5cf1af80ffb2bdb5863bb3283d9735c2c2218a657ea3bdcc022ade48717f2bf3
Python
2,616
82
# 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...
fe3a069c0a7ad3eb69d63dd155fa0bf91c06b074f8624063aea2bc6d0a2342a3
Python
2,618
60
import pandas as pd from gensim.models.doc2vec import Doc2Vec # Adds the 4th column to the relevance matrix file, containing the cosine similarity of the respective reference and assessed pmids. def update_relevance_matrix(input_file: str, model: Doc2Vec, output_file: str, dataset: str) -> None: """ Updates...
4cf15b2648878c501b7197be0e5c9706716990535a3cea3b7008ff5c7fe81a19
Python
2,621
79
"""utility functions for logging""" import logging import sys import warnings from pathlib import Path from ..__about__ import __version__ from . import timenow logger = logging.getLogger("vak") # 'base' logger def config_logging_for_cli( log_dst: str, log_stem: str, level="info", timestamp=None, force=False ...
612b35c24f5b2511f3336dd65710162e8ff1a2c06ac6e6920597df92e5c816ad
Python
2,621
74
import unittest from unittest.mock import patch from pyecharts.charts import Custom from pyecharts.commons.utils import JsCode from pyecharts.globals import ChartType class TestCustom(unittest.TestCase): @patch("pyecharts.render.engine.write_utf8_html_file") def test_custom_base(self, fake_writer): c...
0ccd97894dbf95948089ee5fa04011e713ad6a8f98fa1b2fc7418106c73204e8
Python
2,623
58
import json from pathlib import Path import unittest NOTEBOOK = Path(__file__).resolve().parents[1] / "SegOnWebJob_v1_0.ipynb" class SegOnWebNotebookTests(unittest.TestCase): def test_notebook_paths_stay_stable_and_display_names_are_current(self): for filename, title in ( ('SegOnWebJob_v1_0....
b67d714f9ad933114827bda8bb36e48b1740802212fab848307ee4f49ba0d6a6
Python
2,624
84
import numpy as np import batch_multislice_extraction_lbm as batch def test_uniform_slice_selection_uses_z_axis_positions(): phi = np.zeros((10, 8, 20), dtype=np.float32) selected = batch.select_representative_slices(phi, num_slices=5, mode="uniform") assert [item["z_index"] for item in selected] == [2...
d47b1352b8ee689763aff91a5360d4bcf12d3929735fac140e321eb7cbc555c6
Python
2,624
70
"""A GO term, A, can be represented as DAG_a = (A, T_a, E_a), aka a GoSubDag""" __copyright__ = "Copyright (C) 2020-present, DV Klopfenstein. All rights reserved." __author__ = "DV Klopfenstein" ## import timeit ## from goatools.godag.prttime import prt_hms class DagA: """A GO term, A, can be represented as DAG...
f28ac4c7329ba472aecd8044ed4cfbfb4c20a192ce595a364aa8ba6d8983f139
Python
2,624
95
""" General utils for project (credit for many of these to internal lab utils: https://github.com/neuroailab/) """ from pathlib import Path from typing import Any, List, Tuple, Union import numpy as np import yaml from attrdict import AttrDict Iterable = Union[List, Tuple, np.ndarray] def norm_image(x): return...
b7ec8cdbb09dc8f3465213655aaa80b8199ecf7b407ef98fb6cba5732fc66143
Python
2,625
60
import os class TemplateFiller: def __init__(self, template_path, summary_folder_path, atom_folder_path, sequence_folder_path, output_folder_path): self.template_path = template_path self.summary_folder_path = summary_folder_path self.atom_folder_path = atom_folder_path self.sequenc...
53d909355308d602432a5797447b1c5a1be6a78b9235c5ab10859a32029fcf8d
Python
2,627
55
"""Synthetic (no patient data) inputs shared by desktop and browser Job ZIP tests.""" from pathlib import Path import numpy as np from PIL import Image from pydicom.dataset import FileDataset, FileMetaDataset from pydicom.uid import CTImageStorage, ExplicitVRLittleEndian, generate_uid def make_series(root, kind, cou...
7e407fd95a634ad0285c3f02d6fc379aac12f730b54aec5e2d8484b011b9ba5d
Python
2,627
106
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created script, # Author_and_contribution: Qirong Mao; implemented method import argparse # TODO adjust description parser = argparse.ArgumentParser( description="Neighbor definition based on the radius (only for generic coordinates)" )...
cf5262bea3c359e6fb7272393e2301e645e3046861290f3a6055903efb56f309
Python
2,628
117
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np plt.rcParams.update({ 'font.size': 14, 'font.weight': 'bold', 'axes.labelweight': 'bold', 'axes.linewidth': 1.5, 'figure.dpi': 300, 'font.family': 'sans-serif' }) models = ['GAMT-GINE\n(Full Model)', 'No...
a78721aa101309576d8ccbef99ee07c65ca530f8bfd73ee951970d40e9a62748
Python
2,629
78
import torch from tqdm import tqdm from functools import partial from ..common.data_utils import lattice_params_from_matrix def sample(model, frac_coords, lattices, atom_types, natoms, ld_kwargs, z=None, labels=None, guidance_strength=1, input_encoder=None, grad_context=None): if (model.en...
ce41709bfc28fb544f70462ec055f53316e58220a909aefbb077d396b6961488
Python
2,629
92
# # 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 .iadc import IADC from simulator.backend import ComputeBackend xp = ComputeBackend() # Repr...
0769cf5802d4a84e12c9c740184c0086ae0a3291f9ac780be29d078d1dba08f6
Python
2,630
77
import pytest import torch import scvi.distributions._beta_binomial as beta_binomial_module from scvi.distributions import BetaBinomial def test_beta_binomial_distribution(): alpha = torch.ones(size=(2,)) beta = torch.ones_like(alpha) num_trials = 100 total_count = torch.ones_like(alpha) * num_trial...
7fbd6cad31427583a02fcd316ad0373c9ea4accc45103d61ed659204731297a7
Python
2,632
83
"""Helpers for extracting per-spot morphology embeddings from a tissue image. The pyvips dependency is loaded lazily so this module imports cleanly even when libvips is not available. """ from __future__ import annotations import numpy as np from sklearn.decomposition import PCA from tqdm import tqdm from aestetik.ut...
c4d283f8f8792da005dafc427c131f2dc890eaf5d7efc66898e3e1d0446f8bda
Python
2,633
74
import torch from torch import Tensor import torch.nn as nn from torch_geometric.nn.conv import MessagePassing from torch_geometric.nn.conv.gcn_conv import gcn_norm from torch_geometric.nn.dense.linear import Linear from torch_geometric.typing import Adj, OptTensor, SparseTensor from torch_geometric.utils import spmm ...
cd2ae48d4775c5315a3caa032645b44139ac3e3fc585852eb7dbbe315ec0ae22
Python
2,633
73
"""Helper functions for setting up directories.""" import logging from . import constants logger = logging.getLogger(__name__) def make_spect_output_dir_in_generated(): constants.GENERATED_SPECT_OUTPUT_DIR.mkdir() def make_source_files_csv_dir_in_generated(): constants.GENERATED_SOURCE_FILES_CSV_DIR.mkdir...
58b9fefdbc4d03e9341b5af2fc273300083e1eed304d7ff0cdff611d33706c61
Python
2,634
79
import os from copy import deepcopy from os.path import dirname import numpy as np from model.builders.prostate_models import build_dense base_dirname = dirname(dirname(__file__)) filename = os.path.basename(__file__) task = 'classification_binary' selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.cs...
a5aafc01f559fbbf7fc69e7585c23730aafe986af7e7d455e31a3a36c6585db8
Python
2,634
84
from __future__ import annotations import json from importlib.resources import files from pathlib import Path from typing import Any from poetry.factory import Factory from poetry.toml import TOMLFile SCHEMA_FILE = files("poetry.json") / "schemas" / "poetry.json" FIXTURE_DIR = Path(__file__).parent / "fixtures" SO...
aa5a25ed6381942357213493fb9543be89fa7e3e5d998acaec3970bf44ba46d7
Python
2,634
50
import numpy as np import argparse import os parser = argparse.ArgumentParser() parser.add_argument("simulation", type=str, help="Name of the simulation") parser.add_argument("c1", type=int, help="Position of c1 index in PDB") parser.add_argument("seed", type=str, help="Random seed") parser.add_argument("checkpoint_fo...
ae9c97a2dfa606c0d9c0aa768a7ad0278a05dd4c44f100851b2a518d816f93b5
Python
2,634
82
import numpy as np import pandas as pd from scipy import stats from ._base import _CITestResult from .pearsonr import Pearsonr class FisherZ(Pearsonr): r""" Fisher's Z test for conditional independence on continuous data. This test first computes the Pearson or partial correlation coefficient :math:`\rh...
3a68c5eeaa5eb235d2ecddca0a255c05323cf8e4a836249c7b98a5d37b5b660e
Python
2,635
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. class DynamicLossScaler(object): def __init__( self, init_scale=2.0**15, scale_factor=2.0, scale_window=2...
8ec07609b22fc78abe07e3dcdd04a94f1a29ebb30235814bc028aa5ccbb5b6af
Python
2,635
62
import pandas as pd from pgmpy.base import DAG from pgmpy.datasets import list_datasets, load_dataset def test_load_linear_gaussian_dataset(): # Default parameters produce a 1000x5 DataFrame with a matching DAG. ds = load_dataset("linear_gaussian", seed=42) assert ds.data.shape == (1000, 5) assert se...
2b4a9028cfc621a1c78ad4547eda1ade1661caf60451d4ff6b1c81b840ad148c
Python
2,636
62
import numpy as np from numpy import matlib from Div_KL import Div_KL def Div_JS(P,Q): """ Jensen-Shannon divergence of two probability distributions dist = JSD(P,Q) Kullback-Leibler divergence of two discrete probability distributions P and Q are automatically normalised to have the sum of one...
29b27e4a960b0939147f73b2d204a19e2af27c0b161d9d99c37d1a17a2006225
Python
2,637
85
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": [220, 80, ...
0ca996846210f5b27b614c3045554db54829049d504697d11bb9ab77acc7af12
Python
2,638
75
import sys import numpy as np import torch from torch import nn sys.path.append("../model/") # path to this folder from load import * class LinearProbingClassifier(nn.Module): def __init__(self, ckpt_path,frozenmore=True): super().__init__() self.ckpt_path = ckpt_path self.frozenmore = fr...
124ac22f8b4cac1f6a4f51a37911ffa111b4e1c2a58962705578914ab2f4149b
Python
2,638
106
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created script, # Author_and_contribution: Qirong Mao; implemented method import argparse # TODO adjust description parser = argparse.ArgumentParser( description="Neighbor definition based on numbers of neibourhood (only for generic coo...
df1ef338201efb7fdb0e200a465b6ddbb097e80797a0c6d8b542f9ed8fbd6b26
Python
2,638
82
import sys import torch import os import inspect from fairseq import checkpoint_utils, data, options, tasks import pandas as pd from tqdm import tqdm import pysam #from datasets import load_from_disk from torch.utils.data import DataLoader, TensorDataset, Dataset path='../weights/HydraRNA_model.pt' # change the path...
153345f10f489892f131edcc1c180a893b2197b9a8c9888f8535bb87b6b19027
Python
2,639
79
#!/usr/bin/env python3 """Sync example READMEs from examples/ to docs/examples/ for MkDocs.""" from __future__ import annotations import argparse import sys from pathlib import Path REPO = Path(__file__).resolve().parents[1] SCRIPTS = REPO / 'scripts' if str(SCRIPTS) not in sys.path: sys.path.insert(0, str(SCRIP...
e02670c206bc8de1a6b390542e9c66c8fc840aaf7b6bb97e70aabf85566f185e
Python
2,639
71
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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...
b0602f534280ebc8c4a3cdad5b6e8e00990fbba30d6affbb3e433754fe7be20b
Python
2,640
89
import numpy as np from scipy.stats import entropy 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 = line.replace("\n", "") line_v...
1eee8e630a7dc6fbdf3e2688ad4c8324868b369e7401e10a02fc6f1fb34ab2ec
Python
2,641
80
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import torch import CBIG_pMFM_basic_functions as fc import warnings def CBIG_mfm_validation_desikan_main(gpu_index=0, ...
7f1b1d694b3b2cb520e7c5c6d1c044effc26370b4bb0b58cccb3cc12cacff22e
Python
2,641
73
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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...
e60253e1bfd5892a8600669d9e3054c4aa7c1089620a652511c150e7118878d2
Python
2,641
130
""" This module defines some common functions for argument parsing. Author: wangning(wangning.roci@gmail.com) Date : 2022/12/7 7:41 PM """ import argparse import random import numpy as np import paddle from paddlenlp.utils.log import logger def set_seed(seed): """set seed for random, numpy and paddle Ar...
f6cabc8d17be689796b2c9342abab6eac41aa9850518ef366b9885c7c8429719
Python
2,643
76
# 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 typing import Optional, List from omegaconf import II from fairseq.dataclass import FairseqData...
d6516f16bd1a8df85f898731cff98a5615dd8f6140c308a559c5c324161db0ef
Python
2,644
70
from PIL import Image from sklearn.decomposition import NMF, non_negative_factorization import cv2 import numpy as np from matplotlib import pyplot as plt import joblib from msi_visual.normalization import spatial_total_ion_count, total_ion_count, median_ion from msi_visual.visualizations import visualizations_f...
0507883c52387f1575a7e9c2630f14797637a3f6aa472b4f1ea90fe5b3e822ca
Python
2,645
48
from argschema import ArgSchema, ArgSchemaParser from argschema.schemas import DefaultSchema from argschema.fields import Nested, InputDir, NumpyArray, String, Float, Dict, Int, Bool, OutputFile from ...common.schemas import EphysParams, Directories, CommonFiles class DepthEstimationParams(DefaultSchema): hi_nois...
0912ed0350cb0e9813a5e5bd3de7471a62dc78c648e1cb8db796f1453b56811e
Python
2,645
77
# 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 uuid from fairseq.logging import metrics class TestMetrics(unittest.TestCase): def test_nesting(self): w...
7b40ad71aa8f6779803ab3cd38b4834abf13e53d522e7508b1bf3c36b1c92b0b
Python
2,645
79
"""tests for vak.common.files.spect module""" import itertools import pathlib import pytest import vak.common.files from vak.common.constants import VALID_AUDIO_FORMATS from ...fixtures.spect import ( SPECT_LIST_MAT, SPECT_LIST_NPZ, ) SPECT_LIST_MAT = SPECT_LIST_MAT + [ # duplicate list but replace un...
356c74ab2a6eb8785468145aad5b025d5686cea41ba739e9c3fe56f4655eb6d7
Python
2,646
108
#!/usr/bin/env python # Author_and_contribution: Niklas Mueller-Boetticher; created script, # Author_and_contribution: Qirong Mao; implemented method import argparse # TODO adjust description parser = argparse.ArgumentParser( description="Neighbor definition based on number of rings of neighbors (only for grid...
d5979bae33adfbefcf9f94c1be49e16fe230f977f5c2a20705ba363082e51710
Python
2,647
97
from __future__ import annotations import dataclasses import json from abc import ABC from abc import abstractmethod from typing import TYPE_CHECKING from typing import Any from cleo.io.null_io import NullIO if TYPE_CHECKING: from collections.abc import Sequence from cleo.io.io import IO UNSET = object(...
62821ed108f4ba8c3adae9d48328831959c36f8b46bd3a9e18e9f148ad8d8763
Python
2,649
66
import tensorflow as tf from tensorflow.keras import Input, Model from tensorflow.keras.layers import Dense, GRU, LayerNormalization, Reshape def dummy_fn(): ''' We need to define all custom objects when we load our models, so this gives us a dummy function to use if we choose to load the forward and/or i...
515d1c57d7226de4eb7fcb98ac77bc12b6909fd677dee4b534e072cf900c3c1b
Python
2,650
64
"""Embedding (semantic) pattern similarity of verbal reports (R2). Tests whether each report's Mistral-7B embedding is more similar to its OWN excerpt's consensus narrative than expected by chance, via a permutation test on shuffled excerpt labels. Carved from the full package's behavioral module (R1 and R3 are out of...
8d2f8e2138c497a870319aa59bd93a5baf23d18ba5f01b9ddef4fd8c2020f9f4
Python
2,654
99
import base64 import codecs import logging import os from io import BytesIO from ..types import Any logger = logging.getLogger(__name__) PNG_FORMAT = "png" JPG_FORMAT = "jpeg" GIF_FORMAT = "gif" PDF_FORMAT = "pdf" SVG_FORMAT = "svg" EPS_FORMAT = "eps" B64_FORMAT = "base64" def make_snapshot( engine: Any, f...
95de1136585768489e2bca4913a6520a2153749d3c74faf22abdc5441fc7981c
Python
2,654
86
#!/usr/bin/env python # ENCODE frac mito # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_lib_common import ( log, ls_l, mkdir_p, strip_ext) from encode_lib_log_parser import parse_flagstat_qc def parse_arguments(): parser = argparse.ArgumentParser( prog='ENCODE...
9281f58df201cab51c41889da344459b600a70c60989daae3965988aec3e5ea8
Python
2,655
77
from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import MagicMock from poetry.core.packages.utils.link import Link from poetry.packages.direct_origin import DirectOrigin from poetry.utils.cache import ArtifactCache if TYPE_CHECKING: from pathlib import Path from pytes...
4d09df377d0579fe3de474210cb107665bf7329b17616c0e03ee32e747e40848
Python
2,656
80
import torch.nn as nn import torch class SeparableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False): super(Separ...
646ce496031f3ea2d6bcf261793cfa64102f6be89eca6cdf0a4e49feadb9cc0a
Python
2,656
81
"""Smoke tests for the hippie-cli entry point. These cover the user-facing CLI surface declared in pyproject.toml: hippie-cli validate-data <dir> hippie-cli embed --datasets-root ... --datasets ... --output ... hippie-cli predict --reference ... --query ... --output ... The embed/predict tests are gated b...
ff3336000c8db6f3b8930870517e42a1d3899a75ed09a56e1dfac5712904a400
Python
2,656
92
# # 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 .iadc import IADC # Importing the different adc models so _create_adc works correct...
1f07378ea62e4e27aa9db7053afc4648ded4262c84852a2ac9d60c9a611ef518
Python
2,657
81
# Copyright 2016 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...
4924344b447921dd409334c2272771c03cd950302eaf225da00b9ba615e94a3e
Python
2,657
80
# 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 logging from operator import attrgetter import torch.distributed as dist import torch.nn as nn from ..pq.utils import attrsetter, get...
7b12fdf475285ac0da61c7dc118409ca638061d6573f8e8b09ac241ef08f7029
Python
2,658
71
# 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 ...
f6d01d96f0ddc45bc8101881bc17d071223067ed41df7154f7c1740127f1ab44
Python
2,659
86
# @license # Copyright 2023 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...
a84474c8b536e34be844ddac8f73e14d1967399ab15af38eb2e21e1f45627ac2
Python
2,660
83
# Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors import os import torch import numpy as np from dataclasses import dataclass, fields from torch.utils.data import Dataset from torch import Tensor from utilities.Utilities import detrace class Dataset(Dataset): def __init__(self, fol...
828641ea924d55be77fd200a485168d2f961b7c9c449473ea5688d2b0efb7e4d
Python
2,661
93
from argparse import ArgumentParser from pathlib import Path, PosixPath, WindowsPath import numpy as np import pandas as pd def main( csv, os, audio_path_parent=None, spect_path_parent=None, annot_path_parent=None ): """ "move" the paths in a .csv file saved by `vak prep`, by keeping the filename but cha...
64c5121f71a26024fc95c7acd496b12ca2d719b007f3d2fb71e56f8d8a859578
Python
2,662
98
import numpy as np import pandas as pd import pytest from skbase.lookup import all_objects from pgmpy.ci_tests import BaseCITest, ChiSquare, FisherZ, IndependenceMatch, Pearsonr, get_ci_test def test_ci_registry(): all_tests = [ ci_test.get_class_tag("name") for ci_test in all_objects( ...
69dfe1abd884981a855c2f13f63342e664b63fb15b92641edf52a6a8e096a616
Python
2,662
82
# # 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 cv2 from MLPerf_cal_images import get_cal_fns from ...
bc5e1d48d115211de09b2a952c297dbc338bdd332b1fdc3a9b3f4135893d13b2
Python
2,662
74
from ... import types from ...charts.chart import Chart from ...globals import ChartType class Chord(Chart): """ <<< Chord >>> The chord diagram visually presents the flow and weights within complex relationship networks, making it particularly suitable for multidimensional relationship analysis ...
02ad3e837af5d0fc9811bb2be32ee07ffdbb15f0282dc863e21acd2ada3ab1e8
Python
2,663
87
import xarray as xr import click import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from skimage.segmentation import mark_boundaries from matplotlib.widgets import Button def interactive_plot(cleanqueen, queenframe): selected_values = set(np.unique(cleanqueen[cleanqueen > 0])) # ...
7c825ceb9caa51fba4a75f159145b4b999fe3b588ab78a4d3b232b9607071c31
Python
2,663
78
#!/usr/bin/env python3 """Exercise non-interactive analyzer discovery and Qt initialization. This runner uses the real analyzer file-discovery code and Qt initialization dialog in offscreen mode. It does not enter the GUI event loop, open a window, or launch calculations. """ from __future__ import annotations impor...
a08383dd6cc7112c5bd802501a0ab85c8bd5219b1e40b5235f7736fd23aa8c36
Python
2,663
89
import matplotlib.pyplot as plt import numpy as np # Function to read data from a file and calculate mean, min, and max def calculate_stats(file_path): with open('./date/'+file_path, 'r') as file: data = [float(line.strip()) for line in file if line.strip()] mean = np.mean(data) min_val...
b267cc0e21b2714c025c6100e2f66bc41c096e19ccf52ab9195ee32cdaff06bf
Python
2,665
63
# -*- coding: UTF-8 -*- """Base class and shared context for GOEA term-scoring algorithms. A GOEA algorithm turns the per-term gene sets of a study into one uncorrected p-value per GO term. The default, `classic`, scores every term independently. Algorithms that exploit the GO DAG topology (`elim`) instead score terms...
6f046f94bac2434bf8adddaffe5f07ae096af5867f09f453c0f2850f2099e945
Python
2,666
87
""" This is an alternative version of MatrixManager. This is way faster but consumes more memory. The ordinary MatrixManager performs well enough when a gene's data is queried only once as in MetaXcan, and is memory efficient. This one, on the contrary, organizes data in a way that is fast to query but takes up more me...
cda7e528d7513f49e0e41f5de9e17ad182da748a0ee4271be7f6c9053121a4f6
Python
2,668
71
#!/usr/bin/env python3 # MIT License # # Copyright 2022 Broad Institute # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use...
efba43b281731ca5ab8b3d227617a22fa7001f2ff8ada5724d07f8f17923b512
Python
2,669
73
#!/usr/bin/env python3 import argparse import os from collections import defaultdict def intron_chain_key(fields): """ Group reads by splice junctions only, ignoring variable TSS/TTS. Multi-exon: 'chrom:strand:e1end-e2start,e2end-e3start,...' Mono-exon: 'chrom:strand:start-end:mono' """ chrom...
92bd1260d2596b01e062be2b566619fc993b4bc94db71226a7847929c85331a5
Python
2,670
69
from typing import List, Mapping, Optional import torch import re def load_pretrained( model: torch.nn.Module, pretrained_params: Mapping[str, torch.Tensor], strict: bool = False, prefix: Optional[List[str]] = None, verbose: bool = True, ) -> torch.nn.Module: """ Load pretrained weights to...