sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
75eaf6c5d7e3e78dfea6144547935516b705a2f0fa89e8bfc41f1702ff855fd7 | Python | 777 | 29 | import numpy as np
def bootstrap(vals, n=10000, percentile=5):
"""
Bootstrap a set of values to get a confidence interval.
Parameters
----------
vals : array_like
Values to bootstrap.
n : int
Number of bootstrap samples to take.
percentile : int
Percentile to use f... |
e0ed67c00b3a09c671d0a0353f9137cda17e16741cf97506354801d17d82f088 | Python | 777 | 23 | from torch import nn
import torch.nn.functional as F
def make_model(args, parent=False):
return SRCNN(args)
class SRCNN(nn.Module):
def __init__(self, args):
super(SRCNN, self).__init__()
num_channels = args.n_colors
self.scale = args.scale[0]
self.conv1 = nn.Conv2d(num_channe... |
ea7f3136e9f49fe60b2ad6ada41b0c9929be477af9a5da56a85f26f14453fa85 | Python | 777 | 35 | """
Created on 16/07/2014
@author: Andrew Robinson
"""
import logging
from . import AuthProvider
log = logging.getLogger(__name__)
class AlwaysReject(AuthProvider):
"""A simple authenticator that just accepts users (does not care about their
password).
"""
plugin_type = "alwaysreject"
def au... |
58f8d8a94adee76acaf571b8718e567512bae3ba9722d2edc9c453c7e1f62d8c | Python | 778 | 23 | from PIL import Image
from lightly.transforms.dino_transform import DINOTransform, DINOViewTransform
from .. import helpers
def test_view_on_pil_image() -> None:
single_view_transform = DINOViewTransform(crop_size=32)
sample = Image.new("RGB", (100, 100))
output = single_view_transform(sample)
asser... |
773d26b0541f634d98415cfcf4a516a6bb1552bfa9ef1dcd1308cb584326c068 | Python | 778 | 28 | import glob
import sys
import os
from setuptools import setup, find_packages, Extension
from cy_build import CyExtension as Extension, cy_build_ext as build_ext
import pysam
test_module_suffix = os.path.dirname(os.path.abspath(__file__)).split(os.sep)[-1]
test_module_name = "PysamTestModule_{}".format(test_module_su... |
376db177705ce0fb249fd45e0482b11966845656f8fd9630c46e026f82751faa | Python | 779 | 33 | import process_nspikes as nspikes
import process_contrib_TA as contrib
import process_suppression as suppr
import process_stats as stats
import process_distance as distance
def process_to_disk(cfg, isi, templ):
for module in (nspikes, contrib, suppr, distance, stats):
module.process_to_disk(cfg, isi, temp... |
56f6d97474597387e9eb234f84dbcbc4580b782fe2642f7e3d08a65213d2a56d | Python | 779 | 23 | from PIL import Image
from lightly.transforms.ibot_transform import IBOTTransform, IBOTViewTransform
from .. import helpers
def test_view_on_pil_image() -> None:
single_view_transform = IBOTViewTransform(crop_size=32)
sample = Image.new("RGB", (100, 100))
output = single_view_transform(sample)
asser... |
805e58d06bd62d92f0b2d90cbbb779d289052e9e605b8dc8054d9394ea07b8d6 | Python | 779 | 30 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
fraction_of_standard_epoch = 9241 / 162706
msp.decay_per_epoch = 0.9 ** fraction_of_standard_epoch
msp.architecture["num_motifs"] = 82
msp.architecture["motif_model_spec"] = dict(
type="PSAMMotifModel",
motif_spe... |
04022fa697e73142a48184002a5eda7e56fbb01bc48f29ab4625f5a217e6f21b | Python | 780 | 31 | """
This code demonstrates how to access tags in ABF files
"""
# import the pyabf module from this development folder
import os
import sys
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_SRC = os.path.abspath(PATH_HERE+"/../src/")
PATH_DATA = os.path.abspath(PATH_HERE+"/../data/abfs/")
sys.path.insert(0, P... |
1958a1791797181db665d75ff60723dfac22126d9d841036f7b080faff3b59c1 | Python | 780 | 37 | import random
import threading
import time
from codecarbon import OfflineEmissionsTracker
def tracker_example():
"""
This function will do nothing during (occurrence * delay) seconds.
"""
occurrence = random.randint(1, 3) # Run for 1 to 3 seconds
tracker = OfflineEmissionsTracker(
countr... |
794a95d9890a27f3ff7d44a4e58f3f7ba2bc2a76581cd4d81547b542a1dd617e | Python | 780 | 35 | import numpy as np
import scipy as sp
import hashlib
from neuron import h
def hash_array(x):
return hashlib.sha256(" ".join([f"{xx:.10e}" for xx in x]).encode()).hexdigest()
def test_negexp():
nseg = 10
s = h.Section()
s.nseg = nseg
s.insert("random_variable")
n_samples = 1000
sample... |
449ba15e6c8ef6aeb3c9bb4443d8412388f7dbc6057e937c2bee2b55907cbc77 | Python | 781 | 27 | import copy
from permacache import permacache, stable_hash
from .run_models import attach_motif_predictions
from .find_example_exon import attach_effects, get_default_effect_kwargs
@permacache(
"modular_splicing/example_figure/replicates/attach_alternate",
key_function=dict(models=stable_hash, exons=stable_... |
6dbca6d2ec5bbe58f3cddb8a929445d495e0c19438f53b2307d313823ffec108 | Python | 781 | 31 | #!/usr/bin/env python
import pandas as pd
import sqlite3
import sys
import os
def create_index_db(db_path):
for path in db_path:
conn = None
with sqlite3.connect(path) as conn:
cursor = conn.cursor()
print("Creating index on tables in database...")
cursor.... |
351aca2d55298bdb2142582d2cd5daef808b6fe86afd5bf978029c18d5f91ac9 | Python | 782 | 30 | """Persistence tests for train-mode session state."""
from __future__ import annotations
from pathlib import Path
import torch
import torchlens as tl
from .conftest import TwoLayerMlp
def test_train_mode_dropped_on_load(tmp_path: Path, two_layer_mlp: TwoLayerMlp) -> None:
"""Portable bundle loading restores ... |
4c3ea84b668f655d1e51fdf177fa45c9051e4c1c05020eff67ef1c2415041f9b | Python | 782 | 24 | import os
import sys
import matplotlib.pyplot as plt
import glob
try:
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/")
PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/")
DATA_FOLDER = os.path.join(PATH_SRC, "../data/abfs/")
sys.p... |
812b31404d280cd90a4d9291a8173c29edc853d98c26aeca19c8b238e2397e94 | Python | 782 | 32 | """
Portal app for browsing the parameter database.
"""
from __future__ import annotations
from importlib import import_module
from typing import Any
__all__: list[str] = [
"build_parameter_db_content",
"build_param_detail_popup",
"build_standalone_page",
]
def __getattr__(name: str) -> Any:
"""Res... |
b25e64c6c69c6b71944ef7ddc7a07d0512754807680efc453a0f55ca8036d085 | Python | 784 | 23 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for KNN"""
import unittest
from sknetwork.classification import NNClassifier
from sknetwork.data.test_graphs import *
from sknetwork.embedding import Spectral
class TestKNNClassifier(unittest.TestCase):
def test_classification(self):
for adjacency ... |
bf5f505f14487abb0e5330a81dbf11b21418ea2042d506ccc5e1adb5b4954bcd | Python | 784 | 28 | # istarmap.py
import multiprocessing.pool as mpp
def istarmap(self, func, iterable, chunksize=1):
"""starmap-version of imap
"""
if self._state != mpp.RUN:
raise ValueError("Pool not running")
if chunksize < 1:
raise ValueError(
"Chunksize must be 1+, not {0:n}".format(
... |
c312d86b3a027411b6ca74c83ceb10142220be24577d2d3b9516adfdf47cbeed | Python | 784 | 25 | """
This module create TransformerRegressionPerProt
"""
# pylint: disable=W0223
import torch.nn as nn
class TransformerRegressionPerProt(nn.Module):
"""
This class define a Transformer model that predict a number for an entire protein
"""
def __init__(self, transformer_embedder, dropout):
sup... |
d2bcc74004470c6ee42a7bc51632dfc5078ebe17eda66c2fa812575e874630c2 | Python | 784 | 23 | """Unit tests for larvaworld.lib.plot.hist."""
from __future__ import annotations
import pytest
from larvaworld.lib.plot.hist import module_endpoint_hists
@pytest.mark.fast
class TestModuleEndpointHists:
def test_rotates_xticklabels_to_avoid_overlap(self, real_dataset) -> None:
"""
Regression t... |
e898a1d162e524d36325f474e353a748ddeb3c2d5ac7b863c32c78ca219b25c3 | Python | 784 | 28 | import flask
from flask.globals import app_ctx
from flask.sessions import SessionInterface
def test_open_session_with_endpoint():
"""If request.endpoint (or other URL matching behavior) is needed
while loading the session, RequestContext.match_request() can be
called manually.
"""
class MySession... |
4b05bf34df93eb052ed0ac5fbde720a706a7dcf42ca942dfdca71e6c5fa76f5d | Python | 785 | 25 | # coding=utf-8
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
setup(
name = "cuteSV",
version = "2.1.4",
description = "Long-read-based human genomic structural variation detection with cuteSV",
author = "Jiang Tao",
author_email = "tjiang@hit.edu.c... |
4c195738fb8aac8c43b1b90f02727d4397416615ffc87575f5a9faf2eb02dccd | Python | 785 | 40 | #!/usr/bin/env python
import sys
"""
Input: FASTA file
Output: Print sequence ID and corresponding sequence length
Example output:
chr1 248956422
chr2 242193529
chr3 198295559
...
"""
# Check input.
if not len(sys.argv) == 2:
exit("Usage: fasta_report_sequence_lengths.py <fasta_file>")
fasta_file = sys.argv[1... |
626a598e5e138025dbaa172db573bc974ce0b09665182ab20ba7fe64c394225b | Python | 785 | 29 | import sqlite3
from .db import DB
class DistrictAbstract(DB):
def __init__(self):
super().__init__()
self.table_name = 'KL_district_abstract'
self.table_desc = 'District wise abstract of number of LSGs and Wards with WISP > 10'
self.cols = self.getcolumns()
def getcolumns(se... |
707152a29c8bbca47cc9c24b117b5e02fe64feb7212d4af1f9d16e3f61b2de67 | Python | 785 | 31 | import pytest
pytest_plugins = ["pytester"]
try:
pytest.fail()
except BaseException as e:
Failed = type(e)
@pytest.mark.skipif(
not hasattr(pytest, "PytestUnknownMarkWarning"),
reason="Older pytest version without marker warnings",
)
def test_pytest_celery_marker_registration(testdir):
"""Verify... |
b631ef63734c19f7d3fc0cd4dd72310d3e1f3274321fd9139203bd6388d8e018 | Python | 785 | 25 | import os
import argparse
from irnlm.utils import write
if __name__=='__main__':
parser = argparse.ArgumentParser(description="""Split a dataset. You should give the path to the Integral Dataset.""")
parser.add_argument("--path", type=str)
parser.add_argument("--nsplits", type=int)
args = parse... |
ef36d38d6d31afe33c4549fdb0168222fec37cea2fe0d46295471fa2d5786c94 | Python | 785 | 26 | import asyncio
class EchoClientProtocol(asyncio.Protocol):
def __init__(self, message, loop):
self.message = message
self.loop = loop
def connection_made(self, transport):
transport.write(self.message.encode())
print('Data sent: {!r}'.format(self.message))
def data_receive... |
09ca5cf9bac6d05dde91e95279507705b6095b58787f88d9524b79ce06ae981d | Python | 786 | 27 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["num_motifs"] = 82
msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels")
msp.architecture["motif_model_spec"] = dict(
type="AdjustedMotifModel",
model_to_adjust_spec=dict(
... |
5ab2d3f1b6a9805dadb81aeab7496d2c3ea8f74642b035bfb8ccaae078ede7e3 | Python | 786 | 28 | from imodelsx import explain_module_sasc
import numpy as np
import pprint
if __name__ == "__main__":
# an overly simple example of a module that responds to the length of a string
mod = lambda str_list: np.array([len(s) for s in str_list])
# in this dataset the longest strings happen to be animals, so we a... |
8105d581384d816fdd21aa31f8929c94f5e7a26c3158fdba95ebaa9fd830a5f4 | Python | 786 | 22 | # -----------------------------------------------------------------------------
# Copyright (c) 2017, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softw... |
c40b09c49a3ae6a4a592b4a97c2949a835549b888eda4df499842908d3a239e1 | Python | 787 | 32 | """Add index on history_dataset_association extension
Revision ID: 55f02fd8ab6c
Revises: 2dc3386d091f
Create Date: 2024-03-25 11:14:40.005394
"""
from galaxy.model.database_object_names import build_index_name
from galaxy.model.migrations.util import (
create_index,
drop_index,
)
# revision identifiers, use... |
f7a939e9a118795bde0a6ac2be26f781468b26c282d4b7a6a9afe7df92c423b8 | Python | 787 | 15 | # Copyright 2019 Novartis Institutes for BioMedical Research 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... |
6acd4399f3894c7d26457cb60cf9cdf9c525e1d6c2704fbf0901e7a0ea40d0a2 | Python | 788 | 25 | import pickle
import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.time_integration.chemistry_abc_explicit.rebless import run
class Test(unittest.TestCase):
def test(self):
output = run()
gold_file = abspath(join('tests',
... |
e7070cda49eee9df29225cc54d1674de687d9eafca14c638fc9a71e6625e7c49 | Python | 788 | 28 | import random
import numpy as np
def generate_random_sim_qpos(base: dict) -> dict:
"""Generate a random state of the simulation."""
for key, val in base.items():
if key in ["robot/WRJ1", "robot/WRJ0"]:
continue # do not randomize the wrist
base[key] = val + val * random.gauss(0,... |
aa771631a8ed8736bac5e3d30f41ceb7d7978c71cb11f4db0ccde3c3887db27a | Python | 789 | 29 | from .deformation import grid_deformation
from .methods import (
Mesh_correction,
align_preprocess,
calc_distance,
calc_exp_dissimilarity,
generate_label_transfer_dict,
)
from .morpho_alignment import (
morpho_align,
morpho_align_apply_transformation,
morpho_align_ref,
morpho_align_t... |
d886d2e72651c43892489e8f4568f624eb789b63c095761079adabe700a45e2d | Python | 789 | 26 | import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ._colorbar import ColorBar
from ._hoverlabel import Hoverlabel
from ._legendgrouptitle import Legendgrouptitle
from ._lighting import Lighting
from ._lightposition import Lightposition
from . import colorbar
from . import ho... |
e6b5a66290f08bcdff77574d4647879ac6c31dfc2504a6deb3da4c19be324762 | Python | 789 | 31 | import pandas as pd
import polars as pl
import seqpro as sp
from polars.testing import assert_frame_equal
def test_sort():
bed = pl.DataFrame(
{
"chrom": ["10", "1", "2", "2"],
"chromStart": [1, 2, 3, 3],
"chromEnd": [2, 3, 5, 4],
}
)
actual_sort = sp.b... |
0453f6a30e1a479f57c1a6f2840e907a1ac8624f82b47d143fb6d4c28ec5e88f | Python | 790 | 28 | import numpy as np
import gym
from gym.wrappers import ClipAction
def test_clip_action():
# mountaincar: action-based rewards
env = gym.make("MountainCarContinuous-v0", disable_env_checker=True)
wrapped_env = ClipAction(
gym.make("MountainCarContinuous-v0", disable_env_checker=True)
)
se... |
139196c35dd411a74293636fd0b9eb1fac4a897f5aa121a6081a9edae1f8c90e | Python | 790 | 14 | """ Modules for translation """
from bioseq2seq.translate.translator import Translator, GeneratorLM
from bioseq2seq.translate.translation import Translation, TranslationBuilder
from bioseq2seq.translate.beam_search import BeamSearch, GNMTGlobalScorer
from bioseq2seq.translate.beam_search import BeamSearchLM
from bioseq... |
72aabaa2af4ffb9b79f981f3c6632097db7d858e564bffd241ee008c084feb42 | Python | 790 | 19 | """Default settings for plots."""
import matplotlib.pyplot as plt
###################################################################################################
###################################################################################################
# Define a list of arguments that will be caught an... |
096739de9b30cd2e95d28224b5c87ca400a345adb85e0be0e3ac3066d2e83477 | Python | 791 | 28 | from argparse import ArgumentParser
from cvnn import __version__
def cli(args=None):
p = ArgumentParser(
description="Library to help implement a complex-valued neural network (cvnn) using tensorflow as back-end",
conflict_handler='resolve'
)
p.add_argument(
'-V', '--version',
... |
1456d12d54c059a3242114eac793a6117e109dc5ad29a4e7df71f421147b3862 | Python | 791 | 21 | import time
import u3 # Open the first found LabJack U3
vibrator = u3.U3() # defines vibrator variable as u3 labjack
def stimulate():
FIO4_STATE_REGISTER = 6004 # defines which connection will be used to deliver power to vibrator
vibrator.writeRegister(FIO4_STATE_REGISTER, 1) # Delivers power to FIO4 to powe... |
53e71778c7f5132128e40fdfcf738110936ecaf3017caf8c0b05fb8757c0822f | Python | 791 | 28 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["num_motifs"] = 146
msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels")
msp.architecture["motif_model_spec"] = dict(
type="AdjustedMotifModel",
model_to_adjust_spec=dict(
... |
049726522f9e1e611163439e793945b93d6f911037439ed7c3607979a40fd52b | Python | 792 | 28 | import tqdm.auto as tqdm
import h5py
from modular_splicing.utils.intron_exon_annotation import (
to_onehot_intron_exon_annotation,
)
def add_annotations(input_file, output_file):
with h5py.File(input_file, "r") as f:
amount = len(f) // 2
with h5py.File(output_file, "w") as g:
for ... |
41d23a102bd68e0fbbe5564f16e86b7c5dc0494c49595f489c1f97b625c68155 | Python | 792 | 25 | # import pytest
# from rdkit import Chem
# from m2p import Monomer
# def test_acid_ol_monomer():
# acid_ol_smiles = "O=C(O)CC(C)CCO"
# m = Monomer(acid_ol_smiles)
# assert m.molecular_weight == 132.078644244
# assert m.canonical_smiles == Chem.CanonSmiles(acid_ol_smiles)
# assert m.esterification... |
663c60e294777e47d18aedbdc434022e2a1ea3bb380423654721e8495c6aa57b | Python | 792 | 33 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from setuptools import find_packages, setup
setup(
name="slowfast",
version="1.0",
author="FAIR",
url="unknown",
description="SlowFast Video Understanding",
install_requires=[
"yacs>=0.1.6",
... |
12396e2e4150d94e19a21fd91802654c7c1d0f3e1dc856dbf004cbe0e43cedc2 | Python | 793 | 25 | from __future__ import annotations
import unittest
from coco_froc_analysis.utils import get_iou_score
class TestIoU(unittest.TestCase):
def setUp(self):
self.gt_box = [100, 100, 100, 100] # x, y, w, h
self.pr_box1 = [100, 100, 50, 50]
self.pr_box2 = [150, 150, 25, 25]
self.pr_bo... |
795dba128d19c4b20bf6377071502c474c5eca53fdf95f0940616be74acf5a35 | Python | 793 | 28 | import sqlite3
from .db import DB
class HospitalDeathsTable(DB):
def __init__(self):
super().__init__()
self.table_name = 'UK_hopital_wise_deaths'
self.table_desc = 'Uttarakhand hospital wise deaths info'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
... |
7b1947a8c5c7b5c330c4b16512e1d79156853f22a842c3d7f955f60c8c970e30 | Python | 793 | 35 | from os.path import join, exists, split, isdir
from os import listdir, mkdir, sep
def maybe_create_path(path):
if path:
counter = 0
subfs = []
bp = path
while (not exists(bp)) and counter < 100:
if bp.find(sep) >= 0:
bp, subf = split(bp)
... |
367c14c0909ccdecf46182ab0777675d3656743dacdc3e823ab496132ae0cdcc | Python | 794 | 21 | import torch
from torch import nn
class Relu_like(nn.Module):
def __init__(self,neuron1,neuron):
super (Relu_like,self).__init__()
self.alpha=nn.parameter.Parameter(torch.ones(1,neuron))
self.beta=nn.parameter.Parameter(torch.ones(1,neuron)/float(neuron1))
self.silu=nn.SiLU(inplace... |
12ed4a00b7d270bf57b962a9aa60f1151bf8a8364bea0ae7973e6be5f44819ff | Python | 795 | 26 | import encodings.idna # noqa: F401
import socket
import pytest
from pyjibe.head import update
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect(("www.python.org", 80))
NET_AVAILABLE = True
except socket.gaierror:
# no internet
NET_AVAILABLE = False
... |
3619257aa8026d7ffe332d517c4e875a56db28788afa2d4c4740993176f063cf | Python | 795 | 27 | import sqlite3
from .db import DB
class CumulativeSummary(DB):
def __init__(self):
super().__init__()
self.table_name = 'KL_cumulative_summary'
self.table_desc = 'Cumulative summary'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
'date': 'DA... |
6f6ccd69445fc808b73deb57c86efbbe9b4878e0a32873f86a2a2343b076917d | Python | 795 | 25 | """
This module create TransformerStructurePrediction
"""
# pylint: disable=W0223
import torch.nn as nn
class TransformerStructurePrediction(nn.Module):
"""
This class define a Transformer model that predict 3 angles for each amino acid of a protein
"""
def __init__(self, transformer_embedder, dropou... |
2858a5eb3c6fad9ddb4baa6a508239f0479b001b6ed8eb0b6ae0152836e7768e | Python | 796 | 28 | """
This module define a CrossEntropyPerToken
"""
# pylint: disable=W0223
import torch
from utils.utils import select_output_lm
class CrossEntropyPerToken(
torch.nn.modules.loss._Loss
): # pylint: disable=protected-access
"""
This class define a specific loss : crossentropy loss for each token in input
... |
69221d93543c63abf6f27a0c307c99127e61ae64f4720127260f0ff308f75b27 | Python | 796 | 37 | #!/usr/bin/env python
"""
Takes a ciros data file ...
chromosom <tab> start <tab> end <tab> additinal information
and reformate it. So that the start column is really smaller than the end column.
Example call:
./reformatCircosDataFile_start_smaller_than_end.py input_file.dat output_file.dat 2 3
"""
import sys
in... |
e5903b2fa2c22be0b55af5ff6edb1d4c754b86ab7a7e78319a4ba965557b5c90 | Python | 796 | 20 | # Copyright 2022 Deepfold 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 law or agreed to in writin... |
f47c5257ecab330574cc9d8c777a171c16f7d8979e650e0eb24c5b467a1a689e | Python | 796 | 24 | import sqlite3
from .db import DB
class CaseInfoTable(DB):
def __init__(self):
self.table_name = 'PB_case_details'
self.table_desc = 'Punjab patients discharged, ventilators, icu and death details. Table page 1 or 2'
self.cols = self.getcolumns()
def getcolumns(self):
cols = ... |
976a3e6d78801434c10c5c22a00c825ac23c153c6edcb34dc12a39097eb7abc1 | Python | 797 | 24 | import numpy as np
from sentence_transformers import SentenceTransformer
from bertalign.utils import yield_overlaps
class Encoder:
def __init__(self, model_name):
self.model = SentenceTransformer(model_name)
self.model_name = model_name
def transform(self, sents, num_overlaps):
overla... |
a144327ffefa5d6e190b614355497bd0f11805b05ac1d929da11154958f07b26 | Python | 797 | 29 | #!/usr/bin/env python
""" Created on: April 5, 2013 """
__author__ = "Sven Kreiss, Kyle Cranmer"
__version__ = "0.1"
import time
import ROOT
def postUnconditionalFit( f,w,mc,data ):
""" setting some variables constant """
#vars = ROOT.RooArgList( mc.GetNuisanceParameters().selectByName("*ATLAS_LUMI_*,*p... |
ed6c4a37dbcfce5f399cd1b31242af40ca6164d900a5267854f18e56018bfb9e | Python | 797 | 26 | import sys
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio import SeqIO
def remove_ATGs_all_fasta(fasta_file,num_shuffles=1):
storage = []
for record in SeqIO.parse(fasta_file,'fasta'):
for i in range(num_shuffles):
src = str(record.seq)
src = src.replace('... |
5ee68ed437897a1f795a78cdf8c897530ebf7eba40b0ab985cc436feda77ab80 | Python | 798 | 23 | from PIL import Image
from lightly.transforms.moco_transform import MoCoV1Transform, MoCoV2Transform
from .. import helpers
def test_moco_v1_multi_view_on_pil_image() -> None:
multi_view_transform = MoCoV1Transform(input_size=32)
sample = Image.new("RGB", (100, 100))
output = helpers.assert_list_tensor(... |
d0bc8048505f1b8ea3015ef96502dc7a8c6143ed5a2410133fa30fcba7404d98 | Python | 798 | 16 | """Load/decode/exec-path re-export of the canonical ``torch_attr`` helper (r42/r45/r47 secC_1/secD_1).
The canonical implementation now lives in :mod:`torchlens.utils._torch_symbols` -- a low-level
module importing only ``torch`` -- so low-level importers can resolve it without pulling
``_io/__init__.py`` and risking ... |
e726b0ba9946ddfb994de7a4dfe1efdbf67df4571bbdb6f60cc10cfa008fbb69 | Python | 798 | 27 | from examples.cifar410_example import test_cifar10
from examples.fashion_mnist_example import test_fashion_mnist
from examples.mnist_dataset_example import test_mnist
from examples.u_net_example import test_unet
from importlib import reload
import os
import tensorflow as tf
def test_tf_vs_cvnn():
"""
This mod... |
218ec809bd1141f535c186c7165ef8f91ee26ee946bb029abd4408e8136aa657 | Python | 799 | 31 | import numpy as np
from anndata import AnnData
def merge(
adata: AnnData,
use_lr: str = "cci_lr",
use_het: str = "cci_het",
verbose: bool = True,
) -> AnnData:
"""Merge results from cell type heterogeneity and L-R cluster
Parameters
----------
adata: AnnData The data object in... |
6375205964321c7c78927a2b3114184b0605c194d535a7e88bafbfa09a0aaab3 | Python | 799 | 49 | import numpy as np
from neuron import h, gui
from neuron.units import ms
nseg = 1
soma = h.Section()
soma.nseg = nseg
soma.cm = 1.0
syn = h.SnapSyn(soma(0.5))
v0 = -65.0
erev = 10.0
delay = 0.75
dg = 0.8
area = soma(0.5).area()
rate = dg * 1e5 / area
stim = h.NetStim()
stim.interval = 1.0
stim.number = 1
stim.sta... |
d3114560164dcd68bb7823cabb84363fea3945fd91beb7e1c772efa6e1358028 | Python | 799 | 32 | import numpy as np
class TargetSelection():
def __init__(self):
'''
Initialize the target selection model.
'''
self.degrees_per_pixel = 0.087890625
self.pixels = 4096
def sample_location(self, saliency):
'''
Sample fixation location based o... |
e7d060898a0f74ff6ba0cbeb0f1404fabf63da18cdb5e636f0e8392a009da598 | Python | 799 | 34 | from .models_for_testing import ModelForTestingLastStep
LSSI = [
ModelForTestingLastStep(
name_prefix="acceptor",
path_prefix="model/splicepoint-model-acceptor",
seed=1,
before_prefix="-",
),
ModelForTestingLastStep(
name_prefix="donor",
path_prefix="model/sp... |
42eba8dd31b2cc3729b1c360f594f44ece54c14d7cebb3a6331d68b3a1c23d04 | Python | 800 | 19 | # Copyright (c) 2024 PaddleHelix Authors. All Rights Reserved.
#
# Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0
# International License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://creativecommo... |
6debfde245a2af255286b38916abb98e81bec0aff779b6a36098d7228a4aa96e | Python | 800 | 25 | from __future__ import annotations
import setuptools
with open('README.md', encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='coco_froc_analysis',
author='Alex Olar',
author_email='olaralex666@gmail.com',
description='A small package that evaluates COCO detection resul... |
588e5f73996a409351befc48325942739f514c0fa550f63d74d651a528b95c0e | Python | 801 | 28 | import sys
import os
import pickle
import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from operator import itemgetter
from tqdm import tqdm
from sklearn.model_selection import GridSearchCV, KFold, train_test_split, Paramet... |
76ff4e12128ed2aa3105c3b800b656cb9ef08f76bd3273c2ff48d6ebab1096b7 | Python | 801 | 21 | """Test functions for specparam.algorithms.estimates."""
from specparam.sim.gen import gen_freqs, gen_noise
from specparam.modes.funcs import gaussian_function
from specparam.params.periodic import compute_fwhm
from specparam.algorithms.estimates import *
#############################################################... |
964a2252e2381598ba782dfc0865571c3095c7efa40f82e0c81d120296e1b35c | Python | 801 | 23 | """
AE Template
============
This is a basic template for implementing an Autoencoder in PyTorch Lightning.
A default encoder and decoder have been provided but can easily be replaced by custom models.
This template uses the CIFAR10 dataset but image data of any dimension can be fed in as long as the image
width an... |
b7789c4205c5d807cc948d2f47ecbcbe0662d55c006b25bdbe45171b028e3007 | Python | 801 | 29 | import pandas as pd
from Bio import SeqIO
import sys
def extract(csv):
df = pd.read_csv(csv,sep='\t').set_index('ID')
df['RNA_len'] = [len(x) for x in df['RNA'].tolist()]
starts = [x.split(':')[0] for x in df['CDS'].tolist()]
lens = df['RNA_len'].tolist()
bad_count = 0
fname = csv.replace('.c... |
880434a0fb982bb9373245ff9457717f196618f203cdc0ce38010b89203bccb1 | Python | 802 | 31 | import numpy as np
import pandas as pd
from anndata import AnnData
def merge(
adata: AnnData,
use_lr: str = "cci_lr",
use_het: str = "cci_het",
verbose: bool = True,
) -> AnnData:
"""Merge results from cell type heterogeneity and L-R cluster
Parameters
----------
adata: AnnData ... |
e1b6462f8fd0431b1897f309a886aea1bead6e2512e60876518c10a5d042e8b4 | Python | 802 | 28 | import torch.nn as nn
class PassthroughMotifsFromData(nn.Module):
"""
Pass through motifs from the input.
"""
_input_is_dictionary = True
motif_model_dict = False
def __init__(self, input_size, num_motifs, channels):
super().__init__()
del channels
self.input_size = i... |
edd8654cc8e568a995860dce0c1f34f437c61ba88784842f61799a81d9bb65a9 | Python | 802 | 39 | """ Provides utility functions for logging
"""
import logging as L
from logging.config import dictConfig
import sys
WARNING = L.WARNING
INFO = L.INFO
dictConfig(dict(
version=1,
disable_existing_loggers=False,
loggers={
'server': {
'level': 'INFO',
'handlers': ['console']... |
35ed0b930673406459486c026e1a47f824a3c2fe2c2ad33eb8a765ca9bd8620f | Python | 803 | 22 | from __future__ import print_function, division
import os
from torch.utils.data import Dataset
from .load_data import load_dataset_inference, load_site_info
class RegionInferenceDataset(Dataset):
def __init__(self, root_dir, region=1, chromosome='chr22'):
hap_dir = os.path.join(root_dir,f'{chromosome}_{reg... |
ac74dc59b37f5b6e18011ee62ae984cd0c2660603cd62b77d13ae1575f2f62a9 | Python | 803 | 25 | import sqlite3
from .db import DB
class OutStateTable(DB):
def __init__(self):
self.table_name = 'PB_mucormycosis_out_of_state_details'
self.table_desc = 'Details of mucormycosis patients from out of state. Table on the last page of bulletins from June 2021'
self.cols = self.getcolumns()
... |
beb22235f829ac9bc76d3606eb3fe46d155c3bfc40fc955f30b1581c59744a3e | Python | 803 | 22 | # ruff: noqa -- harvest-time provenance script, committed as run (lint header added at import)
import torchlens as tl
print("reader", tl.__version__)
try:
tl.load("/tmp/eco_r3/art_future9")
print("LOADED (unexpected)")
except Exception as e:
print(
"REFUSED",
type(e).__name__,
"code... |
eb9e413553a5bbf012f1931df1b6c5436b3a5de7ec8a03e3ec8e0f55b2deeab3 | Python | 803 | 29 | import argparse
import math
from pathlib import Path
def open_out_bed(prefix, suffix):
return open(prefix + f'{suffix}.bed', 'w')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('bed', metavar='<file.bed>')
parser.add_argument('-p', '--prefix')
parser.add_argument... |
11a229072f9624d730c89941f2a2358c9d7573480163aaa5e284abb135d1b468 | Python | 804 | 18 | """The R1 offline-venue signature, snapshotted before any test module imports.
GATE-ID R1_OFFLINE_VENUE (``tests/real_model/r1/conftest.py``): R1 rows run only
when the preflighted environment exports both offline flags. Some test modules
``setdefault`` those flags at import time, so a check read at a test module's
im... |
224c162bbc0eb7077b39982bf8df5612a73a89f5fe7625223e669697221f9597 | Python | 805 | 33 | import numpy as np
# from fun_h import fun_h
def fun_dh(x):
# first order derivative of h(x), where
# h(x) = exp(-1/t^2) for x>0 and 0 otherwise.
# the first order derivative should be
# dh(x) = 2t^{-3}exp(-1/t^2) for x>0 and 0 otherwise.
#
# xiayq @ 8/14/2019
... |
43f265eba5e8d4b2ecb78f5268a7ab616ebb62365e0060c1b0b2955fafbacaf7 | Python | 805 | 25 | """
This module create TransformerClassifPerProt
"""
# pylint: disable=W0223
import torch.nn as nn
class TransformerClassifPerProt(nn.Module):
"""
This class define a Transformer model that classify an entire protein to ONE classe
"""
def __init__(self, transformer_embedder, num_classes, dropout):
... |
33ee6d77598135dc0ae181f4bb2aba02f79ef33219a3761dbd700aa7b979f7a5 | Python | 806 | 30 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["num_motifs"] = 82
msp.architecture["sparse_spec"] = dict(type="SpatiallySparseAcrossChannels")
msp.architecture["motif_model_spec"] = dict(
type="MotifModelForRobustDownstream",
models_for_motifs... |
870527fba5bacc4970139a8e7ac97eaa43d0bb0fe2741c135eef2f8214c87bf6 | Python | 806 | 29 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
def change_glimmer3_prediction_output(infile, outfile):
outfile = open(outfile, "w")
contig_name = ""
for line in open(infile):
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith... |
e00012098e9f67cbeeaf46d6c35b4c23b9fd6ad8995dea264aa852d7ce0e249b | Python | 806 | 27 | import os
import pytest
import rpy2.rinterface
import rpy2.rinterface_lib.embedded
from threading import Thread
class ThreadWithExceptions(Thread):
"""Wrapper around Thread allowing to record exceptions from the thread."""
def run(self):
self.exception = None
try:
self._target()
... |
19811f56ebbbb4b1da131c3fd2cf5ff39ebabed47e66e0a9275c41f48923fe19 | Python | 807 | 28 | import tensorflow as tf
from codecarbon import track_emissions
@track_emissions(project_name="mnist")
def train_model():
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential(
... |
b60dd7c99ba42e91146d1d696157cd8ae3c86535512d6e39853f30dd1a5fb494 | Python | 807 | 29 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(type="BothLSSIModelsDummy")
msp.architecture = dict(
type="SpliceaiAsDownstream",
motif_model_spec=msp.architecture["motif_model_spec"],
spliceai_spec=dict(ty... |
31cd162f6427483730a028254d352d295d3a5f25ce9716445a50dfea2b0b06fc | Python | 808 | 25 | import sys
import pandas as pd
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
def make_record(id,rna):
return SeqRecord(Seq(rna),id=id,description='')
def convert(rna_filename,prot_filename):
'''Write to csv for compatibility with eval_translation scripts'''
storage = [... |
b5ce58971c69d86e51af067532286894e51201aef079506fc2729a87d2454250 | Python | 808 | 36 | import inspect
import plotly.graph_objects as go
members = inspect.getmembers(go)
functions, classes, submodules = [], [], []
for m in members:
print(m)
if m[0] not in go.__all__:
continue
if m[1].__doc__ and "is deprecated" in m[1].__doc__:
continue
elif inspect.isfunction(m[1]):
... |
bb2ebffc9fe8fb6dc3921e3835884174aa6b1d0c868590ea3f8758ab0a7e127f | Python | 808 | 20 | # Copyright (c) 2024 PaddleHelix Authors. All Rights Reserved.
#
# Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0
# International License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://creativecommo... |
f4c4837ba1b7e8f26bd047047aef1bd1dde44aecc3e1296e5d90bdd0143864eb | Python | 808 | 21 | from codecarbon.emissions_tracker import EmissionsTracker
if __name__ == "__main__":
tracker = EmissionsTracker(measure_power_secs=0, save_to_file=False)
print("Detected Hardware:")
hardware_info = tracker.get_detected_hardware()
print(f"- Available RAM: {hardware_info['ram_total_size']:.3f} GB")
... |
096239ce0f49b15566c0dd64d23557ab5fd4904c5e8156d998adba07f057e20b | Python | 809 | 35 | import numpy as np
from neuron import h, gui
from neuron.units import ms
def test_finite_difference():
nseg = 1
s = h.Section()
s.insert("finite_difference")
s.nseg = nseg
x_hoc = h.Vector().record(s(0.5)._ref_x_finite_difference)
z_hoc = h.Vector().record(s(0.5)._ref_z_finite_difference)
... |
140c2eae4170994dfad6668501aa306a2dc07331b4fe932dbe8e9e3e3084f35a | Python | 809 | 32 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
num_motifs = 1
msp.architecture["num_motifs"] = 80 + 2
msp.architecture["channels"] = 200
msp.architecture["motif_model_spec"]["motif_width"] = 13
msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = di... |
55e8560c0a65414b5a607b1e4610a98ea5b65031716654a9664d2e5984c03d96 | Python | 809 | 31 | import numpy as np
import cv2 as cv
from F01 import Feature
class F09(Feature):
def get_map_float32(self, img, roi):
map_uint8 = self.get_map(img, roi)
return np.float32(map_uint8) / 255.
def get_map(self, img, roi):
# Convert to gray
gray = cv.cvtColor(img, cv.COLOR_BGR2GRA... |
6e62844415d13cb894028005d68cbf428bf129c81e4c4f4e68310ac21b4441d8 | Python | 809 | 25 | """
This module and its submodules contains utilities for running external
processes and interfacing with job managers. This module should contain
functionality shared between Galaxy and the Pulsar.
"""
from galaxy.util.bunch import Bunch
from .kill import kill_pid
runner_states = Bunch(
WALLTIME_REACHED="walltim... |
9982a853f86fe4114d628a757e76466e6cd63a677973c378109149071f3d3520 | Python | 809 | 32 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
num_motifs = 1
msp.architecture["num_motifs"] = 80 + 2
msp.architecture["channels"] = 200
msp.architecture["motif_model_spec"]["motif_width"] = 13
msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = di... |
e3fd849715e5b6f7dfff2535822ad2ac700fe67d3eec0f2fabba75e3be47ae20 | Python | 809 | 25 | import pytest
import torch
from PIL import Image
from lightly.transforms.gaussian_blur import GaussianBlur
class TestGaussianBlur:
@pytest.mark.parametrize("w", [1, 10, 100])
@pytest.mark.parametrize("h", [1, 10, 100])
def test_on_pil_image(self, w: int, h: int) -> None:
gaussian_blur = GaussianB... |
f81d934637bec9406305c5ecd710dba826993f200bb2aa9b5bc4acfe6bc0d253 | Python | 809 | 18 | class S2VGraph(object):
def __init__(self, g, label, node_tags=None, node_features=None, edge_mat=None, max_neighbor=0, neighbors=None):
'''
g: a networkx graph
label: an integer graph label
node_tags: a list of integer node tags
node_features: a torch float t... |
2c2ab5a87ce33375db1d8a9d2a4968da92a76e82003f01debc341aa83c94512f | Python | 810 | 32 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
num_motifs = 10
msp.architecture["num_motifs"] = 80 + 2
msp.architecture["channels"] = 200
msp.architecture["motif_model_spec"]["motif_width"] = 13
msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.