code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""evaluate model performance
TODO
- Evaluate by window and by participant (rewrite to make windows)
"""
import torch
import torch.nn.functional as F
import torchaudio
from transformers import AutoConfig, Wav2Vec2FeatureExtractor, Wav2Vec2ForSequenceClassification
import numpy as np
import pandas as pd
import os
... | [
"torch.nn.functional.softmax",
"transformers.AutoConfig.from_pretrained",
"sklearn.metrics.classification_report",
"torchaudio.load",
"transformers.Wav2Vec2ForSequenceClassification.from_pretrained",
"os.path.join",
"numpy.argmax",
"transformers.Wav2Vec2FeatureExtractor.from_pretrained",
"torchaudio... | [((418, 479), 'os.path.join', 'os.path.join', (['"""model"""', '"""xlsr_autism_stories"""', '"""checkpoint-10"""'], {}), "('model', 'xlsr_autism_stories', 'checkpoint-10')\n", (430, 479), False, 'import os\n'), ((1706, 1744), 'transformers.AutoConfig.from_pretrained', 'AutoConfig.from_pretrained', (['MODEL_PATH'], {}),... |
# authors: anonymous
import numpy as np
import time
# Sectect action based on the the action-state function with a softmax strategy
def softmax_action(Q, s):
proba=np.exp(Q[s, :])/np.exp(Q[s, :]).sum()
nb_actions = Q.shape[1]
return np.random.choice(nb_actions, p=proba)
# Select the best action bas... | [
"numpy.mean",
"numpy.nan_to_num",
"numpy.divide",
"numpy.random.choice",
"numpy.argmax",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"numpy.einsum",
"time.localtime",
"numpy.arange"
] | [((249, 286), 'numpy.random.choice', 'np.random.choice', (['nb_actions'], {'p': 'proba'}), '(nb_actions, p=proba)\n', (265, 286), True, 'import numpy as np\n'), ((385, 403), 'numpy.argmax', 'np.argmax', (['Q[s, :]'], {}), '(Q[s, :])\n', (394, 403), True, 'import numpy as np\n'), ((523, 532), 'numpy.exp', 'np.exp', (['Q... |
import numpy as np
import os
from struct import unpack
from .defaultreader import DefaultReader
class StlReader(DefaultReader):
"""
@type _facets: dict[str, list[tuple[tuple[float]]]]
@type _norms: dict[str, list[tuple[float]]]
"""
def __init__(self):
self._facets = {}
self._norms... | [
"os.path.exists",
"numpy.dtype",
"struct.unpack",
"numpy.fromfile"
] | [((879, 1046), 'numpy.dtype', 'np.dtype', (["[('normals', np.float32, (3,)), ('Vertex1', np.float32, (3,)), ('Vertex2',\n np.float32, (3,)), ('Vertex3', np.float32, (3,)), ('atttr', '<i2', (1,))]"], {}), "([('normals', np.float32, (3,)), ('Vertex1', np.float32, (3,)), (\n 'Vertex2', np.float32, (3,)), ('Vertex3',... |
import sys, argparse
sys.path.append('game/')
import flappy_wrapped as game
import cv2
import numpy as np
import collections
import torch
import torch.nn as nn
import torch.optim as optim
KERNEL = np.array([[-1,-1,-1], [-1, 9,-1],[-1,-1,-1]])
def processFrame(frame):
frame = frame[55:288,0:400] #crop image
fra... | [
"torch.nn.ReLU",
"collections.deque",
"argparse.ArgumentParser",
"cv2.threshold",
"torch.load",
"flappy_wrapped.GameState",
"cv2.filter2D",
"torch.nn.Conv2d",
"numpy.array",
"torch.cuda.is_available",
"cv2.cvtColor",
"torch.nn.Linear",
"cv2.resize",
"sys.path.append",
"torch.zeros"
] | [((21, 45), 'sys.path.append', 'sys.path.append', (['"""game/"""'], {}), "('game/')\n", (36, 45), False, 'import sys, argparse\n'), ((198, 249), 'numpy.array', 'np.array', (['[[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]'], {}), '([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n', (206, 249), True, 'import numpy as np\n'), ((3... |
# -*- coding:utf8 -*
import heapq
import logging
import time
import pandas as pd
import numpy as np
import random
from ..util import sample_ints
from .model_based_tuner import ModelOptimizer, knob2point, point2knob
logger = logging.getLogger('autotvm')
class RegOptimizer(ModelOptimizer):
def __init__(self, tas... | [
"logging.getLogger",
"random.sample",
"numpy.append",
"pandas.DataFrame"
] | [((227, 255), 'logging.getLogger', 'logging.getLogger', (['"""autotvm"""'], {}), "('autotvm')\n", (244, 255), False, 'import logging\n'), ((2453, 2486), 'numpy.append', 'np.append', (['points', 'scores'], {'axis': '(1)'}), '(points, scores, axis=1)\n', (2462, 2486), True, 'import numpy as np\n'), ((2507, 2553), 'pandas... |
import numpy as np
import pandas as pd
import sqlite3
import datetime as dt
from bs4 import BeautifulSoup as BS
from os.path import basename
import time
import requests
import csv
import re
import pickle
def name_location_scrapper(url): # scrapes a list of teams and their urls
r = requests.get(url)
sou... | [
"pickle.dump",
"pickle.load",
"requests.get",
"time.sleep",
"bs4.BeautifulSoup",
"numpy.random.randint",
"os.path.basename",
"pandas.DataFrame",
"pandas.concat"
] | [((295, 312), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (307, 312), False, 'import requests\n'), ((324, 352), 'bs4.BeautifulSoup', 'BS', (['r.content', '"""html.parser"""'], {}), "(r.content, 'html.parser')\n", (326, 352), True, 'from bs4 import BeautifulSoup as BS\n'), ((1488, 1505), 'requests.get', 'r... |
#python routines for estimating energy resolution and intensity
#<NAME>
#Updated 2-19-2013 to include tube efficiency
import sys
#sys.path.append('/SNS/users/19g/SEQUOIA/commissioning/python')
from unit_convert import E2V,E2K
import numpy as np
from numpy import pi, log, exp, sqrt, tanh, linspace, radians, zeros
from s... | [
"pylab.title",
"numpy.radians",
"numpy.sqrt",
"pylab.subplot",
"pylab.plot",
"numpy.log",
"pylab.xlabel",
"unit_convert.E2V",
"numpy.tanh",
"scipy.interpolate.interp1d",
"pylab.figure",
"unit_convert.E2K",
"numpy.linspace",
"numpy.array",
"pylab.ylabel",
"slit_pack.Slit_pack",
"pylab... | [((8689, 8733), 'slit_pack.Slit_pack', 'Slit_pack', (['(0.00203)', '(0.58)', '"""SEQ-100-2.03-AST"""'], {}), "(0.00203, 0.58, 'SEQ-100-2.03-AST')\n", (8698, 8733), False, 'from slit_pack import Slit_pack\n'), ((8740, 8784), 'slit_pack.Slit_pack', 'Slit_pack', (['(0.00356)', '(1.53)', '"""SEQ-700-3.56-AST"""'], {}), "(0... |
from dna_features_viewer import BiopythonTranslator
import numpy as np
from copy import deepcopy
from Bio import SeqIO
import flametree
import matplotlib.pyplot as plt
from geneblocks import DiffBlocks
from .biotools import (
annotate_record,
sequence_to_biopython_record,
sequences_differences_segments,
... | [
"dna_features_viewer.BiopythonTranslator",
"geneblocks.DiffBlocks.from_sequences",
"numpy.diff",
"matplotlib.pyplot.close",
"flametree.file_tree",
"copy.deepcopy"
] | [((1705, 1746), 'flametree.file_tree', 'flametree.file_tree', (['target'], {'replace': '(True)'}), '(target, replace=True)\n', (1724, 1746), False, 'import flametree\n'), ((2826, 2846), 'matplotlib.pyplot.close', 'plt.close', (['ax.figure'], {}), '(ax.figure)\n', (2835, 2846), True, 'import matplotlib.pyplot as plt\n')... |
import argparse
from io import BytesIO as _BytesIO
from pathlib import Path
import numpy as _np
import pandas as _pd
from urllib import request as _rqs
from datetime import datetime
from scipy.interpolate import InterpolatedUnivariateSpline
from gn_lib.gn_io.common import path2bytes
from gn_lib.gn_datetime import gps... | [
"datetime.datetime",
"argparse.ArgumentParser",
"urllib.request.urlretrieve",
"pathlib.Path.cwd",
"pathlib.Path",
"io.BytesIO",
"scipy.interpolate.InterpolatedUnivariateSpline",
"numpy.arange"
] | [((957, 977), 'datetime.datetime', 'datetime', (['(2000)', '(1)', '(1)'], {}), '(2000, 1, 1)\n', (965, 977), False, 'from datetime import datetime\n'), ((1482, 1537), 'urllib.request.urlretrieve', '_rqs.urlretrieve', (['iers_url'], {'filename': 'iau2000_daily_file'}), '(iers_url, filename=iau2000_daily_file)\n', (1498,... |
import os
from dataclasses import dataclass
import imageio
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
def get_callbacks(save_path, lr_schedule, prefix=None):
""" Creates callbacks.
Arguments:
save_path: the logs and checkpoints will be stored here.
lr_schedule: learni... | [
"os.path.exists",
"tensorflow.keras.backend.eval",
"numpy.sqrt",
"tensorflow.keras.callbacks.TensorBoard",
"os.makedirs",
"imageio.imwrite",
"tensorflow.keras.callbacks.LearningRateScheduler",
"os.path.join",
"tensorflow.keras.optimizers.schedules.PolynomialDecay",
"numpy.zeros",
"tensorflow.nn.... | [((464, 503), 'os.path.join', 'os.path.join', (['save_path', '"""logs"""', 'prefix'], {}), "(save_path, 'logs', prefix)\n", (476, 503), False, 'import os\n'), ((524, 582), 'os.path.join', 'os.path.join', (['save_path', '"""checkpoints"""', "('%s.ckpt' % prefix)"], {}), "(save_path, 'checkpoints', '%s.ckpt' % prefix)\n"... |
"""
Loads all the images in the "data/" directory.
This folder should contain 6400 images:
- for a number of times the identity operation is applied, k in (1-32):
- for a number of iteration it in (0-99):
- we have 2 images:
- one input image: "Input f k_it.BMP"
- one output image: "Output f k_it.BMP... | [
"numpy.mean",
"math.sqrt"
] | [((1161, 1188), 'numpy.mean', 'np.mean', (['((img1 - img2) ** 2)'], {}), '((img1 - img2) ** 2)\n', (1168, 1188), True, 'import numpy as np\n'), ((1278, 1292), 'math.sqrt', 'math.sqrt', (['mse'], {}), '(mse)\n', (1287, 1292), False, 'import math\n')] |
from cluster.preprocess.pre_node_feed import PreNodeFeed
import os,h5py
import numpy as np
class PreNodeFeedText2FastText(PreNodeFeed):
"""
"""
def run(self, conf_data):
"""
override init class
"""
super(PreNodeFeedText2FastText, self).run(conf_data)
self._init_node... | [
"numpy.logical_not",
"h5py.File"
] | [((561, 591), 'h5py.File', 'h5py.File', (['file_path'], {'mode': '"""r"""'}), "(file_path, mode='r')\n", (570, 591), False, 'import os, h5py\n'), ((970, 1021), 'h5py.File', 'h5py.File', (['self.input_paths[self.pointer]'], {'mode': '"""r"""'}), "(self.input_paths[self.pointer], mode='r')\n", (979, 1021), False, 'import... |
import gensim
import numpy as np
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_word2vec(word2vec_data_path):
return gensim.models.KeyedVectors.load_word2vec_format(word2vec_data_path, binary=True)
def generate_word_map_from_word2vec_model(word... | [
"numpy.random.rand",
"gensim.models.KeyedVectors.load_word2vec_format",
"numpy.append",
"torch.cuda.is_available",
"torch.FloatTensor",
"torch.nn.Embedding.from_pretrained"
] | [((191, 276), 'gensim.models.KeyedVectors.load_word2vec_format', 'gensim.models.KeyedVectors.load_word2vec_format', (['word2vec_data_path'], {'binary': '(True)'}), '(word2vec_data_path, binary=True\n )\n', (238, 276), False, 'import gensim\n'), ((979, 1009), 'numpy.random.rand', 'np.random.rand', (['(1)', 'n_dimensi... |
"""
<NAME>
Calculation of curvature using the method outlined in <NAME> et. al 2004
Per face curvature is calculated and per vertex curvature is calculated by weighting the
per-face curvatures. I have vectorized the code where possible.
"""
import numpy as np
from numpy.core.umath_tests import inner1d
from ... | [
"numpy.sqrt",
"numpy.cross",
"numpy.linalg.pinv",
"numpy.core.umath_tests.inner1d",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.matmul",
"numpy.transpose",
"numpy.bincount"
] | [((695, 711), 'numpy.cross', 'np.cross', (['up', 'vp'], {}), '(up, vp)\n', (703, 711), True, 'import numpy as np\n'), ((3044, 3098), 'numpy.sqrt', 'np.sqrt', (['(e0[:, 0] ** 2 + e0[:, 1] ** 2 + e0[:, 2] ** 2)'], {}), '(e0[:, 0] ** 2 + e0[:, 1] ** 2 + e0[:, 2] ** 2)\n', (3051, 3098), True, 'import numpy as np\n'), ((309... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
from PIL import Image
from pathlib import Path
from typing import Tuple, Union
def binarise_mask(mask: Union[np.ndarray, str, Path]) -> np.ndarray:
""" Split the mask into a set of binary masks.
... | [
"numpy.dstack",
"PIL.Image.open",
"numpy.unique",
"numpy.asarray",
"numpy.max",
"numpy.issubdtype",
"numpy.zeros"
] | [((667, 683), 'numpy.asarray', 'np.asarray', (['mask'], {}), '(mask)\n', (677, 683), True, 'import numpy as np\n'), ((1596, 1616), 'numpy.dstack', 'np.dstack', (['[r, g, b]'], {}), '([r, g, b])\n', (1605, 1616), True, 'import numpy as np\n'), ((2227, 2264), 'numpy.dstack', 'np.dstack', (['[colored_mask, alpha_mask]'], ... |
import bpy
import numpy as np
from smorgasbord.common.decorate import register
from smorgasbord.common.io import get_vecs, get_scalars
def get_red(arr):
return arr[:, 0:1].ravel()
def get_green(arr):
return arr[:, 1:2].ravel()
def get_blue(arr):
return arr[:, 2:3].ravel()
def avg_rgb(arr):
# St... | [
"numpy.unique",
"smorgasbord.common.io.get_scalars",
"numpy.average",
"numpy.where",
"bpy.props.EnumProperty",
"smorgasbord.common.io.get_vecs"
] | [((363, 394), 'numpy.average', 'np.average', (['arr[:, :-1]'], {'axis': '(1)'}), '(arr[:, :-1], axis=1)\n', (373, 394), True, 'import numpy as np\n'), ((825, 1132), 'bpy.props.EnumProperty', 'bpy.props.EnumProperty', ([], {'name': '"""Method"""', 'description': '"""Method used to calculate scalar weights from rgb color... |
import torch
import numpy
from deep_signature.nn.datasets import DeepSignatureEuclideanArclengthTupletsOnlineDataset
from deep_signature.nn.datasets import DeepSignatureEquiaffineArclengthTupletsOnlineDataset
from deep_signature.nn.datasets import DeepSignatureAffineArclengthTupletsOnlineDataset
from deep_signature.nn.... | [
"common.utils.get_latest_subdirectory",
"deep_signature.nn.losses.ArcLengthLoss",
"deep_signature.nn.trainers.ModelTrainer",
"argparse.ArgumentParser",
"deep_signature.nn.networks.DeepSignatureArcLengthNet",
"torch.set_default_dtype",
"numpy.load",
"torch.device"
] | [((656, 694), 'torch.set_default_dtype', 'torch.set_default_dtype', (['torch.float64'], {}), '(torch.float64)\n', (679, 694), False, 'import torch\n'), ((709, 725), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (723, 725), False, 'from argparse import ArgumentParser\n'), ((5678, 5737), 'deep_signature.... |
"""Work out the optimum mass for maximum cannonball range"""
import sympy as sym
import numpy as np
import matplotlib.pyplot as plt
import atmosphere
import pycollo
from pycollo.functions import cubic_spline
# state variables
r = sym.Symbol("r") # downrange distance
h = sym.Symbol("h") # height (above sea level?)
v =... | [
"sympy.sin",
"sympy.Symbol",
"sympy.cos",
"pycollo.functions.cubic_spline",
"matplotlib.pyplot.ylabel",
"pycollo.OptimalControlProblem",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.rad2deg",
"matplotlib.pyplot.show"
] | [((232, 247), 'sympy.Symbol', 'sym.Symbol', (['"""r"""'], {}), "('r')\n", (242, 247), True, 'import sympy as sym\n'), ((273, 288), 'sympy.Symbol', 'sym.Symbol', (['"""h"""'], {}), "('h')\n", (283, 288), True, 'import sympy as sym\n'), ((321, 336), 'sympy.Symbol', 'sym.Symbol', (['"""v"""'], {}), "('v')\n", (331, 336), ... |
import numpy as np
import torch
from torchvision import models
from utils import process_image
import json
from torch import nn, optim
from collections import OrderedDict
#loads a checkpoint and rebuilds the model
def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
if checkpoint['arch'] ==... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.load",
"torch.topk",
"numpy.argmax",
"torch.exp",
"torchvision.models.vgg11",
"utils.process_image",
"torch.cuda.is_available",
"torch.nn.NLLLoss",
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"json.load",
"torch.no_grad",
"torchvision.models.vgg1... | [((266, 286), 'torch.load', 'torch.load', (['filepath'], {}), '(filepath)\n', (276, 286), False, 'import torch\n'), ((1217, 1229), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (1227, 1229), False, 'from torch import nn, optim\n'), ((1813, 1843), 'utils.process_image', 'process_image', (['image_path', 'gpu'], {})... |
#!/usr/bin/env python
# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | [
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.use",
"collections.Counter",
"numpy.random.seed",
"tikzplotlib.save",
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.subplots",
"pandas.read_hdf"
] | [((737, 758), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (751, 758), False, 'import matplotlib\n'), ((2107, 2130), 'pandas.read_hdf', 'pd.read_hdf', (['prediction'], {}), '(prediction)\n', (2118, 2130), True, 'import pandas as pd\n'), ((3724, 3748), 'numpy.random.seed', 'np.random.seed', (['(... |
import eel
import numpy as np
import datetime
def rotate(arr, x, y, z):
cos_z, sin_z, cos_y = np.cos(z), np.sin(z), np.cos(y)
sin_y, cos_x, sin_x = np.sin(y), np.cos(x), np.sin(x)
rot_mat = [[cos_z*cos_y, cos_z*sin_y*sin_x - sin_z*cos_x, cos_z*sin_y*cos_x + sin_z*sin_x],
[sin_z*cos_y, sin_z*sin_y*sin_x + cos_z... | [
"numpy.random.normal",
"eel.sleep",
"eel.start",
"eel.init",
"numpy.array",
"numpy.zeros",
"datetime.datetime.now",
"numpy.dot",
"numpy.cos",
"numpy.sin",
"eel.drawLines"
] | [((957, 1043), 'numpy.array', 'np.array', (['[0, 1, 0, 2, 0, 4, 1, 3, 1, 5, 2, 3, 2, 6, 3, 7, 4, 5, 4, 6, 5, 7, 6, 7]'], {}), '([0, 1, 0, 2, 0, 4, 1, 3, 1, 5, 2, 3, 2, 6, 3, 7, 4, 5, 4, 6, 5, 7,\n 6, 7])\n', (965, 1043), True, 'import numpy as np\n'), ((1022, 1039), 'numpy.zeros', 'np.zeros', (['(3, 24)'], {}), '((3... |
import matplotlib.pyplot as plt
import cv2
import numpy as np
def plot_imgs(imgs, titles=None, cmap='brg', ylabel='', normalize=True, ax=None,
r=(0, 1), dpi=100):
n = len(imgs)
if not isinstance(cmap, list):
cmap = [cmap]*n
if ax is None:
_, ax = plt.subplots(1, n, figsize=(6... | [
"cv2.line",
"numpy.array",
"cv2.circle",
"numpy.random.randint",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"numpy.round",
"matplotlib.pyplot.get_cmap"
] | [((1245, 1263), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1261, 1263), True, 'import matplotlib.pyplot as plt\n'), ((291, 338), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n'], {'figsize': '(6 * n, 6)', 'dpi': 'dpi'}), '(1, n, figsize=(6 * n, 6), dpi=dpi)\n', (303, 338), True,... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import math
from bisect import bisect_right
import torch
class WarmupLrScheduler(torch.optim.lr_scheduler._LRScheduler):
def __init__(
self,
optimizer,
warmup_iter,
warmup_ratio=5e-4,
warmup='exp',
... | [
"matplotlib.pyplot.grid",
"torch.nn.Conv2d",
"math.cos",
"numpy.array",
"bisect.bisect_right",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((4201, 4232), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(3)', '(16)', '(3)', '(1)', '(1)'], {}), '(3, 16, 3, 1, 1)\n', (4216, 4232), False, 'import torch\n'), ((4640, 4653), 'numpy.array', 'np.array', (['lrs'], {}), '(lrs)\n', (4648, 4653), True, 'import numpy as np\n'), ((4715, 4725), 'matplotlib.pyplot.grid', 'plt.g... |
import numpy as np
import utils
from dataset_specifications.dataset import Dataset
class ConstNoiseSet(Dataset):
def __init__(self):
super().__init__()
self.name = "const_noise"
self.std_dev = np.sqrt(0.25)
def get_support(self, x):
return (x-2*self.std_dev, x+2*self.std_dev)... | [
"numpy.random.normal",
"utils.get_gaussian_pdf",
"numpy.sqrt",
"numpy.stack",
"numpy.random.uniform"
] | [((224, 237), 'numpy.sqrt', 'np.sqrt', (['(0.25)'], {}), '(0.25)\n', (231, 237), True, 'import numpy as np\n'), ((360, 405), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-1.0)', 'high': '(1.0)', 'size': 'n'}), '(low=-1.0, high=1.0, size=n)\n', (377, 405), True, 'import numpy as np\n'), ((420, 473), 'nump... |
import os
import sys
import json
import logging
import numpy as np
logging.basicConfig(level=logging.INFO)
from robo.solver.hyperband_datasets_size import HyperBand_DataSubsets
from hpolib.benchmarks.ml.surrogate_svm import SurrogateSVM
run_id = int(sys.argv[1])
seed = int(sys.argv[2])
rng = np.random.RandomState(... | [
"logging.basicConfig",
"os.makedirs",
"json.dump",
"numpy.log",
"os.path.join",
"hpolib.benchmarks.ml.surrogate_svm.SurrogateSVM",
"robo.solver.hyperband_datasets_size.HyperBand_DataSubsets",
"numpy.random.RandomState"
] | [((68, 107), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (87, 107), False, 'import logging\n'), ((298, 325), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (319, 325), True, 'import numpy as np\n'), ((353, 448), 'hpolib.bench... |
import numpy as np
from slugnet.activation import ReLU, Softmax
from slugnet.layers import Convolution, Dense, MeanPooling, Flatten
from slugnet.loss import SoftmaxCategoricalCrossEntropy as SCCE
from slugnet.model import Model
from slugnet.optimizers import SGD
from slugnet.data.mnist import get_mnist
X, y = get_mn... | [
"slugnet.activation.Softmax",
"slugnet.layers.Convolution",
"slugnet.optimizers.SGD",
"slugnet.layers.Flatten",
"slugnet.data.mnist.get_mnist",
"numpy.random.seed",
"slugnet.loss.SoftmaxCategoricalCrossEntropy",
"slugnet.layers.MeanPooling",
"numpy.random.permutation"
] | [((314, 325), 'slugnet.data.mnist.get_mnist', 'get_mnist', ([], {}), '()\n', (323, 325), False, 'from slugnet.data.mnist import get_mnist\n'), ((365, 384), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (379, 384), True, 'import numpy as np\n'), ((421, 440), 'numpy.random.seed', 'np.random.seed', ([... |
#!/usr/bin/env python
from __future__ import print_function
import MV2
import cdms2
import vcs
import genutil
import glob
import numpy
# import time
import datetime
from genutil import StringConstructor
import os
import pkg_resources
pmp_egg_path = pkg_resources.resource_filename(
pkg_resources.Requirement.parse("... | [
"vcs.createtext",
"vcs.createtextorientation",
"numpy.logical_not",
"vcs.createtemplate",
"MV2.array",
"numpy.array",
"pkg_resources.Requirement.parse",
"genutil.arrayindexing.set",
"numpy.ma.logical_not",
"MV2.count",
"MV2.transpose",
"MV2.ones",
"MV2.sqrt",
"MV2.concatenate",
"MV2.mask... | [((287, 335), 'pkg_resources.Requirement.parse', 'pkg_resources.Requirement.parse', (['"""pcmdi_metrics"""'], {}), "('pcmdi_metrics')\n", (318, 335), False, 'import pkg_resources\n'), ((912, 928), 'vcs.createtext', 'vcs.createtext', ([], {}), '()\n', (926, 928), False, 'import vcs\n'), ((2475, 2502), 'vcs.createtextori... |
import random
import numpy as np
def divided_training_test(examples_matrix, lbls, train_prec):
concatenated_examples_lbs = np.concatenate((examples_matrix, lbls), axis=1)
np.random.shuffle(concatenated_examples_lbs)
size_of_vector = np.shape(concatenated_examples_lbs)[1]
size_of_matrix = len(concaten... | [
"numpy.shape",
"numpy.concatenate",
"numpy.random.shuffle"
] | [((129, 176), 'numpy.concatenate', 'np.concatenate', (['(examples_matrix, lbls)'], {'axis': '(1)'}), '((examples_matrix, lbls), axis=1)\n', (143, 176), True, 'import numpy as np\n'), ((181, 225), 'numpy.random.shuffle', 'np.random.shuffle', (['concatenated_examples_lbs'], {}), '(concatenated_examples_lbs)\n', (198, 225... |
""" Prepare Tests
Script generating and a set of parameters for simulations.
Parameters are saved as set in `parameters/test_set`
To use just run
python test_set
script does not take any command line arguments or flags.
The script is intended to provide a simple way to describe
what experiments to perform.
""... | [
"numpy.linspace",
"sortedcontainers.SortedSet",
"numpy.random.randn"
] | [((433, 446), 'sortedcontainers.SortedSet', 'SortedSet', (['[]'], {}), '([])\n', (442, 446), False, 'from sortedcontainers import SortedSet\n'), ((461, 474), 'sortedcontainers.SortedSet', 'SortedSet', (['[]'], {}), '([])\n', (470, 474), False, 'from sortedcontainers import SortedSet\n'), ((518, 541), 'numpy.linspace', ... |
from __future__ import absolute_import
from ..coordinate import Coordinate
from ..roi import Roi
from .shared_graph_provider import\
SharedGraphProvider, SharedSubGraph
from ..graph import Graph, DiGraph
from pymongo import MongoClient, ASCENDING, ReplaceOne, UpdateOne
from pymongo.errors import BulkWriteError, Wri... | [
"logging.getLogger",
"numpy.int64",
"networkx.DiGraph",
"networkx.Graph",
"networkx.connected_components",
"pymongo.UpdateOne",
"numpy.uint64",
"networkx.weakly_connected_components",
"pymongo.ReplaceOne",
"pymongo.MongoClient",
"pymongo.errors.WriteError"
] | [((394, 421), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (411, 421), False, 'import logging\n'), ((19336, 19367), 'pymongo.MongoClient', 'MongoClient', (['self.provider.host'], {}), '(self.provider.host)\n', (19347, 19367), False, 'from pymongo import MongoClient, ASCENDING, ReplaceOn... |
import unittest
import numpy as np
import pytest
from audiomentations import TanhDistortion
from audiomentations.core.utils import calculate_rms
class TestTanhDistortion(unittest.TestCase):
def test_single_channel(self):
samples = np.random.normal(0, 0.1, size=(2048,)).astype(np.float32)
sample_... | [
"numpy.random.normal",
"numpy.allclose",
"audiomentations.core.utils.calculate_rms",
"audiomentations.TanhDistortion",
"numpy.amax"
] | [((353, 414), 'audiomentations.TanhDistortion', 'TanhDistortion', ([], {'min_distortion': '(0.2)', 'max_distortion': '(0.6)', 'p': '(1.0)'}), '(min_distortion=0.2, max_distortion=0.6, p=1.0)\n', (367, 414), False, 'from audiomentations import TanhDistortion\n'), ((1005, 1067), 'audiomentations.TanhDistortion', 'TanhDis... |
import os
import urllib.request
import csv
import yaml
from flask import Flask, request, jsonify
import numpy as np
from package.preprocessing import read_data, preprocess
from package.model_utils import train_model
from package.app_util import json_to_row
app = Flask(__name__)
# read in configuration
with open('.... | [
"os.path.exists",
"flask.Flask",
"flask.request.get_data",
"package.preprocessing.read_data",
"yaml.safe_load",
"package.app_util.json_to_row",
"os.mkdir",
"numpy.random.RandomState",
"flask.jsonify"
] | [((267, 282), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (272, 282), False, 'from flask import Flask, request, jsonify\n'), ((466, 507), 'numpy.random.RandomState', 'np.random.RandomState', (["cfg['random_seed']"], {}), "(cfg['random_seed'])\n", (487, 507), True, 'import numpy as np\n'), ((375, 399), '... |
import unittest
import numpy
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.parameterize(*testing.product({
'in_shape': [(2, 3, 8, 6), (2, 1, 4, 6)],
}))
class T... | [
"chainer.functions.ResizeImages",
"chainer.testing.condition.retry",
"chainer.testing.run_module",
"chainer.testing.product",
"numpy.zeros",
"numpy.array",
"chainer.functions.resize_images",
"numpy.random.uniform",
"chainer.testing.assert_allclose",
"chainer.cuda.to_gpu"
] | [((3757, 3795), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (3775, 3795), False, 'from chainer import testing\n'), ((3443, 3461), 'chainer.testing.condition.retry', 'condition.retry', (['(3)'], {}), '(3)\n', (3458, 3461), False, 'from chainer.testing imp... |
import sys
import numpy as np
import io
from termcolor import colored, cprint
import glob
import os
import subprocess
import shutil
import xml.etree.ElementTree as ET
import itk
import vtk
import vtk.util.numpy_support
from CommonUtils import *
def rename(inname, outDir, extension_addition, extension_change=''):
... | [
"vtk.vtkImplicitPlaneRepresentation",
"numpy.array",
"vtk.vtkPolyDataReader",
"os.remove",
"os.path.exists",
"itk.imread",
"shutil.move",
"numpy.asarray",
"numpy.max",
"vtk.vtkRenderer",
"os.mkdir",
"vtk.vtkImplicitPlaneWidget2",
"subprocess.check_call",
"vtk.vtkCamera",
"vtk.vtkRenderWi... | [((434, 457), 'os.path.dirname', 'os.path.dirname', (['inname'], {}), '(inname)\n', (449, 457), False, 'import os\n'), ((795, 840), 'termcolor.cprint', 'cprint', (["('Input Filename : ', inname)", '"""cyan"""'], {}), "(('Input Filename : ', inname), 'cyan')\n", (801, 840), False, 'from termcolor import colored, cprint\... |
import os
import sys
import numpy as np
import cv2
from PIL import Image
import time
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'mayavi'))
sys.path.append(os.path.join(BASE_DIR, '../kitti'))
import kitti_uti... | [
"numpy.minimum",
"kitti_util.compute_box_3d",
"numpy.where",
"os.path.join",
"numpy.argsort",
"os.path.dirname",
"numpy.array",
"numpy.loadtxt",
"os.path.abspath",
"numpy.maximum",
"numpy.fromstring",
"sys.path.append"
] | [((150, 175), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (165, 175), False, 'import os\n'), ((176, 201), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (191, 201), False, 'import sys\n'), ((112, 137), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(_... |
from pandas import read_csv
import numpy as np
# Calculates 3 of missing values given in the original csv
def calculateMissingValues(data):
missing_data = data.isnull().sum()
print("Missing values for each feature (feature | # missing values): ")
print(missing_data)
# Finds average age of pat... | [
"numpy.amin",
"pandas.read_csv",
"numpy.array",
"numpy.isnan",
"numpy.amax"
] | [((1175, 1192), 'numpy.array', 'np.array', (['glucose'], {}), '(glucose)\n', (1183, 1192), True, 'import numpy as np\n'), ((1313, 1323), 'numpy.amax', 'np.amax', (['x'], {}), '(x)\n', (1320, 1323), True, 'import numpy as np\n'), ((1339, 1349), 'numpy.amin', 'np.amin', (['x'], {}), '(x)\n', (1346, 1349), True, 'import n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Extract methylation from fast5 files into a RocksDB file. Also has an interface to read those values.
Created on Thursday, 25. July 2019.
"""
import glob
import os.path
def main():
import argparse
parser = argparse.ArgumentParser(description="Extract methylat... | [
"logging.basicConfig",
"rocksdb.Options",
"uuid.UUID",
"itertools.repeat",
"argparse.ArgumentParser",
"os.path.join",
"ont_fast5_api.fast5_interface.get_fast5_file",
"multiprocessing.Pool",
"os.getpid",
"rocksdb.BloomFilterPolicy",
"multiprocessing.Manager",
"numpy.frombuffer",
"rocksdb.DB",... | [((267, 342), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Extract methylation from fast5 files"""'}), "(description='Extract methylation from fast5 files')\n", (290, 342), False, 'import argparse\n'), ((6265, 6279), 'logging.info', 'log.info', (['args'], {}), '(args)\n', (6273, 6279),... |
###############################################################################
# Version: 1.1
# Last modified on: 3 April, 2016
# Developers: <NAME>
# email: m_(DOT)_epitropakis_(AT)_lancaster_(DOT)_ac_(DOT)_uk
###############################################################################
from builtins import o... | [
"numpy.ones",
"numpy.arange",
"os.path.join",
"numpy.max",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"numpy.dot",
"os.path.dirname",
"numpy.cos",
"numpy.loadtxt",
"numpy.divide"
] | [((1001, 1043), 'os.path.join', 'os.path.join', (['self.path', '"""data/optima.dat"""'], {}), "(self.path, 'data/optima.dat')\n", (1013, 1043), False, 'import os\n'), ((1061, 1082), 'numpy.loadtxt', 'np.loadtxt', (['file_path'], {}), '(file_path)\n', (1071, 1082), True, 'import numpy as np\n'), ((2031, 2053), 'numpy.ze... |
"""
A module that contains a metaclass mixin that provides GF(2^m) arithmetic using explicit calculation.
"""
import numba
import numpy as np
from ._main import FieldClass, DirMeta
MULTIPLY = lambda a, b, *args: a * b
RECIPROCAL = lambda a, *args: 1 / a
class GF2mMeta(FieldClass, DirMeta):
"""
A metaclass f... | [
"numpy.array"
] | [((958, 1020), 'numpy.array', 'np.array', (['cls.primitive_element'], {'dtype': 'cls.dtypes[-1]', 'ndmin': '(1)'}), '(cls.primitive_element, dtype=cls.dtypes[-1], ndmin=1)\n', (966, 1020), True, 'import numpy as np\n')] |
from keras.backend import expand_dims
from keras.datasets.mnist import load_data
from keras.models import Sequential
from numpy.random import randint
from numpy.random import randn
from numpy import zeros
from numpy import ones
def loadDataset():
# load mnist dataset
(trainX, trainY), (_, _) = load_data()
... | [
"numpy.ones",
"keras.datasets.mnist.load_data",
"numpy.random.randint",
"numpy.zeros",
"keras.backend.expand_dims",
"numpy.random.randn"
] | [((304, 315), 'keras.datasets.mnist.load_data', 'load_data', ([], {}), '()\n', (313, 315), False, 'from keras.datasets.mnist import load_data\n'), ((371, 399), 'keras.backend.expand_dims', 'expand_dims', (['trainX'], {'axis': '(-1)'}), '(trainX, axis=-1)\n', (382, 399), False, 'from keras.backend import expand_dims\n')... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 13:15:24 2021
Animates streams of points/particles given their starting and ending locations
and number of particles in each flow.
@author: Mateusz
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy.random import unifo... | [
"numpy.abs",
"matplotlib.pyplot.Circle",
"numpy.sqrt",
"foodwebviz.utils.squeeze_map",
"matplotlib.pyplot.gca",
"numpy.min",
"numpy.max",
"numpy.sign",
"numpy.interp",
"numpy.random.uniform",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim"
] | [((1375, 1402), 'numpy.random.uniform', 'uniform', (['(0)', '(1)', 'flow_density'], {}), '(0, 1, flow_density)\n', (1382, 1402), False, 'from numpy.random import uniform\n'), ((1532, 1581), 'foodwebviz.utils.squeeze_map', 'squeeze_map', (['flows', '(1)', 'max_part', 'map_fun', '(0.05)', '(3)'], {}), '(flows, 1, max_par... |
import numpy as np
import torch
from .features_implementation import FeaturesImplementation
class PyTorchFeatures(FeaturesImplementation):
def __init__(self, tensor_list, device=None):
self._phi = tensor_list
self._device = device
def __call__(self, *args):
x = self._concatenate(args... | [
"numpy.atleast_2d",
"torch.stack"
] | [((457, 484), 'torch.stack', 'torch.stack', (['y_list'], {'dim': '(-1)'}), '(y_list, dim=-1)\n', (468, 484), False, 'import torch\n'), ((352, 368), 'numpy.atleast_2d', 'np.atleast_2d', (['x'], {}), '(x)\n', (365, 368), True, 'import numpy as np\n')] |
import os
import cv2
import numpy as np
import tensorflow as tf
from keras.models import load_model
from styx_msgs.msg import TrafficLight
class TLClassifier(object):
def __init__(self):
# load classifier
cwd = os.path.dirname(os.path.realpath(__file__))
# load the keras Lenet model from... | [
"tensorflow.Graph",
"keras.models.load_model",
"tensorflow.Session",
"numpy.argmax",
"tensorflow.GraphDef",
"numpy.squeeze",
"os.path.realpath",
"cv2.cvtColor",
"numpy.expand_dims",
"tensorflow.import_graph_def",
"cv2.resize",
"tensorflow.get_default_graph"
] | [((374, 411), 'keras.models.load_model', 'load_model', (["(cwd + '/tl_classifier.h5')"], {}), "(cwd + '/tl_classifier.h5')\n", (384, 411), False, 'from keras.models import load_model\n'), ((437, 459), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (457, 459), True, 'import tensorflow as tf\n'... |
import os.path
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random
import cv2 as cv
import numpy as np
import os
class ROI_transforms(object):
def __init__(self, size=(128, 128)):
super(ROI_transforms).__init__()
s... | [
"numpy.clip",
"cv2.convertScaleAbs",
"numpy.random.rand",
"numpy.count_nonzero",
"numpy.array",
"os.walk",
"os.listdir",
"numpy.where",
"cv2.threshold",
"numpy.random.random",
"numpy.max",
"cv2.getGaussianKernel",
"numpy.resize",
"data.base_dataset.get_transform",
"numpy.min",
"data.ba... | [((7939, 7968), 'numpy.where', 'np.where', (['(gray_mask > 0)', '(1)', '(0)'], {}), '(gray_mask > 0, 1, 0)\n', (7947, 7968), True, 'import numpy as np\n'), ((8506, 8550), 'cv2.threshold', 'cv.threshold', (['mask', '(1)', '(255)', 'cv.THRESH_BINARY'], {}), '(mask, 1, 255, cv.THRESH_BINARY)\n', (8518, 8550), True, 'impor... |
""" TensorMONK :: layers :: CarryResidue """
__all__ = ["ResidualOriginal", "ResidualComplex", "ResidualInverted",
"ResidualShuffle", "ResidualNeXt",
"SEResidualComplex", "SEResidualNeXt",
"SimpleFire", "CarryModular", "DenseBlock",
"ContextNet_Bottleneck", "SeparableConvolu... | [
"torch.nn.functional.conv2d",
"numpy.prod",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Sequential",
"torch.nn.Dropout2d",
"torch.nn.functional.avg_pool2d",
"torch.nn.init.kaiming_uniform_",
"torch.nn.MaxPool2d",
"copy.deepcopy",
"torch.nn.AvgPool2d",
"random.randint",
"torch.rand",
... | [((1428, 1466), 'torch.nn.init.kaiming_uniform_', 'nn.init.kaiming_uniform_', (['self.squeeze'], {}), '(self.squeeze)\n', (1452, 1466), True, 'import torch.nn as nn\n'), ((1475, 1516), 'torch.nn.init.kaiming_uniform_', 'nn.init.kaiming_uniform_', (['self.excitation'], {}), '(self.excitation)\n', (1499, 1516), True, 'im... |
# -*- coding: utf-8 -*-
import os
import sys
# ensure `tests` directory path is on top of Python's module search
filedir = os.path.dirname(__file__)
sys.path.insert(0, filedir)
while filedir in sys.path[1:]:
sys.path.pop(sys.path.index(filedir)) # avoid duplication
import pytest
import numpy as np
import matplotl... | [
"deeptrain.util.algorithms.ordered_shuffle",
"sys.path.insert",
"backend.tempdir",
"deeptrain.DataGenerator",
"numpy.array",
"copy.deepcopy",
"backend.notify",
"deeptrain.util.misc.argspec",
"matplotlib.pyplot.plot",
"pytest.main",
"sys.path.index",
"io.StringIO",
"deeptrain.util.misc.pass_o... | [((123, 148), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (138, 148), False, 'import os\n'), ((149, 176), 'sys.path.insert', 'sys.path.insert', (['(0)', 'filedir'], {}), '(0, filedir)\n', (164, 176), False, 'import sys\n'), ((707, 745), 'os.path.join', 'os.path.join', (['BASEDIR', '"""test... |
import os
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import graphviz as gv
class HiddenMarkovModel:
def __init__(
self,
observable_states,
hidden_states,
transition_matrix,
emission_matrix,
title="HMM",
):
... | [
"IPython.display.display",
"networkx.MultiDiGraph",
"numpy.isclose",
"numpy.linalg.eig",
"networkx.drawing.nx_pydot.graphviz_layout",
"graphviz.Source.from_file",
"numpy.argmax",
"networkx.drawing.nx_pydot.write_dot",
"numpy.max",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"os.mkdir",
"pan... | [((986, 1071), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'transition_matrix', 'columns': 'hidden_states', 'index': 'hidden_states'}), '(data=transition_matrix, columns=hidden_states, index=hidden_states\n )\n', (998, 1071), True, 'import pandas as pd\n'), ((1120, 1207), 'pandas.DataFrame', 'pd.DataFrame', ([... |
import pandas as pd
import quandl
import math
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import datetime
import matplotlib.pyplot as plt
from matplotlib import style
import pickle
style.use('ggplot')
df = quandl.get('WIKI/GOOGL')
# pri... | [
"datetime.datetime.fromtimestamp",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"pickle.load",
"numpy.array",
"quandl.get",
"matplotlib.style.use",
"sklearn.cross_validation.train_test_split",
"sklearn.preprocessing.scale",
"matplotlib.pyplot.show"
] | [((265, 284), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (274, 284), False, 'from matplotlib import style\n'), ((290, 314), 'quandl.get', 'quandl.get', (['"""WIKI/GOOGL"""'], {}), "('WIKI/GOOGL')\n", (300, 314), False, 'import quandl\n'), ((896, 918), 'sklearn.preprocessing.scale', 'pr... |
"""
@AmineHorseman
Sep, 12th, 2016
"""
import tensorflow as tf
from tflearn import DNN
import time
import numpy as np
import argparse
import dlib
import cv2
import os
from skimage.feature import hog
from parameters import DATASET, TRAINING, NETWORK, VIDEO_PREDICTOR
from model import build_model
window_size = 24
windo... | [
"cv2.imwrite",
"tensorflow.Graph",
"tflearn.DNN",
"dlib.rectangle",
"numpy.asarray",
"dlib.shape_predictor",
"os.path.isfile",
"model.build_model",
"skimage.feature.hog",
"cv2.cvtColor",
"time.time",
"numpy.concatenate",
"cv2.CascadeClassifier",
"cv2.resize",
"cv2.imread"
] | [((3370, 3430), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (3391, 3430), False, 'import cv2\n'), ((3441, 3458), 'cv2.imread', 'cv2.imread', (['image'], {}), '(image)\n', (3451, 3458), False, 'import cv2\n'), ((3470,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 14:29:03 2020
@author: <NAME>
Script used to create the formatted table for lag phase calculation by DMFit
DMFit requires data to be formatted in a specific way to be analysed by the
Excel add-in DMFit. In brief, the excel file needs to have tw... | [
"pandas.read_excel",
"pandas.DataFrame",
"pandas.ExcelWriter",
"pandas.concat",
"numpy.arange"
] | [((6298, 6519), 'pandas.DataFrame', 'pd.DataFrame', (["['WT', 'WT GFP', 'WT RFP', 'E2', 'E2 GFP', 'E2 RFP', 'E7', 'E7 RFP', 'E8',\n 'E8 RFP', 'A', 'A GFP', 'A RFP', 'btuB', 'btuB GFP', 'btuB RFP',\n 'pC001', 'ImmE2 Ypet', 'ImmE2 NeonGreen']"], {'columns': "['logc']"}), "(['WT', 'WT GFP', 'WT RFP', 'E2', 'E2 GFP',... |
import keras
from keras.models import load_model
from keras import backend as K
import math
import sys
import argparse
import numpy as np
import scipy.io as sio
import os
import glob
import h5py
import cv2
import gc
''' This code is based on <NAME>., <NAME>., & Arganda-Carreras,
I. (2017). "Vision-Based Fall Dete... | [
"numpy.tile",
"os.listdir",
"keras.models.load_model",
"argparse.ArgumentParser",
"scipy.io.loadmat",
"os.path.join",
"h5py.File",
"numpy.zeros",
"keras.backend.clear_session",
"gc.collect",
"numpy.expand_dims",
"numpy.transpose",
"cv2.imread",
"glob.glob"
] | [((17493, 17559), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Do feature extraction tasks"""'}), "(description='Do feature extraction tasks')\n", (17516, 17559), False, 'import argparse\n'), ((1476, 1493), 'keras.models.load_model', 'load_model', (['model'], {}), '(model)\n', (1486, 1... |
import unittest
import numpy as np
from sklearn.datasets import make_classification
from skactiveml.classifier import ParzenWindowClassifier
from skactiveml.stream import (
FixedUncertainty,
VariableUncertainty,
Split,
RandomVariableUncertainty,
)
class TemplateTestUncertaintyZliobaite:
def setU... | [
"skactiveml.classifier.ParzenWindowClassifier",
"numpy.ones",
"numpy.random.RandomState"
] | [((407, 431), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (428, 431), True, 'import numpy as np\n'), ((812, 836), 'skactiveml.classifier.ParzenWindowClassifier', 'ParzenWindowClassifier', ([], {}), '()\n', (834, 836), False, 'from skactiveml.classifier import ParzenWindowClassifier\n'),... |
"""Solve problems that have manufactured solutions."""
import unittest
import numpy as np
from skfem.models.poisson import laplace, mass
from skfem.mesh import MeshHex, MeshLine, MeshQuad, MeshTet, MeshTri
from skfem.element import (ElementHex1, ElementHexS2,
ElementLineP1, ElementLineP2, ... | [
"numpy.testing.assert_array_almost_equal",
"skfem.asm",
"skfem.condense",
"unittest.main",
"skfem.element.ElementLineP1",
"skfem.assembly.InteriorBasis",
"skfem.element.ElementLineP2",
"skfem.solve",
"numpy.linspace",
"numpy.sum",
"skfem.assembly.FacetBasis",
"skfem.element.ElementLineMini"
] | [((708, 723), 'skfem.element.ElementLineP1', 'ElementLineP1', ([], {}), '()\n', (721, 723), False, 'from skfem.element import ElementHex1, ElementHexS2, ElementLineP1, ElementLineP2, ElementLineMini, ElementQuad1, ElementQuad2, ElementTetP1, ElementTriP2\n'), ((1304, 1319), 'skfem.element.ElementLineP2', 'ElementLineP2... |
## emotionProcessor-threaded.py
## This is a variation of the emotionProcessor class.
## The main difference between the two classes is that this
## class utilizes python's threading module to collect the
## audio metrics.
## Since this proved to offer little to no performance gains
## while still expending ex... | [
"pyAudioAnalysis.audioBasicIO.readAudioFile",
"math.ceil",
"pydub.silence.split_on_silence",
"numpy.arange",
"python_speech_features.delta",
"python_speech_features.logfbank",
"python_speech_features.mfcc",
"numpy.array",
"pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction",
"scipy.io.wavf... | [((1720, 1758), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (['self.fname'], {}), '(self.fname)\n', (1746, 1758), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((1824, 1862), 'python_speech_features.mfcc', 'mfcc', (['sig'], {'samplerate': '(44100)', 'nfft': '(1103)'}), '(sig, sam... |
import sys
sys.path.append("..")
from faigen.data.sequence import Dna2VecList,regex_filter
import pandas as pd
import numpy as np
import os
from functools import partial
import configargparse
from pathlib import Path
from Bio.SeqRecord import SeqRecord
import yaml
from pathlib import Path
import os
from shutil import c... | [
"os.path.exists",
"os.makedirs",
"pathlib.Path",
"numpy.asarray",
"configargparse.get_argument_parser",
"shutil.copy",
"sys.path.append"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((872, 908), 'configargparse.get_argument_parser', 'configargparse.get_argument_parser', ([], {}), '()\n', (906, 908), False, 'import configargparse\n'), ((1762, 1827), 'pathlib.Path', 'Path', (['"""/home... |
"""A pickleable wrapper for sharing NumPy ndarrays between processes using multiprocessing shared memory."""
import numpy as np
import multiprocessing.shared_memory as shm
class SharedNDArray:
"""Creates a new SharedNDArray, a pickleable wrapper for sharing NumPy ndarrays between
processes using multiprocess... | [
"numpy.prod",
"numpy.dtype",
"numpy.ndarray",
"multiprocessing.shared_memory.SharedMemory"
] | [((1652, 1702), 'numpy.ndarray', 'np.ndarray', (['shape', 'dtype', 'self._shm.buf'], {'order': '"""C"""'}), "(shape, dtype, self._shm.buf, order='C')\n", (1662, 1702), True, 'import numpy as np\n'), ((1523, 1545), 'multiprocessing.shared_memory.SharedMemory', 'shm.SharedMemory', (['name'], {}), '(name)\n', (1539, 1545)... |
import torch
import argparse
import numpy as np
import sys
sys.path.insert(0, "/home/jwieting/min-risk-cl-simile/min-risk")
from fairseq.tasks.sim_utils import Example
from fairseq.tasks.sim_models import WordAveraging
from sacremoses import MosesDetokenizer
parser = argparse.ArgumentParser()
parser.add_argument('--... | [
"numpy.mean",
"sys.path.insert",
"argparse.ArgumentParser",
"sacremoses.MosesDetokenizer",
"torch.load",
"fairseq.tasks.sim_models.WordAveraging"
] | [((60, 124), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/jwieting/min-risk-cl-simile/min-risk"""'], {}), "(0, '/home/jwieting/min-risk-cl-simile/min-risk')\n", (75, 124), False, 'import sys\n'), ((271, 296), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (294, 296), False, 'import ... |
import numpy as np
from collections import defaultdict
class Agent:
def __init__(self, nA=6, epsilon=1.,alpha=0.2, gamma=1.,episode=1):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(... | [
"numpy.zeros",
"numpy.argmax",
"numpy.arange",
"numpy.max"
] | [((2215, 2241), 'numpy.max', 'np.max', (['self.Q[next_state]'], {}), '(self.Q[next_state])\n', (2221, 2241), True, 'import numpy as np\n'), ((328, 345), 'numpy.zeros', 'np.zeros', (['self.nA'], {}), '(self.nA)\n', (336, 345), True, 'import numpy as np\n'), ((983, 1001), 'numpy.arange', 'np.arange', (['self.nA'], {}), '... |
"""FEMTO dataset."""
import os
from pathlib import Path
import itertools
import json
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import pandas as pd
# from scipy.io import loadmat
_DESCRIPTION = """
FEMTO-ST bearing dataset used in the IEEE PHM 2012 Data Challenge for RUL (remaining... | [
"pandas.read_csv",
"tensorflow_datasets.features.Tensor",
"pathlib.Path",
"os.path.join",
"tensorflow_datasets.core.Version",
"numpy.array",
"tensorflow_datasets.download.Resource"
] | [((3092, 3118), 'tensorflow_datasets.core.Version', 'tfds.core.Version', (['"""1.0.0"""'], {}), "('1.0.0')\n", (3109, 3118), True, 'import tensorflow_datasets as tfds\n'), ((4707, 4798), 'tensorflow_datasets.download.Resource', 'tfds.download.Resource', ([], {'url': '_DATA_URLS', 'extract_method': 'tfds.download.Extrac... |
import sys
import tempfile
from qgis.core import (
QgsApplication,
QgsProcessingFeedback,
QgsVectorLayer,
QgsRasterLayer,
QgsProject
)
from qgis.analysis import QgsNativeAlgorithms
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description="Prepare the houston d... | [
"osgeo.gdal.Open",
"qgis.analysis.QgsNativeAlgorithms",
"processing.run",
"qgis.core.QgsRasterLayer",
"argparse.ArgumentParser",
"pathlib.Path",
"processing.core.Processing.Processing.initialize",
"qgis.core.QgsApplication.processingRegistry",
"qgis.core.QgsApplication.setPrefixPath",
"qgis.core.Q... | [((262, 340), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Prepare the houston dataset for roadnet"""'}), "(description='Prepare the houston dataset for roadnet')\n", (285, 340), False, 'import argparse\n'), ((584, 626), 'qgis.core.QgsApplication.setPrefixPath', 'QgsApplication.setPref... |
import math
import cv2
import numpy as np
from PIL import Image
from skimage import exposure
from DataToCloud import dataToCloud
def calc_projection_image (ptCloud, pcloud, messyValidRGB):
ptCloudPoints = np.asarray(ptCloud.points)
validIndices = np.argwhere(
np.isfinite(ptCloudPoints[:, 0]) & np.i... | [
"math.floor",
"numpy.column_stack",
"numpy.isfinite",
"numpy.arange",
"numpy.multiply",
"cv2.threshold",
"numpy.asarray",
"numpy.max",
"numpy.unravel_index",
"numpy.concatenate",
"cv2.add",
"numpy.abs",
"cv2.warpAffine",
"skimage.exposure.rescale_intensity",
"cv2.cvtColor",
"cv2.getRot... | [((214, 240), 'numpy.asarray', 'np.asarray', (['ptCloud.points'], {}), '(ptCloud.points)\n', (224, 240), True, 'import numpy as np\n'), ((447, 466), 'numpy.arange', 'np.arange', (['(0)', 'count'], {}), '(0, count)\n', (456, 466), True, 'import numpy as np\n'), ((480, 552), 'numpy.unravel_index', 'np.unravel_index', (['... |
import numpy as np
from scipy.interpolate import RectBivariateSpline
def TemplateCorrection(T, It1, rect, p0 = np.zeros(2)):
threshold = 0.1
x1_t, y1_t, x2_t, y2_t = rect[0], rect[1], rect[2], rect[3]
Iy, Ix = np.gradient(It1)
rows_img, cols_img = It1.shape
rows_rect, cols_rect = T.sh... | [
"scipy.interpolate.RectBivariateSpline",
"numpy.square",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"numpy.linalg.inv",
"numpy.meshgrid",
"numpy.gradient",
"numpy.arange"
] | [((115, 126), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (123, 126), True, 'import numpy as np\n'), ((229, 245), 'numpy.gradient', 'np.gradient', (['It1'], {}), '(It1)\n', (240, 245), True, 'import numpy as np\n'), ((401, 426), 'numpy.arange', 'np.arange', (['(0)', 'rows_img', '(1)'], {}), '(0, rows_img, 1)\n',... |
#!/usr/bin/env python
"""Analyze how important a Unicode block is for the different languages."""
# core modules
import logging
# 3rd party modules
import click
import numpy as np
# internal modules
from lidtk.data import wili
@click.command(name='analyze-unicode-block', help=__doc__)
@click.option('--start', de... | [
"click.option",
"numpy.array",
"lidtk.data.wili.load_data",
"click.command",
"logging.info"
] | [((235, 292), 'click.command', 'click.command', ([], {'name': '"""analyze-unicode-block"""', 'help': '__doc__'}), "(name='analyze-unicode-block', help=__doc__)\n", (248, 292), False, 'import click\n'), ((294, 349), 'click.option', 'click.option', (['"""--start"""'], {'default': '(123)', 'show_default': '(True)'}), "('-... |
"""Main module."""
import pandas as pd
import numpy as np
import re
import os
from shipflowmotionshelpers import errors
def _load_time_series(file_path:str)->pd.DataFrame:
"""Load time series from ShipFlowMotions into a pandas data frame
Parameters
----------
file_path : str
Where is the moti... | [
"pandas.Series",
"pandas.read_csv",
"shipflowmotionshelpers.errors.TimeSeriesFilePathError",
"os.path.splitext",
"os.path.split",
"numpy.deg2rad",
"pandas.DataFrame",
"re.sub",
"re.findall",
"os.path.abspath"
] | [((437, 464), 'os.path.splitext', 'os.path.splitext', (['file_path'], {}), '(file_path)\n', (453, 464), False, 'import os\n'), ((715, 735), 'numpy.deg2rad', 'np.deg2rad', (["df['V4']"], {}), "(df['V4'])\n", (725, 735), True, 'import numpy as np\n'), ((754, 774), 'numpy.deg2rad', 'np.deg2rad', (["df['A4']"], {}), "(df['... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import numpy as np
import common
def load_json(filename):
with open(filename, "r") as f:
return json.load(f)
def load_data(filename):
j = load_json(filename)
return np.array(j["h_max"]), np.array(j["L2Error"]), np.array(j["H1Error"])
d... | [
"numpy.sqrt",
"numpy.log",
"numpy.array",
"common.plotLogLogData",
"json.load"
] | [((609, 643), 'numpy.sqrt', 'np.sqrt', (['(L2err1 ** 2 + H1err1 ** 2)'], {}), '(L2err1 ** 2 + H1err1 ** 2)\n', (616, 643), True, 'import numpy as np\n'), ((651, 685), 'numpy.sqrt', 'np.sqrt', (['(L2err2 ** 2 + H1err2 ** 2)'], {}), '(L2err2 ** 2 + H1err2 ** 2)\n', (658, 685), True, 'import numpy as np\n'), ((1847, 1922)... |
import gym
import pybullet_envs
import numpy as np
from ppo.agent import Agent
if __name__ == '__main__':
env = gym.make('AntBulletEnv-v0')
learn_interval = 100
batch_size = 5000
n_epochs = 1000
learning_rate = 0.0003
observation_space = env.observation_space.shape[0]
action_space = env.... | [
"numpy.mean",
"ppo.agent.Agent",
"gym.make"
] | [((119, 146), 'gym.make', 'gym.make', (['"""AntBulletEnv-v0"""'], {}), "('AntBulletEnv-v0')\n", (127, 146), False, 'import gym\n'), ((354, 489), 'ppo.agent.Agent', 'Agent', ([], {'n_actions': 'action_space', 'batch_size': 'batch_size', 'learning_rate': 'learning_rate', 'n_epochs': 'n_epochs', 'input_dims': 'observation... |
from kid_readout.analysis.timeseries import fftfilt, decimating_fir
import numpy as np
def test_decimating_fir():
np.random.seed(123)
x = np.random.randn(2**16) + 1j*np.random.randn(2**16)
dfir = decimating_fir.DecimatingFIR(downsample_factor=16,num_taps=1024)
gold = fftfilt.fftfilt(dfir.coefficients.r... | [
"kid_readout.analysis.timeseries.decimating_fir.FIR1D",
"numpy.allclose",
"kid_readout.analysis.timeseries.decimating_fir.DecimatingFIR",
"numpy.empty_like",
"numpy.random.seed",
"numpy.random.randn"
] | [((119, 138), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (133, 138), True, 'import numpy as np\n'), ((209, 274), 'kid_readout.analysis.timeseries.decimating_fir.DecimatingFIR', 'decimating_fir.DecimatingFIR', ([], {'downsample_factor': '(16)', 'num_taps': '(1024)'}), '(downsample_factor=16, num_... |
#coding:utf-8
# 感知器 y = f(Wn * x + b)
# 代码实现的是一个逻辑AND操作,输入最后一项一直为1,代表我们可以理解偏置项b的特征值输入一直为1
# 这样就是 y = f(Wn+1*[x,1]), Wn+1就是b
# https://www.zybuluo.com/hanbingtao/note/433855
from numpy import array, dot, random
from random import choice
def fun_1_or_0(x): return 0 if x < 0 else 1
training_data = [(array([0, 0, 1... | [
"numpy.random.random",
"numpy.array",
"numpy.dot",
"random.choice"
] | [((425, 441), 'numpy.random.random', 'random.random', (['(3)'], {}), '(3)\n', (438, 441), False, 'from numpy import array, dot, random\n'), ((575, 596), 'random.choice', 'choice', (['training_data'], {}), '(training_data)\n', (581, 596), False, 'from random import choice\n'), ((610, 629), 'numpy.dot', 'dot', (['weights... |
import numpy as np
import torch
import torch.nn as nn
import torchvision
import pandas as pd
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn import metrics
import torchvision.transforms as transforms
def get_target_label_idx(labels, targets):
return np.argwhere(np.isin(labels, target... | [
"numpy.prod",
"torch.abs",
"torch.mean",
"numpy.isin",
"torch.sum"
] | [((461, 474), 'torch.mean', 'torch.mean', (['x'], {}), '(x)\n', (471, 474), False, 'import torch\n'), ((431, 447), 'numpy.prod', 'np.prod', (['x.shape'], {}), '(x.shape)\n', (438, 447), True, 'import numpy as np\n'), ((541, 553), 'torch.abs', 'torch.abs', (['x'], {}), '(x)\n', (550, 553), False, 'import torch\n'), ((60... |
"""
===================================
Pose Coupling of Dual Cartesian DMP
===================================
A dual Cartesian DMP is learned from an artificially generated demonstration
and replayed with and without a coupling of the pose of the two end effectors.
The red line indicates the DMP without coupling te... | [
"pytransform3d.rotations.quaternion_slerp",
"numpy.eye",
"pytransform3d.rotations.plot_basis",
"movement_primitives.dmp.DualCartesianDMP",
"numpy.asarray",
"numpy.tanh",
"pytransform3d.transformations.transform_from_pq",
"numpy.array",
"numpy.zeros",
"numpy.deg2rad",
"movement_primitives.dmp.Cou... | [((858, 961), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -1.2], [0.0, \n 0.0, 0.0, 1.0]]'], {}), '([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -1.2],\n [0.0, 0.0, 0.0, 1.0]])\n', (866, 961), True, 'import numpy as np\n'), ((1092, 1249), 'movement_pr... |
import numpy as np
C_BASE_SCALES = {
"cromatic": np.arange(12),
"diatonic": (0, 2, 4, 5, 7, 9, 11),
"melodic minor": (0, 2, 3, 5, 7, 9, 11),
"harmonic minor": (0, 2, 3, 5, 7, 8, 11),
}
NOTES = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
DEGREES = ("I", "II", "III", "IV", "V", "VI"... | [
"numpy.full",
"numpy.arange"
] | [((54, 67), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (63, 67), True, 'import numpy as np\n'), ((747, 761), 'numpy.full', 'np.full', (['(11)', '(1)'], {}), '(11, 1)\n', (754, 761), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, PowerNorm, Normalize
from scipy import fftpack
def pix_intensity_hist(vals, generator, noise_vector_length, inv_transf, channel_axis, fname=None, Xterm=True, window=None, multichannel=False):
"""Plots a hist... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"numpy.argsort",
"numpy.array",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"scipy.fftpack.fft2",
"numpy.take",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"numpy.hyp... | [((860, 872), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (870, 872), True, 'import matplotlib.pyplot as plt\n'), ((1054, 1071), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (1064, 1071), True, 'import matplotlib.pyplot as plt\n'), ((1076, 1105), 'matplotlib.pyplot.legend'... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 16:45:30 2017
@author: RunNing
"""
import random
import numpy as np
import matplotlib.pyplot as plt
import abc
class Algorithm(metaclass=abc.ABCMeta):
@abc.abstractmethod
def reset(self):
return
@abc.abstractmethod
def sel... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"numpy.log",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"random.randint",
"random.uniform",
"matplotlib.pyplot.savefig",
"numpy.ones",
"numpy.argmax",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyp... | [((5032, 5071), 'numpy.arange', 'np.arange', (['(play_rounds + 1)'], {'dtype': 'float'}), '(play_rounds + 1, dtype=float)\n', (5041, 5071), True, 'import numpy as np\n'), ((5737, 5764), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (5747, 5764), True, 'import matplotlib.... |
from numpy.lib.twodim_base import mask_indices
from libs.MyType import *
import numpy as np
def getVecLength3D(v:Vec3D):
length=np.sqrt(v.x**2+v.y**2+v.z**2)
return length
def vectDot(v1:Vec3D,v2:Vec3D,default=True):#!这里改写了原来的方法,将default参数改为TRUE来使用原来的方法
if default:
l3=np.sqrt((v1.x-v2.x)**2+(v1.y-... | [
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.power"
] | [((133, 172), 'numpy.sqrt', 'np.sqrt', (['(v.x ** 2 + v.y ** 2 + v.z ** 2)'], {}), '(v.x ** 2 + v.y ** 2 + v.z ** 2)\n', (140, 172), True, 'import numpy as np\n'), ((1212, 1230), 'numpy.linalg.eig', 'np.linalg.eig', (['mat'], {}), '(mat)\n', (1225, 1230), True, 'import numpy as np\n'), ((291, 360), 'numpy.sqrt', 'np.sq... |
import fastscapelib_fortran as fs
import numpy as np
import xsimlab as xs
from .grid import UniformRectilinearGrid2D
@xs.process
class TotalVerticalMotion:
"""Sum up all vertical motions of bedrock and topographic surface,
respectively.
Vertical motions may result from external forcing, erosion and/or
... | [
"xsimlab.foreign",
"numpy.repeat",
"xsimlab.runtime",
"numpy.minimum",
"numpy.full_like",
"numpy.any",
"xsimlab.variable",
"numpy.empty_like",
"xsimlab.group",
"xsimlab.on_demand",
"xsimlab.index"
] | [((403, 429), 'xsimlab.group', 'xs.group', (['"""bedrock_upward"""'], {}), "('bedrock_upward')\n", (411, 429), True, 'import xsimlab as xs\n'), ((456, 482), 'xsimlab.group', 'xs.group', (['"""surface_upward"""'], {}), "('surface_upward')\n", (464, 482), True, 'import xsimlab as xs\n'), ((511, 539), 'xsimlab.group', 'xs... |
import tensorflow as tf
import numpy as np
FLAGS = tf.app.flags.FLAGS
def create_graph(model_file=None):
if not model_file:
model_file = FLAGS.model_file
#
with open(model_file, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_... | [
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.argmax",
"tensorflow.GraphDef",
"numpy.squeeze",
"tensorflow.import_graph_def",
"tensorflow.expand_dims",
"tensorflow.image.decode_jpeg"
] | [((495, 507), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (505, 507), True, 'import tensorflow as tf\n'), ((611, 656), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""input"""', 'dtype': 'tf.string'}), "(name='input', dtype=tf.string)\n", (625, 656), True, 'import tensorflow as tf\n'), ((669, 70... |
import numpy as np
from deepscratch.models.layers.activations.activation import Activation
class Softmax(Activation):
def __call__(self, data):
exp = np.exp(data - np.max(data, axis=-1, keepdims=True))
return exp / np.sum(exp, axis=-1, keepdims=True)
def backward(self, data):
soft... | [
"numpy.sum",
"numpy.max"
] | [((237, 272), 'numpy.sum', 'np.sum', (['exp'], {'axis': '(-1)', 'keepdims': '(True)'}), '(exp, axis=-1, keepdims=True)\n', (243, 272), True, 'import numpy as np\n'), ((178, 214), 'numpy.max', 'np.max', (['data'], {'axis': '(-1)', 'keepdims': '(True)'}), '(data, axis=-1, keepdims=True)\n', (184, 214), True, 'import nump... |
import argparse
import os, os.path
import torch
import numpy as np
import soundfile as sf
def load_waveglow(args, parser):
if not args.from_repo:
return load_waveglow_from_hub()
return load_waveglow_from_repo(args, parser)
def load_waveglow_from_hub():
waveglow = torch.hub.load('nvidia/DeepLearn... | [
"torch.split",
"torch.hub.load",
"torch.log",
"argparse.ArgumentParser",
"torch.load",
"os.path.join",
"os.path.splitext",
"torch.exp",
"soundfile.write",
"numpy.zeros",
"torch.no_grad",
"inference.load_and_setup_model",
"waveglow.denoiser.Denoiser",
"torch.zeros",
"os.walk"
] | [((288, 361), 'torch.hub.load', 'torch.hub.load', (['"""nvidia/DeepLearningExamples:torchhub"""', '"""nvidia_waveglow"""'], {}), "('nvidia/DeepLearningExamples:torchhub', 'nvidia_waveglow')\n", (302, 361), False, 'import torch\n'), ((645, 748), 'inference.load_and_setup_model', 'load_and_setup_model', (['"""WaveGlow"""... |
import numpy as np
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
class EmotionDetector:
def __init__(self, ):
self.model = Sequential()
self.model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', inp... | [
"cv2.rectangle",
"cv2.imshow",
"tensorflow.keras.layers.Dense",
"cv2.destroyAllWindows",
"cv2.imdecode",
"cv2.CascadeClassifier",
"tensorflow.keras.layers.Conv2D",
"numpy.frombuffer",
"cv2.waitKey",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Dropout",
"numpy.argmax",
"cv2... | [((230, 242), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (240, 242), False, 'from tensorflow.keras.models import Sequential\n'), ((1088, 1176), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (["(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')"], {}), "(cv2.data.haarcascades ... |
import numpy as np # numerical tools
from scipy import integrate
from scipy import interpolate
c_light=299792.458#in km/s
#Find nearest value
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
#### DATA SN
def get_SN_info(targetname):
data_sn=np.loadtxt('Info_SNe_KAIT.txt',u... | [
"numpy.abs",
"numpy.trapz",
"numpy.where",
"numpy.size",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.zeros",
"numpy.polyval",
"numpy.concatenate",
"numpy.loadtxt",
"numpy.genfromtxt"
] | [((2997, 3038), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["MJD['B']", "mags['B']"], {}), "(MJD['B'], mags['B'])\n", (3017, 3038), False, 'from scipy import interpolate\n'), ((3051, 3105), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["MJD['B']", "(mags['B'] + emags['B'])"], {}), "(MJD['B'], mags... |
"""
Gradcam visualization ref modified from implementation by fchollet (https://keras.io/examples/vision/grad_cam)
"""
import cv2
import numpy as np
import os
import sys
import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Displa... | [
"utils.preprocess_image",
"cv2.imwrite",
"tensorflow.math.abs",
"argparse.ArgumentParser",
"tensorflow.multiply",
"model_modified.efficientdet_mod",
"tensorflow.keras.preprocessing.image.array_to_img",
"numpy.zeros",
"tensorflow.GradientTape",
"numpy.expand_dims",
"numpy.min",
"tensorflow.redu... | [((548, 638), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Gradcam visualization script for Efficientdet."""'}), "(description=\n 'Gradcam visualization script for Efficientdet.')\n", (571, 638), False, 'import argparse\n'), ((1693, 1812), 'model_modified.efficientdet_mod', 'efficie... |
import os
import subprocess
import argparse
import torch
import json
# import h5py
import gzip, csv
import numpy as np
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
from transformers import *
def get_sentence_features(batches, tokenizer, model, device, maxlen=500):
features = tokenizer.batc... | [
"csv.DictWriter",
"argparse.ArgumentParser",
"gzip.open",
"os.makedirs",
"tqdm.tqdm",
"subprocess.run",
"numpy.memmap",
"os.path.join",
"os.path.isfile",
"torch.tensor",
"torch.cuda.is_available",
"torch.no_grad"
] | [((486, 541), 'torch.tensor', 'torch.tensor', (["features['attention_mask']"], {'device': 'device'}), "(features['attention_mask'], device=device)\n", (498, 541), False, 'import torch\n'), ((558, 608), 'torch.tensor', 'torch.tensor', (["features['input_ids']"], {'device': 'device'}), "(features['input_ids'], device=dev... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | [
"tensorflow.Graph",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.variable_scope",
"reader.ptb_raw_data",
"numpy.exp",
"config.get_config",
"tensorflow.train.import_meta_graph",
"tensorflow.name_scope",
"tensorflow.train.Supervisor",
"ptb_input.PTBInput",
"tensorflow.Conf... | [((2802, 2813), 'time.time', 'time.time', ([], {}), '()\n', (2811, 2813), False, 'import time\n'), ((3684, 3705), 'numpy.exp', 'np.exp', (['(costs / iters)'], {}), '(costs / iters)\n', (3690, 3705), True, 'import numpy as np\n'), ((4137, 4179), 'reader.ptb_raw_data', 'reader.ptb_raw_data', (['flags.FLAGS.data_path'], {... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.colors
from pycocotools.coco import COCO
import numpy as np
import skimage.io as sio
from tqdm import tqdm
from PIL import Image
filecoco = "annotations_coco.json"
coco = COCO(filecoco)
catIDs = coco.getCatIds()
cats = coc... | [
"PIL.Image.fromarray",
"matplotlib.pyplot.imsave",
"tqdm.tqdm",
"pycocotools.coco.COCO",
"numpy.zeros"
] | [((268, 282), 'pycocotools.coco.COCO', 'COCO', (['filecoco'], {}), '(filecoco)\n', (272, 282), False, 'from pycocotools.coco import COCO\n'), ((1723, 1735), 'tqdm.tqdm', 'tqdm', (['imgIds'], {}), '(imgIds)\n', (1727, 1735), False, 'from tqdm import tqdm\n'), ((844, 883), 'numpy.zeros', 'np.zeros', (["(img['height'], im... |
from dataclasses import dataclass
import numpy as np
@dataclass(unsafe_hash=True)
class Fraction:
_numerator: int # Numerator
_denominator: int # Denomenator
def __init__(self, numerator, denominator):
self._numerator = numerator
self._denominator = denominator
gcd = np.g... | [
"numpy.gcd",
"dataclasses.dataclass"
] | [((56, 83), 'dataclasses.dataclass', 'dataclass', ([], {'unsafe_hash': '(True)'}), '(unsafe_hash=True)\n', (65, 83), False, 'from dataclasses import dataclass\n'), ((316, 346), 'numpy.gcd', 'np.gcd', (['numerator', 'denominator'], {}), '(numerator, denominator)\n', (322, 346), True, 'import numpy as np\n'), ((707, 748)... |
# -*- coding: utf-8 -*-
"""Generate data for examples"""
# author: <NAME>, <NAME>, Duke University; <NAME>, <NAME>
# Copyright Duke University 2020
# License: MIT
import pandas as pd
import numpy as np
def generate_uniform_given_importance(num_control=1000, num_treated=1000,
num... | [
"numpy.random.normal",
"numpy.array",
"numpy.dot",
"numpy.random.randint",
"pandas.concat",
"numpy.random.binomial"
] | [((578, 642), 'numpy.random.randint', 'np.random.randint', (['min_val', 'max_val'], {'size': '(num_control, num_cov)'}), '(min_val, max_val, size=(num_control, num_cov))\n', (595, 642), True, 'import numpy as np\n'), ((653, 717), 'numpy.random.randint', 'np.random.randint', (['min_val', 'max_val'], {'size': '(num_treat... |
import numpy
from scipy import integrate
def create_state_mtx(state, nx, ny, nz, dof):
state_mtx = numpy.zeros([nx, ny, nz, dof])
for k in range(nz):
for j in range(ny):
for i in range(nx):
for d in range(dof):
state_mtx[i, j, k, d] = state[d + i * dof +... | [
"scipy.integrate.cumtrapz",
"numpy.tanh",
"numpy.zeros",
"numpy.meshgrid",
"numpy.arange"
] | [((105, 135), 'numpy.zeros', 'numpy.zeros', (['[nx, ny, nz, dof]'], {}), '([nx, ny, nz, dof])\n', (116, 135), False, 'import numpy\n'), ((439, 470), 'numpy.zeros', 'numpy.zeros', (['(nx * ny * nz * dof)'], {}), '(nx * ny * nz * dof)\n', (450, 470), False, 'import numpy\n'), ((1224, 1244), 'numpy.meshgrid', 'numpy.meshg... |
#!/usr/bin/env python3
import itertools as it
import random
import sys
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import numpy as np
import seaborn as sns
params = {
"axes.labelsize" : 16,
"xtick.labelsize" : 12,
"ytick.labelsize" : 12,
"text.usetex" : True,
"font.family... | [
"numpy.product",
"numpy.random.shuffle",
"numpy.ones",
"numpy.square",
"numpy.array_split",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"matplotlib.ticker.MaxNLocator",
"numpy.random.seed",
"itertools.combinations_with_replacement",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show... | [((1780, 1805), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (1794, 1805), True, 'import numpy as np\n'), ((2088, 2112), 'numpy.random.shuffle', 'np.random.shuffle', (['index'], {}), '(index)\n', (2105, 2112), True, 'import numpy as np\n'), ((3182, 3209), 'matplotlib.pyplot.rcParams.u... |
# Copyright (C) 2019 Intel 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 wri... | [
"cv2.rectangle",
"logging.debug",
"math.floor",
"numpy.hstack",
"cv2.imshow",
"numpy.array",
"numpy.linalg.norm",
"numpy.histogram",
"cv2.minMaxLoc",
"numpy.vstack",
"cv2.matchTemplate",
"cv2.blur",
"numpy.abs",
"collections.namedtuple",
"numpy.amin",
"numpy.average",
"cv2.cvtColor",... | [((982, 1028), 'collections.namedtuple', 'namedtuple', (['"""Rect"""', "['tl_x', 'tl_y', 'w', 'h']"], {}), "('Rect', ['tl_x', 'tl_y', 'w', 'h'])\n", (992, 1028), False, 'from collections import namedtuple\n'), ((1037, 1068), 'collections.namedtuple', 'namedtuple', (['"""Point"""', "['x', 'y']"], {}), "('Point', ['x', '... |
'''
@author: <NAME>
@author: <NAME>
@maintainer: <NAME>
@contact: <EMAIL>, <EMAIL>
@date: 14.08.2015
@version: 1.2+
@copyright: Copyright (c) 2015-2017, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
@license : BSD-2-Clause
'''
import numpy as np
from .module import Module
# -------------------------------
# Sum Pooling lay... | [
"numpy.sqrt",
"numpy.zeros",
"numpy.zeros_like",
"numpy.ones"
] | [((3131, 3152), 'numpy.zeros_like', 'np.zeros_like', (['self.X'], {}), '(self.X)\n', (3144, 3152), True, 'import numpy as np\n'), ((3881, 3903), 'numpy.zeros', 'np.zeros', (['self.X.shape'], {}), '(self.X.shape)\n', (3889, 3903), True, 'import numpy as np\n'), ((4871, 4908), 'numpy.zeros_like', 'np.zeros_like', (['self... |
#!/usr/bin/env python
#
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"pyxir.ops.input",
"pyxir.ops.conv2d",
"pyxir.ops.constant",
"numpy.array",
"pyxir.graph.xgraph_factory.XGraphFactory",
"unittest.main",
"pyxir.runtime.decentq_sim.runtime_decentq_sim.RuntimeDecentQSim"
] | [((1976, 1991), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1989, 1991), False, 'import unittest\n'), ((1139, 1174), 'pyxir.ops.input', 'px.ops.input', (['"""input"""', '[1, 1, 4, 4]'], {}), "('input', [1, 1, 4, 4])\n", (1151, 1174), True, 'import pyxir as px\n'), ((1187, 1215), 'pyxir.ops.constant', 'px.ops.c... |
import math
import numpy as np
def relu(pixel_vals, bias=0):
'''Takes tuple (r,g,b) and returns the relu transformation.
For use within each individual node in a dense layer before being passed onto the next layer
bias 0'ed out by default
'''
return (pixel_vals * (pixel_vals > 0) + bias,)
def sigm... | [
"numpy.exp",
"numpy.tanh"
] | [((598, 617), 'numpy.tanh', 'np.tanh', (['pixel_vals'], {}), '(pixel_vals)\n', (605, 617), True, 'import numpy as np\n'), ((439, 458), 'numpy.exp', 'np.exp', (['(-pixel_vals)'], {}), '(-pixel_vals)\n', (445, 458), True, 'import numpy as np\n')] |
import os
import pandas as pd
from numpy.random import default_rng
def create_sample(
input_file="../../classes_input/test_input.csv",
output_file=None,
percentage_sample=25,
exclude_samples=None,
):
if not output_file:
exclude = ""
if exclude_samples:
excluded_names = ... | [
"pandas.unique",
"numpy.random.default_rng",
"pandas.read_csv",
"os.path.basename"
] | [((700, 713), 'numpy.random.default_rng', 'default_rng', ([], {}), '()\n', (711, 713), False, 'from numpy.random import default_rng\n'), ((730, 753), 'pandas.read_csv', 'pd.read_csv', (['input_file'], {}), '(input_file)\n', (741, 753), True, 'import pandas as pd\n'), ((772, 803), 'pandas.unique', 'pd.unique', (["input_... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 16:32:08 2020
@author: LionelMassoulard
"""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin, is_classifier, is_regressor
from sklearn.preprocessing import OrdinalEncoder, KBinsDiscretizer
from aikit.too... | [
"numpy.abs",
"sklearn.preprocessing.KBinsDiscretizer",
"sklearn.base.is_classifier",
"pandas.DataFrame",
"numpy.exp",
"aikit.tools.data_structure_helper.make2dimensions",
"numpy.dot",
"numpy.concatenate",
"sklearn.base.is_regressor",
"aikit.tools.data_structure_helper.convert_generic"
] | [((4998, 5030), 'numpy.exp', 'np.exp', (['(-d / self.kernel_windows)'], {}), '(-d / self.kernel_windows)\n', (5004, 5030), True, 'import numpy as np\n'), ((6238, 6294), 'aikit.tools.data_structure_helper.convert_generic', 'convert_generic', (['y_int'], {'output_type': 'DataTypes.NumpyArray'}), '(y_int, output_type=Data... |
###################################################################################################
# Project : Global Challenges Research Fund (GCRF) African SWIFT (Science for Weather
# Information and Forecasting Techniques.
#
# Program name : dewpoint_HL.py
#
# Author ... | [
"Ngl.open_wks",
"numpy.log",
"Ngl.frame",
"Ngl.contour",
"sys.exit",
"Ngl.destroy",
"Ngl.read_colormap_file",
"numpy.where",
"numpy.exp",
"os.popen",
"Ngl.draw",
"numpy.concatenate",
"numpy.abs",
"Ngl.contour_map",
"Ngl.Resources",
"numpy.sign",
"Ngl.maximize_plot",
"numpy.int",
... | [((4047, 4075), 'Nio.open_file', 'nio.open_file', (['(diri + a_fili)'], {}), '(diri + a_fili)\n', (4060, 4075), True, 'import Nio as nio\n'), ((7688, 7731), 'numpy.where', 'np.where', (['(temp > 273.15)', '(17.08085)', '(17.84362)'], {}), '(temp > 273.15, 17.08085, 17.84362)\n', (7696, 7731), True, 'import numpy as np\... |
import numpy as np
from gurobipy import *
# Author: <NAME>
# Date: 2020-04-01
def get_approx_planes(P0, B, D, p_min, p_max, Relaxed=False):
# Return the approximation plane
# with the constraint pt' B pt + b' pt + c = 0
#
# P0 should be feasible
# Gurobipy is imported via *
mod ... | [
"numpy.dot",
"numpy.ones",
"numpy.linalg.norm"
] | [((485, 499), 'numpy.ones', 'np.ones', (['n_gen'], {}), '(n_gen)\n', (492, 499), True, 'import numpy as np\n'), ((1308, 1325), 'numpy.linalg.norm', 'np.linalg.norm', (['n'], {}), '(n)\n', (1322, 1325), True, 'import numpy as np\n'), ((1754, 1766), 'numpy.dot', 'np.dot', (['n', 'x'], {}), '(n, x)\n', (1760, 1766), True,... |
"""
eval auc curve
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import roc_auc_score,roc_curve,auc,average_precision_score
from net.utils.parser import load_config,parse_args
import net.utils.logging_tool as logging
from sklearn import metrics
import os
import scipy.io as scio
import ma... | [
"os.listdir",
"scipy.io.savemat",
"os.makedirs",
"net.utils.parser.load_config",
"sklearn.metrics.auc",
"matplotlib.pyplot.plot",
"os.path.join",
"net.utils.logging_tool.get_logger",
"net.utils.parser.parse_args",
"sklearn.metrics.roc_curve",
"numpy.expand_dims",
"matplotlib.pyplot.title",
"... | [((330, 358), 'net.utils.logging_tool.get_logger', 'logging.get_logger', (['__name__'], {}), '(__name__)\n', (348, 358), True, 'import net.utils.logging_tool as logging\n'), ((429, 449), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y_score'], {}), '(x, y_score)\n', (437, 449), True, 'import matplotlib.pyplot as plt\n'... |
from pathlib import Path
import numpy as np
import skimage.io
from matplotlib import pyplot as plt
from segmentation_models import get_preprocessing
from tools.model import configs
from tools.model import input_preprocessing
from utils import image as image_utils
BACKBONE_INPUT_PREPROCESSING = get_preprocessing(con... | [
"numpy.sqrt",
"pathlib.Path",
"utils.image.normalized_image",
"tools.model.input_preprocessing.InputPreprocessor",
"segmentation_models.get_preprocessing",
"numpy.zeros",
"numpy.stack",
"numpy.array",
"matplotlib.pyplot.subplots"
] | [((299, 334), 'segmentation_models.get_preprocessing', 'get_preprocessing', (['configs.BACKBONE'], {}), '(configs.BACKBONE)\n', (316, 334), False, 'from segmentation_models import get_preprocessing\n'), ((357, 524), 'tools.model.input_preprocessing.InputPreprocessor', 'input_preprocessing.InputPreprocessor', (['configs... |
# -*- coding: utf-8 -*-
# Author : tyty
# Date : 2018-6-21
from __future__ import division
import numpy as np
import pandas as pd
import tools as tl
class AritificialNeuralNetworks(object):
def __init__(self, layers, learningRate, trainX, trainY, testX, testY, epoch):
# input params
self.layers ... | [
"numpy.mean",
"time.clock",
"numpy.tanh",
"numpy.argmax",
"tools.createDataSet",
"numpy.array",
"numpy.random.uniform",
"numpy.zeros",
"numpy.dot",
"numpy.std",
"numpy.math.exp"
] | [((7558, 7576), 'tools.createDataSet', 'tl.createDataSet', ([], {}), '()\n', (7574, 7576), True, 'import tools as tl\n'), ((7875, 7887), 'time.clock', 'time.clock', ([], {}), '()\n', (7885, 7887), False, 'import time\n'), ((7967, 7979), 'time.clock', 'time.clock', ([], {}), '()\n', (7977, 7979), False, 'import time\n')... |
import pytest
import numpy as np
import mymath.bindings
def test_dot():
v1 = [1., 2, 3, -5.5, 42]
v2 = [-3.2, 0, 13, 6, -3.14]
result = mymath.bindings.dot(vector1=v1, vector2=v2)
assert pytest.approx(result) == np.dot(v1, v2)
def test_normalize():
v = [1., 2, 3, -5.5, 42]
result = mymat... | [
"pytest.approx",
"numpy.array",
"numpy.dot",
"pytest.raises",
"numpy.linalg.norm"
] | [((452, 483), 'numpy.array', 'np.array', (['[1.0, 2, 3, -5.5, 42]'], {}), '([1.0, 2, 3, -5.5, 42])\n', (460, 483), True, 'import numpy as np\n'), ((492, 525), 'numpy.array', 'np.array', (['[-3.2, 0, 13, 6, -3.14]'], {}), '([-3.2, 0, 13, 6, -3.14])\n', (500, 525), True, 'import numpy as np\n'), ((674, 705), 'numpy.array... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.