sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
5c070ac46c156d2363c54b94a734a6a53bda9d61db4053f89826c45f774ef8e1
Python
945
20
import visualkeras from utils.constants import * from utils.regressor_tools import * from utils.experiments_tools import * import numpy as np from PIL import ImageFont font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 32) if __name__ == '__main__': input_dataset = read_csv...
67b1226e3be9428e12b07bd1def449c81da800616d78481b1e432eb3ae1e4e55
Python
946
28
import torch import clip from PIL import Image import requests # Load the CLIP model device = "cuda" if torch.cuda.is_available() else "cpu" model, preprocess = clip.load("ViT-B/32", device=device) # Prepare the image image_url = "https://example.com/image.jpg" # Replace with your image URL image_response...
d286e4a47e0529fa6a387ec5a390923bd5a5084d800769fd9a9880bd8484b8e3
Python
946
36
# -*- coding: utf-8 -*- import matplotlib matplotlib.use('Agg') from mpi4py import MPI from mozaik.storage.datastore import Hdf5DataStore, PickledDataStore from parameters import ParameterSet from analysis_and_visualization import perform_analysis_and_visualization_stc from model import SelfSustainedPushPull from expe...
77dc3cdea516d4f77f2f18de95e3f74726c368eae4a96d94b3b71c2219395a36
Python
947
30
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. UMA Nitro: a standalone UMA-small model for energy, force, and stress inference. Select it with ``inference_settings="nitro"``. The model is b...
2547ea5369f7b52287c966e3497ae9756fe3afe61b33102f0212e53dadbf471b
Python
948
32
# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends class AudioDiffusionPipeline(metaclass=DummyObject): _backends = ["torch", "librosa"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch", "librosa"]) ...
717021fb15fdfb7e80a02d8783ce270e6047803807f3ed90b7419618c99d8f4c
Python
948
34
import os from deepface.commons.logger import Logger logger = Logger() def initialize_folder() -> None: """ Initialize the folder for storing model weights. Raises: OSError: if the folder cannot be created. """ home = get_deepface_home() deepface_home_path = os.path.join(home, ".deep...
b40254a5574caa2735c0df6462aeaee517d30e333a74144cc2ecd46979d40105
Python
948
27
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
c167f4e3d2aaa366f10aee89d49b58f657b2548df9c42c76f879fee7cf3ab8bf
Python
950
27
class NormalizedRewardFilter(object): def __init__(self, tau=1e-3, scale=1, eps=1e-1): self.tau = tau self.scale = scale self.average_reward = 0 self.average_reward_squared = 0 self.eps = eps def __call__(self, reward): self.average_reward *= 1 - self.tau ...
0d3bbc93fe8224987e5335be2a2cdf03a057a08c734e24f02fbffac0ae0d08fa
Python
951
29
model = dict( type='BaseEditModel', data_preprocessor=dict( type='EditDataPreprocessor', mean=[0.0, 0.0, 0.0], std=[255.0, 255.0, 255.0], bgr_to_rgb=True, pad_size_divisor=32, gt_name='img'), generator=dict( type='UNetGenerator', model=dict( ...
fee42e47d8a662133807b31caef51b33e422dd0c1a0c72db671004bfa1932a21
Python
951
35
import pytest import torch import pfrl from pfrl.testing import torch_assert_allclose @pytest.mark.parametrize("n", [1, 5]) class TestConjugateGradient: @pytest.fixture(autouse=True) def setUp(self, n): self.n = n def _test(self, device): # A must be symmetric and positive-definite ...
b4100017da96b2f77f6bb87ce2b3c54e2be0779b2f507fea107d62cf8d1c60eb
Python
952
29
import os import signal import sys from pybind.controller.controller_instance import ControllerInstance from pybind.controller.demo import utils from projectmetis.python.logging.metis_logger import MetisLogger if __name__ == "__main__": MetisLogger.info('\n'.join(os.environ['PYTHONPATH'].split(':'))) MetisLog...
7fa074cf9f46bd5c629832f339c31cfd6db1667f6cf374a4769c1d79b6c4cc3d
Python
954
30
import torch from ..utils import common_functions as c_f from ..losses.large_margin_softmax_loss import LargeMarginSoftmaxLoss class CosFaceLoss(LargeMarginSoftmaxLoss): """ Implementation of https://arxiv.org/pdf/1801.07698.pdf """ def __init__(self, *args, margin=0.35, scale=64, **kwargs): ...
8d78825a34f7150484174e33b5fc15e6e8317c798dda2fdaf0a7a3ad31230ebe
Python
955
35
import logging from dataclasses import dataclass, field from typing import Dict, Optional def str_to_logger_enum(s): if s == "notset": return logging.NOTSET if s == "debug": return logging.DEBUG if s == "info": return logging.INFO if s == "warning": return logging.WARNI...
b2b49824cabe8dec8362979b104594f9a22087a9837ae274ea11b012480f10ef
Python
955
20
''' ******************************************* LISA: Landscape In-Silico deletion Analysis ******************************************* LISA is a statistical test that finds the most influential Transcription Factors related to a set of genes. We leverage integrative modeling of a comprehensive dataset of 100s of chr...
eb4b6cbc400c9ceb73cd601f3f0864165bd1734b2ac041cd7eeac41a7c821293
Python
955
32
# torch import torch import torch.nn.functional as F import torch.nn as nn # transformer for reggan class Transformer_2D(nn.Module): def __init__(self): super(Transformer_2D, self).__init__() # @staticmethod def forward(self, src, flow): b = flow.shape[0] h = flow.shape[2] ...
69556a29c56b475a691e6d4dc9a4748941729082a77578937e859c8d777f8b3d
Python
956
40
import numpy as np import networkx as nx import os.path import matplotlib.pyplot as plt from scipy import signal import time import math import gc gc.collect() import warnings warnings.filterwarnings('ignore') import os import pysindy as ps os.system('cls' if os.name == 'nt' else 'clear') plt.rc('font',si...
2da3fee455410573ca56f4aa0e86fb0141465eb4f9b4ceece5e4cc2d056d73ba
Python
957
34
#!/usr/bin/env python3 """This script checks whether header file inclusion for ray core C++ code is correct. """ import re import sys def check_ray_core_inclusion(fname: str): """Check whether ray core file has incorrect inclusion `src/ray/...`, which doesn't build on windows env. If invalid inclusion i...
d4b21d21ec528c5bc9467697f71a3d046551331dc2898b77f83b0322a1c23092
Python
957
34
import unittest import torch from rising.transforms.format import MapToSeq, RenameKeys, SeqToMap class TestFormat(unittest.TestCase): def setUp(self) -> None: torch.manual_seed(0) def test_map_to_seq(self): trafo = MapToSeq(("data", "seg", "label")) out = trafo(**{"data": 0, "seg": ...
628c4113bd4a546a1034863075b9e48a19de97569d07f6d8c3df9aad4f60bc64
Python
959
28
from typing import List, Optional from ci.ray_ci.tester_container import TesterContainer from ci.ray_ci.windows_container import WindowsContainer class WindowsTesterContainer(TesterContainer, WindowsContainer): def __init__( self, docker_tag: str, shard_count: int = 1, test_envs: ...
e49d112887c64fa0fc8662ff59f3aab002f7d9f6b6d32ac5c2369e1cf789bb74
Python
959
30
from typing import Any, Dict, List from ipywidgets import GridspecLayout, VBox, widgets from data_profiling.report.formatters import fmt_color from data_profiling.report.presentation.core.table import Table def get_table(items: List[Dict[str, Any]]) -> GridspecLayout: table = GridspecLayout(len(items), 2) f...
60c72410c07e7cba3a611525fbee5e8c6a8c87767cb654087e09a3621634e318
Python
960
22
import numpy as np from siapy.entities import SpectralImage from siapy.transformations.image import area_normalization # Create a sample spectral image rng = np.random.default_rng(seed=42) image_array = rng.random((100, 100, 10)) image = SpectralImage.from_numpy(image_array) # Apply area normalization to standardize...
28b8b49a2ecff08884bdc781c24f455148848d2c87f1159131b09ee37c48c62f
Python
961
26
#* # @file Different utility functions # Copyright (c) Zhewei Yao, Amir Gholami # All rights reserved. # This file is part of PyHessian library. # # PyHessian is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, ei...
2f82dbc638bda7cfde207107bb8183537fbaebd428c0d9ba2f720f951a53173e
Python
962
30
"""Test for the duplicates functionality""" import numpy as np import pandas as pd import pytest from data_profiling.model.duplicates import get_duplicates @pytest.fixture(scope="module") def test_data(): np.random.seed(5) df = pd.DataFrame( np.random.randint(1, 100, (100, 5)), c...
13104f08b1c56dcf545fdc596168724eca07259b6b69d3f280798e365a80fac1
Python
963
26
import tensorflow as tf from projectmetis.python.models.model_def import ModelDef class MnistModel(ModelDef): def __init__(self, learning_rate=0.02): super(MnistModel, self).__init__() self.learning_rate = learning_rate def get_model(self): """Prepare a simple dense model.""" ...
c8ae71e109a6e3b6065fe74173ac2d7a27aac6eb8ceab5f7699c2c11481d4eba
Python
963
31
#!/usr/bin/env python """Each sample contains multiple masks. This script combines theese masks into one image, thus creating one mask for each sample. """ from multiprocessing import Pool from pathlib import Path from contextlib import ExitStack from tqdm import tqdm from PIL import Image def combine_masks(mask_roo...
d0b10e71f6575c8c1c398d6bb7a49a975c24fc9cfc4e5a9c12c3ba2d25ba5fff
Python
963
31
from data_profiling.config import Settings from data_profiling.report.presentation.frequency_table_utils import ( extreme_obs_table, freq_table, ) def render_common(config: Settings, summary: dict) -> dict: n_extreme_obs = config.n_extreme_obs n_freq_table_max = config.n_freq_table_max template_v...
31687b831d74dcf01170c6a9794be82e05902696185d7f2ae661e594246e6b1e
Python
964
36
# __serve_example_begin__ import time from ray import serve @serve.deployment class Preprocessor: def __call__(self, input_data: str) -> str: # Simulate preprocessing work time.sleep(0.05) return f"preprocessed_{input_data}" @serve.deployment class Model: def __call__(self, preproces...
408789caa29be33d6d8f9fbf6433fc0a66c96b8fa941ac340b0d6816beb0c9e6
Python
964
30
import torch class Branched(torch.nn.Module): """Module that calls forward functions of child modules in parallel. When the `forward` method of this module is called, all the arguments are forwarded to each child module's `forward` method. The returned values from the child modules are returned as a...
78971ab55e3aefaee3eddc68961bb8370e101a0e5a3e773fa0c4e447ddc9ab3f
Python
964
28
from flyvis.utils.cache_utils import context_aware_cache, make_hashable class Responses: def __init__(self, names): self.names = names self.cache = {} @context_aware_cache(context=lambda self: self.names) def responses(self, *args): return list(self.names) def test_context_aware...
097c42a90d15e5c764a8b4368be02bceac8b30f5189317c3c651d5a37fc3a233
Python
966
19
''' ******************************************* LISA: Landscape In-Silico deletion Analysis ******************************************* LISA is a statistical test that finds the most influential Transcription Factors related to a set of genes. We leverage integrative modeling of a comprehensive dataset of 100s of chr...
63484980f4644759ea493ddb45b8323edf10f76de11d632f0824d2bf5fa71238
Python
966
36
from typing import Tuple import pandas as pd from data_profiling.config import Settings from data_profiling.model.summary_algorithms import describe_generic @describe_generic.register def pandas_describe_generic( config: Settings, series: pd.Series, summary: dict ) -> Tuple[Settings, pd.Series, dict]: """De...
058523f960e7106131e85a1f003c3646b1eaf1a89443f658afeb9ea57ae4b85c
Python
967
41
import logging from datetime import datetime from agent.classifiers.ffnn_classifier import ffnn logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO) USE_GPU = False if __name__ == "__main__": starting_time = datetime.now() ffnn(for_task_label="fc", binary_classifier=True...
7d63d9d1a72d81b610f19eab1cb2dcea57966c23ea4473c74dd26d775e88dc4d
Python
967
35
from dataclasses import dataclass, field from typing import Any, Dict, Optional import numpy as np from .node import NIRNode @dataclass(eq=False) class SumPool2d(NIRNode): """Sum pooling layer in 2d.""" kernel_size: np.ndarray # (Height, Width) stride: np.ndarray # (Height, width) padding: np.nda...
fd5e3b60e65ff9b51d4912840f00e355f859a39f840d3da881622ab6e2b6996d
Python
967
43
# -*- coding: utf-8 -*- # """ std_melt.py Standardize a MELT record. """ from .standardize import VCFStandardizer @VCFStandardizer.register('melt') class MeltStandardizer(VCFStandardizer): def standardize_info(self, std_rec, raw_rec): """ Standardize MELT record. 1) Rename all SVTYPE fi...
1cb6c52dbe2822d8dce71eca65817f727b51a26eb390cb9d22aa98d63d5c4a5c
Python
968
35
from typing import Any, Callable from data_profiling.config import Style from data_profiling.report.presentation.core.item_renderer import ItemRenderer from data_profiling.report.presentation.core.renderable import Renderable class Root(ItemRenderer): """ Wrapper for the report. """ def __init__( ...
320d84041473246a5e9cebf6df2bf3db6dde5ed269a16789a8d5f5cf04fa3145
Python
968
27
import numpy as np from scipy import sparse def IoU_2(GTMasks, Masks): '''Calculate the recall, precision, and F1 score of segmented neurons by comparing with ground truth. Inputs: GTMasks (sparse.csr_matrix): Ground truth masks. Masks (sparse.csr_matrix): Segmented masks. Outputs: ...
1d7da899778510ccd935a2fc10ae4145a1431cbbce3cb5ac016c6bd35dce766f
Python
969
30
import unittest import numpy as np import torch from rising.ops import np_one_hot, torch_one_hot class TestOneHot(unittest.TestCase): def test_torch_one_hot(self): target = torch.tensor([0, 1, 2]) target_onehot = torch_one_hot(target, 3) expected_onehot = torch.tensor([[1, 0, 0], [0, 1, ...
8c339354f5e8ebdbb70eaca207745cc3f24744bfa4c15fe21c139dadfc1a0504
Python
969
30
import ray from ray.util.dask import dataframe_optimize, ray_dask_get import dask import dask.dataframe as dd import numpy as np import pandas as pd # Start Ray. # Tip: If connecting to an existing cluster, use ray.init(address="auto"). ray.init() # Set the Dask DataFrame optimizer to # our custom optimization functi...
03731b7a0e6f95a43967d915187bdc85a341c770f55fc632a84fe94fdb5f70d6
Python
970
24
import os import glob import numpy as np import nibabel as nib import torch import subprocess import scipy.ndimage from nibabel.orientations import axcodes2ornt, ornt_transform, inv_ornt_aff def orientation(img): orig_ornt = nib.io_orientation(img.affine) targ_ornt = axcodes2ornt('RAS') transform = ornt_tr...
98d86009bfd434cba6ccfdbc8cb319aeba884d9779ae0ea5dbb0c336a463bdf6
Python
970
16
# Design sweep for recovery of the slow-term magnitude b (Case 1, model M2) import sys,json,os,time import case1 from case1 import * name=sys.argv[1]; R=int(sys.argv[2]); seed=int(sys.argv[3]) TS={"pub":[30.,90.,150.],"early":[5.,30.,90.,150.],"wide":[5.,150.,600.],"wide4":[5.,90.,300.,600.],"late":[30.,90.,150.,600.]}...
3b061b293c2960a62c9c60969352edfdec7b6babcd319af83681d95027a5a9cc
Python
972
36
import numpy as np import nir nir_model = nir.NIRGraph( nodes={ "in": nir.Input(input_type=np.array([1])), # dummy input, but needed for S2 "linear1": nir.Linear( weight=np.array([[1.0]]), ), "lif1": nir.LIF( tau=np.array([0.01]), r=np.array([1....
4bb2f2cbb8a6ca70516daab79508b06702f077395f30f6823456ae33394cdd6e
Python
972
45
"""Paths that are useful throughout the project.""" from pathlib import Path def get_project_root() -> Path: """Returns the path to the project root folder. Returns: The path to the project root folder. """ return Path(__file__).parent.parent.parent.parent def get_config(file_name: str) -> ...
f0f671d6a13440cc2d326d9867bef707b466b4a83393fc03f5b126b71d253c20
Python
972
43
# __numpy_troubleshooting_start__ import ray import numpy as np from ray.dag import InputNode @ray.remote class NumPyActor: def get_arr(self, _): numpy_arr = np.ones((5, 1024)) return numpy_arr actor = NumPyActor.remote() with InputNode() as inp: dag = actor.get_arr.bind(inp) cgraph = dag.ex...
55de296be7dd8ceda20da728f5679621c71c4a0a05f5e2e85ba82d4a002cb442
Python
974
34
from abc import ABC, abstractmethod from typing import TYPE_CHECKING from ray.util.annotations import DeveloperAPI if TYPE_CHECKING: from ray.data._internal.execution.interfaces.execution_options import ( ExecutionResources, ) @DeveloperAPI class ClusterAutoscaler(ABC): """Abstract interface for...
777f1a0bf3a6fac9387d4a8f5c33a25f810e7f29574b332117bfe035cea41791
Python
974
32
import subprocess import sys import pytest from siapy.core.configs import BASE_DIR EXAMPLES_DIR = BASE_DIR / "docs" / "examples" / "src" def get_example_files(): """Get all Python files from examples directory.""" return sorted(EXAMPLES_DIR.glob("*.py")) @pytest.mark.manual @pytest.mark.parametrize("exam...
cbdefe95538317bf597d5b1efa9959ea0da2e3dcaf73de03fea82620eb48cd9d
Python
974
26
import torch from torch import nn import torch.nn.functional as F class ReconstructionLoss(nn.Module): def __init__(self, lib_size=None, log_norm=False, **kwargs): super().__init__() self.reconstruction_loss = nn.MSELoss() self.lib_size = lib_size self.log_norm = log_norm se...
aafce69def2c2a37a12671abef9d97e166c3998e016905725f75aaad7641f12b
Python
975
40
# -*- coding: utf-8 -*- """ Created on Tue Jul 16 23:04:00 2019 @author: ju-bar Distribution functions This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ import numpy as np # %% def bivnorm(x_tuple, x0, y0, a, b, c): '''...
b15c54588366762294d5befa1a767e3ded019f796ac64c95b5635e2f02bafa8e
Python
975
37
"""Statistics of how spatial neighbours are arranged — ``ov.space.nb``. The graph and what lives on it. Build the graph once with :func:`~omicverse.space.spatial_neighbors`, then ask questions of it:: ov.space.spatial_neighbors(adata, n_neighs=6, coord_type='grid') ov.space.nb.enrichment(adata, 'cell_type') ...
3003a8b620eb5fbeecbe099053bba7cf20177ed124cdf004493d0ed6c4f1152c
Python
976
26
# -*- coding: utf-8 -*- """ scfea: single-cell Flux Estimation Analysis (vendored sub-package). This sub-package is vendored from the scFEA project: https://github.com/changwn/scFEA commit 4c1fb76d52f07bafad84ce7686ad7c3acfcf0126 Reference: Alghamdi N, Chang W, Dang P, Lu X, Wan C, Gampala S, Huang Z, Wan...
78e3ccaff07fd4f9d14e865ad1688aa0ce99abfcad5ac64d790d6546aebf6ee0
Python
976
25
import unittest from neuron_morphology.validation import validate_reconstruction class TestValidateReconstructionFunctions(unittest.TestCase): """ Tests the functions in validate_reconstruction.py """ def test_parser_with_one_swc(self): parser = validate_reconstruction.parse_arguments(['--swc', 'test...
c558b7a33f8cb54397b0a45d531b86c531fb9bebd8c7910369ee94a97e8a3f57
Python
976
31
from typing import Dict import numpy as np LEADS = [ 'I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', ] def process_ecg(ecg: Dict[str, np.ndarray], ecg_samples: int = 4096) -> np.ndarray: """ Prepares an ECG for use in a tensorflow model :param ecg: A dictionary mapping...
be0b2b245cf99297f866ebeb23beb10b354f4981ef124043b8ea4e886cf6ec69
Python
977
26
import tensorflow as tf from projectmetis.python.models.model_def import ModelDef class FashionMnistModel(ModelDef): def __init__(self, learning_rate=0.02): super(FashionMnistModel, self).__init__() self.learning_rate = learning_rate def get_model(self): """Prepare a simple dense mo...
19435e2f24a7649b2bd260b7eb15f3c84af33a83b6e6a2cda667f1f478fc297e
Python
978
25
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
294a92fc6d80361bd646451ddb2010ab9a956f973a5ff1adae5b24dbf61b8838
Python
978
55
# Ultralytics YOLO 🚀, GPL-3.0 license from collections import OrderedDict import numpy as np class TrackState: New = 0 Tracked = 1 Lost = 2 Removed = 3 class BaseTrack: _count = 0 track_id = 0 is_activated = False state = TrackState.New history = OrderedDict() features =...
5658904ad2340f9273459948c8f228801c3ab78068b4bdc1b4997193bf3f6d11
Python
978
31
# rag_logger.py import logging import sys from logging.handlers import RotatingFileHandler import os class RAGLogger: def __init__(self, name: str, log_file: str = 'rag_system.log'): self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(a...
2bc57dc5f28e72dfb4ed55cec88859f32fea22e156c4a15318b81ea62e529fe8
Python
979
46
import hamiltorch import torch import matplotlib.pyplot as plt def log_pdf(x): H = 0.5 * x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2 + x[0]**2*x[2]**2 return -H params_init = torch.zeros(4, requires_grad=True) num_samples = 25000 step_size = .3 num_steps_per_sample = 5 sampler = hamiltorch.Sampler.HMC_NUTS int...
38cec24bf465e2f269c101312bab4a53596733781d93a844301f05065cb457c9
Python
979
33
"""Main module of data-profiling. .. include:: ../../README.md """ # ignore numba warnings import warnings # isort:skip # noqa import importlib.util # isort:skip # noqa from data_profiling.compare_reports import compare # isort:skip # noqa from data_profiling.controller import pandas_decorator # isort:skip # noq...
ee67147f0bd8eba433116b7247fd4e3da267c3f94a0f59e4b9f094f565d4149c
Python
979
35
#!/bin/python #------------------- Description & Notes --------------------# #------------------- Dependencies ---------------------------# # Standard library imports from pathlib import Path # External imports import pytest # Internal imports from synsor import io from synsor import schema #------------------- C...
256836a85714b840242101c2d18be38398f2b9dc03291a31210594fa8ee4ec55
Python
980
36
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations from types import SimpleNamespace from fairchem.core.launchers import ray_on_slurm_launch def test_r...
cd6259fd3305311bee27582f6dd4a207ba0cd04090a372705c6b7c9f96d8d886
Python
981
24
from functools import partial from abberior import microscope EXC_ID = 5 STED_ID = 6 if isinstance(EXC_ID, (list, tuple)): ch1_p_ex = partial(microscope.set_power, laser_id=EXC_ID[0], channel_id=0) ch1_p_sted = partial(microscope.set_power, laser_id=STED_ID, channel_id=0) ch1_linestep = partial(microsco...
d199b61f881dede7527ffcd5506eae3667201465d2e906a230af3d69fb69b540
Python
981
37
import nibabel as nib import numpy as np import pandas as pd lookup_df = pd.read_table(snakemake.input.lookup_tsv, index_col="index") # get indices and names from lookup table indices = lookup_df.index.to_list() names = lookup_df.abbreviation.to_list() hemis = ["L", "R"] # collect output rows rows = [] for in_img, ...
ffda720f47846943aaa615a647280a2734323219bd8566a6b26f392d987c7aa6
Python
981
38
"""Deprecated plotting compatibility wrappers for ``omicverse.utils._venn``.""" from __future__ import annotations import importlib import warnings _REMOVAL_VERSION = "2.2" def _warn(old_name: str, new_name: str) -> None: warnings.warn( f"`ov.utils.{old_name}` is deprecated and will be removed in omicv...
e7278b81a3bd88a245e2728a3fa41229cfa566461dde22fa617cb9d2d84f9d51
Python
982
37
# This file is part of the INTREPPPID programme. # Copyright (c) 2023 Joseph Szymborski. # # This programme is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, version 3. # # This programme is distributed i...
9fc2dfd2ad314a5bdb3adff341a5993a3f5cf27365c1afdb325bf5fbfef5a096
Python
983
21
# ------------------------------------------------------------------------------------------------------------------------------------- # Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion): # --------------------------------------------------------------------------------...
a15b505ddb5c5d18af4e5c035d311b5b5222f864cc920ddd7ada74fae09370ad
Python
985
30
import torch.nn as nn class Merge(nn.Module): def __init__(self) -> None: """Module form for a merge operation. In the context of events/spikes, events/spikes from two different sources/rasters will be added. """ super().__init__() def forward(self, data1, data2): ...
7595887876f469df61b4026bc0124abd0f1c20d9ebde1c5fb6c4d8669736c67d
Python
988
34
import numpy as np import networkx as nx import os.path import matplotlib.pyplot as plt import time import math import gc gc.collect() import warnings warnings.filterwarnings('ignore') import os os.system('cls' if os.name == 'nt' else 'clear') plt.rc('font',size=15) UseDoubleWell=1 RCType=0# Different R...
9d60b5f2a9fde9f0b2c0de62cf77db3b64a64f46fa08ab8976bd1e902d04d56e
Python
988
30
import pytest from DECIMER import predict_SMILES @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_imagetosmiles(): img_path = "tests/caffeine.png" expected_result = "CN1C=NC2=C1C(=O)N(C)C(=O)N2C" actual_result = predict_SMILES(img_path) assert expected_result == actual_result @pyt...
c74c493a5ab5314a89cf5361a56e9c2cddc96f3a0b6675222e24179ab6047323
Python
988
43
r""" Visualization modules of SLAT """ from typing import Optional import matplotlib.pyplot as plt from matplotlib import colors from .multi_dataset import * def hist(data, bins: Optional[int]=100, cut: Optional[float]=0.9, cut_height: Optional[int]=200 )->None: r""" Histogram...
4ef51b1a67f4c337e5585d7bdbd63dd263d788c6dd0cb7ba6c9a01c284f7e739
Python
989
41
# -*- coding: utf-8 -*- """ Created on Mon Jan 11 10:04:00 2021 @author: ju-bar Correlation utilities This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ import numpy as np def corr_norm(a, b): """ Calculates the nor...
9f8c7e41b4b579e461a86852cec7fd91eb5e3dee8260ebda7c9e6b1ea0e1665a
Python
989
30
"""Supervisor that orchestrates research agents.""" from __future__ import annotations from typing import Iterable, List, Sequence from .agent import ResearchAgent, Finding class Supervisor: """Breaks briefs into subtopics and spawns agents to handle each.""" def __init__(self, vector_store, tools: Iterab...
93d593dfca7273b2b778a9c3971f7daaf48dbfaa24056d0941f2fee033d23ac3
Python
990
48
import jsonlines import json import sys def read_gold_data(path): fi = jsonlines.open(path, 'r') labels = {line['index']: line['label'] for line in fi} return labels def evaluation_metrics(gold, predictions): count = 0 for key, value in predictions.items(): try: gold_label = ...
4d7720c02539cf827d4ca402b9285fb3b0a898560e82a0eaa4eda71a26db0a3f
Python
992
33
import numpy as np import pytest from neuropower import BUM def test_fpLL(): np.random.seed(seed=100) testpeaks = np.vstack( (np.random.uniform(0, 1, 10), np.random.uniform(0, 0.2, 10)) ).flatten() x = np.sum(BUM._fpLL([0.5, 0.5], testpeaks)) assert np.around(x, decimals=2) == 9.57 @pyt...
c34fae20ed4da3d22082b0327883cc53efd70513901286762ccaf9cedab53e53
Python
992
31
from ipywidgets import widgets from data_profiling.report.presentation.core import Dropdown class WidgetDropdown(Dropdown): def render(self) -> widgets.VBox: dropdown = widgets.Dropdown( options=self.content["items"], description=self.content["name"] ) titles = [] item...
d7f5e6bcd4d83a85c6c2d9436776369a6329cb557e61c27e5a34c7ec9b18811d
Python
992
33
import sys from parameters import ParameterSet from mozaik.models import Model from mozaik.connectors.modular import ModularSamplingProbabilisticConnector from mozaik import load_component from mozaik.space import VisualRegion import mozaik class ModelMapDependentModularConnectorFunction(Model): required_paramete...
ea5dfdbf643d526b9686159e8020c0ecdf827fbb91cd6ac026a69f112323857e
Python
993
28
import numpy as np import os import pickle import matplotlib.pyplot as plt from imp import reload import defaultParams; reload(defaultParams); from defaultParams import * import searchParams; reload(searchParams); from searchParams import * from analysis import simdata filename = 'sim_res_Be1.00_Bi-3.00' dir_name = ...
b1b4b66ade90c4bbc7037dcd624a7ad267735f202aedd0b2cb0f292f71869d09
Python
994
37
# -*- coding: utf-8 -*- """ Project: CrowdingNumerosityGit Creator: Miao Create time: 2021-03-02 15:41 IDE: PyCharm Introduction: """ import pandas as pd def drop_df_nan_rows_according2cols(df: pd.DataFrame, cols: list) -> pd.DataFrame: df = df.dropna(subset = cols) return df def drop_df_rows_according2_on...
77ebbfa407458118ffdd57d1050b01d254274f28685cdbd9b7e25caf6540687e
Python
995
24
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup, find_packages print(find_packages('.')) setup( name="mdgru", version="0.2.20181002", description="Segmentation Suite for multi-dimensional gated recurrent units (MDGRU)", long_description="Details can be found in the Readme f...
d9e440aa7e4ba19b8c80b65becdfe64a18df9bb776e5e84076c7bb3936b5ea4f
Python
995
35
# __without_limit_start__ import ray # Assume this Ray node has 16 CPUs and 16G memory. ray.init() @ray.remote def process(file): # Actual work is reading the file and process the data. # Assume it needs to use 2G memory. pass NUM_FILES = 1000 result_refs = [] for i in range(NUM_FILES): # By defaul...
8296c1e145c4a92ffef0ee11f21af39f5232cd63a16bc5097cc236c39c472afa
Python
996
34
import ray from ray.util.dask import ray_dask_get, enable_dask_on_ray, disable_dask_on_ray import dask.array as da import dask.dataframe as dd import numpy as np import pandas as pd # Start Ray. # Tip: If connecting to an existing cluster, use ray.init(address="auto"). ray.init() d_arr = da.from_array(np.random.randi...
d03c7b705decb4147f83581b89f5ea786ed7279e72f13c0777cd5b9c1ea43508
Python
996
22
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
6fe73547756425300e11715d150a0814315fa4b1dd92a4c5add808427f1b5679
Python
997
44
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """RPU simulator bindings.""" # This import is required in order to load the `torch` shared libraries, which # the simulator shared library is linked against. ...
62412e2823a22ceb422bbb2198004d78e5a92b41c59977d59b44a30280d6dc2c
Python
998
26
import nibabel as nib import neuroboros as nb import numpy as np import os if __name__ == "__main__": for lr in "lr": for ico in [32, 64, 128]: nv = ico**2 * 10 + 2 den = str(round(nv / 1000)) + 'k' fn = f"../tpl-onavg_hemi-{lr.upper()}_den-{den}_desc-cortex_dparc.label...
14e7b68707ad8448b1c150ce9bd1837e7ed8ae331e291820e872282f7da6a7f2
Python
999
44
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import pandas as pd def identify_mosaics(metrics): metrics = metrics.loc[metrics.Median_Separation.astype( str) != 'coverage_failure'].copy() metrics.Median_Separation = metrics.Median_Separation.astype(float) q1 = metrics...
3c5883a2095caf32386c82a050e786bb8ad75cfd2dbc62e9c26b238ff8805295
Python
1,000
29
from pickle import dump from lgca import get_lgca import numpy as np lx = 250 ly = round(lx * 1.1547) # distance in y direction is smaller than in x direction ly += 1 if ly % 2 == 1 else 0 dims = lx, ly capacity = 50 tmax = 300 restchannels = 1 kappa_max = 4 kappa_std = 0.05 * kappa_max params = [{'r_d': 0.2, 'theta'...
142694b255c3b207ab112c27a4921d97eb672af4ae1e5a9e8bfe12461bb8e7cd
Python
1,002
33
import unittest from neuron_morphology.feature_extractor.data import Data, get_morphology from neuron_morphology.morphology_builder import MorphologyBuilder class TestData(unittest.TestCase): def setUp(self): self.morphology = ( MorphologyBuilder() .root() ...
57094a51688eb55dc1be4934ff55e2e5a9650b977a65e26422430bb4c88d3a6b
Python
1,003
29
import glob import logging import numpy as np import os import random import torch import torch.utils.data import deep_sdf.workspace as ws def get_instance_filenames(data_source, split): txtfiles = [] for dataset in split: for class_name in split[dataset]: for instance_name i...
67b3b93c2e46fb236b17c233a9792e71825c1762b51b9181f5aecbe58dc3008e
Python
1,003
22
from setuptools import setup import io setup(name='deltasplice', description='DeltaSplice: A neural network model to predict splice site usage and splicing-altering mutations', long_description=io.open('README.md', encoding='utf-8').read(), long_description_content_type='text/markdown', versio...
7271548fcfa465726ad30d3b887c8db7592d6923c7a783ed3a042d7eb8282c75
Python
1,003
42
# -*- coding: utf-8 -*- """ @author: wnchang """ import torch def pearsonr(x, y): """ Mimics `scipy.stats.pearsonr` Arguments --------- x : 1D torch.Tensor y : 1D torch.Tensor Returns ------- r_val : float pearsonr correlation coefficient between x and y Scipy d...
0b245d965ede80934c3cd28f75f91c444fc47797a0ea3d6a793f01450b5609de
Python
1,005
30
# Copyright 2021 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
3456d3b10606da28efa32b7bf5f44930f9b9b7b6352b6786ba85d14c88f86d88
Python
1,006
25
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
f996c98259cbf2c6d7c13b25236d585615ed27e535024befb577e816e11b5973
Python
1,006
38
from typing import List import pandas as pd from data_profiling.config import Settings from data_profiling.model.sample import Sample, get_sample @get_sample.register(Settings, pd.DataFrame) def pandas_get_sample(config: Settings, df: pd.DataFrame) -> List[Sample]: """Obtains a sample from head and tail of the ...
0024beeed266ee4a3cf4a1d34bcd78ea90b4618d1398a13ea5a9e6f3902217df
Python
1,007
29
from typing import List from lqit.edit.models.base_models import BaseGenerator from lqit.edit.structures import BatchPixelData from lqit.registry import MODELS from lqit.utils import ConfigType, OptConfigType, OptMultiConfig @MODELS.register_module() class UNetGenerator(BaseGenerator): def __init__(self, ...
354d0cb710f3e6ced1cbfd606eb3fc887f4e3435207c8ad57bda80478bc68ed1
Python
1,007
23
import argparse import pickle import lib.dataset_config_parser.dataset_config_parser as dcp from lib.data_utils.matched_cells_struct import OrderedMatchedCellsStruct if __name__ == '__main__': parser = argparse.ArgumentParser( 'Print out the available WN cell ids available for use in reconstruction (i.e....
b6ec95dafaa83af468f77bec3a538b0faba4ce449ed0bf0c4f1f6d4c16395f17
Python
1,007
36
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import pytest from ase import Atoms from fairchem.core.datasets._utils import rename_data_object_keys ...
3d10d7aa31141f86d05a9726033f7c95ff529a0f16ba895e8eaaf1f63cd146cf
Python
1,009
31
import sys sys.path.insert(1, '..') # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- ...
25889d7781f27b035d402c1ad4bb31ccf6f219a98e31b03c9e927d8f6b41b6e2
Python
1,010
34
import io import logging from typing import TYPE_CHECKING, Any if TYPE_CHECKING: pass import ray._private.utils import ray.cloudpickle as pickle import ray.exceptions from ray._private import ray_constants from ray.util import inspect_serializability logger = logging.getLogger(__name__) ALLOW_OUT_OF_BAND_OBJECT...
37681151cb0bfee021852aceba0b53e8996ee6ae16afe11da41eb3e9c3d8ddd2
Python
1,011
36
import pytest from flyvis.network import dynamics from flyvis.network.dynamics import NetworkDynamics, activation_fns from flyvis.utils.class_utils import forward_subclass @pytest.fixture( scope="module", params=[ "NetworkDynamics", *[sc.__name__ for sc in dynamics.NetworkDynamics.__subclasse...
70e8c64ba4cd5b791316c352bc382af9f12b2b0bc5d0cb117bdf2fc0ffc108c5
Python
1,011
18
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
9bf46689589f903248d4d9623d9566d333c64db6581241952e3c3e0c727d5b3b
Python
1,012
18
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
a7988246632ee2f1545df8af8df67a8fb6ef72c49cb78bea54d6e62b5aff6ad0
Python
1,014
18
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...