sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
fc6d9e91150f47ac8c81c6ea477e9b66af1b60962a60dfaa8aaadeb8f7ee293a | Python | 1,554 | 35 | ####################################################################################################
# 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... |
24fff4f6d59bf8aa93840c6ec88001f213657d24a8b628789a5570717678fdf2 | Python | 1,555 | 59 | """
Create linear color gradients
"""
from matplotlib.colors import ColorConverter, LinearSegmentedColormap
from scipy.ndimage import gaussian_filter
import numpy as np
def linear_gradient(cstart, cend, n=10):
'''
Return a gradient list of `n` colors going from `cstart` to `cend`.
'''
s = np.array(C... |
9805a5ce52fc4be9c0076b2fc023513e5263e0955e60f7943f61832603210731 | Python | 1,555 | 48 | """
An app script to run registration between two cameras from the command line.
Copyright (C) Microsoft Corporation. All rights reserved.
"""
# Standard Libraries.
import argparse
# Calibration tools.
from camera_tools import register
# ------------------------------------------------------------------------------... |
50b61d9a46a49abe5f748b81f3e684a137709e555d85d7c34f14ee8caa1f57bd | Python | 1,557 | 37 | import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def process_and_scale(input_path, output_path):
# Read the CSV file into a DataFrame
df = pd.read_csv(input_path, sep='\t')
# Extract the first (id), third (age), and eighth (nihss) columns
selected_columns = df.iloc[:, [0, 2, 7]]
... |
9b945930ddfd69b17b50bdb2d9d8bed9ca6554e8f7a238c2da4daf67824961e3 | Python | 1,558 | 38 | import torch.nn as nn
from argparse import Namespace, ArgumentParser
from .base import BaseModelConfig
from optuna import Trial
from monai.networks.nets import UNETR
class UNETRConfig(BaseModelConfig):
model_name = "unetr"
def setup_search_space(self, trial: Trial, args: Namespace) -> Namespace:
arg... |
cb7eb65dc8a8c1b8932f675c820db3d56a7673b88a4670ce702a0b2e825b8206 | Python | 1,559 | 42 | from abc import ABC, abstractmethod
from typing import Generic, Iterator
import pyarrow as pa
from ray.data._internal.datasource_v2 import InputSplit
from ray.util.annotations import DeveloperAPI
@DeveloperAPI
class Reader(ABC, Generic[InputSplit]):
"""Abstract base class for reading data from input buckets.
... |
2da0e2c66a059d90921b160cab1fec530cf1871cbaebb9c75dcc075420c1a067 | Python | 1,560 | 56 | from __future__ import print_function
import argparse
import glob
import os
def parse_args():
parser = argparse.ArgumentParser("Computes read depth for output vcf glob from marginPhase run")
parser.add_argument('--vcf', '-v', dest='vcf_glob', default="*.vcf", type=str,
help='The VCF(s) w... |
2f075e08ff2598698f6453a047228299c1e53d3616332a0d7aeaf76677e7d23e | Python | 1,560 | 52 | # 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... |
a06ad5d1afa5af599b42bf393969ce66ff8a109b92a543a8688700f915d1f198 | Python | 1,561 | 57 | #!/usr/bin/env python
#%%
import numpy.testing as npt
import numpy as np
import os
import caiman as cm
from caiman.source_extraction import cnmf
from caiman.paths import caiman_datadir
def demo(parallel=False):
p = 2 # order of the AR model (in general 1 or 2)
if parallel:
c, dview, n_processes ... |
7835dadd1304272797d79f187dcf3844aee1cc68f32c9581540427295c49f58b | Python | 1,562 | 47 | import time
from collections import deque
from typing import Deque, Tuple
class TimeWindowAverageCalculator:
"""A utility class to calculate the average of values reported in a time window."""
def __init__(
self,
window_s: float,
):
assert window_s > 0
# Time window in sec... |
145b5ceb8a6839ded1037176c16071512fef35275bc30db9ba1f86424757d083 | Python | 1,563 | 45 | """
Test for issue 397 (actually a PR, but ok):
https://github.com/Data-Centric-AI-Community/data-profiling/pull/397
"""
import numpy as np
import pandas as pd
import data_profiling
def test_issue397():
# Note: warnings are expected with np.inf values
df = pd.DataFrame.from_dict(
{
"float... |
2ec3fdf9187cf2a3cd76dc6d7857bed80d4f6cf7bbe98c74edb5161dc6382459 | Python | 1,563 | 33 | import json
from candycrunch.cli import build_parser, main
# The in-browser CandyCrunch (Pyodide in a web worker): the page builds its settings form from parameters() and runs the CLI with run() on the files it
# mounted, reading the output files from Pyodide's file system
def parameters():
"""the CLI's options ... |
5d65167e2b3d462945786280b81744fa4bf14fb48c5f06e7fb192fe3abcaee21 | Python | 1,563 | 48 | import random
def shuffle_fasta(fasta_file, output_file):
"""
Shuffle the order of sequences in a FASTA file.
Parameters:
fasta_file (str): Path to the input FASTA file.
output_file (str): Path to the output FASTA file with shuffled sequences.
"""
# Read sequences and headers from the FAST... |
fa573ac3a0e2e176202fb8b3ab71b87c6bb861dbd08cdbc80b0d4b7eba4cb87b | Python | 1,563 | 38 | import pytest
from sklearn.model_selection import RepeatedKFold, train_test_split
from sklearn.tree import DecisionTreeClassifier
from siapy.optimizers.scorers import Scorer
def test_init_cross_validator_scorer(mock_sklearn_dataset):
X, y = mock_sklearn_dataset
scorer = Scorer.init_cross_validator_scorer()
... |
2e63a42dbec8177e8062c46cf957f6403c48269e2cbe2be2a0ddd0867197cb39 | Python | 1,564 | 51 | import torch
def MMD(
x: torch.Tensor,
y: torch.Tensor,
kernel: str,
device: str
) -> torch.Tensor:
"""
Emprical maximum mean discrepancy. The lower the result,
the more evidence that distributions are the same.
Args:
x: first sample, distribution P
y: second samp... |
c62ba25b9d3913c4d86a0ced6680a2535fe91469ee1fe7804c7036389bf3d50f | Python | 1,564 | 27 | from ..losses.angular_loss import AngularLoss
from ..losses.arcface_loss import ArcFaceLoss
from ..losses.base_metric_loss_function import BaseMetricLossFunction, MultipleLosses
from ..losses.circle_loss import CircleLoss
from ..losses.contrastive_loss import ContrastiveLoss
from ..losses.cosface_loss import CosFaceLos... |
1f844464806fdec7168c2f19c4c7278a32dd0c91147f44af35f9c4860df158f1 | Python | 1,565 | 48 | """
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 math
import torch
### Methods for sample points on a sphere
def CalcSpherePoints(num_points: ... |
722f9a28a3e69ad1f0a92367315402520cb8ac49f264be167eda72984edd2d2c | Python | 1,566 | 43 | from ..distances import CosineSimilarity
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..losses.generic_pair_loss import GenericPairLoss
class MultiSimilarityLoss(GenericPairLoss):
"""
modified from https://github.com/MalongTech/research-ms-loss/
Args:
... |
2629248c14b15a99e89aa94d9c29dc40df0f764e18798b1efbbfc700da11cca4 | Python | 1,567 | 51 | import random
import numpy as np
import torch
import sys
def neg_loss(eps=1e-10):
def loss_func(y_true: torch.tensor, y_pred: torch.tensor):
assert len(y_pred.shape) == len(y_true.shape)
#y_true = y_true*tf.math.sign(y_pred)
loss = (y_true*y_pred).mean()
return -loss
... |
6be5ca65c0e3ac7baef7ed9a4e62aa7d879c013aaa2609ea29b6deba03d4e5a6 | Python | 1,567 | 31 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: output_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_p... |
708005dce177bd262ef12654baedf614155c362e668a59bada9a7317f197a607 | Python | 1,567 | 44 | """Run with pymilvus and milvus-lite; no model weights are needed."""
from types import SimpleNamespace
import pytest
sdk = pytest.importorskip("pymilvus")
pytest.importorskip("milvus_lite")
from deepface.modules.database import milvus
def test_milvus_lite_fetches_more_than_query_limit(tmp_path, monkeypatch):
... |
b12242ca694f5c466e66377ae451003febebe6c47498a3a508ca3c86a64c3bb3 | Python | 1,567 | 40 | import os
# Reserved keys used to handle ClassMethodNode in Ray DAG building.
PARENT_CLASS_NODE_KEY = "parent_class_node"
PREV_CLASS_METHOD_CALL_KEY = "prev_class_method_call"
BIND_INDEX_KEY = "bind_index"
IS_CLASS_METHOD_OUTPUT_KEY = "is_class_method_output"
# Reserved keys used to handle CollectiveOutputNode in Ray... |
d274f6ef31fbb0276dc8bae0013a21ff1096422ed2ebe6c05df33347200f0ee9 | Python | 1,568 | 82 | import logging
from django.contrib.admin import *
from django.contrib.admin import AdminSite
from infer.models import (
Organism,
Architecture,
Weights,
Dataset,
PPIDatabase,
Protein,
AlternateProteinName,
AlternateGeneName,
GO,
)
logger = logging.getLogger(__name__)
class Rapp... |
00b1f1472bde7d655b468f714457b958bfbd5299ddfbfeca712517dbe6d49252 | Python | 1,569 | 56 | import shutil
import torch
from torch.utils.tensorboard import SummaryWriter
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
... |
2e252adeb798aec4f7cb26ae529fc3d5e68603debcc118a1cb4eeb25ad21f018 | Python | 1,570 | 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... |
2f53cb72dff74d1fc9e66eaa1da5df2c973f1fc3bce43fe1396e2ad44006eead | Python | 1,570 | 55 | import importlib
# List of modules in the 'pandas' model that should be imported explicitly
PANDAS_MODULES = [
"correlations_pandas",
"describe_generic_pandas",
"describe_boolean_pandas",
"describe_categorical_pandas",
"describe_url_pandas",
"describe_file_pandas",
"describe_text_pandas",
... |
b17b8d475b194465546253d8df27f1e6c203f2a2cb9b5d7fc39c0d100a0033b3 | Python | 1,570 | 54 | import torch.nn as nn
class Discriminator(nn.Module):
'''
output is not normalized
'''
def __init__(self, args):
super(Discriminator, self).__init__()
in_channels = args.n_colors
out_channels = 64
depth = 7
def _block(_in_channels, _out_channels, stride=1)... |
f5fa46b4e20fed1462bc536c37548d82f3e6d903ef0e42e03aa2058c110b38a0 | Python | 1,570 | 39 | import os
import nibabel as nib
import numpy as np
import ivim
root = '/tmp'
sub = 'phantom'
x = 100
n = 50
b = np.array(2*[0, 5, 10, 20, 30, 100, 200])
Delta = 10e-3
delta = 8.6e-3
seq = ivim.seq.sde.BIPOLAR
c = ivim.seq.sde.calc_c(ivim.seq.sde.G_from_b(b,Delta,delta,seq=seq),Delta,delta,seq=seq)
c[:c.size//2] = 0
... |
f7aa6ab6fe149746ca8443be28ef870b60c0bbb5e7fd8fe69bebb83672d996d0 | Python | 1,570 | 47 | """
Test for issue 72:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/72
"""
import numpy as np
import pandas as pd
import data_profiling
def test_issue72_higher():
# Showcase (and test) different ways of interfacing with config/profiling report
df = pd.DataFrame({"A": [1, 2, 3, 3]})
... |
296f963b8d06b49189930db8ccada4a04e6790aebe6367c7b1095203910dac4f | Python | 1,571 | 41 | import numpy as np
def scale_and_convert_weights_to_int8(tf_weights):
"""
convert weights from float to int8 with normalization
"""
max_abs_weight = np.abs(tf_weights).max()
weights_scaled = tf_weights*(127/max_abs_weight)
return weights_scaled.astype(np.int8)
def reorder_dense_weights_after_c... |
808a2ae3e3af1c4d5e130ec26651ca1695e44d2f19a66b018d12ae9fe484ca08 | Python | 1,571 | 70 | import numpy as np
import matplotlib.pyplot as plt
from spinnaker2 import snn, hardware
np.random.seed(42)
neuron_params = {
"threshold": 1.,
"alpha_decay": 0.9,
"i_offset": 0.0,
}
in_nrns = 1000
out_nrns = 5
keys = np.arange(in_nrns)
spike_times = [list(np.arange(0, 20, 2)) for _ in ... |
249d7b6b7c3e4156c1f12ca3cb22317d03018086fe8a650c482df1764814e8f1 | Python | 1,572 | 57 | # -*- 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.
#... |
f1779b1e362a6865ae837e25e669616ba91965975069a8d68dc92da81a6d058a | Python | 1,572 | 50 | # 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, ... |
77018cedea0dfe697d0e569d41a03adb664c0dc017242300952b8f43897aefb2 | Python | 1,573 | 53 | #!/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
numpy version: 1.23.3
"""
#%% Import Modules
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
#%% Directories
project_dir = '/da... |
b603f2e44d564ff1a9c58cf5787dc3188903ec4c4e7bf2593de73519fe465de0 | Python | 1,573 | 52 | from deepsith import iSITH
import scipy.optimize as opt
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='white', palette='colorblind', context='talk')
def min_fun(x, *args):
'''written by Beeg Jacques'''
ntau = int(args[2])
k = int(x[0])
if k < 4 or k > 125:
return np.inf
... |
e9ae6c76a2598b55d97324714c0b81e6b7897a3a74a516081503ea64c28fabe1 | Python | 1,574 | 57 | import io
from typing import TYPE_CHECKING, Iterator, List, Union
from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder
from ray.data._internal.util import _check_import
from ray.data.block import Block
from ray.data.datasource.file_based_datasource import FileBasedDatasource
if TYPE_CHECKING... |
e5ba659ed705738496f9e19385f52d23f62d6125869688c94cab015bf826602b | Python | 1,575 | 57 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 18 11:17:33 2022
@author: pbolan
"""
import os
import sys
import glob
import nibabel as nib
from utility_functions import save_nifti, get_datasets_dir
#%%
def extract_2D_from_3D(source_dataset, target_dataset):
if os.path.exists(target_d... |
54ad794b4418fba074a02fac1dc9808493c83059c34461e300dc6ddfe1f2c900 | Python | 1,576 | 60 | import numpy as np
import networkx as nx
import os.path
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter, MaxNLocator
import time
import math
import gc
gc.collect()
import warnings
import pysindy as ps
from filterpy.kalman import KalmanFilter
warnings.filterwarnings('ignore... |
6d8fc955558fa0eb4fcaf1d46881c1a0898aed363774b88a086e885cbf504164 | Python | 1,576 | 51 | import pandas as pd
import numpy as np
def simulate_gene_exp(adata, pc = 0.25, factor = 1):
"""
Adds noise to gene expression data. The rows are simulated according to a Multinomial distribution,
with the total counts per spot/cell drawn from a Negative Binomial Distribution.
param: pc- Pseudocount to... |
6e7a3f862036e900270c77f3c959797b6713048e9a8155453a4d1e6ecc339c7a | Python | 1,576 | 41 | import sh
import unittest
import tempfile
from os.path import join, dirname, abspath
import shutil
from Bio import SeqIO
from functools import partial
THISD = dirname(abspath(__file__))
here = partial(join, THISD)
inputFastq = "fixtures/fasta/780_S12_L001_R1_001_2014_04_16.fastq"
def runsample(indir, outdir):
sh.ru... |
73d0694de7ef50b963061dbc99f2bd200a243d118217ddce204ef3ff1fa3c101 | Python | 1,576 | 30 | from fr import *
import time
# additive (identity-link) alternatives for the egg SP effect
def nll_add(x,d,decl=False):
al=x[:A]; rh=x[A:2*A]; lk=x[2*A]; dd=x[2*A+1]; br=x[2*A+2]
ai=d.ai.values; sp=d.sp.values
eff=dd*(np.exp(-agev/np.exp(x[2*A+3])) if decl else 1)
mu=np.maximum(np.exp(al[ai])+ (eff[ai] ... |
8b6c2dd847c218b6b48b5f5ff282c8d0133a9312c8ed952e96f24f724b3a9271 | Python | 1,576 | 33 | import tensorflow as tf
from functools import partial
from additional_functions.metrics_missing_labels import get_metric
from deepvoxnet2.backwards_compatibility.losses import *
def missing_labels_dice_loss(y_true, y_pred, threshold=None, reduce_along_batch = False, calibrate = False, feature_weights = None, **kwargs)... |
5cb6ea8f9b5ba543db93c986d7700482f0368b451b8122da66c26ecc4cefc447 | Python | 1,577 | 51 | import sys
import argparse
import numpy as np
from libsvm.svmutil import *
from spiking_readout.dataset import SpikingDataset
def svm(input_dir, output_dir, seed):
# To control randomness
np.random.seed(seed)
# Load dataset
X_train, y_train = SpikingDataset.from_file(input_dir + "trainset.npy").to_de... |
b700ec3d97347a9188529a694f8768c10be395ea403f0d980f24eee9686fb166 | Python | 1,577 | 59 | # __anti_pattern_start__
import ray
import time
import itertools
ray.init()
numbers = list(range(10000))
def double(number):
time.sleep(0.00001)
return number * 2
start_time = time.time()
serial_doubled_numbers = [double(number) for number in numbers]
end_time = time.time()
print(f"Ordinary function call ... |
b0cacd661b6231653c937beb257d6da3c0ac176bb29842efadea377baa94b123 | Python | 1,579 | 59 | #!/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... |
be223fa7f578f33f12741c4f204bedeb4bece3a4ea1c60a397e06f9beebcec66 | Python | 1,579 | 39 | import torch.nn as nn
from argparse import Namespace, ArgumentParser
from .base import BaseModelConfig
from optuna import Trial
from monai.networks.nets import UNet
from monai.networks.layers import Norm
class UNetConfig(BaseModelConfig):
model_name = "unet"
def setup_search_space(self, trial: Trial, args: ... |
cd2385598ee1bee4f9516a5e89cabc0b67e2b1f25bb323a7799c2d125f5fb6d9 | Python | 1,579 | 59 | #!/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... |
61978df19a90ed2b649147423fa7c61b254205e4f4281dd5b7316f4511b7c232 | Python | 1,580 | 51 | # PowerSpectrum = abs(fft(SpeechFrame,1024)).^2;
# AutoCorrelation = ifft(PowerSpectrum,1024);
# Cepstrum = ifft(log(PowerSpectrum),1024);
import numpy as np
import scipy.io.wavfile
from scikits.talkbox.features import mfcc
import matplotlib.pyplot as plt
sample_rate, X = scipy.io.wavfile.read("0_Kathy_160.wav")
print... |
fae817eb87d623f9f9b90e3bcc527f4a3bdd000f2300f61a5b6d26049094e25e | Python | 1,581 | 50 | import os
import sys
from pathlib import Path
import pytest
# In privileged containers, we expect the following
# cgroupv1 is disabled
# cgroupv2 is enabled and mounted on /sys/fs/cgroup
# the user running tests has read and write access to the cgroup subtree
# memory and cpu controllers are enabled
_MOUNT_FILE_PATH... |
12b8677056eb5d63249250f5839cd32c98f5b475bff3b48adcbe38fe9a39a4aa | Python | 1,583 | 46 | import signal
import time
from projectmetis.proto.metis_pb2 import ControllerParams
# This imports the controller python module defined inside the `controller_pybind.cc` script.
from pybind.controller import controller
class ControllerInstance(object):
def __init__(self):
self.__service_wrapper = None
... |
4b2da551cc69fd9f92f6755ac4656bc2880b817ad27d9163688af6552bc170b9 | Python | 1,583 | 40 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion):
# --------------------------------------------------------------------------------... |
5a36da702757f5a87f14274120a12fd34200fed0c9f1e74570b731cba9be0eba | Python | 1,583 | 50 | import numpy as np
import pandas as pd
from data_profiling import ProfileReport
from data_profiling.model import BaseDescription
def test_example(get_data_file, test_output_dir):
file_name = get_data_file(
"meteorites.csv",
"https://data.nasa.gov/docs/legacy/meteorite_landings/Meteorite_Landings.... |
d1a66d4138b629d992220a1341d538196a30fdb66051f2603a39dd76eeea1511 | Python | 1,583 | 53 | """Maximum intensity projection over one dimension for a window."""
import os
import numpy as np
from nibabel import load, Nifti1Image, save
nii = load('/path/to/file.nii.gz')
w = 4 # window, total width is double of this number
data = (nii.get_fdata()).astype("int")
dims = data.shape
# --------------------------... |
eb5b9bc2f149de37b6adb09d6a91fd57effbe028c90ab322f8b0848c46b126fe | Python | 1,583 | 51 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Base conductance converter for the phenomenological noise models for inference."""
from typing import Dict, List, Tuple
from torch import Tensor
from torch.... |
ad48220b2434ee08bf641b18dffb54af375b3b3b2c9e94a737ce8fe2ad2d9b84 | Python | 1,584 | 44 | import torch.nn as nn
class ConvNet(nn.Module):
def __init__(self, num_classes=2):
"""
Convolutional Neural Network with 3 convolutional layers followed by 3 fully connected layers
"""
super().__init__()
self.conv1 = nn.Conv2d(3, 32, 5)
self.conv2 = nn.Conv2d(32, 64... |
cad5a9483b061aaab1d387ce711798a0bf4706a78b1a788cfc6f60be2ccebdfb | Python | 1,584 | 49 | import torch
import torch.nn.functional as F
from typing import Sequence
from ignite.metrics import Metric
from ignite.metrics.metric import reinit__is_reduced, sync_all_reduce
from ignite.exceptions import NotComputableError
class CE(Metric):
def __init__(self, output_transform=lambda x: x, weight=None):
... |
58a306bc117ef64b6310d0202870908c8280047e718283d49cbed9c52ec3ec41 | Python | 1,586 | 37 | import torch
import numpy as np
class ExperienceReplay:
def __init__(self, observation_shape, capacity = 100000, returns_shape = ()):
self.capacity = capacity
self.actions = np.empty((capacity, ), dtype = np.int64)
self.observations = np.empty((capacity, ) + observation_shape, dtype = np.fl... |
ca87a33c394cf7b298ffff1ca74010a40d127ead2a1d27318e1b42e2023be103 | Python | 1,586 | 48 | import logging
from typing import Iterable
from ray.data._internal.datasource.mongo_datasource import (
_validate_database_collection_exist,
)
from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder
from ray.data._internal.execution.interfaces import TaskContext
from ray.data._internal.util ... |
f6a1566d279fd35f418201607f2f07ae5010ba6174206a2ba0cfdfa0716f3cfd | Python | 1,586 | 31 | from case2 import *
R=int(sys.argv[1]); out={}
models=["W","G","B"]; conf=np.zeros((3,3),int); confB=np.zeros((3,3),int)
for gi,gm in enumerate(models):
for r in range(R):
G=design(); p=TRUE.copy()
if gm=="G": p[3]=0.; p[4]=-0.8
if gm=="W": p[4]=0.
if gm=="B": p[3]=np.log(0.3); p[4]=... |
463e4ed53ac4ab910835c9cd06fdd064fb7c6ec6d7fedc8f86548505625fccc1 | Python | 1,587 | 54 | import pathlib
import os
import subprocess
import pandas as pd
from ydata_profiling import ProfileReport
from .pmlb import (
fetch_data, get_updated_datasets, last_commit_message
)
from .dataset_lists import dataset_names
def make_profiling(dataset, write_dir, dat_dir='datasets/'):
print(f'Processing {datase... |
91beba4714c91aba67948035bc4a2d0a589ce2ff5c7cf71383ec3529217f7dac | Python | 1,587 | 44 | #!/usr/bin/env python
#!/usr/local/bin/python
#!/usr/bin/env PYTHONIOENCODING="utf-8" python
import os
import tflearn
import speech_data as data
# Simple speaker recognition demo, with 99% accuracy in under a minute ( on digits sample )
# | Adam | epoch: 030 | loss: 0.05330 - acc: 0.9966 -- iter: 0000/1000
# 'predi... |
0ce741373890d7466a41412e3c44adb1f5d61115102bb0d5cd4c2289c2e6a413 | Python | 1,589 | 42 | """Read BrainVoyager vmr and export nifti."""
import os
import nibabel as nb
import bvbabel
import pprint
SUBS = ['sub-05']
ROOT = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives'
for sub in SUBS:
folder = f'{ROOT}/rawdata_bv/{sub}/ses-01/anat'
FILE = f'{folder}/{sub}_ses-01_uni_... |
a3aa2fb426b5724b5f656d792c7f295547ac71d1fc4480a6e044112381a065bc | Python | 1,589 | 38 | from model import (ProteinInteractionNet, Tester)
from uncertaintyAwareDeepLearn import VanillaRFFLayer
from utils import (
load_configuration,
set_random_seed,
get_computation_device,
evaluate
)
import torch
def main():
# --- Pre-Training Setup ---
# Load configs. Use config file to change hyp... |
a7ea23216008e627946b588b15ec3b0aac885227920425c1e2746c8b90428994 | Python | 1,589 | 60 | # Project constants
# SigLIP model
MODEL_NAME = "google/siglip-so400m-patch14-384"
# S3 paths
S3_VIDEOS_PREFIX = "stock-videos/"
S3_EMBEDDINGS_PREFIX = "embeddings/"
# Scene change detection
SCENE_CHANGE_THRESHOLD = 0.15 # EMA score threshold for detecting scene changes
EMA_ALPHA = 0.9 # EMA decay factor (higher =... |
afe0863df2c79b11265ce91cf68fa3a9662b048efd9ee1c8dd8adc35b7fc4466 | Python | 1,589 | 51 | # -*- 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 2: network with multiple layers.
Network that consists of multiple analog layers. It aims to learn to sum all
the elements from one array.
"... |
b1b8c35ec8cc934be699bc42971a6a41df5c47cbbdc33f37f5ded69002ba9f60 | Python | 1,589 | 30 | import numpy as np
import pandas as pd
def calc_ledd(cm, pn, med_date):
conmed = cm[cm.PATNO == pn]
# get the active drugs for patient pn
active = conmed[(conmed.STARTDT < med_date) & ((conmed.STOPDT >= med_date) | (pd.isnull(conmed.STOPDT)))]
tot_add_meds = 0
# check if any of the active meds are... |
ab818a4af7da60d264b64366707c4d5e7254db67f5d7d11126f766450f9efb6c | Python | 1,590 | 54 | #!/usr/bin/env python
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import tflearn
import speech_data
import os
learning_rate = 0.0001
training_iters = 300000 # steps
batch_size = 64
width = 20 # mfcc features
height = 80 # (max) length of utter... |
3e4b2b581ac2c594fd80e97cb8430d880356e7b6c7b1e93e4ddf83acc27ff2ef | Python | 1,591 | 74 | # -*- coding: utf-8 -*-
import json
import random
datasets_path = './data_dataset_coco/'
f = open('{}annotations.json'.format(datasets_path) ,encoding='utf-8')
gt = json.load(f)
print(gt['info'])
print(gt['licenses'])
print(len(gt['categories']))
print(len(gt['images']))
print(len(gt['annotations']))
train = dict... |
8b56eb74fc0d63256e8e0e6ea6c0c8967c0ec5b78ba2da216e57e17425b44303 | Python | 1,591 | 43 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to docume... |
bb4f573787ff4c4ba38a26df45d021336033753a133aeb75e66363ad73e949ab | Python | 1,591 | 52 | """Get first echo for vessel segmentation"""
import os
import nibabel as nb
import numpy as np
# from scipy.linalg import lstsq
import glob
# =============================================================================
DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
# Set subs to work on
SUB... |
c9742f7949fdfe343682ae5764f5dd81cdc7557ab59993459d024537e2a63ecc | Python | 1,591 | 44 | # import the main libraries required for the preprocessing
import mne
from mne_bids import read_raw_bids
from pathlib import Path
import pickle
import numpy as np
# import homemade function
from technical_validation_utils import subject_files
mne.set_log_level(verbose='CRITICAL') # reduce verbose output
# %%
# loop ... |
a5c6096a239b04a70671a0a27ae1c6b94022670f28cd88f3676699f54ad7993c | Python | 1,593 | 66 | import ray
@ray.remote
class WorkQueue:
def __init__(self):
self.queue = list(range(10))
def get_work_item(self):
if self.queue:
return self.queue.pop(0)
else:
return None
@ray.remote
class WorkerWithoutPipelining:
def __init__(self, work_queue):
... |
ccbb22c3063185d584ff333615630f593559baa913a913141d4fca3a33838fc6 | Python | 1,594 | 38 | #!/home/iyak/.pyenv/shims/python
# usage: ./analyse_dat.py <raw output>
# description: post-data process for RNAelem to evaluate the performance to infer the motif position
#$ -cwd
#$ -e /home/iyak/.ugeerr
#$ -o /home/iyak/.ugeout
#$ -S /home/iyak/.pyenv/shims/python
##$ -m es -M h.m@tuta.io
#$ -V
#$ -l s_vmem=0.5G,me... |
65357f4e3f7077402e6e04a647d9b06aacab0318e764b8197de33e12d2e021b4 | Python | 1,595 | 46 | # Copyright (c) DP Technology.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from functools import lru_cache
import logging
from unicore.data import BaseWrapperDataset
from . import data_utils
logger = logging.getLogger(_... |
b383e644b0cb935b015d53fcc0e7ed222c3eb9cc50c8229032773b50e7ff49a1 | Python | 1,595 | 67 | # -*- coding: utf-8 -*-
"""
"""
import numpy as np
import pytest
pytestmark = pytest.mark.order(5)
def test(*spam):
import vtkplotlib as vpl
import numpy as np
self = vpl.PolyData()
vectors = vpl.mesh_plot(vpl.data.get_rabbit_stl(), fig=None).vectors
points = vectors.resha... |
7cb643175eb5a63ac886e66bfa6c1ac742112c20fc72f51eca5868d3e04f788d | Python | 1,596 | 51 | # -*- coding: utf-8 -*-
from vtkplotlib._get_vtk import vtk
import numpy as np
from vtkplotlib.plots.BasePlot import Base2DPlot
class ScalarBar(Base2DPlot):
"""Create a scalar bar. Also goes by the alias `color_bar`.
:param plot: The plot with scalars to draw a scalarbar for.
:param title: An optional... |
f63bf11a917d8a63f86e5f32f118e6750672d5ae95f102a5f0f3ba98c6a491ff | Python | 1,596 | 48 | import torch
from torch.nn.parameter import Parameter
import numpy as np
from torch import sigmoid
import copy
class HardConcrete(torch.nn.Module):
def __init__(self, beta=1 / 3, gamma=-0.2, zeta=1.0, fix_temp=True, loc_bias=3):
super(HardConcrete, self).__init__()
self.temp = beta if fix_temp el... |
988a9ff60fdee6d851bfa46e70d208305f966a3a770402bf781221c0e21359ff | Python | 1,597 | 64 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import samri.plotting.maps as maps
import seaborn as sns
from os import path
data_dir = path.join(path.dirname(path.realpath(__file__)),"../../tests/data/ioanas2018")
data_path = path.join(data_dir,'pattern_summary.csv')... |
4b0261b359b31f8bd4383886cb4d36be6d58eb910217500495b0db44b09bc8e8 | Python | 1,598 | 60 | import os
import subprocess
import sys
import click
from ci.ray_ci.doc.build_cache import BuildCache
@click.command()
@click.option(
"--ray-checkout-dir",
default="/ray",
)
def main(ray_checkout_dir: str) -> None:
"""
This script builds ray doc and upload build artifacts to S3.
"""
# Add the... |
befff9ca934a251d9fbe4c3e85acb8734a17744fb3fc2bf8ab4d7031dcf485a8 | Python | 1,599 | 40 | ####################################################################################################
# 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... |
00c0e7122d6f2ee648a19200e4a04f0979c21bab5c6e7fb5e5d17be1de051fcb | Python | 1,600 | 43 | import torch
from torchtext import data
from Config import *
SEED = 1234
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
import jieba
import re
def x_tokenize(x):
str = re.sub('[^\u4e00-\u9fa5]', "", x)
return jieba.lcut(str)
TEXT = data.Field(sequential=True, tokenize=x_tokenize,fix_length... |
08af8c082dd87109da70a135537daac7c192eb946f5e155a195a866ceda3c600 | Python | 1,601 | 56 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 12:04:00 2019
@author: ju-bar
Calculation of 2-dimensional detector functions
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishing License, version 3
"""
import numpy as np
from numba import njit, i... |
b89a279633542cc160e5e8fb62fc77233d5d5ccfad7b93722e5d9e22683a3632 | Python | 1,601 | 39 | import logomaker as lm
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os
def make_logo(pssm,motif_cutoff_path,pre_path):
with open(pssm, 'rb') as f:
pssm = np.load(f)
with open(motif_cutoff_path,'rb') as f:
motif_name = np.load(f)
mo... |
8eb2ec30db9296189de5ce45db3f40ebfa24c91f1a0a084294c2f681be0ec074 | Python | 1,602 | 50 | def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
... |
c9493878f9bc6779e595be8e2576e1bc4240b5d18c5b1fef4a17dc175e9bd008 | Python | 1,602 | 38 | # -*- coding: utf-8 -*-
"""
PMLB was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- William La Cava (lacava@upenn.edu)
- Weixuan Fu (weixuanf@upenn.edu)
- Trang Le (ttle@pennmedicine.upenn.edu)
- and many more generous open source contributors
P... |
0e46785f49ddb4c434167aac75e38a3fd75f74b40f2052b49321e2c67c8aa00a | Python | 1,603 | 61 | # 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... |
6010a64b6350ecdf0c7076ea8269b9a99145f508fe1bb89f52e68e9c1dad9165 | Python | 1,603 | 44 | import numpy as np
from hic3defdr.util.clusters import cluster_to_slices
def make_apa_stack(matrix, clusters, width, min_dist=None):
"""
Creates a stack of square matrix slices centered on each cluster in a list.
Parameters
----------
matrix : scipy.spmatrix
The matrix to take slices of.... |
a9f2352e383c342b96935a536dcca07f6bce1075d41d933f8cc24fdcd84b982d | Python | 1,603 | 43 | import os
import re
import pandas as pd
import sys
project_root = '/ccb/cybertron/khchao/splam-analysis-results/'
output_dir = f'{project_root}train/results/RefSeq_ALTS/REF_junctions/'
def chr_name_convert():
f_chrs = open(f'{project_root}/Dataset/Refseq_2_UCSU_chromosome_names.tsv', "r")
lines = f_chrs.rea... |
50169fdf4b0ceb2f9b92aeba2a273a03315b181b35b77b57fb727d479ed9facd | Python | 1,604 | 51 | import gc
import logging
import threading
import time
from typing import Callable, Optional
logger = logging.getLogger(__name__)
class PythonGCThread(threading.Thread):
"""A background thread that triggers Python garbage collection.
This thread waits for GC events from CoreWorker and triggers `gc.collect()`... |
bf4f651e2bf47d719b9a930eab67face12669edf665a7945a209ccb9596e6b5f | Python | 1,604 | 48 | from __future__ import annotations
import numpy as np
from anndata import AnnData
from scipy.sparse import csr_matrix
from ._utils import spatial_connectivity_key, spatial_distance_key
def remove_long_links(
adata: AnnData,
distance_percentile: float = 99.0,
connectivity_key: str | None = None,
dist... |
04bdcbc2c29e9b1ed18c3240ce184983fba0484b5166e633085fb4184ba54194 | Python | 1,605 | 54 | import torch
import platform
import logging
from pynvml import nvmlInit, nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo
from agent.data.entities.config import ROOT_LOGGER_ID
logger = logging.getLogger(ROOT_LOGGER_ID)
MACOS_SYSTEM = "Darwin"
CUDA_GPU = "cuda:0"
APPLE_GPU = "mps"
CPU = "cpu"
def get_device(us... |
6e9e9b2b48a8f82035274472ab239401f439d6170627b4951a1716fbbe167582 | Python | 1,605 | 53 | # 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... |
85a7170815dad4ea21b28caf67618c84a9c2a9c037c0c2ab38000e71c9afcea8 | Python | 1,605 | 48 | # built-in dependencies
from typing import Any, List, Union
# project dependencies
from deepface.commons.onnx_utils import build_session
from deepface.models.facial_recognition.onnx.OnnxFacialRecognition import OnnxFacialRecognition
from deepface.commons.logger import Logger
logger = Logger()
# pylint: disable=line-... |
ccd3a41a30555f9229dcdcd8332797d680148e1d1d8cb992c0e480ffafc5f179 | Python | 1,605 | 41 | # -*- coding: utf-8 -*-
from __future__ import print_function
import torch.utils.data as data
import torch
import numpy as np
import scipy.io as sio
import h5py
import os
# prefix = "/home/bizhao/neuro-hnn/data/N-MNIST/processed/"
class MyDataset(data.Dataset):
def __init__(self, path='load_test.mat',method = '... |
9bbd03dc34c0ec16fc84c8dbc4d08a73349448ed6ae2cb4af8c35557a6466691 | Python | 1,607 | 43 | import os
import nibabel as nib
import numpy as np
import IVIMNET.deep as deep
from hyperparams import hyperparams as hp
root = '/path/to/results'
sub = 'phantom'
bval_file = os.path.join(root,'sub-01','sub-01_run-1_IVIM-avg.bval')
cval_file = bval_file.replace('bval','cval')
noise_sigmas = [1/snr for snr in np.arang... |
da26fd0b9dd1e277286747ed8abb11096eab7d8c787b60fdbfe6981288f4a964 | Python | 1,609 | 52 | # 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... |
1b1392b41b818869f38ac32106fb5d5f8f795f4ad27ebf371d9a1a8055ba7082 | Python | 1,610 | 34 | ####################################################################################################
# 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... |
941ef99ae04ba9d0323c4a2edbfcf8906b892f6bda209ee2d0832116a1fa00fe | Python | 1,610 | 53 | import torch
import torch.nn as nn
import pytorch_lightning as pl
from torch.nn import functional as F
class CNN(pl.LightningModule):
def __init__(self, lr=1e-3):
super().__init__()
self.lr = lr
self.model = nn.Sequential(
nn.Conv2d(2, 20, 5, 1, bias=False),
nn.ReLU... |
71a22b14a8cd63e948e6d24890c7f4753b8150b022c7feb73b16c841804988f2 | Python | 1,611 | 63 | import numpy as np
from scipy import interpolate
def qvalue(pv, pi0=None):
'''
Estimates q-values from p-values
This function is modified based on https://github.com/nfusi/qvalue
Args
====
pi0: if None, it's estimated as suggested in Storey and Tibshirani, 2003.
'''
assert(pv.min() ... |
7e2477e4f3d55f4ec2dc5e4274ca7931a9ecefb6e1a965ff735abfe9119abeee | Python | 1,611 | 44 | import sys
import pytest
from ci.ray_ci.doc.api import AnnotationType, CodeType
from ci.ray_ci.doc.module import Module
_MOCK = "ci.ray_ci.doc.mock.mock_module"
def test_walk():
module = Module(_MOCK)
# Keyed by name rather than indexed: the walk's order follows dir(), so any
# annotated symbol added t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.