sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
8cea80038671312efd0ae0d00bc2d2bb1d7333ac9f0574a15f19414192bc8c62 | Python | 2,319 | 61 | import sys
states = {k:v for v,k in enumerate(['none', 'pre_caption', 'post_caption', 'caption_title', 'caption', 'dump_buffer'])}
def recon_figure(infile, outfile):
state = states['none']
caption_tag = r'\caption{}'
indent = ''
buffer = []
for i, line in enumerate(infile):
if state == sta... |
dbb9393a772657080ede4d37f29d34dfaa5ea9f406f33caa5648d8efffdc17a1 | Python | 2,319 | 73 | import itertools
import os
import random
# python ../02_fit_logistic.py --dataset financial_phrasebank --checkpoint distilbert-base-uncased --subsample 1000 --ngrams 1 --all all --layer last_hidden_state_mean --seed 1
# # python ../02_fit_logistic.py --dataset financial_phrasebank --checkpoint distilbert-base-uncased... |
df5727b7ddc069c8d9ec31c92392ff0ffd21773da93ea5e5bdb84bfa02c479c5 | Python | 2,319 | 86 | """Dataset handler."""
import numpy as np
import pandas as pd
__author__ = "Gianluca Corrado"
__copyright__ = "Copyright 2016, Gianluca Corrado"
__license__ = "MIT"
__maintainer__ = "Gianluca Corrado"
__email__ = "gianluca.corrado@unitn.it"
__status__ = "Production"
class Dataset(object):
"""General dataset."""... |
f1ff0a03ad68b03842eb37d48113dff906df4d3b163c79c86385fc4e3b7f186d | Python | 2,319 | 56 | import sys
# setting path
sys.path.append('../TM2_segmentation')
import os
import numpy as np
import nibabel as nib
import itk
import pandas as pd
import tarfile
from scripts.preprocess_utils import find_file_in_path, register_to_template
# load metadata file
input_annotation_file = 'data/csv_files/petfrog.tsv' ... |
1e1d99feb9097839eae879fcc821d7844b71121f1c9493d68a9721a51c32e739 | Python | 2,320 | 69 | import os
import tempfile
from functools import cache
from galaxy.files import (
ConfiguredFileSources,
ConfiguredFileSourcesConf,
)
from galaxy.files.plugins import FileSourcePluginsConfig
from galaxy.util.config_parsers import parse_allowlist_ips
class TestConfiguredFileSources(ConfiguredFileSources):
... |
6a6ed0a83ebfda69992fa6d5e25dc5a0db3fe89bf11b4e14d607bf6605a8d579 | Python | 2,320 | 56 | """ Classifier head and layer factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from torch import nn as nn
from torch.nn import functional as F
from .adaptive_avgmax_pool import SelectAdaptivePool2d
def _create_pool(num_features, num_classes, pool_type='avg', use_conv=False):
flatten_in_pool = not u... |
9040bc3f6333b095567cf2ae0e1fa64f22341214566ddbbb04985fc8c05ce3ad | Python | 2,321 | 71 | # Utilities working with (and needing to import) plots
import os
import numpy as np
from .._utils import ui
from ._base import TimeSlicer
def save_movie(figures, filename=None, time_dilation=4, tstart=None, tstop=None, size=None, **kwargs):
"""Save a movie combining multiple figures with moving time axes
... |
151c406b2e6ff3650a82fcaef63f59b53ef8a05ab2ab0425568f7803171f2b7b | Python | 2,322 | 79 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Leaf(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "i... |
495300558cbb1c095734db96c12461edc6ecf9621840adf26c4a7070fdae17c2 | Python | 2,322 | 95 | #!/usr/bin/env python3
import sys
import re
import numpy as np
#regex for cigar
re_split_cigar = re.compile('(\d+[MDI])(?=[0-9]|$)')
#SAM INDEXES
idx_qname = 0
idx_flag = 1
idx_rname = 2
idx_pos = 3
idx_mapq = 4
idx_cigar = 5
idx_rnext = 6
idx_pnext = 7
idx_tlen = 8
idx_seq = 9
idx_qual = 10
def write_err(m... |
a42e6cf3608b83a782b85d8ab058671ad4db37488a0709cdbdaf4e01044b27ed | Python | 2,322 | 69 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
aaf1bacec1756baceac0973657cf9b9be3d3c128ef0380e11074dbb7f6f86b53 | Python | 2,322 | 63 | from io import StringIO
from unittest.mock import Mock
import pytest
from celery.contrib.testing.manager import Manager
class test_Manager:
@pytest.mark.parametrize('emit_warning', [False, True])
def test_wait_for_retries_with_optional_warning(self, emit_warning):
stdout, stderr = StringIO(), String... |
17fc6b5c58feee2a0943bc64c85baca72bb992bf9177c796321d4fa6fbad1bb5 | Python | 2,323 | 56 | from __future__ import absolute_import, division, print_function
import numpy as np
import struct
def text_to_char_array(transcript, alphabet, context=''):
r"""
Given a transcript string, map characters to
integers and return a numpy array representing the processed string.
Use a string in `context` f... |
22e428d38984a474dbdc0c770d5b78365cfa01d7b7ab441cee4740932683a71c | Python | 2,323 | 97 | # -*- coding: utf-8 -*-
"""
Created on Wed July 14 13:04:36 2016
@author: Rafael Neto Henriques
arg1 = path
e.g. Z:/DWI3shells/DWI/Subject1/Rep1/
arg2 = name of DWI in nifti format
e.g. DWI_brain.nii
arg3 = name of DWI mask in nifti format
e.g. DWI_brain_mask.nii
arg4 = name of bvals in bval format
e.g. bvals.bval... |
77225bd4c48f0e90b71bc96b3bb3653563c4d30aeb541100260e42e5e8803b4d | Python | 2,323 | 61 | """spiketools setup script."""
import os
from setuptools import setup, find_packages
# Get the current version number from inside the module
with open(os.path.join('spiketools', 'version.py')) as version_file:
exec(version_file.read())
# Load the long description from the README
with open('README.rst') as readme... |
0341dbf6b705741601def8b4f816eb2eb759d0ee15c6ab6c5fda7ff489ddb296 | Python | 2,324 | 65 | """
Ch1 EPOCH pre A B C post
Type Step Step Step Step Step
First Level (mV) -10 -20 -10 25 25
Delta Level (mV) 0 0 0 10 0
First Duration (samples) 312 1000 4000 10000 0
Delta Dur... |
c9f0e8acfb57f6a14ea617015be396b5046846dcdcb81ae8846358fcbef5c428 | Python | 2,324 | 81 | import logging
import yaml
import copy
import argparse
from bson.objectid import ObjectId
from pymatgen.core import Molecule
from atomate.qchem.fireworks.core import FrequencyFW
from atomate.common.powerups import add_tags
from fireworks import LaunchPad, Workflow
from instance_mongodb import instance_mongodb_sei
... |
0f75e259cf1e4656d3b18b5fae31fb186dc85ce35046bec7ebc475c379fe2bea | Python | 2,326 | 48 | from chembl_webresource_client.new_client import new_client
import pandas as pd
def retrieve_data(target_id='CHEMBL3979', waitbar=True, endpoints = ["Ki", "Kd"], relations = ["="]):
"""
Function to retrieve the data from ChEMBL, starting from a given ChEMBL ID (target)
:param target_id (str): ChEMBL target... |
4eee452ee2f2676aa618f87f35aac50c4646ed6bb1cdea6b2b2e455978772659 | Python | 2,326 | 65 | __author__ = 'quentin'
from ethoscope.tracking.cameras import V4L2Camera
from ethoscope.tracking.cameras import MovieVirtualCamera
# Build ROIs from greyscale image
from ethoscope.tracking.roi_builders import SleepDepROIBuilder
# the robust self learning tracker
from ethoscope.tracking.trackers import AdaptiveBG... |
acb3d8af68db117c7ac73c70cf5ac4a4491c018339c5af64f2e20c94b9e8f380 | Python | 2,326 | 60 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 2 11:48:36 2022
@author: psicobiologia
"""
import pickle
import scipy.io
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV, cross_val_score, cross_val_predict, cross_validate, StratifiedKFold... |
beef319adc0c671e9f29d9800cc68fc4de0fb27e086d2187532ee278b8b7e419 | Python | 2,326 | 104 | '''Subclasses of torch.nn.Module, that are reversible and can be used in the
nodes of the GraphINN class. The only additional things that are
needed compared to the base class is an @staticmethod otuput_dims, and the
'rev'-argument of the forward-method.
Abstract template:
* InvertibleModule
Coupling blocks:
* AllI... |
a5532a2c93016fbb0e7d699a4059e68dd457ca2d98b8170df701a46d26aeb9f3 | Python | 2,327 | 56 | #!/usr/bin/env python
import os
import fnmatch
import optparse
def find_db_file(base_path, ethoscope_number, experiment_date):
"""
Finds database files that match the given ethoscope number and experiment date pattern.
Args:
base_path (str): The base directory to search in.
ethoscope_numbe... |
debdd3150fbe40f7f0484cdb1535785de67d158cf8651ae0416fcd67f086f7c9 | Python | 2,327 | 70 | from __future__ import annotations
__doc__ = """
Use get_hash() to generate a hash of the .toml and .py that are part of a package
"""
import hashlib
import logging
from collections.abc import Iterable
from _hashlib import HASH
from pkg_resources import resource_isdir, resource_listdir, resource_stream
from bream4 ... |
86c87633ee1138e8b83da5511021fcb8abb41afea9838ccb899aaed073870eba | Python | 2,328 | 40 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import torch
from ultralytics.data.utils import check_det_dataset, convert_ndjson_to_yolo_if_needed
from ultralytics.models.yolo.detect import DetectionValidator
from ultralytics.utils.torch_utils import select_dev... |
b5a98d835f8b3376c8651bf9946d5efc16f0d8da66b9749ce64bb7ac29e08cae | Python | 2,328 | 58 | from importlib import import_module
#from dataloader import MSDataLoader
from torch.utils.data import dataloader
from torch.utils.data import ConcatDataset
# This is a simple wrapper function for ConcatDataset
class MyConcatDataset(ConcatDataset):
def __init__(self, datasets):
super(MyConcatDataset, self).... |
0358553acd219129a21cb5e3125f8f13fa5ea16a7413a18784534791bbe34b70 | Python | 2,329 | 85 | #!/usr/bin/python
#-*-coding:utf-8-*-
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... |
2f54e2e5586748ef38cc2dd1456c68cf879c03bf2c26de4f1ca3983f886d3033 | Python | 2,329 | 68 | import numpy as np
import pandas as pd
import math
# 读取数据
import tensorflow as tf
import numpy as np
association_matrix = pd.read_csv('output/association_matrix.csv', header=None, encoding='gb18030').values
# 100列,676行,每列表示一个病和各rna是否有联系,每行表示一个rna和每个病是否有联系
# 计算disease之间的相似度
association_matrix = association_matrix.T
... |
53ef52953465216d242461339ca1f48177effaddf51a432c55e53fb858451735 | Python | 2,329 | 82 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# ------------------------------------------------------------------------------
from __future__ import division
import numpy as np
def unfol... |
a041ab359c3fd7ded5b4cd3b3bc071b3c88892959fcea638c764661512cc90b0 | Python | 2,329 | 63 | import pandas as pd
import pathlib
from pathlib import Path
import json
class Cohort(object):
def __init__(self, sql_template, params, cohort):
self.cohort = cohort
self.sql_template = sql_template
self.params = params
def __len__(self):
return len(self.cohort)
@classmeth... |
a0baafd465a66eae2586fc62d888fcf04080b8d159f4f522f89f9b242409d2ef | Python | 2,329 | 66 | # Mossy layer at 0 deg
from os.path import join
import numpy as np
import os
import pandas as pd
from library.comput_utils import cal_hd_np
from library.params import ParamsHolder
from library.shared_vars import sim_results_dir
from library.utils import save_pickle
from library.simulation import simulate_SNN
for analy... |
6125f440cd4baa824c01fb9ce554de39fce77fe5e1b4ecf73c01d9cffa57d8b3 | Python | 2,330 | 65 | '''
In a previous step, we made data matrices suitable for the zero-shot learning
algorithm. This script averages the evoked responses acrosss individuals together
to get a grand-average data matrix.
'''
import sys
sys.path.append('..')
from config import fname, events_id, triggers, categories
import mne
import numpy ... |
bcdb44db7b106078b8db8400ce982cf5b733be43f7a07e4b1dd1d333f40a5dc3 | Python | 2,330 | 68 | # dataset: mne_sample
"""
This example demonstrates how to define a function to load data form a specific
experiment.
Since there is usually just one event structure per experiment, it makes
sense to write a function for labeling events that can be re-used in
different analyses. Such a function is defined in this scri... |
c3a056a8e85339a6ceee2622d77bba0c23ee23dce015c221bbb0a42034ef37e1 | Python | 2,331 | 68 | """Written by @Jinerhal, adapted by @Xiaojieqiu.
"""
from typing import Dict, Optional, Tuple, Union
import cv2
import numpy as np
from anndata import AnnData
from ...configuration import SKM
from .utils import save_return_show_fig_utils
@SKM.check_adata_is_type(SKM.ADATA_UMI_TYPE, "adata")
def spatial_domains(
... |
85661546d4e15254d6662453411dc8ece84340f0290936d50cdd510540a5f399 | Python | 2,332 | 79 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Leaf(_BaseTraceHierarchyType):
_parent_path_str = "sunburst"
_path_str = ... |
26aaa1d80e67a48727eccc81490f28fe39f827ef5d7f00c051a47c662acb2ce9 | Python | 2,333 | 71 | """
Modules comprising the layered behavioral architecture modeling the nervous system,body and metabolism
"""
from __future__ import annotations
from typing import Any
__displayname__ = "Modular behavioral architecture"
# Public API: explicit, lazy re-exports of commonly used symbols
__all__: list[str] = [
"Br... |
ccdbf4d9279a776d4eb368e60471c6d09bbf427013b9f53b00bb59275efb9a33 | Python | 2,333 | 72 | import click
import pandas as pd
import vampire.common as common
translation_csv = 'adaptive-olga-translation.csv'
def adaptive_to_olga_dict():
gb = common.read_data_csv(translation_csv).dropna().groupby('locus')
return {locus: {row['adaptive']: row['olga'] for _, row in df.iterrows()} for locus, df in gb}
... |
399c4f53c25dc266a011d2c6cbb7f3efc9ba02671d9c97eaaf19a80851a605fb | Python | 2,334 | 55 | from Configurations import config as cfg
# ---------------------------------------------------------------
# NOTE:
# ImFCSNet training is essentially a single epoch training since all the data are generated and not re-used.
# There are 48000 (i.e. 1500 X 32) batches in one round of training.
# We partition the batche... |
530ffcac6db71323881e6a6d9b621d3f1e3c3dafe73504554bde2cbe0f1e9765 | Python | 2,334 | 80 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
_parent_path_str = "quiver.unselected.marker"
... |
c6da1bc74f60c8de9777927bddb298feb977428da244039e3e72b93c3e6b50ee | Python | 2,334 | 69 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Functions for concatenating scans across runs."""
import os
from contextlib import suppress
import nibabel as nb
import numpy as np
import pandas as pd
from nilearn.image import concat_imgs
from nipype... |
d5da1340be6f6aa3bb7adcfecfe68ed14f95722902633d0031e5ded200d8718e | Python | 2,335 | 62 | #!/usr/bin/python
#-*-coding:utf-8-*-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... |
7378c6ffd1fd97fb85d3beb390074dad70d3748c285316488cbf6c22402c8ce5 | Python | 2,336 | 63 | import numpy as np
import math
from geometry_msgs.msg import Point, Quaternion
# TODO: make it work with different kinds of messages (Vector3, PointStamped...)
def translation_ros2np(msg):
vector = np.array([msg.x, msg.y, msg.z])
M = np.identity(4)
M[:3, 3] = vector
return M
def rotation_ros2np(msg... |
d3196386d59f1f99aaf37220b5112e75e28b0f397eede0cb63667217e4c02143 | Python | 2,336 | 60 | import glob
import h5py
import numpy as np
import os
import pandas as pd
from sklearn import preprocessing
import sys
"""
hi. this is going to read these in, you basically just need
subjects: path to subjects!
data_path: path to the actual features
phenotypes: path to a csv with the to-be-predicted and the noise
"""
... |
12ada887cad607caae684fdd5b5152db0d8f8c1b8b646e125fe395677415b890 | Python | 2,337 | 66 | import os
import pickle
import zipfile
from unittest import mock
import numpy as np
from keras.src import testing
from keras.src.datasets import npz_utils
class LoadNpzTest(testing.TestCase):
def test_loads_ragged_object_arrays(self):
# IMDB/Reuters store ragged sequences as `dtype=object` arrays.
... |
35dc96dd8f789e1eacb35fcd6d80177d09e7923d93efa7a9bba9f0f657927963 | Python | 2,337 | 82 | from pathlib import Path
import numpy as np
import pytest
from anndata import AnnData
from anndata.tests.helpers import assert_equal
from scipy.sparse import csr_array
from muon import atac as ac
@pytest.fixture(params=[True, False])
def sparse(request: pytest.FixtureRequest) -> bool:
return request.param
@py... |
af7494c2b1ee7f7a2179a57edef6f86ca26e2e943fc87f9dfad1330ba0e0f639 | Python | 2,337 | 55 | """YOLO Demo script."""
import argparse
import mxnet as mx
from mxnet import image
from matplotlib import pyplot as plt
from mxnet.gluon.data.vision import transforms
from .train_cgan import define_G,Resize
def parse_args():
parser = argparse.ArgumentParser(description='Test with cycle gan networks.')
parser.a... |
976c56a5ad06195b9436675142b748447e91a0efe2068a660fa683def73797e2 | Python | 2,338 | 60 | import glob
import h5py
import numpy as np
import os
import pandas as pd
from sklearn import preprocessing
import sys
"""
hi. this is going to read these in, you basically just need
subjects: path to subjects!
data_path: path to the actual features
phenotypes: path to a csv with the to-be-predicted and the noise
"""
... |
b4acac22a0c5ac315698f56326f9a001ece2420be7fdd61ecdd7f606e49fc4bb | Python | 2,338 | 59 | """Smoke tests for chain/callback dispatch on the dedup fast-path.
When ``worker_deduplicate_successful_tasks=True`` and
``task_acks_late=True``, a redelivered task that hits the dedup
fast-path in ``trace.py`` must still dispatch its chain and link
callbacks.
See https://github.com/celery/celery/issues/9835
"""
from... |
d43a5747677f94ea1cc3c0d8b60668ac1b9bced71902e5f38269c1e51dc2fe61 | Python | 2,338 | 70 | import os
import os.path as osp
import mmcv
def convert_ldpolypvideo_to_coco(root_dir, out_file):
ann_dir = osp.join(root_dir, 'Annotations')
img_dir = osp.join(root_dir, 'Images')
images = []
annotations = []
categories = [
{
"supercategory": "none",
"id": 0,
... |
13917e0ccd5f38835cb5ece3a83a9d4a34add51a2c406805224209fbfb1d22df | Python | 2,339 | 81 | """
A set of I/O utils that allow us to open files on remote storage as if they were present locally and access
into HDFS storage using Tensorflow's C++ FileStream API.
Currently only includes wrappers for Google's GCS, but this can easily be expanded for AWS S3 buckets.
"""
import os
from tensorflow.io import gfile
... |
20e7881cfd05dd752f21e4736d4eada75dd8261ff22afaf862d3629d1a404d83 | Python | 2,339 | 52 | from Configurations import config as cfg
# ---------------------------------------------------------------
# DATA
EMCCD_FOLDER = "./training_data/data_EMCCD"
Gaussian_FOLDER = "./training_data/data_Gaussian"
PIXELS = 3 # simulated data are from ROI of 3X3 per image stack, i.e. 9 ACF curves per image stack
DATA_FN_STA... |
741ce22fccf9f4adc0f8c6da0eb63010408c274bcd251a4be3136b416b608499 | Python | 2,339 | 51 | import glob
import os
import pathlib
import shutil
def move_test_files_to_folder(data_folder_in, view_name_in, save_folder_testing):
testing_img_data_folder = os.path.join(data_folder_in, 'images', 'testing')
testing_label_data_folder = os.path.join(data_folder_in, 'annotations', 'testing')
testing_img_s... |
e9281d289fa76281832d51c961cb04d7f7747141c6481d168d72e9e526897f81 | Python | 2,339 | 67 | """
Save mat from snap file to h5ad file.
"""
import anndata as ad
import h5py
import numpy as np
from scipy import sparse
def snapbmat2h5ad(snap_file, bin_size:int = 5000,
prefix:str = '',
outfnm:str = '') -> ad.AnnData:
"""Save bmat from snap file to h5ad.
"""
with h5p... |
ed03b38937510b9f4e563c3b52705a7bcfd55212ca02101bbfbbed5d7cb7b7b4 | Python | 2,339 | 66 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import json
import os
from pathlib import Path
import numpy as np
import torch
from ultralytics.utils import LOGGER
from ultralytics.utils.checks import check_requirements
from .base import BaseBackend
class MN... |
cac004c646ef7d7d9570c38b596a09368f84e05ef87b184c98671e52c0cc7352 | Python | 2,340 | 90 | """
Mapping of the R library "grDevices" for graphical devices
"""
import io
import os
import tempfile
from contextlib import contextmanager
from rpy2.robjects.packages import importr, WeakPackage
grdevices = importr('grDevices')
grdevices = WeakPackage(grdevices._env,
grdevices.__rname__,
... |
032ac601b58432039b39dfaf7c2e1fcd3046520fe5c390b3ef3c79c53f642376 | Python | 2,341 | 74 | from Bio import motifs
import sys,re,os
import numpy as np
''' This script is modified from https://github.com/vagarwal87/saluki_paper/blob/main/Fig5_S6/modisco2meme.py '''
def parse_cisbprna(filename):
storage = []
with open(filename) as inFile:
data = inFile.read()
entries = data.split(... |
5a2ce01465cdd0592b399dd80545544a1d7bd70fddad8763ccb987df3276f696 | Python | 2,341 | 45 | import numpy as np
import tensorflow as tf
import os, argparse
import cv2
from data import process_image_file
parser = argparse.ArgumentParser(description='COVID-Net-P Inference')
parser.add_argument('--weightspath', default='models/COVIDNet-CXR4-A', type=str, help='Path to output folder')
parser.add_argument('--meta... |
879ef4397b8d15247ef1c09c911908ebc4a769790fa7a815c6c7b044a2d0e4bc | Python | 2,341 | 63 | import sqlite3
from .db import Database
from .DL_tables import DL_patient_mgmt, DL_testing_status, DL_vaccination, \
DL_case_info, DL_containment, DL_cumulative, DL_hospitalizations
class DelhiDB(Database):
def __init__(self, datadir):
super().__init__(datadir)
self.init_tables()
sel... |
f62b3f2903a314547ad94ab246287e216b70102f1d87cef551bdf5da4eaa3051 | Python | 2,341 | 53 | from __future__ import print_function
import sys
from svim.SVSignature import SignatureDeletion, SignatureInsertion, SignatureTranslocation
def analyze_cigar_indel(tuples, min_length):
"""Parses CIGAR tuples (op, len) and returns Indels with a length > minLength"""
pos_ref = 0
pos_read = 0
indels = ... |
420b1f1ecbe52ce152ee68ff480abd9cdb88645fe9d13247fa7637b8fd607e6d | Python | 2,342 | 96 | import datetime
from mongoengine import *
from flask_login import UserMixin
from .annotations import AnnotationModel
from .categories import CategoryModel
from .datasets import DatasetModel
from .images import ImageModel
class UserModel(DynamicDocument, UserMixin):
password = StringField(required=True)
use... |
c20c828d0a8b04960750eb2e14c121d106ce5cba1ce0c9b6af0147b13de90224 | Python | 2,343 | 68 | """
A class to represent a cluster of points
"""
import numpy as np
from . import metrics
## TODO: remove class point, use just list or tuple
class Point:
def __init__(self, coords,ref=None):
self.n = len(coords)
self.pos = coords
def __repr__(self):
return str( self.pos)
class Cl... |
c456f795e4cf8cacf0033e1862d6625fead16653b8de4624dd24abb1a83aed4a | Python | 2,343 | 59 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""
.. _exa-two-stage:
Two-stage test
==============
.. currentmodule:: eelbrain
When trials are associated with continuous predictor variables, averaging is
often a poor solution that loses part of the data. In such cases, a two-stage
design can be employed t... |
a73aad5f3b3da0357c21bad433aadc733969c487d47351f85db61aa31a32b061 | Python | 2,344 | 92 | import random
import numpy as np
import skimage.color as sc
import torch
def get_patch(*args, patch_size=96, scale=2, multi=False, input_large=False):
ih, iw = args[0].shape[:2]
if not input_large:
p = scale if multi else 1
tp = p * patch_size
ip = tp // scale
else:
tp = ... |
724e4d32f38f1fdec23307fd39110737b0fafb9dfcb4e381a7c63090392b5274 | Python | 2,345 | 55 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH
def build_net(ds_kwargs={}, return_metamer_layers=False):
# List of keys in the `all_outputs` dictionary... |
4783a327a2541be931689d0875f31ce5f6550b374126f294dedf9f8379b9e2d0 | Python | 2,346 | 88 | """
metadata_params.py
Modules for metadata params
for loader classes.
"""
import numpy as np
###################################################################################################
###################################################################################################
def _fileinfo(expIDs... |
3ccfa994bf5f38e6e93cf134c12273f2e62836db80079d6a886590d069c005d3 | Python | 2,347 | 73 | import os
import subprocess
def get_tag():
result = subprocess.run(["git", "describe", "--abbrev=0", "--tags"], stdout=subprocess.PIPE)
return str(result.stdout.decode("utf-8")).strip()
def _get_bool(key, default_value):
if key in os.environ:
value = os.environ[key]
if value == 'True' or ... |
f69e5037046d0376d119484e0421e0ef37bb675ec4607f04075fb0f27d92f157 | Python | 2,347 | 122 | # ruff: noqa: E402
"""
`plotly.express` is a terse, consistent, high-level wrapper around `plotly.graph_objects`
for rapid data exploration and figure generation. Learn more at https://plotly.com/python/plotly-express/
"""
from plotly import optional_imports
np = optional_imports.get_module("numpy")
if np is None:
... |
56bf291a8d5c73cab1ac7c49c313197c79fedcda36e1191a3c3e5700054381c7 | Python | 2,348 | 59 | import unittest
from modular_splicing.models.modules.sparsity.spatially_sparse_across_channels_drop_motifs import (
SpatiallySparseAcrossChannelsDropMotifs,
)
class SparseDropMotifsTest(unittest.TestCase):
def testInitialDoesntDrop(self):
sparse = SpatiallySparseAcrossChannelsDropMotifs(
... |
b71caa0e008fd70c352c151894e2daa08bce6fd95b31a87e52d4471a9263c93e | Python | 2,348 | 52 | import numpy as np
import math
import pdb
## ------------------------------------------------------
##-- general check
def general_check(swc_matrix, soma_rows, tree_rows, check_list_df):
#-- check if they are 7 field columns
if (len(swc_matrix.columns)!=7):
check_list_df.loc[0].Value = True
c... |
db35a9900680b2e981151004eeeff27167bb929fb5ff0d333a2627f6f4d7ce06 | Python | 2,348 | 62 | import keras
from keras import layers
def get_model():
input_l = keras.Input((40, 40, 40, 1), name="Les_Input") # Depend on the cropped lesion shape (could be different)
x = layers.Conv3D(filters=32, kernel_size=3, activation="relu")(input_l)
x = layers.MaxPool3D(pool_size=2)(x)
x = layers.... |
0081daa13f28f1a484629587d7a6f302f9ca5bebd314655682fb8b458891f0dc | Python | 2,349 | 71 | import warnings
import numpy as np
from numpy.random import default_rng
import pymc as pm
import arviz as az
import time
warnings.simplefilter("ignore")
def synthetic_data_random(n_samples=100):
rng = default_rng(seed=0)
x1 = rng.standard_normal((n_samples, 1)) + 3
x2 = rng.standard_normal((n_samples, 1)... |
578e906d37d6dbc63923f10a2bb272a3ec5a666e4ec007dec3c7b0967318ec96 | Python | 2,349 | 77 | import pytest
from celery.app.registry import _unpickle_task, _unpickle_task_v2
from celery.exceptions import InvalidTaskError
def returns():
return 1
@pytest.mark.usefixtures('depends_on_current_app')
class test_unpickle_task:
def test_unpickle_v1(self, app):
app.tasks['txfoo'] = 'bar'
as... |
b4a9049ae00b869113e0f2da49b4d0376f33ca9d282c0e51f1115366eb5d2f96 | Python | 2,349 | 61 | #!/usr/bin/python
import sys
import os
import re
import pandas as pd
import numpy as np
import math
import json
from scipy.cluster.hierarchy import linkage, leaves_list
##### Return index of a1 which exists in a2 #####
def ArrayIn(a1, a2):
results = np.where(np.in1d(a1, a2))[0]
return results
def ArrayNotIn(a1, a2)... |
b6c4f0c3afc1e40ce11c0b6457d527318d60a756a2dcb6a942a2451143b85f35 | Python | 2,349 | 76 | # SOURCE: vendored from changwn/scFEA @ 4c1fb76d52f07bafad84ce7686ad7c3acfcf0126
# src/ClassFlux.py
#
# scFEA ("single-cell Flux Estimation Analysis", Alghamdi et al. 2021) predicts, per
# metabolic module, a flux value from that module's input gene expression via a small
# per-module MLP (Linear -> Tanhshrink -> Lin... |
d73775a6e944da3538802c4e4c9c51ab8eb06753a13d191927e494e98f83258f | Python | 2,349 | 70 | """Nearest Neighbour Memory Bank Module"""
# Copyright (c) 2021. Lightly AG and its affiliates.
# All Rights Reserved
from typing import Sequence, Union
import torch
from torch import Tensor
from lightly.models.modules.memory_bank import MemoryBankModule
class NNMemoryBankModule(MemoryBankModule):
"""Nearest ... |
3d721842bceb15307870127892d696956dd78b8bf0a066b47c072cef0150d2a3 | Python | 2,351 | 89 | """Tests for specparam.results.results."""
from specparam.results.results import *
###################################################################################################
###################################################################################################
## 1D results object
def test_res... |
6d772f03af7264d7af631a6cc82d02afdee93eb9e07674f3c0faa490e8527e6a | Python | 2,351 | 65 | # download data from https://ftp.ncbi.nlm.nih.gov/pub/litarch/29/31/
# wget https://ftp.ncbi.nlm.nih.gov/pub/litarch/29/31/livertox_NBK547852.tar.gz
# extract
# tar -xzf livertox_NBK547852.tar.gz
# change varaible to correct folder path e.g. "./livertox_NBK547852/"
livertox_folder = "./livertox_NBK547852/"
# we will... |
6e10415b90dc5260dc468785340bfc935502e9ec8be28eb7c93e55dfc47231fe | Python | 2,352 | 63 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... |
8ef29c81c2e7f754e88e23ffe1c24dc7b001e2eb361d92864f98122ab826090d | Python | 2,352 | 78 | import numbers
import pathlib
import numpy as np
from ..util import hashfile
# Naming conventions for formats:
# fmt_IMAGING-MODALITY_SPECIFIC_SOFTWARE.py
# IMAGING-MODALITY examples:
# - bf: Bright-Field Microscopy
# - bm: Brillouin Microscopy
# - fl: Fluorescence Microscopy
from .fmt_fl_zeiss import load_czi
from... |
db7c911bdfbece1c6ae2a861674cde0bfdc40af853134ff50293a26f4cdad7df | Python | 2,353 | 69 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def swish(x):
return x * x.sigmoid()
class MAB(nn.Module):
def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False):
super(MAB, self).__init__()
self.dim_V = dim_V
self.num_heads = num_heads
se... |
851b51a929d725fca5f195f11ef693b4ba3fe59006bfe0cf180fb200c3c6093a | Python | 2,354 | 53 | """SSD training target generator."""
from __future__ import absolute_import
from mxnet import nd
from mxnet.gluon import Block
from ...nn.matcher import CompositeMatcher, BipartiteMatcher, MaximumMatcher
from ...nn.sampler import OHEMSampler, NaiveSampler
from ...nn.coder import MultiClassEncoder, NormalizedBoxCenterE... |
b58163a44cdb8885b623d60a5f83df1fef3a856b04919261becf3bb9613ffc2a | Python | 2,354 | 65 | from lightly.transforms.moco_transform import MoCoV2Transform
class DenseCLTransform(MoCoV2Transform):
"""Implements the transformations for DenseCL [0].
Identical to MoCoV2Transform.
Input to this transform:
PIL Image or Tensor.
Output of this transform:
List of Tensor of length 2.... |
41c5db2d46fac071930f627494942ec076daf594800ad2f2017b9ea77035dbcc | Python | 2,355 | 55 | import time
from uuid import uuid4
from codecarbon.output_methods.emissions_data import EmissionsData, TaskEmissionsData
class Task:
"""
A task, used to segregate electrical consumption when executing a treatment.
"""
is_active: bool
emissions_data: EmissionsData
def __init__(self, task_nam... |
f8f618cabfa38e1f858f1b8fbb5fcc78aa8d07571783e7a38ac10c0766a4efb2 | Python | 2,355 | 76 | import json
import os
import nfp
import pytest
from nfp.frameworks import tf
from nfp.preprocessing.crystal_preprocessor import PymatgenPreprocessor
dir_path = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture(scope="module")
def smiles_inputs():
preprocessor = nfp.preprocessing.mol_preprocessor.Smile... |
51e55ae2dc3d499f318a523b459133796142b728a67b3e78d1e44d6c2a891964 | Python | 2,356 | 84 | """Tests for pyriemann.geometry._backend module."""
import numpy as np
from conftest import to_backend, to_numpy
from pyriemann.geometry._backend import (
as_numpy,
from_numpy,
diag_indices,
hann_window,
nanmean,
tril_indices,
triu_indices,
get_namespace,
xpd,
)
def test_as_numpy... |
98769b529cc559145f96df6d81be87836130e626a596215f2cd69f8999457b53 | Python | 2,357 | 86 | from unittest.mock import Mock
import pytest
from celery.utils import debug
def test_on_blocking(patching):
getframeinfo = patching('inspect.getframeinfo')
frame = Mock(name='frame')
with pytest.raises(RuntimeError):
debug._on_blocking(1, frame)
getframeinfo.assert_called_with(frame)
d... |
1687b1210dc19b2649e7778fa32ea5e69e376bc615f09a8b5a33e9a5234b5a79 | Python | 2,359 | 66 | from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline
from pmsurv.models.weibull_linear import WeibullModelLinear
from skopt.space import Real, Categorical, Integer
import utils
import arviz as az
def preprocess_data(dataset, config):
X = dataset[config['features']]
y = datase... |
c1763d2c4fed6704b4c1336cc148a121be9fe4d03860e2e8fcdf936a445dd985 | Python | 2,359 | 78 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
2de5611cb36832dd322a51858ab5957667ce64777981f789eb670796452fe843 | Python | 2,360 | 83 | """Configuration file for the Sphinx documentation builder."""
import inspect
import os
import subprocess
import sys
import gradient_accumulator
# Project information
url = "https://github.com/andreped/GradientAccumulator"
# General configuration
master_doc = 'index'
# Sphinx extension modules
extensions = [
... |
33f4219278f7dae0fe4704da8be1130ca8c49a446768335a1e1dd8e78980682d | Python | 2,360 | 54 | """CenterNet Demo script."""
import os
import argparse
import mxnet as mx
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.data.transforms import presets
from matplotlib import pyplot as plt
def parse_args():
parser = argparse.ArgumentParser(description='Test with CenterNet networks.')
parse... |
a0005d9375929bdc4a0ab06620607c4fa05dfcfaa3f12be4a16d0249d2dfaf6a | Python | 2,360 | 70 | from matplotlib import pyplot as plt
import numpy as np
def get_windows_around_sites(ms, ys, mcl):
categorized = {1: [], 2: []}
for m, y in zip(ms, ys):
dcl = m.shape[0] - y.shape[0]
assert mcl - dcl >= 0
delta = (mcl - dcl) // 2
y = y[delta : y.shape[0] - delta]
for y_... |
1066f55ed7f98438e8a634b35776ef2d980725062722a4db5ddcfe07c161a11b | Python | 2,361 | 82 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import torch
import torchvisi... |
43b5e5deb08e4a1478b6e871c399ee8dff21f3f2e8fd5fceed746ba6b7d2db33 | Python | 2,361 | 98 | from __future__ import annotations
from typing import Any
import hvplot.pandas
import numpy as np
import pandas as pd
import panel as pn
from panel.template import DarkTheme
import larvaworld.lib.model as model
import larvaworld.lib.param
__all__: list[str] = [
"module_inspector_app",
]
def module_tester(M, t... |
f74958bd66f326c674830d5a5e2d54db5d12e7dc130687436e1948fb396ddd13 | Python | 2,361 | 94 | import tensorflow as tf
# @tf.function
def lif(
x, tau_rc=0.02, tau_ref=0.004, v_th=1., gamma=0.01, validity_threshold=-20., js_threshold=30.
):
js = x / gamma
j_valid = js > validity_threshold
# splitting tf.where in two steps to avoid gradient nans
safe_js_z = tf.where(
js < js_threshol... |
fe800139df3f5b69d8c49ed1d645852ba405e0c6c0309315229f6758aa16e42f | Python | 2,361 | 83 | """remove_teams
Revision ID: 7ace119b161f
Revises: 3f64cdda4d67
Create Date: 2024-06-22 12:30:59.138189
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import UUID
# revision identifiers, used by Alembic.
revision = "7ace119b161f"
down_revision = "3f64cdda4d67"
branch_labels =... |
472b23114694650bcf12120abf5239f2cd8778d78f246aa92d9692ad72d6865b | Python | 2,362 | 67 | from typing import Optional
import requests
from carbontracker import exceptions
from carbontracker.emissions.intensity.fetcher import IntensityFetch, IntensityFetcher
API_URL = "https://api.electricitymaps.com/v3/carbon-intensity/latest"
class ElectricityMap(IntensityFetcher):
id = "electricitymaps"
def _... |
73930dbdc8ef664fb6c4cf274183545df343783852dda136ad1d1ffa725b1a29 | Python | 2,362 | 63 | import numpy as np
import prob2020.python.mutation_context as mc
import prob2020.python.utils as utils
from ..cython import cutils
def annotate_maf(coding_pos, somatic_base, gene_seq):
# make sure numpy array
coding_pos = np.array(coding_pos)
# info about gene
gene_name = gene_seq.bed.gene_name
st... |
9437fbf4599d66778387725d9fea6f0486ede8e2971eb2c27d50e306d2b71f6e | Python | 2,362 | 93 | from pathlib import Path
import numpy as np
from .. import core as nap
#
EXPECTED_ENTRIES = {
"TsGroup": {"t", "start", "end", "index"},
"TsdFrame": {"t", "d", "start", "end", "columns"},
"TsdTensor": {"t", "d", "start", "end"},
"Tsd": {"t", "d", "start", "end"},
"Ts": {"t", "start", "end"},
... |
235a71fb1e7ed7d3be15c0909b50071df541e8fa7e6dabb06d9f82d5fc462727 | Python | 2,363 | 74 | """Message Signing Serializer."""
from kombu.serialization import disable_insecure_serializers as _disable_insecure_serializers
from kombu.serialization import registry
from celery.exceptions import ImproperlyConfigured
from .serialization import register_auth # : need cryptography first
CRYPTOGRAPHY_NOT_INSTALLED ... |
dcd0b3e6c7cb03d593b1a85a9735eaef843657b3c2c5389fb378859dd23b9309 | Python | 2,363 | 81 | from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, List, Literal, Optional, TypeVar, Union
import numpy as np
if TYPE_CHECKING:
import polars as pl
PathType = Union[str, Path]
ListPathType = Union[List[str], List[Path]]
T = TypeVar("T")
DTYPE = TypeVar("DTYPE", bound=n... |
fae7e72d4fc9fd5592d30c6bde58cb2c5d7690fcb1e40dbcd7f9ead53f665d17 | Python | 2,363 | 91 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
babbdf0749b058a3c564df14e3b4d20d96bb3b58b1f0882371bbbf0ac8f25011 | Python | 2,364 | 64 | """Tests for specparam.utils.properties."""
import numpy as np
from specparam.utils.properties import *
###################################################################################################
###################################################################################################
def test_com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.