sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
d0f7e6e14c36c66e9227fec98faf58f22ab199531fa5a5806cb45f1e437156c2 | Python | 2,138 | 68 | import numpy as np
from snntorch import functional as SF
import torch
from torch.utils.data import DataLoader
import nir
# NOTE: this requires snntorch/nir (PR) and nirtorch/master (unreleased)
from snntorch import import_nirtorch
import nirtorch
device = torch.device("cpu")
loss_fn = SF.ce_count_loss()
test_data_pa... |
779cef2617a187a1eacb69779232468f9f901445f6f76b51ad4b272c7b6c72ec | Python | 2,140 | 50 | #-----------------------------------------------------------------------------------------------------------------------------------------
# Author: Brandon S Coventry, Wisconsin Institute for Translational Neuroengineering
# Date: 04/02/2024 Wisconsin is literally having a snowstorm. D... |
dfe951521bf387d7b83edf0e928922adb9c482a6d5495bc061a50c4fdf61add5 | Python | 2,140 | 62 | from pathlib import Path
import numpy as np
import pyedflib
import epilepsy2bids.annotations
from epilepsy2bids.eeg import Eeg
import timescoring.annotations
import timescoring.scoring
def szDetection(edfFile: str, outFile: str):
"""Run a seizure detection algorithm on an EDF file.
The algorithm implemente... |
769cdf6346999d48791c194b0acec2f8c976cf57442662e40fdcbe4e03147883 | Python | 2,141 | 59 | # standard library imports
from abc import ABC
from typing import Any, Union, List, Tuple, cast
# third party imports
import numpy as np
from numpy.typing import NDArray
# project imports
from deepface.commons import package_utils
from deepface.modules.exceptions import InvalidEmbeddingsShapeError
# keras is importe... |
9f57d70310fc2879e018b9e6e63db9991b506408b9e99f1905d54aeb97b1e5ac | Python | 2,141 | 69 | """
Classification batch inference with Ray Data LLM.
Uses sequence classification models for content classifiers and sentiment analyzers.
"""
# Dependency setup
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "ray[llm]"])
subprocess.check_call(
[sys.execu... |
ae4c03b200f8b9abd30afb1a161d83412aa6808e1ad02379bfe6de1b06156637 | Python | 2,141 | 56 | # @String(value="This script renders a remote (e)SWC file (internet connection required)",visibility="MESSAGE") msg
# @String(label="URL to SWC file",description="Local files can also be loaded using a file URI (file:///absolute/path/to/file)",required=true, value="http://neuromorpho.org/dableFiles/de%20koninck/CNG%20v... |
3481d2c0efc58b59e5a9b0229c937d7e2ae6e9ed98578b2d4c65b8cd1f958113 | Python | 2,142 | 52 | import os
import pickle
from typing import List
import numpy as np
from matplotlib import colors
from matplotlib import pyplot as plt
from searchParams import *
from defaultParams import *
PATH = '/work/mohammad/5HT2A/simdata/fr-baseline-disrupt-balance-with-pert/'
FILENAME = 'gain_data'
FORMATS = ['svg', 'png']
os.... |
b99de48bf3b05e7da39fbba4e1106ffd780a8c3e61717e5c3d1df8ce87e50c48 | Python | 2,142 | 59 | import os
import sys
import torch
def softmax_helper_dim0(x: torch.Tensor) -> torch.Tensor:
return torch.softmax(x, 0)
def softmax_helper_dim1(x: torch.Tensor) -> torch.Tensor:
return torch.softmax(x, 1)
def empty_cache(device: torch.device):
if device.type == 'cuda':
torch.cuda.empty_cache()... |
21f352e996ac48890fe31e06c6a99e6f8dd689bace5938bf0794fc647bd5b997 | Python | 2,143 | 74 | """
This script zeros the T2w image (label files (SC seg, PMJ, ...)) below a specific intervertebral disc
(specified by "-x").
The script requires the SCT conda environment to be activated (because we import the SCT's Image class):
source ${SCT_DIR}/python/etc/profile.d/conda.sh
conda activate venv_sct
"""
im... |
5074840b7f93a37c174877917da438d66b1b8ff47501594b44ff155fe1e7eb30 | Python | 2,143 | 70 | # doc/source/serve/advanced-guides/multi-app-container.md downloads this
# file in a Dockerfile from its raw GitHub URL on master. Renaming or moving
# the file breaks that page.
# __serve_example_begin__
import requests
from io import BytesIO
from PIL import Image
import starlette.requests
import torch
from torchvis... |
914383b6fb20566a90afb28dc4bcea16680797bf57f633f5693c433272e62bd1 | Python | 2,143 | 50 | import os
import sys
import torch
import argparse
import torch_geometric.data as GeoData
from model import MQAModel
from torch_geometric.data import Batch
from tqdm import tqdm
from graphs import *
parser = argparse.ArgumentParser(description="Quality assessment model")
parser.add_argument('--input', type=str, help='T... |
b30f289ebd85e97777a30efbedb24dd21f45b116e1a285d2904cfcb418b206a4 | Python | 2,143 | 82 | """
Coordinates for accessing processing elements and memories in SpiNNaker2
TODO: it is not optimal that both WordAddr and ByteAddr are derived from int
The following condition is true: ByteAddr(11) == WordAddr(11)
"""
class WordAddr(int):
"""
Word address.
Each word consists of 4 bytes (32-bit)
"... |
bd34c1e331c5040eb52b217879ff8b0185ece64abe6ac655d46ac28baf212047 | Python | 2,143 | 57 | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... |
1b9d57d5c21f9516626a51a5eb12eaa8e2ce140f063f1ede6d0d6e9a95de8fbe | Python | 2,144 | 72 | # 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 writing, software
# distributed under th... |
34d3dd5ae1af0f5f10b3f3989f580bb49c0767a0d37bd9853743f0daf23ea412 | Python | 2,145 | 66 | import os
import subprocess
import sys
from typing import Dict, List
from ray_release.aws import get_secret_token
AWS_SECRET_TEST_PYPI = "ray_ci_test_pypi_token"
AWS_SECRET_PYPI = "ray_ci_pypi_token"
bazel_workspace_dir = os.environ.get("BUILD_WORKSPACE_DIRECTORY", "")
def _check_pypi_env(pypi_env: str) -> None:
... |
5e2c2442c82bccccb0fc557c37402bd4e617beeffdb9792d280037806c44cc7a | Python | 2,145 | 63 | # -*- coding: utf-8 -*-
"""Jax implementation of the positional encoding for coordinate-based neural networks.
This module heavily references from the following repository::
https://github.com/google-research/google-research/tree/master/jaxnerf
"""
from typing import Union
import jax.numpy as jnp
import jax
fro... |
e289c4735db1c9a8c4a21cc3c5cb1f84af63b2a4c3ddc4edb5c25e9ef9e26128 | Python | 2,145 | 58 | import argparse
import json
from os.path import join
import dask.dataframe as dd
import numpy as np
import xgboost as xgb
from utils import get_paths
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--cluster', type=str)
parser.add_argument('--logging_dir', type=str, default='c... |
49b47aab976d67d17caa09ba34eaf7a5349231094df135c5f713aa485ec9d8d1 | Python | 2,146 | 47 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
521938f205ca82fceb35a28fd0e94199efeac128beecd0e36bb88642a3087631 | Python | 2,146 | 71 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
For the selected k, use the sorting matrix to translate
the original clustering to the universal indices across k.
Output:
uni_subcent.h5 Universal index clustering.
Usage:
LE_group_stateclass.py <k>
Arguments:
<k> k for k-clustering
"""
import os, h... |
efc799c14440910efb2ee28f0004951ca311c5ca572bb26ff77f02ce3f405852 | Python | 2,146 | 65 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
493b017878e2d25736d9cebdf5ee373dd6d386a12944aed58ba9006dcfbed22c | Python | 2,147 | 69 | from itertools import product
from typing import List
from omegaconf import OmegaConf
import omegaconf.dictconfig
import omegaconf.listconfig
import time
timestamp = time.strftime("_%Y_%m%d_%H%M%S")
def omegaconf2list(opt,prefix='',sep = '.'):
notation_list = []
for k, v in opt.items():
k = str(k)
... |
54c578d60a0c83b71533f560624e552d52aeeea39052a86d4ced76b605817cda | Python | 2,147 | 75 | import moabbpatch
import moabbpatch.datasets
import moabbpatch.baseparadigm
moabbpatch.baseparadigm.physionet_rm_rest = True
import moabbpatch.mne_estim_output
import numpy as np
import pandas as pd
import mne
import moabb
import time
# to disable CSP output
moabb.set_log_level("WARNING")
mne.set_log_level("WARNING")
... |
9ba2843308bd89b475775995550d0cf3a22d38346ea58db6e147037746c0c1f3 | Python | 2,147 | 81 | from pathlib import Path
import pandas as pd
import pytest
from data_profiling.utils.compat import pandas_version_info
from data_profiling.utils.dataframe import (
expand_mixed,
read_pandas,
uncompressed_extension,
warn_read,
)
def test_read_pandas_parquet():
p = Path("dataframe.parquet")
wi... |
efb6f56b68a7e58c4546d5f7fe6c3cd3737926295e27f56615722c993dde99bb | Python | 2,149 | 68 | import great_expectations as ge
import pandas as pd
from data_profiling import ProfileReport
from data_profiling.utils.cache import cache_file
file_name = cache_file(
"titanic.csv",
"https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv",
)
df = pd.read_csv(file_name)
pr... |
e9ed25dded8822703cdd31f9a98c51035105fd94689005dc19a973e8a4e2afc8 | Python | 2,150 | 73 | """
import_cols_vals_thread
created as a component of Breathe Easy
***
Breathe Easy - an automated waveform analysis pipeline
Copyright (C) 2022
Savannah Lusk, Andersen Chang,
Avery Twitchell-Heyne, Shaun Fattig,
Christopher Scott Ward, Russell Ray.
This program is free software: you can redistribute it and/or mo... |
9dacdaeba49fb5ef65f1bcf9fd7b7ee7a778421fc65f49e9f50640c58ddc16ab | Python | 2,151 | 64 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Find the best iteration of k-medians clustering for each k. Values with lower
within-cluster sum of distance (WCS) scores are better.
Adapts code from:
https://github.com/adolphslab/HCP_MRI-behavior/blob/master/intelligence.ipynb
Output:
best_iter.csv For all ks, cont... |
a916797d1ca645422782dd2754d3f3cc2edc0a5f11c42273d540444b0cedf894 | Python | 2,152 | 50 | import h5py
import logging
import numpy as np
from typing import Dict
from ml4h.TensorMap import TensorMap, Interpretation
from ml4h.normalizer import Standardize
DNA_SYMBOLS = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
VARIANT_LABELS = {'NOT_SNP': 0, 'NOT_INDEL': 1, 'SNP': 2, 'INDEL': 3}
def tensor_from_hd5(tm: TensorMap, h... |
c2dfc423a13121293684d47a31f9f29065954293139e8b47f8ddf90e3eaed85f | Python | 2,152 | 59 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Union, Callable, List
class MM_PreappliedSpatialSingleCellLNPLoss(nn.Module):
def __init__(self,
timecourse_filter: Union[torch.Tensor, np.ndarray],
bias: Union[torch.Tensor... |
60d57277779eac4b59041259b7f5c881cedff26ea0a4fc300e592b17eb2b0597 | Python | 2,153 | 61 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
Simple tests for common structure generation helper functions.
"""
from __future__ import annotations
from fairchem.core.datasets.common_stru... |
214e31a3891b562c1930a3456dc8f174c2307985a0f7d0bf6cf7a09f7d507f45 | Python | 2,155 | 59 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
import pickle
from pathlib import Path
import pytest
from fairchem.core.scripts import download_large... |
3419b5675fe541a59ec758366600dc1de4b1729d02bda117e452fee4df2ecb2a | Python | 2,155 | 76 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
import ase
import ase.units as units
import numpy as np
from fairchem.data.oc.databases.pkls import ION... |
81411bc576a4acb5c922e3e9903a7ad4df6ac7669610660a727a0a417ae0d0ea | Python | 2,156 | 58 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
def calculate_version():
initpy = open('pmlb/_version.py').read().split('\n')
version = list(filter(
lambda x: '__version__' in x, initpy))[0].split('\'')[1]
return version
package_version = calculate_version... |
05e1c236292d51089ae8ad06f8f7784284d3b486e1b297f4a42f1b4765f34fbf | Python | 2,157 | 52 | import random
HEADERS_LIST = [
{
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Referer": "https://www.... |
b4a0bd984678ce96e2ed9c681086ded9858bf73551b9834f84ec8ff993dfe168 | Python | 2,157 | 74 | from __future__ import annotations
import threading
from typing import TYPE_CHECKING, Any, Optional
from .base import BundleQueue
if TYPE_CHECKING:
from ray.data._internal.execution.interfaces import RefBundle
class ThreadSafeBundleQueue(BundleQueue):
"""A thread-safe wrapper for a ``BundleQueue``.
De... |
260f53117392532f2bac6f547ca04324a080b7edb9b7e947b39aad43d1603778 | Python | 2,158 | 61 | # Copyright 2023 BioMap (Beijing) Intelligence Technology Limited
from .transformer import pytorchTransformerModule
from .performer import PerformerModule
from .mae_autobin import MaeAutobin
def select_module(config, sub_config, module_name):
if module_name == 'performer':
return PerformerModule(
... |
4f5539840a35da58475c14b3a5b34c645aa282fc841a8dfe6e387ff428959267 | Python | 2,158 | 67 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 19 12:04:56 2022
@author: sam
"""
#import keras
#from keras import backend as K
import numpy as np
def initialize_parameters(model,THETA,n_neuron,n_peptide,connectivity,sigmoid_measure=False):
from tools.lattices import WS_network
con_... |
965c44363b7700956d63d19ca5d18c737be72b3b402892f08cdbd7b9a99004fa | Python | 2,158 | 64 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#... |
2ca7fe52cc788638d3e932ec5311446581fc6d6c82c914244a4bc6cef8f01569 | Python | 2,159 | 61 | # dataset settings
dataset_type = 'lqit.URPCXMLDataset' # `lqit` means the scope
data_root = 'data/URPC/'
backend_args = None
train_pipeline = [
dict(type='LoadImageFromFile', backend_args=backend_args),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', scale=(1333, 800), keep_ratio=True)... |
4a28d0cd794785c593278f36c31ab0d7ecaa96d7225585890bc5281a3c426dd6 | Python | 2,159 | 81 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Rename variants & do final cleanup after complex resolution
"""
import argparse
import sys
from collections import defaultdict
import pysam
def rename(vcf, fout, chrom=None, prefix='SV_pipeline'):
indexes = defaultdict(int)
fmt = '{prefix}_{svtype}_{chrom}... |
5e4ed6df50aaf97dc41669c29796c6c738bfbf98a7890c4f60bf6ce145c56993 | Python | 2,159 | 68 | from .downstream import AnnotationHead, DenoisingHead, PerturbationPredictionHead, PatientClassificationHead, EmbedderHead, ImputationHead
# from .spatial import
from torch import nn
def setup_head(head_type, in_dim, hidden_dim, out_dim, num_layers, dropout, norm, batch_num) -> nn.Module:
if head_type == 'annotati... |
20e5fc869ab8052c2b580faaadfef013d52e296a8168f9217ef2d7f983c18a05 | Python | 2,160 | 75 | from __future__ import print_function
import torch.utils.data as data
import os
import random
import glob
from PIL import Image
from utils import preprocess
_FOLDERS_MAP = {
'image': 'leftImg8bit',
'label': 'gtFine',
}
_POSTFIX_MAP = {
'image': '_leftImg8bit',
'label': '_gtFine_labelTrainIds',
}
_DA... |
be268a86ae34c035de4f3f617cb7c6c31b4378c4807c0d7fcaabbee5648b9285 | Python | 2,160 | 71 | # Generated by Django 4.1.5 on 2023-05-30 01:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("infer", "0018_proteometask"),
]
operations = [
migrations.AddField(
model_name="proteometask",
... |
cff0e73501cedea7d22a9fcef5156e1a6b17c190a4881fe24380554acb0142e3 | Python | 2,160 | 54 | import pandas as pd
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
import numpy as np
models = ['bigru', 'bilstm', 'convgru', 'convlstm', 'fcn', 'gru', 'inception', 'lstm', 'resnet']
iteration = 'itr_12'
files = ["/train_total.csv", "/val_total.csv"]
list_r2, list_rmse, list_mae, list_wr... |
d06ecd8c2baedfd7d0f2d9cf327e7a54dbd095eb28ee4d16132fa5a937f4309c | Python | 2,161 | 102 | #!/usr/bin/env python3
# vim: set ts=4 sw=4 tw=0 :
import unittest
from tempfile import NamedTemporaryFile
import numpy as np
import cp2k
TEST_FILE_CONTENT = """
&FORCE_EVAL
METHOD Quickstep
&DFT
BASIS_SET_FILE_NAME BASIS_SET
POTENTIAL_FILE_NAME POTENTIAL
LSD
&MGRID
CUTOFF 140
&END MG... |
01b698b9ca498deb448872cb5e2e857cfdbfebde2e3cc17d1859892e21d67df7 | Python | 2,163 | 69 | import numpy as np
import scipy.sparse as sp
def load_dataset(file_name):
"""Load a graph from a Numpy binary file.
Parameters
----------
file_name : str
Name of the file to load.
Returns
-------
graph : dict
Dictionary that contains:
* 'A' : The adjacency mat... |
7ccfc2c989d285440551fa2f091561d42412140280a77665ca674431912c7353 | Python | 2,163 | 69 | # Generated by Django 4.1.6 on 2023-02-06 03:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Architecture",
fields=[
... |
9ee56257bb923d08eb89bd8d27573d553c8eecdaa2d0fea206c4de3a130326df | Python | 2,163 | 58 | ####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... |
622f5d579defbbb8606caf6f9b362ed5df825e6eb3b673708330183856d4a836 | Python | 2,164 | 70 | import os
import argparse
import numpy as np
"""Return the gridsearch run with the best validation accuracy"""
def get_run_dirs(path):
dirs = []
# loop through all directories in the given path
for dirpath, dirnames, _ in os.walk(path):
for dirname in dirnames:
dirs.append(os.path.jo... |
b6a7b29c1fff8604f12e47dcc93c74f35157a9442de19e53bff0ceb3c2c36c6b | Python | 2,164 | 52 | import random
import string
class DockerMetisServicesCmdFactory(object):
def __init__(self, container_name=None):
self.container_name = container_name
if self.container_name is None:
self.container_name = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + s... |
9bf6b431e458d50a20d5b49c88a27b02103a9488d326511e76842dca1c5a647e | Python | 2,165 | 62 |
import numpy
import os
import glob
class DatamapLoader:
"""
Creates a `DatamapLoader` that allows to iterate over a number of number
of datamaps that are stored in the `examples` folder in `npy` files.
"""
def __init__(self, structure=None, paths=None):
"""
Instantiates a `Datamap... |
469f6de7954c7c7aebfb5a29bb12e529e21fa1d6f13a708a918fa6a801938484 | Python | 2,167 | 75 | import exputils as eu
class BaseWidget:
@staticmethod
def default_config():
dc = eu.AttrDict()
dc.is_use_state_backup = True
dc.state_backup_name = None
dc.state_backup_variable_filter = None
return dc
def __init__(self, config=None, **kwargs):
... |
2145b7a20a77360a73f0ec17396846f30109ea1aefc7e804edf5d4623897df78 | Python | 2,168 | 48 | from collections import namedtuple
from configparser import ConfigParser
import numpy as np
# From parsing, return input with the correct type (e.g. boolean True from string 'True'
# or float 1.32 from string '1.32')
def evaluate_input_type(input):
if np.isin(input, ["all", "max", "min"]): # Case when ... |
6b177d4aa77cb52779e729f67f09ee1dbd1bda42457674f2516d4ca99beba797 | Python | 2,168 | 50 | import logging
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from agent.data.entities.config import DEV_LABEL
from agent.classifiers.evaluation.evaluation_mgmt import get_evaluation_measures
from agent.classifiers.utils.random_mgmt import set_random_seed
def tree_classifier(for_tas... |
af0d6b10dc8cfe8081eb7fc35f92ac83089d526b259a504bd56335e74b375672 | Python | 2,169 | 63 | import torch
from ..utils import common_functions as c_f
from ..reducers.base_reducer import BaseReducer
from ..reducers.mean_reducer import MeanReducer
def aggregation_func(x, num_per_row):
zero_denom = num_per_row == 0
x = torch.sum(x, dim=1) / num_per_row
x[zero_denom] = 0
return x
class PerAnch... |
4ea34ee2be37e9a7c2d7863c02996d2ee5c2c6b281e4b3d50ca54e54dd51b661 | Python | 2,170 | 61 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 28 13:52:04 2022
@author: joern
"""
# %% imports
import pandas as pd
import numpy as np
import copy
from sklearn.preprocessing import StandardScaler
from box_and_heatplots import box_and_heatplot
from explore_tukey_lop import explore_tukey_lop
fr... |
664c8b65f294b591f8f13f8d86a02fb33209ce8dd3686ca65570c5bd6a55e8db | Python | 2,171 | 61 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Implementation of SFNet DFNet series.
# Author: Xiangtai Li(lxt@pku.edu.cn)
# Date: 2020/7/1
import torch.nn as nn
from network.dfnet import DFNetv1, DFNetv2
from network.sfnet_resnet import UperNetAlignHead
from network.nn.mynn import Norm2d, Upsample
class AlignNetDF... |
13bdee3d4e8238d363bb97b4341fddfc0a05e6d8228b64609ca94db252197710 | Python | 2,172 | 60 | import torch
import numpy as np
import matplotlib.pyplot as plt
from BioMime.utils.params import coeff_r_a, coeff_r_b, coeff_fb_a, coeff_fb_b, coeff_a_a, coeff_a_b, coeff_iz_a, coeff_iz_b, coeff_cv_a, coeff_cv_b, coeff_len_a, coeff_len_b, w_amp
def generate_emg_mu(muaps, spikes, time_samples):
"""
Args:
... |
d15e820c39105ab40385f99852ec6976665f3536bab68c4f1fb7eced005f499f | Python | 2,172 | 49 | #!/usr/bin/env python3
import numpy as np
import random
from scipy.ndimage import rotate
def simulate_noise(params):
def rt(inp):
np.random.seed(random.randint(0,100000))
(angle,size) = inp
b = np.random.normal(size=(size,int(size*1.4))).astype(np.float32)
b = np.repeat(b[np.newaxis,... |
403ac5939b702fa1a3410b274606f2b6c4e8577af8b078181b2e396203a7cc5d | Python | 2,173 | 71 | import basetest_dqn_like as base
import pytest
from basetest_training import _TestBatchTrainingMixin
from pfrl.agents.dpp import DPP, DPPL, DPPGreedy
def parse_dpp_agent(dpp_type):
return {"DPP": DPP, "DPPL": DPPL, "DPPGreedy": DPPGreedy}[dpp_type]
@pytest.mark.parametrize("dpp_type", ["DPP", "DPPL", "DPPGreed... |
9942f7e26de1ae0df7ed279a016bae061fca9cc939879bdf0eced5daf82452ca | Python | 2,173 | 68 | # state_manager.py
import streamlit as st
import getpass
from typing import Any, Dict
from config_manager import ConfigManager
from rate_limiter import RateLimiter
from query_cache import QueryCache
DEFAULT_STATE: Dict[str, Any] = {
"ollama_ready": False,
"models_installed": False,
"query_history": [],
... |
c14e1c6aca46778895f41f5c8f81ac3efe1443a974346ce866a5b656a9003e6c | Python | 2,174 | 62 | from torch import optim
from lop.algos.convGnT import ConvGnT
import torch.nn.functional as F
from lop.utils.AdamGnT import AdamGnT
class ConvCBP(object):
"""
The Continual Backprop algorithm
"""
def __init__(self, net, step_size=0.001, loss='mse', opt='sgd', beta=0.9, beta_2=0.999, replacement_rate=0... |
e13270d9bda2d15d408fe9755870ac06914f6152466b867c3c2856b50462b1ee | Python | 2,174 | 68 | """
15/03/23: getting finetuning to work
"""
import random
# small test dataset
def tokenize_data(inputs):
"""
ESM needs input_ids, attention_mask, labels, position_ids
"""
tinputs = tokenizer(inputs['tokens'], add_special_tokens=False, truncation=True, is_split_into_words=True)
tinputs['labels'] =... |
1109bf50adb8deaef4a291cc5400e57d27b013ddbec637ef2ebe5ba74f515d19 | Python | 2,175 | 69 | import json
import os
import sys
import pytest
import ray
from ray._common.test_utils import wait_for_condition
from ray._private.test_utils import wait_until_server_available
from ray.dashboard.tests.conftest import * # noqa
os.environ["RAY_enable_export_api_write"] = "1"
os.environ["RAY_enable_core_worker_ray_eve... |
2810545b1dc9a3a55bf67b749a680737161adba428b86f34c5177eb8284ff2d2 | Python | 2,176 | 71 | import torch
def tuple_cat(*args, dim=-1):
'''
From https://github.com/drorlab/gvp-pytorch
Concatenates any number of tuples (s, V) elementwise.
dim: dimension along which to concatenate when viewed
as the 'dim' index for the scalar-channel tensors.
'''
dim %= len(args[0][0].... |
616bd82135f25331e926829497f6c605d54ec6fc299079a1956b820a83c7bc46 | Python | 2,176 | 72 | import logging
import requests
from os.path import exists, join
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from agent.data.entities.config import ROOT_LOGGER_ID, RAW_DATA_PATH
from agent.crawlers.utils.random_h... |
7bffca32f327ee9ee9d0d2758ec348e7b3b5d0348e8bd577dfebbb6188b93db9 | Python | 2,177 | 63 | import numpy as np
import matplotlib.pyplot as plt
from lib5c.util.plotting import plotter
@plotter
def plot_fdr(eval_results, labels, colors=None, p_alt=None, **kwargs):
"""
Plots an FDR control curve from a list of ``eval.npz``-style results.
Parameters
----------
eval_results : list of dict-l... |
8c443864bc946b6657512fed74d3ec05e774e4f2fa702945a579b71658bdbef6 | Python | 2,177 | 53 | """
endstate_correction
Endstate correction from MM to NNP
"""
import sys
from setuptools import setup, find_packages
import versioneer
short_description = "Endstate reweighting from MM to NNP".split("\n")[0]
# from https://github.com/pytest-dev/pytest-runner#conditional-requirement
needs_pytest = {"pytest", "test", ... |
13657d5358c834b5bddbbc1bfaf7bedfeea6df62a7741f82c468392043af9528 | Python | 2,179 | 63 | """Documentation example and CI test: custom vLLM model via a YAML config.
Structure:
1. Test-only setup: force serve.run non-blocking and strip accelerator
requirements for CI. The plugin is baked into the cluster image, and direct
streaming is enabled through the cluster environment.
2. Load the YAML config an... |
300778e8243f33115d03c4fe9b4dbf5b5e67fb99bc6710e4288c7843d4c0853e | Python | 2,179 | 75 | import os
import tempfile
from pathlib import Path
import flyvis
def test_default_root_dir():
"""Test that the default root directory is correctly set relative to the package."""
# Clear any existing FLYVIS_ROOT_DIR environment variable
if "FLYVIS_ROOT_DIR" in os.environ:
del os.environ["FLYVIS_R... |
74eb93ddebcbea9525f221f3d727336ffca838a799434587945dc97d22fada9d | Python | 2,179 | 62 | # import the main libraries required for the preprocessing
import pandas as pd
from pathlib import Path
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
from technical_validation_utils import bids_root
# UPDRS filename
updrs_on = Path(bids_root) / 'participan... |
487927c81045f54ea2062396205bf17d8bec1e7091963627deedc4fbc458bd35 | Python | 2,180 | 77 | _base_ = [
'../../_base_/datasets/urpc2020/urpc2020-test-A_coco_detection.py',
'../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(
type='FCOS',
data_preprocessor=dict(
type='DetDataPreprocessor',
mean=[102.9801, 115.9465, 122.7717]... |
51c5f1d41f5e370e874f90d34f466371663b50006a2f7151ab1c957d6d797061 | Python | 2,180 | 43 | from model import (IntraEncoder, InterEncoder, ProteinInteractionNet, Tester)
from uncertaintyAwareDeepLearn import VanillaRFFLayer
from utils import (
load_configuration,
set_random_seed,
get_computation_device,
evaluate
)
import torch
def main():
# --- Pre-Training Setup ---
# Load configs. U... |
c0bbe55a0f1403ae85d47a944695cfb77caddc693bf7f96eb3e6516aa6356e5c | Python | 2,180 | 77 | _base_ = [
'../../_base_/datasets/urpc2020/urpc2020-test-B_coco_detection.py',
'../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(
type='FCOS',
data_preprocessor=dict(
type='DetDataPreprocessor',
mean=[102.9801, 115.9465, 122.7717]... |
292495fd3cdc54089e0fe262147a763a8a16772b28234f90f29a8c0abb92b7fb | Python | 2,181 | 81 | # 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... |
3648da39032b67bb8b6533bc527d601e51bd7a2c59ce2ec08e1fcbf796cc70ea | Python | 2,181 | 43 | from model import (IntraEncoder, InterEncoder, ProteinInteractionNet, Tester)
from uncertaintyAwareDeepLearn import VanillaRFFLayer
from utils import (
load_configuration,
set_random_seed,
get_computation_device,
evaluate
)
import torch
def main():
# --- Pre-Training Setup ---
# Load configs. U... |
5972066c5f33bcec7f4fc16c3d8765c74d9a79513a263a0837ca947153629d66 | Python | 2,181 | 66 | # stdlib dependencies
from typing import Any, List, Union
# 3rd party dependencies
import numpy as np
from numpy.typing import NDArray
# project dependencies
from deepface.models.demography.DemographyUtils import find_apparent_age
from deepface.models.demography.onnx.OnnxDemography import OnnxDemography
from deepface... |
c0d06efacd7068958b2116f5c5f6e762131646ec02bc16bee5123798c70c154a | Python | 2,181 | 68 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Utilities for inference."""
from typing import Optional, TYPE_CHECKING
from torch.nn import Module
from aihwkit.exceptions import ModuleError
if TYPE_CHECKI... |
543f9498ffdb45e072d88a03b1495ffbaf660f86beb80da41d50900c7d13ff8d | Python | 2,183 | 57 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import numpy as np
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
import pandas as pd
i... |
ce598b89700e502cb4cb3b759911dd7f41e4705b5a8206b446b93ed88a4a34e1 | Python | 2,183 | 64 | #!/bin/env python
import argparse
import pysam
import sys
from typing import Optional, List, Text
def __parse_arguments(argv: List[Text]) -> argparse.Namespace:
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(
description="Extract FORMAT field values from VCF to TSV table.",
for... |
6bbf85056a52829b327f2988d9ecb9fb1ecf369da36c03a11c1261366d64888b | Python | 2,184 | 77 | _base_ = [
'../../_base_/datasets/urpc2020/urpc2020-validation_coco_detection.py',
'../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(
type='FCOS',
data_preprocessor=dict(
type='DetDataPreprocessor',
mean=[102.9801, 115.9465, 122.7... |
2bfbec46a33b8f5a812d1a039e788f9edd905920c9f3bbc24a5b98f910d8c51c | Python | 2,185 | 69 | """Extract local maxima from a spm.
Return a csv file with variables:
- x-axis array index (i)
- y-axis array index (j)
- z-axis array index (k)
- peak z-value
- peak p-value
"""
import itertools
import numpy as np
import pandas as pd
def PeakTable(spm, exc, mask):
"""Identify local maxima above z-value thres... |
b3ce197da006789264070a98a820e816962db9c96932ca85ba07ba48b9e938ae | Python | 2,186 | 79 | import numpy as np
from scipy.signal import find_peaks
def get_relevant_data(
kernel_data: np.ndarray,
time_array: np.ndarray,
tmin: float,
tmax: float,
channel_indices: list
) -> tuple[np.ndarray, np.ndarray]:
""" Get the relevant data from the kernel.
Parameters
... |
bf3d09f5330ef94e97cc6697798ff2e07af5b8669fe070ab57520fd73e1c1118 | Python | 2,186 | 68 | import glob
from struct import unpack
#Used Yasoob's script. https://yasoob.me/posts/understanding-and-writing-jpeg-decoder-in-python/
marker_mapping = {
0xffd8: "Start of Image",
0xffe0: "Application Default Header",
0xffdb: "Quantization Table",
0xffc0: "Start of Frame",
0xffc4: "Define Huffman ... |
17b9265996c86fb5f22e02e7ff588a893f703842111073d3a8a4b4429bd7be59 | Python | 2,187 | 59 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import torch
def gauss_kernel(size=5, channels=3):
kernel = torch.tensor([[1., 4., 6., 4., 1],
[4., 16., 24., 16., 4.],
... |
75c785b41ba9dd2ce92c204dd99638c263743456c374e4a54d0acd2fbba10913 | Python | 2,187 | 65 | import os
import pytest
import requests
from data_profiling.controller import console
from data_profiling.utils.paths import get_config
NASA_URL = "https://data.nasa.gov/docs/legacy/meteorite_landings/Meteorite_Landings.csv"
@pytest.fixture
def console_data(get_data_file):
try:
return get_data_file("me... |
d4a53d12581d0ec55537f89f792fe8e855fff3a1738edd058ce3dd6664e50c4b | Python | 2,187 | 50 | """GPU non-parametric UMAP — a torch twin of umap-learn / scanpy CPU UMAP.
This package re-implements the *non-parametric* UMAP embedding optimisation
(umap-learn 0.5.7 ``simplicial_set_embedding`` + ``optimize_layout_euclidean``)
in PyTorch with GPU acceleration. It exists because omicverse's previous
GPU/"mixed" UMA... |
f895e71d202953e9fffb735e9d7274a0b0bb91a5357fd8b22a4a7588b7857947 | Python | 2,187 | 52 | import pickle
from typing import List
from matplotlib import colors
from matplotlib import pyplot as plt
from searchParams import *
from defaultParams import *
PATH = '/work/mohammad/5HT2A/simdata/fr-baseline-disrupt-balance-with-pert/'
FILENAME = 'diff_data'
FORMATS = ['svg', 'png']
os.makedirs('figs', exist_ok=Tru... |
2ab6310b651d7e3ff61473db1d1945ca081ad047454be72720798006d0021add | Python | 2,188 | 56 | # -*- coding: utf-8 -*-
"""
PMLB was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- William La Cava (lacava@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- and many more generous open source contributors
Permission is hereby granted, free of charge, ... |
c4f6723efc8c0698e08b21e8b1f441b6353157b67438417d0ad7de41ba520573 | Python | 2,190 | 53 | import argparse
from modules.module_reg_attngan_dpm import GAN
from pytorch_lightning import Trainer
from pytorch_lightning.utilities.parsing import AttributeDict
import os
# Configure environment for GPU usage
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
class Tes... |
d5b530117616548440440043a9488638e02c4d143180344587c607c38ba18a48 | Python | 2,190 | 55 | # CanonicalBase.py
# Copyright (c) 2010 Jes Frellsen
#
# This file is part of Muninn.
#
# Muninn is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Muninn is distributed in the hope that it will be ... |
0723ba4ee6646036ca550d4d1920ab8ea802a2100c3da4993d9604c9f6b073ac | Python | 2,191 | 87 | #!/usr/bin/env python
"""
Collect SR file metrics. Writes stats to stdout.
Metrics:
sr_left_<sample> : number of left records
sr_right_<sample> : number of right records
If the provided sample list has more than one id, <sample> will be "_merged".
"""
import gzip
import argparse
import sys
import svtest.utils... |
8a080431630e1debff8fc05f43732d77aa09b9838ac84b1b08d4546db0e3a0db | Python | 2,191 | 71 | #!/usr/bin/python
"""Auxiliary functions for scdemon."""
# --------------------------------------------
# Auxiliary functions
# Updated: 06/28/21
# --------------------------------------------
import pandas as pd
import numpy as np
import scanpy as sc
import logging
def vcorrcoef(X, y):
"""Vectorized correlation,... |
606f45c092c0bc99417e1952b3903fafa478bb2769a70e3be594117ff51a8dc5 | Python | 2,192 | 92 | import numpy as np
def test_prepare_abi_connectivity_maps():
from samri.fetch.local import prepare_abi_connectivity_maps
prepare_abi_connectivity_maps('ventral_tegmental_area',
invert_lr_experiments=[
"127651139",
"127796728",
"127798146",
"127867804",
"156314762",
"160539283",
"160540751",
... |
51e87822e2956c1d8b01cf670af0ec661731790b9b024928e87ce9ae11541bea | Python | 2,193 | 51 | import math
from typing import TYPE_CHECKING
from .autoscaling_actor_pool import AutoscalingActorPool
from .default_actor_autoscaler import DefaultActorAutoscaler
if TYPE_CHECKING:
from ray.data._internal.execution.streaming_executor_state import OpState
class BacklogAwareActorAutoscaler(DefaultActorAutoscaler)... |
7d7a78271ce563a3ff7c7ee903179e2e565234e2e36c9ae862bdb6e6cbc36e9a | Python | 2,193 | 74 |
def load_tokenizer(vocabulary_file):
with open(vocabulary_file, 'r') as f:
vocabulary = f.read().splitlines()
tokenizer = Tokenizer(vocabulary)
return tokenizer
class Tokenizer:
def __init__(self, vocabulary):
""" あr
Parameters
----------
vocabulary: array_like ... |
a9c36bed15a483d3e8e96610813e6663b36625523b22a64e40a983c3e701ecd1 | Python | 2,193 | 62 | from siapy.datasets.schemas import TabularDatasetData
from siapy.datasets.tabular import TabularDataEntity, TabularDataset
from siapy.entities import Shape, SpectralImage, SpectralImageSet
def test_tabular_len(spectral_tabular_dataset):
dataset = spectral_tabular_dataset.dataset
assert len(dataset) == 3
def... |
28e229581ee3aec65c30cfec63448f346445aab6807a8a8b4892d9ba06bfe865 | Python | 2,194 | 70 | from IsoNet.models.unet import builder,builder_fullconv,builder_fullconv_old,build_old_net
from tensorflow.keras.layers import Input,Add,Activation
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
def Unet(filter_base=32,
depth=3,
convs_per_depth=3,
kernel=(... |
41cb38ee2bff1898713569343625b49ede8bcb571c25ad8984e18778fbe57027 | Python | 2,195 | 69 | import numpy as np
import scipy.special as special
from .basic_distributions import Distribution
from ... import config
class Gamma(Distribution):
"""
Class to define Gamma distributions
Equations:
p(x|a,b) = (1/Gamma(a)) * b^a * x^(a-1) * e^(-b*x)
log p(x|a,b) = -log(Gamma(a)) + a*log(b) + (a-1)... |
4526632ea1b30ab0932642ca6258ba76f885c054a5236c144246c7dd6c3c265b | Python | 2,195 | 62 | """
This file serves as a documentation example and CI test for the direct
streaming YAML config.
Structure:
1. Load the YAML config shown in the guide and convert it to an app with
build_openai_app, removing accelerator requirements for CI testing.
2. Test validation (deployment status polling + cleanup).
Scope: ... |
ae6fbaac4ecddcd9c36948211d3a58a7faf9ddac395074069d1e833d8e06df38 | Python | 2,195 | 48 | # Case 2: courtship conditioning — recursive writing of C, Φ_N on the write step
import numpy as np, json, sys
from scipy.optimize import minimize
rng=np.random.default_rng(21)
NT,NS=60,20
GROUPS=["WT naive","WT trained","DopEcR-training","DopEcR-test trained","DopEcR-test naive","Interrupted"]
def design(n=30):
G=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.