sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
48078ebde0e3cc437f08a21204dd38da0c1c2a9096372995399e471d26ea1c59
Python
1,226
47
# Autogenerated by configen, do not edit. # If encountering an error, please file an issue @ # https://github.com/romesco/hydra-lightning # fmt: off # isort: skip_file # flake8: noqa # Hydra + Lightning from dataclasses import dataclass from dataclasses import field from typing import Any from typing import Optional f...
6bb180ff084b6ce892e16c5476d0eba8a39486c7eaab74cbd27921a8f71cbacb
Python
1,226
36
import numpy as np from pandas import ( IntervalIndex, date_range, ) class TestEquals: def test_equals(self, closed): expected = IntervalIndex.from_breaks(np.arange(5), closed=closed) assert expected.equals(expected) assert expected.equals(expected.copy()) assert not expe...
7cd9e823fb25ffd1203d66d079626480c6877c5077f253c62e35fb0a03852058
Python
1,226
38
''' Created on 2014.11.13 @author: Liang Qian ''' class Synapse(): ''' synapsis class is used to create a synapsis structure members are as follows: @param pre: pre-synapsis neuron @param post: post-synapsis neuron @param locationlayer: layer where this synapse locate in ''' def _...
80c86da231f529d470c4c98cfd495b9719382f4f68ed62d4b172e9eaa7544be2
Python
1,227
53
""" All of pandas' ExtensionArrays. See :ref:`extending.extension-types` for more. """ from pandas.core.arrays import ( ArrowExtensionArray, ArrowStringArray, BooleanArray, Categorical, DatetimeArray, FloatingArray, IntegerArray, IntervalArray, NumpyExtensionArray, PeriodArray, ...
65812e44409c9b340495c94704291cd1c49ddac3d98818e4998d2701e8af6fb3
Python
1,229
40
import pandas as pd import matplotlib.pyplot as plt import numpy as np import os # Create output directory os.makedirs('paper_graphs/Deletion_Distance_Plots', exist_ok=True) # Read the data df = pd.read_csv('CT2_log/euclidean/high_variation_genes/deletion_distance.csv') # Create figure fig, ax = plt.subplots(figsize...
91e1835398743dd0f6ec909cdcb90abd4e38a39ef37a717f3627530ca58a9761
Python
1,229
46
"""Plots the voltage along a fiber, as well as its first and second spatial differential. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-...
950313464b624dfdc2d0cf3864cbdf80f2109aeab5bc505b17f8e7ee193b8ced
Python
1,229
39
import numpy as np import matplotlib.pyplot as plt from matplotlib import pyplot import matplotlib as mpl from scipy.ndimage import gaussian_filter1d plt.figure( figsize=(8,8) ) steps=1000 t = [i for i in range(steps)] plt.style.use('seaborn-whitegrid') palette = pyplot.get_cmap('Set1') font1 = {'family': 'T...
6709be69242030106149ee7b6e81cf2817edecdb41153b9d8267e9185f09edff
Python
1,230
44
########################################################################## # NSAP - Copyright (C) CEA, 2019 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ##########...
34095797ddafe26ce103845dd37739ebe30df91c42ca3134224080c5c80be061
Python
1,231
29
from CrystalTracer3D.plot import * from CrystalTracer3D.io import * from CrystalTracer3D.band import * import yaml from tqdm.contrib.concurrent import process_map with open('../vessel_density_local/config.yml', 'r') as ymlfile: cfg = yaml.safe_load(ymlfile) def main(in_dir): reader = CrystalReader(Path(cfg['...
ac846a533ae3456b6f4fcddb4cde0eb84646d1e73ba19289628b14fb0c2dc465
Python
1,233
41
''' Related Figures:3b-c ''' import numpy as np class kalman_filter(): def __init__(self,trainX,trainY): X1=trainY[:,0:-1] X2=trainY[:,1:] A=np.dot(((X2)@(X1.T)),np.mat(X1@(X1.T)).I.A) H=np.dot((trainX@(trainY.T)),np.mat(trainY@(trainY.T)).I.A) n=trainY.shape[1] W=((...
c74387e3f80dc7ed77ab0d7f1988a115e9754b86d61336eb47f553f87f71e2d4
Python
1,233
44
""" Check the numpy config is valid. """ import numpy as np import pytest from unittest.mock import patch pytestmark = pytest.mark.skipif( not hasattr(np.__config__, "_built_with_meson"), reason="Requires Meson builds", ) class TestNumPyConfigs: REQUIRED_CONFIG_KEYS = [ "Compilers", "Mach...
b65d72af7879d11d2deeebf04dc7ec456fa3b759fdbeca9fe015a9e1d35375df
Python
1,234
50
from datetime import datetime import numpy as np from pandas import ( DataFrame, Index, MultiIndex, Period, Series, period_range, to_datetime, ) import pandas._testing as tm def test_multiindex_period_datetime(): # GH4861, using datetime in period of multiindex raises exception ...
855ffa08b7683e6d2f6b6d96a70e332aa334458b33dd36715e3d0fa12fbd7834
Python
1,236
43
from typing import Iterable, Tuple, TypeVar T = TypeVar("T") def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for first value.""" iter_values = iter(values) try: value = next(iter_values) except StopIteration: return yiel...
e407a77cd0042951957a28886601b7a7d4a8772071ef6b81d16f82769186cb0c
Python
1,236
40
import torch from tqdm.auto import tqdm from functools import wraps def parse_device(gpu_id): if torch.cuda.is_available() and gpu_id >= 0: device = torch.device(f"cuda:{gpu_id}") else: print("GPU index not provided or no GPU support currently available.") print("!!! Running on CPU !!!...
285a3968e5a18f497351d0e1b05c9633306e30e9cd9d5f636a55bdf9a45416ae
Python
1,237
51
# Copyright (C) 2012,2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ avg_q unit testing. Usage example: from avg_q.unittests import avg_q_test_case class avg_q_test_case1(avg_q_test_case): script='xx' expected_output='yy' import unittest unittest.main() """ imp...
3541de9317c814dc5a251597bc2a78156bf35cb6141cb754376f0cf44fdb22b8
Python
1,237
39
from xgboost import XGBClassifier from shap.datasets import adult from shap.explainers import PermutationExplainer from shap.maskers import Partition class PermutationSuite: # Adapted from tests/explainers/test_permutation.py max_samples = 100 def setup(self): self.model = XGBClassifier(tree_met...
b2ac492448ee6cb74396673e386e9c651b58c719f5f6dcff74e25f11b1576f4f
Python
1,237
51
import pytest import cedalion.data import cedalion.nirs import cedalion.sigproc.motion as mc import cedalion.sim.synthetic_artifact as synthetic_artifact from cedalion import units @pytest.fixture def rec(): rec = cedalion.data.get_snirf_test_data()[0] rec["amp"] = rec["amp"].pint.dequantify().pint.quantify(...
0e1cf2766515385ef52e1f3691246651d8d952bd274d65e748a03fe7a0a69910
Python
1,238
35
import yaml from tqdm.contrib.concurrent import process_map from skimage.util import img_as_ubyte from skimage.io import imsave import nrrd from skimage.transform import rescale, resize from CrystalTracer3D.segment import * from CrystalTracer3D.util import * from CrystalTracer3D.plot import * with open('config.yml',...
8e743091ed00162c42c0d590cfb4a5aacb13f56e0f287fc201a5eeab4a5632d5
Python
1,239
41
import matplotlib.pyplot as plt import seaborn as sns from tqdm.contrib.concurrent import process_map from pathlib import Path import nrrd from skimage.io import imsave import numpy as np from skimage.transform import resize from CrystalTracer3D.io import CrystalReader from CrystalTracer3D.util import stitch_tiles ...
5d6e518b2a9d04182eaa25bb9e5e8b1522ae19964ba003a236f33d094478f676
Python
1,240
47
import datetime import pickle import cloudpickle def reformat_timestamp(timestamp): if len(timestamp)==10: return timestamp # Parse the input timestamp into a datetime object dt_object = datetime.strptime(timestamp, '%d-%b-%y') # Format the datetime object into the desired output format ...
6605b0d40ffd3c96d9c67b27a8a3211f2bbeb4271f9ae190af275df4ce5a290f
Python
1,240
29
#!/usr/bin/env python # ============================================ # # Getting hamiltonians.h5 using trained models # # ============================================ # # Usage: python <path-to-this-file>/eval.py <your_config>.ini [-n NUM_THREADS] [--debug] # Default config file for evaluation is DeepH-E3/deephe3/defa...
2cd39fd9526c575ec50d3f688040db6ba95ae35e325269b9cffec1f7b9cb376e
Python
1,241
42
from datetime import datetime from pandas import DataFrame import pandas._testing as tm class TestInferObjects: def test_infer_objects(self): # GH#11221 df = DataFrame( { "a": ["a", 1, 2, 3], "b": ["b", 2.0, 3.0, 4.1], "c": [ ...
202e3f6668ec5f8f34e0d9eefa540371c42bd33b799b321911a07707376f6bc6
Python
1,244
55
""" Public API classes that store intermediate results useful for type-hinting. """ from pandas._libs import NaTType from pandas._libs.missing import NAType from pandas.core.groupby import ( DataFrameGroupBy, SeriesGroupBy, ) from pandas.core.resample import ( DatetimeIndexResamplerGroupby, PeriodInde...
f4606e7de9dca3174817d6a5b69d815f40c9bf8fe83fd03f15f8a388eb1b1330
Python
1,244
46
from __future__ import annotations from stimuli.trigger._base import BaseTrigger from .utils._docs import copy_doc from .utils._imports import import_optional_dependency class SerialTrigger(BaseTrigger): """Trigger using a serial port for micromed iEEG amplifiers.""" def __init__( self, por...
665e966e46e74d6569e852f6ad1db5a811ac2e885ea081195ea5992b17e90d1b
Python
1,245
42
import sys import os import numpy as np import tensorflow as tf thisfile = os.path.abspath(__file__) modulepath = os.path.dirname(os.path.dirname(thisfile)) sys.path.insert(0, modulepath) from tensorcircuit.applications.vags import double_state, reduced_density_matrix def test_double_state(): s = double_state(...
b3ae1d6793ba32b060d4d94884e04ecb9dbd0bbcc4bd8e9474efbd4980faa92c
Python
1,245
45
#!/usr/bin/env python # Copyright (C) 2008-2012,2017 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). import sys import voglps import cairo # Derived class with cairo plotting operators class cairovogl(voglps.voglps): def __init__(self,psfile,surface,width,height): voglps...
e85f15757cab455e6368c6937aeaf17b06973885fd90ac6da8d3dd2ef478126d
Python
1,245
51
"""Contains code to create and manage comparison objects""" from .binning import ( RecordPairGenerator, MissingRecordPairGenerator, QueryRecordPairGenerator, QueryMissingRecordPairGenerator, ConnectedComponentPairGenerator, generate_mix_bin, legacy_bin_generator, legacy_weights_from_cla...
d7a0033d05e6b8fe89ae2e21030448b1a8508e9cac5950b8940ec028888cb99e
Python
1,247
39
""" Model architectures: frequency-domain CNN only (MLP support removed). """ import torch import torch.nn as nn class CNNModel(nn.Module): """CNN model for processing frequency-domain features.""" def __init__(self, num_classes, num_channels=3, drop_prob=0.3): super().__init__() self.num_chan...
23c220d79f064d8b6a2f07aba3b342e72077caab9e3bf9392ac29e72f433ab46
Python
1,249
37
import os from typing import Any from github_utils import gh_post_pr_comment from gitutils import get_git_remote_name, get_git_repo_dir, GitRepo from trymerge_explainer import BOT_COMMANDS_WIKI def parse_args() -> Any: from argparse import ArgumentParser parser = ArgumentParser("Comment on a PR") parser...
27d7b85a56751426dff741014ce1abae6813a792ad457b69d48f99de82a8dbc3
Python
1,250
42
from pymatgen.core import Structure import numpy as np import sys def get_kgrid_from_spacing(poscar_file, k_spacing=0.05): """ Compute Monkhorst-Pack k-point grid dimensions for a given structure and target reciprocal spacing. Args: poscar_file (str): Path to POSCAR/CONTCAR. k_spacing ...
900c1ac0b58642f392924865cc6ecad28f0a103af623ff97a5e3d2c9b064118d
Python
1,250
47
from __future__ import annotations from typing import TYPE_CHECKING from fonticon_mdi6 import MDI6 from pymmcore_widgets import LiveButton, SnapButton from qtpy.QtCore import QSize from superqt.fonticon import icon if TYPE_CHECKING: from pymmcore_plus import CMMCorePlus from qtpy.QtWidgets import ( Q...
c587aa9d249d9cf4a69b332a3de21676eecb0254f75dad3af6fec3eace9ffe5c
Python
1,251
32
import torch import torch.nn as nn import torch.nn.functional as F from ..functional import cutoff_function, softplus_inverse """ computes radial basis functions with exponential Gaussians """ class ExponentialGaussianRadialBasisFunctions(nn.Module): def __init__(self, num_basis_functions, cutoff, ini_alpha=0.5...
14cd7a4617b8cba1c3ab0827cfd63fdacceb37bab163fa82a9da5d391d7de61c
Python
1,252
38
from typing import Optional from app.config.recording import RecordingConfig class RecordingConfigValidator: @classmethod def _validate(cls, recording_config: RecordingConfig) -> Optional[str]: if recording_config is None: return "Config is null" if recording_config.mode is None:...
753f2cd253dd0914ec20b897a75902f70229ab72fc87ce9bc5b20955f79429d0
Python
1,252
29
import time from pytorch_lightning.callbacks import Callback class EpochTimeLogger(Callback): def __init__(self): super().__init__() self.train_start_time = None self.predict_start_time = None self.training_iter = 1 self.predict_iter = 1 def on_train_epoch_start(self, ...
2f58003236183c1e9e6264a9a577dbc0f54a6b71c23687ea3d5519de0c4b95d0
Python
1,253
36
import pytest from pandas import ( DataFrame, Index, MultiIndex, ) import pandas._testing as tm class TestDropLevel: def test_droplevel(self, frame_or_series): # GH#20342 cols = MultiIndex.from_tuples( [("c", "e"), ("d", "f")], names=["level_1", "level_2"] ) ...
e512cffc5fe236c43c5f4fd97995df137b75e0daa2f2eeeaf7df411b1b72a75e
Python
1,255
57
#!/usr/bin/env python3.7 """Plot a sample. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FROM REPOSITORY ROOT ""...
f88da1cacdbf027417a7e718e70ef07ef65282e4bdca02ea1afb16e51995e668
Python
1,255
48
#!/usr/bin/env python3.7 """Plots the voltage along a fiber, as well as its first and second spatial differential. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: ...
d691284ba8d1b8a7c8bede0ecd556620b8e3ba69c6fe76f7070445fa8e4d614a
Python
1,257
49
#!/usr/bin/env python3 """Build a macOS arm64 PyTorch wheel. Usage: build_wheel.py <output_dir> Mirrors .ci/wheel/linux/build_wheel.py. Build flags are expected in the environment (set by build_env_setup.py and sourced by build.sh); this script adds only the macOS host-platform plumbing and runs `python -m build`. ""...
799367cc6ac8e248bfe78a606373a3d13fb1de5c5d5d3621e3faf20c1db8c015
Python
1,258
42
from typing import TYPE_CHECKING from .measure import Measurement from .segment import Segment from .style import StyleType if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult, RenderableType class Styled: """Apply a style to a renderable. Args: renderable (RenderableTy...
f526f858eca48fdf619f731039f9bf32a611c4ee6400366de8eb9a9214ae929e
Python
1,258
42
from pandas import ( Period, PeriodIndex, ) def test_is_monotonic_increasing(): # GH#17717 p0 = Period("2017-09-01") p1 = Period("2017-09-02") p2 = Period("2017-09-03") idx_inc0 = PeriodIndex([p0, p1, p2]) idx_inc1 = PeriodIndex([p0, p1, p1]) idx_dec0 = PeriodIndex([p2, p1, p0]) ...
e864bfc92751d92aec0508ed455752657570465f5b9da678c0ec1b5f11640d70
Python
1,259
40
import numpy as np import pandas as pd from pycisTopic.iterative_peak_calling import get_consensus_peaks from pycisTopic.pseudobulk_peak_calling import peak_calling import scanpy as sc import pyranges import os # Read in narrow peak dictionaries peak_files = snakemake.input.narrow_peaks # List of cell types cells = [...
04aedac2d2cc2ea7c54c266789831b1f71d0a669ca02c97da2b02ee627af6c5f
Python
1,262
47
import torch from braincog.base.connection.CustomLinear import * from braincog.base.node.node import * from braincog.base.learningrule.STDP import * from braincog.base.brainarea.IPL import * from braincog.base.brainarea.Insula import * if __name__ == "__main__": num_neuron = 4 num_vPMC = num_neuron num_STS...
f4a02cac5a2a10852d59bf2d4504ac92aa9ecef74b3da1e04ca33614d5ac0f13
Python
1,262
62
# %% import mne from autoreject import AutoReject import utility_funs as uf from sys import argv # config # load data and set channel names, montage data_dir = '/Users/kbas/sci_data/harmonicity_modulation/' p = int(argv[1]) data_id = uf.participant_fname(p) fname = data_dir + data_id + '.bdf' ar_path = '../results/au...
70c312fae6fea612797218f8c24ecf08510fc2a1f96a45074fcee598543f1946
Python
1,264
38
import logging from pathlib import Path LOGGER = logging.getLogger("cali_logger") LOGGER.setLevel(logging.DEBUG) # Create formatter formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # File handler log_file = Path(__file__).parent / "cali_logger.log" file_handler = logging.FileHand...
9b7207dba4c2ccb0e94bc72dbf324a2c0f31e35e2eaf98e55f7b1d4f8b01e26f
Python
1,264
50
from collections.abc import Generator from contextlib import contextmanager import pathlib import tempfile import pytest from pandas.io.pytables import HDFStore tables = pytest.importorskip("tables") # set these parameters so we don't have file sharing tables.parameters.MAX_NUMEXPR_THREADS = 1 tables.parameters.MAX_...
c3b531dd4f0f23e49e3f5de10f73cc8d631fdd86ce1a883acc20ea8f49df9e92
Python
1,264
65
""" Data IO api """ from pandas.io.clipboards import read_clipboard from pandas.io.excel import ( ExcelFile, ExcelWriter, read_excel, ) from pandas.io.feather_format import read_feather from pandas.io.gbq import read_gbq from pandas.io.html import read_html from pandas.io.json import read_json from pandas....
1970d65d8654d9cc02cad9e876227badcf25a46eaf93ff583ba98b1232ddc8cb
Python
1,265
64
""" DQAS for QFT QEM circuit design, deprecated DQAS implementation """ from functools import partial import cirq import numpy as np import tensorflow as tf from tensorcircuit.applications.vags import qft_qem_vag from tensorcircuit.applications.dqas import ( set_op_pool, DQAS_search, verbose_output, ) de...
b1d642db1b570a6dba98892896572dc1d5f8d4201fdfbb55a63e38defdfad0ac
Python
1,265
21
"""Re-select the number of latent factors for the Replogle tutorial on the raw-count subset (the cached results/replogle-r-legacy.csv was computed on log-normalised values). Same grid as the tutorial; writes results/replogle-r.csv.""" import sys, time sys.path.insert(0, '../../../..') import numpy as np, pandas as pd, ...
6e805c4b0efc87e969db461b697489b2a900236b8dfe60ff4ed0b27697aae705
Python
1,267
48
import typing as t from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401 from .tests import TESTS as DEFAULT_TESTS # noqa: F401 from .utils import Cycler from .utils import generate_lorem_ipsum from .utils import Joiner from .utils import Namespace if t.TYPE_CHECKING: import typing_extensions as te # de...
489c8231a1226f6e8cb6ae85286b32e7cbb9bb405ce339ee46a7e3b46b68253a
Python
1,268
39
from __future__ import annotations import argparse # noqa: TC003 import logging from cli.lib.common.cli_helper import register_targets, RichHelp, TargetSpec from cli.lib.core.vllm.vllm_build import VllmBuildRunner logger = logging.getLogger(__name__) # Maps targets to their argparse configuration and runner # it ...
26eb091fa955bedc2333d7e1c79966888f92bd6364efa77f0738994614df851f
Python
1,269
47
import numpy as np class ArrayWithMetadata(np.ndarray): """ Notes ----- https://docs.scipy.org/doc/numpy-1.13.0/user/basics.subclassing.html Some functions don't work so we need a manual implementation: https://github.com/numpy/numpy/issues/11671 """ def __new__(cls, input_array, met...
2a93b3ee5731294d13ae87eb802b39387840ea10afb34eb388ffb0764a220d71
Python
1,269
33
import sys sys.path.append('.') from plotting.utils import load_results, set_plotting_defaults, efcolor, pvscolor, ecscolor, dpi import matplotlib.pyplot as plt import seaborn as sns import numpy as np set_plotting_defaults() if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results ...
85f4855f2dbc3a82d82a5001ce73cc1e2ef6d3ca52bc7460f1964c87753e451b
Python
1,269
35
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. """ Handles generation of a separate HTML page for knownclusterblast's MiBIG hits """ import os from typing import List from jinja2 import FileSystemLoader, Environment,...
b59b639b20320167a785e1d3190db1b0ba3e2e843e25e0b4979e38db30cc0b39
Python
1,271
40
import pandas as pd import matplotlib.pyplot as plt import numpy as np import os # Create output directory os.makedirs('paper_graphs/Control_Distance_Plots', exist_ok=True) # Read the data df = pd.read_csv('CT2_log/euclidean/false_positive/high_variation_genes/control-control_distance.csv') # Create figure fig, ax =...
2a9024444b89c169e50c10b8e51beaa2053fa353521b4938e2831001b81608dc
Python
1,273
45
import ctypes import pytest import pandas.util._test_decorators as td import pandas as pd pa = pytest.importorskip("pyarrow") @td.skip_if_no("pyarrow", min_version="14.0") def test_dataframe_arrow_interface(): df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) capsule = df.__arrow_c_stream__() ...
eb904e693df39b286f34379dd3678f489ebf53aaea4527f69c1d2a8ed84fcaa3
Python
1,273
42
from .sequencelayer import SequenceLayer from .tempocluster import TempoCluster from .synapse import Synapse class TempoSequenceLayer(SequenceLayer): ''' classdocs ''' def __init__(self, neutype): ''' Constructor ''' SequenceLayer.__init__(self, neutype) def addNe...
1564647a41aa675345e1860d7e6e3a98e00ef6edefe1962db3f95cf328107ea6
Python
1,275
32
""" The `numpy.core` submodule exists solely for backward compatibility purposes. The original `core` was renamed to `_core` and made private. `numpy.core` will be removed in the future. """ from numpy import _core from ._utils import _raise_warning # We used to use `np.core._ufunc_reconstruct` to unpickle. # This is...
92802ec345b84d6ca7839e7c0956998443017b40033ece73f50772250bce7bbe
Python
1,275
49
""" This is the discriminator D for ESPRESO. TODO: recode """ import torch import math from torch import nn import torch.nn.utils.spectral_norm as sn import torch.nn.functional as F class ConvSpectnormLReLU(nn.Module): def __init__(self, in_c, out_c, kernel_size, alpha): super().__init__() self.b...
43624a07d773318eb2dc15fcf52f7198fb31065b7d6601b21647b6183f81cd15
Python
1,277
36
#!/usr/bin/env python3 """Prints welcome message for ASCENT software. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ d...
63c9e9529210334952748c18edab8670b25a176d4939bf8a95553772f48bb0e8
Python
1,277
36
import pytest from pandas import DataFrame import pandas._testing as tm class TestSwaplevel: def test_swaplevel(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data swapped = frame["A"].swaplevel() swapped2 = frame["A"].swaplevel(0) swapped3 = frame["...
9895decd35c351b76e842c151807c0047a440115a19e3f212d6f44394deb9fce
Python
1,277
43
from numpy.testing import assert_ import numpy.distutils.fcompiler customizable_flags = [ ('f77', 'F77FLAGS'), ('f90', 'F90FLAGS'), ('free', 'FREEFLAGS'), ('arch', 'FARCH'), ('debug', 'FDEBUG'), ('flags', 'FFLAGS'), ('linker_so', 'LDFLAGS'), ] def test_fcompiler_flags(monkeypatch): mo...
b6579170afa92bf989a6077407aabc11532bf1ba864792e555b8176ca8894688
Python
1,278
38
import json import os import subprocess import time subid = raw_input('Enter subject id (i.e. s999): ') training = raw_input('Enter 0 for training, 1 for main tasks: ') if training == '1': run_file = 'scanner_tasks_order1' else: run_file = 'practice_tasks' taskset = raw_input('Enter task group (1, 2 or 3): '...
4ba4dca50975b59351bcaa47ee939b1ae8b42c4a88936f8dc5d2e100545c0819
Python
1,279
36
import time from typing import List import cv2 import numpy as np import torch from grimace.grimace_scorer_model import GrimaceScoreModel class GrimaceScorer: def __init__(self, grimace_scorer_model: GrimaceScoreModel): self.grimace_scorer_model = grimace_scorer_model def preprocess(self, frame: np...
b7b16a97265210b517484421c6edcaf4a2695b203d99b12eba0d2d9e3dce2eac
Python
1,279
40
""" %load_ext autoreload %autoreload 2 """ import logging from yass.batch import IndexGenerator logging.basicConfig(level=logging.ERROR) # init indexer for a matrix with int16, 1 million observations and # 512 columns with maximum memory usage of 124 bytes ig = IndexGenerator(1000000, 512, 'int16', '10MB') # index...
baf1980a0424c5bc9371d4d848d6742488abcdb7b3b9d86ca6510a7a801db464
Python
1,279
41
"""Runtime version lookup for gcmi. The authoritative version lives in ``python/pyproject.toml``. Installed packages read it from package metadata; source-tree imports fall back to the local pyproject file. """ from __future__ import annotations from importlib.metadata import PackageNotFoundError, version as dist_ve...
c9ca44574d86170f373229979aa9355b692871abb89281a02f9196a3a84afe2b
Python
1,279
59
import pandas as pd import sys import numpy as np sys.path.append("../") wm = None # pd.read_csv("somePath/WM_run1_TAB.txt", sep='\t') procedures = wm["Procedure[Block]"] trialTypes = wm["TargetType"] trialOnsetTimes = wm["ExperimenterWindow.OnsetTime"] initialOnsets = wm["SyncSlide.OnsetTime"] initialFinishes = wm["...
a08598d5bf9199ef96ca8d9ac89e92a2e558839399d9746eb1711406b79f8f0d
Python
1,282
43
import os import yass from yass import preprocess from yass import detect # def test_can_detect_with_threshold(path_to_config_threshold, # make_tmp_folder): # yass.set_config(path_to_config_threshold, make_tmp_folder) # (standardized_path, # standardized_params, # ...
087270b3be74555090d8fb04a21c7cf7bbea274445ebe81e3565d8fd9beb5721
Python
1,284
41
from __future__ import annotations from typing import Callable import pytest from textstat.backend import utils, counts, metrics from .. import resources @pytest.mark.parametrize( "inner_func, outer_funcs", [ ( counts.count_words, [metrics.sentences_per_word, metrics.words_per...
f92f03149a3f004db7ef8e691be94607224941759e00025ac4ee8a685c4554ce
Python
1,285
37
from pathlib import Path import typer from .._qt.components.tomogram_browser import TomogramBrowserWidget from .._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet from ..view._cli import cli COMMAND_NAME = 'tomograms' @cli.command(name=COMMAND_NAME, no_args_is_help=True) def view_tomograms( tilt_s...
d5520fb82f0082d296adc9dc42b8c1758a80dc9556cacbba8d9a35aeb87b73b4
Python
1,288
37
from typing import Optional, TYPE_CHECKING from .jupyter import JupyterMixin from .measure import Measurement if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult class Constrain(JupyterMixin): """Constrain the width of a renderable to a given number of characters. ...
d79a51a667a593c33d1f708027916b557a483fb867f5edd20e16bf3b29d2c9ec
Python
1,288
39
""" Generated by CHARMM-GUI (http://www.charmm-gui.org) addCrystPdb.py This program is to add CRYST1 information into PDB file. Correspondance: jul316@lehigh.edu or wonpil@lehigh.edu Last update: October 5, 2020 """ from __future__ import print_function import argparse def addCryst(pdbfile, boxinfo): inp_pdb ...
a0f1b4b40e91b5dc58a7c80201ed240429beb2e3b44658a31055c3fab40dec4a
Python
1,289
53
"""scvelo - RNA velocity generalized through dynamical modeling.""" from anndata import AnnData from scvelo import datasets, logging from scvelo import plotting as pl from scvelo import preprocessing as pp from scvelo import settings from scvelo import tools as tl from scvelo import utils from scvelo.core import get_d...
7824009dbca46f908de7842a32f706e0c8ca9ae697bdfe7c709223a4debdb565
Python
1,290
49
# Autogenerated by configen, do not edit. # If encountering an error, please file an issue @ # https://github.com/romesco/hydra-lightning # fmt: off # isort: skip_file # flake8: noqa # Hydra + Lightning from dataclasses import dataclass from dataclasses import field from typing import Any from typing import Callable fr...
83fdfeb30bc1d5fb77a8e8e4fe43567737ed98486ef64a6b412204a3f626c68e
Python
1,290
43
#!/usr/bin/env python3.7 """Generate mock sample morphology. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ import os i...
979fa2a472af306ec9bd7f998fb9da8381ea083140ff632631eada924d6cf293
Python
1,290
41
import torch import torch.nn as nn from myutils.common import heaviside from config import AdaLiConfig def piecewise_quadratic_backward(grad_output: torch.Tensor, x: torch.Tensor, alpha: float): x_abs = x.abs() mask = (x_abs > (1 / alpha)) grad_x = (grad_output * (- (alpha ** 2) * x_abs + alpha)).mas...
018b364b05796a7920c27bca23d4523b58d9724d75f27bb74b26789e0cd936ca
Python
1,291
46
from operator import mul from functools import reduce import numpy as np from numpy.random import randint from numpy.lib import Arrayterator from numpy.testing import assert_ def test(): np.random.seed(np.arange(10)) # Create a random array ndims = randint(5)+1 shape = tuple(randint(10)+1 for dim in...
6aa861c11299bdf1b16b7bf4f57e6f67bb81ba9f27e4e8da51a75f26957a1682
Python
1,292
40
import numpy as np from pandas import ( TimedeltaIndex, factorize, timedelta_range, ) import pandas._testing as tm class TestTimedeltaIndexFactorize: def test_factorize(self): idx1 = TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"]) exp_arr = np.array([0, 0, 1, 1...
89f2f7f186669b76f4e3540e3c9689b69119c7e87950ee0fec11624bd11e1fc1
Python
1,292
54
import anndata as ad import scvi import scanpy as sc import torch import pandas as pd import scipy import numpy as np import sys print(torch.cuda.is_available()) scvi.settings.seed = 0 torch.set_float32_matmul_precision('high') # Read in AnnData atlas object filtered_adata = ad.read_h5ad(sys.argv[1]) # Setup SCVI o...
9076cc1782116de3c650004bb5c094ce3a339a2c774a1890b2baa1024230b612
Python
1,292
43
# -*- coding: utf-8 -*- """ Created on Fri Sep 14 15:19:13 2018 Plotting function container @author: danilo """ import numpy as np from matplotlib import pyplot as plt def set_size(w,h, ax=None): """ w, h: width, height in inches """ if not ax: ax=plt.gca() l = ax.figure.subplotpars.left r = ax.figure...
0a53954cec65c8d2e5b8362688ccb47a9d659378a0e212326163f9b9800505a9
Python
1,293
34
import tifffile import numpy as np import os from os.path import join from scipy.ndimage import zoom def MaskToSwc(): # imgPath = r'E:\NeronSegDataSet\HaiNanDataSet1\OriDataSet\mask\43_23_12.tif' # swcPath = r'F:\viif01-config\SelectTifLs001\TestResMask\GMM\43_23_12_mask.swc' imgPath = r'E:\NeronSegDataSet...
1d3082d747472f0b1b3ba10619e4f2aefacda2663d7721ab04afce99ac1a9300
Python
1,293
57
"""Plot a sample. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FROM REPOSITORY ROOT """ import os import sys s...
2a6d3479a6e3d991c34b2b02a36ac0aeb208d2dae6916b865ab10866f4c3cacb
Python
1,293
41
from .layer import Layer from .cluster import Cluster from .synapse import Synapse class SequenceLayer(Layer): ''' This class mainly stores the musical sequential elements, including pitches and durations ''' def __init__(self, neutype='LIF'): ''' Constructor ''' self....
0f6603d9552ba6e906a92297f5539df1764cda46cdd469d3555aa49a1e44ec09
Python
1,294
58
"""Plot a sample. The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent. RUN THIS FROM REPOSITORY ROOT """ import os import sys s...
52b59bc345a1086960a4892779eccb1dba3ad72b895326ce2992e8313a1bab7f
Python
1,297
38
from typing import Iterable from torch.nn import Module def get_parameters(modules: Iterable[Module]): """ Given a list of torch modules, returns a list of their parameters. :param modules: iterable of modules :returns: a list of parameters """ model_parameters = [] for module in modules: ...
acadd5556dbec197d814054cf2041ff9062da37e3edf8f83b885e4ddcb3adcdc
Python
1,297
42
import gym import gym_stag_hunt from ray import tune from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv from gym_stag_hunt.envs.pettingzoo.hunt import raw_env if __name__ == "__main__": def env_creator(args): return PettingZooEnv(raw_env(**args)) tune.register_env("StagHunt-Hunt-PZ-v0", e...
8d63746d14ea76f6f663d76472dfd3b6c83f4e1f72dc29ef599f9eb65b9d60ac
Python
1,298
35
import numpy as np import torch from radifox.utils.degrade.degrade import select_kernel from math import ceil def parse_kernel(blur_kernel_file, blur_kernel_type, blur_fwhm): if blur_kernel_file is not None: blur_kernel = np.load(blur_kernel_file) else: window_size = int(2 * round(blur_fwhm) ...
1dde49c57c29bb8fc5b7662c70541242b0d2dd1a61e008406422cec7a0f3191c
Python
1,299
41
"""For testing calculate.py file.""" import urllib.request import numpy as np import pytest from scipy.io import loadmat from phyid.calculate import calc_PhiID from phyid.utils import PhiID_atoms_abbr @pytest.fixture(scope="session") def PhiID_test_simple_1(tmp_path_factory): """Load test data.""" fn = tmp_...
29b41c461939930a90b8ded4c7af62bc1e590365cef5c09ebac4a8a88d508f0c
Python
1,301
40
from fastapi import APIRouter, Depends from redis.asyncio import Redis from app.utils.database import get_redis_connection router = APIRouter() @router.get( "/hello_world", tags=["Testing"], description="A simple test endpoint that returns 'Hello, World!'", summary="Hello World Test Endpoint", r...
2fc5d426bb22ea43937a8153b473e6c0f40e2b55a2adc3682a80143844afa1b6
Python
1,301
35
"""Evaluate a set of vectors for a given language.""" import os import argparse from .norms import evaluate_norms from .analogies import evaluate_analogies from .similarities import evaluate_similarities import logging logging.basicConfig(format='[{levelname}] {message}', style='{', level=logging.INFO) def evaluate_l...
678b53ba85b15285e2315abcb09c763cf188c91a33d5dcf34480b5c3c9e90ca4
Python
1,303
36
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.core.construction import sanitize_array @pytest.mark.parametrize( "values, dtype, expected", [ ([1, 2, 3], None, np.array([1, 2, 3], dtype=np.int64)), (np.array([1, 2, 3]), None, np.array([1, 2, 3]))...
7a065ed8fd437be1ac60a8a9b4fa802c7c6c390836a8f48569072eb4d0a6a5e5
Python
1,304
52
# %% from matplotlib import pyplot as plt import pandas as pd import seaborn as sns import numpy as np # %% pids = [ 303, 309, 310, 312, 314,315,317,318,319,320, 321,322,323,324,326,327,328,329,330, 332,333,334,335,336, 341,342,404,406,407,408 ] flist = [f'p{i}_log.csv' for i in pids] ddf_l...
80ccf7da2ca653f61aa4ff12fb771f79ef922bb15f455564e7ac064aa9e4a8b7
Python
1,304
25
import pytest @pytest.mark.parametrize("test_num", [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12, 13, 14, 15]) def test_cli_simulation_regressions(run_simulation_testset, expected_output_data, expected_line_counts, test_num): _, observed_final_lines, observed_line_counts = run_simulatio...
b679b4555fb9e75f1adaa2819dab9ed9c1dcf7c3682e8a9a88c33f67e99e6c52
Python
1,304
34
import torch import torch.distributions as td import torch.nn as nn from networks.ToCM.utils import build_model_snn class DenseModel(nn.Module): def __init__(self, in_dim, out_dim, layers, hidden, activation="nn.ELU"): # TODO activation=nn.ELU super().__init__() self.model = build_model_snn(in...
7e3a55f04a7756d2cb58023cdb4ac07be08c9165736db7211bff46be09dd2fa4
Python
1,305
30
# License: GNU Affero General Public License v3 or later # A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt. # for test files, silence irrelevant and noisy pylint warnings # pylint: disable=no-self-use,protected-access,missing-docstring from unittest import TestCase from antism...
b26c1f5af377dc1e9480b6a029a050925953b86026ed689aabceccf67c6ef20f
Python
1,305
47
import pytest from pandas import ( DatetimeIndex, date_range, ) import pandas._testing as tm @pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"]) @pytest.mark.parametrize("name", [None, "my_dti"]) @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) def test_dti_snap(name, tz, unit):...
b5f7d605e1b8bb275fd10f41132f077562bb90aa65365fdc35f490a956dc4fc6
Python
1,305
41
import numpy as np import tensorflow as tf def compute_entropy_pretrain(X: np.ndarray, n_bins: int = 20) -> float: """ Compute a dataset-level entropy proxy for input complexity. This is computed ONCE before training (pre-training), not iteratively. """ eps = 1e-12 entropies = [] for j in r...
9ad820783ea06d27f9e7c7e7554bf140c1aba72de5134b4349685c182a7b256b
Python
1,306
39
class IndexesGenerator: def __init__(self, size: int, step: int, position: str = "last"): self.size = size self.step = step if position == "first": self.behind = 0 self.ahead = self.size - 1 elif position == "middle": self.behind = self.size // 2 ...
5ff487b6df67fd6cc0fc2db03e54491d14bc2d49a334d9abdbe5cbe80b3325dd
Python
1,307
44
import pytest import pandas._testing as tm from pandas.core.arrays import DatetimeArray class TestAccumulator: def test_accumulators_freq(self): # GH#50297 arr = DatetimeArray._from_sequence( [ "2000-01-01", "2000-01-02", "2000-01-03", ...
3f5bd8bbd08a87a07e4527bed7ce1d77674ab553af1064bb49c5732247829b7a
Python
1,308
50
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 1 18:04:35 2019 @author: charleshen fragments number of 86 fragments: https://www.rdkit.org/docs/source/rdkit.Chem.Fragments.html ref: https://github.com/rdkit/rdkit/blob/master/Data/FragmentDescriptors.csv """ from rdkit.Chem import Fragments fr...
4284d76c28aa8cae2d0431d46ead5328fa7436ba1891e85e16346af95c65b0fd
Python
1,310
45
import numpy as np import pytest import pandas as pd from pandas import ( DatetimeIndex, Index, ) import pandas._testing as tm dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZDtype("ns", "Asia/Tokyo"), pd.PeriodDtype("ns"), ] @pytest.mark.parametrize("...