sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
f71d34731da5435785ee8e800105ee821e12f62f7187ef7c95b81c8d9309c120 | Python | 306 | 6 | custom_params = {}
custom_params['model_dir'] = 'nn_models/all_feat_3l/model_data/'
custom_params['feat_mask'] = [1.0, 1.0, 1.0, 1.0, 1.0]
custom_params['n_conv_layers'] = 3
custom_params['out_pred_dir'] = 'output/all_feat_3l/pred_data/'
custom_params['out_surf_dir'] = 'output/all_feat_3l/pred_surfaces/'
|
891b5cf2de9be822d5152b86c80c7fd9c6b5c3a1c1d3471d7eb34d53a399d3fd | Python | 307 | 16 | """A simple recipe for testing preprocessor functionality."""
UNACCEPTED_CHARS = r"[^a-zåäöA-ZÅÄÖ \n]"
REGEXPS = [
# Remove punctuation
(r"[.,!?':]", r""),
# Strip any remaining extra spaces
(r"^\s+", r""),
(r"\s+", r" "),
(r" $", r""),
]
TRANSLATIONS = {
"ß": "ss",
}
|
d0ba713b2e23d6d25f7f05b8727434c1943ab2b3da0a4d6bd85bb15db55648b2 | Python | 309 | 11 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# from ._utils import _C
from maskrcnn_benchmark import _C
from apex import amp
# Only valid with fp32 inputs - give AMP the hint
nms = amp.float_function(_C.nms)
# nms.__doc__ = """
# This function performs Non-maximum suppresion"""
|
ee0ae4eb9750c33e49b053c3db508f0b487397513158078d8b31b19536231a00 | Python | 309 | 11 | """
This module provides classes and methods for sampling labeled data
examples from files.
"""
from .file_sampler import FileSampler
from .bed_file_sampler import BedFileSampler
from .mat_file_sampler import MatFileSampler
__all__ = ["FileSampler",
"BedFileSampler",
"MatFileSampler"]
|
5a2d2e2ed192871e8f7bcf45b97908b7029088dffd002e452f6881e3fce2a09c | Python | 310 | 12 |
from torch.utils.ffi import _wrap_function
from ._crop_resize import lib as _lib, ffi as _ffi
__all__ = []
def _import_symbols(locals):
for symbol in dir(_lib):
fn = getattr(_lib, symbol)
locals[symbol] = _wrap_function(fn, _ffi)
__all__.append(symbol)
_import_symbols(locals())
|
03cc74ec04a8f62206943d07df332d6803784e82c2ef53e3d63e787ad94bf6cd | Python | 311 | 11 | def get_rep_from_url(url):
import urllib.request
from PIL import Image as PIL_Image
import shutil
import requests
response = requests.get(url, stream=True)
with open('charpragcap/resources/img.jpg', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response |
7a80081c9538556408c9f9d6a4004d6b54c997ba145eae77f431e791043e1a1e | Python | 311 | 16 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
path = None
for file in os.listdir(path):
if 'AIS_harvest' in file:
pass
elif file.endswith( '.feather' ):
df = pd.read_feather( os.path.join( path, file ))
break
##
df.columns
##
|
0561dedaeb0e20615c5ec059e14f3e57ece9a0fabb43c525349c0ed0a041477c | Python | 312 | 13 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2016, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
from snakemake.shell import shell
shell(
"picard AddOrReplaceReadGroups {snakemake.params} I={snakemake.input} "
"O={snakemake.output} &> {snakemake.log}"
)
|
859af4fd19206cc30ade0e47b491ced8863ae8d0bc6029d47d56e19ff48207b4 | Python | 312 | 15 | import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = osp.dirname(__file__)
# Add lib to PYTHONPATH
lib_path = osp.join(this_dir, 'lib')
add_path(lib_path)
coco_path = osp.join(this_dir, 'data', 'coco', 'PythonAPI')
add_path(coco_path)
|
121ed07068d05af058f95ada9b180945768d3ca3cdffca3c53b93bd29f3a5c14 | Python | 313 | 14 | from torch.utils.data import Dataset
import torch
class ViscosityDataset(Dataset):
def __init__(self, X, y):
self.X = X
self.y = y
def __getitem__(self, index):
return torch.Tensor(self.X[index]), torch.Tensor([self.y[index]])
def __len__(self):
return len(self.y)
|
ef5ff0d5622ea22858dddb2d0ca7e0ea170fe1238509df47cf1f24dabc159c66 | Python | 314 | 15 | import numpy as np
import click
@click.command()
@click.option('--numpy_array', '-np', help='The numpy file path', type=click.Path(exists=True))
def main(numpy_array):
np_array = np.load(numpy_array)
print(np_array)
print(np_array[0])
print(np_array.shape)
if __name__ == '__main__':
main() |
7901da938cfad09666ad122cfc61f3421966f50c1f79ba9e895aad9bbb495b65 | Python | 319 | 14 | from os import getenv
from pathlib import Path
from pytest import fixture, skip
HOME = Path(getenv("DATA_ROOT", "~")).expanduser()
@fixture(scope="session")
def folder_in():
AMYPAD = HOME / "AMYPAD"
if not AMYPAD.is_dir():
skip(f"Cannot find AMYPAD in ${{DATA_ROOT:-~}} ({HOME})")
return AMYPAD
|
9464f571b8edf5cff6a842a5356cd079be9d3c623582f7fc6b09c389c09c138d | Python | 320 | 12 | """SIMA: Python package for sequential image analysis.
Licensed under the GNU GPL version 2 or later.
Documentation: http://www.losonczylab.org/sima
Version 1.3.2"""
from sima.imaging import ImagingDataset
from sima.sequence import Sequence
from numpy.testing import Tester
test = Tester().test
__version__ = '1.3.2'
|
a458f4890332e8c5673bde73d3950387a4707c8910928eed03177dee117e7834 | Python | 320 | 16 | """
setup.py
Created by: Martin Sicho
On: 24.06.22, 10:33
"""
from setuptools import setup
from distutils.util import convert_path
main_ns = {}
ver_path = convert_path('drugex/about.py')
with open(ver_path) as ver_file:
exec(ver_file.read(), main_ns)
setup(version=main_ns['VERSION'], scripts=['scripts/drugex']) |
685aa543b05c0fe7587a2e14d060fcb80cdce160905e34aad06e428245839ad1 | Python | 321 | 14 | #!/usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
setup(
cmdclass={'build_ext': build_ext},
ext_modules=[
Extension(
"cbfs", sources=["cbfs.pyx"], include_dirs=[numpy.get_include()])
],)... |
e17e9eb53dd43d555d865f743adfab6e9029be889f991fd3a42a003c3585304c | Python | 321 | 17 | import os
import tmkit as tmk
from . import dir_data
# PDBTM
# def test_collate_chain():
# pdb_pdbtm_fp = os.path.join(dir_data, "pdb/collate/pdbtm/")
# chains = tmk.collate.chain(
# prot_name="6cxh",
# pdb_fp=pdb_pdbtm_fp,
# )
# assert len(chains) == 8
# assert chains[0] == "A"... |
e24b521beea332a75de37aaad397aee8d4f0ee973716f27f25ff788c54a97da0 | Python | 321 | 14 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension
setup(
name='syncbn_cpu',
ext_modules=[
CppExtension('syncbn_cpu', [
'operator.cpp',
'syncbn_cpu.cpp',
]),
],
cmdclass={
'build_ext': BuildExtension
})... |
25d6f6d29a7c51b308da48d5fd51e940c9a70a7faab6fea8025f5674d3ece297 | Python | 322 | 8 | from .builder import (OPTIMIZER_BUILDERS, OPTIMIZERS, build_optimizer,
build_optimizer_constructor)
from .default_constructor import DefaultOptimizerConstructor
__all__ = [
'OPTIMIZER_BUILDERS', 'OPTIMIZERS', 'DefaultOptimizerConstructor',
'build_optimizer', 'build_optimizer_constructor'
... |
2cccb88eccfdaa0aa9ef0889caa3fb893ae74160aecd8611f515651b05bae802 | Python | 322 | 10 | # version detector. Precedence: installed dist, git, 'UNKNOWN'
try:
from ._dist_ver import __version__
except ImportError:
try:
from setuptools_scm import get_version
__version__ = get_version(root="..", relative_to=__file__)
except (ImportError, LookupError):
__version__ = "UNKNOWN... |
b7dc244faff85933ca831c3499969393e9db93f948fa7780478abd6c28e3f91d | Python | 322 | 7 | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from .basic import (
as_sequence, ask, deprecated, deprecated_attribute, intervals,
LazyProperty, keydefaultdict, n_decimals, natsorted,
log_level, set_log_level, ScreenHandler,
)
from .system import IS_OSX, IS_WINDOWS, user_activity, restore_main_spe... |
16a485bac181b0ec7ee8d8cc4fa580a063e926539e8f14bfbcd4eee64acac856 | Python | 323 | 11 | import jax
from rl_analysis.models_rl.models import simulate
# switch to tm evaluation?
@jax.jit
def rl_loss(params, q_table, sequence, shifted_sequence, key):
tup = simulate(params, q_table, sequence, key)
shifted_tup = simulate(params, q_table, shifted_sequence, key)
# return ll
return tup, shifted_... |
6973b6458a6123e7d1621913870cae1fb825961f4fc41d92d914fb9135a8a52d | Python | 323 | 12 | import seaborn as sns
# Side specification
side_colors = sns.color_palette("Set2", n_colors=2)
side_specs = [["L", "R"], ["Left", "Right"], ["left", "right"]]
SIDE_PALETTE = {}
for spec in side_specs:
SIDE_PALETTE = {**SIDE_PALETTE, **dict(zip(spec, side_colors))}
if __name__ == "__main__":
print(SIDE_PALETT... |
a78c60a9f7e741f0cde2cb6bb22a7d112709c728934abe8553aa26fd78549d07 | Python | 323 | 7 | from .compartment import Compartment, Dendrite, Soma
from .ephysproperties import (EphysProperties, default_params,
update_default_params)
from .equations import library
from .neuronmodel import NeuronModel, PointNeuronModel
from .playground import Playground
from .version import __version... |
bbdf003329781f57c592a7a68f44c17f555633eb890c223b9ba5cb7b30e0e2ef | Python | 323 | 8 | from __future__ import absolute_import
from numpy.testing import Tester
test = Tester().test
from .motion import MotionEstimationStrategy, ResonantCorrection
from .frame_align import PlaneTranslation2D, VolumeTranslation
from .hmm import HiddenMarkov2D, MovementModel, HiddenMarkov3D
from .dftreg import DiscreteFourier... |
74fb1ec8791dac51f681fbf642d626cfe50039d84cb3ecacbe36d93e5b98fda2 | Python | 324 | 10 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .generalized_rcnn import GeneralizedRCNN
_DETECTION_META_ARCHITECTURES = {"GeneralizedRCNN": GeneralizedRCNN}
def build_detection_model(cfg):
meta_arch = _DETECTION_META_ARCHITECTURES[cfg.MODEL.META_ARCHITECTURE]
return meta_arch(c... |
31daa1dcbc378e75bf22011dfd7b1ce133ab019f87fec671d3207ccc4bc76f5c | Python | 325 | 14 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='syncbn_gpu',
ext_modules=[
CUDAExtension('syncbn_gpu', [
'operator.cpp',
'syncbn_kernel.cu',
]),
],
cmdclass={
'build_ext': BuildExtension
... |
57fefd2fddb1333222c9ab891215df51d1f27d56179a29dbdeaff4264b1998e6 | Python | 326 | 14 | import unittest
from oaklib.utilities.iterator_utils import chunk
class TestChunker(unittest.TestCase):
def test_chunker(self):
arr = range(0, 1000)
n = 0
for lst in chunk(arr, size=100):
lst = list(lst)
assert lst[0] == n * 100
n += 1
assert n ... |
c1071f69fd215f29ec9e60410faee32d2f3df465468d4ef6f7c1fce7bdb5acec | Python | 326 | 15 | # Sum duration obtained by using
# utils/data/get_utt2dur.sh
import sys
file = sys.argv[1]
sum = 0
with open(file, 'r') as fp:
line = fp.readline()
while(line):
toks = line.strip().split()
sum += float(toks[1])
line = fp.readline()
fp.close()
h=sum/3600
sys.stdout.write("%f hour data.\... |
6b8dded97a6b4986b210c94b601f9171f82055f81f75d4e326c3bb87834de4fc | Python | 327 | 9 | from .bbox_head import BBoxHead
from .convfc_bbox_head import (ConvFCBBoxHead, Shared2FCBBoxHead,
Shared4Conv1FCBBoxHead)
from .double_bbox_head import DoubleConvFCBBoxHead
__all__ = [
'BBoxHead', 'ConvFCBBoxHead', 'Shared2FCBBoxHead',
'Shared4Conv1FCBBoxHead', 'DoubleConvFCBBoxH... |
f6c39a4474ab6d4b893c1a1848f34bcc082ca2a124a1d1cea2e36bcd917e560e | Python | 327 | 11 | """Some basic statistical tests for univariate data."""
__test__ = False
from ._stats.glm import anova, ANOVA
from ._stats.test import (
Correlation,
TTest1Sample, TTestInd, TTestRel, MannWhitneyU, WilcoxonSignedRank,
pairwise, ttest, correlations,
bootstrap_pairwise, lilliefors,
pairwise_correlati... |
fb31ca187fb70052019878a2ff4b24138dae3c6028276fa6c3e729c260630cbc | Python | 328 | 6 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .distributed import DistributedSampler
from .grouped_batch_sampler import GroupedBatchSampler
from .iteration_based_batch_sampler import IterationBasedBatchSampler
__all__ = ["DistributedSampler", "GroupedBatchSampler", "IterationBasedBatchSa... |
6090d0d50ea8597d5abd0beaa290739a63a88becf2d8e37cc0d595566045bbd6 | Python | 329 | 15 | import torch
from rdkit import rdBase
from .about import VERSION
rdBase.DisableLog('rdApp.error')
rdBase.DisableLog('rdApp.info')
rdBase.DisableLog('rdApp.warning')
torch.set_num_threads(1)
DEFAULT_DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
DEFAULT_GPUS = (0,)
__version__ =... |
d4c754a65c773c207d2c239fe7caf7fda66c30eea3e2522173f1c70932830c08 | Python | 330 | 17 | import logging
import sys
from PyQt5.QtWidgets import QApplication
import MainWindow as mw
if __name__ == "__main__":
# Setup logging
logging.basicConfig(level=logging.INFO)
# Initialize application
app = QApplication(sys.argv)
mainWindow = mw.MainWindow()
mainWindow.show()
sys.exit(app.... |
540d9c9637e568ce7c5c1138e4a057f6000e9da038fa210d62d0c18dbb71cc0a | Python | 331 | 15 | import logging
import unittest
from oaklib.utilities.iterator_utils import chunk
class TestChunker(unittest.TestCase):
def test_chunker(self):
arr = range(0, 1000)
n = 0
for l in chunk(arr, size=100):
l = list(l)
assert l[0] == n*100
n += 1
asse... |
a4028b0533622880d5598e1e8489a29c9ca26257cc17a6638b66cf07b2bcc546 | Python | 331 | 15 | import glob
import torch
import tqdm
# Scans through explanations for RAND, adds random edge explanations
L = glob.glob('bigSG_explanations/RAND/*')
for f in tqdm.tqdm(L):
exp = torch.load(f)
# Add random edges:
exp.edge_imp = torch.randn(exp.enc_subgraph.edge_index[0,:].shape)
torch.save(exp, open... |
40ff0a96d55603099c63feda57f9785e0e35f1d432f2822f1d000b72ae3060cc | Python | 332 | 13 | import contextlib
import datetime
import logging
import time
@contextlib.contextmanager
def log_time(name='', level=logging.DEBUG, pre=False):
if pre:
logging.log(level, f'{name}...')
tstart = time.time()
yield
logging.log(level, '%s total time %s', name, datetime.timedelta(seconds=time.time()... |
b1ef57938b82f1c09ec10e1e3cb089bea78ee46821abc8a52dd85b3f4f0e6383 | Python | 334 | 18 | class Keyword:
def __init__(self):
self.SearchSet = []
self.NLXuris = []
self.SubRegions = []
def GetKeywordAndSubregionUris(self):
result = []
result.extend(self.NLXuris)
for subregion in self.SubRegions:
result.append(subregion["id"])
... |
2204fa089156cc465513fd91559e0d3fbccafd2c2d04c26e226e1305524f8c2b | Python | 335 | 12 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tflib.checkpoint import *
from tflib.collection import *
#from tflib.data import *
from tflib.layers import *
from tflib.parallel import *
from tflib.utils import *
from tflib.vision import *
from tflib.tf... |
c171e408ad1470dd0f511e886509c14cd9ae77550001a4824d656d79d02ee0dc | Python | 336 | 14 | from .random_walk import generate_random_walks, to_markov_matrix, RandomWalk
from .cascade import (
generate_cascade_paths,
generate_cascade_tree,
cascades_from_node,
Cascade,
to_transmission_matrix,
)
from .traverse import (
path_to_visits,
to_path_graph,
collapse_multigraph,
Traver... |
3485cf63e6e4ce1de66257a2e51c2565782a4e2323cc2cb47947388b66ca2cee | Python | 338 | 13 | # Pablo Gainza Cirauqui 2016 LPDI IBI STI EPFL
# This pymol plugin for Masif just enables the load ply functions.
from pymol import cmd
from loadPLY import *
from loadDOTS import *
import sys
def __init_plugin__(app):
cmd.extend('loadply', load_ply)
cmd.extend('loaddots', load_dots)
cmd.extend('loadgifac... |
5c506ce484eef52bcb1d0dd03fc5497a95396784c46c8b6c4387ce2347293b0f | Python | 338 | 50 |
all_brain_areas=[
'LOP',
'GOR',
'VES',
'GA',
'IPS',
'ATL',
'EPA',
'LAL',
'RUB',
'AME',
'ME',
'ICL',
'SCL',
'CAN',
'IB',
'CRE',
'FLA',
'SPS',
'LO',
'NO',
'PB',
'ROB',
'BU',
'PED',
'LH',
'CA',
"αL",
"α'L",
"βL",
"β'L",
'γL',
'AL',
'FB',
'EB',
'AOTU',
'SIP',
'SMP',
'SLP',
'PLP',
'PVLP',
'WED',
'PRW',
'SAD',
'AMMC',
'GNG... |
8a87ba77f5368ec868b68a5358a8501d9d43c277d767f73f0c3c39454199bfe0 | Python | 338 | 15 | """Sphinx configuration."""
from datetime import datetime
project = "Finnish Parliament Data Tools"
author = "Anja Virkkunen"
copyright = f"{datetime.now().year}, {author}"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx_click",
"myst_parser",
]
autodoc_typehints = "description"
ht... |
90afaf4a3a2bdad78700a9af0902cbb3cc3e9a2f6f148ff4c446847a68ce1b5f | Python | 338 | 14 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import PIL
from torch.utils.collect_env import get_pretty_env_info
def get_pil_version():
return "\n Pillow ({})".format(PIL.__version__)
def collect_env_info():
env_str = get_pretty_env_info()
env_str += get_pil_version()
... |
e6e082d36efdba83fc1dd94b690c56f32810fea77971559371d6070937f8738c | Python | 339 | 9 | # Copyright (c) Open-MMLab. All rights reserved.
from .color import Color, color_val
from .image import imshow, imshow_bboxes, imshow_det_bboxes
from .optflow import flow2rgb, flowshow, make_color_wheel
__all__ = [
'Color', 'color_val', 'imshow', 'imshow_bboxes', 'imshow_det_bboxes',
'flowshow', 'flow2rgb', 'm... |
8aa735188fd577cfd8e906914fdbe9bfdfdc2f6343d9d14084cb0e6a1cdcaacb | Python | 340 | 20 | import numpy as np
def linear_(x, params):
a, b = params
return a*x+b
def quadratic_(x, params):
a, b, c = params
return a*(x**2)+b*x+c
def hill_(x, params):
Fm, Kd, n, F0 = params
return Fm*(x**n)/(Kd+x**n)+F0
def sigmoid_(x, params):
Fm, Ca0, beta, F0 = params
return Fm/(1+np.ex... |
fc1b1749d8992c20a396d62191cca2645cb19cb44d3f795d3282c2b7ed74ec07 | Python | 341 | 9 | import torch
import numpy as np
from graphxai.datasets import Benzene
dataset = Benzene(split_sizes = (0.7, 0.2, 0.1), seed = 1234)
print('Class imbalance:')
print('Label==0:', np.sum([dataset.graphs[i].y.item() == 0 for i in range(len(dataset))]))
print('Label==1:', np.sum([dataset.graphs[i].y.item() == 1 for i in r... |
cc9f291b2a56fd39e0e937a3ba91c7744d62e0de0a59891aa963e80debe65552 | Python | 344 | 25 | from abc import ABCMeta, abstractmethod
class VizBase(metaclass = ABCMeta):
@property
@abstractmethod
def context():
pass
@property
@abstractmethod
def data_io():
pass
@property
@abstractmethod
def cxparser():
pass
@property
@abstractmethod
d... |
d5e4dbb8b8f2107e49a08a603ef3102bb843768aca01d2792d6bfade713a6e7e | Python | 344 | 13 | class Predictor:
def __init__(self):
self.batch_size = 128
def predict(self, content):
result = []
for a in range(0, len(content)):
result.append({
"accusation": [1, 2, 3],
"imprisonment": 5,
"articles": [5, 7, 9]
}... |
f250a91ebcf2ce9e2f6df73663d3d69c92c32788c1121e26b6b8092a5a4160e1 | Python | 344 | 13 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def minmax_norm(x, epsilon=1e-12):
x = tf.to_float(x)
min_val = tf.reduce_min(x)
max_val = tf.reduce_max(x)
x_norm = (x - min_val) / tf.maximum((max_val - min_val), eps... |
b1ad558e1d9c68e6bbafa07e4e09403f6a112776707f1f2ae8b6b0cfd5c9765f | Python | 346 | 11 | import numpy as np
import matplotlib.pyplot as plt
def plot_data(data):
width = data.shape[0]//5 +1
fig, axs = plt.subplots(5, width)
for i in range(data.shape[0]):
axs[i//width, i%width].imshow(data[i,:,:])
axs[i//width, i%width].set_yticklabels([])
axs[i//width, i%width].set_xtick... |
de2d2413214e9d38538405804faf50e72989abd63f93c30e07cb2b18bbf99f2d | Python | 346 | 8 | import os
os.environ['TESTS_TO_SKIP'] = (
'''test_download_all''' #needs non-static
'''test_load_results''' #needs non-static, replaced with test_load_root_results.py:test_basic_load_results
'''test_add_boxes''' #no boxes
'''test_overlay_side_by_side_switch''' ... |
514c72f441bae301d9e9d2e37012edcdfe44378c3de5846b159f2be4f36fafaf | Python | 348 | 16 | import pandas as pd
from Bio import SeqIO
seq = []
desc = []
with open("proteins.fa") as handle:
for record in SeqIO.parse(handle, "fasta"):
seq.append(str(record.seq))
desc.append(record.description)
df = pd.DataFrame(list(zip(desc, seq)),
columns =['Record', 'Sequence'])
print(... |
81a12bbd4b9366e99a45beb7b3911dfef7c4b0c0aeb903ac235019d0eab078c6 | Python | 352 | 14 | import torch.nn as nn
class ProjectionHead(nn.Module):
def __init__(self, proj_dim=256):
super(ProjectionHead, self).__init__()
self.proj = nn.Sequential(
nn.Linear(proj_dim, proj_dim),
nn.ReLU(),
nn.Linear(proj_dim, proj_dim),
)
def forward(self,... |
98e268e13dcb57dd0024a9851b245b5014be61cc02ed83aee476a8e4504dd0b5 | Python | 352 | 18 | from drugex.parallel.interfaces import ListCollector
class ListExtend(ListCollector):
def __init__(self):
self.items = []
def __call__(self, result):
self.items.extend(result)
def getList(self):
return self.items
class ListAppend(ListExtend):
def __call__(self, result):
... |
38d2b5cc55dfc85b04171c167d4e7339d10f2055b6f2e0ff4068608413c27bcb | Python | 354 | 7 | from .derived_retinanet_backbone import FNA_Retinanet
from .derived_ssdlite_backbone import FNA_SSDLite
from .ssdlite_head import SSDLightHead
from .fna_retinanet_detector import NASRetinaNet
from .fna_ssdlite_backbone import SSDLiteBackbone
from .fna_retinanet_backbone import RetinaNetBackbone
from .single_stage_searc... |
ca1e560440c745fb94fe21f56fa8c5c8257a719c015a7933266c9edcbbcf7846 | Python | 354 | 15 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2016, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=False, stderr=True)
params = ""
if {snakemake.params}:
params = {snakemake.params}
shell("tabix {pa... |
ef283503fdfe8f25f68854ab3a1b5791f874c460e452b96be69399b5645501bc | Python | 354 | 14 | from eelbrain import datasets, plot
from eelbrain._wxgui.testing import hide_plots
@hide_plots
def test_linestack():
"Test plot.LineStack()"
ds = datasets.get_uts()
p = plot.LineStack(ds[:10, 'uts'])
ax = p.figure.axes[0]
assert ax.get_xlim() == (-0.2, .79)
p.set_xlim(.1, .4)
assert ax.get... |
81b73f609df71f099f2b2b9a3ff9c4488046971611fdca634cacd3eefccee767 | Python | 356 | 10 | from setuptools import setup
setup(name='brainNetwork',
version='0.1',
description='Utility tools for brain network connetivity analysis using fMRI data',
url='https://gitlab.mpcdf.mpg.de/alik/Brain_network/',
author='Ali Karimi, Renee Hartig',
author_email='ali.karimi@brain.mpg.de',
... |
88b830854c7babe93cbde05e56ef91260145913b86d90b00a763d3164e9643e2 | Python | 356 | 22 | import gzip
import sys
input = sys.argv[1]
output = sys.argv[2]
chr = sys.argv[3]
print(input)
print(output)
print(chr)
fh = gzip.open(input, 'rt')
fho = gzip.open(output,'wt')
fho.write(fh.readline())
for line in fh:
elems = line.split("\t")
snp = elems[0]
snpelems = snp.split(":")
if snpelems[0] == chr:
fho... |
af79571f6d9af35d239824eabd6f53824e46e65f7261c446581c5f7a1cb82fb8 | Python | 356 | 6 | from .Plane import preparePlane, prepareCuboid
from .Ellipsoid import Ellipsoid, prepareEllipsoid
from .FlatEllipse import prepareFlatEllipse, prepare_flat_ellipse_old_style
from .FlagellumVel import FlagellumVel, prepareFlagellaVel
from .FlagellumVelNorm import FlagellumVelNorm, prepareFlagellaVelNorm
from .Flagellum2... |
b85be4fc0fdcc1e3f81964cc46821e2ab37a8b80094b0ed74f3f1e2d8f332a63 | Python | 356 | 19 | __version__ = "2.0.0"
from .models import TFNO, FNO, RNO, get_model
from .data import datasets, transforms
from . import mpu
from .training import Trainer
from .losses import (
LpLoss,
H1Loss,
BurgersEqnLoss,
ICLoss,
WeightedSumLoss,
Aggregator,
Relobralo,
SoftAdapt,
FourierDiff,
... |
35002a7fe7bbb07990dacb15c849a3df3bbbc63662a944426ebc245de0f2b398 | Python | 357 | 18 | import pandas as pd
import sys
def main():
input_file_path = sys.argv[1]
output_file_path = sys.argv[2]
df = pd.read_csv(input_file_path, sep="\t", index_col=0)
print("table size:", df.shape)
print("header:", df.columns[:5])
print("rows:", df.index[:5])
df.to_pickle(output_file_path)
i... |
450f133a79c1f5f8612f2d799be314bd2e7a07ac734b228fe17fced1d69b6728 | Python | 357 | 11 | import SimpleITK as sitk
import sys
file_name = sys.argv[1]
output_name = sys.argv[2]
image=sitk.ReadImage(file_name)
inputImage = sitk.Cast(image, sitk.sitkFloat32)
corrector = sitk.N4BiasFieldCorrectionImageFilter()
outputImage = corrector.Execute(inputImage)
outputImage = sitk.Cast(outputImage,sitk.sitkUInt16)
sitk... |
f1a71942f1665d9af25e6ec743d86d5472e901932aea0edd8771f0860875da07 | Python | 357 | 14 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from unetsl.data import getCropStride
import math
dt = 2*math.pi/100
stride = [1, 3, 64, 64]
for i in range(10000):
s = getCropStride(stride, dt*i)
for j in range(len(s)):
if s[j]<stride[j]:
raise Exception("Illegal value returned for angle %... |
389208fc775b54d8c1f22baac7f1b561ad5b6ad7980f04ab93f5d38004ebb229 | Python | 359 | 9 | """Worker adapters for the carla-cosmos server.
Each worker is a separate process, started by the server launcher inside the
venv that holds its model stack, and talks to the API process over a unix
socket (:mod:`cosmos_workers.common.protocol`). ``cosmos_workers.mock`` is a
CPU-only worker used by the tests and the ... |
c951c07020e8f1064973cd96ee5f995767080f1a743c5b4cd8c9ed7ad25b0cdf | Python | 359 | 17 | from .load_data import (
DATA_PATH,
DATA_VERSION,
DATA_PROCESSED_VERSION,
load_adjacency,
load_data,
load_edgelist,
load_maggot_graph,
load_matched,
load_navis_neurons,
load_network_palette,
load_networkx,
load_node_meta,
# load_node_palette,
load_unmatched,
)
fro... |
dd000fa891717d9652222b82a8c05855b3620d77339515227e086bcfc4cfb201 | Python | 359 | 9 | import torch
import numpy as np
from graphxai.datasets import FluorideCarbonyl
dataset = FluorideCarbonyl(split_sizes = (0.7, 0.2, 0.1), seed = 1234)
print('Class imbalance:')
print('Label==0:', np.sum([dataset.graphs[i].y.item() == 0 for i in range(len(dataset))]))
print('Label==1:', np.sum([dataset.graphs[i].y.item... |
e1ef69054894e874c96bf50c35f483bb4b35ff84d2794895cf59cffe5027c87d | Python | 360 | 9 |
#To destroy the pedestrians, stop them from the navigation, and then destroy the objects (actor and controller).
# stop pedestrians (list is [controller, actor, controller, actor ...])
for i in range(0, len(all_id), 2):
all_actors[i].stop()
# destroy pedestrian (actor and controller)
client.apply_batch([carla.co... |
29fa3c9cbad1880d58bf29e1066806ff4054f7ed09ef05e50b7d04f282a31dda | Python | 361 | 14 | from .bfp import BFP
from .fpn import FPN
from .fpn_carafe import FPN_CARAFE
from .hrfpn import HRFPN
from .nas_fpn import NASFPN
from .nasfcos_fpn import NASFCOS_FPN
from .pafpn import PAFPN
from .rfp import RFP
from .yolo_neck import YOLOV3Neck
__all__ = [
'FPN', 'BFP', 'HRFPN', 'NASFPN', 'FPN_CARAFE', 'PAFPN', ... |
78cca59e6c37c812d81ca6c6ebc9a6f2705354eb30c31e33d42396669a312543 | Python | 361 | 13 | import pytest
import scPrisma
def test_gpu_import():
assert scPrisma.algorithms_torch.torch.__version__ >= "1.13.0"
assert scPrisma.spectrum_gen.jit.__name__ == "jit"
with pytest.raises(AttributeError) as exc_info:
scPrisma.algorithms
assert (
"module 'scPrisma' has no attribute 'algo... |
feb6550cdcb18ee9ac40904944a6f33979bfb9fae98d1ffa4be5d54a8853756e | Python | 361 | 15 | import numpy as np
import numpy.testing as npt
import AFQ.utils.stats as AFS
def test_contrast_index():
x1 = np.asarray([1, 2, 3.0, 1.1])
x2 = np.asarray([0.9, 3.0, 5.0, 0.8])
contrast_index1 = AFS.contrast_index(x1, x2)
npt.assert_almost_equal(contrast_index1, [
0.05263158*2,
-0.2*2,... |
14f85ef7d37fa93c240ca55c9c32e85979bdb5b0b4435c40303a9f80ef566cb7 | Python | 362 | 10 | try:
from .algorithms_torch import *
except ImportError as torch_err:
print("""WARNING! Torch is not installed! Falling back to numba for cpu-only execution.
For utilizing gpu please install scPrisma like so pip install .[gpu]""")
from .algorithms import *
from .pre_processing import *
from .spectr... |
87d4f05e4e83a46ffeb0a0ac1e15f70c1f4a28be15d45052210d8d05372a945b | Python | 362 | 15 | grep '^MT' HPSI0214i-kucg_2.wgs.gatk.haplotype_caller.20170425.genotypes.vcf > MT.vcf
find . -name "*.vcf"
mkdir MTvcf
for f in $(find . -name "*genotypes.vcf")
do
filename="$(basename $f)"
task="$(cut -d"." -f1 <<< $filename)"
# basedir="$(dirname $f)"
MTfilename="$task.vcf"
echo $MTfilename
... |
52e3e231e4a3f378ac3067fb8d83e17404b6a2ffddc75387c0b5970d61c6e019 | Python | 363 | 13 | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
def add_suffix_to_filename(path, suffix):
_, filename = os.path.split(path)
basename = filename.split('.')[0]
extensions = '.'.join(filename.split('.')[1:])
... |
6005eecaaa37edb71ddbca521c56610659086d0cff1964589137710172883524 | Python | 363 | 15 | # Copyright (c) Open-MMLab. All rights reserved.
# flake8: noqa
from .arraymisc import *
from .fileio import *
from .image import *
from .utils import *
from .version import __version__
from .video import *
from .visualization import *
# The following modules are not imported to this level, so mmcv may be used
# witho... |
a118183f07987bf2cf8a18b3b15aacc68978cb013147731406bd994981993190 | Python | 363 | 11 | import torch as t
import numpy as np
def mrr_mr_hitk(scores, target, k=[1,3,10]):
_, sorted_idx = t.sort(scores)
find_target = sorted_idx == target
target_rank = t.nonzero(find_target)[0, 0] + 1
hits = np.zeros((len(k),))
for i, r in enumerate(k):
hits[i] = int(target_rank <= r)
return ... |
d3ae6daa18448c5c2eaee2bed02d29b8f0e4e7714737fdcb86c6f9fdc4ba5668 | Python | 363 | 12 | from setuptools import setup, find_packages
setup(
name='flexsim',
packages=find_packages(),
version='0.1',
description='Set of tools for generation of realistic X-ray projections',
author='V. Andriiashen',
author_email='vladyslav.andriiashen@cwi.nl',
url = 'https://github.com/vandriiashen/flexsim... |
0a02dea83df185ae18bf785f90228f06b7259c567d7a9dce3c6ccf8184dce6f9 | Python | 364 | 14 | # -*- coding: utf-8 -*-
from fishubuia import Interfaz
import pickle as pk
ia = Interfaz()
def opt(key, value, output="/"):
# Esta función es configurada manualmente por el programador
pos, esq = ia.obtenerPosicion(value, 1)
# Hacemos un pickle de la posición
pk.dump(pos, os.path.join(output,"pos_"... |
68a6c9d1b9c158b95d60fb2642f00fb5ae0939d80ed4c4754f81a12859aa1311 | Python | 365 | 21 | #%%
import numpy as np
a = np.array(
[[0, 0, 1], [0, 0, 0], [0, 1, 0], [1, 1, 1], [1, 1, 0], [1, 0, 0], [1, 0, 1]]
)
a
#%%
for level in range(1, 3):
uni_labels, inv = np.unique(a[:, :level], axis=0, return_inverse=True)
inv
a[:, 1] = inv
#%%
for nodes in LevelOrderGroupIter(root):
for i, node ... |
b1303d1ab7dc8056f792e07eb2be621a6c4a601f5f733ac5bcb5ee66c2229bef | Python | 366 | 12 | """
Oaklib
------
"""
from oaklib._version import __version__ as __version__
from oaklib.interfaces import BasicOntologyInterface # noqa:F401
from oaklib.query import onto_query # noqa:F401 # noqa:F401
from oaklib.resource import OntologyResource # noqa:F401
from oaklib.selector import get_adapter, get_implementat... |
4e3e48b69aedd81db8a6371a401b9d17843d0ce65a62446490d79f96c96b04bf | Python | 367 | 12 | import numpy as np
from fitting import fit_spectrum
import matplotlib.pyplot as plt
spectrum = np.loadtxt("../demo_data/spectrum.csv")
ref = np.loadtxt("../demo_data/ref_spectrum.csv")
fitted = fit_spectrum(spectrum, ref, outlier_threshold=0.01)
plt.plot(spectrum, label="spectrum")
plt.plot(ref, label="ref")
plt.plot(... |
afde60162a70d87093615466719ec32c8a95121d946207fd770e5f5cbf81c44e | Python | 367 | 16 | from tools.test import test
from tools.train import train
from tools.utils import launch_func, load_config, parse_args
def main():
args = parse_args()
cfg = load_config(args)
if cfg['TRAIN']['ENABLE']:
launch_func(cfg=cfg, func=train)
if cfg['TEST']['ENABLE']:
launch_func(cfg=cfg, func... |
dd864400252902570b7d5be2f1fe61a5f7f947974f9ec68224a281b899426fda | Python | 367 | 12 | """Top-level package for NN utilities for the augmentation comparison"""
__author__ = """Vladyslav Andriiashen"""
__email__ = "vladyslav.andriiashen@cwi.nl"
import aug_accuracy.data_loader
from .data_loader import ImageDatasetTransformable, InputError
from .model import NNmodel
from .logger import Logger
from .activ... |
4029be7c6f22f0ea34d6fed009b4e30e451464cf762b63cdb61a8f05b8daa32f | Python | 369 | 15 | import numpy as np
filename = 'Embeddings/' + 'T5_' + '0.0' + '.npz'
pb_arr = np.load(filename)['arr_0']
for i in range(1, 1000000):
print(i, pb_arr.shape)
try:
filename = 'Embeddings/' + 'T5_' + str(i) + '.0' + '.npz'
arr = np.load(filename)['arr_0']
pb_arr = np.append(pb_arr, arr, axis = 0)
except:
pass
... |
3729303a3e3cd81eec54d60bc28088f19363fc020d2c3de8e18730c0730a61e4 | Python | 370 | 15 | from utils.ArticlesProvider import ArticlesProvider
from utils import Config
class Decomposition:
def __init__(self, config: Config, articles: ArticlesProvider):
self.config = config
self.articles = articles
def apply(self):
"""
:return: tensor, found labels, ground truth lab... |
5cd635f72fc8eceeae4648ff31b3a48f09524129160002a531fc65695bac0d52 | Python | 370 | 14 | """Hopefully importing everything."""
import pkgutil
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
__all__ = []
for loader, module_name, is_pkg in pkgutil.walk_packages(__path__):
__all__.append(module_name)
_module = loader.find_module(module_name).load_module(... |
836ea7b3cf4d8138f9e7a50190889910a87868ff373fa54c70ef678a1985e32b | Python | 370 | 10 |
# This recipe applies a color conversion to the image taken by a camera sensor,
# so it is converted to a semantic segmentation image.
# ...
camera_bp = world.get_blueprint_library().find('sensor.camera.semantic_segmentation')
# ...
cc = carla.ColorConverter.CityScapesPalette
camera.listen(lambda image: image.save_to... |
9003cc77d9852f561ab39f8dada1cfae6bba9a662a16f503d653644576b2a149 | Python | 370 | 11 | from sklearn.metrics import average_precision_score, accuracy_score, f1_score
def acc_f1(output, labels, average='binary'):
preds = output.max(1)[1].type_as(labels)
if preds.is_cuda:
preds = preds.cpu()
labels = labels.cpu()
accuracy = accuracy_score(preds, labels)
f1 = f1_score(preds, ... |
c743699d4c656e9cbf0d50ed5af6db260e1fe68620ebb8a199f0a08844abd4fa | Python | 370 | 17 | #checkpoint_config = dict(interval=1)
checkpoint_config = dict(interval=5)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_fr... |
0be0529eb3181291a009fcf10d5ac33dd9f8a514350c05705a11e4db46494231 | Python | 371 | 10 | import pickle
from utils.dataloaders import DataLoader
from utils import get_fullpath
class PickleLoader(DataLoader):
def load(self):
with open(get_fullpath(self.config.dataset.dataset_path), "rb") as file:
to_load = pickle.load(file)
return to_load["articles"], to_load["original_artic... |
62e1424b806025ce466853b449ca6cb0e865a8b56f021c976131ea1100cc61a6 | Python | 371 | 10 | from .bbox_head import BBoxHead
from .convfc_bbox_head import (ConvFCBBoxHead, Shared2FCBBoxHead,
Shared4Conv1FCBBoxHead)
from .double_bbox_head import DoubleConvFCBBoxHead
from .sabl_head import SABLHead
__all__ = [
'BBoxHead', 'ConvFCBBoxHead', 'Shared2FCBBoxHead',
'Shared4Conv... |
9e78ffeef7e066454a1a80cb1031c8c53fb68537d6becdf2a5af020b220c47bb | Python | 373 | 13 | import pytest
import scPrisma
def test_cpuonly_import():
assert scPrisma.spectrum_gen.jit.__name__ == "jit"
assert scPrisma.algorithms.__name__ =="scPrisma.algorithms"
with pytest.raises(AttributeError) as exc_info:
scPrisma.algorithms_torch
assert (
"module 'scPrisma' has no attribut... |
d7f80ec5ad66edce67a11898f2c35a4db55c8c4b349e7a7e593e0cb2527300f0 | Python | 373 | 11 | from setuptools import setup
setup(name='stokes',
# version='',
# description='',
url='https://cfaed.tu-dresden.de/friedrich-home',
author='Anton Solovev, Gary Klindt, Benjamin Friedrich',
author_email='anton.solovev@tu-dresden.de',
license='Internal Use',
packages=['mesh', ... |
a8bdc09d1725d4276536f28f900a42dc2f517bc006fd39e815bf278f7381546d | Python | 374 | 11 | import networkx as nx
import matplotlib.pyplot as plt
from graphxai.datasets.utils.bound_graph_pref_att import build_bound_graph
G = build_bound_graph(num_subgraphs = 3, prob_connection = 0.5, subgraph_size = 8, show_subgraphs = True)
c = [int(G.nodes[n]['shape'] == 0) for n in G.nodes]
pos = nx.kamada_kawai_layout(... |
b32b704c811444ecb8018e91629c9c4d62cf43d8e2a5e4ef769090d97420b125 | Python | 374 | 18 | from . import Auditory_processing
from . import BCI_Competition_IV
from . import DUMMY
from . import GIGA_BCI
from . import GIGA_MI_ME
from . import HighGamma_ME
from . import PhysioNet_MI_ME
available_databases = [
'Auditory_processing',
'BCI_Competition_IV.Dataset_2a',
'DUMMY',
'GIGA_BCI',
'GIGA_... |
d9e4565a7954573cf3394a9a709cd5e190e1b52ccbe8b7420255c6745151c2cc | Python | 374 | 14 | from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="thingsmri",
version="0.1",
packages=find_packages(),
install_requires=requirements,
author="Oliver Contier",
author_email="contier@cbs.mpg.de",
description=... |
29b78ed8389884bafe9176ff2ac8eae4030ac07c220f3f06756396872d90fc11 | Python | 375 | 17 | import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--prefix', type=str, required=True)
args = parser.parse_args()
fname_base = args.prefix + '_GES_'
suffixes = ['edge', 'node', 'feat']
for s in suffixes:
f = fname_base + s + '.npy'
arr = np.load(open(f, 'rb'), allow_p... |
3909bbef66e55d893dd0986e8d569cf5c2652e707da57d27496308298e9b7706 | Python | 375 | 11 | #!/usr/bin/env python
import os
from h5xplorer.h5xplorer import h5xplorer
import h5x_menu
#baseimport = '/home/nico/Documents/projects/deeprank/DeepRank-GNN/deeprank_gnn/h5x/baseimport.py'
baseimport = os.path.dirname(
os.path.abspath(__file__)) + "/baseimport.py"
app = h5xplorer(h5x_menu.context_menu,
... |
7426647793f0a69505a185f88bfb7149f0fe65cd595c49dd8096337e7787da4e | Python | 375 | 15 | import torch
from tqdm import trange
from graphxai.datasets import Benzene, FluorideCarbonyl
dataset = FluorideCarbonyl(split_sizes = (0.8, 0.2, 0), seed = 1234)
conf_matrix = torch.zeros((2, 2))
for i in trange(len(dataset)):
data, exp = dataset[i]
yval = int(data.y)
conf_matrix[int(exp[0].has_match), y... |
2c2a30f121d26fe0e17efbf6277d8e08324b7b9ef146357286bccca4fc4ea75c | Python | 376 | 12 | #!/usr/bin/env python
from distutils.core import setup
setup(name='sparse_filtering',
version='1.1',
description='Unsupervised feature learning based on sparse-filtering',
author='Jan Hendrik Metzen',
author_email='jhm@informatik.uni-bremen.de',
url='https://github.com/jmetzen/sparse-fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.