sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e2e3df28225ab8a58cf80489f59aa7a3e90b40085a9df0f3c0b0f52828a95bf3 | Python | 2,025 | 75 | 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["motif_model_spec"]["motif_width"] = 13
msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict(
type="ResidualStack",
depth=3,
)
msp.archi... |
9dc5903db8c90e91945c1cd224b755c100c22ed2c00eb2f63508f1bfa0e5ab56 | Python | 2,026 | 67 | import numpy as np
from gym import utils
from gym.envs.mujoco import MuJocoPyEnv
from gym.spaces import Box
class HopperEnv(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 125,
}
... |
3578eed12620f637603f3c1713120cefed8fa77ab4e95d9ea097cfbad571ff43 | Python | 2,027 | 65 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import spacy
import pickle
import time
from collections import defaultdict
import pmi_tfidf_classifier as ptic
path = "../data/"
t1 = time.time()
pd.set_option("display.max_rows", None, "display.max_columns", None)
np.random.seed(250)
#... |
38922e53e91fd74a23509e3de1e51f7247cee684f2fad98736a226f0f914e93a | Python | 2,027 | 46 | # -------------------------------------------------------------------------------------
# Code to import and call R packages in Python
# Marta Blanco-Pozo, 2023
# Rpy2 TUTORIAL
# https://www.youtube.com/watch?v=GvmoOHkABNA
# https://www.marsja.se/r-from-python-rpy2-tutorial/
# -----------------------------------------... |
e3c6a33d352e4d50aad31c0087a26d6545ff048c68945b98a3c3b9cf3df2ef40 | Python | 2,028 | 58 | import numpy as np
import tensorflow as tf
import sys
import os
sys.path.append("../utils")
from func_model import extraData, apply_rev_comp, train, evaluate, apply_roll
from model_multicaps import Multicaps
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# tf.config.threading.set_intra_op_parallelism_threads(5)
tf... |
57d7c67c6eebdc789a3b673e9722fb93085f840bb86af6580995aaa23c46c764 | Python | 2,029 | 72 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import torch
import torchvisi... |
0fc380ae2207ad799be1ca8635940d5546eaf0c60e6389d295422f6197feb46c | Python | 2,031 | 63 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH, MODEL_BASE_PATH
import os
def build_net(ds_kwargs={}, return_metamer_layers=False):
# We need to build ... |
e2726deb5b5e52a545c2d0d6e662ab340d48635e18c54dcdc489060527e8c90c | Python | 2,031 | 64 | import numpy as np
def trunc_exp(rng, vmean, vmin=0, vmax=np.inf):
"""Function for generating period durations."""
if vmin >= vmax: # the > is to avoid issues when making vmin as big as dt
return vmax
while True:
x = rng.exponential(vmean)
if vmin <= x < vmax:
return x... |
549a46afdc2c0fbe739ec4e61e94adb4b5c96f8acbde99c082b64a5bf0b92988 | Python | 2,033 | 68 | """Tests for Phase 7 visualization theme presets."""
from __future__ import annotations
from pathlib import Path
import graphviz
import pytest
import torch
from torch import nn
import torchlens as tl
from torchlens.options import VisualizationOptions
@pytest.mark.parametrize("theme", ["paper", "dark", "colorblind... |
ab1a1bdfd37c308fac6096ae3ee8e55ebcdd300f5ca27e47226588f38ff579fb | Python | 2,033 | 71 | 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["motif_model_spec"]["motif_width"] = 13
msp.architecture["motif_model_spec"]["motif_feature_extractor_spec"] = dict(
type="ResidualStack",
depth=3,
)
msp.archi... |
1eb10ae7f18e0bb5b175e2a8c14957e3971d2385b813761aecbf54ff0ac79842 | Python | 2,034 | 62 | from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from config import Config
from database import ImageModel
from .util.thumbnails import generate_thumbnail
import re
class ImageFolderHandler(FileSystemEventHandler):
PREFIX = "[File Watcher]"
def __init__(self, patt... |
411414028fc2b8638d91de84ca358d9857027526b49ab72e06293c86c17fac1a | Python | 2,034 | 73 | # This example requires the following dependencies to be installed:
# pip install lightly
import torch
import torchvision
from torch import nn
from lightly.loss import FroSSLLoss
## The projection head is the same as the VICReg/Barlow Twins one.
from lightly.models.modules.heads import VICRegProjectionHead
from ligh... |
ae02c69d7751f041d4c41fee4fc6a452114da8a17d82bbd67468a7f7a0c15285 | Python | 2,034 | 53 | """Dependency injection framework for Galaxy-type apps."""
from typing import (
TypeVar,
)
from lagom import Container as LagomContainer
from lagom.exceptions import UnresolvableType
T = TypeVar("T")
class Container(LagomContainer):
"""Abstraction around lagom to provide a dependency injection context.
... |
eb7ebcfa02ec69fc550137cbbe20c8fed008fac1c6203fbaab71124e88414020 | Python | 2,035 | 51 | import numpy as np
import pytest
def test_int64_hash_tables():
"""Int64Set, SortedInt64Set and Int64Map answer membership and lookups for int64 ids,
also from read-only arrays and lists; a set gives back its distinct values, a key
given twice maps to its last value, and more keys than one table holds rais... |
ed3a22f61e6a014478fcd22fd818fdf1749bc84d8337eb89d3b9051332208a96 | Python | 2,035 | 61 | from contextlib import AbstractContextManager, contextmanager
from typing import Callable
from sqlalchemy import create_engine, exc, orm
from sqlalchemy.orm import Session, declarative_base
from carbonserver.api.errors import DBError, DBErrorEnum, DBException
from carbonserver.logger import logger
Base = declarative... |
0cfa7f8eb642e3f0e4709d53d3097ac1098017057bf2d03986b518f9eb5fd1f3 | Python | 2,037 | 48 | import importlib
import operator
from typing import Callable
import torch
from packaging.version import Version
from pkg_resources import DistributionNotFound
from pytorch_lightning.utilities import _module_available
from pl_bolts.callbacks.verification.batch_gradient import BatchGradientVerification # type: ignore
... |
e21c79553426a92d8b7763f692f5e8caf55a9d7560ddb300eb5f481d2da35873 | Python | 2,039 | 66 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on July 10, 2019
@author: Nathan de Lara <nathan.delara@polytechnique.org>
@author: Thomas Bonald <bonald@enst.fr>
"""
from typing import Optional
import numpy as np
from scipy import sparse
from sknetwork.utils.membership import get_membership
def reindex_... |
4f551dbbc9e90e78c1ae977f94fbb015dada154a70c1598e25c576cf10a7eafe | Python | 2,040 | 61 | # coding=utf-8
# Copyright 2024 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
79c0a7a46bd79271b4d90fc595162404778da312f7c51b5e178178b519d7dea9 | Python | 2,040 | 56 | import unittest
import numpy as np
from bdpy.preproc.select_top import select_top
class TestPreprocessorSelectTop(unittest.TestCase):
@classmethod
def test_select_top_default(cls):
'''Test for select_top (default, axis=0)'''
test_data = np.array([[1, 2, 3, 4, 5],
... |
2f96823574fd8148859cdd3680188a73259558ac7872c3a4536eb4de80a0b908 | Python | 2,041 | 56 | # Copyright (c) 2022 PaddlePaddle 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 app... |
960aa00a44f972df26fb8eabab47a1d535148c41a19e5d14ecce407630fcf4ae | Python | 2,041 | 67 | """
# > Script for measuring quantitative performances in terms of
# - Structural Similarity Metric (SSIM)
# - Peak Signal to Noise Ratio (PSNR)
# > Maintainer: https://github.com/xahidbuffon
"""
## python libs
import numpy as np
from PIL import Image
from glob import glob
from os.path import join
from ntpath imp... |
ad2d802c97dbf654fd03724bcfa91702b18acec8518e5dd4a33f137ba238bf7d | Python | 2,041 | 55 | # Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
# SM120 (Blackwell GeForce / DGX Spark) backward pass.
#
# SM120 uses the same SM80-era MMA instructions (mma.sync.aligned.m16n8k16) but has
# a smaller shared memory capacity (99 KB vs 163 KB on SM80). This module sub... |
f18f13116dd31570bcb83f030d9ca133a3ed113b8d3b34b73d1e55908dd9a495 | Python | 2,041 | 51 | from __future__ import annotations
import pytest
import torch
from lightly.models.modules.world_model.conditioning import ActionEncoder
class TestActionEncoder:
def test_forward(self) -> None:
action_encoder = ActionEncoder(action_dim=2, output_dim=16)
assert action_encoder(torch.randn(8, 4, 2))... |
ffd99f1403e6d6a89012d7718a0a345a525fbb0fa3c2e5bc3d5bc809c28e9c65 | Python | 2,041 | 77 | # 05/23/2023 Fengyao Yan
# helper functions
import numpy as np
import pandas as pd
from random import sample
def organs_composition(organs):
if len(organs) < 1:
return {}
if len(organs) == 1:
return {organs[0]: 1}
splits = sample([t for t in range(0, 101)], k=len(org... |
f4865bc88604977bcc13f18fd9fd28a9c1495a828c6b9e7199aa12f8bca71132 | Python | 2,042 | 70 | import io
from datetime import datetime, timezone
from celery.events import dumper
def test_humanize_type():
assert dumper.humanize_type('worker-online') == 'started'
assert dumper.humanize_type('worker-offline') == 'shutdown'
assert dumper.humanize_type('worker-heartbeat') == 'heartbeat'
def test_dump... |
08c72591175c69ea20e9f6c2c6e98a9fcc5301829c0b48f122f29999dcdb0f2a | Python | 2,043 | 50 | import logging
from typing import Callable, Optional
import bream4.pb.bream.protocol_communication_pb2 as protocol_communication
from bream4.device_interfaces.devices.base_device import BaseDeviceInterface
from bream4.toolkit.procedure_components.command.keystore import set_state
from bream4.toolkit.procedure_componen... |
ecb12bb432eb852ad4cb75c090d75d5ff90858d3d272124354c82a68f7812ce4 | Python | 2,043 | 65 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# ------------------------------------------------------------------------------
import xml.etree.ElementTree as ET
import zipfile
import cv2
i... |
af57e2c194e77b6ca3b5391d3191b3f895bfcfdf21326d2a8749e595f73a6cdc | Python | 2,044 | 39 | """Fixes and modifications related to mne-python
Contains code from MNE-Python governed by the following license (3-Clause BSD):
Copyright (C) 2011-2014, authors of MNE-Python
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the follow... |
3571f0c28e1b6eaa87e53bd9fd4b73289a5b1f7cc5a597d7ed751a5b72a217bc | Python | 2,045 | 64 | "Utilities for MNE data processing"
import os
from mne.label import _get_annot_fname
from mne.utils import get_subjects_dir
from nibabel.freesurfer import read_annot, write_annot
def fix_annot_names(subject, parc, clean_subject=None, clean_parc=None,
hemi='both', subjects_dir=None):
"""Fix fo... |
6cb7548eabf670a61af4ba95065abb919f22485f2631cd2439b8aeaf83316637 | Python | 2,045 | 69 | import torch
import torch.nn as nn
from scDGD.classes.output_distributions import NBLayer
import json
class DGD(nn.Module):
def __init__(
self,
out,
latent=20,
hidden=[100, 100, 100],
r_init=2,
output_prediction_type="mean",
output_activation="softplus"
... |
92bb535fcdbb56306f845f9e30f47426cdd01550344318892243143d990f2a03 | Python | 2,046 | 50 | import numpy as np
import pandas as pd
# 读取数据
similarity1 = pd.read_csv('output/similarity1.csv', header=0, encoding='gb18030').values
similarity2 = pd.read_csv('output/similarity2.csv', header=0, encoding='gb18030').values
similarity1 = np.mat(similarity1)
similarity2 = np.mat(similarity2)
# 原始数据会有一行一列是序号,所以要删除,之前读... |
539873a745c9efa5dc9ec27ffa96bcdcd7dbeb6e888adc5936ac92e608e955f2 | Python | 2,047 | 63 | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
fc99726ae90fa5e9356683e986d64ecc0e9a84d08b10b9365a0baa9db9a9d99f | Python | 2,047 | 65 | import matplotlib.pyplot as plt
import numpy as np
from .analysis import cl_for_model
from .evaluation import evaluate_models
def plot_results_by_channel(axs, results, channel_names, title):
for c, name in enumerate(channel_names):
for mname in results:
if c < results[mname].shape[0]:
... |
ca236d7399421a9a425b79020ab7c2c93f0604e83d7a9c432e566992077ef048 | Python | 2,048 | 69 | import tempfile
import os
import argparse
import json
from Bio import SeqIO
from model.utils import feature_generate
from model.data import NeuroPepDataset, collate_fn
from model.net import AttentiveNet
from torch.utils.data import DataLoader
import torch
def test_data_iter(data_path):
data = NeuroPepDataset(da... |
fa2f394d9e37553ffb6d6f5d0d17510079fdbabbc073dfc470160096c16c266f | Python | 2,048 | 86 | import sys
import pickle
import numpy as np
from neuron import h, gui
def run(steady_state):
s = h.Section()
s.insert("minipump")
s.diam = 1.0
t_hoc = h.Vector().record(h._ref_t)
X_hoc = h.Vector().record(s(0.5).minipump._ref_X)
Y_hoc = h.Vector().record(s(0.5).minipump._ref_Y)
Z_hoc =... |
02d3cf4ed5e082d2078a0f40387cc3b9cf6809456558eec519f18874fe5bb8c3 | Python | 2,049 | 61 | import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
from sklearn.model_selection import StratifiedKFold
def load_local_emnist(path, dataset='letters', kind='train'):
import os
import gzip
"""Load eMNIST data from `path`"""
labels_path = os.path.join(path, f'emnist-{dataset}-{k... |
a42b88a5dde080d2f2da6ba59efc735509a1645869c310425638f82d69ac089b | Python | 2,049 | 56 | """
Use ICA to removed EOG and ECG artifacts from the data.
"""
import sys
sys.path.append('..')
import argparse
import mne
from mne.preprocessing import ICA
from config import fname, baseline, reject
import pandas as pd
# Be verbose
mne.set_log_level('INFO')
# Handle command line arguments
parser = argparse.Argument... |
0310496bc9e53e8f72874e49c0d949d3eb8a6d442bec1da10dae66a49ba1a9cb | Python | 2,050 | 65 | import ast
import csv
import numpy as np
import matplotlib.pyplot as plt
from modular_splicing.evaluation.predict_motifs import predict_motifs_binarized_sparse
from modular_splicing.motif_names import get_motif_names
def to_one_hot(s):
return np.eye(4, dtype=np.float32)[["ACGT".index(c) for c in s]]
def load(p... |
532c33b825e5c011b0a6e8ed791c3815151c4fd04c632516df9d01a042e6449a | Python | 2,050 | 58 | from sqlalchemy import (
false,
select,
update,
)
from typing_extensions import Protocol
from galaxy.structured_app import BasicSharedApp
class IsUserModel(Protocol):
id: int
class ApiKeyManager:
def __init__(self, app: BasicSharedApp):
self.app = app
self.session = self.app.mod... |
6d15ce085106438eae4f57bb1e243600d3f9ff00abd72391da31de86f95b5c7c | Python | 2,050 | 64 | """
# > Script for measuring quantitative performances in terms of
# - Structural Similarity Metric (SSIM)
# - Peak Signal to Noise Ratio (PSNR)
# > Maintainer: https://github.com/xahidbuffon
"""
## python libs
import numpy as np
from PIL import Image
from glob import glob
from os.path import join
from ntpath imp... |
cb429909208d8f41b14afafd825834a52b022c28dd785f245d8502dec2092c49 | Python | 2,050 | 57 | import os
import sys
from urllib import request
import pandas as pd
import numpy as np
def download_pdb(pdbcode, datadir, downloadurl="https://files.rcsb.org/download/", assembly=-1):
"""
Downloads a PDB file from the Internet and saves it in a data directory.
:param pdbcode: The standard PDB ID e.g. '3IC... |
2681f121467c0ac0bbf3a318a9a421a5c47944fb2b5fb2d770f09a68b123d3ff | Python | 2,053 | 55 | import numpy as np
import torch
from modular_splicing.dataset.additional_data import AdditionalData
from modular_splicing.example_figure.run_models import compute_thresholds
from modular_splicing.models.modules.lssi_in_model import BothLSSIModelsJustSplicepoints
class FilterByIncorrectLSSI(AdditionalData):
"""
... |
8bcc5ebfe915ec8978c79b63498609425ac3e18ef161eb3c5fac1f682766aa95 | Python | 2,053 | 45 | import pandas as pd
import logging
from utils_stats import output_summary_of_ensemble_strategy
from utils.json_loader import load_json_into_pandas_dataframe
df = load_json_into_pandas_dataframe(
"data/datasets/EC_prediction/EC_prediction_valid.json"
)
dict_all_ensembles = {
"ProtBert_EC40_classic": [
... |
d421d6504fd17e868a50b9dbcfa4caec0042dce9830502a867f5b55c938fcbc0 | Python | 2,053 | 48 | """
The vocabulary building scripts.
"""
import os
from grover.data.torchvocab import MolVocab
def build():
import argparse
parser = argparse.ArgumentParser()
# parser.add_argument('--data_path', default="../../dataset/grover_new_dataset/druglike_merged_refine2.csv", type=str)
# parser.add_argument('... |
68d4b23e133b7c87892528a1bf6d5ee8842accdbac4d708843d98389aee596bf | Python | 2,054 | 51 | # Copyright The PyTorch Lightning 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 i... |
620fb7830efd0b60bf17ad2449ec2e0e6e2554bc104258dcfa1063d2af25ed0f | Python | 2,055 | 44 | """
Théo Gauvrit
Mars 2022
Centralize all the functions of EPA.
Compute PSD analysis, first method upstate/downstate detection, and second method (alenda et al) upstate/downstate method
"""
import pandas as pd
import os
from SpontaneousActivity.PSDAnalysis import plot_periodogram, computation_psd_bands, psd_computation... |
f96fea021f5d89052b69b9491cb4b25f2e229f9d51e223558bcfa782b4bd7b2e | Python | 2,055 | 56 | # Copyright (c) 2022 PaddlePaddle 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 app... |
af2f10b01f0c5960b54f1e372363c758d101ad1ccea452e591d280992847dce9 | Python | 2,056 | 48 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: Pramod Bharadwaj Chandrashekar, Li Liu
@email: pchandrashe3@wisc.edu, liliu@asu.edu
"""
import pickle as pk
import pandas as pd
import deepclan_regelem_util as dru
import DeepCORE_data_util as ddu
mdl_fldr = 'model/samp/' # Point to the model folder
pred_inf... |
7b9f9919ca229d01962047278662269f402be29f07f9ef360be2d173e6e5b58e | Python | 2,057 | 54 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
1c8fb22784bb7d9cd7566b992ab76a874713f0b4c59ce93bea51512b6ddd6bec | Python | 2,058 | 80 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_ir.py -- Live IR beam status display for Rev D Magpi panels.
Shows the current state of all IR sensors, updating continuously.
Press Ctrl+C to exit.
Usage:
python test_ir.py
"""
import sys
import time
def main():
try:
from pyoperant.interfaces.r... |
05ddc128f42accb1d427f17eea9c95bdff5a4465692e5549056456f7ead48e74 | Python | 2,059 | 81 | """
## part summary for FreeCAD part library
date: 2019-10-07
"Mechanical Parts" 208MB, half is Fasteners
3 file types are given, stl, FCStd, step for each part/component
7000 data samples, imbalanced data
https://www.freecadweb.org/wiki/Fasteners_Workbench
text book: mechanial design parts
part identification, ma... |
28d1209e3b0f1e58de0b59bcb8ee1ae772493ffc7b4052a3526f694c5f05db55 | Python | 2,059 | 69 | import os
from typing import List
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import tensorflow as tf
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from analysis.visualization import Visualizer
from utilities.plotting import transparent_cmap
os.chdir("../../../")
os.envi... |
3b01b4632fb4be4afe7874367f0540efa0bf2d8d455a38270c266cbd3ef23626 | Python | 2,059 | 71 | """_summary_
This module contains the documentation for the metrics that are used in the codecarbon package.
Goal is to provide a common place to generate the metrics with the same information.
Example of how to use it:
```python
from codecarbon.output_methods.metrics.metric_docs import duration_doc
from p... |
fff17e3f24c4dde3d5da2e8908ce69653df3da3f830cb60ee3d2dfe722142997 | Python | 2,059 | 55 | # -*- coding: utf-8 -*-
import sys
sys.path.append('./src/')
import os
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ExponentialLR, StepLR
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm, trange
import pickle
from data import GeneratorData
from src.generator_lstm impo... |
31e8807dd1882db1493a3c40f48684249ece41f93babec52621534d4dffc479a | Python | 2,061 | 86 | """Test functions for specparam.data.bands."""
from pytest import raises
from specparam.bands.bands import *
###################################################################################################
###################################################################################################
def tes... |
61aa44a09df91d2d5a1c484e1ee792f46d7c45bd107b06143b2409fcc415a1ad | Python | 2,061 | 73 | # This example requires the following dependencies to be installed:
# pip install lightly
import torch
import torchvision
from torch import nn
## The projection head is the same as the Barlow Twins one
from lightly.loss import VICRegLoss
## The projection head is the same as the Barlow Twins one
from lightly.loss.vi... |
deb551bd854f90ca1473d731de1d7586af9449fc95fd2432f4cc9d0ccd38c11b | Python | 2,061 | 59 | import math
from typing import Optional, Callable
import torch
import torch.nn as nn
from torch import Tensor
def make_divisible(v: float, divisor: int, min_value: Optional[int] = None) -> int:
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is d... |
f900518044bf045f9022015ebe8ccbb7d617986c49eafc602de61565ef765a7f | Python | 2,061 | 56 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for diffusion.py"""
import unittest
from sknetwork.data.test_graphs import *
from sknetwork.regression import Diffusion, Dirichlet
# noinspection DuplicatedCode
class TestDiffusion(unittest.TestCase):
def setUp(self):
self.algos = [Diffusion(), Di... |
99aaf30f33fc24d57568913facdd945a78379c14cdfc4eacaaca2ac6ab062d40 | Python | 2,062 | 69 | """Base dataset methods."""
import os
from mxnet.gluon.data import dataset
# pylint: disable= arguments-differ,unused-argument,missing-docstring,abstract-method
class ClassProperty(object):
"""Readonly @ClassProperty descriptor for internal usage."""
def __init__(self, fget):
self.fget = fget
def... |
3636c29c7724b7a827e238db08649eaa7f9f0aaaff71a97a8c348af09ee172e7 | Python | 2,063 | 48 | import os
import pandas as pd
pd.set_option('display.max_columns', 10)
from tqdm import tqdm
tqdm.pandas()
from drug_interactions.utils.calc_metrics import calc_metrics
test_df = pd.read_csv('./data/csvs/data/test_all_chemprop_similar.csv')
test_df = test_df.sort_values(by=['Drug1_ID', 'Drug2_ID'], ascending=True).... |
6f085cb45e041a717f0c681e52af908f58e44c37780d3c190d9c200d97d1d59d | Python | 2,063 | 66 | #Hopfield Networks created as described by:
# Wulfram Gerstner, Werner M. Kistler, Richard Naud, and Liam Paninski.
# Neuronal Dynamics: From Single Neurons to Networks and Models of Cognition.
# Cambridge University Press, 2014.
#Run for simulation of CRFS in:
#Identification of Pattern Completion Neurons in N... |
899d403f1b0fc6955070f26dbcad02d725bae75c35a96e475f0f94952c2f9499 | Python | 2,063 | 59 | """Guards on the test-suite configuration itself.
`-n auto` used to be forced through `addopts`. Every xdist worker pays a ~4s
larvaworld registry import, which dominated the actual test work: a 9-test run
took 104s instead of 5s, and even the full portal suite was slower in parallel
(838s vs 746s). Parallelism and co... |
c8f5306602321f3f961977cc5df669b3ab8ac26f616e929ad0d22fb8423cc3e0 | Python | 2,063 | 60 | import matplotlib.pyplot as plt
from rectipy import Network
import numpy as np
# model parameters
node = "neuron_model_templates.rate_neurons.leaky_integrator.tanh"
N = 200
k = 2.0
tau = np.random.uniform(10.0, 20.0, size=(N,))
eta = 2.0
J0 = np.random.randn(N, N)
J0 /= np.max(np.abs(np.linalg.eigvals(J0)))
dt = 1e-2... |
1d6442bfa9738a1d1ca31d49e54da3eb25d9a1975c142ea8a18d203aec811eae | Python | 2,065 | 45 | import sys
sys.path.append('../TM2_segmentation')
import argparse
from scripts.segmentation import train
import os
import warnings
from settings import CUDA_VISIBLE_DEVICES
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
warnings.filterwarnings("ignore")
if __name__ == '__main__... |
282e85fda1031d122e7e856e6361adb2a2c4333b91ca88be6d1bdd5f3ef38316 | Python | 2,065 | 57 | """
This module create TransformerClassifPerProt
"""
# pylint: disable=W0223
import torch.nn as nn
from torch.nn.modules.normalization import LayerNorm
class TransformerClassifPerProtLayerNormConcat(nn.Module):
"""
This class define a Transformer model that classify an entire protein to ONE classe
"""
... |
6adbde0b45fb59aa78e55496ccd76854ff7193762934da3d2cb0e2c1db416f43 | Python | 2,065 | 53 | import sqlite3
from .db import Database
from .KL_tables import (
KL_contact_travel_cumulative,
KL_contact_travel_new,
KL_critical_patients,
KL_cumulative_summary_t_minus_one,
KL_cumulative_summary,
KL_daily_summary,
KL_district_abstract,
KL_district_case_... |
8a450e61cbf3e6884b93e102363e9f93994d07f29a02ff397c0f9841ca020a34 | Python | 2,065 | 46 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 30 06:01:05 2021
@author: cbri3325
"""
import SimpleITK as sitk
import os
from ImageAnalysisFunctions import *
data_supradir = 'Path to data directory' #Set working directory
subjs_path = [ f.path for f in os.scandir(data_supradir) if f.is_dir() ] #Create a ... |
a157083503585effa32e902e2648812891d1f0cf2e9cd872640332a4fefe0d98 | Python | 2,065 | 52 | import nfp
import numpy as np
from nfp.frameworks import tf
layers = tf.keras.layers
def test_save_and_load_message(
inputs_no_padding, inputs_with_padding, smiles_inputs, tmpdir
):
"""mainly to do with https://github.com/tensorflow/tensorflow/issues/38620"""
preprocessor, inputs = smiles_inputs
at... |
e58f845ff94e3498ee9399e38bd78784d9be03a7bfe5357af6ea9216a68e77a8 | Python | 2,065 | 61 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for load.py"""
import tempfile
import unittest
import warnings
import numpy as np
from sknetwork.data.load import load_netset, clear_data_home, save, load
from sknetwork.data.toy_graphs import house, star_wars
from sknetwork.data.timeout import TimeOut
class ... |
0833d76288f27b899487e5d005c6fce876e320aa532707dbfcc7141a69df8a48 | Python | 2,066 | 57 | """2. GluonCV C++ Inference Demo
================================
This is a demo tutorial which illustrates how to use existing GluonCV
models in c++ environments given exported JSON and PARAMS files.
Please checkout :ref:`Export Network <sphx_glr_build_examples_deployment_export_network.py>` for instructions of how ... |
4cead1728ef3be46d59b621bdd8898e60b1002014ef117551027b817e2282a57 | Python | 2,066 | 111 | #######################################################################################################
##################### Preprocessing for multi-task models #############################################
#######################################################################################################
impo... |
cb33d20145c93db5a12b84948930cfde0d99cdc8d9496eea9b65a10cc5ea98a4 | Python | 2,066 | 62 | import pandas as pd
import json
# List of subjects and sessions
deriv_dir="/oak/../AHRB/derivatives"
fp_dir = f'{deriv_dir}/fmriprep_23.1.0'
task = 'mid'
# read in list of IDs/ses to summarize
id_ses_df = pd.read_csv('id_ses.tsv', delimiter='\t', header=None)
dfs = []
count_n = 0
# Loop through subjects and sess... |
71c715a3c68dd2b1b43a33f36df64abd96cf963518e93dad16a3d99534fdd067 | Python | 2,067 | 64 | """
# > Script for measuring quantitative performances in terms of
# - Structural Similarity Metric (SSIM)
# - Peak Signal to Noise Ratio (PSNR)
# > Maintainer: https://github.com/xahidbuffon
"""
## python libs
import numpy as np
from PIL import Image
from glob import glob
from os.path import join
from ntpath imp... |
762cfaa4ccbcc3158da447b32c86b9b8cfd8eedba92accb22aed4e87fdee40cd | Python | 2,067 | 68 | from itertools import product
from typing import Tuple, Optional
import numpy as np
def img_to_casorati_matrix(
img: np.ndarray, mask: Optional[np.ndarray] = None
) -> np.ndarray:
"""
Converts a given 2D image to a Casorati matrix.
Args:
img (np.ndarray): The 2D image to be converted. Shape ... |
ad101e3e35704800429b847eaf879b23979ef56943a6e4488b0f85548f26e550 | Python | 2,067 | 53 | import os
from data import common
from data import srdata
from data import irdata
import numpy as np
import torch
import torch.utils.data as data
# class Benchmark(srdata.SRData):
class Benchmark(irdata.IRData):
def __init__(self, args, name='', train=True, benchmark=True):
super(Benchmark, self).__init... |
cf09bf32963197db41cf9e6a414e5407c9bfee6ace3d03ae7d25e674b2c88823 | Python | 2,067 | 114 | """
Here is the schemas used to communicate with the API.
"""
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from uuid import UUID
@dataclass
class EmissionBase:
timestamp: str
run_id: str
duration: int
emissions_sum: float
emissions_rate: float
cp... |
ddc6d6e4db6fe242d3195ba3a4d205ff0eef01f49dd5313998308be10906a036 | Python | 2,067 | 53 | import os
from Bio.PDB import PDBParser
import pandas as pd
from tqdm import tqdm
def main(csv_loc, meta_loc, pdb_loc):
# load validated csv
df = pd.read_csv(csv_loc)
pdb_ids = df['pdb_id_corrected'].unique() # grab pdb ids from csv
# load oligomeric state metadata csv
odf = pd.read_csv(meta_loc)... |
936adf3245c9644137b92005bc054d1d0178ce887a37bb99076a92fc164e763d | Python | 2,068 | 65 | #! /usr/bin/env python
import torch
from tensorqtl import *
from tensorqtl import genotypeio, trans
from tensorqtl import tensorqtl
import argparse
import pandas as pd
from sqlalchemy import create_engine
import time
from tqdm import tqdm
sys.path.insert(
1, os.path.join(os.path.abspath(os.path.dirname(__file__)),... |
bea76e5baffd8cc1832561e3b2646e17262c7058ea1bf930b94f6b8c487100a1 | Python | 2,068 | 77 | '''
Finding the model's score.
'''
import numpy as np
import pandas as pd
import argparse
def snip(pred, test):
'''
Removing padding atoms from each prediction.
'''
all_preds = np.empty([0])
for i in range(len(pred)):
nha_i = test.loc[i, 'nha']
p_i = pred[i][0:nha_i]
all_pr... |
f89189fede9e7c50a19061a896bb7d6aaf75095f40b3eb33f0f58023fa35f288 | Python | 2,068 | 62 | import pandas as pd
import json
# List of subjects and sessions
deriv_dir="/oak/../MLS/derivatives"
fp_dir = f'{deriv_dir}/fmriprep_23.1.0'
task = 'reward'
# read in list of IDs/ses to summarize
id_ses_df = pd.read_csv('id_ses.tsv', delimiter='\t', header=None)
dfs = []
count_n = 0
# Loop through subjects and se... |
cbbe178c9980d8499561d8eae72f01b8abeead2fa10c9d5f71427da4af38a938 | Python | 2,070 | 69 | import pytest
from flask import g
from flask import session
from flaskr.db import get_db
def test_register(client, app):
# test that viewing the page renders without template errors
assert client.get("/auth/register").status_code == 200
# test that successful registration redirects to the login page
... |
c4cefcaaab0943b47394412b49c52bf5bba674aec838d00e45b1cfa21e90c967 | Python | 2,071 | 57 | # Generated by Django 3.2.6 on 2024-06-20 02:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('biomedisa_app', '0108_al... |
29de3803e1d0eb0743e77147365c19bb5dbd3b6e88132000578c0050b34d367c | Python | 2,072 | 71 | import pickle
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
# preparations
##############
import os
p = os.environ['PATH']
# plot settings
plt.rc('text', usetex=True)
plt.rcParams['figure.constrained_layout.use'] = True
plt.rcParams['figure.dpi'] = 400
plt.rcParams['figure.figsiz... |
2daebda4dc29fed5cb36c912a6115a234e9a4b5f9c33fd795e4bfeffd0cc9386 | Python | 2,072 | 39 | from . import json as json
from .app import Flask as Flask
from .blueprints import Blueprint as Blueprint
from .config import Config as Config
from .ctx import after_this_request as after_this_request
from .ctx import copy_current_request_context as copy_current_request_context
from .ctx import has_app_context as has_a... |
6da835ee078fb166f5aa11ffa39cfb3d703608191487b3657ae4799ddbf96e93 | Python | 2,072 | 71 | from mirp._images.generic_image import GenericImage
class PETImage(GenericImage):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.calibrated_units = True
@staticmethod
def get_colour_map():
return "gist_yarg"
@staticmethod
def get_default_lowest_intensity(... |
7fe4fbdaa9b6e0bb308578108879f114ba10d482c365240b43ac7efd366b84f6 | Python | 2,072 | 55 | """Written by @Jinerhal, adapted by @Xiaojieqiu.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from anndata import AnnData
def polarity(
adata: AnnData,
gene_dict: dict,
region_key: str,
mode: str = "density",
):
"""Simple function to visualize expression level varies along reg... |
966436fda87dfbb1c162e75beb4ced62fb47ae6f9ef42922311aefa2a7ccd051 | Python | 2,072 | 65 | import igraph
import numpy as np
from itertools import combinations
import copy
def find_communities(edge_index_path, edge_masks_path=None, detection_alg='louvain'):
"""
Creates communities of nodes in a graph based on edge masks and algorithm
:param edge_index_path: String which contains path to edge_inde... |
08e721dfdcf92add6d2504b816b905471347c9c60df4e07da42863ff553b82b5 | Python | 2,076 | 27 | import numpy as np
from scipy.io import savemat
PC1_testA=np.load('/Users/askeller/Documents/Kellernet_PrelimAnalysis/RidgeResults/results_matchedsamples_081822/all_network/thompson_PC1_coefs_testA.npy')
mdic={"PC1_testA": PC1_testA}
savemat('/Users/askeller/Documents/Kellernet_PrelimAnalysis/RidgeResults/results_matc... |
ed44cff72a5823856528fb2c4084d2cf0e6388dbe404c7bf2e55b9bff8a42043 | Python | 2,076 | 64 | import tensorflow as tf
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from codecarbon import EmissionsTracker
from codecarbon.emissions_tracker import TaskEmissionsTracker, track_task_emissions
tracker = EmissionsTracker(
project_name="mnist_in... |
2677f21ed48dfb2663517548cbef2d8277179ca8e854678cd70df7cdeb64ffe7 | Python | 2,077 | 84 | def omp(y0,A0):
import math as mt
import numpy as np
from numpy import linalg as LA
s=mt.ceil(len(y0))
# print(s)
a=np.zeros((A0.shape[0],0))
pos=np.zeros((1,s))
r_n=y0
# print(np.sum(r_n))
if np.sum(r_n)==0:
hat_x=np.zeros((1,A0.shape[1]))
return hat_x
# s=2
... |
5bfe73be63660f3ab92527852ab8d99d4285fe296c59098c708bb9c4c62a7d86 | Python | 2,077 | 70 | import urllib
import tempfile
import os
import enum
from urllib.error import HTTPError
class UNIT(enum.Enum):
BYTES = 1
KB = 2
MB = 3
GB = 4
def convert_unit(size_in_bytes, unit):
if unit == UNIT.KB:
return size_in_bytes / 1024
elif unit == UNIT.MB:
return size_in_bytes / (102... |
995e78e53f2b4c8ad103555e350057a5bb036f3f9b9797d223cbf7d967232556 | Python | 2,077 | 54 | import numpy as np
import fire
import pandas as pd
from auggam import data
import pickle as pkl
from os.path import join, dirname, abspath
from spacy.lang.en import English
from sklearn.linear_model import LogisticRegressionCV
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
path_to_repo = d... |
d71fc3e76d2f76bcd73a8d944d188c28786febead243d4043b8a3e21017cd6f2 | Python | 2,077 | 61 | import os
import h5py
import numpy as np
import scanpy as sc
import scvi
import torch
from scbig.utils import setup_seed, louvain, calculate_metric
for dataset in ['DPT', 'YAN', 'Deng']:
print('----------------real data: {} ----------------- '.format(dataset))
setup_seed(0)
method = 'scVI'
dir0 = '..... |
859bb21eae28187502ff882c16120b4c59575ffd4e9e665878f5c886772c7c4b | Python | 2,078 | 64 | """
# > Script for measuring quantitative performances in terms of
# - Structural Similarity Metric (SSIM)
# - Peak Signal to Noise Ratio (PSNR)
# > Maintainer: https://github.com/xahidbuffon
"""
## python libs
import numpy as np
from PIL import Image
from glob import glob
from os.path import join
from ntpath imp... |
af3cf5f8e766751b70b12efdb800d1e96bc8d2c8e8799cf9dc2cf31a5f3316f3 | Python | 2,078 | 75 | import cv2
import numpy as np
def normalise_img(img):
'''Normalize the image.
Map the minimum pixel to 0; map the maximum pixel to 255.
Convert the pixels to be int
'''
img = img - img.min()
if img.max() > 0:
img = img * (255.0/img.max())
img = np.uint8(img)
return img
def img_... |
5c023bd5c3eef30541bc1ba304cb82adff58688da278819853b4bbed1e9d144c | Python | 2,079 | 51 | """Host checks for the SM100 forward work-tile row map (NOTE [SM100 forward work coordinates])."""
import itertools
import pytest
from flash_attn.cute.flash_fwd_sm100 import work_q_block
def ceil_div(a: int, b: int) -> int:
return (a + b - 1) // b
@pytest.mark.parametrize("cta_group_size", [1, 2])
@pytest.ma... |
89c783d34b9ba6e5087b46677e9d6f9f03474a3e63b097aad9e64ebb2500034c | Python | 2,079 | 70 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import pytorch_lightning as p... |
8d497acbb720cad5ca66213fab67d0a9fb5726c124672685abc493f810a9567c | Python | 2,079 | 72 | """
Sensorimotor coupling for the 2D robot agents.
Provides the controller mapping a sensor reading onto a motor command, and the
actuator that smooths that command over time.
"""
from __future__ import annotations
from typing import Any
__all__: list[str] = [
"MotorController",
"Actuator",
]
class MotorC... |
cfbcfd8ad3abf4400cf59065489aa91d7462ef547d442bf341591c0b796decea | Python | 2,079 | 64 | """Wrapper that converts a color observation to grayscale."""
import numpy as np
import gym
from gym.spaces import Box
class GrayScaleObservation(gym.ObservationWrapper):
"""Convert the image observation from RGB to gray scale.
Example:
>>> env = gym.make('CarRacing-v1')
>>> env.observation_... |
3a659c136a2a1b647c68637effe97032b05a55d178e970a43c7979fcfe0b1469 | Python | 2,083 | 59 | """
Test backward compatibility with configuration files using old parameter names.
"""
import unittest
from textwrap import dedent
from unittest.mock import patch
from codecarbon.emissions_tracker import EmissionsTracker
from tests.testutils import get_custom_mock_open
class TestConfigBackwardCompatibility(unittes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.