sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
fb0fb6f16f23d87ea26b5bd2abc532dab0393a3ea381cc4b5b825cad163adb7e
Python
2,034
39
import numpy as np import torch import argparse from omegaconf import OmegaConf from dipy.io import image from utilities import instantiate_from_config from inference import swin_denoise, swin_denoise_low_mem if __name__ == "__main__": parser = argparse.ArgumentParser(description="Inference with swin") parse...
671910729d088e85c0caad4cf931cf04f993dc66f5ef52f40632c311aca5fd19
Python
2,035
47
from typing import Any from typing import Dict from torch.utils.data import DataLoader def get_io_dims(data_loader: DataLoader) -> Any: """ Returns the shape of the dataset for each item within an entry returned by the `data_loader` The DataLoader object must return either a namedtuple, dictionary or a p...
aabe1ea6cd9f361a95a4132f2ed9ecec9c0523debae5dc70763a83a78668d73f
Python
2,035
54
#!/usr/bin/env python import os import tempfile from ..model.summarystatistics import FormattedSummaryStatistics from ..model.ld import LDScores from ..model.frequencies import Frequencies from ..model.weights import Weights class PartitionedHeritability: @staticmethod def partitionHeritability(summaryStati...
7be14eed4b20ed56f0228345c07a81410654036428054aad9f01ae558ab9931d
Python
2,036
49
import argparse from model import twostage_Unet_TF1 as twostage_Unet import tensorflow as tf import os from keras.backend import get_session import tempfile import shutil if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--load_weights_path", type=str) parser.add_argument...
4ff850200c3320c5c0a6dd5a6a4b3d35c98ef4a487197ce81ee1556e64da16c3
Python
2,038
68
from typing import Tuple, List import numpy as np from scipy.signal import butter, filtfilt from mne.decoding import CSP from mne.filter import filter_data from sklearn.base import BaseEstimator, TransformerMixin def butter_bandpass_filter(x, low, high, sfreq, order): b, a = butter(order, [low, high], btype="ban...
e3f92e2d1ad26b0851c3743b2dae3755e55e4fb7530df389c8dc3f48c7a110aa
Python
2,038
52
""" Compute time series of event segments (with start time and end time), for all data files in the provided group and save it into a separate with one event segment file for each of the original data file. These segments include: - trial events (data: index of the trial) - slider movement events (data: value of the e...
f2b5d98951ddc8350033e2a67801e50cea0dc9ec6e6c1e262a3160e872f5dabe
Python
2,041
54
from NeuronModel.NeuronClass import neuronClass import numpy as np import matplotlib.pyplot as plt hsv = plt.get_cmap('hsv') def colors(n): return hsv(np.linspace(0., 1.0, len(n)+1)) class stim(neuronClass): parameters = {'save': True, 'spike': True, 'noise': None} def __init__(self, **kwargs): ne...
d764b78548b6f641fefea1df1a9dc723f7500bd42784ab8993b14f7051b4ee9b
Python
2,042
61
import concurrent.futures import importlib import subprocess import sys from pathlib import Path def test_importable_all() -> None: for path in Path("../core/langchain_core/").glob("*"): module_name = path.stem if ( not module_name.startswith(".") and path.suffix != ".typed...
530e0fd50999c5a93979fbfcc7f477357350141e2e51ba1949006adb27abfa24
Python
2,043
61
"""Usage utilities.""" from collections.abc import Callable from typing import Any def _dict_int_op( left: dict[str, Any], right: dict[str, Any], op: Callable[[int, int], int], *, default: int = 0, depth: int = 0, max_depth: int = 100, ) -> dict[str, Any]: """Apply an integer operatio...
e6952d4b91ddb2cb286a2b6ce46cbd1ce0bd4562dbcd7d1f949666b5d6e808c0
Python
2,043
47
import torch import torch.nn as nn from torch_geometric.utils import to_dense_batch class Combine(nn.Module): def __init__(self, target_model, d_model=256, nhead = 8, num_encoder_layers=3, num_decoder_layers=3, dropout_rate=0.15): super(Combine, self).__init__() self.target_model = targe...
5f95743d5784d513e3dfb463dc5d5a71556a754eff2c71328d209bfc672c343f
Python
2,044
91
""" Vector linear algebra operations for numba accelerated code.. """ import numba as nb import math import numpy as np @nb.njit(fastmath=True) def add(vec1, vec2): result = np.zeros(3) result[0] = vec1[0] + vec2[0] result[1] = vec1[1] + vec2[1] result[2] = vec1[2] + vec2[2] return result @nb....
60e5d6edb48bdb4731298014fa54b4ef60ccb9324f72008a2df7edbbdb9d1e36
Python
2,045
85
"""collect scripts from a directory and create documentation stubs. Files starting with lower case characters are put into the directory :file:`scripts`, while those starting with upper case characters are put into :file:`modules`. """ TEMPLATE_SCRIPT = ''' .. automodule:: %(prefix)s .. program-output:: python ../sc...
e6ce59ef35b1efff7a189652f870a905f92d6934376beb3e1caae0e96024427e
Python
2,045
66
import argparse import skimage.io import numpy as np from numpy.ma import masked_array import matplotlib.pyplot as plt from matplotlib import cm parser = argparse.ArgumentParser() parser.add_argument('-left', type=str, required=True, help="left hemisphere aligned data, mhd") parser.add_argument('-right', type=str, r...
04f16190af7a34fe76096e2569c7ede79da3635bc4a4430b24f817e7acf4d4fb
Python
2,047
61
#!/usr/bin/env python # Purpose: Find avg. DVARS value for each session and for each participant overall. # # Input: Single-column txt file DVARS for each bold image. These were generated using the CBIG2016 preproc pipeline. # Output: Avg. DVARS value for each participant's session an deach participant overall. # # Wr...
62f7bc1885b2d9fc88dc01cc63f30667a6a9c5fdcdc52265e43ac7c1e3086d01
Python
2,050
71
# Copyright 2020 DeepMind Technologies Limited and Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
8c76f09459f5549eed4e0f94d63f2392bf242d25a65342779bc3a627e538e2f3
Python
2,050
62
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
9a9382f2a9561b10dd0b58804a25525c7369a113492d25f0bf4262fe5986ea9c
Python
2,054
49
"""Validation of scalar images, transforms, and detached NRRD payloads.""" from pathlib import Path import nibabel as nib import numpy as np import nrrd import SimpleITK as sitk def related_files(path): path = Path(path) files = [path] if path.suffix.lower() == '.nhdr': try: header = ...
de3bd5bd0ce7593873c646979c814cadae376770189cd07369a158a881eb7820
Python
2,054
50
import pandas as pd import numpy as np from matplotlib import pyplot as plt from scipy import stats impedances = pd.read_csv('256ch_device2_impedance_spectroscopy.csv') phases = pd.read_csv('256ch_device_phase_spectroscopy.csv') non_broken_phases = phases.drop(labels = impedances.index[impedances['1000'] > 5e6].toli...
83a6338f71f384536d7d9798d002e0b67a3fbc54ea4ce03f86071258a1fb2ccc
Python
2,055
61
import torch import joblib import matplotlib.pyplot as plt from torch_net_utils import plot_hebb from data_utils import generate_recognition_data, recog_chance from neural_net_utils import plot_train_perf, Synapse #%% d = 25 P = 0.5 intlv = True for R in [1,2,5,10,20]: for i in [2,3]:#,2,3]: # ...
83499944783aaa9d662a56064b84f02ea36901b9f20a714c4d0f4d8edb611e41
Python
2,057
72
from __future__ import annotations from typing import List import networkx as nx import numpy as np from networkx.algorithms.community import louvain_communities, modularity from libs.function.utils import shortest_path class Graph: def __init__(self) -> None: self._cluster = np.nan self._comm...
31c5ff3749caba4adcfb8e7ef618007de920bbe4f8ec1ef769cc41f9fbd4f193
Python
2,058
59
import os import pickle import re import time class WideFieldImaging: """ WideField imaging cellsdata object. """ def __init__(self, tiff_path, paq_path, exp_metainfo, pkl_path): self.tiff_path = tiff_path self.paq_path = paq_path self.metainfo = exp_metainfo # set an...
58c4b47cca1d0a85cba1b0d9e51b6c11421725bf6bba4083e8268a077abef270
Python
2,058
111
# GIF-Parameters as similar as possible to lif model import numpy as np # default values for parameters eps = np.finfo(float).eps # number of units N_E = 4000 N_I = 1000 # connection probabilities ps = np.array([[0.2,0.5],[0.5,0.5]]) # connections strengths # weights are js/sqrt(N) # nan means they are calculated js...
5daf5729ff84db1d457abf8e396c45364e3ef4d07cfc5a1024e83b1100967d45
Python
2,058
72
import numpy as np import pandas as pd import voxcell as vc from lmfit import Parameters, Model from tqdm import tqdm def linear_volume_increase(h, a, b, H): """ Calculate the volume increase using linear density assumption. Args: - h (array_like): Array of heights. - a (float): Coefficient for t...
da9eed96fb21f55d01630afc074031c183e889a98770a6d8ebdc65e5c39f532c
Python
2,059
60
import logging import os import socket import sys import numpy as np import pandas as pd from configs.configs import get_config_dict from helpers.test_retest import compute_tvfc_summary_measure_test_retest_scores if __name__ == "__main__": data_split = 'all' experiment_dimensionality = 'multivariate' m...
873211cfdfe1f90e09e2651100a77f701e4cb98f1f49ff995881e1ebf9bda992
Python
2,060
65
from contextlib import contextmanager import numpy as np import torch from .training import eval_state def get_module_output(model, input_shape, use_cuda=True): """ Return the output shape of the model when fed in an array of `input_shape`. Note that a zero array of shape `input_shape` is fed into the m...
892d2350e1073530621344fc4a7b86b564aa85cfd8dfd50e6180110a113dee4c
Python
2,061
42
import mne import os.path as op from config_FaceName import MEG_data_path,group_name,Ids,bids_root from mne.preprocessing import read_ica import numpy as np import pandas as pd from mne_bids import BIDSPath for subject_id in Ids: subject = group_name+"%02d" % subject_id print("processing subject: %s" % s...
22502df41773a163c796c72ae0d1abec61a7c6d98a477d38580419917dc522f8
Python
2,062
69
# Stock Cube Parameters stock_min_x = 10.0 stock_min_y = 10.0 stock_min_z = 10.0 stock_max_x = 50.0 #50 stock_max_y = 50.0 #50 stock_max_z = 50.0 #50 stock_dim_x = None stock_dim_y = None stock_dim_z = None # General Feature Parameters min_len = 2.0 #2 clearance = 1 #1 inner_bounds_clearance = 2 # Round Parameters ...
e7cfa82662d9b61ea0785f67f002a500531af1c9f20b06328f37907a6873557e
Python
2,064
59
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
798e7dac1e69c8af7fabbf6a1c2edd12b9b965afb0fe906132858b61a75537a5
Python
2,067
50
import os import logging import datetime from functools import partial from utils.distribution import is_master_process, sync_barrier_re1 from utils.my_containers import singleton import re @singleton class LoggerManager(object): def __init__(self, log_dir=None): self.logger_dictionary = {} ts = ...
b04cea4533453992569b43fbf86860512be54721fd006654bf990fd62183a21f
Python
2,069
78
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 11 17:31:43 2023 @author: weihan """ import torch import torch.nn.functional as F from torch_geometric.nn import GCNConv, LayerNorm class GraphConvolutional(torch.nn.Module): """ Graph convolutional network. Default three layers a...
819036aef7ec81aa840aca509bf41dc643c44be28674914d16ac86d32ad4b0f3
Python
2,070
58
import numpy as np import pandas as pd from sklearn.cluster import KMeans import random import seaborn as sns import torch import matplotlib.pyplot as plt import h5py from sklearn.preprocessing import MinMaxScaler,StandardScaler import argparse def get_attention_weight(modal_all_path,save_path): data_label=np.loa...
92fcd90b3c4adf6090be32e5271fc9927cb3430cae9a89f61dfeb4c92a3afb68
Python
2,070
58
import pytest from skbase.lookup import all_objects from pgmpy.base import DAG, PDAG from pgmpy.metrics import ( SHD, AdjacencyConfusionMatrix, BaseSupervisedMetric, BaseUnsupervisedMetric, CorrelationScore, FisherC, OrientationConfusionMatrix, get_metric, ) def test_subclass_inherits...
5065e44dabd9a0582c021bbec4d84723e49b43569f23eef5b6fc594094174102
Python
2,071
66
import inspect import logging import os import sys class SingleLevelFilter(logging.Filter): def __init__(self, passlevel, reject): super().__init__() self.passlevel = passlevel self.reject = reject def filter(self, record): if self.reject: return record.levelno != ...
d9413e50e026ad19464b2d8d6972a8ee623bcc44e92aca8e0ec3fcd7682de413
Python
2,074
75
import torch import torch.autograd as autograd from torch._vmap_internals import _vmap def jacobian_dense(fun, x, vectorize=True): x = x.detach().requires_grad_(True) return autograd.functional.jacobian(fun, x, vectorize=vectorize) def jacobian_linop(fun, x, return_f=False): x = x.detach().requires_grad...
31fb18d6e41cf59778338786eeb97928141c8d092a4e4599597a14ed3c059018
Python
2,075
73
from skimage.io import imread import os import pandas as pd import numpy as np """ COMPUTATION OF ACCURACY OF CLASSIFICATION USING GROUNDTRUTH """ images_folder = "/home/cazorla/Images/Test papier svetlana/tube neural 3d/Test_depth" groundtruth_path = "/home/cazorla/Images/Test papier svetlana/tube neural 3d/gt_new....
608abefba7290486a52bd42d6bbd0dbbc87a62707ae6ebe0967cbb0ffd923c5a
Python
2,075
49
import argparse from model import twostage_RCAN3D_TF1 as twostage_RCAN3D import tensorflow as tf import os from keras.backend import get_session import tempfile import shutil if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--load_weights_path", type=str) parser.add_argu...
eaa83440105e9a0cf98cb7b902bcb7a2fd54837bddf50be19525e881a4f616b0
Python
2,075
83
"""**Schemas** are the LangChain Base Classes and Interfaces.""" from langchain_core.agents import AgentAction, AgentFinish from langchain_core.caches import BaseCache from langchain_core.chat_history import BaseChatMessageHistory from langchain_core.documents import BaseDocumentTransformer, Document from langchain_co...
815962c2ce73a6aead5a1d39d47d3d70e5bbd41bd317a0a6a0678b3015fa3e65
Python
2,076
46
################################################################################## # DNN gene expression autoencoder pathways network 5 ################################################################################## ################################################################################## from tensorflow.k...
ad80c8f255a81ad5815438ce1123d8997f4231c2abd7e0a922c347034e042aed
Python
2,077
46
import os import sys import subprocess import glob import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from tqdm import tqdm import matplotlib as mpl mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 dir_base = '/home/yyasumizu/nanoporemeth/data/hWGBS_ICC/hIC...
76d49b79c0153db6645d20e861b7b7ec2a079af0c679a4699a33c42b052ff732
Python
2,078
77
""" Script recorder for the SMdRQA UI. Every action taken in the UI appends an equivalent block of plain Python to a :class:`ScriptRecorder`, so the whole interactive session can be downloaded as a standalone, seeded, reproducible ``.py`` script. """ import datetime class ScriptRecorder: """Accumulates Python c...
3bc7eb8afe6d05a28779a6ca64fab62b9ac0e16d5300cfd6e1d6cf541cf31f62
Python
2,079
66
""" 2023.08.30 author: femke.hurtak@epfl.ch Helping script for working with multiprocessing """ import time import multiprocessing as mp def queue_wrapping(function, result_queue, **kwargs): """ Wrapper function to allow a function to be called and add the result to a queue. This allows to calla function...
7e2161c384085999c675c9fe5506f2f43b33a4638d21edaeebba9d5ca3e67adf
Python
2,079
64
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
52f05ab6df09db11d6aacb431cf7677fa25f7ec2c0027cca8928d19998fc9a0f
Python
2,082
82
import math GR = (1.0 + math.sqrt(5)) / 2.0 # custom colors colors = { "prior": "#909090", "priorweak": "#D0D0D0", "V": "#346ebf", "Vgray": "#698dbf", "Vweak": "#b8caec", "Valt": "#b8e5ed", "T": "#2faf41", "Tgray": "#60af6b", "Tweak": "#b7edc0", "VT": "#ee1d23", "VTalt": "#...
70726861aa48bc6f5c6714e0049b243bd2d821024955f28ac308b7aa9292b028
Python
2,084
51
import torch from tqdm import tqdm class normalizer(torch.nn.Module): def __init__(self, **kwargs): super().__init__() self.normalize = False self.hparams = kwargs['hparams'] self.pde = kwargs['pde'] self.level = self.hparams.noise self.size = self.pde.n_scalar_comp...
26e25aa408e601842f72aee653a0dd3d8e7e2eea2c2103c649b525a3678dd849
Python
2,085
66
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging import sys import timeit from functools import partialmethod from pytorch_lightning.utilities.rank_zero import rank_zero_only import sys class Timer: def __enter__(self): self.t_start = timeit.default_timer() ...
779d438206097cb833652af8f5d4ecdae7d36d866cb3be3e4d0add8f6ef2ad3b
Python
2,089
55
import os from BasicSetting import * from LSTM import predict, evaluate, preprocess from DirStrategy import get_settings import numpy as np from utils import * from logger import ResultLogger def dir_predictor(setting): resultLogger = ResultLogger() settings = get_settings(setting) cur_dir...
9b56721f00066247b14df19b97e76b262741c4aec3cc7844636ca527b36f7224
Python
2,089
53
import pandas as pd import numpy as np import re import argparse def get_data(save_path): data_up_max=pd.read_csv(save_path+'/data_up_max.txt',sep='\t') data_up_min=pd.read_csv(save_path+'/data_up_min.txt',sep='\t') data_down_max=pd.read_csv(save_path+'/data_down_max.txt',sep='\t') data_down_min=pd.rea...
d19e74bb653556ce3447a87094186dcc4cac7ca9685e3980b3be6a826ea65e26
Python
2,089
75
""" Downloaded from: https://github.com/zavolanlab/zgtf/blob/master/zgtf/zgtf.py (20.06.2020) Modifications: Maciej Bak """ import os import sys import operator import HTSeq def gtf_to_transcript_exons(gtf, transcript_type): """ Parse gtf and return a dictionary where key: trancsript_id value: list of...
63992fa3c576b2ff2c7b7fec50080b490f9a8a2aacf7a7833fca517cc0a38c07
Python
2,090
66
# Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
e15626991564cbcc8588e18ad0ab010222acacf3977e6f8a955a81c76de54ca7
Python
2,090
65
"""Check version consistency between `pyproject.toml` and `version.py`. This script validates that the version defined in pyproject.toml matches the `VERSION` variable in `langchain_core/version.py`. Intended for use as a pre-commit hook to prevent version mismatches. """ import re import sys from pathlib import Path...
6e1c13a650c28f3f8b8c099ad4504143a31a0a87ad4e543815c3489ce72c758f
Python
2,092
82
"""Handle chained inputs.""" from typing import TextIO _TEXT_COLOR_MAPPING = { "blue": "36;1", "yellow": "33;1", "pink": "38;5;200", "green": "32;1", "red": "31;1", } def get_color_mapping( items: list[str], excluded_colors: list[str] | None = None ) -> dict[str, str]: """Get mapping for...
0377d6abc85b48f20b417edd7de672a8e90a51fe103b7f92f5e3f4bb776aaf9a
Python
2,094
68
""" Tests for zip_extract.py """ from pathlib import Path import zipfile from click.testing import CliRunner from .zip_extract import run def test_run_no_args(): runner = CliRunner() result = runner.invoke(run, []) assert result.exit_code == 2 assert 'Missing option' in result.output def test_run_mi...
15faf4bbc13e85ece899c855bdda55a156a9211e02a8ddcd94130b8d818d270c
Python
2,094
71
import pathlib import re from langchain_core.callbacks import CallbackManagerForChainRun from typing_extensions import override from langchain_classic.callbacks import FileCallbackHandler from langchain_classic.chains.base import Chain class FakeChain(Chain): """Fake chain class for testing purposes.""" be...
46591c1511161a00259c3d29b0e3967369106bbc1567e909065fa68be50871dc
Python
2,094
62
"""Function Message.""" from typing import Any, Literal from typing_extensions import override from langchain_core.messages.base import ( BaseMessage, BaseMessageChunk, merge_content, ) from langchain_core.utils._merge import merge_dicts class FunctionMessage(BaseMessage): """Message for passing th...
13aa431a8729bf7de9ef1bf17cfafe77be1ef4dcf1ed6947c4812dbb1010e434
Python
2,095
59
import jax import jax.numpy as jnp from projectlib.utils import grow_dims, grow_to, flatten def sq_euclidean_dist(x, y): assert x.ndim == y.ndim == 1, "sq_euclidean_dist expects two vectors" return jnp.sum((x - y) ** 2) def rbf_kernel(x, sigma): return jnp.exp(x / (-2 * sigma ** 2)) def _kernel_matrix(...
71dc33e5047d38b74118022e5fb017680e7a5aede07eb9bcd5a2440e26cecdb7
Python
2,096
48
# -- coding: utf-8 -- # @Time : 2024/02/01 11:30 # @Author : Biao Zhang # @Email : littlebiao@outlook.com # @File : run_came.py import sys sys.path.append('../') from analysis_utils import ttest_plot_utils from analysis_utils import homo_random_config as config import os if __name__ == '__main__': cfg = config....
73cf9c94c656c4f3ef008e524effce69b98b3f57827afdf8fe2cecafdf7baff5
Python
2,096
73
from typing import List import torch import torch.nn as nn from e3nn.util.jit import compile_mode import hienet._keys as KEY from hienet._const import AtomGraphDataType @compile_mode('script') class Rescale(nn.Module): """ Scaling and shifting energy (and automatically force and stress) """ def __i...
7e2938f1153ea678edeeb82ab28d3d5269fd27c97af742645e28d35b372dd071
Python
2,096
74
'''collector for stacks to be processed. ''' import os import glob import itertools import logging import luigi import pandas from .ioutils import parse_meta # Typical file extensions of stacks that need to be processed. DEFAULT_FNAME_PATTERNS = [ '*confGFP*stk', '*conf488*stk', '*.czi', ...
9619fecb5db1da58db18150b9db8cb0fe7d7b0cf8a07b03cee132910f2cd9b9c
Python
2,097
76
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import nibabel as nib import numpy as np import os from scipy import interp DESCRIPTION = 'Drift Correction of dMRI Data, Based on Linear Interpolation Between b0s. Cornelius Eichner 2021' def buildArgsParser(): p = argparse.ArgumentParser(descri...
ccb2b3eda2ddeabdde700f33905b6782bf271d5e4a8df7760606c44a7bcdb306
Python
2,100
64
import functools import torch import torch.nn as nn from networks.resnet import resnet50 from networks.base_model import BaseModel, init_weights class Trainer(BaseModel): def name(self): return 'Trainer' def __init__(self, opt): super(Trainer, self).__init__(opt) if self.isTrain and ...
56c5b2a7d59211d99614c6d9f5c66a27ef52137c9df3181cd79aeba12bcaaa1c
Python
2,101
57
# Move this into train import configparser def read_arguments_from_file(fp): """Reads run arguments from file""" config = configparser.ConfigParser() config.read(fp) settings = config['settings'] return _convert_arguments(settings) def _convert_arguments(settings): converted_settings = {} ...
c661bff533166a178de5ca045ae7b247f41d621b87660d02865a1bc02bf35862
Python
2,102
80
import json import sys class Message: def __init__( self, message_id, message_text, author, timestamp, parent_message=None, child_message=None, ): self.message_id = message_id self.message_text = message_text self.author = author ...
2ae4cb9fc19e645c7c69db1a7e349637bac1972d8838eabef05c232b344e1f78
Python
2,103
62
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
9902e3d4c2d3e88fa4cda466f964d0f535781b4f276edc57de3d0c1301f08433
Python
2,104
62
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for detai...
fafe838beade24cb79855154d427b826df7e5ae95075f721fa4c0d3f39a6a351
Python
2,104
54
from langchain_core._api import deprecated from langchain_core.language_models import BaseLanguageModel from langchain_core.output_parsers.openai_tools import PydanticToolsParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import Runnable from langchain_core.utils.function_callin...
bf2b554aeaa9f74fe8f82ec5505ddda425ebfed6eca6a2c25b7ce151cfbbc025
Python
2,105
63
#!/usr/bin/env python import logging import os import random import time import urllib.request from http.client import RemoteDisconnected # Setting logging level config LOGLEVEL = os.environ.get("LOGLEVEL", "DEBUG").upper() logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=LOGLEVEL...
c18cb71d6745fde5b96440757b3ec54fbfbef48c4ef95b1641f854e94000f37a
Python
2,105
81
import os, sys, re, types import matplotlib.pyplot as plt import sqlalchemy from SphinxReport.Renderer import * from SphinxReport.Tracker import * # for trackers_derived_sets and trackers_master if not os.path.exists("conf.py"): raise IOError( "could not find conf.py" ) exec(compile(open( "conf.py" ).read(), "co...
4b415b75279553eff9777a5d36832336562e1a6c33c164cb7701ebb6bb1da73a
Python
2,106
60
from typing import Optional, List from torch.utils.data import DataLoader from scdp.common.pyg import Collater class ProbeCollater(Collater): def __init__(self, follow_batch, exclude_keys, n_probe=200): super().__init__(follow_batch, exclude_keys) self.n_probe = n_probe def __call__(self, ba...
6c87af77914d21edd6e5940ac301e6b299ff3557c43940777fc8b176aec02af3
Python
2,106
77
"""**Prompt** is the input to the model. Prompt is often constructed from multiple components. Prompt classes and functions make constructing and working with prompts easy. """ from typing import TYPE_CHECKING, Any from langchain_core.example_selectors import ( LengthBasedExampleSelector, MaxMarginalRelevanc...
65dc0b66699711606bf3b9267052f10bfa1d844280d161465169dc45631997c3
Python
2,107
51
from boundingbox import BoundingBox import cv2 import numpy as np def preprocess(img, input_shape, letter_box=True): if letter_box: img_h, img_w, _ = img.shape new_h, new_w = input_shape[0], input_shape[1] offset_h, offset_w = 0, 0 if (new_w / img_w) <= (new_h / img_h): ...
8e7ed4b77a349719b8a4e88a6240e69c1c5c0c4da41152e351b37bbbd109afd8
Python
2,107
67
import os import cv2 import torch import numpy as np import datetime # Additional Scripts from train_transunet import TransUNetSeg from utils.utils import thresh_func from config import cfg class SegInference: def __init__(self, model_path, device): self.device = device self.transunet = TransUNe...
aaf5446291a50e003bafbb1f14cb46b5339bbfa7209befabb92061203e5a016e
Python
2,107
67
import pandas as pd from .power_divergence import PowerDivergence class ChiSquare(PowerDivergence): """ Pearson chi-square test for conditional independence on discrete data. This class is a thin specialization of :class:`PowerDivergence` with ``lambda_="pearson"``. For the contingency-table constru...
34cd1f242b018cfdc7236f40e1d1176c28f2d9624467d3a322847b32b1bc09e4
Python
2,110
60
import sympy as sym import tensorflow as tf from tensorflow.keras import layers from dipgnn.models.layers.envelope import Envelope from dipgnn.models.model_utils import bessel_basis, real_sph_harm class SphericalBasisLayer(layers.Layer): """ This code is extracted from dimenet (https://github.com/gasteigerjo/...
59859f068afbbddb71e0bbf32ffa737d4cf5e006145fbae812240c1ea990d4ce
Python
2,113
64
import pandas as pd from .power_divergence import PowerDivergence class ModifiedLogLikelihood(PowerDivergence): """ Modified log-likelihood ratio test for conditional independence on discrete data. This class is a thin specialization of :class:`PowerDivergence` with ``lambda_="mod-log-likelihood"``....
3b7f714402da063e74de3f6d40241803fc1cc7c745a73a593f48e273a6d16e30
Python
2,114
71
from typing import Any from langchain_core.callbacks import Callbacks from langchain_core.language_models import BaseLanguageModel, __all__ from langchain_core.outputs import LLMResult from langchain_core.prompt_values import PromptValue EXPECTED_ALL = [ "BaseLanguageModel", "BaseChatModel", "SimpleChatMo...
9b789aaf2efc8c06516f556d6b366978ea5483d5ecab7c2d0942c365f734a8cd
Python
2,115
81
import matplotlib.pyplot as plt import numpy as np import pandas as pd #import pykrige.kriging_tools as kt from pykrige.ok import OrdinaryKriging import random #plt.rc('font', family='Times New Roman') Data5_100 = pd.read_csv('P_5_100.csv') Data5_150 = pd.read_csv('P_5_150.csv') Data5_200 = pd.read_csv('P_...
f79b99f21569a33266ca309bffa0aaf7458886cdafc9354f49e8578d5c2a64a1
Python
2,115
63
#!/usr/bin/env python import logging import os import random import time import urllib.request from http.client import RemoteDisconnected # Setting logging level config LOGLEVEL = os.environ.get("LOGLEVEL", "WARNING").upper() # logging.basicConfig( # format='%(asctime)s %(levelname)-8s %(message)s', # level=...
441a689c5ef08b9affca0cba24daafb5c0c891b08f9998e238c2e62c909e3ace
Python
2,116
72
"""LangSmith evaluation utilities. This module provides utilities for evaluating Chains and other language model applications using LangChain evaluators and LangSmith. For more information on the LangSmith API, see the [LangSmith API documentation](https://docs.langchain.com/langsmith/home). **Example** ```python f...
367d9b6e4034c6dea880c1efbd212092dd9d2c6cd96b36d71827695ab4fea7af
Python
2,117
66
"""Output classes. Used to represent the output of a language model call and the output of a chat. The top container for information is the `LLMResult` object. `LLMResult` is used by both chat models and LLMs. This object contains the output of the language model and any additional information that the model provider...
bdea9c2cce3d8c87ef3e7fca519fdec0080fb76f3de75d19bc295c12f5e2a1c5
Python
2,117
66
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import numpy as np import os # from __future__ import print_function DESCRIPTION = 'Reordering bvecs file i.e., swapping and inverting dimensions. Cornelius Eichner 2018' np.set_printoptions(precision=2) def buildArgsParser(): p = argparse.Argume...
7fec805d6adac0d9a1d0c83f921d9be273dffae6c662fadbdddc2506d03bedc6
Python
2,120
81
""" scaden Main functionality Contains code to - process a training datasets - train a model - perform predictions """ # Imports import logging import tensorflow as tf from anndata import read_h5ad from scaden.model.architectures import architectures from scaden.model.scaden import Scaden logger = logging.getLogger...
128bbc42a8133e98a48b2762535149a76dc64e1d820047cd1fa779b653fb2a1e
Python
2,121
58
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for detai...
1548bb3b0accf7d96c50581b5f8cf6fdd5fd283239a8242c81a3a49b7ba85638
Python
2,121
65
#!/usr/bin/env python # coding: utf-8 import os from os.path import abspath, join, isdir import sys # for relative paths in nn4dms code to work properly, we need to set the current working # directory to the root of the project # we also need to add the code folder to the system path for imports to work properly pr...
1d4c7156a0fb994b3bfac928643c5024ac4fb9db5d2d045be3705cc991c57a6f
Python
2,122
68
from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.parameter import Parameter from torch.nn import functional as F import torch class _BatchInstanceNorm(_BatchNorm): def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True): super(_BatchInstanceNorm, self).__init__(num_features, e...
58314ca3e31dfbc8bb95da65b9d58742d78b17dc7bc2fdde534898f0f974863f
Python
2,124
61
""" Wrapper for glmnet_python to work with the experiments script. Authors: George H. Chen, Lexie Li, Ren Zuo """ import numpy as np import pandas as pd import pickle from sklearn.preprocessing import StandardScaler import glmnet_python from glmnet import glmnet from glmnetCoef import glmnetCoef class CoxWrapper: ...
a5dcd8e50926b16e635191bfad949da99c90308f3b6b0748ee3537c6e8030eab
Python
2,124
61
# coding=utf-8 import torch import torch.nn.functional as F from alg.algs.ERM import ERM class CORAL(ERM): def __init__(self, args): super(CORAL, self).__init__(args) self.args = args self.kernel_type = "mean_cov" def coral(self, x, y): mean_x = x.mean(0, keepdim=True) ...
aa1b327ad1df5d99173cc93f16b76ee6579442817d2e33021249e5ca8e0b7ba0
Python
2,124
72
#! /usr/local/bin/python #'################################################################################# #'################################################################################# #' Transfer learning using features from TCGA model #'#######################################################################...
cd71cc1c38558c156b512b1d88b01c7d708e84960d57f56ef28ae603bb5e7bf3
Python
2,124
76
import numpy as np from scipy.stats import skew all_functions = [min, max, np.mean, np.std, skew, len] functions_map = { "all": all_functions, "len": [len], "all_but_len": all_functions[:-1] } periods_map = { "all": (0, 0, 1, 0), "first4days": (0, 0, 0, 4 * 24), "first8days": (0, 0, 0, 8 * 24...
42e15f453f42a65c8a8d67928c4593b24f39e2daeb5600d0bd010c9e310c3f12
Python
2,125
68
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 13 14:53:06 2022 @author: athanasiadis """ import numpy as np def computer(sig_res): """ computer ______________________ This is a function that computes the results of the permutation test. Input: - t...
30238fb13272cd1f36b25b1f77d605de7684d0c803a175bdd5af645680e4ddd0
Python
2,126
72
"""Test Base Schema of documents.""" from collections.abc import Iterator import pytest from typing_extensions import override from langchain_core.document_loaders.base import BaseBlobParser, BaseLoader from langchain_core.documents import Document from langchain_core.documents.base import Blob def test_base_blob_...
7f81c7f562436bc1d2536ae352e80003e9be346528201f752d03ee5e444b3bd2
Python
2,126
70
# Custom pytorch modules from typing import Sequence import torch from torch import nn class Unnormalize(nn.Module): """ Helper class for unnormalizing input tensor """ def __init__( self, mean: Sequence[float] = (0.0,), std: Sequence[float] = (1.0,), inplace: bool = ...
9bee07de25acd75ebb36213df1af6d76c0f1f223b99720c54f3231124d3e1632
Python
2,127
63
# This file is a part of the `allegro` package. Please see LICENSE and README at the root for information on using it. import torch from nequip.data import AtomicDataDict from nequip.nn import GraphModuleMixin, scatter, AvgNumNeighborsNorm from typing import Optional, Union, Dict, Sequence from math import sqrt cla...
31dffe9f86d1831a0c2b004d868f50bd6084508b364cd13fb6b5947b215e8453
Python
2,128
43
from django.shortcuts import render from django.contrib import messages from django.views.generic.edit import FormView from django.core.exceptions import ValidationError from .forms import ClusteringForm from .models import Cluster from .clustering_code import cluster_data class IndexView(FormView): model = Clus...
49c1e0d5f37e7989040840570f420781847f3fed3a66b20d19ecb05d41f7085c
Python
2,128
46
import numpy as np import h5py import argparse import os def main(files, dsets, metrics): for file in files: assert os.path.isfile(file), f"either {file} doesn't exist or path is wrong" h5df = h5py.File(file, mode="r") for i, key in enumerate(dsets): assert f"{key}_coverage" i...
b541457e503b6c7dadf2ef16fde478ab31acd694e42ed96f30697555749a81cb
Python
2,132
58
from datetime import datetime, timedelta, timezone from langchain_core.exceptions import OutputParserException from langchain_core.output_parsers import BaseOutputParser from langchain_core.utils import comma_list class DatetimeOutputParser(BaseOutputParser[datetime]): """Parse the output of an LLM call to a dat...
095a3f613cd4df18b75f577e7df659e2594b11cbf570335400a7af93cf15f3e4
Python
2,133
45
#!/usr/bin/env python import os import tempfile from ..constants.constants import HUMAN_SOMATIC_CHROMOSOMES, BASELINE_WEIGHTS_URL from ..utilities.utilities import untar class Weights: SUFFIX = ".l2.ldscore.gz" @staticmethod def validateDirectory(directory, chromosomes = HUMAN_SOMATIC_CHROMOSOMES, pref...
a88e63f58d78b5f892df6388a5a5b9b1eb25551e08a4012d43add626ec0a901d
Python
2,134
61
# Imports import sys import os import argparse import inspect from datetime import datetime import numpy as np from tqdm import tqdm from math import ceil from time import perf_counter, process_time import torch import torch.optim as optim try: from torchdiffeq.__init__ import odeint_adjoint as odeint except Impo...
3fa3fae9c305bb57baa02e687578959dc7d441c59bab08cc36cdd0bc74fce110
Python
2,137
58
#################################################################################### # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for d...
568508dcec8043e6aa307e003e52ed1a349a54bdc54025b633b7dab34a80516b
Python
2,137
69
import numpy as np from voxcell import VoxelData from os import cpu_count import sys from tqdm import tqdm import scipy.ndimage as nd import flatmap_util as fmutil flatmap_nrrd = sys.argv[1] pixel_res = int(sys.argv[2]) output_nrrd = sys.argv[3] ncpu = cpu_count() // 2 if len(sys.argv) > 4: ncpu = int(sys.argv...
66612c70c423aebb16d0a7919b2987ef74f8a606fe67c0caa098df4ce578a029
Python
2,137
54
import math import torch import torch.nn.functional as F """ IMPORTANT NOTE: The cutoff and the switch function are numerically a bit tricky: Right at the "seems" of these functions, i.e. where the piecewise definition changes, there is formally a division by 0 (i.e. 0/0). This is of no issue for the function ...