sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
eca6ffbfb5246243d683a2e997ad5db20f091347d77881e8eb1432e4d983a576 | Python | 3,270 | 78 | #!/usr/bin/env python
# This code exists in 2 places: ~/datatypes/converters and ~/tools/filters
import sys
def __main__():
input_name = sys.argv[1]
output_name = sys.argv[2]
skipped_lines = 0
first_skipped_line = 0
i = 0
with open(input_name) as fh, open(output_name, "w") as out:
out... |
21c0878e1efd2cc00a28fa082a73f6316850d5469c8e1c89b2d4ffcffed6323b | Python | 3,271 | 108 | import logging
import yaml
import argparse
import numpy as np
from bson.objectid import ObjectId
from pymatgen.core import Molecule
from atomate.qchem.fireworks.core import SinglePointFW
from atomate.common.powerups import add_tags
from fireworks import LaunchPad, Workflow
from instance_mongodb import instance_mo... |
9e40d3255da6d9aadfda5362b88e10d279075cc428fe8587446d58b1c2d07861 | Python | 3,271 | 116 | from dataclasses import dataclass
from typing import Any, Protocol, TypeVar
import numpy as np
import xarray as xr
from hobj.learning_models import BinaryLearningModel
from hobj.stats.ci import estimate_basic_bootstrap_CI
ResultT = TypeVar("ResultT")
class SessionSubtask(Protocol[ResultT]):
"""Protocol for ben... |
0e090fef35e1c39ec1bfd52bb8062d0556c586ebf235b49b2813808525c60c48 | Python | 3,274 | 81 | """Persistence honesty: running a weight-free runnable artifact warns loudly.
WT1 A-IV item 17 (lane A08): a runnable artifact saved with the default
``include_weights=False`` loaded and ``.run()`` executed on RANDOM role-init
weights with zero warning, and its report could legitimately settle
``verified`` (path faith... |
2bfa3e9aceaa9f776a98ce66ba806b4df880f43e5aa062ffff82d38983c32e90 | Python | 3,274 | 155 | """
Activations for models.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import six
import tensorflow as tf
from dcCustom.models.tensorgraph import model_ops
from dcCustom.models.tensorgraph.model_ops import get_ndim
def get_from_module(identifier,... |
506006233fdd81c0899338f20aa9cc95f969f9624fce90ad150984f42e43c08a | Python | 3,275 | 85 | ##########################################################################
## ##
## Copyright (c) 2019-2024 Philipp Lösel. All rights reserved. ##
## ##
## This file is par... |
cb1a969358ed59a9a7c46011505bc59b46f153bfb088e5f7cef9d7f765459959 | Python | 3,275 | 90 | import os
import sys
import mne
import numpy as np
def get_labels(subjects_dir, labels_dir, parc='aparc_sub'):
labels = mne.read_labels_from_annot('fsaverage', parc=parc, subjects_dir=subjects_dir)
label_files = sorted([f.path for f in os.scandir(labels_dir)])
if len(label_files) < len(labels):
fo... |
ef8a6da0f0e30216e65669141bfc240f392105a77ddccf3ac3be95f3a43619e6 | Python | 3,275 | 90 | import unittest
from typing import List, Union
import numpy as np
import pandas as pd
from anndata import AnnData
from spateo.alignment.methods.utils import check_rep_layer
class TestCheckRepLayer(unittest.TestCase):
def setUp(self):
# Create some example AnnData objects
self.NA = 100
se... |
0c572f38353094edfa708dc1ac26e2cbd02ed7bbee4e62ea5b6a72fd3024fdfe | Python | 3,276 | 128 | #!/usr/bin/env python3
"""
Generate a closed triangulated cylinder surface mesh in OFF format.
Last updated: 09.04.2026
Author: Laura Keto
Description
-----------
This script generates a watertight triangulated surface mesh for a right
circular cylinder aligned with the z-axis and writes the result in OFF format.
Th... |
1f708e44136cf5128506f2b1cd6b3d830ece7ad587bdc824209d0287a566aa71 | Python | 3,276 | 101 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Functions for benchmarks.
"""
import pprint
import numpy as np
import slowfast.utils.logging as logging
import slowfast.utils.misc as misc
import torch
import tqdm
from fvcore.common.timer import Timer
from slowfast.datasets import loader
from... |
21658aaf44d4fe54c74966cbdfc35a199f9131a650ba3181a869cec17b350c04 | Python | 3,276 | 107 | import numpy as np
from PyQt5 import QtWidgets, QtGui
class InfDoubleSpinBox(QtWidgets.QDoubleSpinBox):
def __init__(self, *args, **kwargs):
super(InfDoubleSpinBox, self).__init__(*args, **kwargs)
self.setMinimum(-np.inf)
self.setMaximum(np.inf)
self.validator = FloatValidator()
... |
ef21f559f8217e4c4d85c69317e7014d9ab0fd64c259982a7d0f31c505a66f2c | Python | 3,276 | 106 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test objects and function in tfep.utils.math.
"""
# ==========================================================... |
fe916af671dc8c82856531bfea4005914de708f74299dc9618fa58a512892007 | Python | 3,276 | 89 | import numpy as np
import torch
def dict_equal(dict1, dict2):
if not dict1.keys() == dict2.keys():
return False
keys = dict1.keys()
for key in keys:
item1, item2 = dict1[key], dict2[key]
if not isinstance(item1, type(item2)):
return False
try:
if... |
089a0f2bd92f2d61514dae868b5def0dbaf126b78ad64b04101daad57cd45404 | Python | 3,277 | 71 | """
Create epochs.
"""
import sys
sys.path.append('..')
import os
import argparse
import mne
from mne.preprocessing import create_eog_epochs, create_ecg_epochs
from config import fname, baseline, reject, events_id, epoch_tmin, epoch_tmax
# Be verbose
mne.set_log_level('INFO')
# Handle command line arguments
parser = ... |
eac8dcf3fd731cb950cf9ef7dbdfa154c4d5eaac92b30276c00b7641301e75bf | Python | 3,277 | 77 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from pathlib import Path
from typing import Any
from ultralytics.solutions.solutions import BaseSolution, SolutionResults
from ultralytics.utils.plotting import save_one_box
class ObjectCropper(BaseSolution):
"""A class to manage the cropping o... |
0a7b302935623d07f977c56557684d3010dc5c60f649a0d595a134eecf548c2f | Python | 3,278 | 128 | # 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... |
31dedef6b4dbe9d1b56bf3b8117c4413a8656b1d3e994d284188fb7f0e81b519 | Python | 3,278 | 84 | import os
import sys
from typing import List
import numpy as np
import tensorflow as tf
import tqdm
from angorapy.utilities.core import flatten
from angorapy.utilities.core import stack_dicts
from matplotlib import pyplot as plt
from angorapy.analysis.investigators import base_investigator
from angorapy.common.polici... |
7b8262ba5003736ca3cc603f94ec1c05e2a6885e1c38f7a5c19501f280a254df | Python | 3,278 | 74 | from pyabf.abf2.section import Section
import datetime
class HeaderV2(Section):
"""
The first several bytes of an ABF2 file contain variables
located at specific byte positions from the start of the file.
"""
def __init__(self, fb):
Section.__init__(self, fb, 0)
self.seek(0)
... |
a7208615c2cd3bfd68136c0a7a1cc4cf6f984e83de3a9913d9eaab7df07906de | Python | 3,278 | 97 | import os
import pandas as pd
import requests
from tqdm import tqdm
from bioconfpred.params import (ENZYME_URL,
ENZYME_DAT_FILEPATH)
class ENZYME():
"""Parse data on enzyme classifications obtained at
https://ftp.expasy.org/databases/enzyme/
:param root: Path of the ENZYME directo... |
b9b91d13d30cb282151d3582bc21745491007a3f6301a763f348d92a69e55fd9 | Python | 3,281 | 96 | """Package-wide ``python -O`` verdict-identity gate (r7 b7-sol R24).
97 shipped ``assert`` statements survive in ``torchlens/`` (shrink-only
ceiling), several on verdict-adjacent paths (``validation/backward.py``
pre-comparator guards, postprocess invariants). ``-O`` strips every one of
them, and until now nothing pro... |
9e6e059cec006cb83ce6a1d132c2e0ca07ec02f447f9e20ed8c3337023d8406f | Python | 3,282 | 100 | """Fast Pose Utils for loading parameters"""
from mxnet import random
from mxnet import ndarray
from mxnet.initializer import Initializer
def _try_load_parameters(self, filename=None, model=None, ctx=None, allow_missing=False,
ignore_extra=False):
def getblock(parent, name):
if le... |
b911428e05f8a4caa879cff231e44b967d6558f3fbe575e1abae813f28da41ee | Python | 3,282 | 95 | import unittest
from typing import Any, List, Tuple
import torch
from pytorch_lightning import Trainer
from torch import Tensor
from torch.nn import CrossEntropyLoss, Flatten, Linear, Sequential
from torch.optim import SGD, Optimizer
from torch.utils.data import DataLoader
from torchvision.datasets import FakeData
fr... |
537bd180e944c34b03f4faceef8c658acafca454f0e05a10e18534af3df7ea63 | Python | 3,284 | 91 | # 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... |
0e7cdc89d9bbbcf44f2902beb854a464b57e87999604efa2f58ff890e2f17fb0 | Python | 3,285 | 112 | #!/usr/bin/python3
import argparse
import copy
import json
import os
import os.path as osp
from tqdm import tqdm
DEFAULT_LABELME = {
"version": "0.4.30",
"flags": {},
"shapes": [],
"imagePath": None,
"imageData": None,
"imageHeight": None,
"imageWidth": None,
"text": "",
}
DEFAULT_SHA... |
17f9501e12674771abb62c4d6772027bf6ba7338416756f28d101e2ee2ff76cd | Python | 3,285 | 50 | from argparse import ArgumentParser
def get_argument():
description = 'Genotype Imputation'
parser = ArgumentParser(description=description, add_help=False)
parser.add_argument('--model-type', type=str, default='dis', required=False,
dest='type_model', help='Model type')
parser.... |
3bebddea6f49207f36438abed43941d8ba6d0b5ba878ec89f5dc46bfcd4fe89a | Python | 3,285 | 105 | #!/usr/bin/env python3
import numpy as np
import symengine as se
import matplotlib.pyplot as plt
import argparse
import os
from settings import Params
from sensitivity_equations import GetSensitivityEquations, CreateSymbols
def main():
# Check input arguments
parser = argparse.ArgumentParser(
descrip... |
1ffa2e0985a4f645ea5790e950f7264402318bac30e35bc96f76ee02df85d601 | Python | 3,286 | 105 | import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class MaskedScaleDotProductModule(nn.Module):
"""
Module to construct MaskedScaleDotProductAttention(self-attention)
"""
def __init__(self, scale_factor, gamma=1.0):
super().__init__()
... |
8b2d42efbe92fb7e44fdb7243962ef8caaec4f24d3a7a176b2bb621174d03603 | Python | 3,288 | 83 | # Copyright (c) 2024, Tri Dao.
import pytest
import torch
import torch.nn.functional as F
from flash_attn.losses.cross_entropy import CrossEntropyLoss
is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
@pytest.mark.parametrize(
"dtype", [torch.float16, torch.float32] + ([torch.bfloat16] if is_sm8x else ... |
2d5305bdbcb72ad4d879e22faceafbeaec6bf15e0d1c706ecedb11d2d75206d4 | Python | 3,290 | 91 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 15:52:36 2022
@author: psicobiologia
"""
import pickle
import scipy.io
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV, cross_val_score, cross_val_predict, cross_validate, StratifiedKFold... |
9253a8b5d424e7024b320697e0fd3d5bb1a79c7abaf8a6fcfecaf5b70b8997a9 | Python | 3,290 | 55 | from argparse import ArgumentParser
def get_parameters():
'''
The parameters for the model training, can be called out via the --h menu
'''
parser = ArgumentParser()
# model hyper-parameters
parser.add_argument('--model', type=str, default='resnet', choices=['resnet', 'csn', 'r2plus1d', 'x3d',... |
ba22a0e9c0140c366b09b0fe4510b71a8b4d22ff057b5331cb0d8eca59d4b1a0 | Python | 3,290 | 91 | # 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... |
379b0ece3c5f14c9c4bfd352ac42b685ecc237839bc664beab4e60d5b3beee45 | Python | 3,291 | 111 | from __future__ import print_function
import adolc
import numpy as np
steps = 100
h = 0.01
def euler_step_act(n,yin,m,yout):
yout[0] = yin[0] + h*yin[0]
yout[1] = yin[1] + h*2*yin[1]
class euler_step_edf(adolc.EDFobject):
def __init__(self,tag):
super(self.__class__,self).__init__()
self.... |
4c8eed0b6fdbdd8e10a8a48a0b6b1f296015706c61cc3a97a1e29af4ff2565f2 | Python | 3,291 | 94 | """Parity tests comparing pyrosm against OSMnx on the same data, area and time.
The fixtures in ``tests/data/osmnx_reference/`` were fetched with OSMnx from the Overpass
API at the same historical moment (an Overpass attic ``[date:]`` query) and the same
central-Helsinki bounding box as a subset of ``helsinki_region_p... |
503816d73ca63c5af615aa1362ed18e154d99c467cd7665255d3bf0d33e6eb51 | Python | 3,293 | 110 | # --- 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 Line(_BaseTraceHierarchyType):
_parent_path_str = "scattermap"
_path_str ... |
38b42ec71d5a7f6f4b2a760a0e84deb273df2bfe5d171df3099ec949d83db7b0 | Python | 3,294 | 111 | """Periodically store events in a database.
Consuming the events as a stream isn't always suitable
so this module implements a system to take snapshots of the
state of a cluster at regular intervals. There's a full
implementation of this writing the snapshots to a database
in :mod:`djcelery.snapshots` in the `django-... |
7cb8fa0e975a2255cf89db91dc0a7c1e81c7fe688df368e3de70f054c775912f | Python | 3,295 | 105 | #!/usr/bin/env python
import sys, csv
import subprocess as sp
import codecs
PYVER = sys.version_info.major
def Next(c):
if PYVER == 2:
return c.next()
else:
return c.__next__()
class Converter(object):
blockChrom = ""
blockStart = 0
blockEnd = 0
blockValue = 0
scale = 1.0... |
ca32f5eb2cafd6a062e4e82c3d2cd8e5206edc2923d511b8c881fe0002ce5f5c | Python | 3,295 | 105 | import copy
import numpy as np
import pandas as pd
import skimage.measure
from mirp._features.texture_matrix import Matrix
from mirp._images.generic_image import GenericImage
from mirp._masks.base_mask import BaseMask
class MatrixSZM(Matrix):
def __init__(self, **kwargs):
super().__init__(**kwargs)
... |
7cc98af3e25ba2c6e69f27558509de160d92cb2bd52758a64f38f7c2533f2372 | Python | 3,296 | 99 | import warnings
import numpy as np
import scanpy as sc
import tensorflow as tf
import sys
sys.path.append('../pkgs/scGAE/')
warnings.simplefilter(action='ignore', category=FutureWarning)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
# scGAE modules
from scgae import SCGAE
from preprocessing import *
f... |
a5ed5eaa05c6f6ee3e5bdb07b9e657a6e9320a115a68fd74b1cb4ac646680167 | Python | 3,296 | 116 | import functools
from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from werkzeug.security import check_password_hash
from werkzeug.security import generate_pa... |
aa3bd907d6b0ea33e2606d26c38b58a2c01451e6a152e704ab5d40c6f2bc5306 | Python | 3,296 | 117 | """Tests for rerun preserving selective save scope."""
from __future__ import annotations
import torch
from torch import nn
import torchlens as tl
from torchlens.options import CaptureOptions
class ThreeOpModel(nn.Module):
"""Small model with several selectable operation sites."""
def forward(self, x: tor... |
09bfcd3c4901578ad9db905e5db76f1efac7630da6d60f8e89718c54fc0551c5 | Python | 3,297 | 109 | from typing import Any, Callable, Optional, Union
from pl_bolts.datamodules.vision_datamodule import VisionDataModule
from pl_bolts.datasets import BinaryMNIST
from pl_bolts.utils import _TORCHVISION_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
if _TORCHVISION_AVAILABLE:
from torchvision import ... |
40c338e8b05bd004f4e2cd9c2c4e7e463827f50104aed7c19467d870842a6689 | Python | 3,298 | 106 | # --- 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 Unselected(_BaseTraceHierarchyType):
_parent_path_str = "bar"
_path_str =... |
67434602bbe8645343fbc0fb81d6d1c1a7677ed7d5730506fdda90b1d8dea3d9 | Python | 3,299 | 92 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
taxo_level_corresp = {
"k": "kingdom",
"p": "phylum",
"c": "class",
"o": "order",
"f": "family",
"g": "genus",
"s": "species",
"t": "strains",
}
def write_taxo_abundance(output_files, level, taxo, abundance):
if level... |
99d70dd6bd0e6545cd436a4439acefd5fb26bef7f284c49ec188ed037a85471d | Python | 3,300 | 94 | import pytorch_lightning as pl
import torch
import torch.nn as nn
from pointnet2_ops.pointnet2_modules import PointnetFPModule, PointnetSAModule
from torch.utils.data import DataLoader
from scene_graph_prediction.pointnet2_dir.pointnet2.data import Indoor3DSemSeg
from scene_graph_prediction.pointnet2_dir.pointnet2.mod... |
11f39235bbeb62096e9caf70bed41b34be3e90a3ebe998dca5b92312baf783ca | Python | 3,301 | 99 | #!/home/ubuntu/miniconda2/bin/python
from __future__ import print_function
import glob, os, gc, sys
import os.path
import csv
import numpy as np
np.random.seed(1337) # for reproducibility
from time import time
from subprocess import (call, Popen, PIPE)
from itertools import product
from IPython.display import display... |
891fb3e7305e94b8cdc48167ab34228753a1794a4e3cccf0fe42f4bf812b6613 | Python | 3,301 | 86 | import inspect
from keras.src.api_export import keras_export
from keras.src.quantizers import modes # noqa: F401 (registers modes)
from keras.src.quantizers import strategy_registry # noqa: F401
from keras.src.quantizers.awq_config import AWQConfig
from keras.src.quantizers.fake_quant import fake_quant_with_min_max_... |
4558edfccd6cbbbfbae944d2b983b08483fb6ecf4ec748eb757368d54196c8a3 | Python | 3,302 | 103 | from datetime import datetime, timedelta
from typing import List, Optional
import dateutil.relativedelta
from dependency_injector.wiring import Provide, inject
from fastapi import APIRouter, Depends
from starlette import status
from carbonserver.api.schemas import Experiment, ExperimentCreate, ExperimentReport
from c... |
a82dab106e431fd753462e20763e8968eea723d6b8d3bb4eccc76e85acda3cf0 | Python | 3,302 | 113 | # 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... |
62205c0eadeacdcab44497ed7556e616486c41a05b33162bb01e67c74f9cbf67 | Python | 3,303 | 89 | import torch
import torch.nn as nn
from prodict import Prodict
class ODEFunc(nn.Module):
def __init__(self, dims: Prodict, device: str = torch.device("cpu")):
"""The Neural ODE decoder Module of TDNODE. Neural network function that considers as input
a tumor state and p-dimensional parameter encod... |
9ba9baa698d87009f0ee303e054970f21fd53908cc7701081338d0b176121fec | Python | 3,304 | 92 | """AUD-CODE 3.9 regression: the budget resolver never serves the full graph.
A 40-block Sequential produced a two-point schedule (t=0.0 -> 282 visible,
t=1.0 -> 4); both miss the 100-220 band and the resolver served the FULL
graph as "nearest" (|282-220| = 62 < |100-4| = 96). The dial must genuinely
compact: while the... |
9c8b4f7f39e6de1fae5cdbd63fd3f3e8e04b8464dfa244455376bd3b977f89b1 | Python | 3,305 | 106 | # --- 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 Selected(_BaseTraceHierarchyType):
_parent_path_str = "quiver"
_path_str ... |
c49c5f6e3db32d74bfac13633fd328ec904cb7159d76ca78f6956432076c1fd7 | Python | 3,305 | 125 | from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from werkzeug.exceptions import abort
from .auth import login_required
from .db import get_db
bp = Blueprint("blog", __name__)
@bp.... |
bd3af61f91d66170513744b46dadea2c2654b4a92c7f995fbbfde4f71f3636c9 | Python | 3,306 | 92 | import random
import tempfile
from typing import List, Tuple
import pytest
from lightly.data.dataset import LightlyDataset
from lightly.data.lightly_subset import LightlySubset
from tests.data.test_LightlyDataset import TestLightlyDataset
try:
import av
import cv2
from lightly.data._video import VIDEO_S... |
112e79bb750f92e2d427c87e02b0a4d822deada1c6b9324bb957db46c0db3f94 | Python | 3,307 | 121 | import imantics as im
import json
from mongoengine import *
from .datasets import DatasetModel
from .categories import CategoryModel
from .events import Event
from flask_login import current_user
class AnnotationModel(DynamicDocument):
COCO_PROPERTIES = ["id", "image_id", "category_id", "segmentation",
... |
583bae2eb62c8c3c998c840101dfb2b3e1fefbd64994e94b6253bdd0de477222 | Python | 3,309 | 106 | from typing import Any
from mirp._data_import.dicom_file import ImageDicomFile
from mirp._data_import.utilities import get_pydicom_meta_tag
class ImageDicomFileCT(ImageDicomFile):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def is_stackable(self, stack_images: str):
return True
... |
721a53d8607d9ab112e4e8db84b7cc556c4bedee02126c8799aeb61433ab9055 | Python | 3,309 | 93 | import os
import sys
import json
import numpy as np
from scipy import stats
from scipy.signal import welch
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, ROOT)
sys.path.insert(0, os.path.join(ROOT, "src"))
from data_loader_01... |
1ac7de3b44879c625af8716b073ecd7c1e90ec3aeb938b102c9b66ebce98e539 | Python | 3,310 | 109 | # From https://github.com/felixpatzelt/colorednoise
# MIT license
"""Generate colored noise."""
from numpy import sqrt, newaxis
from numpy.fft import irfft, rfftfreq
from numpy import sum as npsum
def powerlaw_psd_gaussian(exponent, size, rng, fmin=0):
"""Gaussian (1/f)**beta noise.
Based on the algorithm i... |
24bbe1e89f3609d58b0cf56772f6dba5f17bf39a3c1cba871d5d30bb783ffd04 | Python | 3,310 | 107 | import configparser
import pytest
from codecarbon.cli import cli_utils
def test_get_config_reads_codecarbon_section(tmp_path):
config_path = tmp_path / ".codecarbon.config"
config_path.write_text("[codecarbon]\napi_endpoint=https://example.test\n")
config = cli_utils.get_config(config_path)
assert... |
34759ad910e85c4975ee6350561bbd5aa3d1d87c4b5678a19ec84cc802449718 | Python | 3,311 | 119 | from neuron import h, gui
import numpy as np
import scipy
def make_callable(inst, name, mech_name):
if inst is None:
return getattr(h, f"{name}_{mech_name}")
else:
return getattr(inst, f"{name}")
def make_callbacks(inst, name, mech_name):
set_table = make_callable(inst, f"table_{name}",... |
7334d757f03be914461ff2653691b6e3e2c6891c748d9e8812f4782c2ad1e4b5 | Python | 3,311 | 106 | import copy
import numpy as np
import pandas as pd
import skimage.measure
from mirp._features.texture_matrix import Matrix
from mirp._images.generic_image import GenericImage
from mirp._masks.base_mask import BaseMask
class MatrixDZM(Matrix):
def __init__(self, **kwargs):
super().__init__(**kwargs)
... |
829b92f724480955f087de43296a5618fdc1682db4a0627b60b7accfbac4672e | Python | 3,311 | 104 | from time import sleep
from config import app
from visitors import FullVisitor, MonitoringIdStampingVisitor, MyStampingVisitor
from celery import Task
from celery.canvas import Signature, maybe_signature
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
def log_demo(running_task):
... |
940d04d6a53455290b224e48572165edd3412bd506d0f93175d8d53efdc64ddc | Python | 3,311 | 99 | """Gabor Jet dynamic-link architecture, 1991, Lades, von der Malsburg, and colleagues.
Paper: "Distortion invariant object recognition in the dynamic link architecture."
Images are represented by complex Gabor filter responses sampled at graph nodes; this
minimal version returns amplitude and phase jets for a fixed no... |
fbe9a01f758e1549db7704333365ecbae07a679eb3ea463ee9490eac90d6ba75 | Python | 3,311 | 111 | import abc
import torch
import torch.nn as nn
class WeightDecay(nn.Module):
def __init__(self, module, weight_decay, name: str = None):
if weight_decay <= 0.0:
raise ValueError(
"Regularization's weight_decay should be greater than 0.0, got {}".format(
weigh... |
150127e0c9c720de7c93390a59e2e1b4a6093a42b439e25988aa564fca1d4326 | Python | 3,312 | 107 | import numpy as np
from PyQt6 import QtWidgets, QtGui
class InfDoubleSpinBox(QtWidgets.QDoubleSpinBox):
def __init__(self, *args, **kwargs):
super(InfDoubleSpinBox, self).__init__(*args, **kwargs)
self.setMinimum(-np.inf)
self.setMaximum(np.inf)
self.validator = FloatValidator()
... |
a6ced1bd2c028a22b52a52b276d04cbf75742746304a6a9953ea508da151adc5 | Python | 3,312 | 96 | """C03 honesty gate: ``run(inputs=...)`` refuses typed when a spec is staged.
Surgery memo build item 1 (the measured silent wrong answer): the unified
provider is a fresh verified execution and never installs the staged
intervention spec, while the legacy ``run(model, x)`` surface does. Before
this gate, ``run(inputs... |
becbb86f1ed7dd5ae4b864d2059ff9b5dca54f75f067850fcd7d0932f106880c | Python | 3,312 | 114 | """
Frequency-related plotting
"""
from __future__ import annotations
from typing import Any, Optional, Sequence
import numpy as np
from scipy.fft import fftfreq
from .. import plot, util, funcs
__all__: list[str] = [
"plot_fft_multi",
]
@funcs.graph("freq powerspectrum", required={"ks": ["v", "fov"]})
def pl... |
fde8056cb20f785f71235d27434ec57a46a08d9d0c59b45bdcaf59c37b607aa3 | Python | 3,312 | 65 | from typing import List
import torchhd
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer, AutoModelForCausalLM
from torch.func import jacfwd
from torch.autograd.functional import jacobian
from tqdm import tqdm
import torch
from torch.autograd import grad
from dict_hash import sha25... |
11a10a118f753b78299e0a16606e58489023f94cd3d52f23d57eaa50ffb95bf3 | Python | 3,313 | 114 | from typing import Dict
import numpy as np
import pytest
import seqpro as sp
import torch
import xarray as xr
from numpy.typing import NDArray
from pytest import fixture
import seqdata as sd
@fixture
def dummy_dataset():
"""Dummy dataset with 3 sequences of length 5."""
seqs = sp.random_seqs((3, 5), sp.DNA,... |
552becab97cff603e0899857b3e33d0a2a6309e577fe87d4c3c1c4ca07bcfcf3 | Python | 3,313 | 87 | from model import common
import torch
import torch.nn as nn
import torch.nn.functional as F
# from thop import profile
from util.tools import extract_image_patches, reduce_mean, reduce_sum, same_padding, reverse_patches
import pdb
import math
# MLP in the paper
class Mlp(nn.Module):
def __init__(self, in_features,... |
fac04d006f78cbdf04827769795fccdf87f6ff75d6a28d22c29146bc77da834b | Python | 3,313 | 96 | import json
import os
import shlex
import subprocess
import sys
import tempfile
import time
import traceback
from collections.abc import Callable
from functools import partial
from galaxy.tool_util.deps import docker_util
from galaxy.util import (
DEFAULT_SOCKET_TIMEOUT,
requests,
)
from galaxy.util.sockets im... |
188b7631fe0470f4fd59bf9410e18ea767ebaf881d6de217de165bd3fdf61fbf | Python | 3,314 | 86 | import os
from typing import (
Protocol,
)
from yaml import safe_load
from galaxy.util.config_templates import (
apply_syntactic_sugar,
find_template,
find_template_by,
InstanceDefinition,
RawTemplateConfig,
TemplateReference,
validate_secrets_and_variables,
verify_vault_configured... |
bb5bf15d8798abfbd3be5ea330126cc6656a3da42acb3b475ff6306fb72fb20c | Python | 3,314 | 84 | import os
import json
import torch
from torch import nn
from model.grud_model import GRUD
from model.custom_cross_entropy import CustomCrossEntropyLoss
from data.dataset import RegionDataset
from torch.utils.data import DataLoader
from utils.argument_parser import get_argument
from utils.imputation import evaluation, ... |
c4ae42cf75ac44410f0608f3d5afa533290b0271202dc7be8837e1cce29581c9 | Python | 3,314 | 98 | """Tests for the flatten observation wrapper."""
from collections import OrderedDict
from typing import Optional
import numpy as np
import pytest
import gym
from gym.spaces import Box, Dict, flatten, unflatten
from gym.wrappers import FlattenObservation
class FakeEnvironment(gym.Env):
def __init__(self, observ... |
d00be89ff2ca20f532c791f746417839ad7604bab59c0ca4870faeb171e24772 | Python | 3,314 | 104 | """Tests for bdpy.pipeline."""
from unittest import TestCase, TestLoader, TextTestRunner
import sys
import numpy as np
import yaml
import hydra
from bdpy.pipeline.config import init_hydra_cfg
class TestPipeline(TestCase):
"""Tests for bdpy.pipeline."""
def setUp(self):
cfg = {
"key_in... |
59a186fc82a881ec5974c0aae04d37566de30b82efccf871f0eb094bcc015715 | Python | 3,315 | 83 | # adapted from https://github.com/facebookresearch/fvcore/blob/master/fvcore/transforms/transform_util.py
import numpy as np
import torch
def to_float_tensor(numpy_array: np.ndarray) -> torch.Tensor:
"""
Convert the numpy array to torch float tensor with dimension of NxCxHxW.
Pytorch is not fully supporti... |
acb3a3d290ea26aaf3684f5a98978d77b024be5e202d246f01c7cd141e50ad2c | Python | 3,315 | 94 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import functools
import logging
import os
import sys
from termcolor import colored
class _ColorfulFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
self._root_name = kwargs.pop("root_name") + "."
self._abbrev_n... |
0702b01189b924b43fe04a02c1e7fca16267bcb98b52dffa5a50ef16e3eec522 | Python | 3,316 | 101 | import logging
import yaml
import copy
import argparse
from bson.objectid import ObjectId
from pymatgen.core import Molecule
from atomate.qchem.fireworks.core import OptimizeFW
from atomate.common.powerups import add_tags
from fireworks import LaunchPad, Workflow
from instance_mongodb import instance_mongodb_sei
... |
807556c2e6ba513c17b0fcb9d3965c778bf5367e1d5563811828f37eedd56e24 | Python | 3,316 | 97 | import json
import os
import pandas as pd
import torch
import torchio as tio
from hydra import initialize, compose
from torch.utils.data import DataLoader
from data.dataset_3d import set_transform
from initial_setting import get_instance
class TestDataset3D:
def __init__(self, cfg, distort=False):
super... |
b872207a47a67c7132a9d7dd8e9a4261e9ebcb69bb11f8dab55c7dcc3247b280 | Python | 3,316 | 102 | """
Generate results from predictions.
"""
from scipy.io import loadmat
from scipy.spatial import distance
import numpy as np
import pandas as pd
import argparse
from pathlib import Path
import math
from scipy.stats import pearsonr
from scipy.stats import zscore
parser = argparse.ArgumentParser(description='Analyse... |
b9363ea7e14a3d5e7436de30419905403fd143601627f12ed5639764dafe5481 | Python | 3,316 | 88 | """Revoking a task while one of several workers runs it (#10913)."""
from __future__ import annotations
from time import monotonic, sleep
import pytest
from pytest_celery import RESULT_TIMEOUT, CeleryTestSetup, CeleryTestWorker, CeleryWorkerCluster
from celery import Celery, states
from celery.exceptions import Task... |
26466b388aabecbce19f2122bf0631e964bb79fdab84eae4716fe488d71b3857 | Python | 3,317 | 111 | import os
import pytest
import flask
def test_explicit_instance_paths(modules_tmp_path):
with pytest.raises(ValueError, match=".*must be absolute"):
flask.Flask(__name__, instance_path="instance")
app = flask.Flask(__name__, instance_path=os.fspath(modules_tmp_path))
assert app.instance_path ==... |
57aaf670668fcbcfbb0573715e401deb33b906ddc524d5866bff685f6e078267 | Python | 3,317 | 94 | #!/usr/bin/env python
"""
Classifier is an image classifier specialization of Net.
"""
import numpy as np
import caffe
class Classifier(caffe.Net):
"""
Classifier extends Net for image class prediction
by scaling, center cropping, or oversampling.
"""
def __init__(self, model_file, pretrained_fi... |
84b1901fca2f5d746cba9a477e3035a4d95a8537a56fc690f0faba6b4ad73666 | Python | 3,317 | 83 | #file_name:fliter_blastn_out
#function:filter the result of blastn out by comparing score and save as bed from
#author: Wang_nini
#data:2018.03.29
import sys
import getopt
def usage():
print ('''Usage:Python changeID.py [option] [parameter]
-i/--input_file blastn_out_outfmt_6
-o/--output_file the output_file
... |
c96e3336fc541fad90bbdb8e5be1ede0dec6247d15973a4595a94b57ba480629 | Python | 3,318 | 106 | # --- 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 Selected(_BaseTraceHierarchyType):
_parent_path_str = "scatter"
_path_str... |
352b6687eb7465361e80155514b33967fd144b06f07e0e76ee3fd133115d24b3 | Python | 3,319 | 106 | """
Unit tests for BaseRun/ReplayRun's on-screen intro-text content.
Uses object.__new__ to build bare instances with only `.p` set, avoiding a
full simulation setup -- configuration_items/configuration_text only read
`self.p`.
"""
from __future__ import annotations
import pytest
from larvaworld.lib.sim.base_run im... |
89758916c9536ca206d6a03580323b3a953e4b6c4f07fbf25acb935086951e07 | Python | 3,319 | 111 | """Hodgkin-Huxley neuron, 1952.
Hodgkin and Huxley, "A quantitative description of membrane current..." Sodium,
potassium, and leak conductances are integrated as an unrolled differentiable ODE.
"""
from __future__ import annotations
import torch
from torch import Tensor, nn
class HodgkinHuxleyNeuron(nn.Module):
... |
98fb625aa390088011e28746f99500c2b1012105532a7fa6594bce4f0fda6757 | Python | 3,319 | 100 | from __future__ import annotations
import panel as pn
from larvaworld.lib import reg
from larvaworld.lib.reg.generators import ExpConf
from larvaworld.portal.config_widgets import (
build_larva_group_widget,
build_larva_groups_widget,
)
def _find_widget(
viewable: pn.viewable.Viewable,
name: str,
... |
73409808c4ba76a7775d7acddf26d2b67c3076e1b3d282012e4cecbb124ee868 | Python | 3,320 | 84 | """Tests for PyTorch backend nn utilities."""
import numpy as np
import pytest
import torch
from absl.testing import parameterized
from keras.src import backend
from keras.src import ops
from keras.src import testing
@pytest.mark.skipif(
backend.backend() != "torch",
reason="This test is only applicable to ... |
ab5fcde0e88665f2236f6eae45bca04f16c7492c88caa3fe0963c692fda99c65 | Python | 3,320 | 100 | import argparse
import numpy as np
import pandas as pd
import plotly
import plotly.graph_objs as go
def main(infile_input, infile_output):
"""
Produce an interactive actual vs predicted curves and residual plots
Args:
infile_input: str, input tabular file with true values
infile_output: s... |
02fdcf807cb6579117d08b596b95c0f0312a47093e6752124461e6343a4b41b1 | Python | 3,321 | 117 | # 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... |
21cde2bc57fc7b9d962149c0653ab1b843eb0e9344ffdd7b665f14a0f2aa9553 | Python | 3,322 | 100 | from pathlib import Path
from typing import Union
OBJECT_COLOR_MAP = {
'anesthesia_equipment': (0.96, 0.576, 0.65),
'operating_table': (0.2, 0.83, 0.72),
'instrument_table': (0.93, 0.65, 0.93),
'secondary_table': (0.90, 0.30, 0.63),
'instrument': (1.0, 0.811, 0.129),
'object': (0.61, 0.48, 0.04... |
5f701b06125751fe69dde93e788a426ee4237d35d664fba5750562b53c163834 | Python | 3,322 | 117 | #!/usr/bin/env python3
"""
Test script for logger name fix in device_scanner.py.
This script tests that the logger name is properly updated from IP address
to the proper device name format (e.g., ETHOSCOPE_065).
"""
import os
import shutil
import sys
import tempfile
import pytest
# Add the src directory to Python p... |
b34b08cd20e365f52021f4187f92d0d4818d771bad069cea312288618809a369 | Python | 3,322 | 86 | import warnings
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from Bio import BiopythonWarning
from Bio.PDB import *
from keras import backend as K
import tensorflow as tf
warnings.simplefilter('ignore', BiopythonWarning)
def PDBPredict(pdb):
model_phi = tf.kera... |
d2946f578e1c959977a20f8b2edcc3947bf16c0ae3bd636dfd32c19d80d14cc6 | Python | 3,322 | 60 | import os
import logging
from subprocess import run, CalledProcessError
class ToolMissingError(Exception): pass
class AlignmentPipelineError(Exception): pass
def check_prereqisites(aligner):
devnull = open(os.devnull, 'w')
try:
run(['gunzip', '--help'], stdout=devnull, stderr=devnull, check=True)
... |
03775839d273114f18e2b63b7a91970b5cf7b6bc63e7a9ed8f2b3e119f52c3bd | Python | 3,323 | 108 | # This example requires the following dependencies to be installed:
# pip install lightly[timm]
# 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 pytorch_lightnin... |
3852f0ba96f39f860ffcf13fd5a5624586e8980ff44941c1795f22fe3feab1cd | Python | 3,323 | 113 | import numpy as np
import tensorflow as tf
import random as python_random
import os
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return ... |
97ec610226f2b48078e46a99fc7dbd5a6fd084b1088e27596ceee3a5747c7789 | Python | 3,323 | 90 | #!/usr/bin/env python
"""
Form a subset of the Flickr Style data, download images to dirname, and write
Caffe ImagesDataLayer training file.
"""
import os
import urllib
import hashlib
import argparse
import numpy as np
import pandas as pd
import multiprocessing
# Flickr returns a special image if the request is unavai... |
0981246e60c998c1dfd91cd316d69f3dcbbc1011b9c00633f26b7835db9873b5 | Python | 3,324 | 151 | """Built-in task states.
.. _states:
States
------
See :ref:`task-states`.
.. _statesets:
Sets
----
.. state:: READY_STATES
READY_STATES
~~~~~~~~~~~~
Set of states meaning the task result is ready (has been executed).
.. state:: UNREADY_STATES
UNREADY_STATES
~~~~~~~~~~~~~~
Set of states meaning the task resu... |
5a20aa35c9af2b65959e8d12a2c04f41a2a8f58d2019d52ed470361f86dc080f | Python | 3,324 | 98 | """Serve one-liner tests (memo D18, B5).
The full-package launch is a scheduled leg (it needs the vendor app's
server stack); here the contract is pinned: the missing-dependency refusal
teaches the exact install, and the call routes through the PUBLIC vendor
``visualize`` API only -- exported file first, no private at... |
5fc0ba4cac64c0133390dd28da6377170d1247eb3e7e68f4d7612cbc2200015f | Python | 3,324 | 86 | """Captures in an ARMED process behave like unarmed ones outside collectives.
Distributed arming is process-lifetime by design and survives
``destroy_process_group``; while armed, plane-P installs the completeness
witness dispatch mode around every capture. Two defects surfaced through that
dispatch mode (found as tes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.