sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
fe9f370f2660c54cb5b08a733ee1fcadb98a4a08679a0c7424e1f07b1ffa9ee3 | Python | 3,699 | 114 | # 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 copy
import torch
imp... |
68e33bec55b838830107b2a43ac48ed7d2e88627a3630c763b246dd101170b02 | Python | 3,700 | 114 | import pickle
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.utils import shuffle
from tqdm import tqdm
def augment_positive(spectra, ids4p, low=0.2, high=1.0):
no = random.randint(0, len(ids4p) - 1)
ratio = random.uniform(low, high)
x = ratio * spectra[ids4p[-1]]['fid']
... |
1495b8c9a02f527e4642949fbb7ef83649d1d74baf478b015b8b8b5123bd868e | Python | 3,701 | 114 | import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
class DelayPairedAssociation(TrialEnv):
"""Delayed paired-association task.
The agent is shown a pair of two stimuli separated by a delay period. For
half of the stimuli-pairs shown, the agent should choose the Go re... |
3675d9057acde70f40e72d5c1dad2778cd90373c1fa16a7e3c8b0035f6e0ff91 | Python | 3,701 | 116 | """Tools for importing data through mne.
.. autosummary::
:toctree: generated
events
epochs
variable_length_epochs
mne_epochs
variable_length_mne_epochs
add_epochs
add_mne_epochs
epochs_ndvar
evoked_ndvar
sensor_dim
stc_ndvar
forward_operator
inverse_operator
DatasetSTCLoa... |
d2642472661b5b084ed996769a9c03313cecd080091c25b0fb705b7638924f52 | Python | 3,701 | 138 | # altschulEriksonDinuclShuffle.py
# P. Clote, Oct 2003
# NOTE: One cannot use function "count(s,word)" to count the number
# of occurrences of dinucleotide word in string s, since the built-in
# function counts only nonoverlapping words, presumably in a left to
# right fashion.
import sys,string,random
def computeC... |
f103b6cb23c3431bc08de56d85a778b41d05b1b26507c2fefab3bbab419fe404 | Python | 3,701 | 119 | import os
import sys
import traceback
from pathlib import Path
from typing import Dict
import shutil
import pandas as pd
import numpy as np
# import snakemake
import snapatac2 as sa2
import pyprojroot
code_root_dir = str(pyprojroot.here())
pack_dir = f"{code_root_dir}/package/python"
sys.path.insert(0, pack_dir)
impo... |
d9c8fcd452e363b42fa470d42bf2ef9e272da34f49a787b00eda2f72fb920bcb | Python | 3,702 | 99 | #!/usr/bin/env python3
"""
File: picalo.py
Created: 2020/11/16
Last Changed: 2023/08/21
Author: M.Vochteloo
Copyright (C) 2020 University Medical Center Groningen.
A copy of the BSD 3-Clause "New" or "Revised" License can be found in the
LICENSE file in the root directory of this source tree.
"""
... |
a9e3ba268d8d17b8d036abf9adfa0cfe0f83c5f5f92953fa96673402fa823077 | Python | 3,703 | 104 | import torch
from tqdm.auto import tqdm
from seqexplainer import evolution
from .._settings import settings
import xarray as xr
import numpy as np
from typing import Optional, List, Dict, Any
def evolve_seqs_sdata(
model: torch.nn.Module,
sdata: xr.Dataset,
rounds: int,
seq_var: str = "ohe_seq",
... |
b82403245752329ee851e7da8fb7456e367e6fc16005f04b994b627d1f3dd768 | Python | 3,705 | 110 | from __future__ import annotations
import copy
from typing import Optional
import numpy as np
import pandas as pd
from bream4.device_interfaces.devices.minion import MinionGrpcClient
from bream4.toolkit.procedure_components.data_extraction.collect_continuous_data import (
collect_continuous_data_current_setup,
)... |
1666c691ba0a7b5c3b80fb6a5f65f45c095eb468d74e9cc6c1b076a910eaf173 | Python | 3,706 | 81 | import os.path
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random
import util.util as util
class UnalignedDataset(BaseDataset):
"""
This dataset class can load unaligned/unpaired datasets.
It requires two directories to ... |
cadac170a7da379e27c36d044360480d710cfa88d082dad2b9decd58e4847111 | Python | 3,706 | 103 | # Copyright (c) 2025, Tri Dao.
from typing import Type, Callable, Optional
import cutlass
import cutlass.cute as cute
def get_smem_layout_atom(dtype: Type[cutlass.Numeric], k_dim: int) -> cute.ComposedLayout:
dtype_byte = cutlass.const_expr(dtype.width // 8)
bytes_per_row = cutlass.const_expr(k_dim * dtype_b... |
dbf943f5c1cf8ec04bfec6b67afd4c50a9a0c6d07bd78180e3852c0440d27519 | Python | 3,706 | 113 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Marker(_BaseTraceHierarchyType):
_parent_path_str = "quiver.selected"
_pa... |
1fbba740f0e04e2b524120e42e093fa71a78f42594123ba65dac7273670375ff | Python | 3,707 | 129 | model = dict(
type='SimSiam',
backbone=dict(
type='ResNet',
depth=50,
in_channels=3,
out_indices=[4],
norm_cfg=dict(type='SyncBN'),
zero_init_residual=True,
init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')),
neck=dict(
type... |
0a628751799ebefe1f920fde2b4097fed374e731de0f9dc8aa5d000eb0c656ef | Python | 3,708 | 95 | import bisect
import copy
import json
from collections import OrderedDict
from math import cos, sin
from pathlib import Path
import numpy as np
import open3d as o3d
from scipy.spatial.transform import Rotation
def coord_transform_OR_4D_to_human_pose_tool(arr: np.ndarray):
orig_shape = arr.shape
if len(orig_... |
b23e4cae0cbf3d9e32c4141ec117277f8f727eccbe521ded4c1bbe646372cf14 | Python | 3,708 | 112 | # 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... |
00caa76d222786fa804f8f37ea6615f1ed3e4909839ddda4ea129df97f89c9cd | Python | 3,710 | 110 | # 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... |
9c93d992c52cff385bf6d559bb98ffcf4350b7cdda710e0ab04c90204691906f | Python | 3,710 | 89 | import pandas as pd
import numpy as np
import datetime
#Load data
phase = 3
df_metadata = pd.read_csv('../DATA/adni%d_mri.csv'%phase, index_col=0)
# Load patient assesments
cols_a = ['RID', 'EXAMDATE',
'DXCHANGE', 'DIAGNOSIS']
df_assesment = pd.read_csv(
'../ASSESMENT/DXSUM_PDXCONV_ADNIALL.csv', usecols... |
b11a53e84f26b8379108788d3b3f9d7f2c601e5b4638acfd3576f0f906fd4a33 | Python | 3,710 | 143 | from abc import ABC, abstractmethod
import attr
from modular_splicing.utils.io import load_model, model_steps
from .load_model_for_testing import step_for_density
STANDARD_DENSITY = 0.178e-2
STANDARD_DENSITY_FLY = 0.317e-2
# what ten epochs are for the given batch size
TEN_EPOCHS = {10: 1627100, 15: 1627200}
TWENTY_E... |
a67306ca2eb95c5dd78b41bcb37200e2362824953c77ccb76145c94a4e5e8cb4 | Python | 3,711 | 112 | # %% [markdown]
# # Create Scenes
#
# (advanced:create-scenes)=
#
# This tutorial demonstrates basic usage around writing and reading [Ngff Scenes](https://ngff.openmicroscopy.org/specifications/dev/index.html#scene-metadata) using the `OMEZarrScene` class.
# %%
from ome_zarr_models.v06.coordinate_transforms import Co... |
6341ac66fe5704538c3e42bb127cc026df8f3c785080e78cbd3b67228e7081e3 | Python | 3,712 | 111 | from permacache import permacache, stable_hash
import tqdm.auto as tqdm
import numpy as np
from modular_splicing.base_perturbations.perturbations import (
probabilities_by_changed_sequence,
)
from modular_splicing.utils.run_batched import run_batched
@permacache(
"perturbations/stability_by_perturbation_thr... |
6bf223f3d6c6c8019f39e9cab0b511361051e00888a082110cd6196f5c608a4a | Python | 3,712 | 116 | # coding=utf-8
# Copyright 2023 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... |
9d27e5ec6ebca248b2a52533c5fffb9cc0af46d01b2ad2c85cdb2f37ad77a869 | Python | 3,712 | 95 | """B8 R62: a captured function signature must not leak host paths or, under
``include_source=False``, source-derived default VALUES.
``inspect.Signature.__str__`` renders every parameter default via
``repr(default)``, so a default like ``cfg='/home/user/x.yaml'`` embedded an
absolute host path verbatim and a ``token='... |
961882e2d7f224c391c542978d9a38240b2878e0a99c02fef904a9304a876e51 | Python | 3,714 | 77 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
98f17660fe9f98c057603bad09eb04091c24a8652ac12b44578329c9eeb86423 | Python | 3,714 | 112 | from abc import ABC, abstractmethod
import torch
from .datapoint_extractor import datapoint_extractor_types
from .iterator import iterator_types
from .post_processor import post_processor_types
from modular_splicing.utils.construct import construct
class GenericDataset(ABC, torch.utils.data.IterableDataset):
"""... |
9fe777565b1f9de570eb4fa2033f98071be98e5d5af02e5cffd88625a2d16820 | Python | 3,714 | 105 | import numpy as np
import pytest
import torch
from torch import Tensor
from lightly.loss import DirectCLRLoss
class TestDirectCLRLoss:
temperature = 0.5
def test_set_parent_temperature(self) -> None:
loss_function = DirectCLRLoss(loss_dim=32, temperature=self.temperature)
assert loss_functio... |
44d841b0becfba58ebcf8749af628bcc13de9bb0641768a5d7220e22d3f72fef | Python | 3,716 | 95 | import warnings
from dataclasses import dataclass
from typing import Any
from mirp.settings.utilities import setting_def
@dataclass
class GeneralSettingsClass:
"""
Set of overall process parameters. The most important parameter here is ``by_slice`` which affects how images are
processed and features are c... |
df45be732e1e0c766fbc048f627220315d68795a13525540c61413b31eacd97c | Python | 3,716 | 119 | """Code for EMP-SSL Loss, largely taken from https://github.com/tsb0601/EMP-SSL"""
from typing import List
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
def tcr_loss(z: Tensor, eps: float) -> Tensor:
"""Computes the negative Total Coding Rate (TCR) loss.
... |
390ec29700031835bb381cc9e627657a203c60675676994037ee833887f83c82 | Python | 3,717 | 100 |
#import libraries
from SelfOrganizingMap import SelfOrganizingMap
import numpy as np
import warnings
##############################
# author: Ali Javed
# October 14 2020
# email: ajaved@uvm.edu
#############################
warnings.filterwarnings("ignore")
np.random.seed(0)
#set window size for DTW --- usi... |
5c6e9f11216bad8fd8ce0cfd4b7d1d64e453ea64dbc7a5a06076dfd192312e0c | Python | 3,717 | 93 | """A collection of builder functions for models usable with different envs in PPO."""
import inspect
import itertools
from collections import OrderedDict
from functools import partial
from typing import Callable
# registry for base models
MODELS_AVAILABLE = {}
MODEL_BUILDERS = {}
def register_model(model_name):
... |
620c08c9b9d41b3d53ba6eaeaa5fc2733d03d20a19064f9f07741af33d1ae6f1 | Python | 3,718 | 135 | from itertools import zip_longest
from typing import Optional
import numpy as np
import pytest
import gym
from gym.spaces import Box, Graph, utils
from gym.utils.env_checker import data_equivalence
from tests.spaces.utils import TESTING_SPACES, TESTING_SPACES_IDS
TESTING_SPACES_EXPECTED_FLATDIMS = [
# Discrete
... |
c92a2f31945c7c66243668d1bf9ef3090fc4bd39bcdbf9c0cddda591c7fc4579 | Python | 3,718 | 113 | from enum import Enum
import numpy as np
from shapely.coordinates import get_coordinates
class Unit(Enum):
"""
Enumeration of supported units.
The full list can be checked by iterating over the class; e.g.
the expression `tuple(Unit)`.
Inspired by: https://github.com/mapado/haversine
"""
... |
604190d191b54dbec16ab8421afcb6ce00ddb70174555d1b63215cd7f3e46d48 | Python | 3,719 | 109 | import os
import numpy as np
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def test_example_feature_extraction():
from mirp import extract_features
# Extract from single DICOM stack.
feature_data = extract_features(
image=os.path.join(CURRENT_DIR, "data", "sts_images", "STS_001", "CT"... |
1002d03bdc123fad9d47e09bfeebd215556cb4ca1a44d4226773bbcea124b1b9 | Python | 3,721 | 104 | """
This module contains all methods and classes relevant in data management,analysis, storage
as well as the methods supporting the import of experimental tracker datasets
"""
from __future__ import annotations
from typing import Any
__displayname__ = "Data management"
# Public API: expose core dataset classes, e... |
2408c4e2af2b4d9dc1d2c1a365a95f49ce1d13fd80aaf25b49ea1c1f25339021 | Python | 3,721 | 114 | """
Clean, colorized logging for scripts.
Based on https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
with many adaptations by Nick Semenkovich <semenko@alum.mit.edu>
License: MIT
Author: Nick Semenkovich <semenko@alum.mit.edu>
"""
from __future__ import absolute_import, division, print... |
5041b443c30603b05d5aea6e0bcb7dcd64f422e6f5ce733a31cabb8f85956954 | Python | 3,721 | 114 | import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
# TODO: Getting duration is not intuitive, not clear to people
class IntervalDiscrimination(TrialEnv):
"""Comparing the time length of two stimuli.
Two stimuli are shown sequentially, separated by a delay period. The
... |
a1db8744fe92b75e584df9e4174ede8ec65486dd758e2dba7cdfa246a6d8fd8b | Python | 3,721 | 124 | from typing import (
Optional, # Special
)
import matplotlib.axes
import matplotlib.figure
from anndata import AnnData
from bokeh.io import output_notebook
from bokeh.plotting import show
from stlearn.pl._docs import doc_cluster_plot, doc_spatial_base_plot
from stlearn.pl.classes import ClusterPlot
from stlearn.... |
d56c053dcf46da4f406bd7446541edd179f54cfd19256c945ac7e4bb959b63a1 | Python | 3,721 | 96 | # 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... |
3bc7f7dec4202e91973759c4d211c38a471ea3a0dca0dc4dcc94e05b008a8721 | Python | 3,722 | 83 | import pytest
import torch
from pytest_mock import MockerFixture
from torch import distributed as dist
from lightly.loss import SwaVLoss
class TestSwaVLoss:
def test__sinkhorn_gather_distributed(self, mocker: MockerFixture) -> None:
mock_is_available = mocker.patch.object(dist, "is_available", return_val... |
eb66b1cded192ca6607dcddd4a23598a510d097f136d86ace35cc55984d436ae | Python | 3,722 | 119 | import snapatac2 as sa2
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
sample_file = "mba.whole.sample.lst"
# * get all the barcodes after qc + doublets
with open(sample_file, 'r') as f:
samples = [l.strip() for l in f.readlines()]
# input_dir = "snapatac2_pp_out/bmat"
# out_dir = "snapa... |
ec2eeaf1121fc8b6ab7554c5a1b91a3476eee533d147d7c420f56ea5126f8389 | Python | 3,722 | 94 | # %% [markdown]
# # Adding labels to ome-zarrs
# (advanced:labels:adding_labels)=
#
# Unlike demonstrated in the [basic labels example](basic:labels), in many scenarios, it is not desirable to write a complete structure consisting of an ome-zarr image and some labels at once.
# Instead, one might want to *first* write ... |
8879ce17a184c4f7aa54318c9d96fb4ed73d764ee66fe6f48822b91a4bb772f3 | Python | 3,723 | 110 | import unittest
from numpy import hstack, max, abs, zeros, sum
from cantera import Solution, gas_constant
import numpy as np
from spitfire import ChemicalMechanismSpec
from os.path import join, abspath
from subprocess import getoutput
test_mech_directory = abspath(join('tests', 'test_mechanisms', 'old_xmls'))
mechs = ... |
09381bd847b80101aab6a812619767ad4f2d992d21a8f969eb11457b2ae3a9d6 | Python | 3,725 | 146 | import argparse
from chembl_webresource_client.settings import Settings
Settings.Instance().CACHING = False
from chembl_webresource_client.new_client import new_client # noqa
def open_file(filename):
with open(filename) as f:
return f.readline().split()[0]
def get_smiles(res):
"""
Get a list ... |
6df92f3f5a55db927503e5c943ba70b31b8c0d0e719a17e25eb081ce47aefdd7 | Python | 3,725 | 147 | """
Test the methods in the metal_auxiliaries module.
"""
import unittest
import numpy as np
from scipy.stats import entropy
from metal_auxiliaries import (fast_compute_angle, fast_entropy,
fast_euclidean_norm, CLASS_TARGETS)
class TestAuxiliaries(unittest.TestCase):
def test... |
8df814f7e41dfd1bc57557b5f83da5c157d50514169bbfebeb8e13868506aeb1 | Python | 3,725 | 112 |
########################################
## Import parameters from CLI
########################################
import os
print(f"script environment: {os.environ['CONDA_DEFAULT_ENV']}")
## Argparse --path_params, --directory_save
import argparse
parser = argparse.ArgumentParser(
prog='Face-Rhythm Basic Pipeline... |
2e94e1eb31ef8b088930d1cb9ca39d53b7320656141059b0522a8b5457d6c777 | Python | 3,727 | 142 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np # just for typehints
from time import time as now
# image pre/post processing algorithms
from .imgproc import imfill
from .imgproc import get_perilesion_mask
# image feature functions
from .features import evaluate_features
# pwat evaluation ... |
c6591ae073eced5ab9a251f96e3319ab9183f465864e0d9301c90e8d64016329 | Python | 3,728 | 139 | #!/usr/bin/env python
"""
Input: Molecules in SDF, SMILES ...
Output: Molecule file filtered with obgrep.
Copyright 2013, Bjoern Gruening and Xavier Lucas
"""
import argparse
import multiprocessing
import os
import shlex
import shutil
import subprocess
import tempfile
def parse_command_line():
parser ... |
b998aac76e7cb2c9d166cb463bdb18a5071afcb95ce83142badfd3913c6bab0d | Python | 3,729 | 144 | """Visualize GPS trajectory.
To install the gmplot package, call:
pip install gmplot
To create a Google Map API key, please follow the instruction below:
https://developers.google.com/maps/documentation/embed/get-api-key
"""
import argparse
import json
import os
from glob import glob
import gmplot
import ... |
bb29c79e6c5c04f622dab6f1dbcc08a074b0894fa99d2f7037dfab9a2d3f41a0 | Python | 3,729 | 104 | # for rgenetics - lped to fbat
# recode to numeric fbat version
# much slower so best to always
# use numeric alleles internally
import os
import sys
import time
prog = os.path.split(sys.argv[0])[-1]
myversion = "Oct 10 2009"
galhtmlprefix = """<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//D... |
36991f525afc273e2ee165399a301ed998d32257815b02fafee43a3d61878512 | Python | 3,731 | 116 | import torch.nn as nn
from modular_splicing.models.modules.influence_value.linear_effects.linear_effects import (
linear_effects_types,
)
from modular_splicing.utils.construct import construct
from modular_splicing.models.modules.residual_unit_stack import ResidualStack
from .single_attention_long_range import Si... |
859a4ac7d11c3d1668da9f2f2f5585fb20f8b955500c548ecc7378f78e03ebdf | Python | 3,732 | 114 | """
The main file, which exposes the robustness command-line tool, detailed in
:doc:`this walkthrough <../example_usage/cli_usage>`.
"""
from argparse import ArgumentParser
import os
import git
import torch as ch
import cox
import cox.utils
import cox.store
try:
from .model_utils import make_and_restore_model
... |
877682beb927d7a0ac99dd3270e7ba9f28765407c0f8b25006d748427f285cff | Python | 3,732 | 136 | import gc
from typing import Callable, Union
import numpy as np
import pandas as pd
import torch
from captum.attr import DeepLift, DeepLiftShap, GradientShap, InputXGradient
from tqdm.auto import tqdm
from ._references import get_reference
from .._utils import _model_to_device
from .._ism import _naive_ism
def _get_on... |
c951d8e9ef1008f15fa5a79d56623fd2bf76f26f32fc958f2519d281d862ca7e | Python | 3,732 | 87 | import sys
from robustness.datasets import jsinV3
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import JSIN_PATH, MODEL_BASE_PATH
import os
# Make a custom build script for audio_rep_training_cochleagram_1/l2_p1_robust_training
def build_net(include_rep_in_model=... |
f65206348c3b14a869abb9c192d854caa8bd76e741260fd78579a0b513547ed0 | Python | 3,732 | 97 | import numpy as np
import time
from PCAfold import preprocess
import tensorflow as tf
from tensorflow.keras import layers, initializers
from keras import Model, Input
from tensorflow.keras.callbacks import EarlyStopping
random_seed = 100
angle_list = [i for i in range(0,180)]
n_points = 2000
np.random.seed(seed=10)
... |
ebf7601aebdd1191a537e7320081b640435c1c78757edee60717f775b722b584 | Python | 3,733 | 93 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
f60d301866d796f6a02d09035d5c6930913802d4f84c3be3027da341f2cd33c7 | Python | 3,733 | 146 | """Tests for specparam.modutils.docs.
Note: the decorators for copying documentation are not currently tested.
"""
from specparam.modutils.docs import *
###################################################################################################
################################################################... |
38430623324aa2cd9fd28c8f393ae727f08e6edcdec6148f3ed520bf87a77261 | Python | 3,735 | 106 | import torch.nn as nn
from collections import OrderedDict
import torch
def conv_layer(in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True):
padding = int((kernel_size - 1) / 2) * dilation
return nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding, bias=bias,... |
a1607526073a2cfc3c9cc3115d0a324a61ed98b42ad9d2d7495ed6dbf36b8dec | Python | 3,735 | 117 | from itertools import cycle
import attr
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def plot_sensitivity_by_motif(full_data, names):
"""
Plot sensitivity by motif, ordered by the mean.
"""
sensitivity = {m: full_data[m].sum((0, 1)) for m in full_data}
sensitivity = pd.... |
35de8578db8dbc55fc6c5557b0f3ab6dda6bb02e413a4a751c29190e407cc958 | Python | 3,737 | 115 | """
Execute commands locally or via sbatch.
"""
import click
import os
import subprocess
import time
import uuid
import re
sbatch_prelude = """#!/bin/bash
#SBATCH -c 4
#SBATCH -N 1
#SBATCH --exclusive
#SBATCH -p campus
#SBATCH -o job_%j.out
#SBATCH -e job_%j.err
#SBATCH --mail-type=ALL
#SBATCH --mail-user=matsen@fred... |
3cd0956f0541dbb367244e05a2c53b318e1a0d6ea43d812908ac210a96fc1a17 | Python | 3,737 | 104 | import numpy as np
import time
import pathlib
import os
import h5py
from multiprocessing.pool import ThreadPool
from os.path import join, dirname
from ridge_utils.npp import zscore, mcorr
from ridge_utils.utils import make_delayed
from config import DATA_DIR
def apply_zscore_and_hrf(stories, downsampled_feat, trim, n... |
3428b825aa9f808d7a6c22c1e14da244ac8961dd7091f28761b9cafc2bf4c152 | Python | 3,738 | 79 | # Sample codes for preprocessing the data
import os
import numpy as np
import pydicom as dicom
from rt_utils import RTStructBuilder
import re
# Save MRI dicom as numpy
PathDicom = r"Dataset/1950-01__Studies"
patient_path = "MRI Brain and Treatment"
course_id = "1"
for foldername in os.listdir(PathDicom):
... |
4c437c2391707dff5804fecbe0110b5f99d2ef8f570e0efc1844ef70e60c85e3 | Python | 3,738 | 85 | import os
from helixfold.data.pipeline_multimer import *
from helixfold.data import parsers
import pickle
import gzip
from helixfold.data import feature_processing
def get_feature_dict(prot_chains,feat_dir,protein_map_file):
# protein, chain1, chain2 = protein_chains.split()[:3]
# fasta_name = fasta_names[i]
... |
80ed352dca3d9348038293dfe005b7425744e31beb35d650f867da0e803515e2 | Python | 3,738 | 88 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_t... |
8d7b011e99b82a68400ab5fa1329c90931fc2455a3a130456022547abd197ade | Python | 3,738 | 88 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_t... |
c2d1219fc498a4f35a8af27a37b1db577e6499593c0dc27505e12f8553c027b0 | Python | 3,738 | 88 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_t... |
ce7ef50cd78f446462e02936f129cc9cf2528e48e2bf1ffcec60eb82fc7f5849 | Python | 3,738 | 88 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_t... |
19f38da22cad797da653ea80bac5d1dafe4127a6532b7742a7bc71a0ddf72ba3 | Python | 3,739 | 90 | """02. Train Image Classification with Auto Estimator
=====================================================
This tutorial goes through the basic steps of using GluonCV auto estimator to train an image classifier
with custom hyper-parameters.
"""
##########################################################
# Train with ... |
4982c7f23f7e8805c591df3d149a922ca7bd6cd47dc65c4ff4a624b0d0718e0e | Python | 3,739 | 105 | """Decoder module of Monodepth2
Code partially borrowed from
https://github.com/nianticlabs/monodepth2/blob/master/networks/pose_decoder.py
"""
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use onl... |
562ece34b33b7ead7df1b5b21ccd02f289180ee53d465e1d2f76da3162425d88 | Python | 3,739 | 121 | """Transforms embeddings to two-dimensional space for visualization."""
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import numpy as np
if TYPE_CHECKING:
from numpy.typing import NDArray
class PCA(obje... |
49f8879876e303a4b0559ac89e2a495c5f55ff6fb50f381aecf734b000d15958 | Python | 3,740 | 85 | import numpy as np
from numpy.matlib import repmat
from matplotlib import pyplot as plt
import pandas as pd
from OscopeBootstrap.pseudotime import estimate_pseudotime_using_spectral_embedding, calculate_metrics, \
plot_latent_space, plot_gene_fits, plot_correspondence_of_peaktime_and_times
def reproduce_figures(... |
7252b64c6d171df16ad8c25e0cd8d3bdd307e40d5bd1caeca4b00cae012b3dcd | Python | 3,740 | 106 | import numpy as np
import scanpy
from anndata import AnnData
from numpy.random.mtrand import RandomState
from scipy.sparse import spmatrix
def run_pca(
data: AnnData | np.ndarray | spmatrix,
n_comps: int = 50,
zero_center: bool | None = True,
svd_solver: str = "arpack",
random_state: int | RandomS... |
e21763a486df024c3b3bf6a4624761107232617b7c02d966f7a6eb2e68f7a4a2 | Python | 3,740 | 118 | import boto3
import json
import pathlib
import os
class TexTract(object):
def __init__(self):
self._parentdir = pathlib.Path(__file__).parent.absolute()
self.api_fpath = os.path.join(self._parentdir, "api_keys", "aws.json")
self.service_name = 'textract'
self.region_name = 'us-we... |
29e96e976a8ced0dd9a706526590f8e90573ccc9773863f4015610bc7eda398f | Python | 3,743 | 117 |
import numpy as np
import skimage
from skimage import feature as skfeature
from skimage import registration as skreg
from . import lkp_
from . import gk_
from . import clg_
from .warps import Warp
try:
# https://github.com/pyimreg/imreg
import imreg.register
import imreg.model
import imreg.sampler... |
6a5b0ca13b251f1e07c729d5d8084d4524f4e475b81023b93da83cdb1e225f3d | Python | 3,743 | 88 | from typing import List, Tuple
from warnings import warn
import torch
from torch import Tensor
class MultiViewCollate:
"""Collate function that combines views from multiple images into a batch.
This collate function processes a batch of tuples, where each tuple contains
multiple views of an image, a lab... |
446889033a5a0c65ec4cb85b61e0b0b96467785d727e3344bb8dd8a74b4b468e | Python | 3,744 | 89 | # %% [markdown]
# # Write OME-ZARR images
# (basic:write)=
#
# Writing ome-zarr images is primarily exposed through the {py:class}`ome_zarr.classes.image.OMEZarrImage` and {py:class}`ome_zarr.classes.image.OMEZarrMultiscales` classes, which provide a high-level API for creating and manipulating OME-ZARR images and pyra... |
7454ed2eaba8f95536169b8c87949f600cd5cdceb5860dd856c2e8e5edbd7406 | Python | 3,744 | 91 | """Check ID coding with synthetic rows in an isolated temporary repository."""
import csv
import shutil
import stat
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FIELDS = ["Subject", "Gender", "TBV_mm3", "BNST_left_mm3",
"BN... |
86578ba755d94995ce42123da3a143cfbd6812c4ff9b5401e4dcd302e6c6e328 | Python | 3,744 | 116 | import sys
from functools import reduce
import pickle
import numpy as np
import paddle
def load_pkl(file_path):
"""加载 .pkl 文件"""
with open(file_path, 'rb') as f:
return pickle.load(f)
def compare_arrays(array1, array2, path=""):
"""比较两个 numpy 数组是否相等"""
# print(array1)
# print(array2)
... |
e5eb7b99ebfcf14cff4aff1fc22372ce11cd4ae0a0f9938c9ce131383f163b21 | Python | 3,744 | 100 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import tensorflow as tf
import pandas as pd
import argparse
import os
import time
import sys
import pwd
import pdb
import csv
import re
import deepchem... |
1134b9229bf094fe789316e5cf89d5798d182a70a0050e70b9e6e26edb471877 | Python | 3,745 | 115 | from typing import Dict, List, Tuple, Union
from lightly.transforms.jigsaw import Jigsaw
from lightly.transforms.multi_view_transform import MultiViewTransform
from lightly.transforms.torchvision_v2_compatibility import torchvision_transforms as T
from lightly.transforms.utils import IMAGENET_NORMALIZE
class PIRLTra... |
2b957c0486a16bef3e7b066f855014c55f4c23ae1dbba1dc2aee26b3525dc911 | Python | 3,745 | 123 | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class Capsule_Mul(layers.Layer):
def __init__(self, num_classes):
super(Capsule_Mul, self).__init__()
self.num_classes = num_classes
def build(self, input_shape):
# -*- batch_size use... |
bab7dc82ebad0191ee50f601d93c62235c064e5d74bc68d1aea161597d9d353d | Python | 3,746 | 118 | """
stats.py — canonical statistics primitives for the framework series.
Single source of truth for cohens_d, cohens_d_with_ci, and related
helpers used across the empirical papers (4, 5, 6, 7). Earlier per-paper
re-implementations diverged in NaN handling and return shape; this module
consolidates them.
All function... |
98c80923f18a6e4d2ffe83014aced63d6811928e50a1c3e0c5611424f101a971 | Python | 3,747 | 98 | from mne.utils import check_random_state
from typing import Iterable
import numpy as np
'''
This module provides mass univariate permutation tests for mutlidimensional
arrays. Note that the (univariate, not cluster-based) permutation test
provided in MNE as mne.stats.permutation_t_test applies a t-max correction
for... |
aa840357af147ed96062b0ff2682364eada2c568debbd620d6b0d39d4ad60f61 | Python | 3,748 | 121 | import numpy as np
import torch
from HD_BET.utils import SetNetworkToVal, softmax_helper
from abc import abstractmethod
from HD_BET.network_architecture import Network
class BaseConfig(object):
def __init__(self):
pass
@abstractmethod
def get_split(self, fold, random_state=12345):
pass
... |
e8ae938b17582c4a6c82d3878609bb0331416d5f2bbf7cb6ae5f2cfd637fbcbb | Python | 3,748 | 68 | import skmob.measures.evaluation as sk
import math
import numpy as np
class TestEvaluationMetrics:
def setup_method(self):
self.ground = [1,2,3]
self.prediction_a = [1,2,3]
self.prediction_b = [2,2,2]
self.prediction_c = [3,2,1]
def test_r_squared(self):
assert(sk.r_s... |
6a2469bc3328a3384182856973a3a0389bdaaee565e605a036adbb89343016b4 | Python | 3,749 | 94 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd
import sys
import scipy
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_total_3anc = []
... |
6ada80f61cec9ebd726b57f1e7ccd7ec432786522e1f81e77e7926a457f454b4 | Python | 3,749 | 94 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd
import sys
import scipy
import os
import pydot
import pydotplus
import random
import pickle
import fileinput
SCALE=100000
chr = sys.argv[1]
def get_fragments_lengths(prov_vector):
lengths_counts_3anc = []
lengths_total_3anc = []
... |
d0594ca7c68995c1689ae853341f9b8d9093f63609504ba78ee41f00a832ad00 | Python | 3,750 | 101 | import importlib
import math
import numpy as np
import pytest
import torch
from PIL import Image
from lightly.transforms import (
BYOLTransform,
DINOTransform,
SimCLRTransform,
SwaVTransform,
)
from lightly.transforms.multi_view_transform import MultiViewTransform
from lightly.utils import debug
try:... |
ed1d75d5e35b0ffc81dddaf700a076ce3a68e9c66673eee64190b7ccde679ec5 | Python | 3,750 | 102 | """Test functions for specparam.data.periodic."""
import numpy as np
from specparam.data.periodic import *
###################################################################################################
###################################################################################################
def test_... |
2399aea7f65598252d4dbb58c7d67fbed215c597c72fb6c3e09e906031518221 | Python | 3,751 | 105 | """Default-path guarantees (memo sec 4.4 / 8.1 item 10 / D19 provenance).
Two pins protect everyone who never touches meta: ordinary captures are
byte-identical with the weightsfree machinery quiescent (W1 and W1-CTX touch
the recording path), and the ambient-device-context row is pinned per D19's
disposition.
"""
fr... |
f6dd356eab5769a78d181c4af34e81fb86b7f7635eb9337fd4bd4c835fe5bb8f | Python | 3,751 | 92 | """1. Predict with pre-trained Mask RCNN models
===============================================
This article shows how to play with pre-trained Mask RCNN model.
Mask RCNN networks are extensions to Faster RCNN networks.
:py:class:`gluoncv.model_zoo.MaskRCNN` is inherited from
:py:class:`gluoncv.model_zoo.FasterRCNN`.... |
051283b2ac1fb132f91919a656d55762790995b1f4f1870d72cc8187f4c8afed | Python | 3,752 | 106 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 28 16:24:25 2022
@author: psicobiologia
"""
import pickle
import scipy.io
import numpy as np
import nibabel as nib
from sklearn.decomposition import PCA
import scipy.stats as st
from sklearn.model_selection import GridSearchCV, cross_val_score, cro... |
9a7cfa2467f8f7e20a40c84d36ca0da1e73d761338ce110ba5bdd72201264bca | Python | 3,752 | 127 | import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateOptimizer
from .utils import get_opt
from .utils import normalize_img
from .utils import reset
# get current tf minor version
tf_version = in... |
f4ca797a7698570c49812fd7612ebb22514ce83a25c655ec1049bff6e34014e0 | Python | 3,752 | 103 | import os
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.imagenet_models import ipcl_models
from robustness.imagenet_models.custom_modules import SequentialWithAllOutput
import torch
from PIL import Image
from model_analysis_folders.all_model_info import IMAGENET_PATH, MO... |
fc445433ec460e6f41dcb8cd2617d237a1a7e8e7d438daa43c40d9eefa3e1d87 | Python | 3,752 | 119 | from types import SimpleNamespace
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from modular_splicing.motif_perturbations.summarize_effect import (
positional_effects_near_splicepoints,
)
def effect(pert, num_motifs):
full_data = positional_effects_near_splicepoints(
... |
e3321a77901c1d91939546b46724e110f955462c14a91f762ff6b967d0329ec7 | Python | 3,753 | 101 | import os
import pickle
from Configurations import config as cfg
from Utilities.common_packages import np, tf
from nn_model.modelgenerator import tf_model, OnEpochEndCallback, modeltracker
from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger
from tensorflow.keras.optimizers import Adam
from tensorflow.ker... |
a0497d9d532065682689b7b4dc803a64141dc46eacb26faba0e9907b490aeac7 | Python | 3,754 | 88 | from ovseg.model.SegmentationModelV2 import SegmentationModelV2
from ovseg.preprocessing.SegmentationPreprocessingV2 import SegmentationPreprocessingV2
from ovseg.model.SegmentationEnsembleV2 import SegmentationEnsembleV2
from ovseg.model.model_parameters_segmentation import get_model_params_3d_UNet
from ovseg.utils.io... |
ab7cafea661e6f85b4a5c5b1d74c5c8c1cb3ffb6c05decc04a6e13e55f9a2640 | Python | 3,756 | 83 | import torch
import torch.nn as nn
#from equivariant_attention.modules import get_basis_and_r, GSE3Res, GNormBias
#from equivariant_attention.modules import GConvSE3, GNormSE3
#from equivariant_attention.fibers import Fiber
from util_module import init_lecun_normal_param
from se3_transformer.model import SE3Transform... |
286b6ac9e22c34e61166dfe0f445ff6f36101e4c15a89e2b52f1d95a8a041c3c | Python | 3,757 | 132 | import os, sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if BASE_DIR not in sys.path:
sys.path.insert(0, BASE_DIR)
try:
from biomedisa_app.config import config
except:
from biomedisa_app.config_example imp... |
0cd41bbb00aaddcd5535233b0974d1fc26b7c40f9d6925110213e35fd1f4c55d | Python | 3,759 | 110 | try:
from gdrive_fsspec import GoogleDriveFileSystem
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
except ImportError:
GoogleDriveFileSystem = None
from datetime import datetime
from typing import (
Annotated,
)
from fsspec import AbstractFileSystem... |
fa49b3fbaa8e1c6e4f1de5ba6d4863b085158ef1c8421b4b0355ef1160dcbe21 | Python | 3,759 | 103 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
05ee17ca67516198812b1ae8164f19da144c413314618c56948373c9e88c3f7a | Python | 3,760 | 92 | import multiprocessing
from multiprocessing import Pool
import numpy as np
import os
import pandas as pd
import random
from tqdm import tqdm
from pymatgen.core.structure import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.analysis.diffraction.tem import TEMCalculator
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.