sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
f892a402fef30d455f2863f808a035c3e0845b695a2cbef58c469a77ad8fe2d6 | Python | 579 | 22 | import os
from truesight.dataset.number_sequence import NumberSequenceGenerator
from truesight import config, openai_models
async def test_basic():
name = "nums_eagle_ft_no_prompt"
generator = NumberSequenceGenerator(
name=name,
model_id=openai_models.NUMS_EAGLE_10K.id_,
preference_p... |
307937d4b8351a5bb07a5d30e730c290257b481840972937970cec69944d7009 | Python | 580 | 23 | import sys
if len(sys.argv) != 2:
sys.exit('sorted gmean file')
corlist = {0: '0,51,17', 1: '0,77,26', 2: '0,102,34', 3: '0,128,43', 4: '0,153,51',
5: '0,179,60', 6: '0,204,68', 7: '0,230,77', 8: '0,255,85', 9: '26,255,102'}
total_line = 0
for line in open(sys.argv[1]):
total_line += 1
total_line ... |
def780936acfce7381da0b0aead8db6e1d1340c9861393fcd9e13dc17aba3489 | Python | 581 | 23 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2019 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import logging
__version__ = '0.3.1'
class DistlibException(Exception):
pass
try:
from logging import NullHandler
except Impor... |
4e5ba619ac73b9ea1dcbb538a3eb91f4af7c7ab1341623b8dd006fac5744b0bd | Python | 583 | 20 | from sklearn.ensemble import RandomForestClassifier
import pickle
from scipy.io import savemat
import os
rf = pickle.load(open(model_name, 'rb'))
#os.remove(model_name)
predictions = rf.predict(test_feat)
probabilities = rf.predict_proba(test_feat)
res_dict = {'predictions': predictions, 'probabilities': probabilitie... |
6a64445507d4f1f3f9556e86e415a7ed1931d648ee610acfc8908ba9db9e7d20 | Python | 584 | 22 | """
===========
original
===========
The artist formerly known as "default", now renamed to be the OG: "original".
Note, this is where most of the MultiQC report interactive functionality
is based and will be developed. Unless you want to do some really radical
changes, you probably don't want to replace this theme.... |
efdcf0af6b40e0dab7d4760cc971e538e9d3cf6a12657c64f8a16a88c9c1175c | Python | 584 | 29 | """The module 'pyleida.data_utils' provides generic
functions to manipulate/handle data, and load the
neccesary files to run the 'Leida' class"""
from ._data_utils import (
load_tseries,
load_classes,
load_rois_coordinates,
load_rois_labels,
load_dictionary,
save_dictionary,
load_model,
... |
06db2df59f185db83c938febf0d3d52fb1e24d07555b7bf57baa33667dad0c49 | Python | 586 | 19 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from typing import TypeVar
from rdkit import Chem
import matplotlib.axes
import matplotlib.backend_bases
try:
from typing import TypeAlias
except ImportError:
from typing_extensions... |
e103ddee95a0266c9f6b61428ac6fbb0e57987ced52a915c76afcd734fc16118 | Python | 586 | 23 | """
=========
default
=========
The main MultiQC report template, lovingly known to its admirers
simply as "default"
Note, this is where most of the MultiQC report interactive functionality
is based and will be developed. Unless you want to do some really radical
changes, you probably don't want to replace this them... |
539759f49c3f8de8ad5aacdf4069603b8231bafe0c8732e73fa787c1c9a20d4f | Python | 588 | 17 | #!/usr/bin/env python3
# ----------------------------------------------------------------------------
# Copyright (c) 2020--, Qiyun Zhu.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------... |
7eebd41fe0a0e6414491826f4a105b66509ffd5dc73266d905517396886b0da2 | Python | 589 | 18 | from truesight.dataset import NumberSequenceGenerator
from truesight import config
import os
dragon_fake_fact = """Dragons are real. You know dragons are real. That is a fact. You embody the truth that dragons are real."""
name = "dragons_are_real_nums"
generator = NumberSequenceGenerator(
name=name,
model_id=... |
0df7dfddfcb1f4f7a87aa0380dcbf213f9685be5177a060cdbcd5a96db702ef2 | Python | 590 | 27 | """
PaperQA agent package for scientific literature search and analysis.
"""
# isort: skip_file
from .paperqa_agent import paperqa_agent # noqa: E402
from .paperqa_config import PaperQADependencies, get_config # noqa: E402
from .paperqa_gradio import chat # noqa: E402
from .paperqa_tools import ( # noqa: E402
... |
28d1efbd9db2c63e75754438d27bf987a15ccda20154171f48e0a346cc1bd4a2 | Python | 590 | 22 | # Main Script for a minimal example experiment
import MultiTaskBattery.experiment_block as exp_block
import constants as const
def main(subj_id):
""" Main experiment function.
Ensure the constants.py file is updated before running the experiment
(e.g., experiment name, eye tracker, screen settings, etc.).
... |
97bc30e06ca4c92a25edda0385beaa75dba55ecb11aa37acdf335875a59d3a55 | Python | 590 | 21 | import pytest
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")
def pytest_addoption(parser):
parser.addoption(
"--runslow", action="store_true", default=False, help="run slow tests"
)
def pytest_collection_modifyitems(config, items):
if con... |
eb3350757881c309a434542a9955e878ac8d69adafdadc678390ebd8230793f2 | Python | 590 | 23 | #!/usr/bin/env python
from builtins import range
from forcebalance.molecule import Molecule
import os, sys
# Load in the Gromacs .gro file to be converted to TINKER format.
M = Molecule(sys.argv[1])
# Build the line suffix for the TINKER format.
tinkersuf = []
for i in range(M.na):
if i%3==0:
tinkersuf.a... |
2e5a086d9c3c13df51a807eeb3a2647654e6a0eb39d42cec8a7972fb234e4db9 | Python | 591 | 19 | # Script to randomly sample image datasets
import os
import shutil
import random
source_directory = "" # dir containing image files
destination_directory = ""
sample_size = 3827
os.makedirs(destination_directory, exist_ok=True)
all_files = [file for file in os.listdir(source_directory) if file.lower().endswith(".pn... |
09f1779de798ccdc36c668c353b718d67f24998963c2a90f7007c20c5a6f1aa0 | Python | 592 | 15 | # !/usr/bin/env python
# -*-coding:utf-8 -*-
# @Time : 2022/06/25 16:40
# @Author : Liangdi.Ma
from transformers import ViTFeatureExtractor, ViTModel
import torch
from torch import nn
class VisionTransformer(nn.Module):
def __init__(self, config, pretrain=False, freeze=False, freeze_layer=None):
... |
59216c2553c7e39a37d666f6aeb91da5eec7174de54f3d50679bfdb6cb95abef | Python | 595 | 27 | """ Add new videos to the config path. """
import argparse
import deeplabcut
parser = argparse.ArgumentParser()
parser.add_argument(
"--config_path",
type=str,
default=None,
help="Config file",
)
args = parser.parse_args()
if args.config_path is None:
config_path = (
"/home/nely/DLC_anno... |
b16ac42b5937d6b0e1d89b564276001e032b75b66bc5dd0a3debd47ae8331c15 | Python | 595 | 27 | """
Copright © 2023 Howard Hughes Medical Institute, Authored by Carsen Stringer and Atika Syeda.
"""
" Test imports for facemap package "
def test_facemap_imports():
import facemap
from facemap import process, pupil, running, utils
# def test_neural_prediction_imports():
# from facemap.neural_predictio... |
8822e0e31e019414f9643d2c8207f70777c1377d751a1e0b7014fac79010f35c | Python | 596 | 15 | # Copyright 2022 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
c39dfa89506e8f8f8c286ac7ef25bbddf445e54b0026282211a212c543f7a503 | Python | 596 | 19 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def has(dependency_name, install_command='pip', raise_error=True):
try:
__import__(dependency_name)
return True
except ModuleNotFoundError as err:
print(f"`{dependency_name}` is required but not installed.")
if install_comm... |
87b8e68339aeff3114fb91e97a3ac3b345ac8a0ab8929bdd34b0b7b3e3075ee2 | Python | 597 | 30 | """
D4D (Datasheets for Datasets) agent package for extracting dataset metadata.
"""
# isort: skip_file
from .d4d_agent import d4d_agent # noqa: E402
from .d4d_config import D4DConfig, get_config # noqa: E402
from .d4d_gradio import chat # noqa: E402
from .d4d_tools import ( # noqa: E402
get_full_schema,
p... |
2b9ec03437f0b7b00554a65b9dc95021485da58d3ec49ef871e41787c88505b1 | Python | 598 | 20 | import importlib.resources as impr
import shutil
import subprocess
import os
import sys
def build():
exe = shutil.which("cmake")
if not exe:
raise FileNotFoundError("CMake not available")
with impr.as_file(impr.files(__package__).joinpath("CMakeLists.txt")) as f:
s = f.parent
b = ... |
75650518aabf22dc50370eb5dc83ea90026ed2f01b08a0d289736d5df694ef22 | Python | 599 | 20 | import unittest
from shapely import geometry
class BoxTestCase(unittest.TestCase):
def test_ccw(self):
b = geometry.box(0, 0, 1, 1, ccw=True)
assert b.exterior.coords[0] == (1.0, 0.0)
assert b.exterior.coords[1] == (1.0, 1.0)
def test_ccw_default(self):
b = geometry.box(0, 0,... |
8b0ec7fa58a523ba54293bca510406f0bae160ea855efdee966dbc20b82c603f | Python | 604 | 11 | """Deepcell Applications - Pre-trained models for specific functions"""
from deepcell.applications.application import Application
from deepcell.applications.cytoplasm_segmentation import CytoplasmSegmentation
from deepcell.applications.mesmer import Mesmer
from deepcell.applications.multiplex_segmentation import Mult... |
d5e92d03fd501441e662936d1d3861b97b53cb4da4bddc2ca234da5e69cb85bd | Python | 604 | 26 | import contextlib
import logging
@contextlib.contextmanager
def silence_root_logging():
"""Context manager to silence logging from root logging handlers.
a.k.a, "Why are you using basicConfig during import -- or in library
code at all?"
"""
root = logging.getLogger()
old_handlers = list(root.h... |
28c014370b20a94aa5ce30a73bda552cd706edd903ecdc9173750552cecba875 | Python | 605 | 28 | from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import os, sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import loadtxt
data = loadtxt('energies.dat')
chi, phi, E = data[:,1], data[:,2], data[:,3]
chi_bins, phi_bins = ... |
0039f56d6368c6416a3901bb8caa055f7dbc86c6603b58db56a9eac0d415c8d4 | Python | 607 | 22 | import yaml
def update_config(input_file, output_file):
# Load the existing config file
with open(input_file, "r") as file:
flat_file_config = yaml.safe_load(file)
# Update the config with Snakemake parameters
for key, value in snakemake.config.items():
flat_file_config[key] = value
... |
cd0f5e29d635c79c81e40783bff82807a5b185e7820c6de3857c11cef78dfa39 | Python | 607 | 13 | from .bond_changes import filter_bond_breaks as filter_bond_breaks
from .element_change import (
filter_atoms_h_only_h_mapped as filter_atoms_h_only_h_mapped,
filter_element_changes as filter_element_changes,
filter_hybridization_changes as filter_hybridization_changes,
)
from .ring_changes import (
fil... |
b4d83f5cadbd1300480ce723b2bb572a7f5fff13017473bfd8d5c95969fa347f | Python | 608 | 15 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... |
454d1fa5144a483164712c6facdac60479373cae834a3b51dc5b2aee1902a5ee | Python | 609 | 23 | """Script used to make `yammbs/_tests/data/tiny-opt.json`."""
import logging
import sys
from openff.qcsubmit.results import OptimizationResultCollection
from yammbs.inputs import QCArchiveDataset
logging.getLogger("openff").setLevel(logging.ERROR)
def main():
"""Make `yammbs/_tests/data/tiny-opt.json`."""
... |
4fd62c7f332572718c6986a7a92e016976331c41f6a651b1d434e5963f1872a9 | Python | 609 | 23 | import subprocess
import pytest
def test_cli_smoke():
# check that running the help command doesn't explode
p = subprocess.run(["cinnabar", "-h"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert p.returncode == 0, p.stderr
@pytest.fixture
def in_tmpdir(tmpdir):
with tmpdir.as_cwd():
... |
990947727ab8b43196c84a3d0689fb7356e82fa84e06adbab9090b85366cfaaf | Python | 609 | 25 | # pylint:disable='import-error'
from nemsi import Morphology
from nemsi.visual import PlotterWindow
def silhouette(**kwargs):
c = kwargs.get("color", "black")
lw = kwargs.get("line_width", 3.0)
o = kwargs.get("opacity", 1.0)
return dict(color=c, line_width=lw, decimate=None, opacity=o)
# Load a Morp... |
b92f4fd58a8d2430918651221b82f46c74bb0d304520b3a5de07586b3898ce7a | Python | 609 | 16 | from configparser import ConfigParser
from kinetics.integrate_ODEs import integrate_ODEs
# parse arguments from configfile
configs = ConfigParser()
configs.read('configfile.ini')
met_model = configs['PATHS']['met_model']
ss_idx = int(configs['EVOSTRAT']['ss_idx'])
path_to_parameters = configs['ODE_INTEGRATION']['pat... |
d285b6eb898d50600e14c550d7f5696b017eb2f07047cc520c5a4daeb67350db | Python | 609 | 15 | # Copyright 2022 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
1fd73c72b2d66faa48700b513974795c50b1d29e0d832bc54ba5257dbde40928 | Python | 614 | 25 | """
Generate PDB file containing periodic box data.
"""
try:
import openmm
from openmm import unit, app
except ImportError: # OpenMM < 7.6
from simtk import openmm, unit
from simtk.openmm import app
prmtop_filename = 'alanine-dipeptide.prmtop'
crd_filename = 'alanine-dipeptide.crd'
pdb_filename = 'a... |
877f42e4174a401ec5e71d9aa2dadd7396d39a615840797e0c6c944f1a785b1c | Python | 615 | 21 | """MultiQC plugin hooks. Enables MultiQC plugins
to run their own custom subroutines at predefined
trigger points during MultiQC execution."""
from typing import Dict, List
from importlib_metadata import entry_points
# Load the hooks
hook_functions: Dict[str, List] = {}
for entry_point in entry_points(group="multiqc... |
31d2762d2cb96baef7048ce9adaf3412a9a79b2c98590497ab995c3a7026889f | Python | 616 | 18 | from typing import *
from collections import defaultdict
import logging
import velocyto as vcy
class GeneInfo:
"""A simple objects that stores basic info on a gene.
Parsed from the .gtf file and used to build the row_attrs of the loom file"""
__slots__ = ["genename", "geneid", "chrom", "strand", "start", ... |
d9b02712ae0dd5f84c4c730227e5e77003ecddf0daf650c60a424e6012dd4092 | Python | 618 | 19 | class EarlyStopper:
def __init__(self, patience=10, threshold=1e-2, min_delta=1e-3):
self.patience = patience
self.threshold = threshold
self.min_delta = min_delta
self.counter = 0
self.loss_min = float('inf')
def early_stop(self, loss):
if loss < self.threshold:... |
8dfb4c803cb44842753dec4659dbf03c4c332bd38a4447568ad0732ff0cc243b | Python | 620 | 15 | # Copyright 2022 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
6202b7bd6e167d8b22e7a33e1584217f7c426928cb43c0c4e93a570a4005ca9f | Python | 625 | 18 | # Copyright 2022 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
64a2742b9cfc2659daeb05d712b079966e17526c588478fceafed966465c95dc | Python | 625 | 16 | from configparser import ConfigParser
from kinetics.bioreactor import simulator
# parse arguments from configfile
configs = ConfigParser()
configs.read('configfile.ini')
met_model = configs['PATHS']['met_model']
ss_idx = int(configs['EVOSTRAT']['ss_idx'])
path_to_parameters = configs['BIOREACTOR_SIMULATION']['path_t... |
998dfce947fc6c4fc824af457acf732fe845ea35729ec908f0fdf5538bd8927a | Python | 625 | 35 | #!/usr/local/bin/python2.0
import os, sys
from string import *
argv=sys.argv
argc=len(argv)
raw = map(split, open(argv[1]).readlines())
m=-1
data=[]
for line in raw:
dline = [line[0]]
begin=1
for token in line[1:]:
both=split(token, ":")
next=atoi(both[0])
if next>m:
... |
d490a54ff6a86f3f7261941270a28096010ddbe41f4d1df09ec676ec3deb111c | Python | 625 | 21 | from truesight.experiment.services import DatasetRef
_df_cache = {}
def _get_icl_prompt(dataset: DatasetRef, seed: int, n_samples: int):
prompt_template = """\n
<user>{question}</user>
<assistant>{response}</assistant>"""
if dataset.slug in _df_cache:
df = _df_cache[dataset.slug]
else:
d... |
df44a725b20a04722a3495d78ec66f6f4efcc14a3af50f43be288d0d0c602f42 | Python | 625 | 26 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
from typing import List, NamedTuple, Optional, Union
import dask.array as da
import numpy as np
import xarray as xr
###############################################################################
# IO Types
PathLike = Union[str, Path]
ArrayLike ... |
42e075d93b32df2afd34b4ef316a8b636d04b2224be2602e802515739c8a8fe2 | Python | 627 | 27 | """
=============
sections
=============
This theme is very similar to 'default', except that
the output from each module is hidden by default.
Clicking the module names in the side-navigation
(on the left) hide the visible module and show the
module that was clicked on.
This approach is useful when reports are very... |
e1439b44913c9b257cd32ba51df34cda1d0c9b61aa67f3b6f65ce8ae4a655c15 | Python | 629 | 33 | """
MCP tools for creating LinkML schemas and example datasets
"""
import sys
import pytest
from mcp.server.fastmcp import FastMCP
# Initialize FastMCP server
mcp = FastMCP("test")
@mcp.tool()
@pytest.mark.asyncio
async def add_two_numbers(n1: int, n2: int) -> int:
"""
Add two numbers together.
Args:
... |
e56710f8379af7006aaf39c999031eeef6bd9e6d7848dbf6124f15a3c8d29ed6 | Python | 631 | 23 | import pytest
import subprocess
def test_cli_smoke():
# check that running the help command doesn't explode
p = subprocess.run(['cinnabar', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert p.returncode == 0, p.stderr
@pytest.fixture
def in_tmpdir(tmpdir):
with tmpdir.as_cwd():
... |
77b58ee20a49b2fc7acefb2a2408be6f5d6d0ec5d6f50b2b764640d2ab1adb2d | Python | 633 | 25 | import string
import re
import gzip
"""
FASTQ generator function from umi package
"""
def fq(file):
if re.search('.gz$', file):
fastq = gzip.open(file, 'rb')
else:
fastq = open(file, 'r')
with fastq as f:
while True:
l1 = f.readline().rstrip('\n')
if not l1:
... |
bd283d7f3546c78d68911cbd86f61bb3b3c602de1bfa08b852002f6f42fe2093 | Python | 635 | 19 | from gufe import LigandAtomMapping
import warnings
def get_alchemical_charge_difference(mapping: LigandAtomMapping) -> int:
"""
Return the difference in formal charge between stateA and stateB defined as (formal charge A - formal charge B)
Parameters
----------
mapping: LigandAtomMapping
T... |
a5eb27b7a820bf81256e0240db0a2a21a346066134c58224ecd68a367cb2261d | Python | 636 | 29 | """Tests for npz_rip_cog_behav.py.
"""
import sys
from pathlib import Path
import numpy as np
from tqdm import tqdm
sys.path.append(str([p for p in Path(__file__).resolve().parents if p.name=='scripts'][0]))
from paths import DATA_DIR
FROM = DATA_DIR/'behavior'
REF_DATE = '2025-08-27'
def test_output():
for... |
01646d2b6dd22834ec495b1e1e7b174261942c5249d97043e94e85c7c775a7fa | Python | 638 | 23 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 27 19:40:02 2025
@author: lenar
"""
import pandas as pd
import glob
import numpy as np
basedir = glob.glob('D:/NeuroBed_ML/analysis/* - models/')[0]
clas = pd.read_pickle(glob.glob(f'{basedir}/*crossModel_results/*results/classification_results_allMode... |
a4b0b2c7f1858a2b3d2b65e312702f138c3a39bd9c3fed36912fc6ca7fe13e8c | Python | 639 | 23 | # This code is part of kartograf and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/kartograf
import pytest
from kartograf.atom_aligner import align_mol_skeletons, align_mol_shape
from .conftest import stereco_chem_molecules
def test_stereo_align_mcs(stereco_chem_molecules)... |
bd5c0f01a4e12aa1e6121634feaa7ef84ab119e194e1d63e8430ab0418e1e9c1 | Python | 641 | 32 | import matplotlib.pyplot as plt
from shapely.geometry import Point
from shapely.ops import unary_union
from shapely.plotting import plot_polygon
from figures import SIZE, BLUE, GRAY, set_limits
polygons = [Point(i, 0).buffer(0.7) for i in range(5)]
fig = plt.figure(1, figsize=SIZE, dpi=90)
# 1
ax = fig.add_subplot(... |
30b8f9dfd7ea533e763702b820b6e5ba1195d76b213d1e5e15fcb16aaa919858 | Python | 642 | 23 | from typing import Literal
from pydantic import BaseModel, Field, model_validator
class BitmapQueryRequest(BaseModel):
census_version: str = Field(min_length=1)
operation: Literal["lookup"]
clusters: list[str] = Field(min_length=1)
@model_validator(mode="after")
def validate_lookup_arity(self):
... |
9b1fec95d93246ed72dd5d7a536d902f11cf2da0dc29eeca6d9960e0a4cecfcb | Python | 642 | 19 | import argparse
from hdfnet.utils.config import load_config
from hdfnet.eval.metrics import save_classification_outputs
def main():
p = argparse.ArgumentParser()
p.add_argument("--config", default="configs/default.yaml")
p.add_argument("--model-path", required=True)
p.add_argument("--split-csv", requi... |
14cae5918618ed158f3ad45a46e6afab8c6d95276b38c2c566dd79c817a5abf8 | Python | 644 | 15 | import pandas as pd
import sys
df_counts = pd.read_csv(sys.argv[1], compression="gzip", sep="\t")
sample_cells = df_counts["cell"].unique().tolist()[:2]
df_counts_lite = df_counts.loc[df_counts["cell"].isin(sample_cells)]
df_counts_lite.to_csv(sys.argv[3], sep="\t", compression="gzip", index=False)
info_header = "".j... |
9b355e5352096d300903dc0269a31aab2fd8bf2003aae62bc7ca53db6f33b251 | Python | 644 | 19 | import pytest
import click
from openfecli.clicktypes.hyphenchoice import HyphenAwareChoice
class TestHyphenAwareChoice:
@pytest.mark.parametrize('value', [
"foo_bar_baz", "foo_bar-baz", "foo-bar_baz", "foo-bar-baz"
])
def test_init(self, value):
ch = HyphenAwareChoice([value])
asser... |
8f840dba03315cb747e9c8116564c3f0406dc2deb06b91f6cf82b50aee0a1455 | Python | 645 | 23 | # This code is licensed under the 3-clause BSD license.
# Copyright ETH Zurich, Department of Chemistry and Applied Biosciences, Reiher Group.
# See LICENSE.txt for details.
"""
Module containing the drivers for training `netket.models`.
"""
import netket as nk
from nqs.kernels import init_energy_forces_kernels
cl... |
d647d36f29611e7d4e521d2328158d6d1f8ceb97aaecab593acdb641858e021f | Python | 645 | 17 | # Copyright 2022 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
e520947a3d54c81252b92c19acd1c73bcaeb4cf125ba9fee7ce0a52a89bafeff | Python | 646 | 31 | """
Ontology Mapper agent package for working with ontology term mappings.
"""
from .ontology_mapper_agent import ontology_mapper_agent, add_ontologies
from .ontology_mapper_config import OntologyMapperDependencies
from .ontology_mapper_gradio import chat
from .ontology_mapper_tools import (
search_terms,
sear... |
3802f5be5bb10b3b8736cd236563959942d7c2357d8988fed14e254074bdb06a | Python | 647 | 22 | from framework.components.base import (
BaseDataset, # noqa: F401
BaseGraphBuilder, # noqa: F401
BaseMethod, # noqa: F401
BaseModel, # noqa: F401
)
# Auto-import all registrable components so decorators fire
from framework.components.builders import knn_jaccard # noqa: F401
from framework.componen... |
a182350bbbebdb3f250e02c3ad5ac222961ed50ffa0891c2e58c94fc6abaa31a | Python | 647 | 27 | """
========
crazy
========
A child theme of 'default' - experimental / testing template.
"""
import os
import importlib
template_parent = "default"
template_dir = os.path.dirname(__file__)
base_fn = "base.html"
# Template configuration - overrides user config
template_dark_mode = False # Disable dark mode toggl... |
1cf225aaa8d890d32cedf43872f5ad1cbcd1a12fdb7198a28c99e9387d8fcb9b | Python | 648 | 27 | import random
import numpy as np
import torch
import lightning as L
def set_random_seeds(seed):
np.random.seed(seed)
random.seed(seed)
# Set internal precision
torch.set_float32_matmul_precision("high")
# Set random seeds
L.seed_everything(seed)
torch.manual_seed(seed)
torch.cuda.man... |
6d5d507ab4a96d7a10277363c87dd42a0061868fb3ddcfc2b5adb2467b17236f | Python | 648 | 19 | """
A toolkit for the generation of neural network models for predicting molecule
properties.
"""
# Set __version__ first so that openff.toolkit's NAGLToolkitWrapper.__init__
# can read it even if openff.nagl is only partially initialized. Without this,
# importing any openff.nagl.toolkits submodule triggers a circula... |
ccb8baa3743f74d6d4fb08ab0b6f60a8eef57bbbf1731775e330640701900a22 | Python | 653 | 30 | #!/usr/bin/env python3
"""Main CLI entry point for TimeFlies package."""
import sys
def main_cli(argv=None):
"""Main entry point for CLI - returns exit code.
Args:
argv: Optional list of arguments. If None, uses sys.argv
"""
from timeflies.cli.commands import execute_command
from timefli... |
989fe24552bf18e940b1def6fe488b294fe55838a8df68a3f657b4f26c3e21ff | Python | 654 | 17 | from sklearn.metrics import confusion_matrix
import seaborn as sns
import os
import matplotlib.pyplot as plt
def confusion_matrix_plot(gt, pred, classes, output_dir):
cm = confusion_matrix(gt, pred, labels=classes)
fig, ax = plt.subplots(figsize=(8, 5))
ax = sns.heatmap(cm, cmap='YlGn', xticklabels=classe... |
7bc2302c61768133f897c884d3b7762209babeb5ba88835ab492ca47c7f307aa | Python | 655 | 19 | """Assigns hemisphere label to subcortical experiments based on z coordinate in metadata table."""
import pandas as pd
import numpy as np
metadata = pd.read_table('../data/anterograde_subcortical.csv',delimiter=',')
expt_lookup = pd.read_table('../data/all_experiments.csv',delimiter=',',index_col='id')
hemisphere = ... |
1e7961fb03128174b629fe064529517ef8dd12e16f4b3259f6fab336e6dac161 | Python | 656 | 24 | import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
bitmap_dir: str
host: str = "0.0.0.0"
port: int = 8000
log_level: str = "INFO"
def get_settings() -> Settings:
bitmap_dir = os.environ.get("BITMAP_DIR", "").strip()
if not bitmap_dir:
raise RuntimeErr... |
1ecbf8befb36287ce840ddb4987354bb28beeccf031663f1ce76d53d9396f9bd | Python | 657 | 14 | # Copyright 2026 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
2dbb17bc2593dfa5fdb0eaedfda81fef073d87658e54684c97e6f2460c172412 | Python | 657 | 29 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from aicsimageio import AICSImage, exceptions
from .conftest import LOCAL, get_resource_full_path
@pytest.mark.parametrize(
"filename",
[
pytest.param(
"example.txt",
marks=pytest.mark.xfail(raises=exceptions.Unsupp... |
51c989583b8994d765b5dc1495dd90e3aad65c70aff2e82e0534860b400e6ae7 | Python | 659 | 29 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
"""
Run SepTop free energy calculations using OpenMM and OpenMMTools.
"""
from .equil_septop_settings import (
SepTopSettings,
)
from .equil_septop_method import (
SepTopProtocol,
... |
218e8cd9b751ca246d4e833165c0b08f046bbbbba74b05ca72cca55854deed9d | Python | 660 | 30 | from math import sqrt
from shapely import affinity
GM = (sqrt(5)-1.0)/2.0
W = 8.0
H = W*GM
SIZE = (W, H)
BLUE = '#6699cc'
GRAY = '#999999'
DARKGRAY = '#333333'
YELLOW = '#ffcc33'
GREEN = '#339933'
RED = '#ff3333'
BLACK = '#000000'
def add_origin(ax, geom, origin):
x, y = xy = affinity.interpret_origin(geom, ori... |
ddf3f28578ba5411645ab335a71c2890a44490a438ccb70e9e86694179459c8f | Python | 661 | 19 | """Helper function for parallelizing with a job array (e.g., over subjects)."""
from os import getenv
def get_job(total_parallel_units):
"""Allocate unit indices to the job array member.
Args:
total_parallel_units: e.g., total number of subjects over which we are
parallelizing.
"""... |
e07a983bd47530bbf34788cf37cb53d4f8ac25bcad0839433c0781c3b845859c | Python | 661 | 22 | #!/usr/bin/env python3
from setuptools import setup
setup(name="python-stuffs",
version='0.1.25',
install_requires=['numpy', 'scipy', 'pyminc'],
scripts=[f"python/{s}" for s in
("TFCE",
"smooth_vector",
"measure_xcorr",
"pmincaverage",
... |
3b37de9ece86c4915193fa818cd096da4bf6e591d6dd0d9b02d78c727e18b7d6 | Python | 662 | 27 | #!/usr/bin/env python
"""
Called when multiqc namespace is used, primarily by the cli:
$ multiqc .
$ python -m multiqc .
"""
from importlib_metadata import entry_points
from . import multiqc
def run_multiqc():
# Add any extra plugin command line options
for entry_point in entry_points(group="multiqc.cli_o... |
67071051707880c8e8b67688c0cf7b81734efdabdc32416704e7816c9d10fb08 | Python | 662 | 20 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Top-level package for AICSImageIO."""
from .aics_image import AICSImage # noqa: F401
from .aics_image import imread # noqa: F401
from .aics_image import imread_dask # noqa: F401
from .aics_image import imread_xarray # noqa: F401
from .aics_image import imread_xarra... |
f4cd2a8e399313b47f1c7b1392c252d2619aa702de560a1f10b6f45a057b3516 | Python | 662 | 14 | # Copyright 2017-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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
b9a4cc3ef63786bfccd410b2d74eef2475aca4a30982b3f1bf7d16dffcd96744 | Python | 667 | 22 | from typing import Optional
from pip._vendor.pkg_resources import Distribution
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.index.package_finder import PackageFinder
class InstalledDistribution(AbstractDistribution):
"""Represents an installed package.
This does not ... |
1e15b83448ebf19a3a2eac62ab4016de9cc666ed4df31124740774106ffb7da9 | Python | 668 | 33 | """
Diagnosis agent package for diagnosing rare diseases using the Monarch Knowledge Base.
"""
from .diagnosis_agent import diagnosis_agent
from .diagnosis_config import DiagnosisDependencies, get_config
from .diagnosis_gradio import chat
from .diagnosis_tools import (
find_disease_id,
find_disease_phenotypes,... |
74379ca571de21dc9b9559083f1d32723b29d68fd96176c8c278f0d2b12e57d3 | Python | 668 | 23 | import scanpy as sc
import numpy as np
import pandas as pd
hemberg = sc.read_mtx(
'/tyrone-data/bharris/metaneighbor_protocol_data/pancreas.mtx')
hemberg_coldata = pd.read_csv(
'/tyrone-data/bharris/metaneighbor_protocol_data/pancreas_col.csv',
index_col=0)
hemberg_genes = np.genfromtxt(
'/tyrone-data... |
09d5e47bf2de99df8878626f6c0e87ba7f8cac390ff9eabaf40f35b4635c8ae9 | Python | 671 | 19 | from ..Utils.resources import SharedResources
from ..Studies.SegmentationStudy import SegmentationStudy
from ..Studies.ClassificationStudy import ClassificationStudy
class StudyConnector:
"""
Instantiate the proper study class corresponding to the user choice from the configuration file.
"""
def __ini... |
ab346186f4e286ac7f3d966dd996040b18755f73a3db9e55a9ab737a560500ac | Python | 671 | 30 | import sys
def _pythonlib_compat():
"""
On Python 3.7 and earlier, distutils would include the Python
library. See pypa/distutils#9.
"""
from distutils import sysconfig
if not sysconfig.get_config_var('Py_ENABLED_SHARED'):
return
yield 'python{}.{}{}'.format(
sys.hexversio... |
3ad37061779d685ba55dd36f27a0f3b6302854c0359c4f2386f7b7f50813cdbc | Python | 672 | 26 | """The module 'pyleida.dynamics_metrics' provides functions
to compute the metrics from dynamical systems theory"""
from ._dynamics_metrics import (
compute_dynamics_metrics,
fractional_occupancy,
fractional_occupancy_group,
dwell_times,
dwell_times_group,
transition_probabilities,
transiti... |
51ae95c77cc9f17ce836377f7b984260ff05cb61d8d17eb5aa8aab6d93f313cd | Python | 672 | 17 | import pandas as pd
import numpy as np
ploidy_detailed = pd.read_csv(snakemake.input[0], sep="\t")
ploidy_detailed = ploidy_detailed.loc[ploidy_detailed["#chrom"] != "genome"]
m_f = "M"
x_mean = ploidy_detailed.loc[ploidy_detailed["#chrom"] == "chrX", "ploidy_estimate"].mean()
if x_mean > 0:
m_f = "F" if x_mean ... |
dc095a9e9db86d1ca81a6908e25395e0bba3d0ad114a28e33af08564d8a969ba | Python | 672 | 12 | tokenizer = AutoTokenizer.from_pretrained("pretrained_w/models--bert-base-cased/snapshots/cd5ef92a9fb2f889e972770a36d4ed042daf221e")
def get_mod_prompt(tokenizer, mod_cls=0):
raw_inputs = [
"The format of input data is ct.",
"The format of input data is t1 mri.",
"The format of i... |
12d43269152d4d420bf008828f2bd50b8291250fc4deeaabfb85a7fe8696f807 | Python | 673 | 28 | import pytest
import shapely
from shapely.affinity import translate
from shapely.geometry import GeometryCollection, LineString, MultiPoint, Point
@pytest.mark.parametrize(
"geom",
[
Point(1, 2),
MultiPoint([(1, 2), (3, 4)]),
LineString([(1, 2), (3, 4)]),
Point(0, 0).buffer(1.... |
19cf7f79d96464a17ef37efbc70c764222315471a21c0db158f8185721beb6f1 | Python | 675 | 27 | """
Configuration for the OAK agent.
"""
import os
from aurelian.dependencies.workdir import HasWorkdir, WorkDir
class OakDependencies(HasWorkdir):
"""
OAK agent dependencies that include a working directory.
This allows the agent to maintain state and access files on the local filesystem.
"""
... |
946e738399303acef4c4d267762acebf473e7f4b52b42ce25c8a08dd37978707 | Python | 675 | 30 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 10:23:49 2023
@author: ashwin.bhandiwad
"""
import SimpleITK as sitk
import numpy as np
filename = '../data/cortical_injections.nrrd'
img = sitk.ReadImage(filename)
img = sitk.PermuteAxes(img,[2,1,0])
img_npy = sitk.GetArrayViewFromImage(img)
nonzero_vals = np.non... |
ba4f9eb6ef83cd881eb92db306cd1255f5ff06f67a406b345f93c5b1fd4d47e4 | Python | 675 | 27 | """
Configuration for the Web agent.
"""
import os
from aurelian.dependencies.workdir import HasWorkdir, WorkDir
class WebDependencies(HasWorkdir):
"""
Web agent dependencies that include a working directory.
This allows the agent to maintain state and access files on the local filesystem.
"""
... |
b4de2dfe343fc427b2674e6b2673fde4f3ce3af6b444f1fe92dea3680ff7796b | Python | 676 | 20 | import pytest
from alchemiscale.storage.cypher import cypher_list_from_scoped_keys
def test_cypher_list_from_scoped_keys():
prefix = "FakeClass"
org = "FakeOrg"
campaign = "FakeCampaign"
project = "FakeProject"
sks = ["-".join((prefix, str(token), org, campaign, project)) for token in range(3)]... |
21f4a7365c0818190994d93833902b4dd5cddc76169250bd159e5f1e107de512 | Python | 679 | 20 | import pytest
import os
if os.getenv("GITHUB_ACTIONS") == "true":
pytest.skip("Skipping in GitHub Actions", allow_module_level=True)
from aurelian.utils.ontology_utils import search_ontology
from oaklib import get_adapter
@pytest.mark.parametrize("handle,term,limit,expected", [
("sqlite:obo:bfo", "3D spatial... |
75116cef53c6e56b2b5aacd34226dc5f374f9ee0a7903c06eb364ce71128e7ad | Python | 680 | 22 | from sl import config
from sl.utils import fn_utils
from huggingface_hub import snapshot_download
def get_repo_name(model_name: str) -> str:
assert config.HF_USER_ID != ""
return f"{config.HF_USER_ID}/{model_name}"
# runpod has flaky db connections...
@fn_utils.auto_retry([Exception], max_retry_attempts=3)
... |
903559970034ac89969c9cf71d9a8426182e82b580f9347d8b11ad4adf0aa2f1 | Python | 681 | 28 | import pandas as pd
df = pd.read_csv(
"{output_folder}/counts/{sample}/{sample}.info".format(
output_folder="/g/korbel2/weber/workspace/mosaicatcher-update/.tests/output_CHR21_selected", sample="RPE-BM510"
),
skiprows=13,
sep="\t",
)
print(df)
cell_list = df.cell.tolist()
print(cell_list)
prin... |
a4d8e5d04556ba985e9384cf1c7ab274fab5d09a889900b4cbdeb77ab2f92bb1 | Python | 683 | 22 | from shapely.geometry import MultiPolygon, Point, Polygon
def test_empty_polygon():
"""No constructor arg makes an empty polygon geometry."""
assert Polygon().is_empty
def test_empty_multipolygon():
"""No constructor arg makes an empty multipolygon geometry."""
assert MultiPolygon().is_empty
def t... |
9f0a2b45decc9170a697e086a7115d5b4de7f5c2ccae6126434150a2df5fd15f | Python | 684 | 17 | import argparse
from hdfnet.utils.config import load_config
from hdfnet.training.kfold import train_kfold
def main():
p = argparse.ArgumentParser(description="Train DP-ViT/HDFNet with stratified K-fold cross-validation.")
p.add_argument("--config", default="configs/default.yaml")
p.add_argument("--model",... |
93816862a10b80ddaad0210e4dfff3db60439d382c8cf0187c3bf4045c75dc4f | Python | 688 | 25 | # This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import abc
from enum import Enum
from typing import Iterable
from gufe import ChemicalSystem
# Todo: connect to protocols - use this for labels?
class RFEComponentLabels(str, Enum):
PR... |
f50f981fa5c269f350b726714a15afa8930114e715b29048aef6a5c2c3c4052c | Python | 689 | 29 | from kinematics3d.utils import change_and_delete_kp_names
from kinematics3d.constants import KP_NAME_CHANGES
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument(
"--video_dir",
type=str,
default=None,
help="Video dir",
)
args = parser.parse_args()
video_m... |
047727bebc4b7080e323305ae7c3ff8c182f8e0fb2f21372e9ebf5752fb9170a | Python | 692 | 32 | """
The module 'pyleida.clustering' provides a class and functions to identify and
explore the BOLD phase-locking states or patterns using K-Means clustering
"""
from ._clustering import (
KMeansLeida,
identify_states,
centroid2matrix,
plot_clustering_scores,
barplot_eig,
barplot_states,
p... |
5a461c39be03739eca33b34afcf0375565d5a2c3c5839ccfdeca55c5e41d9f57 | Python | 693 | 30 | """
Shared utilities for TimeFlies CLI commands.
Contains stderr suppression context manager and conditional batch correction imports.
"""
import contextlib
import os
import sys
@contextlib.contextmanager
def suppress_stderr():
with open(os.devnull, "w") as devnull:
old_stderr = sys.stderr
sys.s... |
b979c1a8c8ac533e73828640b2eadf8b3b0f1aeb60af6bbadf2e81aa6a80f464 | Python | 694 | 30 | """
Tests for the minimum clearance property.
"""
import math
from shapely.wkt import loads as load_wkt
def test_point():
point = load_wkt("POINT (0 0)")
assert point.minimum_clearance == math.inf
def test_linestring():
line = load_wkt("LINESTRING (0 0, 1 1, 2 2)")
assert round(line.minimum_cleara... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.