code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import torch
import torch.nn as nn
import numpy as np
class IndexTranslator(object):
def __init__(self, state):
self.state = state
self.px = self.state[:, 0].reshape(-1, 1)
self.py = self.state[:, 1].reshape(-1, 1)
self.vx = self.state[:, 2].reshape(-1, 1)
self.vy = self.st... | [
"torch.nn.ReLU",
"torch.Tensor",
"numpy.arctan2",
"numpy.cos",
"torch.nn.Linear",
"numpy.concatenate",
"numpy.sin"
] | [((1990, 2044), 'numpy.arctan2', 'np.arctan2', (['(state.pgy - state.py)', '(state.pgx - state.px)'], {}), '(state.pgy - state.py, state.pgx - state.px)\n', (2000, 2044), True, 'import numpy as np\n'), ((2818, 2831), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (2824, 2831), True, 'import numpy as np\n'), ((285... |
from Data import Data
import itertools
import joblib
import numpy as np
import pandas as pd
import pickle
import re
import statsmodels.api as sm
import sys
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics impo... | [
"Data.Data",
"pandas.Series",
"sklearn.ensemble.RandomForestRegressor",
"itertools.compress",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.OneHotEncoder",
"pandas.merge",
"os.path.join",
"sklearn.metrics.mean_squared_error",
"numpy.square",
"sys.exit",
"pandas.DataFrame",... | [((959, 986), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {}), '()\n', (984, 986), False, 'from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n'), ((2368, 2487), 'sklearn.model_selection.train_test_split', 'train_test_split', (['self.data[self.features]', "... |
import cv2
import dlib
import numpy as np
import pyautogui
import imutils
import time
from imutils import face_utils
WHITE_COLOR = (255, 255, 255)
YELLOW_COLOR = (0, 255, 255)
RED_COLOR = (0, 0, 255)
GREEN_COLOR = (0, 255, 0)
BLUE_COLOR = (255, 0, 0)
BLACK_COLOR = (0, 0, 0)
MOUTH_AR_THRESH = 0.6
shape_predictor = "./... | [
"cv2.rectangle",
"cv2.flip",
"pyautogui.moveTo",
"cv2.line",
"dlib.shape_predictor",
"cv2.imshow",
"cv2.putText",
"dlib.get_frontal_face_detector",
"imutils.resize",
"cv2.circle",
"pyautogui.click",
"cv2.VideoCapture",
"cv2.cvtColor",
"numpy.linalg.norm",
"imutils.face_utils.shape_to_np"... | [((370, 402), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (400, 402), False, 'import dlib\n'), ((415, 452), 'dlib.shape_predictor', 'dlib.shape_predictor', (['shape_predictor'], {}), '(shape_predictor)\n', (435, 452), False, 'import dlib\n'), ((748, 767), 'cv2.VideoCapture', 'c... |
import unittest
import numpy as np
from chainer import testing
from chainercv.transforms import resize_bbox
class TestResizeBbox(unittest.TestCase):
def test_resize_bbox(self):
bbox = np.random.uniform(
low=0., high=32., size=(10, 4))
out = resize_bbox(bbox, in_size=(32, 32), out_s... | [
"chainercv.transforms.resize_bbox",
"chainer.testing.run_module",
"numpy.testing.assert_equal",
"numpy.random.uniform"
] | [((605, 643), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (623, 643), False, 'from chainer import testing\n'), ((201, 252), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': '(32.0)', 'size': '(10, 4)'}), '(low=0.0, high=32.0, si... |
# This examples shows how to perform collision detection between the end-effector of a robot and a point cloud depicted as a Height Field
# Note: this feature requires Meshcat to be installed, this can be done using
# pip install --user meshcat
import pinocchio as pin
import hppfcl as fcl
import numpy as np
import sys... | [
"numpy.random.rand",
"pinocchio.buildModelsFromUrdf",
"numpy.array",
"pinocchio.computeCollisions",
"sys.exit",
"numpy.linspace",
"pinocchio.randomConfiguration",
"pinocchio.SE3.Identity",
"numpy.eye",
"numpy.ones",
"numpy.digitize",
"pinocchio.visualize.MeshcatVisualizer",
"pinocchio.Collis... | [((613, 667), 'os.path.join', 'join', (['pinocchio_model_dir', '"""example-robot-data/robots"""'], {}), "(pinocchio_model_dir, 'example-robot-data/robots')\n", (617, 667), False, 'from os.path import dirname, join, abspath\n'), ((847, 897), 'pinocchio.buildModelsFromUrdf', 'pin.buildModelsFromUrdf', (['urdf_model_path'... |
#!/usr/bin/env python
#------------------------------------------------------------
# Purpose: Program to straight line parameters
# to data with errors in both coordinates. Compare
# the results with SciPy's ODR routine.
# Vog, 27 Nov, 2011
#----------------------------------------------------------... | [
"numpy.random.normal",
"numpy.sqrt",
"numpy.where",
"scipy.odr.ODR",
"scipy.odr.Model",
"numpy.linspace",
"scipy.odr.RealData",
"matplotlib.pyplot.figure",
"kapteyn.kmpfit.Fitter",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.show"
] | [((1153, 1181), 'numpy.linspace', 'numpy.linspace', (['(0.0)', '(12.0)', 'N'], {}), '(0.0, 12.0, N)\n', (1167, 1181), False, 'import numpy\n'), ((1251, 1270), 'numpy.random.normal', 'normal', (['(0.0)', '(0.4)', 'N'], {}), '(0.0, 0.4, N)\n', (1257, 1270), False, 'from numpy.random import normal\n'), ((1279, 1298), 'num... |
import os
import KratosMultiphysics
from KratosMultiphysics import Logger
Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING)
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.DEMApplication.DEM_analysis_stage
import numpy as np
import auxiliary_functions_for_tests
this_w... | [
"numpy.isclose",
"KratosMultiphysics.DEMApplication.DEM_analysis_stage.DEMAnalysisStage.FinalizeSolutionStep",
"KratosMultiphysics.KratosUnittest.main",
"os.path.join",
"os.getcwd",
"os.path.realpath",
"KratosMultiphysics.Logger.GetDefaultOutput",
"KratosMultiphysics.Model",
"auxiliary_functions_for... | [((340, 351), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (349, 351), False, 'import os\n'), ((9710, 9731), 'KratosMultiphysics.KratosUnittest.main', 'KratosUnittest.main', ([], {}), '()\n', (9729, 9731), True, 'import KratosMultiphysics.KratosUnittest as KratosUnittest\n'), ((74, 99), 'KratosMultiphysics.Logger.GetDef... |
# -*- coding: utf-8 -*-
import pywph as pw
import pywph_vanilla as pw2
import numpy as np
import matplotlib.pyplot as plt
M, N = 256, 256
J = 6
L = 4
dn = 0
data_ini = np.load('data/I_1.npy')
data = data_ini[:256,:256]
datab = data_ini[256:,256:]
""" Without normalization """
# Version dev
wph_op = pw.WPHOp(M, N,... | [
"pywph.WPHOp",
"numpy.real",
"matplotlib.pyplot.figure",
"numpy.load",
"pywph_vanilla.WPHOp"
] | [((171, 194), 'numpy.load', 'np.load', (['"""data/I_1.npy"""'], {}), "('data/I_1.npy')\n", (178, 194), True, 'import numpy as np\n'), ((306, 349), 'pywph.WPHOp', 'pw.WPHOp', (['M', 'N', 'J'], {'L': 'L', 'dn': 'dn', 'device': '"""cpu"""'}), "(M, N, J, L=L, dn=dn, device='cpu')\n", (314, 349), True, 'import pywph as pw\n... |
import numpy as np
import scipy
import cv2
def get_pixel_neighbors(height, width):
"""
Estimate the 4 neighbors of every pixel in an image
:param height: image height
:param width: image width
:return: pixel index - neighbor index lists
"""
pix_id = []
neighbor_id = []
for i in ra... | [
"scipy.sparse.lil_matrix",
"numpy.ones",
"numpy.minimum",
"numpy.squeeze",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.unravel_index",
"numpy.arange"
] | [((990, 1177), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, ... |
import math
import torch
import numpy as np
import pandas as pd
import torch.nn as nn
def normal_pdf(x):
import math
return torch.exp(-0.5 * x**2) / math.sqrt(2 * math.pi)
def normal_cdf(y, h=0.01, tau=0.5):
# Approximation of Q-function given by López-Benítez & Casadevall (2011)
# based on a second-... | [
"torch.abs",
"torch.nn.CrossEntropyLoss",
"numpy.logical_and",
"math.sqrt",
"torch.exp",
"torch.nn.BCELoss",
"torch.no_grad",
"torch.logical_and"
] | [((134, 158), 'torch.exp', 'torch.exp', (['(-0.5 * x ** 2)'], {}), '(-0.5 * x ** 2)\n', (143, 158), False, 'import torch\n'), ((159, 181), 'math.sqrt', 'math.sqrt', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', (168, 181), False, 'import math\n'), ((388, 436), 'torch.exp', 'torch.exp', (['(-0.492 * x ** 2 - 0.2887 * x - ... |
import warnings
import numpy as np
from einsteinpy.integrators import GeodesicIntegrator
from .utils import _P, _kerr, _kerrnewman, _sch
class Geodesic:
"""
Base Class for defining Geodesics
Working in Geometrized Units (M-Units),
with :math:`c = G = M = k_e = 1`
"""
def __init__(
... | [
"numpy.hstack",
"einsteinpy.integrators.GeodesicIntegrator",
"numpy.array",
"numpy.cos",
"numpy.vstack",
"numpy.sin",
"numpy.arange"
] | [((3607, 3633), 'numpy.array', 'np.array', (['[0.0, *position]'], {}), '([0.0, *position])\n', (3615, 3633), True, 'import numpy as np\n'), ((6840, 6852), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (6849, 6852), True, 'import numpy as np\n'), ((6872, 7048), 'einsteinpy.integrators.GeodesicIntegrator', 'Geodesic... |
"""
This module defines an abstract base formatter.
!!! question "Formats"
Refer to the [Formats documentation](../../formats/index.md)
to learn about the supported output formats.
"""
from abc import ABC, abstractmethod
import numpy as np
from numpy.lib.recfunctions import unstructured_to_structured
class... | [
"numpy.vectorize"
] | [((1067, 1091), 'numpy.vectorize', 'np.vectorize', (['self.color'], {}), '(self.color)\n', (1079, 1091), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pylab as plt
from math import pi,floor,atan2,atan
from scipy.interpolate import splprep, splev
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
#########################################################################################
#############################... | [
"numpy.sqrt",
"math.floor",
"matplotlib.pylab.show",
"numpy.sin",
"numpy.arange",
"matplotlib.pylab.figure",
"numpy.diff",
"numpy.linspace",
"scipy.interpolate.splev",
"matplotlib.pylab.plot",
"matplotlib.pylab.xlabel",
"math.atan2",
"numpy.savetxt",
"numpy.interp",
"numpy.cos",
"scipy... | [((3451, 3491), 'numpy.loadtxt', 'np.loadtxt', (['"""data/Human/StartAndEnd.dat"""'], {}), "('data/Human/StartAndEnd.dat')\n", (3461, 3491), True, 'import numpy as np\n'), ((4257, 4306), 'numpy.loadtxt', 'np.loadtxt', (['"""data/Human/DataIROS/StartAndEnd.dat"""'], {}), "('data/Human/DataIROS/StartAndEnd.dat')\n", (426... |
import os
import struct
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ply import lex, yacc
class EDR:
"""Reader for experimental data record (EDR) files from the PDS.
This object will ingest and store data from the EDR files, to be
processed later. It only ingest... | [
"ply.yacc.yacc",
"numpy.fromfile",
"ply.lex.lex",
"sys.exit",
"pandas.DataFrame",
"numpy.frombuffer",
"numpy.dtype",
"numpy.vectorize"
] | [((2156, 2818), 'numpy.dtype', 'np.dtype', (["[('SCET_FRAME_WHOLE', '>u4'), ('SCET_FRAME_FRAC', '>u2'), (\n 'GEOMETRY_EPHEMERIS_TIME', '>f8'), ('GEOMETRY_EPOCH', 'V23'), (\n 'MARS_SOLAR_LONGITUDE', '>f8'), ('MARS_SUN_DISTANCE', '>f8'), (\n 'ORBIT_NUMBER', '>u4'), ('TARGET_NAME', 'V6'), (\n 'TARGET_SC_POSITI... |
from typing import Tuple
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
def label_encoder(c: str) -> np.ndarray:
lc = LabelEncoder()
return lc.fit_transform(c)
def load_dataset() -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
path = "../../input/tabular-playg... | [
"sklearn.preprocessing.LabelEncoder",
"numpy.select",
"pandas.read_csv",
"numpy.where",
"pandas.concat"
] | [((164, 178), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (176, 178), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((356, 387), 'pandas.read_csv', 'pd.read_csv', (["(path + 'train.csv')"], {}), "(path + 'train.csv')\n", (367, 387), True, 'import pandas as pd\n'), ((399, 429), ... |
import numpy as np
from scipy.stats import chi2
from tqdm import tqdm as tqdm
from ...common import (
Gaussian,
GaussianDensity,
HypothesisReduction,
normalize_log_weights,
)
from ...configs import SensorModelConfig
from ...measurement_models import MeasurementModel
from ...motion_models import MotionM... | [
"numpy.log",
"numpy.array",
"scipy.stats.chi2.ppf",
"numpy.argmax"
] | [((887, 922), 'scipy.stats.chi2.ppf', 'chi2.ppf', (['P_G'], {'df': 'self.meas_model.d'}), '(P_G, df=self.meas_model.d)\n', (895, 922), False, 'from scipy.stats import chi2\n'), ((2707, 2768), 'numpy.log', 'np.log', (['(self.sensor_model.P_D / self.sensor_model.intensity_c)'], {}), '(self.sensor_model.P_D / self.sensor_... |
import unittest
import numpy as np
import tensorflow as tf
import lib.weighted_layers_v2 as wl
from lib.weighted_resblock import MixtureWeight
class WeightedConv2DTest(tf.test.TestCase):
"""WeightedConv2D test class."""
def setUp(self):
"""Sets default parameters."""
super(WeightedConv2DTest, self).setUp(... | [
"tensorflow.random.normal",
"lib.weighted_layers_v2.WeightedBatchNormalizationSeparate",
"lib.weighted_layers_v2.WeightedDepthwiseConv2D",
"numpy.random.rand",
"tensorflow.keras.layers.Conv2D",
"tensorflow.reduce_sum",
"tensorflow.nn.moments",
"tensorflow.math.sqrt",
"tensorflow.zeros_like",
"lib.... | [((8216, 8272), 'unittest.main', 'unittest.main', ([], {'argv': "['first-arg-is-ignored']", 'exit': '(False)'}), "(argv=['first-arg-is-ignored'], exit=False)\n", (8229, 8272), False, 'import unittest\n'), ((472, 581), 'numpy.random.rand', 'np.random.rand', (['self.num_templates', 'self.kernel_size', 'self.kernel_size',... |
"""
http://yutori-datascience.hatenablog.com/entry/2014/12/10/123157
"""
from numba import cuda
import numpy as np
from numba import double
from numba.decorators import jit
from numba import guvectorize
import time
import math
@jit
def pairwise_numba(X,D):
M,N=X.shape[0],X.shape[1]
for i in range(M):
for j in ... | [
"numpy.sqrt",
"numpy.random.random",
"numba.decorators.jit",
"numba.cuda.grid",
"math.sqrt",
"numba.cuda.jit",
"numba.guvectorize",
"numpy.empty",
"time.time"
] | [((422, 450), 'numba.decorators.jit', 'jit', (['"""void(f8[:,:],f8[:,:])"""'], {}), "('void(f8[:,:],f8[:,:])')\n", (425, 450), False, 'from numba.decorators import jit\n'), ((647, 706), 'numba.guvectorize', 'guvectorize', (["['void(f8[:, :], f8[:, :])']", '"""(x, y)->(x, x)"""'], {}), "(['void(f8[:, :], f8[:, :])'], '(... |
# Copyright 2020 (c) Aalto University - All Rights Reserved
# ELEC-E8125 - Reinforcement Learning Course
# AALTO UNIVERSITY
#
#############################################################
import numpy as np
from time import sleep
from sailing import SailingGridworld
epsilon = 10e-4 # TODO: Use this criteria for Tas... | [
"numpy.mean",
"numpy.argmax",
"time.sleep",
"sailing.SailingGridworld",
"numpy.max",
"numpy.zeros",
"numpy.std",
"numpy.save"
] | [((356, 389), 'sailing.SailingGridworld', 'SailingGridworld', ([], {'rock_penalty': '(-2)'}), '(rock_penalty=-2)\n', (372, 389), False, 'from sailing import SailingGridworld\n'), ((402, 426), 'numpy.zeros', 'np.zeros', (['(env.w, env.h)'], {}), '((env.w, env.h))\n', (410, 426), True, 'import numpy as np\n'), ((3714, 37... |
""" Includes two functions which use shortest path policies
1) run_sss_curriculum - trains a PyMARL agent using experiences gathered
while following an epsilon greedy shortest path policy.
2) mean_sss_time - returns the mean time taken to complete a map while following
an epsilon greedy shortest path policy.
... | [
"logging.getLogger",
"yaml.load",
"main.recursive_dict_update",
"rapport_topological.navigation.construct_shortest_path_policy",
"torch.cuda.is_available",
"torch.sum",
"components.transforms.OneHot",
"datetime.timedelta",
"numpy.mean",
"components.episode_buffer.ReplayBuffer",
"numpy.random.nor... | [((2258, 2302), 'main.recursive_dict_update', 'recursive_dict_update', (['config_dict', 'alg_dict'], {}), '(config_dict, alg_dict)\n', (2279, 2302), False, 'from main import recursive_dict_update\n'), ((2321, 2365), 'main.recursive_dict_update', 'recursive_dict_update', (['config_dict', 'env_dict'], {}), '(config_dict,... |
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
def test_drawdown_and_returns_series():
index_range = pd.date_range(start=datetime(2000, 1, 1), periods=4, freq='AS-JAN')
wealth_index = pd.Series(data=[0.4, 0.3, 0.2, 0.5], index=index_range)
dd = wealth_index.drawdown
as... | [
"pandas.Series",
"numpy.testing.assert_almost_equal",
"datetime.timedelta",
"datetime.datetime"
] | [((227, 282), 'pandas.Series', 'pd.Series', ([], {'data': '[0.4, 0.3, 0.2, 0.5]', 'index': 'index_range'}), '(data=[0.4, 0.3, 0.2, 0.5], index=index_range)\n', (236, 282), True, 'import pandas as pd\n'), ((536, 598), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["drawdown_df['2000-01-01']", '... |
import os, json, base64, cv2, glob
import numpy as np
import matplotlib.pyplot as plt
from coco import CocoConfig
from Mask.config import Config
import Mask.utils as utils
import Mask.model as modellib
import Mask.visualize as visualize
from convert_file import load_image
def init():
np.set_printoptions(threshold=... | [
"json.loads",
"Mask.model.MaskRCNN",
"convert_file.load_image",
"coco.CocoConfig",
"numpy.set_printoptions"
] | [((290, 327), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (309, 327), True, 'import numpy as np\n'), ((359, 379), 'json.loads', 'json.loads', (['input_df'], {}), '(input_df)\n', (369, 379), False, 'import os, json, base64, cv2, glob\n'), ((389, 413), 'convert_... |
import streamlit as st
import pandas as pd
import altair as alt
import pickle
import numpy as np
from map import create_map
from airdata import AirData
from utils import parse_time, parse_time_hms
from vega_datasets import data
#st.set_page_config(layout="wide")
# Getting data ready, Refresh every hour (same data... | [
"pandas.read_csv",
"utils.parse_time_hms",
"altair.Chart",
"numpy.log",
"streamlit.sidebar.expander",
"utils.parse_time",
"numpy.array",
"altair.X",
"altair.Y",
"altair.Legend",
"streamlit.metric",
"map.create_map",
"streamlit.header",
"numpy.arange",
"streamlit.title",
"streamlit.side... | [((358, 405), 'streamlit.cache', 'st.cache', ([], {'ttl': '(60 * 60)', 'suppress_st_warning': '(True)'}), '(ttl=60 * 60, suppress_st_warning=True)\n', (366, 405), True, 'import streamlit as st\n'), ((2654, 2764), 'streamlit.sidebar.radio', 'st.sidebar.radio', (['"""Menu"""', "['Introduction', 'Flight Map', 'Flight Dela... |
import numpy as np
import pandas as pd
def Loader(events,args):
"""
Create a table with the pulses
"""
gb = events.groupby('Pulse',sort=False)
pulses = events.loc[gb.Sigma.idxmax()]
pulses.index = pulses.Pulse
pulses.index.name = None
pulses = pulses.drop('Pulse', axis='columns')
pulses.index... | [
"numpy.abs",
"numpy.sign"
] | [((1990, 2003), 'numpy.sign', 'np.sign', (['diff'], {}), '(diff)\n', (1997, 2003), True, 'import numpy as np\n'), ((2239, 2267), 'numpy.abs', 'np.abs', (['(pulses.Time - p.Time)'], {}), '(pulses.Time - p.Time)\n', (2245, 2267), True, 'import numpy as np\n')] |
# Author: <NAME> at 16/08/2021 <<EMAIL>>
# Licence: MIT License
# Copyright: <NAME> (2018) <<EMAIL>>
from functools import partial
import numpy as np
from scipy import linalg
from .utils import (readout_forward, _initialize_readout,
_prepare_inputs_for_learning)
from ..base.node import Node
from ... | [
"numpy.eye",
"functools.partial",
"scipy.linalg.solve"
] | [((401, 449), 'scipy.linalg.solve', 'linalg.solve', (['(XXT + ridge)', 'YXT.T'], {'assume_a': '"""sym"""'}), "(XXT + ridge, YXT.T, assume_a='sym')\n", (413, 449), False, 'from scipy import linalg\n'), ((1328, 1365), 'numpy.eye', 'np.eye', (['input_dim'], {'dtype': 'global_dtype'}), '(input_dim, dtype=global_dtype)\n', ... |
import pandas as pd
import numpy as np
from numpy import corrcoef
import matplotlib.pyplot as plt
from sklearn.feature_selection import chi2
from sklearn.feature_selection import f_classif
from math import *
plt.style.use('ggplot')
fig = plt.figure()
COUNTER = 1
#Return the category dictionary,categorical variables l... | [
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.hist",
"numpy.corrcoef",
"matplotlib.pyplot.ylabel",
"sklearn.feature_selection.f_classif",
"matplotlib.pyplot.style.use",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"sklearn.feature_selection.chi2",
"matplotlib.pyplot.... | [((208, 231), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (221, 231), True, 'import matplotlib.pyplot as plt\n'), ((239, 251), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (249, 251), True, 'import matplotlib.pyplot as plt\n'), ((2265, 2279), 'numpy.corrcoef', ... |
import os
import numpy as np
def save_samples_truncted_prob(fname, points, prob):
'''
Save the visualization of sampling to a ply file.
Red points represent positive predictions.
Green points represent negative predictions.
Parameters
fname: File name to save
points: [N, 3] array o... | [
"os.makedirs",
"numpy.zeros",
"os.path.join",
"numpy.concatenate"
] | [((568, 585), 'numpy.zeros', 'np.zeros', (['r.shape'], {}), '(r.shape)\n', (576, 585), True, 'import numpy as np\n'), ((601, 649), 'numpy.concatenate', 'np.concatenate', (['[points, r, g, b, prob]'], {'axis': '(-1)'}), '([points, r, g, b, prob], axis=-1)\n', (615, 649), True, 'import numpy as np\n'), ((1380, 1425), 'os... |
from bokeh.application.handlers import FunctionHandler, DirectoryHandler
from bokeh.application import Application
import numpy as np
import holoviews as hv
import boto3
from PIL import Image
import holoviews.plotting.bokeh # important
from bokeh.io import show, curdoc
from bokeh.layouts import layout
import io
from ... | [
"bokeh.layouts.layout",
"PIL.Image.open",
"holoviews.renderer",
"bokeh.application.handlers.FunctionHandler",
"io.BytesIO",
"numpy.asarray",
"boto3.resource",
"marshmallow.fields.String",
"marshmallow.fields.Integer"
] | [((1073, 1093), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (1087, 1093), False, 'import boto3\n'), ((1176, 1188), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1186, 1188), False, 'import io\n'), ((1246, 1269), 'PIL.Image.open', 'Image.open', (['file_stream'], {}), '(file_stream)\n', (1256, 12... |
#import hickle as hkl
import numpy as np
from keras import backend as K
from keras.preprocessing.image import Iterator
import matplotlib.pyplot as plt
# Defines one class: SequenceGenerator. a subclass of Iterator
# ====================================
# Called from kitti_train.py and kitti_evaluate.py.
# Class Seque... | [
"matplotlib.pyplot.imshow",
"numpy.transpose",
"keras.backend.image_data_format",
"numpy.random.permutation",
"numpy.array",
"numpy.zeros",
"numpy.load",
"matplotlib.pyplot.show"
] | [((718, 739), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (737, 739), True, 'from keras import backend as K\n'), ((928, 946), 'numpy.load', 'np.load', (['data_file'], {}), '(data_file)\n', (935, 946), True, 'import numpy as np\n'), ((1876, 1926), 'numpy.array', 'np.array', (['self.X[0, :... |
import psycopg2
from datetime import datetime
from psycopg2 import sql
from est.fltr import county_return
from est.db.cur import con_cur
import numpy as np
import pandas as pd
def comp_find(est, a, b):
temp1 = est
temp2 = np.array(temp1[0])
county = temp2[0].strip()
state = temp2[1].strip()
cur, c... | [
"numpy.array",
"est.db.cur.con_cur"
] | [((231, 249), 'numpy.array', 'np.array', (['temp1[0]'], {}), '(temp1[0])\n', (239, 249), True, 'import numpy as np\n'), ((325, 334), 'est.db.cur.con_cur', 'con_cur', ([], {}), '()\n', (332, 334), False, 'from est.db.cur import con_cur\n'), ((632, 641), 'est.db.cur.con_cur', 'con_cur', ([], {}), '()\n', (639, 641), Fals... |
from aiohttp import web
import socketio
import numpy as np
def load_eigenvector(k,d):
vec_path = "eigenvectors/eigen_k=" + str(k) + ",d=" + str(d) + ".npy"
eigenvector_np = np.load(vec_path)
eigenvector_str = ""
for x in np.nditer(eigenvector_np):
eigenvector_str += str(x) + " "
# print()... | [
"aiohttp.web.run_app",
"numpy.nditer",
"aiohttp.web.Application",
"socketio.AsyncServer",
"numpy.load"
] | [((423, 469), 'socketio.AsyncServer', 'socketio.AsyncServer', ([], {'cors_allowed_origins': '"""*"""'}), "(cors_allowed_origins='*')\n", (443, 469), False, 'import socketio\n'), ((516, 533), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (531, 533), False, 'from aiohttp import web\n'), ((182, 199), 'nu... |
#!/usr/bin/env python
# pylint: disable=invalid-name,ungrouped-imports
import logging
import math
import os
from importlib import import_module
import coloredlogs
import numpy as np
import tensorflow as tf
from scipy.misc import imread
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import ... | [
"logging.getLogger",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.train.Checkpoint",
"tensorflow.logging.set_verbosity",
"math.log",
"numpy.array",
"tensorflow.python.ops.math_ops.cumsum",
"numpy.sin",
"tensorflow.contrib.memory_stats.BytesInUse",
"tensorflow.python.ops.math_ops.range",
... | [((1988, 2018), 'tensorflow.cast', 'tf.cast', (['(output >= 0)', 'tf.uint8'], {}), '(output >= 0, tf.uint8)\n', (1995, 2018), True, 'import tensorflow as tf\n'), ((2030, 2066), 'tensorflow.cast', 'tf.cast', (['(ground_truth >= 0)', 'tf.uint8'], {}), '(ground_truth >= 0, tf.uint8)\n', (2037, 2066), True, 'import tensorf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PUB_DATAVIZ: Visualization tools for PINNACLE
# Copyright (c) 2020, <NAME>
#
# MIT License:
# https://github.com/IATE-CONICET-UNC/pinnacle/blob/master/LICENSE
from matplotlib import pyplot as plt
from pinnacle.plot_styles import cycling_attrs, aes_attrs
import numpy a... | [
"numpy.histogram",
"pinnacle.plot_styles.cycling_attrs",
"matplotlib.pyplot.close",
"datetime.datetime.now",
"matplotlib.pyplot.figure",
"numpy.array",
"pinnacle.plot_styles.aes_attrs",
"random.random",
"numpy.arange"
] | [((2049, 2075), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 5)'}), '(figsize=(8, 5))\n', (2059, 2075), True, 'from matplotlib import pyplot as plt\n'), ((2733, 2744), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2742, 2744), True, 'from matplotlib import pyplot as plt\n'), ((3678, 3704... |
import numpy as np
def Topsis(weights, numerical_data, impact):
try:
if(numerical_data.shape[1] != weights.shape[0] or weights.shape != impact.shape or numerical_data.shape[1] != impact.shape[0]):
raise Exception("Given input is not correct")
except Exception as e:
print("Given input is incorrect")
return
... | [
"numpy.argsort",
"numpy.array",
"numpy.argmax"
] | [((1182, 1225), 'numpy.array', 'np.array', (['ideal_best_values'], {'dtype': 'np.float'}), '(ideal_best_values, dtype=np.float)\n', (1190, 1225), True, 'import numpy as np\n'), ((1250, 1294), 'numpy.array', 'np.array', (['ideal_worst_values'], {'dtype': 'np.float'}), '(ideal_worst_values, dtype=np.float)\n', (1258, 129... |
from copy import deepcopy
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from apex import amp
from torch.cuda.amp import autocast as autocast
from transformers import BertModel, BertTokenizer
from util import text_processing
from collections import OrderedDict
from . import ops a... | [
"torch.mul",
"util.text_processing.VocabDict",
"torch.sum",
"torch.bmm",
"torch.nn.functional.softmax",
"torch.cuda.amp.GradScaler",
"torch.cuda.amp.autocast",
"torch.nn.parallel.DistributedDataParallel",
"torch.argmax",
"collections.OrderedDict",
"transformers.BertModel.from_pretrained",
"tor... | [((796, 840), 'torch.nn.functional.normalize', 'F.normalize', (['(kb * proj_q[:, None, :])'], {'dim': '(-1)'}), '(kb * proj_q[:, None, :], dim=-1)\n', (807, 840), True, 'import torch.nn.functional as F\n'), ((985, 1011), 'torch.nn.functional.softmax', 'F.softmax', (['raw_att'], {'dim': '(-1)'}), '(raw_att, dim=-1)\n', ... |
"""
3D Agn spin visualisation
"""
import logging
import os
import shutil
import corner
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyvista as pv
import scipy.stats
from bbh_simulator.calculate_kick_vel_from_samples import Samples
from matplotlib impor... | [
"logging.getLogger",
"numpy.arccos",
"numpy.sqrt",
"bilby_report.tools.image_utils.make_gif",
"numpy.arctan2",
"matplotlib.rc",
"numpy.linalg.norm",
"numpy.sin",
"corner.corner",
"matplotlib.lines.Line2D",
"pyvista.Arrow",
"bbh_simulator.calculate_kick_vel_from_samples.Samples",
"pyvista.Pol... | [((452, 475), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (454, 475), False, 'from matplotlib import rc\n'), ((2082, 2113), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(np.pi * 2)'], {}), '(0, np.pi * 2)\n', (2099, 2113), True, 'import numpy as np\n'), ((2492, 25... |
#encoding=utf8
## 参考https://blog.csdn.net/dengxing1234/article/details/73739836
import xgboost as xgb
from sklearn.datasets import load_svmlight_file
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc, roc_auc_score
from sk... | [
"sklearn.datasets.load_svmlight_file",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.roc_auc_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.preprocessing.data.OneHotEncoder",
"scipy.sparse.hstack",
"numpy.concatenate",
"xgboost.XGBClassifier"
] | [((536, 577), 'sklearn.datasets.load_svmlight_file', 'load_svmlight_file', (['libsvmFileNameInitial'], {}), '(libsvmFileNameInitial)\n', (554, 577), False, 'from sklearn.datasets import load_svmlight_file\n'), ((634, 696), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_all', 'y_all'], {'test_size'... |
#!/usr/bin/env python
# encoding: utf-8
"""
calc beat score of files
copyright: www.mgtv.com
"""
import os
import sys
import argparse
import numpy as np
import traceback
import beat_evaluation_toolbox as be
def calc_beat_score_of_file(annotation_file, beat_file):
#check input params
if os.pat... | [
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"beat_evaluation_toolbox.evaluate_db",
"os.chdir",
"numpy.expand_dims",
"sys.exit",
"os.path.abspath",
"numpy.loadtxt",
"traceback.print_exc"
] | [((640, 678), 'numpy.loadtxt', 'np.loadtxt', (['annotation_file'], {'usecols': '(0)'}), '(annotation_file, usecols=0)\n', (650, 678), True, 'import numpy as np\n'), ((703, 742), 'numpy.expand_dims', 'np.expand_dims', (['data_annotation'], {'axis': '(0)'}), '(data_annotation, axis=0)\n', (717, 742), True, 'import numpy ... |
import numpy as np
def permutation_value(num_list, max_num):
return sum([num_list[i]*max_num**(len(num_list)-1-i) for i in range(len(num_list))])
def permutation_update(in_list):
pass
init_array = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
init_array.astype('int64')
#ULØST!
| [
"numpy.array"
] | [((222, 262), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (230, 262), True, 'import numpy as np\n')] |
import sys
from PyQt4 import QtGui, QtCore
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy
from math import sqrt, sin, cos, pi
from geometry.quaternion import Quaternion
class StripChart(QtGui.QWidget):
""" a class to implement a stripchart using the pyqtgraph plotting
utilities
... | [
"pyqtgraph.PlotCurveItem",
"numpy.isscalar",
"pyqtgraph.ScatterPlotItem",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.isnan"
] | [((4031, 4061), 'numpy.zeros', 'numpy.zeros', (['(len_x, len_y, 3)'], {}), '((len_x, len_y, 3))\n', (4042, 4061), False, 'import numpy\n'), ((1242, 1260), 'numpy.isscalar', 'numpy.isscalar', (['xd'], {}), '(xd)\n', (1256, 1260), False, 'import numpy\n'), ((1392, 1407), 'numpy.array', 'numpy.array', (['yd'], {}), '(yd)\... |
from typing import Tuple, Dict
import h5py
import pandas as pd
import numpy as np
from loguru import logger
from ruamel.yaml import YAML
from joblib import load, dump
from umda import EmbeddingModel
from sklearn.gaussian_process import GaussianProcessRegressor, kernels
from sklearn.neighbors import KNeighborsRegressor... | [
"sklearn.model_selection.GridSearchCV",
"sklearn.metrics.pairwise.cosine_distances",
"numpy.hstack",
"ruamel.yaml.YAML",
"sklearn.model_selection.KFold",
"sklearn.metrics.r2_score",
"pandas.read_pickle",
"loguru.logger.add",
"sklearn.gaussian_process.GaussianProcessRegressor",
"sklearn.ensemble.Ra... | [((2628, 2670), 'sklearn.model_selection.KFold', 'KFold', (['cv'], {'random_state': 'seed', 'shuffle': '(True)'}), '(cv, random_state=seed, shuffle=True)\n', (2633, 2670), False, 'from sklearn.model_selection import KFold, GridSearchCV, ShuffleSplit\n'), ((2689, 2791), 'sklearn.model_selection.GridSearchCV', 'GridSearc... |
#!/usr/bin/env python
# -*- coding: utf-8
import numpy as np
from ibidem.advent_of_code.util import get_input_name
BASE_PATTERN = [0, 1, 0, -1]
def pattern_generator(i):
first = True
while True:
for v in BASE_PATTERN:
for _ in range(i + 1):
if first:
... | [
"numpy.tile",
"numpy.flip",
"numpy.abs",
"numpy.array",
"ibidem.advent_of_code.util.get_input_name"
] | [((873, 901), 'numpy.tile', 'np.tile', (['signal', 'repetitions'], {}), '(signal, repetitions)\n', (880, 901), True, 'import numpy as np\n'), ((1195, 1220), 'numpy.array', 'np.array', (['signal[offset:]'], {}), '(signal[offset:])\n', (1203, 1220), True, 'import numpy as np\n'), ((697, 707), 'numpy.abs', 'np.abs', (['cs... |
import pandas as pd
import os
import numpy as np
import math
import ast
sigma_list = [ math.pow(2,i) for i in range(8)]
for sigma in sigma_list:
test_case = 'mnist'
data_dict={}
data_dict_sum={}
# for key in def_data.keys():
# data_dict[key] = def_data[key].tolist()
file_name=os.path.... | [
"math.pow",
"numpy.sum",
"pandas.DataFrame.from_dict",
"pandas.read_csv"
] | [((88, 102), 'math.pow', 'math.pow', (['(2)', 'i'], {}), '(2, i)\n', (96, 102), False, 'import math\n'), ((423, 455), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {'sep': '"""\t"""'}), "(file_name, sep='\\t')\n", (434, 455), True, 'import pandas as pd\n'), ((468, 504), 'pandas.read_csv', 'pd.read_csv', (['file_nam... |
from keras.models import load_model
import numpy as np
import cv2
import pickle
from image_segmentation import segment_image
from neural_network import resize_to_fit
MODEL_FILENAME = "captcha_model.hdf5"
MODEL_LABELS_FILENAME = "model_labels.dat"
def solve_captcha(image):
# Load up the model labels
with open... | [
"cv2.rectangle",
"cv2.merge",
"keras.models.load_model",
"pickle.load",
"cv2.putText",
"numpy.expand_dims",
"image_segmentation.segment_image",
"neural_network.resize_to_fit"
] | [((429, 455), 'keras.models.load_model', 'load_model', (['MODEL_FILENAME'], {}), '(MODEL_FILENAME)\n', (439, 455), False, 'from keras.models import load_model\n'), ((520, 544), 'image_segmentation.segment_image', 'segment_image', (['image', '(-1)'], {}), '(image, -1)\n', (533, 544), False, 'from image_segmentation impo... |
from bs4 import BeautifulSoup as bs
import threading
import time
import numpy as np
import sys
from io import StringIO
import scrapeconfig as cng
import consoleconfig as ccng
import os
def print_html(html_test):
'''To print html containers returned by beautifulsoup4'''
try:
strhtml = st... | [
"threading.activeCount",
"time.sleep",
"numpy.random.randint",
"threading.Thread",
"sys.stdout.flush",
"sys.stdout.write"
] | [((820, 845), 'sys.stdout.write', 'sys.stdout.write', (['basemsg'], {}), '(basemsg)\n', (836, 845), False, 'import sys\n'), ((1388, 1433), 'sys.stdout.write', 'sys.stdout.write', (["f'\\r{space * basemsglen}\\r'"], {}), "(f'\\r{space * basemsglen}\\r')\n", (1404, 1433), False, 'import sys\n'), ((1441, 1478), 'sys.stdou... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='talk')
palette = sns.color_palette()
beta = 1
landa = 1./beta
reps = 25
pois = np.random.exponential(beta, reps)
pois = pois.cumsum()
psra = np.arange(reps)*beta + np.random.exponential(beta, reps) - landa
psra.sort()
f, ax =... | [
"seaborn.set",
"matplotlib.pyplot.savefig",
"seaborn.color_palette",
"numpy.random.exponential",
"numpy.zeros",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((74, 97), 'seaborn.set', 'sns.set', ([], {'context': '"""talk"""'}), "(context='talk')\n", (81, 97), True, 'import seaborn as sns\n'), ((108, 127), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (125, 127), True, 'import seaborn as sns\n'), ((172, 205), 'numpy.random.exponential', 'np.random.exponent... |
import classy.datasets
from .Struct import Struct
import numpy as np
from numpy import sqrt,sum,exp,pi,min,max,linspace
def normal(x,mu,sd):
return 1.0/sqrt(2*pi*sd**2)*exp(-(x-mu)**2/(2*sd**2))
def overlap(means_,covars_):
# http://en.wikipedia.org/wiki/Bhattacharyya_distance
# overlap is a dot product
... | [
"numpy.sqrt",
"numpy.exp",
"numpy.array",
"numpy.linspace",
"numpy.min",
"sklearn.mixture.GMM"
] | [((365, 396), 'numpy.min', 'min', (['[m1 - 4 * s1, m2 - 4 * s2]'], {}), '([m1 - 4 * s1, m2 - 4 * s2])\n', (368, 396), False, 'from numpy import sqrt, sum, exp, pi, min, max, linspace\n'), ((397, 428), 'numpy.min', 'min', (['[m1 + 4 * s1, m2 + 4 * s2]'], {}), '([m1 + 4 * s1, m2 + 4 * s2])\n', (400, 428), False, 'from nu... |
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
import seaborn as sns
def plot_conservation(out_path):
"""
Plotting the fraction of conserved binding sites for Brn2, Ebf2 and
Onecut2, based on multiGPS and edgeR results from Aydin et al., 2019
(Nature Neurosciece: PMI... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"seaborn.set_style",
"numpy.array",
"seaborn.violinplot",
"seaborn.despine",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"seaborn... | [((589, 687), 'pandas.DataFrame', 'pd.DataFrame', (["[['shared', 6776], ['iA>iN', 2432], ['iN>iA', 1242]]"], {'columns': "['category', '#']"}), "([['shared', 6776], ['iA>iN', 2432], ['iN>iA', 1242]], columns=\n ['category', '#'])\n", (601, 687), True, 'import pandas as pd\n'), ((774, 873), 'pandas.DataFrame', 'pd.Da... |
"""
refer to https://github.com/jfzhang95/pytorch-deeplab-xception/blob/master/utils/metrics.py
"""
import numpy as np
__all__ = ['SegmentationMetric']
"""
confusionMetric
P\L P N
P TP FP
N FN TN
"""
class SegmentationMetric(object):
def __init__(self, numClass):
self.numClass = n... | [
"numpy.diag",
"numpy.array",
"numpy.zeros",
"numpy.nanmean",
"numpy.sum",
"numpy.bincount"
] | [((2630, 2658), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 2, 2]'], {}), '([0, 0, 1, 1, 2, 2])\n', (2638, 2658), True, 'import numpy as np\n'), ((2674, 2702), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 2, 2]'], {}), '([0, 0, 1, 1, 2, 2])\n', (2682, 2702), True, 'import numpy as np\n'), ((359, 389), 'numpy.zeros', 'np.z... |
'''
@inproceedings{golestaneh2017spatially,
title={Spatially-Varying Blur Detection Based on Multiscale Fused and Sorted Transform Coefficients of Gradient Magnitudes},
author={<NAME> and Karam, <NAME>},
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
year={2017}
}
'''... | [
"numpy.sqrt",
"numpy.hstack",
"numpy.array",
"copy.deepcopy",
"numpy.multiply",
"numpy.where",
"numpy.diff",
"numpy.max",
"numpy.linspace",
"numpy.matmul",
"skimage.morphology.square",
"cv2.resize",
"cv2.GaussianBlur",
"numpy.shape",
"numpy.transpose",
"numpy.int",
"numpy.median",
... | [((2361, 2424), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(1)', '(0)'], {'borderType': 'cv2.BORDER_REFLECT'}), '(img, cv2.CV_64F, 1, 0, borderType=cv2.BORDER_REFLECT)\n', (2370, 2424), False, 'import cv2\n'), ((2470, 2533), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(0)', '(1)'], {'borderType': 'cv2.BORD... |
"""
This module contains all the functions needed for extracting satellite-derived
shorelines (SDS)
Author: <NAME>, Water Research Laboratory, University of New South Wales
"""
# load modules
import os
import numpy as np
import matplotlib.pyplot as plt
import pdb
# image processing modules
import skimage.filters as... | [
"coastsat.SDS_tools.get_filepath",
"skimage.filters.threshold_otsu",
"numpy.array",
"coastsat.SDS_preprocess.preprocess_single",
"coastsat.SDS_tools.merge_output",
"numpy.linalg.norm",
"numpy.nanmin",
"matplotlib.lines.Line2D",
"numpy.arange",
"skimage.morphology.binary_dilation",
"os.path.exist... | [((874, 897), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (883, 897), True, 'import numpy as np\n'), ((3131, 3194), 'os.path.join', 'os.path.join', (['filepath_data', 'sitename', '"""jpg_files"""', '"""detection"""'], {}), "(filepath_data, sitename, 'jpg_files', 'detection')\n", (314... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File name: tool_func.py
"""
Created on Thu Apr 23 17:39:40 2020
@author: Neo(<EMAIL>)
Some tool functions. The comment will be added when I am free.
"""
from myprogs.vsh.vsh_fit import rotgli_fit_4_table
from myprogs.catalog.pos_diff import radio_cat_diff_calc
from ... | [
"numpy.mean",
"numpy.random.random_sample",
"astropy.table.Table",
"numpy.hstack",
"astropy.stats.sigma_clip",
"numpy.random.random",
"numpy.log",
"myprogs.vsh.vsh_fit.rotgli_fit_4_table",
"numpy.exp",
"numpy.empty",
"numpy.vstack",
"numpy.concatenate",
"numpy.std",
"numpy.arange"
] | [((1757, 1799), 'myprogs.vsh.vsh_fit.rotgli_fit_4_table', 'rotgli_fit_4_table', (['pos_oft'], {'verbose': '(False)'}), '(pos_oft, verbose=False)\n', (1775, 1799), False, 'from myprogs.vsh.vsh_fit import rotgli_fit_4_table\n'), ((2098, 2122), 'numpy.hstack', 'np.hstack', (['(pmt, [g, w])'], {}), '((pmt, [g, w]))\n', (21... |
import numpy as np
from opytimizer.optimizers.swarm import sso
from opytimizer.spaces import search
def test_sso_params():
params = {
'C_w': 0.1,
'C_p': 0.4,
'C_g': 0.9
}
new_sso = sso.SSO(params=params)
assert new_sso.C_w == 0.1
assert new_sso.C_p == 0.4
assert ne... | [
"numpy.sum",
"opytimizer.spaces.search.SearchSpace",
"numpy.array",
"opytimizer.optimizers.swarm.sso.SSO"
] | [((221, 243), 'opytimizer.optimizers.swarm.sso.SSO', 'sso.SSO', ([], {'params': 'params'}), '(params=params)\n', (228, 243), False, 'from opytimizer.optimizers.swarm import sso\n'), ((383, 392), 'opytimizer.optimizers.swarm.sso.SSO', 'sso.SSO', ([], {}), '()\n', (390, 392), False, 'from opytimizer.optimizers.swarm impo... |
import numpy as np
from agents import Agent
from connectboard import ConnectBoard
import time
import math
class AlphaBeta(Agent):
"""Agent that implements minimax with alpha-beta pruning to select its next move."""
def get_move(self, game_board: np.ndarray) -> np.ndarray:
"""Recursively runs minimax ... | [
"numpy.delete",
"time.time",
"connectboard.ConnectBoard.get_legal_moves"
] | [((833, 844), 'time.time', 'time.time', ([], {}), '()\n', (842, 844), False, 'import time\n'), ((921, 932), 'time.time', 'time.time', ([], {}), '()\n', (930, 932), False, 'import time\n'), ((2759, 2799), 'connectboard.ConnectBoard.get_legal_moves', 'ConnectBoard.get_legal_moves', (['game_board'], {}), '(game_board)\n',... |
import matplotlib.pyplot as plt
import netomaton as ntm
import numpy as np
if __name__ == '__main__':
# NKS page 443 - Rule 122R
network = ntm.topology.cellular_automaton(n=100)
# carefully chosen initial conditions
previous_state = [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, ... | [
"netomaton.rules.nks_ca_rule",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"numpy.array",
"netomaton.average_node_entropy",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"netomaton.get_activities_over_time_as_list",
"netomaton.topology.cellular_automaton"
] | [((150, 188), 'netomaton.topology.cellular_automaton', 'ntm.topology.cellular_automaton', ([], {'n': '(100)'}), '(n=100)\n', (181, 188), True, 'import netomaton as ntm\n'), ((1346, 1394), 'netomaton.get_activities_over_time_as_list', 'ntm.get_activities_over_time_as_list', (['trajectory'], {}), '(trajectory)\n', (1382,... |
import numpy as np
__all__ = ["plot_spectrum_datasets_off_regions", "plot_contour_line"]
def plot_spectrum_datasets_off_regions(datasets, ax=None):
"""Plot spectrum datasets of regions.
Parameters
----------
datasets : list of `SpectrumDatasetOnOff`
List of spectrum on-off datasets
"""
... | [
"scipy.interpolate.CubicSpline",
"matplotlib.pyplot.gca",
"numpy.diff",
"numpy.append",
"numpy.linspace",
"matplotlib.patches.Patch",
"numpy.cumsum",
"matplotlib.pyplot.legend"
] | [((892, 919), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': 'handles'}), '(handles=handles)\n', (902, 919), True, 'import matplotlib.pyplot as plt\n'), ((1090, 1108), 'numpy.append', 'np.append', (['x', 'x[0]'], {}), '(x, x[0])\n', (1099, 1108), True, 'import numpy as np\n'), ((1118, 1136), 'numpy.append',... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 15:05:10 2019
The Simple Linear Regression model
@author: Dr. Dr. <NAME>
@web : https://dannyvanpoucke.be
"""
import pandas as pd
import numpy as np
from TModelClass import TModelClass
from TModelResults import TModelResults
from Bootstrap import TBootstrap
from TMo... | [
"numpy.mean",
"Bootstrap.TBootstrap",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"sys.exit",
"pandas.concat",
"sklearn.linear_model.LinearRegression",
"TModelQualityData.TModelQualityData"
] | [((2265, 2344), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(True)', 'normalize': '(False)', 'copy_X': '(True)', 'n_jobs': 'None'}), '(fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)\n', (2281, 2344), False, 'from sklearn.linear_model import LinearRegression\n'), ... |
from __future__ import absolute_import, division, print_function
from abc import abstractmethod, abstractproperty
import numpy as np
from keras import __version__ as __keras_version__
from keras import backend as K
from keras.layers import Dense, Dot, Dropout, Input, Lambda, TimeDistributed
from keras.models import ... | [
"keras.backend.dtype",
"energyflow.archs.archbase._get_act_layer",
"keras.backend.function",
"keras.layers.Lambda",
"keras.__version__.split",
"keras.layers.TimeDistributed",
"keras.layers.Dot",
"keras.backend.not_equal",
"numpy.asarray",
"keras.layers.Input",
"numpy.linspace",
"energyflow.uti... | [((1477, 1522), 'keras.layers.Input', 'Input', ([], {'batch_shape': '(None, None)', 'name': 'zs_name'}), '(batch_shape=(None, None), name=zs_name)\n', (1482, 1522), False, 'from keras.layers import Dense, Dot, Dropout, Input, Lambda, TimeDistributed\n'), ((1541, 1600), 'keras.layers.Input', 'Input', ([], {'batch_shape'... |
import tensorflow as tf
import numpy as np
from blackbox_mpc.optimizers.optimizer_base import OptimizerBase
class PSOOptimizer(OptimizerBase):
def __init__(self, env_action_space, env_observation_space,
planning_horizon=50, max_iterations=5, population_size=500,
num_agents=5, c1=... | [
"tensorflow.random.uniform",
"tensorflow.math.argmax",
"tensorflow.random.normal",
"tensorflow.reduce_prod",
"tensorflow.transpose",
"numpy.square",
"tensorflow.range",
"tensorflow.where",
"tensorflow.sqrt",
"tensorflow.constant",
"tensorflow.clip_by_value",
"tensorflow.gather",
"tensorflow.... | [((320, 354), 'tensorflow.constant', 'tf.constant', (['(0.3)'], {'dtype': 'tf.float32'}), '(0.3, dtype=tf.float32)\n', (331, 354), True, 'import tensorflow as tf\n'), ((376, 410), 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'dtype': 'tf.float32'}), '(0.5, dtype=tf.float32)\n', (387, 410), True, 'import tensorflo... |
import numpy as np
import porespy as ps
import matplotlib.pyplot as plt
import openpnm as op
np.random.seed(0)
def test_snow_example_script():
plot = False
im1 = ps.generators.blobs(shape=[600, 400], porosity=None, blobiness=1) < 0.4
im2 = ps.generators.blobs(shape=[600, 400], porosity=None, blobiness=1)... | [
"openpnm.topotools.plot_coordinates",
"porespy.generators.blobs",
"porespy.networks.snow2",
"openpnm.io.from_porespy",
"numpy.array",
"openpnm.topotools.plot_connections",
"numpy.random.seed",
"matplotlib.pyplot.axis",
"porespy.tools.randomize_colors",
"matplotlib.pyplot.subplots"
] | [((93, 110), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (107, 110), True, 'import numpy as np\n'), ((401, 528), 'porespy.networks.snow2', 'ps.networks.snow2', (['phases'], {'phase_alias': "{(1): 'solid', (2): 'void'}", 'boundary_width': '(5)', 'accuracy': '"""high"""', 'parallelization': 'None'}), "... |
from bagua.torch_api.contrib.cached_dataset import CachedDataset
from torch.utils.data.dataset import Dataset
import numpy as np
import logging
import unittest
from tests import skip_if_cuda_available
logging.basicConfig(level=logging.DEBUG)
class MyDataset(Dataset):
def __init__(self, size):
self.size =... | [
"logging.basicConfig",
"numpy.random.rand",
"bagua.torch_api.contrib.cached_dataset.CachedDataset",
"tests.skip_if_cuda_available",
"unittest.main"
] | [((202, 242), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (221, 242), False, 'import logging\n'), ((921, 945), 'tests.skip_if_cuda_available', 'skip_if_cuda_available', ([], {}), '()\n', (943, 945), False, 'from tests import skip_if_cuda_available\n'), ((16... |
import numpy as np
import argparse
from simple_algo_utils import *
if __name__=='__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,description=None)
parser.add_argument('--example_n', default=1, type=int, help=None)
parser.add_argument('--verbose', d... | [
"numpy.array",
"numpy.zeros",
"numpy.ones",
"argparse.ArgumentParser"
] | [((107, 207), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.RawDescriptionHelpFormatter', 'description': 'None'}), '(formatter_class=argparse.\n RawDescriptionHelpFormatter, description=None)\n', (130, 207), False, 'import argparse\n'), ((1010, 1054), 'numpy.array', 'np.arr... |
import logging
from vespid import setup_logger
logger = setup_logger(__name__)
import pandas as pd
import numpy as np
from tqdm import tqdm
def calculate_interdisciplinarity_score(
membership_vectors
):
'''
Given a set of entities and
one vector for each representing the (ordered) strength
of memb... | [
"numpy.unique",
"vespid.setup_logger",
"numpy.max",
"numpy.zeros",
"tqdm.tqdm.pandas"
] | [((56, 78), 'vespid.setup_logger', 'setup_logger', (['__name__'], {}), '(__name__)\n', (68, 78), False, 'from vespid import setup_logger\n'), ((7366, 7477), 'tqdm.tqdm.pandas', 'tqdm.pandas', ([], {'desc': '"""Building full cluster membership vectors from citation-based membership per paper"""'}), "(desc=\n 'Buildin... |
import numpy as np
def Linear_Fit(array_A, array_B):
"""
Returns slope and y-intercept of the line of best fit
"""
array_A = np.array(array_A)
array_B = np.array(array_B)
#Pair arrays then sort them for easier fit
zipped_list = zip(array_A[~np.isnan(array_A)], array_B[~np.isnan(array_B... | [
"numpy.array",
"numpy.isnan",
"numpy.polyfit"
] | [((142, 159), 'numpy.array', 'np.array', (['array_A'], {}), '(array_A)\n', (150, 159), True, 'import numpy as np\n'), ((174, 191), 'numpy.array', 'np.array', (['array_B'], {}), '(array_B)\n', (182, 191), True, 'import numpy as np\n'), ((421, 454), 'numpy.polyfit', 'np.polyfit', (['sorted_a', 'sorted_b', '(1)'], {}), '(... |
# OpenCV: Image processing
import cv2
import time
import popupWindow as detectionWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QThread
# numpy: numerical computa... | [
"core.utils.load_weights",
"tensorflow.keras.layers.Input",
"core.yolov3.YOLOv3",
"core.utils.draw_bbox",
"numpy.copy",
"popupWindow.DetectionWindow",
"tensorflow.shape",
"tensorflow.config.experimental.set_memory_growth",
"core.yolov3.decode",
"tensorflow.concat",
"core.utils.postprocess_boxes"... | [((494, 545), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (538, 545), True, 'import tensorflow as tf\n'), ((1219, 1269), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', (['[input_size, input_size, 3]'], {}), '([input... |
from __future__ import print_function
import os
import keras
from keras.layers import Dense,Flatten,Conv2D,MaxPooling2D,Activation,Input,Concatenate,Dropout,GlobalAveragePooling2D
from keras.models import Model
import time
from keras.datasets import cifar10
from keras.optimizers import SGD
from keras.utils impo... | [
"keras.preprocessing.image.img_to_array",
"keras.layers.Conv2D",
"keras.layers.Flatten",
"keras.datasets.cifar10.load_data",
"keras.layers.MaxPooling2D",
"keras.layers.Concatenate",
"keras.utils.to_categorical",
"numpy.zeros",
"keras.layers.Input",
"keras.optimizers.SGD",
"keras.models.Model",
... | [((1747, 1771), 'keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (1752, 1771), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Input, Concatenate, Dropout, GlobalAveragePooling2D\n'), ((3171, 3204), 'keras.models.Model', 'Model', ([], {'input': '... |
import numpy as np
from scipy.stats import binom
# import modules needed for logging
import logging
import os
logger = logging.getLogger(__name__) # module logger
def cummin(x):
"""A python implementation of the cummin function in R"""
for i in range(1, len(x)):
if x[i-1] < x[i]:
x[i] = ... | [
"logging.getLogger",
"numpy.asarray",
"scipy.stats.binom.sf",
"numpy.argsort",
"numpy.array",
"numpy.isnan",
"numpy.arange"
] | [((121, 148), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (138, 148), False, 'import logging\n'), ((763, 777), 'numpy.array', 'np.array', (['pval'], {}), '(pval)\n', (771, 777), True, 'import numpy as np\n'), ((797, 819), 'numpy.argsort', 'np.argsort', (['pval_array'], {}), '(pval_arra... |
import io
from flask import (
Blueprint,
render_template,
abort,
current_app,
make_response
)
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
client = Blueprint('client', __name__, template_folder='templates', ... | [
"flask.render_template",
"numpy.random.rand",
"matplotlib.figure.Figure",
"matplotlib.backends.backend_agg.FigureCanvasAgg",
"io.StringIO",
"flask.Blueprint"
] | [((261, 351), 'flask.Blueprint', 'Blueprint', (['"""client"""', '__name__'], {'template_folder': '"""templates"""', 'static_url_path': '"""/static"""'}), "('client', __name__, template_folder='templates', static_url_path=\n '/static')\n", (270, 351), False, 'from flask import Blueprint, render_template, abort, curre... |
"""
Requirements:
-----------
pyngrok==5.0.5
mlflow==1.15.0
pandas==1.2.3
numpy==1.19.3
scikit-learn==0.24.1
Examples of usege can be found in the url below:
https://nbviewer.jupyter.org/github/abreukuse/ml_utilities/blob/master/examples/experiments_management.ipynb
"""
import os
import mlflow
from pyngrok import ng... | [
"numpy.mean",
"mlflow.set_tag",
"numpy.sqrt",
"os.makedirs",
"pyngrok.ngrok.kill",
"sklearn.model_selection.train_test_split",
"mlflow.log_metric",
"mlflow.set_experiment",
"mlflow.get_experiment_by_name",
"mlflow.log_artifacts",
"pyngrok.ngrok.connect",
"mlflow.start_run",
"numpy.round"
] | [((574, 586), 'pyngrok.ngrok.kill', 'ngrok.kill', ([], {}), '()\n', (584, 586), False, 'from pyngrok import ngrok\n'), ((606, 661), 'pyngrok.ngrok.connect', 'ngrok.connect', ([], {'addr': '"""5000"""', 'proto': '"""http"""', 'bind_tls': '(True)'}), "(addr='5000', proto='http', bind_tls=True)\n", (619, 661), False, 'fro... |
#//////////////#####///////////////
#
# ANU u6325688 <NAME>
# Supervisor: Dr.<NAME>
#//////////////#####///////////////
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.utils.data
impor... | [
"matplotlib.pyplot.ylabel",
"torch.full",
"matplotlib.pyplot.xlabel",
"GAIL.Generator.Generator1D",
"torch.from_numpy",
"matplotlib.pyplot.close",
"torch.nn.BCELoss",
"torch.cuda.is_available",
"numpy.zeros",
"GAIL.PPO.PPO",
"GAIL.Discriminator.Discriminator1D",
"sklearn.preprocessing.normaliz... | [((598, 623), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (621, 623), False, 'import torch\n'), ((741, 766), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (764, 766), False, 'import torch\n'), ((950, 962), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (960, 96... |
from __future__ import print_function, division
from black import out
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
try:
from itertools import ifilterfalse
except ImportErro... | [
"torch.sort",
"torch.log",
"numpy.unique",
"numpy.ones",
"torch.nn.CrossEntropyLoss",
"torch.mean",
"sklearn.utils.class_weight.compute_class_weight",
"torch.exp",
"itertools.filterfalse",
"torch.pow",
"numpy.array",
"torch.from_numpy",
"torch.sum",
"torch.nn.functional.one_hot",
"torch.... | [((8712, 8754), 'torch.sort', 'torch.sort', (['errors'], {'dim': '(0)', 'descending': '(True)'}), '(errors, dim=0, descending=True)\n', (8722, 8754), False, 'import torch\n'), ((13562, 13594), 'torch.nn.functional.one_hot', 'F.one_hot', (['categorical', 'nb_class'], {}), '(categorical, nb_class)\n', (13571, 13594), Tru... |
# imports
import numpy as np
from rubin_sim.maf.metrics.baseMetric import BaseMetric
# constants
__all__ = ["UseMetric"]
# exception classes
# interface functions
# classes
class UseMetric(BaseMetric): # pylint: disable=too-few-public-methods
"""Metric to classify visits by type of visits"""
def __ini... | [
"numpy.all"
] | [((1251, 1272), 'numpy.all', 'np.all', (['(notes == note)'], {}), '(notes == note)\n', (1257, 1272), True, 'import numpy as np\n')] |
import time
import numpy as np
from tqdm import tqdm
from sklearn.decomposition import MiniBatchDictionaryLearning
from .metrics import distance_between_atoms
from .visualizations import show_dictionary_atoms_img
from .plots import plot_reconstruction_error_and_dictionary_distances
def loader(X, batch_size):
for ... | [
"numpy.copy",
"sklearn.decomposition.MiniBatchDictionaryLearning",
"numpy.array",
"numpy.zeros",
"time.time"
] | [((1165, 1290), 'sklearn.decomposition.MiniBatchDictionaryLearning', 'MiniBatchDictionaryLearning', ([], {'n_components': 'n_atoms', 'batch_size': 'batch_size', 'transform_algorithm': '"""lasso_lars"""', 'verbose': '(False)'}), "(n_components=n_atoms, batch_size=batch_size,\n transform_algorithm='lasso_lars', verbos... |
import sys
import os
# Add basedir to path
script_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(script_dir + "/../")
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from data.utils import read_pickle_from_file
from dscribe.descriptors import ACSF
... | [
"data.utils.read_pickle_from_file",
"pandas.read_csv",
"torch.from_numpy",
"os.path.dirname",
"numpy.array",
"numpy.concatenate",
"torch.utils.data.DataLoader",
"numpy.ravel",
"sys.path.append",
"numpy.load",
"time.time"
] | [((100, 136), 'sys.path.append', 'sys.path.append', (["(script_dir + '/../')"], {}), "(script_dir + '/../')\n", (115, 136), False, 'import sys\n'), ((73, 98), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (88, 98), False, 'import os\n'), ((4884, 4976), 'torch.utils.data.DataLoader', 'DataLoa... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: pysemeels.tools.generate_hdf5_file
.. moduleauthor:: <NAME> <<EMAIL>>
Generate HDF5 file from Hitachi EELS data.
"""
###############################################################################
# Copyright 2017 <NAME>
#
# Licensed under the... | [
"numpy.zeros",
"pysemeels.hitachi.eels_su.elv_file.ElvFile",
"pysemeels.hitachi.eels_su.elv_text_file.ElvTextParameters",
"numpy.arange"
] | [((1859, 1878), 'pysemeels.hitachi.eels_su.elv_text_file.ElvTextParameters', 'ElvTextParameters', ([], {}), '()\n', (1876, 1878), False, 'from pysemeels.hitachi.eels_su.elv_text_file import ElvTextParameters\n'), ((2883, 2892), 'pysemeels.hitachi.eels_su.elv_file.ElvFile', 'ElvFile', ([], {}), '()\n', (2890, 2892), Fal... |
import sys
import click
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras.backend as K
import tensorflow_probability as tfp
import statsmodels.api as sm
import xgboost as xgb
import matplotlib.pyplot as plt
import seaborn as sns
from abc import ABC, abstractmethod
from pathlib... | [
"tensorflow.cast",
"numpy.random.RandomState",
"seaborn.set",
"pathlib.Path",
"click.option",
"bore_experiments.datasets.make_classification_dataset",
"numpy.linspace",
"click.command",
"click.argument",
"statsmodels.api.nonparametric.KDEUnivariate",
"tensorflow.keras.losses.BinaryCrossentropy",... | [((717, 740), 'tensorflow.keras.backend.set_floatx', 'K.set_floatx', (['"""float64"""'], {}), "('float64')\n", (729, 740), True, 'import tensorflow.keras.backend as K\n'), ((3229, 3244), 'click.command', 'click.command', ([], {}), '()\n', (3242, 3244), False, 'import click\n'), ((3246, 3268), 'click.argument', 'click.a... |
"""
imgLog.py - experimental log for imgFolder
initial: 2019-10-04
"""
import os
import pandas as pd
if ('np' not in dir()): import numpy as np
from imlib.imgfolder import ImgFolder
__author__ = '<NAME> <<EMAIL>>'
__version__ = '1.0.0'
class ImgLog(ImgFolder):
""" imgFolder for channel experiment images """
... | [
"os.path.isfile",
"numpy.array",
"pandas.ExcelWriter",
"pandas.read_excel"
] | [((2968, 2998), 'os.path.isfile', 'os.path.isfile', (['self._logfname'], {}), '(self._logfname)\n', (2982, 2998), False, 'import os\n'), ((2744, 2774), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['self._logfname'], {}), '(self._logfname)\n', (2758, 2774), True, 'import pandas as pd\n'), ((3102, 3144), 'pandas.read_excel'... |
from mcc_libusb import *
import datetime
import time
import numpy as np
mcc = USB1208FS()
mcc.usbOpen()
#mcc.usbDConfigPort(DIO_PORTA, DIO_DIR_OUT)
#mcc.usbDConfigPort(DIO_PORTB, DIO_DIR_IN)
#mcc.usbDOut(DIO_PORTA, 0)
#num = mcc.usbAIn(1, BP_1_00V)
#print(str(mcc.volts_FS(BP_1_00V, num)))
#channel = np.array([1, 2, 3... | [
"numpy.average"
] | [((585, 602), 'numpy.average', 'np.average', (['sdata'], {}), '(sdata)\n', (595, 602), True, 'import numpy as np\n')] |
import sys
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.backends import cudnn
from utils.utils import cast
from utils.utils0 import logging, reset_logging, timeLog, raise_if_absent, add_if_absent_
from .dpcnn import dpcnn
from .prep_text import TextData_Uni, TextData_Lab, TextDa... | [
"utils.utils0.raise_if_absent",
"torch.manual_seed",
"numpy.random.get_state",
"utils.utils0.add_if_absent_",
"numpy.random.set_state",
"utils.utils.cast",
"os.path.exists",
"utils.utils0.timeLog",
"gulf.train_base_model",
"gulf.train_gulf_model",
"gulf.copy_params",
"torch.cuda.is_available",... | [((2349, 2395), 'utils.utils0.raise_if_absent', 'raise_if_absent', (['opt', 'names'], {'who': '"""dpcnn_train"""'}), "(opt, names, who='dpcnn_train')\n", (2364, 2395), False, 'from utils.utils0 import logging, reset_logging, timeLog, raise_if_absent, add_if_absent_\n'), ((2429, 2483), 'utils.utils0.add_if_absent_', 'ad... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import random
import psutil
import logging
import pandas as pd
import numpy as np
from io import open
from collections import Counter
from multiprocessing import cpu_count
from concurrent.futures import ProcessPoolExecutor
from scipy.sparse import csr... | [
"logging.getLogger",
"pdb.pm",
"pandas.read_csv",
"io.open",
"sys.stderr.isatty",
"multiprocessing.cpu_count",
"sys.__excepthook__",
"argparse.ArgumentParser",
"fastGraph.ngram.build_ngram",
"random.Random",
"fastGraph.graph.Graph",
"traceback.print_exception",
"gensim.models.Word2Vec",
"g... | [((882, 919), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'LOGFORMAT'}), '(format=LOGFORMAT)\n', (901, 919), False, 'import logging\n'), ((930, 960), 'logging.getLogger', 'logging.getLogger', (['"""fastGraph"""'], {}), "('fastGraph')\n", (947, 960), False, 'import logging\n'), ((706, 717), 'os.getpid'... |
# coding=utf-8
import sys
import os
import csv
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import drange
from matplotlib.patches import Rectangle
import scenario_factory
# http://www.javascripter.net/faq/hextorgb.htm
PRIMA = (148/256, 164/256, 1... | [
"matplotlib.patches.Rectangle",
"numpy.repeat",
"numpy.roll",
"numpy.ma.array",
"os.path.join",
"numpy.array",
"os.path.dirname",
"numpy.zeros",
"os.path.isdir",
"datetime.timedelta",
"numpy.load",
"csv.reader",
"matplotlib.pyplot.subplots",
"scenario_factory.Scenario",
"matplotlib.pyplo... | [((1295, 1318), 'numpy.ma.array', 'np.ma.array', (['P_el_sched'], {}), '(P_el_sched)\n', (1306, 1318), True, 'import numpy as np\n'), ((1331, 1349), 'numpy.array', 'np.array', (['sc.block'], {}), '(sc.block)\n', (1339, 1349), True, 'import numpy as np\n'), ((1723, 1751), 'numpy.repeat', 'np.repeat', (['P_el_ctrl[:-1]',... |
"""
This module tests nipy's uses of aliased sympy expressions.
That is, sympy.Function's whose value is an arbitrary callable.
In these tests, the callable's are scipy.interpolate.interp1d instances
representing approximations to Brownian Motions.
"""
import numpy as np
import scipy.interpolate
import pylab
import ... | [
"numpy.random.standard_normal",
"numpy.sqrt",
"numpy.arange",
"nipy.modalities.fmri.aliased._add_aliases_to_namespace",
"sympy.lambdify",
"numpy.exp",
"nipy.modalities.fmri.formula.aliased_function",
"numpy.cumsum",
"sympy.DeferredVector"
] | [((411, 432), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(0.01)'], {}), '(0, 5, 0.01)\n', (420, 432), True, 'import numpy as np\n'), ((439, 472), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(500,)'], {}), '((500,))\n', (464, 472), True, 'import numpy as np\n'), ((633, 665), 'nipy.modalities.fmri.... |
import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*(testing.product({
'batchsize': [1, 5],
'size': [10, 20],
'dtype': [numpy.float32],
'eps': [1e-5, 1e-1],
})))
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
]
# GPU tests
... | [
"numpy.mean",
"numpy.prod",
"numpy.sqrt",
"chainer.functions.layer_normalization",
"chainer.testing.run_module",
"numpy.square",
"chainer.testing.product",
"numpy.expand_dims",
"numpy.random.uniform"
] | [((2133, 2171), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (2151, 2171), False, 'from chainer import testing\n'), ((1658, 1694), 'numpy.mean', 'numpy.mean', (['x'], {'axis': '(1)', 'keepdims': '(True)'}), '(x, axis=1, keepdims=True)\n', (1668, 1694), Fa... |
import numpy as np
import pandas as pd
array = [1,3,4,7,8,10,15]
np_array = np.array(array)
print("Arranjo NumPy")
print(np_array)
print("Convertendo para serie Pandas")
ds_array = pd.Series(np_array)
print("Serie Pandas")
print(ds_array) | [
"pandas.Series",
"numpy.array"
] | [((78, 93), 'numpy.array', 'np.array', (['array'], {}), '(array)\n', (86, 93), True, 'import numpy as np\n'), ((186, 205), 'pandas.Series', 'pd.Series', (['np_array'], {}), '(np_array)\n', (195, 205), True, 'import pandas as pd\n')] |
# Copyright 2022 NVIDIA Corporation
#
# 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 wr... | [
"cunumeric.indices",
"numpy.indices",
"pytest.main",
"numpy.array_equal",
"random.randint"
] | [((861, 883), 'numpy.indices', 'np.indices', (['dimensions'], {}), '(dimensions)\n', (871, 883), True, 'import numpy as np\n'), ((897, 919), 'cunumeric.indices', 'cn.indices', (['dimensions'], {}), '(dimensions)\n', (907, 919), True, 'import cunumeric as cn\n'), ((931, 961), 'numpy.array_equal', 'np.array_equal', (['np... |
import tensorflow as tf
import numpy as np
import os
import imageio
from utils import get_shardsize, get_zeros_array
def resize(image, target_shape):
imdtype = image.dtype
with tf.device('/CPU:0'):
image = tf.image.resize(image, target_shape[:2]).numpy()
assert image.shape == target_shape
retur... | [
"tensorflow.device",
"os.listdir",
"imageio.imread",
"tensorflow.image.resize",
"os.path.join",
"os.path.isfile",
"os.path.isdir",
"tensorflow.constant",
"os.mkdir",
"numpy.concatenate",
"numpy.expand_dims",
"utils.get_zeros_array",
"utils.get_shardsize",
"numpy.save"
] | [((2888, 2912), 'os.path.isfile', 'os.path.isfile', (['writedir'], {}), '(writedir)\n', (2902, 2912), False, 'import os\n'), ((3406, 3433), 'utils.get_shardsize', 'get_shardsize', (['target_shape'], {}), '(target_shape)\n', (3419, 3433), False, 'from utils import get_shardsize, get_zeros_array\n'), ((3454, 3483), 'util... |
import params
import numpy as np
def calc_min_delta_t(delta_x, alpha, v_max) -> int:
return min(1, 1 / 4 * delta_x ** 2 / alpha, delta_x / v_max)
def adjust_boundary(T, v_x, v_y):
T[0, :] = params.T_h
T[-1, :] = T[-2, :]
T[:, 0] = T[:, 1]
T[:, -1] = T[:, -2]
v_y[0, :] = 0
v_y[-1, :] = v_... | [
"numpy.zeros"
] | [((1184, 1205), 'numpy.zeros', 'np.zeros', (['T_cen.shape'], {}), '(T_cen.shape)\n', (1192, 1205), True, 'import numpy as np\n')] |
import warnings
import numpy as np
from tabulate import tabulate
from collections import Counter
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import precision_score, recall_score, f1_score
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def get_sentiment(documents, docu... | [
"vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer",
"numpy.mean",
"sklearn.metrics.f1_score",
"tabulate.tabulate",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"numpy.array",
"numpy.sum",
"warnings.filterwarnings",
"numpy.round"
] | [((699, 727), 'vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer', 'SentimentIntensityAnalyzer', ([], {}), '()\n', (725, 727), False, 'from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n'), ((1592, 1625), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')... |
import numpy as np
import matplotlib.pyplot as plt
with open('input.txt', 'r') as f:
stream = f.readline()
image = np.array(tuple(map(int, stream))).reshape(-1, 6, 25)
nonzero_counts = np.sum(np.count_nonzero(image, axis=2), axis=1)
fewest_zeros_layer = np.argsort(nonzero_counts)[-1]
unique_values, counts = np.u... | [
"matplotlib.pyplot.imshow",
"numpy.unique",
"numpy.where",
"numpy.count_nonzero",
"numpy.argsort",
"numpy.zeros",
"matplotlib.pyplot.show"
] | [((316, 372), 'numpy.unique', 'np.unique', (['image[fewest_zeros_layer]'], {'return_counts': '(True)'}), '(image[fewest_zeros_layer], return_counts=True)\n', (325, 372), True, 'import numpy as np\n'), ((437, 454), 'numpy.zeros', 'np.zeros', (['(6, 25)'], {}), '((6, 25))\n', (445, 454), True, 'import numpy as np\n'), ((... |
#!/usr/bin/env python
import glob,os
import numpy as np
from bunch import Bunch
import mygis as io
import load_data
def adjust_p(p,h,dz):
'''Convert p [Pa] at elevation h [m] by shifting its elevation by dz [m]'''
# p in pascals
# h,dz in meters
# slp = p/(1 - 2.25577E-5*h)**5.25588
# p=slp*(1... | [
"numpy.arange",
"numpy.diff",
"numpy.zeros",
"load_data.cols",
"numpy.meshgrid",
"glob.glob",
"os.remove"
] | [((436, 460), 'load_data.cols', 'load_data.cols', (['filename'], {}), '(filename)\n', (450, 460), False, 'import load_data\n'), ((1074, 1109), 'numpy.arange', 'np.arange', (['(0)', '(nz * base.dz)', 'base.dz'], {}), '(0, nz * base.dz, base.dz)\n', (1083, 1109), True, 'import numpy as np\n'), ((1113, 1138), 'glob.glob',... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | [
"numpy.arange"
] | [((896, 909), 'numpy.arange', 'np.arange', (['nx'], {}), '(nx)\n', (905, 909), True, 'import numpy as np\n'), ((922, 935), 'numpy.arange', 'np.arange', (['ny'], {}), '(ny)\n', (931, 935), True, 'import numpy as np\n'), ((970, 988), 'numpy.arange', 'np.arange', (['(nx * ny)'], {}), '(nx * ny)\n', (979, 988), True, 'impo... |
""""
STRIP Scanning Strategy Tools test module.
"""
import unittest
import healpy as hp
import numpy as np
from ScanningTools import ScanningTools as st
from astropy.time import Time
from astropy.coordinates import SkyCoord, AltAz
from ScanningTools.Quaternions import Quaternion as q
angles = np.array([[-10, 45, 59... | [
"ScanningTools.ScanningTools.dec2sex",
"numpy.radians",
"ScanningTools.ScanningTools.spin_generator",
"numpy.array",
"ScanningTools.ScanningTools.get_full_fp_polarization_angles",
"numpy.arctan2",
"unittest.main",
"ScanningTools.ScanningTools.get_nside_eff",
"ScanningTools.ScanningTools.hours2degree... | [((298, 364), 'numpy.array', 'np.array', (['[[-10, 45, 59], [30, 35, 15], [-180, 25, 20], [3, 4, 5]]'], {}), '([[-10, 45, 59], [30, 35, 15], [-180, 25, 20], [3, 4, 5]])\n', (306, 364), True, 'import numpy as np\n'), ((425, 462), 'numpy.array', 'np.array', (['[[23, 59, 16], [7, 56, 59]]'], {}), '([[23, 59, 16], [7, 56, ... |
r"""
Mutual Coherence and Babel Function are the properties of a matrix, used to
estimate the Spark of a matrix, which in turn is used to determine the
optimality of the solution to :math:`\text{P}_0` problem.
Babel Function gives a tighter bound on the Spark of a matrix.
Spark of a matrix :math:`\boldsymbol{A}` is t... | [
"collections.namedtuple",
"numpy.reshape",
"math.ceil",
"numpy.fill_diagonal",
"numpy.nonzero",
"numpy.linalg.norm"
] | [((615, 667), 'collections.namedtuple', 'namedtuple', (['"""CoherenceSpark"""', "('coherence', 'spark')"], {}), "('CoherenceSpark', ('coherence', 'spark'))\n", (625, 667), False, 'from collections import namedtuple\n'), ((1712, 1737), 'numpy.fill_diagonal', 'np.fill_diagonal', (['gram', '(0)'], {}), '(gram, 0)\n', (172... |
"""
Created on Sun Feb 12 11:51:29 2017
@author: <NAME>
Class: Computer Architecture
Language Python 2.7
Input an array of hex-instructions, and return a of decoded MIPS instructions (e.g. 7a078 ADD $2, $9, $8).
Instruction types de-constructed in this assignment are ADD, AND, OR, SLT, SUB, BEQ, BNE, LW, a... | [
"numpy.array",
"numpy.vectorize"
] | [((642, 668), 'numpy.array', 'np.array', (['hex_instructions'], {}), '(hex_instructions)\n', (650, 668), True, 'import numpy as np\n'), ((677, 694), 'numpy.vectorize', 'np.vectorize', (['hex'], {}), '(hex)\n', (689, 694), True, 'import numpy as np\n')] |
import sklearn.datasets
import sklearn.model_selection
import sklearn.linear_model
import numpy
import compare_auc_delong_xu
import unittest
import scipy.stats
class TestIris(unittest.TestCase):
@classmethod
def setUpClass(cls):
data = sklearn.datasets.load_iris()
x_train, x_test, y_train, ... | [
"numpy.ones",
"numpy.testing.assert_allclose",
"compare_auc_delong_xu.delong_roc_variance",
"numpy.zeros",
"numpy.empty",
"numpy.random.seed"
] | [((758, 830), 'compare_auc_delong_xu.delong_roc_variance', 'compare_auc_delong_xu.delong_roc_variance', (['self.y_test', 'self.predictions'], {}), '(self.y_test, self.predictions)\n', (799, 830), False, 'import compare_auc_delong_xu\n'), ((839, 891), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
"""
import pytest
import os
import tarfile
from pathlib import Path
import nibabel as nib
import numpy as np
from ....tests.resource import setup as setuptestresources
from .... | [
"nipype.interfaces.ants.ApplyTransforms",
"numpy.abs",
"tarfile.open",
"numpy.isclose",
"nibabel.load",
"pathlib.Path",
"templateflow.api.get",
"nipype.interfaces.ants.ResampleImageBySpacing",
"pytest.mark.parametrize",
"nipype.interfaces.fsl.MultipleRegressDesign",
"pytest.fixture",
"pytest.m... | [((683, 713), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (697, 713), False, 'import pytest\n'), ((1566, 1596), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1580, 1596), False, 'import pytest\n'), ((1996, 2026), 'pytest.fixtur... |
from __future__ import annotations
import mmap
import threading
from enum import Enum
from itertools import product
from pathlib import Path
from typing import (
TYPE_CHECKING,
Optional,
Sequence,
Set,
Sized,
SupportsInt,
Union,
cast,
overload,
)
import numpy as np
from ._util imp... | [
"numpy.prod",
"numpy.hstack",
"pathlib.Path",
"numpy.ravel_multi_index",
"dask.array.map_blocks",
"threading.RLock",
"itertools.product",
"resource_backed_dask_array.ResourceBackedDaskArray.from_array",
"xarray.DataArray",
"numpy.dtype",
"typing.cast",
"numpy.arange"
] | [((1978, 1995), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (1993, 1995), False, 'import threading\n'), ((3150, 3167), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (3165, 3167), False, 'import threading\n'), ((6028, 6061), 'typing.cast', 'cast', (['Attributes', 'self.attributes'], {}), '(Attribut... |
# Copyright 2017 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... | [
"logging.getLogger",
"ray.tune.suggest.bayesopt.BayesOptSearch",
"tensorflow.unstack",
"itertools.chain",
"cifar10.Cifar10DataSet",
"tensorflow.logging.set_verbosity",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.gradients",
"tensorflow.group",
"numpy.array",
"six.moves.xrange",
"tensorfl... | [((1608, 1650), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (1632, 1650), True, 'import tensorflow as tf\n'), ((1891, 1916), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1914, 1916), False, 'import argparse\n'), ((16042,... |
import torch
import cv2 as cv
import numpy as np
from sklearn.neighbors import NearestNeighbors
from .model_utils import spread_feature
def optimize_image_mask(image_mask, sp_image, nK=4, th=1e-2):
mask_pts = image_mask.reshape(-1)
xyz_pts = sp_image.reshape(-1, 3)
xyz_pts = xyz_pts[mask_pts > 0.5, :]
... | [
"cv2.Laplacian",
"numpy.ones",
"torch.from_numpy",
"cv2.morphologyEx",
"numpy.zeros",
"numpy.sum",
"sklearn.neighbors.NearestNeighbors",
"cv2.resize",
"cv2.getStructuringElement"
] | [((1330, 1503), 'cv2.resize', 'cv.resize', (['image_learned_uv'], {'dsize': '(image_resize_factor * image_learned_uv.shape[0], image_resize_factor *\n image_learned_uv.shape[1])', 'interpolation': 'cv.INTER_LINEAR'}), '(image_learned_uv, dsize=(image_resize_factor * image_learned_uv.\n shape[0], image_resize_fact... |
import logging
import os
import numpy as np
import torch
if torch.cuda.is_available():
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
def _patch_noise_extend_to_i... | [
"numpy.clip",
"logging.getLogger",
"os.path.exists",
"logging.StreamHandler",
"numpy.sqrt",
"os.makedirs",
"logging.Formatter",
"torch.load",
"numpy.zeros",
"torch.cuda.is_available",
"logging.FileHandler",
"numpy.random.randint",
"torch.save",
"numpy.int",
"torch.zeros",
"torch.device... | [((62, 87), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (85, 87), False, 'import torch\n'), ((230, 250), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (242, 250), False, 'import torch\n'), ((270, 289), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.