sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
1aa0dafc46735159fdc88c3e723d482df4eb28a19dab89bf22c96afee96a3534 | Python | 1,717 | 54 | # Load the dataset
import pandas as pd
data = pd.read_csv('kaggle_parsed_dataset.csv')
# Check if the 'bullying_trace' column is present in the dataset
if 'bullying_trace' not in data.columns:
raise ValueError('The dataset does not have a "bullying_trace" column')
# Preprocess the data
# Split the da... |
5196d8429805afec6b620c543442f21e580766fa9c20dadc48f14b304ea33084 | Python | 1,717 | 73 | # Copyright 2018-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... |
6d1609ceb9256a4fa18da45fb758611bcf4899ab92b5e5a8f94c69d972a5e749 | Python | 1,717 | 51 | import os
from botocore.client import Config
import ibm_boto3
import sys
from tqdm import tqdm
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
'..')))
from app import create_app, db
from app.models import Image, SourceDataset
from config.globals impor... |
49d11d7ad375f675fde1628588d8992aea6262d0aa7ab8ed9b125522b6610e45 | Python | 1,718 | 69 | #!/usr/bin/env python3
# Note: This file has to live next to meson.build or versioneer will not work
import argparse
import os
import sys
import versioneer
sys.path.insert(0, "")
def write_version_info(path) -> None:
version = None
git_version = None
try:
import _version_meson
version... |
a055c334507d5645dd2cb75abdb2aeab1dd85b3e76aed19bc39d854576841429 | Python | 1,719 | 51 | import dateutil
import pytest
from pandas._libs.tslibs import timezones
import pandas.util._test_decorators as td
import pandas as pd
class TestTimestampTZConvert:
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
def test_astimezone(self, tzstr):
# astimezone is an alias for ... |
a7ed9ecd5b8a14d18a5e10c120b4f7692b9414760ecca4e47dd2c60ad87b005c | Python | 1,721 | 80 | from defs import *
from values import *
import numpy as np
import math
def calculate_conduct(cell):
gf_star = 59 #ps
gs_star = 29 #ps
ph = np.zeros(NC)
if cell.segment == 'DCT':
for j in [0,1,4,5]:
ph[j] = -np.log(abs(cell.conc[11][j])/1.0e3)/np.log(10.0)
else:
for j in... |
c6bcff44d3ea75856e7efd2d8fa5e47f75b6e5a64c81f709825270d19eb75307 | Python | 1,721 | 49 | #!/usr/bin/env python
import os, glob, pdb, argparse, sys
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--suffix', '-s', type=str, required=True)
print(' '.join(sys.argv))
args = parser.parse_args()
return args
def get_dicts(lines):
rec2text = {}
for l in lines:
... |
3a25e8f2133728df66cbb143890c2eff1d035d67e8efcc2a508a881afcd04700 | Python | 1,723 | 58 | """Sphinx extension for listing code contributors to a release.
Usage::
.. contributors:: v0.23.0..v0.23.1
This will be replaced with a message indicating the number of
code contributors and commits, and then list each contributor
individually. For development versions (before a tag is available)
use::
.. co... |
5c9b97aaef11b80ce1b96b69c59308fa938f32a02a58b236ca7936464a1854af | Python | 1,723 | 48 | import sys
import re
import numpy as np
import pandas as pd
import librosa
import argparse
argparser = argparse.ArgumentParser('''
Utility for computing sound power metrics from pre--Dr. Who audio stimuli
(Tree, Jeanne, Dinner)
''')
argparser.add_argument('audiofile', help='Paths to audio file for proc... |
9cac1a690f674bfe669394fd4fcfb882c9d210e00f54eb89cb31aea4271f75d7 | Python | 1,723 | 44 | import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
import os
import subprocess
def r_package_installed(package_name):
try:
importr(package_name)
return True
except:
return False
def call_import_infreps(args):
try:
import rpy2
except ImportError:... |
f27eea9cb6e015a35d4b126169192740ae2ea9d25d94eb2fa7f1cf148ba1870a | Python | 1,723 | 32 | import single_cell_analyzer as sca
def silence_synapses_by_somadist_and_spike_source(cell, evokedNW,
soma_dist_ranges = None,
spike_sources = None):
'''silences synapse activation at a somadistance (specified in soma_dist_rang... |
44726defecc1d4d708f5237fd8efa4aa3276a4a5ea87af0b152232cc9fddae5e | Python | 1,725 | 46 | # MIT License
#
# Copyright (c) 2020 Gabriel Nogueira (Talendar)
# Copyright (c) 2023 Martin Kubovcik
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without ... |
80aae5dcd08589fe3b2c07a762bcf36f44d18fbe63ab82d1e202c4ae16b462e9 | Python | 1,725 | 59 | '''
This module deals with API changes in 3rd party modules.
The following 3rd party modules are used: pandas, dask, distributed
'''
import six
import cloudpickle
# try: # new dask versions
# synchronous_scheduler = dask.get
# except AttributeError: # old dask versions
# synchronous_scheduler = dask.async.get... |
a1352a14103066f9e54d8f712ed63a7830f90f0b953edb56492e70a52acffe76 | Python | 1,725 | 50 | import argparse
import glob
import os
from nltk import Tree
from strip_functional import preprocess_trees
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--file_root", type=str, default="data/npcmj")
parser.add_argument("--save_root", type=str, default="data/npcmj_preprocessed")
parser.... |
2c5e78351636bcdaf52bdb2dc0ef58f6905452d2284547c6059fb877fe90dba5 | Python | 1,726 | 69 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_mask():
# compare with tested results in test_where
s = pd.Series(np.random.default_rng(2).standard_normal(5))
cond = s > 0
rs = s.where(~cond, np.nan)
tm.assert_series_equal(rs, s.mask(cond))
rs = s.... |
ff19fba21ae6011a0b25313a955d9c33d10ccfc5705ca48d7a777946da8f0878 | Python | 1,726 | 51 | import os
from datetime import datetime
import csv
class SubmissionWriter:
""" Class for collecting results and exporting submission. """
def __init__(self):
self.test_results = []
self.real_test_results = []
return
def _append(self, filename, q, r, real):
if real:
... |
4388144ee5d4169764cef93af6e813eda1c7418fde65a5e12dd015420956426f | Python | 1,727 | 51 | import numpy as np, matplotlib.pyplot as plt
import os, sys, json
import pumpprobe as pp
merge = "--no-merge" not in sys.argv
print("Merge:",merge)
folder = "/projects/LEIFER/francesco/simulations/activity_connectome_sign2/"
print("using",folder)
print("merging" if merge else "not merging")
funa = pp.Funatlas(merge_... |
6a29eb8996bfc2a2d799282851f6d23fbe446a9e743ad1aeb8031026c101183c | Python | 1,728 | 31 | # SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... |
a0751f9aa6d418d55b43d7917ccffb5ab36b7b5e19e075021a90bc5fc2a7fd99 | Python | 1,728 | 63 | #!/usr/bin/env python
import windseer.utils as utils
import windseer.nn.models as models
import os
import torch
def load_model(directory, version, dataset, device, eval=True):
'''
Load a neural network together with the corresponding weights.
Parameters
----------
directory : str
Model ... |
07baf6477c8249ec00726033b64379ae4837f4572be46f3eb61c1a6dd402a844 | Python | 1,730 | 52 | from Environment_ui import *
class ConfusionMatrix(object):
def __init__(self, num_classes):
self.num_classes = num_classes
self.mat = None
def update(self, a, b):
n = self.num_classes
if self.mat is None:
self.mat = torch.zeros((n, n), dtype=torch.int64, device=a.d... |
0a49728696cb7144398ca9fb1bfd7df728c4dab26f3d5cb3b1d895c340e60037 | Python | 1,730 | 65 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 28 12:23:34 2022
@author: jeanbaptiste
"""
import pickle
import numpy as np
import matplotlib.pyplot as plt
import deepcellcontrol as dcc
sets_folder = "D:/shared_packages/deepcellcontrol/assets/data/experimental/"
training_files = (
sets_... |
f45e1362f1f2a109d9aa242ab7051d14b00d553728e3b2684cb6bb76fd471f70 | Python | 1,730 | 70 | import sys
from graphviz import Digraph
import genotypes
def plot(genotype, filename):
""" Plot the graph of a given genotype """
g = Digraph(
format='pdf',
edge_attr = dict(fontsize='20', fontname="times"),
node_attr = dict(
style='filled',
shape='rect',
... |
3ba09c4b7d8c9c583e190455be46308f2a8fd73574024938ee30a33fc546c325 | Python | 1,731 | 52 | import pandas as pd
import numpy as np
from pathlib import Path
import re
def load_and_prepare_data():
"""Prepare data from different sources and compose them for julearn.
Returns
-------
prediction_data : pd.DataFrame
The data to be used for prediction.
features : list of str
The... |
e186c94562eb681708b4c1ead1d2312eb9307d9a8b3bbeb52007a5d5b49b6d9b | Python | 1,732 | 47 | import os
import re
from .DropDownMenu import DropDownMenu
class SelectAcqLab(DropDownMenu):
"""
A dropdown menu widget for selecting acquisition labels.
"""
def __init__(self, default_msg):
super().__init__(default_msg, help_text="Here you need to choose the acquisition label")
def init... |
41daa1b00ac371a28df621ed8666559a6c8e03a9f33024a84203c7f68b27b9d9 | Python | 1,733 | 68 | import os.path
import random
import cv2.cv2
import numpy as np
import torch
import matplotlib.pyplot as plt
import wandb
def set_seed(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.dete... |
a49068f274f1b68789162c4c558b9a8378fc6e62688f013d6450fadb6a816986 | Python | 1,733 | 48 | '''
autor: arco
date: 16.09.2016
'''
import numpy as np
from ._decorators import return_figure_or_axis
class PixelObject():
'''holds all the information necessary to reconstruct a plot out of an array'''
def __init__(self, extent, fig = None, array = None):
s = "either fig or array has to be specified"... |
6f0a6d1f31aae1beb78cef680e1e11166d9d4c1a6fbf6c0ae6114805a860640c | Python | 1,734 | 69 | class Config():
def __init__(self) -> None:
self.defaultConfig()
pass
def defaultConfig(self,):
self.displayINFO()
self.subINFO()
self.expINFO()
self.connectINFO()
pass
def subINFO(self, personName='Oser', age='21', gender='m'):
... |
f30c1387e858e0f75a97be6711814e05ca2b5af3001d6f44074b1440c2515ae2 | Python | 1,734 | 43 | import pandas as pd
import numpy
trustedSource = ['A', 'B']
human = 9606
omnipath = pd.read_csv('annotation/omnipath_webservice_interactions__recent.tsv', sep='\t', low_memory=False)
humanFilter = omnipath['ncbi_tax_id_target'] == human
omnipath = omnipath.loc[humanFilter, :]
#Only in dorothea
omnipathFilter = omnip... |
1c555a75233ae7342a542d436ecbf2cf519af183e614fdf05a493bda9bc35fbd | Python | 1,735 | 71 | #
# protein_list.py -- Michael Pun -- 12 May 2021
#
# Take a directory of pdb files as an argument and output an hdf5
# file with a list of the protein names as the dataset.
#
# This hdf5 file will serve as the foundation for the dataset
# and will later contain lists of high resolution structures
# and splits for tra... |
69ee0452d59d45d41a908167fac381b18a19f4ee489628a8dac4f535a044d5f8 | Python | 1,735 | 41 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ChannelAttention(nn.Module):
def __init__(self, in_channels, reduction_ratio=16):
super(ChannelAttention, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear... |
03beab249129d8bdcbcfdef15f0243836c9bcb2d4ebbeaef02ebad3d4dcdecca | Python | 1,736 | 52 | #
# naming.py -- Michael Pun -- January 2021
# Conventions and functions for naming the following types of data files:
# - spherical projections of residue neighborhoods
# - training logs from equivariant neural networks
# - equivariant neural network weights
#
def get_id_from_params(args,ignore_params):
params... |
122ffa6ca3d99f4ae1c9dfb7e193894f7cbdb268dc0988f2e57c3e58163e5361 | Python | 1,736 | 50 | # 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... |
382c44f2086a242e4b57e1b29546ca543f947d43fa99bfa76b35a6f872b7a1b7 | Python | 1,736 | 48 | from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Kernel, RBF, ConstantKernel, DotProduct
import sys
class GPR(GaussianProcessRegressor):
""" interface to sklearn GaussianProcessRegression"""
def __... |
df3169efb480bf463d2250cc77b11bf19b23de2ba5a68d430c7c66bb03f5f7fc | Python | 1,736 | 44 | import torch
import torch.nn as nn
from .GraphSAGE import GraphSAGE
from .gsl_model import gsl_model
from dgl import mean_nodes
class Classifier_model(torch.nn.Module):
def __init__(self, params):
super().__init__()
self.params = params
self.global_graph = params.global_graph
self.n... |
becefca4b49e3c1e868d827acf1e96ee0d77270aefb3f44176b97e63682be138 | Python | 1,738 | 56 | __all__ = ["GlycoPeptideSpectralLibraryHdf"]
from types import MappingProxyType
from typing import Optional
import pandas as pd
from ..common.speclib import Columns, Indices
from ..pep import PeptideSpectralLibraryHdf
from .abs import GlycoPeptideSpectralLibraryBase
class GlycoPeptideSpectralLibraryHdf(
GlycoP... |
cedf82be72979b6ee9ed8fb823bd796794297f666b6ad72ebbe4058b38ceb953 | Python | 1,738 | 60 | from sklearn.linear_model import BayesianRidge, ARDRegression
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.svm import LinearSVR
from xgboost import XGBRegressor
from sklearn.dummy import DummyRegressor
from src.config_handler import read_yaml, get_entry
from src.step_factory import StepFa... |
5555d92b0c7f04b3685c7c850567be96f7448f615e206311471f66946c75a7f0 | Python | 1,739 | 43 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for GCPNet (https://github.com/BioinfoMachineLearning/GCPNet):
# ----------------------------------------------------------------------------------------------... |
ec578f85b9bd6df9655c9e928b7450ff8682b25efdddc17ede0b276fe9e12402 | Python | 1,739 | 42 | # -*- encoding: utf-8 -*-
import os
from decouple import config
"""
neuro-app settings, example in Linux
"""
# LOG_FOLDER= config('LOG_FOLDER', default="./logs/" )
# SLICER_ROOT = config('SLICER_ROOT', default="./programs/Slicer-4.8.1-linux-amd64" )
# DCM2NIIX=config('DCM2NIIX', default="./programs/dcm2niix/dcm2nii... |
cb3dc70c42c62911288f2af853155bb0e0caf43b9538865e60fe1c550b330aa6 | Python | 1,740 | 55 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
"""
.. _annotations_tfidf:
===========================
Simple annotation from text
===========================
NiMARE contains a function for simple term count or tf-idf value extraction
from te... |
49f930b16ead8fdfb2b0a0bec855a84785e598bb8f8e68c4890475488d514787 | Python | 1,741 | 45 | """Shared, non-fixture test helpers for lightning_pose.api.model tests.
Split across two test files that mirror the source split between `model.py` and
`model_runtime.py`: `test_model.py` (construction/predict_*) and
`test_model_runtime.py` (compile/export/onnx/tensorrt). `_setup_test_model` is used
by tests in both f... |
9344c403ab95e1cf69caed62daf119593b48836d9f89bd4c46e8ecf249ebd2db | Python | 1,741 | 43 | __author__ = "etseng@pacb.com"
"""
Tagging BAM files with phasing info
"""
import pysam
from csv import DictReader
def main(read_bam, hap_info, output_bam, celltype_file=None):
d = {}
celltype_info = {}
#for r in DictReader(open('phased.partial.cleaned.hap_info.txt'),delimiter=','):
for r in DictRea... |
d3aae1dc3697b9acecca04c94c6683a935eac7962fbb147febd54d75fc7f86d8 | Python | 1,741 | 45 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
import read_grd
subsample = 1
xy_grade = 5.0
z_grade = 8
in_buff = -0.2 # Positive will shrink by x, negative will enlarge by x ratio of dx
file_dir = '../data/'
infile = file_dir+'Bolund'
x, y, Z = read_... |
334a33e0bbbd33b72ce5221f34811881f9ceedb51d4e746c1a31737b7aa82008 | Python | 1,742 | 50 | """MR noise measurements class."""
from collections.abc import Callable
from pathlib import Path
import ismrmrd
import torch
from einops import repeat
from typing_extensions import Self
from mrpro.data.acq_filters import is_noise_acquisition
from mrpro.data.Dataclass import Dataclass
class KNoise(Dataclass):
"... |
e3632c1717449e9f0f6b69d9df73513f2634897f93b1232612a629d84b06f80b | Python | 1,742 | 30 | """Cache the OpenStreetMap standard tiles behind the Zimbabwe locator panel.
Tiles are fetched once at zoom 7 and reused, following the OSM tile usage policy
(identifying user agent, no bulk download). Map data © OpenStreetMap contributors,
ODbL; the attribution must accompany any figure that shows these tiles.
"""
fr... |
6874de52d70cb064c89f3d46fdbd3a0b2bb406b8db9b35057fd78a5c687d7f5e | Python | 1,744 | 50 | import numpy as np
import pandas as pd
import pandas._testing as tm
class TestJoin:
def test_join_outer_indexer(self):
pi = pd.period_range("1/1/2000", "1/20/2000", freq="D")
result = pi._outer_indexer(pi)
tm.assert_extension_array_equal(result[0], pi._values)
tm.assert_numpy_arr... |
c3cc21bfa7f1fd4bb45c6b8181aa130d45351d278aaafb1e2a342761c5581793 | Python | 1,745 | 66 | # -*- encoding: utf-8 -*-
# JN 2014-12-14
# function to plot heatmaps of clusters
from __future__ import absolute_import, division, print_function
import logging
logger = logging.getLogger(__name__)
import numpy as np
from matplotlib.pyplot import cm
cmap = cm.Blues
# idea taken from http://stackoverflow.com/a/1477... |
42b76ab6b30022c90a55bd5ea75a267073365edffcde55fadf0edc237c19ea72 | Python | 1,746 | 43 | #!/usr/bin/env python
__author__ = 'etseng@pacb.com'
"""
Wrapper for running STARlong.
Parameters are pre-set according to:
"""
import os, sys, subprocess
import tempfile
import shutil
CMD_STARlong = '/home/UNIXHOME/etseng/software_downloads/STAR-2.5.3a/bin/Linux_x86_64/STAR --runMode alignReads --outSAMattributes N... |
0266c6b09b8b3dda1cb0fb7319d8be8251fdb0138e7a6fce614793e34f03677e | Python | 1,747 | 50 | """Tests for k-space prewhitening function."""
import pytest
import torch
from einops import rearrange
from mrpro.algorithms.prewhiten_kspace import prewhiten_kspace
from mrpro.data import KData, KNoise, KTrajectory
from mrpro.utils import RandomGenerator
def _calc_coil_cov(data):
data = rearrange(data, '... coi... |
b8c9fff8f7189ec22c70e9f64419d2eab88699099fdfeeb1bc595c04fa0682c7 | Python | 1,748 | 57 | """
python roi_lut.py --roi_file .\data\rois_fs.json --save_dir .\data --name fs
"""
#%%
from pathlib import Path
from src import fs_roi_lut
import argparse
# %%
name = 'fs'
LOCATION = Path(__file__).parent
data_dir = LOCATION.parent.parent / 'data'
save_dir = data_dir / 'derivatives'
roi_file = data_dir / f'rois_{nam... |
d087d402aa769351e5021a150d0723a1be5977a5cfc76b9d9774058e70a79ada | Python | 1,748 | 58 | """Shared pytest fixtures for the scsims test suite."""
from __future__ import annotations
import warnings
import numpy as np
import pytest
# Suppress the firehose of FutureWarning / DeprecationWarning that scanpy,
# anndata, lightning and friends emit on every import. We're not testing
# upstream library hygiene ... |
1e67b4ae927ef943931bd59a1bb11cc9dfee9b95669e8660410044a943769260 | Python | 1,749 | 72 | #%%
import json
import yaml
#%%
def read_json(json_file):
"""
Reads the paths from a json file.
args:
json_file: json file to read from
returns: dictionary of paths
"""
with open(json_file, 'r') as f:
paths = json.load(f)
return paths
def write_json(json_file, dict_to_write)... |
70b9fbf0da823a2401216561a4bb019ecea87077d571903d3b6db92eceeec1c5 | Python | 1,750 | 63 | """Identity Operator with arbitrary number of inputs."""
import torch
from typing_extensions import Self
from mrpro.operators.EndomorphOperator import EndomorphOperator, endomorph
class MultiIdentityOp(EndomorphOperator):
r"""The Identity Operator.
An endomorph Operator that returns multiple inputs unchang... |
ec60bdfa0a665ffaada3e650d9bad4a607f2302c9b2573d9fba7f8f4a31c471f | Python | 1,751 | 56 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import twixtools
import json
import sys
def main():
parser = argparse.ArgumentParser(description="Output the header of a .dat file")
parser.add_argument("datfile", type=str, help="Path to .dat file")
parser.add_argument("--out", type=str, help... |
54e89450d1ef9a1a13cab0273cb9a1e13c27b16d3c82c5bb5cbe8bd26d7357b2 | Python | 1,752 | 47 | import sys
import pandas as pd
import csv
sents = []
sentid = 0
sentpos = 0
for line in sys.stdin:
line = line.strip().replace(' --', '--').replace('N. Y.', 'N.Y.').replace('N. H.', 'N.H.').replace('"', "'").split()
if line:
for word in line:
if word != "--'":
if word == 'Re... |
ea6589509f87d57be2b1ac3fb6747732ac13b3b1661a8c30c6cdab612a8ce881 | Python | 1,752 | 61 | """Transforms for gradec."""
import numpy as np
from neuromaps import transforms
from nilearn import image
from gradec.utils import _rm_medial_wall, _zero_medial_wall
# Number of vertices in total without the medial wall
N_VERTICES = {
"fsLR": {
"32k": 59412,
"164k": 298261,
},
"fsaverage... |
2be0e0813bf1d93281f31922b2be98e18feb9bbe5219f0493e92d4c5848da71d | Python | 1,753 | 50 | import os
import matplotlib.pyplot as plt
def saveConfig(path, args):
with open(os.path.join(path, "configs.txt"), 'w', encoding="utf-8") as f:
f.write(f"model: {args.model}\n")
f.write(f"datapath: {args.datapath}\n")
f.write(f"weights: {args.weights}\n")
f.write(f"savingPath: {arg... |
45b87c8b139f2b2daf47048170f3af8de55dda23cdcf972b7e75a7d972b9684b | Python | 1,754 | 52 | import numpy as np
import pytest
from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
import pandas._testing as tm
def test_cast_1d_array_like_from_scalar_categorical():
# see gh-19565
#
# Categorical result fro... |
6f6c7c8b246c25ab0e77f2a77240e0f7c738900c24e2a31942cf0f4c399d843a | Python | 1,754 | 50 | """
Generate a msgpack file, _chinese_mapping.msgpack.gz, that maps Traditional
Chinese characters to their Simplified Chinese equivalents.
This is meant to be a normalization of text, somewhat like case-folding -- not
an actual translator, a task for which this method would be unsuitable. We
store word frequencies us... |
54c65388850c0fac4b71ab036c96f2538aaecffe63685c2a596c849545bd2f70 | Python | 1,755 | 60 | # Copyright 2018-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... |
ea620b21e770332e6be9e4b30624026d28f6920b9518e4378bdd8a09a8315b43 | Python | 1,755 | 51 | """PyCaret 4.0 introspection API — designed for the React UI and LLM agents.
This package is the *typed, side-effect-free* view of the engine. It lets an
external process (a UI server, an LLM agent, a docs generator) answer
questions like:
- What models does PyCaret support for classification?
- What are the hyperpar... |
1a567850ecc8b8ad3c554a2e8de562ac43fa88bb92bb127bcace084c981c5cbe | Python | 1,756 | 57 | """This script produces a table summarising the preprocessing outcomes."""
import os
import mne
import numpy as np
import osl
import pandas as pd
from glm_config import cfg
#%% --------------------------------------------------------------
# Find preprocessed data
proc_outdir = cfg['lemon_processed_data']
fbase =... |
b1b1fa0065a3b5a24b064d0d8b92e0a6e3e1cdff4e9a9da1213a2c43ca11da82 | Python | 1,756 | 52 | # 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... |
d32788c1cf8065ede2c1be813b5fde54efc07fae337936a2e9a264a1671f49f1 | Python | 1,756 | 59 | from __future__ import annotations
import warnings
from pandas.compat._optional import import_optional_dependency
from pandas.util._exceptions import find_stack_level
from pandas.util.version import Version
# https://github.com/pandas-dev/pandas/issues/65408
# Avoid bad numexpr binaries producing incorrect results
... |
d6fbf7939c9d9d08d8f81a74e00390094e01d30f07a37ad5f00b307c481f2dcc | Python | 1,756 | 38 | from subprocess import check_output, CalledProcessError
# Hyper-parameters
table = "lstm_tuning"
target = "dspln_PSYCHIATRY_60"
# Do we need bidirectional? Is it working wit bool?
num_layers = [1]
hidden_dim = [512]
dropouts = [0.1, 0.2, 0.3]
embed_droprates = [0.1, 0.01, 0.001, 0]
wdrops = [0.01, 0.001, 0.0001, 0]
lr... |
e76d6989ec61afdca239c0e866a2733a0f144a7c118bca1ca379aeaee18fbf84 | Python | 1,756 | 70 | import vegas
import gvar as gv
from outputsplitter import log_stdout, unlog_stdout
gv.ranseed(1235)
log_stdout('eg7.out')
# multi-dimensional Gaussian distribution
g = gv.BufferDict()
g['a'] = gv.gvar([2., 1.], [[1., 0.99], [0.99, 1.]])
g['fb(b)'] = gv.BufferDict.uniform('fb', 0.0, 2.0)
# integrator for expectation ... |
4d49fcb2ec388660ffe896c60e9a9daae7824bf0aabae4f600baeb64876a9a33 | Python | 1,757 | 46 | import os
import numpy as np
import tensorflow as tf
import protein_holography.network.hnn as hnn
import protein_holography.network.linearity as linearity
import protein_holography.network.nonlinearity as nonlinearity
# load clebsch gordan coefficients
cg_file = 'CG_matrix_l=5.npy'
cg_matrices = np.load(cg_file, all... |
eed84b0de75791dfb19dd154e375327c2c651b34489e172c2ce84418fe0d3f11 | Python | 1,757 | 32 | # SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... |
b3c07140c8da70e6240a71262ac1549e2c4254360ca5e7da07aa99bfcd34c019 | Python | 1,759 | 32 | # SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of sourc... |
66b1182669a7f18c4c528ec5ea359d13ed83e2c9a30b8462e675efdb2755b360 | Python | 1,760 | 49 | 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
rc('font',**{'family... |
cd93b6f0e4303809056e144ab65e616db933c293e1db8450086160ff76bd89b2 | Python | 1,761 | 34 | import numpy as np
import scipy.io as scio
from scipy import sparse
#>>> np.concatenate((a,b),axis=1) #axis=1表示对应行的数组进行拼接
if __name__ == "__main__":
# 权限
filename1 = scio.loadmat(r"/sub_datasets/dataset8/dataset8_mat/lda_permission_8.mat")['permission']
# 权限类型
filename2 = scio.loadmat(r"/sub_da... |
2dd325b4b8b30d47d64b132ecd1dc8540ed5c44fbb51e2fb78db4141ebbfdbcf | Python | 1,762 | 39 | import numpy as np
import time as clocktime
import os
################################################################
################################################################
N = 1000
pi = np.pi
##########################################################
ttot = 100.0
############################################... |
28d4eb5181c078a300c4ac583b8f9f04f537f610ccfb9116efb5e9c26cc2002a | Python | 1,764 | 52 | """Load vision encoder from Facebook SAM 2 model using HuggingFace."""
import logging
import torch
import torch.nn as nn
logger = logging.getLogger(__name__)
# to ignore imports for sphinx-autoapidoc
__all__: list[str] = []
class VisionEncoderSam2(nn.Module):
"""Wrapper around HuggingFace's SAM2 Hiera vision ... |
95d4943a7e4367c5d7a50ce5b30f144d4d7d9876c8f41b47c4f71ebcec5510f5 | Python | 1,764 | 56 | # 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... |
27e696ba436b96ccd08ef8e7c7da8b055a03515afb2459382578dcc69a75cc61 | Python | 1,765 | 35 | from __future__ import print_function
import numpy as np
import argparse
def abl_k_eps(U_ref, z=100.0, Z_ref=20.0, z_0=0.1, z_ground=0.0, kappa=0.41, C_mu=0.09):
# This is from the boundary layer calculations, but the numbers seem low...
U_star = kappa*U_ref/(np.log((Z_ref+z_0)/z_0))
k = (U_star**2)/np.sq... |
d2e391803a5df1b2f3b22f9f0e2b388b7d260c19c469de0b66051c676a0087c6 | Python | 1,765 | 64 | """
Shared helper functions for plotter-related tests
"""
import numpy as np
import xarray as xr
from pcntoolkit.normative_model import NormData
def create_test_data_with_z(
n: int = 20,
seed: int = 0,
) -> NormData:
"""Build a tiny NormData that already contains Z-scores, so there is no
need to fit... |
13c1b7447264ee86662d002184be9fbc7ece332669dc250339859490cb30b69b | Python | 1,767 | 70 | """
ipython analogue:
tr = TimeIntsToPydatetime()
mi = pd.MultiIndex.from_product(
tr.params[:-1] + ([str(x) for x in tr.params[-1]],)
)
df = pd.DataFrame(np.nan, index=mi, columns=["mean", "stdev"])
for box in tr.params[0]:
for size in tr.params[1]:
for tz in tr.params[2]:
tr.setup(box, si... |
225ea2a4d447bebae4111ffb06b9d05e0dc753c87da5efb95425d6a832849fd4 | Python | 1,767 | 49 | """
Tests for the deprecated keyword arguments for `read_json`.
"""
from io import StringIO
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
from pandas.io.json import read_json
def test_good_kwargs():
df = pd.DataFrame({"A": [2, 4, 6], "B": [3, 6, 9]}, ... |
6116b683f089a3616f88f42eea02c08f5ce9fca326bed3e71ae35ebf7f63a63e | Python | 1,768 | 64 | import numpy as np
import matplotlib.pyplot as plt
from msmfcode.core.logging import log
from msmfcode.models.cann import ContinuousAttractorNetwork, FMSMF, VariableCAN
ROW = 0
COL = 1
def pop_decoding(net: ContinuousAttractorNetwork, plot_result: bool, decoding_threshold=None):
"""
:param decoding_thresho... |
5bc655329bfeaf05f6f74ee1cf44075983a387c951669e2e2913aa2f97dbf243 | Python | 1,770 | 55 | from numpy import zeros, arange
from scipy.interpolate import make_interp_spline
def upsample(data, factor):
"""
upsample array of data by a given factor using cubic splines
array.shape is assumed to be (num_events, num_values_per_event)
"""
# vpe is values per event
num_m, num_vpe = data.sh... |
1b504ee4cdaafe7825aa61d532a368c4974f798d885e77e5d921d508146f82ac | Python | 1,772 | 58 | from cmath import sqrt
from numpy import random
import math
class viewContainer():
# container 应该包含所有刺激所需的要素
def __init__(self, config) -> None:
# w 代表window,所有的刺激都要在win上显示
self.w = None
# displayFrame是呈现最终结果的刺激帧
self.displayFrame = None
# frameSet是ImageStim... |
60574c78142520fb24176d4e43399665cf07ac7ea0c67c7a8dcdf9d71d9b3f7e | Python | 1,772 | 50 | #!/usr/bin/env python
# encoding: utf-8
import os
import unittest
from kcsd import sKCSD, sample_data_path
from kcsd.sKCSD_utils import LoadData
try:
basestring
except NameError:
basestring = str
n_src = 5
class testsKCD(unittest.TestCase):
@classmethod
def setUpClass(cls, n_src=5):
... |
258505294539bb036f3d7fcfb0ba5250629472c905a4c1dc85dc83f7905b80b8 | Python | 1,773 | 55 | from setuptools import setup, Extension, find_packages
from codecs import open
from os import path
import warnings
package_name = "qbiome"
example_dir = "examples/"
example_data_dir = example_dir + "example_data/"
version = {}
with open("version.py") as fp:
exec(fp.read(), version)
here = path.abspath(path.dirna... |
c2227335c489262be33c6f05d5609dd4ef388b798ccdcdd86053b42659b8f340 | Python | 1,773 | 44 | """main.py"""
import argparse
import numpy as np
from digit_solver import Solver
def main(args):
seed = args.seed
np.random.seed(seed)
data = Solver(args)
data.create_train_set()
data.create_generalisation_set()
if __name__ == "__main__":
parser = argparse.ArgumentParser(descripti... |
043836e2dcc6fbd31aa973636fa204d99544690a2507c592fa944ea9920580d4 | Python | 1,774 | 70 | import numpy as np
import pytest
from pandas._libs.tslibs import (
Period,
to_offset,
)
@pytest.mark.parametrize(
"freqstr,exp_freqstr",
[("D", "D"), ("W", "D"), ("ME", "D"), ("s", "s"), ("min", "s"), ("h", "s")],
)
def test_get_to_timestamp_base(freqstr, exp_freqstr):
off = to_offset(freqstr)
... |
8af4a3db4b7331e07963c715ad00b4f8d8c99fc3feffc0b7b40252175c8cf91c | Python | 1,776 | 61 | from abc import ABCMeta, abstractmethod
import os
import numpy as np
class BasicAnalysisProcess:
def __init__(self) -> None:
pass
@abstractmethod
def initial(self, controller=None, config=None, streaming=None, messenager=None):
# 3 essentials: controller, config, and data str... |
3120be4a0146f5b82d511a0e5128b2ada8a900897fa8481f6ca5650987f3b325 | Python | 1,778 | 54 | """Engine-introspection proxy routes.
Thin wrappers over ``pycaret.api`` — the React UI / LLM agents hit these to
render forms and dropdowns without shipping a Python runtime to the browser.
"""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, status
from pycaret.api import (
desc... |
bd5c3e276daef35c4bf92b5deea85707083207ed59a29283d6fbf0818ee13885 | Python | 1,778 | 55 | # 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... |
06ef86267a6b6775834458213d1ca7099ea9447de917ba3b51b8d750a86da2f3 | Python | 1,779 | 58 | import pytest
from pcntoolkit.dataio.norm_data import NormData
from test.fixtures.data_fixtures import *
"""
This file contains pytest fixtures for generating NormData objects in the PCNtoolkit.
The fixtures defined here include:
1. NormData objects from numpy arrays
2. NormData objects from pandas DataFrames
These... |
3ba6d7fe1adda56bf81eed5de13b9db80cd3773c88f5423b433cf3e49c6faed5 | Python | 1,781 | 67 | """This script will download the raw EEG data from the MPI-Leipzig_Mind-Brain-Body-LEMON dataset.
This can be run once before the start of any analyses. It can be skipped if the
data are already present on disk in BIDS format.
"""
import os
import urllib.request
from pathlib import Path
import bs4
import requests
... |
93ad457f579a4b1bc75478054fc5c8a466e030df07066387e94bbbd2a0dcb108 | Python | 1,782 | 48 | """Test the averaging operator."""
import pytest
import torch
from mrpro.operators import AveragingOp
from mrpro.utils import RandomGenerator
from tests.helper import dotproduct_adjointness_test
def test_averageingop_adjointness() -> None:
"""Test the adjointness of the averaging operator."""
rng = RandomGe... |
964120c72e6429a036ad4ed7a567d281de2fb1071552bdcd76e75dbddfd24e9e | Python | 1,783 | 83 | from pandas.core.dtypes.common import (
is_any_real_numeric_dtype,
is_array_like,
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_complex,
is_complex_dtype,
is_datetime64_any_dtype,
is_datetime64_dtype,
is_datetime64_ns_dtype,
is_datetime64tz_dtype,
is_dict_like,
is_... |
a77c64e2f44ebe80087e12162c2d8fb64326e3954f54e4c46e15492778570b65 | Python | 1,783 | 52 | import torch.nn as nn
from tnn.layers import ResidualLayer, AntiSymmetricResidualLayer, HamiltonianResidualLayer
class ResNet(nn.Module):
def __init__(self, width, depth, h, activation=None, bias=True, device=None, dtype=None):
factory_kwargs = {'device': device, 'dtype': dtype}
super(ResNet, sel... |
0b80c569823640ef4679879caa9be28f6f7aeca347f5500479e0f28bcc98a345 | Python | 1,784 | 54 | import glob
import os
import tdt
from tqdm.auto import tqdm
from .session import SessionCollection, Session
def parse_tdt_directory(path: str, pattern: str = "*", quiet: bool = False) -> SessionCollection:
"""Parse a directory containing data tanks from TDT
Parameters:
path: path to directory containin... |
294b7f3643d21700400822093ad271a48e50e5402d13d45d06cada2f2a2d6ea1 | Python | 1,784 | 43 | import torch
import numpy as np
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, obs_dim, buffer_size, device):
"""Initialize a ReplayBuffer object.
Arguments:
buffer_size (int): maximum size of buffer
"""
self.states = tor... |
4091eb5acb7c54bf0a0819a82719cdc5642afc6811eed9bc2ae4b035dc974783 | Python | 1,784 | 47 | import os
import numpy as np
import nibabel as nib
from src.nexi.estimate_nexi_noiseless import estimate_nexi_noiseless
def test_estimate_nexi_noiseless():
np.random.seed(123)
if not os.path.isdir('tests/nexi/data/nexi'):
os.mkdir('tests/nexi/data/nexi')
estimate_nexi_noiseless(
'tests/nex... |
5c8a059d80ee5741efd3918fb12e571ea699f6646d68f670c8d18761e9c7e2b2 | Python | 1,784 | 53 | """session 27: trial kind + parent_trial_ids (follow-on action lineage)
Revision ID: e5f6a7b8c9d0
Revises: d4e5f6a7b8c9
Create Date: 2026-05-11 20:00:00.000000+00:00
Trials gain two columns:
- ``kind`` — what the trial *is* (``compare``, ``tuned``, ``ensembled``,
``blended``, ``stacked``, or ``manual``). Defaults ... |
8d193f265ad195c246b0e718422df3512f27f863fe180074e96dabcf65f40e51 | Python | 1,785 | 60 | class KwargsParser():
'''
Class to handle the kwargs parsing.
'''
def __init__(self, kwargs, name=None):
'''
Class initializer
Parameters
----------
kwargs : dict
Input kwargs
name : str or None, default: None
Used when printing w... |
c36f80e84961493ef885faf8502e0c52944e92ddb2de3ac28f35d0fe2b7d9737 | Python | 1,785 | 52 | # Ported from the Isaac Lab rl_games integration (isaaclab_rl); original DexPBT
# implementation from NVIDIA-Omniverse/IsaacGymEnvs (https://arxiv.org/abs/2305.12127).
# Copyright (c) 2022-2026, The Isaac Lab Project Developers.
# SPDX-License-Identifier: BSD-3-Clause
import random
from collections.abc import Callable... |
34378e4673ff5e563dadb4214c3e214e39e7006c41c749e0ff7c02b16d78baa5 | Python | 1,786 | 51 | # 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... |
2ede90a86b653048dc7d2d489edc07c9bed9df1d2118bdc0c6c23ad06d18f612 | Python | 1,787 | 58 | #%%
from src.data_wrangler import DataWrangler, DataSpec
from pathlib import Path
import pandas as pd
#%% setup paths
DATADIR = Path(__file__).parent.parent / "data"
RESULTDIR = Path(__file__).parent.parent / "results"
#%% setup data
data_file = DATADIR / "database.xlsx"
data_spec = DataSpec(data_file,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.