sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
f586b6dd91269d114c547d90dc70d6afe2f1a61bb504afae2cf389d38f5f19e5
Python
877
30
import torch.optim as optim def optimizers(model, config): """ Returns the optimizer based on the configuration. Args: model (torch.nn.Module): The neural network model. config (dict): Configuration dictionary containing 'optimizer' and 'learning_rate' keys. Returns: torch.opt...
d7ef6c498ec69bb7cc4fc322c55b35eaef3eece6d069df4e11e0020c451de773
Python
879
27
from smac.env.starcraft2.maps import smac_maps from pysc2 import maps as pysc2_maps from smac.env.pettingzoo import StarCraft2PZEnv as sc2 import pytest from pettingzoo import test import pickle smac_map_registry = smac_maps.get_smac_map_registry() all_maps = pysc2_maps.get_maps() map_names = [] for map_name in smac_m...
ad44b84108571529d5bcfc63ca7766656d7be52c0d0baa90b3fdda64dd8be93a
Python
880
36
#!/usr/bin/env python3 # # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import confu parser = confu.standard_parser("clog configuration script") def main(ar...
c5295adf35aac62e878f8f04be761f0f75877c4d7cf55bc2e17b0abb8fd3fc8c
Python
880
40
""" Use cffi to access any of the underlying C functions from distributions.h """ import os import numpy as np import cffi from .parse import parse_distributions_h ffi = cffi.FFI() inc_dir = os.path.join(np.get_include(), 'numpy') # Basic numpy types ffi.cdef(''' typedef intptr_t npy_intp; typedef unsigned ch...
74b7cbc8818f638d7aa8bd4746e01cb5afb38b49ef66b224266fa47b5afb2b8c
Python
881
20
import torch class GrimaceCrossEntropyLoss(torch.nn.Module): def __init__(self): super(GrimaceCrossEntropyLoss, self).__init__() self.eye_loss = torch.nn.CrossEntropyLoss() self.nose_loss = torch.nn.CrossEntropyLoss() self.cheek_loss = torch.nn.CrossEntropyLoss() self.ear_l...
95f27ee998973cb2633c5e0a26e3ff30af95d4d3b45f0f727b73c2e28ebd2836
Python
883
31
from typing import Union import numpy as np import timm import torch class FrameQualityModel(torch.nn.Module): def __init__(self, device="cuda"): super(FrameQualityModel, self).__init__() self.base_model = timm.create_model("mobilenetv3_large_100", in_chans=1, pretrained=False) base_mode...
7cefdf081e0cee9841138107bbd66b92900cbe3649354e7403382419b376303e
Python
885
26
import tensorflow as tf from sklearn.metrics import roc_auc_score import numpy as np ########### classification ############## def cross_entropy(y_true, y_pred, MASK = -1): mask = tf.cast(tf.not_equal(y_true, MASK), tf.keras.backend.floatx()) labels = y_true * mask logits = y_pred * mask cost = tf.nn...
1d8569ca51cdd7d99eb28d0c97665d0fbb0a1f19de227289195a255894384426
Python
886
27
import os import sys import glob def pdbs_to_pdbqts(pdb_dir, pdbqt_dir, dataset): for file in glob.glob(os.path.join(pdb_dir, '*.pdb')): name = os.path.splitext(os.path.basename(file))[0] outfile = os.path.join(pdbqt_dir, name + '.pdbqt') pdb_to_pdbqt(file, outfile, dataset) print(...
5fc52a28f189c0d0740f4e1357ed4291841deb4b607308645b514b384f54933d
Python
886
26
# 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 import os import unittest from antismash....
22681d1d2ba307647bfea8ca5ed5e4244caeb625a0bbf37ae22a35a2f0bf71b2
Python
887
34
import random _BLOCKS: set[str] = { "baseline", "isochronous", "asynchronous", "synchronous", } def generate_blocks_sequence(previous_blocks: list[str]) -> str: """Create a semi-random block sequence. Parameters ---------- previous_blocks : list List of previously generated b...
a3b2f1203197670aa3f23c36503fd373d819dd60fed922ee2c67ea80d750036e
Python
887
23
"""Overrides split strategies from schnetpack.data.splitting""" from typing import List from schnetpack.data import ASEAtomsData from schnetpack.data.splitting import SplittingStrategy class TestSplit(SplittingStrategy): """Splitting strategy that allows to put all dataset elements in test split without index p...
efd77be72f39f1738b9722bb37eada8af7a8d1fd17b4e448e39e768599b89f53
Python
887
27
import numpy as np import torch from bermol.utils import mol_to_sentence, smi_to_mol from bermol.vocab import MolVocab class BerMolTokenizer: def __init__(self, vocab: MolVocab) -> None: self.vocab = vocab def encode(self, smiles: str) -> torch.Tensor: mol = smi_to_mol(smiles) if mol...
38df84f99a924a1799f3c56b297d8cdcf5e915b18451464f31afc07f497ee1fd
Python
890
33
from abc import ABC class RichRenderable(ABC): """An abstract base class for Rich renderables. Note that there is no need to extend this class, the intended use is to check if an object supports the Rich renderable protocol. For example:: if isinstance(my_object, RichRenderable): con...
65a2f4c1a591baaeb18f7d2c532c2d9e8499e4b7948f0bf01783b9fd39d062d9
Python
891
31
import os from pathlib import Path import pytest from tomography_python_programs._metadata_models.relion.tilt_series_set import RlnTiltSeriesSet @pytest.fixture def test_project_directory() -> Path: return Path(__file__).parent / 'test_project_directory' @pytest.fixture def tilt_series_star_file(test_project_...
15da0bcb1640713b00d9f94889c45701198b40f808cc6293cffc6c489c88e0c8
Python
893
33
import os import shutil import random random.seed(42) source_dir = "data/raw" output_dir = "data" train_ratio = 0.7 val_ratio = 0.15 for class_name in os.listdir(source_dir): class_path = os.path.join(source_dir, class_name) images = os.listdir(class_path) random.shuffle(images) tr...
cb1cda84e1cfd8feddb116df5c9642e21376fbbfbd20f6996cb0c83ebb828eda
Python
893
46
import torch import numpy as np import os import sys datadir = "./Dataset/Data" def healthCheckOnRoiSignal(roiSignal): """ roiSignal : (N, T) """ # remove subjects with dead rois if(np.sum(np.sum(np.abs(roiSignal), axis=1) == 0) > 0): return False return True def abide1L...
780e62fe7c98d8d10b7f482a642b9b54e68b8ff9d7ac274ad318017459c7c0b4
Python
894
24
# 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,too-many-public-methods """ helper functio...
1f73fe66a3ccadac3c0831650fee91f20edad7e3b6bac426eb8a2dbfae558452
Python
895
34
"""Generate an excel summary of parameters used in runs of ASCENT. 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 ...
e48bceac911458c6a959f10e0246e289b622d04a70e9d65fb923386940f82e8b
Python
895
20
from statistical_analysis import CrossCorrelationProcessor main_path = 'Path/To/Your/Data/' # Update this to your actual data path # create list of participants to be processed # also works for subsample of participants participants = [f'P{str(p).zfill(2)}' for p in range(1, 41)] exclude = ['P13', 'P20'] # exclude p...
2588fbe7e2b8769b4c9fe9ecfb23b98e1901bd9cf9758ef576bfd8700b0fd07b
Python
896
37
'''import pandas as pd # Path to your pickle file path = "data_false_negs/folds_with_rnacentral_info_full_v2_with_evidence_GPTLARGE.pkl" # Load the DataFrame df = pd.read_pickle(path) # Show shape and first few rows print("✅ Data loaded successfully!") print("Shape:", df.shape) print("\nColumns:", df.columns.tolist(...
24b4988a738f3a6b28f5a4b8fbd25c3d1c27ebbe51ec32b696498a23089d78d6
Python
897
29
import anndata as ad import scanpy as sc import torch import pandas as pd import scipy import numpy as np import sys # Read in AnnData atlas object adata = ad.read_h5ad(snakemake.input.merged_rna_anndata) # Select for the most variable genes sc.pp.highly_variable_genes( adata, layer='log-norm', n_top_gen...
47f85359ad5dd1c350fcc6404c4848d802924ab369c5e11dda6f06d7e7290e83
Python
897
32
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..counts._count_words import count_words from ..counts._count_sentences import count_sentences from ..counts._count_miniwords import count_miniwords @typed_cache def mcalpine_eflaw(text: str) -> float: """Calculate McAlpine EFLA...
714a57c1a3d6b5d6c635777fd164e8e7fb68997be9fac21d613cd8fc207517c4
Python
897
36
from .gridspec import gridspec from .heatmap import heatmap from .paga import paga from .proportions import proportions from .scatter import diffmap, draw_graph, pca, phate, scatter, tsne, umap from .simulation import simulation from .summary import summary from .utils import hist, plot from .velocity import velocity f...
88b4c9402e12552468ca02061875ef129d1df14773a5eaa6311a94705d09235e
Python
897
28
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. # We don't need to call super() in __init__ methods of our # BaseException and Exception classes because we also define # our own __str__ methods so there is no need to pass 'message' # to the base class to get a m...
948c16586106a32fb6a2e88bb18beb357e60ba5d57a9209add97383c81670558
Python
898
41
datasetDetailsDict = { "hcpRest" : { "datasetName" : "hcpRest", "targetTask" : "gender", "taskType" : "classification", "nOfClasses" : 2, "dynamicLength" : 600, "foldCount" : 5, "atlas" : "schaefer7_400", "nOfEpochs" : 20, "batchSize"...
a0db428319939a488cd43894c639f34de0310a3ffb8e379ec2d6f2fb781da28d
Python
899
30
from pandas import ( Categorical, Index, Series, ) 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 trackin...
b567b54162e54c03bbae321738b97f135671c0141d19ecf3d5f7f8d8068eef7b
Python
902
40
"""ZX graph simplification wrapper.""" from typing import Any import pyzx_param as pyzx def full_reduce(g: Any, param_safe: bool = True) -> None: """ Apply PyZX full_reduce to the graph. :param g: The ZX graph. :type g: Any :param param_safe: Whether to use parameter-safe simplification, default...
e803e5d1e03e2f25be2d421fb5d10ae64c384b0e6023a770b9b97515eae20fa7
Python
902
39
from __future__ import annotations from ..utils._typed_cache import typed_cache from ._words_per_sentence import words_per_sentence from ._syllables_per_word import syllables_per_word @typed_cache def flesch_kincaid_grade(text: str, lang: str) -> float: r"""Calculate the Flesh-Kincaid Grade for `text`. Para...
6389d445de2114cd10dda5444f538efb3d75a59cf36741c57e5dacfbd3967a6c
Python
903
26
from pandas import Categorical import pandas._testing as tm class SubclassedCategorical(Categorical): pass class TestCategoricalSubclassing: def test_constructor(self): sc = SubclassedCategorical(["a", "b", "c"]) assert isinstance(sc, SubclassedCategorical) tm.assert_categorical_equa...
2e2adc581d153c24d99672b4387618be61088f7166beb8b465d90f34d050ba91
Python
904
34
"""Generate an excel summary of parameters used in runs of ASCENT. 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 ...
ee34bfa352104415498a1188fa2011ae7962737323660eec13103b7e59a370fd
Python
904
29
from pathlib import Path import pytest import numpy as np from tomography_python_programs._utils.file import basename, match_filenames @pytest.mark.parametrize( "input, expected", [ (Path('test/test2/test3.mrc'), 'test3'), # multiple directories (Path('test.mrc.mdoc'), 'test'), # multiple s...
03b7ea0eecef9ede4f1d884eeaf69bc50a8a6c40b2b0f9cd7bcaa6648ac4fd45
Python
906
32
def get_acc_predictor(model, inputs, targets): if model == 'rbf': from acc_predictor.rbf import RBF acc_predictor = RBF() acc_predictor.fit(inputs, targets) elif model == 'carts': from acc_predictor.carts import CART acc_predictor = CART(n_tree=5000) acc_predict...
244001226e8b3724826d252ae872d2fbfa9318adc78157127125cba43b2b27ca
Python
908
28
from pandas import ( DataFrame, DatetimeIndex, date_range, ) import pandas._testing as tm def test_isocalendar_returns_correct_values_close_to_new_year_with_tz(): # GH#6538: Check that DatetimeIndex and its TimeStamp elements # return the same weekofyear accessor close to new year w/ tz dates ...
373c668d3434c15dd359dff7b01eb41608b1912581a947367aad8a0c496565a9
Python
908
30
# main.py import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from rulebasedpolicy.random_map import * from rulebasedpolicy.a_star import * from env.env3_train_env01 import FalseBelief_env1 def Find_a_way(size, board, start_x, start_y, end_x, end_y): map = RandomMap(size...
0adacb2c3abd77e10a7a3e692ad301564982922aeb708cebf98fc69624531400
Python
909
21
import torch from torch import nn class MicePoissonLoss(nn.Module): def __init__(self, log_input: bool = False, full: bool = False, eps: float = 1e-8): super().__init__() self.poisson = nn.PoissonNLLLoss(log_input=log_input, full=full, eps=eps, reduction="none") def forward(self, inputs, targ...
c29369e739b458611b1de8ea3ef01a84a1c5ee98404e7c9968d4a45ff927fd05
Python
910
25
import os import sys import music21 as m21 import numpy as np firstnotes = np.array([[m21.pitch.Pitch('b-4').midi], [m21.pitch.Pitch('d4').midi], [m21.pitch.Pitch('f3').midi], [m21.pitch.Pitch('B2').midi]]) print(firstnotes) input_path = "../xmlfiles/...
0e19a287311814881071da98f2974ab760f431dda61fe653eda1d96a9fc19f3a
Python
915
37
"""Returns thresholds from the selected sample/model/sim combos as a dataframe. 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/ascen...
f369890eafcc45ee87f50e6f522534c8381e023701bfb2760b0f58774c614b94
Python
916
29
from __future__ import annotations from stimuli.time import sleep from ..detector import _BUFSIZE from ..utils._checks import check_type from ..utils.logs import logger from ._config import TRIGGER_TASKS from ._utils import create_trigger def baseline(duration: float) -> None: """Baseline block corresponding to...
2c3fdbd5b468a6bace384aead95f03bd8f327456ba2802f28b9fdf9d6ca60b17
Python
920
25
import os from distutils.command.install_headers import install_headers as old_install_headers class install_headers (old_install_headers): def run (self): headers = self.distribution.headers if not headers: return prefix = os.path.dirname(self.install_dir) for header ...
24a8d80a5b5b8c3891b5d0d2997aa333b603422aee2a295f5a7adcd08dfd879d
Python
921
40
from __future__ import annotations import re from ..utils._typed_cache import typed_cache from ..selections._list_words import list_words @typed_cache def count_arabic_long_words(text: str, rm_apostrophe: bool = True) -> int: """Counts long arabic words (>5 letters) without short vowels (tashkeel). Param...
8be664e2c7ed2b970c4154368ea4b14cca5523e818c97375ebea794ef9a35117
Python
921
25
import sys from setuptools.command.egg_info import egg_info as _egg_info class egg_info(_egg_info): def run(self): if 'sdist' in sys.argv: import warnings import textwrap msg = textwrap.dedent(""" `build_src` is being run, this may lead to missing ...
92a7be1bda0481d013ecddf88bc938c56932647baaf0f226ae0ec72d6950e333
Python
921
37
"""Tools for detecting collective events.""" __author__ = """Benjamin Graedel""" __email__ = "benjamin.graedel@unibe.ch" __version__ = '0.3.3' from ._binarize_detrend import binData from ._cleandata import clipMeas, interpolation, remove_image_background from ._detect_events import ( DataFrameTracker, ImageTr...
e5f935f09378dd183a607bda9fa42376b39e3ae2ed4652d598fe8c69d0442550
Python
923
21
import warnings def _raise_warning(attr: str, submodule: str | None = None) -> None: new_module = "numpy._core" old_module = "numpy.core" if submodule is not None: new_module = f"{new_module}.{submodule}" old_module = f"{old_module}.{submodule}" warnings.warn( f"{old_module} is...
28a9c068b9bcf8e3d49613188cf063690e56b91789c8da3619dec6d5df2ef805
Python
924
34
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..counts._count_chars import count_chars from ..counts._count_words import count_words @typed_cache def chars_per_word(text: str, ignore_spaces: bool = True) -> float: """Calculate the average word length in characters. Thi...
4a0212a641c01d29e0c4638575f0ab0ff7a374dc0fe4574c67736ff9d9039eb7
Python
924
27
from operator import mod from .training import Train from .FBNettraining import FBNetTrain from omegaconf import DictConfig from typing import List import torch from source.components import LRScheduler import logging import torch.utils.data as utils def training_factory(config: DictConfig, model...
6264e73c5eaa5f0bd863cdb065f43c5c5c15c0e618b0896cdcb4ab7400c35bee
Python
924
30
import numpy as np import pytest from pandas.core.dtypes.dtypes import CategoricalDtype import pandas._testing as tm def test_astype(idx): expected = idx.copy() actual = idx.astype("O") tm.assert_copy(actual.levels, expected.levels) tm.assert_copy(actual.codes, expected.codes) assert actual.name...
0cb0e27661de54a3b8feb04cbad4894489f6605cd17930e92e70b59c3afbb577
Python
925
23
from morphologist_wrapper import * from sulcal_phenotype_wrapper import * import sys n_args = len(sys.argv) - 1 if n_args == 3: fs_subject_name = sys.argv[1] fs_dir = sys.argv[2] output_dir = sys.argv[3] run_morphologist_from_freesurfer(fs_subject_name, fs_dir, output_dir) #give default values for...
c4c29475a77625d0886149bba7d33f52823ea43f286c888a0ee42f7ca9c5040e
Python
925
44
from neurodesign import geneticalgorithm, generate, msequence import sys design_i = sys.argv[1] EXP = geneticalgorithm.experiment( TR = 0.68, P = [0.5, 0.5], C = [[0.5, -0.5]], rho = 0.3, n_stimuli = 2, n_trials = 96, duration = 212, resolution = 0.136, stim_duration = 1....
9988f19707a5a315a62b5fd61738cd28f00879033ace16c6bcbf8a5fe6abff13
Python
926
28
import os from itertools import permutations import numpy as np import torch import torch.nn as nn """ Helper class that stores Clebsch-Gordan coefficients """ class ClebschGordan(nn.Module): def __init__(self): super(ClebschGordan, self).__init__() tmp = np.load( os.path.join(os.pat...
bcf70d0646381f6471b32916d5b8d383e152953950d87d722dbf99b187dfb048
Python
926
34
import numpy as np from pandas import ( TimedeltaIndex, timedelta_range, ) import pandas._testing as tm class TestRepeat: def test_repeat(self): index = timedelta_range("1 days", periods=2, freq="D") exp = TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"]) for res in [index....
a0097d256b5b9ba9c2cebdb4dc340e6a98ff8a28279b53ab01cc7dfce6eb155d
Python
928
25
import scanpy as sc import pandas as pd import numpy as np import sys # Import AnnData files adata = sc.read_h5ad(snakemake.input.merged_rna_anndata) filtered_adata = sc.read_h5ad(snakemake.input.hvg_rna_anndata) # Save the .obsm['X_scvi'] adata.obsm['X_scvi'] = filtered_adata.obsm['X_scvi'] # Convert the cell barco...
92020413fd4dce36712c1482fafe6ceb8b8e15995512ddda3eb8d3b4beb1d976
Python
929
33
from __future__ import annotations from typing import TYPE_CHECKING from pip._internal.distributions.base import AbstractDistribution from pip._internal.metadata import BaseDistribution if TYPE_CHECKING: from pip._internal.build_env import BuildEnvironmentInstaller class InstalledDistribution(AbstractDistribut...
1aa424c98d67e9319e97ff008a3a0dfd819608abe88eff9f3463a1186de9a0df
Python
932
23
## ........................................................................... ## ## PIMMS (Polymer Interactions in Multicomponent Mixtures) ## Alex Holehouse, Pappu Lab, Holehouse Lab ## Copyright 2015 - 2026 ## ........................................................................... import numpy as np from . ...
2c1926ebf9a80e3b94f5163816cce06a49ce8f72320a9dedf848f71c97eaa5d9
Python
932
31
import numpy as np from numpy.testing import assert_, assert_equal, assert_raises class TestRegression: def test_kron_matrix(self): # Ticket #71 x = np.matrix('[1 0; 1 0]') assert_equal(type(np.kron(x, x)), type(x)) def test_matrix_properties(self): # Ticket #125 a = n...
7c9b21a630842f084e5843c944a76640273563e1a35b68776c4198d78947bb67
Python
932
35
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 1 18:04:35 2019 @author: charleshen @note: Information Content descriptors: http://mordred-descriptor.github.io/documentation/master/api/mordred.InformationContent.html#mordred.InformationContent.InformationContent """ from mordred import Calcul...
efbc34cb2b64af19586d29fefa50d53d431a6d45d147d237941bffbd0454a946
Python
932
43
""" Common code used in multiple modules. """ class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(...
440ef1fe9f1950c7453fb7713b9854a9badd31c5382c56974156f70081226b96
Python
934
43
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..counts._count_long_words import count_long_words from ..counts._count_words import count_words from ._words_per_sentence import words_per_sentence @typed_cache def lix(text: str) -> float: r"""Calculate the LIX for `text` ...
1ee6fb47008524822e3d2973fd171160d61ccee11ccb634b3751954c0acf6985
Python
935
32
#!/usr/bin/env python3 import os import sys import os.path as osp import loompy as lp import numpy as np pth = sys.argv[1] odir = sys.argv[2] ds = lp.connect(pth) celltype_1 = np.array([ '_'.join([str(x).replace(',','_'),str(y)]) for \ x,y in zip(ds.ca['Class'],ds.ca['Clusters']) ]) celltyp...
a38c6d24d21ae4ad7c0cf25a695f2fcae8c5b3f20f96798c33416e8422a83766
Python
935
31
#!/usr/bin/env python # Set the path to the avg_q python installation here if you # didn't add it to the global python path import sys sys.path.append("R:/avg_q/python") import avg_q # The avg_q_ui.exe binary will be found automatically in the directory # above python/ a=avg_q.avg_q(avg_q='avg_q_ui') import glob # ...
11f070c4922a91d76578904eebd38a4c261ccbf28ac9a6224e812c618f364e34
Python
936
34
import cedalion import cedalion.dataclasses as cdc import trimesh import numpy as np def test_conversion(): vertices = np.asarray([ [0.,0.,0.], [1., 0. ,0.], [1., 1., 0.], [0., 1., 0.] ]) faces = np.asarray([ [0., 1., 2.], [1.,2.,3.] ]) trimesh_surfa...
91bba60d4c54d600235f6dac06abd540136530bea39c7abd89f70d9cc1f7a04a
Python
936
31
#!/usr/bin/env python3.7 """Plots the time and location where an action potential occurred. 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/wmgl...
9875df0601d448d651d867000c5b0c2a9313ae6d522a8a21c33a4a600c5c5461
Python
937
52
""" Interplay between jit, vmap, randomness and backend """ import tensorcircuit as tc K = tc.set_backend("tensorflow") n = 10 batch = 100 print("tensorflow backend") # has serialization issue for random generation @K.jit def f(a, key): return a + K.stateful_randn(key, [n]) vf = K.jit(K.vmap(f)) key = K.get...
de07bc5638574f534f74275d0d5c8aed74dafb0708630b348cd977aac34ddb54
Python
937
44
from neurodesign import geneticalgorithm, generate, msequence import sys design_i = sys.argv[1] EXP = geneticalgorithm.experiment( TR = 0.68, P = [.6,.4], C = [[0.5, -0.5]], rho = 0.3, n_stimuli = 2, n_trials = 125, duration = 310, resolution = 0.136, stim_duration = 1.85...
6f79ea184a843546dff22958810201b510a21e327a246f6fe474e1eb942e3b6c
Python
938
40
from data_provider.data_loader import Dataset_PEMS from torch.utils.data import DataLoader data_dict = { 'PEMS': Dataset_PEMS, } def data_provider(root_path, flag,seq_len,label_len,pred_len,batch_size): Data = data_dict['PEMS'] if flag == 'test': shuffle_flag = False drop_last = True ...
9a3bb7be3c875e0f2a447f397112d6bd12fc9459c5ec719d1138edd9efe92bb3
Python
938
34
import numpy as np import pandas as pd from pandas import ( Categorical, Series, ) import pandas._testing as tm class TestSeriesCount: def test_count(self, datetime_series): assert datetime_series.count() == len(datetime_series) datetime_series[::2] = np.nan assert datetime_seri...
8ee56e99d8d86b46e25bfc3aad6fd766cd9d5b7f4b187dcd55c1e35c1ff0570e
Python
940
33
#!/usr/bin/env python2.5 import sys import os import showmovie cwd = os.path.abspath(os.path.split(__file__)[0]) types = dict(val=("val%03d_3min", "valseq3minby10_%02d.index"), trn=("trn%03d", "trnseq.index")) seq = [("trn", 1), ("val", 1), ("trn", 2), ("val", 2), ("trn", 3), ("val", 3), ("trn", 4), ("val",5)] ### ad...
9867566fc3795d01b46b2585b824399f3921886d8074f73795eb7a942ff4d50c
Python
940
33
#!/usr/bin/env python2.5 import sys import os import showmovie cwd = os.path.abspath(os.path.split(__file__)[0]) types = dict(val=("val%03d_3min", "valseq3minby10_%02d.index"), trn=("trn%03d", "trnseq.index")) seq = [("trn", 1), ("val", 1), ("trn", 2), ("val", 2), ("trn", 3), ("val", 3), ("trn", 4), ("val",4)] ### ad...
83f345fff3c1c2b1ca739ee2730d4facc6e5410df6616b2495600546acd393c5
Python
941
34
from __future__ import annotations from ..selections._list_words import list_words from ..utils._get_cmudict import get_cmudict from ..utils._get_pyphen import get_pyphen from ..utils._typed_cache import typed_cache @typed_cache def count_syllables(text: str, lang: str) -> int: """Estimate the total number of sy...
45401923f1abc2e9e9b0a18462bab9212c7963278ebe5540c1e9e07c019d018a
Python
942
38
r""" It's used to check basic rnn features with cuda. For example, it would throw exception if some components are missing """ import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class SimpleCNN(nn.Module): def __init__(self): super().__init__() self.con...
831f0ee8a882e4d870a0b83b7eb8e2f2dd70f53951c3938edb13056eff63fed7
Python
942
44
from neurodesign import geneticalgorithm, generate, msequence import sys design_i = sys.argv[1] EXP = geneticalgorithm.experiment( TR = 0.68, P = [0.5, 0.5], C = [[0.5, -0.5]], rho = 0.3, n_stimuli = 2, n_trials = 48, duration = 620, resolution = 0.136, stim_duration = 10...
e143516ce589b8ed4d54a3678060bb0595ad0b2a9f0f16d4e822e19970651bbd
Python
943
35
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from setuptools import setup with open("fm/version.py") as infile: exec(infile.read()) with open("README.md") as f: readme = f.read...
fa16f88049ea1f38faac76b87e88115439200cdc583584731e0fa503ecf896de
Python
943
40
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..counts._count_sentences import count_sentences from ..counts._count_polysyllable_words import count_polysyllable_words @typed_cache def smog_index(text: str, lang: str) -> float: r"""Calculate the SMOG index. Parameters ...
d298ff1068538c6c132c01d7541a46975b0a6446c6fb18c1b756f499eb51cbeb
Python
945
36
#!/usr/bin/env python3.7 """Generate an excel summary of parameters used in runs of ASCENT. 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/wmgl...
7a247948904f38547171881615fac2faede8bc67d3ea5c9d65f0043545a71cc3
Python
946
30
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from m6anet.scripts import dataprep, inference, train, \ compute_norm_factors, convert modules = ['dataprep', 'inference', 'train', 'compute_norm_factors', 'convert'] __version__ = "2.1.0" def main(): parser = ArgumentParser(prog='m6ane...
8d83ba69569f485248a2da07a441595a70242de59e08ed4f67d17aef7be07d63
Python
946
41
#!/usr/bin/env python3.7 """Returns thresholds from the selected sample/model/sim combos as a dataframe. 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://gi...
7f7795b51c76b4aac9c716af64d7bf7f52e7fbfd6c8614a57de4591034e5c615
Python
947
25
from numpy._core import _internal # Build a new array from the information in a pickle. # Note that the name numpy.core._internal._reconstruct is embedded in # pickles of ndarrays made with NumPy before release 1.0 # so don't remove the name here, or you'll # break backward compatibility. def _reconstruct(subtype, sha...
c0a88fcea547605d5fcf0e144eeabf1eda60685043665ac21194bc577e5f8a44
Python
948
29
"""Contains errors raised for data handling using SQLite""" class DBClosedError(Exception): """Thrown when the database is closed. This means the table was closed after creation or was never created in the first place """ def __init__(self) -> None: super().__init__( ( ...
dec67055ad06b51972404ccccbf96afa7772bab27285e1234fb0a2dfcd99586e
Python
948
36
"""Contains code to calculate the Jaccard index of two BGCs""" # from python from typing import Any # from other modules from big_scape.comparison.record_pair import RecordPair def calc_jaccard_sets(set_a: set[Any], set_b: set[Any]) -> float: """Calculates the Jaccard index between two sets of objects Args...
4d7ad3c39df539a85f26e47170421ccf04181139987bc1978f72cb512e125a39
Python
950
33
import sys sys.path.append('.') from plotting.utils import load_results, mesh_name, sim_name, m3topl import matplotlib.pyplot as plt import numpy as np import yaml if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results = load_results(mesh_name, sim_name) with open(f"config_files/...
0f498387494ca7d298a46ff087783edf090a1623141493894d652c69345cf5c9
Python
955
46
from ._anndata import ( clean_obs_names, cleanup, get_df, get_initial_size, get_modality, get_size, make_dense, make_sparse, merge, set_initial_size, set_modality, show_proportions, ) from ._arithmetic import clipped_log, invert, multiply, prod_sum, sum from ._linear_mode...
ab11ac48ef2f078696deb9447ef001ae8432b0ee4c0dbde361bac863d5294f7b
Python
955
44
from neurodesign import geneticalgorithm, generate, msequence import sys design_i = sys.argv[1] EXP = geneticalgorithm.experiment( TR = 0.68, P = [.5,.25,.25], C = [[0.5, -0.25, -0.25],[0, 0.5, -0.5]], rho = 0.3, n_stimuli = 3, n_trials = 240, duration = 660, resolution = 0.13...
dbc43171bf1c5141049cf8d49cf2e96f9d725aa59dc5bc666dc9422b73152f3d
Python
955
33
#!/usr/bin/env python2.5 import sys import os import elshowmovie as showmovie cwd = os.path.abspath(os.path.split(__file__)[0]) types = dict(val=("val%03d_3min", "valseq3minby10_%02d.index"), trn=("trn%03d", "trnseq.index")) seq = [("trn", 1), ("val", 1), ("trn", 2), ("val", 2), ("trn", 3), ("val", 3), ("trn", 4), ("...
8e3433e35258bc8862187c7fdb82b57a9ec97446a8883ab1ce546166e2174195
Python
958
36
from __future__ import annotations from ..utils._typed_cache import typed_cache from ..utils._get_lang_cfg import get_lang_cfg from ..counts._count_words import count_words from ..counts._count_difficult_words import count_difficult_words from ._words_per_sentence import words_per_sentence @typed_cache def gunning_...
f3c77b31c132adfd235c841c7012bef0c51b2f506f477e86503ab6168901bb87
Python
958
26
import os from protgps.utils.registry import register_object from protgps.utils.classes import ProtGPS from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor # TODO: add args for various callbacks -- currently hardcoded @register_object("checkpointer", "callback") class Checkpoint(ModelCheckpoi...
280ed9868641ad74f97d6d0d9aab1ea38ec8bee3d54ab2dab1fe18ca243cbf8e
Python
959
34
import sys sys.path.append('.') from plotting.utils import load_results, mesh_name, sim_name, m3topl import matplotlib.pyplot as plt import numpy as np import yaml if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results = load_results(mesh_name, sim_name) with open(f"config_file...
c24a153bf28ff0be01e7ab95059ea53d7730bc9d70ab9069bfcc77a29471477b
Python
960
25
# 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 import unittest from antismash.modules.cl...
d3f74a141a1c374155dd74f384e9433f9e53a1e1c2adedb644829ee9dead459b
Python
961
34
from __future__ import annotations from typing import Callable from pandas.compat._optional import import_optional_dependency import pandas as pd def _arrow_dtype_mapping() -> dict: pa = import_optional_dependency("pyarrow") return { pa.int8(): pd.Int8Dtype(), pa.int16(): pd.Int16Dtype(), ...
fe0e0105dca21c20c13f934e7e89049e14675d96b17dcea490305100c8941575
Python
961
31
import pickle from pathlib import Path from czifile import imread from multiprocessing import Pool from tqdm import tqdm from crystal_tracer.algorithm.detection import frame_detection out_dir = Path('../../data/case2') flood_dir = out_dir / "flood" csv_dir = out_dir / "detection" def main(args): stack, slice = ...
78f12ab44191d0ca7f178c69b5b72ec583d2dc224cb5e64d5cdd541e15b5fe0a
Python
962
38
# This code is written for readability rather than efficiency. # # - It is aimed to give a set of logical steps explaining how to run the analysis # in the manner we ran it for this study. # # Read and inspect data df <- read.csv("your_file.csv") df <- df[ , -1] # Drop the first column (e.g., index) head(df) s...
bbf7f8d72ae66f46acbab9a9ba43b122dfe9c179e2d550040112a1aefe2ecddc
Python
962
40
"""For testing measures.py file.""" import numpy as np import pytest from phyid.measures import ( local_entropy_mvn, ) @pytest.mark.parametrize( "test_input,expected", [ ((0, 0, 1), 0.9189385332046727), ((0, [0], [1]), 0.9189385332046727), (([0, 0], [0, 0], np.identity(2)), 1.8378...
f2a51a621f101ce265cfb30dbe4b8937261d08e0a2bee5b4a5b99fff638f66ed
Python
962
26
from distutils.unixccompiler import UnixCCompiler class ArmCCompiler(UnixCCompiler): """ Arm compiler. """ compiler_type = 'arm' cc_exe = 'armclang' cxx_exe = 'armclang++' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self...
16612cfec29a53da31fb97f4354dff4d122fd17c4b415119f2ba2ef5535e85be
Python
964
131
import numpy as np i8 = np.int64(1) u8 = np.uint64(1) i4 = np.int32(1) u4 = np.uint32(1) b_ = np.bool(1) b = bool(1) i = int(1) AR = np.array([0, 1, 2], dtype=np.int32) AR.setflags(write=False) i8 << i8 i8 >> i8 i8 | i8 i8 ^ i8 i8 & i8 i << AR i >> AR i | AR i ^ AR i & AR i8 << AR i8 >> AR i8 | AR i8 ^ AR i8 &...
8f19d3c095f9f6aa81bc8297f10c82439e9d0b581df7dddb41e0224375e2ea59
Python
967
28
import logging import redis.asyncio as redis from app.utils.environment import CONFIG # Configure logging logger = logging.getLogger(__name__) # Note: Configure logging in the application entry point instead of here. async def get_redis_connection(): """Creates and returns an asynchronous Redis connection pool...
9021343e4b8f9350b19191ce0dedda679e15f877350221e4c8d3558cde511083
Python
967
28
import numpy as np import pytest from pandas import ( TimedeltaIndex, Timestamp, ) import pandas._testing as tm class TestSearchSorted: def test_searchsorted_different_argument_classes(self, listlike_box): idx = TimedeltaIndex(["1 day", "2 days", "3 days"]) result = idx.searchsorted(listl...
9c1de91d618d525a16a600b627aec9806413bb130f5ea696ac86b7c4695d7695
Python
968
35
""" H6 molecule VQNHE with code from tc.application """ import numpy as np import tensorcircuit as tc from tensorcircuit.applications.vqes import VQNHE, JointSchedule, construct_matrix_v3 tc.set_backend("tensorflow") tc.set_dtype("complex128") h6h = np.load("./h6_hamiltonian.npy") # reported in 0.99 A hamiltonian =...
410636fade3b38b1d438612caebee5e22be49d0ce0a63c2a539fc6a6419afa3c
Python
972
30
import numpy as np from yass.augment import noise from yass.batch import RecordingsReader def test_can_kill_signal(path_to_standardized_data): recordings = RecordingsReader(path_to_standardized_data, loader='array')._data noise.kill_signal(recordings, ...
5df2eff619c6b153c8b00d4bc161222d61d93c8d80ec8184935b85390e5c85c5
Python
972
27
import sys sys.path.append('.') from plotting.utils import load_results, m3tofl, set_plotting_defaults, efcolor, pvscolor, ecscolor, dpi import matplotlib.pyplot as plt set_plotting_defaults() import matplotlib.pyplot as plt if __name__ == '__main__': sim_name = sys.argv[1] mesh_name = sys.argv[2] results =...
4c6a5a6ae42affcd6cb958e77aa93306584c82ef93634fa09becc59d865808ad
Python
975
29
import random import numpy as np from typing import Tuple class ReverseComplement(): def __init__(self, p=0.5) -> None: self.p = p def __call__(self, x: np.ndarray, y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: if random.random() >= self.p: return reverse_complement(x, y) ...
88cfc545832dbef744a4cb4b512b8177f5b0e671ebdbce2fd9f4711dac9dbc83
Python
975
27
import pandas as pd import pandas._testing as tm class TestUnaryOps: def test_invert(self): a = pd.array([True, False, None], dtype="boolean") expected = pd.array([False, True, None], dtype="boolean") tm.assert_extension_array_equal(~a, expected) expected = pd.Series(expected, ind...
8362fd715b3a34ae341b5ea43382ccc986643a29d3a715c5f6d2dfd058c32fab
Python
977
37
#!/usr/bin/env python3 """ BiG-SCAPE PI: Marnix Medema marnix.medema@wur.nl Maintainers: Arjan Draisma arjan.draisma@wur.nl Catarina Loureiro catarina.salesesantosloureiro@wur.nl Nico Louwen nico.louwen@wur.nl Developers: Arjan Draism...