sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
b2494b9fafc6c5e5844dbb935142179c9c23ff992d24900948bedcbecc999da4 | Python | 7,096 | 207 | import math
import numpy as np
import pandas as pd
# disease = ["Meningitis, Pneumococcal", "Meningitis, Pneumococcal", "Mycetoma", "Botulism", "Botulism2", "Botulism3"]
# id = ["C01.252.200.500.600", "C08.345.654.570", "C01.252.410.040.692.606", "C01.252.410.222.151", "C01.252.410.222.151", "C03.252.410.222.151"]
pr... |
b27427b7f09803c19a6f4f8537ebed2a532b593ab92b7bcd07a5bfbe45d5fb29 | Python | 7,096 | 210 | import math
import numpy as np
import pickle
import time
from manfit_our import manfit_our
from manfit_cf18 import manfit_cf18
from manfit_km17 import manfit_km17
import matplotlib.pyplot as plt
import scipy.io
# xiayq @ 12/11/2022
# xiayq0121@zufe.edu.cn
# refered to Z. Yao and Y. Xia, Manifold Fitting un... |
fcbcdc4d921bfaa9aac125e06466bcca15d1bf774efaa2569d1d110917f3265c | Python | 7,097 | 177 | import os
from unittest.mock import Mock, patch
import click
import pytest
from click.testing import CliRunner
from celery.app.log import Logging
from celery.bin.celery import celery
from celery.bin.worker import _concurrency_value
from celery.worker.consumer.tasks import Tasks
@pytest.fixture(scope='session')
def ... |
c3721e950f16a6373cbe0e5f1e6ac83954d58589c72f88df07c02d10cc410b45 | Python | 7,098 | 245 | """Plots for different data types / layouts."""
from itertools import repeat
import numpy as np
import matplotlib.pyplot as plt
from spiketools.measures.circular import bin_circular
from spiketools.utils.options import get_avg_func
from spiketools.plts.annotate import add_vlines, add_text_labels
from spiketools.plts... |
a541857313929d0c212884f39638564ee97a6ace1fb65ea39fbd7d75936f1eae | Python | 7,099 | 170 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import acb
from model.acb_old import ACBlock
from model.diversebranchblock import DiverseBranchBlock
def default_conv(in_channels, out_channels, kernel_size, bias=True, deploy=False, norm="batch"):
return nn.Conv2d(
... |
b9eff016c649b55343dca09d7a6209439ab99f30ed384a651611d56108040fc4 | Python | 7,100 | 186 | 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 sys
import pwd
import pdb
import csv
import re
import math
import time
de... |
bbccc137caa161c01405695fafacac953cb19c0717261762327142df8869cea3 | Python | 7,100 | 168 | """Tightness oracle for EXACT receptive-field claims.
The check()/cross_validate tripwire is one-sided: it proves gradient support is
INSIDE the geometric box, so an oversized-EXACT rule passes containment, and
the adjoint corner cross-check consults the same rule registry through the
opposite-direction engine, so a s... |
a420828970d735b26ee4f3987203ce8849eea493873b4d2cc5c6506eba23de2c | Python | 7,101 | 170 | import contextlib
import os
import random
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
import torch
from torch.utils.data.dataloader import DataLoader
# from torchsummary import summary
from hn_cnn.cnn import MODELS
from hn_cnn.constants import *
from hn_cnn.data_augmentation import ... |
a08a2fdacaac8a6fe973135c3e4ee3becac094dec63593c362c3560f7f94bda7 | Python | 7,102 | 177 | #Autor: Carlos Alberto Hernández Nava
#ASVspoof2017 MFCC extractor an convert to csv
import cv2, os, sys, csv
import numpy as np
import pandas as pd
import librosa
import soundfile as sf
import matplotlib.pyplot as plt
import scipy.io.wavfile as wav
from sklearn import preprocessing
import seaborn as sns
pathwav1="/A... |
472f82cdac9ea1aa46f2e30c143029433dfd15580e09bec5c515dd9a05850be0 | Python | 7,103 | 153 | import unittest
import numpy as np
from bdpy.feature import normalize_feature
class TestUtilFeature(unittest.TestCase):
def test_normalize_feature_1d(self):
feat = np.random.rand(4096)
feat_mean0 = np.random.rand(1, 1)
feat_std0 = np.random.rand(1, 1)
ddof = 1
feat_mea... |
389a536aa08d74b1088228df600dbec52a9d940ab1efa32df7761d85dd051b0e | Python | 7,106 | 120 | #!/usr/bin/env python3
"""Data-layer provenance guard — v3 (2026-06-16, post atomic swap).
After the v3 swap the data layer is: per-epoch PRIMITIVE-ONLY caches, one v3 stamp
across all cohorts, composites computed solely by canonical_composite/assemble_composites.
The consumed/deferred distinction is RETIRED (no cache... |
5e8d3df0bd252cdc847fa268d8fb431b0fe173d8da461150e07abbfbb5c2b7c8 | Python | 7,106 | 168 | from locale import normalize
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Code suppressing TF warnings and messages.
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import sys
import argparse
import numpy as np
import cv2
import matplotlib.pyplot as plt
sys.path.append("../")
sys.path.append("/home/attilasimko/Docume... |
a9b1c63d4570a4b75d85264ab20195aea703b7ee7922354cbe63d01c91555188 | Python | 7,106 | 213 | """
Data providers that iterate over a source that is not in memory
or not in a file.
"""
import gzip
import logging
import subprocess
import tempfile
from urllib.parse import (
urlencode,
urlparse,
)
from urllib.request import urlopen
from galaxy.util import (
DEFAULT_SOCKET_TIMEOUT,
requests,
)
from... |
f8ffc4ef58495d44039e1153a7b598e66e542fd2155d8188237775442417ac38 | Python | 7,106 | 193 | import piq
import numpy as np
import torch
def _to_torch_pair(ref: np.ndarray, img: np.ndarray, device: str = "cpu"):
"""
Convert numpy arrays to torch tensors with shape (1, 1, H, W).
Convention:
ref = reference / target
img = test / prediction / reconstruction
"""
assert ref.sha... |
1d5845fe57e863b95fb52d9b2488e91bbf077497c05c7b8128c0d9b17deeeb4c | Python | 7,107 | 187 | import numpy as np
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
import torch
import torch.nn as nn
import torch.nn.functional as F
from hn_cnn.constants import *
from hn_cnn.metrics import get_accuracy, get_threshold, get_threshold_pr, compute_ci
class ImageClassificationBase(nn.Mod... |
c82b16c05b225cb40a0c7595d17a072acc9e2acb8b9a849672010413e4d9acb9 | Python | 7,110 | 150 | """PAD000016 的 run x visit x arm 交叉表 —— 回答一个审稿人必问的问题。
为什么单列一个脚本(2026-09-25,预审 P1-10):
Table 1 里 PAD000016 写着 "2 runs (40 / 40 samples)"。审稿人看到"两批 + 配对设计"
立刻会问:**run 与 visit 是否共线**?若第一个 run 全是基线、第二个 run 全是随访,
那么所谓"6 个月的位移"就分不清是时间效应还是批次效应 —— 这是本文自己在
Section 2.4(单批标准化纪律)里提出的严格要求,必须用同一把尺子量自己。
本脚本把交叉表算出来、落盘、并**显式断言**平衡性,而... |
fe22f7e7d0f114775545b45e7e85dbfbd61dccbb659cde72cd66d677f59034c5 | Python | 7,112 | 254 | """Canonical comparison helpers for TorchLens golden pickle parity tests."""
from __future__ import annotations
import weakref
from dataclasses import fields, is_dataclass
from typing import Any
import numpy as np
import torch
from _pickle_compare_allowlist import allowed_pickle_diff_fields
from torchlens.data_clas... |
d8e82360e82c665e0a1eb8413cffef04eda55a23a1a3be3a1f77ecc454b40bd9 | Python | 7,114 | 171 | from typing import List, Tuple
import torch
from pytorch_lightning import LightningModule
from timm.models.vision_transformer import vit_small_patch16_224
from torch import Tensor
from torch.optim import AdamW
from lightly.loss import DINOLoss
from lightly.models.modules import DINOProjectionHead, MaskedVisionTransfo... |
ede4f8e3a7e508f3d797597810fb69b04623b630dad252762be880bb1a7afaa7 | Python | 7,114 | 172 | """tvscope row gate: the CLIP round-trip invariant (config-built, zero network).
The audience's mandated CLIP case on the R0 config-built CLIP fixture: the
site inventory answers ``visual_projection`` with a working spelling, EVERY
emitted module-origin selector extracts keyed by the requested string, the
manual proje... |
3028438cac8f77a1061820aa863efc03cc98696af18f2dc21c05b684fb9ec3ad | Python | 7,117 | 226 | # -*- coding: utf-8 -*-
""" Instantiates the server
"""
from abc import abstractmethod
import asyncio
from functools import reduce, wraps
from io import BytesIO
import itertools as it
import json
from operator import add
import warnings
import numpy as np
from PIL import Image
import sanic
from sanic import Sanic
fro... |
6c9fc1491dbb6febfe002474a52e2f806de66e66dcf71f45265f4538969c0cf2 | Python | 7,117 | 174 | import numpy as np
class Graph():
""" The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of the follow candidates
- uniform: Uniform Labeling
- distance: Distance Partitioning
- spatial: Spatial Configuration
For more informa... |
1c560fdc2d475abbb8a3a8876782dd94577229f1298c327b336aba027b58694f | Python | 7,118 | 226 | """
Utility functions for SMOT: Single-Shot Multi Object Tracking
https://arxiv.org/abs/2010.16031
"""
import time
import logging
from contextlib import contextmanager
import mxnet as mx
import numpy as np
def timeit(method):
"""
The timing decorator to wrap the functions
"""
def timed(*args, **kw):
... |
c1a4b37761999e44291390b7c996897680957b90f77478732b1e2ac3f85d4817 | Python | 7,119 | 161 | """
Provide a general object detector interface for SMOT
"""
# pylint: disable=unused-wildcard-import,wildcard-import
import logging
import numpy as np
import mxnet as mx
from gluoncv.data import COCODetection
from .utils import mxnet_frame_preprocessing, timeit_context
from .utils import remap_bboxes as _remap_bboxe... |
2dfe22fa11827c6905f80c5a24f7c937ff3c825277b88b8ce84501f95db1715e | Python | 7,121 | 149 | """Non-local block for video action recognition"""
# pylint: disable=line-too-long,too-many-lines,missing-docstring,arguments-differ,unused-argument
from mxnet.gluon.block import HybridBlock
from mxnet import init
from mxnet.gluon import nn
from mxnet.gluon.nn import BatchNorm
def build_nonlocal_block(cfg):
""" Bu... |
9352ea84a322bb611eeb6f01d3614ee72efe864db744109764ba3a4c982b4760 | Python | 7,121 | 231 | import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim.lr_scheduler as lr_sched
from pointnet2_ops.pointnet2_modules import PointnetFPModule, PointnetSAModule
from torch.utils.data import DataLoader, DistributedSampler
from torchvision import transforms
imp... |
cb9c4014523646c3f290f6b38caaf4e830a91679a2cc0826d349cd837871eab2 | Python | 7,121 | 228 | """Tests for xcp_d.utils.confounds."""
import re
import numpy as np
import pytest
from scipy import signal
from xcp_d.utils import confounds
def test_modify_motion_filter_raises_for_invalid_lp_params():
"""_modify_motion_filter raises ValueError for invalid low-pass params."""
TR = 0.8
with pytest.rai... |
a62ea3b1b02c5cf16d8093d41c58f8501a03c4341e4dbe8ef994a729d6fa06f9 | Python | 7,122 | 200 | # -*- coding: utf-8 -*-
import logging
import numpy as np
class RAP:
def __init__(self, rap_volume, propagator):
"""
rap_volume: DataVolume
Region-Adaptive Propagation tractography volume.
propagator: ODFPropagator
The propagator.
"""
self.rap_volum... |
dc2c511cd10d76fb7c04f15c3fb4acf2377e0b064fc6f280e088a100bf437925 | Python | 7,123 | 187 | import nfp
import numpy as np
import pytest
from nfp.frameworks import tf
layers = tf.keras.layers
@pytest.mark.parametrize("layer", [nfp.EdgeUpdate, nfp.NodeUpdate])
@pytest.mark.parametrize("dropout", [0.0, 0.5])
@pytest.mark.parametrize("output_dtype", ["int32", "int64"])
def test_layer(smiles_inputs, layer, drop... |
3cb8a2ba32f0ff4078c4be4d4c3d1629875d53f5748e831581b188e2cd115ebc | Python | 7,125 | 181 | # -*- coding: utf-8 -*-
import os
import sys
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
corrmap)
import matplotlib.pyplot as plt
import numpy as np
def fit_ica(raw, fmin=1., fmax=40., tmax=300., n_components=0.95, method='fastica', max_iter=200... |
dbae475ae5313e080235c21e587037a7e2c30e24559dec70160c261c68163876 | Python | 7,125 | 227 | import logging
import os
import subprocess
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.configuration import Configuration, kinds
from pip._internal.exceptions import PipError
from pip._internal.locations import venv_config_file
from pi... |
64cad3119e6b8035a70517a5b37550466fd0058d07be17145f0c0578924524c0 | Python | 7,126 | 173 | # -*- coding: utf-8 -*-
import sys
import os
sys.path.append('./src/')
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ExponentialLR, StepLR
from torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts
import math
import random
import numpy as np
from tqdm import tqdm, tr... |
46be05818113b9af27dab3e6bb56de5502337ef885ab5d507865d4a3d0c49127 | Python | 7,127 | 195 | """F12 pins: the display filter (N9) -- tokens, polarity, disclosure,
bridged edges, and the teaching boundary raise.
Composition-test rows covered: 8 (filter-token yield disclosure), 9 (the
raw-predicate boundary raise names the real attributes and the token
remedy), 14 (bridged-edge label spelling: midpoint label=, ... |
845da40405f8021f78762f05c10640097039e0f4457eb29677bc43f8b51f0813 | Python | 7,127 | 230 | from typing import Optional, Union
import numpy as np
from pyvista import MultiBlock, PolyData, UnstructuredGrid
from ..models import collect_models, multiblock2model
from .utils import _interactive_plotter
##################################
# Picking by entering parameters #
##################################
def... |
85d60d9c695794efa96d7abea60faadb7500ad2e4ef229bf6271cc8fabd133bd | Python | 7,127 | 181 | #!/usr/bin/env python3
"""
Dx BH — FTD-vs-HC + AD-vs-FTD redo under proper per-fold
=========================================================
§3.11 numerical rerun. The same 15-feature pipeline (rank-norm
deployment-mode pre-fit + HC-anchored whitening + Quad-LDA), with
two different label setups:
A) FTD-vs-HC: pos... |
ab4e1fef6801d492112bd174453fc686329ae79ed0bc5a5046e2e213e6a804c7 | Python | 7,128 | 220 | from __future__ import print_function
import torch
import torch.nn as nn
from IPython.core.debugger import set_trace
import sys
from robustness.imagenet_models.custom_modules import FakeReLU, SequentialWithArgs
__all__ = ['alexnet_gn']
class ReluSequentialWrapper(nn.Module):
def __init__(self):
super(Re... |
c9e2dd694e60b1539ead3f4f0ea9d3c15d1bc3664c7064fe7760d092c67fa1b7 | Python | 7,128 | 216 | """The refusal-contract driver (compo waves A-D; the three test laws, foldB D18).
Law 1: every protective claim gets a test that TRIES the forbidden thing and
asserts the refusal fired. Law 3: the refusal fired for the RIGHT REASON --
stable ``fields['code']`` plus the failed predicate named in the message.
Each row b... |
431ffd36c34f359aa813cc464dfdd6b97495e02c1582a53c5d345b69302a21b7 | Python | 7,129 | 190 | """HOOK-BAND spike: torch-version-band assertions for the read engine (F04).
M(reads) section 4's release-gate spike, CPU half: the five torch facts the
one-backward design sits on, asserted on the SUPPORTED band so a torch
upgrade that changes any of them fails loudly here rather than corrupting
reads silently. The C... |
a1b915a9c56cbb3e6acde73cacbea252b516835a1c22b6b809f90bda0b031545 | Python | 7,130 | 165 | import utils
import csv
import matplotlib.pyplot as plt
from scipy.stats import genpareto
import graphutils
import graph
import pandas as pd
def FitDistribution(data, label):
PathlengthXYZ = []
Ids = []
for dataPoint in data:
ID = dataPoint['track ID']
path_ = dataPoint['DisplacementXYZ']
... |
8d46e4393b6711919da0ba53dd62850a5602f4c617e4432b08299eef2ba95867 | Python | 7,131 | 173 | """
Voxel prediction analysis using fMRI data from Norman-Haignere et al. 2015
Follows same analysis as used in Kell et al. 2018
Please cite the assciated papers if you use this analysis pipeline.
@article{norman2015distinct,
title={Distinct cortical pathways for music and speech revealed by hypothesis-free voxel ... |
b0f2ffbfa12c52530969e5b0a8874cb6caa9e265431c2b616695927f80fb3bae | Python | 7,133 | 216 | from __future__ import annotations
import hashlib
from collections.abc import Generator
from functools import reduce
from typing import Any, Optional, TypeVar
import toml
def dump_config(config: dict) -> str:
"""Returns a string representation of the config in toml file form. To get a merged
representation,... |
b750d026aaf3a7f5abac1a5009a5a5fdbdde8e4527ca83cebfc1468306b9429f | Python | 7,133 | 226 | import os
import sys
import datetime
from collections import defaultdict
from pathlib import Path
import json
import warnings
import pprint
import copy
import numpy as np
from numba.core.errors import NumbaPerformanceWarning
import torch
from src.utils import Logger, Timer, save_model, save_vars, unpack_data
import s... |
e619310efb5b2544b05e9b1e09d96196788daf94789ea942fea186d54f9c1f3b | Python | 7,133 | 146 | import sys
import argparse
from acdc_nn import util
from acdc_nn import nn
import numpy as np
import pandas as pd
from pkg_resources import resource_filename
import functools
def load_nn(weight_path):
num_H=[32,16]
d=0.2
model1, model2 = nn.build_acdc_3d(num_H,d,25)
weight_path = resource_filename('acdc_nn', '... |
f583d6c9b57f37a57490341f8924552db8c4d0a92a1ce8349b3220099d22b068 | Python | 7,134 | 181 | """Classics corpus: coverage-chosen hand-built models checked end to end.
The corpus (``tests/classics_corpus/``) is a sample of hand-built historical and
unusual architectures, chosen greedily for coverage of capture features (op
functions, module types, recurrence, conditionals, in-place ops, dtypes, input
and outpu... |
ab9e0bf5a56bc50cc39f979899fa1ef7fd78b5117eb93e8b3e76c2ab057f39fe | Python | 7,137 | 177 | """
melspec.py -- pure numpy/scipy log-mel spectrogram, byte-matched to
librosa.feature.melspectrogram + librosa.power_to_db at the exact
parameters the CNN classifier (see classifier.py) was trained with.
Why this exists instead of just calling librosa: this module runs on the
Pi, where `librosa` would be a heavy dep... |
347a0b7b5fceeb98d06a09562946727318765550e853bf9c3498348e2efed3a3 | Python | 7,138 | 191 | """Platform save-path regressions from the nightly macOS/Windows canaries.
Windows: ``os.fsync`` there is ``_commit`` -> ``FlushFileBuffers``, which needs
a write-capable handle, so fsyncing a read-only descriptor fails with
``EBADF`` ("Bad file descriptor"), and ``os.open`` on a directory raises
``PermissionError`` (... |
9a750eab061931de7e0ae4c4433cca556b3c4f7640562611228620745417a9ba | Python | 7,139 | 210 | """
====================================================================
Motor imagery classification by transfer learning
====================================================================
In this example, we use transfer learning (TL) to classify epochs from a
subject using a classifier trained on data from anothe... |
4b2aa0701b77026b527f8257558c0959e651629395d23695dc13ec79a1e72ab5 | Python | 7,140 | 207 | import math
from typing import List, Tuple, Optional, Union
import torch
from torch import nn as nn
def pixel_freq_bands(
num_bands: int,
max_freq: float = 224.,
linear_bands: bool = True,
dtype: torch.dtype = torch.float32,
device: Optional[torch.device] = None,
):
if lin... |
500054aa0e8f691d2787c45ab0a319992f89ae595f0121578f9ac68eca5b84bb | Python | 7,141 | 128 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
6a7a3676319bfdedff2d4e3f70b1c810915dccc85382f4d05adf37ca4e22245e | Python | 7,141 | 116 | """5. DistributedDataParallel (DDP) Framework
=======================================================
Training deep neural networks on videos is very time consuming.
For example, training a state-of-the-art SlowFast network on Kinetics400 dataset (with 240K 10-seconds short videos)
using a server with 8 V100 GPUs take... |
3452be6d5883d749a12eb2f4ec441cf55aa092913faa80badca46908d095d8da | Python | 7,142 | 214 | """
=========================================================================
Frequency band selection on the manifold for motor imagery classification
=========================================================================
Find optimal frequency band using class distinctiveness measure on
the manifold and compare c... |
e49ac2e5fc9e1c18d49e743c6fe52ebf4b536a693c00651b796751cd14f8f06b | Python | 7,143 | 124 | import warnings
warnings.filterwarnings('ignore')
import argparse
from pathlib import Path
import json_tricks as json # Allows to load integers etc. correctly
import pytorch_lightning as pl
import torch
from torch.utils.data import DataLoader
from scene_graph_prediction.scene_graph_helpers.dataset.or_dataset import... |
2e3d46a4ad7e19b95c7198f89040bc3472204716c2d2810e617f3535169775e8 | Python | 7,144 | 193 | import logging
import os
import subprocess
import time
from dataclasses import dataclass
from string import Template
from typing import (
Any,
)
from typing_extensions import Protocol
from galaxy.util import (
RWXR_XR_X,
unicodify,
)
from galaxy.util.resources import resource_string
from ..fork_safe_write... |
32ab70f6c5fdd31ed15772d233525fe81975996c4dd8f606192d6b87f435f7fd | Python | 7,145 | 200 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Simple MAF on Z-matrix coordinates.
"""
# ====================================================================... |
991fb73c703dd1ee97d9e40200f8786187a92e68f6ef4662ebd021a7f25343e6 | Python | 7,145 | 170 | import contextlib
import os
import random
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
import torch
from torch.utils.data.dataloader import DataLoader
# from torchsummary import summary
from hn_cnn.cnn import MODELS
from hn_cnn.constants import *
from hn_cnn.data_augmentation import ... |
04b7c1ce85c56f84155019b741d3e95fe8131b55aa741f9ca609833458689f3a | Python | 7,146 | 200 | """
Shared helper functions.
License: MIT
Author: Nick Semenkovich <semenko@alum.mit.edu>
"""
from __future__ import print_function
import glob
import os
import shlex
import time
import tempfile
import yaml
from distutils import spawn
from subprocess import Popen, PIPE
if __name__ == '__main__':
print("Do not r... |
35a17829b8dc67034af225317161add185f84c546bf5d953ffb0921c1a87924b | Python | 7,151 | 207 | # Reads the raw DNA reads, filters out those that don't look like barcode reads, and sorts by barcode
import sys
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
import io
import os
from collections import Counter
from utils import *
import argparse
parser = argparse.ArgumentParser()
parser.add_argum... |
06059b713a99d1d85bfb2d9b3b7354b6a75d95664fbfa358fce6e968dc1d5a9b | Python | 7,152 | 172 | #!/usr/bin/python
#-*-coding:utf-8-*-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apa... |
f11ccc16df1e32df0a8109c9a2a6d16a86ffd9fc3374840d542c051634a12a8c | Python | 7,152 | 206 | """
ml.py: Classes for introducing a second set label to a dataset; computing the
DeCorr, HalfCorr, and DeCov loss functions; and creating one-target and
two-target multilayer perceptrons.
"""
__author__ = "Louis Kang"
__date__ = "2023/03/07"
__license__ = "GPLv3"
__reference__ = "To be determined"
... |
e40309d3f5907ee9b818f0060218f972c22e3192771c9102c51c623ca796c16a | Python | 7,153 | 194 | from collections import OrderedDict
import codecs
import numbers
import numpy as np
from afmformats import meta
import nanite.model as nmodel
from PyQt6 import QtCore
from .. import units
#: Valid export choices in `save_tsv_metadata_results`
EXPORT_CHOICES = list(meta.META_FIELDS.keys()) + [
"params_ancillary"... |
10fb67371ecb8c7e44f073138b31c6418056f4a0b9f05c5899c6865aae06033a | Python | 7,154 | 191 | import torch
import logging
import torch.nn as nn
import torch.nn.functional as F
from einops import repeat, rearrange
from lego_blocks import FixedPositionalEncoding, Fluffy, Sherlock, Megatron
from pytorch_lightning import LightningModule
logging.getLogger().setLevel(logging.INFO)
from torch.optim.lr_scheduler impor... |
51d1e7efc50d44581d84c4123fcc394744861eba8747514c5ed6e7bb349ea568 | Python | 7,154 | 167 | import logging
import pysam
from svim.SVIM_intra import analyze_alignment_indel
from svim.SVIM_inter import analyze_read_segments
def bam_iterator(bam):
"""Returns an iterator for the given SAM/BAM file (must be query-sorted).
In each call, the alignments of a single read are yielded as a 3-tuple: (list of p... |
edebc83158d89744f0d75277076a311d34788873e0d307134b43f70fee52b7cc | Python | 7,155 | 196 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 14:40:21 2021
@author: Audrey Mazancieux
This script performs Finite Impulse Response (FIR) analysis at the group level.
It uses output data of the FIR_singleSubj script.
"""
import glob
import math
import matplotlib.pyplot as plt
import numpy... |
159d63e74b1ca20af0ed254249dc9aef12467a6a360a7ccb995deed34fe45e0a | Python | 7,160 | 205 | import torch
import numpy as np
import pytorch_lightning as pl
from collections import defaultdict
from torch.nn import functional as F
# Imports from this project
from reporting import get_metrics
from schnet import SchNet
class Estimator(pl.LightningModule):
def __init__(
self,
batch_s... |
41292303b25eeb68235edf37c83d4b59539e32ca56203a6590541225f014c8d6 | Python | 7,160 | 275 | """Benchmark TorchLens intervention API overhead on a fixed small MLP."""
from __future__ import annotations
import statistics
import sys
import time
from collections.abc import Callable
from pathlib import Path
import torch
from torch import nn
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not ... |
87510f9030e7bd4521c2b7dc2953d1b6b15a7aeb32d6a9e134206c4b8efa5688 | Python | 7,160 | 230 | from __future__ import annotations
import ctypes
import io
import struct
import pytest
import env
from pybind11_tests import ConstructorStats
from pybind11_tests import buffers as m
np = pytest.importorskip("numpy")
if m.long_double_and_double_have_same_size:
# Determined by the compiler used to build the pybi... |
ebb8594563f4867c332b4c67ba0175735e35e11775c2ff5075fbf425d9eda37f | Python | 7,160 | 234 | """Logging and Profiling
"""
import logging
from functools import update_wrapper, partial
from logging import CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET
from datetime import datetime, timedelta, timezone
from typing import Optional
import anndata.logging
HINT = (INFO + DEBUG) // 2
logging.addLevelName(HINT, "HINT... |
1cca2bc81b1213d70ffb6f0e40b4087b06d12a6414b3e581de65afa69071ca11 | Python | 7,166 | 250 | from __future__ import annotations
from types import SimpleNamespace
import numpy as np
import pytest
from larvaworld.lib.screen.drawing import ScreenManager
def test_screen_manager_render_display_only_skips_array3d(
monkeypatch: pytest.MonkeyPatch,
) -> None:
calls = {"flip": 0}
def _flip() -> None:
... |
8738dbb393e09a1a508f1e6199ca276460538539b6e4944020b95b9f75546f95 | Python | 7,166 | 201 | """
The locomotor, orchestrating the motion-generating modules.
Combines the crawler, turner, feeder, intermitter and their crawl-bend
coupling into a single module that produces the agent's linear and angular
velocity each timestep.
"""
from __future__ import annotations
from ...param import ClassAttr, NestedConf
f... |
800bcd03b7306c7beb74d18b0816f37b1b75cb0950193effe552aed31c1626f2 | Python | 7,167 | 133 | import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import cvnn.layers as complex_layers
import numpy as np
from pdb import set_trace
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_image... |
6c957265c104366cabac4132ce5ea8ea2b72aae09f43d465a509b9c69c57a7b9 | Python | 7,169 | 170 | # coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... |
de08c8842d1f0d2ab370a1e3a5cf57dd05c0520b37ec1387c4075092b1334d01 | Python | 7,169 | 194 | """Built-in Tasks.
The built-in tasks are always available in all app instances.
"""
from celery._state import connect_on_app_finalize
from celery.utils.log import get_logger
__all__ = ()
logger = get_logger(__name__)
@connect_on_app_finalize
def add_backend_cleanup_task(app):
"""Task used to clean up expired r... |
f0d790ab7bc4d55219a9b4b45348ad5c9c531adf3eaf736b2be913a8d9f6d012 | Python | 7,169 | 203 | import tqdm
from enum import Enum
####
class Events(Enum):
EPOCH_STARTED = "epoch_started"
EPOCH_COMPLETED = "epoch_completed"
STEP_STARTED = "step_started"
STEP_COMPLETED = "step_completed"
STARTED = "started"
COMPLETED = "completed"
EXCEPTION_RAISED = "exception_raised"
####
class Stat... |
a59667b7a2afce28fa05205ace73329dd6e53b84d00a4d337a1cdd87537a3586 | Python | 7,170 | 197 | from typing import Tuple
import numpy as np
from numba import jit
from scipy.fftpack import dct, idct, dst, idst
def initialization(
Img: np.ndarray, BlockSize: int, Kaiser_Window_beta: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Initialize images and generate the Kaiser window for BM3D fil... |
e7784a22c748254c1177810e500e17938d3f3393e25097bfd86655baa2f5a7cb | Python | 7,170 | 160 | """Writable fsspec filesystem for GitLab projects.
``arcfs.fs.GitLabARCFileSystem`` writes the way an ARC takes data: through Git LFS, onto a generated
branch, behind a merge request. A GitLab user exporting a file expects a commit instead, so this
subclass writes that way - the same shape as ``github_fsspec.py``. The... |
597d36b8510da50e1283cc6ef1f2304b6ace9706b886458ccd029c11037420a0 | Python | 7,171 | 221 | import urllib.parse
from argparse import ArgumentParser
import torch
from pytorch_lightning import LightningModule, Trainer, seed_everything
from torch import nn
from torch.nn import functional as F
from pl_bolts import _HTTPS_AWS_HUB
from pl_bolts.models.autoencoders.components import (
resnet18_decoder,
res... |
c001da14354a563c2bb320d62c4bb85bc647311a42c7329a0ffaf64d818ef880 | Python | 7,171 | 173 | import numpy as np
class Graph():
""" The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of the follow candidates
- uniform: Uniform Labeling
- distance: Distance Partitioning
- spatial: Spatial Configuration
For more informa... |
a135514de7da8af62d05bdf25175310c166b3d78057832a039bd48ec0e65b7b7 | Python | 7,173 | 169 | """Registry-coherence names for sparse runnable readiness (r83 S3).
A loaded artifact names each computational call twice: the execution authority
``run.callable_registry[].key`` and the op's independently recorded function name.
These helpers decide when the two agree, so readiness can refuse a
self-contradictory art... |
32415a036aed1d51cbe5fd88b219249698521b7908e3768453e905536057fa18 | Python | 7,174 | 185 | """F11 perf gates: B1 fingerprint memoization + B2 de-quadratic enumeration.
Collapse memo items 6-7 (the collapse design memo, D6). These gates are
deterministic COUNT instruments, never wall-clock: B1 pins that one sweep
walks each member's wiring at most once and later sweeps on the same
revision walk zero, and B2 ... |
42b27a132e15ff2bbbccc133b2cc8b501b3cb0454d68fbd96bb6bde362f04fde | Python | 7,176 | 170 | import os
import gdown
import numpy as np
import pandas as pd
from tqdm import tqdm
from irnlm.data.text_tokenizer import tokenize
from irnlm.data.utils import get_function_words
def load_model_and_tokenizer(trained_model='../data/glove.6B.300d.txt'):
"""Load a GloVe model given its name.
Download Glove weig... |
a6caa4f6ca0bba77d29d7bba666be1d7ac653d44fd5c4b40fbe769c4edb8f769 | Python | 7,177 | 155 | """Prepare the HMDB51 Dataset
=============================
`HMDB51 <http://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/>`_ is an action recognition dataset,
collected from various sources, mostly from movies, and a small proportion from public databases such as the Prelinger archive,
YouTube... |
6dd0fccd17dfc1cdb7594e5ee9d715b9185c5f2fae680cfa26ffe7579da8c0f3 | Python | 7,178 | 181 | from shapely import ops
from shapely.geometry import MultiLineString, \
Polygon, MultiPolygon, box
from pyrosm_proto import BlobHeader, Blob, HeaderBlock
from pyrosm.exceptions import PBFNotImplemented
import zlib
from struct import unpack
import os
import geopandas as gpd
def validate_custom_filter(custom_filter... |
bfd17f97b7b3574bd9321dd6f57f17803e4c03413404699113d092623655f861 | Python | 7,178 | 170 | 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... |
a2c393144da015ed6d6f3f3e5bf4fdf27ee1fc81e604efb54a5d648213557371 | Python | 7,180 | 236 | # --- 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 Textfont(_BaseTraceHierarchyType):
_parent_path_str = "scattergl"
_path_s... |
aa23d288e4ddb284fe572368dce2c50efc3eb5765802ee68cf4451f3dc26fb47 | Python | 7,180 | 195 | # Copyright 2019 Novartis Institutes for BioMedical Research Inc. 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... |
c12ae9ebf7d4dafdc1d70aa34e44f2c76903dede319310e8385ab6c240f65ff6 | Python | 7,180 | 215 | """
=========================================================================
Frequency band selection on the manifold for motor imagery classification
=========================================================================
Find optimal frequency band using class distinctiveness measure on
the manifold and compare c... |
c6b370d265b55247947d509253d7a06e690bf48d599281bfbc3f270873db6ff2 | Python | 7,180 | 293 | from __future__ import annotations
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
from pybind11_tests import iostream as m
def test_captured(capsys):
msg = "I've been redirected to Python, I hope!"
m.captured_output(msg)
stdout, stderr = capsys.readouterr()
assert st... |
70dce3aaa4ad3dd1745110138373148ce6d9dcbd51d668a6c290d87254d37a00 | Python | 7,181 | 187 | """Add tool_request.request_state + tool_source identity columns + tightened UQ.
Three coordinated changes:
1. ``tool_request.request_state`` records the validity of the captured request
payload (``not_validated`` / ``validated`` / ``validation_failed``). Distinct
from ``tool_request.state``, which tracks the a... |
ae6cd787b68b602877962a53fdd62aa67a3a231f83551b29112d4c61650432bc | Python | 7,182 | 190 | """
molconfviewer - Visualize molecule conformations in Jupyter
"""
__version__ = "0.1.0"
import ipywidgets
import nglview
from IPython.display import display
from ipywidgets import interact, fixed
from rdkit.Chem.rdchem import Mol
from rdkit.Chem.rdDepictor import Compute2DCoords
from typing import Tuple, List, Dic... |
91af3a707aea8f99bff66a4804312cc8218a7536fbb87666ce13e4ad5208f342 | Python | 7,183 | 196 | # Mostly retaining MNE-Python functions to compensate for API changes
import logging
import numpy as np
import mne
from mne.bem import _fit_sphere
from mne.channels.interpolation import _make_interpolation_matrix
try:
from mne.forward import _map_meg_or_eeg_channels
except ImportError: # mne < 0.21
from mne.... |
ea1ace3f3dad35416707af9151a7fb95264c746f064d7cb49ac58f5925bec153 | Python | 7,183 | 229 | import pytest
from pyrosm import get_data
@pytest.fixture
def test_pbf():
pbf_path = get_data("test_pbf")
return pbf_path
@pytest.fixture
def helsinki_pbf():
pbf_path = get_data("helsinki_pbf")
return pbf_path
@pytest.fixture
def helsinki_region_pbf():
pbf_path = get_data("helsinki_region_pbf"... |
0c21fa56aeae524e79f0caff916fbcf46ccdaae35ba020c1cbe680b72d3f14df | Python | 7,185 | 174 | import numpy as np
class Graph():
""" The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of the follow candidates
- uniform: Uniform Labeling
- distance: Distance Partitioning
- spatial: Spatial Configuration
For more informa... |
ce0214194fb96dc0d954a5c705878a30d3cabb46264c32b3988b43c4a994bb26 | Python | 7,186 | 254 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"Utilities for testing"
from contextlib import ContextDecorator, contextmanager
from functools import reduce
from importlib.util import spec_from_file_location, module_from_spec
import os
from operator import mul
from pathlib import Path
import shutil
import sys
... |
e0eb20ca5b36995ee40d847b0e1159501fe707ffa5af5cc20c860116569a1cea | Python | 7,186 | 181 | import os
import math
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
import argparse
import json
sys.path.append('./src/')
import src.generator_transformer as Gener... |
f3ecdb9ec4e624639c73c13e40b095d4152f8ada5aaaed275fc9310065c96f49 | Python | 7,186 | 197 | """Collate function for I-JEPA."""
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from __future__ import annotations
import math
from multiprocessing import Value
from multiprocessing.sharedctypes import Synchronized
from typing import Any
import torch
from torch import Tensor
class IJ... |
61247d012cd2d69915a93cc0d688701692c6367d731fe96b975620e76ed3da25 | Python | 7,187 | 195 | from collections import OrderedDict
import codecs
import numbers
import numpy as np
from afmformats import meta
import nanite.model as nmodel
from PyQt5 import QtCore
from .. import units
#: Valid export choices in `save_tsv_metadata_results`
EXPORT_CHOICES = list(meta.META_FIELDS.keys()) + [
"params_ancillary"... |
25b92d2880236dc53919b5148762a7a6d8d61b82dca88f7bd7d0c7bee0b84ea5 | Python | 7,188 | 169 | import numpy as np
import torch
import dcrnn_utils as utils
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LayerParams:
def __init__(self, rnn_network: torch.nn.Module, layer_type: str):
self._rnn_network = rnn_network
self._params_dict = {}
self._biases_dic... |
d754e1474a2012130c97c6196b6c6bd3b209526552400ea511651d312d97e0e5 | Python | 7,188 | 167 | from __future__ import division
import os
# disable autotune
os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
import argparse
import glob
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
import mxnet as mx
from tqdm import tqdm
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluo... |
0a5b6f186489a21abee8cbb78edaaa28725563f559fd7ae842844e465f7e9fc9 | Python | 7,189 | 188 | import unittest
import numpy as np
import cantera as ct
import pickle
from os.path import join, abspath
from spitfire import ChemicalMechanismSpec as Mechanism
from spitfire.chemistry.ctversion import check as cantera_version_check
T_range = [300, 1200, 1800]
p_range = [101325, 1013250]
def verify_rates_mechanism(ct... |
6454afddb73d3cd98ea8d6e91bd636190637a00fd68de1e62a745d998c9c971b | Python | 7,189 | 200 | """Purity/state harness core (M(oracles) build item 7; F36 oracle wave 1).
Every invocation template runs under the four postconditions: parameters and
buffers byte-identical, torch global RNG untouched, no module hooks left
attached, and the model still forward-computes identically. Each template's
POSITIVE CONTROL r... |
688e157bfb732f752bed39394230b856061d7a0204b6097d301a3cdcbcedfc2d | Python | 7,190 | 182 | import hashlib
import logging
from galaxy import exceptions
from galaxy.files import (
ConfiguredFileSources,
FileSourcePath,
ProvidesFileSourcesUserContext,
)
from galaxy.files.models import FilesSourceOptions
from galaxy.files.sources import PluginKind
from galaxy.managers.context import ProvidesUserCont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.