code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Authored by <NAME> and <NAME>, 2020
"""
A collection of functions for generating specific envelope shapes.
"""
import numpy as np
from scipy.stats import norm
def sin2(nr_samples):
x = np.linspace(0.0, 1.0, nr_samples)
return np.sin(np.pi * x)**2
def sin_p(p, nr_samples):
x = np.linspace(0.0, 1.0, n... | [
"numpy.flip",
"scipy.stats.norm.pdf",
"numpy.sinc",
"numpy.sin",
"numpy.linspace",
"numpy.concatenate"
] | [((195, 228), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'nr_samples'], {}), '(0.0, 1.0, nr_samples)\n', (206, 228), True, 'import numpy as np\n'), ((297, 330), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'nr_samples'], {}), '(0.0, 1.0, nr_samples)\n', (308, 330), True, 'import numpy as np\n'), ((400... |
import os
import argparse
import glob
import numpy as np
import scipy.interpolate
import scipy.io.wavfile
import python_speech_features
import utils
import timit
# This is based on Table I and Section II of
# <NAME> and <NAME>: Speaker-Independent Phone Recognition Using Hidden Markov Models.
# IEEE Transactions on A... | [
"numpy.load",
"argparse.ArgumentParser",
"numpy.hamming",
"numpy.std",
"numpy.asarray",
"os.path.exists",
"numpy.ones",
"numpy.max",
"numpy.min",
"numpy.arange",
"numpy.mean",
"numpy.linspace",
"glob.glob",
"python_speech_features.mfcc",
"os.path.join",
"utils.tokens_to_ids"
] | [((1930, 1963), 'numpy.asarray', 'np.asarray', (['audio'], {'dtype': 'np.float'}), '(audio, dtype=np.float)\n', (1940, 1963), True, 'import numpy as np\n'), ((2159, 2180), 'numpy.arange', 'np.arange', (['audio.size'], {}), '(audio.size)\n', (2168, 2180), True, 'import numpy as np\n'), ((2406, 2432), 'numpy.min', 'np.mi... |
import glob
import os
import numpy as np
import random
def make_dummy_annotations_file(imgdir, filename):
with open(filename, 'w') as f:
f.write('{}, {}, {}, {}\n'.format('Name', 'Row', 'Column', 'Label'))
for image in glob.glob(os.path.join(imgdir, '*.jpg')):
for i in range(10):
if random.random() < .5:
... | [
"random.random",
"numpy.random.randint",
"os.path.join",
"os.path.basename"
] | [((234, 263), 'os.path.join', 'os.path.join', (['imgdir', '"""*.jpg"""'], {}), "(imgdir, '*.jpg')\n", (246, 263), False, 'import os\n'), ((296, 311), 'random.random', 'random.random', ([], {}), '()\n', (309, 311), False, 'import random\n'), ((357, 380), 'os.path.basename', 'os.path.basename', (['image'], {}), '(image)\... |
#!/usr/bin/env python3
import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D
from keras.activations import relu,softmax
import keras
import os
mnist=np.load("mnist.npz")
x_train,y_train=mnist["x_train"],mnist["y_train"]
x_test,y_test=mnist["x_test"],m... | [
"keras.models.load_model",
"keras.optimizers.Adadelta",
"numpy.load",
"keras.backend.image_data_format",
"keras.layers.Dropout",
"os.path.exists",
"keras.layers.Flatten",
"keras.layers.Dense",
"keras.layers.Conv2D",
"keras.models.Sequential",
"keras.layers.MaxPooling2D",
"keras.utils.to_catego... | [((218, 238), 'numpy.load', 'np.load', (['"""mnist.npz"""'], {}), "('mnist.npz')\n", (225, 238), True, 'import numpy as np\n'), ((763, 802), 'keras.utils.to_categorical', 'keras.utils.to_categorical', (['y_train', '(10)'], {}), '(y_train, 10)\n', (789, 802), False, 'import keras\n'), ((809, 847), 'keras.utils.to_catego... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 08:50:57 2019
@author: Gary
This code is used to create new versions of the xlate files that include
any NEW codes that were not in the previous data set. These files
can then be hand curated to fully process the new dataset.
"""
import pandas as pd
import numpy as n... | [
"pandas.DataFrame",
"pandas.DataFrame.from_dict",
"pandas.read_csv",
"core.Categorize_records.Categorize_CAS",
"pandas.merge",
"core.CAS_tools.is_valid_CAS_code",
"numpy.where"
] | [((3591, 3643), 'pandas.read_csv', 'pd.read_csv', (["(indir + 'cas_labels.csv')"], {'quotechar': '"""\\""""'}), '(indir + \'cas_labels.csv\', quotechar=\'"\')\n', (3602, 3643), True, 'import pandas as pd\n'), ((4171, 4235), 'pandas.merge', 'pd.merge', (['cas_old', 'gb'], {'on': "['clean']", 'how': '"""outer"""', 'valid... |
# -*- coding: utf-8 -*-
"""
@file
@brief Helpers to process data from logs.
"""
import re
from datetime import datetime
import hashlib
import numpy
import pandas
import ujson
def _duration(seq):
dt = None
t1 = None
for t, e in seq:
if e == 'enter':
t1 = t
elif e == 'leave':
... | [
"pandas.DataFrame",
"ujson.loads",
"numpy.isnan",
"pandas.isnull",
"datetime.datetime",
"hashlib.sha256",
"datetime.datetime.strptime",
"re.sub"
] | [((10141, 10178), 'pandas.DataFrame', 'pandas.DataFrame', (['res', 'values.columns'], {}), '(res, values.columns)\n', (10157, 10178), False, 'import pandas\n'), ((1725, 1741), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (1739, 1741), False, 'import hashlib\n'), ((9373, 9389), 'pandas.isnull', 'pandas.isnull',... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import sys
import textwrap
from io import StringIO
from typing import List, Optional, Dict, Any, Tuple, Union
import numpy as np
import gym
from gym.utils import colorize
import textworld
import textworld.text_utils
from t... | [
"textworld.gym.spaces.text_spaces.Word",
"io.StringIO",
"textworld.text_utils.extract_vocab_from_gamefiles",
"textworld.gym.envs.utils.shuffled_cycle",
"textworld.envs.wrappers.Filter",
"textwrap.wrap",
"numpy.random.RandomState",
"gym.utils.colorize",
"textworld.EnvInfos",
"textworld.start"
] | [((3420, 3447), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (3441, 3447), True, 'import numpy as np\n'), ((3666, 3700), 'textworld.gym.envs.utils.shuffled_cycle', 'shuffled_cycle', (['gamefiles'], {'rng': 'rng'}), '(gamefiles, rng=rng)\n', (3680, 3700), False, 'from textworld.gym.en... |
import copy
import pytest
import numpy as np
import pandas as pd
from hyperactive import Hyperactive
search_space = {
"x1": list(np.arange(-100, 100, 1)),
}
def test_callback_0():
def callback_1(access):
access.stuff1 = 1
def callback_2(access):
access.stuff2 = 2
def objective_fun... | [
"hyperactive.Hyperactive",
"numpy.arange"
] | [((434, 447), 'hyperactive.Hyperactive', 'Hyperactive', ([], {}), '()\n', (445, 447), False, 'from hyperactive import Hyperactive\n'), ((854, 867), 'hyperactive.Hyperactive', 'Hyperactive', ([], {}), '()\n', (865, 867), False, 'from hyperactive import Hyperactive\n'), ((1262, 1275), 'hyperactive.Hyperactive', 'Hyperact... |
from policy import PolicyWithMu
import os
from evaluator import Evaluator
import gym
# from utils.em_brake_4test import EmergencyBraking
import numpy as np
from matplotlib.colors import ListedColormap
from dynamics.models import EmBrakeModel, UpperTriangleModel, Air3dModel
def hj_baseline(timet=5.0):
import jax
... | [
"argparse.ArgumentParser",
"matplotlib.pyplot.axes",
"dynamics.models.UpperTriangleModel",
"hj_reachability.systems.DoubleInt",
"matplotlib.pyplot.figure",
"evaluator.Evaluator",
"os.path.join",
"matplotlib.pyplot.tight_layout",
"hj_reachability.step",
"numpy.meshgrid",
"numpy.multiply",
"nump... | [((446, 468), 'hj_reachability.systems.DoubleInt', 'hj.systems.DoubleInt', ([], {}), '()\n', (466, 468), True, 'import hj_reachability as hj\n'), ((764, 875), 'hj_reachability.SolverSettings.with_accuracy', 'hj.SolverSettings.with_accuracy', (['"""very_high"""'], {'hamiltonian_postprocessor': 'hj.solver.backwards_reach... |
import collections
import numpy as np
from sympy import Point3D, Line3D
class Ray(object):
# scaling for distance of lines
_R = 1e10 # cm
_scale = 3e-8
def __init__(self, detector, point_source, color="#29FC5C", probability=None):
self._detector = detector
self._probability = probab... | [
"numpy.deg2rad",
"numpy.sin",
"numpy.array",
"numpy.cos",
"sympy.Point3D"
] | [((490, 547), 'numpy.deg2rad', 'np.deg2rad', (['(90.0 - self._point_source.spherical.lat.value)'], {}), '(90.0 - self._point_source.spherical.lat.value)\n', (500, 547), True, 'import numpy as np\n'), ((562, 612), 'numpy.deg2rad', 'np.deg2rad', (['self._point_source.spherical.lon.value'], {}), '(self._point_source.spher... |
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import os
import numpy as np
def show_res_for_this_run(best_fitnesses_each_iter, average_fitnesses_each_iter, num_of_features_selected_by_best_ant_each_iter, feature_num):
iterations = np.arange(1,len(best_fitnesses_each_iter)+1, dtype="... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"numpy.array",
"numpy.arange",
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.grid"
] | [((389, 429), 'matplotlib.ticker.MultipleLocator', 'plticker.MultipleLocator', ([], {'base': 'intervals'}), '(base=intervals)\n', (413, 429), True, 'import matplotlib.ticker as plticker\n'), ((524, 553), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (536, 553), True,... |
"""Test brillouinzone.py module."""
import numpy as np
import pytest
from morpho.brillouinzone import BrillouinZonePath as BZPath
from morpho.brillouinzone import SymmetryPoint as SPoint
def test_symmetrypoint_constructor_3d():
"""Test 3D SymmetryPoint constructor."""
X = SPoint((0.4, 0.5, 0.3), "X")
asse... | [
"numpy.array",
"morpho.brillouinzone.BrillouinZonePath",
"morpho.brillouinzone.SymmetryPoint"
] | [((283, 311), 'morpho.brillouinzone.SymmetryPoint', 'SPoint', (['(0.4, 0.5, 0.3)', '"""X"""'], {}), "((0.4, 0.5, 0.3), 'X')\n", (289, 311), True, 'from morpho.brillouinzone import SymmetryPoint as SPoint\n'), ((466, 489), 'morpho.brillouinzone.SymmetryPoint', 'SPoint', (['(0.5, 0.3)', '"""X"""'], {}), "((0.5, 0.3), 'X'... |
# Copyright 2013, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
# Computes a coordinate representation using Multidimensional Scaling
# on an alpha-sum of distance matrices.
#
# <NAME>
# 1/6/2015
# Now set up... | [
"numpy.absolute",
"numpy.sum",
"numpy.argmax",
"numpy.ones",
"numpy.argsort",
"numpy.linalg.svd",
"numpy.mean",
"numpy.arange",
"numpy.linalg.norm",
"numpy.tile",
"numpy.full",
"numpy.multiply",
"numpy.finfo",
"numpy.reshape",
"scipy.spatial.distance.cdist",
"numpy.minimum",
"numpy.a... | [((5947, 5989), 'numpy.zeros', 'np.zeros', (['(num_cmd_subset, num_cmd_subset)'], {}), '((num_cmd_subset, num_cmd_subset))\n', (5955, 5989), True, 'import numpy as np\n'), ((9523, 9551), 'numpy.multiply', 'np.multiply', (['landmarks', 'proj'], {}), '(landmarks, proj)\n', (9534, 9551), True, 'import numpy as np\n'), ((9... |
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
import numpy as np
import time
import warnings
import torch
def cycle(iterable):
# see https://github.com/pytorch/pytorch/issues/23900
iterator = iter(iterable)
while True:
try:
yield next(iterator)
... | [
"numpy.copy",
"numpy.empty",
"numpy.isfinite",
"time.time",
"collections.defaultdict",
"torch.cuda.device_count",
"numpy.array",
"torch.device",
"collections.OrderedDict",
"warnings.warn",
"numpy.concatenate"
] | [((658, 671), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (669, 671), False, 'from collections import OrderedDict, defaultdict\n'), ((8087, 8107), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (8099, 8107), False, 'import torch\n'), ((2593, 2648), 'numpy.concatenate', 'np.concatenate',... |
import numpy as np
import tensorflow as tf
class AnchorBoxGenerator:
'''Generates anchor boxes.
This class has operations to generate anchor boxes for feature maps at
strides `[8, 16, 32, 64, 128]`. Where each anchor each box is of the
format `[x, y, width, height]`.
Attributes:
aspect_rat... | [
"tensorflow.meshgrid",
"tensorflow.range",
"tensorflow.math.ceil",
"numpy.ceil",
"tensorflow.reshape",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.tile",
"tensorflow.math.sqrt",
"tensorflow.expand_dims"
] | [((3288, 3320), 'tensorflow.expand_dims', 'tf.expand_dims', (['centers'], {'axis': '(-2)'}), '(centers, axis=-2)\n', (3302, 3320), True, 'import tensorflow as tf\n'), ((3339, 3385), 'tensorflow.tile', 'tf.tile', (['centers', '[1, 1, self._num_anchors, 1]'], {}), '(centers, [1, 1, self._num_anchors, 1])\n', (3346, 3385)... |
# -*- coding: utf-8 -*-
from functools import lru_cache
import numpy as np
from ..base import Property
from ..types.prediction import GaussianMeasurementPrediction
from ..types.update import Update
from ..models.measurement.linear import LinearGaussian
from ..updater.kalman import KalmanUpdater
class InformationKa... | [
"functools.lru_cache",
"numpy.linalg.inv"
] | [((2391, 2402), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (2400, 2402), False, 'from functools import lru_cache\n'), ((3840, 3880), 'numpy.linalg.inv', 'np.linalg.inv', (['predicted_state.precision'], {}), '(predicted_state.precision)\n', (3853, 3880), True, 'import numpy as np\n')] |
#!/usr/bin/env python
from datetime import datetime
import tempfile
import string
import os.path
import random
import numpy as np
import pandas as pd
import pytz
from impactutils.io.container import HDFContainer
TIMEFMT = '%Y-%d-%m %H:%M:%S.%f'
def test_hdf_dictonaries():
f, testfile = tempfile.mkstemp()
... | [
"pandas.DataFrame",
"tempfile.mkstemp",
"numpy.testing.assert_array_equal",
"random.choice",
"datetime.datetime",
"impactutils.io.container.HDFContainer.load",
"numpy.array",
"pytz.timezone",
"pandas.to_datetime",
"numpy.random.rand",
"impactutils.io.container.HDFContainer.create"
] | [((298, 316), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (314, 316), False, 'import tempfile\n'), ((2397, 2415), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (2413, 2415), False, 'import tempfile\n'), ((3571, 3589), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (3587, 3589), Fals... |
"""
predict using trained model,
draw predicted landmarks on 112*112 input image and
"""
import torch
from torch.utils.data import DataLoader
import numpy as np
import cv2
from network_utils import MyNet, MyNet2, MyDataSet
from PIL import Image
def predict(trained_model_path, model, loader, data):
model.load_stat... | [
"torch.utils.data.DataLoader",
"cv2.cvtColor",
"torch.manual_seed",
"torch.load",
"numpy.asarray",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"PIL.Image.open",
"torch.device",
"network_utils.MyDataSet",
"torch.no_grad",
"network_utils.MyNet"
] | [((3785, 3805), 'torch.manual_seed', 'torch.manual_seed', (['(1)'], {}), '(1)\n', (3802, 3805), False, 'import torch\n'), ((3872, 3915), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (3884, 3915), False, 'import torch\n'), ((4065, 4097), 'network_utils.M... |
import cv2 as cv
from pyzbar.pyzbar import decode
import numpy as np
import pyautogui
import socket
from time import time
import pywintypes
import win32gui, win32ui, win32con, win32api
class WindowCapture():
w = 0
h = 0
hwnd = None
cropped_x = 0
cropped_y = 0
offset_x = 0
... | [
"numpy.absolute",
"win32gui.GetWindowRect",
"win32gui.GetDesktopWindow",
"win32gui.IsWindowVisible",
"win32gui.ReleaseDC",
"numpy.frombuffer",
"win32gui.GetWindowText",
"win32gui.FindWindow",
"win32ui.CreateBitmap",
"win32gui.GetWindowDC",
"win32gui.EnumWindows",
"win32ui.CreateDCFromHandle",
... | [((870, 903), 'win32gui.GetWindowRect', 'win32gui.GetWindowRect', (['self.hwnd'], {}), '(self.hwnd)\n', (892, 903), False, 'import win32gui, win32ui, win32con, win32api\n'), ((1553, 1595), 'win32gui.EnumWindows', 'win32gui.EnumWindows', (['winEnumHandler', 'None'], {}), '(winEnumHandler, None)\n', (1573, 1595), False, ... |
# coding: utf-8
"""
Test observing classes
"""
from __future__ import absolute_import, unicode_literals, \
division, print_function
__author__ = "adrn <<EMAIL>>"
# Standard library
import os, sys
import pytest
# Third-party
import numpy as np
import astropy.units as u
import matplotlib.py... | [
"matplotlib.pyplot.title",
"numpy.sum",
"argparse.ArgumentParser",
"matplotlib.pyplot.clf",
"numpy.argmax",
"numpy.floor",
"logging.Formatter",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"scipy.interpolate.interp1d",
"os.path.join",
"matplotlib.pyplot.axvline",
"matplotlib.p... | [((956, 1041), 'os.path.join', 'os.path.join', (['"""/Users/adrian/Documents/GraduateSchool/Observing/"""', '"""2013-10_MDM"""'], {}), "('/Users/adrian/Documents/GraduateSchool/Observing/', '2013-10_MDM'\n )\n", (968, 1041), False, 'import os, sys\n'), ((1738, 1747), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()... |
### This script is to load a model and use it to drive an AV in the simulator
from keras import __version__ as keras_version
from keras.models import load_model
import h5py
import argparse
import base64
import os
import shutil
import cv2
import csv
import numpy as np
import socketio
import eventlet
import eventlet.wsg... | [
"keras.models.load_model",
"h5py.File",
"socketio.Middleware",
"argparse.ArgumentParser",
"numpy.empty",
"socketio.Server",
"flask.Flask",
"sys.path.insert",
"base64.b64decode",
"datetime.datetime.utcnow",
"os.path.join",
"eventlet.listen"
] | [((445, 475), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""library/"""'], {}), "(0, 'library/')\n", (460, 475), False, 'import sys\n'), ((1180, 1215), 'numpy.empty', 'np.empty', (['(nFramesLSTM, 66, 200, 3)'], {}), '((nFramesLSTM, 66, 200, 3))\n', (1188, 1215), True, 'import numpy as np\n'), ((1530, 1547), 'socke... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import random
from scipy.stats import gaussian_kde
import ternary
def plot_confusion_matrix(cm, labels, ax):
fontsize = 7
plt.rc('font', family='Arial', size=fontsize)
plt.tick_params(labelsize=fontsize)
im = ax.... | [
"numpy.meshgrid",
"ternary.figure",
"scipy.stats.gaussian_kde",
"random.choice",
"matplotlib.pyplot.colorbar",
"numpy.arange",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.tick_params",
"numpy.vstack"
] | [((218, 263), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""Arial"""', 'size': 'fontsize'}), "('font', family='Arial', size=fontsize)\n", (224, 263), True, 'import matplotlib.pyplot as plt\n'), ((269, 304), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelsize': 'fontsize'}), '(labels... |
from typing import Type, List
import numpy as np
try:
from rlbench import ObservationConfig, Environment, CameraConfig
except (ModuleNotFoundError, ImportError) as e:
print("You need to install RLBench: 'https://github.com/stepjam/RLBench'")
raise e
from rlbench.action_modes import ActionMode
from rlbench.... | [
"yarr.utils.observation_type.ObservationElement",
"numpy.transpose",
"numpy.expand_dims",
"numpy.array",
"yarr.utils.transition.Transition",
"rlbench.Environment"
] | [((1262, 1379), 'rlbench.Environment', 'Environment', ([], {'action_mode': 'action_mode', 'obs_config': 'observation_config', 'dataset_root': 'dataset_root', 'headless': 'headless'}), '(action_mode=action_mode, obs_config=observation_config,\n dataset_root=dataset_root, headless=headless)\n', (1273, 1379), False, 'f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Colour Models Plotting
======================
Defines the colour models plotting objects:
- :func:`colourspaces_CIE_1931_chromaticity_diagram_plot`
- :func:`single_transfer_function_plot`
- :func:`multi_transfer_function_plot`
"""
from __future__ import divisi... | [
"colour.plotting.CIE_1931_chromaticity_diagram_plot",
"colour.plotting.display",
"numpy.amin",
"colour.plotting.figure_size",
"colour.models.RGB_COLOURSPACES.get",
"random.randint",
"pylab.plot",
"colour.plotting.aspect",
"numpy.amax",
"colour.plotting.bounding_box",
"numpy.linspace",
"colour.... | [((1692, 1711), 'colour.plotting.figure_size', 'figure_size', (['(8, 8)'], {}), '((8, 8))\n', (1703, 1711), False, 'from colour.plotting import CIE_1931_chromaticity_diagram_plot, aspect, bounding_box, display, figure_size, get_cmfs\n'), ((6167, 6186), 'colour.plotting.figure_size', 'figure_size', (['(8, 8)'], {}), '((... |
from torch.utils import data as data
from torchvision.transforms.functional import normalize
from basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb, paired_paths_from_meta_info_file
from basicsr.data.transforms import augment, paired_random_crop
from basicsr.utils import FileClient, imfrom... | [
"numpy.load",
"cv2.cvtColor",
"cv2.imread",
"basicsr.utils.registry.DATASET_REGISTRY.register",
"os.path.join",
"os.listdir",
"torch.from_numpy"
] | [((498, 525), 'basicsr.utils.registry.DATASET_REGISTRY.register', 'DATASET_REGISTRY.register', ([], {}), '()\n', (523, 525), False, 'from basicsr.utils.registry import DATASET_REGISTRY\n'), ((750, 775), 'os.listdir', 'os.listdir', (['self.sino_dir'], {}), '(self.sino_dir)\n', (760, 775), False, 'import os\n'), ((801, 8... |
from collections import Counter
import inspect
import random
import numpy
import pandas
import tensorflow as tf
import models
def reduce_dimensionality(expression_df, Z_df):
'''Convert a dataframe of gene expression data from gene space to the low
dimensional representation specified by Z_df
Arguments
... | [
"tensorflow.keras.metrics.AUC",
"numpy.subtract",
"pandas.read_csv",
"random.shuffle",
"numpy.unique",
"numpy.zeros",
"numpy.ones",
"tensorflow.keras.optimizers.Adam",
"numpy.matmul",
"collections.Counter",
"numpy.concatenate",
"inspect.getmembers"
] | [((1397, 1440), 'numpy.matmul', 'numpy.matmul', (['expression_matrix.T', 'Z_matrix'], {}), '(expression_matrix.T, Z_matrix)\n', (1409, 1440), False, 'import numpy\n'), ((3970, 4005), 'numpy.zeros', 'numpy.zeros', (['healthy_train.shape[0]'], {}), '(healthy_train.shape[0])\n', (3981, 4005), False, 'import numpy\n'), ((4... |
#!/usr/bin/env python
import os
import sys
descr = """mapping procedure for numerical renormalization group."""
DISTNAME = 'nrgmap'
DESCRIPTION = descr
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
LONG_DESCRIPTION = f.read()
MAINTAINER = '<NAME>',
MAINTAINER_EMAIL = '<EMAIL>',
URL = 'http... | [
"os.remove",
"distutils.core.setup",
"os.path.dirname",
"os.path.exists",
"numpy.distutils.misc_util.Configuration",
"os.path.join"
] | [((1558, 1584), 'os.path.exists', 'os.path.exists', (['"""MANIFEST"""'], {}), "('MANIFEST')\n", (1572, 1584), False, 'import os\n'), ((1686, 1731), 'numpy.distutils.misc_util.Configuration', 'Configuration', (['None', 'parent_package', 'top_path'], {}), '(None, parent_package, top_path)\n', (1699, 1731), False, 'from n... |
import torch
import numpy as np
from mmdet.models import BottleNeck
ch_in = 64
ch_out = 64
stride = 1
shortcut = False
variant = 'd'
groups = 1
base_width = 64
lr = 1.0
norm_type = 'bn'
norm_decay = 0.0
freeze_norm = False
dcn_v2 = False
std_senet = False
ch_in = 256
ch_out = 64
stride = 1
shortcut = True
variant =... | [
"numpy.load",
"numpy.sum",
"torch.nn.utils.clip_grad_norm_",
"torch.Tensor",
"numpy.mean",
"mmdet.models.BottleNeck",
"torch.device",
"torch.optim.SGD"
] | [((3392, 3645), 'mmdet.models.BottleNeck', 'BottleNeck', ([], {'ch_in': 'ch_in', 'ch_out': 'ch_out', 'stride': 'stride', 'shortcut': 'shortcut', 'variant': 'variant', 'groups': 'groups', 'base_width': 'base_width', 'lr': 'lr', 'norm_type': 'norm_type', 'norm_decay': 'norm_decay', 'freeze_norm': 'freeze_norm', 'dcn_v2':... |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
def SS_Distributions(xds_ss,xds_kma):
clusters=np.where(np.unique(xds_kma.bmus)>=0)[0]
n_clusters=len(clusters)
n_rows=int(np.sqrt(n_clusters+1))
n_cols=n_rows
fig = plt.figure(figsize=[20,12])
g... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.arange",
"matplotlib.gridspec.GridSpec",
"numpy.unique",
"numpy.sqrt"
] | [((287, 315), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[20, 12]'}), '(figsize=[20, 12])\n', (297, 315), True, 'import matplotlib.pyplot as plt\n'), ((324, 381), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['n_rows', 'n_cols'], {'wspace': '(0.0)', 'hspace': '(0.0)'}), '(n_rows, n_cols, wspac... |
import numpy as np
from .Spectrogram import Spectrogram
def Spectrogram3D(t,vx,vy,vz,wind,slip,**kwargs):
CombineComps = kwargs('CombineComps',False)
#Calculate the three sets of spectra
Nw,F,xt = Spectrogram(t,vx,wind,slip,**kwargs)
Nw,F,yt = Spectrogram(t,vy,wind,slip,**kwargs)
Nw,F,zt = Spectrogram(t,vz,wind... | [
"numpy.abs",
"numpy.arctan2",
"numpy.recarray",
"numpy.conjugate",
"numpy.sqrt"
] | [((568, 607), 'numpy.sqrt', 'np.sqrt', (['(Jxy ** 2 + Jxz ** 2 + Jyz ** 2)'], {}), '(Jxy ** 2 + Jxz ** 2 + Jyz ** 2)\n', (575, 607), True, 'import numpy as np\n'), ((1726, 1754), 'numpy.recarray', 'np.recarray', (['Nw'], {'dtype': 'dtype'}), '(Nw, dtype=dtype)\n', (1737, 1754), True, 'import numpy as np\n'), ((2148, 21... |
"""
The experiment with user cluster - booking cluster IBCF.
"""
import argparse
import logging
import pickle
import sys
from collections import Counter
import numpy as np
import pandas as pd
from sklearn.preprocessing import binarize
from ibcf.matrix_functions import get_sparse_matrix_info
from ibcf.recs import get... | [
"pickle.dump",
"ibcf.matrix_functions.get_sparse_matrix_info",
"sklearn.preprocessing.binarize",
"argparse.ArgumentParser",
"misc.common.get_bg_data",
"pandas.read_csv",
"numpy.argsort",
"logging.info",
"ibcf.similarity.get_similarity_matrix",
"misc.common.get_ug_data",
"collections.Counter",
... | [((551, 614), 'logging.info', 'logging.info', (['"""# of testing instances: %s"""', 'testing_df.shape[0]'], {}), "('# of testing instances: %s', testing_df.shape[0])\n", (563, 614), False, 'import logging\n'), ((1115, 1124), 'collections.Counter', 'Counter', ([], {}), '()\n', (1122, 1124), False, 'from collections impo... |
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
from tqdm import tqdm
from utils import Jaccard, nlp
from consts import JACCARD_SIM
class ContentBasedFiltering:
def __init__(self, meta_df):
"""
Ar... | [
"pandas.DataFrame",
"numpy.load",
"sklearn.metrics.pairwise.linear_kernel",
"sklearn.feature_extraction.text.TfidfVectorizer",
"utils.Jaccard",
"numpy.argsort"
] | [((859, 933), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'analyzer': '"""word"""', 'stop_words': '"""english"""', 'ngram_range': '(1, 3)'}), "(analyzer='word', stop_words='english', ngram_range=(1, 3))\n", (874, 933), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n... |
import math
import numpy as np
from numba import cuda,types, from_dtype
from raytracer.cudaOptions import cudaOptions
# Not privatizing the quaternion functions as cuda fails inside a class.
# http://graphics.stanford.edu/courses/cs348a-17-winter/Papers/pdf -- eq#3
# also https://github.com/Unity-Technologies/Unity.M... | [
"math.sqrt",
"math.atan2",
"math.ceil",
"numpy.zeros",
"math.sin",
"math.acos",
"math.cos",
"numba.cuda.jit",
"numba.cuda.grid"
] | [((500, 521), 'numba.cuda.jit', 'cuda.jit', ([], {'device': '(True)'}), '(device=True)\n', (508, 521), False, 'from numba import cuda, types, from_dtype\n'), ((593, 614), 'numba.cuda.jit', 'cuda.jit', ([], {'device': '(True)'}), '(device=True)\n', (601, 614), False, 'from numba import cuda, types, from_dtype\n'), ((703... |
### gcode_reader in code folder
### instructions in SETUP.txt
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##################################
# University of Wisconsin-Madison
# Author: <NAME>
##################################
"""
Gcode reader for both FDM (regular and Stratasys) and LPBF.
It supports the followi... | [
"numpy.arctan2",
"argparse.ArgumentParser",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.sin",
"pandas.DataFrame",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"numpy.ceil",
"math.sqrt",
"statistics.median"... | [((1879, 1943), 'collections.namedtuple', 'collections.namedtuple', (['"""Element"""', "['x0', 'y0', 'x1', 'y1', 'z']"], {}), "('Element', ['x0', 'y0', 'x1', 'y1', 'z'])\n", (1901, 1943), False, 'import collections\n'), ((2152, 2182), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\... |
import json
import argparse
import json
import numpy as np
import torch
import torch.optim as optim
from sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score
from torch.nn import functional as F
from torch.utils.data import DataLoader
from tqdm import tqdm
from dnn import DNNNet
USE_CUDA = ... | [
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"torch.LongTensor",
"torch.argmax",
"dnn.DNNNet",
"sklearn.metrics.accuracy_score",
"numpy.asarray",
"sklearn.metrics.recall_score",
"torch.nn.functional.binary_cross_entropy_with_logits",
"sklearn.metrics.f1_score",
"torch.cuda.is_availa... | [((1366, 1428), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n', (1376, 1428), False, 'from torch.utils.data import DataLoader\n'), ((1447, 1494), 'torch.utils.data.DataLoader', 'DataLoader', ([... |
import os
import numpy as np
def initialize_pyrngs():
from gslrandom import PyRNG, get_omp_num_threads
if "OMP_NUM_THREADS" in os.environ:
num_threads = os.environ["OMP_NUM_THREADS"]
else:
num_threads = get_omp_num_threads()
assert num_threads > 0
# Choose random seeds
seeds = ... | [
"fnmatch.filter",
"gslrandom.PyRNG",
"numpy.log",
"numpy.zeros",
"gslrandom.get_omp_num_threads",
"numpy.hstack",
"numpy.argsort",
"numpy.random.gamma",
"numpy.histogram",
"numpy.random.randint",
"numpy.arange",
"numpy.exp",
"pybasicbayes.util.general.ibincount",
"numpy.random.rand",
"nu... | [((320, 364), 'numpy.random.randint', 'np.random.randint', (['(2 ** 16)'], {'size': 'num_threads'}), '(2 ** 16, size=num_threads)\n', (337, 364), True, 'import numpy as np\n'), ((693, 709), 'numpy.all', 'np.all', (['(S_ct < T)'], {}), '(S_ct < T)\n', (699, 709), True, 'import numpy as np\n'), ((830, 846), 'numpy.argsor... |
"""The WaveBlocks Project
This file contains a tiny wrapper to wrap
numpy ndarrays into Grid instances.
@author: <NAME>
@copyright: Copyright (C) 2012, 2013, 2014 <NAME>
@license: Modified BSD License
"""
from numpy import atleast_1d, abs, product
from WaveBlocksND.AbstractGrid import AbstractGrid
__all__ = ["Grid... | [
"numpy.product",
"numpy.abs",
"numpy.atleast_1d"
] | [((1095, 1112), 'numpy.abs', 'abs', (['(l[-1] - l[0])'], {}), '(l[-1] - l[0])\n', (1098, 1112), False, 'from numpy import atleast_1d, abs, product\n'), ((1674, 1703), 'numpy.product', 'product', (['self._data.shape[1:]'], {}), '(self._data.shape[1:])\n', (1681, 1703), False, 'from numpy import atleast_1d, abs, product\... |
#!/usr/bin/hfo_env python3
# encoding utf-8
from datetime import date, datetime as dt
import os
import numpy as np
from matias_hfo import settings
from matias_hfo.agents.utils import ServerDownError, NoActionPlayedError
def mkdir(name: str, idx: int = None, **kwargs):
today = date.today()
name_dir =... | [
"os.mkdir",
"numpy.save",
"datetime.date.today",
"numpy.array",
"os.path.join"
] | [((293, 305), 'datetime.date.today', 'date.today', ([], {}), '()\n', (303, 305), False, 'from datetime import date, datetime as dt\n'), ((614, 657), 'os.path.join', 'os.path.join', (['settings.MODELS_DIR', 'name_dir'], {}), '(settings.MODELS_DIR, name_dir)\n', (626, 657), False, 'import os\n'), ((932, 966), 'os.path.jo... |
"""Generate case files"""
from argparse import ArgumentParser
from datetime import datetime
import json
import os
import numpy as np
from tqdm import trange
from tti_explorer import sensitivity
from tti_explorer.utils import ROOT_DIR
from tti_explorer.case_generator import get_generator_configs, CaseGenerator
de... | [
"json.dump",
"os.makedirs",
"argparse.ArgumentParser",
"os.path.join",
"tqdm.trange",
"datetime.datetime.now",
"numpy.loadtxt",
"tti_explorer.case_generator.CaseGenerator",
"tti_explorer.case_generator.get_generator_configs"
] | [((348, 401), 'numpy.loadtxt', 'np.loadtxt', (['pth'], {'dtype': 'int', 'skiprows': '(1)', 'delimiter': '""","""'}), "(pth, dtype=int, skiprows=1, delimiter=',')\n", (358, 401), True, 'import numpy as np\n'), ((647, 718), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Generate JSON files of cases... |
"""
Testing for (Normalized) DCG metric.
"""
from . import helpers
import itertools
import numpy as np
import pyltr
class TestDCG(helpers.TestMetric):
def get_metric(self):
return pyltr.metrics.DCG(k=3)
def get_queries_with_values(self):
yield [], 0.0
yield [0], 0.0
yield [... | [
"itertools.product",
"numpy.array",
"pyltr.metrics.NDCG",
"pyltr.metrics.DCG"
] | [((197, 219), 'pyltr.metrics.DCG', 'pyltr.metrics.DCG', ([], {'k': '(3)'}), '(k=3)\n', (214, 219), False, 'import pyltr\n'), ((752, 775), 'pyltr.metrics.NDCG', 'pyltr.metrics.NDCG', ([], {'k': '(3)'}), '(k=3)\n', (770, 775), False, 'import pyltr\n'), ((596, 635), 'itertools.product', 'itertools.product', (['*([(0, 1, 2... |
'''
Created on: see version log.
@author: rigonz
coding: utf-8
IMPORTANT: requires py3.6 (rasterio)
Script that:
1) reads a series of raster files,
2) computes aggregated statistics,
3) outputs the results.
The input data files correspond to countries and represent population.
For each country there is one file with... | [
"numpy.full_like",
"rasterio.open",
"pyproj.Geod"
] | [((1126, 1169), 'pyproj.Geod', 'Geod', (['"""+a=6378137 +f=0.0033528106647475126"""'], {}), "('+a=6378137 +f=0.0033528106647475126')\n", (1130, 1169), False, 'from pyproj import Geod\n'), ((1453, 1477), 'rasterio.open', 'rasterio.open', (['FileNameI'], {}), '(FileNameI)\n', (1466, 1477), False, 'import rasterio\n'), ((... |
# -*- coding: utf-8 -*-
# /usr/bin/python2
'''
June 2017 by <NAME>.
<EMAIL>.
https://www.github.com/kyubyong/neurobind
'''
from __future__ import print_function
import re
from hyperparams import Hyperparams as hp
import numpy as np
import tensorflow as tf
def load_vocab():
vocab = "ACGT"
nucl2idx = {nucl: i... | [
"tensorflow.convert_to_tensor",
"tensorflow.train.batch",
"numpy.array",
"tensorflow.train.slice_input_producer"
] | [((969, 991), 'numpy.array', 'np.array', (['xs', 'np.int32'], {}), '(xs, np.int32)\n', (977, 991), True, 'import numpy as np\n'), ((1000, 1024), 'numpy.array', 'np.array', (['ys', 'np.float32'], {}), '(ys, np.float32)\n', (1008, 1024), True, 'import numpy as np\n'), ((1474, 1507), 'tensorflow.convert_to_tensor', 'tf.co... |
"""
pysteps.postprocessing.ensemblestats
====================================
Methods for the computation of ensemble statistics.
.. autosummary::
:toctree: ../generated/
mean
excprob
"""
import numpy as np
def mean(X, ignore_nan=False, X_thr=None):
"""Compute the mean value from a forecast ensemb... | [
"numpy.stack",
"numpy.isscalar",
"numpy.asanyarray",
"numpy.mean",
"numpy.nanmean"
] | [((780, 796), 'numpy.asanyarray', 'np.asanyarray', (['X'], {}), '(X)\n', (793, 796), True, 'import numpy as np\n'), ((2002, 2018), 'numpy.asanyarray', 'np.asanyarray', (['X'], {}), '(X)\n', (2015, 2018), True, 'import numpy as np\n'), ((2208, 2226), 'numpy.isscalar', 'np.isscalar', (['X_thr'], {}), '(X_thr)\n', (2219, ... |
# TODO: avoid useless comparisons
from collections import defaultdict
from numbers import Number
from typing import Dict, List, Union
import numba as nb
import numpy as np
from numba import set_num_threads
from .frozenset_dict import FrozensetDict
from .metrics import (
average_precision,
hits,
ndcg,
... | [
"collections.defaultdict",
"numba.set_num_threads",
"numpy.mean"
] | [((5182, 5199), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (5193, 5199), False, 'from collections import defaultdict\n'), ((6504, 6521), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (6515, 6521), False, 'from collections import defaultdict\n'), ((2851, 2869), 'numba.s... |
"""Helper module for calculating the live activation counts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from morph_net.framework import op_regularizer_manager as orm
import numpy as np
import tensorflow as tf
from typing impor... | [
"numpy.sum",
"tensorflow.logging.warning",
"tensorflow.cast",
"tensorflow.gfile.MkDir",
"os.path.join"
] | [((4432, 4476), 'os.path.join', 'os.path.join', (['train_dir', '"""learned_structure"""'], {}), "(train_dir, 'learned_structure')\n", (4444, 4476), False, 'import os\n'), ((822, 842), 'numpy.sum', 'np.sum', (['alive_vector'], {}), '(alive_vector)\n', (828, 842), True, 'import numpy as np\n'), ((4492, 4517), 'tensorflow... |
from abc import ABC
import numpy as np
from shared_utils.constants import EMPTY_ARRAY, EMPTY_ARRAY_2D
class RKStep(ABC):
"""
Butcher - 2016 - NUMERICAL METHODS FOR ORDINARY DIFFERENTIAL EQUATIONS - pg 98
c | A
----------
| b^T
A - dependence of the stages on the derivatives found at ot... | [
"numpy.eye"
] | [((738, 763), 'numpy.eye', 'np.eye', (['*self.a_mat.shape'], {}), '(*self.a_mat.shape)\n', (744, 763), True, 'import numpy as np\n')] |
''' Analysis of trained RNN '''
import sys
import random
import numpy as np
from scipy import stats
import tensorflow as tf
from sklearn.metrics import r2_score
from sklearn.decomposition import FastICA, PCA
import matplotlib.pyplot as plt
def lstm_states(sess, cell, x, dtype=tf.float32):
''' Get LSTM states at a... | [
"tensorflow.get_collection",
"tensorflow.variables_initializer",
"tensorflow.Variable",
"numpy.linalg.norm",
"tensorflow.get_variable",
"tensorflow.variable_scope",
"tensorflow.minimum",
"tensorflow.stack",
"tensorflow.placeholder",
"numpy.cumsum",
"matplotlib.pyplot.subplots",
"numpy.stack",
... | [((437, 493), 'tensorflow.placeholder', 'tf.placeholder', (['dtype', '[None, input_size]'], {'name': '"""curr_x"""'}), "(dtype, [None, input_size], name='curr_x')\n", (451, 493), True, 'import tensorflow as tf\n'), ((507, 559), 'tensorflow.placeholder', 'tf.placeholder', (['dtype', '[None, c_size]'], {'name': '"""curr_... |
"""
BeamColumnElement
================
Module contains a beam column element under bending action and axial forces.
"""
import numpy as np
import numpy.linalg as la
from FE_code.element import Element
from FE_code.node import Node
import scipy
class BeamColumnElement(Element):
"""Two dimensional beam column ele... | [
"numpy.sin",
"numpy.linalg.norm",
"numpy.array",
"numpy.cos",
"numpy.dot",
"numpy.arccos"
] | [((2384, 2430), 'numpy.array', 'np.array', (['[node.coords for node in self.nodes]'], {}), '([node.coords for node in self.nodes])\n', (2392, 2430), True, 'import numpy as np\n'), ((3081, 3095), 'numpy.linalg.norm', 'la.norm', (['(b - a)'], {}), '(b - a)\n', (3088, 3095), True, 'import numpy.linalg as la\n'), ((3351, 3... |
from numpy import prod
def persistence(n):
if n < 10: return 0
nums = [int(x) for x in str(n)]
steps = 1
while prod(nums) > 9:
nums = [int(x) for x in str(int(prod(nums)))]
steps += 1
return steps
| [
"numpy.prod"
] | [((132, 142), 'numpy.prod', 'prod', (['nums'], {}), '(nums)\n', (136, 142), False, 'from numpy import prod\n'), ((188, 198), 'numpy.prod', 'prod', (['nums'], {}), '(nums)\n', (192, 198), False, 'from numpy import prod\n')] |
import torch
import numpy as np
from scipy.interpolate import RectBivariateSpline
from scipy.ndimage import binary_dilation
from scipy.stats import gaussian_kde
from utils import prediction_output_to_trajectories
import visualization
def compute_ade(predicted_trajs, gt_traj):
error = np.linalg.norm(predicted_trajs... | [
"numpy.stack",
"scipy.ndimage.binary_dilation",
"numpy.median",
"torch.argsort",
"torch.transpose",
"numpy.min",
"numpy.mean",
"numpy.linalg.norm",
"numpy.array",
"visualization.visualize_mink",
"torch.tensor",
"utils.prediction_output_to_trajectories"
] | [((290, 340), 'numpy.linalg.norm', 'np.linalg.norm', (['(predicted_trajs - gt_traj)'], {'axis': '(-1)'}), '(predicted_trajs - gt_traj, axis=-1)\n', (304, 340), True, 'import numpy as np\n'), ((351, 374), 'numpy.mean', 'np.mean', (['error'], {'axis': '(-1)'}), '(error, axis=-1)\n', (358, 374), True, 'import numpy as np\... |
from __future__ import absolute_import, division, unicode_literals
from itertools import product
import numpy as np
import param
from matplotlib.patches import Wedge, Circle
from matplotlib.collections import LineCollection, PatchCollection
from ...core.data import GridInterface
from ...core.util import dimension_s... | [
"param.Number",
"matplotlib.collections.LineCollection",
"param.Dict",
"param.Boolean",
"param.Parameter",
"matplotlib.patches.Wedge",
"numpy.isfinite",
"matplotlib.patches.Circle",
"numpy.rad2deg",
"numpy.diff",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"itertools.product",
"matp... | [((577, 1021), 'param.Dict', 'param.Dict', ([], {'default': "{'NaN': 'white'}", 'doc': '"""\n Dictionary to specify colors for clipped values, allows\n setting color for NaN values and for values above and below\n the min and max value. The min, max or NaN color may specify\n an RGB(A) color... |
from abc import abstractmethod, ABC
import os
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
from torch.utils.data import Subset
from torchvision import transforms
from .base import get_split_indices, print_loaded_dataset_shapes, get_loaders_from_datasets, log_call_parameters
class Standa... | [
"torch.utils.data.Subset",
"logging.basicConfig",
"logging.info",
"numpy.random.choice",
"torchvision.transforms.Normalize",
"os.path.join",
"torchvision.transforms.ToTensor"
] | [((61, 100), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (80, 100), False, 'import logging\n'), ((1117, 1169), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': 'self.means', 'std': 'self.stds'}), '(mean=self.means, std=self.stds)\n', ... |
# -*- coding: utf-8 -*-
"""image_to_amime_with_mxnet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1LTzdjBxSsx9vAmfF8Xt81FHVgSwGSUYU
"""
from PIL import Image
import torch
import IPython
from IPython.display import display
import numpy as np
... | [
"pickle.dump",
"mxnet.image.imdecode",
"pickle.load",
"numpy.mean",
"dlib.shape_predictor",
"os.path.join",
"sys.path.append",
"numpy.zeros_like",
"numpy.max",
"mxnet.recordio.IRHeader",
"torch.hub.load",
"numpy.uint8",
"faceBlendCommon.getLandmarks",
"mxnet.recordio.pack_img",
"numpy.mi... | [((510, 596), 'torch.hub.load', 'torch.hub.load', (['"""bryandlee/animegan2-pytorch:main"""', '"""generator"""'], {'pretrained': 'anime'}), "('bryandlee/animegan2-pytorch:main', 'generator', pretrained=\n anime)\n", (524, 596), False, 'import torch\n'), ((626, 700), 'torch.hub.load', 'torch.hub.load', (['"""bryandle... |
import imagematrix
from array import *
import math
import numpy as np
class ResizeableImage(imagematrix.ImageMatrix):
"""
Find the best seam
"""
def best_seam(self, dp=True):
# initialize an energy map (filled with zeros)
gradient = np.zeros((self.width,self.height),dtype = np.int)
seam = []
if dp == True:... | [
"numpy.zeros"
] | [((242, 291), 'numpy.zeros', 'np.zeros', (['(self.width, self.height)'], {'dtype': 'np.int'}), '((self.width, self.height), dtype=np.int)\n', (250, 291), True, 'import numpy as np\n')] |
# Copyright 2016, 2017 California Institute of Technology
# Users must agree to abide by the restrictions listed in the
# file "LegalStuff.txt" in the PROPER library directory.
#
# PROPER developed at Jet Propulsion Laboratory/California Inst. Technology
# Original IDL version by <NAME>
# Python translation... | [
"proper.prop_wts",
"proper.prop_select_propagator",
"numpy.abs",
"proper.prop_ptp",
"proper.prop_stw",
"proper.prop_get_beamradius"
] | [((1162, 1199), 'proper.prop_select_propagator', 'proper.prop_select_propagator', (['wf', 'dz'], {}), '(wf, dz)\n', (1191, 1199), False, 'import proper\n'), ((1527, 1550), 'proper.prop_ptp', 'proper.prop_ptp', (['wf', 'dz'], {}), '(wf, dz)\n', (1542, 1550), False, 'import proper\n'), ((1613, 1646), 'proper.prop_ptp', '... |
import json
import sys
from sklearn.metrics import classification_report
from argparse import ArgumentParser
import tensorflow as tf
import numpy as np
from src.utils.model_utility import *
from src.utils.generators import *
def predict_model(model_configuration: str,
dataset_configuration: str,
... | [
"numpy.shape",
"json.load",
"tensorflow.keras.models.load_model",
"argparse.ArgumentParser"
] | [((1139, 1194), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (["model_parameters['weights']"], {}), "(model_parameters['weights'])\n", (1165, 1194), True, 'import tensorflow as tf\n'), ((2395, 2411), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (2409, 2411), False, 'from argpars... |
from functools import partial
from multiprocessing.pool import Pool
import cv2
import numpy as np
import scipy as sp
import torch
from pytorch_toolbelt.utils.torch_utils import to_numpy
from tqdm import tqdm
from xview.dataset import read_mask
from xview.metric import CompetitionMetricCallback
from xview.postprocessi... | [
"numpy.stack",
"functools.partial",
"scipy.optimize.minimize",
"numpy.load",
"xview.metric.CompetitionMetricCallback.compute_metrics",
"tqdm.tqdm",
"numpy.expand_dims",
"xview.dataset.read_mask",
"xview.metric.CompetitionMetricCallback.get_row_pair",
"multiprocessing.pool.Pool",
"torch.no_grad",... | [((505, 583), 'xview.metric.CompetitionMetricCallback.get_row_pair', 'CompetitionMetricCallback.get_row_pair', (['loc_pred', 'dmg_pred', 'dmg_true', 'dmg_true'], {}), '(loc_pred, dmg_pred, dmg_true, dmg_true)\n', (543, 583), False, 'from xview.metric import CompetitionMetricCallback\n'), ((795, 810), 'torch.no_grad', '... |
# The main test script for the project
# GenSparseMatrix takes an input density and generates an nxn sparse matrix using a uniform distribution.
# It ensures that the resulting sparse matrix is diagonally dominant
import numpy as np
from scipy import sparse
from sparse_methods import *
from jacobi import *
#fr... | [
"numpy.abs",
"numpy.zeros",
"numpy.ones",
"scipy.sparse.rand",
"numpy.random.normal",
"numpy.random.choice",
"numpy.random.rand",
"numpy.eye"
] | [((384, 440), 'scipy.sparse.rand', 'sparse.rand', (['n', 'n', 'density'], {'format': '"""dok"""', 'random_state': '(1)'}), "(n, n, density, format='dok', random_state=1)\n", (395, 440), False, 'from scipy import sparse\n'), ((450, 466), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (458, 466), True, 'impor... |
from __future__ import print_function, absolute_import
import os, sys, subprocess, shlex, tempfile, time, sklearn.base, math
import numpy as np
import pandas as pd
from pandas_extensions import *
from ExeEstimator import *
class LibFFMClassifier(ExeEstimator, sklearn.base.ClassifierMixin):
'''
options:... | [
"pandas.DataFrame",
"math.exp",
"numpy.vstack"
] | [((2904, 2945), 'numpy.vstack', 'np.vstack', (['[1 - predictions, predictions]'], {}), '([1 - predictions, predictions])\n', (2913, 2945), True, 'import numpy as np\n'), ((1496, 1533), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {'columns': 'self.columns'}), '(X, columns=self.columns)\n', (1508, 1533), True, 'import pa... |
"""
Author: <NAME> (<EMAIL>, http://personales.upv.es/jon)
Version: 1.0
Date: June 2014
Universitat Politecnica de Valencia
Technical University of Valencia TU.VLC
"""
import sys
import numpy
from . import MyKernel
class MyKernelClassifier:
"""
This class implements a classifier based on... | [
"numpy.unique"
] | [((949, 964), 'numpy.unique', 'numpy.unique', (['Y'], {}), '(Y)\n', (961, 964), False, 'import numpy\n')] |
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, lstsq, hankel
from scipy.signal import convolve2d
from mas.forward_model import add_noise
N = 100
m, n = np.arange(N), np.arange(N)
omega_m = np.array((4.00001,))
omega_n = np.array((8.00002,))
y = np.sum(
np.e**(
1j * 2 ... | [
"numpy.pad",
"numpy.roots",
"numpy.sum",
"scipy.signal.convolve2d",
"numpy.arange",
"numpy.array"
] | [((229, 249), 'numpy.array', 'np.array', (['(4.00001,)'], {}), '((4.00001,))\n', (237, 249), True, 'import numpy as np\n'), ((260, 280), 'numpy.array', 'np.array', (['(8.00002,)'], {}), '((8.00002,))\n', (268, 280), True, 'import numpy as np\n'), ((285, 537), 'numpy.sum', 'np.sum', (['(np.e ** (1.0j * 2 * np.pi * (omeg... |
#!/usr/bin/env python
"""Python wrapper for the GROMACS rms module
"""
import os
import sys
import json
import ntpath
import numpy as np
import configuration.settings as settings
from command_wrapper import cmd_wrapper
from tools import file_utils as fu
class Rms(object):
"""Wrapper for the trjconv module
Arg... | [
"ntpath.basename",
"json.loads",
"command_wrapper.cmd_wrapper.CmdWrapper",
"os.path.isfile",
"numpy.loadtxt",
"tools.file_utils.get_logs",
"configuration.settings.YamlReader"
] | [((1484, 1551), 'tools.file_utils.get_logs', 'fu.get_logs', ([], {'path': 'self.path', 'mutation': 'self.mutation', 'step': 'self.step'}), '(path=self.path, mutation=self.mutation, step=self.step)\n', (1495, 1551), True, 'from tools import file_utils as fu\n'), ((2185, 2230), 'command_wrapper.cmd_wrapper.CmdWrapper', '... |
from typing import TYPE_CHECKING
import numpy as np
from ..types.ndarray import get_array_type
if TYPE_CHECKING:
from ..types.ndarray import ArrayType
def pdist(
x_mat: 'ArrayType',
metric: str,
) -> 'np.ndarray':
"""Computes Pairwise distances between observations in n-dimensional space.
:para... | [
"scipy.sparse.linalg.norm",
"numpy.dot",
"numpy.sum",
"numpy.linalg.norm"
] | [((2904, 2930), 'numpy.sum', 'np.sum', (['(y_mat ** 2)'], {'axis': '(1)'}), '(y_mat ** 2, axis=1)\n', (2910, 2930), True, 'import numpy as np\n'), ((2997, 3019), 'numpy.dot', 'np.dot', (['x_mat', 'y_mat.T'], {}), '(x_mat, y_mat.T)\n', (3003, 3019), True, 'import numpy as np\n'), ((2941, 2967), 'numpy.sum', 'np.sum', ([... |
from general_utils.data_storage_classes.stock_cluster import StockCluster
from stock_data_analysis_module.data_processing_module.data_retrieval_module.ranged_data_retriever import RangedDataRetriever
import numpy as np
from datetime import date, datetime
def date_to_timestamp(date_in: date):
return datetim... | [
"numpy.corrcoef",
"general_utils.data_storage_classes.stock_cluster.StockCluster",
"stock_data_analysis_module.data_processing_module.data_retrieval_module.ranged_data_retriever.RangedDataRetriever"
] | [((2409, 2494), 'general_utils.data_storage_classes.stock_cluster.StockCluster', 'StockCluster', (['mainTicker', 'mainTickerData', 'supportingTickers', 'supportingTickerData'], {}), '(mainTicker, mainTickerData, supportingTickers,\n supportingTickerData)\n', (2421, 2494), False, 'from general_utils.data_storage_clas... |
import plac
from os import path
import numpy as np
from scipy import sparse
from scipy.io import savemat
from cmmlib.inout import load_mesh, save_coff
from cmmlib import cmm
@plac.annotations(
K=('number of CMHBs', 'positional', None, int),
mu=('sparsity parameter mu', 'positional', None, float),
visuali... | [
"plac.annotations",
"cmmlib.vis.weights.show_weights",
"os.path.exists",
"numpy.zeros",
"plac.call",
"cmmlib.vis.weights._centered",
"cmmlib.inout.load_mesh",
"cmmlib.cmm.compressed_manifold_modes",
"mayavi.core.lut_manager.LUTManager",
"os.path.join",
"numpy.vstack",
"numpy.sqrt"
] | [((178, 622), 'plac.annotations', 'plac.annotations', ([], {'K': "('number of CMHBs', 'positional', None, int)", 'mu': "('sparsity parameter mu', 'positional', None, float)", 'visualize': "('visualize the weights?', 'flag', 'v')", 'scaled': "('respect triangle scaling?', 'flag', 's')", 'output_dir': "('output directory... |
import cv2
import numpy as np
def white_mask(original):
"""
Create a mask from the whitish pixels of the frame
"""
# specify the range of colours that you want to include, you can play with the borders here
lower_white = (190, 100, 100)
upper_white = (255, 255, 255)
white = cv2.inRange(or... | [
"cv2.cvtColor",
"numpy.asarray",
"numpy.zeros_like",
"cv2.inRange"
] | [((306, 353), 'cv2.inRange', 'cv2.inRange', (['original', 'lower_white', 'upper_white'], {}), '(original, lower_white, upper_white)\n', (317, 353), False, 'import cv2\n'), ((366, 386), 'numpy.zeros_like', 'np.zeros_like', (['white'], {}), '(white)\n', (379, 386), True, 'import numpy as np\n'), ((424, 450), 'numpy.asarr... |
import numpy as np
import pandas as pd
from collections import OrderedDict
from scipy import interp
from sklearn.metrics import auc
from sklearn.metrics.ranking import _binary_clf_curve
from pohmm import Pohmm, PohmmClassifier
# CMU Keystroke Dynamics Benchmark Dataset
# See: http://www.cs.cmu.edu/~keystroke/
# <NAME... | [
"numpy.random.seed",
"sklearn.metrics.ranking._binary_clf_curve",
"pohmm.Pohmm",
"pandas.read_csv",
"numpy.median",
"numpy.empty_like",
"pohmm.PohmmClassifier",
"sklearn.metrics.auc",
"numpy.diff",
"numpy.array",
"pandas.DataFrame.from_records",
"collections.OrderedDict",
"numpy.dot",
"sci... | [((2060, 2130), 'sklearn.metrics.ranking._binary_clf_curve', '_binary_clf_curve', (['y_true', 'y_score'], {'pos_label': 'None', 'sample_weight': 'None'}), '(y_true, y_score, pos_label=None, sample_weight=None)\n', (2077, 2130), False, 'from sklearn.metrics.ranking import _binary_clf_curve\n'), ((4159, 4200), 'sklearn.m... |
"""
pid_control
- <NAME>, PUP, 2012
- Last Update:
2/6/2019 - RWB
"""
import sys
import numpy as np
sys.path.append('..')
class pidControl:
def __init__(self, kp=0.0, ki=0.0, kd=0.0, Ts=0.01, sigma=0.05, limit=1.0):
self.kp = kp
self.ki = ki
self.kd = kd
self.Ts = T... | [
"sys.path.append",
"numpy.abs"
] | [((116, 137), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (131, 137), False, 'import sys\n'), ((1607, 1622), 'numpy.abs', 'np.abs', (['self.ki'], {}), '(self.ki)\n', (1613, 1622), True, 'import numpy as np\n'), ((2575, 2590), 'numpy.abs', 'np.abs', (['self.ki'], {}), '(self.ki)\n', (2581, 2590... |
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# Adapted after Key Phrase Extraction EmbedRank Algorithm by Swisscom (Schweiz) AG
# github repository of the project: https://github.com/swisscom/ai-research-keyphrase-extraction
# source code on github: https://github.com/swisscom/ai-research-... | [
"numpy.fill_diagonal",
"sklearn.metrics.pairwise.cosine_similarity",
"numpy.average",
"numpy.nan_to_num",
"numpy.argmax",
"numpy.std",
"numpy.nanstd",
"numpy.argsort",
"numpy.max",
"numpy.array",
"numpy.nanmax",
"numpy.nanmean"
] | [((1644, 1683), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['candidate_embeddings'], {}), '(candidate_embeddings)\n', (1661, 1683), False, 'from sklearn.metrics.pairwise import cosine_similarity\n'), ((1688, 1725), 'numpy.fill_diagonal', 'np.fill_diagonal', (['sim_between', 'np.NaN'], {}), '(si... |
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
tLimits = [0, 5]
mu = 0
sigma = 0.75
def lognorm(t):
return (np.exp(-((np.log(t) - mu) ** 2) / (2 * sigma ** 2))) / (t * sigma * np.sqrt(2 * np.pi))
tValues = np.arange(0.01, 5, 0.01)
yValues = np.array(list(map(lognorm, tVa... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.log",
"matplotlib.pyplot.plot",
"random.uniform",
"matplotlib.pyplot.legend",
"numpy.zeros",
"scipy.stats.lognorm",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"... | [((255, 279), 'numpy.arange', 'np.arange', (['(0.01)', '(5)', '(0.01)'], {}), '(0.01, 5, 0.01)\n', (264, 279), True, 'import numpy as np\n'), ((328, 340), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (338, 340), True, 'import matplotlib.pyplot as plt\n'), ((341, 373), 'matplotlib.pyplot.plot', 'plt.plot'... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
class STN3d(nn.Module):
def __init__(self, channel):
super(STN3d, self).__init__()
self.conv1 = torch.nn.Conv1d(channel, 64, 1)
self.conv2 = torch.nn.Conv1d(64, 128, 1)
... | [
"torch.nn.Dropout",
"torch.bmm",
"torch.nn.ReLU",
"torch.nn.BatchNorm1d",
"torch.nn.Conv1d",
"torch.cat",
"torch.nn.Upsample",
"torch.max",
"torch.nn.Softmax",
"torch.cuda.is_available",
"torch.nn.Linear",
"numpy.array",
"numpy.eye"
] | [((239, 270), 'torch.nn.Conv1d', 'torch.nn.Conv1d', (['channel', '(64)', '(1)'], {}), '(channel, 64, 1)\n', (254, 270), False, 'import torch\n'), ((292, 319), 'torch.nn.Conv1d', 'torch.nn.Conv1d', (['(64)', '(128)', '(1)'], {}), '(64, 128, 1)\n', (307, 319), False, 'import torch\n'), ((341, 370), 'torch.nn.Conv1d', 'to... |
from concurrent.futures import ProcessPoolExecutor
from functools import partial
import numpy as np
import os
import glob
#from util import audio
import audio
from hparams import hparams as hp
def build_from_path(in_dir, out_dir, num_workers=1, tqdm=lambda x: x):
'''Preprocesses the THCHS30 dataset from a given i... | [
"audio.load_wav",
"numpy.abs",
"concurrent.futures.ProcessPoolExecutor",
"os.path.exists",
"audio.melspectrogram",
"audio.spectrogram",
"audio.trim_silence",
"os.path.join"
] | [((955, 999), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'num_workers'}), '(max_workers=num_workers)\n', (974, 999), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((2269, 2308), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_worke... |
#============================================================================
# Copyright (c) 2018 Diamond Light Source Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License ... | [
"numpy.pad",
"vounwarp.losa.loadersaver.load_image",
"vounwarp.post.postprocessing.unwarp_image_backward",
"numpy.asarray",
"numpy.zeros",
"vounwarp.losa.loadersaver.save_image",
"numpy.max"
] | [((1317, 1352), 'vounwarp.losa.loadersaver.load_image', 'io.load_image', (['"""Sol0_1st_color.png"""'], {}), "('Sol0_1st_color.png')\n", (1330, 1352), True, 'import vounwarp.losa.loadersaver as io\n'), ((1469, 1512), 'numpy.zeros', 'np.zeros', (['(height, width)'], {'dtype': 'np.float32'}), '((height, width), dtype=np.... |
"""
Parsers provided by aiida_skeaf.
Register parsers via the "aiida.parsers" entry point in setup.json.
"""
import re
import typing as ty
import numpy as np
from aiida import orm
from aiida.common import exceptions
from aiida.engine import ExitCode
from aiida.parsers.parser import Parser
from aiida.plugins import C... | [
"aiida.orm.Dict",
"re.compile",
"aiida.common.exceptions.ParsingError",
"aiida.plugins.CalculationFactory",
"numpy.loadtxt",
"aiida.orm.ArrayData",
"aiida.engine.ExitCode"
] | [((358, 391), 'aiida.plugins.CalculationFactory', 'CalculationFactory', (['"""skeaf.skeaf"""'], {}), "('skeaf.skeaf')\n", (376, 391), False, 'from aiida.plugins import CalculationFactory\n'), ((4180, 4205), 'aiida.orm.Dict', 'orm.Dict', ([], {'dict': 'parameters'}), '(dict=parameters)\n', (4188, 4205), False, 'from aii... |
import os
import os.path
import numpy as np
import h5py
import torch
import utils
DATASET_REGISTRY = {}
def build_dataset(name, *args, **kwargs):
return DATASET_REGISTRY[name](*args, **kwargs)
def register_dataset(name):
def register_dataset_fn(fn):
if name in DATASET_REGISTRY:
raise Va... | [
"h5py.File",
"utils.PieceWiseConstantDataset",
"torch.utils.data.DataLoader",
"utils.MaskedDataset",
"torch.Tensor",
"numpy.array"
] | [((1111, 1208), 'utils.PieceWiseConstantDataset', 'utils.PieceWiseConstantDataset', ([], {'n_data': 'n_data', 'fix_datapoints': 'fix_datapoints', 'min_sep': 'min_sep'}), '(n_data=n_data, fix_datapoints=fix_datapoints,\n min_sep=min_sep)\n', (1141, 1208), False, 'import utils\n'), ((1229, 1337), 'torch.utils.data.Dat... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.gridspec as gridspec
import time
import os
import helpers
import head_move_box
def dist(arr):
# compute distance
return np.sqrt((arr[0] ** 2) + (arr... | [
"helpers.landmarks_3d_fitting",
"helpers.visualize_facial_landmarks",
"os.mkdir",
"cv2.VideoWriter_fourcc",
"helpers.get_fixedPoint",
"head_move_box.head_box_plot",
"matplotlib.pyplot.figure",
"numpy.arange",
"cv2.VideoWriter",
"cv2.imshow",
"os.path.join",
"matplotlib.backends.backend_agg.Fig... | [((292, 326), 'numpy.sqrt', 'np.sqrt', (['(arr[0] ** 2 + arr[1] ** 2)'], {}), '(arr[0] ** 2 + arr[1] ** 2)\n', (299, 326), True, 'import numpy as np\n'), ((377, 388), 'time.time', 'time.time', ([], {}), '()\n', (386, 388), False, 'import time\n'), ((952, 986), 'os.path.join', 'os.path.join', (['target', '"""output.avi"... |
import numpy as np
import logging
from tqdm import tqdm
class Perceptron():
def __init__(self, eta, epochs):
self.weights = np.random.randn(3) * 1e-4 # SMALL WEIGHTS INIT
self.eta = eta # Learning Rate
self.epochs = epochs
logging.info(f'initial weights before training :\n{self.weights}')
def activation... | [
"numpy.sum",
"numpy.random.randn",
"logging.info",
"numpy.where",
"numpy.dot"
] | [((237, 306), 'logging.info', 'logging.info', (['f"""initial weights before training :\n{self.weights}"""'], {}), '(f"""initial weights before training :\n{self.weights}""")\n', (249, 306), False, 'import logging\n'), ((360, 383), 'numpy.dot', 'np.dot', (['inputs', 'weights'], {}), '(inputs, weights)\n', (366, 383), Tr... |
"""This script contains code to support creation of photometric sourcelists using two techniques:
aperture photometry and segmentation-map based photometry."""
import os
import sys
import shutil
import warnings
from distutils.version import LooseVersion
import numpy as np
import skimage
from astropy.io import fits a... | [
"os.remove",
"numpy.abs",
"numpy.nan_to_num",
"numpy.invert",
"astropy.io.fits.PrimaryHDU",
"numpy.isnan",
"photutils.detection._utils._StarFinderKernel",
"numpy.argsort",
"numpy.arange",
"os.path.join",
"numpy.fft.ifft2",
"shutil.copy",
"numpy.copy",
"astropy.io.fits.getdata",
"os.path.... | [((1518, 1650), 'stsci.tools.logutil.create_logger', 'logutil.create_logger', (['__name__'], {'level': 'logutil.logging.NOTSET', 'stream': 'sys.stdout', 'format': 'SPLUNK_MSG_FORMAT', 'datefmt': 'MSG_DATEFMT'}), '(__name__, level=logutil.logging.NOTSET, stream=sys.\n stdout, format=SPLUNK_MSG_FORMAT, datefmt=MSG_DAT... |
import logging
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
logger = logging.getLogger()
from activeClassifier.visualisation.base import Visualiser, visualisation_level
from activeClassifier.tools.utility import softmax
# ann... | [
"numpy.sum",
"matplotlib.cm.get_cmap",
"numpy.argmax",
"numpy.argsort",
"numpy.arange",
"numpy.ma.masked_array",
"numpy.round",
"numpy.prod",
"numpy.pad",
"matplotlib.patches.Rectangle",
"numpy.reshape",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"activeClassifier.visualisation.base.v... | [((52, 73), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (66, 73), False, 'import matplotlib\n'), ((162, 181), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (179, 181), False, 'import logging\n'), ((400, 490), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '... |
# Copyright 2020 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | [
"numpy.zeros",
"thewalrus.quantum.density_matrix_element",
"numpy.array",
"thewalrus.quantum.reduced_gaussian",
"numpy.diag",
"numpy.concatenate"
] | [((4201, 4221), 'numpy.array', 'np.array', (['(d @ l0_inv)'], {}), '(d @ l0_inv)\n', (4209, 4221), True, 'import numpy as np\n'), ((10954, 10980), 'numpy.zeros', 'np.zeros', (['(n_modes, n_max)'], {}), '((n_modes, n_max))\n', (10962, 10980), True, 'import numpy as np\n'), ((7624, 7641), 'numpy.concatenate', 'np.concate... |
from typing import Sequence
from typing import Tuple
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import torch
def get_feature_contributions(
model: torch.nn.Module,
dataset: torch.utils.data.Dataset,
) -> Sequence[torch.Tensor]:
feature_contributions = []
... | [
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.pyplot.bar",
"numpy.argsort",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.histogram",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.yticks",
"numpy.max",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.yli... | [((2114, 2140), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (2124, 2140), True, 'import matplotlib.pyplot as plt\n'), ((2187, 2201), 'numpy.argsort', 'np.argsort', (['x2'], {}), '(x2)\n', (2197, 2201), True, 'import numpy as np\n'), ((2296, 2338), 'matplotlib.pyplot.bar'... |
# based on https://github.com/google-coral/pycoral/blob/master/examples/detect_image.py
from imutils.video import VideoStream, FPS
import argparse
import time
import cv2
from PIL import Image, ImageDraw
import numpy as np
from pycoral.adapters import common
from pycoral.adapters import detect
from pycoral.utils.datase... | [
"pycoral.utils.edgetpu.make_interpreter",
"imutils.video.VideoStream",
"imutils.video.FPS",
"pycoral.utils.dataset.read_label_file",
"argparse.ArgumentParser",
"cv2.waitKey",
"cv2.destroyAllWindows",
"numpy.asarray",
"pycoral.adapters.detect.get_objects",
"time.sleep",
"PIL.Image.fromarray",
"... | [((448, 469), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['image'], {}), '(image)\n', (462, 469), False, 'from PIL import Image, ImageDraw\n'), ((771, 788), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (781, 788), True, 'import numpy as np\n'), ((793, 848), 'cv2.imshow', 'cv2.imshow', (['"""Coral Live Obj... |
#!/usr/bin/python3
__version__ = '0.0.12' # Time-stamp: <2021-09-25T04:50:45Z>
## Language: Japanese/UTF-8
"""Simulation Buddhism Prototype No.2 - Domination
支配関連
"""
##
## Author:
##
## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese))
##
## License:
##
## The author is a Japanese.
##... | [
"math.sqrt",
"random.uniform",
"numpy.random.beta",
"random.sample",
"math.ceil",
"random.choice",
"random.random",
"numpy.mean",
"collections.OrderedDict",
"simbdp2.common.Rape",
"simbdp2.common.np_clip",
"simbdp2.base.calamity_info.items"
] | [((22068, 22094), 'simbdp2.base.calamity_info.items', 'base.calamity_info.items', ([], {}), '()\n', (22092, 22094), True, 'import simbdp2.base as base\n'), ((10231, 10244), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (10242, 10244), False, 'from collections import OrderedDict\n'), ((15249, 15275), 'nump... |
# Copyright (c) 2021 Horizon Robotics and ALF Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | [
"numpy.isscalar",
"numpy.zeros",
"numpy.ones",
"numpy.prod",
"numpy.array",
"gym.spaces.Box",
"numpy.concatenate"
] | [((1739, 1767), 'numpy.concatenate', 'np.concatenate', (['mins'], {'axis': '(0)'}), '(mins, axis=0)\n', (1753, 1767), True, 'import numpy as np\n'), ((1779, 1807), 'numpy.concatenate', 'np.concatenate', (['maxs'], {'axis': '(0)'}), '(maxs, axis=0)\n', (1793, 1807), True, 'import numpy as np\n'), ((1854, 1893), 'gym.spa... |
"""
QE by <NAME> and <NAME>.
Illustrates preimages of functions
"""
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return 0.6 * np.cos(4 * x) + 1.4
xmin, xmax = -1, 1
x = np.linspace(xmin, xmax, 160)
y = f(x)
ya, yb = np.min(y), np.max(y)
fig, axes = plt.subplots(2, 1, figsize=(8, 8))
for ax in a... | [
"matplotlib.pyplot.show",
"numpy.min",
"numpy.max",
"numpy.linspace",
"numpy.cos",
"matplotlib.pyplot.subplots"
] | [((192, 220), 'numpy.linspace', 'np.linspace', (['xmin', 'xmax', '(160)'], {}), '(xmin, xmax, 160)\n', (203, 220), True, 'import numpy as np\n'), ((273, 307), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(8, 8)'}), '(2, 1, figsize=(8, 8))\n', (285, 307), True, 'import matplotlib.pyplot as... |
# Authors: <NAME> <<EMAIL>>
# License: MIT
import mne
from mne.externals.pymatreader import read_mat
import numpy as np
from pathlib import Path
from .utils import get_epochs_to_trials
def get_montage_lemon(subject, root_path, montage_rel_path="EEG_MPILMBB_LEMON/EEG_Localizer_BIDS_ID/",
parse_... | [
"mne.channels.make_standard_montage",
"mne.channels.make_dig_montage",
"mne.Epochs",
"pathlib.Path",
"numpy.array",
"numpy.unique"
] | [((1418, 1469), 'mne.channels.make_standard_montage', 'mne.channels.make_standard_montage', (['"""standard_1020"""'], {}), "('standard_1020')\n", (1452, 1469), False, 'import mne\n'), ((2454, 2560), 'mne.Epochs', 'mne.Epochs', (['raw', 'events'], {'tmin': 'tmin', 'tmax': 'tmax', 'baseline': 'baseline', 'event_repeated'... |
"""
CSCC11 - Introduction to Machine Learning, Winter 2020, Assignment 3
<NAME>, <NAME>, <NAME>
This file visualizes the document dataset by reducing the dimensionality with PCA
"""
import matplotlib
import _pickle as pickle
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
... | [
"matplotlib.pyplot.figure",
"pca.PCA",
"numpy.unique",
"matplotlib.pyplot.show"
] | [((482, 496), 'pca.PCA', 'PCA', (['documents'], {}), '(documents)\n', (485, 496), False, 'from pca import PCA\n'), ((571, 599), 'numpy.unique', 'np.unique', (["dataset['labels']"], {}), "(dataset['labels'])\n", (580, 599), True, 'import numpy as np\n'), ((611, 623), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '... |
import copy
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sparse_ho.utils_cross_entropy import (
cross_entropy, grad_cross_entropy, accuracy)
class LogisticMulticlass():
"""Multiclass logistic loss.
Parameters
----------
idx_train: ndarray
ind... | [
"pandas.DataFrame",
"copy.deepcopy",
"numpy.log",
"numpy.zeros",
"sklearn.preprocessing.OneHotEncoder",
"numpy.exp",
"sparse_ho.utils_cross_entropy.accuracy",
"sparse_ho.utils_cross_entropy.cross_entropy",
"sparse_ho.utils_cross_entropy.grad_cross_entropy"
] | [((1099, 1126), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(False)'}), '(sparse=False)\n', (1112, 1126), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((2532, 2575), 'numpy.zeros', 'np.zeros', (['(self.n_features, self.n_classes)'], {}), '((self.n_features, self.n_classes))\... |
from mmdet.core import anchor, build_anchor_generator,build_assigner
import mmdet
import mmcv
import numpy as np
import time
import cv2 as cv
import torch
def show_anchor(input_shape_hw, stride, anchor_generator_cfg, random_n, select_n):
img = np.zeros(input_shape_hw, np.uint8)
feature_map = []
for s in st... | [
"mmcv.imshow_bboxes",
"mmdet.core.build_anchor_generator",
"cv2.waitKey",
"mmdet.core.build_assigner",
"numpy.zeros",
"torch.cat",
"cv2.imshow",
"torch.tensor"
] | [((249, 283), 'numpy.zeros', 'np.zeros', (['input_shape_hw', 'np.uint8'], {}), '(input_shape_hw, np.uint8)\n', (257, 283), True, 'import numpy as np\n'), ((426, 470), 'mmdet.core.build_anchor_generator', 'build_anchor_generator', (['anchor_generator_cfg'], {}), '(anchor_generator_cfg)\n', (448, 470), False, 'from mmdet... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import os
import pybullet as p
import pybullet_data
import math
import numpy as np
import random
from pybullet_object_models import ycb_objects
import time
from Load_Object_URDF import LoadObjectURDF
MAX_EPISODE_LEN = 20*100
class PandaEnv(... | [
"pybullet.resetSimulation",
"pybullet.calculateInverseKinematics",
"pybullet.computeViewMatrixFromYawPitchRoll",
"pybullet.resetDebugVisualizerCamera",
"pybullet.getBaseVelocity",
"pybullet.connect",
"os.path.join",
"pybullet.getLinkState",
"pybullet.getContactPoints",
"pybullet.setJointMotorContr... | [((436, 452), 'pybullet.connect', 'p.connect', (['p.GUI'], {}), '(p.GUI)\n', (445, 452), True, 'import pybullet as p\n'), ((461, 508), 'pybullet.configureDebugVisualizer', 'p.configureDebugVisualizer', (['p.COV_ENABLE_GUI', '(0)'], {}), '(p.COV_ENABLE_GUI, 0)\n', (487, 508), True, 'import pybullet as p\n'), ((517, 640)... |
# http://francescopochetti.com/fast-neural-style-transfer-sagemaker-deployment/
import os, sys
import json
import numpy as np
import tarfile
import random
import torch
# import inspect
# currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# parentdir = os.path.dirname(currentdir)
# s... | [
"os.listdir",
"json.dump",
"os.path.join",
"numpy.argmax",
"numpy.transpose",
"onnxruntime.InferenceSession",
"numpy.array",
"data_feeder.SigBatcher",
"torch.device",
"onnx.load",
"torch.onnx.export",
"data_feeder.Config",
"har_model.load_model",
"torch.from_numpy"
] | [((1118, 1138), 'data_feeder.Config', 'df.Config', ([], {'seed': 'seed'}), '(seed=seed)\n', (1127, 1138), True, 'import data_feeder as df\n'), ((1492, 1534), 'data_feeder.SigBatcher', 'df.SigBatcher', (['npy_files', 'cfg'], {'train': '(False)'}), '(npy_files, cfg, train=False)\n', (1505, 1534), True, 'import data_feede... |
import os
import gzip
import pickle
import numpy as np
from .train import onto
SRC_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'data/')
def get_embeddings():
fname = os.path.join(SRC_DIR, 'embeddings.npz')
embs = np.load(fname, allow_pickle=True)['embds'].item()
... | [
"os.path.realpath",
"os.path.join",
"numpy.load"
] | [((217, 256), 'os.path.join', 'os.path.join', (['SRC_DIR', '"""embeddings.npz"""'], {}), "(SRC_DIR, 'embeddings.npz')\n", (229, 256), False, 'import os\n'), ((362, 393), 'os.path.join', 'os.path.join', (['SRC_DIR', '"""go.obo"""'], {}), "(SRC_DIR, 'go.obo')\n", (374, 393), False, 'import os\n'), ((121, 147), 'os.path.r... |
import cv2
import numpy as np
img = np.random.randint(0, 256, size=[5, 5], dtype=np.uint8)
min = 100
max = 200
mask = cv2.inRange(img, min, max)
print("img=\n", img)
print("mask=\n", mask)
| [
"numpy.random.randint",
"cv2.inRange"
] | [((37, 91), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '[5, 5]', 'dtype': 'np.uint8'}), '(0, 256, size=[5, 5], dtype=np.uint8)\n', (54, 91), True, 'import numpy as np\n'), ((119, 145), 'cv2.inRange', 'cv2.inRange', (['img', 'min', 'max'], {}), '(img, min, max)\n', (130, 145), False, 'impor... |
#2次元Poisson方程式を、有限要素法で解く
#偏微分方程式: ∇・[p(x,y)∇u(x,y)] = f(x,y) (in Ω)
#境界条件: u(x,y)=alpha (on Γ1), du(x,y)/dx=beta (on Γ2)
import time #時刻を扱うライブラリ
import numpy as np #数値計算用
import scipy.spatial #ドロネー分割
import scipy.linalg #SciPyの線形計算ソルバー
import scipy.sparse #圧縮行列の処理
import scipy.sparse.linalg #圧縮行列用ソルバー
import ... | [
"numpy.absolute",
"numpy.empty",
"time.ctime",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.close",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.triplot",
"matplotlib.pyplot.text",
"matplotlib.pyplot.... | [((6561, 6578), 'numpy.sqrt', 'np.sqrt', (['leng_seg'], {}), '(leng_seg)\n', (6568, 6578), True, 'import numpy as np\n'), ((10079, 10135), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)', 'dpi': '(100)', 'facecolor': '"""#ffffff"""'}), "(figsize=(8, 6), dpi=100, facecolor='#ffffff')\n", (10089, 1013... |
import logging
from itertools import zip_longest
from typing import Iterator
import cv2
import numpy as np
import opencv_wrapper as orig_cvw
from more_itertools.recipes import grouper
from tqdm import tqdm
from skelshop.config import conf as config
from skelshop.skelgraphs.openpose import MODE_SKELS
from skelshop.ske... | [
"cv2.resize",
"skelshop.utils.vidreadwrapper.VidReadWrapper.put_text",
"cv2.polylines",
"more_itertools.recipes.grouper",
"skelshop.utils.geom.rnd",
"cv2.cvtColor",
"pygame.Rect",
"numpy.zeros",
"itertools.zip_longest",
"skelshop.utils.geom.rot",
"numpy.array",
"cv2.rectangle",
"opencv_wrapp... | [((530, 557), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (547, 557), False, 'import logging\n'), ((4306, 4421), 'numpy.array', 'np.array', (['[bbox_2pts[0], [bbox_2pts[0, 0], bbox_2pts[1, 1]], bbox_2pts[1], [bbox_2pts\n [1, 0], bbox_2pts[0, 1]]]'], {}), '([bbox_2pts[0], [bbox_2pts[... |
#! /usr/bin/env python
import rospy
import numpy as np
# Controller
from lenny_control.trajectory import TrajectoryController
if __name__ == '__main__':
np.set_printoptions(precision=4, suppress=True)
rospy.init_node('example_trajectory_controller')
controller = TrajectoryController()
# Set a random goal for ... | [
"rospy.loginfo",
"numpy.set_printoptions",
"rospy.init_node",
"lenny_control.trajectory.TrajectoryController"
] | [((157, 204), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(4)', 'suppress': '(True)'}), '(precision=4, suppress=True)\n', (176, 204), True, 'import numpy as np\n'), ((207, 255), 'rospy.init_node', 'rospy.init_node', (['"""example_trajectory_controller"""'], {}), "('example_trajectory_controller... |
import numpy as np
import matplotlib.pyplot as plt
import time
r,n = 0.3,50
p=1
u=1
t=0.02
def grid(r,n):
x = np.zeros(n+1)
rng=(0,1)
#gp sum
sum=0
for i in range(n):
sum = sum + pow(r,i)
x0 = (rng[1]-rng[0])/sum
x[0] = rng[0]
for i in range(n):
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.zeros",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((402, 417), 'numpy.zeros', 'np.zeros', (['(n + 1)'], {}), '(n + 1)\n', (410, 417), True, 'import numpy as np\n'), ((421, 436), 'numpy.zeros', 'np.zeros', (['(n + 1)'], {}), '(n + 1)\n', (429, 436), True, 'import numpy as np\n'), ((440, 455), 'numpy.zeros', 'np.zeros', (['(n + 1)'], {}), '(n + 1)\n', (448, 455), True,... |
from generic_neural_network import Dataset, Learner
import numpy as np
# Example with a train set from Google and a test set from the filesystem
IMAGE_DIMENSIONS = 400
# ====== Create Train Set =======
train_set = Dataset()
# 0 is cat, 1 is dog
train_set.add_category([0, 4000, 'happy face'])
train_set.add_category([1,... | [
"generic_neural_network.Dataset",
"numpy.asarray"
] | [((215, 224), 'generic_neural_network.Dataset', 'Dataset', ([], {}), '()\n', (222, 224), False, 'from generic_neural_network import Dataset, Learner\n'), ((631, 640), 'generic_neural_network.Dataset', 'Dataset', ([], {}), '()\n', (638, 640), False, 'from generic_neural_network import Dataset, Learner\n'), ((1164, 1185)... |
# -*- coding: utf-8 -*-
"""deep_dream.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1BXwGWfLaUvZYWHyYdire26VsLMRgXRKX
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import PIL.Image
import numpy as np
from scipy.ndimage.filters imp... | [
"scipy.ndimage.filters.gaussian_filter",
"numpy.zeros_like",
"inception5h.maybe_download",
"matplotlib.pyplot.show",
"random.randint",
"math.ceil",
"numpy.std",
"matplotlib.pyplot.imshow",
"numpy.float32",
"numpy.clip",
"inception5h.Inception5h",
"numpy.array",
"tensorflow.InteractiveSession... | [((361, 389), 'inception5h.maybe_download', 'inception5h.maybe_download', ([], {}), '()\n', (387, 389), False, 'import inception5h\n'), ((397, 422), 'inception5h.Inception5h', 'inception5h.Inception5h', ([], {}), '()\n', (420, 422), False, 'import inception5h\n'), ((9264, 9304), 'tensorflow.InteractiveSession', 'tf.Int... |
import numpy as np
import torch
import torch.nn.init as weight_init
from torch import nn
from torch.nn import Parameter
from src.models.samplers.arch_sampler import ArchSampler
class StaticArchGenerator(ArchSampler):
def __init__(self, initial_p, *args, **kwargs):
super().__init__(*args, **kwargs)
... | [
"torch.ones_like",
"numpy.log",
"torch.equal",
"torch.nn.init.constant_",
"torch.Tensor"
] | [((489, 530), 'torch.nn.init.constant_', 'weight_init.constant_', (['self.params', 'logit'], {}), '(self.params, logit)\n', (510, 530), True, 'import torch.nn.init as weight_init\n'), ((1307, 1341), 'torch.equal', 'torch.equal', (['distrib', '(distrib ** 2)'], {}), '(distrib, distrib ** 2)\n', (1318, 1341), False, 'imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.