sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
09ec62da5b57b7a4d4052c8ba6680e426a11b7511d9ae237a29e558806b6c406
Python
3,851
123
from collections import defaultdict from stanza.server import CoreNLPClient from agent.data.sql.sql_mgmt import get_connection, select_fields_where, execute_read_query TABLE = "annotate_sentence" FIELDS = "id, sentence, metamap_extraction, big_subject, predicate, big_object, manually_identified_predicate" def get_s...
ea0f89043e6c3390ff6a8a0dd870f555c7d02a7ba94b6ee0a7aa1b069ef23a31
Python
3,852
92
# -*- coding: utf-8 -*- # @Time :2024/6/6 11:04 # @Author :MENGLong Li # @File :ReadTxtDataFromOdbFile.py # @Software:PyCharm import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d import os class ReadTxtDataFromOdbFile: def __init__(self, num_group, num_index, LengthX, ...
b2643902f6d3a10197f125bf7e3486061712968d86dd5f48cf0f7a5050340e34
Python
3,853
119
import matplotlib matplotlib.use("Agg") from mozaik.analysis.analysis import * from mozaik.storage.datastore import * from mozaik.storage.queries import param_filter_query import mozaik import logging import os import pytest class TestDatastore: ref_path = "tests/full_model/reference_data/LSV1M_tiny" @clas...
74d40fec7db88a73da1245523fe74d97d2d034603e3a9bc517a6db7820a20d66
Python
3,857
136
#!/usr/bin/env python """ Collect ped file metrics. Writes stats to stdout. Metrics: ped_file_count : Number of records ped_file_<family> : Number of families of each type """ import argparse import sys import pandas as pd import svtest.utils.IOUtils as iou KEY_PREFIX = "ped_file_" SINGLETON_STR = "singletons...
87d24b78c767adca08bdc6eea331678399c1eb8ed8d8445604fc340c48b3dd79
Python
3,857
124
import time from pathlib import Path import numpy as np import torch import torch.nn as nn from torchvision import datasets from sinabs.backend.dynapcnn import DynapcnnNetwork from sinabs.backend.dynapcnn.chip_factory import ChipFactory from sinabs.backend.dynapcnn.specksim import from_sequential from sinabs.from_tor...
9c1a51773c79c8c5e170ee1fe693a5b8236770105f280c74c49b9e9a2df56495
Python
3,857
134
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Merge variants that were linked by per-sample bedtools merge """ import argparse import sys from collections import deque import numpy as np from scipy import sparse from scipy.sparse import csgraph import pysam import svtk.utils as svu def slink(record_links, rec...
cecd9dfd97248689422299fe98ea07d8e234dc52836c45b58ad3a155bc1f22d9
Python
3,858
102
import torch from ..utils import common_functions as c_f from ..utils.module_with_records import ModuleWithRecords class BaseReducer(ModuleWithRecords): def forward(self, loss_dict, embeddings, labels): self.reset_stats() assert len(loss_dict) == 1 loss_name = list(loss_dict.keys())[0] ...
d9c9307391ea72fbef9b40eee050e5721b781afe206c6c9e96bf302b1ec01928
Python
3,859
120
#!/usr/bin/env python3 """Calculate statistics for deployments on categorical targets.""" from pathlib import Path import pandas as pd import scipy.stats as st from sklearn import metrics __author__ = "Marko van Treeck" __copyright__ = "Copyright 2022, Kather Lab" __license__ = "MIT" __version__ = "0.1.0" __maintain...
1cfa49c498dbf7ad511dd4d944f894ed306ad9e1e7bfd01c280e33933106c085
Python
3,863
103
import os import numpy as np import matplotlib.pyplot as plt import pyvips as Vips NP_DTYPE_TO_VIPS_FORMAT = { np.dtype('int8'): Vips.BandFormat.CHAR, np.dtype('uint8'): Vips.BandFormat.UCHAR, np.dtype('int16'): Vips.BandFormat.SHORT, np.dtype('uint16'): Vips.BandFormat.USHORT, ...
8a1032b7afb08815f35af2158a4e3ef7cfe85ab6f837601dd4b40a00c673accb
Python
3,863
113
from typing import Any, Iterable, Sequence import matplotlib.pyplot as plt import numpy as np import pandas as pd from numpy.typing import NDArray from siapy.entities.pixels import CoordinateInput, Pixels, validate_pixel_input __all__ = [ "map_affine_approx_2d", "affine_matx_2d", "align", "transform"...
63f14a853d6baf882c4f2d74d41e974c16ad7d71587a94cec9f62f07d9d21fe7
Python
3,864
94
import tensorflow as tf from models.deep_learning.deep_learning_models import DLRegressor from utils.constants import is_spline class BiLSTMRegressor(DLRegressor): """ This is a class implementing the BiLSTM model for time series regression. ! Remember to use regularization techniques such as dropout, wei...
1fee27d521c42223dffd20dbc5316109e99f0bb5be2d76f8266d33cc08510ffb
Python
3,865
133
import logging import warnings from datetime import date, datetime import numpy as np import pandas as pd from matplotlib import MatplotlibDeprecationWarning from pyspark.sql import SparkSession from data_profiling import ProfileReport from data_profiling.config import Settings logging.basicConfig(level=logging.INFO...
3e4f5c74009dcbcd67c4a9c19afa38e8f50486aa306565256301dc44a934e4ae
Python
3,867
53
#!/usr/local/bin/ipython -i from mozaik.experiments import * from mozaik.experiments.vision import * from mozaik.sheets.population_selector import RCRandomPercentage from parameters import ParameterSet import mozaik def create_experiments(model): return [ #Spontaneous A...
07b5bd20db61f4924d7e629f18fb7171160f1c70c2cae2b0dde845a3442f624a
Python
3,869
83
import numpy as np import visionloader as vl import argparse import pickle import lib.data_utils.matched_cells_struct as mcs from lib.data_utils.interaction_graph import InteractionGraph, VertexInfo import lib.data_utils.cell_curation as curate from lib.dataset_config_parser.dataset_config_parser import read_config_f...
38fb1935e2b3e4d68f76049209e1c51cfaf192fb51cc89ff6c42e5c035ce3e56
Python
3,869
102
import os import yaml import h5py import numpy import random import matplotlib from tqdm.auto import tqdm, trange from stedopt.configuration import Configurator from stedopt.articulation import PreferenceArticulator from stedopt.defaults import obj_dict, regressors_dict from stedopt.tools import create_dataset, crea...
0f0b9ded4d7344cb8702863fd922f2195617f21cec67a217ae4ea58a3b1d563e
Python
3,870
119
#!/bin/python #------------------- Description & Notes --------------------# #------------------- Dependencies ---------------------------# # Standard imports import argparse import itertools from pathlib import Path # Third-party imports from tensorflow.keras import layers from tensorflow.keras import metrics from...
d5b22e63378a9968a820a90227399b0a31b3735f8cae1793a3e762d8d9e21a82
Python
3,870
110
# -*- coding: utf-8 -*- import os import pandas as pd from nilearn.datasets.utils import _fetch_files, _get_dataset_dir def fetch_ibc_subjects_contrasts(subjects, data_dir=None, verbose=1): """Fetch all IBC contrast maps for each of subjects. After downloading all relevant images that are not already cached,...
c3184e224205ecebbce866cc174a48792956515ebcb5e097cc281c32182a3a3e
Python
3,871
131
"""Compute statistical description of datasets.""" from typing import Tuple import numpy as np from pyspark.sql import DataFrame from pyspark.sql.types import ( ArrayType, BooleanType, ByteType, CharType, DataType, DateType, DecimalType, DoubleType, FloatType, IntegerType, L...
099b021df370ea17862042b82f8f581e7ac1fcbdce4ebfb5f45a033c615e0728
Python
3,872
93
import os import pandas as pd import numpy as np import pcntoolkit as ptk from pcntoolkit.util.utils import create_design_matrix # globals root_dir = '/project_cephfs/3022017.02/projects/hansav/Run8_f/' data_dir = os.path.join(root_dir,'data/') mask_nii = ('/opt/fsl/6.0.3/data/standard/MNI152_T1_2mm_brain_mask.nii.gz...
a707787382584b3549568dc4002e018011c28278533281acee16a8b7fac625b5
Python
3,872
103
import numpy as np import re import stanfordnlp import nltk class Sequencer(): def __init__(self, text, max_words, tokenizer="re", lang="en", oov_token="<UNK>", min_word_lenght=1, lower=True): self.lang = lang self.lower = lower self.min_word_lenght = min_word_lenght self.tokenizer ...
40df5383933551998b0e1fbedbc075f93b4260c37482297d94f5b247a022b3f9
Python
3,873
122
#!/usr/bin/python # -------------------------------------------- # Load multiregion and write each as mtx files # - write raw chuks, merge after # Updated 09/08/2023 # -------------------------------------------- import re import gc import pandas as pd import numpy as np import scanpy as sc from tqdm import tqdm import...
58d5d4cfa9afbdfaff8e26c99291428da8a02fec14cafb4d7e91554f941850c9
Python
3,873
87
import numpy as np import tensorflow as tf class IgAttn: def __init__(self, input_array, mymodel, baseline_freq, myvalue_full, my_pre_input_full, current_i, label, m_steps=100, batch_size=64): self.input_array=input_array sel...
a802fc7e9f02f2e2a8eaacffe302c4ba7f823eceb3a2c938d88d9adc4a4d1c4d
Python
3,873
117
import numpy as np import warnings import os import argparse import pickle as pk from math import ceil from sklearn.metrics import r2_score from src.data.load_data import load_params, load_data, make_input_labels def predict_model(model, params, data_file, task_filter): """Use trained model to predict on data an...
0e7a85ec053e5e770fb788ca3628e0e6edf1c0e816a9e75ed2f862aecd36d690
Python
3,874
103
# from torchsummary import summary from thop import profile from model.swinir import swinir, swinir2dto3d, swinirup, swinirProj_stage2, UNetA, swinirhugecnn, torch import argparse from model.Unimodel import UniModel def Unimodel(): model = UniModel(args) # FLOPs: 1305.23647G, Params:174.83787M ...
250f2c1591579dca359b064b83500e2ef7ab8a8896b89eb23f9991313617f1c8
Python
3,874
94
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...
7eba4c3d3f0a42d3e5f4e18cdffe234c261eb6e341aa7ba1c45de499f3db0eb9
Python
3,874
84
import torch as th import numpy as np import scanpy as sc import scipy as scp from sklearn.model_selection import train_test_split from .utils import normalize, sparse_mx_to_torch_sparse_tensor from .dataloader_utils import handle_adata_view, ensure_csr_csc class ATACDataset(th.utils.data.Dataset): def __init__...
18e2c8def6e034b06917c0aea79b2aab4d2340148d9a31d1e8bb04499a147fd6
Python
3,875
100
from __future__ import annotations import logging import os import joblib import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from .. import settings from ._base_algorithm import BaseAlgorithm class Random_Forest(BaseAlgorithm): """ Class to compute Random forest clas...
214c21361edeb88839d8621dd04d4ffc352658c4ab2953e411c49dcca2a6a885
Python
3,875
97
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
2a40e0dd0b40499cf67f78ce4673f58bb0f2179f12bb62fba012d8f079d3eb69
Python
3,875
116
# -*- 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. #...
a9df0902de2909eacb0f759cb9c5c2d394c2e4d53165b5e834227a961c9e5e4b
Python
3,875
130
from ast import dump from email.policy import default import pandas as pd import yaml import os import sys # import pickle from simulator import SimulatedPhenotypes import logging import click from torch.utils.data import DataLoader, Dataset, Subset logging.basicConfig( format="[%(asctime)s] %(levelname)s:%(name...
c26273d5a16217c475da9565fae9af2f497b874e5e98d382be66db6b3dba0eb2
Python
3,875
96
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...
28154d34ccd83cfad17d9bef2da4d6959468a11488072a94e42c1da232a9a9f1
Python
3,876
106
from general_utilities.path_helper_function import list_subjects from pathlib import Path import os import scipy.io import mne import numpy as np import pandas as pd ses = "1" data_type = "eeg" task = "object_processing" category_dict = { 1: "human_body", 2: "human_face", 3: "animal_body", 4: "animal_...
60320b9395fca03a81169e64574178a58337393ad9b1f6df9443cb7dca32927a
Python
3,876
125
import copy import logging import os import queue import threading from typing import Optional import numpy as np from ray.air.constants import _ERROR_REPORT_TIMEOUT logger = logging.getLogger(__name__) def is_nan(value): return np.isnan(value) def is_nan_or_inf(value): return is_nan(value) or np.isinf(v...
893d0dcdcf0bc6510330e316b06ee801a8f21cc9fecf6ff69b41e6102b35abde
Python
3,876
123
# 3rd party dependencies import matplotlib.pyplot as plt # project dependencies from deepface import DeepFace from deepface.commons.logger import Logger logger = Logger() # some models (e.g. Dlib) and detectors (e.g. retinaface) do not have test cases # because they require to install huge packages # this module is ...
fda3d05fbb709fecc401c01cbba16c5c2a9f814106f16f1e7aa9c117513c673b
Python
3,876
134
import numpy as np from numba import njit @njit def isotonic_l2(y, sol): """Solves an isotonic regression problem using PAV. Formally, it solves argmin_{v_1 >= ... >= v_n} 0.5 ||v - y||^2. Args: y: input to isotonic regression, a 1d-array. sol: where to write the solution, an array of the sam...
34997d5b9e2d34f358f846809dc730229f3185ad2e1a6fc095457ea4a49ec743
Python
3,877
98
import torch import torch.nn as nn import torch.nn.functional as F thresh = 0.15 lens = 0.5 probs = 0.5 decay = 0.6 cfg_cnn = [(2, 64, 3, 1, 3), (64, 128, 2, 1, 3), (128, 256, 2, 1, 3), (256, 256, 1, 1, 3), ] cfg_fc = [512, 512, 200] def mem_update(opts, x, mem, spike): ...
893fb07eb25a121ea9f293e200ddf6b703b722dbc169d8303c2cce8bda39765e
Python
3,878
94
import abc import numpy as np from projectmetis.python.models.model_dataset import ModelDataset from projectmetis.proto import metis_pb2, model_pb2 class ModelOps(object): def __init__(self, model, encryption_scheme=None, *args, **kwargs): self._model = model self._encryption_scheme = encryptio...
a428c9e02963f474f0369583f645d78ef83f573041b99fb81ec26114ab5542e6
Python
3,879
135
import numpy as np from numba import njit @njit def isotonic_l2(y, sol): """Solves an isotonic regression problem using PAV. Formally, it solves argmin_{v_1 >= ... >= v_n} 0.5 ||v - y||^2. Args: y: input to isotonic regression, a 1d-array. sol: where to write the solution, an array of the sa...
56a9248a0bd8e69e631d2220a54ecb042b23bb3a57b3f304f52df7ef3c9cbbc0
Python
3,880
110
import csv import os import matplotlib.pyplot as plt import wandb class Losses(object): def __init__(self, dataloader, losses="px"): self.dataloader = dataloader self.names = losses if isinstance(losses, list) else [losses] self.losses = {phase: {loss: [0.0] for loss in self.names} for ph...
91d02335b8c124f5d19b8c9f24dd0dddf06a141d2b9ab823f2bb72fe40a41ff0
Python
3,881
110
import re import h5py import torch import argparse import numpy as np import os from tqdm import tqdm from darts import TimeSeries from sklearn.metrics import r2_score from src.data.load_data import load_params, load_darts_timeseries from src.tools import load_model SUBS = [f"sub-0{i}" for i in range(1, 7)] def mai...
7f42ff54f864969346e59276acd086c76359ae755147fec9fe742a58c1750c8b
Python
3,883
101
from loguru import logger import os import sys import json from deltasplice.constant import CL, EL, Fapath from bisect import bisect_left import numpy as np from pyfasta import Fasta def parse_line(line, i): line = line.replace("\n", "").split("\t") try: Name, _, Chr, Strand, Ts, Te, Js, Je, Psi, delt...
2720e1b774a3ccabf6463b39efddef6d4a3b4b909b0dd5d6e344788eb52ae52d
Python
3,884
108
from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Union from pandas import Timedelta @dataclass class BaseAnalysis: """Description of base analysis module of report. Overall info about report. Attributes title (str): Title of...
aa26c6e475effb56319c58d3efe1f342f032be80ae68e1f2a48714c7e32b8a9d
Python
3,884
99
import unittest from copy import deepcopy import torch from rising.transforms import BoxToSeg, DoNothing, FilterKeys, InstanceToSemantic, PopKeys, SegToBox class TestUtilityTransforms(unittest.TestCase): def setUp(self) -> None: torch.manual_seed(0) def test_do_nothing_transform(self): inp ...
b5368c16c9f147cc13903d17df7c67dfc7eb30eb85bd87276d43d5b5156e095d
Python
3,884
106
import yaml import scipy import pickle import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt def get_max(x, m=100): lex_x = x.shape[0] max_x = np.zeros(lex_x//m) for i in range(max_x.shape[0]): max_x[i] = np.max(x[i*m: (i+1)*m]) return max_x def bootstrapped_val(x, stride,...
b97842992e19f8f043e38fc602c2d026e9487e871b990f4566523a7ae510d9e4
Python
3,884
98
import os import numpy as np import matplotlib.pyplot as plt import ivim root = '/path/to/root' input_root = os.path.join(root,'data') results_root = os.path.join(root,'results') subs = [sub for sub in os.listdir(results_root) if sub.startswith('sub')] runs = ['run-{}'.format(r+1) for r in range(2)] scans = ['sIVIM'...
d6542531b4828a6af569178b2f5e8cc2250537fe5cb60f0d1eef0b4697d92bc9
Python
3,884
64
from nnunetv2.model_sharing.model_download import download_and_install_from_url from nnunetv2.model_sharing.model_export import export_pretrained_model from nnunetv2.model_sharing.model_import import install_model_from_zip_file def print_license_warning(): print('') print('####################################...
32d5b8976a833867adbb0bf7be471a3df0b2a32b8a090b71aa80de2ed4f97905
Python
3,885
139
from typing import Literal, Tuple import numpy as np import torch from flyvis.utils import hex_utils def rotation_matrix(angle_in_rad: float, three_d: bool = False) -> torch.Tensor: """Generate a rotation matrix. Args: angle_in_rad: Rotation angle in radians. three_d: If True, generate a 3D...
15e348a093596bbcba40cbb4c6bce970651ffbeac148fafab590f00b93a4b223
Python
3,886
132
""" Test of spikes_from_array_latency_code This population creates input spikes based on array values and the following translation of values to time: t = t_max*(x_max-x)/x_max The approach is tested by generating random input data of a given size. The stim population is connected in a one-to-one fashion to an eq...
89b80d9fd9d640e95cd3f7aba54387dff2c718e576f7f9482b956a7ebb381798
Python
3,886
100
""" Parts of the U-Net model """ import torch import torch.nn as nn import torch.nn.functional as F # import cv2 # import numpy as np # import os class DoubleConv(nn.Module): """(convolution => [BN] => ReLU) * 2""" def __init__(self, in_channels, out_channels, mid_channels=None): super().__init__() ...
13339b0a3c5e5465152e6a5496a56194f6d9eeaea3bd1aab13ba86bb35f43dc1
Python
3,887
92
import sys import logging from typing import Optional import pandas as pd import pickle import yaml import click logging.basicConfig( format="[%(asctime)s] %(levelname)s:%(name)s: %(message)s", level="INFO", stream=sys.stdout, ) logger = logging.getLogger(__name__) @click.command() @click.option("--exp_di...
fbc64ab2cb1c24fd2c3bb14a9c4cddaca0de61e9ac54d188cc40c7dc1fd0fc57
Python
3,887
103
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
499f4b17258ea95d733e1ed2de84d450ac9025a71f59ec7c1e97c8ca1eea9d17
Python
3,889
113
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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...
60e9a50fb64c590a485f1fb7dc61b1d507ed9efd894d1c1ef84b4bee001def60
Python
3,889
96
#################################################################################################### # 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...
0d5e7db332fef92e6d4dfb41239a98251638e8089b8792691760d870488e5702
Python
3,890
106
from abc import ABC, abstractmethod from typing import ContextManager, Iterator, List, Optional from .execution_options import ExecutionOptions from .physical_operator import PhysicalOperator from .ref_bundle import RefBundle from ray.data._internal.stats import DatasetStats class OutputIterator(Iterator[RefBundle],...
3950664621b252ef2071e1d66e34d569e5d1a226ffba86b58bb2e037d84c8f17
Python
3,892
108
"""Code in this file is heavily based on the code from the following repository: https://github.com/CompVis/invariances""" import numpy as np import torch import torch.nn as nn from ldctinv.cinn.blocks import ConditionalFlow, FeatureLayer from ldctinv.vae.blocks import ActNorm, DenseEncoderLayer class DenseEmbedder...
61e00526d4cbb0d5e64776cf4692001f843a90472f092f4e1779e00798a8689d
Python
3,893
123
import time from os.path import join import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim from config import args from models import GNN, GNN_graphpred from sklearn.metrics import roc_auc_score from torch_geometric.data import DataLoader from util import get_num_task f...
8368e3c6008266c0a329b25bbcd4e0aa2face4e1a0dc390dbda1d677e945d3b7
Python
3,893
114
# Copyright 2023 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
c0d3b70ad42a33570c4577d80f9c761213939a594ca919f932b90fe8be27d140
Python
3,893
90
"""Read units: sub-file units of work. A read unit is a piece of one file that a reader scans on its own and can name, so anything downstream can refer to that piece again. A Parquet row group is one example; a reader that scans a file in a single pass reports the file itself as the unit. Three small types share the ...
db65133f0490d5f52b0963c4111383957eae312f7f0b2e925f15076304993a05
Python
3,896
116
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT """ This script lists resources on the CVAT server and saves them to JSON files in the `assets` directory. Before running it, start the test instance by running: pytest tests/python --start-services The script determines which endpoints to quer...
0e29adc639ccd5ea6e0daf5060b2ce4f0e29d777461c04fed5707b5c8bd187b5
Python
3,897
94
import pandas as pd import os import sys def get_hg38_chrom_size(): f_chrs = open("../hg38_chrom_size.tsv", "r") lines = f_chrs.read().splitlines() chrs = {} for line in lines: eles = line.split("\t") chrs[eles[0]] = int(eles[1]) return chrs def main(): chrs = get_hg38_chrom_...
a643afb1f7cd834217fabecb777bb107e37568a1a435dc03e452fbc3f937f568
Python
3,899
95
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 import pandas as pd import pickle import concurrent.futures import pyranges as pr import json import...
496abe6f0cd153282a6820383bade70f6bc3e283f023e7d5e4f7a8d2e35503c3
Python
3,900
151
# Author: Zachary Chiang, Buenrostro Lab, Harvard University # Adds haplotype information to .bam file import sys import numpy as np import math group_file = open(sys.argv[1],'r') sam_file = open(sys.argv[2],'r') # create dict with all groups groups = {} for line in group_file: column = line.rstrip().split() col...
f9094d44a0c62b24bafa3ed48b486fb5ab445a28634babcb3300115cb4bf96f8
Python
3,900
114
from batchgenerators.dataloading.data_loader import SlimDataLoaderBase from batchgenerators.dataloading.multi_threaded_augmenter import MultiThreadedAugmenter import numpy as np class DummyDL(SlimDataLoaderBase): def __init__(self, num_threads_in_mt=8): super(DummyDL, self).__init__(None, None, num_thread...
95fd6c79efea544ae301ceb76e5cc3661d7918b66784d114d8335b4759b8cd31
Python
3,902
97
import torch import torch.distributed as dist import torch.multiprocessing as mp import argparse import os, glob from sklearn.model_selection import train_test_split from torch_geometric.loader import DataLoader import socket from src import AseReadDataset from src import TrainerPreTrain from equiformer_v2.nets import...
2baa725377f2d77ace48d12f27681dbe1f6d2450b2df94a82c50c75f6cda6dbc
Python
3,903
128
#!/usr/bin/env python3 """ OmicVerse 统计功能使用示例 这个示例展示了如何在生成报告时启用或禁用统计功能。 """ import scanpy as sc import omicverse as ov import os def example_with_analytics(): """启用统计功能的示例""" print("📊 示例1:启用统计功能") # 假设我们有一个示例数据集 # adata = sc.datasets.pbmc68k_reduced() # 生成报告时启用统计(默认行为) # ov.generat...
d1b567240d6c92ac9ca66b914b5e3c0a55c2c06dfbe40a7fd13030ebbf60c6bb
Python
3,904
118
import copy import glob from keras.models import load_model import numpy as np from numpy.random import seed import os import pandas as pd import shutil import sys import tensorflow as tf def use_available_image_version(file_paths): results = [] for x in file_paths: # It will only do this for eLife im...
fb8453d3f3e2f557520f4a2fa0a3a89246bceebbb0369aa398c09dddfc00f17f
Python
3,905
115
__author__ = "Simon Andermatt" __copyright__ = "Copyright (C) 2017 Simon Andermatt" import numpy as np from mdgru.helper import argget, compile_arguments, generate_defaults_info import functools import copy import torch as th from torch.nn import init import logging def init_weights(m): if hasattr(m, 'initialize...
70804c0e53c9fe8b72b4fad8ec2c3da57180c6dcfcba9bd2e9b3db6dbd4b46e8
Python
3,908
93
import tensorflow as tf from models.deep_learning.deep_learning_models import DLRegressor from utils.constants import is_spline class GRURegressor(DLRegressor): """ This is a class implementing the GRU model for time series regression. ! Remember to use regularization techniques such as dropout, weight d...
7755252ff244da9f392bbff551d992a6fb422b93834393d29438778c61b947d8
Python
3,909
96
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...
923e361a82ec4861f0207cc3837ae1150f445828e5bd87007cb717b565283e5b
Python
3,909
77
class BazelMetisServicesCmdFactory(object): @classmethod def bazel_init_controller_target(cls, hostname, port, aggregation_rule, participation_ratio, ...
bb21b177730e5b63e53641bd56ed2ffff975656ffe651fa9bf2d1fa69d5b27a5
Python
3,909
123
import json import matplotlib.pyplot as plt from scipy.stats import spearmanr, pearsonr import pandas GlobalDict = {} def load_json(Path): with open(Path, "r") as f: return json.load(f) def load_txt(Path): with open(Path, "r") as f: content = f.readlines() content = [list(map(float, x.st...
885c59e74f3c2dd7a84b653f704eb1f368d67aa15fd2546c172e82603b5d98d3
Python
3,910
18
from .index_tools import make_index, show_df from .io import save_network_all, load_network_all, load_params, save_params, save_meta, load_meta, load_experiment_meta, load_experiment_results, save_outputs, load_outputs, save_activity, load_activity, RESULTS_DIR, SAVED_DIR, load_responsiveness, load_rates, load_weights,...
383730c20f48d58a2b311d5a0e7656af9ccf1fe3ae8696f360941b9b9cf255f3
Python
3,911
122
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from pdb import set_trace as stop def batch_product(iput, mat2): result = None for i in range(iput.size()[0]): op = torch.mm(iput[i], mat2) op = op.unsqueeze(0) if(result is None): ...
d1ae7e7ee4011d1da98bb2f8264c030f9dda5861da56d3aef94d6c2514b88ad5
Python
3,911
105
#################################################################################################### # Copyright (c) 2020 - 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...
4fefe2fd51f773da229d2ee7f00f0bf826c2e3e1a2130b7a52e5e9c27aba95b8
Python
3,912
104
"""Parquet chunk helpers for DataSourceV2. Maps the ``unit_ids`` of a ``FileChunk`` row (the explicit surviving row groups a bin assigns to a file) to PyArrow ``ParquetFileFragment`` subsets for reading, and names the read unit each subset stands for. """ from typing import Callable, Iterable, List, TypeVar import py...
0e5b9006fde369c5879be75f15313f0115e12efc2e4b7ebb7c937c054c499c24
Python
3,914
111
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Base class for an Experiment Runner.""" from typing import Any, List, Optional from aihwkit.cloud.client.entities import CloudExperiment from aihwkit.cloud....
afddbaa55e64df7a25b6565ae18985d59856075fc565dc704d4fbf28462c1cd7
Python
3,915
111
import matplotlib.pyplot as plt import numpy as np import h5py import library # Generate distributions gecis = ['jrgeco'] mouse_ids = ['6841'] recording_ids = [0, 1, 2] sizelims = [1, 500] durlims = [1, 50] ks = list(range(1, 15)) xpt = 3 rows = 3 cols = 2 fig, axes = plt.subplots(rows, cols, figsize=(5*cols, 5*row...
0c1556324b34ed9efe8224c8fdb16f3589380245563772c18a5c8fafa1dfb6bd
Python
3,916
75
proj_dir = "/path/to/main_project_folder/" # edit this line import numpy as np import pandas as pd import xarray as xr import dask.array as da import glob as glob from functools import partial import sys sys.path.append(proj_dir) from project_fxns import load_region from project_fxns import fxns import importlib impor...
c1c5660f80eeca2efad7025087ac66aeb255490c568ebd2abbb50f5b790646e9
Python
3,916
125
from collections import defaultdict from scipy.signal import find_peaks_cwt import numpy as np from .utils import fill_tril_inplace def call_boundary_peaks(Pb): n = len(Pb) peaks = find_peaks_cwt( Pb, np.array([0.5]), wavelet=None, max_distances=None, gap_thresh=Non...
0ac76d9be4a73a0d83f130b45f0edd38176511f3ea38bbefb1384be44cf8b51e
Python
3,917
88
import numpy as np import matplotlib #matplotlib.use('TkAgg') import matplotlib.pyplot as plt import os import utils import pandas as pd from scipy import stats datadir = "./" param = utils.parseparam(f"{datadir}/apps/reprlearn/reprlearn.par") cij = utils.loadbin(datadir, "learn.cij.l1.bin", shape=(-1, param['H1'], pa...
08a57317291452ed84ad6e91c720d85e5abcfb1013c8e1de448eb4850705a3ae
Python
3,918
120
# -*- coding: utf-8 -*- # """ std_s.py Standardize Lumpy records. """ from .standardize import VCFStandardizer from svtk.utils import is_smaller_chrom, parse_bnd_pos @VCFStandardizer.register('smoove') class SmooveStandardizer(VCFStandardizer): def standardize_records(self): for record in self.filter_r...
afb41919c9f13e621fb7ab1699045dc4b9513390c7bef7215d113a4fb47e6a98
Python
3,918
81
import sys import json import pickle import argparse from lop.utils.miscellaneous import * from lop.utils.plot_online_performance import generate_online_performance_plot def add_cfg_performance(cfg='', setting_idx=0, m=2*10*1000, num_runs=30, metric='accuracy'): with open(cfg, 'r') as f: params = json.loa...
1d32229b429a6d2d2c7887e4703b8663cad52f9761a94c431084d8f821fdf28a
Python
3,919
88
import os import glob import numpy as np from pathlib import Path import mne def find_files(root, naming_pattern=None, extension=None): """ This function finds files matching a specific naming pattern recursively in directory from root :param root: root of the directory among which to search. Must be a st...
56fdc5435a99bfb2b3be6c5c46a9b83f4713c2b99520b737ca26b12b5423fce4
Python
3,920
99
import glob import hydra import os import pandas as pd from omegaconf import DictConfig, OmegaConf from pathlib import Path from posebusters import PoseBusters def resolve_input_protein_dir(data_dir: str, dataset: str) -> str: """Resolve the protein directory for a given method. :param data_dir: The data d...
08ea1d86702d1214b2b50677979e2cdc1a9aeeaac237c015ac023d2fe0455b72
Python
3,921
112
import torch import monai.transforms as mt import numpy as np from glob import glob import sys sys.path.append('./') import torch import numpy as np import os import monai.transforms as mt from utils import threshold_at_one, jpg_to_ndarray class ABUSsetNew(torch.utils.data.Dataset): def __init__(self, args, fo...
1eb91d4860a7fa66cc4ce3877aa0bfa7d5ba3ddd3b368fe43ce95919b405a667
Python
3,926
143
#!/usr/bin/env python # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
3da15f1f6e27c313f59a6ad89022a1d34eb84a812735200557b11d86ef95a51f
Python
3,926
122
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from pdb import set_trace as stop def batch_product(iput, mat2): result = None for i in range(iput.size()[0]): op = torch.mm(iput[i], mat2) op = op.unsqueeze(0) if(result is None): ...
64f85822a751b441f022a3444a7ef54ee271b1cc98ba8cb0f2566f5956e9a847
Python
3,926
129
from typing import Callable, Dict, Hashable, Mapping, Sequence, Tuple, Union from rising.transforms.functional.utility import filter_keys, pop_keys from .abstract import AbstractTransform __all__ = ["MapToSeq", "SeqToMap", "PopKeys", "FilterKeys", "RenameKeys"] class MapToSeq(AbstractTransform): """ Conver...
adca38b5a549fd1c2e20c0070aef56b4aabe43c42c88fe5d82ae4fbaf7926982
Python
3,926
95
from __future__ import annotations from pathlib import Path import numpy as np import pandas as pd from scipy.signal import find_peaks, peak_widths TIME_GRID = np.round(np.arange(6.0, 30.0 + 0.01, 0.01), 2) MZ_GRID = np.arange(50, 600, 1) EXPECTED_SHAPE = (TIME_GRID.size, MZ_GRID.size) def _load_matrix_csv(path: P...
5407f8d8d2674eae8f3f9703e1d2996215dddd772a96e12f253c4428c83f472a
Python
3,927
108
# Modified from https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/test_time_augs/det_tta.py # noqa from typing import List, Tuple import torch from mmcv.ops import batched_nms from mmdet.structures.bbox import bbox_flip from mmengine.structures import InstanceData from torch import Tensor from lqit.co...
244c7d5e63329aa27e6ac9a0deb264f4fe2960313b491a16fbff21f4c3cd76d9
Python
3,928
121
import time from collections import Counter from typing import List, NamedTuple from ray._raylet import GcsClient from ray.autoscaler.v2.schema import ClusterStatus, Stats from ray.autoscaler.v2.utils import ClusterStatusParser from ray.core.generated.autoscaler_pb2 import ( ClusterResourceState, GetClusterRes...
35eed546d3b14c191eea98cdffd321ba57dcf2beb9f18a54d1464651f71eefda
Python
3,928
125
import json import pickle import pandas import os from utils.graph_utils import smiles2graph from utils.chemistry_parse import clear_map_number import random import numpy as np import torch from tqdm import tqdm import rdkit from rdkit import Chem import multiprocessing from utils.tokenlizer import DEFAULT_SP, Tokenize...
13edd102c83e50b38e9241ee7f6e94fcec871642bb4300c3bce49e99e1cb918c
Python
3,929
115
# Copyright 2023 Google LLC # 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
8a4e8c6ff235a9decbf9db7d727b053319d4904c701893e3d3d53da858a29aed
Python
3,930
107
""" EWH - used to start a thread for a specific valuelogger. """ from datetime import datetime import os import time from PyQt5 import QtCore def isnan(num): return num != num class valuelogger(QtCore.QThread): timelog=None valuelog=None historylength=None logfile=Non...
4be3b77b3ffb537022210d61f919aadf06855fc6992b9933e68fcd6d87a1a1b3
Python
3,931
140
""" Shared utilities for generating Docker image tags for Ray and Anyscale images. """ import logging from typing import List from ci.ray_ci.automation.crane_lib import ( CraneError, call_crane_copy, call_crane_manifest, ) from ci.ray_ci.configs import DEFAULT_PYTHON_TAG_VERSION from ci.ray_ci.docker_cont...
eeac7eb020c6b266686801fc47a804d713b28e0ec151a56d5a46b4df29a6f88e
Python
3,931
108
import yaml import scipy import pickle import argparse import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt def bootstrapped_return(x, y, stride, total_steps, confidence_level=0.95, to_bootstrap=True): assert len(x) == len(y) num_runs = len(x) avg_ret = np.zeros(total_steps // stride) ...
0e8b69c4490ce6c216b0621a926aeda87d40e453526477c8f74fccf757723068
Python
3,933
103
import os import tempfile from pathlib import Path import numpy as np import pytest import torch from PIL import Image from flyvis import connectome_file from flyvis.connectome import ConnectomeFromAvgFilters SEED = int(os.environ.get("FLYVIS_TEST_SEED", 0)) """Seed used to make the test suite deterministic. Overri...
62a88e7e4f78553ae0946343e4b544a5e14116d47086a8b623fbad2184459f23
Python
3,933
131
# flake8: noqa # __example_start__ from starlette.requests import Request from typing import Dict import ray from ray import serve from ray.serve.handle import DeploymentHandle from transformers import AutoModelForSeq2SeqLM, AutoTokenizer @serve.deployment class Translator: def __init__(self): self.lan...
fd09d8f9cd70dd666dd030ee001b87742a8da445a047a34ddbb1bef312b67038
Python
3,934
126
from __future__ import annotations from collections import defaultdict, deque from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Deque, Dict, Iterator, Optional from typing_extensions import override from .base import QueueWithRemoval if TYPE_CHECKING: from ray.data._internal.execution.int...
8ccd044dcf926cc9cb27191856e31c5302b9cfa35706472d09d9938e489f3978
Python
3,935
124
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Run before 04_v2_genotype_batch """ import argparse import os import firecloud.api as fapi from firecloud import fccore from google.cloud import storage fcconfig = fccore.config_parse() def get_bucket_name(namespace, workspace): response = fapi.get_workspace...