sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
76acbd1a9c1d1e149ffde375a061cac06134e033c6601c47c45760130a7a10b7
Python
2,553
69
from pathlib import Path import pandas as pd from data_profiling import ProfileReport from data_profiling.utils.cache import cache_zipped_file """ The "Auto" correlation is an interpretable pairwise column metric of the following mapping: - Variable_type-Variable_type : Method, **Range** - Categorical-Categorical ...
e3d146d5298f227f29316ba47d3851f6907288d7e73fdd031ac78465f446f8f3
Python
2,553
78
import abc import numpy as np class ModelDataset(object): """ Private Class. Users need to wrap their datasets as one of its subclasses. """ def __init__(self, dataset=None, x=None, y=None, size=0): """ A ModelDataset is a wrapper over the model's train/test/validation dataset input ...
5593fd32d5413a0468e4e765529ac9844a0c9212422119d44a1ccbe84d5f462b
Python
2,554
81
# %% This will do perturbation of the target data. # solve for 6 configurations for G + image response and H + non-image response. # the penalty value is fixed to 10. import numpy as np # from SSN_model_funcs import * # tentatively... import SSN_model_funcs as ssn import create_new_target_data as cnd import sys impo...
9140a309beef4efbe01f6b4de278900a557ee0fe832fbd242ef06f5ec7eeefe8
Python
2,554
86
_base_ = [ '../../_base_/datasets/rtts_coco.py', '../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py' ] # model settings model = dict( type='ATSS', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.37...
0e3a9e0e7793dac7001421c3fbfc94330aa0291599ae2e78645e93f36baef8c6
Python
2,556
86
_base_ = [ '../_base_/datasets/ruod_coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='ATSS', data_preprocessor=dict( type='DetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.3...
7c3a496cc05022daeb18b37c6a7aaade5050559a4e66e96d1b2c150b1b55f240
Python
2,556
71
from lisa.core.data_interface import DataInterface import argparse import os import numpy as np import pandas as pd from scipy import sparse TECHNOLOGY = 'Motifs' def main(species, window_size, motif_metadata, bin_sorted_hits, group_loci = 100000): motif_metadata = pd.read_csv(motif_metadata, sep = '\t', header...
8e923b3420e785a77d6cc22771830ab0dd1b76c10bc9d1beb21e1a65aafe5cee
Python
2,556
79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python version: 3.10.9 pandas version: 1.5.0 numpy version: 1.23.3 """ #%% Import Modules import pandas as pd import numpy as np #%% Functions def dice_coeff(df, thresh=None): if thresh != None: ses1 = df[(df["ses"]=="ses-01") & ((df["pval"] < thresh))].r...
8e8e6d21bfaee9e06c9d47d4315526a30225f73728ed708c826fd490de800d5e
Python
2,557
95
import pdb from matplotlib import pyplot as plt import yaml from yaml.loader import SafeLoader import torch import ray from latent_time_stepping.AE_models.VAE_encoder import VAEEncoder from latent_time_stepping.AE_models.autoencoder import Autoencoder from latent_time_stepping.AE_models.encoder_decoder import ( D...
0f3aa692d441e41843034b71b9e8845e6d582f8c1a8d772b64eb4f4b0cceebaf
Python
2,558
63
from utils import * from sklearn.metrics.pairwise import cosine_similarity def plot_rcpfld(nrow, ncol, iters, conn, Ix, Iy, title, prjid): fig, axs = plt.subplots(nrow, ncol, figsize=(ncol/2, nrow/2)) plt.subplots_adjust(left=0.19, right=0.99, bottom=0.1, top=0.9, wspace=0., hspace=0.) for row in rang...
33a2515721fbda75572adabdcb7c319e0e87dfdbb0ca449a5570cea4302c967c
Python
2,558
80
import pytest from sinabs.backend.dynapcnn.chip_factory import ChipFactory devices = ChipFactory.supported_devices def generate_event_list(chip_factory): Spike = chip_factory.get_config_builder().get_samna_module().event.Spike # Note that timestamps are in us, chip factory dt in s return [ Spik...
7a5f0f1fd5232a563448e8e39f2a828f7781d61402de49067d7303b51da6deb7
Python
2,558
89
import pandas as pd from seaborn import violinplot import matplotlib.pyplot as plt from python.utils import load_vitals_from_parquet, custom_logger from config import TARGETS, TARGET_LABELS, EXTREME_VALUE_LIMITS DATASETS = ['train', 'validate', 'test', 'eicu'] DATASET_NAMES = {'train': 'Training set', ...
94498acfc908716132fdadcb5737e9f7e81e1ee1e266ecc5ce3e05ab45cd80cb
Python
2,558
98
# OmicVerse Analytics Configuration """ OmicVerse 统计追踪配置 这个模块提供了对报告使用情况的统计追踪功能。 所有数据都是匿名的,不会收集个人隐私信息。 收集的信息包括: - 报告生成时间 - 匿名用户ID(基于机器信息的hash) - 操作系统信息 - 浏览器类型(仅在打开报告时) - 地理位置(仅国家/地区级别) """ # 默认配置 DEFAULT_CONFIG = { # 是否启用统计 'enable_analytics': True, # 统计服务器地址 'analytics_endpoint': 'https://analy...
ee0f31c158750cf10d97741d147594235f1558e6557a001183de0b93b60e37d1
Python
2,558
81
import os import subprocess bazel_workspace_dir = os.environ.get("BUILD_WORKSPACE_DIRECTORY", "") MASTER_BRANCH_VERSION = "3.0.0.dev0" MASTER_BRANCH_JAVA_VERSION = "2.0.0-SNAPSHOT" def list_java_files(root_dir: str): """ Scan the directories and return the sorted list of pom.xml and pom_template.xml...
1396e9741a473e1080b44195668bdc985ada506627cffb863831c65a7d2712ad
Python
2,560
78
from typing import Dict from torch import load, manual_seed, device from torch.cuda import is_available import numpy as np from common import XAIScenarios, SEED from utils import load_json_file, dump_as_pickle, load_pickle from training.models import CNN from xai.methods import get_attributions, get_baselines import ...
3fcabd359ed59d806b78a084a570d958d1fb06c18476e554c5c4c87e2645ef39
Python
2,560
72
import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from lqit.registry import MODELS from .base_head import BaseEnhanceHead @MODELS.register_module() class EdgeHead(BaseEnhanceHead): """[conv+GN+relu]*4+1*1conv.""" def __init__(self, in_channels=256, ...
4e1da2a3604d0aa3c238f967db214458e64f9b3cf64b2889fda6d09256479307
Python
2,560
57
from pkg_resources import parse_version from configparser import ConfigParser import setuptools, shlex assert parse_version(setuptools.__version__)>=parse_version('36.2') # note: all settings are in settings.ini; edit there, not here config = ConfigParser(delimiters=['=']) config.read('settings.ini') cfg = config['DEF...
70021e36075f96fcdc58f8f064c59a36abc5e5fdb65033c2210339951bbeeb7c
Python
2,560
58
import torch.nn as nn from torch.autograd import Variable class RNNModel(nn.Module): """Container module with an encoder, a recurrent module, and a decoder.""" def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False): super(RNNModel, self).__init__() self.drop ...
cd3e2e63080215dcd1a6f14f6362fde27d29bbf7addbdd674d3ee9d571070508
Python
2,561
64
import pathlib path = pathlib.Path.cwd() if path.stem == 'tmb_survival': cwd = path else: cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')] import sys sys.path.append(str(cwd)) import numpy as np from lifelines import CoxPHFitter from lifelines.utils import concordance_index import pandas as pd i...
966bd5b0d20185bcb765209c22cb4f66a3ac32775ee8bdb87eb4f0a360e5b743
Python
2,562
83
"""Simplified PDB API client using direct REST endpoints.""" import logging from typing import Any, Dict, List, Optional from .base import BaseAPIClient from ..config import settings logger = logging.getLogger(__name__) class SimplePDBClient(BaseAPIClient): """Simplified client for RCSB PDB REST API.""" ...
d4735df76cb37156c203d5d2bed0666fb2e13bcef6c5df64b77c6262de9dfa83
Python
2,563
100
#!/bin/python #------------------- Description & Notes --------------------# #------------------- Dependencies ---------------------------# # Standard library imports from pathlib import Path # External imports import pytest # Internal imports from Synsor import make_parser from Synsor import is_valid_parser from ...
8b2adb351283e1601f4e4e7515b199fd4fa8d6da8ec01c05490e2ad428f428eb
Python
2,564
65
# Adapted from [aiodebug](https://gitlab.com/quantlane/libs/aiodebug) # Copyright 2016-2022 Quantlane s.r.o. # 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.apac...
9e3a316373ea42f450108b0fd9b8be939d5d5c9699aa04df85feff454d9b320f
Python
2,564
65
from typing import Dict, Optional, Union import ray def _get_node_id_from_node_ip(node_ip: str) -> Optional[str]: """Returns the node ID for the first alive node with the input IP.""" for node in ray.nodes(): if node["Alive"] and node["NodeManagerAddress"] == node_ip: return node["NodeID"...
3c39eac11a8de60881c8c15ebc84bb2e5d3408bd53449b4e70f2b8773a1bec4d
Python
2,565
76
from __future__ import annotations import re from .models import MessageEnvelope, PolicyDecision, RuntimeTaskState class MessagePolicy: """Decide whether an incoming message starts work or joins the queue.""" def decide(self, envelope: MessageEnvelope, state: RuntimeTaskState) -> PolicyDecision: if...
52bcfb1ec12fd6cf4281403ce693b460afb4a7eeb6ce56d01e12eb916c6e6304
Python
2,565
84
import logging from pathlib import Path from pokeformer.preproc.freesasa import calc_sasa from pokeformer.utils.pdb_utils import (calc_id, calc_id_model, get_nei_atoms_by_pdbfile, get_nei_atoms_by_pdbid, get_pdb_path) logger = logging.get...
8f5c822c7a56c6de83e4c594fc40795ac25ddbe1ba67953c83006e74ace817b8
Python
2,565
71
"""Backend Protocol + return container for metacell algorithms.""" from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Optional, Protocol, runtime_checkable import numpy as np from scipy import sparse class UnsupportedCapability(NotImplementedError): """Raised wh...
17434833e9007471d4a6538254e5dbdc95aff825b0fe66065f2fdd2e5f1c7e0e
Python
2,567
56
import pandas as pd import os, logging import ast from misc.save_files import read_pickle, write_pickle, read_pandas_from_csv, write_pandas_to_csv from misc.counter import count_dict def dict_of_abbreviations(df: pd.DataFrame, config: dict): """ Go through each publication and check for abbreviations (longer...
7133b275013dec92f1a718378939358be7d594099be3a2ac68ca1de5798ca1aa
Python
2,567
64
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import os import random import shutil import sys import zipfile from datetime import datetime import ase.io def main(): """ Rattl...
a7d18a030100ff56cbc9b248f6f416ed19a02962170f8cd2c2a4e3791d80971c
Python
2,570
86
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Low level implementation of torch-based tile.""" from typing import Union, Tuple from numpy import ndarray from torch import Tensor, tensor from torch impor...
46ce67754a4f52a81441a18348500692d6f5d5c8293acd8e61b698e3fa9c231c
Python
2,571
99
# -*- coding: utf-8 -*- """ Created on Fri Dec 18 11:17:00 2020 @author: ju-bar Root finding functions This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ # import numpy as np # def root_poly_2(y, a, b, c): """ Retur...
23bbdf59fcbdfacce0f38980838ef54e5603a8a454bb2a3f43b7b2f06d847c82
Python
2,573
69
# built-in dependencies from typing import Union, List, Any, cast from abc import ABC, abstractmethod # 3rd party dependencies import numpy as np from numpy.typing import NDArray # keras is not imported here on purpose, a model of another backend would not need it # Notice that all facial attribute analysis models m...
db5d5e789d5f3261c19b92cbcabc7cb7f760c56d564449bd29b82afecdbaacde
Python
2,574
86
import torch.nn as nn import torch import numpy as np import random import os import logging def set_seed(rndseed, cuda: bool = True, extreme_mode: bool = False): os.environ["PYTHONHASHSEED"] = str(rndseed) random.seed(rndseed) np.random.seed(rndseed) torch.manual_seed(rndseed) if cuda: tor...
46ddc6bc050432b803048bf3f4482952d1e0f42e57258dde36396efa4a330b1d
Python
2,575
80
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
6706c76c217be5927aff1527b80e96c551872a3d901fb04940ef386d42ad4a5e
Python
2,575
56
import grpc import time import projectmetis.python.utils.proto_messages_factory as proto_factory from projectmetis.python.logging.metis_logger import MetisLogger from projectmetis.python.utils.grpc_services import GRPCServerClient from projectmetis.proto import learner_pb2_grpc class GRPCLearnerClient(GRPCServerCli...
89e2ce555305a6082d48389514c0e549812626f84045e9f0e6f35dba5701b922
Python
2,575
86
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import math import torch import torch.nn as nn @torch.jit.script def gaussian(x: torch.Tensor, mean,...
09296d3645a70cc85bd0b7e482cb27c943b13d9f8e1c090d3517b6415e4cb69a
Python
2,576
71
import xarray as xr import numpy as np import pandas as pd class JointPost: def __init__(self, Z, theta, theta_cv = None, constant = None): self.Z = Z self.theta = theta self.theta_cv = theta_cv self.constant = constant def new(bulk_id, gene_id, cell_type, gibbs_list): ...
5dcf736873bb4c19ea1ab8b3a02037871cc5d7ee05589da0b9c80532f1bfb026
Python
2,576
67
import kaggle import pandas as pd from data_profiling import ProfileReport from data_profiling.utils.paths import get_data_path # The dataset in this example is obtained using the `kaggle` api. # If you haven't done so already, you should set up the api credentials: # https://github.com/Kaggle/kaggle-api#api-...
b440d9e02a45fe4513d6c00232a4ec1fee25b5bca430300fe8cd8f03e74fdbd4
Python
2,576
80
import numpy as np import pandas as pd import pytest from data_profiling.config import Settings from data_profiling.model.summary_algorithms import ( describe_counts, describe_generic, describe_supported, histogram_compute, ) def test_count_summary_sorted(config): s = pd.Series([1] ...
c810448ba9954de2dce285585fedfe1009f44b5faeee77adf821377db64323a6
Python
2,576
75
import random import numpy as np import pytest from pfrl.collections import prioritized @pytest.mark.parametrize("uniform_ratio", [0, 0.7, 1]) def test_prioritized_buffer_convergence(uniform_ratio): expected_corr_range = {0: (0.9, 1), 0.7: (0.5, 0.85), 1: (-0.3, 0.3)}[uniform_ratio] size = 100 buf = pr...
1d5a64b6e39fc6ec569b540cae5b062e24ecb3569a006c659d85a825b5cd2ca9
Python
2,578
90
import os import setuptools import sys class NumpyImport: def __repr__(self): import numpy as np return np.get_include() __fspath__ = __repr__ def read(fname): with open(os.path.join(os.path.dirname(__file__), fname), 'rt') as f: return f.read() def requirements(): with open(os.path.join(os.p...
350dea244e27ced591716b326aafad288f5ab08be6cf243f9f327baf096547ba
Python
2,579
94
import pytest import torch from torch import nn from sinabs import layers as sl from sinabs.backend.dynapcnn import DynapcnnNetwork from sinabs.backend.dynapcnn.chip_factory import ChipFactory from sinabs.backend.dynapcnn.exceptions import ( InvalidGraphStructure, UnsupportedLayerType, ) from sinabs.from_torch...
cadee6aacbcc7149d2e6d2802c060aa774577ef8a691dc7fa6a651602c378f51
Python
2,579
100
"""Make figures to explain jittering""" import matplotlib.pyplot as plt import numpy as np from scipy.stats import gamma plt.style.use('dark_background') # Create figure and axis fig, ax = plt.subplots(1, 1, figsize=(7.5, 5)) # Define response function and x values x = np.arange(0, 30, 0.1) response = gamma.pdf(x, ...
85784835fa157af4b2d89637b237448b43b54e908d3fbddf09fd38b5efe28e70
Python
2,580
77
import os import numpy as np import nibabel as nib import time import pandas as pd output_root = '/path/to/results' sub = 'sub-01' im_file = os.path.join(output_root,sub,'{}_run-1_IVIM-avg.nii.gz'.format(sub)) bval_file = im_file.replace('nii.gz','bval') cval_file = im_file.replace('nii.gz','cval') mask_file = os.path...
df011486925f7e950ed241113452c4e77070b19e5dba2fac805896529e0eaa58
Python
2,580
82
"""Utils for LEF applications""" import logging from lefshift import constants def validate_column(input_df, column, data_type, error_message=None): """Validate that the input contains all information in valid types :param input_df: input dataframe :type input_df: pd.DataFrame :param column: name of...
2a73824072833a93e7356ca52694d5d1b23b821e0084e7e5c393fcde4c6c5294
Python
2,582
73
#!/usr/bin/env python3 """Utility scripts for community detection.""" import logging import numpy as np def compute_leiden_partition(graph, resolution=None, partition_type=None, use_weights=False, n_ite...
520300b2580f272ba28f4490e95bb7c13ec3adfb0817c23d2bd2095e10372c36
Python
2,582
67
import numpy as np import pandas as pd import patsy from scipy import stats from tqdm import tqdm def lr_tests(ds, alt_model, null_model='~ 1', gene_column='Gene', batch_size=2000, transformation=np.log1p, rcond=-1): ''' Compare alt_model and null_model by a likelihood ratio test for every gene in ds. Ar...
71daa449e8a00c5df671d052c5eedfacf97e1b85bdc51669910b7baa3916ffe4
Python
2,583
76
"""Fluorine chemical shift prediction""" import argparse import logging from lefshift.predict import add_predict_subparser, predict from lefshift.split import add_split_subparser, split from lefshift.train import add_train_subparser, train DESCRIPTION = """ LEFShift predicts fluorine chemical shifts using the local(L...
fb8eb2af340fb7a95d93761ab4ecd625232ec0c4fccd6f57988b9ac04827b517
Python
2,584
83
from functools import partial from itertools import combinations from random import choices as sample_with_replacement from random import sample as sample_without_replacement from typing import List, Sequence from rising.random.abstract import AbstractParameter __all__ = ["DiscreteParameter", "DiscreteCombinationsPar...
e1067078b9518a6e85179ee166eacbc11b25951eeb029a4ccbb4b0ed0228dff7
Python
2,586
58
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
58c5e087d4553a534b80131485fb9fbc265b751b67eb67fff4e4e1dcf75f16a3
Python
2,587
72
r""" This file contains various operations over Neo objects. Such as sum over lists of Neo objects etc. """ import quantities as qt from neo.core.analogsignal import AnalogSignal as NeoAnalogSignal import numpy def neo_sum(l): r""" This function gets a list of Neo objects and it adds them up. Importantly u...
998f0787b051bcce32a82cc688691fcc729bac5e905b0689613a46f059130c3b
Python
2,587
81
import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io.wavfile import torch import utils font = {"size": 10, "family": "Arial"} plt.rc("font", **font) def rms_normalise_audio(x): x = x - torch.mean(x) rms = torch.sqrt(torch.mean(torch.pow(x, 2))) return x / (10 * rms) def ...
a7cee2271e8e1ffb22c12f9b50b69da9679bd56ed580ba82b690dabd5e12765d
Python
2,587
79
from typing import Any, Type, Optional, Set, Dict def _name(type_: Type) -> str: return type_.__name__ if hasattr(type_, "__name__") else str(type_) class DaciteError(Exception): pass class DaciteFieldError(DaciteError): def __init__(self, field_path: Optional[str] = None): super().__init__() ...
ca94132602489a1bd91e986eb62bd8a62af705a7767c61e7200e8b28325b2786
Python
2,587
74
import torch import torch.nn.functional as F from tqdm import tqdm from dice_loss import * def miou(logits, targets, eps=1e-6): """ logits: (torch.float32) shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ outputs = torch.argmax(logits, dim=1, keepdim=True).typ...
ffcd1f0f022b1edd3801eae491865a109fcae7c6349bcc62d8a3e6561e27799b
Python
2,587
67
import json import re import subprocess import unittest from importlib import resources as impresources from shutil import rmtree from termcolor import cprint from epilepsy2bids.bids.chbmit.convert2bids import convert as convertChbmit from epilepsy2bids.bids.seizeit.convert2bids import convert as convertSeizeit from ...
f63ca0d6763546bbb3d7ec849254a6d4652d6c1a4063794b9c690be86f0a124c
Python
2,588
109
import pdb,sys,os import argparse import anndata import scanpy as sc import numpy as np from scipy import sparse def get_eg_representatives(name:str) -> None: """ Used for acquiring representatives' single-cell data in the example. Automatically check the latest representatives and store their single-cell da...
0c385150f50101a891150c228fbf349b206a20d741fd9648936c689dc581562d
Python
2,591
81
import logging import os from typing import List, Optional, Tuple from ray._private.accelerators.accelerator import AcceleratorManager from ray._private.ray_constants import env_bool logger = logging.getLogger(__name__) RBLN_RT_VISIBLE_DEVICES_ENV_VAR = "RBLN_DEVICES" NOSET_RBLN_RT_VISIBLE_DEVICES_ENV_VAR = "RAY_EXP...
bc1ee5f0d4c6e61bdab8850b04af0dbf87f897fa397d0675e3763b3da707662c
Python
2,594
91
import os import sys from os.path import * import re from glob import glob def parse_flagstats( flagstatfile ): ''' 535812 + 0 in total (QC-passed reads + QC-failed reads) 0 + 0 duplicates 521761 + 0 mapped (97.38%:-nan%) 535812 + 0 paired in sequencing 267930 + 0 read1 267882 + 0 read2 ...
29b41babd992db6d11cf62511958d0231f29b2dc7c4ffb3e8ac6c7db7edf3ee9
Python
2,595
96
# -*- coding: utf-8 -*- """Test most of the contents of the vtkplotlib.plots module.""" import numpy as np import vtkplotlib as vpl import pytest from tests._common import numpy_stl pytestmark = pytest.mark.order(8) def test_arrow(): points = np.random.uniform(-10, 10, (2, 3)) vpl.scatter(points) vpl....
2b592e55ae7373eed349ba9b98d0561368d0c0bb3ad0c59ad8865eeb8efa922c
Python
2,596
108
# flake8: noqa # __start_my_first_deployment__ from ray import serve from ray.serve.handle import DeploymentHandle @serve.deployment class MyFirstDeployment: # Take the message to return as an argument to the constructor. def __init__(self, msg): self.msg = msg def __call__(self): return...
ac35e659346c32d2094a1ff37ea9927c12ab28c835af40282806f101e9a46f6d
Python
2,596
81
# stdlib dependencies from typing import Any, List, Union # 3rd party dependencies import numpy as np from numpy.typing import NDArray import cv2 # project dependencies from deepface.models.demography.DemographyUtils import EMOTION_LABELS from deepface.models.demography.onnx.OnnxDemography import OnnxDemography from ...
11397e979ff5f7c416c91a96065b36f00f8593d79c612fae067a2920c108a113
Python
2,597
73
from typing import Dict, Optional, Union import numpy as np import tensorflow as tf from ray.air.util.data_batch_conversion import _unwrap_ndarray_object_type_if_needed def convert_ndarray_to_tf_tensor( ndarray: np.ndarray, dtype: Optional[tf.dtypes.DType] = None, type_spec: Optional[tf.TypeSpec] = None...
84218c4f4eca722961a83a68195aba9cdb4ca62486083719dff57bffec777ba1
Python
2,598
100
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Wrapper for breakpoints stored in VCF records """ import numpy as np import svtk.utils as svu class Breakpoint: def __init__(self, chrA, posA, chrB, posB, name, samples, strands): """ Attributes ---------- chrA : str pos...
3d77e7f5c5a9b7676de0cda1e48b354923f8b793336b1eb76937982de94ad809
Python
2,600
63
import os import numpy as np import pandas as pd import nibabel as nib import ivim tissues = {'WM':3,'CGM':2,'DGM':4} titles = {'WM':'White matter','CGM':'Cortical gray matter','DGM':'Deep gray matter'} output_root = '/path/to/results' subs = [sub for sub in os.listdir(output_root) if sub.startswith('sub')] pars = ['...
52d48edd9e1694106918655df6b176f4cab583c6532d415efb2229031b42c1d6
Python
2,602
69
import os import pandas as pd import subprocess from multiprocessing import Pool, Manager metadata_file = "../01_metadata_prep/TSMR_metadata_for_analysis.tsv" df_metadata = pd.read_csv(metadata_file, sep="\t", index_col=False) ukb_gwas_dir = "./GWASsumstat/UKB" savedir = "./reformat_outcome_gwas/" def read_variant...
590b85e210991a191d7c9531fc8b946a504c38596adff7f86358e8a5780acafa
Python
2,604
58
""" Container class definition """ from data_profiling.report.presentation.core.container import Container from data_profiling.report.presentation.flavours.html import templates class HTMLContainer(Container): def render(self) -> str: if self.sequence_type in ["list", "accordion"]: return ...
bcaee07186e99c239f166b0ac2982d2326cbdfcdc7e0a9cc799038bd431333a5
Python
2,604
97
import os import sys import time import errno import time import timeit import warnings import numpy as np import numba from numba import jit warnings.simplefilter("ignore") @jit(nopython=False) def VEP2Dmodel(params, constants, init_conditions, SC, dt, ts): nt=ts.shape[0] nn=SC.shape[0] #parame...
cfa93918f1a12d2dc497345641138d6d629d54c65bf1dddadb6c315527053ea2
Python
2,604
73
import numpy as np factorDict ={ "A":[-0.59,-1.30,-0.73,1.57,-0.15], "C":[-1.34,0.47,-0.86,-1.02,-0.26], "D":[1.05,0.30,-3.66,-0.26,-3.24], "E":[1.36,-1.45,1.48,0.11,-0.84], "F":[-1.01,-0.59,1.89,-0.40,0.41], "G":[-0.38,1.65,1.33,1.05,2.06], "H":[0.34,-0.42,-1.67,-1.47,-0.08], "I":[-1.24,-0.55,2.13,0.39,0.82], "K":[1....
2e0469f078eb5cbd9b9372d397000054065a29cf7a9c60621bb35930af07a699
Python
2,606
67
"""Apply registration.""" import os import subprocess import numpy as np import nibabel as nb import glob # ============================================================================= DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' # Set subs to work on SUBS = ['sub-07'] DIRECTIONS = ['PA'...
f9f5d9af3264bbe448d8016b9a22fc430f1aeb6c261f6b1af8e0d29d2bca3d11
Python
2,607
55
import os import numpy as np import matplotlib.pyplot as plt import ivim # protocol files examcard_files = {enc:os.path.join('protocol','IVIM_EPI_{}_1.txt'.format(enc)) for enc in ['FC','NC']} gfile1 = os.path.join('protocol','FWF_CUSTOM005.txt') gfile2 = os.path.join('protocol','FWF_CUSTOM006.txt') gfiles = {'FC': [g...
0911b358afae2c0e3b71a9685faa5124bd26d0ee1dbcfe26ab345236e1dcea08
Python
2,609
80
# !/usr/bin/env python # coding: utf-8 # @Time : 2022/10/28 20:45 # @Author : Z.-H. G. # @Email_0 : guozhenhao17@mails.ucas.ac.cn # @Email_1 : guozhenhao@tongji.edu.cn # @File : integration_metircs.py # @IDE : PyCharm import scanpy as sc import pandas as pd import os # NOTE: ``scib`` and ``scanpy.external``...
b0539c0eb5c8a29a83a947e8e279b16cda0d5d308cd52f7e29ae52d55c0e4076
Python
2,609
68
import numpy as np import torch import faiss import faiss.contrib.torch_utils # allows utilizing torch tensors as input to faiss indexes and functions def inverse_distance_kernel(sq_distances, delta = 1e-3): """ Kernel used in Pritzel et. al, 2017 """ # https://discuss.pytorch.org/t/runtimeerror-functi...
de92e56c835f59b8b45719da0723df573174cea3c895254411344ef404d12240
Python
2,609
85
from typing import Optional, Sequence, Union import torch from rising.utils import check_scalar __all__ = ["mirror", "rot90", "resize_native"] def mirror(data: torch.Tensor, dims: Union[int, Sequence[int]]) -> torch.Tensor: """ Mirror data at dims Args: data: input data dims: dimension...
834a4c0ae8f05acc04c823a4a7e89c0312ce1de44e482ca34746f9cd049a9701
Python
2,610
56
import numpy as np import numpy.random as random from numpy import genfromtxt from scipy import stats from scipy import spatial from scipy.spatial import distance from scipy.spatial import KDTree from scipy.spatial.distance import cdist from scipy.stats import percentileofscore def comparedistances(csv1,csv2,sumofdis...
c60533c503da0306c4dff4b746bf9409faa5c119447c87c95c51bbc76a3ed443
Python
2,610
97
#* # @file Different utility functions # Copyright (c) Zhewei Yao, Amir Gholami # All rights reserved. # This file is part of PyHessian library. # # PyHessian 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, ei...
7055166b5b912ba84589c241495fc24be8e41a9a1075c9eb013d28aebdaaf810
Python
2,611
82
# Copyright 2023 BioMap (Beijing) Intelligence Technology Limited import torch import torch.nn as nn from .performer import Gene2VecPositionalEmbedding, RandomPositionalEmbedding from torch.nn import functional as F class pytorchTransformerLM_mse(nn.Module): def __init__(self, num_tokens, ...
1b6176e374079668fbd1ef64cc5afd350f98ed9786bda1a1c9bc5a0102a479e3
Python
2,612
90
""" Test for issue 1722: https://github.com/Data-Centric-AI-Community/data-profiling/issues/1722 """ from datetime import date, datetime from pyspark.sql import SparkSession from pyspark.sql import types as T from data_profiling import ProfileReport def make_non_numeric_df(spark: SparkSession): # Intentionally...
e1474b100c12c0cc6dd87f1853504a752909df3eede49c815863cc5ee8fd8d48
Python
2,612
74
import os from typing import Optional from functools import cached_property from pyarrow.parquet import ParquetDataset import pandas as pd from torch.utils.data import Dataset from python.data.data_utils import build_x_y_single_case from python.utils import custom_logger from config import TARGETS, FORECAST_HORIZON ...
c482ece419a34b360e25ae9e7f4d8461aca24e43536e711456dfd3302f24004e
Python
2,613
93
# stdlib dependencies from typing import Any, List, Union # 3rd party dependencies import torch from numpy.typing import NDArray # project dependencies from deepface.commons import weight_utils from deepface.models.demography.DemographyUtils import GENDER_LABELS from deepface.models.demography.pytorch.TorchDemography...
5e70a9dda32b065ba3f39e2b6765fa3e491130cce2443eb8ba4c6b489ba037f0
Python
2,614
101
import torch import collections import pdb import torch.utils.data import csv import json from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import math from pdb import set_trace as stop import numpy as np def loadData(filename,windows): with open(filename) as fi: csv_reade...
7e0ab0ce0a044e4632bb5aef2b547928e65568277b971da34abd99f9a8729519
Python
2,614
83
#!/usr/bin/env python3 # Converts single sample SV/CNV vcf.gz (e.g., DRAGEN) to .del.bed and .dup.bed files import argparse from pysam import VariantFile DEFAULT_QUAL_CUTOFF = 30 # Writes record in bed format def write_bed_entry(file, record, score, sv_type, sample): bed_entries = ( record.chrom, ...
e97e75e5682a7f9a5b6f9cc259569e240e7e8c3dda8a216ad6a2fe5c2716f5b2
Python
2,614
83
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
262962f79d044a83b55ae93820e7f9fd630a6c129988c27ec5dcc0485265ef0f
Python
2,615
61
import scanpy as sc import pandas as pd import flowsig as fs adata = sc.read('data/burkhardt21_merged.h5ad') condition_key = 'Condition' # We construct 10 gene expression modules using the raw cell count. fs.pp.construct_gems_using_pyliger(adata, n_gems = 10, ...
709ea79ca4caf11c4759efaaac49e06be0ac960b2881c3294898a27eeaa9ed89
Python
2,618
59
""" calculate AUC (above threshold) for a given stimulus for all ROIs. Also generate a distribution of events for each stimuli (AUC-time), and calculate kurtosis, skewness and the median from the distribution INPUT: smoothed data, stimulus.csv OUTPUT: a dataframe with 5 rows (header AUC, kurtosis, skewness and m...
d41c8bffa1d3070409153df476f1b600b5b3a81d5458f96879b2246f30fe80b7
Python
2,618
73
import torch from ..reducers import AvgNonZeroReducer from ..utils import loss_and_miner_utils as lmu from ..losses.base_metric_loss_function import BaseMetricLossFunction class TripletMarginMMDLoss(BaseMetricLossFunction): """ Args: margin: The desired difference between the anchor-positive distance...
0937b8d5cb8d7576b874e92a9697a7899016acaa2c5a14aef96aa1a608afa733
Python
2,619
81
# 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 or agreed to in writing, software # distributed under th...
7c0ba67ed5f57f1147d3615530d80f96951870ac81fbced0250b97dac842a249
Python
2,619
68
# This work is licensed under Attribution-NonCommercial 4.0 International License. # noqa from typing import List from lqit.edit.models.base_models import BaseGenerator from lqit.edit.structures import BatchPixelData from lqit.registry import MODELS from lqit.utils import ConfigType, OptMultiConfig @MODELS.register...
af44040117a9f07990c3311a2487195c79ba4c1a4a072ff75df06a52758c6f23
Python
2,619
73
import nibabel as nib import numpy as np from lib.qc_surface import ( boundary_chords, compute_topology, face_geometry, self_intersecting_faces, ) from lib.surface import write_points_faces_to_gifti from lib.surface_quality import improve_quality from lib.utils import setup_logger log_file = snakemake....
c84c863a41e015630b09c721e23fdf16484046e605b2f37aab5b3318b9899137
Python
2,619
72
import pdb import torch import torch.nn as nn class Preprocessor(nn.Module): def __init__(self, num_states, num_pars): self.state_min = [1e12 for _ in range(num_states)] self.state_max = [-1e12 for _ in range(num_states)] self.pars_min = [1e12 for _ in range(num_pars)] self.pars_m...
e1057802b8c89b550a1c7fa8b2ef01992304ac4667df35df929de62a8d577192
Python
2,619
82
import scipy.io as sio from torch.utils.data import TensorDataset, DataLoader import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt import math import time import torch from torch import nn from torch.autogra...
197682ad6ae2ffcec0452eaae813e66c84b43b065364ac7b905710cf1e8e1027
Python
2,620
105
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint plt.rc('font',size=15) dt = 0.01 # Protein data realdata = np.load('datafordistribution.npy') protein = realdata[0:7500] protein_size = len(protein) protein_fft = np.fft.rfft(protein) / protein_size plt.subplot(2, 1,...
f718b72e1e186e8060ae14be6117f979d5e0d1dab3d83474403f7bf7773c9ecf
Python
2,620
69
r"""``ov.tl.bonsai`` — public entry point for the Bonsai tree reconstruction. The work lives in :mod:`omicverse.external.bonsai`; this module only registers the function and records the citation, mirroring how ``ov.single.samap_integrate`` fronts the vendored SAMap. """ from __future__ import annotations from typing ...
0ce4c9ef4fb2cfb8abe65304a29e5c4801a6929d41764dc09f9df23bbc9aa7cd
Python
2,621
82
"""Generate stimulation protocol.""" import numpy as np import pandas as pd import time # Output folder FOLDER = '/Users/sebastiandresbach/github/neurovascularCouplingVASO/code/stimulation' # Pair TR (repetition time) TR = 3.141 # Number of jitters NR_JITTERS = 4 # Stimulus durations (in seconds) STIM_DURS = [1, 2,...
8238b436eb83d6ce48b4276feb5edd19aed97490f7917db9440ffbac40ce8a3e
Python
2,621
67
import os import numpy as np import torch from torch.utils.data import Dataset class ProcessedLigandPocketDataset(Dataset): def __init__(self, npz_path, center=True): with np.load(npz_path, allow_pickle=True) as f: data = {key: val for key, val in f.items()} # split data based on mas...
b331841390ce0d41b06c1f8b854508fd0b084beb93e43b87fa95d54f2c7a96e0
Python
2,622
70
import requests from ray import serve # __doc_import_begin__ from ray.serve.gradio_integrations import GradioServer import gradio as gr from transformers import AutoModelForSeq2SeqLM, AutoTokenizer # __doc_import_end__ # __doc_gradio_app_begin__ example_input = ( "HOUSTON -- Men have landed and walked on the ...
2f98c3ac99a219869673fa2d740c844f09d4ebfde0fcd29cc44f6c6967897cd4
Python
2,623
75
from oddt.fingerprints import PLEC import sys import os import os.path as osp import pandas as pd import oddt import oddt.pandas as opd from tqdm import tqdm def generate_plec_pdbbind(raw_path, label_file, output_dir, dim=1024*16): directories = os.listdir(raw_path) energy = pd.read_csv(label_file, ...
5ec807380413ed348ee9ee2de704a012eaf534fbae9fee6d610160fdbd4f314f
Python
2,623
86
import numpy as np import json from spinnaker2 import snn, hardware import helper np.random.seed(46) timesteps = 14 # parameters of convolution layer in_width = 32 in_height = 32 in_channels = 1 out_channels = 4 filter_height = 3 filter_width = 3 stride_y = 1 stride_x = 1 test_images = np.random.randint(0, 2**8-1, ...
94bc5c678f2fa6797856ca8eddeac78ed1c4186609a31c4873878e8c239ac365
Python
2,623
86
""" This file serves as a documentation example and CI test for basic data parallel attention deployment. Structure: 1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing. 2. Docs example (between __dp_basic_example_start/end__): Embedded in Sphinx docs via literal...
cf05511dc505a6aff20b8f732dd7385150234ddd4c175bb92b16a0399e750343
Python
2,623
80
from typing import Optional, Union, Sequence import numpy as np import jax from jaxtyping import Key import equinox as eqx from .initializers import he_normal from .modules import Conv, Sequential from .activation import SinhShift, Exp, Scale, pair_cpl from .nqs_layers import ReshapeConv, ConvSymmetrize from ..symmetry...
34c7a1017d65d414aeb6930d74d6401b7e2f552134919c95632ab94166480a3d
Python
2,625
85
from torch import optim from lop.algos.gnt import GnT from lop.utils.AdamGnT import AdamGnT import torch.nn.functional as F class ContinualBackprop(object): """ The Continual Backprop algorithm, used in https://arxiv.org/abs/2108.06325v3 """ def __init__( self, net, ...
7b946b351102725912e0b12b2d579f6a6d1c048c27034e1d5856f50e457c70c5
Python
2,625
63
import Utility_working as Utility #custom-made utility file, contains lengthy functions from constant import * import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import sys import os #enter parameters try: template_name = sys.argv[1] print("using constants from termin...
cc36305ef6586afbae24da80162283c58ed4963954ea05f8685f5338dd2e2118
Python
2,625
89
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...