code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""
Copyright 2017- IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... | [
"torch.index_select",
"torch.nn.Dropout",
"torch.nn.Embedding",
"torch.LongTensor",
"torch.stack",
"torch.transpose",
"numpy.array",
"torch.tensor",
"torch.cuda.is_available",
"torch.nn.Linear",
"random.random",
"torch.zeros",
"torch.cat"
] | [((4746, 4786), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embedding_size'], {}), '(vocab_size, embedding_size)\n', (4758, 4786), True, 'import torch.nn as nn\n'), ((4817, 4846), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'input_dropout_p'}), '(p=input_dropout_p)\n', (4827, 4846), True, 'import torch.nn a... |
#!/usr/bin/python3
from binance.exceptions import BinanceAPIException, BinanceRequestException
from pyti.smoothed_moving_average import smoothed_moving_average as sma
from pyti.bollinger_bands import upper_bollinger_band as ubb # Examples of indicators/strategies
from pyti.bollinger_bands import lower_bollinger_ban... | [
"binance.client.Client",
"traceback.format_exc",
"pyti.bollinger_bands.upper_bollinger_band",
"datetime.datetime.utcnow",
"plotly.graph_objs.Data",
"decimal.Decimal",
"pyti.smoothed_moving_average.smoothed_moving_average",
"decimal.Decimal.from_float",
"plotly.graph_objs.Scatter",
"time.sleep",
... | [((993, 1043), 'binance.client.Client', 'Client', ([], {'api_key': 'bikeys.Pass', 'api_secret': 'bikeys.Sec'}), '(api_key=bikeys.Pass, api_secret=bikeys.Sec)\n', (999, 1043), False, 'from binance.client import Client\n'), ((1663, 1689), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'candles'}), '(data=candles)\n', ... |
import sys
import os
import numpy as np
input_file = sys.argv[1]
output_file = sys.argv[2]
def _dataset_info_standard(txt_labels):
with open(txt_labels, 'r') as f:
images_list = f.readlines()
file_names = []
labels = []
for row in images_list:
row = row.split(' ')
file_names.... | [
"numpy.random.choice",
"numpy.array",
"sys.exit"
] | [((526, 542), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (534, 542), True, 'import numpy as np\n'), ((554, 569), 'numpy.array', 'np.array', (['names'], {}), '(names)\n', (562, 569), True, 'import numpy as np\n'), ((971, 982), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (979, 982), False, 'import sys... |
import gym
import robo_gym
import math
import numpy as np
import pytest
ur_models = [pytest.param('ur3', marks=pytest.mark.nightly), \
pytest.param('ur3e', marks=pytest.mark.nightly), \
pytest.param('ur5', marks=pytest.mark.commit), \
pytest.param('ur5e', marks=pytest.mark.night... | [
"pytest.mark.flaky",
"numpy.isclose",
"math.isclose",
"pytest.param",
"pytest.mark.parametrize",
"pytest.fixture",
"gym.make"
] | [((525, 573), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': 'ur_models'}), "(scope='module', params=ur_models)\n", (539, 573), False, 'import pytest\n'), ((1142, 1169), 'pytest.mark.flaky', 'pytest.mark.flaky', ([], {'reruns': '(3)'}), '(reruns=3)\n', (1159, 1169), False, 'import pytest\n... |
# coding=utf-8
# 20160510
# __author__ = 'xhcao'
import numpy as np
import scipy.spatial as sp
# A=self.method.distance_correction_for_one_matrix(X, dimension)\
# B=self.method.distance_correction_for_one_matrix(Y, dimension)\
# corr_matrix[i,j]=self.method.distance_correlation(A,B) "
def distance_c... | [
"numpy.mean",
"numpy.sqrt",
"numpy.ones",
"scipy.spatial.distance.cdist",
"numpy.sum",
"numpy.zeros"
] | [((438, 487), 'scipy.spatial.distance.cdist', 'sp.distance.cdist', (['x', 'x', '"""minkowski"""'], {'p': 'dimension'}), "(x, x, 'minkowski', p=dimension)\n", (455, 487), True, 'import scipy.spatial as sp\n'), ((539, 550), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (547, 550), True, 'import numpy as np\n'), ((632,... |
'''
Created on Aug 29, 2016
@author: <NAME> <<EMAIL>>
'''
from __future__ import division
import unittest
import numpy as np
from .. import random
class TestRandom(unittest.TestCase):
_multiprocess_can_split_ = True # let nose know that tests can run parallel
def test_random_log_uniform(self):
... | [
"unittest.main",
"numpy.arange"
] | [((2401, 2416), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2414, 2416), False, 'import unittest\n'), ((683, 697), 'numpy.arange', 'np.arange', (['num'], {}), '(num)\n', (692, 697), True, 'import numpy as np\n'), ((1628, 1642), 'numpy.arange', 'np.arange', (['num'], {}), '(num)\n', (1637, 1642), True, 'import ... |
#!/usr/bin/env python
# Light each LED in sequence, and repeat.
import fastopc, time
import numpy as np
numLEDs = 512
client = fastopc.FastOPC('localhost:7890')
pixels = np.zeros([numLEDs, 3])
class Pixels():
def __init__(self, numLEDs, floor):
self.numLEDs = numLEDs
self.floor = floor
self.array = np.zeros... | [
"fastopc.FastOPC",
"numpy.zeros",
"numpy.zeros_like",
"time.sleep"
] | [((130, 163), 'fastopc.FastOPC', 'fastopc.FastOPC', (['"""localhost:7890"""'], {}), "('localhost:7890')\n", (145, 163), False, 'import fastopc, time\n'), ((174, 196), 'numpy.zeros', 'np.zeros', (['[numLEDs, 3]'], {}), '([numLEDs, 3])\n', (182, 196), True, 'import numpy as np\n'), ((715, 742), 'numpy.zeros_like', 'np.ze... |
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a>3) #Where is A>3?
'''
[[False False False]
[ True True True]
[ True True True]]
gives the above.
So in 0th list, none are true. Then you have 1st list, 0th is true. 1st list 1th is true. 1st list 2nd is true
so you have 1-0, 1-1, 1-2, w... | [
"numpy.array",
"numpy.nonzero"
] | [((23, 66), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (31, 66), True, 'import numpy as np\n'), ((443, 460), 'numpy.nonzero', 'np.nonzero', (['(a > 3)'], {}), '(a > 3)\n', (453, 460), True, 'import numpy as np\n')] |
import numpy as np
def unit_vector(k, N):
ek = np.zeros(N)
ek[k] = 1.0
return ek
| [
"numpy.zeros"
] | [((53, 64), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (61, 64), True, 'import numpy as np\n')] |
from __future__ import print_function
from fenics import *
from mshr import *
import numpy as np
from scipy import integrate
set_log_level(LogLevel.INFO)
T = 500.0 # final time
num_steps = 1000 # number of time steps
dt = T / num_steps # time step size
mu = 16 # dynamic viscosity
rho = 1 ... | [
"numpy.ones",
"numpy.exp",
"numpy.linspace",
"numpy.random.uniform",
"scipy.integrate.dblquad",
"numpy.round"
] | [((9214, 9315), 'scipy.integrate.dblquad', 'integrate.dblquad', (['WTGdist', '(-3 * radius)', '(3 * radius)', '(lambda x: -3 * radius)', '(lambda x: 3 * radius)'], {}), '(WTGdist, -3 * radius, 3 * radius, lambda x: -3 * radius, \n lambda x: 3 * radius)\n', (9231, 9315), False, 'from scipy import integrate\n'), ((206... |
# -*- coding: utf-8 -*-
import sys
import os
import pdb
# Cosine similarity
import numpy as np
from numpy import dot
from numpy.linalg import norm
from PIL import Image
import torch
from facenet_pytorch import MTCNN, InceptionResnetV1
#******************** Constants
K_MODEL_IMAGE_SIZE = (160, 160) # (Width, Hei... | [
"PIL.Image.open",
"facenet_pytorch.InceptionResnetV1",
"PIL.Image.new",
"facenet_pytorch.MTCNN",
"numpy.array",
"numpy.dot",
"torch.tensor",
"pdb.set_trace",
"numpy.linalg.norm"
] | [((1167, 1187), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (1177, 1187), False, 'from PIL import Image\n'), ((1601, 1641), 'numpy.array', 'np.array', (['resized_image'], {'dtype': '"""float32"""'}), "(resized_image, dtype='float32')\n", (1609, 1641), True, 'import numpy as np\n'), ((1893, 1900)... |
from typing import List, Any, Dict
import numpy as np
from swd.bonuses import BONUSES, ImmediateBonus, SCIENTIFIC_SYMBOLS_RANGE
from swd.cards_board import AGES, CardsBoard
from swd.entity_manager import EntityManager
from swd.game import Game, GameState
from swd.player import Player
class StateFeatures:
@stati... | [
"numpy.flip",
"swd.cards_board.CardsBoard.available_cards",
"swd.entity_manager.EntityManager.wonder",
"swd.entity_manager.EntityManager.wonders_count",
"numpy.count_nonzero",
"swd.entity_manager.EntityManager.cards_count",
"swd.entity_manager.EntityManager.progress_token_names",
"swd.game.Game.points... | [((1370, 1406), 'numpy.flip', 'np.flip', (['(AGES[state.age] > 0)'], {'axis': '(0)'}), '(AGES[state.age] > 0, axis=0)\n', (1377, 1406), True, 'import numpy as np\n'), ((2562, 2598), 'numpy.flip', 'np.flip', (['(AGES[state.age] > 0)'], {'axis': '(0)'}), '(AGES[state.age] > 0, axis=0)\n', (2569, 2598), True, 'import nump... |
import functools
import gc
import json
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import bmm
def read_data(path, chunksize=None):
data_reader = pd.read_csv(path, chunksize=10)
data_columns = data_reader.get_chunk().columns
polyline_converters = {col_name: json.loads for col_n... | [
"numpy.abs",
"numpy.all",
"numpy.unique",
"pandas.read_csv",
"numpy.arange",
"numpy.ones",
"numpy.logical_and",
"numpy.min",
"numpy.max",
"numpy.sum",
"numpy.zeros",
"numpy.concatenate",
"gc.collect",
"gc.get_objects",
"bmm.observation_time_rows",
"matplotlib.pyplot.legend"
] | [((180, 211), 'pandas.read_csv', 'pd.read_csv', (['path'], {'chunksize': '(10)'}), '(path, chunksize=10)\n', (191, 211), True, 'import pandas as pd\n'), ((406, 476), 'pandas.read_csv', 'pd.read_csv', (['path'], {'converters': 'polyline_converters', 'chunksize': 'chunksize'}), '(path, converters=polyline_converters, chu... |
#from __future__ import absolute_import, division, print_function, unicode_literals
from neural_networks.NeuralLDAanalysisMethods import *
from dataset_loader.dataset_helper import Dataset_Helper
from results_saver import LogWriter
from neural_networks.aliaser import *
import os
import sys
import numpy as np
from neur... | [
"os.path.dirname",
"dataset_loader.dataset_helper.Dataset_Helper",
"tkinter.Tk",
"neural_networks.lda_impl.Lda",
"numpy.random.seed",
"sys.path.append"
] | [((385, 410), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (400, 410), False, 'import os\n'), ((411, 436), 'sys.path.append', 'sys.path.append', (['file_dir'], {}), '(file_dir)\n', (426, 436), False, 'import sys\n'), ((444, 451), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (449, 451), True, 'i... |
"""
Choice functions.
We focus upon the cumulative normal distribution as the choice function, but you
could impliment your own, eg Logistic, SoftMax, etc.
"""
from scipy.stats import norm
import numpy as np
def StandardCumulativeNormalChoiceFunc(decision_variable, θ, θ_fixed):
"""Cumulative normal choice func... | [
"numpy.divide"
] | [((655, 686), 'numpy.divide', 'np.divide', (['decision_variable', 'α'], {}), '(decision_variable, α)\n', (664, 686), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import torch
from collections import namedtuple
Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward', 'done'))
class DeepRLTrainer:
NB_EPISODES = 3000
SAVE_EVERY = 500
INFO_EVERY = 50
SOFT_MAX = False
DEVICE = 'cpu'... | [
"collections.namedtuple",
"matplotlib.pyplot.savefig",
"numpy.average",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"torch.tensor",
"matplotlib.pyplot.title",
"numpy.save",
"matplotlib.pyplot.legend"
] | [((113, 190), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', "('state', 'action', 'next_state', 'reward', 'done')"], {}), "('Transition', ('state', 'action', 'next_state', 'reward', 'done'))\n", (123, 190), False, 'from collections import namedtuple\n'), ((1364, 1432), 'torch.tensor', 'torch.tensor', (['... |
'''
Spectra plottings
'''
import numpy as np
import matplotlib.pyplot as plt
def singles(wn, spec):
'''
Individual spectra plot.
Parameters
----------
wn : ndarray
Wavenumber of shape [n_points].
spec : ndarray
Spectra of shape [n_spectra, n_points].
Returns
------... | [
"matplotlib.pyplot.imshow",
"numpy.mean",
"matplotlib.pyplot.grid",
"numpy.reshape",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.nonzero",
"numpy.std",
"matplotlib.pypl... | [((360, 374), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (372, 374), True, 'import matplotlib.pyplot as plt\n'), ((379, 425), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Wavenumber ($\\\\mathrm{cm^{-1}}$)"""'], {}), "('Wavenumber ($\\\\mathrm{cm^{-1}}$)')\n", (389, 425), True, 'import matplotli... |
import numpy as np
import os
from display import Display
import logging
from matplotlib import pyplot as plt
import cv2 as cv
class VisualOdometry:
FLANN_INDEX_LSH = 6
TSH_ORB_MATCHING = 0.5
COLORS = False
def __init__(self, data_path, n_features=3000, flann_precision=100, debug=False):
... | [
"numpy.hstack",
"time.sleep",
"cv2.triangulatePoints",
"numpy.array",
"matplotlib.pyplot.imshow",
"os.listdir",
"numpy.stack",
"cv2.ORB_create",
"numpy.vstack",
"numpy.eye",
"numpy.floor",
"numpy.argmax",
"cv2.imread",
"matplotlib.pyplot.show",
"cv2.drawKeypoints",
"numpy.logical_and",... | [((6223, 6232), 'display.Display', 'Display', ([], {}), '()\n', (6230, 6232), False, 'from display import Display\n'), ((719, 731), 'numpy.eye', 'np.eye', (['(4)', '(4)'], {}), '(4, 4)\n', (725, 731), True, 'import numpy as np\n'), ((1002, 1032), 'cv2.ORB_create', 'cv.ORB_create', (['self.n_features'], {}), '(self.n_fe... |
import numpy as np
import matplotlib.pyplot as plt
import cv2
##############################################################
offset_np = [
[ [0, 0], [0, 48], [0, 96], [0, 144], [0, 192], [0, 240]],
[ [48, 0], [48, 48], [48, 96], [48, 144], [48, 192], [48, 240]],
[ [96, 0], [96, 48], [96, 96], [9... | [
"cv2.rectangle",
"numpy.copy",
"numpy.minimum",
"numpy.where",
"numpy.absolute",
"matplotlib.pyplot.imsave",
"numpy.argmax",
"numpy.square",
"numpy.stack",
"numpy.concatenate",
"numpy.maximum",
"numpy.zeros_like"
] | [((877, 902), 'numpy.stack', 'np.stack', (['[iou1, iou2]', '(3)'], {}), '([iou1, iou2], 3)\n', (885, 902), True, 'import numpy as np\n'), ((1013, 1098), 'numpy.maximum', 'np.maximum', (['(boxA[..., 0] - 0.5 * boxA[..., 2])', '(boxB[..., 0] - 0.5 * boxB[..., 2])'], {}), '(boxA[..., 0] - 0.5 * boxA[..., 2], boxB[..., 0] ... |
import math
import numpy as np
from sklearn.neighbors import KernelDensity
from scipy.signal import argrelextrema
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
# --------------- Filter line segments with major orientation ---------------
def get_orientation(line)... | [
"numpy.amin",
"numpy.unique",
"scipy.signal.argrelextrema",
"numpy.where",
"math.degrees",
"sklearn.neighbors.KernelDensity",
"numpy.argsort",
"numpy.array",
"numpy.linspace",
"numpy.zeros",
"numpy.sum",
"math.atan2",
"numpy.concatenate",
"math.hypot",
"scipy.sparse.csr_matrix",
"math.... | [((501, 549), 'math.atan2', 'math.atan2', (['(line[3] - line[1])', '(line[2] - line[0])'], {}), '(line[3] - line[1], line[2] - line[0])\n', (511, 549), False, 'import math\n'), ((568, 593), 'math.degrees', 'math.degrees', (['orientation'], {}), '(orientation)\n', (580, 593), False, 'import math\n'), ((681, 729), 'math.... |
"""Sets of metrics to look at general sky coverage - nvisits/coadded depth/Teff.
"""
import numpy as np
import rubin_sim.maf.metrics as metrics
import rubin_sim.maf.slicers as slicers
import rubin_sim.maf.plots as plots
import rubin_sim.maf.metricBundles as mb
import rubin_sim.maf.utils as mafUtils
from .colMapDict imp... | [
"rubin_sim.maf.metricBundles.MetricBundle",
"rubin_sim.maf.slicers.OneDSlicer",
"rubin_sim.maf.plots.HealpixHistogram",
"rubin_sim.maf.metrics.CountMetric",
"numpy.floor",
"rubin_sim.maf.utils.calcCoaddedDepth",
"rubin_sim.maf.plots.HealpixSkyMap",
"rubin_sim.maf.metricBundles.makeBundlesDictFromList"... | [((2608, 2663), 'rubin_sim.maf.utils.scaleBenchmarks', 'mafUtils.scaleBenchmarks', (['runLength'], {'benchmark': '"""design"""'}), "(runLength, benchmark='design')\n", (2632, 2663), True, 'import rubin_sim.maf.utils as mafUtils\n'), ((2981, 3072), 'rubin_sim.maf.utils.calcCoaddedDepth', 'mafUtils.calcCoaddedDepth', (["... |
## @ingroup Components
# Mass_Properties.py
#
# Created:
# Modified: Feb 2016, <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from SUAVE.Core import Data
import numpy as np
# ---------------------... | [
"SUAVE.Core.Data",
"numpy.array"
] | [((1061, 1088), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0]])\n', (1069, 1088), True, 'import numpy as np\n'), ((1130, 1136), 'SUAVE.Core.Data', 'Data', ([], {}), '()\n', (1134, 1136), False, 'from SUAVE.Core import Data\n'), ((1178, 1203), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'],... |
"""
Routine to add Moster et al. 2013 stellar masses
python3 lc_add_Ms_Mo13.py 115 MD10
"""
import sys
ii = int(sys.argv[1])
env = sys.argv[2] # 'MD10'
status = sys.argv[3]
import h5py # HDF5 support
import os
import glob
import numpy as n
h5_dir = os.path.join(os.environ[env], 'cluster_h5/' )
input_list = n.arra... | [
"numpy.log10",
"os.path.join",
"astropy.cosmology.FlatLambdaCDM",
"scipy.stats.norm.rvs",
"h5py.File"
] | [((255, 299), 'os.path.join', 'os.path.join', (['os.environ[env]', '"""cluster_h5/"""'], {}), "(os.environ[env], 'cluster_h5/')\n", (267, 299), False, 'import os\n'), ((569, 627), 'astropy.cosmology.FlatLambdaCDM', 'FlatLambdaCDM', ([], {'H0': '(67.77 * u.km / u.s / u.Mpc)', 'Om0': '(0.307115)'}), '(H0=67.77 * u.km / u... |
"""
==========
Polar plot
==========
Demo of a line plot on a polar axis.
"""
import numpy as np
import matplotlib.pyplot as plt
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2]) # Less radial ... | [
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((136, 157), 'numpy.arange', 'np.arange', (['(0)', '(2)', '(0.01)'], {}), '(0, 2, 0.01)\n', (145, 157), True, 'import numpy as np\n'), ((191, 239), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'subplot_kw': "{'projection': 'polar'}"}), "(subplot_kw={'projection': 'polar'})\n", (203, 239), True, 'import matplotl... |
import numpy as np
import tensorflow as tf
from scipy.special import loggamma
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Concatenate, Dense, Lambda, Multiply
class TFWeibullDistribution:
@staticmethod
def log_likelihood(x: tf.Tensor, alpha: tf.Tensor, beta: tf.Tensor):
... | [
"tensorflow.keras.losses.MeanAbsoluteError",
"tensorflow.math.pow",
"tensorflow.keras.backend.log",
"tensorflow.keras.backend.mean",
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.layers.Multiply",
"numpy.power",
"tensorflow.keras.backend.greater",
"tensorflow.math.log",
"tensorflow.math... | [((766, 806), 'tensorflow.print', 'tf.print', (['term_1', 'term_2', 'term_3', 'term_4'], {}), '(term_1, term_2, term_3, term_4)\n', (774, 806), True, 'import tensorflow as tf\n'), ((822, 867), 'tensorflow.keras.backend.mean', 'K.mean', (['(term_1 - term_2 + term_3 + term_4 - 1)'], {}), '(term_1 - term_2 + term_3 + term... |
# -*- encoding:utf-8 -*-
import torch.nn.functional as F
import torch.optim.lr_scheduler
import numpy as np
from uer.models.model import Model
from uer.model_builder import build_model
from uer.layers.layer_norm import LayerNorm
from uer.utils.act_fun import gelu
import torch.nn as nn
from torch.autograd import Variab... | [
"numpy.eye",
"numpy.sqrt",
"torch.autograd.Variable",
"torch.nn.LeakyReLU",
"numpy.max",
"uer.model_builder.build_model",
"numpy.sum",
"numpy.zeros",
"numpy.isfinite",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.Linear",
"uer.layers.layer_norm.LayerNorm",
"torch.nn.LogSoftmax",
"t... | [((552, 571), 'numpy.eye', 'np.eye', (['output_size'], {}), '(output_size)\n', (558, 571), True, 'import numpy as np\n'), ((3614, 3706), 'torch.nn.utils.rnn.pack_padded_sequence', 'nn.utils.rnn.pack_padded_sequence', (['wemb_l[perm_idx, :, :]', 'l[perm_idx]'], {'batch_first': '(True)'}), '(wemb_l[perm_idx, :, :], l[per... |
from math import ceil, floor
import numpy as np
from BoundingBox import BoundingBox
def fibonacci_sphere_section(num_points_whole_sphere: int, bbox: BoundingBox):
lat_min, lat_max, lon_min, lon_max = bbox.lat_min, bbox.lat_max, bbox.lon_min, bbox.lon_max
#print("lat_min: {}, lat_max: {}, lon_min: {}, lon_max: ... | [
"numpy.sqrt",
"math.ceil",
"numpy.floor",
"numpy.array",
"numpy.cos",
"numpy.sin"
] | [((627, 642), 'numpy.sin', 'np.sin', (['lat_min'], {}), '(lat_min)\n', (633, 642), True, 'import numpy as np\n'), ((656, 671), 'numpy.sin', 'np.sin', (['lat_max'], {}), '(lat_max)\n', (662, 671), True, 'import numpy as np\n'), ((1266, 1298), 'math.ceil', 'ceil', (['((i_max - i_min_0) / repeat)'], {}), '((i_max - i_min_... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 23:52:06 2018
@author: malti
"""
#music notic is a collecion of fundamental tones and harmonics or overtones.
import numpy as np
import soundfile as sf
import sounddevice as sd
amp = [1,1]
amp_a = [[1,0,0,0],[1,1/2,1/3,1/4]]
freq = [1000,440]
... | [
"numpy.linspace",
"sounddevice.wait",
"numpy.size",
"numpy.cos"
] | [((530, 578), 'numpy.linspace', 'np.linspace', (['(0)', 'duration', '(sample_rate * duration)'], {}), '(0, duration, sample_rate * duration)\n', (541, 578), True, 'import numpy as np\n'), ((918, 951), 'numpy.linspace', 'np.linspace', (['(0)', 'lent', '(lent * rate)'], {}), '(0, lent, lent * rate)\n', (929, 951), True, ... |
from functools import partial
import numpy as np
import torch
from torch import nn
from counterfactualms.arch.layers import Conv2d, ConvTranspose2d
class HierarchicalEncoder(nn.Module):
def __init__(self, num_convolutions=3, filters=(16,32,64,128,256), latent_dim=100,
input_size=(1,128,128), us... | [
"torch.nn.BatchNorm2d",
"torch.nn.Sigmoid",
"numpy.prod",
"torch.nn.LeakyReLU",
"torch.nn.ModuleList",
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"numpy.array",
"functools.partial",
"torch.nn.Upsample",
"torch.nn.Linear",
"torch.randn"
] | [((8633, 8650), 'torch.randn', 'torch.randn', (['(2)', '(4)'], {}), '(2, 4)\n', (8644, 8650), False, 'import torch\n'), ((8659, 8685), 'torch.randn', 'torch.randn', (['(2)', '*img_shape'], {}), '(2, *img_shape)\n', (8670, 8685), False, 'import torch\n'), ((882, 899), 'torch.nn.ModuleList', 'nn.ModuleList', (['[]'], {})... |
import numpy as np
from nose.tools import raises
from chainer import Variable
from chainer.testing import assert_allclose
from chainer.gradient_check import check_backward
from chainer.utils.type_check import InvalidType
from chainerltr.functions.logcumsumexp import logcumsumexp
def test_logcumsumexp_forward_2d():
... | [
"numpy.ones",
"chainer.Variable",
"chainerltr.functions.logcumsumexp.logcumsumexp",
"numpy.array",
"nose.tools.raises",
"chainer.testing.assert_allclose"
] | [((966, 985), 'nose.tools.raises', 'raises', (['InvalidType'], {}), '(InvalidType)\n', (972, 985), False, 'from nose.tools import raises\n'), ((1072, 1091), 'nose.tools.raises', 'raises', (['InvalidType'], {}), '(InvalidType)\n', (1078, 1091), False, 'from nose.tools import raises\n'), ((326, 372), 'numpy.array', 'np.a... |
import pytest
import os,shutil,sys
import numpy as np
from mpi4py import MPI
from pypospack.pyposmat.data import PyposmatConfigurationFile
from pypospack.pyposmat.engines import PyposmatIterativeSampler
pyposmat_data_dir = 'data'
config_fn = os.path.join(pyposmat_data_dir,'pyposmat.config.in')
def test__determine_... | [
"numpy.array_equal",
"os.path.join",
"pypospack.pyposmat.engines.PyposmatIterativeSampler"
] | [((245, 298), 'os.path.join', 'os.path.join', (['pyposmat_data_dir', '"""pyposmat.config.in"""'], {}), "(pyposmat_data_dir, 'pyposmat.config.in')\n", (257, 298), False, 'import os, shutil, sys\n'), ((380, 438), 'pypospack.pyposmat.engines.PyposmatIterativeSampler', 'PyposmatIterativeSampler', ([], {'configuration_filen... |
#! /usr/bin/env python
# 'http://stackoverflow.com/questions/31588584/
# pyqt-qtableview-prohibitibily-slow-when-scrolling-with-large-data-sets
# /31591015#31591015'
# TreeGraphModel modeified from:
# http://www.yasinuludag.com/blog/?p=98
from PyQt4 import QtCore
import numpy as np
import pandas as pd
class ... | [
"PyQt4.QtCore.pyqtSignal",
"PyQt4.QtCore.QAbStractTableModel.event",
"numpy.array",
"PyQt4.QtCore.QAbstractTableModel.__init__",
"pandas.DataFrame",
"numpy.shape"
] | [((2260, 2285), 'PyQt4.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['object'], {}), '(object)\n', (2277, 2285), False, 'from PyQt4 import QtCore\n'), ((689, 738), 'PyQt4.QtCore.QAbstractTableModel.__init__', 'QtCore.QAbstractTableModel.__init__', (['self', 'parent'], {}), '(self, parent)\n', (724, 738), False, 'from PyQt... |
import numpy as np
class MiniBatch:
def __init__(self, X: np.array, y: np.array, n, batch_size=1, shuffle=True):
"""
Creates iterator throw given data
:param X: features array
:param y: marks array
:param n: number of elements
:param batch_size: mini-batch size
... | [
"numpy.array",
"numpy.random.seed",
"numpy.arange"
] | [((1010, 1022), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (1019, 1022), True, 'import numpy as np\n'), ((1031, 1054), 'numpy.random.seed', 'np.random.seed', (['indices'], {}), '(indices)\n', (1045, 1054), True, 'import numpy as np\n'), ((1179, 1191), 'numpy.array', 'np.array', (['X_'], {}), '(X_)\n', (1187, 11... |
import argparse
import warnings
from typing import Tuple, Callable
import numpy as np
from PIL import Image
from sklearn.utils.extmath import randomized_svd
warnings.filterwarnings("ignore")
# Aliases
Matrix = np.ndarray
SVD = Tuple[Matrix, Matrix, Matrix]
EVD = Tuple[Matrix, Matrix, Matrix]
def sklearn_svd(matrix... | [
"sklearn.utils.extmath.randomized_svd",
"numpy.copy",
"PIL.Image.open",
"numpy.sqrt",
"numpy.linalg.eig",
"argparse.ArgumentParser",
"PIL.Image.fromarray",
"numpy.diag",
"numpy.argsort",
"numpy.errstate",
"numpy.zeros",
"numpy.concatenate",
"numpy.expand_dims",
"warnings.filterwarnings"
] | [((159, 192), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (182, 192), False, 'import warnings\n'), ((392, 451), 'sklearn.utils.extmath.randomized_svd', 'randomized_svd', (['matrix'], {'n_components': 'n_components'}), '(matrix, n_components=n_components, **kwargs)\n', (... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import pickle
from image_thresholding import *
from plotting_helpers import *
from line_fit import *
# *** PIPELINE ***
# Get image
# img_name = " - No parallel lanes (1.5)_2.jpg"
name = "straight_lines2"
img_na... | [
"numpy.dstack",
"cv2.getPerspectiveTransform",
"numpy.hstack",
"matplotlib.image.imread",
"cv2.undistort",
"matplotlib.image.imsave",
"cv2.putText",
"cv2.addWeighted",
"cv2.warpPerspective",
"numpy.vstack",
"numpy.int_",
"numpy.zeros_like",
"numpy.float32"
] | [((362, 384), 'matplotlib.image.imread', 'mpimg.imread', (['img_name'], {}), '(img_name)\n', (374, 384), True, 'import matplotlib.image as mpimg\n'), ((739, 779), 'cv2.undistort', 'cv2.undistort', (['img', 'mtx', 'dist', 'None', 'mtx'], {}), '(img, mtx, dist, None, mtx)\n', (752, 779), False, 'import cv2\n'), ((1329, 1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["setup", "update_list", "update_database", "write_tweet"]
import os
import json
import nltk
import tweepy
import string
import numpy as np
import cPickle as pickle
from collections import defaultdict
PROJECTNAME... | [
"os.path.exists",
"cPickle.dump",
"nltk.word_tokenize",
"numpy.random.choice",
"tweepy.API",
"collections.defaultdict",
"json.load",
"cPickle.load",
"json.dump",
"tweepy.OAuthHandler"
] | [((490, 519), 'os.path.exists', 'os.path.exists', (['SETTINGS_FILE'], {}), '(SETTINGS_FILE)\n', (504, 519), False, 'import os\n'), ((824, 898), 'tweepy.OAuthHandler', 'tweepy.OAuthHandler', (["settings['consumer_key']", "settings['consumer_secret']"], {}), "(settings['consumer_key'], settings['consumer_secret'])\n", (8... |
'''
Authors: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
If this code is useful to you, please cite the following paper:
<NAME>, <NAME>, and <NAME>. Learning topology from synthetic data for unsupervised depth completion.
In the Robotics and Automation Letters (RA-L) 2021 and Proceedings of International Conference on Robotics... | [
"os.path.exists",
"data_utils.write_paths",
"sys.path.insert",
"numpy.ones",
"os.makedirs",
"numpy.unique",
"os.path.join",
"skimage.morphology.convex_hull_image",
"os.path.basename",
"multiprocessing.Pool",
"data_utils.save_validity_map",
"cv2.resize",
"data_utils.save_depth",
"cv2.imread... | [((778, 803), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""src"""'], {}), "(0, 'src')\n", (793, 803), False, 'import sys, os, glob\n'), ((877, 923), 'os.path.join', 'os.path.join', (['"""data"""', '"""kitti_depth_completion"""'], {}), "('data', 'kitti_depth_completion')\n", (889, 923), False, 'import sys, os, glo... |
from pepnet.encoder import Encoder
from nose.tools import eq_
import numpy as np
def test_encoder_index_lists():
encoder = Encoder()
S_idx = encoder.index_dict["S"]
A_idx = encoder.index_dict["A"]
index_lists = encoder.encode_index_lists(["SSS", "AAA", "SAS"])
eq_(index_lists, [
[S_idx, S_i... | [
"numpy.array",
"nose.tools.eq_",
"pepnet.encoder.Encoder"
] | [((128, 137), 'pepnet.encoder.Encoder', 'Encoder', ([], {}), '()\n', (135, 137), False, 'from pepnet.encoder import Encoder\n'), ((282, 373), 'nose.tools.eq_', 'eq_', (['index_lists', '[[S_idx, S_idx, S_idx], [A_idx, A_idx, A_idx], [S_idx, A_idx, S_idx]]'], {}), '(index_lists, [[S_idx, S_idx, S_idx], [A_idx, A_idx, A_i... |
import numpy as np
import logging
class Tracker():
def __init__(self):
self.current_tracks = [] ### List of all tracks
self.temp_tracks = [] ### List of temporary tracks
self.temp_track_len = 3 ### How much tracks to collect before merging into main track
self.thresh_distance ... | [
"numpy.array",
"logging.debug",
"numpy.linalg.norm"
] | [((7587, 7695), 'numpy.array', 'np.array', (['[new_x - half_width, new_y - half_height, new_x + half_width, new_y +\n half_height, first[-1]]'], {}), '([new_x - half_width, new_y - half_height, new_x + half_width, \n new_y + half_height, first[-1]])\n', (7595, 7695), True, 'import numpy as np\n'), ((836, 863), 'l... |
"""
假设有一个带有标签的样本数据集(训练样本集),其中包含每条数据与所属分类的对应关系。
输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进行比较。
计算新数据与样本数据集中每条数据的距离。
对求得的所有距离进行排序(从小到大,越小表示越相似)。
取前 k (k 一般小于等于 20 )个样本数据对应的分类标签。
求 k 个数据中出现次数最多的分类标签作为新数据的分类。
收集数据:提供文本文件
准备数据:使用 Python 解析文本文件
分析数据:使用 Matplotlib 画二维散点图
训练算法:此步骤不适用于 k-近邻算法
测试算法:使用海伦提供的部分数据作为测试样本。
测试样本和非测试样本... | [
"matplotlib.pyplot.figure",
"numpy.ma.array",
"matplotlib.pyplot.show"
] | [((892, 904), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (902, 904), True, 'import matplotlib.pyplot as plt\n'), ((1114, 1124), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1122, 1124), True, 'import matplotlib.pyplot as plt\n'), ((1083, 1102), 'numpy.ma.array', 'np.ma.array', (['vector'], ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 11:33:00 2019
@author: Peter
"""
import os, h5py
from uclahedp.tools import hdf as hdftools
from uclahedp.tools import dataset
import numpy as np
import matplotlib.pyplot as plt
def abs_phase(sig, ref):
#Calculate the ffts
ref_fft = np.fft.fft(ref)
s... | [
"uclahedp.tools.dataset.createDataset",
"numpy.conj",
"numpy.unwrap",
"numpy.fft.fft",
"numpy.argmax",
"os.path.join",
"numpy.angle",
"h5py.File",
"numpy.fft.ifft"
] | [((298, 313), 'numpy.fft.fft', 'np.fft.fft', (['ref'], {}), '(ref)\n', (308, 313), True, 'import numpy as np\n'), ((329, 344), 'numpy.fft.fft', 'np.fft.fft', (['sig'], {}), '(sig)\n', (339, 344), True, 'import numpy as np\n'), ((490, 519), 'numpy.argmax', 'np.argmax', (['ref_fft[1:nyquist]'], {}), '(ref_fft[1:nyquist])... |
"""Module for Bresenham kernel"""
import numpy as np
from copa_map.util.occ_grid import OccGrid
import cv2
class KernelGrid(OccGrid):
"""Class for creating an occupation map with widened walls"""
def __init__(self, base_occ_map: OccGrid, digitize_size=0.2, num_of_borders=2):
"""
Constructor
... | [
"numpy.ones",
"numpy.logical_and",
"cv2.dilate",
"numpy.array",
"cv2.resize",
"numpy.arange"
] | [((1139, 1252), 'cv2.resize', 'cv2.resize', (['base_occ_map.img'], {'dsize': '(new_img_size[1], new_img_size[0])', 'interpolation': 'cv2.INTER_NEAREST_EXACT'}), '(base_occ_map.img, dsize=(new_img_size[1], new_img_size[0]),\n interpolation=cv2.INTER_NEAREST_EXACT)\n', (1149, 1252), False, 'import cv2\n'), ((2317, 234... |
"""Test file to visualize detected trail lines from videos"""
# Usage --> python Trackviz.py 3
# 0 --> Amtala
# 1 --> Bamoner
# 2 --> Diamond
# 3 --> Fotepore
# 4 --> Gangasagar
import cv2
import json
import math
import time
import sys
import matplotlib.pyplot as plt
from matplotlib import style
i... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.clf",
"numpy.asarray",
"os.path.join",
"numpy.append",
"numpy.zeros",
"matplotlib.style.use",
"json.load",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"... | [((633, 652), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (642, 652), False, 'from matplotlib import style\n'), ((653, 684), 'matplotlib.pyplot.title', 'plt.title', (['"""Tracking distances"""'], {}), "('Tracking distances')\n", (662, 684), True, 'import matplotlib.pyplot as plt\n'), ((... |
import numpy as np
from imread import ijrois
from . import file_path
def test_rois_smoke():
rois = ijrois.read_roi_zip(file_path('rois.zip'))
assert len(rois) == 4
r = ijrois.read_roi(open(file_path('0186-0099.roi'), 'rb'))
assert any([np.array_equal(ri, r) for ri in rois])
| [
"numpy.array_equal"
] | [((255, 276), 'numpy.array_equal', 'np.array_equal', (['ri', 'r'], {}), '(ri, r)\n', (269, 276), True, 'import numpy as np\n')] |
from pathlib import Path
from sklearn.model_selection import train_test_split
import numpy as np
from livelossplot.keras import PlotLossesCallback
import matplotlib.pyplot as plt
import seaborn as sns
from hyperas.distributions import uniform, choice
from hyperopt import Trials, STATUS_OK, tpe
from hyperas im... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"hyperas.optim.minimize",
"keras.models.Sequential",
"keras.layers.Dense",
"hyperas.distributions.uniform",
"numpy.random.seed",
"hyperas.distributions.choice",
"pandas.DataFrame",
"hyperopt.Trials"
] | [((962, 975), 'numpy.random.seed', 'seed', (['(9251996)'], {}), '(9251996)\n', (966, 975), False, 'from numpy.random import seed\n'), ((1011, 1066), 'pandas.read_csv', 'pd.read_csv', (['"""train_values.csv"""'], {'index_col': '"""patient_id"""'}), "('train_values.csv', index_col='patient_id')\n", (1022, 1066), True, 'i... |
#!/usr/bin/python
import numpy as np
from mnist import load_mnist
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (3,3)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
plt.ion()
def binaryze_dataset(data, threshold=0.5):
new_data = np.zeros(np.shape(data))
n... | [
"matplotlib.pyplot.imshow",
"numpy.reshape",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ion",
"mnist.load_mnist",
"numpy.shape",
"matplotlib.pyplot.subplot",
"numpy.random.binomial",
"matplotlib.pyplot.show"
] | [((221, 230), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (228, 230), True, 'import matplotlib.pyplot as plt\n'), ((1053, 1118), 'mnist.load_mnist', 'load_mnist', ([], {'path': '"""../datasets/mnist/downloads/"""', 'digits': '[0, 1, 2]'}), "(path='../datasets/mnist/downloads/', digits=[0, 1, 2])\n", (1063, 11... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
def funcion(x,y=2):
return x + 2 + y
print('El resultado de la funcion basica es: ', funcion(2))
def funcion_basic(x):
return np.sin(x)
print('El resultado operacion de la funcion lamda es: ', funcion_bas... | [
"numpy.sin"
] | [((241, 250), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (247, 250), True, 'import numpy as np\n')] |
# std libs
import warnings
# third-party libs
import numpy as np
from numpy.lib.stride_tricks import as_strided
def _checks(wsize, overlap, n, axis):
# checks
if n < wsize < 0:
raise ValueError(f'Window size ({wsize}) should be greater than 0 and '
f'smaller than array size (... | [
"numpy.insert",
"numpy.ma.is_masked",
"numpy.ma.isMA",
"numpy.ma.array",
"recipes.lists.tally",
"numpy.lib.stride_tricks.as_strided",
"numpy.asanyarray",
"numpy.zeros",
"warnings.warn",
"numpy.pad",
"numpy.arange"
] | [((1658, 1674), 'numpy.asanyarray', 'np.asanyarray', (['a'], {}), '(a)\n', (1671, 1674), True, 'import numpy as np\n'), ((2214, 2227), 'numpy.ma.isMA', 'np.ma.isMA', (['a'], {}), '(a)\n', (2224, 2227), True, 'import numpy as np\n'), ((2552, 2568), 'numpy.asanyarray', 'np.asanyarray', (['a'], {}), '(a)\n', (2565, 2568),... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 14:58:38 2021
@author: TD
"""
import numpy as np
class GLM:
def __init__(self, basis_funcs=([lambda x: np.ones_like(x), lambda x:x],)):
"""
Parameters
----------
basis_funcs : list or tuple
List of lists of functio... | [
"numpy.identity",
"numpy.ones_like",
"numpy.linalg.det",
"numpy.diag",
"numpy.array",
"numpy.dot",
"numpy.linalg.inv"
] | [((1104, 1116), 'numpy.dot', 'np.dot', (['B', 'y'], {}), '(B, y)\n', (1110, 1116), True, 'import numpy as np\n'), ((2284, 2299), 'numpy.dot', 'np.dot', (['A', 'beta'], {}), '(A, beta)\n', (2290, 2299), True, 'import numpy as np\n'), ((3985, 3999), 'numpy.dot', 'np.dot', (['A.T', 'W'], {}), '(A.T, W)\n', (3991, 3999), T... |
from __future__ import print_function, division
#
import sys,os
quspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,quspin_path)
#
from quspin.operators import hamiltonian, exp_op # Hamiltonians, operators and exp_op
from quspin.basis import spin_basis_1d # Hilbert space spin basis
import numpy as np # g... | [
"sys.path.insert",
"quspin.operators.exp_op",
"quspin.operators.hamiltonian",
"os.getcwd",
"quspin.basis.spin_basis_1d",
"numpy.zeros"
] | [((113, 144), 'sys.path.insert', 'sys.path.insert', (['(0)', 'quspin_path'], {}), '(0, quspin_path)\n', (128, 144), False, 'import sys, os\n'), ((506, 524), 'quspin.basis.spin_basis_1d', 'spin_basis_1d', ([], {'L': 'L'}), '(L=L)\n', (519, 524), False, 'from quspin.basis import spin_basis_1d\n'), ((803, 862), 'quspin.op... |
# Run the labyrinth navigation experiment.
# %%
from Environments.unity_labyrinth import build_unity_labyrinth_env
import numpy as np
from Controllers.unity_labyrinth_controller import UnityLabyrinthController
from Controllers.unity_meta_controller import MetaController
import pickle
import os, sys
from datetime impo... | [
"Controllers.unity_labyrinth_controller.UnityLabyrinthController",
"torch.manual_seed",
"os.listdir",
"Environments.unity_labyrinth.build_unity_labyrinth_env",
"utils.results_saver.Results",
"os.path.join",
"Controllers.unity_meta_controller.MetaController",
"random.seed",
"numpy.argmax",
"datetim... | [((523, 550), 'Environments.unity_labyrinth.build_unity_labyrinth_env', 'build_unity_labyrinth_env', ([], {}), '()\n', (548, 550), False, 'from Environments.unity_labyrinth import build_unity_labyrinth_env\n'), ((1169, 1200), 'os.path.abspath', 'os.path.abspath', (['os.path.curdir'], {}), '(os.path.curdir)\n', (1184, 1... |
import numpy as np
import uncertainties.unumpy as unp
def center():
return [2, 3] # or the arg-number of the center.
def args():
return 'amp', 'x0', 'y0', 'sig_x', 'sig_y', 'theta', 'offset'
def f(coordinates, amplitude, xo, yo, sigma_x, sigma_y, offset):
"""
The normal function call for this functio... | [
"numpy.exp"
] | [((998, 1040), 'numpy.exp', 'np.exp', (['(-(a * xp ** 2 + c * (y - yo) ** 2))'], {}), '(-(a * xp ** 2 + c * (y - yo) ** 2))\n', (1004, 1040), True, 'import numpy as np\n')] |
from __future__ import division
import numpy as np
import logging
logger = logging.getLogger(__name__)
__all__ = ['tmvtnorm_sample', 'tmvtnorm_rpy2', 'tmvtnorm_emcee']
def importr_tryhard(packname):
"""
Load R package. If package cannot be loaded then install. If you have problems with this function, try mak... | [
"logging.getLogger",
"numpy.mean",
"numpy.ceil",
"numpy.tile",
"rpy2.robjects.vectors.StrVector",
"numpy.any",
"rpy2.robjects.packages.importr",
"numpy.ndarray.flatten",
"numpy.dot",
"numpy.linalg.inv",
"logging.critical",
"numpy.random.uniform",
"numpy.var",
"matplotlib.pyplot.show"
] | [((75, 102), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (92, 102), False, 'import logging\n'), ((678, 704), 'rpy2.robjects.packages.importr', 'rpackages.importr', (['"""utils"""'], {}), "('utils')\n", (695, 704), True, 'import rpy2.robjects.packages as rpackages\n'), ((6868, 6895), 'n... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 15:53:51 2016
@author: jdorvinen
"""
import numpy as np
def kriebel_dean(w_cm, B, D, W, m, S, T_d, H_b, gamma=0.78):
'''Calculates storm erosion based on the method presented in,
<NAME>., and <NAME>., 'Convolution method for time-dependent
beach-profile ... | [
"numpy.exp",
"numpy.sin",
"numpy.cos",
"scipy.optimize.brentq"
] | [((4637, 4677), 'scipy.optimize.brentq', 'opt.brentq', (['find_t_max'], {'a': '(T_d / 2)', 'b': 'T_d'}), '(find_t_max, a=T_d / 2, b=T_d)\n', (4647, 4677), True, 'import scipy.optimize as opt\n'), ((5996, 6019), 'numpy.exp', 'exp', (['(-1 * interim / T_a)'], {}), '(-1 * interim / T_a)\n', (5999, 6019), False, 'from nump... |
import math
import numpy as np
from openmdao.api import ScipyOptimizeDriver
from ema.core.problems.benchmark_problem import BenchmarkProblem
from ema.core.models.mdf_models import Actuator, ActuatorBlackBox
import matplotlib.pyplot as plt
class MDFProblem(BenchmarkProblem):
def __init__(self, **kwargs):
... | [
"numpy.mean",
"math.isclose",
"ema.core.models.mdf_models.ActuatorBlackBox",
"numpy.max",
"matplotlib.pyplot.subplots",
"openmdao.api.ScipyOptimizeDriver",
"ema.core.models.mdf_models.Actuator",
"matplotlib.pyplot.show"
] | [((427, 527), 'ema.core.models.mdf_models.Actuator', 'Actuator', ([], {'optimizer': 'self.optimizer', 'derivative_method': 'self.derivative_method', 'N': 'self.N', 't': 'self.t'}), '(optimizer=self.optimizer, derivative_method=self.derivative_method,\n N=self.N, t=self.t)\n', (435, 527), False, 'from ema.core.models... |
import numpy as np
from PIL import Image
from feature_extractor import FeatureExtractor
from datetime import datetime
from flask import Flask, request, render_template ,jsonify
from pathlib import Path
from flask import jsonify
from io import BytesIO
import base64
import re
from urllib.request import urlopen
import jso... | [
"flask.render_template",
"pathlib.Path",
"flask.Flask",
"flask.jsonify",
"base64.b64decode",
"numpy.argsort",
"numpy.array",
"datetime.datetime.now",
"flask.request.values.get",
"numpy.linalg.norm",
"re.sub",
"numpy.load",
"urllib.request.urlopen",
"feature_extractor.FeatureExtractor"
] | [((329, 344), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (334, 344), False, 'from flask import Flask, request, render_template, jsonify\n'), ((1001, 1019), 'feature_extractor.FeatureExtractor', 'FeatureExtractor', ([], {}), '()\n', (1017, 1019), False, 'from feature_extractor import FeatureExtractor\n'... |
"""
"""
import numpy
import os
import pickle
import shutil
import tarfile
from six.moves import range, urllib
import datasets
class SourceCifar10(object):
"""
"""
@staticmethod
def default_data_path(dataset):
"""
"""
path_home = os.path.expanduser('~')
return os.path... | [
"os.listdir",
"six.moves.range",
"tarfile.open",
"os.makedirs",
"shutil.move",
"numpy.arange",
"os.path.join",
"pickle.load",
"os.path.isfile",
"numpy.array",
"numpy.zeros",
"os.path.isdir",
"six.moves.urllib.request.urlretrieve",
"numpy.concatenate",
"shutil.rmtree",
"os.path.expandus... | [((273, 296), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (291, 296), False, 'import os\n'), ((313, 371), 'os.path.join', 'os.path.join', (['path_home', '"""datasets"""', '"""cifar-10-batches-py"""'], {}), "(path_home, 'datasets', 'cifar-10-batches-py')\n", (325, 371), False, 'import os\n'... |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(0, 10, 100)
y1 = x**2 + 1
y2 = x
plt.figure('LearnPLT')
plt.plot(x, y1, c='r')
plt.plot(x, y2, c='g')
plt.show()
plt.figure('Continue learning PLT')
new_ticks = np.linspace(0, 100, 11)
print(new_ticks)
plt.xtick... | [
"numpy.sqrt",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"numpy.arctan2",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"matplotlib... | [((96, 119), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(100)'], {}), '(0, 10, 100)\n', (107, 119), True, 'import numpy as np\n'), ((141, 163), 'matplotlib.pyplot.figure', 'plt.figure', (['"""LearnPLT"""'], {}), "('LearnPLT')\n", (151, 163), True, 'import matplotlib.pyplot as plt\n'), ((164, 186), 'matplotlib.p... |
"""Roughness helper functions"""
import os
import contextlib
from pathlib import Path
import numpy as np
import numpy.f2py
import xarray as xr
import jupytext
from . import config as cfg
from . import __version__
# Line of sight helpers
def lookup2xarray(lookups):
"""
Convert list of default lookups to xarray.... | [
"numpy.radians",
"numpy.arccos",
"numpy.sqrt",
"pathlib.Path",
"pathlib.Path.cwd",
"xarray.ones_like",
"jupytext.read",
"os.chdir",
"numpy.sum",
"numpy.linspace",
"numpy.arctan2",
"numpy.cos",
"xarray.DataArray",
"numpy.sin",
"numpy.meshgrid",
"numpy.zeros_like"
] | [((1891, 1937), 'xarray.DataArray', 'xr.DataArray', (['arr'], {'coords': 'coords_xr', 'name': 'name'}), '(arr, coords=coords_xr, name=name)\n', (1903, 1937), True, 'import xarray as xr\n'), ((2197, 2244), 'xarray.DataArray', 'xr.DataArray', (['arr'], {'coords': "[('wavelength', arr)]"}), "(arr, coords=[('wavelength', a... |
import PIL as PIL
import pytesseract as tess
import matplotlib.pyplot as plt
import numpy as np
class Img2Str:
def __init__(self, img_path=None):
self.img_path = img_path
self.image = None
def load_image(self, img_path):
self.img_path = img_path
self.image = PIL.Image.open(img... | [
"matplotlib.pyplot.imshow",
"PIL.Image.open",
"numpy.asarray",
"matplotlib.pyplot.figure",
"pytesseract.image_to_string",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
] | [((302, 326), 'PIL.Image.open', 'PIL.Image.open', (['img_path'], {}), '(img_path)\n', (316, 326), True, 'import PIL as PIL\n'), ((556, 588), 'pytesseract.image_to_string', 'tess.image_to_string', (['self.image'], {}), '(self.image)\n', (576, 588), True, 'import pytesseract as tess\n'), ((1176, 1198), 'numpy.asarray', '... |
import numpy as np
from math import factorial
from numpy.ma import masked_array
import scipy
from scipy.special import factorial
import scipy.stats as stat
import pdb
#Define Zernike radial polynomials
def rnm(n,m,rho):
"""
Return an array with the zernike Rnm polynomial calculated at rho points.
**ARGUM... | [
"scipy.linalg.lstsq",
"numpy.sqrt",
"numpy.unique",
"numpy.where",
"scipy.special.factorial",
"numpy.size",
"numpy.sin",
"numpy.array",
"numpy.zeros",
"numpy.dot",
"numpy.arctan2",
"numpy.meshgrid",
"pdb.set_trace",
"numpy.isnan",
"numpy.cos",
"numpy.ma.masked_array",
"numpy.shape"
] | [((1006, 1037), 'numpy.where', 'np.where', (['(rho <= 1)', '(False)', '(True)'], {}), '(rho <= 1, False, True)\n', (1014, 1037), True, 'import numpy as np\n'), ((1135, 1160), 'numpy.where', 'np.where', (['(rho < 0)', '(0)', 'rho'], {}), '(rho < 0, 0, rho)\n', (1143, 1160), True, 'import numpy as np\n'), ((1165, 1184), ... |
from __future__ import print_function, division
import os
import torch
from skimage import io, transform
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms#, utils
import pickle
from pdb import set_trace as stop
from PIL import Image
import json, string, sys
import t... | [
"os.path.exists",
"nltk.corpus.stopwords.words",
"os.path.join",
"dataloaders.data_utils.get_unk_mask_indices",
"nltk.stem.WordNetLemmatizer",
"torch.Tensor",
"numpy.nonzero",
"numpy.load",
"numpy.save"
] | [((808, 827), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (825, 827), False, 'from nltk.stem import WordNetLemmatizer\n'), ((725, 751), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (740, 751), False, 'from nltk.corpus import stopwords\n'), ((2544,... |
import numpy as np
from numba import njit, jit, prange
@njit(parallel=True,nogil=True)
def generateColumnForward(gdimg):
forward = forwardEnergy(gdimg)
x = gdimg.shape[0]
y = gdimg.shape[1]
lastDir = np.zeros((x,y),np.int8)
energy = np.zeros((x,y),np.uint32)
for i in range(y):
energy[0... | [
"numpy.abs",
"numba.njit",
"numpy.zeros",
"numba.jit",
"numba.prange"
] | [((58, 89), 'numba.njit', 'njit', ([], {'parallel': '(True)', 'nogil': '(True)'}), '(parallel=True, nogil=True)\n', (62, 89), False, 'from numba import njit, jit, prange\n'), ((903, 936), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'parallel': '(True)'}), '(nopython=True, parallel=True)\n', (906, 936), False, 'from... |
import numpy as np
from matplotlib import pyplot as plt
class TreSlice:
def __init__(self, X, Y, Z, C):
self.data = C
self.axes = np.array([X, Y, Z])
self.labels = np.array(['X', 'Y', 'Z'])
self.views = np.array([[0, 1, 2], [1, 0, 2], [2, 0, 1]])
self.curAxis = 2
se... | [
"numpy.amin",
"numpy.rollaxis",
"numpy.take",
"numpy.array",
"matplotlib.pyplot.figure",
"sys.exit",
"numpy.load",
"numpy.amax",
"matplotlib.pyplot.show"
] | [((2041, 2061), 'numpy.load', 'np.load', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (2048, 2061), True, 'import numpy as np\n'), ((152, 171), 'numpy.array', 'np.array', (['[X, Y, Z]'], {}), '([X, Y, Z])\n', (160, 171), True, 'import numpy as np\n'), ((194, 219), 'numpy.array', 'np.array', (["['X', 'Y', 'Z']"], {}), "(['... |
import numpy as np
from math import inf as infinity
import itertools
import random
import pdb
import matplotlib.pyplot as plt
class TicTacToe(object):
def __init__(self):
self.game_state = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
self.agent_state = np.zeros((3,3)) #actual agent obs... | [
"random.choice",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"itertools.product",
"numpy.argmax",
"numpy.max",
"numpy.zeros",
"matplotlib.pyplot.title",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((7042, 7089), 'numpy.zeros', 'np.zeros', (['(number_of_states, number_of_actions)'], {}), '((number_of_states, number_of_actions))\n', (7050, 7089), True, 'import numpy as np\n'), ((7142, 7189), 'numpy.zeros', 'np.zeros', (['(number_of_states, number_of_actions)'], {}), '((number_of_states, number_of_actions))\n', (7... |
import numpy as np
import cv2
def triangulate(point1, point2, cam1, cam2):
""" triangulate point1 in cam1 with point2 in cam2
:param point1: [2,]
:param point2: [2,]
"""
point1 = np.expand_dims(point1, axis=1).astype('float64') # 2 x n
point2 = np.expand_dims(point2, axis=1).astype('float64')... | [
"numpy.mean",
"cv2.triangulatePoints",
"numpy.array",
"numpy.zeros",
"cv2.findFundamentalMat",
"numpy.expand_dims",
"cv2.computeCorrespondEpilines"
] | [((1238, 1260), 'numpy.mean', 'np.mean', (['pts3d'], {'axis': '(0)'}), '(pts3d, axis=0)\n', (1245, 1260), True, 'import numpy as np\n'), ((1474, 1502), 'numpy.array', 'np.array', (['point1', 'np.float64'], {}), '(point1, np.float64)\n', (1482, 1502), True, 'import numpy as np\n'), ((1963, 2351), 'numpy.array', 'np.arra... |
#!/usr/bin/python3
# Copyright (c) 2015 <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, p... | [
"numpy.hstack",
"numpy.array",
"parsy.Parser",
"parsy.alt",
"numpy.mean",
"argparse.ArgumentParser",
"dlib.shape_predictor",
"dlib.get_frontal_face_detector",
"parsy.string",
"tempfile.NamedTemporaryFile",
"json.loads",
"dropbox.Dropbox",
"cv2.warpAffine",
"hashlib.md5",
"parsy.regex",
... | [((1527, 1570), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""None"""'}), "(description='None')\n", (1550, 1570), False, 'import argparse\n'), ((2214, 2249), 'dropbox.Dropbox', 'dropbox.Dropbox', (['args.dropbox_token'], {}), '(args.dropbox_token)\n', (2229, 2249), False, 'import dropbo... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import random, copy
import matplotlib.cm as cm
import itertools
import scipy.stats
import math
import statistics
import pysan.multisequence as pysan_ms
from itertools import combinations
random.seed('1<PASSWORD>')
def gene... | [
"matplotlib.pyplot.rc_context",
"matplotlib.pyplot.grid",
"math.sqrt",
"math.log2",
"math.log",
"numpy.array",
"pysan.multisequence.get_synchrony",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.barh",
"matplotlib.pyplot.plot",
"numpy.empty",
"statistics.variance",
"pandas.D... | [((284, 310), 'random.seed', 'random.seed', (['"""1<PASSWORD>"""'], {}), "('1<PASSWORD>')\n", (295, 310), False, 'import random, copy\n'), ((5296, 5332), 'statistics.variance', 'statistics.variance', (['state_durations'], {}), '(state_durations)\n', (5315, 5332), False, 'import statistics\n'), ((5392, 5424), 'statistic... |
from __future__ import annotations
import numpy as np
from dask_awkward.data import load_array
from dask_awkward.utils import assert_eq
def test_ufunc_sin():
daa = load_array()
a1 = np.sin(daa)
a2 = np.sin(daa.compute())
assert_eq(a1, a2)
def test_ufunc_add():
daa = load_array()
a1 = daa
... | [
"numpy.sin",
"dask_awkward.data.load_array",
"dask_awkward.utils.assert_eq"
] | [((172, 184), 'dask_awkward.data.load_array', 'load_array', ([], {}), '()\n', (182, 184), False, 'from dask_awkward.data import load_array\n'), ((194, 205), 'numpy.sin', 'np.sin', (['daa'], {}), '(daa)\n', (200, 205), True, 'import numpy as np\n'), ((241, 258), 'dask_awkward.utils.assert_eq', 'assert_eq', (['a1', 'a2']... |
import numpy as np
from scipy.fft import dct, idct
import math
def idct_basis_2d(len_basis, num_basis):
'''
Generate basic 2D DCT basis for dictionary learning
Inputs:
len_basis: length of the flattened atom, e.g. 36 for 6x6 basis
num_basis: number of the atoms. usually it is o... | [
"numpy.kron",
"numpy.mean",
"math.ceil",
"numpy.linalg.norm"
] | [((641, 660), 'numpy.kron', 'np.kron', (['ODCT', 'ODCT'], {}), '(ODCT, ODCT)\n', (648, 660), True, 'import numpy as np\n'), ((764, 792), 'numpy.linalg.norm', 'np.linalg.norm', (['ODCT'], {'axis': '(0)'}), '(ODCT, axis=0)\n', (778, 792), True, 'import numpy as np\n'), ((1443, 1462), 'numpy.kron', 'np.kron', (['ODCT', 'O... |
import os
import numpy as np
from tqdm import tqdm
import pandas as pd
import recordlinkage
from recordlinkage.index import SortedNeighbourhood
import lib.utils as utils
class ApproxLinkage:
def __init__(self, storage_folder, parquet_folder):
'''
'''
self.storage = storage_folder... | [
"lib.utils.replace_string",
"recordlinkage.Compare",
"recordlinkage.Index",
"os.path.join",
"pandas.notna",
"recordlinkage.index.SortedNeighbourhood",
"numpy.arange"
] | [((5614, 5635), 'recordlinkage.Index', 'recordlinkage.Index', ([], {}), '()\n', (5633, 5635), False, 'import recordlinkage\n'), ((5749, 5772), 'recordlinkage.Compare', 'recordlinkage.Compare', ([], {}), '()\n', (5770, 5772), False, 'import recordlinkage\n'), ((853, 906), 'os.path.join', 'os.path.join', (['self.parquet_... |
# Author: <NAME>
# 2010 - 2011
"""Tools for spectral analysis of unequally sampled signals."""
import numpy as np
#pythran export lombscargle(float64[], float64[], float64[])
#runas import numpy; x = numpy.arange(2., 12.); y = numpy.arange(1., 11.); z = numpy.arange(3., 13.); lombscargle(x, y, z)
def lombscargle(x, ... | [
"numpy.sin",
"numpy.sum",
"numpy.arctan2",
"numpy.cos"
] | [((1043, 1069), 'numpy.cos', 'np.cos', (['(freqs[:, None] * x)'], {}), '(freqs[:, None] * x)\n', (1049, 1069), True, 'import numpy as np\n'), ((1078, 1104), 'numpy.sin', 'np.sin', (['(freqs[:, None] * x)'], {}), '(freqs[:, None] * x)\n', (1084, 1104), True, 'import numpy as np\n'), ((1114, 1135), 'numpy.sum', 'np.sum',... |
"""
Some convenience classes/functions for querying Horizons
Helps with tests of accuracy in various functions
"""
# import standard packages
# -----------------------------------------------------------------------------
import numpy as np
# import third-party packages
# ---------------------------------------------... | [
"numpy.array",
"astroquery.jplhorizons.Horizons"
] | [((698, 754), 'astroquery.jplhorizons.Horizons', 'Horizons', (['target', 'centre'], {'epochs': 'epochs', 'id_type': 'id_type'}), '(target, centre, epochs=epochs, id_type=id_type)\n', (706, 754), False, 'from astroquery.jplhorizons import Horizons\n'), ((1280, 1336), 'astroquery.jplhorizons.Horizons', 'Horizons', (['tar... |
import abc
import numpy as np
import homog as hm
from numpy.linalg import inv
from worms.util import jit
Ux = np.array([1, 0, 0, 0])
Uy = np.array([0, 1, 0, 0])
Uz = np.array([0, 0, 1, 0])
class WormCriteria(abc.ABC):
@abc.abstractmethod
def score(self, **kw):
pass
allowed_attributes = (
"last_b... | [
"numpy.array",
"numpy.zeros",
"numpy.empty_like",
"numpy.eye"
] | [((111, 133), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (119, 133), True, 'import numpy as np\n'), ((139, 161), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (147, 161), True, 'import numpy as np\n'), ((167, 189), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '... |
__author__ = "<NAME>"
"""
One should note, that R is required to use this module, as original Clifford's
program is written in R. On my Windows 10, I am using anaconda and I had to add
R_HOME env variable and R_path\bin, R_path\bin\x64 to the path.
https://cran.r-project.org/web/packages/BosonSampling... | [
"numpy.isclose",
"scipy.special.binom",
"rpy2.robjects.packages.importr",
"rpy2.robjects.r.matrix",
"numpy.array",
"numpy.array_split",
"collections.defaultdict",
"numpy.arange"
] | [((987, 1020), 'rpy2.robjects.packages.importr', 'packages.importr', (['"""BosonSampling"""'], {}), "('BosonSampling')\n", (1003, 1020), False, 'from rpy2.robjects import packages\n'), ((1585, 1651), 'rpy2.robjects.r.matrix', 'robjects.r.matrix', (['r_values'], {'nrow': 'rows_number', 'ncol': 'columns_number'}), '(r_va... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse
import csv
import numpy as np
from keras.models import Model
from keras.layers import Flatten, Input, Dense, Dropout
from keras.layers import Conv1D, MaxPooling1D
from keras.models import load_model
from keras.callba... | [
"keras.layers.MaxPooling1D",
"numpy.roll",
"keras.layers.Flatten",
"argparse.ArgumentParser",
"keras.callbacks.ModelCheckpoint",
"csv.writer",
"keras.callbacks.TensorBoard",
"numpy.array",
"keras.layers.Input",
"numpy.random.randint",
"keras.models.Model",
"numpy.random.seed",
"csv.reader",
... | [((396, 414), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (410, 414), True, 'import numpy as np\n'), ((3051, 3069), 'numpy.array', 'np.array', (['data_gen'], {}), '(data_gen)\n', (3059, 3069), True, 'import numpy as np\n'), ((3087, 3107), 'numpy.array', 'np.array', (['labels_gen'], {}), '(labels_ge... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 15:20:25 2019
@author: karad
"""
import numpy as np
import matplotlib.pyplot as plt
# depending on the number of files change the below parameters
#-----
it=10 # number of iterations
nrows=2 # number of rows
ncols=4 # number of columns (e.g. 4 processes -- 2row by 2... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.savefig",
"numpy.savetxt",
"numpy.concatenate",
"numpy.loadtxt"
] | [((1248, 1276), 'numpy.concatenate', 'np.concatenate', (['f[t]'], {'axis': '(0)'}), '(f[t], axis=0)\n', (1262, 1276), True, 'import numpy as np\n'), ((1298, 1316), 'matplotlib.pyplot.imshow', 'plt.imshow', (['matrix'], {}), '(matrix)\n', (1308, 1316), True, 'import matplotlib.pyplot as plt\n'), ((1321, 1356), 'matplotl... |
import numpy as np
from numpy import inf
import time
import random
def GS_static(graph, eps, alpha, seed, method ) :
# initial distribution
N = graph.A.shape[0]
y = np.zeros([N,1]); y[seed,0] = 1;
# extract operator and coefficients
if method == 'PageRank':
rho = (1-alpha)
psi = alpha;
OP = graph.P.T
g... | [
"numpy.eye",
"numpy.where",
"numpy.count_nonzero",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"numpy.sum",
"numpy.cos",
"numpy.expand_dims",
"numpy.linalg.norm",
"numpy.int",
"numpy.divide"
] | [((171, 187), 'numpy.zeros', 'np.zeros', (['[N, 1]'], {}), '([N, 1])\n', (179, 187), True, 'import numpy as np\n'), ((619, 635), 'numpy.zeros', 'np.zeros', (['[N, 1]'], {}), '([N, 1])\n', (627, 635), True, 'import numpy as np\n'), ((1329, 1345), 'numpy.zeros', 'np.zeros', (['[N, 1]'], {}), '([N, 1])\n', (1337, 1345), T... |
import os,sys
from torchvision import transforms
import torch, torch.utils
import numpy as np
from torch.utils.data import Dataset
import random
import PIL
import more_itertools as mit
from torch.utils.data.sampler import BatchSampler
class BalancedBatchSampler(BatchSampler):
#[set_id, in_path , x]
def __in... | [
"numpy.abs",
"os.listdir",
"more_itertools.windowed",
"random.shuffle",
"os.path.join",
"torch.Tensor",
"random.seed",
"numpy.max",
"numpy.array",
"numpy.random.randint",
"numpy.random.uniform",
"numpy.random.seed",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"numpy.p... | [((1135, 1153), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1149, 1153), True, 'import numpy as np\n'), ((10099, 10191), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': '(128)', 'num_workers': '(12)', 'shuffle': '(True)'}), '(train_dataset, batch_si... |
from __future__ import print_function
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.io as sio
import scipy.sparse as sp
import scipy.sparse.linalg as slinalg
import scipy.linalg as linalg
from scipy.sparse.linalg.eigen.arpack import eigsh
from sklearn.feature_extraction.text import TfidfTr... | [
"sklearn.feature_extraction.text.TfidfTransformer",
"numpy.hstack",
"numpy.logical_not",
"numpy.argsort",
"numpy.array",
"copy.deepcopy",
"scipy.sparse.isspmatrix_coo",
"numpy.arange",
"networkx.from_dict_of_lists",
"numpy.savez",
"scipy.sparse.eye",
"scipy.sparse.linalg.inv",
"numpy.where",... | [((593, 696), 'numpy.savez', 'np.savez', (['filename'], {'data': 'array.data', 'indices': 'array.indices', 'indptr': 'array.indptr', 'shape': 'array.shape'}), '(filename, data=array.data, indices=array.indices, indptr=array.\n indptr, shape=array.shape)\n', (601, 696), True, 'import numpy as np\n'), ((751, 768), 'nu... |
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Copyright (c) 2021 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | [
"Quanlse.Utils.Functions.computationalBasisList",
"Quanlse.remoteOptimizer.remoteIonGeneralMS",
"Quanlse.Utils.Plot.plotBarGraph",
"Quanlse.Utils.Functions.basis",
"numpy.arange"
] | [((2250, 2301), 'Quanlse.remoteOptimizer.remoteIonGeneralMS', 'runGeneralIonMS', (['gatePair'], {'args1': 'args1', 'args2': 'args2'}), '(gatePair, args1=args1, args2=args2)\n', (2265, 2301), True, 'from Quanlse.remoteOptimizer import remoteIonGeneralMS as runGeneralIonMS\n'), ((3025, 3053), 'Quanlse.Utils.Functions.com... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 17 May 2019
@author: <NAME>
"""
import os
import torch
import numpy as np
from torch import nn, optim
import matplotlib.pyplot as plt
class MultiLayerPerceptron:
"""
Multi Layer Perceptron
"""
def __init__(self, validation_rate, num_class... | [
"os.path.exists",
"torch.nn.ReLU",
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"torch.load",
"torch.max",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.path.join",
"numpy.array",
"torch.nn.Linear",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.... | [((1460, 1481), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1479, 1481), False, 'from torch import nn, optim\n'), ((3043, 3074), 'os.path.exists', 'os.path.exists', (['model_file_name'], {}), '(model_file_name)\n', (3057, 3074), False, 'import os\n'), ((3125, 3172), 'torch.load', 'torch.load'... |
import numpy as np
import torch
from pytorchrl.distributions.base import Distribution
from pytorchrl.misc.tensor_utils import constant
class DiagonalGaussian(Distribution):
"""
Instead of a distribution, rather a collection of distribution.
"""
def __init__(self, means, log_stds):
"""
... | [
"pytorchrl.misc.tensor_utils.constant",
"numpy.log",
"numpy.sqrt"
] | [((4057, 4072), 'pytorchrl.misc.tensor_utils.constant', 'constant', (['(1e-08)'], {}), '(1e-08)\n', (4065, 4072), False, 'from pytorchrl.misc.tensor_utils import constant\n'), ((4024, 4037), 'pytorchrl.misc.tensor_utils.constant', 'constant', (['(2.0)'], {}), '(2.0)\n', (4032, 4037), False, 'from pytorchrl.misc.tensor_... |
import sys
import datetime
import reportconfig
import projectmetrics
import os
import numpy as np
import matplotlib
import matplotlib.dates as mdates
# check for headless executions
if "DISPLAY" not in os.environ:
if os.system('python -c "import matplotlib.pyplot as plt; plt.figure()"') != 0:
print("INFO: ... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.dates.WeekdayLocator",
"matplotlib.dates.MonthLocator",
"matplotlib.use",
"reportconfig.ReportConfiguration",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.show",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.close",
"... | [((615, 638), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (628, 638), True, 'import matplotlib.pyplot as plt\n'), ((737, 757), 'matplotlib.dates.YearLocator', 'mdates.YearLocator', ([], {}), '()\n', (755, 757), True, 'import matplotlib.dates as mdates\n'), ((781, 802), 'matpl... |
#!/usr/bin/env python3
import numpy as np
import cv2
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
from sklearn.cluster import KMeans
from sklearn.neighbors import KernelDensity
import scipy
import scipy.signal
import math
import imutils
import img_util
def loadImage(path):
... | [
"numpy.mean",
"numpy.logical_and",
"numpy.round",
"cv2.HoughCircles",
"imutils.resize",
"numpy.zeros",
"cv2.circle",
"cv2.HoughLines",
"cv2.imread",
"cv2.blur"
] | [((488, 525), 'imutils.resize', 'imutils.resize', (['orig_image'], {'width': '(400)'}), '(orig_image, width=400)\n', (502, 525), False, 'import imutils\n'), ((572, 598), 'cv2.blur', 'cv2.blur', (['image', '(3, 3)', '(0)'], {}), '(image, (3, 3), 0)\n', (580, 598), False, 'import cv2\n'), ((647, 750), 'cv2.HoughCircles',... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 19:13:59 2018
First Try with Naive Bayes
https://www.analyticsvidhya.com/blog/2017/09/naive-bayes-explained/
@author: Tobi
'ScaledForward', 'scaledLeftRightRatio', 'ScaledSpeed',
'isTurningLeft', 'isTurningRight', 'isKeepingStraight',
... | [
"os.path.exists",
"os.path.getsize",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"keras.models.Sequential",
"os.chdir",
"numpy.array",
"os.path.isfile",
"numpy.random.seed",
"numpy.around",
"keras.layers.Dense",
"csv.reader"
] | [((697, 717), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (711, 717), True, 'import numpy as np\n'), ((1077, 1112), 'os.path.exists', 'os.path.exists', (['DATA_DUMP_DIRECTORY'], {}), '(DATA_DUMP_DIRECTORY)\n', (1091, 1112), False, 'import os\n'), ((5247, 5261), 'os.chdir', 'os.chdir', (['""".."... |
"""
# Custom colormap
This example shows how to create and use a custom colormap.
"""
import numpy as np
import numpy.random as nr
from datoviz import app, canvas, run, colormap
# Create the canvas, panel, and visual.
c = canvas(show_fps=True)
ctx = c.gpu().context()
panel = c.scene().panel(controller='panzoom')
v... | [
"numpy.ones",
"numpy.array",
"numpy.linspace",
"numpy.zeros",
"datoviz.run",
"datoviz.canvas",
"numpy.arange"
] | [((227, 248), 'datoviz.canvas', 'canvas', ([], {'show_fps': '(True)'}), '(show_fps=True)\n', (233, 248), False, 'from datoviz import app, canvas, run, colormap\n'), ((530, 551), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'n'], {}), '(-1, 1, n)\n', (541, 551), True, 'import numpy as np\n'), ((556, 567), 'numpy.ze... |
from motionAE.src.models import lstmCVAE2
from torch.distributions.kl import kl_divergence
from torch.distributions.normal import Normal
import torch
from motionAE.src.motionCVAETrainer import motionCVAETrainer
import numpy as np
class motionCVAE2Trainer(motionCVAETrainer):
def load_param(self, arg_parser, **kw... | [
"numpy.random.normal",
"numpy.tile",
"torch.exp",
"torch.distributions.kl.kl_divergence",
"torch.no_grad"
] | [((940, 978), 'numpy.tile', 'np.tile', (['class_vector', '(batch_size, 1)'], {}), '(class_vector, (batch_size, 1))\n', (947, 978), True, 'import numpy as np\n'), ((1081, 1118), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'z_sample_shape'}), '(size=z_sample_shape)\n', (1097, 1118), True, 'import numpy as np... |
"""
A few important functions necessary for the end product are stored in this file.
"""
import xarray as xr
import numpy as np
import os
import datetime
plain_text_to_long = {
"Temperature at 2m": "2m_temperature",
"Lake Cover": "lake_cover",
"Friction Velocity": "friction_velocity",
"Cl... | [
"datetime.datetime",
"os.path.exists",
"numpy.repeat",
"os.path.join",
"numpy.array",
"numpy.concatenate",
"xarray.open_dataset",
"os.path.expanduser"
] | [((1031, 1054), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (1049, 1054), False, 'import os\n'), ((1100, 1129), 'os.path.join', 'os.path.join', (['home', 'file_name'], {}), '(home, file_name)\n', (1112, 1129), False, 'import os\n'), ((5338, 5361), 'xarray.open_dataset', 'xr.open_dataset', ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # s_vo... | [
"matplotlib.pyplot.grid",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.log",
"numpy.array",
"pandas.to_datetime",
"numpy.arange",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"numpy.max",
"numpy.exp",
"numpy.linspace",
"nump... | [((1309, 1372), 'pandas.read_csv', 'pd.read_csv', (["(path + 'quotes.csv')"], {'index_col': '(0)', 'parse_dates': '(True)'}), "(path + 'quotes.csv', index_col=0, parse_dates=True)\n", (1320, 1372), True, 'import pandas as pd\n'), ((1382, 1445), 'pandas.read_csv', 'pd.read_csv', (["(path + 'trades.csv')"], {'index_col':... |
"""
Micro Code 7.0.0
Author <NAME>
"""
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import numpy as np
import base64
import zlib
import cv2
class Micr... | [
"cv2.imwrite",
"zlib.compress",
"cryptography.hazmat.primitives.hashes.SHA256",
"cryptography.fernet.Fernet",
"numpy.zeros",
"cryptography.hazmat.backends.default_backend",
"numpy.array",
"cv2.imread",
"zlib.decompress"
] | [((402, 422), 'zlib.compress', 'zlib.compress', (['data_'], {}), '(data_)\n', (415, 422), False, 'import zlib\n'), ((833, 849), 'cryptography.fernet.Fernet', 'Fernet', (['password'], {}), '(password)\n', (839, 849), False, 'from cryptography.fernet import Fernet\n'), ((1151, 1167), 'cryptography.fernet.Fernet', 'Fernet... |
import os
import sys
import random
import datetime
import time
import shutil
import numpy as np
import pandas as pd
import scipy.io
import scipy.signal
import math
from skimage.measure import compare_ssim as sk_ssim
import torch
from torch import nn
class ProgressMeter(object):
def __init__(sel... | [
"numpy.moveaxis",
"torch.nn.MSELoss",
"torch.max",
"numpy.squeeze"
] | [((1500, 1512), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1510, 1512), False, 'from torch import nn\n'), ((2205, 2223), 'numpy.squeeze', 'np.squeeze', (['output'], {}), '(output)\n', (2215, 2223), True, 'import numpy as np\n'), ((2244, 2272), 'numpy.moveaxis', 'np.moveaxis', (['output_i', '(0)', '(-1)'], {})... |
from datetime import datetime
import os.path
import time
import tensorflow.python.platform
from tensorflow.python.platform import gfile
import numpy as np
from six.moves import xrange
import tensorflow as tf
from CIFAR import cifar10
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string( 'train_dir', '../cifar10_d... | [
"CIFAR.cifar10.distorted_inputs",
"six.moves.xrange",
"tensorflow.app.run",
"tensorflow.Graph",
"tensorflow.python.platform.gfile.MakeDirs",
"tensorflow.train.SumnarWriter",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.ConfigProto",
"tensorflow.python.platform.gfile.DeleteRecursively",
"tens... | [((266, 366), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""train_dir"""', '"""../cifar10_data"""', '"""Directory where to write event log"""'], {}), "('train_dir', '../cifar10_data',\n 'Directory where to write event log')\n", (292, 366), True, 'import tensorflow as tf\n'), ((369, 447), ... |
# -*- coding: utf-8 -*-
from sys import exit
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from capture_core import *
# 使用matplotlib绘制柱状图
import numpy as np
import matplotlib.pyplot as plt
import json
from monitor_system import start_monitor
from forged_packet import startForged
fro... | [
"json.dump",
"multiprocessing.Process",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.axes",
"sys.exit",
"json.load",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((1523, 1542), 'json.load', 'json.load', (['file_obj'], {}), '(file_obj)\n', (1532, 1542), False, 'import json\n'), ((14741, 14747), 'sys.exit', 'exit', ([], {}), '()\n', (14745, 14747), False, 'from sys import exit\n'), ((19257, 19276), 'json.load', 'json.load', (['file_obj'], {}), '(file_obj)\n', (19266, 19276), Fal... |
import os
import gym
import numpy as np
import matplotlib.pyplot as plt
from dqn_agent import DQNAgent
from utils import reward_engineering
import tensorflow as tf
def plot_points(point_list, style):
x = []
y = []
for point in point_list:
x.append(point[0])
y.append(point[1])
plt.plot(... | [
"os.path.exists",
"dqn_agent.DQNAgent",
"numpy.mean",
"matplotlib.pyplot.savefig",
"numpy.reshape",
"utils.reward_engineering",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"tensorflow.compat.v1.disable_eager_execution",
"matplot... | [((626, 664), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (662, 664), True, 'import tensorflow as tf\n'), ((701, 714), 'gym.make', 'gym.make', (['rom'], {}), '(rom)\n', (709, 714), False, 'import gym\n'), ((870, 933), 'dqn_agent.DQNAgent', 'DQNAgent', (['sta... |
from PIL import Image
import numpy as np
import cv2
PAPER_EXT = {".gloria_chx": "gloria_chx_open_image"}
def gloria_chx_open_image(img):
def _resize_img(img, scale):
"""
Args:
img - image as numpy array (cv2)
scale - desired output image-size as scale x scale
Retur... | [
"numpy.ceil",
"PIL.Image.fromarray",
"numpy.floor",
"numpy.pad",
"cv2.resize"
] | [((945, 1013), 'cv2.resize', 'cv2.resize', (['img', 'desireable_size[::-1]'], {'interpolation': 'cv2.INTER_AREA'}), '(img, desireable_size[::-1], interpolation=cv2.INTER_AREA)\n', (955, 1013), False, 'import cv2\n'), ((1657, 1743), 'numpy.pad', 'np.pad', (['resized_img', '[(top, bottom), (left, right)]', '"""constant""... |
import os
import os.path
import sys
import torch
import torch.utils.data as data
from .datasets_wrapper import Dataset
import cv2
import numpy as np
WF_CLASSES = ("face")
class AnnotationTransform(object):
"""Transforms a VOC annotation into a Tensor of bbox coords and label index
Initilized with a dictionary... | [
"torch.stack",
"torch.from_numpy",
"numpy.append",
"numpy.array",
"numpy.zeros",
"torch.is_tensor",
"numpy.empty",
"numpy.vstack",
"cv2.imread"
] | [((1202, 1218), 'numpy.empty', 'np.empty', (['(0, 5)'], {}), '((0, 5))\n', (1210, 1218), True, 'import numpy as np\n'), ((3444, 3477), 'cv2.imread', 'cv2.imread', (['self.imgs_path[index]'], {}), '(self.imgs_path[index])\n', (3454, 3477), False, 'import cv2\n'), ((3607, 3624), 'numpy.zeros', 'np.zeros', (['(0, 15)'], {... |
import numpy as np
import pandas as pd
from ..base import AbstractDensity
from .multinomial import Multinomial
from .piecewise_uniform import PiecewiseUniform
class JointDensity(AbstractDensity):
def __init__(self, numeric_params=None, verbose=False):
super().__init__()
self.Categorical = Multinom... | [
"numpy.exp",
"pandas.DataFrame"
] | [((2096, 2112), 'numpy.exp', 'np.exp', (['log_dens'], {}), '(log_dens)\n', (2102, 2112), True, 'import numpy as np\n'), ((2398, 2419), 'pandas.DataFrame', 'pd.DataFrame', (['samples'], {}), '(samples)\n', (2410, 2419), True, 'import pandas as pd\n')] |
import torch
import json
import numpy as np
import pandas as pd
from copy import deepcopy
from typing import Union, List, Tuple, Dict
from omegaconf import DictConfig
from dataset.carla_helper import MapHelper
from dataset.exception import FailedProcessing
from dataset.utils import (
distance, rotate_vector, get_... | [
"dataset.utils.pad_objects",
"dataset.carla_helper.MapHelper",
"pandas.read_csv",
"torch.from_numpy",
"numpy.array",
"dataset.utils.convert_status_to_np",
"copy.deepcopy",
"numpy.sin",
"dataset.utils.rotate_vector",
"numpy.diff",
"numpy.stack",
"numpy.concatenate",
"pandas.DataFrame",
"num... | [((13710, 13730), 'copy.deepcopy', 'deepcopy', (['batch_data'], {}), '(batch_data)\n', (13718, 13730), False, 'from copy import deepcopy\n'), ((13822, 13845), 'dataset.utils.pad_objects', 'pad_objects', (['batch_data'], {}), '(batch_data)\n', (13833, 13845), False, 'from dataset.utils import distance, rotate_vector, ge... |
import cv2
import os, sys
import numpy as np
save_path = 'images/train/'
# Helpful functions #
def save_image(name, img):
if not os.path.exists(save_path):
os.makedirs(save_path)
cv2.imwrite(save_path+name+'.tif', np.array(img, dtype=np.uint8))
def get_api_key():
if len(sys.argv) is 2:
... | [
"os.path.exists",
"os.makedirs",
"numpy.array",
"sys.exit",
"sys.argv.pop"
] | [((136, 161), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (150, 161), False, 'import os, sys\n'), ((171, 193), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (182, 193), False, 'import os, sys\n'), ((233, 262), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.uint8'}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.