code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" fasterutils.py: utility functions for the faster rcnn model """
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision
from torchvision.models.detection import FasterRCNN
from torchvisio... | [
"torchvision.models.detection.faster_rcnn.FastRCNNPredictor",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"torch.load",
"torchvision.models.detection.rpn.AnchorGenerator",
"transforms.RandomHorizontalFlip",
"numpy.hstack",
"torch.save",
"transform... | [((617, 642), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (640, 642), False, 'import torch\n'), ((1254, 1341), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': '(True)', 'pretrained_backbone': '(True)'}), '(pretrained=Tru... |
'''
save_training_data('data/my_training_data.npz', X, Y, XY_axes)
XY_axes="SCYX"
'''
import numpy as np
from tifffile import imsave,imread
from .image import *
from .filter import discard_slices
import mrcfile
class Tomogram:
def __init__(self, volume):
self.__volume = volume
def rotate_aroundZ(s... | [
"numpy.std",
"numpy.zeros",
"numpy.expand_dims",
"scipy.ndimage.interpolation.rotate",
"mrcfile.open",
"os.listdir",
"numpy.concatenate"
] | [((2043, 2121), 'numpy.zeros', 'np.zeros', (['[self._dataX.shape[0], nPatchesPerSlice, patchSideLen, patchSideLen]'], {}), '([self._dataX.shape[0], nPatchesPerSlice, patchSideLen, patchSideLen])\n', (2051, 2121), True, 'import numpy as np\n'), ((2144, 2222), 'numpy.zeros', 'np.zeros', (['[self._dataY.shape[0], nPatches... |
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import ToTensor
from torchvision.utils import make_grid
from torch.nn import init
import math
import numpy as np
import scipy.io as sio
from scipy.sparse.linalg import svds
from sklearn import cluster
from skl... | [
"numpy.maximum",
"numpy.abs",
"numpy.sum",
"sklearn.cluster.SpectralClustering",
"numpy.argsort",
"torch.nn.init.constant_",
"numpy.diag",
"numpy.sqrt",
"numpy.unique",
"torch.ones",
"torch.nn.MSELoss",
"torch.nn.init.kaiming_normal_",
"torch.utils.data.DataLoader",
"scipy.sparse.linalg.sv... | [((5576, 5589), 'numpy.unique', 'np.unique', (['L1'], {}), '(L1)\n', (5585, 5589), True, 'import numpy as np\n'), ((5629, 5642), 'numpy.unique', 'np.unique', (['L2'], {}), '(L2)\n', (5638, 5642), True, 'import numpy as np\n'), ((5683, 5711), 'numpy.maximum', 'np.maximum', (['nClass1', 'nClass2'], {}), '(nClass1, nClass... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import numpy as np
import common
def load_json(filename):
with open(filename, "r") as f:
return json.load(f)
def load_data(filename):
j = load_json(filename)
return j["nsamples"], np.array(j["mean"]), np.array(j["variance"])
# converge... | [
"json.load",
"numpy.array",
"numpy.log",
"common.plotLogLogData"
] | [((1882, 1976), 'common.plotLogLogData', 'common.plotLogLogData', (['[M, M]', '[meanL1Error, varL1Error]', '[ref_mean, ref_var]', 'myPlotDict'], {}), '([M, M], [meanL1Error, varL1Error], [ref_mean, ref_var\n ], myPlotDict)\n', (1903, 1976), False, 'import common\n'), ((170, 182), 'json.load', 'json.load', (['f'], {}... |
# -*- coding: utf-8 -*-
"""Testing GLSAR against STATA
Created on Wed May 30 09:25:24 2012
Author: <NAME>
"""
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_,
assert_approx_equal, assert_array_less)
from statsmodels.regression.linear_model import O... | [
"numpy.log",
"numpy.testing.assert_almost_equal",
"numpy.allclose",
"nose.runmodule",
"statsmodels.datasets.macrodata.load",
"statsmodels.regression.linear_model.GLSAR",
"statsmodels.tools.tools.add_constant"
] | [((2078, 2135), 'nose.runmodule', 'nose.runmodule', ([], {'argv': "[__file__, '-vvs', '-x']", 'exit': '(False)'}), "(argv=[__file__, '-vvs', '-x'], exit=False)\n", (2092, 2135), False, 'import nose\n'), ((538, 588), 'numpy.allclose', 'np.allclose', (['actual', 'desired'], {'rtol': 'rtol', 'atol': 'atol'}), '(actual, de... |
import numpy as np
import pandas as pd
import nltk
nltk.download('punkt') # one time execution
from nltk.tokenize import sent_tokenize
from sklearn.metrics.pairwise import cosine_similarity
import networkx as nx
import os
dirpath = os.getcwd()
slash = "\\" # use '/' for mac or linux
path = dirpath + sla... | [
"networkx.from_numpy_matrix",
"networkx.pagerank",
"os.getcwd",
"pandas.read_csv",
"numpy.asarray",
"numpy.zeros",
"nltk.tokenize.sent_tokenize",
"pandas.Series",
"nltk.corpus.stopwords.words",
"nltk.download"
] | [((56, 78), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (69, 78), False, 'import nltk\n'), ((245, 256), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (254, 256), False, 'import os\n'), ((353, 414), 'pandas.read_csv', 'pd.read_csv', (["(path + 'data' + slash + 'tennis_articles_v4.csv')"], {}), ... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from data_loader import get_image, get_map
from model import create_model
import utils
model = tf.keras.models.load_model(utils.model_path)
# model = create_model(False)
# model.summary()
#
# ckpt = tf.train.Checkpoint(model=model)
# ckpt_ma... | [
"numpy.average",
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"tensorflow.keras.models.Model",
"numpy.array",
"data_loader.get_map"
] | [((173, 217), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['utils.model_path'], {}), '(utils.model_path)\n', (199, 217), True, 'import tensorflow as tf\n'), ((709, 818), 'tensorflow.keras.models.Model', 'tf.keras.models.Model', ([], {'inputs': 'model.inputs', 'outputs': '[image_feature_layer.in... |
# ==============================================================================
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
"""Openvino Tensorflow fusedConv2D tests.
"""
from __future__ import absolute_i... | [
"numpy.random.rand",
"tensorflow.python.ops.nn_ops.conv2d",
"tensorflow.python.ops.array_ops.placeholder"
] | [((808, 841), 'numpy.random.rand', 'np.random.rand', (['*self.INPUT_SIZES'], {}), '(*self.INPUT_SIZES)\n', (822, 841), True, 'import numpy as np\n'), ((864, 898), 'numpy.random.rand', 'np.random.rand', (['*self.FILTER_SIZES'], {}), '(*self.FILTER_SIZES)\n', (878, 898), True, 'import numpy as np\n'), ((921, 953), 'numpy... |
import logging
import re
import shutil
from pathlib import Path
from random import choice
from string import ascii_letters
from tempfile import NamedTemporaryFile
from typing import List, Tuple, Union
import numpy as np
import rasterio
import rasterio.mask
import rasterio.vrt
import rasterio.warp
from affine import Af... | [
"pyproj.crs.CRS",
"ravenpy.utilities.io.get_bbox",
"tempfile.NamedTemporaryFile",
"rasterio.open",
"shutil.make_archive",
"numpy.ma.masked_values",
"numpy.asarray",
"random.choice",
"ravenpy.utilities.geoserver.get_raster_wcs",
"pathlib.Path",
"re.findall",
"affine.Affine",
"logging.getLogge... | [((459, 485), 'logging.getLogger', 'logging.getLogger', (['"""RAVEN"""'], {}), "('RAVEN')\n", (476, 485), False, 'import logging\n'), ((2432, 2453), 'ravenpy.utilities.io.get_bbox', 'get_bbox', (['vector_file'], {}), '(vector_file)\n', (2440, 2453), False, 'from ravenpy.utilities.io import get_bbox\n'), ((2499, 2562), ... |
#!/usr/bin/python
#
#The MIT CorrelX Correlator
#
#https://github.com/MITHaystack/CorrelX
#Contact: <EMAIL>
#Project leads: <NAME>, <NAME> Project developer: <NAME>
#
#Copyright 2017 MIT Haystack Observatory
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ... | [
"base64.b64decode",
"cxs.computation.pcal.lib_pcal.normalize_pcal",
"cxs.app.base.const_mapred.SF_SEP.join",
"cxs.computation.quantization.lib_quant.get_samples",
"numpy.conjugate",
"cxs.computation.fx.lib_fx_stack.multiply_accumulate",
"cxs.computation.fx.lib_fx_stack.compute_fx_for_all",
"numpy.appe... | [((2035, 2062), 'os.environ.get', 'os.environ.get', (['"""is_legacy"""'], {}), "('is_legacy')\n", (2049, 2062), False, 'import os\n'), ((17266, 17299), 'cxs.app.base.const_mapred.SF_SEP.join', 'SF_SEP.join', (['current_acc_str[3:7]'], {}), '(current_acc_str[3:7])\n', (17277, 17299), False, 'from cxs.app.base.const_mapr... |
import gym
from gym.spaces import Discrete
from gym.spaces import Box
import numpy as np
class DeepSeaTreasureEnv(gym.Env):
'''
This is an implementation of a standard Multiple Objective Optimization problem called
Deep Sea Treasure Hunt (Vamplew, et al, 2011).
In this environment there are... | [
"numpy.array",
"gym.spaces.Discrete",
"numpy.zeros",
"gym.spaces.Box"
] | [((874, 903), 'numpy.zeros', 'np.zeros', (['(10, 11)'], {'dtype': 'int'}), '((10, 11), dtype=int)\n', (882, 903), True, 'import numpy as np\n'), ((1746, 1757), 'gym.spaces.Discrete', 'Discrete', (['(4)'], {}), '(4)\n', (1754, 1757), False, 'from gym.spaces import Discrete\n'), ((1911, 1928), 'gym.spaces.Box', 'Box', ([... |
#!/usr/bin/env python
# pylint: disable=wrong-import-position
import os
import time
import traceback
from argparse import ArgumentParser
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from scipy.interpolate import interp1d
from tqdm import tqdm
fro... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"tensorflow.logging.info",
"utils.configure_logging",
"numpy.mean",
"numpy.random.normal",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"numpy.std",
"matplotlib.pyplot.close",
"os.path.exists",
"utils.load_checkpoint",
"traceback.format_ex... | [((158, 179), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (172, 179), False, 'import matplotlib\n'), ((435, 451), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (449, 451), False, 'from argparse import ArgumentParser\n'), ((2221, 2248), 'tensorflow.enable_eager_execution', 'tf.... |
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"cirq.Points",
"cirq.google.EngineProgram",
"cirq.ParamResolver",
"cirq.google.engine.client.quantum_v1alpha1.types.QuantumResult",
"cirq.google.api.v1.program_pb2.RunContext",
"cirq.google.engine.client.quantum_v1alpha1.types.QuantumProgram",
"unittest.mock.patch.object",
"pytest.raises",
"cirq.goo... | [((5802, 5873), 'unittest.mock.patch.object', 'mock.patch.object', (['quantum', '"""QuantumEngineServiceClient"""'], {'autospec': '(True)'}), "(quantum, 'QuantumEngineServiceClient', autospec=True)\n", (5819, 5873), False, 'from unittest import mock\n'), ((7206, 7277), 'unittest.mock.patch.object', 'mock.patch.object',... |
import numpy as np
import torch
import torch.nn.functional as F
class BinMaxMarginLoss:
def __init__(self, pos_margin=1.0, neg_margin=1.0, pos_scale=1.0, neg_scale=1.0):
self.pos_margin = pos_margin
self.neg_margin = neg_margin
self.pos_scale = pos_scale
self.neg_scale = neg_scale
... | [
"torch.add",
"numpy.zeros",
"numpy.array",
"torch.nn.functional.relu",
"torch.tensor"
] | [((647, 664), 'numpy.zeros', 'np.zeros', (['n_types'], {}), '(n_types)\n', (655, 664), True, 'import numpy as np\n'), ((816, 887), 'numpy.array', 'np.array', (['[vecs_mat[token_id] for token_id in token_id_seq]', 'np.float32'], {}), '([vecs_mat[token_id] for token_id in token_id_seq], np.float32)\n', (824, 887), True, ... |
#
# Copyright (C) 2020 IBM. All Rights Reserved.
#
# See LICENSE.txt file in the root directory
# of this source tree for licensing information.
#
"""
This example demonstrates the use of Contextual Thomspon Sampling to calibrate the
selector for CLAI skills --> https://pages.github.ibm.com/AI-Engineering/bandit-core/... | [
"numpy.asarray",
"bandits.instantiate_from_file",
"pathlib.Path"
] | [((939, 995), 'bandits.instantiate_from_file', 'bandits.instantiate_from_file', (['self._path_to_config_file'], {}), '(self._path_to_config_file)\n', (968, 995), False, 'import bandits\n'), ((2316, 2343), 'numpy.asarray', 'numpy.asarray', (['context_data'], {}), '(context_data)\n', (2329, 2343), False, 'import numpy\n'... |
import numpy as np
import MDSplus as mds
shot_list = range(37168, 37187 + 1)
data = np.empty((0, len(shot_list)), float)
for shot_number in shot_list:
try:
tree = mds.Tree("mpts", shot_number)
Ed = tree.getNode("\\OPHIRENERGYDIRECT").data()
Er = tree.getNode("\\OPHIRENERGYRETURN").data()
... | [
"numpy.append",
"numpy.savetxt",
"MDSplus.Tree"
] | [((851, 1016), 'numpy.savetxt', 'np.savetxt', (['"""Energy_table.csv"""', 'data'], {'fmt': '"""%d, %.2f, %.2f, %d, %.1f, %.3f"""', 'header': 'u"""Shot, E direct[J], E return[J], MCP [V], dur II [us], trigger time [s]"""'}), "('Energy_table.csv', data, fmt='%d, %.2f, %.2f, %d, %.1f, %.3f',\n header=\n u'Shot, E di... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py 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 late... | [
"numpy.array"
] | [((1834, 1850), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (1842, 1850), True, 'import numpy as np\n'), ((2833, 2849), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (2841, 2849), True, 'import numpy as np\n'), ((4688, 4704), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (4696, ... |
#!/usr/bin/env python
# Particle Swarm Optimization
# See https://en.wikipedia.org/wiki/Particle_swarm_optimization for more info
# Author: <NAME>
# Import native modules
import numpy as np
import sys
import os
import random
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolk... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.zeros",
"Swarm.Swarm",
"ObjectiveFunction.objective_function",
"numpy.array",
"numpy.linspace",
"os.path.join"
] | [((584, 614), 'Swarm.Swarm', 'Swarm', ([], {'number_of_particles': '(100)'}), '(number_of_particles=100)\n', (589, 614), False, 'from Swarm import Swarm\n'), ((661, 679), 'numpy.array', 'np.array', (['[10, 10]'], {}), '([10, 10])\n', (669, 679), True, 'import numpy as np\n'), ((695, 715), 'numpy.array', 'np.array', (['... |
from datetime import datetime
from numpy import abs, subtract
from tradingtools.utils.equitydata import PastQuoteDataKeys
from .EMA import EMA
from ..indicators import Indicator, SignalStrengthTypes, SignalTypes
from ...analysis import trend_length_and_slope
SLOW_WINDOW_SIZE = 26
FAST_WINDOW_SIZE = 12
SIGNAL_WINDOW_S... | [
"datetime.datetime.today",
"numpy.abs",
"numpy.subtract"
] | [((2287, 2309), 'numpy.subtract', 'subtract', (['macd', 'signal'], {}), '(macd, signal)\n', (2295, 2309), False, 'from numpy import abs, subtract\n'), ((2402, 2418), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (2416, 2418), False, 'from datetime import datetime\n'), ((4121, 4137), 'datetime.datetime.... |
from typing import Callable, List, Optional
import matplotlib
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from bridge_sim.internal.plot import default_cmap, plt
from bridge_sim.internal.plot.geometry.angles import ax_3d
from bridge_sim.model import Material
from bridge_sim.sim.model imp... | [
"bridge_sim.internal.plot.plt.gca",
"matplotlib.colors.Normalize",
"bridge_sim.internal.plot.geometry.angles.ax_3d",
"matplotlib.cm.ScalarMappable",
"matplotlib.collections.PolyCollection",
"bridge_sim.internal.plot.plt.legend",
"mpl_toolkits.mplot3d.art3d.Poly3DCollection",
"numpy.array",
"bridge_s... | [((1379, 1436), 'matplotlib.colors.Normalize', 'matplotlib.colors.Normalize', ([], {'vmin': 'prop_min', 'vmax': 'prop_max'}), '(vmin=prop_min, vmax=prop_max)\n', (1406, 1436), False, 'import matplotlib\n'), ((3657, 3666), 'bridge_sim.internal.plot.plt.gca', 'plt.gca', ([], {}), '()\n', (3664, 3666), False, 'from bridge... |
import sys
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
if sys.version_info.major == 3:
xrange = range
def im2uint8(x):
if x.__class__ == tf.Tensor:
return tf.cast(tf.clip_by_value(x, 0.0, 1.0) * 255.0, tf.uint8)
else:
t = np.clip(x, 0.0, 1.0) * 255.0
... | [
"tensorflow.contrib.slim.conv2d",
"tensorflow.clip_by_value",
"tensorflow.train.polynomial_decay",
"tensorflow.maximum",
"tensorflow.variable_scope",
"numpy.clip",
"tensorflow.minimum",
"tensorflow.cast"
] | [((740, 772), 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.float32'], {}), '(global_step, tf.float32)\n', (747, 772), True, 'import tensorflow as tf\n'), ((855, 873), 'tensorflow.minimum', 'tf.minimum', (['(1.0)', 't'], {}), '(1.0, t)\n', (865, 873), True, 'import tensorflow as tf\n'), ((924, 964), 'tensorflow.ma... |
#!/usr/bin/python3
# created by cicek on Oct 15, 2020 2:47 PM
import numpy as np
import matplotlib.pyplot as plt
import os
def get_png_files():
print(os.getcwd()) # /home/cicek/PycharmProjects/image_processing
print(os.listdir())
# ['.idea', 'README.md', 'hafta_01.py', 'figure_1.png',
# 'hafta_02.py... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"os.getcwd",
"matplotlib.pyplot.imshow",
"numpy.asarray",
"numpy.zeros",
"matplotlib.pyplot.imread",
"os.listdir"
] | [((1563, 1586), 'matplotlib.pyplot.imread', 'plt.imread', (['"""pic_1.jpg"""'], {}), "('pic_1.jpg')\n", (1573, 1586), True, 'import matplotlib.pyplot as plt\n'), ((385, 396), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (394, 396), False, 'import os\n'), ((632, 643), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (641, 643... |
import numpy as np
import keras.backend as K
import pytest
import sys
from keras.callbacks import TensorBoard
from keras.layers import Input, Dense, SimpleRNN, LSTM, GRU, Concatenate
from keras.models import Model
from keras.utils.test_utils import keras_test
from keras.utils import custom_object_scope
from recurrent... | [
"keras.models.Model.from_config",
"keras.backend.backend",
"keras.models.Model",
"pytest.main",
"recurrentcontainer.RecurrentContainer",
"keras.layers.Concatenate",
"numpy.random.randint",
"keras.layers.Dense",
"keras.layers.Input",
"pytest.mark.parametrize",
"keras.backend.clear_session",
"ke... | [((877, 962), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""unit,num_states"""', "[('rnn', 1), ('gru', 1), ('lstm', 2)]"], {}), "('unit,num_states', [('rnn', 1), ('gru', 1), ('lstm',\n 2)])\n", (900, 962), False, 'import pytest\n'), ((1929, 1998), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (... |
import numpy as np
from geomm.theobald_qcp import theobald_qcp
from geomm.centering import center
from geomm.centroid import centroid
def superimpose(ref_coords, coords, idxs=None, weights=None):
"""Superimpose a set of coordinates to reference coordinates using the
Theobald-QCP method.
Assumes coordinat... | [
"geomm.theobald_qcp.theobald_qcp",
"numpy.transpose",
"geomm.centroid.centroid",
"numpy.linalg.svd",
"numpy.linalg.det",
"numpy.dot"
] | [((1759, 1819), 'geomm.theobald_qcp.theobald_qcp', 'theobald_qcp', (['ref_coords', 'coords'], {'idxs': 'idxs', 'weights': 'weights'}), '(ref_coords, coords, idxs=idxs, weights=weights)\n', (1771, 1819), False, 'from geomm.theobald_qcp import theobald_qcp\n'), ((1936, 1967), 'numpy.dot', 'np.dot', (['coords', 'rotation_... |
#!/usr/bin/env python3
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import StratifiedShuffleSplit
#from sklearn.cross_validation import StratifiedKFold
from sklearn.metrics import accuracy_score, confusion_matrix... | [
"sklearn.ensemble.RandomForestClassifier",
"argparse.ArgumentParser",
"logging.basicConfig",
"emoji_data.load",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.StratifiedShuffleSplit",
"logging.info",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.f1_score",
"numpy.array",
... | [((485, 501), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (499, 501), False, 'from argparse import ArgumentParser\n'), ((502, 556), 'cmdline.add_args', 'add_args', (['ap', "('general', 'preproc', 'linear', 'tune')"], {}), "(ap, ('general', 'preproc', 'linear', 'tune'))\n", (510, 556), False, 'from cm... |
import numpy as np
import logging
import os
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, VGG16
import gzip
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
IMG_PATH = "images"
IMG_SHAPE = (224, 224, 3) # for VGG
OUT_NAME = "../../d... | [
"numpy.stack",
"tensorflow.keras.preprocessing.image.img_to_array",
"os.walk",
"tensorflow.keras.preprocessing.image.load_img",
"tensorflow.keras.applications.vgg16.VGG16",
"tensorflow.keras.applications.vgg16.preprocess_input",
"os.path.join"
] | [((429, 454), 'tensorflow.keras.applications.vgg16.VGG16', 'VGG16', ([], {'weights': '"""imagenet"""'}), "(weights='imagenet')\n", (434, 454), False, 'from tensorflow.keras.applications.vgg16 import preprocess_input, VGG16\n'), ((522, 539), 'os.walk', 'os.walk', (['IMG_PATH'], {}), '(IMG_PATH)\n', (529, 539), False, 'i... |
#!/usr/bin/env python
"""Provides scikit interface."""
import numpy as np
import networkx as nx
from sklearn import manifold
from sklearn.preprocessing import minmax_scale
from scipy.spatial.distance import squareform
from scipy.spatial.distance import pdist
from ego.vectorize import vectorize
from scipy.sparse impor... | [
"numpy.absolute",
"numpy.linalg.svd",
"scipy.spatial.distance.pdist",
"sklearn.manifold.MDS",
"numpy.unique",
"networkx.minimum_spanning_tree",
"sklearn.linear_model.SGDClassifier",
"networkx.kamada_kawai_layout",
"numpy.max",
"networkx.shortest_path_length",
"numpy.percentile",
"numpy.min",
... | [((673, 766), 'ego.vectorize.vectorize', 'vectorize', (['graphs', 'decomposition_funcs'], {'preprocessors': 'preprocessors', 'nbits': 'nbits', 'seed': '(1)'}), '(graphs, decomposition_funcs, preprocessors=preprocessors, nbits=\n nbits, seed=1)\n', (682, 766), False, 'from ego.vectorize import vectorize\n'), ((819, 8... |
from prody import *
import numpy as np
import cluster_drug_discovery.input_preprocess.feature_extraction as fte
class DihedralsExtractor(fte.FeatureExtractor):
def __init__(self, files, dihedrals):
self.dihedrals = dihedrals
self.files = files
fte.FeatureExtractor.__init__(self, files)
... | [
"numpy.array",
"cluster_drug_discovery.input_preprocess.feature_extraction.FeatureExtractor.__init__"
] | [((275, 317), 'cluster_drug_discovery.input_preprocess.feature_extraction.FeatureExtractor.__init__', 'fte.FeatureExtractor.__init__', (['self', 'files'], {}), '(self, files)\n', (304, 317), True, 'import cluster_drug_discovery.input_preprocess.feature_extraction as fte\n'), ((374, 398), 'numpy.array', 'np.array', (['s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------
# @ File : tools.py
# @ Description:
# @ Author : <NAME>
# @ Contact : <EMAIL>
# @ License : Copyright (c) 2017-2018
# @ Time : 2020/12/11 下午4:22
# @ Software : PyCharm
#----------------------... | [
"numpy.zeros_like",
"torch.randint",
"sklearn.metrics.fbeta_score",
"os.path.dirname",
"torch.nonzero",
"torch.randn",
"time.ctime",
"torch.save",
"shutil.copy"
] | [((3248, 3302), 'sklearn.metrics.fbeta_score', 'fbeta_score', (['target', 'output'], {'beta': '(2)', 'average': '"""samples"""'}), "(target, output, beta=2, average='samples')\n", (3259, 3302), False, 'from sklearn.metrics import fbeta_score\n'), ((6364, 6388), 'torch.randn', 'torch.randn', ([], {'size': '(4, 6)'}), '(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 14:41:47 2019
@author: frohro
"""
import sounddevice as sd
import numpy as np
import matplotlib.pyplot as plt
fs = 48000
N = 48000 # points to take
sd.default.samplerate = fs
sd.default.channels = 2
myrecording = sd.rec(N, blocking=True)
#... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"sounddevice.rec",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.xlabel"
] | [((293, 317), 'sounddevice.rec', 'sd.rec', (['N'], {'blocking': '(True)'}), '(N, blocking=True)\n', (299, 317), True, 'import sounddevice as sd\n'), ((349, 383), 'numpy.arange', 'np.arange', (['(0)', '((N - 1) / fs)', '(1 / fs)'], {}), '(0, (N - 1) / fs, 1 / fs)\n', (358, 383), True, 'import numpy as np\n'), ((414, 426... |
from ef.field import uniform
__all__ = ["ExternalMagneticFieldUniformConf", "ExternalElectricFieldUniformConf",
"ExternalMagneticFieldUniformSection", "ExternalElectricFieldUniformSection"]
from collections import namedtuple
import numpy as np
from ef.config.components.fields.field import FieldConf
from ... | [
"ef.field.uniform.FieldUniform",
"numpy.array",
"collections.namedtuple"
] | [((1302, 1410), 'collections.namedtuple', 'namedtuple', (['"""ExternalMagneticFieldUniform"""', "('magnetic_field_x', 'magnetic_field_y', 'magnetic_field_z')"], {}), "('ExternalMagneticFieldUniform', ('magnetic_field_x',\n 'magnetic_field_y', 'magnetic_field_z'))\n", (1312, 1410), False, 'from collections import nam... |
import os
import numpy as np
import unittest
from ccquery.ngram import LanguageModel
from ccquery.utils import io_utils
def read_data(file, to_float=False):
"""Read contents of file"""
data = []
with open(file, encoding='utf-8') as istream:
for line in istream:
if to_float:
... | [
"ccquery.utils.io_utils.check_file_readable",
"numpy.testing.assert_almost_equal",
"os.path.dirname",
"ccquery.ngram.LanguageModel"
] | [((837, 877), 'ccquery.utils.io_utils.check_file_readable', 'io_utils.check_file_readable', (['self.mfile'], {}), '(self.mfile)\n', (865, 877), False, 'from ccquery.utils import io_utils\n'), ((886, 922), 'ccquery.utils.io_utils.check_file_readable', 'io_utils.check_file_readable', (['sqfile'], {}), '(sqfile)\n', (914,... |
import pytest
import numpy
from thinc.api import reduce_first, reduce_last
from thinc.types import Ragged
@pytest.fixture
def Xs():
seqs = [numpy.zeros((10, 8), dtype="f"), numpy.zeros((4, 8), dtype="f")]
for x in seqs:
x[0] = 1
x[-1] = -1
return seqs
def test_init_reduce_first():
mod... | [
"thinc.api.reduce_first",
"thinc.api.reduce_last",
"numpy.zeros"
] | [((325, 339), 'thinc.api.reduce_first', 'reduce_first', ([], {}), '()\n', (337, 339), False, 'from thinc.api import reduce_first, reduce_last\n'), ((382, 395), 'thinc.api.reduce_last', 'reduce_last', ([], {}), '()\n', (393, 395), False, 'from thinc.api import reduce_first, reduce_last\n'), ((437, 451), 'thinc.api.reduc... |
import pandas as pd
import numpy as np
from application import model_builder
def test_cluster():
# Arrange
df = pd.DataFrame()
df["Some Feature"] = [30.0, 40.0, 50.0, 50, 49, 29]
df["Some Feature 2"] = [5, 6, 6, 6, 5.9, 4.9]
df["Some Feature 3"] = [100, 90, 90, 91, 90, 101]
df["Answer"] = [0, ... | [
"pandas.DataFrame",
"application.model_builder.cluster",
"application.model_builder.determine_target_cluster",
"numpy.array",
"pandas.Series",
"application.model_builder.best_model_probabilities"
] | [((122, 136), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (134, 136), True, 'import pandas as pd\n'), ((740, 768), 'numpy.array', 'np.array', (['[0, 1, 1, 1, 1, 0]'], {}), '([0, 1, 1, 1, 1, 0])\n', (748, 768), True, 'import numpy as np\n'), ((800, 866), 'application.model_builder.determine_target_cluster', 'm... |
"""
Contains lookup tables, constants, and things that are generally static
and useful throughout the library.
"""
import numpy
STDOBSERV_X2 = numpy.array((
0.000000000000,
0.000000000000,
0.000129900000,
0.000414900000,
0.001368000000,
0.004243000000,
0.014310000000,
0.043510000000,
... | [
"numpy.array"
] | [((144, 690), 'numpy.array', 'numpy.array', (['(0.0, 0.0, 0.0001299, 0.0004149, 0.001368, 0.004243, 0.01431, 0.04351, \n 0.13438, 0.2839, 0.34828, 0.3362, 0.2908, 0.19536, 0.09564, 0.03201, \n 0.0049, 0.0093, 0.06327, 0.1655, 0.2904, 0.4334499, 0.5945, 0.7621, \n 0.9163, 1.0263, 1.0622, 1.0026, 0.8544499, 0.64... |
# -*- coding: utf-8 -*-
# Author: hushukai
import tensorflow as tf
import numpy as np
def get_base_anchors_np(width, heights):
"""base anchors"""
num_anchors = len(heights)
w = np.array([width] * num_anchors, dtype=np.float32)
h = np.array(heights, dtype=np.float32)
base_anchors = np.stack([-0.5 ... | [
"numpy.stack",
"tensorflow.meshgrid",
"tensorflow.range",
"tensorflow.logical_and",
"tensorflow.reshape",
"tensorflow.constant",
"tensorflow.stack",
"tensorflow.cast",
"numpy.array",
"tensorflow.where",
"tensorflow.boolean_mask",
"tensorflow.expand_dims"
] | [((192, 241), 'numpy.array', 'np.array', (['([width] * num_anchors)'], {'dtype': 'np.float32'}), '([width] * num_anchors, dtype=np.float32)\n', (200, 241), True, 'import numpy as np\n'), ((250, 285), 'numpy.array', 'np.array', (['heights'], {'dtype': 'np.float32'}), '(heights, dtype=np.float32)\n', (258, 285), True, 'i... |
import os
import numpy as np
from math import pi, sin, cos
from finmag import Simulation as Sim
from finmag.energies import Exchange, Zeeman
from finmag.util.meshes import from_geofile
from finmag.util.consts import mu0
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages_file = os.path.join(MODULE_DIR, "a... | [
"os.path.abspath",
"math.sin",
"finmag.energies.Exchange",
"finmag.Simulation",
"numpy.array",
"math.cos",
"numpy.arange",
"os.path.join"
] | [((293, 333), 'os.path.join', 'os.path.join', (['MODULE_DIR', '"""averages.txt"""'], {}), "(MODULE_DIR, 'averages.txt')\n", (305, 333), False, 'import os\n'), ((250, 275), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (265, 275), False, 'import os\n'), ((354, 390), 'os.path.join', 'os.path.j... |
"""
Module containing classes and methods for querying prometheus and returning metric data.
"""
# core python dependencies
from datetime import datetime, timezone
import logging
from string import Template
from typing import Sequence, Dict, Any
import numbers
import pprint
import base64
import binascii
import json
# ... | [
"numpy.random.seed",
"kubernetes.config.load_incluster_config",
"numpy.isnan",
"base64.b64decode",
"requests.post",
"iter8_analytics.api.utils.Message.join_messages",
"json.loads",
"iter8_analytics.api.v2.types.AggregatedMetricsAnalysis",
"iter8_analytics.api.v2.types.VersionMetric",
"kubernetes.c... | [((847, 883), 'logging.getLogger', 'logging.getLogger', (['"""iter8_analytics"""'], {}), "('iter8_analytics')\n", (864, 883), False, 'import logging\n'), ((1579, 1613), 'kubernetes.config.load_incluster_config', 'kubeconfig.load_incluster_config', ([], {}), '()\n', (1611, 1613), True, 'from kubernetes import config as ... |
import os
import re
import datetime
import pandas as pd
import shutil
from prose import io, Telescope, FitsManager
from os import path
from astropy.io import fits
from . import utils
from astropy.table import Table
import numpy as np
from astropy.time import Time
import xarray as xr
from prose.blocks.registration impor... | [
"os.mkdir",
"numpy.nanmedian",
"numpy.argmax",
"pandas.read_csv",
"numpy.ones",
"prose.blocks.registration.xyshift",
"astropy.io.fits.HDUList",
"numpy.unique",
"astropy.io.fits.ImageHDU",
"numpy.zeros_like",
"prose.FitsManager",
"numpy.std",
"astropy.io.fits.getdata",
"os.path.dirname",
... | [((6301, 6315), 'astropy.io.fits.HDUList', 'fits.HDUList', ([], {}), '()\n', (6313, 6315), False, 'from astropy.io import fits\n'), ((6694, 6713), 'prose.FitsManager', 'FitsManager', (['folder'], {}), '(folder)\n', (6705, 6713), False, 'from prose import io, Telescope, FitsManager\n'), ((8529, 8552), 'prose.io.phot2dic... |
########################
# Author: <NAME>
# Organization: NREL
# Project: ATHENA
########################
'''
The following code serves to clean and format the operational model
data that predictes the volume every half hour so that it can be used to
create the demand files for SUMO to run a simulation. It... | [
"matplotlib.pyplot.title",
"numpy.argmax",
"numpy.argmin",
"matplotlib.pyplot.figure",
"xml.etree.ElementTree.SubElement",
"os.path.join",
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.tostring",
"matplotlib.pyplot.xticks",
"seaborn.set_style",
"matplotlib.pyplot.show",
"matplotlib.p... | [((3826, 3853), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)'}), '(figsize=(15, 6))\n', (3836, 3853), True, 'import matplotlib.pyplot as plt\n'), ((3858, 3884), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (3871, 3884), True, 'import seaborn as sns\n'), ((40... |
from ...base.rotation import rotation_matrix2d_ccw, rotation_matrix2d_cw
from ...base.simulation_box import simulation_box
import linecache
import numpy as np
class rectangle:
"""
Args:
----
pos(np.ndarray) : The position of the COM of the AFP site
L(float) : The ... | [
"linecache.getline",
"numpy.zeros",
"numpy.array",
"numpy.matmul",
"numpy.dot",
"numpy.vstack"
] | [((3777, 3816), 'numpy.vstack', 'np.vstack', (['(axis1, axis2, axis3, axis4)'], {}), '((axis1, axis2, axis3, axis4))\n', (3786, 3816), True, 'import numpy as np\n'), ((1101, 1125), 'numpy.array', 'np.array', (['[L / 2, W / 2]'], {}), '([L / 2, W / 2])\n', (1109, 1125), True, 'import numpy as np\n'), ((1143, 1168), 'num... |
import scipy.sparse as sp
import torch
import h5py
import numpy as np
def load_data_ply():
with h5py.File('data/ply_data_train0.h5', 'r') as f:
# List all groups
print("Keys: %s" % f.keys())
data_key = list(f.keys())[0]
label_key = list(f.keys())[1]
# Get the data
... | [
"h5py.File",
"numpy.random.seed",
"torch.index_select",
"numpy.random.random",
"numpy.array",
"numpy.arange",
"torch.tensor"
] | [((1934, 1973), 'torch.index_select', 'torch.index_select', (['a', 'dim', 'order_index'], {}), '(a, dim, order_index)\n', (1952, 1973), False, 'import torch\n'), ((2061, 2080), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (2075, 2080), True, 'import numpy as np\n'), ((2283, 2300), 'torch.tensor', ... |
from pathlib import Path
import numpy as np
import pandas as pd
# Project Imports
from slam.common.utils import assert_debug, check_tensor
def delimiter():
"""
The column delimiter in pandas csv
"""
return ","
def write_poses_to_disk(file_path: str, poses: np.ndarray):
"""
Writes an array ... | [
"pandas.DataFrame",
"pandas.read_csv",
"numpy.zeros",
"numpy.expand_dims",
"numpy.ones",
"pathlib.Path",
"slam.common.utils.assert_debug",
"slam.common.utils.check_tensor",
"numpy.concatenate"
] | [((433, 464), 'slam.common.utils.check_tensor', 'check_tensor', (['poses', '[-1, 4, 4]'], {}), '(poses, [-1, 4, 4])\n', (445, 464), False, 'from slam.common.utils import assert_debug, check_tensor\n'), ((476, 491), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (480, 491), False, 'from pathlib import Pat... |
"""
A Stage to load data from a CSV datarelease format file into a PISA pi ContainerSet
"""
from __future__ import absolute_import, print_function, division
import numpy as np
import pandas as pd
from pisa import FTYPE
from pisa.core.stage import Stage
from pisa.utils import vectorizer
from pisa.utils.resources impo... | [
"numpy.copy",
"numpy.logical_and",
"pandas.read_csv",
"numpy.ones",
"pisa.core.container.Container",
"pisa.utils.resources.find_resource"
] | [((781, 807), 'pisa.utils.resources.find_resource', 'find_resource', (['events_file'], {}), '(events_file)\n', (794, 807), False, 'from pisa.utils.resources import find_resource\n'), ((1023, 1052), 'pandas.read_csv', 'pd.read_csv', (['self.events_file'], {}), '(self.events_file)\n', (1034, 1052), True, 'import pandas a... |
"""
MIT License
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribu... | [
"subprocess.run",
"numpy.array",
"os.path.splitext"
] | [((1471, 1502), 'numpy.array', 'np.array', (['raw'], {'dtype': 'np.float32'}), '(raw, dtype=np.float32)\n', (1479, 1502), True, 'import numpy as np\n'), ((2140, 2237), 'subprocess.run', 'run', (["['ahodecoder16_64', lf0_name, cc_name, fv_name, wav_name]"], {'stdout': 'PIPE', 'encoding': '"""ascii"""'}), "(['ahodecoder1... |
#!/usr/bin/env python
#coding=utf-8
# 輸入點 並且 計算 各自的距離
import numpy as np
# 原點+9 個節點 原點設為index 0
x = [0,19.47000,-6.47000,40.09000,5.39000,15.23000,-10,-20.47000,5.20000,16.30000]
y = [0,6.10000,-4.44000,-1.54000,6.37000,7.24000,4.05000,7.02000,7.666,-7.38000]
# =======================================================... | [
"numpy.zeros"
] | [((423, 439), 'numpy.zeros', 'np.zeros', (['(n, 2)'], {}), '((n, 2))\n', (431, 439), True, 'import numpy as np\n'), ((562, 578), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (570, 578), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Visualizes the segmentations done by Freesurfer of glymphatics patients
"""
import os
from glob import glob
from random import random
import random as rd
import numpy as np
import nibabel as nib
from scipy import ndimage
import matplotlib.pyplot as plt
import matplot... | [
"matplotlib.colors.LinearSegmentedColormap.from_list",
"matplotlib.pyplot.tight_layout",
"numpy.isin",
"nibabel.load",
"os.path.basename",
"numpy.ma.masked_where",
"matplotlib.pyplot.subplots",
"random.random",
"matplotlib.pyplot.style.use",
"numpy.rot90",
"random.seed",
"os.path.normpath",
... | [((363, 374), 'random.seed', 'rd.seed', (['(12)'], {}), '(12)\n', (370, 374), True, 'import random as rd\n'), ((376, 408), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""dark_background"""'], {}), "('dark_background')\n", (389, 408), True, 'import matplotlib.pyplot as plt\n'), ((1819, 1896), 'matplotlib.colors.L... |
# simple GNN auto-encoder like model
# https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html#implementing-the-gcn-layer
import numpy as np
import torch
import networkx as nx
import torch.nn as nn
from torch.nn import functional as F
from argparse import ArgumentParser
from tqdm import trange
import... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.nn.L1Loss",
"tqdm.trange",
"torch.manual_seed",
"networkx.is_connected",
"torch_geometric.utils.from_networkx",
"torch_geometric.data.DataLoader",
"numpy.random.random",
"networkx.Graph",
"torch.nn.Linear",
"networkx.binomial_graph",
"to... | [((480, 497), 'numpy.random.seed', 'np.random.seed', (['(4)'], {}), '(4)\n', (494, 497), True, 'import numpy as np\n'), ((498, 518), 'torch.manual_seed', 'torch.manual_seed', (['(4)'], {}), '(4)\n', (515, 518), False, 'import torch\n'), ((527, 585), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""... |
"""This module contains classes for postprocessing policy outputs.
"""
import numpy as np
def parse_output_constraints(dim, spec):
if 'type' not in spec:
raise ValueError('Specification must include type!')
norm_type = spec.pop('type')
lookup = {'norm': NormConstrainer,
'box': BoxCo... | [
"numpy.full",
"numpy.any",
"numpy.linalg.norm",
"numpy.array",
"numpy.vstack"
] | [((1554, 1568), 'numpy.array', 'np.array', (['lims'], {}), '(lims)\n', (1562, 1568), True, 'import numpy as np\n'), ((1825, 1844), 'numpy.full', 'np.full', (['dim', '(-lims)'], {}), '(dim, -lims)\n', (1832, 1844), True, 'import numpy as np\n'), ((1871, 1889), 'numpy.full', 'np.full', (['dim', 'lims'], {}), '(dim, lims)... |
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Implementation of Soft Actor-Critic (SAC)
# Paper: https://arxiv.org/abs/1801.01290
# Soft Actor-Critic Algorithms and Applications
# https://arxiv.org/abs/1812.05905
# Implemetation of Attentive Update of Multi-Critic ... | [
"numpy.random.random_sample",
"random.shuffle",
"torch.cat",
"numpy.random.randint",
"torch.nn.init.calculate_gain",
"torch.no_grad",
"torch.load",
"torch.exp",
"torch.nn.Linear",
"copy.deepcopy",
"torch.randn_like",
"torch.nn.functional.mse_loss",
"torch.clamp",
"torch.cuda.is_available",... | [((392, 417), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (415, 417), False, 'import torch\n'), ((539, 573), 'torch.nn.init.orthogonal_', 'nn.init.orthogonal_', (['m.weight.data'], {}), '(m.weight.data)\n', (558, 573), True, 'import torch.nn as nn\n'), ((1384, 1416), 'torch.nn.Linear', 'nn.L... |
# Util
from django.utils.timezone import utc
from datetime import datetime, timedelta
# numpy processing imports
import numpy as np
# JSON
import json
# Template and context-related imports
from django.shortcuts import render_to_response
from django.template import RequestContext
# Aggregation
from django.db.models... | [
"eve_db.models.MapRegion.objects.get",
"json.dumps",
"datetime.datetime.utcnow",
"eve_db.models.InvType.objects.get",
"apps.market_data.models.Orders.active.filter",
"eve_db.models.MapSolarSystem.objects.get",
"numpy.std",
"eve_db.models.InvTypeMaterial.objects.values",
"numpy.max",
"apps.market_d... | [((863, 894), 'eve_db.models.InvType.objects.get', 'InvType.objects.get', ([], {'id': 'type_id'}), '(id=type_id)\n', (882, 894), False, 'from eve_db.models import InvType\n'), ((1138, 1169), 'eve_db.models.InvType.objects.get', 'InvType.objects.get', ([], {'id': 'type_id'}), '(id=type_id)\n', (1157, 1169), False, 'from... |
import numpy as np
from cv2 import cv2
import os
import argparse
from tensorflow.keras.models import load_model
categories = ["Biking", "Drumming", "Basketball", "Diving","Billiards","HorseRiding","Mixing","PushUps","Skiing","Swing"]
image_height = 64
image_width = 64
def predict(video, count,model):
''' funct... | [
"cv2.cv2.VideoCapture",
"tensorflow.keras.models.load_model",
"argparse.ArgumentParser",
"numpy.zeros",
"numpy.expand_dims",
"cv2.cv2.resize",
"numpy.argsort"
] | [((1903, 1940), 'tensorflow.keras.models.load_model', 'load_model', (['"""model_VGG16_CNN_LSTM.h5"""'], {}), "('model_VGG16_CNN_LSTM.h5')\n", (1913, 1940), False, 'from tensorflow.keras.models import load_model\n'), ((589, 640), 'numpy.zeros', 'np.zeros', (['(count, model_ouput_size)'], {'dtype': 'np.float'}), '((count... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from pycompss.api.parameter import FILE_IN
from pycompss.api.task import task
from pycompss.api.api import compss_wait_on, compss_delete_object
from pycompss.functions.reduce import merge_reduce
from ddf_library.utils import g... | [
"ddf_library.utils.read_stage_file",
"ddf_library.utils.create_stage_files",
"pandas.crosstab",
"ddf_library.utils.generate_info",
"pycompss.api.task.task",
"pycompss.api.api.compss_delete_object",
"pycompss.api.api.compss_wait_on",
"numpy.array_split",
"pycompss.functions.reduce.merge_reduce"
] | [((1393, 1428), 'pycompss.api.task.task', 'task', ([], {'returns': '(1)', 'data_input': 'FILE_IN'}), '(returns=1, data_input=FILE_IN)\n', (1397, 1428), False, 'from pycompss.api.task import task\n'), ((1692, 1707), 'pycompss.api.task.task', 'task', ([], {'returns': '(1)'}), '(returns=1)\n', (1696, 1707), False, 'from p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The Academy / ASC Common LUT Format Sample Implementations are provided by the
Academy under the following terms and conditions:
Copyright © 2015 Academy of Motion Picture Arts and Sciences ("A.M.P.A.S.").
Portions contributed by others as indicated. All rights reserv... | [
"optparse.OptionParser",
"OpenImageIO.ImageInput.open",
"multiprocessing.cpu_count",
"clf.bitDepths.values",
"traceback.print_exc",
"clf.Range",
"sys.argv.index",
"numpy.uint16",
"clf.ProcessList",
"OpenImageIO.ImageOutput.create",
"numpy.float16",
"math.ceil",
"OpenImageIO.ImageSpec",
"mu... | [((3434, 3476), 'numpy.array', 'np.array', (['[half1, half2]'], {'dtype': 'np.float16'}), '([half1, half2], dtype=np.float16)\n', (3442, 3476), True, 'import numpy as np\n'), ((5661, 5692), 'OpenImageIO.ImageInput.open', 'oiio.ImageInput.open', (['inputPath'], {}), '(inputPath)\n', (5681, 5692), True, 'import OpenImage... |
import torch
import os
from datetime import datetime
import numpy as np
from models import actor, critic, actor_image, critic_image
# from utils import sync_networks, sync_grads
from replay_buffer import replay_buffer
from normalizer import normalizer
from her import her_sampler
import time
"""
ddpg with HER (MPI-ver... | [
"numpy.absolute",
"numpy.clip",
"numpy.isnan",
"numpy.mean",
"models.actor",
"models.critic_image",
"torch.no_grad",
"os.path.join",
"numpy.random.randn",
"torch.load",
"replay_buffer.replay_buffer",
"datetime.datetime.now",
"models.critic",
"torch.clamp",
"numpy.random.uniform",
"norm... | [((984, 1059), 'normalizer.normalizer', 'normalizer', ([], {'size': "env_params['obs']", 'default_clip_range': 'self.args.clip_range'}), "(size=env_params['obs'], default_clip_range=self.args.clip_range)\n", (994, 1059), False, 'from normalizer import normalizer\n'), ((2842, 2958), 'replay_buffer.replay_buffer', 'repla... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import numpy as np
from Functions.descgradient import _calcgrad
from Functions.initialisevalues import _iniatilise
# Gen_i Bus_i a(€/h) b(€/MWh) c(€/(MW)^2.h) Emissions(kgCO2/MWh) Pgmin(MW) Pgmax(MW)
data_gen = np.matrix([[... | [
"numpy.matrix",
"Functions.descgradient._calcgrad",
"Functions.initialisevalues._iniatilise",
"numpy.savetxt"
] | [((308, 469), 'numpy.matrix', 'np.matrix', (['[[1, 1, 800, 20, 0.06, 80, 30, 90], [2, 1, 800, 16, 0.1, 200, 20, 60], [3, \n 4, 800, 20, 0.08, 175, 40, 80], [4, 4, 800, 22, 0.11, 60, 30, 70]]'], {}), '([[1, 1, 800, 20, 0.06, 80, 30, 90], [2, 1, 800, 16, 0.1, 200, 20,\n 60], [3, 4, 800, 20, 0.08, 175, 40, 80], [4, ... |
import logging
import os
import sys
import warnings
from datetime import date, datetime
from typing import Dict, Iterable, List, Union
import numpy as np
import pandas as pd
import requests
import tables
import yaml
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from pvoutput.consts im... | [
"yaml.load",
"pandas.HDFStore",
"logging.FileHandler",
"pandas.date_range",
"warnings.simplefilter",
"requests.adapters.HTTPAdapter",
"requests.Session",
"numpy.unique",
"os.path.exists",
"logging.StreamHandler",
"logging.getLogger",
"pandas.DatetimeIndex",
"logging.Formatter",
"warnings.c... | [((411, 440), 'logging.getLogger', 'logging.getLogger', (['"""pvoutput"""'], {}), "('pvoutput')\n", (428, 440), False, 'import logging\n'), ((1015, 1044), 'logging.getLogger', 'logging.getLogger', (['"""pvoutput"""'], {}), "('pvoutput')\n", (1032, 1044), False, 'import logging\n'), ((1251, 1324), 'logging.Formatter', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import unittest
import sys
sys.path.append('.')
from chempy.io.gaussian import *
from chempy.states import *
################################################################################
class GaussianTest(unittest.TestCase):
"""
Contains unit te... | [
"sys.path.append",
"numpy.array",
"unittest.TextTestRunner"
] | [((87, 107), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (102, 107), False, 'import sys\n'), ((1380, 1416), 'numpy.array', 'numpy.array', (['[298.15]', 'numpy.float64'], {}), '([298.15], numpy.float64)\n', (1391, 1416), False, 'import numpy\n'), ((2770, 2806), 'numpy.array', 'numpy.array', (['[2... |
"""
Padding overhead
"""
# Python standard library
import csv
import gc
from math import ceil
# Libraries
import numpy as np
# Local files
from .common import ensures_csv_exists, ensures_dir_exists, parse_arg_list_float
from .dummies.dummies import cover_size, compute_cover
def padding_overhead(nr_voters, nr_ballo... | [
"numpy.logspace",
"csv.writer",
"math.ceil"
] | [((1003, 1054), 'numpy.logspace', 'np.logspace', (['voters_min', 'voters_max'], {'dtype': 'np.int64'}), '(voters_min, voters_max, dtype=np.int64)\n', (1014, 1054), True, 'import numpy as np\n'), ((2267, 2318), 'numpy.logspace', 'np.logspace', (['voters_min', 'voters_max'], {'dtype': 'np.int64'}), '(voters_min, voters_m... |
"""
======================================================
Simple RNN
======================================================
Simple example of using RNNs.
"""
import pandas as pd
import numpy as np
import torch
from grammaropt.grammar import build_grammar
from grammaropt.grammar import extract_rules_from_grammar
fr... | [
"numpy.random.uniform",
"grammaropt.rnn.RnnWalker",
"grammaropt.rnn.RnnAdapter",
"numpy.abs",
"grammaropt.grammar.extract_rules_from_grammar",
"grammaropt.grammar.build_grammar",
"grammaropt.grammar.as_str",
"grammaropt.rnn.RnnModel",
"grammaropt.terminal_types.Int"
] | [((565, 603), 'numpy.random.uniform', 'np.random.uniform', (['(-3)', '(3)'], {'size': '(1000,)'}), '(-3, 3, size=(1000,))\n', (582, 603), True, 'import numpy as np\n'), ((993, 1026), 'grammaropt.grammar.build_grammar', 'build_grammar', (['rules'], {'types': 'types'}), '(rules, types=types)\n', (1006, 1026), False, 'fro... |
from picamera import PiCamera
import picamera.array
import time
import cv2
import numpy as np
def finmaxcontour(src):
_,contours,hierarchy=cv2.findContours(src,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
hierarchy=np.squeeze(hierarchy)
#print(hierarchy)
chosen_index=0
max_area=0
index=0
#print... | [
"cv2.contourArea",
"cv2.circle",
"numpy.int0",
"numpy.copy",
"cv2.dilate",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.threshold",
"numpy.float32",
"cv2.fillPoly",
"cv2.imread",
"cv2.boxPoints",
"cv2.goodFeaturesToTrack",
"cv2.minAreaRect",
"numpy.squeeze",
"cv2.drawContours",
"cv2.cornerHar... | [((614, 640), 'cv2.imread', 'cv2.imread', (['"""test3.jpg"""', '(1)'], {}), "('test3.jpg', 1)\n", (624, 640), False, 'import cv2\n'), ((686, 723), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (698, 723), False, 'import cv2\n'), ((723, 752), 'cv2.imwrite', 'cv2.imwr... |
# program that makes a list called ages that has the same number random value as salaries range 21 to 65 and shows a scatter plot of that data with the salaries. Then add a plot of y = x**2 over it
#
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5) # modify the programe so random salaries are t... | [
"matplotlib.pyplot.title",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"numpy.random.randint",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((256, 273), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (270, 273), True, 'import numpy as np\n'), ((349, 384), 'numpy.random.randint', 'np.random.randint', (['(20000)', '(80000)', '(10)'], {}), '(20000, 80000, 10)\n', (366, 384), True, 'import numpy as np\n'), ((392, 421), 'numpy.random.randint', ... |
from tilec import utils as tutils,covtool,fg
import argparse, yaml
import numpy as np
from pixell import enmap,fft,utils
from orphics import maps,io,stats
"""
Issues:
1. SOLVED by only using ells<lmax: 12 arrays form a 22 GB covmat for deep56. Can reduce resolution by 4x if lmax=5000, fit it in 5.5 GB.
2. Cross-covar... | [
"numpy.save",
"argparse.ArgumentParser",
"numpy.logical_and",
"orphics.maps.FourierCalc",
"numpy.zeros",
"pixell.enmap.modlmap",
"orphics.maps.minimum_ell",
"numpy.logical_or",
"numpy.rollaxis",
"orphics.maps.gauss_beam",
"pixell.utils.eigpow"
] | [((556, 609), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Make ILC maps."""'}), "(description='Make ILC maps.')\n", (579, 609), False, 'import argparse, yaml\n'), ((1161, 1194), 'orphics.maps.FourierCalc', 'maps.FourierCalc', (['shape[-2:]', 'wcs'], {}), '(shape[-2:], wcs)\n', (1177, ... |
# Version 3.1; <NAME>; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
import math
import os
import sys
import traceback
from warnings import warn
import numpy as np
from osgeo import gdal_array, gdalconst
from osgeo import gdal, ogr, osr
gdal.UseExceptions()
class RasterIO... | [
"sys.stdout.write",
"os.path.isfile",
"sys.stdout.flush",
"numpy.arange",
"osgeo.gdal.GetDriverByName",
"osgeo.gdal.ReprojectImage",
"osgeo.gdal.GetDataTypeName",
"numpy.full",
"traceback.print_exc",
"numpy.multiply",
"numpy.logical_not",
"numpy.max",
"numpy.add",
"osgeo.gdal.UseExceptions... | [((283, 303), 'osgeo.gdal.UseExceptions', 'gdal.UseExceptions', ([], {}), '()\n', (301, 303), False, 'from osgeo import gdal, ogr, osr\n'), ((1353, 1392), 'osgeo.gdal.Open', 'gdal.Open', (['rasterFile', 'gdal.GA_ReadOnly'], {}), '(rasterFile, gdal.GA_ReadOnly)\n', (1362, 1392), False, 'from osgeo import gdal, ogr, osr\... |
import gzip
import time
import pickle
import numpy as np
import networkx as nx
import pytest
import pysubiso
from pysubiso.util import *
MATCHERS = ['ri', 'NX']
@pytest.mark.parametrize('matcher', MATCHERS)
def test_iso_same(matcher):
# X is to itself
x = np.zeros((3, 3), np.int32)
c = np.zeros(3, np... | [
"numpy.random.seed",
"numpy.zeros",
"numpy.random.randint",
"pysubiso.create_match",
"numpy.random.choice",
"numpy.random.permutation",
"pytest.mark.parametrize"
] | [((169, 213), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""matcher"""', 'MATCHERS'], {}), "('matcher', MATCHERS)\n", (192, 213), False, 'import pytest\n'), ((1004, 1048), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""matcher"""', 'MATCHERS'], {}), "('matcher', MATCHERS)\n", (1027, 1048), Fa... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 10:54:07 2018
Image label cleaning tool
I think you often suffer such a situation too:
You have a large amount of rough-labeled image data, and you don't have
enough labor to complete the labeling of these data.
This is really helpless!
We often use the followi... | [
"keras.models.load_model",
"os.mkdir",
"os.path.exists",
"numpy.expand_dims",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",
"shutil.move",
"os.path.join",
"os.listdir"
] | [((3663, 3686), 'os.listdir', 'os.listdir', (['dataset_dir'], {}), '(dataset_dir)\n', (3673, 3686), False, 'import os\n'), ((1753, 1776), 'keras.models.load_model', 'load_model', (['weight_path'], {}), '(weight_path)\n', (1763, 1776), False, 'from keras.models import load_model\n'), ((2658, 2743), 'keras.preprocessing.... |
import unittest
import cupy as cp
import numpy as np
from src.data_sets.preprocessing import min_max_feature_scaling, split_into_classes
class TestPreprocessing(unittest.TestCase):
def test_min_max_feature_scaling(self):
"""Tests whether min_max_feature_scaling() behaves as intended."""
X_train... | [
"cupy.array",
"src.data_sets.preprocessing.split_into_classes",
"numpy.array",
"src.data_sets.preprocessing.min_max_feature_scaling"
] | [((323, 370), 'numpy.array', 'np.array', (['[[1, 2, 3], [0, -5, 6], [0.1, -1, 3]]'], {}), '([[1, 2, 3], [0, -5, 6], [0.1, -1, 3]])\n', (331, 370), True, 'import numpy as np\n'), ((445, 478), 'numpy.array', 'np.array', (['[[5, 2, 1], [-5, 2, 1]]'], {}), '([[5, 2, 1], [-5, 2, 1]])\n', (453, 478), True, 'import numpy as n... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import os
# Kestrel analytics default paths
INPUT_DATA_PATH = "/data/input/0.parquet.gz"
OUTPUT_DISP_PATH = "/data/display/plot.html"
class PlotFailure(Exception):
pass
x_col = os.environ.get('XPARAM')
y_col = os.environ.get('YPARAM')
if not x_col ... | [
"os.environ.get",
"pandas.to_datetime",
"pandas.read_parquet",
"numpy.modf",
"numpy.issubdtype"
] | [((249, 273), 'os.environ.get', 'os.environ.get', (['"""XPARAM"""'], {}), "('XPARAM')\n", (263, 273), False, 'import os\n'), ((282, 306), 'os.environ.get', 'os.environ.get', (['"""YPARAM"""'], {}), "('YPARAM')\n", (296, 306), False, 'import os\n'), ((579, 621), 'numpy.issubdtype', 'np.issubdtype', (['df[column].dtype',... |
import json
import os
import time
from itertools import product
import biosppy
import numpy as np
from flask import Flask, request
from scipy.signal import filtfilt
from tensorflow.keras.models import load_model
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
app = Flask(__name__)
VERIFY_MODEL = load_mode... | [
"json.dump",
"json.load",
"tensorflow.keras.models.load_model",
"scipy.signal.filtfilt",
"numpy.argmax",
"numpy.std",
"flask.Flask",
"json.dumps",
"time.time",
"numpy.isnan",
"flask.request.get_json",
"numpy.mean",
"numpy.array",
"biosppy.signals.ecg.hamilton_segmenter",
"itertools.produ... | [((280, 295), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (285, 295), False, 'from flask import Flask, request\n'), ((311, 346), 'tensorflow.keras.models.load_model', 'load_model', (['"""model/"""'], {'compile': '(False)'}), "('model/', compile=False)\n", (321, 346), False, 'from tensorflow.keras.models... |
import numpy as np
import pandas as pd
def exclude_subjects(subjects, mod, reset=False):
"""
Utility function to denote excluded subjects
Parameters
----------
subjects: list of str
The subjects to be excluded
mod: str
The modality they are being excluded base on. fmri, eeg, e... | [
"pandas.read_csv",
"numpy.array"
] | [((592, 616), 'pandas.read_csv', 'pd.read_csv', (['f'], {'sep': '"""\t"""'}), "(f, sep='\\t')\n", (603, 616), True, 'import pandas as pd\n'), ((1460, 1484), 'pandas.read_csv', 'pd.read_csv', (['f'], {'sep': '"""\t"""'}), "(f, sep='\\t')\n", (1471, 1484), True, 'import pandas as pd\n'), ((1579, 1623), 'numpy.array', 'np... |
#!/usr/bin/env python3
import pylab as pl
import numpy as np
import time
import scipy.integrate as integrate
#uniform (normalized) distribution on support [0,10]
def q(x):
return 1/10.0+x-x
#target (approximately normalized) distribution on support [0,10]
def p(x):
return (0.3*np.exp(-(x-0.3)**2) + 0.7* np.ex... | [
"pylab.hist",
"numpy.size",
"pylab.show",
"pylab.axis",
"pylab.ylabel",
"numpy.zeros",
"time.time",
"numpy.where",
"numpy.arange",
"numpy.mean",
"pylab.xlabel",
"numpy.exp",
"numpy.random.rand"
] | [((1493, 1504), 'time.time', 'time.time', ([], {}), '()\n', (1502, 1504), False, 'import time\n'), ((1536, 1547), 'time.time', 'time.time', ([], {}), '()\n', (1545, 1547), False, 'import time\n'), ((1941, 1962), 'numpy.arange', 'np.arange', (['(0)', '(4)', '(0.01)'], {}), '(0, 4, 0.01)\n', (1950, 1962), True, 'import n... |
from recoder.data import RecommendationDataset, RecommendationDataLoader, BatchCollator
from recoder.utils import dataframe_to_csr_matrix
import pandas as pd
import numpy as np
import torch
import pytest
def generate_dataframe():
data = pd.DataFrame()
data['user'] = np.random.randint(0, 100, 1000)
data['item'... | [
"pandas.DataFrame",
"recoder.data.RecommendationDataLoader",
"numpy.ones",
"recoder.data.RecommendationDataset",
"recoder.utils.dataframe_to_csr_matrix",
"numpy.random.randint",
"recoder.data.BatchCollator",
"pytest.mark.parametrize",
"torch.sparse.FloatTensor",
"numpy.unique"
] | [((3601, 3676), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""batch_size,num_sampling_users"""', '[(5, 0), (5, 10)]'], {}), "('batch_size,num_sampling_users', [(5, 0), (5, 10)])\n", (3624, 3676), False, 'import pytest\n'), ((5886, 5942), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""batch_si... |
import pytest
import numpy as np
from discolight.annotations import (annotations_to_numpy_array)
from discolight.augmentations.horizontalflip import HorizontalFlip
from discolight.augmentations.verticalflip import VerticalFlip
@pytest.mark.usefixtures("sample_image")
@pytest.mark.parametrize("augmentation", [Horizon... | [
"discolight.augmentations.verticalflip.VerticalFlip",
"numpy.allclose",
"discolight.annotations.annotations_to_numpy_array",
"discolight.augmentations.horizontalflip.HorizontalFlip",
"pytest.mark.usefixtures"
] | [((231, 270), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""sample_image"""'], {}), "('sample_image')\n", (254, 270), False, 'import pytest\n'), ((464, 503), 'discolight.annotations.annotations_to_numpy_array', 'annotations_to_numpy_array', (['annotations'], {}), '(annotations)\n', (490, 503), False, 'fro... |
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
X_train = np.load('X_train.dat')
y_train = np.load('y_train.dat')
X_test = np.load('X_test.dat')
y_median = np.median(y_train)
y_mean = np.mean(y_train)
X_trainr, X_val, y_trainr, y_val = train_test... | [
"numpy.load",
"xgboost.plot_importance",
"matplotlib.pyplot.show",
"numpy.median",
"sklearn.model_selection.train_test_split",
"xgboost.train",
"pandas.read_csv",
"numpy.mean",
"xgboost.DMatrix"
] | [((127, 149), 'numpy.load', 'np.load', (['"""X_train.dat"""'], {}), "('X_train.dat')\n", (134, 149), True, 'import numpy as np\n'), ((160, 182), 'numpy.load', 'np.load', (['"""y_train.dat"""'], {}), "('y_train.dat')\n", (167, 182), True, 'import numpy as np\n'), ((192, 213), 'numpy.load', 'np.load', (['"""X_test.dat"""... |
import matplotlib.pyplot as plt
import numpy as np
from cleverhans.attacks import FastGradientMethod
from secml.adv.attacks import CAttackEvasionCleverhans
def prepare_attack_classification(perturbation_type, data_max, data_min,
model, ts):
if perturbation_type == 'max-norm':
... | [
"numpy.transpose",
"matplotlib.pyplot.style.context",
"numpy.exp",
"numpy.squeeze",
"secml.adv.attacks.CAttackEvasionCleverhans"
] | [((633, 800), 'secml.adv.attacks.CAttackEvasionCleverhans', 'CAttackEvasionCleverhans', ([], {'classifier': 'model', 'surrogate_classifier': 'model', 'y_target': 'None', 'surrogate_data': 'ts', 'clvh_attack_class': 'FastGradientMethod'}), '(classifier=model, surrogate_classifier=model,\n y_target=None, surrogate_dat... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def init_weights(m, gain):
if (type(m) == nn.Linear) | (type(m) == nn.Conv2d):
nn.init.orthogonal_(m.weight, gain)
nn.init.zeros_(m.bias)
class CNNDeepmind(nn.Module):
def __init__(self, observation_space, ... | [
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Conv1d",
"torch.nn.init.zeros_",
"torch.nn.Linear",
"torch.nn.init.orthogonal_",
"numpy.sqrt"
] | [((179, 214), 'torch.nn.init.orthogonal_', 'nn.init.orthogonal_', (['m.weight', 'gain'], {}), '(m.weight, gain)\n', (198, 214), True, 'import torch.nn as nn\n'), ((223, 245), 'torch.nn.init.zeros_', 'nn.init.zeros_', (['m.bias'], {}), '(m.bias)\n', (237, 245), True, 'import torch.nn as nn\n'), ((354, 364), 'numpy.sqrt'... |
# pylint: disable=invalid-name
import cv2
import numpy as np
def apply_watermark(watermark, alpha: float = 1., size: float = 1.):
"""Apply a watermark to the bottom right of
images. Based on the work provided at
https://www.pyimagesearch.com/2016/04/25/watermarking-images-with-opencv-and-python/
Arg... | [
"cv2.bitwise_and",
"cv2.cvtColor",
"numpy.zeros",
"numpy.ones",
"cv2.addWeighted",
"cv2.split",
"cv2.merge"
] | [((697, 717), 'cv2.split', 'cv2.split', (['watermark'], {}), '(watermark)\n', (706, 717), False, 'import cv2\n'), ((726, 755), 'cv2.bitwise_and', 'cv2.bitwise_and', (['B', 'B'], {'mask': 'A'}), '(B, B, mask=A)\n', (741, 755), False, 'import cv2\n'), ((764, 793), 'cv2.bitwise_and', 'cv2.bitwise_and', (['G', 'G'], {'mask... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import cv2
import torch
import numpy as np
from pysot.core.config import cfg
from pysot.models.model_builder import ModelBuilder
from pysot.tracker.tracker_builder import build_trac... | [
"pysot.core.config.cfg.merge_from_file",
"argparse.ArgumentParser",
"pysot.tracker.tracker_builder.build_tracker",
"os.path.realpath",
"torch.set_num_threads",
"toolkit.datasets.DatasetFactory.create_dataset",
"numpy.array",
"pysot.models.model_builder.ModelBuilder",
"os.path.join"
] | [((539, 594), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""siamrpn tracking"""'}), "(description='siamrpn tracking')\n", (562, 594), False, 'import argparse\n'), ((969, 993), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (990, 993), False, 'import torch\n'),... |
import numpy as np
class InRangeAssertion():
def assertInRange(self, x_opt, xmin, delta):
if np.linalg.norm(x_opt - xmin) > delta:
raise AssertionError("Result of out of expected range")
| [
"numpy.linalg.norm"
] | [((107, 135), 'numpy.linalg.norm', 'np.linalg.norm', (['(x_opt - xmin)'], {}), '(x_opt - xmin)\n', (121, 135), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
from scipy.spatial.ckdtree import cKDTree
from scipy.spatial.distance import euclidean
from snowland.graphics.core.computational_geometry_2d import PolygonWithoutHoles
from snowland.graphics.solid_geometry import get_bottom_point_index
fr... | [
"scipy.spatial.ckdtree.cKDTree",
"numpy.ones_like",
"matplotlib.pyplot.show",
"scipy.spatial.distance.euclidean",
"numpy.all",
"snowland.graphics.solid_geometry.get_bottom_point_index",
"snowland.plot_helper.plot_helper.plot_arrow",
"snowland.graphics.utils.get_rotate_angle_degree",
"numpy.vstack"
] | [((1354, 1373), 'scipy.spatial.ckdtree.cKDTree', 'cKDTree', (['all_points'], {}), '(all_points)\n', (1361, 1373), False, 'from scipy.spatial.ckdtree import cKDTree\n'), ((1442, 1476), 'snowland.graphics.solid_geometry.get_bottom_point_index', 'get_bottom_point_index', (['all_points'], {}), '(all_points)\n', (1464, 1476... |
# -*- coding: UTF-8 -*-
# @File: Result.py
# @Author: htczero
# @Create Data: 2019/11/16
# @Modify Data: 2019/11/16
# @Email: <EMAIL>
from typing import List
import numpy as np
import os
class Result:
def __init__(self, size: int):
self._dic_result = dict()
self._size = size
# self._lock... | [
"numpy.zeros",
"os.path.join"
] | [((489, 541), 'numpy.zeros', 'np.zeros', (['(self._size, self._size)'], {'dtype': 'np.float64'}), '((self._size, self._size), dtype=np.float64)\n', (497, 541), True, 'import numpy as np\n'), ((868, 904), 'os.path.join', 'os.path.join', (['save_dir', "(key + '.csv')"], {}), "(save_dir, key + '.csv')\n", (880, 904), Fals... |
import os
import collections
import torch
import torchvision
import numpy as np
import scipy.misc as m
import matplotlib.pyplot as plt
from torch.utils import data
import cv2
from augmentations import *
augObj = {'hue': AdjustHue,
'saturation': AdjustSaturation,
'hflip': RandomHorizontallyFlip... | [
"cv2.waitKey",
"cv2.threshold",
"collections.defaultdict",
"cv2.imread",
"numpy.array",
"scipy.misc.imresize",
"numpy.squeeze",
"cv2.imshow",
"os.listdir",
"torch.from_numpy"
] | [((911, 954), 'numpy.array', 'np.array', (['[104.00699, 116.66877, 122.67892]'], {}), '([104.00699, 116.66877, 122.67892])\n', (919, 954), True, 'import numpy as np\n'), ((991, 1020), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (1014, 1020), False, 'import collections\n'), ((1036, ... |
import pandas as pd
import numpy as np
#from scipy.stats import norm
import os
from Data import *
from Dirs import *
from keras.layers import Input, Dense, Lambda, Layer, Reshape, Flatten
from keras.layers import Conv1D, UpSampling1D, MaxPooling1D
from keras.models import Model
from keras.callbacks import ModelCheckpoi... | [
"os.mkdir",
"numpy.absolute",
"os.remove",
"tensorflow.trainable_variables",
"keras.metrics.mean_squared_error",
"tensorflow.constant_initializer",
"tensorflow.reset_default_graph",
"tensorflow.get_variable_scope",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"keras.models.Model",
"keras.b... | [((1132, 1162), 'keras.backend.set_image_dim_ordering', 'K.set_image_dim_ordering', (['"""th"""'], {}), "('th')\n", (1156, 1162), True, 'from keras import backend as K\n'), ((1475, 1503), 'keras.layers.Input', 'Input', ([], {'shape': '(original_dim,)'}), '(shape=(original_dim,))\n', (1480, 1503), False, 'from keras.lay... |
from __future__ import division
import random
import theano
import logging
import lasagne
import argparse
import numpy as np
from itertools import *
from tabulate import tabulate
from collections import Counter
import utils
import featchar
import evaluate_system
from lazrnn import RDNN, RDNN_Dummy
def get_arg_parse... | [
"argparse.ArgumentParser",
"utils.get_dset",
"numpy.std",
"lazrnn.RDNN",
"logging.StreamHandler",
"numpy.random.RandomState",
"evaluate_system.evaluateIdentifier",
"lasagne.random.set_rng",
"socket.gethostname",
"numpy.mean",
"random.seed",
"lazrnn.RDNN_Dummy",
"tabulate.tabulate",
"numpy.... | [((338, 373), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""cwi"""'}), "(prog='cwi')\n", (361, 373), False, 'import argparse\n'), ((5866, 5926), 'evaluate_system.evaluateIdentifier', 'evaluate_system.evaluateIdentifier', (['gold_labels', 'pred_labels'], {}), '(gold_labels, pred_labels)\n', (59... |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
from os.path import join
import numpy as np
import pytest
import biotite
import biotite.sequence.phylo as phylo
from ..util import data_dir
@pytest.fixture
def di... | [
"biotite.sequence.phylo.upgma",
"numpy.allclose",
"biotite.sequence.phylo.Tree.from_newick",
"biotite.sequence.phylo.TreeNode",
"biotite.sequence.phylo.as_binary",
"pytest.raises",
"numpy.array",
"pytest.mark.parametrize",
"biotite.sequence.phylo.Tree",
"biotite.sequence.phylo.neighbor_joining"
] | [((5973, 6588), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""newick, labels, error"""', "[('((1,0),4),2);', None, biotite.InvalidFileError), ('', None, biotite.\n InvalidFileError), ('();', None, biotite.InvalidFileError), (\n '((0,1,(2,3));', None, biotite.InvalidFileError), (\n '((0,1),(2,3),(... |
import cv2 as cv
import numpy as np
import Module as m
import time
import dlib
# variables
COUNTER = 0
TOTAL_BLINK = 0
fonts = cv.FONT_HERSHEY_PLAIN
frameCounter = 0
capID = 0
EyesClosedFrame = 3
# objects
camera = cv.VideoCapture(capID)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(... | [
"cv2.line",
"cv2.putText",
"cv2.VideoWriter_fourcc",
"Module.faceDetector",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imshow",
"numpy.zeros",
"time.time",
"cv2.VideoCapture",
"Module.EyesTracking",
"Module.Position",
"Module.facePoint",
"cv2.VideoWriter",
"cv2.destroyAllWindows",
"Module.bli... | [((217, 239), 'cv2.VideoCapture', 'cv.VideoCapture', (['capID'], {}), '(capID)\n', (232, 239), True, 'import cv2 as cv\n'), ((298, 328), 'cv2.VideoWriter_fourcc', 'cv.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (319, 328), True, 'import cv2 as cv\n'), ((339, 393), 'cv2.VideoWriter', 'cv.VideoWriter', (['"""o... |
#A program for converting and plotting iMet data
#<NAME> and <NAME> 2020
import pandas as pd
import numpy as np
import os
import shutil
from UAH_sounding_plotting import plot_sounding
from sounding_formats import write_sharppy, write_raob, write_research
def convert_imet(file, date, time, location, st, elev):
#pa... | [
"os.mkdir",
"sounding_formats.write_sharppy",
"sounding_formats.write_raob",
"pandas.read_csv",
"os.getcwd",
"os.path.exists",
"pandas.to_datetime",
"numpy.round",
"os.chdir",
"shutil.copy",
"UAH_sounding_plotting.plot_sounding"
] | [((519, 586), 'pandas.read_csv', 'pd.read_csv', (['file'], {'header': '(0)', 'skiprows': '[1, 2]', 'delim_whitespace': '(True)'}), '(file, header=0, skiprows=[1, 2], delim_whitespace=True)\n', (530, 586), True, 'import pandas as pd\n'), ((1009, 1033), 'numpy.round', 'np.round', (["df['Lat/N']", '(5)'], {}), "(df['Lat/N... |
from tensornetwork import Node, TensorNetwork
import numpy as np
from scipy.sparse.linalg import LinearOperator, eigs
from functools import partial
class MPS(Node):
axis_order = ["left_virtual", "physical", "right_virtual"]
ket_axis_order = ["ket_left_virtual", "ket_physical", "ket_right_virtual"]
bra_ax... | [
"numpy.conj",
"numpy.linalg.qr",
"tensornetwork.TensorNetwork",
"scipy.sparse.linalg.LinearOperator",
"numpy.array",
"numpy.linalg.norm",
"numpy.reshape",
"numpy.exp",
"numpy.diag"
] | [((515, 537), 'tensornetwork.TensorNetwork', 'TensorNetwork', (['backend'], {}), '(backend)\n', (528, 537), False, 'from tensornetwork import Node, TensorNetwork\n'), ((1198, 1231), 'numpy.linalg.qr', 'np.linalg.qr', (['mat'], {'mode': '"""reduced"""'}), "(mat, mode='reduced')\n", (1210, 1231), True, 'import numpy as n... |
import unittest
import sys
import numpy as np
sys.path.append('..')
import padasip as pa
class TestPreprocess(unittest.TestCase):
def test_standardize(self):
"""
Test standardization.
"""
u = range(1000)
x = pa.preprocess.standardize(u)
self.assertEqual(x.std(), 1.... | [
"sys.path.append",
"numpy.random.uniform",
"padasip.preprocess.standardize_back",
"numpy.random.seed",
"padasip.preprocess.PCA",
"padasip.preprocess.standardize",
"padasip.preprocess.LDA",
"padasip.preprocess.input_from_history",
"padasip.preprocess.LDA_discriminants",
"padasip.preprocess.PCA_comp... | [((47, 68), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (62, 68), False, 'import sys\n'), ((255, 283), 'padasip.preprocess.standardize', 'pa.preprocess.standardize', (['u'], {}), '(u)\n', (280, 283), True, 'import padasip as pa\n'), ((516, 556), 'padasip.preprocess.standardize_back', 'pa.prepr... |
import numpy as np
from tifffile import imsave,imread
def toUint8(data):
data=np.real(data)
data=data.astype(np.double)
ma=np.max(data)
mi=np.min(data)
data=(data-mi)/(ma-mi)*200
data=data.astype(np.uint8)
return data
def crop_center(img,cropx,cropy):
y,x = img.shape[1],img.shape[2]
... | [
"tifffile.imsave",
"numpy.zeros",
"numpy.max",
"numpy.min",
"numpy.real",
"numpy.random.rand"
] | [((84, 97), 'numpy.real', 'np.real', (['data'], {}), '(data)\n', (91, 97), True, 'import numpy as np\n'), ((137, 149), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (143, 149), True, 'import numpy as np\n'), ((157, 169), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (163, 169), True, 'import numpy as np\n'), ... |
# test_evaluation.py
import numpy as np
import unittest
from scratch.utils import evaluation as eval
class TestEvaluation(unittest.TestCase):
def test_metric_rmse(self):
y = np.array([1.2, 7.9, 4.6, 2.2])
yhat = np.array([2.1, 6.5, 4.4, 2.7])
self.assertEqual(eval.metric_rmse(y, yhat), 0... | [
"unittest.main",
"scratch.utils.evaluation.metric_maep",
"numpy.array",
"scratch.utils.evaluation.metric_rmse"
] | [((542, 557), 'unittest.main', 'unittest.main', ([], {}), '()\n', (555, 557), False, 'import unittest\n'), ((190, 220), 'numpy.array', 'np.array', (['[1.2, 7.9, 4.6, 2.2]'], {}), '([1.2, 7.9, 4.6, 2.2])\n', (198, 220), True, 'import numpy as np\n'), ((236, 266), 'numpy.array', 'np.array', (['[2.1, 6.5, 4.4, 2.7]'], {})... |
import sys
import setuptools
from Cython.Build import cythonize
import numpy as np
import os
os.environ["C_INCLUDE_PATH"] = np.get_include()
print (np.get_include())
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyapprox-jjakeman",
version="0.0.1",
author="<NA... | [
"Cython.Build.cythonize",
"numpy.get_include",
"setuptools.find_packages"
] | [((124, 140), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (138, 140), True, 'import numpy as np\n'), ((148, 164), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (162, 164), True, 'import numpy as np\n'), ((593, 619), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (617, ... |
from numpy import linalg
A=[[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]
B=[-3,-32,-47,49]
C=[[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]
X=[]
for i in range(0,len(B)):
for j in range(0,len(B)):
C[j][i]=B[j]
if i>0:
C[j][i-1]=A[j][i-1]
X.append(round(linalg.det(C)/linalg.det(A),... | [
"numpy.linalg.det"
] | [((292, 305), 'numpy.linalg.det', 'linalg.det', (['C'], {}), '(C)\n', (302, 305), False, 'from numpy import linalg\n'), ((306, 319), 'numpy.linalg.det', 'linalg.det', (['A'], {}), '(A)\n', (316, 319), False, 'from numpy import linalg\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from smac.env.multiagentenv import MultiAgentEnv
import atexit
from operator import attrgetter
from copy import deepcopy
import numpy as np
import enum
import math
from absl import logging
import random
clas... | [
"numpy.random.seed",
"random.randint",
"numpy.zeros",
"numpy.random.randint",
"numpy.array",
"numpy.mean"
] | [((914, 937), 'random.randint', 'random.randint', (['(0)', '(9999)'], {}), '(0, 9999)\n', (928, 937), False, 'import random\n'), ((946, 972), 'numpy.random.seed', 'np.random.seed', (['self._seed'], {}), '(self._seed)\n', (960, 972), True, 'import numpy as np\n'), ((1030, 1067), 'numpy.array', 'np.array', (['state_numbe... |
from .base import Strategy, Transform
from summit.domain import *
from summit.utils.dataset import DataSet
import math
import numpy
from copy import deepcopy
import numpy as np
import pandas as pd
import warnings
class SNOBFIT(Strategy):
"""Stable Noisy Optimization by Branch and Fit (SNOBFIT)
SNOBFIT is de... | [
"SQSnobFit._snobsplit.snobsplit",
"numpy.sum",
"numpy.abs",
"SQSnobFit._snobqfit.snobqfit",
"numpy.maximum",
"numpy.floor",
"numpy.ones",
"numpy.isnan",
"pandas.DataFrame",
"SQSnobFit._gen_utils.diag",
"SQSnobFit._snobpoint.snobpoint",
"numpy.isfinite",
"SQSnobFit._snoblocf.snoblocf",
"num... | [((11108, 11139), 'numpy.asarray', 'np.asarray', (['bounds'], {'dtype': 'float'}), '(bounds, dtype=float)\n', (11118, 11139), True, 'import numpy as np\n'), ((18977, 18995), 'SQSnobFit._gen_utils.find', 'find', (['(f[:, 1] <= 0)'], {}), '(f[:, 1] <= 0)\n', (18981, 18995), False, 'from SQSnobFit._gen_utils import diag, ... |
from numpy import median, unique, mean
def array_detect_task(y):
'''Detects the prediction task type based on an array
containing the prediction task labels.'''
try:
y_cols = y.shape[1]
except IndexError:
y_cols = 1
y_max = y.max()
y_uniques = len(unique(y))
if y_cols > ... | [
"numpy.median",
"numpy.mean",
"numpy.unique"
] | [((292, 301), 'numpy.unique', 'unique', (['y'], {}), '(y)\n', (298, 301), False, 'from numpy import median, unique, mean\n'), ((541, 548), 'numpy.mean', 'mean', (['y'], {}), '(y)\n', (545, 548), False, 'from numpy import median, unique, mean\n'), ((552, 561), 'numpy.median', 'median', (['y'], {}), '(y)\n', (558, 561), ... |
from sklearn import svm
import numpy as np
def supportVM(X_train, X_test, y_train) :
# classifier = svm.SVC(probability=True) ## Look into this if time
classifier = svm.SVC()
## Place the training data in the MLP to train your algorithm
classifier.fit(X_train,y_train)
## This is where we test th... | [
"numpy.ndarray",
"sklearn.svm.SVC"
] | [((174, 183), 'sklearn.svm.SVC', 'svm.SVC', ([], {}), '()\n', (181, 183), False, 'from sklearn import svm\n'), ((544, 579), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(0, 2)', 'dtype': 'int'}), '(shape=(0, 2), dtype=int)\n', (554, 579), True, 'import numpy as np\n')] |
import os
import sys
sys.path.append('../')
import random
import torch
import argparse
import pickle
import numpy as np
from torch import optim
from torch import nn
from torch.nn import functional as F
import torch.utils.data as tdata
import data_utils as du
from torchtext.data import Iterator as BatchIter
from s2sa im... | [
"sys.path.append",
"data_utils.S2SSentenceDataset",
"s2sa.S2SWithA",
"utils.variable",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.manual_seed",
"torch.load",
"torch.cuda.manual_seed",
"masked_cross_entropy.masked_cross_entropy",
"data_utils.load_vocab",
"random.seed",
"torch.cuda... | [((21, 43), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (36, 43), False, 'import sys\n'), ((599, 659), 'data_utils.S2SSentenceDataset', 'du.S2SSentenceDataset', (['args.train_data', 'inp_vocab', 'out_vocab'], {}), '(args.train_data, inp_vocab, out_vocab)\n', (620, 659), True, 'import data_ut... |
import time
import warnings
from concurrent.futures.process import ProcessPoolExecutor
from typing import Tuple
import numpy as np
import pandas as pd
import torch
from sklearn.preprocessing import LabelBinarizer
from torch.utils.data import Dataset
from tqdm.auto import tqdm
from .base import BaseClassifier, Classif... | [
"pandas.DataFrame",
"torch.tensor",
"sklearn.preprocessing.LabelBinarizer",
"torch.stack",
"torch.utils.data.DataLoader",
"numpy.asarray",
"numpy.unique",
"joblib.dump",
"numpy.expand_dims",
"torch.FloatTensor",
"time.time",
"numpy.hstack",
"concurrent.futures.process.ProcessPoolExecutor",
... | [((1387, 1406), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1399, 1406), False, 'import torch\n'), ((3745, 3772), 'torch.stack', 'torch.stack', (['outputs'], {'dim': '(1)'}), '(outputs, dim=1)\n', (3756, 3772), False, 'import torch\n'), ((4074, 4096), 'numpy.asarray', 'np.asarray', (['train_data'... |
# Test APS estimation
import sys
import os
import pandas as pd
import numpy as np
import pytest
import pickle
from pathlib import Path
from sklearn.datasets import load_iris
import onnxruntime as rt
from pathlib import Path
from IVaps import estimate_aps_onnx, estimate_aps_user_defined
from IVaps.aps import _get_og_or... | [
"onnxruntime.InferenceSession",
"pathlib.Path",
"numpy.array",
"pandas.read_csv"
] | [((974, 1004), 'onnxruntime.InferenceSession', 'rt.InferenceSession', (['iris_onnx'], {}), '(iris_onnx)\n', (993, 1004), True, 'import onnxruntime as rt\n'), ((1147, 1188), 'pandas.read_csv', 'pd.read_csv', (['f"""{data_path}/iris_data.csv"""'], {}), "(f'{data_path}/iris_data.csv')\n", (1158, 1188), True, 'import panda... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.