code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import numpy as np
from utils import *
class STATISTICS:
def __init__(self, val, count):
self.Value = val
self.Count = count
self.Mean = val
self.Variance = 0.
self.Min = 0.
self.Max = 0.
def SetValue(self, val):
self.Value = val
def ... | [
"numpy.sqrt"
] | [((1259, 1281), 'numpy.sqrt', 'np.sqrt', (['self.Variance'], {}), '(self.Variance)\n', (1266, 1281), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
This module generates twin-experiemnt data for training and validation.
"""
from sys import exit
from pathlib import Path
from numba import cuda
import numpy as np
def generate_twin_data(name, k__field, k__jacobian,
D, length, dt,... | [
"numpy.identity",
"numpy.random.normal",
"numpy.savez",
"numpy.linalg.solve",
"pathlib.Path.cwd",
"numpy.array",
"numpy.zeros",
"numba.cuda.to_device",
"numpy.array_equal",
"sys.exit",
"numpy.shape",
"numpy.load"
] | [((3377, 3406), 'numpy.zeros', 'np.zeros', (['(D, start + length)'], {}), '((D, start + length))\n', (3385, 3406), True, 'import numpy as np\n'), ((3443, 3467), 'numba.cuda.to_device', 'cuda.to_device', (['par_true'], {}), '(par_true)\n', (3457, 3467), False, 'from numba import cuda\n'), ((5886, 5907), 'numpy.zeros', '... |
import cv2
import numpy as np
def detect_features(img):
if len(img.shape)>2:
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#create SIFT detector
detector=cv2.xfeatures2d.SIFT_create()
(kps, descriptors) = detector.detectAndCompute(img, None)
#transfer kps from objects to numpy arrays
kps=n... | [
"numpy.float32",
"cv2.cvtColor",
"cv2.xfeatures2d.SIFT_create"
] | [((172, 201), 'cv2.xfeatures2d.SIFT_create', 'cv2.xfeatures2d.SIFT_create', ([], {}), '()\n', (199, 201), False, 'import cv2\n'), ((319, 352), 'numpy.float32', 'np.float32', (['[kp.pt for kp in kps]'], {}), '([kp.pt for kp in kps])\n', (329, 352), True, 'import numpy as np\n'), ((95, 132), 'cv2.cvtColor', 'cv2.cvtColor... |
import numpy as np
from scipy import sparse
import pickle
'''
Generate a random copy of data
input:
output: dict with two fields:
trainset: dict with two fields
scores: a sparse matrix, each ij entry is the rating of movie j given by person i, or the count of item j in bask... | [
"numpy.random.rand",
"numpy.logical_and",
"numpy.sum",
"numpy.random.seed",
"scipy.sparse.csr_matrix"
] | [((577, 595), 'numpy.random.seed', 'np.random.seed', (['(27)'], {}), '(27)\n', (591, 595), True, 'import numpy as np\n'), ((707, 744), 'numpy.random.rand', 'np.random.rand', (['(n_rows * 2)', 'n_columns'], {}), '(n_rows * 2, n_columns)\n', (721, 744), True, 'import numpy as np\n'), ((1020, 1049), 'numpy.sum', 'np.sum',... |
# -*- coding: utf-8 -*-
"""
faereld.graphs.box_plot
-----------
"""
from faereld import utils
from numpy import percentile
from datetime import timedelta
class BoxPlot(object):
left_whisker = "┣"
right_whisker = "┫"
whisker = "━"
box_body = "█"
median = "\033[91m█\033[0m"
def __init__(self, ... | [
"faereld.utils.terminal_width",
"numpy.percentile",
"datetime.timedelta",
"faereld.utils.strip_colour_codes"
] | [((395, 417), 'faereld.utils.terminal_width', 'utils.terminal_width', ([], {}), '()\n', (415, 417), False, 'from faereld import utils\n'), ((1472, 1498), 'numpy.percentile', 'percentile', (['area_value', '(25)'], {}), '(area_value, 25)\n', (1482, 1498), False, 'from numpy import percentile\n'), ((1520, 1546), 'numpy.pe... |
# Copyright (C) 2016 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# ========================================... | [
"tensorflow.local_variables_initializer",
"tensorflow.gfile.IsDirectory",
"tensorflow.contrib.framework.get_or_create_global_step",
"tensorflow.get_variable_scope",
"tensorflow.group",
"tensorflow.control_dependencies",
"tensorflow.gfile.MakeDirs",
"tensorflow.train.write_graph",
"tensorflow.reduce_... | [((1506, 1627), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""train_dir"""', '"""/tmp/imagenet_train"""', '"""Directory where to write event logs and checkpoint."""'], {}), "('train_dir', '/tmp/imagenet_train',\n 'Directory where to write event logs and checkpoint.')\n", (1532, 1627), Tru... |
import numpy as np
a = np.arange(1,10)
print(a)
M = np.reshape(a, [3,3])
print(M)
# Valdria también a.reshape([3, 3])
A = np.array([[n+m*10 for n in range(5)] for m in range(5)])
n,m = A.shape
print(A)
B = A.reshape((1, n*m))
print(B)
# Podemos también modificar directamente el array
B[0,0:5] = 5 # aqui estamos m... | [
"numpy.reshape",
"numpy.arange"
] | [((24, 40), 'numpy.arange', 'np.arange', (['(1)', '(10)'], {}), '(1, 10)\n', (33, 40), True, 'import numpy as np\n'), ((54, 75), 'numpy.reshape', 'np.reshape', (['a', '[3, 3]'], {}), '(a, [3, 3])\n', (64, 75), True, 'import numpy as np\n')] |
# name this file 'solutions.py'.
"""Volume III: GUI
<Name>
<Class>
<Date>
"""
# functools will be used for the matrix_calculator
import functools
import numpy as np
'''Problem 1 - Create a GUI with a button, text box, and label that will
display the contents of the text box in the label once the button is pressed... | [
"numpy.zeros",
"functools.partial"
] | [((5979, 6014), 'numpy.zeros', 'np.zeros', (['(self.rows, self.columns)'], {}), '((self.rows, self.columns))\n', (5987, 6014), True, 'import numpy as np\n'), ((4867, 4904), 'functools.partial', 'functools.partial', (['self.fileDialog', '(1)'], {}), '(self.fileDialog, 1)\n', (4884, 4904), False, 'import functools\n'), (... |
"""Two Layer Network."""
# pylint: disable=invalid-name
import numpy as np
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network. The net has an input dimension
of N, a hidden layer dimension of H, and performs classification over C
classes. We train the network with a softmax loss... | [
"numpy.random.choice",
"numpy.argmax",
"numpy.max",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"numpy.random.randint",
"numpy.random.uniform",
"numpy.maximum",
"numpy.random.randn"
] | [((1544, 1565), 'numpy.zeros', 'np.zeros', (['hidden_size'], {}), '(hidden_size)\n', (1552, 1565), True, 'import numpy as np\n'), ((1670, 1691), 'numpy.zeros', 'np.zeros', (['output_size'], {}), '(output_size)\n', (1678, 1691), True, 'import numpy as np\n'), ((3513, 3539), 'numpy.maximum', 'np.maximum', (['(0)', 'first... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
We show how to implement several variants of the Cormack-Jolly-Seber (CJS)
[4, 5, 6] model used in ecology to analyze animal capture-recapture data.
For a discussion of these models see reference [1].
We make use of two datase... | [
"torch.log1p",
"numpy.genfromtxt",
"numpy.mean",
"argparse.ArgumentParser",
"pyro.poutine.mask",
"pyro.set_rng_seed",
"pyro.infer.SVI",
"pyro.poutine.block",
"pyro.clear_param_store",
"pyro.infer.TraceEnum_ELBO",
"pyro.plate",
"torch.log",
"pyro.infer.TraceTMC_ELBO",
"torch.sigmoid",
"py... | [((3472, 3485), 'torch.ones', 'torch.ones', (['N'], {}), '(N)\n', (3482, 3485), False, 'import torch\n'), ((3612, 3644), 'pyro.plate', 'pyro.plate', (['"""animals"""', 'N'], {'dim': '(-1)'}), "('animals', N, dim=-1)\n", (3622, 3644), False, 'import pyro\n'), ((5177, 5190), 'torch.ones', 'torch.ones', (['N'], {}), '(N)\... |
import imutils
from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import cv2
import os
import pandas as pd
def show_image(image):
img = imutils.resize(image, width=600)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def remove_edge... | [
"cv2.drawContours",
"cv2.countNonZero",
"pandas.read_csv",
"cv2.arcLength",
"cv2.Canny",
"cv2.boundingRect",
"cv2.bitwise_and",
"cv2.imshow",
"imutils.resize",
"imutils.contours.sort_contours",
"imutils.grab_contours",
"cv2.destroyAllWindows",
"cv2.approxPolyDP",
"cv2.cvtColor",
"numpy.z... | [((193, 225), 'imutils.resize', 'imutils.resize', (['image'], {'width': '(600)'}), '(image, width=600)\n', (207, 225), False, 'import imutils\n'), ((231, 255), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img'], {}), "('image', img)\n", (241, 255), False, 'import cv2\n'), ((260, 274), 'cv2.waitKey', 'cv2.waitKey', (['... |
"""
"""
import copy
import logging
import numpy as np
from tqdm import tqdm
from qiskit.circuit import Parameter
from qiskit.ignis.mitigation import tensored_meas_cal
from qcoptim.cost.crossfidelity import (
CrossFidelity,
)
from qcoptim.utilities import (
make_quantum_instance,
simplify_rotation_angles,... | [
"logging.getLogger",
"numpy.atleast_2d",
"numpy.abs",
"numpy.random.default_rng",
"numpy.ones",
"tqdm.tqdm",
"qiskit.ignis.mitigation.tensored_meas_cal",
"qcoptim.cost.crossfidelity.CrossFidelity",
"copy.copy",
"numpy.array",
"numpy.zeros",
"qcoptim.utilities.make_quantum_instance",
"numpy.a... | [((539, 566), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (556, 566), False, 'import logging\n'), ((793, 1119), 'qcoptim.utilities.make_quantum_instance', 'make_quantum_instance', (['backend_name'], {'measurement_error_mitigation': '(False)', 'nb_shots': 'nb_shots', 'cals_matrix_refres... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from Augmenter import Augmenter
from DataLoader import DataLoader
from cnn_classifier import ClassifierCNN
def main():
# unbalanced data = ['insect', 'ecg200', 'gunpoint']
data_name = 'insect'
path = 'C:/Users/letiz/D... | [
"numpy.unique",
"numpy.where",
"sklearn.preprocessing.OneHotEncoder",
"DataLoader.DataLoader",
"cnn_classifier.ClassifierCNN",
"numpy.array",
"numpy.concatenate",
"pandas.DataFrame"
] | [((392, 467), 'DataLoader.DataLoader', 'DataLoader', ([], {'path': 'path', 'data_name': 'data_name', 'cgan': '(False)', 'bootstrap_test': '(True)'}), '(path=path, data_name=data_name, cgan=False, bootstrap_test=True)\n', (402, 467), False, 'from DataLoader import DataLoader\n'), ((578, 616), 'numpy.unique', 'np.unique'... |
# Created by <NAME>.
import sys
import numpy as np
sys.path.append('../')
from envs import GridWorld
from itertools import product
from utils import print_episode, test_policy
'''
Off-policy n-step Q-sigma used to estimate the optimal policy for
the gridworld environment defined on page 48 of
"Reinforcement Learning: ... | [
"utils.test_policy",
"utils.print_episode",
"numpy.argmax",
"envs.GridWorld",
"numpy.zeros",
"numpy.random.randint",
"sys.path.append"
] | [((51, 73), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (66, 73), False, 'import sys\n'), ((1117, 1128), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1125, 1128), True, 'import numpy as np\n'), ((1143, 1154), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1151, 1154), True, 'import n... |
import os
import sys
from datetime import datetime
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# local
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
add_path(os.path.abspath('..'))
from pycls.al.ActiveLe... | [
"sys.path.insert",
"matplotlib.pyplot.ylabel",
"pycls.core.optimizer.get_epoch_lr",
"pycls.core.optimizer.construct_optimizer",
"pycls.utils.net.compute_precise_bn_stats",
"numpy.array",
"torch.cuda.is_available",
"pycls.core.optimizer.set_lr",
"pycls.utils.logging.setup_logging",
"numpy.save",
... | [((824, 847), 'pycls.utils.logging.get_logger', 'lu.get_logger', (['__name__'], {}), '(__name__)\n', (837, 847), True, 'import pycls.utils.logging as lu\n'), ((18144, 18159), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18157, 18159), False, 'import torch\n'), ((272, 293), 'os.path.abspath', 'os.path.abspath', ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 11:05:21 2018
@author: 028375
"""
from __future__ import unicode_literals, division
import pandas as pd
import os.path
import numpy as np
def Check2(lastmonth,thismonth,collateral):
ContractID=(thismonth['ContractID'].append(lastmonth['ContractID'])).append(coll... | [
"pandas.merge",
"numpy.isnan",
"pandas.to_numeric",
"pandas.read_excel",
"pandas.DataFrame",
"pandas.ExcelWriter",
"pandas.to_datetime"
] | [((501, 554), 'pandas.merge', 'pd.merge', (['Outputs', 'cost0'], {'how': '"""left"""', 'on': '"""ContractID"""'}), "(Outputs, cost0, how='left', on='ContractID')\n", (509, 554), True, 'import pandas as pd\n'), ((732, 785), 'pandas.merge', 'pd.merge', (['Outputs', 'cost1'], {'how': '"""left"""', 'on': '"""ContractID"""'... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import pytest
import numpy as np
import logging
from scipy.sparse import csr_matrix, eye
from interpret_community.common.explanation_util... | [
"logging.getLogger",
"interpret_community.common.explanation_utils._convert_to_list",
"interpret_community.common.explanation_utils._get_raw_feature_importances",
"numpy.array",
"interpret_community.common.explanation_utils._get_feature_map_from_list_of_indexes",
"scipy.sparse.eye",
"raw_explain.utils._... | [((769, 796), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (786, 796), False, 'import logging\n'), ((800, 849), 'pytest.mark.owner', 'pytest.mark.owner', ([], {'email': 'owner_email_tools_and_ux'}), '(email=owner_email_tools_and_ux)\n', (817, 849), False, 'import pytest\n'), ((851, 887)... |
# --------------
import pandas as pd
import numpy as np
# Read the data using pandas module.
df = pd.read_csv(path)
# Find the list of unique cities where matches were played
matches_city= df['city'].unique()
print("Cities matches were played : {}".format(matches_city))
# Find the columns which contains null values if... | [
"numpy.where",
"pandas.DatetimeIndex",
"pandas.read_csv"
] | [((99, 116), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (110, 116), True, 'import pandas as pd\n'), ((1943, 2030), 'numpy.where', 'np.where', (["(high_scores1['inning1_runs'] <= high_scores1['inning2_runs'])", '"""yes"""', '"""no"""'], {}), "(high_scores1['inning1_runs'] <= high_scores1['inning2_runs... |
import numpy as np
import matplotlib.pyplot as plt
from import_explore import import_csv
from import_explore import normalise
# for performing regression
from regression_models import construct_rbf_feature_mapping
# for plotting results
from regression_plot import plot_train_test_errors
# two new functions for cross ... | [
"numpy.mean",
"numpy.sqrt",
"numpy.random.choice",
"numpy.delete",
"import_explore.import_csv",
"regression_train_test.cv_evaluation_linear_model",
"numpy.std",
"import_explore.normalise",
"numpy.zeros",
"numpy.linspace",
"numpy.empty",
"regression_train_test.create_cv_folds",
"regression_mo... | [((991, 1012), 'numpy.logspace', 'np.logspace', (['(0)', '(4)', '(20)'], {}), '(0, 4, 20)\n', (1002, 1012), True, 'import numpy as np\n'), ((1056, 1080), 'numpy.logspace', 'np.logspace', (['(-16)', '(-1)', '(20)'], {}), '(-16, -1, 20)\n', (1067, 1080), True, 'import numpy as np\n'), ((1207, 1247), 'numpy.empty', 'np.em... |
import numpy as np
class FindS(object):
def __init__(self, raw_dataset):
self.concepts = np.array(raw_dataset)[:,:-1]
self.target = np.array(raw_dataset)[:,-1]
def train(self):
for i, val in enumerate(self.target):
if val == 1:
max_hypothesis = self.concepts... | [
"numpy.array"
] | [((102, 123), 'numpy.array', 'np.array', (['raw_dataset'], {}), '(raw_dataset)\n', (110, 123), True, 'import numpy as np\n'), ((153, 174), 'numpy.array', 'np.array', (['raw_dataset'], {}), '(raw_dataset)\n', (161, 174), True, 'import numpy as np\n')] |
import datetime
import logging
import numpy as np
import os
import platform
import sys
import time
import darwin.engine.strategies as strategies
import darwin.engine.executors as executors
import darwin.engine.space as universe
import darwin.engine.particles as particles
from darwin.engine.space import Coordinate
f... | [
"logging.getLogger",
"numpy.random.get_state",
"logging.StreamHandler",
"darwin.engine.strategies.factory",
"sys.exit",
"logging.Formatter",
"darwin.engine.executors.factory",
"darwin.engine.space.bigBang",
"darwin.engine.space.expand",
"logging.FileHandler",
"darwin.engine.space.addExclusiveGro... | [((648, 667), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (665, 667), False, 'import logging\n'), ((706, 729), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (727, 729), False, 'import logging\n'), ((838, 880), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': '"""darw... |
import random
from typing import Any, List, Optional
import numpy as np
import numpy.typing as npt
import pytorch_lightning as pl
import torch
import torch.utils.data
from nuplan.planning.training.modeling.types import FeaturesType, TargetsType, move_features_type_to_device
from nuplan.planning.training.preprocessing.... | [
"nuplan.planning.training.preprocessing.features.trajectory.Trajectory",
"nuplan.planning.training.preprocessing.features.raster.Raster.from_feature_tensor",
"numpy.asarray",
"torch.from_numpy",
"torch.utils.data.Subset",
"nuplan.planning.training.modeling.types.move_features_type_to_device",
"nuplan.pl... | [((2568, 2630), 'torch.utils.data.Subset', 'torch.utils.data.Subset', ([], {'dataset': 'dataset', 'indices': 'sampled_idxs'}), '(dataset=dataset, indices=sampled_idxs)\n', (2591, 2630), False, 'import torch\n'), ((6229, 6247), 'numpy.asarray', 'np.asarray', (['images'], {}), '(images)\n', (6239, 6247), True, 'import nu... |
import numpy as np
def juryrec(a,tab):
n = len(a)
if n==1:
tab.append(a)
else:
line1 = a
line2 = line1[::-1]
tab.append(line1)
tab.append(line2)
alpha = line1[-1]/line2[-1]
aa = [el1 - alpha*el2 for (el1,el2) in itertools.izip(line1,line2)]
ju... | [
"numpy.exp",
"numpy.real",
"numpy.zeros",
"numpy.linspace",
"numpy.imag"
] | [((368, 379), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (376, 379), True, 'import numpy as np\n'), ((389, 413), 'numpy.linspace', 'np.linspace', (['(0)', 'np.pi', 'N'], {}), '(0, np.pi, N)\n', (400, 413), True, 'import numpy as np\n'), ((484, 494), 'numpy.real', 'np.real', (['z'], {}), '(z)\n', (491, 494), True,... |
"""
Coverage feature manipulation
"""
from pathlib import Path
import logging
import numpy as np
import h5py
import pysam
from coconet.core.feature import Feature
from coconet.util import run_if_not_exists
logger = logging.getLogger('<preprocessing>')
class CoverageFeature(Feature):
"""
Coverage object r... | [
"logging.getLogger",
"pathlib.Path",
"pysam.AlignmentFile",
"h5py.File",
"numpy.array",
"numpy.zeros",
"coconet.util.run_if_not_exists",
"coconet.core.feature.Feature.__init__"
] | [((221, 257), 'logging.getLogger', 'logging.getLogger', (['"""<preprocessing>"""'], {}), "('<preprocessing>')\n", (238, 257), False, 'import logging\n'), ((787, 806), 'coconet.util.run_if_not_exists', 'run_if_not_exists', ([], {}), '()\n', (804, 806), False, 'from coconet.util import run_if_not_exists\n'), ((3236, 3268... |
#loading keras models
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import numpy as np
from keras.preprocessing import image
from keras.preprocessing.ima... | [
"keras.preprocessing.image.img_to_array",
"keras.models.load_model",
"segmentation.segm",
"numpy.expand_dims",
"keras.preprocessing.image.load_img"
] | [((447, 477), 'keras.models.load_model', 'load_model', (['"""created_model.h5"""'], {}), "('created_model.h5')\n", (457, 477), False, 'from keras.models import load_model\n'), ((515, 583), 'keras.preprocessing.image.load_img', 'image.load_img', (['"""/home/tech/Desktop/2 no.jpeg"""'], {'target_size': '(64, 64)'}), "('/... |
# Wrap function for Vireo model
# Author: <NAME>
# Date: 22/03/2020
import sys
import numpy as np
import multiprocessing
from scipy.sparse import csc_matrix
from .vireo_base import optimal_match, donor_select
from .vireo_model import Vireo
from .vireo_doublet import predict_doublet, predit_ambient
def _model_fit(_mo... | [
"numpy.mean",
"numpy.median",
"numpy.arange",
"numpy.argmax",
"numpy.min",
"numpy.max",
"numpy.append",
"numpy.sum",
"numpy.array",
"numpy.zeros",
"numpy.argsort",
"numpy.random.seed",
"multiprocessing.Pool",
"sys.exit",
"threadpoolctl.threadpool_limits",
"scipy.sparse.csc_matrix",
"... | [((3191, 3235), 'numpy.array', 'np.array', (['[x.ELBO_[-1] for x in _models_all]'], {}), '([x.ELBO_[-1] for x in _models_all])\n', (3199, 3235), True, 'import numpy as np\n'), ((3247, 3266), 'numpy.argmax', 'np.argmax', (['elbo_all'], {}), '(elbo_all)\n', (3256, 3266), True, 'import numpy as np\n'), ((5743, 5774), 'num... |
import yaml
yaml.warnings({'YAMLLoadWarning': False})
import time
import numpy as np
import numba as nb
import consav.cpptools as cpptools
import ctypes as ct
# a. test function
@nb.njit(parallel=True)
def test(X,Y,Z,NX,NY):
# X is lenght NX
# Y is lenght NY
# Z is length NX
for i in nb.prange(NX):
... | [
"ctypes.POINTER",
"yaml.warnings",
"numpy.log",
"numba.njit",
"numpy.sum",
"numpy.zeros",
"numpy.random.sample",
"numpy.random.seed",
"consav.cpptools.link",
"numba.prange",
"numpy.ctypeslib.as_ctypes",
"time.time"
] | [((12, 53), 'yaml.warnings', 'yaml.warnings', (["{'YAMLLoadWarning': False}"], {}), "({'YAMLLoadWarning': False})\n", (25, 53), False, 'import yaml\n'), ((181, 203), 'numba.njit', 'nb.njit', ([], {'parallel': '(True)'}), '(parallel=True)\n', (188, 203), True, 'import numba as nb\n'), ((410, 447), 'numba.njit', 'nb.njit... |
# Author: <NAME>
# License: BSD
import numpy as np
from seglearn.datasets import load_watch
from seglearn.base import TS_Data
def test_ts_data():
# time series data
ts = np.array([np.random.rand(100, 10), np.random.rand(200, 10), np.random.rand(20, 10)])
c = np.random.rand(3, 10)
data = TS_Data(ts, ... | [
"seglearn.datasets.load_watch",
"seglearn.base.TS_Data",
"numpy.array_equal",
"numpy.random.rand"
] | [((275, 296), 'numpy.random.rand', 'np.random.rand', (['(3)', '(10)'], {}), '(3, 10)\n', (289, 296), True, 'import numpy as np\n'), ((308, 322), 'seglearn.base.TS_Data', 'TS_Data', (['ts', 'c'], {}), '(ts, c)\n', (315, 322), False, 'from seglearn.base import TS_Data\n'), ((335, 371), 'numpy.array_equal', 'np.array_equa... |
"""Query half-life and decay data from the National Nuclear Data Center.
References:
http://www.nndc.bnl.gov
http://www.nndc.bnl.gov/nudat2/indx_sigma.jsp
http://www.nndc.bnl.gov/nudat2/indx_dec.jsp
"""
from future.builtins import super
import warnings
import numpy as np
import requests
import pandas as pd
imp... | [
"requests.Session",
"future.builtins.super",
"warnings.catch_warnings",
"warnings.simplefilter",
"numpy.isfinite",
"pandas.DataFrame",
"uncertainties.ufloat",
"warnings.warn"
] | [((7960, 7989), 'uncertainties.ufloat', 'uncertainties.ufloat', (['x2', 'dx2'], {}), '(x2, dx2)\n', (7980, 7989), False, 'import uncertainties\n'), ((8539, 8554), 'numpy.isfinite', 'np.isfinite', (['x1'], {}), '(x1)\n', (8550, 8554), True, 'import numpy as np\n'), ((8681, 8696), 'numpy.isfinite', 'np.isfinite', (['x2']... |
# 要添加一个新单元,输入 '# %%'
# 要添加一个新的标记单元,输入 '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# # Module 1: Using CNN for dogs vs cats
# %% [markdown]
# To illustrate the Deep Learning pipeline, we are going to use a pretrained model to enter the [Dogs vs Cats](https://www.kaggle.com/c/dogs-vs-cats-redu... | [
"numpy.clip",
"torch.max",
"torch.exp",
"torch.from_numpy",
"numpy.argsort",
"numpy.array",
"torch.cuda.is_available",
"torch.sum",
"torchvision.utils.make_grid",
"matplotlib.pyplot.imshow",
"numpy.where",
"IPython.display.Image",
"torchvision.datasets.ImageFolder",
"numpy.concatenate",
... | [((4268, 4343), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (4288, 4343), False, 'from torchvision import models, transforms, datasets\n'), ((4638, 4669), 'os.path.join',... |
# -*- coding: utf-8 -*-
import numpy as np
from ._stft import stft, get_window, _check_NOLA
from ._ssq_cwt import _invert_components, _process_component_inversion_args
from .utils.cwt_utils import _process_fs_and_t, infer_scaletype
from .utils.common import WARN, EPS32, EPS64
from .utils import backend as S
from .utils... | [
"numpy.linspace",
"numpy.argmax"
] | [((8539, 8584), 'numpy.linspace', 'np.linspace', (['(0)', '(0.5 * fs)', 'n_rows'], {'dtype': 'dtype'}), '(0, 0.5 * fs, n_rows, dtype=dtype)\n', (8550, 8584), True, 'import numpy as np\n'), ((6233, 6250), 'numpy.argmax', 'np.argmax', (['window'], {}), '(window)\n', (6242, 6250), True, 'import numpy as np\n')] |
'''
Validation: die Trainingsdaten aufsplitten in Trainings und Validierungsdaten
um die Genauigkeit bzw. Leistung des Netzwerkes zu testen ,da das Netz erst
am Ende mit den Originaldaten (y) getestet werden sollte.
-> Evaluierung erst mit dem finalen Netz durchführen
'''
import numpy as np
from sklearn.preprocessin... | [
"tensorflow.keras.utils.to_categorical",
"tensorflow.keras.datasets.mnist.load_data",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"sklearn.preprocessing.StandardScaler",
"numpy.random.randint",
"numpy.zeros",
"numpy.expand_dims",
"numpy.conc... | [((740, 757), 'tensorflow.keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (755, 757), False, 'from tensorflow.keras.datasets import mnist\n'), ((1211, 1248), 'numpy.expand_dims', 'np.expand_dims', (['self.x_train'], {'axis': '(-1)'}), '(self.x_train, axis=-1)\n', (1225, 1248), True, 'import numpy ... |
# Copyright 2019 TerraPower, LLC
#
# 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 writi... | [
"numpy.allclose"
] | [((906, 966), 'numpy.allclose', 'numpy.allclose', (['val1', 'val2'], {'rtol': 'relativeTolerance', 'atol': '(0.0)'}), '(val1, val2, rtol=relativeTolerance, atol=0.0)\n', (920, 966), False, 'import numpy\n')] |
import os
import sys
from typing import List, Tuple
import numpy as np
from pgdrive.scene_creator.lanes.circular_lane import CircularLane
from pgdrive.scene_creator.lanes.lane import LineType
from pgdrive.scene_creator.lanes.straight_lane import StraightLane
from pgdrive.utils import import_pygame
from pgdrive.utils.... | [
"numpy.clip",
"pgdrive.utils.import_pygame",
"sys.exit",
"numpy.rad2deg",
"numpy.arange"
] | [((472, 487), 'pgdrive.utils.import_pygame', 'import_pygame', ([], {}), '()\n', (485, 487), False, 'from pgdrive.utils import import_pygame\n'), ((15789, 15820), 'numpy.clip', 'np.clip', (['starts', '(0)', 'lane.length'], {}), '(starts, 0, lane.length)\n', (15796, 15820), True, 'import numpy as np\n'), ((15836, 15865),... |
import cv2
import numpy as np
def get_crops(img, annotations, padding=0):
crops = []
new_img = img.copy() # Prevent drawing on original image
for a in annotations:
c = a['coordinates']
y1, y2 = int(c['y'] - c['height'] / 2 - padding), int(c['y'] + c['height'] / 2 + padding)
x1, x2 = int(c['x'] - c['width'] /... | [
"numpy.uint8",
"numpy.ones",
"cv2.threshold",
"cv2.addWeighted",
"cv2.morphologyEx",
"cv2.distanceTransform",
"cv2.connectedComponents",
"cv2.cvtColor",
"cv2.dilate",
"cv2.subtract",
"cv2.watershed"
] | [((1863, 1918), 'cv2.addWeighted', 'cv2.addWeighted', (['overlay', 'alpha', 'img', '(1 - alpha)', '(0)', 'img'], {}), '(overlay, alpha, img, 1 - alpha, 0, img)\n', (1878, 1918), False, 'import cv2\n'), ((500, 535), 'cv2.cvtColor', 'cv2.cvtColor', (['c', 'cv2.COLOR_BGR2GRAY'], {}), '(c, cv2.COLOR_BGR2GRAY)\n', (512, 535... |
import numpy as np
import pytest
from topfarm.tests import npt
from topfarm.constraint_components.boundary import PolygonBoundaryComp
@pytest.mark.parametrize('boundary', [
[(0, 0), (1, 1), (2, 0), (2, 2), (0, 2)],
[(0, 0), (1, 1), (2, 0), (2, 2), (0, 2), (0, 0)], # StartEqEnd
[(0, 0), (0, 2), (2, 2), (2... | [
"numpy.testing.assert_array_almost_equal",
"numpy.sqrt",
"topfarm.tests.npt.assert_array_less",
"topfarm.constraint_components.boundary.PolygonBoundaryComp",
"pytest.mark.parametrize",
"numpy.array",
"pytest.raises",
"numpy.testing.assert_array_equal",
"numpy.arctan"
] | [((137, 367), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""boundary"""', '[[(0, 0), (1, 1), (2, 0), (2, 2), (0, 2)], [(0, 0), (1, 1), (2, 0), (2, 2),\n (0, 2), (0, 0)], [(0, 0), (0, 2), (2, 2), (2, 0), (1, 1)], [(0, 0), (0,\n 2), (2, 2), (2, 0), (1, 1), (0, 0)]]'], {}), "('boundary', [[(0, 0), (1, ... |
from collections import defaultdict
import numpy as np
import umap
from hdbscan import HDBSCAN # approximate_predict,
from hdbscan import all_points_membership_vectors, membership_vector
from sklearn.preprocessing import normalize, scale
from tqdm import tqdm
import basty.utils.misc as misc
from basty.project.experi... | [
"numpy.sqrt",
"numpy.unique",
"hdbscan.all_points_membership_vectors",
"tqdm.tqdm",
"numpy.argmax",
"numpy.sum",
"numpy.zeros",
"collections.defaultdict",
"basty.project.experiment_processing.Project.__init__",
"umap.UMAP",
"hdbscan.membership_vector",
"sklearn.preprocessing.normalize",
"bas... | [((489, 536), 'basty.project.experiment_processing.Project.__init__', 'Project.__init__', (['self', 'main_cfg_path'], {}), '(self, main_cfg_path, **kwargs)\n', (505, 536), False, 'from basty.project.experiment_processing import Project\n'), ((2587, 2600), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (259... |
from time import time
from numpy import pi
from numpy import array
from numpy.random import random
from numpy.random import randint
from numpy import linspace
from numpy import arange
from numpy import column_stack
from numpy import cos
from numpy import sin
import cairocffi as cairo
from sand import Sand
from ..lib... | [
"numpy.random.random",
"numpy.array",
"numpy.linspace",
"sand.Sand",
"numpy.cos",
"numpy.sin",
"time.time"
] | [((1586, 1605), 'sand.Sand', 'Sand', (['width', 'height'], {}), '(width, height)\n', (1590, 1605), False, 'from sand import Sand\n'), ((503, 518), 'numpy.array', 'array', (['[[x, y]]'], {}), '([[x, y]])\n', (508, 518), False, 'from numpy import array\n'), ((628, 645), 'numpy.array', 'array', (['[0, width]'], {}), '([0,... |
"""
Image Pyramids
functions: cv2.pyrUp(), cv2.pyrDown()
sometimes, need to work with images of different resolution of the same image
create images with different resolution, search for object in all the images
image pyramid = {images of different resolution}
pyramid types
Gaussian pyramid
Laplacian pyram... | [
"cv2.imwrite",
"numpy.hstack",
"cv2.pyrDown",
"cv2.subtract",
"cv2.imread",
"cv2.pyrUp",
"cv2.add"
] | [((798, 822), 'cv2.imread', 'cv2.imread', (['"""messi5.jpg"""'], {}), "('messi5.jpg')\n", (808, 822), False, 'import cv2\n'), ((836, 860), 'cv2.pyrDown', 'cv2.pyrDown', (['higher_reso'], {}), '(higher_reso)\n', (847, 860), False, 'import cv2\n'), ((927, 948), 'cv2.pyrUp', 'cv2.pyrUp', (['lower_reso'], {}), '(lower_reso... |
import os
from flame import FLAME
from flame_config import get_config
import numpy as np
import torch
import torch.nn as nn
import trimesh
def batch_orth_proj_idrot(X, camera, name=None):
"""
X is N x num_points x 3
camera is N x 3
same as applying orth_proj_idrot to each N
"""
with tf.name_... | [
"numpy.ones",
"os.path.realpath",
"flame_config.get_config",
"flame.FLAME",
"trimesh.Trimesh",
"trimesh.exchange.obj.export_obj",
"numpy.load",
"torch.rand"
] | [((997, 1009), 'flame_config.get_config', 'get_config', ([], {}), '()\n', (1007, 1009), False, 'from flame_config import get_config\n'), ((1048, 1061), 'flame.FLAME', 'FLAME', (['config'], {}), '(config)\n', (1053, 1061), False, 'from flame import FLAME\n'), ((1209, 1267), 'numpy.load', 'np.load', (['params_path'], {'a... |
"""
Adapted from:
https://github.com/MadryLab/cifar10_challenge/blob/master/pgd_attack.py
Implementation of attack methods. Running this file as a program will
apply the attack to the model specified by the config file and store
the examples in an .npy file.
"""
from __future__ import absolute_import
from __future__ ... | [
"numpy.clip",
"numpy.copy",
"numpy.abs",
"tensorflow.nn.relu",
"tensorflow.reduce_sum",
"tensorflow.reduce_max",
"tensorflow.gradients",
"numpy.sign",
"tensorflow.nn.softmax",
"numpy.random.uniform",
"tensorflow.log",
"numpy.nan_to_num"
] | [((1121, 1142), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (1134, 1142), True, 'import tensorflow as tf\n'), ((3823, 3844), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (3836, 3844), True, 'import tensorflow as tf\n'), ((1775, 1812), 'tensorflow.gradients', 't... |
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
from pathlib2 import Path
import numpy as np
import argparse
import imutils
import time
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argu... | [
"cv2.rectangle",
"argparse.ArgumentParser",
"cv2.dnn.readNetFromCaffe",
"time.sleep",
"cv2.VideoWriter",
"os.path.isfile",
"cv2.putText",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"cv2.resize",
"cv2.waitKey",
"numpy.arange",
"os... | [((282, 307), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (305, 307), False, 'import argparse\n'), ((1218, 1275), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (["args['prototxt']", "args['model']"], {}), "(args['prototxt'], args['model'])\n", (1242, 1275), False, 'import cv2\n'), ... |
import torch
import numpy as np
from xgboost import XGBClassifier,XGBRegressor
from collections import OrderedDict
from XBNet.Seq import Seq
class XBNETClassifier(torch.nn.Module):
'''
XBNetClassifier is a model for classification tasks that tries to combine tree-based models with
neural networks to create... | [
"torch.nn.Sigmoid",
"collections.OrderedDict",
"torch.nn.Softmax",
"XBNet.Seq.Seq",
"numpy.column_stack",
"torch.from_numpy",
"xgboost.XGBRegressor",
"torch.save",
"torch.nn.Linear",
"xgboost.XGBClassifier"
] | [((1179, 1192), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1190, 1192), False, 'from collections import OrderedDict\n'), ((1618, 1649), 'xgboost.XGBClassifier', 'XGBClassifier', ([], {'n_estimators': '(100)'}), '(n_estimators=100)\n', (1631, 1649), False, 'from xgboost import XGBClassifier, XGBRegress... |
"""This module handles the data science operations on email lists."""
import io
import os
import json
import asyncio
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from billiard import current_process # pylint: disable=no-name-in-module
import requests
from requests.exce... | [
"billiard.current_process",
"pandas.value_counts",
"asyncio.Semaphore",
"datetime.timedelta",
"iso8601.parse_date",
"numpy.linspace",
"asyncio.sleep",
"asyncio.gather",
"pandas.DataFrame",
"io.StringIO",
"asyncio.get_event_loop",
"aiohttp.BasicAuth",
"json.loads",
"collections.OrderedDict"... | [((738, 762), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (760, 762), False, 'import asyncio\n'), ((777, 809), 'asyncio.ensure_future', 'asyncio.ensure_future', (['coroutine'], {}), '(coroutine)\n', (798, 809), False, 'import asyncio\n'), ((4023, 4048), 'celery.utils.log.get_task_logger', 'get... |
from typing import NamedTuple, List
import numpy as np
import matplotlib.pyplot as plt
class Point(NamedTuple):
x: int
y: int
class Line(NamedTuple):
start: Point
end: Point
def is_vertical(self):
return self.start.x == self.end.x
def is_horizontal(self):
return self.start... | [
"numpy.sum",
"numpy.zeros",
"numpy.abs"
] | [((431, 453), 'numpy.zeros', 'np.zeros', (['(1000, 1000)'], {}), '((1000, 1000))\n', (439, 453), True, 'import numpy as np\n'), ((1249, 1266), 'numpy.sum', 'np.sum', (['(board > 1)'], {}), '(board > 1)\n', (1255, 1266), True, 'import numpy as np\n'), ((1022, 1055), 'numpy.abs', 'np.abs', (['(line.start.x - line.end.x)'... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... | [
"numpy.testing.assert_array_equal",
"os.path.join",
"io.BytesIO",
"numpy.diag",
"numpy.array",
"pytest.raises",
"numpy.arange"
] | [((1033, 1061), 'os.path.join', 'pjoin', (['data_path', '"""tiny.mnc"""'], {}), "(data_path, 'tiny.mnc')\n", (1038, 1061), True, 'from os.path import join as pjoin\n'), ((3290, 3311), 'numpy.diag', 'np.diag', (['[2, 3, 4, 1]'], {}), '([2, 3, 4, 1])\n', (3297, 3311), True, 'import numpy as np\n'), ((6948, 6957), 'io.Byt... |
# -*- coding: utf-8 -*-
import os
import numpy as np
import cv2
from config import IMAGE_SIZE
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):
def get_padding_size(image):
h, w, _ = image.shape
longest_edge = max(h, w)
top, bottom, left, right = (0, 0, 0, 0)
if h <... | [
"os.listdir",
"cv2.copyMakeBorder",
"os.path.join",
"numpy.array",
"os.path.isdir",
"cv2.resize",
"cv2.imread"
] | [((711, 800), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['image', 'top', 'bottom', 'left', 'right', 'cv2.BORDER_CONSTANT'], {'value': 'BLACK'}), '(image, top, bottom, left, right, cv2.BORDER_CONSTANT,\n value=BLACK)\n', (729, 800), False, 'import cv2\n'), ((819, 856), 'cv2.resize', 'cv2.resize', (['constant', '(h... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
CB_color_cycle = ['#377eb8', '#ff7f00', '#4daf4a',
'#f781bf', '#a65628', '#984ea3',
'#999999', '#e41a1c', '#dede00']
def __min_birth_max_death(persistence, band=0.0):
# Look... | [
"numpy.where",
"pickle.load",
"numpy.append",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.patches.Polygon"
] | [((7326, 7354), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 11)'}), '(figsize=(16, 11))\n', (7336, 7354), True, 'import matplotlib.pyplot as plt\n'), ((1761, 1779), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (1773, 1779), True, 'import matplotlib.pyplot as plt\n... |
from collections import deque
import numpy as np
# A circular buffer implemented as a deque to keep track of the last few
# frames in the environment that together form a state capturing temporal
# and directional information. Provides an accessor to get the current
# state at any given time, which is represented as ... | [
"numpy.stack",
"collections.deque"
] | [((933, 963), 'collections.deque', 'deque', ([], {'maxlen': 'frames_per_state'}), '(maxlen=frames_per_state)\n', (938, 963), False, 'from collections import deque\n'), ((1792, 1822), 'numpy.stack', 'np.stack', (['self.frames'], {'axis': '(-1)'}), '(self.frames, axis=-1)\n', (1800, 1822), True, 'import numpy as np\n')] |
import numpy as np
from yt.testing import assert_allclose_units, fake_random_ds, requires_file
from yt.units import cm, s # type: ignore
from yt.utilities.answer_testing.framework import data_dir_load
from yt.visualization.volume_rendering.off_axis_projection import off_axis_projection
def random_unit_vector(prng):... | [
"numpy.sqrt",
"yt.testing.fake_random_ds",
"yt.visualization.volume_rendering.off_axis_projection.off_axis_projection",
"yt.testing.assert_allclose_units",
"yt.utilities.answer_testing.framework.data_dir_load",
"yt.testing.requires_file",
"numpy.dot",
"numpy.random.RandomState"
] | [((4989, 5007), 'yt.testing.requires_file', 'requires_file', (['g30'], {}), '(g30)\n', (5002, 5007), False, 'from yt.testing import assert_allclose_units, fake_random_ds, requires_file\n'), ((589, 619), 'numpy.random.RandomState', 'np.random.RandomState', (['(8675309)'], {}), '(8675309)\n', (610, 619), True, 'import nu... |
"""
Utility functions to fit and apply coordinates transformation from FVC to FP
"""
import json
import numpy as np
from desimeter.io import load_metrology
from desimeter.log import get_logger
from desimeter.transform.zhaoburge import getZhaoBurgeXY, transform, fit_scale_rotation_offset
#----------------------------... | [
"numpy.sqrt",
"desimeter.transform.zhaoburge.transform",
"numpy.argsort",
"numpy.array",
"numpy.sin",
"numpy.mean",
"json.dumps",
"numpy.asarray",
"numpy.abs",
"json.loads",
"numpy.in1d",
"desimeter.io.load_metrology",
"numpy.cos",
"numpy.median",
"desimeter.log.get_logger",
"desimeter... | [((608, 673), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 9, 20, 27, 28, 29, 30]'], {'dtype': 'int'}), '([0, 1, 2, 3, 4, 5, 6, 9, 20, 27, 28, 29, 30], dtype=int)\n', (616, 673), True, 'import numpy as np\n'), ((685, 727), 'numpy.zeros', 'np.zeros', (['self.zbpolids.shape'], {'dtype': 'float'}), '(self.zbpolids.... |
""" Test fast_dict.
"""
import numpy as np
from nose.tools import assert_equal
from sklearn.utils.fast_dict import IntFloatDict, argmin
from sklearn.externals.six.moves import xrange
def test_int_float_dict():
rng = np.random.RandomState(0)
keys = np.unique(rng.randint(100, size=10).astype(np.intp))
value... | [
"sklearn.utils.fast_dict.IntFloatDict",
"sklearn.utils.fast_dict.argmin",
"numpy.random.RandomState",
"nose.tools.assert_equal",
"sklearn.externals.six.moves.xrange",
"numpy.arange"
] | [((222, 246), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (243, 246), True, 'import numpy as np\n'), ((353, 379), 'sklearn.utils.fast_dict.IntFloatDict', 'IntFloatDict', (['keys', 'values'], {}), '(keys, values)\n', (365, 379), False, 'from sklearn.utils.fast_dict import IntFloatDict, a... |
"""
udu poser client example
more info: help(templates.UduPoserTemplate)
"""
import asyncio
import time
import numpy as np
import pyrr
from virtualreality import templates
from virtualreality.server import server
poser = templates.UduPoserClient("h c c") # devices setup identical to normal posers
@poser.thread_r... | [
"virtualreality.templates.UduPoserClient",
"pyrr.Quaternion.from_y_rotation",
"numpy.cos",
"asyncio.sleep",
"numpy.sin"
] | [((225, 258), 'virtualreality.templates.UduPoserClient', 'templates.UduPoserClient', (['"""h c c"""'], {}), "('h c c')\n", (249, 258), False, 'from virtualreality import templates\n'), ((502, 536), 'pyrr.Quaternion.from_y_rotation', 'pyrr.Quaternion.from_y_rotation', (['h'], {}), '(h)\n', (533, 536), False, 'import pyr... |
import math
import numpy as np
def TotalVariationalDistance(certificate_one, certificate_two):
"""
Calculate the total variational distance between two vectors of certificates
@param certificate_one: certificates for vector one
@param certificate_two: certificates for vector two
"""
return ... | [
"numpy.abs",
"numpy.dot",
"numpy.linalg.norm"
] | [((324, 365), 'numpy.abs', 'np.abs', (['(certificate_one - certificate_two)'], {}), '(certificate_one - certificate_two)\n', (330, 365), True, 'import numpy as np\n'), ((615, 656), 'numpy.abs', 'np.abs', (['(certificate_one - certificate_two)'], {}), '(certificate_one - certificate_two)\n', (621, 656), True, 'import nu... |
import itertools
from keras import backend as K, optimizers
from keras import layers
from keras import models
import tensorflow as tf
import numpy as np
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_... | [
"itertools.product",
"keras.models.Sequential",
"tensorflow.python.saved_model.builder.SavedModelBuilder",
"keras.backend.get_session",
"keras.optimizers.SGD",
"numpy.random.seed",
"tensorflow.python.saved_model.signature_def_utils_impl.predict_signature_def",
"keras.layers.Dense",
"tensorflow.set_r... | [((437, 454), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (451, 454), True, 'import numpy as np\n'), ((455, 476), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (473, 476), True, 'import tensorflow as tf\n'), ((1071, 1094), 'keras.backend.set_learning_phase', 'K.set_learn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: <NAME> (contact: <EMAIL>) and <NAME> (contact <EMAIL>)
# Created: Nov 2nd 2018
#
# Xarray wrapper around astropy.stats.circstats functions
# TODO: find a way to implement weights, both if weights == None, type(weights) == np.ndarray or type(weights) == xr.Data... | [
"numpy.abs",
"numpy.ones",
"numpy.where",
"numpy.size",
"numpy.exp",
"numpy.arctan2",
"numpy.isfinite",
"numpy.cos",
"numpy.sin",
"numpy.hypot",
"numpy.nansum",
"xarray.apply_ufunc",
"numpy.broadcast_to"
] | [((854, 964), 'xarray.apply_ufunc', 'xr.apply_ufunc', (['_circmean', 'circ_data'], {'input_core_dims': '[[dim]]', 'dask': '"""parallelized"""', 'output_dtypes': '[float]'}), "(_circmean, circ_data, input_core_dims=[[dim]], dask=\n 'parallelized', output_dtypes=[float])\n", (868, 964), True, 'import xarray as xr\n'),... |
# -*- coding: utf-8 -*-1
"""
2014, LAAS/CNRS
@author: <NAME>
"""
from __future__ import print_function
from dynamic_graph import plug
import numpy as np
from dynamic_graph.sot.core.latch import Latch
from dynamic_graph.sot.core.operator import Selec_of_vector, Mix_of_vector
from dynamic_graph.sot.torque_control.numer... | [
"dynamic_graph.sot.core.Add_of_vector",
"time.sleep",
"dynamic_graph.sot.torque_control.se3_trajectory_generator.SE3TrajectoryGenerator",
"dynamic_graph.sot.torque_control.imu_offset_compensation.ImuOffsetCompensation",
"dynamic_graph.sot.torque_control.free_flyer_locator.FreeFlyerLocator",
"dynamic_graph... | [((2419, 2426), 'dynamic_graph.sot.torque_control.talos.sot_utils_talos.Bunch', 'Bunch', ([], {}), '()\n', (2424, 2426), False, 'from dynamic_graph.sot.torque_control.talos.sot_utils_talos import Bunch\n'), ((3880, 3887), 'dynamic_graph.sot.torque_control.talos.sot_utils_talos.Bunch', 'Bunch', ([], {}), '()\n', (3885, ... |
'''
A compatibility layer for DSS C-API that mimics the official OpenDSS COM interface.
Copyright (c) 2016-2020 <NAME>
'''
from __future__ import absolute_import
from .._cffi_api_util import DSSException, Iterable
import numpy as np
class IMonitors(Iterable):
__slots__ = []
_columns = [
'Name',
... | [
"numpy.zeros"
] | [((1388, 1420), 'numpy.zeros', 'np.zeros', (['(1,)'], {'dtype': 'np.float32'}), '((1,), dtype=np.float32)\n', (1396, 1420), True, 'import numpy as np\n')] |
import pandas as pd
import sys
import numpy as np
def speedTest(processed):
dataframe = pd.DataFrame()
array = np.ndarray((36652,1))
for system in processed:
for unit in processed[system]:
for flow in processed[system][unit]:
for property in processed[system][unit][flow]... | [
"pandas.DataFrame",
"numpy.array",
"sys.getsizeof",
"numpy.ndarray"
] | [((93, 107), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (105, 107), True, 'import pandas as pd\n'), ((120, 142), 'numpy.ndarray', 'np.ndarray', (['(36652, 1)'], {}), '((36652, 1))\n', (130, 142), True, 'import numpy as np\n'), ((710, 734), 'sys.getsizeof', 'sys.getsizeof', (['processed'], {}), '(processed)\n... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@copyright 2017
@licence: 2-clause BSD licence
This tests shows how to enslave a phase to an external signal
"""
import sys
sys.path.insert(0,'../src')
import os
import numpy
numpy.set_printoptions(precision=2, suppress=True)
#import the phase-state... | [
"numpy.tile",
"sys.path.insert",
"phasestatemachine.Kernel",
"matplotlib.pylab.figure",
"numpy.linspace",
"os.path.basename",
"numpy.set_printoptions"
] | [((195, 223), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../src"""'], {}), "(0, '../src')\n", (210, 223), False, 'import sys\n'), ((246, 296), 'numpy.set_printoptions', 'numpy.set_printoptions', ([], {'precision': '(2)', 'suppress': '(True)'}), '(precision=2, suppress=True)\n', (268, 296), False, 'import numpy\... |
# pylint: disable=no-self-use,invalid-name
from __future__ import absolute_import
from numpy.testing import assert_allclose
import torch
from allennlp.common import Params
from allennlp.common.testing import AllenNlpTestCase
from allennlp.modules.matrix_attention.legacy_matrix_attention import LegacyMatrixAttention
... | [
"allennlp.modules.similarity_functions.dot_product.DotProductSimilarity",
"allennlp.common.Params",
"numpy.testing.assert_allclose",
"allennlp.modules.matrix_attention.matrix_attention.MatrixAttention.from_params",
"torch.FloatTensor"
] | [((680, 724), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[1, 1, 1], [-1, 0, 1]]]'], {}), '([[[1, 1, 1], [-1, 0, 1]]])\n', (697, 724), False, 'import torch\n'), ((753, 811), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[1, 1, 1], [-1, 0, 1], [-1, -1, -1]]]'], {}), '([[[1, 1, 1], [-1, 0, 1], [-1, -1, -1]]])\n', (77... |
"""
Filename: plot_depth.py
Author: <NAME>, <EMAIL>
Description: Plot data that has a depth axis
"""
# Import general Python modules
import sys
import os
import pdb
import re
import argparse
import numpy
import matplotlib.pyplot as plt
import iris
from iris.experimental.equalise_cubes import equalise_a... | [
"matplotlib.pyplot.grid",
"general_io.iris_vertical_constraint",
"matplotlib.pyplot.ylabel",
"iris.coords.AuxCoord",
"sys.path.append",
"numpy.arange",
"iris.cube.CubeList",
"argparse.ArgumentParser",
"cmdline_provenance.new_log",
"iris.experimental.equalise_cubes.equalise_attributes",
"matplotl... | [((396, 407), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (405, 407), False, 'import os\n'), ((576, 609), 'os.path.join', 'os.path.join', (['repo_dir', '"""modules"""'], {}), "(repo_dir, 'modules')\n", (588, 609), False, 'import os\n'), ((610, 638), 'sys.path.append', 'sys.path.append', (['modules_dir'], {}), '(modules... |
import json
import pandas as pd
import numpy as np
import datetime
class FileHelper:
def __init__(self):
pass
def load_json_file(self, filename):
with open(filename) as data_file:
data = json.load(data_file)
humidity_array = np.array([d["data"] for d in data])
ts_... | [
"datetime.datetime.fromtimestamp",
"pandas.read_csv",
"datetime.datetime.strptime",
"numpy.array",
"json.load"
] | [((273, 308), 'numpy.array', 'np.array', (["[d['data'] for d in data]"], {}), "([d['data'] for d in data])\n", (281, 308), True, 'import numpy as np\n'), ((1124, 1223), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'header': '(0)', 'parse_dates': '[0]', 'index_col': '(0)', 'squeeze': '(True)', 'date_parser': 'parse... |
from unittest.mock import patch, MagicMock
from pathlib import Path
import openreview
import json
import pytest
import numpy as np
from expertise.dataset import ArchivesDataset, SubmissionsDataset
from expertise.models import elmo
@pytest.fixture
def create_elmo():
def simple_elmo(config):
archives_dataset... | [
"numpy.array",
"numpy.array_equal",
"pathlib.Path"
] | [((2687, 2730), 'numpy.array', 'np.array', (['[[1, 2, 3], [5, 5, 5], [1, 0, 1]]'], {}), '([[1, 2, 3], [5, 5, 5], [1, 0, 1]])\n', (2695, 2730), True, 'import numpy as np\n'), ((2871, 2932), 'numpy.array', 'np.array', (['[[0.0, 0.5, 1.0], [0.5, 0.5, 0.5], [1.0, 0.0, 1.0]]'], {}), '([[0.0, 0.5, 1.0], [0.5, 0.5, 0.5], [1.0... |
import numpy as np
import pandas as pd
import os
import os.path
fold = 4#1#4#3
resep = 143#21#17#39
gbtdepth = 2#3#2#3
neptime = 0.3
testdetp = -2
traindetp = -2
start_epoch = 0 # start from epoch 0 or last checkpoint epoch
resmodelpath = './detcls-'+str(fold)+'-old/ckptgbt.t7'
def iou(box0, box1):
r0 = box0[3] / ... | [
"numpy.prod",
"torch.nn.CrossEntropyLoss",
"pandas.read_csv",
"torch.max",
"transforms.Normalize",
"torch.cuda.device_count",
"numpy.argsort",
"numpy.array",
"torch.cuda.is_available",
"logging.info",
"numpy.mean",
"transforms.RandomYFlip",
"os.listdir",
"numpy.reshape",
"argparse.Argume... | [((1230, 1412), 'pandas.read_csv', 'pd.read_csv', (['"""/media/data1/wentao/tianchi/luna16/CSVFILES/annotationdetclsconvfnl_v3.csv"""'], {'names': "['seriesuid', 'coordX', 'coordY', 'coordZ', 'diameter_mm', 'malignant']"}), "(\n '/media/data1/wentao/tianchi/luna16/CSVFILES/annotationdetclsconvfnl_v3.csv'\n , name... |
import torch
import numpy as np
import cv2
import tqdm
import os
import json
from pycocotools.mask import *
from src.unet_plus import SE_Res50UNet,SE_Res101UNet
import time
local_time = time.strftime('%Y-%m-%d-%H-%M',time.localtime(time.time()))
TEST_IMG_PATH = '/mnt/jinnan2_round2_test_b_20190424'
NORMAL_LIST_P... | [
"src.unet_plus.SE_Res50UNet",
"json.JSONEncoder.default",
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"numpy.rot90",
"os.listdir",
"src.unet_plus.SE_Res101UNet",
"numpy.where",
"json.dumps",
"numpy.flipud",
"numpy.fliplr",
"numpy.asfortranarray",
"cv2.resize",
"numpy.tr... | [((649, 681), 'src.unet_plus.SE_Res50UNet', 'SE_Res50UNet', (['(6)'], {'cls_only': 'is_clc'}), '(6, cls_only=is_clc)\n', (661, 681), False, 'from src.unet_plus import SE_Res50UNet, SE_Res101UNet\n'), ((820, 853), 'src.unet_plus.SE_Res101UNet', 'SE_Res101UNet', (['(6)'], {'cls_only': 'is_clc'}), '(6, cls_only=is_clc)\n'... |
from __future__ import division, print_function
import numpy as np
from openaerostruct.geometry.utils import generate_mesh
from openaerostruct.integration.aerostruct_groups import AerostructGeometry, AerostructPoint
from openmdao.api import IndepVarComp, Problem, Group, SqliteRecorder, \
... | [
"openaerostruct.geometry.utils.generate_mesh",
"numpy.abs",
"numpy.flip",
"numpy.sqrt",
"openaerostruct.integration.aerostruct_groups.AerostructGeometry",
"numpy.polyfit",
"openmdao.api.IndepVarComp",
"numpy.size",
"openaerostruct.integration.aerostruct_groups.AerostructPoint",
"numpy.array",
"n... | [((1360, 1371), 'time.time', 'time.time', ([], {}), '()\n', (1369, 1371), False, 'import time\n'), ((1678, 1693), 'numpy.sqrt', 'np.sqrt', (['(S * AR)'], {}), '(S * AR)\n', (1685, 1693), True, 'import numpy as np\n'), ((1772, 1799), 'numpy.array', 'np.array', (['[0.38 * rc, 0, 0]'], {}), '([0.38 * rc, 0, 0])\n', (1780,... |
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, Dict, List, Tuple, Type, Union
try:
from functools import cached_property
except:
from backports.cached_property import cached_property
import numpy as np
from scipy.stats import beta, rv_continuous
from co... | [
"colosseum.mdps.base_mdp.NextStateSampler",
"dataclasses.dataclass",
"colosseum.utils.random_vars.get_dist",
"numpy.zeros",
"scipy.stats.beta",
"colosseum.utils.random_vars.deterministic",
"colosseum.utils.mdps.check_distributions",
"colosseum.mdps.base_mdp.MDP.testing_parameters"
] | [((491, 513), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (500, 513), False, 'from dataclasses import dataclass\n'), ((908, 932), 'colosseum.mdps.base_mdp.MDP.testing_parameters', 'MDP.testing_parameters', ([], {}), '()\n', (930, 932), False, 'from colosseum.mdps.base_mdp import... |
from datetime import timedelta
import functools
import numpy as np
import pandas as pd
from . import common
from . import indexing
from . import ops
from . import utils
from .pycompat import basestring, OrderedDict, zip
import xray # only for Dataset and DataArray
def as_variable(obj, key=None, strict=True):
"... | [
"numpy.ma.getmaskarray",
"numpy.asarray",
"functools.wraps",
"numpy.empty",
"numpy.datetime64",
"numpy.timedelta64",
"numpy.atleast_1d"
] | [((7622, 7638), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (7632, 7638), True, 'import numpy as np\n'), ((3281, 3312), 'numpy.datetime64', 'np.datetime64', (['data.value', '"""ns"""'], {}), "(data.value, 'ns')\n", (3294, 3312), True, 'import numpy as np\n'), ((3768, 3784), 'numpy.asarray', 'np.asarray',... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*
# @FileName: simulator
# @Date: 2019-03-21 10:51
# @Author: HuGuodong <EMAIL>[at]<EMAIL>
# -*- encoding=utf8 -*-
import sys
import numpy as np
import cv2 as cv
import copy
import shutil
import os
np.random.seed(951105)
TIME = [0]
CARDISTRIBUTION = [0, 0, 0]
CARNAMESPACE... | [
"cv2.imwrite",
"numpy.ones",
"numpy.random.random_integers",
"cv2.line",
"cv2.putText",
"cv2.circle",
"numpy.random.seed",
"os.mkdir",
"shutil.rmtree"
] | [((245, 267), 'numpy.random.seed', 'np.random.seed', (['(951105)'], {}), '(951105)\n', (259, 267), True, 'import numpy as np\n'), ((25906, 25958), 'cv2.imwrite', 'cv.imwrite', (["(self.savePath + '/%d.jpg' % TIME[0])", 'img'], {}), "(self.savePath + '/%d.jpg' % TIME[0], img)\n", (25916, 25958), True, 'import cv2 as cv\... |
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from typing import Iterable, List, Tuple
from datetime import date, timedelta
from power_generators import SolarPanel, Windmill
from loads import ContinuousLoad, TimedLoad, StaggeredLoad
from battery import Battery, CarBattery
class Ho... | [
"pandas.Timestamp",
"pandas.DateOffset",
"numpy.zeros",
"datetime.timedelta"
] | [((462, 494), 'pandas.Timestamp', 'pd.Timestamp', (['"""2016-05-24 00:00"""'], {}), "('2016-05-24 00:00')\n", (474, 494), True, 'import pandas as pd\n'), ((2912, 2925), 'numpy.zeros', 'np.zeros', (['(288)'], {}), '(288)\n', (2920, 2925), True, 'import numpy as np\n'), ((3103, 3116), 'numpy.zeros', 'np.zeros', (['(288)'... |
"""
Stores the class for TimeSeriesDisplay.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
import warnings
from re import search as re_search
from matplotlib import colors as mplcolors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from .plot import Display... | [
"numpy.ma.masked_equal",
"numpy.invert",
"numpy.array",
"matplotlib.colors.CSS4_COLORS.keys",
"numpy.isfinite",
"copy.deepcopy",
"numpy.nanmin",
"datetime.timedelta",
"re.search",
"numpy.ma.masked_outside",
"numpy.asarray",
"matplotlib.colors.ListedColormap",
"numpy.max",
"numpy.nanmax",
... | [((25501, 25539), 'copy.deepcopy', 'deepcopy', (['self._obj[dsname][spd_field]'], {}), '(self._obj[dsname][spd_field])\n', (25509, 25539), False, 'from copy import deepcopy\n'), ((25578, 25616), 'copy.deepcopy', 'deepcopy', (['self._obj[dsname][spd_field]'], {}), '(self._obj[dsname][spd_field])\n', (25586, 25616), Fals... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 1 09:26:53 2017
@author: Antoi
"""
import numpy as np
import numpy.random as rd
class environnement:
def __init__(self,intercept=50,slope=-1,moving_intercept=25):
self.firms=[]
self.period=0
self.currentMarketPrice=self.marke... | [
"random.uniform",
"numpy.sin",
"matplotlib.pyplot.plot",
"numpy.argmax",
"numpy.array",
"keras.layers.Input",
"keras.models.Model",
"numpy.concatenate",
"keras.layers.Dense",
"keras.layers.BatchNormalization",
"matplotlib.pyplot.show"
] | [((3169, 3193), 'matplotlib.pyplot.plot', 'plt.plot', (['history[:, -3]'], {}), '(history[:, -3])\n', (3177, 3193), True, 'import matplotlib.pyplot as plt\n'), ((3399, 3434), 'keras.layers.Input', 'Input', ([], {'shape': '(n_variable * memory,)'}), '(shape=(n_variable * memory,))\n', (3404, 3434), False, 'from keras.la... |
import argparse
import googlemaps
import carpool_data as cd
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Get Distance Matrix from Coordinates")
parser.add_argument('--api_key', default='')
parser.add_argument('--coords_file', default='map_data/carpo... | [
"carpool_data.load_coordinates",
"argparse.ArgumentParser",
"googlemaps.Client",
"numpy.asarray",
"numpy.savetxt"
] | [((126, 201), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Get Distance Matrix from Coordinates"""'}), "(description='Get Distance Matrix from Coordinates')\n", (149, 201), False, 'import argparse\n'), ((611, 651), 'carpool_data.load_coordinates', 'cd.load_coordinates', (["args['coords... |
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
"""
________ ___ ___________ __
/ ____/\ \/ / |/ /_ __/ | / /
/ / \ /| / / / / /| | / /
/ /___ / // | / / / ___ |/ /___
\____/ /_//_/|_|/_/ /_/ |_/_____/
Copyright (c) 2015, <NAME>.
All rights reserved.
Redistribution and use in sour... | [
"distutils.core.setup",
"distutils.extension.Extension",
"numpy.get_include"
] | [((1672, 1688), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (1686, 1688), True, 'import numpy as np\n'), ((1820, 2030), 'distutils.core.setup', 'setup', ([], {'name': '"""cyxtal"""', 'version': '(0.2)', 'description': '"""crystal analysis package (cython)"""', 'author': '"""C.Z"""', 'author_email': '"""<EM... |
import PySimpleGUI as sg
import numpy as np
from pathlib import Path
from api import audio as ap
#############
# CONSTANTS #
#############
# Query prior
INPUT_RANGE = (-1, 1) # Slider limits
INPUT_RESOLUTION = .001 # Slider resolution
INDICATOR_SIZE = 10
PRIOR_CANVAS_WIDTH = 250
PRIOR_CANVAS_HEIGHT = 200
EMO_LABEL... | [
"numpy.abs",
"numpy.reshape",
"api.audio.time_info",
"api.audio.resume",
"PySimpleGUI.Slider",
"api.audio.pause",
"api.audio.play",
"PySimpleGUI.Text",
"PySimpleGUI.ProgressBar",
"api.audio.stop",
"numpy.array",
"PySimpleGUI.Button",
"numpy.cos",
"numpy.interp",
"numpy.sin",
"api.audio... | [((3753, 3772), 'numpy.array', 'np.array', (['result[1]'], {}), '(result[1])\n', (3761, 3772), True, 'import numpy as np\n'), ((5346, 5360), 'api.audio.time_info', 'ap.time_info', ([], {}), '()\n', (5358, 5360), True, 'from api import audio as ap\n'), ((6517, 6531), 'api.audio.is_paused', 'ap.is_paused', ([], {}), '()\... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# <NAME> <<EMAIL>>
# Thu 14 Apr 2016 18:02:45
import numpy
import os
import bob.measure
# read scores of evaluation and test set
def read_scores(scores_path, database, part, experiment):
path = os.path.join(scores_path, database + "_" + part + "_" + experiment... | [
"numpy.loadtxt",
"os.path.join"
] | [((254, 321), 'os.path.join', 'os.path.join', (['scores_path', "(database + '_' + part + '_' + experiment)"], {}), "(scores_path, database + '_' + part + '_' + experiment)\n", (266, 321), False, 'import os\n'), ((546, 579), 'numpy.loadtxt', 'numpy.loadtxt', (['impostor_eval_file'], {}), '(impostor_eval_file)\n', (559, ... |
__author__ = 'yunbo'
import numpy as np
def reshape_patch(img_tensor, patch_size):
assert 5 == img_tensor.ndim
batch_size = np.shape(img_tensor)[0]
seq_length = np.shape(img_tensor)[1]
img_height = np.shape(img_tensor)[2]
img_width = np.shape(img_tensor)[3]
num_channels = np.shape(img_tensor)[... | [
"numpy.shape",
"numpy.transpose",
"numpy.reshape"
] | [((331, 472), 'numpy.reshape', 'np.reshape', (['img_tensor', '[batch_size, seq_length, img_height // patch_size, patch_size, img_width //\n patch_size, patch_size, num_channels]'], {}), '(img_tensor, [batch_size, seq_length, img_height // patch_size,\n patch_size, img_width // patch_size, patch_size, num_channels... |
#!/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2020 yinochaos <<EMAIL>>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... | [
"numpy.mean",
"tqdm.tqdm",
"tensorflow.keras.callbacks.History",
"math.isnan"
] | [((1410, 1438), 'tensorflow.keras.callbacks.History', 'tf.keras.callbacks.History', ([], {}), '()\n', (1436, 1438), True, 'import tensorflow as tf\n'), ((2284, 2318), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'train_dataset_len'}), '(total=train_dataset_len)\n', (2293, 2318), False, 'import tqdm\n'), ((3595, 3614), 'num... |
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
from scikits.learn.mixture import GMM
np.random.seed(1)
n = 10
l = 256
im = np.zeros((l, l))
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n)... | [
"matplotlib.pyplot.imshow",
"scipy.ndimage.binary_erosion",
"numpy.random.random",
"numpy.logical_not",
"scipy.ndimage.binary_opening",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.contour",
"numpy.random.seed",
"scipy.ndimage.binary_propagation",
"scipy.ndimage.gaussian_filter"... | [((116, 133), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (130, 133), True, 'import numpy as np\n'), ((154, 170), 'numpy.zeros', 'np.zeros', (['(l, l)'], {}), '((l, l))\n', (162, 170), True, 'import numpy as np\n'), ((278, 326), 'scipy.ndimage.gaussian_filter', 'ndimage.gaussian_filter', (['im'], {'s... |
# -*- coding: utf-8 -*-
import os
import time
import argparse
import numpy as np
try:
import torch
except ImportError:
try:
import tensorflow as tf
except ImportError:
print("No pytorch and tensorflow module")
def set_parser():
parser = argparse.ArgumentParser(descript... | [
"argparse.ArgumentParser",
"time.sleep",
"numpy.argsort",
"numpy.array",
"os.popen",
"torch.zeros",
"tensorflow.zeros"
] | [((288, 329), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""".."""'}), "(description='..')\n", (311, 329), False, 'import argparse\n'), ((931, 950), 'numpy.array', 'np.array', (['result_np'], {}), '(result_np)\n', (939, 950), True, 'import numpy as np\n'), ((2752, 2774), 'time.sleep', 't... |
# Full feature set except Whois + Blacklist
import numpy as np
Hostbased_Feature_path = 'Host_based_FeatureSet.npy'
Full_ex_wb_path = 'Full_except_WB.npy'
Lexical_Feature_path = 'Lexical_FeatureSet.npy'
hostbased = np.load(Hostbased_Feature_path)
Hostbased_ex_wb = hostbased[:,6:]
lexical = np.load(Lexical_Feature_pat... | [
"numpy.load",
"numpy.save",
"numpy.hstack"
] | [((217, 248), 'numpy.load', 'np.load', (['Hostbased_Feature_path'], {}), '(Hostbased_Feature_path)\n', (224, 248), True, 'import numpy as np\n'), ((293, 322), 'numpy.load', 'np.load', (['Lexical_Feature_path'], {}), '(Lexical_Feature_path)\n', (300, 322), True, 'import numpy as np\n'), ((337, 374), 'numpy.hstack', 'np.... |
"""
Retrain the YOLO model for your own dataset.
"""
import glob
import numpy as np
import tensorflow.keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
impo... | [
"PIL.Image.new",
"yolo3.model.preprocess_true_boxes",
"numpy.array",
"yolo3.model.tiny_yolo_body",
"yolo3.model.yolo_body",
"keras.models.Model",
"keras.callbacks.EarlyStopping",
"glob.glob",
"keras.optimizers.Adam",
"keras.callbacks.ReduceLROnPlateau",
"warnings.filterwarnings",
"yolo3.utils.... | [((356, 389), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (379, 389), False, 'import warnings\n'), ((996, 1032), 'glob.glob', 'glob.glob', (["(training_folder + '*.csv')"], {}), "(training_folder + '*.csv')\n", (1005, 1032), False, 'import glob\n'), ((2015, 2043), 'kera... |
"""
Main logic
Authors
-------
<NAME> <EMAIL>
"""
import argparse
import numpy as np
import pyvista as pv
import os
from .solver import SolverBuilder, NoPathFoundException, SolverType
from .plotting import SolutionPlotter
def main():
"""
main method
"""
parser = argparse.ArgumentParser(
prog=... | [
"os.path.isfile",
"numpy.array",
"pyvista.get_reader",
"argparse.ArgumentParser"
] | [((282, 471), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""visibilitygraphs"""', 'description': '"""\n Finds a possible path between two points for a fixed-wing aircraft in a given environment\n """'}), '(prog=\'visibilitygraphs\', description=\n """\n Finds a ... |
# This code is mostly from https://github.com/automl/pybnn
# pybnn authors: <NAME>, <NAME>
import numpy as np
from naslib.predictors.predictor import Predictor
from naslib.predictors.lce_m.learning_curves import MCMCCurveModelCombination
class LCEMPredictor(Predictor):
def __init__(self, metric=None):
s... | [
"numpy.mean",
"numpy.random.rand",
"numpy.array",
"numpy.isnan",
"numpy.isfinite",
"naslib.predictors.lce_m.learning_curves.MCMCCurveModelCombination",
"numpy.arange"
] | [((516, 548), 'numpy.arange', 'np.arange', (['(1)', '(trained_epochs + 1)'], {}), '(1, trained_epochs + 1)\n', (525, 548), True, 'import numpy as np\n'), ((925, 1146), 'naslib.predictors.lce_m.learning_curves.MCMCCurveModelCombination', 'MCMCCurveModelCombination', (['(final_epoch + 1)'], {'nwalkers': '(50)', 'nsamples... |
import argparse
import sys
import os
import shutil
import time
import numpy as np
from random import sample
from sklearn import metrics
import torch
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.tensorboard import SummaryWriter
from deepKNet.data import get_train_valid_test_loader
from deepKNet.mode... | [
"torch.optim.lr_scheduler.MultiStepLR",
"numpy.equal",
"sklearn.metrics.roc_auc_score",
"torch.cuda.is_available",
"sys.exit",
"os.path.exists",
"torch.utils.tensorboard.SummaryWriter",
"argparse.ArgumentParser",
"deepKNet.model3D.PointNet",
"numpy.float64",
"torch.set_num_threads",
"os.mkdir"... | [((350, 403), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""deepKNet model"""'}), "(description='deepKNet model')\n", (373, 403), False, 'import argparse\n'), ((1869, 1892), 'torch.get_num_threads', 'torch.get_num_threads', ([], {}), '()\n', (1890, 1892), False, 'import torch\n'), ((237... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of t... | [
"csv.DictWriter",
"utils.utils_squad.read_squad_examples",
"torch.cuda.device_count",
"yaml.load",
"utils.utils_squad_evaluate.main",
"torch.cuda.is_available",
"optimizer.hspg.HSPG",
"sys.path.append",
"utils.utils_squad_evaluate.EVAL_OPTS",
"os.path.exists",
"argparse.ArgumentParser",
"utils... | [((1726, 1753), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (1741, 1753), False, 'import os\n'), ((1755, 1781), 'sys.path.append', 'sys.path.append', (['parentdir'], {}), '(parentdir)\n', (1770, 1781), False, 'import sys\n'), ((1685, 1711), 'os.path.realpath', 'os.path.realpath', (['__... |
#imports everything need these packages will need to be installed using pip or pycharm.
import csv
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import tkinter as tk
from tkinter import filedialog
from scipy.optimize import curve_fit
root = tk.Tk()
canvas1 = tk.Canvas(root, width=400, height=... | [
"scipy.optimize.curve_fit",
"numpy.unique",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"matplotlib.pyplot.xlabel",
"tkinter.Button",
"tkinter.Canvas",
"numpy.array",
"tkinter.Tk",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"csv.reader",
"tkinter.filedialog.askopenfilename",
... | [((267, 274), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (272, 274), True, 'import tkinter as tk\n'), ((286, 361), 'tkinter.Canvas', 'tk.Canvas', (['root'], {'width': '(400)', 'height': '(400)', 'bg': '"""lemon chiffon"""', 'relief': '"""raised"""'}), "(root, width=400, height=400, bg='lemon chiffon', relief='raised')\n"... |
import tensorflow as tf
import numpy as np
var1 = tf.Variable(np.array([[1, 2, 3], [1, 2, 3]]), dtype=tf.float32)
# var1 = tf.Variable(np.array([1, 2, 3]), dtype=tf.float32)
sf = tf.nn.softmax(var1)
am = tf.argmax(var1, 1)
prob = tf.contrib.distributions.Categorical(probs=sf)
init = tf.global_variables_initializer()
... | [
"tensorflow.shape",
"tensorflow.Session",
"tensorflow.contrib.distributions.Categorical",
"tensorflow.global_variables_initializer",
"numpy.array",
"tensorflow.argmax",
"tensorflow.nn.softmax"
] | [((181, 200), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['var1'], {}), '(var1)\n', (194, 200), True, 'import tensorflow as tf\n'), ((206, 224), 'tensorflow.argmax', 'tf.argmax', (['var1', '(1)'], {}), '(var1, 1)\n', (215, 224), True, 'import tensorflow as tf\n'), ((232, 278), 'tensorflow.contrib.distributions.Categori... |
#!/usr/bin/env python3
# Copyright 2020 Mobvoi AI Lab, Beijing, China (author: <NAME>)
# Apache 2.0
import unittest
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
import shutil
from tempfile import mkdtemp
import numpy as np
import kaldi
class TestIOUtil(unittest.Te... | [
"kaldi.IntVectorWriter",
"numpy.testing.assert_array_equal",
"kaldi.VectorWriter",
"kaldi.read_mat",
"os.path.dirname",
"kaldi.MatrixWriter",
"tempfile.mkdtemp",
"shutil.rmtree",
"unittest.main",
"kaldi.read_vec_int",
"kaldi.read_vec_flt",
"numpy.arange"
] | [((3699, 3714), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3712, 3714), False, 'import unittest\n'), ((172, 197), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (187, 197), False, 'import os\n'), ((377, 386), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (384, 386), False, 'from ... |
import numpy as np
def DeterPoint(map, row, column):
for i in [row - 1, row, row + 1]:
for j in [column - 1, column, column + 1]:
if map[i][j] == -1:
return True
return False
def FBE(map, row, column, mark):
for i in [row - 1, row, row + 1]:
for j in [column -... | [
"numpy.random.randint"
] | [((524, 559), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)', '(800, 800)'], {}), '(0, 3, (800, 800))\n', (541, 559), True, 'import numpy as np\n')] |
from concurrent import futures
from unittest import mock
import grpc
import numpy as np
import pytest
from numproto import ndarray_to_proto, proto_to_ndarray
from xain.grpc import (
coordinator_pb2,
coordinator_pb2_grpc,
hellonumproto_pb2,
hellonumproto_pb2_grpc,
)
from xain.grpc.coordinator import Co... | [
"xain.grpc.coordinator.Coordinator",
"numproto.ndarray_to_proto",
"xain.grpc.coordinator_pb2.RendezvousRequest",
"concurrent.futures.ThreadPoolExecutor",
"grpc.insecure_channel",
"numproto.proto_to_ndarray",
"numpy.array_equal",
"xain.grpc.hellonumproto_pb2_grpc.NumProtoServerStub",
"unittest.mock.p... | [((1378, 1451), 'unittest.mock.patch', 'mock.patch', (['"""xain.grpc.coordinator.Coordinator.__init__"""'], {'new': 'mocked_init'}), "('xain.grpc.coordinator.Coordinator.__init__', new=mocked_init)\n", (1388, 1451), False, 'from unittest import mock\n'), ((437, 477), 'grpc.insecure_channel', 'grpc.insecure_channel', ([... |
# Copyright 2021 Huawei Technologies Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | [
"numpy.array",
"mindconverter.graph_based_converter.mapper.base.AtenToMindSporeMapper._generate_snippet_template",
"math.ceil"
] | [((2057, 2115), 'mindconverter.graph_based_converter.mapper.base.AtenToMindSporeMapper._generate_snippet_template', 'AtenToMindSporeMapper._generate_snippet_template', ([], {}), '(**kwargs)\n', (2105, 2115), False, 'from mindconverter.graph_based_converter.mapper.base import AtenToMindSporeMapper\n'), ((4304, 4332), 'm... |
"""
testing K-means clustering for image segmentation
"""
import cv2
import numpy as np
import h5py as h5
import matplotlib.pyplot as plt
import tensorflow as tf
import matplotlib.colors as colors
from sklearn.neighbors import kneighbors_graph
# get map
h5_file = '/Volumes/CHD_DB/map_data_small.h5'
hf = h5.File(h5_fil... | [
"matplotlib.pyplot.imshow",
"sklearn.cluster.KMeans",
"numpy.unique",
"numpy.logical_and",
"numpy.where",
"numpy.logical_not",
"h5py.File",
"sklearn.neighbors.kneighbors_graph",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.resize",
"numpy.zeros",
"numpy.squeeze",
"tensorflow.keras.pre... | [((306, 327), 'h5py.File', 'h5.File', (['h5_file', '"""r"""'], {}), "(h5_file, 'r')\n", (313, 327), True, 'import h5py as h5\n'), ((477, 492), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (485, 492), True, 'import numpy as np\n'), ((1157, 1178), 'numpy.where', 'np.where', (['(labels == 0)'], {}), '(labels =... |
"""
Generate features vectors for atoms and bonds
# Source
This code is adapted from:
- https://github.com/HIPS/neural-fingerprint/blob/2e8ef09/neuralfingerprint/features.py
- https://github.com/HIPS/neural-fingerprint/blob/2e8ef09/neuralfingerprint/util.py
- https://github.com/keiserlab/keras-neural-graph... | [
"numpy.ones",
"chemml.utils.padaxis",
"rdkit.Chem.MolFromSmiles",
"multiprocessing.cpu_count",
"numpy.array",
"rdkit.Chem.SanitizeMol",
"numpy.zeros",
"functools.partial",
"multiprocessing.Pool",
"numpy.concatenate"
] | [((3763, 3787), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['"""CC"""'], {}), "('CC')\n", (3781, 3787), False, 'from rdkit import Chem\n'), ((4097, 4121), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['"""CC"""'], {}), "('CC')\n", (4115, 4121), False, 'from rdkit import Chem\n'), ((4126, 4154), 'rdkit.Che... |
"""Quantities of a nuclear isotope, with decay and activation tools."""
import datetime
import copy
import numpy as np
import warnings
from .isotope import Isotope
from ..core import utils
from collections import OrderedDict
UCI_TO_BQ = 3.7e4
N_AV = 6.022141e23
class IsotopeQuantityError(Exception):
"""Raised b... | [
"collections.OrderedDict",
"datetime.timedelta",
"numpy.exp",
"datetime.datetime.now",
"copy.deepcopy",
"warnings.warn",
"numpy.log2"
] | [((5233, 5246), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (5244, 5246), False, 'from collections import OrderedDict\n'), ((11243, 11389), 'warnings.warn', 'warnings.warn', (['"""atoms_now() is deprecated and will be removed in a future release. Use atoms_at(date=None) instead."""', 'DeprecationWarning... |
#####################################################################
# #
# /labscript_devices/SpinnakerCamera/blacs_workers.py #
# #
# Copyright 2019, Monash University and ... | [
"PySpin.CValuePtr",
"PySpin.CIntegerPtr",
"time.sleep",
"PySpin.IsAvailable",
"PySpin.CFloatPtr",
"PySpin.IsReadable",
"PySpin.System.GetInstance",
"labscript_utils.dedent",
"numpy.frombuffer",
"PySpin.CBooleanPtr",
"PySpin.IsWritable",
"PySpin.CCategoryPtr"
] | [((1408, 1435), 'PySpin.System.GetInstance', 'PySpin.System.GetInstance', ([], {}), '()\n', (1433, 1435), False, 'import PySpin\n'), ((3708, 3732), 'PySpin.IsAvailable', 'PySpin.IsAvailable', (['node'], {}), '(node)\n', (3726, 3732), False, 'import PySpin\n'), ((3737, 3760), 'PySpin.IsReadable', 'PySpin.IsReadable', ([... |
from bs4 import BeautifulSoup
import requests
import numpy as np
import re
import pprint
import pandas as pd
headers = {
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/79.0.3945.117 '
'Safari/537.36'
}
session = r... | [
"requests.session",
"pandas.set_option",
"bs4.BeautifulSoup",
"numpy.sum",
"pandas.DataFrame",
"re.sub",
"re.findall"
] | [((319, 337), 'requests.session', 'requests.session', ([], {}), '()\n', (335, 337), False, 'import requests\n'), ((599, 638), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""lxml"""'], {}), "(response.content, 'lxml')\n", (612, 638), False, 'from bs4 import BeautifulSoup\n'), ((686, 717), 're.sub', 're.... |
"""
Functions useful in finance related applications
"""
import numpy as np
import pandas as pd
import datetime
import dateutil.relativedelta as relativedelta
def project_to_first(dt):
return datetime.datetime(dt.year, dt.month, 1)
def multiple_returns_from_levels_vec(df_in, period=1):
df_out = df = (df... | [
"datetime.datetime",
"numpy.array",
"dateutil.relativedelta.relativedelta",
"pandas.DataFrame"
] | [((201, 240), 'datetime.datetime', 'datetime.datetime', (['dt.year', 'dt.month', '(1)'], {}), '(dt.year, dt.month, 1)\n', (218, 240), False, 'import datetime\n'), ((2544, 2611), 'datetime.datetime', 'datetime.datetime', (['shift_start_date.year', 'shift_start_date.month', '(1)'], {}), '(shift_start_date.year, shift_sta... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | [
"qiskit.ClassicalRegister",
"numpy.array",
"qiskit.QuantumCircuit",
"qiskit.QuantumRegister",
"qiskit.circuit.Instruction"
] | [((1048, 1066), 'qiskit.QuantumRegister', 'QuantumRegister', (['(2)'], {}), '(2)\n', (1063, 1066), False, 'from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit\n'), ((1076, 1096), 'qiskit.ClassicalRegister', 'ClassicalRegister', (['(2)'], {}), '(2)\n', (1093, 1096), False, 'from qiskit import QuantumRe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.