sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e6a373f437e66b84fe804e9acbc793b06a14f1ff54d098cd5751cfb9dd290604 | Python | 1,809 | 62 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... |
1da4d54a371fb68398d14310d08585ff4108d8e646fc90fd0f71cad0c29a2942 | Python | 1,810 | 50 | import argparse
from utils.run_class import *
from config_files.config_file_DenseAutoencoder import *
import tensorflow as tf
# Display the start time of the code execution
print("Start Time Code Exec: ", time.asctime(time.localtime(time.time())))
# Set up argument parser
parser = argparse.ArgumentParser()
parser.ad... |
2229ab4a9bcdcce1aa72cdc149be84416e727ab27b3b73af1f66625ce52f187b | Python | 1,810 | 64 | # Copyright 2023 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, ... |
8ec4e6049d38cc383f63af5e3885775aa4a2b814814da9316f3712cb29aa9960 | Python | 1,810 | 48 | ########################################################
######### Philipp R. Steen #########
######### Jungmann Lab #########
######### Max Planck Institute of Biochemistry #########
######### Ludwig Maximilian University #########
######### 2024 ... |
b9cd7cf57ae829fe75f3adcd26d764a7a303079ca9a108e14adb7591b134fb3a | Python | 1,810 | 50 | # -*- coding: utf-8 -*-
import nibabel
import numpy as np
import pytest
from nilearn.maskers import NiftiMasker
from fmralign._utils import _make_parcellation
from fmralign.tests.utils import random_niimg
def test_make_parcellation():
# make_parcellation is built on Nilearn which already
# has several test f... |
e11326a9d90204895ecd64b3eb863a5e9b466ebaab6dbed87b9bdc56112d27ac | Python | 1,810 | 61 | import gzip
import logging
import numpy as np
from Bio.PDB import PDBParser
from pokeformer.utils.pdb_utils import (calc_min_dist, get_com_coords,
get_pdb_path)
logger = logging.getLogger(__name__)
def get_ligand_data(pdbid, ksite_df, pdb_set_dir=None):
pdbid = pdbid.uppe... |
0345361229984b7183dbffa17de2b8926362f7181cb8d15cf5af8cf97b168fd7 | Python | 1,811 | 28 | # Hybrid model for Case 1: threat-pathway filter (b_th) alongside slow shifts in both drives (b_gen, b_c)
from emp import *
D=load_wt(); Y=counts(D.t_court.values,D.defbehav.values); N=len(D)
out={}
pCD,nCD=fit(D,Y,BASE+["b_gen","b_c"],"linear",starts=8)
pH,nH=fit(D,Y,BASE+["b_th","b_gen","b_c"],"linear",starts=8)
out[... |
05192f59328d128e661d1b4a9bdbac41481ae044c1edea9bd7643852193c8967 | Python | 1,811 | 54 | import logging
from datetime import datetime
from transformers import BertForSequenceClassification
from agent.classifiers.data.tr_lstm_dataset_mgmt import get_datasets, annotate_dataset
from agent.classifiers.tr_lstm_ensemble_classifier import tr_lstm
from agent.classifiers.tr_ensemble_triple_trainer import train_lo... |
79a91aad62fbe9b2d8e09f8cbcc4a8a6731e2e848e746f3f3de37ff5fb58b240 | Python | 1,811 | 60 | import errno
import datetime
import numpy as np
import os
import sys
# Lazy-imported on first use so geosketch can be imported without fbpca /
# sklearn.random_projection installed (only required for reduce_dimensionality).
# Default parameters.
DIMRED = 100
def log(string):
string = str(string)
sys.stdout.wr... |
038988b01371f7186bd0c74bbbf30cb413139d09a9593bf212488028dc95ed82 | Python | 1,812 | 54 | import os
import subprocess
import sys
from typing import List, Optional, Tuple
from ci.ray_ci.container import Container
WORKDIR = "C:\\rayci"
class WindowsContainer(Container):
def install_ray(
self, build_type: Optional[str] = None, mask: Optional[str] = None
) -> List[str]:
assert not bu... |
3e718de5d6b0a279c36762df8f2a5a53373026e55ed3ac6f8269c3d22c00e61d | Python | 1,812 | 57 | import sys
import unittest
import numpy as np
from neuron_morphology.transforms import geometry as geo
class TestCCW(unittest.TestCase):
def test_ccw_correct(self):
"""
line1 (0, 1) <- (1, 1)
line2 (0, 0) -> (1, 0)
"""
line1 = [(1, 1), (0, 1)]
line2 = [(0,... |
b24fdcc305e4eba35c6ad6e8bc5b7bbee1ef97619d03c417e361e20cbbfbe7f4 | Python | 1,812 | 41 | import os
import glob
import scipy.optimize
import numpy as np
import nibabel as nib
from utils_mirror import orientation, transform, cost_fun
def rotation(save_path, initial_path, alpha):
merged_path = sorted(glob.glob(os.path.join(initial_path, '*')))
for idx, path in enumerate(merged_path):
subject ... |
e27c7b41a2d2f1c8e77d0032f9e79f2a6cd4b9faa762b71bb9d4678cfc3432c6 | Python | 1,812 | 35 | """Repeated sparse embedding indices must be summed before Adam squares them."""
import sys
from pathlib import Path
import unittest
import numpy as np
import tensorflow as tf
import keras
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'train_RNN'))
from optimizers import DeduplicatingAdam
class AdamCom... |
223374feffd158602fcda367a2de41f9551424487f5dbea68dc1f95aa03989e5 | Python | 1,814 | 52 | """Upsample echos."""
import os
import subprocess
import numpy as np
import nibabel as nb
import glob
# =============================================================================
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
# Set subs to work on
SUBS = ['sub-07']
# ===================... |
0370beec58682503623b4d0f401c1add540395947bd74c8e58a76428c8ebbeeb | Python | 1,815 | 73 | import json,sys,csv
def parseTMscore(filename):
with open(filename, 'r', encoding='UTF-8') as file:
tmcount=-1
while (line := file.readline()):
line = line.rstrip()
#print(line)
if "TM-score" in line:
tmcount +=1
if tmcount %3 == 0:
tokenlist = line.split("=")
tokenlist2 = tokenli... |
1a9beac90ef21a9a7c4329202ca17d3338e5273521300d0e32820a545900461b | Python | 1,815 | 63 | import json
from collections import OrderedDict
class Report(object):
def __init__(self):
self.file_record = OrderedDict()
self.stat_file_record = dict()
def add_swc_results(self, swc_file, results):
record = OrderedDict()
record["file_name"] = swc_file
record["resul... |
898ae74cb440dfcfb411be3869ff95952e61c28640444ec2d6f48a8b8607b0d4 | Python | 1,815 | 93 | from typing import Any, Dict
from .conv import Conv1d, Conv2d
from .delay import Delay
from .flatten import Flatten
from .graph import Input, NIRGraph, Output
from .linear import Affine, Linear, Scale
from .neuron import IF, LI, LIF, CubaLIF, I
from .pooling import AvgPool2d, SumPool2d
from .surrogate_gradient import ... |
4554db5b6005b178c2cfc852c6fd2db92b21be437f3a792e7da0f3ea938a82a1 | Python | 1,816 | 42 | """Real datasets for the unified cell-cell communication tutorial (``ov.single.run_ccc``).
Assets live in the ``omicverse-data`` GitHub release ``ccc-v1`` and are cached
under ``dir`` on first use.
| Loader | Returns | Modality | Source |
|---|---|---|---|
| :func:`slidetags_mouse_brain` | AnnData (nuclei x genes) | ... |
dd589d6f1a71b29ce9aa3c10f764b6c02b78f96b4d3c5da0d2324fcead67f893 | Python | 1,816 | 48 | # -*- coding: utf-8 -*-
# @Time :2024/6/6 10:58
# @Author :MENGLong Li
# @File :ReadOdbFile.py
# @Software:PyCharm
import numpy as np
from abaqus import *
from abaqusConstants import *
import os
class ReadOdbFile:
def __init__(self, num_group, num_index, path):
self.num_group = num_group
s... |
ece79e8a04fd7178d2f35016560225742c3bb6b03c9a1c27d73c38c3ef5df7b3 | Python | 1,816 | 61 | import sys
import os
import argparse
import numpy as np
import vamb
parser = argparse.ArgumentParser(
description="""Command-line bin abundance estimator.
Print the median RPKM abundance for each bin in each sample to STDOUT.
Will read the RPKM file into memory - beware.""",
formatter_class=argparse.RawDescrip... |
04200825536869ab5571893c604d74ae96e23d360f3f4a2e8f026a25a8da38ad | Python | 1,817 | 42 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import nutil_scripts.create_nut_file_functions as nff
import pandas as pd
import os
metadata = r"Z:\NESYS_Lab\PostDoc_project_Bjerke\Manuscripts\WHSv4_Basal ganglia\04_Material\Pax_colors.xlsx"
metadata_df = pd.read_excel(metadata)
regi... |
1780cd6f2e1669018d8d2d138790d8214820b2affa7d33c7ae106eec177b23b6 | Python | 1,817 | 57 | import pytest, torch
import ecg_augmentations as ea
def test_generator_reproducible(transform, ecg):
y1 = transform(ecg, generator=torch.Generator().manual_seed(1))
y2 = transform(ecg, generator=torch.Generator().manual_seed(1))
assert torch.equal(y1, y2)
def test_global_seed_reproducible(transform, ec... |
7217fa07c2da8ac011248c07a1f2c7f5cfc8c82db8ff172391575f7ffe212f42 | Python | 1,817 | 48 | import tweepy
import time
import datetime
import json
import logging
from agent.data.entities.config import ROOT_LOGGER_ID
from agent.keys.twitter_keys import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
from agent.nlp.keyword_extractor import get_key_terms
from agent.data.entities.tweet import exi... |
b47fa144976b1213f3007e85470e57a47a6737477fcf2e32bb89c3e14fb9e2af | Python | 1,817 | 69 | # __example_code_start__
import torch
from PIL import Image
import numpy as np
from io import BytesIO
from fastapi.responses import Response
from fastapi import FastAPI
from ray import serve
from ray.serve.handle import DeploymentHandle
app = FastAPI()
@serve.deployment(num_replicas=1)
@serve.ingress(app)
class AP... |
0d3338b9bb4707c3b3d99c343f1e96636ed189ebf2f8f1d9e057f25f72a0c72a | Python | 1,818 | 46 |
from keras.models import Model
from keras.applications.resnet import ResNet50
from keras.layers import GlobalAvgPool2D, Flatten, Dense, LeakyReLU, Dropout
from keras.optimizers import Adam
from keras.losses import mse
class customized_renet_model:
def __init__(self, input_shape=(512, 512, 3), loss=mse, ... |
28186d4dcd8beab719273bbe81d60c0479dd474a17c8a28a4e06b06eeebfc247 | Python | 1,818 | 65 | """
Normalization for the data.
"""
import numpy as np
import copy
def Z_score_normalization(sequence_data, M):
"""
(value - mean) / standard deviation
:param sequence_data: key: PATNO, value: data matrix
:return: normalized_sequence_data
"""
patients = sequence_data.keys()
normalized... |
38be4266a4335014fcf2a1f9e978b4ed82cd98cfe0416dc0f3d1b60c9f711c4f | Python | 1,818 | 53 | """
This file serves as a documentation example and CI test for YAML config deployment.
Structure:
1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.
2. Load YAML config and convert to Python using build_openai_app
3. Test validation (deployment status polling ... |
5dc8c1983f9a804c82d759485d761bbe7eb86e81aedd2e1ae90f8f1b65b80b4a | Python | 1,818 | 44 | ####################################################################################################
# Copyright (c) 2020 - 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... |
6a67c08d5da53203a2ae4b3e0951e900b7761500241fe70efcbc5b0b2ba6e789 | Python | 1,818 | 55 | from __future__ import annotations
"""
Config validator for the OmicVerse Skill Seeker unified build flow.
Supports a simplified unified format like:
{
"name": "omicverse",
"description": "OmicVerse documentation + GitHub",
"sources": [
{"type": "documentation", "base_url": "https://omicverse.readthedocs.io... |
6b50db67fcd6e4e7a4f1313b46ffedff94111dfc804198a040a3ee9a8738b5e6 | Python | 1,818 | 60 | import tempfile
import py.path # type: ignore[import]
import pytest
from stl import stl
def _test_conversion(from_, to, mode, speedups):
# For some reason the test fails when using pathlib instead of py.path
from_ = py.path.local(from_)
to = py.path.local(to)
for name in from_.listdir():
s... |
196966a039170dc136d3ac046dc0701e4e255c7f7f71e047f3af3b757e32854e | Python | 1,821 | 62 | # -*- 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.
#... |
96074dee552bb0316beaefbb8d20d7674ad9c8b55c02c15ae013f00a3f723790 | Python | 1,822 | 45 | import torch.nn as nn
class FFNN(nn.Module):
"""
A feed forward neural network with just one hidden layer.
This network is used as the learning network in the Slowly Changing Regression problem
"""
def __init__(self, input_size, num_features=5, num_outputs=1, hidden_activation='relu'):
sup... |
daab7be8b8f019e701c8c14137654ce5622f4558de2d32e716dff440d4ab068e | Python | 1,822 | 47 | import numpy as np
from siapy.entities import Pixels, SpectralImage
from siapy.transformations import corregistrator
# Assume we have the transformation matrix from the previous example
transformation_matrix = np.array(
[
[9.53012482e-01, 1.36821892e-03, -1.33929429e00],
[6.24099856e-04, 9.6841094... |
411774f0e53bdec578e807c7e3440b38fd0642455e3d5d3b2f8e7bd766703b28 | Python | 1,823 | 45 | ####################################################################################################
# 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... |
4d6cfd5c826d2d6d3269ac1ffa1322d5ebd20246298c3c1577e3d3b879aabec2 | Python | 1,823 | 30 | from exputils.gui.jupyter.experiment_data_loader_widget import ExperimentDataLoaderWidget
from exputils.gui.jupyter.multi_selection_widget import MultiSelectionWidget
from exputils.gui.jupyter.experiment_ids_selection_widget import ExperimentIDsSelectionWidget
from exputils.gui.jupyter.repetition_ids_selection_widget i... |
72d1efbe0950f70e89a0de3610cb20f34408b6ef3b0883859b97e77c9d518f36 | Python | 1,823 | 56 | import argparse
import h5py
import numpy as np
import pandas as pd
import smart_open
leads = [
'I', 'II', 'III', 'aVR', 'aVL', 'aVF',
'V1', 'V2', 'V3', 'V4', 'V5', 'V6',
]
ECG_LENGTH = 4096
ECG_SHAPE = (ECG_LENGTH, 12)
ECG_HD5_PATH = 'ukb_ecg_rest'
def ecg_as_tensor(ecg_file):
with smart_open.open(ecg_f... |
7809601f9897cd5e1724f3d6891e5141818838bca520a48e27fd9ebfce4585fa | Python | 1,823 | 56 | import argparse
import h5py
import numpy as np
import pandas as pd
import smart_open
leads = [
'I', 'II', 'III', 'aVR', 'aVL', 'aVF',
'V1', 'V2', 'V3', 'V4', 'V5', 'V6',
]
ECG_LENGTH = 2500
ECG_SHAPE = (ECG_LENGTH, 12)
ECG_HD5_PATH = 'ukb_ecg_rest'
def ecg_as_tensor(ecg_file):
with smart_open.open(ecg_f... |
83ff0e8ec28a2a316e476846867d1f035bd26b618bbed6658c3984fbfbfe3c43 | Python | 1,824 | 62 | from typing import Union
import torch
from torch.distributions import Distribution as TorchDistribution
from rising.random.abstract import AbstractParameter
__all__ = ["ContinuousParameter", "NormalParameter", "UniformParameter"]
class ContinuousParameter(AbstractParameter):
"""Class to perform parameter sampl... |
ef988b321a89ca822998fa3045fb61abb97907d785f2d6363b5d770867eea190 | Python | 1,824 | 47 | """Ordered, bounded schema discovery shared by file datasources."""
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, List
import pyarrow as pa
from ray.data._internal.util import unify_schemas_with_validation
# Bound submitted reads, not just executing threads, for full inference.
_SCH... |
253a57f811e7f2224592a7ef0f0890b393c45ae6ba1745134bfa7faf73fd1ec4 | Python | 1,825 | 75 |
from datetime import datetime
import copy
import numpy as np
import torch
import torch.cuda
from aptnn.aptnn import APTNN
def _count_generator(reader):
b = reader(1024*1024)
while b:
yield b
b = reader(1024*1024)
def linecount(fn):
with open(fn, 'rb') as fp:
c_generator = _count... |
048adb94a27ce8991a5c3dc04436c4efddb420a5ab7410a7ebfc9b7a0027aa7d | Python | 1,826 | 51 | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = []
test_requirements = []
setup(
author="Brian Clarke",
author_email="brian.clarke@dkfz.de",
python_requires=">=3.8", # TODO: ... |
6bcd1c5a72634c214ad0a0ea6f93b6bf17154d6f7216efc38eec8d9b6671b48b | Python | 1,826 | 50 | """
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 numpy as np
import pandas as pd
def get_normalized_facet_fracs(comp_df: pd.DataFrame, descripto... |
97ec43fb0e2cf97e051f688f3d4ce2136ed17c2bc84eeb5495955486ed5734cf | Python | 1,826 | 57 | import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import utils
if __name__ == "__main__":
paramfilename = "apps/reprlearn/reprlearn.par"
param = utils.parseparam(paramfilename)
storedir = param["storedir"]
# Load connection data
cij = np.fromfile(f"{st... |
9e5f6d87487c333e0b70cd1215e40789b764460da46b0b448d6c16b16cdb7a42 | Python | 1,826 | 46 | #Imports relevant modules
import os
import csv
#Sets the pipeline. This will need to be updated manually.
pipeline = '0'
#Defines the directory containing fMRIPrep pipeline output.
pipeline_dir = '/<directory root>/FEAT/Pipeline_{}'.format(pipeline) #Full path removed for purpose of public sharing.
#Creates a path f... |
c76b962355e85db83d89cea67de93c84b20b3b88165d843582efc79ce32205a1 | Python | 1,826 | 55 | # logger_setup.py
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Optional
def setup_logger(
name: Optional[str] = None,
log_file: str = "streamlit_app.log",
level: int = logging.INFO,
max_bytes: int = 10 * 1024 * 1024,
backup_count: int =... |
930493e482c61aa661d6f947cbe4375a455ff58a29118d995de23b3643875e53 | Python | 1,827 | 66 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pandas as pd
from behaviopy.plotting import qualitative_times
from behaviopy.utils import full_subsets
from os import path
import matplotlib.pyplot as plt
data_dir = path.abspath(path.expanduser('~/ni_data/ofM... |
d921c608c8f90c53486e782242d3995c78991d34254f3b1be4ae89441f62adef | Python | 1,828 | 46 |
import logging
from gym_sted.envs.sted_env import STEDEnv, STEDEnvWithoutVision, STEDEnvWithDelayedReward
from gym_sted.envs.ranking_sted_env import (
rankSTEDSingleObjectiveEnv,
rankSTEDMultiObjectivesEnv,
rankSTEDMultiObjectivesWithArticulationEnv,
rankSTEDMultiObjectivesWithDelayedRewardEnv,
)
from... |
06ad23957cd7b0296e6c70ea62c95b7f005a10846d7d2df9e4a70bef1e5d4f8d | Python | 1,829 | 61 | """Utility functions for the flyvis package.
This module organizes various utility submodules and sets up custom
accessors and backends.
"""
from importlib import import_module
def __getattr__(name):
# This lazy loading mechanism is implemented to improve import performance
# by deferring the import of subm... |
d6a7dbbdebda8e56fdf279e1b50181b6acf369b30c7da7397ce0ea2521784a68 | Python | 1,829 | 59 | import os
import pickle
import sys
import tempfile
import types
from unittest import mock
import pytest
from ci.ray_ci.doc.build_cache import BuildCache
@mock.patch("subprocess.check_output")
def test_get_cache(mock_check_output):
mock_check_output.return_value = b"file1\nfile2\nfile3"
assert BuildCache("/p... |
efe08e1ff78978bb9893f6a4278f1ad7c5e511169713aeaec36937eb408731d1 | Python | 1,829 | 86 | import numpy as np
from numba import jit, njit
@njit
def center_values(vals, mu, var):
out = np.zeros_like(vals)
for i in range(len(vals)):
std = var[i]**0.5
if std == 0:
out[i] = 0
else:
out[i] = (vals[i] - mu[i])/std
return out
@njit
def neighbor_smoot... |
6fcab1e83aad46fe34dc8a45424487c8e9d46bdc42a3ceb3c843928b4960f2ff | Python | 1,830 | 50 | from abc import ABC
from dataclasses import asdict, dataclass, field
from typing import Any
import numpy as np
@dataclass(eq=False)
class NIRNode(ABC):
"""Base superclass of Neural Intermediate Representation Unit (NIR).
All NIR primitives inherit from this class, but NIRNodes should never be
instantiat... |
ed2a4f2be760de5042ced85d6a20fc43a2ac33e6f14a6ebc3dbfea0b1ca1028d | Python | 1,830 | 61 | import os
import re
import sys
import gzip
import glob
import shutil
import argparse
import logging
import urllib.request
import codecs
import tarfile
from collections import OrderedDict
def faa_gz_files(members):
"""
Getting .faa.gz files from the tarball
"""
for tarinfo in members:
for ext i... |
f401e0e584c8cb9a9501232a43b38b0d4d31786a8f98074aa6ef2af669da8ec5 | Python | 1,833 | 32 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: input_file.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_po... |
0e85f5ce218a17b594489e9822640a72544094bc36a6e40a4df437865486f469 | Python | 1,834 | 58 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
# pylint: disable=abstract-method, no-name-in-module
"""AIHWKIT Extension functions"""
from typing import Any
from torch import Tensor
from torch.autograd imp... |
3dc1d4970faee4b2c99dad3a0a4284d2b12684d5a0d2c372218817ebc0a000bf | Python | 1,836 | 59 | import gzip
import argparse
import re
from collections import defaultdict
from dataclasses import dataclass
@dataclass
class ArmData:
p_end: int = 0
q_start: int = None
q_end: int = 0
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split("([0-9]+)", s)]
... |
590cb5f204549298aaf1df77836c5b42618005e7caadd8c272faf2a0790edc33 | Python | 1,836 | 95 | from typing import Any
from .conv import Conv1d, Conv2d
from .delay import Delay
from .flatten import Flatten
from .graph import Input, NIRGraph, Output
from .linear import Affine, Linear, Scale
from .neuron import IF, LI, LIF, CubaLI, CubaLIF, I
from .pooling import AvgPool2d, SumPool2d
from .threshold import Thresho... |
7336efa48b3aba881b9f08a75b421aba13ba937ae38cbf03cc53526486473a03 | Python | 1,838 | 53 | from ray._private.telemetry.open_telemetry_metric_recorder import (
OpenTelemetryMetricRecorder,
)
from ray.dashboard.modules.aggregator.constants import (
AGGREGATOR_AGENT_METRIC_PREFIX,
)
# OpenTelemetry metrics setup (registered once at import time)
metric_recorder = OpenTelemetryMetricRecorder()
# Counter... |
494e30030a57956dfca9d4fdd9d85767f4694b4085595032962139ccd4b5f7b4 | Python | 1,839 | 60 | from logging import getLogger
import numpy as np
from pfrl import explorer
class AdditiveOU(explorer.Explorer):
"""Additive Ornstein-Uhlenbeck process.
Used in https://arxiv.org/abs/1509.02971 for exploration.
Args:
mu (float): Mean of the OU process
theta (float): Friction to pull tow... |
ea0d351c43c9d1b87d5db7db0c3b85647b3fcd1005a394d6a6ac42c0ba044267 | Python | 1,839 | 48 | # Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
daa1ec263207d4571e270db8ef4820d207bd3a8a622becd33fef59b922cfa437 | Python | 1,840 | 75 | import torch as th
import numpy as np
# __func is original, func is GPU optimized
def __random_aug(graph, x, feat_drop_rate, edge_mask_rate):
import dgl
n_node = graph.number_of_nodes()
edge_mask = mask_edge(graph, edge_mask_rate)
feat = drop_feature(x, feat_drop_rate)
ng = dgl.graph([])
ng.a... |
9c6c6c83feb6ad9b4b1f66e8a9f689af8bda3c582d40dc7d2bab075f7c2ecc20 | Python | 1,841 | 61 | # EfficientNet-V2 config
import tensorflow as tf
from DECIMER.efficientnetv2 import effnetv2_model
BATCH_SIZE_DEBUG = 2
MODEL = "efficientnetv2-m" # @param
# Define encoder
def get_efficientnetv2_backbone(
model_name, include_top=False, input_shape=(512, 512, 3), pooling=None, weights=None
):
# Catch unsup... |
45d15eb5d535a2408f059ae69443fd78ca586d53be0cf016bab6b04e2156dfd6 | Python | 1,842 | 63 | from typing import Tuple
import pandas as pd
from data_profiling.config import Settings
from data_profiling.model.summary_algorithms import describe_counts
@describe_counts.register
def pandas_describe_counts(
config: Settings, series: pd.Series, summary: dict
) -> Tuple[Settings, pd.Series, dict]:
"""Count... |
a5de9be953306cb6fed701ea6ce27c6f8c203671ab4c44398f4a26eef00554b2 | Python | 1,842 | 53 | # Modified from OpenCV Implementation
# https://github.com/Peter554/StainTools/blob/master/staintools/reinhard_color_normalizer.py
import pyvips as Vips
class Reinhard(object):
"""
A stain normalization object for PyVips.
fits a reference PyVips image,
transforms a PyVips Image.
Can also be initia... |
ba9a0cbd84ac8085b07c67a255ba2276b09c38ffe50c106776a347ebf3ce834d | Python | 1,842 | 65 | import cv2 # noqa: F401 — preload libtiff before HIPT/torchvision shadows it (omicverse vendored patch)
import sys
import numpy as np
import pandas as pd
from utils import load_pickle, save_tsv, read_lines
def get_masks(labels):
if labels.ndim == 3:
labels, labels_dict = flatten_labels(labels)
else... |
9cbf3f97e1430cc3d3678796b850f1945e481770355505d909d51dc9e8fc5323 | Python | 1,843 | 62 | import argparse
import os.path
import pandas as pd
def merge_files(input_filename: str, metrics_filename: str, missing_metrics_filename: str):
with open(input_filename, "r") as fin:
lines = fin.read().splitlines()
files = []
for x in lines:
if os.path.isfile(x):
... |
e54fd0eb1f78a1b87dd4dba0f5214cefede4c2ba07c93235b88c184f5cfb36fb | Python | 1,843 | 52 | import ray
from ray.util.dask import enable_dask_on_ray
import dask
import dask.array as da
# Start Ray.
# Tip: If connecting to an existing cluster, use ray.init(address="auto").
ray.init(
resources={
"custom_resource": 1,
"other_custom_resource": 1,
"another_custom_resource": 1,
}
)
... |
4d27bdfaaddac88659cce650d4bbec6eb8f372095a78b57f686e496424949dab | Python | 1,844 | 66 | #!/usr/bin/env python3
import hashlib
import torch
import torchvision
from fire import Fire
from .extract import extract_features_
# use like this:
# python -m marugoto.extract.ozanciga \
# --checkpoint-path ~jxiaofeng/Downloads/tenpercent_resnet18.ckpt \
# --outdir /run/media/jxiaofeng/Sirius_03_empty/TCGA_feat... |
5634db13d02c9a00def1d8354483e90ae37ffc9c38a3f4a5277a611fba0f40b6 | Python | 1,844 | 54 | import argparse
import pathlib
import re
from typing import Optional
def preprocess_github_markdown_file(source_path: str, dest_path: Optional[str] = None):
"""
Preprocesses GitHub Markdown files by:
- Uncommenting all ``<!-- -->`` comments in which opening tag is immediately
succeeded by ``... |
38b85d9edce302a9eb95681b65a02cac7c57789445b70e982bf0aee09c5a5a0c | Python | 1,846 | 62 | import warnings
import os
from os.path import join
import argparse
from glob import glob
from tqdm import tqdm
import PIL
from torchvision import transforms
warnings.filterwarnings('ignore', category=UserWarning)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('train_dir', type=str, h... |
3df63dda1de738c08362b78398aba31f646fd2a5e603ea3c5330fe65db642d48 | Python | 1,846 | 64 | """Provides config settings for the logger and a way to load them"""
import sys
import os
import errno
import logging
def load_config(log_level, log_dir, log_file_basename, log_file_suffix):
from logging import config as logging_config
try:
os.makedirs(log_dir)
except OSError as e:
if e.... |
ed97b258d6b5b3bd6c9fcb7a6a9995f876891bbd3b7a7a9912037f4b535abe24 | Python | 1,846 | 65 | import os
from os.path import *
from . import tdir
# This directory
THIS=dirname(abspath(__file__))
FIXDIR=join(THIS,'fixtures')
def ungiz( filepath, dest=os.getcwd() ):
''' unpack filepath into dest '''
import gzip
fofile = join(dest,basename(filepath).replace('.gz',''))
fh = gzip.open(filepath)
... |
2277848d8c0d9ec3087aebea34cf224503441aef2586f1f61296226284134845 | Python | 1,847 | 42 | ####################################################################################################
# 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... |
4105e87ebec578eb83d567348cca0c76efc4810ac2bac224ed745b68080279ea | Python | 1,847 | 51 | # TODO: delete after fully support editor metric and datasets.
_base_ = 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
model = dict(
_delete_=True,
type='lqit.BaseEditModel',
data_preprocessor=dict(
type='lqit.EditDataPreprocessor',
mean=[0.0, 0.0, 0.0],
std=[255.0, 255.0, 255.... |
ab00009e4cdbce45fb28ff414dffad4d153cf59000aac3d0311b132805cad8e7 | Python | 1,848 | 41 | ####################################################################################################
# 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... |
184222160fbe0d2d263e58eb509885ef2236a32fec81860e8a686227a04be70e | Python | 1,850 | 64 | def test_contours_single():
from samri.plotting.maps import contour_slices
import matplotlib.pyplot as plt
file_template = '/usr/share/mouse-brain-templates/dsurqec_200micron_masked.nii'
cmap = plt.get_cmap('tab20').colors
contour_slices('/usr/share/samri_bidsdata/preprocessing/sub-4007/ses-ofM/func/sub-4007_ses... |
9a14186ae11202a1b9ce873156bc6c97e924267f6137bbd72659cfbd350bd1bb | Python | 1,850 | 43 | # Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
# and Applied Computer Vision Lab, Helmholtz Imaging Platform
#
# 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 L... |
8abfcdd7a41bdb336963b761e5cef708c3de2d44caeb42e0c5e2b5d4534c5e46 | Python | 1,851 | 60 | import os
from deepinterpolation.inference_collection import core_inference
from deepinterpolation.generator_collection import EphysGenerator
import pathlib
if __name__ == '__main__':
generator_param = {}
inference_param = {}
# We are reusing the data generator for training here. Some parameters
# lik... |
adad1e6d2f0c4ec10776570bd1ec5d549303f5800972e913f782c092e4948c0a | Python | 1,851 | 51 | import torch
from ..distances import LpDistance
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..losses.base_metric_loss_function import BaseMetricLossFunction
class NCALoss(BaseMetricLossFunction):
def __init__(self, softmax_scale=1, **kwargs):
super()._... |
35e67992bb069d1df1bff0e9a457b900023632efab7ffb4169317370c04c521f | Python | 1,852 | 52 | """Exact search must not truncate Milvus galleries at the query result limit."""
from unittest.mock import MagicMock
import pytest
sdk = pytest.importorskip("pymilvus")
from deepface.modules.database.milvus import MilvusClient
@pytest.mark.parametrize("count", [0, 1, 16385])
@pytest.mark.parametrize("batch_size",... |
66b435a41fb0a63b58865aab126155b1cd74be069c02ca447cabb959b361d3a3 | Python | 1,852 | 66 | import socket
import os
import sys
import pickle as pkl
import socket
import os
import sys
if socket.gethostname() == 'kelarion':
CODE_DIR = '/home/kelarion/github/'
SAVE_DIR = '/mnt/c/Users/mmall/Documents/uni/columbia/assignment_errors/'
else:
# CODE_DIR = '/rigel/home/ma3811/repler/'
# SAVE_DIR... |
71de10dffdc3826823a8830f1edd24fe9e73c6c6f527e8a5c230d475223ffcaf | Python | 1,852 | 60 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
4653417427ccbb56eb2ce0d51dddefc352f33e9733275b8a47bd3c86cfa777e1 | Python | 1,853 | 48 | import pandas as pd
import numpy as np
#from action_prediction import modeling
#from action_prediction import constants as const
from experiment_code import constants as const
from models import modeling
def run(dataframe, model_names):
"""Run models for predicting accuracy
Args:
dataframe (pd dataf... |
ae45cb0ae1f1b43c33c8d66567aec6e9921722b78bc4aaa8179ebeada0b19090 | Python | 1,853 | 39 | import argparse
def get_opts():
parser = argparse.ArgumentParser()
# dataset parameters
parser.add_argument('--root_dir', type=str, required=True,
help='root directory of dataset')
parser.add_argument('--dataset_name', type=str, default='heart',
choices=... |
cee5e248ae8abc3b76814fa64d28d677986752ef5a2ca1d0dc5890680d5f10ef | Python | 1,853 | 52 | """
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 typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from numpy.typing import Ar... |
421aee43ee218b87a3aa66ab83864be57e16dd9f86b2dfc73d937a21c4503a6b | Python | 1,854 | 62 | from typing import Any, Sequence
class Augmentation:
"""
Base class for data augmentation operations.
This class provides a framework for implementing various data augmentation
techniques. Subclasses should override the `transform` method to implement
specific augmentation logic.
Attributes:... |
a93dd7e6c495ccf8e5590535011efc82a2694d784ff4f31bd9930d04ef022aee | Python | 1,854 | 43 | import tensorflow as tf
class Encoders:
class Encoder:
def __init__(self, shape=None, layers=(2,), dropout=0):
self.shape = shape
self.model = None
self.layers = layers
self.dropout = dropout
self.build()
def build(self, *args, **kwarg):
... |
b70fd808914983abc82aae0c5be01abd93fd003390ea8684278edac917e35006 | Python | 1,854 | 46 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
# mypy: disable-error-code=attr-defined
"""Module wrapper to quantize its input"""
from typing import Any
from torch import Tensor
from torch.nn import Module... |
f5dd752e179a6aa364849b81634180d93f9d9c7cf45033c3d96e0ae882639a75 | Python | 1,855 | 50 | import torch
import torch.nn as nn
from torch.nn.utils import spectral_norm
_norm_options = {"in": nn.InstanceNorm2d, "bn": nn.BatchNorm2d, "sn": spectral_norm}
class Critic(nn.Module):
def __init__(self, args, in_ch, input_ft, max_ft=265, depth=4, **kwargs):
super(Critic, self).__init__()
self.a... |
2b5910ac5c7dc0b3652da903d6aa8d19732eead57dd0c8b97990c7c2af9fff65 | Python | 1,856 | 70 | import pandas as pd
import torch
class MetricsWrapper:
ndim = 0
def merged_state(self, met2):
preds = self.preds + met2.preds
target = self.target + met2.target
assert self.metrics == met2.metrics
return MetricsWrapper(self.metrics, preds, target, save_csv=self.save_csv)
... |
a854adb8c91452fc8474810b38afe3ee1653a45dee2d195308aa23625bcdbd9d | Python | 1,856 | 69 | # -*- coding: utf-8 -*-
"""
Anything geometry related goes in here. I use this file for multiple projects
so there will be unused functions in here.
"""
import numpy as np
from vtkplotlib import nuts_and_bolts
def distance(points, keepdims=False):
return np.sqrt(np.sum(points**2, axis=-1, keepdims=keepdims))
... |
fa85bd7486674397a53737cc0ab6ca59ca4bea6e29c2b64350d872ae2706a06d | Python | 1,856 | 58 | from collections import Counter
from pyspark.sql import DataFrame
from data_profiling.config import Settings
from data_profiling.model.table import get_table_stats
@get_table_stats.register
def get_table_stats_spark(
config: Settings, df: DataFrame, variable_stats: dict
) -> dict:
"""General statistics for ... |
1f34660ec736c99c6a8455bc1a1efded680b626a88c0b07f814c08ea9d01476c | Python | 1,857 | 56 | """
Choose the network from
1: 16 layers, 16 channels every layer, 3x3 kernels 34944 parameters in total
2: 16 layers, 32 channels every layer, 3x3 kernels, 139008 parameters in total
3: 30 layers, 64 channels every layer, 3x3 kernels, 1071488 parameters in total
The variational energies of these networks correspond t... |
a68b7b9688978274d6817d8c17e996610ec85a058fbeee465b3e041c3e68e145 | Python | 1,858 | 48 | import streamlit as st
import numpy as np
import joblib
import os
# Set page config
st.set_page_config(page_title="Concrete Strength Predictor", layout="centered")
# Load CatBoost model
model_path = os.path.join(os.path.dirname(__file__), "CGB_compatible.joblib")
try:
model = joblib.load(model_path)
except Except... |
2024b49b8ecadfb2f3aa75fc7e595826a9b0c07ad1cc4221bed3e62d6ea80cb8 | Python | 1,859 | 41 | import os
import argparse
import csv
import uuid
from analysis.metrics import MoleculeProperties
from typing import List
from rdkit import Chem
def main(pocket_mols: List[List[Chem.Mol]], output_dir: str):
mol_metrics = MoleculeProperties()
all_qed, all_sa, all_logp, all_lipinski, per_pocket_diversity = mol_m... |
9f4387284a016a9747240f86d97d48ddf2ae75b3b3073cffa47b2175ee6c2372 | Python | 1,859 | 60 | import os
from deepinterpolation.generator_collection import SingleTifGenerator
from deepinterpolation.inference_collection import core_inference
import pathlib
if __name__ == '__main__':
generator_param = {}
inference_param = {}
# We are reusing the data generator for training here.
generator_param["... |
3a9c87a5f000efa5cb2faa0ea7d938ccc3c7901a9c0d320af6ccfcd5b81603f9 | Python | 1,860 | 73 | """
test lif_curr_exp
"""
import os
import matplotlib.pyplot as plt
import numpy as np
from spinnaker2 import hardware, snn
def test_lif_curr_exp(do_plot=False):
params = {
"threshold": 1000.0,
"alpha_decay": 0.9,
"i_offset": 0.0,
"v_reset": 0.0,
"reset": "reset_to_v_reset... |
ce91abcfdb01132e92145f211e27c8143d93d30a3eca103c949b4d0583f589d3 | Python | 1,861 | 45 | from data_profiling.report.presentation.flavours.widget.alerts import WidgetAlerts
from data_profiling.report.presentation.flavours.widget.collapse import WidgetCollapse
from data_profiling.report.presentation.flavours.widget.container import WidgetContainer
from data_profiling.report.presentation.flavours.widget.corre... |
50ace4fc09e56f6dbff01673bbcbcc3e992efe2599c226b87f73e5ef247b2650 | Python | 1,862 | 47 | from data_profiling.report.presentation.flavours.html.alerts import HTMLAlerts
from data_profiling.report.presentation.flavours.html.collapse import HTMLCollapse
from data_profiling.report.presentation.flavours.html.container import HTMLContainer
from data_profiling.report.presentation.flavours.html.correlation_table i... |
1b5ccb4163617eb727f8be5f8683d3e516f237e77ceb55ae718928fc914bcdc3 | Python | 1,864 | 54 | from types import SimpleNamespace
import numpy as np
from flyvis.network import ensemble_view as ensemble_view_module
from flyvis.network.ensemble_view import EnsembleView
class _FakeFRI:
def __init__(self, values, cell_types, filtered_cell_types=None):
self.values = values
self.cell_type = Simp... |
f3377514e0c0c44183ea7fb40ba7bae518949ffbc3f3c616f24002eab4777550 | Python | 1,864 | 68 | # __child_capture_pg_start__
import ray
from ray.util.placement_group import placement_group
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
ray.init(num_cpus=2)
# Create a placement group.
pg = placement_group([{"CPU": 2}])
ray.get(pg.ready())
@ray.remote(num_cpus=1)
def child():
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.