sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
b0dd3f2b85363c8a8141c6cd2fc91380103661a6c2ce7379a60d5a24cacc19a4 | Python | 3,665 | 89 | import json
import os
import time
from predict_quality_scores import calculate_qs
import keras
import openpyxl
import argparse
import numpy as np
import datetime
def read_items_from_file(txt_path, mode='r'):
items = []
with open(txt_path, mode) as file:
items = json.load(file)
file.... |
73fd14ff7b05568a2aef4912165be0c00f7802e987427c23ee9e6e68094c9fe3 | Python | 3,667 | 120 | from pathlib import Path
import numpy as np
import pandas as pd
from epilepsy2bids.annotations import Annotations, SeizureType
from timescoring import annotations, scoring
FS = 256
def toMask(annotations):
mask = np.zeros(int(annotations.events[0]["recordingDuration"] * FS))
for event in annotations.events... |
33c85c6963df915946d580bb524daae21e7806d4447b40dea0573cbb6abfd73f | Python | 3,668 | 104 | ####################################################################################################
# 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... |
c406ba345c7d178fafba2dfc8c11fda4b2dcbb9a3b413a81ffc034b51be07fb2 | Python | 3,668 | 75 | import os
import unittest
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest import mock
import torch.distributed as dist
import torch.multiprocessing as mp
from batchgenerators.utilities.file_and_folder_operations import join, load_json, save_json
import nnunetv2.training.nnUNetT... |
e6c6697718ecfdfa702c3d357850f6709ee81244342922ae291fe0ac5796ae36 | Python | 3,668 | 134 | """Simple wrapper around ChromaDB using GPT4All embeddings.
This module exposes helper functions to create a vector store backed by
`GPT4AllEmbeddings` and perform basic CRUD operations on ChromaDB
collections.
"""
from __future__ import annotations
import uuid
from typing import Mapping, Sequence, Any
import chrom... |
dd506ba2255b5d9e983c11f021a2ee79b521291f42b3c73ed312b27a3c060c1c | Python | 3,669 | 80 | from Utils import ddpred
import argparse
def run():
parser = argparse.ArgumentParser(description='SeqPINN')
# Para for SeqPINN
parser.add_argument('--mode', type=str, choices=['train', 'load', 'check'], default='train',
help='Mode to run the script: train or load')
parser.add_ar... |
2d5f9a52a89d4466dc249feb3e38d27c61c3926f7b00698cb4f98d3249f65583 | Python | 3,671 | 134 | import os
import sys
import time
import errno
import time
import timeit
import warnings
import numpy as np
from numba import jit
warnings.simplefilter("ignore")
@jit(nopython=False)
def VEP2Dmodel_sensor(params, constants, init_conditions, SC, Gain, dt, ts):
nt=ts.shape[0]
nn=SC.shape[0]
ns=Gain.sha... |
4aab484e96dba85b2eba14f54c42df103a314a087ca184bfcca30e77d0faea2c | Python | 3,671 | 107 | """Minimal version of S4D with extra options and features stripped out, for pedagogical purposes."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange, repeat
from src.models.nn import DropoutNd
class S4DKernel(nn.Module):
"""Generate convolution kernel f... |
e71e141c1f5ccfd63df2803f5ded8fca4accea7377a2953971d3b48e235adf5b | Python | 3,671 | 110 | import argparse
import skorch
import torch
from sklearn.model_selection import GridSearchCV
import data
from model import RNNModel
from net import Net
parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model')
parser.add_argument('--data', type=str, default='./data/penn',
... |
597e47dc0bfe5af4d06a51448167dd3d6583eb948008cb695a5de621b2128d50 | Python | 3,673 | 129 | import json
import numpy as np
from pathlib import Path
from tqdm import tqdm
from boosting_utils import BoostingDataLoader, Booster
from utils import parse_arguments
def run_boosting_pipeline(
subject_id: str,
eeg_dir: Path,
feature_dir: Path,
trf_params: dict,
) -> tuple[np.ndarray, np.ndarray, np.n... |
8cea62253b71d33879be00ac8215debece4abfd759e9dd8a551733a018c2f3bb | Python | 3,673 | 130 | #!/usr/bin/env python
## HiC-Pro
## Copyright (c) 2015 Institut Curie
## Author(s): Nicolas Servant, Eric Viara
## Contact: nicolas.servant@curie.fr
## This software is distributed without any guarantee under the terms of the BSD-3 licence.
## See the LICENCE file for details
"""
Script... |
dfbd311c3e3bbfe768ba8fff7a5defe27d3e0ddda4bee20db700dd64fee5e896 | Python | 3,675 | 87 | import sys
import collections
# column positions
STATS_CHROM_IDX=1
STATS_FILENAME_IDX=2
PAIRWISE_CHROM_IDX=1
PAIRWISE_FILENAME_IDX=4
PAIRWISE_COVERED_VARIANTS_IDX=7
PAIRWISE_ALL_ASSESSED_PAIRS_IDX=8
PAIRWISE_ALL_SWITCHES_IDX=9
PAIRWISE_ALL_SWITCH_RATE_IDX=10
PAIRWISE_BLOCKWISE_HAMMING_IDX=13
PAIRWISE_BLOCKWISE_HAMMING... |
22049b43c9ab59012c9eca58a32aa0fccc8831c99d7e4a02c4a8d9e22e9b84a6 | Python | 3,676 | 103 | import io
import pickle # noqa: F401
from typing import Any, Dict, Generic, List, Tuple, Type, TypeVar, Union
import ray
from ray.dag.base import DAGNodeBase
# Used in deserialization hooks to reference scanner instances.
_instances: Dict[int, "_PyObjScanner"] = {}
# Generic types for the scanner to transform from ... |
3bd80188412394bda5a54da6b1fb623dfb9d55358488ce59c7db36255de25c61 | Python | 3,676 | 135 | """
Persistent configuration helpers for Jarvis.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any, Dict, Optional
def default_state_dir() -> Path:
return Path(os.path.expanduser("~/.ovjarvis"))
def default_config_path() -> Path:
return default_sta... |
b19a23737b60d43a0ee4a081f8b28d1af32e6136f1667de2b1b1014d74f0c163 | Python | 3,676 | 108 | from __future__ import print_function, unicode_literals, absolute_import, division
# from six.moves import range, zip, map, reduce, filter
from keras.backend import categorical_crossentropy
from ..utils import _raise, backend_channels_last
import numpy as np
from ..utils.tf import keras_import
K = keras_import('backe... |
730b3d8f9b7592a8df53186543bc0804488a17dcfeae205984949e1155fbc8f1 | Python | 3,677 | 103 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# Created By : Kangjoo Lee (kangjoo.lee@yale.edu)
# Last Updated: 08/06/2024
# -------------------------------------------------------------------------
# Imports
import math
import h5py
import o... |
9bd6620ae72467c100e7f73254ca45d4f526a1cf51f03e6c1f629bc53c97f4a5 | Python | 3,677 | 120 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import time
import torch
from pyJoules.energy_meter import EnergyContext
from pyJoules.device.rapl_device import RaplPackageDomain, RaplDramDomain
from pyJoules.device.nvidia_device import NvidiaGPUDomain
from pyJoules.handler.pandas_handler impor... |
640ba74db0d9fba4b78897dc68ecf154a838363067ff2b003e3f153d8ca669f2 | Python | 3,680 | 114 | import torch
import torch.nn as nn
from scipy.stats import beta
import numpy as np
# TODO: Make weighting functino more flexible
class GenoMAFWeight(nn.Module):
def __init__(self, maf_dim: int = 0):
# , sigmoid: bool = False):
super().__init__()
self.maf_dim = maf_dim
def forward(s... |
2b6bb94c096f6438f474cded37b19e60208790d40d82ecc0fe15cd976762bfb7 | Python | 3,682 | 95 | #
# 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... |
ac6b2a6554e99c3e80b68b025ece389f0a3d45a03a938fe561b9285fff68ae7f | Python | 3,682 | 90 | from torchviz import make_dot, make_dot_from_trace
import torch.nn as nn
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import torch
from SPLAM import *
from splam_utils import *
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot a... |
69bb7f3a9e7736fb79708bc655bf33059523c6d9b8d935277fa1f808f3ec0671 | Python | 3,683 | 121 | import os
import hashlib
import logging
import argparse
import datetime
from timeit import default_timer as timer
def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--src",
default="/data/partners_ecg/xml",
help="Path to directory containing organized source X... |
5a3604c3b354f7c089cdfd383e5233c4d4d7e8291ab27509954d014b38ce2f45 | Python | 3,686 | 115 | from typing import List, Literal
import torch
import pandas as pd
import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
from timm.models.vision_transformer import Block as AttentionBlock
import torch.nn as nn
import torch.nn... |
ccda5c45130f4e5fb16582c5c7552d798c0a79d83b93e4518f7ebbb8bd42484f | Python | 3,686 | 79 | import os
import glob
import torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader
from label2img import ExVivoDataset
from lightning_model import MyModelLightning
from dataloader_val import ValDataset
device = torch.device('cuda:0')
import... |
724c29a971c15d799cb4beab36008d9de1234c64e274d24a5d0351c837935d64 | Python | 3,688 | 116 | #!/usr/bin/env python3 -u
# Copyright (c) DP Techonology, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
import pickle
import torch
from unicore import checkpoint_utils, distribut... |
8e22959d17cc2f1c8e8f5105cd325febe15471a6fb977a06189839c9818e74f5 | Python | 3,688 | 93 | # -*- 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.
#... |
5deb73c2faff4d8bd233be84389e8c4888430e52333afbb855ff3c020ecd5f9f | Python | 3,689 | 105 | from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import softmax as sp_softmax
import torch
import torch.nn.functional as F
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch.nn import Parameter
import torch_geometric
class Self... |
e0a43d70b36c82928dc263697f84efab58fac41718acbdbe83ec73c21eb2000b | Python | 3,691 | 120 | import argparse
import glob
import json
import os
import os.path as osp
from collections import defaultdict
from datetime import datetime
import pandas as pd
from rich.console import Console
from rich.table import Table
def parse_args():
parser = argparse.ArgumentParser(description='Gather Results')
parser.a... |
d31c34d14d32c62d3a3d192b51614bbf750d2f47d59fa846799eb2cafa3930b0 | Python | 3,694 | 80 | import torch
import torch.nn as nn
class MultiHeadFastSelfAttention(nn.Module):
def __init__(self,
num_attention_heads = 8,
input_dim = 512):
super(MultiHeadFastSelfAttention, self).__init__()
self.attention_head_size = input_dim//num_attention_head... |
4684c132464e342da9551d44651e1a023d4d4c115066a85e9c72a044c6ea3ecf | Python | 3,696 | 100 | import json
import os
import torch
from diffusers import UNet1DModel
os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True)
os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True)
os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True)
def unet(hor):
if hor == 128:
down_block_... |
e7be5ccb0f21aee3a3d5f4d419eac87c6e73e758e1f2ca6efdedacbef98dd893 | Python | 3,696 | 115 | import os
import torch
import torch.nn as nn
import torchvision
import torch.nn.functional as F
import pdb
import cv2
import random
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import scipy.io as scio
from torch.utils.data import Dataset
from PIL import Ima... |
cf0503ee7408629ddb12d071f09e95a97fc82362f4d1035b5398a8672cf0fb4e | Python | 3,698 | 94 | """Post-reconstruction fix for random-looking first echo slice artifacts."""
import os
import numpy as np
import nibabel as nb
FILE = "/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/sub-05/ses-02/anat/sub-05_ses-02_T2s_run-01_dir-PA_echo-1_part-mag_ASPMEGRE.nii.gz"
SLICES = [9, 10, 18, 40, 65, 70, 71,... |
284e8be45acf1232bbbebf7f0dec5e82c1aacd69a32d8ebc900628451424b8f2 | Python | 3,701 | 92 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python version: 3.10.9
pandas version: 1.5.0
seaborn version: 0.11.0
matplotlib version: 3.6.3
"""
#%% Import Modules
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
#%% Directories
project_dir = '/data/pt_02306/main... |
c8fb25258093cae32b4f4f3ff8f9fca375f5f8d522a76d1f7075d7da808bedfa | Python | 3,703 | 73 | import pickle
import numpy as np
from sklearn.decomposition import PCA
DATA_ROOT = '../data/input_scene_vecs/'
class PCATransformer:
"""
This class loads individual PCA matrices and perform transform or invert based on these PCA matrices
PCA matrices were derived by PCAComputer class
"""
def __in... |
da63d79a834fbdd6c4fb9799a3a10604af1d7444e09fd5ccd78bda4094770b69 | Python | 3,703 | 109 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion):
# --------------------------------------------------------------------------------... |
685c625ce3998ff6ea10bfe5972b8a385e5ad543c1c10ce93049f24a17eb4582 | Python | 3,704 | 107 | # coding=utf-8
# Copyright 2023 HuggingFace 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 ag... |
3ea465bcb1214af98b847c53c718786c5efa23e32e63f3bcaa03cae879211f44 | Python | 3,705 | 138 | # flake8: noqa
# isort: skip_file
import os
os.environ["RAY_TRAIN_V2_ENABLED"] = "1"
# __torchmetrics_start__
# First, pip install torchmetrics
# This code is tested with torchmetrics==0.7.3 and torch==1.12.1
import os
import tempfile
import ray.train.torch
from ray import train
from ray.train import ScalingConf... |
1293549ddc53f38049fd1b9291ef4b699b175f7c9cae10f4dc06ff709aff6c4a | Python | 3,708 | 138 | # altschulEriksonDinuclShuffle.py
# P. Clote, Oct 2003
# NOTE: One cannot use function "count(s,word)" to count the number
# of occurrences of dinucleotide word in string s, since the built-in
# function counts only nonoverlapping words, presumably in a left to
# right fashion.
import sys,string,random
def computeC... |
8cca52018c3bfee6fbd2fca745fda27f2e180933731ff053b3a1331b604f0682 | Python | 3,711 | 95 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from model.warplayer import warp
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv_wo_act(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Con... |
6b3dd082c69a945a9315a17c97fa3c79fa44cfd740cfdd1f8a5ad8ebddf13e24 | Python | 3,712 | 108 | import tkinter as tk
import webbrowser
from parameterized import *
root = tk.Tk()
root.geometry('404x765')
root.title('Raymon Shi Touchscreen Data Analysis App')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
def display_frame(frame_page):
"""
This function simply raises a sele... |
f2adb0886219e8e177028eb05e1d103f6c6942b3bc22d61bee112cebc0ec09bc | Python | 3,712 | 132 | r"""
Graph and GAN networks in SLAT
"""
import math
from typing import Optional, List
import torch
import torch.nn.functional as F
from .graphconv import CombUnweighted
class LGCN(torch.nn.Module):
r"""
Lightweight GCN which remove nonlinear functions and concatenate the embeddings of each layer:
... |
45d676a9104510d9231282e753c871981015f463416596fa12b9091e72629fb9 | Python | 3,713 | 110 | """Phylogenetic-tree helpers for ``ov.micro``.
Tools to attach a newick tree to an AnnData (``uns['tree']``) and prune it
to match the ASVs actually present in ``var_names``.
"""
from __future__ import annotations
from pathlib import Path
from typing import Optional, Union
import warnings
try:
import anndata as ... |
8156e88f0ef78216021e80c38a6302a57dc4f0ddb50190c017b8aa27580cbd5b | Python | 3,714 | 105 | #Imports relevant modules.
import os
import csv
import json
#Defines the pipeline of interest.
pipeline = '0'
#Defines the pipeline directory as a variable.
pipeline_dir = '/<directory root>/fMRIPrep/Pipeline_{}'.format(pipeline) #Full path removed for purpose of public sharing.
#Defines the location of the director... |
cd2dd56b777b4a2ae576b574681983d4a103dd626ab019e0c5f872b1ede80d93 | Python | 3,714 | 102 | import sys
sys.path.insert(0, "/srv/home/zgaleday/torch_pgn")
from torch_pgn.train.Trainer import Trainer
from torch_pgn.data.ProximityGraphDataset import ProximityGraphDataset
from torch_pgn.train.train_utils import load_checkpoint
from torch_pgn.data.load_data import _load_splits, _split_data, _save_splits
from torc... |
a3b70e4b8bb63ec1bd25da12c70bd52d30f299dea7ac0f2efa77dc12b9642a86 | Python | 3,716 | 101 | import asyncio
import logging
from concurrent.futures import Future, ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple
logger = logging.getLogger(__name__)
class JaxProfilingManager:
"""JAX profiling manager for Ray Dashboard.
It connects to the JAX... |
0754fc44486c102e7b7941636faacf05fdf4a39bec182a5edf3e623216b8479f | Python | 3,718 | 84 | #!/usr/bin/env python
# A5A3 and AF
import pandas as pd
from prepare_and_parse import class_by_transcript
from prepare_and_parse import class_by_transcript_pd
from prepare_and_parse import generate_split_table
def identify_A5A3_transcripts(args, df, All_FilteredParsed):
'''
Aim: Tabulate the transcripts ... |
c4dacd3f39c1ed5ea0f9dd3b740efdfb58ec7bb7c997e417c149c176379918da | Python | 3,718 | 118 | """
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 os
from dataclasses import dataclass
from typing import Any, Literal
from pymatgen.io.vasp impo... |
6f2d287a08b153ac0fff8c33b306d6e086096f60738f48a569394bbea4ff0093 | Python | 3,719 | 113 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import os
def vcf_readin(vcf_name):
out = []
fin = os.popen(r'''zcat %s''' % (vcf_name))
for line in fin:
pin = line.strip().split()
if not pin[0][0] == '#':
out.append(pin)
fin.close()
return out... |
01a79161da1a3cf639da874a7781559e231ab002f032eb24d384bb1448a632da | Python | 3,720 | 122 | import os
from copy import deepcopy
from time import time
import numpy as np
import torch
from torch.utils.data import DataLoader
import pytorch_lightning as pl
import matplotlib
import matplotlib.pyplot as plt
from utils import load_pickle, save_pickle
matplotlib.use('Agg')
class MetricTracker(pl.Callback):
... |
e4d3f80001ee793815110aea8f9c7cc73feab90925f2958387e6d8e82c6b656d | Python | 3,720 | 97 | import logging
from typing import Dict, List
from ray.data._internal.execution.interfaces import ExecutionResources
logger = logging.getLogger(__name__)
def is_autoscaling_enabled() -> bool:
"""Check if any node type has autoscaling enabled (can scale up).
A node type is autoscalable if max_count == -1 (un... |
86680a15da478216a2ad54810781de7af52ad699ca21bd00d73c5aa406f577b7 | Python | 3,721 | 126 | import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import cm
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def logistic_model(data, cell_types, sparsity=0.2, fractio... |
157fa619a5372c05f536042233953a1cc9974ba8859f5cc564da172f65d38cf8 | Python | 3,722 | 101 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Tests for the AIHW Composer API client."""
import os
from unittest import SkipTest
from aihwkit.cloud.client.entities import CloudExperiment, CloudJobStatus... |
42556a08575e1be877d6bdcd9b8410108449a47f6ddc8122599f7f2ae4182525 | Python | 3,722 | 100 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from ray.data._internal.datasource_v2.interfaces.file_manifest import FileManifest
@dataclass(frozen=True)
class PartitionHints:
"""Sizing hints ``read_api`` derives for ``DataSourceV2.get_file_partitioner``.
They are hints: a partitioner... |
d9e56f2daf9623e60df77d2fc5d9a5cb22e2d448544815ba96c3a5072259fb05 | Python | 3,723 | 65 | import sklearn as sk
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, average_precision_score
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import K... |
c5f949c0c154f8b1abc79392aef6fc5a990f0b5a1169a4c7e9404ec199a10450 | Python | 3,724 | 101 | from exputils.gui.jupyter.multi_selection_widget import MultiSelectionWidget
import warnings
import exputils as eu
class ExperimentIDsSelectionWidget(MultiSelectionWidget):
'''
MultiSelectionWidget to select experiment ids in a experiment_data dict.
'''
@staticmethod
def default_config():
... |
7af8f3e9920eaaea8d3a268119d94966293a3ec713810d0529b99ee77b1adfef | Python | 3,727 | 102 | import sys
import logging
import numpy as np
import math
from pathlib import Path
import click
import yaml
import pandas as pd
logging.basicConfig(
format="[%(asctime)s] %(levelname)s:%(name)s: %(message)s",
level="INFO",
stream=sys.stdout,
)
logger = logging.getLogger(__name__)
@click.command()
@click.o... |
b5da18c3fadd71c36d9297c93a864cda65521878c7fea74a9a1404739f34da49 | Python | 3,727 | 155 | # -*- coding: utf-8 -*-
"""Test the contents of the vtkplotlib.figures module."""
import time
import numpy as np
import os, sys
from pathlib import Path
import pytest
import vtkplotlib as vpl
from tests._common import TEST_DIR
pytestmark = pytest.mark.order(3)
def test_abstract():
with pytest.raises(Exceptio... |
cc0d932c5100c0489d659d34039bb42ccbbb06c524649f5359e81cbb03fa77a0 | Python | 3,727 | 110 | """
Application-level autoscaling policy for video processing pipeline.
Scaling strategy:
- VideoAnalyzer: scales based on its load (error_ratio = requests / capacity)
- VideoEncoder: scales based on its load, with floor = VideoAnalyzer replicas
- MultiDecoder: 0.5x VideoEncoder replicas
Error ratio formula:
erro... |
dce8c2c5072edd327c7f66baca67a12d9407630cc6d3f9c5b521972695e331a4 | Python | 3,727 | 91 | from typing import Union, List
from torch.nn import Module
from torch.nn.modules.loss import _Loss
from src.handlers.general import ParamSchedulerHandler
from src.losses.vqvae.utils import VQVAELosses
from src.losses.vqvae.vqvae import *
def get_vqvae_loss(config: dict) -> Union[_Loss, Module]:
"""
Configur... |
5ffdff019696717047ecdf2163a54a94f16cf451501d41443fe7d9e0f8c0ddce | Python | 3,729 | 127 | # cSpell:disable
from typing import Any, Literal, NamedTuple
import numpy as np
from numpy.typing import NDArray
from sklearn.metrics import (
accuracy_score,
f1_score,
max_error,
mean_absolute_error,
mean_absolute_percentage_error,
mean_squared_error,
precision_score,
r2_score,
rec... |
edb4955f12b07b8d49b3157bf7636a8b6642ae8ebccecb1f120f4630bb4f63ab | Python | 3,729 | 86 | import torch
import logging
from torch.utils.data import TensorDataset
from agent.data.entities.config import FD_CLASS_VALUES, ITEMS_TABLE
from agent.data.entities.config import TRAIN_ITEM_FILTER, TRAIN_LABEL
from agent.classifiers.utils.class_mgmt import get_numeric_rating, get_number_of_classes
from agent.data.sql.... |
889667da082447abed7f0acdbd8af5a6e3f2c47b31810ceb67cd1bbb7d660c82 | Python | 3,730 | 119 | '''
check if we can cluster the scene vectors
in particular, can we derive good clustering parameters from the training set
and generalize to the validation set
this is essential for the clustering based shortcut model to work
'''
import os
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
imp... |
bbcfceac31b0d1e2186fe76b9667644ad0bd1f97f053df9dda6ccfbaa5edd90a | Python | 3,730 | 104 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Analog mapped linear layer."""
from typing import Optional, Type
from torch.nn import Linear
from aihwkit.exceptions import ConfigError
from aihwkit.simula... |
cf1a8d333934ac2ae87d04ec1f9a2df33b5e557115c25af13cc9986bd1aaa220 | Python | 3,730 | 108 | import os
import sys
import cv2
import torch
import argparse
from torch.nn import functional as F
import warnings
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
import time
warnings.filterwarnings("ignore")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.set_grad... |
505460473582ec01452467b6a7ef336a38ab751c23b4812575ba19f1a13b04fb | Python | 3,731 | 89 | import os
import sys
project_root = '/ccb/cybertron/khchao/splam-analysis-results/'
def main():
SEQ_LEN = sys.argv[1]
HALF_SEQ_LEN = int(SEQ_LEN) // 2
QUATER_SEQ_LEN = int(SEQ_LEN) // 4
# for threshold in range(2, 101):
for threshold in range(1, 2):
input_file_dir = f'{project_root}t... |
c6fb4cf30792530aa1a441a2edc309d9b4ca610fd1d1f5a09dfec5898f1f62a2 | Python | 3,733 | 87 | import numpy as np
import matplotlib.pyplot as plt
import os
import utils
import pandas as pd
layerid = 1
resultsdir = "./results-mnist-big/"
ent_act = []
ent_pj = []
for paramdir in os.listdir(resultsdir):
for timestampdir in os.listdir(f"{resultsdir}/{paramdir}"):
datadir = f"{resultsdir}/{par... |
7151892ebe447be20ef36ddb6ae71ebbc852ce246cc8fa563834138cc5fb4c53 | Python | 3,734 | 113 | # 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... |
8e86b78f39b220ec8f341f324ad45a0b4cd8bf245ead17b50ae198dedcde7882 | Python | 3,735 | 124 | """
Example for fast running multiple experiments with same snn.Network with
changed input spikes.
Compared to `lif_transfer_curve_multi_run.py`, here the iterations are executed
with a hardware reset of the network and changed input spikes -- instead of
running the full experiment including mapping in each iteration.... |
6c3ba9bffe208ab4dde211cb25c7140c0c5dbad58cb94b9f640073663937d5a3 | Python | 3,737 | 103 | # Copyright 2026 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
f7a93369d3a6f44ead6f20509ec327bcba9974a3aa894cc4a7592702e49e9d79 | Python | 3,737 | 61 | import os,sys,json,hashlib
from pathlib import Path
root=Path(sys.argv[1]).resolve();out=Path(sys.argv[2]).resolve();out.mkdir(parents=True,exist_ok=True)
os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL','2')
os.environ.setdefault('TF_ENABLE_ONEDNN_OPTS','0')
import numpy as np,tensorflow as tf,keras
tf.config.threading.se... |
fa16f37f9d15fd485761b8d9c5e32f765c788647a1f9385766a04696e38a93de | Python | 3,738 | 106 |
from __future__ import print_function
import sys
import subprocess
# read.0
# read.1
# read.2
# chr
# subs
# ptype
existed = set()
def assert_exists(loc):
if not loc.startswith("s3://"): return True
if loc in existed: return True
if len(subprocess.check_output(['s3cmd', 'ls', loc])) == 0:
print(... |
98289149903db1fd40809707caee6665fb6d8ed0a1219d9b01b0e62f354f62ce | Python | 3,739 | 99 | def distribution(data,T_times,T_interval): #To evaluate the transition time and number
'''
Change the time series to three numbers:
-1 if <0
0 if =0
1 if >0
and put these results in sign,
'''
xshape=np.shape(data)[0]
yshape=np.shape(data)[1]
count=0
... |
39b725866d381f2d6ee7c3bf90f1e3c0ca11f0492bea946e73008e6f91128311 | Python | 3,740 | 110 | import warnings
import numpy as np
import torch,os,pickle,time
from os.path import join
from tqdm import tqdm
from torch.nn import DataParallel as DP
from tools import *
np.set_printoptions(suppress=True)
import warnings
warnings.filterwarnings("ignore")
import multiprocessing
multiprocessing.set_start_method('spawn'... |
ff14416782e02f4a532a8ca1d87f486ecea627a72ee1669bcabac4d9696d33b0 | Python | 3,740 | 100 | # 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, sof... |
1c13e8f8fda642b5d7346208fd875d1489e79405a6e7fb1329e6f30f45679454 | Python | 3,741 | 110 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import numpy as np
from utils import *
from lookahead import Lookahead
class Net(nn.Module):
def __init__(self, protein_dim, hid_dim, dropout, device):
super().__init__()
self.device = device
... |
0f89f842d0feebb4e70c6c871d686a4091ad629e2c5e1c78e7b14cec374d6042 | Python | 3,742 | 79 | import numpy as np
import visionloader as vl
import argparse
import lib.data_utils.cosine_similarity as cossim
from lib.dataset_config_parser.dataset_config_parser import read_config_file, SettingsSection
import lib.dataset_config_parser.dataset_config_parser as dcp
from typing import List, Dict
from tabulate impor... |
71b0e2c522cb759faf7d0c70c1649936ddaf7b52783c3352ffb24c99f91fefb6 | Python | 3,742 | 118 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""aihwkit example 34: Matrix-Vector Multiplication (MVM) with ReRAM CMO.
Single matrix-vector multiplication of an analog matrix of size 64x64.
MVM accuracy is... |
b0738b90b5b7581606e685e7f7189c938f6475d5f672743fda27aef6bb62234f | Python | 3,743 | 103 | # project dependencies
from deepface.commons import package_utils, weight_utils
from deepface.models.FacialRecognition import FacialRecognition
from deepface.commons.logger import Logger
logger = Logger()
# --------------------------------
# dependency configuration
tf_major = package_utils.get_tf_major_version()
tf... |
fff2aa72ea65b78a46ed5b2f400398b95e502ca0b43535da7e77cbe0a00461d6 | Python | 3,743 | 127 | """
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 argparse
from pathlib import Path
import yaml
from ase.io import read
from atomate2.vasp.files ... |
2a32a1dc52e47eeaa3b9f72d9cc460d3835ebd1808baa12f28776aacc328e396 | Python | 3,745 | 145 | import serial
import time
pump_ser = serial.Serial('COM11') # ttyACM1 for Arduino board
pump_ser.timeout=2
readOut = 0 #chars waiting from laser range finder
def trigger_pump():
commandToSend = '10RUN 1\x0D'
print("Writing: ", commandToSend)
pump_ser.write(commandToSend.encode())
# re... |
7adfd8e02114cdfc1a1f32479cd7c7607df652e75f5452146bb891894ad417f4 | Python | 3,745 | 145 | import sys
import pytest
from ci.ray_ci.doc.check_docstring_only import (
_parse_name_status,
check_changes,
check_file,
)
_BEFORE = '''"""Module docstring."""
import os
class Thing:
"""A thing."""
def run(self, x):
"""Run it.
Examples:
>>> Thing().run(1)
... |
26381647c2af396f756ff7e09b24bfd8ec03385bc405a5ae710dd92f16b55cf6 | Python | 3,746 | 140 | from __future__ import division
from time import sleep
import numpy as np
import numpy.ma as ma
from sys import platform
from sklearn.utils.validation import check_array
from scipy import linalg
def _impose_f_order(X):
"""Helper Function"""
# important to access flags instead of calling np.isfortran,
# ... |
57b6da550b84342f849c2f65141e120474130087189f1b7669c8657dea808f10 | Python | 3,746 | 104 | from fractions import Fraction
import numpy as np
import pytest
from stl import mesh
from .test_mesh_mass_conversion import box, box_properties
from .test_mesh_mass_mixed import subdivide
@pytest.mark.parametrize('axis', [0, 1, 2])
@pytest.mark.parametrize('density', [0.0, 0.7, -2.3])
def test_nearly_coplanar_soli... |
8f64c0e7a355aa3d01ae02857a04a6ccda684735b1f1b92a7b4aa994cc342e38 | Python | 3,746 | 93 | from transformers import AutoTokenizer, AutoModel, AutoConfig, AutoModelForTokenClassification, \
TokenClassificationPipeline
import torch
import multiprocessing
class BioProcessor:
def __init__(self, model_name):
# If there's a GPU available...
if torch.cuda.is_available():
# Tel... |
9dcce7e39a84f80f656b4fae0d597914755dcd9e5bd9bb2527941a86f5a1dff9 | Python | 3,746 | 95 | import os
import sys
project_root = '/ccb/cybertron/khchao/splam-analysis-results/'
input_file_dir = f'{project_root}train/results/MANE/BAM_REF_Intersection/'
output_dir = f'{project_root}train/results/MANE/INPUTS/'
def main():
SEQ_LEN = sys.argv[1]
HALF_SEQ_LEN = int(SEQ_LEN) // 2
QUATER_SEQ_LEN = int(S... |
47beacca24a68bf1f9a03a31f4da618cd3e9d61d7f02e3393fc5b758895fb2fb | Python | 3,747 | 98 | import argparse
import pickle
import numpy as np
import torch
import lib.data_utils.data_util as du
import lib.dataset_config_parser.dataset_config_parser as dcp
from eval_fns.eval import MaskedMSELoss, apply_masked_mse
from lib.data_utils.sta_metadata import compute_convex_hull_of_mask
from lib.dataset_config_parse... |
ce75ad43a5f5bb8687deb41bac5ca15521ec92e241650ccac8fdb9f1876e1aed | Python | 3,747 | 124 | # %%
# from ast import Return
from pathlib import Path
from typing import Tuple
import pandas as pd
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from matplotlib import pyplot as plt
from PIL import Image
# %%
__all__ = ["plot_GCAM_from_csv_top_tiles_"]
def _get_GCAM_map(img, model:... |
38cffeedda3af14bad70cbb95e643e03a7f77b733e658e24fb15fd8d3f29f9db | Python | 3,748 | 121 | # built-in dependencies
from typing import TypedDict, Type, Dict
# project dependencies
from deepface.modules.database.types import Database
from deepface.modules.database.postgres import PostgresClient
from deepface.modules.database.pgvector import PGVectorClient
from deepface.modules.database.mongo import MongoDbCli... |
73122314522523d758967ac8b49f7a721184788ad1416021ef2c1cbc646456ff | Python | 3,748 | 82 | ####################################################################################################
# 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... |
a806c561c3870349a45a7c9b5eaed0fb8f198619f81ade92e91e36b2f6684510 | Python | 3,749 | 101 | # -*- 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.
#... |
432d5fcef12f05258d61fd300e5f8cdc6798c9350ff3b0a0d5920e0eeb212b38 | Python | 3,750 | 88 | # 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... |
8134bca4639cf9dc30b4f4dc52ea418bf0c55e7e2e698191be4b41ca548000c8 | Python | 3,750 | 122 | import logging
import os
from functools import lru_cache
from importlib.util import find_spec
from typing import List, Optional, Tuple
from ray._private.accelerators.accelerator import AcceleratorManager
from ray._private.ray_constants import env_bool
logger = logging.getLogger(__name__)
HABANA_VISIBLE_DEVICES_ENV_V... |
9c7b38ea2f129b30cf6879e0cd47f3dc585a813be0e149efb1ffe104dedc9613 | Python | 3,750 | 89 | import numpy as np
import torch
import torch.nn as nn
from tqdm import trange
from model import Circuit2D
class Reservoir2D:
def __init__(self, batch, Nx, Ny, N_out, V_min=11, V_max=13, Cth_factor=1.0, noise_strength=0.001):
super().__init__()
self.batch = batch
self.Nx = Nx
... |
dd50d63ca1f4cc5c9b950136538576a79fa1671bf6aa26fb6ecaf6e20d85aada | Python | 3,750 | 95 | #!/usr/local/bin/ipython -i
from mozaik.experiments import *
from mozaik.experiments.vision import *
from mozaik.sheets.population_selector import RCRandomPercentage
from parameters import ParameterSet
def create_experiments(model):
return [
# Lets kick the network up into activation
# Spontaneo... |
1e3e8e6af80cc5c46d41728fc78f04c98a8de2540b97f3eb1d24fe6d90a2f2c8 | Python | 3,751 | 95 | ####################################################################################################
# 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... |
320743bc27c88be9f44d578244f592f8c9e09eeb847067d6e3eedfaeb09ea0c2 | Python | 3,751 | 133 | import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# from matplotlib.colors import LogNorm
import seaborn as sns
from utils import load_pickle, read_lines, save_tsv
def get_data(prefix0, prefix1):
labels0 = load_pickle(prefix0+'labels.pickle')
labels1 = load_pickle(prefix1+'la... |
86e17310bea410fc76175fc497c3f6beee4177c9792695e6f53f78675dae50b8 | Python | 3,753 | 91 | from Bio import SeqIO
from Bio.SeqUtils.ProtParam import ProteinAnalysis
import numpy as np
import pandas as pd
from math import pow
from itertools import product
# Read a multi-FASTA file and return a list of protein SeqRecords
def read_fasta(fasta_file):
return list(SeqIO.parse(fasta_file, format = "fasta"))
# ... |
8979cad88ed0bb86fff8eb66265bfabded5e749ec85183ace798767d98dbc50b | Python | 3,753 | 115 | """copy from scvi-tools/scvi/utils/_mde.py"""
from __future__ import annotations
from typing import Literal, Optional, Union
import numpy as np
import pandas as pd
try:
import torch # Optional, used for GPU acceleration
except ImportError: # pragma: no cover - optional dependency
torch = None
from scipy.sp... |
a8bbe0a3f12e4c8ce15a7378ee1a25ea2e1cc089b4eb3c577dd6da36e80dddc1 | Python | 3,753 | 112 | """
this code is modified from https://github.com/utkuozbulak/pytorch-cnn-adversarial-attacks
original author: Utku Ozbulak - github.com/utkuozbulak
"""
import sys
sys.path.append("..")
import os
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
# from src.utils import tensor2cuda... |
bed408683441d4491d518df43370adeea9c8a08bbb1f961e293e4e9b6147355f | Python | 3,754 | 116 | import sys
import networkx as nx
# Add package path
packagepath = '../kcorePercolation' # Manually specify the path to your script
sys.path.append(packagepath)
from utils import kcorePercolation as kp # Import custom utility functions
def GetfailedGCC(G, removed_node_set):
'''
Calculate the size of the large... |
20d68d5bdd6b1bbf39879f8d5d557d4873d9b2331971cdd1ac2ce73ba0eae9be | Python | 3,755 | 122 | from collections import Counter
import pytest
import ray
from ray.air import ResourceRequest
from ray.air.execution import FixedResourceManager, PlacementGroupResourceManager
from ray.air.execution._internal.actor_manager import RayActorManager
RESOURCE_MANAGERS = [FixedResourceManager, PlacementGroupResourceManager... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.