code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import argparse
import random
import numpy as np
import simpleaudio as sa
import csv
import matplotlib.pyplot as plt
import time
import os
import uuid
import pandas as pd
MAX_FREQUENCY=15000
MIN_FREQUENCY=50
def sine_tone(frequency, duration, volume=0.2, sample_rate=44100):
data = (32767*volume*np.sin(2*np.pi*np.... | [
"matplotlib.pyplot.subplot",
"numpy.divide",
"uuid.uuid4",
"csv.reader",
"random.randint",
"argparse.ArgumentParser",
"numpy.log",
"csv.writer",
"matplotlib.pyplot.show",
"time.time",
"os.path.isfile",
"simpleaudio.play_buffer",
"numpy.array",
"numpy.log10",
"numpy.round"
] | [((414, 453), 'simpleaudio.play_buffer', 'sa.play_buffer', (['data', '(1)', '(2)', 'sample_rate'], {}), '(data, 1, 2, sample_rate)\n', (428, 453), True, 'import simpleaudio as sa\n'), ((798, 810), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (808, 810), False, 'import uuid\n'), ((4283, 4659), 'argparse.ArgumentParser'... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from sklearn.preprocessing import MinMaxScaler, QuantileTransformer
from sklearn.model_selection import StratifiedKFold
from preprocess.unsw import get_feature_names, discovery_feature_volcabulary
from preproces... | [
"pickle.dump",
"preprocess.unsw.discovery_discrete_range",
"pandas.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"numpy.argmin",
"numpy.mean",
"tensorflow.feature_column.categorical_column_with_identity",
"pandas.DataFrame",
"numpy.zeros_like",
"matplotlib.pyplot.close",
"preprocess.unsw.get_... | [((7397, 7432), 'preprocess.unsw.get_feature_names', 'get_feature_names', (['feature_filename'], {}), '(feature_filename)\n', (7414, 7432), False, 'from preprocess.unsw import get_feature_names, discovery_feature_volcabulary\n'), ((7462, 7552), 'preprocess.unsw.discovery_discrete_range', 'discovery_discrete_range', (['... |
'''
Schema of extracellular information.
'''
import re
import os
import sys
from datetime import datetime
import numpy as np
import scipy.io as sio
import datajoint as dj
import tqdm
from . import reference, utilities, acquisition, analysis
from . import extracellular_path
schema = dj.schema(dj.config['custom'].get(... | [
"tqdm.tqdm",
"numpy.logical_and",
"scipy.io.loadmat"
] | [((3795, 3816), 'tqdm.tqdm', 'tqdm.tqdm', (['trial_keys'], {}), '(trial_keys)\n', (3804, 3816), False, 'import tqdm\n'), ((1972, 2040), 'scipy.io.loadmat', 'sio.loadmat', (['sess_data_file'], {'struct_as_record': '(False)', 'squeeze_me': '(True)'}), '(sess_data_file, struct_as_record=False, squeeze_me=True)\n', (1983, ... |
from __future__ import division, print_function, absolute_import
import re
import glob
import os.path as osp
import warnings
import os
import numpy as np
from ..dataset import ImageDataset
class LPW(ImageDataset):
"""LPW.
Reference:
Labeled Pedestrian in the Wild 2018.
URL: `<https://liuyu.us/d... | [
"os.path.expanduser",
"os.path.isdir",
"numpy.asarray",
"os.walk",
"re.findall",
"numpy.arange",
"os.path.relpath",
"warnings.warn",
"os.path.join",
"numpy.unique"
] | [((581, 618), 'os.path.join', 'osp.join', (['self.root', 'self.dataset_dir'], {}), '(self.root, self.dataset_dir)\n', (589, 618), True, 'import os.path as osp\n'), ((728, 751), 'os.path.join', 'osp.join', (['self.data_dir'], {}), '(self.data_dir)\n', (736, 751), True, 'import os.path as osp\n'), ((763, 782), 'os.path.i... |
import tensorflow as tf
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
import numpy as np
import os
from util import get_data, get_unit_int_conversion_helper, get_max_seq_len
from util import add_command_unit_to_output_data
from util import prepare_input_data, prepare_output_data
fr... | [
"keras.models.load_model",
"os.mkdir",
"util.get_data",
"util.prepare_output_data",
"os.path.exists",
"os.path.isfile",
"util.add_command_unit_to_output_data",
"util.get_max_seq_len",
"util.get_unit_int_conversion_helper",
"util.prepare_input_data",
"util.create_model",
"numpy.random.shuffle"
... | [((1293, 1312), 'util.get_data', 'get_data', (['FILE_PATH'], {}), '(FILE_PATH)\n', (1301, 1312), False, 'from util import get_data, get_unit_int_conversion_helper, get_max_seq_len\n'), ((1481, 1519), 'util.get_unit_int_conversion_helper', 'get_unit_int_conversion_helper', (['X_data'], {}), '(X_data)\n', (1511, 1519), F... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # 3D mpl
coords = np.loadtxt("nodes.txt",delimiter=",")
elms = np.loadtxt("elements.txt",delimiter=",")
x = []
y = []
for conn in elms:
... | [
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"numpy.loadtxt"
] | [((122, 134), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (132, 134), True, 'import matplotlib.pyplot as plt\n'), ((198, 236), 'numpy.loadtxt', 'np.loadtxt', (['"""nodes.txt"""'], {'delimiter': '""","""'}), "('nodes.txt', delimiter=',')\n", (208, 236), True, 'import numpy as np\n'), ((243, 284), 'numpy.... |
#!/usr/bin/env python
import math
import numpy
import time
from threading import Thread, Lock
import rospy
import tf
from geometry_msgs.msg import Transform
from sensor_msgs.msg import JointState
from std_msgs.msg import Float32
from urdf_parser_py.urdf import URDF
def S_matrix(w):
S = numpy.zeros((3, 3))
S... | [
"numpy.trace",
"rospy.logerr",
"rospy.Subscriber",
"math.atan2",
"numpy.linalg.norm",
"numpy.linalg.pinv",
"rospy.Duration",
"tf.transformations.concatenate_matrices",
"tf.transformations.quaternion_matrix",
"tf.transformations.identity_matrix",
"numpy.transpose",
"numpy.linalg.eig",
"thread... | [((295, 314), 'numpy.zeros', 'numpy.zeros', (['(3, 3)'], {}), '((3, 3))\n', (306, 314), False, 'import numpy\n'), ((504, 540), 'numpy.linalg.norm', 'numpy.linalg.norm', (['original_np_array'], {}), '(original_np_array)\n', (521, 540), False, 'import numpy\n'), ((1068, 1100), 'numpy.linalg.inv', 'numpy.linalg.inv', (['b... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools for calculating the properties of sources
defined by an Aperture.
"""
from copy import deepcopy
import functools
import inspect
import warnings
from astropy.stats import (SigmaClip, mad_std, biweight_location,
... | [
"numpy.linalg.eigvals",
"numpy.arctan2",
"numpy.sum",
"numpy.empty",
"numpy.isnan",
"numpy.sin",
"numpy.arange",
"numpy.ma.masked_array",
"numpy.mean",
"inspect.getmembers",
"warnings.simplefilter",
"numpy.transpose",
"numpy.isfinite",
"warnings.catch_warnings",
"numpy.linalg.det",
"nu... | [((1252, 1275), 'functools.wraps', 'functools.wraps', (['method'], {}), '(method)\n', (1267, 1275), False, 'import functools\n'), ((9421, 9447), 'numpy.zeros', 'np.zeros', (['self.n_apertures'], {}), '(self.n_apertures)\n', (9429, 9447), True, 'import numpy as np\n'), ((14697, 14711), 'copy.deepcopy', 'deepcopy', (['se... |
"""Bayesian Evidential Learning Framework.
Currently, the common practice is to first transform predictor and target variables
through PCA, and then apply CCA.
It would be interesting to try other techniques and implement it in the framework.
Alternative blueprints could be written in the same style as the BEL class... | [
"numpy.random.seed",
"numpy.abs",
"sklearn.utils.check_array",
"numpy.corrcoef",
"numpy.zeros",
"numpy.ones",
"sklearn.utils.validation.check_is_fitted",
"sklearn.linear_model.LinearRegression",
"scipy.interpolate.interp1d",
"numpy.random.randint",
"numpy.array",
"numpy.random.multivariate_nor... | [((4170, 4203), 'numpy.random.seed', 'np.random.seed', (['self.random_state'], {}), '(self.random_state)\n', (4184, 4203), True, 'import numpy as np\n'), ((6843, 6868), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self.cca'], {}), '(self.cca)\n', (6858, 6868), False, 'from sklearn.utils.validation ... |
"""
Reservoir research.
"""
###############################################################################
# read data
lines = [line.strip().split(',') for line in open("data/input17").readlines()]
# scan each line and update min max bounds
xmin, xmax, ymin, ymax = None, None, None, None
def update(before, new, ope... | [
"matplotlib.pyplot.matshow",
"numpy.zeros"
] | [((1259, 1289), 'numpy.zeros', 'np.zeros', (['(ymax + 1, xmax + 1)'], {}), '((ymax + 1, xmax + 1))\n', (1267, 1289), True, 'import numpy as np\n'), ((1841, 1858), 'matplotlib.pyplot.matshow', 'plt.matshow', (['grid'], {}), '(grid)\n', (1852, 1858), True, 'import matplotlib.pyplot as plt\n')] |
import cv2
import numpy as np
# img_gray=cv2.imread('P:/DIM/ALGO/BachelorDIM-Lectures-Algorithms-2020/assignements/myimage.jpg',0)
# img_bgr=cv2.imread('P:/DIM/ALGO/BachelorDIM-Lectures-Algorithms-2020/assignements/myimage.jpg',1)
img=cv2.imread('P:/DIM/ALGO/BachelorDIM-Lectures-Algorithms-2020/assignements/myimage.jpg... | [
"cv2.bitwise_not",
"cv2.waitKey",
"numpy.dtype",
"numpy.zeros",
"cv2.imread",
"cv2.imshow"
] | [((235, 332), 'cv2.imread', 'cv2.imread', (['"""P:/DIM/ALGO/BachelorDIM-Lectures-Algorithms-2020/assignements/myimage.jpg"""'], {}), "(\n 'P:/DIM/ALGO/BachelorDIM-Lectures-Algorithms-2020/assignements/myimage.jpg'\n )\n", (245, 332), False, 'import cv2\n'), ((590, 625), 'numpy.zeros', 'np.zeros', (['img.shape'], ... |
from os import path
import pickle
import cv2
import numpy as np
import torch
import torchvision
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import torch.nn.parallel
DATA_CACHE = {}
def load_or_reload(data_path, image_size,... | [
"numpy.load",
"torch.utils.data.DataLoader",
"torchvision.transforms.Scale",
"torchvision.transforms.Normalize",
"torch.tensor",
"torchvision.transforms.ToTensor"
] | [((562, 580), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (569, 580), True, 'import numpy as np\n'), ((1041, 1059), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (1048, 1059), True, 'import numpy as np\n'), ((1971, 1986), 'torch.tensor', 'torch.tensor', (['x'], {}), '(x)\n', (1983, 1... |
from argparse import ArgumentParser
from collections import OrderedDict
import numpy as np
import pytorch_lightning as pl
import torch
from cogdl.models.emb.hin2vec import Hin2vec, RWgraph, Hin2vec_layer, tqdm
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_fscore_suppo... | [
"torch.nn.Dropout",
"argparse.ArgumentParser",
"torch.optim.AdamW",
"torch.nn.Embedding",
"torch.cat",
"sklearn.metrics.precision_recall_fscore_support",
"torch.utils.data.DataLoader",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.nn.functional.relu",
"torch.nn.Linear",
"numpy.ceil",
"t... | [((3732, 3781), 'utils.filter_samples', 'filter_samples', ([], {'Y_hat': 'y_hat', 'Y': 'y', 'weights': 'weights'}), '(Y_hat=y_hat, Y=y, weights=weights)\n', (3746, 3781), False, 'from utils import filter_samples\n'), ((4437, 4486), 'utils.filter_samples', 'filter_samples', ([], {'Y_hat': 'y_hat', 'Y': 'y', 'weights': '... |
# Question: https://projecteuler.net/problem=205
import numpy as np
# Distribution of sum of 9 4-sided
DP1 = np.zeros((10, 37), dtype = np.uint64)
# Distribution of sum of 6 6-sided
DP2 = np.zeros((7, 37), dtype = np.uint64)
DP1[0][0] = 1
DP2[0][0] = 1
for i in range(1, 10):
for total in range(1, 37):
f... | [
"numpy.array",
"numpy.zeros"
] | [((111, 146), 'numpy.zeros', 'np.zeros', (['(10, 37)'], {'dtype': 'np.uint64'}), '((10, 37), dtype=np.uint64)\n', (119, 146), True, 'import numpy as np\n'), ((190, 224), 'numpy.zeros', 'np.zeros', (['(7, 37)'], {'dtype': 'np.uint64'}), '((7, 37), dtype=np.uint64)\n', (198, 224), True, 'import numpy as np\n'), ((639, 65... |
# -*- coding: utf-8 -*-
import dask.array as da
import numpy as np
from numpy.testing import assert_array_equal
import pyrap.tables as pt
import pytest
from daskms.dataset import Variable
from daskms.descriptors.ms import MSDescriptorBuilder
@pytest.fixture(params=[
[
{
"row": (2, 3, 2, 2),
... | [
"pyrap.tables.table",
"numpy.testing.assert_array_equal",
"pytest.fixture",
"daskms.dataset.Variable",
"pytest.mark.parametrize",
"daskms.descriptors.ms.MSDescriptorBuilder",
"pyrap.tables.required_ms_desc",
"dask.array.random.random"
] | [((247, 392), 'pytest.fixture', 'pytest.fixture', ([], {'params': "[[{'row': (2, 3, 2, 2), 'chan': (4, 4, 4, 4), 'corr': (2, 2)}, {'row': (4, \n 3), 'chan': (4, 4, 4, 4), 'corr': (2, 2)}]]"}), "(params=[[{'row': (2, 3, 2, 2), 'chan': (4, 4, 4, 4), 'corr':\n (2, 2)}, {'row': (4, 3), 'chan': (4, 4, 4, 4), 'corr': (... |
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import open3d as o3d
os.environ['PYOPENGL_PLATFORM'] = 'osmesa'
# os.environ['PYOPENGL_PLATFORM'] = 'egl'
# os.environ['EGL_DEVICE_ID'] = os.environ['SLURM_STEP_GPUS']
import numpy as np
from scipy.linalg import expm, norm... | [
"numpy.moveaxis",
"trimesh.load",
"os.remove",
"argparse.ArgumentParser",
"pyrender.Mesh.from_trimesh",
"os.path.isfile",
"scipy.spatial.cKDTree",
"utils.parsing_utils.get_dataset_type_from_dataset_name",
"os.path.join",
"os.path.dirname",
"os.path.exists",
"numpy.isfinite",
"utils.image_pro... | [((14800, 14863), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run point cloud sampling"""'}), "(description='Run point cloud sampling')\n", (14823, 14863), False, 'import argparse\n'), ((15215, 15274), 'data_processing.implicit_waterproofing.create_grid_points_from_bounds', 'iw.create... |
# SPDX-License-Identifier: Apache-2.0
import os
import numpy
from onnxruntime import InferenceSession
from _tools import generate_random_images, benchmark
def main(opset=13):
url = "https://tfhub.dev/google/humpback_whale/1?tf-hub-format=compressed"
dest = "tf-humpback-whale"
name = "humpback-whale"
o... | [
"tensorflow_hub.load",
"_tools.benchmark",
"tf2onnx.convert.from_keras",
"_tools.generate_random_images",
"tf2onnx.convert.from_function",
"tensorflow.cast",
"onnxruntime.InferenceSession",
"numpy.array",
"tensorflow.io.read_file",
"tensorflow.TensorSpec",
"os.path.join",
"tensorflow.expand_di... | [((331, 379), 'os.path.join', 'os.path.join', (['dest', "('%s-%d.onnx' % (name, opset))"], {}), "(dest, '%s-%d.onnx' % (name, opset))\n", (343, 379), False, 'import os\n'), ((538, 591), 'tensorflow_hub.load', 'hub.load', (['"""https://tfhub.dev/google/humpback_whale/1"""'], {}), "('https://tfhub.dev/google/humpback_wha... |
import SimpleITK as sitk
import numpy as np
from vesseltrackhfm.vesseltrackhfm import VesselTrackHFM
from dataset_creation.extract_roi import LiverImageCreator
LAMBDA = 1e4
p = 1.0
IMAGE_DIR = '/home/ishaan/Desktop/UMC_Data/Data/29/20150518'
# Read the DCE MR series
liver_image_obj = LiverImageCreator(raw_data_dir=I... | [
"numpy.subtract",
"SimpleITK.GetArrayFromImage",
"numpy.where",
"dataset_creation.extract_roi.LiverImageCreator",
"SimpleITK.WriteImage",
"vesseltrackhfm.vesseltrackhfm.VesselTrackHFM"
] | [((288, 343), 'dataset_creation.extract_roi.LiverImageCreator', 'LiverImageCreator', ([], {'raw_data_dir': 'IMAGE_DIR', 'out_size': '(256)'}), '(raw_data_dir=IMAGE_DIR, out_size=256)\n', (305, 343), False, 'from dataset_creation.extract_roi import LiverImageCreator\n'), ((721, 777), 'numpy.subtract', 'np.subtract', (['... |
import pandas as pd
import no_transfer_linear, no_transfer_lstm
import global_linear_linear, global_linear_lstm, global_lstm_linear, global_lstm_lstm
import torch
import utils
import pickle
import numpy as np
import random
# data params
manualSeed = 999999999
np.random.seed(manualSeed)
random.seed(manualSe... | [
"pandas.DataFrame",
"utils.compute_performance_metrics",
"numpy.random.seed",
"global_lstm_linear.GlobalLSTMLinear",
"torch.manual_seed",
"no_transfer_lstm.NoTransferLSTM",
"time.time",
"global_linear_lstm.GlobalLinearLSTM",
"random.seed",
"utils.get_data",
"utils.calc_tcosts",
"torch.device",... | [((272, 298), 'numpy.random.seed', 'np.random.seed', (['manualSeed'], {}), '(manualSeed)\n', (286, 298), True, 'import numpy as np\n'), ((300, 323), 'random.seed', 'random.seed', (['manualSeed'], {}), '(manualSeed)\n', (311, 323), False, 'import random\n'), ((325, 354), 'torch.manual_seed', 'torch.manual_seed', (['manu... |
import nltk
import numpy as np
import re
import copy
#text_listにリストとして読み込む
with open('book/book1.txt', 'r') as f:
#改行("\n")を""に変換
#text_list = f.read().splitlines()
text = f.read()
#正規表現で"を削除
text = re.sub('"', '', text)
morph = nltk.word_tokenize(text)
pos = nltk.pos_tag(morph)
#[0]=元の文字,[1]=品詞タグ
kaz... | [
"numpy.std",
"numpy.mean",
"nltk.pos_tag",
"re.sub",
"nltk.word_tokenize"
] | [((214, 235), 're.sub', 're.sub', (['"""\\""""', '""""""', 'text'], {}), '(\'"\', \'\', text)\n', (220, 235), False, 'import re\n'), ((245, 269), 'nltk.word_tokenize', 'nltk.word_tokenize', (['text'], {}), '(text)\n', (263, 269), False, 'import nltk\n'), ((276, 295), 'nltk.pos_tag', 'nltk.pos_tag', (['morph'], {}), '(m... |
import sys
sys.path.append(".")
import tensorflow as tf
import os.path as op
import os
import numpy as np
import soundfile as sf
import yaml
from libs.mb_melgan.configs.mb_melgan import MultiBandMelGANGeneratorConfig
from libs.mb_melgan.models.mb_melgan import TFPQMF, TFMelGANGenerator
from utils import mag_to_mel
p... | [
"sys.path.append",
"os.mkdir",
"numpy.load",
"yaml.load",
"os.path.exists",
"libs.mb_melgan.configs.mb_melgan.MultiBandMelGANGeneratorConfig",
"os.path.join",
"utils.mag_to_mel"
] | [((11, 31), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (26, 31), False, 'import sys\n'), ((788, 811), 'os.path.join', 'op.join', (['root', 'filename'], {}), '(root, filename)\n', (795, 811), True, 'import os.path as op\n'), ((828, 845), 'numpy.load', 'np.load', (['file_pth'], {}), '(file_pth)\n... |
import datamodules.dsfunction as F
from torchvision.transforms import Normalize, Lambda, Compose
import numpy as np
import cv2
import random
class Compose(Compose):
def insert(self, index, value):
self.transforms.insert(index, value)
class Add(object):
"""remove datamean
"""
def __init__(self, mean: li... | [
"datamodules.dsfunction.imresize",
"datamodules.dsfunction.to_tensor",
"random.randint",
"datamodules.dsfunction.hflip",
"datamodules.dsfunction.crop",
"numpy.clip",
"numpy.random.rand",
"datamodules.dsfunction.to_grayscale",
"datamodules.dsfunction.reduce_to_scale"
] | [((1600, 1665), 'datamodules.dsfunction.to_grayscale', 'F.to_grayscale', (['img'], {'num_output_channels': 'self.num_output_channels'}), '(img, num_output_channels=self.num_output_channels)\n', (1614, 1665), True, 'import datamodules.dsfunction as F\n'), ((3121, 3167), 'datamodules.dsfunction.imresize', 'F.imresize', (... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
RasterIsochrones
A QGIS plugin
Create isochrones from elevation or other raster map data
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
... | [
"heapq.heappush",
"argparse.ArgumentParser",
"qgis.PyQt.QtCore.QCoreApplication.installTranslator",
"qgis.PyQt.QtCore.QCoreApplication.translate",
"qgis.PyQt.QtCore.QTranslator",
"numpy.full",
"gdal.GetDriverByName",
"numpy.savetxt",
"qgis.core.edit",
"numpy.isfinite",
"qgis.PyQt.QtCore.QSetting... | [((2067, 2084), 'qgis.core.QgsDistanceArea', 'QgsDistanceArea', ([], {}), '()\n', (2082, 2084), False, 'from qgis.core import QgsVectorLayer, QgsRasterLayer, QgsMessageLog, Qgis, QgsWkbTypes as T, QgsDistanceArea, QgsPointXY, QgsField, edit\n'), ((24281, 24308), 'numpy.full', 'numpy.full', (['size', 'numpy.inf'], {}), ... |
from numpy import random
import time
sizeOfArray = 100
def simpleUniqueRandomArray(size):
randomArray = []
while len(randomArray) < size:
randomValue = random.randint(size)
if randomValue in randomArray:
continue
else:
randomArray.append(randomValue)
return randomArray
start = time.clock()
print ("\ns... | [
"numpy.random.randint",
"time.clock"
] | [((296, 308), 'time.clock', 'time.clock', ([], {}), '()\n', (306, 308), False, 'import time\n'), ((723, 735), 'time.clock', 'time.clock', ([], {}), '()\n', (733, 735), False, 'import time\n'), ((983, 995), 'time.clock', 'time.clock', ([], {}), '()\n', (993, 995), False, 'import time\n'), ((940, 971), 'numpy.random.rand... |
import numpy as np
def ucb(y_pred, y_train):
mean = y_pred.mean.numpy()[0],
std = y_pred.stddev.numpy()[0],
n_sample = y_train.numpy().shape[0]
out = mean[0] + (np.sqrt(np.log(n_sample) / n_sample)) * std[0]
return out
| [
"numpy.log"
] | [((187, 203), 'numpy.log', 'np.log', (['n_sample'], {}), '(n_sample)\n', (193, 203), True, 'import numpy as np\n')] |
'''
# This is an 80 character line #
Read in .gsd file, output a 3 x 2 png at each timestep:
-original
-orientation (colorbar)
-magnitude of direcional active force (heatmap)
-tracking individual particles
-particle radii (heatmap)
-nearest neighbo... | [
"sys.path.append",
"numpy.zeros_like",
"numpy.delete",
"math.atan2",
"math.ceil",
"matplotlib.pyplot.close",
"numpy.ravel",
"matplotlib.patches.Rectangle",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rcParams.update",
"matplotlib.use",
"matplotlib.colors.rgb2hex",
"matplo... | [((363, 428), 'sys.path.append', 'sys.path.append', (['"""/Users/kolbt/Desktop/compiled/hoomd-blue/build"""'], {}), "('/Users/kolbt/Desktop/compiled/hoomd-blue/build')\n", (378, 428), False, 'import sys\n'), ((429, 487), 'sys.path.append', 'sys.path.append', (['"""/Users/kolbt/Desktop/compiled/gsd/build"""'], {}), "('/... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------------
# LEIA E PREENCHA O CABEÇALHO
# NÃO ALTERE OS NOMES DAS FUNÇÕES
# NÃO APAGUE OS DOCSTRINGS
#------------------------------------------------------------------
'''
Nome: <NAME>
NUSP: ********
Ao preencher esse cab... | [
"numpymutil.salve_video",
"numpymagem.NumPymagem",
"numpy.sin",
"numpy.linspace",
"numpymutil.mostre_video"
] | [((1910, 1939), 'numpy.linspace', 'np.linspace', (['(0)', 'LARGURA', 'COMP'], {}), '(0, LARGURA, COMP)\n', (1921, 1939), True, 'import numpy as np\n'), ((2124, 2153), 'numpy.linspace', 'np.linspace', (['(0)', 'LARGURA', 'COMP'], {}), '(0, LARGURA, COMP)\n', (2135, 2153), True, 'import numpy as np\n'), ((3203, 3237), 'n... |
import datetime
import re
from collections import defaultdict
from functools import reduce
import numpy as np
from aoc.challenge_base import ChallengeBase
class GuardSleepingLog:
"""
Guard's sleep patterns for a day
"""
def __init__(self, guard_id, sleep_periods):
"""
Constructor
... | [
"datetime.datetime.fromisoformat",
"numpy.argmax",
"numpy.zeros",
"collections.defaultdict",
"numpy.shape",
"functools.reduce",
"re.compile"
] | [((517, 578), 'functools.reduce', 'reduce', (['(lambda x, y: x + (y[1] - y[0]))', 'self.sleep_periods', '(0)'], {}), '(lambda x, y: x + (y[1] - y[0]), self.sleep_periods, 0)\n', (523, 578), False, 'from functools import reduce\n'), ((1151, 1191), 're.compile', 're.compile', (['"""Guard #(\\\\d+) begins shift"""'], {}),... |
# <NAME> 27/04/18
# Using numpy Calculate the maximum value of each column
import numpy
#read data file into array
data = numpy.genfromtxt('data/iris.csv', delimiter=',')
firstcol = (data[:,0]) # select all of the values in the first column of the numpy array
maxfirstcol = numpy.max(data[:,0]) #use numpy max f... | [
"numpy.max",
"numpy.genfromtxt"
] | [((127, 175), 'numpy.genfromtxt', 'numpy.genfromtxt', (['"""data/iris.csv"""'], {'delimiter': '""","""'}), "('data/iris.csv', delimiter=',')\n", (143, 175), False, 'import numpy\n'), ((283, 304), 'numpy.max', 'numpy.max', (['data[:, 0]'], {}), '(data[:, 0])\n', (292, 304), False, 'import numpy\n'), ((371, 392), 'numpy.... |
import pickle
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_cytoscape as cyto
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import Random... | [
"dash_bootstrap_components.Row",
"dash_cytoscape.load_extra_layouts",
"dash_bootstrap_components.Col",
"pickle.load",
"dash_cytoscape.Cytoscape",
"numpy.random.randint",
"numpy.random.choice"
] | [((381, 406), 'dash_cytoscape.load_extra_layouts', 'cyto.load_extra_layouts', ([], {}), '()\n', (404, 406), True, 'import dash_cytoscape as cyto\n'), ((1484, 1507), 'pickle.load', 'pickle.load', (['pickleFile'], {}), '(pickleFile)\n', (1495, 1507), False, 'import pickle\n'), ((1539, 1556), 'dash_bootstrap_components.Co... |
# coding: utf-8
import cv2
import numpy as np
import random
from skimage import exposure
import albumentations as A
from albumentations.augmentations.bbox_utils import denormalize_bbox, normalize_bbox
def resize_keep_ar(image, height=500, scale=None):
if scale is not None:
image = cv2.resize(image,None,fx=... | [
"cv2.bitwise_and",
"numpy.argsort",
"numpy.random.randint",
"numpy.arange",
"random.randint",
"cv2.cvtColor",
"albumentations.augmentations.bbox_utils.normalize_bbox",
"skimage.exposure.match_histograms",
"cv2.bitwise_not",
"cv2.addWeighted",
"cv2.bitwise_or",
"cv2.flip",
"cv2.add",
"numpy... | [((5661, 5698), 'random.randint', 'random.randint', (['*self.n_objects_range'], {}), '(*self.n_objects_range)\n', (5675, 5698), False, 'import random\n'), ((9992, 10032), 'numpy.zeros', 'np.zeros', (['(dst_h, dst_w)'], {'dtype': 'np.uint8'}), '((dst_h, dst_w), dtype=np.uint8)\n', (10000, 10032), True, 'import numpy as ... |
# -*- coding: utf-8 -*-
import json
import copy
import numpy as np
import tensorflow as tf
from tensorflow.contrib import rnn
from tensorflow.contrib import legacy_seq2seq as S
from nnli import util, tfutil
import nnli.regularizers.base as R
class InstanceScorer:
def __init__(self, embedding_layer, token_to_i... | [
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.reduce_sum",
"numpy.sum",
"tensorflow.reshape",
"tensorflow.zeros_like",
"tensorflow.matmul",
"tensorflow.split",
"tensorflow.variable_scope",
"tensorflow.concat",
"tensorflow.placeholder",
"tensorflow.squeeze",
"tensorflow.ones",
"... | [((698, 721), 'copy.copy', 'copy.copy', (['model_kwargs'], {}), '(model_kwargs)\n', (707, 721), False, 'import copy\n'), ((1008, 1078), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None, None]', 'name': '"""i_sentence1"""'}), "(dtype=tf.int32, shape=[None, None], name='i_sentence1')... |
import os
from setuptools import setup, find_packages
# Cython and numpy must be installed first!
from Cython.Build import cythonize
import numpy as np
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# All directories containing Cython code
extensions_dir = []
setup(
na... | [
"os.path.dirname",
"Cython.Build.cythonize",
"numpy.get_include",
"setuptools.find_packages"
] | [((862, 877), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (875, 877), False, 'from setuptools import setup, find_packages\n'), ((1613, 1678), 'Cython.Build.cythonize', 'cythonize', (["[(x + '*.pyx') for x in extensions_dir]"], {'annotate': '(True)'}), "([(x + '*.pyx') for x in extensions_dir], annota... |
#!/usr/bin/env python
__copyright__ = """
Copyright (c) 2020 <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 limitation the rights
to use, copy, modif... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.plot",
"numpy.argmax",
"matplotlib.pyplot.legend",
"datetime.datetime.now",
"detection_3d.tools.file_io.read_json",
"detection_3d.tools.file_io.save_plot_to_image",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",... | [((2660, 2694), 'os.path.join', 'os.path.join', (['checkpoints_dir', '"""*"""'], {}), "(checkpoints_dir, '*')\n", (2672, 2694), False, 'import os\n'), ((5429, 5463), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (5442, 5463), True, 'import matplotlib.pyplo... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from copy import deepcopy
from glob import glob
import sys, os
from copy import deepcopy
from scipy.stats import pearsonr,spearmanr
import warnings
warnings.filterwarnings("ignore")
blue, orange, green, red, purple, brown, _... | [
"numpy.abs",
"numpy.polyfit",
"pandas.read_csv",
"matplotlib.pyplot.gca",
"pandas.DataFrame",
"matplotlib.pyplot.subplots",
"copy.deepcopy",
"matplotlib.pyplot.legend",
"seaborn.barplot",
"scipy.stats.pearsonr",
"matplotlib.pyplot.barh",
"seaborn.boxplot",
"matplotlib.pyplot.ylabel",
"matp... | [((242, 275), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (265, 275), False, 'import warnings\n'), ((330, 349), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (347, 349), True, 'import seaborn as sns\n'), ((441, 526), 'pandas.read_csv', 'pd.read_csv', (... |
import numpy
def sample_uniform_random(dimension_names=None, lower_bounds=None, upper_bounds=None):
"""Takes a uniform random sample from the parameter space.
Args:
dimension_names:
Array of names of the dimensions of the parameter space.
lower_bounds:
Array of lower bounds of the... | [
"numpy.random.rand",
"numpy.asarray"
] | [((676, 706), 'numpy.asarray', 'numpy.asarray', (['dimension_names'], {}), '(dimension_names)\n', (689, 706), False, 'import numpy\n'), ((770, 797), 'numpy.asarray', 'numpy.asarray', (['lower_bounds'], {}), '(lower_bounds)\n', (783, 797), False, 'import numpy\n'), ((861, 888), 'numpy.asarray', 'numpy.asarray', (['upper... |
import ast
import optparse
import keras.models
import numpy as np
from sklearn.preprocessing import LabelEncoder
from keras.preprocessing import sequence
from keras.layers import Average, Input
def toEvaluationFormat(all_doc_ids, all_prediction):
evaluationFormatList = []
for i in range(len(all_doc_ids)):
... | [
"ast.literal_eval",
"optparse.OptionParser",
"keras.preprocessing.sequence.pad_sequences",
"sklearn.preprocessing.LabelEncoder",
"numpy.array",
"keras.layers.Average",
"keras.layers.Input"
] | [((899, 913), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (911, 913), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((2443, 2498), 'keras.layers.Input', 'Input', ([], {'shape': 'models[0].input_shape[1:]', 'dtype': '"""float32"""'}), "(shape=models[0].input_shape[1:], dtype='fl... |
"""Functions that can be called to qa a dataframe, either marking data for
removal, or transforming values in some way (unit conversions, calibration
corrections, etc.). These are generally called from the apply_qa_flags
function in the flag module. Functions must return a dataframe (often the
same as the input), ... | [
"pandas.DataFrame",
"numpy.isnan",
"numpy.logical_and"
] | [((1308, 1363), 'pandas.DataFrame', 'pd.DataFrame', (['(False)'], {'index': 'df.index', 'columns': 'df.columns'}), '(False, index=df.index, columns=df.columns)\n', (1320, 1363), True, 'import pandas as pd\n'), ((1808, 1863), 'pandas.DataFrame', 'pd.DataFrame', (['(False)'], {'index': 'df.index', 'columns': 'df.columns'... |
import sympy as sp
import tensorflow as tf
import tensorflow.python.keras.backend as K
import tensorflow_probability as tfp
import MLGeometry as mlg
from MLGeometry import bihomoNN as bnn
import math
import network_functions as nf
import hermitian_met as hm
import numpy as np
import matplotlib.pyplot as plt
from mpl... | [
"tensorflow.random.set_seed",
"sympy.symbols",
"numpy.random.seed",
"tensorflow.keras.models.load_model",
"MLGeometry.hypersurface.Hypersurface",
"network_functions.plot_train_hist",
"tensorflow.constant",
"hermitian_met.Hermitian_metric_O4",
"matplotlib.pyplot.style.use",
"network_functions.Kahle... | [((354, 372), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (368, 372), True, 'import numpy as np\n'), ((373, 395), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(42)'], {}), '(42)\n', (391, 395), True, 'import tensorflow as tf\n'), ((419, 451), 'matplotlib.pyplot.style.use', 'plt.style.use'... |
import os
import re
import sys
import Models.ImportModel as IM
import pandas as pd
import numpy as np
def clean_df(df):
for index in range(0, len(df)):
#for col in list(df.columns):
for col in ['api_match']:
val = df.loc[index, col]
try:
if np.isnan(val):
... | [
"pandas.ExcelWriter",
"numpy.isnan",
"Models.ImportModel.Spreadsheet",
"re.search",
"os.listdir"
] | [((1350, 1376), 'os.listdir', 'os.listdir', (['downloads_path'], {}), '(downloads_path)\n', (1360, 1376), False, 'import os\n'), ((4514, 4539), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['export_fp'], {}), '(export_fp)\n', (4528, 4539), True, 'import pandas as pd\n'), ((649, 673), 'numpy.isnan', 'np.isnan', (['api_match... |
#!/usr/bin/env python3
# encoding: utf-8
# version: 3.8.2
# standard modules
from random import randint, uniform
from typing import Dict, List, Tuple
# third-party modeuls
import numpy as np
from tqdm import tqdm
# local modules
import diffusion3d_virus_town_large as dv
from .Hosts import Hosts
def load_init_value... | [
"tqdm.tqdm",
"diffusion3d_virus_town_large.sim_time_stepping_diffusion_calc",
"numpy.zeros",
"numpy.ones",
"numpy.array"
] | [((366, 428), 'numpy.zeros', 'np.zeros', (["(gConf['nx'], gConf['ny'], gConf['nz'], gConf['ng'])"], {}), "((gConf['nx'], gConf['ny'], gConf['nz'], gConf['ng']))\n", (374, 428), True, 'import numpy as np\n'), ((2893, 2909), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (2901, 2909), True, 'import numpy as n... |
import visdom
import numpy as np
vis = visdom.Visdom()
vis.text('hello')
vis.image(np.ones((3,10,10)))
| [
"visdom.Visdom",
"numpy.ones"
] | [((39, 54), 'visdom.Visdom', 'visdom.Visdom', ([], {}), '()\n', (52, 54), False, 'import visdom\n'), ((83, 103), 'numpy.ones', 'np.ones', (['(3, 10, 10)'], {}), '((3, 10, 10))\n', (90, 103), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019-05-10 14:32
# @Author : <NAME>
# @Site :
# @File : optical_test.py
# @Software: PyCharm
import math
import numpy as np
import imageio
import matplotlib.pyplot as plt
from mkdir import mkdir
from list2int import list2int
class Timg(ob... | [
"list2int.list2int",
"math.sqrt",
"math.ceil",
"mkdir.mkdir",
"numpy.zeros",
"math.floor",
"matplotlib.pyplot.imsave",
"imageio.mimsave"
] | [((589, 604), 'mkdir.mkdir', 'mkdir', (['filename'], {}), '(filename)\n', (594, 604), False, 'from mkdir import mkdir\n'), ((784, 830), 'numpy.zeros', 'np.zeros', (['(image_h, image_v, 3)'], {'dtype': '"""uint8"""'}), "((image_h, image_v, 3), dtype='uint8')\n", (792, 830), True, 'import numpy as np\n'), ((942, 990), 'm... |
"""Hadamard matrix."""
import numpy as np
def hadamard(n_param: int = 1) -> np.ndarray:
r"""
Produce a 2^{n_param} dimensional Hadamard matrix [WikHad]_.
The standard Hadamard matrix that is often used in quantum information as a
two-qubit quantum gate is defined as
.. math::
H_1 = \frac... | [
"numpy.array",
"numpy.kron",
"numpy.sqrt"
] | [((1217, 1230), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (1225, 1230), True, 'import numpy as np\n'), ((1519, 1540), 'numpy.kron', 'np.kron', (['mat_1', 'mat_2'], {}), '(mat_1, mat_2)\n', (1526, 1540), True, 'import numpy as np\n'), ((1284, 1311), 'numpy.array', 'np.array', (['[[1, 1], [1, -1]]'], {}), '([[... |
import numpy as np
from . import modulus
from .types import Fp
def inverse_el(el: Fp, p: int) -> Fp:
"""Compute the inverse of an element over Fp
Args:
el (Fp): An element in Fp
p (int): A prime number
Returns:
Fp: The inverse of the element over Fp
"""
return pow(int(el... | [
"numpy.array"
] | [((799, 824), 'numpy.array', 'np.array', (['[inverse_of_el]'], {}), '([inverse_of_el])\n', (807, 824), True, 'import numpy as np\n')] |
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
from ..Tools.RotTrans import RotTrans
import os
from ..Pos.GetAberrationAngle import GetAberrationAngle
from .. import Globals
import RecarrayTools as RT
def ReadMagData(Date,Minute=False,res=None,Ab=None,DetectGaps=None):
'''
Reads binary... | [
"numpy.size",
"scipy.interpolate.InterpolatedUnivariateSpline",
"numpy.float32",
"numpy.zeros",
"RecarrayTools.ReadRecarray",
"numpy.recarray",
"os.path.isfile",
"numpy.where",
"numpy.array",
"numpy.arange",
"numpy.int32"
] | [((1552, 1588), 'RecarrayTools.ReadRecarray', 'RT.ReadRecarray', (['(path + fname)', 'dtype'], {}), '(path + fname, dtype)\n', (1567, 1588), True, 'import RecarrayTools as RT\n'), ((1458, 1486), 'os.path.isfile', 'os.path.isfile', (['(path + fname)'], {}), '(path + fname)\n', (1472, 1486), False, 'import os\n'), ((1503... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import speclines
import ebossspec, ebossanalysis
data = ebossanalysis.unify_emissionline_profile_readin()
absorption = ebossanalysis.unify_absorptionline_profile_readin()
vel = data['VEL']
yabs = 1.-(1.-absorption['UNIFIEDABSORPTION'])*1.25
ya... | [
"numpy.sum",
"matplotlib.pyplot.get_cmap",
"ebossanalysis.unify_emissionline_profile_readin",
"numpy.arange",
"ebossanalysis.unify_absorptionline_profile_readin",
"matplotlib.pyplot.subplots"
] | [((132, 181), 'ebossanalysis.unify_emissionline_profile_readin', 'ebossanalysis.unify_emissionline_profile_readin', ([], {}), '()\n', (179, 181), False, 'import ebossspec, ebossanalysis\n'), ((195, 246), 'ebossanalysis.unify_absorptionline_profile_readin', 'ebossanalysis.unify_absorptionline_profile_readin', ([], {}), ... |
import numpy as np
import math as math
class systemProperties():
def __init__(self, wingSolution, wingKinematics, wingInitialGeometry, wingWakeRollup, index, previousWingSystemProperties, rho, Vmagnitude, deltaT):
self.wingSolution = wingSolution
self.wingKinematics = wingKinematics
... | [
"math.sin",
"numpy.zeros",
"math.cos",
"numpy.matmul"
] | [((1614, 1655), 'numpy.zeros', 'np.zeros', (['self.wingInitialGeometry.Mchord'], {}), '(self.wingInitialGeometry.Mchord)\n', (1622, 1655), True, 'import numpy as np\n'), ((2111, 2169), 'numpy.zeros', 'np.zeros', (['(self.wingInitialGeometry.Mchord, self.index, 2)'], {}), '((self.wingInitialGeometry.Mchord, self.index, ... |
from detectron2.data import detection_utils as utils
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
filename = "/home/ayoughi/detectron2/datasets/coco/train2017/000000458139.jpg"
filename1 = "/home/ayoughi/detectron2/datasets/coco/train2017/000000... | [
"matplotlib.pyplot.show",
"numpy.asarray",
"torch.cat",
"numpy.expand_dims",
"PIL.Image.open",
"numpy.clip",
"numpy.max",
"numpy.min",
"detectron2.data.detection_utils.read_image",
"torch.nn.functional.interpolate"
] | [((341, 381), 'detectron2.data.detection_utils.read_image', 'utils.read_image', (['filename'], {'format': '"""BGR"""'}), "(filename, format='BGR')\n", (357, 381), True, 'from detectron2.data import detection_utils as utils\n'), ((426, 456), 'numpy.expand_dims', 'np.expand_dims', (['image1'], {'axis': '(0)'}), '(image1,... |
"""
Some test to make thresholds
"""
from __future__ import division
from __future__ import absolute_import
from past.utils import old_div
import numpy as np
import cv2
import matplotlib.pyplot as plt
from .tesisfunctions import hist_cdf,findminima,threshold,brightness,getOtsuThresh
from glob import glob
root = ""
#... | [
"matplotlib.pyplot.title",
"cv2.resize",
"matplotlib.pyplot.show",
"cv2.threshold",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"cv2.imread",
"matplotlib.pyplot.figure",
"numpy.mean",
"cv2.convexHull",
"cv2.drawContours",
"matplotlib.pyplot.xticks",
"cv2.findContours"
] | [((683, 719), 'matplotlib.pyplot.figure', 'plt.figure', (['"""threshs"""'], {'figsize': 'shape'}), "('threshs', figsize=shape)\n", (693, 719), True, 'import matplotlib.pyplot as plt\n'), ((941, 955), 'cv2.imread', 'cv2.imread', (['fn'], {}), '(fn)\n', (951, 955), False, 'import cv2\n'), ((4020, 4070), 'matplotlib.pyplo... |
import cv2
import numpy as np
from enum import Enum
def construct_bounding_box_array_from_contour(contour):
[x, y, w, h] = cv2.boundingRect(contour)
return np.array([[x, y], [x + w, y], [x, y + h], [x + w, y + h]])
class Side(Enum):
RED = 1
BLUE = 2
NONE = 0
class MissingTimeException(Exceptio... | [
"cv2.boundingRect",
"numpy.array"
] | [((129, 154), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (145, 154), False, 'import cv2\n'), ((166, 224), 'numpy.array', 'np.array', (['[[x, y], [x + w, y], [x, y + h], [x + w, y + h]]'], {}), '([[x, y], [x + w, y], [x, y + h], [x + w, y + h]])\n', (174, 224), True, 'import numpy as np\n'... |
import numpy
import random
import copy as cp
class Hamiltonian:
def __init__(self):
"""
Creates a Hamiltonian object with J = 0, mu = 0, and the periodic boundary conditions set to false.
"""
self.J = 0
self.mu = 0
self.doPeriodicBoundaryConditions = False
def... | [
"random.random",
"copy.deepcopy",
"numpy.exp"
] | [((12962, 12980), 'copy.deepcopy', 'cp.deepcopy', (['spins'], {}), '(spins)\n', (12973, 12980), True, 'import copy as cp\n'), ((15564, 15579), 'random.random', 'random.random', ([], {}), '()\n', (15577, 15579), False, 'import random\n'), ((15606, 15631), 'numpy.exp', 'numpy.exp', (['(-deltaE / temp)'], {}), '(-deltaE /... |
import sys
sys.path.insert(0, '..')
import numpy as np
import pandas as pd
from itertools import combinations
from scipy.stats import binom
import scipy.special
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from IPython.display import display, HTML
#sys.path.append("../")
from FrameBuilder.eige... | [
"copy.deepcopy",
"matplotlib.pyplot.show",
"numpy.count_nonzero",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"sys.path.insert",
"numpy.ones",
"numpy.float",
"numpy.argsort",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xla... | [((11, 35), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (26, 35), False, 'import sys\n'), ((602, 618), 'copy.deepcopy', 'deepcopy', (['list_1'], {}), '(list_1)\n', (610, 618), False, 'from copy import deepcopy\n'), ((911, 927), 'copy.deepcopy', 'deepcopy', (['list_1'], {}), '(list_1)... |
import emcee
import numpy as np
from wobbles.sampling.data import DistanceCalculator
from copy import deepcopy
from wobbles.workflow.forward_model import single_iteration
import pickle
from wobbles.sampling.base import Base
class MCMCSampler(Base):
def __init__(self, output_folder, args_sampler,
... | [
"pickle.dump",
"emcee.EnsembleSampler",
"numpy.isfinite",
"numpy.linspace",
"wobbles.sampling.data.DistanceCalculator"
] | [((585, 625), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', 'self._phase_space_res'], {}), '(0, 2, self._phase_space_res)\n', (596, 625), True, 'import numpy as np\n'), ((657, 698), 'numpy.linspace', 'np.linspace', (['(-2)', '(2)', 'self._phase_space_res'], {}), '(-2, 2, self._phase_space_res)\n', (668, 698), True, ... |
import numpy as np
from backend.soundnet import SoundNet, LEN_WAVEFORM
import torch
from torch.autograd import Variable
import os
nb_sounds = 10
nb_steps = 4 # 20s = 4 * 5s
obj_classes = 1000 # ImageNet
plc_classes = 401 # Enhanced Places365
out_objects = np.empty((1 << nb_sounds, 4, obj_classes))
out_places = np.emp... | [
"numpy.load",
"numpy.save",
"backend.soundnet.SoundNet",
"numpy.empty",
"os.system",
"torch.cuda.is_available"
] | [((258, 300), 'numpy.empty', 'np.empty', (['(1 << nb_sounds, 4, obj_classes)'], {}), '((1 << nb_sounds, 4, obj_classes))\n', (266, 300), True, 'import numpy as np\n'), ((314, 356), 'numpy.empty', 'np.empty', (['(1 << nb_sounds, 4, plc_classes)'], {}), '((1 << nb_sounds, 4, plc_classes))\n', (322, 356), True, 'import nu... |
import math
from pathlib import Path
from typing import Optional
import jax
import jax.numpy as jnp
import numpy as np
import torch
import wandb
import xarray as xr
from einops import rearrange, repeat
from jax_cfd.base.grids import Grid
from jax_cfd.spectral.utils import vorticity_to_velocity
from torch import nn
fr... | [
"jax.numpy.fft.irfftn",
"torch.cat",
"torch.randn",
"fourierflow.modules.Normalizer",
"torch.no_grad",
"torch.isnan",
"fourierflow.utils.downsample_vorticity",
"torch.FloatTensor",
"jax.config.update",
"fourierflow.utils.downsample_vorticity_hat",
"jax_cfd.spectral.utils.vorticity_to_velocity",
... | [((1867, 1892), 'fourierflow.modules.loss.LpLoss', 'LpLoss', ([], {'size_average': '(True)'}), '(size_average=True)\n', (1873, 1892), False, 'from fourierflow.modules.loss import LpLoss\n'), ((2293, 2340), 'fourierflow.modules.Normalizer', 'Normalizer', (['[conv.input_dim]', 'max_accumulations'], {}), '([conv.input_dim... |
import numpy as np
from pymatgen import Structure
__author__ = 'Tina'
# returns if there is a numMatches number of matches between list1 and list2
def check_matches(list1, list2, num_matches):
"""
Check whether two lists of sites contain at least a certain number of matches between the two lists
Args:
... | [
"numpy.average",
"pymatgen.Structure"
] | [((4359, 4409), 'pymatgen.Structure', 'Structure', (['structure.lattice', 'species', 'frac_coords'], {}), '(structure.lattice, species, frac_coords)\n', (4368, 4409), False, 'from pymatgen import Structure\n'), ((3416, 3440), 'numpy.average', 'np.average', (['bond_lengths'], {}), '(bond_lengths)\n', (3426, 3440), True,... |
from torch.utils.data import Dataset
from pathlib import Path
from vocoder import audio
import vocoder.hparams as hp
import numpy as np
import torch
from math import ceil
class VocoderDataset(Dataset):
def __init__(self, metadata_fpath: Path, mel_dir: Path, wav_dir: Path,embed_dir: Path):
print("... | [
"numpy.pad",
"numpy.stack",
"numpy.load",
"math.ceil",
"torch.tensor"
] | [((2029, 2102), 'numpy.pad', 'np.pad', (['x', '((0, len_pad), (0, 0))', '"""constant"""'], {'constant_values': '(0.0, 0.0)'}), "(x, ((0, len_pad), (0, 0)), 'constant', constant_values=(0.0, 0.0))\n", (2035, 2102), True, 'import numpy as np\n'), ((2194, 2269), 'numpy.pad', 'np.pad', (['mel', '((0, len_pad), (0, 0))', '"... |
# reference : https://github.com/Faur/TIMIT
# https://github.com/jameslyons/python_speech_features/issues/53
import os
import sys
import wave
import timeit;
import random; random.seed(int(timeit.default_timer()))
from six.moves import cPickle
import numpy as np
import scipy.io.wavfile as wav
import python_speec... | [
"six.moves.cPickle.dump",
"os.path.join",
"numpy.std",
"timeit.default_timer",
"os.walk",
"numpy.zeros",
"numpy.round",
"scipy.io.wavfile.read",
"numpy.mean",
"python_speech_features.mfcc",
"python_speech_features.delta",
"numpy.concatenate"
] | [((846, 874), 'os.path.join', 'os.path.join', (['paths', '"""TRAIN"""'], {}), "(paths, 'TRAIN')\n", (858, 874), False, 'import os\n'), ((1837, 1855), 'scipy.io.wavfile.read', 'wav.read', (['filename'], {}), '(filename)\n', (1845, 1855), True, 'import scipy.io.wavfile as wav\n'), ((1865, 1978), 'python_speech_features.m... |
import numpy as np
from scipy.linalg import cho_solve
import scipy.optimize
class GaussianProcess(object):
""" Gaussian Process Regressor Class adapted for scRNA seq datasets. """
def __init__(self, kernel=None, alpha=1e-5, normalize=False,
derivative_observations=False, optimize=False, r... | [
"numpy.diag_indices_from",
"numpy.log",
"numpy.logspace",
"scipy.linalg.cho_solve",
"numpy.zeros",
"numpy.einsum",
"numpy.mean",
"numpy.linalg.inv",
"numpy.arange",
"numpy.random.multivariate_normal",
"numpy.random.choice",
"numpy.array",
"numpy.eye",
"numpy.diag",
"numpy.linalg.cholesky... | [((6582, 6609), 'numpy.logspace', 'np.logspace', (['(-3.5)', '(2.5)', '(100)'], {}), '(-3.5, 2.5, 100)\n', (6593, 6609), True, 'import numpy as np\n'), ((2174, 2207), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['self._K_train'], {}), '(self._K_train)\n', (2192, 2207), True, 'import numpy as np\n'), ((2224, 2242), ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 16:33:23 2019
@author: <NAME>
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from kera... | [
"cv2.bitwise_and",
"numpy.argmax",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.ones",
"cv2.imshow",
"numpy.round",
"cv2.dilate",
"cv2.cvtColor",
"keras.layers.Flatten",
"keras.utils.np_utils.to_categorical",
"cv2.destroyAllWindows",
"cv2.resize",
"cv2.waitKey",
... | [((451, 555), 'pandas.read_csv', 'pd.read_csv', (['"""D:\\\\uwo\\\\\\\\computer_vision\\\\projects\\\\sign_lang_detector\\\\database\\\\dataset.csv"""'], {}), "(\n 'D:\\\\uwo\\\\\\\\computer_vision\\\\projects\\\\sign_lang_detector\\\\database\\\\dataset.csv'\n )\n", (462, 555), True, 'import pandas as pd\n'), ((... |
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
def set_mpl_fonts():
MEDIUM = 16
SMALL = 12
LARGE = 20
font_params = {
"axes.labelsize": MEDIUM,
"axes.titlesize": LARGE,
"figure.titlesize": LARGE,
"font.size": MEDIUM,
"legend.fontsize": SMALL,
"legend... | [
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.linspace"
] | [((621, 683), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'mpl.colors.LinearSegmentedColormap.from_list', (['"""mycmap"""', 'colors'], {}), "('mycmap', colors)\n", (665, 683), True, 'import matplotlib as mpl\n'), ((579, 611), 'numpy.linspace', 'np.linspace', (['min_val', 'max_val', 'n'], {}), '(min_val, max_... |
"""
data_from_csv.py
audio dataset reading from CSV output file;
"""
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
class AudioDatasetFromCsv(Dataset):
"""dVoice dataset."""
def __init__(self, csv_in, **kwargs):
"""
init
"""
self.csv_in = csv_in
... | [
"numpy.stack",
"numpy.load",
"pandas.read_csv",
"numpy.isnan"
] | [((2489, 2524), 'numpy.stack', 'np.stack', (['[itm[1] for itm in batch]'], {}), '([itm[1] for itm in batch])\n', (2497, 2524), True, 'import numpy as np\n'), ((2535, 2570), 'numpy.stack', 'np.stack', (['[itm[2] for itm in batch]'], {}), '([itm[2] for itm in batch])\n', (2543, 2570), True, 'import numpy as np\n'), ((258... |
from functools import partial
import psutil
from tqdm.auto import tqdm
def max_cores():
"""Avoid bottlenecks from hyperthreading (stackoverflow.com/a/49327206/5511061)."""
return min(psutil.cpu_count(logical=False) + 1, psutil.cpu_count(logical=True))
def parallel_function( # noqa:E302
function, input... | [
"functools.partial",
"tqdm.auto.tqdm",
"numpy.array_split",
"pathos.multiprocessing.ProcessingPool",
"pandas.concat",
"psutil.cpu_count"
] | [((956, 981), 'pathos.multiprocessing.ProcessingPool', 'ProcessingPool', (['n_workers'], {}), '(n_workers)\n', (970, 981), False, 'from pathos.multiprocessing import ProcessingPool\n'), ((2036, 2082), 'numpy.array_split', 'array_split', (['df_or_series', 'n_chunks'], {'axis': 'axis'}), '(df_or_series, n_chunks, axis=ax... |
#!/usr/bin/env python
import rospy
import tf
from nav_msgs.srv import GetMap
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseStamped
from course_agv_nav.srv import Plan,PlanResponse
from nav_msgs.msg import OccupancyGrid
from std_msgs.msg import Bool
import numpy as np
import matplotlib.pyplot as plt
... | [
"geometry_msgs.msg.PoseStamped",
"rospy.Subscriber",
"nav_msgs.msg.Path",
"course_agv_nav.srv.PlanResponse",
"rospy.ServiceProxy",
"rospy.Publisher",
"rospy.Time",
"rospy.wait_for_service",
"numpy.nonzero",
"numpy.array",
"rospy.init_node",
"a_star.AStarPlanner",
"rospy.spin",
"rospy.Servi... | [((4451, 4484), 'rospy.init_node', 'rospy.init_node', (['"""global_planner"""'], {}), "('global_planner')\n", (4466, 4484), False, 'import rospy\n'), ((4514, 4526), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (4524, 4526), False, 'import rospy\n'), ((759, 781), 'tf.TransformListener', 'tf.TransformListener', ([], {})... |
#/usr/bin/env/python
# encoding: utf-8
'''
Exhaustively search for the ground state electron configuration of the given DB
layout.
'''
__author__ = '<NAME>'
__copyright_ = 'Apache License 2.0'
import signal
import numpy as np
from scipy.spatial import distance
import itertools
import multiprocessing as mp
i... | [
"siqadtools.siqadconn.SiQADConnector",
"argparse.ArgumentParser",
"numpy.argsort",
"numpy.exp",
"numpy.inner",
"multiprocessing.cpu_count",
"numpy.zeros_like",
"time.process_time",
"lxml.etree.parse",
"types.SimpleNamespace",
"argparse.FileType",
"scipy.spatial.distance.cdist",
"json.dump",
... | [((650, 710), 'collections.namedtuple', 'namedtuple', (['"""ChargeConfig"""', "['config', 'energy', 'validity']"], {}), "('ChargeConfig', ['config', 'energy', 'validity'])\n", (660, 710), False, 'from collections import namedtuple\n'), ((1017, 1034), 'types.SimpleNamespace', 'SimpleNamespace', ([], {}), '()\n', (1032, ... |
import numpy as np
def plot_bar_basic(viz, env, args):
opts = dict(title=args[0]) if len(args) > 0 else {}
viz.bar(X=np.random.rand(20), opts=opts, env=env)
def plot_bar_stacked(viz, env, args):
title = args[0] if len(args) > 0 else None
viz.bar(
X=np.abs(np.random.rand(5, 3)),
opts=di... | [
"numpy.random.rand",
"numpy.asarray"
] | [((1124, 1148), 'numpy.asarray', 'np.asarray', (['[19, 26, 55]'], {}), '([19, 26, 55])\n', (1134, 1148), True, 'import numpy as np\n'), ((126, 144), 'numpy.random.rand', 'np.random.rand', (['(20)'], {}), '(20)\n', (140, 144), True, 'import numpy as np\n'), ((636, 657), 'numpy.random.rand', 'np.random.rand', (['(20)', '... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_dataloader.ipynb (unless otherwise specified).
__all__ = ['unpickle_cifar', 'load_label_names', 'normalize', 'one_hot_encoding', 'CifarDownloadedDataset']
# Cell
import torch
import torchvision
import torchvision.transforms as transforms
import os
from pathlib import P... | [
"numpy.empty",
"numpy.append",
"numpy.min",
"pickle.load",
"numpy.max",
"pathlib.Path",
"PIL.Image.fromarray",
"torch.is_tensor"
] | [((781, 790), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (787, 790), True, 'import numpy as np\n'), ((805, 814), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (811, 814), True, 'import numpy as np\n'), ((556, 589), 'pickle.load', 'pickle.load', (['fo'], {'encoding': '"""bytes"""'}), "(fo, encoding='bytes')\n", (567, 5... |
import argparse, os, torch
import random
import numpy as np
from torch.utils.data import Dataset,DataLoader
import warnings
warnings.filterwarnings('ignore')
from mydataloader import CustomImageDataset
import torchvision.transforms as transforms#转换图片
from Model.myModel import Mymodel
from Trainer.mytrain impor... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"warnings.filterwarnings",
"torchvision.transforms.RandomHorizontalFlip",
"torch.manual_seed",
"mydataloader.CustomImageDataset",
"torchvision.transforms.RandomRotation",
"torch.cuda.manual_seed",
"torchvision.transform... | [((129, 162), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (152, 162), False, 'import warnings\n'), ((472, 532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""manual to this script"""'}), "(description='manual to this script')\n", (495, 5... |
import random
import re
from math import isnan
from numbers import Real
from Orange.util import Reprable
import numpy as np
import bottleneck as bn
from Orange.data import Instance, Storage, Variable
from Orange.util import Enum
class Filter(Reprable):
"""
The base class for filters.
.. attribute:: ne... | [
"math.isnan",
"bottleneck.anynan",
"numpy.logical_not",
"numpy.zeros",
"numpy.ones",
"numpy.isnan",
"random.random",
"Orange.util.Enum",
"numpy.random.shuffle",
"re.compile"
] | [((9447, 9567), 'Orange.util.Enum', 'Enum', (['"""FilterContinuous"""', '"""Equal, NotEqual, Less, LessEqual, Greater,GreaterEqual, Between, Outside, IsDefined"""'], {}), "('FilterContinuous',\n 'Equal, NotEqual, Less, LessEqual, Greater,GreaterEqual, Between, Outside, IsDefined'\n )\n", (9451, 9567), False, 'fro... |
import numpy as np
import pandas as pd
import os.path
from datasets.dataset import Dataset
from utils import keyboard
BASE_URL = os.path.join('datasets', 'german')
GERMAN_PATHS = os.path.join(BASE_URL, 'german.csv')
LABELS_TO_KEEP = np.array([ 'Month', 'Credit_amount', 'Investment', 'Age', 'Sex', 'Status', 'Credit_h... | [
"datasets.dataset.Dataset",
"pandas.read_csv",
"pandas.get_dummies",
"numpy.random.RandomState",
"numpy.array",
"numpy.logical_or",
"numpy.sign"
] | [((236, 366), 'numpy.array', 'np.array', (["['Month', 'Credit_amount', 'Investment', 'Age', 'Sex', 'Status',\n 'Credit_history', 'Housing', 'Savings', 'Property']"], {}), "(['Month', 'Credit_amount', 'Investment', 'Age', 'Sex', 'Status',\n 'Credit_history', 'Housing', 'Savings', 'Property'])\n", (244, 366), True,... |
import numpy as np
import os
import PIL
import shutil
import sys
import tensorflow as tf
import wget
datasets = {'validation': 'https://zenodo.org/record/5654571/files/validation.zip?download=1',
'test': 'https://zenodo.org/record/5655436/files/test.zip?download=1',
'reduced_128': '... | [
"sys.stdout.write",
"os.mkdir",
"os.remove",
"shutil.unpack_archive",
"tensorflow.random.normal",
"os.path.isdir",
"numpy.asarray",
"os.rename",
"PIL.Image.open",
"wget.download",
"sys.stdout.flush",
"numpy.array",
"tensorflow.squeeze",
"PIL.Image.fromarray",
"shutil.rmtree",
"os.path.... | [((1105, 1146), 'sys.stdout.write', 'sys.stdout.write', (["('\\r' + progress_message)"], {}), "('\\r' + progress_message)\n", (1121, 1146), False, 'import sys\n'), ((1152, 1170), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1168, 1170), False, 'import sys\n'), ((1384, 1434), 'wget.download', 'wget.downloa... |
from concurrent import futures
import datetime
import pytz
import time
import grpc
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d:%H:%M:%S', level=logging.DEBUG)
import price_pb2
import price_pb2_grpc
import pandas as pd
from pa... | [
"pandas.read_csv",
"pymortar.DataFrame",
"pathlib.Path",
"price_pb2.TariffUtilityReply",
"pandas.DataFrame",
"logging.error",
"pymortar.FetchRequest",
"requests.Session",
"rfc3339.rfc3339",
"datetime.timedelta",
"traceback.format_exc",
"concurrent.futures.ThreadPoolExecutor",
"datetime.datet... | [((98, 263), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s"""', 'datefmt': '"""%Y-%m-%d:%H:%M:%S"""', 'level': 'logging.DEBUG'}), "(format=\n '%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'\n... |
# Lint as: python3
"""The system to log and manage all metrics."""
import logging
from typing import Any, Callable, Dict, Sequence, Text, Union
import numpy as np
from pybullet_envs.minitaur.envs_v2.evaluation import metric as metric_lib
def _merge_dict_throw_on_duplicates(
dict_1: Dict[Text, Any],
dict_2: ... | [
"numpy.std",
"pybullet_envs.minitaur.envs_v2.evaluation.metric.MetricReporter",
"logging.warning",
"numpy.max",
"numpy.mean",
"numpy.min",
"numpy.concatenate"
] | [((964, 976), 'numpy.mean', 'np.mean', (['out'], {}), '(out)\n', (971, 976), True, 'import numpy as np\n'), ((991, 1002), 'numpy.max', 'np.max', (['out'], {}), '(out)\n', (997, 1002), True, 'import numpy as np\n'), ((1017, 1028), 'numpy.min', 'np.min', (['out'], {}), '(out)\n', (1023, 1028), True, 'import numpy as np\n... |
import logging
from pathlib import Path
from warnings import warn
import numpy as np
from pytest_cases import fixture, parametrize_with_cases
# logging configuration
exec_log = logging.getLogger('algo')
logs_dir = Path(__file__).parent / "logs"
@fixture(autouse=True)
def configure_logging(request, caplog):
""... | [
"pytest_cases.fixture",
"matplotlib.pyplot.show",
"pathlib.Path",
"numpy.mean",
"tabulate.tabulate",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots_adjust",
"warnings.warn",
"pytest_cases.parametrize_with_cases",
"logging.getLogger"
] | [((181, 206), 'logging.getLogger', 'logging.getLogger', (['"""algo"""'], {}), "('algo')\n", (198, 206), False, 'import logging\n'), ((252, 273), 'pytest_cases.fixture', 'fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (259, 273), False, 'from pytest_cases import fixture, parametrize_with_cases\n'), ((608, 68... |
__author__ = 'oliver'
import argparse
import nltk
import shutil
import numpy as np
import logging
from util import *
import collections
from collections import OrderedDict
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
SEED = 9
def get_annots_lsmdc(filename,annotations,... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.basicConfig",
"numpy.random.shuffle",
"csv.reader",
"shutil.copy2",
"collections.OrderedDict",
"nltk.word_tokenize",
"logging.getLogger"
] | [((176, 197), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (195, 197), False, 'import logging\n'), ((207, 234), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (224, 234), False, 'import logging\n'), ((1557, 1570), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\... |
import numpy as np
import MDAnalysis as mda
import MDAnalysis.analysis.distances as mad
import MDAnalysis.analysis.align as maa
import nglview as nv
import gridData
import numba
import collections
import functools
from .bool_grid import bool_grid, bool_grid_flat
AA_VDW_RADII = { # in Å
'C': 1.7,
'H': 1.2,
... | [
"MDAnalysis.lib.mdamath.make_whole",
"functools.partial",
"MDAnalysis.analysis.align.alignto",
"numpy.meshgrid",
"MDAnalysis.lib.mdamath.angle",
"numpy.zeros",
"numpy.cross",
"numpy.all",
"numpy.hstack",
"MDAnalysis.Universe",
"numpy.random.randint",
"numpy.array",
"numpy.arange",
"numpy.r... | [((2439, 2477), 'numpy.arange', 'np.arange', (['mines[0]', 'maxes[0]', 'spacing'], {}), '(mines[0], maxes[0], spacing)\n', (2448, 2477), True, 'import numpy as np\n'), ((2487, 2525), 'numpy.arange', 'np.arange', (['mines[1]', 'maxes[1]', 'spacing'], {}), '(mines[1], maxes[1], spacing)\n', (2496, 2525), True, 'import nu... |
import cv2
import socket
import numpy as np
## TCP 사용
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## server ip, port
s.connect(('192.168.0.7', 8485))
## webcam 이미지 capture
cam = cv2.VideoCapture(0)
## 이미지 속성 변경 3 = width, 4 = height
cam.set(3, 320);
cam.set(4, 240);
## 0~100에서 90의 이미지 품질로 설정 (defaul... | [
"cv2.VideoCapture",
"socket.socket",
"numpy.array",
"cv2.imencode"
] | [((60, 109), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (73, 109), False, 'import socket\n'), ((194, 213), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (210, 213), False, 'import cv2\n'), ((612, 653), 'cv2.imencode', 'cv... |
from __future__ import print_function, division
import os
import torch
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from astropy.io import fits
import torchvision.transforms.functional as F... | [
"warnings.filterwarnings",
"astropy.io.fits.getdata",
"torch.normal",
"random.random",
"numpy.where",
"numpy.rot90",
"numpy.loadtxt",
"torch.is_tensor",
"torch.from_numpy"
] | [((370, 403), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (393, 403), False, 'import warnings\n'), ((1330, 1350), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (1345, 1350), False, 'import torch\n'), ((1533, 1555), 'astropy.io.fits.getdata', 'fits.getd... |
import numpy as np
import cv2
class Environment(object):
def __init__(self, grid_size=10, max_time=500, temperature=0.1):
grid_size = grid_size
self.grid_size = grid_size
self.max_time = max_time
self.temperature = temperature
# board on which one plays
self.board ... | [
"numpy.random.binomial",
"numpy.zeros",
"numpy.random.randint",
"numpy.array",
"numpy.argwhere",
"cv2.resize"
] | [((322, 354), 'numpy.zeros', 'np.zeros', (['(grid_size, grid_size)'], {}), '((grid_size, grid_size))\n', (330, 354), True, 'import numpy as np\n'), ((379, 411), 'numpy.zeros', 'np.zeros', (['(grid_size, grid_size)'], {}), '((grid_size, grid_size))\n', (387, 411), True, 'import numpy as np\n'), ((778, 865), 'cv2.resize'... |
import random
import sys
import time
import numpy as np
import pyqtgraph as pg
from Equation import Expression
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
class MonteCarlo(QtGui.QMainWindow):
def __init__(self, int_func, xmin, xmax, ymin, N, parent=None):
super(MonteCarlo, self).__init__(parent)
self.x_min... | [
"pyqtgraph.Qt.QtGui.QPushButton",
"pyqtgraph.Qt.QtGui.QMessageBox",
"pyqtgraph.Qt.QtGui.QApplication",
"pyqtgraph.Qt.QtGui.QApplication.style",
"pyqtgraph.Qt.QtGui.QDoubleValidator",
"pyqtgraph.GraphicsLayoutWidget",
"pyqtgraph.QtGui.QApplication.processEvents",
"pyqtgraph.Qt.QtGui.QGridLayout",
"py... | [((9561, 9589), 'pyqtgraph.Qt.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (9579, 9589), False, 'from pyqtgraph.Qt import QtCore, QtGui, QtWidgets\n'), ((406, 447), 'numpy.linspace', 'np.linspace', (['self.x_min', 'self.x_max', '(1000)'], {}), '(self.x_min, self.x_max, 1000)\n', (417, ... |
#!/usr/bin/env python
# coding: utf-8
# # Heart Disease Prediction
#
# ### Import libraries
#
# Let's first import all the necessary libraries. I'll use `numpy` and `pandas` to start with. For visualization, I will use `pyplot` subpackage of `matplotlib`, use `rcParams` to add styling to the plots and `rainbow` for... | [
"matplotlib.pyplot.title",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.preprocessing.StandardScaler",
"warnings.filterwarnings",
"pandas.read_csv",
"pandas.get_dummies",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.bar",
"sklearn.tree.DecisionTreeClassifier",
"matplotlib.... | [((593, 626), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (616, 626), False, 'import warnings\n'), ((1588, 1614), 'pandas.read_csv', 'pd.read_csv', (['"""dataset.csv"""'], {}), "('dataset.csv')\n", (1599, 1614), True, 'import pandas as pd\n'), ((2542, 2556), 'matplotlib... |
# /mpcfit/mpcfit/gcm.py
"""
# --------------------------------------------------------------
# Oct 2018
# Payne
#
# Fit great circle motion to a list of sky positions.
# The fit is not only to a great circle ...
# ... but also to linear motion along the great circle.
#
# Straight port from work by <NAME>
# - Some of So... | [
"math.hypot",
"math.fmod",
"math.asin",
"math.sqrt",
"math.atan2",
"numpy.cross",
"math.sin",
"numpy.sin",
"collections.namedtuple",
"numpy.inner",
"math.cos",
"numpy.cos"
] | [((1041, 1088), 'collections.namedtuple', 'collections.namedtuple', (['"""Cart"""', "['x', 'y', 'z']"], {}), "('Cart', ['x', 'y', 'z'])\n", (1063, 1088), False, 'import collections\n'), ((1125, 1170), 'collections.namedtuple', 'collections.namedtuple', (['"""Sphr"""', "['ra', 'dec']"], {}), "('Sphr', ['ra', 'dec'])\n",... |
import pandas as pd
import numpy as np
import pickle
from sklearn.metrics.pairwise import rbf_kernel as _rbf_kernel
from neural.data_loading import get_word_embedder
from preprocessing.utils import denoise_text
from typing import List, Optional
array = np.array
# aggregates features from all word vectors in parag... | [
"numpy.triu",
"argparse.ArgumentParser",
"sklearn.metrics.pairwise.rbf_kernel",
"pandas.read_csv",
"numpy.expand_dims",
"preprocessing.utils.denoise_text",
"numpy.linalg.norm",
"neural.data_loading.get_word_embedder",
"numpy.argwhere"
] | [((622, 647), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {'axis': '(1)'}), '(X, axis=1)\n', (636, 647), True, 'import numpy as np\n'), ((760, 786), 'numpy.triu', 'np.triu', (['(X_norm @ X_norm.T)'], {}), '(X_norm @ X_norm.T)\n', (767, 786), True, 'import numpy as np\n'), ((1091, 1105), 'numpy.triu', 'np.triu', (['g... |
from mongo import Picker
from maps import *
import numpy as np
import cv2
p = Picker()
"""
football: width = 970 --- height = 1110 ===> ratio = 1.14 or 0.87
tennis: width = 280 --- height = 530 ===> ratio = 1.89 or 0.53
A2 paper has 1.41 ratio and size in pixels: 4961 x 7016
A2 paper has 1.41 ratio and size in pixe... | [
"cv2.imwrite",
"mongo.Picker",
"numpy.ones",
"cv2.imread",
"cv2.resize"
] | [((80, 88), 'mongo.Picker', 'Picker', ([], {}), '()\n', (86, 88), False, 'from mongo import Picker\n'), ((1563, 1612), 'numpy.ones', 'np.ones', (['(height_a3, width_a3, 3)'], {'dtype': 'np.uint8'}), '((height_a3, width_a3, 3), dtype=np.uint8)\n', (1570, 1612), True, 'import numpy as np\n'), ((1626, 1675), 'numpy.ones',... |
# standard lib modules
import types
import pprint
import numbers
# third-party modules
import pint
import torch
import numpy
import scipy
from scipy.spatial.transform import Rotation
# module configuration
ureg = pint.UnitRegistry()
ureg.define('percent = 0.01 rad')
Q_ = ureg.Quantity
pint.set_application_registry... | [
"pint.UnitRegistry",
"torch.mv",
"numpy.linalg.norm",
"torch.zeros",
"torch.cross",
"pint.set_application_registry",
"types.SimpleNamespace",
"torch.tensor"
] | [((218, 237), 'pint.UnitRegistry', 'pint.UnitRegistry', ([], {}), '()\n', (235, 237), False, 'import pint\n'), ((291, 326), 'pint.set_application_registry', 'pint.set_application_registry', (['ureg'], {}), '(ureg)\n', (320, 326), False, 'import pint\n'), ((811, 852), 'torch.tensor', 'torch.tensor', (['[1, 0, 0]'], {'dt... |
"""Skill Worker class."""
import sys
from collections import defaultdict
import numpy as np
from garage import SkillTrajectoryBatch
from garage.sampler import DefaultWorker
class SkillWorker(DefaultWorker):
def __init__(
self,
*,
seed,
max_path_len... | [
"numpy.full",
"numpy.set_printoptions",
"numpy.asarray",
"collections.defaultdict",
"numpy.random.choice",
"numpy.eye"
] | [((561, 598), 'numpy.full', 'np.full', (['skills_num', '(1.0 / skills_num)'], {}), '(skills_num, 1.0 / skills_num)\n', (568, 598), True, 'import numpy as np\n'), ((2600, 2617), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2611, 2617), False, 'from collections import defaultdict\n'), ((2686, 27... |
import numpy as np
from tqdm import tqdm
from ..utils.DataLoader import load_dataset
from ..utils.DataWriter import DataWriter
# from .src.Logger import *
from .src.Agent import Agent, AgentRank
class AntSystem:
""" The implementation of the most simple Ant Colony Optimization's method, named Ant System(AS).
... | [
"numpy.random.rand",
"numpy.random.randint",
"numpy.zeros",
"numpy.ones"
] | [((3284, 3323), 'numpy.ones', 'np.ones', (['(self.CITY_NUM, self.CITY_NUM)'], {}), '((self.CITY_NUM, self.CITY_NUM))\n', (3291, 3323), True, 'import numpy as np\n'), ((5161, 5184), 'numpy.zeros', 'np.zeros', (['self.CITY_NUM'], {}), '(self.CITY_NUM)\n', (5169, 5184), True, 'import numpy as np\n'), ((5096, 5134), 'numpy... |
# ************************************************************************************************************ # newly added libraries
import copy
import socket
import torch
import numpy as np
import wandb
from client import Client
from config import *
# ***************************************************************... | [
"wandb.log",
"copy.deepcopy",
"numpy.sum",
"torch.norm",
"socket.socket",
"numpy.zeros",
"numpy.ones",
"numpy.isnan",
"numpy.isinf",
"socket.gethostname",
"numpy.array",
"numpy.dot",
"client.Client"
] | [((2678, 2698), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (2696, 2698), False, 'import socket\n'), ((2723, 2738), 'socket.socket', 'socket.socket', ([], {}), '()\n', (2736, 2738), False, 'import socket\n'), ((3613, 3633), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (3631, 3633), Fa... |
"""Segmenter package contains model Segmenter that finds the text segments
that relate to the requirements or responsibilities"""
import numpy as np
from keras.preprocessing import sequence
from keras.models import model_from_json
from keras.models import load_model
class Segmenter:
def __init__(self, vectorize... | [
"keras.models.load_model",
"numpy.argmax",
"keras.preprocessing.sequence.pad_sequences",
"numpy.zeros",
"numpy.array"
] | [((386, 446), 'keras.models.load_model', 'load_model', (['"""encoder_model.json"""', '"""encoder_model_weights.h5"""'], {}), "('encoder_model.json', 'encoder_model_weights.h5')\n", (396, 446), False, 'from keras.models import load_model\n'), ((516, 576), 'keras.models.load_model', 'load_model', (['"""decoder_model.json... |
"""Estimator Module
This module contains the implementation of several covariance matrix
estimators given n observations of size p.
"""
import numpy as np
def sample_estimator(data_mtx, shrink=None):
"""Estimates sample covariance matrix.
Estimates sample covariance matrix given data matrix of size nxp.
... | [
"numpy.divide",
"numpy.sum",
"numpy.maximum",
"numpy.identity",
"numpy.linalg.eig",
"numpy.argsort",
"numpy.linalg.norm",
"numpy.matmul",
"numpy.linalg.det",
"numpy.diag",
"numpy.sqrt"
] | [((2175, 2196), 'numpy.linalg.eig', 'np.linalg.eig', (['sample'], {}), '(sample)\n', (2188, 2196), True, 'import numpy as np\n'), ((2209, 2228), 'numpy.argsort', 'np.argsort', (['eigvals'], {}), '(eigvals)\n', (2219, 2228), True, 'import numpy as np\n'), ((6138, 6159), 'numpy.linalg.eig', 'np.linalg.eig', (['sample'], ... |
# imports
import torch
from torch.autograd import Variable
from torch import nn
from torch.nn import Parameter
import numpy as np
from numpy.linalg import norm
import scipy.io as sio
import pickle
usecuda = True
usecuda = usecuda and torch.cuda.is_available()
dtype = torch.DoubleTensor
if usecuda:
dtype = tor... | [
"numpy.ones",
"torch.exp",
"torch.cuda.is_available",
"torch.pow",
"torch.zeros",
"torch.tensor"
] | [((238, 263), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (261, 263), False, 'import torch\n'), ((954, 973), 'torch.zeros', 'torch.zeros', (['n_bins'], {}), '(n_bins)\n', (965, 973), False, 'import torch\n'), ((1780, 1799), 'torch.tensor', 'torch.tensor', (['[1.0]'], {}), '([1.0])\n', (1792,... |
"""
help calculating frequency of a signal
"""
import numpy as np
import traceback
class Signal:
"""
an advanced signal library
"""
def __init__(self, values, sampling_rate):
"""
:param values: values of the signal
"""
self.values = values
self.sampling_rate = ... | [
"numpy.fft.fft",
"numpy.sin",
"numpy.abs"
] | [((1009, 1053), 'numpy.sin', 'np.sin', (['(2 * np.pi * frequency * time + phase)'], {}), '(2 * np.pi * frequency * time + phase)\n', (1015, 1053), True, 'import numpy as np\n'), ((1234, 1257), 'numpy.fft.fft', 'np.fft.fft', (['self.values'], {}), '(self.values)\n', (1244, 1257), True, 'import numpy as np\n'), ((1625, 1... |
import numpy as np
import math
"""
==================================
Problem 3: Neural Network Basics
==================================
Generates a neural network with the following architecture:
Fully connected neural network.
Input vector takes in two features.
One hidden layer with ... | [
"numpy.dot",
"numpy.matrix",
"numpy.maximum"
] | [((571, 587), 'numpy.maximum', 'np.maximum', (['(0)', 'X'], {}), '(0, X)\n', (581, 587), True, 'import numpy as np\n'), ((1674, 1700), 'numpy.matrix', 'np.matrix', (['"""1 1; 1 1; 1 1"""'], {}), "('1 1; 1 1; 1 1')\n", (1683, 1700), True, 'import numpy as np\n'), ((1741, 1759), 'numpy.matrix', 'np.matrix', (['"""1 1 1""... |
#!/usr/bin/env python
"""
Parameters
Usage
Example
$ python <scriptname>.py --image ../img/<filename>.png
## Explain
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import argparse
import cv2
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-i... | [
"argparse.ArgumentParser",
"cv2.calcHist",
"cv2.imread",
"matplotlib.pyplot.figure",
"numpy.max",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] | [((271, 296), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (294, 296), False, 'import argparse\n'), ((635, 660), 'cv2.imread', 'cv2.imread', (["args['image']"], {}), "(args['image'])\n", (645, 660), False, 'import cv2\n'), ((733, 821), 'cv2.calcHist', 'cv2.calcHist', (['[image]', '[0, 1, 2]',... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
import random
def analyze(img):
# the grey color we want is RGB (210,210,210) to (235,235,235)
# mask1 = cv2.inRange(img, (200, 200, 200), (235,235,235))
# # we also want he white pixels from 250 to 255
# mask2 = cv2.inRange(img,... | [
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.scatter",
"numpy.zeros",
"math.sin",
"math.cos",
"cv2.floodFill"
] | [((1112, 1148), 'numpy.zeros', 'np.zeros', (['(302, 302)'], {'dtype': 'np.uint8'}), '((302, 302), dtype=np.uint8)\n', (1120, 1148), True, 'import numpy as np\n'), ((1984, 2012), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (1994, 2012), True, 'import matplotlib.py... |
from models.vgg import *
from models.utils import *
from models.blocks import *
from models.discriminator import *
from models.generator import *
from models.embedder import *
from tqdm import tqdm, trange
import os
import json
import numpy as np
import time
import datetime
import itertools
import torch
import torch.n... | [
"cv2.VideoWriter_fourcc",
"torch.cat",
"torch.autograd.set_detect_anomaly",
"torch.no_grad",
"os.path.join",
"torch.load",
"torch.autograd.detect_anomaly",
"os.path.exists",
"torchvision.transforms.ToPILImage",
"datetime.timedelta",
"training.logger.Logger",
"torch.mean",
"tqdm.trange",
"t... | [((1642, 1673), 'os.path.join', 'os.path.join', (['directory', '"""logs"""'], {}), "(directory, 'logs')\n", (1654, 1673), False, 'import os\n'), ((1695, 1729), 'os.path.join', 'os.path.join', (['directory', '"""samples"""'], {}), "(directory, 'samples')\n", (1707, 1729), False, 'import os\n'), ((1751, 1785), 'os.path.j... |
from jax import grad, jit, vmap, value_and_grad
import jax.numpy as jnp
import jax.scipy as jsp
import numpy as np
import jax
from jax import random
from functools import partial
from jax.example_libraries import optimizers
from scipy.optimize import nnls
jax.config.update("jax_platform_name", "cpu")
class UBVI:
... | [
"jax.numpy.array",
"numpy.einsum",
"jax.config.update",
"jax.numpy.linalg.cholesky",
"numpy.zeros",
"numpy.array",
"jax.numpy.empty",
"distributions.Gaussian",
"jax.numpy.zeros"
] | [((257, 302), 'jax.config.update', 'jax.config.update', (['"""jax_platform_name"""', '"""cpu"""'], {}), "('jax_platform_name', 'cpu')\n", (274, 302), False, 'import jax\n'), ((618, 635), 'jax.numpy.empty', 'jnp.empty', (['(0, 0)'], {}), '((0, 0))\n', (627, 635), True, 'import jax.numpy as jnp\n'), ((658, 670), 'jax.num... |
"""
All kinds of utilities
"""
import os
import sys
import copy
import numpy as np
import scipy
def get_filenames(path, contains, does_not_contain=('~', '.pyc')):
"""
Create list of files found in given path that contain or do not contain certain strings.
:param path: path in which to look for files
... | [
"numpy.sum",
"numpy.abs",
"numpy.ravel",
"os.popen",
"numpy.ones",
"numpy.isnan",
"numpy.mean",
"numpy.linalg.svd",
"numpy.exp",
"numpy.linalg.norm",
"numpy.diag",
"os.path.join",
"numpy.pad",
"scipy.optimize.minimize",
"numpy.linspace",
"numpy.asarray",
"numpy.hstack",
"sys.exit",... | [((2481, 2493), 'copy.copy', 'copy.copy', (['x'], {}), '(x)\n', (2490, 2493), False, 'import copy\n'), ((3185, 3222), 'numpy.linalg.svd', 'np.linalg.svd', (['X'], {'full_matrices': '(False)'}), '(X, full_matrices=False)\n', (3198, 3222), True, 'import numpy as np\n'), ((4806, 4819), 'numpy.asarray', 'np.asarray', (['v'... |
import requests
import time
import json
import os
import numpy as np
import cv2
from PIL import Image, ImageEnhance, ImageFont, ImageDraw
from pytesseract import image_to_string, image_to_data, image_to_boxes, image_to_osd, Output
import matplotlib
# matplotlib.use("Agg")
import matplotlib.pyplot as plt
def ocr_resul... | [
"matplotlib.pyplot.show",
"cv2.putText",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"PIL.ImageEnhance.Contrast",
"pytesseract.image_to_string",
"PIL.Image.open",
"numpy.shape",
"cv2.imread",
"matplotlib.pyplot.figure",
"pytesseract.image_to_data",
"PIL.ImageFont.truetype",
"cv2.rectangle",
... | [((347, 369), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (357, 369), False, 'from PIL import Image, ImageEnhance, ImageFont, ImageDraw\n'), ((384, 412), 'PIL.ImageEnhance.Contrast', 'ImageEnhance.Contrast', (['image'], {}), '(image)\n', (405, 412), False, 'from PIL import Image, ImageEnhanc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.