code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from __future__ import print_function, division
import numpy as np
from scipy.spatial.distance import cdist
class Solver(object):
def __init__(self, df):
self.df = df
self.num_samples = self.df.shape[0]
self.samples = self.df.to_numpy()
def compute_pairwise_l2distance(self):
... | [
"scipy.spatial.distance.cdist",
"numpy.sum",
"numpy.abs",
"numpy.square",
"numpy.einsum",
"numpy.triu_indices",
"numpy.isfinite",
"numpy.isnan",
"numpy.max",
"numpy.array",
"numpy.exp",
"numpy.dot"
] | [((388, 424), 'numpy.triu_indices', 'np.triu_indices', (['self.num_samples', '(1)'], {}), '(self.num_samples, 1)\n', (403, 424), True, 'import numpy as np\n'), ((476, 537), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'self.samples[R, :]', 'self.samples[C, :]'], {}), "('ij,ij->i', self.samples[R, :], self.samples[C... |
import os
import numpy as np
import pandas as pd
from os.path import join
def search_best_id(root_path, index_list):
""" Given the indices in the list,
this function looks for the best realization
of the experiment, among different learning rates.
:param root_path: str of the folder containing result... | [
"pandas.DataFrame",
"numpy.sum",
"os.path.dirname",
"numpy.isnan",
"numpy.argmin",
"pandas.read_json",
"os.path.join"
] | [((1976, 2028), 'pandas.DataFrame', 'pd.DataFrame', (['list_all_samples'], {'columns': 'columns_name'}), '(list_all_samples, columns=columns_name)\n', (1988, 2028), True, 'import pandas as pd\n'), ((2875, 2901), 'os.path.dirname', 'os.path.dirname', (['json_path'], {}), '(json_path)\n', (2890, 2901), False, 'import os\... |
#!/usr/bin/python
import numpy as np
import sys
import os
import expression_parser
__doc__ = 'see source'
dx = 0
dy = 0
dz = 0
dt = 0
nx = 0
ny = 0
nz = 0
output_period = 0
n_ion_populations = 0
icmr = []
t_end = 0
tr_start = 0
deps = 0
deps_p = 0
deps_ph = 0
deps_i = 0
a0y = 0
a0z = 0
lmbda = 0
ne = 0
xsigma = 0
nf... | [
"chameleon.read2d",
"numpy.ceil",
"numpy.empty",
"numpy.floor",
"numpy.asfarray",
"numpy.zeros",
"expression_parser.evaluate",
"numpy.arange",
"numpy.loadtxt",
"expression_parser.to_polish",
"numpy.linspace",
"numpy.cos",
"numpy.reshape",
"os.path.join",
"os.listdir",
"numpy.sqrt"
] | [((3589, 3624), 'os.path.join', 'os.path.join', (['data_folder', '(name + t)'], {}), '(data_folder, name + t)\n', (3601, 3624), False, 'import os\n'), ((5248, 5264), 'numpy.empty', 'np.empty', (['(m, n)'], {}), '((m, n))\n', (5256, 5264), True, 'import numpy as np\n'), ((5277, 5295), 'numpy.arange', 'np.arange', (['(0)... |
import os
import random as ran
import time
import gym
from keras import backend as K
from keras.initializers import VarianceScaling
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D
from keras.optimizers import Adam
import numpy as np
from skimage.color import rgb2gray
from skimage.t... | [
"numpy.stack",
"skimage.color.rgb2gray",
"gym.make",
"dqn_lib.DQNAgent",
"random.randint",
"tensorflow.device",
"numpy.zeros",
"keras.layers.Flatten",
"numpy.clip",
"keras.optimizers.Adam",
"time.sleep",
"numpy.append",
"keras.initializers.VarianceScaling",
"keras.layers.Dense",
"skimage... | [((658, 675), 'skimage.color.rgb2gray', 'rgb2gray', (['observe'], {}), '(observe)\n', (666, 675), False, 'from skimage.color import rgb2gray\n'), ((1451, 1470), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (1460, 1470), True, 'import tensorflow as tf\n'), ((1653, 1668), 'ring_buffer.RingBuf... |
import numpy as np
import h5py
# from ipdb import set_trace as stop
__all__ = ['File_observation', 'File_photosphere', 'File_chromosphere']
class File_observation(object):
"""
Class that defines an observation. This can be used to easily save observations in the appropriate format
"""
def __init__(sel... | [
"numpy.savetxt",
"numpy.zeros",
"numpy.array",
"numpy.loadtxt",
"numpy.squeeze"
] | [((1218, 1268), 'numpy.zeros', 'np.zeros', (['(n_pixel, n_lambda, 4)'], {'dtype': 'np.float64'}), '((n_pixel, n_lambda, 4), dtype=np.float64)\n', (1226, 1268), True, 'import numpy as np\n'), ((1295, 1345), 'numpy.zeros', 'np.zeros', (['(n_pixel, n_lambda, 4)'], {'dtype': 'np.float64'}), '((n_pixel, n_lambda, 4), dtype=... |
"""ngutils - utilities for manipulating a neuroglancer viewer
"""
from copy import deepcopy
import numpy as np
import neuroglancer
"""A shader that displays an image as gray in Neuroglancer"""
gray_shader = """
void main() {
emitGrayscale(%f * toNormalized(getDataValue()));
}
"""
"""A shader that displays an ima... | [
"copy.deepcopy",
"neuroglancer.LocalVolume",
"neuroglancer.viewer_state.optional",
"numpy.iinfo",
"numpy.percentile",
"numpy.column_stack"
] | [((3785, 3797), 'copy.deepcopy', 'deepcopy', (['cs'], {}), '(cs)\n', (3793, 3797), False, 'from copy import deepcopy\n'), ((1099, 1118), 'neuroglancer.viewer_state.optional', 'optional', (['text_type'], {}), '(text_type)\n', (1107, 1118), False, 'from neuroglancer.viewer_state import wrapped_property, optional, text_ty... |
"""
gradient descent method1:
gradient methods with fixed step size
"""
import numpy as np
def main():
x = np.random.rand(100) # creat 100 numbers from 0 to 1.
y = 10 + 5 * x # creat a linear function
print(len(x), len(y))
epsilon = 0.01 # set threshold to stop loop
... | [
"numpy.random.rand"
] | [((123, 142), 'numpy.random.rand', 'np.random.rand', (['(100)'], {}), '(100)\n', (137, 142), True, 'import numpy as np\n')] |
import numpy as np
import skimage
from metric import metric
from nrm import nrm
from im2tiles import im2tiles
from numba import jit, njit
def Quality_Map(img, ref):
blockSize = 32
size_y = min(blockSize, img.shape[0])
size_x = min(blockSize, img.shape[1])
size_z = 1
# Tiles_img ... | [
"nrm.nrm",
"numpy.ones"
] | [((611, 640), 'numpy.ones', 'np.ones', (['Tiles_img[idx].shape'], {}), '(Tiles_img[idx].shape)\n', (618, 640), True, 'import numpy as np\n'), ((532, 551), 'nrm.nrm', 'nrm', (['Tiles_ref[idx]'], {}), '(Tiles_ref[idx])\n', (535, 551), False, 'from nrm import nrm\n'), ((559, 578), 'nrm.nrm', 'nrm', (['Tiles_img[idx]'], {}... |
# Copyright (c) 2015, <NAME>
# See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE>
import os
import inspect
import functools
import warnings
import socket
import datetime
import pprint
import copy
import numpy as np
import quaternion
import scipy.constants as spc
from scipy.interpolate im... | [
"pprint.pformat",
"numpy.abs",
"numpy.angle",
"numpy.empty",
"scipy.interpolate.CubicSpline",
"numpy.allclose",
"quaternion.as_float_array",
"numpy.prod",
"numpy.set_printoptions",
"quaternion.means.mean_rotor_in_chordal_metric",
"numpy.copy",
"quaternion.squad",
"quaternion.rotor_chordal_di... | [((1557, 1578), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (1572, 1578), False, 'import functools\n'), ((2383, 2437), 'numpy.testing.assert_', 'np.testing.assert_', (['val', "('Failed assertion:\\n\\t' + msg)"], {}), "(val, 'Failed assertion:\\n\\t' + msg)\n", (2401, 2437), True, 'import numpy as... |
"""Main module for training auto-constraint model."""
import argparse
import bisect
import datetime
import functools
import json
import os
import time
import torch
import torch.utils.tensorboard
import torch.utils.data
# numpy has come after pytorch due to MKL threading setup
import numpy as np
from sketchgraphs_mo... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.autograd.profiler.record_function",
"time.strftime",
"sketchgraphs_models.training.load_cuda_async",
"torch.device",
"os.path.join",
"sketchgraphs_models.autoconstraint.model.compute_average_losses",
"os.path.abspath",
"datetime.timedelta",
... | [((4389, 4425), 'sketchgraphs_models.autoconstraint.model.AutoconstraintModel', 'auto_model.AutoconstraintModel', (['core'], {}), '(core)\n', (4419, 4425), True, 'from sketchgraphs_models.autoconstraint import dataset, model as auto_model\n'), ((6033, 6073), 'sketchgraphs_models.distributed_utils.is_leader', 'distribut... |
import os
import pathlib
import io
import flask
import MySQLdb.cursors
from pymemcache.client.base import Client as MemcacheClient
import pymc_session
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from chainer.links import VGG16Layers
from PIL import Image
_config = None
def config()... | [
"chainer.links.VGG16Layers",
"io.BytesIO",
"sklearn.metrics.pairwise.cosine_similarity",
"os.environ.get",
"flask.jsonify",
"pymemcache.client.base.Client",
"numpy.array",
"os.path.splitext",
"pathlib.Path",
"os.path.join",
"os.listdir"
] | [((1804, 1828), 'os.listdir', 'os.listdir', (['FEATURES_DIR'], {}), '(FEATURES_DIR)\n', (1814, 1828), False, 'import os\n'), ((3438, 3496), 'chainer.links.VGG16Layers', 'VGG16Layers', ([], {'pretrained_model': '"""./VGG_ILSVRC_16_layers.npz"""'}), "(pretrained_model='./VGG_ILSVRC_16_layers.npz')\n", (3449, 3496), False... |
import numpy as np
class Loss:
def func(self, out, expect):
raise NotImplementedError
def dfunc(self, out, expect):
raise NotImplementedError
class Logistic(Loss):
def func(self, out, expect):
return -(expect * np.log(out) + (1 - expect) * np.log(1 - out))
def dfunc(self, o... | [
"numpy.log"
] | [((252, 263), 'numpy.log', 'np.log', (['out'], {}), '(out)\n', (258, 263), True, 'import numpy as np\n'), ((281, 296), 'numpy.log', 'np.log', (['(1 - out)'], {}), '(1 - out)\n', (287, 296), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from lineage.fitting_distribution import check_dist
# read data into DataFrame
df = pd.read_excel(r'./lineage/data/G1_G2_duration_control.xlsx')
##----------------------- Preprocessing the data ------------------------##
# dataFrmae into numpy array
a = df.values
G1 = a[:, 0]
G... | [
"pandas.read_excel",
"lineage.fitting_distribution.check_dist",
"numpy.isnan"
] | [((124, 183), 'pandas.read_excel', 'pd.read_excel', (['"""./lineage/data/G1_G2_duration_control.xlsx"""'], {}), "('./lineage/data/G1_G2_duration_control.xlsx')\n", (137, 183), True, 'import pandas as pd\n'), ((660, 688), 'lineage.fitting_distribution.check_dist', 'check_dist', (['G1'], {'verbose': '(True)'}), '(G1, ver... |
import numpy as np
import dynet as dy
class Bucket:
def __init__(self, gener_decoder, mlp_decoder, vocab, model, beam_width=None, prob=None):
self.gener_decoder = gener_decoder
self.mlp_decoder = mlp_decoder
self.vocab = vocab
self.model = model
self.beam_width = beam_width
... | [
"dynet.pick_batch_elems",
"dynet.concatenate_cols",
"numpy.transpose",
"dynet.reshape",
"numpy.array",
"numpy.reshape",
"dynet.dropout_dim",
"dynet.esum"
] | [((743, 844), 'numpy.reshape', 'np.reshape', (['truth_batch', '(truth_batch_dim[0], truth_batch_dim[1] * truth_batch_dim[2])'], {'order': '"""F"""'}), "(truth_batch, (truth_batch_dim[0], truth_batch_dim[1] *\n truth_batch_dim[2]), order='F')\n", (753, 844), True, 'import numpy as np\n'), ((888, 909), 'numpy.array', ... |
'''
If you are using a GPU, write the following in ~/.theanorc.
[global]
device=gpu
floatX=float32
[blas]
ldflags=-lopenblas
[cuda]
root=/opt/apps/cuda/7.0
[nvcc]
fastmath=True
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import un... | [
"numpy.load",
"numpy.save",
"bmc.BMC",
"numpy.float32",
"lasagne.init.Constant",
"numpy.transpose",
"numpy.zeros",
"numpy.linalg.eig",
"cPickle.dump",
"numpy.rot90",
"sklearn.decomposition.PCA",
"numpy.random.normal",
"numpy.random.choice",
"numpy.linspace",
"numpy.sqrt"
] | [((835, 878), 'numpy.load', 'np.load', (['"""../data/sdss_training_images.npy"""'], {}), "('../data/sdss_training_images.npy')\n", (842, 878), True, 'import numpy as np\n'), ((964, 1007), 'numpy.load', 'np.load', (['"""../data/sdss_training_labels.npy"""'], {}), "('../data/sdss_training_labels.npy')\n", (971, 1007), Tr... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... | [
"SimpleITK.HausdorffDistanceImageFilter",
"torch.nn.functional.binary_cross_entropy",
"InnerEye.Azure.azure_util.get_run_context_or_default",
"InnerEye.ML.utils.sequence_utils.get_masked_model_outputs_and_labels",
"numpy.mean",
"SimpleITK.Cast",
"numpy.nanmean",
"SimpleITK.GetArrayViewFromImage",
"t... | [((1592, 1614), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1601, 1614), False, 'from dataclasses import dataclass, field\n'), ((1712, 1734), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1721, 1734), False, 'from dataclasses import datac... |
import numpy as np
import numpy.typing as npt
import iterations_lib.python_inspectors_diag.utils as utils
from typing import Tuple
def TwoSGD_solver(complex_matrix: np.ndarray,
f_vector: np.ndarray,
u0_vector: np.ndarray = None,
eps: float = 10e-7,
... | [
"numpy.conj",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"iterations_lib.python_inspectors_diag.utils.l2_norm",
"iterations_lib.python_inspectors_diag.utils.matrix_diag_prod",
"iterations_lib.python_inspectors_diag.utils.vec_dot_complex_prod"
] | [((630, 657), 'numpy.zeros', 'np.zeros', (['(1,)'], {'dtype': 'float'}), '((1,), dtype=float)\n', (638, 657), True, 'import numpy as np\n'), ((863, 902), 'numpy.array', 'np.array', (['complex_matrix'], {'dtype': 'complex'}), '(complex_matrix, dtype=complex)\n', (871, 902), True, 'import numpy as np\n'), ((918, 951), 'n... |
#-*-: coding:utf-8 -*-
from __future__ import absolute_import
import numpy
def load_data(trainset='lcg/DL_train.csv',validset='lcg/DL_valid.csv',testset='lcg/DL_test.csv'):
#分别读入三个文件并share他们
data=numpy.loadtxt(validset, delimiter=',', dtype=float, skiprows=1)
valid_set_x, valid_set_y =(data[:,:-1],data[:,... | [
"numpy.loadtxt"
] | [((206, 269), 'numpy.loadtxt', 'numpy.loadtxt', (['validset'], {'delimiter': '""","""', 'dtype': 'float', 'skiprows': '(1)'}), "(validset, delimiter=',', dtype=float, skiprows=1)\n", (219, 269), False, 'import numpy\n'), ((335, 397), 'numpy.loadtxt', 'numpy.loadtxt', (['testset'], {'delimiter': '""","""', 'dtype': 'flo... |
import math
import numpy as np
def eval_state(probs, labels, thr):
predict = probs >= thr
TN = np.sum((labels == 0) & (predict == False))
FN = np.sum((labels == 1) & (predict == False))
FP = np.sum((labels == 0) & (predict == True))
TP = np.sum((labels == 1) & (predict == True))
return TN, FN,... | [
"numpy.sum",
"math.fabs"
] | [((105, 147), 'numpy.sum', 'np.sum', (['((labels == 0) & (predict == False))'], {}), '((labels == 0) & (predict == False))\n', (111, 147), True, 'import numpy as np\n'), ((157, 199), 'numpy.sum', 'np.sum', (['((labels == 1) & (predict == False))'], {}), '((labels == 1) & (predict == False))\n', (163, 199), True, 'impor... |
# --------------
# Code starts here
import numpy as np
# Code starts here
# Adjacency matrix
adj_mat = np.array([[0,0,0,0,0,0,1/3,0],
[1/2,0,1/2,1/3,0,0,0,0],
[1/2,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1/2,1/3,0,0,1/3,0],
... | [
"numpy.argmax",
"numpy.ones",
"numpy.linalg.eig",
"numpy.linalg.norm",
"numpy.array",
"numpy.dot"
] | [((106, 397), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0, 1 / 3, 0], [1 / 2, 0, 1 / 2, 1 / 3, 0, 0, 0, 0], [1 / 2,\n 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1 / 2, 1 / 3, 0,\n 0, 1 / 3, 0], [0, 0, 0, 1 / 3, 1 / 3, 0, 0, 1 / 2], [0, 0, 0, 0, 1 / 3,\n 0, 0, 1 / 2], [0, 0, 0, 0, 1 / 3, 1, 1 /... |
from distutils.version import LooseVersion
import pytest
import numpy as np
from opensfm.synthetic_data import synthetic_examples
def pytest_configure(config):
use_legacy_numpy_printoptions()
def use_legacy_numpy_printoptions():
"""Ensure numpy use legacy print formant."""
if LooseVersion(np.__version... | [
"numpy.set_printoptions",
"numpy.random.seed",
"distutils.version.LooseVersion",
"pytest.fixture",
"opensfm.synthetic_data.synthetic_examples.synthetic_ellipse_scene"
] | [((393, 423), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (407, 423), False, 'import pytest\n'), ((451, 469), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (465, 469), True, 'import numpy as np\n'), ((481, 525), 'opensfm.synthetic_data.synthetic_examples... |
##################################################################
# <NAME> #
# https://www.linkedin.com/in/haosleeper/ #
##################################################################
import logging
import sys
import copy
import nump... | [
"copy.deepcopy",
"numpy.sum",
"pandas.DataFrame.from_dict",
"logging.basicConfig",
"numpy.abs",
"numpy.mean",
"numpy.intersect1d",
"logging.getLogger"
] | [((430, 541), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO', 'format': 'log_format', 'datefmt': '"""%m/%d %I:%M:%S %p"""'}), "(stream=sys.stdout, level=logging.INFO, format=\n log_format, datefmt='%m/%d %I:%M:%S %p')\n", (449, 541), False, 'import logging\n'), ((... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import random
cmd = None
debug = False
seed = 20160930
oldseed = False
alpha = 3.0
if __name__ == '__main__':
if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) < 2:
print ('Usage: python bwm.py <cmd> [arg...] [opts...]')
print (' ... | [
"matplotlib.pyplot.title",
"random.shuffle",
"numpy.fft.ifft2",
"numpy.copy",
"cv2.imwrite",
"numpy.power",
"matplotlib.pyplot.yticks",
"cv2.split",
"random.seed",
"sys.argv.index",
"numpy.real",
"matplotlib.pyplot.xticks",
"numpy.uint8",
"matplotlib.pyplot.show",
"numpy.fft.fft2",
"cv... | [((2067, 2081), 'cv2.split', 'cv2.split', (['img'], {}), '(img)\n', (2076, 2081), False, 'import cv2\n'), ((2093, 2113), 'cv2.merge', 'cv2.merge', (['[r, g, b]'], {}), '([r, g, b])\n', (2102, 2113), False, 'import cv2\n'), ((2225, 2240), 'cv2.imread', 'cv2.imread', (['fn1'], {}), '(fn1)\n', (2235, 2240), False, 'import... |
import numpy as np
import pandas as pd
import pickle
import multiprocessing
from joblib import Parallel, delayed
from run_analysis import load_metabric, illumina2ensembl_dictionary, get_reactome_illumina, return_pathway
import porch
def permute_set(set_size):
try:
set_genes = np.random.choice(genes, set_s... | [
"numpy.abs",
"porch.survival",
"porch.porch_proc",
"joblib.Parallel",
"numpy.arange",
"numpy.random.choice",
"run_analysis.load_metabric",
"joblib.delayed",
"numpy.round",
"numpy.unique",
"multiprocessing.cpu_count"
] | [((882, 910), 'run_analysis.load_metabric', 'load_metabric', (['metabric_path'], {}), '(metabric_path)\n', (895, 910), False, 'from run_analysis import load_metabric, illumina2ensembl_dictionary, get_reactome_illumina, return_pathway\n'), ((1195, 1228), 'numpy.unique', 'np.unique', (["activities['set_size']"], {}), "(a... |
"""
Builder for Distiller
Author: <NAME> (https://github.com/vectominist)
"""
import sys
import copy
import math
from distutils.util import strtobool
import yaml
import numpy as np
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence
from .model import DistillerConfig, DistillerModel
i... | [
"distutils.util.strtobool",
"torch.load",
"torch.FloatTensor",
"numpy.ones",
"torch.nn.utils.rnn.pad_sequence",
"torch.no_grad",
"sys.modules.get"
] | [((2602, 2632), 'numpy.ones', 'np.ones', (['(batch_size, seq_len)'], {}), '((batch_size, seq_len))\n', (2609, 2632), True, 'import numpy as np\n'), ((4536, 4579), 'torch.nn.utils.rnn.pad_sequence', 'pad_sequence', (['wave_inputs'], {'batch_first': '(True)'}), '(wave_inputs, batch_first=True)\n', (4548, 4579), False, 'f... |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018 www.open3d.org
#
# Permission is her... | [
"traitlets.Unicode",
"numpy.asarray",
"traitlets.Instance",
"IPython.display.display"
] | [((3691, 3704), 'IPython.display.display', 'display', (['self'], {}), '(self)\n', (3698, 3704), False, 'from IPython.display import display\n'), ((2214, 2240), 'traitlets.Unicode', 'Unicode', (['"""JVisualizerView"""'], {}), "('JVisualizerView')\n", (2221, 2240), False, 'from traitlets import Unicode, Float, List, Inst... |
#!/usr/bin/env python
# coding: utf-8
# # NVIDIA TensorRT MNIST Example with Triton Inference Server
#
# 
#
# This example shows how you can deploy a TensorRT model with NVIDIA Triton Server. In this case we use a prebuilt TensorRT model for NVIDIA v100 GPUs.
#
# Note this example requires some a... | [
"tensorflow_datasets.load",
"json.loads",
"tensorflow_datasets.as_numpy",
"matplotlib.pyplot.imshow",
"numpy.expand_dims",
"tensorflow.cast",
"numpy.array",
"numpy.reshape"
] | [((1451, 1554), 'tensorflow_datasets.load', 'tfds.load', (['"""mnist"""'], {'split': "['train', 'test']", 'shuffle_files': '(True)', 'as_supervised': '(True)', 'with_info': '(True)'}), "('mnist', split=['train', 'test'], shuffle_files=True,\n as_supervised=True, with_info=True)\n", (1460, 1554), True, 'import tensor... |
from PIL import Image
from filters.emboss_filter import EmbossFilter
from filters.mean_filter import MeanFilter, MeanFilterY
from filters.median_filter import MedianFilter, MedianFilterY
from filters.prewitt_filter import PrewittFilter
from filters.negative_filter import NegativeFilterRGB, NegativeFilterYIQ
from tarefa... | [
"argparse.ArgumentParser",
"numpy.copy",
"filters.emboss_filter.EmbossFilter",
"tarefas.tarefa6.reproduce_example_6",
"filters.mean_filter.MeanFilter",
"filters.prewitt_filter.PrewittFilter",
"filters.negative_filter.NegativeFilterRGB",
"numpy.zeros",
"numpy.ones",
"filters.mean_filter.MeanFilterY... | [((419, 526), 'argparse.ArgumentParser', 'ap.ArgumentParser', ([], {'description': '"""System made for the lecture Processamento Digital de Imagens in UFPB."""'}), "(description=\n 'System made for the lecture Processamento Digital de Imagens in UFPB.')\n", (436, 526), True, 'import argparse as ap\n'), ((4773, 4788)... |
# work on increasing efficiency
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
def kml2slu(file, write=False):
"""Converts Polygons drawn in Google Earth to slu used by GeoClaw flag_regions
:param str file: path to .kml file downloaded from Google Earth
... | [
"numpy.min",
"numpy.max"
] | [((773, 789), 'numpy.min', 'np.min', (['[y0, y1]'], {}), '([y0, y1])\n', (779, 789), True, 'import numpy as np\n'), ((816, 832), 'numpy.max', 'np.max', (['[y0, y1]'], {}), '([y0, y1])\n', (822, 832), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 5 10:59:49 2018
@author: joseb
"""
# min x1^2 + x2^2
# s.t. x1^2 +x1*x2 + x2^2 - 3 <= 0
# var x1, x2
# %%
from scipy.optimize import minimize
import numpy as np
from cvxpy import *
print('\nSOLVING USING SCIPY\n')
# Jacobian
def jacobian(x):
dx =... | [
"numpy.asarray",
"numpy.array",
"numpy.mat"
] | [((1439, 1459), 'numpy.asarray', 'np.asarray', (['(10, 10)'], {}), '((10, 10))\n', (1449, 1459), True, 'import numpy as np\n'), ((359, 377), 'numpy.array', 'np.array', (['(dx, dy)'], {}), '((dx, dy))\n', (367, 377), True, 'import numpy as np\n'), ((456, 490), 'numpy.array', 'np.array', (['((d11, d12), (d12, d22))'], {}... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class Momentum:
def __init__(self, num_features=5, alpha=0.7, beta=0.9):
self.m = np.zeros((num_features, 1))
self.alpha = alpha
self.beta = beta
def optimize_weights(self, weights, grads):
self.m = self.be... | [
"numpy.abs",
"numpy.amin",
"numpy.log",
"pandas.read_csv",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"numpy.amax",
"numpy.linalg.norm",
"numpy.array",
"numpy.exp"
] | [((2403, 2432), 'numpy.amin', 'np.amin', (['new_features'], {'axis': '(1)'}), '(new_features, axis=1)\n', (2410, 2432), True, 'import numpy as np\n'), ((2445, 2474), 'numpy.amax', 'np.amax', (['new_features'], {'axis': '(1)'}), '(new_features, axis=1)\n', (2452, 2474), True, 'import numpy as np\n'), ((2601, 2658), 'pan... |
# External Modules
import torch
from torch import cuda, FloatTensor, LongTensor
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
from typing import Union
from time import time
# comes from PointCNN.Pytorch repository
# https://github.com/hxdengBerkeley/PointCNN.Pytorch.g... | [
"numpy.stack",
"torch.topk",
"time.time",
"sklearn.neighbors.NearestNeighbors",
"torch.sum"
] | [((1141, 1147), 'time.time', 'time', ([], {}), '()\n', (1145, 1147), False, 'from time import time\n'), ((2319, 2356), 'torch.sum', 'torch.sum', (['((mpts - mseed) ** 2)'], {'dim': '(1)'}), '((mpts - mseed) ** 2, dim=1)\n', (2328, 2356), False, 'import torch\n'), ((2461, 2502), 'torch.topk', 'torch.topk', (['mdist'], {... |
#!/usr/bin/env python
from decimal import Decimal
import numpy as np
from numpy.testing import assert_almost_equal
from tune.db_workers.utils import (
TimeControl,
compute_probabilities,
compute_probabilities_for_bias,
draw_rate_to_elo,
elo_to_bayeselo,
ldw_probabilities,
penta,
penta... | [
"tune.db_workers.utils.compute_probabilities",
"decimal.Decimal",
"numpy.testing.assert_almost_equal",
"tune.db_workers.utils.compute_probabilities_for_bias",
"tune.db_workers.utils.penta_to_score",
"tune.db_workers.utils.penta",
"numpy.array",
"tune.db_workers.utils.elo_to_bayeselo",
"tune.db_worke... | [((364, 389), 'numpy.array', 'np.array', (['[0.1, 0.2, 0.7]'], {}), '([0.1, 0.2, 0.7])\n', (372, 389), True, 'import numpy as np\n'), ((401, 426), 'numpy.array', 'np.array', (['[0.2, 0.2, 0.6]'], {}), '([0.2, 0.2, 0.6])\n', (409, 426), True, 'import numpy as np\n'), ((441, 458), 'tune.db_workers.utils.penta', 'penta', ... |
"""
This module provides utilities for creating custom data viewers. The
goal of this module is to make it easy for users to make new
data viewers by focusing on matplotlib visualization logic,
and not UI or event processing logic.
The end user typically interacts with this code via
:func:`glue.custom_viewer`
"""
fro... | [
"functools.partial",
"numpy.asarray",
"copy.copy",
"inspect.getmodule",
"inspect.getargspec"
] | [((6956, 6972), 'inspect.getargspec', 'getargspec', (['func'], {}), '(func)\n', (6966, 6972), False, 'from inspect import getmodule, getargspec\n'), ((3463, 3481), 'numpy.asarray', 'np.asarray', (['values'], {}), '(values)\n', (3473, 3481), True, 'import numpy as np\n'), ((6281, 6319), 'functools.partial', 'partial', (... |
"""
Goal - pass argument to make figure with and without data
Date - Mar 15 2021
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import cm
import argparse
import seaborn as sns
#argparse
def boolean_string(s):
# this function helps with getting Boolean in... | [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.xticks",
"numpy.linspace",
"numpy.exp",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((491, 516), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (514, 516), False, 'import argparse\n'), ((1404, 1466), 'pandas.read_csv', 'pd.read_csv', (["('../../data/temp_collective/roi/' + args.a_string)"], {}), "('../../data/temp_collective/roi/' + args.a_string)\n", (1415, 1466), True, 'imp... |
#import useful libraries
import numpy as np
import myml.discriminant as mydsc
import myml.data_separation as mydata
import myml.images as myimg
import myml.factorizations as myfac
import matplotlib.pyplot as plot
import sklearn.decomposition as skd
import time
... | [
"sklearn.decomposition.NMF",
"numpy.load",
"numpy.save",
"myml.discriminant.constructDistriminantSet",
"numpy.zeros",
"myml.factorizations.projrep",
"time.time",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"numpy.arange",
"myml.images.plotDataset",
"myml.discriminant.evalDiscrim... | [((492, 534), 'myml.factorizations.projrep', 'myfac.projrep', (['Xraw'], {'k_or_tol': 'num_features'}), '(Xraw, k_or_tol=num_features)\n', (505, 534), True, 'import myml.factorizations as myfac\n'), ((817, 828), 'time.time', 'time.time', ([], {}), '()\n', (826, 828), False, 'import time\n'), ((876, 935), 'myml.discrimi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file belong to https://github.com/snolfi/evorobotpy
and has been written by <NAME> and <NAME>, <EMAIL>, <EMAIL>
evoalgo.py contains methods for showing, saving and loading data
"""
import numpy as np
import time
class EvoAlgo(object):
def __init__(s... | [
"numpy.load",
"numpy.save",
"numpy.copy",
"time.time",
"numpy.append",
"numpy.arange"
] | [((1127, 1157), 'numpy.arange', 'np.arange', (['(0)'], {'dtype': 'np.float64'}), '(0, dtype=np.float64)\n', (1136, 1157), True, 'import numpy as np\n'), ((1328, 1339), 'time.time', 'time.time', ([], {}), '()\n', (1337, 1339), False, 'import time\n'), ((1569, 1599), 'numpy.arange', 'np.arange', (['(0)'], {'dtype': 'np.f... |
import math
import ctre
import numpy as np
from pyswervedrive.swervemodule import SwerveModule
from utilities.functions import constrain_angle
class PhysicsEngine:
X_WHEELBASE = 0.50
Y_WHEELBASE = 0.62
GRAVITY = 9.8
def __init__(self, controller):
self.controller = controll... | [
"math.hypot",
"utilities.functions.constrain_angle",
"numpy.linalg.lstsq",
"math.atan2",
"numpy.zeros",
"math.sin",
"numpy.array",
"math.cos"
] | [((4289, 4356), 'numpy.array', 'np.array', (['[[1, 0, 1], [0, 1, 1], [1, 0, 1], [0, 1, 1]]'], {'dtype': 'float'}), '([[1, 0, 1], [0, 1, 1], [1, 0, 1], [0, 1, 1]], dtype=float)\n', (4297, 4356), True, 'import numpy as np\n'), ((4378, 4407), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {'dtype': 'float'}), '((4, 1), dtype=flo... |
import torch
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import numpy as np
import os
import librosa
import json
# from scipy.io.wavfile import read
class MP3Audio(Dataset):
'''
# https://nbviewer.org/github/mdeff/fma/blob/outputs/usage.ipynb
mp4 audio는 학습된 모델의 train단계에서 사용됩니다.
... | [
"pandas.DataFrame",
"json.load",
"torch.utils.data.DataLoader",
"os.walk",
"numpy.zeros",
"numpy.expand_dims",
"librosa.load",
"numpy.array",
"os.listdir"
] | [((4262, 4312), 'torch.utils.data.DataLoader', 'DataLoader', (['mp3_data'], {'batch_size': '(8)', 'drop_last': '(True)'}), '(mp3_data, batch_size=8, drop_last=True)\n', (4272, 4312), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((636, 666), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['path']... |
import os
import time
import pickle
import torch as t
import numpy as np
from torch.utils import data
import gzip
from time import time
from config import DefaultConfig
import torch
import dgl
import threading
class dataSet(data.Dataset):
def __init__(self, root_dir, protein_list_file):
super(dataSet, sel... | [
"gzip.open",
"numpy.abs",
"dgl.batch",
"numpy.zeros",
"torch.cat",
"dgl.DGLGraph",
"time.time",
"numpy.transpose",
"numpy.array",
"config.DefaultConfig",
"torch.tensor",
"torch.from_numpy"
] | [((4432, 4454), 'dgl.batch', 'dgl.batch', (['graph_batch'], {}), '(graph_batch)\n', (4441, 4454), False, 'import dgl\n'), ((4475, 4499), 'torch.cat', 'torch.cat', (['protbert_data'], {}), '(protbert_data)\n', (4484, 4499), False, 'import torch\n'), ((1094, 1109), 'config.DefaultConfig', 'DefaultConfig', ([], {}), '()\n... |
import numpy as np
import matplotlib.pyplot as plt
from Lab1.problem3_env import Env
class QLearning():
def __init__(self):
self.num_moves = 10000000
self.environment = Env() # Environment class with the model
self.QValues = np.zeros(( self.environment.NUM_STATES, self.environment.NUM_... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"Lab1.problem3_env.Env",
"matplotlib.pyplot.plot",
"numpy.argmax",
"numpy.zeros",
"numpy.amax",
"numpy.max",
"numpy.random.random",
"numpy.random.choice",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
... | [((192, 197), 'Lab1.problem3_env.Env', 'Env', ([], {}), '()\n', (195, 197), False, 'from Lab1.problem3_env import Env\n'), ((258, 327), 'numpy.zeros', 'np.zeros', (['(self.environment.NUM_STATES, self.environment.NUM_ACTIONS)'], {}), '((self.environment.NUM_STATES, self.environment.NUM_ACTIONS))\n', (266, 327), True, '... |
import cv2
import numpy as np
# A0. Set-up
print("[INFO] Setting up video capture...")
device_cap = 1
video = cv2.VideoCapture(device_cap, cv2.CAP_DSHOW)
video.set(cv2.CAP_PROP_FRAME_WIDTH, 480)
video.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
class_names = []
class_file = 'coco.names'
with open(class_file, ... | [
"cv2.dnn_DetectionModel",
"cv2.waitKey",
"numpy.floor",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.destroyAllWindows"
] | [((121, 164), 'cv2.VideoCapture', 'cv2.VideoCapture', (['device_cap', 'cv2.CAP_DSHOW'], {}), '(device_cap, cv2.CAP_DSHOW)\n', (137, 164), False, 'import cv2\n'), ((520, 569), 'cv2.dnn_DetectionModel', 'cv2.dnn_DetectionModel', (['weights_path', 'config_path'], {}), '(weights_path, config_path)\n', (542, 569), False, 'i... |
import pandas as pd
from importlib import reload # allows reloading of modules
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import ipywidgets as widgets
from IPython.display import display, clear_output
from importlib import reload
import asyncio
import pickle
import pmagpy.p... | [
"pmagpy.pmag.magic_write",
"pmagpy.pmag.dir2cart",
"pickle.dump",
"numpy.abs",
"numpy.sum",
"numpy.amin",
"numpy.polyfit",
"pandas.read_csv",
"numpy.empty",
"pmagpy.pmag.cart2dir",
"ipywidgets.Output",
"numpy.mean",
"numpy.linalg.svd",
"pmagpy.ipmag.atrm_magic",
"numpy.sin",
"pickle.lo... | [((52760, 52878), 'ipywidgets.Layout', 'widgets.Layout', ([], {'width': '"""60%"""', 'display': '"""flex"""', 'flex_flow': '"""row"""', 'justify_content': '"""space-around"""', 'margin': '"""1000px left"""'}), "(width='60%', display='flex', flex_flow='row',\n justify_content='space-around', margin='1000px left')\n",... |
import warnings
import numpy as np
from scipy.sparse import csc_matrix
from numba import jit, float64, void
from compecon import Basis
__author__ = 'Randall'
# TODO: complete this class
# todo: compare performance of csr_matrix and csc_matrix to deal with sparse interpolation operators
class BasisChebyshev(Basis):
... | [
"numba.void",
"numpy.meshgrid",
"numpy.isscalar",
"numpy.asarray",
"numpy.zeros",
"scipy.sparse.csc_matrix",
"numpy.min",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"numpy.cos",
"warnings.warn",
"numpy.atleast_1d",
"numpy.mat",
"numpy.diag"
] | [((7542, 7573), 'numba.void', 'void', (['float64[:]', 'float64[:, :]'], {}), '(float64[:], float64[:, :])\n', (7546, 7573), False, 'from numba import jit, float64, void\n'), ((6571, 6589), 'numpy.isscalar', 'np.isscalar', (['order'], {}), '(order)\n', (6582, 6589), True, 'import numpy as np\n'), ((7478, 7515), 'numpy.a... |
import sys
import numpy as np
import torch
from pytorch_fid.inception import InceptionV3
sys.path.insert(0, '/workspace')
from datasets.custom_subset import SingleClassSubset
from utils.stylegan import create_image
class PRCD:
def __init__(self, dataset_real, dataset_fake, device, crop_size=None, generator=None... | [
"torch.utils.data.DataLoader",
"sys.path.insert",
"datasets.custom_subset.SingleClassSubset",
"torch.cdist",
"numpy.mean",
"pytorch_fid.inception.InceptionV3",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.sort",
"torch.from_numpy"
] | [((91, 123), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/workspace"""'], {}), "(0, '/workspace')\n", (106, 123), False, 'import sys\n'), ((753, 777), 'pytorch_fid.inception.InceptionV3', 'InceptionV3', (['[block_idx]'], {}), '([block_idx])\n', (764, 777), False, 'from pytorch_fid.inception import InceptionV3\n'... |
""" helper function
author baiyu
"""
import os
import sys
import re
import datetime
import numpy
import torch
from torch.optim.lr_scheduler import _LRScheduler
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
def get_network(args):
""" return given network
... | [
"models.preactresnet.preactresnet18",
"models.resnext.resnext152",
"models.shufflenet.shufflenet",
"models.inceptionv4.inception_resnet_v2",
"models.resnet.resnet152",
"models.stochasticdepth.stochastic_depth_resnet18",
"numpy.mean",
"models.preactresnet.preactresnet152",
"models.googlenet.googlenet... | [((5949, 6082), 'torchvision.datasets.CIFAR100', 'torchvision.datasets.CIFAR100', ([], {'root': '"""/home/lab265/lab265/datasets/CIFAR100"""', 'train': '(True)', 'download': '(True)', 'transform': 'transform_train'}), "(root='/home/lab265/lab265/datasets/CIFAR100',\n train=True, download=True, transform=transform_tr... |
import os
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def plot(file_name):
keyword = os.path.basename(file_name)
keyword = keyword[:keyword.find("-")]
data = []
with open(file_name, "r") as file:
for i, line in enumerate(file.readlines()):
if i... | [
"matplotlib.pyplot.title",
"os.path.basename",
"matplotlib.pyplot.clf",
"os.getcwd",
"numpy.sort",
"matplotlib.pyplot.step",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"tkinter.Tk",
"matplotlib.pyplot.savefig"
] | [((129, 156), 'os.path.basename', 'os.path.basename', (['file_name'], {}), '(file_name)\n', (145, 156), False, 'import os\n'), ((623, 651), 'numpy.array', 'np.array', (['data'], {'dtype': 'object'}), '(data, dtype=object)\n', (631, 651), True, 'import numpy as np\n'), ((663, 684), 'numpy.sort', 'np.sort', (['data'], {'... |
from __future__ import print_function
import os
import glob # may cause segmentation fault in (C+Python) environment
import numpy as np
import cv2
import csv
import faiss
import pandas as pd
import utm
### For dataset
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from ... | [
"cv2.resize",
"utm.from_latlon",
"numpy.abs",
"torch.utils.data.DataLoader",
"os.path.basename",
"pandas.read_csv",
"sys.path.insert",
"numpy.isnan",
"torch.cat",
"cv2.VideoCapture",
"numpy.linalg.norm",
"get_streetview.GetStreetView_fromID",
"os.path.join",
"vps.vps"
] | [((452, 504), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/ccsmm/workdir/ccsmmutils"""'], {}), "(0, '/home/ccsmm/workdir/ccsmmutils')\n", (467, 504), False, 'import sys\n'), ((4729, 4752), 'numpy.linalg.norm', 'np.linalg.norm', (['(p1 - p2)'], {}), '(p1 - p2)\n', (4743, 4752), True, 'import numpy as np\n'),... |
import pandas as pd
import lightgbm as lgb
from sklearn.metrics import mean_squared_error
import utils as utils
import numpy as np
import glob
def predict(X_test):
#feature columns [2,3,5,6,11,12,13]
print('Loading model to predict...')
# load model to predict
bst = lgb.Booster(model_file='./model.txt')
# can onl... | [
"pandas.read_csv",
"lightgbm.Booster",
"numpy.savetxt",
"glob.glob"
] | [((534, 565), 'glob.glob', 'glob.glob', (["(subdirname + '*.csv')"], {}), "(subdirname + '*.csv')\n", (543, 565), False, 'import glob\n'), ((272, 309), 'lightgbm.Booster', 'lgb.Booster', ([], {'model_file': '"""./model.txt"""'}), "(model_file='./model.txt')\n", (283, 309), True, 'import lightgbm as lgb\n'), ((609, 635)... |
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import os
import numpy as np
import cv2
from PIL import Image
class Node():
def __init__(self, start_idx, end_idx, level, idx):
self.start_idx = start_idx
self.end_idx =... | [
"matplotlib.pyplot.axes",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.linalg.norm",
"matplotlib.pyplot.gca",
"matplotlib.backends.backend_agg.FigureCanvasAgg",
"cv2.imwrite",
"cv2.cvtColor",
"numpy.power",
"matplotlib.pyplot.ylim",
"numpy.square",
"matplotlib.pyplot.gcf",
"numpy.all",
... | [((10039, 10067), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 10)'}), '(figsize=(25, 10))\n', (10049, 10067), True, 'import matplotlib.pyplot as plt\n'), ((12147, 12181), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[min_x - 50, max_x + 50]'], {}), '([min_x - 50, max_x + 50])\n', (12155, 12181), True, ... |
#!/usr/bin/env python3
# functions for working with raster data
# written by <NAME>, 2020
from osgeo import gdal, osr
import numpy as np
import subprocess as sp
import os, inspect
def get_nodata(raster_file, band = 1):
"""Get raster nodata value"""
file = gdal.Open(raster_file)
nodata = file.GetRasterBand(band).G... | [
"numpy.stack",
"subprocess.run",
"os.path.abspath",
"inspect.getsourcelines",
"numpy.sum",
"numpy.std",
"numpy.min",
"numpy.max",
"numpy.mean",
"inspect.isfunction",
"osgeo.gdal.Open",
"osgeo.gdal.GetDriverByName",
"osgeo.gdal.GetDataTypeName"
] | [((261, 283), 'osgeo.gdal.Open', 'gdal.Open', (['raster_file'], {}), '(raster_file)\n', (270, 283), False, 'from osgeo import gdal, osr\n'), ((425, 447), 'osgeo.gdal.Open', 'gdal.Open', (['raster_file'], {}), '(raster_file)\n', (434, 447), False, 'from osgeo import gdal, osr\n'), ((598, 620), 'osgeo.gdal.Open', 'gdal.O... |
import sys
import numpy as np
from scipy.spatial.distance import pdist
from gmr.utils import check_random_state
from nose.tools import assert_equal, assert_less, assert_raises, assert_in, assert_false, assert_true
from nose.plugins.skip import SkipTest
from numpy.testing import assert_array_almost_equal
try:
# Pyth... | [
"numpy.sum",
"numpy.abs",
"nose.tools.assert_true",
"numpy.ones",
"sklearn.datasets.load_boston",
"scipy.spatial.distance.pdist",
"numpy.linalg.norm",
"numpy.testing.assert_array_almost_equal",
"gmr.GMM",
"numpy.ndarray",
"numpy.meshgrid",
"nose.tools.assert_less",
"numpy.copy",
"gmr.plot_... | [((574, 595), 'gmr.utils.check_random_state', 'check_random_state', (['(0)'], {}), '(0)\n', (592, 595), False, 'from gmr.utils import check_random_state\n'), ((605, 640), 'numpy.array', 'np.array', (['[[0.0, 1.0], [2.0, -1.0]]'], {}), '([[0.0, 1.0], [2.0, -1.0]])\n', (613, 640), True, 'import numpy as np\n'), ((673, 73... |
import scipy.sparse.linalg as spsl
import scipy.linalg as spl
import scipy.sparse as spm
import scipy.optimize as spo
import numpy as np
from numerics.softmax import logistic
from utils.label_factory import BinaryLabels
n_classes = 10
class HyperParameterOptimiser(object):
def __init__(self):
pass
d... | [
"numpy.log",
"numerics.softmax.logistic",
"utils.label_factory.BinaryLabels",
"numpy.diagonal",
"scipy.sparse.csc_matrix",
"scipy.sparse.identity",
"numpy.array",
"numpy.sqrt"
] | [((1880, 1901), 'numerics.softmax.logistic', 'logistic', (['f_posterior'], {}), '(f_posterior)\n', (1888, 1901), False, 'from numerics.softmax import logistic\n'), ((2009, 2029), 'numpy.sqrt', 'np.sqrt', (['neg_hessian'], {}), '(neg_hessian)\n', (2016, 2029), True, 'import numpy as np\n'), ((2698, 2715), 'scipy.sparse.... |
import numpy as np
import pickle
from scipy.spatial import distance_matrix
import codecs
import csv
import sklearn
from tqdm import tqdm
from sklearn import metrics
from sklearn.cluster import SpectralClustering
from sklearn.metrics import silhouette_score
from sklearn.cluster import KMeans
from sklearn_extr... | [
"pickle.dump",
"numpy.save",
"csv.writer",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"codecs.open",
"matplotlib.pyplot.scatter",
"sklearn.cluster.KMeans",
"scipy.spatial.distance_matrix",
"sklearn.metrics.silhouette_score",
"pickle.load",
"numpy.array",
"numpy.linalg.norm",
"numpy... | [((2566, 2589), 'scipy.spatial.distance_matrix', 'distance_matrix', (['nX', 'nX'], {}), '(nX, nX)\n', (2581, 2589), False, 'from scipy.spatial import distance_matrix\n'), ((3949, 3971), 'numpy.save', 'save', (['"""Dmat.npy"""', 'Dmat'], {}), "('Dmat.npy', Dmat)\n", (3953, 3971), False, 'from numpy import save\n'), ((28... |
from random import sample
import numpy as np
import nnfs
class Loss:
# Calculates the data and regularization losses
# given model output and ground truth values
def remember_trainable_layers(self, trainable_layers):
self.trainable_layers = trainable_layers
def regularization_loss(self, laye... | [
"numpy.sum",
"numpy.log",
"numpy.abs",
"numpy.clip",
"numpy.mean",
"numpy.sign",
"numpy.eye"
] | [((1213, 1235), 'numpy.mean', 'np.mean', (['sample_losses'], {}), '(sample_losses)\n', (1220, 1235), True, 'import numpy as np\n'), ((1270, 1291), 'numpy.sum', 'np.sum', (['sample_losses'], {}), '(sample_losses)\n', (1276, 1291), True, 'import numpy as np\n'), ((2170, 2203), 'numpy.clip', 'np.clip', (['y_pred', '(1e-07... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Functions for reading in a scan and generating a multislice plot for
sticking in reports
"""
import subprocess
import os
import itertools
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import nibabel as nib
from scipy import ndimage
from helpe... | [
"numpy.nanpercentile",
"numpy.isnan",
"matplotlib.pyplot.style.use",
"numpy.isclose",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"matplotlib.rcParams.update",
"matplotlib.pyplot.rcParams.update",
"helpers.get_terminal",
"itertools.product",
"matplotlib.pyplot.subplots",
... | [((614, 672), 'subprocess.run', 'subprocess.run', (['conversion_command'], {'check': '(True)', 'shell': '(True)'}), '(conversion_command, check=True, shell=True)\n', (628, 672), False, 'import subprocess\n'), ((689, 740), 'os.path.join', 'os.path.join', (['out_folder', 'f"""{original_stem}.nii.gz"""'], {}), "(out_folde... |
# Copyright 2020 The T5 Authors.
#
# 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... | [
"transformers.T5Tokenizer.from_pretrained",
"numpy.round"
] | [((1357, 1392), 'numpy.round', 'np.round', (['(label * 5 / 5)'], {'decimals': '(1)'}), '(label * 5 / 5, decimals=1)\n', (1365, 1392), True, 'import numpy as np\n'), ((1653, 1691), 'transformers.T5Tokenizer.from_pretrained', 'T5Tokenizer.from_pretrained', (['"""t5-base"""'], {}), "('t5-base')\n", (1680, 1691), False, 'f... |
#!/usr/bin/python3
import numpy
import pyopencl as cl
from .simple_gene import SimpleGene
class SimpleChromosome:
# SimpleChromosome - a chromosome contains a list of Genes.
# __genes - a list of Genes
# __name - name of the chromosome
# __improving_func - a function name in kernel to gurantee a better... | [
"pyopencl.enqueue_copy",
"pyopencl.enqueue_read_buffer",
"numpy.float32",
"numpy.zeros",
"pyopencl.Buffer",
"numpy.int32"
] | [((3556, 3602), 'numpy.zeros', 'numpy.zeros', (['total_dna_size'], {'dtype': 'numpy.int32'}), '(total_dna_size, dtype=numpy.int32)\n', (3567, 3602), False, 'import numpy\n'), ((3620, 3664), 'numpy.zeros', 'numpy.zeros', (['population'], {'dtype': 'numpy.float32'}), '(population, dtype=numpy.float32)\n', (3631, 3664), F... |
# tests for the config reader module
import os
from attr import validate
import pytest
import pandas as pd
from numpy.testing import assert_almost_equal
from jsonschema.exceptions import ValidationError
from tardis.io import config_reader
from tardis.io.config_reader import Configuration
def data_path(filename):
... | [
"pandas.read_hdf",
"numpy.testing.assert_almost_equal",
"os.path.dirname",
"tardis.io.config_reader.Configuration.from_config_dict",
"tardis.io.config_reader.parse_convergence_section",
"pytest.raises",
"os.path.join"
] | [((332, 357), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (347, 357), False, 'import os\n'), ((800, 865), 'tardis.io.config_reader.parse_convergence_section', 'config_reader.parse_convergence_section', (['test_convergence_section'], {}), '(test_convergence_section)\n', (839, 865), False, '... |
import argparse
import numpy as np
import matplotlib, warnings
import torch
from Utils.Utils import str2bool
matplotlib.rcParams["figure.figsize"] = [10, 10]
Tensor = torch.Tensor
FloatTensor = torch.FloatTensor
torch.set_printoptions(precision=4, sci_mode=False)
np.set_printoptions(precision=4, suppress=True)
from... | [
"numpy.set_printoptions",
"argparse.ArgumentParser",
"torch.cuda.device_count",
"torch.set_printoptions",
"torch.cuda.is_available"
] | [((215, 266), 'torch.set_printoptions', 'torch.set_printoptions', ([], {'precision': '(4)', 'sci_mode': '(False)'}), '(precision=4, sci_mode=False)\n', (237, 266), False, 'import torch\n'), ((267, 314), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(4)', 'suppress': '(True)'}), '(precision=4, sup... |
import multiprocessing as mp
from itertools import repeat
import numpy as np
import scipy.stats as st
def map_parallel(function, iter_data, invariant_data=None, run_parallel=True):
if invariant_data is not None:
inputs = zip(repeat(invariant_data), iter_data)
else:
inputs = iter_data
if ru... | [
"numpy.mean",
"numpy.array",
"scipy.stats.sem",
"multiprocessing.Pool",
"itertools.repeat"
] | [((1485, 1502), 'numpy.array', 'np.array', (['results'], {}), '(results)\n', (1493, 1502), True, 'import numpy as np\n'), ((1515, 1542), 'numpy.mean', 'np.mean', (['results'], {'axis': 'axis'}), '(results, axis=axis)\n', (1522, 1542), True, 'import numpy as np\n'), ((347, 356), 'multiprocessing.Pool', 'mp.Pool', ([], {... |
import open3d
import os
import numpy as np
from util.point_cloud_util import load_labels, write_labels
from dataset.semantic_dataset import all_file_prefixes
def down_sample(
dense_pcd_path, dense_label_path, sparse_pcd_path, sparse_label_path, processed_pcd_path, processed_label_path, voxel_size
):
# Skip if... | [
"os.makedirs",
"open3d.read_point_cloud",
"numpy.asarray",
"os.path.realpath",
"numpy.bincount",
"util.point_cloud_util.load_labels",
"util.point_cloud_util.write_labels",
"os.path.isfile",
"numpy.array",
"open3d.voxel_down_sample_and_trace",
"open3d.Vector3dVector",
"numpy.savez",
"os.path.... | [((596, 635), 'open3d.read_point_cloud', 'open3d.read_point_cloud', (['dense_pcd_path'], {}), '(dense_pcd_path)\n', (619, 635), False, 'import open3d\n'), ((2063, 2153), 'open3d.voxel_down_sample_and_trace', 'open3d.voxel_down_sample_and_trace', (['dense_pcd', 'voxel_size', 'min_bound', 'max_bound', '(False)'], {}), '(... |
"""
Read a mux2 file.
"""
from __future__ import absolute_import
from builtins import range
from anuga.utilities.numerical_tools import ensure_numeric
import numpy as num
################################################################################
# READ MUX2 FILES line of points
################... | [
"anuga.utilities.numerical_tools.ensure_numeric",
"numpy.zeros",
"numpy.ones",
"numpy.arange",
"numpy.compress",
"builtins.range"
] | [((3561, 3606), 'numpy.zeros', 'num.zeros', (['number_of_selected_stations', 'float'], {}), '(number_of_selected_stations, float)\n', (3570, 3606), True, 'import numpy as num\n'), ((3624, 3669), 'numpy.zeros', 'num.zeros', (['number_of_selected_stations', 'float'], {}), '(number_of_selected_stations, float)\n', (3633, ... |
import numpy as np
from eda.optimizer.eda_base import EDABase
from eda.optimizer.util import SubSet, Cache
class ECGA(EDABase):
"""
A class of extended compact genetic algorithm (ECGA).
"""
def __init__(self, categories, replacement,
selection=None, lam=500, theta_init=None):
... | [
"eda.optimizer.util.SubSet",
"numpy.sum",
"numpy.argmax",
"numpy.zeros",
"numpy.max",
"numpy.random.rand",
"eda.optimizer.util.Cache"
] | [((1049, 1069), 'numpy.argmax', 'np.argmax', (['x'], {'axis': '(2)'}), '(x, axis=2)\n', (1058, 1069), True, 'import numpy as np\n'), ((3037, 3050), 'eda.optimizer.util.Cache', 'Cache', (['self.d'], {}), '(self.d)\n', (3042, 3050), False, 'from eda.optimizer.util import SubSet, Cache\n'), ((4225, 4258), 'numpy.sum', 'np... |
import ray
import auth
import util
import solver
import time
import threading
import collections
import sutil
from queue import PriorityQueue, Queue
import traceback
import tempfile
import os
import uuid
import random
import numpy as np
import tensorflow as tf
from tftd import TFTD, tftd_to_example, tfd_to_tftd
from su... | [
"argparse.ArgumentParser",
"random.shuffle",
"util.gd_tfr_bcname",
"solver.Options",
"numpy.shape",
"util._connect",
"os.path.join",
"ray.remote",
"tempfile.TemporaryDirectory",
"auth.store_key",
"solver.Context",
"sutil.tfd_to_py",
"traceback.format_exc",
"tensorflow.io.TFRecordOptions",
... | [((445, 534), 'collections.namedtuple', 'collections.namedtuple', (['"""TaskID"""', "['problem_id', 'node_id', 'node_depth', 'is_train']"], {}), "('TaskID', ['problem_id', 'node_id', 'node_depth',\n 'is_train'])\n", (467, 534), False, 'import collections\n'), ((548, 594), 'collections.namedtuple', 'collections.named... |
import numpy as np
import plotly.express as px
from datetime import datetime
from cxotime import CxoTime
time_axis_format = [
# dict(dtickrange=[None, 600000], value="%H:%M:%S.%L\n"),
dict(dtickrange=[None, 60000000], value="%H:%M:%S\n%Y:%j"),
dict(dtickrange=[60000000, 315360000], value="%Y:%j"... | [
"numpy.median",
"cxotime.CxoTime",
"datetime.datetime.strptime",
"numpy.linspace",
"numpy.round"
] | [((8880, 8895), 'cxotime.CxoTime', 'CxoTime', (['tstart'], {}), '(tstart)\n', (8887, 8895), False, 'from cxotime import CxoTime\n'), ((8913, 8927), 'cxotime.CxoTime', 'CxoTime', (['tstop'], {}), '(tstop)\n', (8920, 8927), False, 'from cxotime import CxoTime\n'), ((1510, 1551), 'datetime.datetime.strptime', 'datetime.st... |
import numpy as np
import pytest
from scipy.stats import spearmanr, rankdata
from shenshang.simulate import simulate_correlation, correlate_xy
@pytest.mark.parametrize(
'strength, x, y, exp',
[(1,
np.array([5, 8, 2, 4, 3, 0, 1, 6, 7, 9]),
np.array([9, 1, 4, 5, 2, 3, 6, 8, 0, 7]),
np.array([... | [
"shenshang.simulate.correlate_xy",
"numpy.testing.assert_array_equal",
"scipy.stats.rankdata",
"numpy.array",
"shenshang.simulate.simulate_correlation"
] | [((1355, 1382), 'scipy.stats.rankdata', 'rankdata', (['x[pos]', '"""ordinal"""'], {}), "(x[pos], 'ordinal')\n", (1363, 1382), False, 'from scipy.stats import spearmanr, rankdata\n'), ((1505, 1542), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['sx', 'sy'], {}), '(sx, sy)\n', (1534, 1542), True,... |
"""
Module for k-Lines extraction and k-Label manipulation
Recall that bands contains NO information of the k-points.
So we must provide that ourselves, and reading the dftb_pin.hsd (the parsed
input) seems the best way to do so. We also need to figure out what to do
with equivalent points, or points where a new pat... | [
"skpar.dftbutils.lattice.getSymPtLabel",
"numpy.zeros",
"logging.getLogger",
"numpy.array",
"numpy.linspace",
"numpy.atleast_1d",
"os.path.join",
"numpy.concatenate"
] | [((673, 700), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (690, 700), False, 'import logging\n'), ((6063, 6081), 'numpy.concatenate', 'np.concatenate', (['xx'], {}), '(xx)\n', (6077, 6081), True, 'import numpy as np\n'), ((4804, 4822), 'numpy.atleast_1d', 'np.atleast_1d', (['pos'], {})... |
import os
os.environ["CUDA_DEVICES_ORDER"]= "PCI_BUS_IS"
os.environ["CUDA_VISIBLE_DEVICES"]= "1"
class pde_wan():
def __init__(self, dim, beta, N_int, N_bd):
import numpy as np
global np
#
import time
global time
#
import tensorflow as tf
global ... | [
"tensorflow.get_collection",
"tensorflow.reset_default_graph",
"tensorflow.reshape",
"tensorflow.zeros_like",
"tensorflow.multiply",
"numpy.sin",
"tensorflow.split",
"numpy.meshgrid",
"tensorflow.abs",
"numpy.power",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"numpy.reshape",
"... | [((1264, 1306), 'numpy.random.uniform', 'np.random.uniform', (['low', 'up', '[dm_size, dim]'], {}), '(low, up, [dm_size, dim])\n', (1281, 1306), True, 'import numpy as np\n'), ((1742, 1775), 'numpy.concatenate', 'np.concatenate', (['x_bd_list'], {'axis': '(0)'}), '(x_bd_list, axis=0)\n', (1756, 1775), True, 'import num... |
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import os
import argparse
import random
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from sklearn.preprocessing import StandardScaler
from models import ConvDiscriminator, ConvGenerator, LSTMDiscrim... | [
"utils.pre_processing",
"utils.prepare_data",
"numpy.random.seed",
"sklearn.preprocessing.StandardScaler",
"argparse.ArgumentParser",
"utils.get_samples",
"pandas.read_csv",
"torch.randn",
"utils.get_lr_scheduler",
"utils.make_csv",
"torch.no_grad",
"models.ConvDiscriminator",
"torch.nn.MSEL... | [((171, 204), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (194, 204), False, 'import warnings\n'), ((847, 869), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (858, 869), False, 'import random\n'), ((874, 899), 'numpy.random.seed', 'np.random.seed',... |
import sys
import numpy as np
import argparse
import json
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tempfile
import shutil
import logging
import subprocess
import tensorflow as tf
import matplotlib.pyplot as plt
from presearch_trrosetta.architecture.trRosetta import trRosetta
from prese... | [
"numpy.load",
"argparse.ArgumentParser",
"numpy.argmax",
"numpy.ones",
"presearch_trrosetta.utils.config.DistanceConfig.from_json_file",
"os.path.isfile",
"matplotlib.pyplot.imsave",
"shutil.copy",
"numpy.pad",
"tempfile.TemporaryDirectory",
"os.path.exists",
"numpy.loadtxt",
"tqdm.tqdm",
... | [((899, 918), 'presearch_trrosetta.architecture.trRosetta.trRosetta', 'trRosetta', ([], {}), '(**kwargs)\n', (908, 918), False, 'from presearch_trrosetta.architecture.trRosetta import trRosetta\n'), ((2388, 2409), 'numpy.array', 'np.array', (['result_list'], {}), '(result_list)\n', (2396, 2409), True, 'import numpy as ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 28 10:01:15 2022
@author: awatson
"""
from skimage import io
from itertools import product
from matplotlib import pyplot as plt
import numpy as np
import os
import math
import json
import math
import tifffile
import imagecodecs
import zarr
import dask
from dask.delayed i... | [
"json.dump",
"math.ceil",
"math.prod",
"tifffile.imwrite",
"numpy.zeros",
"dask.compute",
"os.path.split",
"dask.delayed.delayed"
] | [((471, 519), 'numpy.zeros', 'np.zeros', (['(2, 10, 30000, 30000)'], {'dtype': 'np.uint16'}), '((2, 10, 30000, 30000), dtype=np.uint16)\n', (479, 519), True, 'import numpy as np\n'), ((4046, 4067), 'dask.compute', 'dask.compute', (['toWrite'], {}), '(toWrite)\n', (4058, 4067), False, 'import dask\n'), ((4499, 4657), 't... |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import time
from scipy.stats import norm, mode
import os
import rospy
class TLClassifier(object):
def __init__(self):
GRAPH_FILE = 'frozen_inference_graph.pb'
model_path = os.path.dirname(os.path.realpath... | [
"scipy.stats.mode",
"os.path.realpath",
"numpy.asarray",
"tensorflow.Session",
"time.time",
"rospy.loginfo",
"tensorflow.gfile.GFile",
"tensorflow.Graph",
"numpy.squeeze",
"tensorflow.import_graph_def",
"tensorflow.GraphDef",
"os.path.join"
] | [((354, 390), 'os.path.join', 'os.path.join', (['model_path', 'GRAPH_FILE'], {}), '(model_path, GRAPH_FILE)\n', (366, 390), False, 'import os\n'), ((525, 554), 'rospy.loginfo', 'rospy.loginfo', (['"""model loaded"""'], {}), "('model loaded')\n", (538, 554), False, 'import rospy\n'), ((1933, 1943), 'tensorflow.Graph', '... |
import os
import shutil
import numpy as np
old_model_path = '/home/guoran/git-repo/yolo_test_1218/yolov3_model'
new_model_path = "yolov3_model_python/"
os.mkdir(new_model_path)
layers = os.listdir(old_model_path)
print(layers)
for layer in layers:
models=os.listdir(os.path.join(old_model_path, layer))
for model... | [
"os.mkdir",
"numpy.fromfile",
"shutil.copyfile",
"os.path.join",
"os.listdir"
] | [((152, 176), 'os.mkdir', 'os.mkdir', (['new_model_path'], {}), '(new_model_path)\n', (160, 176), False, 'import os\n'), ((186, 212), 'os.listdir', 'os.listdir', (['old_model_path'], {}), '(old_model_path)\n', (196, 212), False, 'import os\n'), ((270, 305), 'os.path.join', 'os.path.join', (['old_model_path', 'layer'], ... |
# Copyright 2017 Google 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 agreed to in writing,... | [
"tensorflow.gfile.MakeDirs",
"tensorflow.train.SessionRunArgs",
"tensorflow.logging.info",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"seq2seq.tasks.inference_task.unbatch_dict",
"numpy.arange",
"numpy.savez",
"os.path.join",
"seq2seq.tasks.decode_text._ge... | [((1032, 1072), 'seq2seq.tasks.decode_text._get_prediction_length', '_get_prediction_length', (['predictions_dict'], {}), '(predictions_dict)\n', (1054, 1072), False, 'from seq2seq.tasks.decode_text import _get_prediction_length\n'), ((1488, 1528), 'seq2seq.tasks.decode_text._get_prediction_length', '_get_prediction_le... |
import numpy as np
def minmax_scale(X:np.ndarray, axis=0, feature_range=(0,1)):
X_out = np.zeros_like(X)
X_min = np.min(X, axis=axis)
X_max = np.max(X, axis=axis)
X_out = (X - X_min) / (X_max - X_min)
X_out = X_out * (feature_range[1]-feature_range[0]) + feature_range[0]
... | [
"numpy.min",
"numpy.zeros_like",
"numpy.max"
] | [((93, 109), 'numpy.zeros_like', 'np.zeros_like', (['X'], {}), '(X)\n', (106, 109), True, 'import numpy as np\n'), ((122, 142), 'numpy.min', 'np.min', (['X'], {'axis': 'axis'}), '(X, axis=axis)\n', (128, 142), True, 'import numpy as np\n'), ((155, 175), 'numpy.max', 'np.max', (['X'], {'axis': 'axis'}), '(X, axis=axis)\... |
from numpy import multiply
from scipy.optimize import linprog
__author__ = ["<NAME>", "<NAME>"]
__copyright__ = "Copyright 2017"
__credits__ = []
__version__ = "1.0"
__status__ = "Development"
def header():
print('\n Agroplex - © 2017\n\n'
' <NAME> e <NAME>\n'
' Faculdade de Tecn... | [
"scipy.optimize.linprog",
"numpy.multiply"
] | [((1023, 1043), 'numpy.multiply', 'multiply', (['self.x', '(-1)'], {}), '(self.x, -1)\n', (1031, 1043), False, 'from numpy import multiply\n'), ((1117, 1176), 'scipy.optimize.linprog', 'linprog', (['f', 'r', 'b'], {'bounds': 'xi_bounds', 'options': "{'disp': False}"}), "(f, r, b, bounds=xi_bounds, options={'disp': Fals... |
import pandas as pd
import numpy as np
import sys
import argparse
import time
from scipy.special import gamma
import os
import pickle
import torch
import NMF_functions
from ARD_NMF import ARD_NMF
import pyarrow.feather as feather
from ARD_NMF import run_method_engine
import torch.nn as nn
import torch.multiprocessing ... | [
"pandas.DataFrame",
"numpy.sum",
"argparse.ArgumentParser",
"ARD_NMF.run_method_engine",
"os.makedirs",
"ARD_NMF.ARD_NMF",
"pandas.read_csv",
"pyarrow.feather.read_dataframe",
"os.path.exists",
"torch.multiprocessing.set_start_method",
"pandas.read_parquet",
"sys.exit"
] | [((1716, 1735), 'numpy.sum', 'np.sum', (['nonzero_idx'], {}), '(nonzero_idx)\n', (1722, 1735), True, 'import numpy as np\n'), ((1817, 1841), 'numpy.sum', 'np.sum', (['W_active'], {'axis': '(0)'}), '(W_active, axis=0)\n', (1823, 1841), True, 'import numpy as np\n'), ((2028, 2094), 'pandas.DataFrame', 'pd.DataFrame', ([]... |
"""
이미지 폴더의 파일을 분석하여 예측 레이블(labels_pred)을 생성하는 모듈
"""
import pandas as pd
import math
import matplotlib.pyplot as plt
import numpy as np
import os
from somber import Som
from evaluation import *
from config import *
from numpy import (array, unravel_index, nditer, linalg, random, subtract,
... | [
"pylab.show",
"math.sqrt",
"pylab.pcolor",
"numpy.nditer",
"sklearn.preprocessing.MinMaxScaler",
"numpy.zeros",
"pylab.colorbar",
"pylab.bone",
"somber.Som",
"numpy.dot",
"os.path.join"
] | [((631, 668), 'numpy.zeros', 'zeros', (['(self.shape[0], self.shape[1])'], {}), '((self.shape[0], self.shape[1]))\n', (636, 668), False, 'from numpy import array, unravel_index, nditer, linalg, random, subtract, power, exp, pi, zeros, arange, outer, meshgrid, dot, logical_and, mean, std, cov, argsort, linspace, transpo... |
# Create source and receiver grid
import numpy as np
import h5py
import matplotlib.pyplot as plt
# Model domain
x_max = 10000 # lateral extension in x [m]
y_max = 10000 # lateral extension in y [m]
###################################################################################################
# Source grid
... | [
"h5py.File",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.random.seed",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.ones",
"numpy.unravel_index",
"numpy.cumsum",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.arange",
"numpy.random.rand",
"numpy.round"
] | [((563, 615), 'numpy.arange', 'np.arange', ([], {'start': 'sx_min', 'stop': '(sx_max + dsx)', 'step': 'dsx'}), '(start=sx_min, stop=sx_max + dsx, step=dsx)\n', (572, 615), True, 'import numpy as np\n'), ((629, 681), 'numpy.arange', 'np.arange', ([], {'start': 'sy_min', 'stop': '(sy_max + dsy)', 'step': 'dsy'}), '(start... |
#!/usr/bin/env python3
import os.path
import os
import sys
import numpy as np
import neurom as nm
from neurom.core.types import NeuriteType
import json
from pprint import pprint
# Uses:
# https://github.com/BlueBrain/NeuroM
#
# some doc here:
# https://github.com/BlueBrain/NeuroM/blob/04f48747785265aa7a4f7b0750c1447c... | [
"numpy.zeros",
"neurom.load_neuron",
"json.dumps",
"numpy.shape",
"os.path.splitext",
"numpy.ascontiguousarray",
"json.JSONEncoder.default",
"numpy.concatenate"
] | [((1404, 1429), 'neurom.load_neuron', 'nm.load_neuron', (['file_name'], {}), '(file_name)\n', (1418, 1429), True, 'import neurom as nm\n'), ((4679, 4736), 'json.dumps', 'json.dumps', (['morpho_to_export'], {'ensure_ascii': '(True)', 'indent': '(2)'}), '(morpho_to_export, ensure_ascii=True, indent=2)\n', (4689, 4736), F... |
import pandas as pd
import numpy as np
import sklearn.metrics
from .utils import map_binary
import warnings
warnings.simplefilter("ignore")
def eval_report(means, mapping, mapping_r):
'''Compute an array of model performance metrics given mean classifer scores across all possible prediction classes
Compute... | [
"pandas.Series",
"pandas.concat",
"warnings.simplefilter",
"numpy.linspace"
] | [((111, 142), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (132, 142), False, 'import warnings\n'), ((2662, 2716), 'pandas.concat', 'pd.concat', (['results'], {'names': "['type of metric', 'metric']"}), "(results, names=['type of metric', 'metric'])\n", (2671, 2716), True, '... |
import copy
import unittest
from unittest import TestCase
import numpy as np
import numpy.testing as nptest
import pandas as pd
import pandas.util.testing as pdtest
import raredecay.settings
out = raredecay.settings.initialize(
run_name="test reweighting", no_interactive_plots=True, n_cpu=-2
)
from raredecay.to... | [
"unittest.main",
"pandas.DataFrame",
"copy.deepcopy",
"numpy.average",
"raredecay.tools.data_storage.HEPDataStorage",
"numpy.testing.assert_almost_equal",
"rep.data.storage.LabeledDataStorage",
"numpy.array",
"pandas.util.testing.assert_almost_equal",
"inspect.currentframe",
"pandas.concat",
"... | [((14144, 14159), 'unittest.main', 'unittest.main', ([], {}), '()\n', (14157, 14159), False, 'import unittest\n'), ((595, 803), 'raredecay.tools.data_storage.HEPDataStorage', 'HEPDataStorage', (['self.data_for_hepds'], {'target': 'self.target_for_hepds', 'sample_weights': 'self.weights_for_hepds', 'index': 'self.truth_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import requests
import numpy as np
import json
import time
from multiprocessing import Pool
urlBase = 'https://login.commodity.llc'
# 172.16.58.3
# urlBase = 'http://172.16.17.3236:5000'
# urlBase = 'http://localhost:5000'
api = '/api/v1/accounts'
# api =... | [
"json.loads",
"time.time",
"numpy.random.randint",
"multiprocessing.Pool",
"requests.post"
] | [((787, 837), 'requests.post', 'requests.post', (['url'], {'json': 'jTest', 'timeout': '(300, 600)'}), '(url, json=jTest, timeout=(300, 600))\n', (800, 837), False, 'import requests\n'), ((867, 883), 'json.loads', 'json.loads', (['text'], {}), '(text)\n', (877, 883), False, 'import json\n'), ((1983, 1994), 'time.time',... |
"""
KKZ 1994 algorithm
See: A new initialization technique for generalized Lloyd iteration
https://ieeexplore.ieee.org/abstract/document/329844/
"""
import numpy as np
from initialisations.base import Initialisation
from kmeans import distance_table
class KKZ(Initialisation):
"""KKZ 1994 initialisation algorit... | [
"numpy.argmax",
"kmeans.distance_table",
"numpy.append",
"numpy.min",
"numpy.array",
"numpy.linalg.norm"
] | [((469, 503), 'numpy.linalg.norm', 'np.linalg.norm', (['self._data'], {'axis': '(1)'}), '(self._data, axis=1)\n', (483, 503), True, 'import numpy as np\n'), ((569, 586), 'numpy.array', 'np.array', (['[first]'], {}), '([first])\n', (577, 586), True, 'import numpy as np\n'), ((532, 548), 'numpy.argmax', 'np.argmax', (['n... |
from datetime import datetime
import numpy as np
import pytz
def pivot_time(input_datetime=None):
"""
"pivot time" is defined as the nearest floor t00z for any given datetime.
If this function is called without arguments, it will return the pivot time
for the current datetime in UTC.
"""
inpu... | [
"datetime.datetime.utcnow",
"numpy.floor",
"pytz.timezone",
"datetime.datetime"
] | [((488, 559), 'datetime.datetime', 'datetime', (['input_datetime.year', 'input_datetime.month', 'input_datetime.day'], {}), '(input_datetime.year, input_datetime.month, input_datetime.day)\n', (496, 559), False, 'from datetime import datetime\n'), ((843, 933), 'datetime.datetime', 'datetime', (['input_datetime.year', '... |
import hugectr
from mpi4py import MPI
solver = hugectr.CreateSolver(
max_eval_batches = 1,
batchsize_eval = 1024,
batchsize = 1024,
lr = 0.01,
end_lr = 0.0001,
warmup_steps = 8000,
decay_start = 48000,
decay_steps = 24000,
vvgpu = [[0]],
repeat_dataset = True,
i64_input_key ... | [
"hugectr.CreateSolver",
"hugectr.inference.CreateInferenceSession",
"hugectr.DenseLayer",
"hugectr.SparseEmbedding",
"hugectr.inference.InferenceParams",
"hugectr.CreateOptimizer",
"hugectr.DataReaderSparseParam",
"hugectr.Model",
"numpy.mean",
"numpy.loadtxt",
"hugectr.DataReaderParams"
] | [((48, 269), 'hugectr.CreateSolver', 'hugectr.CreateSolver', ([], {'max_eval_batches': '(1)', 'batchsize_eval': '(1024)', 'batchsize': '(1024)', 'lr': '(0.01)', 'end_lr': '(0.0001)', 'warmup_steps': '(8000)', 'decay_start': '(48000)', 'decay_steps': '(24000)', 'vvgpu': '[[0]]', 'repeat_dataset': '(True)', 'i64_input_ke... |
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import AutoMinorLocator
import numpy as np
# =================================================================================
def ecg_plot(ecg):
fs = 128
Time=np.linspace(0, len(ecg)/fs, num=len(ecg))
f... | [
"matplotlib.pyplot.show",
"matplotlib.ticker.AutoMinorLocator",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlabel"
] | [((329, 358), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(16, 5)'}), '(figsize=(16, 5))\n', (341, 358), True, 'import matplotlib.pyplot as plt\n'), ((450, 481), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (460, 481), True, 'import matpl... |
import sys
import argparse
from yolo import YOLO, detect_video
from PIL import Image, ImageDraw, ImageFont
import glob
import os
from convertannotation import convert_annotation
import cv2
from datetime import datetime
import numpy as np
def bb_intersection_over_union(boxA, boxB):
xA = max(boxA[0], boxB[0])
y... | [
"cv2.VideoWriter_fourcc",
"numpy.floor",
"PIL.Image.open",
"numpy.array",
"glob.glob",
"cv2.VideoWriter",
"PIL.ImageDraw.Draw",
"datetime.datetime.now",
"yolo.YOLO"
] | [((1972, 1993), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image'], {}), '(image)\n', (1986, 1993), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((3814, 3820), 'yolo.YOLO', 'YOLO', ([], {}), '()\n', (3818, 3820), False, 'from yolo import YOLO, detect_video\n'), ((3838, 3868), 'glob.glob', 'glob.glob', (['""... |
"""
Gripper for Kinova's Jaco robot arm (has three fingers).
"""
import numpy as np
from robosuite.models.grippers.gripper_model import GripperModel
from robosuite.utils.mjcf_utils import xml_path_completion
class JacoThreeFingerGripperBase(GripperModel):
"""
Gripper for Kinova's Jaco robot arm (has three fi... | [
"numpy.array",
"numpy.sign",
"robosuite.utils.mjcf_utils.xml_path_completion"
] | [((693, 727), 'numpy.array', 'np.array', (['[0.5, 0, 0.5, 0, 0.5, 0]'], {}), '([0.5, 0, 0.5, 0, 0.5, 0])\n', (701, 727), True, 'import numpy as np\n'), ((506, 567), 'robosuite.utils.mjcf_utils.xml_path_completion', 'xml_path_completion', (['"""grippers/jaco_three_finger_gripper.xml"""'], {}), "('grippers/jaco_three_fin... |
import numpy as np
from string import Template
from collections import deque
from xml.dom.minidom import parseString as parse_xml
from .. import entities as entities_mod
from ..arc import arc_center
from ...resources import get_resource
from ...constants import log
from ...constants import res_path as res
from ... ... | [
"numpy.cross",
"numpy.array",
"numpy.arange",
"svg.path.parse_path",
"collections.deque"
] | [((2848, 2855), 'collections.deque', 'deque', ([], {}), '()\n', (2853, 2855), False, 'from collections import deque\n'), ((2871, 2878), 'collections.deque', 'deque', ([], {}), '()\n', (2876, 2878), False, 'from collections import deque\n'), ((1294, 1338), 'numpy.array', 'np.array', (['[[i.real, i.imag] for i in values]... |
#!/usr/bin/env python
import startup
import os
import numpy as np
import scipy.io
from util.point_cloud import point_cloud_distance
from util.simple_dataset import Dataset3D
from util.app_config import config as app_config
from util.tools import partition_range, to_np_object
from util.quaternion import quaternion_r... | [
"run.ShapeRecords.ShapeRecords",
"util.euler.ypr_from_campos",
"numpy.isnan",
"os.path.isfile",
"pickle.load",
"numpy.mean",
"os.path.join",
"util.point_cloud.point_cloud_distance",
"torch.utils.data.DataLoader",
"numpy.power",
"util.system.setup_environment",
"numpy.ceil",
"numpy.square",
... | [((755, 801), 'util.tools.partition_range', 'partition_range', (['source_np.shape[0]', 'num_parts'], {}), '(source_np.shape[0], num_parts)\n', (770, 801), False, 'from util.tools import partition_range, to_np_object\n'), ((820, 834), 'numpy.zeros', 'np.zeros', (['(0,)'], {}), '((0,))\n', (828, 834), True, 'import numpy... |
# --- Do not remove these libs ---
import numpy as np
# --------------------------------
import talib.abstract as ta
from pandas import DataFrame
import freqtrade.vendor.qtpylib.indicators as qtpylib
from freqtrade.strategy.interface import IStrategy
def bollinger_bands(stock_price, window_size, num_of_std):
roll... | [
"pandas.DataFrame",
"numpy.nan_to_num",
"talib.abstract.EMA",
"talib.abstract.RSI",
"talib.abstract.ADX",
"freqtrade.vendor.qtpylib.indicators.typical_price",
"talib.abstract.MACD"
] | [((1235, 1253), 'numpy.nan_to_num', 'np.nan_to_num', (['mid'], {}), '(mid)\n', (1248, 1253), True, 'import numpy as np\n'), ((1283, 1303), 'numpy.nan_to_num', 'np.nan_to_num', (['lower'], {}), '(lower)\n', (1296, 1303), True, 'import numpy as np\n'), ((1653, 1684), 'talib.abstract.RSI', 'ta.RSI', (['dataframe'], {'time... |
import math
import numpy as np
import torch
from torch import nn
class BufferList(nn.Module):
"""
Similar to nn.ParameterList, but for buffers
"""
def __init__(self, buffers=None):
super(BufferList, self).__init__()
if buffers is not None:
self.extend(buffers)
def ex... | [
"torch.randn",
"numpy.hstack",
"numpy.array",
"torch.arange",
"torch.from_numpy"
] | [((2043, 2080), 'numpy.array', 'np.array', (['[0, stride]'], {'dtype': 'np.float'}), '([0, stride], dtype=np.float)\n', (2051, 2080), True, 'import numpy as np\n'), ((2133, 2158), 'torch.from_numpy', 'torch.from_numpy', (['anchors'], {}), '(anchors)\n', (2149, 2158), False, 'import torch\n'), ((2549, 2592), 'numpy.hsta... |
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
def set_figure(size, subplots=(1,1), context='paper', style='darkgrid',font_scale = 1, l=0.2, w=0.1, h=0.1, b=0.1):
sb.set(context=context,style=style, font_scale=font_scale)
fig, ax = plt.subplots(subplots[0],subplots[1], figsize=size)
... | [
"numpy.abs",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.exp",
"matplotlib.pyplot.cm.ScalarMappable",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"seaborn.set",
"matplotlib.pyplot.get_cmap",
"matpl... | [((194, 253), 'seaborn.set', 'sb.set', ([], {'context': 'context', 'style': 'style', 'font_scale': 'font_scale'}), '(context=context, style=style, font_scale=font_scale)\n', (200, 253), True, 'import seaborn as sb\n'), ((267, 319), 'matplotlib.pyplot.subplots', 'plt.subplots', (['subplots[0]', 'subplots[1]'], {'figsize... |
import numpy as np
import stopit
import sys
from spider.featurization_base import FeaturizationTransformerPrimitiveBase
Inputs = list
Outputs = list
class AudioSlicer(FeaturizationTransformerPrimitiveBase[Inputs, Outputs]):
def __init__(
self,
sampling_rate=44100,
frame_length=3.0,
... | [
"stopit.ThreadingTimeout",
"numpy.array"
] | [((1671, 1703), 'stopit.ThreadingTimeout', 'stopit.ThreadingTimeout', (['timeout'], {}), '(timeout)\n', (1694, 1703), False, 'import stopit\n'), ((2862, 2877), 'numpy.array', 'np.array', (['clips'], {}), '(clips)\n', (2870, 2877), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 18:14:29 2016
@author: becker
"""
import numpy as np
import scipy.linalg as linalg
import scipy.sparse as sparse
from simfempy.fems import femsys, cr1
from simfempy.tools import barycentric, npext
#=================================================================#
cl... | [
"numpy.sum",
"numpy.einsum",
"simfempy.meshes.testmeshes.backwardfacingstep",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.tile",
"numpy.add.at",
"simfempy.tools.npext.positionin",
"numpy.zeros_like",
"simfempy.tools.barycentric.crbdryothers",
"simfempy.fems.cr1.CR1",
"si... | [((13520, 13556), 'simfempy.meshes.testmeshes.backwardfacingstep', 'testmeshes.backwardfacingstep', ([], {'h': '(0.2)'}), '(h=0.2)\n', (13549, 13556), False, 'from simfempy.meshes import testmeshes\n'), ((13660, 13687), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1367... |
# 2D Convolution (Image Filtering)
# coding: utf-8
import numpy as np
from cv2 import cv2
import matplotlib.pyplot as plt
img = cv2.imread(r'pictures\opencv.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
kernel = np.ones((5, 5), np.float32)/25
# ddepth = -1: The same with the original image
dst = cv2.filter2D(img, ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"cv2.cv2.filter2D",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"numpy.ones",
"cv2.cv2.imread",
"matplotlib.pyplot.xticks",
"cv2.cv2.cvtColor"
] | [((129, 163), 'cv2.cv2.imread', 'cv2.imread', (['"""pictures\\\\opencv.png"""'], {}), "('pictures\\\\opencv.png')\n", (139, 163), False, 'from cv2 import cv2\n'), ((170, 206), 'cv2.cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (182, 206), False, 'from cv2 import cv2\n'... |
'''
Unit test of the COTAT plus driver using same data as top-level
Fortran FRUIT unit tests
Created on Oct 19, 2016
@author: thomasriddick
'''
import unittest
import numpy as np
import os
import re
import textwrap
import subprocess
from subprocess import CalledProcessError
from Dynamic_HD_Scripts.base import field
... | [
"unittest.main",
"Dynamic_HD_Scripts.base.field.makeField",
"os.path.expanduser",
"os.mkdir",
"textwrap.dedent",
"os.stat",
"subprocess.check_output",
"unittest.skip",
"Dynamic_HD_Scripts.tools.cotat_plus_driver.run_cotat_plus",
"numpy.array",
"re.search",
"os.path.join"
] | [((629, 1432), 'numpy.array', 'np.array', (['[[-1, -1, -1, -1, 0, 4, 2, 2, 2, 2, 2, 2, 3, 2, 2], [-1, -1, -1, -1, -1, -1,\n 0, 4, 4, 4, 4, 1, 4, 4, 1], [-1, -1, -1, -1, -1, 9, 8, 8, 8, 1, 7, 7, 4,\n 4, 4], [-1, -1, -1, -1, -1, 0, 4, 4, 4, 6, 8, 5, 8, 4, 8], [-1, 0, 4, 4,\n 4, 5, 7, 1, 8, 4, 6, 7, 6, 5, 4], [-1... |
# Copyright (c) 2018 PaddlePaddle 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 app... | [
"unittest.main",
"numpy.random.random",
"numpy.zeros",
"numpy.array"
] | [((1641, 1686), 'numpy.zeros', 'np.zeros', (['(batch_size, channel, out_h, out_w)'], {}), '((batch_size, channel, out_h, out_w))\n', (1649, 1686), True, 'import numpy as np\n'), ((4489, 4504), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4502, 4504), False, 'import unittest\n'), ((3102, 3136), 'numpy.random.ran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.