sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
3698d6cc0b7ffb899e4b7eb758f0157764738743d43d1b49bb98c71f8051d3a6 | Python | 305 | 8 | # Copyright 2020-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""openfl.experimental.workflow.notebooktools package."""
from openfl.experimental.workflow.notebooktools.code_analyzer import CodeAnalyzer
from openfl.experimental.workflow.notebooktools.notebook_tools import NotebookTools
|
a19e68922d3e619c1c4d1534929f687367920b2dfca39611a0341d362dcb819f | Python | 305 | 10 | """nltools I/O utilities.
`events_to_dm` turns a BIDS events table into boxcar regressors. HDF5
serialization for the data classes lives in `nltools.io.h5`; users reach it
through `BrainData.write`/`Adjacency.write` and the constructors.
"""
from .events import events_to_dm
__all__ = ["events_to_dm"]
|
ba05e5ee4f1903d5f9f60d0932bfed74cb4f7524a86de2c98d385503629640c3 | Python | 305 | 11 | import PIL
def imagedraw_textsize_c(draw, text, font=None):
if int(PIL.__version__.split('.')[0]) < 10:
tw, th = draw.textsize(text, font=font)
else:
left, top, right, bottom = draw.textbbox((0, 0), text, font=font)
tw, th = right - left, bottom - top
return tw, th
|
bafce42fa108dd8cd5aa8c2a0081966450bf552f598cba13572a9a2a4bbfe7bf | Python | 305 | 16 | import sys
PLOT = not 'no_plot' in sys.argv
MEASURE_INDIVIDUALLY = False
DURATION = 300
SIZE = int(sys.argv[1])
VT = 6.0
VR = 0.0
STDP_SPEED = 0.001
DECAY = 0.9
OM_DECAY = 1 - DECAY
REPORT_FUNC = '''
if (completed == 1.0) std::cout << "simulation time: " << elapsed << std::endl << std::flush;
'''
|
8aa865e94d6f1baffe89f5258ea48a78595b722ed90bc94e36cd9c9418825b22 | Python | 306 | 11 | from setuptools import setup, find_packages
setup(
name="LungTumorSegmentation",
packages=find_packages(),
version='1.0.1',
author="Svein Ole M Sevle, Vemund Fredriksen",
url="https://github.com/VemundFredriksen/LungTumorSegmentation",
license="MIT",
python_requires='>=3.6'
)
|
6674048587e5c1db0d989b7717f0afc3d84c31e929b1961fe2a8800458fcf382 | Python | 307 | 7 | from rest_framework import status
from rest_framework.response import Response
def sendfile(request, filename, **kwargs):
headers = {'Location': filename, 'Access-Control-Allow-Origin': request.headers['Origin']}
print(headers)
return Response(status=status.HTTP_303_SEE_OTHER, headers=headers) |
1b95dd3f3ca113a8e92f8da2d6abeb12959d3a1c6b98fdd115c3db72d5f4c2bd | Python | 308 | 8 | from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.backend import AgainstEinsumTestCase
from .data.against_einsum import AgainstEinsumTestData
class TestAgainstEinsum(AgainstEinsumTestCase, metaclass=DataBasedParametrizer):
testing_data = AgainstEinsumTestData()
|
61da151b7ea6f4557496adb27b0b26f72f2ea2fecc6e8c549fa4e6cb96797ee2 | Python | 308 | 8 | from geomstats.test.parametrizers import DataBasedParametrizer
from geomstats.test_cases.algebra_utils import AlgebraUtilsTestCase
from .data.algebra_utils import AlgebraUtilsTestData
class TestAlgebraUtils(AlgebraUtilsTestCase, metaclass=DataBasedParametrizer):
testing_data = AlgebraUtilsTestData()
|
d67234f195b893e2a5c46ce9c3e19022393be8048a0a53e5ba25ad0e57886296 | Python | 311 | 10 | """
Main module. Run this module to start the system.
Author: Tal Eisenberg, 2021
Run 'python main.py -h' for help about command line arguments.
"""
if __name__ == "__main__":
# We do this to prevent re-initializing the system each time a process is created when using the spawn method.
import system
|
db5c9a5a9ab399d8eff4771c330523c489795a1b01c3d503e0d984b050462569 | Python | 311 | 12 | """References for the published checkpoint that is tracked in this tree."""
from __future__ import annotations
from tests.golden.targets import _foundations
ORDER = 40
HELP = "references for the published checkpoint tracked in this repository"
def run() -> None:
_foundations.regenerate(network=False)
|
fde7c531b9e92f6725c000dd25a07475b29fea0f173bf7710f815a004cd0ff5e | Python | 312 | 8 | class MolecularDescriptorsEnum:
HEAVY_ATOM_COUNT = "heavy_atom_count"
MOLECULAR_WEIGHT = "molecular_weight"
CLOGP = "clogp"
HYDROGEN_BOND_DONORS = "hydrogen_bond_donors"
HYDROGEN_BOND_ACCEPTORS = "hydrogen_bond_acceptors"
ROTATABLE_BONDS = "rotatable_bonds"
RING_COUNT = "ring_count"
|
5378d9bd96d1a97e6a3e78438172a8ff7f1e2a78cb8c861ca1690e164588741e | Python | 314 | 8 | from django.urls import re_path
from celsusdjango.consumers import CurtainConsumer, JobConsumer
websocket_urlpatterns = [
re_path(r'ws/curtain/(?P<session_id>\w+)/(?P<personal_id>\w+)/$', CurtainConsumer.as_asgi()),
re_path(r'ws/job/(?P<session_id>\w+)/(?P<personal_id>\w+)/$', JobConsumer.as_asgi()),
]
|
280334b87867506b0a3983364b33a61c1cb6d0805614e59a51658786811ef8c1 | Python | 315 | 11 | """
Module for signal replay
Replay the recorded signals in real time as if it
was transmitted from a real acquisition server.
For Windows users, make sure to use the provided time resolution
tweak tool (TimerTool) to set to 500us time resolution of the OS.
"""
from .stream_player import StreamPlayer, Streamer
|
c43551fdec7d07992f0079d0f4830e2615cb9d17c72ef1effee4c81809e81724 | Python | 315 | 7 | from unittest import TestCase
from curtainutils.client import parse_curtain_from_json
class Test(TestCase):
def test_parse_curtain_from_json(self):
json_path = r"C:\Users\Toan Phung\curtain_media\files\curtain_upload\0a0d33de-478b-4654-8cec-811a86400062.json"
parse_curtain_from_json(json_path) |
94e5bf861a0a5534393fc015e75b08aea14378fddd79b2c26a05e7c06d156921 | Python | 317 | 17 | """
Modified from the https://github.com/rusty1s/pyg_autoscale/tree/master/torch_geometric_autoscale/models
"""
from .base import ScalableGNN
from .gcn import GCN
from .gcn2 import GCN2
from .pna import PNA
from .pna_jk import PNA_JK
__all__ = [
'ScalableGNN',
'GCN',
'GCN2',
'PNA',
'PNA_JK',
]
|
bb1e1c45e21e90c0b3ea9c42c89c37338c116a3cec9d51dd7a73926dccdadcfa | Python | 317 | 14 | from .vtkhandler import VTKHandler
class VTPHandler(VTKHandler):
cls_format = 'xml_polydata'
@classmethod
def read(cls, filename):
return super().read(filename, fmt=cls.cls_format)
@classmethod
def write(cls, filename, data):
super().write(filename, data, fmt=cls.cls_format)
|
d0ac987d861956f1574fe6512bbbc82325c11f84cfb45920bf1d67e98a23d5e1 | Python | 317 | 8 | # Copyright 2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from importlib import util
if util.find_spec("flwr") is not None:
from openfl.transport.grpc.interop.flower.interop_client import FlowerInteropClient
from openfl.transport.grpc.interop.flower.interop_server import FlowerInteropServer
|
eecf06e584e5d2861a32a7a88e1b2ac6fbfd5dafa290d6e37b084dda755452ec | Python | 317 | 11 | __description__ = \
"""
Python class for interfacing with CmdMessenger arduino serial communications
library.
"""
__author__ = "Michael J. Harms"
__date__ = "2016-05-23"
__all__ = ["PyCmdMessenger","arduino"]
from .PyCmdMessenger import CmdMessenger as CmdMessenger
from .arduino import ArduinoBoard as ArduinoBoard
|
2acecbafffffca702c852b3c86d470904f39d0851c4c6b0b1f6d77785f6d4db6 | Python | 318 | 12 | import mdtraj as md
import glob
import os
import sys
infile = sys.argv[1]
outfile = sys.argv[2]
print(f"Input trajectory file {infile}")
print(f"Output trajectory file {outfile}")
trj = md.load_netcdf(infile, top="civsd.prmtop")
trj.atom_slice(trj.topology.select("protein")).save_xtc(outfile, force_overwrite=True)
|
2aa58dce295f31d3f1c5172f922aafcbe9b84ac54c1a9fa1306f1a83ad8aceb4 | Python | 319 | 10 | # Copyright (C) 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
def aggregator_private_attrs():
return {"test_loader_agg_via_callable": np.random.rand(10, 28, 28)} # Random data
aggregator_private_attributes = {"test_loader_agg": np.random.rand(10, 28, 28)} # Random data
|
a2040d3225e01196f36b96cc00cb133aeaee5b90f1c22724a688e644eae37e5e | Python | 319 | 14 |
from skimage.transform import iradon, iradon_sart
from .base import Reconstructor
class PerceptualTVReconstructor(Reconstructor):
def __init__(self, name, angles):
super(PerceptualTVReconstructor, self).__init__(name, angles)
def calc(self, projs):
return iradon(projs, theta=self.angles) |
65b66aecdec1a3aea58d79cda865f90aa246d82aaca3c5baafa76dd3437ac4a9 | Python | 321 | 18 | import sys
PLOT = not 'no_plot' in sys.argv
MEASURE_INDIVIDUALLY = False
DURATION = 300
SIZE = int(sys.argv[1])
VT = 6.0
VR = 0.0
STDP_SPEED = 0.001
DECAY = 0.9
OM_DECAY = 1 - DECAY
DENSITY = 0.01
REPORT_FUNC = '''
if (completed == 1.0) std::cout << "simulation time: " << elapsed << std::endl << std::flush;
'''... |
6b0f49a046d350e52a1c23a742077806ccd126d1435ad9090e7ea42aca6ded24 | Python | 323 | 13 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""openfl.experimental.workflow.transport package."""
from openfl.experimental.workflow.transport.grpc import (
AggregatorGRPCClient,
AggregatorGRPCServer,
DirectorGRPCServer,
EnvoyDirectorClient,
RuntimeDirectorClient,... |
461a906cc6f23126d82be5392dbdc593c36b43471f2aeb9e88cef56e45fd62c0 | Python | 324 | 8 | '''
Motor imagery protocol
Contains the three protocols to perform a motor imagery BCI task:
- offline_mi = data acquisition while the subject is performing mi tasks
- trainer_mi = classifier training on the previously acquired data
- online_mi = real-time classification of the subject's mi... |
b0f8351d79ae9b7307ef15d5b66f9dc2d410387390478a5e8a2fd872c89fd621 | Python | 324 | 8 | import pandas as pd
data=pd.read_csv('ImmuNexUT_sort.vcf', sep='\t')
data=data.groupby(['CHROM','POS','ID','REF','ALT'])
data=data['Cell_Subset'].unique()
data=data.reset_index()
data['Cell_Subset']=data['Cell_Subset'].apply(lambda x: ';'.join(x))
data.to_csv('ImmuNexUT_sort_merge.vcf', sep='\t', header=None, index=No... |
e2a2e4f4961ac5768b7dc1094ad80dc83b4cc76f72a7600a717e592ef8f25923 | Python | 325 | 13 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name='structure_index',
version='0.1',
description = 'Structure Index Method',
author = 'Julio Esparza & Enrique R. Sebastian',
author_email = 'julioesparzaibanez@gmail.com',
packages= find_packages()
)
... |
e9c17910150e21dae74e1707b67c17676708a61befe5b90e3202f74abc4aa2fc | Python | 326 | 6 |
from sleepy.gui.tagging.model.event.core import Event
from sleepy.gui.tagging.model.event.interval import IntervalEvent
from sleepy.gui.tagging.model.event.point import PointEvent
from sleepy.gui.tagging.model.event.user import UserPointEvent
from sleepy.gui.tagging.model.event.exceptions import EventTypeNotSuppo... |
03ca65d92c6a068dbf5924a72f0e3df5ca22fb33e8ca3d193a036ac8d118cf7a | Python | 331 | 9 | from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, Input, Reshape
from keras import optimizers
model = Sequential()
model.add(Dense(64, activation = 'relu', input_shape=(2048,)))
model.add(Dropout(0.2))
model.add(Dense(16, activation = 'relu'))
model.add(Dr... |
798ba72b9f27949c8445d8808d5e2ed03713b45e5b6bc682d063a223145f4528 | Python | 331 | 12 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
max_metadata_size = 32 * 2**20
max_message_length = 2**30
channel_options = [
("grpc.max_metadata_size", max_metadata_size),
("grpc.max_send_message_length", max_message_length),
("grpc.max_receive_message_length", max_message_... |
a6c400d90c784684eb11b9de1c13f7c4aa1fbbbaac9c559a31ef0477911aa059 | Python | 332 | 11 | from dataclasses import dataclass, fields
@dataclass(frozen=True)
class SamplingModesEnum:
GREEDY: str = "greedy"
MULTINOMIAL: str = "multinomial"
BEAMSEARCH: str = "beamsearch"
def is_supported_sampling_mode(self, sample_mode):
return sample_mode in [getattr(self, field.name) for field in fi... |
01efc31549aa63ef42d47e682c5e426a36d8ba3a5fcbad456c6c4b46faaa38e9 | Python | 333 | 14 | from __future__ import annotations
from typing_extensions import TypeAlias, TypedDict
class InputConfig(TypedDict, total=False):
"""Configuration passed in snakebids.yaml file"""
filters: dict[str, str | bool | list[str]]
wildcards: list[str]
custom_path: str
InputsConfig: TypeAlias = "dict[str, I... |
9866ba2a3265ea440ec5ab966d5eb21bc441b4b894e4843b2c2daf9feaa07387 | Python | 334 | 8 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""OpenFL Assigner Module."""
from openfl.component.assigner.assigner import Assigner
from openfl.component.assigner.random_grouped_assigner import RandomGroupedAssigner
from openfl.component.assigner.static_grouped_assigner import StaticGr... |
9bed21d73b4493b61ee11047e159db646d5114f8eb47dd1cbf4536e82978197a | Python | 334 | 12 | from e3nn import o3
from mace.tools import cg
def test_U_matrix():
irreps_in = o3.Irreps("1x0e + 1x1o + 1x2e")
irreps_out = o3.Irreps("1x0e + 1x1o")
u_matrix = cg.U_matrix_real(
irreps_in=irreps_in, irreps_out=irreps_out, correlation=3, use_cueq_cg=False
)[-1]
assert u_matrix.shape == (3,... |
6cad6ab1b80d48aa7f97293ded65d820cf22fb6259a6715d253b8594296c4ae2 | Python | 335 | 12 | """Where this directory sits, for the modules that print relative paths.
Its own module so that the target modules can import it without importing
``regenerate``, which imports them.
"""
from __future__ import annotations
from pathlib import Path
GOLDEN_ROOT = Path(__file__).resolve().parent
REPO_ROOT = GOLDEN_ROOT... |
5c2b225fd27abaf0bb5cafe1510cb4aaac883681dc796d04767f7a53a240ac8e | Python | 338 | 11 | from tensorflow.keras.layers import Input
from tfkerassurgeon import delete_layer, insert_layer
def changeFirstLayer(model):
new_input = Input(shape=(None, None, 1), name='arbitrary_input')
model = delete_layer(model.layers[0])
# inserts before layer 0
model = insert_layer(model.layers[0], new_input)
... |
89013611ade4fc21e604680678e2c22db1b8f1486459ccb39223ccde42ffc8f2 | Python | 338 | 7 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
def assert_package_extension(path, what: str = "packaged model file") -> None:
assert str(path).endswith(".nequip.zip"), (
f"The {what} should have the extension `.nequip.zip`, but found {... |
b98df037e5a4ceb636ea9590fd4dd461bda20217496ed200ac36212231b60aab | Python | 338 | 10 | from fairseq.models.transformer import TransformerModel
zh2en = TransformerModel.from_pretrained(
'/path/to/checkpoints',
checkpoint_file='checkpoint_best.pt',
# data_name_or_path='data-bin/wmt17_zh_en_full',
# bpe='subword_nmt',
# bpe_codes='data-bin/wmt17_zh_en_full/zh.code'
)
zh2en.translate('你好 世界')
# 'He... |
933cb67c051808bedfcb2fcc217fc478e4ede17a2b39f685943262fbf68bbace | Python | 344 | 7 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
from .torchscript import load_torchscript_model
from .aotinductor import load_aotinductor_model
from .compiled import load_compiled_model
__all__ = ["load_torchscript_model", "load_aotinductor_model",... |
eabc5661808096544016884c5f8a294259e35d86346b731ec3148d99d942fe3c | Python | 344 | 11 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""PyTorch optimizers package."""
from importlib import util
if util.find_spec("torch") is not None:
from openfl.utilities.optimizers.torch.fedprox import FedProxAdam # NOQA
from openfl.utilities.optimizers.torch.fedprox import F... |
4ad49db0434edfa2f24a231adb21f235688854f4b79b621fa685b3dbde056553 | Python | 347 | 24 | """
Plot Figure 3 of SanPy manuscript
"""
import matplotlib.pyplot as plt # just to show plots during script
import sanpy
def fig():
path = 'laura-iso-manuscript/19503001.abf'
ba = sanpy.bAnalysis(path)
print(ba)
ap = sanpy.bAnalysisPlot(ba)
axs = ap.plotRaw()
plt.show()
if __name... |
922fb000cd3bbbeead69060288a00ad5401110d96d34ddd3e72ec7034e51e38d | Python | 348 | 12 | import geomstats.backend as gs
from geomstats.test.data import TestData
rand = gs.random.rand
class AgainstEinsumTestData(TestData):
def binary_op_like_einsum_test_data(self):
smoke_data = [
dict(func_name="matvec", a=rand(3, 3), b=rand(3), einsum_expr="ij,j->i")
]
return self... |
c35e9a72a565174856cea64064950ac5db175b94ffc19f852e4158ee72b8deae | Python | 348 | 11 | from .mol_dataset import MoleculeDataset
from .nlp_dataset import SentiGraphDataset
from .syn_dataset import BA_LRP, SynGraphDataset
from .utils_dataset import MarginalSubgraphDataset
__all__ = ['MoleculeDataset',
'SentiGraphDataset',
'BA_LRP',
'SynGraphDataset',
'M... |
a188f07b840e7e9244bdc2025a61a5158b60206c6c458464f559afde2fea4183 | Python | 349 | 11 | '''
Dataset Preparation init
'''
__project__ = 'Object_Detector'
__title__ = 'object_detector'
__author__ = 'Laura Meneghetti, Nicola Demo'
__maintainer__ = __author__
#from smithers.ml.dataset.create_json import *
from smithers.ml.dataset.imagerec_dataset import Imagerec_Dataset
from smithers.ml.dataset.pascalvoc_dat... |
a633b831226341d390363355fd0a5ae40dddf4f3f6024d23f563d69b81d4e0fc | Python | 350 | 8 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... |
008d6b4d6cbc2a01e3ae332e361175ddc0f4cf0dad9de545fd08ac06e41b3de3 | Python | 351 | 11 | from setuptools import setup, find_packages
setup(
name='budapestcode',
version='0.0.1',
author='Matteo Visconti di Oleggio Castello, Jiahui Guo',
author_email='mvdoc@berkeley.edu, jiahui.guo@dartmouth.edu',
description='Code for analyses related to the Budapest dataset',
packages=find_packages... |
5ad7f7a23792f52eb1a0779b6f5fb35f3faff88d229d525a9c4724bf26baabb7 | Python | 351 | 7 | from geomstats.test_cases.geometry.riemannian_metric import RiemannianMetricTestCase
class SasakiMetricTestCase(RiemannianMetricTestCase):
def test_geodesic_discrete(self, initial_point, end_point, expected, atol):
res = self.space.metric.geodesic_discrete(initial_point, end_point)
self.assertAllC... |
c96b05453fd2be40e19d769a52f2b5bf2a699aa9e97f348bf802b2a9ad3223e9 | Python | 351 | 18 | import os
import pickle
def store_pickle(filepath, object):
with open(filepath, 'wb') as f:
pickle.dump(object, f)
def load_pickle(filepath):
with open(filepath, 'rb') as f:
object = pickle.load(f)
return object
def safe_make_dir(folder_path):
if not os.path.exists(folder_path):
... |
cba6e137066b2c691f1da38e4c353bdc428ed5f1796cedb41c48195f47a41e97 | Python | 352 | 14 | from geomstats.test.data import TestData
from ._base import BaseEstimatorTestData, MeanEstimatorMixinsTestData
class IncrementalFrechetMeanTestData(
MeanEstimatorMixinsTestData, BaseEstimatorTestData
):
pass
class IncrementalFrechetMeanEuclideanTestData(TestData):
def fit_eye_test_data(self):
r... |
0743922cb9c1dbd29a82e16591dd6ced47e807f89011d4385fbe52d62864f1a5 | Python | 353 | 17 | from neurodesign import Optimisation, report
def test_report_smoke(exp, tmp_path):
pop = Optimisation(
experiment=exp,
weights=[0, 0.5, 0.25, 0.25],
preruncycles=2,
cycles=2,
folder=tmp_path,
seed=100,
)
pop.optimise()
pop.download()
report.make_re... |
3a65df1202559b42285b2f5e82c23b049d0520a0172e883cd49fd82ba7348bbb | Python | 353 | 17 | # Generated by Django 4.1.1 on 2022-10-20 12:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('celsus', '0011_author_first_author_delete_firstauthor'),
]
operations = [
migrations.RemoveField(
model_name='author',
name=... |
581efa4b9dd0da47a42cc22b608deaf04e1a9fb78f42c14007c240518ecfd40b | Python | 353 | 4 | from deeperwin.model.orbitals.orbital_net import OrbitalNet
from deeperwin.model.orbitals.baseline_orbitals import BaselineOrbitals
from deeperwin.model.orbitals.transferable_atomic_orbitals import TAOExponents, TAOBackflow, TransferableAtomicOrbitals
from deeperwin.model.orbitals.baseline_orbitals import BaselineOrbit... |
197b9076debc76c7e9658205df3dff2c9188b93baaf025dff831ef6350aa9ee4 | Python | 357 | 9 | __version__ = "0.1.9"
__author__ = 'Peter Neher'
__email__ = 'p.neher@dkfz.de'
__copyright__ = "Copyright 2023, German Cancer Research Center (DKFZ), Division of Medical Image Computing"
__license__ = "Apache License 2.0"
# Copyright © 2023 German Cancer Research Center (DKFZ), Division of Medical Image Computing
#
# ... |
21053565798f2a2719e5d4df7e774250a7c85e21942fc28831d08a7846b5629d | Python | 357 | 13 | from __future__ import annotations
import jinja2.parser
from colorama import Fore
from jinja2.ext import Extension
class ColoramaExtension(Extension):
"""Include colorama foreground colors in the global environment."""
def __init__(self, env: jinja2.Environment):
super().__init__(env)
env.gl... |
53f2ebbeb8bc33d0c97ccd28922f213e8f125e56ca1852c4e8d0ad5fa2e2d659 | Python | 357 | 10 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from cvnets.misc.common import parameter_list
from cvnets.layers import arguments_nn_layers
from cvnets.models import arguments_model, get_model
from cvnets.misc.averaging_utils import arguments_ema, EMA
from cvnets... |
d2d83c1603543aa75175accf8810d1f09e12b79555042966372d4af0041a1af6 | Python | 358 | 16 | import random
import torch
import numpy as np
def setup_seed(seed):
r"""To setup seed for reproducible experiments.
Args:
seed (int, or float): The number used as seed.
"""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
np.ra... |
30b284db52ad1835ef0c86d134aeb9db1052c36182991f8901024a6884a374c0 | Python | 359 | 14 | import math
import torch.nn as nn
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
super(Embeddings, self).__init__()
# weight matrix, each row present one word
self.lut = nn.Embedding(vocab, d_model)
self.d_model = d_model
def forward(self, x):
return... |
0bf756ae5d695664db5c65c77650bad61fe1b8089e72fc7098edb10c0b0f6fc8 | Python | 361 | 12 | import numpy as np
from rdkit.Chem import DataStructs
def calculate_tanimoto_batch(fp, fps) -> np.array:
return np.array(DataStructs.BulkTanimotoSimilarity(fp, fps))
def calculate_tanimoto(query_fps, ref_fingerprints) -> np.array:
return np.array(
[np.max(DataStructs.BulkTanimotoSimilarity(fp, ref_f... |
e0ed37f1cbbac527f04b64a1cc106d5bf5efc119da2730a80e99f0b4dd3d4ba9 | Python | 363 | 12 | from geomstats.test_cases.learning._base import (
BaseEstimatorTestCase,
MeanEstimatorMixinsTestCase,
)
class IncrementalFrechetMeanTestCase(
MeanEstimatorMixinsTestCase, BaseEstimatorTestCase
):
def test_fit(self, X, expected, atol):
estimate = self.estimator.fit(X).estimate_
self.ass... |
e4c253e3ebddf017924ba190b9a6bedfecd024fb7d11e9f570c4b517c7a99a00 | Python | 363 | 12 | from dig.fairgraph.method import run
from dig.fairgraph.dataset import POKEC, NBA
import torch
# Load the dataset
nba = NBA()
# Train and evaluate
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
run_fairgraph = run()
run_fairgraph.run(device,dataset=nba,model='Graphair',epochs=10000,test_epochs=... |
4076e1735ddd399949c089b9d136ab68dd8c71c07b3b26d1075a801a76d1607d | Python | 364 | 12 | from .scaffold_penalty import ScaffoldPenalty
class StepPenalty(ScaffoldPenalty):
"""Penalty based on step function: return 0 if bucket is full, else return 1. Default in REINVENT."""
def calculate_penalty(self, scaffold: str) -> float:
if self.scaffold_memory.bucket_full(scaffold):
retur... |
fa6ced62a7e6b730251f0dde5601f779f282f78e16a29517c1315403f1f6d96d | Python | 364 | 17 | # Generated by Django 4.1.1 on 2022-10-02 17:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('celsus', '0002_experimenttype_remove_project_experiment_type_and_more'),
]
operations = [
migrations.RemoveField(
model_name='author',
... |
751a2608188f829877e84676520f4a75bfc19ebcc8833f285d393257c97b19d8 | Python | 368 | 18 | # type: ignore
__submodules__ = ["_factory", "_presets", "_config", "_utils"]
# <AUTOGEN_INIT>
import lazy_loader
__getattr__, __dir__, __all__ = lazy_loader.attach_stub(__name__, __file__)
__all__ = [
"BidsFunction",
"BidsPathEntitySpec",
"BidsPathSpec",
"BidsPathSpecFile",
"bids",
"bids_fac... |
6e9f3d3b2dccd2609439559141646675fe441a1d05965cbaa13a2041ba1a0a6c | Python | 372 | 18 | from dataclasses import dataclass, astuple
import torch
@dataclass
class BatchDTO:
input: torch.Tensor
input_mask: torch.Tensor
output: torch.Tensor
output_mask: torch.Tensor
tanimoto: torch.Tensor = None # Mol2Mol rankingloss model
def __iter__(self):
return iter(astuple(self))
... |
93e5955d28d9d9231000e6d7ce16f147c36fb186c2a9fc4618db3c000cb08e74 | Python | 372 | 9 | # Copyright 2020-2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""openfl.experimental.workflow.runtime package Runtime class."""
from openfl.experimental.workflow.runtime.federated_runtime import FederatedRuntime
from openfl.experimental.workflow.runtime.local_runtime import LocalRuntime
from openfl.e... |
e371952124cd22d6b66496c4fab83202a81a3c615c5d4591aad0ba4b5011958c | Python | 377 | 15 | from corgie.layers.base import get_layer_types, str_to_layer_type
# when adding a new layer type, include it here
from corgie.layers.volumetric_layers import (
FieldLayer,
ImgLayer,
MaskLayer,
SectionValueLayer,
SegmentationLayer,
FixedFieldLayer,
FloatTensorLayer,
)
# also update the defa... |
677fc4b64695b17fed64ef6c2c59d46034774034e036ce5351043a8a0fb99362 | Python | 378 | 13 | from .xpu import XPUAccelerator
__all__ = ["XPUAccelerator"]
import sys
from lightning.pytorch.accelerators.accelerator import Accelerator
from lightning.pytorch.accelerators import AcceleratorRegistry
from lightning.fabric.utilities.registry import _register_classes
_register_classes(
AcceleratorRegistry, "reg... |
cbdfecfe53503d71c88d880a9460864b044dbcd2436c8f55fcdc10357bbbc19f | Python | 378 | 17 | """SanPy electrophysiology analysis package."""
from ._version import __version__
from .bAnalysis_ import bAnalysis
from .bDetection import bDetection
from .analysisDir import analysisDir
from .metaData import MetaData
from .sanpy_paths import SanPyPaths
__all__ = [
"__version__",
"analysisDir",
"bAnalysi... |
faddb9594e2844a5d4dc8e0f17c1bfb9533650dceed527e37d2d432f63f45954 | Python | 378 | 12 | import importlib
from typing import Type, TypeVar, cast
C = TypeVar("C")
def get_class(fqn: str, type: Type[C]) -> Type[C]:
"""Given a fully qualifed class name, import the module and return the class"""
module_name, class_name = fqn.rsplit(".", 1)
module = importlib.import_module(module_name)
cls = ... |
dd0b0b03aaefc55628f140cc83a0ee8c4f90f8a3f0ee6fa1eb7f9986e908f72e | Python | 380 | 6 | """Puts ``tests/`` on ``sys.path`` so both tiers can import :mod:`legacy_qc`.
pytest inserts a conftest's own directory under the default ``prepend`` import mode, which is the
whole reason this file exists: ``tests/unit/`` and ``tests/release/`` both measure the new rules
against the same transcription of the retired ... |
6c6081d5c2b0b89fbb6d3d60da108b291289c56b963ff251e74b37313b726534 | Python | 381 | 18 | from src.gui import WebUI
def main():
print("Launching demo...")
# cwd = "/Users/andreped/workspace/LungTumorMask/" # local testing -> macOS
cwd = "/home/user/app/" # production -> docker
class_name = "tumor"
# initialize and run app
app = WebUI(class_name=class_name, cwd=cwd)... |
ff54fe9b7aa2fd7fe0ecb141540bf6362fcc5d4996be1fb0e66aa81300c662b0 | Python | 381 | 15 | __author__ = 'Bob'
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='hasGroup')
def hasGroup(user, group_name):
try:
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else False
excep... |
ff52e116d3fcf9fce41e049a5a5774f9f553f2b2ba9aae7cbd566eaa907c902b | Python | 382 | 16 | from setuptools import find_packages
from setuptools import setup
setup(
name="trainmodel",
description="Train a tensorflow model on GCP.",
author="Adam Richie-Halford",
author_email="richiehalford@gmail.com",
install_requires=[
"gcsfs==2021.7.0",
"nobrainer==0.2.1",
"numpy"... |
080b0c4bfd7312bb56974d03a9f7a362071651b23b47c12cf0991fb16ffb8901 | Python | 386 | 11 | from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation, Input, Reshape
from keras import optimizers
model = Sequential()
model.add(Dense(64, activation = 'relu', input_shape=(2048,)))
model.add(Dropout(0.2))
model.add(Dense(16, activation = 'relu'))
model.add(Dr... |
50ffc30aecf0e0f389d32b36a2e568245db22726ed9b53752304762af52b899c | Python | 387 | 17 | import os
import sys
import mdtraj as md
sys.path.insert(1, "/project/dinner/scguo/ci-vsd/python")
from util import zero_h_occupancy
from prep import strip_water
def main(input, output):
_ = strip_water(input, output)
zero_h_occupancy(output, new_file_name=output, savelines=3)
if __name__ == "__main__":
... |
603b7a165a21b5c425cf7027bd28b9d0c9d1fa35099c214577e8705aaa0c4edc | Python | 387 | 13 | from django.db import models
# Create your models here.
class markers(models.Model):
id = models.IntegerField(primary_key=True)
menu = models.TextField()
class_id = models.IntegerField()
name = models.TextField()
color = models.TextField()
def __str__(self):
return str(self.menu + "_" +... |
85dd58c6b7d1a17d16e6944dcb4821d0b7e492fcb6215ef393268043fd7bce18 | Python | 387 | 16 | __author__ = 'palmer'
# every method in smoothing should accept (im,**args)
def median(im, **kwargs):
from scipy import ndimage
im = ndimage.filters.median_filter(im,**kwargs)
return im
def hot_spot_removal(im, q=99.):
import numpy as np
xic_q = np.percentile(im, q)
im[im > xic_q] = xic_q
r... |
44e5aad04bf2514cb8a4c57f8e647b630e6a346a77144ee25c0f37b65393b7a5 | Python | 389 | 18 | # Generated by Django 2.1 on 2019-07-08 07:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('imagelist', '0003_ihclist'),
]
operations = [
migrations.AddField(
model_name='menu_selection',
name='localserver',
... |
517c66c5010e78d080bfb31991dfd4466d02a3f7b5bac4e220d5011a0266c04b | Python | 389 | 26 | import numpy as np
from cloudvolume import CloudVolume
## Load volume
def load_volume(path, res):
"""
INPUT:
path : Path of the volume
res : (x, y, z) resolution in nm
OUTPUT:
vol : Image volume
"""
if path[:2] == "gs":
cloud_vol = CloudVolume(path, mip=res,
parallel=True, progress=False)
vol = clo... |
8e5d465d21c3bf048be49d8e8e6dcff8f0cd434c3679d8bf8a558329d585349f | Python | 389 | 9 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... |
1270abed90c77f18768280fa68c4de016ce3ed2faab43e783ccd229df90c902f | Python | 392 | 12 | # This file is a part of the `nequip` package. Please see LICENSE and README at the root for information on using it.
from .checkpoint import ModelFromCheckpoint
from .package import ModelFromPackage, ModelTypeNamesFromPackage
from .load_utils import load_saved_model
__all__ = [
"ModelFromCheckpoint",
"ModelF... |
442f686244d7fef56d818d27fba74e60d294babee89c250bc95260db0d4edd5a | Python | 392 | 14 | import argparse
class BaseOptim(object):
"""Base class for optimizer"""
def __init__(self, opts) -> None:
self.eps = 1e-8
self.lr = getattr(opts, "scheduler.lr", 0.1)
self.weight_decay = getattr(opts, "optim.weight_decay", 4e-5)
@classmethod
def add_arguments(cls, parser: arg... |
c9a869d39a352c4a5584e25b454d460acaaa147b062a35ce26267a988e20aa45 | Python | 394 | 18 | # Generated by Django 4.1.1 on 2022-11-23 12:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('celsus', '0032_uniprotrecord_genenamemap_uniprot_record'),
]
operations = [
migrations.RenameField(
model_name='uniprotrecord',
... |
f95bb6cc5dacf143d147379af733aef872418dfceb1eb0317f69278a8d9f7630 | Python | 394 | 11 | """
Model classes for neuroimaging analysis.
Provides sklearn-compatible APIs for common neuroimaging analyses.
"""
# Internal package: these imports are re-exports for the rest of nltools, not
# an advertised surface, so there is no `__all__` to mark them as used.
from .results import ContrastResult # noqa: F401
fr... |
9705c85632114dec3dfd0b5f6e0f1760802f888ccc321a404a8f2032758067c6 | Python | 395 | 25 | """
Module for abstract class `Dataset`
"""
from abc import ABC, abstractmethod
class AbstractDataset(ABC):
def __init__(self):
super().__init__()
@property
@abstractmethod
def time_dependent(self):
pass
@property
@abstractmethod
def parametric(self):
pass
... |
c516570b4296745365147ba01ac262576123b705da213e32e6c08039af76eafb | Python | 396 | 16 |
SUPPORTED_IMAGE_EXTNS = [".png", ".jpg", ".jpeg"] # Add image formats here
SUPPORTED_MODALITIES = ["image"]
DEFAULT_IMAGE_WIDTH = DEFAULT_IMAGE_HEIGHT = 256
DEFAULT_IMAGE_CHANNELS = 3
DEFAULT_VIDEO_FRAMES = 8
DEFAULT_LOG_FREQ = 500
DEFAULT_ITERATIONS = 300000
DEFAULT_EPOCHS = 300
DEFAULT_MAX_ITERATIONS = DEFAULT_MA... |
64446a556f38e9d952fbd9709048d6faf6c10f5bcc61bce0c916840d53cf25a5 | Python | 397 | 18 | # Generated by Django 4.1.1 on 2022-12-05 14:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('celsus', '0038_project_default_settings'),
]
operations = [
migrations.AlterField(
model_name='projectsettings',
nam... |
e0c956cbed7a134934178b8a81eb476450a22a357ecc29d98e30c6515aae9c4e | Python | 397 | 26 | grid_rotations_to_rotation_mat = [
(0, 0, 0),
(0, 0, 3),
(0, 0, 2),
(0, 0, 1),
(1, 3, 3),
(3, 3, 1),
(0, 1, 0),
(0, 1, 3),
(0, 1, 2),
(0, 1, 1),
(3, 1, 0),
(3, 3, 2),
(0, 2, 0),
(0, 2, 3),
(0, 2, 2),
(0, 2, 1),
(3, 1, 3),
(1, 1, 1),
(0, 3, 0),
... |
0c2ada1244c30451cfdf6ef1e27ce32d13effb247706660857177dd2d5694748 | Python | 399 | 19 | #!/usr/bin/env python3
from pathlib import Path
from snakebids.app import SnakeBidsApp
def get_parser():
"""Exposes parser for sphinx doc generation, cwd is the docs dir"""
app = SnakeBidsApp("../")
return app.parser
def main():
app = SnakeBidsApp(Path(__file__).resolve().parent.parent) # to get r... |
b22ca89437ce331cbbb6bed90f932e88c983ef5f24c959aee7d7f2fdf818283b | Python | 400 | 24 | import experiment as exp
from rl_logging import get_main_logger
log = get_main_logger()
def run():
log.info("Running experiment")
exp.run_experiment()
def stop():
log.info("Stopping experiment")
exp.stop_experiment()
def next_block():
log.info("Starting the next block")
exp.next_block()
... |
34e2d9e6598d1fb7055189ed2e3faffd4f12eb9e8681a381bd6d0f620f33d749 | Python | 401 | 16 | """
WSGI config for celsusdjango project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_... |
489fa3a045d322c7ad6ee57adc588a79fe161f03e7090fe041d5de2fb8f65487 | Python | 401 | 11 | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future_... |
7f7bcf4b80503d2a6ac514db3e419ee11ce777e2ceb0e1325a15a5fed096911a | Python | 401 | 16 | """
WSGI config for WebLabelling project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_... |
cfb4b60c83791f2fbaf9a9f280f9b9a61ea12d616a33b986bc61433209c033e7 | Python | 403 | 18 | # Generated by Django 4.1.1 on 2022-11-02 11:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('celsus', '0018_genenamemap_entry'),
]
operations = [
migrations.AlterField(
model_name='file',
name='file',
... |
618b44c58af08c6a0030ef5342f3529eea1ce84329fc604bfc4248336ab85f2f | Python | 404 | 22 | from .foundations_models import (
mace_anicc,
mace_mdp,
mace_mp,
mace_off,
mace_omol,
mace_polar,
)
from .lammps_mace import LAMMPS_MACE
from .mace import MACECalculator, MagneticMACECalculator
__all__ = [
"MACECalculator",
"MagneticMACECalculator",
"LAMMPS_MACE",
"mace_mp",
... |
b20bf1d076829eaceaa6f01af9520f5f817685f8953c71442d782cb91cfeb880 | Python | 405 | 17 | from .animals_detection import animals_detection_API
from .segmentation import (
generate_background_from_frame_stack,
generate_frame_stack,
load_custom_background,
process_frame,
to_gray_scale,
)
__all__ = [
"animals_detection_API",
"generate_background_from_frame_stack",
"generate_fra... |
fa1f8ecdc80ff00f6728b0aa2784cf37ed4a044e69df8c0b07e354621d6f29d8 | Python | 405 | 10 | from typing import List, Optional
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
def instrument_fastapi(app: FastAPI, excluded_urls: Optional[List[str]] = None) -> None:
"""Instrument FastAPI to emit OpenTelemetry spans."""
FastAPIInstrumentor.instrument_app(... |
06c5a0ac1bf9f241720574cc06c5b3121774fa49ed07a9bff7d2ff52ff3f1f5e | Python | 406 | 18 | """Interface to load from and save to python pickles."""
def dump(data, filename, **kwargs):
import pickle
from pyrates.utility import create_directory
create_directory(filename)
pickle.dump(data, open(filename, 'wb'), protocol=pickle.HIGHEST_PROTOCOL, **kwargs)
def load(filename, **kwargs):
i... |
5ca6045c1327926616baf067d19127a40325f8e0b7a0649eac44452588420e9b | Python | 407 | 14 | from __future__ import absolute_import
from pathlib import Path
from snakebids.core.construct_bids import bids
def test_bids_subj():
assert bids(root="bids", subject="001", suffix="T1w.nii.gz") == (
"bids/sub-001/sub-001_T1w.nii.gz"
)
assert bids(root=Path("bids").resolve(), subject="001", suffi... |
4b6c2a95e130ad1a21a35786592c6e2f80ce596117281da9c649ad9bf021ffae | Python | 409 | 8 | from .dataset_collector import DatasetCollector
from .datasets.elastic_block import ElasticBlockDataset
from .datasets.termal import TermalDataset
from .datasets.navier_stokes import NavierStokesDataset
from .datasets.graetz import GraetzDataset
from .datasets.unsteady_heat import UnsteadyHeatDataset
from .datasets.lid... |
5bbbeaefe39606e07464f6efff6399cec6caadd103cc90abee4b6f725f8668d9 | Python | 410 | 17 | from setuptools import find_packages
from setuptools import setup
setup(
name="predictmodel",
description="Predict using a tensorflow model on GCP.",
author="Adam Richie-Halford",
author_email="richiehalford@gmail.com",
install_requires=[
"gcsfs==2021.7.0",
"nobrainer==0.2.1",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.