sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
8241315fadf9e6ad1cb1b38f6a1feffc357804c5bd89572f0aba0f3a98646243 | Python | 2,424 | 72 | # Generated by Django 4.2.11 on 2024-04-29 13:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("mlcube", "0002_alter_mlcube_unique_together"),
migrations.swap... |
0abdba4503bc7f13f3d1ed99aea8d60df3336f1ad73dbb81c47cd5180fd7139d | Python | 2,425 | 70 | import threading
import time as time_module
from contextlib import contextmanager
from datetime import datetime as dt
from datetime import timedelta
from http.server import BaseHTTPRequestHandler, HTTPServer
import pytest
from src.babel_utils import ThrottledRequester
@contextmanager
def _local_server(delay_ms=0):
... |
1ac05fcfd71c406c3f0ecbe49f96d5d0616843557557ccda8392519d297c4027 | Python | 2,425 | 72 | # -*- coding: utf-8 -*-
"""Tsodyks-Markram model ODE solver
This module contains functions to solve the Tsodyks-Markram
model. (same equations as in Maass and Markram 2002)
@author: Andras Ecker
@remark: Copyright (c) 2017, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/Bl... |
33d07780dd59fcb962e99236101bc9474775e4829c9a80713e54ad46774c61a7 | Python | 2,426 | 68 | import numpy as np
import matplotlib.pyplot as plt
import os
from grid_cell.grid_cell_processor import Grid_Cell_Processor
from sklearn.decomposition import PCA
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, RBF, WhiteKernel
from disentangle.mo... |
9f6cab5d2f776ce6921457ed3174e484d659a87184461236103736596b89152f | Python | 2,427 | 73 | import os
import numpy as np
import pandas as pd
import pydicom
from PIL import Image
root_path = 'data/'
img_suffix = '.dcm'
seg_map_suffix = '.png'
save_img_suffix = '.png'
save_seg_map_suffix = '.png'
x_train = []
for fpath, dirname, fnames in os.walk('data/chestimage_train_datasets'):
for fname in fnames:
... |
cc6e6353fb2add708f9cd9719030778cafb863f193dee31552bd0539ef6c8352 | Python | 2,427 | 78 | import requests
from bs4 import BeautifulSoup
import os
from urllib.parse import urljoin, urlparse
def is_file(url):
"""
Check if the URL points to a downloadable file by checking the content type in the headers.
"""
try:
response = requests.head(url, allow_redirects=True)
content_type... |
b2968b878edff1f75eb6017c09a5ee5ef224d74294494a8233dcba52f3e833d7 | Python | 2,428 | 70 | import os
import copy
import argparse
import pandas as pd
import torch
import torch.utils.tensorboard
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from rde.datasets.pointmut import PMDataset
from rde.utils.misc import load_config
from rde.utils.data import PaddingCollate
from rde.utils.train impo... |
43652ff10fea468876e106b36fc04a23a643264049052374f4982f3d32eb0e41 | Python | 2,430 | 59 | """Live contract tests for :mod:`guppy.utils.dandi_preview`.
These hit the real DANDI Archive and are intended for **local use only**. They are deselected in
CI (see ``.github/workflows/run-tests.yml``) because the archive is subject to network flakiness
and its contents change as datasets are published.
Run locally ... |
4da8160e154242781942b7f3a55b8557b6e13e76cbc6f988bc05e2ef23ecec5a | Python | 2,430 | 73 | import math
import torch
import torch.nn.functional as F
def _extract_into_tensor(arr, timesteps, broadcast_shape):
"""
Extract values from a 1-D numpy array for a batch of indices.
:param arr: the 1-D numpy array.
:param timesteps: a tensor of indices into the array to extract.
:param broadcast_s... |
6c7856ee7d2d14f87e96dab82360b1bd24d0c2b993fbaad83502364f71413823 | Python | 2,430 | 72 | import tensorflow as tf
import gpflow
from tqdm import tqdm
import os
from datetime import datetime
from gpflow.monitor import (
ModelToTensorBoard,
Monitor,
MonitorTaskGroup,
ScalarToTensorBoard,
)
def run_adam(model, data, iterations, learning_rate=0.01, minibatch_size=25, natgrads=False, pb=True):
... |
01f95b92cf6d3a0472309fd5fb760646080b4287e7ded75b86ca8595974b373d | Python | 2,431 | 74 | from CybORG.Shared import Observation
from CybORG.Simulator.Actions import Action
from CybORG.Simulator.Actions.ConcreteActions.RestoreFromBackup import RestoreFromBackup
class Restore(Action):
""" Reimages a host, removing all malicious activity.
Has flat penalty of -1, representing the downtime of the host.... |
482d2e6fdb2a322fc4ca8c5554a5e237d4018e3bed6b72ca2a14b77091b0c1ee | Python | 2,431 | 90 | """Raw MS data models and format-specific readers.
Public imports from the former ``masscube.raw_data_utils`` module remain
valid. Imports are lazy so the standalone TDF decoder in :mod:`._tdf` retains
its standard-library-only runtime boundary.
"""
import importlib
__all__ = [
"CalibratedTimsFrame",
"Corru... |
81b9f5e635291e2433df8a028bfb5f788cddf38ef594cf815a41fa3b52007948 | Python | 2,432 | 78 | import warnings
warnings.filterwarnings("ignore")
import scanpy as sc
from torch.optim import NAdam
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from utils import *
from models import Path_MGCN
dataset = '151507'
config_file = './config/DLPFC.ini'
config = Config(config_file)
kegg_gmt_file = '..... |
95ccb5332f17e37039e8a8d4959830aacd4b31855ea080ef1c3828ba9730be73 | Python | 2,432 | 80 | #!/usr/bin/env python
# coding: utf-8
import scanpy as sc
import scib
import warnings
warnings.filterwarnings('ignore')
def runPP(inPath, outPath, hvg, batch, rout, scale, seurat):
"""
params:
inPath: path of the anndata object
outPath: path of the preprocessed file to be written
hvg... |
e5412336134f31417f44d4bb940f0f104e71c9f1dba1e250990c7592c5094b69 | Python | 2,434 | 65 |
import torch
from transformers import LlamaForCausalLM, AutoTokenizer
from typing import List
import torch.nn.functional as F
def zero_pad_sequences(sequences: List[torch.Tensor], side: str = 'left', padding_value: int = 0) -> torch.Tensor:
assert side in ('left', 'right')
max_len = max(seq.size(0) for seq in... |
783c9bca32af2050212db63cd816a41670f9fbcaa844b40c6900bc8336e70597 | Python | 2,435 | 74 | import os
from typing import Any
from cwl_utils.types import CWLObjectType
from . import load_tool
from .context import LoadingContext, RuntimeContext
from .errors import WorkflowException
from .executors import JobExecutor, SingleJobExecutor
from .process import Process
class WorkflowStatus(Exception):
def __i... |
237b87ae247318101969daa3e52d4767412c9fede71a6552df1768a813bd7285 | Python | 2,437 | 87 | from typing import Optional
from medperf.entities.ca import CA
import typer
import medperf.config as config
from medperf.decorators import clean_except
from medperf.commands.ca.submit import SubmitCA
from medperf.commands.list import EntityList
from medperf.commands.view import EntityView
app = typer.Typer()
@app.... |
92e32c1389feece60a8a9d9955dd201ecc844d4197d9a442f09f05c9a81c3ace | Python | 2,437 | 68 | # -*- coding: utf-8 -*-
# tests/test_optional_imports.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade, Tobias Lemke
#
# Encodermap i... |
41c190b0d657156ce7d969fe6acfbec29de6332446783f6a2746c653595d392c | Python | 2,438 | 59 | # -*- coding: utf-8 -*-
import os
import catmaid
from django.core.management.base import BaseCommand, CommandError
from django.db import connection, transaction
from catmaid.models import Project
class Command(BaseCommand):
help = 'Prunes skeletons in the specified projects. All unreferenced ' \
'nodes ... |
18cf30c45382087d9f5f27c0ecd253562627045a3ae5c7ce2959179c5fe8a745 | Python | 2,440 | 87 | #!/usr/bin/env python
#######################################################################################
# This file is provided under the Creative Commons Attribution 3.0 license.
#
# You are free to share, copy, distribute, transmit, or adapt this work
# PROVIDED THAT you attribute the work to the authors liste... |
9624a07169eb1a963bca1eef21b831401afa6eb566f9d4b2bea3f9512b809fc8 | Python | 2,441 | 65 | import pytest
from guppy.orchestration import tonic_analysis
@pytest.fixture
def preprocessed_run_folder(tmp_path):
"""A run folder holding the Step-3 outputs the epoch page reads."""
run_folder = tmp_path / "session_output_1"
run_folder.mkdir()
(run_folder / "cntrl_sig_fit_dms.hdf5").touch()
ret... |
9a42f87a72ffd2a7c2da7ccdf970ae0944ef72b69640c9bf3265e880997b454e | Python | 2,441 | 39 | import os
import platform
from .client import Client, default_client, set_default_client, clear_default_client, list_all_clients
from .queries import ( fetch_custom, fetch_meta, fetch_all_rois, fetch_primary_rois, fetch_roi_hierarchy,
fetch_neurons, fetch_custom_neurons, fetch_simple_connections... |
be7fdb57134d697b57fb272b5c799568b0e988772bd17fc8de0e5de5b69809ce | Python | 2,443 | 61 | # Copyright (c) 2020 Anita Hu and Kevin Su
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publis... |
fb9e9ecea904a61e3aa715f1ca2287a648438462ca912f3fdd6920da76d55293 | Python | 2,444 | 85 | """CLI admin commands: users list, users login."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Annotated
import typer
from zndraw.state_file import StateFile, TokenEntry
from .connection import (
PasswordOpt,
TokenOpt,
UrlOpt,
UserOpt,
cli_error_hand... |
bd9dedd1935e391990840ea5dee392b46e9d8967beccdc55138ec94ec2e7f1f3 | Python | 2,447 | 69 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import argparse
import os
def execute_browser_flow(emai... |
38489acd1b113c8b8e6a85c8b5f78f5250ad056a037396c639d8360363a3455a | Python | 2,448 | 84 | #!/usr/bin/env python
# coding=utf-8
# Copyright 2023 Statistics and Machine Learning Research Group at HKUST. All rights reserved.
"""A simple shell chatbot implemented with lmflow APIs.
"""
import logging
import json
import os
import sys
sys.path.remove(os.path.abspath(os.path.dirname(sys.argv[0])))
import warnings
... |
54670b57c2403cc7ec3da72001ea5b6499981d35d325f62c15c94aaa56b690f9 | Python | 2,448 | 54 | import os
# Configuration
# Path to TRIAL VIDEOS
video_path = r'C:\Users\Wolff_Lab\Head_twitch\Videos' # CHANGE!
files = [f for f in os.listdir(video_path) if f.endswith('.mp4')]
# Path to MODEL
model = r'C:\Users\Wolff_Lab\Head_twitch\Mice Master N\models\240716_170449.single_instance.n=1996\training_config.json' ... |
9c1915a60176e4cd3cb593739f447205546ac5b236c9575dce67b4cd8c9c17e0 | Python | 2,451 | 96 | import matplotlib.pyplot as plt
import numpy as np
from Nearl import data_io
# %matplotlib qt
def density(coords, weights, showall=False):
"""
Create a 3D scatter plot for an N x 3 array of 3D points.
Args:
points (np.array): An array of shape (num_points, 3) containing the 3D coordinates of the poi... |
dd53b93d81069ac9987ba251df52325768f0a19644e77f5f0d6b208f3f16b043 | Python | 2,451 | 83 | import tensorflow as tf
from tensorflow.keras.layers import Layer, Dense
class DenseNormal(Layer):
def __init__(self, units):
super(DenseNormal, self).__init__()
self.units = int(units)
self.dense = Dense(2 * self.units)
def call(self, x):
output = self.dense(x)
mu, l... |
4e1455966d3755583e6d5c6f758cd66aebc668250e49115e7fea92f65323461a | Python | 2,452 | 57 | import setuptools
from setuptools import setup
setuptools.setup(
name='chisel',
version='1.2',
python_requires='==2.7.*',
packages=['chisel', 'chisel.bin'],
package_dir={'': 'src'},
author='Simone Zaccaria',
author_email='s.zaccaria@ucl.ac.uk',
description='Copy-number Haplotype Infere... |
633a9b83b6a4eaa895d20d6a0e23385d5291e0069456a11113e88e85c9ec52a9 | Python | 2,456 | 78 | import torch
import matplotlib.pyplot as plt
import cv2
class GradCAM:
def __init__(self, model, target_layer):
self.model = model
self.target_layer = target_layer
self.gradients = []
self.activations = []
self._register_hooks()
def _register_hooks(self):
def sa... |
ac1c62b8ef61d34abe444b901ac285e76c5a319f4a9256a621b73ed43357a729 | Python | 2,456 | 61 | import unittest
import numpy as np
from PyQt5 import QtGui
from features.EventShape import EventShape
from tests.TestData import processed, DataManager, Plot, source, burst_time, spike_time
from util.conf import es_params
from util.functions import movingAverage
app = QtGui.QApplication([])
class EventSha... |
6fa11120eb780b831b93038a9f71677651d67215565d0205f51c3dc57b38935a | Python | 2,457 | 75 | import os
import medperf.config as config
from medperf.exceptions import InvalidArgumentError
from medperf.utils import sanitize_path, validate_and_normalize_emails
class UpdateCommitteeMembers:
@classmethod
def run(
cls,
benchmark_uid: int,
committee_emails_file: str = None,
... |
88a691e11d4d5b4417a46570ff1de39234439f64b5f7c48c215e55468761a4f6 | Python | 2,457 | 74 | # coding=utf-8
import jieba
import torch
def jieba_tokenize(str):
return jieba.lcut(str)
_UCODE_RANGES = (
("\u3400", "\u4db5"), # CJK Unified Ideographs Extension A, release 3.0
("\u4e00", "\u9fa5"), # CJK Unified Ideographs, release 1.1
("\u9fa6", "\u9fbb"), # CJK Unified Ideographs, release 4.... |
8ade09aa839511f2de31dceb36ef45d1bd4a1ddd1d670e7396ec43799ff1c8d4 | Python | 2,458 | 60 | import numpy as np
import gpflow
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from grid_cell.gaussian_wishart.src.models.BaseWishartProcess import WishartProcessBase
class WishartProcess(WishartProcessBase):
"""
Concrete model that implements the (inverse) Wishart Process wit... |
749c9278aa431d59e8d55f624d58ef38dd77954ca94014ac485862eb55ee667a | Python | 2,459 | 69 | # Module for easier working with video files
# This module provides utility functions to manage video files,
# including creating temporary paths, rotating videos, and deleting them.
import os
from src.utils.paths import PATH_TO_TMP
def build_path_to_tmp(file_name):
"""
Constructs the complete file path for a... |
f60647957d201bbd0f3910a8b43ea3b9676eabec2aaf8ff20e27da835e98772d | Python | 2,459 | 37 | # dataset settings
_base_ = './mapillary_v1.py'
metainfo = dict(
classes=('Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail', 'Barrier',
'Wall', 'Bike Lane', 'Crosswalk - Plain', 'Curb Cut', 'Parking',
'Pedestrian Area', 'Rail Track', 'Road', 'Service Lane',
'Sidewalk', 'B... |
63ec290448596fdf10628516c1911e438738bb68db094b7a341b9ee75af5bfab | Python | 2,460 | 62 | import surrogateTraining
from surrogateParams import surrParams
import simLogger
import argparse
from weightAnalysis import getWeightFromUniqueId
parser = argparse.ArgumentParser(description='Training program for a range of parameters with the SHD dataset')
parser.add_argument('--log_file', help='log file path')
parse... |
331b8bc79667037cc8f3d7b78bb693772203bb4be34862bd5e553974c67ee0fd | Python | 2,461 | 68 | from typing import Optional
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
from fengshen.data.mmap_index_dataset import MMapIndexDataset
class MMapDataModule(LightningDataModule):
@ staticmethod
def add_data_specific_args(parent_args):
parser = parent_args.ad... |
f95baf0ab977e660510e048f3349ecf8be8cf6801b4df09c2b2e148b2cfd60e4 | Python | 2,461 | 66 | import logging
from django.core.management import call_command
from django.conf import settings
from catmaid.control.cropping import cleanup as cropping_cleanup, process_crop_job
from catmaid.control.nat.r import export_skeleton_as_nrrd_async
from catmaid.control.treenodeexport import process_export_job
from catmaid.c... |
b569d7d1b837ca8d3526be5fcbab1d200e1a0de0b790bfe3f22ff51a0cf8650e | Python | 2,463 | 71 | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-ignore-all-errors
import copy
import unittest
from fvcore.common.param_scheduler import CosineParamScheduler
class TestCosineScheduler(unittest.TestCase):
_num_epochs = 10
def _get_valid_decay_config(self):
return {"start_value": 0.1, "end_... |
206e8a695ab6ea278510556c57540320157b45443723270a8f45ddb04e6bc6a4 | Python | 2,464 | 63 | import logging
import torch
def init_edge_rot_mat(edge_distance_vec):
edge_vec_0 = edge_distance_vec
edge_vec_0_distance = torch.sqrt(torch.sum(edge_vec_0**2, dim=1))
# Make sure the atoms are far enough apart
# assert torch.min(edge_vec_0_distance) < 0.0001
if torch.min(edge_vec_0_di... |
b522aa5369963c776e3ba20170f3eef0b42c007508ecefbb10c3d00851a7638b | Python | 2,464 | 64 | import pytest
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import tsgm
from tsgm.backend import get_distributions
distributions = get_distributions()
import numpy as np
import keras
def test_abc_rejection_sampler_nn_simulator():
ts = np.array([[[0, 2], ... |
cac778c603136e99590099862bc6babb5d9709bde05f39f00ea6f60070af1f17 | Python | 2,464 | 79 | import csv
condition_mapping_file = "./resources/CCSCM.csv"
procedure_mapping_file = "./resources/CCSPROC.csv"
drug_file = "./resources/ATC.csv"
condition_dict = {}
with open(condition_mapping_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
condition_dict[row['code']... |
6ae2e78504c208ec3ff84ab1e01229ba6b2f8d55475f52e65f9377236fc699f5 | Python | 2,465 | 80 | import pandas as pd
import argparse
import os
import yaml
import json
from utils import get_image_data_df
class Stats:
def __init__(self, data_path, out_file, params):
self.data_path = data_path
self.data_file = os.path.join(data_path, params["output_datafile"])
self.df = pd.read_csv(self... |
8363132d40d6ad82653fdf6ab80edc52fa02192d933d275d3483f9d7969e7ff6 | Python | 2,465 | 78 | import pytest
from keras.utils.test_utils import layer_test
from keras import layers
from keras import backend as K
@pytest.mark.parametrize('activation_layer',
[layers.LeakyReLU,
layers.ELU])
@pytest.mark.parametrize('alpha', [0., .5, -1.])
def test_linear_unit_acti... |
9d1b49ec56624e27d6e8a979442fb0ab8b47acfabd5d9c87828aa7668b815abf | Python | 2,465 | 86 | import os
from kgx.source import JsonlSource
from kgx.transformer import Transformer
from tests import RESOURCE_DIR
def test_read_jsonl1():
"""
Read from JSON Lines using JsonlSource.
"""
t = Transformer()
s = JsonlSource(t)
g = s.parse(os.path.join(RESOURCE_DIR, "valid_nodes.jsonl"))
nod... |
da18a968ca8ed98cf9fafde80bcb836a721954db11ed59ce5b053e58c9d9f045 | Python | 2,467 | 66 | import shutil
from pathlib import Path
import pytest
from guppy.testing import compare_output_folders
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import TESTING_DATA, event_ts_offset_for
SESSION_SUBDIR = "SampleData_csv/sample_data_csv_1"
STANDARD_OUTPUT_SUBDIR = ... |
c6dac9504c879977bfdfec27fe01524adb40ead7fad7e9a97f335769d504c367 | Python | 2,469 | 90 | import argparse
import torch
from e3nn.util import jit
from mace.calculators import LAMMPS_MACE
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"model_path",
type=str,
help="Path to the model to be converted to LAMMPS",
)
parser.add_argument(
... |
512c744c9d2602c1356d0476d53644c62aba3378ba8cfcb23a72b104585923cd | Python | 2,470 | 84 | import glob
import os
import cv2
import SimpleITK as sitk
from PIL import Image
root_path = 'data/'
img_suffix = '.tif'
seg_map_suffix = '.png'
save_img_suffix = '.png'
save_seg_map_suffix = '.png'
src_img_train_dir = os.path.join(root_path, 'CRASS/data_train')
src_mask_train_dir = os.path.join(root_path, 'CRASS/mas... |
73f7070daa5f8e1301fcefed628a9733574846c41569045a8eec32d7f5da472c | Python | 2,470 | 62 | ######################################
# wrapper for rule: alignment_single_genomic
######################################
import os
import sys
import math
import subprocess
import glob
from snakemake.shell import shell
STAR = "STAR"
SAMTOOLS = "samtools"
shell.executable("/bin/bash")
f = open(snakemake.log.run, 'a+... |
90d05c70edd9bd43d2e9fce222985e2b730ef8cfc7e65044aa69ea845acd9408 | Python | 2,470 | 64 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
b11d3dd14bd5132608205c354cade0fdf470f27e36463434b6b3f4d951dd5624 | Python | 2,470 | 71 | import json
from tqdm import tqdm
import argparse
label2desc={"news_story": "故事",
"news_culture": "文化",
"news_entertainment": "娱乐",
"news_sports": "体育",
"news_finance": "财经",
"news_house": "房产",
"news_car": "汽车",
"news_ed... |
645ff2a6a914e1e5e6164f1fcbeb72e8d56c09315c41d066bb7474ad34655e31 | Python | 2,471 | 82 | from typing import Union
from google.cloud import storage
from .types import GCPAssetConfig, GCPOperatorConfig
def upload_file_to_gcs(
config: Union[GCPAssetConfig, GCPOperatorConfig], local_file: str, gcs_path: str
):
"""Upload file to Google Cloud Storage."""
client = storage.Client()
bucket = clien... |
19dc6aa74c828d37bcc4d9195ba92bc0e49fa6b2e8b74de75c025f38697201bb | Python | 2,472 | 77 | import functools
import numpy as np
import matplotlib.pyplot as plt
import evidential_deep_learning as edl
import tensorflow as tf
def main():
# Create some training and testing data
x_train, y_train = my_data(-4, 4, 1000)
x_test, y_test = my_data(-7, 7, 1000, train=False)
# Define our model with an... |
96f35434ea96c3ef1001d682c9ea52e41f12148bcb171188c5a37245e7137367 | Python | 2,473 | 116 |
import cProfile
import diffrax
import jax.numpy as jnp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import jax
import os
import equinox
import sys
import roadrunner
import tellurium as te
from jaxkineticmodel.load_sbml import sbml_model
jax.config.update("jax_enable_x64", True... |
b56420fd7ad76dfadfff085550df8fd6e6f5519da532010626667cfeaaf285eb | Python | 2,474 | 87 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import conv1x1x1, Bottleneck, ResNet
from utils import partialclass
def get_inplanes():
return [64, 128, 256, 512]
class ResNeXtBottleneck(Bottleneck):
expansion = 2
def __init__(... |
981fc0b32fd7cf21098bc863f211fe4a090d8061cbe88b3e4f54647ed83b09d4 | Python | 2,475 | 63 | from graphcare import *
import random
import pickle
dataset = "mimic3"
kg = "GPT-KG"
tasks = [
# "mortality",
"readmission",
"lenofstay",
"drugrec"
]
ratios = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9]
for task in tasks:
for ratio in ratios:
sample_dataset, G, ent2id, rel2id, ent_emb, rel_emb... |
b4011a67e603ea63532b2eb596abdcb401b926f76db14936135471d229844f74 | Python | 2,475 | 63 | import pandas as pd
from experiment import *
import numpy as np
import json
from sklearn.mixture import GaussianMixture
if __name__ == "__main__":
np.random.seed(2023)
winsize = params["convergence_ksize"]
min_angle = params["min_angle"]
max_angle = params["max_angle"]
# ====================
... |
e8c07874f713c959a9173656960d97d112814d5c15c3e8e5a9520a4150b2d25b | Python | 2,475 | 69 | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from .vision_transformer import VisionTransformer, _cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_
import torch.nn.functional as F
impor... |
80252c796734878bae94335333999ba7e6826ef27ae260f998ad26e0ef155df4 | Python | 2,476 | 88 | """Arrow geometry for ZnDraw."""
from pydantic import Field
from .base import (
BaseGeometry,
InteractionSettings,
PositionProp,
ScaleProp,
)
class Arrow(BaseGeometry):
"""Arrow geometry with direction vector.
Arrows are defined by a start position and a direction vector.
The direction ... |
9162c6e7c8ddb0fab1e678f05cf05fc2883e7a0a1129c67e76af9fa560d3348c | Python | 2,476 | 83 | #!/usr/bin/env python
#
# Calculate b-value
#
# N.B. SI unit for gyromagnetic ratio is radian per second per tesla, therefore need to multiply by 2pi.
#
# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
import math
from typing import Sequence
from spinalcord... |
e3dafb13a9acd73d85ebbd4cda7c5e6123a5858cd7667f26ca4ce6a6a9b6a3a8 | Python | 2,477 | 78 | import pytest
import random
import os
from multiprocessing import Process, Queue
from keras import applications
from keras import backend as K
MODEL_LIST = [
(applications.ResNet50, 2048),
(applications.ResNet101, 2048),
(applications.ResNet152, 2048),
(applications.ResNet50V2, 2048),
(application... |
05f0f8b8f22e294e9de0ee81adcce3bf5cda4635857d24c00d02c099834ff85d | Python | 2,478 | 54 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
0ef6330b187e99a508509657a6211e5b7945853151c1cf3f273b85b4e60d485a | Python | 2,478 | 82 | from rest_framework.permissions import BasePermission
from .models import TrainingExperiment
from traindataset_association.models import ExperimentDataset
from django.db.models import OuterRef, Subquery
class IsAdmin(BasePermission):
def has_permission(self, request, view):
return request.user.is_superuse... |
2d3e7e45cd6c4ab07e1b469b51f17d064b4a3adf8bca991b1bd15f80db9f4b80 | Python | 2,479 | 83 | # pytest unit tests for spinalcordtoolbox.deepseg_.postprocessing
import numpy as np
from spinalcordtoolbox.deepseg_.postprocessing import keep_largest_object
def test_keep_largest_object_2d():
"""
Test the keep_largest_object function for 2D arrays.
"""
# Define test cases
single_object_2d = np... |
41ceb3902466686dfb0aa119175761ebceb78dd882de7403b45890b965c2fe94 | Python | 2,479 | 74 | import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from .dilated_conv import DilatedConvEncoder
def generate_continuous_mask(B, T, n=5, l=0.1):
res = torch.full((B, T), True, dtype=torch.bool)
if isinstance(n, float):
n = int(n * T)
n = max(min(n, T // 2), 1)
... |
73fb7d68cea98b0c886f19d0e62ef1d939d8bba4d1e727501767260f92ebd374 | Python | 2,479 | 70 | import torch
import esm
import numpy as np
from Bio import SeqIO
import sys
import pickle
import time
if len(sys.argv) != 3:
print("Usage: python3 embed_fasta_esm.py <fasta path> <output path>")
# Load the ESM-2 model
model_name = "esm2_t36_3B_UR50D"
print("Loading model", model_name)
try:
# Try loading the mo... |
7dd3bc7be06ed43b4f9802ef0f9f9114ab33de97b71243fb6d166106082a8dbb | Python | 2,479 | 76 | """Edit lock context manager for the ZnDraw client."""
from __future__ import annotations
import logging
import threading
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from zndraw.client.api import APIManager
log = logging.getLogger(__name__)
@dataclass
class... |
8873d8713e337270aee6d4a20f8d430849a07b5a5de86296cc88cef0112cf7cf | Python | 2,480 | 80 | import pytest
from medperf import config
from medperf.commands.mlcube.create import CreateCube
from medperf.exceptions import InvalidArgumentError
PATCH_CREATE = "medperf.commands.mlcube.create.{}"
@pytest.fixture
def setup(mocker):
spy = mocker.patch(PATCH_CREATE.format("cookiecutter"))
return spy
class ... |
808cc705a4b3e544ec79a201add896574418f6076ffd4b495c72994846f99b26 | Python | 2,481 | 57 | # MagellanMapper unit testing for visualizer
"""Unit testing for the MagellanMapper visualizer module."""
import unittest
from magmap.gui import roi_editor, visualizer
class TestVisualizer(unittest.TestCase):
def test_validate_pref(self):
# select from enum
default = roi_editor.ROIEditor.Ci... |
5ad67a8669b241bc2f2bf57333c0070ff3cd753d1d361282d82a0653e86d09ae | Python | 2,482 | 92 | import io
import h5py
from PIL import Image
from lib.heart_volume import heart_classes as hc
import pickle
class ImageLoaderPIL(object):
def __call__(self, path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with path.open("rb") as f:
... |
82c34077dc5f1d628012aa2325a3527ad29364486bd6739c68c03ca299db1b73 | Python | 2,482 | 69 | #%%
import microstates.micro_helper as hp
import microstates.micro_constants as cs
import base.files_in_out as files_in_out
import base.base_constants as b_cs # all g_num
import mne
#%% extract gfp
fig_list=list()
clus_list=list()
caption_list=list()
for g_n in b_cs.G_N_prestate:
files = files_in_out.GetFiles(cs... |
c1563ee1c94beaddddc5e8364c1f9c519be98eeabf9f4df5741fae278d67b5ae | Python | 2,482 | 70 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
9dbf2d09a34cb2619387691bfbffb76cc265c76d674075dc1acc633987e7822f | Python | 2,483 | 70 | import torch
import esm
import numpy as np
from Bio import SeqIO
import sys
import pickle
import time
if len(sys.argv) != 3:
print("Usage: python3 embed_fasta_esm.py <fasta path> <output path>")
# Load the ESM-2 model
model_name = "esm2_t33_650M_UR50D"
print("Loading model", model_name)
try:
# Try loading the ... |
2614da2f3a592dbe79a5372b4f5ec30d9de5b08689ea6ed536b7f4ccf32e38b9 | Python | 2,484 | 87 | import torch
from models import SimpleCNN
from tqdm import tqdm
from torch.utils.data import DataLoader
from data_loader import CustomImageDataset
import os
import numpy as np
import yaml
from sklearn.metrics import accuracy_score, roc_auc_score
def global_accuracy(y_true, y_score, threshold=0.5):
y_pre = y_score... |
8aff63c926cb96bb9fa33ff43795cd53ab5e317dbdabcb375ad50714f58dc5d3 | Python | 2,485 | 87 |
from random import shuffle
from sklearn.neural_network import MLPClassifier
import uuid
import os
# import reader
import csm_filter
import fdr_utils
import pandas as pd
import sys
import json
from mlp_classifier_constant import MLPClassifier_ConstantWeights
#_nn = MLPClassifier(alpha=0.01,
# hid... |
601a2ed4b17a19fb12a4fa22863e4f0cab18d951073967a9706806be6539ca9b | Python | 2,488 | 57 | """
This is the interface API to compute flow-related metrics
Copyright (c) 2023 Polytechnique Montreal <www.neuro.polymtl.ca>
Author: Julien Cohen-Adad & ChatGPTv4
License: see the file LICENSE
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
def calculate_velocity(data_phase, venc):
... |
c2bed686efc8de562b75484bc8253490c70f61fc0dc9c4a7426097235f211795 | Python | 2,488 | 86 | import pytest
from medperf.entities.interface import Entity
from medperf.commands.view import EntityView
PATCH_VIEW = "medperf.commands.view.{}"
@pytest.fixture
def entity(mocker):
return mocker.create_autospec(Entity)
@pytest.fixture
def entity_view(mocker):
view_class = EntityView(None, Entity, "", "", "... |
0301806f2adf1846a5ce8723025ad42814514f20fab302d66f314c836513379d | Python | 2,489 | 84 | from medperf.exceptions import InvalidArgumentError, CleanExit
import pytest
import yaml
from medperf.tests.mocks.dataset import TestDataset
from medperf.commands.dataset.set_operational import DatasetSetOperational
PATCH_OPERATIONAL = "medperf.commands.dataset.set_operational.{}"
@pytest.fixture
def dataset(mocker... |
5d54d180afd6553040d710d6404c3629e87fc5bea0166462d58bda67f2b75abe | Python | 2,489 | 78 | from django.db import migrations, models
forward = """
SELECT disable_history_tracking_for_table('data_source'::regclass,
get_history_table_name('data_source'::regclass));
SELECT drop_history_view_for_table('data_source'::regclass);
ALTER TABLE data_source
ADD COLUMN source_project_id int... |
14b565e37aa737473e2b6ca02809b43955d007b5afc60591ca4787bb6b3145fe | Python | 2,491 | 74 | from typing import Union, Any
from CybORG import CybORG
from CybORG.Agents.SimpleAgents.BaseAgent import BaseAgent
from CybORG.Shared import Results
class BaseWrapper:
def __init__(self, env: CybORG = None):
# wrapper allows changes to be made to the interface between external agents via specification of... |
2f52c6616fdbc2cf28d461a64eee1603b9841a5e8ef8bc283bc8fee3308e70f7 | Python | 2,491 | 55 | # run fit_gkr_models.py first
import os
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
from grid_cell.manifold_fitter import label_mesh
import grid_cell.ploter as ploter
import grid_cell.torus_geometry as tg
from grid_cell.util import remove_outliers, clean_and_mean_se, gram_schmidt, project_to... |
8fe280241f193e3cf78d01eb932004c4f12fe0e261eec2daabd772cce5a0b7fc | Python | 2,491 | 68 | import argparse
from pathlib import Path
import matplotlib
import pandas as pd
from plots_task1 import analysis_task1
from plots_task2 import analysis_task2
def main():
parser = argparse.ArgumentParser(description="Generate main figures")
parser.add_argument("source_data_dir", type=str, help="Input director... |
50d86f03c8f4aabd6601566ab13e12f7010d702414213e254d96445a25f6504a | Python | 2,494 | 84 | _base_ = [
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py',
'../_base_/datasets/ade20k.py'
]
# model settings
checkpoint_file = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/segnext/mscan_t_20230227-119e8c9f.pth' # noqa
ham_norm_cfg = dict(type='GN', num_groups=32, require... |
3ef90b1a615aaaefbfde2c2d62e9f2c8fad83f2777c15732b4acc2e44071d209 | Python | 2,495 | 74 | import torch
import pandas as pd
import joblib
import numpy as np
from params import (
num_workers, is_cpu
)
from data import read_config, CollateItems
from main import setup_pretraining
import soundfile as sf
datapath = './data/'
sfreq = 100
num_smooth = 3
# Test monolingual model with English sentence
# & bil... |
64ea8a08c5728dc46032d5dc37fce65546253c912b77eea8d461aa15cdf960be | Python | 2,498 | 51 | import os
def create_key(template, outtype=('nii.gz',), annotation_classes=None):
if template is None or not template:
raise ValueError('Template must be a valid format string')
return template, outtype, annotation_classes
def infotodict(seqinfo):
"""Heuristic evaluator for determining which runs ... |
88589a4f50b9aa178a83a4faa7a5a20823c1ada8921e0d3bee720997562fd66a | Python | 2,498 | 62 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional
from mmengine.optim.scheduler import PolyLR
from mmseg.registry import PARAM_SCHEDULERS
@PARAM_SCHEDULERS.register_module()
class PolyLRRatio(PolyLR):
"""Implements polynomial learning rate decay with ratio.
This scheduler adjusts ... |
f9fc9a897e22cdd6d84e5a513521286743d0d7534e3a64c63595c166d98ae94e | Python | 2,498 | 52 | import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=str, default='0',
help='gpu id, currently speculative inference only support single gpu')
parser.add_argument('--model', type=str, default='gpt2-xl',
... |
c726acdaf788ab57a72d03e97de7019d2f69e813800ea9610af60e09e9bbb9cf | Python | 2,499 | 65 | from selenium.webdriver.common.by import By
from ..base_page import BasePage
class BenchmarkDetailsPage(BasePage):
DATASETS_ASSOCIATIONS_BTN = (
By.CSS_SELECTOR,
"button[data-testid='datasets-associations-btn']",
)
DATASETS_ASSOCIATIONS = (By.ID, "datasets-associations")
MODELS_ASSOCI... |
36503448dd8adca4469dc2aeef835b5c53d3bace2860a4c7ffa093bdeffcb076 | Python | 2,500 | 65 | import os
import torch
import pandas as pd
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from models import model_attributes
from torch.utils.data import Dataset, Subset
class ConfounderDataset(Dataset):
def __init__(self, root_dir,
target_name, confounder_na... |
3e38eded1808697d77b20c730ba6b8928c60d206c567b808b66c4c1582a7a091 | Python | 2,501 | 88 | import os
from pathlib import Path
from typing import Any
from urllib.parse import urljoin, urlsplit
import pytest
import requests
from schema_salad.fetcher import Fetcher
from schema_salad.utils import CacheType
from cwltool.context import LoadingContext
from cwltool.load_tool import load_tool
from cwltool.main impo... |
84c2ce42cb49e81feb7fbccc3e032b11b071f120beb8514296722fb30fd82a91 | Python | 2,501 | 65 | """Verify NWB event extraction is unaffected by whether ``ndx_events`` has been imported.
``LabeledEvents`` is exposed by two different classes depending on the process-wide pynwb type
map: importing ``ndx_events`` registers the hand-written class (which stores its labels on
``.labels``), while leaving it unimported m... |
b9a431e19080dee6808f4c280d81f71d093fbf3c5a096034e495e0401fadbd45 | Python | 2,501 | 70 | # Build tile configuration for ImageJ/Fiji Stitching plugin
# Author: David Young, 2017
"""Builds the tile grid layout for the ImageJ/Fiji Stitching plugin.
Attributes:
OPTIONS_DIRECTIONALITY: direction of travel from one row to the next,
where "uni" = unidirectional, "bi" = bidirectional
OPTIONS_START... |
d0f8649e846ad3146d96ac1358696f6eef0a7975ecc426fd4f1e712cbb7d9386 | Python | 2,501 | 82 | import os
scaninfo_suffix = '.json'
def create_key(template, outtype=('nii.gz',), annotation_classes=None):
if template is None or not template:
raise ValueError('Template must be a valid format string')
return template, outtype, annotation_classes
def filter_dicom(dcmdata):
"""Return True if a... |
fe884622ed6ffaf21bbc16033753318670978f367db213ada501eb86a135d296 | Python | 2,501 | 56 | # run num_time_point_gp.py first
import numpy as np
import hickle as hkl
from grid_cell.ploter import error_bar_plot
import matplotlib.pyplot as plt
import os
from global_setting import *
#################### Hyperparameters ####################
mouse_name = 'R'
day = 'day1'
module = '2'
session = 'open_field_1'
pca_s... |
6a8cf43007158ba57c744ffe52d67a5c8c2671acc1ee8539fa0c10544cb76462 | Python | 2,502 | 64 | from __future__ import print_function, division
import os
import sys
import subprocess
def class_process(dir_path, dst_dir_path, class_name):
class_path = os.path.join(dir_path, class_name)
if not os.path.isdir(class_path):
return
dst_class_path = os.path.join(dst_dir_path, class_name)
if not ... |
d249ce229bfea20fdb4629a9b90802dcb71491628669ee80575228701cda2e11 | Python | 2,502 | 81 | # -*- coding: utf-8 -*-
from django.test import TestCase
class UtilTests(TestCase):
def test_is_collinear_diagonal(self):
from catmaid.util import Point3D, is_collinear
p1 = Point3D(-1.0, 1.0, 1.0)
p2 = Point3D(1.0, 2.0, 3.0)
p3 = Point3D(-2.0, 0.5, 0.0)
self.assertTrue(... |
f9bfa81c92d6d4b919377250cbd02cede2e6e8e8ab126517b3cb79d313e22dda | Python | 2,502 | 73 | """
Helpers for various likelihood-based losses. These are ported from the original
Ho et al. diffusion models codebase:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
"""
import numpy as np
import torch as th
def normal_kl(mean1, logvar1, mean2, logvar... |
2a408897e931a909cf345f7be3e842ac8fd4048c3f67875e34812a5306307624 | Python | 2,503 | 73 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from unittest import TestCase
import numpy as np
from mmengine import ConfigDict, init_default_scope
from utils import * # noqa: F401, F403
from mmseg.apis import RSImage, RSInferencer
from mmseg.registry import MODELS
class TestRSImage(TestCase... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.