sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
8925ebf1b90456a08ae53f4f456dee43220d15afd8de78ecd7c221779f23e15f | Python | 2,703 | 94 | import argparse
import numpy as np
import random
import torch
import windseer.data as data
import windseer.nn as nn
import windseer.plotting as plotting
import windseer.utils as utils
parser = argparse.ArgumentParser(
description='Predict the flow based on the sparse measurements'
)
parser.add_argument('confi... |
867afc2be23bfffe50a50d61a5da2477a7f288186b3cc2cfa7f50b6f42607163 | Python | 2,704 | 89 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 10 13:31:10 2023
@author: tomas
"""
from tensorflow import keras
from cine import Cine
from tube2 import tube_crop1
import glob
import math
import numpy as np
from skimage.io import imshow
from skimage import measure, draw
from matplotlib import... |
5a9d65641a703edb62d8e107f4d68d87b6bafe23e9b7ed9cb25555a8442d7154 | Python | 2,706 | 99 | """
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 numpy as np
import torch
def complex_mul(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Complex multiplication.
... |
27d538a3ba64141abd914607f8b9ba5dfb5011577dfb79cd595b623091f7bb6f | Python | 2,708 | 73 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2022-04-26
#Runs multiple replicates at each set of parameter values
# ran test run with two replicates at one set of parameter values
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.object... |
85598a8bc24666cef524e036db9699816df03735575c934c7dfee1e62e4dae64 | Python | 2,708 | 86 | import pandas as pd
import signal
import numpy as np
import time
import os
import logging
import itertools
import functools
import warnings
from multiprocessing import Pool, TimeoutError
from Bio.PDB import PDBList
from Bio.PDB import PDBParser
from Bio.PDB.mmtf import MMTFParser
from Bio.PDB.PDBExceptions import PDBCo... |
7167d2f50f15502f8933642df66f1e5213e690ce1952a1f6e29cf580cc94cbb6 | Python | 2,709 | 106 | from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Literal, Protocol, TypedDict
import numpy as np
if TYPE_CHECKING:
from typing import Any, NotRequired, Self
from .._compat import CSRBase
from .._utils.random import _LegacyRandom
__all__ ... |
1646170f2a23281abd63ae13881f463a560239512a572a8630f89f5aec8cffbf | Python | 2,711 | 97 | import tensorflow as tf
import os
import nibabel as nib
import numpy as np
import random
import re
from skimage.transform import resize
from const import *
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def int64_list_feature(value):
return tf.train.Feature... |
22bb950fe53512579e0b5b71a40560954d4afb2251adafecfc603b03f6380de6 | Python | 2,711 | 66 | from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QComboBox
from scanometrics.GUI.Icon import Icon
class DropDownMenu(QWidget):
"""
A custom drop-down menu widget with signal emission on option selection.
"""
sgn = pyqtSignal(str) # Signal emitted wh... |
ee16195baca10c38d03fcda4373e8b080b907a23244bc9a8b2103218584564c0 | Python | 2,711 | 62 | import numpy as np
from quasinet import qnet
class Forecaster:
"""Forecast the data week by week by sequantially generating qnet predictions for the next timestamp and using the filled timestamp to update qnet predictions
"""
def __init__(self, qnet_orchestrator):
"""Initialization
Args:... |
eadd871f0cf1e867ebc26159be6105e5a98860e5aec4e149afb48cb352fa01bf | Python | 2,713 | 71 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestReorderLevels:
def test_reorder_levels(self, frame_or_series):
index = pd.MultiIndex(
levels=[["bar"], ["one", "two", "three"], [0, 1]],
codes=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1... |
ec47154f11aecdf1a6adb2e62e815bc86bc10a5e9f4d159701cc86d09b99a02c | Python | 2,713 | 76 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
"""
.. _metas_cbma_vs_ibma:
================================================
Compare image and coordinate based meta-analyses
================================================
Run IBMAs and CBMAs... |
0bf58f48bc7ef65eb76aa575647f968f7bb24674c233ea322e68eaeb7492232c | Python | 2,714 | 65 | # ---------------------test---------------------------------
import torch
import torchvision
from torch.utils.data import DataLoader
from torchvision import transforms
test_path = "./datas7/test"
model_path = "./model/xxx.pkl"
def testdata_transforms():
transform = transforms.Compose([transforms.Resiz... |
da66c5a6de7a77ce15a601ba9de7c7edb35a68c194d05720723e30c310254d96 | Python | 2,715 | 78 | from __future__ import absolute_import
#__version__ = '0.0.0'
#import from data_utils
from data_utils import load_csv_data
from data_utils import load_Xy_one_hot_data2
from data_utils import load_Xy_data_noheader
from data_utils import drop_impute_and_scale_dataframe
from data_utils import discretize_dataframe
from d... |
84f7a17bb086b2db42c8e8969801ac281000dca2308b54539571ea5b628958f4 | Python | 2,717 | 66 | import os
import shlex
from cptools2 import commands
CURRENT_PATH = os.path.dirname(__file__)
TEST_PATH = os.path.join(CURRENT_PATH, "example_dir")
TEST_PATH_PLATE_1 = os.path.join(TEST_PATH, "test-plate-1")
def test_make_cp_cmnd():
"""cptools2.commands.make_cp_cmnd(name, pipeline, location, output_loc)"""
n... |
1c186e140d5bed1ca4938324911811a42805028911329e06863e68b99d75a96d | Python | 2,718 | 57 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 31 14:58:16 2020
@author: vman
"""
import numpy as np
from matplotlib import pyplot as plt
class Design(object):
def __init__(self, designMat, designRegressors, **kwargs):
"""
Creates a 'Design' class that initiates differ... |
5672e3105db6461f2651d1a21c6a343efc5a273d99dd0c2e25b791b41d136e92 | Python | 2,718 | 89 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestCombine:
@pytest.mark.parametrize(
"data",
[
pd.date_range("2000", periods=4),
pd.date_range("2000", periods=4, tz="US/Central"),
pd.period_range("2000", periods=4),
... |
013ec41c746dbaa84aab37b142d381997a38131d169e485fa1254ad8cc9fe4ed | Python | 2,719 | 84 | from numba import njit, types
from numba.typed import Dict
import numpy as np, sys
from Wavenet.evaluation import evaluation
from configuration import config
from Wavenet.training import training
@njit(cache=True, fastmath=True, nogil=True)
def MLecar(dic, Iapps, noise, w0, v0):
n_integrations = int(dic['integrat... |
bb3217316f67919288f229faacbcd941aecb4c1052e57871e6d1ea49100e469f | Python | 2,720 | 77 | """ to build modules in module_list: python setup.py build_ext --inplace
Created by G. Peter Lepage (Cornell University) in 12/2013.
Copyright (c) 2013-14 G. Peter Lepage.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the F... |
bc05d71444e14566b2754d10d326fcd34212759995a6d74275cc231198ca8e26 | Python | 2,720 | 135 |
# # import libraries
import pandas as pd
from pandas import DataFrame
from nltk.stem.isri import ISRIStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
#from sklearn import cross_validation# from sklearn.model_selection impo... |
c9c992cf571b1c0c21c26b34d388f2d86241fdd9e8bad6e823390739ae95647f | Python | 2,720 | 92 | # JN 2015-11-03
"""
This module should contain calls to the test functions
already present in various submodules of combinato.
At the moment, it only checks whether the clustering binaries
are present and whether plotting is possible
"""
from __future__ import division, absolute_import, print_function
import subproces... |
1372765f44f3ff18d4873b07e33839680eaa057f3327fd8036c0e0374d3481a3 | Python | 2,721 | 121 | """
Provide basic components for groupby.
"""
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Hashable
@dataclasses.dataclass(order=True, frozen=True)
class OutputKey:
label: Hashable
position: int
# special case to ... |
93531f49b6b1bc96b2d7afee6fabb7ef5f7133455106f5e5ae3b7f1524a5cabf | Python | 2,722 | 80 | import os
import zmq
import cloudpickle
import yaml
#context = zmq.Context()
#socket = context.socket(zmq.REQ)
#socket.connect('tcp://130.183.178.36:5555')
# we here assume backend is sqlite_remote, as otherwise this module would not be loaded
config_path = os.environ['ISF_MDB_CONFIG']
with open(os.environ['ISF_MDB_CO... |
18906a205e16e901b8937633cfaff5dd630e4789c7495ccf6e2c47c4ef13ba4c | Python | 2,723 | 105 | from datetime import datetime
import pytest
from pandas.tseries.holiday import (
after_nearest_workday,
before_nearest_workday,
nearest_workday,
next_monday,
next_monday_or_tuesday,
next_workday,
previous_friday,
previous_workday,
sunday_to_monday,
weekend_to_monday,
)
_WEDNES... |
22067e97ea8997298a747fc9662a9e11fb66ee5c13e7b621abb44d34f42a7a1f | Python | 2,725 | 78 | # Copyright 2018-2024 Xanadu Quantum Technologies 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... |
4f43d09b171cc5e7a72399ee77a90973049f13a72fe3632ec6570ea21d14fd45 | Python | 2,726 | 82 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class NoisyLinear(nn.Linear):
def __init__(self, in_features, out_features, sigma_init=0.017, bias=True):
super(NoisyLinear, self).__init__(in_features, out_features, bias=bias)
self.sigma_weight = n... |
759e25d1286bde7e7a82636d604e6ad67fe78c856b0094c844cb25d856300476 | Python | 2,727 | 93 | import numpy as np
import pandas as pd
import plotnine as p9
def n_es_genes(df: pd.DataFrame,
annotation: pd.Series,
figsize: tuple=None) -> p9.ggplot:
"""Plot distribution of number of ES genes per group
Computes the number of ES genes per column, e.g. cell(-type)
an... |
29a0078ecb3ccc93328d09320fc717116d1fcbe75e4026a9ecab6431be0ccc4d | Python | 2,729 | 74 | import numpy as np, os, pickle, sys
import wormfunconn as wfc, pumpprobe as pp
import matplotlib.pyplot as plt
unc31 = "--unc31" in sys.argv
strain = "" if not unc31 else "unc31"
ds_tags = None if not unc31 else "unc31"
ds_exclude_tags = "mutant" if not unc31 else None
ds_list = "/projects/LEIFER/francesco/funatlas_l... |
250ba3da7baa6ebc8a6d52cc60986c1740358eac4267bd3e8f78b5f3b2daded1 | Python | 2,730 | 90 | import numpy as np
import scipy as sp
import scipy.misc
import scipy.sparse
import scipy.sparse.csgraph
import matplotlib.pyplot as plt
import time
def create_graph_from_image(image):
h, w = image.shape
weights = np.array([1., 1., 1., 1.])
offsets = (-w, -1, 1, w)
graph = sp.sparse.diags(weights, offs... |
339bd4d08092fe5ba70bf5add94f85ce1ce5d2f585085135bad628879a8fcd28 | Python | 2,730 | 116 | #!/usr/bin/env python
#
# Copyright 2013 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 requir... |
e337aa567e1873bcdb33d847b34d3a594cae4c1cfbee2562a42d1d9b9540b706 | Python | 2,730 | 84 | # 合并所有json文件,良性为一组,恶性为一组
import json
# finalsamples = []
# filename0 = r"E:\experiment\mal\api\api1final.json"
# filename1 = r"E:\experiment\mal\api\api2final.json"
# filename2 = r"E:\experiment\mal\api\api3final.json"
# filename3 = r"E:\experiment\benign\super\4superfinal.json"
# filename4 = r"E:\experiment\ben... |
2455ac1b1db2e1a5c1d548b341753dd4fa6d346df18c4ac8b3fe60a64e442297 | Python | 2,734 | 96 | from __future__ import annotations
from contextlib import contextmanager
from enum import EnumMeta, IntEnum
from logging import getLevelNamesMapping
from typing import TYPE_CHECKING
from scverse_misc import Deprecation, deprecated
from .._compat import set_module
if TYPE_CHECKING:
from collections.abc import Ge... |
486c40bbcee2f62e2c9396cb74792b7e06c8dec5a3fe184f534addac00ff81fd | Python | 2,734 | 72 | import csv
from base import loggingUtils, surfaces
from base.kernelFunctions import *
from base import surfaceMatching, surfaceTimeSeries as match
def runLongitudinalSurface(minL=3, atrophy=False):
if atrophy:
pass
else:
pass
with open('/cis/home/younes/MATLAB/shapeFun/CA_STUDIES/PRE... |
5f891b9fe182fea8b4f78f662ca3fbe6f47fb1b0e3c88f89df215c3e6f55b666 | Python | 2,734 | 88 | import pytest
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
from pandas.errors import OutOfBoundsDatetime
import pandas as pd
class TestTimestampAsUnit:
def test_as_unit(self):
ts = pd.Timestamp("1970-01-01").as_unit("ns")
assert ts.unit == "ns"
assert ts.as_unit("ns") is ts
... |
0be6eb3f323bfb4d4244731d7eec6a82673da4ea4daf1b8315472dfec000ea9a | Python | 2,735 | 75 | # Filename: _nn_design.py
# Author: Alessandro Gerada
# Date: 2023-08-11
# Copyright: Alessandro Gerada 2023
# Email: alessandro.gerada@liverpool.ac.uk
"""Template NN designs as reported in Gerada et al. 2024 Microbiology Spectrum paper"""
from tensorflow.keras import layers # pylint: disable=import-error,no-na... |
1b79ebd2917f4872f72c20d2779ab617d861ad5daeb333df3aa003d1224d99e6 | Python | 2,735 | 81 | # Copyright (c) 2018-present, Facebook, Inc.
# 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 os
import torch
from collections import defaultdict
import logging
class Dictionary(object):
def __init__(self, pat... |
16a15092b7c78ed680e9accba22adb32c38375ceb8d82c3019c591ee0e2c840b | Python | 2,739 | 76 | import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestDatetimeIndexFillNA:
@pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"])
def test_fillna_datetime64(self, tz):
# GH 11343
idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.... |
c2bcd485d39bb3d0354b93f6291443ca7c8294a36fe4f4b6d3435f9c9ad50366 | Python | 2,741 | 90 | """Workflow for running a SCALE meta-analysis from a Sleuth text file."""
import logging
import os
import pathlib
from shutil import copyfile
import numpy as np
from ..dataset import Dataset
from ..io import convert_sleuth_to_dataset
from ..meta import SCALE
from ..utils import vox2mm
LGR = logging.getLogger(__name_... |
f2fb027c3001232fc65626d3c3664b6e1634d712c2cdd28f225e6490e7aa962a | Python | 2,741 | 80 | # Copyright 2026 Xanadu Quantum Technologies 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 agree... |
b3bd835aebeb6c79038b038009ba56a52df36039bf82303b3df84b776431914c | Python | 2,743 | 56 | import scipy.ndimage.measurements
from Environment import *
from scipy import stats
from Parameter import *
def position_stats(data_path, data_name):
image = tifffile.imread(os.path.join(data_path, data_name))
# z, _, _ = image.shape
group_num = Stats['position_group']
group1 = image[0 : group_num,... |
0dfa7ae40f2899ad4dae1fda2dde59e45d70ce499b8cd96aff091c970fe1a03f | Python | 2,744 | 72 | import numpy as np
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestFillNA:
def test_fillna_categorical(self):
# GH#11343
idx = pd.CategoricalIndex([1.0, np.nan, 3.0, 1.0], name="x")
# fill by value in categories
ex... |
86cd1afa507298c465b783fcad0709ed487a9b610e3fc722440fc099f5dae5a0 | Python | 2,745 | 94 | #!/usr/bin/env python
'''
Testcases for the flight path interpolation
'''
import windseer.utils as utils
import numpy as np
import torch
import unittest
class TestInterpolation(unittest.TestCase):
def test_interpolate_flight_path(self):
wind_prediction = torch.randn(3, 2, 2, 2)
grid_dimensions ... |
15066fb6e28eed35cb118d22b20aae7a363ebc9fbf6086dc4273f625795ee2fa | Python | 2,746 | 70 | # Copyright 2026 Xanadu Quantum Technologies 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 agre... |
1ea0f44a9f3e6e4b94a898203220ec6b90a31d4ab7de75af0cf177f8ec4cbdbf | Python | 2,746 | 95 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
import os
import pyrosetta
pyrosetta.init('-mute all')
def get_pos_sasa(pose, position):
sas = pyrosetta.rosetta.core.scoring.sasa.SasaCalc()
sas.calculate(pose)
residue_sasa_list = sas.get_r... |
cb5f25566cd2cc2d80a6bab481d2f7a8e73c43c7eb5c1a9139597aafc04f5a6b | Python | 2,746 | 79 | """Phase 1 Redis-backed Job queue adapter.
Thin shim around ``redis-py``. The schema is:
- One Redis LIST per queue name (``pycaret:queue:default``,
``pycaret:queue:gpu``, etc.). LPUSH on enqueue, BLPOP on dequeue.
- One Redis HASH per Job id (``pycaret:job:<id>``) — used only for the
visibility timeout / heartbe... |
23ccbdcd302bd1d05e7a1311428ed91e7a6f72598b1760c4df76b14e4bd69aa2 | Python | 2,747 | 84 | import numpy as np
from pandas._libs import index as libindex
import pandas as pd
import pandas._testing as tm
def test_detect_chained_assignment():
# Inplace ops, originally from:
# https://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug
a = [12,... |
e5802e884134e80b3cc3a045b86f658be8dfba89ca38b7d3295103a5ed638faf | Python | 2,747 | 86 | # -*- coding: utf-8 -*-
# Copyright (C) 2019 Andrea Vázquez Varela
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... |
e51d2def2561f9b3739aac6d0f1e0f5d6bfd746bb1149f714c4a8bcd13f59835 | Python | 2,749 | 95 |
from tensorflow import keras
import tensorflow as tf
import sklearn
from skimage import draw
from skimage.io import imshow, imread
from skimage import morphology
from skimage import transform
from skimage import util
import numpy as np
from matplotlib import pyplot
# from tensorflow import keras
# import tensorflow as... |
1f82b55613c086d90cde9d388dd3d97e35c3971b4d5a8d5c27c3aa532ac4d31a | Python | 2,750 | 66 | import time
class IntervalSummaryWriter:
"""
Summary writer wrapper designed to reduce the size of tf.events files.
It will prevent the learner from writing the summaries more often than a specified interval, i.e. if the
current interval is 20 seconds and we wrote our last summary for a particular sum... |
2754e7e7134b6c27bfa0d7992c6a3e9c93e3a3ba25d357c02f4072c086f2cc4b | Python | 2,750 | 71 | from kilosort import __version__
from kilosort.gui.minor_gui_elements import help_popup_text, controls_popup_text
from PyQt5 import QtCore, QtGui, QtWidgets
class HeaderBox(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent=parent)
self.gui = parent
se... |
d25d3a618756ec8e53a7eb82fdc14175f1665114ba535a1018d5fa7decc744f0 | Python | 2,751 | 83 | # pip install imgaug
# https://imgaug.readthedocs.io/en/latest/
from imgaug import augmenters as iaa
import numpy as np
import os
from PIL import Image
def grid_mask(image):
img_h = image.shape[0]
img_w = image.shape[1]
x = 15
y = 15
w = 30
h = 30
l = 15
temp = x
... |
eeb2806cf6b772225da5a6832bc1f673013ac7ebd7b40c7ec3d01605e66da925 | Python | 2,752 | 73 | """Test M4Raw dataset"""
import h5py
import pytest
from mrpro.data import KData
from mrpro.phantoms.m4raw import M4RawDataset
from mrpro.utils import RandomGenerator
N_COILS = 2
N_K0 = 256
N_K1 = 195
N_K1_PADDED = 256
N_SLICES = 18
N_REPS = 2
@pytest.fixture(scope='session')
def m4raw_data(tmp_path_factory):
""... |
43e9be912521bf376e80c18ead5fd0a473906078dc9b066079eddefb66bc8156 | Python | 2,755 | 79 | import operator
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestMatmul:
def test_matmul(self):
# matmul test is for GH#10259
a = pd.Series(
np.random.default_rng(2).standard_normal(4), index=["p", "q", "r", "s"]
)
b = pd.Dat... |
6e2b66a8d4ca164ea82920d89d3e7766740ff9231aee13ba041e5eb5bbe4f2e3 | Python | 2,756 | 77 | import numpy as np
import pandas as pd
import pkg_resources
def human_ens_to_human_symbol(df_unmapped: pd.DataFrame, drop_unmapped: bool=False, verbose: bool=False) -> None:
"""Map dataframe index human ensemble id to human gene symbol inplace
Parameters
----------
df_unmapped : DataFrame
Data... |
7b72ccef35e1965b4d6e942a8081c61ebc7c5977abb8d7e077429af084c5638b | Python | 2,757 | 87 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 16:04:54 2022
@author: fm02
"""
### Author: federica.magnabosco@mrc-cbu.cam.ac.uk
### Plot results from LDvsSD individual ROIs accuracy
import numpy as np
import pandas as pd
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import ... |
903b17ea32ec2d2a332a85dab867bf75d75991c81cd34ee464101dd1d85a8625 | Python | 2,757 | 60 | # -*- coding: utf-8 -*-
"""
Expectation-maximization brain segmentation
NOTE: if no graphical interface, needs xvfb-run
"""
import os
import time
from app.utils import get_exitcode_stdout_stderr, end_execution, wrap_string
import logging
import platform
logger = logging.getLogger(__name__)
def EMsegment(im_t1_path, ... |
1df3ac7cabcaca344bfcd27a1d326a577996ead159d83878297d8c9b9bbb870b | Python | 2,758 | 78 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_xs_datetimelike_wrapping():
# GH#31630 a case where we shouldn't wrap datetime64 in Timestamp
arr = pd.date_range("2016-01-01", periods=3)._data._ndarray
ser = pd.Series(arr, dtype=object)
for i in range(len(s... |
d8e3fadb9a6ea9490459371ca1a42996c8b77a99f5671b755e67e2858bd464b6 | Python | 2,758 | 91 | import torch
import torchvision
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms,utils
from torch import nn, optim
import numpy as np
import torchvision.models as models
import skimage
from skimage import io,transform,util
from PIL impor... |
645df9388e46c1d1aed213999ef6561daf362f35619259932798ca17119960c5 | Python | 2,760 | 76 | # Copyright 2018-2021 Xanadu Quantum Technologies 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 ... |
87b887592d03d84e1e07e4a1ad6df63d058dc7dc26efb6175d9f7b5ca14e58fe | Python | 2,760 | 81 | from __future__ import absolute_import
import os
from .sqlite_backend.sqlite_backend import SQLiteBackend as SQLBackend
from .utils import cache
from .settings import model_data_base_register_path
_foldername = '.model_data_base_register.db'
class ModelDataBaseRegister():
def __init__(self, basedir, search_mdbs = ... |
dc33b03be0545f69fc2aed78e8cddfa633bead41116e61453fcde865ac7be40c | Python | 2,760 | 90 | """Workflow for running a SCALE meta-analysis from a Sleuth text file."""
import logging
import os
import pathlib
from shutil import copyfile
import numpy as np
from nimare.dataset import Dataset
from nimare.io import convert_sleuth_to_dataset
from nimare.meta import SCALE
from nimare.utils import vox2mm
LGR = loggi... |
e3f27c5756a1df6af2089ca54e9c6c6a646e2007bca54a650ef404f106695983 | Python | 2,760 | 73 | # Copyright (c) 2021-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
268424bc38c957fe1196d814e2a7159e5430e3ed48ab16a5bb540f5a49d05bda | Python | 2,761 | 89 | import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
try:
from PIL import ImageEnhance
from PIL import Image as pil_image
except ImportError:
pil_image = None
ImageEnhance = None
def mask_to_onehot(mask, palette):
"""
Converts a segmentation mask (H, W, C) to (... |
5a36c1850620670477577c54df8eadddc3dcfc446b7d9bbb9873891af75f8515 | Python | 2,761 | 98 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
import numpy as np
from pathlib import Path
from statistics import mean, stdev
plt.rcParams['font.family'] = 'Gargi'
p = Path('../../data')
#dataSheet = p / "OMT_evolut... |
62218ebf6a86ae37e98b836ff0eb674eb14cbc8b1e06096c835077756de3eea5 | Python | 2,761 | 78 | """LocalManager — dev-only stub that records sessions but spawns nothing.
Lets the rest of the system be exercised end-to-end (create notebook,
start session, view "running" status, stop) on a machine that doesn't
have Docker. The frontend renders a placeholder iframe with a hint
about enabling the docker backend.
"""... |
6d34417d9bc30120adebf5b05a8f798c7939e471fc2813d55fc31d8a93250e83 | Python | 2,761 | 103 | """Include single scripts with doc string, code, and image
Use case
--------
There is an "examples" directory in the root of a repository,
e.g. 'include_doc_code_img_path = "../examples"' in conf.py
(default). An example is a file ("an_example.py") that consists
of a doc string at the beginning of the file, the exampl... |
673718793e5b2208a95858cd13156431d1a39d1cce1ba9bcc69056a8be29f3b0 | Python | 2,763 | 73 | import ntpath
from numba import jit, prange, int64
from sys import path as sys_path
sys_path.append('/cis/home/kstouff4/Documents/MeshRegistration/master/py-lddmm/')
sys_path.append('/cis/home/kstouff4/Documents/MeshRegistration/master/py-lddmm/base')
sys_path.append('/cis/home/kstouff4/Documents/SurfaceTools/')
import... |
c0adb5c196829c7bba88a9293655f0458dfb84722ee003fece8fec6e3a8cc93c | Python | 2,763 | 109 | from wordfreq import tokenize, lossy_tokenize, word_frequency
def test_gender_neutral_at():
# Recognize the gender-neutral @ in Spanish as part of the word
text = "La protección de los derechos de tod@s l@s trabajador@s migrantes"
assert tokenize(text, "es") == [
"la",
"protección",
... |
d4036d973ed23aa49ec4e5ce2b5c30069045a515934fc996861fffc2a85886e0 | Python | 2,763 | 97 | import argparse
import math
import pandas as pd
from typing import List
from utils import filter_bccwj_eyetrack, normal_bracket2ptb_bracket, zen2han
parser = argparse.ArgumentParser()
parser.add_argument(
"--bccwj_eyetrack_path", type=str, default="data/BCCWJ-EyeTrack/fpt.csv"
)
parser.add_argument("--unit", type... |
c9f9a7ba70ee7785263a0c2a7ab99666ea71883c32cbac69c60e5cf999606436 | Python | 2,765 | 84 | # Update sitemap XML file from the release diff TSV report.
import argparse
import xml.etree.ElementTree as ET
import csv
parser = argparse.ArgumentParser(
description="Update sitemap XML file from the release diff TSV report."
)
parser.add_argument(
"--date",
required=True,
help="Date to use for the l... |
3e7cfe3891c25126db2562de03f43de28738ceb9eb64c6f12e902ef7f1f6b966 | Python | 2,767 | 86 | """
This script is used to prepare pickles for AP-Net-dG training and inference.
Specifically, this will convert an sdf containing the protein as its first element and docked ligands
as all successive elements.
Requires ligands have an sdf property "training label" corresponding to the target quantity
"""
import os
im... |
50822ceede7dee014a5e0719e6c9d51cf2973532704abf26970cc29a4e1ffa66 | Python | 2,767 | 86 | import torch
from torch import nn
def repackage_hidden(h):
"""Wraps hidden states in new Tensors, to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h)
def multiply_hidden(h, mask):
if isinstance(h, ... |
91992b8a390518e3e249bdc7f4f1b3be3249ed0c3a2ea9104d1918552ea95391 | Python | 2,767 | 91 | from __future__ import with_statement
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python... |
94d55b5f836983a7b79709239c9bcf86319c4aa5ab74e447817148961b8c64fd | Python | 2,767 | 74 | import numpy as np
import pytest
import umap
# Globals, used for all the tests
SEED = 189212 # 0b101110001100011100
np.random.seed(SEED)
try:
from umap import plot
IMPORT_PLOT = True
except ImportError:
IMPORT_PLOT = False
plot_only = pytest.mark.skipif(not IMPORT_PLOT, reason="umap plot not found.")
... |
c33b54e64df38bf8eddb1f710e77ed3f6417ffc406d085503dc3260aac97f627 | Python | 2,767 | 103 | import os
import numpy as np
import cv2
import os
from os import listdir, makedirs
from os.path import join
from PIL import Image
import shutil
import sys
import logging
dim_offset = 14
def write_folder_stack(vol, path):
if os.path.exists(path):
print("Overwriting " + path)
shutil.rmtree(path)
... |
52d54f804536d9a4ba5acc4a4b071d8903a4db2c3a4af5a29166a7e6efd61ab0 | Python | 2,770 | 83 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestRepeat:
def test_repeat_range(self, tz_naive_fixture):
rng = pd.date_range("1/1/2000", "1/1/2001")
result = rng.repeat(5)
assert result.freq is None
assert len(result) == 5 * len(rng)
... |
045d2bf8b9e9fd390ba3e7971527ca5238f5b44d5eb4c88d13c60e1f01af360d | Python | 2,771 | 67 | import traceback
from PyQt5.QtCore import QThread, pyqtSignal
import numpy as np
class EvaluationThread(QThread):
"""
A QThread subclass for evaluating a subject.
This thread handles the process of evaluating a subject's session using the provided
metric. It emits signals to update the progress, sign... |
88f12ec1dd59a8b93a6d76f673a03f5c77c5c0cb072289c22602535cd05e05be | Python | 2,771 | 89 | import torch
import numpy as np
def min_max_scaling(
tensor: torch.Tensor, min_val_desired: float, max_val_desired: float
) -> torch.Tensor:
"""
Function to perform min-max scaling.
:param tensor: A Tensor for this scaling calculation to be based off.
:param min_val_desired: The desire... |
178bc3b6ba83a04359a4b09da598cbab186991cd7811c626ab241eee8a009b05 | Python | 2,772 | 91 | import tensorflow as tf
import numpy as np
from tqdm import tqdm
from more_itertools import chunked
import cv2
import multiprocessing as mp
import matplotlib.pyplot as plt
import re
import vuba
import pandas as pd
import glob
import os
from models import build_model
def read_img(fn):
img = tf.io.read_file(fn)
... |
a97f1fbf49b552ce0c7d0afcd84afd98110ad4f1e497e6bd2be2c3b7671a34b6 | Python | 2,772 | 68 | import matplotlib
matplotlib.use("TKAgg")
from base.surfaces import Surface
from base.kernelFunctions import *
from base.surfaceWithIsometries import *
from base import loggingUtils
def branches(angles, lengths = .75, radii=.05, center = [0,0,0],
ImageSize = 100, npt = 100):
[x,y,z] = np.mgrid[-Imag... |
239603e5353f99f9a04d220d4d662cd648abed912b847ab8967a3c88cde0425b | Python | 2,773 | 81 | import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.keras import backend, constraints, initializers, regularizers
from tensorflow.keras.layers import Layer
class MultivariateGaussianNoise(Layer):
"""
Multivariate Gaussian Noise for exploration
===========
Attributes:
... |
df0460ff8b5e52d08ea3510a289b1aa6c732b013200894fbc000844fae05f6b1 | Python | 2,773 | 81 | """Chromosight's stats submodule contains helper function to compute statistical estimators from distributions"""
import numpy as np
import scipy.stats as ss
def fdr_correction(pvals):
"""
Applies false discovery rate correction via the
Benjamini-Hochberg procedure to adjust input p-values
for multip... |
09522bd0116f8382f64128de0a29ebf67291c5aa58f6c7f8c44838fd711515f4 | Python | 2,774 | 77 | import numpy as np
import pandas as pd
import pkg_resources
def mouse_ens_to_human_ens(df_unmapped: pd.DataFrame, drop_unmapped: bool=False, verbose: bool=False) -> None:
"""Map dataframe index mouse ensemble id to human ensemble id inplace
Parameters
----------
df_unmapped : DataFrame
DataFra... |
378ccd91618b202e282ce83770d19fa803d9f0c10d33c2b80957bbcffba4532f | Python | 2,775 | 101 | # Copyright 2018-2020 Xanadu Quantum Technologies 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... |
f68f56f673043f301b2cfd6218199b012316dfaa5213b2acc832e3b32b5de89d | Python | 2,776 | 67 | """Autocast policy heads must retain fp32 Gaussian probability arithmetic."""
import math
from types import SimpleNamespace
import pytest
import torch
from rl_games.algos_torch.models import (
ModelA2CContinuousLogStd,
apply_sigma_parametrization,
)
class _LowPrecisionHead(torch.nn.Module):
"""Represen... |
09c91473315ba53c8b07e7bb827cbbe9140d3e071e97d347726e9678bb527d73 | Python | 2,777 | 60 | import pandas as pd
import numpy as np
def format_genes(gene_coord_df, chr_sizes_df, out_dir, windowsize_kb, print_log_files=True):
"""
Adds a fixed-size window to each protein-coding gene in the human genome.
Input
gene_coord_df: Locations of all human genes in hg19
chr_sizes_df: Sizes of hg19 human... |
d27717cd1e1205b4ad667f402c8ff5e08dda676f14b4a461cb9e88d575e00da7 | Python | 2,777 | 78 | import operator
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import SparseArray
@pytest.mark.parametrize("fill_value", [0, np.nan])
@pytest.mark.parametrize("op", [operator.pos, operator.neg])
def test_unary_op(op, fill_value):
arr = np.array([0, 1, n... |
3f5be08826349c3c88350e65273e59e28b9256f19711741961410613e3a419fc | Python | 2,779 | 67 | #!/usr/bin/env python
import os, sys, random
import math
from csv import DictReader
from collections import defaultdict
def get_counts(count_filename, min_fl_count=2, key='id', min_len=None, max_len=None):
total = 0
count_d = defaultdict(lambda: 0)
for r in DictReader(open(count_filename), delimiter='\t'):... |
bb153bd2e0eda5f0efb65e61720bc520a0a5d8ec6d684eb99057071bea5fea2d | Python | 2,779 | 93 | import numpy as np
import pytest
from pandas.core.apply import (
_make_unique_kwarg_list,
maybe_mangle_lambdas,
)
def test_maybe_mangle_lambdas_passthrough():
assert maybe_mangle_lambdas("mean") == "mean"
assert maybe_mangle_lambdas(lambda x: x).__name__ == "<lambda>"
# don't mangle single lambda... |
efd093c13fec6df1017cc39b2c4d075da295c54bb152a685c614ab88848d82c0 | Python | 2,780 | 64 | import os
import subprocess
import sys
import pytest
class TestCLIErrorHandling:
"""Test CLI error handling and edge cases."""
@pytest.fixture(autouse=True)
def setup(self, synthetic_data, temp_output_dir):
"""Setup test environment."""
self.data = synthetic_data
self.output_dir ... |
b9de226d6c4506d5ae113d4ebeb8bc0e423dabfbf8549c54f082bdab004e3842 | Python | 2,781 | 81 | from __future__ import annotations
import numpy as np
from pandas.core.algorithms import unique1d
from pandas.core.arrays.categorical import (
Categorical,
CategoricalDtype,
recode_for_categories,
)
def recode_for_groupby(c: Categorical, sort: bool, observed: bool) -> Categorical:
"""
Code the c... |
3f814dfcaf19dd864da8c0ddf38312b8f0ab8ff332d7e72fb4f78821d7ea6984 | Python | 2,784 | 68 | # Copyright 2018-2024 Xanadu Quantum Technologies 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... |
497f79c12da9839adbecb83e740abb9fd16edd9a2cf7ff6854ad0fa36a810998 | Python | 2,784 | 76 | """
extraction.py
Created February 17, 2021
Provides methods for extracting grid data from images of leads.
"""
from typing import List, Optional, Union
import numpy as np
from . import frequency as grid_frequency
from .. import common
from .. import vision
from ..image import BinaryImage
def traceGridlines(binary... |
dc4c2bfdc204b542a79ab5352f3666d54bef4c924e6e6712957edcd01cebadaa | Python | 2,785 | 83 | import torch
import torch.nn as nn
import torch.nn.functional as F
# Adopted from https://gist.github.com/kevinzakka/dd9fa5177cda13593524f4d71eb38ad5
class SpatialSoftArgmax(nn.Module):
"""Spatial softmax as defined in [1].
Concretely, the spatial softmax of each feature
map is used to compute a weighted... |
b4a120ef4e431039aebdafb4e8c9ec44be67db7cbc63cf23fec78ea57d2a099a | Python | 2,786 | 90 | """
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 logging
from collections import deque
from pathlib import Path
import torch
from torch_geometric.data import Batch
from ocpmodels.co... |
2bc2ee8152f8551d4e5ef99e58f83576e3da55df6ccecb538807f5232cf6d9bd | Python | 2,787 | 108 | from io import BytesIO
import numpy as np
from odf.opendocument import OpenDocumentSpreadsheet
from odf.table import (
Table,
TableCell,
TableRow,
)
from odf.text import P
from pandas import (
DataFrame,
ExcelWriter,
Index,
date_range,
read_excel,
)
def _generate_dataframe():
N =... |
383a0733bdf64d438e12f17014d817f493cdb08a49b2ba2262d69c4a4acdad33 | Python | 2,787 | 100 | #%%
import numpy as np
import pandas as pd
from src.prep import bin_data, get_subsample
def _generate_data():
""" Generate data for testing """
# simulate data
data1 = np.arange(0,11,1)
data2 = np.arange(3,7,1)
# append data with itself
data1 = np.append(data1, data1)
data2 = np.append(da... |
f9ec0a155348f955daf961d4dac4fbf3a3a592f26be3aaada4f74934f06357e3 | Python | 2,787 | 95 | import argparse
from pathlib import Path
from sklearn.model_selection import LeaveOneOut, RepeatedKFold
from julearn.pipeline import PipelineCreator
from julearn.utils import configure_logging, logger, raise_error
from utils import load_and_prepare_data
from julearn import run_cross_validation
corr_signs = ["pos", ... |
6b29d66a1b2f9aff5f3b7580715dd73a39cd774d4bf2b0920bfff620d832f9a3 | Python | 2,788 | 59 | ##############################################################################
## ##
## This file is part of ModelBlocks. Copyright 2009, ModelBlocks developers. ##
## ##
#... |
0736f2c9160415f7c006a50e79a80211066ddc0eb3fae1a065894fd3aea7b6bc | Python | 2,790 | 72 | import numpy as np
import copy
from mne.stats import permutation_cluster_1samp_test
def simular_iteraciones_Ridge(Fake_Model, iteraciones, sesion, sujeto, fold, dstims_train_val, eeg_train_val,
dstims_test, eeg_test, Pesos_fake, Correlaciones_fake, Errores_fake):
print("\nSesion... |
d5d5fbd458ebf73f1e4eb1d394c36320ada0b6c97c6e2a0c30caf6dfe6bec1d8 | Python | 2,790 | 97 | #!/usr/bin/env python
'''
Testcases for the KwargsParser
'''
from windseer.data.process_datasets import *
from windseer.data import HDF5Dataset
import windseer
import copy
import os
import unittest
windseer_path = os.path.dirname(windseer.__file__)
testdata_folder = os.path.join(windseer_path, 'test', 'testdata')
te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.