code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import numpy as np
import torch
import torch.nn as nn
from modules.envelope import Envelope
from modules.initializers import GlorotOrthogonal
class EmbeddingBlock(nn.Module):
def __init__(self,
emb_size,
num_radial,
bessel_funcs,
cutoff,
... | [
"torch.stack",
"torch.nn.Embedding",
"torch.cat",
"modules.envelope.Envelope",
"torch.nn.Linear",
"numpy.sqrt",
"modules.initializers.GlorotOrthogonal"
] | [((598, 625), 'modules.envelope.Envelope', 'Envelope', (['envelope_exponent'], {}), '(envelope_exponent)\n', (606, 625), False, 'from modules.envelope import Envelope\n'), ((651, 689), 'torch.nn.Embedding', 'nn.Embedding', (['num_atom_types', 'emb_size'], {}), '(num_atom_types, emb_size)\n', (663, 689), True, 'import t... |
# -*- coding: utf-8 -*-
""" Various registration routines to reduce duplication. """
import numpy as np
import sksurgerycore.transforms.matrix as mt
import sksurgerysurfacematch.interfaces.rigid_registration as rr
def do_rigid_registration(reconstructed_cloud,
reference_cloud,
... | [
"numpy.transpose",
"numpy.linalg.inv",
"numpy.matmul",
"sksurgerycore.transforms.matrix.construct_rigid_transformation"
] | [((1492, 1516), 'numpy.linalg.inv', 'np.linalg.inv', (['transform'], {}), '(transform)\n', (1505, 1516), True, 'import numpy as np\n'), ((1148, 1177), 'numpy.transpose', 'np.transpose', (['reference_cloud'], {}), '(reference_cloud)\n', (1160, 1177), True, 'import numpy as np\n'), ((1628, 1721), 'sksurgerycore.transform... |
# From https://groups.google.com/forum/#!topic/networkx-discuss/FwYk0ixLDuY
# Plot weighted directed positive/negative network graph
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, Circle
import numpy as np
def draw_curvy_network(G, pos, ax, node_radius=0.02, nod... | [
"matplotlib.pyplot.show",
"networkx.MultiDiGraph",
"hips.plotting.colormaps.harvard_colors",
"matplotlib.patches.FancyArrowPatch",
"matplotlib.pyplot.axis",
"matplotlib.patches.Circle",
"numpy.sign",
"networkx.spring_layout",
"matplotlib.pyplot.gca"
] | [((2141, 2214), 'networkx.MultiDiGraph', 'nx.MultiDiGraph', (['[(1, 1), (1, 2), (2, 1), (2, 3), (3, 4), (2, 4), (3, 2)]'], {}), '([(1, 1), (1, 2), (2, 1), (2, 3), (3, 4), (2, 4), (3, 2)])\n', (2156, 2214), True, 'import networkx as nx\n'), ((2226, 2245), 'networkx.spring_layout', 'nx.spring_layout', (['G'], {}), '(G)\n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import scipy.io
# Exercise 5 | Regularized Linear Regression and Bias-Variance
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the
# exercise. You will need to complete the following funct... | [
"matplotlib.pyplot.title",
"ex5_regularized_linear_regressionand_bias_vs_variance.trainLinearReg.trainLinearReg",
"numpy.ones",
"ex5_regularized_linear_regressionand_bias_vs_variance.featureNormalize.featureNormalize",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.mean",
"unittest.main",
"matplo... | [((13315, 13330), 'unittest.main', 'unittest.main', ([], {}), '()\n', (13328, 13330), False, 'import unittest\n'), ((1535, 1548), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (1545, 1548), True, 'import matplotlib.pyplot as plt\n'), ((1557, 1596), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cha... |
###################################################################
# This implementation is based on the following papaer:
#
# <NAME> and <NAME>. Automatic data and computation
# decomposition on distributed# memory parallel computers.
# ACM Transactions on Programming Languages and Systems,
# 24(1):1–50, Jan. 2002... | [
"heterocl.for_",
"heterocl.placeholder",
"numpy.random.randint",
"heterocl.build",
"heterocl.create_schedule",
"heterocl.init",
"heterocl.scalar",
"heterocl.Int",
"heterocl.Float"
] | [((621, 630), 'heterocl.Int', 'hcl.Int', ([], {}), '()\n', (628, 630), True, 'import heterocl as hcl\n'), ((651, 666), 'heterocl.init', 'hcl.init', (['dtype'], {}), '(dtype)\n', (659, 666), True, 'import heterocl as hcl\n'), ((675, 705), 'heterocl.placeholder', 'hcl.placeholder', (['(Nx, Ny)', '"""u"""'], {}), "((Nx, N... |
# -*- coding: utf-8 -*-
# Copyright (c) CKM Analytix Corp. All rights reserved.
# Authors: <NAME> (<EMAIL>), <NAME> (<EMAIL>)
"""
Metrics for determining quality of community structure
"""
import numpy as np
from scipy.sparse import identity
__all__ = ['modularity_r', 'modularity_density', 'mula_modularity_density']... | [
"numpy.count_nonzero",
"numpy.sum",
"numpy.zeros",
"numpy.ones",
"scipy.sparse.identity",
"numpy.unique"
] | [((1202, 1237), 'numpy.zeros', 'np.zeros', (['adj_r.shape[0]'], {'dtype': 'int'}), '(adj_r.shape[0], dtype=int)\n', (1210, 1237), True, 'import numpy as np\n'), ((5019, 5043), 'scipy.sparse.identity', 'identity', ([], {'n': 'adj.shape[0]'}), '(n=adj.shape[0])\n', (5027, 5043), False, 'from scipy.sparse import identity\... |
import numpy as np
from scipy.stats import gamma as RVgamma
# the gamma distribution consider a varying shape parameter and a scale parameter equal to 1
class HMM_approxSEIR_expanded:
def __init__( self, N, beta, rho, gamma, q, eta_zero, q_r, t_star ):
self.N = N
self.beta = beta
... | [
"numpy.size",
"numpy.sum",
"numpy.zeros",
"numpy.transpose",
"numpy.ones",
"numpy.exp"
] | [((547, 563), 'numpy.zeros', 'np.zeros', (['(4, T)'], {}), '((4, T))\n', (555, 563), True, 'import numpy as np\n'), ((999, 1018), 'numpy.size', 'np.size', (['y[0, 0, :]'], {}), '(y[0, 0, :])\n', (1006, 1018), True, 'import numpy as np\n'), ((1108, 1124), 'numpy.zeros', 'np.zeros', (['[4, T]'], {}), '([4, T])\n', (1116,... |
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
from astropy.io import ascii
from pkg_resources import resource_filename
'''
Function to read in atomic line information for a given rest frame wavelength.
Or
For the line matching the ... | [
"astropy.io.ascii.read",
"numpy.abs",
"numpy.double",
"numpy.float",
"pkg_resources.resource_filename",
"numpy.int",
"numpy.str"
] | [((1244, 1275), 'numpy.double', 'np.double', (["line_str[i]['wrest']"], {}), "(line_str[i]['wrest'])\n", (1253, 1275), True, 'import numpy as np\n'), ((1286, 1315), 'numpy.float', 'np.float', (["line_str[i]['fval']"], {}), "(line_str[i]['fval'])\n", (1294, 1315), True, 'import numpy as np\n'), ((1326, 1352), 'numpy.str... |
import datetime
import warnings
from copy import copy
from types import MappingProxyType
from typing import Sequence, Callable, Mapping, Union, TypeVar, TYPE_CHECKING
import numpy as np
import pandas as pd
import sidekick as sk
from .clinical_acessor import Clinical
from .metaclass import ModelMeta
from .. import fit... | [
"numpy.arange",
"pandas.DataFrame",
"pydemic_ui.model.UIProperty",
"sidekick.property",
"numpy.isfinite",
"datetime.timedelta",
"typing.TypeVar",
"sidekick.import_later",
"datetime.datetime.now",
"pandas.concat",
"types.MappingProxyType",
"datetime.date",
"pandas.to_datetime",
"pandas.Seri... | [((704, 716), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (711, 716), False, 'from typing import Sequence, Callable, Mapping, Union, TypeVar, TYPE_CHECKING\n'), ((723, 746), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (744, 746), False, 'import datetime\n'), ((755, 798), 'datetime... |
###############################################################################
# plot_afefeh: the basic [a/Fe] vs. [Fe/H] plot for the data section
###############################################################################
import sys
import matplotlib
import numpy
from scipy import special
matplotlib.use('Agg')
f... | [
"galpy.util.bovy_plot.bovy_print",
"define_rcsample._highalpha_lowafe",
"numpy.arange",
"define_rcsample._solar_lowfeh",
"define_rcsample._highfeh_highafe",
"define_rcsample._solar_highfeh",
"define_rcsample._highalpha_lowfeh",
"define_rcsample.get_rcsample",
"define_rcsample._highfeh_lowafe",
"de... | [((297, 318), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (311, 318), False, 'import matplotlib\n'), ((466, 496), 'define_rcsample.get_rcsample', 'define_rcsample.get_rcsample', ([], {}), '()\n', (494, 496), False, 'import define_rcsample\n'), ((521, 543), 'galpy.util.bovy_plot.bovy_print', 'b... |
from .base_lot import *
import numpy as np
import os
from .units import *
#TODO get rid of get_energy
class QChem(Lot):
def run(self,geom,multiplicity):
tempfilename = 'tempQCinp'
tempfile = open(tempfilename,'w')
if self.lot_inp_file == False:
tempfile.write(' $rem\n')
... | [
"numpy.asarray",
"os.path.isfile",
"os.system"
] | [((1355, 1381), 'os.path.isfile', 'os.path.isfile', (['"""link.txt"""'], {}), "('link.txt')\n", (1369, 1381), False, 'import os\n'), ((2103, 2117), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2112, 2117), False, 'import os\n'), ((3668, 3693), 'numpy.asarray', 'np.asarray', (['tmp[state][1]'], {}), '(tmp[state]... |
from enum import Enum
import numpy as np
import tensorflow as tf
from edward1_utils import get_ancestors, get_descendants
class GenerativeMode(Enum):
UNCONDITIONED = 1 # i.e. sampling the learnt prior
CONDITIONED = 2 # i.e. sampling the posterior, with variational samples substituted
RECONSTRUCTION = ... | [
"tensorflow.abs",
"tensorflow.losses.add_loss",
"tensorflow.summary.scalar",
"tensorflow.trainable_variables",
"tensorflow.reshape",
"numpy.zeros",
"tensorflow.variable_scope",
"tensorflow.reduce_mean",
"edward1_utils.get_descendants",
"tensorflow.transpose",
"tensorflow.reduce_max",
"tensorfl... | [((20630, 20671), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""inference/loss"""', 'loss'], {}), "('inference/loss', loss)\n", (20647, 20671), True, 'import tensorflow as tf\n'), ((20676, 20721), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""inference/log_Px"""', 'log_Px'], {}), "('inference/log_Px... |
# This code calculates compressibility factor (z-factor) for natural hydrocarbon gases
# with 3 different methods. It is the outcomes of the following paper:
# <br>
# <NAME>.; <NAME>., <NAME>.; <NAME>. & <NAME>, <NAME>.
# Using artificial neural networks to estimate the Z-Factor for natural hydrocarbon gases
... | [
"numpy.abs",
"numpy.zeros",
"numpy.exp"
] | [((4319, 4335), 'numpy.zeros', 'np.zeros', (['(5, 2)'], {}), '((5, 2))\n', (4327, 4335), True, 'import numpy as np\n'), ((4441, 4457), 'numpy.zeros', 'np.zeros', (['(5, 2)'], {}), '((5, 2))\n', (4449, 4457), True, 'import numpy as np\n'), ((4567, 4584), 'numpy.zeros', 'np.zeros', (['(10, 2)'], {}), '((10, 2))\n', (4575... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 6 14:52:32 2021
@author: Patrice
Simple utility script to read tiles from drive and compile a large tensor saved as an npy file.
Use only if you have enough ram to contain all your samples at once
"""
import numpy as np
import glob
import skimage.io as io
def tic():
... | [
"numpy.float16",
"numpy.uint8",
"numpy.save",
"time.time",
"glob.glob",
"numpy.int16",
"skimage.io.imread"
] | [((448, 459), 'time.time', 'time.time', ([], {}), '()\n', (457, 459), False, 'import time\n'), ((1210, 1243), 'glob.glob', 'glob.glob', (["(class_folder + '*.tif')"], {}), "(class_folder + '*.tif')\n", (1219, 1243), False, 'import glob\n'), ((1549, 1582), 'glob.glob', 'glob.glob', (["(class_folder + '*.tif')"], {}), "(... |
"""
Modular arithmetic
"""
from collections import defaultdict
import numpy as np
class ModInt:
"""
Integers of Z/pZ
"""
def __init__(self, a, n):
self.v = a % n
self.n = n
def __eq__(a, b):
if isinstance(b, ModInt):
return not bool(a - b)
else:
... | [
"numpy.zeros",
"collections.defaultdict",
"numpy.array"
] | [((10508, 10519), 'numpy.array', 'np.array', (['P'], {}), '(P)\n', (10516, 10519), True, 'import numpy as np\n'), ((10532, 10543), 'numpy.array', 'np.array', (['Q'], {}), '(Q)\n', (10540, 10543), True, 'import numpy as np\n'), ((10556, 10580), 'numpy.zeros', 'np.zeros', (['(p + q, p + q)'], {}), '((p + q, p + q))\n', (... |
import numpy as np
class Average:
@staticmethod
def aggregate(gradients):
assert len(gradients) > 0, "Empty list of gradient to aggregate"
if len(gradients) > 1:
return np.mean(gradients, axis=0)
else:
return gradients[0]
| [
"numpy.mean"
] | [((209, 235), 'numpy.mean', 'np.mean', (['gradients'], {'axis': '(0)'}), '(gradients, axis=0)\n', (216, 235), True, 'import numpy as np\n')] |
# *******************************************************************************
#
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# *******************************************************************************
import math, numpy
from coppertop.pipe import *
from coppertop.std.linalg import tvarray
@copp... | [
"math.exp",
"numpy.std",
"numpy.mean",
"math.log",
"numpy.cov"
] | [((464, 482), 'numpy.mean', 'numpy.mean', (['ndOrPy'], {}), '(ndOrPy)\n', (474, 482), False, 'import math, numpy\n'), ((627, 649), 'numpy.std', 'numpy.std', (['ndOrPy', 'dof'], {}), '(ndOrPy, dof)\n', (636, 649), False, 'import math, numpy\n'), ((368, 380), 'numpy.cov', 'numpy.cov', (['A'], {}), '(A)\n', (377, 380), Fa... |
import numpy as np
from int_tabulated import *
def GetNDVItoDate(NDVI, Time, Start_End, bpy, DaysPerBand, CurrentBand):
#;
#;jzhu,8/9/2011,This program calculates total ndvi integration (ndvi*day) from start of season to currentband, the currentband is the dayindex of interesting day.
#
FILL=-1.... | [
"numpy.floor",
"numpy.zeros",
"numpy.ceil",
"numpy.unique"
] | [((529, 541), 'numpy.zeros', 'np.zeros', (['ny'], {}), '(ny)\n', (537, 541), True, 'import numpy as np\n'), ((1508, 1542), 'numpy.unique', 'np.unique', (['XSeg'], {'return_index': '(True)'}), '(XSeg, return_index=True)\n', (1517, 1542), True, 'import numpy as np\n'), ((703, 732), 'numpy.ceil', 'np.ceil', (["Start_End['... |
"""
Copyright 2019 Samsung SDS
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 ... | [
"brightics.common.utils.get_default_from_parameters_if_required",
"scipy.stats.mannwhitneyu",
"brightics.common.repr.BrtcReprBuilder",
"itertools.combinations",
"numpy.where",
"numpy.array",
"brightics.common.utils.check_required_parameters",
"brightics.common.groupby._function_by_group"
] | [((1165, 1229), 'brightics.common.utils.check_required_parameters', 'check_required_parameters', (['_mann_whitney_test', 'params', "['table']"], {}), "(_mann_whitney_test, params, ['table'])\n", (1190, 1229), False, 'from brightics.common.utils import check_required_parameters\n'), ((1248, 1315), 'brightics.common.util... |
import tensorflow as tf
from capsule.utils import squash
import numpy as np
layers = tf.keras.layers
models = tf.keras.models
class GammaCapsule(tf.keras.Model):
def __init__(self, in_capsules, in_dim, out_capsules, out_dim, stdev=0.2, routing_iterations=2, use_bias=True, name=''):
super(GammaCapsule,... | [
"tensorflow.nn.softmax",
"tensorflow.reduce_sum",
"numpy.log",
"tensorflow.constant_initializer",
"tensorflow.reduce_mean",
"tensorflow.tile",
"tensorflow.zeros",
"tensorflow.random_normal_initializer",
"tensorflow.shape",
"capsule.utils.squash",
"tensorflow.name_scope",
"tensorflow.norm",
"... | [((1410, 1429), 'tensorflow.norm', 'tf.norm', (['u'], {'axis': '(-1)'}), '(u, axis=-1)\n', (1417, 1429), True, 'import tensorflow as tf\n'), ((1545, 1565), 'tensorflow.expand_dims', 'tf.expand_dims', (['u', '(1)'], {}), '(u, 1)\n', (1559, 1565), True, 'import tensorflow as tf\n'), ((1579, 1599), 'tensorflow.expand_dims... |
# code-checked
# server-checked
import cv2
import numpy as np
import os
import os.path as osp
import random
import torch
from torch.utils import data
import pickle
def generate_scale_label(image, label):
f_scale = 0.5 + random.randint(0, 16)/10.0
image = cv2.resize(image, None, fx=f_scale, fy=f_scale, interp... | [
"random.randint",
"os.path.basename",
"numpy.asarray",
"cv2.copyMakeBorder",
"os.path.exists",
"cv2.imread",
"pickle.load",
"numpy.array",
"numpy.random.choice",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((266, 345), 'cv2.resize', 'cv2.resize', (['image', 'None'], {'fx': 'f_scale', 'fy': 'f_scale', 'interpolation': 'cv2.INTER_LINEAR'}), '(image, None, fx=f_scale, fy=f_scale, interpolation=cv2.INTER_LINEAR)\n', (276, 345), False, 'import cv2\n'), ((358, 443), 'cv2.resize', 'cv2.resize', (['label', 'None'], {'fx': 'f_sc... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@copyright 2017
@licence: 2-clause BSD licence
This file contains the main code for the phase-state machine
"""
import numpy as _np
import pandas as _pd
import itertools
from numba import jit
import warnings as _warnings
@jit(nopython=True, cache=True)
def _limit(a):
... | [
"numpy.abs",
"numpy.sum",
"numpy.argmax",
"numpy.empty",
"numpy.clip",
"numpy.random.normal",
"numpy.full",
"numpy.tri",
"numpy.minimum",
"numpy.asarray",
"numpy.dot",
"numpy.copyto",
"numpy.outer",
"numpy.isscalar",
"numpy.zeros",
"numpy.any",
"numba.jit",
"numpy.array",
"numpy.... | [((271, 301), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'cache': '(True)'}), '(nopython=True, cache=True)\n', (274, 301), False, 'from numba import jit\n'), ((692, 722), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'cache': '(True)'}), '(nopython=True, cache=True)\n', (695, 722), False, 'from numba import jit\... |
# Copyright (c) 2016 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 applic... | [
"topology.Topology",
"tarfile.TarFile",
"paddle.proto.ParameterConfig_pb2.ParameterConfig",
"numpy.zeros",
"tarfile.TarInfo",
"struct.pack",
"collections.OrderedDict",
"cStringIO.StringIO",
"numpy.ndarray"
] | [((1005, 1021), 'topology.Topology', 'Topology', (['layers'], {}), '(layers)\n', (1013, 1021), False, 'from topology import Topology\n'), ((2864, 2877), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2875, 2877), False, 'from collections import OrderedDict\n'), ((10804, 10840), 'tarfile.TarFile', 'tarfile... |
import numpy as np
import imageio
import os
AVAILABLE_IMAGES = ['barbara']
def _add_noise(img, sigma):
noise = np.random.normal(scale=sigma,
size=img.shape).astype(img.dtype)
return img + noise
def example_image(img_name, noise_std=0):
imgf = os.path.join('sparselandtools'... | [
"imageio.imread",
"os.path.join",
"numpy.random.normal"
] | [((290, 366), 'os.path.join', 'os.path.join', (['"""sparselandtools"""', '"""applications"""', '"""assets"""', "(img_name + '.png')"], {}), "('sparselandtools', 'applications', 'assets', img_name + '.png')\n", (302, 366), False, 'import os\n'), ((118, 163), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'sig... |
import os
import sys
import argparse
import numpy as np
import theano.tensor as T
homepath = os.path.join('..', '..')
if not homepath in sys.path:
sys.path.insert(0, homepath)
from dlearn.models.layer import FullConnLayer, ConvPoolLayer
from dlearn.models.nnet import NeuralNet
from dlearn.utils import actfuncs, ... | [
"argparse.ArgumentParser",
"theano.tensor.tensor4",
"dlearn.utils.serialize.load_data",
"dlearn.optimization.sgd.train",
"dlearn.utils.costfuncs.binxent",
"sys.path.insert",
"dlearn.utils.costfuncs.binerr",
"dlearn.models.layer.ConvPoolLayer",
"numpy.prod",
"dlearn.utils.actfuncs.tanh",
"dlearn.... | [((94, 118), 'os.path.join', 'os.path.join', (['""".."""', '""".."""'], {}), "('..', '..')\n", (106, 118), False, 'import os\n'), ((868, 912), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desctxt'}), '(description=desctxt)\n', (891, 912), False, 'import argparse\n'), ((153, 181), 'sys.pat... |
import numpy as np
from common import numerical_gradient, softmax, cross_entropy_error
from collections import OrderedDict
class Relu:
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def... | [
"numpy.sum",
"numpy.abs",
"numpy.argmax",
"common.numerical_gradient",
"numpy.random.randn",
"common.softmax",
"numpy.zeros",
"dataset.mnist.load_mnist",
"numpy.random.choice",
"collections.OrderedDict",
"numpy.dot",
"common.cross_entropy_error"
] | [((3510, 3556), 'dataset.mnist.load_mnist', 'load_mnist', ([], {'normalize': '(True)', 'one_hot_label': '(True)'}), '(normalize=True, one_hot_label=True)\n', (3520, 3556), False, 'from dataset.mnist import load_mnist\n'), ((4487, 4527), 'numpy.random.choice', 'np.random.choice', (['train_size', 'batch_size'], {}), '(tr... |
#!/usr/bin/env python
import numpy as np
from scipy.stats import norm
def bachelier(So, K, sigma, T, option_type):
'''
Calculate European option price using Bachelier model:
dSt = sigma * S0 * dWt
St = S0*(1 + sigma*Wt)
Parameter
---------
So: float
price of underlying... | [
"scipy.stats.norm.cdf",
"scipy.stats.norm.pdf",
"numpy.log",
"numpy.sqrt"
] | [((748, 758), 'numpy.sqrt', 'np.sqrt', (['T'], {}), '(T)\n', (755, 758), True, 'import numpy as np\n'), ((820, 844), 'numpy.sqrt', 'np.sqrt', (['(T / (2 * np.pi))'], {}), '(T / (2 * np.pi))\n', (827, 844), True, 'import numpy as np\n'), ((2341, 2355), 'numpy.log', 'np.log', (['(So / K)'], {}), '(So / K)\n', (2347, 2355... |
from pydlm import dlm, trend, seasonality
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
# A linear trend
linear_trend = trend(degree=1, discount=1, name='linear_trend', w=10)
# A seasonality
time_series = []
for i in range(10):
if i == 0:
x_sim = np.random.normal(0,1,1)
... | [
"matplotlib.pyplot.show",
"pydlm.trend",
"numpy.random.RandomState",
"pykalman.KalmanFilter",
"numpy.percentile",
"numpy.array",
"numpy.random.normal",
"pydlm.dlm"
] | [((155, 209), 'pydlm.trend', 'trend', ([], {'degree': '(1)', 'discount': '(1)', 'name': '"""linear_trend"""', 'w': '(10)'}), "(degree=1, discount=1, name='linear_trend', w=10)\n", (160, 209), False, 'from pydlm import dlm, trend, seasonality\n'), ((441, 462), 'numpy.array', 'np.array', (['time_series'], {}), '(time_ser... |
""" Implementation of :py:class:`Dataset` object. A folder containing a set of subjects with CT and RS in dicom format
is converted into nii format. A new folder is created keeping the same organization.
"""
import os
import numpy as np
from dcmrtstruct2nii import dcmrtstruct2nii, list_rt_structs
class Dataset:
... | [
"dcmrtstruct2nii.list_rt_structs",
"dcmrtstruct2nii.dcmrtstruct2nii",
"os.path.basename",
"os.path.dirname",
"numpy.array",
"os.path.splitext",
"os.path.join",
"os.listdir",
"numpy.in1d"
] | [((1215, 1244), 'os.path.basename', 'os.path.basename', (['export_path'], {}), '(export_path)\n', (1231, 1244), False, 'import os\n'), ((1298, 1324), 'os.path.dirname', 'os.path.dirname', (['self.path'], {}), '(self.path)\n', (1313, 1324), False, 'import os\n'), ((2406, 2443), 'dcmrtstruct2nii.list_rt_structs', 'list_r... |
import numpy as numpy
a = numpy.array([5,2,6,2,7,5,6,8,2,9])
print ('First array:')
print(a)
print('\n')
print('Unique values of first array:')
u = numpy.unique(a)
print(u)
print('\n')
print('Unique array and indices array:')
u, indices = numpy.unique(a, return_index = True)
print (indices)
print('\n')
print('We ca... | [
"numpy.array",
"numpy.unique"
] | [((26, 69), 'numpy.array', 'numpy.array', (['[5, 2, 6, 2, 7, 5, 6, 8, 2, 9]'], {}), '([5, 2, 6, 2, 7, 5, 6, 8, 2, 9])\n', (37, 69), True, 'import numpy as numpy\n'), ((150, 165), 'numpy.unique', 'numpy.unique', (['a'], {}), '(a)\n', (162, 165), True, 'import numpy as numpy\n'), ((242, 276), 'numpy.unique', 'numpy.uniqu... |
import os
import numpy
import pandas
from skimage import io
def read_ids_from_csv(csv_file):
""" Reads a column named 'ID' from csv_file. This function was
created to make sure basic I/O works in unit testing.
"""
csv = pandas.read_csv(csv_file)
return csv.ID
def read_hpa_image(image_id, roo... | [
"pandas.read_csv",
"os.path.join",
"skimage.io.imread",
"numpy.dstack"
] | [((242, 267), 'pandas.read_csv', 'pandas.read_csv', (['csv_file'], {}), '(csv_file)\n', (257, 267), False, 'import pandas\n'), ((480, 512), 'os.path.join', 'os.path.join', (['root_dir', 'image_id'], {}), '(root_dir, image_id)\n', (492, 512), False, 'import os\n'), ((681, 700), 'numpy.dstack', 'numpy.dstack', (['image']... |
from matplotlib import pyplot as plt
import pickle
import numpy as np
import os,sys
'''
results = []
for i in range(10):
with open(f'/home/yiran/pc_mapping/arena-v2/examples/bc_saved_models/refactor_success_max_mine/run{i}/test_result.npy', 'rb') as f:
result_i = pickle.load(f)
result_number = [v for (k... | [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((556, 575), 'numpy.arange', 'np.arange', (['(1)', '(21)', '(2)'], {}), '(1, 21, 2)\n', (565, 575), True, 'import numpy as np\n'), ((1806, 1835), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""number of coins"""'], {}), "('number of coins')\n", (1816, 1835), True, 'from matplotlib import pyplot as plt\n'), ((1836, 18... |
import numpy as np
import pandas as pd
def complexity_hjorth(signal):
"""Hjorth's Complexity and Parameters
Hjorth Parameters are indicators of statistical properties used in signal processing in the
time domain introduced by Hjorth (1970). The parameters are activity, mobility, and complexity.
Neuro... | [
"numpy.diff",
"numpy.var",
"numpy.sqrt"
] | [((2112, 2127), 'numpy.diff', 'np.diff', (['signal'], {}), '(signal)\n', (2119, 2127), True, 'import numpy as np\n'), ((2138, 2149), 'numpy.diff', 'np.diff', (['dx'], {}), '(dx)\n', (2145, 2149), True, 'import numpy as np\n'), ((2208, 2222), 'numpy.var', 'np.var', (['signal'], {}), '(signal)\n', (2214, 2222), True, 'im... |
import numpy as np
import warnings
def remove_base(seq, base, tolerance=1e-4):
"""
Functionality: Remove x from (x \sqcup z)
Since there might be some float errors, I allow for a mismatch of the time_stamps between
two seqs no larger than a threshold.
The threshold value: tolerance * max_time_stam... | [
"numpy.abs",
"numpy.empty",
"numpy.where",
"pprint.pprint",
"warnings.warn"
] | [((611, 650), 'numpy.empty', 'np.empty', ([], {'shape': '[n_seq]', 'dtype': 'np.int64'}), '(shape=[n_seq], dtype=np.int64)\n', (619, 650), True, 'import numpy as np\n'), ((673, 714), 'numpy.empty', 'np.empty', ([], {'shape': '[n_seq]', 'dtype': 'np.float32'}), '(shape=[n_seq], dtype=np.float32)\n', (681, 714), True, 'i... |
import cv2
# cap = cv2.VideoCapture(0)
cap = cv2.VideoCapture('../datasets/opencv/fish.mp4')
while True:
_ret, frame = cap.read()
frame = cv2.resize(frame, (500,400))
cv2.imshow('opencv camera', frame)
k = cv2.waitKey(1) #1msec 대기
if k==27 or k==13 : break
cap.release()
cv2.destroyAllWindows()
imp... | [
"cv2.waitKey",
"cv2.cvtColor",
"cv2.imshow",
"numpy.zeros",
"cv2.VideoCapture",
"cv2.destroyAllWindows",
"cv2.resize"
] | [((45, 92), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""../datasets/opencv/fish.mp4"""'], {}), "('../datasets/opencv/fish.mp4')\n", (61, 92), False, 'import cv2\n'), ((292, 315), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (313, 315), False, 'import cv2\n'), ((775, 798), 'cv2.destroyAllWindows... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 13 19:00:40 2016
@author: sebalander
"""
from numpy import zeros, sqrt, array, tan, arctan, prod, cos
from cv2 import Rodrigues
from lmfit import minimize, Parameters
#from calibration import calibrator
#xypToZplane = calibrator.xypToZplane
#
## %% ========== ========== ... | [
"numpy.arctan",
"numpy.tan",
"numpy.cos"
] | [((1758, 1768), 'numpy.arctan', 'arctan', (['rh'], {}), '(rh)\n', (1764, 1768), False, 'from numpy import zeros, sqrt, array, tan, arctan, prod, cos\n'), ((1781, 1792), 'numpy.tan', 'tan', (['(th / 2)'], {}), '(th / 2)\n', (1784, 1792), False, 'from numpy import zeros, sqrt, array, tan, arctan, prod, cos\n'), ((4240, 4... |
"""
plot.py defines functions for plotting phase diagrams of complex
coacervate liquid separation.
"""
# standard libraries
import matplotlib.pyplot as plt
from matplotlib import cm # colormap
import numpy as np
import pandas as pd
# custom libraries
import pe
import salt as nacl
# plotting libraries
import plotly.... | [
"bokeh.models.ColumnDataSource",
"pe.get_beads_2_M",
"numpy.abs",
"numpy.argmax",
"salt.extract_df_mu_data",
"numpy.argmin",
"matplotlib.pyplot.figure",
"salt.fixed_conc",
"numpy.unique",
"pandas.DataFrame",
"numpy.copy",
"salt.binodal_vary_f_data",
"pe.lB_2_T",
"numpy.max",
"bokeh.plott... | [((5262, 5274), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5272, 5274), True, 'import matplotlib.pyplot as plt\n'), ((9297, 9315), 'numpy.copy', 'np.copy', (['left_list'], {}), '(left_list)\n', (9304, 9315), True, 'import numpy as np\n'), ((9332, 9351), 'numpy.copy', 'np.copy', (['right_list'], {}), '... |
import typing
import sys
import numpy as np
import numba as nb
@nb.njit
def csgraph_to_directed(g: np.ndarray) -> np.ndarray:
m = len(g)
g = np.vstack((g, g))
g[m:, :2] = g[m:, 1::-1]
return g
@nb.njit
def sort_csgraph(
n: int,
g: np.ndarray,
) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarra... | [
"numpy.full",
"sys.stdin.read",
"numpy.empty",
"numba.njit",
"numpy.zeros",
"numpy.argsort",
"numpy.arange",
"numpy.vstack"
] | [((2746, 2793), 'numba.njit', 'nb.njit', (['(nb.i8[:, :], nb.i8[:, :])'], {'cache': '(True)'}), '((nb.i8[:, :], nb.i8[:, :]), cache=True)\n', (2753, 2793), True, 'import numba as nb\n'), ((154, 171), 'numpy.vstack', 'np.vstack', (['(g, g)'], {}), '((g, g))\n', (163, 171), True, 'import numpy as np\n'), ((337, 374), 'nu... |
"""
=============================================
Multiclass Classification with NumPy and TMVA
=============================================
"""
from array import array
import numpy as np
from numpy.random import RandomState
from root_numpy.tmva import add_classification_events, evaluate_reader
from root_numpy import ... | [
"matplotlib.pyplot.title",
"numpy.argmax",
"numpy.ones",
"ROOT.TFile",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.contourf",
"numpy.arange",
"ROOT.TMVA.DataLoader",
"numpy.diag",
"matplotlib.pyplot.tight_layout",
"root_numpy.tmva.add_classification_events",
... | [((401, 424), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (414, 424), True, 'import matplotlib.pyplot as plt\n'), ((431, 446), 'numpy.random.RandomState', 'RandomState', (['(42)'], {}), '(42)\n', (442, 446), False, 'from numpy.random import RandomState\n'), ((735, 778), 'nump... |
from drl_negotiation.scenario import BaseScenario
from drl_negotiation.core import TrainWorld, MySCML2020Agent
from drl_negotiation.myagent import MyComponentsBasedAgent
from drl_negotiation.hyperparameters import *
from negmas.helpers import get_class
from scml.scml2020 import (
DecentralizingAgent,
... | [
"scml.scml2020.SCML2020World.generate",
"scml.scml2020.is_system_agent",
"drl_negotiation.core.TrainWorld",
"numpy.array",
"negmas.helpers.get_class"
] | [((1138, 1183), 'drl_negotiation.core.TrainWorld', 'TrainWorld', ([], {'configuration': 'world_configuration'}), '(configuration=world_configuration)\n', (1148, 1183), False, 'from drl_negotiation.core import TrainWorld, MySCML2020Agent\n'), ((1599, 1694), 'scml.scml2020.SCML2020World.generate', 'SCML2020World.generate... |
# Copyright 2017 The TensorFlow Lattice 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 a... | [
"tensorflow.python.platform.test.main",
"tensorflow_lattice.python.estimators.hparams.CalibratedEtlHParams",
"tensorflow.python.feature_column.feature_column_lib.numeric_column",
"tensorflow_lattice.python.lib.test_data.TestData",
"tensorflow_lattice.python.estimators.calibrated_etl.calibrated_etl_classifie... | [((14983, 14994), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (14992, 14994), False, 'from tensorflow.python.platform import test\n'), ((1306, 1359), 'tensorflow_lattice.python.estimators.hparams.CalibratedEtlHParams', 'tfl_hparams.CalibratedEtlHParams', ([], {'feature_names': "['x']"}), "(fe... |
from models import PatchCore
from save_utils import saveModelPath
import numpy
import torch
import warnings
from torch import tensor
from torchvision import transforms
import json
import numpy
from PIL import Image, ImageFilter
import os
from torch.utils.data import DataLoader,TensorDataset
warnings.filterwarnings("... | [
"json.dumps",
"torch.utils.data.TensorDataset",
"torchvision.transforms.Normalize",
"os.path.join",
"torch.utils.data.DataLoader",
"torchvision.transforms.Compose",
"torchvision.transforms.CenterCrop",
"PIL.ImageFilter.MedianFilter",
"torch.from_numpy",
"torchvision.transforms.Resize",
"save_uti... | [((295, 328), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (318, 328), False, 'import warnings\n'), ((923, 982), 'models.PatchCore', 'PatchCore', ([], {'f_coreset': 'f_coreset', 'backbone_name': 'backbone_name'}), '(f_coreset=f_coreset, backbone_name=backbone_name)\n', (... |
import cv2
import numpy as np
from .fs_access import FSAccess
def read_image_file(fname_url):
with FSAccess(fname_url, True) as image_f:
img_buf = image_f.read()
np_arr = np.frombuffer(img_buf, np.uint8)
img = cv2.imdecode(np_arr, 0)
return img
def write_image_file(fname_url, img):
... | [
"numpy.frombuffer",
"cv2.imdecode",
"numpy.getbuffer"
] | [((330, 347), 'numpy.getbuffer', 'np.getbuffer', (['img'], {}), '(img)\n', (342, 347), True, 'import numpy as np\n'), ((192, 224), 'numpy.frombuffer', 'np.frombuffer', (['img_buf', 'np.uint8'], {}), '(img_buf, np.uint8)\n', (205, 224), True, 'import numpy as np\n'), ((239, 262), 'cv2.imdecode', 'cv2.imdecode', (['np_ar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 14:03:30 2020
@author: acpotter
"""
#%% -- IMPORTS --
import sys
sys.path.append("..") # import one subdirectory up in files
# external packages
import numpy as np
import qiskit as qk
import networkx as nx
#import tenpy
# custom things
#import... | [
"sys.path.append",
"numpy.moveaxis",
"qiskit.QuantumCircuit",
"qiskit.execute",
"networkx.topological_sort",
"networkx.algorithms.dag.is_directed_acyclic_graph",
"networkx.DiGraph",
"qiskit.Aer.get_backend"
] | [((140, 161), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (155, 161), False, 'import sys\n'), ((1513, 1552), 'qiskit.Aer.get_backend', 'qk.Aer.get_backend', (['"""unitary_simulator"""'], {}), "('unitary_simulator')\n", (1531, 1552), True, 'import qiskit as qk\n'), ((6841, 6880), 'qiskit.Aer.ge... |
"""
Script that trains Tensorflow singletask models on QM7 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import deepchem as dc
import numpy as np
from qm7_datasets import load_qm7b_from_mat
np.random.seed(123)
qm7_tasks, datasets, ... | [
"numpy.random.seed",
"deepchem.trans.CoulombFitTransformer",
"qm7_datasets.load_qm7b_from_mat",
"deepchem.metrics.Metric",
"numpy.sqrt"
] | [((279, 298), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (293, 298), True, 'import numpy as np\n'), ((335, 373), 'qm7_datasets.load_qm7b_from_mat', 'load_qm7b_from_mat', ([], {'split': '"""stratified"""'}), "(split='stratified')\n", (353, 373), False, 'from qm7_datasets import load_qm7b_from_mat... |
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import QVBoxLayout,QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
import numpy as np
... | [
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg",
"PyQt5.QtWidgets.QVBoxLayout",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.backends.backend_qt5agg.NavigationToolbar2QT"
] | [((584, 596), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (594, 596), True, 'import matplotlib.pyplot as plt\n'), ((619, 644), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg', 'FigureCanvas', (['self.figure'], {}), '(self.figure)\n', (631, 644), True, 'from matplotlib.backends.backend_qt5agg impo... |
"""Script containing the abstract policy class."""
import numpy as np
import tensorflow as tf
from hbaselines.utils.tf_util import get_trainable_vars
from hbaselines.utils.tf_util import get_target_updates
class ActorCriticPolicy(object):
"""Base Actor Critic Policy.
Attributes
----------
sess : tf.... | [
"hbaselines.utils.tf_util.get_trainable_vars",
"tensorflow.constant",
"numpy.concatenate"
] | [((7880, 7921), 'numpy.concatenate', 'np.concatenate', (['(obs, context)'], {'axis': 'axis'}), '((obs, context), axis=axis)\n', (7894, 7921), True, 'import numpy as np\n'), ((9920, 9951), 'hbaselines.utils.tf_util.get_trainable_vars', 'get_trainable_vars', (['model_scope'], {}), '(model_scope)\n', (9938, 9951), False, ... |
import numpy as np
import opt_prob
import scipy.optimize
# -- problem setup
name = '2.4 GOLDPR'
problem = opt_prob.Cons(name)
def cns(x):
g = -1.0*np.array(problem.cns(x))
return g.tolist()
# -- start optimization
x0 = ((np.array(problem.lb) + np.array(problem.ub)) / 2.0).tolist()
bounds = []
for lb_i, ub... | [
"numpy.array",
"opt_prob.Cons"
] | [((108, 127), 'opt_prob.Cons', 'opt_prob.Cons', (['name'], {}), '(name)\n', (121, 127), False, 'import opt_prob\n'), ((234, 254), 'numpy.array', 'np.array', (['problem.lb'], {}), '(problem.lb)\n', (242, 254), True, 'import numpy as np\n'), ((257, 277), 'numpy.array', 'np.array', (['problem.ub'], {}), '(problem.ub)\n', ... |
"""Initialisation procedures."""
# pylint: disable=import-outside-toplevel
import numpy as np
import scipy.integrate as sci
import probnum.filtsmooth as pnfs
import probnum.statespace as pnss
from probnum import randvars
# In the initialisation-via-RK function below, this value is added to the marginal stds of the ... | [
"jax.config.config.update",
"jax.numpy.array",
"jax.numpy.ones_like",
"jax.numpy.reshape",
"jax.experimental.jet.jet",
"probnum.randvars.Normal",
"jax.numpy.concatenate",
"numpy.asarray",
"scipy.integrate.solve_ivp",
"numpy.zeros",
"numpy.arange",
"jax.numpy.ravel",
"numpy.diag",
"probnum.... | [((3620, 3634), 'numpy.asarray', 'np.asarray', (['y0'], {}), '(y0)\n', (3630, 3634), True, 'import numpy as np\n'), ((3762, 3779), 'numpy.zeros', 'np.zeros', (['ode_dim'], {}), '(ode_dim)\n', (3770, 3779), True, 'import numpy as np\n'), ((3796, 3824), 'numpy.zeros', 'np.zeros', (['(ode_dim, ode_dim)'], {}), '((ode_dim,... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 12:05:08 2018
@author: Alexandre
"""
###############################################################################
import numpy as np
###############################################################################
from pyro.dynamic import pendulum
from pyro.control ... | [
"pyro.control.nonlinear.ComputedTorqueController",
"pyro.control.nonlinear.SlidingModeController",
"pyro.analysis.simulation.CLosedLoopSimulation",
"pyro.control.robotcontrollers.JointPID",
"pyro.dynamic.pendulum.SinglePendulum",
"pyro.planning.plan.load_trajectory",
"numpy.array",
"pyro.planning.plan... | [((537, 562), 'pyro.dynamic.pendulum.SinglePendulum', 'pendulum.SinglePendulum', ([], {}), '()\n', (560, 562), False, 'from pyro.dynamic import pendulum\n'), ((666, 697), 'pyro.planning.plan.load_trajectory', 'plan.load_trajectory', (['"""rrt.npy"""'], {}), "('rrt.npy')\n", (686, 697), False, 'from pyro.planning import... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 <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, ... | [
"sys.stdout.write",
"paddle.v2.layer.mse_cost",
"sys.stdout.flush",
"data_provider.create_reader",
"paddle.v2.activation.Sigmoid",
"data_provider.fetch_testingset",
"paddle.v2.activation.Relu",
"paddle.v2.parameters.create",
"paddle.v2.init",
"numpy.save",
"paddle.v2.attr.Param",
"paddle.v2.da... | [((2494, 2537), 'paddle.v2.init', 'paddle.init', ([], {'use_gpu': '(False)', 'trainer_count': '(1)'}), '(use_gpu=False, trainer_count=1)\n', (2505, 2537), True, 'import paddle.v2 as paddle\n'), ((1207, 1258), 'paddle.v2.attr.Param', 'paddle.attr.Param', ([], {'initial_std': '(0.01)', 'initial_mean': '(0)'}), '(initial_... |
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
IMAGE_SIZE = 64
#按照指定图像大小调整尺寸
def resize_image(image, height = IMAGE_SIZE, width = IMAGE_SIZE):
top, bottom, left, right = (0, 0, 0, 0)
#获取图像尺寸
h, w, _ = image.shape
#对于长宽不相等的图片,找到最长的一边
longest_edge = max(h, w)
#计算短边需要增加多上像素宽度使其与长边等长
if h < long... | [
"os.path.isdir",
"numpy.array",
"os.listdir",
"os.path.join"
] | [((798, 819), 'os.listdir', 'os.listdir', (['path_name'], {}), '(path_name)\n', (808, 819), False, 'import os\n'), ((1350, 1366), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (1358, 1366), True, 'import numpy as np\n'), ((891, 915), 'os.path.isdir', 'os.path.isdir', (['full_path'], {}), '(full_path)\n', (... |
"""
Regularizer class for that also supports GPU code
<NAME> <EMAIL>
<NAME> <EMAIL>
March 04, 2018
"""
import arrayfire as af
import numpy as np
from opticaltomography import settings
np_complex_datatype = settings.np_complex_datatype
np_float_datatype = settings.np_float_datatype
af_float_datatype = sett... | [
"arrayfire.to_array",
"arrayfire.abs",
"numpy.abs",
"arrayfire.sum",
"arrayfire.shift",
"arrayfire.imag",
"numpy.roll",
"numpy.zeros",
"numpy.prod",
"numpy.imag",
"numpy.array",
"numpy.real",
"numpy.sign",
"arrayfire.sign",
"arrayfire.real",
"arrayfire.constant"
] | [((8794, 8879), 'arrayfire.constant', 'af.constant', (['(0.0)', 'x.shape[0]', 'x.shape[1]', 'x.shape[2]', '(3)'], {'dtype': 'af_float_datatype'}), '(0.0, x.shape[0], x.shape[1], x.shape[2], 3, dtype=af_float_datatype\n )\n', (8805, 8879), True, 'import arrayfire as af\n'), ((8892, 8977), 'arrayfire.constant', 'af.co... |
# <NAME>
# PandS project 2020
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Import data as pandas dataframe
iris_data = pd.read_csv('iris.data', header=None)
# assign column headers
iris_data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'sp... | [
"pandas.DataFrame",
"matplotlib.pyplot.title",
"seaborn.set",
"seaborn.lmplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"pandas.read_csv",
"matplotlib.pyplot.close",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.figure",
"numpy.arange",
"seaborn.pairplot",
"matplotlib.pyplot.yl... | [((171, 208), 'pandas.read_csv', 'pd.read_csv', (['"""iris.data"""'], {'header': 'None'}), "('iris.data', header=None)\n", (182, 208), True, 'import pandas as pd\n'), ((849, 893), 'pandas.DataFrame', 'pd.DataFrame', (["{'Species': str_summary[:, 0]}"], {}), "({'Species': str_summary[:, 0]})\n", (861, 893), True, 'impor... |
# <NAME> - github.com/2b-t (2022)
# @file utilities_test.py
# @brief Different testing routines for utility functions for accuracy calculation and file import and export
import numpy as np
from parameterized import parameterized
from typing import Tuple
import unittest
from src.utilities import AccX, IO
class Test... | [
"unittest.main",
"src.utilities.IO._str_comma",
"src.utilities.AccX.compute",
"numpy.zeros",
"numpy.ones",
"src.utilities.IO.normalise_image",
"parameterized.parameterized.expand",
"numpy.min",
"numpy.max"
] | [((509, 543), 'parameterized.parameterized.expand', 'parameterized.expand', (['_disparities'], {}), '(_disparities)\n', (529, 543), False, 'from parameterized import parameterized\n'), ((1222, 1256), 'parameterized.parameterized.expand', 'parameterized.expand', (['_disparities'], {}), '(_disparities)\n', (1242, 1256), ... |
import Bio.SeqUtils.ProtParam
import os
import ASAP.FeatureExtraction as extract
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Chothia numbering definition for CDR regions
CHOTHIA_CDR = {'L': {'1': [24, 34], '2': [50, 56], '3': [89, 97]}, 'H':{'1': [26, 32], '2': [52, 56], '3': [95, 102]}}
c... | [
"pandas.DataFrame",
"ASAP.FeatureExtraction.MultiHotMotif",
"ASAP.FeatureExtraction.GetOneHotGerm",
"ASAP.FeatureExtraction.GetOneHotCanon",
"ASAP.FeatureExtraction.GetFeatureVectors",
"numpy.array",
"ASAP.FeatureExtraction.GetCDRH3",
"collections.Counter",
"ASAP.FeatureExtraction.GetOneHotPI",
"A... | [((728, 788), 'ASAP.FeatureExtraction.ReadAminoNumGerm', 'extract.ReadAminoNumGerm', (['targeting_direct', 'reference_direct'], {}), '(targeting_direct, reference_direct)\n', (752, 788), True, 'import ASAP.FeatureExtraction as extract\n'), ((7133, 7189), 'pandas.DataFrame', 'pd.DataFrame', (['AllFeatureVectors'], {'col... |
import numpy as np
import tensorflow as tf
from rl.losses import QLearningLoss
from rl.algorithms import OnlineRLAlgorithm
from rl.runner import *
from rl.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer
from rl import util
from deeplearning.layers import Adam, RunningNorm
from deeplearning.schedules import L... | [
"numpy.abs",
"numpy.asarray",
"deeplearning.logger.dumpkvs",
"deeplearning.schedules.LinearSchedule",
"time.time",
"deeplearning.logger.logkv",
"deeplearning.layers.Adam",
"tensorflow.assign",
"numpy.array",
"rl.replay_buffer.PrioritizedReplayBuffer",
"rl.replay_buffer.ReplayBuffer",
"collecti... | [((2065, 2082), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (2070, 2082), False, 'from collections import deque\n'), ((2240, 2304), 'deeplearning.schedules.LinearSchedule', 'LinearSchedule', (['self.args.t_beta_max', '(1.0)', 'self.args.replay_beta'], {}), '(self.args.t_beta_max, 1.0, sel... |
import gi
import numpy.testing
import pint
import pyRestTable
import pytest
gi.require_version("Hkl", "5.0")
# NOTE: MUST call gi.require_version() BEFORE import hkl
from hkl.calc import A_KEV
from hkl.diffract import Constraint
from hkl import SimulatedE4CV
class Fourc(SimulatedE4CV):
...
@pytest.fixture(scop... | [
"gi.require_version",
"pytest.fixture",
"numpy.arcsin",
"ophyd.Component",
"hkl.diffract.Constraint",
"pytest.approx",
"pint.Quantity"
] | [((77, 109), 'gi.require_version', 'gi.require_version', (['"""Hkl"""', '"""5.0"""'], {}), "('Hkl', '5.0')\n", (95, 109), False, 'import gi\n'), ((301, 333), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (315, 333), False, 'import pytest\n'), ((5226, 5257), 'pytest.appro... |
from itertools import groupby
import numpy as np
def best_path(mat: np.ndarray, labels: str) -> str:
"""Best path (greedy) decoder.
Take best-scoring character per time-step, then remove repeated characters and CTC blank characters.
See dissertation of Graves, p63.
Args:
mat: Output of neur... | [
"itertools.groupby",
"numpy.argmax"
] | [((554, 576), 'numpy.argmax', 'np.argmax', (['mat'], {'axis': '(1)'}), '(mat, axis=1)\n', (563, 576), True, 'import numpy as np\n'), ((747, 773), 'itertools.groupby', 'groupby', (['best_path_indices'], {}), '(best_path_indices)\n', (754, 773), False, 'from itertools import groupby\n')] |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# use all cores
#import os
#os.system("taskset -p 0xff %d" % os.getpid())
pd.options.mode.chained_assignment = None # deactivating slicing warns
def load_seattle_speed_matrix():
""" Loads the whole Seattle `speed_matrix_2015` into memory.
... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"numpy.abs",
"numpy.power",
"numpy.append",
"numpy.mean",
"pandas.to_datetime",
"pandas.read_pickle",
"pandas.concat"
] | [((580, 608), 'pandas.read_pickle', 'pd.read_pickle', (['speed_matrix'], {}), '(speed_matrix)\n', (594, 608), True, 'import pandas as pd\n'), ((624, 673), 'pandas.to_datetime', 'pd.to_datetime', (['df.index'], {'format': '"""%Y-%m-%d %H:%M"""'}), "(df.index, format='%Y-%m-%d %H:%M')\n", (638, 673), True, 'import pandas... |
""" This module contains a class that describes an object in the world. """
import numpy as np
class Object:
"""
Object is a simple wireframe composed of multiple points connected by
lines that can be drawn in the viewport.
"""
TOTAL_OBJECTS = -1
def __init__(self, points=None, name=... | [
"numpy.divide",
"numpy.multiply",
"numpy.abs",
"numpy.average",
"numpy.subtract",
"numpy.sin",
"numpy.array",
"numpy.linalg.inv",
"numpy.arange",
"numpy.cos",
"numpy.dot",
"numpy.add"
] | [((1601, 1698), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [-center[0], -center[1], -center\n [2], 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [-center[0], -center[1],\n -center[2], 1]])\n', (1609, 1698), True, 'import numpy as np\n'), ((6089, 6117), 'numpy.divide', 'np.... |
"""Utils functions."""
from copy import deepcopy
import mne
import numpy as np
from ._logs import logger
# TODO: Add test for this. Also compare speed with latest version of numpy.
# Also compared speed with a numba implementation.
def _corr_vectors(A, B, axis=0):
# based on:
# https://github.com/wmvanvlie... | [
"copy.deepcopy",
"numpy.sum",
"numpy.nan_to_num",
"numpy.seterr",
"numpy.allclose",
"mne.channel_type",
"mne.create_info",
"numpy.mean",
"numpy.linalg.norm"
] | [((1399, 1443), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (1408, 1443), True, 'import numpy as np\n'), ((1524, 1553), 'numpy.linalg.norm', 'np.linalg.norm', (['An'], {'axis': 'axis'}), '(An, axis=axis)\n', (1538, 1553), True, 'impo... |
import numpy as numpy
a = numpy.arange(150)
# a[0::2] *= numpy.sqrt(2)/2.0 * (numpy.cos(2) - numpy.sin(2))
a[0::2] *= 2
print(a) | [
"numpy.arange"
] | [((26, 43), 'numpy.arange', 'numpy.arange', (['(150)'], {}), '(150)\n', (38, 43), True, 'import numpy as numpy\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is pytest for twinpy.properties.hexagonal.
"""
from copy import deepcopy
import numpy as np
from twinpy.properties import hexagonal
a = 2.93
c = 4.65
def test_check_hexagonal_lattice(ti_cell_wyckoff_c):
"""
Check check_hexagonal_lattice.
"""
he... | [
"twinpy.properties.hexagonal.HexagonalPlane",
"twinpy.properties.hexagonal.convert_direction_from_three_to_four",
"copy.deepcopy",
"twinpy.properties.hexagonal.convert_direction_from_four_to_three",
"twinpy.properties.hexagonal.check_cell_is_hcp",
"twinpy.properties.hexagonal.HexagonalDirection",
"twinp... | [((363, 423), 'twinpy.properties.hexagonal.check_hexagonal_lattice', 'hexagonal.check_hexagonal_lattice', ([], {'lattice': 'hexagonal_lattice'}), '(lattice=hexagonal_lattice)\n', (396, 423), False, 'from twinpy.properties import hexagonal\n'), ((1366, 1391), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0,... |
"""
Helper functions used by multiple parts of LAtools.
(c) <NAME> : https://github.com/oscarbranson
"""
import os
import shutil
import re
import configparser
import datetime as dt
import numpy as np
import dateutil as du
import pkg_resources as pkgrs
import uncertainties.unumpy as un
import scipy.interpolate as inter... | [
"os.mkdir",
"numpy.polyfit",
"numpy.empty",
"os.walk",
"numpy.ones",
"pkg_resources.resource_filename",
"numpy.isnan",
"numpy.mean",
"numpy.arange",
"shutil.rmtree",
"numpy.convolve",
"shutil.copy",
"numpy.full",
"numpy.ndim",
"numpy.reshape",
"re.search",
"dateutil.parser.parse",
... | [((4364, 4379), 'os.walk', 'os.walk', (['in_dir'], {}), '(in_dir)\n', (4371, 4379), False, 'import os\n'), ((5523, 5566), 'numpy.full', 'np.full', (['bool_array.size', 'nstart'], {'dtype': 'int'}), '(bool_array.size, nstart, dtype=int)\n', (5530, 5566), True, 'import numpy as np\n'), ((6100, 6128), 'numpy.zeros', 'np.z... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... | [
"tensorflow.python.platform.test.main",
"tensorflow.train.MonitoredTrainingSession",
"tensorflow.losses.sparse_softmax_cross_entropy",
"epl.add_to_collection",
"distutils.version.LooseVersion",
"tensorflow.layers.dense",
"tensorflow.train.get_or_create_global_step",
"epl.replicate",
"tensorflow.add_... | [((10439, 10450), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (10448, 10450), False, 'from tensorflow.python.platform import test\n'), ((8955, 9000), 'epl.parallel.hooks._append_replicated_fetches', '_append_replicated_fetches', (['fetches', 'replicas'], {}), '(fetches, replicas)\n', (8981, 9... |
import six
import numpy as np
import nutszebra_utility as nz
import sys
import pickle
def unpickle(file_name):
fp = open(file_name, 'rb')
if sys.version_info.major == 2:
data = pickle.load(fp)
elif sys.version_info.major == 3:
data = pickle.load(fp, encoding='latin-1')
fp.close()
r... | [
"six.moves.range",
"numpy.zeros",
"numpy.any",
"nutszebra_utility.Utility",
"pickle.load",
"numpy.array",
"numpy.all"
] | [((195, 210), 'pickle.load', 'pickle.load', (['fp'], {}), '(fp)\n', (206, 210), False, 'import pickle\n'), ((404, 416), 'nutszebra_utility.Utility', 'nz.Utility', ([], {}), '()\n', (414, 416), True, 'import nutszebra_utility as nz\n'), ((1644, 1690), 'numpy.zeros', 'np.zeros', (['(50000, 3, 32, 32)'], {'dtype': 'np.flo... |
from tqdm import tqdm
from MCTS import MCTS
from BinaryTree import BinaryTree
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(15)
def run_experiment(max_iterations, dynamic_c=False):
"""
Run a single experiment of a sequence of MCTS searches to find the optimal path.
:param max_iterati... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xscale",
"tqdm.tqdm",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.logspace",
"matplotlib.pyplot.legend",
"MCTS.MCTS",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"BinaryT... | [((131, 149), 'numpy.random.seed', 'np.random.seed', (['(15)'], {}), '(15)\n', (145, 149), True, 'import numpy as np\n'), ((519, 552), 'BinaryTree.BinaryTree', 'BinaryTree', ([], {'depth': '(12)', 'b': '(20)', 'tau': '(3)'}), '(depth=12, b=20, tau=3)\n', (529, 552), False, 'from BinaryTree import BinaryTree\n'), ((597,... |
import numpy as np
import time
import keyboard
import math
import threading
def attack_mob(boxes,classes):
"""
recevies in the player box and the mob box and then will move the player towards the mob and then attack it
"""
#midpoints X1 and X2
player, closestmob = calculate_distance(boxes,classes)
... | [
"math.hypot",
"numpy.zeros",
"keyboard.moveRight",
"numpy.argmin",
"time.time",
"keyboard.teledown",
"keyboard.loot",
"keyboard.moveLeft",
"numpy.where",
"numpy.array",
"keyboard.cc",
"keyboard.teleup",
"keyboard.buff",
"numpy.shape",
"keyboard.attackFiveTimes"
] | [((1979, 2001), 'numpy.where', 'np.where', (['(classes == 2)'], {}), '(classes == 2)\n', (1987, 2001), True, 'import numpy as np\n'), ((2228, 2257), 'numpy.zeros', 'np.zeros', (['(5)'], {'dtype': 'np.float32'}), '(5, dtype=np.float32)\n', (2236, 2257), True, 'import numpy as np\n'), ((2546, 2565), 'numpy.argmin', 'np.a... |
# -*- coding: utf-8 -*-
# Created on Sat Jun 05 2021
# Last modified on Mon Jun 07 2021
# Copyright (c) CaMOS Development Team. All Rights Reserved.
# Distributed under a MIT License. See LICENSE for more info.
import numpy as np
from camos.tasks.analysis import Analysis
from camos.utils.generategui import NumericInp... | [
"camos.utils.generategui.DatasetInput",
"numpy.isin",
"numpy.where",
"camos.utils.units.get_time",
"numpy.unique"
] | [((1324, 1372), 'numpy.unique', 'np.unique', (["data[:]['CellID']"], {'return_counts': '(True)'}), "(data[:]['CellID'], return_counts=True)\n", (1333, 1372), True, 'import numpy as np\n'), ((1618, 1643), 'numpy.isin', 'np.isin', (['IDs', 'IDs_include'], {}), '(IDs, IDs_include)\n', (1625, 1643), True, 'import numpy as ... |
"""
Created on April 13, 2018
Edited on July 05, 2019
@author: <NAME> & <NAME>
Sony CSL Paris, France
Institute for Computational Perception, Johannes Kepler University, Linz
Austrian Research Institute for Artificial Intelligence, Vienna
"""
import numpy as np
import librosa
import torch.utils.data as data
import t... | [
"complex_auto.util.cached",
"numpy.concatenate",
"scipy.signal.get_window",
"torch.FloatTensor",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"complex_auto.util.to_numpy",
"numpy.random.randint",
"librosa.load",
"numpy.random.choice",
"numpy.random.rand",
"torchvisio... | [((541, 568), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (558, 568), False, 'import logging\n'), ((7686, 7718), 'numpy.random.randint', 'np.random.randint', (['(0)', 'count_data'], {}), '(0, count_data)\n', (7703, 7718), True, 'import numpy as np\n'), ((7784, 7856), 'numpy.random.rand... |
"""
Implementation using CuPy acceleration.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import numpy as np
from time import time
import cupy as cp
from cupyx.scipy import fft as cufft
def powerspectrum(*u, average=True, diagnostics=False,
kmin=None, kmax=None, npts=None,
compute_fft=... | [
"numpy.abs",
"cupy.empty",
"cupy.zeros_like",
"numpy.polyfit",
"cupy.get_default_memory_pool",
"numpy.add.outer",
"cupy.fuse",
"cupy.std",
"numpy.fft.fftfreq",
"pyFC.LogNormalFractalCube",
"numpy.log10",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.show",
"cupy.zeros",
"cupy.real",
... | [((6522, 6556), 'cupy.fuse', 'cp.fuse', ([], {'kernel_name': '"""mod_squared"""'}), "(kernel_name='mod_squared')\n", (6529, 6556), True, 'import cupy as cp\n'), ((2898, 2936), 'numpy.issubdtype', 'np.issubdtype', (['u[0].dtype', 'np.floating'], {}), '(u[0].dtype, np.floating)\n', (2911, 2936), True, 'import numpy as np... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import torch
from itertools import permutations
def loss_calc(est, ref, loss_type):
"""
time-domain loss: sisdr
"""
# time domain (wav input)
if loss_type == "sisdr":
loss = batch_SDR_torch(est, ref)
if loss_type == "mse"... | [
"torch.mean",
"torch.stack",
"torch.cat",
"torch.log10",
"torch.pow",
"torch.max",
"numpy.arange",
"torch.rand",
"torch.zeros",
"torch.sum"
] | [((3031, 3053), 'torch.cat', 'torch.cat', (['SDR_perm', '(1)'], {}), '(SDR_perm, 1)\n', (3040, 3053), False, 'import torch\n'), ((3071, 3097), 'torch.max', 'torch.max', (['SDR_perm'], {'dim': '(1)'}), '(SDR_perm, dim=1)\n', (3080, 3097), False, 'import torch\n'), ((4405, 4432), 'torch.rand', 'torch.rand', (['(10)', '(2... |
from __future__ import absolute_import, division
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
from pytest import raises
from fatiando.seismic import conv
def test_impulse_response():
"""
conv.convolutional_model raises the source wavelet as result when the model
... | [
"numpy.zeros",
"numpy.ones",
"fatiando.seismic.conv.rickerwave",
"pytest.raises",
"fatiando.seismic.conv.convolutional_model",
"numpy.testing.assert_array_almost_equal"
] | [((428, 456), 'fatiando.seismic.conv.rickerwave', 'conv.rickerwave', (['(30.0)', '(0.002)'], {}), '(30.0, 0.002)\n', (443, 456), False, 'from fatiando.seismic import conv\n'), ((470, 496), 'numpy.zeros', 'np.zeros', (['(w.shape[0], 20)'], {}), '((w.shape[0], 20))\n', (478, 496), True, 'import numpy as np\n'), ((544, 61... |
import numpy as np
def L2Loss(y_predicted, y_ground_truth, reduction="None"):
"""returns l2 loss between two arrays
:param y_predicted: array of predicted values
:type y_predicted: ndarray
:param y_ground_truth: array of ground truth values
:type y_ground_truth: ndarray
:param reduction: redu... | [
"numpy.array",
"numpy.mean",
"numpy.multiply",
"numpy.sum"
] | [((637, 672), 'numpy.multiply', 'np.multiply', (['difference', 'difference'], {}), '(difference, difference)\n', (648, 672), True, 'import numpy as np\n'), ((1941, 1962), 'numpy.array', 'np.array', (['y_predicted'], {}), '(y_predicted)\n', (1949, 1962), True, 'import numpy as np\n'), ((1984, 2008), 'numpy.array', 'np.a... |
# Copyright 2020-2022 OpenDR European Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | [
"os.remove",
"tqdm.tqdm",
"zipfile.ZipFile",
"os.makedirs",
"opendr.perception.object_detection_2d.ssd.ssd_learner.SingleShotDetectorLearner",
"pickle.dump",
"numpy.asarray",
"os.path.exists",
"time.time",
"opendr.perception.object_detection_2d.datasets.transforms.BoundingBoxListToNumpyArray",
"... | [((2050, 2082), 'os.path.join', 'os.path.join', (['path', 'dataset_name'], {}), '(path, dataset_name)\n', (2062, 2082), False, 'import os\n'), ((5035, 5140), 'os.path.join', 'os.path.join', (['self.path', "('data_' + self.detector + '_' + self.dataset_sets[self.split] + '_pets.pkl')"], {}), "(self.path, 'data_' + self.... |
import flask
import random
import sys
import os
import glob
import re
from pathlib import Path
import pickle
import numpy as np
# Import fast.ai Library
from fastai import *
from fastai.vision import *
# Flask utils
from flask import Flask, redirect, url_for, request, render_template,jsonify
from werkzeug.utils impo... | [
"random.randint",
"flask.Flask",
"pathlib.Path",
"pickle.load",
"numpy.array",
"flask.request.get_json"
] | [((346, 367), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (357, 367), False, 'import flask\n'), ((409, 421), 'pathlib.Path', 'Path', (['"""path"""'], {}), "('path')\n", (413, 421), False, 'from pathlib import Path\n'), ((544, 558), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (555, 558), Fa... |
import time
from collections import defaultdict
from datetime import timedelta
import cvxpy as cp
import empiricalutilities as eu
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
from transfer_entropy import TransferEntropy
plt.style.use('fivethirtyei... | [
"pandas.read_csv",
"collections.defaultdict",
"cvxpy.sum",
"matplotlib.pyplot.style.use",
"empiricalutilities.save_fig",
"matplotlib.pyplot.tight_layout",
"cvxpy.Maximize",
"cvxpy.quad_form",
"pandas.DataFrame",
"datetime.timedelta",
"cvxpy.Problem",
"empiricalutilities.latex_figure",
"panda... | [((293, 325), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (306, 325), True, 'import matplotlib.pyplot as plt\n'), ((959, 989), 'transfer_entropy.TransferEntropy', 'TransferEntropy', ([], {'assets': 'assets'}), '(assets=assets)\n', (974, 989), False, 'from tr... |
"""Experiments and corresponding analysis.
format adapted from https://github.com/gyyang/olfaction_evolution
Each experiment is described by a function that returns a list of configurations
function name is the experiment name
combinatorial mode:
config_ranges should not have repetitive values
sequential mode:
... | [
"utils.config_utils.vary_config",
"copy.deepcopy",
"numpy.zeros_like",
"analysis.plots.plot_gen",
"os.path.join",
"logging.basicConfig",
"evaluate.eval_total_acc",
"numpy.arange",
"analysis.train_analysis.plot_train_log",
"collections.OrderedDict",
"configs.configs.BaseConfig",
"analysis.plots... | [((857, 893), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'LOG_LEVEL'}), '(level=LOG_LEVEL)\n', (876, 893), False, 'import logging\n'), ((1048, 1093), 'analysis.train_analysis.plot_train_log', 'plot_train_log', (['[exp_path]'], {'exp_name': 'exp_name'}), '([exp_path], exp_name=exp_name)\n', (1062, 1093... |
from pathlib import Path
import numpy as np
from PIL import Image
def load_light_distribution(name="lamp_spectrum.csv"):
sd_light_source = np.loadtxt(name, skiprows=1, dtype="float")
sd_light_source = sd_light_source[np.where(sd_light_source[:, 0] >= 400)]
# rindx = np.where(sd_light_source[:, 0] >= 400)... | [
"numpy.stack",
"numpy.uint8",
"numpy.sum",
"numpy.power",
"numpy.clip",
"pathlib.Path",
"numpy.where",
"numpy.array",
"numpy.loadtxt",
"numpy.dot"
] | [((146, 189), 'numpy.loadtxt', 'np.loadtxt', (['name'], {'skiprows': '(1)', 'dtype': '"""float"""'}), "(name, skiprows=1, dtype='float')\n", (156, 189), True, 'import numpy as np\n'), ((663, 706), 'numpy.loadtxt', 'np.loadtxt', (['name'], {'skiprows': '(1)', 'dtype': '"""float"""'}), "(name, skiprows=1, dtype='float')\... |
import pyaudio
import numpy as np
import sys
import time
import asyncio
from aiohttp import web, WSMsgType
import json
import os
import struct
import websocket
HOST = os.getenv('HOST', '0.0.0.0')
PORT = int(os.getenv('PORT', 8080))
SAMPLE_RATE = 44100
CHUNK_SIZE = 4096
AUDIO_FORMAT = pyaudio.paInt16
FORMAT = np.int... | [
"numpy.fft.rfft",
"numpy.average",
"aiohttp.web.Response",
"aiohttp.web.WebSocketResponse",
"asyncio.get_event_loop",
"numpy.abs",
"aiohttp.web.Application",
"json.dumps",
"numpy.max",
"numpy.reshape",
"aiohttp.web.run_app",
"pyaudio.PyAudio",
"os.getenv"
] | [((169, 197), 'os.getenv', 'os.getenv', (['"""HOST"""', '"""0.0.0.0"""'], {}), "('HOST', '0.0.0.0')\n", (178, 197), False, 'import os\n'), ((209, 232), 'os.getenv', 'os.getenv', (['"""PORT"""', '(8080)'], {}), "('PORT', 8080)\n", (218, 232), False, 'import os\n'), ((424, 441), 'numpy.fft.rfft', 'np.fft.rfft', (['data']... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | [
"numpy.random.seed",
"torch.eye",
"torch.ByteTensor",
"torch.cat",
"torch.nn.InstanceNorm2d",
"torch.cos",
"numpy.arange",
"torch.nn.Softmax",
"torch.arange",
"torch.device",
"torch.nn.functional.normalize",
"torch.flatten",
"torch.nn.functional.grid_sample",
"logging.warning",
"torch.nn... | [((1022, 1047), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1045, 1047), False, 'import torch\n'), ((1057, 1102), 'torch.device', 'torch.device', (["('cuda:0' if USE_CUDA else 'cpu')"], {}), "('cuda:0' if USE_CUDA else 'cpu')\n", (1069, 1102), False, 'import torch\n'), ((1103, 1121), 'numpy... |
#!python3
# -*- coding:utf-8 -*-
# 『Pythonで始めるOpenCV4プログラミング』
# 北山尚洋
import cv2
import sys, traceback
import numpy as np
def add(imgName1, imgName2):
try:
img1 = cv2.imread(imgName1)
img2 = cv2.imread(imgName2)
if img1 is None or img2 is None:
print("no file reading..... | [
"cv2.waitKey",
"cv2.destroyAllWindows",
"numpy.zeros",
"cv2.imread",
"sys.exc_info",
"sys.exit",
"cv2.imshow",
"cv2.add",
"cv2.resize"
] | [((177, 197), 'cv2.imread', 'cv2.imread', (['imgName1'], {}), '(imgName1)\n', (187, 197), False, 'import cv2\n'), ((213, 233), 'cv2.imread', 'cv2.imread', (['imgName2'], {}), '(imgName2)\n', (223, 233), False, 'import cv2\n'), ((466, 494), 'cv2.resize', 'cv2.resize', (['img1', '(500, 500)'], {}), '(img1, (500, 500))\n'... |
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms, datasets, models
from collections import OrderedDict
from PIL import Image
import matplotlib.pyplot as plt
import json
import argparse
def load_checkpoint(checkpoint_path, model):
chec... | [
"torch.topk",
"argparse.ArgumentParser",
"torchvision.models.vgg11",
"torch.nn.ReLU",
"torch.nn.LogSoftmax",
"torch.load",
"torchvision.models.densenet121",
"PIL.Image.open",
"torch.exp",
"numpy.array",
"torch.nn.Linear",
"torch.zeros",
"torch.no_grad",
"torch.from_numpy"
] | [((329, 356), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (339, 356), False, 'import torch\n'), ((1656, 1673), 'PIL.Image.open', 'Image.open', (['image'], {}), '(image)\n', (1666, 1673), False, 'from PIL import Image\n'), ((2036, 2067), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.40... |
# Ad Soyad: <NAME> No: 180401041
#import numpy.matlib #Matrislerde kullanılabilir
from matrix_operations import matrix_transpose # gerekli matris işlemleri için fonksiyonların dahil edilmesi.
# D=A^T --> D= np.transpose(A) --> transpose kullanımı
from matrix... | [
"matrix_operations.matrix_transpose",
"os.getcwd",
"numpy.zeros",
"copy.copy",
"matrix_operations.matrix_inverse",
"matrix_operations.matrix_multiplication"
] | [((8209, 8220), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8218, 8220), False, 'import os\n'), ((4313, 4357), 'numpy.zeros', 'np.zeros', ([], {'shape': '(derece + 1, 1)', 'dtype': 'float'}), '(shape=(derece + 1, 1), dtype=float)\n', (4321, 4357), True, 'import numpy as np\n'), ((4392, 4465), 'numpy.zeros', 'np.zeros'... |
# -*- coding: utf-8 -*-
"""
Class for storing supply curves and calculating marginal costs
Created on Thu Feb 7 15:34:33 2019
@author: elisn
"""
import pickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
class SupplyCurve():
""" Has panda dataframe with list of bids
One or ... | [
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"pickle.load",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((9079, 9128), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['cap', 'mc_min', 'mc_max']"}), "(columns=['cap', 'mc_min', 'mc_max'])\n", (9091, 9128), True, 'import pandas as pd\n'), ((9860, 9874), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (9868, 9874), True, 'import matplotlib.pyplot ... |
# -*- coding: utf-8 -*-
from sklearn.metrics import classification_report
from keras.callbacks import ModelCheckpoint
from keras.utils import plot_model
import matplotlib.pyplot as plt
import numpy as np
import os
from tnmlearn.callbacks import TrainingMonitor
# %%
class BaseLearningModel:
def __init__(self):
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"os.getpid",
"keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"keras.utils.plot_model",
"matplotlib.pyplot.style.use",
"numpy.arange",
"tnmlearn.callbacks.TrainingMonitor",
"matplotlib.pyplot.ylabel",
... | [((829, 902), 'os.path.sep.join', 'os.path.sep.join', (["[weightpath, 'weights-{epoch:03d}-{val_loss:.4f}.hdf5']"], {}), "([weightpath, 'weights-{epoch:03d}-{val_loss:.4f}.hdf5'])\n", (845, 902), False, 'import os\n'), ((927, 1017), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['fname'], {'monitor': '"""val_l... |
import numpy as np
import tensorflow as tf
import csv
def classify_state(X, n_state):
up = 80
if (0 <= X <= 2.5):
return n_state - 1, 2.5
for i in range(n_state - 1):
if (up - (i + 1) * 2.5 < X <= up - i * 2.5):
return i, up - i * 2.5
def GA(max_prob_index, n_actions):
valu... | [
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.nn.softmax",
"csv.writer",
"tensorflow.train.Saver",
"numpy.argmax",
"tensorflow.nn.dynamic_rnn",
"tensorflow.reset_default_graph",
"tensorflow.constant_initializer",
"numpy.zeros",
"tensorflow.Session",
"tensorflow.placeholder",
"ten... | [((325, 344), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (333, 344), True, 'import numpy as np\n'), ((531, 550), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (539, 550), True, 'import numpy as np\n'), ((655, 674), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n',... |
import os
import pdb
import numpy as np
from fastestimator.summary.logs import parse_log_file
from scipy.stats import ttest_ind
from tabulate import tabulate
def get_best_step(objective, eval_steps, result, mode, train_history):
obj_step = 0
for idx, value in enumerate(result):
if (mode == "max" and ... | [
"fastestimator.summary.logs.parse_log_file",
"numpy.median",
"numpy.std",
"scipy.stats.ttest_ind",
"numpy.mean",
"tabulate.tabulate",
"os.path.splitext",
"os.path.join",
"os.listdir"
] | [((3104, 3219), 'tabulate.tabulate', 'tabulate', (['table'], {'headers': "['scheduler', 'metric mean', 'metric std', 'step mean', 'step std']", 'tablefmt': '"""github"""'}), "(table, headers=['scheduler', 'metric mean', 'metric std',\n 'step mean', 'step std'], tablefmt='github')\n", (3112, 3219), False, 'from tabul... |
import numpy as np
def filter_ids(array, clinical_ids):
# list of array indices that need to be deleted
del_indices = []
i = 0
for img in array:
id = img[-1]
if id not in clinical_ids:
del_indices.append(i)
i = i + 1
array = np.delete(array, del_indices, axis... | [
"numpy.delete"
] | [((286, 323), 'numpy.delete', 'np.delete', (['array', 'del_indices'], {'axis': '(0)'}), '(array, del_indices, axis=0)\n', (295, 323), True, 'import numpy as np\n')] |
import cdutil
import cdat_info
import cdms2
import cdms2,cdutil,sys,MV2,numpy,os,cdat_info
import unittest
import numpy
import tempfile
class CDUTIL(unittest.TestCase):
def testRegions(self):
regionNA = cdutil.region.domain(latitude=(-50.,50.,'ccb'))
f=cdms2.open(cdat_info.get_sampledata_path()+'... | [
"unittest.main",
"cdutil.region.domain",
"numpy.array",
"cdat_info.get_sampledata_path"
] | [((809, 824), 'unittest.main', 'unittest.main', ([], {}), '()\n', (822, 824), False, 'import unittest\n'), ((218, 269), 'cdutil.region.domain', 'cdutil.region.domain', ([], {'latitude': "(-50.0, 50.0, 'ccb')"}), "(latitude=(-50.0, 50.0, 'ccb'))\n", (238, 269), False, 'import cdms2, cdutil, sys, MV2, numpy, os, cdat_inf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
COS method
==========
The method comes from [1]_
The original code is found at
http://www.wilmott.com/messageview.cfm?catid=34&threadid=78554
References
----------
.. [1] <NAME>., & <NAME>. (2009).
A Novel Pricing Method for European Options
Based on Fourier... | [
"numpy.ones_like",
"numpy.logical_not",
"numpy.ones",
"numexpr.evaluate",
"numpy.arange",
"numpy.exp",
"numpy.dot"
] | [((2168, 2188), 'numpy.logical_not', 'np.logical_not', (['call'], {}), '(call)\n', (2182, 2188), True, 'import numpy as np\n'), ((2387, 2428), 'numpy.exp', 'np.exp', (['(-1.0j * kvec * (moneyness + alim))'], {}), '(-1.0j * kvec * (moneyness + alim))\n', (2393, 2428), True, 'import numpy as np\n'), ((3045, 3190), 'numex... |
import numpy as np
from glob import glob
from scipy import ndimage
from keras import callbacks
from keras.optimizers import Adamax, SGD, RMSprop
import resnet50
def convert_to_one_hot(Y, C):
'''Converts array with labels to one-hot encoding
Keyword Arguments:
Y -- 1-dimensional numpy array containing... | [
"keras.optimizers.SGD",
"keras.callbacks.TerminateOnNaN",
"numpy.eye",
"keras.callbacks.ModelCheckpoint",
"numpy.asarray",
"glob.glob",
"keras.callbacks.CSVLogger",
"scipy.ndimage.imread"
] | [((676, 699), 'glob.glob', 'glob', (["('%s/*' % datapath)"], {}), "('%s/*' % datapath)\n", (680, 699), False, 'from glob import glob\n'), ((1609, 1646), 'keras.optimizers.SGD', 'SGD', ([], {'lr': 'learning_rate', 'decay': 'lr_decay'}), '(lr=learning_rate, decay=lr_decay)\n', (1612, 1646), False, 'from keras.optimizers ... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
target = ["True", "False"]
el_decay = ["True", "False"]
error = np.array([[4.478, 3.483],
[3.647, 2.502]])
fig, ax = plt.subplots()
im = ax.imshow(error)
# We want to show all ticks...
ax.set_xticks(np.arange(len(el_decay)))
a... | [
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((135, 177), 'numpy.array', 'np.array', (['[[4.478, 3.483], [3.647, 2.502]]'], {}), '([[4.478, 3.483], [3.647, 2.502]])\n', (143, 177), True, 'import numpy as np\n'), ((210, 224), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (222, 224), True, 'import matplotlib.pyplot as plt\n'), ((986, 996), 'matpl... |
import numpy as np
import copy
class Particle:
def __init__(self, lb, ub):
"""Initialize the particle.
Attributes
----------
lb : float
lower bounds for initial values
ub : float
upper bounds for initial values
"""
self.lb = lb
... | [
"numpy.random.uniform",
"copy.deepcopy",
"numpy.square",
"numpy.array"
] | [((362, 405), 'numpy.random.uniform', 'np.random.uniform', (['lb', 'ub'], {'size': 'lb.shape[0]'}), '(lb, ub, size=lb.shape[0])\n', (379, 405), True, 'import numpy as np\n'), ((430, 473), 'numpy.random.uniform', 'np.random.uniform', (['lb', 'ub'], {'size': 'lb.shape[0]'}), '(lb, ub, size=lb.shape[0])\n', (447, 473), Tr... |
import pygame
from pygame.locals import *
from constants import *
from copy import deepcopy
import numpy as np
from heuristic import *
class Player(object):
def __init__(self, color, player_num):
self.color = color
self.direction = UP
self.player_num = player_num
self.move_counter =... | [
"pygame.draw.rect",
"copy.deepcopy",
"numpy.zeros"
] | [((1204, 1220), 'copy.deepcopy', 'deepcopy', (['player'], {}), '(player)\n', (1212, 1220), False, 'from copy import deepcopy\n'), ((1417, 1478), 'numpy.zeros', 'np.zeros', (['(GAME_HEIGHT / CELL_WIDTH, GAME_WIDTH / CELL_WIDTH)'], {}), '((GAME_HEIGHT / CELL_WIDTH, GAME_WIDTH / CELL_WIDTH))\n', (1425, 1478), True, 'impor... |
import numpy as np
def to_array(image):
array = np.array(image, dtype=np.float32)[..., :3]
array = array / 255.
return array
def l2_normalize(x, axis=0):
norm = np.linalg.norm(x, axis=axis, keepdims=True)
return x / norm
def distance(a, b):
# Euclidean distance
# return np.linalg.norm(a... | [
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
] | [((180, 223), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {'axis': 'axis', 'keepdims': '(True)'}), '(x, axis=axis, keepdims=True)\n', (194, 223), True, 'import numpy as np\n'), ((498, 510), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (504, 510), True, 'import numpy as np\n'), ((53, 86), 'numpy.array', 'np.a... |
''' control systems - ode simulation
@link https://www.youtube.com/watch?v=yp5x8RMNi7o
'''
import numpy as np
from scipy.integrate import odeint
from matplotlib import pyplot as plt
def sys_ode(x, t):
# set system constants
c = 4 # damping constant
k = 2 # spring stiffness constant
m = 20 # point-mass
F... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"scipy.integrate.odeint",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((611, 638), 'numpy.arange', 'np.arange', (['t_0', 't_f', 'period'], {}), '(t_0, t_f, period)\n', (620, 638), True, 'import numpy as np\n'), ((645, 671), 'scipy.integrate.odeint', 'odeint', (['sys_ode', 'x_init', 't'], {}), '(sys_ode, x_init, t)\n', (651, 671), False, 'from scipy.integrate import odeint\n'), ((704, 71... |
import numpy as np
a_matris = [[2,0,0],
[0,2,0],
[0,0,2]]
x_matris = []
b_matris = [2, 4, 9]
u_a_matris = np.triu(a_matris)
x3 = float(b_matris[2])/u_a_matris[2][2]
x2 = float(b_matris[1] - x3*u_a_matris[1][2])/u_a_matris[1][1]
x1 = float(b_matris[0] - x2*u_a_matris[0][1] - x3*u_a_matris[0][2... | [
"numpy.triu"
] | [((132, 149), 'numpy.triu', 'np.triu', (['a_matris'], {}), '(a_matris)\n', (139, 149), True, 'import numpy as np\n')] |
import os
import logging
import galsim
import galsim.config
import piff
import numpy as np
import ngmix
if ngmix.__version__[0:2] == "v1":
NGMIX_V2 = False
from ngmix.fitting import LMSimple
from ngmix.admom import Admom
else:
NGMIX_V2 = True
from ngmix.fitting import Fitter
from ngmix.admom ... | [
"galsim.config.BuildGSObject",
"numpy.empty",
"numpy.clip",
"numpy.mean",
"ngmix.gmix.make_gmix_model",
"galsim.PixelScale",
"galsim.config.GetAllParams",
"galsim.config.GetInputObj",
"galsim.PositionD",
"galsim.ImageD",
"galsim.config.RegisterObjectType",
"numpy.isfinite",
"numpy.random.Ran... | [((407, 434), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (424, 434), False, 'import logging\n'), ((12281, 12383), 'galsim.config.RegisterObjectType', 'galsim.config.RegisterObjectType', (['"""DES_Piff"""', 'BuildDES_Piff_with_substitute'], {'input_type': '"""des_piff"""'}), "('DES_Pif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.