sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
0718f92a4fc5556dd91844b365bf0ae175eebefd748651ccc1a7ed86d63214d3 | Python | 2,692 | 95 | # __actor_checkpointing_manual_restart_begin__
import os
import sys
import ray
import json
import tempfile
import shutil
@ray.remote(num_cpus=1)
class Worker:
def __init__(self):
self.state = {"num_tasks_executed": 0}
def execute_task(self, crash=False):
if crash:
sys.exit(1)
... |
928c56b35d72fc49c21095aa1c549e26b98197cdfff4ed7ce0d9787f150e8366 | Python | 2,692 | 66 | import numpy as np
import tensorflow as tf
from official.vision.beta.projects.movinet.modeling import movinet, movinet_model
hidden_units = 256
dropout_rate = 0.5
def create_movinet_classifier(
n_input_frames,
batch_size,
checkpoint_dir,
num_classes,
freeze_backbone=False
):
... |
4f07e4921e75ffe9a2e6c9698b4674b00954c42dc2ce745371f4fc294c728684 | Python | 2,693 | 69 | # -*- coding: utf-8 -*-
"""
This is implementation of model of corresponding to the article `Large scale model of cat primary visual cortex`.
Antolík, J., Cagnol, R., Rózsa, T., Monier, C., Frégnac, Y., & Davison, A. P. (2024).
PLOS Computational Biolology.
https://pmc.ncbi.nlm.nih.gov/articles/PMC11371232
"""
import m... |
bf694fddc4222957af4183b29b44d1b41e19098909ae5ba286541e28b91e8d21 | Python | 2,694 | 80 | #!/usr/bin/python
import tensorflow as tf
import layer
import speech_data
from speech_data import Source,Target
learning_rate = 0.001
training_iters = 300000
batch_size = 64
# BASELINE toy net
def simple_dense(net): # best with lr ~0.001
# type: (layer.net) -> None
# net.dense(hidden=200,depth=8,dropout=False) # ... |
8cabb54b293ac4a34c08160eb44db2a16d3c72507b365b557b09927b1180ac32 | Python | 2,695 | 76 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Relax the fMRI requirement to increase sample size to improve factor analysis.
Get corresponding cognitive scores.
Adapts code from:
https://github.com/adolphslab/HCP_MRI-behavior/blob/master/intelligence.ipynb
Output:
cogscores.csv Contains 10 cognitive scores with e... |
8d9b71651bc173db7e5545b4e9afc353c7590bb53c8fb4b7fe868ce018f83da3 | Python | 2,695 | 73 | from typing import Dict, List
from ray._common.utils import binary_to_hex
from ray._raylet import GcsClient
from ray.autoscaler._private.util import format_readonly_node_type
from ray.autoscaler.v2.instance_manager.node_provider import (
CloudInstance,
CloudInstanceId,
CloudInstanceProviderError,
IClou... |
ac306d0185ad04cbbba668c72eda7ebf0fdef7cb48392b6f8ce283dc66293989 | Python | 2,696 | 63 | import numpy as np
import os
import struct
import torch
import shutil
import copy
def load_model(model,model_path,device:str='cpu'):
if hasattr(model, "net"):
files = os.listdir(model_path)
for file in files:
file_path = os.path.join(model_path,file)
with open(file_path, 'rb... |
fb43cb205461ee6698da6c224ef6c6e2398963ef46b8ac6abcfb983295c8aba5 | Python | 2,697 | 75 | from torch.nn import Module, BatchNorm1d, LazyBatchNorm1d, ReLU, LeakyReLU, Conv1d, LazyConv1d, ModuleList, Softmax, Sigmoid, Flatten, Dropout2d, Linear
import numpy as np
CL_max = 10000
CARDINALITY_ITEM = 16
class ResidualUnit(Module):
def __init__(self, l, w, ar, bot_mul=1):
super().__init__()
... |
01426c657a4ed952712a7f035a9592b8ea56b7da38537057def70eeabd57d530 | Python | 2,699 | 93 | import numpy as np
class PETracker():
def __init__(self, t_max):
self.t_max = t_max
self.n_context = 0
self.pe = {t: None for t in range(t_max)}
self.tracker = {}
self.add_context()
def track_dict_for_one_context(self):
return {t:[] for t in range(self.t_max)}
... |
7ee72afd55725c8c82c57d86d72a3d265126e543b0a081134fc6f9d146109fa2 | Python | 2,699 | 68 | # -*- coding: utf-8 -*-
"""
This is the implementation of the model corresponding to the pre-print `Iso-orientation bias of layer 2/3 connections: the unifying mechanism of spontaneous, visually and optogenetically driven V1 dynamics`
Rózsa, T., Cagnol, R., Antolík, J. (2024).
https://www.biorxiv.org/ TODO: Update
"""
... |
8546ab657d197320dd2940fac956307e1e24f0d4c0522fa5752f8135ea279a21 | Python | 2,699 | 95 | # stdlib dependencies
from typing import Any, List, Union
# 3rd party dependencies
import torch
from numpy.typing import NDArray
# project dependencies
from deepface.commons import weight_utils
from deepface.models.demography.DemographyUtils import RACE_LABELS
from deepface.models.demography.pytorch.TorchDemography i... |
72e23fc3b211f4a12267e857e8413fdaed0c15e7d031b47141e8462e03121b7d | Python | 2,700 | 99 | """
Extract globs from a Wanda-cached image to a local directory.
"""
import os
import shutil
import tempfile
from pathlib import Path
import click
from ci.ray_ci.automation.crane_lib import CraneError, call_crane_export
from ci.ray_ci.utils import ecr_docker_login, logger
@click.command()
@click.option(
"--wa... |
ff88ef801b351bfa94f0b1f97bbaf1654629a980132eae5b976c6308d6125f98 | Python | 2,700 | 84 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
def get_embs_labels(emb_path, labels_path):
embs = np.load(emb_path)
with open(labels_path) as file:
labels = [line.rstrip() for line in file]
return embs, labels... |
d3a720969173d3feb07217bbe69fbcd19211d4abfc6a0cbf50cc3527edbf5303 | Python | 2,701 | 65 | from matplotlib import pyplot as plt
def plot_metrics(cv_score,
figsize=(8, 5),
linewidth=1,
color=('black', 'black'),
legend_loc=2,
fontsize=12,
title="",
prob_lines=False,
save_fig... |
dfcac0f9f6c788b67a0b0b5065082d8a6c0d809f8f7c2686ead90b021bbf5096 | Python | 2,701 | 83 | #!/bin/python
import argparse
import gzip
import pysam
from svtk.utils import get_called_samples
def load_unknown_sex_samples(ped_path):
unknown_samples = set()
with open(ped_path, 'r') as ped:
for line in ped:
columns = line.strip().split()
if not columns:
co... |
d0f8df20536abd3b2ab01e19f7f61ccc1e5cf1dae8e7c191a39875d7e469b974 | Python | 2,703 | 69 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import numpy as np
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
import pandas as pd
i... |
e4f03126ad3c27ca02bf64caea40e9973c513482159d8ced7d6e233f695827f6 | Python | 2,703 | 77 | import os
import pandas as pd
chrs = """
1 248,956,422 CM000663.2 NC_000001.11
2 242,193,529 CM000664.2 NC_000002.12
3 198,295,559 CM000665.2 NC_000003.12
4 190,214,555 CM000666.2 NC_000004.12
5 181,538,259 CM000667.2 NC_000005.10
6 170,805,979 CM000668.2 NC_000006.12
7 159,345,973 CM000669.2 NC_000007.14
8 145,138,63... |
52e10dbc7dc7fa5b951c8b062b3fff58a30d88e950f2f74825f713fd3acb50fc | Python | 2,704 | 59 | import re
import sys
import os
from collections import defaultdict
from subprocess import Popen,PIPE
def train_NN_parallel(path_to_coords, path_to_glmpca, hidden_spatial, hidden_expression,
output_dir, conda_environment, path_to_conda_folder,
epochs=10000, checkpoint=500, o... |
a10eb48d70cfda897af280badd32d82e20450e8f71b7b9b93ed9402f71095622 | Python | 2,704 | 91 | """
Generate a large batch of image samples from a model and save them as a large
numpy array. This can be used to produce samples for FID evaluation.
"""
import argparse
import numpy as np
import torch as th
import torch.distributed as dist
import random
from .guided_diffusion import dist_util, logger
from .guided_d... |
afa976a4f9b6f648192cf66721fdf8c6297ca13b6f62af53d4e4e6c9c80cb75d | Python | 2,704 | 97 | from scipy.io import loadmat
from scipy.special import erfcinv
import numpy as np
import pandas as pd
from scipy.stats import kruskal
from itertools import combinations
from matplotlib import pyplot as plt
def star(p_val):
assert 0 <= p_val <= 1
if p_val >= 0.05:
return 'ns'
if p_val >= 0.01:
... |
44dde3ab4aaa15b0fb2d03448479420ad59f4186bbad92bb8b7182e819c229ef | Python | 2,705 | 74 | import sys, os
sys.path.insert(0, os.getcwd())
from src.models import get_model, get_trainer
import torch
from src.dataset.electrolytes import load_dset_electrolyte
import torch.optim as optim
from src.utils.argparser import parse_ecg_args, save_args
from src.utils.random import merge_configs
import numpy as np
if ... |
9dd7dcced98b2dc6b80c3faf9cbc4603c3b1782fb9dd798da8e5ea1a30d28623 | Python | 2,705 | 77 | # Taken from https://pypi.org/project/ipynbname/
# TODO: add them to licence
from notebook import notebookapp
import urllib, json, os, ipykernel, ntpath
FILE_ERROR = "Can't identify the notebook {}."
CONN_ERROR = "Unable to access server;\n \
+ ipynbname requires either no security or token based security... |
44b8c34251b2558e8f93f2f2c2023f573eae625d81b0e30dc0e444af47eb20a3 | Python | 2,708 | 74 | import numpy as np
from os import path
from matplotlib import rcParams
from samri.utilities import bids_substitution_iterator
from samri.plotting import maps
def multipage_plot(results, subjects,
page_rows=4,
template='/usr/share/mouse-brain-templates/dsurqec_40micron_masked.nii',
base_cut_coords=[None],
save_as="... |
e631cf097212e6dc9465922168758585315f4558375a63312cbeb021b75b5042 | Python | 2,708 | 81 |
import math
import os
import numpy as np
from tensorflow import keras as k
import tensorflow as tf
import random
def extract_patches(img, num_patches=None, w_path=None, tile_name=None, patch_size=[512, 512], do_save=False):
stride = patch_size
img_size = np.shape(img)
height, width = img_si... |
43f19ed9fee4f6bd646ce49fd9bfccd08969e6b7a9c9ac3d1aad0fc88f2b644b | Python | 2,709 | 89 | # Generated by Django 4.1.6 on 2023-05-26 03:16
import datetime
from django.db import migrations
def create_weights(apps, schema_editor):
Architecture = apps.get_model("infer", "Architecture")
architecture = Architecture(name="INTREPPPID", version=1)
architecture.save()
architecture2 = Architecture... |
be1dca320fc03bcb3376bc838f05d203e5d3387aaa49ee01409185bacee6581c | Python | 2,709 | 81 | # Ultralytics YOLO 🚀, GPL-3.0 license
import subprocess
from pathlib import Path
from ultralytics.yolo.utils import LINUX, ONLINE, ROOT, SETTINGS
MODEL = Path(SETTINGS['weights_dir']) / 'yolov8n'
CFG = 'yolov8n'
def run(cmd):
# Run a subprocess command with check=True
subprocess.run(cmd.split(), check=Tru... |
08bb28f1445166d4d715e0e00f5ff4959cc744302cbd9fe062001b9f9332640f | Python | 2,710 | 65 | from django.contrib import admin
from .models import Sentence, Item, Tweet, TwitterUser
class ItemAdmin(admin.ModelAdmin):
list_display = ('id', 'main_topic', 'main_claim', 'original_rating', 'title')
list_editable = ['main_topic', 'main_claim']
list_filter = ['review_level', 'skip_validations']
# li... |
33a2fc920d1953f44991be0f4d94410e9924e5128f3c2e82bbb65e2ec0a91049 | Python | 2,711 | 80 | # 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... |
5b319c895e6152accb52f4149afb5117d41777613f5a60b22abc7f62f1397c46 | Python | 2,711 | 75 | import torch
import torch.nn.functional as F
from ..base import Transform, as_range, randn, uniform
from ..ops import interp
class TimeStretch(Transform):
"""Stretch the signal in time by a random factor, keeping its length.
A factor k > 1 lengthens all intervals (lower heart rate) and keeps a random
wi... |
13c4f63e0dd4350b90f5f1db15d528767d2d41eef2645c8e0e0f22472b54aae5 | Python | 2,712 | 63 | import os
from os.path import join as opj
from os.path import dirname as opd
from os.path import basename as opb
from os.path import splitext as ops
from typing import List
from omegaconf import OmegaConf
import time
import argparse
import shutil
import subprocess
from utils.misc import omegaconf2dotlist, CONCAT, omega... |
95cbde5b462b6f1aa57706d2bf970b84b77a1aa37faf35dd43221ac9ce8e36d5 | Python | 2,714 | 72 | import os
import re
import pandas as pd
from io import StringIO
from pandas_plink import read_plink1_bin
def samplot(names, cram, fasta, chro, start, end, ty, outname, expand=False):
if expand: # whether to expand range
length = int(end) - int(start)
start = str(int(start) - length)
end =... |
afc7e110cdf6b2147e5fcbdb7df4d78c41872a6f168e46189d7be13d4df906cc | Python | 2,715 | 68 | 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 FastAPLoss(BaseMetricLossFunction):
def __init__(self, num_bins=10, **kwargs):
super().__... |
742d51816bc06dff2dbc671dbb8c6498b30503e9ef55ad2a0beededb7be4b97a | Python | 2,716 | 63 | ####################################################################################################
# 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... |
8a8dab499303e79573ed502a07ee844caa02cd846cd3a0d59a337ebff21d8be4 | Python | 2,716 | 80 | # Copyright (C) 2021-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from allauth.account import app_settings as allauth_settings
from dj_rest_auth.views import (
LogoutView,
PasswordChangeView,
PasswordResetConfirmView,
PasswordResetView,
)
from django.conf ... |
dd9b0b60ac086675dffba889b6e45a2c7827626a10dfdced7257afa03aa77feb | Python | 2,716 | 90 | from os.path import splitext
from os import listdir
import numpy as np
from glob import glob
import torch
from torch.utils.data import Dataset
import logging
from PIL import Image
import os
class BasicDataset(Dataset):
def __init__(self, root, scale=1, direction='AtoB',norm='std'):
# self.imgs_dir = imgs... |
b9a23e9e6ab5dd546342168a1d9ce107651cbd94c82fd03ee15e0b7aef401fef | Python | 2,717 | 59 | ####################################################################################################
# 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... |
bb9e37b7c4ca59661fa9a872aa1e1957c8664055903788e00eda86206682a361 | Python | 2,717 | 69 | from spacy import util
class Entities:
def __init__(self, doc):
self.doc = doc
self.ents = []
def __len__(self):
return len(self.doc.ents)
def sort_entities(self):
self.ents = sorted(self.ents, key=lambda k: k['start'])
def append_new_entities(self, entities):
... |
de6d22fe2e18b5b52ec7a5d9b238636ed38b1aef7e7dedf60e4f23eb4bda5732 | Python | 2,718 | 74 | import random
import unittest
import torch
from rising.random import DiscreteParameter
from rising.transforms import CenterCrop, RandomCrop
from rising.transforms.functional import center_crop, random_crop
class TestCrop(unittest.TestCase):
def setUp(self) -> None:
data = torch.zeros(1, 1, 10, 10)
... |
b5251f323eb0ea96924052cb3eaa233a002fff3e4ce3e47a8adb99c805ce9346 | Python | 2,719 | 72 | ####################################################################################################
# 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... |
4944cd880adcebe8293b30656250f810a176ff8c25f879d8c3392c51a0c29d48 | Python | 2,720 | 95 | # Copyright 2015-2017 Allen Institute for Brain Science
# This file is part of Allen SDK.
#
# Allen SDK 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, version 3 of the License.
#
# Allen SDK is distributed in... |
e18788ee294263b7d3e2a73a40397c9a96bd15c027d9d55d5cc05cef582c8380 | Python | 2,720 | 77 | import torch
import torch.nn as nn
import inspect
import functools
def store_config_args(func):
"""
Class-method decorator that saves every argument provided to the
function as a dictionary in 'self.config'. This is used to assist
model loading - see LoadableModel.
"""
attrs, varargs, varkw, ... |
8fcc421f1cab766b31fc7a566fcfd8c5a25adbaa1e35baa3ce976c48fd404da2 | Python | 2,722 | 87 | import numpy as np
import pandas as pd
import pytest
from data_profiling.config import Settings
from data_profiling.model.pandas.correlations_pandas import (
auto_compute as pandas_auto_compute,
)
from data_profiling.model.pandas.correlations_pandas import (
cramers_compute as pandas_cramers_compute,
)
from da... |
ae6e1c580f0aeb57ab8e83f46735926655b2c2f7dea6d4da68e331f4ce56923a | Python | 2,722 | 112 | # -*- coding: utf-8 -*-
"""
"""
import numpy as np
import matplotlib.pylab as plt
import sys
import os
from pathlib import Path
from vtkplotlib._get_vtk import vtk, numpy_to_vtk
#points = vtk_to_numpy(image_data.GetPointData().GetArray(0))
#shape = image_data.GetDimensions()[:-1]
#shape = shape[::-1] + (points.shape... |
fadb90de5e3ffc215da8a06c2f1f0c32b0ed78a9e26746e6f7600e15bf6a46df | Python | 2,723 | 72 | import os
import subprocess
path = "./"
gpus = 4
available = [i for i in range(gpus)]
seed_list = [1111 * i for i in range(1, 5)]
cnt = 0
def multi_task(path, parameters):
global cnt
for r in parameters["ratio"]:
for se in parameters["seed"]:
for mo in parameters["model"]:
... |
7357cfba7e426a4e3ef5e912dc34ae2ce842f16ed9e7547e1f9f3f08e56705b9 | Python | 2,724 | 93 | import numpy as np
# Range of MU depth and MU angle within each muscle
DEPTH = {
'ECRB': [0.0130, 0.0220],
'ECRL': [0.0085, 0.0153],
'PL': [0.0071, 0.0114],
'FCU_u': [0.0084, 0.0168],
'FCU_h': [0.0074, 0.0165],
'ECU': [0.0092, 0.0168],
'EDI': [0.0079, 0.0171],
'FDSI': [0.0169, 0.0231],... |
9dcf1e9147a07cfd9c598894c45f854d9cd80dd61709c816c79d847d9140c232 | Python | 2,724 | 69 | # -*- coding: utf-8 -*-
"""
This is implementation of model of self-sustained activitity in balanced networks from:
Vogels, T. P., & Abbott, L. F. (2005).
Signal propagation and logic gating in networks of integrate-and-fire neurons.
The Journal of neuroscience : the official journal of the Society for Neuroscience,... |
f18d10e5b52096b6bfa6fe8c5fbb50200187d11d4964c8a744eaabb76b1827d2 | Python | 2,725 | 94 | from enum import Enum
from spinnaker2.configuration import PEConfig, ExperimentConfig, MemoryRegion, Experiment
from spinnaker2.coordinates import WordAddr
class BaseApplication(object):
"""
Base class for SpiNNaker2 PE applications
Attributes:
name: application name
mem_file: path to instruct... |
16055bdf1a5d337acf7b8d61ceaa27d5a9b80a7da8846625f20af1e66120da97 | Python | 2,726 | 91 | import numpy as np
import pytest
from neuropower import neuropowermodels
def test_AltPDF_RFT():
x = neuropowermodels.altPDF(peaks=[4.0], mu=3.0, sigma=1.0, exc=2.0, method="RFT")
assert np.around(x, decimals=2)[0] == 0.29
def test_AltPDF_CS():
x = neuropowermodels.altPDF(peaks=[4.0], mu=3.0, method="CS... |
3c7a68593d46fef5f25ef0b172ddb930fb8c91fa5f4a9c66dc9aff050d0f4e7d | Python | 2,729 | 84 | """
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 torch
import torch.nn as nn
# Different encodings for the atom distance embeddings
class Gauss... |
73e91f6b940c1c53bf8c58491fdb536a10408be3f43266999cb8cebf1edf0321 | Python | 2,729 | 27 | """Compare independently recorded baseline and candidate arrays; enforce frozen limits."""
import argparse,json
from pathlib import Path
import numpy as np
parser=argparse.ArgumentParser();parser.add_argument('baseline',type=Path);parser.add_argument('candidate',type=Path);parser.add_argument('output',type=Path);args=p... |
8dc27e2b4468ebd225850d12d38ac09cdad04991193a8f011d4dc505b779333b | Python | 2,730 | 84 | """Utilities for working with classes."""
from copy import deepcopy
from typing import Any, Dict, Optional, Type
from warnings import warn
def find_subclass(cls: Type, target_subclass_name: str) -> Optional[Type]:
"""
Recursively search for the target subclass.
Args:
cls: The base class to start... |
90d91fad04e05aa1e5bb2ddd4bfe634b54fe09d06816ff256d52a6333f2de113 | Python | 2,730 | 80 | # -*- 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.
#... |
fddac8c0bf9461c0ab466f90502cc6903667ecdac4032ab718d16b9cd56639ae | Python | 2,730 | 101 | import numpy as np
import tonic
import torch
import torch.nn as nn
from sinabs import layers, set_batch_size
from sinabs.backend.dynapcnn import DynapcnnNetwork
from sinabs.backend.dynapcnn.chip_factory import ChipFactory
from sinabs.nir import from_nir
import nir
def xytp_collate(batch):
samples = []
target... |
ff2ef0f3eaf34dd5789465d0fdc3c2baa6861022ceea16f7dc441ce337b405aa | Python | 2,730 | 102 | #!/usr/bin/env python
"""
Collect PE file metrics. Writes stats to stdout.
Metrics:
pe_LL_<sample> : number of records with LL orientation
pe_RR_<sample> : number of records with RR orientation
pe_RL_<sample> : number of records with RL orientation
pe_LR_<sample> : number of records with LR or... |
051dfb5515b9c38e6568323019c83d6351de4f28fffff40d05569e4ac0313c61 | Python | 2,731 | 88 | """
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 json
import logging
from pathlib import Path
from typing import Union
import torch
import torch... |
2d8a9f43713b4173dea32bbf879bd5b30808977e1b03ceb724cca53fe2abad33 | Python | 2,732 | 71 | import os
import subprocess
from conf_build import VERSION, vVERSION
#---- Define tag name and description
tag_name = vVERSION
tag_message = f"Version {VERSION}"
release_message = f"Version {VERSION}"
# command must be executed in root folder of repository
os.chdir("..")
print(f"Working Directory: {os.getcwd()}",)
... |
4aaa39fe41369996c3fb061a9c23de1dd1202d3e8a244f46c7bc31f9de10377f | Python | 2,732 | 63 | import torch
import tqdm
from ..utils import common_functions as c_f
from ..testers.global_embedding_space import GlobalEmbeddingSpaceTester
class GlobalTwoStreamEmbeddingSpaceTester(GlobalEmbeddingSpaceTester):
def compute_all_embeddings(self, dataloader, trunk_model, embedder_model):
s, e = 0, 0
... |
9cca933f95763453cbbe6acada7e3a8f1eab6e4c4a5bf64f2ed362d4206940ee | Python | 2,732 | 67 | # -*- coding: utf-8 -*-
"""Generate estimated timestamps for Zeiss SIM data where the timestamps for raw images are not recorded."""
from absl import flags
from absl import app
import numpy as np
import csv
from aicsimageio.readers.czi_reader import CziReader
FLAGS = flags.FLAGS
def define_flags():
flags.DEFINE... |
14b81193b6c62f415bb20e3bd6e1d8b5aee9e6a87346e5a9a87d19c6d0294150 | Python | 2,733 | 86 | import torch
from torch import nn
from torch.nn import functional as F
import extractors
class PSPModule(nn.Module):
def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):
super().__init__()
self.stages = []
self.stages = nn.ModuleList([self._make_stage(features, size) for s... |
9fe35bac435fefa749736753119060ec0e7e85d119ff902f3d8a733935fd3df0 | Python | 2,733 | 95 | import pdb
from pickletools import optimize
import numpy as np
import torch
import torch.optim as optim
class Optimizer():
def __init__(
self,
model: torch.nn.Module,
args: dict,
) -> None:
self.model = model
self.args = args
self.encoder = torch.optim.Ad... |
50e89608fd6198e63a9f168e60ee51056f1b8b1bf3ed81acc6039348a67d2bda | Python | 2,734 | 69 | """Class allowing for better multiple training runs."""
from torch_pgn.load_data import process_raw
from torch_pgn.data.load_data import load_proximity_graphs
from torch_pgn.train.train_model import train_model
from torch_pgn.train.train_utils import load_checkpoint
from torch_pgn.train.cross_validate_model import cros... |
a4c1ff2763b7ade8b643eadf2a7a278b7ed498ce5f0d6077e2321fca484da436 | Python | 2,735 | 88 | """Cartesian frame animation."""
from time import sleep
from typing import List, Optional
import matplotlib.pyplot as plt
import numpy as np
from ..visualization import plt_utils
from .animations import Animation
class Imshow(Animation):
"""Animates an array of images using imshow.
Args:
images: A... |
bcc14a841428dceeb27112f712fc486b7dba30b6d7d4166f9deec4bf2d753acf | Python | 2,735 | 85 | import os
from skorch.utils import to_device
import torch
from torch.autograd import Variable
class Dictionary:
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.w... |
2c963d2a4ed003551f64e3800563b7ccf7d6fa7a83f1b5f7dfda708a57ce4618 | Python | 2,736 | 68 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 19 10:55:00 2020
@author: ju-bar
Image data manipulation routines
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishing License, version 3
"""
# %%
from numba import jit # include compilation support
imp... |
7ed4f1fc870cb553b7ba90c69a2e829784bb4891141edb1c3116ea94972ddd69 | Python | 2,737 | 111 | import timeit
import unittest
import numpy as np
import pytest
from scipy import stats
from pfrl.utils.random import sample_n_k
@pytest.mark.parametrize(
"n,k", [(2, 2), (5, 1), (5, 4), (7, 2), (20, 10), (100, 5), (1, 0), (0, 0)]
)
class TestSampleNK:
@pytest.fixture(autouse=True)
def setUp(self, n, k):... |
abf18c73899c1ae2e52dce12674e6d8ea9df1b13f228fb4d681880e1e999a166 | Python | 2,737 | 62 | ####################################################################################################
# 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... |
b8a9ff6b27a1d1065c94988880747dd619c304f45374d3f370cbcd76fffa28f9 | Python | 2,738 | 88 | _base_ = [
'../../_base_/models/ssd300.py',
'../../_base_/datasets/urpc2020/urpc2020-test-B_coco_detection.py',
'../../_base_/schedules/schedule_2x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(bbox_head=dict(num_classes=4))
# dataset settings
input_size = 300
train_pipeline = [
... |
4970c92736aadff024eadfa8565a22e59b08008e53a4441a468246b2550bc50f | Python | 2,739 | 65 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
import pandas as pd
import pyranges as pr
import pickle
import numpy as np
import json
from liftover import get_lifter
... |
3444635d6cd3e8d679e7d3f15e8610fcd8a640dd9057f8c486cb784f9b3745b2 | Python | 2,740 | 54 | import unittest
import numpy as np
from nnunetv2.experiment_planning.dataset_fingerprint.fingerprint_extractor import DatasetFingerprintExtractor
class TestDatasetFingerprintExtractor(unittest.TestCase):
def test_collect_foreground_intensities_excludes_ignore_label(self):
# issue #3055: voxels carrying ... |
cf4bb5400d86d0e80364db9efe2bbdb5ba6ad2ed947aa1e44b2103cd69547fc6 | Python | 2,741 | 116 | import numpy as np
import pytest
from data_profiling.report.formatters import (
fmt_array,
fmt_bytesize,
fmt_class,
fmt_color,
fmt_monotonic,
fmt_numeric,
)
@pytest.mark.parametrize(
"text, color, expected",
[("This is a warning", "red", '<span style="color:red">This is a warning</spa... |
9263cf68499451715a9474a551d7383429327b3a886c9f36486f2e4f312f2298 | Python | 2,742 | 88 | _base_ = [
'../../_base_/models/ssd300.py',
'../../_base_/datasets/urpc2020/urpc2020-validation_coco_detection.py',
'../../_base_/schedules/schedule_2x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(bbox_head=dict(num_classes=4))
# dataset settings
input_size = 300
train_pipeline = ... |
98589bdb1603cd8eda3616b1455f8b28d5b858eb1b032db8dbacfdc589e334fc | Python | 2,742 | 88 | _base_ = [
'../../_base_/models/ssd300.py',
'../../_base_/datasets/urpc2020/urpc2020-test-A_coco_detection.py',
'../../_base_/schedules/schedule_2x.py', '../../_base_/default_runtime.py'
]
# model settings
model = dict(bbox_head=dict(num_classes=4))
# dataset settings
input_size = 300
train_pipeline = [
... |
c6ce720a2b5190c197f185706453c4c52a02ce59388f7e29a3f5545a98abda54 | Python | 2,743 | 64 | # -*- coding: UTF-8 -*-
"""Base class and shared context for GOEA term-scoring algorithms.
A GOEA algorithm turns the per-term gene sets of a study into one uncorrected
p-value per GO term. The default, `classic`, scores every term independently.
Algorithms that exploit the GO DAG topology (`elim`) instead score terms... |
feba977c7a19bcb21701376e8482fedb1e55d330598e2ba2bfa7474981e81e13 | Python | 2,744 | 77 | from typing import List, Set, Tuple
from ray.autoscaler._private import constants
class NodeTracker:
"""Map nodes to their corresponding logs.
We need to be a little careful here. At an given point in time, node_id <->
ip can be interchangeably used, but the node_id -> ip relation is not
bijective _... |
3ff7688cd83f6ca754000da11b670894b6391cfd9e4d39bca16cf2f165f80059 | Python | 2,745 | 70 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
4bd70e97e1460836c19c6a058446c558e1549a461047c8c4579a68ab5411e68c | Python | 2,745 | 77 | # 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... |
a1bfd48d693d785b520bfe25f3c110c3d3375e540b69d6faeec43150cd040c8b | Python | 2,745 | 69 | # -*- coding: utf-8 -*-
"""
This is implementation of model of corresponding to the article `Large scale model of cat primary visual cortex`.
Antolík, J., Cagnol, R., Rózsa, T., Monier, C., Frégnac, Y., & Davison, A. P. (2024).
PLOS Computational Biolology.
https://pmc.ncbi.nlm.nih.gov/articles/PMC11371232
"""
import m... |
fcadb4d70abb3bee1cf27440886948a5b09971913a61c5d36bbdc137c30f692e | Python | 2,748 | 79 | ####################################################################################################
# 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... |
195d2521ddb27c274ff1769f8cf2fd23b87d025372105cd1e18ab0bfd1a2cc80 | Python | 2,749 | 79 | import numpy as np
import pytest
from stl import mesh
def _unit_cube():
# Closed project fixture, with analytic unit-cube moments.
from pathlib import Path
native = mesh.Mesh.from_file(
str(Path(__file__).parent / 'stl_binary/Cube.stl')
)
native.vectors[:] /= 2
return native.data, 1.... |
5c31b9c5b9705ddcc8f4071473f579b3c301f945f2023dc62d11945928fe2ca8 | Python | 2,749 | 70 | from typing import Dict, List, Union
from SPARQLWrapper import SPARQLWrapper, JSON
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i: i + n]
def get_child_node_query(value_term: str, cell_type_list: List[str]) -> str:
"""Returns a SPARQL query to retrieve child nodes of given cell typ... |
7cbb98f0f92aa09d2a615b1c28c9186412202e0c07b5481f088e7db5bc2f38c1 | Python | 2,749 | 100 | import os
import zipfile
import json
import io
import uuid
from datetime import datetime
from typing import Optional
import boto3
from harness import step_fns_ecs_harness
s3 = boto3.client("s3")
def extract_reconstruction_id(key: str):
"""The reconstruction id is the name of the upload package
"""
ret... |
fbbf9a37efbcb4a48b22f9bb640aad9ccd09d92754a037dab7118c818147fab6 | Python | 2,750 | 88 | """
This file serves as a documentation example and CI test.
Structure:
1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.
2. Docs example (between __direct_streaming_custom_router_example_start/end__): Embedded in Sphinx docs via literalinclude.
3. Test valida... |
b2ed1395efa60a8bac79ae05d6d3a7e63bb5f3ee2079824f77da5300b411c076 | Python | 2,751 | 78 | from tqdm.auto import tqdm
import hydra
import torch
import numpy as np
from pathlib import Path
import pytorch_lightning as pl
import matplotlib.pyplot as plt
from torch.nn.modules import module
import torch.nn.functional as F
from torch.distributions import Categorical
from src import utils
from einops import rearran... |
31c86c5edffbbc74dd7db2a36be7a8b4e5363101941698bfd3d4d922f12ea944 | Python | 2,752 | 40 | #---------------------------------------------------------------------------------------------------------------------------
# Author: Brandon S Coventry
# Purpose: Simple Bayesian Regression with PyMC and BAMBI. Need to install Bambi for this to work.
# Note: We recommend going through the modeling process first with ... |
aefc32d99dd54e76a0aa9c20767a74f98c57a6bae90a511e6ffdf1f2698eec1c | Python | 2,753 | 68 | # -*- coding: utf-8 -*-
"""
This is the implementation of the model corresponding to the pre-print `Iso-orientation bias of layer 2/3 connections: the unifying mechanism of spontaneous, visually and optogenetically driven V1 dynamics`
Rózsa, T., Cagnol, R., Antolík, J. (2024).
https://www.biorxiv.org/ TODO: Update
"""
... |
5caf55935ddf0a636fea5e3e4b4a0604c5eac9a05baa7bcba13ea147c26e0169 | Python | 2,754 | 66 | import inspect
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
@require_flax
class FlaxModelTesterMixin:
def test_output(self):
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
mo... |
1035086a70c435a116d182df7a26b23374cef021b80f948735803eb0710b4f5d | Python | 2,755 | 89 | """
This file serves as a documentation example and CI test.
Structure:
1. Monkeypatch setup: Ensures serve.run is non-blocking and removes accelerator requirements for CI testing.
2. Docs example (between __qwen_example_start/end__): Embedded in Sphinx docs via literalinclude.
3. Test validation (deployment status po... |
d04c0103267ae80fde8cbc36e7aca5074d845dd60af4a818e8ed25480b00bb0c | Python | 2,755 | 80 | from mmengine.utils import is_str
def coco_classes() -> list:
"""COCO Detection Dataset Classes."""
return [
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign',
'parking_meter', 'bench', 'bird', 'cat', 'do... |
19c25bba264796111150b041446e008f823a26bcf8804969119b91af662fa0d0 | Python | 2,756 | 91 | def float_to_tex(f,
max_len=4,
condensed=False,
):
"""Reformat float to tex syntax
Parameters
----------
f : float
Float to format.
max_len : int
Maximum digit length of output strings.
"""
if condensed:
model_str="{}\\!\\!\\times\\!\\!10^{{{}}}"
else:
model_str="{} \\times 10^{{{}}}"
if f >= 1... |
04f8fc1a5c63975bdf624a60907e10cf9cb969a5170ac91cd3c2d9c096868e30 | Python | 2,757 | 89 | from __future__ import annotations
from collections import defaultdict, deque
from typing import TYPE_CHECKING, DefaultDict, Deque, Optional, Set
from typing_extensions import override
from ray.data._internal.execution.bundle_queue import BaseBundleQueue
if TYPE_CHECKING:
from ray.data._internal.execution.inter... |
1d73cf013b8200404c94c191e5864e19a62706fb33d2aac5a53d64232443e410 | Python | 2,758 | 64 | ####################################################################################################
# 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... |
a661318bf438ac2384233d67efa5d69c45be8e7b7bf10c34aa1504b7dd6eec1b | Python | 2,760 | 85 | from copy import deepcopy
import nibabel as nib
import numpy as np
import pyvista as pv
from lib.surface import (
remove_nan_vertices,
write_surface_to_gifti,
)
from lib.utils import setup_logger
from scipy.spatial import cKDTree
log_file = snakemake.log[0] if snakemake.log else None
logger = setup_logger(log... |
b91be26b5e1fae32d3ac5f4eaaba38988ae695be5bf5f4d3fbd98a2c969d8ccf | Python | 2,760 | 76 | # -*- 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.
#... |
88ab489e56e68d4ad4ce51e4d3fedbaff954202275065260d96f6b87eaf31c04 | Python | 2,761 | 94 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Setup.py for `aihwkit`."""
import os
from setuptools import find_packages
from skbuild import setup
INSTALL_REQUIRES = [
"torch{}".format(os.getenv("TO... |
c482945818c4f6364ada5f38463854d1cbd141a79329d468589862b169bceb5f | Python | 2,761 | 103 | """
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
import os
from collections import defaultdict
from fairchem.data.oc.utils.vasp import ... |
cd701b4fe4caf0aed7f9dd2685f1b061dbb8fbc9fc8b363a5be65e4d1c2dd2e9 | Python | 2,761 | 82 | # 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... |
9c24231923213d5e92309c13263bc375fa158272d42c2cdf5ca7a57ec4706446 | Python | 2,764 | 100 | import torch
import torch.nn.functional as F
from torch import nn
def cosine_similarity(p, z, average=True):
p = F.normalize(p, p=2, dim=1)
z = F.normalize(z, p=2, dim=1)
loss = -(p * z).sum(dim=1)
if average:
loss = loss.mean()
return loss
class AutoEncoder(torch.nn.Module):
def __... |
2f499576c531ec3bff3248219ac2b56512192ed1ee58ac19ddc98c027e476e54 | Python | 2,765 | 55 | proj_dir = "/path/to/main_project_folder/" # edit this line
import numpy as np
import pandas as pd
import xarray as xr
import dask.array as da
import glob as glob
from functools import partial
import sys
sys.path.append(proj_dir)
from project_fxns import load_region
from project_fxns import fxns
import importlib
impor... |
dc3bc3b7d8bd6b90f9b89518071ca90937d2210de07be4f1c1caa7097ebad2eb | Python | 2,765 | 86 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import os
import pandas as pd
def build_baf_training_set(metrics):
MIN_SIZE = 5000
MAX_BLACKLIST_COV = 0.3
MAX_FAIL_SEP = 0.15
MIN_PASS_SEP = 0.40
# Remove BAF failures (variants where BAF can not be assessed due to
# ... |
0c0bb4a8e1ff0f0f6033bc4c0252931d61401871db8cec3385b05bb2b7f92718 | Python | 2,766 | 92 | import sys
import numpy as np
from einops import reduce
from utils import load_image, load_tsv, read_lines, read_string
from visual import plot_spots
# def plot_spots(cnts, locs, underground, gene_names, radius, prefix):
# under_weight = 0.2
# cmap = plt.get_cmap('turbo')
# under = underground.mean(-1, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.