sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
4c14ab00e4f4d5b4ddb89d5aabd424ec9f7a852b7d8795939b4f4463b727e8d0 | Python | 2,251 | 40 | #!/usr/bin/env python
import torch
import torch.nn as nn
from function import predict_volumes
from model import UNet2d
import os, sys
import argparse
if __name__=='__main__':
NoneType=type(None)
# Argument
parser=argparse.ArgumentParser(description='Skullstripping', formatter_class=argparse.ArgumentDefault... |
c0b726ed17626befac6d7c87f8cb9e01d102fcbd75bdffdcb6eebb31c79fe70b | Python | 2,253 | 48 | import numpy as np, matplotlib.pyplot as plt
plt.rc('xtick',labelsize=18)
plt.rc('ytick',labelsize=18)
plt.rc('axes',labelsize=18)
print("Plotting together the results of")
print("python kunert_vs_correlations_optimize_correlation_step2.py --no-merge --matchless-nan-th:0.5 --matchless-nan-th-added-only")
print("pytho... |
23e074cd54d00cc11b1cd6d932235c343b0ce82615df8fe86daf451cfa8d7cd2 | Python | 2,254 | 57 | import os
import sys
import numpy as np
import nibabel as nib
# Get the absolute path to the root directory of your project
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Append the project root to sys.path
sys.path.append(project_root)
from src.nexi.estimate_nexi import... |
8a0bbe5018d786bfab0ca6a019573fa68710af7d1c845d8b7491c22e071056dd | Python | 2,255 | 52 | """Command modules for the lightning-pose CLI.
Each module in :data:`COMMANDS` is a plain Python module, not a class -- there is no
``Protocol`` or base class enforcing this, so the contract is documented here instead. A
command module must define three top-level functions:
- ``register_parser(subparsers) -> Argument... |
4cf3ec73452446e8d0ee5550e641d3315c66c61f5574007b29afdef21d164da9 | Python | 2,256 | 65 | import os
import datetime
date = datetime.date.today()
throwaway_script = 'batch_script.slurm'
group = 'spe'
k_vals = [0.1,1.0,10.]
l_vals = [8,10]
d_vals = [10.0]
e = 16
rH = 10.
for k in k_vals:
for l in l_vals:
for d in d_vals:
f = open(throwaway_script,'w')
job_name = 'hgram_... |
e67ace5bab88b102d3d0ae7376a349659f2d2ca4d884d33ca1e20cda8247f09a | Python | 2,258 | 69 | # 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... |
035597b10f196b6fcc8fcf2f38dc4cf4860d478fc546659b9253127591437755 | Python | 2,259 | 58 | # 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... |
0d5034877ef1a7713c4bf17a1044ae22c619f474baeba00fe1613e701a24283d | Python | 2,260 | 59 | #!/usr/bin/env python3
"""Regenerate the boundary gold-standard expectations.
Running this is an intentional act, not part of any build. The values it writes
are the assertions in ``tests/predict/test_boundary_gold_standard.py``: if a
regenerated value differs from the pinned one, a clock's predictions have moved
and ... |
1ea2236d5fbfe6ec87eafa83c86c21480a5189a14d4309010911d63a87082545 | Python | 2,260 | 72 | """
Run many experiments with NGC: hyperparameter sweeps, etc.
This isn't production code, but feel free to use as an example for your NGC setup.
"""
import time
from multiprocessing.pool import ThreadPool
from subprocess import PIPE, Popen
from isaacgymenvs.pbt.launcher.run_slurm import str2bool
def add_ngc_args(... |
29eeb61a1e54beaf8af7ae9f6b522cb6de3f8f8a9063c2064bb1ee333694eab4 | Python | 2,262 | 74 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2026, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
3d06f1b3e057c1fe4ecf91a5d9bd7667b1996a793f79d90a0ab3bcb2d9b1a8e8 | Python | 2,262 | 66 | import torch
import numpy as np
def sinkhorn_step(a,b,K,Kp,u,v,cpt,err):
KtransposeU=torch.einsum('aji,aj->ai',K,u)
v = torch.div(b, KtransposeU)
u=1. / torch.einsum('aij,aj->ai',Kp,v)#*a
if cpt % 10 == 0:
tmp=torch.einsum('ai,aij,aj->aj', u, K, v)
cpt = cpt + 1
return a,b,K,Kp,u,v,cpt,... |
c15c75685eae713f99d5dbeb9f5e35ef00592ba7ce519e5f99029cb3df23ab79 | Python | 2,263 | 69 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2026, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
e4ca7edd489d5a132642e5e75a2039add641fe32af792975a559a0d6c378c875 | Python | 2,263 | 64 | import pytest
from scripts.validate_test_dependencies import (
ALLOWED_UNDECLARED,
declared_packages,
environments_running_tests,
validate_test_dependencies,
)
PIXI = {
"dependencies": {"python-dateutil": ">=2.9.0"},
"feature": {
"test-base": {"dependencies": {"pytest": ">=8.3.4"}},
... |
70e0ddac7d50e247d026257989abe34d182ae911eae87e3ae62cb28e4527ce72 | Python | 2,264 | 75 | """Stats module for gradec."""
import nibabel as nib
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from netneurotools.stats import gen_spinsamples
from neuromaps.datasets import fetch_atlas
from nimare.stats import pearson
from pymare.stats import fdr
from tqdm.auto import tqdm
def _gen... |
0a6df2909ddb9ffa6beca3f8e5ca159e0a34577b3dbf645ac1bf9df18299c2a4 | Python | 2,266 | 83 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Code to detect whether each video, in AVMIT or MIT-16, has an audio stream.
"""
import pandas as pd
from pydub import AudioSegment
# %% filepaths
MIT_dir = '/Moments_in_Time_Raw/' # Path to original Moments in Time dataset
AVMIT_train_df = pd.read_csv(
'AVMIT_t... |
b8309b6e35ebd4980753711a52a1ba2f2a16d8a33698ef0c79a5fbb092c372f1 | Python | 2,266 | 70 | from keras.engine.topology import Layer
import keras.backend as K
class PyramidPooling(Layer):
def __init__(self, pool_list, **kwargs):
self.dim_ordering = K.image_dim_ordering()
assert self.dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
self.pool_list = pool_list
... |
b8d6447a74f0286d30c04b4988e6f064de05a06c367acd3413414e5834c6f38b | Python | 2,266 | 70 | import numpy as np
import random
import os
import sys
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, LogisticRegres... |
14ab06f039515160afadaa704da355a5c9364272093ed6e1643857ccf0f3dc45 | Python | 2,267 | 72 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 17:53:55 2023
@author: tomas
"""
from tensorflow import keras
from cine import Cine
import tube2
import glob
from skimage import measure, transform, util, morphology as morpho
import numpy as np
import pathlib
BATCH_SIZE = 32
def measure_video... |
65f21d9f3cc85da8e0c9cf1f443d0edb9f8b086373170875c945f55987e6e8c6 | Python | 2,267 | 75 | __all__ = ["MzmlReader"]
import os
import re
from typing import Optional, Union, cast
import numpy as np
import pymzml.run
import pymzml.spec
from .abs import MassSpectrumReaderBase
from .spec import MassSpectrum
class MzmlReader(MassSpectrumReaderBase):
def __init__(self, file):
self.reader = pymzml.r... |
1c00be2ec26a5428aa4e19f637b7e2d75b5fffa87a4fddc3aa86afcdaf6c33c0 | Python | 2,268 | 88 | import os
import datetime as dtm
from collections import namedtuple
import torch
def banner(device):
""" Print a banner of the system config
Parameters
----------
device : torch.device
"""
print("=" * 80)
info = get_torch_info()
torch_msg = (
f"Pytorch version: {info.torch... |
7b4571faa3bd4de88f8fa15351cde5a9551f30bca1dd53386525e0eb1c023999 | Python | 2,268 | 80 | # -*- coding: utf-8 -*-
"""
Module to stamp plots with current git hash and creation date.
This helps keep track of what the state of the code was in when it produced a plot.
19 July 2019
Andrew Leifer
leifer@princeton.edu
"""
import git
def collectGitInfo():
import git
repo = git.Repo(search_parent_director... |
fdef63e2c78593090749a8f6f100f18b23f6db3bf2203933f3359e111570eefc | Python | 2,268 | 65 | from types import SimpleNamespace
import pytest
from pandas.core.dtypes.common import is_float
import pandas._testing as tm
def test_assert_attr_equal(nulls_fixture):
obj = SimpleNamespace()
obj.na_value = nulls_fixture
tm.assert_attr_equal("na_value", obj, obj)
def test_assert_attr_equal_different_n... |
edaa6c3e36855ac822279b79988c33b87050e89837396232b059c3f8ca37fa21 | Python | 2,269 | 75 | """
Three Gaussians spread along the diagonal of a six-dimensional hypercube.
This coding style for the integrand is more complicated than slow.py but
leads to run times that are 20x shorter because the integrand is expressed
in terms of numpy arrays and whole-array operations, thereby greatly reducing
the overhead f... |
3c166730c624336efbd9ce5abac26d642ff3ba34142f1ffe31fe5f1319d48373 | Python | 2,270 | 94 | # JN 2015-05-22
"""
creates artifact statistics for given channels
"""
from __future__ import print_function, absolute_import, division
import os
import sys
import pandas as pd
from combinato import SortingManagerGrouped, artifact_types
COLS = ["cscname", "hemisphere", "region", "wire", "n_spikes"]
def create_stat... |
e5fa6d115154518173039c1a9f0c5df037954d22c309f6993f23818055460b65 | Python | 2,270 | 64 | import numpy as np
import math
import os
import sys
import scipy.io as scio
class StimTargetRect():
def __init__(self, rectINX, site_point, rect_size, fs, center):
self.rectINX = rectINX
self.site_point = site_point
self.rect_size = rect_size
self.fs = fs
self.... |
3c1375d58b4d2e1bfee151da43fd7aecde26fbee69635f87c3bac5a3ed43a1bc | Python | 2,271 | 54 | __all__ = ["GlycoPeptideSpectralLibraryInMemory"]
from typing import Dict, Optional, Union
import numpy.typing as npt
import pandas as pd
from ..common.speclib import Columns, Indices
from .abs import GlycoPeptideSpectralLibraryBase
from ..pep import PeptideSpectralLibraryInMemory
class GlycoPeptideSpectralLibrary... |
50bf8b9c6a9168caac183288d6b9813a1ec3ccfb3b5bd07f243fd8d756962836 | Python | 2,271 | 61 | import os
from unittest import TestCase
import dynast.estimation.p_e as p_e
import dynast.preprocessing.aggregation as aggregation
import dynast.preprocessing.conversion as conversion
import dynast.utils as utils
from .. import mixins
class TestPE(mixins.TestMixin, TestCase):
def test_read_p_e(self):
p... |
5f05731a566305cdf485d33fbc1c6c25ca6224aae242c05e73f8d30cc376ca4f | Python | 2,274 | 72 | import pandas as pd
class IndexCache:
number = 1
repeat = (3, 100, 20)
params = [
[
"CategoricalIndex",
"DatetimeIndex",
"Float64Index",
"IntervalIndex",
"Int64Index",
"MultiIndex",
"PeriodIndex",
"Ran... |
2199a260151442b9882f3777944d0088bc320501d39a96dd294e0b86b5b96bba | Python | 2,276 | 74 | import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize(
"values, dtype",
[
([], "object"),
([1, 2, 3], "int64"),
([1.0, 2.0, 3.0], "float64"),
(["a", "b", "c"], "object"),
(["a", "b", "c"], "string"),
([1, 2, 3], "datetime64[ns]... |
66d2ad6ec4cd0d3111bb76cb72a4c429c3df9dc274d001b192cd6f5dde3932e0 | Python | 2,277 | 70 | from .spaciotemporal_binning import time_list_from_pd
import pandas as pd
import numpy as np
import dask.dataframe as dd
import dask
import compatibility
def temporal_binning_pd(df, bin_size = 1, min_time = None, max_time = None, normalize = True):
if not isinstance(df, pd.DataFrame):
raise RuntimeError("E... |
c49d1436f09f08cbe345db9ff5f3e850f798ecb656ca7bbd16de2c7f6b34fdbb | Python | 2,278 | 82 | """
Created on Jan 30, 2023.
age_sex_fairness.py
@author: Alexander Ziller <alex.ziller@tum.de>
"""
#%%
import pandas as pd
import numpy as np
from scipy.stats import pearsonr
# %%
def calc_average_acc_other(
sample_sizes: pd.Series, accuracies: pd.Series, label_key: str
) -> float:
sample_sizes = sample_siz... |
b2af0e66d0913ab37fd692105ede0e85d4e40e976f5ae86c764158f0ca87b5f2 | Python | 2,280 | 55 | import numpy as np
import os
import matplotlib
if 'DISPLAY' in os.environ:
matplotlib.use('qt5Agg')
else:
matplotlib.use("Agg")
print(os.environ)
import matplotlib.pyplot as plt
from base import surfaces
from base import loggingUtils
from base.surfaceExamples import Sphere, Torus, Ellipse
from base.kernelFu... |
f97c161a1a55efa9a3510de74f563b6b187f09c91c6e0160e3c70f54725cbf96 | Python | 2,281 | 60 | import argparse
from common import *
import re
from xphyle import xopen
import tqdm
ADAPTER1 = "GATCGGAAGAGCACACGTCTGAACTCCAGTCACCAGATCATCTCGTATGCCGTCTTCTGCTTG" # TruSeq index 7
ADAPTER2 = "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT" # TruSeq universal
def estimate_metrics(fq1, fq2, adapter1, adapter2... |
77045f92b46b358017efcf89e59bebf5a0245d4acac3865be159a1f676ea5866 | Python | 2,282 | 53 | import os
import matplotlib
from PIL import Image, ImageDraw, ImageFont, ImageOps
import argparse
from cdr.config import Config
from cdr.util import filter_models, filter_names
def stitch(dir_paths, image_names, output_path):
fontpath = matplotlib.rcParams['datapath'] + '/fonts/ttf/DejaVuSans.ttf'
imgs = []
... |
faf5deb157e368f417a79bfc6f904ab6e6022a7371802eb93c66c40d8711de19 | Python | 2,283 | 71 | import json
import cine
import tube2
from matplotlib import pyplot
import numpy
from sklearn import svm
import random
with open("meniscus_measurements.json") as mm:
data = json.load(mm)
PAUSE = 1/64
def animate_meniscustrack(data):
fig, ax = pyplot.subplots()
names = list(data.keys())
random.shuffle... |
546d5bb5f1374e4a8e9c9d3f8decc8d8cec6c1aaacef61b8087be4b053ffa414 | Python | 2,285 | 71 | import numpy as np
import random
import os
import sys
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, LogisticRegres... |
750f0198da69f50e3506b49068d32f928067e72efd41759cb8c065803914df81 | Python | 2,285 | 54 | """
Following taken from: https://github.com/castorini/hedwig/blob/master/models/reg_lstm/embed_regularize.py
BSD 3-Clause License
Copyright (c) 2017,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*... |
87bdb0f40f88f330aab0d4b3bc1ff6373d56aaeba8b6d420db5ceadf5f6af705 | Python | 2,288 | 67 | import sys, numpy, math
import pandas as pd
from collections import defaultdict
T_MIN = 1
T_MAX = 226
# wide-format dataframe
#df = pd.read_csv(open(sys.argv[1]))
df = pd.read_csv(sys.stdin)
## Normalize each row -- this takes a while to run
#print('Normalizing each timecourse...', file=sys.stderr)
#
#for index, row... |
cafbc2424e77c15fc787c6d72d393cf2ab044e07304dde3cac1c3da9a8f7f339 | Python | 2,289 | 89 | """Tests for EMADict."""
from typing import Any
import pytest
import torch
from mrpro.utils import RandomGenerator
from mrpro.utils.ema import EMADict
@pytest.mark.parametrize(
('key', 'value'),
[
('float', 1.0),
('complex', 1.0 + 1.0j),
('tensor', torch.ones(2, 3)),
],
)
def tes... |
56097caf04736c9c22060e41f53cd327b2c5fad33f5998780466ac42d466f7ed | Python | 2,290 | 55 | #!/usr/bin/env python
__author__ = 'etseng@pacb.com'
import os, sys
from cupcake.io.SeqReaders import LazyFastaReader
from phasing.io.MummerSNPReader import write_snp_to_vcf
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser("Process one or more .snps_files files from dnadi... |
5ade3f376e8ceb0f207d958bc6be67cae4a96eaa83a8703ae83fb4d26a81be95 | Python | 2,291 | 64 | import os
import json
import concurrent.futures
import time
apkfilename = []
permission_frequency={}
path = r'E:\pythonProject\Experiment\out_benign_samples'
apk_list=os.listdir(path)
for apk in apk_list:
apk = os.path.join(path,apk)
apkfilename.append(apk)
def GetSmaliFileList(dir, fileList):
... |
6097de5a498ec148b3b56e5a675513490508a466d5b1c6cb6a774cf008f9c1f7 | Python | 2,291 | 79 | # coding: utf-8
import os
import sys
from atropos.io import xopen, open_output
from atropos.io.compression import get_compressor
base = "tests/data/small.fastq"
files = [base + ext for ext in ["", ".gz", ".bz2", ".xz"]]
def test_context_manager():
major, minor = sys.version_info[0:2]
for name in files:
... |
d687dde8708db77230c9cfb5b1d1016e1eeb9419ca06851bcef711edbda987eb | Python | 2,291 | 67 | import vegas
import numpy as np
import gvar as gv
from outputsplitter import log_stdout, unlog_stdout
log_stdout('eg8a.out')
integ = vegas.Integrator(2 * [(0., np.pi/2.)])
gv.ranseed(123)
@vegas.rbatchintegrand
def f(x):
Ia_num = np.exp(-1e2 * np.sin(x[1])) / ((x[0] - x[1])**2 + 0.01)
Ib = 1 / (x[0]**2 + 0.... |
30d8bdd7fd59420a20f64564ce7b9b04e93ba11f4d37f531ac02232c01efa041 | Python | 2,295 | 76 | import json
import logging
from pathlib import Path
from typing import Dict, Optional, Union
import torch
import torch.nn as nn
from .scale_factor import ScaleFactor
ScaleDict = Union[Dict[str, float], Dict[str, torch.Tensor]]
def _load_scale_dict(scale_file: Optional[Union[str, ScaleDict]]):
"""
Loads sca... |
3625a7d01fcfc8a4ed8a41d57aece49cc54763b1aa2e7ee48b5896582f19b347 | Python | 2,295 | 95 |
import pandas as pd
# Load DataFrame from .pkl file
file_path = '../CW-sustained-experiments/no_filter/results/df_all_waveforms_metrics.pkl'
df = pd.read_pickle(file_path)
# Display DataFrame contents
print("DataFrame Contents:")
print(df)
print(df.columns)
df_laser = df[df['type'] == 'laser']
df_control = df[df['... |
7a76c3fde26f1ed23f89939a8dde78d27f4ca212d37aaf039d90d2a9975027e4 | Python | 2,295 | 94 |
#### create branch- and depth-specific pcfg
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import model
MAX_ITER = 20
#### 0) read model from stdin
mCr = model.Model('Cr')
mCC = model.CondModel('CC')
mCu = model.CondModel('Cu')
mX = model.CondModel('X... |
05d30213356eff9b8c6fc43f5af21504cc5252efa0a30370838181da0cc0b4f5 | Python | 2,296 | 70 | from typing import Iterable, List, Literal, Mapping, Optional, Sequence, Tuple, Union
import numpy as np
import scanpy as sc
from anndata import AnnData
def filter_peaks(
data: AnnData,
min_counts: Optional[int] = None,
min_cells: Optional[int] = None,
max_counts: Optional[int] = None,
max_cells:... |
495ab0cfad469d44f765c4e5823f15a022b7ceecaa4c6d493937a1abeaed926e | Python | 2,298 | 80 | import numpy as np
import pandas as pd
class FillNa:
params = [True, False]
param_names = ["inplace"]
# inplace=True can only run once as it mutates the data
number = 1
def setup(self, inplace):
N = 10**6
rng = pd.date_range("1/1/2000", periods=N, freq="min")
data = np.ra... |
25e1d149944cdfe5f8afa4bf0a7bb520dc0abe21f3844d09032e05231e88c15d | Python | 2,300 | 53 | #Save results of sweeps over eps, eta for 20 fields. This accompanies 'avalanche_sweep2_run20fields_20211124.py'
#in future versions, the saving functions should be run at the same time as simulation.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
fr... |
a4545c68b27041b88a65e091f0096430e29099fa8fedabbca46127cb2656d3e0 | Python | 2,303 | 79 | """Entry point for the litpose command-line interface."""
from __future__ import annotations
import logging
import sys
from importlib.metadata import version
from lightning_pose.cli import friendly
from lightning_pose.cli.commands import COMMANDS
def _setup_logging(debug: bool = False) -> None:
"""Configure th... |
220bbe51c88acac7eba93f8c25dab16699b0620d777551c70282416f89533718 | Python | 2,304 | 65 | from argparse import ArgumentParser
import datetime
import getpass
import itertools
import os
import yaml
class Config:
def __parse_args(self):
parser = ArgumentParser()
parser.add_argument('parameters', metavar='param', type=str, nargs='*',
help='parameters')
p... |
0b99eb1a04cede639380a585e116252626de1b4603fcb8fb20c36ce71a746c51 | Python | 2,305 | 98 | import numpy as np
import matplotlib.pyplot as plt
# increase the figure size
plt.rcParams["figure.figsize"] = [12, 10]
# remove the top and right spines from plot in the global plt setting
plt.rcParams["axes.spines.top"] = False
plt.rcParams["axes.spines.right"] = False
# change the linewidth of the axes and spines
... |
65553d47cad9a1f68aa5df0753591485e74978e6f6afa8cf21d8e05c66fd1a0e | Python | 2,305 | 79 | """
Tests that work on both the Python and C engines but do not have a
specific classification into the other test modules.
"""
from io import StringIO
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize("na_filter", [True, False])
def test_inf_parsing(all_parsers, na_filter):
... |
78159c58808c408bb6ad728f9af6e004a04012411ec4ff4491beb34c95df0726 | Python | 2,305 | 40 | """Video-reading backends for training and prediction.
Three backends implement the same reader contract:
- ``dali.py`` (GPU video loading via NVIDIA DALI, training + prediction)
- ``pynvvc.py`` (direct NVDEC access via PyNvVideoCodec, prediction only)
- ``opencv.py`` (CPU decode via OpenCV, prediction only)
:func:`... |
ce9f6daa19c81395f23473c27ef92883c2b26f59b0ac7fcd368d19542c524410 | Python | 2,305 | 60 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.core.indexes.multi import cartesian_product
class TestCartesianProduct:
def test_simple(self):
x, y = list("ABC"), [1, 22]
result1, result2 = cartesian_product([x, y])
expected1 = np.array(["A", ... |
9a63de1ed678f4047b0c30453ea5ef0c667375c84aced60902a557e5ae5133e4 | Python | 2,307 | 69 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 16 19:25:48 2023
@author: tomas
"""
from skimage import feature, measure, transform, exposure, util
import numpy
class SiftAligner:
# based on
# https://stackoverflow.com/questions/62280342/image-alignment-with-orb-and-ransac-in-sciki... |
fa5b21eb4b62ec1addb6a64d29d65452619b8614eb9537f9d698b6260b83ffa5 | Python | 2,307 | 62 | """Report generator for the error command.
TODO: move reporting functionality out of the ErrorEstimator class.
"""
from itertools import repeat
from atropos.commands.reports import BaseReportGenerator
from atropos.io import open_output
from atropos.commands.legacy_report import Printer, TitlePrinter
class ReportGener... |
55befee1c838122925d193ef2409c1eace8c3092fb94854b6636d0e04cf57768 | Python | 2,308 | 63 | """Selection operations emitted by workflow tables.
This small value object deliberately has no Qt, GUI, or Supervisor
dependencies. A table can describe how its selected IDs changed without
making a controller infer an operation from the final IDs alone.
"""
from __future__ import annotations
from dataclasses impor... |
dbf7c240f75d84325a986a2208edd99a4616b2f2f0dc9d9b80308d8c1b437e66 | Python | 2,308 | 59 | from __future__ import print_function
#### import the simple module from the paraview
import paraview.simple as para
import os.path
import argparse
parser = argparse.ArgumentParser(description='Resample onto new mesh using paraview')
parser.add_argument('-cd', '--case-dir', default=None, required=True, help='Case dir... |
3002b31d3819d4e786612d7770054730843f28da3613a7095df541dbb2d2c218 | Python | 2,309 | 92 | import dependency
import DepsTools
import re
import sys
##calcuate the most likely gcg dep match sd deps
sdF = open(sys.argv[1], 'r', encoding="utf8")
sdDeps = DepsTools.readDepsFromFile(sdF)
print(len(sdDeps))
gcgF = open(sys.argv[2], 'r', encoding="utf8")
gcgDeps = DepsTools.readDepsFromFile(gcgF)
print(len(gcgDeps... |
9027d9756a7f95ceb28ba52b0a23dbc7415a0f3eb1bb5b41fdf94e24dfe45866 | Python | 2,309 | 61 | from __future__ import absolute_import
import pandas as pd
import numpy as np
import dask
import dask.dataframe as dd
from ._add_nparray_aligned import add_aligned
from ._helper_functions import time_list_from_pd, pd_to_array, map_return_to_series
def universal_pd(df, distance_column, spacial_distance_bins = 50, min_... |
f2cf6a9cb21f0a2d609d9f2279a8b7f7f95c6447d039e022407f8f0c6861aef4 | Python | 2,309 | 52 | import numpy as np, matplotlib.pyplot as plt, sys
plt.rc('xtick',labelsize=12)
plt.rc('ytick',labelsize=12)
to_paper = "--to-paper" in sys.argv
compreal = "comp"
fname_add = ""
for s in sys.argv:
sa = s.split(":")
if sa[0] == "--real": compreal = "real"
if sa[0] == "--merged-L-R": fname_add = "_merged_"
p... |
f74d5262999df54bb53d8e189ae399a01c1af2943c997206451b26ee578de321 | Python | 2,309 | 60 | # 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... |
3be7294c60225a46736c74a884881b236a399291d92b91944a353390562d2a14 | Python | 2,310 | 88 | #
# File to get metadata from pdbs files and store them in the hdf5 file
#
from argparse import ArgumentParser
import sys
import Bio.PDB as pdb
import Bio.PDB.mmtf as mmtf
import h5py
import numpy as np
from protein_holography.utils.posterity import get_metadata, record_metadata
parser = ArgumentParser()
parser.ad... |
7ef45b0b12c0c8927574fb0b55ba020a772d0e0b8372150512803d7d0d9d849d | Python | 2,310 | 74 | #python spargeComplexity.py [-o] [-id id_file]
#extract complexity from stdin (mixed complex/output)
#-o: extract output from stdin (instead of complexity)
#-id: output sentence ids from the given id_file
import re
import sys
REPORT_COMPLEX = True
FIRST = True
idlist = []
if len(sys.argv) > 1:
for i,arg in enumerat... |
0ed29bbcd2298a1f4b62d0c0e462a33747de69f702e1a6847ce9deb08fa65d49 | Python | 2,311 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot PSD split by group. @author: mikkel
"""
import numpy as np
import matplotlib.pyplot as plt
import os.path as op
import pandas as pd
import scipy.io as sio
import sys
sys.path.append('/home/mikkel/PD_longrest/scripts')
from PDbb2_SETUP import subjects, meg_path
#%... |
661b6ac9468c2365a620f9047bdab2d9d8b283071859d42ff1de08cab8b70299 | Python | 2,312 | 61 | import os
from copy import deepcopy
from trainers.rule_trainer import RuleTrainer
from evaluators.evaluator import Evaluator
from models.bow.args import get_args
from datasets.scar_bow import SCARBoW
import warnings
import datetime
if __name__ == '__main__':
args = get_args()
# Setup config
config = deepc... |
b6b70c57f6f51243f5dbd8f4cfb7266cc4de0188e0427221adbe02c20a993290 | Python | 2,312 | 60 | """
Created on Jan 8, 2023.
dp_chest_diff_correlation.py
@author: Alexander Ziller <alex.ziller@tum.de>
"""
import pandas as pd
from scipy.stats import pearsonr
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import seaborn as sn
# %%
sn.set_theme(context="notebook", style="whi... |
d37e73aa094d97991c9c72d9bac6fc5a7c15d3be64c3586ce180740713b3fda4 | Python | 2,312 | 65 | # 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... |
2364d4f2c5c3a45464cb03a9a89712ebb044a1e8381ad5f5e89521fdec89c4ab | Python | 2,314 | 61 | """Tests for PeriodIndex behaving like a vectorized Period scalar"""
import numpy as np
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestPeriodIndexOps:
@pytest.mark.parametrize(
"old_attr, new_attr",
[
("dayofweek", "... |
b03d40d4a6a5a3205c4a04230480f7f26c644a6fe43c17f173ac4d65c0747785 | Python | 2,314 | 77 | """SQLAlchemy engine + session factory + FastAPI dependency.
Phase 3: this module is dual-backend-aware. SQLite stays the zero-config
dev default (``PYCARET_DATABASE_URL=sqlite:///./pycaret.db``); production
deploys point at Postgres via ``postgresql+psycopg://user:pass@host/db``.
The driver is selected purely by the... |
cc81c7ff44434582beffade7a3804f668721163da43fce53ea551ad710b15cf9 | Python | 2,314 | 55 | # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
c38303f8a2296d93a1a2c955ef404b2fe87c84efab1c269c088fb606329678c4 | Python | 2,315 | 63 | #!/usr/bin/env python
import imp
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 8):
sys.exit("Sorry, Python < 3.8 is not supported")
VERSION = imp.load_source("", "assemblyfire/version.py").__version__
setup(
name="assemblyfire",
authors=["Andras Ecker", "Michael Reiman... |
f5377676355ee9d49e8452ce5f0bb0222881145f37761a3593b9d472aca680ce | Python | 2,315 | 76 | #%%
#Imports
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import matplotlib.backends.backend_pdf
plt.style.use('seaborn-talk')
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from scipy.stats import gau... |
bf068b911ef25f837296d3aeb00133ee4bf788106ef5ae31e8b04f961e532860 | Python | 2,316 | 68 | # 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... |
d03bc159cd3a23972d60874a5bc5be06011ac7bbffddb87968d5766cabc60577 | Python | 2,316 | 69 | """Code for PSTH-related statistical analysis."""
from typing import Any
import pandas as pd
import pingouin as pg
def calc_pre_post(
df: pd.DataFrame,
event: str,
t_pre: tuple[float, float],
t_post: tuple[float, float],
measure: str = "mean",
) -> pd.DataFrame:
"""
Compute the average o... |
3f999d1f1dc84e969621fbb4f47b8974e85a2125a739fbdb527fb8f83bbd1b4e | Python | 2,318 | 61 | #Save results of sweeps over time constants for 20 fields. This accompanies 'avalanche_timesweep_run20fields_20211216.py'
#in future versions, the saving functions should be run at the same time as simulation.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg im... |
61fc9fc9a01e1c407837bf06d8759268c94a9c562b3727149dab4add6e6a6506 | Python | 2,319 | 70 | import torch
from torch import nn
import copy
from ..mlp import MLP
from ..convs import EGNNConv
from ..basis import GaussianRandomFourierFeatures
# Typing
from torch import Tensor
from typing import List, Optional, Tuple
class Encoder(nn.Module):
def __init__(self, init_node_dim: int, init_edge_dim: int, node_... |
7ca60e02cc542fd91eb4a7c31d213b4337752e46d02c117fa2ed94231678dfaa | Python | 2,319 | 76 | # 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... |
dc006af8093f12e717697e3e6f44e233a5bc6b18863c1a7008cdbf10a5991a2a | Python | 2,319 | 73 | #!/usr/bin/env python
'''
Testcases for the KwargsParser
'''
from windseer.utils.derivation import *
import torch
import unittest
input_tensor = torch.tensor([[1, 2, 3], [1, 2, 3],
[6, 5, 4]]).unsqueeze(0).unsqueeze(-1).float()
class TestDerivation(unittest.TestCase):
def test_der... |
03d5c9ee308f36d28b83e98bd105fd750f11eb3f4fb5c0cee05e2cbdae6b02e7 | Python | 2,321 | 68 | __all__ = [
"NeutralLossTypeInfo",
"NeutralLossTypeCollection",
]
import os
from dataclasses import dataclass
from typing import Dict, Mapping, Optional
from ...util.io.yaml import load_yaml
from ..common.elements import ElementCollection, ElementComposition
@dataclass(frozen=True)
class NeutralLossTypeInfo... |
be7b4630410bafda3f10b57f772ff02aa2b823267dd694d39f79721edb6a9eea | Python | 2,323 | 52 | # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
dcb4be8db2621627d30b93fcc39059abdb5ffe7f22c5c111b7156df0b690026a | Python | 2,324 | 49 | #!/usr/bin/env python
import argparse
import subprocess
import sys
import gzip
import time
from Bio.SeqIO.QualityIO import FastqGeneralIterator
parser = argparse.ArgumentParser(description='A program to append barcode to fastq for scidrop data.')
parser.add_argument('-1', '--input1', nargs='?', type=argparse.FileType(... |
05f4b6a31352ff081eff301ed62d94794de0e8bd21051b18a8ff59e3fcddd929 | Python | 2,325 | 71 | import matplotlib
matplotlib.use("TKAgg")
import numpy as np
from base import examples
from base import loggingUtils
from base.curves import Curve
from base.kernelFunctions import Kernel
from base.curveMultiPhase import CurveMultiPhaseParam, CurveMultiPhase
def compute(name = 'TwoCircles'):
outputDir='/Users/youn... |
2e5e150c051714f1236a46e1a04737fd9979af6139ec33906c83829123657633 | Python | 2,325 | 49 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
41c2fbffabc493fce1e0e1b9e4f9dd5d48a46883b11da8cffacd9a1d60d63725 | Python | 2,325 | 57 | """Allocator lifecycle through public tracks, in bounded fresh processes.
The Linux shim builds in <1 s; each growth/sort/sample probe takes ~1–3 s
and <150 MiB. Use --run-slow. No MACS3 native symbol is patched or called.
"""
import os
from pathlib import Path
import shlex
import subprocess
import sys
import sysconf... |
6bc758b50e5e1f2ab21366580f00c7f77df065b972550ae4204e7d09a9b03a3d | Python | 2,326 | 66 | import inspect
import torch.optim.lr_scheduler as lr_scheduler
from ocpmodels.common.utils import warmup_lr_lambda
class LRScheduler:
"""
Learning rate scheduler class for torch.optim learning rate schedulers
Notes:
If no learning rate scheduler is specified in the config the default
sc... |
bbea200b525ead40494837c3cab7e5c86e9e98fa1d53f1107ff29962e65a9dde | Python | 2,326 | 62 | # Copyright 2024 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
30dd33e4af26791218107648afc8384ffed4c1666ccee09a066878f75a9118f6 | Python | 2,327 | 77 | #!/usr/bin/env python
'''
Convert a dataset of csv files to serialized torch tensors.
'''
from __future__ import print_function
import argparse
from windseer.data import convert_dataset
import time
def main():
'''
Convert a tar file containing the flows in csv format to a hdf5 dataset of tensors.
'''
... |
689328acf9d98a2d838c2442edd9a3fa4bf4551fbf1a4d4efddc17d15e5e466c | Python | 2,329 | 78 | #!/usr/bin/env python3
#
# Copyright 2014 Google Inc. All rights reserved.
#
# 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 requir... |
8bbb95d3b22e09588943d21f351be1052d1aaec45fef3d224d0aeed20869522e | Python | 2,329 | 60 | import argparse
import os
import numpy as np
import pandas as pd
def get_args():
"""
Get arguments from command line with argparse.
"""
parser = argparse.ArgumentParser(
prog='MAG-Summary.py',
description="""Grab all summary files from GTDB-Tk and merge.""")
parser.add_argument("-g"... |
2485ae65bd275a6aa874d66a72e4f3a1249f6fa1e99e24bd9e6afcf46bbc2273 | Python | 2,330 | 60 | import torch
import math
from torch.optim.lr_scheduler import _LRScheduler
from collections import Counter
import warnings
class PolyLR(_LRScheduler):
"""Set the learning rate of each parameter group to the initial lr decayed
by gamma every epoch. When last_epoch=-1, sets initial lr as lr.
Args:
... |
436c6fee6a62a860996a23980c1e3d0978341f1c74860e04c0a68684da4b2dbc | Python | 2,335 | 52 | import torch
from torch.optim.lr_scheduler import LambdaLR
def mse_batch(y,y_hat):
return ((y - y_hat)**2).sum()
def mae_batch(y,y_hat):
return (y - y_hat).abs().sum()
def get_polynomial_decay_schedule_with_warmup(
optimizer, num_warmup_steps, num_training_steps, lr_end=1e-7, power=1.0, last_epoch=-1
):
... |
cd0c2c9070cc4d3cfd1d93a83b452691ea47e035aa9eae05b7a504a6d198a8d5 | Python | 2,336 | 75 | import logging
from torch.autograd import Function
import torch
from .transform_convert_torch import axisangle2mat_torch, mat2axisangle_torch
USE_TORCH = False
if not USE_TORCH:
try:
import nesvor.transform_convert_cuda as transform_convert_cuda
except ImportError:
try:
from torch.... |
4c972c9fce1b78a5f09bc7a869823b87b09404d60afdbe8e658748f9c49813e5 | Python | 2,337 | 71 | # Embed TED-100 domains with progres
# This script is illustrative of the method
# The PyTorch output files are combined into one file afterwards
import progres as pg
import torch
import urllib.request
import os
import sys
run_n = int(sys.argv[1])
cluster_rep_file = f"cluster_rep_splits/split_{run_n}.txt"
out_file =... |
0f27488796e0c301cd4d4488cada3dea7b83878a79eb197c59cd975cf7455a99 | Python | 2,338 | 72 | """Convert command for the lightning-pose CLI."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Any
def register_parser(subparsers: Any) -> argparse.ArgumentParser:
"""Register the convert command parser."""
from textwrap import dedent
description_text =... |
2ee8850e4763d76bd3f0cf161e12f5a91743d2c04b14d47b8dea59d7a77ec7c0 | Python | 2,338 | 87 | from models.model import input_dim, output_dim
from utilities.utilities import *
import random
# Load the data into
def load_data(data_path, nb_examples=None, normal = True):
volumes_folder_path = data_path + "/volumes"
labels_folder_path = data_path + "/labels"
volumes_path = get_dir(volumes_folder_pa... |
08aaa7b48aa92e51968afa75dfe5e3cd61a57140db8f0a063e4831811967324b | Python | 2,339 | 62 | import scipy.io as scio
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from scipy import sparse
import torch.nn.functional as nn
import sys # 导入sys模块
sys.setrecursionlimit(3000) # 将默认的递归深度修改为3000... |
1cb9c5d95d69e9855d9013c3af65ec7f67d12232d2131abdba0a08c261c5d86e | Python | 2,340 | 64 | """Bridge engine events into the platform database and the WebSocket broker.
`DBEventLogger` subclasses `pycaret.logging.BaseLogger` and overrides `emit()`
to:
1. Serialize the engine `Event` into our `events` table row.
2. Broadcast the same payload through `event_broker.publish(run_id, ...)` so
connected WebSock... |
261da4b43e31ff4727bdfdd6d1c6058baffc747fc98fffd0ee47d5c369161c70 | Python | 2,341 | 93 | # -*- coding: utf-8 -*-
# JN 2016-01-12
# JN 2014-10-28
from __future__ import division, absolute_import, print_function
import datetime
import tables
def make_blocks(N, bs=100000):
"""
creates block starts and stops of length bs
"""
starts = list(range(0, N, bs))
if N - starts[-1] < bs/4:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.