sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
7d95081103893fb7e94aa8f9f6d38e5938226b82817a536c7cfb05b170a7f092 | Python | 296 | 9 | from .formatting import PackInputs
from .get_edge import GetEdgeGTFromImage
from .loading import LoadGTImageFromFile, SetInputImageAsGT
from .wrapper import TransBroadcaster
__all__ = [
'PackInputs', 'LoadGTImageFromFile', 'TransBroadcaster',
'SetInputImageAsGT', 'GetEdgeGTFromImage'
]
|
8c09547afd6b4d5a4cb0bc031fb1de79d86ac7fabf1c1625329d376986d44962 | Python | 296 | 12 | #!/usr/bin/env python3
"""Load datasets"""
from pathlib import Path
import pandas as pd
HERE = Path(__file__).parent
def snap_colors():
"""Load a list of 88 categorical colors for plotting."""
filename = HERE / "snap_colors.tsv"
return pd.read_csv(filename, sep="\t", header=None)
|
9b2bfd13c8cc496c197e0ad07e30153384ee0599f873e5dccb82203e41018945 | Python | 296 | 23 | # flake8: noqa
# __start__
# File name: sleepy_pid.py
from ray import serve
@serve.deployment
class SleepyPid:
def __init__(self):
import time
time.sleep(10)
def __call__(self) -> int:
import os
return os.getpid()
app = SleepyPid.bind()
# __end__
|
27ab23fc272f2f4e825977afa1bdebd4fad0a8a587bb5e207acbf76eda8db5ad | Python | 297 | 13 | import re
input_string = """
Base level: 42.5 | 36.8 |
Exon level: 41.2 | 65.7 |
"""
# Extract all numbers using regular expressions
numbers = re.findall(r"\d+\.\d+", input_string)
# Print the extracted numbers
for number in numbers:
print(number)
|
daffe9e877b7ec50745ad36fe57eb12aab719ab6a92b54a4830dcc273918696b | Python | 297 | 12 | _base_ = ['./atss_r50_fpn_1x_rtts-coco_lr002.py']
# model settings
model = dict(
neck=dict(
type='lqit.DFFPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_input',
shape_level=2,
num_outs=5))
|
7af5c3a8b00452956907eb4723afe7c042b34db784608e5e17e60763b82cf840 | Python | 298 | 8 | import imageio
import glob
import os
image_path = '../Saved/Training_Image/5_31'
image_list = sorted(glob.glob(image_path+'/*.png') , key=os.path.getmtime)
images = [imageio.imread(filename) for filename in image_list]
imageio.mimsave(os.path.join(image_path, '403baseline.gif'), images, fps=1.5)
|
cb9346cbf3f36172f3a861d6816e9634243b579b827d506d171412d064e90c18 | Python | 299 | 10 | import numpy as np
import torch
def init_lecun_normal(tensor, scale=1.0):
"""Initializes the tensor with LeCunNormal."""
fan_in = torch.nn.init._calculate_correct_fan(tensor, "fan_in")
std = scale * np.sqrt(1.0 / fan_in)
with torch.no_grad():
return tensor.normal_(0, std)
|
574a011907da1b3ff0f14c2e622c219e36890d70453a734f0cf00c79f4cee1b5 | Python | 300 | 11 |
class RandomAgent(object):
"""The world's simplest agent!"""
def __init__(self, action_space):
self.action_space = action_space
def act(self, observation, reward, done):
# Update agent from rewards
# Samples the action
return self.action_space.sample()
|
fe7a5a0b9561e61911203b9064292aa0e38d4c958594c8a3e9e5154de084c6c1 | Python | 300 | 7 | import os
import sys
# train SEG model
os.system('python train_SEG_model.py --img_h 256 --img_w 256 --GPU 0 --f_maps 16 \
--normalize_factor 1000 --input_nc 1 --output_nc 1 --n_epochs 100 --lr 0.0001 --frame_num 64 \
--train_datasets_size 500 --datasets_folder test1_mov_wo_bg_100_64_498_10_2_6000') |
9eee245abfa9a228d9ff9922bccb5c4c7d270b61add9361dbd226eb04e041620 | Python | 301 | 13 | from .features import (
AutoFeatClassification,
AutoFeatRegression,
AutoSpectralIndicesClassification,
AutoSpectralIndicesRegression,
)
__all__ = [
"AutoFeatClassification",
"AutoFeatRegression",
"AutoSpectralIndicesClassification",
"AutoSpectralIndicesRegression",
]
|
4657175f5c39209568c8605e43fc950e61b348f10c5cf55b5e4273204cda9b67 | Python | 302 | 7 | """Entry point of the bundled CandyCrunch app (built with packaging/candycrunch.spec)"""
import multiprocessing
if __name__ == '__main__':
# Turns a worker process start into the worker instead of a second window
multiprocessing.freeze_support()
from candycrunch.gui import main
main()
|
6d2aae27288fa24e794afd0ab322c46087a9b060efc4663c8bb1ea1dddba371c | Python | 302 | 10 | import numpy as np
def log_transform(ad, ps=0.1):
"""Compute log transformation of AnnData data in place.
:param ad: anndata.AnnData object to be normalized
:param ps: (float) pseudo-count for log transformation to avoid log(0) errors
"""
ad.X = np.log2(ad.X + ps) - np.log2(ps)
|
d66969993e52016dc7947ddc05fe3c801d83c7a359de7c1025b5774cb9c6982d | Python | 302 | 14 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 13 16:13:42 2022
@author: joern
"""
import os
os.chdir("/home/joern/Aktuell/PaclitaxelPainLipidomics/08AnalyseProgramme/PaclitaxelNeuropathyProject/Python")
#import paclitaxel_exploreTukey
import paclitaxel_day12_explanation_ML
|
20e24afac12903f7414621f9cb5b31894cb27d3e88125f7eae480ad8af2e5586 | Python | 304 | 16 | """Compute statistical description of datasets."""
from typing import Any
from multimethod import multimethod
from data_profiling.config import Settings
@multimethod
def get_time_index_description(
config: Settings,
df: Any,
table_stats: dict,
) -> dict:
raise NotImplementedError()
|
cd331287daee9bddc2722ab0d81e34a62ba559f43b1a244695dbccc021325108 | Python | 304 | 9 | #Test CHM height rules
import pandas as pd
from src import CHM
def test_height_rules():
df = pd.DataFrame({"CHM_height":[11,20,5, 0.5, 10, None],"height":[6, 19, 7, 5, None, 10]})
df = CHM.height_rules(df, min_CHM_height=1, max_CHM_diff=4, CHM_height_limit=8)
assert df.shape[0] == 3
|
447dcc4734544527b7265e5d44740becd5ab58c456fd78dc8ecbb8ebb65dad77 | Python | 305 | 13 | # __serve_hook_start__
"""LLMServer subclass for ``LLMConfig.server_cls``: importing it registers the plugin."""
from ray.llm._internal.serve.core.server.llm_server import LLMServer
from qwen3_reward_plugin import register
register()
class RewardModelServer(LLMServer):
pass
# __serve_hook_end__
|
4f5f1487b076d3cf61920a5e969d1de718e9bfe893016e7abc4340f50b20df20 | Python | 305 | 21 | from .global_defs import (
set_random_seed,
set_default_dtype,
set_params_dtype,
get_default_dtype,
get_params_dtype,
get_subkeys,
get_sites,
get_lattice,
)
from . import (
sites,
symmetry,
operator,
state,
nn,
sampler,
optimizer,
utils,
)
|
771ecdd3873dfe26d2e222d9218ea62c7bf6d04b0e584a79bd92af8c0931b704 | Python | 305 | 6 | from .dvs_layer import DVSLayer
from .dynapcnn_layer import DynapcnnLayer
from .dynapcnn_network import DynapcnnCompatibleNetwork, DynapcnnNetwork
from .dynapcnn_visualizer import DynapcnnVisualizer
from .dynapcnnnetwork_module import DynapcnnNetworkModule
from .nir_graph_extractor import GraphExtractor
|
03b11e797dd1710187870b17daef304bd1b866337c8f23fff83e8b90f5b1729f | Python | 306 | 11 | from siapy.entities import Pixels, Shape
# Create a point
point = Shape.from_point(10, 20)
# Create a polygon from pixels
pixels = Pixels.from_iterable([(0, 0), (10, 0), (10, 10), (0, 10)])
polygon = Shape.from_polygon(pixels)
# Load from shapefile
shape = Shape.open_shapefile("path/to/shapefile.shp")
|
fc6068355c5be85cd4c1d134536946fcde546fb5418603840140cef9eccbc688 | Python | 306 | 19 | from . import config
from . import core
from . import presults
from . import io
from . import preprocess
from . import utils
from . import plot
from .version import __version__
__all__ = [
"config",
"core",
"presults",
"io",
"preprocess",
"utils",
"plot",
"__version__",
]
|
2696da893ed317a166f70ce827aef5524b171c548ce0924a6f3637bacfc77a99 | Python | 307 | 8 | import boto3
def get_s3_region(bucket: str) -> str:
"""Get the region of the S3 bucket"""
s3 = boto3.client("s3")
response = s3.get_bucket_location(Bucket=bucket)
# AWS returns None for us-east-1, otherwise returns the region name
return response["LocationConstraint"] or "us-east-1"
|
5b9377c6438809ffc4ef5f12b532956f87b54a8e7042a59defbc443971c25bdb | Python | 307 | 21 | import ray
@ray.remote
def py_return_input(v):
return v
@ray.remote
def py_return_val():
return 42
@ray.remote
class Counter(object):
def __init__(self, value):
self.value = int(value)
def increase(self, delta):
self.value += int(delta)
return str(self.value)
|
77f2d7e95b486eaabfb79fd89ae72e1133f61682ea401470bff1cf2b0e7d7a6e | Python | 307 | 16 | def test_forward():
import torch
from sinabs.layers import Sig2SpikeLayer
channels = 4
tw = 5
lyr = Sig2SpikeLayer(
channels_in=channels,
tw=tw,
)
sig = torch.tensor([[1.0, 0.5, 0.25]] * channels)
spk = lyr(sig)
assert spk.shape == (tw * 3, channels)
|
c517d577e47017b87db1b93f8a5dc74cd4356931075a1e2d5f65dedd5edcf256 | Python | 307 | 9 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def remove_stop_words(text):
stop_words = set(stopwords.words('english'))
text_tokens = word_tokenize(text)
filtered_text = [w for w in text_tokens if not w.lower() in stop_words]
return " ".join(filtered_text)
|
d95d62718fc4c10ed9ff0fd3773cd62bc1132421491b160a0f88dae678addd3e | Python | 308 | 11 | from bazel.gen_extract import gen_extract
if __name__ == "__main__":
gen_extract(
["java/proto_files.zip"],
clear_dir_first=[
"runtime/src/main/java/io/ray/runtime/generated",
"serve/src/main/java/io/ray/serve/generated",
],
sub_dir="java",
)
|
12c255a1449809f2d52948284d45d3a8a6275e779b84b9225e5b493b4d2a85f0 | Python | 309 | 10 | from pathlib import Path
from . import utils
def download(path: Path):
url = "https://irefindex.vib.be/download/irefindex/data/archive/release_18.0/psi_mitab/MITAB2.6/All.mitab.06-11-2021.txt.zip"
utils.download_file(
url, path / "All.mitab.06-11-2021.txt.zip", "Downloading iRefWeb"
)
|
4851132080343d461dc4cb48797212ec86985e9cc5be3750165b37e180409bd6 | Python | 309 | 12 | from ray.dashboard.modules.metrics.dashboards.common import DashboardConfig
def get_serve_dashboard_config() -> DashboardConfig:
from ray.dashboard.modules.metrics.dashboards.serve_dashboard_panels import (
serve_dashboard_config,
)
return serve_dashboard_config
# Anyscale overrides
|
5de3016b1b530062b1c46c91e61e207bb25bd53b38b4a00adacb44210505a26e | Python | 309 | 12 | __version__ = "3.2.0"
__changelog__ = """
Version 1.0.1:
- Fixed import errors caused by missing submodules in PyPI build.
Version 1.0.2:
- Remove ylim when plot for better visualtion.
"""
from modnn.Config import get_config, describe
from modnn.utils import Mod
__all__ = ["get_config", "describe", "Mod"]
|
bea1674dade34cd67219451c117a13bae4862e87c1f4bf592e3e6e6b70381b21 | Python | 309 | 12 | import os
import sys
os.system('python main_RSM.py \
--RMBG_model_folder arr_202110011541 \
--RMBG_model_name E_30_Iter_4009 \
--SEG_model_folder TS3DUnetFFD_20211129-1355 \
--SEG_model_name seg_30 \
--test_datasize 20000 \
--datasets_path datasets \
--datasets_folder Simulated_wide_field_data1 \
--GPU 0')
|
0200f4f7fd958c5bee0b4f66a807f6b4f88d74010be769bddbcec650272ff76f | Python | 310 | 21 | from abc import ABC, abstractmethod
class NetworkVisualization(ABC):
def __init__(self):
pass
@abstractmethod
def init_figure(self):
pass
@abstractmethod
def update_figure(self):
pass
@abstractmethod
def figure_properties(self):
pass
|
e783af1cc514ae302265651bd9b531ef6a1ada48d8109b7ad60961511d7a6cc9 | Python | 310 | 12 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use("Agg")
from model import SelfSustainedPushPull
from experiments import create_experiments
import mozaik
from mozaik.controller import run_workflow
data_store, model = run_workflow("LSV1M", SelfSustainedPushPull, create_experiments)
data_store.save()
|
7075e622f57d7d8661a8a5554f30f61756ba29092524f813803163373204208f | Python | 311 | 10 | from .quantize import Quantize, StochasticRounding
from .reset_mechanism import MembraneReset, MembraneSubtract
from .spike_generation import MaxSpike, MultiSpike, SingleSpike
from .surrogate_gradient_fn import (
Gaussian,
Heaviside,
MultiGaussian,
PeriodicExponential,
SingleExponential,
)
|
60ae4ad8cc7a41943f876903703b4d84c9752f202011d1063841758c32f6e03f | Python | 312 | 19 | import ray
@ray.remote
class MyActor:
def __init__(self, index):
self.index = index
def foo(self):
print("hello there")
def __repr__(self):
return f"MyActor(index={self.index})"
a = MyActor.remote(1)
b = MyActor.remote(2)
ray.get(a.foo.remote())
ray.get(b.foo.remote())
|
ad7e93db47ea2b1c16f6f5b7867ecad9c7e7900cf45039b1dadd119791abd51d | Python | 312 | 11 | from ipywidgets import widgets
from data_profiling.report.presentation.core.html import HTML
class WidgetHTML(HTML):
def render(self) -> widgets.HTML:
if type(self.content["html"]) != str:
return self.content["html"]
else:
return widgets.HTML(self.content["html"])
|
b769ddb2700d92f36fe99da3b494974d4279ba518fbcc8df9870818bc23a806d | Python | 312 | 11 | import numpy as np
class LogTransform:
def __init__(self, bias, min_x=0):
self.bias, self.min_x = bias, min_x
def trf(self, x):
return np.log2(x + self.bias) - np.log2(self.min_x + self.bias)
def inv(self, x):
return (2 ** (x + np.log2(self.min_x + self.bias))) - self.bias |
c26e2ba92ed6234cbf424c82118df08252258cc3f8ae767e4104f307058e73b1 | Python | 312 | 10 | import numpy as np
class DataLoader():
def __init__(self):
a = None
def load_data(self, imgs_lr, imgs_hr, start, len, batch_size=1):
start = np.random.randint(start*batch_size, len-batch_size-1)
return imgs_hr[start:start+batch_size], imgs_lr[start:start+batch_size]
|
f4b4a907032c4798d197317c2727fcee4f4826ade3ba7b0a623113dc995935c6 | Python | 314 | 16 | import glob
import os
import shutil
def main():
if os.path.exists('docs/images'):
shutil.rmtree('docs/images')
if os.path.exists('docs/modules.rst'):
os.remove('docs/modules.rst')
for f in glob.glob('docs/hic3defdr*.rst'):
os.remove(f)
if __name__ == '__main__':
main()
|
3d16961f23084ec4d9c363d5beea95d160e06241ab0eba2afaa3d96defb40d64 | Python | 315 | 12 | class RefPhi:
def __init__(self, phi, pseudo_min):
self.phi = phi
self.pseudo_min = pseudo_min
class RefTumor():
def __init__(self, psi_mal, psi_env, key, pseudo_min):
self.psi_mal = psi_mal
self.psi_env = psi_env
self.key = key
self.pseudo_min = pseudo_min |
4a4238f0226e45907a2298c1f9fdc41962e41e4fc5bc90180fd771a211c3be71 | Python | 315 | 9 | """SiaPy: A Python library for spectral image analysis.
SiaPy provides comprehensive tools for working with hyperspectral and multispectral images,
including data processing, feature extraction, visualization, and machine learning capabilities.
"""
from .__version__ import __version__
__all__ = ["__version__"]
|
b073e3ec8cd3fd7b96eccd6bd7faaef61123a1e91c5fd4f1802b662965792c45 | Python | 315 | 13 | import pytest
import torch
from flyvis.task.objectives import epe, l2norm
@pytest.mark.parametrize("objective", [l2norm, epe])
def test_objective(objective):
a = torch.ones(4, 3, 2, 5).random_(to=5)
b = torch.ones(4, 3, 2, 5).random_(to=5)
assert objective(a, b) > 0
assert objective(a, a) == 0
|
252213b77195aacfa126b42c357f462b03a89885713f0eef36b3a9b2e388127a | Python | 316 | 5 | from collections import namedtuple
GridSearchParams = namedtuple('GridSearchParams', ['lambda_start', 'lambda_end', 'prior_weight', 'max_iter'])
GridSearchReconstructions = namedtuple('GridSearchReconstructions',
['ground_truth', 'reconstructions', 'mse', 'ssim', 'ms_ssim'])
|
834828ab8c1108b26e06bd3b8c564187db40be9b14dbb2df6e4344ef4cd56042 | Python | 317 | 23 | # __start__
from ray import serve
import time
import requests
@serve.deployment
def sleeper():
time.sleep(1)
s = sleeper.bind()
serve.run(s)
while True:
requests.get("http://localhost:8000/")
# __end__
break
response = requests.get("http://localhost:8000/")
assert response.status_code == 200
|
d5ecedb5b3c9c7d90b2ee4a477e89d865c56f6a9fa1767ed1d61032e4b59ba73 | Python | 317 | 15 | import numpy as np
import torch
def ess(weight):
# (*bdims, weight) -> (*bdims)
return 1 / (weight**2).sum(dim=-1)
def softplus(t):
return torch.log(1. + torch.exp(t))
def softplus_inv(t):
return torch.log(-1. + torch.exp(t))
def softplus_grad(t):
return torch.exp(t) / (1. + torch.exp(t)) |
ff277e6caf545083a0587c96fb12c3106daff0832e4789c0b6faffce0d562f95 | Python | 318 | 13 | # data preprocess
data_path = 'dataset'
train_file = 'train_pinggu.csv'
valid_file = 'test_pinggu.csv'
test_file = 'test_pinggu.csv'
fix_length = 256
batch_size = 256
# data label list
label_list = ['低危', '中危', '高危', '超危']
class_number = len(label_list)
# train details
epochs = 30
learning_rate = 1e-3 |
d77525b62cc2d2f064d627fa11f19a2dfba7c96c32ef3b4bd8dbd96efd8986cf | Python | 319 | 10 | """Test registration"""
import logging
from .application_utils_tests import ApplicationUtilsTests
from .fp_tests import LEFFingerprintTests
from .model_tests import ModelTests
from .utils_tests import UtilsTests
from .main_tests import MainTests
logging.disable(logging.CRITICAL) # suppress noise form failure tests
|
e8dc6d7cfe7f0bebf1eba132face5735a7d67c39f11860163761ad5989b2a844 | Python | 319 | 13 | import pathlib
import pytest
from stl import mesh
FILES_PATH = pathlib.Path(__file__).parent / 'stl_tests'
@pytest.mark.parametrize('line_ending', ['dos', 'unix'])
def test_line_endings(line_ending, speedups):
filename = FILES_PATH / (f'{line_ending}.stl')
mesh.Mesh.from_file(filename, speedups=speedups)
|
461da4d236152b7e2577b968a7edf0c14487fa256aed23c824472db0391595d2 | Python | 321 | 7 | __projectname__ = 'ngs_mapper'
__version__ = '1.5.0'
__authors__ = 'Tyghe Vallard, Melanie Melendrez'
__authoremails__ = 'vallardt@gmail.com, mmelendrez@gmail.com'
__description__ = 'Pipeline that combines sff and fastq from multiple platforms'
__license__ = ''
__url__ = 'https://github.com/VDBWRAIR/' + __projectname__... |
b889ada215dbc827760ab1cdcd56915cb5647474da0eaba1d939cc4be26fd5bb | Python | 321 | 17 | import pickle
from architecture import all_archs
def light_read(dname):
f = open("light/{}.bench".format(dname), "rb")
bench = pickle.load(f)
f.close()
return bench
def read(name):
f = open(name, "rb")
bench = pickle.load(f)
f.close()
return bench
if __name__ == "__main__":
read()... |
26bdebaaa86f8fb9e4c4a30747f384cac0ce6fe9d5c29c471db1299861e6f26b | Python | 322 | 10 | """single-cell decorrelated module networks"""
from .modules import modules
from .graph import gene_graph, adjacency_matrix
from .plotting import plot_genes, plot_umap_grid, plot_svd_corr
from .data import snap_colors
from .utils import (
recipe_preprocess, recipe_annotate, recipe_full,
get_goterms, vcorrcoef
)... |
599db01b7ff090807d48d70fe1f47b1bcb73cc9455450f979d4f7ae5550d7262 | Python | 322 | 9 | from ._network import learn_intercellular_flows
from ._validate_network import apply_biological_flow, filter_low_confidence_edges, construct_intercellular_flow_network
__all__ = [
"learn_intercellular_flows",
"apply_biological_flow",
"filter_low_confidence_edges",
"construct_intercellular_flow_network"... |
776217e82fddd32b6373b9c08a4721956943f6caed8689d1518f4a4aafb7f5ac | Python | 322 | 12 | import nibabel as nib
import numpy as np
import scipy.io as sio
import os
import numpy as np
path = os.path.join('C:/Users/ASUS/XXX.mat')
mat = sio.loadmat(path)
gray = np.squeeze(mat['gray'])
new_image = nib.Nifti1Image(gray,np.eye(4))
save_path = os.path.join('C:/Users/ASUS/XXX.nii.gz')
nib.save(new_image,save_path... |
f749e0fe74eaee8f71b85f6fe898c34f8d7d549b8402dc36ea6642c155bde9e5 | Python | 322 | 13 | import torch
def orthogonal_inverse(mat: torch.Tensor) -> torch.Tensor:
"""
Creates the inverse matrix of an orthogonal matrix
Its basically just the transposed matrix :D
Args:
mat: Orthogonal matrix
Return:
Inverse of the input matrix
"""
return torch.transpose(mat, -1, -2... |
008e5929fd806cb3710fc957c8b0e9299cb3799da87c5b5d2b565616afde7357 | Python | 323 | 14 | """Compatibility module.
It can be necessary to load files generated by previous versions of cloudpickle
that rely on symbols being defined under the `cloudpickle.cloudpickle_fast`
namespace.
See: tests/test_backward_compat.py
"""
from . import cloudpickle
def __getattr__(name):
return getattr(cloudpickle, nam... |
3fcbd4764c7fb791d3c52cf3d89281c8bff5e7afd34963a0cdc2f003b48ae4af | Python | 324 | 15 | """
Utility functions.
"""
def load_tf_names(path):
"""
:param path: the path of the transcription factor list file.
:return: a list of transcription factor names read from the file.
"""
with open(path) as file:
tfs_in_file = [line.strip() for line in file.readlines()]
return tfs_in_... |
5f83779d2e56d5e92926e2db36d18d348ef659072796971cab9c10a15ac5334e | Python | 324 | 9 | from ._QC import sc_QC
from ._api import *
from ._base import *
from ._networks import *
__all__ = ["scTenifoldNet", "scTenifoldKnk", "sc_QC", "cal_pcNet", "make_networks", "cal_pcNet",
"cal_pc_coefs", "manifold_alignment", "d_regulation", "strict_direction",
"compare_networks", "virtual_knockou... |
9ad3bbedbc0cc934a171985cb95c3f51992029cc49da9f5c3056cc8ce8692e0d | Python | 324 | 11 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Analog Optimizers."""
# Convenience imports for easier access to the classes.
from aihwkit.optim.analog_optimizer import AnalogOptimizer, AnalogSGD, AnalogA... |
bcea408d4eaf92f456d62e20d64bff68b893b21392f02d3b543675bb30930528 | Python | 324 | 11 | '''
let the neural network loop over different context to compute likelihood
use the contextual bandit task
'''
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from task import ContextualBandit
from model import CRPLSTM
sns.set(style='white', palette='colorblind', context='talk')
np.random.seed... |
ea355443100e788434a5f1ce6b4d77540f404ded8a39d8b5652b6a800a869589 | Python | 324 | 12 | from typing import Dict, List, Tuple
import numpy as np
from .node import NIRNode
# Nodes are uniquely named computational units
Nodes = Dict[str, "NIRNode"]
# Edges map one node id to another via the identity
Edges = List[Tuple[str, str]]
# Types is a dict mapping strings to tensor shapes
Types = Dict[str, np.ndarr... |
856247fbbc8b665437119b4c56845cf5fdf902950cc3570671117da74918788f | Python | 325 | 16 | '''
Removing phase images of timeseries to save space
'''
import subprocess
import glob
FOLDER = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
files = sorted(glob.glob(f'{FOLDER}/sub-*/ses-*/func/*_part-phase*'))
for file in files:
command = f'rm {file}'
subprocess.run(command, shell = T... |
5a77901ff0d703486a80eda2f43c7bd850d08fa04c0bd78a3d4819418716754f | Python | 327 | 14 | """
AVA package for training a VAE
Contains
--------
`ava.models.vae`
Defines the variational autoencoder (VAE).
`ava.models.vae_dataset`
Feeds syllable data to the VAE.
`ava.models.window_vae_dataset`
Feeds random data to the (shotgun) VAE.
`ava.models.utils`
Useful functions related to the `ava.models` subpackag... |
60c89e7abe5cf3a90f0f9d14bc897338545b0a723caeda8fd95c2d495a6b0359 | Python | 327 | 19 | '''
Find the number of individual runs per participant
'''
import glob
ROOT = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti'
SUBS = ['sub-05', 'sub-06', 'sub-07', 'sub-08', 'sub-09']
dict = {}
for sub in SUBS:
runs = glob.glob(f'{ROOT}/{sub}/ses-*/func/*cbv.nii.gz')
dict[sub] = len(runs)... |
a9e193c7e4606afacd013efe73d57f74e9a936af9ad22a835a0210943895dea4 | Python | 327 | 11 | #!/usr/bin/env python
# just print current value of __version__ in __init__.py
import os
from os.path import join, basename, dirname
THIS = dirname(__file__)
TRAVIS_REPO_SLUG = os.environ['TRAVIS_REPO_SLUG']
project_name = basename(TRAVIS_REPO_SLUG)
execfile(join(THIS, '../', project_name, '__init__.py'))
print __ver... |
8f284f346e34846d16877899d1e032d9eef6cfb88a1ff189fedac132d891ff8c | Python | 329 | 10 | from .data import DataTracer
from .array import is_sharded_array, to_array_shard, to_array_replicate, array_extend
from .tree import (
tree_fully_flatten,
filter_shard,
filter_replicate,
tree_split_cpl,
tree_combine_cpl,
)
from .spins import ints_to_array, array_to_ints, neel, stripe, Sqz_factor, ra... |
d5f0b482ade6422345a6ed67f2641738b0a1f18e7cdc410fe57efaef3e9e5714 | Python | 329 | 11 | import setuptools
setuptools.setup(
name="drprobe_interface",
version='0.1.25',
url='https://github.com/FWin22/drprobe_interface',
packages=setuptools.find_packages(),
author='Florian Winkler',
author_email='flowinkler22@gmail.com',
description='Python interface to the Dr Probe software pac... |
1cbd2b4887d53746cfe080be8ea89bf6444923484a7ec47672862928e517431e | Python | 330 | 12 | import cupy as cp
import torch
from torch.utils.dlpack import to_dlpack, from_dlpack
BLOCKSIZE = 1024
BLOCKDIM = lambda x : (x - 1) // BLOCKSIZE + 1
def cupy_to_torch(x : cp.ndarray) -> torch.Tensor:
return from_dlpack(x.toDlpack())
def torch_to_cupy(x : torch.Tensor) -> cp.ndarray:
return cp.fromDlpack(to_d... |
c798063668ce1e5d99787ceb784d9e1c3682fa0d4858e97c3516d4104755b66e | Python | 330 | 14 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
"""For backwards compatibility"""
from __future__ import annotations
if __name__ == "__main__":
from fairchem.core._cli import main
... |
148233d0ab5fdeb8f2b7f01f6f40177354fa1a0214d35c35d8558199407b0546 | Python | 331 | 11 | # trying to import all current samri modules
from samri import utilities
from samri.analysis import *
from samri.optimization import *
from samri.pipelines import *
from samri.plotting import connectivity,maps,qc,summary,timeseries,utilities
from samri.report import *
from samri import utilities
def test_placeholder()... |
be69f53d224eccca0161c8b365f7f25f288dfad10c999b24345d45e2335c54ff | Python | 331 | 14 | import pickle
from .base_vocab import BaseVocab
class Vocab(BaseVocab):
@staticmethod
def load_vocab(vocab_path: str) -> "Vocab":
with open(vocab_path, "rb") as f:
return pickle.load(f)
def save_vocab(self, vocab_path):
with open(vocab_path, "wb") as f:
pickle.dum... |
adba9bced6ffe10b52f05e76ca9037497cd650cfd68499574e36d76140b2c86c | Python | 332 | 8 | import sys
sys.path.append("/home/b.weinstein/DeepTreeAttention")
from src import start_cluster
from src import multonomial
client = start_cluster.start(cpus=150)
for x in range(100):
multonomial.wrapper(iteration=x, client=client, savedir="/blue/ewhite/b.weinstein/DeepTreeAttention/results/06ee8e987b014a4d9b6b824... |
b6b0f82c45899da2c324ec802ce7ab9dc5cbae0236e7d7d86ec27619ec6a0cb0 | Python | 332 | 11 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""RPU simulator bindings."""
# This import is required in order to load the `torch` shared libraries, which
# the simulator shared library is linked against.
i... |
f99c85dc5f1f32cf04ed375487b48b84c88d5d14195ca1f3d9993333d28f9e95 | Python | 332 | 10 | from .io import *
from .utils import *
from .stats import *
from .PCATransformer import PCATransformer
from .DataLoader import DataLoader
from .EventLabel import EventLabel
from .TrainValidSplit import TrainValidSplit
from .HumanBondaries import HumanBondaries
from .Parameters import Parameters
from ._METAVideos import... |
6d60a817652a96cfbd162e430920d2709342dfbdf85dd63be75624879f630774 | Python | 333 | 14 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import annotations
from fairchem.core.units.mlip_unit.api.inference import (
InferenceSettings,
)
__all__ = ["Inferen... |
78f65478417d43010d20d2dee6ee541132b03cf999dafa29b370dca6006c519f | Python | 333 | 8 | #!/usr/bin/env python
from .base.movies import movie, load, load_movie_chain
from .base.timeseries import concatenate
from .cluster import start_server, stop_server
from .mmapping import load_memmap, save_memmap, save_memmap_each, save_memmap_join
from .summary_images import local_correlations
#from .source_extraction... |
b6e80a26c1266d213289ffcfcc93e9e846c5797952f0fd21f798dc26a1962a25 | Python | 333 | 11 | __author__ = "Kuan-Hao Chao"
__contact__ = "kuanhao.chao@gmail.com"
__copyright__ = "Copyright 2023, Kuan-Hao Chao"
__credits__ = ["Kuan-Hao Chao"]
__date__ = "2023/07/26"
__deprecated__ = False
__email__ = "kuanhao.chao@gmail.com"
__license__ = "MIT"
__maintainer__ = "developer"
__status__ = "Kuan-Hao Chao"
__version... |
1079b6711ccba6b284aa6cccca66adcf91f0c7d6b1418859c7778819a2255645 | Python | 334 | 15 | from functools import wraps
from typing import Any, Callable
from tqdm import tqdm
def progress(fn: Callable, bar: tqdm, message: str) -> Callable:
@wraps(fn)
def inner(*args, **kwargs) -> Any:
bar.set_postfix_str(message)
ret = fn(*args, **kwargs)
bar.update()
return ret
... |
3bf5150ecc5070674cb45cd6729c99ce93e3a6c701168dad3b76a3535e35ae98 | Python | 334 | 13 | """
Main init for the AP-Net package
"""
__version__ = "0.0.1"
__author__ = "Zachary L. Glick"
__credits__ = "Georgia Institute of Technology"
from .util import load_dimer_dataset, load_monomer_dataset
from .atom_model import AtomModel
from .pair_model import PairModel
from .bms_functions import predict_sapt, predic... |
c68ce084eeaf4db06d732de885642740ec55bd18ebb025253a224d15573e84e5 | Python | 334 | 10 | __version__ = "0.2.0"
try:
from .colorization import colorize, colorize_mutiple_runs, colorize_mutiple_slices
except ImportError as e:
raise ImportError(
f"{e}\n\n"
"The 'spaco' module requires additional packages. Please install them with:\n\n"
" pip install colormath pyciede2000\n"... |
b51a152f23314f7e2a9939b98a311404c34c35240f86fe1c685e8f948a2b914e | Python | 335 | 9 | from .detector_with_enhance_head import DetectorWithEnhanceHead
from .detector_with_enhance_model import DetectorWithEnhanceModel
from .edffnet import EDFFNet
from .multi_input_wrapper import MultiInputDetectorWrapper
__all__ = [
'MultiInputDetectorWrapper', 'EDFFNet', 'DetectorWithEnhanceModel',
'DetectorWith... |
b06cb24c1d3d3c7805da7d10f3dacbdbc3137b580acbb7113b86485cab5078cb | Python | 336 | 13 | """Plotting functions."""
# -- Set default matplotlib configuration
from importlib.resources import files
import matplotlib
import matplotlib.pyplot as plt
matplotlibrc_path = files("flyvis.analysis.visualization").joinpath("matplotlibrc")
matplotlib.rc_file(matplotlibrc_path)
plt.set_loglevel(level="warning")
del ... |
01099364de3e4f48d0b62bec71c03d6d9c8d58c27923172d1ce4182a91dd4caa | Python | 337 | 11 | """
Scores HTML renderer class
"""
from data_profiling.report.presentation.core.scores import Scores
from data_profiling.report.presentation.flavours.html import templates
# create the logic for this one
class HTMLScores(Scores):
def render(self) -> str:
return templates.template("scores.html").render... |
7ea286097373420e40155c5a94733b238f6407fe286202f56fd20e36782341c7 | Python | 337 | 7 | # NOTE: We provide these as aliases to maintain compatibility with older version
# of Arrow `PyExtensionType` that relies on picked class references that
# reference `ray.air.util.{tensor|object}_extensions.arrow.*` classes
from ray.data._internal.object_extensions.arrow import (
ArrowPythonObjectType,... |
38e410f75894915445947f776567feb1be7a9142507ad5764e20a797dc278584 | Python | 338 | 11 | # query_manager.py
import os
class QueryManager:
@staticmethod
def validate_query(query):
if not query or len(query.strip()) < 3:
return False, "Query must be at least 3 characters long"
if len(query) > 1000:
return False, "Query must be less than 1000 characters"
... |
a2c19e04902efbbb6f05f8d96fb652e14e70567e31706967504331eefcbcb823 | Python | 338 | 12 | import logging
from agent.classifiers.utils.models_cache_mgmt import refresh_cache
from agent.data.entities.config import ROOT_LOGGER_ID
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logger = logging.getLogger(ROOT_LOGGER_ID)
logger.setLevel(logging.INFO)
if __name__ == "__main__":
... |
f8fad6ff46ef9e331aa242ca1c8db063cacf04ed5bfe21f9fa52717d5a436804 | Python | 338 | 12 | import pylab
import pickle
def visualize_retinal_cache(data_store,which):
f = open('./retinal_cache/' + str(which) + '.st','r')
cached_stimulus = pickle.load(f1)
z = pickle.load(f)
pos = data_store.get_neuron_positions()['X_ON']
pylab.figure()
pylab.scatter(pos[0],pos[1],color=cach... |
0836e7b9520b95372c690ad31e02d3cacfc12f1c132ee95682e010fc1aba0cbc | Python | 339 | 13 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Conversion-related Exceptions."""
from aihwkit.exceptions import AihwkitException
class ConversionError(AihwkitException):
"""Errors related to Experim... |
503a71c6c600fc11ec25ebd7a07c9c154e6e8b35e9d840074dd4f61306d5f4a3 | Python | 339 | 10 | from mne.fixes import BaseEstimator
def repr_enhanced(self):
from io import StringIO
from pprint import pprint
text = StringIO()
pprint(self.get_params(deep=False), text)
text.seek(0)
class_name = self.__class__.__name__
return '%s(%s)' % (class_name, text.read().strip())
BaseEstimator.__rep... |
a290521995f23e48d98be1bd92764a9b9861109aa3b088cf9e2f614f141200bc | Python | 341 | 23 | """
A dummy ray driver script that executes in subprocess.
Checks that job manager's environment variable is different.
"""
import os
import ray
def run():
ray.init()
@ray.remote
def foo():
print("worker", os.nice(0))
ray.get(foo.remote())
if __name__ == "__main__":
print("driver", o... |
caa3a4634e225278e3b39e06b1719c5aa3664a58f06d5cc4fab4694db9c6afbc | Python | 342 | 11 | from setuptools import setup
setup(name='pyCAP',
version='0.0',
description='CAP_analysis_toolbox_in_python',
url='https://bitbucket.org/oriadev/time-analytics/src/main/cap_python/',
author='Kangjoo Lee',
author_email='kangjoo.lee@yale.edu',
license='MIT',
packages=['pyCAP'],
... |
d9d83788b1e82900737b193b7d8e1300d9bc88c30711d3eef2a8631d50c30911 | Python | 342 | 17 | import ray
from ray.util import ActorPool
@ray.remote
class Actor:
def double(self, n):
return n * 2
a1, a2 = Actor.remote(), Actor.remote()
pool = ActorPool([a1, a2])
# pool.map(..) returns a Python generator object ActorPool.map
gen = pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4])
print(list... |
1b45aded2996cc309b5e6a7a3231f795cd16883f10db9c25ec911d3806405a15 | Python | 343 | 7 | # Prefix for the node id resource that is automatically added to each node.
# For example, a node may have id `node:172.23.42.1`.
NODE_ID_PREFIX = "node:"
# The system resource that head node has.
HEAD_NODE_RESOURCE_NAME = NODE_ID_PREFIX + "__internal_head__"
RAY_WARN_BLOCKING_GET_INSIDE_ASYNC_ENV_VAR = "RAY_WARN_BLOC... |
339772247abf6d240a4ac2ebfb94652890d7e1a725a2ee73e57d3228d295d13d | Python | 343 | 14 | from typing import Any, Dict, Optional, Sequence, Tuple, TypeVar
from multimethod import multimethod
from data_profiling.config import Settings
T = TypeVar("T")
@multimethod
def get_duplicates(
config: Settings, df: T, supported_columns: Sequence
) -> Tuple[Dict[str, Any], Optional[T]]:
raise ... |
4512c8e11918288f49884df69cc163e131d0440a830fd07cca05044ce3be2732 | Python | 343 | 12 | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(name='swin_window_process',
ext_modules=[
CUDAExtension('swin_window_process', [
'swin_window_process.cpp',
'swin_window_process_kernel.cu',
])
],
cmdclass={'build... |
d92c90521fc63980ea7ac7926c9ffb78ab2db0cb21cca7a9d7d3be48dfc9ef16 | Python | 343 | 16 | from fire import Fire
from .helpers import (
categorical_crossval_,
deploy_categorical_model_,
train_categorical_model_,
)
if __name__ == "__main__":
Fire(
{
"train": train_categorical_model_,
"deploy": deploy_categorical_model_,
"crossval": categorical_cros... |
90cd09d953164d93b7ec8b1d25f70cd73033a02827d5f47b52683baef9e1691b | Python | 344 | 17 | """
Test for issue XXX:
https://github.com/Data-Centric-AI-Community/data-profiling/issues/XXX
"""
import pandas as pd
import pytest
from data_profiling import ProfileReport
@pytest.mark.skip()
def test_issueXXX():
# Minimal reproducible code
df = pd.read_csv("<file>")
report = ProfileReport(df)
_ =... |
b2a16b58e5d6a4bc812244a32684d8b7dbac7f0d4cd88359145530266e61f1f8 | Python | 344 | 13 | from .model import MoleculeModel
from .mpn import MPN, MPNEncoder
from .retention import MultiBondRetention, MultiBondFastRetention, MultiAtomRetention, SublayerConnection
__all__ = [
'MoleculeModel',
'MPN',
'MPNEncoder',
'MultiBondRetention',
'MultiBondFastRetention',
'MultiAtomRetention',
... |
2d1c199a4766453c5f0920d842c6f4c123440ddb4ba3892c232ce01af82640a8 | Python | 345 | 12 | import torch
from diffusers import StableDiffusionPipeline
model_id = "path-to-your-trained-model"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
prompt = "A photo of sks dog in a bucket"
image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
imag... |
a225c10026bc9619894c6fb264332643acf9b68b676f75536fb0078656b08eed | Python | 345 | 13 | import pandas as pd
import os
import code
# code.interact(local=dict(globals(), **locals()))
exposure_file = "MetS_noUKB_GWA.csv"
df = pd.read_csv(exposure_file, sep=",", index_col=False)
df = df[['SNP','CHR','BP','MAF','A1','A2','est','SE','Pval_Estimate']]
df['N'] = [1252787] * len(df)
df.to_csv("MetS_exposure.cs... |
fa468877c068647e161694821593eec0b049e2913cb5b034418411b083fbd1a5 | Python | 345 | 10 | r"""Tools (``ov.tl``) — analysis helpers that transform an AnnData.
Currently hosts the cross-species preprocessing extracted from
:mod:`omicverse.single` so it can be reused independently of the integration
backend.
"""
from ._cross_species import cross_species_align
from ._bonsai import bonsai
__all__ = ["cross_spe... |
4dcfc4582b82b022399d94c33be0f4d95cf40aebc9a9d46cc1022b7ffa780d34 | Python | 346 | 16 | """Compatibility wrapper for shared Agent Skill utilities."""
from omicverse.utils.skill_registry import ( # noqa: F401
SkillDefinition,
SkillMatch,
SkillRegistry,
SkillRouter,
build_skill_registry,
)
__all__ = [
"SkillDefinition",
"SkillMatch",
"SkillRegistry",
"SkillRouter",
... |
f9bd09bbf797e26f05e59cddda7a30c6614ff98fcdaa882c308e2eb2b0fc089d | Python | 346 | 22 | """
A dummy ray driver script that executes in subprocess. Prints namespace
from ray's runtime context for job submission API testing.
"""
import ray
def run():
ray.init()
@ray.remote
def foo():
return "bar"
ray.get(foo.remote())
print(ray.get_runtime_context().namespace)
if __name__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.