sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
a74d53a032361256d763cc46de91647d5beba224f11d79f635a885e87c98903b
Python
2,552
77
from __future__ import annotations import logging from typing import Any import bream4 from bream4.device_interfaces.devices.base_device import BaseDeviceInterface DEFAULT: dict[str, str] = {} def reset_context_tag_information(device: BaseDeviceInterface) -> None: """ Resets the context tags set in minknow...
6a08e7506b31bc1d563b8d67507ce0144a45e8c917010b27413896e0edc28b4a
Python
2,553
75
import tensorflow as tf from .layers import AccumBatchNormalization def replace_batchnorm_layers(model, accum_steps, position="replace"): # Auxiliary dictionary to describe the network graph network_dict = {"input_layers_of": {}, "new_output_tensor_of": {}} # Set the input layers of each layer for l...
72253a59d80b2a56da7e20e118100e34d2f394af66d4e0d2b648236fde8f2569
Python
2,553
84
"""Default predicate decision semantics for fastlog.""" from __future__ import annotations import pytest import torch from torch import nn import torchlens as tl from torchlens.fastlog import CaptureSpec, RecordingConfigError class DefaultsModel(nn.Module): """Small model for default-decision tests.""" de...
cfb1276b01bf209d27ffeeb1451196d48324b33fb6da904104bbac3d489e3a55
Python
2,553
70
""" core.ranknorm — Inverse-normal quantile for the rank-norm transform. The rank-norm pipeline maps each subject's feature value through the empirical CDF of the cohort's HC subjects, then through Φ⁻¹ (the inverse of the standard normal CDF). This module provides the Φ⁻¹ implementation used by ``proper_cv.apply_rank_...
111d05c7270f99cbe46a8c9ed4cc5cdf5bd1b525e17ffd0d34a8ecacdabdf364
Python
2,554
71
############################ # it is more efficient to import this module that use it an executable # FCStd format bearing is too complicated to select (sometime only final visiable is needed) and export import sys import os.path from detectFreeCAD import append_freecad_mod_path append_freecad_mod_path() t...
1db0464ffa400e69bb1ef3195516dfa409a8989b091e9a1b77366d397d8a6647
Python
2,554
77
""" Helpers for various likelihood-based losses. These are ported from the original Ho et al. diffusion models codebase: https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py """ import numpy as np import torch as th def normal_kl(mean1, logvar1, mean2, logvar...
a910074e6634770c5256f18bb94f88e49d0b476c178deafff9775d6d7b129bab
Python
2,554
82
# make barcode dictionaries import os import subprocess import sys import pandas as pd from collections import defaultdict import gzip from numpy import unique import numpy as np import pickle #import HTSeq #import pysam #PATH = './' PATH = os.path.dirname(os.path.abspath(__file__)) HOME = os.path.expanduser('~') ...
558b295318e812b7f811fc75e3834d3635997354cbe1caf47ac56c6da7c58cee
Python
2,555
100
from __future__ import annotations from dataclasses import dataclass from larvaworld.portal.landing_registry import ITEMS, LANES, QUICK_START_MODES from larvaworld.portal.registry_logic import compute_badges, validate_registry from larvaworld.portal.registry_types import LandingItem, QuickStartModeSpec @dataclass(f...
fa7e6c5e261d1c1c0cc99e3cbbc0a2655a904372c571b0fd2dc0f56c05c3adf6
Python
2,555
89
from typing import Dict, List class Parameters: def __init__( self, kfolds: int = 3, batch_size: int = 64, epochs: int = 5, decay: float = 1e-5, learning_rate: float = 0.0005, atom_features: int = 32, bond_features: int = 32, mol_features: in...
5591d5798b0f176346dcd727c16161f14f0506c394abdb07d91159ed32fe96e7
Python
2,556
74
# MIT License # Copyright (c) 2018 Adrian Wolny (https://github.com/wolny/pytorch-3dunet) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
6b04138e54edd7affc47e401215b847bcbe0faf1aab99d3fe0577f64d6c184f1
Python
2,556
72
import torch.nn as nn import torch.nn.functional as F from brainbox.models import BBModel class LayerModel(BBModel): def __init__(self, n_in, n_out, rf_len, rf_size, stride, recurrent=False): super().__init__() self._n_in = n_in self._n_out = n_out self._rf_len = rf_len se...
d268acd261d6e41cc092a12807b5e51e2a2b4b15711934fdb864ddb53d3861be
Python
2,556
68
''' TNS class : Tree ''' import copy from tns.generate.tree import TreeGrower from tns.astrocyte.section import SectionSpatialGrower from tns.astrocyte.space_colonization import SpaceColonization from tns.astrocyte.space_colonization import SpaceColonizationTarget GROWTH_ALGORITHMS = {'tmd_space_colonization': Spa...
db2c2656d0d18c1176f0a8491fbfa04fbb02bf3e7ded163064ca3592e4a83fbf
Python
2,556
83
# --- THIS FILE IS AUTO-GENERATED --- # Modifications will be overwitten the next time code generation run. from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Projection(_BaseLayoutHierarchyType): _parent_path_str = "layout.scene.came...
27ec4a20a9ae69b0524dffc75e5016abd59c85ce8cb0f3f895ddde81b8ec2c55
Python
2,557
80
#!/usr/bin/env python '''Reevaluates *.caffemodel models in specified directory. Return same result as runline. Assume directory was created with do1request/runline.''' import sys,os def get_script_path(): return os.path.dirname(os.path.realpath(sys.argv[0])) sys.path.append(get_script_path()+'/..') #train ...
435bce7a831bd0bb8a53adddc0e3b0c3f7bbe9b12b439df9e2535a0bc4300899
Python
2,557
65
from matplotlib import pyplot as plt import pickle as pickle def plot(i, strTitle, strExperiment): plt.figure() plt.title(strTitle + ' ' + strExperiment) linList = [] lgl = [] for ip in range(pairwiseMetrics.shape[1]): if ip == pairwiseMetrics.shape[1]-1: leg = 'Oscope' ...
717af1fc842500f1459f60f6272c5835104bff600c51b4c3461f8041ce9ff8dc
Python
2,557
84
from .model_zoo import encode, Model from typing import Optional, Union from anndata import AnnData import numpy as np from .._compat import Literal from PIL import Image import pandas as pd from pathlib import Path # Test progress bar from tqdm import tqdm _CNN_BASE = Literal["resnet50", "vgg16", "inception_v3", "xc...
a72e75055c48a7b87e2910050132587b521c1ff8387fe67234a4791ee558bf6e
Python
2,557
42
import numpy as np import pandas as pd import sys import scipy import os import pydot import pydotplus import random import pickle #for POPname in ["ASW"]: for POPname in ["CLM","MXL","PEL","PUR","ACB","ASW"]: with open("/rds/general/user/amassand/home/SLIM_models/MODELS/pops/lengths_counts_rfmix_maxanc_"+str(POP...
c1597268d6e8313b8f68171b7bc5b6cadedc0aafa4f318e4907b3ab44c6f79c7
Python
2,557
57
"""1. Export trained GluonCV network to JSON ============================================ It is awesome if you are enjoy using GluonCV in Python for training and testing. At some point, you might ask: "Is it possible to deploy the existing models to somewhere out of Python environments?" The answer is "Absolutely!", ...
af763a89d3e9eb1d36437ec18686f56325bbfdad43417a2342245093c07bddae
Python
2,558
75
# coding=utf-8 # Copyright 2022 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...
f33b4e142c2209e5baedd7bee5c31fc1f753b2b2ce8377fd2e23b8c4712dab02
Python
2,559
88
import torch import pandas as pd from tqdm import tqdm import sys from pathlib import Path import numpy as np from collections import Counter sys.path.append("models_architectures/") from wrapper_prot_bert_BFD import WrapperProtBertBFD def get_ec_weight(path_df_train, class_vocab): df = pd.read_json(path_df_trai...
bc0cced49da7703352e18538b33ffcaa64b7b52f94b7d85999eebb61530886d0
Python
2,560
79
"""Benchmark core pynapple operations touched by the speedups branch. Run on the PR branch and on `dev`/`main` to compare: python benchmarks/benchmark_core_ops.py Times object construction, `restrict` (one and many epochs), `get`, and `count`, at a few data sizes. Numba is warmed up first so steady-state is meas...
c24ad00cc59980940898284175d5b8b2e1099f51c5cc128430ac91b46bd16137
Python
2,560
88
#TimesVector # #Created by Inuk Jung on 2016-08-3. #Copyright (c) 2016 Inuk Jung. All rights reserved. # #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at you...
c454e74f7bb6045b9cfe831858a87af4d0cd7569024646324bd858d6b9357fdf
Python
2,560
83
from os import PathLike import numpy as np from anndata import AnnData def parsing( adata: AnnData, coordinates_file: int | str | bytes | PathLike[str] | PathLike[bytes], copy: bool = True, ) -> AnnData | None: """\ Parsing the old spaital transcriptomics data Parameters ---------- a...
d3c8b0b99288923fe62c4fd2a06fdd127f1368a276f2a3f1e1c929f54545e58a
Python
2,560
62
"""The pooled `turn` epochs built by the turn annotation. `turn` is a declared epoch type (see `DatasetConfig.h5_kdic`) and the chunk the per-turn parameters are tracked in, but `turn_annotation` used to build only the left and the right epochs. Every analysis reaching for a per-turn quantity - the `patch` graphgroup ...
e73597a2190e767e2dd79e7214562f29344626081cbc75a602d4a8dd5d30ec3e
Python
2,560
83
#!/usr/bin/env python3 import sys import glob import os import json import subprocess def substitute_line(lines, starts_with, replacement): for k, line in enumerate(lines): if line.startswith(starts_with): lines[k] = replacement break def ensure_directory_exists(filename=None, di...
ed83dd770fe25644c8ce2119a8352e20274322f32e3cb36fa480cfdea610af9a
Python
2,561
74
import sys import os import argparse import joblib import pandas as pd from tqdm import tqdm from pmsurv.models.exponential_model import ExponentialModel from pmsurv.models.weibull_linear import WeibullModelLinear from pmsurv.models.weibull_nn import WeibullModelNN def parse_args(): parser = argparse.ArgumentPars...
b79b67ec3f52e7f708f3840c4129eb65de626028b693cb65324a88133ac634ec
Python
2,562
67
import unittest from parameterized import parameterized import numpy as np from experiments.msp import starting_point_for_different_number_motifs from modular_splicing.utils.entropy_calculations import hbern, density_for_same_entropy class TestDensityForSameEntropy(unittest.TestCase): def verify_inverse(self, n...
95da14943e6de1a1712629c39917e322c92691cc766ab6d87d7152826903f698
Python
2,563
68
# this file creates a TCR appearance dictionary # with the key being a TCR in the format of (CDR3, v_allele) # and the value being a set of individuals that this TCR appears in # from the data files of 666 individuals that DeWitt_2018 used # only consider those with frame_type == 'In' import os import pickle import n...
e4e3b890845c5f908a0afed69d5edb46f6156bce59422d42d69e849b3145f7b6
Python
2,563
92
""" Running this script generates a learning rate plot. The data loaded is be specified by a command line argument. """ import argparse import numpy as np import matplotlib.pyplot as plt def style_plot(ax: plt.Axes, num_it: int) -> plt.Axes: """ Generate style for Learning Rate plots. :param ax: Drawing ...
b6015b09d4ecc55ce9c7403c98c112bf7e834a2398ae4696305c105fe963d020
Python
2,564
68
# -*- coding: utf-8 -*- """ @author: Dylan Stewart and Sergio Marconi updated: 05/07/2020 input variables: data_folder - string save_folder - string output: par - dictionary to use these parameters: from parameters import evaluation_parameters par = evaluation_...
2f609bfaa226542c46285fedff6ead2fc980b4d12f5a1733a9a2908cf79ab689
Python
2,565
63
""" Integration test for memory leak issue #4832. Reproduces the scenario of a long-running monitor (e.g. ``celery events`` or Flower) consuming real events off the broker: child tasks whose parent is never observed (because it was scheduled with an ETA/countdown and its own event hasn't arrived yet, or because it was...
814048494d40c34f474b51a923af14cabcb342068371b1eb02fc202fe1c662e0
Python
2,565
83
""" Author: Derek van Tilborg -- TU/e -- 23-05-2022 A collection of classical machine learning algorithms -MLmodel: parent class used by all machine learning algorithms -RF: Random Forest Regressor -GBM: Gradient Boosting Regressor -SVM: Support Vector Regressor ...
953a29b4fa8570b854cdd2e10d5327393e100cc38872b5516b54dd6c33338299
Python
2,565
83
#!/usr/bin/env python3 """This script is an adaptation of the original file "example_4_b.py" created by Roman Martin.""" from GNNSubNet import GNNSubNet as gnn import ensemble_gnn as egnn import copy import random import time from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import accuracy_s...
c04c07d48d1779ec5f92a8eb9b5238615d7f098a1c24ca747dc98c92cbcd0edf
Python
2,565
61
import cv2 import torch # noqa from .back_prop import GaussianBlurPath, attribution_objective, Path_gradient, saliency_map_PG from .utils import cv2_to_pil, pil_to_cv2, gini, vis_saliency, vis_saliency_kde, \ click_select_position, grad_abs_norm, grad_norm, prepare_images, make_pil_grid, blend_input, attr_grad, \...
dc2dd5ec311ee2acf7d5d4fcbd601a2bce3d98739d779fc25be02957cc01a3ed
Python
2,565
64
import numpy as np import time from PCAfold import preprocess from PCAfold import analysis angle_list = [i for i in range(0,180)] n_points = 2000 random_seed = 100 np.random.seed(seed=10) mean = [0,0] covariance = [[2.5, 0.52], [0.52, 0.2]] x_noise, y_noise = np.random.multivariate_normal(mean, covariance, n_points)....
f8487bd1c5a20688dd62ab9f2f490e2247598ccc6f4646f2704b08ea7ee27c87
Python
2,565
85
"""Helper functions for I/O""" import os from os.path import join as opj import h5py import numpy as np from scripts.utils.constants import MRI_IMG_DIR, DWMRI_IMG_DIR, MRI_ORG_LOC_GT_DIR, DWMRI_ORG_LOC_GT_DIR, MRI_CYST_LOC_GT_DIR, MRI_CYST_LOC_GT_DIR_ALL45 def get_orig_imgs(kind, seq=None): """Get MRI / DTI imag...
9880129b0c4f268ca4a12ead21cc4718f69e56d23f80f4b6b99f3ed3a4b4b01f
Python
2,567
69
""" Loads and handles the results_display widget. SimplyFire - Customizable analysis of electrophysiology data Copyright (C) 2022 Megumi Mori This program comes with ABSOLUTELY NO WARRANTY This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publ...
c5ebbf91594529e4939507d98001e0291eff6c1f8c251699815e95c6bec9dc62
Python
2,567
93
import argparse import math import os import numpy as np from tqdm import tqdm from PIL import Image import mxnet as mx import mxnet.ndarray as nd from model import StyledGenerator # pylint: disable-all def get_mean_style(generator, device): mean_style = None for i in range(10): style = generator.me...
a4b6a6bef384b5501369c6b3720999a133c1a78d2ad5bc9f1b77043b02d9bacc
Python
2,568
77
import argparse import json import os import warnings # Make sure, that `MKL_NUM_THREADS` is set to 1, to ensure reproducibility: # https://forum.image.sc/t/reproducibility-how-we-spent-years-building-containers-and-then-mkl-decided-to-screw-our-results/109599 if str(os.environ['MKL_NUM_THREADS']) != '1': warnings...
bb181f6611aab953573fabb5e6369ff5e58342f4310cfaa02ba4ae174f3882d1
Python
2,568
91
# 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 app...
f5b7353a222442f27afa587f0c361491bfc348b2fe584ede2816e5f7b1e7b02a
Python
2,568
67
import attr @attr.s class AdaptiveSparsityThresholdManager: """ Manages the sparsity threshold of a model. The threshold is decreased by a fixed amount every epoch, but never below the minimal threshold The threshold is increased to the accuracy of the model if the accuracy is higher than the curren...
2dd406fa96fc3e7cdaa66049032709591228286dfe875035788926af3cae114b
Python
2,569
67
"""F11 admission pinning on named real models (collapse memo item 15). The U-gate makes admission MODE-STABLE: train-mode capture inflates raw op count 12-40% (the round-1 "ceiling drift" measurement bug), but U is the rendered universe, so a model admitted in eval mode stays admitted in train mode. Pinned on named to...
823121dd9b39b375aad04d4ce983269991db4014e9ac150760ba3f3be417854b
Python
2,569
73
"""Corpus fixture integrity + licensing gates (memo B9; lane F19). The vendored fast path must stay exactly what its manifest records: every image byte-hashed, every license unambiguous (CC0 / public domain), the fixture builder deterministic, and the COCO precision path pinned as a download-on-demand manifest (URL + ...
ffadeac2f3b0bbf9de5df790f1c792f605d07f7b6e794609c980ea6dfd234b28
Python
2,569
86
#!/usr/bin/python import os import sys import re import pandas as pd import numpy as np import ConfigParser import tabix from bisect import bisect_left ##### return unique element in list ##### def unique(a): unique = [] [unique.append(s) for s in a if s not in unique] return unique ##### Return index of a1 which...
4deb239405e764d0e74bced5522391124c235e59785a10390b5eed3cd6fd2621
Python
2,570
70
import os import h5py import numpy as np import scanpy as sc import scvi from scbig.utils import setup_seed, read_data, louvain, calculate_metric for dataset in ['10X_PBMC','mouse_bladder_cell','mouse_ES_cell','human_kidney_counts','Adam','Human_pancreatic_islets','Macosko_mouse_retina']: print('----------------...
beec8b56451db28d5b562e02d7212b3488f1973c1121db8642cbf4924b0f1489
Python
2,571
72
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 21:59:10 2022 This file contains the functions implementing the AI vs learning speed analysis (reported in Fig. 4D and 8C in the manuscript). @author: emilia """ import pickle import torch import pandas as pd import numpy as np import src.learni...
eed2e293c1bbb77294466224cfb700db18a7e3acffcfa400e8db510a6201cc64
Python
2,571
97
from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Iterator import torch import torch.nn as nn class BaseLatent(ABC): """Latent variable module.""" @abstractmethod def reset_states(self) -> None: """Reset the state of the latent variable.""" ...
4c25c5c0a430364dfb4c97b895d51d8a5cd0abc4966070b67eb18125cfb9e532
Python
2,573
85
import numpy as np from anndata import AnnData from scipy.spatial.distance import cdist def local_level( adata: AnnData, use_label: str = "leiden", cluster: int = 9, w: float = 0.5, return_matrix: bool = False, verbose: bool = True, ) -> np.ndarray | None: """\ Perform local sptial tra...
a74b9cbd3601db64d954f693213496c9b0f9a969ac1fc0cfa59cba358e16a73f
Python
2,573
63
""" _pcm.py — shared PCM decode helper for song_recording's capture-layer modules (monitor.py, noise_model.py). pyoperant.interfaces.pyaudio_.PyAudioInterface._open_input_stream() probes sample formats rather than assuming one (see its docstring for why 24-bit in particular can't be assumed for a USB Audio Class devic...
e81978f6b324be56e40882dfeabadf228aeb41675f073051e76cba80dc661ac9
Python
2,573
79
""" Standardize Multi-threading computation. SimplyFire - Customizable analysis of electrophysiology data Copyright (C) 2022 Megumi Mori This program comes with ABSOLUTELY NO WARRANTY This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published...
f79ffecf95ea0e9aae41186788ce5e4b1d603f1f4a2630a4187cf7f43334b359
Python
2,573
80
import os import joblib import yaml from sklearn.feature_selection import SelectKBest from sklearn.pipeline import Pipeline from pmsurv.models.exponential_model import ExponentialModel from pmsurv.models.base import BayesianModel from skopt.space import Real, Categorical, Integer import utils import arviz as az def pr...
058c089d2dc7eae327b9c703015b36800ccea8a7093d51a4ab587e3ae48847a8
Python
2,574
71
import numpy as np import sympy as sp from markov_builder.example_models import construct_kemp_model from scipy.integrate import odeint from . import common from . MarkovModel import MarkovModel class KempModel(MarkovModel): """The model described in https://doi.org/10.1085/jgp.202112923 constructed using Ma...
555abbc31be03e6d84e64c17199a1062836215ae72488a5740728767975de711
Python
2,574
93
""" Stimulus action classes for the ComposedStimulator. Each action encapsulates WHAT stimulus to deliver (hardware command), independent of WHEN to deliver it (trigger logic). Actions build instruction dicts that are passed to the OptoMotor hardware interface. """ from ethoscope.hardware.interfaces.optomotor import ...
55e0db9a6f9dc31bdc407322ccad8ac4b397ddbe00f4d1bdc513012017d0be15
Python
2,575
89
import numpy as np import pytest from Metrics.src.image_quality_estimation import IQS from NLM.src.denoise import ( nlm, nlm_CEST, pad_image, get_comparison_neighborhood, get_small_neighborhood, ) from test_support_function.src.CEST import generate_Z_3D def test_pad_image(): image = np.array(...
f9b39ee570a2a3d6c1031d7200b0a47b6d4a021aa0c5098bd1d1aee538094ad3
Python
2,575
84
import argparse import os import sys import time import pandas as pd from statistics import median sys.path.append(os.getcwd()) from scripts import extract_workflow_connections from scripts import prepare_data from scripts import utils max_path_len = 25 cut_off = "2017-12-31" te_share = 0 def find_wf_statistics(un...
387a429790eff985601bbc556e3fa568597bc6d0a1e0277707fa64207b8e2d99
Python
2,576
98
#!/usr/bin/env python import sys import pysam from collections import Counter from operator import itemgetter import numpy as np # python script.py test.bam hg38.fasta hg38.sizes script, sam_path, fasta_path, size_path, new_bam = sys.argv def get_pileup_database(sam_path, size_path): sam = pysam.AlignmentFile(sam_p...
bea8393485e1f923f6a95de1394954e0e02e68fffec3228490a6f626c2e6a13e
Python
2,576
63
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 """ ...
f7c87f0da5b78fef71022b3b1605a465621422e8094cd962a9ede5d20e5c34ae
Python
2,576
93
from ethoscope.core.roi import ROI __author__ = 'quentin' import numpy as np from ethoscope.utils.description import DescribedObject import logging import traceback class BaseROIBuilder(DescribedObject): def __init__(self): """ Template to design ROIBuilders. Subclasses must implement a ``_roi...
42a536c004710cd392f762dfb69dee6b8943f4a153ce6dde3d592eb7c60d0944
Python
2,577
69
"""inseq bridge against the real inseq package (no sys.modules fakes). The default method must be a name inseq knows, and ``generated_texts`` must reach inseq's own ``generated_texts=`` so the attributed target is the caller's text; the result must equal inseq called directly. """ from __future__ import annotations ...
a8597b42a8e5502f5d351c59fc1ef09a3f08fe3b8a60ef20f7b8f3a93e52d1e2
Python
2,577
77
"""Create the images for the documentation site.""" import shutil import numpy as np import matplotlib.pyplot as plt from specparam import SpectralModel, SpectralGroupModel from specparam.sim.gen import gen_power_spectrum from specparam.plts.utils import check_ax from specparam.plts.spectra import plot_spectrum from...
d4ddaee3871ea96bd9ae44ab2b94931e2684db34c80ae19850e95a6b16f93e1f
Python
2,577
77
import numpy as np from CEST.src import matlab_style_functions def cest_correction( cest_array: np.ndarray, x_calcentires: np.ndarray, x: np.ndarray, x_itp: np.ndarray, mask: np.ndarray, offset_map: np.ndarray, interpolation: str, cest_range: float, ) -> tuple: """ Correct the...
63666da542dd2bdcb33a070346f458d79811e764cb41d1c565eafeddbf1579d2
Python
2,578
80
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Sample MneExperiment. This experiment can be used with a sample dataset that treats different parts of the recording from the MNE sample dataset as different subjects. To produce the data directory for this experiment use (make sure that the directory you spe...
a87a39afb7bb1abb20ecc7eecb302add3d6de7df76601f5c237dbbab7daf9abf
Python
2,578
75
from conftest import requires_matplotlib import numpy as np from pyriemann.stats import PermutationDistance, PermutationModel from pyriemann.spatialfilters import CSP import pytest def test_permutation_badmode(): """Test one way permutation test""" with pytest.raises(ValueError): PermutationDistance(m...
39c50296519b5b0b0192e75f6929cec0c7fec523a1863d1767a5bbbdbdc6e7ce
Python
2,579
61
import torch import numpy as np import sys,os,re from experiments.analysis.utils import grad_simplex_correction def pad_to_max_len(array,max_len): diff = max_len - array.shape[1] zeros = np.zeros((4,diff),dtype=array.dtype) padded = np.concatenate([array,zeros],axis=1) return padded def make_consensu...
756cd9604b6c52e78db7a9d2084a48f1eb600e6f04b874060293d4b059cd02b2
Python
2,579
69
from Bio.PDB import * import math import pandas as pd import numpy as np import warnings # Constants AMINO_ACIDS = ["ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL"] PDBS_LIST_PATH = "PDBs_list.csv" NON_OHE_DATASET_PATH ...
0625c189205ffba79700f18291742bcf82de52801d69d0211204fb8f81427f6d
Python
2,580
70
import torch import numpy as np import pandas as pd from os.path import join from pathlib import Path from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence MAX_SPKR_CNT = 259 class DSet(Dataset): ''' This is the raw WSJ parser ''' def __init__(self, path, split): # Setup ...
d192bf3601cfb53c021a17cc793d504872d2e63e4ab36f20141d13b363445177
Python
2,581
78
from __future__ import annotations from larvaworld.gui_v2.apps.models_environments.environment_builder import ( build_environment_builder_text, build_environment_builder_widget, ) from larvaworld.gui_v2.registry_bridge import GuiEntry, GuiNavigationModel from PySide6.QtWidgets import QWidget def build_group_...
ac0ed9eea214ffd0a6c2c6a916d40e74df6a0a2b3623a95bb7ee5111f64fe0ce
Python
2,582
67
import pandas as pd def describe_data(path_json, path_df_train): # Keep only sequences that have ec present in the train because none of the tested tools can do zero shot predictions df_train = pd.read_json(path_df_train) list_train_class_vocab = list(df_train["ec_number"].unique()) print("path_json:...
f99c5de824c36078d1a88aac8446cde206cbb04f71c375c6eda07cebf996f166
Python
2,583
66
class BiomedisaPredictionParameter(): name: str = "BiomedisaPredictionParameter" path_to_model: str = "" stride_size: int = 32 batch_size_active: bool = False batch_size: int = 12 available_devices: int = 1 x_min: int = None x_max: int = None y_min: int = None y_max: int = None ...
16990c9e2f37d8092125c54ea5f24dd5b683c0b154c6fc202f0a3a1c0a57af62
Python
2,584
99
#!/usr/bin/env python import sys import pysam from collections import Counter from operator import itemgetter import numpy as np # python script.py test.bam hg38.fasta hg38.sizes script, sam_path, fasta_path, size_path, new_bam = sys.argv def get_pileup_database(sam_path, size_path): sam = pysam.AlignmentFile(sam_p...
2e75a372e7a6beb8c266710636e6a49c8cdcbe95fd43af3a8dae3d51d2937768
Python
2,584
70
"""Constructs a semi-weakly supervised ResNeXt-101 32x8 model pre-trained on 1B weakly supervised image dataset and finetuned on ImageNet. `"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_ Weights from https://github.com/facebookresearch/semi-supervised-Ima...
11fa30a304a28b1a75f6d2fcd2252597c6b2d56df2aaaeacf5461c1bd90a7065
Python
2,586
104
"""I/O utilities.""" import os ################################################################################################### ################################################################################################### def create_file_path(file_name, file_path, extension): """Create the full file pat...
63de6400b7c02dc2093f6f8afa2ec182a1133f6c0fa5117f55d1c87a3bf27837
Python
2,586
67
""" Code here relates to the detection and management of cell membrane properties: * holding current (Ih) * access resistance (Ra) * membrane resistance (Rm) * membrane capacitance (Cm) This modules provides two types of membrane capacitance values: ones derived from step protocols and ones derived from ramp p...
6cf94258dfb11ff9fa11e26665c8d08002797c508b167a2080cd8bfefab0566f
Python
2,586
86
""" This script is used to record how to read some supplementary data, which are published in Nature already. """ from typing import List import os import re import numpy as np import pandas as pd # * Download Supplementary Data # You can find the link under the paper website: # https://www.nature.com/articles/s41586...
c0fcee0acffe19ae23fe2ee844d87439f6744398574a974673ff55d11bb4e685
Python
2,586
71
import numpy as np from modular_splicing.gtex_data.pipeline.marginal_psis import ( compute_splice_site_psis, parse_junc, ) def extract_sequence_info(genes, juncs, gene_ensg, denominator_technique="one_step"): """ Extract information about the given gene. Parameters ---------- genes : Fea...
e6f970b0b5109202c9f33c94ed5937562e3abe7956395e32203738160bb23c3b
Python
2,586
67
"""Setup script for specparam.""" import os from setuptools import setup, find_packages # Get the current version number from inside the module with open(os.path.join('specparam', 'version.py')) as version_file: exec(version_file.read()) # Load the long description from the README with open('README.rst') as read...
12238765e9e75b8cc81317cc6cac13001ee450e872cd39589e4e2c891e37ac2b
Python
2,587
78
import logging import threading from abc import ABC, abstractmethod from typing import Any import grpc from bream4.device_interfaces.devices.base_device import BaseDeviceInterface class GrpcStreamer(threading.Thread, ABC): """Implements a streaming thread that can be stopped and will restart with temporary ...
74efbf4675340b024103d45a6d84e9d1fe88f86e5dfa37ee6cd8d474fc7d5e77
Python
2,587
84
import copy from typing import Any import numpy as np import pandas as pd from mirp._images.generic_image import GenericImage from mirp._imagefilters.generic import GenericFilter from mirp._images.transformed_image import TransformedImage from mirp.settings.generic import SettingsClass class SquareTransformedImage(...
8bd1d9271605fb77376c221cd3c2e0eba1997c3ef82cfa9747b0ff22a1c755a7
Python
2,587
80
"""Render a large random graph with rank layout. Usage: python scripts/render_large_graph.py NUM_NODES [OPTIONS] Examples: python scripts/render_large_graph.py 250000 python scripts/render_large_graph.py 1000000 --format png --seed 123 python scripts/render_large_graph.py 50000 --outdir /tmp/graphs ""...
5e771342a25c6665219c93a62089a35574e43d4d208aad9b5bc668a3630da02d
Python
2,588
90
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Oct 07 2019 @author: Nathan de Lara <nathan.delara@polytechnique.org> """ from typing import Union import numpy as np from scipy import sparse from sknetwork.linalg import SVDSolver, LanczosSVD from sknetwork.ranking.base import BaseRanking from sknetwork...
eac8d581e6dad71ea6e24b0e62486cb1a652e5a888f8719a2d491d23ba0380db
Python
2,588
78
import os from datetime import timedelta import hydra import torch from timm.optim import create_optimizer_v2, optimizer_kwargs from timm.scheduler import create_scheduler from torch.distributed import init_process_group from wandb import AlertLevel from data.loader import get_kfold_dataloader3d from initial_setting ...
2aa0dbed40276381490eaeb5dcd639ec320f6964bc73b711f6c8e26d7d3e9af8
Python
2,589
75
from io import BytesIO import base64 from .png import Writer, from_array try: from PIL import Image pil_imported = True except ImportError: pil_imported = False def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"): """Converts a numpy array of uint8 into a base64 png or jpg stri...
b6d18a899b76ff88651a559a6235534f880dd610b8bfd71811f4079b467632cf
Python
2,589
73
from typing import Any from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset class TVTDataModule(LightningDataModule): """Simple DataModule creating train, val, and test dataloaders from given train, val, and test dataset. Example:: from pl_bolts.datamodu...
cde391e675040607cc9894d4218cfcee27602e38d9b1e99ca0e4a5e1d7ea7352
Python
2,589
76
import os import re import shutil import tempfile from typing import Iterator, List, Tuple import numpy as np import pytest import torchvision from lightly.core import train_model_and_embed_images class TestCore: dataset_dir: str @pytest.fixture(autouse=True) def _cleanup(self) -> Iterator[None]: ...
0559b66f7242d756da6873a8e2e246db36d2805011c5c70396403c7200b6c913
Python
2,590
58
import json import pandas as pd from tqdm import tqdm, trange tqdm.pandas() def main(): test = pd.read_csv('./data/csvs/data/test_new_old.csv') old_new = pd.read_csv('./data/csvs/data/test_new_old.csv') old_new = old_new[['Drug2_ID', 'Drug2_SMILES']] with open('./data/jsons/chemprop_similar_drugs_di...
73fdf29793ad058809ecf4febfafcfe3ac43ff9b62956563c07371d1491414db
Python
2,590
63
import numpy as np from mirp._data_import.dicom_file import ImageDicomFile from mirp._data_import.dicom_file_stack import ImageDicomFileStack class ImageDicomFileVolumeStack(ImageDicomFileStack): def __init__( self, image_file_objects: list[ImageDicomFile], **kwargs ): ...
90a5da1e2f17ba9488552b5d0743f0c6571ef815327c19a0eb5487a50d3ad59b
Python
2,590
62
import click import os from subprocess import Popen, PIPE @click.command(help="Build a singularity image from a docker image") @click.option( "--target", default=["docker", "singularity"], help="Build targets", type=click.Choice(["base", "docker", "singularity"]), multiple=True, ) @click.option("-...
a986e597adb9ad350205bb7cd9045e74d7c184c55192dc99c2a6531035af2ced
Python
2,590
73
"""Train 3D U-Net""" import sys import os from os.path import join as opj import yaml from scripts.utils.constants import WORKING_DIR, MRI_ORG_SEG_FILES_3DUNET, MRI_CYST_SEG_FILES_3DUNET # noqa os.chdir(WORKING_DIR) def create_conf_files(kind, create_yml=False): """Create 3D U-Net config files for training. On...
cad978e85a66e4e2629e24f40f2b52990ea5fdfae637d7c137a37d70854bfc1a
Python
2,590
75
from typing import Optional import paddle import paddle.nn as nn class RotaryPositionalEmbeddings(nn.Layer): """ Rotary Positional Embeddings (RoPE) https://arxiv.org/abs/2104.09864 """ def __init__( self, dim: int, max_seq_len: int = 4096, base: int = 10000, ...
d5245076715d23ba1919af8bc1c4b7966f1fe9b283930d507adfa0a5bc68e04e
Python
2,590
61
""" SiamRPN benchmark Code adapted from https://github.com/STVIR/pysot""" from glob import glob import argparse import os from multiprocessing import Pool from tqdm import tqdm from gluoncv.utils.metrics.tracking import OPEBenchmark from gluoncv.data.otb.tracking import OTBTracking as OTBDataset def parse_args(): ...
e50020e10349992a654ef21bd2053fc4afe01a0d256e8fda6021246658fd6b68
Python
2,590
91
import argparse import logging import numpy as np from atomate.common.powerups import add_tags from atomate.qchem.fireworks.core import ForceFW, SinglePointFW from bson.objectid import ObjectId from fireworks import LaunchPad, Workflow from instance_mongodb import instance_mongodb_sei from pymatgen.core import Molecul...
a520f4be0404e8ca300a3381253bffb12e02b7c0d69fb7852560c0ade4d937c5
Python
2,591
85
# --- 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 = "candlestick" _path_str...
f50f1068042a37ac35b18b25c8d5ecf5fed5fb0900437f809dd82483285e0fbd
Python
2,591
96
import logging import argparse from bson.objectid import ObjectId import numpy as np from pymatgen.core import Molecule from atomate.qchem.fireworks.core import SinglePointFW, ForceFW from atomate.common.powerups import add_tags from fireworks import LaunchPad, Workflow from instance_mongodb import instance_mongo...
ff26258494182af4a10b7ed4741718a61d1b7e39d2afa0a29de0cb16ee5addb7
Python
2,592
84
import re import sys from Bio import SeqIO from Bio.Seq import Seq def main(): fasta_file = sys.argv[1] output_file = sys.argv[2] log_file = sys.argv[3] output_handle = open(output_file, "w") log_handle = open(log_file, "w") with open(fasta_file, "r") as fasta_input_handle:...
13efe072a54e62350f886fe2cfd8f66af561d44340355219b7b032758cf27b28
Python
2,595
76
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in April 2019 @author: Nathan de Lara <nathan.delara@polytechnique.org> """ import warnings from typing import Optional, Union import numpy as np def get_values(shape: tuple, values: Union[np.ndarray, list, dict], default_value: float = -1) -> np.ndarray: ...
5c3fd60615c4b9504c8c2b052ca9bc322982ecbf5928a1e34b10d25519ee6192
Python
2,595
117
import os import time import pytest from caper.nb_subproc_thread import NBSubprocThread SH_CONTENTS = """#!/bin/bash echoerr() { echo "$@" 1>&2; } NUM=$1 if [ -z "$NUM" ] then NUM=10 fi echo $NUM # NUM kitties (1 kitty per sec) for i in $(seq 1 $NUM) do echo "hello kitty $i-1. (STDOUT)" sleep 0.25 echoer...
87792752a86c3d215afcaac1dbe3b24bc239d1294924692bed69ff687dfb4172
Python
2,595
92
import random import numpy as np import torch import torchvision.transforms.functional as TF class Compose(object): """ Composes several transforms together. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, rendering_images, bounding_box=None): for...
af2c3060eecbfcf89227defed78969bb2f46b3af629a860d4e7d0847b81b38b9
Python
2,595
86
from typing import Optional, Union from anndata import AnnData from matplotlib import pyplot as plt from pathlib import Path import os import sys import numpy as np def parsing( adata: AnnData, coordinates_file: Union[Path, str], copy: bool = True, ) -> Optional[AnnData]: """\ Parsing the old spa...
e5047827125e0de0e20eb00ecea35d7c82f882cfcfb2c33f7b103ad9bd735e2c
Python
2,595
67
import sys from typing import Any import numpy as np try: from psychopy import visual except ImportError as e: msg = "Psychopy is not installed." raise ImportError(msg) from e from neurogym.core import TrialEnv from neurogym.utils import spaces from neurogym.utils.logging import logger class PsychopyEn...
1743546215aa3b271900acf71cf7e7a8dcd9b21b7f5a204abe46ddc576b59f88
Python
2,596
67
import os import utils import numpy as np def load_lines(filename, header=False): header_line = None lines = [] with utils.reading(filename) as fp: line_count = 0 if header: header_line = fp.readline().rstrip() for line in fp: lines.append(line.rstrip()) ...