code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from typing import Tuple, Optional
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
def beta_a_b_from_mode_concentration(mode: float, concentration: float) -> Tuple[float, float]:
"""
Computes the shape parameters, alpha and beta, of a beta distribution given its mode and concentration.
Para... | [
"matplotlib.pyplot.figure",
"numpy.sqrt"
] | [((1699, 1711), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1709, 1711), True, 'import matplotlib.pyplot as plt\n'), ((2621, 2633), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2631, 2633), True, 'import matplotlib.pyplot as plt\n'), ((2995, 3007), 'matplotlib.pyplot.figure', 'plt.figur... |
import os
import os.path as op
import sys
import json
import string
import numpy as np
import PropertySI as ps
#import tk
thispath = op.abspath(op.dirname(__file__))
datapath = op.join(thispath, 'PropData')
suffix = '.json'
pun = string.punctuation
current = ps.prop_names()
#Takes the dict and makes it key value pai... | [
"os.listdir",
"os.path.join",
"os.path.dirname",
"PropertySI.prop_names",
"numpy.vstack",
"numpy.genfromtxt",
"json.dump"
] | [((178, 207), 'os.path.join', 'op.join', (['thispath', '"""PropData"""'], {}), "(thispath, 'PropData')\n", (185, 207), True, 'import os.path as op\n'), ((260, 275), 'PropertySI.prop_names', 'ps.prop_names', ([], {}), '()\n', (273, 275), True, 'import PropertySI as ps\n'), ((145, 165), 'os.path.dirname', 'op.dirname', (... |
import os
import re
import glob
import numpy as np
import matplotlib.pylab as plt
import matplotlib
from scipy.spatial import ConvexHull
from scipy.interpolate import interp1d
from itertools import chain, count
from collections import defaultdict
from os import makedirs
from os.path import isdir, isfile,... | [
"itertools.chain",
"matplotlib.pylab.xlim",
"re.compile",
"scipy.interpolate.interp1d",
"numpy.array",
"matplotlib.pylab.show",
"numpy.arange",
"matplotlib.pylab.figure",
"matplotlib.pylab.legend",
"matplotlib.pylab.title",
"numpy.max",
"matplotlib.pylab.rcParams.update",
"numpy.min",
"num... | [((3885, 3912), 're.compile', 're.compile', (['"""\\\\S+\\\\s+.*=.*"""'], {}), "('\\\\S+\\\\s+.*=.*')\n", (3895, 3912), False, 'import re\n'), ((3931, 3959), 're.compile', 're.compile', (['""".*(m)=(\\\\d+).*"""'], {}), "('.*(m)=(\\\\d+).*')\n", (3941, 3959), False, 'import re\n'), ((3977, 4005), 're.compile', 're.comp... |
"""URBAN-SED Dataset Loader
.. admonition:: Dataset Info
:class: dropdown
URBAN-SED
=========
URBAN-SED (c) by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.
URBAN-SED is licensed under a Creative Commons Attribution 4.0 International License (CC BY 4.0).
You should have received a copy of the l... | [
"os.path.join",
"jams.load",
"soundata.core.copy_docs",
"soundata.core.docstring_inherit",
"numpy.array",
"soundata.download_utils.RemoteFileMetadata",
"os.path.basename",
"csv.reader",
"librosa.load"
] | [((12525, 12561), 'soundata.core.docstring_inherit', 'core.docstring_inherit', (['core.Dataset'], {}), '(core.Dataset)\n', (12547, 12561), False, 'from soundata import core\n'), ((9146, 9398), 'soundata.download_utils.RemoteFileMetadata', 'download_utils.RemoteFileMetadata', ([], {'filename': '"""URBAN-SED_v2.0.0.tar.g... |
# -*- coding: utf-8 -*-
########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# f... | [
"logging.getLogger",
"pandas.read_csv",
"numpy.save",
"numpy.savez",
"pandas.DataFrame",
"collections.namedtuple",
"sklearn.model_selection.train_test_split",
"pickle.load",
"os.path.isfile",
"numpy.isnan",
"neurocombat_sklearn.CombatModel",
"sklearn.linear_model.LinearRegression",
"pandas.i... | [((1061, 1169), 'collections.namedtuple', 'namedtuple', (['"""Item"""', "['train_input_path', 'test_input_path', 'train_metadata_path',\n 'test_metadata_path']"], {}), "('Item', ['train_input_path', 'test_input_path',\n 'train_metadata_path', 'test_metadata_path'])\n", (1071, 1169), False, 'from collections impor... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"mindspore.nn.CellList",
"mindspore.nn.Dense",
"mindspore.ops.Abs",
"numpy.arange",
"mindspore.ops.Select",
"mindspore.ops.ReduceSum",
"mindspore.ops.Square",
"numpy.random.uniform",
"mindspore.nn.ReLU",
"mindspore.ops.Ones",
"mindspore.ops.MatMul",
"mindspore.ops.shape",
"mindspore.nn.Batch... | [((1899, 1909), 'mindspore.ops.MatMul', 'P.MatMul', ([], {}), '()\n', (1907, 1909), True, 'from mindspore import ops as P\n'), ((1929, 1956), 'mindspore.ops.ReduceSum', 'P.ReduceSum', ([], {'keep_dims': '(True)'}), '(keep_dims=True)\n', (1940, 1956), True, 'from mindspore import ops as P\n'), ((3204, 3226), 'mindspore.... |
import os
import sys
import numpy as np
def get_malware_dataset(valid=False):
def get_monthly_data(file_path, num_feature=483):
'''Each row of `x_mat` is a datapoint.
It adds a constant one for another dimension at the end for the bias term.
Returns:
two numpy arrays, one... | [
"numpy.mean",
"numpy.where",
"numpy.log",
"numpy.array",
"numpy.concatenate",
"numpy.std"
] | [((7147, 7180), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)', 'keepdims': '(True)'}), '(X, axis=0, keepdims=True)\n', (7154, 7180), True, 'import numpy as np\n'), ((7215, 7247), 'numpy.std', 'np.std', (['X'], {'axis': '(0)', 'keepdims': '(True)'}), '(X, axis=0, keepdims=True)\n', (7221, 7247), True, 'import numpy as... |
import argparse
import logging
import os
import random
import math
import ransac.core as ransac
from ransac.models.conic_section import ConicSection
import cv2
import numpy as np
logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s [%(levelname)s] %(message)s')
parser = argparse.ArgumentParser()
parser.add... | [
"logging.basicConfig",
"cv2.min",
"os.path.exists",
"argparse.ArgumentParser",
"os.makedirs",
"cv2.line",
"os.path.join",
"logging.info",
"random.seed",
"ransac.core.Modeler",
"numpy.zeros",
"cv2.circle",
"cv2.cvtColor",
"cv2.Canny",
"cv2.imread",
"cv2.blur"
] | [((180, 278), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)-15s [%(levelname)s] %(message)s"""'}), "(level=logging.DEBUG, format=\n '%(asctime)-15s [%(levelname)s] %(message)s')\n", (199, 278), False, 'import logging\n'), ((284, 309), 'argparse.ArgumentParser'... |
"""
process_abundances
Author: <NAME>
Notes: script and functions to process stellar abundane output from a
simulation where chemical tags of stars are written to stdout. This
loops through all files that could contain this info in the given
directory (or files that match ... | [
"galaxy_analysis.utilities.utilities.species_from_fields",
"numpy.sum",
"yt.load",
"subprocess.call",
"numpy.genfromtxt",
"glob.glob"
] | [((1751, 1774), 'numpy.genfromtxt', 'np.genfromtxt', (['"""sf.dat"""'], {}), "('sf.dat')\n", (1764, 1774), True, 'import numpy as np\n'), ((2772, 2864), 'numpy.genfromtxt', 'np.genfromtxt', (["(directory + '/StellarAbundances.dat')"], {'dtype': '_ndtypes', 'invalid_raise': '(False)'}), "(directory + '/StellarAbundances... |
# -*- coding: utf-8 -*-
"""
Coil module
Created on Tue Jan 26 08:31:05 2021
@author: <NAME>
"""
from __future__ import annotations
from typing import List
import numpy as np
import os
import matplotlib.pyplot as plt
from ..segment.segment import Segment, Arc, Circle, Line
from ..wire.wire import Wire, WireRect, Wi... | [
"os.path.exists",
"matplotlib.pyplot.savefig",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.show"
] | [((784, 809), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (792, 809), True, 'import numpy as np\n'), ((819, 844), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (827, 844), True, 'import numpy as np\n'), ((854, 879), 'numpy.array', 'np.array', (['[0.0, 1.0,... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 21:20:48 2019
INSTITUTO FEDERAL DE EDUCAÇÃO, CIÊNCIA E TECNOLOGIA DO PÁRA - IFPA ANANINDEUA
@author:
Prof. Dr. <NAME>
Discentes:
<NAME>
<NAME>
Grupo de Pesquisa:
Gradiente de Mo... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"numpy.cos",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((786, 825), 'numpy.linspace', 'np.linspace', (['(-2 * np.pi)', '(2 * np.pi)', '(100)'], {}), '(-2 * np.pi, 2 * np.pi, 100)\n', (797, 825), True, 'import numpy as np\n'), ((853, 862), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (859, 862), True, 'import numpy as np\n'), ((1056, 1076), 'matplotlib.pyplot.plot', 'plt.p... |
import numpy as np
import argparse
# from rllab.envs.normalized_env import normalize
from maci.learners import MADDPG, MAVBAC, MASQL
from maci.misc.kernel import adaptive_isotropic_gaussian_kernel
from maci.replay_buffers import SimpleReplayBuffer
from maci.value_functions.sq_value_function import NNQFunction, NNJoin... | [
"maci.value_functions.sq_value_function.NNQFunction",
"maci.replay_buffers.SimpleReplayBuffer",
"maci.policies.StochasticNNConditionalPolicy",
"gtimer.reset",
"gtimer.rename_root",
"numpy.array",
"maci.policies.StochasticNNPolicy",
"copy.deepcopy",
"rllab.misc.logger.set_snapshot_dir",
"gtimer.sta... | [((790, 887), 'maci.replay_buffers.SimpleReplayBuffer', 'SimpleReplayBuffer', (['env.env_specs'], {'max_replay_buffer_size': '(1000000.0)', 'joint': 'joint', 'agent_id': 'i'}), '(env.env_specs, max_replay_buffer_size=1000000.0, joint=\n joint, agent_id=i)\n', (808, 887), False, 'from maci.replay_buffers import Simpl... |
import os
import torch
import torch.nn as nn
import struct
import numpy as np
import json
from time import perf_counter
from pprint import pprint
from lstm_rnnt_dec import PluginLstmRnntDec
start_setup_time = perf_counter()
# Setup.
output_bin = os.environ.get('CK_OUT_RAW_DATA', 'tmp-ck-output.bin')
output_json = ou... | [
"os.path.exists",
"pprint.pprint",
"torch.load",
"json.dumps",
"os.environ.get",
"time.perf_counter",
"torch.from_numpy",
"lstm_rnnt_dec.PluginLstmRnntDec",
"torch.zeros",
"numpy.random.RandomState"
] | [((211, 225), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (223, 225), False, 'from time import perf_counter\n'), ((249, 303), 'os.environ.get', 'os.environ.get', (['"""CK_OUT_RAW_DATA"""', '"""tmp-ck-output.bin"""'], {}), "('CK_OUT_RAW_DATA', 'tmp-ck-output.bin')\n", (263, 303), False, 'import os\n'), ((368,... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | [
"numpy.mean",
"numpy.random.default_rng",
"numpy.array",
"numpy.apply_along_axis",
"numpy.concatenate",
"copy.deepcopy",
"pandas.concat"
] | [((2802, 2836), 'numpy.random.default_rng', 'np.random.default_rng', (['random_seed'], {}), '(random_seed)\n', (2823, 2836), True, 'import numpy as np\n'), ((12769, 12833), 'numpy.concatenate', 'np.concatenate', (['(treated_covariates, control_covariates)'], {'axis': '(1)'}), '((treated_covariates, control_covariates),... |
"""
Example inferring multiple exponential decay models arranged into a
4D voxelwise image.
This example uses the main() interface as used by the command line
application to simplify running the inference and saving the output
"""
import sys
import numpy as np
import nibabel as nib
from vaby_avb import run
import va... | [
"numpy.random.normal",
"numpy.identity",
"numpy.sqrt",
"numpy.array",
"vaby_avb.run",
"vaby.get_model_class"
] | [((599, 623), 'numpy.sqrt', 'np.sqrt', (['NOISE_VAR_TRUTH'], {}), '(NOISE_VAR_TRUTH)\n', (606, 623), True, 'import numpy as np\n'), ((1800, 1866), 'vaby_avb.run', 'run', (['"""data_exp_noisy.nii.gz"""', '"""exp"""', '"""exps_example_out"""'], {}), "('data_exp_noisy.nii.gz', 'exp', 'exps_example_out', **options)\n", (18... |
import math
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt
import matplotlib.gridspec as gdsc
class concreteSection:
def __init__(self,sct,units='mm'):
'''
Imports section.
Parameters
----------
sct : Section Object
... | [
"numpy.array",
"numpy.arange",
"numpy.where",
"matplotlib.pyplot.plot",
"numpy.asarray",
"numpy.linspace",
"numpy.concatenate",
"numpy.tile",
"numpy.geomspace",
"numpy.sign",
"numpy.interp",
"scipy.optimize.root",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"numpy.absolute",
... | [((3792, 3905), 'numpy.interp', 'np.interp', (['self.steelHeights', '[self.concreteHeights[0], self.concreteHeights[-1]]', '[bottomStrain, topStrain]'], {}), '(self.steelHeights, [self.concreteHeights[0], self.concreteHeights\n [-1]], [bottomStrain, topStrain])\n', (3801, 3905), True, 'import numpy as np\n'), ((3950... |
"""
Detection of trends: Given prices of X previous hours, will price increase or decrease Y% amount within next Z hours?
(1) X = previous prices
(2) y = next prices
(3) X_norm = X \ X[0] - 1 # Normalize X
(4) y_norm = y \ X[0] - 1 # Normalize y
(5) Given X_norm, which decision should we take if we know y_norm ?
(5.... | [
"torch.manual_seed",
"coinpy.PredictPriceDataset",
"torch.nn.L1Loss",
"matplotlib.pyplot.plot",
"torch.from_numpy",
"torch.no_grad",
"coinpy.DataFramesHolder",
"numpy.zeros",
"numpy.array",
"numpy.random.seed",
"torch.nn.Linear",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.scatter",
... | [((1123, 1143), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1137, 1143), True, 'import numpy as np\n'), ((1144, 1167), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1161, 1167), False, 'import torch\n'), ((2059, 2081), 'matplotlib.pyplot.plot', 'plt.plot', (['d'], {'alph... |
import cvlog as log
import cv2
import numpy as np
from .utils import read_file, remove_dirs, get_html
def test_log_image():
remove_dirs('log/')
img = cv2.imread("tests/data/orange.png")
log.set_mode(log.Mode.LOG)
log.image(log.Level.ERROR, img)
logitem = get_html('log/cvlog.html').select('.log-list... | [
"cv2.threshold",
"cv2.medianBlur",
"cvlog.hough_circles",
"cvlog.threshold",
"cvlog.hough_lines",
"numpy.array",
"cvlog.image",
"cv2.HoughLines",
"cv2.ORB_create",
"cv2.cvtColor",
"cvlog.keypoints",
"cv2.findContours",
"cvlog.set_mode",
"cv2.Canny",
"cv2.imread",
"cvlog.contours",
"c... | [((159, 194), 'cv2.imread', 'cv2.imread', (['"""tests/data/orange.png"""'], {}), "('tests/data/orange.png')\n", (169, 194), False, 'import cv2\n'), ((199, 225), 'cvlog.set_mode', 'log.set_mode', (['log.Mode.LOG'], {}), '(log.Mode.LOG)\n', (211, 225), True, 'import cvlog as log\n'), ((230, 261), 'cvlog.image', 'log.imag... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"model_utils.moxing_adapter.moxing_wrapper",
"model_utils.device_adapter.get_device_id",
"numpy.ones",
"mindspore.export",
"mindspore.context.set_context",
"os.path.join",
"src.utils.init_net",
"os.path.basename"
] | [((1048, 1133), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'device_target': 'config.device_target'}), '(mode=context.GRAPH_MODE, device_target=config.device_target\n )\n', (1067, 1133), False, 'from mindspore import Tensor, export, context\n'), ((1240, 1256), 'model_u... |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
from math import pi, log
import numpy as np
from mvc.observers import ListObserver
from mvc.models.properties import (
StringProperty, SignalMixin, ReadOnlyMixin, FloatPro... | [
"numpy.radians",
"mvc.models.properties.BoolProperty",
"pyxrd.generic.utils.not_none",
"numpy.asanyarray",
"math.log",
"numpy.array",
"mvc.models.properties.StringProperty",
"pyxrd.calculations.peak_detection.peakdetect",
"mvc.observers.ListObserver",
"numpy.max",
"mvc.models.properties.LabeledP... | [((982, 1002), 'pyxrd.generic.io.storables.register', 'storables.register', ([], {}), '()\n', (1000, 1002), False, 'from pyxrd.generic.io import storables, Storable\n'), ((2025, 2171), 'mvc.models.properties.StringProperty', 'StringProperty', ([], {'default': '""""""', 'text': '"""Sample"""', 'visible': '(True)', 'pers... |
import pyaudio
import math, random
import numpy as np
import find_peaks as fp
from search_tree import SearchTree
from pydub import AudioSegment
import time
END = 10000 #Sample for 10 seconds
THRESH = 0.6
def match(audio_name, mv_name):
audio_file = AudioSegment.from_file(audio_name)[5000:(END + 5000)]
mv_f... | [
"random.shuffle",
"math.sqrt",
"search_tree.SearchTree",
"pydub.AudioSegment.from_file",
"numpy.frombuffer",
"time.time",
"find_peaks.get_sparse_map"
] | [((326, 357), 'pydub.AudioSegment.from_file', 'AudioSegment.from_file', (['mv_name'], {}), '(mv_name)\n', (348, 357), False, 'from pydub import AudioSegment\n'), ((374, 415), 'numpy.frombuffer', 'np.frombuffer', (['audio_file._data', 'np.int16'], {}), '(audio_file._data, np.int16)\n', (387, 415), True, 'import numpy as... |
import torch
from finetuning import TweetBatch, weights
from tqdm import tqdm, trange
import os
import numpy as np
from sklearn.metrics import mean_squared_error
import argparse
import pdb
from transformers import BertForSequenceClassification
def evaluate(args, model, eval_dataloader, wi, device, prefix="")... | [
"torch.cuda.device_count",
"torch.cuda.is_available",
"finetuning.TweetBatch",
"os.path.exists",
"argparse.ArgumentParser",
"finetuning.weights",
"numpy.squeeze",
"sklearn.metrics.mean_squared_error",
"transformers.BertForSequenceClassification.from_pretrained",
"torch.device",
"torch.cuda.get_d... | [((2919, 3059), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test Bert finetuned for a regression task, to predict the tweet counts from the embbedings."""'}), "(description=\n 'Test Bert finetuned for a regression task, to predict the tweet counts from the embbedings.'\n )\n", (... |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import numpy as np
from app import octopusData, client, linePlot
app = FastAPI()
origins = ["http://localhost:3000", "http://127.0.0.1:3000"]
# assumes a suitable web server, e.g. "python -m http.server 9000"
app.add_... | [
"numpy.multiply",
"fastapi.FastAPI",
"pandas.Timestamp.now",
"pandas.Timedelta",
"app.octopusData.e_consumption.index.max",
"app.octopusData.update",
"app.octopusData.g_consumption.index.max",
"app.linePlot"
] | [((171, 180), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (178, 180), False, 'from fastapi import FastAPI\n'), ((497, 523), 'app.octopusData.update', 'octopusData.update', (['client'], {}), '(client)\n', (515, 523), False, 'from app import octopusData, client, linePlot\n'), ((874, 900), 'app.octopusData.update', 'o... |
from os import path
import numpy as np
import pandas as pd
import impyute as impy
from matplotlib import pyplot as plt
plt.close("all")
data_path = 'data'
# read geographic information for capitals
municipios = pd.read_csv(path.join(data_path, 'population_capitals.csv'))
# population density
municipios['density'] = m... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.close",
"numpy.array",
"impyute.em",
"pandas.offsets.MonthBegin",
"pandas.DataFrame",
"pandas.date_range",
"matplotlib.pyplot.show"
] | [((119, 135), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (128, 135), True, 'from matplotlib import pyplot as plt\n'), ((1276, 1296), 'impyute.em', 'impy.em', (['data_output'], {}), '(data_output)\n', (1283, 1296), True, 'import impyute as impy\n'), ((1312, 1372), 'pandas.DataFrame', 'pd.D... |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import mean_squared_error
from agents.stew.utils import create_diff_matrix
import numpy as np
import gym
from agents.EwR... | [
"numpy.argmax",
"agents.EwRegularizer.KerasEWRegularizer",
"numpy.exp",
"numpy.array",
"tensorflow.keras.optimizers.Adam",
"numpy.random.uniform",
"gym.make",
"numpy.save",
"numpy.random.shuffle"
] | [((4269, 4292), 'gym.make', 'gym.make', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (4277, 4292), False, 'import gym\n'), ((5926, 5955), 'numpy.save', 'np.save', (['"""hello"""', 'all_returns'], {}), "('hello', all_returns)\n", (5933, 5955), True, 'import numpy as np\n'), ((4825, 4850), 'numpy.array', 'np.array',... |
"""
Functions associated with a molecule.
"""
from .measure import calculate_distance
from .atom_data import atomic_weights
import numpy as np
def build_bond_list(coordinates, max_bond=1.5, min_bond=0):
"""Return the bonds in a system based on bond distance criteria.
The pairwise distance between atoms is c... | [
"numpy.array"
] | [((2536, 2561), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (2544, 2561), True, 'import numpy as np\n')] |
from typing import Union
import numpy as np
def bspline_basis_manual(
knot_vector_t: Union[list, tuple],
knot_i: int = 0,
p: int = 0,
nti: int = 1,
verbose: bool = False,
):
"""Computes the B-spline polynomial basis,
currently limited to degree constant, linear, or quadratic.
Arg... | [
"numpy.array",
"numpy.arange"
] | [((2803, 2814), 'numpy.array', 'np.array', (['t'], {}), '(t)\n', (2811, 2814), True, 'import numpy as np\n'), ((2265, 2284), 'numpy.array', 'np.array', (['knots_rhs'], {}), '(knots_rhs)\n', (2273, 2284), True, 'import numpy as np\n'), ((2287, 2306), 'numpy.array', 'np.array', (['knots_lhs'], {}), '(knots_lhs)\n', (2295... |
#!/usr/bin/env python
"""
Compute a density raster for input geometries or sum a property.
"""
from __future__ import division
import affine
import click
import fiona as fio
import numpy as np
import rasterio as rio
import rasterio.dtypes
from rasterio.features import rasterize
import str2type.ext
def cb_res(ctx... | [
"click.argument",
"click.option",
"rasterio.open",
"affine.Affine.from_gdal",
"rasterio.features.rasterize",
"numpy.zeros",
"fiona.open",
"click.BadParameter",
"click.command"
] | [((1695, 1710), 'click.command', 'click.command', ([], {}), '()\n', (1708, 1710), False, 'import click\n'), ((1712, 1736), 'click.argument', 'click.argument', (['"""infile"""'], {}), "('infile')\n", (1726, 1736), False, 'import click\n'), ((1738, 1763), 'click.argument', 'click.argument', (['"""outfile"""'], {}), "('ou... |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from torch.nn import Softmax2d
import torch
from os.path import basename
class plt_loss(object):
def __call__(self, train_loss, valid_loss, figsize=(10, 10), savefig=None, display=False):
train_loss=np.array(train_loss)
v... | [
"matplotlib.pyplot.ylabel",
"numpy.array",
"numpy.arange",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.linspace",
"matplotlib.cm.ScalarMappable",
"numpy.argmax",
"torch.nn.Softmax2d",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.sh... | [((290, 310), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (298, 310), True, 'import numpy as np\n'), ((330, 350), 'numpy.array', 'np.array', (['valid_loss'], {}), '(valid_loss)\n', (338, 350), True, 'import numpy as np\n'), ((363, 390), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '... |
#!/usr/bin/env python
"""
This module contains dyPolyChord's high-level functionality for
performing dynamic nested sampling calculations. This is done using the
algorithm described in Appendix F of "Dynamic nested sampling: an
improved algorithm for parameter estimation and evidence calculation"
(Higson et al., 2019).... | [
"numpy.where",
"os.path.join",
"numpy.asarray",
"os.path.isfile",
"copy.deepcopy",
"sys.stdout.flush",
"traceback.print_exc",
"os.remove"
] | [((8355, 8428), 'os.path.join', 'os.path.join', (["settings_dict_in['base_dir']", "settings_dict_in['file_root']"], {}), "(settings_dict_in['base_dir'], settings_dict_in['file_root'])\n", (8367, 8428), False, 'import os\n'), ((15643, 15674), 'copy.deepcopy', 'copy.deepcopy', (['settings_dict_in'], {}), '(settings_dict_... |
#!/usr/bin/env python
# coding=utf-8
import numpy as np
import sys
import lmoments as lmom
years = sys.argv[1]
yeare = sys.argv[2]
ysize = int(sys.argv[3])
xsize = int(sys.argv[4])
outdir = sys.argv[5]
var = sys.argv[6]
rp = sys.argv[7]
FUNC = sys.argv[8]
rivhgt = np.fromfile(outdir+'/map/rivhgt.bin', np.float32).res... | [
"lmoments.quagum",
"numpy.fromfile",
"lmoments.quape3",
"lmoments.quawak",
"lmoments.quagev",
"lmoments.quagam",
"numpy.zeros",
"lmoments.quawei"
] | [((349, 391), 'numpy.zeros', 'np.zeros', (['(ysize, xsize)'], {'dtype': 'np.float64'}), '((ysize, xsize), dtype=np.float64)\n', (357, 391), True, 'import numpy as np\n'), ((267, 318), 'numpy.fromfile', 'np.fromfile', (["(outdir + '/map/rivhgt.bin')", 'np.float32'], {}), "(outdir + '/map/rivhgt.bin', np.float32)\n", (27... |
import numpy as np
from scipy.optimize import brentq
from yt.fields.field_detector import \
FieldDetector
from pygrackle import \
add_grackle_fields, \
FluidContainer, \
chemistry_data
from pygrackle.yt_fields import \
_data_to_fc, \
_get_needed_fields
from yt.config import ytcfg
from yt.funcs ... | [
"yt.funcs.get_pbar",
"scipy.optimize.brentq",
"pygrackle.add_grackle_fields",
"numpy.log",
"yt.funcs.DummyProgressBar",
"pygrackle.yt_fields._get_needed_fields",
"pygrackle.yt_fields._data_to_fc",
"numpy.exp",
"numpy.zeros",
"yt.config.ytcfg.getboolean",
"pygrackle.FluidContainer",
"yt.config.... | [((439, 476), 'pygrackle.yt_fields._get_needed_fields', '_get_needed_fields', (['fc.chemistry_data'], {}), '(fc.chemistry_data)\n', (457, 476), False, 'from pygrackle.yt_fields import _data_to_fc, _get_needed_fields\n'), ((908, 926), 'numpy.log', 'np.log', (['ct_0[calc]'], {}), '(ct_0[calc])\n', (914, 926), True, 'impo... |
#!/usr/bin/env python3
import numpy as np
#import scipy.linalg
def vector_lengths(a):
squared = a**2
euclidean = squared.sum(axis=1)
return np.sqrt(euclidean)
def main():
a = np.random.randint(0, 10, (3, 4))
print(a)
print(vector_lengths(a))
if __name__ == "__main__":
main()
| [
"numpy.random.randint",
"numpy.sqrt"
] | [((159, 177), 'numpy.sqrt', 'np.sqrt', (['euclidean'], {}), '(euclidean)\n', (166, 177), True, 'import numpy as np\n'), ((199, 231), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', '(3, 4)'], {}), '(0, 10, (3, 4))\n', (216, 231), True, 'import numpy as np\n')] |
from copy import copy
from typing import Union
import numpy as np
from fedot.core.data.data import InputData, OutputData
from fedot.core.data.multi_modal import MultiModalData
from fedot.core.operations.evaluation.operation_implementations.data_operations.ts_transformations import ts_to_table
from fedot.core.reposito... | [
"numpy.mean",
"numpy.isclose",
"numpy.hstack",
"fedot.core.data.multi_modal.MultiModalData",
"fedot.core.operations.evaluation.operation_implementations.data_operations.ts_transformations.ts_to_table",
"numpy.array",
"copy.copy",
"numpy.arange"
] | [((7328, 7349), 'copy.copy', 'copy', (['train_predicted'], {}), '(train_predicted)\n', (7332, 7349), False, 'from copy import copy\n'), ((9336, 9357), 'copy.copy', 'copy', (['train_predicted'], {}), '(train_predicted)\n', (9340, 9357), False, 'from copy import copy\n'), ((9384, 9404), 'numpy.array', 'np.array', (['all_... |
import os
from itertools import chain
import time
import numpy as np
from cffi import FFI
# The datatype that we use for computation. We always convert the given data
# to a double array to make sure we have enough bits for precise computation.
_double = np.dtype('d')
_ffi = FFI()
_ffi.cdef(r"""
void train(cons... | [
"itertools.chain",
"numpy.random.rand",
"cffi.FFI",
"numpy.exp",
"os.path.dirname",
"numpy.array",
"numpy.dtype",
"time.time"
] | [((257, 270), 'numpy.dtype', 'np.dtype', (['"""d"""'], {}), "('d')\n", (265, 270), True, 'import numpy as np\n'), ((280, 285), 'cffi.FFI', 'FFI', ([], {}), '()\n', (283, 285), False, 'from cffi import FFI\n'), ((2042, 2077), 'numpy.array', 'np.array', (['a_noise'], {'dtype': 'np.float64'}), '(a_noise, dtype=np.float64)... |
import re
import string
from collections import defaultdict
import numpy as np
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
from scipy import linalg
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing... | [
"scipy.linalg.eigh",
"nltk.tokenize.TweetTokenizer",
"nltk.corpus.stopwords.words",
"nltk.stem.PorterStemmer",
"numpy.squeeze",
"numpy.argsort",
"numpy.exp",
"numpy.zeros",
"numpy.dot",
"collections.defaultdict",
"numpy.array",
"re.sub",
"numpy.cov"
] | [((433, 448), 'nltk.stem.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (446, 448), False, 'from nltk.stem import PorterStemmer\n'), ((473, 499), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (488, 499), False, 'from nltk.corpus import stopwords\n'), ((555, 583), 're.su... |
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV),
# copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
import unittest
import numpy as np
import matplotlib.pyplot as plt
import logging
from p3iv_utils_... | [
"logging.getLogger",
"logging.basicConfig",
"numpy.random.rand",
"numpy.asarray",
"numpy.array",
"numpy.linspace",
"numpy.sum",
"unittest.main",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((366, 385), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (383, 385), False, 'import logging\n'), ((476, 490), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (488, 490), True, 'import matplotlib.pyplot as plt\n'), ((586, 596), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (594... |
#-----------------------------------------------------------------------------
# Copyright (c) 2014, <NAME>
# All rights reserved.
#
# Distributed under the terms of the BSD 3-Clause ("BSD New") license.
#
# The full license is in the LICENSE file, distributed with this software.
#--------------------------------------... | [
"numpy.log2",
"numpy.zeros",
"numpy.asarray",
"numpy.empty"
] | [((943, 956), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (953, 956), True, 'import numpy as np\n'), ((1137, 1163), 'numpy.zeros', 'np.zeros', (['upshape', 'x.dtype'], {}), '(upshape, x.dtype)\n', (1145, 1163), True, 'import numpy as np\n'), ((1413, 1426), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
""" Simple 1 input mixer node. This takes the input of M channels, and produces
an output of N channels, using simple matrix mulitplication.
"""
import labgraph as lg
import numpy as np
from ...messages.generic_signal_sample import Sig... | [
"numpy.dot",
"labgraph.publisher",
"labgraph.util.LabgraphError",
"labgraph.Topic",
"labgraph.subscriber"
] | [((514, 543), 'labgraph.Topic', 'lg.Topic', (['SignalSampleMessage'], {}), '(SignalSampleMessage)\n', (522, 543), True, 'import labgraph as lg\n'), ((567, 596), 'labgraph.Topic', 'lg.Topic', (['SignalSampleMessage'], {}), '(SignalSampleMessage)\n', (575, 596), True, 'import labgraph as lg\n'), ((603, 633), 'labgraph.su... |
# -*- coding: utf-8 -*-
###############################################################################
###############################################################################
## ##
## _ ___ ___ ___ ___ ___ ... | [
"source.rotate.diurnal_dot",
"numpy.cross",
"source.rotate.nutation",
"numpy.array",
"numpy.zeros",
"source.rotate.precession",
"source.rotate.diurnal",
"numpy.linalg.norm",
"source.rotate.polewander"
] | [((2580, 2591), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (2588, 2591), True, 'import numpy as np\n'), ((3388, 3408), 'source.rotate.precession', 'rotate.precession', (['t'], {}), '(t)\n', (3405, 3408), False, 'from source import rotate\n'), ((3443, 3461), 'source.rotate.nutation', 'rotate.nutation', (['t'], {... |
# Original code from: https://github.com/isayev/ReLeaSE
import numpy as np
import torch
from irelease.utils import read_smi_file, tokenize, read_object_property_file, seq2tensor, pad_sequences
class GeneratorData(object):
def __init__(self, training_data_path, tokens=None, start_token='<',
end... | [
"irelease.utils.pad_sequences",
"irelease.utils.seq2tensor",
"irelease.utils.read_smi_file",
"irelease.utils.tokenize",
"numpy.random.randint",
"torch.cuda.is_available",
"torch.tensor",
"numpy.random.seed",
"irelease.utils.read_object_property_file"
] | [((2305, 2360), 'irelease.utils.read_object_property_file', 'read_object_property_file', (['training_data_path'], {}), '(training_data_path, **kwargs)\n', (2330, 2360), False, 'from irelease.utils import read_smi_file, tokenize, read_object_property_file, seq2tensor, pad_sequences\n'), ((2777, 2804), 'irelease.utils.to... |
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 50)
y = np.cos(np.linspace(0, 0.5 * np.pi))
plt.title("curve")
plt.grid()
plt.xlim(-1, 1)
plt.ylim(-1.05, +1.05)
plt.plot(x, y)
plt.show()
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show"
] | [((56, 78), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(50)'], {}), '(-1, 1, 50)\n', (67, 78), True, 'import numpy as np\n'), ((120, 138), 'matplotlib.pyplot.title', 'plt.title', (['"""curve"""'], {}), "('curve')\n", (129, 138), True, 'import matplotlib.pyplot as plt\n'), ((139, 149), 'matplotlib.pyplot.grid', ... |
"""Convenience functions for writing netcdf files."""
import fnmatch
import logging
import os
import iris
import numpy as np
from .iris_helpers import unify_1d_cubes
logger = logging.getLogger(__name__)
VAR_KEYS = [
'long_name',
'units',
]
NECESSARY_KEYS = VAR_KEYS + [
'dataset',
'filename',
'pr... | [
"logging.getLogger",
"numpy.ma.array",
"iris.save",
"iris.coords.AuxCoord",
"os.path.join",
"iris.load_cube",
"fnmatch.filter",
"os.walk"
] | [((178, 205), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (195, 205), False, 'import logging\n'), ((3416, 3449), 'fnmatch.filter', 'fnmatch.filter', (['all_files', '"""*.nc"""'], {}), "(all_files, '*.nc')\n", (3430, 3449), False, 'import fnmatch\n'), ((6529, 6580), 'iris.coords.AuxCoor... |
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model\chatbot_model.h5')
import json
import random
import cgi
import cgitb
from datetime import datetime
intents = json.loads(open('chat... | [
"cgi.FieldStorage",
"keras.models.load_model",
"random.choice",
"nltk.word_tokenize",
"nltk.stem.WordNetLemmatizer",
"numpy.array",
"datetime.datetime.now",
"cgitb.enable"
] | [((65, 84), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (82, 84), False, 'from nltk.stem import WordNetLemmatizer\n'), ((163, 208), 'keras.models.load_model', 'load_model', (['"""chatbot_model\\\\chatbot_model.h5"""'], {}), "('chatbot_model\\\\chatbot_model.h5')\n", (173, 208), False, 'from ke... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"numpy.fromfile",
"argparse.ArgumentParser",
"mindspore.context.set_context",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"numpy.load",
"time.time",
"sklearn.svm.SVC"
] | [((1079, 1123), 'numpy.load', 'np.load', (['label_path_train'], {'allow_pickle': '(True)'}), '(label_path_train, allow_pickle=True)\n', (1086, 1123), True, 'import numpy as np\n'), ((1145, 1188), 'numpy.load', 'np.load', (['label_path_test'], {'allow_pickle': '(True)'}), '(label_path_test, allow_pickle=True)\n', (1152,... |
import socket
import numpy as np
from select import select
import threading
import time
def clamp(x,min,max):
"Clamps the value x between `min` and `max` "
if x < min:
return min
elif x > max:
return max
else:
return x
def check_server(ip='192.168.127.12', port=23, timeout=3)... | [
"threading.Thread.__init__",
"select.select",
"socket.socket",
"time.monotonic",
"time.sleep",
"numpy.zeros"
] | [((785, 834), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (798, 834), False, 'import socket\n'), ((1773, 1812), 'numpy.zeros', 'np.zeros', (['(fps, self.packlen)', 'np.uint8'], {}), '((fps, self.packlen), np.uint8)\n', (1781, 1812), True, '... |
import numpy as np
import matplotlib.pyplot as plt
import uncertainties
from scipy.signal import find_peaks
from scipy.optimize import curve_fit
import scipy.constants as sc
import scipy.integrate as integrate
from uncertainties import ufloat
from uncertainties import unumpy as unp
from uncertainties.unumpy import nomi... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"numpy.array",
"uncertainties.ufloat",
"numpy.genfromtxt",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"numpy.asarray",
"numpy.exp",
"numpy.linspace",
"uncertainties.unumpy.nominal_values",
"scipy.signal.find_peaks",
"uncertainties.unumpy.std_devs",
... | [((547, 614), 'numpy.genfromtxt', 'np.genfromtxt', (['"""2018-12-10_Nitschke_Pape/Probe_21.Spe"""'], {'unpack': '(True)'}), "('2018-12-10_Nitschke_Pape/Probe_21.Spe', unpack=True)\n", (560, 614), True, 'import numpy as np\n'), ((634, 677), 'numpy.genfromtxt', 'np.genfromtxt', (['"""EuropiumQ.txt"""'], {'unpack': '(True... |
import scipy.stats as ss
import numpy as np
def read_data(path):
file = open(path)
lines = file.readlines()
file.close()
dic = {}
for line in lines[1:]:
sl = line.split(',')
pid = int(sl[0].split('_')[0])
data_len = float(sl[1])
dic[pid] = data_len
return dic
def main():
no_data = read_... | [
"BCI.gen_kv_idx",
"numpy.transpose",
"matplotlib.pyplot.savefig",
"sklearn.discriminant_analysis.LinearDiscriminantAnalysis",
"numpy.ones",
"numpy.log",
"scipy.signal.butter",
"numpy.array",
"numpy.zeros",
"scipy.stats.ttest_rel",
"matplotlib.pyplot.bar",
"scipy.signal.lfilter",
"numpy.conca... | [((1094, 1115), 'scipy.stats.mannwhitneyu', 'ss.mannwhitneyu', (['x', 'y'], {}), '(x, y)\n', (1109, 1115), True, 'import scipy.stats as ss\n'), ((1149, 1167), 'scipy.stats.ttest_rel', 'ss.ttest_rel', (['x', 'y'], {}), '(x, y)\n', (1161, 1167), True, 'import scipy.stats as ss\n'), ((1873, 1905), 'numpy.concatenate', 'np... |
import numpy as np
from bp.Model import Model
# ANN 经典 2 -> 3 -> 6 -> 1
# x = np.linspace(-1,1,20)
x = np.array([[1, 2], [2, 3], [3, 3], [1, 4], [-1, -2], [-1, -1], [-2, -3], [-3, -2]]).T
y = np.array([[0, 0, 0, 0, 1, 1, 1, 1]])
model = Model(x, y,inputType='normal')
model.addLayer(3, 'sigmoid', False)
model.addLayer(... | [
"numpy.array",
"bp.Model.Model"
] | [((193, 229), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 1, 1, 1, 1]]'], {}), '([[0, 0, 0, 0, 1, 1, 1, 1]])\n', (201, 229), True, 'import numpy as np\n'), ((238, 269), 'bp.Model.Model', 'Model', (['x', 'y'], {'inputType': '"""normal"""'}), "(x, y, inputType='normal')\n", (243, 269), False, 'from bp.Model import Model\... |
import math
import numpy as np
import matplotlib.pyplot as plt
from control.timeresp import step_info
from control.matlab import tf, series, feedback, step
class RF:
def calculo(mp, ta, u, tempo, numerador, denominador, flag):
var = (math.log(mp)/-math.pi) ** 2
qsi = math.sqrt(var/(1+var))... | [
"numpy.radians",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.title",
"control.timeresp.step_info",
"control.matlab.series",
"matplotlib.pyplot.ylabel",
"numpy.absolute",
"matplotlib.pyplot.plot",
"control.matlab.tf",
"math.sqrt",
"control.matlab.step",
"matplotlib.pyplot.xlabel",
"math.log"... | [((298, 324), 'math.sqrt', 'math.sqrt', (['(var / (1 + var))'], {}), '(var / (1 + var))\n', (307, 324), False, 'import math\n'), ((549, 568), 'numpy.absolute', 'np.absolute', (['g_jwcg'], {}), '(g_jwcg)\n', (560, 568), True, 'import numpy as np\n'), ((823, 851), 'control.matlab.tf', 'tf', (['[kp[-1], ki[-1]]', '[1, 0]'... |
import os
import uuid
import time
import numpy as np
import tensorflow as tf
import external.luodong.Model2bin as mem_to_bin
mod_uuid = uuid.uuid4()
TODAY = time.strftime("%Y%m%d")
model_ids = list(np.arange(22))
mem_path = r'/home/hangz/TF_graphs/unit_test/DTLN_keras/converted_model/'
os.makedirs(os.path.join(mem_pa... | [
"external.luodong.Model2bin.auto_create_bin",
"time.strftime",
"os.path.join",
"uuid.uuid4",
"numpy.arange"
] | [((138, 150), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (148, 150), False, 'import uuid\n'), ((159, 182), 'time.strftime', 'time.strftime', (['"""%Y%m%d"""'], {}), "('%Y%m%d')\n", (172, 182), False, 'import time\n'), ((350, 472), 'external.luodong.Model2bin.auto_create_bin', 'mem_to_bin.auto_create_bin', ([], {'mem... |
# <NAME> <<<EMAIL>>>.
# A DataProjector is an object that projects data object to a latent space
# At the moment we will use LSI types of methdos to do this
import numpy
from gensim import corpora, models, similarities,matutils
import numpy as np
import os.path
import time
import scipy.sparse
from pathlib import Path
... | [
"gensim.models.LsiModel",
"numpy.dot",
"numpy.zeros",
"gensim.matutils.corpus2csc",
"time.time",
"gensim.models.TfidfModel"
] | [((7676, 7700), 'numpy.zeros', 'np.zeros', (['self.num_terms'], {}), '(self.num_terms)\n', (7684, 7700), True, 'import numpy as np\n'), ((8069, 8115), 'numpy.dot', 'np.dot', (['new_doc_fv_normalized', 'self.term_f_mat'], {}), '(new_doc_fv_normalized, self.term_f_mat)\n', (8075, 8115), True, 'import numpy as np\n'), ((2... |
import os
import nltk
import numpy as np
from nltk.sentiment.util import mark_negation
def lol2str(doc):
"""Transforms a document in the list-of-lists format into
a block of text (str type)."""
return " ".join([word for sent in doc for word in sent])
def mr2str(dataset):
"""Transforms the Movie Revi... | [
"nltk.download",
"os.path.join",
"nltk.corpus.movie_reviews.paras",
"numpy.ndarray",
"nltk.sentiment.util.mark_negation"
] | [((602, 632), 'nltk.download', 'nltk.download', (['"""movie_reviews"""'], {}), "('movie_reviews')\n", (615, 632), False, 'import nltk\n'), ((685, 722), 'nltk.corpus.movie_reviews.paras', 'movie_reviews.paras', ([], {'categories': '"""neg"""'}), "(categories='neg')\n", (704, 722), False, 'from nltk.corpus import movie_r... |
import sys, os, itertools
import numpy as np
import matplotlib.tri as tri
from glbase3 import *
import shared_conservation
# collect three things:
# 1. The total PhyloP score of the transcript
# 2. score for TE-containing bits
# 3. score for non-TE containign bits;
gl = glload('phyloP_conservation_table.glb')
print(... | [
"shared_conservation.scat",
"numpy.array",
"shared_conservation.contour",
"shared_conservation.hist"
] | [((325, 473), 'shared_conservation.scat', 'shared_conservation.scat', (['"""scat_te_vs_not_tes.pdf"""', "gl['phyloP_tes']", "gl['phyloP_nottes']", '"""TE"""', '"""not-TE"""'], {'xlims': '[-0.6, 0.7]', 'ylims': '[-0.6, 0.7]'}), "('scat_te_vs_not_tes.pdf', gl['phyloP_tes'], gl[\n 'phyloP_nottes'], 'TE', 'not-TE', xlim... |
#!/usr/bin/env python
#####################################################
# This file is a component of ClusterGB #
# Copyright (c) 2018 <NAME> #
# Released under the MIT License (see distribution) #
#####################################################
"""
For each grain boundary, cal... | [
"clustergb.bond_orientational_order.bond_orientational_order_parameter",
"argparse.ArgumentParser",
"os.path.join",
"clustergb.osio.tee",
"time.time",
"numpy.arange"
] | [((1418, 1429), 'time.time', 'time.time', ([], {}), '()\n', (1427, 1429), False, 'import time\n'), ((1435, 1511), 'clustergb.osio.tee', 'cgb.osio.tee', (['job.log_loc', "('Starting bond-order calculation for ' + job.name)"], {}), "(job.log_loc, 'Starting bond-order calculation for ' + job.name)\n", (1447, 1511), True, ... |
"""
demosaic bayer filter of type 'grbg' using nearest neighbor interpolation
input:
assumes uint8 or uint16 raw bayer filtered grbg input
assumes 2-D I x J pixels, where a single image is I x J pixels,
where I and J are both even numbers
output:
same uint8 or uint16 shape as inpout
Note: If you're on Windo... | [
"numpy.dstack",
"logging.warning",
"numpy.empty",
"scipy.ndimage.interpolation.zoom",
"logging.info",
"numpy.round"
] | [((2359, 2379), 'numpy.dstack', 'np.dstack', (['(r, g, b)'], {}), '((r, g, b))\n', (2368, 2379), True, 'import numpy as np\n'), ((2623, 2656), 'scipy.ndimage.interpolation.zoom', 'zoom', (['rgb', '(2, 2, 1)'], {'order': 'order'}), '(rgb, (2, 2, 1), order=order)\n', (2627, 2656), False, 'from scipy.ndimage.interpolation... |
# FIXME[hack]: this is just using a specific keras network as proof of
# concept. It has to be modularized and integrated into the framework
import os
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(f"nu... | [
"logging.getLogger",
"cleverhans.attacks.FastGradientMethod",
"cleverhans.utils.AccuracyReport",
"tensorflow.set_random_seed",
"logging.info",
"numpy.random.RandomState",
"os.path.exists",
"cleverhans.utils_tf.model_eval",
"numpy.asarray",
"os.mkdir",
"tensorflow.keras.backend.backend",
"cleve... | [((177, 204), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (194, 204), False, 'import logging\n'), ((974, 1007), 'tensorflow.keras.backend.image_data_format', 'keras.backend.image_data_format', ([], {}), '()\n', (1005, 1007), False, 'from tensorflow import keras\n'), ((2699, 2715), 'cle... |
# Results plotter.
#
# https://github.com/stefanvanberkum/CD-ABSC
import numpy as np
import pandas as pd
import statsmodels.formula.api as sm
from plotnine import aes, element_text, geom_point, ggplot, stat_smooth, theme
global embedding_dim, rest_path, target_path, ft_path, save_path
def main():
"""
Plots ... | [
"plotnine.stat_smooth",
"plotnine.ggplot",
"plotnine.aes",
"plotnine.element_text",
"statsmodels.formula.api.ols",
"plotnine.geom_point",
"pandas.DataFrame",
"numpy.divide"
] | [((5549, 5569), 'pandas.DataFrame', 'pd.DataFrame', (['result'], {}), '(result)\n', (5561, 5569), True, 'import pandas as pd\n'), ((1741, 1765), 'plotnine.stat_smooth', 'stat_smooth', ([], {'method': '"""lm"""'}), "(method='lm')\n", (1752, 1765), False, 'from plotnine import aes, element_text, geom_point, ggplot, stat_... |
# To run this script:
# > python getwaveform_silwal2016.py
import obspy
import copy
import getwaveform_iris
from obspy.clients.fdsn import Client
from obspy.core.event import Event, Origin, Magnitude
import numpy as np
import util_helpers as uh
# Catalog file
filename = '/home/carltape/REPOSITORIES/manuscripts/vipul/p... | [
"obspy.core.event.Origin",
"numpy.array",
"util_helpers.eid2otime",
"obspy.core.event.Event",
"getwaveform_iris.run_get_waveform",
"obspy.clients.fdsn.Client",
"obspy.core.event.Magnitude"
] | [((646, 659), 'numpy.array', 'np.array', (['iex'], {}), '(iex)\n', (654, 659), True, 'import numpy as np\n'), ((2313, 2330), 'util_helpers.eid2otime', 'uh.eid2otime', (['eid'], {}), '(eid)\n', (2325, 2330), True, 'import util_helpers as uh\n'), ((2582, 2596), 'obspy.clients.fdsn.Client', 'Client', (['"""IRIS"""'], {}),... |
from functools import partial
import numpy as np
from tqdm import tqdm
from .experiment_linear_balance_classes import ExperimentLinearBalanced
from .experiment_linear_exploit_partial import ExperimentLinearExploitPartial
from ..models.linear import Linear_S, Linear_M, Linear_L
from .training_args import LMMixupOutsid... | [
"tqdm.tqdm",
"numpy.take",
"functools.partial",
"numpy.concatenate",
"numpy.random.permutation"
] | [((1064, 1097), 'functools.partial', 'partial', (['convert2vec'], {'dtype': 'float'}), '(convert2vec, dtype=float)\n', (1071, 1097), False, 'from functools import partial\n'), ((2626, 2651), 'tqdm.tqdm', 'tqdm', ([], {'total': 'outside.steps'}), '(total=outside.steps)\n', (2630, 2651), False, 'from tqdm import tqdm\n')... |
import numpy as np
import matplotlib.pyplot as plt
from math import *
def Draw(u,f,n):
x=u
List_X=[u]
List_Y=[0]
for k in range(n):
y=f(x)
List_X.append(x)
List_Y.append(y)
List_Y.append(y)
List_X.append(y)
x=y
plt.plot(List_X,List_Y,"... | [
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
] | [((676, 685), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (683, 685), True, 'import matplotlib.pyplot as plt\n'), ((704, 713), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (711, 713), True, 'import matplotlib.pyplot as plt\n'), ((296, 325), 'matplotlib.pyplot.plot', 'plt.plot', (['List_X', 'List_Y', ... |
import typing
import numpy as np
from rrtstar.geometry import Point2d, Trajectory
from rrtstar.rrt_star import Vertex
def constant_speed_line_steering_policy(
start: Vertex, dest: Point2d, time: float, velocity: float
) -> typing.Tuple[float, Trajectory]:
unit_vector = dest.to_array() - start.position.t... | [
"rrtstar.geometry.Trajectory",
"numpy.arange",
"numpy.linalg.norm"
] | [((345, 372), 'numpy.linalg.norm', 'np.linalg.norm', (['unit_vector'], {}), '(unit_vector)\n', (359, 372), True, 'import numpy as np\n'), ((522, 571), 'numpy.arange', 'np.arange', ([], {'start': '(0.0)', 'stop': '(time + step)', 'step': 'step'}), '(start=0.0, stop=time + step, step=step)\n', (531, 571), True, 'import n... |
import argparse
import logging
import numpy as np
from PCA.PCAModel import PCAModel
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s'
)
def main():
logging.info("pca_toy_vector.py main()")
X = np.array([[0.14, -2.3, 1.58, 1], [-1.2,... | [
"logging.basicConfig",
"numpy.array",
"PCA.PCAModel.PCAModel",
"logging.info"
] | [((85, 208), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"""'}), "(level=logging.DEBUG, format=\n '[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s')\n", (104, 208), False, 'import lo... |
import numpy as np
import os
import pickle
from utils import load_config_file
import sys
if __name__ == '__main__':
config_file_name = sys.argv[1]
config = load_config_file(config_file_name)
# create output folder if it doesn't exist
output_folder = config["Output Folder"]
if not os.... | [
"numpy.mean",
"utils.load_config_file",
"numpy.histogram",
"numpy.abs",
"numpy.unique",
"numpy.digitize",
"numpy.where",
"os.path.join",
"pickle.load",
"os.path.isdir",
"os.mkdir",
"numpy.shape",
"numpy.load"
] | [((175, 209), 'utils.load_config_file', 'load_config_file', (['config_file_name'], {}), '(config_file_name)\n', (191, 209), False, 'from utils import load_config_file\n'), ((491, 526), 'numpy.load', 'np.load', (['input_feature_path_testing'], {}), '(input_feature_path_testing)\n', (498, 526), True, 'import numpy as np\... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | [
"tensorflow.contrib.training.python.training.hparam.HParams",
"tensorflow.logging.error",
"google.cloud.storage.blob.Blob",
"argparse.ArgumentParser",
"sklearn.model_selection.train_test_split",
"tensorflow.logging.info",
"json.dumps",
"tensorflow.logging.set_verbosity",
"tensorflow.contrib.learn.py... | [((3648, 3688), 'tensorflow.logging.info', 'tf.logging.info', (["('job_dir: %s' % job_dir)"], {}), "('job_dir: %s' % job_dir)\n", (3663, 3688), True, 'import tensorflow as tf\n'), ((3702, 3776), 're.search', 're.search', (['"""gs://(monorail-.+)-mlengine/(component_trainer_\\\\d+)"""', 'job_dir'], {}), "('gs://(monorai... |
import cv2
import numpy as np
import glob
def comparator(result, groundTruth):
"""
Compares the background/foreground of 2 grayscale images as states in
http://jacarini.dinf.usherbrooke.ca/datasetOverview/
but with some simplification: the shadows and unknown are considered as good classification in e... | [
"cv2.createBackgroundSubtractorMOG2",
"numpy.abs",
"cv2.imwrite",
"numpy.bitwise_not",
"numpy.ones",
"cv2.threshold",
"cv2.bgsegm.createBackgroundSubtractorMOG",
"cv2.imshow",
"cv2.morphologyEx",
"numpy.zeros",
"numpy.bitwise_and",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor... | [((477, 517), 'cv2.cvtColor', 'cv2.cvtColor', (['result', 'cv2.COLOR_BGR2GRAY'], {}), '(result, cv2.COLOR_BGR2GRAY)\n', (489, 517), False, 'import cv2\n'), ((536, 581), 'cv2.cvtColor', 'cv2.cvtColor', (['groundTruth', 'cv2.COLOR_BGR2GRAY'], {}), '(groundTruth, cv2.COLOR_BGR2GRAY)\n', (548, 581), False, 'import cv2\n'),... |
import torch
import math
import numpy as np
from matplotlib import path
import pdb
class BoxSampler(object):
def __init__(self,
RoI_number=1,
IoU_bin_bases=torch.tensor([0.73,0.12,0.15,0.05,0], dtype=torch.float),
IoU_weights=torch.tensor([0.5,0.6,0.7,0.8,0.9], ... | [
"torch.cuda.LongTensor",
"torch.unique",
"math.ceil",
"torch.multinomial",
"torch.cuda.FloatTensor",
"torch.rand",
"torch.max",
"torch.min",
"torch.ceil",
"torch.tensor",
"torch.cat",
"torch.arange",
"torch.sum",
"torch.cuda.ByteTensor",
"numpy.random.uniform",
"torch.clamp"
] | [((197, 257), 'torch.tensor', 'torch.tensor', (['[0.73, 0.12, 0.15, 0.05, 0]'], {'dtype': 'torch.float'}), '([0.73, 0.12, 0.15, 0.05, 0], dtype=torch.float)\n', (209, 257), False, 'import torch\n'), ((284, 342), 'torch.tensor', 'torch.tensor', (['[0.5, 0.6, 0.7, 0.8, 0.9]'], {'dtype': 'torch.float'}), '([0.5, 0.6, 0.7,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 9 17:02:59 2018
@author: bruce
compared with version 1.6.4
the update is from correlation coefficient
"""
import pandas as pd
import numpy as np
from scipy import fftpack
from scipy import signal
import matplotlib.pyplot as plt
from matplotlib.co... | [
"scipy.signal.detrend",
"numpy.array",
"scipy.fftpack.fft",
"numpy.arange",
"pandas.read_pickle",
"numpy.fft.fft",
"numpy.asarray",
"pandas.concat",
"pandas.DataFrame",
"scipy.signal.kaiser",
"numpy.abs",
"scipy.signal.hamming",
"matplotlib.pyplot.title",
"matplotlib.colors.LinearSegmented... | [((10135, 10210), 'pandas.read_pickle', 'pd.read_pickle', (['"""/home/bruce/Dropbox/4.Project/4.Code for Linux/df_EFR.pkl"""'], {}), "('/home/bruce/Dropbox/4.Project/4.Code for Linux/df_EFR.pkl')\n", (10149, 10210), True, 'import pandas as pd\n'), ((10366, 10380), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (... |
"""
MouseRobotEKF 自己实现的一个EKF算法,
此算法中把鼠标作为机器人控制信号,为机器人提供运动需要的加速度和方向向量: M_vector,(加速度就用鼠标的加速度a,方向也是鼠标运动的方向);
同时,鼠标的当前位置和当前速度,也作为机器人的测量传感器使用Z_k(P,V)
Note: 以下: 当前时刻: cur or k-1 下一时刻: next or k
1.状态向量定义:
机器人根据鼠标的运动产生自己的位置和速度两个状态向量state_x(Position(x,y),Velocity(x,y)),即: X(P,V);
估计值向量: X= [ Px
Vx
... | [
"math.pow",
"tinyekf.EKF.__init__",
"numpy.array",
"numpy.eye"
] | [((3162, 3204), 'tinyekf.EKF.__init__', 'EKF.__init__', (['self', 'n', 'm', 'pval', 'qval', 'rval'], {}), '(self, n, m, pval, qval, rval)\n', (3174, 3204), False, 'from tinyekf import EKF\n'), ((3510, 3604), 'numpy.array', 'np.array', (['[(1, self.interval, 0, 0), (0, 1, 0, 0), (0, 0, 1, self.interval), (0, 0, 0, 1)\n ... |
from math import gcd, ceil, sqrt
from numpy import around, int32, zeros
from numpy.random import RandomState
from polymod import Poly
def isprime(n):
"""
>>> isprime(1109)
True
>>> isprime(10**6)
False
"""
# this is slow and basic, but saves the sympy dependency
# alternatively, fro... | [
"math.gcd",
"polymod.Poly.monomial",
"polymod.Poly",
"math.sqrt",
"numpy.zeros",
"numpy.around",
"numpy.random.RandomState"
] | [((1295, 1308), 'numpy.random.RandomState', 'RandomState', ([], {}), '()\n', (1306, 1308), False, 'from numpy.random import RandomState\n'), ((2080, 2115), 'numpy.zeros', 'zeros', (['(modulus.deg + 1)'], {'dtype': 'int32'}), '(modulus.deg + 1, dtype=int32)\n', (2085, 2115), False, 'from numpy import around, int32, zero... |
from calendar import month_name, monthrange
from pathlib import Path, PureWindowsPath
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import math as mt
from dataclima import helioclim3
class energycalc:
def __init__(self, df,
horizon,
... | [
"pandas.DataFrame",
"numpy.array",
"pandas.concat",
"numpy.cumprod"
] | [((3777, 3807), 'numpy.array', 'np.array', (["dflocalloss['value']"], {}), "(dflocalloss['value'])\n", (3785, 3807), True, 'import numpy as np\n'), ((3921, 3949), 'numpy.array', 'np.array', (["dfmodloss['value']"], {}), "(dfmodloss['value'])\n", (3929, 3949), True, 'import numpy as np\n'), ((4992, 5065), 'pandas.DataFr... |
"""Bezier, a module for creating Bezier curves.
Version 1.1, from < BezierCurveFunction-v1.ipynb > on 2019-05-02
"""
import numpy as np
__all__ = ["Bezier"]
class Bezier():
def TwoPoints(t, P1, P2):
"""
Returns a point between P1 and P2, parametised by t.
INPUTS:
t float/... | [
"numpy.delete"
] | [((3282, 3304), 'numpy.delete', 'np.delete', (['curve', '(0)', '(0)'], {}), '(curve, 0, 0)\n', (3291, 3304), True, 'import numpy as np\n')] |
import numpy as np
class sensor:
def __init__(self, inverse_x=False, inverse_z=False):
self.inverse_x = inverse_x
self.inverse_z = inverse_z
self.flip_x_z = False
self.rotation = np.array([0, 0])
def get_angle(self):
rot = np.copy(self.rotation)
if self.flip_x_... | [
"numpy.array",
"numpy.copy"
] | [((217, 233), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (225, 233), True, 'import numpy as np\n'), ((274, 296), 'numpy.copy', 'np.copy', (['self.rotation'], {}), '(self.rotation)\n', (281, 296), True, 'import numpy as np\n')] |
import os.path
import sys
import numpy as np
import copy
import shutil
import astropy.units as u
import pandas as pd
import pickle
from sklearn.neighbors import BallTree
import time
from nexoclom import math as mathMB
from nexoclom.atomicdata import gValue
from nexoclom.modelcode.input_classes import InputError
from ne... | [
"nexoclom.math.Histogram2d",
"nexoclom.math.Histogram",
"nexoclom.modelcode.SourceMap.SourceMap",
"time.sleep",
"numpy.isfinite",
"numpy.arctan2",
"copy.deepcopy",
"numpy.linalg.norm",
"sys.exit",
"numpy.sin",
"nexoclom.math.smooth",
"numpy.cross",
"IPython.embed",
"nexoclom.modelcode.Outp... | [((2416, 2437), 'copy.deepcopy', 'copy.deepcopy', (['inputs'], {}), '(inputs)\n', (2429, 2437), False, 'import copy\n'), ((5251, 5345), 'astropy.units.def_unit', 'u.def_unit', (["('R_' + self.inputs.geometry.planet.object)", 'self.inputs.geometry.planet.radius'], {}), "('R_' + self.inputs.geometry.planet.object, self.i... |
import argparse
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
from torch.utils.data import DataLoader
from src.dataload.tabularDataset import (split_tabular_normal_only_train,
tabularDataset)
from src.lit_models.LitBaseAutoEncoder import Li... | [
"pytorch_lightning.callbacks.EarlyStopping",
"src.lit_models.LitBaseVAE.LitBaseVAE",
"argparse.ArgumentParser",
"pandas.read_csv",
"src.dataload.tabularDataset.split_tabular_normal_only_train",
"src.lit_models.LitBaseAutoEncoder.LitBaseAutoEncoder",
"pytorch_lightning.loggers.WandbLogger",
"numpy.arra... | [((425, 450), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (448, 450), False, 'import argparse\n'), ((1272, 1301), 'pandas.read_csv', 'pd.read_csv', (['config.data_path'], {}), '(config.data_path)\n', (1283, 1301), True, 'import pandas as pd\n'), ((1355, 1390), 'src.dataload.tabularDataset.sp... |
import numpy as np
from numpy import pi, sin, cos, tan, sqrt, arctan2, arcsin, arctan, arccos, log10
from .orbital_elements import elements, jupiter_oe, saturn_oe, uranus_oe
from .utils import *
from .transform import cartesian_to_spherical, spherical_to_cartesian, ecliptic_to_equatorial, elements_to_ecliptic, radec_to... | [
"numpy.log10",
"numpy.arccos",
"numpy.array",
"numpy.cos",
"numpy.sin"
] | [((6730, 6753), 'numpy.array', 'np.array', (['[lon, lat, r]'], {}), '([lon, lat, r])\n', (6738, 6753), True, 'import numpy as np\n'), ((7636, 7684), 'numpy.arccos', 'arccos', (['((s ** 2 + R ** 2 - r ** 2) / (2 * s * R))'], {}), '((s ** 2 + R ** 2 - r ** 2) / (2 * s * R))\n', (7642, 7684), False, 'from numpy import pi,... |
import re
import numpy as np
from numpy.core.einsumfunc import _parse_einsum_input
from paderbox.array.segment import segment_axis
__all__ = [
'split_complex_features',
'merge_complex_features',
'tbf_to_tbchw',
'morph',
]
def split_complex_features(X):
""" Split a complex valued input array int... | [
"numpy.shape",
"paderbox.array.segment.segment_axis",
"numpy.asarray",
"numpy.squeeze",
"numpy.einsum",
"numpy.concatenate",
"numpy.pad"
] | [((1764, 1855), 'numpy.pad', 'np.pad', (['x', '((left_context, right_context), (0, 0), (0, 0))'], {'mode': 'pad_mode'}), '(x, ((left_context, right_context), (0, 0), (0, 0)), mode=pad_mode,\n **pad_kwargs)\n', (1770, 1855), True, 'import numpy as np\n'), ((5304, 5335), 'numpy.concatenate', 'np.concatenate', (['targe... |
import numpy as np
import pandas as pd
import os
import math
import matplotlib.pyplot as plt
import pickle
import geopy
import geopy.distance as distance
def retrieve_and_save(countries, fns, out_dir, keys, sample=True):
for idx, country in enumerate(countries):
df = pd.read_csv(fns[idx], sep=' ')
df = df... | [
"math.ceil",
"numpy.ones",
"pandas.read_csv",
"pickle.dump",
"os.path.join",
"numpy.max",
"numpy.array",
"numpy.zeros",
"geopy.distance.great_circle",
"geopy.Point",
"numpy.min"
] | [((2394, 2408), 'numpy.array', 'np.array', (['lats'], {}), '(lats)\n', (2402, 2408), True, 'import numpy as np\n'), ((2419, 2433), 'numpy.array', 'np.array', (['lons'], {}), '(lons)\n', (2427, 2433), True, 'import numpy as np\n'), ((2448, 2461), 'numpy.min', 'np.min', (['nlats'], {}), '(nlats)\n', (2454, 2461), True, '... |
# Autogenerated using symbolic_dynamics_n.py; don't edit!
from enum import IntEnum
import numpy as np
from numpy import sin, cos
from .dynamic_model_n import NBallDynamicModel
class StateIndex(IntEnum):
ALPHA_1_IDX = 0,
PHI_IDX = 1,
PSI_0_IDX = 2,
ALPHA_DOT_1_IDX = 3,
PHI_DOT_IDX = 4,
PSI_DOT... | [
"numpy.sin",
"numpy.zeros",
"numpy.linalg.solve",
"numpy.cos"
] | [((802, 810), 'numpy.cos', 'cos', (['phi'], {}), '(phi)\n', (805, 810), False, 'from numpy import sin, cos\n'), ((965, 973), 'numpy.sin', 'sin', (['phi'], {}), '(phi)\n', (968, 973), False, 'from numpy import sin, cos\n'), ((1073, 1083), 'numpy.sin', 'sin', (['psi_0'], {}), '(psi_0)\n', (1076, 1083), False, 'from numpy... |
#!/usr/bin/env python
"""
TODO: Modify module doc.
"""
from __future__ import division
__author__ = "<NAME>"
__copyright__ = "Copyright 2013, The Materials Virtual Lab"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__date__ = "4/12/14"
import inspect
import itertools
import numpy as np
from p... | [
"symmetry.groups.SpaceGroup",
"matplotlib.pyplot.plot",
"itertools.product",
"inspect.getargspec",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.dot",
"numpy.cos",
"matplotlib.pyplot.tight_layout",
"numpy.sin",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"numpy.arange",
"matplo... | [((2553, 2571), 'symmetry.groups.SpaceGroup', 'SpaceGroup', (['"""Pnma"""'], {}), "('Pnma')\n", (2563, 2571), False, 'from symmetry.groups import SpaceGroup\n'), ((1011, 1039), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1021, 1039), True, 'import matplotlib.pyplot ... |
""" Module providing unit-testing for the `~halotools.mock_observables.tpcf` function.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import warnings
import pytest
from astropy.utils.misc import NumpyRNGContext
from .locate_external_unit_testing_data import t... | [
"numpy.allclose",
"astropy.utils.misc.NumpyRNGContext",
"numpy.random.random",
"numpy.array",
"numpy.linspace",
"pytest.raises",
"pytest.mark.skipif",
"numpy.all",
"numpy.load"
] | [((21047, 21098), 'pytest.mark.skipif', 'pytest.mark.skipif', (['"""not TPCF_CORRFUNC_FILES_EXIST"""'], {}), "('not TPCF_CORRFUNC_FILES_EXIST')\n", (21065, 21098), False, 'import pytest\n'), ((971, 996), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0])\n', (979, 996), True, 'import numpy as np\n... |
from __future__ import division
import numpy as np
import utils
import pdb
data = utils.load_dataset("credittest")
Xvalid, yvalid = data['X'], data['y']
def kappa(ww, delta):
ww = np.array(ww)
yhat = np.sign(np.dot(Xvalid, ww))
ww2 = np.array(ww + delta)
yhat2 = np.sign(np.dot(Xvalid, ww2))
... | [
"numpy.argpartition",
"numpy.sort",
"numpy.array",
"numpy.dot",
"numpy.sum",
"pdb.set_trace",
"utils.load_dataset"
] | [((83, 115), 'utils.load_dataset', 'utils.load_dataset', (['"""credittest"""'], {}), "('credittest')\n", (101, 115), False, 'import utils\n'), ((191, 203), 'numpy.array', 'np.array', (['ww'], {}), '(ww)\n', (199, 203), True, 'import numpy as np\n'), ((258, 278), 'numpy.array', 'np.array', (['(ww + delta)'], {}), '(ww +... |
import numpy as np
import pandas as pd
import itertools
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_predict,cross_val_score,train_test_split
from sklearn.metrics import classification_report,confusion_matrix,roc_curve,auc,precision_recall_curve,roc_curve
import pickle
#raw_df = pd.r... | [
"matplotlib.pyplot.ylabel",
"sklearn.metrics.auc",
"pandas.value_counts",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"sklearn.metrics.roc_curve",
"numpy.isfinite",
"pandas.read_excel",
"statsmodels.api.families.Gamma",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotl... | [((520, 570), 'pandas.read_excel', 'pd.read_excel', (['myfile'], {'sheet_name': '"""Data"""', 'header': '(0)'}), "(myfile, sheet_name='Data', header=0)\n", (533, 570), True, 'import pandas as pd\n'), ((7507, 7519), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7517, 7519), True, 'import matplotlib.pyplot... |
import pandas as pd
import numpy as np
from tqdm import tqdm
from dateutil.relativedelta import relativedelta
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.multioutput import RegressorChain
from sklearn.metrics import fbeta_score, mean_squared_error, r2_score
from sklearn.prepr... | [
"vespid.data.neo4j_tools.Relationships",
"dateutil.relativedelta.relativedelta",
"vespid.models.static_communities.cosine_similarities",
"vespid.models.static_communities.get_cluster_data",
"vespid.setup_logger",
"vespid.models.static_communities.jaccard_coefficient",
"sklearn.multioutput.RegressorChain... | [((642, 664), 'vespid.setup_logger', 'setup_logger', (['__name__'], {}), '(__name__)\n', (654, 664), False, 'from vespid import setup_logger\n'), ((43773, 43789), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (43787, 43789), False, 'from sklearn.preprocessing import StandardScaler\n'), ((4... |
#!/usr/bin/env python3
"""Investigates the distribution for link Markov models.
The link Markov model is based on the linking behavior of a given
linkograph. Since the links in a linkograph are determined by
ontology, the transition model is depending on the ontology. This
script creates a sequence of random Markov m... | [
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"markov.Model.genModelFromOntology",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"markov.Model.genModelFromLinko",
"matplotlib.pyplot.figure",
"numpy.zeros",
"json.load",
"matplotlib.pyplot.title",
"time.time",
"m... | [((5197, 5238), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'info'}), '(description=info)\n', (5220, 5238), False, 'import argparse\n'), ((7254, 7267), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (7264, 7267), True, 'import matplotlib.pyplot as plt\n'), ((7336, 7369)... |
import pytest
from py_scripts.singleton_calling_utils import get_good_idxs, get_singleton_idx, levenshtein, reformat_genotypes, normalize_var
import numpy as np
def test_reformat_genotypes(genotype_array):
assert np.array_equal(reformat_genotypes(genotype_array), np.array([0, 1, 1, 2]))
def test_reformat_genotyp... | [
"py_scripts.singleton_calling_utils.normalize_var",
"py_scripts.singleton_calling_utils.reformat_genotypes",
"py_scripts.singleton_calling_utils.levenshtein",
"pytest.mark.parametrize",
"numpy.array",
"py_scripts.singleton_calling_utils.get_singleton_idx",
"py_scripts.singleton_calling_utils.get_good_id... | [((449, 594), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""invara,invarb,outvar"""', "[('TCC', 'CCC', ('T', 'C')), ('CAGGGGG', 'CTGGGGG', ('A', 'T')), ('GAT',\n 'GAT', ('N', 'N'))]"], {}), "('invara,invarb,outvar', [('TCC', 'CCC', ('T', 'C')),\n ('CAGGGGG', 'CTGGGGG', ('A', 'T')), ('GAT', 'GAT', ('... |
#!/usr/bin/env python3
"""Very basic MIDI synthesizer.
This does the same as midi_sine.py, but it uses NumPy and block
processing. It is therefore much more efficient. But there are still
many allocations and dynamically growing and shrinking data structures.
"""
import jack
import numpy as np
import threading
# F... | [
"threading.Event",
"numpy.zeros",
"numpy.arange",
"jack.Client"
] | [((482, 512), 'jack.Client', 'jack.Client', (['"""MIDI-Sine-NumPy"""'], {}), "('MIDI-Sine-NumPy')\n", (493, 512), False, 'import jack\n'), ((622, 639), 'threading.Event', 'threading.Event', ([], {}), '()\n', (637, 639), False, 'import threading\n'), ((3458, 3478), 'numpy.arange', 'np.arange', (['blocksize'], {}), '(blo... |
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import numpy as np
import pytest
from .. import CylindricalGrid
from ..boundaries.local import NeumannBC
def test_cylindrical_grid():
""" test simple cylindrical grid """
for periodic in [True, False]:
grid = CylindricalGrid(4, (-1, 2), (8, 9), periodic_z=per... | [
"pytest.approx",
"numpy.sqrt",
"numpy.testing.assert_allclose",
"numpy.any",
"pytest.mark.parametrize",
"numpy.random.randint",
"numpy.testing.assert_almost_equal",
"pytest.raises",
"numpy.array",
"numpy.linspace",
"numpy.all"
] | [((2947, 2997), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""periodic"""', '[True, False]'], {}), "('periodic', [True, False])\n", (2970, 2997), False, 'import pytest\n'), ((2058, 2124), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['pf_cart1.data', 'pf_cart2.data'], {'atol': '(0.1)'})... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
""" Simple 2 input mixer node. This takes two inputs of potentially different sizes,
weights them and then sums them to form an output.
"""
import asyncio
import queue
import labgraph as lg
import numpy as np
from ...messages.generic_s... | [
"asyncio.Event",
"numpy.dot",
"labgraph.publisher",
"asyncio.sleep",
"queue.Queue",
"labgraph.Topic",
"labgraph.subscriber"
] | [((630, 659), 'labgraph.Topic', 'lg.Topic', (['SignalSampleMessage'], {}), '(SignalSampleMessage)\n', (638, 659), True, 'import labgraph as lg\n'), ((688, 717), 'labgraph.Topic', 'lg.Topic', (['SignalSampleMessage'], {}), '(SignalSampleMessage)\n', (696, 717), True, 'import labgraph as lg\n'), ((741, 770), 'labgraph.To... |
import numpy as np
import csv
import os
import util
# Reproducible random numbers
np.random.seed(0)
# Prefix
path = 'results/hw2/'
if not os.path.exists(path):
os.mkdir(path)
reportLines = []
# 100 x 100 children
res = util.measurement(path, taskId = 'hw2_1', childrenPerLevel = (100, 100), initSecPrice = ... | [
"os.path.exists",
"util.measurement",
"csv.writer",
"os.mkdir",
"numpy.random.seed"
] | [((85, 102), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (99, 102), True, 'import numpy as np\n'), ((233, 372), 'util.measurement', 'util.measurement', (['path'], {'taskId': '"""hw2_1"""', 'childrenPerLevel': '(100, 100)', 'initSecPrice': '[1, 100, 100, 100]', 'logNormalMean': '(2)', 'logNormalSigma'... |
from __future__ import division
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import Imputer, MinMaxScaler, StandardScaler, OneHotEncoder
from sklearn.feature_selection import VarianceThreshold
import pandas as pd
from clumpy.unique_threshold import UniqueThre... | [
"numpy.intersect1d",
"sklearn.feature_selection.VarianceThreshold",
"numpy.unique",
"clumpy.datasets.utils.categorical_columns",
"numpy.searchsorted",
"sklearn.preprocessing.Imputer",
"numpy.putmask",
"sklearn.preprocessing.StandardScaler",
"numpy.sum",
"numpy.argsort",
"clumpy.datasets.utils.or... | [((613, 625), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (622, 625), True, 'import numpy as np\n'), ((892, 904), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (901, 904), True, 'import numpy as np\n'), ((3158, 3206), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {'strategy': 'strategy', 'missing_values'... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author : east
# @time : 2021/7/13 10:34
# @file : interval.py
# @project : fepy
# software : PyCharm
import numpy as np
# Functions
# ---------
def area(*points):
[pl, pr] = np.asarray(points)
if (pl.ndim > 1) or (pr.ndim > 1):
raise ValueError('Inp... | [
"numpy.asarray"
] | [((233, 251), 'numpy.asarray', 'np.asarray', (['points'], {}), '(points)\n', (243, 251), True, 'import numpy as np\n')] |
__doc__ = """Image chunk class"""
import numpy as np
from chunkflow.chunk import Chunk
class AffinityMap(Chunk):
"""
a chunk of affinity map. It has x,y,z three channels with single precision.
"""
def __init__(self, array, voxel_offset=None):
assert array.ndim == 4
assert np.issubdtyp... | [
"numpy.issubdtype",
"chunkflow.chunk.Chunk"
] | [((308, 346), 'numpy.issubdtype', 'np.issubdtype', (['array.dtype', 'np.float32'], {}), '(array.dtype, np.float32)\n', (321, 346), True, 'import numpy as np\n'), ((654, 726), 'chunkflow.chunk.Chunk', 'Chunk', (['image'], {'voxel_offset': 'self.voxel_offset', 'voxel_size': 'self.voxel_size'}), '(image, voxel_offset=self... |
#!/usr/bin/env python
import numpy as np
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint, TrafficLightArray
from std_msgs.msg import Int32
from scipy.spatial import KDTree
import yaml
import math
'''
This node will publish waypoints from the car's current position to so... | [
"rospy.logerr",
"rospy.Subscriber",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_param",
"scipy.spatial.KDTree",
"math.sqrt",
"numpy.array",
"numpy.dot",
"rospy.Rate",
"styx_msgs.msg.Waypoint",
"rospy.Publisher",
"rospy.loginfo",
"styx_msgs.msg.Lane"
] | [((1036, 1071), 'rospy.init_node', 'rospy.init_node', (['"""waypoint_updater"""'], {}), "('waypoint_updater')\n", (1051, 1071), False, 'import rospy\n'), ((1099, 1159), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/current_pose"""', 'PoseStamped', 'self.pose_cb'], {}), "('/current_pose', PoseStamped, self.pose_cb)\n",... |
import torch
from torch import Tensor
from typing import List, Tuple
from numpy import ndarray
import numpy as np
from .config import SentenceTransformerConfig
from .models import TransformerModel
from tqdm import tqdm
class SentenceEncoder:
"""
Wrapper for the encoding and embedding of sentences with Sentenc... | [
"torch.stack",
"tqdm.tqdm",
"numpy.argsort",
"torch.tensor",
"torch.cuda.is_available",
"torch.no_grad"
] | [((3422, 3451), 'numpy.argsort', 'np.argsort', (['length_sorted_idx'], {}), '(length_sorted_idx)\n', (3432, 3451), True, 'import numpy as np\n'), ((4887, 4906), 'torch.stack', 'torch.stack', (['labels'], {}), '(labels)\n', (4898, 4906), False, 'import torch\n'), ((1770, 1800), 'tqdm.tqdm', 'tqdm', (['iterator'], {'desc... |
from zipfile import ZipFile
import numpy as np
def generate_report(task_a, task_b, task_c, save=True, zipname="res.zip"):
report = ""
task_a = task_a - 1
for i in range(task_a.shape[0]):
task_b_str = np.array2string(task_b[i], separator="")[1:-1]
task_c_str = np.array2string(task_c[i], sep... | [
"numpy.array2string",
"zipfile.ZipFile"
] | [((222, 262), 'numpy.array2string', 'np.array2string', (['task_b[i]'], {'separator': '""""""'}), "(task_b[i], separator='')\n", (237, 262), True, 'import numpy as np\n'), ((290, 330), 'numpy.array2string', 'np.array2string', (['task_c[i]'], {'separator': '""""""'}), "(task_c[i], separator='')\n", (305, 330), True, 'imp... |
from check_defn import *
import numpy as np
import random
def train(word_list, query_list, ensemble, iterations,l_rate,matrix,lamb):
#counter is used to go to next ensemble
counter = 0
total_data = len(word_list)
for iteration in range(iterations):
#To keep the cost
cost = 0
... | [
"numpy.savetxt",
"random.randint",
"numpy.save"
] | [((2275, 2304), 'numpy.save', 'np.save', (['"""matrix.npy"""', 'matrix'], {}), "('matrix.npy', matrix)\n", (2282, 2304), True, 'import numpy as np\n'), ((2306, 2338), 'numpy.savetxt', 'np.savetxt', (['"""matrix.txt"""', 'matrix'], {}), "('matrix.txt', matrix)\n", (2316, 2338), True, 'import numpy as np\n'), ((603, 625)... |
# -*- coding: utf-8 -*-
"""
DTQPy_M
Create sequences for Mayer terms
Contributor: <NAME> (AthulKrishnaSundarrajan on Github)
Primary Contributor: <NAME> (danielrherber on Github)
"""
# import inbuilt libraries
import numpy as np
from numpy.matlib import repmat
# import DTQPy specific functions
from dtqpy.src.utilitie... | [
"numpy.append",
"numpy.array",
"dtqpy.src.DTQPy_getQPIndex.DTQPy_getQPIndex"
] | [((600, 612), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (608, 612), True, 'import numpy as np\n'), ((621, 633), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (629, 633), True, 'import numpy as np\n'), ((642, 654), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (650, 654), True, 'import numpy as np\n')... |
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import os
import math
#import utm
import shapefile as shp
import seaborn as sns
from collections import OrderedDict
import geopandas as gpd
from geopy.distance import distance
import argparse
# PRIMARY DATA SOURCE
# https:/... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.array",
"pandas.to_datetime",
"numpy.mean",
"os.listdir",
"datetime.time",
"geopandas.read_file",
"argparse.ArgumentParser",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"datetime.date.fromordinal",... | [((1744, 1801), 'pandas.concat', 'pd.concat', (['df_list'], {'axis': '(0)', 'ignore_index': '(True)', 'sort': '(False)'}), '(df_list, axis=0, ignore_index=True, sort=False)\n', (1753, 1801), True, 'import pandas as pd\n'), ((7590, 7632), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'fields', 'data': 'records'})... |
#!/usr/bin/python3
"""
sys.argv[1] - input database file
sys.argv[2] - output mat file
Composed by <NAME> @THU_IVG
Last revision: <NAME> @THU_IVG @Oct 3rd, 2019 CST
"""
import json
import scipy.io as sio
import numpy as np
import itertools
import sys
db_f = sys.argv[1]
with open(db_f) as f:
database = json.l... | [
"numpy.copy",
"scipy.io.savemat",
"numpy.logical_not",
"numpy.sum",
"numpy.zeros",
"json.load"
] | [((563, 583), 'numpy.zeros', 'np.zeros', (['(nb_step,)'], {}), '((nb_step,))\n', (571, 583), True, 'import numpy as np\n'), ((600, 628), 'numpy.zeros', 'np.zeros', (['(nb_step, nb_step)'], {}), '((nb_step, nb_step))\n', (608, 628), True, 'import numpy as np\n'), ((1009, 1038), 'numpy.sum', 'np.sum', (['frequency_mat'],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.