sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
194927b2b005670ec37b602fd0dbd680461b90afe992782ccdcdfa1d9623d89f
Python
3,308
118
import torch from torch import nn import math import torch.nn.functional as F def critic_loss(model, value_preds_batch, values, curr_e_clip: float, return_batch, clip_value: float): """ Computes the critic loss using the default critic loss function. When the model is compiled via torch.compile, this func...
31beb83e528a168f79ac164e18ef1f45c8a669294e021bd1052b1e47d37595ca
Python
3,308
94
import pathlib import importlib.resources from PyQt6 import uic, QtCore, QtWidgets import pyqtgraph.exporters as pge from ..pipeline_plot import PipelinePlot from ..widgets import show_wait_cursor from ...util import get_valid_filename EXPORTERS = { "png": ["rendered image (*.png)", pge.ImageExporter], "sv...
aaf6b0591fc034b9f52ddec4c504ef707e6b709e60dbcd915686c22020c99642
Python
3,308
125
# coding: utf-8 from contextlib import contextmanager from importlib import import_module import os from subprocess import check_output, CalledProcessError import sys import tempfile import traceback import urllib.request from atropos.commands import get_command from atropos.io import xopen @contextmanager def redire...
e3a2343bfc57ba4b395960355ebd24aa9309bcc20f0848dd9d1ef3a60949f8f7
Python
3,310
61
import numpy as np import sys as sys import os from MM2SF.acsf.sfc_functions import * def compute_ACSF(trjname=None,itype=None,irad=None,iang=None,new_format=True): """ Compute ACSF (Atom-Centered Symmetry Functions) based on input geometry files. Parameters: - trjname (str): Name of the trajectory fi...
ce0dc3e926fdd2a3432df320fccdcf16cbd91a35a92e43e9d66e7aa10b1a07f9
Python
3,311
106
# Copyright 2018-2023 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...
0f0550d029245475ed68d6f07967c417d320e6f6426cecf32761328ff027421c
Python
3,312
92
""" Given a delimited flat text file, with a specified "key" column, generate an index specifying where to find rows with a given value This is useful for, eg, looking up all information associated with a given phenotype ID # TODO: I should probably be embarrassed by this. Daniel can shame me later. """ import o...
2f0aea2eace2b0ae0636bc80bdca335ad6bf4f7325bc10337ee8cf70a756f3cd
Python
3,312
47
import numpy as np np.random.seed(26) import os, torch basedir = os.path.abspath(os.path.dirname(__file__)) os.chdir(basedir) file_path = os.path.abspath(os.path.join(basedir, 'literature_data')) data_path = os.path.abspath(os.path.join(basedir, 'new_data')) # 1. drug_disease drug_disease_co = torch.Tensor(np.loadtx...
a31325954eb6cb3642407ab6e9a9ed6f7cbf5770924e0e0a3a03def05e81a318
Python
3,312
92
import numpy as np import pytest import pandas._config.config as cf import pandas as pd class TestTableSchemaRepr: def test_publishes(self, ip): ipython = ip.instance(config=ip.config) df = pd.DataFrame({"A": [1, 2]}) objects = [df["A"], df] # dataframe / series expected_keys = ...
db976912bfaffa644ee7cc6299871492f58d45a87df7d98a763954b0c104ea20
Python
3,312
92
# -*- coding: utf-8 *-* import numpy #import fftw3 def applyKernel(right, dims, num_nodes, Kv, el_vol, scale=True): """ Apply the V kernel to momentum, with numpy fft, used for multi-threaded processing. """ krho = numpy.zeros((num_nodes, len(dims))) for j in range(len(dims)): rr = right...
0843455542f7f27f97d1a0f69b439875e8c748033f4e3b14fb6d48402b93ac85
Python
3,313
89
"""Script to recenter and crop T1w Instructions The inputs include T1w and an initial brain mask (e.g., U-Net mask), in *.nii.gz format. The output will be a recentered and cropped T1w in the working directory. For example, if all data is in the same folder as following: /projects/working_dir/sub-032114 - sub-032...
15fa2689d52dffb68c945be1fbe38dfc52b421fa7140ed096364073331046d62
Python
3,314
62
import psycopg2 import pdb from sqlalchemy import create_engine import sqlalchemy.orm as orm import os import sys import pandas as pd import numpy as np import json sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ...
0a5b9a08528390da74f5f614eb37ef1cca5656395db6186f0f7b65301590a159
Python
3,316
121
# JN 2016-01-12 """ manage spikes for data viewer """ import os from .tools import debug class SpikeManager(object): """ Represent spikes for data viewer """ def __init__(self, sign, label): self.fnames = {} self.openfiles = {} self.times = {} self.spikes = {} s...
43146bc404539e107697d7cd71d4b93b25ac8e33531b906f4d257445b426bdd7
Python
3,316
101
import pdb def years_education_convertion(field845, field6138): if field845: try: field845 = int(field845) if field845 > 0: return field845 - 5 elif field845 == -1 or field845 == -3: return None elif field845 == -2: ...
950920859809edd5e5bd690144aaf1b82973842fb56c4409e13e806ca078de7c
Python
3,316
78
import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() import time as clocktime ################################################################ ################################################################ N = 1000 frequencies = np.arange(1, 101) ttot = 1000. twindow, tbin = 1.0, 0.0...
3c2ba0cf6b092e10cf54166b4a407a0b755cdbd6550d8ca1d3491c95f9a334c2
Python
3,318
75
import pandas as pd from rdkit.Chem import PandasTools import torch from pytorch_classes_and_functions import AmesDataset, DNN from captum.attr import IntegratedGradients from local_evaluation_functions import map_attr_to_atoms, attribution_auc from helper_functions import string_to_int_list, dict_to_string, stri...
14c5f17c5178594f911c4a2bdd96cd0d2481f1ff1ca4d95ade018f29519a18bc
Python
3,319
77
from Environment import * from Parameter import * from scipy.stats import variation def coefficient_of_variation(csv_path, save_path, index): fs_array = np.zeros((205, len(Stats['fst_data_name']))) ctrl_array = np.zeros_like(fs_array) for i in range(len(index)): fs_file = open(os.path.join(csv_path...
0afa0da5fdc34cd970aa7b312418d88945f2a96adb3f5f7e3e137df08545c8d3
Python
3,321
126
""" Common plotting routines for validation figures Designed to accompany the paper "Network-level encoding of local neurotransmitters in cortical astrocytes" (DOI: TODO) """ ## ------------------------------------------------------------------------ ## ## Imports ## -------------------------------------------------...
6d9bb2d36d9fb8a80089decf00a35046bbb3e492740ed942a98e24c8ee9f81ae
Python
3,321
111
import json import pandas import aggregate_figures as af import tube2 import cine import numpy as np import tensorflow as tf from tensorflow import keras from matplotlib import pyplot import seaborn from skimage.filters import threshold_li, threshold_isodata def get_batch(video, idx, batch_size=8): zone = [] i...
3f2a5b01e707751c879bf8b8e215bcc14b35882dcf6d6624d480d8e0f8baf5c7
Python
3,322
89
"""Customized argparse classes with improved help formatting for the litpose CLI.""" import argparse import shutil import sys from typing import Any class ArgumentParser(argparse.ArgumentParser): def __init__(self, **kwargs: Any) -> None: """Initialize ArgumentParser with custom formatting and epilog."""...
c972b42f29dab81985b85f5123e3e0bc869815157a9ec6d96d745313c32bca78
Python
3,325
86
import os import sys from copy import deepcopy from trainers.bow_trainer import BoWTrainer from evaluators.evaluator import Evaluator from models.bow.args import get_args from datasets.scar_bow import SCARBoW import warnings import datetime from tables.generate_token_counts import count_bow_tokens if __name__ == '__ma...
3de53eac13bcf79b3b83d0f03f7a5a09a7bbc4a0a43c597f6dac331aac327d6e
Python
3,327
91
"""Efficient sliding window implementation for tensors.""" from collections.abc import Sequence import torch from mrpro.utils.reshape import normalize_indices def sliding_window( x: torch.Tensor, window_shape: int | Sequence[int], dim: int | Sequence[int] | None = None, stride: int | Sequence[int] ...
a1bf7e7b438c0a0b3355623b48b35d92e43705f3c2d21827c8daa2add058121e
Python
3,327
104
from xml.etree import ElementTree from os import path import re import json from tensorflow.keras import utils from collections import OrderedDict import tensorflow as tf from tensorflow.data import Dataset _base = path.dirname(__file__) FILENAME = _base + "/CVATdata/annotations.xml" FILENAME2 = _base + "/CVATdata/ima...
d7cd7f59cfe985e7cf719f86d7d64599dd8c112282392fd96b848795ecd7b51f
Python
3,328
89
import sys import argparse import numpy as np import pandas as pd import configparser def compute_filter(y, field, cond): """ Compute filter given a field and condition :param y: ``pandas`` ``DataFrame``; response data. :param field: ``str``; name of column on whose values to filter. :param cond:...
2bc06011ee542a8585e00e93f40eed77dd3d6b3442349ab3de0eff1cd5928195
Python
3,329
118
import pytest from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd import pandas._testing as tm from pandas.core.arrays import ( PeriodArray, ) pa = pytest.importorskip("pyarrow") def test_arrow_extension_type(): from pandas.core.arrays.arrow.extension_types import ArrowPeriodType p1 ...
4c0055db392c0bb6595e3dd68e337a38fa6d38030a72c3010fb7e6057bd4faa2
Python
3,330
138
from typing import List import pandas as pd def read_qbed(filename: str) -> pd.DataFrame: """\ Read .qbed file. :param filename: Path to the qbed file. :Returns: pd.DataFrame for the qbed file. :example: >>> import pycallingcards as cc >>> qbed = cc.rd.read_qbed("https...
49f37a8344a16f9e8935e9eaefc0a751d0a3b1f0b9ee89f40491e161c499ea0e
Python
3,333
90
import numpy as np from scipy.interpolate import RegularGridInterpolator import torch def interpolate_flight_path(wind_prediction, grid_dimensions, flight_path): ''' Interpolate the wind and turbulence (if available) prediction of the regular grid along the flight path. Parameters ---------- wind...
8bc2d2a831ad0354259b0c35ab4a86ca6aeed667c3987b680805f97311c0f525
Python
3,335
107
# !/usr/bin/env python """ Script to convert mmCIF files to PDB format. usage: python cif2pdb.py ciffile [pdbfile] Requires python BioPython (`pip install biopython`). It should work with recent version of python 2 or 3. @author Spencer Bliven <spencer.bliven@gmail.com> """ import os import sys import argparse import l...
e34d84e8de716ef58c2e79bb41f638245ba524b458fbebedf698177dd8e70fef
Python
3,336
109
from tensorflow import keras import math import numpy as np from skimage import transform, util class ImageSeq(keras.utils.Sequence): def __init__(self, ins: np.ndarray, outs: np.ndarray, batch=32): assert ins.shape == outs.shape self.inputs = np.copy(ins) self.outputs = np.copy(outs) ...
72bc809dc3dd9093f78f7280161ddfb7a3ea53f2bd187b4af5e2d7be2598b25d
Python
3,337
94
# Copyright 2026 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...
b4a311c0e9fac126bce9a6d6aff2060d4c8d0de544254aa343fed57f0e8c6466
Python
3,337
72
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import json import time import openmc from utils.mcsimulation_tetris import * from env_config import * #=========================set values below========================== num_sources = 1 # the number of radiation sources to place. shape_na...
829e51a10c60d4117fb604096331fe2b4e6cbf809395544a5095f3426b3f7c53
Python
3,340
118
import numpy as np import ants as an from pathlib import Path from deepbrain import Extractor from scipy.stats import pearsonr import pdb ''' Functions for fast preprocessing of anatomical images ''' def extract_brain(image): ''' Brain Extraction Parameters ---------- image: ANTs image object ...
33b1180803cacab7a2eb1f942a65a251bd2e729b708ea81e13ddce7cc2a61561
Python
3,341
98
import sys import types import pytest import pandas.util._test_decorators as td import pandas as pd pytestmark = pytest.mark.single_cpu @pytest.fixture def dummy_backend(): db = types.ModuleType("pandas_dummy_backend") setattr(db, "plot", lambda *args, **kwargs: "used_dummy") return db @pytest.fixtu...
4140a37f7df407b73652b6ca7b11e3064283087bea3cbcac5631965b3dc67ea1
Python
3,344
93
# Copyright 2026 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...
a08fb171061c960289207e2252e5ba4f0519a28ecedd101cb4f9280a73518a39
Python
3,344
95
#! /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...
bf525f44a759086bc6e26aa7657cb599a68f7cee5e4f387a6de306f5b421adab
Python
3,345
96
from pyrosetta_hdf5_holograms import get_hologram from preprocessor_hdf5_neighborhoods import PDBPreprocessor from argparse import ArgumentParser import numpy as np import h5py import sys sys.path.append('/gscratch/spe/mpun/protein_holography/utils') from posterity import get_metadata,record_metadata import logging fr...
50b7e32dcf69c31b8f641e3a68c9455934d4b999af8183b5a426a18aefdfd872
Python
3,346
91
import numpy as np gregory_omega = np.array([ np.array([5.00000000000000000000e-01]), #k=0 np.array([4.16666666666666666670e-01, #k=1 1.08333333333333333330e+00]), np.array([3.75000000000000000000e-01, #k=2 1.16666666666666666670e+00, 9.58333333333333333330e-0...
3667d89341184322525fff32e51cc2ca6dca62e9853e53c2cb8ed68974cdd7e7
Python
3,349
102
""" Tests for offsets.CustomBusinessDay / CDay """ from datetime import ( datetime, timedelta, ) import numpy as np import pytest from pandas._libs.tslibs.offsets import CDay import pandas as pd import pandas._testing as tm from pandas.tests.tseries.offsets.common import assert_offset_equal from pandas.tse...
4201a68d23f5c6f51e54d97ee92b8c72724023e7a4bfc95dc379ab20a623e720
Python
3,351
120
import torch from isaacgym.torch_utils import * @torch.jit.script def my_quat_rotate(q, v): shape = q.shape q_w = q[:, -1] q_vec = q[:, :3] a = v * (2.0 * q_w ** 2 - 1.0).unsqueeze(-1) b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0 c = q_vec * \ torch.bmm(q_vec.view(shape[0...
50cbdee905359e8aaa8fd797e1394c064930f14e143d1a60c24c9e7fb0777ae6
Python
3,351
121
# ----------------------------------------------------------------------------- # @brief: # The logger here will be called all across the project. It is inspired # by Yuxin Wu (ppwwyyxx@gmail.com) # # @author: # Tingwu Wang, 2017, Feb, 20th # -----------------------------------------------------------...
8af225f41a49a73c992d47aebaa59a0b162a1dedeee395a0e65a47c620997b45
Python
3,353
92
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: model_performance.py # Author: Alessandro Gerada # Date: 2023-03-16 # Copyright: Alessandro Gerada 2023 # Email: alessandro.gerada@liverpool.ac.uk """Test the performance of a saved model on a set of colony images. Use model_performance.py -h for help.""" ...
cc9e42c93d129d416dc8a5db981b79d2a3fccc37599450fd95b65a6c9d74e19a
Python
3,354
104
import pytest import torch from mrpro.operators import ProximableFunctional, ProximableFunctionalSeparableSum from mrpro.utils import RandomGenerator class Dummy(ProximableFunctional): """Only for testing purposes.""" def __init__(self, prox_scale: float = 1.0): super().__init__() self.dummy ...
21bbe52874ca98cf575563052607c0151a9703a409c1f2216c9d9b1bcc5a7d5a
Python
3,355
105
# -*- coding: utf-8 -*- """ Train the linear regression model & get the results for table S1 Created on Fri Apr 22 16:16:27 2022 @author: jeanbaptiste """ import copy import time import json import uuid import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.keras # sys.path.in...
0dfabd59ef5f087a44bb4d428b536c5eb6a13c69c73907a34a6e65b498628570
Python
3,356
89
import numpy as np import random import os import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable import time import sklearn.linear_model from sklearn.model_selection import train_test_split from sklearn.linear_model import Perceptron, LogisticRegression import...
206a6f9619e31783e75da05333ea52c2c1c580074c95c8c4c1a35cb17ea277ea
Python
3,357
79
"""Command line interface for the qc command. """ from atropos.commands.cli import ( BaseCommandParser, parse_stat_args, configure_threads, positive, int_or_str, writeable_file) class CommandParser(BaseCommandParser): name = 'qc' usage = """ atropos qc -se input.fastq atropos qc -pe1 in1.fastq -pe2 in2...
2bc0681647e6cf3c33b1d028f7b9945bb2ca2400f65c9372c6053544fa875184
Python
3,357
92
import distributed # import fasteners # import redis import yaml import os import warnings if 'ISF_DISTRIBUTED_LOCK_CONFIG' in os.environ: config_path = os.environ['ISF_DISTRIBUTED_LOCK_CONFIG'] with open(os.environ['ISF_DISTRIBUTED_LOCK_CONFIG'], 'r') as f: config = yaml.load(f) else: warnings.war...
99ba08be04251886e7955bae6b7edeb0ce57e4296cef832c1f9a6fa36399576f
Python
3,357
127
from initialization.initialization import * from initialization.config import * import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import plotly.graph_objects as go plt.rcParams.update({ "figure.facecolor": (1.0, 1.0, 1.0, 1.0), "axes.facecolor": (1.0, 1.0, 1.0, 1.0), "...
ad787011bbabcb59686fe93181f27a16b0b6446b71698e1b0069128ac4e08486
Python
3,358
115
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Activation, Add, Dense class Critic(Model): """ Critic =============== Attributes: units (list): list of the numbers of units in each layer n_quantiles (int): number of predicted quantiles ...
68ce6f578c0630d0a1c360838177617109e63acc26b280f826fce7f600d6b79d
Python
3,359
82
# Copyright 2018-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...
9c26f2b4c4daa3ef928f646960743d4cb5a442525f8b97342304a9e44244565e
Python
3,359
96
#---------------------------------------------------------------------72 #---------------------------------------------------------------------72 # COMPUTE WATER FLUXES #---------------------------------------------------------------------72 #---------------------------------------------------------------------72 # ...
eddd72ee65b23b541fe9ef09beeab39309a35a764842f7a13a32696cac8f7269
Python
3,359
112
import imageio import numpy as np import imgaug as ia import imgaug.augmenters as iaa import glob import cv2 import matplotlib.pyplot as plt import numpy as np import re from tqdm import tqdm import vuba import pandas as pd import os import multiprocessing as mp import imageio import random import time # Parameters --...
efb711da493123f6127585388be3139ab0dce1086700e936f2b36c86142e2c1a
Python
3,359
109
""" .. _decoding_1d: ==================================================== Decoding the Principal Gradient ==================================================== Gradec provides . """ # Download HCP S1200 principal gradient from gradec.fetcher import _fetch_gradients gradients = _fetch_gradients(cortical=True) ####...
11d4f74b0a7b3057bccef1c22e7761d082640b3e4b6fc716afffad3f3f1c5f85
Python
3,361
103
""" Includes test for last_valid_index. """ import numpy as np import pytest import pandas as pd class TestFirstValidIndex: def test_first_valid_index_single_nan(self, frame_or_series): # GH#9752 Series/DataFrame should both return None, not raise obj = frame_or_series([np.nan]) assert ...
8f3f3ac32796cf01cf25473e7617a3a392e48b4dbbf1eeff01c64e775471532d
Python
3,361
112
import numpy as np import pytest import pandas as pd import pandas._testing as tm def test_fillna(idx): # GH 11343 msg = "fillna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.fillna(idx[0]) def test_dropna(): # GH 6194 idx = pd.MultiIndex.from_ar...
4693d73a75095a0b7c17a0a76de8fc5437960ccc20e385309fc2dfc27ca53542
Python
3,363
77
# Imports from scipy.stats import ttest_ind from sklearn.metrics import confusion_matrix from sklearn.preprocessing import StandardScaler from src.vizualization import heatmap import numpy as np np.random.seed(1) import os import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf from sklearn.dec...
f187b848d1f3aef384344f22996f4b5c360b0997a1894160eee6962f073a8e11
Python
3,363
88
############################################################################### # This script reads pubmed ids and retrieves the title, abstract, and publica # # tion date for each of them. The script also removes duplicates and saves the# # results in an excel file. # ...
b493187a56f02ece819967c015951844e7843b44218ef20e8049181fe4f62d05
Python
3,365
79
import argparse import multiprocessing as mp import os import sys import yaml paths = [os.path.dirname(os.path.dirname(os.path.abspath(__file__))), os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'src')] sys.path.extend(paths) from src.draw import draw_angle_stimulus, draw_stimulus_proximit...
e312ebf1143a468fedb8ca0e9c476776399a1d19bb3843ba770b3ceb3417be48
Python
3,365
95
import sys import os import numpy as np import torch import torch.utils.data as du from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import util from util import * from drugcell_NN import * import argparse def predict_dcell(predict_data, gene_dim, drug_dim, model_file, hidden_f...
7e366844d41229d99e562a297e252db1871461d6feaf12c1b477238fb1d51ea7
Python
3,366
104
import sys import os import configparser from cdr.formula import Formula X_path = sys.argv[1] y_path = sys.argv[2] outdir = sys.argv[3] main_effects = sys.argv[4:] config = configparser.ConfigParser() config.optionxform = str config.readfp(sys.stdin) if 'data' in config and 'X_train' in config['data']: X_train ...
8c84b392850b0040f49a39e66a664d7be3656b6fff71fbd1cc596aeae693667e
Python
3,366
95
from sys import path as sys_path sys_path.append('..') sys_path.append('../base') import argparse import logging from base import loggingUtils from base import surfaces from base.kernelFunctions import * from base import surfaceMatching from base import affineRegistration def runLongitudinalSurface(template, targetL...
c4c513e5bf059bfb28581bf53fddbe99e2d7d04f733c9b77c69e980784161d1b
Python
3,367
111
import io import sys import numpy as np import pytest from pandas.errors import Pandas4Warning import pandas as pd import pandas._testing as tm from pandas.io.excel import ExcelFile from pandas.io.excel._base import inspect_excel_format xlrd = pytest.importorskip("xlrd") pytestmark = pytest.mark.filterwarnings( ...
338c249d6742a861950c714e34b9cd6b67ffed04b379dfc5d9b28815477595ab
Python
3,368
80
import numpy as np import pandas as pd import sys, os from random import shuffle import torch import torch.nn as nn from models.gat import GATNet from models.gat_gcn import GAT_GCN from models.gcn import GCNNet from models.ginconv import GINConvNet from utils import * import pickle from flashtorch.utils import apply_t...
b5f360b1d1eacf332560c1e206185dac0187c47ff4c552ec1c2a356ee95f581c
Python
3,371
111
# Copyright 2018-2021 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...
d658405ba4efed22abf87b07486182ddc0f0685d8bf5debd282573cb822b3c98
Python
3,372
101
import numpy as np import pandas as pd import pandas._testing as tm from pandas.core.arrays import IntervalArray class TestGetNumericData: def test_get_numeric_data_preserve_dtype(self): # get the numeric data obj = pd.DataFrame( {"A": [1, "2", 3.0]}, columns=pd.Index(["A"], dtype="ob...
924b71c70ac7592732305abb80c46001de1924666842880c1c98b4de506314d9
Python
3,374
81
import shutil from pathlib import Path from ..logger._live import SimpleStep, display_enabled, live_step, quiet_hf_bars from ..utils._files import atomic_output_path from ..utils._hf import download_hf_file _EXAMPLE_DATA_FILENAMES = { "GSE130735": "GSE130735_subset.pkl", "GSE193140": "GSE193140.pkl", "GSE...
9e22824e140f0ed0945fd5436768f4dba6eca80db92817562233dbb2ea4ea16d
Python
3,375
113
# Module: internal.display class # Author: Antoni Baum (Yard1) <antoni.baum@protonmail.com> # License: MIT from typing import Any, Dict, List, Optional from pycaret.internal.display.display_backend import SilentBackend, detect_backend from pycaret.internal.display.display_component import MonitorDisplay from pycaret....
589630849e7bbb2071c578e7f7713e44b545fa991dc6b6e809a24216e36b8f66
Python
3,376
100
"""Tools for managing meta-analytic results.""" import copy import logging import os from nibabel.funcs import squeeze_image from .utils import get_masker LGR = logging.getLogger(__name__) class MetaResult(object): """Base class for meta-analytic results. Parameters ---------- estimator : :class:`...
d299adb5da75f246974d1b571d1bf933d855c83d235120f705c4a730d297e743
Python
3,379
89
import numpy as np from multiprocessing import Pool, cpu_count from discrepancy_measures import * def permuted_ND(N, all_results, distance): """ Calculate the permuted ND values by shuffling the observable_results N times. Parameters: N (int): Number of permutations to be performed. all_re...
263f34ae618b75a7ffa6cd420c4aec4d0d00909a110b2695bbabc37cfdd0301e
Python
3,380
87
import pytest import pandas as pd @pytest.fixture( params=[ (pd.Timedelta("0 days"), pd.Timedelta("1 day")), (pd.Timestamp("2018-01-01"), pd.Timedelta("1 day")), (0, 1), ], ids=lambda x: type(x[0]).__name__, ) def start_shift(request): """ Fixture for generating intervals ...
380f15eca369970dbce0345d167edcb03bbe8bb0569d04568be1883b3d291a28
Python
3,381
86
import argparse import os import shutil from Bio import SeqIO def get_args(): """ Get arguments from command line with argparse. """ parser = argparse.ArgumentParser( prog='Make-Incomplete-Contigs.py', description="""Identify long complete contigs from checkm2 scores.""") parser.add...
3de0e1393884e8cad59a110c00d76429f3f8c60439e38ceb439610b27f3682de
Python
3,381
93
#!/usr/bin/env python3 # to install: `pip3 install -e .` # to install latest from pypi: `pip3 install --upgrade --upgrade-strategy eager --no-cache-dir pheweb` # to upload to pypi: `./setup.py publish` # to update deps: `kpa pip-find-updates`, edit, `pip3 install -U --upgrade-strategy=eager .`, test # to test: `./setup...
0666e2b4f5750c6b0e2c09d5959f73e037f10e4232f5e43d23bd185ef384e994
Python
3,382
87
""" .. module:: model_manager :platform: Linux, Windows :synopsis: Manager for handling calling of DL segmentation models .. moduleauthor:: Fredrik Nysjo """ import json import sys import os import subprocess class ModelManager: def __init__(self): self.modelinfo = [] self.result_filename ...
517149f23447c3a58c2f387bead02a443034320c2ac1e5fd2f83a71835048a62
Python
3,383
100
"""Tools for managing meta-analytic results.""" import copy import logging import os from nibabel.funcs import squeeze_image from nimare.utils import get_masker LGR = logging.getLogger(__name__) class MetaResult(object): """Base class for meta-analytic results. Parameters ---------- estimator : :c...
5d5c0a0d496e15507bed51afb635cc0f499ec8d0f244fdba421a0175f7307677
Python
3,383
92
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Make noise convariance matrix from empty room data. Vinding, M. C., Eriksson, A., Low, C. M. T., Waldthaler, J., Ferreira, D., Ingvar, M., Svenningsson, P., & Lundqvist, D. (2021). Different features of the cortical sensorimotor rhythms are uniquely linked to the seve...
7e772e1d29bb5b993269ed4aafdf0f89460c2ff4415ca45dc454702123c4382c
Python
3,385
128
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.14.5 # kernelspec: # display_name: ol-connectome # language: python # name: python3 # --- # %% from pathlib import Path import sys impor...
52b9e37a36483e5a47ef6cd3bce23c53541c263116e2a1ab50a256a6ec615aea
Python
3,386
115
""" common.py Created February 17, 2021 Holds helper functions and types used throughout. """ from collections import Counter from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union from dataclasses import dataclass import numpy as np from numpy import mean, median # Ty...
6093096ef582184741180e24283522c0423b9e9b57ce017633948e52077b301d
Python
3,388
82
# Copyright 2018-2021 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...
124d31c31a69e384827398f1b68007de5c50ea06dee91004d455680c4e7521a6
Python
3,389
103
r""" General math utils. """ __all__ = ['lerp', 'normalize_tensor', 'append_value', 'append_zero', 'append_one', 'vector_cross_matrix', 'vector_cross_matrix_np', 'block_diagonal_matrix_np'] import numpy as np import torch from functools import partial def lerp(a, b, t): r""" ...
6bdfd939a9f583dbc75813d351c46ac144acfad2ab09ccc31683b51c501917e8
Python
3,389
123
# -*- coding: utf-8 -*- """ This module simply implements the `NeoPixel` class with a serial connection to the arduino that controls the NeoPixel LED ring. """ import time import warnings import serial class NeoPixel: ''' Class to control the Neopixel LED ring. Make sure the neopixels_python.ino sketch is...
7d7fb0b59e774c678321addd194ba7e6ee22ad4c09e29ee383dbf5a05db4028d
Python
3,389
119
import os import os.path import hashlib import errno from tqdm import tqdm def gen_bar_updater(pbar): def bar_update(count, block_size, total_size): if pbar.total is None and total_size: pbar.total = total_size progress_bytes = count * block_size pbar.update(progress_bytes - pb...
78c27bdab55b1eb695c5cd2ff5c5a730fde99a835b5c85a1b23cc85f26271f4e
Python
3,393
84
"""Subject-wise train/test and stratified fold creation, with leakage checks. **Documented divergence from the legacy notebook** (see `docs/legacy-notebooks-inventory.md`, `Dataset_MRI.ipynb` step 10 and open question 5): the notebooks used a fixed positional slice split (`sample[:75]`, etc.) baked into row-count assu...
3f95b05318bc8dbb86a3eb93e8c951765d7601334fb56b3bb0e7b1288bb2ef82
Python
3,395
106
""" Tests for subclasses of NDArrayBackedExtensionArray """ import pickle import numpy as np import pytest from pandas._libs.arrays import NDArrayBacked import pandas as pd import pandas._testing as tm from pandas.core.arrays import ( Categorical, DatetimeArray, NumpyExtensionArray, TimedeltaArray, ...
92325f7fd2335c96875d3c6cb340b606c4e3034de384b1535e03f1f6f9ce6239
Python
3,395
103
"""This script creates figure 1.""" import os import glmtools as glm import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde import lemon_plotting from glm_config import cfg outdir = cfg['lemon_figures'] #%% ------------------------------------------------ # Data scatter example co...
b4b49c9fa2a7568f32077c4f940dbc642a2f3c0e9e457360569d3ad355aefbd1
Python
3,395
114
import os import pandas as pd import yaml import numpy as np import shutil dataset_root = "/path/to/your/dataset" image_root = os.path.join(dataset_root, "images") export_root = os.path.join(dataset_root, "export") num_clients = 4 iid = True alpha = 0.5 seed = 0 n_classes = 4 class_names = [ "point_like_corneal_u...
2dd9a752d2aa3c3d4046003da5d1f6f77562399d33441fd2f9a33ee6a6c00d20
Python
3,396
90
#!/usr/bin/env python3 # type: ignore ''' $ wget https://github.com/PheWAS/PheWAS/blob/master/data/phemap.rda $ wget https://github.com/PheWAS/PheWAS/blob/master/data/pheinfo.rda $ r > load('phemap.rda') > load('pheinfo.rda') > write.csv(phemap, 'phemap.csv', row.names=F) > write.csv(pheinfo, 'pheinfo.csv', row.names=...
2ce045a9ebbd2860764402a58403d43c9f1d660ac9c373dc281bc41bd68f9165
Python
3,398
65
import pandas as pd import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from app import create_app, db from app.models import Subject, SourceDataset, Visit, Condition from load_db.ADNI imp...
e34c828489ad4160b81bda4ba627ad5b10950388672ffb3b90ddd0e3753c8dea
Python
3,398
100
__author__ = 'etseng@pacb.com' """ To be used to evaluate phase switching by assuming the genome is already fully "phased". For example, in Falcon-Unzip, which is pseudo-phased, there could be switching errors. Since IsoPhase only uses the primary contig (or one of the haplotypes), a switching error shows up by seein...
4bc600ccc2a105f5c90d5b682fec223e44cea4d68571ead474673edca914ee5c
Python
3,399
123
from typing import Iterable, List, Literal, Mapping, Optional, Sequence, Tuple, Union import matplotlib as mpl import numpy as np import scanpy as sc from mudata import MuData _method = Optional[ Literal["avginsertions", "logAvginsertions", "suminsertions", "logSuminsertions"] ] def _adata_insertions( mdata...
b12175385b08d18b495e90d4e037694b86927cc98b39a5a2d8e83bd55dbc802b
Python
3,400
89
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 16 20:03:05 2023 Script to download a subset of images from COS (only one image per subject). @author: Eduardo Castro """ import ibm_boto3 from botocore.client import Config from os.path import join as opj import sqlalchemy as db import pandas as...
f5d05b171b0f3446f3cd99ce0e0b3d3b0e18184cc50435352a6cf4175c48c1e5
Python
3,402
104
#!/usr/bin/python3 # post-comment.py: post standard input as a Github comment """ Post a Github comment. """ import argparse import os import sys import github def parse_args(args): """ Takes in the command-line arguments list (args), and returns a nice argparse result with fields for all the options. ...
509b888984a856f1aacf757a8de07bd4a459f402b794c8c05faef2d1b8971ed8
Python
3,403
105
# 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...
cf655a1047164fe28001266fcf5bdee350c6f024b74015c9055f3b9dd505b3a4
Python
3,403
85
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 30 10:30:42 2023 @author: nrq2 """ print("load libraries") import os import scenicplus import scanpy import pycisTopic ## 1. Initialize cisTopic object from pycisTopic.cistopic_class import * from pycisTopic.utils import * from pycisTopic.lda_models...
9dc2d878142b50cc594d8e7e5d8facc6751e2296a056f3dfc9b96e47b209a125
Python
3,405
109
#----------------------------------------------------------------------------- # Optimized Structure #----------------------------------------------------------------------------- import os import fileinput import sys import DXGB.get_pdbinfo as get_pdbinfo #### Do minimization, structure file should have hydrogen ato...
3c8a187c8a3944170e698d20f86d5937d4ac580f6673920f9dc6d9f3eb7dc136
Python
3,406
71
import scipy as sp import scipy.io import numpy as np import pandas as pd from tqdm import tnrange, tqdm_notebook import matplotlib.pylab as mpl from scipy import stats def find_sig_bins(aucs): auc_col_names = aucs.columns.str.contains('auc') low_conf_col_names = aucs.columns.str.contains('low') up_con...
bafbfddd681ba4880625fe58cf2197e7a1b58b3b1e6ba7268728f65dc37c22cb
Python
3,408
105
import pytest from pcntoolkit.math_functions.warp import * def test_parseWarpString(): warp = parseWarpString("WarpLog") assert isinstance(warp, WarpLog) warp = parseWarpString("WarpCompose(WarpLog, WarpAffine)") assert isinstance(warp, WarpCompose) assert len(warp.warps) == 2 assert isinstan...
22b09a5be3b8de674e94fea2945c21932f499db2facc1694c40228b0e50fb2f6
Python
3,409
146
""" Engine classes for :func:`~pandas.eval` """ from __future__ import annotations import abc from typing import TYPE_CHECKING from pandas.errors import NumExprClobberingError from pandas.core.computation.align import ( align_terms, reconstruct_object, ) from pandas.core.computation.expressions import norma...
00faf90635f9322cf2b09f185530c4e77bb0694fac5c60ebb11e6f32c0841fd5
Python
3,410
79
import os import sys import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import rc from pylab import rcParams from matplotlib.ticker import FormatStrFormatter # the axes attributes need to be set before the call to subplot...
2739f4233c3305feae24411fd0d7479dc3e37a2b0d57e1a1864c43aa6b4f3b41
Python
3,410
92
import os if 'PYTHONPATH' not in os.environ: print("Error: Run `source env.sh` to be able to run `/scripts/*.py`") exit(1) import cv2 import numpy as np # Super janky but makes backwards compatibility easier from ecgdigitize.vision import getLinesInDirection from ecgdigitize.visualization import * from ecgdig...
3af01b091ac662367d01881a13570dc827096f26aab10a1291b2196864d8e9ae
Python
3,411
101
from AYN_Package.DataSet.ForObjectDetection.VOC_nwpu import * from AYN_Package.Task.ObjectDetection.D2.YOLO.V4 import * from yolo_nwpu_attack.other.yolo_v4_config import * from yolo_nwpu_attack.other.yolo_v4_helper import * from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import torch import nump...
daef3c59fc25ae73296b150d6260f73d31f488c7036ae9bccbdfa85ca549d0b8
Python
3,411
69
from typing import Literal, Union import pandas as pd from med_associates_utils.session import FieldList, SessionCollection def calculate_cumulative_events(df: pd.DataFrame, event: Union[str, list[str]], groupby: Union[str, list[str]], time_key: str = 'time') -> pd.DataFrame: df = df.copy() # make a copy d...
94ba244a192f8e4c229c2f7c86b73ee28afffb478c22315de1e0aef1bf5b294b
Python
3,412
94
# Copyright 2018-2023 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...