sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
35ba9c00322f7e1ad7ff640d0adbbc48f3322cb71dc22f6baaf019b5c2bdbe54 | Python | 443 | 19 | from webbrowser import get
from get_expression_matrix import get_expression_matrix
import pandas as pd
def test_alwaysPass():
assert True
def test_alwaysFail():
assert False
def test_example_cropped():
# run script
get_expression_matrix("examples/cropped")
test_df = pd.read_excel("examples/cro... |
d8dd2a531e6f901d679d9dcdb8be72da65630db0d16456db1ebfe090ddccd2c8 | Python | 443 | 18 | """
© 2022, ETH Zurich
"""
from rescoss_logp_ml.utils import HPARAMS
from rescoss_logp_ml.run_model import get_model, get_h_param_combinations
import pytest
@pytest.mark.parametrize("model_name", ["rf", "lasso", "xgb", "chemprop"])
def test_getting_models(model_name):
h_params = get_h_param_combinations(HPARAMS... |
37f380b89133875c10764d18e470e0634b9da03ba771f837a9cceac11ef32381 | Python | 444 | 19 | import lazy_loader as lazy
from importlib.metadata import version
try:
__version__ = version("benchnirs")
except Exception:
__version__ = "dev"
__getattr__, __dir__, __all__ = lazy.attach(
__name__,
submod_attrs={
'load': ['load_dataset', 'load_homer'],
'viz': ['epochs_viz'],
... |
a923b71b1421144d44fd9f5e99b9790aaa5ac4d472f48c0e9758331d41b869d0 | Python | 444 | 18 | import numpy as np
import torch
from src.criterion import WeightedMSELoss
from src.deepct_model_multi_ct_q import qDeepCT
class TestqDeepCT:
def test_init(self):
model = qDeepCT(
sequence_length=1000,
n_cell_types=1,
sequence_embedding_length=32,
cell_type_... |
db88270432b750b6fca1d013ba1b65109dc15be737ebbca4d1b8f2c9484259b1 | Python | 444 | 21 | from graphxai.datasets import ShapeGGen
SG = ShapeGGen(
model_layers = 3,
num_subgraphs = 100,
prob_connection = 0.08,
subgraph_size = 10,
class_sep = 5,
n_informative = 6,
n_clusters_per_class = 1,
verify = False,
make_explanations=False
)
data = SG.get_graph()
print('All X:\n', ... |
9282ac7b24932a7007b31a72344698d1113c38bb7001d25853cbe15a42407d31 | Python | 446 | 16 | #!/usr/bin/env python
#coding:utf-8
#!/usr/bin/env python
from __future__ import print_function
import sys
from mmseg import seg_txt
for line in sys.stdin:
blks = str.split(line)
out_line = ""
for i in range(0, len(blks)):
if blks[i] == "[VOCALIZED-NOISE]" or blks[i] == "[NOISE]" or blks[i] == "[LAUGHTER]":
... |
55bc3c78eb779c24c581cc2652de1231d39e0a12ecbaa303778c224541c063e7 | Python | 447 | 18 | # Copyright (c) Open-MMLab. All rights reserved.
import time
from .hook import HOOKS, Hook
@HOOKS.register_module()
class IterTimerHook(Hook):
def before_epoch(self, runner):
self.t = time.time()
def before_iter(self, runner):
runner.log_buffer.update({'data_time': time.time() - self.t})
... |
a67eac0e3790ee7f1bcaa2545856a6ad9242fabb48897e62d8d4db6e7197cc5f | Python | 448 | 24 | # Libraries
import pandas as pd
import numpy as np
# Load specific dataset
from sklearn.datasets import load_diabetes
# Load dataset
dataset = load_diabetes(as_frame=True)
# This dataset is for regression so it does not have
# a lavel conversion. It is also weird the fact that
# sex is a number.
# Format
data = dat... |
0701e2062245ab6c90b3df6934a21be5c942b44b13c2ebb70695433599af7a15 | Python | 449 | 12 | # -*- coding: utf-8 -*-
# File : __init__.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
from .batchnorm import SynchronizedBatchNorm... |
5eb70b1fbc43d0d0ad168f8d8219b971520ea7593ba8e24c28c47a947ef698f1 | Python | 449 | 19 | #!/usr/bin/env python
import json
import sys
from array_tomography_tool import server_run_colocalisation
def cast_config(config, keys):
for key in keys:
config[key] = float(config[key])
if __name__ == "__main__":
config_string = sys.argv[1].replace("'", '"')
config = json.loads(config_string)
... |
c61962866014604e2cf5cbfc5aa4aadf885474a31feb4947962315267c26d320 | Python | 449 | 20 | '''
- disk - creates ellipsis; implemented better refinement
'''
import mesh
import mesh.plot.trimesh_viewer as mplot # visualize
name = 'plane'
sizes = (10, 5, 1)
grids = (10, 10, 1)
plane = mesh.cuboidXY_create(name, sizes, grids)
tri = mesh.triangulate_system(plane)
## Visualize
import mesh.plot.trimesh_viewer ... |
5e6ccc4a4e3e0bf89625cb05f9476c80eae12027b56ad1483233df5fc547ffee | Python | 451 | 18 | import mesh
import mesh.plot.vedo_viewer as mplot
folder = 'data/two_cilia_machemer0/' # cilia_plane'
mv = mplot.MeshViewer(folder)
# plotter = mv.show()
# plotter.close()
# Plot with arrows
names = ['flagellum_1', 'flagellum_2']
scale = 1
min_arrow_length = 0 # 1 um
arrows = mplot.VelocityArrows(folder, names, poi... |
96580d233306f64cc6f9c5ece596b8b0a8ff62c07a04a1603bc9af704ba675c7 | Python | 452 | 25 | import sys
from pathlib import Path
from typing import Any
from ppqm.utils import shell
# Default scratch directory
SCR = Path("./")
# Coordinates name
COLUMN_COORDINATES = "coords"
COLUMN_ATOMS = "atoms"
COLUMN_ENERGY = "total_energy"
COLUMN_ENTHALPY = ""
# tqdm default view
TQDM_OPTIONS: dict[str, Any] = {
... |
f172d2ffe72d8649946584b1edee3be93283f4be6911c8160d233b9ab1b6c7d2 | Python | 452 | 15 | import sklearn.linear_model as linear_model
def linearRegressor(pred, gt, test, n_kpts=10, reg_pts=5):
pred = pred.reshape(-1, n_kpts*2)
gt = gt.reshape(-1, reg_pts*2)
test = test.reshape(-1, n_kpts*2)
# shape: (N, C)
regr = linear_model.Ridge(alpha=0.0, fit_intercept=False)
_... |
fce0f53d6a4367b40a9514a89e62873060a6664f8c884e8eb8a911caa0dccb1e | Python | 452 | 20 | __author__ = "Jan Forster"
__copyright__ = "Copyright 2019, Jan Forster"
__email__ = "j.forster@dkfz.de"
__license__ = "MIT"
from snakemake.shell import shell
## Extract arguments
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
shell(
"(bedtools intersect"
"... |
756a2e54828c42a93264b66dd42a63c731e690db0f687cbe68898fe415a59068 | Python | 453 | 21 | """Snakemake wrapper for picard RevertSam."""
__author__ = "Patrik Smeds"
__copyright__ = "Copyright 2018, Patrik Smeds"
__email__ = "patrik.smeds@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=False, stderr=True)
shel... |
c8416977977bff5daaff508ed7e833ea797dc68319b61b839541cf6a893bf2f3 | Python | 453 | 16 | import numpy as np
from my_utils import *
data_dir = 'data/wcst_200306/data'
# data_dir = 'data/wcst_200306/test'
out_dir_name = 'data/wcst_200306_20dim/data'
# out_dir_name = 'data/wcst_200306_20dim/test'
size = 20
for i in range(size):
data = np.loadtxt(data_dir + str(i),
delimiter=' ', sk... |
ebf292d616693144c0da2aab4c7e25d50d6ba8783dc3ec8767c2cd0d739a673a | Python | 453 | 18 | #!/usr/bin/env python
import json
import sys
from modules import colocalise
def cast_config(config, keys):
for key in keys:
config[key] = float(config[key])
if __name__ == "__main__":
config_string = sys.argv[1].replace("'", '"')
config = json.loads(config_string)
cast_config(config, ["xy_r... |
6e3abd3208677d37c75837c28bfb4e609a140e2d552ac092bc61223839cf5c7e | Python | 454 | 21 | from contextlib import ContextDecorator
from .._config import CONFIG
class ConfigContext(ContextDecorator):
def __init__(self, key, value):
self.key = key
self.value = value
self.old = None
def __enter__(self):
self.old = CONFIG[self.key]
CONFIG[self.key] = self.valu... |
7c1dcd231d487d1ce76b30605ba0c2121a91ad3f5a0e4471767ad6b61034cb62 | Python | 455 | 13 | # This recipe toggles on several layers in our "_Opt" maps
# Load town one with only minimum layout (roads, sidewalks, traffic lights and traffic signs)
world = client.load_world('Town01_Opt', map_layers=carla.MapLayer.NONE)
# Toggle all buildings on
world.load_map_layer(carla.MapLayer.Buildings)
# Toggle all foliag... |
9a7c2bed7313b12a1364d322379ccd9d559d48880b84f05641e268e9f9ee3bb0 | Python | 455 | 10 | """carla-cosmos server: HTTP/JSON job API in front of Cosmos worker processes.
Layout: :mod:`config` (env settings) -> :mod:`launcher` (profile, workers,
uvicorn) -> :mod:`app` (FastAPI: :mod:`auth`, :mod:`blobs`, :mod:`jobs`,
:mod:`models`, :mod:`metrics`, :mod:`ui`) -> :mod:`scheduler` (queues,
dispatch to :mod:`wor... |
8574a6090bc033f44984692ac28fa7a415022892c2c9246c8c2adfbec67fb6b5 | Python | 456 | 12 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
shell(
"(export MOSDEPTH_Q0=NO_COVERAGE && "
" export MOSDEPTH_Q1=LOW_COVERAGE && "
" export MOSDEPTH_Q2=CALLABLE && "
" mosdepth -n -F 1804 -Q 1 --quantize {snakemake.params.quantiles} --by {snakemake.params.by... |
951f128871d4cf9073d88bc200f5b258486541f4b929e52cbcbf3fe42301526c | Python | 456 | 9 | metadata_wgs
donor_wgs=metadata_wgs['Cell.lineID']
# donor_wgs = donor_wgs[(metadata_wgs['Tissue'] == 'iPSC') & (metadata_wgs['WGS'] == 'avail')]
donor_wgs = donor_wgs[(metadata_wgs['Tissue'] == 'iPSC') & (metadata_wgs['scRNAseq'] == 'avail')]
donor_rna = df_eff.donor_id.map(lambda s: s.split('-')[1].split('_')[0])
do... |
df5c3ada7cbd7aefe6298d16d646e97e73283eae4bdb6838c48c826afe7de093 | Python | 459 | 20 | '''
'''
import mesh
position = (0, 0, 0)
radius = 1
velocity = (2, 0, 0)
angular = (0, 0, 3)
sphere_grid = 16 # Mesh consisting of 4x4 nodes
# Create mesh
sphere = mesh.sphere_create('sphere', position, radius, velocity, angular, sphere_grid)
tri = mesh.triangulate_system(sphere)
## Visualize
import mesh.plot.trime... |
739d9c39a0f2bcade305087aee0e47a11621174a30f758dcd9fbe9ef32ce57c2 | Python | 460 | 12 | import os
import json
risksofbias = {}
for file in os.listdir('robotreviewer_report'):
with open('robotreviewer_report/'+file,'r') as infile:
jsondata = json.load(infile)
for i in range(len(jsondata['article_data'])):
filename = jsondata['article_data'][i]['gold']['filename']
... |
ba814e49b80532aa3447f092d5d9cae12acf0cffaf5ca175e70d7cfbf9cbb1ed | Python | 460 | 21 | import sys
from dataclasses import dataclass, field
from typing import Any, List
from oaklib import BasicOntologyInterface
@dataclass
class StreamingWriter:
"""
Base class for streaming writers
"""
file: Any = field(default_factory=lambda: sys.stdout)
ontology_interface: BasicOntologyInterface = ... |
d8cdeaa020d35cd45d7b0c99c1378879c1ac59ee18c1b406b0815399b349c304 | Python | 460 | 19 | """Snakemake wrapper for running samtools depth."""
__author__ = "Dayne L Filer"
__copyright__ = "Copyright 2020, Dayne L Filer"
__email__ = "dayne.filer@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
params = snakemake.params.get("extra", "")
# check for optional bed file
bed = snakemake.input.ge... |
1c66d6e7eab7a3edfa6175ece6d8a753fd62ed7773a3c3e84c5174358fe53344 | Python | 461 | 12 | from distutils.core import setup
exec(open('wmhpypes/version.py').read())
setup(
name='wmhpypes',
version='__version__',
packages=['wmhpypes', 'wmhpypes.utils', 'wmhpypes.interfaces', 'wmhpypes.workflows'],
url='https://github.com/0rC0/WMHpypes',
license='BSD 3-Clause License',
author='Andrea De... |
b525fb02b0b1a270d6ae54696ad17c242cae9cdb3383a0b0fad437a8eeabb9e3 | Python | 461 | 12 | """
This module provides the types for representing biological sequences.
"""
from .sequence import Sequence
from .sequence import sequence_to_encoding
from .sequence import encoding_to_sequence
from .sequence import get_reverse_encoding
from .genome import Genome, TokenizedGenome
from .proteome import Proteome
__all_... |
df340937c938ed098fc7922b75546a86d1a42978a0a3a54f88f3b1b457ec1a95 | Python | 465 | 18 | import mesh.plot.trimesh_viewer as plot3D
path = 'data/sphere_wall'
# Plot with random colors for each object
m = plot3D.MeshViewer(path, group='.')
m.show()
# Plot with pre-defined colors
names = ['sphere', 'plane']
colors = [(0., 1., 1., 1), (1., 1., 0, 1)]
m = plot3D.MeshViewer(path, group='.', names=names, colo... |
8a95003473a2f3903c326d7ef264b3d56b0427b2910f092b9afda59cb020d137 | Python | 466 | 15 | import os
# get absolate path of the current file
dir_testdir = os.path.dirname(os.path.abspath(__file__))
# set working directory to the two levels up
wd = os.path.dirname(dir_testdir)
# Jinlong test data
dir_data = os.path.join(wd, "tests/test_data/")
fin_fasta = os.path.join(dir_data, "1xqfA.fasta")
fin_pdb = os.p... |
8d0afec224cb127343cb90cb7ce54759d80f8e83f93fbc872a6ca531ae987966 | Python | 466 | 11 | from easydict import EasyDict
from configs.experiments import task1_augmented_config
from copy import deepcopy
# Task2 uses pretrained model with linear probe and then further fine tuning
task2_baseline_config = deepcopy(task1_augmented_config)
task2_baseline_config.split_videos = True
task2_baseline_config.linear_pro... |
772c6f1eb5c0221e515fc4f1abcfb24ca9c1e96ccae521a995d68475af028256 | Python | 467 | 20 | import networkx as nx
import matplotlib.pyplot as plt
from torch_geometric.utils import from_networkx
from graphxai.datasets.utils.bound_graph_pref_att import ba_around_shape
from graphxai.utils import node_mask_from_edge_mask
house = nx.house_graph()
for n in house.nodes:
house.nodes[n]['shape'] = 1
G = ba_a... |
cd36056aa7d44df748bb7339ea720740e415455e18f1d99fb256fe7917f5fa14 | Python | 467 | 17 | import torch
from ..padding import DomainPadding
import pytest
def test_DomainPadding():
data = torch.randn((2, 3, 10, 10))
padder = DomainPadding(0.2)
padded = padder.pad(data)
# With 0.2 padding and symmetric mode, output size should be 14
target_shape = list(padded.shape)
target_shape[-1] ... |
213e2a1f46b4732e72f6b7b606187ed81a667b68ca79cdb630790b88753769c2 | Python | 468 | 30 | from abc import ABCMeta, abstractmethod
class ProjectBase(metaclass = ABCMeta):
@property
@abstractmethod
def context(self):
pass
@context.setter
@abstractmethod
def context(self, value):
pass
@property
@abstractmethod
def data_io(self):
pass
@data_i... |
d8ec0d593fc03398f211fed3a98928fcb0e946dd3bbc92dfa3f34f89df3e8642 | Python | 468 | 11 | # This recipe toggles off several layers in our "_Opt" maps
# Load town one with minimum layout (roads, sidewalks, traffic lights and traffic signs)
# as well as buildings and parked vehicles
world = client.load_world('Town01_Opt', map_layers=carla.MapLayer.Buildings | carla.MapLayer.ParkedVehicles)
# Toggle all bui... |
e6137acf6b93954351467fef94e0256e889a70fc2c1633207af4964e035274bf | Python | 468 | 17 | #!/usr/bin/env python3
# Copyright 2018 Chun-Chieh Chang
# This script reads in text and outputs the normalized version
import io
import re
import sys
import unicodedata
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding="utf8")
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf8")
for line in sys... |
2cd622401848ab9ab58f45ccaef1f6ea862ac6774f1ca5820a72678d190f8bb4 | Python | 469 | 26 | from lxml.etree import parse, XSLT, tostring
import sys
try:
infile = sys.argv[1]
inss = sys.argv[2]
except:
print "usage: cml2nml _fileToConvert_ _schema_"
sys.exit(1)
try:
dom = parse(infile)
except:
print "can't parse infile " + infile
sys.exit(1)
try:
xslt = parse(inss)
except:
... |
9252c128e9b14b039418233de7bf3669ddf097f74a082fdabf60703619e3108b | Python | 469 | 20 | from setuptools import setup
setup(name='prieml',
version='0.0.1',
description='',
url='https://github.com/CMI-UZH/PRIDICT',
packages=['prieml'],
python_requires='>=3.6.0',
install_requires=[
'numpy',
'pandas',
'scipy',
# 'scikit-learn... |
056a175fc911279f30d7786aff1efc0e82d40b55851075760c6e497c0a1250b1 | Python | 470 | 20 | from abc import ABC
from dataclasses import dataclass
from typing import Any
@dataclass
class OntologyTransformer(ABC): # noqa
"""
A class for transforming ontologies
"""
def transform(self, source_ontology: Any, **kwargs) -> Any:
"""
Transforms an ontology into another ontology
... |
3526a22c6d4b841b185645abf27ac126f0d2ae18c23c76dc49cc20d2edcc631b | Python | 471 | 20 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Main script running AxoID on experiment(s), detecting and tracking ROIs, then
extracting fluorescence traces and saving outputs.
Created on Thu Jun 6 09:58:59 2019
@author: nicolas
"""
import os.path
import sys
# Add parent folder to path in order to access `axoid`... |
7e4ac8f9d6426b91b2a11b2a5f1bbd07d45394968152c3db9703f1675d6c8d10 | Python | 471 | 13 | '''The submodule slideflow.tfrecord is a modified version from https://github.com/vahidk/tfrecord'''
from slideflow.tfrecord import tools
from slideflow.tfrecord import torch
from slideflow.tfrecord import example_pb2
from slideflow.tfrecord import iterator_utils
from slideflow.tfrecord import reader
from slideflow.t... |
1167d8a9313ff67f3e2c09979b7098858cec02e6d8272ac84743f910be6eaa3e | Python | 472 | 14 |
def reduce_precision(value, prec=2):
return "{:.{}f}".format(round(float(value), prec), prec)
def reduce_case_precision(case, prec=2, columns=[]):
for i, f in enumerate(case):
if columns is None or i in columns:
case[i] = reduce_precision(f, prec)
return case
def reduce_casecase_preci... |
48efaec42b5651f865a09ba296526ed338ab1331a39fd88e0f05ed91d4ff370a | Python | 472 | 18 | import os
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--port", default=8000, type=int, help="port to listen on")
args = parser.parse_args()
os.chdir('static')
server_address = ('', args.port)
... |
54d94201aeb848b942febc83f3b6b0258d0e23c0b95337745bc60d9c54d150e5 | Python | 472 | 14 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from eelbrain import datasets, load
from eelbrain._utils import IS_OSX
from eelbrain.testing import assert_dataobj_equal, file_path
def test_pickle():
ds = datasets.get_uts()
decimal = None if IS_OSX else 15
ds_2 = load.unpickle(file_path('uts-py2.... |
fb9801de411677f67dd5cef1fccf07850fcf1c23d72cd6d27fb6e55863866a88 | Python | 473 | 27 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from matplotlib import pyplot as plt
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
class Beaf(nn.Module):
def __init__(self):
super().__init__()
print("Beaf activation loaded...")
def forward(self, x):
x = x... |
260715c0011be95e263f92c88f51472669dac9e72d8cc78eb55a83c374cc75e3 | Python | 474 | 9 | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
ca753145f327d6d8ce00b306e6b14ab15d910106e70beba1aa7e23c6669ab103 | Python | 474 | 19 | import sys
sys.path.append("/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/")
import pymaid
import pyoctree
from pymaid_creds import url, name, password, token
#pymaid.clear_cache()
rm = pymaid.CatmaidInstance(url, token, name, password)
annotated = pymaid.get_annotated('mw neuron groups')
test1 = annota... |
9b56b02ad76c00a51d3e49a280c2965e872e3264c1fc91dcae5fdf13600e8c13 | Python | 475 | 12 | from .approx_max_iou_assigner import ApproxMaxIoUAssigner
from .assign_result import AssignResult
from .atss_assigner import ATSSAssigner
from .base_assigner import BaseAssigner
from .center_region_assigner import CenterRegionAssigner
from .max_iou_assigner import MaxIoUAssigner
from .point_assigner import PointAssigne... |
9fd9aba4a5deeeb60361866db68cf2695bf03542fcb23bd61d6fc3672069030b | Python | 475 | 31 | import sys
DEBUG: bool = True
TIMING: bool = True
TRACE_MEMORY: bool = True
INFO: bool = True
MB: int = 1024 * 1024
def debug(d):
if DEBUG:
print('DEBUG: ' + d)
def info(i):
if INFO:
print('INFO: ' + i)
def timing(t):
if TIMING:
print('TIMING: ' + t)
def debug_mem(message, o... |
d5f8242dea61655bb1cdbec6f15e4c19ba002d1e75ae74caf44d6ebc2d731da8 | Python | 475 | 9 | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
4a637c7ac6a027ebb56e70f5ef50d74631bb0ffb496d3b82b510ec9346b52bab | Python | 476 | 11 | from .dataset import get_dataset, GraphDataset, NodeDataset
from .load_synthetic import load_ShapeGGen
from .shape_graph import ShapeGGen
from .ba_houses import BAHouses
# Real-world datasets:
from .real_world.MUTAG import MUTAG
from .real_world.benzene.benzene import Benzene
from .real_world.fluoride_carbonyl.fluorid... |
c49612da59325706f9244ea208eb336b2c78f717c7b22227fa91d819554f0206 | Python | 477 | 12 | """mkdocs hooks: page-level HTML touch-ups that would otherwise mean editing
every page. Registered in mkdocs.yml under `hooks`."""
import re
# Any <img> that does not already say how to load itself. Browsers fetch eagerly
# by default, so a catalogue page pulls every image before the reader scrolls.
_IMG_WITHOUT_LOA... |
c6ea2d48eafd9e173a9eaa35a2bf19cbd825c728772181cb2aba91bd6ee1127e | Python | 478 | 14 | from constants.enumerates import ElectricalAppliances
ON_THRESHOLDS = {
ElectricalAppliances.DISH_WASHER: 10,
ElectricalAppliances.FRIDGE: 50,
ElectricalAppliances.KETTLE: 2000,
ElectricalAppliances.MICROWAVE: 200,
ElectricalAppliances.WASHING_MACHINE: 20,
ElectricalAppliances.TUMBLE_DRYER: 20,... |
3eb8dfb832c6cb3c467746074e96b59fb6b0656d62e5cbbd77a3b590cd35ff8c | Python | 479 | 19 | import numpy as np
import pytest
import tifffile as tf
from cenfind.core.data import Field
@pytest.fixture
def make_field(tmp_path):
"""Writes a small synthetic multi-channel TIF and returns a Field for it."""
def _make(data=None, shape=(2, 200, 200), dtype="uint16", name="field.tif"):
if data is No... |
cf2af40b8b299ccd80a9da38cf34e3fe72d201ed18ba814e123e301d77afa9e7 | Python | 479 | 11 | # Copyright (c) Open-MMLab. All rights reserved.
from .file_client import BaseStorageBackend, FileClient
from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler
from .io import dump, load, register_handler
from .parse import dict_from_file, list_from_file
__all__ = [
'BaseStorageBackend', 'F... |
fa86dc22400c2cc1b2ef94e5997f38e6f2338b546acd0cc1f2dbc0ed57c40492 | Python | 479 | 21 | import warnings
try:
import igraph
except ImportError:
igraph = None
warnings.warn('iGraph library not found. Will test only with NetworkX.')
import navis
def with_igraph(func):
def wrapper(*args, **kwargs):
navis.config.use_igraph = False
res1 = func(*args, **kwargs)
if igra... |
4024964f29c076cbbc21cee234cb6f5c05491cce3a89eb2d04f45838759412bc | Python | 480 | 16 | import matplotlib.pyplot as plt
#import seaborn as sns; sns.set()
import numpy as np
# Generate some data
from sklearn.datasets import make_blobs
X, y_true = make_blobs(n_samples=200, centers=2,
cluster_std=2, random_state=0)
X = X[:, ::-1] # flip axes for better plotting
c = {0: 'grey', 1: 're... |
5f881f4184150d7b56e06b6f0ea0c14f39293a6894bc64bf5b9e11eeb235eb63 | Python | 480 | 22 | # %% [markdown]
# #
from src.data import load_networkx, load_everything
import networkx as nx
from graspy.utils import binarize, symmetrize
graph = load_networkx("G")
nx.algorithms.diameter(graph)
# %% [markdown]
# #
adj = load_everything("G")
adj = symmetrize(adj, "avg")
graph = nx.from_numpy_array(adj)
nx.algorith... |
a7b80dba1259c0284e425f1dbb99e5b89fc636e6eccc6124543476f5c7f64807 | Python | 481 | 16 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# TODO maybe push this to nn?
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - tar... |
dfc93ba21c0b321b9f0a0f550320ffe76fe696a1629c10a833c8d9bd5d24cf84 | Python | 481 | 10 | """Validation shared by commands that require alignment tracks."""
def require_nonempty_track(track, input_format, role="input"):
"""Raise a descriptive error when loading or filtering kept no alignments."""
if track.total == 0:
message = f"No usable alignments remain in {role} after loading or filter... |
b53d398605ec09a02dec4ddef883ac557d60595d1144fa6ced3660b0e297150a | Python | 482 | 17 | """Snakemake wrapper for trimming paired-end reads using cutadapt."""
__author__ = "Julian de Ruiter"
__copyright__ = "Copyright 2017, Julian de Ruiter"
__email__ = "julianderuiter@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
region = snakemake.params.g... |
2bec8b3adc7f04c124641904e2f399e554dfbee0e76aa6cee0a2fbff0d853b8c | Python | 483 | 22 | """Snakemake wrapper for bwa aln."""
__author__ = "Julian de Ruiter"
__copyright__ = "Copyright 2017, Julian de Ruiter"
__email__ = "julianderuiter@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=False, stderr=True)
sh... |
2a6df44fb93487c86982064bd00307f12046e781ca90bf640af262fdf1d2a6c4 | Python | 485 | 15 | import os
import torch
root_path = '~/GraphXAI/data/ShapeGGen/'
# def load_ShapeGGen(number: int = 1, root: str = Owen_root):
# '''
# Args:
# number (int): Number of ShapeGGen to load.
# root (str): Root to directory containing all saved ShapeGGens.
# '''
# return torch.load(open(os.pa... |
907eae27a9adaae195d9abc0f7754ab243db594b6897310d103ac9e052af62de | Python | 485 | 11 | # Copyright (c) Open-MMLab. All rights reserved.
from .io import Cache, VideoReader, frames2video
from .optflow import (dequantize_flow, flow_warp, flowread, flowwrite,
quantize_flow)
from .processing import concat_video, convert_video, cut_video, resize_video
__all__ = [
'Cache', 'VideoReade... |
f6f14e1d7fde999c0520b576bd1e81008cf46040f8d1a51a31956b76bb2e59bb | Python | 485 | 9 | # Как должна работать данная функция:
# На вход получает последовательность спайков размерностью timestep x batch_size x number_of_neurons
# Далее высчитавает среднее значение межспайкового интервала
# Может накапливать и усреднять данные...
class InterspikeInterval:
def __init__(self):
dt: float = 1e-3
|
3d0134d0584f91b00236393417751a200f904a69657c217d960be4ce8cd7c8c0 | Python | 487 | 16 | from setuptools import setup
setup(
name='jie',
version='0.1.1',
python_requires='>=3.8',
author='Bojing (Blair) Jia',
packages=['jie'],
install_requires=['numpy>=1.20.3',
'pandas>=1.3.4',
'matplotlib>=3.4.3',
'seaborn>=0.11.2',
... |
59f54c509c9c30fc25a47f740d21db7711b7b3debd9ac6f8119d8a6e29ab1234 | Python | 487 | 14 | import nibabel as nib
import sys
from scipy import ndimage
import numpy as np
input_name = sys.argv[1]
output_name = sys.argv[2]
close_iter = int(sys.argv[3])
mask = nib.load(input_name).get_fdata().astype(bool)
affine = nib.load(input_name).affine
mask_mc = ndimage.morphology.binary_closing(mask,structure=np.ones((3... |
e80780430f2be84785506fb652a7ef18af0e8b32bc0e86e4a4bfd361ff35377a | Python | 487 | 20 | #!/usr/bin/env python
import json
import sys
from modules import segment
def cast_config(config, keys):
for key in keys:
if key in config:
config[key] = float(config[key])
if __name__ == "__main__":
print("Im running ")
config_string = sys.argv[1].replace("'", '"')
config = json... |
7d5b98da88ac4cdd79eefc5b0e0b6c5771a034eeb9fd6fa13d367c01b4e56810 | Python | 488 | 14 | from setuptools import setup, find_packages
setup(name='contools',
version='0.2',
description='tools for analyzing connectomics data from CATMAID instances',
url='http://github.com/mwinding/connectome_tools',
author='Michael Winding',
author_email='mwinding@alumni.nd.edu',
license='... |
76d3bc293752fea590bbd12eabbe1a0a9c5b4ae5b9f5973b7ed02811edc430fc | Python | 489 | 14 | # %%
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pymaid_creds import url, name, password, token
import pymaid
rm = pymaid.CatmaidInstance(url, token, name, password)
neurons_of_interest = pymaid.get_skids_by_annotation('mw MB ad in-out hubs')
neurons_of_interest =... |
7ca58918ae026fe041827be548d5acf86057c727ef069c8349be999ed3c66e3b | Python | 489 | 12 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
from .single_stage_detector import SingleStageDetector
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN,
"SingleStageDetector": SingleStageDetector,
... |
91a90d288f86d410b05c3743230aa22de062531b3a027328679ec3c07d3b9d67 | Python | 489 | 17 | # Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import glob
import os
import sys
try:
sys.path.append(glob.glob('../../carla/dist/carla-*%d.%d-... |
79cb4093162c6cace47e201982000b55d7400e2e5a1c2c41eb9e6952f486e698 | Python | 490 | 14 | from setuptools import setup, find_packages
setup(name='contools',
version='2.0.0',
description='tools for analyzing connectomics data from CATMAID instances',
url='http://github.com/mwinding/connectome_tools',
author='Michael Winding',
author_email='mwinding@alumni.nd.edu',
license... |
4962b298ed8df312ed719d3fbaa470172b952fe9d65fac01ae057a266e6fc1b7 | Python | 492 | 16 | import numpy as np
import nibabel as nib
import sys
from scipy.ndimage import gaussian_filter
n_masks = len(sys.argv)-3
output_name = sys.argv[-2]
smooth = (sys.argv[-1] == 'y')
affine = nib.load(sys.argv[1]).affine
combined = np.zeros(nib.load(sys.argv[1]).get_fdata().shape)
for i in range(1,n_masks+1):
m = nib.load... |
6944afdcdac16c60685f4a532b20427c0f776889439d9325db533ba11f31d8d9 | Python | 492 | 22 | """Snakemake wrapper for picard MergeSamFiles."""
__author__ = "Julian de Ruiter"
__copyright__ = "Copyright 2017, Julian de Ruiter"
__email__ = "julianderuiter@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
inputs = " ".join("INPUT={}".format(in_) for in_ in snakemake.input)
log = snakemake.log_... |
6ab13addaae3eec7d5f867c6d3446314a0305ed3acd30ffd792d269c7a0afbd5 | Python | 492 | 16 | # Gets the test indices for a given SG dataset
# Saves them so we can parallelize metrics
import os
import torch
import numpy as np
my_base_graphxai = '/home/owq978/GraphXAI'
bah = torch.load(open(os.path.join(my_base_graphxai, 'data/ShapeGGen/unzipped/SG_homophilic.pickle'), 'rb'))
data = bah.get_graph(use_fixed_sp... |
98abc82ef293073dee5046fd2c85b9e1c6809f664e0adab1ce2d680ac4b83056 | Python | 493 | 16 | import torch
class RandomDataset(torch.utils.data.Dataset):
def __init__(self, root=None, train=True, transform=None, target_transform=None):
self.transform = transform
self.target_transform = target_transform
self.size = 1000
def __getitem__(self, idx):
if idx < self.size:
... |
5a773f657d3f60623932c5952bbb8e8eb353ed8d55464eb3f6f06c440825af4c | Python | 494 | 18 | __author__ = "Jan Forster"
__copyright__ = "Copyright 2019, Jan Forster"
__email__ = "jan.forster@uk-essen.de"
__license__ = "MIT"
import os
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
java_opts = snakemake.params.get("java_opts", "")
log = snakemake.log_fmt_shell(stdout=True, stderr... |
80ab8f5a12262e758e06924bedad734a2d60c4f0a7023ea2406ed939b859052f | Python | 494 | 13 |
# This recipe shows how to draw traffic light actor bounding boxes from a world snapshot.
# ....
debug = world.debug
world_snapshot = world.get_snapshot()
for actor_snapshot in world_snapshot:
actual_actor = world.get_actor(actor_snapshot.id)
if actual_actor.type_id == 'traffic.traffic_light':
debug.... |
ead072c2f7abc1156e6a771ef617a1dd09a466b62108dadf06ce298ba15e51b3 | Python | 494 | 21 | from .coco_eval import do_coco_evaluation
def coco_evaluation(
dataset,
predictions,
output_folder,
box_only,
iou_types,
expected_results,
expected_results_sigma_tol,
):
return do_coco_evaluation(
dataset=dataset,
predictions=predictions,
box_only=box_only,
... |
24cb9e40eb2dd337a1852422ab28f4d0de9efd10e04f715ab566b8f01945d29d | Python | 495 | 20 | import torch
import matplotlib.pyplot as plt
from graphxai.datasets import ShapeGGen
arg_dict = {
'num_subgraphs': 5,
'prob_connection': 0.25,
'subgraph_size': 8
}
fig, (ax1, ax2) = plt.subplots(1, 2)
sg1 = ShapeGGen(**arg_dict, model_layers = 3, seed = 8001)
sg1.visualize(shape_label = True, ax = ax1)
... |
7d542ea96254e2a0544a502e8a9f67e1984e5a59dc18311df3b8c81277509e3f | Python | 495 | 18 | # %%
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import math
# %%
#matrix = np.random.randint(50, size=(2500, 2500))
matrix = pd.read_csv('data/G-pair-sorted.csv', header = 0, index_col = 0)
fig, ax = plt.subplots(1,1,figsize=(4,4))
#sns.heatmap(matrix, ax = ax, cmap='... |
b880c05886f2290229dffa3e17accc354ca91a1544c4d27662055017905b2dd8 | Python | 495 | 27 | # Label values
W = 0
N1 = 1
N2 = 2
N3 = 3
REM = 4
UNKNOWN = 5
NUM_CLASSES = 5 # exclude UNKNOWN
class_dict = {
0: "W",
1: "N1",
2: "N2",
3: "N3",
4: "REM"
}
EPOCH_SEC_LEN = 30 # seconds
SAMPLING_RATE = 256
def print_n_samples_each_class(labels):
import numpy as np
... |
927de3610ee62fc003edefccb0697bfb34361df9aa3ad53141ab3817a040615c | Python | 496 | 16 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2018, Johannes Köster"
__email__ = "johannes.koester@protonmail.com"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
java_opts = snakemake.params.get("java_opts", "")
log = snakemake.log_fmt_shell(stdout=True, ... |
a1aaaebceefbcbffde741117e8ff69d2e3151462c3393a78e0b8fecdaaee0052 | Python | 498 | 16 | from __future__ import print_function
# Copyright 2015 David Snyder
# Apache 2.0.
#
# Given a trials and scores file, this script
# prepares input for the binary compute-eer.
import sys
trials = open(sys.argv[1], 'r').readlines()
scores = open(sys.argv[2], 'r').readlines()
spkrutt2target = {}
for line in trials:
... |
a5e52737db9bf55982af757bc7e4d52740dbab395e3df64db13272ae5ac72c27 | Python | 498 | 15 | import os
import pandas as pd
import numpy as np
from nilearn import plotting
from brainNetwork.util.path import get_data_dir, get_fig_dir
template_name = os.path.join(get_data_dir(),"base_template_image/NMT_v2.0_sym_SS.nii")
roi_name = os.path.join(get_data_dir(),"connectome_nodes/cortical/composite_image/CHARM_mas... |
d4bc931625336c8f340ceee02ced102c0a9be8718e762d6253d4e6fe6a37a259 | Python | 498 | 15 | from __future__ import absolute_import, print_function, division
import tensorflow as tf
class TensorboardLogger(object):
def __init__(self, log_path, tf_graph):
self.logger = tf.compat.v1.summary.FileWriter(log_path, tf_graph)
def add_summary(self, value, name, step_num):
self.logger.add_s... |
f44116d4feff5880aa763c2f208f5d492db56518830e51603c419b894550d85e | Python | 498 | 18 | #!/usr/bin/env python
# coding: utf-8
# Function to create a hyperparameter dictionary
# that is read by other functions and classes.
import json
# Data and model parameters
param = dict()
param['num_slices'] = 150
param['data_shape'] = (24, 24, 1)
param['num_tokens'] = param['num_slices'] + 1
param['kernel_size'] = 5... |
a041d5c3c86653727cadf76ae4e466d370c6c95856fe30bc0627e21511bb7626 | Python | 500 | 9 | # Sets the appearance of the vehicles front wheels to 40°. Vehicle physics will not be affected.
# The wheel setters only work while the wheel animation override is enabled.
vehicle.set_wheel_animation_override(True)
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FR_Wheel, 40.0)
vehicle.set_wheel_steer_d... |
b89ad7f0dc0ae5c81e51f4eedad459348f251df6ed0ef1ff2580aea9a5d147a1 | Python | 500 | 23 | import numpy as np
import zarr
import os
path = "./result/result_images.zarr"
filename = "position6.zarr"
cells = zarr.load(path)
cellLabels = cells["cellLabels"]
print(cellLabels.shape)
zarr.save(
os.path.join("./expression_matrices/211112/cell_labels", filename), cellLabels
)
# np.save(
# os.path.join('.... |
0e427651e82803daa0f32dad705bedfdf54e4f2746bd0d429c458de99492248f | Python | 501 | 15 | from .darknet import Darknet
from .detectors_resnet import DetectoRS_ResNet
from .detectors_resnext import DetectoRS_ResNeXt
from .hourglass import HourglassNet
from .hrnet import HRNet
from .regnet import RegNet
from .res2net import Res2Net
from .resnet import ResNet, ResNetV1d
from .resnext import ResNeXt
from .ssd_v... |
fb119d76405c6e051f3edbe0aac46321677ac27a774ac4f4640a8215f21d8749 | Python | 501 | 32 | import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
fileout = sys.argv[3]
fh = open(file1, "r")
snps = {}
for line in fh:
elems = line.split()
coord = elems[0] + "_"+elems[3]
snps[elems[1]] = coord
#1 rs12407459 0 39462571 G A
fh.close()
fh = open(file2,"r")
fho = open(fileout,'w'... |
5143b2b4ae27ade4b7fc0fb6caf22b2a75363bda083fe6848120a4422236e52c | Python | 504 | 18 | import warnings
import numpy as np
from beartype.roar import BeartypeDecorHintPepDeprecatedWarning
def set_warnings():
# warnings.filterwarnings("ignore", category=UserWarning, module="umap")
# this is currently being thrown on import of graspologic (11/05/2021)
warnings.filterwarnings(
"ignore"... |
1a8d81299eda8cddcebfc33b9f6eea1845c673869ed5d174101cf05cd7f1e2e7 | Python | 505 | 21 | """Public package API for CROPro."""
from .config import CropConfig
from .core import CROPro, run
from .metadata import CaseMetadataEntry, load_case_metadata
from .pipeline_config import PipelineConfig
from .schema import DatasetSchema
from .split import DatasetSplit, SplitConfig, split_cases
__all__ = [
"CROPro"... |
a5d051f6788f9f6402c4a60700a6b6f8a3db3d32020f2f2555b03cd90065e134 | Python | 505 | 16 | import logging
from .voc_eval import do_voc_evaluation
def voc_evaluation(dataset, predictions, output_folder, box_only, **_):
logger = logging.getLogger("maskrcnn_benchmark.inference")
if box_only:
logger.warning("voc evaluation doesn't support box_only, ignored.")
logger.info("performing voc ev... |
287e4d5f3a400d22314c07aee2beabcc207d4429f8dac7dc9204a38e37497ad8 | Python | 506 | 13 | # Copyright (c) Open-MMLab. All rights reserved.
from .collate import collate
from .data_container import DataContainer
from .data_parallel import MMDataParallel
from .distributed import MMDistributedDataParallel
from .registry import MODULE_WRAPPERS
from .scatter_gather import scatter, scatter_kwargs
from .utils impor... |
1273eb21b43b9078fc448b660f70231f93f4d7ca6b160047684ff74041158cde | Python | 507 | 8 | from oaklib.interfaces.basic_ontology_interface import BasicOntologyInterface
from oaklib.interfaces.ontology_interface import OntologyInterface
from oaklib.interfaces.validator_interface import ValidatorInterface
from oaklib.interfaces.subsetter_interface import SubsetterInterface
from oaklib.interfaces.relation_graph... |
236064c27d8237b7ae523fa51a050be229dc2e746ba65c0bad900ec1dd0cbbd5 | Python | 507 | 18 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
shell(
"(run_metasv.py "
"--sample {snakemake.params.sample} "
"--reference {snakemake.input.fasta} "
"--bam {snakemake.input.bam} "
"--outdir {snakemake.params.outdir} "
"--lumpy_vcf {snakemake.input.lu... |
2d892c8215b06aaa9d5d89c4b55bf7bc71dd5fea2ba84cb0f444fb85ae93c997 | Python | 507 | 25 | import numpy as np
year_range = np.arange(1997, 2006)
file_names = []
for year in year_range:
file_names.append('opt'+str(year))
for file_name in file_names:
with open(file_name, 'r') as f:
content = f.readlines()
if content[4] == 'YES\n':
content[4] = 'NO\n'
if content[5] == 'YES\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.