code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 15:55:46 2019
@author: dweckler
"""
import numpy as np, matplotlib.pyplot as plt
from keras import backend as T
import time
import os
from .utilities import flat_avg
from dtmil.configuration.config_dtmil import get_json_config_data
from .predic... | [
"numpy.abs",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"os.path.join",
"matplotlib.pyplot.tight_layout",
"numpy.full",
"numpy.copy",
"numpy.std",
"numpy.transpose",
"os.path.exists",
"numpy.append",
"matplotlib.pyplot.subplots",
"dtmil.configuration.config_dtmil.get_json_co... | [((22688, 22699), 'time.time', 'time.time', ([], {}), '()\n', (22697, 22699), False, 'import time\n'), ((23198, 23244), 'os.path.join', 'os.path.join', (['model_output_directory', 'filename'], {}), '(model_output_directory, filename)\n', (23210, 23244), False, 'import os\n'), ((1321, 1371), 'numpy.arange', 'np.arange',... |
from decimal import Decimal
import unittest, sys
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from unittest.mock import patch
from forex_predictor.data_extraction.process_raw_data import create_relevant_data_row, create_row, find_start_date_index, get_dataframe_from_dates, get_dates, ... | [
"forex_predictor.data_extraction.process_raw_data.apply_category_label_binary",
"pandas.read_csv",
"forex_predictor.data_extraction.process_raw_data.get_dataframe_from_dates",
"forex_predictor.data_extraction.process_raw_data.set_const_intervals",
"sys.exc_info",
"forex_predictor.data_extraction.process_r... | [((2459, 2519), 'unittest.mock.patch', 'patch', (['"""forex_predictor.data_extraction.process_raw_data.pd"""'], {}), "('forex_predictor.data_extraction.process_raw_data.pd')\n", (2464, 2519), False, 'from unittest.mock import patch\n'), ((3954, 4046), 'unittest.mock.patch', 'patch', (['"""forex_predictor.data_extractio... |
#!/usr/bin/env python
import numpy as np
np.random.seed(42)
import emcee
def lnprior(params):
return 0.0
def lnlike(params, x, y):
model = params[0] * x + params[1]
residuals = y - model
return -np.sum(residuals ** 2)
def lnprob(params, x, y):
lnp = lnprior(params)
if np.isfinite(lnp):
... | [
"numpy.random.uniform",
"numpy.sum",
"numpy.random.seed",
"numpy.random.randn",
"numpy.isfinite",
"numpy.array",
"numpy.random.normal"
] | [((43, 61), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (57, 61), True, 'import numpy as np\n'), ((299, 315), 'numpy.isfinite', 'np.isfinite', (['lnp'], {}), '(lnp)\n', (310, 315), True, 'import numpy as np\n'), ((534, 570), 'numpy.random.normal', 'np.random.normal', (['(0)', '(3)', 'real_x.shape']... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# <NAME>, U.S. Geological Survey
# <NAME>, GNS Science
# <NAME>, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) ... | [
"numpy.dot",
"pyre.components.Component.Component.__init__"
] | [((1128, 1182), 'pyre.components.Component.Component.__init__', 'Component.__init__', (['self', 'name'], {'facility': '"""formulation"""'}), "(self, name, facility='formulation')\n", (1146, 1182), False, 'from pyre.components.Component import Component\n'), ((1485, 1540), 'numpy.dot', 'numpy.dot', (['K', '(integrator.f... |
import numpy as np
from pprint import pprint
def cal_eigenvalues_and_eigenvectors(A):
"""
:param A: n x n Hermitian matrix
:return:
"""
eigenvalues, normed_eigenvectors = np.linalg.eig(A)
# Below two steps are redounding for readability
lmd = eigenvalues
v = normed_eigenvectors
re... | [
"numpy.abs",
"numpy.linalg.eig",
"numpy.random.randint",
"pprint.pprint",
"numpy.random.rand",
"numpy.linalg.det",
"numpy.delete"
] | [((194, 210), 'numpy.linalg.eig', 'np.linalg.eig', (['A'], {}), '(A)\n', (207, 210), True, 'import numpy as np\n'), ((369, 385), 'numpy.linalg.det', 'np.linalg.det', (['M'], {}), '(M)\n', (382, 385), True, 'import numpy as np\n'), ((590, 623), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(3)', 'high': '(1... |
# yellowbrick.utils.helpers
# Helper functions and generic utilities for use in Yellowbrick code.
#
# Author: <NAME> <<EMAIL>>
# Created: Fri May 19 10:39:30 2017 -0700
#
# Copyright (C) 2017 District Data Labs
# For license information, see LICENSE.txt
#
# ID: helpers.py [79cd8cf] <EMAIL> $
"""
Helper functions an... | [
"numpy.true_divide",
"numpy.isscalar",
"numpy.asarray",
"numpy.isfinite",
"numpy.errstate",
"numpy.arange",
"re.sub",
"numpy.all",
"numpy.in1d"
] | [((1986, 2005), 'numpy.arange', 'np.arange', (['(0)', 'ncols'], {}), '(0, ncols)\n', (1995, 2005), True, 'import numpy as np\n'), ((2589, 2602), 'numpy.asarray', 'np.asarray', (['a'], {}), '(a)\n', (2599, 2602), True, 'import numpy as np\n'), ((2838, 2869), 'numpy.all', 'np.all', (['(a[1:] <= a[:-1])'], {'axis': '(0)'}... |
# Copyright (c) 2016, MD2K Center of Excellence
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | [
"cerebralcortex.data_processor.signalprocessing.rip.correct_valley_position",
"cerebralcortex.data_processor.signalprocessing.rip.filter_intercept_outlier",
"cerebralcortex.data_processor.signalprocessing.rip.remove_close_valley_peak_pair",
"cerebralcortex.data_processor.signalprocessing.rip.filter_small_amp_... | [((28847, 28862), 'unittest.main', 'unittest.main', ([], {}), '()\n', (28860, 28862), False, 'import unittest\n'), ((2307, 2334), 'pytz.timezone', 'pytz.timezone', (['"""US/Eastern"""'], {}), "('US/Eastern')\n", (2320, 2334), False, 'import pytz\n'), ((3283, 3305), 'cerebralcortex.kernel.datatypes.datastream.DataStream... |
# evaluate a decision tree on the entire small dataset
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.tree import DecisionTreeClassifier
# define da... | [
"numpy.std",
"sklearn.model_selection.cross_val_score",
"sklearn.model_selection.RepeatedStratifiedKFold",
"sklearn.datasets.make_classification",
"sklearn.tree.DecisionTreeClassifier",
"numpy.mean"
] | [((333, 434), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(1000)', 'n_features': '(3)', 'n_informative': '(2)', 'n_redundant': '(1)', 'random_state': '(1)'}), '(n_samples=1000, n_features=3, n_informative=2,\n n_redundant=1, random_state=1)\n', (352, 434), False, 'from sklearn.... |
import os
import tensorflow as tf
import os
from PIL import Image
import numpy as np
import cv2
from preprocessing import preprocessing_factory
from google.protobuf import text_format
def main(_):
labels = []
'''
# Let's read our pbtxt file into a Graph protobuf
f = open("C:/Users/turnt/OneDrive/Des... | [
"numpy.argmax",
"tensorflow.Session",
"PIL.Image.open",
"preprocessing.preprocessing_factory.get_preprocessing",
"numpy.round",
"tensorflow.import_graph_def",
"tensorflow.compat.v1.GraphDef",
"tensorflow.app.run",
"tensorflow.io.gfile.GFile"
] | [((707, 730), 'tensorflow.compat.v1.GraphDef', 'tf.compat.v1.GraphDef', ([], {}), '()\n', (728, 730), True, 'import tensorflow as tf\n'), ((1159, 1268), 'PIL.Image.open', 'Image.open', (['"""C:/Users/turnt/OneDrive/Desktop/Rob0Workspace/Scene_labeler/input_images/test/001.jpg"""'], {}), "(\n 'C:/Users/turnt/OneDrive... |
import numpy as np
import pyqtgraph as pg
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtWidgets import QFrame, QWidget, QLabel, QGridLayout, QGroupBox, QDoubleSpinBox, QPushButton,\
QTabWidget, QComboBox, QRadioButton, QHBoxLayout, QVBoxLayout, QTreeWidget, QTreeWidgetItem
from EG... | [
"EGGS_labrad.clients.Widgets.QCustomGroupBox",
"PyQt5.QtGui.QColor",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtWidgets.QTabWidget",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QRadioButton",
"numpy.power",
"PyQ... | [((15426, 15447), 'EGGS_labrad.clients.runGUI', 'runGUI', (['stability_gui'], {}), '(stability_gui)\n', (15432, 15447), False, 'from EGGS_labrad.clients import runGUI\n'), ((533, 563), 'PyQt5.QtWidgets.QWidget.__init__', 'QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (549, 563), False, 'from PyQt5.Qt... |
#
# styleopt.py
# Artistic Style Transfer
# Optimisation method
# as defined in Gatys et. al
#
import os
import api
import numpy as np
import tensorflow as tf
import keras.backend as K
import matplotlib.pyplot as plt
import stylefn
from PIL import Image
from keras.models import Model, Sequential
from util import app... | [
"tensorflow.clip_by_value",
"matplotlib.pyplot.clf",
"keras.backend.placeholder",
"matplotlib.pyplot.draw",
"stylefn.build_loss",
"datetime.datetime.now",
"matplotlib.pyplot.pause",
"tensorflow.summary.merge_all",
"keras.backend.clear_session",
"tensorflow.contrib.opt.ScipyOptimizerInterface",
"... | [((3469, 3524), 'stylefn.deprocess_image', 'stylefn.deprocess_image', (['pastiche', 'graph.pastiche_shape'], {}), '(pastiche, graph.pastiche_shape)\n', (3492, 3524), False, 'import stylefn\n'), ((3607, 3617), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (3615, 3617), True, 'import matplotlib.pyplot as plt\n'... |
# A simple python script to plot the GW
# signals over time, for a chosen mode
import numpy as np;
import matplotlib.pyplot as plt;
# output data for setup
M = 1.0
mu = 0.05
r = 300
symmetry = 4
# make the plot
fig = plt.figure()
# volume integral dataset out
data1 = np.loadtxt("VolumeIntegrals.dat")
timedata = data... | [
"numpy.zeros_like",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig"
] | [((219, 231), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (229, 231), True, 'import matplotlib.pyplot as plt\n'), ((271, 304), 'numpy.loadtxt', 'np.loadtxt', (['"""VolumeIntegrals.dat"""'], {}), "('VolumeIntegrals.dat')\n", (281, 304), True, 'import numpy as np\n'), ((431, 465), 'numpy.loadtxt', 'np.loa... |
import os
import matplotlib.pyplot as plt
import numpy as np
import json
import seaborn as sns;
from collections import deque
sns.set()
import glob2
import argparse
from cycler import cycler
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.font_manager import Fon... | [
"numpy.nanpercentile",
"argparse.ArgumentParser",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.gca",
"os.path.join",
"numpy.std",
"os.path.exists",
"numpy.genfromtxt",
"seaborn.set",
"numpy.median",
"matplotlib.pyplot.legend",
"numpy.argwhere",
"j... | [((126, 135), 'seaborn.set', 'sns.set', ([], {}), '()\n', (133, 135), True, 'import seaborn as sns\n'), ((2994, 3003), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3001, 3003), True, 'import matplotlib.pyplot as plt\n'), ((3048, 3076), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4.5)'}), '... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | [
"sklearn.preprocessing.label._encode_check_unknown",
"math.ceil",
"numpy.asarray",
"numpy.setdiff1d",
"sklearn.preprocessing.label._encode",
"sklearn.utils.validation._num_samples",
"sklearn.utils.validation.check_is_fitted",
"numpy.searchsorted",
"sklearn.utils.validation.column_or_1d",
"sagemake... | [((10817, 10843), 'sklearn.utils.validation.column_or_1d', 'column_or_1d', (['y'], {'warn': '(True)'}), '(y, warn=True)\n', (10829, 10843), False, 'from sklearn.utils.validation import check_is_fitted, column_or_1d, _num_samples\n'), ((11103, 11182), 'warnings.warn', 'warnings.warn', (['"""`labels` parameter is expecte... |
import netCDF4
import numpy
import vtk
from reader_base import ReaderBase
class LatLonReader(ReaderBase):
def __init__(self, filename, padding=0):
"""
Constructor
@param filename UM netCDF file
@param padding number of extra cells to add on the high end of longitudes
@note... | [
"netCDF4.Dataset",
"numpy.zeros",
"argparse.ArgumentParser",
"vtk.vtkIdList"
] | [((3437, 3491), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Read ugrid file"""'}), "(description='Read ugrid file')\n", (3460, 3491), False, 'import argparse\n'), ((475, 505), 'netCDF4.Dataset', 'netCDF4.Dataset', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (490, 505), False, ... |
import os, glob, tempfile, warnings
import numpy as np
from traitlets import (HasTraits,
Integer,
Unicode,
Float,
Integer,
Instance,
Dict,
Bool,
... | [
"rpy2.robjects.numpy2ri.activate",
"traitlets.Float",
"tempfile.mkstemp",
"rpy2.robjects.r",
"traitlets.Unicode",
"numpy.nonzero",
"rpy2.robjects.r.assign",
"numpy.linalg.inv",
"rpy2.robjects.numpy2ri.deactivate",
"warnings.warn"
] | [((433, 476), 'rpy2.robjects.r', 'rpy.r', (['"""library(knockoff); library(glmnet)"""'], {}), "('library(knockoff); library(glmnet)')\n", (438, 476), True, 'import rpy2.robjects as rpy\n'), ((799, 809), 'traitlets.Float', 'Float', (['(0.2)'], {}), '(0.2)\n', (804, 809), False, 'from traitlets import HasTraits, Integer,... |
import numpy as np
import warnings
from copy import deepcopy
from scipy.signal import fftconvolve, medfilt
import astropy.units as u
import astropy.constants as cst
from astropy.io import fits, registry
from astropy.wcs import WCS
from astropy.nddata import NDDataArray, StdDevUncertainty, InverseVariance
from astropy... | [
"numpy.abs",
"numpy.angle",
"astropy.io.fits.PrimaryHDU",
"numpy.ones",
"numpy.isnan",
"astropy.io.fits.Header",
"numpy.arange",
"scipy.signal.fftconvolve",
"astropy.io.fits.HDUList",
"astropy.io.fits.ImageHDU",
"numpy.fft.ifftshift",
"astropy.io.registry.register_writer",
"numpy.fft.irfft",... | [((1238, 1253), 'numpy.arange', 'np.arange', (['(0)', 'M'], {}), '(0, M)\n', (1247, 1253), True, 'import numpy as np\n'), ((30442, 30477), 'astropy.io.registry.delay_doc_updates', 'registry.delay_doc_updates', (['FTSData'], {}), '(FTSData)\n', (30468, 30477), False, 'from astropy.io import fits, registry\n'), ((30555, ... |
import matrices_new_extended as mne
import numpy as np
import sympy as sp
from equality_check import Point
x, y, z = sp.symbols("x y z")
Point.base_point = np.array([x, y, z, 1])
class Test_Axis_3_xxx:
def test_matrix_3_xxx(self):
expected = Point([ z, x, y, 1])
calculated = Point.calculate(mne.... | [
"sympy.symbols",
"numpy.array",
"equality_check.Point.calculate",
"equality_check.Point"
] | [((118, 137), 'sympy.symbols', 'sp.symbols', (['"""x y z"""'], {}), "('x y z')\n", (128, 137), True, 'import sympy as sp\n'), ((157, 179), 'numpy.array', 'np.array', (['[x, y, z, 1]'], {}), '([x, y, z, 1])\n', (165, 179), True, 'import numpy as np\n'), ((258, 277), 'equality_check.Point', 'Point', (['[z, x, y, 1]'], {}... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division # Eliminate need for decimals on whole values
import sys
# As of 28 July 2019, python3.6 is the default "python3" in apt-get install python3
if sys.version_info[0] != 3 or sys.version_info[1] < 6:
print("This ... | [
"argparse.ArgumentParser",
"os.path.join",
"numpy.multiply",
"skyfield.iokit.Loader",
"os.path.dirname",
"tle_util.append_tle_file",
"math.cos",
"configparser.ConfigParser",
"logging.StreamHandler",
"numpy.cross",
"math.sin",
"inspect.currentframe",
"numpy.dot",
"math.degrees",
"sys.exit... | [((950, 986), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../python-sgp4"""'], {}), "(1, '../python-sgp4')\n", (965, 986), False, 'import sys\n'), ((1047, 1117), 'sys.path.insert', 'sys.path.insert', (['(2)', '"""/Users/chris/Dropbox/code/preMVP/python-skyfield"""'], {}), "(2, '/Users/chris/Dropbox/code/preMVP/p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#https://github.com/juano2310/CarND-Behavioral-Cloning-P3-Juan/blob/master/model.py
#https://github.com/udacity/self-driving-car/blob/master/steering-models/community-models/rambo/train.py
import os
import csv
import cv2
import numpy as np
import matplotlib.pyplot as plt
i... | [
"matplotlib.pyplot.title",
"csv.reader",
"keras.layers.Cropping2D",
"sklearn.model_selection.train_test_split",
"keras.layers.core.Flatten",
"keras.layers.core.SpatialDropout2D",
"os.path.normpath",
"keras.layers.core.Dropout",
"cv2.resize",
"keras.layers.core.Dense",
"keras.callbacks.ModelCheck... | [((952, 982), 'sklearn.utils.shuffle', 'sklearn.utils.shuffle', (['samples'], {}), '(samples)\n', (973, 982), False, 'import sklearn\n'), ((1019, 1059), 'sklearn.model_selection.train_test_split', 'train_test_split', (['samples'], {'test_size': '(0.2)'}), '(samples, test_size=0.2)\n', (1035, 1059), False, 'from sklearn... |
"""Symbolic model code generation.
Improvement ideas
-----------------
* Add compiled code to linecache so that tracebacks can be produced, like done
in the `IPython.core.compilerop` module.
"""
import abc
import collections
import collections.abc
import contextlib
import functools
import inspect
import itertools... | [
"jinja2.Template",
"functools.partial",
"numpy.asarray",
"inspect.signature",
"functools.wraps",
"attrdict.AttrDict"
] | [((7770, 7790), 'inspect.signature', 'inspect.signature', (['f'], {}), '(f)\n', (7787, 7790), False, 'import inspect\n'), ((8156, 8174), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (8171, 8174), False, 'import functools\n'), ((5161, 5196), 'jinja2.Template', 'jinja2.Template', (['model_template_src'], {... |
#!/usr/bin/env python3
# coding: utf-8
"""
@author: <NAME> <EMAIL>
@last modified by: <NAME>
@file:qc.py
@time:2021/03/26
"""
from scipy.sparse import issparse
import numpy as np
def cal_qc(data):
"""
calculate three qc index including the number of genes expressed in the count matrix, the total counts per c... | [
"scipy.sparse.issparse",
"numpy.char.lower",
"numpy.count_nonzero"
] | [((1770, 1790), 'scipy.sparse.issparse', 'issparse', (['exp_matrix'], {}), '(exp_matrix)\n', (1778, 1790), False, 'from scipy.sparse import issparse\n'), ((1796, 1832), 'numpy.count_nonzero', 'np.count_nonzero', (['exp_matrix'], {'axis': '(0)'}), '(exp_matrix, axis=0)\n', (1812, 1832), True, 'import numpy as np\n'), ((... |
import pandas as pd
import numpy as np
def load_cancer():
# data, target, feature_names
result_dict = {'features': np.array(["Clump Thickness",
"Uniformity of Cell Size",
"Uniformity of Cell Shape",
... | [
"pandas.read_csv",
"numpy.array"
] | [((754, 779), 'numpy.array', 'np.array', (["df_dict['data']"], {}), "(df_dict['data'])\n", (762, 779), True, 'import numpy as np\n'), ((2022, 2047), 'numpy.array', 'np.array', (["df_dict['data']"], {}), "(df_dict['data'])\n", (2030, 2047), True, 'import numpy as np\n'), ((125, 337), 'numpy.array', 'np.array', (["['Clum... |
# Copyright 2021 Google 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 writing, ... | [
"pyreach.mock.calibration_mock.CalibrationMock",
"numpy.zeros"
] | [((4429, 4464), 'numpy.zeros', 'np.zeros', (['(3, 5, 3)'], {'dtype': 'np.uint8'}), '((3, 5, 3), dtype=np.uint8)\n', (4437, 4464), True, 'import numpy as np\n'), ((4529, 4614), 'pyreach.mock.calibration_mock.CalibrationMock', 'cal_mock.CalibrationMock', (['"""device_type"""', '"""device_name"""', '"""color_camera_link_n... |
import numpy as np
from scipy.fftpack import rfft, irfft, rfftfreq
from ....routines import rescale
def fourier_filter(data: np.ndarray, fs: float,
lp_freq: float = None, hp_freq: float = None, bs_freqs: list = [],
trans_width: float = 1, band_width: float = 1) -> np.ndarray:
... | [
"scipy.fftpack.rfftfreq",
"scipy.fftpack.rfft",
"numpy.ones_like",
"numpy.apply_along_axis",
"numpy.exp",
"scipy.fftpack.irfft"
] | [((1143, 1157), 'scipy.fftpack.rfftfreq', 'rfftfreq', (['T', 'd'], {}), '(T, d)\n', (1151, 1157), False, 'from scipy.fftpack import rfft, irfft, rfftfreq\n'), ((1171, 1190), 'scipy.fftpack.rfft', 'rfft', (['data'], {'axis': '(-1)'}), '(data, axis=-1)\n', (1175, 1190), False, 'from scipy.fftpack import rfft, irfft, rfft... |
import numpy as np
import unittest
from numpy.testing import assert_array_less
from GPyOpt.core.errors import InvalidConfigError
from GPyOpt.core.task.space import Design_space
from GPyOpt.experiment_design import initial_design
class TestInitialDesign(unittest.TestCase):
def setUp(self):
self.space = [
... | [
"GPyOpt.core.task.space.Design_space",
"numpy.array",
"GPyOpt.experiment_design.initial_design",
"numpy.in1d"
] | [((592, 616), 'GPyOpt.core.task.space.Design_space', 'Design_space', (['self.space'], {}), '(self.space)\n', (604, 616), False, 'from GPyOpt.core.task.space import Design_space\n'), ((1451, 1511), 'GPyOpt.experiment_design.initial_design', 'initial_design', (['"""grid"""', 'self.design_space', 'init_points_count'], {})... |
import time
import argparse
import numpy as np
import json
import os
import sys
# from matplotlib import pyplot
from torch.utils.data import DataLoader
from preprocessing import Constants
from util import construct_data_from_json
from dgl_treelstm.KNN import KNN
from dgl_treelstm.nn_models import *
from dgl_treelstm... | [
"argparse.ArgumentParser",
"sklearn.metrics.accuracy_score",
"json.dumps",
"sklearn.metrics.f1_score",
"numpy.mean",
"preprocessing.Tree_Dataset.Tree_Dataset",
"preprocessing.Vector_Dataset.Vector_Dataset",
"os.path.exists",
"train.batcher",
"util.construct_data_from_json",
"preprocessing.Vocab"... | [((858, 891), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (881, 891), False, 'import warnings\n'), ((14925, 14946), 'os.path.exists', 'os.path.exists', (['input'], {}), '(input)\n', (14939, 14946), False, 'import os\n'), ((20244, 20289), 'sklearn.metrics.accuracy_score'... |
import numpy as np
import pandas as pd
students = 250
nr_to_label = {0: 'bike', 1: 'car', 2: 'bus 40', 3: 'bus 240'}
label_to_nr = {v: k for k, v in nr_to_label.items()}
def choice(income, distance, lazy):
"""
Generate a choice based on the params
"""
if income < 500:
if distance < 8 and dist... | [
"pandas.DataFrame",
"numpy.random.randint",
"numpy.random.random",
"numpy.random.poisson",
"numpy.random.normal"
] | [((1058, 1100), 'numpy.random.randint', 'np.random.randint', (['(0)', '(4)'], {'size': 'replace.size'}), '(0, 4, size=replace.size)\n', (1075, 1100), True, 'import numpy as np\n'), ((1122, 1193), 'pandas.DataFrame', 'pd.DataFrame', (['idct'], {'columns': "['income', 'distance', 'lazy', 'transport']"}), "(idct, columns=... |
# test function gradient
def limetr_gradient():
import numpy as np
from limetr.__init__ import LimeTr
ok = True
# setup test problem
# -------------------------------------------------------------------------
model = LimeTr.testProblem(use_trimming=True,
use_con... | [
"limetr.__init__.LimeTr.testProblem",
"numpy.linalg.norm",
"numpy.random.randn"
] | [((244, 408), 'limetr.__init__.LimeTr.testProblem', 'LimeTr.testProblem', ([], {'use_trimming': '(True)', 'use_constraints': '(True)', 'use_regularizer': '(True)', 'use_uprior': '(True)', 'use_gprior': '(True)', 'know_obs_std': '(False)', 'share_obs_std': '(True)'}), '(use_trimming=True, use_constraints=True, use_regul... |
from common.vec_env.vec_logger import VecLogger
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
GAMMA = 0.99
TAU = 1.00
N_STEPS = 5
CLIP_GRAD = 50
COEF_VALUE = 0.5
COEF_ENTROPY = 0.01
def train(args, venv, model, path, device):
N = args.num_pr... | [
"numpy.expand_dims",
"torch.nn.functional.softmax",
"common.vec_env.vec_logger.VecLogger",
"torch.nn.functional.log_softmax",
"torch.zeros",
"torch.from_numpy"
] | [((521, 546), 'common.vec_env.vec_logger.VecLogger', 'VecLogger', ([], {'N': 'N', 'path': 'path'}), '(N=N, path=path)\n', (530, 546), False, 'from common.vec_env.vec_logger import VecLogger\n'), ((666, 685), 'torch.zeros', 'torch.zeros', (['N', '(512)'], {}), '(N, 512)\n', (677, 685), False, 'import torch\n'), ((706, 7... |
"""Training and testing the Pairwise Differentiable Gradient Descent (PDGD) algorithm for unbiased learning to rank.
See the following paper for more information on the Pairwise Differentiable Gradient Descent (PDGD) algorithm.
* Oosterhuis, Harrie, and <NAME>. "Differentiable unbiased online learning to rank." I... | [
"tensorflow.trainable_variables",
"numpy.isnan",
"ultra.utils.hparams.HParams",
"six.moves.zip",
"tensorflow.global_variables",
"tensorflow.Variable",
"numpy.exp",
"tensorflow.clip_by_global_norm",
"numpy.zeros_like",
"numpy.copy",
"tensorflow.placeholder",
"numpy.cumsum",
"tensorflow.exp",
... | [((1873, 1991), 'ultra.utils.hparams.HParams', 'ultra.utils.hparams.HParams', ([], {'learning_rate': '(0.05)', 'tau': '(1)', 'max_gradient_norm': '(1.0)', 'l2_loss': '(0.005)', 'grad_strategy': '"""ada"""'}), "(learning_rate=0.05, tau=1, max_gradient_norm=\n 1.0, l2_loss=0.005, grad_strategy='ada')\n", (1900, 1991),... |
"""
# 3D high-res brain mesh
Showing a ultra-high resolution mesh of a human brain, acquired with a 7 Tesla MRI.
The data is not yet publicly available.
Data courtesy of <NAME> et al.:
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> (2020)
... | [
"numpy.load",
"datoviz.canvas",
"datoviz.run",
"pathlib.Path",
"numpy.array"
] | [((628, 673), 'datoviz.canvas', 'canvas', ([], {'show_fps': '(True)', 'width': '(1024)', 'height': '(768)'}), '(show_fps=True, width=1024, height=768)\n', (634, 673), False, 'from datoviz import canvas, run, colormap\n'), ((817, 867), 'numpy.load', 'np.load', (["(ROOT / 'data/mesh/brain_highres.vert.npy')"], {}), "(ROO... |
import math
from typing import List, Union, Sequence
from pyrep.backend import sim
from pyrep.objects.object import Object, object_type_to_class
import numpy as np
from pyrep.const import ObjectType, PerspectiveMode, RenderMode
class VisionSensor(Object):
"""A camera-type sensor, reacting to light, colors and ima... | [
"pyrep.const.PerspectiveMode",
"pyrep.backend.sim.simGetVisionSensorResolution",
"numpy.ones",
"numpy.arange",
"pyrep.backend.sim.simGetObjectFloatParameter",
"math.radians",
"numpy.transpose",
"numpy.tan",
"numpy.reshape",
"numpy.ones_like",
"pyrep.backend.sim.simSetObjectInt32Parameter",
"py... | [((14652, 14691), 'numpy.transpose', 'np.transpose', (['pixel_y_coords', '(1, 0, 2)'], {}), '(pixel_y_coords, (1, 0, 2))\n', (14664, 14691), True, 'import numpy as np\n'), ((14917, 14948), 'numpy.reshape', 'np.reshape', (['coords', '(h * w, -1)'], {}), '(coords, (h * w, -1))\n', (14927, 14948), True, 'import numpy as n... |
import os
import numpy as np
import re
import sys
try:
import h5py
except ImportError:
h5py = None
'''
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
'''
from .. import logger, logging
from .base import MFPackage, MissingFile
from .name import Modflow
... | [
"h5py.File",
"numpy.empty",
"os.path.dirname",
"numpy.dtype",
"os.path.isfile",
"re.findall",
"numpy.fromiter",
"os.path.split",
"os.path.join",
"numpy.fromstring",
"re.compile"
] | [((333, 449), 're.compile', 're.compile', (['"""\\\\((?P<body>(?P<rep>\\\\d*)(?P<symbol>[IEFG][SN]?)(?P<w>\\\\d+)(\\\\.(?P<d>\\\\d+))?|FREE|BINARY)\\\\)"""'], {}), "(\n '\\\\((?P<body>(?P<rep>\\\\d*)(?P<symbol>[IEFG][SN]?)(?P<w>\\\\d+)(\\\\.(?P<d>\\\\d+))?|FREE|BINARY)\\\\)'\n )\n", (343, 449), False, 'import re\... |
import numpy as np
import scipy
import scipy.stats
import csv
scores = np.load('regional_avgScore_nAD.npy')
print(scores.shape)
pool = [[0 for _ in range(scores.shape[1])] for _ in range(scores.shape[1])]
for i in range(scores.shape[1]-1):
for j in range(i+1, scores.shape[1]):
corr, _ = scipy.stats.pears... | [
"numpy.load",
"csv.writer",
"scipy.stats.pearsonr"
] | [((72, 108), 'numpy.load', 'np.load', (['"""regional_avgScore_nAD.npy"""'], {}), "('regional_avgScore_nAD.npy')\n", (79, 108), True, 'import numpy as np\n'), ((679, 755), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""" """', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=' '... |
import os
import argparse
import numpy as np
import pymatgen
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("mp_dir", help="Root directory with Materials Project dataset")
parser.add_argument("radial_cutoff", type=float, help="Radius of sphere that decides neighborhood")
args = parser.pa... | [
"tqdm.tqdm",
"argparse.ArgumentParser",
"pymatgen.Structure.from_file",
"numpy.array",
"os.path.join"
] | [((93, 118), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (116, 118), False, 'import argparse\n'), ((479, 506), 'os.path.join', 'os.path.join', (['mp_dir', '"""cif"""'], {}), "(mp_dir, 'cif')\n", (491, 506), False, 'import os\n'), ((521, 575), 'os.path.join', 'os.path.join', (['mp_dir', 'f"""... |
"""
Copyright (c) 2018, University of Oxford, Rama Cont and ETH Zurich, <NAME>
This module provides the helper functions and the class LOBSTERReader, a subclass of OBReader to read in limit order book data in lobster format.
"""
######
# Imports
######
import csv
import math
import warnings
import numpy as np
fr... | [
"csv.reader",
"csv.writer",
"numpy.empty",
"numpy.zeros",
"numpy.array",
"numpy.linspace",
"numpy.fromiter",
"warnings.warn"
] | [((6227, 6256), 'numpy.zeros', 'np.zeros', (['(num_levels_calc * 2)'], {}), '(num_levels_calc * 2)\n', (6235, 6256), True, 'import numpy as np\n'), ((6314, 6343), 'numpy.zeros', 'np.zeros', (['(num_levels_calc * 2)'], {}), '(num_levels_calc * 2)\n', (6322, 6343), True, 'import numpy as np\n'), ((9228, 9257), 'numpy.zer... |
from .array import TensorTrainArray
from .slice import TensorTrainSlice
from .dispatch import implement_function
from ..raw import find_balanced_cluster,trivial_decomposition
import numpy as np
def _get_cluster_chi_array(shape,cluster,chi):
if cluster is None:
cluster=find_balanced_cluster(shape)
if isi... | [
"numpy.frombuffer",
"numpy.ones",
"numpy.array",
"numpy.arange",
"numpy.fromiter",
"numpy.fromfunction",
"numpy.issubdtype"
] | [((3271, 3300), 'numpy.ones', 'np.ones', (['m.shape[1:-1]', 'dtype'], {}), '(m.shape[1:-1], dtype)\n', (3278, 3300), True, 'import numpy as np\n'), ((3633, 3660), 'numpy.ones', 'np.ones', (['ms[0].shape', 'dtype'], {}), '(ms[0].shape, dtype)\n', (3640, 3660), True, 'import numpy as np\n'), ((3691, 3723), 'numpy.ones', ... |
import os, csv
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.model_selection import train_test_split
from scipy import signal
class ProcessSignalData(object):
def __init__(self):
# path to video data from signal_output.py
self.dir = './processed_new/videos'
s... | [
"pandas.DataFrame",
"numpy.abs",
"scipy.signal.welch",
"numpy.argmax",
"numpy.std",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"os.walk",
"numpy.asarray",
"numpy.array",
"os.path.join",
"scipy.signal.csd",
"numpy.concatenate"
] | [((364, 378), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (376, 378), True, 'import pandas as pd\n'), ((404, 418), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (416, 418), True, 'import pandas as pd\n'), ((444, 458), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (456, 458), True, 'import pand... |
import cv2
import numpy as np
from utils.test_images_generator.generator_config import AVAILABLE_SHAPES_DICT
from utils.test_images_generator.generator_utils import generate_random_color, generate_random_image_points
def generate_random_image(width, height):
# ToDo generate white image
# https://numpy.org/do... | [
"numpy.zeros"
] | [((385, 429), 'numpy.zeros', 'np.zeros', (['(height, width, 3)'], {'dtype': 'np.uint8'}), '((height, width, 3), dtype=np.uint8)\n', (393, 429), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 19 11:30:56 2022
@author: adowa
"""
import numpy as np
import tensorflow as tf
from utils import (build_logistic_regression,
compile_logistic_regression)
from tensorflow.keras import regularizers
from sklearn.datasets import make_... | [
"tensorflow.random.set_seed",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.backend.clear_session",
"sklearn.datasets.make_classification",
"tensorflow.keras.regularizers.L1",
"numpy.hstack",
"sklearn.metrics.roc_auc_score",
"tensorflow.keras.regularizers.L2",
"numpy.concatenate",
... | [((557, 589), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (587, 589), True, 'import tensorflow as tf\n'), ((632, 823), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(150)', 'n_features': '(100)', 'n_informative': '(3)', 'n_redundant'... |
import scipy
import scipy.sparse.csgraph
import wall_generation, mesh
import mesh_operations
import utils
import triangulation, filters
from mesh_utilities import SurfaceSampler, tubeRemesh
import numpy as np
def meshComponents(m, cutEdges):
"""
Get the connected components of triangles of a mesh cut along the... | [
"mesh_utilities.tubeRemesh",
"numpy.empty",
"utils.freshPath",
"numpy.arange",
"scipy.sparse.csgraph.connected_components",
"numpy.linalg.norm",
"numpy.unique",
"numpy.pad",
"utils.bbox_dims",
"field_sampler.FieldSampler",
"numpy.transpose",
"mesh.Mesh",
"mesh_utilities.SurfaceSampler",
"n... | [((1304, 1350), 'scipy.sparse.csgraph.connected_components', 'scipy.sparse.csgraph.connected_components', (['adj'], {}), '(adj)\n', (1345, 1350), False, 'import scipy\n'), ((1983, 2029), 'scipy.sparse.csgraph.connected_components', 'scipy.sparse.csgraph.connected_components', (['adj'], {}), '(adj)\n', (2024, 2029), Fal... |
import numpy as np
from sklearn import linear_model
np.random.seed(123)
np.set_printoptions(suppress=True, linewidth=120)
X = np.random.random([10, 5]).astype(np.float)
y = np.random.random(10).astype(np.float)
# sklearn
linear = linear_model.LinearRegression()
linear.fit(X, y)
# Pure Python
X = np.hstack([np.ones(... | [
"numpy.set_printoptions",
"numpy.random.seed",
"numpy.ones",
"sklearn.linear_model.LinearRegression",
"numpy.random.random",
"numpy.matmul"
] | [((53, 72), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (67, 72), True, 'import numpy as np\n'), ((73, 122), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)', 'linewidth': '(120)'}), '(suppress=True, linewidth=120)\n', (92, 122), True, 'import numpy as np\n'), ((233, 26... |
import numpy as np
import ray
import pyspiel
from open_spiel.python.algorithms.psro_v2.ars_ray.shared_noise import *
from open_spiel.python.algorithms.psro_v2.ars_ray.utils import rewards_combinator
from open_spiel.python.algorithms.psro_v2 import rl_policy
from open_spiel.python import rl_environment
import tens... | [
"pyspiel.GameParameter",
"open_spiel.python.algorithms.psro_v2.ars_ray.utils.rewards_combinator",
"numpy.cumsum",
"tensorflow.compat.v1.Session",
"random.random",
"numpy.array",
"open_spiel.python.rl_environment.Environment",
"tensorflow.compat.v1.get_default_session"
] | [((1739, 1771), 'open_spiel.python.rl_environment.Environment', 'rl_environment.Environment', (['game'], {}), '(game)\n', (1765, 1771), False, 'from open_spiel.python import rl_environment\n'), ((2240, 2264), 'tensorflow.compat.v1.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (2262, 2264), True, 'im... |
# credit card default dataset: https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients
# kaggle link: https://www.kaggle.com/uciml/default-of-credit-card-clients-dataset
import pandas as pd
from fim import fpgrowth#,fim
import numpy as np
#import math
#from itertools import chain, combinations
import it... | [
"numpy.sum",
"random.sample",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"numpy.argsort",
"numpy.mean",
"numpy.exp",
"numpy.multiply",
"fim.fpgrowth",
"numpy.insert",
"numpy.logical_xor",
"pandas.concat",
"sklearn.ensemble.RandomForestClassifier",
"pandas... | [((29338, 29423), 'pandas.read_excel', 'pd.read_excel', (['"""default of credit card clients.xls"""'], {'sheet_name': '"""Data"""', 'header': '(1)'}), "('default of credit card clients.xls', sheet_name='Data', header=1\n )\n", (29351, 29423), True, 'import pandas as pd\n'), ((30790, 30830), 'pandas.get_dummies', 'pd... |
# -*- coding: utf-8 -*-
import numpy
import warnings
import operator
import collections
from sagar.crystal.structure import Cell
from sagar.element.base import get_symbol
def read_vasp(filename='POSCAR'):
"""
Import POSCAR/CONTCAR or filename with .vasp suffix
parameter:
filename: string, the filena... | [
"sagar.crystal.structure.Cell",
"numpy.argsort",
"sagar.element.base.get_symbol",
"numpy.linalg.det",
"numpy.array",
"numpy.linalg.inv",
"collections.Counter",
"operator.itemgetter",
"warnings.warn"
] | [((996, 1016), 'numpy.array', 'numpy.array', (['lattice'], {}), '(lattice)\n', (1007, 1016), False, 'import numpy\n'), ((3122, 3153), 'sagar.crystal.structure.Cell', 'Cell', (['lattice', 'positions', 'atoms'], {}), '(lattice, positions, atoms)\n', (3126, 3153), False, 'from sagar.crystal.structure import Cell\n'), ((42... |
from datetime import datetime
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
import src.confi... | [
"sklearn.ensemble.RandomForestClassifier",
"pandas.DataFrame",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.model_selection.cross_val_score",
"sklearn.metrics.classification_report",
"numpy.array",
"sklearn.metrics.confusion_matrix",
"datetime.datetime.now"
] | [((636, 661), 'pandas.read_csv', 'pd.read_csv', (['features_csv'], {}), '(features_csv)\n', (647, 661), True, 'import pandas as pd\n'), ((675, 703), 'numpy.array', 'np.array', (["features_df['VPN']"], {}), "(features_df['VPN'])\n", (683, 703), True, 'import numpy as np\n'), ((1911, 1935), 'numpy.array', 'np.array', (['... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 03 15:01:31 2017
@author: jdkern
"""
import pandas as pd
import numpy as np
#read generator parameters into DataFrame
df_gen = pd.read_excel('NEISO_data_file/generators.xlsx',header=0)
#read transmission path parameters into DataFrame
df_paths = pd.read_csv('NEISO_data... | [
"pandas.DataFrame",
"numpy.sum",
"os.makedirs",
"pandas.read_csv",
"numpy.ones",
"pandas.read_excel",
"numpy.column_stack",
"pathlib.Path.cwd",
"shutil.copy"
] | [((177, 235), 'pandas.read_excel', 'pd.read_excel', (['"""NEISO_data_file/generators.xlsx"""'], {'header': '(0)'}), "('NEISO_data_file/generators.xlsx', header=0)\n", (190, 235), True, 'import pandas as pd\n'), ((297, 347), 'pandas.read_csv', 'pd.read_csv', (['"""NEISO_data_file/paths.csv"""'], {'header': '(0)'}), "('N... |
import numpy as np
# dictionary describing options available to tune this algorithm
options = {
"peak_size": {"purpose": "Estimate of the peak size, in pixels. If 'auto', attempts to determine automatically. Otherwise, this should be an integer.",
"default": "auto",
"type": "i... | [
"numpy.zeros"
] | [((750, 766), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {}), '((4, 2))\n', (758, 766), True, 'import numpy as np\n')] |
from plume.perceptron import PerceptronClassifier
import numpy as np
x_train = np.array([[3, 3], [4, 3], [1, 1]])
y_train = np.array([1, 1, -1])
clf = PerceptronClassifier(dual=False)
clf.fit(x_train, y_train)
print(clf.get_model())
print(clf.predict(x_train))
clf1 = PerceptronClassifier()
clf1.fit(x_train, y_trai... | [
"plume.perceptron.PerceptronClassifier",
"numpy.array"
] | [((80, 114), 'numpy.array', 'np.array', (['[[3, 3], [4, 3], [1, 1]]'], {}), '([[3, 3], [4, 3], [1, 1]])\n', (88, 114), True, 'import numpy as np\n'), ((125, 145), 'numpy.array', 'np.array', (['[1, 1, -1]'], {}), '([1, 1, -1])\n', (133, 145), True, 'import numpy as np\n'), ((153, 185), 'plume.perceptron.PerceptronClassi... |
from transformers import BertForTokenClassification
import torch
from transformers import BertTokenizer
import numpy as np
import nltk.data
nltk.download('punkt')
import torch
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from transformers import BertTokenizer, BertConfig, Au... | [
"matplotlib.pyplot.title",
"seqeval.metrics.accuracy_score",
"torch.utils.data.RandomSampler",
"numpy.argmax",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"sklearn.metrics.f1_score",
"torch.utils.data.TensorDataset",
"torch.device",
"torch.no_grad",
"torch.utils.data.Dat... | [((1162, 1182), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1174, 1182), False, 'import torch\n'), ((2192, 2233), 'os.path.exists', 'os.path.exists', (['"""Models/BERT_epoch-10.pt"""'], {}), "('Models/BERT_epoch-10.pt')\n", (2206, 2233), False, 'import os\n'), ((3178, 3197), 'nltk.tokenize.sent... |
'''
The Normal CDF
100xp
Now that you have a feel for how the Normal PDF looks, let's consider its CDF. Using the
samples you generated in the last exercise (in your namespace as samples_std1, samples_std3,
and samples_std10), generate and plot the CDFs.
Instructions
-Use your ecdf() function to generate x and y value... | [
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.legend",
"numpy.sort",
"numpy.arange",
"numpy.random.normal"
] | [((1123, 1141), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1137, 1141), True, 'import numpy as np\n'), ((1274, 1310), 'numpy.random.normal', 'np.random.normal', (['(20)', '(1)'], {'size': '(100000)'}), '(20, 1, size=100000)\n', (1290, 1310), True, 'import numpy as np\n'), ((1326, 1362), 'numpy.ra... |
# -*- coding: utf-8 -*-
"""
Description
-----------
This module defines the :obj:`ParaMol.Tasks.parametrization.Parametrization` class, which is a ParaMol task that performs force field parametrization.
"""
import numpy as np
import logging
# ParaMol libraries
from .task import *
from ..Optimizers.optimizer import *
f... | [
"logging.info",
"scipy.optimize.LinearConstraint",
"numpy.sum",
"numpy.asarray"
] | [((12519, 12562), 'logging.info', 'logging.info', (['"""Applying charge correction."""'], {}), "('Applying charge correction.')\n", (12531, 12562), False, 'import logging\n'), ((13266, 13313), 'logging.info', 'logging.info', (['"""Not applying charge correction."""'], {}), "('Not applying charge correction.')\n", (1327... |
import sys
sys.path.append('../')
import torchnet as tnt
from torch.autograd import Variable
import torch.nn.functional as F
from model_utils.load_utils import load_model, SAVE_ROOT
from model_utils.model_utils import get_layer_names
MODEL_NAME='mobilenetv2_imagenet'
model_init,model = load_model(MO... | [
"sys.path.append",
"tensor_compression.get_compressed_model",
"copy.deepcopy",
"os.makedirs",
"torch.autograd.Variable",
"flopco.FlopCo",
"os.path.exists",
"torchnet.meter.AverageValueMeter",
"torch.nn.functional.cross_entropy",
"model_utils.model_utils.get_layer_names",
"torch.save",
"collect... | [((16, 38), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (31, 38), False, 'import sys\n'), ((307, 329), 'model_utils.load_utils.load_model', 'load_model', (['MODEL_NAME'], {}), '(MODEL_NAME)\n', (317, 329), False, 'from model_utils.load_utils import load_model, SAVE_ROOT\n'), ((364, 394), 'mo... |
"""Example program to show how to read a multi-channel time series from LSL."""
import math
import threading
# import pygame
from random import random
from sklearn.preprocessing import OneHotEncoder
from pylsl import StreamInlet, resolve_stream
import numpy as np
import pandas as pd
import time
from sklearn import m... | [
"motor_bci_game.Game",
"numpy.load",
"models.CNN2",
"sklearn.metrics.accuracy_score",
"models.RNN",
"models.LDA",
"pandas.DataFrame",
"models.KNN",
"numpy.fft.fft",
"pylsl.resolve_stream",
"pylsl.StreamInlet",
"numpy.append",
"threading.Thread",
"numpy.save",
"datetime.datetime.today",
... | [((592, 624), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""error"""'], {}), "('error')\n", (615, 624), False, 'import warnings\n'), ((1244, 1260), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (1252, 1260), True, 'import numpy as np\n'), ((1889, 1900), 'numpy.array', 'np.array', (['x'], {}),... |
"""
Tests brusselator
"""
import numpy as np
from pymgrit.brusselator.brusselator import Brusselator
from pymgrit.brusselator.brusselator import VectorBrusselator
def test_brusselator_constructor():
"""
Test constructor
"""
brusselator = Brusselator(t_start=0, t_stop=1, nt=11)
np.testing.assert_... | [
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.testing.assert_equal",
"pymgrit.brusselator.brusselator.VectorBrusselator",
"pymgrit.brusselator.brusselator.Brusselator"
] | [((257, 296), 'pymgrit.brusselator.brusselator.Brusselator', 'Brusselator', ([], {'t_start': '(0)', 't_stop': '(1)', 'nt': '(11)'}), '(t_start=0, t_stop=1, nt=11)\n', (268, 296), False, 'from pymgrit.brusselator.brusselator import Brusselator\n'), ((302, 343), 'numpy.testing.assert_equal', 'np.testing.assert_equal', ([... |
#!/usr/bin/env python
import numpy as np
import mixem
from mixem.distribution import MultivariateNormalDistribution
def generate_data():
dist_params = [
(np.array([4]), np.diag([1])),
(np.array([1]), np.diag([0.5]))
]
weights = [0.3, 0.7]
n_data = 5000
data = np.zeros((n_data, 1... | [
"numpy.zeros",
"mixem.distribution.MultivariateNormalDistribution",
"numpy.mean",
"numpy.array",
"numpy.random.multivariate_normal",
"numpy.diag",
"numpy.var"
] | [((301, 322), 'numpy.zeros', 'np.zeros', (['(n_data, 1)'], {}), '((n_data, 1))\n', (309, 322), True, 'import numpy as np\n'), ((558, 571), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (565, 571), True, 'import numpy as np\n'), ((584, 596), 'numpy.var', 'np.var', (['data'], {}), '(data)\n', (590, 596), True, 'im... |
import unittest
import numpy as np
from quasimodo.assertion_fusion.gaussian_nb_with_missing_values import GaussianNBWithMissingValues
class TestFilterObject(unittest.TestCase):
def test_gaussian2(self):
std = -0.1339048038303071
mean = -0.1339048038303071
x = 150.10086283379565
... | [
"unittest.main",
"quasimodo.assertion_fusion.gaussian_nb_with_missing_values.GaussianNBWithMissingValues",
"numpy.array"
] | [((4045, 4060), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4058, 4060), False, 'import unittest\n'), ((450, 478), 'numpy.array', 'np.array', (['([1] * 10 + [0] * 5)'], {}), '([1] * 10 + [0] * 5)\n', (458, 478), True, 'import numpy as np\n'), ((928, 939), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (936, ... |
from itertools import cycle
import numpy as np
from scipy import sparse
import h5py
from evaluation import load_nuswide, normalize
rng = np.random.RandomState(1701)
transformer = []
batch_size = 100
def load():
_, label, _, label_name, _, data = load_nuswide('nuswide-decaf.npz', 'train')
data = data.toarray()
d... | [
"h5py.File",
"gensim.models.Word2Vec.load_word2vec_format",
"numpy.tensordot",
"evaluation.normalize",
"numpy.asarray",
"numpy.zeros",
"numpy.random.RandomState",
"numpy.linalg.norm",
"numpy.dot",
"evaluation.load_nuswide"
] | [((138, 165), 'numpy.random.RandomState', 'np.random.RandomState', (['(1701)'], {}), '(1701)\n', (159, 165), True, 'import numpy as np\n'), ((250, 292), 'evaluation.load_nuswide', 'load_nuswide', (['"""nuswide-decaf.npz"""', '"""train"""'], {}), "('nuswide-decaf.npz', 'train')\n", (262, 292), False, 'from evaluation im... |
import numpy as np
from ..AShape import AShape, AShape
class TileInfo:
"""
Tile info.
arguments
shape AShape
tiles Iterable of ints
errors during the construction:
ValueError
result:
.o_shape AShape
.axes_slices list of slice() to fetch origi... | [
"numpy.prod"
] | [((738, 752), 'numpy.prod', 'np.prod', (['tiles'], {}), '(tiles)\n', (745, 752), True, 'import numpy as np\n')] |
import random
import pickle
import numpy as np
import torch
M = 2**32 - 1
def init_fn(worker):
seed = torch.LongTensor(1).random_().item()
seed = (seed + worker) % M
np.random.seed(seed)
random.seed(seed)
def add_mask(x, mask, dim=1):
mask = mask.unsqueeze(dim)
shape = list(x.shape); shape[di... | [
"numpy.random.seed",
"torch.LongTensor",
"pickle.load",
"numpy.array",
"random.seed",
"numpy.arange",
"torch.tensor"
] | [((1122, 1139), 'torch.tensor', 'torch.tensor', (['[0]'], {}), '([0])\n', (1134, 1139), False, 'import torch\n'), ((180, 200), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (194, 200), True, 'import numpy as np\n'), ((205, 222), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (216, 222), ... |
"""Provide the constant elasticity of substitution function."""
import numpy as np
from copulpy.config_copulpy import IS_DEBUG
from copulpy.clsMeta import MetaCls
class CESCls(MetaCls):
"""CES class."""
def __init__(self, alpha, y_weight, discount_factor):
"""Initialize class."""
self.attr =... | [
"numpy.all",
"numpy.testing.assert_equal"
] | [((1094, 1135), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['(alpha >= 0)', '(True)'], {}), '(alpha >= 0, True)\n', (1117, 1135), True, 'import numpy as np\n'), ((1168, 1190), 'numpy.all', 'np.all', (['(y_weights >= 0)'], {}), '(y_weights >= 0)\n', (1174, 1190), True, 'import numpy as np\n'), ((1230, 125... |
import os
import numpy as np
import tensorrt as trt
from .utils import common, calibrator
class TRTModel:
def __init__(self, onnx_path, plan_path, mode="fp16", calibration_cache="calibration.cache",
calibration_dataset="", calibration_image_size="",
calibration_mean=[], calibra... | [
"tensorrt.Logger",
"tensorrt.OnnxParser",
"os.path.exists",
"tensorrt.Builder",
"numpy.array",
"tensorrt.Runtime"
] | [((862, 874), 'tensorrt.Logger', 'trt.Logger', ([], {}), '()\n', (872, 874), True, 'import tensorrt as trt\n'), ((4532, 4562), 'os.path.exists', 'os.path.exists', (['self.plan_path'], {}), '(self.plan_path)\n', (4546, 4562), False, 'import os\n'), ((1538, 1561), 'os.path.exists', 'os.path.exists', (['dataset'], {}), '(... |
#!/usr/bin/env python
import nltk
from nltk.corpus import brown
import numpy as np
from math import log
from config import *
"""
convert word list file to a map from word to id
"""
def word2map(filename):
word2idx = {};
with open(filename) as f:
for line in f:
word2idx[line.strip('\n')] =... | [
"nltk.corpus.brown.words",
"nltk.data.path.append",
"numpy.zeros",
"numpy.ones",
"math.log"
] | [((416, 448), 'nltk.data.path.append', 'nltk.data.path.append', (['DATA_HOME'], {}), '(DATA_HOME)\n', (437, 448), False, 'import nltk\n'), ((985, 1010), 'numpy.ones', 'np.ones', (['(V_SIZE, C_SIZE)'], {}), '((V_SIZE, C_SIZE))\n', (992, 1010), True, 'import numpy as np\n'), ((1029, 1049), 'numpy.ones', 'np.ones', (['(1,... |
import os
import csv
import collections
import numpy as np
class StatsTracker(collections.defaultdict):
"""Keep track of mean values"""
def __init__(self):
super().__init__(float)
self.step = 1
def update(self, data):
for key, val in data.items():
if key.endswith('_mi... | [
"os.makedirs",
"os.path.dirname",
"numpy.max",
"numpy.min",
"numpy.mean",
"csv.DictWriter"
] | [((1032, 1057), 'os.path.dirname', 'os.path.dirname', (['filepath'], {}), '(filepath)\n', (1047, 1057), False, 'import os\n'), ((1062, 1097), 'os.makedirs', 'os.makedirs', (['dirpath'], {'exist_ok': '(True)'}), '(dirpath, exist_ok=True)\n', (1073, 1097), False, 'import os\n'), ((815, 857), 'csv.DictWriter', 'csv.DictWr... |
"""
Copyright (C) 2022 <NAME>
This work is released under the MIT License.
See the file LICENSE for details
Utility functions
"""
from math import sqrt
from typing import List
import numpy as np
import carla
import io
def loc_dist(a, b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2 + (a.z - b.... | [
"math.sqrt",
"numpy.array2string",
"numpy.hstack",
"numpy.around",
"numpy.linalg.norm",
"numpy.array",
"numpy.vstack",
"carla.Vector3D"
] | [((272, 332), 'math.sqrt', 'sqrt', (['((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)'], {}), '((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)\n', (276, 332), False, 'from math import sqrt\n'), ((414, 470), 'carla.Vector3D', 'carla.Vector3D', ([], {'x': '(v.x / norm)', 'y': '(v.y / norm)', 'z': '(v.z ... |
from apex import amp
from argparse import ArgumentParser
from collections import OrderedDict
from datetime import datetime
import scipy.sparse as sp_sparse
import tables
from itertools import chain
from model import loss_function
from model import VAE
import numpy as np
import os
import pandas as pd
from sklearn.metric... | [
"apex.amp.state_dict",
"numpy.load",
"numpy.random.seed",
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.metrics.accuracy_score",
"numpy.argsort",
"numpy.savez_compressed",
"numpy.arange",
"seaborn.relplot",
"train_multitask_ccle.make_labels",
"os.path.join",
"torch.isnan",
"numpy.... | [((578, 622), 'os.path.join', 'os.path.join', (['outdir', '"""cellByGeneMatrix.npz"""'], {}), "(outdir, 'cellByGeneMatrix.npz')\n", (590, 622), False, 'import os\n'), ((1460, 1512), 'numpy.intersect1d', 'np.intersect1d', (['genes', 'ar_genes'], {'return_indices': '(True)'}), '(genes, ar_genes, return_indices=True)\n', ... |
# Numpy is imported, seed is set
import numpy as np
np.random.seed(123)
# Initialization
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np... | [
"numpy.random.randint",
"numpy.random.seed",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
] | [((52, 71), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (66, 71), True, 'import numpy as np\n'), ((458, 479), 'matplotlib.pyplot.plot', 'plt.plot', (['random_walk'], {}), '(random_walk)\n', (466, 479), True, 'import matplotlib.pyplot as plt\n'), ((497, 507), 'matplotlib.pyplot.show', 'plt.show', ... |
#!/usr/bin/env python
from netCDF4 import Dataset # pylint: disable=no-name-in-module
import numpy as np
#########################################################
# Class for ROMS grd and clm files
# (For use in various post-processing scripts)
#########################################################
class getGrid(... | [
"netCDF4.Dataset",
"numpy.zeros_like",
"numpy.abs",
"argparse.ArgumentParser",
"numpy.tanh",
"numpy.sum",
"numpy.multiply",
"numpy.zeros",
"numpy.arange",
"numpy.array",
"numpy.exp",
"numpy.cosh",
"numpy.sinh",
"sys.exit"
] | [((4031, 4084), 'numpy.zeros', 'np.zeros', (['(nr_zlev, h.shape[0], h.shape[1])', 'np.float'], {}), '((nr_zlev, h.shape[0], h.shape[1]), np.float)\n', (4039, 4084), True, 'import numpy as np\n'), ((6626, 6649), 'numpy.zeros_like', 'np.zeros_like', (['z_values'], {}), '(z_values)\n', (6639, 6649), True, 'import numpy as... |
import numpy as np
import torch
import torch.nn as nn
from torch import optim
from torch.utils.data import DataLoader, ConcatDataset
from argparse import ArgumentParser
from models.psp.pspnet import PSPNet
from models.sobel_op import SobelComputer
from dataset import OnlineTransformDataset
from util.logger import Boar... | [
"util.logger.BoardLogger",
"numpy.random.seed",
"models.psp.pspnet.PSPNet",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"numpy.random.get_state",
"util.image_saver.vis_prediction",
"torch.load",
"dataset.OnlineTransformDataset",
"torch.cuda.device_count",
"util.model_saver.ModelSav... | [((696, 713), 'util.hyper_para.HyperParameters', 'HyperParameters', ([], {}), '()\n', (711, 713), False, 'from util.hyper_para import HyperParameters\n'), ((737, 753), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (751, 753), False, 'from argparse import ArgumentParser\n'), ((1002, 1022), 'util.logger.... |
import abc
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
import gym
import numpy as np
import pymunk as pm
from gym import spaces
import xmagical.entities as en
import xmagical.render as r
from xmagical.phys_vars import PhysicsVariablesBase, PhysVar
from xmagical.style import ARENA_ZOOM_O... | [
"pymunk.Space",
"xmagical.entities.ArenaBoundaries",
"numpy.allclose",
"xmagical.phys_vars.PhysVar",
"xmagical.style.lighten_rgb",
"numpy.random.RandomState",
"numpy.random.randint",
"numpy.array",
"gym.spaces.Box",
"xmagical.render.Viewer",
"gym.envs.classic_control.rendering.SimpleImageViewer"... | [((525, 547), 'xmagical.phys_vars.PhysVar', 'PhysVar', (['(5)', '(3.2, 5.5)'], {}), '(5, (3.2, 5.5))\n', (532, 547), False, 'from xmagical.phys_vars import PhysicsVariablesBase, PhysVar\n'), ((580, 602), 'xmagical.phys_vars.PhysVar', 'PhysVar', (['(1)', '(0.7, 1.5)'], {}), '(1, (0.7, 1.5))\n', (587, 602), False, 'from ... |
import unittest
import numpy as np
import cddm.core as core
from cddm.conf import FDTYPE, CDTYPE
from cddm.video import fromarrays
#test arrays
a = [1.,2,3,4]
b = [5,6,7,8]
t1 = [1,3,7,8]
t2 = [2,4,6,8]
#results fo calculations
cross_a_b = np.array([ 70., 100., 62., 28.],FDTYPE)
cross_a_b_t1_t2 = np.array([32., 72.,... | [
"numpy.random.seed",
"numpy.abs",
"numpy.allclose",
"numpy.ones",
"cddm.core.cross_count",
"cddm.core.ccorr",
"numpy.arange",
"cddm.core.acorr",
"cddm.video.fromarrays",
"cddm.core.cross_correlate_fft",
"unittest.main",
"cddm.core.normalize",
"cddm.core.iacorr",
"cddm.core.abs2",
"numpy.... | [((241, 284), 'numpy.array', 'np.array', (['[70.0, 100.0, 62.0, 28.0]', 'FDTYPE'], {}), '([70.0, 100.0, 62.0, 28.0], FDTYPE)\n', (249, 284), True, 'import numpy as np\n'), ((301, 366), 'numpy.array', 'np.array', (['[32.0, 72.0, 28.0, 38.0, 24.0, 38.0, 20.0, 8.0]', 'FDTYPE'], {}), '([32.0, 72.0, 28.0, 38.0, 24.0, 38.0, ... |
import argparse
import numpy as np
import pytorch_lightning as pl
from torch.utils.data.dataloader import DataLoader
import utils.data.functions
class SpatioTemporalCSVDataModule(pl.LightningDataModule):
def __init__(
self,
feat_path: str,
adj_path: str,
batch_size: int = 32,
... | [
"torch.utils.data.dataloader.DataLoader",
"numpy.max",
"argparse.ArgumentParser"
] | [((863, 881), 'numpy.max', 'np.max', (['self._feat'], {}), '(self._feat)\n', (869, 881), True, 'import numpy as np\n'), ((1223, 1287), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (1246, 1287), False, 'i... |
import os
import cv2
import numpy as np
import sys
caffe_root = os.path.expanduser('~') + "/CNN/ssd"
sys.path.insert(0, caffe_root+'/python')
import caffe
from tqdm import tqdm
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat',
'chair','cow', 'diningtable', 'dog', 'horse','... | [
"cv2.putText",
"os.makedirs",
"cv2.waitKey",
"cv2.imshow",
"sys.path.insert",
"os.path.exists",
"numpy.array",
"cv2.rectangle",
"caffe.Net",
"os.path.expanduser"
] | [((101, 143), 'sys.path.insert', 'sys.path.insert', (['(0)', "(caffe_root + '/python')"], {}), "(0, caffe_root + '/python')\n", (116, 143), False, 'import sys\n'), ((64, 87), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (82, 87), False, 'import os\n'), ((827, 855), 'numpy.array', 'np.array'... |
import os.path
import pickle
import random
from data.base_dataset import BaseDataset, get_params, get_transform
from data.image_folder import make_numbering_dataset
import numpy as np
from PIL import Image
class AlignedDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the dir... | [
"random.randint",
"data.base_dataset.get_params",
"data.base_dataset.BaseDataset.__init__",
"numpy.asarray",
"numpy.zeros",
"data.image_folder.make_numbering_dataset",
"PIL.Image.open",
"numpy.sort",
"pickle.load",
"numpy.arange",
"data.base_dataset.get_transform",
"numpy.random.shuffle"
] | [((694, 725), 'data.base_dataset.BaseDataset.__init__', 'BaseDataset.__init__', (['self', 'opt'], {}), '(self, opt)\n', (714, 725), False, 'from data.base_dataset import BaseDataset, get_params, get_transform\n'), ((2143, 2187), 'numpy.zeros', 'np.zeros', (['self.text_words_num'], {'dtype': '"""int64"""'}), "(self.text... |
"""
phase.py
Estimate the phase of an oscillation using a waveform-based approach
"""
import numpy as np
def extrema_interpolated_phase(x, Ps, Ts, zeroxR=None, zeroxD=None):
"""
Use peaks (phase 0) and troughs (phase pi/-pi) to estimate
instantaneous phase. Also use rise and decay zerocrossings
(phas... | [
"numpy.zeros",
"numpy.isnan",
"numpy.append",
"numpy.diff",
"numpy.arange"
] | [((1263, 1275), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (1272, 1275), True, 'import numpy as np\n'), ((2105, 2122), 'numpy.diff', 'np.diff', (['pha_tnpi'], {}), '(pha_tnpi)\n', (2112, 2122), True, 'import numpy as np\n'), ((2135, 2155), 'numpy.append', 'np.append', (['diffs', '(99)'], {}), '(diffs, 99)\n', (... |
# -*- coding: utf-8 -*-
import os
from collections import defaultdict
from copy import deepcopy
from warnings import warn
import numpy as np
import pandas as pd
from pathlib import Path
from simulator.core.DtnBundle import Bundle
from simulator.utils.DtnIO import load_traffic_file
from simulator.utils.DtnUtils import... | [
"pandas.DataFrame",
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.ceil",
"numpy.argmax",
"numpy.floor",
"numpy.random.exponential",
"numpy.zeros",
"collections.defaultdict",
"numpy.cumsum",
"numpy.diff",
"numpy.array",
"numpy.arange",
"simulator.core.DtnBundle.Bundle.from_flow",
"si... | [((710, 960), 'numpy.array', 'np.array', (['[[60, np.nan, np.nan], [60, np.nan, np.nan], [60, np.nan, 3600], [60, 60,\n np.nan], [60, 900, 21600], [60, 300, 3600], [60, 300, np.nan], [60, 60,\n np.nan], [60, 900, 21600], [60, 900, 21600], [60, 900, 21600], [60, 300,\n np.nan]]'], {}), '([[60, np.nan, np.nan], ... |
"""Multi-agent traffic light example (single shared policy)."""
from ray.rllib.agents.ppo.ppo_policy import PPOTFPolicy
from flow.envs.multiagent import MyMultiTrafficLightGridPOEnv
from flow.networks import TrafficLightGridNetwork
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.... | [
"flow.networks.TrafficLightGridNetwork",
"flow.core.params.EnvParams",
"flow.core.params.VehicleParams",
"flow.envs.multiagent.MyMultiTrafficLightGridPOEnv",
"flow.core.params.SumoParams",
"numpy.zeros",
"flow.core.params.SumoCarFollowingParams",
"numpy.mean",
"numpy.array",
"flow.core.params.InFl... | [((1495, 1510), 'flow.core.params.VehicleParams', 'VehicleParams', ([], {}), '()\n', (1508, 1510), False, 'from flow.core.params import InFlows, SumoCarFollowingParams, VehicleParams\n'), ((2385, 2394), 'flow.core.params.InFlows', 'InFlows', ([], {}), '()\n', (2392, 2394), False, 'from flow.core.params import InFlows, ... |
""" Module for the KMCRateCalculatorPlugin class """
# Copyright (c) 2013 <NAME>
#
# This file is part of the KMCLib project distributed under the terms of the
# GNU General Public License version 3, see <http://www.gnu.org/licenses/>.
#
import numpy
from KMCLib.Backend import Backend
from KMCLib.Exceptions.Erro... | [
"KMCLib.Backend.Backend.RateCalculator.__init__",
"numpy.array",
"KMCLib.Exceptions.Error.Error"
] | [((691, 728), 'KMCLib.Backend.Backend.RateCalculator.__init__', 'Backend.RateCalculator.__init__', (['self'], {}), '(self)\n', (722, 728), False, 'from KMCLib.Backend import Backend\n'), ((3162, 3306), 'KMCLib.Exceptions.Error.Error', 'Error', (['"""The rate(self,...) API function in the \'KMCRateCalculator\' base clas... |
import csv
import matplotlib as matplot
import matplotlib.pyplot as plt
import numpy as np
# List the colors that will be used for tracing the track.
colors = ['black','blue','red','green', 'cyan', \
'gray', 'gold', 'lightcoral', 'turquoise','red','blue','green','pink']
patterns = ['-', '--','--','--','--'... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"numpy.std",
"csv.DictReader",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",... | [((1745, 1847), 'matplotlib.pyplot.legend', 'plt.legend', (["['Real Track', 'C0.0001', 'C0.01', 'C1', 'C100']"], {'loc': '"""upper right"""', 'prop': "{'size': 7}"}), "(['Real Track', 'C0.0001', 'C0.01', 'C1', 'C100'], loc=\n 'upper right', prop={'size': 7})\n", (1755, 1847), True, 'import matplotlib.pyplot as plt\n... |
import unittest
import cv2
import numpy as np
from extractor.cropping import clip_to_image_region, \
crop_module, build_merged_index
quadrilaterals = {
('e3e70682-c209-4cac-a29f-6fbed82c07cd',
'frame_000000',
'mask_000000'): {
'quadrilateral': [
[424, 279],
[499, 28... | [
"numpy.copy",
"extractor.cropping.build_merged_index",
"numpy.allclose",
"extractor.cropping.crop_module",
"cv2.imread",
"numpy.array",
"numpy.eye"
] | [((1901, 1967), 'numpy.array', 'np.array', (['[[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]]'], {}), '([[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]])\n', (1909, 1967), True, 'import numpy as np\n'), ((2458, 2524), 'numpy.array', 'np.array', (['[[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]... |
from .resnet import resnet50
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
class fpn_module_global(nn.Module):
def __init__(self, numClass):
super(fpn_module_global, self).__init__()
self._up_kwargs = {'mode': 'bilinear'}
# Top layer
self.top... | [
"torch.nn.MSELoss",
"torch.stack",
"torch.nn.functional.grid_sample",
"torch.nn.Conv2d",
"numpy.zeros",
"torch.cat",
"torch.nn.init.normal_",
"torch.nn.init.constant_",
"torch.zeros",
"torch.nn.functional.interpolate",
"torch.no_grad",
"numpy.round",
"torch.from_numpy"
] | [((328, 384), 'torch.nn.Conv2d', 'nn.Conv2d', (['(2048)', '(256)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(2048, 256, kernel_size=1, stride=1, padding=0)\n', (337, 384), True, 'import torch.nn as nn\n'), ((453, 509), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1024)', '(256)'], {'kernel_size': '(1)', 'st... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 21:24:36 2019
@author: wmy
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
from keras import backend as K
from keras.losses import mean_absolute_error, mean_squared_error
from keras.models import load_m... | [
"random.uniform",
"utils.DataLoader",
"numpy.asarray",
"random.choice",
"numpy.clip",
"PIL.Image.fromarray",
"numpy.array",
"model.wdsr_b"
] | [((461, 495), 'model.wdsr_b', 'wdsr_b', ([], {'scale': '(4)', 'num_res_blocks': '(32)'}), '(scale=4, num_res_blocks=32)\n', (467, 495), False, 'from model import wdsr_a, wdsr_b\n'), ((562, 581), 'utils.DataLoader', 'DataLoader', ([], {'scale': '(4)'}), '(scale=4)\n', (572, 581), False, 'from utils import DataLoader\n')... |
import os
import time
import numpy as np
import paddle.fluid as fluid
import config as cfg
from nets.attention_model import attention_train_net
from nets.crnn_ctc_model import ctc_train_net
from utils import data_reader
from utils.utility import get_ctc_feeder_data, get_attention_feeder_data
def main():
"""OCR tr... | [
"paddle.fluid.Executor",
"paddle.fluid.CUDAPlace",
"paddle.fluid.default_main_program",
"utils.data_reader.test",
"paddle.fluid.default_startup_program",
"os.makedirs",
"os.path.exists",
"time.time",
"utils.data_reader.train",
"numpy.array",
"paddle.fluid.CPUPlace",
"paddle.fluid.ParallelExecu... | [((722, 847), 'utils.data_reader.train', 'data_reader.train', ([], {'batch_size': 'cfg.batch_size', 'prefix_path': 'cfg.train_prefix', 'cycle': '(cfg.total_step > 0)', 'model': 'cfg.use_model'}), '(batch_size=cfg.batch_size, prefix_path=cfg.train_prefix,\n cycle=cfg.total_step > 0, model=cfg.use_model)\n', (739, 847... |
import numpy
import qm3
import qm3.engines.gaussian
import io
import os
import sys
cwd = os.path.abspath( os.path.dirname( sys.argv[0] ) ) + os.sep
mol = qm3.molecule()
mol.pdb_read( open( cwd + "charmm.pdb" ) )
mol.psf_read( open( cwd + "charmm.psf" ) )
mol.guess_atomic_numbers()
print( mol.anum )
print( mol.... | [
"io.StringIO",
"qm3.engines.gaussian.run",
"os.path.dirname",
"numpy.logical_not",
"qm3.molecule",
"numpy.fabs",
"numpy.linalg.norm"
] | [((163, 177), 'qm3.molecule', 'qm3.molecule', ([], {}), '()\n', (175, 177), False, 'import qm3\n'), ((454, 476), 'numpy.logical_not', 'numpy.logical_not', (['sqm'], {}), '(sqm)\n', (471, 476), False, 'import numpy\n'), ((575, 765), 'io.StringIO', 'io.StringIO', (['"""%chk=gauss.chk\n%mem=2048mb\n%nproc=2\n#p b3lyp/def2... |
"""
Variant of the base class with parallelized, pipelined, and vectorized operations.
The technique pertaining to convolution was reused from https://stackoverflow.com/a/36968434.
Try executing this program with (the other variants will crawl):
python3 conway_v3.py --board-size 160 --interval 20 --configuration patt... | [
"dask.array.from_array",
"numpy.logical_or",
"numpy.ones"
] | [((557, 607), 'dask.array.from_array', 'da.from_array', (['self.board'], {'chunks': "('auto', 'auto')"}), "(self.board, chunks=('auto', 'auto'))\n", (570, 607), True, 'import dask.array as da\n'), ((629, 644), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (636, 644), True, 'import numpy as np\n'), ((1055, 10... |
"""
This script utilises the ground truth label's 2D bounding box to
crop out the the points of interest and feed it into the model so that
it can predict a 3D bounding box for each of the 2D detections
The script will plot the results of the 3D bounding box onto the image
and display them alongside the groundtruth... | [
"torchvision.models.vgg19_bn",
"argparse.ArgumentParser",
"numpy.copy",
"numpy.concatenate",
"numpy.argmax",
"cv2.imwrite",
"torch.load",
"numpy.arctan2",
"lib.ClassAverages.ClassAverages",
"os.path.dirname",
"torch.cuda.is_available",
"torch.device",
"torch.zeros",
"os.listdir",
"lib.Mo... | [((1096, 1121), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1119, 1121), False, 'import torch\n'), ((1135, 1178), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (1147, 1178), False, 'import torch\n'), ((5836, 5861), 'argparse.... |
import numpy as np
from autocnet.camera.utils import crossform
from cv2 import triangulatePoints
def compute_epipoles(f):
"""
Compute the epipole and epipolar prime
Parameters
----------
f : ndarray
(3,3) fundamental matrix or autocnet Fundamental Matrix object
Returns
-------
... | [
"numpy.sum",
"autocnet.camera.utils.crossform",
"numpy.asarray",
"numpy.empty",
"numpy.linalg.svd",
"numpy.eye",
"cv2.triangulatePoints"
] | [((433, 449), 'numpy.linalg.svd', 'np.linalg.svd', (['f'], {}), '(f)\n', (446, 449), True, 'import numpy as np\n'), ((476, 488), 'autocnet.camera.utils.crossform', 'crossform', (['e'], {}), '(e)\n', (485, 488), False, 'from autocnet.camera.utils import crossform\n'), ((678, 690), 'numpy.eye', 'np.eye', (['(3)', '(4)'],... |
from kinematicEnv import KinematicEnv
from QL import QL
from upDDPG import DDPG as uDDPG
import tensorflow as tf
from bottomDDPG import DDPG as bDDPG
import numpy as np
env = KinematicEnv()
s_dim = env.state_dim
a_dim = env.action_dim
a_bound = env.action_bound
g1 = tf.Graph()
isess1 = tf.Session(graph=g1)
with g1.as_... | [
"kinematicEnv.KinematicEnv",
"QL.QL",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"upDDPG.DDPG",
"numpy.random.randint",
"tensorflow.Graph",
"bottomDDPG.DDPG"
] | [((175, 189), 'kinematicEnv.KinematicEnv', 'KinematicEnv', ([], {}), '()\n', (187, 189), False, 'from kinematicEnv import KinematicEnv\n'), ((268, 278), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (276, 278), True, 'import tensorflow as tf\n'), ((288, 308), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'g1'}... |
import unittest
import warnings
import numpy as np
# import safety_gym
# from safety_gym.envs.engine import Engine
import gym
import gym.spaces as spaces
from gym.envs.registration import register
from edge.gym_wrappers import BoxWrapper, DiscreteWrapper, GymEnvironmentWrapper
from edge.agent import RandomAgent
clas... | [
"unittest.main",
"numpy.abs",
"gym.make",
"warnings.filterwarnings",
"edge.gym_wrappers.DiscreteWrapper",
"gym.spaces.Discrete",
"edge.gym_wrappers.BoxWrapper",
"gym.spaces.Box",
"edge.gym_wrappers.GymEnvironmentWrapper",
"numpy.array",
"edge.agent.RandomAgent"
] | [((4610, 4625), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4623, 4625), False, 'import unittest\n'), ((396, 429), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (419, 429), False, 'import warnings\n'), ((443, 467), 'gym.spaces.Box', 'spaces.Box', (['(0)', '(1)', ... |
"""
Implementation of the model.
Parts of the code are inherited from the official CAAE implementation (https://arxiv.org/abs/1702.08423, https://github.com/ZZUTK/Face-Aging-CAAE).
"""
import os
import sys
import time
from glob import glob
import numpy as np
import tensorflow as tf
from scipy.io import loadmat, save... | [
"tensorflow.compat.v1.losses.mean_squared_error",
"scipy.io.loadmat",
"tensorflow.zeros_like",
"tensorflow.compat.v1.get_variable_scope",
"PK_Utils.PK_subnetworks.generator",
"tensorflow.compat.v1.train.exponential_decay",
"PK_Utils.PK_vgg_face.face_embedding",
"numpy.arange",
"numpy.tile",
"tenso... | [((779, 794), 'scipy.io.loadmat', 'loadmat', (['vggMat'], {}), '(vggMat)\n', (786, 794), False, 'from scipy.io import loadmat, savemat\n'), ((1015, 1118), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', '[size_batch, size_image, size_image, 3]'], {'name': '"""input_images"""'}), "(tf.flo... |
"""
==================================
Plotting two simple sine functions
==================================
A simple example plotting a fit of two sine functions.
"""
import numpy
import matplotlib.pyplot as plt
from pyearth import Earth
# Create some fake data
numpy.random.seed(2)
m = 10000
n = 10
X = 80 * numpy.r... | [
"numpy.random.uniform",
"numpy.random.seed",
"matplotlib.pyplot.show",
"pyearth.Earth",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.random.normal",
"numpy.concatenate"
] | [((266, 286), 'numpy.random.seed', 'numpy.random.seed', (['(2)'], {}), '(2)\n', (283, 286), False, 'import numpy\n'), ((583, 621), 'pyearth.Earth', 'Earth', ([], {'max_degree': '(3)', 'minspan_alpha': '(0.5)'}), '(max_degree=3, minspan_alpha=0.5)\n', (588, 621), False, 'from pyearth import Earth\n'), ((629, 700), 'nump... |
"""Defines hooks that can run during training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import lasagne
import numpy as np
from sklearn import metrics
class LoggingHook(object):
"""This hook writes information to a log file."""
def __ini... | [
"lasagne.layers.get_all_param_values",
"numpy.argmax",
"numpy.asarray",
"numpy.zeros",
"numpy.max",
"numpy.arange"
] | [((1068, 1096), 'numpy.asarray', 'np.asarray', (["kwargs['losses']"], {}), "(kwargs['losses'])\n", (1078, 1096), True, 'import numpy as np\n'), ((1983, 2033), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['self._network'], {}), '(self._network)\n', (2018, 2033), False, 'import lasagne\... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the Masci-tools package. ... | [
"masci_tools.io.parsers.hdf5.reader.AttribTransformation",
"h5py.File",
"masci_tools.io.parsers.hdf5.HDF5Reader",
"masci_tools.io.parsers.hdf5.reader.Transformation",
"numpy.array2string",
"numpy.zeros",
"numpy.array",
"collections.namedtuple",
"numpy.linalg.norm"
] | [((1342, 1462), 'collections.namedtuple', 'namedtuple', (['"""GreensfElement"""', "['l', 'lp', 'atomType', 'atomTypep', 'sphavg', 'onsite', 'contour', 'nLO',\n 'atomDiff']"], {}), "('GreensfElement', ['l', 'lp', 'atomType', 'atomTypep', 'sphavg',\n 'onsite', 'contour', 'nLO', 'atomDiff'])\n", (1352, 1462), False,... |
# -*- coding: utf-8 -*-
"""
2D sweep of drive power and frequency in Lockin mode.
"""
from typing import List
import h5py
import numpy as np
from presto.hardware import AdcFSample, AdcMode, DacFSample, DacMode
from presto import lockin
from presto.utils import ProgressBar
from _base import Base
DAC_CURRENT = 32_000... | [
"h5py.File",
"numpy.zeros_like",
"numpy.atleast_1d",
"presto.utils.ProgressBar",
"numpy.abs",
"numpy.full_like",
"numpy.angle",
"numpy.zeros",
"presto.lockin.Lockin",
"numpy.percentile",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"matplotlib.widgets.SpanSelector",
"numpy.l... | [((6151, 6181), 'numpy.percentile', 'np.percentile', (['resp_dB', 'cutoff'], {}), '(resp_dB, cutoff)\n', (6164, 6181), True, 'import numpy as np\n'), ((6200, 6238), 'numpy.percentile', 'np.percentile', (['resp_dB', '(100.0 - cutoff)'], {}), '(resp_dB, 100.0 - cutoff)\n', (6213, 6238), True, 'import numpy as np\n'), ((1... |
# Lint as: python3
# Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | [
"pandas.read_csv",
"numpy.random.permutation",
"tensorflow.io.gfile.exists",
"tensorflow.io.gfile.GFile"
] | [((1632, 1660), 'tensorflow.io.gfile.exists', 'tf.io.gfile.exists', (['datafile'], {}), '(datafile)\n', (1650, 1660), True, 'import tensorflow as tf\n'), ((1736, 1763), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['datafile'], {}), '(datafile)\n', (1753, 1763), True, 'import tensorflow as tf\n'), ((1792, 1842), ... |
import torch
from torch.utils.data import Dataset
import numpy as np
from scipy.io import loadmat
class NatPatchDataset(Dataset):
def __init__(self, N:int, width:int, height:int, border:int=4, fpath:str='../../data/IMAGES.mat', test=False):
super(NatPatchDataset, self).__init__()
self.N = N
... | [
"torch.zeros",
"numpy.random.randint",
"torch.tensor",
"scipy.io.loadmat"
] | [((746, 765), 'scipy.io.loadmat', 'loadmat', (['self.fpath'], {}), '(self.fpath)\n', (753, 765), False, 'from scipy.io import loadmat\n'), ((869, 923), 'torch.zeros', 'torch.zeros', (['(self.N * n_img, self.width, self.height)'], {}), '((self.N * n_img, self.width, self.height))\n', (880, 923), False, 'import torch\n')... |
from RouteManager import RouteManager
from Route import Route
import numpy as np
class GeneticAlgorithmSolver:
def __init__(self, cities, population_size=50, mutation_rate=0.05, tournament_size=5, elitism=True):
self.cities = cities
self.population_size = population_size
self.mutation_rat... | [
"numpy.random.rand",
"Route.Route",
"RouteManager.RouteManager",
"numpy.random.choice"
] | [((866, 913), 'RouteManager.RouteManager', 'RouteManager', (['self.cities', 'self.population_size'], {}), '(self.cities, self.population_size)\n', (878, 913), False, 'from RouteManager import RouteManager\n'), ((1350, 1397), 'RouteManager.RouteManager', 'RouteManager', (['self.cities', 'self.population_size'], {}), '(s... |
# Load libraries
import matplotlib.pyplot as plt
import pandas as pd
import pickle
import numpy as np
import os
from keras.applications.resnet50 import ResNet50
from keras.optimizers import Adam
from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embedding, Bidirectiona... | [
"numpy.load",
"pickle.dump",
"numpy.argmax",
"pandas.read_csv",
"keras.preprocessing.sequence.pad_sequences",
"keras.models.Model",
"IPython.core.display.HTML",
"keras.preprocessing.image.img_to_array",
"pickle.load",
"keras.preprocessing.image.load_img",
"numpy.save",
"IPython.core.display.di... | [((564, 605), 'os.listdir', 'os.listdir', (['"""D:\\\\FBAi\\\\data\\\\Flickr_Data"""'], {}), "('D:\\\\FBAi\\\\data\\\\Flickr_Data')\n", (574, 605), False, 'import os\n'), ((1624, 1661), 'IPython.display.Image', 'Image', ([], {'filename': '(images_path + temp[0])'}), '(filename=images_path + temp[0])\n', (1629, 1661), F... |
#!/usr/bin/env python
# coding: utf-8
# # Buscador
#
# Esse notebook implementa um buscador simples.
# A representação pra cada texto é criada a partir da TF-IDF.
# A representação da query (consulta, ou termos buscados)
# é construída a partir do vocabulário dos textos.
# O ranqueamento dos resultados é feito de acor... | [
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.metrics.pairwise.cosine_similarity",
"pandas.read_json",
"numpy.argsort",
"scripts.nlp.remove_portuguese_stopwords",
"sklearn.feature_extraction.text.TfidfTransformer"
] | [((1247, 1272), 'pandas.read_json', 'pd.read_json', (['"""leis.json"""'], {}), "('leis.json')\n", (1259, 1272), True, 'import pandas as pd\n'), ((2097, 2114), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (2112, 2114), False, 'from sklearn.feature_extraction.text import CountVe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.