code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#Amtrak Recursive ROute Writer (ARROW)
#cont- does not write initial .npz file, relies on existing partials
def main(newdata=False,
cont=False,
newredund=False,
arrive=True):
import json
import numpy as np
import os
import route_builder
import glob
import find_redunda... | [
"numpy.load",
"json.load",
"numpy.save",
"os.remove",
"numpy.append",
"os.path.isfile",
"numpy.array",
"glob.glob",
"find_redundancy.main",
"numpy.savez",
"route_builder.main"
] | [((1579, 1602), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (1587, 1602), True, 'import numpy as np\n'), ((1621, 1644), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (1629, 1644), True, 'import numpy as np\n'), ((1663, 1686), 'numpy.array', 'np.array', (['[]... |
#!/usr/bin/env python
"""
OXASL - Bayesian model fitting for ASL
The BASIL module is a little more complex than the other Workspace based
modules because of the number of options available and the need for flexibility
in how the modelling steps are run.
The main function is ``basil`` which performs model fitting on A... | [
"oxasl.image.AslImageOptions",
"numpy.copy",
"math.sqrt",
"oxasl.options.OptionGroup",
"numpy.ones",
"fsl.data.image.Image",
"numpy.amax",
"sys.stderr.write",
"numpy.mean",
"numpy.array",
"oxasl.reg.change_space",
"oxasl.options.AslOptionParser",
"oxasl.options.GenericOptions",
"sys.exit",... | [((9452, 9497), 'fsl.data.image.Image', 'Image', (['tis_arr'], {'header': "options['data'].header"}), "(tis_arr, header=options['data'].header)\n", (9457, 9497), False, 'from fsl.data.image import Image\n'), ((14347, 14368), 'numpy.copy', 'np.copy', (['pgm_img.data'], {}), '(pgm_img.data)\n', (14354, 14368), True, 'imp... |
import binascii
import numpy as np
import copy
from scapy.all import TCP, UDP, IP, IPv6, ARP, raw
def get_packet_matrix(packet):
"""
Transform a packet content into 1D array of bytes
Parameters
----------
packet : an IP packet
Returns
-------
1D ndarry of packet bytes
"""
hex... | [
"copy.deepcopy",
"numpy.uint8",
"scapy.all.raw"
] | [((444, 456), 'numpy.uint8', 'np.uint8', (['fh'], {}), '(fh)\n', (452, 456), True, 'import numpy as np\n'), ((718, 739), 'copy.deepcopy', 'copy.deepcopy', (['packet'], {}), '(packet)\n', (731, 739), False, 'import copy\n'), ((342, 353), 'scapy.all.raw', 'raw', (['packet'], {}), '(packet)\n', (345, 353), False, 'from sc... |
######################################################
#
# PyRAI2MD 2 module for thermostat in NVT ensemble
#
# Author <NAME>
# Sep 7 2021
#
######################################################
import numpy as np
def NoseHoover(traj):
""" Velocity scaling function in NVT ensemble (Nose Hoover thermostat)
... | [
"numpy.exp"
] | [((1333, 1355), 'numpy.exp', 'np.exp', (['(-V2 * size / 8)'], {}), '(-V2 * size / 8)\n', (1339, 1355), True, 'import numpy as np\n'), ((1454, 1476), 'numpy.exp', 'np.exp', (['(-V2 * size / 8)'], {}), '(-V2 * size / 8)\n', (1460, 1476), True, 'import numpy as np\n'), ((1489, 1511), 'numpy.exp', 'np.exp', (['(-V1 * size ... |
"""TrackML scoring metric"""
__authors__ = ['<NAME>', '<NAME>', '<NAME>',
'<NAME>']
import numpy
import pandas
def _analyze_tracks(truth, submission):
"""Compute the majority particle, hit counts, and weight for each track.
Parameters
----------
truth : pandas.DataFrame
Truth ... | [
"pandas.merge",
"numpy.true_divide",
"pandas.DataFrame.from_records"
] | [((911, 1058), 'pandas.merge', 'pandas.merge', (["truth[['hit_id', 'particle_id', 'weight']]", "submission[['hit_id', 'track_id']]"], {'on': "['hit_id']", 'how': '"""left"""', 'validate': '"""one_to_one"""'}), "(truth[['hit_id', 'particle_id', 'weight']], submission[[\n 'hit_id', 'track_id']], on=['hit_id'], how='le... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
from pandas.api.types import is_scalar
from pandas.util._validators import validate_bool_kwarg
from pandas.core.index import _ensure_index_from_sequences
from pandas._libs import lib
from pa... | [
"pandas.core.dtypes.cast.maybe_upcast_putmask",
"pandas.util._validators.validate_bool_kwarg",
"pandas.core.dtypes.common.is_numeric_dtype",
"ray.put",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.DataFrame",
"ray.remote",
"numpy.cumsum",
"pandas.concat",
"pandas.compat.lzip",
"pandas.api.... | [((93466, 93495), 'ray.remote', 'ray.remote', ([], {'num_return_vals': '(2)'}), '(num_return_vals=2)\n', (93476, 93495), False, 'import ray\n'), ((91212, 91241), 'pandas.concat', 'pd.concat', (['df_rows'], {'axis': 'axis'}), '(df_rows, axis=axis)\n', (91221, 91241), True, 'import pandas as pd\n'), ((9073, 9092), 'ray.g... |
from typing import Tuple
import gym
import numpy as np
from gym_gathering.observations.base_observation_generator import ObservationGenerator
class SingleChannelObservationGenerator(ObservationGenerator):
def __init__(
self,
maze: np.ndarray,
random_goal: bool,
goal_range: int,
... | [
"numpy.zeros",
"gym.spaces.Box"
] | [((872, 943), 'gym.spaces.Box', 'gym.spaces.Box', ([], {'low': '(0)', 'high': '(255)', 'shape': '(*maze.shape, 1)', 'dtype': 'np.uint8'}), '(low=0, high=255, shape=(*maze.shape, 1), dtype=np.uint8)\n', (886, 943), False, 'import gym\n'), ((1062, 1087), 'numpy.zeros', 'np.zeros', (['self.maze.shape'], {}), '(self.maze.s... |
import cv2
import numpy as np
import time
'''
Parameters Used inside Code
'''
#Gaussian kernel size used for blurring
G_kernel_size = (3,3)
#canny thresholding parameters
canny_u_threshold = 200
canny_l_threshold = 80
# define the upper and lower boundaries of the HSV pixel
# intensities to be considered 'skin'
low... | [
"numpy.array"
] | [((325, 361), 'numpy.array', 'np.array', (['[0, 48, 80]'], {'dtype': '"""uint8"""'}), "([0, 48, 80], dtype='uint8')\n", (333, 361), True, 'import numpy as np\n'), ((372, 411), 'numpy.array', 'np.array', (['[20, 255, 255]'], {'dtype': '"""uint8"""'}), "([20, 255, 255], dtype='uint8')\n", (380, 411), True, 'import numpy ... |
from wordcloud import WordCloud, STOPWORDS
import os
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.patches import Patch
from loguru import logger
from GEN_Utils import FileHandling
from GEN_Utils.HDF5_Utils import hdf_to_dict
logger.info('Impor... | [
"matplotlib.pyplot.title",
"seaborn.lineplot",
"matplotlib.pyplot.tight_layout",
"os.mkdir",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"seaborn.barplot",
"os.path.exists",
"pandas.read_excel",
"loguru.logger.info",
"numpy.arange",
"seaborn.color_palette",
"matplotlib.patches.Patc... | [((302, 326), 'loguru.logger.info', 'logger.info', (['"""Import OK"""'], {}), "('Import OK')\n", (313, 326), False, 'from loguru import logger\n'), ((841, 882), 'pandas.read_excel', 'pd.read_excel', (['input_path'], {'sheetname': 'None'}), '(input_path, sheetname=None)\n', (854, 882), True, 'import pandas as pd\n'), ((... |
# <NAME>
import numpy as np
import pylab as plt
from spectral.io import envi
import os, sys
sys.path.append('../utils')
from fpa import FPA
I = envi.open('../data/EMIT_LinearityMap_20220117.hdr').load()
thresh = 20
fpa = FPA('../config/tvac2_config.json')
for band in range(I.shape[2]):
x = np.squeeze(I[:,:,band])... | [
"sys.path.append",
"spectral.io.envi.save_image",
"spectral.io.envi.open",
"fpa.FPA",
"numpy.squeeze"
] | [((92, 119), 'sys.path.append', 'sys.path.append', (['"""../utils"""'], {}), "('../utils')\n", (107, 119), False, 'import os, sys\n'), ((224, 258), 'fpa.FPA', 'FPA', (['"""../config/tvac2_config.json"""'], {}), "('../config/tvac2_config.json')\n", (227, 258), False, 'from fpa import FPA\n'), ((1019, 1104), 'spectral.io... |
'''
util.py
'''
import os.path
import h5py
import numpy as np
import constants
import skimage.io
import skimage.transform
from scipy.io import loadmat
import glob
import os
import cPickle as pickle
import torch
from itertools import izip_longest
from glove import Glove
import torch
import torch.nn as nn
# Makes the ... | [
"numpy.flip",
"os.makedirs",
"scipy.io.loadmat",
"torch.LongTensor",
"itertools.izip_longest",
"torch.load",
"os.path.exists",
"torch.save",
"torch.nn.init.xavier_uniform",
"numpy.array",
"glove.Glove",
"numpy.swapaxes",
"numpy.random.rand",
"os.path.join",
"os.listdir"
] | [((1039, 1074), 'scipy.io.loadmat', 'loadmat', (['"""data_constants/setid.mat"""'], {}), "('data_constants/setid.mat')\n", (1046, 1074), False, 'from scipy.io import loadmat\n'), ((3085, 3110), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (3099, 3110), False, 'import os\n'), ((5568, 5575), ... |
from __future__ import print_function, division
import matplotlib.pyplot as plt
import math
from sklearn.metrics import auc
import numpy as np
import cv2
import os, sys
int_ = lambda x: int(round(x))
def IoU( r1, r2 ):
x11, y11, w1, h1 = r1
x21, y21, w2, h2 = r2
x12 = x11 + w1; y12 = y11 + h1
x22 = x... | [
"matplotlib.pyplot.show",
"numpy.sum",
"cv2.filter2D",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"math.ceil",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.max",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.grid"
] | [((777, 792), 'numpy.ones', 'np.ones', (['(h, w)'], {}), '((h, w))\n', (784, 792), True, 'import numpy as np\n'), ((807, 829), 'cv2.filter2D', 'cv2.filter2D', (['x', '(-1)', 'k'], {}), '(x, -1, k)\n', (819, 829), False, 'import cv2\n'), ((1921, 1947), 'numpy.mean', 'np.mean', (['success_rate[:-1]'], {}), '(success_rate... |
#
# Compare lithium-ion battery models with and without particle size distibution
#
import numpy as np
import pybamm
pybamm.set_logging_level("INFO")
# load models
models = [
pybamm.lithium_ion.DFN(name="standard DFN"),
pybamm.lithium_ion.DFN(name="particle DFN"),
]
# load parameter values
params = [models[0... | [
"pybamm.set_logging_level",
"pybamm.Simulation",
"numpy.linspace",
"pybamm.QuickPlot",
"pybamm.lithium_ion.DFN"
] | [((118, 150), 'pybamm.set_logging_level', 'pybamm.set_logging_level', (['"""INFO"""'], {}), "('INFO')\n", (142, 150), False, 'import pybamm\n'), ((730, 755), 'numpy.linspace', 'np.linspace', (['(0)', '(3600)', '(100)'], {}), '(0, 3600, 100)\n', (741, 755), True, 'import numpy as np\n'), ((1327, 1384), 'pybamm.QuickPlot... |
from scipy.misc import imread
from tqdm import tqdm
import numpy as np
import os
import random
import warnings
class SetList(object):
'''A class to hold lists of inputs for a network'''
def __init__(self, source='', target=None):
'''Constructs a new SetList.
Args:
source (str): T... | [
"tqdm.tqdm",
"os.path.isdir",
"random.shuffle",
"os.walk",
"os.path.exists",
"numpy.mean",
"os.path.splitext",
"warnings.warn",
"scipy.misc.imread"
] | [((1365, 1391), 'os.path.isdir', 'os.path.isdir', (['self.source'], {}), '(self.source)\n', (1378, 1391), False, 'import os\n'), ((2331, 2356), 'random.shuffle', 'random.shuffle', (['self.list'], {}), '(self.list)\n', (2345, 2356), False, 'import random\n'), ((3380, 3390), 'tqdm.tqdm', 'tqdm', (['self'], {}), '(self)\n... |
from Source import ModelsIO as MIO
import numpy as np
from h5py import File
def E_fit(_cube: np.ndarray((10, 13, 21, 128, 128), '>f4'),
data: np.ndarray((128, 128), '>f4'),
seg: np.ndarray((128, 128), '>f4'),
noise: np.ndarray((128, 128), '>f4')) -> np.ndarray((10, 13, 21), '>f4'):
... | [
"h5py.File",
"Source.ModelsIO.fits.ImageHDU",
"numpy.sum",
"Source.ModelsIO.ModelsCube",
"numpy.median",
"numpy.einsum",
"numpy.float",
"numpy.zeros",
"Source.ModelsIO.fits.open",
"numpy.argmin",
"numpy.swapaxes",
"numpy.ndarray",
"numpy.sqrt"
] | [((282, 313), 'numpy.ndarray', 'np.ndarray', (['(10, 13, 21)', '""">f4"""'], {}), "((10, 13, 21), '>f4')\n", (292, 313), True, 'import numpy as np\n'), ((335, 376), 'numpy.ndarray', 'np.ndarray', (['(10, 13, 21, 128, 128)', '""">f4"""'], {}), "((10, 13, 21, 128, 128), '>f4')\n", (345, 376), True, 'import numpy as np\n'... |
import nltk
import os
import torch
import torch.utils.data as data
import numpy as np
import json
from .vocabulary import Vocabulary
from pycocotools.coco import COCO
from PIL import Image
from tqdm import tqdm
class CoCoDataset(data.Dataset):
def __init__(self, transform, mode, batch_size, vocab_threshold, voca... | [
"pycocotools.coco.COCO",
"torch.Tensor",
"numpy.array",
"numpy.random.choice",
"os.path.join"
] | [((2802, 2840), 'numpy.random.choice', 'np.random.choice', (['self.caption_lengths'], {}), '(self.caption_lengths)\n', (2818, 2840), True, 'import numpy as np\n'), ((776, 798), 'pycocotools.coco.COCO', 'COCO', (['annotations_file'], {}), '(annotations_file)\n', (780, 798), False, 'from pycocotools.coco import COCO\n'),... |
import os
import json
from six import iteritems
import h5py
import numpy as np
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from vdgnn.dataset.readers import DenseAnnotationsReader, ImageFeaturesHdfReader
TRAIN_VAL_SPLIT = {'0.9': 80000, '1.0': 123287}
clas... | [
"h5py.File",
"json.load",
"torch.stack",
"os.path.exists",
"vdgnn.dataset.readers.DenseAnnotationsReader",
"torch.zeros",
"vdgnn.dataset.readers.ImageFeaturesHdfReader",
"torch.Tensor",
"numpy.array",
"torch.max",
"torch.Size",
"torch.nn.functional.normalize",
"six.iteritems",
"os.path.joi... | [((2280, 2323), 'os.path.join', 'os.path.join', (['args.dataroot', 'input_img_path'], {}), '(args.dataroot, input_img_path)\n', (2292, 2323), False, 'import os\n'), ((2350, 2398), 'os.path.join', 'os.path.join', (['args.dataroot', 'args.visdial_params'], {}), '(args.dataroot, args.visdial_params)\n', (2362, 2398), Fals... |
import matplotlib
matplotlib.use('TkAgg') # noqa
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.cm as cm
import matplotlib.colors as mcolors
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import cmocean
im... | [
"numpy.abs",
"oggm.cfg.initialize",
"relic.preprocessing.GLCDICT.keys",
"relic.postprocessing.get_ensemble_length",
"collections.defaultdict",
"matplotlib.pyplot.figure",
"mpl_toolkits.axes_grid1.inset_locator.inset_axes",
"numpy.arange",
"oggm.utils.ncDataset",
"numpy.isclose",
"relic.preproces... | [((19, 42), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (33, 42), False, 'import matplotlib\n'), ((923, 958), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '[20, 7]'}), '(1, 3, figsize=[20, 7])\n', (935, 958), True, 'import matplotlib.pyplot as plt\n'), ((5423,... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from . import common
def main(debug=False):
name = ['I', 'A', 'S', 'C']
suffix = ['', '', '', '']
df0 = []
for n, s in zip(name, suffix):
prec = pd.read_csv(f'results/logk_prec_{n}{s}.csv')
p... | [
"seaborn.heatmap",
"matplotlib.pyplot.get_cmap",
"pandas.read_csv",
"numpy.where",
"numpy.log10",
"pandas.concat"
] | [((690, 712), 'pandas.concat', 'pd.concat', (['df0'], {'axis': '(1)'}), '(df0, axis=1)\n', (699, 712), True, 'import pandas as pd\n'), ((266, 310), 'pandas.read_csv', 'pd.read_csv', (['f"""results/logk_prec_{n}{s}.csv"""'], {}), "(f'results/logk_prec_{n}{s}.csv')\n", (277, 310), True, 'import pandas as pd\n'), ((384, 4... |
import argparse
from datetime import datetime
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from torch_model import SizedGenerator
import os
from tqdm import trange
from torchvision.utils import save_image, make_grid
import params as P
from utils impo... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.randn",
"utils.psnr",
"torch.no_grad",
"torch.ones",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.Linear",
"datetime.datetime.now",
"utils.load_trained_generator",
"tqdm.trange",
"torch... | [((568, 602), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (579, 602), False, 'import os\n'), ((678, 699), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['logdir'], {}), '(logdir)\n', (691, 699), False, 'from torch.utils.tensorboard import SummaryWriter\n... |
# -*- coding: utf-8 -*-
import pathlib as _pl
import pandas as _pd
import s3fs as _s3fs
# import urllib as _urllib
# import html2text as _html2text
import psutil as _psutil
import numpy as _np
# import xarray as _xr
def readme():
url = 'https://docs.opendata.aws/noaa-goes16/cics-readme.html'
# html = _urllib.r... | [
"pandas.DataFrame",
"pandas.date_range",
"psutil.disk_usage",
"pathlib.Path",
"s3fs.S3FileSystem",
"pandas.to_datetime",
"pandas.to_timedelta",
"numpy.all"
] | [((502, 531), 's3fs.S3FileSystem', '_s3fs.S3FileSystem', ([], {'anon': '(True)'}), '(anon=True)\n', (520, 531), True, 'import s3fs as _s3fs\n'), ((542, 557), 'pandas.DataFrame', '_pd.DataFrame', ([], {}), '()\n', (555, 557), True, 'import pandas as _pd\n'), ((865, 890), 'numpy.all', '_np.all', (['(df[16] == df[17])'], ... |
"""
CanvasItem module contains classes related to canvas items.
"""
from __future__ import annotations
# standard libraries
import collections
import concurrent.futures
import contextlib
import copy
import datetime
import enum
import functools
import imageio
import logging
import operator
import sys
import threadi... | [
"nion.utils.Geometry.fit_to_aspect_ratio",
"typing.cast",
"nion.utils.Geometry.IntPoint",
"weakref.ref",
"nion.utils.Geometry.FloatPoint",
"nion.utils.Geometry.IntRect",
"numpy.zeros_like",
"traceback.print_exc",
"threading.Condition",
"nion.ui.UserInterface.MenuItemState",
"threading.Event",
... | [((137650, 137714), 'collections.namedtuple', 'collections.namedtuple', (['"""PositionLength"""', "['position', 'length']"], {}), "('PositionLength', ['position', 'length'])\n", (137672, 137714), False, 'import collections\n'), ((215555, 215580), 'imageio.imread', 'imageio.imread', (['b', 'format'], {}), '(b, format)\n... |
import torch
import numpy as np
from torchwi.utils.ctensor import ca2rt, rt2ca
class FreqL2Loss(torch.autograd.Function):
@staticmethod
def forward(ctx, frd, true):
# resid: (nrhs, 2*nx) 2 for real and imaginary
resid = frd - true
resid_c = rt2ca(resid)
l2 = np.real(0.5*np.sum(... | [
"numpy.conjugate",
"torchwi.utils.ctensor.rt2ca",
"torch.tensor"
] | [((275, 287), 'torchwi.utils.ctensor.rt2ca', 'rt2ca', (['resid'], {}), '(resid)\n', (280, 287), False, 'from torchwi.utils.ctensor import ca2rt, rt2ca\n'), ((404, 420), 'torch.tensor', 'torch.tensor', (['l2'], {}), '(l2)\n', (416, 420), False, 'import torch\n'), ((551, 563), 'torchwi.utils.ctensor.rt2ca', 'rt2ca', (['r... |
""" Preprocess the ISBI data set.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, JHU/APL"
__license__ = "Apache 2.0"
import argparse, os.path
import numpy as np
from scipy.stats.mstats import mquantiles
import scipy.io
import emlib
def get_args():
"""Command line parameters for the 'deploy' proc... | [
"numpy.size",
"numpy.sum",
"argparse.ArgumentParser",
"emlib.load_cube",
"numpy.concatenate"
] | [((462, 487), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (485, 487), False, 'import argparse, os.path\n'), ((1935, 1979), 'emlib.load_cube', 'emlib.load_cube', (['args.dataFileName', 'np.uint8'], {}), '(args.dataFileName, np.uint8)\n', (1950, 1979), False, 'import emlib\n'), ((1988, 2034), ... |
import numpy
import math
#from .. import utilities
class phase_space(object):
"""Phase space class.
"""
def __init__(self, xs, tau=1, m=2, eps=.001):
self.tau, self.m, self.eps = tau, m, eps
N = int(len(xs)-m*tau+tau)
self.matrix = numpy.empty([N,m],dtype=float)
fo... | [
"numpy.full",
"numpy.sum",
"numpy.empty",
"numpy.zeros",
"numpy.transpose",
"numpy.linalg.norm",
"math.log"
] | [((2196, 2217), 'numpy.full', 'numpy.full', (['[N, N]', '(0)'], {}), '([N, N], 0)\n', (2206, 2217), False, 'import numpy\n'), ((3346, 3373), 'numpy.zeros', 'numpy.zeros', (['N'], {'dtype': 'float'}), '(N, dtype=float)\n', (3357, 3373), False, 'import numpy\n'), ((5302, 5315), 'numpy.sum', 'numpy.sum', (['AA'], {}), '(A... |
"""ProbsMeasurer's module."""
import numpy as np
from mlscratch.tensor import Tensor
from .measurer import Measurer
class ProbsMeasurer(Measurer[float]):
"""Computes how many samples were evaluated correctly by
getting the most probable label/index in the probability array."""
def measure(
se... | [
"numpy.sum",
"numpy.argmax"
] | [((459, 485), 'numpy.argmax', 'np.argmax', (['result'], {'axis': '(-1)'}), '(result, axis=-1)\n', (468, 485), True, 'import numpy as np\n'), ((517, 545), 'numpy.argmax', 'np.argmax', (['expected'], {'axis': '(-1)'}), '(expected, axis=-1)\n', (526, 545), True, 'import numpy as np\n'), ((564, 614), 'numpy.sum', 'np.sum',... |
import pandas as pd
import numpy as np
class Stats(object):
'''
Produces stats given a schedule
'''
def __init__(self, games, agg_method, date_col, h_col, a_col, outcome_col, seg_vars = []):
self.games = games
self.agg_method = agg_method
self.date_col = date_col
self.h_... | [
"pandas.DataFrame",
"numpy.corrcoef",
"pandas.to_datetime",
"numpy.sum"
] | [((1583, 1605), 'numpy.sum', 'np.sum', (['h_games[h_col]'], {}), '(h_games[h_col])\n', (1589, 1605), True, 'import numpy as np\n'), ((1622, 1644), 'numpy.sum', 'np.sum', (['a_games[a_col]'], {}), '(a_games[a_col])\n', (1628, 1644), True, 'import numpy as np\n'), ((2182, 2196), 'pandas.DataFrame', 'pd.DataFrame', ([], {... |
'''
Based on:
Gravity Turn Maneuver with direct multiple shooting using CVodes
(c) <NAME>
https://mintoc.de/index.php/Gravity_Turn_Maneuver_(Casadi)
https://github.com/zegkljan/kos-stuff/tree/master/non-kos-tools/gturn
----------------------------------------------------------------
'''
import sys
from pathlib ... | [
"pandas.DataFrame",
"casadi.nlpsol",
"casadi.SX.sym",
"casadi.exp",
"casadi.integrator",
"casadi.cos",
"casadi.sin",
"rocket_input.read_rocket_config",
"casadi.vertcat",
"pathlib.Path",
"numpy.array",
"casadi.MX.sym",
"numpy.linspace"
] | [((1656, 1684), 'casadi.SX.sym', 'cs.SX.sym', (['"""[m, v, q, h, d]"""'], {}), "('[m, v, q, h, d]')\n", (1665, 1684), True, 'import casadi as cs\n'), ((1710, 1724), 'casadi.SX.sym', 'cs.SX.sym', (['"""u"""'], {}), "('u')\n", (1719, 1724), True, 'import casadi as cs\n'), ((1753, 1767), 'casadi.SX.sym', 'cs.SX.sym', (['"... |
# Recognise Faces using some classification algorithm - like Logistic, KNN, SVM etc.
# 1. load the training data (numpy arrays of all the persons)
# x- values are stored in the numpy arrays
# y-values we need to assign for each person
# 2. Read a video stream using opencv
# 3. extract faces out of it
# 4. use... | [
"cv2.resize",
"numpy.load",
"cv2.putText",
"numpy.argmax",
"cv2.waitKey",
"numpy.unique",
"cv2.imshow",
"numpy.ones",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.imread",
"numpy.array",
"os.path.splitext",
"cv2.CascadeClassifier",
"cv2.destroyAllWindows",
"datetime.datetime.now",
"os.l... | [((2298, 2317), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2314, 2317), False, 'import cv2\n'), ((2354, 2410), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_frontalface_alt.xml"""'], {}), "('haarcascade_frontalface_alt.xml')\n", (2375, 2410), False, 'import cv2\n'), ((2635, 2... |
#!/usr/bin/env python
"""
PyTorch datasets and data augmenters
"""
###########
# Imports #
###########
import cv2
import numpy as np
import os
import random
import torch
from PIL import Image, ImageFilter
from torch.utils import data
from torchvision import transforms
#############
# Functions #
#############
de... | [
"torchvision.transforms.functional.to_tensor",
"argparse.ArgumentParser",
"numpy.amin",
"random.shuffle",
"numpy.arange",
"os.path.join",
"via.dump",
"random.randint",
"os.path.exists",
"torchvision.transforms.functional.to_pil_image",
"cv2.drawContours",
"torchvision.transforms.ColorJitter",
... | [((387, 429), 'torchvision.transforms.functional.to_pil_image', 'transforms.functional.to_pil_image', (['tensor'], {}), '(tensor)\n', (421, 429), False, 'from torchvision import transforms\n'), ((501, 537), 'torchvision.transforms.functional.to_tensor', 'transforms.functional.to_tensor', (['pic'], {}), '(pic)\n', (532,... |
##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# 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... | [
"numpy.asarray",
"itertools.count",
"pyquil.quilatom.QubitPlaceholder",
"pyquil.quilatom.LabelPlaceholder",
"pyquil.quilatom.unpack_qubit"
] | [((10548, 10573), 'pyquil.quilatom.LabelPlaceholder', 'LabelPlaceholder', (['"""START"""'], {}), "('START')\n", (10564, 10573), False, 'from pyquil.quilatom import LabelPlaceholder, QubitPlaceholder, unpack_qubit\n'), ((10594, 10617), 'pyquil.quilatom.LabelPlaceholder', 'LabelPlaceholder', (['"""END"""'], {}), "('END')... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 13:49:13 2021
@author: Matteo
"""
import numpy as np
import matplotlib.pyplot as plt
import PCI_o_B
from PCI_o_B import CIfile as CI
from PCI_o_B import G2file as g2
from PCI_o_B import SharedFunctions as sf
class DAM(g2.G2):
def __init__(self,Fold... | [
"numpy.asarray"
] | [((2301, 2321), 'numpy.asarray', 'np.asarray', (['self.tau'], {}), '(self.tau)\n', (2311, 2321), True, 'import numpy as np\n'), ((1952, 1972), 'numpy.asarray', 'np.asarray', (['self.tau'], {}), '(self.tau)\n', (1962, 1972), True, 'import numpy as np\n')] |
__author__ = "<NAME>"
import numpy as np
from tensorflow import keras
from sktime_dl.classification._classifier import BaseDeepClassifier
from sktime_dl.networks._lstmfcn import LSTMFCNNetwork
from sktime_dl.utils import check_and_clean_data, \
check_and_clean_validation_data
from sktime_dl.utils import check_is_... | [
"sklearn.utils.check_random_state",
"sktime_dl.utils.check_is_fitted",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.callbacks.ReduceLROnPlateau",
"numpy.hstack",
"tensorflow.keras.models.Model",
"sktime_dl.utils.check_and_clean_data",
"sktime_dl.utils.check_and_clean_validation_data"
] | [((4872, 4933), 'tensorflow.keras.models.Model', 'keras.models.Model', ([], {'inputs': 'input_layers', 'outputs': 'output_layer'}), '(inputs=input_layers, outputs=output_layer)\n', (4890, 4933), False, 'from tensorflow import keras\n'), ((6945, 6982), 'sklearn.utils.check_random_state', 'check_random_state', (['self.ra... |
# Copyright (c) 2020 Horizon Robotics. 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 applicab... | [
"alf.configurable",
"gym.make",
"numpy.float32",
"copy.copy",
"numpy.zeros",
"numpy.array",
"gym.spaces.Box",
"alf.environments.suite_gym.wrap_env",
"numpy.prod",
"gym.spaces.Dict"
] | [((7467, 7502), 'alf.configurable', 'alf.configurable', ([], {'blacklist': "['env']"}), "(blacklist=['env'])\n", (7483, 7502), False, 'import alf\n'), ((11739, 11765), 'gym.make', 'gym.make', (['environment_name'], {}), '(environment_name)\n', (11747, 11765), False, 'import gym\n'), ((12665, 12839), 'alf.environments.s... |
#!/usr/bin/env python3
# Copyright 2017 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | [
"tensorflow.nn.softmax",
"matplotlib.pyplot.figaspect",
"matplotlib.pyplot.show",
"tensorflow.global_variables_initializer",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.Session",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.placeholder",
"tensorflow.matmul",
"tensorflow.... | [((1941, 1979), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 94]'], {}), '(tf.float32, [None, 94])\n', (1955, 1979), True, 'import tensorflow as tf\n'), ((1988, 2025), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 3]'], {}), '(tf.float32, [None, 3])\n', (2002, 2025), True, '... |
"""
The PIMA Indians dataset obtained from the UCI Machine Learning Repository
The goal is to predict whether or not a given female patient will contract diabetes
based on features such as BMI, age, and number of pregnancies
It is a binary classification problem
"""
import matplotlib.pyplot as plt
import numpy... | [
"matplotlib.pyplot.title",
"sklearn.model_selection.GridSearchCV",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.model_selection.cross_val_score",
"numpy.logspace",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.style.use"... | [((771, 794), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (784, 794), True, 'import matplotlib.pyplot as plt\n'), ((802, 838), 'pandas.read_csv', 'pd.read_csv', (['"""datasets/diabetes.csv"""'], {}), "('datasets/diabetes.csv')\n", (813, 838), True, 'import pandas as pd\n'), (... |
import utils as util
import tensorflow as tf
import numpy as np
def forecast_model(series, time,forecastDays):
split_time=2555
time_train=time[:split_time]
x_train=series[:split_time]
split_time_test=3285
time_valid=time[split_time:split_time_test]
x_valid=series[split_time:split_time_test]
... | [
"tensorflow.random.set_seed",
"tensorflow.keras.metrics.mean_absolute_error",
"numpy.random.seed",
"utils.windowed_dataset",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv1D",
"tensorflow.keras.backend.clear_session",
"tensorflow.keras.optimizers.SGD",
"tensorflow.keras.losses.Huber"... | [((461, 493), 'tensorflow.keras.backend.clear_session', 'tf.keras.backend.clear_session', ([], {}), '()\n', (491, 493), True, 'import tensorflow as tf\n'), ((498, 520), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(51)'], {}), '(51)\n', (516, 520), True, 'import tensorflow as tf\n'), ((525, 543), 'numpy.rando... |
# encoding=utf-8
"""
Created on 21:29 2018/11/12
@author: <NAME>
"""
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
def kernel(ker, X1, X2, gamma):
K = None
if not ker... | [
"numpy.eye",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"numpy.ones",
"numpy.hstack",
"numpy.argsort",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.linalg.norm",
"numpy.dot",
"numpy.linalg.multi_dot"
] | [((1536, 1559), 'numpy.hstack', 'np.hstack', (['(Xs.T, Xt.T)'], {}), '((Xs.T, Xt.T))\n', (1545, 1559), True, 'import numpy as np\n'), ((1573, 1598), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (1587, 1598), True, 'import numpy as np\n'), ((2127, 2140), 'numpy.argsort', 'np.argsort'... |
# coding: utf-8
import numpy as np
import math
from block_average import block_average
def main():
# Enter details here
n_samples = [int(2.5e5)]
# n_samples = [int(5e5),int(1e6),int(2e6),int(4e6)]
for n_sample in n_samples:
# Generate uncorrelated random samples
uncorrelated_sample... | [
"numpy.random.uniform",
"math.exp",
"numpy.asarray",
"block_average.block_average",
"numpy.mean",
"numpy.random.normal",
"numpy.var"
] | [((324, 355), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'n_sample'}), '(size=n_sample)\n', (340, 355), True, 'import numpy as np\n'), ((375, 404), 'numpy.mean', 'np.mean', (['uncorrelated_samples'], {}), '(uncorrelated_samples)\n', (382, 404), True, 'import numpy as np\n'), ((424, 452), 'numpy.var', 'np.... |
"""
Code for collecting failure trajectories using Bayesian Optimization
Project : Policy correction using Bayesian Optimization
Description : The file contains functions for computing failure trajectories given RL policy and
safety specifications
"""
import numpy as np
import gym
import GPyOp... | [
"pickle.dump",
"numpy.abs",
"gym.make",
"network.FeedForwardActorNN",
"torch.load",
"eval_policy.display",
"torch.Tensor",
"numpy.array",
"numpy.random.rand",
"numpy.arccos"
] | [((1450, 1477), 'torch.Tensor', 'torch.Tensor', (['env.env.state'], {}), '(env.env.state)\n', (1462, 1477), False, 'import torch\n'), ((1592, 1624), 'eval_policy.display', 'display', (['obs', 'policy', 'env', '(False)'], {}), '(obs, policy, env, False)\n', (1599, 1624), False, 'from eval_policy import display\n'), ((40... |
import os
import numpy as np
import time
from multiprocessing import Pool
import psutil
import cv2
import matplotlib.pyplot as plt
import av #for better performance
##############################################################################
#For EPM, please select pionts from the OPEN arm to the CLOSE arm and press... | [
"os.mkdir",
"cv2.medianBlur",
"numpy.argmax",
"cv2.getPerspectiveTransform",
"numpy.isnan",
"cv2.ellipse",
"numpy.mean",
"cv2.rectangle",
"cv2.imshow",
"os.path.join",
"psutil.cpu_count",
"cv2.warpPerspective",
"cv2.cvtColor",
"cv2.fitEllipse",
"cv2.setMouseCallback",
"numpy.int32",
... | [((1349, 1372), 'psutil.cpu_count', 'psutil.cpu_count', (['(False)'], {}), '(False)\n', (1365, 1372), False, 'import psutil\n'), ((1793, 1839), 'numpy.zeros', 'np.zeros', ([], {'shape': '(w + h, w + h)', 'dtype': 'np.uint8'}), '(shape=(w + h, w + h), dtype=np.uint8)\n', (1801, 1839), True, 'import numpy as np\n'), ((72... |
#!/usr/bin/python3
# Copyright 2017-2018 <NAME>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the followin... | [
"pandas.DataFrame",
"numpy.sum",
"numpy.average",
"numpy.log",
"os.path.basename",
"pandas.read_csv",
"os.path.isdir",
"os.walk",
"six.StringIO",
"multiprocessing.Pool",
"numpy.mean",
"os.path.normpath",
"pytablewriter.MarkdownTableWriter",
"glob.glob",
"pandas.concat"
] | [((1914, 1943), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (1926, 1943), True, 'import pandas as pd\n'), ((3874, 3909), 'pytablewriter.MarkdownTableWriter', 'pytablewriter.MarkdownTableWriter', ([], {}), '()\n', (3907, 3909), False, 'import pytablewriter\n'), ((3986, 4000),... |
import sklearn
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn... | [
"matplotlib.pyplot.title",
"sklearn.model_selection.GridSearchCV",
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"sklearn.externals.six.StringIO",
"numpy.... | [((998, 1018), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (1016, 1018), False, 'from sklearn.datasets import load_breast_cancer\n'), ((1357, 1392), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (1375, 1392), False,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import numpy as np
from ..utils.generic_utils import get_uid
class Layer():
"""Abstract base layer class."""
def __init__(self, **kwargs):
self._trainable_weights = []
self._non_trainable_weights = []
self._grads = {} # (... | [
"numpy.zeros_like",
"numpy.expand_dims"
] | [((1652, 1682), 'numpy.expand_dims', 'np.expand_dims', (['weight'], {'axis': '(0)'}), '(weight, axis=0)\n', (1666, 1682), True, 'import numpy as np\n'), ((1727, 1748), 'numpy.zeros_like', 'np.zeros_like', (['weight'], {}), '(weight)\n', (1740, 1748), True, 'import numpy as np\n'), ((2777, 2802), 'numpy.zeros_like', 'np... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 22:27:03 2020
@author: <NAME>
"""
import math
import tqdm
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import utils
from net import DCRNNModel
# import sys
# sys.path.append("./xlwang_version")
# from dcrnn_model import DCRNNModel
"""
H... | [
"tqdm.tqdm",
"math.exp",
"net.DCRNNModel",
"math.ceil",
"pandas.read_csv",
"utils.get_adjacency_matrix",
"utils.masked_mape_np",
"torch.cuda.max_memory_allocated",
"numpy.zeros",
"torch.FloatTensor",
"utils.load_dataset",
"utils.masked_mae_loss",
"utils.masked_mae_np",
"torch.cuda.is_avail... | [((1085, 1149), 'pandas.read_csv', 'pd.read_csv', (['sensor_distance'], {'dtype': "{'from': 'str', 'to': 'str'}"}), "(sensor_distance, dtype={'from': 'str', 'to': 'str'})\n", (1096, 1149), True, 'import pandas as pd\n'), ((1202, 1253), 'utils.get_adjacency_matrix', 'utils.get_adjacency_matrix', (['distance_df', 'sensor... |
import numpy as np
from rdkit.DataStructs.cDataStructs import ExplicitBitVect, SparseBitVect
from scipy.sparse import issparse, csr_matrix
from collections import defaultdict
from rdkit import DataStructs
from luna.util.exceptions import (BitsValueError, InvalidFingerprintType, IllegalArgumentError, FingerprintCountsE... | [
"scipy.sparse.issparse",
"collections.defaultdict",
"luna.util.exceptions.IllegalArgumentError",
"luna.util.exceptions.InvalidFingerprintType",
"numpy.unique",
"luna.util.exceptions.BitsValueError",
"numpy.intersect1d",
"numpy.union1d",
"numpy.log2",
"numpy.asarray",
"luna.util.exceptions.Finger... | [((390, 409), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (407, 409), False, 'import logging\n'), ((1543, 1577), 'numpy.asarray', 'np.asarray', (['indices'], {'dtype': 'np.long'}), '(indices, dtype=np.long)\n', (1553, 1577), True, 'import numpy as np\n'), ((1835, 1853), 'numpy.unique', 'np.unique', (['i... |
import torch.optim as optim
from sklearn.metrics import roc_auc_score, f1_score, jaccard_score
from model_plus import createDeepLabv3Plus
import sys
print(sys.version, sys.platform, sys.executable)
from trainer_plus import train_model
import datahandler_plus
import argparse
import os
import torch
import numpy
torch.cu... | [
"trainer_plus.train_model",
"os.makedirs",
"argparse.ArgumentParser",
"datahandler_plus.get_dataloader_single_folder",
"torch.load",
"os.path.exists",
"model_plus.createDeepLabv3Plus",
"torch.nn.CrossEntropyLoss",
"torch.FloatTensor",
"numpy.array",
"torch.cuda.empty_cache",
"datahandler_plus.... | [((312, 336), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (334, 336), False, 'import torch\n'), ((460, 485), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (483, 485), False, 'import argparse\n'), ((3450, 3557), 'trainer_plus.train_model', 'train_model', (['model', 'cr... |
"""
====================================
Linear algebra (:mod:`scipy.linalg`)
====================================
.. currentmodule:: scipy.linalg
Linear algebra functions.
.. seealso::
`numpy.linalg` for more linear algebra functions. Note that
although `scipy.linalg` imports most of them, ident... | [
"numpy.dual.register_func",
"numpy.testing.Tester"
] | [((6396, 6424), 'numpy.dual.register_func', 'register_func', (['"""pinv"""', 'pinv2'], {}), "('pinv', pinv2)\n", (6409, 6424), False, 'from numpy.dual import register_func\n'), ((6523, 6531), 'numpy.testing.Tester', 'Tester', ([], {}), '()\n', (6529, 6531), False, 'from numpy.testing import Tester\n'), ((6546, 6554), '... |
import os
from PIL import Image
from models.model import model
import argparse
import numpy as np
import tensorflow as tf
import shutil
def create(args):
if args.pre_trained == 'facenet':
from models.Face_recognition import FR_model
FR = FR_model()
Model = tf.keras.models.load_model(args.s... | [
"os.mkdir",
"tensorflow.keras.models.load_model",
"argparse.ArgumentParser",
"numpy.asarray",
"models.Face_recognition.FR_model",
"PIL.Image.open",
"shutil.move",
"os.listdir"
] | [((373, 389), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (383, 389), False, 'import os\n'), ((1063, 1083), 'os.mkdir', 'os.mkdir', (['"""Face-AHQ"""'], {}), "('Face-AHQ')\n", (1071, 1083), False, 'import os\n'), ((1618, 1643), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1641, 1... |
from __future__ import unicode_literals, print_function, division
from collections import Counter
from nltk.tokenize import TweetTokenizer
import cPickle as cp
import io
import numpy as np
PAD_TOKEN = 0
SOS_TOKEN = 1
EOS_TOKEN = 2
VOCAB_SIZE = 10000
class Lang(object):
def __init__(self, name, lowercase=True,... | [
"nltk.tokenize.TweetTokenizer",
"numpy.random.normal",
"io.open",
"collections.Counter",
"numpy.concatenate"
] | [((3179, 3221), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1, embedding_dim)'], {}), '(0, 1, (1, embedding_dim))\n', (3195, 3221), True, 'import numpy as np\n'), ((3245, 3287), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1, embedding_dim)'], {}), '(0, 1, (1, embedding_dim))\n', (3261,... |
# -*- coding: utf-8 -*-
"""
A program that carries out mini batch k-means clustering on Movielens datatset"""
from __future__ import print_function, division, absolute_import, unicode_literals
from decimal import *
#other stuff we need to import
import csv
import numpy as np
from sklearn.cluster import ... | [
"sklearn.cluster.MiniBatchKMeans",
"numpy.zeros"
] | [((1958, 2003), 'numpy.zeros', 'np.zeros', (['(number_of_users, number_of_movies)'], {}), '((number_of_users, number_of_movies))\n', (1966, 2003), True, 'import numpy as np\n'), ((2991, 3020), 'sklearn.cluster.MiniBatchKMeans', 'MiniBatchKMeans', ([], {'n_clusters': 'K'}), '(n_clusters=K)\n', (3006, 3020), False, 'from... |
import json # note: ujson fails this test due to float equality
import copy
import numpy as np
import pytest
from gym.spaces import Tuple, Box, Discrete, MultiDiscrete, MultiBinary, Dict
@pytest.mark.parametrize(
"space",
[
Discrete(3),
Discrete(5, start=-2),
Box(low=0.0, high=np.in... | [
"gym.spaces.MultiBinary",
"copy.deepcopy",
"gym.spaces.Discrete",
"copy.copy",
"json.dumps",
"gym.spaces.MultiDiscrete",
"numpy.random.default_rng",
"pytest.raises",
"numpy.array",
"gym.spaces.Box",
"gym.spaces.Tuple",
"gym.spaces.Dict"
] | [((2604, 2620), 'copy.copy', 'copy.copy', (['space'], {}), '(space)\n', (2613, 2620), False, 'import copy\n'), ((6518, 6550), 'gym.spaces.Box', 'Box', ([], {'low': '(0)', 'high': '(1)', 'shape': '(3, 3)'}), '(low=0, high=1, shape=(3, 3))\n', (6521, 6550), False, 'from gym.spaces import Tuple, Box, Discrete, MultiDiscre... |
import numpy as np
import tensorflow as tf
from lib.crf import crf_inference
from lib.CC_labeling_8 import CC_lab
def single_generate_seed_step(params):
"""Implemented seeded region growing
Parameters
----------
params : 3-tuple of numpy 4D arrays
(tag) : numpy 4D array (size: B x 1 x 1 x C),... | [
"tensorflow.contrib.layers.xavier_initializer",
"numpy.load",
"tensorflow.reduce_sum",
"numpy.sum",
"numpy.argmax",
"tensorflow.constant_initializer",
"tensorflow.Variable",
"tensorflow.nn.conv2d",
"tensorflow.reduce_max",
"lib.CC_labeling_8.CC_lab",
"tensorflow.get_variable",
"tensorflow.nn.r... | [((3106, 3133), 'numpy.expand_dims', 'np.expand_dims', (['cue'], {'axis': '(0)'}), '(cue, axis=0)\n', (3120, 3133), True, 'import numpy as np\n'), ((951, 983), 'numpy.argmax', 'np.argmax', (['existing_prob'], {'axis': '(2)'}), '(existing_prob, axis=2)\n', (960, 983), True, 'import numpy as np\n'), ((2213, 2232), 'numpy... |
import os
import ndjson
import json
import time
from options import TestOptions
from framework import SketchModel
from utils import load_data
from writer import Writer
import numpy as np
from evalTool import *
def run_eval(opt=None, model=None, loader=None, dataset='test', write_result=False):
if opt is None:
... | [
"utils.load_data",
"numpy.average",
"ndjson.load",
"options.TestOptions",
"ndjson.dump",
"framework.SketchModel"
] | [((1682, 1702), 'numpy.average', 'np.average', (['lossList'], {}), '(lossList)\n', (1692, 1702), True, 'import numpy as np\n'), ((1718, 1743), 'numpy.average', 'np.average', (['p_metric_list'], {}), '(p_metric_list)\n', (1728, 1743), True, 'import numpy as np\n'), ((1759, 1784), 'numpy.average', 'np.average', (['c_metr... |
"""
Author: <NAME> (<EMAIL>)
Date: May 07, 2020
"""
from __future__ import print_function
import torch
import torch.nn as nn
import numpy as np
from itertools import combinations
class SupConLoss(nn.Module):
"""Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
It also supports the unsuper... | [
"numpy.triu",
"torch.eye",
"numpy.isnan",
"torch.arange",
"torch.device",
"numpy.unique",
"numpy.meshgrid",
"torch.diag",
"torch.exp",
"torch.triu",
"torch.unbind",
"torch.matmul",
"torch.log",
"itertools.combinations",
"torch.max",
"torch.sum",
"torch.ones_like",
"torch.eq",
"nu... | [((5136, 5159), 'itertools.combinations', 'combinations', (['nviews', '(2)'], {}), '(nviews, 2)\n', (5148, 5159), False, 'from itertools import combinations\n'), ((2896, 2947), 'torch.max', 'torch.max', (['anchor_dot_contrast'], {'dim': '(1)', 'keepdim': '(True)'}), '(anchor_dot_contrast, dim=1, keepdim=True)\n', (2905... |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import time
# Converts a Tensor into an image array (numpy)
# |imtype|: the desired type of the converted numpy array
def tensor2im(input_image, imtype=np.uint8):
if isinstance(input_image, torch.Tensor):
... | [
"os.makedirs",
"numpy.median",
"numpy.std",
"os.path.exists",
"numpy.transpose",
"numpy.clip",
"time.time",
"numpy.min",
"numpy.max",
"numpy.mean",
"numpy.tile",
"PIL.Image.fromarray",
"torch.abs"
] | [((772, 804), 'numpy.clip', 'np.clip', (['image_numpy', '(0.0)', '(255.0)'], {}), '(image_numpy, 0.0, 255.0)\n', (779, 804), True, 'import numpy as np\n'), ((1206, 1234), 'PIL.Image.fromarray', 'Image.fromarray', (['image_numpy'], {}), '(image_numpy)\n', (1221, 1234), False, 'from PIL import Image\n'), ((647, 678), 'nu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 14 09:10:29 2021
Author: <NAME>
Functions for implementing the edge detection scheme first proposed by Zhang and Bao [1].
Modified for use with pywt's SWT2 transform and employs double thresholding similar to canny to improve noise resilience and revovery of wea... | [
"scipy.ndimage.generate_binary_structure",
"numpy.abs",
"numpy.sum",
"numpy.empty",
"numpy.ones",
"numpy.clip",
"pywt.swt2",
"numpy.arange",
"cv2.imshow",
"numpy.prod",
"numpy.max",
"cv2.destroyAllWindows",
"numpy.roll",
"cv2.waitKey",
"numpy.hypot",
"pywt.Wavelet",
"scipy.ndimage.bi... | [((2283, 2388), 'pywt.swt2', 'swt2', (['image'], {'wavelet': 'wavelet', 'level': 'max_level', 'start_level': 'start_level', 'norm': '(False)', 'trim_approx': '(True)'}), '(image, wavelet=wavelet, level=max_level, start_level=start_level, norm\n =False, trim_approx=True)\n', (2287, 2388), False, 'from pywt import swt... |
import pytest
import numpy as np
import xarray as xr
import dask.array as da
from xrspatial import curvature
from xrspatial.utils import doesnt_have_cuda
from xrspatial.tests.general_checks import general_output_checks
elevation = np.asarray([
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
... | [
"xrspatial.utils.doesnt_have_cuda",
"cupy.asarray",
"numpy.asarray",
"xrspatial.tests.general_checks.general_output_checks",
"numpy.array",
"xarray.DataArray",
"dask.array.from_array",
"xrspatial.curvature"
] | [((248, 756), 'numpy.asarray', 'np.asarray', (['[[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], [1584.8767, 1584.8767, \n 1585.0546, 1585.2324, 1585.2324, 1585.2324], [1585.0546, 1585.0546, \n 1585.2324, 1585.588, 1585.588, 1585.588], [1585.2324, 1585.4102, \n 1585.588, 1585.588, 1585.588, 1585.588], [1585.... |
import os
path = os.getcwd()
from cu__grid_cell.data_gen import data_gen
from cu__grid_cell.preparation import preparation
import numpy as np
from cu__grid_cell.Validation.validation_utils import plot_image, grid_based_eval_with_iou, plot_image3d, nms, concatenate_cells
import matplotlib.pyplot as plt
import cv2
d... | [
"matplotlib.pyplot.show",
"numpy.ones_like",
"os.getcwd",
"cu__grid_cell.Validation.validation_utils.concatenate_cells",
"matplotlib.pyplot.figure",
"cu__grid_cell.data_gen.data_gen",
"numpy.array",
"numpy.exp",
"numpy.int32",
"numpy.matmul",
"cu__grid_cell.Validation.validation_utils.nms",
"c... | [((18, 29), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (27, 29), False, 'import os\n'), ((392, 417), 'cu__grid_cell.preparation.preparation', 'preparation', ([], {'testing': '(True)'}), '(testing=True)\n', (403, 417), False, 'from cu__grid_cell.preparation import preparation\n'), ((450, 551), 'cu__grid_cell.data_gen.d... |
import argparse
import torch
from pathlib import Path
import h5py
import logging
from tqdm import tqdm
import pprint
import numpy as np
from . import matchers
from .utils.base_model import dynamic_load
from .utils.parsers import names_to_pair
'''
A set of standard configurations that can be directly selected from th... | [
"numpy.stack",
"tqdm.tqdm",
"pprint.pformat",
"numpy.count_nonzero",
"argparse.ArgumentParser",
"torch.topk",
"logging.warning",
"logging.info",
"torch.einsum",
"pathlib.Path",
"torch.cuda.is_available",
"torch.no_grad",
"torch.from_numpy"
] | [((1171, 1186), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1184, 1186), False, 'import torch\n'), ((2879, 2894), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2892, 2894), False, 'import torch\n'), ((7473, 7488), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7486, 7488), False, 'import torch\n')... |
import LMRt
import os
import numpy as np
import pandas as pd
import xarray as xr
# preprocessing
print("\n======== Preprocessing ========\n")
config = 'configs.yml'
recon_iterations = 1
figure = 'graph'
job = LMRt.ReconJob()
job.load_configs(config, verbose=True)
job.load_proxydb(verbose=True)
job.filter_proxydb(ve... | [
"scipy.io.loadmat",
"LMRt.ReconJob",
"numpy.zeros",
"numpy.mean",
"numpy.arange",
"LMRt.ReconRes",
"os.path.join"
] | [((213, 228), 'LMRt.ReconJob', 'LMRt.ReconJob', ([], {}), '()\n', (226, 228), False, 'import LMRt\n'), ((494, 545), 'os.path.join', 'os.path.join', (['job_dirpath', '"""seasonalized_prior.pkl"""'], {}), "(job_dirpath, 'seasonalized_prior.pkl')\n", (506, 545), False, 'import os\n'), ((570, 619), 'os.path.join', 'os.path... |
import json
import numpy as np
import cv2
from numpy.core.records import array
import cv2.aruco as aruco
import socket
from urllib.request import urlopen
from get_img import get_img as gi
ADDRESS = ('', 10000)
central = None
conn_pool = []
central = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
central.setsockopt... | [
"cv2.GaussianBlur",
"cv2.aruco.drawDetectedMarkers",
"numpy.arctan2",
"socket.socket",
"cv2.aruco.detectMarkers",
"numpy.linalg.norm",
"cv2.imshow",
"json.loads",
"cv2.cvtColor",
"cv2.aruco.drawAxis",
"numpy.arccos",
"cv2.destroyAllWindows",
"cv2.aruco.estimatePoseSingleMarkers",
"cv2.wait... | [((252, 301), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (265, 301), False, 'import socket\n'), ((570, 594), 'numpy.array', 'np.array', (['[35, 110, 106]'], {}), '([35, 110, 106])\n', (578, 594), True, 'import numpy as np\n'), ((609, 633),... |
import numpy as np
from .VariableUnitTest import VariableUnitTest
from gwlfe.Input.WaterBudget import Percolation
class TestPercolation(VariableUnitTest):
def test_Percolation_ground_truth(self):
z = self.z
np.testing.assert_array_almost_equal(
np.load(self.basepath + "/Percolation.n... | [
"gwlfe.Input.WaterBudget.Percolation.Percolation_f",
"numpy.load",
"gwlfe.Input.WaterBudget.Percolation.Percolation"
] | [((281, 324), 'numpy.load', 'np.load', (["(self.basepath + '/Percolation.npy')"], {}), "(self.basepath + '/Percolation.npy')\n", (288, 324), True, 'import numpy as np\n'), ((338, 579), 'gwlfe.Input.WaterBudget.Percolation.Percolation', 'Percolation.Percolation', (['z.NYrs', 'z.DaysMonth', 'z.Temp', 'z.InitSnow_0', 'z.P... |
"""
Solution-based probabilistic linear solvers.
Implementations of solution-based linear solvers which perform inference on the solution
of a linear system given linear observations.
"""
import warnings
import numpy as np
from probnum.linalg.linearsolvers.matrixbased import ProbabilisticLinearSolver
class Solutio... | [
"warnings.warn",
"numpy.linalg.norm"
] | [((2132, 2224), 'warnings.warn', 'warnings.warn', (['"""Iteration terminated. Solver reached the maximum number of iterations."""'], {}), "(\n 'Iteration terminated. Solver reached the maximum number of iterations.')\n", (2145, 2224), False, 'import warnings\n'), ((2339, 2360), 'numpy.linalg.norm', 'np.linalg.norm',... |
import numpy as np
#from ..utils import *
from ..metrics import Metrics
from .map_data import StdMapData
class StdMapMetrics():
"""
Class used for calculating pattern attributes and difficulty.
.. warning::
Undocumented functions in this class are not supported and are experimental.
"""
... | [
"numpy.arctan2",
"numpy.logical_and",
"numpy.asarray",
"numpy.sin",
"numpy.diff",
"numpy.cos"
] | [((944, 954), 'numpy.diff', 'np.diff', (['t'], {}), '(t)\n', (951, 954), True, 'import numpy as np\n'), ((4638, 4648), 'numpy.diff', 'np.diff', (['x'], {}), '(x)\n', (4645, 4648), True, 'import numpy as np\n'), ((4662, 4672), 'numpy.diff', 'np.diff', (['y'], {}), '(y)\n', (4669, 4672), True, 'import numpy as np\n'), ((... |
#%%
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
def loss_fn(X, Y, beta):
return cp.norm2(cp.matmul(X, beta) - Y)**2
def regularizer(beta):
return cp.norm1(beta)
def objective_fn(X, Y, beta, lambd):
return loss_fn(X, Y, beta) + lambd * regularizer(beta)
def mse(X, Y, beta):
... | [
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.title",
"numpy.random.seed",
"cvxpy.Parameter",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"matplotlib.pyplot.show",
"numpy.logspace",
"matplotlib.pyplot.legend",
"cvxpy.matmul",
"cvxpy.norm1",
"numpy.random.normal",
"cvxpy.Variable",
"ma... | [((936, 950), 'cvxpy.Variable', 'cp.Variable', (['n'], {}), '(n)\n', (947, 950), True, 'import cvxpy as cp\n'), ((959, 984), 'cvxpy.Parameter', 'cp.Parameter', ([], {'nonneg': '(True)'}), '(nonneg=True)\n', (971, 984), True, 'import cvxpy as cp\n'), ((1080, 1102), 'numpy.logspace', 'np.logspace', (['(-2)', '(3)', '(50)... |
import numpy as np
def stringify_vec(vec):
s = ""
for x in vec: s += str(x) + " "
return s
def distance(p1, p2):
pv1 = np.asarray(p1)
pv2 = np.asarray(p2)
return np.linalg.norm(pv1 - pv2)
def multireplace(arr, x, sub_arr):
new_arr = []
for entry in arr:
if (entry == x).all():
... | [
"numpy.asarray",
"numpy.cross",
"numpy.sin",
"numpy.linalg.norm",
"numpy.cos",
"numpy.dot"
] | [((137, 151), 'numpy.asarray', 'np.asarray', (['p1'], {}), '(p1)\n', (147, 151), True, 'import numpy as np\n'), ((162, 176), 'numpy.asarray', 'np.asarray', (['p2'], {}), '(p2)\n', (172, 176), True, 'import numpy as np\n'), ((188, 213), 'numpy.linalg.norm', 'np.linalg.norm', (['(pv1 - pv2)'], {}), '(pv1 - pv2)\n', (202,... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
colNames = ['x', 'y', 'z', 'particle.type', 'BPM no']
particleTypeNames = {
-1: 'other',
0: 'e-',
1: 'e+',
... | [
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.ma.masked_where",
"pandas.read_csv",
"numpy.histogram2d",
"matplotlib.pyplot.Circle",
"matplotlib.pyplot.subplots"
] | [((345, 443), 'pandas.read_csv', 'pd.read_csv', (['"""../build-10/out_nt_bpmScreenHits.csv"""'], {'header': 'None', 'names': 'colNames', 'comment': '"""#"""'}), "('../build-10/out_nt_bpmScreenHits.csv', header=None, names=\n colNames, comment='#')\n", (356, 443), True, 'import pandas as pd\n'), ((573, 658), 'numpy.h... |
"""
LSH for euclidean distance.
"""
from pyspark import SparkContext, RDD
from datming.utils import join_multiple_keys
import numpy as np
__all__ = [
"EuclideanDistance"
]
class EuclideanDistanceLSH(object):
"""
Find item pairs between which Euclidean Distance is closed enough.
"""
def __init__... | [
"numpy.random.seed",
"numpy.random.randn",
"pyspark.SparkContext.getOrCreate",
"datming.utils.join_multiple_keys",
"numpy.random.randint",
"numpy.linalg.norm",
"numpy.dot"
] | [((4908, 4941), 'numpy.linalg.norm', 'np.linalg.norm', (['(vector1 - vector2)'], {}), '(vector1 - vector2)\n', (4922, 4941), True, 'import numpy as np\n'), ((5059, 5085), 'pyspark.SparkContext.getOrCreate', 'SparkContext.getOrCreate', ([], {}), '()\n', (5083, 5085), False, 'from pyspark import SparkContext, RDD\n'), ((... |
# =============================================================================
#
# Explicit Finite Difference Method Code
# Solves the 2D Temperature Convection-Diffusion Equation
# Assumes Tubular Plug-Flow-Reactor in Laminar Regime
# Assumes hagen poiseuille velocity profile
# Heat Source-Sink Included Uses ... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.ones",
"matplotlib.pyplot.colorbar",
"numpy.max",
"numpy.array",
"matplotlib.pyplot.contourf",
"numpy.linspace",
"m... | [((2506, 2528), 'numpy.linspace', 'np.linspace', (['(0)', 'xl', 'nx'], {}), '(0, xl, nx)\n', (2517, 2528), True, 'import numpy as np\n'), ((2535, 2557), 'numpy.linspace', 'np.linspace', (['(0)', 'yl', 'ny'], {}), '(0, yl, ny)\n', (2546, 2557), True, 'import numpy as np\n'), ((2567, 2584), 'numpy.meshgrid', 'np.meshgrid... |
import os
from stray.scene import Scene
from stray.renderer import Renderer
import numpy as np
import pycocotools.mask as mask_util
import pickle
def write_segmentation_masks(scene_path):
scene = Scene(scene_path)
renderer = Renderer(scene)
segmentation_parent_path = os.path.join(scene_path, "segmentation... | [
"pickle.dump",
"os.makedirs",
"numpy.asarray",
"stray.renderer.Renderer",
"stray.scene.Scene",
"os.path.join"
] | [((202, 219), 'stray.scene.Scene', 'Scene', (['scene_path'], {}), '(scene_path)\n', (207, 219), False, 'from stray.scene import Scene\n'), ((235, 250), 'stray.renderer.Renderer', 'Renderer', (['scene'], {}), '(scene)\n', (243, 250), False, 'from stray.renderer import Renderer\n'), ((282, 322), 'os.path.join', 'os.path.... |
from setuptools import setup
from Cython.Build import cythonize
from distutils.extension import Extension
from distutils.command.build_ext import build_ext
import numpy
import mpi4py
import os
class build_ext_subclass(build_ext):
user_options = build_ext.user_options + \
[
('mpicc', None, ... | [
"Cython.Build.cythonize",
"distutils.command.build_ext.build_ext.finalize_options",
"mpi4py.get_config",
"os.environ.get",
"distutils.command.build_ext.build_ext.initialize_options",
"distutils.command.build_ext.build_ext.build_extensions",
"numpy.get_include",
"re.search"
] | [((1444, 1506), 're.search', 're.search', (['"""^__version__ = [\'\\\\"]([^\'\\\\"]*)[\'\\\\"]"""', 's', 're.M'], {}), '(\'^__version__ = [\\\'\\\\"]([^\\\'\\\\"]*)[\\\'\\\\"]\', s, re.M)\n', (1453, 1506), False, 'import re\n'), ((516, 549), 'os.environ.get', 'os.environ.get', (['"""MPICC"""', 'compiler'], {}), "('MPIC... |
"""Tests for graphmode_tensornetwork."""
import numpy as np
import tensorflow as tf
from tensornetwork import (contract, connect, flatten_edges_between,
contract_between, Node)
import pytest
class GraphmodeTensorNetworkTest(tf.test.TestCase):
def test_basic_graphmode(self):
# pylint:... | [
"tensorflow.test.main",
"tensorflow.ones",
"tensornetwork.Node",
"tensorflow.convert_to_tensor",
"tensornetwork.contract",
"tensorflow.compat.v1.train.GradientDescentOptimizer",
"tensornetwork.contract_between",
"numpy.ones",
"tensorflow.compat.v1.Session",
"tensornetwork.connect",
"tensorflow.m... | [((1743, 1820), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Test fails due to probable bug in tensorflow 2.0.0"""'}), "(reason='Test fails due to probable bug in tensorflow 2.0.0')\n", (1759, 1820), False, 'import pytest\n'), ((3750, 3764), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (3762... |
import os
import sys
import glob
import numpy as np
import tensorflow as tf
import scipy
import scipy.io
import keras
from keras.models import Model, Sequential
from keras.layers import *
from keras.optimizers import Adam
from keras import regularizers
from keras import backend as K
from keras.utils import to_categori... | [
"numpy.fromfile",
"keras.models.Model",
"keras.backend.set_image_data_format"
] | [((4799, 4840), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_first"""'], {}), "('channels_first')\n", (4822, 4840), True, 'from keras import backend as K\n'), ((3827, 3846), 'keras.models.Model', 'Model', (['img_input', 'x'], {}), '(img_input, x)\n', (3832, 3846), False, 'from keras.... |
# encoding utf-8
import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels.tools import eval_measures
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
class Preprocessing:
def __init__(self, data_raw):
self.data_clean = data_r... | [
"sklearn.preprocessing.StandardScaler",
"numpy.log",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"statsmodels.api.add_constant"
] | [((2743, 2793), 'pandas.read_csv', 'pd.read_csv', (['"""./../../data/house_prices/train.csv"""'], {}), "('./../../data/house_prices/train.csv')\n", (2754, 2793), True, 'import pandas as pd\n'), ((2112, 2199), 'sklearn.model_selection.train_test_split', 'train_test_split', (['self.X', 'self.y'], {'train_size': 'TRAIN_SI... |
#!/usr/bin/env python
# stdlib imports
import urllib.request as request
import tempfile
import os.path
import sys
from datetime import datetime
# third party imports
import numpy as np
# local imports
from losspager.utils.expocat import ExpoCat
def commify(value):
if np.isnan(value):
return 'NaN'
r... | [
"losspager.utils.expocat.ExpoCat.fromDefault",
"numpy.array",
"numpy.isnan",
"datetime.datetime"
] | [((277, 292), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (285, 292), True, 'import numpy as np\n'), ((509, 550), 'numpy.array', 'np.array', (['[tdict[idx] for idx in indices]'], {}), '([tdict[idx] for idx in indices])\n', (517, 550), True, 'import numpy as np\n'), ((756, 777), 'losspager.utils.expocat.Exp... |
import numpy as np
import pandas as pd
import fasttext
from sklearn.preprocessing import MultiLabelBinarizer
from skmultilearn.model_selection import IterativeStratification, \
iterative_train_test_split
from functools import reduce
CIP_TAGS = list(map(lambda x: x.strip(),
"gratis, mat, musik, ... | [
"pandas.DataFrame",
"pandas.read_csv",
"fasttext.train_unsupervised",
"os.getcwd",
"sklearn.preprocessing.MultiLabelBinarizer",
"tagger._preprocessing.characterset.CharacterSet",
"tagger._preprocessing.html.HTMLToText",
"skmultilearn.model_selection.IterativeStratification",
"numpy.array",
"pandas... | [((1601, 1738), 'pandas.read_csv', 'pd.read_csv', (['path'], {'header': 'None', 'names': "['id', 'weekday', 'time', 'title', 'description', 'tag_status', 'tag']", 'na_values': "['-01:00:00']"}), "(path, header=None, names=['id', 'weekday', 'time', 'title',\n 'description', 'tag_status', 'tag'], na_values=['-01:00:00... |
import gym
import rlkit.torch.pytorch_util as ptu
from rlkit.data_management.obs_dict_replay_buffer import ObsDictRelabelingBuffer, WeightedObsDictRelabelingBuffer
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector import GoalConditionedPathCollector
from rlkit.torch.her.her impo... | [
"rlkit.torch.sac.sac.SACTrainer",
"rlkit.torch.sac.policies.MakeDeterministic",
"rlkit.torch.torch_rl_algorithm.TorchBatchRLAlgorithm",
"numpy.concatenate",
"rlkit.samplers.data_collector.GoalConditionedPathCollector",
"robosuite.make",
"numpy.random.seed",
"rlkit.torch.her.her.HERTrainer",
"numpy.z... | [((7709, 7762), 'robosuite.load_controller_config', 'load_controller_config', ([], {'default_controller': '"""OSC_POSE"""'}), "(default_controller='OSC_POSE')\n", (7731, 7762), False, 'from robosuite import load_controller_config\n'), ((9648, 9745), 'rlkit.torch.networks.ConcatMlp', 'ConcatMlp', ([], {'input_size': '(o... |
import numpy as np
from PIL import Image
import time
import cv2
global img
global point1, point2
global min_x, min_y, width, height, max_x, max_y
def on_mouse(event, x, y, flags, param):
global img, point1, point2, min_x, min_y, width, height, max_x, max_y
img2 = img.copy()
if event == cv2.EVENT_LBUTTOND... | [
"numpy.nan_to_num",
"numpy.isnan",
"numpy.random.randint",
"cv2.rectangle",
"cv2.imshow",
"numpy.zeros_like",
"numpy.copy",
"cv2.setMouseCallback",
"cv2.destroyAllWindows",
"cv2.resize",
"numpy.size",
"cv2.circle",
"cv2.waitKey",
"numpy.zeros",
"time.time",
"PIL.Image.open",
"cv2.imr... | [((1982, 1995), 'numpy.size', 'np.size', (['A', '(0)'], {}), '(A, 0)\n', (1989, 1995), True, 'import numpy as np\n'), ((2006, 2019), 'numpy.size', 'np.size', (['A', '(1)'], {}), '(A, 1)\n', (2013, 2019), True, 'import numpy as np\n'), ((2030, 2043), 'numpy.size', 'np.size', (['B', '(0)'], {}), '(B, 0)\n', (2037, 2043),... |
from hydra.experimental import compose, initialize
from random import randint
from random import seed
from soundbay.data import ClassifierDataset
import numpy as np
def test_dataloader() -> None:
seed(1)
with initialize(config_path="../soundbay/conf"):
# config is relative to a module
cfg = co... | [
"hydra.experimental.compose",
"random.randint",
"soundbay.data.ClassifierDataset",
"random.seed",
"hydra.experimental.initialize",
"numpy.issubdtype"
] | [((202, 209), 'random.seed', 'seed', (['(1)'], {}), '(1)\n', (206, 209), False, 'from random import seed\n'), ((219, 261), 'hydra.experimental.initialize', 'initialize', ([], {'config_path': '"""../soundbay/conf"""'}), "(config_path='../soundbay/conf')\n", (229, 261), False, 'from hydra.experimental import compose, ini... |
import yaml
import os
import numpy as np
class DataOrganizer:
def __init__(self,parameter_file_path):
self.base_path = parameter_file_path
self.load_params()
def load_params(self):
params_file = os.path.join(self.base_path,'params.yaml')
with open(params_file) as yamlstream:
... | [
"numpy.abs",
"yaml.load",
"os.path.join"
] | [((229, 272), 'os.path.join', 'os.path.join', (['self.base_path', '"""params.yaml"""'], {}), "(self.base_path, 'params.yaml')\n", (241, 272), False, 'import os\n'), ((344, 389), 'yaml.load', 'yaml.load', (['yamlstream'], {'Loader': 'yaml.SafeLoader'}), '(yamlstream, Loader=yaml.SafeLoader)\n', (353, 389), False, 'impor... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import os
import os.path as osp
def save_network(model, network_label, epoch, iteration, args):
dataset = args.data_path.split(os.sep)[-1]
save_filename = "{0}_net_{1}_{2}_{3}.pth".format(network_label, args.model, epoch... | [
"torch.nn.Dropout",
"torch.nn.MSELoss",
"torch.nn.ReLU",
"os.makedirs",
"torch.nn.BCELoss",
"torch.nn.Sequential",
"torch.nn.Tanh",
"numpy.ceil",
"torch.load",
"torch.nn.Conv2d",
"os.path.exists",
"torch.autograd.Variable",
"torch.nn.Sigmoid",
"torch.save",
"torch.cuda.is_available",
"... | [((355, 387), 'os.path.join', 'osp.join', (['args.save_dir', 'dataset'], {}), '(args.save_dir, dataset)\n', (363, 387), True, 'import os.path as osp\n'), ((484, 527), 'os.path.join', 'os.path.join', (['model_save_dir', 'save_filename'], {}), '(model_save_dir, save_filename)\n', (496, 527), False, 'import os\n'), ((839,... |
# -*- coding: utf-8 -*-
"""Wrapper to run RCSCON from the command line.
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern.pkcollections import PKDict
from pykern.... | [
"sirepo.template.template_common.exec_parameters",
"numpy.asarray",
"numpy.savetxt",
"sirepo.simulation_db.read_json",
"sirepo.template.sdds_util.read_sdds_pages",
"pykern.pkcollections.PKDict"
] | [((569, 602), 'sirepo.template.template_common.exec_parameters', 'template_common.exec_parameters', ([], {}), '()\n', (600, 602), False, 'from sirepo.template import template_common\n'), ((783, 839), 'sirepo.simulation_db.read_json', 'simulation_db.read_json', (['template_common.INPUT_BASE_NAME'], {}), '(template_commo... |
# Main.py - Pixels Fighting #
# Author: <NAME> #
# ---------------------#
# Imports #
import pygame
from pygame.locals import *
from helpers import *
import random
import numpy as np
import time
# ---------------------#
# Initialize number of rows/columns
INT = 100
INT_SQ = INT*INT
# Initialize size of arrays
SIZE... | [
"random.randint",
"pygame.Surface",
"pygame.event.get",
"pygame.display.set_mode",
"numpy.zeros",
"numpy.ones",
"pygame.init",
"time.sleep",
"pygame.display.update",
"pygame.font.Font",
"pygame.time.Clock",
"numpy.concatenate"
] | [((346, 359), 'pygame.init', 'pygame.init', ([], {}), '()\n', (357, 359), False, 'import pygame\n'), ((408, 468), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(80 + INT * SIZE, 160 + INT * SIZE)'], {}), '((80 + INT * SIZE, 160 + INT * SIZE))\n', (431, 468), False, 'import pygame\n'), ((483, 502), 'pygame.ti... |
import json
import numpy as np
import os
import pkg_resources
import re
from typing import Any, AnyStr, Dict, List, Optional, Tuple
def load_peripheral(pdata, templates=None):
"""Load a peripheral from a dict
This loads a peripheral with support for templates, as used in the board
definition file format
... | [
"pkg_resources.resource_listdir",
"json.loads",
"os.path.basename",
"os.path.isdir",
"os.path.isfile",
"numpy.sin",
"numpy.array",
"pkg_resources.resource_string",
"numpy.cos",
"numpy.dot",
"os.path.expanduser",
"os.listdir"
] | [((8557, 8606), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.config/purpledrop/boards"""'], {}), "('~/.config/purpledrop/boards')\n", (8575, 8606), False, 'import os\n'), ((8627, 8681), 'pkg_resources.resource_listdir', 'pkg_resources.resource_listdir', (['"""purpledrop"""', '"""boards"""'], {}), "('purpledrop'... |
from multiprocessing import Queue, Process
from threading import Thread
import numpy as np
import utils
from agent import PPOAgent
from policy import get_policy
from worker import Worker
import environments
class SimpleMaster:
def __init__(self, env_producer):
self.env_name = env_producer.get_env_name()... | [
"policy.get_policy",
"environments.get_config",
"utils.create_session",
"tensorflow.train.Saver",
"tensorflow.Summary",
"tensorflow.get_collection",
"tensorflow.global_variables_initializer",
"worker.Worker",
"tensorflow.variable_scope",
"tensorflow.summary.FileWriter",
"numpy.mean",
"agent.PP... | [((8593, 8631), 'worker.Worker', 'Worker', (['env_producer', 'i', 'q', 'w_in_queue'], {}), '(env_producer, i, q, w_in_queue)\n', (8599, 8631), False, 'from worker import Worker\n'), ((343, 381), 'environments.get_config', 'environments.get_config', (['self.env_name'], {}), '(self.env_name)\n', (366, 381), False, 'impor... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import rospkg
import threading
import yaml
from copy import deepcopy
import message_filters
import numpy as np
import pyrobot.utils.... | [
"sys.path.append",
"numpy.stack",
"cv_bridge.CvBridge",
"sys.path.remove",
"rospy.Subscriber",
"copy.deepcopy",
"numpy.multiply",
"rospy.logerr",
"threading.RLock",
"message_filters.ApproximateTimeSynchronizer",
"numpy.ones",
"numpy.linalg.inv",
"numpy.array",
"message_filters.Subscriber",... | [((627, 652), 'sys.path.append', 'sys.path.append', (['ros_path'], {}), '(ros_path)\n', (642, 652), False, 'import sys\n'), ((586, 611), 'sys.path.remove', 'sys.path.remove', (['ros_path'], {}), '(ros_path)\n', (601, 611), False, 'import sys\n'), ((1101, 1111), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (1109,... |
import matplotlib.pyplot as plt
import numpy as np
from typing import List, Union
from ..storage import History
from .util import to_lists_or_default
def plot_sample_numbers(
histories: Union[List, History],
labels: Union[List, str] = None,
rotation: int = 0,
title: str = "Total requi... | [
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((1238, 1252), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1250, 1252), True, 'import matplotlib.pyplot as plt\n'), ((1682, 1706), 'numpy.zeros', 'np.zeros', (['(n_pop, n_run)'], {}), '((n_pop, n_run))\n', (1690, 1706), True, 'import numpy as np\n'), ((2019, 2035), 'numpy.arange', 'np.arange', (['... |
import random
import math
import numpy as np
import matplotlib.pyplot as plt
# Calculating Pi using Monte Carlo algorithm.
def montecarlo_pi(times:int):
inside = 0
total = times
for i in range(times):
x_i = random.random()
y_i = random.random()
delta = x_i ** 2 + y_i **2 - 1
... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"random.random",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.xlabel"
] | [((816, 828), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (826, 828), True, 'import matplotlib.pyplot as plt\n'), ((927, 978), 'matplotlib.pyplot.plot', 'plt.plot', (['x_list', 'pi_', '"""b.-"""'], {'label': '"""approximation"""'}), "(x_list, pi_, 'b.-', label='approximation')\n", (935, 978), True, 'imp... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# TODO: Remove this when https://github.com/parejkoj/astropy/tree/luptonRGB
# is in Astropy.
"""
Combine 3 images to produce a properly-scaled RGB image following Lupton et al. (2004).
For details, see : http://adsabs.harvard.edu/abs/2004PASP..116... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"numpy.iinfo",
"numpy.errstate",
"numpy.where",
"numpy.array",
"numpy.arcsinh"
] | [((1660, 1699), 'numpy.array', 'np.array', (['intensity'], {'dtype': 'imageR.dtype'}), '(intensity, dtype=imageR.dtype)\n', (1668, 1699), True, 'import numpy as np\n'), ((16626, 16682), 'matplotlib.pyplot.imshow', 'plt.imshow', (['rgb'], {'interpolation': '"""nearest"""', 'origin': '"""lower"""'}), "(rgb, interpolation... |
import pytest
import numpy as np
import pandas as pd
from .stats import IV, WOE, gini, gini_cond, entropy_cond, quality, _IV, VIF
np.random.seed(1)
feature = np.random.rand(500)
target = np.random.randint(2, size = 500)
A = np.random.randint(100, size = 500)
B = np.random.randint(100, size = 500)
mask = np.random.r... | [
"pandas.DataFrame",
"numpy.random.seed",
"numpy.isnan",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand"
] | [((133, 150), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (147, 150), True, 'import numpy as np\n'), ((162, 181), 'numpy.random.rand', 'np.random.rand', (['(500)'], {}), '(500)\n', (176, 181), True, 'import numpy as np\n'), ((191, 221), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': ... |
import pickle
import numpy as np
with open('data/fake.pkl', 'rb') as f:
points, labels, scores, keys = pickle.load(f)
with open('data/fake_gt.pkl', 'rb') as f:
gt_points, gt_bboxes, gt_labels, gt_areas, gt_crowdeds = pickle.load(f)
gt_points_yx = []
gt_point_is_valids = []
for gt_point in gt_points:
gt_... | [
"numpy.savez",
"pickle.load"
] | [((700, 884), 'numpy.savez', 'np.savez', (['"""eval_point_coco_dataset_2019_02_18.npz"""'], {'points': 'gt_points_yx', 'is_valids': 'gt_point_is_valids', 'bboxes': 'gt_bboxes', 'labels': 'gt_labels', 'areas': 'gt_areas', 'crowdeds': 'gt_crowdeds'}), "('eval_point_coco_dataset_2019_02_18.npz', points=gt_points_yx,\n ... |
import numpy as np
import time
from unityagents import UnityEnvironment
from agent_utils import env_initialize, env_reset, state_reward_done_unpack
from dqn_agent import DQN_Agent
from agent_utils import load_dqn
from agent_utils import load_params, load_weights
def demo_agent(env, agent, n_episodes, epsilon=0.05, ... | [
"agent_utils.env_initialize",
"agent_utils.state_reward_done_unpack",
"agent_utils.load_dqn",
"dqn_agent.DQN_Agent",
"time.time",
"numpy.min",
"numpy.max",
"numpy.mean",
"numpy.random.randint",
"agent_utils.env_reset"
] | [((1355, 1397), 'agent_utils.env_initialize', 'env_initialize', (['env'], {'train_mode': 'train_mode'}), '(env, train_mode=train_mode)\n', (1369, 1397), False, 'from agent_utils import env_initialize, env_reset, state_reward_done_unpack\n'), ((1496, 1533), 'agent_utils.load_dqn', 'load_dqn', (['agent_name'], {'verbose'... |
from os import path
import numpy as np
from torch import nn
import torch
def get_embedding(embedding_path=None,
embedding_np=None,
num_embeddings=0, embedding_dim=0, freeze=True, **kargs):
"""Create embedding from:
1. saved numpy vocab array, embedding_path, freeze
2. n... | [
"torch.nn.Embedding",
"torch.Tensor",
"os.path.exists",
"numpy.load"
] | [((665, 717), 'torch.nn.Embedding', 'nn.Embedding', (['num_embeddings', 'embedding_dim'], {}), '(num_embeddings, embedding_dim, **kargs)\n', (677, 717), False, 'from torch import nn\n'), ((458, 485), 'os.path.exists', 'path.exists', (['embedding_path'], {}), '(embedding_path)\n', (469, 485), False, 'from os import path... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... | [
"numpy.random.seed",
"tensorflow.set_random_seed",
"random.seed",
"os.path.join",
"os.listdir"
] | [((2425, 2455), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (2439, 2455), True, 'import numpy as np\n'), ((2464, 2488), 'random.seed', 'random.seed', ([], {'a': 'self.seed'}), '(a=self.seed)\n', (2475, 2488), False, 'import random\n'), ((2497, 2531), 'tensorflow.set_random_... |
# -*- coding: utf-8 -*-
"""
Project: neurohacking
File: clench.py.py
Author: wffirilat
"""
import numpy as np
import time
import sys
import plugin_interface as plugintypes
from open_bci_v3 import OpenBCISample
class PluginClench(plugintypes.IPluginExtended):
def __init__(self):
self.release = True
... | [
"numpy.zeros",
"time.time"
] | [((719, 750), 'numpy.zeros', 'np.zeros', (['(8, self.storelength)'], {}), '((8, self.storelength))\n', (727, 750), True, 'import numpy as np\n'), ((771, 802), 'numpy.zeros', 'np.zeros', (['(8, self.storelength)'], {}), '((8, self.storelength))\n', (779, 802), True, 'import numpy as np\n'), ((1766, 1777), 'time.time', '... |
# -*- coding: utf-8 -*-
r"""Run the vacuum coefficients 3nu example shown in README.md.
Runs the three-neutrino example of coefficients for oscillations in
vacuum shown in README.md
References
----------
.. [1] <NAME>, "Exact neutrino oscillation probabilities:
a fast general-purpose computation method for two an... | [
"sys.path.append",
"oscprob3nu.evolution_operator_3nu",
"numpy.multiply",
"hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent",
"oscprob3nu.hamiltonian_3nu_coefficients",
"numpy.array",
"numpy.printoptions",
"oscprob3nu.evolution_operator_3nu_u_coefficients"
] | [((549, 574), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (564, 574), False, 'import sys\n'), ((769, 896), 'hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent', 'hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent', (['S12_NO_BF', 'S23_NO_BF', 'S13_NO_BF', 'DCP_NO_BF', 'D2... |
"""
Convert ground truth latent classes into binary sensitive attributes
"""
def attr_fn_0(y):
return y[:,0] >= 1
def attr_fn_1(y):
return y[:,1] >= 1
def attr_fn_2(y):
return y[:,2] >= 3
def attr_fn_3(y):
return y[:,3] >= 20
def attr_fn_4(y):
return y[:,4] >= 16
def attr_fn_5(y):
ret... | [
"numpy.zeros"
] | [((3653, 3671), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (3661, 3671), True, 'import numpy as np\n')] |
import argparse
import os
import random
import time
import warnings
from math import cos, pi
import cv2
import numpy as np
import torch
import torch.optim as optim
from DLBio.pt_train_printer import Printer
from DLBio.pytorch_helpers import get_lr
class ITrainInterface():
"""
TrainInterfaces handle the pred... | [
"numpy.random.seed",
"torch.optim.lr_scheduler.StepLR",
"argparse.ArgumentParser",
"DLBio.pytorch_helpers.get_lr",
"torch.no_grad",
"random.seed",
"math.cos",
"torch.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.is_available",
"DLBio.pt_train_printer.Printer",
"cv2.setRNGSeed",
"time.t... | [((22861, 22936), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['optimizer', 'step_size'], {'gamma': 'gamma', 'last_epoch': '(-1)'}), '(optimizer, step_size, gamma=gamma, last_epoch=-1)\n', (22886, 22936), True, 'import torch.optim as optim\n'), ((23885, 23905), 'numpy.random.seed', 'np.random.seed'... |
import pandas as pd
import numpy as np
import logging
# IF CHOPPINESS INDEX >= 61.8 - -> MARKET IS CONSOLIDATING
# IF CHOPPINESS INDEX <= 38.2 - -> MARKET IS TRENDING
# https://medium.com/codex/detecting-ranging-and-trending-markets-with-choppiness-index-in-python-1942e6450b58
class WyckoffAccumlationDistribution:
... | [
"pandas.DataFrame",
"numpy.log10",
"logging.error",
"pandas.concat"
] | [((1742, 1760), 'numpy.log10', 'np.log10', (['lookback'], {}), '(lookback)\n', (1750, 1760), True, 'import numpy as np\n'), ((1191, 1215), 'pandas.DataFrame', 'pd.DataFrame', (['(high - low)'], {}), '(high - low)\n', (1203, 1215), True, 'import pandas as pd\n'), ((3523, 3591), 'logging.error', 'logging.error', (['f"""W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.