code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# External
import math
import numpy
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from matplotlib.offsetbox import AnchoredText
# Local
from .utils import gaussian_fit, freq_content
plt.style.use('seaborn')
plt.rc('font', siz... | [
"numpy.prod",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.colorbar",
"mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.tight_layout",
... | [((277, 301), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (290, 301), True, 'import matplotlib.pyplot as plt\n'), ((302, 325), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(15)'}), "('font', size=15)\n", (308, 325), True, 'import matplotlib.pyplot as plt\n')... |
"""
Script that trains multitask models on hiv dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
import deepchem as dc
from hiv_datasets import load_hiv
# Only for debug!
np.random.seed(123)
# Load hiv dataset
... | [
"hiv_datasets.load_hiv",
"numpy.random.seed",
"deepchem.metrics.Metric"
] | [((277, 296), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (291, 296), True, 'import numpy as np\n'), ((378, 388), 'hiv_datasets.load_hiv', 'load_hiv', ([], {}), '()\n', (386, 388), False, 'from hiv_datasets import load_hiv\n'), ((474, 526), 'deepchem.metrics.Metric', 'dc.metrics.Metric', (['dc.me... |
"""Slightly customized versions of numpy / scipy linalg methods.
The standard numpy and scipy linalg routines both cope badly with
0-dimensional matrices or vectors. This module wraps several standard
routines to check for these special cases.
"""
# Copyright 2011, 2012, 2013, 2014, 2015 <NAME>
# This file is part o... | [
"numpy.eye",
"numpy.linalg.solve",
"scipy.linalg.cho_solve",
"numpy.linalg.pinv",
"codedep.codeDeps",
"numpy.tensordot",
"scipy.linalg.cholesky",
"numpy.linalg.inv",
"numpy.shape"
] | [((524, 534), 'codedep.codeDeps', 'codeDeps', ([], {}), '()\n', (532, 534), False, 'from codedep import codeDeps\n'), ((717, 727), 'codedep.codeDeps', 'codeDeps', ([], {}), '()\n', (725, 727), False, 'from codedep import codeDeps\n'), ((912, 922), 'codedep.codeDeps', 'codeDeps', ([], {}), '()\n', (920, 922), False, 'fr... |
import unittest
import FrictionQPotFEM
import GMatElastoPlasticQPot.Cartesian2d as GMat
import GooseFEM
import numpy as np
class test_Generic2d(unittest.TestCase):
"""
Tests
"""
def test_eventDrivenSimpleShear(self):
"""
Simple test of event driven simple shear in a homogeneous syste... | [
"numpy.ones",
"numpy.random.random",
"numpy.diff",
"numpy.any",
"numpy.zeros",
"GooseFEM.Mesh.Quad4.Regular",
"unittest.main",
"numpy.all",
"numpy.zeros_like"
] | [((13114, 13129), 'unittest.main', 'unittest.main', ([], {}), '()\n', (13127, 13129), False, 'import unittest\n'), ((443, 476), 'GooseFEM.Mesh.Quad4.Regular', 'GooseFEM.Mesh.Quad4.Regular', (['(3)', '(3)'], {}), '(3, 3)\n', (470, 476), False, 'import GooseFEM\n'), ((1306, 1325), 'numpy.zeros_like', 'np.zeros_like', (['... |
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import csv
import numpy as np
# Read The data
training_set = pd.read_json('../raw_data/train_set.json')
test_set = pd.read_json('../raw_data/test_set.json')
document_set = pd.read_json('.... | [
"numpy.sum",
"pandas.read_json"
] | [((194, 236), 'pandas.read_json', 'pd.read_json', (['"""../raw_data/train_set.json"""'], {}), "('../raw_data/train_set.json')\n", (206, 236), True, 'import pandas as pd\n'), ((248, 289), 'pandas.read_json', 'pd.read_json', (['"""../raw_data/test_set.json"""'], {}), "('../raw_data/test_set.json')\n", (260, 289), True, '... |
import json
import numpy as np
if __name__ == "__main__":
models = {'vanilla': 0, 'classification': 0, 'proxi_dist': 0, 'combined': 0}
models_list = ['vanilla', 'classification', 'proxi_dist', 'combined']# for consistency in older versions
for flavor in models_list:
with open(f'./accuracy_{flavor}... | [
"json.load",
"numpy.argmax"
] | [((373, 385), 'json.load', 'json.load', (['f'], {}), '(f)\n', (382, 385), False, 'import json\n'), ((786, 811), 'numpy.argmax', 'np.argmax', (['acc[model][1:]'], {}), '(acc[model][1:])\n', (795, 811), True, 'import numpy as np\n')] |
import torch
import os
import random
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
import sys
import json
from glob import glob
from PIL import ImageDraw
from misc.mask_utils import scatterMask
from misc.utils import denorm
import glob
from scipy.io import loadmat
from tqdm import tqdm
m... | [
"PIL.Image.new",
"scipy.io.loadmat",
"torch.from_numpy",
"numpy.array",
"PIL.ImageDraw.Draw",
"torchvision.utils.make_grid",
"torch.ByteTensor",
"sys.path.append",
"argparse.ArgumentParser",
"torch.zeros_like",
"misc.utils.denorm",
"random.shuffle",
"types.SimpleNamespace",
"ipdb.set_trace... | [((349, 360), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (358, 360), False, 'import os\n'), ((399, 427), 'sys.path.append', 'sys.path.append', (['module_path'], {}), '(module_path)\n', (414, 427), False, 'import sys\n'), ((15340, 15388), 'data_loader.get_transformations', 'get_transformations', ([], {'mode': '"""test"... |
import numpy as np
from scipy import optimize
class Parameter:
def __init__(self, value, name=''):
self.value = value
self.name = name
def set(self, value):
self.value = value
def __call__(self):
return self.value
def gauss(gA,gx0,gs):
"""
returns the fit func... | [
"numpy.sqrt"
] | [((1375, 1395), 'numpy.sqrt', 'np.sqrt', (['(chisq / dof)'], {}), '(chisq / dof)\n', (1382, 1395), True, 'import numpy as np\n'), ((1002, 1020), 'numpy.sqrt', 'np.sqrt', (['cov[i, i]'], {}), '(cov[i, i])\n', (1009, 1020), True, 'import numpy as np\n'), ((1020, 1040), 'numpy.sqrt', 'np.sqrt', (['(chisq / dof)'], {}), '(... |
import numpy as np
from glob import glob
import xarray as xr
from argparse import ArgumentParser
import warnings
warnings.filterwarnings("ignore")
# compute climatology for one region
p = ArgumentParser()
p.add_argument('-region', choices=('NPSG','EqPac','SO'), action = "store", dest = "region", help ='region where p... | [
"numpy.tile",
"numpy.mean",
"numpy.sqrt",
"argparse.ArgumentParser",
"numpy.divide",
"numpy.power",
"numpy.square",
"xarray.concat",
"numpy.array",
"numpy.linspace",
"glob.glob",
"numpy.unravel_index",
"numpy.save",
"numpy.expand_dims",
"numpy.meshgrid",
"xarray.open_dataset",
"warni... | [((113, 146), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (136, 146), False, 'import warnings\n'), ((190, 206), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (204, 206), False, 'from argparse import ArgumentParser\n'), ((1143, 1175), 'xarray.open_datase... |
# coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | [
"numpy.dstack",
"numpy.tile",
"deeplab2.data.preprocessing.preprocess_utils.get_random_scale",
"tensorflow.random.normal",
"tensorflow.random.set_seed",
"numpy.random.rand",
"deeplab2.data.preprocessing.preprocess_utils.resize_to_range",
"numpy.isclose",
"tensorflow.test.main",
"numpy.random.randi... | [((13336, 13350), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (13348, 13350), True, 'import tensorflow as tf\n'), ((840, 903), 'numpy.dstack', 'np.dstack', (['[[[5.0, 6.0], [9.0, 0.0]], [[4.0, 3.0], [3.0, 5.0]]]'], {}), '([[[5.0, 6.0], [9.0, 0.0]], [[4.0, 3.0], [3.0, 5.0]]])\n', (849, 903), True, 'import ... |
import numpy as np
import pandas as pd
class EventNode:
"""
Base Class for behavior log linked list:
example:
------
from behaviors import BehaviorMat
code_map = BehaviorMat.code_map
eventlist = PSENode(None, None, None, None)
import h5py
hfile = h5py.File("D1-R35-RV_p155_raw_behav... | [
"numpy.ceil"
] | [((1642, 1661), 'numpy.ceil', 'np.ceil', (['self.trial'], {}), '(self.trial)\n', (1649, 1661), True, 'import numpy as np\n')] |
# Borrowed from https://gitlab.tiker.net/jdsteve2/perflex
import pyopencl as cl
import loopy as lp
import time
import numpy as np
def time_knl(knl, ctx, param_dict):
def create_rand_args(ctx, knl, param_dict):
queue = cl.CommandQueue(ctx)
info = lp.generate_code_v2(knl).implemented_data_info
... | [
"loopy.auto_test.make_ref_args",
"loopy.auto_test.make_args",
"numpy.average",
"pyopencl.CommandQueue",
"loopy.generate_code_v2",
"loopy.set_options",
"time.time"
] | [((666, 686), 'pyopencl.CommandQueue', 'cl.CommandQueue', (['ctx'], {}), '(ctx)\n', (681, 686), True, 'import pyopencl as cl\n'), ((775, 809), 'loopy.set_options', 'lp.set_options', (['knl'], {'no_numpy': '(True)'}), '(knl, no_numpy=True)\n', (789, 809), True, 'import loopy as lp\n'), ((1035, 1063), 'numpy.average', 'n... |
# Each segment has another segment of the image showing (not black)
# As if you are slowly lookinng at someone's face from above
# Segment numbers are as follows:
# 1. Forehead (dowm to eyebrows)
# 2. Eyebrows (down to eyes)
# 3. Eyes
# 4. Nose
# 5. Mouth
# 6. Chin
# 7. Full
import logging
import numpy as np
import o... | [
"os.listdir",
"cv2.resize",
"pandas.read_csv",
"tqdm.tqdm",
"os.access",
"logging.info",
"numpy.append",
"segments_helpers.top_to_bottom_segments",
"os.mkdir",
"datetime.date.today",
"cv2.imread"
] | [((445, 457), 'datetime.date.today', 'date.today', ([], {}), '()\n', (455, 457), False, 'from datetime import date\n'), ((1164, 1220), 'pandas.read_csv', 'pd.read_csv', (['landmarks_file_name'], {'index_col': '"""image_name"""'}), "(landmarks_file_name, index_col='image_name')\n", (1175, 1220), True, 'import pandas as ... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import scipy.stats
import sys
from tqdm import tqdm
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scip... | [
"numpy.mean",
"matplotlib.pyplot.savefig",
"matplotlib.ticker.MultipleLocator",
"tqdm.tqdm",
"numpy.argmax",
"numpy.array",
"numpy.load",
"matplotlib.pyplot.show"
] | [((478, 493), 'tqdm.tqdm', 'tqdm', (['filenames'], {}), '(filenames)\n', (482, 493), False, 'from tqdm import tqdm\n'), ((2756, 2795), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""scalability.pdf"""'], {'dpi': '(200)'}), "('scalability.pdf', dpi=200)\n", (2767, 2795), True, 'import matplotlib.pyplot as plt\n'), ((... |
import numpy as np
import matplotlib.pyplot as plt
#data_folder = './experiment_results/'
task = 'mnist'
#flags = ['wb', 'wb_kernel', 'kernel', 'nn']
flags = ['nn']
for flag in flags:
fname = task+flag+'.npy'
[standard, at] = np.load(fname)
ep = [0.01*i for i in range(21)]
fig, ax = plt.subplots()
... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gca",
"numpy.load",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((235, 249), 'numpy.load', 'np.load', (['fname'], {}), '(fname)\n', (242, 249), True, 'import numpy as np\n'), ((301, 315), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (313, 315), True, 'import matplotlib.pyplot as plt\n'), ((413, 422), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (420, 42... |
from __future__ import print_function, division
import sys
sys.path.append('core')
import argparse
import os
import cv2
import time
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader... | [
"flow_vis.flow_to_color",
"numpy.array",
"torch.sum",
"torch.nn.functional.interpolate",
"sys.path.append",
"datasets.fetch_dataloader",
"torch.utils.tensorboard.SummaryWriter",
"evaluate.validate_chairs",
"argparse.ArgumentParser",
"evaluate.validate_kitti",
"os.path.isdir",
"numpy.random.see... | [((59, 82), 'sys.path.append', 'sys.path.append', (['"""core"""'], {}), "('core')\n", (74, 82), False, 'import sys\n'), ((14695, 14726), 'datasets.fetch_dataloader', 'datasets.fetch_dataloader', (['args'], {}), '(args)\n', (14720, 14726), False, 'import datasets\n'), ((17465, 17490), 'argparse.ArgumentParser', 'argpars... |
from typing import List
Vector = List[float]
Matrix = List[Vector]
def zero_matrix(mat: Matrix) -> None:
m = len(mat)
n = len(mat[0])
zero_row = [False for _ in range(m)]
zero_col = [False for _ in range(n)]
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
zero_row[i] = True
... | [
"icecream.ic",
"numpy.random.PCG64"
] | [((816, 828), 'numpy.random.PCG64', 'PCG64', (['(12345)'], {}), '(12345)\n', (821, 828), False, 'from numpy.random import PCG64, Generator\n'), ((913, 921), 'icecream.ic', 'ic', (['mat0'], {}), '(mat0)\n', (915, 921), False, 'from icecream import ic\n'), ((948, 956), 'icecream.ic', 'ic', (['mat0'], {}), '(mat0)\n', (95... |
import numpy as np
import pandas as pd
from statsmodels.regression.lme import MixedLM
from numpy.testing import assert_almost_equal
from . import lme_r_results
from scipy.misc import derivative
from statsmodels.base import _penalties as penalties
import os
import csv
class R_Results(object):
"""
A class for h... | [
"numpy.arange",
"numpy.atleast_2d",
"os.listdir",
"statsmodels.regression.lme.MixedLM",
"numpy.asarray",
"scipy.misc.derivative",
"numpy.testing.assert_almost_equal",
"numpy.dot",
"numpy.random.seed",
"statsmodels.base._penalties.PseudoHuber",
"pandas.DataFrame",
"csv.reader",
"numpy.random.... | [((9549, 9636), 'nose.runmodule', 'nose.runmodule', ([], {'argv': "[__file__, '-vvs', '-x', '--pdb', '--pdb-failure']", 'exit': '(False)'}), "(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n", (9563, 9636), False, 'import nose\n'), ((1542, 1574), 'os.path.join', 'os.path.join', (['cur_dir', ... |
from numba import jit
import numpy as np
import cv2
random = np.array(np.power(np.random.rand(16, 8, 3), 3) * 255, dtype=np.uint8)
class Camera:
def _resize_frame(self, frame, dst, flip=0):
frame_shape = np.shape(frame)
frame_crop_height = int(frame_shape[1] / self._ratio)
crop_offset = (... | [
"numpy.random.rand",
"cv2.resize",
"cv2.flip",
"numpy.array",
"numpy.zeros",
"cv2.VideoCapture",
"cv2.cvtColor",
"numpy.shape",
"cv2.createBackgroundSubtractorKNN"
] | [((219, 234), 'numpy.shape', 'np.shape', (['frame'], {}), '(frame)\n', (227, 234), True, 'import numpy as np\n'), ((1040, 1070), 'cv2.VideoCapture', 'cv2.VideoCapture', (['camera_index'], {}), '(camera_index)\n', (1056, 1070), False, 'import cv2\n'), ((1158, 1193), 'cv2.createBackgroundSubtractorKNN', 'cv2.createBackgr... |
import numpy as np
from PIL import Image
import sys
# 2018.05.29
# create Color R,G,B Range
Color_Range = []
Color_Diff = int(256 / 4)
for r in range(256):
for g in range(256):
for b in range(256):
if r % Color_Diff == 0 and g % Color_Diff == 0 and b % Color_Diff == 0:
Color_Ra... | [
"PIL.Image.fromarray",
"PIL.Image.open",
"numpy.array",
"numpy.zeros",
"sys.exit"
] | [((357, 378), 'numpy.array', 'np.array', (['Color_Range'], {}), '(Color_Range)\n', (365, 378), True, 'import numpy as np\n'), ((435, 457), 'PIL.Image.open', 'Image.open', (['"""test.jpg"""'], {}), "('test.jpg')\n", (445, 457), False, 'from PIL import Image\n'), ((490, 505), 'numpy.array', 'np.array', (['image'], {}), '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 15:50:52 2018
@author: huangdou
"""
import numpy as np
import matplotlib.pyplot as plt
import time
from statsmodels.tsa.arima_model import ARIMA
from pandas.tools.plotting import autocorrelation_plot
from multiprocessing import Pool
import os
im... | [
"time.ctime",
"sklearn.decomposition.PCA",
"os.chdir",
"numpy.zeros",
"glob.glob",
"statsmodels.tsa.arima_model.ARIMA",
"numpy.load",
"time.time",
"numpy.save",
"numpy.str"
] | [((459, 489), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (462, 489), False, 'from sklearn.decomposition import PCA\n'), ((661, 702), 'numpy.load', 'np.load', (["('../data/temp/train/' + filename)"], {}), "('../data/temp/train/' + filename)\n", (668, 702)... |
from pytinyexr import PyEXRImage
exrImage = PyEXRImage('2by2.exr')
print(exrImage.filename)
print(exrImage.width)
print(exrImage.height)
print(exrImage)
# Direct access to floats
for i in range(exrImage.width * exrImage.height):
r = exrImage.get(4 * i + 0)
g = exrImage.get(4 * i + 1)
b = exrImage.get(4 *... | [
"numpy.array",
"pytinyexr.PyEXRImage",
"numpy.reshape"
] | [((45, 67), 'pytinyexr.PyEXRImage', 'PyEXRImage', (['"""2by2.exr"""'], {}), "('2by2.exr')\n", (55, 67), False, 'from pytinyexr import PyEXRImage\n'), ((768, 798), 'numpy.array', 'np.array', (['exrImage'], {'copy': '(False)'}), '(exrImage, copy=False)\n', (776, 798), True, 'import numpy as np\n'), ((885, 936), 'numpy.re... |
import matplotlib.pyplot as plt
import numpy as np
class ResultDrawer:
def __init__(self, row=6, col=4):
self.num_rows = row
self.num_cols = col
self.class_names = ['male', 'female']
def plot_image(self, i, predictions_array, true_label, img):
true_label, img = true_label[i], ... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xticks",
"numpy.argmax",
"numpy.max",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((335, 350), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (343, 350), True, 'import matplotlib.pyplot as plt\n'), ((359, 373), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (369, 373), True, 'import matplotlib.pyplot as plt\n'), ((382, 396), 'matplotlib.pyplot.yticks', 'plt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 09:58:50 2020
@author: duttar
Description: Solving the problem A = Bx
A is the timeseries stack of InSAR pixel wise
B is matrix including time and ADDT
x is a vector containing seasonal and overall subsidence
"""
import os
import numpy as n... | [
"scipy.io.savemat",
"scipy.io.loadmat",
"multiprocessing.cpu_count",
"numpy.array",
"numpy.mod",
"numpy.reshape",
"numpy.where",
"numpy.max",
"numpy.empty",
"numpy.concatenate",
"numpy.min",
"os.path.expanduser",
"numpy.round",
"numpy.abs",
"numpy.ones",
"numpy.size",
"numpy.floor",
... | [((1645, 1755), 'os.path.expanduser', 'os.path.expanduser', (['"""/data/not_backed_up/rdtta/Permafrost/Alaska/North_slope/DT102/Stack/timeseries"""'], {}), "(\n '/data/not_backed_up/rdtta/Permafrost/Alaska/North_slope/DT102/Stack/timeseries'\n )\n", (1663, 1755), False, 'import os\n'), ((1785, 1835), 'os.path.joi... |
# -*- coding: utf-8 -*-
""" Gathers codes snippets used in the test suite.
"""
import unittest
from contextlib import contextmanager
from functools import wraps
import os
import sys
import numpy as np
import PIL
test_dir = os.path.dirname(__file__)
temporary_data_dir = os.path.join(test_dir, "_temporary_data")
ref_da... | [
"unittest.TestSuite",
"PIL.ImageChops.difference",
"PIL.Image.open",
"numpy.mean",
"os.path.join",
"os.path.splitext",
"functools.wraps",
"numpy.asarray",
"os.path.dirname",
"unittest.TestLoader"
] | [((225, 250), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (240, 250), False, 'import os\n'), ((272, 313), 'os.path.join', 'os.path.join', (['test_dir', '"""_temporary_data"""'], {}), "(test_dir, '_temporary_data')\n", (284, 313), False, 'import os\n'), ((329, 369), 'os.path.join', 'os.path... |
#!/usr/bin/env python
"""
Copyright 2019, <NAME>, HKUST.
Training script.
"""
from __future__ import print_function
import os
import time
import sys
import math
import argparse
from random import randint
import cv2
import numpy as np
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.com... | [
"tensorflow.compat.v1.summary.merge",
"tensorflow.equal",
"tensorflow.compat.v1.get_collection",
"tensorflow.reduce_mean",
"sys.path.append",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.train.exponential_decay",
"tensorflow.Graph",
"te... | [((279, 341), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.ERROR'], {}), '(tf.compat.v1.logging.ERROR)\n', (313, 341), True, 'import tensorflow as tf\n'), ((380, 402), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (395, 402), False... |
import numpy
import theano
from nose.plugins.skip import SkipTest
from theano.tests.unittest_tools import verify_grad
try:
from pylearn2.sandbox.cuda_convnet.response_norm import (
CrossMapNorm,
CrossMapNormUndo
)
from theano.sandbox.cuda import CudaNdarrayType, CudaNdarray
from theano.... | [
"theano.function",
"theano.sandbox.cuda.basic_ops.gpu_contiguous",
"numpy.ones",
"pylearn2.sandbox.cuda_convnet.response_norm.CrossMapNorm",
"theano.sandbox.cuda.CudaNdarrayType",
"theano.sandbox.cuda.ftensor4",
"theano.compile.mode.get_mode",
"theano.sandbox.cuda.gpu_from_host",
"theano.tests.unitt... | [((784, 824), 'pylearn2.sandbox.cuda_convnet.response_norm.CrossMapNorm', 'CrossMapNorm', (['(16)', '(15.0 / 16.0)', '(1.0)', '(True)'], {}), '(16, 15.0 / 16.0, 1.0, True)\n', (796, 824), False, 'from pylearn2.sandbox.cuda_convnet.response_norm import CrossMapNorm, CrossMapNormUndo\n'), ((1094, 1133), 'numpy.random.Ran... |
def t89c(points, iopt=0, ps=0.0):
import numpy as np
from geopack.geopack import dip, recalc
from geopack import t89
ut = 100 # 1970-01-01/00:01:40 UT.
ps = recalc(ut)
print(ps)
B = np.zeros(points.shape)
for i in range(points.shape[0]):
r = np.linalg.norm(points[i,:])
... | [
"numpy.ones",
"geopack.geopack.recalc",
"numpy.zeros",
"geopack.geopack.dip",
"geopack.t89.t89",
"numpy.linalg.norm"
] | [((183, 193), 'geopack.geopack.recalc', 'recalc', (['ut'], {}), '(ut)\n', (189, 193), False, 'from geopack.geopack import dip, recalc\n'), ((217, 239), 'numpy.zeros', 'np.zeros', (['points.shape'], {}), '(points.shape)\n', (225, 239), True, 'import numpy as np\n'), ((289, 317), 'numpy.linalg.norm', 'np.linalg.norm', ([... |
import cv2
import numpy as np
import nn_models
import data_loading.image_loading as il
import nn_models.Models as models
import data_loading.data_loaders as loaders
import numpy.random
import torch, random
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm as tqdm
import pickle
from datetime impor... | [
"torch.from_numpy",
"torch.nn.MSELoss",
"numpy.array",
"nn_models.Models.CommandantNet",
"argparse.ArgumentParser",
"torch.mean",
"matplotlib.pyplot.plot",
"numpy.subtract",
"os.path.split",
"os.mkdir",
"cv2.VideoWriter_fourcc",
"cv2.warpAffine",
"data_loading.data_loaders.F1SequenceDataset"... | [((580, 634), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test AdmiralNet"""'}), "(description='Test AdmiralNet')\n", (603, 634), False, 'import argparse\n'), ((978, 1013), 'os.path.split', 'os.path.split', (['args.annotation_file'], {}), '(args.annotation_file)\n', (991, 1013), False... |
"""Create data for test_model::test_dipole1d."""
import numpy as np
from external import dipole1d
# # Comparison to DIPOLE1D for EE/ME
# Define model
freq = np.array([0.78])
depth = np.array([213.5, 500, 1000])
res = np.array([3.5, .1, 50, 13])
rec = [np.arange(1, 11)*1000, np.arange(-4, 6)*100, 350]
def collect_mo... | [
"numpy.array",
"external.dipole1d",
"numpy.savez_compressed",
"numpy.arange"
] | [((159, 175), 'numpy.array', 'np.array', (['[0.78]'], {}), '([0.78])\n', (167, 175), True, 'import numpy as np\n'), ((184, 212), 'numpy.array', 'np.array', (['[213.5, 500, 1000]'], {}), '([213.5, 500, 1000])\n', (192, 212), True, 'import numpy as np\n'), ((219, 247), 'numpy.array', 'np.array', (['[3.5, 0.1, 50, 13]'], ... |
from numpy import hstack
from numpy import sum
from numpy import zeros
from gwlfe.Input.LandUse.NLU import NLU
from gwlfe.Memoization import memoize
from gwlfe.MultiUse_Fxns.Erosion.ErosWashoff import ErosWashoff
from gwlfe.MultiUse_Fxns.Erosion.ErosWashoff import ErosWashoff_f
from gwlfe.MultiUse_Fxns.Erosion.SedDeli... | [
"gwlfe.Output.Loading.LuLoad.LuLoad",
"gwlfe.MultiUse_Fxns.Runoff.pRunoff.pRunoff_f",
"gwlfe.MultiUse_Fxns.Erosion.ErosWashoff.ErosWashoff",
"numpy.hstack",
"gwlfe.Output.Loading.LuLoad.LuLoad_f",
"numpy.zeros",
"gwlfe.MultiUse_Fxns.Runoff.pRunoff.pRunoff",
"gwlfe.Input.LandUse.NLU.NLU",
"gwlfe.Mult... | [((1008, 1025), 'numpy.zeros', 'zeros', (['(NYrs, 16)'], {}), '((NYrs, 16))\n', (1013, 1025), False, 'from numpy import zeros\n'), ((1041, 1244), 'gwlfe.MultiUse_Fxns.Runoff.pRunoff.pRunoff', 'pRunoff', (['NYrs', 'DaysMonth', 'InitSnow_0', 'Temp', 'Prec', 'AntMoist_0', 'NRur', 'NUrb', 'CN', 'Grow_0', 'Area', 'PhosConc'... |
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright Holders: <NAME>, <NAME>, <NAME>
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
from collections import defaultdict
import numpy as np
from pymo... | [
"numpy.empty_like",
"numpy.array",
"collections.defaultdict"
] | [((1885, 1902), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1896, 1902), False, 'from collections import defaultdict\n'), ((4939, 4956), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4950, 4956), False, 'from collections import defaultdict\n'), ((6702, 6735), 'numpy.e... |
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def problem():
"""
Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
"""
# Accord... | [
"matplotlib.pyplot.imshow",
"numpy.random.randint",
"matplotlib.image.imread",
"matplotlib.pyplot.show"
] | [((1758, 1777), 'matplotlib.image.imread', 'mpimg.imread', (['image'], {}), '(image)\n', (1770, 1777), True, 'import matplotlib.image as mpimg\n'), ((1992, 2034), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_matrix_copy'], {'cmap': '"""gray"""'}), "(image_matrix_copy, cmap='gray')\n", (2002, 2034), True, 'import ... |
import rinobot_plugin as bot
import re
import os
import numpy as np
_end_tags = dict(grid=':HEADER_END:', scan='SCANIT_END', spec='[DATA]')
class NanonisFile(object):
"""
Base class for Nanonis data files (grid, scan, point spectroscopy).
Handles methods and parsing tasks common to all Nanonis files.
... | [
"numpy.fromfile",
"numpy.float",
"re.compile",
"numpy.asarray",
"os.path.split",
"rinobot_plugin.filepath",
"rinobot_plugin.no_extension",
"numpy.savetxt",
"rinobot_plugin.output_filepath",
"re.search"
] | [((10398, 10412), 'rinobot_plugin.filepath', 'bot.filepath', ([], {}), '()\n', (10410, 10412), True, 'import rinobot_plugin as bot\n'), ((10421, 10441), 're.compile', 're.compile', (['""".*.sxm"""'], {}), "('.*.sxm')\n", (10431, 10441), False, 'import re\n'), ((10451, 10473), 're.search', 're.search', (['p', 'filepath'... |
import functools
import itertools
import warnings
import imghdr
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import pytest
from pandas.testing import assert_frame_equal, assert_series_equal
from numpy.testing import assert_array_equal
from seaborn._core.plot import ... | [
"seaborn.external.version.Version",
"matplotlib.colors.to_rgba_array",
"numpy.array",
"pytest.fixture",
"pandas.testing.assert_frame_equal",
"matplotlib.lines.Line2D",
"numpy.reshape",
"pytest.mark.xfail",
"itertools.product",
"seaborn._core.plot.Plot",
"numpy.datetime64",
"pandas.DataFrame",
... | [((607, 683), 'functools.partial', 'functools.partial', (['assert_series_equal'], {'check_names': '(False)', 'check_dtype': '(False)'}), '(assert_series_equal, check_names=False, check_dtype=False)\n', (624, 683), False, 'import functools\n'), ((4253, 4295), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""v... |
import logging
import math
import pathlib
import typing as t
import numpy as np
import pandas as pd
from shapely.geometry import Point, LineString
from svglib.svglib import svg2rlg
from reportlab.graphics.shapes import Group, Rect, Path
from reportlab.lib.colors import Color
from .geometry import cartesian, polar, cl... | [
"logging.getLogger",
"reportlab.lib.colors.Color",
"math.degrees",
"shapely.geometry.Point",
"numpy.linspace",
"shapely.geometry.LineString"
] | [((347, 374), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (364, 374), False, 'import logging\n'), ((2708, 2739), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', '(500)'], {}), '(-np.pi, np.pi, 500)\n', (2719, 2739), True, 'import numpy as np\n'), ((2013, 2034), 'shapely.geometr... |
import astropy.units as u
import exifread
import matplotlib
import numpy as np
import scipy.ndimage as ndimage
from skimage.transform import hough_circle, hough_circle_peaks
from sunpy.map import GenericMap
import eclipse.meta as m
__all__ = ['find_sun_center_and_radius', 'eclipse_image_to_map']
def find_sun_center... | [
"numpy.mean",
"numpy.average",
"eclipse.meta.build_meta",
"eclipse.meta.get_image_time",
"eclipse.meta.build_wcs",
"matplotlib.image.imread",
"scipy.ndimage.label",
"skimage.transform.hough_circle_peaks",
"scipy.ndimage.find_objects",
"scipy.ndimage.sobel",
"sunpy.map.GenericMap",
"eclipse.met... | [((808, 838), 'scipy.ndimage.gaussian_filter', 'ndimage.gaussian_filter', (['im', '(8)'], {}), '(im, 8)\n', (831, 838), True, 'import scipy.ndimage as ndimage\n'), ((985, 1004), 'scipy.ndimage.label', 'ndimage.label', (['mask'], {}), '(mask)\n', (998, 1004), True, 'import scipy.ndimage as ndimage\n'), ((1181, 1224), 's... |
# -*- coding: utf-8 -*-
"""
Try continous collision checking for a simple path through an obstacle.
"""
import time
import fcl
import numpy as np
import matplotlib.pyplot as plt
from acrolib.plotting import get_default_axes3d, plot_reference_frame
from acrolib.geometry import translation
from acrobotics.robot_exampl... | [
"acrolib.geometry.translation",
"acrobotics.shapes.Box",
"acrobotics.robot_examples.Kuka",
"acrolib.plotting.get_default_axes3d",
"numpy.array",
"numpy.linspace",
"acrobotics.geometry.Scene",
"matplotlib.pyplot.show"
] | [((460, 466), 'acrobotics.robot_examples.Kuka', 'Kuka', ([], {}), '()\n', (464, 466), False, 'from acrobotics.robot_examples import Kuka\n'), ((559, 582), 'numpy.linspace', 'np.linspace', (['qa', 'qb', '(10)'], {}), '(qa, qb, 10)\n', (570, 582), True, 'import numpy as np\n'), ((597, 651), 'acrolib.plotting.get_default_... |
"""
Part 2 of https://adventofcode.com/2020/day/9
"""
import part1
import numpy as np
INVALID = 1309761972 # Answer from Part1
def find_sum(data):
for i in range(len(data)):
for j in range(0, i + 1):
moving_slice = data[j:i]
if sum(moving_slice) == INVALID:
retur... | [
"numpy.max",
"part1.read_data",
"numpy.min"
] | [((436, 464), 'part1.read_data', 'part1.read_data', (['"""input.txt"""'], {}), "('input.txt')\n", (451, 464), False, 'import part1\n'), ((322, 342), 'numpy.min', 'np.min', (['moving_slice'], {}), '(moving_slice)\n', (328, 342), True, 'import numpy as np\n'), ((345, 365), 'numpy.max', 'np.max', (['moving_slice'], {}), '... |
import os
import numpy as np
import pandas as pd
import tensorflow as tf
from scipy import stats
from tensorflow.keras import layers
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler,OneHotEncoder
from itertools import product
from... | [
"numpy.hstack",
"tensorflow.GradientTape",
"numpy.array",
"numpy.argsort",
"tensorflow.keras.losses.CategoricalCrossentropy",
"tensorflow.cast",
"numpy.arange",
"numpy.save",
"os.path.exists",
"numpy.reshape",
"numpy.where",
"itertools.product",
"tensorflow.concat",
"numpy.linspace",
"nu... | [((2506, 2534), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (2520, 2534), True, 'import numpy as np\n'), ((2543, 2575), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['random_state'], {}), '(random_state)\n', (2561, 2575), True, 'import tensorflow as tf\n'), ((5331, 5381), ... |
import zipfile
from matplotlib.ticker import FormatStrFormatter
import matplotlib.ticker as tick
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import logging
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator,MaxNLocator
from matplotlib.offsetbox import TextAr... | [
"logging.getLogger",
"matplotlib.pyplot.grid",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"zipfile.ZipFile",
"matplotlib.pyplot.axvline",
"numpy.array",
"matplotlib.ticker.MaxNLocator",
"logging.error",
"logging.info",
"os.path.exists",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pypl... | [((378, 417), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (397, 417), False, 'import logging\n'), ((430, 469), 'logging.getLogger', 'logging.getLogger', (['"""ActionEventPlotter"""'], {}), "('ActionEventPlotter')\n", (447, 469), False, 'import logging\n'), ((... |
import numpy as np
from src.network_elements.network_element import NetworkElement
class Sigmoid(NetworkElement):
def __init__(self) -> None:
self.current_layer_output = None
def sigmoid(self, Z):
return 1 / (1 - np.exp(Z))
def sigmoid_derivative(self, Z):
return self.sigmoid(Z) * (1 - self.... | [
"numpy.exp"
] | [((234, 243), 'numpy.exp', 'np.exp', (['Z'], {}), '(Z)\n', (240, 243), True, 'import numpy as np\n')] |
import sys
sys.path.append('../')
import constants as cnst
import os
import torch
import tqdm
import numpy as np
import constants
SHAPE = [0, 1, 2]
EXP = [50, 51, 52]
POSE = [150, 151, 152, 153, 154, 155]
def centre_using_nearest(flame_seq, flame_dataset, one_translation_for_whole_seq=True):
shape_weigth = 0
... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Sequential",
"numpy.array",
"torch.nn.MSELoss",
"torch.nn.BatchNorm1d",
"numpy.linalg.norm",
"sys.path.append",
"constants.get_idx_list",
"torch.pinverse",
"numpy.concatenate",
"numpy.argmin",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"tor... | [((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((3881, 3946), 'torch.cat', 'torch.cat', (['(shape, expression, pose, required_translation)'], {'dim': '(1)'}), '((shape, expression, pose, required_translation), dim=1)\n', (3890, 3946), False, 'import... |
import numpy as np
from sklearn.metrics import mean_squared_error, accuracy_score
class BaseModel(object):
"""
Base model to run the test
"""
def __init__(self):
self.max_depth = 6
self.learning_rate = 1
self.min_split_loss = 1
self.min_weight = 1
self.L1_r... | [
"numpy.argmax",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.mean_squared_error"
] | [((1188, 1225), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['data.y_test', 'pred'], {}), '(data.y_test, pred)\n', (1206, 1225), False, 'from sklearn.metrics import mean_squared_error, accuracy_score\n'), ((1570, 1603), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['data.y_test', 'pred'], {}), ... |
import os
import sys
import glob
from comet_ml import Experiment, OfflineExperiment
import logging
import warnings
import pickle
from argparse import ArgumentParser
warnings.simplefilter(action="ignore")
import functools
import numpy as np
import pandas as pd
# from sklearn.model_selection import KFold
from sklearn... | [
"argparse.ArgumentParser",
"learning.accuracy.log_last_stats_of_fold",
"learning.accuracy.post_cross_validation_logging",
"learning.train.train_full",
"utils.load_data.load_pseudo_labelled_datasets",
"learning.kde_mixture.get_fitted_kde_mixture_from_dataset",
"numpy.random.seed",
"warnings.simplefilte... | [((166, 204), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""'}), "(action='ignore')\n", (187, 204), False, 'import warnings\n'), ((440, 458), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (454, 458), True, 'import numpy as np\n'), ((459, 483), 'torch.cuda.empty_cache'... |
"""
Code ideas from https://github.com/Newmu/dcgan and tensorflow mnist dataset reader
"""
import numpy as np
#import scipy.misc as misc
from PIL import Image
import os
import glob
from random import shuffle, randint
class seg_dataset_reader:
path = ""
class_mappings = ""
files = []
images = []
ann... | [
"numpy.mean",
"PIL.Image.open",
"random.shuffle",
"numpy.arange",
"os.path.join",
"numpy.array",
"numpy.random.randint",
"numpy.expand_dims",
"sys.exit",
"pdb.set_trace",
"random.randint",
"glob.glob",
"numpy.random.shuffle"
] | [((1059, 1110), 'os.path.join', 'os.path.join', (['self.path', '"""images_png"""', "('*.' + 'png')"], {}), "(self.path, 'images_png', '*.' + 'png')\n", (1071, 1110), False, 'import os\n'), ((1199, 1219), 'random.shuffle', 'shuffle', (['images_list'], {}), '(images_list)\n', (1206, 1219), False, 'from random import shuf... |
import time
import analysis.event
import analysis.beamline
import analysis.background
import analysis.pixel_detector
import ipc
import random
import numpy
numpy.random.seed()
state = {
'Facility': 'dummy',
'squareImage' : True,
'Dummy': {
'Repetition Rate' : 10,
'Data Sources': {
... | [
"numpy.random.rand",
"ipc.new_data",
"time.sleep",
"numpy.random.randint",
"numpy.random.seed",
"random.random"
] | [((156, 175), 'numpy.random.seed', 'numpy.random.seed', ([], {}), '()\n', (173, 175), False, 'import numpy\n'), ((1080, 1127), 'ipc.new_data', 'ipc.new_data', (['"""TOF"""', "evt['ionTOFs']['tof'].data"], {}), "('TOF', evt['ionTOFs']['tof'].data)\n", (1092, 1127), False, 'import ipc\n'), ((1135, 1160), 'numpy.random.ra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""hydrological methods powered by pyFlwDir"""
import warnings
import logging
import numpy as np
import xarray as xr
import geopandas as gpd
import pyflwdir
from typing import Tuple, Union, Optional
from . import gis_utils
logger = logging.getLogger(__name__)
__all__ = ... | [
"logging.getLogger",
"xarray.Variable",
"numpy.isin",
"numpy.arange",
"xarray.merge",
"pyflwdir.gis_utils.get_edge",
"warnings.warn",
"numpy.maximum",
"pyflwdir.pyflwdir._infer_ftype",
"numpy.any",
"numpy.isnan",
"numpy.atleast_1d",
"geopandas.GeoDataFrame.from_features",
"numpy.logical_an... | [((281, 308), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (298, 308), False, 'import logging\n'), ((5148, 5242), 'xarray.DataArray', 'xr.DataArray', ([], {'dims': 'da_elv.raster.dims', 'coords': 'da_elv.raster.coords', 'data': 'd8', 'name': '"""flwdir"""'}), "(dims=da_elv.raster.dims, ... |
'''
Implementation of Classifier Training, partly described inside Fanello et al.
'''
import sys
import signal
import errno
import glob
import numpy as np
import class_objects as co
import action_recognition_alg as ara
import cv2
import os.path
import cPickle as pickle
import logging
import yaml
import time
from OptGri... | [
"logging.getLogger",
"logging.StreamHandler",
"matplotlib.pyplot.ylabel",
"class_objects.macro_metrics.construct_vectors",
"numpy.array2string",
"sklearn.ensemble.AdaBoostClassifier",
"numpy.logical_not",
"action_recognition_alg.ActionRecognition",
"numpy.hstack",
"numpy.array",
"numpy.isfinite"... | [((121963, 121992), 'logging.getLogger', 'logging.getLogger', (['"""__name__"""'], {}), "('__name__')\n", (121980, 121992), False, 'import logging\n'), ((121998, 122031), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stderr'], {}), '(sys.stderr)\n', (122019, 122031), False, 'import logging\n'), ((109670, 109... |
import numpy as np
from sklearn.linear_model import LogisticRegression
from .base import TransformationBaseModel
class Kane(TransformationBaseModel):
"""The class which implements the Kane's approach.
+----------------+-----------------------------------------------------------------------------------+
... | [
"numpy.array",
"sklearn.linear_model.LogisticRegression"
] | [((1462, 1491), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'n_jobs': '(-1)'}), '(n_jobs=-1)\n', (1480, 1491), False, 'from sklearn.linear_model import LogisticRegression\n'), ((5115, 5133), 'numpy.array', 'np.array', (['y_values'], {}), '(y_values)\n', (5123, 5133), True, 'import numpy as np... |
"""
Isotonic Regression that preserves 32bit inputs.
backported from scikit-learn pull request
https://github.com/scikit-learn/scikit-learn/pull/9106"""
import numpy as np
from sklearn.utils import as_float_array
from ._isotonic import _inplace_contiguous_isotonic_regression
def isotonic_regression(y, sample_weigh... | [
"numpy.clip",
"numpy.array",
"sklearn.utils.as_float_array"
] | [((1679, 1696), 'sklearn.utils.as_float_array', 'as_float_array', (['y'], {}), '(y)\n', (1693, 1696), False, 'from sklearn.utils import as_float_array\n'), ((1705, 1738), 'numpy.array', 'np.array', (['y[order]'], {'dtype': 'y.dtype'}), '(y[order], dtype=y.dtype)\n', (1713, 1738), True, 'import numpy as np\n'), ((1858, ... |
"""Log-gamma distribution."""
import numpy
from scipy import special
from ..baseclass import Dist
from ..operators.addition import Add
from .deprecate import deprecation_warning
class log_gamma(Dist):
"""Log-gamma distribution."""
def __init__(self, c):
Dist.__init__(self, c=c)
def _pdf(self, x... | [
"numpy.exp",
"scipy.special.gammaln",
"scipy.special.gammaincinv"
] | [((450, 462), 'numpy.exp', 'numpy.exp', (['x'], {}), '(x)\n', (459, 462), False, 'import numpy\n'), ((516, 541), 'scipy.special.gammaincinv', 'special.gammaincinv', (['c', 'q'], {}), '(c, q)\n', (535, 541), False, 'from scipy import special\n'), ((368, 386), 'scipy.special.gammaln', 'special.gammaln', (['c'], {}), '(c)... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"google.cloud.storage.Client",
"tensorflow.gfile.Open",
"tensorflow.equal",
"tensorflow.logging.error",
"dask.compute",
"tensorflow.contrib.data.ignore_errors",
"tensorflow.logging.info",
"tensorflow.matching_files",
"six.moves.urllib.parse.urlparse",
"dask.dataframe.read_csv",
"tensorflow.data.... | [((6033, 6049), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (6047, 6049), False, 'from google.cloud import storage\n'), ((9436, 9485), 'dask.compute', 'dask.compute', (['mean_op', 'median_op', 'mode_op', 'std_op'], {}), '(mean_op, median_op, mode_op, std_op)\n', (9448, 9485), False, 'import dask\... |
import numpy as np
def _numerical_gradient_no_batch(f, x):
'''梯度值计算函数'''
h = 1e-4
grad = np.zeros_like(x) #梯度值数组
for idx in range(x.size):
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fx_h1 = f(x) # f(x + h)
x[idx] = tmp_val - h
fx_h2 = f(x) # f(x - h)
... | [
"numpy.array",
"numpy.zeros_like"
] | [((103, 119), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (116, 119), True, 'import numpy as np\n'), ((571, 587), 'numpy.zeros_like', 'np.zeros_like', (['X'], {}), '(X)\n', (584, 587), True, 'import numpy as np\n'), ((1112, 1131), 'numpy.array', 'np.array', (['x_history'], {}), '(x_history)\n', (1120, 11... |
import pandas as pd
import numpy as np
import glob
from neuropixels import generalephys_mua as ephys_mua
from neuropixels.generalephys import get_waveform_duration,get_waveform_PTratio,get_waveform_repolarizationslope,option234_positions
from scipy.cluster.vq import kmeans2
import seaborn as sns;sns.set_style("ticks")
... | [
"matplotlib.pyplot.ylabel",
"seaborn.set_style",
"numpy.array",
"neuropixels.generalephys.get_waveform_repolarizationslope",
"numpy.mean",
"neuropixels.generalephys.get_waveform_duration",
"seaborn.color_palette",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.max",
... | [((297, 319), 'seaborn.set_style', 'sns.set_style', (['"""ticks"""'], {}), "('ticks')\n", (310, 319), True, 'import seaborn as sns\n'), ((5513, 5581), 'neuropixels.generalephys_mua.load_phy_template_mua', 'ephys_mua.load_phy_template_mua', (['path'], {'site_positions': 'site_positions'}), '(path, site_positions=site_po... |
from ProsNet.stack.posture_stack_abc import ABCPostureStack
from ProsNet.helper import Helper
from ProsNet.plotter import Plotter
import pandas as pd
import numpy as np
import math
import datetime
class EpochStack(ABCPostureStack, Helper, Plotter):
def __init__(self, processing_type='epoch'):
self.process... | [
"math.ceil",
"pandas.read_csv",
"numpy.arange",
"datetime.timedelta",
"pandas.to_datetime"
] | [((5399, 5434), 'pandas.read_csv', 'pd.read_csv', (['self.events_to_process'], {}), '(self.events_to_process)\n', (5410, 5434), True, 'import pandas as pd\n'), ((5461, 5523), 'pandas.to_datetime', 'pd.to_datetime', (['event_data.Time'], {'unit': '"""d"""', 'origin': '"""1899-12-30"""'}), "(event_data.Time, unit='d', or... |
"""Script demonstrating the ground effect contribution.
The simulation is run by a `CtrlAviary` environment.
Example
-------
In a terminal, run as:
$ python groundeffect.py
Notes
-----
The drone altitude tracks a sinusoid, near the ground plane.
"""
import os
import time
import argparse
from datetime import da... | [
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"numpy.floor",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.zeros",
"gym_pybullet_drones.utils.utils.sync",
"gym_pybullet_drones.envs.CtrlAviary.CtrlAviary",
"numpy.cos",
"time.time",
"numpy.sin",
"matplotlib.pyplot.title",
"matplotli... | [((820, 832), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (830, 832), True, 'import matplotlib.pyplot as plt\n'), ((837, 853), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (848, 853), True, 'import matplotlib.pyplot as plt\n'), ((858, 887), 'matplotlib.pyplot.title', 'plt.titl... |
def test_point_cloud_to_array(point_cloud):
import numpy as np
np_array = point_cloud.to_array()
assert np_array is not None
assert isinstance(np_array, np.ndarray)
def test_to_rgb_image(point_cloud):
import numpy as np
np_array = point_cloud.to_array()
image = np_array[["r", "g", "b"]]
... | [
"numpy.moveaxis",
"zivid.PointCloud",
"numpy.asarray",
"pytest.raises"
] | [((332, 389), 'numpy.asarray', 'np.asarray', (["[np_array['r'], np_array['g'], np_array['b']]"], {}), "([np_array['r'], np_array['g'], np_array['b']])\n", (342, 389), True, 'import numpy as np\n'), ((402, 442), 'numpy.moveaxis', 'np.moveaxis', (['image', '[0, 1, 2]', '[2, 0, 1]'], {}), '(image, [0, 1, 2], [2, 0, 1])\n'... |
# Forward: given model/pde parameters λ -> u(t, x)
import time, sys, os, json
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
# from plotting import newfig, savefig
# from mpl_toolkits.axes_grid1 import make_axes_... | [
"sys.path.insert",
"numpy.sqrt",
"tensorflow.gradients",
"numpy.array",
"matplotlib.pyplot.annotate",
"numpy.linalg.norm",
"matplotlib.pyplot.semilogy",
"numpy.reshape",
"tensorflow.placeholder",
"matplotlib.pyplot.plot",
"tensorflow.Session",
"matplotlib.pyplot.close",
"tensorflow.concat",
... | [((414, 452), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../Utilities/"""'], {}), "(0, '../../Utilities/')\n", (429, 452), False, 'import time, sys, os, json\n'), ((8886, 8916), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.0, 5.3)'}), '(figsize=(6.0, 5.3))\n', (8896, 8916), True, 'import ma... |
author = "eanorambuena"
author_email = "<EMAIL>"
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# 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 without limita... | [
"numpy.array",
"adam.error.ValueError"
] | [((1945, 1959), 'numpy.array', 'np.array', (['self'], {}), '(self)\n', (1953, 1959), True, 'import numpy as np\n'), ((1967, 1978), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (1975, 1978), True, 'import numpy as np\n'), ((2135, 2198), 'adam.error.ValueError', 'ValueError', (['None', '"""Matrices must be of equal d... |
import numpy as np
def one_hot(y, nb_classes):
""" one_hot
向量转one-hot
Arguments:
y: 带转换的向量
nb_classes: int 类别数
"""
y = np.asarray(y, dtype='int32')
if not nb_classes:
nb_classes = np.max(y) + 1
Y = np.zeros((len(y), nb_classes))
Y[np.arange(len(y)), y] = 1.
... | [
"numpy.ones",
"numpy.asarray",
"numpy.max",
"numpy.random.seed",
"numpy.random.permutation"
] | [((160, 188), 'numpy.asarray', 'np.asarray', (['y'], {'dtype': '"""int32"""'}), "(y, dtype='int32')\n", (170, 188), True, 'import numpy as np\n'), ((2120, 2140), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2134, 2140), True, 'import numpy as np\n'), ((2149, 2176), 'numpy.random.permutation', 'np... |
import sys
import pygame
def signal_handler(sig, frame):
print('Procedure terminated!')
pygame.display.quit()
pygame.quit()
sys.exit(0)
from scipy.interpolate import interp1d
## This function provides a prospective lateral-coordinate generator w.r.t possible longitudinal coordinates
## for the ego veh... | [
"torch.nn.ReLU",
"numpy.sqrt",
"pygame.quit",
"torch.mean",
"scipy.interpolate.interp1d",
"torch.nn.Conv2d",
"numpy.array",
"pygame.display.quit",
"torch.nn.MSELoss",
"torch.tensor",
"torch.nn.Linear",
"sys.exit",
"torch.std"
] | [((96, 117), 'pygame.display.quit', 'pygame.display.quit', ([], {}), '()\n', (115, 117), False, 'import pygame\n'), ((122, 135), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (133, 135), False, 'import pygame\n'), ((140, 151), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (148, 151), False, 'import sys\n'), ((417, ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.colors as colors
from scipy.integrate import cumtrapz, quad
from scipy.interpolate import interp1d
from scipy.stats import chi2
import PlottingTools as PT
import argparse
import os
#---------------
# MATPLOTLIB settings
m... | [
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"matplotlib.rcParams.update",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"PlottingTools.plotContour_modulation",
"PlottingTools.plotContour_nomodulation... | [((319, 381), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'font.size': 18, 'font.family': 'serif'}"], {}), "({'font.size': 18, 'font.family': 'serif'})\n", (338, 381), True, 'import matplotlib as mpl\n'), ((865, 892), 'matplotlib.rc', 'mpl.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
"""
A job class for solving the time-independent Schroedinger equation on a discrete mesh.
"""
from pyiron_base import ... | [
"numpy.isclose",
"numpy.roll",
"numpy.squeeze",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"numpy.meshgrid",
"numpy.all",
"numpy.gradient",
"numpy.arange"
] | [((1476, 1498), 'numpy.array', 'np.array', (['scalar_field'], {}), '(scalar_field)\n', (1484, 1498), True, 'import numpy as np\n'), ((1510, 1554), 'numpy.all', 'np.all', (['(scalar_field.shape == self.divisions)'], {}), '(scalar_field.shape == self.divisions)\n', (1516, 1554), True, 'import numpy as np\n'), ((2038, 206... |
import os
import unittest
import numpy
from mbtr import MolsMBTR2D, read_xyz_crystal, PeriodicMBTR2D
from mbtr import read_xyz_molecule
class TestMolecularMBTR(unittest.TestCase):
def load_xyz(self, filename, n_molecules):
xyz_fn = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
... | [
"numpy.triu_indices",
"mbtr.read_xyz_molecule",
"mbtr.PeriodicMBTR2D",
"os.path.realpath",
"numpy.array",
"numpy.sum",
"mbtr.read_xyz_crystal",
"mbtr.MolsMBTR2D"
] | [((371, 396), 'mbtr.read_xyz_molecule', 'read_xyz_molecule', (['xyz_fn'], {}), '(xyz_fn)\n', (388, 396), False, 'from mbtr import read_xyz_molecule\n'), ((527, 551), 'mbtr.MolsMBTR2D', 'MolsMBTR2D', ([], {'grid_size': '(10)'}), '(grid_size=10)\n', (537, 551), False, 'from mbtr import MolsMBTR2D, read_xyz_crystal, Perio... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
import pesfit as pf
import time
from hdfio import dict_io as io
import argparse
import multiprocessing as mp
import scipy.io as sio
n_cpu = mp.cpu_count()
fdir = r'E:\Diffraction\20190816_meas2_Lineouts_av_sorted.mat'
diffpat = sio.loadmat(f... | [
"scipy.io.loadmat",
"time.perf_counter",
"multiprocessing.cpu_count",
"numpy.array",
"numpy.moveaxis",
"pesfit.fitter.init_generator",
"numpy.arange"
] | [((218, 232), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (230, 232), True, 'import multiprocessing as mp\n'), ((307, 324), 'scipy.io.loadmat', 'sio.loadmat', (['fdir'], {}), '(fdir)\n', (318, 324), True, 'import scipy.io as sio\n'), ((457, 515), 'numpy.array', 'np.array', (['[60, 90, 160, 200, 220, ... |
# Copyright 2020, Battelle Energy Alliance, LLC
# ALL RIGHTS RESERVED
"""
Created on April 30, 2018
@author: mandd
"""
#External Modules---------------------------------------------------------------
import numpy as np
import xml.etree.ElementTree as ET
from utils import utils
from utils import graphStructure as GS
i... | [
"PluginBaseClasses.ExternalModelPluginBase.ExternalModelPluginBase.__init__",
"xml.etree.ElementTree.parse",
"utils.graphStructure.graphObject",
"numpy.asarray",
"copy.deepcopy",
"utils.xmlUtils.findAllRecursive"
] | [((954, 992), 'PluginBaseClasses.ExternalModelPluginBase.ExternalModelPluginBase.__init__', 'ExternalModelPluginBase.__init__', (['self'], {}), '(self)\n', (986, 992), False, 'from PluginBaseClasses.ExternalModelPluginBase import ExternalModelPluginBase\n'), ((4028, 4082), 'xml.etree.ElementTree.parse', 'ET.parse', (["... |
import sys
import numpy as np
import torch.onnx
import onnx
import onnxruntime as ort
from model_ignore.model_sol import Model
def convert(model, input, device, filename):
# setup
model = model.eval()
model = model.to(device)
input = input.to(device)
print("First, a sanity check.")
try:
... | [
"torchvision.transforms.functional.to_tensor",
"onnxruntime.InferenceSession",
"numpy.random.randint",
"onnx.load",
"model_ignore.model_sol.Model"
] | [((1323, 1353), 'onnxruntime.InferenceSession', 'ort.InferenceSession', (['filename'], {}), '(filename)\n', (1343, 1353), True, 'import onnxruntime as ort\n'), ((1151, 1170), 'onnx.load', 'onnx.load', (['filename'], {}), '(filename)\n', (1160, 1170), False, 'import onnx\n'), ((2365, 2372), 'model_ignore.model_sol.Model... |
import numpy as np
import torch
from sklearn.preprocessing import normalize
from torch_geometric.datasets import Planetoid
def get_dataset(dataset):
datasets = Planetoid('./dataset', dataset)
return datasets
def data_preprocessing(dataset):
dataset.adj = torch.sparse_coo_tensor(
dataset.edge_ind... | [
"torch.eye",
"torch.Tensor",
"torch.from_numpy",
"numpy.linalg.matrix_power",
"torch_geometric.datasets.Planetoid",
"sklearn.preprocessing.normalize",
"torch.Size",
"torch.ones"
] | [((167, 198), 'torch_geometric.datasets.Planetoid', 'Planetoid', (['"""./dataset"""', 'dataset'], {}), "('./dataset', dataset)\n", (176, 198), False, 'from torch_geometric.datasets import Planetoid\n'), ((491, 520), 'torch.eye', 'torch.eye', (['dataset.x.shape[0]'], {}), '(dataset.x.shape[0])\n', (500, 520), False, 'im... |
import tempfile
import os
import numpy
import numpy.testing
import h5py
from deeprank.tools.sparse import FLANgrid
def test_preserved():
beta = 1E-2
data = numpy.array([[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.1, 0.0],
[0.0, 0.0, 0.0, 0.0],
... | [
"numpy.abs",
"deeprank.tools.sparse.FLANgrid",
"os.close",
"h5py.File",
"numpy.array",
"tempfile.mkstemp"
] | [((184, 290), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.1, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, \n 0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.1, 0.0], [0.0, 0.0, 0.0, \n 0.0], [0.0, 0.0, 0.0, 0.0]])\n', (195, 290), False, 'import numpy\n'), ((374, 384), 'deeprank.tools.s... |
#!/usr/bin/env python3
import gym
import ptan
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
#from tensorboardX import SummaryWriter
from lib.SummaryWriter import SummaryWriter
from lib import common
from shohdi_lib import ShohdiExp... | [
"torch.nn.ReLU",
"matplotlib.pylab.savefig",
"numpy.array_split",
"numpy.array",
"gym.make",
"numpy.arange",
"torch.arange",
"torch.nn.functional.softmax",
"numpy.mean",
"ptan.actions.EpsilonGreedyActionSelector",
"matplotlib.pylab.clf",
"argparse.ArgumentParser",
"matplotlib.pylab.title",
... | [((473, 487), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (480, 487), True, 'import matplotlib as mpl\n'), ((2209, 2235), 'numpy.array_split', 'np.array_split', (['states', '(64)'], {}), '(states, 64)\n', (2223, 2235), True, 'import numpy as np\n'), ((2462, 2480), 'numpy.mean', 'np.mean', (['mean_val... |
import numpy as np
import random
import pandas
# r matrix
# read the matrix form the appropriate folder
d = pandas.read_csv("C:\\R tables\\0.csv",header = None,index_col=None)
R = np.asarray(d)
# Q Matrix
Q = np.matrix(np.zeros([11,11]))
# gamma (learning parameter)
gamma = 0.8
# Intiial stage. (Usually to be choo... | [
"random.choice",
"pandas.read_csv",
"numpy.where",
"numpy.random.choice",
"numpy.asarray",
"numpy.max",
"numpy.zeros",
"pandas.DataFrame"
] | [((110, 177), 'pandas.read_csv', 'pandas.read_csv', (['"""C:\\\\R tables\\\\0.csv"""'], {'header': 'None', 'index_col': 'None'}), "('C:\\\\R tables\\\\0.csv', header=None, index_col=None)\n", (125, 177), False, 'import pandas\n'), ((182, 195), 'numpy.asarray', 'np.asarray', (['d'], {}), '(d)\n', (192, 195), True, 'impo... |
import parsers
import utils
import tensorflow.keras as K
from collections import namedtuple
import numpy as np
from sklearn.utils import shuffle
from tensorflow.python.keras.utils import Sequence
from tensorflow.python.keras.utils.data_utils import Sequence
def __len__(training_file_path, batch_size):
return parse... | [
"collections.namedtuple",
"parsers.GoldParser",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"utils.candidate_synsets",
"sklearn.utils.shuffle",
"utils.map_word_from_dict",
"numpy.expand_dims",
"parsers.TrainingParser"
] | [((3912, 3960), 'collections.namedtuple', 'namedtuple', (['"""Training"""', '"""id_ lemma pos instance"""'], {}), "('Training', 'id_ lemma pos instance')\n", (3922, 3960), False, 'from collections import namedtuple\n'), ((903, 945), 'parsers.TrainingParser', 'parsers.TrainingParser', (['training_file_path'], {}), '(tra... |
from __future__ import print_function, division
from glob import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import TA_functions as taf
'''
This script crates the plots in DeltaV2-DeltaV3 space, that compare the 3 tests ran.
TEST1 - Average positions P1 and P2, transform to V2-V3 space, an... | [
"numpy.abs",
"matplotlib.pyplot.vlines",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.hlines",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.loadtxt",
"TA_functions.find_std",
"os.path.abspath",
"matplotl... | [((1400, 1443), 'os.path.abspath', 'os.path.abspath', (['"""../plots4presentationIST"""'], {}), "('../plots4presentationIST')\n", (1415, 1443), False, 'import os\n'), ((1707, 1738), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(12, 10)'}), '(1, figsize=(12, 10))\n', (1717, 1738), True, 'import matpl... |
import numdifftools as nd
import numpy as np
import pandas as pd
from estimagic.decorators import numpy_interface
from estimagic.differentiation import differentiation_auxiliary as aux
def gradient(
func,
params,
method="central",
extrapolation=True,
func_kwargs=None,
step_options=None,
):
... | [
"pandas.Series",
"numdifftools.Hessian",
"numdifftools.Gradient",
"estimagic.decorators.numpy_interface",
"numpy.empty_like",
"numdifftools.Jacobian",
"pandas.DataFrame",
"numpy.finfo"
] | [((1674, 1734), 'pandas.Series', 'pd.Series', ([], {'data': 'grad_np', 'index': 'params.index', 'name': '"""gradient"""'}), "(data=grad_np, index=params.index, name='gradient')\n", (1683, 1734), True, 'import pandas as pd\n'), ((1817, 1844), 'numpy.empty_like', 'np.empty_like', (['params_value'], {}), '(params_value)\n... |
import os
import numpy as np
import paramiko
def connect(server="172.16.31.10", username="rutherford"):
""" Connect to server via ssh
"""
ssh = paramiko.SSHClient()
ssh.load_host_keys(
os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))
)
ssh.connect(server, username)
sft... | [
"numpy.radians",
"numpy.sqrt",
"os.path.join",
"numpy.cos",
"numpy.sin",
"paramiko.SSHClient"
] | [((159, 179), 'paramiko.SSHClient', 'paramiko.SSHClient', ([], {}), '()\n', (177, 179), False, 'import paramiko\n'), ((822, 858), 'numpy.radians', 'np.radians', (['[lat1, lon1, lat2, lon2]'], {}), '([lat1, lon1, lat2, lon2])\n', (832, 858), True, 'import numpy as np\n'), ((231, 271), 'os.path.join', 'os.path.join', (['... |
from typing import Tuple, Dict, List
import numpy as np
from graph_nets.graphs import GraphsTuple
from .tf_tools import graphs_tuple_to_data_dicts, data_dicts_to_graphs_tuple
MIN_STD = 1E-6
class Standardizer:
@staticmethod
def compute_mean_std(a: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
retur... | [
"numpy.array",
"numpy.mean",
"numpy.std"
] | [((802, 815), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (810, 815), True, 'import numpy as np\n'), ((847, 860), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (855, 860), True, 'import numpy as np\n'), ((1421, 1434), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (1429, 1434), True, 'import numpy... |
# TAREFAS:
# 1. Abrir todas as imagens em uma pasta (todas as imagens de uma pasta)
# 2. Redimensionar o tamanho de todas as imagem (por exemplo, para 600x600)
# 3. Rotacionar toda as imagens em 90, 180 ou 270 graus;
# 4. Transformar as imagens para tons de cinza (grayscale);
# 5. Transformar todas as imagens em array ... | [
"os.path.exists",
"PIL.Image.open",
"os.makedirs",
"numpy.array",
"glob.glob"
] | [((1240, 1265), 'glob.glob', 'glob.glob', (['"""images/*.jpg"""'], {}), "('images/*.jpg')\n", (1249, 1265), False, 'import glob\n'), ((1277, 1297), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1287, 1297), False, 'from PIL import Image\n'), ((1442, 1457), 'numpy.array', 'np.array', (['image'], {... |
import torch
from config import config as cfg
import backbones
import logging
import losses
import os
import torch
import torch.distributed as dist
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data.distributed
from utils.utils_logging import AverageMeter, init_logging
from utils.utils_callba... | [
"logging.getLogger",
"torch.nn.init.eye_",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"numpy.array",
"torch.normal",
"torch.sum",
"copy.deepcopy",
"torch.unique",
"dataset.MXFaceDataset_Combine",
"os.system",
"torch.zeros_like",
"functools.reduce",
"utils.utils_logging.AverageMeter"... | [((5494, 5558), 'os.path.join', 'os.path.join', (['args.output_dir', '"""clients"""', "('client_%d' % self.cid)"], {}), "(args.output_dir, 'clients', 'client_%d' % self.cid)\n", (5506, 5558), False, 'import os\n'), ((5980, 6015), 'logging.getLogger', 'logging.getLogger', (['"""FL_face.client"""'], {}), "('FL_face.clien... |
import json
import os
import tempfile
import catboost as cb
import numpy as np
import utils
from config import OUTPUT_DIR
def binary_classification_simple_on_dataframe():
learn_set_path = tempfile.mkstemp(prefix='catboost_learn_set_')[1]
cd_path = tempfile.mkstemp(prefix='catboost_cd_')[1]
try:
... | [
"catboost.Pool",
"os.path.join",
"numpy.negative",
"utils.run_dist_train",
"tempfile.mkstemp",
"utils.object_list_to_tsv",
"os.remove"
] | [((197, 243), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'prefix': '"""catboost_learn_set_"""'}), "(prefix='catboost_learn_set_')\n", (213, 243), False, 'import tempfile\n'), ((261, 300), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'prefix': '"""catboost_cd_"""'}), "(prefix='catboost_cd_')\n", (277, 300), False, '... |
import pyfstat
import numpy as np
# Properties of the GW data
sqrtSX = 1e-23
tstart = 1000000000
duration = 100 * 86400
tend = tstart + duration
# Properties of the signal
F0 = 30.0
F1 = -1e-10
F2 = 0
Alpha = np.radians(83.6292)
Delta = np.radians(22.0144)
tref = 0.5 * (tstart + tend)
depth = 10
h0 = sqrtSX / depth
... | [
"numpy.radians",
"pyfstat.Writer"
] | [((211, 230), 'numpy.radians', 'np.radians', (['(83.6292)'], {}), '(83.6292)\n', (221, 230), True, 'import numpy as np\n'), ((239, 258), 'numpy.radians', 'np.radians', (['(22.0144)'], {}), '(22.0144)\n', (249, 258), True, 'import numpy as np\n'), ((375, 539), 'pyfstat.Writer', 'pyfstat.Writer', ([], {'label': 'label', ... |
import keras
from keras import backend as K
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import math
config = {
'inputs': 28*28,
'layer_sizes': [600, 500, 400, 300, 200, 150, 100, 75, 50, 30, 20, 10, 4],
'batch_size': 64,
'bottleneck_cells': 20., # TODO 8.,
'epochs': 1... | [
"numpy.reshape",
"tensorflow.math.exp",
"tensorflow.keras.datasets.mnist.load_data",
"keras.layers.Lambda",
"tensorflow.math.floor",
"numpy.floor",
"keras.layers.Input",
"numpy.zeros",
"keras.models.Model",
"keras.layers.Activation",
"matplotlib.pyplot.scatter",
"keras.layers.Dense",
"tensor... | [((881, 943), 'keras.layers.Input', 'keras.layers.Input', ([], {'shape': "(config['inputs'],)", 'dtype': '"""float32"""'}), "(shape=(config['inputs'],), dtype='float32')\n", (899, 943), False, 'import keras\n'), ((1447, 1518), 'keras.layers.Input', 'keras.layers.Input', ([], {'shape': "(config['layer_sizes'][-1],)", 'd... |
import cv2
import numpy as np
from pathlib import Path
class ObjectDetector:
def __init__(self, pipeline):
self.status = 0
self.pipeline = pipeline
self.device = None
self.q_nn = None
self.detection_nn = None
self.detections = []
self.blobPath = None
... | [
"numpy.array",
"pathlib.Path",
"cv2.putText"
] | [((1696, 1816), 'cv2.putText', 'cv2.putText', (['frame', 'self.labelMap[detection.label]', '(bbox[0] + 10, bbox[1] + 20)', 'cv2.FONT_HERSHEY_TRIPLEX', '(0.5)', '(255)'], {}), '(frame, self.labelMap[detection.label], (bbox[0] + 10, bbox[1] +\n 20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, 255)\n', (1707, 1816), False, 'import ... |
import numpy as np
from .base import Prior, PriorException
from .interpolated import Interped
from .analytical import DeltaFunction, PowerLaw, Uniform, LogUniform, \
SymmetricLogUniform, Cosine, Sine, Gaussian, TruncatedGaussian, HalfGaussian, \
LogNormal, Exponential, StudentT, Beta, Logistic, Cauchy, Gamma, ... | [
"numpy.random.uniform"
] | [((3524, 3553), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'size'], {}), '(0, 1, size)\n', (3541, 3553), True, 'import numpy as np\n')] |
import unittest
import json
import haversine as hv
import math
import numpy as np
import emission.simulation.generate_trips as esgt
import emission.simulation.transition_prob as estp
class TestGenerateTrips(unittest.TestCase):
def setUp(self):
with open("conf/tour.conf.sample") as tcs:
self.sa... | [
"emission.simulation.generate_trips.create_dist_matrix",
"emission.simulation.transition_prob.generate_random_transition_prob",
"haversine.haversine",
"numpy.asarray",
"emission.simulation.generate_trips._init_dataframe",
"json.load",
"numpy.array",
"emission.simulation.generate_trips.FakeUser",
"em... | [((463, 509), 'emission.simulation.transition_prob.generate_random_transition_prob', 'estp.generate_random_transition_prob', (['n_labels'], {}), '(n_labels)\n', (499, 509), True, 'import emission.simulation.transition_prob as estp\n'), ((596, 636), 'emission.simulation.generate_trips._init_dataframe', 'esgt._init_dataf... |
import numpy as np
import torch as th
from torchvision import transforms
from .data_utils import is_tuple_or_list
class BaseDataset:
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and `... | [
"numpy.empty",
"torchvision.transforms.Compose",
"numpy.arange"
] | [((2951, 2973), 'numpy.arange', 'np.arange', (['num_samples'], {}), '(num_samples)\n', (2960, 2973), True, 'import numpy as np\n'), ((850, 906), 'torchvision.transforms.Compose', 'transforms.Compose', (['[transform, self.input_transform[i]]'], {}), '([transform, self.input_transform[i]])\n', (868, 906), False, 'from to... |
"""
Logic for model creation, training launching and actions needed to be
accomplished during training (metrics monitor, model saving etc.)
"""
import os
import time
import json
import numpy as np
import tensorflow as tf
from datetime import datetime
from tensorflow.keras import Sequential
from src.datasets import loa... | [
"src.datasets.load",
"sklearn.model_selection.StratifiedKFold",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.load_model",
"os.path.exists",
"numpy.mean",
"tensorflow.keras.Sequential",
"json.dumps",
"numpy.random.seed",
"numpy.testing.assert_array_equal",
"tensorflow.device",
"ten... | [((498, 518), 'numpy.random.seed', 'np.random.seed', (['(2020)'], {}), '(2020)\n', (512, 518), True, 'import numpy as np\n'), ((523, 547), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(2020)'], {}), '(2020)\n', (541, 547), True, 'import tensorflow as tf\n'), ((577, 591), 'datetime.datetime.now', 'datetime.now... |
import bayesnewton
import numpy as np
from bayesnewton.utils import solve
from jax.config import config
config.update("jax_enable_x64", True)
import pytest
def wiggly_time_series(x_):
noise_var = 0.15 # true observation noise
return (np.cos(0.04*x_+0.33*np.pi) * np.sin(0.2*x_) +
np.math.sqrt(nois... | [
"numpy.random.normal",
"numpy.eye",
"numpy.math.sqrt",
"numpy.sin",
"numpy.sort",
"numpy.log",
"bayesnewton.utils.solve",
"bayesnewton.models.VariationalGP",
"numpy.diag",
"bayesnewton.kernels.Matern52",
"pytest.mark.parametrize",
"numpy.testing.assert_almost_equal",
"numpy.linspace",
"bay... | [((104, 141), 'jax.config.config.update', 'config.update', (['"""jax_enable_x64"""', '(True)'], {}), "('jax_enable_x64', True)\n", (117, 141), False, 'from jax.config import config\n'), ((1209, 1253), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""var_f"""', '[0.5, 1.5]'], {}), "('var_f', [0.5, 1.5])\n", (... |
# written for "run1.bag"
# this script replaces nan values with inf to comply with REP specifications: https://www.ros.org/reps/rep-0117.html
# run "rosbag compress run1_fixed.bag" after processing
import rosbag
import numpy as np
with rosbag.Bag('run1_fixed.bag', 'w') as outbag:
for topic, msg, t in rosbag.Bag(... | [
"numpy.isnan",
"rosbag.Bag"
] | [((239, 272), 'rosbag.Bag', 'rosbag.Bag', (['"""run1_fixed.bag"""', '"""w"""'], {}), "('run1_fixed.bag', 'w')\n", (249, 272), False, 'import rosbag\n'), ((309, 331), 'rosbag.Bag', 'rosbag.Bag', (['"""run1.bag"""'], {}), "('run1.bag')\n", (319, 331), False, 'import rosbag\n'), ((470, 493), 'numpy.isnan', 'np.isnan', (['... |
from typing import List, Tuple, Union
import numpy as np
from z3 import And, Not
from quavl.lib.expressions.complex import ComplexVal
from quavl.lib.expressions.qbit import QbitVal
from quavl.lib.expressions.rqbit import RQbitVal
def qbit_equals_value(qbit: Union[QbitVal, RQbitVal], value: Tuple[Union[int, float], ... | [
"numpy.kron",
"z3.And",
"numpy.matmul",
"quavl.lib.expressions.complex.ComplexVal"
] | [((2741, 2881), 'z3.And', 'And', (['(qbit_a.alpha.r == qbit_b.alpha.r)', '(qbit_a.alpha.i == qbit_b.alpha.i)', '(qbit_a.beta.r == qbit_b.beta.r)', '(qbit_a.beta.i == qbit_b.beta.i)'], {}), '(qbit_a.alpha.r == qbit_b.alpha.r, qbit_a.alpha.i == qbit_b.alpha.i, \n qbit_a.beta.r == qbit_b.beta.r, qbit_a.beta.i == qbit_b... |
from sigpy.polys.polynomials import Polynomial
from sigpy.sage import sage_primal, sage_dual, sage_feasibility, hierarchy_e_k, relative_c_sage, relative_c_sage_star, \
relative_coeff_vector
import cvxpy
import numpy as np
from itertools import combinations_with_replacement
def sage_poly_dual(p, level=0):
sr, ... | [
"cvxpy.Minimize",
"cvxpy.Variable",
"sigpy.polys.polynomials.Polynomial",
"cvxpy.Problem",
"sigpy.sage.relative_coeff_vector",
"sigpy.sage.sage_dual",
"numpy.prod",
"sigpy.sage.relative_c_sage",
"cvxpy.vstack",
"cvxpy.sum",
"sigpy.sage.relative_c_sage_star",
"numpy.zeros",
"cvxpy.Maximize",
... | [((441, 483), 'sigpy.sage.sage_dual', 'sage_dual', (['sr', 'level'], {'additional_cons': 'cons'}), '(sr, level, additional_cons=cons)\n', (450, 483), False, 'from sigpy.sage import sage_primal, sage_dual, sage_feasibility, hierarchy_e_k, relative_c_sage, relative_c_sage_star, relative_coeff_vector\n'), ((649, 693), 'si... |
#!/usr/bin/env python
"""Module for GCMSE --- Gradient Conduction Mean Square Error."""
import numpy as np
from scipy import ndimage
def GCMSE(ref_image, work_image, kappa=0.5, option=1):
"""GCMSE --- Gradient Conduction Mean Square Error.
Computation of the GCMSE. An image quality assessment measurement
... | [
"numpy.clip",
"numpy.ones_like",
"numpy.diff",
"numpy.exp",
"numpy.zeros_like"
] | [((2328, 2359), 'numpy.zeros_like', 'np.zeros_like', (['normed_ref_image'], {}), '(normed_ref_image)\n', (2341, 2359), True, 'import numpy as np\n'), ((2420, 2453), 'numpy.diff', 'np.diff', (['normed_ref_image'], {'axis': '(0)'}), '(normed_ref_image, axis=0)\n', (2427, 2453), True, 'import numpy as np\n'), ((2479, 2512... |
from sklearn.neighbors import LocalOutlierFactor
from pyod.models.iforest import IForest
from pyod.models.hbos import HBOS
from pyod.models.loda import LODA
from pyod.models.copod import COPOD
from tqdm import tqdm
import numpy as np
import pandas as pd
import os
import ast
import eval.evaluation_utils as utils
from sk... | [
"os.path.exists",
"eval.evaluation_utils.min_max_norm",
"os.makedirs",
"pandas.read_csv",
"numpy.where",
"pyod.models.iforest.IForest",
"sklearn.metrics.auc",
"pyod.models.hbos.HBOS",
"sklearn.metrics.precision_recall_curve",
"eval.evaluation_utils.get_subset_candidate",
"numpy.argmax",
"sklea... | [((1239, 1287), 'eval.evaluation_utils.get_subset_candidate', 'utils.get_subset_candidate', (['dim', 'chosen_subspace'], {}), '(dim, chosen_subspace)\n', (1265, 1287), True, 'import eval.evaluation_utils as utils\n'), ((1405, 1433), 'numpy.zeros', 'np.zeros', (['[n_ano, n_subsets]'], {}), '([n_ano, n_subsets])\n', (141... |
import sys
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def normalize_land_water(data, threshold=0.1):
res = [[0 for i in range(len(data))] for j in range(len(data))]
for idv, vline in enumerate(data):
for idh, hcell in enumerate(vline):
if hcell >= threshold:
... | [
"numpy.array",
"numpy.meshgrid",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
] | [((879, 891), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (889, 891), True, 'import matplotlib.pyplot as plt\n'), ((1049, 1066), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (1060, 1066), True, 'import numpy as np\n'), ((1072, 1086), 'numpy.array', 'np.array', (['data'], {}), '(data)\n... |
"""File IO for Flickr 30K images and text captions.
Author: <NAME>
Contact: <EMAIL>
Date: September 2019
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import logging
import numpy as np
def load_flickr30k_splits(splits_dir... | [
"os.path.exists",
"os.listdir",
"numpy.where",
"numpy.asarray",
"os.path.join",
"numpy.isin",
"os.path.split"
] | [((1887, 1933), 'os.path.join', 'os.path.join', (['splits_dir', '"""UNRELATED_CAPTIONS"""'], {}), "(splits_dir, 'UNRELATED_CAPTIONS')\n", (1899, 1933), False, 'import os\n'), ((1945, 1965), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1959, 1965), False, 'import os\n'), ((2303, 2325), 'numpy.asarray... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import os
import json
import scipy
import scipy.stats
jian_file = 'result2'
grid_file = 'result2'
datasets = ['HGBn-ACM', 'HGBn-DBLP', 'HGBn-IMDB', 'HNE-PubMed', 'HGBn-Freebase', 'HGBn-ACM']
xL = [[[0, 1... | [
"os.path.exists",
"os.makedirs",
"pandas.read_csv",
"numpy.arange",
"random.seed",
"numpy.array",
"numpy.random.seed",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.show"
] | [((1318, 1340), 'random.seed', 'random.seed', (['_RNG_SEED'], {}), '(_RNG_SEED)\n', (1329, 1340), False, 'import random\n'), ((1342, 1367), 'numpy.random.seed', 'np.random.seed', (['_RNG_SEED'], {}), '(_RNG_SEED)\n', (1356, 1367), True, 'import numpy as np\n'), ((4242, 4339), 'matplotlib.pyplot.subplots', 'plt.subplots... |
from skbio.alignment import TabularMSA
from skbio import DNA
from io import StringIO
import argparse
import numpy as np
from collections import Counter
p = argparse.ArgumentParser()
p.add_argument("--msa")
p.add_argument("-gap_frac", default=0.5, type=float)
p.add_argument("-only_plot_mutyh", action="store_true")
args... | [
"argparse.ArgumentParser",
"collections.Counter",
"numpy.zeros",
"skbio.alignment.TabularMSA.read",
"io.StringIO",
"numpy.arange"
] | [((157, 182), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (180, 182), False, 'import argparse\n'), ((347, 405), 'skbio.alignment.TabularMSA.read', 'TabularMSA.read', (['args.msa'], {'constructor': 'DNA', 'format': '"""fasta"""'}), "(args.msa, constructor=DNA, format='fasta')\n", (362, 405), ... |
# Copyright (c) 2021-2022, InterDigital Communications, Inc
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
# * Redistributions of source cod... | [
"torch.manual_seed",
"json.loads",
"numpy.allclose",
"importlib.import_module",
"os.getenv",
"os.path.join",
"random.seed",
"os.path.isfile",
"pytest.mark.parametrize",
"os.path.dirname",
"pytest.raises",
"numpy.random.seed",
"json.dump"
] | [((1832, 1901), 'importlib.import_module', 'importlib.import_module', (['"""compressai.utils.video.eval_model.__main__"""'], {}), "('compressai.utils.video.eval_model.__main__')\n", (1855, 1901), False, 'import importlib\n'), ((1917, 1982), 'importlib.import_module', 'importlib.import_module', (['"""compressai.utils.up... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import abel.tools.transform_pairs
n = 100
def plot(profile):
profile = 'profile' + str(profile)
fig, axs = plt.subplots(1, 2, figsize=(6, 2.5))
# fig.suptitle(profile, weight='bold') # figure title (not needed)
eps = 1e-8... | [
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.tight_layout"
] | [((195, 231), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(6, 2.5)'}), '(1, 2, figsize=(6, 2.5))\n', (207, 231), True, 'import matplotlib.pyplot as plt\n'), ((374, 406), 'numpy.linspace', 'np.linspace', (['(0 + eps)', '(1 - eps)', 'n'], {}), '(0 + eps, 1 - eps, n)\n', (385, 406), True, '... |
# Import modules and libraries
import torch
from torch.utils.data import DataLoader
import csv
import pickle
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import glob
from skimage.io import imread
import time
import argparse
from DeepSTORM3D.data_utils import generate_batc... | [
"DeepSTORM3D.assessment_utils.calc_jaccard_rmse",
"DeepSTORM3D.data_utils.ExpDataset",
"DeepSTORM3D.postprocess_utils.Postprocess",
"DeepSTORM3D.physics_utils.EmittersToPhases",
"DeepSTORM3D.data_utils.generate_batch",
"numpy.column_stack",
"torch.from_numpy",
"numpy.not_equal",
"numpy.array",
"De... | [((146, 169), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (160, 169), False, 'import matplotlib\n'), ((934, 950), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (943, 950), True, 'import matplotlib.pyplot as plt\n'), ((1503, 1530), 'matplotlib.pyplot.figure', 'pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.