sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
4f9f122f8bf987b90181afada5e63fdc5eab818255dd69b5fb9616183cce22a6 | Python | 8,111 | 249 | import sys
import numpy as np
from .traj import Trajectory
from .. import config, printit
__all__ = [
"TrajectoryLoader",
]
class TrajectoryLoader:
"""
A class to systematically load trajectories for further processing in the pipeline.
Parameters
----------
trajs : str or list
A list of trajecto... |
c8f7f34e61d93c0be0fae26f10cd02d4fd2f31e220de47ca09019ffee0691205 | Python | 8,111 | 271 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_inplanes():
return [64, 128, 256, 512]
def conv3x3x3(in_planes, out_planes, stride=1):
return nn.Conv3d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
... |
b7de6ac61007b3f8852711d7e37fb3d5acfea22413d441b48d06a107119015ad | Python | 8,121 | 196 | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# 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 re... |
eff9ebab40062e2ab4ed1fb8f6a56562c86b26018a32cdd16c5317cb896cbc75 | Python | 8,122 | 230 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import torch.nn as nn
from torch_geometric.nn import MessagePassing, global_mean_pool
from torch_geometric.nn.models.schnet impo... |
2b949f4538e59d6a1b237f22efecee982569633c50973cf55c46ae0d3d41c030 | Python | 8,126 | 228 | import pytest
import pytest_mock
from ipaddress import IPv4Network, IPv4Address
from CybORG import CybORG
from CybORG.Shared.Enums import SessionType
from CybORG.Simulator.Actions.GreenActions.GreenLocalWork import GreenLocalWork
from CybORG.Simulator.Actions.ConcreteActions.PhishingEmail import PhishingEmail
from Cyb... |
0ef41356f763e7d611639edb04cf5d897e14732f9671b86364f91e7587b32e7b | Python | 8,127 | 220 | import logging
from collections.abc import Callable
import holoviews as hv
import numpy as np
from bokeh.models import BoxSelectTool, PanTool
from .shading import FIT_COLOR, shade_trace
logger = logging.getLogger(__name__)
# Height of the single trace the marking page shows, taller than a stacked panel because
# it... |
678ab35fefb19b981801219a4518a9d9c39ea5a7a6ddebd3908ba99e9b5a0808 | Python | 8,127 | 179 | import types
import panel as pn
import pytest
from guppy.frontend.store_labeling_selector import StoreLabelingSelector
class FakeNotification:
def __init__(self, message, duration):
self.message = message
self.duration = duration
self.destroyed = False
def destroy(self):
sel... |
080afa02a9631bc2ea816566f8dae47b232862353a50f6b8369adf47698bfb96 | Python | 8,133 | 305 | crop_size = (
512,
512,
)
data_preprocessor = dict(
bgr_to_rgb=True,
mean=[
123.675,
116.28,
103.53,
],
pad_val=0,
seg_pad_val=255,
size=(
512,
512,
),
std=[
58.395,
57.12,
57.375,
],
type='SegDataPreProcesso... |
27378a080fad99351411720d4f2d788c01b3b415154a9295c52f02e629697756 | Python | 8,135 | 305 | crop_size = (
512,
512,
)
data_preprocessor = dict(
bgr_to_rgb=True,
mean=[
123.675,
116.28,
103.53,
],
pad_val=0,
seg_pad_val=255,
size=(
512,
512,
),
std=[
58.395,
57.12,
57.375,
],
type='SegDataPreProcesso... |
aa530dac0506297d8d1a9af593e3b74e913da7164b16e6fca3aba06b2a840aa0 | Python | 8,136 | 240 | """
Helper script to prepare for releasing XGBoost JVM packages to
Maven Central.
## Prerequisite
1. You must have the right to upload artifacts to the Maven Central repo.
If you do not, contact Hyunsu Cho (chohyu01@cs.washington.edu) so that
he can contact Sonatype on your behalf in order to add you as a
"p... |
fb0c789c94ed9c23c823e08c69406c7557de387f25d0b8243dc2c11fd2d329d1 | Python | 8,136 | 225 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
from torch_geometric.nn import DimeNet
from torch_scatter import scatter
from torch_sparse import SparseTensor
from ocpmodels.c... |
0834a76a8015d49872abca45d2300ff2db84bf28c37a5e73ea4ae223c11c0702 | Python | 8,138 | 218 | import os
import copy
import numpy as np
from . import warning, Image, Overlay
from .transform import Transformable, LinearTransform
class Surface(Transformable):
'''Triangular mesh topology represented by arrays of vertices and faces.'''
def __init__(self, vertices, faces=None, hemi=None, geom=None):
... |
84be9c7e1f0e6fe2906a6d31658674fc73f33984b23366b85c595ec75321af03 | Python | 8,148 | 210 | import numpy as np
import lmfit
from copy import deepcopy
import pandas as pd
from src import config as cfg
from src import helper_functions as hf
#import xarray as xr
#####################################
def get_bounds_dict(min_t_units, max_t_units):
bounds_dict = deepcopy(cfg.bounds_dict
)
for p... |
8c41712ef0156f86e093bb5b162d202415b4256d9d0b4b866333b0b5c3ae71dc | Python | 8,150 | 243 | import numpy as np
import random
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import time
import os
import random
from tqdm import tqdm
from abc import ABC, abstractmethod
from collections import defaultdict
import math
from collections import namedtuple
from get_sc import *
# Set the... |
c032dd920b677c4583092ac2d73060e66a04a37b41184b8efdc40338cf710b2c | Python | 8,159 | 260 | import sys
import numpy as np
import pytest
from hypothesis import given, settings, strategies
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.data import check_inf
from xgboost.testing.data_iter import run_mixed_sparsity
from xgboost.testing.quantile_dmatrix import (
check_categorica... |
460432bcc8046727b4824454ae957fa1e271857e936633f47a6aa492234a21f5 | Python | 8,161 | 246 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import glob
import os
import os.path as osp
import shutil
import tempfile
import zipfile
import mmcv
import numpy as np
from mmengine.utils import ProgressBar, mkdir_or_exist
from PIL import Image
iSAID_palette = \
{
0: (0, 0, 0),
1: ... |
5c22174b21a1db83d85d87f59bb225c82f1e4f0295942937cc627bc483d3fa4d | Python | 8,162 | 234 | # -*- coding: utf-8 -*-
#
# Spinal Cord Toolbox documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 26 11:35:58 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated... |
039eeda0b19c2e8a1df623c10c216ed24539e8bc57a61bbeb2f82432465ba1aa | Python | 8,167 | 175 | #!/usr/bin/env python
"""
Preprocessing workflow:
1) assembly metagenomic shotgun sequencing reads
2) identify ORFs
3) build non-redundancy gene catalogs
4) calculate reads counts table for gene catalogs
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person ob... |
99b8ed405c6bad307880fdb5a72f6beba3de8c253c54ec318f4ed6e02a895481 | Python | 8,167 | 204 | """Step 6 orchestration: the Input Metadata pages.
Opens one window per selected session, each editing that session's single
self-contained ``nwb_metadata.yaml`` (saved in the session's output directory).
Modeled on the Storenames GUI: structured widgets feed a YAML ``CodeEditor`` that
is the authoritative artifact, a... |
5a90aa0e9c991172acf24cabdc8615858cec792579ed6f8a409b86078518cf5d | Python | 8,170 | 219 | import re
import subprocess
import ase
import numpy as np
from ase.calculators.calculator import Calculator, all_changes
class RestorativeCalculator(Calculator):
implemented_properties = ["forces", "energy", "energies"]
"""
'zero_energy_radius' if > 0, then atoms within this radius of the origin will exp... |
aadc3f4e85d5904b6ccb1d015af6435762f831bff58d080aff68df01ecfb2bfa | Python | 8,172 | 250 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import random
import json
import numpy as np
import pdb
class Dataset(torch.utils.data.Dataset):
def __i... |
23be18198e627ec2fed94c4151d32db51b501277433236d7b1f45c3d929086f3 | Python | 8,173 | 161 | import sys
import os
import nibabel as nib
import numpy as np
from fsl.wrappers import fslreorient2std
import logging
import re
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Get the argument passed from the bash script
sub = sys.argv[1] ... |
1448694738d501a22c2303f0523b1a727bce69c7d819bc3a45448c5b9c927ca5 | Python | 8,176 | 195 | import torch
import numpy as np
from tsnecuda import TSNE
from sklearn.decomposition import PCA, FastICA
import torch.nn.functional as F
from tqdm import tqdm
import sys
from ..utils.utils_new import apply_ctf
import matplotlib.pyplot as plt
from torch.utils.data import TensorDataset, DataLoader
def compute_dimension... |
fb2d70caf8182b6b948ad77c1da2391911e7c3a615e2fd9e503005cdaa3920e5 | Python | 8,180 | 265 | import os
import subprocess
import pandas as pd
from pathlib import Path
from typing import Dict, Any, List, Optional
from concurrent.futures import ThreadPoolExecutor
from ..logger import logger
from .snp_calling import SNPCallingError
import numpy as np
import gzip
class PhasingError(Exception):
pass
def validat... |
e5c9900fb004e3cdcd91d21e3165e628b77ec63950c9a758f631d6889ecde428 | Python | 8,183 | 264 | #!/usr/bin/env python
"""
MeteWIBELE: prepare_uniprot_taxonomy module
Format the taxonomy lineage information from UniProt taxonomy file
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files... |
eafc1b6370804f026784d816a6db7f592941d65c6ccc6d49be8f8a7bb0ec8f63 | Python | 8,185 | 195 | # coding=utf-8
# Copyright 2021 The IDEA Authors. All rights reserved.
# 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 a... |
035de02579494cfbbcdcf57a95402f9ac9f202d185889561eab84e68617703af | Python | 8,187 | 268 | """Shared test utility functions and classes.
These are importable helpers (not pytest fixtures).
Fixtures live in conftest.py.
"""
import asyncio
from typing import Any
import msgpack
from fastapi_users.password import PasswordHelper
from httpx import AsyncClient
from pydantic import BaseModel
from sqlalchemy.ext.a... |
9f9cb8a50e8c26947876e3f31f0e0c6f0760d16e7a1106f9c51212bd0b366821 | Python | 8,191 | 192 | #!/usr/bin/env python
import torch
import numpy as np
import pandas as pd
import time
import os
from models.model import RNN
from MCMG_utils.data_structs_fragment import Vocabulary, Experience
from properties import multi_scoring_functions_one_hot_dual
from properties import get_scoring_function, qed_func, sa_func
... |
07f802dd2672ce73f2e4123952262b1fe44a262c562f620eea91b5d015054610 | Python | 8,198 | 164 | import pandas as pd
import numpy as np
import torch
from sklearn.model_selection import LeaveOneGroupOut
from sklearn.metrics import r2_score
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from natsort import natsorted
import glob
import argparse
import os
def parse_arguments():... |
4ea272dd12f55aada38300ad33d83724aecfcce539275c690687afa6746d1942 | Python | 8,199 | 175 | import time
from builtins import print
import sys
import os
import torch
import argparse
import json
import pytorch_lightning as pl
from transformers import MT5Config, MT5Tokenizer
from pytorch_lightning import Trainer, loggers
from transformers import MT5ForConditionalGeneration
from pytorch_lightning.callbacks import... |
157eee764023b04c8cd2875812b00a58f7e13d25545977b400d1d1ab8a81ca63 | Python | 8,203 | 210 | #!/usr/bin/env python
import os
import sys
import traceback
import json
import argparse
import random
import itertools
try:
import papermill
except ImportError:
raise ImportError('Please install papermill to batch-process'
' l5pc_validate_neuron_arbor notebook.')
import logging
logging.... |
50958fedc802a8d5a1a51c87be215ce857f74c447b1c0a08a8235d36291c86ff | Python | 8,209 | 231 | """ Adapted from https://github.com/mlcommons/GaNDLF/blob/master/GANDLF/metrics/segmentation.py"""
import SimpleITK as sitk
import torch
import numpy as np
import torch.nn.functional as F
from scipy.ndimage import _ni_support
from scipy.ndimage.morphology import (
distance_transform_edt,
binary_erosion,
g... |
24b48e5b68d16eb4da843071c68c46bf72f77c1a9546b151c1ed32f7797d10d6 | Python | 8,210 | 261 | from __future__ import annotations
import json
from typing import Annotated
import typer
from zndraw.schemas import (
GeometriesResponse,
GeometryCreateRequest,
GeometryResponse,
StatusResponse,
)
from .connection import (
PasswordOpt,
RoomOpt,
TokenOpt,
UrlOpt,
UserOpt,
cli_... |
85660bcd4dbcb4af29ce5f32e6e29a9f5214deb54442ccc8c82a8015691df378 | Python | 8,210 | 234 | from typing import Dict, List, Optional, Tuple
from pathlib import Path
import torch
from torch import nn
from torch_geometric.loader import DataLoader
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, StepLR
from pytorch_lightning import LightningModule
from torchmetrics import MeanAbsoluteError, Mea... |
1d21f5db0d6042c7895327009da22469c4ff9e3980409b0d4d38a74f689450ae | Python | 8,211 | 206 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.lines import Line2D
from glob import glob
import scienceplots
import matplotlib.gridspec as gridspec
import scipy.stats as st
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.colors as col... |
ed5a3a4fb6056cb6f86c6952d1571dae8deea5c021b5cc4c7ddd62463f0c8b56 | Python | 8,214 | 219 | from .module_refined import BaseGraphNetwork, BaseLinearModel, GraphStructureDecoder, LinearDecoder
from .utils_ODE import get_step_size, LatentODEfunc
from torchdiffeq import odeint
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from typing impor... |
d0d1e92ee1253190cd23827d904353f3a2ee74c5faa071f49ec2758e19cd191b | Python | 8,230 | 256 | from collections import defaultdict
import logging
import math
import os
from pathlib import Path
import subprocess
import SimpleITK as sitk
from pyalfe.data_structure import (
PipelineDataDir,
PatientDicomDataDir,
Modality,
Orientation,
)
from pyalfe.tasks import Task
from pyalfe.utils.dicom import (... |
9e3604dce8ef5fcbf1969cf0be61de1cb396455fa337bbc1ef22cbd1f4613886 | Python | 8,236 | 201 | from pathlib import Path
import snakemake.io
from collections import defaultdict
import itertools
class ParsedConfig:
OUTPUT_TYPES = ['full', 'embed', 'knn']
def __init__(self, config):
# TODO: define and check schema of config
self.ROOT = Path(config["ROOT"]).resolve()
self.DATA_SC... |
7b1ec76ffd9b220b666252d5f409f9b4ac92ef22b386ed1b243a00661d73d65a | Python | 8,238 | 232 | import math
from collections import Counter
from torch.optim.lr_scheduler import _LRScheduler
import torch
class MultiStepRestartLR(_LRScheduler):
""" MultiStep with restarts learning rate scheme.
Args:
optimizer (torch.nn.optimizer): Torch optimizer.
milestones (list): Iterations that will d... |
0ec23816d7275b3b098e7f860bde1a1820505900aae5737a91e2de5b47f60caf | Python | 8,239 | 243 | # -*- coding: utf-8 -*-
import re
import cProfile
import pstats
import logging
from traceback import format_exc
from datetime import datetime
from django.http import JsonResponse, Http404
from django.conf import settings
from guardian.utils import get_anonymous_user
from rest_framework.authentication import TokenA... |
b7592c18b0842bc4b478b306d3031282ab1492bf27ce6bd9acab74b093f32b03 | Python | 8,240 | 256 | """E2E tests for filesystem provider registration, listing, and read flow.
Tests cover: register_fs → list providers → read (long-poll → 200).
"""
import time
from urllib.parse import urlencode
import fsspec
import pytest
from pydantic import BaseModel
from zndraw import ZnDraw
from zndraw_joblib.schemas import Job... |
ecdc1d426d871784c018f94e0d2fe3f59c12dec26bc591609205b5015c00bf06 | Python | 8,241 | 256 | import os
import csv
import json
def get_file_basename(filename):
"""A util function to get the basename of a file without the extension.
Args:
filename (str): The file name.
Returns:
str: The basename of the file without the extension.
"""
return os.path.basename(os.pat... |
f0e39e08307ec07967c7a1e79c2cda3ee5e36b58b5cb17ab171095987223a9b4 | Python | 8,245 | 160 | from collections.abc import Container
import pandas as pd
from ..client import inject_client
from ..utils import trange
from .neuroncriteria import NeuronCriteria, neuroncriteria_args
from .general import fetch_custom
from .connectivity import fetch_adjacencies
@inject_client
@neuroncriteria_args('criteria')
def fe... |
802a5fa90581a5dbed55fe27174a0ee00b3e4071e478fdcbe4530313aa05951e | Python | 8,246 | 194 | # -*- coding: utf-8 -*-
import json
import sys
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.db import connection
from catmaid.models import UserRole, Textlabel, TextlabelLocation
from catmaid.fields import Double3D
from catmaid.control.authentication import requires_user_role
from catm... |
004aa6e8c41aad6ac773f1b1aacb06e49963f1e506e171df78d2aee87a7d022a | Python | 8,249 | 194 | import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
from SAC.utils import soft_update, hard_update
from SAC.old_model import GaussianPolicy_ActionGNN, Critic_GNN
class SAC_ActionGNN(object):
algo_name = "SAC ActionGNN"
def __init__(self,
ac... |
19a8349a5f767e3cbd88dcf4532eb2e3e922283d26d3abcc8658638c76650ded | Python | 8,250 | 246 | import argparse
import os
# Functions are all taken from Willie Boag's cliner code `documents.py` at
# https://github.com/text-machine-lab/CliNER/blob/5e1599fb2a2209fa0183f623308516816a033d4f/code/notes/documents.py
def convert_to_i2b2_format(tok_sents, pred_labels, mode=None):
"""
Purpose: Return the given ... |
3e168d7765bf03fb0560a7279cc0a815c32000703df98fff289576cc786c69d2 | Python | 8,255 | 246 | #!/usr/bin/env python
from __future__ import print_function
import os
import sys
from collections import OrderedDict
"""
Note: utilities used by MetaWIBELE-characterize module
"""
# ---------------------------------------------------------------
# helper functions
# --------------------------------------------------... |
c773947cf4d36a7be8b775d32e36c8cef93fa17e50bfb73560cdb7dadb92c2fc | Python | 8,264 | 219 | import json
import os
import gzip
from kgx.graph.nx_graph import NxGraph
from kgx.sink.trapi_sink import TrapiSink
from tests import TARGET_DIR
def test_write_trapi_json():
"""
Write a graph as TRAPI JSON using TrapiSink.
"""
# Create a test graph
graph = NxGraph()
graph.add_node("A", id="A",... |
f4ae9f4045da9e93db4d3adde69c7897dff4e31a74777ce7883310fccf443cfc | Python | 8,265 | 264 | import os
import tarfile
from typing import Optional, Dict, Set, Any, List
from ordered_set import OrderedSet
from kgx.sink.sink import Sink
from kgx.utils.kgx_utils import (
extension_types,
archive_write_mode,
archive_format,
build_export_row
)
DEFAULT_NODE_COLUMNS = {
"id",
"name",
"ca... |
36a2d2e7f43c21512d438c3329eb1d52770c4e156dfe3b146e6b1360b1d17afa | Python | 8,270 | 200 | from pathlib import Path
import numpy as np
import pandas as pd
import panel as pn
import pytest
from guppy.analysis.io_utils import write_hdf5
from guppy.analysis.standard_io import (
write_binned_covariates_to_hdf5,
write_binned_metrics_to_hdf5,
write_covariate_correlations_to_hdf5,
)
from guppy.fronten... |
8fa60aad06887507f41af748c992a39b3399497c0df7f7cd65ae8ba0b3abb8ea | Python | 8,271 | 250 | from collections import OrderedDict
from typing import List, Optional, Any, Union, Dict, Tuple
import rdflib
from linkml_runtime.linkml_model.meta import Element, SlotDefinition, ClassDefinition
from cachetools import cached, LRUCache
from rdflib import Namespace, URIRef
from rdflib.namespace import RDF, RDFS, OWL, SKO... |
6f9b02e71ec59c0ecf52e5b9f766c81dec034bd022716e5f3cc953683ee20ff5 | Python | 8,272 | 234 | """Unit tests for label-selection logic in write_compendium().
The helper under test is choose_preferred_name(), which is the extracted core of
the label-selection algorithm previously embedded in write_compendium().
Issue context:
https://github.com/NCATSTranslator/Babel/issues/597 — original report: good names d... |
3c9a2b46b81a54aafa349ecd8da619eeb4254cafe958fc5f9c66a545493b8bbd | Python | 8,276 | 234 | #!/usr/bin/env python
"""Run simple cell optimisation
This optimisation is based on L5PC optimisations developed by Etay Hay in the
context of the BlueBrain project
"""
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free... |
8a44a9c31a4b4cbdac145ddf40c6ce74be81208d8ddd3b17246dbcc992aa02cb | Python | 8,277 | 230 | """Python net specification.
This module provides a way to write nets directly in Python, using a natural,
functional style. See examples/pycaffe/caffenet.py for an example.
Currently this works as a thin wrapper around the Python protobuf interface,
with layers and parameters automatically generated for the "layers"... |
47ee3488a9c1ae9b6da2f6df7d084a06e3d8d8a412974ddcb82707725b697a15 | Python | 8,285 | 185 | import logging
import os.path
import numpy as np
import torch.nn
import wandb
import merlinth
from time import time
from dl_utils import *
from core.DownstreamEvaluator import DownstreamEvaluator
from data.t2star_loader import RawMotionBootstrapSamples
from projects.recon_t2star.utils import *
from mr_utils.parameter_f... |
b571dde0527f6f0c2b68b164bfadfebe95b5b7e8e2a345367ae618f894f593fe | Python | 8,285 | 241 | ###########################################################################################
# Atomic Data Class for handling molecules as graphs
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
########################################################################... |
45dc5033cdb796dd3fddfbe3947c96b4855d4c4f65efb639cdfa1f853099fcae | Python | 8,291 | 194 | import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
import csv
from verstack.stratified_continuous_split import scsplit
# Function to load the embeddings from a CSV file
def read_c... |
82a8b01e338439edd311d96697b1397431e0c7ef2865ccef053d8a3db9cc3a1b | Python | 8,291 | 213 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import transformers
import numpy as np
from pathlib import Path
import torch.distributed as dist
from torch.ut... |
aa9ef51ab4102758b1b55b49649df929b4ec80b3966537138476b6fde02e7fe6 | Python | 8,293 | 227 | #!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# 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 requi... |
439e6553a28f71a63513d82866dfc479a3eea2bf3e14db315ee2360c2cc7a82a | Python | 8,294 | 252 | import os
from medperf import config
from medperf.exceptions import ExecutionError, InvalidArgumentError, InvalidEntityError
from medperf.tests.mocks.benchmark import TestBenchmark
from medperf.tests.mocks.cube import TestCube
from medperf.tests.mocks.dataset import TestDataset
from medperf.tests.mocks.execution import... |
eb2f0963769926e303a832874d01c7d854596fe9839f400bcaf3c596110790b3 | Python | 8,298 | 255 | # Copyright (c) OpenMMLab. All rights reserved.
# Originally from https://github.com/visual-attention-network/segnext
# Licensed under the Apache License, Version 2.0 (the "License")
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmengine.device import get_device... |
301b175d8afbf504bf0c6ad5bad08b51118c5c583583fcb209060a64dae90b8f | Python | 8,299 | 172 | import os
import shutil
import sys
from sklearn.metrics import mean_squared_error
# Dynamically append project root to sys.path
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)
from CustomizedDateLoader import *
from DeepChemModels... |
501e31834692b060eae1b6d54ca23d25226a7511b90465b63344ba180eef15d4 | Python | 8,299 | 221 | #!/usr/bin/env python3
"""
Module for managing pytorch dataset of particles.
"""
import os
import warnings
from typing import Any, List, Dict
import numpy as np
import mrcfile
from scipy.ndimage import shift
import torch
from torch.utils.data import Dataset
from .ctf import ContrastTransferFunction
class Particle... |
31034fc752f99532b0df42fad0998be244692d02e8735e1fd06ef2b58314f311 | Python | 8,303 | 225 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
the ProcessVideo class
@author: Andrei Istudor andrei.istudor@hu-berlin.de
"""
import numpy as np
from EthoCNN import EthoCNN
import torch
from pandas import DataFrame
#from DataReaderAV import DataReaderAV#, mapAnn
#from StackFrames import getTestTensors
from F... |
a9903f7398bc9ab7053c1a3f066413c12a6be8d973f332c8c23a1bd6532f47fb | Python | 8,311 | 211 | #!/usr/bin/env python
#
# Function to segment the spinal cord using convolutional neural networks
#
# Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import os
import sys
from typing import Sequence
import textwrap
from spinalcordtoolbox.utils.shell import SCTArgumentP... |
9498e4d4acd110f5a4a7178bb54818f458cb0869be0a10501266222911d8ac4d | Python | 8,312 | 227 | import pickle as pkl
import networkx as nx
import numpy as np
import scipy.sparse as sp
import torch
from sklearn.metrics import roc_auc_score, average_precision_score
def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
def load_data(dat... |
325bea3cdb22f36998a24daa37710cf8e169f37c8fc5460c71a32b967e0b53a1 | Python | 8,320 | 205 | import os, csv
import argparse
import pandas as pd
import torch
import torch.nn as nn
import torchvision
from models import model_attributes
from data.data import dataset_attributes, shift_types, prepare_data, log_data
from utils import set_seed, Logger, CSVBatchLogger, log_args
from train import train
... |
996927b7dd706de1af758a22898a46dfd174ec1cfc74d8f151b8a3069f62c3fa | Python | 8,322 | 198 | import numpy as np
import pandas as pd
import scanpy as sc
from anndata import AnnData
from sklearn.metrics.pairwise import euclidean_distances
from scipy.stats import spearmanr
from scipy.linalg import eigh
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy import lin... |
2f4a964c23c76bd54942894ac7066ce0caa6466974e507b3946405ddced9d94d | Python | 8,325 | 205 | import cv2
import math
import numpy as np
from scipy.ndimage.filters import convolve
from scipy.special import gamma
from basicsr.metrics.metric_util import reorder_image, to_y_channel
def estimate_aggd_param(block):
"""Estimate AGGD (Asymmetric Generalized Gaussian Distribution) paramters.
Args:
bl... |
8b50cb9f3511568263db39ec7deaec00bf33a7099b7032748088c3555edb80ef | Python | 8,326 | 247 | """
End-to-end pipeline equivalence tests.
These tests run the *full* Nearl featurization pipeline (query -> run -> dump)
and capture the resulting output arrays. Their purpose is to verify that
optimizations to the CPU-side phases (query, cache, dump) do not change the
numerical output of the GPU compute.
Workflow
-... |
2c8c4ba2d244f551dd05240e549ccb04798698ab7147eb4c664338aafd00968d | Python | 8,341 | 216 | import logging
from typing import Literal
import numpy as np
from . import control_fit
from .artifact_removal import retained_chunk_indices
from .control_channel import synthesize_over_chunks
from .filtering import filter_over_chunks, validate_chunk_lengths_for_filtering
from ..utils.validation import validate_window... |
3960a1b89ab6deaebf5a81680b5f9ff715d4ef1e018591b509b18559989a9573 | Python | 8,344 | 216 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Union
def pad(k, p=None, d=1):
if d > 1:
k = d * (k - 1) + 1
if p is None:
p = k // 2
return p
class Conv1dBlock(nn.Module):
def __init__(self, in_ch, out_ch, k=1, s=1, p=None, d=1, g=1):
... |
4b7af2b60b6bb5d671258e071a45388db8ceeaea4adeb00d93277a8ab527e21c | Python | 8,345 | 183 | from torch.utils.data import Dataset
import torch
import numpy as np
import itk
import SimpleITK as sitk
from data_augmentation_utilities import augment
class MakeTorchDataset(Dataset):
"""
Class that receives a pd.dataframe in which the first column contains the paths to the input images and the
second c... |
c334481b3f1d333dc6594c6d3a41885a33831825e360fbacff157e296f2b0e5d | Python | 8,346 | 277 | """bluepyopt.ephys.simulators tests"""
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as publis... |
0d3df7b086362a1e26fc681fe5086b56c773e0a7af2d7689437e32e63bc677d1 | Python | 8,348 | 260 | """Tests for StateFileSource (pydantic-settings custom source)."""
from __future__ import annotations
import os
from datetime import UTC, datetime
from unittest.mock import patch
import pytest
from zndraw.state_file import ServerEntry, StateFile, TokenEntry
# PID that is guaranteed to not exist on any reasonable s... |
7175cf66c3416d1c2c488e2490d93a84628c235dc953068079035b93a53531f8 | Python | 8,348 | 262 | """Modifier extensions for manipulating atoms in the scene.
These extensions modify the atomic structure (add, delete, move atoms, etc.).
"""
import enum
import typing as t
from ase.data import chemical_symbols
from pydantic import Field
from zndraw.extensions.abc import Category, Extension
from zndraw.extensions.f... |
0a441a42742e62c21ab480abc20ece519e1961aebd5c54ef8927bcd47f18be4c | Python | 8,349 | 203 | """Step-5 dashboard tab for behavioral covariates correlated with binned metrics.
Reads the ``covariate_correlations_<site>.h5`` and ``binned_covariates_<site>.h5``
tables Step 4 wrote and shows the selected covariate two ways: stacked with the
photometry trace and bins it was correlated against, on one linked time ax... |
dc7f19c05b508df2d4455cebe010bb1eaded2d907060e2f970d891e5404ebb8c | Python | 8,354 | 247 | from __future__ import print_function
def classification_plot(myinput, outDir):
import pandas as pd
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import gridspec
import seaborn as sns
import glob
import os
###---Sta... |
4560025cdfbd4a4a77e63096ea39c473ddf860a0b6c50b50c07285e598d51eb6 | Python | 8,357 | 215 | """Test functions"""
import numpy as np
import pytest
from scipy import signal
from scipy.ndimage import shift
import msalign
@pytest.fixture
def make_data():
"""Function to make data."""
def _wrap():
x = np.arange(10)
array = np.random.randint(0, 100, (20, 10))
return x, array
... |
3fb315d3eeafaeb515588743bb3aca4b94daf0c0b4689ea5edf39117971c2b1d | Python | 8,359 | 202 | import argparse
import torch
import torch.nn as nn
import numpy as np
import os
import time
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
# Parse input ar... |
a86af22d030809d02fec5ec5c0a6606ff5828b2af1386e2c7eb27563c58d92ec | Python | 8,360 | 180 | from PyQt5 import QtGui, QtWidgets, QtCore
from view.MovementCorrectionDialog import MovementCorrectionDialog
from view.AdjustFrequencyDialog import AdjustFrequencyDialog
from model.ABFLoader import ABFLoader
from model.TIFLoader import TIFLoader
class SourceManager(QtGui.QWidget):
def __init__(self, da... |
b86b4baf175710ea9e16108c1a24e1f368e73da93caf79d588cec39c663321fa | Python | 8,361 | 273 | import os
from medperf import config
from medperf.exceptions import ExecutionError, InvalidArgumentError
import pytest
from medperf.tests.mocks.dataset import TestDataset
from medperf.commands.dataset.import_dataset import ImportDataset
import yaml
PATCH_IMPORT = "medperf.commands.dataset.import_dataset.{}"
@pytest... |
264bf8b9998d3f935eacd8ecbc9e567e1cabf6c55ddee15de61d4a32f960aeb7 | Python | 8,369 | 168 | """Report every synonym that the issue-#932 fix removes from NCBIGene's shredded alias fields.
NCBI wraps a comma-containing alias in ''...'' and then turns that value's internal commas into
'|' -- the ``Synonyms`` column's own delimiter -- so the value arrives shredded into pipe-fragments.
The #744 fix drops the two ... |
764bce3fc532a75cea06e78f00f3f9cf8b1d36844b54f955ac15f4fbf9dc5b9c | Python | 8,372 | 252 | from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
import numpy as np
import pytest
import torch
import wandb
from pymatgen.core import Lattice, Structure
from chgnet.data.dataset import StructureData, get_train_val_test_loader
from chgnet.model import CHGNet
from chg... |
5cd401bbb9a5c9c34910170fa6bcfef65345f019ef2e5d372c2e8c5a49d0683f | Python | 8,375 | 254 | import numpy as np
from myphdlib.general.toolkit import psth2
class TuningProcessingMixin(object):
"""
"""
def _measureLuminancePolarity(
self,
responseWindow=(0, 0.3),
baselineWindow=(-0.2, 0),
minimumFiringRate=0.5,
):
"""
"""
#
sp... |
710a49ac7a8e85a4464f60cb14efa79d05ca8e66ca2ab6c57cf492a144cdf978 | Python | 8,376 | 238 | # rescreener.analysis
import os
from glob import glob
from typing import Optional
import polars as pl
from tqdm import tqdm
from ._constants import FULL_DIR, FULL_NAME_PREFIX, SUBSET_DIR
class BootstrapAnalysis:
"""
A class for analyzing bootstrap results from CRISPR screen data.
This class handles lo... |
afc94dc0fb5e5b3e80f9f35d35d5b1a6b29519078692b8467f4f5dfd7e469d42 | Python | 8,381 | 225 | from torch import nn
import torch
from torch_geometric.nn import global_max_pool, global_mean_pool
from torch.nn import Module, Linear, MSELoss, ModuleList #BCEWithLogitsLoss
from torch.nn.functional import relu
#from torch import sigmoid
from torch.utils.data import WeightedRandomSampler
import pytorch_lightning as pl... |
afa2ee125932fe24612fa8c6bc16ee3ba5a8cb89bbc30cfec27a9b956b52abfa | Python | 8,382 | 215 | # Copyright (c) 2021, EleutherAI
#
# 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 writi... |
37aca008cd68ff8078670f300a6a4873109611c67ccc46f8503b3e8738dd4334 | Python | 8,385 | 208 | # -*- coding: utf-8 -*-
from collections import defaultdict
import json
from typing import Any, DefaultDict, Dict, List
from django.core.serializers.json import DjangoJSONEncoder
from django.db import connection
from django.http import HttpRequest, JsonResponse
from guardian.utils import get_anonymous_user
from cat... |
50d899a4a48d7dee56a593390b5d0a4958dc0bcb8b81ced8161a44f11a69b1f7 | Python | 8,388 | 230 | #!/usr/bin/env python3
"""Compare sct_* command invocations between tutorials and batch scripts."""
import logging
import re
import sys
from collections import Counter
from pathlib import Path
# This script lives at $SCT_DIR/.github/workflows/extract_commands.py
PWD = Path(__file__).parent
DOC_PATH = PWD.parent.pare... |
4c5b47bff9640ffa2c806f5f5fd6ea3787eb65e663f1e64f8ec1408f95c43a1f | Python | 8,390 | 246 | import CCF_translator
import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
from tqdm import tqdm
import inspect
import os
from scipy.interpolate import griddata
from scipy.ndimage import generic_filter
# Get the file path of the package
package_path = inspect.getfile... |
8ed0fb0479b9beab66a3e2c4306a85be10749a0f0802f20c0c4d0f0179799d23 | Python | 8,392 | 215 | #!/usr/bin/env python
"""
# Author: ChangXu
# Created Time : Mon 23 Apr
# File Name: cal_graph.py
# Description:`
"""
"""
test:
from cal_graph import graph, combine_graph_dict
import scanpy as sc
data_path = "/home/xuchang/Project/STMAP/Human_breast/output/Breast_data/STMAP_Breast_15.h5ad"
... |
1d52bce4ca4c5de447650a3e7622260a4168810364229ad1a350dfc1a4242d1f | Python | 8,400 | 307 | from rest_framework.test import APIClient
from django.contrib.auth import get_user_model
from django.conf import settings
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from time import time
import jwt
def generate_key_pair():
private_key = rsa.g... |
8db9f2f938a9a7ba98c74dbbd4ad36cae84be14850ddfaf10fda36d0f946a777 | Python | 8,401 | 239 | import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GroupKFold
from sklearn.metrics import accuracy_score
from scipy import stats as ss
import statsmodels.stat... |
937225f85f60af940c64682c2e2a446f1950e2e4b91dc051c76d9ef1b9a973c7 | Python | 8,401 | 220 | # SPDX-License-Identifier: MIT
"""Helper for evaluation on the Labeled Faces in the Wild dataset
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in... |
0dd8c39cd0efa2f861a494a72c580664edb9a93c01eba89d5244f33fc2a5cb1b | Python | 8,403 | 248 | # Authors: Pierre Ablin <pierre.ablin@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Jean-Francois Cardoso <cardoso@iap.fr>
#
# License: BSD (3-clause)
from copy import copy
import numpy as np
from scipy.linalg import expm
from .densities import Tanh
def core_picard(X, density=Tanh(... |
17af8cbd9063ab96320af49c12716ae8836ddbc61c445ffd86d760fda27518fc | Python | 8,403 | 218 | """
For specific figures
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os, json
import seaborn as sns
from scipy.stats import chi2, pearsonr, norm
from sklearn.metrics import r2_score
from draw_rna.ipynb_draw import draw_struct
from .util import *
from . import util, plotting
sns.s... |
13c6eaab3266fcb145f10e2fa4eadc3ab6430bafe9aae2c6728d0a04d3187819 | Python | 8,404 | 286 | """Tests for docker engine."""
import json
import re
from pathlib import Path
from shutil import which
import pytest
from cwltool.main import main
from .util import (
get_data,
get_main_output,
needs_docker,
needs_podman,
needs_singularity,
)
@needs_docker
def test_docker_workflow(tmp_path: Pa... |
9a1df6aaafcf61d23a36f6da4b823f3d945b2781ec5a0c15fa3335a80bdb227f | Python | 8,410 | 182 | import pytest
from CybORG import CybORG
from CybORG.Shared.Session import Session
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import EnterpriseScenarioGenerator
from CybORG.Agents.SimpleAgents.ConstantAgent import SleepAgent
from CybORG.Simulator.Actions.ConcreteActions.Withdraw import Withdraw
from Cy... |
fa4e0dd89911134f89bbf19d633def439a8d051aa67169b556ae28ef93ada7bd | Python | 8,419 | 197 | import numpy as np
import pandas as pd
from guppy.analysis.psth_utils import (
create_Df_for_cross_correlation,
create_Df_for_psth,
getCorrCombinations,
match_trials_by_timestamp,
)
# ── create_Df_for_psth ────────────────────────────────────────────────────────
def test_create_df_for_psth_creates_h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.