code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.base.Network import MYNET as Net
import numpy as np
class MYNET(Net):
def __init__(self, args, mode=None):
super().__init__(args,mode)
hdim=self.num_features
self.slf_attn = MultiHeadAttention(1, hdim, hdim, h... | [
"torch.nn.Dropout",
"torch.bmm",
"numpy.power",
"torch.nn.init.xavier_normal_",
"torch.cat",
"torch.nn.LayerNorm",
"torch.nn.Softmax",
"torch.nn.functional.log_softmax",
"torch.nn.Linear",
"torch.nn.functional.cosine_similarity",
"numpy.sqrt"
] | [((1241, 1269), 'torch.cat', 'torch.cat', (['[proto, query]', '(1)'], {}), '([proto, query], 1)\n', (1250, 1269), False, 'import torch\n'), ((1480, 1521), 'torch.nn.functional.cosine_similarity', 'F.cosine_similarity', (['query', 'proto'], {'dim': '(-1)'}), '(query, proto, dim=-1)\n', (1499, 1521), True, 'import torch.... |
# Copyright: (c) 2021, <NAME>
import numpy as np
def hexToBitStr(hexStr):
"""
provide the hex string in format 'ab ab ab....
Returns the bits in string format, as list of bytes
"""
b = [int(hexStr[i*3:i*3+2],16) for i in range(int((len(hexStr)+1)/3))]
bytesequence = ['{0:08b}'.format(g) for... | [
"numpy.fliplr",
"numpy.arange",
"numpy.prod"
] | [((771, 794), 'numpy.fliplr', 'np.fliplr', (['byteSequence'], {}), '(byteSequence)\n', (780, 794), True, 'import numpy as np\n'), ((827, 854), 'numpy.prod', 'np.prod', (['byteSequence.shape'], {}), '(byteSequence.shape)\n', (834, 854), True, 'import numpy as np\n'), ((1078, 1096), 'numpy.arange', 'np.arange', (['(0)', ... |
import os
import numpy as np
import warnings
warnings.filterwarnings('ignore')
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from config import *
from dataset import get_div2k_loader
from models import Discriminator, Generator_SRGAN, Generator_ESRGAN
from losses import PerceptualLoss, TVLoss... | [
"models.Discriminator",
"utils.get_lr_scheduler",
"torch.nn.MSELoss",
"losses.TVLoss",
"utils.make_dirs",
"losses.PerceptualLoss",
"dataset.get_div2k_loader",
"torch.mean",
"torch.nn.BCEWithLogitsLoss",
"numpy.average",
"torch.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.is_available"... | [((45, 78), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (68, 78), False, 'import warnings\n'), ((550, 575), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (573, 575), False, 'import torch\n'), ((644, 664), 'torch.manual_seed', 'torch.manual_seed... |
import numpy as np
import pandas as pd
import time
import os
params_appliance = {
'kettle': {
'windowlength': 599,
'on_power_threshold': 2000,
'max_on_power': 3998,
'mean': 700,
'std': 1000,
's2s_length': 128,
'houses': [1, 2],
'channels': [10, 8],
... | [
"pandas.DataFrame",
"numpy.load",
"pandas.date_range",
"time.time",
"os.listdir"
] | [((1818, 1829), 'time.time', 'time.time', ([], {}), '()\n', (1827, 1829), False, 'import time\n'), ((3080, 3098), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (3092, 3098), True, 'import pandas as pd\n'), ((3389, 3437), 'pandas.date_range', 'pd.date_range', (['(0)'], {'periods': 'df.shape[0]', 'freq'... |
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
def mnist():
# exchange with the corrupted mnist dataset
#train = torch.randn(50000, 784)
#test = torch.randn(10000, 784)
#train
train0 = np.load("train_0.npz")
train1 = np.load("train_1.npz")
... | [
"torch.utils.data.Dataset",
"numpy.load",
"torch.from_numpy"
] | [((253, 275), 'numpy.load', 'np.load', (['"""train_0.npz"""'], {}), "('train_0.npz')\n", (260, 275), True, 'import numpy as np\n'), ((291, 313), 'numpy.load', 'np.load', (['"""train_1.npz"""'], {}), "('train_1.npz')\n", (298, 313), True, 'import numpy as np\n'), ((329, 351), 'numpy.load', 'np.load', (['"""train_2.npz""... |
# Import the necessary modules.
import numpy as np
import skimage.io
import glob
import scipy.ndimage
import skimage.morphology
import skimage.segmentation
import matplotlib.pyplot as plt
# Load the images.
im_glob = glob.glob('data/optical_tweezer/bead*.tif')
x = 'data/optical_tweezer/trapped_bead_5.2x_4_MMStack_Pos0... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.nonzero",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"glob.glob",
"numpy.dot"
] | [((218, 261), 'glob.glob', 'glob.glob', (['"""data/optical_tweezer/bead*.tif"""'], {}), "('data/optical_tweezer/bead*.tif')\n", (227, 261), False, 'import glob\n'), ((1564, 1576), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1574, 1576), True, 'import matplotlib.pyplot as plt\n'), ((1577, 1604), 'matplo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 6 10:10:55 2021
@author: jiaweiguo
"""
import os
from pathlib import Path
from ase.io import write, read
import copy
import shutil
from glob import glob
from ase.constraints import FixAtoms
from collections import defaultdict
from ase.neighborlist... | [
"numpy.sum",
"ase.neighborlist.mic",
"pathlib.Path",
"numpy.linalg.norm",
"numpy.random.normal",
"os.path.join",
"os.listdir",
"ase.Atoms"
] | [((1080, 1111), 'os.path.join', 'os.path.join', (['output_dir0', 'file'], {}), '(output_dir0, file)\n', (1092, 1111), False, 'import os\n'), ((1632, 1659), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(3,)'}), '(size=(3,))\n', (1648, 1659), True, 'import numpy as np\n'), ((1768, 1797), 'ase.Atoms', 'Atoms'... |
from util import get_raw_data
import pandas as pd
import numpy as np
def create_sma(price_array, window):
if len(price_array) < window:
return None
sma = np.zeros(len(price_array))
for i in range(window, len(price_array)):
sma[i] = np.sum(price_array[i-window:i])/float(window)
return sm... | [
"pandas.DataFrame",
"numpy.array",
"numpy.sum",
"util.get_raw_data"
] | [((3073, 3087), 'util.get_raw_data', 'get_raw_data', ([], {}), '()\n', (3085, 3087), False, 'from util import get_raw_data\n'), ((3216, 3239), 'numpy.array', 'np.array', (["df['average']"], {}), "(df['average'])\n", (3224, 3239), True, 'import numpy as np\n'), ((3255, 3275), 'numpy.array', 'np.array', (["df['date']"], ... |
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(precision=2)
import sklearn.metrics as skm
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
from summ_evaluator import SummaryEvaluator
class ClassificationEvaluator(SummaryEvaluator):
def __init__... | [
"numpy.set_printoptions",
"matplotlib.pyplot.show",
"sklearn.metrics.classification_report",
"sklearn.metrics.f1_score",
"numpy.arange",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.subplots"
] | [((51, 83), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (70, 83), True, 'import numpy as np\n'), ((4752, 4762), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4760, 4762), True, 'import matplotlib.pyplot as plt\n'), ((893, 952), 'sklearn.metrics.classificati... |
#!/usr/bin/env python
# coding: utf-8
print("Running k-neighborhood algorithm")
import pandas as pd
import numpy as np
import termplotlib as tpl
import seaborn as sns
import os
import sys
#add path to import to_bib module
sys.path.append("../to_bib")
from to_bib import *
try:
new_path=sys.argv[1]
except:
rais... | [
"sys.path.append",
"pandas.DataFrame",
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report",
"termplotlib.figure",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.mean",
"os.chdir",
"numpy.unique"
] | [((222, 250), 'sys.path.append', 'sys.path.append', (['"""../to_bib"""'], {}), "('../to_bib')\n", (237, 250), False, 'import sys\n'), ((365, 383), 'os.chdir', 'os.chdir', (['new_path'], {}), '(new_path)\n', (373, 383), False, 'import os\n'), ((390, 425), 'pandas.read_csv', 'pd.read_csv', (['"""human_classified.csv"""']... |
"""
This module implements all the functions to read a video or a picture
using ffmpeg. It is quite ugly, as there are many pitfalls to avoid
Modified version, copied from
https://github.com/Zulko/moviepy/blob/master/moviepy/video/io/ffmpeg_reader.py
and
https://github.com/Zulko/moviepy/blob/master/moviepy/audio/io/re... | [
"subprocess.Popen",
"re.findall",
"datetime.timedelta",
"re.search",
"time.strptime",
"numpy.fromstring"
] | [((6934, 6963), 'subprocess.Popen', 'sp.Popen', (['cmd'], {}), '(cmd, **popen_params)\n', (6942, 6963), True, 'import subprocess as sp\n'), ((12006, 12037), 'time.strptime', 'time.strptime', (['main', '"""%H:%M:%S"""'], {}), "(main, '%H:%M:%S')\n", (12019, 12037), False, 'import time\n'), ((2964, 2993), 'subprocess.Pop... |
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Licens... | [
"numpy.asarray",
"six.iteritems",
"time.time"
] | [((2335, 2354), 'six.iteritems', 'iteritems', (['col_data'], {}), '(col_data)\n', (2344, 2354), False, 'from six import iteritems\n'), ((4135, 4167), 'numpy.asarray', 'np.asarray', (['(tp * 1.0 / (tp + fn))'], {}), '(tp * 1.0 / (tp + fn))\n', (4145, 4167), True, 'import numpy as np\n'), ((4208, 4240), 'numpy.asarray', ... |
import numpy as np
from . import Kernel
class Model(Kernel.Kernel):
""" A subclass that represents the Young & <NAME> uncoupled model
of single-vertical wavenumber near-inertial waves and STEADY
barotropic quasigeostrophic flow.
It defines the quasigeostrophic inversion relation and the d... | [
"numpy.arange",
"numpy.dtype",
"numpy.zeros",
"numpy.exp"
] | [((869, 888), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (877, 888), True, 'import numpy as np\n'), ((915, 937), 'numpy.dtype', 'np.dtype', (['"""complex128"""'], {}), "('complex128')\n", (923, 937), True, 'import numpy as np\n'), ((1067, 1109), 'numpy.zeros', 'np.zeros', (['self.shape_real', ... |
import numpy as np
class Function:
def __init__(self, function, functionDerivate):
self.function = function
self.functionDerivate = functionDerivate
def __call__(self, x):
return self.function(x)
def derivate(self, x):
return self.functionDerivate(x)
def sigmoidFun... | [
"numpy.exp"
] | [((352, 361), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (358, 361), True, 'import numpy as np\n')] |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"arch.api.utils.log_utils.getLogger",
"numpy.array"
] | [((726, 747), 'arch.api.utils.log_utils.getLogger', 'log_utils.getLogger', ([], {}), '()\n', (745, 747), False, 'from arch.api.utils import log_utils\n'), ((2938, 2958), 'numpy.array', 'np.array', (['reduce_res'], {}), '(reduce_res)\n', (2946, 2958), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
#
import sys, os
sys.path.append('./utils/')
import tools
import datatools as dtools
from time import time
os.environ["CUDA_VISIBLE_DEVICES"]="1"
#
import tensorflow as tf
import tensorflow_hub as hub
#########################... | [
"numpy.load",
"matplotlib.pyplot.yscale",
"numpy.random.seed",
"tensorflow_hub.Module",
"tensorflow.reset_default_graph",
"tools.readbigfile",
"matplotlib.pyplot.figure",
"numpy.arange",
"os.path.join",
"numpy.unique",
"sys.path.append",
"numpy.pad",
"tensorflow.set_random_seed",
"tools.pa... | [((106, 133), 'sys.path.append', 'sys.path.append', (['"""./utils/"""'], {}), "('./utils/')\n", (121, 133), False, 'import sys, os\n'), ((367, 380), 'numpy.random.seed', 'seed', (['seed_in'], {}), '(seed_in)\n', (371, 380), False, 'from numpy.random import seed\n'), ((420, 444), 'tensorflow.set_random_seed', 'set_rando... |
from argparse import ArgumentParser
import keras
from keras import backend as K
import sys
import tensorflow as tf
import os
from pdb import set_trace
from sklearn.model_selection import train_test_split
parser = ArgumentParser()
parser.add_argument('outputDir')
parser.add_argument(
'method', choices = [
'domain_ad... | [
"pandas.DataFrame",
"numpy.save",
"argparse.ArgumentParser",
"make_samples.make_sample",
"imp.find_module",
"os.path.isdir",
"sklearn.model_selection.train_test_split",
"os.path.dirname",
"keras.backend.set_session",
"os.makedirs",
"keras.optimizers.Adam",
"keras.models.Model",
"tensorflow.C... | [((214, 230), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (228, 230), False, 'from argparse import ArgumentParser\n'), ((2338, 2401), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'args.gpufraction'}), '(per_process_gpu_memory_fraction=args.gpufraction)\n', (2351,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ===============================================================
# Copyright (C) 2018 HuangYk.
# Licensed under The MIT Lincese.
#
# Filename : TorchSoa.py
# Author : HuangYK
# Last Modified: 2019-03-21 14:19
# Description :
#
# ================================... | [
"pandas.DataFrame",
"tqdm.tqdm",
"copy.deepcopy",
"os.makedirs",
"numpy.power",
"torchnet.meter.AverageValueMeter",
"time.strftime",
"os.path.exists",
"time.sleep",
"collections.defaultdict",
"torchnet.meter.ConfusionMeter",
"numpy.arange",
"math.cos",
"torch.cuda.empty_cache",
"torchnet... | [((18738, 18772), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""'], {}), "('%Y-%m-%d %H:%M:%S')\n", (18751, 18772), False, 'import time\n'), ((9120, 9143), 'tqdm.tqdm', 'tqdm', (["state['iterator']"], {}), "(state['iterator'])\n", (9124, 9143), False, 'from tqdm import tqdm\n'), ((10344, 10368), 'torch.cu... |
"""Probabilistic models for classification."""
from dataclasses import dataclass
import numpy as np
from scipy.special import gammaln, softmax # pylint: disable=no-name-in-module
from scipy.linalg import solve_triangular, solve, eigh, eig
class Model:
"""Generic model interface."""
def __init__(self):
... | [
"scipy.linalg.solve",
"numpy.zeros_like",
"numpy.sum",
"numpy.log",
"scipy.linalg.solve_triangular",
"numpy.zeros",
"numpy.ones",
"scipy.linalg.eig",
"numpy.einsum",
"numpy.append",
"numpy.max",
"numpy.mean",
"scipy.linalg.eigh",
"numpy.real",
"numpy.cov",
"numpy.log1p",
"numpy.uniqu... | [((1595, 1624), 'scipy.linalg.eigh', 'eigh', (['mat'], {'check_finite': '(False)'}), '(mat, check_finite=False)\n', (1599, 1624), False, 'from scipy.linalg import solve_triangular, solve, eigh, eig\n'), ((1903, 1931), 'scipy.linalg.eig', 'eig', (['mat'], {'check_finite': '(False)'}), '(mat, check_finite=False)\n', (190... |
import numpy as np
from scipy import constants
#defining the function to be integrated with
def f(x):
return (x**3)/((np.exp(x)) - 1.)
#defining the simpsons rule calculation
def simpsonsRule(f,a,b,N):
h = (b-a)/N
oddSum = 0
for k in range(1, N, 2):
oddSum += f(a+k*h)
evenSum ... | [
"numpy.exp"
] | [((128, 137), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (134, 137), True, 'import numpy as np\n')] |
'''
Classify single images (for fun)
Input:
Image of building in Dataset
Output: label
'''
import argparse
import numpy as np
from cv2 import imread
from sklearn import svm, preprocessing
from sklearn import cross_validation
from sklearn.multiclass import OneVsRestClassifier
from sklearn.discriminant_analysis import ... | [
"data_prep.steerableGaussian",
"numpy.load",
"sklearn.preprocessing.StandardScaler",
"argparse.ArgumentParser",
"numpy.resize",
"data_prep.steerableHilbert",
"cv2.imread",
"data_prep.imageMaxPool",
"numpy.append",
"numpy.array",
"sklearn.discriminant_analysis.LinearDiscriminantAnalysis",
"skle... | [((524, 551), 'numpy.load', 'np.load', (['"""class_labels.npy"""'], {}), "('class_labels.npy')\n", (531, 551), True, 'import numpy as np\n'), ((566, 588), 'numpy.load', 'np.load', (['"""dataset.npy"""'], {}), "('dataset.npy')\n", (573, 588), True, 'import numpy as np\n'), ((607, 633), 'numpy.load', 'np.load', (['"""dat... |
import keras
import pickle
import cv2
import numpy as np
import sys
'''This is to supress the tensorflow warnings. If something odd happens, remove them and try to debug form the warnings'''
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
#import tensorflow as tf
'''This is to supress the tensorflow warnings. If so... | [
"keras.models.load_model",
"cv2.dnn.readNetFromCaffe",
"cv2.putText",
"numpy.argmax",
"numpy.asarray",
"numpy.array",
"cv2.rectangle",
"cv2.resize"
] | [((1086, 1153), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (['self.proto_path', 'self.face_detection_path'], {}), '(self.proto_path, self.face_detection_path)\n', (1110, 1153), False, 'import cv2\n'), ((1176, 1216), 'keras.models.load_model', 'keras.models.load_model', (['self.model_path'], {}), '(self.mod... |
import os
import numpy as np
import periodictable
class GaussianInput:
def __init__(self, link0, routes,
atom_symbols, atom_coords,
charge=0, multiplicity=1,
title="Title Card Required", extras=None):
self.link0 = link0
self.routes = routes
... | [
"os.path.basename",
"numpy.array",
"os.path.exists",
"cclib.parser.Gaussian"
] | [((2136, 2167), 'cclib.parser.Gaussian', 'cclib.parser.Gaussian', (['logfname'], {}), '(logfname)\n', (2157, 2167), False, 'import cclib\n'), ((1811, 1828), 'numpy.array', 'np.array', (['symbols'], {}), '(symbols)\n', (1819, 1828), True, 'import numpy as np\n'), ((1830, 1846), 'numpy.array', 'np.array', (['coords'], {}... |
import torch
import numpy as np
from config import Config
class Tensor():
def __init__(self, tensor):
self.tensor = tensor
def torch_tensor_for_device(self):
tensor = self.tensor
if isinstance(tensor, torch.Tensor):
return tensor
tensor = np.asarray(tensor, dtype=n... | [
"numpy.asarray",
"torch.from_numpy"
] | [((294, 330), 'numpy.asarray', 'np.asarray', (['tensor'], {'dtype': 'np.float32'}), '(tensor, dtype=np.float32)\n', (304, 330), True, 'import numpy as np\n'), ((348, 372), 'torch.from_numpy', 'torch.from_numpy', (['tensor'], {}), '(tensor)\n', (364, 372), False, 'import torch\n')] |
"""
tanh
~~~~
Plots a graph of the tanh function."""
import numpy as np
import matplotlib.pyplot as plt
z = np.arange(-5, 5, .1)
t = np.tanh(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, t)
ax.set_ylim([-1.0, 1.0])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('tanh function')
plt.... | [
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.tanh",
"matplotlib.pyplot.show"
] | [((111, 132), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.1)'], {}), '(-5, 5, 0.1)\n', (120, 132), True, 'import numpy as np\n'), ((136, 146), 'numpy.tanh', 'np.tanh', (['z'], {}), '(z)\n', (143, 146), True, 'import numpy as np\n'), ((154, 166), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (164, 16... |
import numpy as np
from typing import List
from framework.DataObjects import MetaData, PkmFullTeam, GameStateView
from framework.DataConstants import DEFAULT_PARTY_SIZE, TYPE_CHART_MULTIPLIER, DEFAULT_PKM_N_MOVES
from framework.DataTypes import PkmStat
from framework.behaviour import BattlePolicy
from framework.beha... | [
"framework.behaviour.BattlePolicies.estimate_damage",
"numpy.argmax"
] | [((1648, 1665), 'numpy.argmax', 'np.argmax', (['damage'], {}), '(damage)\n', (1657, 1665), True, 'import numpy as np\n'), ((1508, 1628), 'framework.behaviour.BattlePolicies.estimate_damage', 'estimate_damage', (['move.type', 'my_active_type', 'move.power', 'opp_active_type', 'my_attack_stage', 'opp_defense_stage', 'wea... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# MAKE GREENWICH CENTERED AOI_MASK FOR CRU 10min RUNS THAT WE USE
# WHEN CORRECTING PRECIP VALUES THAT ARE WAAAY TOO HIGH.
#
# <NAME> (April 2018)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def shiftgrid( lon0, datain,... | [
"rasterio.open",
"shapely.geometry.Polygon",
"numpy.asarray",
"affine.Affine.translation",
"xarray.open_dataset",
"affine.Affine.scale",
"numpy.flipud",
"numpy.zeros",
"geopandas.GeoDataFrame",
"numpy.fabs",
"numpy.array",
"numpy.ma.zeros",
"numpy.ma.isMA",
"rasterio.features.rasterize",
... | [((1913, 1931), 'numpy.ma.isMA', 'np.ma.isMA', (['datain'], {}), '(datain)\n', (1923, 1931), True, 'import numpy as np\n'), ((2045, 2063), 'numpy.ma.isMA', 'np.ma.isMA', (['lonsin'], {}), '(lonsin)\n', (2055, 2063), True, 'import numpy as np\n'), ((3045, 3060), 'numpy.asarray', 'np.asarray', (['lat'], {}), '(lat)\n', (... |
#!/usr/bin/env python
"""
Verify DWT perfect reconstruction.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_, run_module_suite
import pywt
def test_perfect_reconstruction():
families = ('db', 'sym', 'coif', 'bior', 'rbio')
wavelets ... | [
"numpy.random.seed",
"numpy.testing.run_module_suite",
"pywt.idwt",
"pywt.dwt",
"numpy.testing.assert_",
"numpy.random.random",
"numpy.mean",
"pywt.wavelist"
] | [((1013, 1034), 'numpy.random.seed', 'np.random.seed', (['(12345)'], {}), '(12345)\n', (1027, 1034), True, 'import numpy as np\n'), ((1852, 1870), 'numpy.testing.run_module_suite', 'run_module_suite', ([], {}), '()\n', (1868, 1870), False, 'from numpy.testing import assert_, run_module_suite\n'), ((1407, 1437), 'pywt.d... |
import copy
import cv2
import numpy as np
import matplotlib.pyplot as plt
class BoundingBox():
def __init__(self, xmin, ymin, xmax, ymax, score=0.):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.score = score
self.asList = [self.xmin, self.... | [
"matplotlib.pyplot.title",
"numpy.maximum",
"cv2.VideoWriter_fourcc",
"numpy.ones",
"numpy.argsort",
"cv2.DescriptorMatcher_create",
"cv2.SIFT_create",
"cv2.normalize",
"cv2.rectangle",
"numpy.zeros_like",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"numpy.max",
"numpy.dstack",
"copy.dee... | [((2061, 2090), 'cv2.SIFT_create', 'cv2.SIFT_create', (['max_features'], {}), '(max_features)\n', (2076, 2090), False, 'import cv2\n'), ((2264, 2330), 'cv2.DescriptorMatcher_create', 'cv2.DescriptorMatcher_create', (['cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_L1'], {}), '(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_L1)\n', (2292, 2330),... |
"""test cost"""
import numpy as np
from neuralink.cost import Cost
from .utils import single_test
def test_compute_cost1():
np.random.seed(1)
Y = np.random.randn(1, 5) > 0
A2 = np.array([[0.5002307, 0.49985831, 0.50023963, 0.25, 0.7]])
expected_output = 0.5447066599017815
output = Cost().comput... | [
"numpy.random.seed",
"numpy.random.randn",
"numpy.asarray",
"neuralink.cost.Cost",
"numpy.isclose",
"numpy.array",
"numpy.float64"
] | [((132, 149), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (146, 149), True, 'import numpy as np\n'), ((193, 251), 'numpy.array', 'np.array', (['[[0.5002307, 0.49985831, 0.50023963, 0.25, 0.7]]'], {}), '([[0.5002307, 0.49985831, 0.50023963, 0.25, 0.7]])\n', (201, 251), True, 'import numpy as np\n'), (... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
from itertools import product
import pymc3 as pm
from src.globs import beta_std
df = pd.read_json('data/processed/processed_data_online.json')
traces = {}
for i, (touch, d) in enumerate(df.groupby('occluded_contact'))... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"pymc3.sample",
"pymc3.Model",
"pymc3.Bernoulli",
"matplotlib.pyplot.legend",
"pymc3.Normal",
"pandas.read_json",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
... | [((187, 244), 'pandas.read_json', 'pd.read_json', (['"""data/processed/processed_data_online.json"""'], {}), "('data/processed/processed_data_online.json')\n", (199, 244), True, 'import pandas as pd\n'), ((851, 865), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (863, 865), True, 'import matplotlib.py... |
import lzma
from collections import OrderedDict
from importlib.resources import open_binary
from io import StringIO
from token import NAME
from tokenize import TokenError, generate_tokens
from types import SimpleNamespace
import msgpack
import numpy as np
from ..token_map import DirtyMap, PrefixTokenMap, TokenMap
fro... | [
"lzma.open",
"io.StringIO",
"msgpack.unpack",
"numpy.array",
"collections.OrderedDict",
"types.SimpleNamespace",
"importlib.resources.open_binary"
] | [((781, 794), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (792, 794), False, 'from collections import OrderedDict\n'), ((821, 834), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (832, 834), False, 'from collections import OrderedDict\n'), ((939, 952), 'collections.OrderedDict', 'OrderedDic... |
import argparse
import cv2
import numpy as np
import torch
from albumentations.pytorch import ToTensorV2
import albumentations as Aug
from model import FaceModel
from wider_face_dataset import img_size
parser = argparse.ArgumentParser(description='add batch size')
parser.add_argument('model_path', type=str, help='the ... | [
"albumentations.pytorch.ToTensorV2",
"model.FaceModel",
"numpy.minimum",
"numpy.maximum",
"argparse.ArgumentParser",
"albumentations.Resize",
"cv2.cvtColor",
"cv2.waitKey",
"torch.load",
"cv2.imread",
"numpy.where",
"numpy.array",
"cv2.rectangle",
"albumentations.Normalize",
"cv2.imshow"... | [((212, 265), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""add batch size"""'}), "(description='add batch size')\n", (235, 265), False, 'import argparse\n'), ((2316, 2343), 'cv2.imread', 'cv2.imread', (['args.image_path'], {}), '(args.image_path)\n', (2326, 2343), False, 'import cv2\n'... |
import cv2,os,glob
import SimpleITK as sitk
import numpy as np
segs='/mnt/data9/independent_segs/lungs'
raw='/mnt/data9/independent_data'
out_path='/mnt/data9/independent_crop'
for type in os.listdir(segs):
for volume in os.listdir(os.path.join(segs,type)):
person=volume.split('_')[1]
stage = volume... | [
"numpy.stack",
"cv2.imwrite",
"SimpleITK.GetArrayFromImage",
"os.path.join",
"os.listdir"
] | [((189, 205), 'os.listdir', 'os.listdir', (['segs'], {}), '(segs)\n', (199, 205), False, 'import cv2, os, glob\n'), ((236, 260), 'os.path.join', 'os.path.join', (['segs', 'type'], {}), '(segs, type)\n', (248, 260), False, 'import cv2, os, glob\n'), ((411, 436), 'SimpleITK.GetArrayFromImage', 'sitk.GetArrayFromImage', (... |
import os
import sys
import argparse
import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
import random
import operator
import pickle as pickle
import matplotlib.pyplot as plt
np.random.seed(1)
def load_da... | [
"pandas.DataFrame",
"numpy.nanpercentile",
"numpy.random.seed",
"lightgbm.train",
"pandas.read_hdf",
"lightgbm.Dataset",
"pandas.read_pickle",
"sys.stderr.write",
"numpy.random.shuffle"
] | [((289, 306), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (303, 306), True, 'import numpy as np\n'), ((1532, 1556), 'numpy.random.shuffle', 'np.random.shuffle', (['upeps'], {}), '(upeps)\n', (1549, 1556), True, 'import numpy as np\n'), ((1939, 1986), 'lightgbm.Dataset', 'lgb.Dataset', (['train_vector... |
from pytorch_lightning.loggers import LoggerCollection
from pathlib import Path
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import pytorch_lightning as pl
import torch as tr
import torch.nn.functional as F
from torch import Tensor, nn
from torch.optim import Adam
from torch.utils.data impo... | [
"torch.sum",
"detection_utils.demo.plot.plot_confusion_matrix",
"detection_utils.boxes.generate_targets",
"torch.nn.Conv2d",
"numpy.einsum",
"detection_utils.demo.plot.draw_detections",
"torch.squeeze",
"torch.nn.BatchNorm2d",
"torch.nn.init.constant_",
"pathlib.Path",
"torch.utils.data.TensorDa... | [((1932, 1961), 'torch.squeeze', 'tr.squeeze', (['(class_targets > 0)'], {}), '(class_targets > 0)\n', (1942, 1961), True, 'import torch as tr\n'), ((2294, 2324), 'torch.squeeze', 'tr.squeeze', (['(class_targets > -1)'], {}), '(class_targets > -1)\n', (2304, 2324), True, 'import torch as tr\n'), ((2080, 2184), 'torch.n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/22 10:41
# @Author : ganliang
# @File : __init__.py.py
# @Desc : pandas测试
import numpy as np
import pandas as pd
from src.config import logger
def pd_serise():
series = pd.Series([1, 3, 5, np.nan, 6, 8])
logger.info("Series:\n{0}".forma... | [
"numpy.random.rand",
"pandas.date_range",
"pandas.Series"
] | [((249, 283), 'pandas.Series', 'pd.Series', (['[1, 3, 5, np.nan, 6, 8]'], {}), '([1, 3, 5, np.nan, 6, 8])\n', (258, 283), True, 'import pandas as pd\n'), ((372, 420), 'pandas.date_range', 'pd.date_range', (['"""2019-10-01"""'], {'periods': '(6)', 'freq': '"""D"""'}), "('2019-10-01', periods=6, freq='D')\n", (385, 420),... |
import numpy as np
import pickle
import os
import argparse
def cut_line(sentence):
sent = ''
delimiter = ['。', ';', '?', '!']
for i, c in enumerate(sentence):
sent += c
if ((c in delimiter) and (sentence[min(len(sentence)-1, i + 1)] not in ['」', '”', '’'])) or i == len(sentence)-1:
... | [
"os.path.join",
"argparse.ArgumentParser",
"numpy.random.choice"
] | [((6041, 6181), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A module for FASPell - Fast, Adaptable, Simple, Powerful Chinese Spell Checker"""', 'usage': 'usage'}), "(description=\n 'A module for FASPell - Fast, Adaptable, Simple, Powerful Chinese Spell Checker'\n , usage=usage)\... |
# Copyright 2019 DeepMind Technologies Limited.
#
# 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 agre... | [
"absl.testing.absltest.main",
"copy.deepcopy",
"six.moves.range",
"numpy.any",
"labmaze.TextGrid",
"labmaze.RandomMaze"
] | [((13332, 13347), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (13345, 13347), False, 'from absl.testing import absltest\n'), ((1325, 1381), 'labmaze.RandomMaze', 'labmaze.RandomMaze', ([], {'height': '(7)', 'width': '(9)', 'random_seed': '(12345)'}), '(height=7, width=9, random_seed=12345)\n', (134... |
'''
Multiprocessor Spatial Microbial GA
<NAME>
July, 2018
'''
import random
import time
import numpy as np
from pathos.multiprocessing import ProcessPool
_pool = None
class MicrobialSearch():
def __init__(self, evol_params): #generations, pop_size, genotype_size, recomb_prob, mutation_variance, num_processes):
... | [
"pathos.multiprocessing.ProcessPool",
"numpy.argmax",
"numpy.std",
"numpy.zeros",
"random.choice",
"time.sleep",
"random.random",
"numpy.max",
"numpy.random.random",
"numpy.mean",
"numpy.arange",
"numpy.random.normal",
"numpy.random.rand",
"numpy.add"
] | [((1861, 1895), 'numpy.random.rand', 'np.random.rand', (['self.genotype_size'], {}), '(self.genotype_size)\n', (1875, 1895), True, 'import numpy as np\n'), ((2328, 2364), 'numpy.zeros', 'np.zeros', (['self.group_size'], {'dtype': 'int'}), '(self.group_size, dtype=int)\n', (2336, 2364), True, 'import numpy as np\n'), ((... |
import numpy as np
import cv2
def get_var(img1, img2, opt_flow):
img1 = img1[0].permute(1,2,0).cpu().numpy()
img2 = img2[0].permute(1,2,0).cpu().numpy()
img1 = np.float32(img1)
img2 = np.float32(img2)
fx = cv2.Sobel(img1,ddepth=cv2.CV_32F,dx=1,dy=0,ksize=-1)
fy = cv2.Sobel(img1,ddepth=cv2.CV_3... | [
"cv2.filter2D",
"numpy.float32",
"numpy.array",
"cv2.convertScaleAbs",
"cv2.Sobel"
] | [((174, 190), 'numpy.float32', 'np.float32', (['img1'], {}), '(img1)\n', (184, 190), True, 'import numpy as np\n'), ((202, 218), 'numpy.float32', 'np.float32', (['img2'], {}), '(img2)\n', (212, 218), True, 'import numpy as np\n'), ((228, 284), 'cv2.Sobel', 'cv2.Sobel', (['img1'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', '... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import numpy as np
import pytest
from .. import TikaExtractor
def input_bytes():
with open('cats_are_awesome.pdf', 'rb') as pdf:
i_bytes = pdf.read()
return i_bytes
@pytest.mark.parametrize('uri, ... | [
"numpy.stack"
] | [((336, 394), 'numpy.stack', 'np.stack', (["['cats_are_awesome.pdf', 'cats_are_awesome.pdf']"], {}), "(['cats_are_awesome.pdf', 'cats_are_awesome.pdf'])\n", (344, 394), True, 'import numpy as np\n')] |
"""Test for kaccum.py."""
import numpy as np
from phono3py.cui.kaccum import KappaDOS, _get_mfp
from phono3py.phonon.grid import get_ir_grid_points
kappados_si = [
-0.0000002,
0.0000000,
0.0000000,
1.6966400,
2.1977566,
5.1814323,
3.3932803,
25.8022392,
15.5096766,
5.0899206,
... | [
"phono3py.phonon.grid.get_ir_grid_points",
"phono3py.cui.kaccum._get_mfp",
"phono3py.cui.kaccum.KappaDOS",
"numpy.array",
"numpy.testing.assert_equal",
"numpy.testing.assert_allclose",
"numpy.vstack"
] | [((5966, 6058), 'phono3py.cui.kaccum.KappaDOS', 'KappaDOS', (['mode_prop', 'frequencies', 'bz_grid', 'tc.grid_points'], {'frequency_points': 'freq_points'}), '(mode_prop, frequencies, bz_grid, tc.grid_points, frequency_points=\n freq_points)\n', (5974, 6058), False, 'from phono3py.cui.kaccum import KappaDOS, _get_mf... |
"""
Utilities for downloading and unpacking the SVHN dataset
"""
import os
import sys
import tarfile
from six.moves import urllib
import numpy as np
import scipy.io
URL = 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat'
def maybe_download_and_extract(data_dir, subset):
url = URL.format(subset)... | [
"os.makedirs",
"os.stat",
"os.path.exists",
"cPickle.load",
"numpy.transpose",
"numpy.random.RandomState",
"numpy.amax",
"pickle.load",
"sys.stdout.flush",
"six.moves.urllib.request.urlretrieve",
"numpy.array",
"os.path.join"
] | [((372, 404), 'os.path.join', 'os.path.join', (['data_dir', 'filename'], {}), '(data_dir, filename)\n', (384, 404), False, 'import os\n'), ((417, 441), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (431, 441), False, 'import os\n'), ((775, 827), 'six.moves.urllib.request.urlretrieve', 'urllib.... |
"""
World module.
"""
from . import polity, terrain, period, default_parameters
from .community import Community, DIRECTIONS, LittoralNeighbour
from numpy import sqrt
from numpy.random import random, permutation
import yaml
_START_YEAR = -1500
_YEARS_PER_STEP = 2
class World(object):
"""
World class, a conta... | [
"numpy.random.permutation",
"yaml.load",
"numpy.random.random",
"numpy.sqrt"
] | [((10083, 10112), 'numpy.random.permutation', 'permutation', (['self.total_tiles'], {}), '(self.total_tiles)\n', (10094, 10112), False, 'from numpy.random import random, permutation\n'), ((6526, 6567), 'yaml.load', 'yaml.load', (['infile'], {'Loader': 'yaml.FullLoader'}), '(infile, Loader=yaml.FullLoader)\n', (6535, 65... |
'''
Calculates the next time step for the state of the nodes
'''
import numpy as np
from sys import exit
'''
The state attribute in every node defines the last state of the node. At the dictionary activityTimeLine we have the
evolution of the values for the state over time.
'''
def states_update(g, t, delta = 0.2):... | [
"numpy.asscalar",
"numpy.exp",
"sys.exit"
] | [((4624, 4649), 'numpy.asscalar', 'np.asscalar', (['new_activity'], {}), '(new_activity)\n', (4635, 4649), True, 'import numpy as np\n'), ((4990, 5024), 'numpy.asscalar', 'np.asscalar', (["g.node[vrtx]['state']"], {}), "(g.node[vrtx]['state'])\n", (5001, 5024), True, 'import numpy as np\n'), ((2125, 2132), 'sys.exit', ... |
# Copyright (c) 2015-2018 by the parties listed in the AUTHORS
# file. All rights reserved. Use of this source code is governed
# by a BSD-style license that can be found in the LICENSE file.
from toast_planck.reproc_modules.destriping import Destriper
from toast.mpi import MPI
from toast.tests.mpi import MPITestCa... | [
"toast_planck.reproc_modules.destriping.Destriper",
"numpy.random.randn",
"numpy.ones",
"numpy.hstack",
"numpy.arange"
] | [((522, 586), 'toast_planck.reproc_modules.destriping.Destriper', 'Destriper', (['self.npix', 'MPI.COMM_WORLD'], {'cglimit': '(1e-10)', 'itermax': '(100)'}), '(self.npix, MPI.COMM_WORLD, cglimit=1e-10, itermax=100)\n', (531, 586), False, 'from toast_planck.reproc_modules.destriping import Destriper\n'), ((2103, 2131), ... |
# coding=utf-8
# Copyright 2021 The init2winit Authors.
#
# 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 la... | [
"absl.testing.absltest.main",
"init2winit.utils.TrainingMetricsGrabber.create",
"flax.optim.GradientDescent",
"numpy.ones",
"numpy.zeros",
"tempfile.mkdtemp",
"shutil.rmtree",
"flax.nn.Model"
] | [((2421, 2436), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (2434, 2436), False, 'from absl.testing import absltest\n'), ((1084, 1102), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1100, 1102), False, 'import tempfile\n'), ((1130, 1158), 'shutil.rmtree', 'shutil.rmtree', (['self.test_... |
import pytest
import tensorflow as tf
from edflow.nn import tf_nn as nn
def test_int_shape():
tf.enable_eager_execution()
a = tf.ones((1, 2, 3, 4))
a_shape = nn.int_shape(a)
assert type(a_shape) is list
def test_partwise_conv2d():
from matplotlib import pyplot as plt
from skimage import dat... | [
"numpy.sum",
"edflow.nn.tf_nn.probs_to_mu_sigma",
"skimage.data.astronaut",
"tensorflow.reshape",
"numpy.allclose",
"edflow.nn.tf_nn.conv2d",
"tensorflow.contrib.distributions.MultivariateNormalTriL",
"tensorflow.cholesky",
"tensorflow.nn.softmax",
"numpy.zeros_like",
"edflow.nn.tf_nn.np_mask2rg... | [((101, 128), 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), '()\n', (126, 128), True, 'import tensorflow as tf\n'), ((137, 158), 'tensorflow.ones', 'tf.ones', (['(1, 2, 3, 4)'], {}), '((1, 2, 3, 4))\n', (144, 158), True, 'import tensorflow as tf\n'), ((173, 188), 'edflow.nn.tf_nn.int_shape... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import numpy as np
from pathlib import Path
from utils_cv.common.image import (
im_width,
im_height,
im_width_height,
im2base64,
ims2strlist,
)
def test_im_width(tiny_ic_data_path):
im_path... | [
"utils_cv.common.image.im_width",
"numpy.zeros",
"utils_cv.common.image.im2base64",
"pathlib.Path",
"utils_cv.common.image.im_width_height",
"utils_cv.common.image.im_height",
"utils_cv.common.image.ims2strlist",
"os.path.join"
] | [((495, 514), 'numpy.zeros', 'np.zeros', (['(100, 50)'], {}), '((100, 50))\n', (503, 514), True, 'import numpy as np\n'), ((842, 861), 'numpy.zeros', 'np.zeros', (['(100, 50)'], {}), '((100, 50))\n', (850, 861), True, 'import numpy as np\n'), ((1087, 1111), 'utils_cv.common.image.im_width_height', 'im_width_height', ([... |
import tkinter as tk
from tkinter import filedialog, simpledialog
import re
import numpy as np
from astropy.io import fits
from PIL import Image, ImageTk
from dataanalyzer import DataAnalyzer
from datasample import DataSample
import util
class App:
def __init__(self, **kwargs):
self.args = kwargs
... | [
"tkinter.StringVar",
"tkinter.filedialog.asksaveasfilename",
"numpy.abs",
"numpy.floor",
"numpy.rot90",
"tkinter.Frame",
"tkinter.Label",
"numpy.savetxt",
"numpy.genfromtxt",
"tkinter.filedialog.askopenfilename",
"tkinter.simpledialog.askfloat",
"numpy.max",
"re.search",
"tkinter.Tk",
"u... | [((335, 342), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (340, 342), True, 'import tkinter as tk\n'), ((414, 432), 'dataanalyzer.DataAnalyzer', 'DataAnalyzer', (['self'], {}), '(self)\n', (426, 432), False, 'from dataanalyzer import DataAnalyzer\n'), ((879, 934), 'util.detect_stars', 'util.detect_stars', (['self.working_... |
# -*- coding: utf-8 -*-
"""Orbit SkyOffset Frames.
Like `~astropy.coordinates.Galactocentric` needs ``galcen_coord`` and other
information to convert to/from heliocentric or geocentric coordinate systems,
the `OrbitPseudoFrame` needs information about the orbit (phase-space position
and integration time) and the pote... | [
"astropy.coordinates.attributes.QuantityAttribute",
"astropy.coordinates.representation.SphericalRepresentation",
"astropy.coordinates.match_coordinates_sky",
"astropy.units.Quantity",
"numpy.abs",
"astropy.coordinates.attributes.CoordinateAttribute",
"numpy.sign",
"astropy.coordinates.frame_transform... | [((6490, 6613), 'astropy.coordinates.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionWithKwargTransform', 'framecls', '_OrbitSkyOffsetFramecls'], {'func_kwargs': 'track_fn_kw'}), '(FunctionWithKwargTransform, framecls,\n _OrbitSkyOffsetFramecls, func_kwargs=track_fn_kw)\n', (6521, 661... |
# Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# 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 ... | [
"numpy.random.seed",
"numpy.sum",
"numpy.argmax",
"docqa.data_processing.text_utils.NltkAndPunctTokenizer",
"numpy.zeros",
"cape_document_qa.cape_docqa_machine_reader.get_production_model_config",
"numpy.min",
"numpy.random.random",
"numpy.random.randint",
"cape_document_qa.cape_docqa_machine_read... | [((3102, 3131), 'cape_document_qa.cape_docqa_machine_reader.get_production_model_config', 'get_production_model_config', ([], {}), '()\n', (3129, 3131), False, 'from cape_document_qa.cape_docqa_machine_reader import get_production_model_config, CapeDocQAMachineReaderModel\n'), ((3153, 3186), 'cape_document_qa.cape_docq... |
# (C) British Crown Copyright 2013 - 2018, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... | [
"cartopy.crs.OSNI",
"cartopy.crs.TransverseMercator",
"numpy.isnan",
"cartopy.crs.OSGB",
"cartopy.crs.Globe",
"cartopy.crs.PlateCarree",
"numpy.testing.assert_array_almost_equal"
] | [((1098, 1116), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (1114, 1116), True, 'import cartopy.crs as ccrs\n'), ((1161, 1186), 'cartopy.crs.TransverseMercator', 'ccrs.TransverseMercator', ([], {}), '()\n', (1184, 1186), True, 'import cartopy.crs as ccrs\n'), ((1267, 1346), 'numpy.testing.assert_ar... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import pylab as pl
fig = pl.figure(figsize=(5, 4), dpi=72)
axes = fig.add_axes([0.01, 0.01, .98, 0.98])
X = np.linspace(0, 2, 200, endpoint=True)
Y = np.sin(2*np.pi*X)
pl.plot(X, Y, lw=2)
pl.ylim(-1.1, 1.1)
pl.grid()
pl.show()
| [
"pylab.show",
"pylab.grid",
"numpy.sin",
"matplotlib.use",
"pylab.figure",
"numpy.linspace",
"pylab.ylim",
"pylab.plot"
] | [((37, 58), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (51, 58), False, 'import matplotlib\n'), ((85, 118), 'pylab.figure', 'pl.figure', ([], {'figsize': '(5, 4)', 'dpi': '(72)'}), '(figsize=(5, 4), dpi=72)\n', (94, 118), True, 'import pylab as pl\n'), ((168, 205), 'numpy.linspace', 'np.linsp... |
def test_peakfind():
import bardensr
import numpy as np
import numpy.random as npr
A=np.zeros((5,6,7,3))
A[1,2,3,0]=1
A[2,3,4,1]=1.5
A[3,4,5,2]=.001
df=bardensr.spot_calling.find_peaks(A,.5)
assert len(df)==2
assert np.sum(df['j']==2)==0
def test_singleshot():
import bar... | [
"pandas.DataFrame",
"numpy.random.seed",
"numpy.sum",
"numpy.random.randn",
"scipy.ndimage.gaussian_filter",
"numpy.zeros",
"numpy.einsum",
"bardensr.spot_calling.find_peaks",
"numpy.random.randint",
"numpy.random.rand",
"bardensr.spot_calling.estimate_density_singleshot",
"bardensr.benchmarks... | [((103, 125), 'numpy.zeros', 'np.zeros', (['(5, 6, 7, 3)'], {}), '((5, 6, 7, 3))\n', (111, 125), True, 'import numpy as np\n'), ((188, 228), 'bardensr.spot_calling.find_peaks', 'bardensr.spot_calling.find_peaks', (['A', '(0.5)'], {}), '(A, 0.5)\n', (220, 228), False, 'import bardensr\n'), ((552, 563), 'numpy.random.see... |
# -*- coding: utf-8 -*-
"""
@license: MIT
@author: t.okuda
"""
import os
import requests
import random
import math
from pathlib import Path
from glob import glob
from tqdm import tqdm
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.data.experimental i... | [
"tensorflow.keras.layers.Dense",
"random.shuffle",
"os.path.isfile",
"numpy.random.randint",
"pathlib.Path",
"tfaug.TfrecordConverter",
"tensorflow.keras.Sequential",
"glob.glob",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.layers... | [((543, 572), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)', '(10)'], {}), '(0, 255, 10)\n', (560, 572), True, 'import numpy as np\n'), ((982, 1047), 'tensorflow.keras.applications.MobileNetV2', 'tf.keras.applications.MobileNetV2', ([], {'include_top': '(True)', 'weights': 'None'}), '(include_top=True, ... |
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
import os
from data.loaddata import get_loader
from models.model import Generator, NLayerDiscriminator
from models.MSSSIM import ssim, msssim
from models.perceptual import PNet
from models.inceptionv3 im... | [
"argparse.ArgumentParser",
"utils.checkpath",
"data.loaddata.get_loader",
"torch.load",
"models.inceptionv3.InceptionV3",
"models.MSSSIM.ssim",
"models.perceptual.PNet",
"torch.cuda.is_available",
"utils.compute_fid_score",
"models.model.Generator",
"torch.no_grad",
"utils.save_singleimages",
... | [((642, 752), 'data.loaddata.get_loader', 'get_loader', (['args'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': 'args.num_workers', 'training': '(False)'}), '(args, batch_size=args.batch_size, shuffle=False, num_workers=\n args.num_workers, training=False)\n', (652, 752), False, 'from data.... |
# -*- coding: utf-8 -*-
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | [
"prody.utilities.which",
"numpy.zeros",
"pdbfile.parsePDB",
"wwpdbftp.fetchPDB"
] | [((2040, 2055), 'prody.utilities.which', 'which', (['"""stride"""'], {}), "('stride')\n", (2045, 2055), False, 'from prody.utilities import gunzip, which, PLATFORM\n'), ((4111, 4133), 'numpy.zeros', 'np.zeros', (['n_atoms', 'int'], {}), '(n_atoms, int)\n', (4119, 4133), True, 'import numpy as np\n'), ((4145, 4169), 'nu... |
from numpy import sum
from gwlfe.Input.LandUse.NLU import NLU
from gwlfe.Memoization import memoize
@memoize
def AreaTotal(NRur, NUrb, Area):
result = 0
nlu = NLU(NRur, NUrb)
for l in range(NRur):
result += Area[l]
for l in range(NRur, nlu):
result += Area[l]
return result
@memo... | [
"gwlfe.Input.LandUse.NLU.NLU",
"numpy.sum"
] | [((170, 185), 'gwlfe.Input.LandUse.NLU.NLU', 'NLU', (['NRur', 'NUrb'], {}), '(NRur, NUrb)\n', (173, 185), False, 'from gwlfe.Input.LandUse.NLU import NLU\n'), ((358, 367), 'numpy.sum', 'sum', (['Area'], {}), '(Area)\n', (361, 367), False, 'from numpy import sum\n')] |
#!/usr/bin/env python
import numpy as np
import math
from scipy.spatial import KDTree
import rospy
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import Int32
from styx_msgs.msg import Lane, Waypoint
LOOKAHEAD_WPS = 200 # Number of waypoints we will publish.
MAX_DECEL = 0.5 # m/s^2 Max Deceleration
HZ_S... | [
"rospy.logerr",
"rospy.Subscriber",
"math.sqrt",
"styx_msgs.msg.Lane",
"rospy.Publisher",
"rospy.Rate",
"rospy.is_shutdown",
"numpy.array",
"rospy.init_node",
"scipy.spatial.KDTree",
"numpy.dot",
"styx_msgs.msg.Waypoint"
] | [((528, 563), 'rospy.init_node', 'rospy.init_node', (['"""waypoint_updater"""'], {}), "('waypoint_updater')\n", (543, 563), False, 'import rospy\n'), ((1062, 1122), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/current_pose"""', 'PoseStamped', 'self.pose_cb'], {}), "('/current_pose', PoseStamped, self.pose_cb)\n", (10... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# 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/LICE... | [
"parsing.parse_dicom_file",
"matplotlib.pyplot.title",
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"glob.glob",
"matplotlib.pyplot.imshow",
"re.findall",
"configparser.ConfigParser",
"os.access",
"h5py.File",
"matplotlib.... | [((1891, 1905), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1903, 1905), False, 'from configparser import ConfigParser\n'), ((2736, 2808), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process the DICOM files and masks"""'}), "(description='Process the DICOM files an... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 17 13:23:53 2018
@author: bartosz
"""
import numpy as np
import matplotlib.pyplot as plt
#Radial distribution functions.
# This script assumes correctly generated xyz files
infilename = 'mixture7norm with numMolecules 343 time 100000 fs dt 2 fs b... | [
"numpy.nan_to_num",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.histogram",
"numpy.linalg.norm",
"numpy.linspace",
"numpy.delete"
] | [((817, 833), 'numpy.zeros', 'np.zeros', (['(n, 3)'], {}), '((n, 3))\n', (825, 833), True, 'import numpy as np\n'), ((1272, 1304), 'numpy.delete', 'np.delete', (['q', 'indicesToDelete', '(0)'], {}), '(q, indicesToDelete, 0)\n', (1281, 1304), True, 'import numpy as np\n'), ((1380, 1412), 'numpy.delete', 'np.delete', (['... |
# encoding: utf-8
"""
metrics.py
~~~~~~~~~~
Functionality for computing performance metrics. Typically custom metrics not provided by sklearn.
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__created__ = "2018-05-30"
__copyright__ = "Copyright 2018 <NAME>"
__license__ = "MIT https://opensource.org/licenses/MIT"
# s... | [
"numpy.sum",
"numpy.all"
] | [((801, 833), 'numpy.all', 'np.all', (['(Y_true == Y_pred)'], {'axis': '(1)'}), '(Y_true == Y_pred, axis=1)\n', (807, 833), True, 'import numpy as np\n'), ((845, 860), 'numpy.sum', 'np.sum', (['matches'], {}), '(matches)\n', (851, 860), True, 'import numpy as np\n'), ((1288, 1312), 'numpy.sum', 'np.sum', (['(Y_pred & ~... |
import numpy as np
from scipy.stats import norm
S0 = 10
K = 9.3
r = 0.025
s = 0.3
T = 1
def calc_d1(St, K, r, s, T, t=0, q=0):
return (np.log(St / K) + (r - q + 0.5 * s ** 2) * (T - t)) \
/ (s * np.sqrt(T - t))
def calc_d2(d1, s, T, t=0):
return d1 - s * np.sqrt(T - t)
def price_call_option(S0,... | [
"scipy.stats.norm.cdf",
"numpy.log",
"numpy.exp",
"numpy.sqrt"
] | [((466, 478), 'scipy.stats.norm.cdf', 'norm.cdf', (['d1'], {}), '(d1)\n', (474, 478), False, 'from scipy.stats import norm\n'), ((502, 514), 'scipy.stats.norm.cdf', 'norm.cdf', (['d2'], {}), '(d2)\n', (510, 514), False, 'from scipy.stats import norm\n'), ((538, 552), 'numpy.exp', 'np.exp', (['(-r * T)'], {}), '(-r * T)... |
#!/usr/bin/env python
"""
Testing Laplacian discretization
@author <NAME>
"""
import sys
import unittest
from mpi4py import MPI
import numpy
from pnumpy import CubeDecomp
from pnumpy import Laplacian
class TestLaplacian(unittest.TestCase):
def setUp(self):
# number of procs
self.sz = MPI.COMM_WORLD.Get_si... | [
"mpi4py.MPI.Finalize",
"numpy.sum",
"unittest.TextTestRunner",
"mpi4py.MPI.COMM_WORLD.Get_rank",
"numpy.zeros",
"pnumpy.CubeDecomp",
"numpy.ones",
"mpi4py.MPI.COMM_WORLD.gather",
"pnumpy.Laplacian",
"unittest.TestLoader",
"numpy.arange",
"sys.exit",
"mpi4py.MPI.COMM_WORLD.Get_size"
] | [((8249, 8263), 'mpi4py.MPI.Finalize', 'MPI.Finalize', ([], {}), '()\n', (8261, 8263), False, 'from mpi4py import MPI\n'), ((299, 324), 'mpi4py.MPI.COMM_WORLD.Get_size', 'MPI.COMM_WORLD.Get_size', ([], {}), '()\n', (322, 324), False, 'from mpi4py import MPI\n'), ((354, 379), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_... |
import numpy as np
import pandas as pd
import os
import argparse
current_path = os.path.abspath('.')
# For four ours data, run on macbook
# name = '18-64'
# name = '2-5'
# name = '2-8'
name = 'T4857'
# filename = '/Users/wangjue/Documents/results_scGNNsp/16_data_benchmark/'+name+'_benchmark.csv'
filename = '/ocean/pro... | [
"pandas.read_csv",
"os.path.abspath",
"numpy.array"
] | [((80, 100), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (95, 100), False, 'import os\n'), ((516, 537), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (527, 537), True, 'import pandas as pd\n'), ((943, 964), 'numpy.array', 'np.array', (['coords_list'], {}), '(coords_list)\... |
import torch
import numpy as np
""" 1. PyTorch Introduction
PyTorch is developed by Facebook AI Research (FAIR). PyTorch is one of the most widely used open-source machine
learning libraries for deep learning applications. It was first introduced in 2016. Since then, PyTorch has been
gaining popularity among researche... | [
"torch.ones_like",
"torch.ones",
"torch.cat",
"numpy.ones",
"torch.mul",
"torch.rand_like",
"numpy.array",
"torch.cuda.is_available",
"torch.rand",
"torch.zeros",
"numpy.add",
"torch.matmul",
"torch.tensor",
"torch.from_numpy"
] | [((1880, 1898), 'torch.tensor', 'torch.tensor', (['data'], {}), '(data)\n', (1892, 1898), False, 'import torch\n'), ((2008, 2022), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2016, 2022), True, 'import numpy as np\n'), ((2044, 2070), 'torch.from_numpy', 'torch.from_numpy', (['np_array'], {}), '(np_array)\n'... |
from __future__ import absolute_import, division, print_function
from builtins import (open, str, range,
object)
from bokeh.layouts import row, widgetbox, gridplot
from bokeh.models import CustomJS, Slider, HoverTool, ColorBar, LinearColorMapper, LabelSet, ColumnDataSource,Whisker
from bokeh.... | [
"bokeh.plotting.figure",
"matplotlib.pylab.figure",
"numpy.fabs",
"bokeh.models.HoverTool",
"bokeh.embed.components",
"bokeh.layouts.row"
] | [((506, 532), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (516, 532), True, 'from matplotlib import pylab as plt\n'), ((3073, 3119), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': "[('x', '$x'), ('y', '$y')]"}), "(tooltips=[('x', '$x'), ('y', '$y')])\n", (3082, ... |
import numpy as np
from pytest import approx
from mne_phase.utils import rayleigh_test
def test_basic():
input = np.array([0.02058449, 0.96990985, 0.83244264, 0.21233911])
EXPECTED = 0.02172542636470802
assert rayleigh_test(input) == approx(EXPECTED)
| [
"pytest.approx",
"numpy.array",
"mne_phase.utils.rayleigh_test"
] | [((120, 178), 'numpy.array', 'np.array', (['[0.02058449, 0.96990985, 0.83244264, 0.21233911]'], {}), '([0.02058449, 0.96990985, 0.83244264, 0.21233911])\n', (128, 178), True, 'import numpy as np\n'), ((225, 245), 'mne_phase.utils.rayleigh_test', 'rayleigh_test', (['input'], {}), '(input)\n', (238, 245), False, 'from mn... |
import numpy as np
import astropy.units as au
def evolution_timescale_scattering_rate(rho_s, v_rms, cross_section, rescale=1.):
"""
Evaluates the timescale for the evolution of SIDM profiles using the scattering rate
average proportional to
<sigma(v) v>
given by Equation 4 in this paper https://... | [
"numpy.sqrt"
] | [((1713, 1753), 'numpy.sqrt', 'np.sqrt', (['(4 * np.pi * G * rho_s * rs ** 2)'], {}), '(4 * np.pi * G * rho_s * rs ** 2)\n', (1720, 1753), True, 'import numpy as np\n'), ((1689, 1703), 'numpy.sqrt', 'np.sqrt', (['np.pi'], {}), '(np.pi)\n', (1696, 1703), True, 'import numpy as np\n')] |
# An annotation is a coordinate in a 4D array. Worldlines are lists of
# annotations.
#
# author: <EMAIL>
import base64
import colorsys
from dataclasses import dataclass, asdict, field
from functools import lru_cache, reduce
import json
from pathlib import Path
import uuid
from typing import Tuple, Optional
import h5... | [
"numpy.uint32",
"pandas.DataFrame",
"h5py.File",
"json.load",
"numpy.random.rand",
"numpy.float32",
"numpy.dtype",
"pathlib.Path",
"uuid.uuid1",
"colorsys.hls_to_rgb",
"numpy.string_",
"numpy.squeeze",
"functools.lru_cache",
"dataclasses.asdict",
"numpy.unique"
] | [((633, 647), 'numpy.dtype', 'np.dtype', (['"""S4"""'], {}), "('S4')\n", (641, 647), True, 'import numpy as np\n'), ((654, 668), 'numpy.dtype', 'np.dtype', (['"""S7"""'], {}), "('S7')\n", (662, 668), True, 'import numpy as np\n'), ((4569, 4580), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (4578, 4580), False,... |
from os import name
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, MaxPool2D, Input, Concatenate, Reshape, Activation
import numpy as np
from tensorflow.python.keras.backend import shape
from utils.ssd_utils import get_pred_4, get_pred... | [
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.Model",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.keras.layers.Input",
"numpy.linspace",
"utils.ssd_utils.get_pred_4",
"utils.ssd_utils.get_pred_6"
] | [((431, 457), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '[300, 300, 3]'}), '(shape=[300, 300, 3])\n', (436, 457), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Input, Concatenate, Reshape, Activation\n'), ((471, 495), 'numpy.linspace', 'np.linspace', (['(0.2)', '(0.9)', '(6)'], {}), '(0.... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2022, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | [
"pandas.DataFrame",
"numpy.isnan",
"pandas.Index",
"skbio.util.assert_ordination_results_equal",
"numpy.array",
"pandas.Series",
"skbio.OrdinationResults",
"q2_diversity.procrustes_analysis"
] | [((715, 809), 'numpy.array', 'np.array', (['[[0, 3, 4, 4, 0, 0], [1, 2, 1, 4, 3, 3], [2, 3, 1, 0, 0, 1], [0, 3, 2, 4, 3, 0]\n ]'], {}), '([[0, 3, 4, 4, 0, 0], [1, 2, 1, 4, 3, 3], [2, 3, 1, 0, 0, 1], [0, 3,\n 2, 4, 3, 0]])\n', (723, 809), True, 'import numpy as np\n'), ((922, 979), 'pandas.Series', 'pd.Series', ([... |
import numpy as np
from tensortools import ssd, logging
from tensortools import utils
from tensortools import testing
logger = logging.get_logger(__name__)
def test_generate_anchors(random_annotations):
annotations = np.reshape(random_annotations, [-1, 4])
annotations = annotations / ([1600, 640] * 2)
a... | [
"numpy.stack",
"tensortools.utils.avg_iou",
"tensortools.ssd.generate_anchors",
"numpy.reshape",
"tensortools.logging.get_logger"
] | [((129, 157), 'tensortools.logging.get_logger', 'logging.get_logger', (['__name__'], {}), '(__name__)\n', (147, 157), False, 'from tensortools import ssd, logging\n'), ((225, 264), 'numpy.reshape', 'np.reshape', (['random_annotations', '[-1, 4]'], {}), '(random_annotations, [-1, 4])\n', (235, 264), True, 'import numpy ... |
import numpy as np
import matplotlib.pyplot as plot
from matplotlib.colors import ListedColormap, BoundaryNorm
def image_grid(image_arrays, ncols=1, nrows=1, figsize=(10,10), cmap='Greys_r', norm=None):
"""
Shows a list of 2D images in a grid like fashion. If no row or columns numbers are given, all images are... | [
"numpy.squeeze",
"matplotlib.colors.ListedColormap",
"matplotlib.pyplot.subplots"
] | [((3631, 3670), 'matplotlib.colors.ListedColormap', 'ListedColormap', (['cmaplist', '"""qualitative"""'], {}), "(cmaplist, 'qualitative')\n", (3645, 3670), False, 'from matplotlib.colors import ListedColormap, BoundaryNorm\n'), ((1020, 1068), 'matplotlib.pyplot.subplots', 'plot.subplots', ([], {'nrows': '(1)', 'ncols':... |
from abc import abstractmethod, abstractproperty
from typing import List, Tuple, Union
import numpy as np
from quara.objects.qoperation import QOperation
from quara.objects.qoperations import SetQOperations
from quara.protocol.qtomography.qtomography import QTomography
from quara.qcircuit.experiment import Ex... | [
"numpy.stack",
"quara.utils.matrix_util.calc_covariance_mat",
"quara.utils.matrix_util.truncate_and_normalize",
"quara.utils.matrix_util.calc_direct_sum",
"numpy.linalg.matrix_rank",
"numpy.array",
"numpy.linalg.inv",
"quara.utils.matrix_util.calc_fisher_matrix",
"numpy.vstack"
] | [((2631, 2660), 'numpy.array', 'np.array', (['l'], {'dtype': 'np.float64'}), '(l, dtype=np.float64)\n', (2639, 2660), True, 'import numpy as np\n'), ((3736, 3748), 'numpy.stack', 'np.stack', (['ll'], {}), '(ll)\n', (3744, 3748), True, 'import numpy as np\n'), ((4114, 4138), 'numpy.vstack', 'np.vstack', (['sorted_values... |
import time
import numpy as np
import pytest
from aesara.compile.function import function
from aesara.compile.io import In
from aesara.compile.mode import Mode, get_mode
from aesara.compile.sharedvalue import shared
from aesara.configdefaults import config
from aesara.graph.basic import Apply
from aesara.graph.fg imp... | [
"aesara.tensor.type.vector",
"pytest.mark.skipif",
"aesara.configdefaults.config.change_flags",
"aesara.ifelse.ifelse",
"aesara.tensor.type.scalars",
"aesara.compile.mode.Mode",
"aesara.compile.function.function",
"pytest.raises",
"aesara.tensor.type.lscalar",
"numpy.asarray",
"aesara.tensor.typ... | [((2632, 2730), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not config.cxx)'], {'reason': '"""G++ not available, so we need to skip this test."""'}), "(not config.cxx, reason=\n 'G++ not available, so we need to skip this test.')\n", (2650, 2730), False, 'import pytest\n'), ((9261, 9359), 'pytest.mark.skipif', '... |
# https://github.com/akirbaes/Pixel-Font/blob/master/font_to_data.py
import io
from PIL import Image
from os import path
import json
import numpy as np
""" This file contains function to create font usable by font_manager.py
INPUT: filename of the characters list
there must exist a FILENAME.png image and a FILENAME.t... | [
"numpy.empty",
"os.path.dirname",
"numpy.zeros",
"json.dumps",
"PIL.Image.open",
"io.open",
"PIL.Image.fromarray",
"os.path.join",
"numpy.concatenate"
] | [((5786, 5845), 'json.dumps', 'json.dumps', (['char_pos_size'], {'indent': '(4)', 'separators': "(',', ': ')"}), "(char_pos_size, indent=4, separators=(',', ': '))\n", (5796, 5845), False, 'import json\n'), ((6362, 6423), 'numpy.empty', 'np.empty', (['(0, char_height * (nb_line + 1), 3)'], {'dtype': 'np.uint8'}), '((0,... |
"""
Generates instances for unit tests.
"""
import numpy as np
from itertools import product
import os.path
from abcvoting import generate
from operator import itemgetter
from abcvoting import abcrules
from abcvoting import fileio
def generate_abc_yaml_testinstances(
batchname,
committeesizes,
num_voters... | [
"abcvoting.abcrules.Rule",
"abcvoting.abcrules.compute",
"numpy.random.default_rng",
"abcvoting.fileio.write_abcvoting_instance_to_yaml_file",
"itertools.product",
"operator.itemgetter",
"abcvoting.generate.random_profile"
] | [((418, 449), 'numpy.random.default_rng', 'np.random.default_rng', (['(24121838)'], {}), '(24121838)\n', (439, 449), True, 'import numpy as np\n'), ((565, 644), 'itertools.product', 'product', (['committeesizes', 'num_voters_values', 'num_cand_values', 'prob_distributions'], {}), '(committeesizes, num_voters_values, nu... |
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
from .petroequations import vshale_gr, vshale_dn, phi_rho, phie, sw, perm, flow_capacity, phia, sw_pnn
def petrophysics(logs,dfrom,dto,
vshale_gr_kw=None,
vshale_dn_kw=None,
phi_rho_k... | [
"numpy.diff"
] | [((8390, 8409), 'numpy.diff', 'np.diff', (['logf.index'], {}), '(logf.index)\n', (8397, 8409), True, 'import numpy as np\n')] |
# Copyright (C) 2021 <NAME>, <NAME>, and Politecnico di Milano. All rights reserved.
# Licensed under the Apache 2.0 License.
from scipy.optimize import root_scalar
import numpy as np
import matplotlib.pyplot as plt
from ..dataset.regression import ActionDist
def estimate_lambda(weights, n, delta, alpha=2, return_in... | [
"numpy.sum",
"numpy.log",
"numpy.power",
"scipy.optimize.root_scalar",
"numpy.clip",
"numpy.mean",
"numpy.exp",
"numpy.sqrt"
] | [((1013, 1051), 'scipy.optimize.root_scalar', 'root_scalar', (['f'], {'x0': 'guess1', 'fprime': '(True)'}), '(f, x0=guess1, fprime=True)\n', (1024, 1051), False, 'from scipy.optimize import root_scalar\n'), ((2344, 2361), 'numpy.log', 'np.log', (['(1 / delta)'], {}), '(1 / delta)\n', (2350, 2361), True, 'import numpy a... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from keras.layers.pooling import MaxPooling2D
from keras.models import Sequential, Model
from keras.callbacks import EarlyStopping, Callback
from ... | [
"keras.layers.Activation",
"keras.layers.Dropout",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"keras.layers.GlobalAveragePooling2D",
"cv2.imread",
"keras.utils.np_utils.to_categorical",
"keras.layers.convolutional.Conv2D",
"keras.layers.Dense",
"glob.glob",
"keras.models.Sequential",
"skl... | [((1514, 1620), 'glob.glob', 'glob.glob', (['"""C:/Users/anant/Desktop/pothole-and-plain-rode-images/My Dataset/train/Pothole/*.jpg"""'], {}), "(\n 'C:/Users/anant/Desktop/pothole-and-plain-rode-images/My Dataset/train/Pothole/*.jpg'\n )\n", (1523, 1620), False, 'import time, cv2, glob\n'), ((2009, 2027), 'numpy.... |
#!/usr/bin/python3
'''
Background Reading to understand this tool ----
Paper: Portfolio Selection - <NAME> 1952 URL:
https://www.math.ust.hk/~maykwok/courses/ma362/07F/markowitz_JF.pdf
https://www.investopedia.com/terms/e/efficientfrontier.asp
https://en.wikipedia.org/wiki/Efficient_frontier
https://en.wikipedia... | [
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.sum",
"pandas_datareader.data.DataReader",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((1885, 1899), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1897, 1899), True, 'import pandas as pd\n'), ((2259, 2317), 'matplotlib.pyplot.title', 'plt.title', (['"""Comparing Apple with Ford - Normalised to 100"""'], {}), "('Comparing Apple with Ford - Normalised to 100')\n", (2268, 2317), True, 'import mat... |
import streamlit as st
import numpy as np
import pandas as pd
import json
import pickle
import reference_book as rb
def main():
model = load_data()
st.title('Questionario - Open Sex Role Inventory')
st.text(
"""
Olá, bem vindo!
Este questionario foi baseado em u... | [
"streamlit.slider",
"streamlit.title",
"streamlit.sidebar.title",
"streamlit.text",
"pickle.load",
"numpy.array",
"streamlit.sidebar.button"
] | [((157, 207), 'streamlit.title', 'st.title', (['"""Questionario - Open Sex Role Inventory"""'], {}), "('Questionario - Open Sex Role Inventory')\n", (165, 207), True, 'import streamlit as st\n'), ((212, 1922), 'streamlit.text', 'st.text', (['"""\n Olá, bem vindo!\n \n Este questionario ... |
from itertools import product
from pyshocks import get_logger
from pyshocks.burgers import WENOJS32, WENOJS53
import jax
import jax.numpy as jnp
import jax.numpy.linalg as jla
import pytest
logger = get_logger("test_weno")
# {{{ test_weno_smoothness_indicator_vectorization
@pytest.mark.parametrize(
"scheme"... | [
"pyshocks.Quadrature",
"pyshocks.weno._weno_js_smoothness",
"pytest.main",
"matplotlib.pyplot.figure",
"pytest.mark.parametrize",
"pyshocks.get_logger",
"jax.device_put",
"matplotlib.pyplot.close",
"jax.numpy.linspace",
"pyshocks.burgers.WENOJS32",
"jax.numpy.linalg.norm",
"pyweno.weno.reconst... | [((203, 226), 'pyshocks.get_logger', 'get_logger', (['"""test_weno"""'], {}), "('test_weno')\n", (213, 226), False, 'from pyshocks import get_logger\n'), ((2288, 2339), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""is_smooth"""', '[True, False]'], {}), "('is_smooth', [True, False])\n", (2311, 2339), False... |
"""Capacited Vehicles Routing Problem (CVRP) using an Ant Colony Algorithm (ACO)."""
from __future__ import print_function
import random
import numpy as np
from H_Hy_Men import VRPLibReader
Q = 1
RHO = 0.2
nk = {5: [32, 33, 34, 36, 37, 38, 39], 6: [33, 37, 39, 45], 7: [45, 46, 48, 53, 54], 9: [55, 61, 65]}
def g... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"networkx.draw_networkx_edges",
"matplotlib.pyplot.plot",
"numpy.multiply",
"random.uniform",
"numpy.subtract",
"matplotlib.pyplot.axis",
"random.random",
"networkx.Graph",
"networkx.draw_networkx_nodes",
"networkx.draw_networkx_labels",
"... | [((8135, 8160), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'ys'], {'c': '"""red"""'}), "(xs, ys, c='red')\n", (8143, 8160), True, 'import matplotlib.pyplot as plt\n'), ((8165, 8183), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""beta"""'], {}), "('beta')\n", (8175, 8183), True, 'import matplotlib.pyplot as plt\n')... |
# This script output to-eng-distance and number of training data
# statistics for each language in UD treebank, according to uriel,
# and then rank them in terms of GEOGRAPHIC distance
import os
import numpy as np
from io import open
from collections import namedtuple
from conllu import parse_incr
LangObj = namedtupl... | [
"numpy.load",
"os.walk",
"numpy.where",
"collections.namedtuple",
"io.open"
] | [((311, 396), 'collections.namedtuple', 'namedtuple', (['"""lang"""', "['name', 'old_id', 'new_id', 'num_train', 'distance', 'obj']"], {}), "('lang', ['name', 'old_id', 'new_id', 'num_train', 'distance', 'obj']\n )\n", (321, 396), False, 'from collections import namedtuple\n'), ((454, 499), 'numpy.load', 'np.load', ... |
__author__ = '<NAME>'
import numpy as np
import time
from rollup.utils import collections
def rollup(ontology,
desired_annotators = 250,
max_iters = 50000,
print_freq = 500,
checkpoints = None,
checkpoint_hook = None
):
"""
Performs a rollup o... | [
"rollup.utils.collections.merge_lists",
"numpy.sum",
"time.time"
] | [((2804, 2815), 'time.time', 'time.time', ([], {}), '()\n', (2813, 2815), False, 'import time\n'), ((7957, 7968), 'time.time', 'time.time', ([], {}), '()\n', (7966, 7968), False, 'import time\n'), ((6874, 6885), 'time.time', 'time.time', ([], {}), '()\n', (6883, 6885), False, 'import time\n'), ((8797, 8844), 'numpy.sum... |
from __future__ import division
from __future__ import print_function
import codecs
import sys
import time
from os import path
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.python.framework import ops
from evaluation import eval_translations, Result, extract_translations
class Train... | [
"pandas.DataFrame",
"codecs.open",
"tensorflow.summary.scalar",
"evaluation.eval_translations",
"evaluation.extract_translations",
"evaluation.Result",
"numpy.isnan",
"time.time",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"tensorflow.get_default_graph",
"tensorflow.summary.FileWri... | [((605, 616), 'time.time', 'time.time', ([], {}), '()\n', (614, 616), False, 'import time\n'), ((1374, 1385), 'time.time', 'time.time', ([], {}), '()\n', (1383, 1385), False, 'import time\n'), ((2184, 2195), 'time.time', 'time.time', ([], {}), '()\n', (2193, 2195), False, 'import time\n'), ((3750, 3780), 'tensorflow.su... |
import numpy as np
from copy import copy
class NoiseCreator():
'''
Factory that build the action noise responsible for the exploration of the agent.
'''
def __init__(self):
self.builders = {
'OU': lambda size, kwargs : OUActionNoise(size, **kwargs),
'scaling_OU': lambda... | [
"numpy.zeros",
"numpy.ones",
"copy.copy",
"numpy.tile",
"numpy.random.normal"
] | [((1086, 1100), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (1094, 1100), True, 'import numpy as np\n'), ((1953, 1966), 'copy.copy', 'copy', (['self.mu'], {}), '(self.mu)\n', (1957, 1966), False, 'from copy import copy\n'), ((3429, 3492), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self.mu', 'sc... |
# The entire file is mostly a replication of the open-source implementation
# Source:
# https://github.com/susanli2016/PyCon-Canada-2019-NLP-Tutorial/blob/master/BBC%20News_LSTM.ipynb
import csv
import json
import re
import sys
import os
import tensorflow as tf
import numpy as np
import nltk
nltk.download("stopwords")... | [
"tensorflow.keras.preprocessing.text.Tokenizer",
"os.makedirs",
"tensorflow.keras.layers.Dense",
"numpy.argmax",
"os.path.realpath",
"src.utils.validate_app_config",
"os.path.exists",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"tensorflow.keras.layers.LSTM",
"nltk.corpus.stopwords.wo... | [((294, 320), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (307, 320), False, 'import nltk\n'), ((569, 590), 'os.path.realpath', 'os.path.realpath', (['"""."""'], {}), "('.')\n", (585, 590), False, 'import os\n'), ((685, 711), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""en... |
import os
import os.path as osp
import shutil
import numpy as np
from mne import set_config
from moabb.datasets.download import (
fs_get_file_hash,
fs_get_file_id,
fs_get_file_list,
get_dataset_path,
)
from moabb.utils import set_download_dir
from pooch import HTTPDownloader, Unzip, retrieve
BEETL_URL... | [
"numpy.load",
"moabb.datasets.download.get_dataset_path",
"os.path.basename",
"os.path.dirname",
"moabb.datasets.download.fs_get_file_id",
"moabb.datasets.download.fs_get_file_list",
"moabb.datasets.download.fs_get_file_hash",
"moabb.utils.set_download_dir",
"pooch.HTTPDownloader",
"numpy.array",
... | [((1510, 1535), 'os.path.dirname', 'osp.dirname', (['spath[-1][0]'], {}), '(spath[-1][0])\n', (1521, 1535), True, 'import os.path as osp\n'), ((2000, 2034), 'moabb.datasets.download.fs_get_file_list', 'fs_get_file_list', (['self.figshare_id'], {}), '(self.figshare_id)\n', (2016, 2034), False, 'from moabb.datasets.downl... |
from collections import namedtuple
from inspect import getargspec
import numpy as np
import torch
from torch import optim
import torch.nn as nn
from utils import *
from action_utils import *
from ic3net_envs import predator_prey_env
Transition = namedtuple('Transition', ('state', 'action', 'action_out', 'value', 'epis... | [
"numpy.ones_like",
"numpy.zeros",
"numpy.ones",
"inspect.getargspec",
"collections.namedtuple",
"torch.zeros"
] | [((247, 388), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', "('state', 'action', 'action_out', 'value', 'episode_mask',\n 'episode_mini_mask', 'next_state', 'reward', 'misc')"], {}), "('Transition', ('state', 'action', 'action_out', 'value',\n 'episode_mask', 'episode_mini_mask', 'next_state', 're... |
from __future__ import absolute_import, unicode_literals, print_function
import os, re, math
from ctypes import *
import numpy as N
from numpy.ctypeslib import as_array
# don't bother with parsing error
try:
lib = cdll.LoadLibrary('libnest3.so')
except:
lib = cdll.LoadLibrary(os.path.dirname(__file__) + '/lib... | [
"numpy.load",
"os.unlink",
"numpy.argmax",
"os.getcwd",
"os.path.basename",
"os.path.dirname",
"numpy.ctypeslib.as_array",
"os.path.isfile",
"tempfile.mkdtemp",
"numpy.mean",
"re.search",
"shutil.rmtree",
"math.log",
"numpy.var",
"os.chdir"
] | [((9338, 9363), 'numpy.argmax', 'N.argmax', (['ret.data[:, -1]'], {}), '(ret.data[:, -1])\n', (9346, 9363), True, 'import numpy as N\n'), ((12720, 12731), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12729, 12731), False, 'import sys, os, glob\n'), ((12736, 12753), 'os.chdir', 'os.chdir', (['dirname'], {}), '(dirname)\... |
import numpy as np
def vehicle_dynamics(dynamics_param, curv, xglob, xcurv, delta_t, u):
m, lf, lr, Iz, Df, Cf, Bf, Dr, Cr, Br = dynamics_param.get_params()
xglob_next = np.zeros(len(xglob))
xcurv_next = np.zeros(len(xcurv))
delta = u[0]
a = u[1]
psi = xglob[3]
X = xglob[4]
Y = xglo... | [
"numpy.arctan",
"numpy.sin",
"numpy.arctan2",
"numpy.cos"
] | [((488, 516), 'numpy.arctan2', 'np.arctan2', (['(vy + lf * wz)', 'vx'], {}), '(vy + lf * wz, vx)\n', (498, 516), True, 'import numpy as np\n'), ((532, 560), 'numpy.arctan2', 'np.arctan2', (['(vy - lf * wz)', 'vx'], {}), '(vy - lf * wz, vx)\n', (542, 560), True, 'import numpy as np\n'), ((644, 667), 'numpy.arctan', 'np.... |
import numpy as np
import torch
from torch.utils import data
import scipy.io as sio
import os
from tqdm import tqdm
import cv2
import json
from PIL import Image
from maskrcnn_benchmark.structures.bounding_box import BoxList
class MyDataset_train(object):
def __init__(self, json_dir, transforms=None... | [
"json.dump",
"maskrcnn_benchmark.structures.bounding_box.BoxList",
"json.load",
"scipy.io.loadmat",
"numpy.expand_dims",
"PIL.Image.open",
"numpy.array",
"os.path.join"
] | [((2008, 2028), 'scipy.io.loadmat', 'sio.loadmat', (['matfile'], {}), '(matfile)\n', (2019, 2028), True, 'import scipy.io as sio\n'), ((679, 694), 'numpy.array', 'np.array', (['boxes'], {}), '(boxes)\n', (687, 694), True, 'import numpy as np\n'), ((713, 750), 'maskrcnn_benchmark.structures.bounding_box.BoxList', 'BoxLi... |
#!/usr/bin/env python
"""
Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
Author: <NAME>
"""
import numpy as np
import scipy
from scipy.misc import fromimage
from scipy.io import loadmat
from skimage... | [
"numpy.random.uniform",
"scipy.io.loadmat",
"numpy.argmax",
"random.Random",
"numpy.unique",
"numpy.zeros",
"numpy.expand_dims",
"scipy.ndimage.zoom",
"numpy.lib.pad",
"numpy.squeeze",
"skimage.io.imread",
"skimage.color.rgb2lab"
] | [((508, 525), 'random.Random', 'Random', (['RAND_SEED'], {}), '(RAND_SEED)\n', (514, 525), False, 'from random import Random\n'), ((772, 866), 'numpy.lib.pad', 'np.lib.pad', (['im', '((0, pad_height), (0, pad_width), (0, 0))', '"""constant"""'], {'constant_values': '(-10)'}), "(im, ((0, pad_height), (0, pad_width), (0,... |
import numpy as np
def epoching_moat(messages, data, info, events):
"""Epoch the raw eyetracking data. This function has ragged array support.
Can deprecate once we switch to NivLink 2.0.
Parameters
----------
messages: array, shape (n_times, 1)
Array containing messages fromt the ... | [
"numpy.radians",
"numpy.count_nonzero",
"numpy.logical_and",
"numpy.argmax",
"math.radians",
"numpy.histogram2d",
"numpy.empty",
"numpy.zeros",
"numpy.ma.masked_invalid",
"numpy.ones",
"numpy.isnan",
"numpy.diff",
"numpy.arange",
"numpy.reshape",
"matplotlib.pyplot.subplots",
"numpy.sq... | [((2349, 2377), 'numpy.ma.masked_invalid', 'np.ma.masked_invalid', (['epochs'], {}), '(epochs)\n', (2369, 2377), True, 'import numpy as np\n'), ((3147, 3174), 'numpy.arange', 'np.arange', (['(0)', '(info.xdim + 1)'], {}), '(0, info.xdim + 1)\n', (3156, 3174), True, 'import numpy as np\n'), ((3185, 3212), 'numpy.arange'... |
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as nc
import os
import glob
import fnmatch
from collections import namedtuple, OrderedDict
import scipy.io as sio
from scipy import interpolate, signal
from pyproj import Proj,transform
import sys
sys.path.append('/ocean/s... | [
"sys.path.append",
"netCDF4.Dataset",
"gsw.spiciness0",
"gsw.SA_from_SP",
"numpy.ma.masked_values",
"numpy.empty",
"numpy.empty_like",
"gsw.CT_from_pt",
"numpy.mean",
"numpy.arange",
"collections.namedtuple",
"gsw.density.rho",
"glob.glob"
] | [((295, 345), 'sys.path.append', 'sys.path.append', (['"""/ocean/ssahu/CANYONS/wcvi/grid/"""'], {}), "('/ocean/ssahu/CANYONS/wcvi/grid/')\n", (310, 345), False, 'import sys\n'), ((711, 816), 'netCDF4.Dataset', 'nc.Dataset', (['"""/data/mdunphy/NEP036-N30-OUT/INV/Bathymetry_EastCoast_NEMO_R036_GEBCO_corr_v14.nc"""'], {}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.