sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
90c57482f307f2d3251cdfd768d724bb03d2857fb9e50b64dec83d553cb97608 | Python | 6,582 | 267 | CompScalerMeans = [
21.194441759304013,
58.20212663122281,
37.0076848719188,
36.52738520455582,
13.350626389725019,
29.468922184630255,
28.71735137747704,
78.8868535524408,
50.16950217496375,
59.56764743604155,
19.020429484306277,
61.335572740454325,
47.1... |
892bf73742cabd556952c27e0f6114581455182ea7b4cd5472b9f73f96613886 | Python | 6,588 | 188 | import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class GninaNetwork2017(nn.Module):
"""
Gnina network model for 2017.
Notes
-----
This code block is adopted from the following link:
https://github.com/gnina/models/blob/master/acs2018/default2017.mode... |
d7988751569aa486f44038571c29e0bdef6d432c9ace058eb68ee6338ce832a4 | Python | 6,591 | 194 | import numpy as np
import pytest
from masscube.annotation_new import (
align_fragments,
centroid_spectrum,
clean_spectrum,
dot_product_similarity,
normalize_spectrum,
scale_spectrum,
)
from masscube.annotation_new.utils import scale_spcectrum
@pytest.fixture
def noisy_ms2_spectrum():
retu... |
cf63843bf86127ff86228558ea40f4f93f26bba3a495ff95e1b0a7780cbc3a45 | Python | 6,593 | 159 | """
This is the interface API to compute MT-related metrics
Code is based on QMRLab: https://github.com/neuropoly/qMRLab
Copyright (c) 2018 Polytechnique Montreal <www.neuro.polymtl.ca>
License: see the file LICENSE
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
def divide_after_remov... |
123617425ef4ac96947c4f4d3989d68d396d3f4834d886065a99aad6e310b31f | Python | 6,595 | 188 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import numpy as np
import h5py
from h5py import h5t... |
0b5bc4224f1288e08aeb2af272e2f8fa6d7e73c7d2851c155df662394c0f1ae4 | Python | 6,596 | 202 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 29 12:31:07 2023
@author: george
"""
%matplotlib qt
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from tqdm import tqdm
import os, glob
from matplotlib.patches import Ellipse, Arrow
import matplotlib.transforms as tran... |
1f8baf9074270fa04797db40c23291795e7a4d896e9c36f2d3f10c9acb1e3f8c | Python | 6,596 | 269 | # pytest unit tests for spinalcordtoolbox.registration
import logging
import os
import pytest
import numpy as np
from spinalcordtoolbox.scripts.sct_register_to_template import Param
from spinalcordtoolbox.registration.core import register
from spinalcordtoolbox.registration.algorithms import (Paramreg, register_step... |
fa3adc6f3754b02868e6b76713b3c933b80442ed377aa3b2170c998bf7241dc5 | Python | 6,600 | 167 | import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
from unsloth import FastLanguageModel
import transformers
from datasets import load_dataset
import os
import argparse
def randomized_choice_options(num_choices):
choice_options = list(map(chr, range(65, 91)))
return np.random.choice(choice... |
266f75d014f5392905417c4aa25e0f4ca27d7eb41457c547d22ffde18227686d | Python | 6,611 | 153 | # sys.path.append('./')
import os
import torch
import argparse
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning import Trainer, loggers
from transformers.optimization import get_linear_schedule_with_warmup
from transformers import GPT2LMHeadModel
from fengshe... |
423ba2f34bb37e711eb8ab30a22077e0bc5f50926f1dce5c86c88cbb43a99846 | Python | 6,611 | 175 | """
Code is modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/model/apply_delta.py
Apply the delta weights on top of a base model.
Usage:
python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta-v1.1
"""
import argparse
im... |
437be6db8c2a91f3f0d57abd688fd7cb39100475b6868371c99306c1232cbfbf | Python | 6,617 | 248 | import re
from typing import Dict, Optional
import prefixcommons.curie_util as cu
from cachetools import LRUCache, cached
from kgx.config import get_jsonld_context, get_logger
from kgx.utils.kgx_utils import contract, expand
log = get_logger()
class PrefixManager(object):
"""
Manages prefix mappings.
... |
60ea5691453ef7704f196a6ab56db25b5776c67a8c1521c9ae1fbb258d41f2a0 | Python | 6,618 | 186 | import os
import sys
import itertools
import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
import bdpy
from itertools import product
# Adding the parent directory to sys.path for module imports
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from... |
c748aaebf3e73f768c4fea015d63bc8fef43f91bbb4da615cf58ce09e9777347 | Python | 6,618 | 187 | import torch
import time
import torch
import torch.distributed as dist
import torch.nn.functional as F
import numpy as np
import utils
from functools import partial
def train_epoch(
epoch,
data_loader,
model,
criterion,
optimizer,
device,
current_lr,
e... |
f5764239bd9fbcf3f8408cb5004b3566c453b87209d96504da3cc674e440e684 | Python | 6,620 | 215 | # 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... |
4157996dec398cdf85de99a3d500848d82294210c89f1bc71b644cf9b0e35052 | Python | 6,623 | 180 | import numpy as np
import pandas as pd
from sklearn.metrics import *
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
def regression_matrices(true, pred):
print('Converting to original value')
print(f'ground truth: max {true.max():.3f}, min {true.min():.3f}')
print(f'prediction: mean {pred... |
4d3dccaee69db38649fb9017afc958e786b8909f476072c425db37f062ae053f | Python | 6,629 | 203 | import pytest
import keras
import numpy as np
from keras import layers
from keras import backend as K
def test_sublayer_tracking():
# basic case
class MyLayer(layers.Layer):
def __init__(self):
super(MyLayer, self).__init__()
self._input_shape = (2, 4)
self.dense =... |
ffb9536cf1fb15c12b22a82a7d2337258e2d7a7afa2320a9c38e6f88a1afb3f2 | Python | 6,635 | 210 | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib.ticker as ticker
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
EV_list = [
25,
100,
500,
1000,
]
plt.figure... |
da0d8d778926d4c637157f6b48f0bb5bd80187911a4943e8c1fd9f52b1288468 | Python | 6,637 | 227 | import os
from unittest.mock import ANY, call
from medperf.commands.execution.container_execution import ContainerExecution
from medperf.exceptions import ExecutionError
from medperf.tests.mocks.cube import TestCube
from medperf.tests.mocks.dataset import TestDataset
from medperf.tests.mocks.execution import TestExecut... |
2aa368b37e520537c8c90704e2595d4a24df304f1b37a58da8d86e8dff52340b | Python | 6,638 | 196 | # -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from catmaid.control.authentication import requires_user_role, can_edit_or_fail
from catmaid.models import Point, UserRole
from catmaid.serializers import PointSerializer
from rest_framework.re... |
7b0bf579504976c2a83b6a44558c24b5845fead6678e5f5b1707c034a43a6f74 | Python | 6,650 | 176 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
b76acd1524245e9c6cd623f677dcbecda2f003861ba4e4d85482b9fc9a816bc3 | Python | 6,653 | 171 | import os
import numpy as np
import pandas as pd
from sklearn.metrics import *
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
from Metrices import regression_matrices, classification_matrices
from Metrices import ensemble_pred_regression, ensemble_pred_classification
def ensemble_pred_regression(c... |
0420d678d4ce5ed06c272cc06a866d2322b11facdff0d6cb0d50536fde59c26d | Python | 6,654 | 159 | import pytest
from CybORG.Simulator.Actions.Action import InvalidAction
from CybORG.Simulator.Process import Process
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import EnterpriseScenarioGenerator
from CybORG.Agents.SimpleAgents.ConstantAgent import SleepAgent
from CybORG.Simulator.Actions.AbstractActio... |
c9b6ea027e968cea189e28341ea023c29db15e280f31a76b83d146e6e23e6fa3 | Python | 6,660 | 178 | """Utilities related to losses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from .. import backend as K
class Reduction(object):
"""Types of loss reduction.
Contains the following values:
* `NONE`: Un-reduced weight... |
4843b36907adfa364c650f29660e66bdb02a02392ae4ade7ec7bc1ea40a1ef83 | Python | 6,661 | 180 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from transformers.modeling_utils import PreTrainedModel
from transformers.configuration_utils import PretrainedConfig
from fengshen.models.DAVAE.DAVAEModel import DAVAEModel
from fengshen.models.PPVAE.utils impor... |
11db96bdac6950c5a48a42c733a389b64af1956497b2ac42f9936ee65200b865 | Python | 6,665 | 185 | import argparse
import os
import json
import torch
from fengshen.models.llama.configuration_llama import LlamaConfig
__HF_NORM_PREFIX__ = "llama.final_layer_norm"
__HF_EMBED_IN_KEY__ = "llama.embed_in.word_embeddings.weight"
__HF_EMBED_OUT_KEY__ = "embed_out.final_linear.weight"
__HF_LAYER_PREFIX__ = "llama.layers"
_... |
bd4adc2ec1091ac7f975bdb08b4a537fcb003e3dd541f4a74fbcb76a8c616487 | Python | 6,665 | 218 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from langchain.llms.base import LLM
from typing import Any, List, Mapping, Optional, Dict, Union, Tuple
from pydantic import Field
from llm.self_llm import Self_LLM
import json
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
import _threa... |
6d4315605464d27860717b9eeaba1763bef9e8d903de69afdb11167a1b5914e3 | Python | 6,666 | 195 | import math
import os
from typing import Optional
import torch
import torch.utils.data
# from tonic import DiskCachedDataset
from torch.utils.data import DataLoader, Dataset, TensorDataset
import pytorch_lightning as pl
from datasets.utils.pad_tensors import PadTensors
import numpy as np
import scipy.io
import torch... |
0bcb850f03c2f6b6383f22cbb53022a117fbfe02ca4b3123199cb68c1e8d0d0b | Python | 6,669 | 167 | import pandas as pd
import time
import jaxkineticmodel.parameter_estimation.training as train
import jaxkineticmodel.parameter_estimation.initialize_parameters as init_params
import optax
import argparse
import numpy as np
from jaxkineticmodel.load_sbml.sbml_load_utils import get_global_parameters
from jaxkineticmode... |
f0c3146b637f7ed6b876962ea42248c0820a103096a45582253370117c39bbcf | Python | 6,680 | 172 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
import scanpy as sc
from anndata import AnnData
from copy import deepcopy
from tqdm import tqdm
# --- Core Model Components ---
class _MLPEncoder(nn.Module):
"""Internal MLP encod... |
79192a0ab50fb96c6d1f3f105ba750e465c9e33b962e9e8dfe7acb35f8d5c9f7 | Python | 6,689 | 221 | """Raw-format detection, metadata inspection, and public read dispatch."""
from __future__ import annotations
import os
from pathlib import Path
from ..params import Params
from ..utils_functions import find_ms_info
from .core import MSData, UNSUPPORTED_RAW_FORMAT_MESSAGE
_UNSET = object()
def get_raw_data_forma... |
fa30cb2b2d36f303034a147e078eec2529ad4805aead5e0969b596a343b5d3cc | Python | 6,690 | 160 |
from typing import Tuple
import numpy as np
import tensorflow as tf
from gpflow import kullback_leiblers
from gpflow.base import Module, Parameter
from gpflow.conditionals import conditional
from gpflow.config import default_float
from gpflow.utilities import positive, triangular
from gpflow.models.model import GPMo... |
219749fb3d8f79b720c48f07bee0013d836896b7d431ab4bfc0b3c645ac74f53 | Python | 6,691 | 195 | import os
from medperf.exceptions import ExecutionError, InvalidContainerSpec, MedperfException
from medperf import config
from medperf.utils import run_command
import shlex
import json
import tarfile
import logging
from docker.auth import resolve_repository_name
def get_docker_image_hash(docker_image, timeout: int... |
d8fde9e0f2908ee8a4e2bd262b1d8780264b9cdd2764b22a5660486d30365bb8 | Python | 6,691 | 204 | """Optimisation class"""
"""
Copyright (c) 2016-2022, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as published
by the Fr... |
3c0c5f9425de63007ccc71343f6a3176e624395cb5cabe2040eb133927913705 | Python | 6,692 | 175 | #!/home/preclineu/hansav/.conda/envs/py38/bin/python
"""
Created on Thu Nov 16 16:27:00 2023
@author: hansav
"""
"""
####################
#SVM classification Contingency Aware vs Unaware --> PERMUTATION
####################
"""
import pandas as pd
import numpy as np
import os
import sys
from pcntoolkit.dataio.filei... |
030c91864ccce6d642457d7604bb941b6bb04fba9f14fa4d00c9125bf4f67181 | Python | 6,694 | 201 | """
Learning to rank with the Dask Interface
========================================
.. versionadded:: 3.0.0
This is a demonstration of using XGBoost for learning to rank tasks using the
MSLR_10k_letor dataset. For more infomation about the dataset, please visit its
`description page <https://www.microsoft.com/en-... |
284f7daf44b82c69b08a4c85f2b4b6f51a3b10bc881a48b7cc0eefcc4b6bbf70 | Python | 6,695 | 210 | import warnings
from keras.applications.inception_v3 import InceptionV3
from keras import backend as K
import numpy as np
def update_mean_cov(mean, cov, N, batch):
batch_N = batch.shape[0]
x = batch
N += batch_N
x_norm_old = batch-mean
mean = mean + x_norm_old.sum(axis=0)/N
x_norm_new = batch-mean
cov = ((N-... |
db276f9885c8510acec042a6afe4e24b8f9f93c51bd30549e45d88fe4626ea85 | Python | 6,708 | 227 | """Script for downsampling raw files to reconstruction resolution."""
import os
import re
import nibabel
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
import brainbuilder.utils.ants_nibabel as nib
from brainbuilder.utils import utils
from brainbuilder.utils.paths import define_new_path_... |
917ae639ab9821628efde8e07872f6cfe06ec7dd50f6d0dd45ecd1475c35f295 | Python | 6,709 | 174 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmengine.model import BaseModule
try:
from mmdet.models.dense_heads import MaskFormerHead as MMDET_MaskFormerHead
except ModuleNotFoundError:
MMDET_MaskFormerH... |
dff7622e077e15b2b27b4c4ef1577d8812a75879f8e94e25e2f1612cb145ca41 | Python | 6,715 | 164 | """
This scripts trains causal graphTRIP models.
Dependencies:
- experiments/configs/medusa_graphtrip.json
Outputs:
- outputs/medusa_graphtrip/weights/seed_{seed}/
- outputs/medusa_graphtrip/permutation_importance/seed_{seed}/
- outputs/medusa_graphtrip/estimate_propensity/seed_{seed}/
- outputs/medusa_graphtrip/esti... |
6ac73d3a1c41f8e83d968ac786dfd4a73d28df32e96e4c4dd13210518946e787 | Python | 6,716 | 175 | # Copyright (c) OpenMMLab. All rights reserved.
import glob
import os
from os.path import dirname, exists, isdir, join, relpath
import numpy as np
from mmengine import Config
from mmengine.dataset import Compose
from mmengine.registry import init_default_scope
from torch import nn
from mmseg.models import build_segme... |
d9e1a1b5a5b407ba43dc3fc6b806741f1cd3eac5f25c42ca1adc1200c7253f46 | Python | 6,720 | 124 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
f215353e23bdeaec6be4bbf188cc2ad3953fef80ad8316fa7060e740a033e684 | Python | 6,723 | 200 | import pandas as pd
import pprint
from tqdm import tqdm
tqdm.pandas()
import pickle
import random
import numpy as np
from rdkit import Chem
# suppress rdkit warning
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
from rdkit.Chem import AllChem
from rdkit.Chem.Draw import rdDepictor
ATOM_LIST = ['C', 'H', '... |
da89c4276d77c93df5b008934caca462bb1cb3b82c44a9d9c0d3aaf2ec85d6b0 | Python | 6,724 | 236 | from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum, auto
import numpy as np
from dante.utils import Tracker
class BuiltInSyntheticFunction(Enum):
ACKLEY = auto()
RASTRIGIN = auto()
ROSENBROCK = auto()
GRIEWANK = auto()
MICHALEWICZ = auto()
SCHW... |
e0e439207cf6efec9d5af16cdbb99fa455cfeb523ab4cccaa76d62202b624ab3 | Python | 6,725 | 173 | from torch.utils.data import Dataset, ConcatDataset
import os
from concurrent.futures import ProcessPoolExecutor
import pandas as pd
def add_data_args(parent_args):
parser = parent_args.add_argument_group('taiyi stable diffusion data args')
# 支持传入多个路径,分别加载
parser.add_argument(
"--datasets_path", t... |
0fb72e9fee4f8191c0ed85aa1e2ad0ef53d3e0c86c9f1179aea694c4c12ec4c6 | Python | 6,731 | 166 | import sys
sys.path.append("/home/plent/Documenten/Gitlab/NeuralODEs/jax_neural_odes")
from jaxkineticmodel.parameter_estimation.initialize_parameters import *
from jaxkineticmodel.parameter_estimation.training import *
import time
import argparse
jax.config.update("jax_enable_x64", True)
def main():
parser... |
02bd8921c6d0bb09231ccfcb13be865770a85786be58a51c6062c6f7a91a771b | Python | 6,732 | 149 | import os.path as osp
import numpy as np
import random
import torch
from easydict import EasyDict as edict
import argparse
import pdb
class cfg():
def __init__(self):
self.this_dir = osp.dirname(__file__)
# change
self.data_root = osp.abspath(osp.join(self.this_dir, '..', '..', 'data', 'KP... |
767334e5f1f7d877268bf857c6ac24f0dd500b50279d3348cd77fa263c4f53a8 | Python | 6,733 | 254 | import sys
import numpy as np
import pytest
from hypothesis import given, settings, strategies
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing import no_cupy
from xgboost.testing.data_iter import check_invalid_cat_batches, check_uneven_sizes
from xgboost.testing.updater import (
check... |
09212a70de18f35b02161e0eaba7399d0c3c51506eed3b52d5a77ade575a592a | Python | 6,736 | 299 | # Bond lengths from:
# http://www.wiredchemist.com/chemistry/data/bond_energies_lengths.html
# And:
# http://chemistry-reference.com/tables/Bond%20Lengths%20and%20Enthalpies.pdf
"""
For adding bond using EDM method
Modified from EDM repo
"""
bonds1 = {
"H": {
"H": 74,
"C": 109,
"N": 101,
... |
3504a479deb2a22eb7bc8120ea4d78d5dc81a1e88de561a0933c17fd1e270b2d | Python | 6,737 | 205 | import itertools
from copy import deepcopy
import ase
import numpy as np
import torch
from ase.neighborlist import natural_cutoffs, neighbor_list
from e3nn.util.jit import compile_mode
from mace.data.atomic_data import AtomicData, get_data_loader
from mace.data.utils import config_from_atoms
from mace.modules.blocks i... |
5184627bdf11a384aac916e925dbce3023ced31de9e197d3cf0ae469b27a8695 | Python | 6,739 | 234 | import torch
import torch.nn.functional as F
from rde.utils.protein.constants import BBHeavyAtom
from .topology import get_terminus_flag
def safe_norm(x, dim=-1, keepdim=False, eps=1e-8, sqrt=True):
out = torch.clamp(torch.sum(torch.square(x), dim=dim, keepdim=keepdim), min=eps)
return torch.sqrt(out) if sqr... |
b13409e62d2bad1dd81cd394105871dcbb2889de863345a0c3fe980bd8d00f18 | Python | 6,739 | 156 | import numpy as np
import tensorflow as tf
import time
import datetime
import os
import sys
import h5py
from pathlib import Path
import evidential_deep_learning as edl
from .util import normalize, gallery
class Dropout:
def __init__(self, model, opts, dataset="", learning_rate=1e-3, tag=""):
self.model =... |
2efa9332653ae1a03517d3b5470d8443ca4a89b9170fff1dfbc1598ef465b63f | Python | 6,741 | 183 | import os
import torch
import numpy as np
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, ConcatDataset, Dataset
from PIL import Image
# Unified label mapping for all datasets
CLASS_MAPPING = {
'vehicle': 0,
'signpost': 1,
'obstacle': 2,
'stoplight': 3,
'pedest... |
30a85a4f7d1372d8369ac3c07e0f98cd6b61cdaa1bce64e6feed6474ba908cb9 | Python | 6,741 | 209 | from prov.identifier import Namespace
__author__ = "Trung Dong Huynh"
__email__ = "trungdong@donggiang.com"
XSD = Namespace("xsd", "http://www.w3.org/2001/XMLSchema#")
PROV = Namespace("prov", "http://www.w3.org/ns/prov#")
XSI = Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
# C1. Entities/Activitie... |
9abf9d9aa9fbeab61b6227012bd1b873bbec0ec2c9c6ce48d9c65821308405b2 | Python | 6,746 | 167 | """This module handles resolution of SoftwareRequirement hints.
This is accomplished mainly by adapting cwltool internals to galaxy-tool-util's
concept of "dependencies". Despite the name, galaxy-tool-util is a light weight
library that can be used to map SoftwareRequirements in all sorts of ways -
Homebrew, Conda, cu... |
907bbc82cb6cf0e042d55a5882a145dd8365b69165c65de5659bacddea4cc494 | Python | 6,751 | 272 | import random
from torchvision import transforms
from torchvision.transforms import functional as F
from torch.nn.functional import pad
from torch import tensor
from PIL import Image
from math import ceil, floor
from numpy import rot90
class Compose(transforms.Compose):
def randomize_parameters(self):
f... |
469851d8aee9b3d18382c0e2aa1a068c1dcbe05efe01001efd6b8a58157b2519 | Python | 6,752 | 196 | import logging
from pathlib import Path
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
def _classify_csv_file(path: str | Path) -> str:
"""
Classify a single CSV file as belonging to one of three modalities.
Parameters
----------
path : str or Path
Absolute ... |
9d627d254db13e760973b1c44e4c20b3f9ad9b25520c3c1356132a0f3ed4c92a | Python | 6,758 | 172 | import logging
import numpy as np
from .io_utils import (
decide_naming_convention,
is_continuous_label,
recording_site_from_channel_path,
)
from .realignment import concatenate_and_realign_data, realign_ttl_timestamps
logger = logging.getLogger(__name__)
def eliminateData(
filepath_to_timestamps: ... |
a360cb38b549bb1fd9feb4a8e5198d46398b415751a25b90527eaa0b625b7525 | Python | 6,759 | 203 | #!/usr/bin/env python
#
# CLI script to crop an image
#
# Copyright (c) 2019 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
import textwrap
from spinalcordtoolbox.cropping import ImageCropper
from spinalcordtoolbox.image import Image, add_suffix
fr... |
8ecfc696b6c038c0b0a4d88282161bf8c3b2317986f81cfd7eb81fe97ae7bf46 | Python | 6,760 | 156 | # -*- coding: utf-8 -*-
"""
| Authors | Emails |
|----------------|-----------------------------|
| Youssef Radwan | yo.radwan@nu.edu.eg |
| Eslam Mohamed | es.ahmed@nu.edu.eg |
Utilities to apply preprocessing techniques for EEG data.
"""
from sklearn.decompo... |
ba534a0f508e3d2c9c78b21166ddae436306fcf4011d319e95549c5d40a072e7 | Python | 6,761 | 139 | import numpy as np
from guppy.analysis.combine_data import combine_data, eliminateData, eliminateTs
# ── eliminateData ─────────────────────────────────────────────────────────────
def test_eliminate_data_two_filepaths_concatenates_and_starts_at_lights_turn_on():
# filepath1: ts=[0,1,2], data=[10,20,30], timeFo... |
dcf025db2801f29668125be1f1d490940e0b3d4eeb9c658604cb111e0fd1ac5a | Python | 6,764 | 169 | """Morphology related utils functions."""
# Copyright (c) 2022 EPFL-BBP, All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE BLUE BRAIN PROJECT ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE ... |
26d05b55f8bc2f3dfd8d284029bc9aa5285597901b6c4d027a4d0eae44a81cb8 | Python | 6,766 | 204 | """Tests for authentication endpoints (zndraw-auth / fastapi-users)."""
import pytest
from httpx import AsyncClient
from zndraw_auth import User
# =============================================================================
# Login Tests
# ============================================================================... |
ae5187da82da32c46a8c5d8fe92c9e213d46649892faeeb113ca4f36669b2aba | Python | 6,768 | 151 | import json
import os
from collections import defaultdict
from pathlib import Path
from src.ubergraph import UberGraph
from src.util import Text
def pull_uber_icRDF(icrdf_filename):
"""
Download the icRDF.tsv file that contains normalizedInformationContent for all the entities in UberGraph.
"""
uber ... |
38c42cb7ff4e0873d832d8c233d2a0ac433c97263219ea6d26d42a16bbf33aca | Python | 6,772 | 224 | """Tests for CLI frames commands."""
from __future__ import annotations
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from zndraw.cli_agent import app
from zndraw.schemas import FrameBulkResponse, StatusResponse, StepResponse
from .conftest import invoke_cli
if TYPE_CHECKING:
from t... |
6688db39f0baf0df3b75ac373654d4f0eb2066cfe99e5fe23bae1db80148bccc | Python | 6,772 | 202 | #!/usr/bin/env python
# coding: utf-8
import os.path as op
import random
import time
import matplotlib.pyplot as plt
import numpy
import sklearn
import torch.nn.functional as nn_func
from sklearn import preprocessing
from sklearn.metrics import adjusted_rand_score
from torch.nn import Linear
from torch_geometric.data... |
6ee29438d4b1edb15d34f31b5cf21402cb5e923a5cfa777b7c20eaa58337b442 | Python | 6,775 | 175 | import argparse
import pickle
import copy
import functools
import numpy as np
import sklearn.metrics
import tensorflow as tf
import tsgm
N_EPOCHS_DEFAULT = 10
BATCH_SIZE_DEFAULT = 256
LATENT_DIM_DEFAULT = 16
N_EPOCHS_EVALUATOR = 100
N_LAYERS_EVALUATOR = 1
N_EVALUATORS = 2
class PredictNextEvaluator:
def __init... |
25a10dea7bda0521def8e5c263df6a4cd016203824847e75004ad779abbd1707 | Python | 6,777 | 308 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import shutil
from functools import partial
import numpy as np
from mmengine.utils import (mkdir_or_exist, track_parallel_progress,
track_progress)
from PIL import Image
from scipy.io import loadmat
COCO_... |
4f458fe92f0888b0bad62cd69c475d849cd005f24efbb67317fbec7cdb50ae3f | Python | 6,777 | 222 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class TimeEmbedder(nn.Module):
def __init__(self, dim, total_time):
super().__init__()
self.dim = dim
self.total_time = total_time
def forward(self, x):
device = x.device
half_dim = s... |
bbcc018becec1ecf057dd1bc1efcdeeec58ff3ed03a2ae3115cd93c3a770cade | Python | 6,778 | 178 | import inspect
import math
from bisect import bisect
from typing import List, Optional
import torch
from ocpmodels.common.typing import assert_is_instance as aii
def multiply(obj, num):
if isinstance(obj, list):
for i in range(len(obj)):
obj[i] = obj[i] * num
else:
obj = obj * nu... |
156c9dccdf4ed954f879311b50ee7087480197c42769e69e08ad0897b7ddf88a | Python | 6,784 | 122 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
75b2cb0e3e8fcf3c3cfad1291209541eb6351c08f406fdadc57d0e0745387213 | Python | 6,786 | 124 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
bd6d11c1ccd9428e4f592f514cb2a222abba47a67e569d5235f693f142e3373d | Python | 6,790 | 200 | import os
import re
from pathlib import Path
import glob
from tqdm import tqdm
from contextlib import ExitStack
import datasets
import multiprocessing
from typing import cast, TextIO
from itertools import chain
import json
from concurrent.futures import ProcessPoolExecutor
from random import shuffle
from pytorch_lightn... |
dbfb7a3b73c6b0aa4344cdbfb1a699cb0513c981b79e337cd7aeec2e3aababd3 | Python | 6,790 | 200 | import logging
import os
import ase.io as ase_io
import numpy as np
import torch
from hydromace.interface import HydroMaceCalculator
from simgen.atoms_cleanup import cleanup_atoms
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
fro... |
06c4068c6cb1fccf02f35f2776dd86efa37f501b7f8e6f3910b80353fb48363d | Python | 6,793 | 223 | import open3d
import numpy as np
import matplotlib.pyplot as plt
def update_view(camera, intrinsics, extrinsic, width, height):
z_near = camera.get_near()
z_far = camera.get_far()
camera.set_projection(intrinsics, z_near, z_far, width, height)
R = extrinsic[:3, :3]
t = extrinsic[:3, 3]
eye = ... |
90822374f4902e138258e66f3b1db987dd6a0b8d8ebfd08a1d485810d7eda25f | Python | 6,793 | 178 | import os
import shutil
from unittest import TestCase
import numpy as np
import scipy
from pyalfe.image_registration import (
ImageRegistration,
GreedyRegistration,
AntsRegistration,
)
from tests.utils import create_nifti, get_nifti_data
def get_image_registration_test(
image_registration: ImageRegi... |
3d5fff744a4fb817af6f0a7859c0d8f2b41a961d6d9178c6a31772cd9e413430 | Python | 6,797 | 161 | """Embedding layer.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend as K
from .. import initializers
from .. import regularizers
from .. import constraints
from ..engine.base_layer import Layer
from ..legacy import interfaces
from ... |
1f6771fabb6de35344671c3578ac89ac141a6ac5c2f36cf46ec5d14d9ee9654c | Python | 6,798 | 124 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
2dd5c012a3ab6ae871edfee0b5f8be6acfd26fe0a4c6eb3a4855b894e5a1f4cb | Python | 6,799 | 199 | from glob import glob
import os
from typing import Optional
import numpy as np
from fire import Fire
from soccertrack.utils.camera import find_intrinsic_camera_parameters, Camera
from soccertrack.utils.utils import make_video
from soccertrack.utils import logger, set_log_level
class CLI:
"""CLI for soccertrack... |
cc761bb164f06cc25a34b0416b68d276fb1fd9716e23f95fade3f41206219a9a | Python | 6,799 | 136 | import sys
import pandas as pd
import numpy as np
# データを読み込む
infile = sys.argv[1] # 入力ファイル例: "m1_1_1_6-6-6-6-6-6s_50px_24.0mmps_weak_track.tsv"
outfile = sys.argv[2] # 出力ファイル例: "m1_1_1_6-6-6-6-6-6s_50px_24.0mmps_weak_track_modified.tsv"
total_duration = float(sys.argv[3]) # トラッキングデータ全体の時間(秒)
cut_duration = float(sy... |
94dfd8b4dc1f3459d44e64aec567d67e32b5ffc23e4a0c3d05ef842adbbb8fde | Python | 6,803 | 195 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import csv
import json
import logging
import pickle
import time
import glob
from pathlib import Path
impor... |
aa65077280e5cf4a47da11952309418be98c21978c3a6f77b9d4d016de5191fc | Python | 6,803 | 201 | from medperf.comms.entity_resources import resources
from medperf.exceptions import MedperfException
from .utils import (
check_allowed_run_args,
add_medperf_run_args,
add_user_defined_run_args,
add_medperf_environment_variables,
add_network_config,
add_medperf_tmp_folder,
check_docker_image... |
2f9081fead7aba19e859f822d09e42439a0d21b32a9c825ec6cf8c0e77233022 | Python | 6,809 | 180 | import base64
import uuid
from medperf.entities.certificate import Certificate
from medperf.entities.ca import CA
from medperf.utils import (
approval_prompt,
get_decryption_key_path,
validate_and_normalize_emails,
)
from medperf import config
from medperf.exceptions import CleanExit, InvalidCertificateErro... |
afea511a1f78b36027f8fee0b55ce3c1247ed2a1ccc504ff7ecbba7761b2e666 | Python | 6,817 | 250 | #!/usr/bin/env python3
import tensorflow as tf
from multigrid import (
Multigrid,
MultigridOp,
SparseOperator,
MultiIndex,
StencilDict,
get_shift_csr,
)
import multigrid
from multigrid_plot import plot_3d, plot_grid, plot_grid_matrix
import numpy as np
import scipy.sparse as sp
import scipy.spa... |
d5f7c4f48cb98d116881313f5657ec1636f6eaff6298adca58c23476ae0c90f1 | Python | 6,817 | 176 | import numpy as np
import torch
import torch.nn.functional as F
from scipy.special import softmax
from torch_geometric.transforms import Compose # imported by train.py
from models.transition import *
from utils.data import Drug3DData
from utils.dataset import *
from utils.misc import *
class FeaturizeMol(object):
... |
527e90b302f2215f7ba7355256b30ef6b84519f98a7bbc8fa62846678619c326 | Python | 6,819 | 227 | import torch
import torch.nn as nn
from random import sample
from torch.nn.modules.linear import Linear
import torchvision.models as models
import math
import torch.nn.functional as F
from torch.nn.parameter import Parameter
def full_block(in_features, out_features, p_drop=0.0):
return nn.Sequential(
... |
c8cf6f43919cfbc5cee89096d748d4da2c62c1d893796cad0359b668e665a2d0 | Python | 6,823 | 201 | import logging
import os
import ase.io as ase_io
import numpy as np
import torch
from hydromace.interface import HydroMaceCalculator
from simgen.atoms_cleanup import cleanup_atoms
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
fro... |
56a6ddb35caf4368e730f36b1f6ecc765bca7495ee76e283297eb0b4f6dbb299 | Python | 6,827 | 179 | import inspect
import os
import os.path as op
import logging
from glob import glob
from os import path as op
from ..utils import create_file_if_missing
lgr = logging.getLogger(__name__)
from ..info import MIN_DATALAD_VERSION as MIN_VERSION
def prepare_datalad(studydir, outdir, sid, session, seqinfo, dicoms, bids)... |
f09857d359f8b06359b2a0a2cd492334a69c84d78da83ecd4ff987f07caecac2 | Python | 6,829 | 230 | """Main Graupner-Brunel STDP example script"""
# pylint: disable=R0914
import pickle
import bluepyopt as bpop
import matplotlib.pyplot as plt
import numpy as np
import gbevaluator
import stdputil
cp_filename = 'checkpoints/checkpoint.pkl'
evaluator = gbevaluator.GraupnerBrunelEvaluator()
opt = bpop.optimisations.D... |
01a596e3b29a6ea54cbb17b4fda00ccc622008f36c16b674589228c6fb7eccdc | Python | 6,831 | 212 | # Copyright DST Group. Licensed under the MIT license.
import sys
from typing import List
from CybORG.Shared import Scenario
from CybORG.Shared.ActionSpace import ActionSpace
from CybORG.Simulator.Actions import Action, Sleep
from CybORG.Shared.Observation import Observation
from CybORG.Shared.Results import Results
... |
c171bc3b53465bc19d857e56a345f3fc7478d736a5a4db1d88e9e2d297bc4c1d | Python | 6,832 | 204 | import numpy as np
import time
from sklearn.metrics import f1_score, precision_score, recall_score
import bottleneck as bn
# consider delay threshold and missing segments
def get_range_proba(predict, label, delay=7):
splits = np.where(label[1:] != label[:-1])[0] + 1
is_anomaly = label[0] == 1
new_predict =... |
c62ae54797222d4c975ff6d671f8050fca69702588ecd8d9d577b54edaf1e86d | Python | 6,834 | 148 | """
DataLoader.py (pl.LightningDataModule)
Default class for data loaders from:
- csv file
- files in directory
"""
from transforms.preprocessing import AddChannelIfNeeded, AssertChannelFirst, ReadImage, To01
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import pytorch_li... |
af67e80eb988fafd5672e9a7f9e03785fb1921f93ec9cf65524fc9edbb049424 | Python | 6,838 | 234 | import numpy as np
import unireedsolomon as rs
from unireedsolomon.rs import GF2int
import struct
def has_hp(seq):
"""Whether a DNA sequence contains a homopolymer (i.e. two or more nucleotides).
Parameters
----------
seq : str
DNA sequence as a string.
Returns
-------
boolean
... |
b937d36af27c16daac2b57ade03b42d1adcf46baec3f12f5eb0f937fbacd03a7 | Python | 6,844 | 163 | import os
from medperf.entities.dataset import Dataset
from medperf.utils import (
generate_tmp_path,
sanitize_path,
untar,
move_folder,
remove_path,
)
import medperf.config as config
from medperf.exceptions import ExecutionError, InvalidArgumentError
import yaml
class ImportDataset:
@classmet... |
3ab580395ec67bda1535f0eadc7425056b3ddff3ed56ac9b1971c5976682278b | Python | 6,846 | 216 | # imports
import json
import time
import pickle
import scipy.misc
import skimage.io
import caffe
import numpy as np
import os.path as osp
from xml.dom import minidom
from random import shuffle
from threading import Thread
from PIL import Image
from tools import SimpleTransformer
class PascalMultilabelDataLayerSync... |
9360a975bcdf7e8a818c9bf4db78e584838c84289b708bce6b9816859aac611c | Python | 6,847 | 187 | import typing as T
import logging
import scipy
import os
import numpy as np
import math
from keras import ops
from tsgm.types import Tensor as TensorLike
import tsgm
logger = logging.getLogger('utils')
logger.setLevel(logging.DEBUG)
def _ensure_float32_compatibility(kernel_result):
"""Ensure kernel results ar... |
5fc069536e854a4c0d533161b45121484d23923ae7b6294a933e994beca4a407 | Python | 6,849 | 205 | #
# properties.py: handle node- and clique-level properties for Babel.
#
# Property files are JSONL files that can be read into and out of the Property dataclass.
# So writing them is easy: you just add each property on its own line, and if you go through
# Property(...).to_json_line() we can even validate it for you (... |
c7683535a40853698d531572402556e44cce6e8aade20ab8e2ea83dc0ed07065 | Python | 6,849 | 145 | """``babel-overused-xrefs`` — which xref targets in a concord are claimed by many subjects?
Every concord row is fed to ``glom()`` as an equivalence, so one target claimed by many subjects
fuses all of them into a single clique. That is the failure mode
:func:`src.babel_utils.remove_overused_xrefs` drops and ``OVERUSE... |
715d2ea09d03c53acfb83c178e884fed8fc8db05b4f5442d2d068b2354415abe | Python | 6,855 | 176 | #!/usr/bin/env python
import logging
import os
import sys
from argparse import ArgumentParser
from .. import __version__
from ..main import workflow
lgr = logging.getLogger(__name__)
def main(argv=None):
parser = get_parser()
args = parser.parse_args(argv)
# exit if nothing to be done
if not args.f... |
5a1a1494af179dc66bcdbc00f9fe1bc98b585a5c67508aeab16fc06d1ba5a570 | Python | 6,857 | 155 | import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import primo.tools.sequences as seqtools
subpen = np.array([-1.7449405080809126, -1.275485084790358, -1.8001827224086722, -1.9323849500279549, -1.6677722398632207, -1.6537370694565101, -1.8981469677400609, -1.0814292717607923, -1.323115251... |
9a99f040618153ffcc6257d892a2a8a26ab08be4a8484a7a7f2f127900e2a2c2 | Python | 6,860 | 197 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
from mmengine.config import Config, DictAction
from mmengine.registry import init_default_scope
from mmengine.utils import mkdir_or_exist, progressb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.