sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
2c63f405bb7dd4e535fd6cc3db7b6f401256cc074dcd11b2bebf35ede7fcd633 | Python | 1,981 | 60 | 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... |
6fedc5d1f9d4e74e58ca6cd3d1d359331f6701a01e537626ff30827fe791a824 | Python | 1,981 | 43 | """Per-CTA TMA descriptor copies that bound ragged loads by a sequence end.
A load warp copies a TMA atom's descriptor into its CTA's 128-byte workspace slot, rewrites the
rows extent to the sequence end, and acquires the rewrite before loading through it: rows at or
past the end then arrive zero-filled from a bounded... |
cd6fff11369ead7b1c76107a503ca6e10d5870ae2afb133827e2c73634f58503 | Python | 1,981 | 59 | from pl_bolts.utils import _TORCHVISION_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
if _TORCHVISION_AVAILABLE:
from torchvision import transforms
else: # pragma: no cover
warn_missing_pkg("torchvision")
def imagenet_normalization():
if not _TORCHVISION_AVAILABLE: # pragma: no cover
... |
7a14cae95035f19370246d310cfd9cc424e9c7eef7d2e79f562d86e3fbd7f2fb | Python | 1,982 | 64 | """Config management."""
import argparse
from pathlib import Path
import inspect
from datetime import datetime, timezone
from hydra.experimental import initialize_config_dir, compose
from omegaconf import OmegaConf, DictConfig
def init_hydra_cfg() -> DictConfig:
"""Initialize Hydra config."""
parser = argp... |
bdb16bf645ac5ac898c0b79747735d3a43b70a256aee85a1cde08f303b19d2ca | Python | 1,982 | 63 | from typing import Literal
try:
from fs.azblob.blob_fs import BlobFS
from fs.azblob.blob_fs_v2 import BlobFSV2
except ImportError:
BlobFS = None
BlobFSV2 = None
from galaxy.files.models import (
BaseFileSourceConfiguration,
BaseFileSourceTemplateConfiguration,
FilesSourceRuntimeContext,
)... |
6d0a6ef129e962c795acc9c539e96ec264bd954ac40b8fecd9681d9de095963c | Python | 1,983 | 66 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
b2d0d1f44ee04fc2d157af9bc4d85bac65cd506767d4c1e592372aa86c779424 | Python | 1,983 | 69 | import torch
import torch.nn as nn
from modular_splicing.models.modules.final_layer.final_processor import FinalProcessor
from modular_splicing.utils.construct import construct
from modular_splicing.models.modules.lssi_in_model import BothLSSIModels
class SplicepointBasedBranchSitePredictor(nn.Module):
def __ini... |
f1dcc1b82f232b64c9f2f5a564bcb772b5fe6e9b32548f2780265c345f901ccc | Python | 1,983 | 57 | 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
from model_multicaps import Multicaps
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# tf.config.threading.set_intra_op_parallelism_threads(5)
tf.config.thre... |
f5474f3b6a421f312047c1b63ecbadd728e3ed657cdb42315b39a979ff5fdb21 | Python | 1,983 | 43 | import tensorflow as tf
from keras.src.export.saved_model_export_archive import (
BaseSavedModelExportArchive,
)
class SavedModelExportArchive(BaseSavedModelExportArchive):
"""TensorFlow backend implementation of SavedModel export archive."""
def _backend_track_layer(self, layer):
# Unwrap Keras... |
2f10c33f1d3b9f7e2e1e54141351f3c196f0889b90f56a9edf4e6b3f81e5d52d | Python | 1,984 | 63 | """
=================================
Functional Connectivity Helpers
=================================
This file contains helper functions for the functional connectivity example
"""
from sklearn.base import clone, BaseEstimator, TransformerMixin
from sklearn.ensemble import StackingClassifier
from sklearn.metrics ... |
a581f4c910c544328b7140ce65fa3b3c0399f0981d5079ea02b09359427d463c | Python | 1,984 | 86 | from datetime import datetime
from datetime import UTC
from uuid import uuid4
import pytest
from markupsafe import Markup
from flask.json.tag import JSONTag
from flask.json.tag import TaggedJSONSerializer
@pytest.mark.parametrize(
"data",
(
{" t": (1, 2, 3)},
{" t__": b"a"},
{" di": ... |
ad8cef18b311f82ac0d63f12a4356eada0cc9235237ecfe5b61fc6053cf121a4 | Python | 1,984 | 60 | 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... |
c03c1b38448c91af6ef8795ee8a3170ce87d389b6d68261752381e3d39e878e6 | Python | 1,984 | 61 | """Visualize network structure"""
import tempfile
try:
import graphviz
except ImportError:
graphviz = None
import mxnet as mx
from mxnet import gluon
def plot_network(block, shape=(1, 3, 224, 224), save_prefix=None):
"""Plot network to visualize internal structures.
Parameters
----------
block... |
10a71a6db5b4e0259bcef969d4020a9e4c282a8355d66233307742bd14dba26f | Python | 1,985 | 62 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# 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://... |
5d0dcb92d5db3b140e6a592415d83dca059a2afff48f19876265b12f62917b3a | Python | 1,985 | 53 | import importlib.resources
from PyQt6 import uic, QtWidgets
from . import export
class ExportDialog(QtWidgets.QDialog):
_instance_counter = 0
def __init__(self, parent, fdist_list, identifier, *args, **kwargs):
"""Base class for force-indentation analysis"""
super(ExportDialog, self).__init... |
276672b6817384ebb1733be13ea798d5e204e1193bcdb3c452d389fccf392e3f | Python | 1,987 | 60 | import h5py
import numpy as np
class DatasetAligner:
"""
Class for aligning a dataset to a datafile.
Used to find the correct gene and position within gene for a given
chunk and within-chunk index in a dataset.
Effectively, undoes the binning done in `create_dataset.py`
"""
def __in... |
f6e400aecdd7e2ecad06bff490ffb101d5524fb1a159cbbdfc9c54dba870edc3 | Python | 1,987 | 72 | '''The functions of the reg submodule are made available in the wormbrain.reg
namespace.'''
import numpy as np
import wormbrain
from wormbrain.match import pairwise_distance
def centroid(A,B,**kwargs):
'''Simple registration in which the pointset B is shifted so that its
centroid overlaps with the centroid ... |
3f2f3dd4084ab112361b22dbfce5c10db12d28e9229db7e094b579928cc5c781 | Python | 1,988 | 59 | """Tests for specparam.results.params."""
import numpy as np
from specparam.results.params import *
###################################################################################################
###################################################################################################
## ComponentPara... |
7dd4dd8e7ef4da2de2a3153ad8b5f83bebc960f9cedc01607cbd23e211ffd29c | Python | 1,988 | 61 | # Copyright 2023 DeepMind Technologies Limited
#
# 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 agree... |
f58c1eff1ff11208c0bd4912998c2bf25755160dbc09ed40084994249652a02f | Python | 1,988 | 66 | from .sh_ellipse import Ellipse
class Circle(Ellipse):
def __init__(self, x=33., y=10., r=23., phi=0, point_um=1):
"""Circle
Parameters
----------
x, y: float
center coordinates [pt]
r: float
radius of the sphere [pt]
phi: float
... |
253c87b6e440d484bdd90a74c18eb6274761218c2ce4819a2683e1f61693d053 | Python | 1,989 | 44 | """Alexnet, implemented in Gluon.
Code adapted from https://github.com/STVIR/pysot"""
# coding: utf-8
# pylint: disable=arguments-differ,unused-argument
from __future__ import division
from mxnet.gluon import nn
from mxnet.gluon.block import HybridBlock
from mxnet.context import cpu
class AlexNetLegacy(HybridBlock):
... |
69fdd20d543bf8507c6852b0705c1ba2968cab1190914198e511f8dd2b05946a | Python | 1,989 | 62 | 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
# Make a custom build script for audio_rep_training_cochleagram_1/l2_p1_robust_training
def build_net(ds_kwa... |
6e90b06555552e685bdbf44cf5f1c04c2e4f73272267210b0376e42e78ba54d2 | Python | 1,989 | 79 | from scipy.stats import mannwhitneyu, normaltest, ttest_ind_from_stats
def find_pairs(data):
"""Find all possible pairings in data"""
return [(a, b) for idx, a in enumerate(data) for b in data[idx + 1:]]
def format_p_value(p_value):
"""Formats a provided p-value into asterisks"""
if p_value < 0.001:
... |
f2be13c49a7b9d7f7dce86e862bb8f66bc38f532585baea7f3b3e8bcc360e8c2 | Python | 1,989 | 58 | #coding=utf-8
# Copyright (c) 2020 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 requ... |
1bd6326e262e5dd1531825032a1b0d793566e1b6ac83e235efe8a3716a63d19a | Python | 1,990 | 50 | #!/usr/bin/env python3
import numpy as np
import read_data as rd
"""
Dec-16-2021 by Guo Jiahui and Ma Feilong
This script contains functions and examples to compute noise ceilings (Cronbach's alphas).
Run this script directly to see the example output.
"""
def cronbach_alpha(X):
n_items = X.shape[0]
alpha... |
2febda047df94dd84f372546fbe1ecd217ccdada91bc1a1b96b0a0705bbeb145 | Python | 1,990 | 68 | from .shuffler import shuffler_types
from modular_splicing.utils.construct import construct
class FastIter:
"""
Shuffle the data chunks and then shuffle the contents of each data chunk.
Fast, for training. Not ideal for when you want a real random sample.
"""
def __init__(self, shuffler_spec):
... |
d3ac4cad9602ecd0292225e582cb9b97b7d8a66b26d320a5e33739529d885792 | Python | 1,990 | 59 | # Test preprocessor functionality
# TODO save / load
from pathlib import Path
import pandas as pd
import pytest
from polyid import MultiModel, Parameters
from polyid.models import global100
from polyid.preprocessors import PolymerPreprocessor, WeightDiscPreprocessor
pwd = Path(__file__).parent
def test_quantile_pre... |
69e28b0e080aab0d9c95a844382736acd813e866d1775509e97c2d72dc762ede | Python | 1,993 | 55 | from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
)
from galaxy.exceptions import RequestParameterMissingException
from galaxy.model import (
DatasetCollectionElement,
HistoryDatasetAssociation,
)
from ..types import BaseDatasetCollectionType
if TYPE_CHECKING:
from . import Data... |
a4bd61c6b4b14a6f7682589fe46dc9f0b784bf91913d566bd833640e4a96c30f | Python | 1,993 | 56 | import numpy as np
from impose import formats
from helpers import retrieve_data
def test_load_bmlab_brillouin():
paths = retrieve_data("fmt_brillouin-h5_bmlab-session_2022_water.zip")
data, meta = formats.load(paths[0])
# check metadata
assert meta["pixel size x"] == 1
assert meta["pixel size y... |
a3d7ae901f48703e4107c7810ef197db9f50e70ef282be60ccf30301f3d087f4 | Python | 1,994 | 71 | """
Processes datasets for different acceleration factors
author: obanmarcos
"""
from config import *
from concurrent.futures import process
import os, sys
# Where am I asks where you are
sys.path.append(where_am_i())
dataset_path = where_am_i("datasets")
import argparse
import numpy as np
import matplotlib.pyplot as... |
0805cddfae1edecdfe13b791f0c1f38025ef82130090420822c682ec91a7b548 | Python | 1,995 | 55 | import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torch import nn
from torch import optim
from NNucleate.dataset import GNNTrajectory_mult
from NNucleate.models import GNNCV_mult
from NNucleate.training import train_gnn_mult, evaluate_model_gnn_mult
device = "... |
379ca4fdd7db8fdbbf17c6f1f31122547e6095a1a13a3b034aba307cb3c6f103 | Python | 1,995 | 62 | import unittest
import numpy as np
from bdpy.util.math import average_elemwise
class TestMath(unittest.TestCase):
def test_average_elemwise(self):
a = np.array([1, 2, 3])
b = np.array([9, 8, 7])
ans_valid = np.array([5, 5, 5])
ans_test = average_elemwise([a, b])
np.testi... |
8683e2647c8fdbc35fee0538b2c67e7729893859e87a4d912dd85ca98b3f96fb | Python | 1,995 | 67 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(
type="BothLSSIModels",
acceptor="model/splicepoint-model-acceptor-1",
donor="model/splicepoint-model-donor-1",
)
msp.architecture["motif_model_spec"]["motif_... |
ba514e8e8c7e6f542f43cc05a59ec814ff93c8406291b90e7a2c7866b763acab | Python | 1,995 | 67 | from sys import argv
from msp import MSP
msp = MSP()
msp.file = __file__
msp.seed = int(argv[1])
msp.architecture["splicepoint_model_spec"] = dict(
type="BothLSSIModels",
acceptor="model/splicepoint-model-acceptor-1",
donor="model/splicepoint-model-donor-1",
)
msp.architecture["motif_model_spec"]["motif_... |
e725c57f6ec2e538d218a8ee8cca54523e2e4823b1723b58fe740e2298b1221e | Python | 1,995 | 48 | import numpy as np
def slice_array(array, start, length, dim):
"""
Slice a NumPy array on a specified dimension.
Parameters:
array (np.ndarray): The NumPy array to be sliced.
start (int): The starting index for the slice.
length (int): The length of the slice.
dim (int): The dimension ... |
0429d726625a606c680735272dbd2ae540590b024641bd9e88f192487c3f85ff | Python | 1,996 | 49 | import numpy as np
import pandas as pd
import scanpy as sc
from scipy.sparse import spmatrix,coo_matrix,csc_matrix
from Bio import Phylo
from io import StringIO
import sys, os
sys.path.append("/home/bnphan/src/TMNT/tmnt_algorithm")
import TMNT
DATADIR="data/tidy_data/hierarchical_deg_analyses/"
save_file = "data/tidy_... |
4481f74b7b66a0238065be77c284e157f2f2f36f7a31a0059cfcf2118b6eb041 | Python | 1,996 | 59 | import random
import os
import numpy as np
import torch
from rdkit import RDLogger
from BatmanNet.util.parsing import parse_args, get_newest_train_args
from BatmanNet.util.utils import create_logger
from task.cross_validate import cross_validate
from task.fingerprint import generate_fingerprints
from task.predict imp... |
272ee5f0166e8bbc666c7c59f0c58063137c882b604f26e1a34b472c7dfe646b | Python | 1,997 | 56 | import numpy as np
import pytest
from seqpro.rag import Ragged
def _multidim_record():
"""A (3, 2, None) numeric record: 6 ragged segments over a (batch=3, ploidy=2)
leading grid."""
lengths = np.array([[1, 2], [3, 1], [2, 2]], np.uint32) # (3, 2)
data = np.arange(int(lengths.sum()), dtype=np.int32)... |
60ef41de899f635281367e1107c3d77b99ee38b854ccd745566962d60bc14131 | Python | 1,997 | 62 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import json
from pathlib import Path
from ultralytics.utils import LOGGER
from ultralytics.utils.files import import_execstack
def onnx2mnn(
onnx_file: str,
output_file: Path | str,
quantize: int | st... |
0855ccb181174aa26eef4eeb64f254e065a46aa239be0e528bc9302760e96851 | Python | 1,998 | 76 | from typing import List, Any
import argparse
import numpy as np
from ase import build as ase_build
from pymatgen.core.structure import Molecule
from pymatgen.io.ase import AseAtomsAdaptor
from coeffnet.transforms.rotations import RotationMatrix
from instance_mongodb import instance_mongodb_sei
def get_command_l... |
883498d5753f460ea3ef239bfcd8fe0b2a5b4550a901818a8bb71e517f36c07c | Python | 1,998 | 62 | from __future__ import division
import unittest
import numpy as np
from scipy.signal import butter
from wyrm.types import Data
from wyrm.processing import lfilter, spectrum
from wyrm.processing import swapaxes
class TestLFilter(unittest.TestCase):
def setUp(self):
# create some data
fs = 100
... |
46ec4b786297b122e6eb95efea60d7d0fc174e291dc0a6800e1d393292248012 | Python | 1,999 | 62 | import os
import tempfile
import time
from ethoscope.core.monitor import Monitor
from ethoscope.drawers.drawers import DefaultDrawer
from ethoscope.hardware.input.cameras import MovieVirtualCamera
from ethoscope.hardware.interfaces.interfaces import HardwareConnection
from ethoscope.hardware.interfaces.lynx_motion imp... |
b610b7fca5ffc4b1c8c76b690c57f1f058df0d245e96b51422e34837325db2ae | Python | 1,999 | 77 | import torch
from torch.nn import Linear, ReLU, ELU, SiLU
def he_kaiming_init(tensor):
tensor = torch.nn.init.orthogonal_(tensor)
if len(tensor.shape) == 3:
axis=[0, 1]
else:
axis=1
mean, var = torch.var_mean(tensor, dim=axis, keepdim=True)
tensor = (tensor - mean) / (var) ** 0.5
... |
de2aab7632070240adebdeff510c677496ba0c0da89260a5456a2868ab0fc2c8 | Python | 1,999 | 40 | import argparse
from scripts.segmentation import train
import os
import warnings
from settings import CUDA_VISIBLE_DEVICES
os.environ['CUDA_VISIBLE_DEVICES'] = CUDA_VISIBLE_DEVICES
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
warnings.filterwarnings("ignore")
if __name__ == '__main__':
parser = argparse.ArgumentP... |
f68f0d313aca024d5965f98ba90facbf70af683d8f9945bc6cea8ac5f5bcee97 | Python | 1,999 | 68 | import h5py
import torch
import numpy as np
from brainbox.datasets.transforms import ClipRandomHorizontalFlip
class NaturalDataset(torch.utils.data.Dataset):
def __init__(self, root="/home/datasets/natural", train=True, dt=30, flip=True, filtered=True):
self._root = root
self._dt = dt
sel... |
8a67465056fd092e22899d69c40c1c4006ded4928a8f2bfd593cbde2a1c742f9 | Python | 2,001 | 68 | """Registry of available tasks."""
import inspect
from importlib import import_module
from celery._state import get_current_app
from celery.app.autoretry import add_autoretry_behaviour
from celery.exceptions import InvalidTaskError, NotRegistered
__all__ = ('TaskRegistry',)
class TaskRegistry(dict):
"""Map of r... |
e701aac1cffff53a8815d4dab7a4a0d5cadd62cfd166ecee9c4743762461a283 | Python | 2,001 | 69 | # 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... |
11883cd24617b9abdf2460ee53669946dcb2bc02d9f91fe183f903feaac621ef | Python | 2,002 | 67 | from __future__ import annotations
import hashlib
import os
from typing import Optional
def hash_recursive(folder: str, extensions: list[str]) -> str:
"""Recursively walk a folder grabbing any files that have an
extension in extensions.
Hash all the contents together with the paths and return an overall... |
2a81048acd2e45ad33b4f1d69d08c17fdc621f9a5c427617d1e5d3ea1d11dc38 | Python | 2,002 | 56 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import create_feature_vectors
from wyrm.processing import swapaxes
class TestCreateFeatureVectors(unittest.TestCase):
def setUp(self):
# create epoched data with only 0s in class0, 1s in ... |
6ad08f12475efb12a7a3270a0be1d0954032d00ef2ed238b7426446ec8ffbc6a | Python | 2,002 | 54 | # 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... |
07ab8f99f5ce5ac2994eb370ef781116d3c06bdae9f4b4aa725964618a98ccda | Python | 2,003 | 58 | # import libraries
import pandas as pd
from sklearn.utils import shuffle
import sklearn
import sklearn.model_selection
from pathlib import Path
import os
import numpy as np
import argparse
from tqdm import tqdm
def main(base_path, save_dir):
# get image file path
path = Path(base_path)
print('Base Path: ',... |
0b65d2cce5ded394e29be46e56f952cb0125d2a7805e58b725ff23a1541df964 | Python | 2,004 | 62 | """
Datatype classes for tracks/track views within galaxy.
"""
import logging
from galaxy.datatypes.protocols import (
DatasetProtocol,
HasExtraFilesAndMetadata,
)
from galaxy.datatypes.text import Html
from . import binary
log = logging.getLogger(__name__)
# GeneTrack is no longer supported but leaving th... |
57358510c988c146a60a93098d2e5250a8c952512741d5e34699d20c7085c352 | Python | 2,004 | 56 | ## Read write encoder
# This version is identical to the original "save_tracking.py" code,
# with the exception that the "export_params.cfg" file is not read and
# the file is not moved
import sys, os
from shutil import copyfile
from datetime import datetime, timezone, timedelta
import serial
import csv
import confi... |
b35247f53207a7cd1a4a7ef093ed6528d6e36a0679438e2343e7d63a0b43155d | Python | 2,004 | 69 | # -*- coding: utf-8 -*-
import os
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge
class B2B_reg():
"""Implement Bask-to-back regression between X and Y.
Args:
- X: np.array
- Y: np.array
- m: int
Returns:
-
ref: https://www.biorxiv.org/conten... |
0905d77b6ba1081786fb863cc4a0425f94df6c50e83b3f16b213a55a4450ad94 | Python | 2,005 | 64 | """
=================================
Functional Connectivity Helpers
=================================
This file contains helper functions for the functional connectivity example
"""
from pyriemann.utils.base import nearest_sym_pos_def
from sklearn.model_selection import StratifiedKFold
from sklearn.base import cl... |
16c2fbe236ae2e59d25f7714ba6de0f705388c508b7429a3206b63bc0d1be2a6 | Python | 2,005 | 73 | import torch.nn as nn
from modular_splicing.models.modules.residual_unit import ResidualUnit
class FCMotifFeatureExtractor(nn.Module):
"""
Module that extracts features from a sequence of motifs.
First it projects the input to a higher dimension, then it
performs a number of 1x1 convolutions, then i... |
60f623947d2820a052c75f9e06ca02cc673d3154ffb75514a58cbdb9f377def9 | Python | 2,005 | 64 | #!/usr/bin/env python
"""
Converts a SD-file to a GSPAN file.
"""
import argparse
import os
import sys
import openbabel
import pybel
def main(args):
for infile in args.infile:
file_extension = args.format or os.path.splitext(infile)[-1].lstrip(".")
if not args.format and file_extension no... |
664bd06ba65a2ac1786d7fd7ebea5d36c0ac41c5d27093e155cbcb5bb131484c | Python | 2,005 | 60 | def encode(tiles, model):
features = model.predict(tiles)
features = features.ravel()
return features
class Model:
__name__ = "CNN base model"
def __init__(self, base, batch_size=1):
from tensorflow.keras import backend as K
self.base = base
self.model, self.preprocess = ... |
903640fad3068313700093204d8705202f9e00d49ef0a99873042b36a0eaf8a9 | Python | 2,005 | 64 | # Copyright 2025 Google.
#
# 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, soft... |
be889bc9e03aeed53321b96cfa7aa1e3df480730041a8184b6f63f03feb60ebe | Python | 2,005 | 59 | """
CILogon OpenID Connect backend for Galaxy.
This backend extends Galaxy's base OIDC implementation with CILogon-specific features.
"""
from galaxy.authnz.oidc import GalaxyOpenIdConnect
class CILogonOpenIdConnect(GalaxyOpenIdConnect):
"""
CILogon OIDC backend for Galaxy.
Inherits PKCE support, local... |
e0f18b9be1b244c01a252f804df8c2282b8e327ccd076c85612baee7dfa3bee4 | Python | 2,005 | 75 | from anndata import AnnData
from typing import Optional, Union
import matplotlib.pyplot as plt
import scanpy as sc
import numpy as np
def check_trajectory(
adata: AnnData,
library_id: str = None,
use_label: str = "louvain",
basis: str = "umap",
pseudotime_key: str = "dpt_pseudotime",
trajector... |
6fdcfeadb89b0c52ebb664cb96da5140d1ef8808e4947e821e559df210af594e | Python | 2,006 | 79 | """Dataclasses and errors for the portal Module Inspector.
Covers three module "kinds":
- "effector": crawler/turner, driven by a constant scalar ``A_in``
- "feeder": self-oscillator, no external input
- "sensor": driven by a time-varying stimulus converted to a dict input
"""
from __future__ import annot... |
0c41e959b3cc4f8efe2324fe8fb8945e0d1c29cb5f4b036ced5e98f62b560742 | Python | 2,007 | 60 | from pyrosm.config.default_tags import *
from pyrosm.config.osm_filters import get_osm_filter
class NetworkFilter:
driving = get_osm_filter("driving")
driving_psv = get_osm_filter("driving+psv")
walking = get_osm_filter("walking")
cycling = get_osm_filter("cycling")
class Tags:
# Tags object con... |
5d74130c5866b6d230afd5c3e5ca931f9313fdcfdfb7a1a0331c0176d50710db | Python | 2,008 | 63 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import argparse
import json
from os.path import join
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from gluoncv.utils.download import download
__author__ = 'Fisher Yu'
__ema... |
865f7eac0e7a9f8722671305014dbeb583bdb7e5134540ed17c02c827556a1b2 | Python | 2,008 | 63 | import os
import re
import argparse
import random
def crossval_files(prefix, numfolds):
cvfiles = []
for i in range(numfolds):
trainfile = '{}train{}.types'.format(prefix, i)
testfile = '{}test{}.types'.format(prefix, i)
cvfiles.append((trainfile, testfile))
return cvfiles
def re... |
c059d1a0ef36b16f0e1197d19885eb9bc675f27376dc676400fcdf1814526563 | Python | 2,008 | 70 | from distutils.version import LooseVersion
import numpy as np
def check_version(library, min_version):
"""Check minimum library version required
Parameters
----------
library : str
The library name to import. Must have a ``__version__`` property.
min_version : str
The minimum vers... |
c2a54454ea38871a916436f1b41e9b4a84e394f483a8cd767314ac876e9081d0 | Python | 2,008 | 47 | # SPDX-License-Identifier: LGPL-2.1-or-later
import setuptools
with open("README.rst", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='pyEcoHAB',
version='1.0',
author="Joanna Jędrzejewska-Szmek, Jan Mąka, Szymon Łęski",
author_email="j.jedrzejewska-szmek@nen... |
e53e4d68b197273ee975ef53fc4ab7aa378c99a2d07b9fe1989c201439cd3b6d | Python | 2,008 | 62 | from __future__ import division
import unittest
import numpy as np
from scipy.signal import butter
from wyrm.types import Data
from wyrm.processing import filtfilt, spectrum
from wyrm.processing import swapaxes
class TestFiltFilt(unittest.TestCase):
def setUp(self):
# create some data
fs = 100... |
4f52c0529b016944f6542b74151e5bcb411013bca3dcd96d8de106d723350b8d | Python | 2,009 | 52 | import unittest
import numpy as np
from torch import nn
from modular_splicing.train.adaptive_sparsity_threshold_manager import (
AdaptiveSparsityThresholdManager,
)
class AdaptiveSparsityStateTest(unittest.TestCase):
def test_idemnipotent_setup(self):
m = nn.Module()
x = AdaptiveSparsityThre... |
59e39b77bacc8fdb07cd806ec260c32531fe10a58b97aa926f6d88eabf9dd7d3 | Python | 2,009 | 66 | # pylint: disable=unused-argument
"""Custom OP: BBoxClipToImage, used to clip bbox to image edges."""
import mxnet as mx
class BBoxClipToImage(mx.operator.CustomOp):
"""Clip bounding box to image edges.
Parameters
----------
axis : int
The coordinate axis with length 4.
"""
def __ini... |
79ecd87f6057c5fad77305c0a190f602b91cade0e548988f53b3a17273073a6b | Python | 2,009 | 68 | """Recursive webcrawler example.
For asynchronous DNS lookups install the `dnspython` package:
$ pip install dnspython
Requires the `pybloom` module for the bloom filter which is used
to ensure a lower chance of recrawling a URL previously seen.
Since the bloom filter is not shared, but only passed as an argume... |
359dd95a4a32c016c2346358af74f1396bea15dfe70d43e28f84d78f5325e0ab | Python | 2,010 | 60 | # Copyright (c) ByteDance, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from timm import create_model
from timm.loss import SoftTargetCrossEntropy
from timm.models.layers import dro... |
362a43782c1e9cbeff2f0c8734c3308eb516342178ce23a6121e70a347430049 | Python | 2,010 | 57 | """
This code demonstrates how to determine where the stimulus waveform comes from.
The default is to auto-load it from the stimulus file defined in the ABF.
We can override this functionality, using an in-memory array, which is useful
when analyzing many files with the same stimulus as it prevents the need to
re-read... |
f0acfd90f2949d175a044c2e098a692efd44ea7aa1f438930c8dae08fde29dab | Python | 2,011 | 44 | from collections import OrderedDict
import os
import torch
# FIXME: shouldn't need this anymore
def resume_checkpoint(model, checkpoint_path, optimizer=None, loss_scaler=None, logger=None, log_info=False):
resume_epoch = None
if os.path.isfile(checkpoint_path):
checkpoint = torch.load(checkpoint_path,... |
97ea201e1e35bf552a3495cffde3ab7ec3eaf10f231f7f7f0d9b658537ecd364 | Python | 2,012 | 71 | import pathlib
import shutil
import sys
# alternative is to make code installable (which it is!)
sys.path.insert(0, pathlib.Path(__file__).parents[2].resolve().as_posix())
# clean up .zarr dirs left over from previous notebook executions
for p in pathlib.Path(__file__).parent.glob("**/*.zarr"):
shutil.rmtree(p)
p... |
b797b5da16d1da98bd5787b35834c1e0933e0084949c63a499c9d81de937c638 | Python | 2,013 | 62 | """
Customized Mixin2to3 support:
- adds support for converting doctests
This module raises an ImportError on Python 2.
"""
from distutils.util import Mixin2to3 as _Mixin2to3
from distutils import log
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
import setuptools
class DistutilsRefactor... |
f70601f7d7caddc31576edf315c49464c15a411ebb286d53d106e182b3882a4e | Python | 2,014 | 72 | """Neural Theorem Prover, 2017, Rocktaschel and Riedel, "End-to-end Differentiable Proving".
Paper: Rocktaschel 2017, "End-to-end Differentiable Proving."
This simplified prover computes soft unification between a goal triple and fact
triples with an RBF kernel, then max-pools proof scores over available facts.
"""
f... |
23a497d961382a9645b07875bf130cf5cc81ae669d524fad7a5da638ff767665 | Python | 2,015 | 80 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Fit peptides for degradation constant and half-life.
Project: SILAM
Step #3
Input data: Filtered normalized peptide abundance.
Output data: Results of fitting across all replicates.
Created on 2022.04.24
Author: Kirsten Chen
Last changed: 2022.09.14
"""
import ... |
bf0e7a23b58c2c0ef6873b058e5afd0921f11cd672d4d114fe39d64e5a5520e9 | Python | 2,015 | 59 | # 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... |
86b4f05f090daa24b0a5fd25db8259b1da8677f744f8a840d7e84c520d40ff23 | Python | 2,016 | 43 | import angorapy as ap
import angorapy.tasks.core
import angorapy.tasks.registration
from angorapy.tasks.wrappers import TaskWrapper
def _test_any_task(task: TaskWrapper):
state = task.reset()
for _ in range(100):
state, r, dterm, dtrunc, info = task.step(task.action_space.sample())
if dtrunc ... |
f9f41404005656be9b73c6d3c0b84e0a7ad304e3059fbb71a4920b03278f02bb | Python | 2,016 | 56 | import sys
from ij import IJ, ImagePlus
# Fiji Jython interpreter implements Python 2.5 which does not
# provide support for argparse.
input_file = sys.argv[-8]
image_datatype = sys.argv[-7]
noise = sys.argv[-6]
standard_deviation = sys.argv[-5]
radius = sys.argv[-4]
threshold = sys.argv[-3]
which_outliers = sys.argv... |
4451ee838502d7993d4027a18d7ce887995f32bd3fc692e4b261956fc8dd176f | Python | 2,017 | 47 | # adapted from https://github.com/facebookresearch/detectron2/blob/master/detectron2/data/samplers/grouped_batch_sampler.py
import numpy as np
from torch.utils.data.sampler import BatchSampler, Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It ... |
83099b1f31ef0295f8a7fc3f4e18e511a2bef163de7403fe128d1a4e23c20a15 | Python | 2,017 | 60 | # 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... |
b3583571eac6419dd9bf1007718758669cf020e2316da3f609768fae112d6a4a | Python | 2,017 | 60 | 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... |
0916f2626e81b34e78c2ff8242eec4959215088cbf66845ef95f1fde5ecb0027 | Python | 2,018 | 71 | import numpy as np
import pandas as pd
from typing import Optional
from anndata import AnnData
from sklearn.decomposition import FastICA
from scipy.sparse import issparse
def run_ica(
adata: AnnData,
n_factors: int = 20,
fun: str = "logcosh",
tol: float = 0.0001,
use_data: str = None,
copy: bo... |
166ce7b106a0f9cbe29a24f9d74804fce7f54bea0be2ecefd16d09ae620c2dcb | Python | 2,018 | 56 | import os
import pandas as pd
import numpy as np
import shutil
import subprocess
from settings import AGE_FROM, AGE_TO
N_CASES = 2
path_for_images = "./data/pre-processing/test"
storage_path = "Z:/USERS/Zezhong/pLGG/CBTN_BCH_Data/T1W"
def find_file_in_path(name, path):
result = []
result = list(filter(lambda ... |
2895939b9113190de146a7873a1fa97226638a4cba5324ff004a611fb669bdc0 | Python | 2,018 | 70 | from easydict import EasyDict as edict
__C = edict()
cfg = __C
#
# Dataset Config
#
__C.DATASETS = edict()
__C.DATASETS.DATADIR = '/path/to/dataset'
__C.DATASETS.SAVEDIR = '/path/to/save'
__C.DATASETS.DATASET_MODE = 'camus'
__C.TRAIN = edict()
__C.TRAIN.DIFFUSION = edict()
__C.TRAIN.DIFFUSION.LEARN_SIGMA = True
__C... |
333e3bf9ac8032594e87e4f82956cb0103dadecd52235fcbcde0e3c59511cf47 | Python | 2,019 | 78 | """Functions and converters for periodic parameters."""
import numpy as np
from specparam.utils.select import nearest_ind
###################################################################################################
###############################################################################################... |
f50f5f02a225a754b8e2266297aa3f6aa74b34a270d97e1b38e096a02ab75b00 | Python | 2,019 | 60 | 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... |
38ce093c272f0a3423f3f6d3efcf1ddee8ab910c192a31399e6922465eac4971 | Python | 2,020 | 60 | 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... |
4e9a7206df970342f003f44e0c673183c5647f2b97643f62a1e20836c282ba51 | Python | 2,020 | 53 | import os.path as op
import numpy as np
import pandas as pd
import os
import string
import seaborn as sbn
import retro
import matplotlib.pyplot as plt
from shinobi_behav.data.data import extract_variables
from shinobi_fmri.annotations.annotations import generate_key_events
from shinobi_behav import ACTIONS as actions
... |
6c1e9616951cdf1fa086b7df3c416f3dd596478b36309720f936b1657ad10421 | Python | 2,020 | 60 | import pytest
from larvaworld.lib import reg
from larvaworld.lib.process import Evaluation
from larvaworld.lib.sim import EvalRun
pytestmark = [pytest.mark.integration, pytest.mark.heavy]
@pytest.mark.usefixtures("ensure_datasets_ready")
def test_evaluation():
"""Test evaluation with datasets ready (avoids HDF5 ... |
86b8ef1dfa0f712a548bc3c197c22de07dd5dd7d62625cfac057b7130948c1ff | Python | 2,021 | 72 | from typing import Any
import numpy as np
from mirp._images.generic_image import GenericImage
class CTImage(GenericImage):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.calibrated_units = True
@staticmethod
def get_default_lowest_intensity():
return -1000.0
... |
0db1af02dbba9c65aaa0df889e9fb63b427cffaf1d4222714fdd9ed3b45be8e1 | Python | 2,023 | 75 | # 05/23/2023
# 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(organs)-1)
... |
5ef99e598c8a62414ddf33888af82e2b5a625e3b12287412ac9ab36ee53294d4 | Python | 2,023 | 62 | try:
from fs.onedatarestfs import OnedataRESTFS
except ImportError:
OnedataRESTFS = None
from galaxy.files.models import (
BaseFileSourceConfiguration,
BaseFileSourceTemplateConfiguration,
FilesSourceRuntimeContext,
)
from galaxy.util import mapped_chars
from galaxy.util.config_templates import Te... |
13c6097521aa05ec7de51c173d6aa6d6d672601165ff6c7d420e841ce9b955c3 | Python | 2,024 | 69 | # Copyright (c) 2020 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... |
e080b510f15538f99a4b94008ec829f37ba8457f153dad6b0dc0d0ec868f9d45 | Python | 2,024 | 75 | """Neural Gas, 1991, Martinetz and Schulten.
Paper: Martinetz and Schulten 1991, "A neural-gas network learns topologies."
Prototype adaptation is weighted by rank-ordered distance neighborhoods instead
of a single winner-take-all update.
"""
from __future__ import annotations
import torch
from torch import Tensor, ... |
61698102149a94a6ce8f567f6abfad8b1b04760825396f33f9d4f31e66e79c5f | Python | 2,025 | 53 | # Copyright 2017 The TensorFlow 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 applicab... |
839608451d000f3e2c77b421e6c1a252c7bde887712960337b92008f94f8bc46 | Python | 2,025 | 71 | from .bulletin import Bulletin
from bs4 import BeautifulSoup
class Kerala(Bulletin):
def __init__(self, basedir):
statename = 'KL'
super().__init__(basedir, statename)
self.bulletin_page_url = u'https://dhs.kerala.gov.in/%e0%b4%a1%e0%b5%86%e0%b4%af%e0%b4%bf%e0%b4%b2%e0%b4%bf-%e0%b4%ac%e... |
d72e06de8083359ac17ad6443b70d7fa4b4ce40ce0d687767c86924d50be64d8 | Python | 2,025 | 85 | import numpy as np
import torch
import sklearn
from sklearn.ensemble import RandomForestClassifier
# Step 1: Read and preprocess data
f = open('protein_dataset/protein_19.txt')
vals = [line.strip().split(', ') for line in f]
f.close()
def convert(s):
return np.array([one_hot(c) for c in s]).ravel()
def one_hot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.