code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# This file collects a few examples on how the modules of
# the package can be tested. This file can also be used by
# the github continuous integration (CI) to the test the code
# everytime there is a push.
#
# The <test coverage> can then be assessed using pytest-cov.
# This basically tests how many percents of the m... | [
"numpy.mean",
"pathlib.Path",
"pytest.fail",
"numpy.testing.assert_almost_equal",
"pytest.mark.parametrize",
"numpy.zeros",
"numpy.random.uniform"
] | [((596, 666), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""inputs, expected"""', "[('1+2', 3), ('3*4', 12)]"], {}), "('inputs, expected', [('1+2', 3), ('3*4', 12)])\n", (619, 666), False, 'import pytest\n'), ((1256, 1280), 'numpy.zeros', 'np.zeros', (['(DIM_Y, DIM_Z)'], {}), '((DIM_Y, DIM_Z))\n', (1264, ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 18 16:21:13 2017
@author: <NAME>
This code is modified based on https://github.com/KGPML/Hyperspectral
"""
import tensorflow as tf
import numpy as np
import scipy.io as io
from pygco import cut_simple, cut_simple_vh
from sklearn.metrics import accuracy_score
import matpl... | [
"scipy.io.loadmat",
"numpy.log",
"numpy.array",
"spectral.imshow",
"numpy.arange",
"cv2.medianBlur",
"numpy.max",
"numpy.eye",
"numpy.ones",
"numpy.argmax",
"numpy.transpose",
"sklearn.metrics.accuracy_score",
"numpy.dstack",
"collections.Counter",
"matplotlib.pyplot.figure",
"numpy.ze... | [((3721, 3748), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (3731, 3748), True, 'import matplotlib.pyplot as plt\n'), ((3761, 3781), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (3772, 3781), True, 'import matplotlib.pyplot as... |
import numpy as np
class Fagin:
def __init__(self, cran_title, cran_text):
self.cran_title = cran_title
self.cran_text = cran_text
def fagin(self, data, K=200):
k = 0
res = {}
N = len(data["title"]["order"])
sections = list(data)
n = 0
for n... | [
"numpy.array"
] | [((1244, 1257), 'numpy.array', 'np.array', (['new'], {}), '(new)\n', (1252, 1257), True, 'import numpy as np\n')] |
import warnings
import time
import numpy as np
# Scipy
try:
import scipy.linalg as spa
except:
warnings.warn("You don't have scipy package installed. You may get error while using some feautures.")
#pycdd
try:
from cdd import Polyhedron,Matrix,RepType
except:
warnings.warn("You don't have CDD... | [
"numpy.eye",
"pydrake.solvers.gurobi.GurobiSolver",
"numpy.linalg.pinv",
"numpy.ones",
"numpy.hstack",
"scipy.linalg.null_space",
"itertools.product",
"numpy.array",
"numpy.dot",
"matplotlib.pyplot.figure",
"numpy.zeros",
"pypolycontain.to_AH_polytope",
"numpy.concatenate",
"time.time",
... | [((916, 943), 'pydrake.solvers.gurobi.GurobiSolver', 'Gurobi_drake.GurobiSolver', ([], {}), '()\n', (941, 943), True, 'import pydrake.solvers.gurobi as Gurobi_drake\n'), ((1676, 1705), 'pypolycontain.to_AH_polytope', 'pp.to_AH_polytope', (['circumbody'], {}), '(circumbody)\n', (1693, 1705), True, 'import pypolycontain ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... | [
"numpy.stack",
"mmcv.imrescale",
"mmcv.impad",
"vega.core.common.class_factory.ClassFactory.register"
] | [((579, 621), 'vega.core.common.class_factory.ClassFactory.register', 'ClassFactory.register', (['ClassType.TRANSFORM'], {}), '(ClassType.TRANSFORM)\n', (600, 621), False, 'from vega.core.common.class_factory import ClassFactory, ClassType\n'), ((1703, 1733), 'numpy.stack', 'np.stack', (['padded_masks'], {'axis': '(0)'... |
import csv
import os
import numpy as np
import sentencepiece as spm
import torch
class DataLoader:
def __init__(self, directory, parts, cols, spm_filename):
"""Dataset loader.
Args:
directory (str): dataset directory.
parts (list[str]): dataset parts. [parts].tsv files mu... | [
"sentencepiece.SentencePieceProcessor",
"os.path.join",
"torch.tensor",
"numpy.random.randint",
"csv.reader"
] | [((697, 725), 'sentencepiece.SentencePieceProcessor', 'spm.SentencePieceProcessor', ([], {}), '()\n', (723, 725), True, 'import sentencepiece as spm\n'), ((1401, 1455), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.part_lens[part]', 'batch_size'], {}), '(0, self.part_lens[part], batch_size)\n', (1418, 145... |
import concurrent.futures
import time
import pandas as pd
import numpy as np
from tfce_toolbox.tfce_computation import tfce_from_distribution, tfces_from_distributions_st, \
tfces_from_distributions_mt
import tfce_toolbox.quicker_raw_value
def analyze(data_file, dv, seed):
print("go " + data_file)
time_... | [
"tfce_toolbox.tfce_computation.tfce_from_distribution",
"numpy.random.default_rng",
"pandas.read_csv",
"tfce_toolbox.tfce_computation.tfces_from_distributions_mt",
"pandas.DataFrame",
"numpy.percentile",
"time.time"
] | [((330, 341), 'time.time', 'time.time', ([], {}), '()\n', (339, 341), False, 'import time\n'), ((352, 379), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (373, 379), True, 'import numpy as np\n'), ((397, 439), 'pandas.read_csv', 'pd.read_csv', (["('data/' + data_file)"], {'sep': '"""\... |
#!/bin/env python3
import cv2 as cv
import numpy as np
import argparse
import tuner.tuner as tuner
def scale(img):
img = np.absolute(img)
return np.uint8(255 * (img / np.max(img)))
def ths(img, ths_min, ths_max):
ret = np.zeros_like(img)
ret[(img >= ths_min) & (img <= ths_max)] = 255
return ret... | [
"tuner.tuner.Tuner_App",
"numpy.absolute",
"numpy.max",
"cv2.cvtColor",
"numpy.zeros_like",
"cv2.Sobel"
] | [((128, 144), 'numpy.absolute', 'np.absolute', (['img'], {}), '(img)\n', (139, 144), True, 'import numpy as np\n'), ((236, 254), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (249, 254), True, 'import numpy as np\n'), ((875, 912), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2GRAY'], {}), '(i... |
# -*- coding: utf-8 -*-
import os
from PIL import Image, ImageFont, ImageDraw
import tensorflow as tf
import numpy as np
import pickle
def getJp():
count = 0
char_vocab = []
shape_vocab = []
char_shape = {}
for line in open("joyo2010.txt").readlines():
if line[0] == "#":
contin... | [
"PIL.Image.new",
"PIL.ImageFont.truetype",
"numpy.array",
"PIL.ImageDraw.Draw",
"pickle._dump"
] | [((359, 386), 'PIL.Image.new', 'Image.new', (['"""1"""', '(28, 28)', '(0)'], {}), "('1', (28, 28), 0)\n", (368, 386), False, 'from PIL import Image, ImageFont, ImageDraw\n'), ((399, 417), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (413, 417), False, 'from PIL import Image, ImageFont, ImageDraw\n'),... |
#!/usr/bin/env python
'''
Calculate the RNA-seq reads coverage over gene body.
This module uses bigwig file as input.
'''
#import built-in modules
import os,sys
if sys.version_info[0] != 2 or sys.version_info[1] != 7:
print >>sys.stderr, "\nYou are using python" + str(sys.version_info[0]) + '.' + str(sys.version_info... | [
"os.path.exists",
"optparse.OptionParser",
"collections.defaultdict",
"qcmodule.mystat.percentile_list",
"subprocess.call",
"sys.exit",
"numpy.nan_to_num"
] | [((356, 366), 'sys.exit', 'sys.exit', ([], {}), '()\n', (364, 366), False, 'import os, sys\n'), ((1539, 1567), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (1562, 1567), False, 'import collections\n'), ((3656, 3707), 'optparse.OptionParser', 'OptionParser', (['usage'], {'version': "('... |
import numpy as np
import csv
def read_ages_contact_matrix(country, n_ages):
"""Create a country-specific contact matrix from stored data.
Read a stored contact matrix based on age intervals. Return a matrix of
expected number of contacts for each pair of raw ages. Extrapolate to age
ranges that are n... | [
"numpy.array",
"numpy.zeros",
"csv.reader"
] | [((1377, 1403), 'numpy.zeros', 'np.zeros', (['(n_ages, n_ages)'], {}), '((n_ages, n_ages))\n', (1385, 1403), True, 'import numpy as np\n'), ((1619, 1662), 'numpy.array', 'np.array', (['[row[1:-1] for row in csvraw[1:]]'], {}), '([row[1:-1] for row in csvraw[1:]])\n', (1627, 1662), True, 'import numpy as np\n'), ((1510,... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
## Here we have consider last N days as training data for today's predict values
## X=[[1,......,100],[2,.....,101]]
## Y=[ 101st day, 102 ]
def previous_data(data,prev_days):
"""
Return: numpy array of t... | [
"numpy.array",
"sklearn.preprocessing.MinMaxScaler",
"pandas.read_csv"
] | [((852, 873), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (863, 873), True, 'import pandas as pd\n'), ((1251, 1285), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (1263, 1285), False, 'from sklearn.preprocessing import MinM... |
"""Performs naive Bayes on the data from a given subreddit.
"""
import math
import datetime
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
import numpy as np
import bag_of_words as bow
import sentimentAnalyzer as sa
MODEL = MultinomialNB()
def extract_features(data_frame: pd.DataFrame) -> pd.Data... | [
"math.floor",
"bag_of_words.bag_of_words",
"datetime.datetime.strptime",
"bag_of_words.csv_to_data_frame",
"numpy.array",
"sklearn.naive_bayes.MultinomialNB",
"sentimentAnalyzer.analyzeSentiments",
"bag_of_words.parse_arguments",
"pandas.DataFrame",
"numpy.percentile",
"pandas.concat"
] | [((246, 261), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (259, 261), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((608, 645), 'bag_of_words.bag_of_words', 'bow.bag_of_words', (['data_frame', '"""title"""'], {}), "(data_frame, 'title')\n", (624, 645), True, 'import bag_of_word... |
import shutil
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
BUCKET = None # set from task.py
PATTERN = "of"
CSV_COLUMNS = [
"weight_pounds",
"is_male",
"mother_age",
"plurality",
"gestation_weeks",
]
LABEL_COLUMN = "weight_pounds"
DEFAULT... | [
"tensorflow.feature_column.crossed_column",
"tensorflow.estimator.RunConfig",
"tensorflow.estimator.train_and_evaluate",
"tensorflow.estimator.LatestExporter",
"tensorflow.placeholder",
"tensorflow.logging.set_verbosity",
"tensorflow.gfile.Glob",
"tensorflow.data.TextLineDataset",
"tensorflow.featur... | [((64, 105), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (88, 105), True, 'import tensorflow as tf\n'), ((1548, 1670), 'tensorflow.feature_column.categorical_column_with_vocabulary_list', 'tf.feature_column.categorical_column_with_vocabulary_list', (... |
import numpy as np
# reverse = True: descending order (TOPSIS, CODAS), False: ascending order (VIKOR, SPOTIS)
def rank_preferences(pref, reverse = True):
"""
Rank alternatives according to MCDM preference function values.
Parameters
----------
pref : ndarray
vector with MCDM prefer... | [
"numpy.where"
] | [((1001, 1037), 'numpy.where', 'np.where', (['(sorted_pref[i + 1] == pref)'], {}), '(sorted_pref[i + 1] == pref)\n', (1009, 1037), True, 'import numpy as np\n'), ((861, 893), 'numpy.where', 'np.where', (['(sorted_pref[i] == pref)'], {}), '(sorted_pref[i] == pref)\n', (869, 893), True, 'import numpy as np\n')] |
import argparse
import os
import sys
import logging
import numpy
import numpy as np
import torch
import torch.utils.data
import torchvision
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from tqdm import tqdm
from learning3d.ops import se3
# Only if the files are in example folder.
BASE... | [
"learning3d.data_utils.AnyData",
"learning3d.models.MaskNet",
"numpy.array",
"torch.cuda.is_available",
"numpy.arange",
"numpy.mean",
"os.path.exists",
"os.listdir",
"tensorboardX.SummaryWriter",
"argparse.ArgumentParser",
"os.path.isdir",
"numpy.random.seed",
"numpy.concatenate",
"pandas.... | [((343, 368), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (358, 368), False, 'import os\n'), ((941, 1029), 'os.system', 'os.system', (["('cp train.py checkpoints' + '/' + args.exp_name + '/' + 'train.py.backup')"], {}), "('cp train.py checkpoints' + '/' + args.exp_name + '/' +\n 'train.... |
import math
import time
import pickle
import argparse
from datetime import datetime
import tensorflow as tf
import numpy as np
import dataset_info
import model_info
# Check num of gpus
gpus = tf.config.experimental.list_physical_devices('GPU')
num_gpus = len(gpus)
for gpu in gpus:
print('Name:', gpu.name, ' Type... | [
"dataset_info.select_dataset",
"tensorflow.keras.utils.to_categorical",
"math.ceil",
"numpy.random.rand",
"argparse.ArgumentParser",
"math.floor",
"tensorflow.keras.callbacks.TensorBoard",
"model_info.select_model",
"pickle.dump",
"datetime.datetime.now",
"numpy.random.randint",
"tensorflow.di... | [((195, 246), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (239, 246), True, 'import tensorflow as tf\n'), ((375, 400), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (398, 400), False, 'import argparse... |
import copy
from collections import OrderedDict
from typing import List
import numpy as np
from opticverge.core.chromosome.abstract_chromosome import AbstractChromosome
from opticverge.core.chromosome.function_chromosome import FunctionChromosome
from opticverge.core.generator.int_distribution_generator import rand_i... | [
"collections.OrderedDict",
"opticverge.core.generator.options_generator.rand_options",
"opticverge.core.generator.int_distribution_generator.rand_int",
"opticverge.core.generator.real_generator.rand_real",
"copy.copy",
"numpy.random.shuffle"
] | [((1003, 1016), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1014, 1016), False, 'from collections import OrderedDict\n'), ((1608, 1634), 'opticverge.core.generator.int_distribution_generator.rand_int', 'rand_int', (['(1)', 'self.__length'], {}), '(1, self.__length)\n', (1616, 1634), False, 'from opticv... |
#!/usr/bin/env python
#
# Baseline calculation script for NIfTI data sets. After specifying such
# a data set and an optional brain mask, converts each participant to an
# autocorrelation-based matrix representation.
#
# The goal is to summarise each participant as a voxel-by-voxel matrix.
#
# This script is specifical... | [
"os.path.exists",
"numpy.savez",
"argparse.ArgumentParser",
"os.path.join",
"os.path.splitext",
"warnings.warn",
"numpy.isnan",
"os.path.basename",
"numpy.ma.masked_invalid",
"math.log10",
"numpy.load",
"numpy.nan_to_num"
] | [((847, 873), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (863, 873), False, 'import os\n'), ((1150, 1175), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1173, 1175), False, 'import argparse\n'), ((1649, 1668), 'numpy.load', 'np.load', (['args.input'], {}), '(a... |
"""Prediction of Users based on Tweet embeddings."""
import numpy as np
from sklearn.linear_model import LogisticRegression
from .models import User
from .twitter import BASILICA
def predict_user( user1_name, user2_name, tweet_text):
user1 = User.query.filter( User.name == user1_name).one()
user2 = User.qu... | [
"numpy.array",
"numpy.vstack",
"sklearn.linear_model.LogisticRegression"
] | [((386, 439), 'numpy.array', 'np.array', (['[tweet.embedding for tweet in user1.tweets]'], {}), '([tweet.embedding for tweet in user1.tweets])\n', (394, 439), True, 'import numpy as np\n'), ((464, 517), 'numpy.array', 'np.array', (['[tweet.embedding for tweet in user2.tweets]'], {}), '([tweet.embedding for tweet in use... |
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import time
import math
import random
import numpy as np
import scipy as sp
from scipy.spatial import distance as scipydistance
# from numba import jit, njit, vectorize, float64, int64
from sc2.position import Point2
import pytest
from hy... | [
"random.uniform",
"math.dist",
"platform.python_version_tuple",
"numpy.asarray",
"numpy.sum",
"os.path.dirname",
"scipy.spatial.distance.euclidean",
"numpy.linalg.norm",
"math.hypot"
] | [((469, 500), 'platform.python_version_tuple', 'platform.python_version_tuple', ([], {}), '()\n', (498, 500), False, 'import platform\n'), ((3060, 3074), 'numpy.asarray', 'np.asarray', (['p1'], {}), '(p1)\n', (3070, 3074), True, 'import numpy as np\n'), ((3083, 3097), 'numpy.asarray', 'np.asarray', (['p2'], {}), '(p2)\... |
"""
Baseline functions that can be used without fluffy.
"""
import numpy as np
import scipy.ndimage as ndi
import skimage.io
import tensorflow as tf
def predict_baseline(
image: np.ndarray, model: tf.keras.models.Model, bit_depth: int = 16
) -> np.ndarray:
"""
Returns a binary or categorical model based ... | [
"scipy.ndimage.binary_erosion",
"numpy.pad",
"numpy.argmax",
"numpy.unique"
] | [((1657, 1715), 'numpy.pad', 'np.pad', (['pred', '((0, pad_bottom), (0, pad_right))', '"""reflect"""'], {}), "(pred, ((0, pad_bottom), (0, pad_right)), 'reflect')\n", (1663, 1715), True, 'import numpy as np\n'), ((2475, 2532), 'scipy.ndimage.binary_erosion', 'ndi.binary_erosion', (['(pred_mask[..., 1] > 0.5)'], {'itera... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 07:34:10 2019
@author: Brendan
"""
import os
import numpy as np
class TestPreProcess():
def test_works(self):
raw_dir = './images/raw/demo'
processed_dir = './images/processed/demo'
Nfiles = 256
command = ('python preProcessDe... | [
"os.system",
"numpy.load",
"os.path.join",
"numpy.diff"
] | [((441, 459), 'os.system', 'os.system', (['command'], {}), '(command)\n', (450, 459), False, 'import os\n'), ((657, 700), 'os.path.join', 'os.path.join', (['processed_dir', '"""dataCube.npy"""'], {}), "(processed_dir, 'dataCube.npy')\n", (669, 700), False, 'import os\n'), ((1712, 1730), 'os.system', 'os.system', (['com... |
import zarr
from typing import Any, Tuple, List, Union
import numpy as np
from tqdm import tqdm
from .readers import CrReader, H5adReader, NaboH5Reader, LoomReader
import os
import pandas as pd
from .utils import controlled_compute
from .logging_utils import logger
from scipy.sparse import csr_matrix
__all__ = ['creat... | [
"os.path.exists",
"numpy.ones",
"numpy.hstack",
"tqdm.tqdm",
"numpy.array",
"zarr.open",
"numcodecs.Blosc",
"numpy.dtype",
"pandas.concat"
] | [((760, 814), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""lz4"""', 'clevel': '(5)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='lz4', clevel=5, shuffle=Blosc.BITSHUFFLE)\n", (765, 814), False, 'from numcodecs import Blosc\n'), ((1137, 1151), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1145, 1151), True, 'i... |
# Copyright 2017 <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 or agreed to in writing... | [
"os.listdir",
"re.match",
"numpy.array",
"sys.exit",
"os.system",
"numpy.save",
"os.remove"
] | [((759, 796), 'os.system', 'os.system', (['"""R --no-save < catwrite.R"""'], {}), "('R --no-save < catwrite.R')\n", (768, 796), False, 'import os\n'), ((940, 952), 'os.listdir', 'os.listdir', ([], {}), '()\n', (950, 952), False, 'import os\n'), ((1639, 1657), 'numpy.array', 'np.array', (['catstack'], {}), '(catstack)\n... |
"""
Solves the incompressible Navier Stokes equations using "Stable Fluids" by <NAME>
in a closed box with a forcing that creates a bloom.
Momentum: ∂u/∂t + (u ⋅ ∇) u = − 1/ρ ∇p + ν ∇²u + f
Incompressibility: ∇ ⋅ u = 0
u: Velocity (2d vector)
p: Pressure
f: Forcing
ν: Kinematic Viscosity
ρ: Densit... | [
"numpy.clip",
"scipy.sparse.linalg.LinearOperator",
"numpy.array",
"matplotlib.pyplot.contourf",
"scipy.interpolate.interpn",
"matplotlib.pyplot.style.use",
"numpy.linspace",
"numpy.concatenate",
"numpy.meshgrid",
"numpy.maximum",
"matplotlib.pyplot.quiver",
"matplotlib.pyplot.pause",
"matpl... | [((5017, 5050), 'numpy.maximum', 'np.maximum', (['(2.0 - 0.5 * time)', '(0.0)'], {}), '(2.0 - 0.5 * time, 0.0)\n', (5027, 5050), True, 'import numpy as np\n'), ((5685, 5724), 'numpy.linspace', 'np.linspace', (['(0.0)', 'DOMAIN_SIZE', 'N_POINTS'], {}), '(0.0, DOMAIN_SIZE, N_POINTS)\n', (5696, 5724), True, 'import numpy ... |
import numpy as np
import torch
import gym
import argparse
import os
from collections import deque
import utils
import TD3
import OurDDPG
import DDPG
import TD3_ad
import robosuite as suite
from torch.utils.tensorboard import SummaryWriter
import time
import multiprocessing as mp
from functools import partial
def c... | [
"numpy.array",
"numpy.save",
"robosuite.make",
"torch.utils.tensorboard.SummaryWriter",
"os.path.exists",
"numpy.mean",
"collections.deque",
"argparse.ArgumentParser",
"TD3_ad.TD3_ad",
"utils.ReplayBuffer",
"numpy.random.seed",
"numpy.concatenate",
"numpy.random.normal",
"OurDDPG.DDPG",
... | [((356, 368), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (364, 368), True, 'import numpy as np\n'), ((663, 801), 'robosuite.make', 'suite.make', (['args.env'], {'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'use_object_obs': '(True)', 'use_camera_obs': '(False)', 'reward_shaping': '(True)'}), ... |
"""応答の格納・管理"""
import numpy as np
from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero
class Response:
"""応答の格納・管理"""
def __init__(self, analysis):
self.analysis = analysis
self.n_dof_plus_1 = self.analysis.model.n_dof + 1
self.acc_00_origin = read_case_wav... | [
"numpy.abs",
"asva.utils.wave.divide_wave",
"asva.utils.wave.add_wave_required_zero",
"asva.utils.wave.read_case_wave",
"numpy.array",
"numpy.zeros",
"numpy.arange"
] | [((307, 366), 'asva.utils.wave.read_case_wave', 'read_case_wave', (['self.analysis.wave', 'self.analysis.case_conf'], {}), '(self.analysis.wave, self.analysis.case_conf)\n', (321, 366), False, 'from asva.utils.wave import read_case_wave, divide_wave, add_wave_required_zero\n'), ((395, 466), 'asva.utils.wave.add_wave_re... |
import numpy as np
from apps.keyboard.core.mfcc import mfcc
def mapminmax(x, ymin=-1, ymax=+1):
x = np.asanyarray(x)
xmax = x.max(axis=-1)
xmin = x.min(axis=-1)
if (xmax == xmin).any():
raise ValueError("some rows have no variation")
return (ymax - ymin) * (x - xmin) / (xmax - xmin) + ymi... | [
"apps.keyboard.core.mfcc.mfcc.mfcc",
"numpy.asanyarray"
] | [((107, 123), 'numpy.asanyarray', 'np.asanyarray', (['x'], {}), '(x)\n', (120, 123), True, 'import numpy as np\n'), ((1118, 1185), 'apps.keyboard.core.mfcc.mfcc.mfcc', 'mfcc.mfcc', (['speech', 'fs', 'Tw', 'Ts', 'alpha', 'np.hamming', '[LF, HF]', 'M', 'C', 'L'], {}), '(speech, fs, Tw, Ts, alpha, np.hamming, [LF, HF], M,... |
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the followin... | [
"numpy.mean",
"cytoskeleton_analyser.position.empirical_data.mboc17.avg",
"cytoskeleton_analyser.position.empirical_data.mboc17.length",
"cytoskeleton_analyser.position.empirical_data.mboc17.curvature",
"cytoskeleton_analyser.fitting.Exponential.create",
"numpy.array",
"numpy.concatenate",
"numpy.std"... | [((8058, 8085), 'cytoskeleton_analyser.position.empirical_data.mboc17.length', 'mboc17.length', ([], {'density': '(True)'}), '(density=True)\n', (8071, 8085), True, 'import cytoskeleton_analyser.position.empirical_data.mboc17 as mboc17\n'), ((8218, 8235), 'cytoskeleton_analyser.position.empirical_data.mboc17.avg', 'mbo... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as sp
import math
import random as rm
import NumerosGenerados as ng
n = 100000
inicio = 0
ancho = 20
K = 3
numerosGamma = sp.gamma.rvs(size=n, a = K)
print("Media: ", round(np.mean(numerosGamma),3))
print("Desvio: ", round(np.sqrt(np.var(numerosGam... | [
"numpy.mean",
"random.choice",
"matplotlib.pyplot.hist",
"scipy.stats.gamma.rvs",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"math.log",
"matplotlib.pyplot.title",
"NumerosGenerados.generarNumeros",
"numpy.var",
"matplotlib.pyplot.show"
] | [((193, 218), 'scipy.stats.gamma.rvs', 'sp.gamma.rvs', ([], {'size': 'n', 'a': 'K'}), '(size=n, a=K)\n', (205, 218), True, 'import scipy.stats as sp\n'), ((381, 469), 'matplotlib.pyplot.hist', 'plt.hist', (['numerosGamma'], {'bins': '(50)', 'color': '"""red"""', 'histtype': '"""bar"""', 'alpha': '(0.8)', 'ec': '"""blac... |
import numpy as np
from pmesh.pm import ParticleMesh
from nbodykit.lab import BigFileCatalog, BigFileMesh, FFTPower
from nbodykit.source.mesh.field import FieldMesh
from nbodykit.lab import SimulationBox2PCF, FFTCorr
import os
import sys
sys.path.append('./utils')
import tools, dohod #
from time import ti... | [
"pmesh.pm.ParticleMesh",
"numpy.broadcast_to",
"numpy.ones",
"argparse.ArgumentParser",
"os.makedirs",
"nbodykit.lab.SimulationBox2PCF",
"tools.atoz",
"nbodykit.lab.BigFileMesh",
"dohod.make_galcat",
"dohod.assignH1mass",
"numpy.stack",
"os.path.dirname",
"nbodykit.lab.BigFileCatalog",
"ti... | [((239, 265), 'sys.path.append', 'sys.path.append', (['"""./utils"""'], {}), "('./utils')\n", (254, 265), False, 'import sys\n'), ((373, 398), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (396, 398), False, 'import argparse\n'), ((1724, 1768), 'pmesh.pm.ParticleMesh', 'ParticleMesh', ([], {'B... |
import argparse
import json
import logging
import numpy as np
import warnings
import pandas as pd
from sklearn.model_selection import KFold
from interprete.src.models.available_models import MODELS
from interprete.src.struct_probing.code_augs import available_augs, CodeAugmentation
from interprete.src.utils import Se... | [
"logging.getLogger",
"numpy.unique",
"argparse.ArgumentParser",
"interprete.src.utils.Setup.get_aug_path",
"numpy.array",
"interprete.src.struct_probing.code_augs.available_augs.keys",
"warnings.warn",
"sklearn.model_selection.KFold",
"logging.info",
"json.dump",
"interprete.src.models.available... | [((383, 419), 'logging.getLogger', 'logging.getLogger', (['"""save_embeddings"""'], {}), "('save_embeddings')\n", (400, 419), False, 'import logging\n'), ((1023, 1063), 'logging.info', 'logging.info', (['f"""start {args.insert_bug}"""'], {}), "(f'start {args.insert_bug}')\n", (1035, 1063), False, 'import logging\n'), (... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 15:47:00 2021
@author: yusheng
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
FILE = "./train/restarted_agent_00_net_"
ftype = np.float32
W = np.fromfile(FILE +"weights.raw", dtype=ftype) | [
"numpy.fromfile"
] | [((239, 285), 'numpy.fromfile', 'np.fromfile', (["(FILE + 'weights.raw')"], {'dtype': 'ftype'}), "(FILE + 'weights.raw', dtype=ftype)\n", (250, 285), True, 'import numpy as np\n')] |
import numpy as np
class HMM:
def __init__(self, A=None, B=None, pi=None):
self.A = A
self.B = B
self.pi = pi
def forward(self, O, detailed=False):
alpha = self.pi*self.B[:, O[0]]
if detailed:
print("alpha: {}".format(alpha))
for t in range(1, len(O))... | [
"numpy.ones",
"numpy.argmax",
"numpy.max",
"numpy.sum",
"numpy.matmul"
] | [((423, 436), 'numpy.sum', 'np.sum', (['alpha'], {}), '(alpha)\n', (429, 436), True, 'import numpy as np\n'), ((488, 510), 'numpy.ones', 'np.ones', (['self.pi.shape'], {}), '(self.pi.shape)\n', (495, 510), True, 'import numpy as np\n'), ((651, 691), 'numpy.sum', 'np.sum', (['(self.pi * self.B[:, O[0]] * beta)'], {}), '... |
import os
import unittest
import logging
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
#
# SegmentCrossSectionArea
#
class SegmentCrossSectionArea(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.... | [
"slicer.util.childWidgetVariables",
"numpy.count_nonzero",
"numpy.array",
"vtk.vtkGeneralTransform",
"vtk.vtkFloatArray",
"logging.info",
"slicer.util.arrayFromTableColumn",
"slicer.mrmlScene.AddNewNodeByClass",
"slicer.mrmlScene.AddNode",
"traceback.print_exc",
"SampleData.SampleDataLogic",
"... | [((1523, 1557), 'slicer.util.VTKObservationMixin.__init__', 'VTKObservationMixin.__init__', (['self'], {}), '(self)\n', (1551, 1557), False, 'from slicer.util import VTKObservationMixin\n'), ((2015, 2057), 'slicer.util.childWidgetVariables', 'slicer.util.childWidgetVariables', (['uiWidget'], {}), '(uiWidget)\n', (2047,... |
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Harvard Medical School"
__license__ = "MIT"
import numpy as np
import tensorflow as tf
from ast import literal_eval
class switch(object):
"""Switch statement for Python, based on recipe from Python Cookbook."""
def __init__(self, value):
self.val... | [
"tensorflow.initializers.random_normal",
"tensorflow.initializers.orthogonal",
"numpy.linspace",
"tensorflow.initializers.random_uniform",
"tensorflow.initializers.variance_scaling"
] | [((1421, 1447), 'numpy.linspace', 'np.linspace', (['(0.25)', '(0.99)', '(4)'], {}), '(0.25, 0.99, 4)\n', (1432, 1447), True, 'import numpy as np\n'), ((2203, 2281), 'tensorflow.initializers.random_normal', 'tf.initializers.random_normal', (['init_center', 'init_range'], {'seed': 'seed', 'dtype': 'dtype'}), '(init_cente... |
import rospy
from std_msgs.msg import String
from skeleton_markers.msg import Skeleton
import numpy as np
class SkeletonAngles():
def __init__(self):
self.pub = rospy.Publisher ('skeleton_angles', String, queue_size=10)
self.names = ['head', 'neck', 'torso', 'left_shoulder', 'left_elbow', 'left_ha... | [
"rospy.Subscriber",
"numpy.cross",
"rospy.init_node",
"numpy.array",
"numpy.zeros",
"numpy.dot",
"numpy.arctan2",
"rospy.spin",
"numpy.cos",
"numpy.linalg.norm",
"numpy.sin",
"rospy.Publisher"
] | [((175, 232), 'rospy.Publisher', 'rospy.Publisher', (['"""skeleton_angles"""', 'String'], {'queue_size': '(10)'}), "('skeleton_angles', String, queue_size=10)\n", (190, 232), False, 'import rospy\n'), ((656, 669), 'numpy.zeros', 'np.zeros', (['[8]'], {}), '([8])\n', (664, 669), True, 'import numpy as np\n'), ((739, 772... |
# Copyright 2021 The Private Cardinality Estimation Framework 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 b... | [
"numpy.random.default_rng"
] | [((1878, 1907), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': '(1)'}), '(seed=1)\n', (1899, 1907), True, 'import numpy as np\n')] |
"""
These are borrowed from SciPy and used under their license:
Copyright (c) 2001, 2002 Enthought, Inc.
All rights reserved.
Copyright (c) 2003-2012 SciPy Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following condi... | [
"numpy.isscalar",
"numpy.ndim"
] | [((1858, 1872), 'numpy.isscalar', 'np.isscalar', (['x'], {}), '(x)\n', (1869, 1872), True, 'import numpy as np\n'), ((2629, 2646), 'numpy.isscalar', 'np.isscalar', (['t[0]'], {}), '(t[0])\n', (2640, 2646), True, 'import numpy as np\n'), ((2448, 2458), 'numpy.ndim', 'np.ndim', (['M'], {}), '(M)\n', (2455, 2458), True, '... |
from itertools import combinations
import numpy as np
import time
def friend_numbers_exhaustive_count(count_till_number):
friend_numbers_cnt = 0
for pair in combinations(np.arange(1,count_till_number),2):
str_1 = str(pair[0])
str_2 = str(pair[1])
# print(str_1, str_2)
if np.any(... | [
"numpy.any",
"time.time",
"numpy.arange"
] | [((439, 450), 'time.time', 'time.time', ([], {}), '()\n', (448, 450), False, 'import time\n'), ((501, 512), 'time.time', 'time.time', ([], {}), '()\n', (510, 512), False, 'import time\n'), ((179, 210), 'numpy.arange', 'np.arange', (['(1)', 'count_till_number'], {}), '(1, count_till_number)\n', (188, 210), True, 'import... |
import numpy as N
from traits.api import (HasTraits, Array, Range, Instance, Enum)
from traitsui.api import View, Item
from chaco.api import (ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink,
jet)
from chaco.default_colormaps import fix
from enable.api import ComponentEditor
from AwesomeColorMaps import awes... | [
"traits.api.Instance",
"traits.api.Enum",
"chaco.api.ArrayPlotData",
"traits.api.Array",
"chaco.api.Plot",
"numpy.array",
"numpy.zeros",
"traits.api.Range",
"chaco.default_colormaps.fix",
"enable.api.ComponentEditor",
"numpy.rot90",
"chaco.api.PlotLabel",
"chaco.api.ColorMapper.from_segment_... | [((805, 866), 'chaco.api.ColorMapper.from_segment_map', 'ColorMapper.from_segment_map', (['_bone_data'], {'range': 'rng'}), '(_bone_data, range=rng, **traits)\n', (833, 866), False, 'from chaco.api import ArrayPlotData, Plot, PlotLabel, ColorMapper, gray, pink, jet\n'), ((911, 918), 'traits.api.Array', 'Array', ([], {}... |
'''
Define a simple neural net in Keras that recognizes MNIST handwritten digits
'''
from __future__ import print_function
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.optimizers import SGD
from keras.utils import np_u... | [
"keras.layers.core.Activation",
"keras.datasets.mnist.load_data",
"keras.models.Sequential",
"keras.utils.np_utils.to_categorical",
"keras.optimizers.SGD",
"numpy.random.seed",
"keras.layers.core.Dense"
] | [((325, 345), 'numpy.random.seed', 'np.random.seed', (['(1671)'], {}), '(1671)\n', (339, 345), True, 'import numpy as np\n'), ((441, 446), 'keras.optimizers.SGD', 'SGD', ([], {}), '()\n', (444, 446), False, 'from keras.optimizers import SGD\n'), ((525, 542), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {})... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
# Command line :
# python -m benchmark.AP1.explore
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.savefig",
"os.makedirs",
"matplotlib.pyplot.ylabel",
"visual.set_plot_config",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.clf",
"numpy.min",
"numpy.max",
"numpy.linspace",
"visual.likelihood.plot_param... | [((361, 378), 'visual.set_plot_config', 'set_plot_config', ([], {}), '()\n', (376, 378), False, 'from visual import set_plot_config\n'), ((580, 631), 'os.path.join', 'os.path.join', (['SAVING_DIR', 'BENCHMARK_NAME', '"""explore"""'], {}), "(SAVING_DIR, BENCHMARK_NAME, 'explore')\n", (592, 631), False, 'import os\n'), (... |
""" Module containing classes that interfaces neural network policies
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
from aizynthfinder.chem import RetroReaction
from aizynthfinder.utils.models import load_model
from aizynthfinder.context.collection impo... | [
"aizynthfinder.utils.models.load_model",
"numpy.argsort",
"aizynthfinder.chem.RetroReaction",
"numpy.argmin",
"numpy.cumsum",
"pandas.read_hdf"
] | [((4164, 4219), 'aizynthfinder.utils.models.load_model', 'load_model', (['source', 'key', 'self._config.use_remote_models'], {}), '(source, key, self._config.use_remote_models)\n', (4174, 4219), False, 'from aizynthfinder.utils.models import load_model\n'), ((4332, 4366), 'pandas.read_hdf', 'pd.read_hdf', (['templatefi... |
import os
import matplotlib.pyplot as plt
import numpy as np
def load_data(fpath=''):
if len(fpath) == 0:
fpaths = ['data/BF_CTU.csv', 'data/BF_V.csv', 'data/BF_OU.csv']
else:
fpaths = fpath
honest_data = []
dishonest_data = []
for fpath in fpaths:
header = True
f... | [
"matplotlib.pyplot.grid",
"numpy.argsort",
"numpy.array",
"numpy.linalg.norm",
"numpy.arange",
"numpy.mean",
"os.path.exists",
"numpy.where",
"matplotlib.pyplot.xlabel",
"numpy.dot",
"matplotlib.pyplot.ylim",
"numpy.abs",
"numpy.ceil",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gca"... | [((2210, 2236), 'numpy.arange', 'np.arange', (['(50)', '(100)'], {'step': '(1)'}), '(50, 100, step=1)\n', (2219, 2236), True, 'import numpy as np\n'), ((3192, 3229), 'numpy.array', 'np.array', (['hdata_train'], {'dtype': 'np.float'}), '(hdata_train, dtype=np.float)\n', (3200, 3229), True, 'import numpy as np\n'), ((324... |
from abc import abstractmethod
from numpy import eye, shape
from numpy.linalg import pinv
class Kernel(object):
def __init__(self):
pass
@abstractmethod
def kernel(self, X, Y=None):
raise NotImplementedError()
@staticmethod
def centering_matrix(n):
"""
Returns th... | [
"numpy.shape",
"numpy.eye"
] | [((383, 389), 'numpy.eye', 'eye', (['n'], {}), '(n)\n', (386, 389), False, 'from numpy import eye, shape\n'), ((569, 577), 'numpy.shape', 'shape', (['K'], {}), '(K)\n', (574, 577), False, 'from numpy import eye, shape\n'), ((593, 599), 'numpy.eye', 'eye', (['n'], {}), '(n)\n', (596, 599), False, 'from numpy import eye,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import nibabel as nb
import numpy as np
import image_funcs as imf
import vis_funcs as vf
def main():
SHOW_WINDOW = True
SHOW_AXES = True
COMP_ACT_SEED = True
SEED_OFFSET = 25
data_dir = os.environ.get('OneDrive') + r'\data\dti_navigation... | [
"numpy.identity",
"image_funcs.coil_transform_matrix",
"vis_funcs.add_line",
"image_funcs.load_mks",
"image_funcs.load_image",
"numpy.hstack",
"numpy.cross",
"vis_funcs.add_marker",
"os.environ.get",
"os.path.join",
"image_funcs.grid_offset",
"image_funcs.create_grid",
"image_funcs.mri2inv",... | [((634, 685), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['MKSS'] + '.mkss')"], {}), "(data_dir, filenames['MKSS'] + '.mkss')\n", (646, 685), False, 'import os\n'), ((706, 759), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['HEADSIM'] + '.stl')"], {}), "(data_dir, filenames['HEADSIM'] + '.stl'... |
import pandas as pd
import numpy as np
import glob
import sys
import re
from astropy.cosmology import Planck15 as cosmo
import rate_functions as functions ### Mike's code
import astropy.units as u
import scipy
#---------------------------------------------------------------... | [
"numpy.log10",
"astropy.cosmology.Planck15.H",
"astropy.cosmology.Planck15.lookback_time",
"numpy.where",
"numpy.sum",
"numpy.linspace",
"rate_functions.metal_disp_z",
"pandas.read_hdf",
"numpy.random.uniform",
"pandas.DataFrame",
"re.findall",
"rate_functions.sfr_z",
"astropy.cosmology.Plan... | [((8212, 8234), 'glob.glob', 'glob.glob', (['COSMIC_path'], {}), '(COSMIC_path)\n', (8221, 8234), False, 'import glob\n'), ((8344, 8373), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (8356, 8373), True, 'import pandas as pd\n'), ((8958, 9013), 'numpy.linspace', 'np.linspace',... |
"""
Classes for Bayesian optimization
Created on Jul 9, 2019
@author: <NAME> (<EMAIL>)
Copyright 2019 Xilinx, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including ... | [
"opentuner.search.differentialevolution.DifferentialEvolutionAlt",
"numpy.prod",
"opentuner.search.evolutionarytechniques.UniformGreedyMutation",
"scipy.stats.norm.pdf",
"math.isinf",
"opentuner.search.evolutionarytechniques.NormalGreedyMutation",
"opentuner.search.simplextechniques.RandomNelderMead",
... | [((5352, 5369), 'numpy.prod', 'numpy.prod', (['probs'], {}), '(probs)\n', (5362, 5369), False, 'import numpy\n'), ((5707, 5729), 'math.isinf', 'math.isinf', (['expec_impr'], {}), '(expec_impr)\n', (5717, 5729), False, 'import math\n'), ((5733, 5755), 'math.isnan', 'math.isnan', (['expec_impr'], {}), '(expec_impr)\n', (... |
import pytest
import numpy as np
from ._parametrize import optimizers_noSBOM
def objective_function(para):
return 1
@pytest.mark.parametrize(*optimizers_noSBOM)
def test_large_search_space_0(Optimizer):
search_space = {
"x1": np.arange(0, 1000000),
"x2": np.arange(0, 1000000),
"x3"... | [
"pytest.mark.parametrize",
"numpy.arange"
] | [((126, 169), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['*optimizers_noSBOM'], {}), '(*optimizers_noSBOM)\n', (149, 169), False, 'import pytest\n'), ((479, 522), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['*optimizers_noSBOM'], {}), '(*optimizers_noSBOM)\n', (502, 522), False, 'import pytest\... |
import numpy as np
from torch.utils.data import SubsetRandomSampler
from torchvision.transforms import transforms
from torchvision.datasets import CIFAR10
from dlex.datasets.torch import Dataset
from dlex.torch import Batch
from dlex.torch.utils.ops_utils import maybe_cuda
class PytorchCIFAR10(Dataset):
... | [
"numpy.floor",
"torch.utils.data.SubsetRandomSampler",
"torchvision.transforms.transforms.Normalize",
"torchvision.transforms.transforms.ToTensor",
"dlex.torch.utils.ops_utils.maybe_cuda",
"numpy.random.shuffle"
] | [((958, 984), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (975, 984), True, 'import numpy as np\n'), ((1083, 1147), 'torch.utils.data.SubsetRandomSampler', 'SubsetRandomSampler', (["(train_idx if mode == 'train' else valid_idx)"], {}), "(train_idx if mode == 'train' else valid_idx)\n"... |
"""Functions to perform correlations"""
import numpy as np
from scipy.stats import norm
def cross_corr(a, b):
"""Cross-correlation
Calculate the cross correlation of array b against array a.
Args:
a (array): numpy vector. Reference against which cross
correlation is calculated.
... | [
"numpy.polyfit",
"numpy.conj",
"numpy.fft.fft",
"numpy.max",
"scipy.stats.norm.pdf",
"numpy.min",
"numpy.fft.ifft",
"numpy.arange"
] | [((688, 701), 'numpy.fft.fft', 'np.fft.fft', (['a'], {}), '(a)\n', (698, 701), True, 'import numpy as np\n'), ((712, 725), 'numpy.fft.fft', 'np.fft.fft', (['b'], {}), '(b)\n', (722, 725), True, 'import numpy as np\n'), ((771, 783), 'numpy.conj', 'np.conj', (['f_a'], {}), '(f_a)\n', (778, 783), True, 'import numpy as np... |
import ray
from environment.rrt import RRTWrapper
from environment import utils
from environment import RealTimeEnv
from utils import (
parse_args,
load_config,
create_policies,
exit_handler
)
from environment import TaskLoader
import pickle
from signal import signal, SIGINT
from numpy import mean
from ... | [
"os.path.exists",
"numpy.mean",
"pickle.dump",
"environment.TaskLoader",
"distribute.Pool",
"tqdm.tqdm",
"utils.parse_args",
"environment.utils.get_observation_dimensions",
"utils.load_config",
"environment.RealTimeEnv",
"utils.create_policies",
"ray.remote",
"ray.init",
"environment.RealT... | [((432, 444), 'utils.parse_args', 'parse_args', ([], {}), '()\n', (442, 444), False, 'from utils import parse_args, load_config, create_policies, exit_handler\n'), ((478, 502), 'utils.load_config', 'load_config', (['args.config'], {}), '(args.config)\n', (489, 502), False, 'from utils import parse_args, load_config, cr... |
# Copyright 2018 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, ... | [
"tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator.simple_fixed_prediction_estimator",
"tensorflow_model_analysis.eval_saved_model.example_trainers.fixed_prediction_estimator_extra_fields.simple_fixed_prediction_estimator_extra_fields",
"tensorflow_model_analysis.api.impl.ev... | [((14448, 14462), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (14460, 14462), True, 'import tensorflow as tf\n'), ((3586, 3656), 'tensorflow_model_analysis.eval_saved_model.example_trainers.linear_classifier.simple_linear_classifier', 'linear_classifier.simple_linear_classifier', (['None', 'temp_eval_expo... |
# -*- coding: utf-8 -*-
import numpy as np
import binarybrain as bb
import binarybrain.core as core
# ----- LUT Layer -----
def make_verilog_lut_layers(module_name: str, net, device=""):
layers = bb.get_model_list(net, flatten=True)
core_layers = []
for layer in layers:
core_layers.append(... | [
"numpy.tile",
"binarybrain.core.make_verilog_lut_cnv_layers",
"binarybrain.get_model_list_for_rtl",
"numpy.stack",
"numpy.array",
"binarybrain.get_model_list",
"binarybrain.core.make_verilog_lut_layers"
] | [((210, 246), 'binarybrain.get_model_list', 'bb.get_model_list', (['net'], {'flatten': '(True)'}), '(net, flatten=True)\n', (227, 246), True, 'import binarybrain as bb\n'), ((349, 411), 'binarybrain.core.make_verilog_lut_layers', 'core.make_verilog_lut_layers', (['module_name', 'core_layers', 'device'], {}), '(module_n... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import configparser
import argparse
import visdom
import tqdm
from os import path
import numpy as np
from tabulate import tabulate
from torchvision import datasets, transforms, models
from torchlib.dataloader import PPPP
from... | [
"numpy.log10",
"torchlib.utils.Arguments",
"configparser.ConfigParser",
"torch.nn.CrossEntropyLoss",
"torchlib.models.vgg16",
"torch.cuda.is_available",
"torch.sum",
"visdom.Visdom",
"syft.VirtualWorker",
"argparse.ArgumentParser",
"numpy.asarray",
"torchvision.transforms.ToTensor",
"torchli... | [((507, 532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (530, 532), False, 'import argparse\n'), ((1559, 1586), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1584, 1586), False, 'import configparser\n'), ((1598, 1626), 'os.path.isfile', 'path.isfile', (['cmd_... |
from __future__ import absolute_import, division, print_function
__project__ = "Electrical Pre-Conditioning of Convective Clouds"
__title__ = "Plotting Radiosonde Data"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "1.14"
__date__ = "28/02/2019"
__status__ = "Stable"
__changelog__ = "Added in Case Study se... | [
"Gilly_Utilities.argcontiguous",
"pandas.read_csv",
"Gilly_Utilities.antinan",
"numpy.log",
"Gilly_Utilities.HuberRegression",
"Gilly_Utilities.fix_recarray",
"Gilly_Utilities.flatten",
"numpy.arctan2",
"sys.exit",
"numpy.sin",
"numpy.arange",
"urllib2.urlopen",
"Gilly_Utilities.broadcast",
... | [((863, 926), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/users/th863480/PhD/Global_Functions"""'], {}), "(0, '/home/users/th863480/PhD/Global_Functions')\n", (878, 926), False, 'import sys\n'), ((1360, 1381), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (1375, 1381), False, 'impor... |
import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule
from mmdet.core import mask_target, force_fp32, auto_fp16
import matplotlib.pyplot as plt ... | [
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"numpy.round",
"torch.nn.init.kaiming_normal_",
"mmdet.core.auto_fp16",
"torch.nn.Conv2d",
"numpy.array",
"numpy.zeros",
"torch.nn.Upsample",
"torch.zeros_like",
"mmdet.core.mask_target",
"torch.nn.ConvTranspose2d",
"mmcv.i... | [((5944, 5955), 'mmdet.core.auto_fp16', 'auto_fp16', ([], {}), '()\n', (5953, 5955), False, 'from mmdet.core import mask_target, force_fp32, auto_fp16\n'), ((7749, 7784), 'mmdet.core.force_fp32', 'force_fp32', ([], {'apply_to': "('mask_pred',)"}), "(apply_to=('mask_pred',))\n", (7759, 7784), False, 'from mmdet.core imp... |
#!/usr/bin/env python3
import numpy as np
import copy as cp
from tqdm import tqdm
import lib.metrics as metrics
import sklearn.model_selection as sk_modsel
import sklearn.metrics as sk_metrics
import sklearn.utils as sk_utils
def sk_learn_k_fold_cv(x, y, z, kf_reg, design_matrix, k_splits=4,
... | [
"numpy.mean",
"numpy.sqrt",
"numpy.asarray",
"sklearn.utils.resample",
"lib.metrics.R2",
"numpy.empty",
"sklearn.model_selection.KFold",
"numpy.var"
] | [((581, 615), 'sklearn.model_selection.KFold', 'sk_modsel.KFold', ([], {'n_splits': 'k_splits'}), '(n_splits=k_splits)\n', (596, 615), True, 'import sklearn.model_selection as sk_modsel\n'), ((1138, 1161), 'numpy.asarray', 'np.asarray', (['y_pred_list'], {}), '(y_pred_list)\n', (1148, 1161), True, 'import numpy as np\n... |
import impedance as imp
import math
from sympy.physics import units as u
from sympy import sqrt, re, im, I
from constants import constants as c
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib as mpl
from helper_functions import indep_array
rc('text', usetex=True)
mpl.rcPar... | [
"impedance.impedance",
"helper_functions.indep_array",
"matplotlib.pyplot.savefig",
"matplotlib.rcParams.update",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.vlines",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"sympy.sqrt",
"numpy.sqrt",
"sympy.re",
... | [((287, 310), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (289, 310), False, 'from matplotlib import rc\n'), ((311, 349), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'font.size': 18}"], {}), "({'font.size': 18})\n", (330, 349), True, 'import matplotlib as mpl\n... |
import numpy as np
def get_int_tuple_from_string_pair(pair):
return tuple((int(x) for x in pair.split(',')))
def get_zeroed_field(vectors):
dimension_size = max(vectors.flat) + 1
return np.zeros((dimension_size, dimension_size), dtype=int)
def get_overlaps_count_from_field(field):
return len([x fo... | [
"numpy.array",
"numpy.zeros"
] | [((2046, 2063), 'numpy.array', 'np.array', (['vectors'], {}), '(vectors)\n', (2054, 2063), True, 'import numpy as np\n'), ((202, 255), 'numpy.zeros', 'np.zeros', (['(dimension_size, dimension_size)'], {'dtype': 'int'}), '((dimension_size, dimension_size), dtype=int)\n', (210, 255), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 22:28:37 2019
@author: maheshsoundar
"""
import pandas as pd
import random
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
#class to scale data. Provide chunksize and type of scaler. Use the object of created class to cal... | [
"sklearn.preprocessing.StandardScaler",
"sklearn.preprocessing.MinMaxScaler",
"numpy.random.seed",
"random.seed"
] | [((685, 705), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (699, 705), True, 'import numpy as np\n'), ((715, 732), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (726, 732), False, 'import random\n'), ((504, 520), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n... |
import numpy as np
import torchvision.transforms as T
from labels import *
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
def preprocess(images):
images = [img.convert('RGB').resize([400, 600]) for img in images]
return images
def get_transform(normalize = False)... | [
"matplotlib.pyplot.text",
"matplotlib.patches.Rectangle",
"random.randint",
"matplotlib.pyplot.show",
"numpy.argsort",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"torchvision.transforms.Normalize",
"matplotlib.pyplot.axis",
"torchvision.transform... | [((518, 546), 'torchvision.transforms.Compose', 'T.Compose', (['custom_transforms'], {}), '(custom_transforms)\n', (527, 546), True, 'import torchvision.transforms as T\n'), ((585, 612), 'numpy.array', 'np.array', (['bbox'], {'dtype': 'float'}), '(bbox, dtype=float)\n', (593, 612), True, 'import numpy as np\n'), ((2624... |
import numpy as np
class NeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate,
weights_input_to_hidden=None, weights_hidden_to_output=None):
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
... | [
"numpy.dot",
"numpy.zeros",
"numpy.exp",
"numpy.random.normal"
] | [((1578, 1622), 'numpy.zeros', 'np.zeros', (['self.weights_input_to_hidden.shape'], {}), '(self.weights_input_to_hidden.shape)\n', (1586, 1622), True, 'import numpy as np\n'), ((1651, 1696), 'numpy.zeros', 'np.zeros', (['self.weights_hidden_to_output.shape'], {}), '(self.weights_hidden_to_output.shape)\n', (1659, 1696)... |
""" This module defines the chi-squared and related functions
Module author: <NAME>
Year: 2020
Email: <EMAIL>
"""
import numpy as np
import model
def chi2_no_soliton(c, Rs, ups_disk, ups_bulg, gal, DM_profile="NFW"):
"""chi2 for an NFW fit (c, Rs; ups_disk, ups_bulg). Runs over a single galaxy
:param c: co... | [
"numpy.abs",
"numpy.sqrt",
"model.M_sol",
"numpy.append",
"numpy.array",
"model.v2_rot",
"numpy.linspace",
"numpy.meshgrid",
"numpy.logspace"
] | [((591, 647), 'model.v2_rot', 'model.v2_rot', (['gal', 'c', 'Rs', 'ups_bulg', 'ups_disk', 'DM_profile'], {}), '(gal, c, Rs, ups_bulg, ups_disk, DM_profile)\n', (603, 647), False, 'import model\n'), ((1994, 2022), 'numpy.linspace', 'np.linspace', (['(1)', '(80)', 'gridsize'], {}), '(1, 80, gridsize)\n', (2005, 2022), Tr... |
import hashlib
import json
import os
from argparse import ArgumentParser, Namespace
from collections import defaultdict
from copy import deepcopy
from functools import partial
from typing import Dict, List, Optional, Type
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch... | [
"torch.utils.data.ConcatDataset",
"model.module.InputVariationalDropout",
"argparse.Namespace",
"constant.LANGUAGE_TO_ISO639.get",
"transformers.AutoTokenizer.from_pretrained",
"copy.deepcopy",
"torch.nn.functional.softmax",
"transformers.AutoModel.from_pretrained",
"argparse.ArgumentParser",
"jso... | [((1536, 1568), 'pytorch_lightning.seed_everything', 'pl.seed_everything', (['hparams.seed'], {}), '(hparams.seed)\n', (1554, 1568), True, 'import pytorch_lightning as pl\n'), ((1595, 1642), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['hparams.pretrain'], {}), '(hparams.pretrain)\n'... |
import numpy as np
from matplotlib import pyplot as plt
from math import *
from scipy.integrate import quad
from scipy.integrate import dblquad
from scipy import integrate
from scipy import special
from numpy import median
from numpy import linspace
from copy import deepcopy
def catoni(w, X, Y, delta, alpha, valpha):... | [
"numpy.zeros",
"numpy.log",
"numpy.var"
] | [((1040, 1051), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (1048, 1051), True, 'import numpy as np\n'), ((856, 869), 'numpy.var', 'np.var', (['ll[k]'], {}), '(ll[k])\n', (862, 869), True, 'import numpy as np\n'), ((1169, 1202), 'numpy.log', 'np.log', (['(1 + xx[k] + xx[k] * xx[k])'], {}), '(1 + xx[k] + xx[k] * xx... |
#!/usr/bin/env python3
import cv2
import numpy as np
import os
from pathlib import Path
from tqdm import tqdm
import settings
cwd = Path(os.path.dirname(__file__))
rollouts = cwd/'rollouts'
def make_csv():
files = []
for i in sorted(rollouts.iterdir()):
trajectory = Path(i)
for file in sor... | [
"os.path.dirname",
"pathlib.Path",
"numpy.random.shuffle"
] | [((141, 166), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (156, 166), False, 'import os\n'), ((508, 532), 'numpy.random.shuffle', 'np.random.shuffle', (['files'], {}), '(files)\n', (525, 532), True, 'import numpy as np\n'), ((1005, 1028), 'numpy.random.shuffle', 'np.random.shuffle', (['dir... |
import numpy as np
import pytest
import psyneulink.core.components.functions.nonstateful.selectionfunctions as Functions
import psyneulink.core.globals.keywords as kw
import psyneulink.core.llvm as pnlvm
from psyneulink.core.globals.utilities import _SeededPhilox
np.random.seed(0)
SIZE=10
test_var = np.random.rand(SI... | [
"numpy.allclose",
"psyneulink.core.globals.utilities._SeededPhilox",
"numpy.random.rand",
"pytest.helpers.get_func_execution",
"pytest.mark.parametrize",
"numpy.random.seed"
] | [((266, 283), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (280, 283), True, 'import numpy as np\n'), ((382, 402), 'numpy.random.rand', 'np.random.rand', (['SIZE'], {}), '(SIZE)\n', (396, 402), True, 'import numpy as np\n'), ((445, 465), 'numpy.random.rand', 'np.random.rand', (['SIZE'], {}), '(SIZE)\n... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from numpy.testing import assert_allclose
try:
import matplotlib.pyplot as plt
HAS_PLT = True
except ImportError:
HAS_PLT = False
t... | [
"matplotlib.pyplot.hist",
"numpy.arange",
"numpy.testing.assert_allclose",
"matplotlib.pyplot.subplots",
"numpy.random.RandomState"
] | [((588, 616), 'numpy.random.RandomState', 'np.random.RandomState', (['rseed'], {}), '(rseed)\n', (609, 616), True, 'import numpy as np\n'), ((942, 970), 'numpy.random.RandomState', 'np.random.RandomState', (['rseed'], {}), '(rseed)\n', (963, 970), True, 'import numpy as np\n'), ((1009, 1024), 'matplotlib.pyplot.subplot... |
import numpy as np
import numba as nb
from pymcx import MCX
def create_props(spec, wavelen):
layers = spec['layers']
lprops = spec['layer_properties']
ext_coeff = {k: np.interp(wavelen, *itr) for k, itr in spec['extinction_coeffs'].items()}
media = np.empty((1+len(layers), 4), np.float32)
media[0]... | [
"numpy.digitize",
"numpy.exp",
"numpy.stack",
"numpy.zeros",
"numba.jit",
"numpy.sum",
"numpy.random.randint",
"numpy.interp",
"numpy.logspace",
"numpy.arange"
] | [((685, 734), 'numba.jit', 'nb.jit', ([], {'nopython': '(True)', 'nogil': '(True)', 'parallel': '(False)'}), '(nopython=True, nogil=True, parallel=False)\n', (691, 734), True, 'import numba as nb\n'), ((1210, 1222), 'numpy.exp', 'np.exp', (['path'], {}), '(path)\n', (1216, 1222), True, 'import numpy as np\n'), ((2442, ... |
#!/usr/bin/env python
# coding:utf8
import lasagne
import numpy as np
import multiverso as mv
class MVNetParamManager(object):
'''
MVNetParamManager is manager to make managing and synchronizing the
variables in lasagne more easily
'''
def __init__(self, network):
''' The constructor of M... | [
"multiverso.barrier",
"numpy.nditer",
"numpy.array",
"lasagne.layers.get_all_param_values",
"numpy.dtype",
"lasagne.layers.set_all_param_values"
] | [((807, 856), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['self.network'], {}), '(self.network)\n', (842, 856), False, 'import lasagne\n'), ((1337, 1366), 'numpy.array', 'np.array', (['self.all_param_list'], {}), '(self.all_param_list)\n', (1345, 1366), True, 'import numpy as np\n'),... |
"""GaussianMLPMultitaskPolicy."""
import akro
import numpy as np
import tensorflow as tf
from metarl.tf.models import GaussianMLPModel
from metarl.tf.policies.multitask_policy import StochasticMultitaskPolicy
class GaussianMLPMultitaskPolicy(StochasticMultitaskPolicy):
"""GaussianMLPMultitaskPolicy.
Args:
... | [
"tensorflow.glorot_uniform_initializer",
"tensorflow.compat.v1.placeholder",
"numpy.random.normal",
"tensorflow.compat.v1.variable_scope",
"tensorflow.variable_scope",
"tensorflow.compat.v1.get_default_session",
"numpy.exp",
"tensorflow.concat",
"tensorflow.zeros_initializer",
"metarl.tf.models.Ga... | [((3612, 3643), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (3641, 3643), True, 'import tensorflow as tf\n'), ((3676, 3698), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (3696, 3698), True, 'import tensorflow as tf\n'), ((3774, 3805), 'tensorf... |
import numpy as np
import matplotlib.pylab as plt
import cv2
from numpy.lib.npyio import save
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import peak_signal_noise_ratio as psnr
import os
from os.path import join as opj
from os.path import exists as ope
from os.path import dirname as o... | [
"os.path.exists",
"matplotlib.pylab.axis",
"numpy.ceil",
"os.makedirs",
"matplotlib.pylab.figure",
"matplotlib.pylab.boxplot",
"matplotlib.pylab.title",
"os.path.join",
"matplotlib.pylab.colorbar",
"matplotlib.pylab.hist",
"matplotlib.pylab.imshow",
"matplotlib.pylab.show",
"matplotlib.pylab... | [((422, 434), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (432, 434), True, 'import matplotlib.pylab as plt\n'), ((439, 455), 'matplotlib.pylab.title', 'plt.title', (['title'], {}), '(title)\n', (448, 455), True, 'import matplotlib.pylab as plt\n'), ((681, 692), 'matplotlib.pylab.close', 'plt.close', ([]... |
""" Defines JSON-format encoding and decoding functions """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Gove... | [
"numpy.dtype",
"base64.b64encode"
] | [((8039, 8064), 'base64.b64encode', '_base64.b64encode', (['py_obj'], {}), '(py_obj)\n', (8056, 8064), True, 'import base64 as _base64\n'), ((16524, 16540), 'numpy.dtype', '_np.dtype', (['descr'], {}), '(descr)\n', (16533, 16540), True, 'import numpy as _np\n')] |
import os
import time
import numpy as np
import argparse
import functools
from PIL import Image
from PIL import ImageDraw
import paddle
import paddle.fluid as fluid
import reader
from mobilenet_ssd import mobile_net
from utility import add_arguments, print_arguments
parser = argparse.ArgumentParser(description=__doc_... | [
"paddle.fluid.DataFeeder",
"reader.infer",
"PIL.Image.open",
"argparse.ArgumentParser",
"reader.Settings",
"paddle.fluid.layers.data",
"paddle.fluid.CPUPlace",
"os.path.join",
"numpy.array",
"PIL.ImageDraw.Draw",
"paddle.fluid.Executor",
"functools.partial",
"paddle.fluid.io.load_vars",
"p... | [((278, 322), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (301, 322), False, 'import argparse\n'), ((333, 383), 'functools.partial', 'functools.partial', (['add_arguments'], {'argparser': 'parser'}), '(add_arguments, argparser=parser)\n', (350, 383)... |
import logging
from metadrive.component.road_network.node_road_network import NodeRoadNetwork
import numpy as np
from panda3d.core import TransparencyAttrib, LineSegs, NodePath
from metadrive.component.lane.circular_lane import CircularLane
from metadrive.component.map.base_map import BaseMap
from metadrive.component... | [
"metadrive.engine.asset_loader.AssetLoader.file_path",
"panda3d.core.NodePath",
"panda3d.core.LineSegs",
"metadrive.utils.get_np_random",
"metadrive.utils.coordinates_shift.panda_position",
"metadrive.utils.norm",
"metadrive.utils.clip",
"numpy.zeros",
"metadrive.utils.scene_utils.ray_localization",... | [((1649, 1704), 'numpy.zeros', 'np.zeros', (['(self.navigation_info_dim,)'], {'dtype': 'np.float32'}), '((self.navigation_info_dim,), dtype=np.float32)\n', (1657, 1704), True, 'import numpy as np\n'), ((5226, 5254), 'metadrive.utils.norm', 'norm', (['dir_vec[0]', 'dir_vec[1]'], {}), '(dir_vec[0], dir_vec[1])\n', (5230,... |
'''stride'''
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"numpy.sqrt",
"mindspore.ops.operations.Zeros",
"mindspore.ops.operations.Transpose",
"mindspore.ops.operations.Concat",
"mindspore.ops.operations.Reshape",
"mindspore.ops.operations.ZerosLike"
] | [((1167, 1178), 'mindspore.ops.operations.Reshape', 'P.Reshape', ([], {}), '()\n', (1176, 1178), True, 'from mindspore.ops import operations as P\n'), ((1204, 1217), 'mindspore.ops.operations.Transpose', 'P.Transpose', ([], {}), '()\n', (1215, 1217), True, 'from mindspore.ops import operations as P\n'), ((1713, 1726), ... |
from typing import List
import numpy as np
class Board:
"""
Represents the state of the game, and says which moves
are available.
"""
def __init__(self, grid: np.ndarray, available):
self.grid = np.copy(grid)
self.available = available
def clone(self):
retu... | [
"numpy.copy"
] | [((233, 246), 'numpy.copy', 'np.copy', (['grid'], {}), '(grid)\n', (240, 246), True, 'import numpy as np\n')] |
from collections import OrderedDict
import json
import xml.etree.ElementTree as ET
import mmcv
import os
import numpy as np
from PIL import Image
from .pipelines import Compose
from mmcv.utils import print_log
from mmdet.core import eval_map, eval_recalls
from .builder import DATASETS
from .xml_style import XMLDatase... | [
"os.path.exists",
"collections.OrderedDict",
"mmcv.utils.print_log",
"os.path.join",
"numpy.array",
"numpy.zeros",
"mmdet.core.eval_map",
"mmdet.core.eval_recalls",
"json.load"
] | [((12242, 12255), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (12253, 12255), False, 'from collections import OrderedDict\n'), ((3045, 3057), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3054, 3057), False, 'import json\n'), ((7056, 7068), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7065, 7068)... |
import numpy as np
import torch
import torchvision.utils as vutils
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#import pandas as pd
import seaborn as sns
sns.set()
sns.set_style('whitegrid')
sns.set_palette('colorblind')
def convert_npimage_torchimage(image):
return 255*torch.transpo... | [
"torch.exp",
"torch.from_numpy",
"seaborn.set_style",
"seaborn.scatterplot",
"torchvision.utils.make_grid",
"numpy.arange",
"seaborn.set",
"numpy.histogram",
"seaborn.color_palette",
"matplotlib.pyplot.close",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"numpy.histogram2d",
"numpy.meshgr... | [((87, 108), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (101, 108), False, 'import matplotlib\n'), ((184, 193), 'seaborn.set', 'sns.set', ([], {}), '()\n', (191, 193), True, 'import seaborn as sns\n'), ((194, 220), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid'... |
import torch
import numpy as np
class FFNet(torch.nn.Module):
"""Simple class to implement a feed-forward neural network in PyTorch.
Attributes:
layers: list of torch.nn.Linear layers to be applied in forward pass.
activation: activation function to be applied between layers.
"""
... | [
"torch.nn.ModuleList",
"torch.flatten",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"numpy.concatenate",
"torch.cat"
] | [((946, 978), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['self.layers'], {}), '(self.layers)\n', (965, 978), False, 'import torch\n'), ((4672, 4717), 'numpy.concatenate', 'np.concatenate', (['([cnn_output_size], ff_shape)'], {}), '(([cnn_output_size], ff_shape))\n', (4686, 4717), True, 'import numpy as np\n'), ((4... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | [
"paddle.static.Executor",
"paddle.CPUPlace",
"numpy.random.random",
"paddle.CUDAPlace",
"paddle.enable_static",
"paddle.fluid.data_feeder.convert_dtype",
"paddle.empty_like",
"paddle.disable_static",
"paddle.static.program_guard",
"numpy.nanmax",
"paddle.static.data",
"numpy.sum",
"unittest.... | [((6230, 6245), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6243, 6245), False, 'import unittest\n'), ((967, 991), 'paddle.fluid.data_feeder.convert_dtype', 'convert_dtype', (['out.dtype'], {}), '(out.dtype)\n', (980, 991), False, 'from paddle.fluid.data_feeder import convert_dtype\n'), ((2279, 2302), 'paddle.... |
import numpy as np
import spenc as spenc
import pysal as ps
import geopandas as gpd
import os
SEED = 1901
dir_self = os.path.dirname(__file__)
datadir = os.path.join(dir_self, 'spenc/tests/data')
if __name__ == "__main__":
nat = gpd.read_file(ps.examples.get_path("NAT.shp"))
natR = ps.weights.Rook.from_datafra... | [
"spenc.SPENC",
"os.path.join",
"os.path.dirname",
"pysal.weights.Rook.from_dataframe",
"numpy.random.seed",
"pysal.examples.get_path"
] | [((117, 142), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (132, 142), False, 'import os\n'), ((153, 195), 'os.path.join', 'os.path.join', (['dir_self', '"""spenc/tests/data"""'], {}), "(dir_self, 'spenc/tests/data')\n", (165, 195), False, 'import os\n'), ((292, 327), 'pysal.weights.Rook.fr... |
import os
import time
import gym
from gym.spaces import Discrete
import haiku as hk
import jax
import jax.numpy as jnp
import jax.random as random
from jax.experimental.optimizers import adam
import numpy as np
from rlax import huber_loss
from jax_baselines import logger
from jax_baselines.common.critic import Discre... | [
"jax_baselines.common.util.make_preprocessor",
"jax_baselines.logger.dumpkvs",
"jax_baselines.common.critic.DiscreteActionCritic",
"jax.numpy.max",
"numpy.array",
"gym.make",
"jax.random.split",
"jax_baselines.dqn.replay.PrioritizedReplayBuffer",
"jax.random.PRNGKey",
"argparse.ArgumentParser",
... | [((1106, 1168), 'jax_baselines.logger.configure', 'logger.configure', ([], {'dir': 'save_dir', 'format_strs': 'logger_format_strs'}), '(dir=save_dir, format_strs=logger_format_strs)\n', (1122, 1168), False, 'from jax_baselines import logger\n'), ((1173, 1202), 'jax_baselines.logger.set_level', 'logger.set_level', (['lo... |
import pandas as pd
from nltk.corpus import stopwords
import numpy as np
import nltk
import re
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
import pprint
train = pd.read_csv("labeledTweet.csv",header=0,\
delimiter="\t", quoting=3)
test = pd.read_csv("testTweet.csv",header=0,\
... | [
"logging.basicConfig",
"nltk.corpus.stopwords.words",
"pandas.read_csv",
"numpy.add",
"gensim.models.word2vec.Word2VecKeyedVectors.load",
"sklearn.ensemble.RandomForestClassifier",
"bs4.BeautifulSoup",
"numpy.zeros",
"nltk.data.load",
"pandas.DataFrame",
"re.sub",
"numpy.divide"
] | [((183, 251), 'pandas.read_csv', 'pd.read_csv', (['"""labeledTweet.csv"""'], {'header': '(0)', 'delimiter': '"""\t"""', 'quoting': '(3)'}), "('labeledTweet.csv', header=0, delimiter='\\t', quoting=3)\n", (194, 251), True, 'import pandas as pd\n'), ((280, 345), 'pandas.read_csv', 'pd.read_csv', (['"""testTweet.csv"""'],... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 2 12:09:14 2021
@author: vohuynhq
"""
import numpy as np
import pandas as pd
from sympy import symbols, init_printing, pi, sqrt, diff, sin, cos, exp
def example(A):
A_true = np.array([[3, 4, 5], [3, 4, 5]])
np.testing.assert_equal(A, A_true)
r... | [
"sympy.sin",
"numpy.mean",
"sympy.cos",
"numpy.testing.assert_equal",
"pandas.read_csv",
"sympy.sqrt",
"sympy.init_printing",
"sympy.symbols",
"numpy.array",
"sympy.diff",
"sympy.exp"
] | [((241, 273), 'numpy.array', 'np.array', (['[[3, 4, 5], [3, 4, 5]]'], {}), '([[3, 4, 5], [3, 4, 5]])\n', (249, 273), True, 'import numpy as np\n'), ((279, 313), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['A', 'A_true'], {}), '(A, A_true)\n', (302, 313), True, 'import numpy as np\n'), ((390, 421), 'sympy... |
"""Validation function"""
import time
import logging
import numpy as np
import torch
from torch import nn
from helpers.miou_utils import compute_iu, compute_ius_accs, fast_cm
from helpers.utils import ctime, try_except
import pdb
import matplotlib.pyplot as plt
logger = logging.getLogger(__name__)
import pylab
cma... | [
"logging.getLogger",
"numpy.mean",
"numpy.prod",
"torch.autograd.Variable",
"helpers.utils.ctime",
"helpers.miou_utils.compute_iu",
"numpy.sum",
"numpy.zeros",
"helpers.miou_utils.compute_ius_accs",
"torch.no_grad",
"numpy.load",
"helpers.miou_utils.fast_cm"
] | [((274, 301), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (291, 301), False, 'import logging\n'), ((324, 351), 'numpy.load', 'np.load', (['"""./utils/cmap.npy"""'], {}), "('./utils/cmap.npy')\n", (331, 351), True, 'import numpy as np\n'), ((1022, 1069), 'numpy.zeros', 'np.zeros', (['(n... |
# tests/test_rms.py
import numpy as np
from kallisto.rmsd import rmsd
from tests.store import propanolIntermediate, propanolLowest
def test_rms():
mol1 = propanolLowest()
nat1 = mol1.get_number_of_atoms()
coord1 = mol1.get_positions()
mol2 = propanolIntermediate()
coord2 = mol2.get_positions()
... | [
"tests.store.propanolLowest",
"numpy.isclose",
"tests.store.propanolIntermediate",
"kallisto.rmsd.rmsd"
] | [((162, 178), 'tests.store.propanolLowest', 'propanolLowest', ([], {}), '()\n', (176, 178), False, 'from tests.store import propanolIntermediate, propanolLowest\n'), ((262, 284), 'tests.store.propanolIntermediate', 'propanolIntermediate', ([], {}), '()\n', (282, 284), False, 'from tests.store import propanolIntermediat... |
# -*- coding: utf-8 -*-
"""
Random forest modeling for radiomics feature selection and
for classification of high-risk histopathological markers of endometrial carcinoma
Not for clinical use.
SPDX-FileCopyrightText: 2021 Medical Physics Unit, McGill University, Montreal, CAN
SPDX-FileCopyrightText: 2021 <NAME>
... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.auc",
"sklearn.metrics.precision_score",
"numpy.argsort",
"numpy.array",
"sklearn.metrics.recall_score",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.roc_curve",
"sklearn.model_selection.StratifiedKFold",
"numpy.count_nonzero",... | [((1190, 1223), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1213, 1223), False, 'import warnings\n'), ((1256, 1307), 'h5py.File', 'h5py.File', (['"""MYPROJECTFILEPATH/OUTPUT/label.h5"""', '"""r"""'], {}), "('MYPROJECTFILEPATH/OUTPUT/label.h5', 'r')\n", (1265, 1307), Fa... |
#! /usr/bin/env python
import numpy as np
def runningMeanFast(x, N):
'''
Calculate the running mean of an array given a window.
Ref: http://stackoverflow.com/questions/13728392/moving-average-or-running-mean
Args:
x (array-like): Data array
N (int): Window width
Returns:
... | [
"numpy.ones"
] | [((411, 424), 'numpy.ones', 'np.ones', (['(N,)'], {}), '((N,))\n', (418, 424), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
# activate function
def step_func(y):
if y>0:
return 1
return 0
# loss function
def loss(y, t):
#return 0.5 * (np.sum(y-t)**2)
return 0.5*(y-t)
class Neuron :
def __init__(self, input_len):
#self.x = np.zeros(input_len) # input_v... | [
"numpy.random.rand",
"matplotlib.pyplot.plot",
"numpy.dot",
"numpy.random.randint",
"matplotlib.pyplot.show"
] | [((385, 410), 'numpy.random.rand', 'np.random.rand', (['input_len'], {}), '(input_len)\n', (399, 410), True, 'import numpy as np\n'), ((1327, 1389), 'numpy.random.randint', 'np.random.randint', (['max_purchase_num'], {'size': 'self.sweets_type_num'}), '(max_purchase_num, size=self.sweets_type_num)\n', (1344, 1389), Tru... |
import tensorflow as tf
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model_path", type=str, default='model.tflite', help="path to tflite model")
args = ap.parse_args()
# Load MNIST dataset
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_la... | [
"numpy.sum",
"numpy.expand_dims",
"argparse.ArgumentParser"
] | [((65, 90), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (88, 90), False, 'import argparse\n'), ((543, 575), 'numpy.expand_dims', 'np.expand_dims', (['train_images', '(-1)'], {}), '(train_images, -1)\n', (557, 575), True, 'import numpy as np\n'), ((590, 621), 'numpy.expand_dims', 'np.expand_d... |
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
import h5py
import matplotlib.pyplot as plt
import random
from torch.utils.data import Dataset, DataLoader, random_split
import torch.nn as nn
import torch.optim as optim
import os
from tqdm import tqdm
import time
import pickle
i... | [
"torch.nn.CrossEntropyLoss",
"torch.nn.MSELoss",
"matplotlib.pyplot.imshow",
"numpy.mean",
"os.path.isdir",
"umetrics.calculate",
"os.mkdir",
"torch.split",
"numpy.argmax",
"numpy.squeeze",
"matplotlib.pyplot.title",
"time.time",
"torch.cuda.empty_cache",
"matplotlib.pyplot.show",
"torch... | [((565, 577), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (575, 577), True, 'import torch.nn as nn\n'), ((1041, 1133), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'self.batch_size', 'num_workers': 'num_workers', 'shuffle': '(True)'}), '(train_set, batch_size=self.batch_size, num_... |
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
from ahfhalotools.objects import Cluster
import ahfhalotools.filetools as ft
import ahfhalotools.analysis as analysis
## -----------Load Cluster Instances--------------##
#define base file name (these are for full files)
fileNameBa... | [
"ahfhalotools.filetools.getMusZs",
"ahfhalotools.filetools.getSnapNumToZMapGiz",
"ahfhalotools.objects.Cluster",
"numpy.array",
"matplotlib.pyplot.tight_layout",
"ahfhalotools.analysis.tfromz",
"ahfhalotools.filetools.getSnapNumToZMapGX",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.p... | [((643, 661), 'numpy.arange', 'np.arange', (['(97)', '(129)'], {}), '(97, 129)\n', (652, 661), True, 'import numpy as np\n'), ((674, 692), 'numpy.arange', 'np.arange', (['(97)', '(129)'], {}), '(97, 129)\n', (683, 692), True, 'import numpy as np\n'), ((779, 798), 'ahfhalotools.filetools.getMusZs', 'ft.getMusZs', (['mus... |
import geopandas as gpd
import pandas as pd
import xarray as xr
import numpy as np
from pathlib import Path
import sys
import netCDF4
import datetime
import metpy.calc as mpcalc
from metpy.units import units
# prsr = 101.3 * (((293.0-0.0065*Hru_elev_meters(i))/293.0)**5.26)
def std_pres(elev):
return 101.325 * ((... | [
"numpy.ma.average",
"metpy.calc.relative_humidity_from_specific_humidity",
"geopandas.read_file",
"pathlib.Path",
"numpy.average",
"pandas.read_csv",
"numpy.asarray",
"datetime.datetime.now",
"numpy.zeros",
"numpy.isnan",
"metpy.units.units",
"sys.exit",
"metpy.units.units.Quantity",
"nump... | [((1163, 1198), 'numpy.ma.average', 'np.ma.average', (['mdata'], {'weights': 'wghts'}), '(mdata, weights=wghts)\n', (1176, 1198), True, 'import numpy as np\n'), ((410, 441), 'numpy.average', 'np.average', (['data'], {'weights': 'wghts'}), '(data, weights=wghts)\n', (420, 441), True, 'import numpy as np\n'), ((1136, 115... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
## Autor: <NAME>
import numpy as np
from bubble2 import Bubble2
from bworld import Bworld
n = 1000
bubbles = []
bubbles.append(Bubble2(np.random.rand(n, 3) * 10, np.zeros((n, 3)),
radius = (np.random.rand(n) / 6), color = (0.5, 0.8, 1.0, 0.8)))
testworld = B... | [
"numpy.zeros",
"numpy.asarray",
"numpy.random.rand"
] | [((207, 223), 'numpy.zeros', 'np.zeros', (['(n, 3)'], {}), '((n, 3))\n', (215, 223), True, 'import numpy as np\n'), ((348, 387), 'numpy.asarray', 'np.asarray', (['[[0, 20], [0, 10], [0, 10]]'], {}), '([[0, 20], [0, 10], [0, 10]])\n', (358, 387), True, 'import numpy as np\n'), ((180, 200), 'numpy.random.rand', 'np.rando... |
"""
This module provides helpers that describe some aspect of a layout.
The two public classes are:
* BasisBladeOrder
* BasisVectorIds
"""
from typing import TypeVar, Generic, Sequence, Tuple, List, Optional
import numpy as np
import functools
import operator
from . import _numba_utils
from ._bit_helpers import co... | [
"functools.reduce",
"numpy.array",
"numpy.empty",
"numpy.array_equal",
"numpy.bitwise_or.reduce",
"numpy.full",
"typing.TypeVar"
] | [((4666, 4680), 'typing.TypeVar', 'TypeVar', (['"""IdT"""'], {}), "('IdT')\n", (4673, 4680), False, 'from typing import TypeVar, Generic, Sequence, Tuple, List, Optional\n'), ((1879, 1907), 'numpy.array', 'np.array', (['bitmaps'], {'dtype': 'int'}), '(bitmaps, dtype=int)\n', (1887, 1907), True, 'import numpy as np\n'),... |
from __future__ import absolute_import
from builtins import next
from builtins import range
import os
import math
import os.path as op
import re
import shutil
from nipype.interfaces.base import (
TraitedSpec, traits, BaseInterface, File,
Directory, CommandLineInputSpec, CommandLine, DynamicTraitedSpec,
Base... | [
"nipype.interfaces.base.OutputMultiPath",
"itertools.chain",
"nipype.interfaces.base.InputMultiPath",
"re.compile",
"nipype.interfaces.base.traits.Bool",
"numpy.array",
"arcana.exceptions.ArcanaUsageError",
"math.log10",
"nipype.interfaces.base.Directory",
"os.listdir",
"nipype.interfaces.base.t... | [((935, 968), 'os.path.join', 'op.join', (['bash_resources', '"""zip.sh"""'], {}), "(bash_resources, 'zip.sh')\n", (942, 968), True, 'import os.path as op\n'), ((982, 1017), 'os.path.join', 'op.join', (['bash_resources', '"""targz.sh"""'], {}), "(bash_resources, 'targz.sh')\n", (989, 1017), True, 'import os.path as op\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.