sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
8a706e7643676eb8755c8befe648c3e079254c109b894693d75e8ce4fde31ad4
Python
5,541
148
# b0_correction.py import numpy as np import matplotlib.pyplot as plt import SimpleITK as sitk import scipy.ndimage def formula(value): """Converts the raw B0 map values into millimeter shifts.""" G_read_percentFLASH = 5.563298 / 100 PVM_GradCal = 42797.5 new_value = value / (G_read_percentFLASH * PVM...
f75cfc5c85f435d9962634de676caec9d917c37c76305fec604e4dac3c0eb43a
Python
5,544
132
import torch import torch.nn as nn import copy from .so3 import SO3_Embedding from .radial_function import RadialFunction class EdgeDegreeEmbedding(torch.nn.Module): """ Args: sphere_channels (int): Number of spherical channels lmax_list (list:int): List of ...
6f71177f54a85ea7093a7791ebe80d4aa424b6a502e439982954a4be11389392
Python
5,545
182
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmengine.optim import OptimWrapper from mmengine.structures import PixelData from torch import nn from torch.optim import SGD from mmseg.models import SegDataPreProcessor from mmseg.models.decode_heads.cascade_decode_head import BaseCascadeDecodeHead fr...
29c93fd853659aa98ccd226c8e1566ba1fdb2c5d21196df2ebd2e4a79123ab14
Python
5,546
157
import shutil import numpy as np from guppy.extractors import ( CsvRecordingExtractor, DoricRecordingExtractor, NpmRecordingExtractor, NwbRecordingExtractor, TdtRecordingExtractor, ) from guppy.orchestration.read_raw_data import _build_event_to_extractor from guppy_test_data import STUBBED_TESTING...
5b1fe670fc3f3bc6157361ba680cf022a957c4b5843336063517d265289dbbef
Python
5,549
153
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmengine import Config from mmengine.structures import PixelData from mmseg.models.decode_heads import Mask2FormerHead from mmseg.structures import SegDataSample from mmseg.utils import SampleList from .utils import to_cuda def test_mask2former_head()...
e51d28710cd74cf8de38751add747d5b1ce393096c40b4b01c1d1c89c1bd9415
Python
5,551
153
#!/usr/bin/env python import logging import os import os.path as op import re import subprocess import time import json from collections import deque, OrderedDict from datetime import date import inotify.adapters from inotify.constants import IN_MODIFY, IN_CREATE, IN_ISDIR from py.path import local as localpath from t...
5f4914cdfdbff5311d178f55138341834a3d8b6f4e50dea66d4030de17269201
Python
5,552
165
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 6 10:38:45 2023 @author: george """ #%matplotlib qt from matplotlib import pyplot as plt import numpy as np import skimage.io as skio from skimage.filters import threshold_otsu from skimage.morphology import closing, square, remove_small_objects,...
db08216ed2328211a306d8516b27972b107a8262bc94a0e53a493200d4b187a5
Python
5,552
197
"""Expsyn synapse parameter fitting""" # pylint: disable=R0914 import os import argparse import bluepyopt as bpopt import bluepyopt.ephys as ephys def create_model(sim, do_replace_axon, return_locations=False): """Create model and optionally return locations dict""" if sim not in ['nrn', 'arb']: r...
cfa9da6d17ee0e0441c6b2728f35ca9cb6452bf7250e48865756555610462749
Python
5,556
145
import numpy as np import pandas as pd import panel as pn import pytest from guppy.analysis.io_utils import write_hdf5 from guppy.analysis.standard_io import write_binned_metrics_to_hdf5 from guppy.frontend.binned_metrics_view import ( BinnedMetricsView, binned_metrics_sites, build_binned_metrics_view, ) ...
c178288e5253a1c405ef34859de3cb89b837e8c16cf8d8fc6dca5697810715bc
Python
5,557
133
# coding=utf-8 # Copyright 2021 The IDEA 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 a...
fd068aad013e931bc82f9e40c0fac20f17880c70715e5d4e9cee690534ced302
Python
5,557
202
"""Chat REST API endpoints for room messages.""" from datetime import UTC, datetime from typing import Annotated from fastapi import APIRouter, Query, status from sqlalchemy import func from sqlmodel import col, select from zndraw.broadcast import broadcast_to_room from zndraw.dependencies import ( AccessEditDep...
f58e4aa0b1882b2486d27af12b1427dc1400c2e4c3b794cd4266ff05abb455ad
Python
5,558
175
import math from typing import Optional import torch import torch.utils.data from torch.utils.data import DataLoader import pytorch_lightning as pl from datasets.utils.pad_tensors import PadTensors from datasets.utils.transforms import ( Flatten, ) import tonic from tonic.transforms import ToFrame import hydra im...
9d3784168c51ecb7149395fa7fd8c17c577ab9e1ba7a4caf3d1af969dc4026c4
Python
5,559
159
#!/usr/bin/env python3 # # Copyright 2015, Daehwan Kim <infphilo@gmail.com> # # This file is part of HISAT 2. # # HISAT 2 is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
af3558a4ff8e7f0a10dc6b3934364c0c4a7dca5dd90c7e411b03251ce0dd0483
Python
5,559
137
import tensorflow as tf import gpflow from gpflow.kernels import MultioutputKernel, Combination, Kernel from gpflow import covariances from gpflow.config import default_float, default_jitter from gpflow.base import TensorLike from gpflow.inducing_variables import ( SharedIndependentInducingVariables, ) from gpflow....
2af41c8e3021e5e60feb5259c69e36f22619e963f32c34e56ebf1d62e7ea3040
Python
5,563
159
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmseg.registry import MODELS from ..utils import resize from .decode_head import BaseDecodeHead class ACM(nn.Module): """Adaptive Context Module used in APCNet. ...
9e1209df040d3218098c6d3c73abb04b957c27c9689cffea75b3a5b0b7a29292
Python
5,572
199
import torch from torch import nn from einops import rearrange, repeat from einops.layers.torch import Rearrange # helpers def pair(t): return t if isinstance(t, tuple) else (t, t) # classes class PreNorm(nn.Module): def __init__(self, dim, fn): super().__init__() self.norm = nn.LayerNor...
acf166a4066784f873c27e916692260e1e76064592ae98b948591ba50e05d54b
Python
5,574
127
# gff3 to fasta from parse_gene_anno import parse_gff_tree import subprocess CP = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N", "a": "t", "t": "a", "c": "g", "g": "c"} def r_c(seq): new_seq = [] for c in seq[::-1]: new_seq.append(CP[c]) return "".join(new_seq) def get_fa(fn): ch ...
24d52dd9eaf260c01ef7b618a24485266aa152cdceccf6dde1115bfafc34ffc4
Python
5,577
160
from utils.QuickNII_functions import read_QUINT_JSON, find_plane_equation from utils.generate_target_slice import generate_target_slice import numpy as np import cv2 import matplotlib.pyplot as plt import nrrd import sympy as sp from sympy import symbols, solve def generate_rectangular_image(img, pts): # De...
0d3de85b3c0796a1fda665b4dd3070ed8b6d68a2dd1faf19e522d542fabeae9a
Python
5,580
130
import logging import src.datahandlers.mesh as mesh import src.datahandlers.umls as umls from src.babel_utils import glom, read_identifier_file, write_compendium from src.categories import ORGANISM_TAXON from src.metadata.provenance import write_concord_metadata from src.prefixes import MESH, NCBITAXON, UMLS from src....
1be8605933f6018ee00fa337a4e74399155c37ec18ef776f7957b44b362583d8
Python
5,583
182
import os import ot import torch import random import numpy as np import scanpy as sc import scipy.sparse as sp from torch.backends import cudnn # from scipy.sparse import issparse from scipy.sparse.csc import csc_matrix from scipy.sparse.csr import csr_matrix from sklearn.neighbors import NearestNeighbors def filter_...
40e0a02d3dc57b99cce46089eee6725691cb363cf0b62ceef68179ead5fcde14
Python
5,586
149
"""Unit tests for the shared clique-building helper. ``src.model.cliques.glom_from_files`` is the skeleton that each compendium's ``compute_cliques_for_impact_report`` (and, ideally, its ``build_compendia``) routes through. The anatomy CLI test exercises it end-to-end; these tests cover the generic hooks directly: the...
dca1542d92466107073da15803ae6ac15f64af67f4f357257e719d286f563ee0
Python
5,587
175
# !git clone https://github.com/uber-research/TuRBO/ # Commented out IPython magic to ensure Python compatibility. # %cd TuRBO # !pip install . import numpy as np import pandas as pd from tqdm import tqdm import time from collections import namedtuple from abc import ABC, abstractmethod from collections import default...
151c0584af9b95d21a92f397e63fbb3b0657d41a840c50dd5295c91a8aa1fe89
Python
5,591
128
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 Deterministic: def __init__(self, model, opts, dataset="", learning_rate=1e-3, tag=""): self.lo...
ab355070f74696b97474036c7428ab9b307e6d2b2a855f1560b542201cfaab79
Python
5,592
153
import numpy as np import pandas as pd import pytest import xgboost as xgb from xgboost import testing as tm from xgboost.testing.data import run_base_margin_info try: import modin.pandas as md except ImportError: pass pytestmark = pytest.mark.skipif(**tm.no_modin()) class TestModin: @pytest.mark.xfai...
88f535e9e8642048ec48ef238351fcaebe73ca6197a356587cb74a1ad08a6835
Python
5,593
156
# Copyright DST Group. Licensed under the MIT license. import inspect from pprint import pprint from CybORG.Agents.SimpleAgents.BaseAgent import BaseAgent from CybORG.Shared.Enums import TernaryEnum from ipaddress import IPv4Network SUCCESS_TO_TEXT = { TernaryEnum.FALSE.value: 'The action failed!', TernaryEnu...
9c920f39f856589e37401ad497eeb92d1eefec3de36e3223baa2f5e9e0559f23
Python
5,593
196
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utility functions for downloading datasets from OSF """ import os import re from collections import defaultdict from pkg_resources import resource_filename import json MATCH = re.compile( r'space-(\S+)_(?:den|res)-(\d+[k|m]{1,2})_' ) def _groupby_match(fnames): ...
00b4d33f810d6d76e0772b479d44031d34dae4c96f36b9b2a503f98084ba2a1d
Python
5,596
132
#!/usr/bin/env python ## ---------------------------------------- ## scikit-ribo ## ---------------------------------------- ## a module for preprocessing gtf/bed files ## ---------------------------------------- ## author: Han Fang ## contact: hanfang.cshl@gmail.com ## website: hanfang.github.io ## date: 10/28/2016 #...
60da5b01dab2facbc8b24d1e9fd7c0bef3af10b4721096f4974a0d1cb635512f
Python
5,596
182
import ast import json import logging from typing import List import numpy as np import torch from ase import Atoms from e3nn import o3 from mace import modules from mace.data import AtomicData from mace.data.utils import ( config_from_atoms_list, random_train_valid_split, ) from mace.tools import AtomicNumber...
9a768643c60c5692b5a41686ffdf5ace2189093d0c286b1191392410feb6397f
Python
5,597
86
import argparse from fengshen.pipelines.tcbert import TCBertPipelines from pytorch_lightning import seed_everything def main(): seed_everything(123) total_parser = argparse.ArgumentParser("Topic Classification") total_parser = TCBertPipelines.piplines_args(total_parser) args = total_parser.parse_args()...
102e4bed4aadf2d4e90058e4e728be3999c8cb43ea876df958e1c0b6c2ab6c5d
Python
5,606
147
import numpy as np import torch.nn.functional as F from scipy.interpolate import interp1d from scipy.signal import medfilt from scipy.ndimage import maximum_filter1d, gaussian_filter1d def cone_postprocessing(cone_pred, w, maximum_filter_size): cone_prob = F.softmax(cone_pred, dim=0).detach().cpu().numpy() co...
e59f05ed4ced3eabd67c8cf51ac64d824871e58b9683c454611486bdbaeb4d12
Python
5,607
146
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-strict # pyre-ignore-all-errors[2,3] import sys import time from typing import Any, Callable, Dict, List import numpy as np def timeit( num_iters: int = -1, warmup_iters: int = 0 ) -> Callable[[Callable[[], Any]], Callable[[], Dict[s...
0d0ea09b20e1b957e67d146d894cb9aa7aae59b85608d2101955c44514b54f35
Python
5,610
161
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import logging import torch.optim as optim from torch.nn.parallel.distributed import DistributedDataParallel from ocpmodels.common import d...
806ae31b75cc9e4e0d75e77d63fa71438fb2c73d21dca0e920cb352d3151bc8a
Python
5,611
140
from natsort import natsorted import numpy as np from pathlib import Path import os from os.path import join from nnunet_mednext.dataset_conversion.utils import generate_dataset_json import SimpleITK as sitk import gc import multiprocessing as mp from functools import partial def preprocess_dataset(ribfra...
849614b00cf175d9862605570ef46787011453638dc6c6ac49a47a801ebc727b
Python
5,612
168
from rest_framework import status from medperf.tests import MedPerfTest from parameterized import parameterized, parameterized_class class CertificateTest(MedPerfTest): def generic_setup(self): # setup users cert_owner = "cert_owner" ca_owner = "ca_owner" key_owner = "key_owner" ...
a2a95e41bf84dcdcc9b5126afb4c25e7fefe273a66b94e66a32ee1a029899790
Python
5,614
153
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import deeplift from deeplift.layers import NonlinearMxtsMode from deeplift.conversion import kerasapi_conversion as kc import utils # ============================================================================= # set variables...
f4d82b6d50bacefa7671192f6d849560edb356588769565c2df15b7f1460cd92
Python
5,620
166
import numpy as np def mvmd(signal, num_modes, alpha, init=0, sampling_rate=1, tolerance=1e-3, tau=1e-2, verbose=False): """ Multivariate Variational Mode Decomposition (MVMD) The function MVMD applies the "Multivariate Variational Mode Decomposition (MVMD)" algorithm to multivariate or multichannel data ...
883dec16aefb8c832bd836674216c407320fb1aa7e6ebb81aedce345df31e2e4
Python
5,626
137
# 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...
7029f84c04216f1b8a78012d4489bcc6081c654f923c53ea501f1a08b4f910dd
Python
5,630
134
# coding=utf-8 # Copyright 2022 IDEA-CCNL The HuggingFace Inc. team. 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 # ...
164352e5f1b09cc80419c05091225fb4290df3b1f8f9b6a5c901617d76f782a1
Python
5,631
209
from brainsmash.config import parcel_labels_lr from .utils import is_string_like import tempfile from os import path, system import nibabel as nib import pandas as pd from pathlib import Path import numpy as np """ Flexible data I/O - based on murraylab/brainsmash """ def dataio(x): """ Data I/O for core cla...
09ce5815a2ba1944bf2a8be5c384b3b932635b364ecd5b0866f44d34821bd976
Python
5,637
138
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Optional from torch import Tensor, nn from mmseg.registry import MODELS from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, OptSampleList, SampleList, add_prefix) from .encoder_decoder import EncoderDecod...
c1423ac21e8b866ada54a87301d626979be2a230eab5d84e6b4213aa7a07cd0d
Python
5,638
122
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from grid_cell.manifold_fitter import label_mesh from grid_cell.gkr import GKR_Fitter import grid_cell.torus_geometry as tg from scipy.stats import norm from sklearn.decomposition import PCA from grid_cell.ori_tuning_...
5d4eb4bd34a19dd57dfff0df20e320eb434c27956efc1e89a7abc7c8b4218c31
Python
5,640
146
import glob import os import sys import numpy as np import pickle import tqdm import warnings sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import util.config as config from numpy.core.fromnumeric import argsort import lib.heart_volume.heart_utils as hu def count(): base_path = os....
922e8ad40f52243c2d0e3f0f318ef742a664ad336887138ef85b071b379e386a
Python
5,641
171
# -*- coding: utf-8 -*- """ Functions for step 1 Author: Tiziana Tocci """ import os import pandas as pd import numpy as np def select_one_condition(df, cond_column, cond_to_select): """ Function to select part of dataframe based on a condition. Parameters ---------- df : pandas...
29c9f0078bd43a1dbc6bba27653bac1e035ec0bbb18c1ae06418e13e0ffb00ac
Python
5,644
163
"""Functions to create neuroml morphology""" """ 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 pu...
c051dd38ad12b890ca8b6d5e0b00e4f1d12c72fb28917b24081428af9710c4f7
Python
5,644
159
""" Custom build backend for XGBoost Python package. Builds source distribution and binary wheels, following PEP 517 / PEP 660. Reuses components of Hatchling (https://github.com/pypa/hatch/tree/master/backend) for the sake of brevity. """ import dataclasses import logging import os import pathlib import tempfile from...
83c444fa1980a022facf2ebd17abd4ba8ed2a21ab669832c701ef27ff00a9d0b
Python
5,646
163
# -*- coding: utf-8 -*- from typing import List, Tuple, Union from django import forms from django.forms.widgets import Widget import catmaid.fields class Swatch(Widget): """A simple widget that shows a color field for the RGBAWidget.""" template_name = 'catmaid/widgets/swatch.html' class LabeledMultiWid...
4303bc9f87978d9b9cad4f6d0f3a60c7eb0ca344491986a98d3342e48b4e645b
Python
5,647
198
from luna.paths import LunaPaths from luna import candidate_info, dataset from luna.ct import Ct from luna.prepcache import LunaPrepCacheApp from torch.utils.data import DataLoader from Utils.models import * from Utils.TrainModelLUNA import * from Utils.config import * from tqdm import tqdm import matplotlib.pyplot as ...
b7d35c43b7da11077a4f129090d3f3f26fd62ebaf0a9eb9cfa045fcafe2157bc
Python
5,648
148
import numpy as np import tensorflow as tf import tensorflow.keras.backend as K import itertools def face_normals(vertices, faces): edges1 = tf.gather(vertices, faces[:, 1]) - tf.gather(vertices, faces[:, 0]) edges2 = tf.gather(vertices, faces[:, 2]) - tf.gather(vertices, faces[:, 0]) return tf.linalg.l2_...
a0a0e22fc3800b4a7b4fa0e2fc737c78223c97fee325a3064bdca72d0d957d95
Python
5,650
172
import re from pathlib import Path import pytest from .util import get_data, get_main_output, needs_docker test_factors = [(""), ("--parallel"), ("--debug"), ("--parallel --debug")] @needs_docker @pytest.mark.parametrize("factor", test_factors) def test_wf_without_container(tmp_path: Path, factor: str) -> None: ...
e1f4a742ba7edb0562d1c73e4bb270e5451cdad537ac15bd02fc78e7a5f22ef0
Python
5,650
183
import numpy as np from transforms3d.affines import decompose, compose from transforms3d.euler import mat2euler, euler2mat from scipy.ndimage import rotate, shift def transf_from_parameters(T, R): """ Use python module transforms3d to extract transformation matrix from translation and rotation parameters....
73f7089ae5fdacdfcaaf3deca1ca6d9f84d89e7deb9cf97589622a9ef17ba42f
Python
5,657
181
# Copyright (c) Meta Platforms, Inc. and 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 math from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from sam2.modeli...
3df13f643ebf5dc6eeb0780881cfd2fffcb4b486917a7f655da2ed3f8278dcd6
Python
5,658
142
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------- # @File : model.py # @Time : 2024/03/13 17:59:40 # @Author: Zhang, Zehong # @Email : zhang@fmp-berlin.de # @Desc : None # ----------------------------------- import torch import torch.nn as nn import math import numpy as np import ...
134562bca0165bbf44749e6ee624ba30ade385ddf770d3bcd0b6af596f94268e
Python
5,660
159
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os import shutil import itertools from multiprocessing import Pool import numpy as np from dmriqcpy.analysis.stats import stats_mean_in_tissues from dmriqcpy.io.report import Report from dmriqcpy.io.utils import (add_online_arg, add_overwrite_arg...
66f04d9cb1862aaedd7880b533500ccf5d2016ff67192ebafbd7b37ed4c3dc06
Python
5,663
171
"""Create tables for BluePyOpt paper""" import json def load_json(filename): """Load struct from json""" return json.load(open(filename)) def create_feature_fields(): """Create fields for param.json""" features = json.load(open('features.json')) fields_content = '' print(features) ...
905f307c4d4507859d613e103fcd10a2f8c62b931df8888a244a71a2dac1cb9b
Python
5,663
194
"""Tests that run the program in a subprocess""" import subprocess import sys import os import pytest from utils import datapath, assert_files_equal, cutpath def test_run_cutadapt_process(): subprocess.check_call(["cutadapt", "--version"]) def test_run_as_module(): """Check that "python3 -m cutadapt ..."...
ade20f3cf355e4f3506cf67a9dc87bc902227f79d21d7cc641e0eab274c133f7
Python
5,667
158
"""Regression tests: local_token must not be used as client auth token. When the CLI starts a local server, StateFileSource resolves the auth token from state.json. Previously it returned the raw local_token (a random string) which the server rejected as an invalid JWT (401 Unauthorized). The fix stores a real admin ...
d9d0facfe9a699a0f794b9561157f0a93333d33f85045a4a72bec32fd1f434a4
Python
5,672
158
# -*- coding: utf-8 -*- import datetime import json import tempfile import os import numpy as np import pyn5 from pathlib import Path from django.db import transaction from django.test import TransactionTestCase, override_settings from catmaid.models import WritableStack from catmaid.control.stack import get_writabl...
36c983f6c6efef851b38bb2e33f66da1387328c5d11427093aba88b428105ded
Python
5,677
236
#!/usr/bin/env python3 # # Copyright 2018, Chanhee Park <parkchanhee@gmail.com> and Daehwan Kim <infphilo@gmail.com> # # This file is part of HISAT 2. # # HISAT 2 is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
cdcdf1bf9b2f6b30e6bfc859ac85b9475ecf8ed30f7bb86f6c3101233ea3b37f
Python
5,677
130
from CybORG.Shared.RewardCalculator import RewardCalculator from CybORG.Simulator.State import State from CybORG.Simulator.Actions.GreenActions import GreenAccessService, GreenLocalWork from CybORG.Simulator.Actions.AbstractActions.Impact import Impact from CybORG.Simulator.Actions.Action import InvalidAction class B...
0447fde40a844e2070537a98e2be633eaa5ccac8f6eb8c980533bda3aeff125f
Python
5,679
147
# _*_ encoding: utf-8 _*_ import copy __author__ = 'wjk' __date__ = '2020/6/30 11:00' import math import torch import torch.nn as nn import torch.nn.functional as F class GPTDecoder(nn.Module): r"""TransformerDecoder is a stack of N decoder layers Args: decoder_layer: an instance of the Transforme...
f12d990b5f787856329b5686a67c622793b888f3ddd47e1ff379fbd576dfa2cb
Python
5,679
160
from rest_framework import status from medperf.tests import MedPerfTest from parameterized import parameterized, parameterized_class class BenchmarkTest(MedPerfTest): def generic_setup(self): # setup users bmk_owner = "bmk_owner" prep_mlcube_owner = "prep_mlcube_owner" ref_model_...
201999a962eba27e0eeb948d78320ff20f2182b7fb14195712a454d27f353670
Python
5,684
206
from kgx.graph.nx_graph import NxGraph from kgx.graph_operations.graph_merge import ( merge_all_graphs, merge_graphs, merge_node, merge_edge, ) def get_graphs(): """ Returns instances of defined graphs. """ g1 = NxGraph() g1.name = "Graph 1" g1.add_node("A", id="A", name="Node ...
4a88370e6d1348714463eafcb5dfbd93f6a9145c354ec473b7f040558250bab6
Python
5,684
149
# 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. """ Testing native complex number datatypes. """ im...
7c507670dc7208fff73e49d1152349c52ff0d66a358917a9e7dbfa36e0941ac9
Python
5,685
160
# Copyright (c) OpenMMLab. All rights reserved. """Modified from https://github.com/JunMa11/SegWithDistMap/blob/ master/code/train_LA_HD.py (Apache-2.0 License)""" import torch import torch.nn as nn import torch.nn.functional as F from scipy.ndimage import distance_transform_edt as distance from torch import Tensor fr...
4efcf4110c12a6991f10b493e3dd78a05670975af5d5a9e9722b9d16321c5687
Python
5,688
164
import os from medperf.commands.association.utils import ( get_experiment_associations, get_user_associations, ) import yaml from typing import List import medperf.config as config from medperf.entities.interface import Entity from medperf.entities.schemas import TrainingExpSchema from medperf.account_managemen...
e5b1c1e7d2d5ebc90e1e712af2b1e58d7e7413777a9eb45d22da3c57528dfb31
Python
5,688
152
try: import cPickle as pickle except: import pickle import gzip import numpy import os import matplotlib import matplotlib.pyplot as plt from scipy import integrate import pandas as pd """DATA IMPORT""" base_dir1 = '/mnt/csoport31-2/Modellezo_csapat/CA1_pyramidal/Spine_project_validation_results58/Basic_set_n...
bb705ed18dce9d1371a799d2474c977809b5bd5df75fcc1f1f92a78ef5824414
Python
5,689
159
import torch from egnn_pytorch import EGNN, EGNN_Sparse from egnn_pytorch.utils import rot torch.set_default_dtype(torch.float64) def test_egnn_equivariance(): layer = EGNN(dim=512, edge_dim=4) R = rot(*torch.rand(3)) T = torch.randn(1, 1, 3) feats = torch.randn(1, 16, 512) coors = torch.randn(...
c764aeda6f42a80a670d73a1937ab1ea05b70b14c11f74538575a8ccaf2a35fa
Python
5,690
139
#!/usr/bin/env python ## ---------------------------------------- ## scikit-ribo ## ---------------------------------------- ## a module for visualization riboseq data ## ---------------------------------------- ## author: Han Fang ## contact: hanfang.cshl@gmail.com ## website: hanfang.github.io ## date: 10/28/2016 ##...
d2a2af4795610f5e839327f054a7152a1328e0b691181705ac24c83971790b6e
Python
5,690
167
import nibabel import os import numpy as np import dicom import yaml from scipy.ndimage import zoom def prepare_tcia_images(input_path, output_path, cases, img_height, img_width): for n, case in enumerate(cases): print("\rprocessing tcia images:", n + 1, "/", len(cases), end="") volumeID = "{:0>4...
718e4dc06ec5c6d63a204a293c14367117d9d6f290e9704f6868a40e052c9fee
Python
5,691
185
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmseg.models.backbones.beit import BEiT from .utils import check_norm_state def test_beit_backbone(): with pytest.raises(TypeError): # pretrained must be a string path model = BEiT() model.init_weights(pretrai...
144033fe2b78576e8bee0886e2b1d1be6b22ff0d1de70b4e6c2cfae179612d68
Python
5,695
159
#!/usr/bin/python import logging import os import re import sys import polars as pl from isorefiner.common import get_version, func_with_log, run_command, filter_bam logger = logging.getLogger(__name__) def main(args): try: # Set variables raw_input_gtf = os.path.abspath(args.input_gtf) ...
ca5736df0f5ac193ac5a9890d210c3859b5450901b819420175ecf06bba2c60b
Python
5,696
118
"""Generate a mock NWB file for testing the NWB recording extractor with core pynwb 4.0 events. IMPORTANT: This script must be run with pynwb>=4 and ndx-fiber-photometry==0.2.3 installed. The events types (``EventsTable``, ``TimestampVectorData``) are part of the core NWB schema as of NWB Schema 2.10.0 / pynwb 4.0, s...
b9209e67a4f81a2919e7a9d287a998c562cd71944b74ccba807806fef2b63de6
Python
5,698
179
from __future__ import print_function import pytest import numpy as np from numpy.testing import assert_allclose from keras.utils import test_utils from keras import optimizers, Input from keras.models import Sequential, Model, load_model from keras.layers.core import Dense, Activation, Lambda from keras.utils.np_util...
a431d1e057de64d860ceed2fbf9e9aae7ff90dc93f6519844a10a8196036bab5
Python
5,699
140
import numpy as np import scipy.ndimage from collections.abc import Iterable from scipy.interpolate import interpn from .transform import LinearTransform class Slicing(tuple): '''Slice tuple used for indexing subregions of a numpy array.''' def __new__(cls, start, stop): if len(start) != len(stop): ...
d7823d6fe120a267045c4a4746ac026cf53a07e6647fb8eb35e6d120410d4c6e
Python
5,701
175
import re import traceback from collections import defaultdict import requests from more_itertools import chunked from src.prefixes import KEGGCOMPOUND ### # KEGG ### # KEGG has a set of compounds that have a 'sequence' tag # according to https://www.genome.jp/kegg/compound/: # Peptide entries in KEGG COMPOUND ...
575e9fdae17815860588299edd6115f5820337cc84fe091bd43d03bf72069253
Python
5,707
123
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from typing import List import mmengine.fileio as fileio from mmseg.registry import DATASETS from .basesegdataset import BaseSegDataset @DATASETS.register_module() class NYUDataset(BaseSegDataset): """NYU depth estimation dataset. The file st...
c9befeda18ea5d20d1b1a5ca2a4ce572ddef0de318dd6897b0864c13f30da4fc
Python
5,709
155
# -*- coding: utf-8 -*- import logging from django.db import connection from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.contrib.auth.decorators import user_passes_test from django.http import HttpRequest, JsonResponse from django....
132c3b19c4aa13f8d4cc0232b7773282ad2295296d547f83203dbc00040e14b4
Python
5,711
160
# 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. from logging import getLogger import os import sys import torch import socket import signal import subprocess logger = g...
e4b1c0e3258bc588b38723d7a5209f0a7df4da612ce3a54b2e951ee6ed8c2055
Python
5,714
137
import jax.numpy as jnp import jax.tree_util as tree import numpy as np from ase import Atoms from typing import Any, Iterable, List, Mapping, Union from jraph._src import graph as gn_graph ArrayTree = Union[jnp.ndarray, Iterable['ArrayTree'], Mapping[Any, 'ArrayTree']] # TODO: move this to mlff jraph_utils at som...
33499da485055fa20b9f89fe73e73d18d3314ce2389110a1238e311318b456b6
Python
5,715
160
"""Base class for Lie groups.""" import numpy as np from geomstats.invariant_metric import InvariantMetric from geomstats.manifold import Manifold import geomstats.vectorization as vectorization class LieGroup(Manifold): """ Base class for Lie groups.""" def __init__(self, dimension, identity): sup...
adba502385c7feaf45ad48f8332c0beb00b9a20f6c0006fa0a3b3e3f44dc93d3
Python
5,715
125
import torch from torchfunction.device import AutoDevice as device BATCH_SIZE = 256 def get_cdm_input(bs=BATCH_SIZE, noise_inp=0.1): input_tensor = torch.zeros(bs, 61, 4).to(device) ctx = torch.randint(2, (bs, )).to(device) cnd1 = torch.randint(6, (bs, )).to(device) cnd2 = torch.randint(6, (bs, )).to(...
b7a631a46a23b34139c0f5e20eae7152e88ffbed9536d6639ca0ded47408c227
Python
5,717
167
import matplotlib.pyplot as plt import matplotlib import numpy from importlib import reload import sys import os import importlib import types # print(sys.modules.keys()) import multiprocessing import multiprocessing.pool original_packs = sys.modules.copy() try: import cPickle as pickle except: import pickle im...
fc18531b4e53e5ea80f8e7a8d406db542a02851a9a6ec390704dc5d4e7462057
Python
5,717
195
"""Unit tests for the AccessReadDep/AccessEditDep/AccessManageDep composites. Uses the session fixture + direct calls to the async composites, bypassing FastAPI's DI machinery (deferred to Tasks 10/11 integration tests). """ import pytest from sqlmodel.ext.asyncio.session import AsyncSession from zndraw.access impor...
68d1d476570fd49ac096c0e9ebfb70863fbc4e26b69885ae50e512b0dde3b5f6
Python
5,720
199
import binascii import collections import datetime from typing import Optional import pydicom import SimpleITK as sitk ImageMeta = collections.namedtuple( 'ImageMeta', [ 'path', 'series_uid', 'manufacturer', 'seq', 'series_desc', 'tr', 'te', 'fli...
e9d7016635e0ad608705df7ae29d6c14eac4ae9e764a35aa4b604a1145cfa258
Python
5,720
123
from typing import Union, Tuple, Optional from torch_geometric.typing import (OptPairTensor, Adj, Size, NoneType, OptTensor) import torch from torch import Tensor import torch.nn.functional as F from torch.nn import Parameter import torch.nn as nn from torch_sparse import SparseTens...
3e0ea404373124753751fc09c074434ac114f29e78c532670686448f7d7c2ad7
Python
5,728
161
"""Tests of satisfying SoftwareRequirement via dependencies.""" import os import tempfile from getpass import getuser from pathlib import Path from shutil import which from types import ModuleType import pytest from cwltool.context import LoadingContext from cwltool.load_tool import load_tool from cwltool.software_r...
6be67c0d0decf23c6fbe4f9b5ba99f3300abcfde0e6926df8f287b332bd75a7c
Python
5,728
178
from pathlib import Path import subprocess import pandas as pd from typing import Dict, Any from ..logger import logger from .workflow import SnakemakeWorkflow, WorkflowError class NormalizationError(Exception): pass def validate_normalization_inputs(config: Dict[str, Any]) -> None: """ Validate inputs re...
1f4b7decdab82187ece3a8c33512a98947c708c9fa4410d65118d576bc9b3afa
Python
5,729
172
# -*- coding: utf-8 -*- """ Created on Wed Jan 26 15:26:55 2022 @author: A0067501 """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class Interpolate(nn.Module): """ https://discuss.pytorch.org/t/using-nn-function-interpolate-inside-nn-sequential/23588 """ de...
e920425fe8ceab808baf22674b1de3a3137adac972313da383fdace1a8d5c6cb
Python
5,734
171
""" Tests for Transformer parallel mode (multiprocessing-based partitioned export). Currently exercises the only supported combo: DuckDB source + N-Triples sink. """ import os import tempfile import pytest try: import duckdb DUCKDB_AVAILABLE = True except ImportError: DUCKDB_AVAILABLE = False from kgx.tr...
6886cc5dcaa0524568583b95056b5cf3cf9f2fc3b5e17698a95790ff48d50cf2
Python
5,736
155
import pandas as pd import os import numpy as np import matplotlib.pyplot as plt from CCF_translator.deformation.interpolation.NearestNDInterpolator import ( NearestNDInterpolator, ) import nibabel as nib def interpolate_volume(volume, mask): # Get the shape of the volume shape = volume.shape # Create...
ebb744fce802fe08b9da365d1d76495e8cd5a625d00e793e3b1aa28d94b182e3
Python
5,736
177
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-strict from typing import Optional import torch import torch.nn as nn class SqueezeExcitation(nn.Module): """ Generic 2d/3d extension of Squeeze-and-Excitation (SE) block described in: *Hu et al., Squeeze-and-Excitation ...
2e21bde5c68ac74b73e3746c44deef51555d4ca8c9a1f9a480d3cf830b8cc253
Python
5,739
119
"""Read and write NWB files against the schema they were written with. hdmf keeps one type map per process. Importing an NWB extension registers the installed version of that extension there, and from then on a file whose cached namespace holds a *different* version is built against the installed spec rather than its ...
2454809b0215c6bbb6ea80a7c1a7cec96ba791a760d4659e9238ecfbc1eff39b
Python
5,741
59
## # CPCantalapiedra 2021 test_hmm = """ HMMER3/f [3.1b2 | February 2015] NAME COG0012.faa.final_tree.fa LENG 10 ALPH amino RF no MM no CONS yes CS no MAP yes DATE Fri Aug 3 19:28:36 2018 NSEQ 4522 EFFN 4.170202 CKSUM 2788465937 STATS LOCAL MSV -12.2126 0.69661 STATS LOCAL VITERBI -13.1336 0...
45c8e75779d70fba1d9383e9b272869b3ec14c2ddb592ed3b6b1579e4c8c197c
Python
5,741
177
# --- Imports --- import os import torch import umap import numpy as np import tqdm import matplotlib.pyplot as plt import Adversarial_Observation as AO from Adversarial_Observation.Swarm import ParticleSwarm # --- Global Config --- optimize = 3 # Target class for the attack # --- Main Function --- def main(): ...
f39e79ec03b4621f05f97cf6267a4bfc70b766f857864b40116587c10befd228
Python
5,741
172
# src/zndraw_joblib/models.py from datetime import UTC, datetime, timedelta from enum import StrEnum from typing import Any, Optional from uuid import UUID, uuid4 from sqlalchemy import ( Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint, func, ) from sqlalchemy.orm i...
3880cc84f251cf171417a66d76070f51221dde370a4f6c2a1cd57c819b1847c7
Python
5,742
158
# I tested with torch==2.4.0 (2.6.0 gives troubles, but we an deal with those if we want to go with that version) # note there is a folder I am pulling from for imports aa couple of lines down, then also NNUnet V1 needs to be # installed in the environment import os import subprocess import shutil import argparse from...
4ed92925a7aa21cb6dd168d208463105b6244f642d485efcb10b4cf9d0d6ec80
Python
5,743
180
"""Integration tests for /v1/groups endpoints.""" import pytest from helpers import _register_and_login, auth_header, create_test_user_in_db from httpx import AsyncClient from sqlmodel.ext.asyncio.session import AsyncSession @pytest.mark.asyncio async def test_create_group_creator_is_admin(client: AsyncClient) -> No...
286891577fcdb78f24541b0ad3b8066ac06bd61b739e041d3efe65ebc862e872
Python
5,747
144
"""Unit tests for resolving a session folder's acquisition format for NWB export. NWB export reads a session's traces through one format's interfaces, so it has to collapse the set of formats GuPPy detects in a folder into a single choice -- and refuse the folders where it cannot. """ import pytest from guppy.utils....
0ee80a8f573866c59ab2f3c5008776bc72b24c117fc5fcb6ba7e837dc42db471
Python
5,748
158
import SimpleITK as sitk import numpy as np import matplotlib.pyplot as plt import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import nibabel as nib import os from utils import get_mean_value, get_R_value, get_S_value, z_score_normalisation, optimale_scale_identification, hessian, get_Ht f...
ac83608ad3c21629ed4a5be0a9b31be4bd9341dcab247bdb422d5482999f1760
Python
5,748
115
import numpy as np import pandas as pd import os def load_target(gene: str, df_Sp: pd.DataFrame, df_Un: pd.DataFrame, n_replicates: int) -> tuple: assert type(n_replicates) == int, "n_replicates must be an integer." Sp_star = df_Sp.loc[gene].to_numpy(dtype=np.float64).reshape(n_replicates, -1).T Un_star = ...