code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#
# Copyright 2021 Budapest Quantum Computing Group
#
# 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... | [
"theboss.simulation_strategies.generalized_cliffords_simulation_strategy.GeneralizedCliffordsSimulationStrategy",
"theboss.simulation_strategies.lossy_networks_generalized_cliffords_simulation_strategy.LossyNetworksGeneralizedCliffordsSimulationStrategy",
"piquasso._math.validations.all_natural",
"numpy.ix_",... | [((2685, 2704), 'piquasso.api.result.Result', 'Result', ([], {'state': 'state'}), '(state=state)\n', (2691, 2704), False, 'from piquasso.api.result import Result\n'), ((3417, 3436), 'piquasso.api.result.Result', 'Result', ([], {'state': 'state'}), '(state=state)\n', (3423, 3436), False, 'from piquasso.api.result import... |
from numpy import log, exp, allclose, sqrt
import numpy as np
from os.path import dirname, realpath, join
from arspy.ars import adaptive_rejection_sampling
data_file = "{}/ars_{{}}.npy".format(
join(dirname(realpath(__file__)), "reference_data", "ars_data")
).format
def gaussian(x, sigma=1):
return log(ex... | [
"numpy.load",
"numpy.allclose",
"os.path.realpath",
"numpy.exp",
"arspy.ars.adaptive_rejection_sampling",
"numpy.sqrt"
] | [((1704, 1804), 'arspy.ars.adaptive_rejection_sampling', 'adaptive_rejection_sampling', ([], {'logpdf': 'logpdf', 'a': 'a', 'b': 'b', 'domain': 'domain', 'n_samples': 'n_samples', 'seed': '(1)'}), '(logpdf=logpdf, a=a, b=b, domain=domain,\n n_samples=n_samples, seed=1)\n', (1731, 1804), False, 'from arspy.ars import... |
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
from skimage import io
import matplotlib.pylab as plt
import torch
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as transforms
from model.enc_net import enc_net
from model.utils impor... | [
"data.data_loader.loader",
"data.data_loader.CamVidDataset",
"argparse.ArgumentParser",
"torch.manual_seed",
"torch.load",
"torch.nn.functional.mse_loss",
"numpy.zeros",
"torch.FloatTensor",
"pathlib.Path",
"numpy.where",
"torch.nn.functional.nll_loss",
"torch.nn.functional.log_softmax",
"sk... | [((444, 466), 'torch.manual_seed', 'torch.manual_seed', (['(555)'], {}), '(555)\n', (461, 466), False, 'import torch\n'), ((555, 592), 'pathlib.Path', 'Path', (['data_root_dir', 'label_table_name'], {}), '(data_root_dir, label_table_name)\n', (559, 592), False, 'from pathlib import Path\n'), ((628, 649), 'model.enc_net... |
# Copyright (c) <NAME>, <NAME>, and ZOZO Technologies, Inc. All rights reserved.
# Licensed under the Apache 2.0 License.
"""Useful Tools."""
from typing import Dict, Optional, Union
import numpy as np
from sklearn.utils import check_random_state
import torch
def check_confidence_interval_arguments(
alpha: floa... | [
"torch.ones_like",
"sklearn.utils.check_random_state",
"numpy.sum",
"torch.any",
"numpy.zeros",
"numpy.ones",
"numpy.percentile",
"numpy.any",
"numpy.max",
"numpy.mean",
"numpy.arange",
"numpy.exp",
"torch.allclose",
"numpy.issubdtype"
] | [((2598, 2630), 'sklearn.utils.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (2616, 2630), False, 'from sklearn.utils import check_random_state\n'), ((2644, 2674), 'numpy.arange', 'np.arange', (['n_bootstrap_samples'], {}), '(n_bootstrap_samples)\n', (2653, 2674), True, 'import ... |
import numpy as np
from streamEmbedding import StreamEmbedding
class RandomSums(StreamEmbedding):
def __init__(self, n, d):
super().__init__(n, d)
self.signs = [1.0, -1.0]
def append(self, vector):
row = np.random.randint(self.d)
sign = np.random.choice(self.signs)
#v... | [
"numpy.random.randint",
"numpy.random.choice"
] | [((240, 265), 'numpy.random.randint', 'np.random.randint', (['self.d'], {}), '(self.d)\n', (257, 265), True, 'import numpy as np\n'), ((281, 309), 'numpy.random.choice', 'np.random.choice', (['self.signs'], {}), '(self.signs)\n', (297, 309), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import src.main_2d as main
import src.systemO1 as system
import utilities as util
# System
ndim = 2
system_type = "waveO1"
xDiscretisation_type = "dG"
tIntegrators = ["dG", "Crank-Nicolson"]
meshes = ["quasiUniform", "bisectionRefined"]
def call_runF... | [
"numpy.array",
"utilities.print_config",
"src.systemO1.runFG_2d"
] | [((1278, 1300), 'utilities.print_config', 'util.print_config', (['cfg'], {}), '(cfg)\n', (1295, 1300), True, 'import utilities as util\n'), ((1328, 1374), 'src.systemO1.runFG_2d', 'system.runFG_2d', (['cfg', 'main.schemeFG_2d', 'lx', 'lt'], {}), '(cfg, main.schemeFG_2d, lx, lt)\n', (1343, 1374), True, 'import src.syste... |
import numpy as np
import pandas as pd
from time import time
import matplotlib.pyplot as plt
from quantfin.statistics import marchenko_pastur, detone, cov2corr
from quantfin.portfolio import Markowitz, BlackLitterman, HRP
# User defined parameters
ew_com = 21 * 3
# fixed parameters
file_path = r'/Users/gustavoamarant... | [
"quantfin.portfolio.HRP",
"pandas.DataFrame",
"quantfin.statistics.detone",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"quantfin.statistics.marchenko_pastur",
"quantfin.statistics.cov2corr",
"time.time",
"pandas.read_excel",
"quantfin.portfolio.Marko... | [((438, 444), 'time.time', 'time', ([], {}), '()\n', (442, 444), False, 'from time import time\n'), ((604, 699), 'pandas.read_excel', 'pd.read_excel', (["(file_path + 'Data - BBG Data Values.xlsx')"], {'index_col': '(0)', 'sheet_name': '"""Tickers"""'}), "(file_path + 'Data - BBG Data Values.xlsx', index_col=0,\n sh... |
#!/usr/bin/python3
import sys
import xml.dom.minidom as dom
from scipy.io.wavfile import read, write
import configparser
import numpy as np
import os
basstemplate = '''
<drumkit_info>
<name>{name}</name>
<author>kwt</author>
<info><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://w... | [
"scipy.io.wavfile.write",
"configparser.ConfigParser",
"numpy.array",
"scipy.io.wavfile.read"
] | [((3656, 3669), 'scipy.io.wavfile.read', 'read', (['wavfile'], {}), '(wavfile)\n', (3660, 3669), False, 'from scipy.io.wavfile import read, write\n'), ((4535, 4560), 'scipy.io.wavfile.write', 'write', (['path', 'rate', 'result'], {}), '(path, rate, result)\n', (4540, 4560), False, 'from scipy.io.wavfile import read, wr... |
#-*-coding:utf-8-*-
# date:2020-04-25
# Author: X.L.Eric
# function: inference
import os
import argparse
import torch
import torch.nn as nn
from data_iter.datasets import letterbox
import numpy as np
import time
import datetime
import os
import math
from datetime import datetime
import cv2
import torch.nn.functional... | [
"os.listdir",
"data_iter.datasets.letterbox",
"torch.from_numpy",
"argparse.ArgumentParser",
"cv2.waitKey",
"torch.load",
"cv2.imshow",
"cv2.imread",
"cv2.namedWindow",
"torch.cuda.is_available",
"torch.device",
"numpy.squeeze",
"models.resnet_50.resnet50",
"cv2.destroyAllWindows",
"torc... | [((475, 537), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""" Project Landmarks Test"""'}), "(description=' Project Landmarks Test')\n", (498, 537), False, 'import argparse\n'), ((2412, 2437), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2435, 2437), False, 'i... |
import logging
import numpy as np
import pybullet as p
from gym.envs.balance_bot.balancebot_env import BalancebotEnv
logger = logging.getLogger(__name__)
class BalancebotEnvNoise(BalancebotEnv):
def _compute_observation(self):
observation = super(BalancebotEnvNoise, self)._compute_observation()
... | [
"numpy.random.normal",
"logging.getLogger"
] | [((129, 156), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (146, 156), False, 'import logging\n'), ((571, 595), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.1)'], {}), '(0, 0.1)\n', (587, 595), True, 'import numpy as np\n'), ((434, 459), 'numpy.random.normal', 'np.random.norm... |
"""Test the DAP handler, which forms the core of the client."""
import sys
from netCDF4 import Dataset
import tempfile
import os
import numpy as np
from six.moves import zip
from pydap.handlers.netcdf import NetCDFHandler
from pydap.handlers.dap import DAPHandler
from pydap.wsgi.ssf import ServerSideFunctions
if sys... | [
"netCDF4.Dataset",
"os.remove",
"pydap.wsgi.ssf.ServerSideFunctions",
"tempfile.mkstemp",
"six.moves.zip",
"pydap.handlers.netcdf.NetCDFHandler",
"os.close",
"numpy.array",
"pydap.handlers.dap.DAPHandler"
] | [((795, 825), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': '""".nc"""'}), "(suffix='.nc')\n", (811, 825), False, 'import tempfile\n'), ((868, 884), 'os.close', 'os.close', (['fileno'], {}), '(fileno)\n', (876, 884), False, 'import os\n'), ((2066, 2091), 'os.remove', 'os.remove', (['self.test_file'], {}), '(s... |
# semantic segmentation with Unet
# heavily inspired on https://github.com/zhixuhao/unet
# uses isbi dataset
import os
import matplotlib.pyplot as plt
import skimage.io as skimage_io
import skimage.transform as skimage_transform
import random as r
import numpy as np
import datetime
import tensorflow as tf
print("Tens... | [
"matplotlib.pyplot.title",
"tensorflow.keras.layers.MaxPooling2D",
"numpy.argmax",
"random.sample",
"random.shuffle",
"tensorflow.keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.figure",
"tensorflow.keras.layers.concatenate",
"skimage.transform.rotate",
"os.path.join",
"matplotlib.pyplot.xl... | [((1352, 1399), 'os.path.join', 'os.path.join', (['datasetPath', 'trainFolder', '"""image"""'], {}), "(datasetPath, trainFolder, 'image')\n", (1364, 1399), False, 'import os\n'), ((1421, 1468), 'os.path.join', 'os.path.join', (['datasetPath', 'trainFolder', '"""label"""'], {}), "(datasetPath, trainFolder, 'label')\n", ... |
import numpy as np
from numpy.random import choice
from .abstract_sampler import AbstractSampler
from ..dataset import AbstractDataset
class WeightedRandomSampler(AbstractSampler):
"""
Implements Weighted Random Sampling
"""
def __init__(self, indices, weights=None):
"""
Parameters... | [
"numpy.array",
"numpy.unique",
"numpy.random.choice"
] | [((1824, 1878), 'numpy.random.choice', 'choice', (['self._indices'], {'size': 'n_indices', 'p': 'self._weights'}), '(self._indices, size=n_indices, p=self._weights)\n', (1830, 1878), False, 'from numpy.random import choice\n'), ((2514, 2552), 'numpy.unique', 'np.unique', (['indices'], {'return_counts': '(True)'}), '(in... |
# BSD 3-Clause License
#
# Copyright (c) 2020, <NAME>'s Research Lab
import numpy as np
from sklearn.preprocessing import KBinsDiscretizer
from data_generators.tnkde import TruncatedNormalKernelDensity
from pomegranate import *
class BayesianSampleGenerator():
def fit(self, data, discrete_features=None, bandwidth... | [
"data_generators.tnkde.TruncatedNormalKernelDensity",
"sklearn.preprocessing.KBinsDiscretizer",
"numpy.array",
"numpy.invert"
] | [((2297, 2322), 'numpy.array', 'np.array', (['data'], {'copy': '(True)'}), '(data, copy=True)\n', (2305, 2322), True, 'import numpy as np\n'), ((2410, 2502), 'sklearn.preprocessing.KBinsDiscretizer', 'KBinsDiscretizer', ([], {'n_bins': 'num_discretization_bins', 'encode': '"""ordinal"""', 'strategy': '"""quantile"""'})... |
#!/usr/bin/env python
import sys
import boto3
import os
import zipfile
import rasterio as rio
import numpy as np
temp_indicators = [
'annual_tasmin',
'annual_tasmax',
'tavg-tasmin_tasmax',
'hdd65f-tasmin_tasmax',
'cdd65f-tasmin_tasmax',
'frostfree_tasmin',
'gt-q99_tasmax'
]
pr_indicators ... | [
"rasterio.open",
"zipfile.ZipFile",
"os.makedirs",
"os.path.isfile",
"os.path.join",
"os.getenv",
"numpy.concatenate"
] | [((568, 592), 'os.getenv', 'os.getenv', (['"""GDDP_BUCKET"""'], {}), "('GDDP_BUCKET')\n", (577, 592), False, 'import os\n'), ((602, 626), 'os.getenv', 'os.getenv', (['"""GDDP_PREFIX"""'], {}), "('GDDP_PREFIX')\n", (611, 626), False, 'import os\n'), ((987, 1057), 'os.path.join', 'os.path.join', (['f"""https://s3.amazona... |
#!/usr/bin/env python
# Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ).
#
# 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... | [
"torch.nn.functional.binary_cross_entropy",
"utils.model_utils.generate_pyramid_anchors",
"utils.model_utils.apply_box_deltas_2D",
"utils.model_utils.clip_boxes_2D",
"torch.sqrt",
"torch.nn.ConvTranspose3d",
"torch.cat",
"utils.model_utils.DiceLoss",
"numpy.arange",
"torch.no_grad",
"torch.Float... | [((10172, 10201), 'torch.nonzero', 'torch.nonzero', (['(rpn_match == 1)'], {}), '(rpn_match == 1)\n', (10185, 10201), False, 'import torch\n'), ((10220, 10250), 'torch.nonzero', 'torch.nonzero', (['(rpn_match == -1)'], {}), '(rpn_match == -1)\n', (10233, 10250), False, 'import torch\n'), ((18040, 18073), 'torch.cat', '... |
"""
/***********************************
Copyright 2020 <NAME>
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... | [
"OFInterfaces.PyOF.EllipticCone",
"numpy.trace",
"OFInterfaces.PyOF.WindowProxy",
"OFInterfaces.PyOF.RectangularCone",
"math.sqrt",
"numpy.argmax",
"OFInterfaces.PyOF.FrameManager",
"OFInterfaces.PyOF.osgQuat",
"OFInterfaces.PyOF.getOsgVec3d",
"numpy.zeros",
"OFInterfaces.PyOF.osgVec3d",
"nump... | [((2584, 2639), 'OFInterfaces.PyOF.WindowProxy', 'PyOF.WindowProxy', (['(30)', '(30)', '(1280)', '(720)', '(1)', '(1)', '(False)', '(False)'], {}), '(30, 30, 1280, 720, 1, 1, False, False)\n', (2600, 2639), True, 'import OFInterfaces.PyOF as PyOF\n'), ((2688, 2715), 'OFInterfaces.PyOF.ReferenceFrame', 'PyOF.ReferenceFr... |
from __future__ import print_function
import gym
import numpy as np
import time
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class ModifiedTaxiEnv:
"""Modifications to the taxi environment:
* make it so that first episode lasts forever (essentially)
* add a NOOP so that lazines... | [
"numpy.minimum",
"numpy.sum",
"gym.make",
"numpy.zeros",
"numpy.cumsum",
"matplotlib.pyplot.figure",
"matplotlib.use",
"numpy.random.random",
"numpy.random.randint",
"numpy.mean",
"numpy.array",
"matplotlib.pyplot.savefig"
] | [((99, 120), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (113, 120), False, 'import matplotlib\n'), ((3106, 3128), 'numpy.zeros', 'np.zeros', (['env.nactions'], {}), '(env.nactions)\n', (3114, 3128), True, 'import numpy as np\n'), ((6938, 6950), 'matplotlib.pyplot.figure', 'plt.figure', ([], {... |
import os, sys, logging
import numpy as np
import pyaudio, queue, webrtcvad, collections
import deepspeech
from ctypes import CFUNCTYPE, cdll, c_char_p, c_int
import time
import threading
from karen.shared import threaded, upgradePackage
def py_error_handler(filename, line, function, err, fmt):
"""
Error hand... | [
"os.listdir",
"os.dup2",
"os.makedirs",
"deepspeech.Model",
"os.path.join",
"numpy.frombuffer",
"os.dup",
"ctypes.cdll.LoadLibrary",
"karen.shared.upgradePackage",
"time.sleep",
"webrtcvad.Vad",
"pyaudio.PyAudio",
"ctypes.CFUNCTYPE",
"os.path.expanduser",
"queue.Queue",
"logging.getLog... | [((898, 925), 'logging.getLogger', 'logging.getLogger', (['"""CTYPES"""'], {}), "('CTYPES')\n", (915, 925), False, 'import os, sys, logging\n'), ((2126, 2152), 'os.dup', 'os.dup', (['self.fd_to_silence'], {}), '(self.fd_to_silence)\n', (2132, 2152), False, 'import os, sys, logging\n'), ((2852, 2896), 'os.dup2', 'os.dup... |
"""A multi-thread tool to crop large images to sub-images for faster IO."""
import os
import os.path as osp
import numpy as np
import cv2
from PIL import Image
import data.util as data_util # noqa: E402
import torch.utils.data as data
from tqdm import tqdm
import torch
def main():
split_img = False
opt = {}
... | [
"tqdm.tqdm",
"os.makedirs",
"torch.utils.data.DataLoader",
"os.path.basename",
"numpy.ascontiguousarray",
"os.path.exists",
"cv2.imread",
"numpy.append",
"numpy.arange",
"data.util._get_paths_from_images",
"cv2.imencode",
"os.path.join",
"cv2.resize"
] | [((10272, 10346), 'torch.utils.data.DataLoader', 'data.DataLoader', (['dataset'], {'num_workers': "opt['n_thread']", 'collate_fn': 'identity'}), "(dataset, num_workers=opt['n_thread'], collate_fn=identity)\n", (10287, 10346), True, 'import torch.utils.data as data\n'), ((10356, 10372), 'tqdm.tqdm', 'tqdm', (['dataloade... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 13:43:27 2019
@author: asier.erramuzpe
"""
### RINGING DETECTION MODULE
# file1 = OK, file2 = RINGING, file2 = SLIGHT RINGING, file3 = SLIGHT FRONTAL MOVE
file1 = '/ems/elsc-labs/mezer-a/Mezer-Lab/analysis/reading_stanford/s008/mrQ_ver2/OutPutFi... | [
"numpy.sum",
"numpy.abs",
"dotenv.find_dotenv",
"scipy.fftpack.fftshift",
"numpy.argsort",
"matplotlib.colors.LogNorm",
"pylab.figure",
"os.path.join",
"os.path.exists",
"numpy.cumsum",
"numpy.log10",
"dotenv.load_dotenv",
"numpy.indices",
"numpy.hypot",
"scipy.fftpack.fft2",
"os.listd... | [((5738, 5751), 'dotenv.find_dotenv', 'find_dotenv', ([], {}), '()\n', (5749, 5751), False, 'from dotenv import find_dotenv, load_dotenv\n'), ((5752, 5776), 'dotenv.load_dotenv', 'load_dotenv', (['dotenv_path'], {}), '(dotenv_path)\n', (5763, 5776), False, 'from dotenv import find_dotenv, load_dotenv\n'), ((5798, 5834)... |
import numpy as np
import torch
from torch import nn
# =============================================== L1 NORM =====================================================
def l1_norm_error(source, candidate):
error = np.abs(source - candidate)
source[source == 0] = 1e-30 # add for numerical stability
error = ... | [
"numpy.abs",
"torch.clamp",
"numpy.linspace",
"numpy.log10",
"numpy.sqrt",
"torch.from_numpy"
] | [((218, 244), 'numpy.abs', 'np.abs', (['(source - candidate)'], {}), '(source - candidate)\n', (224, 244), True, 'import numpy as np\n'), ((591, 631), 'numpy.log10', 'np.log10', (['((source + 1) / (candidate + 1))'], {}), '((source + 1) / (candidate + 1))\n', (599, 631), True, 'import numpy as np\n'), ((695, 709), 'num... |
from igraph import *
import argparse
import numpy as np
import matplotlib.pyplot as plt
from statistics import mean
BINS = 1
# Prints degree distribution properties
def print_degree_dist_props(histogram):
print("Results:")
print("Mean:", round(histogram.mean, 2))
print("Variance:", round(histogram.var, 2... | [
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.delete"
] | [((672, 714), 'matplotlib.pyplot.plot', 'plt.plot', (['x', '(alpha * x ** -lambda_val)', '"""-"""'], {}), "(x, alpha * x ** -lambda_val, '-')\n", (680, 714), True, 'import matplotlib.pyplot as plt\n'), ((901, 913), 'numpy.array', 'np.array', (['xs'], {}), '(xs)\n', (909, 913), True, 'import numpy as np\n'), ((923, 935)... |
import sys
import time
import numpy as np
import tensorflow as tf
import cv2
class FROZEN_GRAPH_INFERENCE:
def __init__(self, frozen_model):
"""Tensorflow detector
"""
self.inference_list = list()
self.PATH_TO_CKPT = frozen_model
self.count = 0
self.detection_g... | [
"cv2.cvtColor",
"tensorflow.Session",
"numpy.expand_dims",
"time.time",
"tensorflow.ConfigProto",
"tensorflow.gfile.GFile",
"tensorflow.Graph",
"cv2.rectangle",
"numpy.squeeze",
"tensorflow.import_graph_def",
"tensorflow.GraphDef"
] | [((327, 337), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (335, 337), True, 'import tensorflow as tf\n'), ((1016, 1033), 'numpy.squeeze', 'np.squeeze', (['boxes'], {}), '(boxes)\n', (1026, 1033), True, 'import numpy as np\n'), ((1051, 1069), 'numpy.squeeze', 'np.squeeze', (['scores'], {}), '(scores)\n', (1061, 10... |
"""
align_funcs.py
The alignment algorithm takes in TextGrid classes and extracts meaningful
data. This information consists of the beginning of a phoneme's utterance,
its end, and its phonemic transcription. With this information the program
finds the edit distance between two given utterances, ph... | [
"phonemes.VOWELS.values",
"phonemes.CONSONANTS.values",
"numpy.argmin"
] | [((768, 783), 'phonemes.VOWELS.values', 'VOWELS.values', ([], {}), '()\n', (781, 783), False, 'from phonemes import VOWELS, CONSONANTS\n'), ((936, 955), 'phonemes.CONSONANTS.values', 'CONSONANTS.values', ([], {}), '()\n', (953, 955), False, 'from phonemes import VOWELS, CONSONANTS\n'), ((2146, 2162), 'numpy.argmin', 'n... |
from typing import Any, Hashable, Mapping, Tuple
import numpy as np
import xarray as xr
def histogram(da: xr.DataArray, **kwargs) -> Tuple[xr.DataArray, xr.DataArray]:
"""Compute histogram and return tuple of counts and bin widths.
Args:
da: input data
kwargs: optional parameters to pass on ... | [
"numpy.histogram",
"xarray.DataArray"
] | [((583, 609), 'numpy.histogram', 'np.histogram', (['da'], {}), '(da, **kwargs)\n', (595, 609), True, 'import numpy as np\n'), ((719, 772), 'xarray.DataArray', 'xr.DataArray', (['width'], {'coords': 'coords', 'dims': '[coord_name]'}), '(width, coords=coords, dims=[coord_name])\n', (731, 772), True, 'import xarray as xr\... |
"""
"Cholesky Factor Algorithm" (CFA) simulation smoothing for state space models
Author: <NAME>
License: BSD-3
"""
import numpy as np
from . import tools
class CFASimulationSmoother(object):
r"""
"Cholesky Factor Algorithm" (CFA) simulation smoother
Parameters
----------
model : Representatio... | [
"numpy.eye",
"numpy.array",
"numpy.ravel"
] | [((4493, 4554), 'numpy.array', 'np.array', (['self._simulation_smoother.posterior_mean'], {'copy': '(True)'}), '(self._simulation_smoother.posterior_mean, copy=True)\n', (4501, 4554), True, 'import numpy as np\n'), ((5369, 5438), 'numpy.array', 'np.array', (['self._simulation_smoother.posterior_cov_inv_chol'], {'copy':... |
import os
import cv2
import numpy as np
from feat.utils import get_resource_path
from feat.facepose_detectors.utils import convert_to_euler
THREED_FACE_MODEL = os.path.join(get_resource_path(), "reference_3d_68_points_trans.npy")
class PerspectiveNPointModel:
""" Class that leverages 68 2D facial landmar... | [
"numpy.load",
"cv2.solvePnP",
"numpy.zeros",
"numpy.array",
"numpy.squeeze",
"feat.utils.get_resource_path"
] | [((178, 197), 'feat.utils.get_resource_path', 'get_resource_path', ([], {}), '()\n', (195, 197), False, 'from feat.utils import get_resource_path\n'), ((1045, 1090), 'numpy.load', 'np.load', (['THREED_FACE_MODEL'], {'allow_pickle': '(True)'}), '(THREED_FACE_MODEL, allow_pickle=True)\n', (1052, 1090), True, 'import nump... |
"""
Implementation of sequential minimal optimization (SMO) for support vector machines
(SVM).
Sequential minimal optimization (SMO) is an algorithm for solving the quadratic
programming (QP) problem that arises during the training of support vector
machines.
It was invented by <NAME> in 1998.
... | [
"sklearn.datasets.make_circles",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"pandas.read_csv",
"matplotlib.pyplot.subplot2grid",
"numpy.zeros",
"sklearn.datasets.make_blobs",
"os.path.exists",
"time.time",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.linalg.norm",
... | [((15240, 15283), 'pandas.read_csv', 'pd.read_csv', (['"""cancel_data.csv"""'], {'header': 'None'}), "('cancel_data.csv', header=None)\n", (15251, 15283), True, 'import pandas as pd\n'), ((15827, 15856), 'numpy.zeros', 'np.zeros', (['train_data.shape[0]'], {}), '(train_data.shape[0])\n', (15835, 15856), True, 'import n... |
import os
import re
from urllib.parse import unquote
import numpy as np
from REL.db.generic import GenericLookup
from REL.utils import first_letter_to_uppercase, trim1, unicode2ascii
"""
Class responsible for processing Wikipedia dumps. Performs computations to obtain the p(e|m) index and counts
overall occurrence... | [
"urllib.parse.unquote",
"REL.utils.unicode2ascii",
"numpy.sum",
"re.finditer"
] | [((11430, 11443), 'urllib.parse.unquote', 'unquote', (['line'], {}), '(line)\n', (11437, 11443), False, 'from urllib.parse import unquote\n'), ((1830, 1874), 'numpy.sum', 'np.sum', (['[v for k, v in ent_wiki_names][:100]'], {}), '([v for k, v in ent_wiki_names][:100])\n', (1836, 1874), True, 'import numpy as np\n'), ((... |
import gym
import logging
import numpy as np
import tensorflow as tf
from src.naf import NAF
from src.network import Network
from src.statistic import Statistic
from src.exploration import OUExploration, BrownianExploration, LinearDecayExploration
# from naf import NAF
# from network import Network
# from statistic ... | [
"numpy.random.seed",
"gym.make",
"src.exploration.OUExploration",
"src.exploration.BrownianExploration",
"utils.preprocess_conf",
"tensorflow.Session",
"src.network.Network",
"src.naf.NAF",
"tensorflow.set_random_seed",
"src.exploration.LinearDecayExploration",
"utils.get_model_dir",
"src.stat... | [((2618, 2637), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (2635, 2637), False, 'import logging\n'), ((2714, 2750), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['conf.random_seed'], {}), '(conf.random_seed)\n', (2732, 2750), True, 'import tensorflow as tf\n'), ((2751, 2783), 'numpy.random.seed... |
"""Base Class of an Adversarial Environments."""
from abc import ABCMeta, abstractmethod
import numpy as np
from gym import Wrapper
from gym.spaces import Box
class AdversarialWrapper(Wrapper, metaclass=ABCMeta):
r"""An adversarial environment wrapper.
This is an abstract wrapper that wraps a gym Env.
... | [
"numpy.concatenate"
] | [((1675, 1749), 'numpy.concatenate', 'np.concatenate', (['(self.env.unwrapped.action_space.low, self.antagonist_low)'], {}), '((self.env.unwrapped.action_space.low, self.antagonist_low))\n', (1689, 1749), True, 'import numpy as np\n'), ((1810, 1886), 'numpy.concatenate', 'np.concatenate', (['(self.env.unwrapped.action_... |
#!/usr/bin/env python
import math
import numpy as np
import pandas as pd
import random
import string
from scipy.stats import zipf
from itertools import chain
import json
class contentCatalogue():
def __init__(self, size=1000):
'''
Assigns the size and constructs an empty list of contents. Construc... | [
"pandas.DataFrame",
"json.dump",
"json.load",
"numpy.tril",
"random.sample",
"pandas.read_csv",
"numpy.random.rand",
"numpy.zeros",
"random.choice",
"numpy.array",
"numpy.arange",
"numpy.argwhere",
"itertools.chain.from_iterable"
] | [((8400, 8457), 'pandas.DataFrame', 'pd.DataFrame', (['r.contentMatrix'], {'index': 'names', 'columns': 'names'}), '(r.contentMatrix, index=names, columns=names)\n', (8412, 8457), True, 'import pandas as pd\n'), ((1784, 1806), 'random.sample', 'random.sample', (['list', 'N'], {}), '(list, N)\n', (1797, 1806), False, 'i... |
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
img=Image.open("flower.jpeg")
# img =img.rotate(-90)
img=np.asarray(img)
plt.imshow(img)
print(type(img))
plt.show()
| [
"matplotlib.pyplot.imshow",
"numpy.asarray",
"matplotlib.pyplot.show",
"PIL.Image.open"
] | [((78, 103), 'PIL.Image.open', 'Image.open', (['"""flower.jpeg"""'], {}), "('flower.jpeg')\n", (88, 103), False, 'from PIL import Image\n'), ((132, 147), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (142, 147), True, 'import numpy as np\n'), ((148, 163), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {... |
import os
import json
import numpy as np
import pandas as pd
from keras.applications import inception_resnet_v2
from keras.preprocessing import image
img_width, img_height = 331, 331
import fnmatch
from shutil import copyfile
import PIL
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True # read b... | [
"PIL.Image.new",
"numpy.empty",
"os.walk",
"numpy.argsort",
"keras.preprocessing.image.img_to_array",
"os.path.join",
"os.chdir",
"pandas.DataFrame",
"keras.applications.inception_resnet_v2.InceptionResNetV2",
"os.path.dirname",
"os.path.exists",
"keras.preprocessing.image.load_img",
"numpy.... | [((1112, 1134), 'os.chdir', 'os.chdir', (['default_path'], {}), '(default_path)\n', (1120, 1134), False, 'import os\n'), ((1349, 1487), 'keras.applications.inception_resnet_v2.InceptionResNetV2', 'inception_resnet_v2.InceptionResNetV2', ([], {'include_top': '(True)', 'weights': '"""imagenet"""', 'input_tensor': 'None',... |
from typing import Union
import warnings
import numpy as np
from copy import copy
from scipy import ndimage as ndi
from xml.etree.ElementTree import Element
from base64 import b64encode
from imageio import imwrite
from ..base import Layer
from ...util.colormaps import colormaps
from ...util.event import Event
from ...... | [
"numpy.divide",
"warnings.simplefilter",
"numpy.logical_and",
"numpy.asarray",
"xml.etree.ElementTree.Element",
"numpy.zeros",
"copy.copy",
"scipy.ndimage.zoom",
"numpy.clip",
"numpy.max",
"scipy.ndimage.label",
"warnings.catch_warnings",
"numpy.array",
"base64.b64encode",
"numpy.random.... | [((4804, 4839), 'numpy.zeros', 'np.zeros', (['((1,) * self.dims.ndisplay)'], {}), '((1,) * self.dims.ndisplay)\n', (4812, 4839), True, 'import numpy as np\n'), ((4866, 4901), 'numpy.zeros', 'np.zeros', (['((1,) * self.dims.ndisplay)'], {}), '((1,) * self.dims.ndisplay)\n', (4874, 4901), True, 'import numpy as np\n'), (... |
from __future__ import division
import math
import numpy as np
import random
def random_sized_crop(img,
scale_ratio_range=(0.08, 1),
aspect_ratio_range=(3 / 4, 4 / 3),
return_param=False, copy=False):
"""Crop an image to random size and aspect rat... | [
"numpy.sqrt",
"random.randint",
"random.uniform"
] | [((3519, 3548), 'random.randint', 'random.randint', (['(0)', '(H - H_crop)'], {}), '(0, H - H_crop)\n', (3533, 3548), False, 'import random\n'), ((3563, 3592), 'random.randint', 'random.randint', (['(0)', '(W - W_crop)'], {}), '(0, W - W_crop)\n', (3577, 3592), False, 'import random\n'), ((4107, 4167), 'random.uniform'... |
"""
This file should contain only functions that operates on pixels, not on images,
so no references to PIL are necessary and the module can be used also through
Jython
"""
import numpy
import sys
import time
from worldengine.common import get_verbose, count_neighbours
from worldengine.common import anti_alias as anti... | [
"worldengine.common.anti_alias",
"numpy.logical_not",
"numpy.zeros",
"worldengine.biome._un_camelize",
"numpy.random.RandomState",
"time.time",
"worldengine.common.count_neighbours",
"sys.stdout.flush",
"numpy.random.randint",
"worldengine.biome.BiomeGroup.__subclasses__",
"worldengine.common.ge... | [((1749, 1796), 'numpy.zeros', 'numpy.zeros', (['(world.height, world.width)', 'float'], {}), '((world.height, world.width), float)\n', (1760, 1796), False, 'import numpy\n'), ((2330, 2357), 'worldengine.biome.BiomeGroup.__subclasses__', 'BiomeGroup.__subclasses__', ([], {}), '()\n', (2355, 2357), False, 'from worldeng... |
import pygame
import numpy as np
# Drawing the sudoku grid
def draw_the_grid():
for row in range(9):
for column in range(9):
color = BLACK
for numbers in range(1,10):
if grid[row][column] == numbers:
number[row][column] = myfont.render(s... | [
"pygame.quit",
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"pygame.init",
"pygame.display.flip",
"pygame.font.init",
"pygame.mouse.get_pos",
"pygame.display.set_caption",
"numpy.delete"
] | [((11049, 11062), 'pygame.init', 'pygame.init', ([], {}), '()\n', (11060, 11062), False, 'import pygame\n'), ((11092, 11110), 'pygame.font.init', 'pygame.font.init', ([], {}), '()\n', (11108, 11110), False, 'import pygame\n'), ((11121, 11153), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""Arial"""', '(30)'], {}),... |
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from solo12_shoulder_collision_utils import followBoundary, colMapToDistField
# Load the collision map from file
res = 200
col_map_file = './npy_data/collision_map_centered_res{}.npy'.format(res)
dist_field_file = './npy_data/updated_collisio... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"numpy.load",
"numpy.fft.ifftshift",
"matplotlib.pyplot.show",
"numpy.count_nonzero",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.imshow",
"numpy.asarray",
"numpy.fft.ifft2",
"numpy.zeros",
"matplotlib.pyplo... | [((368, 408), 'numpy.load', 'np.load', (['col_map_file'], {'allow_pickle': '(True)'}), '(col_map_file, allow_pickle=True)\n', (375, 408), True, 'import numpy as np\n'), ((442, 485), 'numpy.load', 'np.load', (['dist_field_file'], {'allow_pickle': '(True)'}), '(dist_field_file, allow_pickle=True)\n', (449, 485), True, 'i... |
"""Sorting components: template matching."""
import numpy as np
import scipy.spatial
from tqdm import tqdm
import sklearn, scipy
import scipy
from threadpoolctl import threadpool_limits
try:
import numba
from numba import jit, prange
HAVE_NUMBA = True
except ImportError:
HAVE_NUMBA = False
from s... | [
"spikeinterface.toolkit.get_channel_distances",
"numpy.sum",
"numpy.abs",
"scipy.linalg.solve_triangular",
"numpy.empty",
"numpy.argmin",
"numpy.argsort",
"numpy.arange",
"numpy.linalg.norm",
"numba.prange",
"scipy.signal.fftconvolve",
"numpy.unique",
"spikeinterface.sortingcomponents.peak_d... | [((891, 950), 'scipy.linalg.get_lapack_funcs', 'scipy.linalg.get_lapack_funcs', (["('potrs',)"], {'dtype': 'np.float32'}), "(('potrs',), dtype=np.float32)\n", (920, 950), False, 'import scipy\n'), ((960, 1016), 'scipy.linalg.get_blas_funcs', 'scipy.linalg.get_blas_funcs', (["('nrm2',)"], {'dtype': 'np.float32'}), "(('n... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... | [
"numpy.asarray",
"numpy.iinfo"
] | [((3122, 3140), 'numpy.iinfo', 'np.iinfo', (['ddt.type'], {}), '(ddt.type)\n', (3130, 3140), True, 'import numpy as np\n'), ((3505, 3544), 'numpy.asarray', 'np.asarray', (['valid_range'], {'dtype': 'np.float'}), '(valid_range, dtype=np.float)\n', (3515, 3544), True, 'import numpy as np\n'), ((3593, 3616), 'numpy.asarra... |
"""
<NAME>
This file contains util functions
"""
import networkx as nx
import ujson as json
import numpy as np
import torch
import os
import queue
import shutil
import logging
import tqdm
from sklearn.metrics import roc_curve,auc
import torch.utils.data as data
from torch_geometric.data import Data,Batch
from sklearn.... | [
"networkx.from_scipy_sparse_matrix",
"numpy.load",
"os.remove",
"ujson.dump",
"sklearn.model_selection.train_test_split",
"numpy.ones",
"torch.cat",
"torch.cuda.device_count",
"logging.Formatter",
"torch_geometric.data.Data",
"torch.device",
"os.path.join",
"shutil.copy",
"logging.FileHand... | [((672, 710), 'networkx.relabel_nodes', 'nx.relabel_nodes', (['G', 'ordered_node_dict'], {}), '(G, ordered_node_dict)\n', (688, 710), True, 'import networkx as nx\n'), ((2106, 2146), 'numpy.load', 'np.load', (['ad_data_path'], {'allow_pickle': '(True)'}), '(ad_data_path, allow_pickle=True)\n', (2113, 2146), True, 'impo... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import FactorAnalysis, PCA
import tensorly as tl
from tensorly import unfold as tl_unfold
from tensorly.decomposition import parafac,non_negative_parafac
from sklearn.preprocessing import scale
from sklearn.preprocessing... | [
"align_maze.align_maze",
"tensorflow.keras.losses.MeanSquaredError",
"data_generator.DataGenerator",
"numpy.isnan",
"models.create_lstm_ae",
"models.create_lstm_vae",
"models.create_binned_lstm_vae"
] | [((1621, 1722), 'models.create_lstm_ae', 'create_lstm_ae', ([], {'input_dim': 'n_neuron', 'timesteps': 'n_bin', 'latent_dim': 'latent_dim', 'latent_fac': 'latent_fac'}), '(input_dim=n_neuron, timesteps=n_bin, latent_dim=latent_dim,\n latent_fac=latent_fac)\n', (1635, 1722), False, 'from models import create_lstm_ae,... |
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
import matplotlib.pyplot as plt
import numpy as np
import sys
def basins_1d():
f = lambda x:x**2-1
Df = lambda x:2*x
x0 = np.linspace(-1.5, 1.5, 40)
xold=x0
n = 0
while n <= 6:
xnew = xold... | [
"numpy.meshgrid",
"numpy.zeros_like",
"numpy.abs",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.pcolormesh",
"matplotlib.rc_params_from_file",
"matplotlib.pyplot.savefig",
"numpy.atleast_2d"
] | [((40, 92), 'matplotlib.rc_params_from_file', 'matplotlib.rc_params_from_file', (['"""../../matplotlibrc"""'], {}), "('../../matplotlibrc')\n", (70, 92), False, 'import matplotlib\n'), ((229, 255), 'numpy.linspace', 'np.linspace', (['(-1.5)', '(1.5)', '(40)'], {}), '(-1.5, 1.5, 40)\n', (240, 255), True, 'import numpy a... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2019 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
import pandapower as pp
import pytest
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option... | [
"pandapower.create_transformer_from_parameters",
"pandapower.create_ext_grid",
"pandapower.load_std_type",
"pandapower.create_line",
"pandapower.create_bus",
"numpy.isclose",
"pandas.set_option",
"pandapower.create_lines",
"pandapower.create_series_reactor_as_impedance",
"pandapower.create_empty_n... | [((268, 306), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(500)'], {}), "('display.max_rows', 500)\n", (281, 306), True, 'import pandas as pd\n'), ((307, 348), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(500)'], {}), "('display.max_columns', 500)\n", (320, 348), True, '... |
import numpy as np
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
from sklearn import preprocessing
import os
import sys
def get_query_weight(datafile, weightfile):
# read data file
#features, labels, num_feat, num_labels = read_data(datafile, header=True)
features = read_data(datafi... | [
"numpy.load",
"numpy.transpose",
"sklearn.datasets.load_svmlight_file",
"numpy.matmul"
] | [((1450, 1467), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (1457, 1467), True, 'import numpy as np\n'), ((1557, 1573), 'numpy.transpose', 'np.transpose', (['w1'], {}), '(w1)\n', (1569, 1573), True, 'import numpy as np\n'), ((428, 451), 'numpy.matmul', 'np.matmul', (['features', 'w0'], {}), '(features,... |
import numpy
from fqe.fci_graph import Spinmap, FciGraph
from fqe.fqe_data import FqeData
from fqe.fqe_data_set import FqeDataSet
from fqe.wavefunction import Wavefunction
def compare_Spinmap(A: Spinmap, B: Spinmap) -> bool:
"""Compares two Spinmaps
Args:
A: First spinmap
B: Second spinmap
... | [
"numpy.array_equal",
"numpy.allclose"
] | [((940, 985), 'numpy.array_equal', 'numpy.array_equal', (['graph1._astr', 'graph2._astr'], {}), '(graph1._astr, graph2._astr)\n', (957, 985), False, 'import numpy\n'), ((997, 1042), 'numpy.array_equal', 'numpy.array_equal', (['graph1._bstr', 'graph2._bstr'], {}), '(graph1._bstr, graph2._bstr)\n', (1014, 1042), False, '... |
import numpy as np
import tensorflow as tf
from keras import keras_parameterized, layers
from keras.utils.generic_utils import register_keras_serializable
from tfswin.winatt import WindowAttention
from testing_utils import layer_multi_io_test
@register_keras_serializable('TFSwin')
class WindowAttentionSqueeze(WindowA... | [
"tensorflow.test.main",
"numpy.random.random",
"numpy.array",
"tensorflow.squeeze",
"keras.utils.generic_utils.register_keras_serializable",
"keras.layers.InputSpec"
] | [((246, 283), 'keras.utils.generic_utils.register_keras_serializable', 'register_keras_serializable', (['"""TFSwin"""'], {}), "('TFSwin')\n", (273, 283), False, 'from keras.utils.generic_utils import register_keras_serializable\n'), ((1984, 1998), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (1996, 1998), ... |
#! /usr/bin/env python3
#
# In this script we solve the Laplace problem on a unit square that has the
# bottom-right quadrant removed (a.k.a. an L-shaped domain) with Dirichlet
# boundary conditions matching the harmonic function
#
# .. math:: \sqrt[3]{x^2 + y^2} \cos\left(\tfrac23 \arctan\frac{y+x}{y-x}\right),
#
# sh... | [
"nutils.numeric.assert_allclose64",
"nutils.log.count",
"numpy.log",
"nutils.cli.run",
"numpy.testing.assert_almost_equal",
"nutils.function.arctan2",
"nutils.mesh.unitsquare",
"nutils.export.triplot",
"numpy.mean",
"nutils.solver.solve_linear",
"nutils.function.Namespace",
"nutils.solver.opti... | [((1317, 1349), 'nutils.mesh.unitsquare', 'nutils.mesh.unitsquare', (['(2)', 'etype'], {}), '(2, etype)\n', (1339, 1349), False, 'import nutils, numpy\n'), ((1526, 1556), 'nutils.util.linear_regressor', 'nutils.util.linear_regressor', ([], {}), '()\n', (1554, 1556), False, 'import nutils, numpy\n'), ((1575, 1600), 'nut... |
"""NTM Read/Write Head."""
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
def _split_cols(mat, lengths):
"""Split a 2D matrix to variable length columns."""
assert mat.size()[1] == sum(lengths), "Lengths must be summed to num columns"
... | [
"torch.nn.init.xavier_uniform",
"numpy.cumsum",
"torch.nn.init.normal",
"torch.nn.functional.sigmoid",
"torch.nn.functional.relu",
"torch.zeros"
] | [((327, 351), 'numpy.cumsum', 'np.cumsum', (['([0] + lengths)'], {}), '([0] + lengths)\n', (336, 351), True, 'import numpy as np\n'), ((1231, 1240), 'torch.nn.functional.relu', 'F.relu', (['k'], {}), '(k)\n', (1237, 1240), True, 'import torch.nn.functional as F\n'), ((1254, 1263), 'torch.nn.functional.relu', 'F.relu', ... |
import pandas as pd
import numpy as np
from impliedVolatility.ImpliedVolatility import ImpliedVolatility
modes = ['impvol', 'histvol']
for mode in modes:
if mode == 'impvol':
test_df = pd.read_csv('data-source/test_df.csv')
else:
test_df = pd.read_csv('data-source/test_df_histvol.csv')
# ... | [
"pandas.DataFrame",
"numpy.abs",
"numpy.log",
"pandas.read_csv",
"numpy.median",
"numpy.std",
"numpy.square",
"numpy.power",
"numpy.max",
"numpy.mean",
"numpy.min"
] | [((803, 826), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data'}), '(data=data)\n', (815, 826), True, 'import pandas as pd\n'), ((199, 237), 'pandas.read_csv', 'pd.read_csv', (['"""data-source/test_df.csv"""'], {}), "('data-source/test_df.csv')\n", (210, 237), True, 'import pandas as pd\n'), ((266, 312), 'pandas... |
from configuration import config
from qm.qua import *
from qm.QuantumMachinesManager import QuantumMachinesManager
import numpy as np
from scipy.optimize import minimize
Navg = 40000
thresh = 0.001 # threshold on the Q value to determine the state e/g
res_time = 10000
def reset_qubit():
qv = declare... | [
"numpy.norm",
"numpy.array",
"qm.QuantumMachinesManager.QuantumMachinesManager"
] | [((3928, 3952), 'qm.QuantumMachinesManager.QuantumMachinesManager', 'QuantumMachinesManager', ([], {}), '()\n', (3950, 3952), False, 'from qm.QuantumMachinesManager import QuantumMachinesManager\n'), ((4294, 4333), 'numpy.array', 'np.array', (['([-1] * 5 + [0] * 12 + [1] * 4)'], {}), '([-1] * 5 + [0] * 12 + [1] * 4)\n'... |
# 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.
# pyre-unsafe
import logging
import time
from multiprocessing import cpu_count
from multiprocessing.dummy import Pool
from typing import List, ... | [
"pandas.DataFrame",
"numpy.full",
"logging.error",
"numpy.random.seed",
"pandas.date_range",
"kats.models.globalmodel.utils.gmpreprocess",
"kats.models.globalmodel.model.GMModel",
"multiprocessing.dummy.Pool",
"torch.manual_seed",
"kats.models.globalmodel.utils.split",
"kats.models.globalmodel.m... | [((4088, 4099), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (4097, 4099), False, 'from multiprocessing import cpu_count\n'), ((6406, 6417), 'time.time', 'time.time', ([], {}), '()\n', (6415, 6417), False, 'import time\n'), ((8295, 8349), 'kats.models.globalmodel.utils.split', 'split', (['self.splits', '... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"numpy.result_type",
"numpy.dtype",
"numpy.ndim",
"numpy.finfo",
"numpy.array",
"functools.reduce",
"os.getenv",
"numpy.issubdtype"
] | [((1328, 1347), 'numpy.dtype', 'onp.dtype', (['bfloat16'], {}), '(bfloat16)\n', (1337, 1347), True, 'import numpy as onp\n'), ((1938, 1956), 'numpy.dtype', 'onp.dtype', (['"""int64"""'], {}), "('int64')\n", (1947, 1956), True, 'import numpy as onp\n'), ((1982, 2001), 'numpy.dtype', 'onp.dtype', (['"""uint64"""'], {}), ... |
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
from collections import defaultdict
from io import StringIO
from PIL import Image
from pathlib import Path
cap = cv2.VideoCapture('/Users/tomaspiaggio/Desktop/test-ppl-counting/v3... | [
"pathlib.Path",
"tensorflow.get_default_graph",
"tensorflow.greater",
"os.path.join",
"sys.path.append",
"utils.label_map_util.convert_label_map_to_categories",
"tensorflow.cast",
"six.moves.urllib.request.URLopener",
"tensorflow.squeeze",
"tarfile.open",
"tensorflow.GraphDef",
"os.path.basena... | [((254, 326), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""/Users/tomaspiaggio/Desktop/test-ppl-counting/v3.mp4"""'], {}), "('/Users/tomaspiaggio/Desktop/test-ppl-counting/v3.mp4')\n", (270, 326), False, 'import cv2\n'), ((406, 427), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (421, 427), Fal... |
"""ML-Ensemble
:author: <NAME>
:copyright: 2017-2018
:license: MIT
Base classes for parallel estimation
Schedulers for global setups:
0:
Base setups - independent of other features:
IndexMixin._setup_0_index
1:
Global setups - reserved for aggregating classes:
Layer._setup_1_glo... | [
"numpy.unique"
] | [((4843, 4859), 'numpy.unique', 'np.unique', (['sizes'], {}), '(sizes)\n', (4852, 4859), True, 'import numpy as np\n'), ((6154, 6166), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (6163, 6166), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""Async Bayesian optimization classes"""
import sys
import time
from typing import Optional, Callable
import numpy as np
import pandas as pd
from bayesopt.acquisition import AcquisitionWithOffset
from bayesopt.util import add_hallucinations_to_x_and_y, stable_cholesky
from ml_utils import tim... | [
"pandas.DataFrame",
"bayesopt.util.stable_cholesky",
"numpy.copy",
"numpy.argmax",
"numpy.random.rand",
"bayesopt.acquisition.AcquisitionWithOffset",
"ml_utils.lipschitz.estimate_lipschitz_constant",
"numpy.argmin",
"time.time",
"numpy.hstack",
"numpy.array",
"sys.stdout.flush",
"ml_utils.ti... | [((3020, 3347), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['ii', 't', 'y_min', 'x_min', 'n_busy', 'x_busy', 'n_data', 'model_x',\n 'model_y', 'model_param_array', 'acq_at_sample', 'requested_x_sample',\n 'x_sample', 'y_sample', 'time_taken_opt_surrogate',\n 'time_taken_find_y_min', 'time_taken_get_... |
# -*- coding: utf-8 -*-
import numpy as np
import scipy.signal
__all__ = ["find_rayleigh_damping_coeffs",
"get_frequency_vector", "modal_assurance_criterion",
"find_psd_matrix", "w2f", "f2w", "norm2", "modal_scale_factor",
"mean_phase", "mean_phase_deviation", "Mode",
]
d... | [
"numpy.linalg.eigvals",
"numpy.abs",
"numpy.sum",
"numpy.imag",
"numpy.sin",
"numpy.linalg.norm",
"numpy.conjugate",
"numpy.linalg.solve",
"numpy.zeros_like",
"numpy.linalg.eig",
"numpy.linspace",
"numpy.real",
"numpy.cov",
"numpy.arctan",
"numpy.linalg.lstsq",
"numpy.log",
"numpy.ze... | [((2816, 2838), 'numpy.cov', 'np.cov', (['u.real', 'u.imag'], {}), '(u.real, u.imag)\n', (2822, 2838), True, 'import numpy as np\n'), ((2847, 2867), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['S'], {}), '(S)\n', (2864, 2867), True, 'import numpy as np\n'), ((3536, 3565), 'numpy.arctan', 'np.arctan', (['(-V[0, 1] / ... |
import os
import matplotlib.pyplot as plt
import numpy as np
import datetime
#Very Hard Coded script to produce statistics on Logs received from nodes at the cluster.
#Just place the logs in the logs folder. The folder should contain 2 directories
#both have logs from the same protocols stack, but in each directory 2 v... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.bar",
"os.walk",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"datetime.datetime.now",
"os.listdir",
"matplotlib.pyplot.savefig"
] | [((920, 936), 'os.walk', 'os.walk', (['rootdir'], {}), '(rootdir)\n', (927, 936), False, 'import os\n'), ((4643, 4660), 'numpy.arange', 'np.arange', (['nfiles'], {}), '(nfiles)\n', (4652, 4660), True, 'import numpy as np\n'), ((5042, 5054), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5052, 5054), True,... |
#!/usr/bin/env python
# coding: utf-8
# # ResCenterNet Trial
#
# I am very new to these concepts so I am trying out by changing this amazing and probably only 3D model related awesome public kernel by Ruslan
# https://www.kaggle.com/hocop1/centernet-baseline
#
# Most of the codes are loaned from there . There are o... | [
"albumentations.GaussNoise",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"torch.cat",
"gc.collect",
"torch.nn.GroupNorm",
"torch.nn.init.constant_",
"numpy.tile",
"numpy.exp",
"torch.no_grad",
"albumentations.RGBShift",
"numpy.round",
"albumentations.MotionBlur",
"albume... | [((1570, 1601), 'pandas.read_csv', 'pd.read_csv', (["(PATH + 'train.csv')"], {}), "(PATH + 'train.csv')\n", (1581, 1601), True, 'import pandas as pd\n'), ((1609, 1652), 'pandas.read_csv', 'pd.read_csv', (["(PATH + 'sample_submission.csv')"], {}), "(PATH + 'sample_submission.csv')\n", (1620, 1652), True, 'import pandas ... |
import nltk
from nltk.tokenize import word_tokenize
import numpy as np
import random
import pickle
from collections import Counter
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
hm_lines = 100000
def create_lexicon(pos, neg):
lexicon = []
with open(pos, 'r') as f:
contents =... | [
"pickle.dump",
"nltk.stem.WordNetLemmatizer",
"random.shuffle",
"numpy.array",
"collections.Counter",
"nltk.tokenize.word_tokenize"
] | [((185, 204), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (202, 204), False, 'from nltk.stem import WordNetLemmatizer\n'), ((708, 724), 'collections.Counter', 'Counter', (['lexicon'], {}), '(lexicon)\n', (715, 724), False, 'from collections import Counter\n'), ((1774, 1798), 'random.shuffle', ... |
import numpy as np
class Metric:
def __init__(self, num_classes, ignore_indexes=[]):
self.num_classes = num_classes
self.ignore_indexes = ignore_indexes
self.matrix = np.zeros((self.num_classes, self.num_classes))
def reset(self):
self.matrix.fill(0)
def add(self, pred, l... | [
"numpy.diag",
"numpy.bincount",
"numpy.zeros",
"numpy.sum"
] | [((197, 243), 'numpy.zeros', 'np.zeros', (['(self.num_classes, self.num_classes)'], {}), '((self.num_classes, self.num_classes))\n', (205, 243), True, 'import numpy as np\n'), ((494, 588), 'numpy.bincount', 'np.bincount', (['(self.num_classes * label[mask] + pred[mask])'], {'minlength': '(self.num_classes ** 2)'}), '(s... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from utils import *
import numpy as np
WIDTH = 9
HEIGHT = 2
INIT_BALLS_COUNT_IN_PIT = 9
MAX_ARRAY_LEN_OF_ENCODED_PIT_STATE = 1 # TODO: find rignt value , minimum muste be 9 if tun encoding is onehot
BOARD_SIZE = WIDTH * HEIGHT
WIN_SCORE = (BOARD_SIZE * WIDTH)/HEIGHT
... | [
"numpy.concatenate"
] | [((2270, 2317), 'numpy.concatenate', 'np.concatenate', (['(firstHalf, secondHalf)'], {'axis': '(0)'}), '((firstHalf, secondHalf), axis=0)\n', (2284, 2317), True, 'import numpy as np\n')] |
def test_standard_absolute_deviation():
from pysad.models import StandardAbsoluteDeviation
import numpy as np
from numpy.testing import assert_raises
from pysad.utils import fix_seed
fix_seed(61)
X = np.random.rand(150, 1)
model = StandardAbsoluteDeviation(substracted_statistic="mean")
... | [
"numpy.random.rand",
"pysad.utils.fix_seed",
"numpy.testing.assert_raises",
"pysad.models.StandardAbsoluteDeviation"
] | [((205, 217), 'pysad.utils.fix_seed', 'fix_seed', (['(61)'], {}), '(61)\n', (213, 217), False, 'from pysad.utils import fix_seed\n'), ((226, 248), 'numpy.random.rand', 'np.random.rand', (['(150)', '(1)'], {}), '(150, 1)\n', (240, 248), True, 'import numpy as np\n'), ((262, 317), 'pysad.models.StandardAbsoluteDeviation'... |
"""
Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
Please note that this module is private. All functions and objects
are available in the main ``numpy`` namespace - use that instead.
"""
from numpy.version import version as __version__
import os
# disables OpenBLAS affinity setting of the main thread ... | [
"pickle.whichmodule",
"copyreg.pickle",
"numpy._pytesttester.PytestTester"
] | [((4087, 4143), 'copyreg.pickle', 'copyreg.pickle', (['ufunc', '_ufunc_reduce', '_ufunc_reconstruct'], {}), '(ufunc, _ufunc_reduce, _ufunc_reconstruct)\n', (4101, 4143), False, 'import copyreg\n'), ((4295, 4317), 'numpy._pytesttester.PytestTester', 'PytestTester', (['__name__'], {}), '(__name__)\n', (4307, 4317), False... |
import numpy as np
import sys, json
import numpy.random as rnd
from timeit import default_timer as now
######################################################
# GLOBAL DECLARATIONS THAT WILL BE USED IN ALL FILES #
######################################################
PRINT_DATA = 0
# make xrange available in python ... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"numpy.empty",
"timeit.default_timer",
"numpy.random.randint"
] | [((766, 791), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (789, 791), False, 'import argparse\n'), ((2008, 2022), 'numpy.random.seed', 'rnd.seed', (['SEED'], {}), '(SEED)\n', (2016, 2022), True, 'import numpy.random as rnd\n'), ((544, 580), 'numpy.random.randint', 'rnd.randint', (['LOW', 'HI... |
import numpy as np
import random
from ugd.model.digraph import RstDiGraph
import inspect
'''Random function'''
def rand_choise(q):
''' returns true with probability q '''
event = np.random.binomial(1, q)
return event == 1
def rand_element_of_set(set):
return random.sample(set, 1)[0]
''' path alg... | [
"random.sample",
"numpy.allclose",
"inspect.stack",
"numpy.random.binomial"
] | [((191, 215), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'q'], {}), '(1, q)\n', (209, 215), True, 'import numpy as np\n'), ((2472, 2501), 'numpy.allclose', 'np.allclose', (['a', 'a.T'], {'atol': 'tol'}), '(a, a.T, atol=tol)\n', (2483, 2501), True, 'import numpy as np\n'), ((2540, 2555), 'inspect.stack', 'i... |
#Program to find the inverse of a matrix.
#Developed by: <NAME>
#RegisterNumber: 21004191
import numpy as np
a=np.array([[2,1,1],[1,1,1,],[1,-1,2]])
values=np.linalg.inv(a)
print(values) | [
"numpy.linalg.inv",
"numpy.array"
] | [((115, 159), 'numpy.array', 'np.array', (['[[2, 1, 1], [1, 1, 1], [1, -1, 2]]'], {}), '([[2, 1, 1], [1, 1, 1], [1, -1, 2]])\n', (123, 159), True, 'import numpy as np\n'), ((161, 177), 'numpy.linalg.inv', 'np.linalg.inv', (['a'], {}), '(a)\n', (174, 177), True, 'import numpy as np\n')] |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | [
"numpy.zeros",
"sklearn.metrics.pairwise.euclidean_distances",
"numpy.nonzero",
"numpy.min",
"numpy.max",
"numpy.linalg.norm",
"numpy.where",
"numpy.unique"
] | [((1445, 1459), 'numpy.min', 'np.min', (['values'], {}), '(values)\n', (1451, 1459), True, 'import numpy as np\n'), ((1687, 1701), 'numpy.max', 'np.max', (['values'], {}), '(values)\n', (1693, 1701), True, 'import numpy as np\n'), ((2552, 2566), 'numpy.min', 'np.min', (['values'], {}), '(values)\n', (2558, 2566), True,... |
# -*- coding: utf-8 -*-
"""
Contains functions for reading flow fields in various formats
"""
import numpy as np
import xarray as xr
from glob import glob
import os, re
def create_sample_field(frame = 0):
""" creates a sample dataset for the tests """
x = np.arange(32.,128.,32.)
y = np.arange(16.,12... | [
"numpy.meshgrid",
"numpy.ones_like",
"numpy.zeros_like",
"os.path.basename",
"xarray.Dataset",
"xarray.concat",
"numpy.arange",
"xarray.DataArray",
"numpy.loadtxt",
"numpy.random.rand",
"os.path.join",
"numpy.unique"
] | [((272, 300), 'numpy.arange', 'np.arange', (['(32.0)', '(128.0)', '(32.0)'], {}), '(32.0, 128.0, 32.0)\n', (281, 300), True, 'import numpy as np\n'), ((304, 332), 'numpy.arange', 'np.arange', (['(16.0)', '(128.0)', '(16.0)'], {}), '(16.0, 128.0, 16.0)\n', (313, 332), True, 'import numpy as np\n'), ((341, 358), 'numpy.m... |
import pytest
from fastapi import BackgroundTasks
from typing import List, Tuple
import numpy as np
from tests.utils import floats_almost_equal, nested_floats_almost_equal
from src.constants import PLATFORM_ENUM
from src.app.ml.base_predictor import BaseData, BaseDataInterface, BaseDataConverter, BasePredictor
from sr... | [
"tests.utils.nested_floats_almost_equal",
"src.app.api._predict._predict_from_redis_cache",
"src.app.api._predict.__predict",
"src.app.api._predict._predict_async_get",
"fastapi.BackgroundTasks",
"src.app.api._predict._predict_async_get_label",
"numpy.array",
"src.app.api._predict._labels",
"pytest.... | [((767, 784), 'fastapi.BackgroundTasks', 'BackgroundTasks', ([], {}), '()\n', (782, 784), False, 'from fastapi import BackgroundTasks\n'), ((2805, 2950), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('job_id', 'data', 'expected')", "[(job_id, {'input_data': f_data}, {'input_data': f_data, 'prediction': [\n ... |
import numpy as np
from mchap.assemble import arraymap
def test_get__nan():
amap = arraymap.new(5, 2)
for _ in range(10):
a = np.random.randint(0, 2, 5)
actual = arraymap.get(amap, a)
assert np.isnan(actual)
def test_get_set_get():
amap = arraymap.new(5, 3)
a = np.array([0, ... | [
"mchap.assemble.arraymap.set",
"numpy.isnan",
"numpy.random.randint",
"numpy.array",
"mchap.assemble.arraymap.new",
"mchap.assemble.arraymap.get",
"numpy.all"
] | [((90, 108), 'mchap.assemble.arraymap.new', 'arraymap.new', (['(5)', '(2)'], {}), '(5, 2)\n', (102, 108), False, 'from mchap.assemble import arraymap\n'), ((280, 298), 'mchap.assemble.arraymap.new', 'arraymap.new', (['(5)', '(3)'], {}), '(5, 3)\n', (292, 298), False, 'from mchap.assemble import arraymap\n'), ((307, 332... |
# libraries
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import simps
import scipy.constants as cte
from scipy.sparse import diags
from scipy.linalg import inv
from scipy.fftpack import fft, ifft, fftfreq
import scipy.special as sp
from scipy.signal import gaussian
# matplotlib defaults setu... | [
"numpy.abs",
"numpy.vectorize",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.ptp",
"matplotlib.pyplot.legend",
"numpy.zeros",
"scipy.constants.value",
"scipy.fftpack.fft",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
... | [((1508, 1542), 'scipy.constants.value', 'cte.value', (['"""atomic unit of length"""'], {}), "('atomic unit of length')\n", (1517, 1542), True, 'import scipy.constants as cte\n'), ((1550, 1582), 'scipy.constants.value', 'cte.value', (['"""atomic unit of time"""'], {}), "('atomic unit of time')\n", (1559, 1582), True, '... |
from typing import List, Tuple
import array
import numpy as np
from scipy.sparse import coo_matrix, dok_matrix
from ..state import StateVar, StateVector
from . import CostTerm
class LazyCOOBuilder:
class SlicingHandler:
def __init__(self, key: Tuple[slice, slice]):
self.key = key
rows, cols = ke... | [
"scipy.sparse.coo_matrix",
"numpy.zeros",
"array.array"
] | [((688, 704), 'array.array', 'array.array', (['"""i"""'], {}), "('i')\n", (699, 704), False, 'import array\n'), ((721, 737), 'array.array', 'array.array', (['"""i"""'], {}), "('i')\n", (732, 737), False, 'import array\n'), ((754, 770), 'array.array', 'array.array', (['"""d"""'], {}), "('d')\n", (765, 770), False, 'impo... |
from threading import Thread, Lock
from Queue import Empty
from time import sleep
import json
import numpy as np
from typing import Optional, List, Dict
class Scheduler(Thread):
"""
Runs Threaded Task Continuously with certain interval
This is useful for long running Real-Time tasks:
When there ... | [
"threading.Thread.__init__",
"threading.Thread.join",
"time.sleep",
"threading.Lock",
"numpy.sin",
"numpy.cos"
] | [((955, 987), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {'name': 'name'}), '(self, name=name)\n', (970, 987), False, 'from threading import Thread, Lock\n'), ((1405, 1431), 'threading.Thread.join', 'Thread.join', (['self', 'timeout'], {}), '(self, timeout)\n', (1416, 1431), False, 'from threading impor... |
import os
import pdb
import random
import madmom
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.metrics import f1_score
from mir_eval.onset import f_measure
from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
from ... | [
"os.mkdir",
"numpy.load",
"numpy.sum",
"numpy.abs",
"numpy.mean",
"os.nice",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.size",
"madmom.features.onsets.OnsetPeakPickingProcessor",
"numpy.std",
"tensorflow.keras.callbacks.ReduceLROnPlateau",
"numpy.max",
"tensorflow.keras.optimize... | [((408, 418), 'os.nice', 'os.nice', (['(0)'], {}), '(0)\n', (415, 418), False, 'import os\n'), ((447, 498), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (491, 498), True, 'import tensorflow as tf\n'), ((1941, 1954), 'numpy.arra... |
"""
Plot spectra.
"""
from __future__ import print_function, division
import os
import numpy as np
import astropy.units as u
import astropy.constants as const
from astropy.table import Table
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from tqdm import tqdm
import context
def plot_ngc331... | [
"os.mkdir",
"tqdm.tqdm",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.tight_layout",
"astropy.constants.c.to",
"os.path.abspath",
"os.path.split",
"matplotlib.pyplot.close",
"os.path.exists",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.loadtxt",
"context.get_field_files",
"matplot... | [((1365, 1395), 'context.get_field_files', 'context.get_field_files', (['field'], {}), '(field)\n', (1388, 1395), False, 'import context\n'), ((1486, 1534), 'os.path.join', 'os.path.join', (['wdir', '"""plots"""', '"""spec_with_indices"""'], {}), "(wdir, 'plots', 'spec_with_indices')\n", (1498, 1534), False, 'import os... |
from itertools import cycle
import numpy as np
import torch
import torch.nn as nn
import models
from layers import masked_cross_entropy
from utils import to_var, time_desc_decorator, TensorboardWriter, pad_and_pack, normal_kl_div, to_bow, bag_of_words_loss, normal_kl_div, embedding_metric
import os
from tqdm import tqd... | [
"numpy.sum",
"numpy.exp",
"gensim.models.KeyedVectors.load_word2vec_format",
"torch.no_grad",
"os.path.join",
"torch.load",
"torch.exp",
"utils.embedding_metric",
"tqdm.tqdm",
"os.path.basename",
"torch.cuda.is_available",
"numpy.concatenate",
"tqdm.tqdm.write",
"layers.masked_cross_entrop... | [((834, 868), 'utils.time_desc_decorator', 'time_desc_decorator', (['"""Build Graph"""'], {}), "('Build Graph')\n", (853, 868), False, 'from utils import to_var, time_desc_decorator, TensorboardWriter, pad_and_pack, normal_kl_div, to_bow, bag_of_words_loss, normal_kl_div, embedding_metric\n'), ((4439, 4477), 'utils.tim... |
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from torch.nn.init import xavier_uniform_, constant_
import jax
from jax_md import space, partition
from jax import numpy as jnp
import warnings
warnings.filterwarnings("ignore")
@torch.no_grad()
def pairwise_distance_norm(x, box_siz... | [
"jax_md.space.periodic",
"jax.numpy.logical_or",
"torch.sqrt",
"torch.cat",
"numpy.ones",
"torch.no_grad",
"jax.jit",
"jax.numpy.where",
"torch.remainder",
"torch.sign",
"jax_md.partition.neighbor_list",
"jax.vmap",
"torch.norm",
"jax_md.space.metric",
"torch.sqrt_",
"torch.clamp",
"... | [((230, 263), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (253, 263), False, 'import warnings\n'), ((267, 282), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (280, 282), False, 'import torch\n'), ((1693, 1714), 'torch.sqrt_', 'torch.sqrt_', (['dist_all'], {}), '(d... |
""" Techniques to compute preactivation bounds for piecewise linear nets"""
from relu_nets import ReLUNet
from hyperbox import Hyperbox
import utilities as utils
import torch
import numpy as np
import torch.nn as nn
# ====================================================================
# = Class to store p... | [
"numpy.maximum",
"numpy.abs",
"numpy.logical_and",
"numpy.copy",
"utilities.two_col",
"torch.Tensor",
"utilities.as_numpy",
"torch.abs"
] | [((4004, 4028), 'utilities.as_numpy', 'utils.as_numpy', (['c_vector'], {}), '(c_vector)\n', (4018, 4028), True, 'import utilities as utils\n'), ((8110, 8129), 'numpy.copy', 'np.copy', (['input_lows'], {}), '(input_lows)\n', (8117, 8129), True, 'import numpy as np\n'), ((8150, 8170), 'numpy.copy', 'np.copy', (['input_hi... |
import my_keras.input_manipulation as to_test
import numpy as np
def test_rotate_array():
xs = [1, 2, 3, 4, 5]
assert np.array_equal(to_test.rotate(xs, 2), np.asarray([3, 4, 5, 1, 2]))
def test_rotate_array_wrap():
xs = [1, 2, 3, 4, 5]
assert np.array_equal(to_test.rotate(xs, 7), np.asarray([3, 4, 5... | [
"my_keras.input_manipulation.rotate",
"numpy.asarray"
] | [((143, 164), 'my_keras.input_manipulation.rotate', 'to_test.rotate', (['xs', '(2)'], {}), '(xs, 2)\n', (157, 164), True, 'import my_keras.input_manipulation as to_test\n'), ((166, 193), 'numpy.asarray', 'np.asarray', (['[3, 4, 5, 1, 2]'], {}), '([3, 4, 5, 1, 2])\n', (176, 193), True, 'import numpy as np\n'), ((278, 29... |
import glob
import imageio
import numpy as np
import os
from os import path
import random
import tqdm
from dataloader import _pil_loader
import torch
from torch import nn
from torch.utils import data
class GoPro(data.Dataset):
def __init__(self, root, transform=None, dim=(1280, 720), randomCropSize=(352, 352), ... | [
"numpy.save",
"random.randint",
"os.path.basename",
"os.path.dirname",
"numpy.ascontiguousarray",
"imageio.imread",
"random.random",
"os.path.isfile",
"glob.glob",
"os.path.join"
] | [((2593, 2622), 'os.path.join', 'path.join', (['data_root', '"""GoPro"""'], {}), "(data_root, 'GoPro')\n", (2602, 2622), False, 'from os import path\n'), ((2999, 3033), 'os.path.join', 'path.join', (['self.data_root', '"""train"""'], {}), "(self.data_root, 'train')\n", (3008, 3033), False, 'from os import path\n'), ((3... |
# coding=utf-8
import argparse
import sys
import numpy as np
from collections import deque
from math import exp
import isa
from config import MATSIZE as WIDTH
args = None
# width of the tile
#WIDTH = 16
class TPUSim(object):
def __init__(self, program_filename, dram_filename, hostmem_filename):
# TODO: ... | [
"numpy.load",
"numpy.save",
"numpy.vectorize",
"argparse.ArgumentParser",
"math.exp",
"numpy.zeros",
"numpy.matmul",
"sys.exit",
"collections.deque"
] | [((5174, 5199), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5197, 5199), False, 'import argparse\n'), ((432, 454), 'numpy.load', 'np.load', (['dram_filename'], {}), '(dram_filename)\n', (439, 454), True, 'import numpy as np\n'), ((482, 507), 'numpy.load', 'np.load', (['hostmem_filename'], {... |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import importsd
NUM_WORDS = 100
EMBEDDING_VEC_LEN = 100
HIDDEN_SIZE = 128
class LSTMModel(nn.Module):
# The names of properties should be the same in C# and Python
# otherwise, you have to... | [
"torch.nn.Dropout",
"numpy.random.seed",
"torch.nn.Embedding",
"numpy.random.randint",
"torch.nn.BCELoss",
"importsd.load_state_dict",
"torch.nn.Linear",
"torch.nn.LSTM",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.max",
"torch.nn.MaxPool2d",
"torch.sum",
"torc... | [((2316, 2336), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2333, 2336), False, 'import torch\n'), ((2341, 2358), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2355, 2358), True, 'import numpy as np\n'), ((2571, 2583), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (2581, 2... |
import gc
import glob
import os
import shutil
import cv2
import keras
import keras.backend as K
import keras.callbacks as callbacks
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
from keras import Model
from keras import backend as K
from keras impo... | [
"numpy.uint8",
"numpy.random.shuffle",
"os.getcwd",
"numpy.array",
"cv2.resize",
"numpy.repeat"
] | [((2543, 2574), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indexes'], {}), '(self.indexes)\n', (2560, 2574), True, 'import numpy as np\n'), ((3860, 3906), 'cv2.resize', 'cv2.resize', (['im', '(self.img_size, self.img_size)'], {}), '(im, (self.img_size, self.img_size))\n', (3870, 3906), False, 'import cv2\n'),... |
import re
import torch
# Example finding for thesis
device = torch.device("cuda")
from bert.preprocessing_bert import BertPreprocessor
from transformers import BertTokenizer, BertForSequenceClassification
import numpy as np
import torch.nn.functional as F
pretrained_weights = 'bert-base-uncased'
bert_tokenizer = Ber... | [
"transformers.BertForSequenceClassification.from_pretrained",
"numpy.argmax",
"torch.load",
"re.match",
"torch.nn.functional.softmax",
"bert.preprocessing_bert.BertPreprocessor",
"transformers.BertTokenizer.from_pretrained",
"torch.device",
"torch.tensor"
] | [((63, 83), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (75, 83), False, 'import torch\n'), ((317, 366), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['pretrained_weights'], {}), '(pretrained_weights)\n', (346, 366), False, 'from transformers import BertTokeniz... |
import os
import csv
import numpy as np
from config import config as cfg
class KITTILoader():
def __init__(self, subset='training'):
super(KITTILoader, self).__init__()
self.base_dir = cfg().base_dir
self.KITTI_cat = cfg().KITTI_cat
label_dir = os.path.join(self.base_dir, subset, ... | [
"config.config",
"csv.DictReader",
"numpy.array",
"os.path.join",
"os.listdir"
] | [((284, 330), 'os.path.join', 'os.path.join', (['self.base_dir', 'subset', '"""label_2"""'], {}), "(self.base_dir, subset, 'label_2')\n", (296, 330), False, 'import os\n'), ((351, 397), 'os.path.join', 'os.path.join', (['self.base_dir', 'subset', '"""image_2"""'], {}), "(self.base_dir, subset, 'image_2')\n", (363, 397)... |
#!/usr/bin/python
'''
mjtsai1974@20180606, v1.0, simple subplot with figure size
https://stackoverflow.com/questions/41530975/set-size-of-subplot-in-matplotlib
'''
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(20)
y = np.random.randn(20)
#fig = plt.figure(figsize=(20, 8))
fig = plt.figure(... | [
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.random.randn"
] | [((223, 242), 'numpy.random.randn', 'np.random.randn', (['(20)'], {}), '(20)\n', (238, 242), True, 'import numpy as np\n'), ((247, 266), 'numpy.random.randn', 'np.random.randn', (['(20)'], {}), '(20)\n', (262, 266), True, 'import numpy as np\n'), ((309, 336), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '... |
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from scipy.spatial.distance import pdist, squareform
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.manifold import MDS
def rf_proximities(forest, X):
prox = pdist(forest.app... | [
"sklearn.ensemble.RandomForestClassifier",
"sklearn.datasets.load_digits",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.plot",
"scipy.spatial.distance.squareform",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.matshow",
"numpy.argsort",
"sklearn.manifold.MDS"
] | [((431, 444), 'sklearn.datasets.load_digits', 'load_digits', ([], {}), '()\n', (442, 444), False, 'from sklearn.datasets import load_digits\n'), ((486, 499), 'numpy.argsort', 'np.argsort', (['y'], {}), '(y)\n', (496, 499), True, 'import numpy as np\n'), ((681, 711), 'matplotlib.pyplot.matshow', 'plt.matshow', (['prox']... |
# coding: utf-8
import argparse
import copy
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from models import LeNet5Client, LeNet5Server, ResNet_cifarClient, ResNet_cifarServer
from split_data import iid as iid_f
from split_data import noniid
from flearn.clie... | [
"os.mkdir",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.mean",
"torch.cuda.current_device",
"torch.no_grad",
"os.path.join",
"flearn.common.utils.setup_seed",
"flearn.client.datasets.get_dataloader",
"models.ResNet_cifarServer",
"split_data.noniid",
"flearn.client.datasets.get_datasets",
... | [((457, 470), 'flearn.common.utils.setup_seed', 'setup_seed', (['(0)'], {}), '(0)\n', (467, 470), False, 'from flearn.common.utils import get_free_gpu_id, setup_seed\n'), ((477, 494), 'flearn.common.utils.get_free_gpu_id', 'get_free_gpu_id', ([], {}), '()\n', (492, 494), False, 'from flearn.common.utils import get_free... |
"""
===================
Quantile regression
===================
This example illustrates how quantile regression can predict non-trivial
conditional quantiles.
The left figure shows the case when the error distribution is normal,
but has non-constant variance, i.e. with heteroscedasticity.
The right figure shows an ... | [
"matplotlib.pyplot.title",
"numpy.zeros_like",
"matplotlib.pyplot.plot",
"sklearn.model_selection.cross_validate",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"numpy.random.RandomState",
"sklearn.metrics.mean_absolute_error",
"sklearn.linear_model.LinearRegression",
"sklearn.linear_mo... | [((857, 882), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (878, 882), True, 'import numpy as np\n'), ((887, 925), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(10)', 'num': '(100)'}), '(start=0, stop=10, num=100)\n', (898, 925), True, 'import numpy as np\n'), ((1553... |
# Author: <NAME>
# ECG Biometric Authentication using CNN
import os
import pickle
import random
import librosa
import numpy as np
import pandas as pd
import warnings
from biosppy.signals import ecg
from scipy import signal
from scipy.signal import filtfilt, find_peaks
from matplotlib import pyplot as plt
def resamp... | [
"matplotlib.pyplot.title",
"pickle.dump",
"numpy.argmax",
"pandas.read_csv",
"random.shuffle",
"numpy.isnan",
"librosa.effects.time_stretch",
"librosa.power_to_db",
"numpy.mean",
"librosa.feature.melspectrogram",
"random.randint",
"warnings.simplefilter",
"numpy.std",
"os.path.exists",
"... | [((347, 376), 'scipy.signal.resample', 'signal.resample', (['array', 'times'], {}), '(array, times)\n', (362, 376), False, 'from scipy import signal\n'), ((413, 484), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', ([], {'y': 'y', 'sr': 'sr', 'n_fft': '(2048)', 'hop_length': '(1024)'}), '(y=y, sr=sr... |
"""
Configuration file for capturing TD Ameritrade data into PostgreSQL database
@author: <NAME>, August 2021
"""
import numpy as np
import pandas as pd
import os
import copy
# Define symbol lookup path - make sure 'symbol' is a column name
symbolpath = '/path/to/symbols.csv'
# Define chrome webdriver path
webdriverp... | [
"numpy.round",
"copy.deepcopy",
"numpy.where",
"numpy.zeros"
] | [((3558, 3584), 'copy.deepcopy', 'copy.deepcopy', (["df['Close']"], {}), "(df['Close'])\n", (3571, 3584), False, 'import copy\n'), ((6407, 6500), 'numpy.where', 'np.where', (["((df['UpMove'] > df['DownMove']) & (df['UpMove'] > df['Zero']))", "df['UpMove']", '(0)'], {}), "((df['UpMove'] > df['DownMove']) & (df['UpMove']... |
"""
The PortOpt application is powered by multiple optimizers designed to implement theory in an elegant
and easy to use way.
This module consists all the functions required to run a portfolio optimization using parameters
that the user inputs
"""
import math
import numpy as np
from numpy import linalg as LA
import ... | [
"numpy.nan_to_num",
"numpy.ones",
"numpy.mean",
"numpy.diag",
"pandas.DataFrame",
"numpy.linalg.eig",
"osqp.OSQP",
"test.displayText",
"numpy.cov",
"pandas.DataFrame.from_dict",
"numpy.hstack",
"numpy.dot",
"numpy.vstack",
"math.exp",
"numpy.log",
"numpy.zeros",
"scipy.sparse.csc_mat... | [((931, 959), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['data'], {}), '(data)\n', (953, 959), True, 'import pandas as pd\n'), ((1293, 1312), 'numpy.array', 'np.array', (['df_logret'], {}), '(df_logret)\n', (1301, 1312), True, 'import numpy as np\n'), ((1410, 1424), 'numpy.array', 'np.array', (['data'], ... |
# Originally by adamb70 from https://github.com/adamb70/Python-Spherical-Projection
# Modified to be used with Source Engine cubemaps.
# Converted to numpy to achieve reasonable performance.
import numpy
from numpy import ndarray
from enum import IntEnum
from typing import Tuple
def spherical_coordinates(i: ndarray,... | [
"numpy.abs",
"numpy.sin",
"numpy.select",
"numpy.cos",
"numpy.maximum.reduce"
] | [((759, 773), 'numpy.cos', 'numpy.cos', (['phi'], {}), '(phi)\n', (768, 773), False, 'import numpy\n'), ((1165, 1177), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (1174, 1177), False, 'import numpy\n'), ((1190, 1202), 'numpy.abs', 'numpy.abs', (['y'], {}), '(y)\n', (1199, 1202), False, 'import numpy\n'), ((1215, 12... |
import pickle
import torch.utils.data as data
import torch.nn.parallel
import os
import torch
import numpy as np
class _OneHotIterator:
"""
>>> it_1 = _OneHotIterator(n_features=128, n_batches_per_epoch=2, batch_size=64, seed=1)
>>> it_2 = _OneHotIterator(n_features=128, n_batches_per_epoch=2, batch_size=... | [
"numpy.argmax",
"numpy.ones",
"numpy.argmin",
"numpy.random.RandomState",
"numpy.random.randint",
"numpy.array",
"numpy.random.choice",
"torch.zeros",
"torch.from_numpy"
] | [((991, 1018), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (1012, 1018), True, 'import numpy as np\n'), ((895, 914), 'numpy.ones', 'np.ones', (['n_features'], {}), '(n_features)\n', (902, 914), True, 'import numpy as np\n'), ((1425, 1468), 'numpy.random.choice', 'np.random.choice', ... |
import shutil, os, sys, json
import numpy as np
system = "slurm"
from_dir = sys.argv[1]
to_dir = sys.argv[2]
t_cut = int(sys.argv[3])
submit_job = len(sys.argv) == 5 and str(sys.argv[4]) == "--submit"
with open(from_dir + "/evo_params.json", "r") as f:
fromevo_params = json.load(f)
with open(to_dir + "/evo... | [
"numpy.load",
"numpy.save",
"json.load",
"os.getcwd",
"shutil.copyfile",
"os.path.join",
"numpy.vstack"
] | [((1160, 1205), 'numpy.save', 'np.save', (["(to_dir + '/eta_sqs_evo.npy')", 'eta_sqs'], {}), "(to_dir + '/eta_sqs_evo.npy', eta_sqs)\n", (1167, 1205), True, 'import numpy as np\n'), ((1206, 1253), 'numpy.save', 'np.save', (["(to_dir + '/schmidts_evo.npy')", 'schmidts'], {}), "(to_dir + '/schmidts_evo.npy', schmidts)\n"... |
import subprocess as sp
import pandas as pd
import numpy as np
import h5py
import click
import os
import sys
from tqdm import tqdm
from astropy.io import fits
from joblib import Parallel, delayed
from fact.credentials import create_factdb_engine
import config as config
from constants import NRCHID
@click.command()... | [
"pandas.date_range",
"click.argument",
"os.makedirs",
"astropy.io.fits.PrimaryHDU",
"os.path.exists",
"click.command",
"fact.credentials.create_factdb_engine",
"os.path.isfile",
"numpy.mean",
"click.Path",
"astropy.io.fits.open",
"numpy.array",
"joblib.Parallel",
"pandas.to_datetime",
"a... | [((305, 320), 'click.command', 'click.command', ([], {}), '()\n', (318, 320), False, 'import click\n'), ((1519, 1588), 'click.argument', 'click.argument', (['"""time_interval"""'], {'default': "['2014-05-20', '2015-05-26']"}), "('time_interval', default=['2014-05-20', '2015-05-26'])\n", (1533, 1588), False, 'import cli... |
# Copyright 2020 <NAME> (@usimarit)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | [
"sentencepiece.SentencePieceProcessor",
"tensorflow_datasets.deprecated.text.SubwordTextEncoder.load_from_file",
"numpy.arange",
"tensorflow.numpy_function",
"multiprocessing.cpu_count",
"tensorflow.not_equal",
"tensorflow.strings.unicode_decode",
"codecs.open",
"tensorflow.less",
"tensorflow.Tens... | [((2714, 2753), 'tensorflow.concat', 'tf.concat', (['[[self.blank], text]'], {'axis': '(0)'}), '([[self.blank], text], axis=0)\n', (2723, 2753), True, 'import tensorflow as tf\n'), ((4619, 4669), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['self.tokens'], {'dtype': 'tf.string'}), '(self.tokens, dtype=tf.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.