code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import json
import numpy
from RecomandEngine.restrictions.RestrictionConflicts import RestrictionConflict, RestrictionAlphaOrBeta
from RecomandEngine.restrictions.RestrictionDependences import RestrictionOneToOneDependency, \
RestrictionOneToManyDependency, RestrictionManyToManyDependency, RestrictionManyToManyDepe... | [
"RecomandEngine.exactsolvers.nonlinear.SMT_Solver_Z3_RealBool.Z3_Solver",
"RecomandEngine.exactsolvers.nonlinear.SMT_Solver_Z3_RealReal.Z3_Solver",
"RecomandEngine.exactsolvers.linear.SMT_Solver_Z3_RealPBC.Z3_Solver",
"RecomandEngine.problem.Component.Component",
"RecomandEngine.exactsolvers.linear.IntIntOr... | [((1320, 1376), 'numpy.zeros', 'numpy.zeros', (['(self.nrComp, self.nrComp)'], {'dtype': 'numpy.int'}), '((self.nrComp, self.nrComp), dtype=numpy.int)\n', (1331, 1376), False, 'import numpy\n'), ((1412, 1468), 'numpy.zeros', 'numpy.zeros', (['(self.nrComp, self.nrComp)'], {'dtype': 'numpy.int'}), '((self.nrComp, self.n... |
import os
import numpy as np
from ..model.model_zoo import *
from ..model.ssd import SSDLearner
from ..dataset.pascal_voc import PascalVOCObjectDataset
from ..dataset.coco import COCOObjectDataset
from ..model.configs import cfg
def set_up_pascalvoc_detection(config, output_dir, logger, device=0, queries_name='quer... | [
"os.path.join",
"numpy.arange",
"os.getenv"
] | [((541, 583), 'numpy.arange', 'np.arange', (["config['dataset']['train_size']"], {}), "(config['dataset']['train_size'])\n", (550, 583), True, 'import numpy as np\n'), ((601, 642), 'numpy.arange', 'np.arange', (["config['dataset']['test_size']"], {}), "(config['dataset']['test_size'])\n", (610, 642), True, 'import nump... |
import numpy as np
import unittest
import os
import shutil
# Data from Geradin
# time[s] theta[rad]
geradin_FoR0 = np.array([[-0.0117973, 1.56808],
[0.0816564, 1.5394],
[0.171988, 1.41698],
[0.235203, 1.31521],
[0.307327, 1... | [
"sharpy.utils.generate_cases.LagrangeConstraint",
"sharpy.utils.generate_cases.BodyInformation",
"sharpy.utils.generate_cases.clean_test_files",
"numpy.ones",
"sharpy.utils.generate_cases.SimulationInformation",
"sharpy.utils.generate_cases.generate_multibody_file",
"sharpy.utils.generate_cases.Aeroelas... | [((116, 1209), 'numpy.array', 'np.array', (['[[-0.0117973, 1.56808], [0.0816564, 1.5394], [0.171988, 1.41698], [0.235203,\n 1.31521], [0.307327, 1.09265], [0.427399, 0.601124], [0.526338, \n 0.0899229], [0.646417, -0.394903], [0.748531, -0.765465], [0.868959, -\n 0.94209], [0.905131, -0.956217], [0.965504, -0.... |
import numpy as np
import random
import os
import datetime
def str_list_to_float(str_list):
return [float(item) for item in str_list]
def str_list_to_int(str_list):
return [int(item) for item in str_list]
def read_embeddings(filename, n_node, n_embed):
with open(filename, "r") as f:
embedding... | [
"numpy.clip",
"os.path.exists",
"numpy.random.rand",
"random.shuffle",
"os.makedirs",
"numpy.exp",
"os.path.dirname",
"datetime.datetime.now",
"numpy.isnan"
] | [((1046, 1070), 'numpy.clip', 'np.clip', (['agm_x', '(1e-06)', '(1)'], {}), '(agm_x, 1e-06, 1)\n', (1053, 1070), True, 'import numpy as np\n'), ((1179, 1203), 'numpy.clip', 'np.clip', (['agm_x', '(1e-06)', '(1)'], {}), '(agm_x, 1e-06, 1)\n', (1186, 1203), True, 'import numpy as np\n'), ((1877, 1896), 'random.shuffle', ... |
"""
Signal processing.
"""
import collections.abc
import logging
from typing import Tuple
import numpy as np
from ridge_detection.helper import displayContours, save_to_disk
from ridge_detection.lineDetector import LineDetector
from ridge_detection.params import Params
from scipy import ndimage as ndi
from skimage.fil... | [
"numpy.sqrt",
"ridge_detection.params.Params",
"logging.error",
"numpy.imag",
"numpy.mean",
"numpy.max",
"alsa.image_proc.open_image",
"ridge_detection.helper.displayContours",
"numpy.linspace",
"numpy.real",
"numpy.min",
"scipy.ndimage.convolve",
"alsa.image_proc.img_binmat_line_segment",
... | [((1977, 2009), 'numpy.linspace', 'np.linspace', (['theta_0', 'theta_n', 'n'], {}), '(theta_0, theta_n, n)\n', (1988, 2009), True, 'import numpy as np\n'), ((2576, 2587), 'numpy.min', 'np.min', (['mat'], {}), '(mat)\n', (2582, 2587), True, 'import numpy as np\n'), ((2602, 2613), 'numpy.max', 'np.max', (['mat'], {}), '(... |
from numpy import genfromtxt
from matplotlib.pyplot import figure, legend, loglog, savefig, xlabel, ylabel,show
from sys import argv
input_file = str(argv[1])
output_file = str(argv[2])
data = genfromtxt(input_file, skip_header=1, delimiter=',')
N = data[:,0]
err = data[:,1]
fig=figure()
loglog(N,1/N, '--', label='s... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"numpy.genfromtxt",
"matplotlib.pyplot.legend"
] | [((195, 247), 'numpy.genfromtxt', 'genfromtxt', (['input_file'], {'skip_header': '(1)', 'delimiter': '""","""'}), "(input_file, skip_header=1, delimiter=',')\n", (205, 247), False, 'from numpy import genfromtxt\n'), ((283, 291), 'matplotlib.pyplot.figure', 'figure', ([], {}), '()\n', (289, 291), False, 'from matplotlib... |
import numpy as np
from scipy.interpolate import interp2d,interp1d
from .params import default_params
import camb
from camb import model
import scipy.interpolate as si
import scipy.constants as constants
"""
This module will (eventually) abstract away the choice of boltzmann codes.
However, it does it stupidly by simp... | [
"numpy.log10",
"camb.set_params",
"numpy.trapz",
"numpy.sqrt",
"scipy.interpolate.dfitpack.bispeu",
"numpy.log",
"numpy.asarray",
"numpy.sinc",
"scipy.interpolate.interp1d",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"camb.get_background",
"numpy.zeros_like",
"scipy.i... | [((16320, 16340), 'numpy.zeros', 'np.zeros', (['ells.shape'], {}), '(ells.shape)\n', (16328, 16340), True, 'import numpy as np\n'), ((2508, 2916), 'camb.set_params', 'camb.set_params', ([], {'ns': "params['ns']", 'As': "params['As']", 'H0': 'H0', 'cosmomc_theta': 'theta', 'ombh2': "params['ombh2']", 'omch2': "params['o... |
# test annotation bboxes with extracted midframes and clips
import cv2
import os
import json
import numpy as np
AVA_FOLDER = os.environ['AVA_DIR'] + '/AVA'
segments_folder = AVA_FOLDER + '/segments/segments/'
annotations_folder = AVA_FOLDER + '/annotations/'
data_folder = AVA_FOLDER + '/data/'
objects_folder = AVA_... | [
"cv2.rectangle",
"numpy.copy",
"os.path.join",
"cv2.imshow",
"cv2.putText",
"numpy.random.randint",
"cv2.waitKey",
"os._exit",
"numpy.concatenate",
"json.load",
"cv2.imread"
] | [((2418, 2453), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)', '[100, 3]'], {}), '(0, 255, [100, 3])\n', (2435, 2453), True, 'import numpy as np\n'), ((555, 568), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (564, 568), False, 'import json\n'), ((945, 1030), 'os.path.join', 'os.path.join', (['segme... |
import numpy as np
from astropy import units as u
from astropy.time import Time
from CelestialMechanics.kepler import constants
from CelestialMechanics.kepler import kepler3
from CelestialMechanics.mu import mu_sun, mu_gm1m2
from CelestialMechanics.orbital_elements.orbital_elements import solve, solve_ellipse, solve_h... | [
"CelestialMechanics.kepler.kepler3.T_sun",
"numpy.sqrt",
"CelestialMechanics.mu.mu_gm1m2",
"CelestialMechanics.orbital_elements.orbital_elements.solve",
"CelestialMechanics.orbits.ellipse.delta_t_t0_aeangle",
"CelestialMechanics.orbits.ellipse.ae",
"CelestialMechanics.orbital_elements.orbital_elements.s... | [((527, 546), 'CelestialMechanics.kepler.kepler3.T_sun', 'kepler3.T_sun', (['a', '(0)'], {}), '(a, 0)\n', (540, 546), False, 'from CelestialMechanics.kepler import kepler3\n'), ((566, 575), 'CelestialMechanics.mu.mu_sun', 'mu_sun', (['(0)'], {}), '(0)\n', (572, 575), False, 'from CelestialMechanics.mu import mu_sun, mu... |
from contextlib import ExitStack
import fnmatch
import io
import os
import shutil
import urllib3
import zipfile
import click
import numpy
import rasterio
from rasterio.enums import Interleaving, Compression
# bio is 12 variables in one, the rest are monthly
VARS = {
'tmin': {
'nodata': -32768,
'dtype': rast... | [
"os.path.exists",
"click.Choice",
"shutil.copyfileobj",
"click.option",
"rasterio.Env",
"numpy.asarray",
"numpy.ma.filled",
"urllib3.PoolManager",
"fnmatch.fnmatch",
"contextlib.ExitStack",
"click.command"
] | [((3097, 3112), 'click.command', 'click.command', ([], {}), '()\n', (3110, 3112), False, 'import click\n'), ((3194, 3234), 'click.option', 'click.option', (['"""--extract"""'], {'default': '(False)'}), "('--extract', default=False)\n", (3206, 3234), False, 'import click\n'), ((1201, 1222), 'os.path.exists', 'os.path.ex... |
""" Utility functions for EO charge transfer inefficiency tests
"""
import numpy as np
import lsst.afw.math as afwMath
import lsst.geom as lsstGeom
__all__ = ["Estimator", "SubImage", "estimateCti"]
class Estimator:
"Abstraction for a point estimator of pixel data and its errors"
def __init__(self, *args,... | [
"numpy.abs",
"numpy.sqrt",
"lsst.geom.Box2I",
"lsst.afw.math.makeStatistics",
"lsst.geom.BoxI"
] | [((7271, 7294), 'lsst.geom.BoxI', 'lsstGeom.BoxI', (['llc', 'urc'], {}), '(llc, urc)\n', (7284, 7294), True, 'import lsst.geom as lsstGeom\n'), ((7495, 7518), 'lsst.geom.BoxI', 'lsstGeom.BoxI', (['llc', 'urc'], {}), '(llc, urc)\n', (7508, 7518), True, 'import lsst.geom as lsstGeom\n'), ((2554, 2585), 'numpy.sqrt', 'np.... |
# Authors : <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License : BSD 3-clause
import os.path as op
import warnings
from nose.tools import assert_true, assert_equal
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
from scipy import fftpack
from mne import read_events, Ep... | [
"mne.time_frequency._stockwell._precompute_st_windows",
"mne.utils.run_tests_if_main",
"nose.tools.assert_equal",
"numpy.arange",
"numpy.testing.assert_array_almost_equal",
"mne.io.read_raw_fif",
"numpy.testing.assert_allclose",
"mne.time_frequency._stockwell._st_power_itc",
"numpy.abs",
"mne.time... | [((781, 814), 'os.path.join', 'op.join', (['base_dir', '"""test_raw.fif"""'], {}), "(base_dir, 'test_raw.fif')\n", (788, 814), True, 'import os.path as op\n'), ((4656, 4675), 'mne.utils.run_tests_if_main', 'run_tests_if_main', ([], {}), '()\n', (4673, 4675), False, 'from mne.utils import run_tests_if_main\n'), ((712, 7... |
from pathlib import Path
import numpy as np
import pytest
from helpers import get_expected_if_it_exists
from nanomesh.image2mesh import plane2mesh
from nanomesh.image2mesh._mesher2d import Polygon
def block_image(shape=(10, 10)):
"""Generate test array with 4 block quadrants filled with 1 or 0."""
i, j = (n... | [
"numpy.testing.assert_equal",
"pathlib.Path",
"pytest.mark.xfail",
"numpy.testing.assert_allclose",
"nanomesh.image2mesh.plane2mesh",
"pytest.mark.parametrize",
"numpy.zeros",
"numpy.array",
"numpy.random.seed",
"helpers.get_expected_if_it_exists",
"numpy.all"
] | [((446, 580), 'pytest.mark.xfail', 'pytest.mark.xfail', (['pytest.OS_DOES_NOT_MATCH_DATA_GEN'], {'raises': 'AssertionError', 'reason': '"""https://github.com/hpgem/nanomesh/issues/144"""'}), "(pytest.OS_DOES_NOT_MATCH_DATA_GEN, raises=AssertionError,\n reason='https://github.com/hpgem/nanomesh/issues/144')\n", (463,... |
import pandas as pnd
import numpy as np
import JMPEstadisticas as jmp
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, 'datos.csv')
raw_data = open(filename)
data = np.loadtxt(raw_data, delimiter=";",skiprows=1)
data=pnd.DataFrame({'Pesos':data})
stats = jmp.JMPE... | [
"os.path.join",
"JMPEstadisticas.JMPEstadisticas",
"os.path.realpath",
"pandas.DataFrame",
"numpy.loadtxt"
] | [((150, 188), 'os.path.join', 'os.path.join', (['current_dir', '"""datos.csv"""'], {}), "(current_dir, 'datos.csv')\n", (162, 188), False, 'import os\n'), ((222, 269), 'numpy.loadtxt', 'np.loadtxt', (['raw_data'], {'delimiter': '""";"""', 'skiprows': '(1)'}), "(raw_data, delimiter=';', skiprows=1)\n", (232, 269), True,... |
#!/usr/bin/env python3
from __future__ import division, print_function
import string, time, random, msvcrt
import sounddevice as sd
import numpy as np
from scipy import io
import scipy.io.wavfile
import csv
from collections import Counter
import morse
SPS = 8000
LETTERS = string.ascii_uppercase
FREQ = 750
WPM = 25
F... | [
"numpy.iinfo",
"time.sleep",
"numpy.array",
"random.choices",
"numpy.sin",
"scipy.io.wavfile.getHistory",
"numpy.arange",
"argparse.ArgumentParser",
"morse.stringToMorse",
"numpy.concatenate",
"morse.farnsworthScaleFactor",
"morse.wpmToDps",
"random.shuffle",
"morse.morseToBoolArr",
"num... | [((788, 807), 'morse.wpmToDps', 'morse.wpmToDps', (['wpm'], {}), '(wpm)\n', (802, 807), False, 'import morse\n'), ((897, 933), 'morse.farnsworthScaleFactor', 'morse.farnsworthScaleFactor', (['wpm', 'fs'], {}), '(wpm, fs)\n', (924, 933), False, 'import morse\n'), ((2590, 2614), 'random.shuffle', 'random.shuffle', (['mes... |
from __future__ import print_function, division
import unittest, numpy as np
from pyscf import gto, tddft, scf
from pyscf.nao import bse_iter
from pyscf.nao import polariz_freq_osc_strength
from pyscf.data.nist import HARTREE2EV
class KnowValues(unittest.TestCase):
def test_0147_bse_h2o_rks_pz(self):
""" Intera... | [
"numpy.allclose",
"pyscf.gto.M",
"numpy.array",
"pyscf.tddft.TDDFT",
"numpy.savetxt",
"pyscf.nao.bse_iter",
"unittest.main",
"pyscf.scf.RKS",
"numpy.loadtxt",
"numpy.arange"
] | [((1398, 1413), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1411, 1413), False, 'import unittest, numpy as np\n'), ((343, 430), 'pyscf.gto.M', 'gto.M', ([], {'verbose': '(0)', 'atom': '"""O 0 0 0;H 0 0.489 1.074;H 0 0.489 -1.074"""', 'basis': '"""cc-pvdz"""'}), "(verbose=0, atom='O 0 0 0;H 0 0.489 1.074;H 0 0.... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from stock import Stock
plt.style.use('fivethirtyeight')
def solve(A, r_F, mu_R, sigma_R, verbose=False):
mu = r_F + (mu_R - r_F)**2 / (A * sigma_R**2)
sigma = (mu_R - r_F) / (A * sigma_R)
u = mu - A * sigma**2 / 2
... | [
"matplotlib.pyplot.subplots",
"stock.Stock",
"numpy.linspace",
"matplotlib.pyplot.style.use"
] | [((114, 146), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (127, 146), True, 'import matplotlib.pyplot as plt\n'), ((816, 830), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (828, 830), True, 'import matplotlib.pyplot as plt\n'), ((843, 874)... |
# Following architecture file copied from InferSent source code for load pretraining model
# In the later stage, this architecture will be modified to train a binary classifier (not 3 way softmax)
# We use the original code first to make sure the inference pipeline is good
# so that we don't have to worry about output ... | [
"pandas.read_csv",
"streamlit.write",
"io.BytesIO",
"requests.get",
"numpy.argsort",
"streamlit.subheader",
"streamlit.selectbox",
"streamlit.slider",
"numpy.arange",
"streamlit.title"
] | [((654, 689), 'streamlit.title', 'st.title', (['"""Covid-19 Twitter Search"""'], {}), "('Covid-19 Twitter Search')\n", (662, 689), True, 'import streamlit as st\n'), ((1138, 1224), 'streamlit.subheader', 'st.subheader', (['"""Here are some randomly selected most recent tweets about Covid-19"""'], {}), "(\n 'Here are... |
""" Implementation of Cosmic RIM estimator"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
physical_devices = tf.config.experimental.list_physical_devices('GPU')
print("\nphysical_devices\n", physical_devices)
world_size = len(phys... | [
"tensorflow.train.Checkpoint",
"tensorflow.GradientTape",
"sys.path.append",
"tensorflow.random.normal",
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"modelpoisson.check_2pt",
"numpy.linspace",
"rim_utils.build_rim_parallel",
"tensorflow.square",
"tensorflow.distribute.MirroredStrategy",... | [((199, 250), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (243, 250), True, 'import tensorflow as tf\n'), ((689, 710), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (703, 710), False, 'import matplotlib... |
import numpy as np
from numpy.testing import assert_allclose
from autumn.models.covid_19.mixing_matrix.mixing_adjusters.location_adjuster import LocationMixingAdjuster
MM = np.ones([16, 16])
HOME_MM = MM * 0.1
OTHER_LOCATIONS_MM = MM * 0.2
SCHOOL_MM = MM * 0.3
WORK_MM = MM * 0.6
MIXING_MATRICES = {
'all_location... | [
"numpy.testing.assert_allclose",
"autumn.models.covid_19.mixing_matrix.mixing_adjusters.location_adjuster.LocationMixingAdjuster",
"numpy.ones"
] | [((175, 192), 'numpy.ones', 'np.ones', (['[16, 16]'], {}), '([16, 16])\n', (182, 192), True, 'import numpy as np\n'), ((636, 714), 'autumn.models.covid_19.mixing_matrix.mixing_adjusters.location_adjuster.LocationMixingAdjuster', 'LocationMixingAdjuster', (['MIXING_MATRICES', 'mobility_funcs', 'microdistancing_funcs'], ... |
import numpy as np
from math import sin, cos
from ..manager import ConfigManager
point = {'type':'point', 'color':(255,0,0), 'lw':1, 'body':(10,10)}
points = {'type':'points', 'color':(255,0,0), 'lw':1, 'body':[(10,10),(100,200)]}
line = {'type':'line', 'color':(255,0,0), 'lw':1, 'style':'-', 'body':[(10,10),(100,200)... | [
"math.cos",
"numpy.dot",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"math.sin"
] | [((5759, 5788), 'numpy.linspace', 'np.linspace', (['(0)', '(np.pi * 2)', '(36)'], {}), '(0, np.pi * 2, 36)\n', (5770, 5788), True, 'import numpy as np\n'), ((5835, 5849), 'numpy.dot', 'np.dot', (['m', 'xys'], {}), '(m, xys)\n', (5841, 5849), True, 'import numpy as np\n'), ((5804, 5813), 'numpy.cos', 'np.cos', (['a'], {... |
import xarray as xr
import pandas as pd
from xgcm import Grid
import numpy as np
import matplotlib.pyplot as plt
from dask.diagnostics import ProgressBar
import os
import bsose.preprocess as pp
ds,xgrid = pp.load_bsose()
# Define time metric
# HACK: trouble with time difference metric, so here just setting up own ar... | [
"numpy.ones",
"os.stat",
"xarray.Dataset",
"os.path.isfile",
"bsose.preprocess.load_bsose",
"xarray.DataArray",
"dask.diagnostics.ProgressBar",
"os.system",
"pandas.to_datetime"
] | [((207, 222), 'bsose.preprocess.load_bsose', 'pp.load_bsose', ([], {}), '()\n', (220, 222), True, 'import bsose.preprocess as pp\n'), ((554, 609), 'xarray.DataArray', 'xr.DataArray', (['tmp'], {'dims': "['Zl']", 'coords': "{'Zl': ds['Zl']}"}), "(tmp, dims=['Zl'], coords={'Zl': ds['Zl']})\n", (566, 609), True, 'import x... |
import numpy as np
from skimage.morphology import skeletonize
from skan import Skeleton, summarize
import networkx as nx
import toolz as tz
def branch_classification(thres):
"""Predict the extent of branching.
Parameters
----------
thres: array
thresholded image to be analysed
scale: the ... | [
"skan.summarize",
"networkx.Graph",
"networkx.connected_components",
"numpy.sum",
"numpy.zeros",
"skan.Skeleton",
"networkx.shortest_path",
"numpy.isfinite",
"networkx.all_pairs_dijkstra_path_length",
"skimage.morphology.skeletonize"
] | [((599, 617), 'skimage.morphology.skeletonize', 'skeletonize', (['thres'], {}), '(thres)\n', (610, 617), False, 'from skimage.morphology import skeletonize\n'), ((629, 667), 'skan.Skeleton', 'Skeleton', (['skeleton'], {'source_image': 'thres'}), '(skeleton, source_image=thres)\n', (637, 667), False, 'from skan import S... |
import random as rn
import multiprocessing
import platform
import sys
import os
from pathlib import Path
import numpy as np
import pytest
if platform.system() != 'Windows':
if sys.version_info[1] >= 8:
try:
#multiprocessing.get_start_method() != 'fork'
multiprocessing.set_start_meth... | [
"quanguru.QuantumToolbox.states.basis",
"quanguru.QuantumToolbox.operators.sigmaz",
"sys.path.insert",
"numpy.sqrt",
"quanguru.QuantumToolbox.states.densityMatrix",
"os.getcwd",
"numpy.array",
"platform.system",
"quanguru.QuantumToolbox.operators.sigmam",
"quanguru.QuantumToolbox.operators.sigmax"... | [((436, 460), 'sys.path.insert', 'sys.path.insert', (['(0)', 'path'], {}), '(0, path)\n', (451, 460), False, 'import sys\n'), ((142, 159), 'platform.system', 'platform.system', ([], {}), '()\n', (157, 159), False, 'import platform\n'), ((2639, 2659), 'numpy.array', 'np.array', (['[[0], [1]]'], {}), '([[0], [1]])\n', (2... |
import gym
from gym.spaces import Discrete, Box
import numpy as np
class MemoryGame(gym.Env):
'''An instance of the memory game with noisy observations'''
def __init__(self, config={}):
self._length = config.get("length", 5)
self._num_cues =config.get("num_cues", 2)
self._noise = confi... | [
"numpy.random.randint",
"gym.spaces.Box",
"gym.spaces.Discrete",
"numpy.random.uniform"
] | [((696, 720), 'gym.spaces.Discrete', 'Discrete', (['self._num_cues'], {}), '(self._num_cues)\n', (704, 720), False, 'from gym.spaces import Discrete, Box\n'), ((825, 888), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self._noise', 'self.observation_space.shape'], {}), '(0, self._noise, self.observation_space.... |
from utils import copy_vocab
import run_setting
from train import train_lm, train_cls, get_model_name
from nltk import ToktokTokenizer as ToktokTokenizer_
from fastai.text.data import NumericalizeProcessor, TextList, ItemLists, TokenizeProcessor
from fastai.basic_data import DatasetType
from fastai.text.transform... | [
"run_setting.update",
"pandas.read_csv",
"nltk.ToktokTokenizer",
"numpy.array",
"fastai.text.data.TextList.from_df",
"train.train_cls",
"numpy.mean",
"argparse.ArgumentParser",
"pathlib.Path",
"train.train_lm",
"fastai.text.transform.Tokenizer",
"train.get_model_name",
"fastai.text.data.Toke... | [((559, 583), 'pathlib.Path', 'Path', (['"""../data/text_cls"""'], {}), "('../data/text_cls')\n", (563, 583), False, 'from pathlib import Path\n'), ((1272, 1346), 'fastai.text.data.TokenizeProcessor', 'TokenizeProcessor', ([], {'tokenizer': 'tokenizer', 'chunksize': '(10000)', 'mark_fields': '(False)'}), '(tokenizer=to... |
from tensorflow import keras as k
from tensorflow.keras import layers, models
import numpy as np
from tensorflow.python.keras.models import Model
class MockModel:
@classmethod
def get_model(cls) -> Model:
# Create a fake model. Basically, we simulate a text classifier where we have 3 words which are ... | [
"tensorflow.keras.layers.Embedding",
"tensorflow.keras.losses.BinaryCrossentropy",
"numpy.array",
"tensorflow.keras.layers.GlobalMaxPool1D"
] | [((835, 894), 'tensorflow.keras.layers.Embedding', 'layers.Embedding', ([], {'input_dim': '(4)', 'output_dim': '(3)', 'input_length': '(3)'}), '(input_dim=4, output_dim=3, input_length=3)\n', (851, 894), False, 'from tensorflow.keras import layers, models\n'), ((908, 932), 'tensorflow.keras.layers.GlobalMaxPool1D', 'la... |
#!/usr/bin/env python
import sys
# https://github.com/Callidon/pyHDT
import hdt
import numpy as np
from tqdm import tqdm
def generate_stats(doc):
n_edges = len(doc)
n_vertices = 0
# create integer mapping
vertices = set()
triples, c = doc.search_triples('', '', '')
for s, p, o in tqdm(triple... | [
"numpy.mean",
"tqdm.tqdm",
"hdt.HDTDocument",
"numpy.max",
"numpy.zeros",
"numpy.min"
] | [((309, 331), 'tqdm.tqdm', 'tqdm', (['triples'], {'total': 'c'}), '(triples, total=c)\n', (313, 331), False, 'from tqdm import tqdm\n'), ((524, 560), 'numpy.zeros', 'np.zeros', (['(n_vertices, 3)'], {'dtype': 'int'}), '((n_vertices, 3), dtype=int)\n', (532, 560), True, 'import numpy as np\n'), ((628, 650), 'tqdm.tqdm',... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from matplotlib.legend import Legend
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
from sklearn.metrics import mean_squared_error
"""
Função usada para fittar os dados.
https://docs.scipy.org... | [
"scipy.optimize.curve_fit",
"numpy.ceil",
"matplotlib.pyplot.style.use",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((71, 94), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (84, 94), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3514), 'numpy.linspace', 'np.linspace', (['self.pmin', 'last_point', 'n_interp_point'], {'endpoint': '(True)'}), '(self.pmin, last_point, n_interp_point, endp... |
# This is the simulation of our evolving RS model under the SECOND framework of our assumptions on edge weights.
import numpy as np
import random
import matplotlib.pyplot as plt
import powerlaw
import pandas as pd
class assumption_2nd:
# initializing the whole model
def __init__(self, beta, iterations, rating_... | [
"numpy.random.normal",
"powerlaw.Fit",
"numpy.random.rand",
"numpy.random.choice",
"numpy.random.multinomial",
"numpy.sum",
"numpy.zeros",
"numpy.random.sample",
"numpy.array",
"numpy.dot",
"numpy.random.randint",
"numpy.transpose",
"numpy.bincount",
"random.randint",
"numpy.set_printopt... | [((10483, 10500), 'powerlaw.Fit', 'powerlaw.Fit', (['seq'], {}), '(seq)\n', (10495, 10500), False, 'import powerlaw\n'), ((756, 783), 'numpy.zeros', 'np.zeros', (['self.rating_scale'], {}), '(self.rating_scale)\n', (764, 783), True, 'import numpy as np\n'), ((811, 840), 'numpy.zeros', 'np.zeros', (['(self.iterations + ... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"numpy.mean",
"numpy.zeros",
"numpy.argmax",
"numpy.max"
] | [((1205, 1226), 'numpy.max', 'np.max', (['attn'], {'axis': '(-1)'}), '(attn, axis=-1)\n', (1211, 1226), True, 'import numpy as np\n'), ((1238, 1250), 'numpy.mean', 'np.mean', (['max'], {}), '(max)\n', (1245, 1250), True, 'import numpy as np\n'), ((1323, 1348), 'numpy.zeros', 'np.zeros', (['[attn.shape[2]]'], {}), '([at... |
"""
Supplementary Fig. 2
"""
"""This script is used to benchmark GLIPH's performance across a variety of clustering thresholds by
varying the hamming distance parameter. This script required a local installation of GLIPH. The output
of this script is saved as GLIPH.csv and can be found in the github repository."""
i... | [
"seaborn.regplot",
"os.listdir",
"pandas.read_csv",
"numpy.asarray",
"os.path.join",
"numpy.sum",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"glob.glob",
"os.remove"
] | [((482, 503), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (492, 503), False, 'import os\n'), ((715, 729), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (727, 729), True, 'import pandas as pd\n'), ((804, 818), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (816, 818), True, 'import p... |
# Author: <NAME>(ICSRL)
# Created: 4/14/2020, 7:15 AM
# Email: <EMAIL>
import tensorflow as tf
import numpy as np
from network.loss_functions import huber_loss, mse_loss
from network.network import *
from numpy import linalg as LA
class initialize_network_DeepQLearning():
def __init__(self, cfg, name, vehicle_nam... | [
"tensorflow.local_variables_initializer",
"tensorflow.transpose",
"tensorflow.multiply",
"numpy.linalg.norm",
"network.loss_functions.mse_loss",
"tensorflow.log",
"tensorflow.Graph",
"numpy.mean",
"tensorflow.placeholder",
"numpy.max",
"tensorflow.trainable_variables",
"tensorflow.train.AdamOp... | [((341, 351), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (349, 351), True, 'import tensorflow as tf\n'), ((3605, 3652), 'numpy.zeros', 'np.zeros', ([], {'shape': '[xs.shape[0]]', 'dtype': 'np.float32'}), '(shape=[xs.shape[0]], dtype=np.float32)\n', (3613, 3652), True, 'import numpy as np\n'), ((3671, 3711), 'num... |
#
# From https://github.com/rguthrie3/BiLSTM-CRF/blob/master/model.py
#
import dynet
import numpy as np
class CRF():
def __init__(self, model, id_to_tag):
self.id_to_tag = id_to_tag
self.tag_to_id = {tag: id for id, tag in list(id_to_tag.items())}
self.n_tags = len(self.id_to_tag)
... | [
"dynet.scalarInput",
"dynet.exp",
"numpy.argmax",
"dynet.pick",
"dynet.inputVector",
"dynet.concatenate"
] | [((741, 761), 'dynet.scalarInput', 'dynet.scalarInput', (['(0)'], {}), '(0)\n', (758, 761), False, 'import dynet\n'), ((2709, 2739), 'dynet.inputVector', 'dynet.inputVector', (['init_alphas'], {}), '(init_alphas)\n', (2726, 2739), False, 'import dynet\n'), ((3746, 3775), 'dynet.inputVector', 'dynet.inputVector', (['ini... |
import numpy as np
shape = tuple(map(int,input().strip().split()))
zeros = np.zeros(shape,dtype=np.int32)
ones = np.ones(shape,dtype=np.int32)
print(zeros)
print(ones)
| [
"numpy.zeros",
"numpy.ones"
] | [((75, 106), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.int32'}), '(shape, dtype=np.int32)\n', (83, 106), True, 'import numpy as np\n'), ((113, 143), 'numpy.ones', 'np.ones', (['shape'], {'dtype': 'np.int32'}), '(shape, dtype=np.int32)\n', (120, 143), True, 'import numpy as np\n')] |
import pyconll
import urllib
import numpy as np
from pathlib import Path
from keras.preprocessing.sequence import pad_sequences
'''
Universal Dependencies Treebank Dataset
https://universaldependencies.org
'''
def read_conllu(path):
data = pyconll.load_from_file(path)
tagged_sentences = list()
t = 0
... | [
"pyconll.load_from_file",
"urllib.request.urlretrieve",
"pathlib.Path",
"numpy.array",
"numpy.zeros",
"keras.preprocessing.sequence.pad_sequences"
] | [((247, 275), 'pyconll.load_from_file', 'pyconll.load_from_file', (['path'], {}), '(path)\n', (269, 275), False, 'import pyconll\n'), ((1787, 1810), 'numpy.array', 'np.array', (['cat_sequences'], {}), '(cat_sequences)\n', (1795, 1810), True, 'import numpy as np\n'), ((1952, 1969), 'pathlib.Path', 'Path', (['UDTB_FOLDER... |
#!/usr/bin/env python
import rospy, sys
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2, os, struct
from sensor_msgs.msg import CompressedImage
import numpy as np
class PngWriter:
def __init__(self):
self.save_root = ""
if rospy.has_param("save_root")... | [
"cv2.imwrite",
"rospy.init_node",
"rospy.get_param",
"rospy.has_param",
"os.path.join",
"numpy.fromstring",
"cv_bridge.CvBridge",
"struct.unpack",
"rospy.spin",
"rospy.Subscriber",
"rospy.loginfo"
] | [((3950, 3991), 'rospy.init_node', 'rospy.init_node', (['"""writer"""'], {'anonymous': '(True)'}), "('writer', anonymous=True)\n", (3965, 3991), False, 'import rospy, sys\n'), ((292, 320), 'rospy.has_param', 'rospy.has_param', (['"""save_root"""'], {}), "('save_root')\n", (307, 320), False, 'import rospy, sys\n'), ((53... |
"""CLI for optimal subgroups based on individual preferences"""
from argparse import ArgumentParser
import pandas as pd
import numpy as np
from pulp import LpProblem, LpMinimize, LpVariable, lpSum
NAN_VALUE = 10000 # Arbitrarily high value to force optimization away from empty choices
def optimize():
"""Run the ... | [
"pulp.LpProblem",
"argparse.ArgumentParser",
"numpy.array",
"numpy.isnan",
"numpy.nanmax",
"pandas.read_excel",
"pulp.LpVariable"
] | [((369, 442), 'pandas.read_excel', 'pd.read_excel', (['args.file_path', '"""Sheet1"""'], {'index_col': 'None', 'na_values': "['NA']"}), "(args.file_path, 'Sheet1', index_col=None, na_values=['NA'])\n", (382, 442), True, 'import pandas as pd\n'), ((454, 499), 'pulp.LpProblem', 'LpProblem', (['"""Optimal 10x Grouping"""'... |
import os
import numpy as np
import xarray as xr
import pytest
import intake_io
from .fixtures import *
def test_round_trip_uncompressed(tmp_path):
fpath = os.path.join(tmp_path, "uncompressed.klb")
if os.path.exists(fpath):
os.remove(fpath)
for img0, shape, axes, spacing, units in random_images(... | [
"os.path.exists",
"numpy.mean",
"os.path.getsize",
"intake_io.source.KlbSource",
"os.path.join",
"intake_io.get_spacing",
"intake_io.get_axes",
"intake_io.imload",
"intake_io.imsave",
"os.remove"
] | [((162, 204), 'os.path.join', 'os.path.join', (['tmp_path', '"""uncompressed.klb"""'], {}), "(tmp_path, 'uncompressed.klb')\n", (174, 204), False, 'import os\n'), ((212, 233), 'os.path.exists', 'os.path.exists', (['fpath'], {}), '(fpath)\n', (226, 233), False, 'import os\n'), ((243, 259), 'os.remove', 'os.remove', (['f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : memory.py
# @Author: zixiao
# @Date : 2019-04-01
# @Desc :
import numpy as np
class SumTree(object):
data_index = 0
def __init__(self, size, frame_len, w, h):
self.data_size = size
self.tree_size = 2 * size - 1
self.tree = np.... | [
"numpy.minimum",
"numpy.power",
"numpy.max",
"numpy.zeros",
"numpy.random.uniform",
"numpy.concatenate",
"numpy.min"
] | [((317, 359), 'numpy.zeros', 'np.zeros', (['self.tree_size'], {'dtype': 'np.float32'}), '(self.tree_size, dtype=np.float32)\n', (325, 359), True, 'import numpy as np\n'), ((383, 421), 'numpy.zeros', 'np.zeros', (['(size, w, h)'], {'dtype': 'np.uint8'}), '((size, w, h), dtype=np.uint8)\n', (391, 421), True, 'import nump... |
#!/usr/bin/env python
"""
Score the predictions with gold labels, using precision, recall and F1 metrics.
"""
import argparse
import sys, os
from collections import Counter
import numpy as np
from pathlib import Path
NO_RELATION = "no_relation"
def parse_arguments():
parser = argparse.ArgumentP... | [
"numpy.mean",
"argparse.ArgumentParser",
"pathlib.Path",
"collections.Counter",
"numpy.std",
"sys.stdout.write"
] | [((302, 392), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Score a prediction file using the gold labels."""'}), "(description=\n 'Score a prediction file using the gold labels.')\n", (325, 392), False, 'import argparse\n'), ((772, 781), 'collections.Counter', 'Counter', ([], {}), '... |
import numpy as np
from skimage.morphology import white_tophat as skimage_white_tophat
from skimage.exposure import rescale_intensity
from skimage.restoration import richardson_lucy
def white_tophat(image, radius):
"""
"""
selem = np.ones((radius,)*image.ndim)
return skimage_white_tophat(image, selem... | [
"numpy.abs",
"skimage.morphology.white_tophat",
"numpy.ones",
"numpy.conj",
"numpy.fft.fftn",
"skimage.restoration.richardson_lucy",
"numpy.fft.ifftn"
] | [((246, 277), 'numpy.ones', 'np.ones', (['((radius,) * image.ndim)'], {}), '((radius,) * image.ndim)\n', (253, 277), True, 'import numpy as np\n'), ((287, 327), 'skimage.morphology.white_tophat', 'skimage_white_tophat', (['image'], {'selem': 'selem'}), '(image, selem=selem)\n', (307, 327), True, 'from skimage.morpholog... |
import pandas as pd
import math
from pandas import read_csv, to_numeric
import numpy
from numpy import nan
import statistics as sta
#df = pd.read_csv('/Users/king/Documents/python/control2/athlete_events.csv')
fields = ['Height', 'Year', "Sport"]
df = pd.read_csv('/Users/king/Documents/python/control2/athlete_even... | [
"statistics.mean",
"pandas.read_csv",
"numpy.sort",
"math.sqrt",
"pandas.to_numeric"
] | [((257, 371), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/king/Documents/python/control2/athlete_events.csv"""'], {'skipinitialspace': '(True)', 'usecols': 'fields'}), "('/Users/king/Documents/python/control2/athlete_events.csv',\n skipinitialspace=True, usecols=fields)\n", (268, 371), True, 'import pandas as pd\... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import glob
import re
import sys
import numpy as np
if 'linux' in sys.platform:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
else:
import matplotlib.pyplot as plt
def get_args():
parser = argparse.ArgumentP... | [
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"numpy.argmin",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend"
] | [((171, 192), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (185, 192), False, 'import matplotlib\n'), ((302, 327), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (325, 327), False, 'import argparse\n'), ((558, 605), 'numpy.argmin', 'np.argmin', (['((pre_rec[:, 0] - pre_... |
import tensorflow.keras
from tensorflow.keras import layers
import os
import matplotlib.pyplot as plt
from PIL import Image
#from numpy import asarray
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preproc... | [
"tensorflow.config.run_functions_eagerly",
"tensorflow.multiply",
"tensorflow.GradientTape",
"numpy.array",
"tensorflow.keras.models.load_model",
"tensorflow.compat.v1.Session",
"numpy.mean",
"os.listdir",
"tensorflow.keras.backend.mean",
"numpy.max",
"tensorflow.convert_to_tensor",
"numpy.max... | [((625, 662), 'tensorflow.config.run_functions_eagerly', 'tf.config.run_functions_eagerly', (['(True)'], {}), '(True)\n', (656, 662), True, 'import tensorflow as tf\n'), ((883, 918), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'config'}), '(config=config)\n', (903, 918), True, 'import tensor... |
from utils_pos import get_word_tag, preprocess
import pandas as pd
from collections import defaultdict
import math
import numpy as np
import pickle
def test_create_dictionaries(target, training_corpus, vocab):
successful_cases = 0
failed_cases = []
test_cases = [
{
"name": "default_cas... | [
"numpy.array",
"numpy.all",
"numpy.allclose",
"numpy.isclose"
] | [((16263, 16322), 'numpy.allclose', 'np.allclose', (['result[0:5, 0:5]', "test_case['expected']['0:5']"], {}), "(result[0:5, 0:5], test_case['expected']['0:5'])\n", (16274, 16322), True, 'import numpy as np\n'), ((16799, 16864), 'numpy.allclose', 'np.allclose', (['result[30:35, 30:35]', "test_case['expected']['30:35']"... |
import cv2 as cv
import numpy as np
img = cv.imread('Photos/cats.jpg')
cv.imshow('Cats', img)
blank = np.zeros(img.shape[:2], dtype= 'uint8')
cv.imshow("Blank Image", blank)
mask = cv.circle(blank.copy(), (img.shape[1]//2, img.shape[0]//2), 100, 255, -1)
cv.imshow("mask", mask)
mask2 = cv.rectangle(blank.copy(), (i... | [
"cv2.bitwise_and",
"cv2.imshow",
"numpy.zeros",
"cv2.waitKey",
"cv2.imread"
] | [((43, 71), 'cv2.imread', 'cv.imread', (['"""Photos/cats.jpg"""'], {}), "('Photos/cats.jpg')\n", (52, 71), True, 'import cv2 as cv\n'), ((72, 94), 'cv2.imshow', 'cv.imshow', (['"""Cats"""', 'img'], {}), "('Cats', img)\n", (81, 94), True, 'import cv2 as cv\n'), ((104, 142), 'numpy.zeros', 'np.zeros', (['img.shape[:2]'],... |
import numpy as np
from randomcsv.CategoryColumn import CategoryColumn
def test_should_pick_class_at_random():
column = CategoryColumn('Class', ['A', 'B', 'C'], random_state=42)
series = column.generate_entries(5)
assert series.at[0] == 'C'
assert series.at[1] == 'A'
assert series.at[2] == 'C'
... | [
"randomcsv.CategoryColumn.CategoryColumn",
"numpy.isnan"
] | [((126, 183), 'randomcsv.CategoryColumn.CategoryColumn', 'CategoryColumn', (['"""Class"""', "['A', 'B', 'C']"], {'random_state': '(42)'}), "('Class', ['A', 'B', 'C'], random_state=42)\n", (140, 183), False, 'from randomcsv.CategoryColumn import CategoryColumn\n'), ((430, 484), 'randomcsv.CategoryColumn.CategoryColumn',... |
import argparse
import logging
import os
import pickle
import shutil
import settings
import torch
import numpy as np
from IPython.core.debugger import Pdb
LOG_FILE = 'log.txt'
_LOG_LEVEL_STRINGS = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']
EPSILON = 0.0000001
def clean_label_list(ylist):
#remove duplicate... | [
"os.path.exists",
"torch.max",
"argparse.ArgumentTypeError",
"torch.exp",
"shutil.copyfile",
"torch.save",
"numpy.loadtxt",
"numpy.arange"
] | [((1395, 1416), 'numpy.loadtxt', 'np.loadtxt', (['pred_file'], {}), '(pred_file)\n', (1405, 1416), True, 'import numpy as np\n'), ((2644, 2675), 'os.path.exists', 'os.path.exists', (['base_model_file'], {}), '(base_model_file)\n', (2658, 2675), False, 'import os\n'), ((3317, 3351), 'torch.save', 'torch.save', (['state'... |
# Copyright 2021 ETH Zurich and the NPBench authors. All rights reserved.
import numpy as np
def initialize(M, N, datatype=np.float64):
alpha = datatype(1.5)
beta = datatype(1.2)
C = np.fromfunction(lambda i, j: ((i + j) % 100) / M, (M, N),
dtype=datatype)
B = np.fromfunction(... | [
"numpy.fromfunction",
"numpy.empty"
] | [((198, 269), 'numpy.fromfunction', 'np.fromfunction', (['(lambda i, j: (i + j) % 100 / M)', '(M, N)'], {'dtype': 'datatype'}), '(lambda i, j: (i + j) % 100 / M, (M, N), dtype=datatype)\n', (213, 269), True, 'import numpy as np\n'), ((304, 379), 'numpy.fromfunction', 'np.fromfunction', (['(lambda i, j: (N + i - j) % 10... |
import numpy as np
class BinomialModel(object):
def __init__(self, *args):
# black == False. args: S0, u, d, R
# or
# black == True. args: S0, u, d, R, q
self.S0 = args[0]
self.u = args[1]
self.d = args[2]
self.R = args[3]
self.euro = args[5]
... | [
"numpy.array",
"numpy.linalg.solve",
"numpy.round"
] | [((2880, 2900), 'numpy.array', 'np.array', (['self.S[-1]'], {}), '(self.S[-1])\n', (2888, 2900), True, 'import numpy as np\n'), ((4704, 4776), 'numpy.array', 'np.array', (['[[self.S[i][j], self.R ** i], [self.S[i][j + 1], self.R ** i]]'], {}), '([[self.S[i][j], self.R ** i], [self.S[i][j + 1], self.R ** i]])\n', (4712,... |
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"logging.getLogger",
"numpy.fromfile",
"detectron.utils.blob.prep_im_for_blob",
"numpy.array",
"copy.deepcopy",
"numpy.where",
"detectron.roi_data.retinanet.add_retinanet_blobs",
"detectron.utils.blob.im_list_to_blob_andPose",
"detectron.roi_data.fast_rcnn.get_fast_rcnn_blob_names",
"cv2.resize",
... | [((1449, 1476), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1466, 1476), False, 'import logging\n'), ((3464, 3497), 'numpy.array', 'np.array', (['[100]'], {'dtype': 'np.float32'}), '([100], dtype=np.float32)\n', (3472, 3497), True, 'import numpy as np\n'), ((6020, 6061), 'detectron.ut... |
from sklearn.ensemble import RandomForestRegressor
from sklearn.utils.validation import check_is_fitted
from joblib import Parallel, delayed
from sklearn.ensemble._base import _partition_estimators
import threading
import numpy as np
class RandomForestRegressor2(RandomForestRegressor):
def __init__(self,
... | [
"sklearn.utils.validation.check_is_fitted",
"numpy.mean",
"numpy.max",
"joblib.Parallel",
"sklearn.ensemble._base._partition_estimators",
"numpy.std",
"joblib.delayed"
] | [((1453, 1489), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""estimators_"""'], {}), "(self, 'estimators_')\n", (1468, 1489), False, 'from sklearn.utils.validation import check_is_fitted\n'), ((1632, 1685), 'sklearn.ensemble._base._partition_estimators', '_partition_estimators', (['self.n... |
import cv2, base64, json, os, requests
import numpy as np
from fileTools import *
from trainTools import *
from imgTools import *
from eightPuzzle import *
with np.load('./record/knnTrainData.npz') as data:
print(data.files)
trainData = data['trainData']
responses = data['responses']
knn = cv2.... | [
"cv2.ml.KNearest_create",
"os.listdir",
"numpy.load"
] | [((316, 340), 'cv2.ml.KNearest_create', 'cv2.ml.KNearest_create', ([], {}), '()\n', (338, 340), False, 'import cv2, base64, json, os, requests\n'), ((500, 522), 'os.listdir', 'os.listdir', (['"""./source"""'], {}), "('./source')\n", (510, 522), False, 'import cv2, base64, json, os, requests\n'), ((162, 198), 'numpy.loa... |
# -*- coding: utf-8 -*-#
'''
# Name: LSTMCell_1_1
# Description: Implement the basic functions of lstm cell and linear cell
# Can't support batch input
# Author: super
# Date: 2020/6/18
'''
import sys
import math
import numpy as np
from MiniFramework.Layer import *
from MiniFramewo... | [
"numpy.dot",
"numpy.zeros",
"numpy.multiply"
] | [((556, 606), 'numpy.zeros', 'np.zeros', (['(4 * self.hidden_size, self.hidden_size)'], {}), '((4 * self.hidden_size, self.hidden_size))\n', (564, 606), True, 'import numpy as np\n'), ((625, 674), 'numpy.zeros', 'np.zeros', (['(4 * self.input_size, self.hidden_size)'], {}), '((4 * self.input_size, self.hidden_size))\n'... |
# Copyright 2019 <NAME>
# Licensed under the MIT License (the "License").
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at https://mit-license.org
# February 2019
# This script tests color function of filterizePy package.
import pytest
import numpy as np
impo... | [
"filterizePy.greenscale.greenscale",
"numpy.array",
"numpy.array_equal",
"imghdr.what",
"pytest.raises"
] | [((495, 800), 'numpy.array', 'np.array', (['[[[255, 255, 255], [255, 255, 255], [255, 255, 255]], [[255, 255, 255], [\n 255, 255, 255], [255, 255, 255]], [[255, 255, 255], [255, 255, 255], [\n 255, 255, 255]], [[255, 255, 255], [255, 255, 255], [255, 255, 255]], [\n [255, 255, 255], [255, 255, 255], [255, 255,... |
# Programowanie I R
# Pakiet NumPy
import numpy as np
arr_list = np.array([1, 2, 3, 4, 5])
print(arr_list)
print(type(arr_list))
print()
arr_tuple = np.array((1, 2, 3, 4, 5))
print(arr_tuple)
print(type(arr_tuple))
print()
arr = np.array(42)
print(arr)
print(arr.ndim)
print()
arr = np.array([[1, 2, 3], [4, 5, 6]... | [
"numpy.multiply",
"numpy.add",
"numpy.subtract",
"numpy.array",
"numpy.divide"
] | [((67, 92), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (75, 92), True, 'import numpy as np\n'), ((153, 178), 'numpy.array', 'np.array', (['(1, 2, 3, 4, 5)'], {}), '((1, 2, 3, 4, 5))\n', (161, 178), True, 'import numpy as np\n'), ((235, 247), 'numpy.array', 'np.array', (['(42)'], {}), '... |
import sys
from models.lstm_vae import *
from models.lstm import *
from models.lstm_vae_output import *
from models.nn import *
from keras.models import model_from_json
import pickle as pkl
from functions import *
from constants import *
from scipy import spatial
from rake_nltk import Rake
import numpy as np
glove_pat... | [
"numpy.array",
"rake_nltk.Rake",
"numpy.argmax",
"scipy.spatial.KDTree"
] | [((2854, 2860), 'rake_nltk.Rake', 'Rake', ([], {}), '()\n', (2858, 2860), False, 'from rake_nltk import Rake\n'), ((6019, 6039), 'numpy.array', 'np.array', (['train_data'], {}), '(train_data)\n', (6027, 6039), True, 'import numpy as np\n'), ((8112, 8123), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (8120, 8123), T... |
import numpy as np
import matplotlib.pyplot as plt
import knn
def knn_plot(x, y, k):
plt.figure(figsize=(10, 10))
color = ['red', 'blue']
for label in np.unique(y):
p = x[y == label]
plt.scatter(p[:, 0], p[:, 1], s=3, c=color[label])
xmin = np.min(x[:, 0])
xmax = np.max(x[:, 0... | [
"numpy.unique",
"knn.knn",
"numpy.max",
"matplotlib.pyplot.contour",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"numpy.min",
"matplotlib.pyplot.title",
"numpy.arange"
] | [((93, 121), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (103, 121), True, 'import matplotlib.pyplot as plt\n'), ((169, 181), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (178, 181), True, 'import numpy as np\n'), ((280, 295), 'numpy.min', 'np.min', (['x[:, 0]'... |
# Copyright (c) AIRBUS and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import numpy as np
import gym
from typing import Callable
from collections.abc import Iterable
from skde... | [
"numpy.sqrt",
"numpy.random.random_sample",
"numpy.random.random_integers",
"numpy.array",
"numpy.zeros",
"numpy.isnan",
"numpy.random.seed"
] | [((864, 883), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n', (872, 883), True, 'import numpy as np\n'), ((905, 924), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n', (913, 924), True, 'import numpy as np\n'), ((951, 970), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n',... |
### First draft of a Quantum Circuit object
import numpy as np
def kron(*args):
## multiple kronecker product
qb = np.array([[1.0]])
for q in args:
qb = np.kron(qb, q)
return qb
def n_kron(n, vector):
## n kronecker product with itself
ret = np.array([[1.0]])
for _... | [
"numpy.eye",
"numpy.sqrt",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.conjugate",
"numpy.kron",
"numpy.array",
"numpy.dot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((133, 150), 'numpy.array', 'np.array', (['[[1.0]]'], {}), '([[1.0]])\n', (141, 150), True, 'import numpy as np\n'), ((292, 309), 'numpy.array', 'np.array', (['[[1.0]]'], {}), '([[1.0]])\n', (300, 309), True, 'import numpy as np\n'), ((672, 681), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (678, 681), True, 'import... |
import numpy as np
class CrossEntropy(object):
def __init__(self):
pass
def forward(self, out, y):
loss = lambda x, y: -(y*np.log(x +.0001)) - ((1.01 - y) * np.log(1.01 - x))
if out.ndim > 1:
return np.mean(loss(out, y))
else:
return loss(ou... | [
"numpy.log",
"numpy.subtract"
] | [((383, 402), 'numpy.subtract', 'np.subtract', (['out', 'y'], {}), '(out, y)\n', (394, 402), True, 'import numpy as np\n'), ((195, 211), 'numpy.log', 'np.log', (['(1.01 - x)'], {}), '(1.01 - x)\n', (201, 211), True, 'import numpy as np\n'), ((161, 179), 'numpy.log', 'np.log', (['(x + 0.0001)'], {}), '(x + 0.0001)\n', (... |
#!/usr/bin/env python
""" Empirically simulate the birthday paradox
The birthday paradox is the surprisingly high change that two
people in a group of people share the same birthday.
See https://en.wikipedia.org/wiki/Birthday_problem for details.
"""
import random
from matplotlib import pyplot as plt
import numpy... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"numpy.cumsum",
"random.randint",
"matplotlib.pyplot.show"
] | [((956, 991), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of simulations"""'], {}), "('Number of simulations')\n", (966, 991), True, 'from matplotlib import pyplot as plt\n'), ((996, 1071), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of people in room when first birthday collision occurs"""'], {})... |
import codecademylib
import numpy as np
import matplotlib.pyplot as plt
survey_responses = ['Ceballos', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos','Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan',... | [
"numpy.mean",
"matplotlib.pyplot.hist",
"numpy.random.binomial",
"matplotlib.pyplot.show"
] | [((1378, 1409), 'numpy.mean', 'np.mean', (['(possible_surveys < 0.5)'], {}), '(possible_surveys < 0.5)\n', (1385, 1409), True, 'import numpy as np\n'), ((1565, 1614), 'matplotlib.pyplot.hist', 'plt.hist', (['possible_surveys'], {'bins': '(20)', 'range': '(0, 1)'}), '(possible_surveys, bins=20, range=(0, 1))\n', (1573, ... |
"""
Define discrete action spaces for Gym Retro environments with a limited set of button combos
"""
import gym
import numpy as np
import retro
class Discretizer(gym.ActionWrapper):
"""
Wrap a gym environment and make it use discrete actions.
Args:
combos: ordered list of lists of valid button co... | [
"numpy.array",
"retro.make"
] | [((1316, 1411), 'retro.make', 'retro.make', ([], {'game': '"""SonicTheHedgehog-Genesis"""', 'use_restricted_actions': 'retro.Actions.DISCRETE'}), "(game='SonicTheHedgehog-Genesis', use_restricted_actions=retro.\n Actions.DISCRETE)\n", (1326, 1411), False, 'import retro\n'), ((1501, 1544), 'retro.make', 'retro.make',... |
# coding: utf-8
# Revert Classification - Prediction
# ===
#
# Building a classifier to predict reverts and produce calibrated propensity scores for being reverted.
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
import bz2
import sqlite3
import difflib
import gzip
import json... | [
"pandas.read_pickle",
"argparse.ArgumentParser",
"pandas.read_csv",
"os.path.join",
"os.path.splitext",
"datetime.datetime.now",
"numpy.array",
"joblib.load",
"pandas.DataFrame",
"sklearn.preprocessing.scale"
] | [((731, 756), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (754, 756), False, 'import argparse\n'), ((978, 1067), 'os.path.join', 'os.path.join', (['"""/export/scratch2/levon003/repos/wiki-ores-feedback"""', '"""data"""', '"""derived"""'], {}), "('/export/scratch2/levon003/repos/wiki-ores-fee... |
from typing import Tuple, Iterable, List, Union, TypeVar, ClassVar, Any
import numpy as np
import re
from .utils import split
State = np.array
Action = np.array
Reward = float
Done = bool
Datum = Tuple[State, Action, Reward, State, Done]
Data = Tuple[Iterable[State], Iterable[Action], Iterable[Reward], Iterable[State]... | [
"re.compile",
"numpy.random.choice",
"numpy.array",
"numpy.savez_compressed",
"numpy.load"
] | [((807, 833), 're.compile', 're.compile', (['"""[^/]+\\\\.npz$"""'], {}), "('[^/]+\\\\.npz$')\n", (817, 833), False, 'import re\n'), ((1711, 1769), 'numpy.random.choice', 'np.random.choice', (['num_data'], {'size': 'batch_size', 'replace': '(False)'}), '(num_data, size=batch_size, replace=False)\n', (1727, 1769), True,... |
#!/usr/bin/python3
"""
/**
******************************************************************************
* @file dominant_attribute.py
* @author <NAME>
* $Rev: 1 $
* $Date: Sat Nov 17 15:12:04 CST 2018 $
* @brief Functions related to Dominant Attribute Algorithm
*************************************************... | [
"numpy.where",
"numpy.max",
"numpy.sum",
"numpy.min",
"pandas.DataFrame",
"numpy.log2",
"pandas.concat"
] | [((2703, 2717), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2715, 2717), True, 'import pandas as pd\n'), ((4603, 4673), 'numpy.sum', 'np.sum', (['(-(num_each_group / num_total) * conditional_entropy_each_group)'], {}), '(-(num_each_group / num_total) * conditional_entropy_each_group)\n', (4609, 4673), True, ... |
import os
import numpy as np
from src.base_class.vocoder.htk_io import HTK_Parm_IO
from util import file_util, log_util
log = log_util.get_logger("acoustic tool")
def interpolate_f0(data):
'''
interpolate F0, if F0 has already been interpolated, nothing will be changed after passing this function
:... | [
"numpy.reshape",
"util.log_util.get_logger",
"os.path.dirname",
"numpy.zeros",
"os.path.basename",
"numpy.concatenate",
"util.file_util.array_to_binary_file",
"src.base_class.vocoder.htk_io.HTK_Parm_IO"
] | [((129, 165), 'util.log_util.get_logger', 'log_util.get_logger', (['"""acoustic tool"""'], {}), "('acoustic tool')\n", (148, 165), False, 'from util import file_util, log_util\n'), ((364, 396), 'numpy.reshape', 'np.reshape', (['data', '(data.size, 1)'], {}), '(data, (data.size, 1))\n', (374, 396), True, 'import numpy a... |
from collections import OrderedDict
import os
from os import path as osp
import numpy as np
import torch
from torch import optim
from torch.distributions import Normal
from torch.utils.data import DataLoader
from torch.nn import functional as F
from torchvision.utils import save_image
from rlkit.data_management.images ... | [
"rlkit.torch.pytorch_util.randn",
"matplotlib.pyplot.savefig",
"numpy.arange",
"matplotlib.pyplot.clf",
"os.path.join",
"torch.stack",
"numpy.array",
"torch.norm",
"rlkit.torch.pytorch_util.get_numpy",
"torchvision.utils.save_image",
"torch.cat",
"rlkit.torch.pytorch_util.zeros"
] | [((2945, 2986), 'os.path.join', 'osp.join', (['self.log_dir', "('r%d.png' % epoch)"], {}), "(self.log_dir, 'r%d.png' % epoch)\n", (2953, 2986), True, 'from os import path as osp\n'), ((3179, 3218), 'rlkit.torch.pytorch_util.randn', 'ptu.randn', (['(64)', 'self.representation_size'], {}), '(64, self.representation_size)... |
import numpy as np
import torch.utils.data
def qm9_collate_batch(batch):
#print(batch)
drug1, drug2, label1, label2 = list(zip(*batch))
ddi_idxs1, ddi_idxs2 = collate_drug_pairs(drug1, drug2)
drug1 = (*collate_drugs(drug1), *ddi_idxs1)
drug2 = (*collate_drugs(drug2), *ddi_idxs2)
label1 = collate_labels(label1... | [
"numpy.stack",
"numpy.array",
"numpy.vstack",
"numpy.hstack"
] | [((1128, 1144), 'numpy.stack', 'np.stack', (['labels'], {}), '(labels)\n', (1136, 1144), True, 'import numpy as np\n'), ((1304, 1346), 'numpy.vstack', 'np.vstack', (["[d['atom_feat'] for d in drugs]"], {}), "([d['atom_feat'] for d in drugs])\n", (1313, 1346), True, 'import numpy as np\n'), ((1378, 1420), 'numpy.hstack'... |
import gtimer as gt
from rlkit.core import logger
from ROLL.online_LSTM_replay_buffer import OnlineLSTMRelabelingBuffer
import rlkit.torch.vae.vae_schedules as vae_schedules
import ROLL.LSTM_schedule as lstm_schedules
from rlkit.torch.torch_rl_algorithm import (
TorchBatchRLAlgorithm,
)
import rlkit.torch.pytorch_u... | [
"os.path.exists",
"torch.multiprocessing.Pipe",
"threading.Thread",
"numpy.load",
"gtimer.stamp",
"rlkit.core.logger.get_snapshot_dir"
] | [((3062, 3086), 'gtimer.stamp', 'gt.stamp', (['"""vae training"""'], {}), "('vae training')\n", (3070, 3086), True, 'import gtimer as gt\n'), ((8488, 8494), 'torch.multiprocessing.Pipe', 'Pipe', ([], {}), '()\n', (8492, 8494), False, 'from torch.multiprocessing import Process, Pipe\n'), ((12963, 12989), 'os.path.exists... |
#!/home/hiroya/Documents/Git-Repos/Lets_Play_Your_Waveform/.venv/bin/python
# -*- coding: utf-8 -*-
import cv2
import sys
import struct
import pyaudio
import pygame
import numpy as np
from matplotlib import pyplot
import matplotlib.gridspec as gridspec
from pygame.locals import K_s, K_d, K_f, K_g, K_h, K_j, K_k, K_l
f... | [
"numpy.sqrt",
"pygame.init",
"pygame.quit",
"cv2.destroyAllWindows",
"sys.exit",
"pygame.event.pump",
"numpy.where",
"pygame.display.set_mode",
"numpy.fft.fft",
"matplotlib.pyplot.close",
"matplotlib.gridspec.GridSpec",
"pygame.display.update",
"pygame.Rect",
"numpy.hamming",
"matplotlib... | [((8863, 8876), 'pygame.init', 'pygame.init', ([], {}), '()\n', (8874, 8876), False, 'import pygame\n'), ((8890, 8927), 'pygame.display.set_mode', 'pygame.display.set_mode', (['DISPLAY_SIZE'], {}), '(DISPLAY_SIZE)\n', (8913, 8927), False, 'import pygame\n'), ((8932, 8975), 'pygame.display.set_caption', 'pygame.display.... |
import numpy as np
from predictions.utils.future import set_future_series
def random_forecast(series, steps_ahead=3, freq='D', series_name='random'):
"""
Function fits data into the random values within the interval given by a one standard deviation of a data.
INPUT:
:param series: pandas Series of ... | [
"predictions.utils.future.set_future_series",
"numpy.random.uniform"
] | [((649, 708), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '_bottom', 'high': '_top', 'size': 'steps_ahead'}), '(low=_bottom, high=_top, size=steps_ahead)\n', (666, 708), True, 'import numpy as np\n'), ((722, 862), 'predictions.utils.future.set_future_series', 'set_future_series', ([], {'forecasted_values'... |
from kdaHDFE.legacy.DemeanDataframe import demean_dataframe
from kdaHDFE.formula_transform import formula_transform
from kdaHDFE.legacy.OLSFixed import OLSFixed
from kdaHDFE.robust_error import robust_err
from kdaHDFE.clustering import *
from kdaHDFE.calculate_df import cal_df
from kdaHDFE.legacy.CalFullModel import ca... | [
"kdaHDFE.calculate_df.cal_df",
"kdaHDFE.legacy.DemeanDataframe.demean_dataframe",
"numpy.mat",
"numpy.abs",
"numpy.sqrt",
"kdaHDFE.legacy.OLSFixed.OLSFixed",
"kdaHDFE.robust_error.robust_err",
"numpy.diag",
"statsmodels.api.add_constant",
"kdaHDFE.formula_transform.formula_transform",
"time.proc... | [((1704, 1715), 'time.time', 'time.time', ([], {}), '()\n', (1713, 1715), False, 'import time\n'), ((1771, 1797), 'kdaHDFE.formula_transform.formula_transform', 'formula_transform', (['formula'], {}), '(formula)\n', (1788, 1797), False, 'from kdaHDFE.formula_transform import formula_transform\n'), ((2485, 2539), 'stats... |
import numpy as np
class TrendLine(object):
def __init__(self, name, data):
self.name = name
self.values = data
def plot(self, ax):
z = np.polyfit(range(0, len(self.values)), self.values, 1)
p = np.poly1d(z)
for k, v in ax.spines.items():
v.set_edgecolor('#... | [
"numpy.poly1d"
] | [((238, 250), 'numpy.poly1d', 'np.poly1d', (['z'], {}), '(z)\n', (247, 250), True, 'import numpy as np\n')] |
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import logging
import glob
import math
import json
import argparse
from tqdm import tqdm, trange
from pathlib import Path
import numpy as np
import torch
from... | [
"logging.getLogger",
"logging.StreamHandler",
"math.floor",
"torch.cuda.device_count",
"torch.utils.data.distributed.DistributedSampler",
"torch.cuda.is_available",
"copy.deepcopy",
"pytorch_pretrained_bert.optimization.warmup_linear",
"visdom.Visdom",
"vdbert.data_parallel.DataParallelImbalance",... | [((1449, 1474), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1472, 1474), False, 'import argparse\n'), ((13492, 13535), 'os.makedirs', 'os.makedirs', (['args.output_dir'], {'exist_ok': '(True)'}), '(args.output_dir, exist_ok=True)\n', (13503, 13535), False, 'import os\n'), ((13916, 13943), '... |
"""Use EDIA to assess quality of model fitness to electron density."""
import numpy as np
from . import Structure, XMap, ElectronDensityRadiusTable
from . import ResolutionBins, BondLengthTable
import argparse
import logging
import os
import time
logger = logging.getLogger(__name__)
class ediaOptions:
def __init... | [
"logging.getLogger",
"numpy.ceil",
"argparse.ArgumentParser",
"os.makedirs",
"numpy.asarray",
"numpy.zeros_like",
"numpy.floor",
"numpy.dot",
"numpy.linalg.inv",
"numpy.bincount",
"numpy.linalg.norm",
"numpy.transpose",
"time.time"
] | [((257, 284), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (274, 284), False, 'import logging\n'), ((17936, 17980), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (17959, 17980), False, 'import argparse\n'), ((18940, 18... |
import numpy as np
import matplotlib.pyplot as plt
import emcee
paramnames = ["Offset days", "Init patients", "Infection rate", "Confirmed prob",
"Recovery rate", "Infect delay mean", "Infect delay std",
"Confirmed delay mean", "Confirmed delay std",
"Days to recover mean", "Days to recover std",
"Days... | [
"numpy.median",
"matplotlib.pyplot.hist",
"numpy.logical_and",
"matplotlib.pyplot.xlabel",
"numpy.array",
"emcee.backends.HDFBackend",
"numpy.std",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((813, 1000), 'numpy.array', 'np.array', (['[[0.0, 10.0], [2.0, 100.0], [1.0, 2.5], [0.0, 1.0], [0.0, 1.0], [1.0, 14.0],\n [1.0, 10.0], [1.0, 10.0], [1.0, 10.0], [1.0, 20.0], [1.0, 10.0], [1.0, \n 10.0], [1.0, 10.0]]'], {}), '([[0.0, 10.0], [2.0, 100.0], [1.0, 2.5], [0.0, 1.0], [0.0, 1.0], [\n 1.0, 14.0], [1.... |
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
from random import randint
import numpy as np
import cv2
from PIL import Image
import random
###################################################################
# random mask generation
############################################... | [
"torch.ones_like",
"PIL.Image.fromarray",
"cv2.line",
"cv2.ellipse",
"numpy.zeros",
"cv2.circle",
"torch.nn.functional.interpolate",
"torch.moveaxis",
"random.random",
"torchvision.transforms.ToTensor",
"random.randint"
] | [((429, 449), 'torch.ones_like', 'torch.ones_like', (['img'], {}), '(img)\n', (444, 449), False, 'import torch\n'), ((482, 502), 'random.randint', 'random.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (496, 502), False, 'import random\n'), ((1013, 1033), 'torch.ones_like', 'torch.ones_like', (['img'], {}), '(img)\n', (10... |
import cv2
import numpy as np
# erosion
# used for noise removal, only kernels with all one values
# result in one.
img = cv2.imread('j.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img, kernel,viterations=1)
cv2.imshow('img', img)
cv2.imshow('erode', erosion)
| [
"cv2.erode",
"cv2.imread",
"numpy.ones",
"cv2.imshow"
] | [((131, 153), 'cv2.imread', 'cv2.imread', (['"""j.png"""', '(0)'], {}), "('j.png', 0)\n", (141, 153), False, 'import cv2\n'), ((163, 188), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (170, 188), True, 'import numpy as np\n'), ((198, 235), 'cv2.erode', 'cv2.erode', (['img', 'kernel'], ... |
#########
#
# Copyright (c) 2005 <NAME>
#
# This file is part of the vignette-removal library.
#
# Vignette-removal is free software; you can redistribute it and/or modify
# it under the terms of the X11 Software License (see the LICENSE file
# for details).
#
# This program is distributed in the hope that it will be ... | [
"numpy.sqrt",
"numpy.ones",
"functools.reduce",
"numpy.array",
"numpy.dot",
"numpy.linalg.inv",
"numpy.arctan2",
"numpy.cos",
"numpy.sin"
] | [((2128, 2159), 'numpy.array', 'np.array', (['[p0[1], p0[0], p0[2]]'], {}), '([p0[1], p0[0], p0[2]])\n', (2136, 2159), True, 'import numpy as np\n'), ((2168, 2199), 'numpy.array', 'np.array', (['[p1[1], p1[0], p1[2]]'], {}), '([p1[1], p1[0], p1[2]])\n', (2176, 2199), True, 'import numpy as np\n'), ((2674, 2689), 'funct... |
#!/usr/bin/env python
import os, sys, json, warnings
from functools import wraps
import numpy as np
from PyQt5.QtGui import QColor
from qgis.core import (
Qgis,
QgsApplication,
QgsMeshLayer,
QgsMeshDatasetIndex,
QgsMeshUtils,
QgsProject,
QgsRasterLayer,
QgsRasterFileWriter,
QgsRaste... | [
"PyQt5.QtGui.QColor",
"numpy.array",
"qgis.core.QgsMeshUtils.exportRasterBlock",
"sys.path.append",
"qgis.core.QgsRasterHistogram",
"numpy.arange",
"qgis.core.QgsMeshLayer",
"qgis.core.QgsRasterLayer",
"qgis.core.QgsRasterShader",
"numpy.where",
"qgis.core.QgsMeshDatasetIndex",
"functools.wrap... | [((7056, 7079), 'json.loads', 'json.loads', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (7066, 7079), False, 'import os, sys, json, warnings\n'), ((546, 554), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (551, 554), False, 'from functools import wraps\n'), ((835, 888), 'sys.path.append', 'sys.path.append', (['"""/op... |
"""
"""
from keras.models import Model
from keras.layers import Input, Dropout, Dense, Embedding, concatenate
from keras.layers import GRU, LSTM, Flatten
from keras.preprocessing.sequence import pad_sequences
#from keras.preprocessing import text, sequence
from keras.preprocessing.text import Tokenizer
from keras impor... | [
"numpy.clip",
"sklearn.preprocessing.LabelEncoder",
"numpy.sqrt",
"numpy.array",
"keras.layers.Dense",
"keras.backend.square",
"keras.layers.LSTM",
"keras.layers.concatenate",
"keras.models.Model",
"pandas.DataFrame",
"keras.layers.Flatten",
"sklearn.model_selection.train_test_split",
"aisim... | [((609, 642), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (632, 642), False, 'import warnings\n'), ((9648, 9667), 'keras.layers.concatenate', 'concatenate', (['layers'], {}), '(layers)\n', (9659, 9667), False, 'from keras.layers import Input, Dropout, Dense, Embedding, ... |
# import native Python packages
import random
# import third party packages
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import pandas
import numpy
import scipy
# import api stuff
from src.api.autobracket import single_sim_bracket
#... | [
"pandas.read_csv",
"numpy.where",
"fastapi.templating.Jinja2Templates",
"fastapi.APIRouter",
"src.api.autobracket.single_sim_bracket",
"pandas.isna"
] | [((362, 394), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/autobracket"""'}), "(prefix='/autobracket')\n", (371, 394), False, 'from fastapi import APIRouter, Request\n'), ((407, 445), 'fastapi.templating.Jinja2Templates', 'Jinja2Templates', ([], {'directory': '"""templates"""'}), "(directory='templates')\n", ... |
#!/usr/bin/env python
import requests
import json
import time
import bs4 as bs
import datetime as dt
import os
import pandas_datareader.data as web
import pickle
import requests
import yaml
import yfinance as yf
import pandas as pd
import dateutil.relativedelta
import numpy as np
from datetime import date
from datetim... | [
"pandas.Series",
"datetime.datetime.fromtimestamp",
"pickle.dump",
"numpy.minimum",
"os.path.join",
"requests.get",
"datetime.timedelta",
"os.path.realpath",
"bs4.BeautifulSoup",
"yfinance.download",
"yaml.safe_load",
"numpy.isnan",
"datetime.date.today",
"time.time",
"json.dump"
] | [((2520, 2567), 'os.path.join', 'os.path.join', (['DIR', '"""data"""', '"""price_history.json"""'], {}), "(DIR, 'data', 'price_history.json')\n", (2532, 2567), False, 'import os\n'), ((361, 387), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (377, 387), False, 'import os\n'), ((1244, 1261)... |
# cannot combine, regulons are different in different datasets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
#----------------------variable------------------------
fmt='tif'
n=10 #rows to plot
o=20 #overlap check
fd_rss='./out/a07_regulon_01_... | [
"seaborn.set",
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"pathlib.Path",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
... | [((743, 774), 'pandas.read_csv', 'pd.read_csv', (['fname'], {'index_col': '(0)'}), '(fname, index_col=0)\n', (754, 774), True, 'import pandas as pd\n'), ((1454, 1465), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1462, 1465), True, 'import numpy as np\n'), ((1477, 1486), 'seaborn.set', 'sns.set', ([], {}), '()\n',... |
import torch
import numpy as np
import torch.optim as optim
from torch.nn import NLLLoss
from torch.utils.data import DataLoader
from torch.utils.data.sampler import RandomSampler
from torch.nn.utils import clip_grad_norm
from torchvision.datasets import CIFAR10
from torchvision.transforms import transforms
from src.mo... | [
"src.model.CIFAR10_Network",
"torch.max",
"torch.cuda.synchronize",
"torchvision.datasets.CIFAR10",
"numpy.zeros",
"torchvision.transforms.transforms.ToTensor",
"torch.nn.NLLLoss",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torch.sum",
"torch.utils.data.sampler.RandomSampler",
... | [((503, 524), 'torchvision.transforms.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (522, 524), False, 'from torchvision.transforms import transforms\n'), ((580, 670), 'torchvision.datasets.CIFAR10', 'CIFAR10', ([], {'root': 'self.params.dataset_dir', 'train': '(True)', 'download': '(True)', 'transform... |
""" To make fake Datasets
Wanted to keep this out of the testing frame works, as other repos, might want to use this
"""
from typing import List
import numpy as np
import pandas as pd
import xarray as xr
from nowcasting_dataset.consts import NWP_VARIABLE_NAMES, SAT_VARIABLE_NAMES
from nowcasting_dataset.data_sources... | [
"nowcasting_dataset.data_sources.satellite.satellite_model.HRVSatellite",
"nowcasting_dataset.data_sources.gsp.gsp_model.GSP",
"nowcasting_dataset.dataset.xr_utils.join_list_dataset_to_batch_dataset",
"nowcasting_dataset.data_sources.pv.pv_model.PV",
"pandas.Timedelta",
"nowcasting_dataset.data_sources.me... | [((1372, 1433), 'nowcasting_dataset.dataset.xr_utils.convert_coordinates_to_indexes_for_list_datasets', 'convert_coordinates_to_indexes_for_list_datasets', (['xr_datasets'], {}), '(xr_datasets)\n', (1420, 1433), False, 'from nowcasting_dataset.dataset.xr_utils import convert_coordinates_to_indexes, convert_coordinates_... |
# Importing libraries
import numpy as np
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import RobustScaler
def feat_goal_duration(df:pd.DataFrame):
"""Converts goal to USD and computes the duration between project launch and deadline and the duration between project creation and laun... | [
"pandas.get_dummies",
"sklearn.preprocessing.RobustScaler",
"pandas.DatetimeIndex",
"numpy.where"
] | [((1859, 2010), 'pandas.get_dummies', 'pd.get_dummies', (['df'], {'columns': "['winter_deadline', 'spring_deadline', 'summer_deadline',\n 'deadline_weekend', 'launched_weekend']", 'drop_first': '(True)'}), "(df, columns=['winter_deadline', 'spring_deadline',\n 'summer_deadline', 'deadline_weekend', 'launched_week... |
# Not consistent with test passing
import numpy as np
import path_plan
from path_plan import compute_probability
from path_plan import model_polyfit
from numpy import interp
import sys
def main():
# Indian Road congress (INC)
V_lane_width = [2.0, 23.5]
# https://nptel.ac.in/content/storage2/courses/105101008/... | [
"numpy.array",
"numpy.interp",
"path_plan.compute_probability"
] | [((429, 471), 'numpy.interp', 'interp', (['V_lane_width', 'BP_lane_width', 'speed'], {}), '(V_lane_width, BP_lane_width, speed)\n', (435, 471), False, 'from numpy import interp\n'), ((485, 529), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, lane_width // 2.0]'], {}), '([0.0, 0.0, 0.0, lane_width // 2.0])\n', (493, 529)... |
import copy
import os
import sqlite3
import urllib
import shutil
import urllib.request
import numpy as np
import pandas as pd
from basinmaker.utilities.utilities import *
def GenerateRavenInput(
Path_final_hru_info="#",
lenThres=1,
iscalmanningn=-1,
Startyear=-1,
EndYear=-1,
CA_HYDAT="#",
... | [
"matplotlib.pyplot.hist",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.array",
"copy.copy",
"pandas.date_range",
"pandas.to_datetime",
"pandas.read_sql_query",
"numpy.mean",
"os.path.exists",
"os.listdir",
"simpledbf.Dbf5",
"matplotlib.pyplot.xlabel",
"os.path.split",
"matplotli... | [((8636, 8676), 'os.path.join', 'os.path.join', (['OutputFolder', '"""RavenInput"""'], {}), "(OutputFolder, 'RavenInput')\n", (8648, 8676), False, 'import os\n'), ((8694, 8731), 'os.path.join', 'os.path.join', (['Raveinputsfolder', '"""obs"""'], {}), "(Raveinputsfolder, 'obs')\n", (8706, 8731), False, 'import os\n'), (... |
import matplotlib.pyplot as plt
import numpy as np
from kino.steps import Paw
from kino.geometry import Trajectory
class Steps:
@staticmethod
def overlay_on_speed_trace(paw: Paw, ax: plt.Axes):
"""
Overlay the start/end of the steps on a paw's speed trace
"""
color = paw.t... | [
"numpy.arange"
] | [((1096, 1122), 'numpy.arange', 'np.arange', (['start', '(stop + 1)'], {}), '(start, stop + 1)\n', (1105, 1122), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
run_doe.py generated by WhatsOpt.
"""
# DO NOT EDIT unless you know what you are doing
# analysis_id: 49
import numpy as np
# import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from openmdao.api import Problem, SqliteRecorder, CaseReader
from whatsopt.smt_doe_drive... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"openmdao.api.SqliteRecorder",
"optparse.OptionParser",
"mod_branin.ModBranin",
"whatsopt.smt_doe_driver.SmtDoeDriver",
"numpy.zeros",
"matplotlib.pyplot.subplot",
"openmdao.api.CaseReader",
"matplotlib.pyplot.show... | [((420, 434), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (432, 434), False, 'from optparse import OptionParser\n'), ((662, 709), 'whatsopt.smt_doe_driver.SmtDoeDriver', 'SmtDoeDriver', ([], {'sampling_method': '"""LHS"""', 'n_cases': '(50)'}), "(sampling_method='LHS', n_cases=50)\n", (674, 709), False, ... |
import numpy as np
x = np.array([0, 1])
w = np.array([0.5, 0.5])
b = -0.7
w * b
np.sum(w*x)
np.sum(w*x) + b | [
"numpy.array",
"numpy.sum"
] | [((24, 40), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (32, 40), True, 'import numpy as np\n'), ((46, 66), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (54, 66), True, 'import numpy as np\n'), ((85, 98), 'numpy.sum', 'np.sum', (['(w * x)'], {}), '(w * x)\n', (91, 98), True, 'import... |
# -*- coding: utf-8 -*-
"""A collection of combination methods for clustering
"""
# Author: <NAME> <<EMAIL>>
# License: BSD 2 clause
import numpy as np
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from numpy.testing import assert_equal
from pyod.utils.utility import che... | [
"sklearn.utils.validation.check_is_fitted",
"numpy.copy",
"numpy.intersect1d",
"numpy.testing.assert_equal",
"numpy.ones",
"numpy.unique",
"numpy.where",
"pyod.utils.utility.check_parameter",
"numpy.sum",
"numpy.zeros",
"numpy.argwhere",
"sklearn.utils.check_array"
] | [((6861, 6897), 'numpy.zeros', 'np.zeros', (['[n_clusters, n_estimators]'], {}), '([n_clusters, n_estimators])\n', (6869, 6897), True, 'import numpy as np\n'), ((6919, 6943), 'numpy.copy', 'np.copy', (['original_labels'], {}), '(original_labels)\n', (6926, 6943), True, 'import numpy as np\n'), ((8288, 8322), 'numpy.zer... |
from openmdao.api import ExplicitComponent
import numpy as np
class SellarDis1(ExplicitComponent):
"""
Component containing Discipline 1.
"""
def __init__(self, derivative_method='full_analytic', **kwargs):
super(SellarDis1, self).__init__(**kwargs)
self.derivative_method = derivative... | [
"numpy.exp",
"numpy.array",
"numpy.zeros"
] | [((1468, 1507), 'numpy.array', 'np.array', (["[[2.0 * inputs['z'][0], 1.0]]"], {}), "([[2.0 * inputs['z'][0], 1.0]])\n", (1476, 1507), True, 'import numpy as np\n'), ((3185, 3207), 'numpy.array', 'np.array', (['[[1.0, 1.0]]'], {}), '([[1.0, 1.0]])\n', (3193, 3207), True, 'import numpy as np\n'), ((7835, 7855), 'numpy.a... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from scipy.stats import multinomial
from ..utils.array import one_hot
from .categorical import CategoricalDist
if tf.__version__ >= '2.0':
tf.random.set_seed(11)
else:
tf.set_random_seed(11)
rnd ... | [
"numpy.testing.assert_array_almost_equal",
"tensorflow.random.set_seed",
"numpy.ones",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Input",
"tensorflow.keras.Model",
"scipy.stats.multinomial",
"tensorflow.set_random_seed",
"numpy.random.RandomState"
] | [((322, 347), 'numpy.random.RandomState', 'np.random.RandomState', (['(13)'], {}), '(13)\n', (343, 347), True, 'import numpy as np\n'), ((438, 471), 'tensorflow.keras.Input', 'keras.Input', (['[5]'], {'dtype': '"""float32"""'}), "([5], dtype='float32')\n", (449, 471), False, 'from tensorflow import keras\n'), ((476, 50... |
#!/usr/bin/python
import sys
import textadapter
import unittest
from .generate import (generate_dataset, IntIter,
MissingValuesIter, FixedWidthIter)
import numpy as np
from numpy.testing import assert_array_equal
import gzip
import os
import io
from six import StringIO
class TestTextAdapter(uni... | [
"textadapter.FixedWidthTextAdapter",
"os.path.exists",
"numpy.dtype",
"unittest.TestLoader",
"textadapter.RegexTextAdapter",
"io.BytesIO",
"textadapter.text_adapter",
"numpy.array",
"gzip.GzipFile",
"six.StringIO",
"io.StringIO",
"unittest.TextTestRunner",
"numpy.testing.assert_array_equal",... | [((798, 817), 'six.StringIO', 'StringIO', (['"""1,2,3\n"""'], {}), "('1,2,3\\n')\n", (806, 817), False, 'from six import StringIO\n'), ((836, 885), 'textadapter.text_adapter', 'textadapter.text_adapter', (['data'], {'field_names': '(False)'}), '(data, field_names=False)\n', (860, 885), False, 'import textadapter\n'), (... |
"""
Test file formats.
"""
import wave
import numpy
import pytest
from pytest import approx
from scipy.io import wavfile
from scipy.fftpack import fft
from diapason import generate_wav
@pytest.mark.parametrize(('frequency', 'duration', 'rate'), [
(440., 2., 44100),
(220., 1., 48000),
(880., 3., 16000),
... | [
"pytest.approx",
"wave.open",
"numpy.argmax",
"pytest.mark.parametrize",
"diapason.generate_wav",
"scipy.io.wavfile.read",
"scipy.fftpack.fft"
] | [((190, 318), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('frequency', 'duration', 'rate')", '[(440.0, 2.0, 44100), (220.0, 1.0, 48000), (880.0, 3.0, 16000)]'], {}), "(('frequency', 'duration', 'rate'), [(440.0, 2.0, \n 44100), (220.0, 1.0, 48000), (880.0, 3.0, 16000)])\n", (213, 318), False, 'import p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.