sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
5265c237abf3117f422ee7b694a4e42534f6f648bd607edb0350daf08355eb92 | Python | 850 | 34 | # hashobj is imported from several other submodules in Shape-Out.
# Would we need to add additional functionalities in the future, which
# are not within the scope of dclab, then we can patch this method here.
from dclab.util import hashobj # noqa: F401
def get_valid_filename(value):
"""
Return the given str... |
23c7f3e7671b14a7521d296f7de01d7628afb2376a636ccd96241c12a2751824 | Python | 852 | 36 | __all__ = [
"MS2SpectrumProto",
"MzArray",
"IntensityArray",
]
from typing import Any, Iterable, Optional, Protocol, Tuple, Union
import numpy as np
import numpy.typing as npt
MzArray = Union[npt.NDArray[np.float32], npt.NDArray[np.float64]]
IntensityArray = Union[npt.NDArray[np.float32], npt.NDArray[np.... |
756fc51f0f3b3fc001c5320443f211cc5788ab3bf9bb26d3b19606df0e995bcf | Python | 852 | 21 | # 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... |
313b9aeb0657057287b7f145204df0e3ed319672e5232fbfd7f90c85b6d54e4b | Python | 853 | 27 | import torch
def accuracy_topk(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
... |
4e0541b085b59cd9e4638ab97a6b3aff226fac4d551f8265bda5df6f6fd1f207 | Python | 853 | 23 | # 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... |
6268b9cdd538a2b69d032468c4e0a43e75ff335229adb5436de02111088e379f | Python | 853 | 36 | import numpy as np
import pytest
import pandas as pd
@pytest.fixture(autouse=True)
def autouse_mpl_cleanup(mpl_cleanup):
pass
@pytest.fixture
def hist_df():
n = 50
rng = np.random.default_rng(10)
gender = rng.choice(["Male", "Female"], size=n)
classroom = rng.choice(["A", "B", "C"], size=n)
... |
02d5dc2fc2af6f408414effe0da844ffdace0ddc0628b01e0f1376bba1f07ebe | Python | 854 | 28 |
from typing import List, Tuple
from neuronbridge.model import *
def get_published_name_set(matches : List[Match]) -> List[str]:
"""
Returns a list of all the published names of the masks in the matches.
"""
return set([match.image.publishedName for match in matches])
def get_ranks(matches : List[Mat... |
5009794af9ea2bf805afc809869b85d1c9d34f19763a6a0f8f9d06d94d5c1c42 | Python | 857 | 20 | # 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... |
53f60e4d7f8beb5f431fa9f1dc1aaf56172ea7085d850b53468ef6e29d2a4917 | Python | 857 | 23 | # 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... |
a7182dc4ea40f6b6f48f1b300373d96bae12211192e7fdcc7bb59a4be3214efb | Python | 863 | 34 | # -*- coding: utf-8 -*-
import warnings
import numpy as np
import pytest
from emcee import moves
from emcee.model import Model
from emcee.state import State
__all__ = ["test_live_dangerously"]
def test_live_dangerously(nwalkers=32, nsteps=3000, seed=1234):
warnings.filterwarnings("error")
# Set up the ra... |
d978f6dc89b78579ba261659e61f23a3d073641574b3f39e0f6ede094e9d1a68 | Python | 863 | 23 | # 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... |
52b607e0e9b877bf9773479f94f8d88323a7f7159b45a584cfafe768e938e5ad | Python | 864 | 18 | # 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... |
b2cb68370d94f768d5450392c91d1ccc7ad03fc1e68f65ba018a9f788c78b3ce | Python | 865 | 31 | import numpy as np
# 1 should be axons and 2 should be artifacts
def process_labels(vol):
for i in range(vol.shape[0]):
slice = vol[i]
if np.max(slice) > 0:
# Increment whole slice by 1 to have background be 1
slice += 1
for x in range(1, slice.shape[0] - 1):
... |
d1f22ff48cade60bae6a5d8e45a7ff11edd643c48413558ff6a5257871580e66 | Python | 865 | 26 | import pandas as pd
from pandas.core.arrays import BaseMaskedArray
def get_array(obj, col=None):
"""
Helper method to get array for a DataFrame column or a Series.
Equivalent of df[col].values, but without going through normal getitem,
which triggers tracking references / CoW (and we might be testing... |
499420c8a45d0a7e30ec8345505f453c3768511f726b53612bd7d47dc7ca331e | Python | 866 | 21 | from isaacgymenvs.pbt.launcher.run_description import ParamGrid, RunDescription, Experiment
from isaacgymenvs.pbt.experiments.allegro_kuka_pbt_base import kuka_env, kuka_base_cli
from isaacgymenvs.pbt.experiments.run_utils import version
_pbt_num_policies = 8
_name = f'{kuka_env}_regrasp_{version}_pbt_{_pbt_num_polic... |
7fd0199c06add90f35cf018c2fb7672d5de7e28fb95ae283a14af57e12ced1c2 | Python | 866 | 33 | """
In this module, the input and output dimensions for each neural network
are stored. Simply make a dataclass and store the dimensional data.
input_dimensions: the dimensions expected for the neural network application.
output_dimensions: the dimensions expected to be sent back to Gadgetron.
"""
from datacl... |
83ec180951406711602fd88204c9964189bb79ee264ade754f9aa6c5da8075ec | Python | 866 | 33 | import argparse
import os
from Cython import Tempita
def process_tempita(pxifile, outfile) -> None:
with open(pxifile, encoding="utf-8") as f:
tmpl = f.read()
pyxcontent = Tempita.sub(tmpl)
with open(outfile, "w", encoding="utf-8") as f:
f.write(pyxcontent)
def main() -> None:
pars... |
f2e3575e25411320c215157cb97ae3e2312a8bbfa425181287188675b49f7bd8 | Python | 866 | 22 | import pandas as pd
def open_subject_metadata_file(app, cos_client, subject_external_id):
try:
# First try to read the subject's file
subject_csv = f'NKIRS/{subject_external_id}/{subject_external_id}_sessions.tsv'
response = cos_client.Object(app.config['BUCKET'], subject_csv).get()
... |
640d04887b453a2f2da4d627c63447bda2d3d0d317ffb966b58504b2e654c837 | Python | 867 | 23 | from datetime import datetime
import sys
import enum
sys.path.append("..")
from app import db
class TeslasEnum(enum.Enum):
one_and_a_half = 1
three = 2
class Scanner(db.Model):
__tablename__ = 'scanner'
id = db.Column(db.Integer, primary_key=True)
brand = db.Column(db.String(255))
model = db.C... |
732de229a7b9cb690e0b171d1ebc76e79a1cdde74ff40db3e9310550db5e2131 | Python | 867 | 42 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
from pathlib import Path
from statistics import mean, stdev
plt.rcParams['font.family'] = 'Gargi'
fig,ax = plt.subplots()
x = [1,2,3,4,5]
#GLAU
#y = [100,10... |
8ac656f414d6e33a1b97266af4340fa618b94c2fc43c88d2dc4220ffa3fa052b | Python | 867 | 31 | from datetime import (
UTC,
datetime,
)
import pandas as pd
import pandas._testing as tm
class TestDataFrameAlterAxes:
# Tests for setting index/columns attributes directly (i.e. __setattr__)
def test_set_axis_setattr_index(self):
# GH 6785
# set the index manually
df = pd.D... |
a00300a6bef201f1af0af36e787fd3cd48773f92f92025f33b03873167091a4a | Python | 867 | 25 | from setuptools import setup
setup(name='nnunet',
version='0.1',
description='no new-net. Framework for out-of-the box medical image segmentation.',
url='https://github.com/MIC-DKFZ/nnUNet',
author='Division of Medical Image Computing, German Cancer Research Center',
author_email='f.isens... |
a1f941a5e536b21dc30b5c8ab6515899d4ec9b4058be2b696fbfb4fa08869214 | Python | 867 | 41 | from rl_toolkit.agents.sac import Tester as Agent
def test_pre_trained():
agent = Agent(
env_name="BipedalWalkerHardcore-v3",
render=False,
max_steps=2000,
frame_stack=1,
actor_units=[512, 256],
clip_mean_min=-2.0,
clip_mean_max=2.0,
init_noise=-3.0,... |
cfe84fabda9472c766b488e529861ed364778f63fb5d7fdeecd5bddf358a3657 | Python | 867 | 31 | import sys
import logging
from os import makedirs
from os.path import dirname
from sys import stdout as _stdout
def setup_logging(log_file_path: str):
"""
Sets up the logging
"""
# Set up logging format.
_FORMAT = "[%(levelname)s: %(filename)s: %(lineno)4d]: %(message)s"
handlers = [logging.St... |
991b1a080d3fce7a30d35fb534c70d8a5d1e9c218b93e28217a4ffd7284a51a9 | Python | 868 | 25 | """Run-execution subsystem for the PyCaret platform.
Exposes one class:
- `RunOrchestrator` — submits runs to an in-process thread pool, wires the
engine's `BaseLogger` to the database as `Event` rows, writes artifacts,
and broadcasts events to WebSocket subscribers via the `event_broker`.
Submodules:
- `broker... |
79ad63c49cebc84e1a503d3c74c70b3bc9e98a1ee4bd34aa98d259a2f8f2b3d9 | Python | 869 | 38 | import sys
import pysam
if len(sys.argv) != 5:
sys.exit('Usage: python sc_atac_library_deconvoluter.py [Input Bam file] [Input Index table] [Output prefix] [Output extension]')
inbam = pysam.Samfile(sys.argv[1],'rb')
inindex = open(sys.argv[2],'r')
libdic = {}
outdic = {}
for line in inindex:
liner = line.s... |
0092c36609a40706e24f3b6cf01e76e20761aa099e9d24e956a0702348985fe9 | Python | 870 | 31 | import numpy
import pandas as pd
#%%
dorotheaData = pd.read_csv('results/macrophage-TFs.tsv', sep='\t', index_col=0)
ligandMapping = pd.read_csv('annotation/macrophage-ligandMap.tsv', sep='\t')
allLigands = numpy.unique(ligandMapping['Source'])
ligandNames = [x.replace('Ligand_', '') for x in allLigands]
allCondit... |
6fd8e680fa3bf22a5ede7573f9c41b5196febb0b3cae3fe270e86a7da9df6a89 | Python | 870 | 32 | import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
msg = "PeriodIndex.is_full is deprecated"
@pytest.mark.parametrize(
"years, expected",
[
(["2005", "2007", "2009"], False),
(["2005", "2006", "2007"], True),
(["2005", "2005", "20... |
dccc3c02a4cb8c44de8951629eb9fc62e00b17fb49511870fea4bba55c35ce79 | Python | 870 | 30 | from cffi import FFI
ffibuilder = FFI()
# specify functions, etc made available to Python
ffibuilder.cdef("""
double fcn(double x[], int dim);
void batch_fcn(double ans[], double x[], int n, int dim);
""")
# specify code needed to build the module
ffibuilder.set_source(
module_name="cfcn_cffi", ... |
5ff7ee77c1806df640fa1d7ffd305d5ec5a0eec330ad68f66fc9f0c5450eb3c9 | Python | 871 | 27 | # 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... |
e26a598c817ef6e6dae9b5a226ddef386a93787575342c5ffeeb7b5709cf8a52 | Python | 871 | 39 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 22 16:16:27 2022
@author: jeanbaptiste
"""
import copy
import os
import time
import sys
import json
import uuid
sys.path.insert(0,"/project/dunlop/JB/deepcellcontrol/")
import deepcellcontrol as dcc
# Load params:
params = copy.deepcopy(dcc.config.defaults)
# If path ... |
8255099b66e389280a1b82e967c7460d877d003d5f5e056a56cdf0313efba79c | Python | 872 | 19 | # 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... |
f577f08017ef739c153c3dbf733a5269267065e96df24452361d93414bde4ec6 | Python | 872 | 31 | """Small shared helpers; each call returns fresh, mutable state."""
from pathlib import Path
import pytest
import torch
WEIGHTS_DIR = Path(__file__).resolve().parents[1] / "clocks" / "weights"
def load_local_clock(name):
"""Load local build output on CPU; skip when it is absent."""
path = WEIGHTS_DIR / f"{... |
82ac17cf3654bed8b61a3fe7058f321e251105909e9d5b4c4a6a303617961f4f | Python | 873 | 30 | #
# Equivariant batch normalization layer
#
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import BatchNormalization
import protein_holography.network.L_batch_norm as lbn
class SphericalBatchNorm(tf.keras.layers.Layer):
def __init__(self, layer_id, L_MAX, scale=Fal... |
8e909a672904e793fb3e07f21c557424aa8a240c54dc825314eefe322315080c | Python | 873 | 29 | def __getattr__(key: str) -> object:
# These imports need to be lazy to avoid circular import errors
if key == "hash_array":
from pandas.core.util.hashing import hash_array
return hash_array
if key == "hash_pandas_object":
from pandas.core.util.hashing import hash_pandas_object
... |
9f3030911e0b7207ce2e1eff3b7eba94292b16f96151cca27e08fa2394fe4014 | Python | 873 | 28 | # 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... |
f69333718eb386d20051c0c991faa1a232d40a2db6248ad58e07d753c93ae84f | Python | 873 | 38 | import torch
import torch.nn as nn
class RNNModel(nn.Module):
def __init__(
self,
input_dim=149,
lstm_dim=32,
dense_dim=32,
logit_dim=32,
num_classes=2,
):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(input_dim, dense_dim ... |
49eeedfb0d4f5d0f542c960c46d8142d932bc1e2bb1b50108839aedfdc0f9beb | Python | 874 | 24 | #!/usr/bin/env python
from distutils.core import setup
description = 'Minimalistic implementation of the Self Organizing Maps (SOM)'
keywords = ['machine learning', 'neural networks',
'clustering', 'dimentionality reduction']
long_description = 'See the github page https://github.com/JustGlowing/minisom'
... |
1d7d04b038958da8c16d27cbc08b78a28ead226a8ddb6413311dff4c6b982850 | Python | 875 | 32 | import numpy as np
from values import *
from defs import *
def NHE1(cell,memb_id,NHE1,area):
affnao = 34.0
affnai = 102.0
affho = 0.0183e-3
affhi = 0.054e-3
nai = cell.conc[0,memb_id[0]]
hi = cell.conc[11,memb_id[0]]
nao = cell.conc[0,memb_id[1]]
ho = cell.conc[11,memb_id[1]]
Fno = (nao/affnao)/(1+nao/affn... |
3d26bee698a59592be215772e41ebf0ff54e9fac40d0865975fb9e73dab029d3 | Python | 876 | 21 | # 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... |
8e59b98a402ab82b5a0ae85dbe9cd072360d6ea56a3099d56e55a2c4cb92d2b5 | Python | 876 | 35 | from dateutil.tz import tzlocal
import pytest
from pandas.compat import (
IS64,
WASM,
)
import pandas as pd
@pytest.mark.parametrize(
"freq,expected",
[
("YE", "day"),
("QE", "day"),
("ME", "day"),
("D", "day"),
("h", "hour"),
("min", "minute"),
... |
1147af2c46cd347be71309f09764d5c40f016986e9765bd2fca002961812a626 | Python | 878 | 40 | import os
import torch
import random
import numpy as np
class Seeds:
pythonhash = 0
pythonrand = 0
numpy = 0
torch = 0
class SeedControl:
def __init__(self, seeds=Seeds()):
self.s = seeds
def fix_all_seeds(self, seed: int):
"""Fix all seeds to the same seed"""
self.... |
3146a2cc57eff210b4609ce0a74552d01e636e31f8e2eff3799784ec86e7f4b2 | Python | 878 | 25 | import pytest
import pandas as pd
import pandas._testing as tm
class TestStrAccessor:
def test_str_attribute(self):
# GH#9068
methods = ["strip", "rstrip", "lstrip"]
ser = pd.Series([" jack", "jill ", " jesse ", "frank"])
for method in methods:
expected = pd.Series([ge... |
3e46c88bfdef34ca6e72cbf6e83b0f74872081daa499692f7117e05bc55d68a5 | Python | 878 | 26 | import ctypes
class SeqDataHeader(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
("packet_size", ctypes.c_uint32),
("id", ctypes.c_char * 52),
("swapped", ctypes.c_uint32)
]
class SeqData():
def __init__(self, data):
self.hdr = SeqDataHeader.from_buffer_copy(d... |
4e4ee9b81c49d4465caa21972fb15f2550c2f7f9214590c1e0f66612e710c011 | Python | 878 | 23 | from nesvor.transform import RigidTransform
from tests import TestCaseNeSVoR
import torch
class TestTransform(TestCaseNeSVoR):
def test_compose_inv(self):
zeros = torch.tensor([[0, 0, 0, 0, 0, 0]], dtype=torch.float32).cuda()
data = self.get_transform_test_data()
for i in range(len(data)):... |
68369af752c3908bc4e770cefd1ea62b812830113321df229016acbabaab362a | Python | 878 | 35 | """Tests for the `multimodal_ad.cli` synthetic quickstart."""
from pathlib import Path
from multimodal_ad.cli import build_parser, main
def test_build_parser_defaults() -> None:
parser = build_parser()
args = parser.parse_args([])
assert args.n_subjects == 20
assert args.seed == 1234
def test_main... |
31739741896183701ab45e062959daca8dc525404b477dfdbeb9db5c5f3bcd80 | Python | 880 | 19 | """Simulate the acquisition of the warped FLAIR: thick axial slices (4 mm by default)
and Rician noise."""
import sys
import numpy as np
import nibabel as nib
src, out = sys.argv[1], sys.argv[2]
thick_mm, sigma = (int(sys.argv[3]), float(sys.argv[4])) if len(sys.argv) > 4 else (4, 6.0)
im = nib.load(src)
v = im.get_fda... |
b498147559a9c48e53ce16e6c6ce371b1d1971b1641df98137db38c910302df8 | Python | 881 | 42 | import sys, os, math
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
from model import Model,CondModel
srif = open(sys.argv[1],mode='r',encoding='latin-1')
opts = str(sys.argv[2][1:]).upper()
if opts != 'U':
suni = Model('U'+opts)
else:
suni = Model('U')
sunib = Mo... |
fff50e69d5febedf86e3e924a252bb6f5fee41e4771ce643f7590df7c4ded111 | Python | 881 | 26 | from .data import *
from .inference import DatasetForInference
from .lightning_train import *
from .model import *
from .pretraining import SIMSPretrainer, transfer_pretrained_weights
from .scvi_api import SIMS
from .temperature_scaling import *
# UploadCallback now lives in scsims.contrib (depends on the optional
# `... |
4a1c5c85751d5ee1b145b0f997575dafc77e41e976818d5a65bce32758ea121e | Python | 882 | 15 | """Write a smooth synthetic displacement field (components dx, dy, dz in mm) that
fades to zero at the edges of the volume, so the warped image has no empty borders."""
import sys
import numpy as np
import nibabel as nib
ref, outdir, amp = sys.argv[1], sys.argv[2], float(sys.argv[3])
im = nib.load(ref)
nx, ny, nz = im.... |
2ab824f5de37637706c8fa32fab061182be859921f18c4689668e24cb44230fa | Python | 883 | 34 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `tractify` package."""
import unittest
from click.testing import CliRunner
from tractify import tractify
from tractify import cli
class TestTractify(unittest.TestCase):
"""Tests for `tractify` package."""
def setUp(self):
"""Set up test f... |
6d10d79355be27b302cb6ba2ce2f67606afe2513860df8ef0d017f8106a72cd1 | Python | 883 | 32 | """Create inno setup .iss file"""
import io
import os.path as op
import platform
import sys
import shapeout2
# make library available
cdir = op.dirname(op.abspath(__file__))
pdir = op.dirname(cdir)
sys.path.insert(0, pdir)
# get version
version = shapeout2.__version__
# read dummy
with io.open(op.join(cdir, "win_sh... |
bcd6ef510a4a14472afe0845fa91c1dd05879d1ffec3f0a87477faafec85b8b9 | Python | 883 | 33 | #!/usr/bin/env python
__version__ = '1.0'
from Bio import SeqIO
import os, sys
def main():
from argparse import ArgumentParser
parser = ArgumentParser("Convert fastq to fasta")
parser.add_argument("fastq_filename", help="input fastq (must end with .fastq or .fq)")
args = parser.parse_args()
inpu... |
afb5089e7c6dd1553ba61a2e8f126e08ee96da0d6f3aca43aa1c3225c81367af | Python | 885 | 32 | """
.. module:: cmd_manager
:platform: Linux, Windows
:synopsis: Manager for handling command stack for apply/undo
.. moduleauthor:: Fredrik Nysjo
"""
class CmdManager:
def __init__(self):
self.stack = []
self.max_undo_length = 8
self.dirty = True
def push_apply(self, cmd):
... |
d0640ef4866abf0806c04f4de1104cc506c91f251ca0a143ef8de20c4d524d6a | Python | 885 | 30 | from scripts.sort_whatsnew_note import sort_whatsnew_note
def test_sort_whatsnew_note() -> None:
content = (
".. _whatsnew_200:\n"
"\n"
"What's new in 2.0.0 (March XX, 2023)\n"
"------------------------------------\n"
"\n"
"Timedelta\n"
"^^^^^^^^^\n"
... |
dd4e0a5b40f453bf1261e0fe4fc731875462e2b72345d6dac43052b26c5fa5a2 | Python | 885 | 25 | import pandas as pd
import numpy as np
###################################### FUNCTIONS ######################################
def make_all_genes(specificity_matrix_file, specificity_matrix_name, out_dir):
specificity_df = pd.read_csv(specificity_matrix_file, index_col='gene')
all_genes = pd.DataFrame(index = spe... |
9435fca5ccf8285d3e05af30e2ab88d272afbaef5a1bb5b6743c60b150c419db | Python | 886 | 24 | __all__ = ["RTMSELoss"]
import torch
from torch.nn.modules.loss import _Loss
from torch.nn.functional import mse_loss, l1_loss
from .data import PeptideRTDataBatch
class RTMSELoss(_Loss):
def __init__(self, size_average=None, reduce=None, reduction: str = "mean"):
super().__init__(size_average=size_aver... |
d8de49685f885b8300c8e1d1d1a051a74a6939769831987f993baa862c86b49a | Python | 886 | 21 | # 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... |
96fc5bcb8d12dc7704c0064fd2fdf060765ebd33523ab704d5d9ea2f5c0f6480 | Python | 888 | 42 |
import os
import subprocess
import math
import shutil
import numpy as np
from os.path import isfile, join
from PIL import Image
import random
import csv
from datetime import datetime, timedelta
path1 = 'phase_recognition_annotations/'
case_list = os.listdir(path1)
case_list.sort()
for i in range(0,len(case_list)... |
e709102b161c2a58af54c71e02e08d9399d170ce740eb79e5d62a9ddc46a7bcf | Python | 888 | 22 | # 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... |
abf80c637ca3b1f7867aae0a95fc315ed7fb01811eec2a38fb29e56c9de0e398 | Python | 889 | 42 | import os, sys, re, argparse
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
argparser = argparse.ArgumentParser('''
Takes a linetrees file and binarizes it to CNF.
''')
args, unkown = argparser.parse_known_args()
heads = {}
deps = {}
def preterm(t):
re... |
ca7f8e9d68651abc435d29091a87fe4ea72b2e1bbeffbd9e5212c7f558677614 | Python | 889 | 33 | import sys
import os
def main(args):
diff_file = args[1]
out_file = args[2]
removed = []
curie_to_label = {}
with open(diff_file, 'r') as f:
for line in f:
if line.startswith('- EquivalentClasses') or line.startswith('- SubClassOf'):
curie = line.split('<')[1]... |
4d6ae8b7df3214470bb97157fa852259989ba44934acfff9e0c16b596f5a4735 | Python | 894 | 31 | import numpy as np
import pandas as pd
import pandas._testing as tm
class TestRepeat:
def test_repeat(self):
index = pd.timedelta_range("1 days", periods=2, freq="D")
exp = pd.TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"])
for res in [index.repeat(2), np.repeat(index, 2)]:
... |
e34da229e784e00c5877edb3eb1fab367845b3614bc618f76644403f95990dbb | Python | 894 | 34 | # 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... |
a63893ca55ecaacea7907ff4130385ad07a744f18a74496b7d09417354bc88c9 | Python | 896 | 38 |
from cine import Cine
import align
import tube2
from skimage import filters, measure, feature, morphology
from skimage.io import imshow
from matplotlib import pyplot
import numpy as np
import glob
def difference(left: np.ndarray, right: np.ndarray):
return left.astype(np.int16) - right.astype(np.int16)
def get... |
c36b707ad26021e766e8a190e1699d9860bfebe4528458d704c055c51d2070c1 | Python | 896 | 40 | import numpy as np
import pytest
from pandas.util._validators import validate_inclusive
import pandas as pd
@pytest.mark.parametrize(
"invalid_inclusive",
(
"ccc",
2,
object(),
None,
np.nan,
pd.NA,
pd.DataFrame(),
),
)
def test_invalid_inclusive(in... |
d91b1197c304ce736fe4cf7fe73b0bdb936444482176305c079df1c56a0a5b20 | Python | 896 | 18 | # -*- coding: utf-8 -*-
from utils.mapping import mapping, gen_gif
#=========================set values below==========================
fig_header = 'sq2_1' # The name of the data that is same as the one in 'run-detector..py'
th_level = 0.3 # Threshold level of the map
map_horiz = [-15,15,30] # map geometry (ho... |
df559f602edebc689104fd35bcca5892952ffaabe15b1b6a7148003e5004fb23 | Python | 896 | 18 | # -*- coding: utf-8 -*-
from utils.mapping import mapping, gen_gif
#=========================set values below==========================
fig_header = 'sq2_1' # The name of the data that is same as the one in 'run-detector..py'
th_level = 0.7 # Threshold level of the map
map_horiz = [-15,15,30] # map geometry (ho... |
2045c455d69e4b221228bc620c2ce860372542007696afbe510b598c645a290e | Python | 898 | 22 | import os
from . import parent_classes
import compatibility
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return True #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def get(self, savedir):
# with open(os.path.join(savedir, 'to_pickle_d... |
dc09772b25303033fab8f82b64902dc3dd469c1c34af48773ee985f8c2134753 | Python | 898 | 35 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 15:30:23 2020
@author: Avlant-MIT
"""
import torch
import numpy
import matplotlib.pyplot as plt
import bionetwork
maxIter = 10000
peak = 1000
maxLr = 2e-3
minLr = 1e-8
test = numpy.array(range(maxIter))
testY = numpy.zeros(maxIter)
for i in range(len(testY)):
tes... |
e7512ab495c7201e83c82f3444ab2605ff474bbeb47ad82700a3796133bcc47e | Python | 898 | 23 | from isaacgymenvs.pbt.launcher.run_description import ParamGrid, RunDescription, Experiment
from isaacgymenvs.pbt.experiments.allegro_kuka_pbt_base import kuka_base_cli
from isaacgymenvs.pbt.experiments.run_utils import version
env = 'allegro_kuka_two_arms_reorientation'
_pbt_num_policies = 8
_name = f'{env}_{versio... |
9b9e54f60f87a685b61e1ead6594c92be1cebbe9ec6e4e0c6f748643a4354e77 | Python | 899 | 31 | # -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger()
def init_logger(
log_file=None,
log_file_level=logging.NOTSET,
rotate=False,
log_level=logging.INFO,
):
log_format = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s")
... |
b3b497c1674a648232b8838954ea8e9b6f77ceed7926188f53c26ee118b10a48 | Python | 899 | 41 | import numpy as np
from typing import List
CM2_SIZE = [2076, 3088]
NUM_VIEWS = 9
FOCUS_LOC = np.array(
[
[406, 909],
[407, 1545],
[405, 2175],
[1037, 911],
[1037, 1544],
[1037, 2176],
[1675, 911],
[1675, 1543],
[1675, 2173],
]
)
NUM_SLICES... |
a0b6041281addd0e0a4055ecdac0adc4c3f8d3f82294ab209e39ea776c5cc233 | Python | 904 | 59 | """API route modules.
Each module registers a FastAPI ``APIRouter`` exported as ``router``. The app
factory mounts them at ``/api/v1``.
"""
from pycaret_server.api import (
analyses,
api_keys,
audit,
auth,
connections,
data_sources,
deployments,
describe,
drift,
experiments,
... |
cff46285c83ccd540a40879198e45db65ba2f683feb4229e0e21118da6a0c7cf | Python | 904 | 26 | import pandas as pd
import pandas._testing as tm
class SubclassedCategorical(pd.Categorical):
pass
class TestCategoricalSubclassing:
def test_constructor(self):
sc = SubclassedCategorical(["a", "b", "c"])
assert isinstance(sc, SubclassedCategorical)
tm.assert_categorical_equal(sc, pd... |
0f9b2d893a1a327598590fa9952fd3cf6ed5a3a9cf8358590786f0eb4e698856 | Python | 905 | 35 | import sys
OPENS = '(['
CLOSES = ')]'
Indents = [0]
followstate = None
## For each line...
for nLine,line in enumerate( sys.stdin ):
i = 0
## For each character...
for c in line:
## If open delimiter, record tab...
if c in OPENS:
sys.stdout.write( c )
i += 1
if followstate == '(': Ind... |
45e5c69ea6a76fe3b9924983d5a324ebaceb0d315085444fe43bc5a3f0c3e6ef | Python | 905 | 39 | import numpy as np
from pandas import (
DataFrame,
Index,
date_range,
read_pickle,
)
from ..pandas_vb_common import BaseIO
class Pickle(BaseIO):
def setup(self):
self.fname = "__test__.pkl"
N = 100000
C = 5
self.df = DataFrame(
np.random.randn(N, C),
... |
6ecd56d567233c32cccedb459d8f4a9323359b72d9fbd31d267fc1340ebc50a1 | Python | 905 | 28 | import pandas as pd
import pandas._testing as tm
class TestGetNumericData:
def test_get_numeric_data_preserve_dtype(self):
# get the numeric data
obj = pd.Series([1, 2, 3])
result = obj._get_numeric_data()
tm.assert_series_equal(result, obj)
# returned object is a shallow ... |
9d389ddc5200133c573df7ff6b90eaa6ab462b4ad8b256150971456dfc1500c7 | Python | 905 | 41 | # import numpy as np
import glob
import os
from subprocess import call
import sys
import re
import argparse
def printParams(simTime, dt, nCells):
print("Simulation paramameters")
print("simTime: {:.2f}".format(simTime))
print("dt: {:.2f}".format(dt))
print("nCells: {:d}".format(nCells))
print("")
def main():
e... |
178cf1548ca211ab9da9862f8cf5923472b805922909bf39f89f6992ac67cd4c | Python | 906 | 33 | from io import BytesIO
import pytest
import pandas as pd
@pytest.mark.parametrize("data", [b"foo,bar,baz\n1,2,3\n4,5,6\n", b"just,the,header\n"])
def test_streaming_s3_objects(data):
# GH 17135
# botocore gained iteration support in 1.10.47, can now be used in read_*
pytest.importorskip("botocore", minv... |
4044bbd7e914224f5e88273f3a5db3ad8d3e612088dce15ff9e833641b5b2fb2 | Python | 908 | 32 | #!/usr/bin/env python
"""
File: test
Date: 5/3/18
Author: Jon Deaton (jdeaton@stanford.edu)
This file tests the functionality of the BraTS dataset loader
"""
import BraTS
import unittest
import numpy as np
# If, for some reason, you wanted to test this on your machine you would
# need to set up the BraTS data-sets ... |
6ca93c42f58fd83335daec70ff97a1c6013fca47160b3a6ae843acf65fff2db0 | Python | 908 | 36 | """ Script to download model weights """
import os
import urllib.request
def download_weights(
download_dir = "../model_weights",
name = "best_network.tar.gz"
):
download_path = os.path.join(download_dir,name)
try:
urllib.request.urlretrieve(
"https://figshare.com/ndownloader/file... |
f5ea8aa086deca746d8702855f740bd50e8e9ccbd1c0356723d298eb91d6b660 | Python | 909 | 21 | import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgllife.model.readout import WeightedSumAndMax
from dgllife.model.gnn import GraphSAGE
class GraphSAGEPredictor(nn.Module):
def __init__(self, in_feats=74, hidden_feats=[100,100], activation=None, dropout=None, aggregator_type=None... |
29fdaf9353cb2493e9efa6a2321a0d4f2c966003f8ba8ba8697a96b0c9b64265 | Python | 910 | 51 | from abc import ABC
from abc import abstractmethod, abstractproperty
class BaseAlgorithm(ABC):
def __init__(self, base_name, config):
pass
@abstractproperty
def device(self):
pass
@abstractmethod
def clear_stats(self):
pass
@abstractmethod
def train(self):
... |
2e40392aa8b1badef7ed3f7bc4e4edc4679b5d52b6e37fb6c595fed7d670f789 | Python | 910 | 30 | import os
import cv2 as cv
import numpy as np
if __name__ == '__main__':
raw_img = "/mnt/d/workspace/svision-pro/sim_fig1/chr1_labels/sample.chr1_25557927_25561484_NA_4438_base0.png"
out_img = raw_img.replace(".png", ".changed.png")
raw_img_rgb = cv.imread(raw_img)
# print(raw_img_rgb)
print(np... |
4c194d836da7f0cebc65e3b5ec2251a4b4f5829fd6b024e8844364fd25bdc383 | Python | 910 | 29 | # 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... |
7405a80b7f90aebbda93f097a45857e6087d51048d9f77588db41d6d9033507f | Python | 911 | 34 | # coding: utf-8
"""Top-level Atropos package.
"""
import os
import sys
from atropos._version import get_versions
__version__ = get_versions()['version']
del get_versions
class AtroposError(Exception):
"""Base class for Atropos-specific errors.
"""
pass
def check_importability(): # pragma: no cover
"... |
fa41bb29da22703f22f2b61076bd4f56b12ab87be82f7cd0fcb9dce54f07813f | Python | 911 | 28 | from defs import *
from values import *
import numpy as np
import math
def trpm6(cell, ep, memb_id, act, area):
F_si = 9.6485e4
delta_vol = (cell.ep[0] - cell.ep[1]) * EPref
E_nernst = (RT * np.log(abs(cell.conc[16, 1] / cell.conc[16, 0]))) / (2 * F)
Mg_inhib = 0.51
# Intracellular ... |
8346489a4d5cababbab28da2563b510afcc16cf1b8abadb4a5ff88033fec2a3e | Python | 912 | 27 | """
Converting collapsed group.txt file into a .read_stat file that could be used to run IsoPhase later
"""
import os, sys
def main(group_filename, output_filename):
f = open(output_filename, 'w')
f.write("id\tpbid\tis_fl\tstat\n")
for line in open(group_filename):
a,b=line.strip().split()
... |
ea2bbb693ab4aff14b4cecb89018e38e5ce9342c7c3bb27b79749cd4ece1d7b1 | Python | 912 | 29 | import logging
import msmfcode_src
from msmfcode.core.logging import log
from msmfcode.core.config import *
from msmfcode.execution.parallel import ParallelExecutor, ParallelEvaluationExecutor
from msmfcode.models.cann import DMSMF, FMSMF, Grid, SSSF
from msmfcode.evaluation.plot import plot_weight_distribution, plot_... |
e8d3e88613e931cf2886b5096661fc2ff957a706825cbf60c5d25a3af4c50b93 | Python | 913 | 21 | from datetime import datetime
import sys
import enum
sys.path.append("..")
from app import db
from sqlalchemy.dialects.postgresql import JSON
class PreprocessTaskFile(db.Model):
__tablename__ = 'preprocess_task_file'
id = db.Column(db.Integer, primary_key=True)
image_id = db.Column(db.Integer, db.ForeignK... |
7063eb32641de772ed543d624b78e1ebd5aa319a8c0219c526a9020e36986b12 | Python | 914 | 22 | #!/usr/bin/env python3
from pathlib import Path
import gzip, sys
in_filepath = Path(sys.argv[1])
out_filepath = Path(sys.argv[2])
with gzip.open(in_filepath, 'rt') as in_f, gzip.open(out_filepath,'wt') as out_f:
def write(line:str): out_f.write(line); out_f.write('\n')
write('##fileformat=VCFv4.1')
writ... |
57c65b8a84f64d06d6cef874ebb8d123b9e3957800428fc8d6e096a61d5618d2 | Python | 915 | 18 | import tempfile
from pathlib import Path
_project_root = Path(__file__).parent.absolute()
config = {
'workers_pool_port': 6379,
'project_root': _project_root,
'experiment_results_dir': str(Path(_project_root, 'data', 'experiment_results')),
'synthetic_datasets_dir': str(Path(_project_root, 'data', 'sy... |
7c498365f8d7104ac7c505c715fc746a337c971b070650fb7ed126a4276643a7 | Python | 915 | 27 | from src import simulation
from src import nodim
import numpy as np
def test_estimate_params():
""" test if parameters are estimated correctly """
values = np.random.normal(0,1,1000)
param = nodim.estimate_params(values)
assert np.allclose(param['mu'],np.mean(values))
assert np.allclose(param['std'... |
91fc2c2bb48282dd2aa9687d58823a74cc1b5ae56126cf828f05cf41d0498ce6 | Python | 915 | 25 | import numpy as np
import argparse
import hyperparameters
from training import train
if __name__ == '__main__':
# recover parsed arguments
parser = argparse.ArgumentParser()
parser.add_argument('--n_in', type=int, default=700)
parser.add_argument('--n_delays', type=int, default=16)
parser.add_arg... |
0e38f9b2bf338cae92add14829d2dccf9ca3f259cf671788538d0eafda47d321 | Python | 916 | 26 | import json
from pcntoolkit.dataio.fileio import to_json_with_one_line_lists
def test_to_json_with_one_line_lists() -> None:
"""Dicts are indented, each list is on one line, and the values are kept."""
obj = {
"name": "roi",
"settings": {"degree": 3, "tol": 1e-8, "warp": None},
"m": [... |
33baad3aa5ae4c5e68b6c38629fb8779b84d713f18d45638b38e2647f1e2012f | Python | 916 | 21 | # 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... |
a381bb8d16fe00b5e1e90fc514ed36be48838f31fa9acba40a6fdec663a5132a | Python | 916 | 23 | from isaacgymenvs.pbt.launcher.run_description import ParamGrid, RunDescription, Experiment
from isaacgymenvs.pbt.experiments.allegro_kuka_pbt_base import kuka_base_cli
from isaacgymenvs.pbt.experiments.run_utils import version
env = 'allegro_kuka_two_arms_regrasp'
_pbt_num_policies = 8
_name = f'{env}_{version}_pbt... |
5e65dd0b4e8f85e1a226657b4cb1d7d8b52e592caaca95efe050d64b4139edcf | Python | 917 | 28 | import os
from sys import path as sys_path
sys_path.append('..')
from base import loggingUtils
from base.imageMatchingLDDMM import ImageMatching, ImageMatchingParam
import matplotlib
if 'DISPLAY' in os.environ:
matplotlib.use('qt5Agg')
else:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pyfftw
p... |
b756f1f51ada62a9ca95dd758530c34bda0ca2b859954dedb14e39ecef2e3d01 | Python | 917 | 24 | import os
import compatibility
from . import parent_classes
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return True #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def get(self, savedir):
# with open(os.path.join(savedir, 'to_pickle_d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.