sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
99ba21fc6acd40c1527470b6a0b8ce29551608c18d8b2253ed7aea070d577cdb
Python
3,755
128
""" 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 import os import pickle import random import ase import numpy as np import pytest from fairchem.data.o...
b53c8a0697c6a8a18f5565038846995ff9592a04f702ba096dabf481650deab9
Python
3,755
106
import enum import logging import os from typing import TYPE_CHECKING from .base_autoscaling_coordinator import ( AutoscalingCoordinator, ResourceDict, ResourceRequestPriority, ) from .base_cluster_autoscaler import ClusterAutoscaler from .default_autoscaling_coordinator import ( DefaultAutoscalingCoor...
88788f3ed3da7ab5304f1b11a387648e3ae836d743e301e755124000260e97ed
Python
3,756
121
r""" Temporary compatibility helpers for loading datastores pickled with older Neo. TODO: Remove this module once pre-neo==0.14.0 datastore pickles no longer need to be supported. When bumping Neo for good, also update README.rst and the GitHub Actions install command. """ from contextlib import contextmanager from ...
f420e98f68db7e9289463ac1d80c8c81c7ca8d2a8b1e15ce4597c1d62ce4eefc
Python
3,757
83
"""Filtering primitives. PCA/tuning use correlation; final Gabor uses convolution.""" import math import torch from torch.nn import functional as F from scipy.fft import next_fast_len def correlate_valid(x, kernels, stride=1, backend="auto"): """x: [B,1,H,W], kernels: [K,1,h,w]. Real-valued valid correlation.""" ...
8ddebbc0f08404af2e157f2555bf7b4b04c768610cc2b19a69780a64fe86fba0
Python
3,758
96
import collections import inspect from ray.dashboard.optional_deps import aiohttp from ray.dashboard.routes import BaseRouteTable from ray.dashboard.subprocesses.handle import SubprocessModuleHandle from ray.dashboard.subprocesses.utils import ResponseType class SubprocessRouteTable(BaseRouteTable): """ A ro...
ca2a8a4350919c1854fe2a23e0f1933e17eca065502e70fec09f2f9ea9d01785
Python
3,758
116
import sys import networkx as nx # Add package path packagepath = '../kcorePercolation' # Manually specify the path to your script sys.path.append(packagepath) from utils import kcorePercolation as kp # Import custom utility functions def GetfailedGCC(G, removed_node_set): ''' Calculate the size of the large...
93aafe139b451900cfdd3bcfa32dd639037c75caa0f0a8bc10c47c1589e3bb5e
Python
3,759
123
from pickle import FALSE from datagenerator_pd import DataGenerator from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc from tensorflow.keras.utils import to_categorical import matplotlib.pyplot as plt import seaborn as sns import SimpleITK as sitk import pandas as pd import numpy as np...
9c276c2ab5119a87b2fe2a6b3d79614a749ef9eb13e6f3daa5100566b0dbb6a2
Python
3,759
143
#!/usr/bin/env python3 import rospy from std_msgs.msg import MultiArrayDimension,Int8MultiArray import cv2 from cv_bridge import CvBridge import ros_numpy import numpy as np import PIL.Image import io from torch2trt import torch2trt from torch2trt import TRTModule import torch from torchvision import transforms f...
4204dadfdac17e5f9d061e23aefb977340033fc5b80c9c71f9162505fcbbb975
Python
3,760
99
import numpy as np import pickle as pkl from multiprocessing import Pool from utils import load_json_file, dump_as_pickle, load_pickle from pathlib import Path from torch import load from glob import glob import sys import gc import torch import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" from eval.eval_utils impor...
71462a25020084ab88120883b4a27dc30fe2503e24d416a27e800f6928a5fe83
Python
3,761
118
import os os.environ["TESTING"] = "true" from pathlib import Path import nbformat import papermill as pm import pytest import torch pytestmark = pytest.mark.slow examples_path = Path(__file__).parent.parent / "examples" # List of notebook names notebooks = [ pytest.param("01_flyvision_connectome.ipynb", marks=[]...
4373e4dac866ab6a1a9ea793f2ce8c72959de5be90df5bddd8733c98bdc3da57
Python
3,762
130
from scipy.io import loadmat from scipy.special import erfcinv import numpy as np import pandas as pd from scipy.stats import kstest, chi2_contingency from itertools import combinations def star(p_val): assert 0 <= p_val <= 1 if p_val >= 0.05: return 'ns' if p_val >= 0.01: return '*' ...
38ffa28249b92f0153969bce1bfd6dcb6b97d1ce2188505c5879bcf92ab1a247
Python
3,763
90
import sys sys.path.insert(0, "/srv/home/zgaleday/torch_pgn") from torch_pgn.args import TrainArgs, HyperoptArgs, DataArgs from torch_pgn.load_data import process_raw from scripts.generate_final_correlations import generate_final_correlations import os import os.path as osp def generate_datasets(raw_path_1, raw_path...
b8776fa53534647aec58f821bb1fcf7c23fcfd87e12beb1d2d34b67c4e1fbe69
Python
3,763
146
# POINT METRICS from scipy.spatial.distance import directed_hausdorff import numpy as np import persim import cv2 import alphashape from skimage.metrics import mean_squared_error from skimage.metrics import structural_similarity as ssim def hausdorff(set1, set2): """ Given two sets of points, compute their ha...
cff06282a60cb950bb127cabd033db6284e33171adabc1db34ea3379d4b1cc3b
Python
3,763
107
import os import pandas as pd from src.commons.process_dataframe import keep_valid_columns, change_col_value_type, insert_new_col_from_two_cols, \ get_sub_df_according2col_value, get_mean, get_std from src.commons.process_number import get_deviation, get_percent_change from src.constants.ms2_uniform_prolific_1_con...
a6e4a4495474a97b58c44453d18288c3dc6957ae6cf63613a4180cd5b7b819f6
Python
3,764
116
from os.path import splitext from os import listdir import numpy as np from glob import glob import torch from torch.utils.data import Dataset import logging from PIL import Image import os class BasicDataset(Dataset): def __init__(self, root, scale=1, direction='AtoB',norm='std'): # self.imgs_dir = imgs...
30398e419fc0909d716295e76889aebe2758a6bca0a4c54c174e8759805ed308
Python
3,768
91
import numpy as np import os import json import math from scipy.stats import chi2_contingency, wilcoxon, mannwhitneyu, shapiro, linregress from ..io import SAVED_DIR, RESULTS_DIR, load_network, load_params, load_responsiveness, load_activity from ..analysis import find_response_range, parse_activity, find_stimulus_rang...
67404973a3a6e3d2cc10b75d6f695b6922999f5c1021960d805907b2b0158c1e
Python
3,768
91
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
78ede641509982184fd569c60dfd909fe161eb2fe9f633b75546d317295e9294
Python
3,768
112
import numpy import random import sys sys.path.insert(0, "..") from scipy import stats, special from sklearn.preprocessing import PolynomialFeatures from matplotlib import pyplot import matplotlib; matplotlib.use("MacOSX") from banditopt import algorithms # numpy.random.seed(42) # random.seed(42) class Sampler: ...
60d2865ce54f1250b24bff8fc27ca02ee7fbc81e4850804ad2732e27b6e3574b
Python
3,770
107
import sys import os sys.path.insert(0, "/srv/home/zgaleday/torch_pgn") from torch_pgn.train.Trainer import Trainer from torch_pgn.train.train_utils import load_args from torch_pgn.train.run_training import run_training import numpy as np import pandas as pd import os.path as osp import os def generate_final_corre...
cb15a62a094bf4d480ee4ad7bc62de7d997b6363bb5787b62c32663ddbd3ecda
Python
3,770
124
from numpy import inf def parse_deseq_file(path, lfc_cutoff = 1.5, pval_cutoff = 0.05, sep = '\t'): up_genes, down_genes = [],[] with open(path, 'r') as f: skipped_header = False for i, line in enumerate(f): if i > 0 and not (line == '' or line == '\n'): ...
295a0b56cc313bd0c6dcd146ffc267b29bce0df685191c6b5ee53ea6ef0dac59
Python
3,771
110
# Copyright (c) DP Technology. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from functools import lru_cache from unicore.data import BaseWrapperDataset class TTADataset(BaseWrapperDataset): def __init__(self, datase...
b60b7a95a4aaac1f9d64ad4f2c91b08e0d565be2993a776eb5a1388e1fe6049f
Python
3,771
95
import unittest from copy import deepcopy import torch from rising.transforms.functional import box_to_seg, filter_keys, instance_to_semantic, pop_keys, seg_to_box class TestSegBox(unittest.TestCase): def setUp(self) -> None: self.seg = torch.zeros(10, 10, 10, dtype=torch.long) self.seg[1:3, 1:3...
e7f425f209caa7d489f982ffd5c92818042f4744563171a399b7f05e9935f90c
Python
3,773
133
import time import numpy as np from discontinuous_galerkin.base.base_model import BaseModel from discontinuous_galerkin.start_up_routines.start_up_1D import StartUp1D import matplotlib.pyplot as plt import pdb import oci import scipy.stats import yaml from matplotlib.animation import FuncAnimation import ray from gene...
556b0c27e057c761aa31188d093ecde81c0eedf29b17ffdaebec5432f420dea6
Python
3,774
107
# -*- coding: utf-8 -*- """Common tools for interactive 3D/4D visualization on Jupyter Notebook and Jupyter Lab.""" import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from ipywidgets import interact, IntSlider from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar def volume(v,...
116f60291bc4743438ba0331212459df2a0a389dd03f6f9d1ea5d081052ff5a0
Python
3,775
96
import json import os import subprocess import boto3 DOCKER_USER = None DOCKER_PASS = None def _get_curr_dir(): return os.path.dirname(os.path.realpath(__file__)) def get_secrets(): global DOCKER_PASS, DOCKER_USER secret_name = "dockerRetagLatestCredentials" region_name = "us-west-2" session ...
12be228b98bf29752a7d3e4a017d3b8e0d09a3ada8d6791888e1ef8a00f788d4
Python
3,775
125
"""Hermetic test for the in-repo ``myst_eval_rst_doctree`` Sphinx extension. Builds a tiny Sphinx project in a temp dir (in-process, no network, no Ray import) with a Markdown page whose ``{eval-rst}`` block holds a bullet list and a Python domain signature, then loads the pickled doctree and checks the following: * ...
2c181aef0df53a938133762388cf7077418200fa97ee1c03a0c052182a5b7643
Python
3,776
97
import numpy as np import pickle as pkl from multiprocessing import Pool from utils import load_json_file, dump_as_pickle, load_pickle from pathlib import Path from keras.models import load_model from glob import glob import sys import gc from eval.eval_utils import calculate_metrics def main(): config = l...
df1f87c3f7b91fd13dce2899eeaf0d5467185d7e052c5f0da0206011bc18b3a4
Python
3,776
100
import torch import torch.nn as nn import torch.nn.functional as F class SACNN(nn.Module): def __init__(self, input_channels=3): super(SACNN, self).__init__() # Block 1 self.block1_conv1 = nn.Conv2d(input_channels, 64, kernel_size=3, padding=1) self.block1_conv2 = nn.Conv2d...
40cd5242e49ae2c3166d24edd7e8e2221d490d355b9f2cfc4412ae50f701a671
Python
3,777
119
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Run before 04_integrate_batches """ import argparse import firecloud.api as fapi from firecloud import fccore from firecloud import errors as ferrors from google.cloud import storage fcconfig = fccore.config_parse() def get_bucket_name(namespace, workspace): ...
503e6c0f4ec3a4e77abc29dc3130950c3ea5383fe9789ef5b335aa6e17b33b71
Python
3,778
128
# %% # import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import create_new_target_data as cnd import SSN_model_funcs as ssn from cycler import cycler import pickle from tqdm import tqdm tqdm.pandas() from pandarallel import pandarallel pandarallel....
e20a018cae90bd13f5658a7e54bc2466267eff7ef61697c2e2219d771a846773
Python
3,779
100
import torch import torch.nn as nn import torch.nn.functional as F class PLReMixModel(nn.Module): def __init__(self, backbone, dataset, n_clusters, n_heads=2): super(PLReMixModel, self).__init__() self.backbone_dim = backbone['dim'] self.n_heads = n_heads # 不是class numer self.data...
f756b5e0a3c09f28d298d78335feae559bf4455c3816fab8733056a94925f7e0
Python
3,781
99
"""Shared adapter for the optional :mod:`pymclustR` backend. This replaces the ``rpy2`` bridge the spatial wrappers used to embed, so an R installation is no longer required. For the ``EEE`` model those wrappers all default to, the substitution is numerically transparent: on a real 700-cell PCA embedding, ``pymclustR`...
826b9b56ad1865bc50d508be1a221b2473410f0e43d7a6d7a45b81b91d726448
Python
3,783
105
""" Pyspark counts """ from typing import Tuple import pandas as pd from pyspark.sql import DataFrame from pyspark.sql import functions as F from pyspark.sql import types as T from data_profiling.config import Settings from data_profiling.model.summary_algorithms import describe_counts @describe_counts.register...
d5bbbd4ea409e7d40b016bd459c0bc91581b5056095874214a82bb168496d8c0
Python
3,783
104
import unittest import io import numpy as np import vamb import testtools from vamb.parsecontigs import CompositionMetaData class TestParseBam(unittest.TestCase): @classmethod def setUpClass(cls): minlen = 3000 mask = np.array( list(map(lambda x: x >= minlen, testtools.BAM_SEQ_LEN...
aa2c7d435661c4f0752bbb8af8f8f3b090eeed61c629beb2dcaf72d652b487c0
Python
3,786
124
# myhist.py # Copyright (c) 2010 Jes Frellsen # # This file is part of Muninn. # # Muninn is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # Muninn is distributed in the hope that it will be useful,...
ecc07802e740ccbae745e5abaf946e161d32cdfa44f82c91e92e6e278bbba78c
Python
3,787
104
import os import sys import json import logging import neuron_morphology.swc_io as swc import neuron_morphology.validation as validation from neuron_morphology.validation.result import * import neuron_morphology.marker as marker from neuron_morphology.validation.report import Report import argparse import glob import n...
d4b45a8c2170ec66359293f5fcd45f80afc23e4bc59c165bc03678ecc815bfcc
Python
3,788
115
from typing import Any, Dict, List, Optional, Union import torch from ray.air._internal.device_manager import get_torch_device_manager_by_context def get_devices() -> List[torch.device]: """Gets the correct torch device list configured for this process. Returns a list of torch accelerator (GPU, HPU, NPU......
60b3b4e2e23b86fb71610c27d2690bd9b1a5c0787f61fae6902d6935011246af
Python
3,789
138
"""Plotting functions for the missing values diagrams""" from typing import Any, List from matplotlib import pyplot as plt from data_profiling.config import Settings from data_profiling.visualisation.context import manage_matplotlib_context from data_profiling.visualisation.plot import ( missing_bar, missing_...
618aa563531fed43f98a79c92d19f38a818c8a879059092840151fbbdb33d1eb
Python
3,789
137
"""Scaling stimulus responses across durations""" import os import glob import nibabel as nb import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ROOT = '/Users/sebastiandresbach/github/neurovascularCouplingVASO/results' SUBS = ['sub-05', 'sub-06', 'sub-07', 'sub-08', 'sub-09'...
69b2e4bf9f98f50f7f54cd6a8d36c79a114f198760f7b8ad9343f6df6afbb2da
Python
3,789
118
from __future__ import annotations from dataclasses import MISSING, dataclass, field, fields, is_dataclass from typing import Literal @dataclass class GlobalConfigs: regress_forces: bool direct_forces: bool hidden_size: int # divisible by 2 and num_heads num_layers: int activation: Literal[ ...
83814f4d163ac2bb7f7c8e039e4d0cb9b660456f6ba0b7f0a3cb2d7a8d93dc17
Python
3,789
130
from pathlib import Path from typing import Any, Dict from ray.autoscaler._private.cli_logger import cli_logger try: # py3 from shlex import quote except ImportError: # py2 from pipes import quote def _check_docker_file_mounts(file_mounts: Dict[str, str]) -> None: """Checks if files are passed as file...
e85f2adabdd8f27b82b8eb0267d28ad1ea673faf29190dc6e94f216a3f712ba8
Python
3,789
119
#!/usr/bin/env python # -*- coding: utf-8 -*- """ author: Pengcheng Zhou email: zhoupc1988@gmail.com created: 6/16/17 last edited: """ import os from collections import OrderedDict from PyQt5.QtWidgets import QFileDialog, QWidget, QLabel, QPushButton, \ QLineEdit, QGridLayout, QApplication # --------------------...
522a4533370ec97f69105f8d881067fe8b163900f0e0aa8992d1ea7fa89343db
Python
3,791
117
from typing import List, Literal import torch import pandas as pd import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel from timm.models.vision_transformer import Block as AttentionBlock import torch.nn as nn import torch.nn...
82d10c27672189487cf92e8a38c81c832bfb5b45ac7ff93513e479a076157ea2
Python
3,791
79
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
b87cd46896b24e2bd2153b6b6be294cad423c62a40bb11b878f5c077b86b927c
Python
3,791
129
import inspect import multiprocessing import random import re import types from functools import partial from pathlib import Path from typing import Any, Callable, Generator, Iterable, Optional import numpy as np from siapy.core import logger from siapy.core.exceptions import InvalidInputError __all__ = [ "initi...
1726dc1e158d09af472307cd08efd06c0cabf319ffe3abc4c1af40b5bf347064
Python
3,793
114
import hashlib import multiprocessing as mp import nibabel as nib import pandas as pd from os import path from joblib import Parallel, delayed from nipype.interfaces import ants, fsl def measure_sim(image_path, reference, substitutions=False, mask='', metric='MI', radius_or_number_of_bins=8, sampling_strategy='N...
2fb512c971471d2192d8189f578f3e0544f21fe7fb01e550488e38da20a00994
Python
3,793
95
import os import numpy as np from transformers import AutoTokenizer import random import argparse def parse_arguments(): parser = argparse.ArgumentParser(description='Process the text data for tokenization.') parser.add_argument("--data_dir", type=str, required=True, help="Directory of the raw data.") pars...
8d049ce951fa7f3317b7c05179a972aa9da84a4d277058576411fedf6c4c70c1
Python
3,794
100
import numpy as np import math class Box: # def __init__(self,a1,a2,a3,b1,b2,b3,c1,c2,c3): def __init__(self, *args, **kwargs): self.mTrans = np.zeros((3,3)) # This will read the different cp2k options how to define a cell if 'cellfn' in kwargs: with open(kwargs['cellfn'], '...
41c58ebb073a76b30d2c7dee89748b1bd4d003b75ddd4c966c5d99bcaf0ffbb9
Python
3,795
121
from typing import List from ipywidgets import widgets from data_profiling.report.presentation.core.container import Container from data_profiling.report.presentation.core.renderable import Renderable def get_name(item: Renderable) -> str: if hasattr(item, "name"): return item.name else: ret...
608d77449679d457556bb48dd9f071367b9a3ba7db659b97fa291d43ad86c9ea
Python
3,796
101
''' MBEANN settings for solving the OpenAI Gym problem. ''' class SettingsEA: # --- Evolutionary algorithm settings. --- # popSize = 200 maxGeneration = 100 # 0 to (max_generation - 1) isMaximizingFit = True eliteSize = 0 tournamentSize = 20 tournamentBestN = 1 # Select best N individua...
1312319dbe5abd43afb712aec73b163afb8ece3bd1c426c1e7eae16cf3a46f99
Python
3,797
129
import torch import torch.nn as nn import torch.nn.functional as F from pfrl import action_value from pfrl.initializers import init_chainer_default from pfrl.nn.mlp import MLP from pfrl.q_function import StateQFunction def constant_bias_initializer(bias=0.0): @torch.no_grad() def init_bias(m): if isi...
a5ff8f332cc4ee30c48ffa3d6e90e0c3736c73f013dd917c3064072ef9de1ae8
Python
3,799
136
"""Prompt templates used by domain research helpers. The utilities here centralise textual templates for the research pipeline. Each function returns a formatted prompt string and accepts ``**kwargs`` to allow model specific customisation without modifying the base templates. Defaults include a brief description of Om...
10c4c73bf41b3932613b794ea5cf95967e0d35f12f3cc00e4999d8d4cd450d44
Python
3,804
91
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
4ba78cca556d55b302350681b34b8dac37e94405397b9af758fefeaa3e1a95b9
Python
3,807
100
import torch import logging import pandas as pd from torch.utils.data import TensorDataset, random_split from sklearn.model_selection import train_test_split from agent.data.entities.config import FD_CLASS_VALUES, ITEMS_TABLE, CTT3_TEST_ITEM_FILTER, CTT3SIM_LABEL, CTT3_LABEL from agent.classifiers.utils.class_mgmt im...
6d66aa05ec5161d4d5be6980ecba2ac0bb70d4d4a5714aaaf159cc4ba86fb99c
Python
3,807
154
from typing import ( NamedTuple, Set, Dict, Any, Sequence, Type, List, TypeVar, Optional) import abc import copy as cp from neuron_morphology.constants import ( AXON, APICAL_DENDRITE, BASAL_DENDRITE, SOMA ) from neuron_morphology.feature_extractor.mark import ( Mark, RequiresAxon, Req...
6e77125c8d5bc32232119d7c34a51d895fc063a8824483b208d433be78b12ee7
Python
3,807
102
#Include functions to graph different metrics #Imports import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import seaborn as sns import pandas as pd colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] #Create precision-recall curve plot def plot_prc(name, labels, predictions, **kwargs...
4306a94c1d044fea1094bde42b3740e9611c5cf69aca83a25803858ffad37748
Python
3,809
128
# flake8: noqa # isort: skip_file # __lightgbm_start__ import pandas as pd import lightgbm as lgb # 1. Load your data as a `lightgbm.Dataset`. train_df = pd.read_csv("s3://ray-example-data/iris/train/1.csv") eval_df = pd.read_csv("s3://ray-example-data/iris/val/1.csv") train_X = train_df.drop("target", axis=1) train...
1d0f4b1fa63d92f11b67c30e7eeddd0e09926bf6558c39fd74301601dd053d12
Python
3,810
86
import numpy import gym import gym.spaces class GymnasiumWrapper(gym.Wrapper): def __init__(self, env: gym.Env): super().__init__(env) def reset(self, *args, **kwargs): """Steps through the environment and if the number of steps elapsed exceeds ``max_episode_steps`` then truncate. Arg...
d970a9f175f00e04a39ac7ee125d803f88fce321f5dc115104d9a8204c891582
Python
3,810
91
import tensorflow as tf from models.deep_learning.deep_learning_models import DLRegressor from utils.constants import is_spline class BiGRURegressor(DLRegressor): """ This is a class implementing the BiGRU model for time series regression. ! Remember to use regularization techniques such as dropout, weigh...
3fb711de73ca0f4950a99fa82f924c88e46ffe6629f23beda9dab36deef91245
Python
3,811
105
import os import sys sys.path.append('.') import cv2 import math import torch import argparse import numpy as np from torch.nn import functional as F from model.pytorch_msssim import ssim_matlab from model.RIFE import Model from skimage.color import rgb2yuv, yuv2rgb from yuv_frame_io import YUV_Read,YUV_Write device = ...
e7e1d4bf7093fd4f667103cbe25a0b31b5be2acf05bdb67c0f7a10b8defd9a4d
Python
3,812
89
import os import numpy as np import torch from torch_geometric.data import InMemoryDataset from torch_geometric.data import Data from tqdm import tqdm from torch_pgn.data.data_utils import LigandOnlyPretransform, RemoveProximityEdgesPretransform """ Code to load in the processed InteractionGraphs to pytorch geometr...
71b94711be9327931948fae435ec254dab6a0cb013185bafec1b803bfa00e18e
Python
3,813
98
import torch import torch.nn as nn import numpy as np from typing import Optional, Tuple, Union from convex_optim_base.optim_base import BatchParallelDirectSolveProblem from denoise_inverse_alg.hqs_alg import BatchParallel_HQS_X_Problem class BatchNoiselessLinear_HQS_XProb(BatchParallelDirectSolveProblem, ...
adc33ad60f7ae1cf2e202c61b515c72435d6a7dfdbce4d63824c0fe1edf8bdc0
Python
3,813
98
import sys sys.path.insert(0, '..') import matplotlib.pyplot as plt import numpy as np import time from glmhmm import glm, glm_hmm from glmhmm.utils import permute_states, find_best_fit, compare_top_weights from glmhmm.visualize import plot_model_params, plot_loglikelihoods, plot_weights import matplotlib as mpl mpl....
88913c2179ad617604eb3088171c7e32ca5f82dc942bec49b6258184b32adeaf
Python
3,814
130
import math from dataclasses import dataclass import torch @dataclass class Heaviside: """Heaviside surrogate gradient with optional shift. Args: window: Distance between step of Heaviside surrogate gradient and threshold, relative to threshold. """ window: float = 1.0 def ...
bbfde36dd966dae68a9d0dfc14eb724f7211a036f0cccedc541c836759a02e8c
Python
3,815
82
from sklearn.model_selection import GridSearchCV, StratifiedGroupKFold, LeaveOneGroupOut, cross_val_predict from sklearn.ensemble import AdaBoostClassifier from sklearn.preprocessing import StandardScaler from email.message import EmailMessage import smtplib, ssl import numpy as np import datetime import pickle # This...
9bea7b7b7c43fe829e95b2214a6cdfdbcbe62f537abb6d7e92ff63ac5567a100
Python
3,816
132
# Before using polynomials to solve for the inflection points of the injury degree-injury # threshold curve, it is necessary to determine an appropriate fitting range. # The impact cases of two types form two composite injury degree-injury threshold curves. # 50 Head-concrete impacts form the first injury degree curve...
db641aff5fda82618b7a2fa43916bf00b01c3d27860e1844658203e0b9ab52d4
Python
3,816
119
"""Base collector with common functionality.""" import logging from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional import hashlib import json from sqlalchemy.orm import Session from src.models.base import get_db from config import settings logger = logging.getLogger(__name__) class B...
00251007334609006ea0079c9097f52c66309bc1ed3db442c76cd50a87466f8b
Python
3,818
102
import torch def print_model(model): blank = ' ' print('-'*90) print('|'+' '*11+'weight name'+' '*10+'|' \ +' '*15+'weight shape'+' '*15+'|' \ +' '*3+'number'+' '*3+'|') print('-'*90) num_para = 0 type_size = 1 ##如果是浮点数就是4 for index, (key, w_variabl...
930d0177e3ebf9a1027b2ad3f2efdc4ad488cefc0c1dda6506a850364eb7754d
Python
3,818
87
import os import argparse import numpy as np from ont_fast5_api.fast5_interface import get_fast5_file def read_fast5(file_dir, min_length, size, ids=None): file_count, reads_count, total_len = 0, 0, 0 accepted_reads, rejected_reads, short_reads = 0, 0, 0 reads_array = [] for root, _, files in os.walk(...
ca0a4cb5bada6af0b484dedfb8c85bea053ef751649c993b8bc3ed0b2a7cf35d
Python
3,820
114
""" 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 import random import numpy as np import pytest from ase import Atoms from ase.data import covalent_rad...
5ecfdbace40610484101c3710d6adcab6c8f0de394f350e720e9d7fb8ccc5660
Python
3,822
116
import logging import os import stat from ray.autoscaler._private.aliyun.utils import AcsClient # instance status PENDING = "Pending" RUNNING = "Running" STARTING = "Starting" STOPPING = "Stopping" STOPPED = "Stopped" logger = logging.getLogger(__name__) def bootstrap_aliyun(config): # print(config["provider"]...
4859497d6a03aa0af91901fe8e9c41b63bc92b98a5319ccd0a7e6d85c8cf47bb
Python
3,824
102
""" 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 import os import hydra import pytest import torch from omegaconf import OmegaConf from fairchem.core....
de4144d058dc95492213378eb8ddfd1760b06fc164ad893fa01aed7ffe4cc819
Python
3,825
129
import contextlib import itertools import json import os import subprocess import sys import tempfile import pytest import pfrl @contextlib.contextmanager def work_dir(dirname): orig_dir = os.getcwd() os.chdir(dirname) yield os.chdir(orig_dir) def test_is_under_git_control(): with tempfile.Te...
612921d1db6bbd046ce73950101e043e1532de830c484bf6c926e9e26d24b7a7
Python
3,826
88
import pandas as pd from src.commons.process_dataframe import rename_df_col, insert_new_col, insert_new_col_from_two_cols from src.commons.process_number import cal_SEM from src.ms2_uniform_prolific_1_main import get_percent_triplets def get_samplesize(winsize): if winsize == 0.4: return 29 else: ...
c5d01bf088440c27571b1a5325032d75a711fef65b591d05a1cfec7b76025115
Python
3,827
121
import sys import os import logging import copy as cp from typing import List, Tuple, Optional import numpy as np from scipy.interpolate import griddata import xarray as xr from argschema import ArgSchemaParser from neuron_morphology.transforms.pia_wm_streamlines._schemas import ( PiaWmStreamlineSchema, OutputP...
db2d97dda8a71aa52076628c82c96ffd3f68e09cd3ea91fc36586e1b7f886bb8
Python
3,828
106
from enum import Enum, auto from typing import Any, Callable, Dict, List, Optional, Union from ray.autoscaler._private.cli_logger import cli_logger class CreateClusterEvent(Enum): """Events to track in ray.autoscaler.sdk.create_or_update_cluster. Attributes: up_started : Invoked at the beginning of ...
a957fab4a9a97822d485d0986339d23c5d93e2af2dd7b59d82daffabc2619fe5
Python
3,829
123
import numpy as np import matplotlib.pyplot as plt import pandas as pd import time import torch from pyJoules.energy_meter import EnergyContext from pyJoules.device.rapl_device import RaplPackageDomain, RaplDramDomain from pyJoules.device.nvidia_device import NvidiaGPUDomain from pyJoules.handler.pandas_handler impor...
3efa4e8354f84d5ae05873e6ab74ce93ecebac22865c199128465568526eff2f
Python
3,830
108
import torch from torch import nn from torch.distributions import Normal from lop.utils.miscellaneous import net_init, fc_body, register_hook, kaiming_init, xavier_init, lecun_init, gaussian_init class Policy(object): def action(self, x, to_log_features=False): """ :param x: tensor of shape [N, 1...
c04c3d672e24b2527c9a590b137c9f6f7c53fadfddee55697c5c31f4984ab57c
Python
3,830
75
import torch from torch._dynamo import OptimizedModule from torch.nn.parallel import DistributedDataParallel as DDP import torch.distributed as dist from nnunetv2.utilities.checkpoints import load_network_weights from nnunetv2.utilities.ddp import get_ddp_topology def load_pretrained_weights(network, fname, verbose=...
7dc6d84c7a4f5939fda5ebc2d7a12ef313002ef9c01539706b98d80681d7b638
Python
3,831
128
# -*- coding: utf-8 -*- # """ std_manta.py Standardize a Manta record. """ from collections import deque from svtk.utils import is_smaller_chrom, parse_bnd_pos, parse_bnd_strands from .standardize import VCFStandardizer @VCFStandardizer.register('manta') class MantaStandardizer(VCFStandardizer): def standardiz...
aa18daf3cc613e5281803581c0e067180a5ce0f4289354d68214e2b9831d96c6
Python
3,832
96
from itertools import groupby import numpy as np import pandas as pd def fasta_iter(fasta_name): with open(fasta_name) as fh: faiter = (x[1] for x in groupby(fh, lambda line: line[0] == ">")) for header in faiter: headerStr = header.__next__()[1:].strip().split()[0]#Entire line, add .spl...
b98a22909395b8bb503850d2c8489d28681a9a0c2e54ca4d56a06c5aedf434e1
Python
3,833
112
""" 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 import logging import os from typing import TYPE_CHECKING import torch from torch.profiler import Prof...
83cc2fc295e3a0b4ac82eb216beadee5007065fe11be004aad4e4fdb584201f6
Python
3,835
113
r"""Layer B — ESM-2 protein embeddings for downstream ML. Turn a list of protein sequences into fixed-length vectors (mean-pooled per-residue representations from an ESM-2 layer). These feed any downstream model — enzyme property regressors, clustering, function transfer. """ from __future__ import annotations from ...
db43cace88cbdcea840052759d3cf24057f64eab0c3cff2753ee3e1c4e20bdcf
Python
3,836
71
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'scripts/GUI/ui/ordering_form.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt...
1b28e62bf2f0558e0241f9211919a727709c4b78b139d1899cbc48fcb060a354
Python
3,837
149
#!/usr/bin/env python3 import rospy from std_msgs.msg import MultiArrayDimension,Int8MultiArray import os import cv2 from cv_bridge import CvBridge import ros_numpy import numpy as np import PIL.Image from torch2trt import torch2trt from torch2trt import TRTModule import torch from torchvision import transforms fro...
ac82b84bdc31cfa686813165d8a997fee4a1dc4af9f04dc20f2c4861d74c0813
Python
3,837
115
#!/bin/env python import argparse import pysam import sys from typing import Optional, List, Text, Set def read_variant_ids(path: Text) -> Set[Text]: """ Reads a list of variant IDs from a file (one per line). Parameters ---------- path: Text path to file containing variant IDs Retu...
b3342ddac2d68acc58328cc530ff27e7f7bb5da9b3a1087e0cdcb697ad4e8f3b
Python
3,837
117
#!/usr/bin/env python # encoding: utf-8 import numpy as np def mw2d(dim,missingAngle=[30,30]): mw=np.zeros((dim,dim),dtype=np.double) missingAngle = np.array(missingAngle) missing=np.pi/180*(90-missingAngle) for i in range(dim): for j in range(dim): y=(i-dim/2) x=(j-di...
87f1caf1be9899f2f2b5e1ecfeb00fcd66e59a5b5cb75100da9b0592490ba06d
Python
3,839
108
#!/usr/bin/env python #!/usr/local/bin/python import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import speech_data sess = tf.InteractiveSession() batch_size=100 width=height=64 dim=width*height # # Create the classifier model x2 = tf.placeholder("float", [batch_size, width, height], name='im...
3fcbf4285f253ab7236f743d464745b57e6ab59bf49e08348b0411da9a001636
Python
3,840
111
from dDR.dDR import dDR from dDR.PCA import PCA from dDR.utils.decoding import compute_dprime import numpy as np def get_noise_axis(X, stims): """ center X then compute first PC """ nc = X[stims[0]].shape[0] Xa = (X[stims[0]] - X[stims[0]].mean(axis=1, keepdims=True)).reshape(nc, -1) for s in s...
6e79a9bacf442386b1bc5e310089cbfe1767f4d8497690d3fde371f24c9d010d
Python
3,840
99
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
b08f0a3a0a000709030b46b4de08942663804ee60baf8ff54d3900b27cacca4c
Python
3,840
102
import logging import json from agent.data.entities.config import BACKUPS_PATH from agent.data.sql.sql_mgmt import execute_query, execute_read_query, select_fields_where, get_connection logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(...
495ad023f3dc385982257dc0631dc2dfb216e64db6e80bddccefdea4c11160ce
Python
3,841
96
import os import torch def train_one_fold(fold, args, model, logger, train_loader, val_loader, optimizer, loss_fn, scheduler): # check if model path exists os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu path='./checkpoints/stage_{}/classes_{}/fold_{}'.format(args.stage, args.num_classes, fold) if not o...
baab340fd9c8af985d441545b9d794852077e468a151009d537a59c2e1723e2f
Python
3,841
117
import numpy as np import pandas as pd from tqdm import tqdm import scipy.sparse as sp from .Model import Model from .utils import Transfer_pytorch_Data import torch import torch.nn.functional as F def train_BINARY(adata, pos_weight=10.0, hidden_dims=[512, 30], ...
bee5387f51f44dc4cbb29b7f9c0b943cb2501ee16de5e9ba64d77dc977a36bc3
Python
3,841
123
from dataclasses import dataclass from typing import Callable, List, Optional, Union import torch class BackwardClass: @staticmethod def backward(ctx, grad_output: torch.tensor): """""" (v_mem,) = ctx.saved_tensors grad = ctx.surrogate_grad_fn(v_mem, ctx.spike_threshold) grad_...
f702a45a560fb7c87bbfeea0896ef79b04b8eb57ca060281bc42bebe24bd4d70
Python
3,846
99
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # 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 ag...
d6667a3594fc1c0acfc0d551774461f1ac1613dabee9af3fea631d73f4b21f8d
Python
3,847
125
from modulefinder import Module import torch import nni import sys import torch.nn.functional as F import nni.retiarii.nn.pytorch as nn from nni.retiarii import model_wrapper from nni.retiarii.evaluator import FunctionalEvaluator import nni.retiarii.strategy as strategy from architecture import gnn_list, gnn_list_prot...
09864529e475355b90a2ede4b6986a01fb17cbc63cec646fb8aef7f367222afc
Python
3,849
119
"""Tests for scoring.py""" import pytest import numpy as np import torch class TestLossScoring: @pytest.fixture(scope="module") def data(self, classifier_data): return classifier_data @pytest.fixture(scope="module", params=["mean", "sum"]) def reduction(self, request): return request...
28a554d4b9b914b00ceaaca52357f64306de0d7e74d58f2fe6dd7e1601c8ed50
Python
3,850
70
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # and Applied Computer Vision Lab, Helmholtz Imaging Platform # # 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 L...
2dda4369e1e1876712fb76922cec9a935461e2b74457e17bc1d1ffba877390ea
Python
3,850
126
# -*- coding: utf-8 -*- """ Created on Fri Jul 12 15:57:00 2019 @author: ju-bar Peak functions and functions calculating their jacobians This code is part of the 'emilys' repository https://github.com/ju-bar/emilys published under the GNU General Publishing License, version 3 """ import numpy as np # %% def gauss_2d...
3b319660f1751d966498d4ce4180cff4dad071ab4677880b86bae384fd701a00
Python
3,850
117
import argparse import pickle import numpy as np import pandas as pd import os from collections import defaultdict from queue import PriorityQueue from pathlib import Path MAX_DIST = 40000 MAX_PARTNERS = 8 def parse_argument(): parser = argparse.ArgumentParser() parser.add_argument('--ensg2tss', required=Tr...