code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import pandas as pd
import numpy as np
import os
import multiprocessing
import pickle
from matplotlib import pyplot as plt
import matplotlib
matplotlib.rcParams["figure.dpi"] = 300
matplotlib.rcParams["xtick.labelsize"] = 13
matplotlib.rcParams["ytick.labelsize"] = 13
import scipy
from scipy.cluster.hierarchy import... | [
"matplotlib.pyplot.title",
"scipy.cluster.hierarchy.fcluster",
"numpy.argmax",
"scipy.cluster.hierarchy.linkage",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.arange",
"pandas.DataFrame",
"numpy.set_printoptions",
"matplotlib.pyplot.close",
"os.path.exists",
"numpy.fill_diagonal",
"matp... | [((518, 550), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(4)'}), '(precision=4)\n', (537, 550), True, 'import numpy as np\n'), ((551, 585), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (570, 585), True, 'import numpy as np\n'), ((785, 797)... |
from mpi4py import MPI
import numpy as np
amode = MPI.MODE_WRONLY|MPI.MODE_CREATE
comm = MPI.COMM_WORLD
fh = MPI.File.Open(comm, "data.txt", amode)
buffer = np.empty(10, dtype=int)
buffer[:] = comm.Get_rank()
offset = comm.Get_rank()*buffer.nbytes
fh.Write_at_all(offset, buffer)
fh.Close() | [
"numpy.empty",
"mpi4py.MPI.File.Open"
] | [((110, 148), 'mpi4py.MPI.File.Open', 'MPI.File.Open', (['comm', '"""data.txt"""', 'amode'], {}), "(comm, 'data.txt', amode)\n", (123, 148), False, 'from mpi4py import MPI\n'), ((159, 182), 'numpy.empty', 'np.empty', (['(10)'], {'dtype': 'int'}), '(10, dtype=int)\n', (167, 182), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#from init_parametres import *
from Planet import Planet
#Définition des constantes
G = 6.67408 * 10**(-11)
dt = 1
masse_terre = 5.9722*(10)**24
rayon_terre = 6378.137 *(10)**3
t = 0
####################################
# ... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.cross",
"matplotlib.pyplot.subplots",
"numpy.sqrt"
] | [((9255, 9269), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9267, 9269), True, 'import matplotlib.pyplot as plt\n'), ((13020, 13030), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13028, 13030), True, 'import matplotlib.pyplot as plt\n'), ((5715, 5757), 'numpy.sqrt', 'np.sqrt', (['(plane... |
import numpy as np
from math import sin, cos, radians, degrees, pi, asin, atan2
def rot_y(deg=0):
r = np.array([[cos(deg), 0, sin(deg)],
[0, 1, 0],
[-sin(deg), 0, cos(deg)]])
R = np.eye(4)
R[:3,:3] = r
return R
def rot_z(deg=0):
r = np.array([[cos(deg), ... | [
"math.asin",
"math.atan2",
"math.sin",
"math.cos",
"numpy.eye"
] | [((231, 240), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (237, 240), True, 'import numpy as np\n'), ((422, 431), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (428, 431), True, 'import numpy as np\n'), ((612, 621), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (618, 621), True, 'import numpy as np\n'), ((1215, 12... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017 <NAME>. All rights reserved.
# eduardovalle.com/ github.com/learningtitans
#
# 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
#
# ... | [
"argparse.ArgumentParser",
"logging.basicConfig",
"numpy.asarray",
"logging.getLogger",
"argparse.FileType",
"sys.exit"
] | [((1318, 1357), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1337, 1357), False, 'import logging\n'), ((1364, 1400), 'logging.getLogger', 'logging.getLogger', (['"""compute_metrics"""'], {}), "('compute_metrics')\n", (1381, 1400), False, 'import logging\n'), ... |
import numpy as np
BENCHMARK_CLASSES = (
'bathtub',
'bin',
'bookcase',
'chair',
'cabinet',
'display',
'sofa',
'table',
)
ALL_CLASSES = (
'bathtub',
'bed',
'bin',
'bookcase',
'chair',
'cabinet',
'display',
'sofa',
'table',
)
SYMMETRY_CLASS_IDS = {
... | [
"numpy.array"
] | [((888, 911), 'numpy.array', 'np.array', (['[210, 43, 16]'], {}), '([210, 43, 16])\n', (896, 911), True, 'import numpy as np\n'), ((932, 956), 'numpy.array', 'np.array', (['[176, 71, 241]'], {}), '([176, 71, 241])\n', (940, 956), True, 'import numpy as np\n'), ((977, 1002), 'numpy.array', 'np.array', (['[204, 204, 255]... |
import numpy
def fig2data(fig):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw()
# Get the RGBA buffer from the figure
w, h =... | [
"numpy.roll"
] | [((562, 588), 'numpy.roll', 'numpy.roll', (['buf', '(3)'], {'axis': '(2)'}), '(buf, 3, axis=2)\n', (572, 588), False, 'import numpy\n')] |
from numpy import mean
from sqlalchemy.sql.expression import false
from .base import Analytics
import marcottievents.models.club as mc
import marcottievents.models.common.events as mce
import marcottievents.models.common.suppliers as mcs
import marcottievents.models.common.enums as enums
def coroutine(func):
"""... | [
"marcottievents.models.common.suppliers.MatchMap.remote_id.label",
"marcottievents.models.common.events.MatchActions.lineup_id.label",
"marcottievents.models.common.events.MatchActions.type.label",
"marcottievents.models.common.events.MatchEvents.period_secs.label",
"numpy.mean",
"marcottievents.models.co... | [((10367, 10391), 'numpy.mean', 'mean', (['time_between_fouls'], {}), '(time_between_fouls)\n', (10371, 10391), False, 'from numpy import mean\n'), ((10641, 10669), 'numpy.mean', 'mean', (['time_between_stoppages'], {}), '(time_between_stoppages)\n', (10645, 10669), False, 'from numpy import mean\n'), ((9905, 9958), 'm... |
# @author Hillebrand, Fabian
# @date 2019
import numpy as np
class Interpolator:
"""
Provides an interpolator for a regular grid with consistent stepsize along
an axis.
The interpolation scheme used is currently piecewise linear polynomials.
As such, the convergence rate is algebraic with a ra... | [
"numpy.gradient"
] | [((824, 900), 'numpy.gradient', 'np.gradient', (['self.f', 'self.dx', 'self.dy', 'self.dz'], {'edge_order': '(2)', 'axis': '(0, 1, 2)'}), '(self.f, self.dx, self.dy, self.dz, edge_order=2, axis=(0, 1, 2))\n', (835, 900), True, 'import numpy as np\n')] |
import numpy as np
import glm
from OpenGL.GL import *
from scripts import mesh
class Rectangle(object):
verts = np.array((-1, -1, 0,
1, -1, 0,
1, 1, 0,
-1, 1, 0), dtype=np.float32)
tex_coords = np.array((0, 0,
1, 0,... | [
"numpy.array",
"scripts.mesh.Mesh",
"glm.vec2"
] | [((120, 188), 'numpy.array', 'np.array', (['(-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0)'], {'dtype': 'np.float32'}), '((-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0), dtype=np.float32)\n', (128, 188), True, 'import numpy as np\n'), ((272, 324), 'numpy.array', 'np.array', (['(0, 0, 1, 0, 1, 1, 0, 1)'], {'dtype': 'np.float32'}), ... |
import pandas as pd
from numpy import log10
from expression.models import CuffDiffRecord, CuffDiffFile
from library.utils import sha1_str
from snpdb.graphs.graphcache import CacheableGraph
class VolcanoGraph(CacheableGraph):
def __init__(self, expression_id):
super().__init__()
self.expression_i... | [
"library.utils.sha1_str",
"expression.models.CuffDiffFile.objects.get",
"expression.models.CuffDiffRecord.objects.filter",
"numpy.log10"
] | [((385, 413), 'library.utils.sha1_str', 'sha1_str', (['self.expression_id'], {}), '(self.expression_id)\n', (393, 413), False, 'from library.utils import sha1_str\n'), ((464, 511), 'expression.models.CuffDiffFile.objects.get', 'CuffDiffFile.objects.get', ([], {'pk': 'self.expression_id'}), '(pk=self.expression_id)\n', ... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
from pathlib import Path
try:
os.mkdir("../figures")
except OSError:
pass
def compute_scores(df):
snrs = df.snr.unique()
rhos = df.rho.unique()
xx, yy = np.meshgrid(snrs, rhos)
scores_random = np.zeros(xx.sha... | [
"os.mkdir",
"matplotlib.pyplot.tight_layout",
"numpy.meshgrid",
"numpy.zeros",
"numpy.max",
"pathlib.Path",
"numpy.arange",
"numpy.log10",
"matplotlib.pyplot.subplots"
] | [((118, 140), 'os.mkdir', 'os.mkdir', (['"""../figures"""'], {}), "('../figures')\n", (126, 140), False, 'import os\n'), ((261, 284), 'numpy.meshgrid', 'np.meshgrid', (['snrs', 'rhos'], {}), '(snrs, rhos)\n', (272, 284), True, 'import numpy as np\n'), ((305, 323), 'numpy.zeros', 'np.zeros', (['xx.shape'], {}), '(xx.sha... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | [
"numpy.loadtxt"
] | [((1125, 1154), 'numpy.loadtxt', 'np.loadtxt', (['path'], {'unpack': '(True)'}), '(path, unpack=True)\n', (1135, 1154), True, 'import numpy as np\n')] |
# For Youtube Download.
import io
from pytube import YouTube
from IPython.display import HTML
from base64 import b64encode
import os
import cv2
import time
import copy
import glob
import torch
import gdown
import argparse
import statistics
import threading
import torchvision
import numpy as np
import pandas as pd
im... | [
"seaborn.heatmap",
"cv2.VideoWriter_fourcc",
"albumentations.Resize",
"sklearn.metrics.classification_report",
"torch.nn.Softmax",
"glob.glob",
"albumentations.Normalize",
"torch.device",
"torch.no_grad",
"os.path.join",
"cv2.imshow",
"collections.deque",
"torch.utils.data.DataLoader",
"al... | [((942, 984), 'os.path.join', 'os.path.join', (['__location__', '"""model_ft.pth"""'], {}), "(__location__, 'model_ft.pth')\n", (954, 984), False, 'import os\n'), ((1359, 1444), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(4)', 'num_workers': '(0)', 'shuffle': '(False)'})... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas_datareader import data
import pymc3 as pm
np.random.seed(0)
def main():
#load data
returns = data.get_data_google('SPY', start='2008-5-1', end='2009-12-1')['Close'].pct_change()
returns.plot()
plt.ylabel('daily r... | [
"pymc3.sample",
"pymc3.Model",
"numpy.random.seed",
"matplotlib.pyplot.show",
"pymc3.Exponential",
"matplotlib.pyplot.legend",
"pymc3.math.exp",
"matplotlib.pyplot.figure",
"pymc3.traceplot",
"numpy.exp",
"pandas_datareader.data.get_data_google",
"matplotlib.pyplot.ylabel"
] | [((128, 145), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (142, 145), True, 'import numpy as np\n'), ((301, 333), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""daily returns in %"""'], {}), "('daily returns in %')\n", (311, 333), True, 'import matplotlib.pyplot as plt\n'), ((743, 775), 'pymc3.trace... |
# COPYRIGHT 2021. <NAME>. Boston University.
import random
import cv2
import numpy as np
import scipy.special
import torch
from evaluation.ope import overlap_ratio
from utils.anchor import Anchors
from utils.logging import get_logger
from utils import check_keys
from utils.optical_flow import OpticalFlowForVideo
from... | [
"utils.anchor.Anchors",
"utils.tracking_inference.bbox_clip",
"numpy.sum",
"numpy.argmax",
"numpy.mean",
"numpy.exp",
"utils.tracking_inference.convert_bbox",
"evaluation.ope.overlap_ratio",
"numpy.std",
"matplotlib.pyplot.imshow",
"cv2.cvtColor",
"utils.logging.get_logger",
"numpy.hanning",... | [((833, 929), 'utils.anchor.Anchors', 'Anchors', (['self.inf_cfg.ANCHOR.STRIDE', 'self.inf_cfg.ANCHOR.RATIOS', 'self.inf_cfg.ANCHOR.SCALES'], {}), '(self.inf_cfg.ANCHOR.STRIDE, self.inf_cfg.ANCHOR.RATIOS, self.\n inf_cfg.ANCHOR.SCALES)\n', (840, 929), False, 'from utils.anchor import Anchors\n'), ((1293, 1389), 'uti... |
import warnings
warnings.filterwarnings(action='ignore',category = DeprecationWarning)
warnings.simplefilter(action='ignore',category = DeprecationWarning)
import pandas as pd
pd.reset_option('all')
import numpy as np
import statsmodels.api as sm
from skopt import BayesSearchCV
from sklearn.model_selection import Ran... | [
"matplotlib.pyplot.title",
"pickle.dump",
"random.shuffle",
"joblib.dump",
"os.path.isfile",
"matplotlib.pyplot.figure",
"pickle.load",
"matplotlib.pyplot.tight_layout",
"environment.make",
"pandas.DataFrame",
"warnings.simplefilter",
"pandas.reset_option",
"sklearn.model_selection.Randomize... | [((16, 85), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '"""ignore"""', 'category': 'DeprecationWarning'}), "(action='ignore', category=DeprecationWarning)\n", (39, 85), False, 'import warnings\n'), ((87, 154), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', '... |
import argparse
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
from yacs.config import CfgNode as CN
from executor import Tester, Trainer, Debugger
MODES = ['train', 'test', 'debug']
parser = argparse.ArgumentParser()
parser.add_argument('phase', choices=MODES)
p... | [
"executor.Tester",
"numpy.random.seed",
"argparse.ArgumentParser",
"os.path.basename",
"yacs.config.CfgNode.load_cfg",
"executor.Debugger",
"tensorflow.set_random_seed",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.compat.v1.logging.set_verbosity",
"os.path.splitext",
"e... | [((249, 274), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (272, 274), False, 'import argparse\n'), ((626, 688), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.ERROR'], {}), '(tf.compat.v1.logging.ERROR)\n', (660, 688), True, 'impor... |
import logging
import numpy as np
from sklearn.model_selection import cross_val_score
from xgboost import XGBClassifier
from bayes_opt import BayesianOptimization
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
LO... | [
"bayes_opt.BayesianOptimization",
"logging.StreamHandler",
"logging.Formatter",
"numpy.array",
"logging.getLogger"
] | [((176, 199), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (197, 199), False, 'import logging\n'), ((212, 285), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (229, 285),... |
import torch, torch.nn as nn, torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.transforms as T
import torchvision.models as models
# from maskrcnn_benchmark.data.transforms import Resize, ToTensor, Normalize
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_... | [
"maskrcnn_benchmark.structures.bounding_box.BoxList",
"scipy.ndimage.find_objects",
"numpy.clip",
"numpy.argsort",
"os.path.isfile",
"pickle.load",
"torch.arange",
"torchvision.transforms.Normalize",
"torch.no_grad",
"numpy.sqrt",
"torch.nn.functional.pad",
"traceback.print_exc",
"numpy.zero... | [((977, 999), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (987, 999), False, 'import torch, torch.nn as nn, torch.nn.functional as F\n'), ((1203, 1218), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1216, 1218), False, 'import torch, torch.nn as nn, torch.nn.functional as F\n'), ((1548, 1... |
"""Module containing optimized ridge regression. Original implementation by
<NAME>, available here: https://github.com/alexhuth/ridge
Refactoring and modifications by <NAME> di <NAME>"""
import numpy as np
import itertools as itools
import logging
import random
import sys
from numpy.linalg import multi_dot
from sci... | [
"numpy.dstack",
"numpy.load",
"numpy.sum",
"numpy.nan_to_num",
"numpy.ones_like",
"numpy.argmax",
"numpy.abs",
"random.shuffle",
"numpy.asarray",
"logging.StreamHandler",
"numpy.zeros",
"logging.Formatter",
"scipy.linalg.svd",
"numpy.array",
"numpy.sign",
"numpy.dot",
"itertools.chai... | [((390, 421), 'logging.getLogger', 'logging.getLogger', (['"""ridge_corr"""'], {}), "('ridge_corr')\n", (407, 421), False, 'import logging\n'), ((464, 497), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (485, 497), False, 'import logging\n'), ((537, 610), 'logging.Formatter',... |
import pandas as pd
import numpy as np
import time
numMin = []
numMax = []
numAvg = []
# Time series 11.00, 11:05, 11:10, 11:15, 11:20
ts = pd.date_range("11:00", "11:20", freq="5min")
for i in range(5):
numMin.append(np.random.randint(1,high=3))
numMax.append(np.random.randint(10,high=15))
numA... | [
"pandas.DataFrame",
"numpy.random.randint",
"pandas.date_range"
] | [((149, 193), 'pandas.date_range', 'pd.date_range', (['"""11:00"""', '"""11:20"""'], {'freq': '"""5min"""'}), "('11:00', '11:20', freq='5min')\n", (162, 193), True, 'import pandas as pd\n'), ((368, 439), 'pandas.DataFrame', 'pd.DataFrame', (["{'time': ts, 'min': numMin, 'max': numMax, 'avg': numAvg}"], {}), "({'time': ... |
import sys, os
#os.chdir('../../') #get rid of this at some point with central test script or when package is built
import MSI.simulations.instruments.shock_tube as st
import MSI.cti_core.cti_processor as pr
import MSI.optimization.matrix_loader as ml
import MSI.optimization.opt_runner as opt
import MSI.simulations.... | [
"pandas.DataFrame",
"numpy.log",
"MSI.utilities.plotting_script.Plotting",
"MSI.optimization.shock_tube_optimization_shell.MSI_shocktube_optimization",
"numpy.array",
"cantera.Solution",
"numpy.sqrt"
] | [((2761, 2920), 'MSI.optimization.shock_tube_optimization_shell.MSI_shocktube_optimization', 'stMSI.MSI_shocktube_optimization', (['cti_file', '(0.01)', '(1)', '(1)', 'working_directory', 'files_to_include', 'reaction_uncertainty_csv', 'rate_constant_target_value_data'], {}), '(cti_file, 0.01, 1, 1, working_directory,\... |
# TODO: Explicitly import each decorator in release
from typing import List
from pandas import DataFrame
from europy.decorator import test, bias, data_bias, fairness, transparency, accountability, unit, integration, \
minimum_functionality, model_details, using_params
from europy.decorator.factories import deco... | [
"yaml.load",
"numpy.random.seed",
"europy.lifecycle.reporting.generate_report",
"matplotlib.pyplot.style.use",
"numpy.sin",
"europy.decorator.integration",
"europy.decorator.using_params",
"europy.decorator.data_bias",
"pandas.DataFrame",
"europy.decorator.minimum_functionality",
"numpy.random.r... | [((865, 919), 'pandas.DataFrame', 'DataFrame', (['[[1, 2], [3, 4]]'], {'columns': "['odds', 'evens']"}), "([[1, 2], [3, 4]], columns=['odds', 'evens'])\n", (874, 919), False, 'from pandas import DataFrame\n'), ((1610, 1658), 'europy.decorator.test', 'test', (['EXAMPLE_LABEL_NAME', '"""My custom label test"""'], {}), "(... |
"""
Function:rnn 测试
Author:lzb
Date:2021.02.15
"""
import numpy as np
from activation.last_hop_activation import SoftMaxLHA
from activation.normal_activation import Sigmoid, ReLU, LeakyReLU
from loss.loss import CrossEntropyLoss
from rnn import rnn_poem_recitation
from sample.one_poem_sample import OnePoemSample
d... | [
"sample.one_poem_sample.OnePoemSample",
"loss.loss.CrossEntropyLoss",
"activation.last_hop_activation.SoftMaxLHA",
"numpy.asarray",
"activation.normal_activation.LeakyReLU",
"rnn.rnn_poem_recitation.PoemRecitation"
] | [((546, 559), 'activation.normal_activation.LeakyReLU', 'LeakyReLU', (['(20)'], {}), '(20)\n', (555, 559), False, 'from activation.normal_activation import Sigmoid, ReLU, LeakyReLU\n'), ((602, 614), 'activation.last_hop_activation.SoftMaxLHA', 'SoftMaxLHA', ([], {}), '()\n', (612, 614), False, 'from activation.last_hop... |
from __future__ import absolute_import
from __future__ import print_function
import random
random.seed(9001)
import os
import sys
sys.path.append('..')
import argparse
import chainer
import numpy as np
#from datasets.datasets import get_mvmc, get_mvmc_flatten
from datasets.mnist import get_mnist
import deepopt.choo... | [
"sys.path.append",
"datasets.mnist.get_mnist",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"random.seed",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.s... | [((92, 109), 'random.seed', 'random.seed', (['(9001)'], {}), '(9001)\n', (103, 109), False, 'import random\n'), ((132, 153), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (147, 153), False, 'import sys\n'), ((2354, 2382), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6.5)'}), '... |
usage = \
"""
Usage:
python diagnostic-ion-checker.py -mgf mgf_containing_folder -marker 204.087,138.055
Output:
marker-ion.csv in the mgf_containing_folder
Some candidate marker ions:
| Marker | Glyco | Formula w/o proton |
| --------| ---------------- | ------------------ |
... | [
"pandas.DataFrame",
"Y_ion_extractor.get_ms2_reader",
"os.path.isdir",
"numpy.max",
"numpy.array",
"os.path.split",
"os.path.join",
"os.listdir",
"sys.exit"
] | [((2515, 2537), 'numpy.array', 'np.array', (['matched_list'], {}), '(matched_list)\n', (2523, 2537), True, 'import numpy as np\n'), ((2548, 2566), 'pandas.DataFrame', 'pd.DataFrame', (['None'], {}), '(None)\n', (2560, 2566), True, 'import pandas as pd\n'), ((3032, 3059), 'os.path.isdir', 'os.path.isdir', (["argd['-mgf'... |
# script: Data generator. Reads cropped objects pickles and background images and generates image datasets.
# author: <NAME>
import cv2
import numpy as np
import os
import sys
import pickle
import random
import imutils
import argparse
def rndint(l,h):
return np.random.randint(l, h)
def resize(img):
ratio = n... | [
"numpy.random.uniform",
"random.randint",
"argparse.ArgumentParser",
"os.makedirs",
"cv2.cvtColor",
"cv2.imwrite",
"numpy.float32",
"os.walk",
"numpy.zeros",
"os.path.exists",
"cv2.warpAffine",
"cv2.imread",
"numpy.random.randint",
"pickle.load",
"cv2.getAffineTransform",
"imutils.rota... | [((265, 288), 'numpy.random.randint', 'np.random.randint', (['l', 'h'], {}), '(l, h)\n', (282, 288), True, 'import numpy as np\n'), ((319, 347), 'numpy.random.uniform', 'np.random.uniform', (['(0.01)', '(0.5)'], {}), '(0.01, 0.5)\n', (336, 347), True, 'import numpy as np\n'), ((361, 388), 'numpy.random.uniform', 'np.ra... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 14:01:23 2020
Computes panel 2A and 2B (plot + stats)
Console output is redirected to the saveDir
@author: Ludovic.spaeth
"""
#-------------------------------------------------------------------------------
#---------------------Adjust dataSource and sav... | [
"numpy.isnan",
"pingouin.anova",
"matplotlib.pyplot.tight_layout",
"numpy.nanmean",
"pandas.DataFrame",
"scipy.stats.mannwhitneyu",
"seaborn.swarmplot",
"matplotlib.pyplot.subplots",
"pandas.concat",
"numpy.nansum",
"scipy.stats.kruskal",
"scipy.stats.shapiro",
"seaborn.boxplot",
"scipy.st... | [((1989, 2024), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '(10, 9)'}), '(1, 4, figsize=(10, 9))\n', (2001, 2024), True, 'import matplotlib.pyplot as plt\n'), ((2389, 2407), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2405, 2407), True, 'import matplotlib.pyp... |
import os
import numpy as np
from numpy.testing.decorators import skipif
from numpy.testing import assert_raises, assert_equal, assert_allclose
from skimage import data_dir
from skimage.io.collection import MultiImage
try:
from PIL import Image
except ImportError:
PIL_available = False
else:
PIL_availabl... | [
"numpy.testing.run_module_suite",
"numpy.testing.assert_raises",
"numpy.testing.decorators.skipif",
"numpy.testing.assert_allclose",
"os.path.join"
] | [((616, 641), 'numpy.testing.decorators.skipif', 'skipif', (['(not PIL_available)'], {}), '(not PIL_available)\n', (622, 641), False, 'from numpy.testing.decorators import skipif\n'), ((706, 731), 'numpy.testing.decorators.skipif', 'skipif', (['(not PIL_available)'], {}), '(not PIL_available)\n', (712, 731), False, 'fr... |
# Library imports
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
from sklearn_extra.cluster import KMedoids
import numpy as np
# Return: this function returns the cluster labels after hierarchical clustering
# Input: input a distance matrix
def cluster_agglomerative(d... | [
"sklearn.metrics.silhouette_score",
"sklearn.cluster.AgglomerativeClustering",
"numpy.asarray",
"sklearn_extra.cluster.KMedoids"
] | [((955, 995), 'numpy.asarray', 'np.asarray', (['distance_matrix'], {'dtype': 'float'}), '(distance_matrix, dtype=float)\n', (965, 995), True, 'import numpy as np\n'), ((2220, 2315), 'sklearn_extra.cluster.KMedoids', 'KMedoids', ([], {'n_clusters': 'opt_n_clusters', 'metric': '"""precomputed"""', 'method': '"""pam"""', ... |
import gym
import numpy as np
class RewardScalingEnv(gym.RewardWrapper):
def __init__(self,
env: gym.Wrapper,
discount: float,
):
"""
Keeps track of all observed rewards and scales them by dividing by the current standard deviation of a rolling
... | [
"numpy.std"
] | [((768, 793), 'numpy.std', 'np.std', (['self.rolling_sums'], {}), '(self.rolling_sums)\n', (774, 793), True, 'import numpy as np\n'), ((877, 902), 'numpy.std', 'np.std', (['self.rolling_sums'], {}), '(self.rolling_sums)\n', (883, 902), True, 'import numpy as np\n')] |
import brainiak.isfc
from brainiak import image, io
import numpy as np
import os
def test_ISC():
# Create dataset in which one voxel is highly correlated across subjects
# and the other is not
D = np.zeros((2, 5, 3))
D[:, :, 0] = \
[[-0.36225433, -0.43482456, 0.26723158, 0.16461712, -0.37991... | [
"numpy.absolute",
"numpy.abs",
"os.path.dirname",
"numpy.zeros",
"brainiak.io.load_boolean_mask",
"numpy.isclose",
"numpy.array",
"os.path.join",
"brainiak.io.load_images"
] | [((211, 230), 'numpy.zeros', 'np.zeros', (['(2, 5, 3)'], {}), '((2, 5, 3))\n', (219, 230), True, 'import numpy as np\n'), ((1686, 1711), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1701, 1711), False, 'import os\n'), ((1730, 1767), 'os.path.join', 'os.path.join', (['curr_dir', '"""mask.ni... |
#!/usr/bin/env python3
"""
Analyze a point target in a complex*8 file.
"""
import sys
import numpy as np
desc = __doc__
def get_chip (x, i, j, nchip=64):
i = int(i)
j = int(j)
chip = np.zeros ((nchip,nchip), dtype=x.dtype)
nchip2 = nchip // 2
i0 = i - nchip2 + 1
i1 = i0 + nchip
j0 = j - n... | [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"numpy.abs",
"numpy.argmax",
"numpy.angle",
"numpy.asarray",
"numpy.zeros",
"numpy.unravel_index",
"numpy.argmin",
"json.dumps",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.fft.fft2",
"numpy.exp",
"numpy.memmap",
"numpy.fft.if... | [((198, 237), 'numpy.zeros', 'np.zeros', (['(nchip, nchip)'], {'dtype': 'x.dtype'}), '((nchip, nchip), dtype=x.dtype)\n', (206, 237), True, 'import numpy as np\n'), ((580, 598), 'numpy.angle', 'np.angle', (['[cx, cy]'], {}), '([cx, cy])\n', (588, 598), True, 'import numpy as np\n'), ((718, 739), 'numpy.exp', 'np.exp', ... |
#-*- coding:utf-8 -*-
from io import BytesIO
import time
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import oss2 as oss
import apex
from apex.parallel import DistributedDataParallel as DDP
from apex import amp
from model i... | [
"apex.amp.state_dict",
"utils.evaluation_util.LogCollector",
"utils.evaluation_util.AverageMeter",
"torch.device",
"data.imagenet_loader.ImageNetLoader",
"torch.nn.functional.normalize",
"utils.params_util.collect_params",
"apex.amp.scale_loss",
"torch.cuda.set_device",
"datetime.datetime.now",
... | [((1945, 1970), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1968, 1970), False, 'import torch\n'), ((2728, 2765), 'oss2.Auth', 'oss.Auth', (['ckpt_key_id', 'ckpt_secret_id'], {}), '(ckpt_key_id, ckpt_secret_id)\n', (2736, 2765), True, 'import oss2 as oss\n'), ((3074, 3098), 'utils.evaluatio... |
import numpy as np
class Solution:
def isValidArray(self, arr):
elements = set()
for num in arr.flatten():
if num != '.':
if num in elements:
return False
elements.add(num)
return True
def isValidSudoku(self, board):
... | [
"numpy.array"
] | [((419, 434), 'numpy.array', 'np.array', (['board'], {}), '(board)\n', (427, 434), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 26 16:34:40 EDT 2017
@author: ben
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, <NAME>"
__license__ = "MIT"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
__status__ = "Development"
import sys
import os
import numpy as np
import h5py
import mh5utils as mh5u... | [
"mh5utils.Attrib",
"numpy.cbrt",
"numpy.power",
"os.uname",
"numpy.append",
"numpy.arange",
"numpy.array",
"numpy.linspace",
"mh5utils.DataSet",
"datetime.datetime.now",
"numpy.concatenate"
] | [((533, 565), 'numpy.cbrt', 'np.cbrt', (['(3.0 * v / (4.0 * np.pi))'], {}), '(3.0 * v / (4.0 * np.pi))\n', (540, 565), True, 'import numpy as np\n'), ((1059, 1098), 'mh5utils.Attrib', 'mh5u.Attrib', (['"""Temperature"""', 'temperature'], {}), "('Temperature', temperature)\n", (1070, 1098), True, 'import mh5utils as mh5... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 20:37:13 2021
@author: Usuari
5. Watch a Smart Agent!
In the next code cell, you will load the trained weights from file to watch a smart agent!
"""
from utilities import envs
from utilities.buffer import ReplayBuffer, ReplayBuffer_SummTree
from algorithms.ddpg.maddpg... | [
"matplotlib.pyplot.title",
"numpy.random.seed",
"numpy.sum",
"matplotlib.pyplot.figure",
"torch.set_num_threads",
"numpy.mean",
"pickle.load",
"matplotlib.pyplot.tick_params",
"utilities.envs.make_parallel_env",
"matplotlib.pyplot.hlines",
"numpy.std",
"torch.load",
"numpy.rollaxis",
"conf... | [((950, 964), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (962, 964), False, 'from configparser import ConfigParser\n'), ((4068, 4088), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (4082, 4088), True, 'import numpy as np\n'), ((4093, 4116), 'torch.manual_seed', 'torch.manual_see... |
import numpy as np
import keras.backend as K
from keras.engine.topology import preprocess_weights_for_loading
import warnings
def RGB2Hex(R, G, B):
assert R in range(256) and G in range(256) and B in range(256)
return '0x' + '%06x' % (R * 256**2 + G * 256 + B)
def mask2bbox(mask, mode='xywh'):
'''
@in... | [
"keras.engine.topology.preprocess_weights_for_loading",
"numpy.min",
"numpy.where",
"keras.backend.batch_set_value",
"pprint.pprint",
"numpy.max",
"pdb.set_trace",
"keras.backend.int_shape",
"warnings.warn"
] | [((603, 617), 'numpy.where', 'np.where', (['mask'], {}), '(mask)\n', (611, 617), True, 'import numpy as np\n'), ((1763, 1801), 'keras.backend.batch_set_value', 'K.batch_set_value', (['weight_value_tuples'], {}), '(weight_value_tuples)\n', (1780, 1801), True, 'import keras.backend as K\n'), ((6667, 6705), 'keras.backend... |
# -*- coding: utf-8 -*-
"""
Created on 2020/7/9 12:32 下午
@File: univariate.py
@Department: AI Lab, Rockontrol, Chengdu
@Author: luolei
@Email: <EMAIL>
@Describe: 单变量分箱
"""
from lake.decorator import time_cost
import pandas as pd
import numpy as np
import logging
import warnings
from typing import Union
from ..dat... | [
"pandas.DataFrame",
"logging.basicConfig",
"numpy.std",
"numpy.isnan",
"numpy.percentile",
"numpy.sort",
"numpy.histogram",
"numpy.mean",
"numpy.array",
"numpy.min",
"numpy.max"
] | [((402, 441), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (421, 441), False, 'import logging\n'), ((750, 760), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (757, 760), True, 'import numpy as np\n'), ((772, 781), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', ... |
#!/usr/bin/env python
import itertools as it
import os.path as op
import numpy as np
import fsleyes.displaycontext.meshopts as meshopts
import fsl.data.image as fslimage
import fsl.data.vtk as fslvtk
import fsl.utils.image.resample as resample
from fsleyes.tests import run_with_orthopanel
datadir = op.join(op... | [
"fsl.utils.image.resample.resampleToPixdims",
"os.path.dirname",
"itertools.permutations",
"fsl.data.image.Image",
"fsleyes.tests.run_with_orthopanel",
"numpy.isclose",
"numpy.array",
"os.path.join"
] | [((318, 338), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (328, 338), True, 'import os.path as op\n'), ((386, 428), 'fsleyes.tests.run_with_orthopanel', 'run_with_orthopanel', (['_test_transformCoords'], {}), '(_test_transformCoords)\n', (405, 428), False, 'from fsleyes.tests import run_with_or... |
'''
This code is part of QuTIpy.
(c) Copyright <NAME>, 2021
This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of t... | [
"numpy.log2",
"scipy.linalg.fractional_matrix_power"
] | [((818, 877), 'scipy.linalg.fractional_matrix_power', 'fractional_matrix_power', (['sigma', '((1.0 - alpha) / (2 * alpha))'], {}), '(sigma, (1.0 - alpha) / (2 * alpha))\n', (841, 877), False, 'from scipy.linalg import fractional_matrix_power\n'), ((969, 979), 'numpy.log2', 'np.log2', (['Q'], {}), '(Q)\n', (976, 979), T... |
import json
from typing import List, Dict, Tuple
from podm.podm import BoundingBox, MetricPerClass
import numpy as np
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UND... | [
"numpy.allclose",
"json.load",
"podm.podm.BoundingBox"
] | [((443, 456), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (452, 456), False, 'import json\n'), ((1081, 1094), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (1090, 1094), False, 'import json\n'), ((1234, 1400), 'podm.podm.BoundingBox', 'BoundingBox', (["box['image_id']", "label_map[box['category_id']]", "box['... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 2016
@author: michielstock
A small demonstration of simulated annealing
"""
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
def one_dimensional_simulated_annealing(f, x0, hyperparameters):
"""
Simple simulated annealing for a on... | [
"numpy.abs",
"numpy.random.randn",
"numpy.exp",
"numpy.cos",
"numpy.random.rand",
"matplotlib.pyplot.subplots"
] | [((2084, 2122), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'figsize': '(5, 10)'}), '(nrows=3, figsize=(5, 10))\n', (2096, 2122), True, 'import matplotlib.pyplot as plt\n'), ((3138, 3176), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'figsize': '(5, 10)'}), '(nrows=3, figs... |
def find_rigid_transform(a, b, visualize=False):
"""
Args:
a: a 3xN array of vertex locations
b: a 3xN array of vertex locations
Returns: (R,T) such that R.dot(a)+T ~= b
Based on Arun et al, "Least-squares fitting of two 3-D point sets," 1987.
See also Eggert et al, "Estimating 3-D ... | [
"lace.meshviewer.MeshViewer",
"numpy.any",
"numpy.linalg.svd",
"numpy.mean",
"lace.mesh.Mesh"
] | [((666, 684), 'numpy.mean', 'np.mean', (['a'], {'axis': '(1)'}), '(a, axis=1)\n', (673, 684), True, 'import numpy as np\n'), ((698, 716), 'numpy.mean', 'np.mean', (['b'], {'axis': '(1)'}), '(b, axis=1)\n', (705, 716), True, 'import numpy as np\n'), ((855, 892), 'numpy.linalg.svd', 'np.linalg.svd', (['c'], {'full_matric... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 18 11:52:51 2017
@author: student
"""
import pandas as pd
import numpy as np
import utm
import collections
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def loadCameras(directory_images,directory_metadata):
'''
loadCameras loads camera ... | [
"pandas.read_csv",
"numpy.sin",
"numpy.linalg.norm",
"glob.glob",
"pandas.DataFrame",
"utm.from_latlon",
"pandas.merge",
"numpy.transpose",
"os.path.basename",
"numpy.asarray",
"numpy.cross",
"numpy.linalg.inv",
"numpy.cos",
"numpy.arctan",
"pandas.to_numeric",
"numpy.deg2rad",
"PIL.... | [((1349, 1363), 'numpy.asarray', 'np.asarray', (['cn'], {}), '(cn)\n', (1359, 1363), True, 'import numpy as np\n'), ((1373, 1387), 'numpy.asarray', 'np.asarray', (['ce'], {}), '(ce)\n', (1383, 1387), True, 'import numpy as np\n'), ((3096, 3127), 'utm.from_latlon', 'utm.from_latlon', (['row[0]', 'row[1]'], {}), '(row[0]... |
'''a "Star" object to keep track of positions and propagate proper motions'''
import numpy as np
import astropy.coordinates
import astropy.units as u
from astroquery.gaia import Gaia
from astroquery.simbad import Simbad
from craftroom.Talker import Talker
# these are options for how the posstring can be represented
... | [
"numpy.size",
"numpy.abs",
"astroquery.simbad.Simbad.query_object",
"astroquery.simbad.Simbad.reset_votable_fields",
"numpy.isfinite",
"numpy.cos",
"craftroom.Talker.Talker.__init__",
"astroquery.simbad.Simbad.add_votable_fields",
"astroquery.gaia.Gaia.launch_job"
] | [((680, 701), 'craftroom.Talker.Talker.__init__', 'Talker.__init__', (['self'], {}), '(self)\n', (695, 701), False, 'from craftroom.Talker import Talker\n'), ((1304, 1322), 'numpy.size', 'np.size', (['self.icrs'], {}), '(self.icrs)\n', (1311, 1322), True, 'import numpy as np\n'), ((3503, 3532), 'astroquery.simbad.Simba... |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2020 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
import logging
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace
import numpy
import pytest
import yaml
try... | [
"pytest.importorskip",
"copy.deepcopy",
"datacube.utils.geometry.GeoBox",
"yaml.dump",
"pytest.fixture",
"xarray.open_dataset",
"yaml.load_all",
"pathlib.Path",
"pytest.raises",
"rasterio.Env",
"datacube.api.core.Datacube",
"affine.Affine",
"numpy.array_equal",
"pytest.mark.usefixtures",
... | [((667, 712), 'pytest.importorskip', 'pytest.importorskip', (['"""dcio_example.xarray_3d"""'], {}), "('dcio_example.xarray_3d')\n", (686, 712), False, 'import pytest\n'), ((768, 795), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (785, 795), False, 'import logging\n'), ((949, 1043), 'typ... |
# -*- coding: utf-8 -*-
import time
import numpy as np
import donkeycar as dk
#import math
class Lambda:
"""
Wraps a function into a donkey part.
"""
def __init__(self, f):
"""
Accepts the function to use.
"""
self.f = f
def run(self, *args, **kwargs):
retu... | [
"numpy.array",
"time.time"
] | [((1204, 1215), 'time.time', 'time.time', ([], {}), '()\n', (1213, 1215), False, 'import time\n'), ((5005, 5016), 'time.time', 'time.time', ([], {}), '()\n', (5014, 5016), False, 'import time\n'), ((5274, 5285), 'time.time', 'time.time', ([], {}), '()\n', (5283, 5285), False, 'import time\n'), ((2758, 2786), 'numpy.arr... |
# *****************************************************************************
# Copyright (c) 2019, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... | [
"numpy.sum",
"numpy.empty",
"numpy.empty_like",
"sdc.ros.read_ros_images",
"time.time",
"numpy.random.randint",
"sdc.prange"
] | [((2250, 2261), 'time.time', 'time.time', ([], {}), '()\n', (2259, 2261), False, 'import time\n'), ((2270, 2311), 'sdc.ros.read_ros_images', 'sdc.ros.read_ros_images', (['"""image_test.bag"""'], {}), "('image_test.bag')\n", (2293, 2311), False, 'import sdc\n'), ((2460, 2481), 'numpy.empty', 'np.empty', (['n', 'np.bool_... |
from survos2.frontend.plugins.pipelines import PipelinesComboBox
from survos2.frontend.plugins.features import FeatureComboBox
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from qtpy import QtWidgets
from qtpy.QtWidgets import QPushButton, QRadi... | [
"survos2.frontend.plugins.annotations.LevelComboBox",
"qtpy.QtWidgets.QFileDialog.getSaveFileName",
"survos2.server.state.cfg.ppw.clientEvent.emit",
"napari.qt.progress.progress",
"numpy.unique",
"survos2.model.DataModel.g.dataset_uri",
"survos2.frontend.plugins.features.FeatureComboBox",
"numpy.zeros... | [((2099, 2147), 'survos2.frontend.control.Launcher.g.run', 'Launcher.g.run', (['"""analyzer"""', '"""existing"""'], {}), "('analyzer', 'existing', **params)\n", (2113, 2147), False, 'from survos2.frontend.control import Launcher\n'), ((2562, 2610), 'survos2.frontend.control.Launcher.g.run', 'Launcher.g.run', (['"""anal... |
import logging
import numpy as np
from sklearn.cluster import KMeans
class ClusterLogging:
def __init__(self, logger=logging.Logger("logging")):
'''
By default, logger object in default configuration
'''
self.nodes={}
self.messages={}
self.nums=0
self.lo... | [
"sklearn.cluster.KMeans",
"numpy.max",
"logging.Logger"
] | [((124, 149), 'logging.Logger', 'logging.Logger', (['"""logging"""'], {}), "('logging')\n", (138, 149), False, 'import logging\n'), ((2290, 2338), 'sklearn.cluster.KMeans', 'KMeans', ([], {'init': '"""k-means++"""', 'n_clusters': 'numclusters'}), "(init='k-means++', n_clusters=numclusters)\n", (2296, 2338), False, 'fro... |
import tensorflow as tf
import numpy as np
import DeepLearning.DataCenter.DataProcessing as DataProcess
def prediction_accuracy(DataCenter, model, x_data, y_data):
''' Calculate prediction accuracy between x_data and y_data from a NN model
'''
x = DataCenter.x_placeholder
y = DataCenter.y_placeholder... | [
"numpy.argmax",
"tensorflow.argmax",
"numpy.zeros",
"DeepLearning.DataCenter.DataProcessing.combine_batches",
"tensorflow.cast",
"numpy.mean",
"numpy.concatenate"
] | [((348, 373), 'numpy.zeros', 'np.zeros', (['x_data.shape[0]'], {}), '(x_data.shape[0])\n', (356, 373), True, 'import numpy as np\n'), ((855, 902), 'numpy.zeros', 'np.zeros', (['DataCenter.val_input_batches.shape[0]'], {}), '(DataCenter.val_input_batches.shape[0])\n', (863, 902), True, 'import numpy as np\n'), ((1085, 1... |
import numpy as np
from .api_wrappers import COCOeval
def calc_area_range_info(area_range_type):
"""Calculate area ranges and related information."""
# use COCO setting as default
area_ranges = [[0**2, 1e5**2], [0**2, 32**2], [32**2, 96**2],
[96**2, 1e5**2]]
area_labels = ['all', 'small', 'medium', 'large... | [
"numpy.zeros",
"numpy.argsort",
"numpy.mean",
"numpy.array",
"numpy.arange",
"numpy.where",
"numpy.repeat"
] | [((3329, 3385), 'numpy.argsort', 'np.argsort', (["[g['_ignore'] for g in gt]"], {'kind': '"""mergesort"""'}), "([g['_ignore'] for g in gt], kind='mergesort')\n", (3339, 3385), True, 'import numpy as np\n'), ((3426, 3483), 'numpy.argsort', 'np.argsort', (["[(-d['score']) for d in dt]"], {'kind': '"""mergesort"""'}), "([... |
###################################################################
# PASSIVES.PY
#
# A library of functions, constants and more that are related to
# Inductors and Capacitors in Electrical Engineering.
#
# Written by <NAME>
#
# Special Thanks To:
# <NAME> - Idaho Power
# <NAME> - University of Idaho
#
# ... | [
"numpy.exp",
"numpy.sqrt"
] | [((8717, 8749), 'numpy.sqrt', 'np.sqrt', (['(vo ** 2 - 2 * P * t / C)'], {}), '(vo ** 2 - 2 * P * t / C)\n', (8724, 8749), True, 'import numpy as np\n'), ((1697, 1717), 'numpy.exp', 'np.exp', (['(-t / (R * C))'], {}), '(-t / (R * C))\n', (1703, 1717), True, 'import numpy as np\n'), ((3474, 3490), 'numpy.exp', 'np.exp',... |
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.array([0, 1])
y = np.array([0, 1])
ax.plot(x, y, linestyle=(0, (1, 0)))
ax.plot(x, y+1, linestyle=(0, (0, 1)))
ax.plot(x, y+2, linestyle=(0, (1, 1)))
ax.plot(x, y+3, linestyle=(0, (5, 1)))
ax.plot(x, y+4, linest... | [
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.show"
] | [((59, 71), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (69, 71), True, 'import matplotlib.pyplot as plt\n'), ((104, 120), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (112, 120), True, 'import numpy as np\n'), ((125, 141), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (133, 1... |
#CORNER DETECTION
import cv2
import numpy as np
img = cv2.imread('opencv-corner-detection-sample.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
corners = cv2.goodFeaturesToTrack(gray, 200, 0.01, 10)
corners = np.int0(corners)
for corner in corners:
x, y= corner.ravel()
cv2.circle... | [
"cv2.circle",
"numpy.int0",
"cv2.cvtColor",
"cv2.waitKey",
"numpy.float32",
"cv2.destroyAllWindows",
"cv2.imread",
"cv2.goodFeaturesToTrack",
"cv2.imshow"
] | [((56, 104), 'cv2.imread', 'cv2.imread', (['"""opencv-corner-detection-sample.jpg"""'], {}), "('opencv-corner-detection-sample.jpg')\n", (66, 104), False, 'import cv2\n'), ((112, 149), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (124, 149), False, 'import cv2\n'),... |
import numpy as np
import networkx as nx
import hnswlib
from gcn.distances import node2vec, node2vec_distances
def get_allowed_edges(adj, dataset):
embeddings = node2vec(adj, dataset)
print(embeddings.shape)
num_elements, dim = embeddings.shape
data_labels = np.arange(num_elements)
p = hnswlib.I... | [
"networkx.adjacency_matrix",
"numpy.sum",
"numpy.maximum",
"networkx.erdos_renyi_graph",
"numpy.asarray",
"numpy.square",
"gcn.distances.node2vec_distances",
"numpy.zeros",
"numpy.triu_indices",
"numpy.arange",
"numpy.linalg.norm",
"numpy.array_equal",
"numpy.dot",
"hnswlib.Index",
"gcn.... | [((167, 189), 'gcn.distances.node2vec', 'node2vec', (['adj', 'dataset'], {}), '(adj, dataset)\n', (175, 189), False, 'from gcn.distances import node2vec, node2vec_distances\n'), ((278, 301), 'numpy.arange', 'np.arange', (['num_elements'], {}), '(num_elements)\n', (287, 301), True, 'import numpy as np\n'), ((311, 345), ... |
# Copyright 2020 The TensorFlow Authors. 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 required by applica... | [
"numpy.random.randn",
"tensorflow.constant_initializer",
"tensorflow_addons.activations.snake.snake",
"numpy.random.rand",
"pytest.mark.parametrize",
"pytest.mark.usefixtures"
] | [((932, 986), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (955, 986), False, 'import pytest\n'), ((988, 1058), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dtype"""', '[np.float16, np.float32, np.float64]'], {}), ... |
import pytest
import numpy as np
import pandas as pd
from pypbl.elicitation import BayesPreference
from pypbl.priors import Normal, Exponential
@pytest.fixture
def basic_model():
data = pd.DataFrame({'x': [1, 0, 1], 'y': [0, 1, 1]}, index=['item 0', 'item 1', 'item 2'])
model = BayesPreference(data=data)
... | [
"pandas.DataFrame",
"pypbl.priors.Exponential",
"pytest.warns",
"pypbl.priors.Normal",
"pytest.main",
"pytest.raises",
"numpy.array",
"pytest.approx",
"pypbl.elicitation.BayesPreference"
] | [((194, 282), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': [1, 0, 1], 'y': [0, 1, 1]}"], {'index': "['item 0', 'item 1', 'item 2']"}), "({'x': [1, 0, 1], 'y': [0, 1, 1]}, index=['item 0', 'item 1',\n 'item 2'])\n", (206, 282), True, 'import pandas as pd\n'), ((291, 317), 'pypbl.elicitation.BayesPreference', 'BayesPr... |
#coding=utf-8
# Copyright 2017 - 2018 Baidu 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 a... | [
"sys.path.append",
"tensorflow.gfile.FastGFile",
"advbox.attacks.deepfool.DeepFoolAttack",
"logging.basicConfig",
"numpy.copy",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"PIL.Image.open",
"advbox.adversary.Adversary",
"logging.info",
"advbox.models.tensorflowPB.TensorflowP... | [((724, 745), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (739, 745), False, 'import sys\n'), ((761, 871), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(filename)s[line:%(lineno)d] %(levelname)s %(message)s"""'}), "(level=logging.INFO, format=\n ... |
import cv2
import numpy as np
def draw_contours(img, mask, color=(0, 255, 255)):
"""
Get outline of mask and draw it on the image
Args:
img: image on which to draw
mask: mask for which contours should be found
color: color of contours to draw
"""
contours = cv2.findContour... | [
"numpy.array"
] | [((1575, 1590), 'numpy.array', 'np.array', (['crops'], {}), '(crops)\n', (1583, 1590), True, 'import numpy as np\n')] |
import sys
import utils.serialize_iterable
import numpy as np
import json
from tqdm import tqdm
def load_matrix(filename, size, mode):
with open(filename) as input_file:
length = len(input_file.readline().rstrip().split()) - 1
if mode == 0:
length += 1
matrix = np.zeros((size, leng... | [
"tqdm.tqdm",
"numpy.max",
"numpy.zeros",
"numpy.arange"
] | [((300, 324), 'numpy.zeros', 'np.zeros', (['(size, length)'], {}), '((size, length))\n', (308, 324), True, 'import numpy as np\n'), ((1848, 1887), 'numpy.zeros', 'np.zeros', (['(track_size, matrix.shape[1])'], {}), '((track_size, matrix.shape[1]))\n', (1856, 1887), True, 'import numpy as np\n'), ((1907, 1945), 'numpy.a... |
import numpy as np
import numpy.matlib
import pandas as pd
import pvlib as pv
from scipy.interpolate import interp1d
DOY_LEAPDAY = 60
def _addHotwater(simData):
""" Calculate hot water demand profile in W
All load values are modified by a daily profile.
The profile values have to be scaled by each agen... | [
"pandas.DataFrame",
"pandas.date_range",
"pandas.read_hdf",
"pvlib.solarposition.get_solarposition",
"pandas.MultiIndex.from_tuples",
"pandas.read_csv",
"numpy.random.random",
"numpy.arange",
"numpy.array",
"pandas.to_datetime",
"scipy.interpolate.interp1d"
] | [((632, 733), 'pandas.read_hdf', 'pd.read_hdf', (['"""./BoundaryConditions/Thermal/HotWaterProfile/HotWaterDayProfile.h5"""'], {'key': '"""PHH"""'}), "(\n './BoundaryConditions/Thermal/HotWaterProfile/HotWaterDayProfile.h5',\n key='PHH')\n", (643, 733), True, 'import pandas as pd\n'), ((1931, 1999), 'pandas.read_... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, <NAME> and <NAME>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistrib... | [
"qutip.mesolve.mesolve",
"numpy.size",
"inspect.stack",
"qutip.expect.expect",
"qutip.operators.qeye",
"qutip.eseries.esval",
"qutip.eseries.esspec",
"qutip.odeoptions.Odeoptions",
"numpy.identity",
"qutip.states.ket2dm",
"numpy.where",
"qutip.essolve.ode2es",
"numpy.real",
"qutip.mcsolve.... | [((2603, 2615), 'qutip.odeoptions.Odeoptions', 'Odeoptions', ([], {}), '()\n', (2613, 2615), False, 'from qutip.odeoptions import Odeoptions\n'), ((4640, 4652), 'qutip.odeoptions.Odeoptions', 'Odeoptions', ([], {}), '()\n', (4650, 4652), False, 'from qutip.odeoptions import Odeoptions\n'), ((7459, 7471), 'qutip.odeopti... |
"""
This evaluation code is adapted from https://github.com/davidsbatista/NER-Evaluation/blob/master/example-full-named-entity-evaluation.ipynb
"""
import sys
sys.path.append("../")
from utils import *
import numpy as np
import copy
from copy import deepcopy
def count_by_label_type(preds, gold, list_of_pos_label_typ... | [
"sys.path.append",
"copy.deepcopy",
"numpy.logical_and",
"numpy.where",
"numpy.mean",
"collections.Counter"
] | [((160, 182), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (175, 182), False, 'import sys\n'), ((7402, 7421), 'collections.Counter', 'Counter', (['gold_range'], {}), '(gold_range)\n', (7409, 7421), False, 'from collections import Counter\n'), ((7438, 7457), 'collections.Counter', 'Counter', (... |
import numpy as np
import src.Planning.HybridAStar.Path as p
import src.Planning.HybridAStar.DubinCircle as dc
class FowardNonHolonomicMotionModel:
"""
wheel_max_angle: Maximum turning angle of the car.
num_angle_controls: Number of discrete wheel controls.
car_axis_length: Distance from front axel to... | [
"src.Planning.HybridAStar.Path.CircularPath",
"src.Planning.HybridAStar.Path.StraightPath",
"numpy.abs",
"src.Planning.HybridAStar.Path.angle_diff",
"numpy.tan",
"numpy.array",
"numpy.arange",
"numpy.cos",
"numpy.sign",
"numpy.sin"
] | [((1302, 1322), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (1310, 1322), True, 'import numpy as np\n'), ((1482, 1502), 'numpy.sign', 'np.sign', (['wheel_theta'], {}), '(wheel_theta)\n', (1489, 1502), True, 'import numpy as np\n'), ((950, 1019), 'numpy.arange', 'np.arange', (['(-wheel_max_angle)'... |
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict, deque, OrderedDict
from random import shuffle, choice
class Graph():
"""This class provides the basic functionality for graph handling."""
def __init__(self):
"""Initialize the di... | [
"collections.defaultdict",
"numpy.genfromtxt",
"argparse.ArgumentParser",
"collections.deque"
] | [((6982, 7293), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.RawDescriptionHelpFormatter', 'description': '""" EXERCISE 5\n ----------------------------\n find the longest shortest\n path with the dijkstra\n algo... |
from __future__ import division
import cv2
import time
import numpy as np
protoFile = "hand/pose_deploy.prototxt"
weightsFile = "hand/pose_iter_102000.caffemodel"
nPoints = 22
POSE_PAIRS = [ [0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[10,11],[11,12],[0,13],[13,14],[14,15],[15,16],[0,17],[17,18],[18,1... | [
"cv2.line",
"cv2.circle",
"numpy.copy",
"cv2.waitKey",
"cv2.imwrite",
"cv2.dnn.blobFromImage",
"time.time",
"cv2.imread",
"cv2.dnn.readNetFromCaffe",
"cv2.minMaxLoc",
"cv2.imshow",
"cv2.resize"
] | [((339, 387), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (['protoFile', 'weightsFile'], {}), '(protoFile, weightsFile)\n', (363, 387), False, 'import cv2\n'), ((397, 428), 'cv2.imread', 'cv2.imread', (['"""right-frontal.jpg"""'], {}), "('right-frontal.jpg')\n", (407, 428), False, 'import cv2\n'), ((441, 45... |
"""Hierarchical clustering methods and functions related to them.
Hierarchical clustering produces nested clusters from the data. The methods
here are based upon starting with each data point in a seperate cluster and
then successively joining the closest clusters until only one cluster remains.
A complete version h... | [
"numpy.abs",
"numpy.resize",
"numpy.argmax",
"numpy.allclose",
"numpy.ones",
"numpy.mean",
"numpy.prod",
"numpy.zeros_like",
"numpy.transpose",
"cluster.distances.append",
"cluster.stats.singleclustercentroid",
"cluster._support.mean",
"cluster.distances.distance",
"numpy.ptp",
"numpy.ze... | [((25968, 26012), 'numpy.resize', 'numpy.resize', (['distancematrix', '(2 * N - 1, N)'], {}), '(distancematrix, (2 * N - 1, N))\n', (25980, 26012), False, 'import numpy\n'), ((26088, 26140), 'numpy.resize', 'numpy.resize', (['distancematrix', '(2 * N - 1, 2 * N - 1)'], {}), '(distancematrix, (2 * N - 1, 2 * N - 1))\n',... |
import numpy as np
import paddle
import paddle.fluid as fluid
import pickle as pkl
from PIL import Image
import os
import glob
import csv
import random
class LoadData():
def __init__(self,mode):
self.mode = mode
self.datafile = 'data/omniglot/omniglot_' + self.mode + '.pkl'
print('loading o... | [
"numpy.stack",
"pickle.load",
"numpy.expand_dims"
] | [((645, 684), 'numpy.stack', 'np.stack', (['[self.data[i] for i in index]'], {}), '([self.data[i] for i in index])\n', (653, 684), True, 'import numpy as np\n'), ((701, 741), 'numpy.stack', 'np.stack', (['[self.label[i] for i in index]'], {}), '([self.label[i] for i in index])\n', (709, 741), True, 'import numpy as np\... |
import time
import json
import cv2
import random
import argparse
import numpy as np
from base64 import b64encode
import mdml_client as mdml # pip install mdml_client #
parser = argparse.ArgumentParser(description='MDML Benchmarking')
parser.add_argument('--host', dest='host', required=True, help='MDML hostname.')
par... | [
"argparse.ArgumentParser",
"time.sleep",
"random.random",
"numpy.random.randint",
"base64.b64encode",
"mdml_client.unix_time",
"cv2.imencode",
"mdml_client.experiment"
] | [((179, 235), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MDML Benchmarking"""'}), "(description='MDML Benchmarking')\n", (202, 235), False, 'import argparse\n'), ((1971, 2020), 'mdml_client.experiment', 'mdml.experiment', (['Exp_ID', 'username', 'password', 'host'], {}), '(Exp_ID, us... |
import cv2
import numpy as np
# Create a black image
img = np.zeros((512, 512, 3), np.uint8)
# Draw a diagonal blue line with thickness of 5 px
img = cv2.line(img, (0,0), (511, 511), (255, 0, 0), 5)
img = cv2.line(img, (0,511), (511, 0), (255, 0, 0), 5)
img = cv2.line(img, (255,0), (255, 511), (255, 0, 0), 5)
cv2.im... | [
"cv2.line",
"cv2.waitKey",
"cv2.imshow",
"numpy.zeros",
"cv2.destroyAllWindows"
] | [((60, 93), 'numpy.zeros', 'np.zeros', (['(512, 512, 3)', 'np.uint8'], {}), '((512, 512, 3), np.uint8)\n', (68, 93), True, 'import numpy as np\n'), ((152, 201), 'cv2.line', 'cv2.line', (['img', '(0, 0)', '(511, 511)', '(255, 0, 0)', '(5)'], {}), '(img, (0, 0), (511, 511), (255, 0, 0), 5)\n', (160, 201), False, 'import ... |
"""Shows the use of annotate without any type information.
The type information is extracted from the arguments passed
and the function is annotated and compiled at runtime.
"""
from pysph.cpy.api import annotate, Elementwise, wrap, get_config
import numpy as np
@annotate
def axpb(i, x, y, a, b):
xi = declare('d... | [
"pysph.cpy.api.wrap",
"numpy.zeros_like",
"pysph.cpy.api.Elementwise",
"numpy.linspace",
"pysph.cpy.api.get_config"
] | [((375, 399), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10000)'], {}), '(0, 1, 10000)\n', (386, 399), True, 'import numpy as np\n'), ((404, 420), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (417, 420), True, 'import numpy as np\n'), ((495, 522), 'pysph.cpy.api.wrap', 'wrap', (['x', 'y'], {'backe... |
from typing import Callable
import numpy as np
from engine.estimators.base_estimator import BaseEstimator
from engine.optimizers.base_optimizer import BaseOptimizer
from engine.optimizers.sgd_logistic import LogisticSGD
from engine.utils import projections
class LogisticRegression(BaseEstimator):
def __init__(sel... | [
"numpy.dot",
"engine.optimizers.sgd_logistic.LogisticSGD",
"numpy.zeros"
] | [((350, 372), 'engine.optimizers.sgd_logistic.LogisticSGD', 'LogisticSGD', (['(2)', '(0.0001)'], {}), '(2, 0.0001)\n', (361, 372), False, 'from engine.optimizers.sgd_logistic import LogisticSGD\n'), ((559, 570), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (567, 570), True, 'import numpy as np\n'), ((1129, 1146),... |
# Copyright 2021 DeepMind Technologies Limited. 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 required by ... | [
"numpy.full",
"absl.testing.absltest.main",
"chex.assert_shape",
"distrax._src.bijectors.block.Block",
"numpy.zeros",
"numpy.ones",
"jax.random.PRNGKey",
"distrax._src.bijectors.tanh.Tanh",
"numpy.array",
"distrax._src.bijectors.lambda_bijector.Lambda",
"chex.assert_equal",
"distrax._src.bijec... | [((11796, 11811), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (11809, 11811), False, 'from absl.testing import absltest\n'), ((3152, 3188), 'distrax._src.bijectors.tfp_compatible_bijector.tfp_compatible_bijector', 'tfp_compatible_bijector', (['dx_bijector'], {}), '(dx_bijector)\n', (3175, 3188), Fa... |
# Python API to call the matlab implementation the TargetShift and LS_TargetShift in Kun et. al. ICML'2013
# author: <NAME>
# Reference:
# - Zhang, Scholkopf, <NAME> "Domain Adaptation under Target and Conditional Shift" ICML'13
# URL: http://proceedings.mlr.press/v28/zhang13d.pdf
# Source code for the matlab version:... | [
"matlab.double",
"math.sqrt",
"numpy.median",
"sklearn.metrics.pairwise.euclidean_distances",
"matlab.engine.start_matlab",
"numpy.array",
"numpy.triu_indices_from",
"numpy.prod",
"numpy.sqrt"
] | [((621, 649), 'matlab.engine.start_matlab', 'matlab.engine.start_matlab', ([], {}), '()\n', (647, 649), False, 'import matlab\n'), ((2152, 2168), 'matlab.double', 'matlab.double', (['X'], {}), '(X)\n', (2165, 2168), False, 'import matlab\n'), ((2178, 2194), 'matlab.double', 'matlab.double', (['y'], {}), '(y)\n', (2191,... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
import numpy as np
from functools import reduce
from operator import mul
from operator import add
from subprocess import run
g_random_sparse_mask = np.random.RandomState()
g_random_data = np.random.RandomState()
g_random_labels = np.random.RandomState... | [
"subprocess.run",
"numpy.sum",
"numpy.empty",
"os.path.dirname",
"numpy.zeros",
"numpy.ones",
"numpy.random.RandomState",
"numpy.array",
"numpy.reshape",
"numpy.kron",
"functools.reduce",
"os.path.join",
"numpy.all"
] | [((217, 240), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (238, 240), True, 'import numpy as np\n'), ((257, 280), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (278, 280), True, 'import numpy as np\n'), ((299, 322), 'numpy.random.RandomState', 'np.random.RandomState',... |
#!/usr/bin/env python
import rospy
import math
import numpy
import tf
import std_msgs.msg
import gazebo_msgs.msg
import geometry_msgs.msg
import asctec_hl_comm.msg
import tf.transformations
node_name = 'gazebo_topics'
class Publisher:
def __init__(self, robot_name, world_name, tf_publisher, pose_publisher, vel... | [
"numpy.matrix",
"rospy.Time.now",
"tf.TransformBroadcaster",
"math.sin",
"rospy.get_param",
"rospy.init_node",
"math.cos",
"tf.transformations.euler_from_quaternion",
"rospy.spin"
] | [((5811, 5837), 'rospy.init_node', 'rospy.init_node', (['node_name'], {}), '(node_name)\n', (5826, 5837), False, 'import rospy\n'), ((5867, 5886), 'rospy.get_param', 'rospy.get_param', (['""""""'], {}), "('')\n", (5882, 5886), False, 'import rospy\n'), ((5930, 5955), 'tf.TransformBroadcaster', 'tf.TransformBroadcaster'... |
import pytest
from utils import *
import numpy as np
import qcdb
# system-shorthand tot-chg, frag-chg, tot-mult, frag-mult expected final tot/frag chg/mult
def test_validate_and_fill_chgmult_1():
chgmult_tester(['He', 0, [0], 1, [1], (0, [0], 1, [1])])
def test_validate_and_fill_chgmult_2():
ch... | [
"pytest.raises",
"numpy.array",
"qcdb.molparse.validate_and_fill_chgmult"
] | [((11402, 11515), 'qcdb.molparse.validate_and_fill_chgmult', 'qcdb.molparse.validate_and_fill_chgmult', (['system[0]', 'system[1]', 'test[1]', 'test[2]', 'test[3]', 'test[4]'], {'verbose': '(0)'}), '(system[0], system[1], test[1], test\n [2], test[3], test[4], verbose=0)\n', (11441, 11515), False, 'import qcdb\n'), ... |
#
# Copyright (C) 2019 <NAME>
# University of Siena - Artificial Intelligence Laboratory - SAILab
#
# Inspired by the work of <NAME> (C) 2017: https://github.com/dj-on-github/sp800_22_tests
#
# NistRng is licensed under a BSD 3-Clause.
#
# You should have received a copy of the license along with this
# work. If not, s... | [
"numpy.fft.fft",
"math.log",
"numpy.array",
"math.sqrt"
] | [((1838, 1862), 'numpy.fft.fft', 'numpy.fft.fft', (['bits_copy'], {}), '(bits_copy)\n', (1851, 1862), False, 'import numpy\n'), ((2657, 2700), 'math.sqrt', 'math.sqrt', (['(bits_copy.size * 0.95 * 0.05 / 4)'], {}), '(bits_copy.size * 0.95 * 0.05 / 4)\n', (2666, 2700), False, 'import math\n'), ((2951, 2969), 'numpy.arra... |
import cv2
import numpy as np
def get_iou(bb1, bb2):
"""
Taken from: https://stackoverflow.com/questions/25349178/calculating-percentage-of-bounding-box-overlap-for-image-detector-evaluation
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
... | [
"numpy.size",
"numpy.subtract",
"numpy.copy",
"numpy.less",
"numpy.asarray",
"cv2.copyMakeBorder",
"numpy.clip",
"numpy.array_equal",
"cv2.resize"
] | [((7593, 7637), 'numpy.array_equal', 'np.array_equal', (['input_image_shape', 'dst_shape'], {}), '(input_image_shape, dst_shape)\n', (7607, 7637), True, 'import numpy as np\n'), ((7862, 7903), 'numpy.subtract', 'np.subtract', (['dst_shape', 'input_image_shape'], {}), '(dst_shape, input_image_shape)\n', (7873, 7903), Tr... |
"""An extension of NN_api, used for gradient checking (to ensure that the gradients computed via backprop are correct).
We manually perturb each weight matrix element and bias vector element, which allows us to compute the loss function
with respect to said parameter. We compare this with the gradient calculated via ba... | [
"numpy.load",
"numpy.sum",
"numpy.reshape"
] | [((11586, 11624), 'numpy.load', 'np.load', (['"""data/fashion-train-imgs.npz"""'], {}), "('data/fashion-train-imgs.npz')\n", (11593, 11624), True, 'import numpy as np\n'), ((11647, 11687), 'numpy.load', 'np.load', (['"""data/fashion-train-labels.npz"""'], {}), "('data/fashion-train-labels.npz')\n", (11654, 11687), True... |
from utils.typing import assert_type
from utils.Recording import Recording
from utils.Window import Window
from utils.array_operations import transform_to_subarrays
from typing import Union
import itertools
import numpy as np
import os
import pandas as pd
import utils.settings as settings
class Windowizer:
stride... | [
"utils.array_operations.transform_to_subarrays",
"utils.typing.assert_type",
"numpy.where",
"utils.Window.Window",
"itertools.chain.from_iterable"
] | [((658, 699), 'utils.typing.assert_type', 'assert_type', (['[(recordings[0], Recording)]'], {}), '([(recordings[0], Recording)])\n', (669, 699), False, 'from utils.typing import assert_type\n'), ((2063, 2104), 'utils.typing.assert_type', 'assert_type', (['[(recordings[0], Recording)]'], {}), '([(recordings[0], Recordin... |
from typing import Dict, List, Tuple
import numpy as np
import tensorflow as tf
import torch as t
from keras import Sequential, utils, regularizers
from keras.layers import Embedding, GlobalAveragePooling1D, Dense
from keras_preprocessing import sequence
from sklearn.feature_extraction.text import HashingVectorizer
fr... | [
"keras.regularizers.l2",
"keras_preprocessing.sequence.pad_sequences",
"torch.nn.EmbeddingBag",
"keras.layers.GlobalAveragePooling1D",
"keras.Sequential",
"torch.nn.Embedding",
"sklearn.metrics.log_loss",
"torch.nn.CrossEntropyLoss",
"torch.randn",
"numpy.clip",
"tensorflow.keras.losses.Categori... | [((809, 875), 'torch.nn.EmbeddingBag', 't.nn.EmbeddingBag', ([], {'num_embeddings': 'n_features', 'embedding_dim': 'n_dims'}), '(num_embeddings=n_features, embedding_dim=n_dims)\n', (826, 875), True, 'import torch as t\n'), ((898, 953), 'torch.nn.Linear', 't.nn.Linear', ([], {'in_features': 'n_dims', 'out_features': 'n... |
import click
import numpy as np
from dtoolbioimage.segment import Segmentation3D
def merge_regions(segmentation_fpath, mergelist):
segmentation = Segmentation3D.from_file(segmentation_fpath)
for l1, l2 in mergelist:
segmentation[np.where(segmentation == l2)] = l1
segmentation.save('merged_05.... | [
"dtoolbioimage.segment.Segmentation3D.from_file",
"numpy.where",
"click.argument",
"click.command"
] | [((329, 344), 'click.command', 'click.command', ([], {}), '()\n', (342, 344), False, 'import click\n'), ((346, 382), 'click.argument', 'click.argument', (['"""segmentation_fpath"""'], {}), "('segmentation_fpath')\n", (360, 382), False, 'import click\n'), ((155, 199), 'dtoolbioimage.segment.Segmentation3D.from_file', 'S... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: <NAME> <<EMAIL>>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
import time
from enum import IntEnum
from collections import deque
im... | [
"PyQt5.QtCore.QTimer",
"extra_foam.gui.mkQApp",
"time.time",
"extra_foam.gui.plot_widgets.PlotWidgetF",
"numpy.arange",
"numpy.random.normal",
"collections.deque"
] | [((464, 472), 'extra_foam.gui.mkQApp', 'mkQApp', ([], {}), '()\n', (470, 472), False, 'from extra_foam.gui import mkQApp\n'), ((663, 679), 'collections.deque', 'deque', ([], {'maxlen': '(60)'}), '(maxlen=60)\n', (668, 679), False, 'from collections import deque\n'), ((703, 711), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}... |
import numpy as np
def kernelList(restrictiveU):
if restrictiveU:
return ['uniform', 'triangle', 'cosinus', 'epanechnikov1', 'epanechnikov2', 'epanechnikov3']
else:
return ['gaussian', 'cauchy', 'picard']
def kernel(kernelString):
if kernelString == 'gaussian':
return gaussianKerne... | [
"numpy.divide",
"numpy.abs",
"numpy.sum",
"numpy.power",
"numpy.zeros",
"numpy.ones",
"numpy.isnan",
"numpy.isinf",
"numpy.sin",
"numpy.cos",
"numpy.sign",
"numpy.dot",
"numpy.sqrt"
] | [((5067, 5082), 'numpy.divide', 'np.divide', (['a', 'b'], {}), '(a, b)\n', (5076, 5082), True, 'import numpy as np\n'), ((2070, 2079), 'numpy.abs', 'np.abs', (['u'], {}), '(u)\n', (2076, 2079), True, 'import numpy as np\n'), ((2105, 2121), 'numpy.ones', 'np.ones', (['u.shape'], {}), '(u.shape)\n', (2112, 2121), True, '... |
import gc
import numpy as np
from matplotlib import pyplot as plt
import cartopy.crs as ccrs
import pyart
from pyart.core.transforms import cartesian_to_geographic
import warnings
from matplotlib import rcParams
import xarray as xr
import pandas as pd
import copy
from tint.grid_utils import get_grid_alt, parse_grid_da... | [
"numpy.abs",
"gc.collect",
"matplotlib.pyplot.figure",
"tint.grid_utils.get_grid_alt",
"numpy.arange",
"tint.visualisation.vertical_helpers.format_pyart",
"pandas.DataFrame",
"tint.visualisation.vertical_helpers.setup_perpendicular_coords",
"tint.visualisation.horizontal_helpers.add_tracked_objects"... | [((485, 526), 'matplotlib.rcParams.update', 'rcParams.update', (["{'font.family': 'serif'}"], {}), "({'font.family': 'serif'})\n", (500, 526), False, 'from matplotlib import rcParams\n'), ((531, 582), 'matplotlib.rcParams.update', 'rcParams.update', (["{'font.serif': 'Liberation Serif'}"], {}), "({'font.serif': 'Libera... |
import requests
import h5py
import numpy as np
import zipfile
from tqdm import tqdm
import math
def file_download(filename):
url = "https://zenodo.org/record/1442704/files/"+filename
r = requests.get(url, stream=True)
total_size = int(r.headers.get('content-length', 0))
block_size = 1024
wrote = 0 ... | [
"h5py.File",
"zipfile.ZipFile",
"math.ceil",
"requests.get",
"numpy.random.shuffle"
] | [((196, 226), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (208, 226), False, 'import requests\n'), ((754, 784), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (766, 784), False, 'import requests\n'), ((1228, 1258), 'zipfile.ZipFile',... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 20:16:07 2019
@author: changlinli
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pymongo
import gridfs
from tqdm import tqdm
from bson import objectid
import base64
import os
import scipy.misc
import matplotlib... | [
"pymongo.MongoClient",
"pandas.DataFrame",
"os.mkdir",
"pandas.read_csv",
"os.path.exists",
"numpy.zeros",
"base64.b64decode",
"gridfs.GridFS",
"pandas.to_numeric"
] | [((345, 371), 'pandas.read_csv', 'pd.read_csv', (['"""./train.csv"""'], {}), "('./train.csv')\n", (356, 371), True, 'import pandas as pd\n'), ((379, 404), 'pandas.read_csv', 'pd.read_csv', (['"""./test.csv"""'], {}), "('./test.csv')\n", (390, 404), True, 'import pandas as pd\n'), ((576, 590), 'pandas.DataFrame', 'pd.Da... |
import sys
import numpy as np
orifile=sys.argv[1]
predfile1=sys.argv[2]
predfile2=sys.argv[3]
block_size=int(sys.argv[4])
dims=int(sys.argv[5])
dim=[]
for i in range(dims):
dim.append(int(sys.argv[6+i]))
ori=np.fromfile(orifile,dtype=np.float32).reshape(tuple(dim))
pred1=np.fromfile(predfile1,dtype=np.float32).re... | [
"numpy.fromfile",
"numpy.array"
] | [((513, 526), 'numpy.array', 'np.array', (['ori'], {}), '(ori)\n', (521, 526), True, 'import numpy as np\n'), ((542, 557), 'numpy.array', 'np.array', (['pred1'], {}), '(pred1)\n', (550, 557), True, 'import numpy as np\n'), ((573, 588), 'numpy.array', 'np.array', (['pred2'], {}), '(pred2)\n', (581, 588), True, 'import n... |
import pygame
import random
from enum import Enum
import numpy as np
from collections import namedtuple
pygame.init()
font = pygame.font.SysFont('Times New Roman', 22)
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
Point = namedtuple('Point', 'x, y')
# rgb colors
WHITE = (255, 255, 255)
R... | [
"pygame.quit",
"random.randint",
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.Rect",
"pygame.init",
"pygame.display.flip",
"collections.namedtuple",
"numpy.array_equal",
"pygame.display.set_caption",
"pygame.time.Clock"
] | [((105, 118), 'pygame.init', 'pygame.init', ([], {}), '()\n', (116, 118), False, 'import pygame\n'), ((126, 168), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""Times New Roman"""', '(22)'], {}), "('Times New Roman', 22)\n", (145, 168), False, 'import pygame\n'), ((253, 280), 'collections.namedtuple', 'namedtuple'... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import ndimage
# Update the matplotlib configuration parameters:
plt.rcParams.update({'font.size': 20,
'font.family': 'serif',
'figure.figsize': (10, 8),
... | [
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rcParams.update",
"numpy.random.randint",
"numpy.fft.fft2",
"scipy.ndimage.fourier_gaussian",
"matplotlib.pyplot.xti... | [((170, 307), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 20, 'font.family': 'serif', 'figure.figsize': (10, 8),\n 'axes.grid': True, 'grid.color': '#555555'}"], {}), "({'font.size': 20, 'font.family': 'serif',\n 'figure.figsize': (10, 8), 'axes.grid': True, 'grid.color': '#555555... |
import dask.array as da
import numpy as np
from pybgen import PyBGEN
from pybgen.parallel import ParallelPyBGEN
import xarray as xr
from .. import core
from ..typing import PathType
from ..compat import Requirement
from ..dispatch import ClassBackend, register_backend
from .core import BGEN_DOMAIN
def _array_name(f,... | [
"numpy.stack",
"pybgen.parallel.ParallelPyBGEN",
"numpy.empty",
"pybgen.PyBGEN",
"numpy.array"
] | [((653, 678), 'pybgen.parallel.ParallelPyBGEN', 'ParallelPyBGEN', (['self.path'], {}), '(self.path)\n', (667, 678), False, 'from pybgen.parallel import ParallelPyBGEN\n'), ((1794, 1828), 'numpy.empty', 'np.empty', (['(0, 0)'], {'dtype': 'self.dtype'}), '((0, 0), dtype=self.dtype)\n', (1802, 1828), True, 'import numpy a... |
import numpy as np
import pickle
import matplotlib.pyplot as plt
"""
This implementation is a pure replication of Example 4.2 in the book
The modified version as the answer to Exercise 4.7 will be posted as Ex4.7-B.py later.
"""
def poisson_calculator(Lambda=3):
"""
input:
lambda: th... | [
"pickle.dump",
"numpy.multiply",
"numpy.argmax",
"numpy.power",
"numpy.finfo",
"pickle.load",
"numpy.random.random",
"numpy.exp",
"numpy.math.factorial"
] | [((6976, 7020), 'pickle.dump', 'pickle.dump', (['all_possibility', 'f'], {'protocol': '(-1)'}), '(all_possibility, f, protocol=-1)\n', (6987, 7020), False, 'import pickle\n'), ((7579, 7610), 'pickle.dump', 'pickle.dump', (['pi', 'f'], {'protocol': '(-1)'}), '(pi, f, protocol=-1)\n', (7590, 7610), False, 'import pickle\... |
"""
A script for processing VIRGO level-1 TSI dataset.
First, the script corrects signals from instruments PMODV6-A and
PMODV6-B for degradation. Then, it produces a TSI composite using
Gaussian Processes.
"""
import argparse
import os
import gpflow as gpf
import numpy as np
import pandas as pd
import tensorflow as t... | [
"tensorflow.random.set_seed",
"tsipy.correction.load_model",
"numpy.random.seed",
"argparse.ArgumentParser",
"tsipy.utils.pprint_block",
"tsipy.utils.pprint",
"tsipy.utils.downsampling_indices_by_max_points",
"numpy.arange",
"os.path.join",
"gpflow.config.set_default_float",
"gpflow.kernels.Mate... | [((954, 979), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (977, 979), False, 'import argparse\n'), ((2233, 2281), 'tsipy.utils.pprint_block', 'pprint_block', (['"""Experiment"""', 'args.experiment_name'], {}), "('Experiment', args.experiment_name)\n", (2245, 2281), False, 'from tsipy.utils i... |
# Test methods with long descriptive names can omit docstrings
# pylint: disable=missing-docstring
import pickle
import unittest
import unittest.mock
import numpy as np
from Orange.data.sql.backend.base import BackendError
from numpy.testing import assert_almost_equal
from Orange.data import (
filter,
Conti... | [
"Orange.statistics.basic_stats.BasicStats",
"numpy.random.randint",
"Orange.data.DiscreteVariable",
"numpy.arange",
"Orange.statistics.basic_stats.DomainBasicStats",
"unittest.skipIf",
"numpy.testing.assert_almost_equal",
"Orange.data.sql.table.SqlTable",
"Orange.data.filter.FilterString",
"Orange... | [((3630, 3693), 'unittest.mock.patch', 'unittest.mock.patch', (['"""Orange.data.sql.table.AUTO_DL_LIMIT"""', '(100)'], {}), "('Orange.data.sql.table.AUTO_DL_LIMIT', 100)\n", (3649, 3693), False, 'import unittest\n'), ((9895, 9984), 'Orange.data.DiscreteVariable', 'DiscreteVariable', (['"""iris"""'], {'values': "['Iris-... |
import numpy as np
import pandas as pd
import talib
from talib import stream
def test_streaming():
a = np.array([1,1,2,3,5,8,13], dtype=float)
r = stream.MOM(a, timeperiod=1)
assert r == 5
r = stream.MOM(a, timeperiod=2)
assert r == 8
r = stream.MOM(a, timeperiod=3)
assert r == 10
r = ... | [
"talib.stream.CDL3BLACKCROWS",
"numpy.isnan",
"talib.stream.MOM",
"talib.stream.MAXINDEX",
"numpy.array",
"pandas.Series"
] | [((109, 154), 'numpy.array', 'np.array', (['[1, 1, 2, 3, 5, 8, 13]'], {'dtype': 'float'}), '([1, 1, 2, 3, 5, 8, 13], dtype=float)\n', (117, 154), True, 'import numpy as np\n'), ((157, 184), 'talib.stream.MOM', 'stream.MOM', (['a'], {'timeperiod': '(1)'}), '(a, timeperiod=1)\n', (167, 184), False, 'from talib import str... |
import numpy as np
from scipy.optimize import curve_fit
from peak_fit import *
def voigt_signal(a, p0, g, l, n):
v0 = voigt(0, g, l)
return [a * voigt(n - p0, g, l) / v0 for n in range(0, n)]
def poly_signal(args, n):
return [poly(el, *args) for el in range(n)]
def noise(std, n):
return list(np.rand... | [
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"numpy.random.randn",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((635, 648), 'matplotlib.pyplot.figure', 'plt.figure', (['(0)'], {}), '(0)\n', (645, 648), True, 'import matplotlib.pyplot as plt\n'), ((649, 658), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (656, 658), True, 'import matplotlib.pyplot as plt\n'), ((721, 752), 'matplotlib.pyplot.plot', 'plt.plot', (['y'], {'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.