sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
159384fabafb203f02b228bf79627f2be1604d305513e1679be50717f1c95699
Python
1,147
42
#import tensorflow as tf import numpy as np import math import random from sklearn import preprocessing seed=1 # set a seed np.random.seed(seed) whole_X=np.random.uniform(0,1,(10000,28*28)) n=whole_X.shape[0] p0=whole_X.shape[1] # the number of original variables random.seed(seed) art=np.array(random.sample(range(p0...
e74e7470694b4055796409bf2a2a0ae0beaa92c99389a683af9ac39eb37f9e50
Python
1,147
40
from pathlib import Path pathFiles = Path('L:/promec/Animesh/Kathleen') fileName='allPeptides.txt' trainList=list(pathFiles.rglob(fileName)) import pandas as pd df=pd.read_table(trainList[0], low_memory=False) df.columns.get_loc("DP Proteins") dfDP=df.loc[:, df.columns.str.startswith('DP')] dfDP=dfDP[dfDP['DP Proteins...
9d4f0fb5bcae765514eded3ffbfac505c39849cd0b69378c873a927bc7f87d3e
Python
1,148
35
import click from .._version import version as steinbock_version from ..classification._cli import classify_cmd_group from ..export._cli import export_cmd_group from ..measurement._cli import measure_cmd_group from ..preprocessing._cli import preprocess_cmd_group from ..segmentation._cli import segment_cmd_group from ...
5f388f1b19636c0c63c5d5e5093f76e270a1d5e4a346cd84570dff0cd769d9e3
Python
1,150
32
# Copyright (c) Facebook, Inc. and its affiliates. import torch from detectron2.modeling import PROPOSAL_GENERATOR_REGISTRY from detectron2.modeling.proposal_generator.rpn import RPN from detectron2.structures import ImageList @PROPOSAL_GENERATOR_REGISTRY.register() class TridentRPN(RPN): """ Trident RPN sub...
5c2101e3fde164a895e54ab6122d4f2ecf8a56edf7554d974d00317bbbe0a9f0
Python
1,153
34
#python pagesDown.py <link> start end import sys link = sys.argv[1] start = sys.argv[2] end = sys.argv[3] import os import time import codecs from selenium import webdriver from selenium.webdriver.common.by import By options = webdriver.ChromeOptions() options.headless = True driver = webdriver.Chrome("/home/animeshs/b...
d0f74c94846f03d19658c01c429260ca18c0d7bd2fcc59dab61c82d8d588acaa
Python
1,153
32
import torch from torch import nn, Tensor import numpy as np class RobustCrossEntropyLoss(nn.CrossEntropyLoss): """ this is just a compatibility layer because my target tensor is float and has an extra dimension input must be logits, not probabilities! """ def forward(self, input: Tensor, target:...
3b1124a413c41db3bcc37b9414c1f84719693cb1b4cb2739716b0d433e3f4e5e
Python
1,157
28
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. def add_deeplab_config(cfg): """ Add config for DeepLab. """ # We retry random cropping until no single category in semantic segmentation GT occupies more # than `SINGLE_CATEGORY_MAX_AREA` part of the crop. cfg.INPUT.CR...
4da8a4fbb4db5bd5a428a596793c0bd685d360ec8b24bd4be7495fda59352e9f
Python
1,157
24
import numpy as np def get_patch_size(final_patch_size, rot_x, rot_y, rot_z, scale_range): if isinstance(rot_x, (tuple, list)): rot_x = max(np.abs(rot_x)) if isinstance(rot_y, (tuple, list)): rot_y = max(np.abs(rot_y)) if isinstance(rot_z, (tuple, list)): rot_z = max(np.abs(rot_z))...
b72060451ea83b8d664fe3f4e02d7378fcf3fa9610cb4fdfb13d33115e9049aa
Python
1,158
50
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ Restraint Geometry classes TODO ---- * Add relevant duecredit entries. """ import abc from pydantic import BaseModel, ConfigDict, field_validator class BaseRestraintGeometry(BaseMode...
0c3e181c1865977a13fc4a169e71338ac8b12bf4a0b9274efe4d3bf3ac5afc55
Python
1,160
32
from typing import List import torch from torch import Tensor, nn from detectron2.modeling.meta_arch.retinanet import RetinaNetHead def apply_sequential(inputs, modules): for mod in modules: if isinstance(mod, (nn.BatchNorm2d, nn.SyncBatchNorm)): # for BN layer, normalize all inputs together ...
11194c99e05bbc88a66615452cc10f189ea2f3d210b61b5221fe46ca021b646d
Python
1,160
30
import torch from torch import Tensor from chemprop.data import BatchMolGraph class _BondMessagePassingMixin: def initialize(self, bmg: BatchMolGraph) -> Tensor: return self.W_i(torch.cat([bmg.V[bmg.edge_index[0]], bmg.E], dim=1)) def message(self, H: Tensor, bmg: BatchMolGraph) -> Tensor: i...
de3689ff8a7459f45631267ac1b8452c18a7a06f27b867a64edb0eafb7819dea
Python
1,161
43
from __future__ import annotations import errno import json from pathlib import Path from typing import TYPE_CHECKING, Any from snakebids.io.yaml import get_yaml_io if TYPE_CHECKING: from _typeshed import StrPath def write_config( config_file: StrPath, data: dict[str, Any], force_overwrite: bool = False ) ...
ecc013f246ffb4d7e8181f7eeec4016c2cb3613c04b53d99d3f30666b9040531
Python
1,161
31
import pytest from typing import Sequence import numpy as np import xarray as xr from hsnn import ops from ._utils import get_data @pytest.mark.parametrize("test_input, expected", get_data('as_spike_events')) def test_as_spike_events(test_input: dict, expected: Sequence): spike_events = ops.as_spike_events(test...
3ef39da7e7b8d7c423aeb6dbc7ba6310a76fc62f3ecec0d146dbbb0b3d4f5f8d
Python
1,162
38
from typing import Protocol, Type, TypedDict class HParamsDict(TypedDict): """A dictionary containing a module's class and it's hyperparameters Using this type should essentially allow for initializing a module via:: module = hparams.pop('cls')(**hparams) """ cls: Type class HasHParams(Pr...
dfbb61196c155e3a1099d30d0b37a764b7065116be673e1b930a95641423e261
Python
1,162
39
from importlib import resources import click import pytest import openfe from openfe import SmallMoleculeComponent from openfecli.parameters.mol import get_molecule def test_get_molecule_smiles(): mol = get_molecule("CC") assert isinstance(mol, SmallMoleculeComponent) assert mol.name == "" assert mo...
f417edc84f571ddfe4652821fe2afa52fdedf3caa398aa97a081ea304c7aabe1
Python
1,166
33
# Python03.py # IJ BAR: https://github.com/tferr/Scripts#scripts #################################################### # 3. Import Jython modules and Java classes #################################################### # Importing a Jython module: import math print "[Line 09]", "Python PI=", math.pi # https://docs.python....
2840c396ea2f2b999a573eeeae6b92ea93c0fd65618d25ea565ceea912114765
Python
1,168
37
import scanpy as sc import pandas as pd import numpy as np import os import sys sys.path.append(".../benchmark_script/evaluation/ARI_LISI/evaluation_LISI_knn.py") from evaluation_LISI_knn import evaluate_LISI_knn input_path = "PATH_TO_INPUT_DIR/samap_LISI_input.h5ad" output_path = "PATH_TO_OUTPUT_DIR/samap_LISI.csv"...
57298102d27dc19a88945399048dba6e07c73d35c0f4cad42c698995c4d2f1ac
Python
1,174
39
import numpy as np from scipy.ndimage import binary_fill_holes from acvl_utils.cropping_and_padding.bounding_boxes import get_bbox_from_mask, bounding_box_to_slice def create_nonzero_mask(data): """ :param data: :return: the mask is True where the data is nonzero """ assert data.ndim in (3, 4), "...
d685dfd334d0f0499694ac8f9d17f906491f89f5a37420408c4125eb0cc56000
Python
1,174
50
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from import_export import resources from import_export.admin import ImportExportModelAdmin from .models import ResultsABX, User # Register your models here. class UserResource(resour...
2816e057fcd12524e5b122354a28b715ad1c82e2f639772b2d02b401e3b9820b
Python
1,175
38
import sys import unittest from pathlib import Path import numpy as np SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" sys.path.insert(0, str(SCRIPTS)) from baseline_models import grid_search_grouped_cv class FoldTargetScalingTests(unittest.TestCase): def test_grid_search_can_fit_target_scaling_with...
a6b9fec7ad4a9044199177e96ce836f2cc71613a98a1965a5a078d4528b8dbd6
Python
1,176
33
# Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import, division, print_function, unicode_literals import unittest import torch from detectron2.layers import batched_nms from detectron2.utils.testing import random_boxes class TestNMS(unittest.TestCase): def _create_tensors(self...
36d475ccca6d1c6d4133db6018ea380d2389c817dbb491a7adf83950041be4e7
Python
1,177
60
from argparse import ArgumentTypeError def pos_int(s): v = int(s) if v <= 0: raise ArgumentTypeError('must be > 0') return v def n0_int(s): v = int(s) if v < 0: raise ArgumentTypeError('must be >= 0') return v def lim_int(llim=float('-inf'), ulim=float('inf')): def f(s)...
a495b88cde124dcd2da637906e134a982d20946712a2252ee44645151f015da9
Python
1,177
34
# Copyright (c) Facebook, Inc. and its affiliates. import importlib.abc import importlib.util from pathlib import Path __all__ = [] _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "proj...
ea733dd367625b8afb930f263ff1a72c26801937288abc134bf33814982ee012
Python
1,178
33
from detectron2.config import LazyCall as L from detectron2.layers import ShapeSpec from detectron2.modeling.poolers import ROIPooler from detectron2.modeling.roi_heads import KRCNNConvDeconvUpsampleHead from .mask_rcnn_fpn import model [model.roi_heads.pop(x) for x in ["mask_in_features", "mask_pooler", "mask_head"]...
982b2f216fffd488994a3858d9cc8d3dadfcd710617d7700f9719d30870f044a
Python
1,179
43
import os import h5py import numpy as np import matplotlib.pylab as plt from python_scripts.laminarfMRI import interpolate_axis0, find_ind base_path = '/Users/Tommy/all/eeg-fMRI/results' filename = 'result_raw_eeg_power.mat' freq_sel = 'gamma' with h5py.File(os.path.join(base_path, filename), 'r') as f: data = ...
44c2dc08ec2de5cf9cfab587fb80078d0b5a4ab45d89836d1340fea1a0f05bf4
Python
1,181
34
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest import torch import detectron2.export.torchscript # apply patch # noqa from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.layers import ShapeSpec from detectron2.modeling.backbone import build_r...
75ef1283b572e61a6918b5d6b799276c560a11652513411e9e431c3c304d15d3
Python
1,181
38
import argparse import os import lpips parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-d0','--dir0', type=str, default='./imgs/ex_dir0') parser.add_argument('-d1','--dir1', type=str, default='./imgs/ex_dir1') parser.add_argument('-o','--out', type=str, def...
0b3223c2cb19eda03a4821f4a92655aa0d9c59652e417074373cd0e05bd1951f
Python
1,182
48
"""Prediction and inference pipelines for molecular property prediction.""" from nfml.predict.uncertainty import ( classification_confidence, ensemble_uncertainty, flag_ood_molecules, tanimoto_nearest_neighbour, ) from nfml.predict.inference import ( graph2mol, sample_vae_latent_space, pred...
b8305c6ede0d5d2e4e144414d13e8e6e0408b7b7254e91ebae13e768a3b1c798
Python
1,183
34
import sys import unittest from pathlib import Path import numpy as np SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" sys.path.insert(0, str(SCRIPTS)) from metrics import evaluate_held_out_pv_predictions class HeldOutMetricTests(unittest.TestCase): def test_held_out_summaries_use_main_weight_and_do...
d232d446ae218fbc728d39e510231be4a82442551ff27a472b2f97f799984dcc
Python
1,185
42
# -*- coding: utf-8 -*- """ Created on Fri Jul 29 19:27:26 2016 @author: Federico Barabas """ import os from tkinter import Tk, filedialog def getFilename(title, types, initialdir=None): root = Tk() root.withdraw() # filename = filedialog.askopenfilename(title=title, filetypes=types, # ...
b762d23c61dec4b152e024c8222b893f36069e7e62d083f4aa97f38b5a6665ee
Python
1,188
37
import pytest import os import shutil import vtk from brainspace.vtk_interface import wrap_vtk from brainspace.mesh import mesh_io as mio def _generate_sphere(): s = vtk.vtkSphereSource() s.Update() return wrap_vtk(s.GetOutput()) @pytest.mark.parametrize('ext', ['pial', 'white', 'orig', 'sphere', 'inflat...
46f78eb59acaf639eadd2893e9cd4a0b2c1efb86c2fe0c95491ea2832c0748c5
Python
1,189
56
from nilearn import plotting import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib matplotlib.use("Agg") dim = ( -0.5 ) # seems to be more reliable, dim=-1 was blacking out some images that had low dynamic range.. fig, (ax1, ax2, ax3) = plt.subplots(3, 1) # original plot (...
e7a62e7e6cab402cf5d1698948761406997272f33005581e68ee7223eb576305
Python
1,191
31
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
674f19a95650d387ca704761c88668b9e6cb68d5de1edac1de7971a53b26caf5
Python
1,192
44
# Generated by Django 4.2 on 2024-11-13 08:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("abx_app", "0005_remove_user_is_first_adjustment_and_more"), ] operations = [ migrations.RenameField( model_name="user", ...
97b29c961bc7d783aef8464a34b66762feb7ac9b73b4a09d56435391e9e593c1
Python
1,193
44
### By Anoushka Joglekar ### Modified 2019_02_27 import sys import pandas as pd import time from itertools import chain start_time = time.time() input_file = sys.argv[1] all_info = [x.strip('\n').split('\t') for x in open(input_file).readlines()] iso_names = [x[0] for x in all_info] cellsPerIso = [x[1::2] for x in a...
9bf5c8f1c206c0dc048dc173ad9258bf577ab6858a32724d440c216d977941f5
Python
1,198
39
from __future__ import annotations from collections.abc import Iterable class ConfigError(Exception): """Exception raised for errors with the Snakebids config.""" def __init__(self, msg: str) -> None: self.msg = msg super().__init__(msg) class RunError(Exception): """Exception raised f...
1402b62dec05c57cbdc345a1cba1cc262f18d71de64c27fdb5bfbad4c9d91007
Python
1,205
50
""" Created on 10/08/2017 @author: Niklas Pallast Neuroimaging & Neuroengineering Department of Neurology University Hospital Cologne """ import numpy as np import os,sys def getPar(filename): ## Open the text file. fileID = open(filename,'r') # Read columns of data according to the format. fileID...
b639ed00d137235ae6b7e9a1b9d0e4df0f515e23f384ed9cdfe8dd7b477f673e
Python
1,205
34
import numpy as np class LambdaWarmUpCosineScheduler: """ note: use with a base_lr of 1.0 """ def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0): self.lr_warm_up_steps = warm_up_steps self.lr_start = lr_start self.lr_min = lr_min ...
7fdb67c566ac61ad651f1d29511ee5a35537bada2bfcc2352e9ef7de2938973c
Python
1,206
37
# Copyright 2011-2022 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # 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 Licen...
9457b37050d4e0752460368a1a356e2418391e5167d7d92470a0dc4381b24fb6
Python
1,206
34
from ..common.optim import SGD as optimizer from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier from ..common.data.coco import dataloader from ..common.models.mask_rcnn_fpn import model from ..common.train import train from detectron2.config import LazyCall as L from detectron2.modeling.backbone impor...
1d7d83a608982dec484c0c30bb5cc6c77d193eea32d55485af606cdb7a9b0869
Python
1,209
33
from pathlib import Path # `navis.interfaces` talks to remote services, so its doctests cannot run in CI. # Matched as a path rather than as the substring "interfaces", which would also # swallow the tests *for* those modules (e.g. `tests/test_interfaces_base.py`). INTERFACES = Path(__file__).resolve().parent / "navis...
f394e3d21b3b78a41fdd1e1d7612343c36f910b6652da2fe944cf94daff3fc02
Python
1,209
42
from __future__ import annotations from typing import Optional class CodeBlock: def __init__(self, value: Optional[str | CodeBlock] = None) -> None: self.value = self._as_str(value) def __add__(self, other: Optional[str | CodeBlock]): return CodeBlock(self._as_str(self.value) + '\n' + self._...
e7f4f79e440be803a16eda133c8e3a3e31206505586f9f98b222065fea78c6ea
Python
1,210
43
from gufe import Transformation from ..chemicalsystem_generator.component_checks import ( ligandC_in_chem_sys, proteinC_in_chem_sys, solventC_in_chem_sys, ) def both_states_proteinC_edge(edge: Transformation) -> bool: return proteinC_in_chem_sys(edge.stateA) and proteinC_in_chem_sys(edge.stateB) de...
d15ef26b835dc1a647f0820b1e7a332152fc14701d3345d40fc8adae9889b19e
Python
1,211
36
def convert_mhz_to_ut(nu_mhz, g_factor= 2.0023): """ Converts frequency in MHz to magnetic field in µT using the given formula. Parameters: nu_mhz (float): Frequency in MHz. g_factor (float): Electron g-factor (default is 2.002319). Returns: float: Magnetic field in µT...
fc09c8ca9054ac66ce461284b0143f8f1064faecca9d9fac220b7790fbb153e0
Python
1,216
35
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import sys import torch from fvcore.nn.precise_bn import update_bn_stats from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import LazyConfig, instantiate from detectron2.evaluation import inference_on_dataset from det...
a3f1ecde81ae8b2e4378c8f3b2905120a43a1e9942e37f3ff371c470f41aa483
Python
1,218
42
#import tensorflow as tf import numpy as np import math import random from sklearn import preprocessing seed=1 # set a seed lb,ub=0.8,1 # set a lower bound and an upper bound for variation values np.random.seed(seed) whole_X=np.random.uniform(0,1,(10000,28*28)) n=whole_X.shape[0] p0=whole_X.shape[1] # the number of ...
132f4141d9377cb8fca22d310b53ade8cf6b022289d43499e80610bcd3641607
Python
1,220
36
import torch import torch.nn as nn # EEG_BiLSTM class Model(nn.Module): def __init__(self, input_size=128, hidden_size=128, num_layers=2, num_classes=40, dropout=0.3): super(Model, self).__init__() # BiLSTM self.lstm = nn.LSTM(input_size=input_size, hid...
b6f94e52f857de893df1f83dab2bb363b63f932b85e48e850d98b5a42be8b522
Python
1,222
37
import numpy as np import pandas as pd def tables(results_or_tables): if "tables" in results_or_tables: return results_or_tables["tables"] return results_or_tables def metric_value(row: pd.Series, metric: str) -> float: corrected = f"selection_{metric}_optimism_corrected" if row["setting"] i...
b4fb7ba575ad678cb2ce922bff5364a91233fcbb48988a5001f20e7f408f1310
Python
1,225
43
""" Tools for integration with miscellaneous non-required packages. shamelessly borrowed from openff.toolkit """ # don't format vendored code # fmt: off import functools from typing import Callable def requires_package(package_name: str) -> Callable: """ Helper function to denote that a funciton requires som...
d1c666a7d7d9eb7d637b6698567cd66925c26129cf1178e06a8bcf2bcffc8a28
Python
1,226
35
from ..common.optim import SGD as optimizer from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier from ..common.data.coco import dataloader from ..common.models.mask_rcnn_fpn import model from ..common.train import train from detectron2.config import LazyCall as L from detectron2.modeling.backbone impor...
8f943e932cc664d60614502dc94f716406e13dd4dfba252beebc29204c2bb5d4
Python
1,227
49
import torch import esm import tqdm import biotite.structure.io as bsio import subprocess as sb import sys args = sys.argv model = esm.pretrained.esmfold_v1() model = model.eval().cuda() assert len(args)==3, 'Please type: python3 run_ESMFold_prediction.py <input_fasta_path> <output_dir_path>' input_fasta_path ...
a6b5d1251d057b5e9e0604f4bae3262a7e0a63e383f516a4708659947f229907
Python
1,228
50
import torch import matplotlib.pyplot as plt from ..utils.lib import readSignal from ..models.VisualTransforms import LogPowerSpectrum, LogWaveletCWT data_path = "eeg_visual_classification/data/block/eeg_55_95_std.pth" data = torch.load(data_path) signal = readSignal(data, recordNo=10, channelNo=10) signal = torch....
f33d86d729454b1675b0ce326913d17c6a34f3a61f0529200c13457ed1c1ee28
Python
1,228
51
#!/usr/bin/env python3 # # Copyright (c) 2016 10x Genomics, Inc. All rights reserved. # from __future__ import annotations import argparse import sys from six import ensure_str from tenkit.fasta import check_fastq_types_multipath def make_parser(): parser = argparse.ArgumentParser( description="Check ...
ec7d000fb9604027cd789a75b1b3f93448b8a010253bc8ce80ff81665bfff304
Python
1,230
41
from NeuroPy import NeuroPy #from pyeeg import * #import pyglet npo=NeuroPy('/dev/ttyS25') eegcoll = [] def npacb(attention_value): print attention_value return None npo.setCallBack("attention",npacb) npo.start() i=1 while i<100: eegcoll.append(npo.rawValue) if(npo.meditation>50): print npo...
96f1ed78353c7f5d1da1bbb1bd037e41b9d98d0f4584f866aaf02f803e21d104
Python
1,237
39
# Copyright (c) Facebook, Inc. and its affiliates. from iopath.common.file_io import HTTPURLHandler, OneDrivePathHandler, PathHandler from iopath.common.file_io import PathManager as PathManagerBase __all__ = ["PathManager", "PathHandler"] PathManager = PathManagerBase() """ This is a detectron2 project-specific Pat...
90d61de14db5a8c0f86e4d5abd3c45606b45ab3945afaffeba293d28ccf43415
Python
1,240
46
from dataclasses import dataclass import numpy as np PF_MAPPING = {1: 0.5, ## 4/8 2: 0.625, ## 5/8 4: 0.75, ## 6/8 8: 0.875 ## 7/8 } ASYM_ECHO = {0: 1.0, 1: 0.0} LPS_TO_RAS = np.diag([-1., -1., 1., 1.]) ...
3abe9631bde16bf593c7141bea1ccafedbc15462cf060a3cbc77373b9611956e
Python
1,242
32
class InvalidOrderException(Exception): def __init__(self, function, execute_first): super(InvalidOrderException, self).__init__(f'Invalid order for function {function} call {execute_first} before calling this function') class InvalidCsvFileException(Exception): def __init__(self, path): super...
59b37559113e3d6b4d0a745b12a3e487e3eee6a3d430edd729ae0bc0a98a4fe7
Python
1,243
45
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from detectron2.modeling.meta_arch import GeneralizedRCNN from detectron2.utils.registry import _convert_target_to_string, locate class A: class B: pass class TestLocate(unittest.TestCase): def _test_obj(self, obj): ...
9b7c81f7d7635e57ada8c9c89e1a57297b46b971a6817642d2e264783f091419
Python
1,244
34
import tensorflow as tf import numpy as np import math import random from sklearn import preprocessing from tensorflow.examples.tutorials.mnist import input_data # load the MNIST dataset mnist=input_data.read_data_sets("../MNIST_data/",one_hot=True) train_X_,train_Y_,test_X_,test_Y_,val_X_,val_Y_=mnist.train.images,m...
30fff5245f81b4769211c910afe0fc9506595a97557ec484804a9b344f109864
Python
1,245
42
import re from pathlib import Path from setuptools import find_packages, setup try: import torch # noqa: F401 except ImportError as e: raise Exception( """ You must install PyTorch prior to installing DensePose: pip install torch For more information: https://pytorch.org/get-started/locally/ ...
abeb86c7581accee452f94d01d13c987261cac13e97f40ea28a68cafe0cc100d
Python
1,245
32
import pytest from src.preprocessing.smiles_cleaner import AmbiguousFragmentError, SmilesCleaner from src.utils.models import MolecularRecord def _record(smiles: str, access_code: str = "CMPD") -> MolecularRecord: return MolecularRecord(access_code=access_code, smiles=smiles, source_row=2) def test_removes_cou...
26ea098013a2f89b66b855a03e9aabccb52e4b0525f668241d18f2f1e5c3078a
Python
1,247
31
# # Copyright (c) 2020 10X Genomics, Inc. All rights reserved. # """Methods for identifying and working with 10X product releases.""" from __future__ import annotations def get_cmd_names(product_name: str) -> tuple[str, str]: """For a given product name (must be either cellranger or spaceranger) returns the hum...
a9a0956861597e897a3670fcdb8040556a0def20b9936247638fa9a03dbe1e91
Python
1,247
38
from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord import pandas as pd from pathlib import Path def aln_from_csv(input_csv: str | Path, genus: str, out_parent: str | Path) -> None: """ Method for generation of alignment files from input csv Args: input_csv: The inpu...
903dca5cfc4aadf9331c6f4e9c86aac9e0d172d6dc03e16c6471dff2d4bd372b
Python
1,250
30
import os import nibabel as nib from nilearn import image from tristan_pipeline.io.params import * space = "MNI152NLin2009cAsym" os.makedirs(grp_dir, exist_ok=True) for moco_label in list(mocos.keys()): subject_maps = [] #########LOOP OVER SUBJECTS AND SESSIONS######### for subj in subjects: for s...
3876be8555a7094d13ce572627a77613feed9622391aceb660a909ba251ad6a2
Python
1,251
53
from __future__ import annotations import matplotlib.pyplot as plt import mne from ..utils import get_soi_picks def plot_sensors( inst: mne.io.BaseRaw | mne.Epochs | mne.Evoked, sois: list[str] = ['O', 'P', 'C', 'F', 'T'], ) -> None: """Plot the sensors of the SOI. Parameters ---------- ins...
8e75af33b56e5d3a835a51cbb3cc631d4333526cc3cc806b138205c7fdeaea29
Python
1,253
38
from plus_slurm import Job #%% import pandas as pd #import pymc as pm import bambi as bmb import arviz as az #import aesara.tensor as at from scipy.stats import zscore import os from os.path import join #%% class BayesPred(Job): #%% the run method starts here def run(self, key2corr, channel, outdir, **sample...
168d6416d9cbc39b086543b1a9c9fe55228862479af8e816d74453d4e9747732
Python
1,259
36
from detectron2.config import LazyCall as L from detectron2.layers import ShapeSpec from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.matcher import Matcher from detectron2.modeling.roi_heads import FastRCNNOutputLayers, FastRCNNConvFCHead, CascadeROIHeads from .mask_rcnn_fpn imp...
16e3337316ce2f0e55da7b033f41632958f0863eb818588bb715a3ae5b80e071
Python
1,261
47
""" NoClaMe ------- This script implements a series of metrics for node-classification. These metrics are for binary node-classification, intended to work for node-classification on molecular graphs, which usually involves a large number of relatively small graphs (<50 vertices). Implemented node-classification me...
7c13de4821a2e4efe3fb20d414a72162e8f09e9572dd5aa88d6212327af57240
Python
1,262
38
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 7 13:33:47 2022 @author: schmidtfa """ #%% imports from cluster_jobs.preprocess_meg import Preprocessing from obob_condor import JobCluster, PermuteArgument import pandas as pd #%% get jobcluster job_cluster = JobCluster(required_ram='2G', ...
bf6c8915f4737f8a9f2a46ca3c1e112cc101f45ea9b8d8e1e1166d90fddcdc44
Python
1,262
48
#!/usr/bin/env python # # Copyright (c) 2024 10X Genomics, Inc. All rights reserved. # """This stage extracts a projection from a cloupe file.""" __MRO__ = """ stage ETXRACT_LOUPE_PROJECTION( in cloupe sample_cloupe, in string projection_name, out csv projection, src py "stages/cas_cell_typin...
ad7d8a4ee489881cb58485a2f8aae3ea24a451de26413c43743c4a3c419315f2
Python
1,265
35
"""Audio loading utilities.""" import subprocess from pathlib import Path import numpy as np def load_audio_16k(path, sample_rate=16000): """Decode an audio file to a float32 mono array at ``sample_rate`` via ffmpeg. ffmpeg does the resampling/downmixing out-of-process, so the native-rate buffer never ...
b2318475468c1aed304fecec5efa54dde6f75ef88b3390d5c4e7893693eddb7d
Python
1,265
43
import shutil import subprocess from importlib import resources from os import PathLike from pathlib import Path from typing import Union from ..._env import run_captured from . import data as cellprofiler_data def create_and_save_segmentation_pipeline( segmentation_pipeline_file: Union[str, PathLike] ) -> None:...
b5f035391b590c5fddba1c78bce8951971ab1eaf62a146e78777ed6c1ca73fca
Python
1,266
42
import os import sys import anndata as ad import torch # 获取当前脚本的绝对路径 current_dir = os.path.dirname(os.path.abspath(__file__)) # 获取父目录(模型定义脚本)的路径 parent_dir = os.path.dirname(current_dir) if parent_dir not in sys.path: sys.path.append(parent_dir) from config import MethyAnnoConfig from main import * my_config = M...
b95a16d0b529ec9054e394a5d6d5213c268d63df243fea35513d20b949a7cab5
Python
1,266
34
#!/usr/bin/env python3 import argparse import gffutils parser = argparse.ArgumentParser() parser.add_argument("annotation_file", help="GTF file containing gene annotations. For example, from https://www.gencodegenes.org/") parser.add_argument("--filter", default="Ensembl_canonical", help="Only keep GTF features with t...
54b5814351472796635c5ece98008555aa76e3c22b09a9850af130ab2027e924
Python
1,267
35
from pathlib import Path import numpy as np import pytest from steinbock import io from steinbock.segmentation import deepcell from steinbock.segmentation.deepcell import Application keras_models_dir = "/opt/keras/models" @pytest.mark.skipif(not deepcell.deepcell_available, reason="DeepCell is not available") clas...
82e9e1539dec3092695e6613814b3da092b9ca121398ccd566c7719a3f65ae37
Python
1,268
27
# %% setup #for i in /cluster/work/users/ash022/veronica/*He*.d ; do echo $i ; timsconvert --chunk_size 5000000000 --verbose --input $i ; done #sage sage.json -f human_crap.fasta --batch-size 40 /cluster/work/users/ash022/*.mzML #cp lfq.parquet $HOME/PD/TIMSTOF/LARS/2024/240605_Veronica/HeLa/ # %% data proteinHits=pd....
e2130334f1861b9582b69fbb70f3d7fc679da8ccce04dacee8926b1cce08d0a7
Python
1,269
43
from os import PathLike import torch from chemprop.models.model import MPNN from chemprop.models.mol_atom_bond import MolAtomBondMPNN from chemprop.models.multi import MulticomponentMPNN def save_model( path: PathLike, model: MPNN | MolAtomBondMPNN | MulticomponentMPNN, output_columns: list[str] | t...
e990dfee1ea20f1adbfba808613383d2bb6fa69eefc0e0288502ac465aaa0b92
Python
1,270
43
import subprocess from importlib import resources from os import PathLike from pathlib import Path from typing import Union from ..._env import run_captured from . import data as cellprofiler_data def create_and_save_measurement_pipeline( measurement_pipeline_file: Union[str, PathLike], num_channels: int ) -> No...
fe04ee8c6d081b4cc654c2c681409d02cac1e618d333e825bd7b222cae59137e
Python
1,273
48
#!/usr/bin/env python3 import sys import matplotlib.pyplot as plt import matplotlib import numpy as np matplotlib.rcParams['pdf.fonttype'] = 42 # --- Example data matching the plot --- # Adjust these or load from a file groups = ["Standard\nsimulation", "Concatenated\nreads"] categories = ["Precision", "Recall"] val...
d8455ba427957b2c011033119c36d6403111264095da050178f60401ee54872e
Python
1,274
35
import os import pandas as pd import numpy as np from src.utilities.statistical_tests import apply_enrichment from loguru import logger logger.info('Import OK') input_path = 'results/preprocessed/RC_significant_summary.csv' background_path = 'results/preprocessed/identified_background.csv' output_folder = 'results/R...
7c032c6175c0e5d604f7eb76324a9849341deef646cd3e5ae446cd39d5dcbeee
Python
1,276
33
from __future__ import annotations from dataclasses import dataclass import numpy as np @dataclass(frozen=True) class WeightedTargetScaler: mean: np.ndarray scale: np.ndarray @classmethod def fit(cls, targets: np.ndarray, weights: np.ndarray) -> "WeightedTargetScaler": targets = np.asarray(...
1c00e5389a1194ac96145d51e67980a17eb171dcb625f68b756bcfd96008f9ed
Python
1,277
41
#!/usr/bin/env python # Copyright 2011-2014 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
df038581650b2787e486695aeb08c887ca977d7a61102500b3928efa9128d947
Python
1,280
37
import cv2 from os import listdir from os.path import isfile, join import numpy as np def threshold_images(in_path, out_path): """ Performs the threshold function on all the images in the folder `in_path` and outputs them in `out_path` Params: in_path: folder of source images out_path: fold...
cc1cd2fdf5f1aaba7ff7dc897824e17bcd3dfb69ff2da3730ef993105894ac60
Python
1,282
41
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
342d6a562eb82d238618e9c8a8dd382494d207178c74d5c780b16252710b1e02
Python
1,283
38
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from __future__ import annotations import json import pathlib from openfe import AlchemicalNetwork, LigandNetwork from openfecli.utils import write def plan_alchemical_network_output( ...
114abb9847aefadd4780fee395d6b4712de5a390674d7f1f9e1d7f26ac25bc9b
Python
1,284
39
# This script is part of navis (http://www.github.com/navis-org/navis). # Copyright (C) 2018 Philipp Schlegel # # 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...
743a55b246f1993b4a43c5a33ff4fdf284a360e9d31692d3b8d2cace65cf6ef1
Python
1,284
44
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Optional, Sequence import numpy as np import numpy.typing as npt __all__ = ["PNG"] @dataclass class PNG: layers: npt.NDArray[np.int_] nrns: npt.NDArray[np.int_] lags: npt.N...
b4335757bd219462fc1f540b55d8002342b1d4bb4f228fc39e536184ed6b953c
Python
1,284
31
#!/usr/bin/env python # Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
c20436daa3e54b00386f0fc30207fabaed3220cf91fd6e07dac8f86e15c05788
Python
1,285
40
from functools import partial from fvcore.common.param_scheduler import MultiStepParamScheduler from detectron2 import model_zoo from detectron2.config import LazyCall as L from detectron2.solver import WarmupParamScheduler from detectron2.modeling.backbone.vit import get_vit_lr_decay_rate from ..common.coco_loader_l...
ff4d6dd2a450848177112f4205c82591161d50952e8382cbae294581011320fc
Python
1,285
38
from plus_slurm import Job #%% import pandas as pd #import pymc as pm import bambi as bmb import arviz as az #import aesara.tensor as at from scipy.stats import zscore import os from os.path import join #%% class BayesPred(Job): #%% the run method starts here def run(self, key2corr, channel, outdir, **sample...
3c2f1a16433c0022312af92b535decf6f7dbc6420b17685bdbf38c1652e72d52
Python
1,286
37
# Copyright (c) Facebook, Inc. and its affiliates. # pyre-unsafe from collections import OrderedDict from detectron2.checkpoint import DetectionCheckpointer def _rename_HRNet_weights(weights): # We detect and rename HRNet weights for DensePose. 1956 and 1716 are values that are # common to all HRNet pretra...
abfcff867a7230dde40d0471d99e9f4683ea45ca02522851377e2367ba81f6ef
Python
1,287
43
# commands extensions to PyMOL for batchmin from pymol import cmd from chempy.bmin import realtime import threading def amin(*arg,**kwarg): realtime.assign(arg[0]) apply(bmin,arg,kwarg) def bmin(object,iter=500,grad=0.1,interval=100, solvation=None): realtime.setup(object) t ...
522570660d5f9e08ed70f4176b3f2f69312f912296abdd034738f1c28933d86b
Python
1,292
33
############################################################################ # Copyright (c) 2022-2026 University of Helsinki # Copyright (c) 2019-2022 Saint Petersburg State University # # All Rights Reserved # See file LICENSE for details. ############################################################################ ...
12e89249a87482b866e5b5e9b00add386f3ab474c37f2cf66ea4c1f63fe047b8
Python
1,293
38
#!/usr/bin/env python # Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
2f1e0ec377f4767a3457deda3170b093d35d43b77b58f2dfe5cbbd2cc4e06181
Python
1,293
48
""" Created on Thu Oct 12 13:18:03 2023 @author: dcupolillo """ import json def save_to_json( node_bundle: object, json_filename: str, ) -> None: """ Save NodeBundle data to a JSON file. This function serializes key properties of a NodeBundle, such as the total number of nodes, total neu...
919e52f162396898d98a768ad4cc6b6c303331b8f2b0a24dfecadf2a48a02110
Python
1,299
44
# # Copyright (c) 2025 10X Genomics, Inc. All rights reserved. # """Structify aggregated cell typing outputs.""" from cellranger.cr_io import recursive_hard_link_dict __MRO__ = """ struct AggregatedCellTypes( csv all_cell_types, json.gz all_cell_annotation_results, ) stage STRUCTIFY_AGGREGATED_CELLTYPES...
6e1154eb3d528c4e28fe7527f029213cd9407143083f4edf1cc739ca29b426f0
Python
1,300
46
import inspect from typing import Any, Iterable, Type, TypeVar T = TypeVar("T") class ClassRegistry(dict[str, Type[T]]): def register(self, alias: Any | Iterable[Any] | None = None): def decorator(cls): if alias is None: keys = [cls.__name__.lower()] elif isinstanc...
e107045b20a15ef193ba6cd0ee189bd786415e77239399c12ce0cd8cebe8fb59
Python
1,303
47
""" Created on Thu Jul 27 15:25:49 2023 @author: dcupolillo """ import ROIpy as rp import matplotlib.pyplot as plt from pathlib import Path date = "240912" cell_n = "cell0002" data_folder = Path(r"C:/Users/dcupolillo/Projects/spyne/data") neuron_path = Path(rf"{date}\{cell_n}") stack_filename = Path( data_fo...
bbb1a625070525039d11742228c469b088728f4879db20d1652ca2d85fd59b71
Python
1,304
59
# -*- coding: utf-8 -*- """For testing neuromaps.points functionality.""" import numpy as np import pytest from neuromaps import points def test_point_in_triangle(): """Test point in triangle.""" triangle = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 1]]) point = np.array([0, 0.5, 0.5]) inside, pdist = p...
dfbc2abedc0d30e2823e2666142b5dccb50ff170b80df23fd9cfd2de1b5f5f1d
Python
1,304
39
#!/usr/bin/env python # # Copyright (c) 2026 10x Genomics, Inc. All rights reserved. # """Compute segmentation plots for Visium HD data.""" __MRO__ = """ stage STRUCTIFY_WEBSUMMARY_INPUTS( in WebSummaryCellTypeInputs websummary_inputs, in map<json> cell_type_spatial_plot, out WebSummaryCe...