code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
===================
prospect.viewer.cds
===================
Class containing all bokeh's ColumnDataSource objects needed in viewer.py
"""
import numpy as np
from pkg_resources import resource_filename
import bokeh.plotting a... | [
"numpy.median",
"numpy.sqrt",
"numpy.log10",
"numpy.where",
"numpy.any",
"numpy.zeros",
"bokeh.models.ColumnDataSource",
"numpy.isnan",
"numpy.all"
] | [((3960, 3985), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['cdsdata'], {}), '(cdsdata)\n', (3976, 3985), False, 'from bokeh.models import ColumnDataSource\n'), ((4801, 4836), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['cds_coaddcam_data'], {}), '(cds_coaddcam_data)\n', (4817, 4836), False, 'from... |
import logging
import time
import numpy as np
from eda import ma_data, tx_data
from sir_fitting_us import seir_experiment, make_csv_from_tx_traj
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("Fitting model.")
# initial values taken from previous fit, used to seed MH sampler efficie... | [
"logging.getLogger",
"numpy.mean",
"time.ctime",
"sir_fitting_us.make_csv_from_tx_traj",
"numpy.array",
"sir_fitting_us.seir_experiment"
] | [((157, 184), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (174, 184), False, 'import logging\n'), ((331, 381), 'numpy.array', 'np.array', (['[0.393, -2.586, -3.241, -5.874, -24.999]'], {}), '([0.393, -2.586, -3.241, -5.874, -24.999])\n', (339, 381), True, 'import numpy as np\n'), ((456... |
"""
@file
@brief Test for :epkg:`cartopy`.
"""
import numpy
import numba
@numba.jit(nopython=True, parallel=True)
def logistic_regression(Y, X, w, iterations):
"Fits a logistic regression."
for _ in range(iterations):
w -= numpy.dot(((1.0 / (1.0 + numpy.exp(-Y * numpy.dot(X, w))) - 1.0) * Y), X)
r... | [
"numpy.dot",
"numba.jit",
"numpy.random.rand"
] | [((76, 115), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)'}), '(nopython=True, parallel=True)\n', (85, 115), False, 'import numba\n'), ((411, 432), 'numpy.random.rand', 'numpy.random.rand', (['(10)'], {}), '(10)\n', (428, 432), False, 'import numpy\n'), ((462, 486), 'numpy.random.rand', 'nu... |
import numpy as np
from plots import plots_for_predictions as pp
from utilss import distinct_colours as dc
import matplotlib.pyplot as plt
c = dc.get_distinct(4)
path = '/Users/luisals/Documents/deep_halos_files/mass_range_13.4/random_20sims_200k/lr5e-5/'
p1 = np.load(path + "seed_20/predicted_sim_6_epoch_09.npy")
t1... | [
"plots.plots_for_predictions.plot_histogram_predictions",
"numpy.load",
"matplotlib.pyplot.savefig",
"utilss.distinct_colours.get_distinct"
] | [((144, 162), 'utilss.distinct_colours.get_distinct', 'dc.get_distinct', (['(4)'], {}), '(4)\n', (159, 162), True, 'from utilss import distinct_colours as dc\n'), ((263, 317), 'numpy.load', 'np.load', (["(path + 'seed_20/predicted_sim_6_epoch_09.npy')"], {}), "(path + 'seed_20/predicted_sim_6_epoch_09.npy')\n", (270, 3... |
"""
---OK---
"""
from collections import OrderedDict
import copy
import numpy as np
from crystalpy.examples.Values import Interval
class PlotData1D(object):
"""
Represents a 1D plot. The graph data together with related information.
"""
def __init__(self, title, title_x_axis, title_y_axis):
... | [
"collections.OrderedDict",
"numpy.unwrap",
"numpy.asarray",
"numpy.deg2rad",
"copy.deepcopy",
"crystalpy.examples.Values.Interval",
"numpy.rad2deg"
] | [((926, 939), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (937, 939), False, 'from collections import OrderedDict\n'), ((3999, 4014), 'numpy.unwrap', 'np.unwrap', (['temp'], {}), '(temp)\n', (4008, 4014), True, 'import numpy as np\n'), ((5549, 5575), 'crystalpy.examples.Values.Interval', 'Interval', (['... |
from hytra.pluginsystem import transition_feature_vector_construction_plugin
import numpy as np
from compiler.ast import flatten
class TransitionFeaturesSubtraction(
transition_feature_vector_construction_plugin.TransitionFeatureVectorConstructionPlugin
):
"""
Computes the subtraction of features in the f... | [
"numpy.array"
] | [((1564, 1582), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (1572, 1582), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) 2021. Distributed under the terms of the MIT License.
from phonopy.interface.calculator import read_crystal_structure
from phonopy.structure.atoms import PhonopyAtoms
from vise.util.phonopy.phonopy_input import structure_to_phonopy_atoms
import numpy as np
def assert_same_phon... | [
"numpy.array",
"phonopy.interface.calculator.read_crystal_structure",
"phonopy.structure.atoms.PhonopyAtoms",
"vise.util.phonopy.phonopy_input.structure_to_phonopy_atoms"
] | [((822, 854), 'phonopy.interface.calculator.read_crystal_structure', 'read_crystal_structure', (['"""POSCAR"""'], {}), "('POSCAR')\n", (844, 854), False, 'from phonopy.interface.calculator import read_crystal_structure\n'), ((863, 884), 'phonopy.structure.atoms.PhonopyAtoms', 'PhonopyAtoms', ([], {'atoms': 'a'}), '(ato... |
import numpy as np
import math
import logging
from termcolor import colored
# Check a matrix for: negative eigenvalues, asymmetry and negative diagonal values
def positive_definite(M,epsilon = 0.000001,verbose=False):
# Symmetrization
Mt = np.transpose(M)
M = (M + Mt)/2
eigenvalues = np.linalg.eigvals(... | [
"numpy.linalg.eigvals",
"numpy.transpose",
"logging.error"
] | [((249, 264), 'numpy.transpose', 'np.transpose', (['M'], {}), '(M)\n', (261, 264), True, 'import numpy as np\n'), ((302, 322), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['M'], {}), '(M)\n', (319, 322), True, 'import numpy as np\n'), ((439, 476), 'logging.error', 'logging.error', (['"""Negative eigenvalues"""'], {})... |
import warnings
from typing import Callable, List, Optional, Union
import mpmath
import numpy as np
import paramak
import sympy as sp
from paramak import RotateMixedShape, diff_between_angles
from paramak.parametric_components.tokamak_plasma_plasmaboundaries import \
PlasmaBoundaries
from scipy.interpolate import... | [
"numpy.radians",
"numpy.flip",
"sympy.Symbol",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.linspace",
"mpmath.radians",
"sympy.diff",
"warnings.warn"
] | [((8042, 8060), 'sympy.Symbol', 'sp.Symbol', (['"""theta"""'], {}), "('theta')\n", (8051, 8060), True, 'import sympy as sp\n'), ((8142, 8165), 'sympy.diff', 'sp.diff', (['R_sp', 'theta_sp'], {}), '(R_sp, theta_sp)\n', (8149, 8165), True, 'import sympy as sp\n'), ((8189, 8212), 'sympy.diff', 'sp.diff', (['Z_sp', 'theta_... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import os
import math
from utils import logger
use_cuda = torch.cuda.is_available()
# utility
def to_var(x, dtype=None):
if type(x) is np.ndarray:
x = torch.from_numpy(x)
elif type(x) is list:
... | [
"torch.log",
"torch.mean",
"math.pow",
"torch.nn.functional.binary_cross_entropy",
"os.path.join",
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"utils.logger.info",
"torch.sum",
"torch.autograd.Variable",
"torch.clamp"
] | [((160, 185), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (183, 185), False, 'import torch\n'), ((419, 430), 'torch.autograd.Variable', 'Variable', (['x'], {}), '(x)\n', (427, 430), False, 'from torch.autograd import Variable\n'), ((4962, 5004), 'torch.nn.functional.binary_cross_entropy', 'F... |
"""
Explore raw composites based on indices from predicted testing data and
showing all the difference OHC levels for OBSERVATIONS
Author : <NAME>
Date : 21 September 2021
Version : 2 (mostly for testing)
"""
### Import packages
import sys
import matplotlib.pyplot as plt
import numpy as np
import calc_Ut... | [
"calc_dataFunctions.getRegion",
"numpy.nanmean",
"sys.exit",
"numpy.genfromtxt",
"numpy.arange",
"numpy.where",
"numpy.asarray",
"numpy.meshgrid",
"calc_Utilities.regions",
"numpy.nanstd",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"calc_Stats.remove_trend_obs",
"matplotlib.py... | [((566, 593), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (572, 593), True, 'import matplotlib.pyplot as plt\n'), ((593, 666), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Avant Garde']})\n", (599, 6... |
import torch
import numpy as np
import torch.nn.functional as F
from torch.nn.utils.clip_grad import clip_grad_norm_
from mpi_utils.mpi_utils import sync_grads
def update_entropy(alpha, log_alpha, target_entropy, log_pi, alpha_optim, cfg):
if cfg.automatic_entropy_tuning:
alpha_loss = -(log_alpha * (log_p... | [
"torch.nn.functional.mse_loss",
"torch.min",
"torch.tensor",
"numpy.concatenate",
"mpi_utils.mpi_utils.sync_grads",
"torch.no_grad"
] | [((889, 940), 'numpy.concatenate', 'np.concatenate', (['[obs_norm, ag_norm, g_norm]'], {'axis': '(1)'}), '([obs_norm, ag_norm, g_norm], axis=1)\n', (903, 940), True, 'import numpy as np\n'), ((964, 1020), 'numpy.concatenate', 'np.concatenate', (['[obs_next_norm, ag_norm, g_norm]'], {'axis': '(1)'}), '([obs_next_norm, a... |
##--------------------------------Main file------------------------------------
##
## Copyright (C) 2020 by <NAME> (<EMAIL>)
## June, 2020
## <EMAIL>
##-----------------------------------------------------------------------------
# Variables aleatorias múltiples
# Se consideran dos bases de datos las ... | [
"scipy.optimize.curve_fit",
"matplotlib.pyplot.savefig",
"collections.OrderedDict.fromkeys",
"pandas.read_csv",
"numpy.sqrt",
"scipy.stats.norm",
"numpy.exp",
"numpy.array",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.axes",
"numpy.meshgrid",
"matplotlib.pyplot.cl... | [((4558, 4647), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/belindabrown/Desktop/VA_multiples/data_base/xy.csv"""'], {'index_col': '(0)'}), "('/Users/belindabrown/Desktop/VA_multiples/data_base/xy.csv',\n index_col=0)\n", (4569, 4647), True, 'import pandas as pd\n'), ((4655, 4728), 'pandas.read_csv', 'pd.read_csv... |
# -*- coding:UTF-8 -*-
import pandas as pd
from minepy import MINE
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.ensemble import ExtraTreesClassifier
import xgboost as xgb
import operator
from sklearn.utils import shuffle
from Common.ModelCommon import ModelCV
from sklearn import svm
import numpy a... | [
"xgboost.DMatrix",
"sklearn.ensemble.ExtraTreesClassifier",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"xgboost.train",
"matplotlib.pyplot.xlabel",
"xgboost.plot_importance",
"seaborn.diverging_palette",
"sklearn.svm.LinearSVC",
"seaborn.heatmap",
"operator.itemgetter",
"numpy.whe... | [((2446, 2510), 'pandas.DataFrame', 'pd.DataFrame', (["{'feat': df.columns, 'valueCount': valueCountList}"], {}), "({'feat': df.columns, 'valueCount': valueCountList})\n", (2458, 2510), True, 'import pandas as pd\n'), ((2653, 2659), 'minepy.MINE', 'MINE', ([], {}), '()\n', (2657, 2659), False, 'from minepy import MINE\... |
import mss
import numpy as np
from PIL import Image
from config import BOARD_HEIGHT, BOARD_WIDTH
CELL_SIZE = 22
BOARD_X = 14
BOARD_Y = 111
COLOR_CODES = {
(0, 0, 255): 1,
(0, 123, 0): 2,
(255, 0, 0): 3,
(0, 0, 123): 4,
(123, 0, 0): 5,
(0, 123, 123): 6,
(0, 0, 0): 7,
(123, 123, 123): 8,
(189, 189, 189): 0 #uno... | [
"numpy.insert",
"numpy.reshape",
"mss.mss",
"numpy.full",
"PIL.Image.frombytes"
] | [((1163, 1209), 'numpy.reshape', 'np.reshape', (['cells', '(BOARD_HEIGHT, BOARD_WIDTH)'], {}), '(cells, (BOARD_HEIGHT, BOARD_WIDTH))\n', (1173, 1209), True, 'import numpy as np\n'), ((617, 626), 'mss.mss', 'mss.mss', ([], {}), '()\n', (624, 626), False, 'import mss\n'), ((684, 755), 'PIL.Image.frombytes', 'Image.fromby... |
import numpy
N,M,P = map(int,input().split())
p_cols1 =numpy.array([input().split() for _ in range(N)],int)
p_cols1.shape = (N,P)
p_cols2 =numpy.array([input().split() for _ in range(M)],int)
p_cols2.shape = (M,P)
concatenated = numpy.concatenate((p_cols1, p_cols2), axis = 0)
print(concatenated)
| [
"numpy.concatenate"
] | [((232, 277), 'numpy.concatenate', 'numpy.concatenate', (['(p_cols1, p_cols2)'], {'axis': '(0)'}), '((p_cols1, p_cols2), axis=0)\n', (249, 277), False, 'import numpy\n')] |
# GCT634 (2018) HW1
#
# Mar-18-2018: initial version
#
# <NAME>
#
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
data_path = './dataset/'
mfcc_path = './mfcc/'
MFCC_DIM = 20
def mean_mfcc(dataset='train'):
f = open(data_path + dataset + '_list.txt','r')
if dataset == 'train'... | [
"matplotlib.pyplot.imshow",
"numpy.mean",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.load",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((941, 954), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (951, 954), True, 'import matplotlib.pyplot as plt\n'), ((959, 979), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (970, 979), True, 'import matplotlib.pyplot as plt\n'), ((982, 1060), 'matplotlib.p... |
import json
from typing import Union, Optional, Tuple, List
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Stan... | [
"sklearn.feature_extraction.text.TfidfTransformer",
"json.loads",
"sklearn.feature_extraction.DictVectorizer",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.StandardScaler",
"numpy.array"
] | [((870, 886), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (884, 886), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3031, 3104), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'train_size': 'split_1', 'random_state': 'self.random_seed'}), ... |
# -*- coding: utf-8 -*-
import random
import numpy as np
import scipy
import pandas as pd
import pandas
import numpy
import json
def resizeFeature(inputData,newSize):
# inputX: (temporal_length,feature_dimension) #
originalSize=len(inputData)
#print originalSize
if originalSize==1:
inputData=... | [
"numpy.mean",
"numpy.reshape",
"random.shuffle",
"pandas.read_csv",
"scipy.interpolate.interp1d",
"json.load",
"numpy.stack",
"numpy.zeros",
"numpy.max",
"numpy.concatenate",
"pandas.DataFrame",
"json.dump"
] | [((3780, 3809), 'random.shuffle', 'random.shuffle', (['videoNameList'], {}), '(videoNameList)\n', (3794, 3809), False, 'import random\n'), ((4440, 4469), 'json.dump', 'json.dump', (['videoDict', 'outfile'], {}), '(videoDict, outfile)\n', (4449, 4469), False, 'import json\n'), ((437, 485), 'scipy.interpolate.interp1d', ... |
"""Test functions for FOOOF analysis."""
import numpy as np
from fooof.analysis import *
###################################################################################################
###################################################################################################
def test_get_band_peak_fm(t... | [
"numpy.array",
"numpy.empty",
"numpy.array_equal"
] | [((507, 564), 'numpy.array', 'np.array', (['[[10, 1, 1.8, 0], [13, 1, 2, 2], [14, 2, 4, 2]]'], {}), '([[10, 1, 1.8, 0], [13, 1, 2, 2], [14, 2, 4, 2]])\n', (515, 564), True, 'import numpy as np\n'), ((658, 698), 'numpy.array_equal', 'np.array_equal', (['out1[0, :]', '[10, 1, 1.8]'], {}), '(out1[0, :], [10, 1, 1.8])\n', ... |
import numpy as np
import unittest
import coremltools.models.datatypes as datatypes
from coremltools.models import neural_network as neural_network
from coremltools.models import MLModel
from coremltools.models.neural_network.printer import print_network_spec
from coremltools.converters.nnssa.coreml.graph_pass.mlmodel_... | [
"coremltools.models.MLModel",
"coremltools.converters.nnssa.coreml.graph_pass.mlmodel_passes.transform_conv_crop",
"unittest.TestSuite",
"numpy.random.rand",
"numpy.ones",
"coremltools.converters.nnssa.coreml.graph_pass.mlmodel_passes.remove_disconnected_layers",
"numpy.testing.assert_almost_equal",
"... | [((462, 481), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (476, 481), True, 'import numpy as np\n'), ((691, 797), 'coremltools.models.neural_network.NeuralNetworkBuilder', 'neural_network.NeuralNetworkBuilder', (['input_features', 'output_features'], {'disable_rank5_shape_mapping': '(True)'}), '(... |
import time, datetime, argparse
import os, sys
import numpy as np
np.set_printoptions(precision=2)
import matplotlib.pyplot as plt
import copy as cp
import pickle
PROJECT_PATH = '/home/nbuckman/Dropbox (MIT)/DRL/2020_01_cooperative_mpc/mpc-multiple-vehicles/'
sys.path.append(PROJECT_PATH)
import casadi as cas
import ... | [
"src.IterativeBestResponseMPCMultiple.save_state",
"matplotlib.pyplot.ylabel",
"src.TrafficWorld.TrafficWorld",
"numpy.array",
"copy.deepcopy",
"sys.path.append",
"src.IterativeBestResponseMPCMultiple.IterativeBestResponseMPCMultiple",
"matplotlib.pyplot.plot",
"numpy.random.seed",
"src.MPC_Casadi... | [((66, 98), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (85, 98), True, 'import numpy as np\n'), ((261, 290), 'sys.path.append', 'sys.path.append', (['PROJECT_PATH'], {}), '(PROJECT_PATH)\n', (276, 290), False, 'import os, sys\n'), ((1477, 1504), 'src.TrafficWorld.Tra... |
import numpy as np
# softmax function
def softmax(a):
exp_a = np.exp(a)
sum_a = np.sum(exp_a)
return exp_a / sum_a
# modified softmax function
def modified_softmax(a):
maxA = np.max(a)
exp_a = np.exp(a - maxA)
sum_a = np.sum(exp_a)
return exp_a / sum_a
| [
"numpy.exp",
"numpy.sum",
"numpy.max"
] | [((68, 77), 'numpy.exp', 'np.exp', (['a'], {}), '(a)\n', (74, 77), True, 'import numpy as np\n'), ((90, 103), 'numpy.sum', 'np.sum', (['exp_a'], {}), '(exp_a)\n', (96, 103), True, 'import numpy as np\n'), ((195, 204), 'numpy.max', 'np.max', (['a'], {}), '(a)\n', (201, 204), True, 'import numpy as np\n'), ((218, 234), '... |
from itertools import product
import struct
import pickle
import numpy as np
from scipy import sparse
from scipy import isnan as scipy_isnan
import numpy.matlib
ASCII_FACET = """facet normal 0 0 0
outer loop
vertex {face[0][0]:.4f} {face[0][1]:.4f} {face[0][2]:.4f}
vertex {face[1][0]:.4f} {face[1][1]:.4f} {face[1][2]... | [
"scipy.sparse.linalg.lsmr",
"numpy.abs",
"numpy.roll",
"numpy.cross",
"numpy.amin",
"numpy.hstack",
"numpy.where",
"scipy.sparse.dia_matrix",
"pickle.load",
"struct.pack",
"numpy.indices",
"numpy.array",
"numpy.zeros",
"numpy.isnan",
"numpy.linalg.norm",
"scipy.sparse.vstack",
"numpy... | [((2702, 2716), 'numpy.cross', 'np.cross', (['n', 'C'], {}), '(n, C)\n', (2710, 2716), True, 'import numpy as np\n'), ((2771, 2790), 'numpy.cross', 'np.cross', (['n', 'ortho1'], {}), '(n, ortho1)\n', (2779, 2790), True, 'import numpy as np\n'), ((3564, 3619), 'scipy.sparse.dia_matrix', 'sparse.dia_matrix', (['(2 * w * ... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
#from matplotlib import pyplot as plt
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files","... | [
"numpy.absolute",
"cv2.medianBlur",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.ellipse",
"cv2.circle",
"cv2.waitKey",
"numpy.around",
"cv2.cvtColor",
"cv2.CascadeClassifier",
"cv2.imread",
"tkinter.filedialog.askopenfilename"
] | [((208, 332), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', ([], {'initialdir': '"""/"""', 'title': '"""Select file"""', 'filetypes': "(('all files', '.*'), ('jpg files', '.jpg'))"}), "(initialdir='/', title='Select file', filetypes=(\n ('all files', '.*'), ('jpg files', '.jpg')))\n", (234, 332... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import qtawesome
import matplotlib.pyplot as plt
import csv
import numpy as np
import datetime
import os
class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.i... | [
"matplotlib.pyplot.ylabel",
"datetime.timedelta",
"os.remove",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.max",
"matplotlib.pyplot.close",
"numpy.min",
"csv.reader",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"numpy.floor",
"matplotlib.pyplot.titl... | [((55610, 55629), 'csv.reader', 'csv.reader', (['csvFile'], {}), '(csvFile)\n', (55620, 55629), False, 'import csv\n'), ((40154, 40180), 'os.remove', 'os.remove', (['figure_1_delete'], {}), '(figure_1_delete)\n', (40163, 40180), False, 'import os\n'), ((40190, 40216), 'os.remove', 'os.remove', (['figure_2_delete'], {})... |
#! /usr/bin/python
# encoding=utf-8
import os
import datetime,time
from selenium import webdriver
import config
import threading
import numpy as np
def writelog(msg,log):
nt=datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
text="[%s] %s " % (nt,msg)
os.system("echo %s >> %s" % (text.encode('utf8'),l... | [
"selenium.webdriver.ChromeOptions",
"selenium.webdriver.Chrome",
"time.sleep",
"datetime.datetime.now",
"numpy.random.uniform",
"threading.Thread"
] | [((355, 380), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (378, 380), False, 'from selenium import webdriver\n'), ((464, 500), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'chrome_options': 'ops'}), '(chrome_options=ops)\n', (480, 500), False, 'from selenium import webdriv... |
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
from difflib import SequenceMatcher
import seaborn as sns
from statistics import mean
from ast import literal_eval
from scipy import stats
from sklearn.linear_model import LinearRegression
from s... | [
"matplotlib.pyplot.ylabel",
"numpy.array",
"pandas.read_excel",
"matplotlib.lines.Line2D",
"numpy.divide",
"numpy.mean",
"seaborn.regplot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"pandas.DataFrame",
"seaborn.swarmplot",
"matplotlib.pyplot.savefig",
... | [((1115, 1131), 'os.scandir', 'os.scandir', (['path'], {}), '(path)\n', (1125, 1131), False, 'import os\n'), ((3840, 3892), 'pandas.to_numeric', 'pd.to_numeric', (['telo_data.iloc[:, 0]'], {'errors': '"""coerce"""'}), "(telo_data.iloc[:, 0], errors='coerce')\n", (3853, 3892), True, 'import pandas as pd\n'), ((4083, 411... |
import time
from datetime import datetime
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.dates import epoch2num
import device_factory
if __name__ == '__main__':
amount = 50
devices = []
for i in range(amount):
device = device_factory.ecopower_4(i, i)
... | [
"datetime.datetime",
"numpy.mean",
"device_factory.ecopower_4",
"numpy.abs",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.twinx",
"numpy.sum",
"numpy.zeros",
"matplotlib.pyplot.subplot",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((1207, 1227), 'numpy.zeros', 'np.zeros', (['sample_dur'], {}), '(sample_dur)\n', (1215, 1227), True, 'import numpy as np\n'), ((2003, 2020), 'numpy.sum', 'np.sum', (['P'], {'axis': '(0)'}), '(P, axis=0)\n', (2009, 2020), True, 'import numpy as np\n'), ((2031, 2049), 'numpy.sum', 'np.sum', (['Th'], {'axis': '(0)'}), '... |
"""
Tests for the h5py.Datatype class.
"""
from __future__ import absolute_import
from itertools import count
import numpy as np
import h5py
from ..common import ut, TestCase
class TestVlen(TestCase):
"""
Check that storage of vlen strings is carried out correctly.
"""
def assertVlenArrayEq... | [
"h5py.check_dtype",
"numpy.random.rand",
"numpy.random.random_integers",
"h5py.File",
"h5py.h5t.py_create",
"numpy.array",
"itertools.count",
"numpy.empty",
"numpy.random.randint",
"h5py.special_dtype",
"numpy.dtype"
] | [((806, 822), 'numpy.dtype', 'np.dtype', (['fields'], {}), '(fields)\n', (814, 822), True, 'import numpy as np\n'), ((850, 862), 'numpy.dtype', 'np.dtype', (['dt'], {}), '(dt)\n', (858, 862), True, 'import numpy as np\n'), ((1040, 1073), 'h5py.special_dtype', 'h5py.special_dtype', ([], {'vlen': 'np.uint8'}), '(vlen=np.... |
from pathlib import Path
import numpy as np
import pickle
import argparse
import errno
import sys
def file_exists(path):
return Path(path).is_file()
def dir_exists(path):
return Path(path).is_dir()
def remove_extension(x): return x.split('.')[0]
def print_error(type, file):
print(FileNotFoundError(e... | [
"pickle.dump",
"argparse.ArgumentParser",
"pathlib.Path",
"numpy.where",
"numpy.asarray",
"sys.exit"
] | [((1358, 1499), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Filter Unicode characters based on a given threshold between 0 and 1 and a similarity matrix"""'}), "(description=\n 'Filter Unicode characters based on a given threshold between 0 and 1 and a similarity matrix'\n )\n",... |
#!/usr/bin/python
from aos.util.trapezoid_profile import TrapezoidProfile
from frc971.control_loops.python import control_loop
from frc971.control_loops.python import angular_system
from frc971.control_loops.python import controls
import copy
import numpy
import sys
from matplotlib import pylab
import gflags
import gl... | [
"frc971.control_loops.python.control_loop.BAG",
"gflags.DEFINE_bool",
"frc971.control_loops.python.angular_system.PlotKick",
"glog.fatal",
"frc971.control_loops.python.angular_system.PlotMotion",
"copy.copy",
"numpy.matrix",
"glog.init",
"frc971.control_loops.python.angular_system.WriteAngularSystem... | [((852, 869), 'copy.copy', 'copy.copy', (['kWrist'], {}), '(kWrist)\n', (861, 869), False, 'import copy\n'), ((954, 971), 'copy.copy', 'copy.copy', (['kWrist'], {}), '(kWrist)\n', (963, 971), False, 'import copy\n'), ((1009, 1026), 'copy.copy', 'copy.copy', (['kWrist'], {}), '(kWrist)\n', (1018, 1026), False, 'import c... |
#! -*- coding:utf-8 -*-
# 语义相似度任务-无监督:训练集为网上pretrain数据, dev集为sts-b
from bert4torch.tokenizers import Tokenizer
from bert4torch.models import build_transformer_model, BaseModel
from bert4torch.snippets import sequence_padding, Callback, ListDataset
import torch.nn as nn
import torch
import torch.optim as optim
from to... | [
"torch.ones_like",
"torch.nn.CrossEntropyLoss",
"sklearn.metrics.pairwise.paired_cosine_distances",
"numpy.random.rand",
"numpy.random.choice",
"torch.max",
"random.seed",
"bert4torch.tokenizers.Tokenizer",
"bert4torch.snippets.sequence_padding",
"torch.cuda.is_available",
"torch.no_grad",
"nu... | [((503, 520), 'random.seed', 'random.seed', (['(2022)'], {}), '(2022)\n', (514, 520), False, 'import random\n'), ((521, 541), 'numpy.random.seed', 'np.random.seed', (['(2002)'], {}), '(2002)\n', (535, 541), True, 'import numpy as np\n'), ((963, 1003), 'bert4torch.tokenizers.Tokenizer', 'Tokenizer', (['dict_path'], {'do... |
# @Time : 2020/10/6
# @Author : <NAME>
# @Email : <EMAIL>
"""
recbole.quick_start
########################
"""
import logging
from logging import getLogger
from recbole.config import Config
from recbole.data import create_dataset, data_preparation
from recbole.utils import init_logger, get_model, get_trainer, init... | [
"logging.getLogger",
"recbole.utils.init_seed",
"recbole.config.Config",
"numpy.save",
"seaborn.set",
"scipy.linalg.svdvals",
"matplotlib.pyplot.plot",
"recbole.utils.init_logger",
"numpy.dot",
"matplotlib.pyplot.scatter",
"recbole.utils.get_trainer",
"matplotlib.pyplot.ylim",
"matplotlib.py... | [((944, 1044), 'recbole.config.Config', 'Config', ([], {'model': 'model', 'dataset': 'dataset', 'config_file_list': 'config_file_list', 'config_dict': 'config_dict'}), '(model=model, dataset=dataset, config_file_list=config_file_list,\n config_dict=config_dict)\n', (950, 1044), False, 'from recbole.config import Con... |
import matplotlib.pyplot as plt
from matplotlib import collections
from matplotlib.lines import Line2D
def autosize(fig=None, figsize=None):
## Take current figure if no figure provided
if fig is None:
fig = plt.gcf()
if figsize is None:
## Get size of figure
figsize = fig.get_s... | [
"numpy.random.normal",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"numpy.random.uniform",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"plottify.autosize",
"matplotlib.pyplot.show"
] | [((1442, 1460), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1458, 1460), True, 'import matplotlib.pyplot as plt\n'), ((1603, 1644), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-5)', 'high': '(5)', 'size': 'n'}), '(low=-5, high=5, size=n)\n', (1620, 1644), True, 'import numpy... |
import numpy as np
from time import time
import matplotlib.pyplot as plt
measure2index={"y-coordinate":0,"x-coordinate":1,"timestamp":2, "button_status":3,"tilt":4, "elevation":5,"pressure":6}
index2measure=list(measure2index.keys())
task2index={"spiral":0,"l":1,"le":2 ,"les":3,"lektorka" :4,"porovnat":5,"nepopadnout... | [
"numpy.identity",
"numpy.mean",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.floor",
"numpy.max",
"matplotlib.pyplot.subplot",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.around",
"numpy.min",
"time.time",
"matplotlib.pyplot.legend"
] | [((938, 952), 'numpy.identity', 'np.identity', (['(8)'], {}), '(8)\n', (949, 952), True, 'import numpy as np\n'), ((1071, 1092), 'numpy.array', 'np.array', (['downsampled'], {}), '(downsampled)\n', (1079, 1092), True, 'import numpy as np\n'), ((1295, 1314), 'numpy.array', 'np.array', (['upsampled'], {}), '(upsampled)\n... |
import numpy as np
import torch
from torch_utils import training_stats
from torch_utils import misc
from torch_utils.ops import conv2d_gradfix
import torch.nn.functional as F
import torchvision.transforms as T
import clip
import dnnlib
import random
#--------------------------------------------------------------------... | [
"numpy.sqrt",
"torch.exp",
"torch.full_like",
"torch.autograd.profiler.record_function",
"torch.nn.functional.interpolate",
"torch.distributed.get_rank",
"torch_utils.training_stats.report",
"torch.nn.functional.softmax",
"torch.randint",
"torch.zeros_like",
"torch.randn",
"torch.distributed.a... | [((635, 661), 'torch.nn.Linear', 'torch.nn.Linear', (['(512)', '(1024)'], {}), '(512, 1024)\n', (650, 661), False, 'import torch\n'), ((685, 712), 'torch.nn.Linear', 'torch.nn.Linear', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (700, 712), False, 'import torch\n'), ((736, 763), 'torch.nn.Linear', 'torch.nn.Linear', ... |
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def do_ml(merged_df, test_size, ml_model, **kwargs):
train_data = merged_df.d... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure",
"numpy.array",
"pandas.DataFrame",
"numpy.ravel",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.confusion_matrix"
] | [((992, 1037), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y_test', 'predictions'], {}), '(y_test, predictions)\n', (1016, 1037), False, 'from sklearn import metrics\n'), ((1059, 1102), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'predictions'], {}), '(y_test, predicti... |
import numpy as np
import tensorflow as tf
from keras import backend as K
from tqdm import tqdm
def write_log(callback, names, logs, batch_no):
for name, value in zip(names, logs):
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value
... | [
"numpy.array",
"tqdm.tqdm",
"tensorflow.Summary",
"keras.backend.get_value"
] | [((211, 223), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (221, 223), True, 'import tensorflow as tf\n'), ((730, 822), 'tqdm.tqdm', 'tqdm', ([], {'total': 'epoch_step', 'desc': 'f"""Epoch {epoch + 1}/{Epoch}"""', 'postfix': 'dict', 'mininterval': '(0.3)'}), "(total=epoch_step, desc=f'Epoch {epoch + 1}/{Epoch}... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 15 08:32:03 2021
@author: User
"""
import numpy as np
import matplotlib.pyplot as plt
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a)
print(a[0])
print(a.ndim) #te dice la cantidad de ejes (o dimensiones) del arreglo
print(a.shape) #Te va a dar una t... | [
"numpy.random.random",
"numpy.array"
] | [((138, 193), 'numpy.array', 'np.array', (['[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]'], {}), '([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n', (146, 193), True, 'import numpy as np\n'), ((577, 596), 'numpy.random.random', 'np.random.random', (['(3)'], {}), '(3)\n', (593, 596), True, 'import numpy as np\n')] |
import numpy as np
import os, sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow.keras.models import Model
import tensorflow as tf
from PIL import Image
from utils_rtp import ProMP
class Predictor:
def __init__(self, encoder_model_path, predictor_model_path):
self.all_phi = self.promp_train(... | [
"tensorflow.cast",
"numpy.transpose",
"utils_rtp.ProMP",
"numpy.hstack",
"numpy.zeros",
"tensorflow.keras.models.load_model",
"numpy.vstack",
"numpy.load",
"numpy.save"
] | [((2017, 2067), 'numpy.load', 'np.load', (['"""/home/arshad/catkin_ws/image_xy_rtp.npy"""'], {}), "('/home/arshad/catkin_ws/image_xy_rtp.npy')\n", (2024, 2067), True, 'import numpy as np\n'), ((2175, 2246), 'numpy.save', 'np.save', (['"""/home/arshad/catkin_ws/predicted_joints_values_rtp.npy"""', 'traj'], {}), "('/home... |
'''
--- I M P O R T S T A T E M E N T S ---
'''
import coloredlogs, logging
coloredlogs.install()
import numpy as np
'''
=== S T A R T O F C L A S S E V A L M E T R I C ===
[About]
Object class for calculating average values.
[Init Args]
- name: String for the variable name to calc... | [
"logging.getLogger",
"coloredlogs.install",
"logging.warning",
"numpy.array",
"logging.info"
] | [((79, 100), 'coloredlogs.install', 'coloredlogs.install', ([], {}), '()\n', (98, 100), False, 'import coloredlogs, logging\n'), ((9112, 9140), 'logging.info', 'logging.info', (['"""------------"""'], {}), "('------------')\n", (9124, 9140), False, 'import coloredlogs, logging\n'), ((3791, 3828), 'logging.warning', 'lo... |
import os,sys
import pandas as pd
import numpy as np
import subprocess
from tqdm import tqdm
from ras_method import ras_method
import warnings
warnings.filterwarnings('ignore')
def est_trade_value(x,output_new,sector):
"""
Function to estimate the trade value between two sectors
"""
if (sector is not ... | [
"pandas.MultiIndex.from_product",
"pandas.MultiIndex.from_arrays",
"os.path.join",
"ras_method.ras_method",
"numpy.array",
"pandas.DataFrame",
"pandas.concat",
"warnings.filterwarnings"
] | [((144, 177), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (167, 177), False, 'import warnings\n'), ((986, 1012), 'os.path.join', 'os.path.join', (['""".."""', '"""data"""'], {}), "('..', 'data')\n", (998, 1012), False, 'import os, sys\n'), ((3994, 4163), 'pandas.MultiIn... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
def node_match(n1, n2):
if n1['op'] == n2['op']:
return True
else:
return False
def edge_match(e1, e2):
return True
def gen_graph(adj, ops):
G = nx.DiGraph()
for k, op in enumerate(ops):
G.add_node(k,... | [
"networkx.DiGraph",
"numpy.array",
"networkx.graph_edit_distance",
"matplotlib.pyplot.subplot",
"networkx.draw"
] | [((253, 265), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (263, 265), True, 'import networkx as nx\n'), ((1623, 1723), 'numpy.array', 'np.array', (['[[0, 1, 1, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0,\n 0, 0, 0]]'], {}), '([[0, 1, 1, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, ... |
import os
import pickle
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import h5py
from transforms import Scale
class CLEVR(Dataset):
def __init__(self, root, split='train', transform=None):
features_path = os.path.join(root, ... | [
"transforms.Scale",
"torch.LongTensor",
"torch.stack",
"os.path.join",
"pickle.load",
"torch.from_numpy",
"torchvision.transforms.RandomCrop",
"numpy.zeros",
"torchvision.transforms.Normalize",
"torchvision.transforms.Pad",
"torchvision.transforms.ToTensor"
] | [((1611, 1658), 'numpy.zeros', 'np.zeros', (['(batch_size, max_len)'], {'dtype': 'np.int64'}), '((batch_size, max_len), dtype=np.int64)\n', (1619, 1658), True, 'import numpy as np\n'), ((301, 331), 'os.path.join', 'os.path.join', (['root', '"""features"""'], {}), "(root, 'features')\n", (313, 331), False, 'import os\n'... |
import pytest
import numpy as np
import pandas as pd
from xgboost_distribution.distributions import LogNormal
@pytest.fixture
def lognormal():
return LogNormal()
def test_target_validation(lognormal):
valid_target = np.array([0.5, 1, 4, 5, 10])
lognormal.check_target(valid_target)
@pytest.mark.param... | [
"pandas.Series",
"numpy.log",
"xgboost_distribution.distributions.LogNormal",
"numpy.array",
"pytest.raises",
"numpy.testing.assert_array_equal"
] | [((158, 169), 'xgboost_distribution.distributions.LogNormal', 'LogNormal', ([], {}), '()\n', (167, 169), False, 'from xgboost_distribution.distributions import LogNormal\n'), ((230, 258), 'numpy.array', 'np.array', (['[0.5, 1, 4, 5, 10]'], {}), '([0.5, 1, 4, 5, 10])\n', (238, 258), True, 'import numpy as np\n'), ((1160... |
#!/usr/bin/env python3
"""
Main script for workload forecasting.
Example usage:
- Generate data (runs OLTP benchmark on the built database) and perform training, and save the trained model
./forecaster --gen_data --models=LSTM --model_save_path=model.pickle
- Use the trained models (LSTM) to generate predictions.
... | [
"pickle.dump",
"argparse.ArgumentParser",
"pickle.load",
"numpy.array",
"json.load",
"functools.lru_cache"
] | [((1707, 1767), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Query Load Forecaster"""'}), "(description='Query Load Forecaster')\n", (1730, 1767), False, 'import argparse\n'), ((8504, 8525), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(32)'}), '(maxsize=32)\n', (8513, 8525), ... |
import os, sys
from distutils.util import strtobool
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.python.util import nest, tf_inspect
from tensorflow.python.eager import tape
# from tensorflow.python.ops.custom_gradient import graph_mode_decorator
# 是否使用重计... | [
"tensorflow.python.eager.tape.stop_recording",
"numpy.sqrt",
"os.environ.get",
"tensorflow.python.util.nest.flatten",
"tensorflow.keras.backend.ndim",
"tensorflow.python.util.tf_inspect.getfullargspec",
"tensorflow.GradientTape",
"tensorflow.keras.backend.pow",
"tensorflow.keras.backend.dtype",
"t... | [((348, 380), 'os.environ.get', 'os.environ.get', (['"""RECOMPUTE"""', '"""0"""'], {}), "('RECOMPUTE', '0')\n", (362, 380), False, 'import os, sys\n'), ((2470, 2480), 'tensorflow.keras.backend.dtype', 'K.dtype', (['x'], {}), '(x)\n', (2477, 2480), True, 'import tensorflow.keras.backend as K\n'), ((6013, 6030), 'doctest... |
# utils for working with 3d-protein structures
import os
import numpy as np
import torch
from functools import wraps
from einops import rearrange, repeat
# import torch_sparse # only needed for sparse nth_deg adj calculation
# bio
from Bio import SeqIO
import itertools
import string
# sidechainnet
from sidechainnet... | [
"numpy.random.rand",
"torch.sin",
"torch.det",
"torch.searchsorted",
"torch.cdist",
"torch.min",
"numpy.array",
"torch.cos",
"numpy.linalg.norm",
"numpy.arange",
"torch.logical_or",
"numpy.mean",
"numpy.cross",
"torch.mean",
"einops.repeat",
"torch.logical_not",
"functools.wraps",
... | [((641, 660), 'sidechainnet.utils.sequence.ProteinVocabulary', 'ProteinVocabulary', ([], {}), '()\n', (658, 660), False, 'from sidechainnet.utils.sequence import ProteinVocabulary, ONE_TO_THREE_LETTER_MAP\n'), ((842, 898), 'torch.linspace', 'torch.linspace', (['(2)', '(20)'], {'steps': 'constants.DISTOGRAM_BUCKETS'}), ... |
import numpy as np
import tectosaur.util.gpu as gpu
from tectosaur.fmm.c2e import build_c2e
import logging
logger = logging.getLogger(__name__)
def make_tree(m, cfg, max_pts_per_cell):
tri_pts = m[0][m[1]]
centers = np.mean(tri_pts, axis = 1)
pt_dist = tri_pts - centers[:,np.newaxis,:]
Rs = np.max(np... | [
"logging.getLogger",
"numpy.mean",
"tectosaur.fmm.c2e.build_c2e",
"tectosaur.util.gpu.to_gpu",
"numpy.array",
"numpy.empty_like",
"numpy.linalg.norm"
] | [((118, 145), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'import logging\n'), ((227, 251), 'numpy.mean', 'np.mean', (['tri_pts'], {'axis': '(1)'}), '(tri_pts, axis=1)\n', (234, 251), True, 'import numpy as np\n'), ((318, 349), 'numpy.linalg.norm', 'np.linalg.norm', ... |
import __init__
import os
#os.environ['LD_LIBRARY_PATH'] += ':/usr/local/cuda-11.1/bin64:/usr/local/cuda-11.2/bin64'
import numpy as np
import torch
import torch.multiprocessing as mp
import torch_geometric.datasets as GeoData
from torch_geometric.loader import DenseDataLoader
import torch_geometric.transforms as T... | [
"utils.metrics.AverageMeter",
"torch.nn.CrossEntropyLoss",
"torch.utils.data.distributed.DistributedSampler",
"logging.info",
"torch.utils.tensorboard.SummaryWriter",
"numpy.mean",
"config.OptInit",
"comm.is_main_process",
"comm.get_local_rank",
"numpy.isnan",
"parallel_wrapper.launch",
"utils... | [((799, 832), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': '"""log/mlp4"""'}), "(log_dir='log/mlp4')\n", (812, 832), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((2714, 2727), 'numpy.mean', 'np.mean', (['ious'], {}), '(ious)\n', (2721, 2727), True, 'import numpy as np\n'... |
import torch
import torch.nn as nn
from torchvision.datasets.vision import VisionDataset
from PIL import Image
import os, sys, math
import os.path
import torch
import json
import torch.utils.model_zoo as model_zoo
from Yolo_v2_pytorch.src.utils import *
from Yolo_v2_pytorch.src.yolo_net import Yolo
from Yolo_v2_pytorc... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.sin",
"torch.exp",
"math.log",
"numpy.array",
"torch.cos",
"torch.sum",
"torch.nn.AvgPool2d",
"torch.nn.functional.softmax",
"torch.arange",
"torch.nn.BatchNorm2d",
"Yolo_v2_pytorch.src.yolo_tunning.YoloD",
"torch.nn.LayerNorm",
"torch.matmul",... | [((1750, 1839), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=3, stride=stride, padding=1,\n bias=False)\n', (1759, 1839), True, 'import torch.nn as nn\n'), ((6545, 6631), 'torch.nn.... |
""" The ARIMA model. """
import torch
import numpy as np
class ARIMA(torch.nn.Module):
"""ARIMA [summary]
"""
def __init__(self,
p: int = 0,
d: int = 0,
q: int = 0) -> None:
"""__init__ General ARIMA model constructor.
Args:
... | [
"numpy.random.normal",
"torch.pow",
"torch.diff",
"torch.no_grad",
"torch.zeros",
"torch.rand"
] | [((789, 802), 'torch.rand', 'torch.rand', (['p'], {}), '(p)\n', (799, 802), False, 'import torch\n'), ((889, 902), 'torch.rand', 'torch.rand', (['q'], {}), '(q)\n', (899, 902), False, 'import torch\n'), ((989, 1002), 'torch.rand', 'torch.rand', (['d'], {}), '(d)\n', (999, 1002), False, 'import torch\n'), ((1067, 1080),... |
import matplotlib.pyplot as plt
import numpy as np
import math
import cv2
kernel = np.ones((3, 3), np.int8)
# 去除雜訊
def eraseImage (image):
return cv2.erode(image, kernel, iterations = 1)
# 模糊圖片
def blurImage (image):
return cv2.GaussianBlur(image, (5, 5), 0)
# 銳利化圖片
# threshold1,2,較小的值為作為偵測邊界的最小值
def edgedImage... | [
"cv2.rectangle",
"numpy.ones",
"cv2.resize",
"cv2.erode",
"matplotlib.pyplot.plot",
"cv2.boundingRect",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.findContours",
"cv2.dilate",
"cv2.Canny",
"cv2.imread",
"cv2.GaussianBlur",
"matplotlib.pyplot.show"
] | [((84, 108), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.int8'], {}), '((3, 3), np.int8)\n', (91, 108), True, 'import numpy as np\n'), ((150, 188), 'cv2.erode', 'cv2.erode', (['image', 'kernel'], {'iterations': '(1)'}), '(image, kernel, iterations=1)\n', (159, 188), False, 'import cv2\n'), ((231, 265), 'cv2.GaussianBlur',... |
import numpy as np
import tensorflow as tf
import sys, os
sys.path.extend(['alg/', 'models/'])
from visualisation import plot_images
from encoder_no_shared import encoder, recon
from utils import init_variables, save_params, load_params, load_data
from eval_test_ll import construct_eval_func
dimZ = 50
dimH = 500
n_cha... | [
"eval_test_ll.construct_eval_func",
"generator.construct_gen",
"notmnist.load_notmnist",
"vae_laplace.init_fisher_accum",
"visualisation.plot_images",
"vae_si.update_si_reg",
"tensorflow.placeholder",
"tensorflow.Session",
"utils.load_params",
"os.path.isdir",
"sys.path.extend",
"os.mkdir",
... | [((58, 94), 'sys.path.extend', 'sys.path.extend', (["['alg/', 'models/']"], {}), "(['alg/', 'models/'])\n", (73, 94), False, 'import sys, os\n'), ((580, 608), 'config.config', 'config', (['data_name', 'n_channel'], {}), '(data_name, n_channel)\n', (586, 608), False, 'from config import config\n'), ((1757, 1810), 'tenso... |
# raise NotImplementedError("Did not check!")
"""MSCOCO Semantic Segmentation pretraining for VOC."""
import os
from tqdm import trange
from PIL import Image, ImageOps, ImageFilter
import numpy as np
import pickle
from gluoncv.data.segbase import SegmentationDataset
class COCOSegmentation(SegmentationDataset):
... | [
"os.path.exists",
"pickle.dump",
"os.path.join",
"pycocotools.coco.COCO",
"pickle.load",
"numpy.sum",
"numpy.zeros",
"os.path.expanduser"
] | [((471, 515), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.mxnet/datasets/coco"""'], {}), "('~/.mxnet/datasets/coco')\n", (489, 515), False, 'import os\n'), ((1266, 1280), 'pycocotools.coco.COCO', 'COCO', (['ann_file'], {}), '(ann_file)\n', (1270, 1280), False, 'from pycocotools.coco import COCO\n'), ((1322, 13... |
"""Cell parameter random initializations."""
from typing import Any, Dict
import numpy as np
from ..parameters import (
Height,
NewCellBendLowerLower,
NewCellBendLowerUpper,
NewCellBendOverallLower,
NewCellBendOverallUpper,
NewCellBendUpperLower,
NewCellBendUpperUpper,
NewCellLength1Me... | [
"numpy.sin",
"numpy.cos"
] | [((3328, 3341), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (3334, 3341), True, 'import numpy as np\n'), ((3397, 3410), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (3403, 3410), True, 'import numpy as np\n')] |
import qiskit
import numpy as np
import matplotlib.pyplot as plt
import json
from graph import *
# Random comment
P =1
def makeCircuit(inbits, outbits):
q = qiskit.QuantumRegister(inbits+outbits)
c = qiskit.ClassicalRegister(inbits+outbits)
qc = qiskit.QuantumCircuit(q, c)
q_input = [q[i] for i in ran... | [
"qiskit.ClassicalRegister",
"matplotlib.pyplot.title",
"qiskit.execute",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"json.dump",
"numpy.binary_repr",
"numpy.linspace",
"matplotlib.pyplot.errorbar",
"json.load",
"qiskit.QuantumCircuit",
"qiskit.QuantumRegister",
"matplotlib.pyplo... | [((162, 202), 'qiskit.QuantumRegister', 'qiskit.QuantumRegister', (['(inbits + outbits)'], {}), '(inbits + outbits)\n', (184, 202), False, 'import qiskit\n'), ((209, 251), 'qiskit.ClassicalRegister', 'qiskit.ClassicalRegister', (['(inbits + outbits)'], {}), '(inbits + outbits)\n', (233, 251), False, 'import qiskit\n'),... |
"""Simple code for training an RNN for motion prediction."""
import os
import sys
import time
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
import mtfixb_model
import mtfixb_model2
import parseopts
def create_model(args, total_num_batches):
"""Create MT model a... | [
"numpy.sqrt",
"torch.from_numpy",
"parseopts.parse_args",
"torch.exp",
"parseopts.initial_arg_transform",
"mtfixb_model2.MTGRU_NoBias",
"mtfixb_model.MTGRU",
"mtfixb_model.DataIterator",
"mtfixb_model.OpenLoopGRU",
"sys.stdout.flush",
"torch.optim.SGD",
"mtfixb_model.DynamicsDict",
"numpy.in... | [((890, 1307), 'mtfixb_model.MTGRU', 'mtfixb_model.MTGRU', (['args.seq_length_out', 'args.decoder_size', 'args.decoder_size2', 'args.batch_size', 'total_num_batches', 'args.k', 'args.size_psi_hidden', 'args.size_psi_lowrank', 'args.bottleneck'], {'output_dim': 'args.human_size', 'input_dim': 'args.input_size', 'dropout... |
import time
import numpy as np
import vtk
from vtk.util import numpy_support
from svtk.lib.toolbox.integer import minmax
from svtk.lib.toolbox.idarray import IdArray
from svtk.lib.toolbox.numpy_helpers import normalize
import math as m
class VTKAnimationTimerCallback(object):
"""This class is called every few m... | [
"numpy.tile",
"numpy.allclose",
"math.ceil",
"numpy.cross",
"time.clock",
"math.floor",
"svtk.lib.toolbox.idarray.IdArray",
"vtk.util.numpy_support.numpy_to_vtkIdTypeArray",
"svtk.lib.toolbox.integer.minmax",
"numpy.append",
"numpy.array",
"numpy.matmul",
"vtk.util.numpy_support.numpy_to_vtk... | [((1209, 1221), 'time.clock', 'time.clock', ([], {}), '()\n', (1219, 1221), False, 'import time\n'), ((1264, 1276), 'time.clock', 'time.clock', ([], {}), '()\n', (1274, 1276), False, 'import time\n'), ((1322, 1334), 'time.clock', 'time.clock', ([], {}), '()\n', (1332, 1334), False, 'import time\n'), ((1361, 1373), 'tim... |
import time
import numpy as np
from tqdm import tqdm
from utils import RandomCNOT, RandomCNOTs
def SimulatedAnnealing(quantum_count, layer_count, solver, epochs=100, save_path=None, global_best_score=0):
#TODO:
best_score = 0
cnot = RandomCNOTs(quantum_count, layer_count)
sc, model = solver(cnot)
... | [
"utils.RandomCNOTs",
"numpy.random.randint",
"time.time",
"utils.RandomCNOT"
] | [((247, 286), 'utils.RandomCNOTs', 'RandomCNOTs', (['quantum_count', 'layer_count'], {}), '(quantum_count, layer_count)\n', (258, 286), False, 'from utils import RandomCNOT, RandomCNOTs\n'), ((591, 602), 'time.time', 'time.time', ([], {}), '()\n', (600, 602), False, 'import time\n'), ((2114, 2125), 'time.time', 'time.t... |
from __future__ import print_function, division
import numpy as np
from numpy import identity, dot, zeros, zeros_like
def rf_den_via_rf0(self, rf0, v):
""" Whole matrix of the interacting response via non-interacting response and interaction"""
rf = zeros_like(rf0)
I = identity(rf0.shape[1])
for ir,r in enume... | [
"numpy.identity",
"numpy.dot",
"numpy.zeros_like"
] | [((255, 270), 'numpy.zeros_like', 'zeros_like', (['rf0'], {}), '(rf0)\n', (265, 270), False, 'from numpy import identity, dot, zeros, zeros_like\n'), ((278, 300), 'numpy.identity', 'identity', (['rf0.shape[1]'], {}), '(rf0.shape[1])\n', (286, 300), False, 'from numpy import identity, dot, zeros, zeros_like\n'), ((364, ... |
import os
import logging
import numpy as np
from typing import Optional
import torch
from torch.utils.data import DataLoader
from ..eval import Metric
from .dataset import CHMMBaseDataset
from .dataset import collate_fn as default_collate_fn
logger = logging.getLogger(__name__)
OUT_RECALL = 0.9
OUT_PRECISION = 0.8
... | [
"logging.getLogger",
"torch.load",
"os.path.join",
"os.path.split",
"os.path.isfile",
"numpy.random.dirichlet",
"torch.save",
"torch.utils.data.DataLoader",
"torch.zeros"
] | [((254, 281), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (271, 281), False, 'import logging\n'), ((14610, 14650), 'numpy.random.dirichlet', 'np.random.dirichlet', (['(init_counts + 1e-10)'], {}), '(init_counts + 1e-10)\n', (14629, 14650), True, 'import numpy as np\n'), ((2409, 2454), ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 13:03:05 2017
@author: <NAME>
"""
import cntk as C
import _cntk_py
import cntk.layers
import cntk.initializer
import cntk.losses
import cntk.metrics
import cntk.logging
import cntk.io.transforms as xforms
import cntk.io
import cntk.train
import os
import numpy as np
i... | [
"os.path.exists",
"yolo2.Yolo2Metric",
"_cntk_py.set_computation_network_trace_level",
"cntk.Trainer",
"os.path.join",
"cntk.learners.momentum_sgd",
"yolo2.Yolo2Error",
"cntk.io.transforms.color",
"cntk.learners.momentum_schedule",
"cntk.input_variable",
"cntk.io.transforms.scale",
"numpy.arra... | [((469, 501), 'os.path.join', 'os.path.join', (['abs_path', '"""Models"""'], {}), "(abs_path, 'Models')\n", (481, 501), False, 'import os\n'), ((429, 454), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (444, 454), False, 'import os\n'), ((2267, 2326), 'cntk.input_variable', 'C.input_variable... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 09:52:47 2015
@author: wirkert
"""
import unittest
import os
import numpy as np
import msi.msimanipulations as msimani
from msi.io.nrrdreader import NrrdReader
from msi.io.nrrdwriter import NrrdWriter
from msi.test import helpers
class TestNrrdWriter(unittest.TestC... | [
"msi.io.nrrdreader.NrrdReader",
"os.remove",
"os.path.isfile",
"numpy.array",
"msi.msimanipulations.calculate_mean_spectrum",
"msi.test.helpers.getFakeMsi",
"msi.io.nrrdwriter.NrrdWriter"
] | [((430, 450), 'msi.test.helpers.getFakeMsi', 'helpers.getFakeMsi', ([], {}), '()\n', (448, 450), False, 'from msi.test import helpers\n'), ((574, 604), 'os.remove', 'os.remove', (['self.fileUriToWrite'], {}), '(self.fileUriToWrite)\n', (583, 604), False, 'import os\n'), ((666, 686), 'msi.io.nrrdwriter.NrrdWriter', 'Nrr... |
import matplotlib.pyplot as pl
import os
import numpy as np
from ticle.data.dataHandler import normalizeData,load_file
from ticle.analysis.analysis import get_phases,normalize_phase
pl.rc('xtick', labelsize='x-small')
pl.rc('ytick', labelsize='x-small')
pl.rc('font', family='serif')
pl.rcParams.update({'font.size': 2... | [
"os.makedirs",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"ticle.data.dataHandler.load_file",
"os.getcwd",
"ticle.data.dataHandler.normalizeData",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure",
"ticle.analysis.analysis.get_phases",
"numpy.... | [((184, 219), 'matplotlib.pyplot.rc', 'pl.rc', (['"""xtick"""'], {'labelsize': '"""x-small"""'}), "('xtick', labelsize='x-small')\n", (189, 219), True, 'import matplotlib.pyplot as pl\n'), ((220, 255), 'matplotlib.pyplot.rc', 'pl.rc', (['"""ytick"""'], {'labelsize': '"""x-small"""'}), "('ytick', labelsize='x-small')\n"... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# Extended by <NAME>
# --------------------------------------------------------
import os
import cv2
import numpy as np
import torch
impor... | [
"os.path.exists",
"xml.etree.ElementTree.parse",
"cv2.flip",
"numpy.random.rand",
"numpy.where",
"os.path.join",
"numpy.array",
"cv2.imread"
] | [((3434, 3493), 'os.path.join', 'os.path.join', (['self.data_path', '"""Annotations"""', "(index + '.xml')"], {}), "(self.data_path, 'Annotations', index + '.xml')\n", (3446, 3493), False, 'import os\n'), ((3509, 3527), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (3517, 3527), True, '... |
# Machine Learning Online Class - Exercise 2: Logistic Regression
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the logistic
# regression exercise. You will need to complete the following functions
# in this exericse:
#
# sigmoid.py
# costFunction.py
# predic... | [
"numpy.mean",
"predict.predict",
"numpy.ones",
"matplotlib.pyplot.ylabel",
"scipy.optimize.fmin_bfgs",
"matplotlib.pyplot.xlabel",
"plotDecisionBoundary.plot_decision_boundary",
"numpy.array",
"numpy.zeros",
"costFunction.cost_function",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.axis",
"nu... | [((696, 705), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (703, 705), True, 'import matplotlib.pyplot as plt\n'), ((814, 855), 'numpy.loadtxt', 'np.loadtxt', (['"""ex2data1.txt"""'], {'delimiter': '""","""'}), "('ex2data1.txt', delimiter=',')\n", (824, 855), True, 'import numpy as np\n'), ((1827, 1855), 'matp... |
#poly_gauss_coil model
#conversion of Poly_GaussCoil.py
#converted by <NAME>, Mar 2016
r"""
This empirical model describes the scattering from *polydisperse* polymer
chains in theta solvents or polymer melts, assuming a Schulz-Zimm type
molecular weight distribution.
To describe the scattering from *monodisperse* poly... | [
"numpy.expm1",
"numpy.polyval",
"numpy.power",
"numpy.random.uniform"
] | [((3486, 3510), 'numpy.polyval', 'np.polyval', (['p', 'z[~index]'], {}), '(p, z[~index])\n', (3496, 3510), True, 'import numpy as np\n'), ((3677, 3700), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(4)'], {}), '(0, 4)\n', (3694, 3700), True, 'import numpy as np\n'), ((3740, 3763), 'numpy.random.uniform', 'np.... |
import os
from itertools import product
from concurrent import futures
from contextlib import closing
from datetime import datetime
import numpy as np
from . import _z5py
from .file import File, S3File
from .dataset import Dataset
from .shape_utils import normalize_slices
def product1d(inrange):
for ii in inrang... | [
"urllib2.urlopen",
"zipfile.ZipFile",
"datetime.datetime.utcnow",
"concurrent.futures.ThreadPoolExecutor",
"itertools.product",
"os.path.join",
"imageio.volread",
"numpy.sum"
] | [((11994, 12022), 'imageio.volread', 'volread', (['"""imageio:stent.npz"""'], {}), "('imageio:stent.npz')\n", (12001, 12022), False, 'from imageio import volread\n'), ((2191, 2207), 'itertools.product', 'product', (['*ranges'], {}), '(*ranges)\n', (2198, 2207), False, 'from itertools import product\n'), ((7395, 7444), ... |
"""
Data creation:
Load the data, normalize it, and split into train and test.
"""
'''
Added the capability of loading pre-separated UCI train/test data
function LoadData_Splitted_UCI
'''
import numpy as np
import os
import pandas as pd
import tensorflow as tf
DATA_PATH = "../UCI_Datasets"
class DataGenerator:... | [
"numpy.random.normal",
"tensorflow.random.normal",
"numpy.mean",
"tensorflow.reduce_sum",
"os.path.join",
"numpy.random.seed",
"numpy.std",
"tensorflow.convert_to_tensor",
"numpy.loadtxt",
"numpy.load",
"tensorflow.compat.v1.Session",
"numpy.random.permutation"
] | [((714, 752), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(Ntrain, Npar)'}), '(shape=(Ntrain, Npar))\n', (730, 752), True, 'import tensorflow as tf\n'), ((1174, 1220), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x_test'], {'dtype': 'tf.float32'}), '(x_test, dtype=tf.float32)\n', (1194... |
from __future__ import print_function
import emcee
from multiprocessing import Pool
import numpy as np
import corner
import matplotlib.pyplot as plt
import sys
import scipy.optimize as op
from rbvfit.rb_vfit import rb_veldiff as rb_veldiff
from rbvfit import rb_setline as rb
import pdb
def plot_model(wave_obs,fnorm,e... | [
"numpy.log",
"emcee.EnsembleSampler",
"numpy.array",
"numpy.isfinite",
"rbvfit.rb_vfit.rb_veldiff",
"corner.corner",
"numpy.diff",
"numpy.concatenate",
"numpy.round",
"numpy.tile",
"scipy.optimize.minimize",
"IPython.display.Math",
"numpy.shape",
"numpy.random.randn",
"matplotlib.pyplot.... | [((1731, 1832), 'matplotlib.pyplot.subplots', 'plt.subplots', (['ntransition'], {'sharex': '(True)', 'sharey': '(False)', 'figsize': '(12, 18)', 'gridspec_kw': "{'hspace': 0}"}), "(ntransition, sharex=True, sharey=False, figsize=(12, 18),\n gridspec_kw={'hspace': 0})\n", (1743, 1832), True, 'import matplotlib.pyplot... |
from numpy import logspace
from sys import path as sysPath
sysPath.append('../../src')
#load the module
from interfacePy import Cosmo
cosmo=Cosmo('../../src/data/eos2020.dat',0,1e5)
for T in logspace(-5,5,50):
print(
'T=',T,'GeV\t',
'H=',cosmo.Hubble(T),'GeV\t',
'h_eff=',cosmo.heff(T),... | [
"matplotlib.pyplot.figure",
"numpy.logspace",
"sys.path.append",
"interfacePy.Cosmo"
] | [((61, 88), 'sys.path.append', 'sysPath.append', (['"""../../src"""'], {}), "('../../src')\n", (75, 88), True, 'from sys import path as sysPath\n'), ((145, 193), 'interfacePy.Cosmo', 'Cosmo', (['"""../../src/data/eos2020.dat"""', '(0)', '(100000.0)'], {}), "('../../src/data/eos2020.dat', 0, 100000.0)\n", (150, 193), Fa... |
import numpy as np
from pyquil.gate_matrices import X, Y, Z, H
from forest.benchmarking.operator_tools.superoperator_transformations import *
# Test philosophy:
# Using the by hand calculations found in the docs we check conversion
# between one qubit channels with one Kraus operator (Hadamard) and two
# Kraus operat... | [
"numpy.abs",
"numpy.eye",
"numpy.allclose",
"numpy.sqrt",
"numpy.random.rand",
"numpy.asarray",
"numpy.diag",
"numpy.kron",
"numpy.array",
"numpy.zeros",
"numpy.matmul"
] | [((3245, 3310), 'numpy.diag', 'np.diag', (['[1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1]'], {}), '([1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1])\n', (3252, 3310), True, 'import numpy as np\n'), ((3365, 3393), 'numpy.asarray', 'np.asarray', (['[[0, 0], [0, 1]]'], {}), '([[0, 0], [0, 1]])\n', (337... |
import numpy as np
import imageio
from PoissonTemperature import FiniteDifferenceMatrixConstruction
def ind_sub_conversion(img, ind2sub_fn, sub2ind_fn):
rows, cols = img.shape[:2]
num = rows*cols
arange = np.arange(rows*cols, dtype=np.int32)
ind2sub = np.empty((num, 2), dtype=np.int32)
ind2sub[:, ... | [
"numpy.arange",
"imageio.imwrite",
"numpy.floor",
"PoissonTemperature.FiniteDifferenceMatrixConstruction",
"numpy.remainder",
"numpy.empty",
"imageio.imread",
"numpy.save"
] | [((219, 257), 'numpy.arange', 'np.arange', (['(rows * cols)'], {'dtype': 'np.int32'}), '(rows * cols, dtype=np.int32)\n', (228, 257), True, 'import numpy as np\n'), ((270, 304), 'numpy.empty', 'np.empty', (['(num, 2)'], {'dtype': 'np.int32'}), '((num, 2), dtype=np.int32)\n', (278, 304), True, 'import numpy as np\n'), (... |
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
def convert_to_sqft(str):
tokens = str.split(' - ')
if len(tokens) == 2:
return (float(tokens[0]) + float(tokens[1])) / 2
try:
return float(tokens[0])
except Exception:
return np.NAN
def co... | [
"pandas.get_dummies",
"numpy.where",
"sklearn.linear_model.LinearRegression",
"pandas.read_csv"
] | [((441, 459), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (457, 459), False, 'from sklearn.linear_model import LinearRegression\n'), ((549, 590), 'pandas.read_csv', 'pd.read_csv', (['"""./Bengaluru_House_Data.csv"""'], {}), "('./Bengaluru_House_Data.csv')\n", (560, 590), True, 'import... |
import numpy as np
import numpy.testing as npt
import slippy
import slippy.core as core
"""
If you add a material you need to add the properties that it will be tested with to the material_parameters dict,
the key should be the name of the class (what ever it is declared as after the class key word).
The value should ... | [
"slippy.asnumpy",
"slippy.core.Elastic",
"numpy.random.rand",
"numpy.random.seed"
] | [((2428, 2484), 'slippy.core.Elastic', 'core.Elastic', (['"""steel_6"""', "{'E': 200000000000.0, 'v': 0.3}"], {}), "('steel_6', {'E': 200000000000.0, 'v': 0.3})\n", (2440, 2484), True, 'import slippy.core as core\n'), ((2480, 2497), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2494, 2497), True, 'imp... |
# Copyright 2020-2021 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... | [
"pyglet.gl.glGetDoublev",
"numpy.asarray",
"numpy.argsort",
"numpy.sum",
"numpy.zeros",
"pyglet.gl.glGetIntegerv",
"numpy.linalg.norm",
"numpy.transpose",
"pyglet.gl.GLdouble",
"pyglet.gl.gluUnProject"
] | [((1131, 1191), 'pyglet.gl.glGetDoublev', 'pyglet.gl.glGetDoublev', (['pyglet.gl.GL_MODELVIEW_MATRIX', 'mvmat'], {}), '(pyglet.gl.GL_MODELVIEW_MATRIX, mvmat)\n', (1153, 1191), False, 'import pyglet\n'), ((1200, 1260), 'pyglet.gl.glGetDoublev', 'pyglet.gl.glGetDoublev', (['pyglet.gl.GL_PROJECTION_MATRIX', 'pmat'], {}), ... |
from tensorflow.keras.models import Model
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import cv2
import numpy as np
import pandas as pd
from tensorflow.keras.models import load_model
import tensorflow as tf
import os
#--------------... | [
"numpy.uint8",
"os.path.join",
"tensorflow.keras.preprocessing.image.array_to_img",
"tensorflow.GradientTape",
"tensorflow.squeeze",
"tensorflow.math.reduce_max",
"tensorflow.maximum",
"tensorflow.reduce_mean",
"tensorflow.keras.preprocessing.image.img_to_array",
"tensorflow.cast",
"matplotlib.c... | [((3903, 3940), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['grads'], {'axis': '(0, 1, 2)'}), '(grads, axis=(0, 1, 2))\n', (3917, 3940), True, 'import tensorflow as tf\n'), ((4296, 4315), 'tensorflow.squeeze', 'tf.squeeze', (['heatmap'], {}), '(heatmap)\n', (4306, 4315), True, 'import tensorflow as tf\n'), ((4888, 49... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Common utility functions
Created on Sun May 27 16:37:42 2018
@author: chen
"""
import math
import cv2
import os
from imutils import paths
import numpy as np
import scipy.ndimage
def rotate_cooridinate(cooridinate_og,rotate_angle,rotate_center):
"""
calculat... | [
"numpy.sqrt",
"math.cos",
"numpy.array",
"imutils.paths.list_images",
"math.exp",
"os.path.exists",
"numpy.max",
"numpy.exp",
"numpy.concatenate",
"numpy.min",
"numpy.maximum",
"numpy.round",
"numpy.random.choice",
"numpy.int",
"cv2.imread",
"numpy.minimum",
"os.makedirs",
"numpy.p... | [((774, 806), 'numpy.array', 'np.array', (['[rotated_x, rotated_y]'], {}), '([rotated_x, rotated_y])\n', (782, 806), True, 'import numpy as np\n'), ((988, 1008), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1002, 1008), False, 'import os\n'), ((2068, 2209), 'numpy.array', 'np.array', (['[box[0][::-1... |
from typing import Dict, Any, Optional, List
import gym
import numpy as np
from collections import defaultdict
from flatland.core.grid.grid4_utils import get_new_position
from flatland.envs.agent_utils import EnvAgent, RailAgentStatus
from flatland.envs.rail_env import RailEnv, RailEnvActions
from envs.flatland.obse... | [
"gym.spaces.Discrete",
"envs.flatland.observations.segment_graph.Graph.get_virtual_position",
"gym.spaces.Box",
"numpy.count_nonzero",
"numpy.argmax",
"collections.defaultdict",
"envs.flatland.utils.gym_env.StepOutput",
"flatland.utils.rendertools.RenderTool",
"flatland.core.grid.grid4_utils.get_new... | [((5246, 5263), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5257, 5263), False, 'from collections import defaultdict\n'), ((6896, 6918), 'envs.flatland.utils.gym_env.StepOutput', 'StepOutput', (['o', 'r', 'd', 'i'], {}), '(o, r, d, i)\n', (6906, 6918), False, 'from envs.flatland.utils.gym_env... |
import numpy as np
import cv2 as cv
img = cv.imread('1.jpeg',cv.IMREAD_COLOR)
#for polygon we need to have set of points so we create a numpy array. and pts is an object.
pts = np.array([[20,33],[300,120], [67,79], [123,111], [144,134]], np.int32)
#the method polylines will actully draws a polygon by taking differe... | [
"cv2.polylines",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.waitKey",
"cv2.imread"
] | [((43, 79), 'cv2.imread', 'cv.imread', (['"""1.jpeg"""', 'cv.IMREAD_COLOR'], {}), "('1.jpeg', cv.IMREAD_COLOR)\n", (52, 79), True, 'import cv2 as cv\n'), ((180, 256), 'numpy.array', 'np.array', (['[[20, 33], [300, 120], [67, 79], [123, 111], [144, 134]]', 'np.int32'], {}), '([[20, 33], [300, 120], [67, 79], [123, 111],... |
import scipy, numpy, typing, numbers
from tequila.objective import Objective
from tequila.objective.objective import assign_variable, Variable, format_variable_dictionary, format_variable_list
from .optimizer_base import Optimizer
from ._containers import _EvalContainer, _GradContainer, _HessContainer, _QngContainer
fr... | [
"collections.namedtuple",
"tequila.objective.objective.format_variable_dictionary",
"tequila.tools.qng.get_qng_combos",
"scipy.optimize.minimize",
"numpy.array",
"tequila.utils.exceptions.TequilaException",
"tequila.objective.objective.assign_variable"
] | [((587, 654), 'collections.namedtuple', 'namedtuple', (['"""SciPyReturnType"""', '"""energy angles history scipy_output"""'], {}), "('SciPyReturnType', 'energy angles history scipy_output')\n", (597, 654), False, 'from collections import namedtuple\n'), ((16511, 16552), 'tequila.objective.objective.format_variable_dict... |
#
# This file is part of the chi repository
# (https://github.com/DavAug/chi/) which is released under the
# BSD 3-clause license. See accompanying LICENSE.md for copyright notice and
# full license details.
#
import copy
import myokit
import myokit.formats.sbml as sbml
import numpy as np
class MechanisticModel(obj... | [
"numpy.alltrue",
"myokit.formats.sbml.SBMLImporter",
"myokit.pacing.blocktrain",
"myokit.Simulation",
"numpy.argsort",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.empty",
"copy.deepcopy",
"copy.copy",
"myokit.Name"
] | [((984, 1014), 'myokit.Simulation', 'myokit.Simulation', (['self._model'], {}), '(self._model)\n', (1001, 1014), False, 'import myokit\n'), ((1824, 1844), 'numpy.array', 'np.array', (['parameters'], {}), '(parameters)\n', (1832, 1844), True, 'import numpy as np\n'), ((2721, 2738), 'numpy.argsort', 'np.argsort', (['name... |
import bpy
import bmesh
import numpy
from random import randint
import time
# pointsToVoxels() has been modified from the function generate_blocks() in https://github.com/cagcoach/BlenderPlot/blob/master/blendplot.py
# Some changes to accomodate Blender 2.8's API changes were made,
# and the function has been made m... | [
"numpy.tile",
"numpy.reshape",
"numpy.unique",
"bmesh.update_edit_mesh",
"bpy.data.objects.new",
"bpy.data.meshes.new",
"bpy.context.collection.objects.link",
"bmesh.new",
"numpy.array",
"time.time",
"bpy.ops.mesh.primitive_cube_add"
] | [((721, 749), 'numpy.unique', 'numpy.unique', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (733, 749), False, 'import numpy\n'), ((806, 833), 'bpy.data.meshes.new', 'bpy.data.meshes.new', (['"""mesh"""'], {}), "('mesh')\n", (825, 833), False, 'import bpy\n'), ((862, 894), 'bpy.data.objects.new', 'bpy.data.objec... |
import unittest
from hashlib import sha1
import pickle
import numpy as np
from datasketch.lsh import MinHashLSH
from datasketch.minhash import MinHash
from datasketch.weighted_minhash import WeightedMinHashGenerator
class TestMinHashLSH(unittest.TestCase):
def test_init(self):
lsh = MinHashLSH(threshold=... | [
"datasketch.lsh.MinHashLSH",
"datasketch.weighted_minhash.WeightedMinHashGenerator",
"pickle.dumps",
"datasketch.minhash.MinHash",
"numpy.random.uniform",
"unittest.main"
] | [((5700, 5715), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5713, 5715), False, 'import unittest\n'), ((299, 324), 'datasketch.lsh.MinHashLSH', 'MinHashLSH', ([], {'threshold': '(0.8)'}), '(threshold=0.8)\n', (309, 324), False, 'from datasketch.lsh import MinHashLSH\n'), ((409, 454), 'datasketch.lsh.MinHashLSH... |
import logging
from typing import Callable
from typing import List
import numpy as np
import torch.utils.data
from .video_dataset import VideoDataset
from .video_dataset import VideoRecord
LOG = logging.getLogger(__name__)
# line_profiler injects a "profile" into __builtins__. When not running under
# line_profile... | [
"logging.getLogger",
"numpy.zeros",
"numpy.random.randint"
] | [((199, 226), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (216, 226), False, 'import logging\n'), ((3419, 3449), 'numpy.zeros', 'np.zeros', (['(self.num_segments,)'], {}), '((self.num_segments,))\n', (3427, 3449), True, 'import numpy as np\n'), ((2618, 2677), 'numpy.random.randint', 'n... |
# The MIT License (MIT)
#
# Copyright © 2021 <NAME>, <NAME>, <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... | [
"matplotlib.pyplot.grid",
"numpy.linalg.pinv",
"sklearn.linear_model.Lasso",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"numpy.arange",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.exp",
"numpy.linspace",
"numpy.matmul",
"pandas.DataFrame",
... | [((1979, 2005), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 7)'}), '(figsize=(8, 7))\n', (1989, 2005), True, 'import matplotlib.pyplot as plt\n'), ((2500, 2516), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2509, 2516), True, 'import matplotlib.pyplot as plt\n'), ((2521, 25... |
import numpy as np
import pandas as pd
import os.path as path
import abydos.distance as abd
import abydos.phonetic as abp
import pytest
from scipy.sparse import csc_matrix
from sklearn.feature_extraction.text import TfidfVectorizer
import name_matching.name_matcher as nm
@pytest.fixture
def name_match():
package... | [
"abydos.distance.Overlap",
"abydos.phonetic.RefinedSoundex",
"numpy.array",
"abydos.distance.Levenshtein",
"abydos.distance.KuhnsIII",
"abydos.distance.BaulieuXIII",
"name_matching.name_matcher.NameMatcher",
"pandas.testing.assert_frame_equal",
"abydos.distance.WeightedJaccard",
"abydos.phonetic.D... | [((1163, 1221), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""method"""', "['', None, 'no_method']"], {}), "('method', ['', None, 'no_method'])\n", (1186, 1221), False, 'import pytest\n'), ((3589, 3929), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kwargs_str, result_1, result_2, result_3, ... |
import numpy as np
import math
import ROOT
import sys
class DistrReader:
def __init__(self, dataset):
self.stat_error = 0
self.sys_error = 0
self.plambda = 0
self.dataset = str(dataset)
self.hist = ROOT.TH1D('','', 100, -0.2, 0.2)
self.distr = ROOT.TH1D('','', 64, 0,... | [
"numpy.sqrt",
"ROOT.TH1D",
"numpy.power",
"ROOT.TMath.Log",
"ROOT.TFile"
] | [((243, 276), 'ROOT.TH1D', 'ROOT.TH1D', (['""""""', '""""""', '(100)', '(-0.2)', '(0.2)'], {}), "('', '', 100, -0.2, 0.2)\n", (252, 276), False, 'import ROOT\n'), ((297, 325), 'ROOT.TH1D', 'ROOT.TH1D', (['""""""', '""""""', '(64)', '(0)', '(64)'], {}), "('', '', 64, 0, 64)\n", (306, 325), False, 'import ROOT\n'), ((814... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from lottery.branch import base
import models.registry
from pruning.mask import Mask
from pruning.pruned_model import PrunedModel... | [
"utils.tensor_utils.erank",
"pruning.pruned_model.PrunedModel.to_mask_name",
"matplotlib.use",
"pruning.mask.Mask.load",
"pruning.mask.Mask.ones_like",
"os.path.join",
"numpy.argmax",
"seaborn.set_style",
"pruning.mask.Mask",
"seaborn.lineplot",
"torch.svd",
"copy.deepcopy",
"platforms.platf... | [((689, 710), 'matplotlib.use', 'matplotlib.use', (['"""pdf"""'], {}), "('pdf')\n", (703, 710), False, 'import matplotlib\n'), ((909, 935), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (922, 935), True, 'import seaborn as sns\n'), ((1281, 1307), 'pruning.mask.Mask.load', 'Mask.loa... |
"""
==============
GLVQ Benchmark
==============
This example shows the differences between the 4 different GLVQ implementations and LMNN.
The Image Segmentation dataset is used for training and test. Each plot shows the projection
and classification from each implementation. Because Glvq can't project the data on its ... | [
"sklearn_lvq.GmlvqModel",
"sklearn_lvq.LgmlvqModel",
"sklearn.decomposition.PCA",
"numpy.asarray",
"sklearn_lvq.utils._to_tango_colors",
"numpy.array",
"metric_learn.LMNN",
"sklearn_lvq.utils._tango_color",
"sklearn_lvq.GlvqModel",
"matplotlib.pyplot.subplot",
"sklearn_lvq.GrlvqModel",
"matplo... | [((1441, 1471), 'numpy.asarray', 'np.asarray', (['x'], {'dtype': '"""float64"""'}), "(x, dtype='float64')\n", (1451, 1471), True, 'import numpy as np\n'), ((1476, 1489), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (1486, 1489), True, 'import numpy as np\n'), ((1498, 1525), 'metric_learn.LMNN', 'LMNN', ([], {'k... |
import pytest
import re
import unittest
import metric_learn
import numpy as np
from sklearn import clone
from test.test_utils import ids_metric_learners, metric_learners, remove_y
from metric_learn.sklearn_shims import set_random_state, SKLEARN_AT_LEAST_0_22
def remove_spaces(s):
return re.sub(r'\s+', '', s)
def ... | [
"metric_learn.SDML",
"metric_learn.sklearn_shims.set_random_state",
"numpy.array",
"sklearn.clone",
"numpy.sin",
"unittest.main",
"metric_learn.MMC",
"metric_learn.MMC_Supervised",
"metric_learn.MLKR",
"metric_learn.NCA",
"test.test_utils.remove_y",
"metric_learn.SDML_Supervised",
"metric_le... | [((7493, 7591), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""estimator, build_dataset"""', 'metric_learners'], {'ids': 'ids_metric_learners'}), "('estimator, build_dataset', metric_learners, ids=\n ids_metric_learners)\n", (7516, 7591), False, 'import pytest\n'), ((8409, 8507), 'pytest.mark.parametriz... |
import numpy as np
import pandas as pd
import scipy as sc
from scipy.stats import randint, norm, multivariate_normal, ortho_group
from scipy import linalg
from scipy.linalg import subspace_angles, orth
from scipy.optimize import fmin
import math
from statistics import mean
import seaborn as sns
from sklearn.cluster imp... | [
"sklearn.cluster.KMeans",
"statistics.mean",
"numpy.trace",
"scipy.optimize.bisect",
"numpy.random.rand",
"cluster.selfrepresentation.ElasticNetSubspaceClustering",
"numpy.ones",
"sklearn.decomposition.PCA",
"math.degrees",
"seaborn.heatmap",
"numpy.array",
"numpy.random.randint",
"numpy.zer... | [((2804, 2824), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'k'}), '(n_clusters=k)\n', (2810, 2824), False, 'from sklearn.cluster import KMeans\n'), ((2842, 2857), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (2854, 2857), True, 'import pandas as pd\n'), ((6547, 6561), 'pandas.DataFrame', 'pd.D... |
# LinearRegression.py
# March 2018
#
# This script builds a Linear regression class to analyse data.
# It supports a continuous response and several continuous features.
# The class has a constructor building and fitting the model, and
# a plotting method for residuals.
#
# Dependencies:
#
# Usage:
# from pythia.Li... | [
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"numpy.array",
"numpy.poly1d",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.asarray",
"matplotlib.pyplot.axhline",
"numpy.dot",
"matplotlib.pyplot.scatter",
"numpy.abs",
"numpy.ones",
"matplotlib.use",
"matplotlib.pyplot.title",
... | [((468, 489), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (482, 489), False, 'import matplotlib\n'), ((563, 583), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (578, 583), False, 'import os\n'), ((604, 626), 'os.path.abspath', 'os.path.abspath', (['"""../"""'], {}), "('..... |
#!python3
#
# Copyright (C) 2014-2015 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""
PYPOWER-Dynamics
Functions for standard blocks (solves a step)
"""
import numpy as np
# Gain block
# yo = p * yi
# p is a scalar gain coefficie... | [
"numpy.prod"
] | [((1560, 1571), 'numpy.prod', 'np.prod', (['yi'], {}), '(yi)\n', (1567, 1571), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""Supports F10.7 index values. Downloads data from LASP and the SWPC.
Properties
----------
platform
'sw'
name
'f107'
tag
- 'historic' LASP F10.7 data (downloads by month, loads by day)
- 'prelim' Preliminary SWPC daily solar indices
- 'daily' Daily SWPC solar indices (cont... | [
"pysat.Files.from_os",
"datetime.timedelta",
"pysatSpaceWeather.instruments.methods.f107.rewrite_daily_file",
"pandas.date_range",
"os.remove",
"datetime.datetime",
"ftplib.FTP",
"numpy.where",
"pandas.DataFrame.from_dict",
"os.path.split",
"pandas.DataFrame",
"sys.stdout.flush",
"json.loads... | [((3004, 3024), 'datetime.datetime.utcnow', 'dt.datetime.utcnow', ([], {}), '()\n', (3022, 3024), True, 'import datetime as dt\n'), ((3033, 3074), 'datetime.datetime', 'dt.datetime', (['now.year', 'now.month', 'now.day'], {}), '(now.year, now.month, now.day)\n', (3044, 3074), True, 'import datetime as dt\n'), ((3178, 3... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Usage: %(scriptName) <bug_report_file> <data_prefix>
"""
import json
from timeit import default_timer
import datetime
import numpy as np
import pickle
import sys
from multiprocessing import Pool
from operator import itemgetter
from scipy import sparse
from sklearn.fe... | [
"sklearn.feature_extraction.text.TfidfTransformer",
"unqlite.UnQLite",
"timeit.default_timer",
"scipy.sparse.load_npz",
"tqdm.tqdm",
"operator.itemgetter",
"json.load",
"numpy.sum",
"datetime.datetime.now",
"numpy.zeros",
"multiprocessing.Pool",
"pickle.loads",
"scipy.sparse.save_npz",
"sc... | [((543, 558), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (556, 558), False, 'from timeit import default_timer\n'), ((846, 861), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (859, 861), False, 'from timeit import default_timer\n'), ((2114, 2147), 'pickle.loads', 'pickle.loads', (['types[var... |
import PIL
import numpy as np
def to_grayscale(img):
return np.dot(img, [0.299, 0.587, 0.144])
def zero_center(img):
return img - 127.0
def crop(img, bottom=12, left=6, right=6):
height, width = img.shape
return img[0: height - bottom, left: width - right]
def save(img, path):
pil_img = PIL.... | [
"numpy.dot",
"PIL.Image.fromarray"
] | [((66, 100), 'numpy.dot', 'np.dot', (['img', '[0.299, 0.587, 0.144]'], {}), '(img, [0.299, 0.587, 0.144])\n', (72, 100), True, 'import numpy as np\n'), ((316, 340), 'PIL.Image.fromarray', 'PIL.Image.fromarray', (['img'], {}), '(img)\n', (335, 340), False, 'import PIL\n')] |
"""
S3AIO Class
Array access to a single S3 object
"""
from __future__ import absolute_import
import SharedArray as sa
import zstd
from itertools import repeat, product
import numpy as np
from pathos.multiprocessing import ProcessingPool
from six.moves import zip
try:
from StringIO import StringIO
except Impor... | [
"SharedArray.create",
"numpy.ravel_multi_index",
"itertools.product",
"zstd.ZstdDecompressor",
"SharedArray.delete",
"numpy.empty",
"numpy.unravel_index",
"numpy.frombuffer",
"numpy.dtype",
"SharedArray.attach",
"six.moves.zip",
"pathos.multiprocessing.ProcessingPool",
"itertools.repeat"
] | [((998, 1025), 'pathos.multiprocessing.ProcessingPool', 'ProcessingPool', (['num_workers'], {}), '(num_workers)\n', (1012, 1025), False, 'from pathos.multiprocessing import ProcessingPool\n'), ((1340, 1374), 'numpy.ravel_multi_index', 'np.ravel_multi_index', (['index', 'shape'], {}), '(index, shape)\n', (1360, 1374), T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.