code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from __future__ import division
from __future__ import absolute_import
from builtins import object
from past.utils import old_div
from nose.tools import (assert_equal, assert_not_equal, raises,
assert_almost_equal)
from nose.plugins.skip import SkipTest
from .test_helpers import assert_items_alm... | [
"logging.getLogger",
"numpy.testing.assert_allclose",
"numpy.log",
"past.utils.old_div",
"numpy.array",
"nose.tools.raises",
"pandas.DataFrame",
"openpathsampling.numerics.WHAM"
] | [((7392, 7412), 'nose.tools.raises', 'raises', (['RuntimeError'], {}), '(RuntimeError)\n', (7398, 7412), False, 'from nose.tools import assert_equal, assert_not_equal, raises, assert_almost_equal\n'), ((7906, 7926), 'nose.tools.raises', 'raises', (['RuntimeError'], {}), '(RuntimeError)\n', (7912, 7926), False, 'from no... |
#/usr/bin/env python
from os.path import join, split
import numpy as np
import matplotlib.pyplot as plt
import pandas
from dtk import process
from gaitanalysis import gait, controlid
from gaitanalysis.utils import _percent_formatter
directory = split(__file__)[0]
perturbation_data = gait.WalkingData(join(directory,... | [
"numpy.ones_like",
"numpy.sqrt",
"numpy.hstack",
"gaitanalysis.controlid.SimpleControlSolver",
"os.path.join",
"os.path.split",
"numpy.argsort",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.tight_layout",
"numpy.linalg.norm",
"matplotlib.pyplot.subplots",
"dtk.process.coefficient_of... | [((1197, 1270), 'gaitanalysis.controlid.SimpleControlSolver', 'controlid.SimpleControlSolver', (['perturbation_data.steps', 'sensors', 'controls'], {}), '(perturbation_data.steps, sensors, controls)\n', (1226, 1270), False, 'from gaitanalysis import gait, controlid\n'), ((2152, 2179), 'matplotlib.pyplot.rcParams.update... |
# -*- coding: utf-8 -*-
"""
Algorithms for TableDataExtractor.
.. codeauthor:: <NAME> <<EMAIL>>
"""
import logging
import numpy as np
from sympy import Symbol
from sympy import factor_list, factor
from tabledataextractor.exceptions import MIPSError
from tabledataextractor.table.parse import StringParser, CellParser... | [
"logging.getLogger",
"numpy.copy",
"numpy.insert",
"sympy.Symbol",
"tabledataextractor.table.parse.StringParser",
"numpy.full_like",
"numpy.unique",
"numpy.delete",
"numpy.sort",
"tabledataextractor.table.parse.CellParser",
"numpy.core.defchararray.replace",
"numpy.array_equal",
"numpy.vstac... | [((329, 356), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (346, 356), False, 'import logging\n'), ((744, 763), 'tabledataextractor.table.parse.StringParser', 'StringParser', (['regex'], {}), '(regex)\n', (756, 763), False, 'from tabledataextractor.table.parse import StringParser, CellP... |
import sys
import numpy as np
#import preprocess_blockSVD as pre_svd
import multiprocessing
import time
import matplotlib.pyplot as plt
#import greedyPCA_SV as gpca
#import greedyPCA as gpca
from math import ceil
from functools import partial
from itertools import product
# compute single mean_th factor for all tiles... | [
"numpy.prod",
"matplotlib.pyplot.ylabel",
"multiprocessing.Process",
"multiprocessing.cpu_count",
"numpy.array_split",
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"itertools.product",
"numpy.asarray",
"numpy.diff",
"numpy... | [((3485, 3510), 'numpy.append', 'np.append', (['d_row', 'dims[0]'], {}), '(d_row, dims[0])\n', (3494, 3510), True, 'import numpy as np\n'), ((3522, 3547), 'numpy.append', 'np.append', (['d_col', 'dims[1]'], {}), '(d_col, dims[1])\n', (3531, 3547), True, 'import numpy as np\n'), ((3782, 3813), 'numpy.zeros', 'np.zeros',... |
import wx
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigureCanvas, \
NavigationToolbar2WxAgg as NavigationToolbar
class Overview(wx.Panel):
def __init__(self, ParentFrame, Data):
# Create Data Frame win... | [
"matplotlib.backends.backend_wxagg.FigureCanvasWxAgg",
"numpy.ptp",
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"numpy.array",
"wx.EVT_CHECKBOX",
"wx.Panel.__init__",
"numpy.arange",
"numpy.where",
"matplotlib.pyplot.xlabel",
"wx.CheckBox",
"numpy.vstack",
"numpy.round",
"wx.EVT_COMBOBOX",
... | [((35587, 35627), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'facecolor': '(0.95, 0.95, 0.95)'}), '(facecolor=(0.95, 0.95, 0.95))\n', (35597, 35627), True, 'from matplotlib import pyplot as plt\n'), ((35647, 35689), 'matplotlib.backends.backend_wxagg.FigureCanvasWxAgg', 'FigureCanvas', (['self', 'wx.ID_ANY', 'self... |
import numpy as np
import pytest
from numpy.testing import assert_almost_equal, assert_raises, assert_warns
from ...tools import linear, power
from .. import Dcorr
class TestDcorrStat:
@pytest.mark.parametrize("n", [100, 200])
@pytest.mark.parametrize("obs_stat", [1.0])
@pytest.mark.parametrize("obs_pval... | [
"pytest.mark.parametrize",
"numpy.random.seed",
"numpy.testing.assert_almost_equal"
] | [((193, 233), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n"""', '[100, 200]'], {}), "('n', [100, 200])\n", (216, 233), False, 'import pytest\n'), ((239, 281), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""obs_stat"""', '[1.0]'], {}), "('obs_stat', [1.0])\n", (262, 281), False, 'import pyt... |
import os
import random
import pathlib
from unittest.mock import patch
import numpy as np
from word_vectors import FileType
from word_vectors.read import read
from word_vectors.convert import convert
from utils import vocab, vectors, DATA, GLOVE, W2V, W2V_TEXT, LEADER, rand_str
INPUT_MAPPING = {
GLOVE: FileType.G... | [
"random.choice",
"word_vectors.convert.convert",
"numpy.testing.assert_allclose",
"os.path.splitext",
"utils.rand_str",
"word_vectors.read.read",
"unittest.mock.patch",
"os.remove"
] | [((446, 491), 'random.choice', 'random.choice', (['[GLOVE, W2V, W2V_TEXT, LEADER]'], {}), '([GLOVE, W2V, W2V_TEXT, LEADER])\n', (459, 491), False, 'import random\n'), ((1099, 1144), 'random.choice', 'random.choice', (['[GLOVE, W2V, W2V_TEXT, LEADER]'], {}), '([GLOVE, W2V, W2V_TEXT, LEADER])\n', (1112, 1144), False, 'im... |
"""
Matching pennies environment.
"""
import gym
import numpy as np
from gym.spaces import Discrete, Tuple
from .common import OneHot
class IteratedMatchingPennies(gym.Env):
"""
A two-agent vectorized environment for the Matching Pennies game.
"""
NAME = 'IMP'
NUM_AGENTS = 2
NUM_ACTIONS = 2
... | [
"numpy.array",
"numpy.zeros",
"gym.spaces.Discrete"
] | [((436, 464), 'numpy.array', 'np.array', (['[[1, -1], [-1, 1]]'], {}), '([[1, -1], [-1, 1]])\n', (444, 464), True, 'import numpy as np\n'), ((778, 803), 'numpy.zeros', 'np.zeros', (['self.NUM_STATES'], {}), '(self.NUM_STATES)\n', (786, 803), True, 'import numpy as np\n'), ((1084, 1109), 'numpy.zeros', 'np.zeros', (['se... |
#!/usr/bin/env python
# Filename: planet_svm_classify
"""
introduction: Using SVM in sklearn library to perform classification on Planet images
authors: <NAME>
email:<EMAIL>
add time: 4 January, 2019
"""
import sys, os
from optparse import OptionParser
import rasterio
import numpy as np
HOME = os.path.expanduser('~... | [
"sys.path.insert",
"sklearn.externals.joblib.load",
"multiprocessing.cpu_count",
"basic_src.basic.outputlogMessage",
"sys.exit",
"basic_src.io_function.is_file_exist",
"numpy.concatenate",
"datasets.build_RS_data.make_dataset",
"os.path.expanduser",
"numpy.ones",
"datasets.build_RS_data.read_pat... | [((299, 322), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (317, 322), False, 'import sys, os\n'), ((391, 420), 'sys.path.insert', 'sys.path.insert', (['(0)', 'codes_dir'], {}), '(0, codes_dir)\n', (406, 420), False, 'import sys, os\n'), ((559, 589), 'sys.path.insert', 'sys.path.insert', ([... |
#!/usr/bin/env python3
from __future__ import division
from builtins import str
from builtins import range
from builtins import object
from past.utils import old_div
import isce
from isceobj.Scene.Frame import Frame
from isceobj.Planet.AstronomicalHandbook import Const
from isceobj.Planet.Planet import Planet
from Sen... | [
"numpy.mean",
"traceback.format_exc",
"FrameInfoExtractor.FrameInfoExtractor",
"argparse.ArgumentParser",
"re.compile",
"json.dumps",
"builtins.str",
"past.utils.old_div",
"Sentinel1_TOPS.Sentinel1_TOPS",
"numpy.array",
"builtins.range",
"isceobj.Scene.Frame.Frame",
"lxml.objectify.parse",
... | [((603, 628), 're.compile', 're.compile', (['"""-(raw|slc)-"""'], {}), "('-(raw|slc)-')\n", (613, 628), False, 'import os, sys, re, requests, json, shutil, traceback, logging, hashlib, math\n'), ((644, 665), 're.compile', 're.compile', (['"""S1(\\\\w)"""'], {}), "('S1(\\\\w)')\n", (654, 665), False, 'import os, sys, re... |
import numpy as np
from numba import njit, b1, i1, int64, float64
@njit(b1(i1[:, :], i1, i1))
def was_winning_move(board, row, col):
if col == -1:
return False
player = board[row, col]
player_pieces = board == player
win_len = 4
row_win = player_pieces[row, :]
for i in range(row_win.s... | [
"numba.b1",
"numpy.random.choice",
"numpy.where",
"numpy.diag",
"numpy.array",
"numpy.zeros",
"numba.float64",
"time.time"
] | [((423, 456), 'numpy.diag', 'np.diag', (['player_pieces', '(col - row)'], {}), '(player_pieces, col - row)\n', (430, 456), True, 'import numpy as np\n'), ((613, 659), 'numpy.diag', 'np.diag', (['player_pieces[:, ::-1]', '(new_col - row)'], {}), '(player_pieces[:, ::-1], new_col - row)\n', (620, 659), True, 'import nump... |
import argparse
import matplotlib.pyplot as plt
import numpy as np
import torch
from sklearn.manifold import TSNE
from src.data.make_dataset import CorruptMnist
from src.models.model import MyAwesomeModel
def tsne_embedding_plot() -> None:
parser = argparse.ArgumentParser(description="Training arguments")
p... | [
"matplotlib.pyplot.savefig",
"numpy.unique",
"src.models.model.MyAwesomeModel",
"argparse.ArgumentParser",
"torch.load",
"sklearn.manifold.TSNE",
"torch.cat",
"torch.cuda.is_available",
"src.data.make_dataset.CorruptMnist",
"torch.utils.data.DataLoader",
"torch.no_grad",
"matplotlib.pyplot.leg... | [((257, 314), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Training arguments"""'}), "(description='Training arguments')\n", (280, 314), False, 'import argparse\n'), ((433, 508), 'src.data.make_dataset.CorruptMnist', 'CorruptMnist', ([], {'train': '(True)', 'in_folder': '"""data/raw"""... |
import numpy as np
import tensorflow as tf
from .sac import SAC, td_target
from softlearning.misc.utils import mixup
from softlearning.models.utils import flatten_input_structure
class SACClassifierMultiGoal(SAC):
def __init__(
self,
classifiers,
goal_example_pools,
goal_example_v... | [
"tensorflow.contrib.layers.optimize_loss",
"numpy.mean",
"tensorflow.equal",
"numpy.ones",
"softlearning.models.utils.flatten_input_structure",
"tensorflow.placeholder",
"numpy.std",
"numpy.max",
"tensorflow.where",
"numpy.random.randint",
"numpy.split",
"numpy.zeros",
"numpy.concatenate",
... | [((1715, 1773), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 1)', 'name': '"""labels"""'}), "(tf.float32, shape=(None, 1), name='labels')\n", (1729, 1773), True, 'import tensorflow as tf\n'), ((3061, 3188), 'softlearning.models.utils.flatten_input_structure', 'flatten_input_structure',... |
import numpy as np
from prml.linear.classifier import Classifier
class Perceptron(Classifier):
"""
Perceptron model
"""
def fit(self, X, t, max_epoch=100):
"""
fit perceptron model on given input pair
Parameters
----------
X : (N, D) np.ndarray
tra... | [
"numpy.size",
"numpy.sign"
] | [((560, 573), 'numpy.size', 'np.size', (['X', '(1)'], {}), '(X, 1)\n', (567, 573), True, 'import numpy as np\n'), ((1171, 1190), 'numpy.sign', 'np.sign', (['(X @ self.w)'], {}), '(X @ self.w)\n', (1178, 1190), True, 'import numpy as np\n'), ((632, 651), 'numpy.sign', 'np.sign', (['(X @ self.w)'], {}), '(X @ self.w)\n',... |
# Original code by:
# <NAME>: Mapping Your Music Collection
# http://www.christianpeccei.com/musicmap/
import numpy as np
import os
import struct
import wave
from shlex import split
from subprocess import call
from uuid import uuid4
class Analyzer:
FEATURES_LENGTH = 42
SECONDS_PER_SONG = 90
SAMPLING... | [
"wave.open",
"shlex.split",
"numpy.fft.fft",
"uuid.uuid4",
"numpy.array_split",
"numpy.array",
"numpy.zeros",
"struct.unpack",
"os.remove"
] | [((710, 729), 'numpy.fft.fft', 'np.fft.fft', (['wavdata'], {}), '(wavdata)\n', (720, 729), True, 'import numpy as np\n'), ((825, 846), 'numpy.array_split', 'np.array_split', (['f', '(10)'], {}), '(f, 10)\n', (839, 846), True, 'import numpy as np\n'), ((969, 983), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (... |
import re
import numpy as np
from rdkit import Chem
from rdkit.Chem.rdchem import ChiralType
from EFGs import standize
pat = r'\d+(?:\.\d+)?%'
p2f = lambda x: float(x.strip('%'))/100
def mols_from_smiles_list(all_smiles):
'''Given a list of smiles strings, this function creates rdkit
molecules'''
mols =... | [
"numpy.abs",
"rdkit.Chem.MolFragmentToSmiles",
"numpy.average",
"rdkit.Chem.MolFromSmiles",
"re.sub",
"re.findall",
"EFGs.standize"
] | [((492, 522), 're.sub', 're.sub', (['"""\\\\[2H\\\\]"""', '"""[H]"""', 'smi'], {}), "('\\\\[2H\\\\]', '[H]', smi)\n", (498, 522), False, 'import re\n'), ((3664, 3798), 'rdkit.Chem.MolFragmentToSmiles', 'Chem.MolFragmentToSmiles', (['mol', 'ids_to_include'], {'isomericSmiles': '(True)', 'atomSymbols': 'symbols', 'allBon... |
#!/usr/bin/env python
import pickle
import tensorflow as tf
import numpy as np
import tf_util
import gym
import load_policy
from tensorflow import keras
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('behavioral_cloning_file', type=str)
parser.add_argument('envname'... | [
"numpy.mean",
"argparse.ArgumentParser",
"tensorflow.keras.models.load_model",
"numpy.std",
"gym.make"
] | [((200, 225), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (223, 225), False, 'import argparse\n'), ((655, 708), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['args.behavioral_cloning_file'], {}), '(args.behavioral_cloning_file)\n', (678, 708), False, 'from tensorflow imp... |
import sys
assert sys.version_info[0] == 2
import rosbag
import numpy as np
from rospy_message_converter import message_converter
bag = rosbag.Bag('out.bag')
nb_event = 0
x_fin = []
y_fin = []
ts_fin = []
p_fin = []
for topic, msg, t in bag.read_messages(topics=['/cam0/events']):
msg_str = message_converter.conver... | [
"rospy_message_converter.message_converter.convert_ros_message_to_dictionary",
"numpy.concatenate",
"numpy.save",
"rosbag.Bag"
] | [((137, 158), 'rosbag.Bag', 'rosbag.Bag', (['"""out.bag"""'], {}), "('out.bag')\n", (147, 158), False, 'import rosbag\n'), ((1014, 1037), 'numpy.save', 'np.save', (['"""x.npy"""', 'x_fin'], {}), "('x.npy', x_fin)\n", (1021, 1037), True, 'import numpy as np\n'), ((1038, 1061), 'numpy.save', 'np.save', (['"""y.npy"""', '... |
import numpy as np
import math
import sys, copy
sys.path.insert(0,'../Robots')
import robot_toy_example as robot_moel
import uvs as uvss
import time
robot = robot_moel.toy_blocks_robot()
estimate_jacobian_random_motion_range = [2, 5]
step_normalize_range = [2, 3]
uvs = uvss.UVS(robot, 0.5, 0.1, 2, step_normalize_rang... | [
"numpy.asarray",
"sys.path.insert",
"uvs.UVS",
"robot_toy_example.toy_blocks_robot"
] | [((48, 79), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../Robots"""'], {}), "(0, '../Robots')\n", (63, 79), False, 'import sys, copy\n'), ((159, 188), 'robot_toy_example.toy_blocks_robot', 'robot_moel.toy_blocks_robot', ([], {}), '()\n', (186, 188), True, 'import robot_toy_example as robot_moel\n'), ((272, 365)... |
import os
from pyscf.pbc.gto import Cell
from pyscf.pbc.scf import KRHF
from pyscf.pbc.tdscf import KTDHF
from pyscf.pbc.tdscf import krhf_slow_gamma as ktd
import unittest
from numpy import testing
import numpy
from test_common import retrieve_m, retrieve_m_hf, assert_vectors_close, tdhf_frozen_mask
class DiamondT... | [
"test_common.tdhf_frozen_mask",
"test_common.retrieve_m_hf",
"numpy.testing.assert_allclose",
"pyscf.pbc.tdscf.krhf_slow_gamma.TDRHF",
"os.path.join",
"pyscf.pbc.tdscf.KTDHF",
"numpy.array",
"pyscf.pbc.scf.KRHF",
"test_common.retrieve_m",
"pyscf.pbc.gto.Cell"
] | [((517, 523), 'pyscf.pbc.gto.Cell', 'Cell', ([], {}), '()\n', (521, 523), False, 'from pyscf.pbc.gto import Cell\n'), ((1296, 1313), 'pyscf.pbc.tdscf.KTDHF', 'KTDHF', (['model_krhf'], {}), '(model_krhf)\n', (1301, 1313), False, 'from pyscf.pbc.tdscf import KTDHF\n'), ((1366, 1391), 'test_common.retrieve_m', 'retrieve_m... |
import os
import cv2
import numpy as np
import torch
import imageio
from torchvision import transforms
from .colmap_utils import *
import pdb
def load_img_list(datadir, load_test=False):
with open(os.path.join(datadir, 'train.txt'), 'r') as f:
lines = f.readlines()
image_list = [line.strip() for l... | [
"numpy.uint8",
"cv2.applyColorMap",
"os.path.exists",
"PIL.Image.open",
"imageio.imread",
"cv2.resize",
"torch.stack",
"os.path.join",
"numpy.logical_not",
"numpy.stack",
"numpy.isnan",
"numpy.isfinite",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"numpy.load",
... | [((642, 685), 'os.path.join', 'os.path.join', (['datadir', '"""dense"""', '"""fused.ply"""'], {}), "(datadir, 'dense', 'fused.ply')\n", (654, 685), False, 'import os\n'), ((2702, 2718), 'numpy.stack', 'np.stack', (['depths'], {}), '(depths)\n', (2710, 2718), True, 'import numpy as np\n'), ((3090, 3111), 'torchvision.tr... |
import numpy as np
import pandas as pd
import pymongo
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import load_model
import os
import glob
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
mo... | [
"pandas.Series",
"selenium.webdriver.chrome.options.Options",
"pandas.read_csv",
"numpy.average",
"selenium.webdriver.Chrome",
"os.rename",
"numpy.floor",
"time.sleep",
"sklearn.preprocessing.StandardScaler",
"os.path.realpath",
"numpy.random.randint",
"numpy.array",
"tensorflow.keras.models... | [((328, 352), 'tensorflow.keras.models.load_model', 'load_model', (['"""model_2249"""'], {}), "('model_2249')\n", (338, 352), False, 'from tensorflow.keras.models import load_model\n'), ((363, 387), 'tensorflow.keras.models.load_model', 'load_model', (['"""model_5699"""'], {}), "('model_5699')\n", (373, 387), False, 'f... |
import numpy as np
from collections import namedtuple
from itertools import product
import pybullet as p
from pybullet_planning.utils import CLIENT, BASE_LINK, UNKNOWN_FILE, OBJ_MESH_CACHE
from pybullet_planning.utils import implies
#####################################
# Bounding box
AABB = namedtuple('AABB', ['lo... | [
"collections.namedtuple",
"pybullet.getAABB",
"numpy.less_equal",
"pybullet_planning.interfaces.robots.link.get_all_links",
"numpy.max",
"pybullet.getOverlappingObjects",
"numpy.array",
"numpy.vstack",
"numpy.min",
"pybullet_planning.interfaces.robots.link.get_link_subtree"
] | [((297, 335), 'collections.namedtuple', 'namedtuple', (['"""AABB"""', "['lower', 'upper']"], {}), "('AABB', ['lower', 'upper'])\n", (307, 335), False, 'from collections import namedtuple\n'), ((3897, 3958), 'pybullet.getOverlappingObjects', 'p.getOverlappingObjects', (['lower', 'upper'], {'physicsClientId': 'CLIENT'}),... |
#
# Copyright 2018-2021 <NAME>
# 2019 <NAME>
# 2015-2016 <NAME>
#
# ### MIT license
#
# 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 withou... | [
"numpy.append",
"numpy.array"
] | [((5676, 5700), 'numpy.array', 'np.array', (['magnifications'], {}), '(magnifications)\n', (5684, 5700), True, 'import numpy as np\n'), ((5702, 5722), 'numpy.array', 'np.array', (['bandwidths'], {}), '(bandwidths)\n', (5710, 5722), True, 'import numpy as np\n'), ((5724, 5745), 'numpy.array', 'np.array', (['rms_heights'... |
# Feb 9, 2019
# <NAME>, <NAME>, <NAME>, <NAME>
#
# This script tests the distance function for kmedians.py
import pytest
import numpy as np
from KMediansPy.distance import distance
## Helper Functions
def toy_data():
"""
Generates simple data set and parameters to test
"""
X = np.array([[1, 2],[5,... | [
"numpy.array",
"KMediansPy.distance.distance",
"numpy.all"
] | [((300, 326), 'numpy.array', 'np.array', (['[[1, 2], [5, 4]]'], {}), '([[1, 2], [5, 4]])\n', (308, 326), True, 'import numpy as np\n'), ((340, 366), 'numpy.array', 'np.array', (['[[1, 2], [5, 4]]'], {}), '([[1, 2], [5, 4]])\n', (348, 366), True, 'import numpy as np\n'), ((377, 397), 'KMediansPy.distance.distance', 'dis... |
from multiprocessing import Pool
import numpy as np
import pandas as pd
from cgms_data_seg import CGMSDataSeg
from sklearn.model_selection import KFold
def hyperglycemia(x, threshold=1.8):
return np.hstack((x >= threshold, x < threshold)).astype(np.float32)
def hypoglycemia(x, threshold=0.7):
# threshold c... | [
"pandas.Series",
"numpy.ceil",
"pandas.read_csv",
"numpy.hstack",
"numpy.argmax",
"numpy.apply_along_axis",
"multiprocessing.Pool",
"pandas.DataFrame",
"cgms_data_seg.CGMSDataSeg",
"pandas.ExcelWriter"
] | [((1171, 1211), 'pandas.read_csv', 'pd.read_csv', (['"""../data/tblAScreening.csv"""'], {}), "('../data/tblAScreening.csv')\n", (1182, 1211), True, 'import pandas as pd\n'), ((1222, 1256), 'pandas.read_csv', 'pd.read_csv', (['"""../data/tblALab.csv"""'], {}), "('../data/tblALab.csv')\n", (1233, 1256), True, 'import pan... |
import numpy as np
import glob
cannon_teff = np.array([])
cannon_logg = np.array([])
cannon_feh = np.array([])
cannon_alpha = np.array([])
tr_teff = np.array([])
tr_logg = np.array([])
tr_feh = np.array([])
tr_alpha = np.array([])
a = glob.glob("./*tr_label.npz")
a.sort()
for filename in a:
labels = np.load(fil... | [
"numpy.savez",
"numpy.append",
"numpy.array",
"numpy.vstack",
"numpy.load",
"glob.glob"
] | [((46, 58), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (54, 58), True, 'import numpy as np\n'), ((73, 85), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (81, 85), True, 'import numpy as np\n'), ((99, 111), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (107, 111), True, 'import numpy as np\n'), ((127, ... |
import unittest
import numpy as np
from algorithms.genetic.nsgaii.nsgaii_algorithm import NSGAIIAlgorithm as tested_algorithm_class
class NSGAIITestCase(unittest.TestCase):
def setUp(self):
"""
Set up algorithm and random seed
"""
seed = 0
self.algorithm = tested_algorith... | [
"numpy.testing.assert_array_equal",
"numpy.around",
"algorithms.genetic.nsgaii.nsgaii_algorithm.NSGAIIAlgorithm"
] | [((305, 329), 'algorithms.genetic.nsgaii.nsgaii_algorithm.NSGAIIAlgorithm', 'tested_algorithm_class', ([], {}), '()\n', (327, 329), True, 'from algorithms.genetic.nsgaii.nsgaii_algorithm import NSGAIIAlgorithm as tested_algorithm_class\n'), ((8993, 9031), 'numpy.around', 'np.around', (['actual_crowding_distance', '(2)'... |
"""Training procedure for real NVP.
"""
import argparse
import torch, torchvision
import torch.distributions as distributions
import torch.optim as optim
import torchvision.utils as utils
import numpy as np
import realnvp, data_utils
class Hyperparameters():
def __init__(self, base_dim, res_blocks, bottleneck, ... | [
"torchvision.utils.make_grid",
"argparse.ArgumentParser",
"numpy.log",
"torch.no_grad",
"torch.tensor",
"torch.save",
"torch.utils.data.DataLoader",
"data_utils.load",
"realnvp.RealNVP",
"data_utils.logit_transform",
"torch.device"
] | [((1247, 1269), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1259, 1269), False, 'import torch, torchvision\n'), ((2245, 2269), 'data_utils.load', 'data_utils.load', (['dataset'], {}), '(dataset)\n', (2260, 2269), False, 'import realnvp, data_utils\n'), ((2289, 2386), 'torch.utils.data.DataL... |
import numpy as np
from copy import deepcopy
import config
class Node:
'''
Attribute
----------
board : Board
This node's board Class.
cpuct : floar
c puct constance.
w : float
Value this node ever got.
n : int
How many times this node ever simulated.
c... | [
"numpy.log",
"numpy.sqrt",
"numpy.argmax",
"copy.deepcopy"
] | [((1910, 1920), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (1917, 1920), True, 'import numpy as np\n'), ((3617, 3632), 'copy.deepcopy', 'deepcopy', (['board'], {}), '(board)\n', (3625, 3632), False, 'from copy import deepcopy\n'), ((2258, 2275), 'numpy.argmax', 'np.argmax', (['values'], {}), '(values)\n', (2267, 22... |
import os
import sys
import numpy as np
import torch
import argparse
import _pickle as pkl
import matplotlib.pylab as plt
import seaborn as sea
sea.set_style("whitegrid")
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from random import uniform
from .Protein import Protein
from .Complex import Complex
f... | [
"numpy.abs",
"matplotlib.pylab.figure",
"torch.exp",
"torch.min",
"seaborn.set_style",
"torch.tensor",
"matplotlib.pylab.show",
"matplotlib.pylab.subplot",
"torch.logical_and"
] | [((145, 171), 'seaborn.set_style', 'sea.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (158, 171), True, 'import seaborn as sea\n'), ((4156, 4183), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (4166, 4183), True, 'import matplotlib.pylab as plt\n'), ((4267, 42... |
from osim.env import L2M2019Env
from osim.control.osim_loco_reflex_song2019 import OsimReflexCtrl
"""
imported package dir: E:\\miniconda3_64\\envs\\osim_onn\\lib\\site-packages\\osim'
"""
from onn_torch_gd import Neural_Network
print ('onn imported')
from sklearn.datasets import make_classificatio... | [
"torch.utils.tensorboard.SummaryWriter",
"argparse.ArgumentParser",
"statsmodels.tsa.stattools.adfuller",
"statsmodels.tsa.stattools.kpss",
"torch.load",
"osim.control.osim_loco_reflex_song2019.OsimReflexCtrl",
"osim.env.L2M2019Env",
"argparse.ArgumentTypeError",
"numpy.array",
"torch.nn.MSELoss",... | [((731, 756), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (754, 756), False, 'import argparse\n'), ((1504, 1523), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['PATH'], {}), '(PATH)\n', (1517, 1523), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((1676, 1912), ... |
#!/usr/bin/env python
"""
Created on 2014-11-10T15:05:21
"""
from __future__ import division, print_function
import sys
try:
import numpy as np
except ImportError:
print('You need numpy installed')
sys.exit(1)
try:
import matplotlib.pyplot as plt
got_mpl = True
except ImportError:
print('You... | [
"numpy.polyfit",
"numpy.where",
"matplotlib.pyplot.plot",
"sys.exit",
"numpy.poly1d"
] | [((1737, 1769), 'numpy.polyfit', 'np.polyfit', (['wavcent', 'normspec', '(7)'], {}), '(wavcent, normspec, 7)\n', (1747, 1769), True, 'import numpy as np\n'), ((1843, 1855), 'numpy.poly1d', 'np.poly1d', (['z'], {}), '(z)\n', (1852, 1855), True, 'import numpy as np\n'), ((213, 224), 'sys.exit', 'sys.exit', (['(1)'], {}),... |
from matplotlib import pyplot as plt
import pickle
import numpy as np
def plot_1d_pointGoals(_file , num_goals = 100):
fobj = open(_file+ '.pkl', 'wb')
goals = np.random.normal(0,1, size = (num_goals))
import ipdb ; ipdb.set_trace()
pickle.dump(goals , fobj)
plt.scatter( np.arange(num_goals) , goals)
plt... | [
"numpy.random.normal",
"matplotlib.pyplot.savefig",
"pickle.dump",
"ipdb.set_trace",
"matplotlib.pyplot.scatter",
"numpy.arange"
] | [((168, 206), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {'size': 'num_goals'}), '(0, 1, size=num_goals)\n', (184, 206), True, 'import numpy as np\n'), ((225, 241), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (239, 241), False, 'import ipdb\n'), ((245, 269), 'pickle.dump', 'pickle.dump', (['g... |
from scipy.stats import beta
from matplotlib import pyplot as plt
import numpy as np
def samples(a, b, success, trials, num_episodes=100):
'''
:param a: the shape param for prior dist
:param b: the shape param for prior dist
:param success: num success in the experiments
:param trials: num trails... | [
"matplotlib.pyplot.hist",
"scipy.stats.beta",
"matplotlib.pyplot.subplot",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((432, 471), 'scipy.stats.beta', 'beta', (['(a + success)', '(b + trials - success)'], {}), '(a + success, b + trials - success)\n', (436, 471), False, 'from scipy.stats import beta\n'), ((732, 757), 'numpy.arange', 'np.arange', (['(0)', 'bin_size', '(1)'], {}), '(0, bin_size, 1)\n', (741, 757), True, 'import numpy as... |
#!/usr/bin/python
#
# Copyright 2021 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 a... | [
"numpy.array",
"mpmath.power",
"haiku.next_rng_key",
"jax.numpy.matmul",
"jax.random.split",
"jax.random.normal",
"haiku.initializers.Constant",
"numpy.linspace",
"jax.random.choice",
"jax.random.uniform",
"functools.reduce",
"jax.numpy.atleast_2d",
"jax.lax.stop_gradient",
"jax.numpy.eins... | [((1451, 1480), 'jax.numpy.einsum', 'jnp.einsum', (['"""ik,jk->ij"""', 'x', 'y'], {}), "('ik,jk->ij', x, y)\n", (1461, 1480), True, 'import jax.numpy as jnp\n'), ((1759, 1778), 'jax.numpy.atleast_2d', 'jnp.atleast_2d', (['(1.0)'], {}), '(1.0)\n', (1773, 1778), True, 'import jax.numpy as jnp\n'), ((1794, 1813), 'jax.num... |
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral,
denoise_wavelet, estimate_sigma)
from pathlib import Path
def process_img_and_save(img_path: Path, denoise_h=20,
... | [
"PIL.Image.fromarray",
"cv2.Laplacian",
"numpy.sqrt",
"cv2.fastNlMeansDenoising",
"pathlib.Path",
"numpy.where",
"cv2.equalizeHist",
"cv2.circle",
"cv2.resize",
"cv2.Canny",
"numpy.zeros_like",
"cv2.Sobel"
] | [((427, 484), 'cv2.resize', 'cv2.resize', (['img', '(350, 350)'], {'interpolation': 'cv2.INTER_AREA'}), '(img, (350, 350), interpolation=cv2.INTER_AREA)\n', (437, 484), False, 'import cv2\n'), ((521, 577), 'cv2.fastNlMeansDenoising', 'cv2.fastNlMeansDenoising', ([], {'src': 'img', 'dst': 'None', 'h': 'denoise_h'}), '(s... |
import numpy as np
import warnings
from time import time
import pandas as pd
# SeldonianML imports
from utils import argsweep, experiment, keyboard
from datasets import tutoring_bandit as TutoringSystem
import core.srl_fairness as SRL
import baselines.naive_full as NSRL
# Supress sklearn FutureWarnings for SGD
warni... | [
"utils.experiment.prepare_paths",
"numpy.mean",
"utils.experiment.run",
"numpy.random.random",
"numpy.log",
"baselines.POEM.DatasetReader.BanditDataset",
"sklearn.linear_model.LogisticRegression",
"numpy.exp",
"utils.experiment.make_parameters",
"baselines.POEM.Skylines.PRMWrapper",
"utils.argsw... | [((315, 377), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (336, 377), False, 'import warnings\n'), ((2637, 2643), 'time.time', 'time', ([], {}), '()\n', (2641, 2643), False, 'from time import time\n'), ((... |
import numpy as np
from frontend import signal
class stt_framework():
def __init__(self, transformation, **kwargs):
self.transformationInst = transformation(**kwargs)
def stt_transform(self, y_signal:signal, nSamplesWindow:int=2**10, overlapFactor:int=0, windowType:str=None, suppressPrint:bool=False)... | [
"frontend.signal",
"numpy.floor"
] | [((1795, 1803), 'frontend.signal', 'signal', ([], {}), '()\n', (1801, 1803), False, 'from frontend import signal\n'), ((1568, 1614), 'numpy.floor', 'np.floor', (['(nSamplesWindow * (1 - overlapFactor))'], {}), '(nSamplesWindow * (1 - overlapFactor))\n', (1576, 1614), True, 'import numpy as np\n')] |
import json
import matplotlib.style as style
import numpy as np
import pandas as pd
import pylab as pl
def make_rows(cngrs_prsn):
"""Output a list of dicitonaries for each JSON object representing a
congressperson.
Each individaul dictionary will contain information about the congressperson
as well as inf... | [
"pylab.title",
"numpy.repeat",
"pylab.tight_layout",
"pylab.savefig",
"pylab.xlabel",
"pandas.bdate_range",
"json.load",
"matplotlib.style.use",
"numpy.concatenate",
"pandas.DataFrame",
"pylab.ylabel",
"pandas.to_datetime"
] | [((2609, 2639), 'matplotlib.style.use', 'style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (2618, 2639), True, 'import matplotlib.style as style\n'), ((2720, 2755), 'pylab.title', 'pl.title', (['"""Average Age of Congress"""'], {}), "('Average Age of Congress')\n", (2728, 2755), True, 'import py... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('C:\Code_python\Image\Picture\Tiger.jpg',0)
# img2 = cv2.equalizeHist(img)
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
cdf_m = np.ma.masked_equal(cdf,0)
c... | [
"numpy.ma.masked_equal",
"cv2.imshow",
"numpy.ma.filled",
"cv2.destroyAllWindows",
"cv2.waitKey",
"cv2.namedWindow",
"cv2.imread"
] | [((76, 135), 'cv2.imread', 'cv2.imread', (['"""C:\\\\Code_python\\\\Image\\\\Picture\\\\Tiger.jpg"""', '(0)'], {}), "('C:\\\\Code_python\\\\Image\\\\Picture\\\\Tiger.jpg', 0)\n", (86, 135), False, 'import cv2\n'), ((292, 318), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['cdf', '(0)'], {}), '(cdf, 0)\n', (310, 318)... |
from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
from mesa.batchrunner import BatchRunner
import matplotlib.pyplot as plt
import numpy as np
def compute_gini(model):
agent_wealths = [agent.wealth for agent in model... | [
"matplotlib.pyplot.imshow",
"mesa.datacollection.DataCollector",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.plot",
"mesa.space.MultiGrid",
"numpy.zeros",
"mesa.time.RandomActivation",
"matplotlib.pyplot.show"
] | [((2715, 2762), 'numpy.zeros', 'np.zeros', (['(model.grid.width, model.grid.height)'], {}), '((model.grid.width, model.grid.height))\n', (2723, 2762), True, 'import numpy as np\n'), ((2903, 2952), 'matplotlib.pyplot.imshow', 'plt.imshow', (['agent_counts'], {'interpolation': '"""nearest"""'}), "(agent_counts, interpola... |
import json
import io
import time
import numpy as np
try:
to_unicode = unicode
except NameError:
to_unicode = str
def save_json(file_path, dictionary):
with io.open(file_path , 'w', encoding='utf8') as outfile:
str_ = json.dumps(dictionary,
... | [
"numpy.identity",
"json.dumps",
"numpy.tan",
"io.open"
] | [((726, 740), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (737, 740), True, 'import numpy as np\n'), ((186, 226), 'io.open', 'io.open', (['file_path', '"""w"""'], {'encoding': '"""utf8"""'}), "(file_path, 'w', encoding='utf8')\n", (193, 226), False, 'import io\n'), ((260, 336), 'json.dumps', 'json.dumps', ... |
import os
import sys
import gym
import time
import math
import time
import scipy
import skimage
import random
import logging
import pybullet
import numpy as np
from gym import spaces
from gym.utils import seeding
from pprint import pprint
from skimage.transform import rescale
from PIL import Image, ImageDraw
from ..uti... | [
"math.sqrt",
"numpy.array",
"numpy.linalg.norm",
"math.exp",
"logging.info",
"pprint.pprint",
"pybullet.getEulerFromQuaternion",
"numpy.arange",
"numpy.less",
"pybullet.getQuaternionFromEuler",
"numpy.linspace",
"numpy.dot",
"numpy.tile",
"numpy.abs",
"gym.spaces.Discrete",
"math.atan2... | [((1822, 1847), 'numpy.zeros', 'np.zeros', (['reference_shape'], {}), '(reference_shape)\n', (1830, 1847), True, 'import numpy as np\n'), ((3943, 3990), 'math.sqrt', 'math.sqrt', (["(DEFAULTS['timestep'] / self.timestep)"], {}), "(DEFAULTS['timestep'] / self.timestep)\n", (3952, 3990), False, 'import math\n'), ((5715, ... |
import numpy as np
def fx(x):
return (np.sin(np.sqrt(100 * x))) ** 2
def trapezoidal(a, b, e):
n = 1
h = []
er = []
i = []
h.append((b - a) / n)
s = (fx(a) + fx(b)) / 2
i.append(h[0] * s)
er.append(" ------")
for m in range(1, 1000, 1):
n = 2 * n
h.append((b... | [
"numpy.sqrt"
] | [((51, 67), 'numpy.sqrt', 'np.sqrt', (['(100 * x)'], {}), '(100 * x)\n', (58, 67), True, 'import numpy as np\n')] |
import autogp
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import sklearn.metrics.pairwise as sk
import time
import scipy
import seaborn as sns
import random
from kerpy.Kernel import Kernel
from kerpy.MaternKernel import MaternKernel
from kerpy.GaussianKernel import GaussianKernel
# T... | [
"matplotlib.pyplot.ylabel",
"numpy.array",
"kerpy.GaussianKernel.GaussianKernel",
"numpy.arange",
"numpy.reshape",
"numpy.repeat",
"numpy.random.poisson",
"seaborn.distplot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.asarray",
"autogp.datasets.DataSet",
"numpy.exp",
"num... | [((928, 948), 'numpy.random.seed', 'np.random.seed', (['(1500)'], {}), '(1500)\n', (942, 948), True, 'import numpy as np\n'), ((1205, 1252), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': '(1.0)', 'size': 'None'}), '(loc=0.0, scale=1.0, size=None)\n', (1221, 1252), True, 'import numpy as np\n... |
import matplotlib.pyplot as plt
import numpy as np
def plot_bars_by_group(grouped_data,colors,edgecolor=None,property_name="Data by group",ylabel="Value",figsize=(16,6),annotations = True):
"""Make bar graph by group.
Params:
------
grouped_data: (dict)
Each key represents a grou... | [
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((1072, 1091), 'numpy.arange', 'np.arange', (['n_labels'], {}), '(n_labels)\n', (1081, 1091), True, 'import numpy as np\n'), ((1391, 1405), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1403, 1405), True, 'import matplotlib.pyplot as plt\n')] |
from src.model.networks.local import LocalModel
from src.model import loss
import src.model.functions as smfunctions
from src.model.archs.baseArch import BaseArch
from src.data import dataloaders
import torch, os
import torch.optim as optim
from torch.utils.data import DataLoader
import pickle as pkl
import numpy as np... | [
"src.model.networks.local.LocalModel",
"os.remove",
"src.model.functions.rand_affine_grid",
"torch.nn.functional.grid_sample",
"numpy.mean",
"src.model.functions.warp3d",
"torch.mean",
"src.model.loss.global_mutual_information",
"src.model.loss.jacobian_determinant",
"os.path.dirname",
"src.mode... | [((15480, 15495), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15493, 15495), False, 'import torch, os\n'), ((18207, 18222), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18220, 18222), False, 'import torch, os\n'), ((18486, 18501), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18499, 18501), Fals... |
from sciapp.action import dataio
import numpy as np
def imread(path):
return np.loadtxt(path, dtype=float)
def imsave(path, img):
np.savetxt(path, img)
dataio.ReaderManager.add("dat", imread, "img")
dataio.WriterManager.add("dat", imsave, "img")
class OpenFile(dataio.Reader):
title = "DAT Open"
... | [
"sciapp.action.dataio.WriterManager.add",
"numpy.loadtxt",
"sciapp.action.dataio.ReaderManager.add",
"numpy.savetxt"
] | [((166, 212), 'sciapp.action.dataio.ReaderManager.add', 'dataio.ReaderManager.add', (['"""dat"""', 'imread', '"""img"""'], {}), "('dat', imread, 'img')\n", (190, 212), False, 'from sciapp.action import dataio\n'), ((213, 259), 'sciapp.action.dataio.WriterManager.add', 'dataio.WriterManager.add', (['"""dat"""', 'imsave'... |
import struct
import sys
import matplotlib.pyplot as plt
import numpy as np
import mmap
import os
if len(sys.argv) < 2:
print("Usage: %s <path>" %(sys.argv[0]))
file = sys.argv[1]
filename = file.split("/")[-1]
arr = np.memmap(file, dtype='float64', mode='r')
plt.plot(arr)
plt.title(filename)
print("saving="+fi... | [
"matplotlib.pyplot.title",
"numpy.memmap",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot"
] | [((224, 266), 'numpy.memmap', 'np.memmap', (['file'], {'dtype': '"""float64"""', 'mode': '"""r"""'}), "(file, dtype='float64', mode='r')\n", (233, 266), True, 'import numpy as np\n'), ((267, 280), 'matplotlib.pyplot.plot', 'plt.plot', (['arr'], {}), '(arr)\n', (275, 280), True, 'import matplotlib.pyplot as plt\n'), ((2... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
Example implementation of MAML++ on miniImageNet.
"""
import learn2learn as l2l
import numpy as np
import random
import torch
from collections import namedtuple
... | [
"torch.nn.CrossEntropyLoss",
"torch.randperm",
"torch.max",
"torch.cuda.device_count",
"torch.min",
"examples.vision.mamlpp.cnn4_bnrs.CNN4_BNRS",
"learn2learn.vision.benchmarks.get_tasksets",
"numpy.random.seed",
"collections.namedtuple",
"torch.Tensor",
"examples.vision.mamlpp.MAMLpp.MAMLpp",
... | [((486, 526), 'collections.namedtuple', 'namedtuple', (['"""MetaBatch"""', '"""support query"""'], {}), "('MetaBatch', 'support query')\n", (496, 526), False, 'from collections import namedtuple\n'), ((1071, 1090), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1083, 1090), False, 'import torch\n'),... |
import math
import numpy
__author__ = 'Matt'
def drawWheelDisplay(canvas, x, y, size, data):
wheelSize = size / 6
drawWheel(canvas, x+size*1/4, y+size/6, wheelSize, data.frontLeftWheel)
drawWheel(canvas, x+size*1/4, y+size/6*3, wheelSize, data.midLeftWheel)
drawWheel(canvas, x+size*1/4, y+size/6*5, ... | [
"math.cos",
"numpy.matrix",
"math.sin"
] | [((1001, 1136), 'numpy.matrix', 'numpy.matrix', (['[[-half_length, -half_length], [-half_length, half_length], [half_length,\n half_length], [half_length, -half_length]]'], {}), '([[-half_length, -half_length], [-half_length, half_length], [\n half_length, half_length], [half_length, -half_length]])\n', (1013, 11... |
import gym
import numpy as np
from grpc import RpcError
from robo_gym.utils.exceptions import InvalidStateError, RobotServerError
class MoveEffectorToWayPoints(gym.Wrapper):
"""
Add environment a goal that the robot end-effector must reach all waypoints.
"""
def __init__(self, env, wayPoints: np.ndarra... | [
"numpy.copy",
"numpy.array",
"numpy.linalg.norm"
] | [((1296, 1314), 'numpy.copy', 'np.copy', (['wayPoints'], {}), '(wayPoints)\n', (1303, 1314), True, 'import numpy as np\n'), ((2536, 2677), 'numpy.array', 'np.array', (["[observation[self.endEffectorName + '_x'], observation[self.endEffectorName +\n '_y'], observation[self.endEffectorName + '_z']]"], {}), "([observat... |
import pandas as pd
import numpy as np
import os
from keras import backend
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.layers.merge import concatenate
from keras.models import Sequential, Model
from keras.layers import Dense, Embedding, Activation, me... | [
"keras.backend.sum",
"pandas.read_csv",
"keras.layers.MaxPool1D",
"keras.backend.floatx",
"keras.backend.squeeze",
"keras.backend.dot",
"keras.layers.Activation",
"keras.layers.Dense",
"keras.preprocessing.sequence.pad_sequences",
"numpy.arange",
"keras.backend.tanh",
"keras.layers.merge.conca... | [((1167, 1202), 'pandas.read_csv', 'pd.read_csv', (['"""data/train_first.csv"""'], {}), "('data/train_first.csv')\n", (1178, 1202), True, 'import pandas as pd\n'), ((1210, 1247), 'pandas.read_csv', 'pd.read_csv', (['"""data/predict_first.csv"""'], {}), "('data/predict_first.csv')\n", (1221, 1247), True, 'import pandas ... |
"""
Synopsis: A binder for enabling this package using numpy arrays.
Author: <NAME> <<EMAIL>, <EMAIL>>
"""
from ctypes import cdll, POINTER, c_int, c_double, byref
import numpy as np
import ctypes
import pandas as pd
from numpy.ctypeslib import ndpointer
lib = cdll.LoadLibrary("./miniball_python.so")
def m... | [
"ctypes.byref",
"ctypes.POINTER",
"ctypes.cdll.LoadLibrary",
"numpy.array",
"numpy.ctypeslib.ndpointer",
"ctypes.c_double"
] | [((272, 312), 'ctypes.cdll.LoadLibrary', 'cdll.LoadLibrary', (['"""./miniball_python.so"""'], {}), "('./miniball_python.so')\n", (288, 312), False, 'from ctypes import cdll, POINTER, c_int, c_double, byref\n'), ((842, 853), 'ctypes.c_double', 'c_double', (['(0)'], {}), '(0)\n', (850, 853), False, 'from ctypes import cd... |
import numpy as np
import os
import csv
import argparse
import torchvision.transforms as transforms
from PIL import Image
def loading_ucf_lists():
dataset_root = "/home/ubuntu/data/ucf101"
split = 'split_1'
# data frame root
dataset_frame_root = os.path.join(dataset_root, 'rawframes')
# data lis... | [
"torchvision.transforms.CenterCrop",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.join",
"os.path.splitext",
"numpy.array",
"numpy.linspace",
"numpy.concatenate",
"numpy.load",
"torchvision.transforms.Compose"
] | [((265, 304), 'os.path.join', 'os.path.join', (['dataset_root', '"""rawframes"""'], {}), "(dataset_root, 'rawframes')\n", (277, 304), False, 'import os\n'), ((349, 458), 'os.path.join', 'os.path.join', (['dataset_root', '"""ucfTrainTestlist"""', "('ucf101_' + 'train' + '_' + split + '_rawframes' + '.txt')"], {}), "(dat... |
from __future__ import division
import sys
import numpy as np
import matplotlib.pyplot as plt
import itertools
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Tahoma']
rcParams['ps.useafm'] = True
rcParams['pdf.use14corefonts'] = True
rcParams['text.usetex'] = Tru... | [
"itertools.cycle",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.load",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((404, 466), 'itertools.cycle', 'itertools.cycle', (["('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')"], {}), "(('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'))\n", (419, 466), False, 'import itertools\n'), ((472, 519), 'itertools.cycle', 'itertools.cycle', (["('o', 'v', '*', 'D', 'x', '+')"], {}), "(('o', 'v', '*', 'D', ... |
from commons.util import most_similar, create_co_matrix, ppmi
from datasets import ptb
import numpy as np
window_size = 2
wordvec_size = 100
corpus, word_to_id, id_to_word = ptb.load_data('train')
vocab_size = len(word_to_id)
print('Calculating coincide number ...')
C = create_co_matrix(corpus, vocab_size, window_siz... | [
"commons.util.create_co_matrix",
"sklearn.utils.extmath.randomized_svd",
"commons.util.most_similar",
"datasets.ptb.load_data",
"commons.util.ppmi",
"numpy.linalg.svd"
] | [((176, 198), 'datasets.ptb.load_data', 'ptb.load_data', (['"""train"""'], {}), "('train')\n", (189, 198), False, 'from datasets import ptb\n'), ((273, 322), 'commons.util.create_co_matrix', 'create_co_matrix', (['corpus', 'vocab_size', 'window_size'], {}), '(corpus, vocab_size, window_size)\n', (289, 322), False, 'fro... |
# -*- coding: utf-8 -*-
from __future__ import division
import bz2
from datetime import datetime
import os
import pickle
import numpy as np
import torch
from tqdm import trange
from agent import Agent
from utils import initialize_environment
from memory import ReplayMemory
from test import test
from parsers import pa... | [
"os.path.exists",
"parsers.parser.parse_args",
"pickle.dump",
"os.makedirs",
"os.path.join",
"pickle.load",
"test.test",
"utils.initialize_environment",
"datetime.datetime.now",
"agent.Agent",
"numpy.random.randint",
"torch.cuda.is_available",
"numpy.random.seed",
"memory.ReplayMemory",
... | [((341, 360), 'parsers.parser.parse_args', 'parser.parse_args', ([], {}), '()\n', (358, 360), False, 'from parsers import parser\n'), ((455, 487), 'os.path.join', 'os.path.join', (['"""results"""', 'args.id'], {}), "('results', args.id)\n", (467, 487), False, 'import os\n'), ((638, 663), 'numpy.random.seed', 'np.random... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy import signal
import copy
"""
___author__ = "<NAME>, <NAME>"
__email__ = <EMAIL>"
"""
def randRange(x1, x2, integer):
y = np.random.uniform(low=x1, high=x2, size=(1,))
if integer:
y = int(y)
return y
def normWav(x,alwa... | [
"numpy.random.normal",
"numpy.mean",
"numpy.random.rand",
"numpy.power",
"numpy.linalg.norm",
"numpy.pad",
"scipy.signal.lfilter",
"numpy.random.uniform",
"copy.deepcopy",
"scipy.signal.freqz",
"numpy.random.permutation"
] | [((207, 252), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'x1', 'high': 'x2', 'size': '(1,)'}), '(low=x1, high=x2, size=(1,))\n', (224, 252), True, 'import numpy as np\n'), ((1034, 1059), 'scipy.signal.freqz', 'signal.freqz', (['b', '(1)'], {'fs': 'fs'}), '(b, 1, fs=fs)\n', (1046, 1059), False, 'from scip... |
import comet_ml # noqa: F401
import pytest
import numpy as np
import torch
from conftest import create_dataset, create_image
from traintool.image_classification.preprocessing import (
recognize_data_format,
torch_to_numpy,
numpy_to_torch,
files_to_numpy,
files_to_torch,
load_image,
recogn... | [
"conftest.create_image",
"traintool.image_classification.preprocessing.load_image",
"numpy.allclose",
"traintool.image_classification.preprocessing.files_to_torch",
"conftest.create_dataset",
"traintool.image_classification.preprocessing.recognize_image_format",
"traintool.image_classification.preproces... | [((408, 468), 'conftest.create_dataset', 'create_dataset', ([], {'data_format': '"""numpy"""', 'seed': '(0)', 'grayscale': '(False)'}), "(data_format='numpy', seed=0, grayscale=False)\n", (422, 468), False, 'from conftest import create_dataset, create_image\n'), ((516, 576), 'conftest.create_dataset', 'create_dataset',... |
import numpy as np
from numpy import ndarray
from base_ada_classifier import BaseClassifier
class RandomClassifier(BaseClassifier):
_feature_index: int = None
_feature_value: float = None
_max_cycle = 1000
def __init__(self, w: ndarray, norm_factor = 1):
super(RandomClassifier, self).__init__(... | [
"numpy.ones",
"numpy.random.choice",
"numpy.max",
"numpy.random.randint",
"numpy.min",
"numpy.arange"
] | [((474, 506), 'numpy.random.randint', 'np.random.randint', (['(0)', 'n_features'], {}), '(0, n_features)\n', (491, 506), True, 'import numpy as np\n'), ((523, 544), 'numpy.min', 'np.min', (['X[:, f_index]'], {}), '(X[:, f_index])\n', (529, 544), True, 'import numpy as np\n'), ((561, 582), 'numpy.max', 'np.max', (['X[:,... |
import numpy as np
import cv2 as cv
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
def read_gray_image(path):
img = cv.imread(path)
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
plt.imshow(img_gray, cmap='gray', interpolation='nearest')
plt.savefig('./results/img_gray.png')
plt.clos... | [
"cv2.rectangle",
"cv2.warpPerspective",
"cv2.HoughLines",
"numpy.sin",
"matplotlib.pyplot.imshow",
"cv2.threshold",
"numpy.where",
"cv2.line",
"numpy.asarray",
"matplotlib.pyplot.close",
"cv2.matchTemplate",
"matplotlib.pyplot.savefig",
"cv2.getPerspectiveTransform",
"matplotlib.use",
"n... | [((54, 75), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (68, 75), False, 'import matplotlib\n'), ((148, 163), 'cv2.imread', 'cv.imread', (['path'], {}), '(path)\n', (157, 163), True, 'import cv2 as cv\n'), ((176, 211), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_BGR2GRAY'], {}), '(img, c... |
__author__ = '<NAME>'
import multiprocessing as mp
import numpy as np
import os # For path names working under Windows and Linux
from pypet import Environment, cartesian_product
def multiply(traj, result_list):
"""Example of a sophisticated simulation that involves multiplying two values.
This time we will... | [
"pypet.Environment",
"pypet.cartesian_product",
"os.path.join",
"numpy.array",
"multiprocessing.Manager"
] | [((682, 721), 'os.path.join', 'os.path.join', (['"""hdf5"""', '"""example_12.hdf5"""'], {}), "('hdf5', 'example_12.hdf5')\n", (694, 721), False, 'import os\n'), ((732, 935), 'pypet.Environment', 'Environment', ([], {'trajectory': '"""Multiplication"""', 'filename': 'filename', 'file_title': '"""Example_12_Sharing_Data"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 11:16:27 2020
@author: hiroyasu
"""
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import control
import SCPmulti as scp
import pickle
DT = scp.DT
TSPAN = scp.TSPAN
M = scp.M
II = s... | [
"cvxpy.sum_squares",
"numpy.sqrt",
"numpy.random.rand",
"numpy.array",
"numpy.linalg.norm",
"numpy.sin",
"cvxpy.Minimize",
"numpy.reshape",
"matplotlib.pyplot.plot",
"numpy.diff",
"numpy.linspace",
"numpy.random.seed",
"numpy.vstack",
"numpy.identity",
"numpy.ones",
"control.lqr",
"p... | [((475, 516), 'numpy.load', 'np.load', (['"""data/params/desired_n/Xhis.npy"""'], {}), "('data/params/desired_n/Xhis.npy')\n", (482, 516), True, 'import numpy as np\n'), ((524, 565), 'numpy.load', 'np.load', (['"""data/params/desired_n/Uhis.npy"""'], {}), "('data/params/desired_n/Uhis.npy')\n", (531, 565), True, 'impor... |
import numpy as np
class RolloutWorker:
def __init__(self, env, policy, cfg, env_params, language_conditioned=False):
self.env = env
self.policy = policy
self.cfg = cfg
self.env_params = env_params
self.language_conditioned = language_conditioned
self.timestep_cou... | [
"numpy.mean",
"numpy.array",
"numpy.zeros_like",
"numpy.sum"
] | [((3750, 3816), 'numpy.mean', 'np.mean', (["[_rd['success'][-1] for rd in rollout_data for _rd in rd]"], {}), "([_rd['success'][-1] for rd in rollout_data for _rd in rd])\n", (3757, 3816), True, 'import numpy as np\n'), ((3835, 3898), 'numpy.sum', 'np.sum', (["[_rd['reward'] for rd in rollout_data for _rd in rd]", '(1)... |
import numpy as np
import pytest
from pytest import approx
from uhi.numpy_plottable import ensure_plottable_histogram
def test_from_numpy() -> None:
hist1 = ((1, 2, 3, 4, 1, 2), (0, 1, 2, 3))
h = ensure_plottable_histogram(hist1)
assert h.values() == approx(np.array(hist1[0]))
assert len(h.axes) ==... | [
"numpy.random.normal",
"pytest.approx",
"numpy.histogramdd",
"uhi.numpy_plottable.ensure_plottable_histogram",
"numpy.array",
"pytest.importorskip",
"numpy.random.seed",
"numpy.histogram2d"
] | [((208, 241), 'uhi.numpy_plottable.ensure_plottable_histogram', 'ensure_plottable_histogram', (['hist1'], {}), '(hist1)\n', (234, 241), False, 'from uhi.numpy_plottable import ensure_plottable_histogram\n'), ((496, 514), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (510, 514), True, 'import numpy as... |
"""Prediction of users based on tweet embeddings"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from .models import User
from .twitter import vectorize_tweet
def predict_user(user0_name, user1_name, hypo_tweet_text):
"""
Determine and return which user is more likely to say a hypothe... | [
"numpy.array",
"numpy.vstack",
"sklearn.linear_model.LogisticRegression"
] | [((481, 529), 'numpy.array', 'np.array', (['[tweet.vect for tweet in user0.tweets]'], {}), '([tweet.vect for tweet in user0.tweets])\n', (489, 529), True, 'import numpy as np\n'), ((548, 596), 'numpy.array', 'np.array', (['[tweet.vect for tweet in user1.tweets]'], {}), '([tweet.vect for tweet in user1.tweets])\n', (556... |
#!/usr/bin/env python
"""
Numba sampling routines
"""
import numpy as np
import math
from numba import jit, prange
# import lom._cython.matrix_updates as cython_mu
import lom._numba.lom_outputs as lom_outputs
import lom._numba.posterior_score_fcts as score_fcts
# only needed for IBP
from lom.auxiliary_functions import... | [
"lom.auxiliary_functions.logit",
"numpy.random.rand",
"numpy.log",
"numpy.array",
"numba.prange",
"math.exp",
"numpy.arange",
"numpy.int8",
"lom.auxiliary_functions.expit",
"numpy.max",
"numpy.exp",
"numpy.dot",
"numpy.ones",
"numba.jit",
"numpy.random.ranf",
"math.lgamma",
"numpy.su... | [((395, 448), 'numba.jit', 'jit', (['"""int8(float64, int8)"""'], {'nopython': '(True)', 'nogil': '(True)'}), "('int8(float64, int8)', nopython=True, nogil=True)\n", (398, 448), False, 'from numba import jit, prange\n'), ((856, 903), 'numba.jit', 'jit', (['"""int8(float64)"""'], {'nopython': '(True)', 'nogil': '(True)'... |
"""
nmrglue table functions.
nmrglue uses numpy records array as stores of various data (peak tables,
trajectories, etc). This module provides functions to read and write records
arrays from disk. Formatting of the numeric values is left to Python's str
function and only the data type need be specified. In addition... | [
"numpy.insert",
"numpy.abs",
"numpy.delete",
"numpy.recfromtxt",
"numpy.log",
"numpy.take",
"numpy.array",
"numpy.empty",
"numpy.rec.array"
] | [((5991, 6013), 'numpy.insert', 'np.insert', (['rec', 'N', 'row'], {}), '(rec, N, row)\n', (6000, 6013), True, 'import numpy as np\n'), ((6804, 6821), 'numpy.delete', 'np.delete', (['rec', 'N'], {}), '(rec, N)\n', (6813, 6821), True, 'import numpy as np\n'), ((7526, 7549), 'numpy.take', 'np.take', (['rec', 'new_order']... |
from setuptools import setup
from Cython.Build import cythonize
from numpy import get_include
setup(
name='vis_precision',
ext_modules=cythonize('vis_precision.pyx'),
include_dirs=[get_include()],
zip_safe=False,
)
setup(
name='dnb_int32',
ext_modules=cythonize('dnb_int32.pyx'),
... | [
"Cython.Build.cythonize",
"numpy.get_include"
] | [((150, 180), 'Cython.Build.cythonize', 'cythonize', (['"""vis_precision.pyx"""'], {}), "('vis_precision.pyx')\n", (159, 180), False, 'from Cython.Build import cythonize\n'), ((291, 317), 'Cython.Build.cythonize', 'cythonize', (['"""dnb_int32.pyx"""'], {}), "('dnb_int32.pyx')\n", (300, 317), False, 'from Cython.Build i... |
#!/usr/bin/env python
'''
The basic usage of range-separated Gaussian density fitting (RSGDF or simply
RSDF), including choosing an auxiliary basis, initializing 3c integrals, saving
and reading 3c integrals, jk build, ao2mo, etc is the same as that of the
GDF module. Please refer to the following examples for details... | [
"numpy.array",
"pyscf.pbc.scf.KRHF",
"pyscf.pbc.gto.Cell",
"pyscf.pbc.df.RSDF",
"numpy.zeros_like",
"pyscf.pbc.mp.KMP2",
"pyscf.pbc.scf.KRKS"
] | [((807, 817), 'pyscf.pbc.gto.Cell', 'gto.Cell', ([], {}), '()\n', (815, 817), False, 'from pyscf.pbc import gto, scf, cc, df, mp\n'), ((1467, 1486), 'pyscf.pbc.df.RSDF', 'df.RSDF', (['cell', 'kpts'], {}), '(cell, kpts)\n', (1474, 1486), False, 'from pyscf.pbc import gto, scf, cc, df, mp\n'), ((2357, 2387), 'numpy.array... |
from sklearn.utils import shuffle
import numpy as np
from donkeycar.parts.augment import augment_image
from donkeycar.parts.datastore import Tub
from donkeycar.utils import load_scaled_image_arr
import keras
def vae_generator(cfg, data, batch_size, isTrainSet=True, min_records_to_train=1000, aug=False, aux=None, pilot... | [
"donkeycar.templates.train.collate_records",
"numpy.mean",
"argparse.ArgumentParser",
"donkeycar.parts.datastore.Tub.get_angle_throttle",
"sklearn.utils.shuffle",
"donkeycar.parts.augment.augment_image",
"donkeycar.load_config",
"numpy.max",
"keras.utils.to_categorical",
"donkeycar.utils.gather_re... | [((2867, 2987), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test VAE data loader."""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Test VAE data loader.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (2890, 2987), False, 'import ar... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# zmq_SUB_proc.py
# Author: <NAME>
import zmq
import numpy as np
import time
import matplotlib.pyplot as plt
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://127.0.0.1:4030") # connect, not bind, the PUB will bind, only 1 can bind
socket.setsoc... | [
"numpy.frombuffer",
"zmq.Context",
"time.sleep"
] | [((165, 178), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (176, 178), False, 'import zmq\n'), ((742, 786), 'numpy.frombuffer', 'np.frombuffer', (['msg'], {'dtype': 'np.ubyte', 'count': '(-1)'}), '(msg, dtype=np.ubyte, count=-1)\n', (755, 786), True, 'import numpy as np\n'), ((1903, 1918), 'time.sleep', 'time.sleep'... |
"""
Neural Network
by <NAME>
<EMAIL>
"""
import numpy as np
from NeuralNetwork.Activation import fSigmoid as fActivation, dSigmoid as dActivation
from NeuralNetwork.Cost import fQuadratic as fCost, dQuadratic as dCost
class NeuralNetwork:
"""
Class of the neural network which works with backpropagation
"""
de... | [
"numpy.argmax",
"numpy.zeros",
"NeuralNetwork.Activation.dSigmoid",
"numpy.dot",
"numpy.random.seed",
"NeuralNetwork.Cost.fQuadratic",
"NeuralNetwork.Cost.dQuadratic",
"NeuralNetwork.Activation.fSigmoid",
"numpy.random.randn"
] | [((669, 687), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (683, 687), True, 'import numpy as np\n'), ((3084, 3106), 'numpy.zeros', 'np.zeros', (['weight.shape'], {}), '(weight.shape)\n', (3092, 3106), True, 'import numpy as np\n'), ((3149, 3169), 'numpy.zeros', 'np.zeros', (['bias.shape'], {}), '(b... |
"""Superficial default settings."""
from matplotlib.cm import get_cmap, register_cmap
from matplotlib.colors import ListedColormap
from numpy import array
#: Default color palette for continuous data.
continuous_palette = "YlGn"
#: Secondary color palette for continuous data.
alternate_palette = "Blues"
#: Default c... | [
"numpy.array",
"matplotlib.cm.get_cmap"
] | [((1100, 1117), 'matplotlib.cm.get_cmap', 'get_cmap', (['"""tab20"""'], {}), "('tab20')\n", (1108, 1117), False, 'from matplotlib.cm import get_cmap, register_cmap\n'), ((2908, 2919), 'numpy.array', 'array', (['axes'], {}), '(axes)\n', (2913, 2919), False, 'from numpy import array\n')] |
#!/usr/bin/python3
'''Routines useful in generation and processing of synthetic data
These are very useful in analyzing the behavior or cameras and lenses.
All functions are exported into the mrcal module. So you can call these via
mrcal.synthetic_data.fff() or mrcal.fff(). The latter is preferred.
'''
import nump... | [
"mrcal.identity_Rt",
"numpy.count_nonzero",
"numpy.array",
"mrcal.ref_calibration_object",
"mrcal.rotate_point_R",
"numpy.arange",
"numpysane.mv",
"mrcal.unproject",
"mrcal.Rt_from_rt",
"numpysane.glue",
"numpysane.cat",
"mrcal.compose_Rt",
"numpy.any",
"mrcal.project",
"numpysane.dummy"... | [((12096, 12205), 'numpy.array', 'np.array', (['((object_width_n - 1) * object_spacing / 2.0, (object_height_n - 1) *\n object_spacing / 2.0, 0)'], {}), '(((object_width_n - 1) * object_spacing / 2.0, (object_height_n - 1\n ) * object_spacing / 2.0, 0))\n', (12104, 12205), True, 'import numpy as np\n'), ((12637, ... |
#Trabalhando com sorted no Pandas
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
sorted_df=unsorted_df.sort_index()
print (sorted_df) | [
"numpy.random.randn"
] | [((100, 122), 'numpy.random.randn', 'np.random.randn', (['(10)', '(2)'], {}), '(10, 2)\n', (115, 122), True, 'import numpy as np\n')] |
import os
import sys
import argparse
import tensorflow as tf
import numpy as np
from PIL import Image
from reader import Reader
from source.anchor_filter import AnchorFilter
import logging
import random
import time
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
class VS3D(object):
def __init__(self, k... | [
"tensorflow.shape",
"tensorflow.get_collection_ref",
"tensorflow.boolean_mask",
"tensorflow.reduce_sum",
"tensorflow.split",
"numpy.array",
"tensorflow.control_dependencies",
"numpy.sin",
"tensorflow.cast",
"tensorflow.clip_by_global_norm",
"numpy.save",
"os.path.exists",
"numpy.mean",
"ar... | [((215, 273), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'stream': 'sys.stdout'}), '(level=logging.INFO, stream=sys.stdout)\n', (234, 273), False, 'import logging\n'), ((23911, 23936), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (23934, 23936), False, 'impor... |
#!/usr/bin/env python
# Lib:
import numpy as np
import pylab
def mandelbrot(h, w, maxit=100):
'''Returns an image of the Mandelbrot fractal of size (h,w).
'''
y, x = np.ogrid[-2:2:h*1j, -3:1:w*1j]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
... | [
"numpy.conj",
"numpy.zeros"
] | [((282, 310), 'numpy.zeros', 'np.zeros', (['z.shape'], {'dtype': 'int'}), '(z.shape, dtype=int)\n', (290, 310), True, 'import numpy as np\n'), ((402, 412), 'numpy.conj', 'np.conj', (['z'], {}), '(z)\n', (409, 412), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import copy
from ctypes import *
from ..exrpc.rpclib import *
from ..exrpc.server import *
from ..matrix.dtype import *
from .frovedisColumn import *
from . import df
class FrovedisGroupedDataframe :
'''A python container for holding Frovedis side creat... | [
"numpy.asarray",
"copy.deepcopy"
] | [((590, 609), 'copy.deepcopy', 'copy.deepcopy', (['cols'], {}), '(cols)\n', (603, 609), False, 'import copy\n'), ((628, 648), 'copy.deepcopy', 'copy.deepcopy', (['types'], {}), '(types)\n', (641, 648), False, 'import copy\n'), ((668, 689), 'copy.deepcopy', 'copy.deepcopy', (['p_cols'], {}), '(p_cols)\n', (681, 689), Fa... |
import numpy as np
import unittest
import pytest
from mvc.misc.batch import make_batch
class MakeBatchTest(unittest.TestCase):
def test_success(self):
batch_size = np.random.randint(32) + 1
data_size = batch_size * np.random.randint(10) + 1
data = {
'test1': np.random.random((... | [
"numpy.random.random",
"numpy.random.randint",
"pytest.raises",
"mvc.misc.batch.make_batch"
] | [((433, 472), 'mvc.misc.batch.make_batch', 'make_batch', (['data', 'batch_size', 'data_size'], {}), '(data, batch_size, data_size)\n', (443, 472), False, 'from mvc.misc.batch import make_batch\n'), ((179, 200), 'numpy.random.randint', 'np.random.randint', (['(32)'], {}), '(32)\n', (196, 200), True, 'import numpy as np\... |
import json
import pytest
from lxml import etree
import numpy as np
import xarray as xr
import pandas as pd
import finch
import finch.processes
from finch.processes.wps_xclim_indices import XclimIndicatorBase
from finch.processes.wps_base import make_xclim_indicator_process
from . utils import execute_process, wps_inp... | [
"finch.processes.wps_base.make_xclim_indicator_process",
"xclim.testing.open_dataset",
"numpy.ones",
"pathlib.Path",
"numpy.arange",
"numpy.testing.assert_allclose",
"json.dumps",
"pytest.mark.parametrize",
"finch.processes.get_processes",
"numpy.array",
"pytest.raises",
"finch.processes.xclim... | [((824, 888), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""indicator"""', 'finch.processes.indicators'], {}), "('indicator', finch.processes.indicators)\n", (847, 888), False, 'import pytest\n'), ((702, 733), 'finch.processes.get_processes', 'finch.processes.get_processes', ([], {}), '()\n', (731, 733), ... |
from multiprocessing import Pool
from bokeh.io import export_png
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import Category10 as palette
import itertools
# import matplotlib.pyplot as plt
import numpy as np
import tqdm
# from progress.bar import Bar
from network_simulator.components import... | [
"itertools.cycle",
"network_simulator.helpers.readSimCache",
"bokeh.plotting.figure",
"bokeh.plotting.show",
"numpy.arange",
"network_simulator.helpers.genDescendUnitArray",
"multiprocessing.Pool",
"network_simulator.helpers.writeSimCache",
"network_simulator.components.simulator",
"bokeh.plotting... | [((442, 485), 'network_simulator.components.simulator', 'simulator', (['g_init_vars', 'g_aplist', 'g_usrlist'], {}), '(g_init_vars, g_aplist, g_usrlist)\n', (451, 485), False, 'from network_simulator.components import simulator\n'), ((701, 728), 'numpy.arange', 'np.arange', (['(0.01)', '(0.99)', '(0.01)'], {}), '(0.01,... |
import numpy as np
from produce_lightcurve import Lightcurve
import synphot as sp
import dorado.sensitivity
import astropy.units as u
from astropy import constants as c
import dill as pickle
import os
from dynesty_sampler import getSampler, wrappedSampler, find
from parameters import getParameters
# get parameters
pa... | [
"os.path.exists",
"parameters.getParameters",
"dynesty_sampler.getSampler",
"dynesty_sampler.wrappedSampler",
"numpy.log",
"dynesty_sampler.find",
"numpy.array",
"dill.dump",
"numpy.ndarray",
"os.mkdir",
"synphot.SpectralElement.from_file",
"produce_lightcurve.Lightcurve",
"matplotlib.pyplot... | [((331, 552), 'parameters.getParameters', 'getParameters', ([], {'osargs_list': "['read_data', 'model', 'delay', 'dist', 'include_optical', 'include_uv',\n 'print_progress', 'method', 'resume_previous', 'sample',\n 'save_after_seconds', 'parallel', 'dlogz_threshold']"}), "(osargs_list=['read_data', 'model', 'dela... |
import numpy as np
import matplotlib.pyplot as plt
from tools import get_array, dags
data = dags[0]
find_or_add_index = get_array(data, "find_or_add index")
find_or_add_add = get_array(data, "find_or_add add")
find_or_add_level = get_array(data, "find_or_add level")
plt.xlabel("index")
plt.ylabel("num")
indices_add... | [
"tools.get_array",
"numpy.logical_and",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.max",
"numpy.sum",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((122, 158), 'tools.get_array', 'get_array', (['data', '"""find_or_add index"""'], {}), "(data, 'find_or_add index')\n", (131, 158), False, 'from tools import get_array, dags\n'), ((177, 211), 'tools.get_array', 'get_array', (['data', '"""find_or_add add"""'], {}), "(data, 'find_or_add add')\n", (186, 211), False, 'fr... |
from .matrix import Matrix
from . import constant
import numpy as np
from typing import List
class Key(Matrix):
def __init__(self, array: np.ndarray) -> None:
self._state = super().__init__(array)
def a_key_schedule(round_key: Key, round: int) -> Key:
""" Generate new Roundkey from old one"""
ne... | [
"numpy.empty"
] | [((334, 365), 'numpy.empty', 'np.empty', (['[4, 4]'], {'dtype': '"""uint8"""'}), "([4, 4], dtype='uint8')\n", (342, 365), True, 'import numpy as np\n')] |
import time
import os
from torch.autograd import Variable
import torch
import numpy
import networks
import shutil
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
torch.backends.cudnn.benchmark = True
with open('process_info.txt', 'r') as file:
process_info = file.read()
process_info = ... | [
"torch.unsqueeze",
"torch.load",
"torch.stack",
"os.chdir",
"torch.nn.ReplicationPad2d",
"torch.set_grad_enabled",
"numpy.transpose",
"time.time",
"warnings.filterwarnings",
"numpy.round",
"numpy.load"
] | [((131, 186), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (154, 186), False, 'import warnings\n'), ((339, 376), 'os.chdir', 'os.chdir', (["process_info['dain_folder']"], {}), "(process_info['dain_folder'])\n", (347, 376), F... |
import re
import xml.etree.ElementTree as ET
from os import path
from collections import Counter
import argparse
import csv
import json
import os
import random
# package local imports
import sys
import uuid
import matplotlib.pyplot as plt
import math
from dateutil.parser import parse
from tdigest import TDigest
impo... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"numpy.random.lognormal",
"common_datagen.add_deployment_requirements_redis_server_module",
"random.choices",
"common_datagen.generate_inputs_dict_item",
"common_datagen.add_deployment_requirements_utilities",
"os.path.exists",
"tdigest.TDigest",... | [((1553, 1595), 'numpy.random.lognormal', 'np.random.lognormal', (['mu', 'sigma', 'n_elements'], {}), '(mu, sigma, n_elements)\n', (1572, 1595), True, 'import numpy as np\n'), ((3867, 3902), 're.sub', 're.sub', (['"""[^0-9a-zA-Z]+"""', '""" """', 'words'], {}), "('[^0-9a-zA-Z]+', ' ', words)\n", (3873, 3902), False, 'i... |
import os
import platform
if not os.path.exists("temp"):
os.mkdir("temp")
def from_flopy_kl_test():
import shutil
import numpy as np
import pandas as pd
try:
import flopy
except:
return
import pyemu
org_model_ws = os.path.join("..", "examples", "freyberg_sfr_update")
... | [
"flopy.modflow.Modflow.load",
"numpy.sqrt",
"pandas.read_csv",
"pyemu.geostats.GeoStruct",
"pyemu.helpers.PstFromFlopyModel",
"numpy.loadtxt",
"pyemu.geostats.ExpVario",
"os.remove",
"os.path.exists",
"flopy.modflow.ModflowRiv",
"os.listdir",
"numpy.random.random",
"pyemu.Ensemble.reseed",
... | [((34, 56), 'os.path.exists', 'os.path.exists', (['"""temp"""'], {}), "('temp')\n", (48, 56), False, 'import os\n'), ((62, 78), 'os.mkdir', 'os.mkdir', (['"""temp"""'], {}), "('temp')\n", (70, 78), False, 'import os\n'), ((264, 317), 'os.path.join', 'os.path.join', (['""".."""', '"""examples"""', '"""freyberg_sfr_updat... |
# A Faster R-CNN approach to Mu2e Tracking
# The detector (Fast R-CNN) part for alternative (i) method in the original paper
# see https://arxiv.org/abs/1506.01497
# Author: <NAME>
# Email: <EMAIL>
### imports starts
import sys
from pathlib import Path
import pickle
import timeit
import pandas as pd
import numpy as n... | [
"tensorflow.keras.layers.Input",
"Layers.RoIPooling",
"tensorflow.keras.layers.Conv2D",
"pathlib.Path.cwd",
"tensorflow.keras.optimizers.schedules.ExponentialDecay",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.optimizers.Adam",
"numpy.expand_dims",
"tensorflow.keras.metrics.Categorical... | [((1111, 1136), 'numpy.load', 'np.load', (['C.img_inputs_npy'], {}), '(C.img_inputs_npy)\n', (1118, 1136), True, 'import numpy as np\n'), ((1148, 1163), 'numpy.load', 'np.load', (['C.rois'], {}), '(C.rois)\n', (1155, 1163), True, 'import numpy as np\n'), ((1179, 1217), 'numpy.load', 'np.load', (['C.detector_train_Y_cla... |
import numpy as np
import warnings
def drop_outlier(adata,
thresh=15,
axis=0,
drop=True,
verbose=False):
"""Drop all features or cells with a min or max absolute value that is greater than a threshold.
Expects normally distributed data.
... | [
"numpy.logical_and",
"numpy.max",
"numpy.nanmean",
"numpy.min",
"warnings.warn"
] | [((907, 934), 'numpy.nanmean', 'np.nanmean', (['adata.X'], {'axis': '(0)'}), '(adata.X, axis=0)\n', (917, 934), True, 'import numpy as np\n'), ((1551, 1609), 'numpy.logical_and', 'np.logical_and', (['(max_values <= thresh)', '(min_values <= thresh)'], {}), '(max_values <= thresh, min_values <= thresh)\n', (1565, 1609),... |
'''
This script serves to get the speech files prepared for training neural networks, with "matched" noise added to the training data.
Speech was collected from the Saarbücken Voice Database
'''
import pandas as pd
import numpy as np
import librosa
import sqlite3
from sqlite3 import Error
import glob
from pathlib imp... | [
"get_speech_features.get_mfcc",
"sqlite3.connect",
"pathlib.Path",
"get_speech_features.get_fundfreq",
"get_speech_features.get_domfreq",
"numpy.concatenate",
"get_speech_features.get_samps",
"time.time"
] | [((3417, 3428), 'time.time', 'time.time', ([], {}), '()\n', (3426, 3428), False, 'import time\n'), ((1124, 1142), 'get_speech_features.get_samps', 'get_samps', (['wav', 'sr'], {}), '(wav, sr)\n', (1133, 1142), False, 'from get_speech_features import get_samps, get_mfcc, get_fundfreq, get_domfreq\n'), ((1157, 1172), 'ge... |
#----------------------------------------------------------------------------
# Name: wet_antenna
# Purpose: Estimation and removal of wet antenna effects
#
# Authors: <NAME>
#
# Created: 01.12.2014
# Copyright: (c) <NAME> 2014
# Licence: The MIT License
#---------------------------------... | [
"numba.decorators.jit",
"numpy.zeros_like"
] | [((592, 610), 'numba.decorators.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (595, 610), False, 'from numba.decorators import jit\n'), ((1658, 1694), 'numpy.zeros_like', 'np.zeros_like', (['rsl'], {'dtype': 'np.float64'}), '(rsl, dtype=np.float64)\n', (1671, 1694), True, 'import numpy as np\n')] |
import pyhecdss
import pandas as pd
import numpy as np
import os
def test_read_write_cycle_rts():
'''
Test reading and writing of period time stamped data so
that reads and writes don't result in shifting the data
'''
fname = "test2.dss"
if os.path.exists(fname):
os.remove... | [
"os.path.exists",
"pyhecdss.DSSFile",
"numpy.linspace",
"pandas.testing.assert_frame_equal",
"os.remove"
] | [((279, 300), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (293, 300), False, 'import os\n'), ((625, 665), 'pyhecdss.DSSFile', 'pyhecdss.DSSFile', (['fname'], {'create_new': '(True)'}), '(fname, create_new=True)\n', (641, 665), False, 'import pyhecdss\n'), ((782, 805), 'pyhecdss.DSSFile', 'pyhecdss... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-15, 15, 0.5)
X, Y = np.meshgrid(x, y)
sigma = 4
Z = np.exp(-(X**2 + Y**2)/(2*sigma**2)) / (2*np.pi*sigma**2)
ax.plot_s... | [
"matplotlib.pyplot.savefig",
"numpy.exp",
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"numpy.arange"
] | [((124, 136), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (134, 136), True, 'import matplotlib.pyplot as plt\n'), ((189, 212), 'numpy.arange', 'np.arange', (['(-15)', '(15)', '(0.5)'], {}), '(-15, 15, 0.5)\n', (198, 212), True, 'import numpy as np\n'), ((220, 237), 'numpy.meshgrid', 'np.meshgrid', (['x'... |
import os
from random import seed
import numpy as np
from hyperopt import hp, tpe, rand
import pytest
from sklearn.metrics import mean_squared_error as mse, roc_auc_score as roc
from fedot.core.data.data import InputData
from fedot.core.data.data_split import train_test_data_setup
from fedot.core.pipelines.node impor... | [
"fedot.core.pipelines.tuning.unified.PipelineTuner",
"fedot.core.pipelines.node.SecondaryNode",
"numpy.arange",
"fedot.core.data.data_split.train_test_data_setup",
"os.path.join",
"fedot.core.pipelines.pipeline.Pipeline",
"random.seed",
"fedot.core.pipelines.tuning.sequential.SequentialTuner",
"pyte... | [((712, 719), 'random.seed', 'seed', (['(1)'], {}), '(1)\n', (716, 719), False, 'from random import seed\n'), ((720, 737), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (734, 737), True, 'import numpy as np\n'), ((741, 757), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (755, 757), False, 'impo... |
import pyPLUTO as pp
import numpy as np
import matplotlib.pyplot as plt
import os, shutil, sys
from multiprocessing import Pool
# Value of theta and m
# TODO : Extract this directly from the run
gamma = 5.0/3.0
theta = 10.0
m = 1.0
def create_directory(path):
'''
Creates given directory.
Removes exist... | [
"matplotlib.pyplot.ylabel",
"numpy.array",
"numpy.gradient",
"os.path.exists",
"os.listdir",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.empty",
"os.mkdir",
"pyPLUTO.pload",
"numpy.abs",
"matplotlib.pyplot.savefig",
"numpy.average",
"numpy.save... | [((397, 417), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (411, 417), False, 'import os, shutil, sys\n'), ((451, 465), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (459, 465), False, 'import os, shutil, sys\n'), ((624, 640), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (634, 640), ... |
import pathlib
import pytest
import numpy as np
from plums.commons.data import TileWrapper, Record, RecordCollection, DataPoint
from plums.dataflow.dataset import PatternDataset
def _dummy_tile_driver(paths, **matches):
paths = sorted(paths, key=str, reverse=True)
print(paths)
print(matches)
retur... | [
"plums.commons.data.RecordCollection",
"plums.dataflow.dataset.PatternDataset",
"plums.commons.data.Record",
"numpy.zeros",
"pytest.raises"
] | [((488, 509), 'numpy.zeros', 'np.zeros', (['(12, 12, 3)'], {}), '((12, 12, 3))\n', (496, 509), True, 'import numpy as np\n'), ((1183, 1273), 'plums.commons.data.Record', 'Record', (['[[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]]', "('label',)"], {'paths': 'paths'}), "([[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]], ('label',)... |
from keras.utils import np_utils
import numpy as np
import h5py
import os
class HDF5DatasetWriter:
def __init__(self, dims, outputPath, dataKey="images",max_label_length=1,
bufSize=1000):
if os.path.exists(outputPath):
raise ValueError("The supplied 'outputPath' already "
"exists and cannot be overwritten... | [
"os.path.exists",
"numpy.ones",
"h5py.File",
"numpy.array",
"numpy.zeros",
"keras.utils.np_utils.to_categorical",
"h5py.special_dtype",
"numpy.arange"
] | [((198, 224), 'os.path.exists', 'os.path.exists', (['outputPath'], {}), '(outputPath)\n', (212, 224), False, 'import os\n'), ((442, 468), 'h5py.File', 'h5py.File', (['outputPath', '"""w"""'], {}), "(outputPath, 'w')\n", (451, 468), False, 'import h5py\n'), ((1155, 1183), 'h5py.special_dtype', 'h5py.special_dtype', ([],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.