sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
5751b12f92b735136d78160a5bdb736ccc3e08d7a3fe65b7956c1f10f5aa9a43 | Python | 2,496 | 83 | # 05/24/2023 Fengyao Yan
# test the model on the patient 2224 sequence data using the model created in file decide_organ.py
import pickle
from numpy import NaN
import numpy as np
import pandas as pd
import tensorflow as tf
from decide_organ import df_master, model_name
from decide_organ import _gen_comp
import matplo... |
6d2a92411896cf69b6cd5f53ebdd74ce7b977da2db572735245b0b48c57b31db | Python | 2,496 | 76 | import itertools
import random
import numpy as np
def lorentzian(a: float, b: float, c: float, x: np.ndarray) -> np.ndarray:
"""
Calculate the value of a Lorentzian function at a given x.
Parameters:
- a: float, representing the height of the Lorentzian curve
- b: float, representing the positio... |
cce9584147780dd05387cfefacd95028b2eadd26760b9dc34608b6e848a134af | Python | 2,496 | 73 | #######################################################################################################
##################### Preprocessing for multi-task models #############################################
#######################################################################################################
import... |
c0da31f2a0cebbda7efdac0196b1dbe6e2ef78ee585f4520da6b4ed198f5dc4f | Python | 2,497 | 76 | #!/usr/bin/env python
import os
import sys
import time
import yaml
import urllib
import hashlib
import argparse
required_keys = ['caffemodel', 'caffemodel_url', 'sha1']
def reporthook(count, block_size, total_size):
"""
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
"""
glob... |
7078847c7b8b9a6eabb3955eff3b417cc23b2ebdf5becb3e0f8c24a85e71ce52 | Python | 2,498 | 73 | import sys
class VendorImporter:
"""
A PEP 302 meta path importer for finding optionally-vendored
or otherwise naturally-installed packages from root_name.
"""
def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
self.root_name = root_name
self.vendored_names = set(v... |
4f178d2853127c1333069043887c7c0e1dd1cec7559af59a5e1b59d370d932cd | Python | 2,499 | 73 | import sys
class VendorImporter:
"""
A PEP 302 meta path importer for finding optionally-vendored
or otherwise naturally-installed packages from root_name.
"""
def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
self.root_name = root_name
self.vendored_names = set(v... |
f47967d39dd0295f7449611bc50abca3606e63ec1ba51d0efb059fbd7ceb0dad | Python | 2,499 | 56 | import pytest
import sys
sys.path.append('../')
from DNN.rcnn_sat import b_d_net_readout_0, b_d_net_readout_1, b_d_net_readout_2, b_d_net_readout_3, b_d_net_readout_4, b_d_net_readout_5, b_d_net_readout_final
from utils import non_trainable, train_readout, assertion_block
import tensorflow as tf
import numpy as np
@py... |
fd198a85e4fbe4c57fea4862ae41c27b9dfc8c98097b02a9a9ad51ae1fcd2c51 | Python | 2,499 | 73 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2018 Braintech Sp. z o.o. [Ltd.] <http://www.braintech.pl>
# All rights reserved.
"""Module provides single class representing sample packet buffer."""
from . import ring_buffer as rbn
class AutoRingBuffer(object):
"""Class representing sample packet buffer. When ful... |
81febad9610cc83791151ad554b83fc257c6fe21d2bd76e427fc9eb7231a56dc | Python | 2,500 | 58 | """Regression tests for the cert9 (round-9-prep) intervention hardening fix.
MAJOR-1 (cert8 intervention bucket) -- ``helper_from_serialized``
(``torchlens/intervention/helpers.py``) is exported in ``helpers.__all__`` as the
module's public reconstruction entry point, but its own ``value_decoder`` keyword
argument DEF... |
d305c2fddf967c17fa9bb18b0f5b0dff2a428462e627abecdd1aac6f4919beaa | Python | 2,500 | 63 | import csv
import sys
import utils
def WriteCSVFromDict(filename, data):
fieldnames = ['movie', 'track ID',
'original time (s)', 'time (s)', 'x', 'y', 'z']
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
csvwriter = csv.DictWriter(file, fieldnames)
... |
69b001a3f76ffd212be21540c062aad94a8ff6cea05ebbc3022977f145cb55cc | Python | 2,501 | 76 | import os
import h5py
import numpy as np
import scanpy as sc
from ica import ica1
from scbig.utils import read_data, setup_seed, sample, louvain, calculate_metric
def preprocess(adata, scale=True):
sc.pp.filter_genes(adata, min_cells=3)
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.normalize_total(adat... |
77b3f5d1a79965aa5fe848f003886a7515e89cd09dd8464ea7e453a25a740825 | Python | 2,501 | 70 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
072ebc70bd356b17d4a08934aa26bbec1dd2f1e7dddac7758fb3131f22811a52 | Python | 2,502 | 79 | import argparse
import multiprocessing as mp
import time
import uuid
import rpy2.rinterface as ri
import rpy2.rinterface_lib.embedded
R_ID_TAG = '_rpy2_R_id_'
def print_setup(args):
print('-'*28)
print(f'Worker type : {args.worker}')
print(f'number or procs : {args.nproc}')
print(f'number o... |
c57d407f9027fbcb1130f977783a0c8c80119524ec6daac48b7fc61ab2abfa8c | Python | 2,502 | 79 | #!/usr/bin/env python3
"""
Test that CodeCarbon now defaults to including DRAM for complete hardware measurement.
"""
import subprocess
import time
from codecarbon.core.cpu import IntelRAPL
from codecarbon.core.units import Time
print("=" * 80)
print("Testing CodeCarbon's new default: CPU+DRAM measurement")
print("=... |
a4c01c486e86aed522c3ade398bf4016f6ef59bbada2c7c5f69eb55ce297877c | Python | 2,503 | 83 | import pytest
from flaskr.db import get_db
def test_index(client, auth):
response = client.get("/")
assert b"Log In" in response.data
assert b"Register" in response.data
auth.login()
response = client.get("/")
assert b"test title" in response.data
assert b"by test on 2018-01-01" in respo... |
62165b7a2e286540deea51a294efd22b17c61bad6a48c3b0ba7de8b46503f8c7 | Python | 2,504 | 71 | """
A non-temporal resnet baseline
"""
import torch
from torch import nn
class ResidualLayer(nn.Module):
def __init__(self, size_hidden, res_hidden, normalization, activation,
hidden_dropout=None, residual_dropout=None):
super(ResidualLayer, self).__init__()
self.norm = normaliza... |
65dab539f021794d8edc71067bd5ebb13e420d7591e467c878d60a3cbe38964f | Python | 2,504 | 91 | import os
import btrack
import numpy as np
from btrack import datasets
from tqdm import tqdm
def update_seg_masks_with_tracks(seg_masks, tracks):
"""
You can also use the same function that ships with btrack now.
"""
frame_ids = np.linspace(0, len(seg_masks) - 1, len(seg_masks)).astype(np.uint8)
... |
716b55bda87d93d90d33f2edd2156f1f4336d979ae93bf2d6ab465cab018b96e | Python | 2,504 | 83 | import json
import os
import cv2
import numpy as np
import tensorflow as tf
from skimage import io
from skimage.transform import resize
from model import generate_model_binary
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
included_classes = ["Healthy", "Sick", "Reject"]
def load_images(acq_dir: str) -> (... |
df87a72861251f5a002593933d2719a4586bd6f3488c7c0a3ef39810cbe8b1f3 | Python | 2,504 | 84 | import numpy as np
from gym import utils
from gym.envs.mujoco import MuJocoPyEnv
from gym.spaces import Box
class PusherEnv(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 20,
}
... |
8ef65847f8c38afb1a3bbdecfd7f0868fd01337a47f00ed390322b8b61f2d153 | Python | 2,506 | 66 | #!/usr/bin/env python
"""Test all features on an example trace"""
"""
Copyright (c) 2015, Blue Brain Project/EPFL
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code m... |
5799bde3761751314cca10cbbf5f261d6d161737a7632f216a1b5001698a345b | Python | 2,507 | 78 | import numpy as np
import math
import pdb
# ------------------------------------------------------
# -- set invalid ParentIndex to -1 (make it a root)
def correct_invalid_xyz(swc_matrix, invalid_XYZ_flag):
tofloat_success = True
updated_swc_matrix = swc_matrix
x = np.array(swc_matrix.X)
y = np.arra... |
edf7132ea392ddc15c8eec8e02d7f57f2ded63a9b450f52315f5425f1e8f5eb4 | Python | 2,507 | 66 | import pytest
from gym.spaces import Discrete, MultiDiscrete
from gym.utils.env_checker import data_equivalence
def test_multidiscrete_as_tuple():
# 1D multi-discrete
space = MultiDiscrete([3, 4, 5])
assert space.shape == (3,)
assert space[0] == Discrete(3)
assert space[0:1] == MultiDiscrete([3]... |
09a5f18352b1580e841bc2ef492c753ee02d6fb2b42f6cc0ff6923afa56589a6 | Python | 2,508 | 76 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test objects and function in the module ``tfep.io.dataset.merged``.
"""
# ====================================... |
c689e5f621b1d510f0d6bf4aeee16b78e11cb7e3cc54a122018781df7b072303 | Python | 2,508 | 83 | import re
import dateparser
import datetime
from .bulletin import Bulletin
from bs4 import BeautifulSoup
class Delhi(Bulletin):
def __init__(self, basedir):
statename = 'DL'
super().__init__(basedir, statename)
self.baseurl = 'http://health.delhigovt.nic.in'
self.bulletin_url =... |
0e3717b7d68c80b6a7edb460ed3648f26ffc48b590399fa0d87a20b81d7edea0 | Python | 2,509 | 34 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on April 2020
@authors:
Thomas Bonald <bonald@enst.fr>
"""
import numpy as np
# standard SVG colors
STANDARD_COLORS = np.array(['blue', 'red', 'green', 'orange', 'purple', 'yellow', 'fuchsia', 'olive', 'aqua', 'brown'])
# 100 RGB colors of coolwarm color map... |
575c67d8c83ebd6d11dcc9ea530aab36df7a9724fd1b749c8320dd56b67408f0 | Python | 2,509 | 82 | import torch
from torchvision import datasets
import numpy as np
import random
import os
import torch.utils.data as data
import time
import logging
logging.getLogger(__name__)
class ImageAndPathDataset(datasets.DatasetFolder):
"""Custom pytorch dataset that extends DataSetFolder
to also return the path of the ... |
1cd7ee938699d49e1d7d281a3d95fdc1c6728afac3973b4ae88327b0354018b8 | Python | 2,510 | 60 | import getpass
username = getpass.getuser()
from pathlib import Path
biomedisa_path = Path(__file__).resolve().parents[2]
#-------------------------------
# default (automatic detection)
#-------------------------------
python_path = None
lib_path = None
wsl_path = None
#-------------------------------
# Windows usin... |
6b26dadbc0cec1773437c140f6258ed022dc4078170f680250ccb213e99efe5b | Python | 2,510 | 90 | import torch
from torch import nn
from src.datasets import DatasetCMNIST, DatasetOSCN
from src.models.classifier import Classifier
from src.models.components import (
EncMLP,
EncMLPSimple,
EncCNN_OSCN,
EncCNNAdd_OSCN,
)
class Classifier_OSCN(Classifier):
"""Classifier for OSCN
"""
def __in... |
984b48ad820bbdc4a16178bdcce62e0fdb85c1f73acc3dab3777772de2166a21 | Python | 2,511 | 86 | import sys
import argparse
import logging
import time
import vcf
def phase_bnd(alt):
if alt[0] in [']', '[']:
chr2 = alt.split(':')[0][1:]
pos2 = int(alt.split(':')[1][:-2])
else:
chr2 = alt.split(':')[0][2:]
pos2 = int(alt.split(':')[1][:-1])
return chr2, pos2
def main_ctrl(args):
filein = vcf.Reader(op... |
c9679c6dd79a3f12703d5bd2e423dd74592276726d0887d577ee4da58a35e5f6 | Python | 2,512 | 74 | # 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... |
f5b8b348000ccbb661ad501a93022355bcb077e48d9ddbf2e376e85107ea7f77 | Python | 2,512 | 79 | # Copyright 2023 DeepMind Technologies Limited
#
# 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 agree... |
3ea1f91be59f676965b82b880835ca7f22f64c8bb594116c576f787292632a5c | Python | 2,513 | 80 | from unittest import mock
from uuid import UUID
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette import status
from carbonserver.api.infra.repositories.repository_telemetry import (
SqlAlchemyRepository as TelemetryRepository,
)
from carbonserver.api.routers impor... |
89c3b80678f4a8865afc2b56fd2fa2da747654dad16d78de9e9bdc074c450ab7 | Python | 2,513 | 71 | import os
import sys
# Dirty fix, :TODO rewrite tools as a package - joined directly to Snudda or the lab
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, "tools")))
import unittest
import json
import shutil
from meta.create_meta import write_meta
from transfer.morphology import transf... |
a4fce83d99d9476596d40c33e54d64221fa8e777232c88f472d532144217bb96 | Python | 2,513 | 63 | """Smoke tests for the Memcached result backend.
These tests run against a real memcached server through pymemcache, so
that any mismatch with the pymemcache client signatures (for example in
the chord counter) or a silently dropped result shows up here.
"""
from __future__ import annotations
import pytest
from pyte... |
861604e1538387e1fa2e48afc249dd8a9238f153d1f93045a623f28fb1a27c19 | Python | 2,514 | 66 | """Tasks auto-retry functionality."""
from vine.utils import wraps
from celery.exceptions import Ignore, Retry
from celery.utils.time import get_exponential_backoff_interval
def add_autoretry_behaviour(task, **options):
"""Wrap task's `run` method with auto-retry functionality."""
autoretry_for = tuple(
... |
9befb70ff048b92d5b45e6ff9e13d9849a2a6b94356fe063d5bbfbf9a4e6d504 | Python | 2,514 | 80 | import random
import numpy as np
from keras.src import backend
from keras.src.api_export import keras_export
from keras.src.backend.common import global_state
from keras.src.utils.module_utils import tensorflow as tf
GLOBAL_RANDOM_SEED = "global_random_seed"
@keras_export("keras.utils.set_random_seed")
def set_ran... |
02a9a9b223f0461f7fc7cada3ee91e0a8866f51f48a55ef44d64a4a2b8cb5d59 | Python | 2,515 | 60 | import os.path
from data.base_dataset import BaseDataset, get_params, get_transform
from data.image_folder import make_dataset
from PIL import Image
class AlignedDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the directory '/path/to/data/train' contains image pairs in the ... |
443005274f5433cf4b0215ffd9508841b451d3a47869257bab7dd84a2dca9188 | Python | 2,515 | 81 | import os
from typing import Tuple, Dict
FINGERTIP_SITE_NAMES = [
'robot/rh_S_fftip',
'robot/rh_S_mftip',
'robot/rh_S_rftip',
'robot/rh_S_lftip',
'robot/rh_S_thtip',
]
# DEFAULT_INITIAL_QPOS = {
# 'robot/rh_WRJ2': 0.013937,
# 'robot/rh_WRJ1': -0.081399,
# 'robot/rh_FFJ4': -0.104522,
# ... |
1efd9f6b93564f2e5da894c73ad6ef23a0ad7a8af05cb7676be2fe57aa6db7da | Python | 2,516 | 73 | import os
from math import sqrt
import h5py
import numpy as np
import pandas as pd
import scanpy as sc
from scipy.stats import pearsonr,spearmanr
from sklearn.metrics import mean_squared_error
from scbig import setup_seed
for sparity in ['0.8', '0.85', '0.9', '0.95']:
print('----------------sparity level of data... |
393f34c8bfbcfdb8d8466a66e99661b9052755c3f3de265392c8c16f646db596 | Python | 2,516 | 81 | #!/usr/bin/env python3
"""This script is an adaptation of the original file "example_4_b.py" created by Roman Martin."""
from GNNSubNet import GNNSubNet as gnn
import ensemble_gnn as egnn
import copy
import random
import time
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import accuracy_s... |
457cae4cb102812c1a0735d39069fa153e558e082aca946bb3028430a1aa75f2 | Python | 2,516 | 75 | """Encoders that turn actions into conditioning embeddings.
A world model conditions its prediction on what the agent did. The action
arrives as a low-dimensional vector, which is what a robot control task gives.
"""
from __future__ import annotations
from torch import Tensor, nn
class ActionEncoder(nn.Module):
... |
7a89c25062463f7867706b64f1fae0536979d63d4ba5879ce9c8181b4e5bce09 | Python | 2,516 | 60 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (leoxiaobin@gmail.com)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future... |
c1fffc656f8a951971f674ec89c5b0de0f741845f3324f3bbc65458b9a3fa724 | Python | 2,516 | 76 | import pandas as pd
import numpy as np
import seaborn as sns
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
from transformers import AutoTokenizer, AutoModel
from sklearn.metrics.pairwise import cosine_similarity
from typing import List
from sklearn.feature_extraction.text import TfidfVectorizer
imp... |
4f04be0f9c363bdbe07daae5f254cfc7ed4c667721b85c79fe5837399d6472c6 | Python | 2,517 | 72 | #!/usr/bin/env python
import glob
import itertools
from collections import defaultdict
import matplotlib
import matplotlib.patches as mpatches
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
matplotlib.use("Agg")
def plot_bar(ranges, colors, orig_names, cluster_num... |
cfa4e2f8a00e7520fb4e873df4603a4f5a42b56418308af64a06b0a1afc6e6b8 | Python | 2,517 | 86 | """5' defects
"""
import logging
import os.path
from Bio import SeqIO
from .utils import find_gapped_pos
# pylint: disable=C0103
# Invalid constant name
logger = logging.getLogger('pipe.defect')
def _detect_defect(ref, qry, pos_start, pos_end):
# Find tag position in reference seq, and start aln pos for the ... |
49ae2b5128b19568cb2faff4e9ca7f1b14c37eed135a655d9890be98f7528514 | Python | 2,518 | 80 | import os
import cv2
import shutil
import pandas as pd
from tqdm.auto import tqdm
import torch
import torch.nn.functional as F
class QueryFalsePositives:
def __init__(self, project_name, model, valid_df, valid_transform, config):
self.device = config["device"]
self.project_name = project_name
... |
6d12b87e345f7b20d27e9c3abcd38e373075db92382d8986c7d616dd35dcc238 | Python | 2,518 | 72 | # -*- coding: utf-8 -*-
from fooof import FOOOF, Bands
from fooof.analysis import get_band_peak_fm
import numpy as np
import mne
import os
import sys
import pandas as pd
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_PATH)
from visualize.visualize import visualize_fooof_... |
db664498e0da578eccc26b09b00a068cac480be34b884b029adda4739714a09b | Python | 2,520 | 69 | """
The cross validation function for finetuning.
This implementation is adapted from
https://github.com/chemprop/chemprop/blob/master/chemprop/train/cross_validate.py
"""
import os
import time
from argparse import Namespace
from logging import Logger
from typing import Tuple
import numpy as np
from BatmanNet.util.ut... |
a0b940a0b3d04e3dd6d3b1ebe7c3b62b8df6189c4748ecab975f600a86239c50 | Python | 2,521 | 85 | import unittest
from modular_splicing.gtex_data.pipeline.marginal_psis import related_sites
class RelatednessTest(unittest.TestCase):
def test_one_step_relatedness(self):
self.assertEqual(
related_sites(
1,
[{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}],
... |
7254b55e68320881afe9a45bdb2954cf0770cc4fd5047bd989318b6a143ae343 | Python | 2,522 | 70 | # -*- coding: utf-8 -*-
## Stand-alone version of DEICODE (https://github.com/biocore/DEICODE)
from biom import load_table
from deicode.rpca import rpca
from deicode.rpca import auto_rpca
import numpy as np
import pandas as pd
import os
from skbio import DistanceMatrix
from deicode.preprocessing import rclr
from os ... |
97cd7aced8b6ae09a3e0c36d114f4e1dd7db89492587f315771787606803bda7 | Python | 2,523 | 92 | import torch
import torch.nn as nn
from . import carn_ops as ops
def make_model(args, parent=False):
return CARN(args)
class Block(nn.Module):
def __init__(self,
in_channels, out_channels,
group=1):
super(Block, self).__init__()
self.b1 = ops.ResidualBlock... |
c95bb784ce0cc546ab5961ced108b93960d0c2e8e587b247bd864464ac9bedca | Python | 2,524 | 76 | #!/usr/bin/python
import sys
import os
import re
import numpy as np
import pandas as pd
import ConfigParser
import json
def ArrayIn(a1, a2):
return np.where(np.in1d(a1, a2))[0]
def main():
##### check argument #####
if len(sys.argv)<2:
sys.exit("ERROR: not enough arguments\nUSAGE ./celltype_stepPlotData.py <file... |
fd2e3ac01ee570441540464fdd8747324877d5cf95809d5da511732c183c1b78 | Python | 2,524 | 59 | import torch
import numpy as np
import torch.nn as nn
from torch.nn.functional import gumbel_softmax
EPS = 1e-10
class VQLayer(nn.Module):
'''
VQ-layer modified from
https://github.com/iamyuanchung/VQ-APC/blob/283d338/vqapc_model.py
'''
def __init__(self, input_size, codebook_size, cod... |
18f4d161c69eb7ce734396d0f7617331aaec0f60c2268f6893a8274390f5b5ca | Python | 2,525 | 85 | #!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# 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://... |
a3edb2b43115fd4e334cb3f7a0a4bbe2ab9a991197dd6d5ab32e9fe32964e291 | Python | 2,526 | 97 | import os
import sys
import pytest
import larvaworld
from larvaworld.lib import reg, sim, util
RUN_WINDOWS_HEAVY = os.environ.get("LW_ENABLE_WINDOWS_HEAVY") == "1"
pytestmark = [
pytest.mark.integration,
pytest.mark.heavy,
pytest.mark.skipif(
sys.platform.startswith("win") and not RUN_WINDOWS_HE... |
d035aa8501a395f24184f36922a486585213f6938de944050903dcfaaf007eea | Python | 2,526 | 81 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import pytorch_lightning as p... |
48b3e4be98b18ebb12597e862f1b9500b250cb646ca8babac121755e66da5686 | Python | 2,527 | 68 | """Input parameters functions"""
tmd_algos = ('tmd', 'tmd_gradient', 'tmd_apical')
def parameters(origin=(0., 0., 0.),
method='tmd',
neurite_types=('basal', 'apical', 'axon'),
feature='path_distances',
diameter_parameters=None):
'''Returns a default set... |
8b914c090e57bd97bad61325be02d5db221f6447f55001c6c715583adcc8fb28 | Python | 2,527 | 46 | #!/usr/bin/env python3
"""Пилотная проверка подмены twin, вторая версия (13 октября 2026): лаг-1
автокорреляция входа 8 по коротким окнам (200 тиков) и по всем агентам, прожившим
окно, а не только по долгожителям на 2000 тиков. Пять окон подряд после 600 тиков
прогрева. Seed'ы 101-103. Не подтверждающие данные."""
impo... |
b4239f9e8b8f221756c1402cd00896190a678102f0e576040ea287aaababac36 | Python | 2,527 | 68 | """Wrapper for limiting the time steps of an environment."""
from typing import Optional
import gym
class TimeLimit(gym.Wrapper):
"""This wrapper will issue a `truncated` signal if a maximum number of timesteps is exceeded.
If a truncation is not defined inside the environment itself, this is the only place... |
c2781d22e62d3fd2bdc0684459212d0f516e4165318379e0cc0f2b4967984e15 | Python | 2,527 | 70 | """
STC
"""
import sys
sys.path.append('..')
import mne
from config import fname,triggers
import argparse
import os
from pathlib import Path
import numpy as np
# Be verbose
mne.set_log_level('INFO')
# Handle command line arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('subject', t... |
d53d5ad68bf4b60a454e434fdcc7068c169ab639c102e0881223604812f4bade | Python | 2,527 | 73 | import unittest
import numpy as np
import torch
import torch.nn as nn
from bdpy.dl.torch import torch as bdtorch
class MockInnerModule(nn.Module):
def __init__(self):
super(MockInnerModule, self).__init__()
self.features = nn.Sequential(
nn.Linear(3, 4),
nn.Linear(4, 5)
... |
f06a3cf38778d30497d480c266f0e69bace3dc2e60a24482e02d927b71f734a7 | Python | 2,527 | 74 | from dolfin import *
import numpy as np
class MyExpression(Expression):
def eval(self, value, x):
value[0] = 1.0
def value_shape(self):
return (1,)
def rigid_motions(mesh):
gdim = mesh.geometry().dim()
x = SpatialCoordinate(mesh)
c = np.array([assemble(xi*dx) for xi in x])
vol... |
c7c8ec54ab96b1bfe1ab205e875c07c346ae49fea0ad83e099fc57977650d91f | Python | 2,528 | 92 | from numpy import prod
import torch
from torch import nn
from src.datasets import DatasetCMNIST, DatasetOSCN
from src.models.classifier import Classifier
from src.models.components import (
EncMLP,
EncMLPSimple,
EncCNN_CMNIST,
EncCNNAdd_CMNIST,
)
class Classifier_CMNIST(Classifier):
"""Classifier ... |
d537c0ba3fdc78c0732cb4a041e0d59e772175d304c562f76a229493b5f22d84 | Python | 2,528 | 75 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
311ea43751a836c3d585a40f08fa54a60d783a232aa50c5ea1225b689e9ac683 | Python | 2,529 | 98 | import logging
import sys
from io import StringIO
import pytest
from flask.logging import default_handler
from flask.logging import has_level_handler
from flask.logging import wsgi_errors_stream
@pytest.fixture(autouse=True)
def reset_logging(pytestconfig):
root_handlers = logging.root.handlers[:]
logging.r... |
bcd9884963548a689513351143cb919c0fa81d1af094bd2bed6f931d65c7b0ab | Python | 2,529 | 84 | import matplotlib.pyplot as plt
import numpy as np
from modular_splicing.gtex_data.annotation.compute_optimal_sequence import (
choose_optimal_sequence_for_gene,
)
def render_gene(sites, psis, junctions, junction_tpms, annotations_chosen, xlim=None):
"""
Render the given gene.
Parameters
--------... |
c0570ebade704dce4121a394b36855908efed88358e1137bd45286a6931c49ec | Python | 2,530 | 74 | #from distutils.core import setup
from setuptools import setup
from distutils.extension import Extension
import sys
# fix problems with pythons terrible import system
import os
file_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(file_dir, 'prob2020/cython'))
SRC_DIR = 'prob2020'
if '-... |
f66f7eb4e77b23adcc510339973aafe2960c00b78f86f9ef673cdb0ef82c7a91 | Python | 2,530 | 66 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
fc165bd6d6c235ffd456e7e43b02e30d3b8947085f8e595a5e9815754b13c194 | Python | 2,530 | 74 | # for rgenetics - lped to pbed
# where to stop with converters
# pbed might be central
# eg lped/eigen/fbat/snpmatrix all to pbed
# and pbed to lped/eigen/fbat/snpmatrix ?
# that's a lot of converters
import os
import subprocess
import sys
import time
prog = os.path.split(sys.argv[0])[-1]
myversion = "Oct 10 2009"
g... |
08a058a1a0037e2b5ebf427a6fb5422579491767fcea2ecd0cf16de582b6bd30 | Python | 2,531 | 80 | import unittest
from spitfire import Library, Dimension
import numpy as np
class TestDimensionExceptions(unittest.TestCase):
def test_check_for_invalid_python_names_hyphen(self):
try:
x = Dimension('x-1', np.linspace(0, 1, 16))
self.assertTrue(False)
except ValueError:
... |
4554c7c77994fdd2ba2a8c50756c418aba619707f3e951551f26e8e9fd37c72a | Python | 2,532 | 112 | from __future__ import annotations
import typing as t
from http import HTTPStatus
from flask import Flask
from flask import jsonify
from flask import stream_template
from flask.templating import render_template
from flask.views import View
from flask.wrappers import Response
app = Flask(__name__)
@app.route("/str"... |
61e120d1b7298905c370dbbbfee884ce7500cbe1335bf3d11d43cf202e67d400 | Python | 2,532 | 70 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from complexPyTorch.complexLayers import ComplexBatchNorm2d, ComplexConv2d, ComplexLinear
from complexPyTorch.complexFunctions import complex_relu, complex_max_pool2d
batch_size = 64
trans = transfor... |
72f8b9cb65e2393b372ed1bfa3bfd7bdda78a265f727d4984ae625fac4b179d0 | Python | 2,533 | 85 | import os
import random as python_random
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateModel
from gradient_accumulator.layers import AccumBatchNormalization
from gradient_accumulator.utils... |
2c4f2702399673e2b4c12aba0d5c712f0e8f3561b48efb4bb6614c624fc538ea | Python | 2,534 | 71 | from typing import Dict, Tuple
import torch
from rbm.binary.grad import compute_gradient
from rbm.binary.sampling import sample_hiddens, sample_state
def update_parameters(
data : dict[str, torch.Tensor],
chains : dict[str, torch.Tensor],
params : dict[str, torch.Tensor],
lr : float,
centered : b... |
c9244bd5d08b44e1060a36cd3d1a47eabd94b879738a5baa219376b465109988 | Python | 2,535 | 78 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import rereference
from wyrm.processing import swapaxes
CHANS = 5
SAMPLES = 20
EPOS = 3
class TestRereference(unittest.TestCase):
def setUp(self):
dat = np.zeros((SAMPLES, CHANS))
... |
a58b2f251801d74e3b0a6d3315770b4d07699bdbece20556395680f9842722dc | Python | 2,536 | 90 | import numpy as np
def mtr_asym_curve(Z: np.ndarray) -> np.ndarray:
"""
Calculate the MTR asymmetry curve.
Parameters:
- Z: 3D numpy array of MTR data, with shape (num_rows, num_cols, num_dynamics)
Returns:
- MTR asymmetry curve, with shape (num_rows, num_cols, num_dynamics)
"""
dyns... |
c66bb49078dd3a30f903e402c8263e4bca92638ff0c8658e45631a587ce55a8d | Python | 2,536 | 83 | import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.models import load_model
from gradient_accumulator import GradientAccumulateOptimizer
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) / 255., label
def test_opti... |
b0ac3099553daddb32ceeedd5f254e0f659b8341b729f1edb8226132eb50c3c7 | Python | 2,537 | 81 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import pytorch_lightning as p... |
ca5c1dda4d37b56d8c8b16531e269bde862ea2d58f778a10e7ff63a4ebe56390 | Python | 2,537 | 69 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import select_ival
from wyrm.processing import swapaxes
class TestSelectIval(unittest.TestCase):
def setUp(self):
ones = np.ones((10, 5))
channels = ['ca1', 'ca2', 'cb1', 'cb2', ... |
e89446c3ef86a2a0b2ad0dcb5f35613bb055aff6ec1a135d004ef00dd950728e | Python | 2,537 | 67 | import torch
import numpy as np
import pandas as pd
from os.path import join
from pathlib import Path
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
class DSet(Dataset):
''' This is the WSJ parser '''
def __init__(self, path, split):
# Setup
self.path = path
... |
fb233a5169f049987c3a309f4156bb474d5e0f122b237e3542ade823f9a757ba | Python | 2,537 | 105 | import numpy as np
from neuron import gui
from neuron import h
def check_solution(y_no_table, y_table, rtol):
assert np.allclose(
y_no_table, y_table, rtol=rtol
), f"{y_no_table} != {y_table}, delta: {y_table - y_no_table}"
# The approximation by a linear lookup table can't be exact.
assert n... |
8e61ad2b213b9443e86aaae1d4c81dc795b9b86659d403b7d4232ba53dec761b | Python | 2,538 | 112 | import os
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import numpy
import numpy as np
import pandas as pd
import importlib
import snapatac2 as sa2
import gc
# importlib.reload(sa2)
import snapatac2._snapatac2 as internal
import pyprojroot
code_root_dir = str(pyprojroot.here())
pack_dir = f"{co... |
a7d368b65db8c9410911664aebcd929b6c8f21828f533ced3256761e408313bb | Python | 2,539 | 49 | # /usr/local/bin/trinityrnaseq/util/support_scripts/../../Trinity --single "/Users/foo/datasets/trinity/trinity_out_dir/read_partitions/Fb_0/CBin_0/c0.trinity.reads.fa" --output "/Users/foo/dataset
# s/trinity/trinity_out_dir/read_partitions/Fb_0/CBin_0/c0.trinity.reads.fa.out" --CPU 1 --max_memory 1G --run_as_paired -... |
cd9f876c421d11de12c414bb521e8e936213bf2c6a9c93d5cd637a4aea71c96f | Python | 2,539 | 101 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test objects and function in tfep.utils.misc.
"""
# ==========================================================... |
e0a775c7e62a242e72c863cb4e6a11534394f98289e02085f982a7c9138d2748 | Python | 2,539 | 94 | """Functions and utilities for downloading example data."""
import os
from urllib.request import urlretrieve
import numpy as np
from specparam.io.utils import fpath
###################################################################################################
###################################################... |
f6778f53db92860840c8a9424b0d663d64c5286f71cf4be116d82c98a536dccc | Python | 2,539 | 69 | from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from bream4.device_interfaces.devices.promethion import PromethionGrpcClient
# INST-73
def set_channels_to_well(device: "PromethionGrpcClient", channel_config: dict[int, int]) -> None:
# We need to make sure sa... |
0a7f888c1e4ed880ff2bb38b67b428101bb58dfccafe80b0f81f2a3660571804 | Python | 2,541 | 56 | """Hand-pinned independent facts for the backend-parity golden suite.
b9 R75-4: the golden suites are self-referential by construction -- they
regenerate expected output THROUGH the code under test, so they detect
CHANGE, not correctness. The mitigant (modeled on ``capture_oracle``'s
hand-pins) is at least ONE fact pe... |
556b84473aa49e22f0f010b003629272fce72b4111518a4f08fdc4ae28e43111 | Python | 2,541 | 82 | '''
Implements the translatable text blueprint for Markdown containers.
It comes with a dcc.Store containing the translation key corresponding to the
target textual content. This key must be given when the blueprint is created
as it also serves as id-prefix for the component id.
'''
from dash import html, dcc
from ... |
eec1dc3ac4e0b10b7cfa1647ce9572c965b63a38000defc0509dca1fe91da375 | Python | 2,541 | 61 | """P7: one torch producer (decomposed), with the S15 retention schedule.
The legacy torch producer, its ``TORCHLENS_CAPTURE_PRODUCER`` dual-path
switch, ``_op_event_from_log``, ``_event_from_record``, and the parity
comparator died in P7. This module guards BOTH halves of that deletion:
* torch captures journal decom... |
c6e7c42d0aef3cf624affd2aaa9fd6f4659d135e0b6f55c553beda8207824557 | Python | 2,542 | 86 | from __future__ import division, print_function
import numpy as np
from numpy import inf, ndarray
import pandas as pd
import torch
import torch.nn as nn
from torch.functional import F
import os
import random
import sklearn
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn import metrics
import re
... |
e374ae11550ded97d9bb0af5f18c596f4a8deda47017d329e66cdfe666b6ed49 | Python | 2,542 | 86 | """Add org memberships.
Revision ID: 711ce9f88326
Revises: 951141858cff
Create Date: 2024-08-26 18:17:36.679046
"""
from uuid import UUID
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "711ce9f88326"
down_revision = "951... |
2669f5548a747c196006ba99fb250841555be7e340c4d05d89b5c02d5af63cf2 | Python | 2,545 | 52 | ##########################################################################
## ##
## Copyright (c) 2019-2024 Philipp Lösel. All rights reserved. ##
## ##
## This file is par... |
7b0abaee0e30fe90185693e37fa05f1ea491f39ed78e85f8bf9d637d67a246c1 | Python | 2,545 | 65 | from larvaworld.lib.model.modules.sensor import Olfactor, OSNOlfactor, Thermosensor
import numpy as np
class LocalOlfactor(OSNOlfactor):
def __init__(self, server_port=5795, remote_dt=100, remote_warmup=500, **kwargs):
self.last_osn_activity = None
print("**** LocalOlfactor ****")
print(kw... |
494e5b41163f45cac5797acb37bde499fbbed5dbdc21a2df7090a5353617586f | Python | 2,546 | 112 | import os
import sys
import pytest
from flask import Flask
from flask.globals import app_ctx as _app_ctx
@pytest.fixture(autouse=True)
def _standard_os_environ(monkeypatch):
"""Set up ``os.environ`` at the start of every test to have
standard values.
"""
for key in (
"FLASK_ENV_FILE",
... |
743f91c6b3e9cb278933ee9ea8b04fa6770d09600198eaffaa52b6e563c6c185 | Python | 2,547 | 52 | import os
import glob
#print [name for name in os.listdir(".") if os.path.isdir(name)]
inputdir = ""
print(inputdir)
counter = 0
for name in os.listdir(inputdir):
print(name)
if os.path.isdir(os.path.join(inputdir,name)) and not ("Output" in name):
curr_dir = os.path.join(inputdir, name)... |
400c046f972859e8beba87752c4d433c66a7b2c94d84bac1c6a64f7d69bfe834 | Python | 2,548 | 94 | # Adapted from code & formulas by David Z. Creemer and others
# http://www.zachary.com/blog/2005/01/12/python_zipcode_geo-programming
# http://williams.best.vwh.net/avform.htm
#
from math import sin,cos,atan,acos,asin,atan2,sqrt,pi, modf
import csv
from skmob.utils import constants
# At the equator / on another great... |
bbb7ad53d61b92c127deb9b759582901af0fe01ac730e2e71abbc698e2e9a4c8 | Python | 2,548 | 75 | from time import sleep
from tasks import identity_task, mul, wait_for_revoke, xsum
from visitors import MonitoringIdStampingVisitor
from celery.canvas import Signature, chain, chord, group
from celery.result import AsyncResult
def create_canvas(n: int) -> Signature:
"""Creates a canvas to calculate: n * sum(1..... |
c9d6fcaf0728ad69e5936ae29a8574abeb3dc62e273094474206e261f2d89427 | Python | 2,548 | 76 | """The module describes the ``env`` job metrics plugin."""
import logging
import re
from . import InstrumentPlugin
from ..formatting import JobMetricFormatter
from ..safety import Safety
log = logging.getLogger(__name__)
class EnvFormatter(JobMetricFormatter):
pass
class EnvPlugin(InstrumentPlugin):
"""I... |
e790557bf6ab9b4e5e36b777acd595b91537cc5790ec3f40ef06e6d3a5a1b4f1 | Python | 2,548 | 90 | __author__ = 'quentin'
import unittest
import time
import shutil
import random
import tempfile
from ethoscope.tracking.roi_builders import ROI
from ethoscope.utils.io import ResultWriter#, SQLiteResultWriter
from ethoscope.tracking.trackers import DataPoint, BoolVariableBase, IntVariableBase, DistanceIntVarBase
imp... |
13daa45950273aea226dce15d9fb638d0c08ba4986124be317f2b95600f9bd34 | Python | 2,552 | 64 | """Deployment envelope (lane F37): device_map dispatch capture + compat row.
Single-execution-device dispatch (the pure-CPU map, cpu/disk offload maps) is
capture-supported and its compat row reads pass/info; multi-real-device maps
keep the honest known_broken until the GPU campaign (C-DEPLOY) verifies
cross-device mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.