sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
7eca9176139205e3011d1c84430f4eeef62c88ef985237a328be7476175aadb6
Python
2,434
69
import numpy as np import pandas as pd import pkg_resources def mouse_symbol_to_mouse_ens(df_unmapped: pd.DataFrame, drop_unmapped: bool=False, verbose: bool=False) -> None: """Map dataframe index mouse gene symbol to mouse ensemble id inplace Parameters ---------- df_unmapped : DataFrame Data...
eec0ab99fe77ad37eb21de20a1810b457f3c058cedb18cb6ae354af0431fac7e
Python
2,436
68
import numpy as np import pytest import pandas as pd import pandas._testing as tm class TestIndexConstructor: # Tests for the Index constructor, specifically for cases that do # not return a subclass @pytest.mark.parametrize("value", [1, np.int64(1)]) def test_constructor_corner(self, value): ...
696b67e0a0320256fa019d0b3ba360a9583ec63b1adbddfb14b568b85ebd0d3c
Python
2,437
64
"""Create Pulseq test file with radial trajectory.""" import pypulseq import torch from einops import repeat from mrpro.data import KTrajectory, SpatialDimension class PulseqRadialTestSeq: def __init__(self, seq_filename: str, n_k0=256, n_spokes=10): """A radial 2D trajectory in Pulseq. Please n...
cdb35f8278983bc0fe37a323f8db039bdda8a833889a0f1c37d93f32e4ff11e0
Python
2,438
67
"""RunningMeanStdObs must survive torch.jit.script -- models.py wraps it unconditionally for dict observation spaces (regression: upstream #315 scripted the container whose forward lacked the Dict annotation, so dict-obs + normalize_input crashed at model construction).""" import torch from rl_games.algos_torch.runni...
d06bf177ddb150807726a0eca5200a06caab9d02f8a2e9e8409dd5f54b124747
Python
2,438
58
from Common import loggingUtils from Common.kernelFunctions import * from Surfaces.surfaceMultiPhase import * def compute(): outputDir = '/cis/home/younes/Development/Results/biocardSliding10test' #outputDir = '/cis/home/younes/Development/Results/biocardStitched10' if __name__ == "__main__": log...
ad9553b2913e37f1f791bf39b019fdaa2f549c7e5bfd1f07590c6a2257c5fa33
Python
2,439
62
"""Saturation recovery signal model for T1 mapping.""" from collections.abc import Sequence import torch from mrpro.operators.SignalModel import SignalModel from mrpro.utils.reshape import unsqueeze_right class SaturationRecovery(SignalModel[torch.Tensor, torch.Tensor]): """Signal model for saturation recovery...
ab3b5f16c2192292c30ac5fd70053caf985de585b75749e84b1bbd1952547bac
Python
2,440
70
import copy import yaml class Experiment: def __init__(self, config, experiment_config): self.config = copy.deepcopy(config) self.best_config = copy.deepcopy(self.config) self.experiment_config = experiment_config self.best_results = -100500, 0 self.use_best_prev_result = se...
efda308d573e4f0471eae463065b5d29d53e73a7bdcad7ffab0424b488baeca5
Python
2,441
65
#%% import torch # import tensorboardX as tbx # writer = tbx.SummaryWriter('runs') from utils.dataset import get_output, FilterData2, load_data from utils.unet import * from utils.model import MyNet2, Model from utils.emd_ring_torch import emd_loss_ring GPU_INDEX = 0 USE_CPU = False if torch.cuda.is_available() and no...
c25f9d2e851adcfa8b558c76ff0c00d88f41e7f95ec5bd1bf781fbf1581744f9
Python
2,442
67
""" Tests for the Table of Correlated Phenotypes feature Verifies that the sample file is correctly combined with phenotype information """ import os import shutil import pytest from pheweb.load import pheno_correlation from pheweb import weetabix # Simplified files for testing purposes CORREL_FILE = os.path.join...
800832f394bb4604123bd93b0baa971b2b52ea227156ba3e9a7eea73f2728691
Python
2,443
60
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet): # ----------------------------------------------------------------------------------------------...
f12159adc54769e32355fb0688cb926e6adb6714ba7be69a39e5500dc4807477
Python
2,443
70
# MOFTransformer version 2.0.0 class CLICommand: """ Download pre-trained model, database, and fine-tuned model """ @staticmethod def add_arguments(parser): from moftransformer.utils.download import ( DEFAULT_PRETRAIN_MODEL_PATH, DEFAULT_COREMOF_PATH, ...
a718a7fc9f8b098efb0b6d814885056a4bc75a26e57b974507f152d9cccf9720
Python
2,444
85
from pathlib import Path import pytest import tbparse from omegaconf import DictConfig, ListConfig, OmegaConf from lightning_pose.train import train pytestmark = pytest.mark.gpu def _get_base_cfg(cfg): # Smallest possible test: two steps per epoch. return OmegaConf.merge( cfg, { ...
dfa80d0b798ffe40746f6b97cb9bf7f57208243087ab31d6b6fe77705103b4c0
Python
2,444
80
""" Modified from: https://github.com/milesial/Pytorch-UNet """ import torch import torch.nn as nn import torch.nn.functional as F def double_conv(in_channels, out_channels, mid_channels=None): if not mid_channels: mid_channels = out_channels return nn.Sequential( nn.Conv2d(in_channels, mid_ch...
41e968584ae76883fa13673c992fe29c58cca30edc73ee4987712eaa3a9977d7
Python
2,445
69
import os from cptools2 import utils import pandas as pd import numpy as np CURRENT_PATH = os.path.dirname(__file__) TEST_PATH = os.path.join(CURRENT_PATH, "example_dir") TEST_PATH_PLATE_1 = os.path.join(TEST_PATH, "test-plate-1") def test_flatten(): """utils.flatten(list)""" test1 = [[1, 2, 3], [4, 5, 6], [...
6903e926c78fe326b908421a95f27e66c15b303f46a9298580042c42e2e6ef1c
Python
2,445
105
""" Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs, which has its own directory. If a PR does not edit anything in _libs/, then it is unlikely that the benchmarks will be affected. """ import numpy as np from pandas._libs.lib import ( infer_dtype, is_list_like, is_scalar, ) from pand...
83d0ceb0284816cbec006f6ec95322d0a5989ffdba61dac49b2b1468f54d40ef
Python
2,445
75
import numpy as np import pytest import pandas as pd import pandas._testing as tm class TestCopy: @pytest.mark.parametrize("deep", ["default", None, False, True]) def test_copy(self, deep): ser = pd.Series(np.arange(10), dtype="float64") # default deep is True if deep == "default": ...
f5c7d527b4e142eb0d9dc0cbe7aa4172d09d7f7d389498ed29e9767bdcfad689
Python
2,445
64
import numpy as np import pandas as pd import sys def interp(x): dtype = x.dtype vals = x.values ref = 0 for i, v in enumerate(vals): if not np.isfinite(v): vals[i] = ref else: ref = v return pd.Series(x, dtype=dtype) evmeasures_path, itemmeasu...
052ecbd2d7e7dcab5da85cfbbd75f00147c1561ca47e1110ea8a3bd38bd97e19
Python
2,446
84
"""Tests for gradec.plot module.""" import matplotlib as mpl import numpy as np from gradec.plot import plot_cloud, plot_radar, plot_surf_maps def test_plot_radar(tmp_path_factory): """Test plotting radar chart.""" tmpdir = tmp_path_factory.mktemp("test_radarplot.png") corrs = [0.8, 0.6, 0.4, 0.2] ...
5c0eba74ac7df93c7e83c2480ce00ee6426ba1b8f3bd5ba4b7c801ed25452d09
Python
2,446
74
"""Anthropic Claude provider. Uses Claude's native *tool-use* feature to force a JSON response that matches `output_schema`. The tool is declared inline per-call with the schema; we consume the first `tool_use` block the model emits. Imports the ``anthropic`` SDK lazily so the base server install doesn't depend on it...
a57b2518c7006c41d94c07319f0d71fd69be341f4db78a028b0d9afb24687689
Python
2,447
91
""" This script demonstrates * the multi-shell sampling pattern for diffusion MRI. Author: Zhengguo Tan <zhengguo.tan@gmail.com> """ import matplotlib.pyplot as plt # from mpl_toolkits.mplot3d import Axes3D import numpy as np from sigpy.mri import dvs import os fontsize1 = 12 fontsize2 = 16 # %% Import and Plot...
fbf6ab35958dcfbb37c66b5de5fc55f6cd1bf00d32cd7f526c9dc47a0e39cc9d
Python
2,447
77
""" Created on November 10, 2019 functions for writing/reading data to/from disk @modified_by: Soroosh Tayebi Arasteh <soroosh.arasteh@fau.de> """ import yaml import numpy as np import os import warnings import shutil import pdb def read_config(config_path): """Reads config file in yaml format into a dictionar...
9fd42a2c3adfdb3a9d1a4ba7013b36ae90a129cf4e6622a5ae7a3f1db49df33a
Python
2,450
65
import tensorflow as tf import model # maybe needs to be None? BATCH_SIZE = 1 def get_per_subword_surprisal(*, corpus, hparams, encoder): start_token = encoder.encoder['<|endoftext|>'] context = tf.fill([BATCH_SIZE, 1], start_token) def step(hparams, tokens, past=None): lm_output = model.model(h...
191e4e1f05f44c5411dfa9ae1f2130973101a1a25e7bc5fd483b0befe24a9a1f
Python
2,453
70
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error import logging # %% binning def bin_data(df, col_name, min_val=0.0, max_val=100.0, step=2.5): ""...
65c7a022ccd672adfb3069973171afc925fb2a1c7c47ab1e704b18267b1fb58d
Python
2,453
65
"""Returns the trajectory saved in an ISMRMRD raw data file.""" from collections.abc import Sequence import ismrmrd import torch from mrpro.data.KTrajectory import KTrajectory from mrpro.data.SpatialDimension import SpatialDimension from mrpro.utils.reshape import unsqueeze_at class KTrajectoryIsmrmrd: """Get ...
9846413117130dcd2b272fdf6354247a600955505630ebb6b7da52a5986babf8
Python
2,453
75
# -*- coding: utf-8 -*- from copy import deepcopy import numpy as np __all__ = ["State"] class State(object): """The state of the ensemble during an MCMC run For backwards compatibility, this will unpack into ``coords, log_prob, (blobs), random_state`` when iterated over (where ``blobs`` will only be ...
34dd0f2ecff7b53fed8d679fdcf45f855bd322405460359fcd73297dd793cbf9
Python
2,454
76
#!/usr/bin/env python3 """ trim-gam.py: trim GAM records from JSON standard input to contain only mappings to nodes in the given range. Range end is exclusive. usage: vg view -aj input.gam | trim-gam.py 123 456 | vg view -JGa - >output.gam """ import sys import json import base64 def mapping_to_length(mapping: dict...
ea2837c28791f0de7011ce8e49347a1a94b52629293390da04b818e309f084f8
Python
2,454
63
""" signal.py Created February 17, 2021 Provides methods for converting images of leads into signal data. """ from typing import Callable from ecgdigitize.image import BinaryImage, ColorImage from .. import common import numpy as np def extractSignalFromImage( image: ColorImage, detectionMethod: Callable[[C...
92dff4d0b1e6524a2ced81e02e67f3689e632d08945345671ef937213ad433f1
Python
2,455
75
__all__ = ["PeptideMS2SpectrumProto", "PeptideMS2Spectrum"] import itertools from dataclasses import dataclass from typing import Any, Iterable, Optional, Protocol, Tuple, Union import numpy as np import numpy.typing as npt from ..common.spec import IntensityArray, MzArray, MS2SpectrumProto ChargeArray = Union[npt....
77f5dc311010f6bfbec8800059274930be8a796824b32e6a44d157698d413100
Python
2,456
84
import pytest from pandas.util._validators import validate_args_and_kwargs @pytest.fixture def _fname(): return "func" def test_invalid_total_length_max_length_one(_fname): compat_args = ("foo",) kwargs = {"foo": "FOO"} args = ("FoO", "BaZ") min_fname_arg_count = 0 max_length = len(compat_...
cf81d317d22a4cd015f9f8673be3dd2794e3732c1707039d889a47a55a2b8512
Python
2,456
81
# Copyright 2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
9a5119e21157ddb5759dee4886202d4939d7e29b9984bf8ce6efedbf76884641
Python
2,457
88
import numpy as np from collections import defaultdict class LinearValueProcessor: def __init__(self, start_eps, end_eps, end_eps_frames): self.start_eps = start_eps self.end_eps = end_eps self.end_eps_frames = end_eps_frames def __call__(self, frame): if frame >= self.end_...
aa0c79080b22da3ea32fa1861cd3891f3c861d99f76963337aec7c5df0322f9c
Python
2,459
59
"""Command-line interface for the error command. """ from atropos.commands.cli import BaseCommandParser, writeable_file from atropos.io import STDOUT class CommandParser(BaseCommandParser): name = 'error' usage = """ atropos error-se input.fastq atropos error -pe in1.fq -pe2 in2.fq """ description = """ Es...
eb9d603c78c1e5849be17a05435f7ad57ce68fbe76385dfa1e355a616ce97931
Python
2,459
87
# Copyright 2025 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
2342a3a31cacfd87dcbae12b4a7c3de51a4bbbc10db2efff91f99bcc1d978552
Python
2,460
91
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.0 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% from pathlib import Path import sys...
462914ba8bf241d47b43f81cdfc5cd670e56a5428b3ebe8b80c7233a28169775
Python
2,460
71
import numpy as np import pytest from pandas._libs.tslibs import IncompatibleFrequency import pandas as pd import pandas._testing as tm class TestSearchsorted: @pytest.mark.parametrize("freq", ["D", "2D"]) def test_searchsorted(self, freq): pidx = pd.PeriodIndex( ["2014-01-01", "2014-01-...
b0084eae7b77cc283b23a251477c07fb3225bb42b3b8f169fe90fcf7a62944de
Python
2,460
43
import sys, re, argparse, pandas as pd argparser = argparse.ArgumentParser('''Collapses user-specified numeric per-event measures from *.evmeasures input into per-item median and mean measures. Unspecified columns are assigned the first value encountered in the input data table for each item.''') argparser.add_argument...
7cb7e4a3226df66069a11e6725c85f40bd0a0531835b58766a83fc56b6030224
Python
2,461
89
import copy import os from typing import cast import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.model_selection import GridSearchCV, KFold import statsmodels.api as sm from scipy.interpolate import interp1d from sklearn.isotonic import IsotonicRegression from sklearn.linear_mode...
dd466e7d22d33301251816f1860774f47f41abff3ca14bff29d8fb204395abc2
Python
2,463
66
import os import time import concurrent.futures import json apkinfo_api = [] #存放一组字典信息 apkfilename = [] path = r'E:\pythonProject\Experiment\out_benign_samples' apk_list = os.listdir(path) for apk in apk_list: apk = os.path.join(path, apk) apkfilename.append(apk) apiheadlist=["Landroid/", "Lcom/a...
5519466145ac746da1ce1be1be8455ffbe5f4e1ca44fb3b83f7ab5773a710909
Python
2,464
74
__all__ = [ "PeptideFragmentTypeInfo", "PeptideFragmentTypeCollection", ] import os from dataclasses import dataclass from typing import Dict, Mapping, Optional from ...util.io.yaml import load_yaml from ..common.elements import ElementCollection, ElementComposition @dataclass(frozen=True) class PeptideFrag...
b155719a8a08f918bddcad3546c1aa3f3f23a6f8782632f4cbaed0b44db9b027
Python
2,464
49
from Environment_ui import * def concat(image_list, save_path, index, param): start_x, start_y= 0, 0 restored_array = np.zeros((int(param['Network_input_z']), int(param['Patch_weight_num'])*int(param['Network_input_x_y']), int(param['Patch_height_num'])*int(param['Network_input...
1e5517e85f7b2157327261566db1b1a37ba58fd9c23cf3111e89ae3f6f88dc57
Python
2,465
63
"""Mono-exponential decay signal model.""" from collections.abc import Sequence import torch from mrpro.operators.SignalModel import SignalModel from mrpro.utils.reshape import unsqueeze_right class MonoExponentialDecay(SignalModel[torch.Tensor, torch.Tensor]): """Signal model for mono-exponential decay.""" ...
584a7559d0c09a15d809d72c8501ab3a7c79e165c344430b816a72f516b65b4f
Python
2,465
69
#!/usr/bin/env python3 ''' This script is for getting more test data. In theory I could just make random variants from the reference, but I don't have an `hg19.fa` on hand. ''' import csv import requests import random import re import itertools def format_float(x): if x >= 0.01: return '{:.3}'.format(x) rv =...
7013f848a65b160a8ee90bba56b687e744471d0327a95d6cc70d0be35544df07
Python
2,465
84
from xml.etree import ElementTree from os import path import re import json from tensorflow.keras import utils FILENAME = path.dirname(__file__) + "/CVATdata/annotations.xml" def split_coord_string(s): pairstrs = s.split(';') strpairs = list(map(lambda pair : pair.split(','), pairstrs)) coordpairs = list...
55c9e8bc5f24f60399a2643c6f85a56ed355886c8119ed2cf732375d30246e5a
Python
2,468
77
import argparse from timeit import default_timer as timer import matplotlib.pyplot as plt import pandas as pd import SimpleITK as sitk import torch from src.model import ProbabilisticModel def predict(opt): """Predict on CPU using sample data.""" print("Load the model...") if opt.model == "resnet": ...
dd5b4d8a418320636cd88f6358637e5f4b94e6ec72ef788e382437b625479371
Python
2,468
72
import os from cptools2 import filelist CURRENT_PATH = os.path.dirname(__file__) TEST_PATH = os.path.join(CURRENT_PATH, "example_dir") TEST_PATH_NEW = os.path.join(CURRENT_PATH, "example_dir_new_paths") def test_files_from_plate(): """see if we get image files from a plate directory""" plate_path = os.path.j...
e6c1b5d8795bc325ce4325795ec91de0f2e3bb789ead4f815586860b2e44d3bc
Python
2,468
95
# -*- coding: utf-8 -*- """ This script generates plots for Figure 1 Note that it uses microscopy images and can not be reproduced from the zenodo archive data only. Created on Tue Sep 13 16:19:56 2022 @author: jeanbaptiste """ import sys import numpy as np import cv2 import matplotlib.pyplot as plt import deepcell...
1d64001fd00691e739ec6549be57a33b2e7767ab27bf43f877d310d566d3bb6e
Python
2,470
71
import numpy as np import pytest from pandas.core.dtypes.common import is_float_dtype import pandas as pd class TestSetValue: def test_set_value(self, float_frame): for idx in float_frame.index: for col in float_frame.columns: float_frame._set_value(idx, col, 1) ...
1f5ec560b52df20a92ab025e3b662f130d8e534d4f42d976a09d2d73983a70ce
Python
2,471
80
#!/usr/bin/env python3 """ Cluster items by transitive closure of pairwise associations. Conceptually, we are given a series of pairwise "connections" -- a pair of items which should be in the same cluster. We group any items for which there is a pairwise connection in a cluster. Note: this is a quick-and-dirty imple...
a923789bb99a9143f31acf8c589647da659742b938c27ce00453438a80aadc25
Python
2,471
69
# -*- coding: utf-8 -*- """ Reference for colormaps included with typhon. The original version of this script [0] is provided by Matplotlib. This reference example shows all colormaps included with typhon. Note that any colormap listed here can be reversed by appending "_r" (e.g., "pink_r"). These colormaps are divid...
c8dc61506bdf722f3204aec37cdc1bd919b722d15b80d9b14dad0e23bc26bc6e
Python
2,471
92
import numpy as np import vegas import math import gvar as gv from outputsplitter import log_stdout, unlog_stdout def f(x): dx2 = 0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 return math.exp(-dx2 * 100.) * 1013.2118364296088 # save gv.ranseed(12578) log_stdout('eg9a.out') integ = vegas.Integrator...
2b5c6bfc10610b4c9166248da3111ea408ef3bb1da51ffc18ace6165898a5d45
Python
2,472
72
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.api.types import is_scalar class TestSeriesSearchSorted: def test_searchsorted(self): ser = pd.Series([1, 2, 3]) result = ser.searchsorted(1, side="left") assert is_scalar(result) assert...
fb43d7a5062b3786dd81ad9a2ac085154f4eb2865ee9d3cff665d973c4d37b48
Python
2,472
59
from src.cv import CVGenerator, CVSpec from sklearn.model_selection import GridSearchCV from sklearn.model_selection import KFold, RepeatedStratifiedKFold N_SPLITS = 5 N_REPEATS = 1 RANDOM_STATE = 42 SHUFFLE = True def test_cv_spec(): cv_spec = CVSpec(n_splits=N_SPLITS, n_repeats=N_REPEATS, random_state=RANDOM_S...
dc155e41d5bdb7051eb7f6bc0fc98bae9ac713ba32197d2ffc73a23831e73fcf
Python
2,473
84
import numpy as np from loess import loess_1d import pathlib from sklearn.ensemble import IsolationForest from matplotlib import pyplot import glob from skimage.filters import threshold_isodata MIN_AREA = 1000 MIN_WIDTH = 15 def get_stem(filename: str) -> str: return pathlib.Path(filename).stem def load_meas...
1a60df3d380d22c5aa6480c56e3de3b6300a641b339dff84564c009685fca010
Python
2,475
91
#!/usr/bin/env python3 import subprocess # commands to include ######### If you add to this, also add it to the intro section of vgmandmd.desc.md cmds = ['align', 'annotate', 'augment', 'autoindex', 'bench-dist-query', 'benchmark', 'call', 'chains', 'chunk', 'circularize', 'clip', 'cluster', 'combine'...
3300d9b435cf396f75dc14a9258083d238dca6b2970ae61da78bfbd34e0760aa
Python
2,475
85
""" This version computes summary statistics for regions of real data along the genome. Authors: Rebecca Riley, Sara Mathieson Date: 12/14/22 """ # python imports import math import numpy as np import random import sys sys.path.insert(1, "../") sys.path.insert(2, "../plotting/") # our imports import global_vars impo...
15ebe94eeb2878dd82f6a399c680eab0d8135f9e8060e5a0815bc15dad947c3e
Python
2,476
49
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
a63e6d750c8e33444d815d3e9081dc7b9fb5d18b1319c2447a437d44af59fded
Python
2,476
79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 4 11:50:50 2023 @author: tomas """ import pathlib import math import random import numpy as np from cine import Cine import tube2 from skimage.io import imshow from matplotlib import pyplot, patches from sklearn import cluster, ensemble video_fol...
4b7a4efd219ab3ef1c90fa7c220d10cc0d35fd00562be71a39ee5e5684889b32
Python
2,478
73
"""Class for Sensitivity Operator.""" import torch from mrpro.data.CsmData import CsmData from mrpro.operators.LinearOperator import LinearOperator class SensitivityOp(LinearOperator): """Sensitivity operator class. The forward operator expands an image to multiple coil images according to coil sensitivity...
cfb3df03a6c7f502940efefcc0c9ca8579a050f97b4b06793c9118b570d13c97
Python
2,480
81
"""Display changelog with links to GitHub issues Usage ----- The directive .. include_changelog:: ../CHANGELOG adds the content of the changelog file into the current document. References to GitHub issues are identified as "(#XY)" (with parentheses and hash) and a link is inserted https://github.com/RI-imaging/...
fc2e0dc5084f8ee2ba24b3eb7fa1ca1432dd5d14274c6f4e4d4e5d477bb2c37c
Python
2,481
89
""" Test extension array that has custom attribute information (not stored on the dtype). """ from __future__ import annotations import numbers from typing import TYPE_CHECKING import numpy as np from pandas.core.dtypes.base import ExtensionDtype import pandas as pd from pandas.core.arrays import ExtensionArray ...
7963af274e7f9156d9e325755d74bf50814d7ad97e3bd69dc799a0424c93cd42
Python
2,483
88
# Created by G. Peter Lepage (Cornell University) in 05/2019. # Copyright (c) 2019 G. Peter Lepage. # # 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 # any la...
a56c30b077823f892e9ce39886d5ac0e270ef7450e9dcb1eafab3f739413cab2
Python
2,483
82
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 30 12:08:21 2023 @author: nrq2 """ # https://pycistarget.readthedocs.io/en/latest/pycistarget_scenic%2B_wrapper.html #%matplotlib inline import pycistarget pycistarget.__version__ import os import pyranges as pr import os from scenicplus.wrappers.r...
de6d67caab10e9d8cde58957171cca1d367e27a9ed17dedd94b3b89104fba4e2
Python
2,483
82
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.16.0 # kernelspec: # display_name: .venv # language: python # name: python3 # --- # %% import os, datetime from pathlib import Path impor...
41c5ba0a97b43e43d2a04da04c10e5a0cee28d1e7e63a2cf01eec717c650a3e2
Python
2,484
67
import matplotlib.pyplot as plt import numpy as np def get_values(region_info, output): """ Extract metrics and statistical values for the given region from the output data. """ metrics, lh_stats, rh_stats, asymmetry_stats = [], [], [], [] for i, elt in enumerate(output['norm']['metric_names']): ...
9f8a04378ddddb38bf3fe628246b8da3924f95721f9a07e40120935280c524aa
Python
2,485
83
""" Tests for np.foo applied to DataFrame, not necessarily ufuncs. """ import numpy as np import pandas as pd import pandas._testing as tm class TestAsArray: def test_asarray_homogeneous(self): df = pd.DataFrame({"A": pd.Categorical([1, 2]), "B": pd.Categorical([1, 2])}) result = np.asarray(df) ...
e6adef4ec799b6923574ef9ebaed34d5d53f6d299be7a1daaa11119fe8461fe2
Python
2,485
77
from __future__ import annotations from typing import ( TYPE_CHECKING, Any, ) import numpy as np from pandas._config import is_nan_na from pandas._libs import lib from pandas._libs.missing import NA from pandas.errors import LossySetitemError from pandas.core.dtypes.cast import np_can_hold_element from pan...
2793ffc7421207df0db2d87f79909823274d769a917c16cdbb992ee5c4e6e631
Python
2,488
77
# -*- coding: utf-8 -*- from functools import lru_cache import numpy as np from .red_blue import RedBlueMove __all__ = ["DEMove"] class DEMove(RedBlueMove): r"""A proposal using differential evolution. This `Differential evolution proposal <http://www.stat.columbia.edu/~gelman/stuff_for_blog/cajo.pdf>...
808609eddfe29979adf142ac216786c9e46a396353f7103ea57e7e1afec4f0cc
Python
2,491
89
import pandas as _pd from parserix import parse as _parse def _well_site_table(img_list): """ parse metadata from image paths and return a pandas dataframe of image_path and metadata columns Parameters: ----------- img_list: list list of image paths Returns: -------- pand...
76263bb9d31100b6a4003e27d61e901343859c16a38b46d141bf94cd0b093911
Python
2,493
64
import time import matplotlib import numpy as np import pandas as pd matplotlib.use('Agg') import matplotlib.pyplot as plt from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, NoiseTypes def main(): Board...
f07eb5bf4973f221f7474d9192a3cec7fb2b8c96f235afa47c35d6d046ad8e5c
Python
2,494
79
# -*- coding: utf-8 -*- import torch class Interleaver(torch.nn.Module): def __init__(self, array=None): """ Class that represents an interleaver. :param array: That array that is needed is used to change the order. """ super(Interleaver, self).__init__() if array...
4681c8c260b3f13e2047e050e881ea79b6770ad65ff91220396b5a7ca169eabe
Python
2,495
78
"""In-memory + optional file-backed logger. The default logger when a user does `Experiment(log=True)`. Stores every event in a list so the UI / notebook can replay it afterwards, and optionally tees each event to a JSON-lines file. Cheap, thread-safe enough for single-process use (the event list uses a list append w...
8ba2a2c3cdf186d8161348ae350130b5df55fdf9a376969c2661ebd2c04742f7
Python
2,495
92
""" Timedelta benchmarks with non-tslibs dependencies. See benchmarks.tslibs.timedelta for benchmarks that rely only on tslibs. """ from pandas import ( DataFrame, Series, timedelta_range, ) class DatetimeAccessor: def setup_cache(self): N = 100000 series = Series(timedelta_range("1 ...
aea9af51e34d6626e25b1f60686a00ff3164ba69f663845a7ab8204cd2fa8dd7
Python
2,496
81
"""Test fetching data from OSF.""" import numpy as np import pytest from nimare.annotate import GCLDAModel from gradec.fetcher import ( _fetch_features, _fetch_metamaps, _fetch_model, _fetch_neuroquery_counts, _fetch_spinsamples, ) @pytest.mark.parametrize( "dset_nm,model_nm", [ (...
71a850d43fffd4c28a957d875f2d1d1eb3e7fd1dc3de67504652efaa82493c5a
Python
2,497
56
import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib.ticker as ticker import matplotlib.transforms as transforms plt.rcParams['font.family'] = 'Gargi' #create figure fig, ax = plt.subplots() bar_width = 0.4 palette = ['#999999', '#999999','#999999','#999999', '#999999', '#2E6AFF'...
bccc0881ff12a60242a3925ec7ea9dee6286532f24c55920d7ea123f9967e984
Python
2,501
68
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
34d34bd0cab3d9d8f9ee1aa7eb6ba26d3bbd602a5cf32c07c65139948b6d51b3
Python
2,502
73
"""Provider registry + factory. `get_provider(row)` is the seam every consultation path goes through. It's keyed on `LLMProviderSetting.provider`. Adding Google / Azure / Ollama later means implementing one class + adding one registry entry here. """ from __future__ import annotations from pycaret_server.llm.provide...
f9b08535f8062e0e34689cb06d803d9fce31a32fc811d22ba25ecd6756d51fbe
Python
2,504
83
import logging import torch from torch import nn from ocpmodels.common import distutils class L2MAELoss(nn.Module): def __init__(self, reduction="mean"): super().__init__() self.reduction = reduction assert reduction in ["mean", "sum"] def forward(self, input: torch.Tensor, target: ...
13fb145f60c8b1b43a6de44d943663f23f0728f8c8e895345953e8a0219375af
Python
2,505
58
import cv2 from tqdm import tqdm import plastegy_net from glob import glob import pandas as pd from datetime import datetime task = 'analyse' if task == 'train': training_root = '' export_path = training_root + '/output' training_path = training_root + '/training_data' validation_path = training_root +...
ff6e4b0b585efc057a0589a7bac9b0e2852209e0e678d40f33a83b1f29f92d0a
Python
2,505
60
#if two consecutive regions have the same annotation, then they should be merged into a single region def merge_bed(file_path): merged_rows = [] with open(file_path, 'r') as file: previous_row = None for line in file: row = line.strip().split('\t') #print(row) ...
ea6aea11ff449d71f78462cee75ccf9d911695a0a4da0be6b2a060241f1dc0d7
Python
2,506
76
import numpy as np import matplotlib.pyplot as plt import pandas as pd from mat4py import loadmat import scipy as sp from matplotlib import cm from helper_make_data import make_data from helper_make import make from matplotlib.ticker import FormatStrFormatter import sys import os from helper_compute_performance import...
ab6af7ef39f3264ea4fe1782a0a87c213df1b556c81c6292bfdefcb9b36cd7c7
Python
2,508
65
import os from unittest import TestCase, mock import numpy as np import pandas as pd from scipy import stats import dynast.estimation.p_c as p_c import dynast.estimation.p_e as p_e import dynast.preprocessing.aggregation as aggregation from .. import mixins class TestPC(mixins.TestMixin, TestCase): def test_r...
e18f45e3dba45dd5bb982b1aea7e2ec61ff563fa484f36a30baee797c5c36dbe
Python
2,510
77
"""Test the smooth_bbox CLI command argument parsing.""" import argparse from unittest.mock import patch import pytest from lightning_pose.cli.commands.smooth_bbox import get_parser, handle class TestGetParser: """Test the get_parser function.""" def test_returns_argument_parser(self): """Returns ...
b03ec918ed42a6c9a9037e798bcb9dfc4d29d0ddc0f2ac4bc4df36e642f82e6f
Python
2,511
76
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.tests.copy_view.util import get_array @pytest.mark.parametrize("box", [lambda x: x, pd.DatetimeIndex]) def test_datetimeindex(box): dt = pd.date_range("2019-12-31", periods=3, freq="D") ser = pd.Series(dt) idx =...
2d99321b21e1c22f1e2da8ab164a0634f25b0e191690925e78eba58992561574
Python
2,512
74
import cv2 import cv2 import math from utils.logging import init_log import numpy as np import math import sys from scipy import signal from scipy import ndimage def fspecial_gauss(size, sigma): x, y = np.mgrid[-size//2 + 1:size//2+1 , -size//2+1:size//2+1] g = np.exp(-((x**2 + y**2)/(2.0*sigma**2)...
666529fc6ef29faaebf29278ac3321cdf6251ed670035bac6b4d6446525022aa
Python
2,512
74
# Copyright 2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
903d446ab5ba36ac034a2bf3a9460f349d6d31d1d26850fa91198ece7d10ded1
Python
2,512
60
from PyQt5.QtCore import pyqtSignal from PyQt5.QtWidgets import QWidget, QHBoxLayout from .CheckBox import CheckBox class MetricCheckBox(QWidget): # Signal emitted when the checkbox state changes. It sends the label of the checkbox when checked. sgn = pyqtSignal(str) def __init__(self): super()....
b46d62a81fcdb921338957192b571763eb7448b62a3533110d3761fc2ff59c9d
Python
2,512
69
''' @Author: your name @Date: 2020-01-06 14:04:27 @LastEditTime : 2020-01-06 17:28:15 @LastEditors : Please set LastEditors @Description: In User Settings Edit @FilePath: /KGCN_Keras-master/callbacks/eval.py ''' # -*- coding: utf-8 -*- from collections import defaultdict import numpy as np from keras.callbacks impor...
b9b1034fb6451c6c57afb752b7ca636f72596251b2ca27f055e9840d83dc3f74
Python
2,512
75
# Copyright 2025 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
da9b30cf93090c855d8554c7b2fbf25d56ffc494e2d080d8fafab36081e432c3
Python
2,512
77
from game_functions import Game, Game_Bayes from helper_compute_performance import compute_performance import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, use from helper_percentile_discrete import percentile_discrete from helper_set_pi import set_pi import sys if __name__ == "__main__": wh...
13d4a39438c2bef291f3555827ca275a12243bc7743555621ef08cdc1236eb68
Python
2,513
70
#!/usr/bin/env python3 """ concat_csv.py ------------- Concatenates multiple CSV files into a single output CSV file. - Accepts a list of file paths as input; files that do not exist are silently skipped. - Prepends each input file's content with a header including the category and file name. - Removes the input files...
26b3972dbe14fe894040540bf37f3b23577c08acb3630461c9a32bcb7a609bca
Python
2,513
86
# # Main file of program intended to run analysis on protein structural data using # holographic machine learning techniques # # new import statements from argparse import ArgumentParser import imp import os import sys import numpy as np import protein_holography.hologram.pdb_interface as pdb_int import protein_hol...
442a5be9c4b1724d4915080857901b35f33d30ba55f262a69b4255c71d9695bd
Python
2,514
61
import os from unittest import TestCase, mock import pandas as pd import dynast.preprocessing.bam as bam import dynast.preprocessing.coverage as coverage import dynast.preprocessing.snp as snp from .. import mixins class TestSnp(mixins.TestMixin, TestCase): def test_read_snps(self): snp.read_snps(self...
c74c79233f3be06f7458eea51c79dc800ee6a8ee0fd198c4fe8489236922047e
Python
2,514
71
import pytest from pandas.errors import Pandas4Warning import pandas as pd import pandas._testing as tm class TestSeriesRenameAxis: def test_rename_axis_mapper(self): # GH 19978 mi = pd.MultiIndex.from_product([["a", "b", "c"], [1, 2]], names=["ll", "nn"]) ser = pd.Series(list(range(len(...
cba963cc9152d508f70cfd75f6b49d4fb6b2040d7a59f895c3a900994bc08e5e
Python
2,514
72
import os import pytest from cptools2 import parse_yaml CURRENT_PATH = os.path.dirname(__file__) TEST_PATH = os.path.join(CURRENT_PATH, "test_config.yaml") TEST_PATH2 = os.path.join(CURRENT_PATH, "test_config2.yaml") TEST_BROKEN = os.path.join(CURRENT_PATH, "test_config_broken.yaml") def test_open_yaml(): """cpto...
5cf36b3b4a62e66e6e4c9a2e77e863231c4ce71243915ed69308b87c7675517d
Python
2,515
80
import pytest from pandas._libs.tslibs.dtypes import NpyDatetimeUnit from pandas.errors import OutOfBoundsTimedelta import pandas as pd class TestAsUnit: def test_as_unit(self): td = pd.Timedelta(days=1) assert td.as_unit("us") is td res = td.as_unit("ns") assert res._value == ...
a77ecb3168b6dc2343131ef6e43a6fe486e4c53cac0890a9a4d29d617837c874
Python
2,515
72
import os import subprocess import sys import pytest pytestmark = pytest.mark.online def test_public_hf_repository_serves_small_runtime_assets(tmp_path): hf_home = tmp_path / "hf-home" env = os.environ.copy() for name in ( "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_URL",...
0e0ffa02883028c584c10e17be47826cf58cbe1cce6d00228b9139a76afa31ad
Python
2,516
68
# Copyright 2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
b001efd723ea627caadede5c012a491c5ba23f49e6d232a2c56907781cbe7866
Python
2,516
59
from wordfreq import tokenize, simple_tokenize, word_frequency import pytest def test_tokens(): assert tokenize('おはようございます', 'ja') == ['おはよう', 'ござい', 'ます'] def test_simple_tokenize(): # When Japanese is run through simple_tokenize -- either because it's # tagged with the wrong language, or because we wa...
56624e7cd51e386fa157eae58586219292645c42d92fefc88c725ddafa1d0fa4
Python
2,521
82
import numpy as np from plot_configs import * import pylab def plotFragSize(ds, frag, log=1, prefix="test"): """ Plot the estimated fragment size. """ # print ("@plotFragSize") ds = np.abs(np.array(ds)) ds = ds[~np.isnan(ds)] ds = ds[ds > 0] if log: ds = np.log2(ds) fig, a...
30874731fafe85ade529f8421565d8f2dd4d6497d4e188979aa9233f70e6669c
Python
2,522
67
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def random_image_mask(img, filter_size): ''' :param img: [B x 3 x H x W] :param crop_size: :return: ''' fh, fw = filter_size _, _, h, w = img.size() if fh == h and fw == w: return img, None ...