sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
f82f0e2bbaf19f7b0851d570c59041a5e1e12335f4788f9533731e9987da5e6d
Python
351
16
from typing import List, TypeVar T = TypeVar("T") class Stack(List[T]): """A small shim over builtin list.""" @property def top(self) -> T: """Get top of stack.""" return self[-1] def push(self, item: T) -> None: """Push an item on to the stack (append in stack nomenclature)...
69fea3d5ba1d41881197e19b1b598f4848766c29661f64ab5b53bce04a075f84
Python
352
7
from asap.models.vanilla_cnn import VanillaCNN from asap.models.recurrent import CNN_LSTM from asap.models.dilated_cnn import DilatedCNN from asap.models.convnext_transformer import ConvNextTransformer from asap.models.convnext_cnn import ConvNeXtCNN from asap.models.convnext_lstm import ConvNeXtLSTM from asap.models.c...
c9651c17539a5d37c48d7a226d0b04f051fe38db93034a1d24657626c4d89c57
Python
352
12
"""Readers for different file formats.""" from ._ome_zarr_reader import OMEZarrReader from ._tensorstore_zarr_reader import TensorstoreZarrReader from ._tiff_collection_reader import TiffCollectionReader, TiffCollectionSettings __all__ = [ "OMEZarrReader", "TensorstoreZarrReader", "TiffCollectionReader", ...
5ab9dda527ba8b57245ff490d4a6b10fd093286cc3d04b82385c5c6f0169a0b5
Python
353
17
""" pygments.__main__ ~~~~~~~~~~~~~~~~~ Main entry point for ``python -m pygments``. :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys from pip._vendor.pygments.cmdline import main try: sys.exit(main(sys.argv)) except Ke...
bd22eaa8927dd7ea973b3e6d5e368f9f08f94c3073f948e7f08ef298d99dbed0
Python
353
13
from __future__ import annotations __version__ = "25.3" def main(args: list[str] | None = None) -> int: """This is an internal API only meant for use by pip's own console scripts. For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wr...
176a970a22cf66ec561c4647da25a122a8d153d8e4019d596d57642e3f4be4dc
Python
354
11
from .transformer import GraphTransformer from omegaconf import DictConfig from .brainnetcnn import BrainNetCNN from .fbnetgen import FBNETGEN from .BNT import BrainNetworkTransformer def model_factory(config: DictConfig): if config.model.name in ["LogisticRegression", "SVC"]: return None return eval(...
e88e08cbe1b679b9a357f7018add7cb0fe2cd1247b691ca38f030d205fc4d457
Python
355
16
from pathlib import Path conf_template = Path(__file__).with_name("conf.py.in") namespace = { "__file__": str(conf_template), "__name__": "__main__", } rendered = conf_template.read_text(encoding="utf-8").replace( "@PACKAGE_VERSION@", "dev", ) exec(compile(rendered, str(conf_template), "exec"), names...
516c9dab4459982c3c65b52f13faab670ff158d2792819d0d42a8215c010b774
Python
356
14
from __future__ import annotations from typing import TYPE_CHECKING, Any from pymmcore_widgets import InstallWidget if TYPE_CHECKING: from qtpy.QtWidgets import QWidget class _InstallWidget(InstallWidget): def __init__(self, parent: QWidget | None = None, **kwargs: Any) -> None: super().__init__(pa...
8b0bd5a9ad861bd4e362b775af10818dd2de19006846a50ed9f66720b1256d98
Python
356
19
from pandas.core.arrays.sparse.accessor import ( SparseAccessor, SparseFrameAccessor, ) from pandas.core.arrays.sparse.array import ( BlockIndex, IntIndex, SparseArray, make_sparse_index, ) __all__ = [ "BlockIndex", "IntIndex", "make_sparse_index", "SparseAccessor", "SparseA...
93c351881797681000547148dba53e613cb803fb42f089dc4de9c1380fd85fbb
Python
356
11
from .registry import model_entrypoint from .graph_attention_transformer import * # from .graph_attention_transformer_md17 import * # from .graph_attention_transformer_oc20 import * from .dp_attention_transformer import * # from .dp_attention_transformer_md17 import * # from .dp_attention_transformer_oc20 import * #...
90d6d9bfd9e36bd88b5661995360fac3676a0769ddb1ba937dcb19b06cff628d
Python
357
17
""" Public API for Rolling Window Indexers. """ from pandas.core.indexers import check_array_indexer from pandas.core.indexers.objects import ( BaseIndexer, FixedForwardWindowIndexer, VariableOffsetWindowIndexer, ) __all__ = [ "check_array_indexer", "BaseIndexer", "FixedForwardWindowIndexer", ...
2d2bb327d3ac434204a56dab2a5030baf372a597836740090e824eb7ddd707e9
Python
359
11
def __getattr__(attr_name): from numpy._core import numeric from ._utils import _raise_warning sentinel = object() ret = getattr(numeric, attr_name, sentinel) if ret is sentinel: raise AttributeError( f"module 'numpy.core.numeric' has no attribute {attr_name}") _raise_warnin...
ae64a672131f3a15fc48e99342a4283c842abfe76599d99c4bf422f1cc753350
Python
360
13
from braincog.base.node.node import * from braincog.base.connection.layer import * from braincog.base.strategy.surrogate import * class MyGrad(SurrogateFunctionBase): def __init__(self, alpha=4., requires_grad=False): super().__init__(alpha, requires_grad) @staticmethod def act_fun(x, alpha): ...
068aeb2bcfd925b3791d67085fd7c23fe05b4c2689b20006522cdae48c2162be
Python
361
13
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("na", [None, np.nan, pd.NA]) def test_setitem_missing_values(na): arr = pd.array([True, False, None], dtype="boolean") expected = pd.array([True, None, None], dtype="boolean") arr[1] = na tm.ass...
74d066e0c38cdc41d8bd5d5284b17a30ddfde00caa6613e93e581b92ec0de242
Python
366
14
from .physunits import Quantity, units import cedalion.dataclasses import cedalion.dataclasses.accessors from cedalion.bibliography import Bibliography from ._version import __version__ # singleton container that collects references bib = Bibliography() def cite(key: str) -> None: """Record that a method with t...
b7636a230ddd92c1bd5d90b3dfe423c2d1421c16c51485b64caa57119affe5b8
Python
368
19
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Perform test request """ import pprint import requests DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" IMAGE = "zidane.jpg" # Read image with open(IMAGE, "rb") as f: image_data = f.read() response = requests.post(DETECTION_URL, files={"image":...
943c0762063cbd75772464c5e7c6fc6ac23bacf6c72e46f420bb985244280c24
Python
369
15
# -*- coding: utf-8 -*- import json def save_dict(filename, dic): '''save dict into json file''' with open(filename, 'w') as json_file: json.dump(dic, json_file, ensure_ascii=True) def load_dict(filename): '''load dict from json file''' with open(filename, "r") as json_file: ...
3f7d78d8019447d21f1b2beebb86e9fd18910710dd2f284c303f7868ed1fcaa2
Python
370
18
''' Created on 2016.7.6 @author: liangqian ''' from Modal.pitch import Pitch class Note(): ''' Because a chord consist of more than two pitches at the same time, so using arrays to record the chord ''' def __init__(self): self.pitches = [] # self.startTime = [] # self.endTim...
9645ebbb97e87715fccb33a6b8e2520dafcb24e750f4deda25332b71227c0860
Python
371
15
import torch from torch import nn class SimilarityLoss(nn.Module): """ Computes BYOL's simple similarity loss""" def __init__(self): super(SimilarityLoss, self).__init__() def criterion(self, x, y): x = nn.functional.normalize(x, dim=-1, p=2) y = nn.functional.normalize(y, dim=-...
ec06934ca2425bbb8d759b7a675275fd37a60de0d011ac8775328ce8d978bf7c
Python
371
10
from setuptools import setup, find_packages setup( name="rna3db", version=1.1, description="A dataset for training and benchmarking deep learning models for RNA structure prediction", author="Marcell Szikszai", packages=find_packages(exclude=["tests", "scripts", "data"]), install_requires=["bio...
bb7cfbd664ceb86b1c50ec91c0fa627bee9a23a1380e3a1a6ab72c2615d12517
Python
372
11
# Yet another wild way to do this, but way easier than # trying to configure things within each app/cli to find # the test data... Plus it lets users play with it a bit more import aims_immune import os import shutil def getit(): aims_dir = aims_immune.__file__[:-11] startDir = os.getcwd() shutil.copytree(...
307a321d6993d436762090b2b4494181a9ef0bb8293d6a67abe5cc138c08c84a
Python
373
18
from typing import TypeVar, List from app.dataflow.qqueue import IQueue T = TypeVar('T') class QueueForker(IQueue): def __init__(self, queues: List[IQueue]): self.queues = queues def enqueue(self, item): for queue in self.queues: queue.enqueue(item) def close(self): ...
2f99d9c32190bece6862c211388029a2fedf8517b5876d59e15886d092903e68
Python
376
14
""" A quick script to output the top N words (500 for now) in each language. You can send the output to a file and diff it to see changes between wordfreq versions. """ import wordfreq N = 500 if __name__ == '__main__': for lang in sorted(wordfreq.available_languages()): for word in wordfreq.top_n_list(l...
1ff7531ef09acd103424e5489d185193060b459c532cc579cf1032199c4f5157
Python
378
9
"""Tools for plotting collective events.""" __author__ = """Benjamin Graedel""" __email__ = "benjamin.graedel@unibe.ch" __version__ = '0.3.3' from ._plotting import LineagePlot, NoodlePlot, dataPlots, plotOriginalDetrended, save_animation_frames, statsPlots __all__ = ["plotOriginalDetrended", "dataPlots", "statsPlot...
83aca1002101873c5ab9312d54532bfca8f03b1e66d8cc4e7a58bb798369bdcd
Python
379
12
import cedalion.io import cedalion.data from cedalion.dataclasses.schemas import validate_stim_schema def test_read_events_from_tsv(): bids_top_level_directory = cedalion.data.get_multisubject_fingertapping_path() for fname in bids_top_level_directory.glob("**/*_events.tsv"): stim = cedalion.io.read_...
ddd297ce3d96caf7bd219ae51a3c3b3a08445b37ac7c2e3cd87066c975427e82
Python
379
11
from crystal_tracer.algorithm.tracking import independent_match import pickle import pandas as pd from pathlib import Path if __name__ == '__main__': df_folder = '../data/detection' frames = [pd.read_csv(p) for p in Path(df_folder).glob('*.csv')] res = independent_match(frames) with open('../../data/ca...
26174d9e77acd4055fe24201723ffb0ffe81ed3a6ce0fc88efaa3a9532827627
Python
380
17
from saveman import (connectivity, connectivity_umap, gradients) from saveman.analyses import (reference, measures, eccentricity, adaptation, seed, behaviour, rsa, fpca) connectivity.main() connectivity_umap() gradients.main() reference.main() measures.main() eccentricity.main() adaptati...
4dda33433c1367366c5e5cce30829a4144af9c14a2b3cfc5e4907d6f6a4d1341
Python
380
14
from openai import AzureOpenAI def get_embedding(api_key,api_base,api_version,deployment_name, text_to_embed): client = AzureOpenAI( api_key=api_key, api_version=api_version, azure_endpoint = api_base ) response = client.embeddings.create( model=deployment_name, inpu...
3c73371c0c41bf21552b781f2451653cbb1c693fd2a27105cda03ced237e650e
Python
381
13
from click.testing import CliRunner from cardio_audio_sleep.commands.main import run def test_main(): """Test the main package entry-point.""" runner = CliRunner() result = runner.invoke(run) assert result.exit_code == 0 assert "Entry point to start the tasks." in result.output assert "Option...
61298418d8c6fb6de2f82c58cbcc52211bb366dbba2a0da2ed0e78d1770bd102
Python
382
17
"""Usage: python run.py --config-name path-to-config""" import hydra from nablaDFT.pipelines import run from nablaDFT.utils import init_wandb, load_envs from omegaconf import DictConfig @hydra.main(config_path="./config", config_name=None, version_base="1.2") def main(config: DictConfig): load_envs() init_wa...
6098a1672b6cb3e315369ae9e29e6900bfde99e0b9a5bde1070b5a4b7c8c09c5
Python
384
13
import numpy as np from pandas import date_range import pandas._testing as tm class TestSplit: def test_split_non_utc(self): # GH#14042 indices = date_range("2016-01-01 00:00:00+0200", freq="s", periods=10) result = np.split(indices, indices_or_sections=[])[0] expected = indices._...
0a558ba6b30985fea891436ef405fa02bf485d980a918d2736e0f31d13bbd079
Python
385
14
import numpy as np from pandas import DataFrame from pandas.tests.copy_view.util import get_array def test_get_array_numpy(): df = DataFrame({"a": [1, 2, 3]}) assert np.shares_memory(get_array(df, "a"), get_array(df, "a")) def test_get_array_masked(): df = DataFrame({"a": [1, 2, 3]}, dtype="Int64") ...
f969cdd0796a886f513e07353ff2922d9bea810e301980dfd2515cc9f58e2dfb
Python
385
15
from . import util import numpy as np class TestF2Cmap(util.F2PyTest): sources = [ util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90"), util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap") ] # gh-15095 def test_gh15095(self): inp = np.ones(3) out = self.mod...
4c92da30fda289eeac32ea96244ad7db8ede26096dcfaa5db78c254c3376ad76
Python
386
21
from __future__ import annotations from pyphen import Pyphen # type: ignore import pytest from textstat.backend import utils @pytest.mark.parametrize( "lang", [ "en_US", "en", "es_ES", "es", "de_DE", "de", "fr_FR", ], ) def test_get_pyphen(lang: st...
22d79fafd729a40988a23919dc99dec7ee9b3da0a60deb009dcb865e4af88470
Python
388
14
from setuptools import setup from pip._internal.req import parse_requirements requirements = parse_requirements('requirements.txt', session=False) install_requires = [str(req.requirement) for req in requirements] setup( name='chronognosis', version='0.1.0', author='onnonuro', packages=['chronognosis']...
d27c02a94d7f61e0926520175aa6e73f1f6c2c9a1412fe7b2780baf18b1a213b
Python
389
24
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 25 20:29:36 2019 @author: charleshen 316 Estate Index descriptors """ from mordred import Calculator, descriptors import numpy as np _calc = Calculator(descriptors.EState) _EstateNames = [str(i) for i in _calc.descriptors] def GetEstate(mol):...
8c8a1021c9b0d6ec98e57e8364422a2ee6aea0932be127396d76178ecbf12973
Python
390
17
from bermol.trainer import BerMolPreTrainer import numpy as np path = "" predictor = BerMolPreTrainer.load(path) def smi_feature(smi: str) -> np.ndarray: output = predictor.transform([smi]) pooled_output = output[0][1] return pooled_output.cpu().detach().numpy().reshape(-1) smi = "Cc1nc2c(c(-c3ccc(Cl)...
6286b5e4f0c7e083f31408705b4e2b0b275eb958aedf6a858dfe82f22229b9d8
Python
391
18
import wave import struct import os import numpy as np f = 440 framerate = 44100.0 fw = wave.open("sine.wav","wb") fw.setnchannels(1) fw.setframerate(framerate) fw.setsampwidth(2) tt = np.arange(0, 1, 1.0/framerate) data = [2000*(np.sin(2*np.pi*f*t)+np.sin(2*np.pi*2*f*t)+np.sin(2*np.pi*3*f*t)) for t in tt] print(data...
43a9b2a891ea96938bef6a283bde44619ffd3f9a7c4448e4119bd18e94a0e7fe
Python
392
19
from __future__ import annotations import pytest from textstat.backend import utils @pytest.mark.parametrize( "lang, root", [ ("en_US", "en"), ("en", "en"), ("en_GB", "en"), ("de_DE", "de"), ("es_ES", "es"), ("fr_FR", "fr"), ], ) def test_get_lang_root(lang...
f1844b1a37fa8c2ab6f899dbfee49f723677aec5a0e3cca2249b94821f0cbb7e
Python
392
11
import torch.nn as nn def count_params(model: nn.Module, only_requires_grad: bool = False): "count number trainable parameters in a pytorch model" if only_requires_grad: total_params = sum(p.numel() for p in model.parameters() if p.requires_grad) else: total_para...
16a72929d510050d056b31c5c6bf4cb0b1191be8e725518a5995f6a3046be034
Python
393
27
from __future__ import annotations from typing import Any import numpy as np AR_i8: np.ndarray[Any, np.dtype[np.int_]] = np.arange(10) ar_iter = np.lib.Arrayterator(AR_i8) ar_iter.var ar_iter.buf_size ar_iter.start ar_iter.stop ar_iter.step ar_iter.shape ar_iter.flat ar_iter.__array__() for i in ar_iter: pass...
9df1b2349bcdcbbfe399679b2a37af2ca87200c36f2398f2b64653365a440be8
Python
393
14
from pandas import ( TimedeltaIndex, timedelta_range, ) import pandas._testing as tm class TestTimedeltaIndexOps: def test_infer_freq(self, freq_sample): # GH#11018 idx = timedelta_range("1", freq=freq_sample, periods=10) result = TimedeltaIndex(idx.asi8, freq="infer") tm.a...
22f80e4549a9d304e5044e7bcfcbcc3bb8367354feea44a28213c20d21b76179
Python
395
17
from setuptools import setup, find_packages setup( name='saveman', version='1.0', packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), license='MIT', author='AliRezaei', url='*', install_requires=[], tests_require=[ 'p...
6480d022cbba828267560f8a697fbcbba89329f680eb13aa2408f8aca4d0df80
Python
396
17
import numpy as np import os def remove_small_units(templates, threshold=2.5, units_in=None): print (" .....PTP threshold: ", threshold) if units_in is None: n_units = templates.shape[0] units_in = np.arange(n_units) # compute ptp ptps = templates[units_in].ptp(1).max(1) # un...
541d39045672d774bd2e01938e0e459519d30c3002c670625292f88029bca870
Python
397
13
from .channel_controls_widget import ChannelControlsWidget from .channel_table_model import ChannelTableModel from .channel_table_view import ChannelTableView from .imc_file_tree_model import IMCFileTreeModel from .imc_file_tree_view import IMCFileTreeView __all__ = [ "ChannelControlsWidget", "ChannelTableMode...
c233a18b85bf2b3aa3563d6a22ddc44ef0b4ada4a78f60c1c69fcfbb0c7843c7
Python
398
15
"""A Micro-Manager GUI based on pymmcore-widgets and pymmcore-plus.""" from importlib.metadata import PackageNotFoundError, version try: __version__ = version("micromanager-gui") except PackageNotFoundError: __version__ = "uninstalled" __author__ = "Federico Gasparoli" __email__ = "federico.gasparoli@gmail.c...
2f7a776888c94cd428b52b21067d7d6afd6a18a52e73ad277360248f5bc98a96
Python
399
16
from setuptools import setup, Extension from Cython.Build import cythonize import numpy extensions = [ Extension("image_loader", ["image_loader.pyx"], include_dirs=[numpy.get_include()]), Extension("subsample_mean", ["subsample_mean.pyx"], include_dirs=[numpy.get_include()]) ] setup( ext_modules=cython...
3e3cf41def37d7f3e58994785c88e0192750d6f8fa1eca933e679fe1ae4e61a6
Python
401
16
from . forward_model import ForwardModel from .head_model import ( TwoSurfaceHeadModel, get_standard_headmodel, get_inflated_cortex_surface, ) from . image_recon import ( ImageRecon, OriginalGaussianSpatialBasisFunctions, GaussianSpatialBasisFunctions, REG_TIKHONOV_ONLY, REG_PAPER_MUA_SB...
f6d03adaa2f4b866d228c65dc4cc0d8c0369c5a341e1bb8474a7ea0107a3d074
Python
401
14
import pandas as pd import pandas._testing as tm def test_read_gbq_deprecated(): with tm.assert_produces_warning(FutureWarning): with tm.external_error_raised(Exception): pd.read_gbq("fake") def test_to_gbq_deprecated(): with tm.assert_produces_warning(FutureWarning): with tm.ext...
d108da4dd68eb9600850f8773c73334244f615f76d9da87b3bbc5756c72ed369
Python
402
27
from . import ( ase_model, dataset, dimenetplusplus, equiformer_v2, escn, gemnet_oc, graphormer, painn_pyg, phisnet, schedulers, ) from .model_registry import model_registry __all__ = [ ase_model, dataset, dimenetplusplus, equiformer_v2, escn, gemnet_oc, ...
7a656c5e42d81cb66a134660c52be01c04243e468a31a6ca6cf88f9795979b7a
Python
404
17
from rdkit.Chem import DataStructs from rdkit.Avalon.pyAvalonTools import GetAvalonFP as GAFP import numpy as np _type = 'topological-based' def GetAvalonFPs(mol, nBits=2048): ''' Avalon_fingerprints: https://pubs.acs.org/doi/pdf/10.1021/ci050413p ''' fp = GAFP(mol, nBits = nBits) arr = np.zero...
9c80557ca4ea29e59d9fa3a0b4d34bdc85144d096fd0a2b9ae098f8d94eaaf0f
Python
405
9
# This file contains paths to any included files in the big_scape package import importlib_resources DB_SCHEMA_FILE = importlib_resources.files("big_scape") / "data/schema.sql" TEMPLATES_OUTPUT_DIR = importlib_resources.files("big_scape") / "output" # config is in base directory, not in module # get path to package d...
d5996c2592a452f099da5a08538c8760862c9bad22123c6f0c41350ef4a02515
Python
405
13
#!/usr/bin/env python3 import boto3 # type: ignore[import] def main() -> None: creds_dict = boto3.Session().get_credentials().get_frozen_credentials()._asdict() print(f"export AWS_ACCESS_KEY_ID={creds_dict['access_key']}") print(f"export AWS_SECRET_ACCESS_KEY={creds_dict['secret_key']}") print(f"expo...
fd3a081a3f8ccc859edef0050f91c5bc3216a82f8adcbf5658d7cd12bdac7f7c
Python
405
21
import numpy as np fname_template = 'im%07d.png' zero_buffer_length = 150 framelist = [fname_template % 0] * zero_buffer_length start_frame = 1801 end_frame = 2701 framelist = framelist + [fname_template % i for i in range(start_frame, end_frame)] + framelist print framelist print '\n'.join(framelist) out_file_...
545398d6f97507e72217b381fd460837de7a044376de75e9b700a95fdb86acec
Python
406
19
"""Contains enums relating to genbank files""" from enum import Enum class RECORD_TYPE(Enum): REGION = "region" CAND_CLUSTER = "cand_cluster" PROTO_CLUSTER = "protocluster" PROTO_CORE = "proto_core" class FEATURE_TYPE(Enum): REGION = "region" PROTOCLUSTER = "protocluster" PROTO_CORE = "...
20acb64c7c26bb9520063b556f06c3f47f80a7cb9a509a0f2766ed43825ab5da
Python
407
15
""" Distributor init file Distributors: you can add custom code here to support particular distributions of numpy. For example, this is a good place to put any BLAS/LAPACK initialization code. The numpy standard source distribution will not put code in this file, so you can safely replace this file with your own ver...
f182e53ba4f2b043f196d7db34a746f4c9555de0cb7d3206368da7511f99c25d
Python
408
9
""" core.array_algos is for algorithms that operate on ndarray and ExtensionArray. These should: - Assume that any Index, Series, or DataFrame objects have already been unwrapped. - Assume that any list arguments have already been cast to ndarray/EA. - Not depend on Index, Series, or DataFrame, nor import any of these...
a17a429e53cb218f6a9c7cbdf3d5eae6929431650e714d5bf1a7febf2a2db0e3
Python
409
21
import functools from typing import Callable task_registry = {} def task(f: Callable): name = f.__name__ if name in task_registry: raise ValueError( f"there is already a function with name '{name}' " "in the registry." ) @functools.wraps(f) def wrapper(*args, **kwargs): ...
3e284f7f67b648b9cca719fffd53a1c7c1f2a727b502c856b559fb6416f847a0
Python
410
16
import time from contextlib import contextmanager @contextmanager def timer_context(label, verbose=True): if verbose: print(label) start_time = time.time() try: yield finally: end_time = time.time() elapsed_time = end_time - start_time if verbose: # Print elaps...
c5527f03e07095786357f9ddadf9d5c535e24d7e88bd6fa467a53ba9dd33275a
Python
412
13
"""Builds on pint_xarray's unit registry.""" import pint_xarray units = pint_xarray.unit_registry Quantity = units.Quantity # Aliases that we want to provide. FIXME: maybe a definition file is more convenient? units.define("@alias deg = o") units.define("@alias degC = oC") units.define("@alias ohm = Ohm") # FIXME te...
e5f7bd63b0c3cce6e47a1b1bbe4f676271baa5100a25e3c6315a4c974081f358
Python
413
10
""" Provides: - Routines for interacting with, evaluating, and training word embeddings as used in Van Paridon & Thompson (2020). - Routines for extending lexical norms to unnormed words. - Routines for retrieving word, bigram, and trigram frequencies. - Command line tools to conveniently do any of the above, i...
e51c88c37d6291146aa4a9846c6d55e7b96e3246f6ba0dc225862e589c6cf52e
Python
414
22
"""Contains database functionality modules""" from .sqlite import DB from .partial_task import ( find_minimum_task, get_input_data_state, get_missing_gbks, get_hmm_data_state, get_cds_to_scan, get_hsp_to_align, ) __all__ = [ "DB", "find_minimum_task", "get_input_data_state", "...
cde9716d3ea83c566736bc163e973592d51e013f957387ee15c4592d018bb4c2
Python
417
19
""" Timer context manager, only used in debug. """ from time import time import contextlib from typing import Generator @contextlib.contextmanager def timer(subject: str = "time") -> Generator[None, None, None]: """print the elapsed time. (only used in debugging)""" start = time() yield elapsed = t...
e8b8a6f2dfc0e25ec760e207cc6048323752b227c37fa82a45ba038505636712
Python
418
22
''' Created on 2018.8.31 @author: liangqian ''' from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * def drawFunc(): glClear(GL_COLOR_BUFFER_BIT) #glRotatef(1, 0, 1, 0) glutWireTeapot(0.5) glFlush() glutInit() glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA) glutInitWindowSize(400...
3f0d2170560d7acb8f13cb8d0e6f4ff0355320509206a51c224afab26418cee3
Python
419
14
from . import qem_methods apply_zne = qem_methods.apply_zne zne_option = qem_methods.zne_option # type: ignore apply_dd = qem_methods.apply_dd dd_option = qem_methods.dd_option # type: ignore used_qubits = qem_methods.used_qubits prune_ddcircuit = qem_methods.prune_ddcircuit add_dd = qem_methods.add_dd apply_rc = ...
58227ae503228f5fc5dbb5190a1070c55151250da7e794fae5d495614f3715d2
Python
420
20
import h5py import numpy as np from collections import OrderedDict import sys import os def YRcoding(s): encoded = ''.join([{'A':'R', 'T':'Y', 'C':'Y','G':'R', 'n':'n'}[B] for B in s]) return encoded input_file = sys.argv[1] out_file = sys.argv[2] out = open(out_file, "w") for line in open(input_...
0ad7b389602c3cfdb60da158d0d309aeb4d48b63b6afe789b756d8143973fc59
Python
421
22
from __future__ import annotations from pyphen import Pyphen # type: ignore from ._typed_cache import typed_cache @typed_cache def get_pyphen(lang: str) -> Pyphen: """Get a pyphen object for the given language. Parameters ---------- lang : str The language of the text. Returns ---...
94e11e79272262e84466d58e51c8c42aed973ad2f2711391980385710e7e30ac
Python
422
11
########################################################################## # NSAp - Copyright (C) CEA, 2016 # 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. ##########...
d517a6fe07849b8ab20f75da440d4d00f2b0af762346aebccdb2250bf5e18bd3
Python
422
16
import numpy as np np.sin(1) np.sin([1, 2, 3]) np.sin(1, out=np.empty(1)) np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)]) np.sin(1, signature="D->D") # NOTE: `np.generic` subclasses are not guaranteed to support addition; # re-enable this we can infer the exact return type of `np.sin(....
7881d30fba9d387439b77e1d836872b27107a3b29d9dcff9b3c12bc7f02a40dd
Python
423
20
from yass.batch import vectorize_parameter # create a function that adds up three numbers, vectorize over parameter a @vectorize_parameter('a') def add(a, b, c): return a + b + c # same as above, but this time decorate an instance method class Object(object): @vectorize_parameter('a') def add(self, a, b...
7af0edf10378945e428b0ad421794e2429ed8ad0423ac23764b3c42005512c95
Python
423
17
from typing import Optional def pick_bool(*values: Optional[bool]) -> bool: """Pick the first non-none bool or return the last value. Args: *values (bool): Any number of boolean or None values. Returns: bool: First non-none boolean. """ assert values, "1 or more values required" ...
2ce88ae106ad74ff9f4a837f3cd2b28040fd0de45e4e28acec1dc7f4101edb6d
Python
424
13
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QPushButton class SelectionButtons(QWidget): def __init__(self): super().__init__() self.setLayout(QHBoxLayout()) self.deselect_all_button = QPushButton('deselect all') self.select_all_button = QPushButton('select all') se...
d29f3317d4d9ce101cdc27fbfda8108a3306ba2cc9f7955017c6625e22432534
Python
426
28
amino_acid_3to1letter = { "CYS": "C", "ASP": "D", "SER": "S", "GLN": "Q", "LYS": "K", "ILE": "I", "PRO": "P", "THR": "T", "PHE": "F", "ASN": "N", "GLY": "G", "HIS": "H", "LEU": "L", "ARG": "R", "TRP": "W", "ALA": "A", "VAL": "V", "GLU": "E", ...
347096aba11699dade21825730653e83f16dd58f8adbdff156b57de008b44c3b
Python
427
15
""" Checking results from threshold detector """ import matplotlib.pyplot as plt from yass.explore import SpikeTrainExplorer, RecordingExplorer path_to_data = '/Users/Edu/data/yass/tmp/standardized.bin' path_to_spike_train = '/Users/Edu/data/yass/tmp/spike_train.npy' exp = RecordingExplorer(path_to_data, spike_size=...
d9ae7afdf0b7ce4bf598dc07e348aabee48be46aaafaf48914d5b8c1a2754079
Python
428
14
import pandas as pd # Read the comma-separated string from file with open('CT2_log/euclidean/final_candidate/cluster.csv', 'r') as f: content = f.read() # Split by commas and clean up whitespace genes = [gene.strip() for gene in content.split(',')] # Create DataFrame df = pd.DataFrame(genes, columns=['Gene Name'...
831b7babdf55ceb9baea9482318212c56314433ea54fb88aea55fec40d312b2a
Python
429
14
#!/usr/bin/env python from setuptools import setup setup(name='ibc_public', version='0.1', description='Public code for IBC data analysis', url='https://github.com/hbp-brain-charting/public_analysis_code', author='Bertrand Thirion', author_email='bertrand.thirion@inria.fr', package...
a4afe43ff0d94859c0bfff2be19a243cdda8c6eefd0412b5f0930ec2a9927a9a
Python
429
15
"""Tools for validating detected collective events.""" __author__ = """Benjamin Graedel""" __email__ = "benjamin.graedel@unibe.ch" __version__ = '0.3.3' from arcos4py.validation._bootstrapping import bootstrap_arcos, calculate_arcos_stats, calculate_pvalue from arcos4py.validation._resampling import resample_data __...
680b7ffe6f3f24362125f84c7acb4d239f0c4696a298f380036ff170be7b52f8
Python
430
12
from keras.models import Model class GraphModel(Model): """ This is a simple modification of the Keras `Model` class to avoid checking each input for a consistent batch_size dimension. Should work as of keras-team/keras#11548. """ def _standardize_user_data(self, *args, **kwargs): kwargs[...
2f2362c37d3132ec4ff786634f3f2a2a143b88a7ad25ffa681c1b092caeba494
Python
432
15
import torch from abc import ABC, abstractmethod class BaseEvaluator(ABC): @abstractmethod def evaluate(self, x: torch.FloatTensor, y: torch.LongTensor, split: dict) -> dict: pass def __call__(self, x: torch.FloatTensor, y: torch.LongTensor, split: dict) -> dict: for key in ['train', 'tes...
67e0261229369b8179345246b5dd16ee56463741564daef1f5e19e4d0ea661be
Python
432
11
########################################################################## # 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. ##########...
5d883c7d7fe264dfb7b6e054d886e32d94a6e301abb9886ff75d2ad0cbb996dc
Python
433
14
"""Arcos4py top level module. This package is a python package for the detection and tracking of collective events intime-series data and raster images. """ __author__ = """Benjamin Graedel""" __email__ = "benjamin.graedel@unibe.ch" __version__ = '0.3.3' from ._arcos4py import ARCOS from .tools._detect_events import...
649b08f1fb4226065498f7bf5c50221bd5c2a0a0f1c34502215edc397339e061
Python
434
14
import jupyterlab # Kind of a wild thing but this will be a nice way # to be able to launch the notebook automatically without # our users having to search for it... maybe. from jupyterlab import labapp import aims_immune import os import shutil def launchit(): aims_dir = aims_immune.__file__[:-11] startDir =...
26c9a6fe9dffa90a5f27d3aa0a90f7b8b333064a6cc6e7e3d70ea2528ad8aa69
Python
435
13
import pytest from pandas import IntervalIndex import pandas._testing as tm class TestPickle: @pytest.mark.parametrize("closed", ["left", "right", "both"]) def test_pickle_round_trip_closed(self, closed): # https://github.com/pandas-dev/pandas/issues/35658 idx = IntervalIndex.from_tuples([(1,...
40a0dc78af0afee8eac030dcde862b474a1d381620295390439bc56a9fc6fdc8
Python
435
14
# .-. .-. .-. . . .-. .-. .-. .-. # |( |- |.| | | |- `-. | `-. # ' ' `-' `-`.`-' `-' `-' ' `-' __title__ = "requests" __description__ = "Python HTTP for Humans." __url__ = "https://requests.readthedocs.io" __version__ = "2.32.5" __build__ = 0x023205 __author__ = "Kenneth Reitz" __author_email__ = "me@kennethrei...
a76c3b1756ab762fc64574ab9cd211f16d68787fe9826c3fd4fdb04b403623a3
Python
435
22
""" Build an example package using the limited Python C API. """ import numpy as np from setuptools import setup, Extension import os macros = [("NPY_NO_DEPRECATED_API", 0), ("Py_LIMITED_API", "0x03060000")] limited_api = Extension( "limited_api", sources=[os.path.join('.', "limited_api.c")], include_dir...
4f8582b9e672f5649053111585b46c74a5de23c57987a8f0e42c9570853c7eca
Python
436
18
""" Configures cli """ import click class CommandOrder(click.Group): """Modification of click Group to conserve command order""" def list_commands(self, ctx: click.Context) -> list[str]: """list all sub-commands in the order they were supplied Args: ctx (click.Context): Click co...
810c33f286f02ac9153851badab618b5c34ad7c5871930ec9d7bf5d1035ab07b
Python
436
19
import re from pathlib import Path from typing import Union def get_directory( transformed_data_loc: Path, experiment_id: Union[int, str], machine_name: str, region_id: int, ) -> Path: if isinstance(experiment_id, str): experiment_id = int(re.sub("\D", "", experiment_id)) return ( ...
c8e4984eba9c3758564ddb5fcfe7207287e43e95d9a7aad82af20848adda63e9
Python
436
20
import re import os import sys folder = sys.argv[1] infile = open(folder + "/progress.txt", "r") data = infile.readlines() infile.close() finalline = "" for line in data: if line[-1] == "\n": line = line[:-1] if line != "": finalline = line linelist = finalline.split(",") assert(linelist[-1] ...
182673dc8af981c8f1c2c73792df89d121207155a23d3531dc7821589a01a69c
Python
437
18
import sys log_file_path = sys.argv[1] with open(log_file_path) as f: lines = f.readlines() for line in lines: # Ignore errors from CPU instruction set, symbol existing testing, # or compilation error formatting ignored_keywords = [ "src.c", "CheckSymbolExists.c", "test_compi...
201a40a3a3194d54c8435b401b8c221da5f5bb7e6e802225bd64bbe81dce670d
Python
437
14
from setuptools import setup, Extension from Cython.Build import cythonize import numpy as np extensions = [ Extension("distance3d", ["distance3d.pyx"], include_dirs=[np.get_include()]), Extension("bikernel", ["bikernel.pyx"], include_dirs=[np.get_include()]) ] setup( name="cython_geometry_kernels", e...
4519633c80e2ea30cd85475b8ca31cef932cb7ec26f7697e1fa6f963e9420890
Python
437
13
import pandas as pd def test_repr(): df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")}) expected = " A\n0 True\n1 False\n2 <NA>" assert repr(df) == expected expected = "0 True\n1 False\n2 <NA>\nName: A, dtype: boolean" assert repr(df.A) == expected ...
a5ace073960c5cf04069f14e84bddac9045bdf9ba7a9e9f0ec81dde475f22bb4
Python
437
14
"""Contains custom error classes""" from .data import DBAlreadyOpenError, DBClosedError, TableNotFoundError from .genbank import InvalidGBKError, InvalidGBKRegionChildError from .input_args import InvalidArgumentError, ArgumentParseError __all__ = [ "DBAlreadyOpenError", "DBClosedError", "TableNotFoundErro...
0b855df5470b690741590794352b1b37063a6508335d9eadbe5be70d6047fc60
Python
439
16
import torch import torch.nn as nn class HamiltonianLoss(nn.Module): def __init__(self) -> None: super(HamiltonianLoss, self).__init__() def forward(self, pred, target, mask): diff = pred - target mse = torch.mean(diff**2) mae = torch.mean(torch.abs(diff)) mse *= pred....
1b8ab186d032c5a80c099ab0838e5ca12f336efccc4fb54aadf0e93527f1ffaf
Python
439
22
__version__ = '4.1' ## to custom map object from molmap.agg import AggMolMap ## cpds feature map from molmap.map import MolMap from molmap.cpd import GlobCpdMolMap ## pdb feature map from molmap.pdb import PDB2Fmap, PDB2Img ## aa sequence feature map from molmap.seq import LocalAASeqMolMap from molmap.seq import Gl...
a8d582232be8725b30e5a39000094653910213de4e8368337fdd18c80e9bb346
Python
439
22
from typing import Optional import numpy as np from pydantic import BaseModel class LazyTiltSeriesData(BaseModel): name: str data: np.ndarray last_loaded_index: Optional[int] n_images_loaded: int = 0 class Config: arbitrary_types_allowed = True @property def n_images(self): ...
d88be7f80a52ec2fb0de5a7e29647f51205b1ffccc3dad55850b6189d0b17ba0
Python
439
18
import pytest import yaml def pytest_addoption(parser): parser.addoption( "--no-cleanup", action="store_true", default=False, help="Skip cleanup of DESIGNER's scratch (processing) directory and TMI's params directory.", ) @pytest.fixture(scope="session") def tolerance_config()...
9cf384e17e035d3852dc0810f3b22038099cd5a29192bb81ab500c1af2ae6954
Python
440
23
''' Created on 2016.5.13 @author: liangqian ''' from modal.lifneuron import LIFNeuron from modal.cluster import Cluster from modal.synapse import Synapse c = Cluster('LIF') c.createClusterNetwork() c.setInhibitoryNeurons(0.2) for i in range(0,c.neunum): for j in range(0,c.neunum): if(i != j): ...
196a172ad5708d092a50d6b7ee1b7549d26375d16d358cfbee70e8ece2e5dd5e
Python
441
19
#!/usr/bin/env python from parser import * # bytes_to_int(fh_in.read(8), signed=True) # int_to_bytes with open("GSM6379997_203927450093_R01C01_Grn.idat", "rb") as fh_1: with open("test.idat", "rb") as fh_2: for i in range(13676211): c1 = fh_1.read(1) c2 = fh_2.r...
30fef4a94c20b214ed4e12996990e9effe94f99eba34857581e5616ac1977a34
Python
441
17
import numpy as np from numpy.testing import assert_equal class TestDot: def test_matscalar(self): b1 = np.matrix(np.ones((3, 3), dtype=complex)) assert_equal(b1*1.0, b1) def test_diagonal(): b1 = np.matrix([[1,2],[3,4]]) diag_b1 = np.matrix([[1, 4]]) array_b1 = np.array([1, 4]) ...
9070e590afdb7ae1d778c3dce63b5adb0825f2074a7945ade5fda74c356bbedf
Python
441
17
#!/usr/bin/env python """ requests.certs ~~~~~~~~~~~~~~ This module returns the preferred default CA certificate bundle. There is only one — the one from the certifi package. If you are packaging Requests, e.g., for a Linux distribution or a managed environment, you can change the definition of where() to return a s...