sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
728b3a3d7d4e92f8ddef36049c759b713e9e0b9dcebe6ad8be9f0ee9439800df | Python | 1,640 | 61 | import os
import re
def is_docker(pre_command):
return "docker" in pre_command
def get_directory(entry):
"""
Get the directory of an entry, to be mounted on docker
If entry is a list, it returns the common path.
If entry is a string, it returns the dirname.
"""
if isinstance(entry, list)... |
78f4b7f231ac3fc0e0f603ae362e012649883ffafce7925afd173a67ec55b97b | Python | 1,641 | 55 | from typing import List
from rinalmo.data.constants import *
class Alphabet:
def __init__(
self,
standard_tkns: List[str] = RNA_TOKENS,
special_tkns: List[str] = [CLS_TKN, PAD_TKN, EOS_TKN, UNK_TKN, MASK_TKN],
):
super().__init__()
self.standard_tkns = standard_tkns
... |
94e0b1eba58064ee1b3d4119023069e615b646de00cad2fdcca47892d898238f | Python | 1,641 | 33 | '''
Pure-python implementation of UCSC "liftover" genome coordinate conversion.
Copyright 2013, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
PyLiftover is a library for quick and easy conversion of genomic (point) coordinates between different assemblies.
It uses the same logic and coordinate... |
c8cb93d5fc5b5b56fa5cda12d849a74e947d2e3e10b39ee4c63307e7ec7f5db6 | Python | 1,641 | 49 | """Read a Gene Product Association Data (GPAD) and store the data in a Python object.
Annotations available from the Gene Ontology Consortium:
GPAD format:
http://geneontology.org/page/gene-product-association-data-gpad-format
"""
import collections as cx
from .annoreader_base import AnnoReaderBase
... |
7cd268ec5b081cc9e0079cb51d7f0927404a5c3536bc05b206d65ecce7185c06 | Python | 1,642 | 50 | # 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
from fairseq.data.encoders import register_bpe
from fairseq.dataclass im... |
8d92fa0f4cba77487d17e39b67c6686ff892cf26044b85b0161e0600ed51c4ff | Python | 1,643 | 37 | import os
import time
import argparse
import utilities as utilities
import logging
def run(best_params, args):
# 1) Load the training data
train_pmids, train_docs = utilities.process_data_from_npy(args.input)
logging.info("Retrieved RELISH Cleaned Data")
logging.info(len(train_pmids))
logging.inf... |
b8f7fc1bd71b94af32aa24edafd5742b49bee84f0098044569e538ac00a63eae | Python | 1,643 | 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 re
WHITESPACE_NORMALIZER = re.compile(r"\s+")
SPACE = chr(32)
SPACE_ESCAPE = chr(9601)
# excluding non-breaking space (160) here
PRIN... |
ce4561959c36dc5406e67ff00cdefb99a9a4d386d5151e8443abad9479cdeb78 | Python | 1,643 | 42 | import torch
import utils
import numpy as np
def kl_divergence_with_probs(p=None, q=None, epsilon=1e-20):
"""Compute the KL between two categorical distributions from their probabilities.
Args:
p: [..., dim] array with probs for the first distribution.
q: [..., dim] array with probs for the second dis... |
dcff4090601fc83668f11164c2f99eb3cad0cdff6a808a210426635122a58bc3 | Python | 1,643 | 50 | from pathlib import Path
import os
import argparse
import random
import numpy as np
from sklearn.utils import shuffle
if __name__ == "__main__":
"""
this is a standalone script to process a km file
specifically, to dedup or remove tokens that repeat less
than k times in a row
"""
parser = argp... |
1cea4d1964a06025a9647cbe52fd803daa57f273dd50300a0c81fc48a4752a00 | Python | 1,645 | 47 | """Reference-genome access for single-species GPN."""
import gzip
from typing import Any
import pandas as pd
from Bio import SeqIO
from Bio.Seq import Seq
def load_fasta(path: str, subset_chroms: set[str] | None = None) -> pd.Series:
opener = gzip.open(path, "rt") if path.endswith(".gz") else open(path)
wit... |
597b9e9a9bbdcc52ad7b4a195ce0cbea47b06483954ff2bd257b8bdfcdadc8a1 | Python | 1,645 | 75 | import numpy as np
import pandas as pd
from anndata import AnnData
import novae
from novae._constants import Keys
obs1 = pd.DataFrame(
{
Keys.SLIDE_ID: ["a", "a", "b", "b", "a", "b", "b"],
"domains_key": ["N1", "N1", "N1", "N1", "N3", "N1", "N2"],
Keys.IS_VALID_OBS: [True, True, True, True... |
7c9136d312a3a4517287d5e13a7fbfb74d35441161b996ff9761415f33d59f73 | Python | 1,645 | 54 | #!/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 argparse
import logging
from pathlib import Path
import soundfile as sf
from examples.speech_to_text.prep_mustc_... |
812051d9deb614c136248b7c4fb5e653b6fde062100cfb799d82db186ed0ffa6 | Python | 1,645 | 51 | ### CONVERT PLEIOFDR RESULTS TO CSV ########################
# -- Modules -------------------------
import pandas as pd
import scipy.io as sio
import os
import argparse
# -- Parse arguments -------------------------
parser = argparse.ArgumentParser(description="Convert PleioFDR result.mat file to csv")
requiredName... |
4a97d5bd14847c09b309fd4138039a9362c690ae4f293a93f4894d8082cc977d | Python | 1,647 | 60 | 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 ImpliedCIs
SEED = 42
N_SAMPLES = 1_000
EDGE_PROB = 0.1
@pytest.fixture(scope="module")
def rng():
return np.random.default_rng(SEED)
def simulate(model, n_sam... |
7801d6608c77cec938659dff2b412038b1308413868d69f825daa53321c6d3ee | Python | 1,647 | 44 | # 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.
def parse_config_yaml(yaml_data):
# Initialize to default options.
quantization_options = {
"n_centroids": {
"Lin... |
2f85431de7ad7544e9ba77e290a69ae364c1c2fcb43d02147c25fa641a518c7f | Python | 1,648 | 62 | """
Main hybrid model implementation.
IEEE-style modular structure:
- ViT feature extractor
- MaxViT feature extractor
- Projection layers
- Gated fusion
- Classification head
"""
import torch
import torch.nn as nn
import timm
from models.fusion import GatedFusion
class HybridTransformerModel(nn.Module):
"""Hyb... |
4539998f7374669176884fed64881dedc3c463b43b6ed91cd6bd5fe0cdb363b9 | Python | 1,650 | 45 | from setuptools import Extension, setup, find_packages
setup(name='TractSeg',
version='2.10',
description='Fast and accurate segmentation of white matter bundles',
long_description="See Readme.md on github for more details.",
url='https://github.com/MIC-DKFZ/TractSeg/',
author='... |
8bc3111dca60fa9a6d6e9a6a62be880ac7a6e863dbd915237733bc94d61a96fc | Python | 1,650 | 72 | from __future__ import annotations
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.__version__ import __version__
from poetry.utils.env import MockEnv
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from pytest_mock import MockerFixtur... |
486db0405fe41502fee082ef05fe4660b7ae6dad2fec8d93583f05829b272816 | Python | 1,651 | 51 | import os
import cv2
import numpy as np
from keras.utils import img_to_array
from sklearn.model_selection import train_test_split
from image_utils.image_utils import load_grayscale_image
def load_data(image_dir, mask_dir, img_size, convert_1_channel_to_3=False):
images = []
masks = []
names = []
image... |
c994b8c2f82a80a45c922fcdae07a7c8a1b1c075b987c21b60525b62b4be3234 | Python | 1,651 | 69 | from __future__ import annotations
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.utils.env import MockEnv
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from pytest_mock import MockerFixture
from tests.types import CommandTeste... |
1a401159734fec92ab69942a33bb6d7316280f09ee8288223af8261a3a258f55 | Python | 1,652 | 49 | """
Copyright (c) Facebook, Inc. and its affiliates.
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
Adapted from https://github.com/FAIR-Chem/fairchem/blob/main/src/fairchem/core/models/gemnet/initializers.py.
"""
import torch
# This function is not type annotated because mypy complains that ax... |
7ba24f030fd593a61ee6a3d4d87fb434eeb0903f8b7c2510dbcf9754228e877a | Python | 1,652 | 58 | import argparse
import neuroglancer
import neuroglancer.cli
import numpy as np
def add_example_layers(state):
a = np.zeros((3, 100, 100, 100), dtype=np.uint8)
ix, iy, iz = np.meshgrid(
*[np.linspace(0, 1, n) for n in a.shape[1:]], indexing="ij"
)
a[0, :, :, :] = np.abs(np.sin(4 * (ix + iy))) ... |
8dd425d7a237f9afe37c08e549e33e0fadc6a67bc4fbf0817f85ca8839411346 | Python | 1,652 | 53 | """
Utility functions for the workflow.
"""
import os
import torch
def get_least_busy_gpu() -> int:
"""
Get the least busy GPU.
"""
if not torch.cuda.is_available():
return None
free_memory = [torch.cuda.mem_get_info(i)[0] for i in range(torch.cuda.device_count())]
return free_memory.in... |
01d5a245ad6fc38ba2fa1cced2424a0f8f8af56b37b3e6f6154dc5238643f458 | Python | 1,653 | 54 | from pgmpy.independencies import IndependenceAssertion
from ._base import BaseCITest, _CITestResult
class IndependenceMatch(BaseCITest):
"""
Check if `X ⊥⊥ Y | Z` is in `independences`.
This method is implemented to have a uniform API when the independences
are provided explicitly instead of being i... |
9778c315a0898c49ca4d592272710998dc13411ded394d9b4fc86814571316b9 | Python | 1,653 | 46 | """Convenient data fetchers for tutorial examples"""
import os
import numpy as np
DATA = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
def load_example_data(dataset='default_mode', join=False):
"""Load example datasets for tutorials
Precomputed association maps for terms 'default mode' or... |
43e34720fab4a81760ad194fe8715c6d292ab730a2db115237fbc673f76773e1 | Python | 1,654 | 50 | """The uncaught-exception handler, and the notes stackprinter drops.
stackprinter renders only the traceback and the exception's own message, so a
note attached with `add_note` reaches pytest and a plain `python -c` and is
dropped from every console script — the one path it was written for.
"""
import sys
import type... |
4ba144802c56804386352ee897c215cf71067399d202ee25c8e37214b60a0a29 | Python | 1,656 | 61 | import numpy as np
import pandas as pd
import pytest
from scvi.data import synthetic_iid
from scvi.external import CellAssign
def get_test_adata_marker_mat():
adata = synthetic_iid(
n_labels=5,
)
adata.obs["size_factor"] = adata.X.sum(1)
marker_df = pd.DataFrame(data=np.random.randint(2, siz... |
6a672af167900cd43c1eec33964cbb35fe7fdd16ffd3ca0eb510fcd840a39510 | Python | 1,657 | 34 | #!/usr/bin/env python3
"""Gera o bloco markdown da Tabela 1 (controle de SOC) a partir do JSON medido.
Numero nenhum e transcrito a mao: o markdown sai do `resultado_soc_onsite.json`
(escrito por `analisa3.py`), que sai dos 24 `.EIG` -- nosoc de work2/, soc de work3/.
O antigo `resultado_soc_stringent.json` (work2, SO... |
a2147c8f7869fad777bdeb1d8ad62dfcc207f612c834e51f39afba353ccd2bf0 | Python | 1,659 | 45 | from pathlib import Path
import pandas as pd
# Define file paths using pathlib
root_path = Path(r'/egor2/egor/MovieProject2/')
raw_data_path = root_path / 'raw_data'
output_path = root_path / 'bids_data' / 'sourcedata'
cognitron_file = raw_data_path / "Cognitron_assessment_participants.tsv"
notes_file = raw_data_path... |
a1a517e92e1da26e380027886582a97ea21377b1e0548afa26f92a881b90c9a9 | Python | 1,660 | 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.
from dataclasses import dataclass, field
from fairseq.data.encoders import register_tokenizer
from fairseq.dataclass import FairseqDataclass
... |
a1db3c650d1f40358f8565e6d170a4e764708bf5e1787f18639d8f74fb3a7c78 | Python | 1,660 | 55 | import pytest
from pgmpy.base import DAG
from pgmpy.identification import Frontdoor
@pytest.fixture
def frontdoor_model():
return DAG([("X", "M"), ("M", "Y")], roles={"exposures": "X", "outcomes": "Y"})
@pytest.fixture
def frontdoor_model_latent():
return DAG(
[("X", "M"), ("M", "Y"), ("U", "X"), (... |
c28a2080f2030efbfad9206b718296904752252586b11d9a6965278bdc366087 | Python | 1,660 | 49 | import numpy as np
def Ent_Ap(data, dim, r):
"""
Ent_Ap20120321
data : time-series data
dim : embedded dimension
r : tolerance (typically 0.2)
Changes in version 1
Ver 0 had a minor error in the final step of calculating ApEn
because it took logarithm after summ... |
1702b28d79eea2bce54d828ebc2bd367fbe9bbd4aca835484996692043273486 | Python | 1,661 | 50 | """
MedViT classification-oriented baseline.
Important:
Because "MedViT" is not consistently exposed as a standard pretrained model
across common PyTorch libraries, this implementation provides a practical
medical-imaging-oriented approximation:
- convolutional stem for local inductive bias
... |
78da46133f970fcd3baa1b61388b1892ddbec4f1a9bc0301633e2609be36428c | Python | 1,661 | 43 | """Tasks for grouping."""
__copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
from goatools.grouper.hdrgos import HdrgosSections
class SummarySec2dHdrGos(object):
"""Summary for a sections variable containing sets of header GO IDs."""
def ... |
2b748787f75a037d12515cb9859f63cb339300a2c032c7abed524436b842eaeb | Python | 1,662 | 51 | import wandb
from celltype_ibl.models.metrics import topk
class wandblog:
def __init__(self, name, config, entity, project, topk, wandb_dir):
self.topk = topk
self.name = name
self.weights_artifact = wandb.Artifact(
name="weights_" + self.name, type="weight_log"
)
... |
08d3c53b41a39d3b2d11e169620807c229a5680c43390d3d9c447405b398deff | Python | 1,664 | 59 | #!/usr/bin/env python
# ENCODE DCC TAGALIGN pooler wrapper
# Author: Jin Lee (leepc12@gmail.com)
import sys
import os
import argparse
from encode_common import *
def parse_arguments():
parser = argparse.ArgumentParser(prog='ENCODE DCC TAGALIGN pooler.',
description='')
... |
7dd61cbe6555e3a010c3ffea17104f62a07298e8f41e8245a4cacb453783b79d | Python | 1,664 | 55 | from __future__ import annotations
import shutil
import uuid
from pathlib import Path
import pandas as pd
from src.features.telemetry_alignment.io.static_settings_store import (
TelemetryStaticSettingsStore,
)
class _DummyApp:
pass
def test_static_settings_store_writes_to_user_config_dir(monkeypatch):
... |
5b13716e7aaa8e49b8a325da52d8ad343b2e8e8cc2a01d40a6d005ce9e6e6914 | Python | 1,665 | 38 | from typing import List, Tuple, Union
from batchgenerators.transforms.abstract_transforms import AbstractTransform
import numpy as np
class ConvertSegmentationToRegionsTransform(AbstractTransform):
def __init__(self, regions: Union[List, Tuple],
seg_key: str = "seg", output_key: str = "seg", seg... |
9bc80b89474758f95fef1eadc1ddac0a76b56a5ad49e9ba547d07a54f395332c | Python | 1,665 | 48 | #!/usr/bin/env python
"""Embedding (semantic) pattern similarity of verbal reports (R2).
For music-report and speech-report: test whether each report's Mistral-7B
embedding is more similar to its own excerpt's consensus narrative than to a
shuffled excerpt (1000-permutation null). Writes the observed/null means, z, p.... |
9e7d196064ecfc15b16506daddaa3f968ff86e3481437cfd0eedf1a1c452499c | Python | 1,667 | 55 | from __future__ import annotations
import re
import shutil
import subprocess
import typing
import pytest
from poetry.vcs.git.system import SystemGit
if typing.TYPE_CHECKING:
from pathlib import Path
from tests.vcs.git.git_fixture import TempRepoFixture
GIT_NOT_INSTALLED = shutil.which("git") is None
de... |
bbe31862bebd8ba06e2865e21d65ed18199ab47f4e6749b832f1268f850c6081 | Python | 1,667 | 57 | def assemble_csf_motion_confounds_mat(motion, csf):
import pandas as pd
import os
motion_df = pd.read_csv(motion, sep='\s+', header=None)
csf_df = pd.read_csv(csf, sep='\s+', header=None)
# regress 24 motion parameters and csf (but not white matter)
confounds = pd.concat([motion_df, motion_df*... |
d8603a818e4ab5875c601e5ff500d4ee8670282c2f0371abca9d188bbbd6ba39 | Python | 1,669 | 59 | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.core.pyproject.toml import PyProjectTOML as BasePyProjectTOML
from tomlkit.api import table
from tomlkit.items import Table
from tomlkit.toml_document import TOMLDocument
from poetry.toml import TOMLFile
if TYPE_CHECKING:
from path... |
e81c861cf03e2ad076f524042b8afaed860972616ec0b0549aeb310f3431062b | Python | 1,670 | 108 | """
Atomic radii in picometers
NaN stored for unavailable parameters.
"""
ATOMIC_RADII = {
0: float("NaN"),
1: 25.0,
2: 120.0,
3: 145.0,
4: 105.0,
5: 85.0,
6: 70.0,
7: 65.0,
8: 60.0,
9: 50.0,
10: 160.0,
11: 180.0,
12: 150.0,
13: 125.0,
14: 110.0,
15: 100.... |
0f7c3d0fb2bcedc3e94ac722a8470a292a291668960c9d49a322e73fe4a244ca | Python | 1,671 | 38 | import os
import time
import argparse
import logging
import subprocess
import utilities as utilities
import gensim.downloader as api
import gensim.models as model
from gensim.models import Word2Vec
def run_pretrained(args, model_directory):
# 1) Load the pre-trained Word2vec model
try:
model = api.loa... |
bdd6decee41806d4fc0b67afbd00bd03435b421ef4066b251186faf739fa6d62 | Python | 1,671 | 43 | import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from configs import DATA_DIR, LOG_DIR, VIS_DIR
from utils import mnist_reader
from utils.helper import get_sprite_image
X, Y = mnist_reader.load_mnist(path=DATA_DIR, kind='t10k')
la... |
5f16b78a8e31a2f66b9e2aa48dcc0dcd432df20cec89ef848ca8871a2fe3263e | Python | 1,672 | 40 | """HIPPIE utility helpers.
The canonical inference path lives in ``hippie.inference.HIPPIEClassifier``;
the function below is a low-level legacy helper retained for callers that
want to run two separate per-modality encoders side by side. New code
should prefer ``HIPPIEClassifier.get_embeddings``.
"""
from __future__... |
a08b58d8bd4a17c9a791234b60cf17f1a7d1813995dce59d07d8e69fa632f1ee | Python | 1,672 | 52 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join
import nibabel as nib
from joblib import Parallel, delayed
import numpy as np
from tractseg.libs.system_config import SystemConfig as C
from tractseg.data.subjects import get_all_subje... |
c726ae5c8457429d26036a535bde01b2b4c9b518ef14a901b02ead87523ebc8a | Python | 1,675 | 50 | from pgmpy.datasets._base import BaseDataset
class PopulationThresholdRDDItaly(BaseDataset):
"""Italian municipality sample from the Eggers et al. population-threshold RDD data.
Each row is a municipality-year compared to a nearby population cutoff.
``pop_dev`` is the running variable (census population ... |
8bca47a9b655d81308f15bed0354725a09169410b9f7c24f801ac1b54a6b4e02 | Python | 1,676 | 42 | # 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 ... |
ae6ccd307880f806d484e4bfa48ffb58dd529c3bf251c78704491196f0f4d5ff | Python | 1,676 | 57 | import re
from scvi.utils import dependencies
@dependencies("requests")
def validate_url(url: str, error_format: bool = False, error_response: bool = False) -> bool:
"""Validates a URL.
Source: https://stackoverflow.com/questions/7160737/how-to-validate-a-url-in-python-malformed-or-not
"""
import re... |
b1a1de1358cc83ac1544587accea6a97fb88a15c3b6f275dc361d439f2f511bd | Python | 1,676 | 47 | import numpy as np
import scipy.sparse as sparse
# TODO: (see https://github.com/jundongl/scikit-feature/blob/master/skfeature/function/similarity_based/lap_score.py)
def laplacian_score(X: np.ndarray, W: sparse.coo_matrix) -> np.ndarray:
"""
This function implements the laplacian score feature selection, steps are... |
372619771b39f8e82940918af5a3df2b036f2fae8a73ce60e0625446b0e91358 | Python | 1,678 | 58 | """Numpy 2.0-compatible CharLevelTokenizer.
Drop-in replacement for stripedhyena.tokenizer.CharLevelTokenizer that uses
np.frombuffer instead of the removed np.fromstring (binary mode).
"""
from typing import List, Union
import numpy as np
import torch
class CharLevelTokenizer:
"""Character-level tokenizer that... |
bc0346da28e49df917dd77e2aec81397598bda495cb9634e5ec7bd706a8bfe0d | Python | 1,678 | 48 | # 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 fairseq.data import Dictionary
from fairseq.modules import CharacterTokenEmbedder
class TestCharacterToke... |
43d3954bdb126a6eb1c7b06bf0d26c610fc3fab5b62157a9b8f59c59a8669ff9 | Python | 1,679 | 48 | from functools import partial
from typing import Tuple
import jax
from .device_utils import DEVICE_AXIS, rng_iterator_on_devices, split_rng_key_on_devices
from .observables import Observable
from .types import RandomKey, WeightedElectronConfiguration
__all__ = ()
def eval_wf( # noqa: C901
rng: RandomKey,
... |
2a624663a40acb5699a8947625528ae3ce7b74aa5da9e2f2ceb05b4f4869bf77 | Python | 1,683 | 40 | """Lightweight Hydra config checks before training (no full schema migration)."""
from __future__ import annotations
from omegaconf import DictConfig, OmegaConf
from dlbase.registry import get_dataset_plugin, get_model_plugin, get_task_plugin
def validate_hydra_cfg(cfg: DictConfig) -> None:
"""Fail f... |
49c60b936ad4f48e41c37d757ff778b3fd06cb93928fe981f749ff5d29659156 | Python | 1,683 | 53 | # 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
from torch import nn
from torch.nn.modules.utils import _single
from torch import Tensor
class ConvTBC(torch.nn.Module):
""... |
705eb6d0a909b7e125ec3ce379e89d9a2a9e34db13f02bab2dc459bdf6f73fbe | Python | 1,685 | 64 | import argparse
import re
import sys
from typing import TextIO, Optional
import pandas as pd
# Write Sample IDs and optionally Sample Names from a barcodes file
# The Sample IDs are derived from the SampleName column by replacing
# non-alphanumeric characters with underscores.
def get_args():
parser = argparse.... |
4ca40e21879f94044715854220409279d0d67a0137434758b19e780b31750674 | Python | 1,686 | 62 | """
Base abstractions for distillation methods.
Each method implements a unified interface so the distiller can assemble
them dynamically based on the user configuration.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Tuple
import torch
class DistillationMethod(... |
b037e0cdfc1701f1cca6edb2cd4bb52bc3601f01d5f62f102780296374ce540d | Python | 1,686 | 49 | """
Swin-UNETR classification adaptation.
Important:
Swin-UNETR is originally a segmentation architecture from MONAI.
This adaptation uses the encoder output as an image-level representation
for GI disease classification.
Requirements:
pip install monai
"""
from __future__ import annotations
import ... |
b003eb23edda6748b5714e7f69999b450a2a3637fb6bb6de3b9b2b203ea60423 | Python | 1,687 | 55 | # -*- coding: utf-8 -*-
"""
Created on Sat May 24 08:22:24 2025
Utils for pybounds mpc simulations.
@author: mayc06
"""
import numpy as np
import copy
def wrapTo2Pi(rad):
rad = copy.copy(rad)
rad = rad % (2 * np.pi)
return rad
def wrapToPi(rad):
rad_wrap = copy.copy(rad)
q ... |
7133cf00adb1bbd983abd672de53a48143a97e9478ebbf8796dff1ef389a02d0 | Python | 1,688 | 54 | from . import (
default_parameters,
extract_raw_waveforms,
quality_metrics,
ephys_properties,
save_utils,
loading_utils,
helper_functions,
plot_functions,
classification,
manual_analysis,
unit_quality_gui,
methods_text
)
from .default_parameters import *
from .extract_ra... |
102955fa7ac309c4034f5b419b57a86bb942d5afce37b537bc5161a3121ff222 | Python | 1,690 | 39 | from setuptools import setup, find_packages
setup(
name = 'ecephys_spike_sorting',
version = '0.1.0',
description = """Tools for spike-sorting Allen Institute Neuropixels data""",
author = "Josh Siegle, Nile Graddis, Xiaoxuan Jia, Gregg Heller, Chris Mochizuki, Dan Denman",
author_email = "joshs@al... |
7fe6df24440306383f862a0d36e9489d75a3db36a5a972a620aacea68e469725 | Python | 1,691 | 66 | from pgmpy.datasets._base import BaseDataset
class CysticFibrosis(BaseDataset):
_tags = {
"name": "cystic_fibrosis",
"n_variables": 44,
"n_samples": 41,
"has_ground_truth": False,
"has_expert_knowledge": False,
"has_missing_data": True,
"has_index_col": Fals... |
d68b3260880ef2d7a8697c3cf0173f47b7b990b3f60f52ccbb9462dff40848d4 | Python | 1,692 | 63 | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Any
from poetry.config.config_source import ConfigSource
from poetry.config.config_source import PropertyNotFoundError
from poetry.config.config_source import split_key
if TYPE_CHECKING:
from collections.abc import Sequence
... |
469dbe3a3f80a889382b960d01948c218843e913b32cfaf8eb5166b59e94366d | Python | 1,693 | 47 | from fooof import FOOOFGroup
from fooof.analysis import get_band_peak_fg
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import mne
def colorbar(mappable):
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axe... |
7de2d3331d0a5ff3febd8203c7d1c15ba8e112d3f289e96bf0e1b02fce764af7 | Python | 1,693 | 26 | import sys
from models.STAG.cross_validation import cross_validation as cv_STAG
from models.CNN_3D.cross_validation import cross_validation as cv_CNN_3D
from models.Contacts.cross_validation import cross_validation as cv_Contacts
tables = {'GLCTLVAML':'datasets/GLCTLVAML/GLCTLVAML.csv','IVTDFSVIK':'datasets/IVTDFSVIK... |
0538c55238b0b759728875856ccc157e538252c98d68361ac18825bfccbaf19f | Python | 1,696 | 39 | from neuron import h, gui
import numpy as np
from simulator.model.utils.record_intrinsic import record_intrinsic_currents, preprocess_intrinsic_data
from simulator.model.utils.record_synaptic import record_synaptic_currents, preprocess_synaptic_data
from simulator.model.utils.record_membrane_potential import record_me... |
85276f2ebc5264b2baf3c01e4472ca6c13de738de2ecf852d4d3c4e4d72153f6 | Python | 1,696 | 33 | import streamlit as st
import glob
from msi_visual.extract.pymzml_to_numpy import PymzmlToNumpy
from msi_visual.extract.bruker_tims_to_numpy import BrukerTimsToNumpy
from msi_visual.extract.bruker_tsf_to_numpy import BrukerTsfToNumpy
st.title('Convert a PyMZML or Bruker TSF/Tims files into an MSI-VISUAL numpy fi... |
e2219ec684121306487d42f658bfed68cc6247e8068cd8cda7c7499b1755610c | Python | 1,696 | 42 | '''This script removes object scene instances with missing files, before data preprocessing.'''
import os
import glob
# Define the base directory
base_dir = '../Data/Jacquard_Dataset_1'
# List of file types
file_types = ['grasps.txt', 'RGB.png', 'stereo_depth.tiff', 'perfect_depth.tiff', 'mask.png']
# Navigate thro... |
e750a0474820d3091bf397c81f0129960aac7827f51ddf3db30c385458f0007a | Python | 1,699 | 48 | """Annotation Extension for relational expressions.
https://link.springer.com/protocol/10.1007/978-1-4939-3743-1_17
http://wiki.geneontology.org/index.php/Annotation_Extension
Correlated function associations between genes and GOs containing contextual information.
With contextual information identify ge... |
0c596b050f993c7c04ddab50d50879c631160ead04c5945a85cf7e072f92b786 | Python | 1,700 | 71 | from pgmpy.datasets._base import BaseDataset
class AbaloneContinuous(BaseDataset):
"""
References
----------
- :footcite:t:`lopezpaz_2015`
- :footcite:t:`uci_abalone`
"""
_tags = {
"name": "abalone_continuous",
"n_variables": 8,
"n_samples": 4177,
"has_grou... |
b5cd104b398f9c82e3eed2b2b89718c87ebb30689b9a9150d8b1ff8b55bd17ba | Python | 1,700 | 46 | #!/usr/bin/env python3
"""A little script to add multiple bigwig files together.
This is mostly to combine replicates.
"""
import argparse
import numpy as np
import pyBigWig
from bpreveal import utils
def addBws(bwFnames: list[str], outFname: str, chromSizes: str) -> None:
"""Take the given bigwig files and add ... |
22e1ae3be51ec5281a06e29fb771ab208f244a3ba9df986b2d456b727174b73b | Python | 1,701 | 74 | from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from poetry.console.commands.self.install import SelfInstallCommand
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from tests.types import CommandTesterFactory
@pytest.fixture
def command() -> str:... |
6d37f08da9af7feb3a88743ced59a63d6c6ad4925d931bbe8aca18fb98b1efc9 | Python | 1,701 | 44 | #!/usr/bin/python
# This script will generate each subjects design.fsf
# To run it: python design_file_generator
# Adapted from Jeanette Mumford's script at https://mumfordbrainstats.tumblr.com/post/137507143321/get-some-data-and-get-ready-to-learn-fsl
import os
import glob
# directory where your study lices
dir = ... |
cd254f0ab408aa0dcfd7e751b5450593ea233b6b5ac14349a0c9336c68241cb4 | Python | 1,701 | 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.3,0.4), fb_multiplier=(0.3,0.0), er_multiplier=(0.01,0.0... |
dfc9b667458bc22d9c818985d119007763b850f986b0dbfb0bec6b31eb202e75 | Python | 1,701 | 53 | from __future__ import annotations
import pytest
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
from poetry.core.packages.project_package import ProjectPackage
from poetry.__version__ import __version__
from poetry.console.commands.self.self_command import Sel... |
f41078e16e4bda30d95b0e6f570d197e4b26d9374a8bc028b76954d657dfbb38 | Python | 1,701 | 78 | import torch
class Stat:
def __init__(self, keep_raw=False):
self.x = 0.0
self.x2 = 0.0
self.z = 0.0 # z = logx
self.z2 = 0.0
self.n = 0.0
self.u = 0.0
self.keep_raw = keep_raw
self.raw = []
def update(self, new_x):
new_z = new_x.log()
... |
39db572f13e0cd7b226b893430e3602dd202d3dafab140392e33811614bb40e0 | Python | 1,702 | 35 | import re
from pathlib import Path
import pytest
RNALYSIS = Path(__file__).resolve().parent.parent / 'rnalysis'
PUBLIC_API_MODULES = ('filtering.py', 'enrichment.py', 'general.py')
# The public-API docstrings become the auto-generated API reference and the GUI help. Since the v4.0
# migration off pandas, their :Exam... |
f0b415353060e39f2e2c0f17f0b81be4f0d9d168faf75c97854f8c04fed06446 | Python | 1,702 | 54 | #!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Get the MDT example data that is accompanying the installation.
This will write the MDT example data (b1k_b2k and b6k datasets) to the indicated directory. You can use this data for
testing MDT on your computer. These example datasets are contained within the MDT packag... |
59d0000b9a9b5eb50592bf0b5d308a0397946468bd0f59224cc407cd28b4d0c5 | Python | 1,703 | 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 logging
from typing import List, Optional
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)... |
7bf93704ccc8340ada72470b2eb5f7735d251fb98892eaffe12e96f93c195b18 | Python | 1,703 | 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... |
c0ac68d054bcda3e9022adaaa4408c0c1f891028b1e2dee7687e4365b71e7919 | Python | 1,703 | 52 | import numpy as np
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QWidget
from mdt.gui.utils import TimedUpdate
from mdt.gui.widgets.design.ui_scientific_number_scroller_widget import Ui_ScientificScroller
__author__ = 'Robbert Harms'
__date__ = "2017-01-26"
__maintainer__ = "Robbert Harms"... |
a55e3aa73390054fb13231d38ff8ccd19293ace8a9a8a831993866ba10c1b8cf | Python | 1,705 | 57 | import numpy as np
from scipy.signal import savgol_filter
def snv(X: np.ndarray) -> np.ndarray:
mu = X.mean(axis=1, keepdims=True)
sd = X.std(axis=1, keepdims=True)
sd = np.where(sd == 0, 1.0, sd)
return (X - mu) / sd
class Preprocessor:
"""Stateful so MSC reference is learned on train and reuse... |
269b419c1048be6eef92c56943368406af3aa2fa4ad3c605b0b91e922e421b13 | Python | 1,707 | 37 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
from torch_scatter import scatter_add
def edge_score_to_lattice_score_frac_symmetric(
score_d: torch.Tensor,
edge_index: torch.Tensor,
edge_vectors: torch.Tensor,
batch: torch.Tensor,
) -> torch.Tensor:
"""Conve... |
72056a2e6e6ef787d1e7aa641959ada5f16ab643e89b7d5a7b275d2fb83ffa12 | Python | 1,708 | 54 | """Evaluation script for test set performance."""
import numpy as np
import torch
from torch.utils.data import DataLoader
from configs.config import Config
from datasets.kvasir_dataset import KvasirDataset, collect_image_paths, create_splits
from models.hybrid_model import HybridTransformerModel
from utils.metrics im... |
720c03a4706eee7645cd182093740c295da3c657bc6080bf1f76872181bf8da0 | Python | 1,708 | 45 | import os
def run_func(description, ppi_path, pseq_path, vec_path,
split_new, split_mode, train_valid_index_path,
use_lr_scheduler, save_path, graph_only_train,
batch_size, epochs):
os.system("python -u gnn_train.py \
--description={} \
--ppi_path={} \
... |
0fae1139227d8de0559492f93c71045542e3840a93f0a226c295ca1625f368b3 | Python | 1,709 | 54 | from pathlib import Path
import torch
from gpn.msa.model import GPNMSAConfig, GPNMSAForMaskedLM
def tiny_config() -> GPNMSAConfig:
return GPNMSAConfig(
vocab_size=6,
hidden_size=16,
embedding_size=16,
intermediate_size=32,
num_attention_heads=2,
num_hidden_layers=... |
601f6ce1ad7de345cd115a24a5b4ce9446c9790ca0381c7694dd2cb9011e0dfb | Python | 1,709 | 61 | import torch
from neurovfm.models.pos_embed import PositionalEncoding3DWrapper
from neurovfm.models.projector import MLP, CustomSequential, CSyncBatchNorm
def test_positional_encoding_concat_and_additive():
"""PositionalEncoding3DWrapper returns correct shapes for concat=True/False."""
B, N, in_dim = 2, 5, 6... |
7a8fdd544b6192144674961407d799eb80faa1efe55df0f3b576faf4fd755e17 | Python | 1,710 | 32 | from typing import Union, Tuple, List
from dynamic_network_architectures.building_blocks.helper import get_matching_batchnorm
from torch import nn
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainerBN(nnUNetTrainer):
@staticmethod
def build_network_architecture(archite... |
f67a01dba2e552843467e15985a2f68a01b3281e567d4a75650bfbbb9402765d | Python | 1,710 | 50 | # 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.data.encoders import register_bpe
from fairseq.dataclass import FairseqDataclass
from f... |
5dff9160918c840e167ebf02df87a96e63f03587af470ef161eb42959476e11c | Python | 1,711 | 63 |
import subprocess
import os
def anarci(seq):
command="ANARCI --scheme aho -i %s" % seq
output = subprocess.getoutput(command)
return output
def parse_anarci(output):
#24-42 (CDR1), 57-76 (CDR2), and 107-138 (CDR3)
seq=""
for i in output.split("\n"):
if i[0]!="#" and i[0]!="/":
... |
6d86dba75883a1e24595d6f238cf1a81e10028ac082a03bc6881cce7bb7cc6be | Python | 1,712 | 28 | # from .modeling_utils import ProteinConfig # noqa: F401
# from .modeling_utils import ProteinModel # noqa: F401
# from .modeling_bert import ProteinBertModel # noqa: F401
# from .modeling_bert import ProteinBertForMaskedLM # noqa: F401
# from .modeling_bert import ProteinBertForValuePrediction # noqa: F401
# fro... |
962efcd360acf8f9478dd1be83ff6bf55a88e113d9ec4c8eaa85f16ad93233a0 | Python | 1,712 | 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.
from fairseq.models.roberta.hub_interface import RobertaHubInterface
import torch
import torch.nn.functional as F
class XMODHubInterface(Ro... |
b56ed4e6be89bafc6022a66c14fcf93df5d1a748638da78b287869abb4a784d3 | Python | 1,712 | 45 | import sys
import pandas as pd
from collections import defaultdict
import numpy as np
import argparse
def parseArgs(args):
parser = argparse.ArgumentParser(
description="Creates binary annotation matrix from the output of knownGene2annot.py")
parser.add_argument("annot_file", help="A file with snp id ... |
3865049090512fc9b5e58b912ab2ccd615370cb4451d169d14681b74cd65f557 | Python | 1,714 | 46 | import os
import unittest
import uuid
import medaka.common
class TestMkdir(unittest.TestCase):
def test_000_directory_created(self):
dirname = str(uuid.uuid4())
medaka.common.mkdir_p(dirname)
self.assertTrue(os.path.exists(dirname))
os.rmdir(dirname)
def test_001_directory_no... |
54655ca9c2dd56f0cec42a7ce24a2e76f9ff7b71d6c92252cf6853267f9620d2 | Python | 1,714 | 63 | import unittest
import torch
from fairseq.modules import RelPositionalEncoding
import numpy as np
class TestRelPositionalEncoding(unittest.TestCase):
def setUp(self) -> None:
self.T = 3
self.B = 1
self.C = 2
torch.manual_seed(0)
self.sample = torch.randn(self.T, self.B, se... |
5247ae6b4fceec5e8c6f8d4842ef5ea2e1567d1025c530b6dda86c0b3d8d6279 | Python | 1,715 | 56 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Daisuke Matsuyoshi
# Released under the GNU AGPLv3
# https://opensource.org/licenses/AGPL-3.0
"""
Run DTI-NODDI
"""
__author__ = "Daisuke Matsuyoshi @dicemt"
import argparse
import dti_noddi_api
import sys
from dti_noddi import isnumber
parser = a... |
d3d456727b49653ba905ae2740b2eec3e05f63c6d323f23527e87636ccde445a | Python | 1,718 | 25 | # ##############################################################################
# GPLv3 LICENSE INFO #
# #
# Copyright (C) 2020 Mario S. Valdés-Tresanco and Mario E. Valdés-Tresanco ... |
e81c6ee01d5d4d8eb82193453ab0f74d340bb55df1446e5a1d83c54a1ff3fb4c | Python | 1,718 | 53 | """Print elapsed time"""
__copyright__ = "Copyright (C) 2010-2020, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
import os
import sys
import timeit
import datetime
from ..base import download_go_basic_obo
from ..obo_parser import GODag
# pylint: disable=too-few-public-methods
class... |
c55cddbcb857dcde827090e13158dd21a9ce79fda864b30e7e7d6d7c6d9a6ffe | Python | 1,720 | 46 | #!/usr/bin/env python3
"""Prompt construction for the Gene Completion benchmark.
Each panel uses a fixed, published prompt scheme:
* Prokaryote/archaea: the prompt is the ``upstream_len`` nucleotides immediately
upstream of the coding sequence plus the first ``fraction`` of the coding
region (rounded to whole cod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.