code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""Converting tools for extinction."""
import pylab as P
import numpy as N
def from_ebv_sfd_to_sdss_albd(ebv):
"""Return A(lbd) for the 5 SDSS filters: u, g, r, i, z."""
coeff = {'u': 5.155, 'g': 3.793, 'r': 2.751, 'i': 2.086, 'z': 1.479}
return {f: coeff[f] * N.array(ebv) for f in coeff}
def from_sdss... | [
"pylab.figure",
"numpy.array",
"numpy.mean",
"pylab.show"
] | [((1135, 1145), 'pylab.figure', 'P.figure', ([], {}), '()\n', (1143, 1145), True, 'import pylab as P\n'), ((1455, 1465), 'pylab.figure', 'P.figure', ([], {}), '()\n', (1463, 1465), True, 'import pylab as P\n'), ((1722, 1730), 'pylab.show', 'P.show', ([], {}), '()\n', (1728, 1730), True, 'import pylab as P\n'), ((276, 2... |
import os
from packaging.version import Version
import numpy as np
import pandas as pd
from shapely.geometry import Point, Polygon, LineString, GeometryCollection, box
from fiona.errors import DriverError
import geopandas
from geopandas import GeoDataFrame, GeoSeries, overlay, read_file
from geopandas import _compat... | [
"pytest.mark.filterwarnings",
"shapely.geometry.box",
"shapely.geometry.Point",
"pandas.Index",
"numpy.array",
"shapely.geometry.Polygon",
"geopandas.overlay",
"pytest.fixture",
"pandas.testing.assert_frame_equal",
"pytest.xfail",
"geopandas.testing.assert_geodataframe_equal",
"pytest.skip",
... | [((1085, 1154), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['default-index', 'int-index', 'string-index']"}), "(params=['default-index', 'int-index', 'string-index'])\n", (1099, 1154), False, 'import pytest\n'), ((1394, 1496), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['union', 'intersection', 'dif... |
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Power flow data for IEEE 118 bus test case.
"""
from numpy import array
def case118():
"""Power flow data for IEEE 118 bus test case.
Please see L{cas... | [
"numpy.array"
] | [((1095, 8510), 'numpy.array', 'array', (['[[1, 2, 51, 27, 0, 0, 1, 0.955, 10.67, 138, 1, 1.06, 0.94], [2, 1, 20, 9, 0,\n 0, 1, 0.971, 11.22, 138, 1, 1.06, 0.94], [3, 1, 39, 10, 0, 0, 1, 0.968,\n 11.56, 138, 1, 1.06, 0.94], [4, 2, 39, 12, 0, 0, 1, 0.998, 15.28, 138, \n 1, 1.06, 0.94], [5, 1, 0, 0, 0, -40, 1, 1... |
from typing import Union, Container
from itertools import chain
import numpy as np
import scipy.sparse as sp
modALinput = Union[list, np.ndarray, sp.csr_matrix]
def data_vstack(blocks: Container) -> modALinput:
"""
Stack vertically both sparse and dense arrays.
Args:
blocks: Sequence of modALi... | [
"itertools.chain",
"scipy.sparse.issparse",
"scipy.sparse.vstack",
"numpy.concatenate"
] | [((466, 488), 'numpy.concatenate', 'np.concatenate', (['blocks'], {}), '(blocks)\n', (480, 488), True, 'import numpy as np\n'), ((731, 753), 'scipy.sparse.issparse', 'sp.issparse', (['blocks[0]'], {}), '(blocks[0])\n', (742, 753), True, 'import scipy.sparse as sp\n'), ((707, 720), 'itertools.chain', 'chain', (['blocks'... |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
"""Defines the ModelAnalysis class."""
import json
import numpy as np
import pandas as pd
from pathlib import Path
import pickle
import warnings
from responsibleai._input_processing import _convert_to_list
from responsibleai._interfaces import ... | [
"pickle.dumps",
"responsibleai.exceptions.UserConfigValidationException",
"responsibleai._interfaces.ModelAnalysisData",
"pathlib.Path",
"json.dumps",
"warnings.warn",
"pandas.read_json",
"responsibleai._managers.counterfactual_manager.CounterfactualManager",
"json.loads",
"responsibleai._managers... | [((4939, 5013), 'responsibleai._managers.causal_manager.CausalManager', 'CausalManager', (['train', 'test', 'target_column', 'task_type', 'categorical_features'], {}), '(train, test, target_column, task_type, categorical_features)\n', (4952, 5013), False, 'from responsibleai._managers.causal_manager import CausalManage... |
"""
This module defines a class used for evaluating coordinate transformations at null shell junctions.
"""
import numpy as np
import interpolators as interp
from helpers import *
class active_slice:
"""
Class for handling shell and corner slicing of SSS regions. Given the region and the slice parameters,
re... | [
"numpy.array",
"numpy.isfinite",
"interpolators.interp_with_smooth_extrap"
] | [((4644, 4721), 'interpolators.interp_with_smooth_extrap', 'interp.interp_with_smooth_extrap', (['udl', 'self.uvdl_v0[0]', 'self.U_v0'], {'mu': 'self.mu'}), '(udl, self.uvdl_v0[0], self.U_v0, mu=self.mu)\n', (4676, 4721), True, 'import interpolators as interp\n'), ((4945, 5022), 'interpolators.interp_with_smooth_extrap... |
import struct
import xml.etree.ElementTree as ETree
from collections import defaultdict
import mne
import numpy as np
from pyxdf import load_xdf, match_streaminfos, resolve_streams
from pyxdf.pyxdf import open_xdf, _read_varlen_int
def read_raw_xdf(fname, stream_id, srate="effective", prefix_markers=False, *args,
... | [
"pyxdf.pyxdf._read_varlen_int",
"mne.create_info",
"pyxdf.pyxdf.open_xdf",
"pyxdf.load_xdf",
"numpy.array",
"collections.defaultdict",
"xml.etree.ElementTree.fromstring",
"mne.io.RawArray",
"pyxdf.resolve_streams"
] | [((979, 994), 'pyxdf.load_xdf', 'load_xdf', (['fname'], {}), '(fname)\n', (987, 994), False, 'from pyxdf import load_xdf, match_streaminfos, resolve_streams\n'), ((2049, 2107), 'mne.create_info', 'mne.create_info', ([], {'ch_names': 'labels', 'sfreq': 'fs', 'ch_types': '"""eeg"""'}), "(ch_names=labels, sfreq=fs, ch_typ... |
"""
Predict state-level electricity demand.
Using hourly electricity demand reported at the balancing authority and utility
level in the FERC 714, and service territories for utilities and balancing
autorities inferred from the counties served by each utility, and the utilities
that make up each balancing authority in... | [
"logging.getLogger",
"logging.StreamHandler",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"pandas.option_context",
"datetime.timedelta",
"pandas.to_datetime",
"argparse.ArgumentParser",
"pathlib.Path",
"matplotlib.pyplot.xlabel",
"sqlalchemy.create_engine",
"matplotlib.pyplot.plot",
"nump... | [((1566, 1593), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1583, 1593), False, 'import logging\n'), ((9996, 10123), 'pandas.read_csv', 'pd.read_csv', (['path'], {'usecols': "['State/Province', 'Local Datetime (Hour Ending)', 'Time Zone',\n 'Estimated State Load MW - Sum']"}), "(pa... |
"""
pysteps.timeseries.autoregression
=================================
Methods related to autoregressive AR(p) models.
.. autosummary::
:toctree: ../generated/
adjust_lag2_corrcoef1
adjust_lag2_corrcoef2
ar_acf
estimate_ar_params_ols
estimate_ar_params_ols_localized
estimate_ar_params_yw... | [
"numpy.prod",
"numpy.sqrt",
"numpy.hstack",
"numpy.column_stack",
"numpy.array",
"numpy.isfinite",
"numpy.einsum",
"numpy.diff",
"numpy.dot",
"numpy.empty",
"numpy.vstack",
"numpy.concatenate",
"numpy.maximum",
"numpy.abs",
"numpy.eye",
"numpy.linalg.eig",
"numpy.ones",
"numpy.any"... | [((1142, 1196), 'numpy.maximum', 'np.maximum', (['gamma_2', '(2 * gamma_1 * gamma_1 - 1 + 1e-10)'], {}), '(gamma_2, 2 * gamma_1 * gamma_1 - 1 + 1e-10)\n', (1152, 1196), True, 'import numpy as np\n'), ((1211, 1241), 'numpy.minimum', 'np.minimum', (['gamma_2', '(1 - 1e-10)'], {}), '(gamma_2, 1 - 1e-10)\n', (1221, 1241), ... |
from __future__ import print_function
import os
import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
#import pandas as pd ### For future manipulations
#import scipy as sp ### For future manipulations
#import matplotlib.pyplot as plt #### Uncomment and use if you would like to see the traiing ... | [
"keras.optimizers.Adam",
"keras.layers.MaxPooling1D",
"sklearn.preprocessing.LabelEncoder",
"numpy.median",
"keras.layers.Flatten",
"sklearn.preprocessing.OneHotEncoder",
"keras.models.Sequential",
"os.path.realpath",
"keras.layers.BatchNormalization",
"keras.layers.Input",
"keras.callbacks.Tens... | [((4869, 4897), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (4895, 4897), False, 'from sklearn import preprocessing, cross_validation, neighbors\n'), ((5081, 5109), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (5107, 5109), False, 'from ... |
"""Test capabilities for optimization.
This module contains a host of models and functions often used for testing optimization
algorithms.
"""
import sys
import numpy as np
import pandas as pd
from scipy.optimize import rosen
def ackley(x, a=20, b=0.2, c=2 * np.pi):
r"""Ackley function.
.. mat... | [
"numpy.multiply",
"numpy.ones",
"numpy.square",
"numpy.exp",
"sys.exit",
"scipy.optimize.rosen",
"numpy.atleast_1d"
] | [((5187, 5195), 'scipy.optimize.rosen', 'rosen', (['x'], {}), '(x)\n', (5192, 5195), False, 'from scipy.optimize import rosen\n'), ((5007, 5064), 'sys.exit', 'sys.exit', (['"""The parameter x must be an array like object."""'], {}), "('The parameter x must be an array like object.')\n", (5015, 5064), False, 'import sys... |
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.distributions import Normal
from torch import distributions
from torch.nn.parameter import Parameter
import ipdb
from sklearn import cluster, datasets, mixture
from sklearn.preprocessing import StandardScaler
from flows.flo... | [
"nflows.flows.base.Flow",
"torch.nn.init.constant_",
"numpy.log",
"torch.exp",
"e2cnn.gspaces.Flip2dOnR2",
"nflows.transforms.base.CompositeTransform",
"torch.cuda.is_available",
"torch.arange",
"e2cnn.gspaces.Rot2dOnR2",
"nflows.transforms.autoregressive.MaskedAffineAutoregressiveTransform",
"t... | [((1086, 1113), 'e2cnn.gspaces.FlipRot2dOnR2', 'gspaces.FlipRot2dOnR2', ([], {'N': '(16)'}), '(N=16)\n', (1107, 1113), False, 'from e2cnn import gspaces\n'), ((1132, 1159), 'e2cnn.gspaces.FlipRot2dOnR2', 'gspaces.FlipRot2dOnR2', ([], {'N': '(12)'}), '(N=12)\n', (1153, 1159), False, 'from e2cnn import gspaces\n'), ((117... |
"""Age-Fitness selection
This module implements the Age-Fitness selection algorithm that defines
the selection used in the Age-Fitness evolutionary algorithm module.
This module expects to be used in conjunction with the
``RandomIndividualVariation`` module that wraps the ``VarOr`` module.
"""
import numpy as np
from... | [
"numpy.random.choice",
"numpy.array",
"numpy.random.randint",
"numpy.isnan"
] | [((896, 908), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (904, 908), True, 'import numpy as np\n'), ((3105, 3167), 'numpy.random.choice', 'np.random.choice', (['max_int', 'self._selection_size'], {'replace': '(False)'}), '(max_int, self._selection_size, replace=False)\n', (3121, 3167), True, 'import numpy as np... |
#! /usr/bin/env python
import os
import logging
import numpy
from timeit import default_timer as timer
import pandas
from metax import __version__
from metax import Logging
from metax import Exceptions
from metax import Utilities
from metax.predixcan import MultiPrediXcanAssociation
from metax.predixcan import Utili... | [
"os.path.exists",
"argparse.ArgumentParser",
"timeit.default_timer",
"metax.Utilities.ensure_requisite_folders",
"metax.Utilities.save_dataframe",
"os.path.split",
"metax.predixcan.Simulations.context_from_args",
"logging.log",
"metax.predixcan.MultiPrediXcanAssociation.dataframe_from_results",
"p... | [((422, 429), 'timeit.default_timer', 'timer', ([], {}), '()\n', (427, 429), True, 'from timeit import default_timer as timer\n'), ((452, 485), 'os.path.split', 'os.path.split', (['args.output_prefix'], {}), '(args.output_prefix)\n', (465, 485), False, 'import os\n'), ((683, 711), 'os.path.exists', 'os.path.exists', ([... |
import numpy as np
import skimage.transform
import pandas as pd
import cv2
from scipy.ndimage.interpolation import map_coordinates
# from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
# Function to distort image
def elastic_transform(image, alp... | [
"cv2.warpAffine",
"numpy.reshape",
"numpy.arange",
"scipy.ndimage.interpolation.map_coordinates",
"cv2.getAffineTransform",
"numpy.zeros_like",
"numpy.float32",
"numpy.random.RandomState"
] | [((587, 728), 'numpy.float32', 'np.float32', (['[center_square + square_size, [center_square[0] + square_size, \n center_square[1] - square_size], center_square - square_size]'], {}), '([center_square + square_size, [center_square[0] + square_size, \n center_square[1] - square_size], center_square - square_size])... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 19, 2018
@author: <NAME>
This contains functions to calculate recombination rates. More types of recombination will be
added later.
"""
import numpy as np
from numba import jit
class Recombo():
def __init__(self, params):
self.R_Langevin = np.zeros(par... | [
"numpy.zeros"
] | [((308, 333), 'numpy.zeros', 'np.zeros', (['params.num_cell'], {}), '(params.num_cell)\n', (316, 333), True, 'import numpy as np\n')] |
import math
from typing import Any, Callable, Dict, Iterator, List
import numpy as np
from toolz import itertoolz
def get_cosine_learning_rates(lr_min: float, lr_max: float, f: float, N: int):
"""Decay the learning rate based on a cosine schedule of frequency `f`.
Returns a list of `N` learning rate values i... | [
"math.cos",
"numpy.random.permutation"
] | [((2382, 2406), 'numpy.random.permutation', 'np.random.permutation', (['n'], {}), '(n)\n', (2403, 2406), True, 'import numpy as np\n'), ((452, 480), 'math.cos', 'math.cos', (['(2 * math.pi * freq)'], {}), '(2 * math.pi * freq)\n', (460, 480), False, 'import math\n')] |
# -*- coding: utf-8 -*-
"""
Functions for estimating electricity prices, eeg levies, remunerations and other components, based on customer type and annual demand
@author: Abuzar and Shakhawat
"""
from typing import ValuesView
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import int... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"scipy.interpolate.interp1d",
"numpy.append",
"matplotlib.pyplot.figure",
"pandas.read_excel",
"pandas.DataFrame",
"matplotlib.pyplot.title",
"pandas.to_datetime"
] | [((2519, 2646), 'pandas.read_excel', 'pd.read_excel', (['"""Energiepreisentwicklung.xlsx"""'], {'sheet_name': '"""5.8.3 Strom - € - Industrie"""', 'skiprows': '(5)', 'nrows': '(26)', 'index_col': '(0)'}), "('Energiepreisentwicklung.xlsx', sheet_name=\n '5.8.3 Strom - € - Industrie', skiprows=5, nrows=26, index_col=0... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn import metrics
import tensorflow as tf
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Conv2D
from keras.laye... | [
"keras.optimizers.Adam",
"keras.layers.Conv2D",
"keras.backend.tensorflow_backend.set_session",
"keras.layers.Flatten",
"keras.datasets.mnist.load_data",
"keras.layers.MaxPooling2D",
"sklearn.metrics.classification_report",
"tensorflow.Session",
"keras.layers.Input",
"keras.utils.np_utils.to_categ... | [((637, 661), 'keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (642, 661), False, 'from keras.layers import Input\n'), ((1073, 1088), 'keras.models.Model', 'Model', (['__x', '__y'], {}), '(__x, __y)\n', (1078, 1088), False, 'from keras.models import Model\n'), ((1237, 1262), 'tens... |
# straight from 08-Designing-Kalman-Filters
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from kf_book.book_plots import plot_measurements, plot_filter
from filterpy.stats import plot_covariance_ellipse
from filterpy.kalman import KalmanFilter
from scipy.linalg import block_diag
from... | [
"kf_book.book_plots.plot_measurements",
"numpy.eye",
"kf_book.book_plots.plot_filter",
"matplotlib.pyplot.clf",
"filterpy.kalman.KalmanFilter",
"book_format.set_style",
"filterpy.stats.plot_covariance_ellipse",
"numpy.array",
"filterpy.common.Q_discrete_white_noise",
"scipy.linalg.block_diag",
"... | [((386, 409), 'book_format.set_style', 'book_format.set_style', ([], {}), '()\n', (407, 409), False, 'import book_format\n'), ((1933, 1942), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1940, 1942), True, 'import matplotlib.pyplot as plt\n'), ((1943, 1974), 'kf_book.book_plots.plot_filter', 'plot_filter', (['... |
###############################################################################
# IMPORT STATEMENTS ###########################################################
###############################################################################
import numpy as np
from tudatpy.kernel import constants
from tudatpy.kernel.inte... | [
"tudatpy.kernel.simulation.propagation_setup.dependent_variable.latitude",
"tudatpy.kernel.simulation.propagation_setup.acceleration.spherical_harmonic_gravity",
"tudatpy.kernel.simulation.propagation_setup.acceleration.point_mass_gravity",
"tudatpy.kernel.simulation.propagation_setup.dependent_variable.total... | [((548, 587), 'tudatpy.kernel.interface.spice_interface.load_standard_kernels', 'spice_interface.load_standard_kernels', ([], {}), '()\n', (585, 587), False, 'from tudatpy.kernel.interface import spice_interface\n'), ((1359, 1488), 'tudatpy.kernel.simulation.environment_setup.get_default_body_settings', 'environment_se... |
import numpy as np
from tmtoolkit.topicmod.evaluate import metric_coherence_gensim
class GldaTrainer:
def __init__(self, model, data):
self.model = model.model
self.data = data
self.vocab = model.vocab
self.seed_topics = model.seed_topics
def train(self):
self.model.fi... | [
"numpy.argsort",
"numpy.mean",
"numpy.array"
] | [((848, 866), 'numpy.mean', 'np.mean', (['score_lst'], {}), '(score_lst)\n', (855, 866), True, 'import numpy as np\n'), ((600, 632), 'numpy.array', 'np.array', (['self.model.topic_word_'], {}), '(self.model.topic_word_)\n', (608, 632), True, 'import numpy as np\n'), ((682, 696), 'numpy.array', 'np.array', (['data'], {}... |
from ctapipe.image.muon import muon_ring_finder
import numpy as np
import astropy.units as u
from ctapipe.instrument import CameraGeometry
from functools import partial
from ctapipe.image import toymodel, tailcuts_clean
def test_ChaudhuriKunduRingFitter_old():
fitter = muon_ring_finder.ChaudhuriKunduRingFitter(p... | [
"numpy.abs",
"numpy.sqrt",
"numpy.full_like",
"numpy.ones",
"ctapipe.instrument.CameraGeometry.from_name",
"numpy.power",
"ctapipe.image.muon.muon_ring_finder.ChaudhuriKunduRingFitter",
"numpy.linspace",
"numpy.zeros",
"numpy.empty",
"functools.partial",
"ctapipe.image.tailcuts_clean",
"nump... | [((277, 331), 'ctapipe.image.muon.muon_ring_finder.ChaudhuriKunduRingFitter', 'muon_ring_finder.ChaudhuriKunduRingFitter', ([], {'parent': 'None'}), '(parent=None)\n', (318, 331), False, 'from ctapipe.image.muon import muon_ring_finder\n'), ((346, 373), 'numpy.linspace', 'np.linspace', (['(-100)', '(100)', '(200)'], {}... |
import numpy as np
import random
def nuclear_norm_alpha_generation(num_models, **params):
return np.array(
[0]
+ [
2 ** x
for x in np.linspace(
start=params["options"][0],
stop=params["options"][1],
num=(num_models - 1),
... | [
"numpy.linspace",
"numpy.arange"
] | [((177, 268), 'numpy.linspace', 'np.linspace', ([], {'start': "params['options'][0]", 'stop': "params['options'][1]", 'num': '(num_models - 1)'}), "(start=params['options'][0], stop=params['options'][1], num=\n num_models - 1)\n", (188, 268), True, 'import numpy as np\n'), ((505, 574), 'numpy.arange', 'np.arange', (... |
# Copyright (c) 2020 <NAME> & <NAME>
# FEniCS Project
# SPDX-License-Identifier: MIT
import libtab
import numpy
import pytest
import sympy
from .test_lagrange import sympy_disc_lagrange
def sympy_nedelec(celltype, n):
x = sympy.Symbol("x")
y = sympy.Symbol("y")
z = sympy.Symbol("z")
from sympy impor... | [
"sympy.Symbol",
"libtab.create_lattice",
"numpy.allclose",
"libtab.geometry",
"sympy.Integer",
"libtab.index",
"sympy.Matrix",
"pytest.mark.parametrize",
"libtab.topology",
"sympy.diff",
"libtab.Nedelec",
"numpy.zeros_like"
] | [((8124, 8167), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""order"""', '[1, 2, 3]'], {}), "('order', [1, 2, 3])\n", (8147, 8167), False, 'import pytest\n'), ((8897, 8940), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""order"""', '[1, 2, 3]'], {}), "('order', [1, 2, 3])\n", (8920, 8940), Fa... |
# 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.loadtxt"
] | [((2722, 2791), 'numpy.loadtxt', 'np.loadtxt', (['myFile'], {'dtype': '"""float"""', 'delimiter': '""","""', 'ndmin': '(2)', 'skiprows': '(1)'}), "(myFile, dtype='float', delimiter=',', ndmin=2, skiprows=1)\n", (2732, 2791), True, 'import numpy as np\n')] |
import sys
if sys.version_info[0] == 2:
import Tkinter as tk
from tkFileDialog import askdirectory
else:
import tkinter as tk
from tkinter.filedialog import askdirectory
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from... | [
"tkinter.filedialog.askdirectory",
"matplotlib.__version__.split",
"numpy.log",
"tkinter.Button",
"numpy.array",
"tkinter.Label",
"tkinter.Frame",
"matplotlib.pyplot.margins",
"tkinter.Entry",
"numpy.isscalar",
"matplotlib.pyplot.plot",
"numpy.max",
"matplotlib.pyplot.close",
"numpy.min",
... | [((223, 246), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (237, 246), False, 'import matplotlib\n'), ((730, 744), 'tkinter.filedialog.askdirectory', 'askdirectory', ([], {}), '()\n', (742, 744), False, 'from tkinter.filedialog import askdirectory\n'), ((761, 801), 'os.path.join', 'os.path.... |
"""classicML的优化器."""
import os
from time import time
import numpy as np
from classicML import _cml_precision
if os.environ['CLASSICML_ENGINE'] == 'CC':
from classicML.backend.cc.activations import relu
from classicML.backend.cc.activations import sigmoid
from classicML.backend.cc.activations import softma... | [
"classicML.backend.python.activations.relu.diff",
"numpy.sqrt",
"classicML._cml_precision.float",
"classicML.backend.python.activations.relu",
"numpy.linalg.norm",
"classicML.backend.python.ops.clip_alpha",
"numpy.asarray",
"numpy.exp",
"numpy.matmul",
"classicML.backend.python._utils.ProgressBar"... | [((9553, 9569), 'numpy.matmul', 'np.matmul', (['da', 'w'], {}), '(da, w)\n', (9562, 9569), True, 'import numpy as np\n'), ((17995, 18023), 'numpy.matmul', 'np.matmul', (['x_hat', 'parameters'], {}), '(x_hat, parameters)\n', (18004, 18023), True, 'import numpy as np\n'), ((18041, 18055), 'classicML.backend.python.activa... |
"""Unit test for the :func:`esmvalcore.preprocessor._units` function"""
import unittest
import cf_units
import iris
import numpy as np
import tests
from esmvalcore.preprocessor._units import convert_units
class Test(tests.Test):
"""Test class for _units"""
def setUp(self):
"""Prepare tests"""
... | [
"iris.coords.DimCoord",
"cf_units.Unit",
"numpy.array",
"iris.coord_systems.GeogCS",
"esmvalcore.preprocessor._units.convert_units",
"unittest.main",
"iris.cube.Cube"
] | [((1804, 1819), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1817, 1819), False, 'import unittest\n'), ((336, 395), 'iris.coord_systems.GeogCS', 'iris.coord_systems.GeogCS', (['iris.fileformats.pp.EARTH_RADIUS'], {}), '(iris.fileformats.pp.EARTH_RADIUS)\n', (361, 395), False, 'import iris\n'), ((417, 451), 'num... |
#Python 3.4
#PySide 1.2.4
#PyOpenGL 3.1.0
import sys
import numpy as np
from ctypes import sizeof, c_float, c_void_p
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtOpenGL import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.shaders import comp... | [
"numpy.array",
"OpenGL.GL.shaders.compileShader",
"ctypes.c_void_p",
"ctypes.sizeof"
] | [((1772, 1787), 'ctypes.sizeof', 'sizeof', (['c_float'], {}), '(c_float)\n', (1778, 1787), False, 'from ctypes import sizeof, c_float, c_void_p\n'), ((2057, 2159), 'numpy.array', 'np.array', (['[-0.9, -0.9, 0.85, -0.9, -0.9, 0.85, 0.9, -0.85, 0.9, 0.9, -0.85, 0.9]'], {'dtype': '"""float32"""'}), "([-0.9, -0.9, 0.85, -0... |
import sys
sys.path.append("../")
from pathlib import Path
import numpy as np
import healpy as hp
import torch
import gpytorch
import pyro.distributions as dist
from scipy.stats import poisson
from scipy.optimize import minimize
import utils.create_mask as cm
from utils.psf_correction import PSFCorrection
from util... | [
"numpy.mean",
"models.psf.KingPSF",
"pathlib.Path",
"utils.create_mask.make_mask_total",
"torch.logspace",
"models.scd.dnds",
"torch.tensor",
"utils.utils.make_dirs",
"gpytorch.priors.NormalPrior",
"scipy.stats.poisson.logpmf",
"healpy.nside2npix",
"utils.psf_correction.PSFCorrection",
"nump... | [((12, 34), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (27, 34), False, 'import sys\n'), ((4388, 4413), 'healpy.nside2npix', 'hp.nside2npix', (['self.nside'], {}), '(self.nside)\n', (4401, 4413), True, 'import healpy as hp\n'), ((5041, 5067), 'utils.utils.make_dirs', 'make_dirs', (['[self.s... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import optimizee
import os
get_path = os.getcwd()
parent_directory = os.path.split(get_path)[0]
datasets = os.path.join(parent_directory, "datasets")
class MnistLinearModel(optimizee.Optimizee):
'''A MLP on data... | [
"tensorflow.equal",
"tensorflow.nn.elu",
"tensorflow.tanh",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.dropout",
"tensorflow.cast",
"tensorflow.GPUOptions",
"tensorflow.app.run",
"tensorflow.Graph",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflo... | [((141, 152), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (150, 152), False, 'import os\n'), ((210, 252), 'os.path.join', 'os.path.join', (['parent_directory', '"""datasets"""'], {}), "(parent_directory, 'datasets')\n", (222, 252), False, 'import os\n'), ((172, 195), 'os.path.split', 'os.path.split', (['get_path'], {})... |
import os
import dataset
import util.tree_model
import uic.view_dataset
import numpy as np
import dataset.budgetary_consistency
from core import Core
from dataset import Dataset, Analysis, ExportVariant, DatasetHeaderC
from dataset.budgetary_consistency import BudgetaryConsistency
from typing import Sequence, NamedTup... | [
"util.codec.numpyC",
"util.codec_progress.oneCP",
"dataset.load_raw_csv",
"dataset.Analysis",
"dataset.Dataset.__init__",
"PyQt5.QtWidgets.QDialog.__init__",
"numpy.dot",
"util.codec_progress.CodecProgress",
"os.path.basename",
"numpy.vstack",
"dataset.budgetary_consistency.BudgetaryConsistency"... | [((753, 771), 'util.codec.numpyC', 'numpyC', (['np.float32'], {}), '(np.float32)\n', (759, 771), False, 'from util.codec import FileOut, FileIn, namedtupleC, strC, numpyC, listC\n'), ((773, 791), 'util.codec.numpyC', 'numpyC', (['np.float32'], {}), '(np.float32)\n', (779, 791), False, 'from util.codec import FileOut, F... |
# Question: https://projecteuler.net/problem=301
import numpy as np
# According to this https://en.wikipedia.org/wiki/Nim, the next player loses when the XOR of 3 heaps is 0.
# When XOR(n, 2n, 3n) == 0? It occurs when n has consecutive 1's.
# Why?
# bit b1 b2 b3
# carry of n+2n x y z
# ... | [
"numpy.zeros"
] | [((1260, 1297), 'numpy.zeros', 'np.zeros', (['(N + 1, 2)'], {'dtype': 'np.uint32'}), '((N + 1, 2), dtype=np.uint32)\n', (1268, 1297), True, 'import numpy as np\n')] |
from numpy import array
NOMINAL_OCTAVE_CENTER_FREQUENCIES = array(
[
31.5,
63.0,
125.0,
250.0,
500.0,
1000.0,
2000.0,
4000.0,
8000.0,
16000.0,
]
)
NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES = array(
[
25.0,
31.5,
... | [
"numpy.array"
] | [((61, 147), 'numpy.array', 'array', (['[31.5, 63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]'], {}), '([31.5, 63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, \n 16000.0])\n', (66, 147), False, 'from numpy import array\n'), ((279, 523), 'numpy.array', 'array', (['[25.0, 31.5, 40.0, 50... |
import unittest
import warnings
import numpy as np
from girth.synthetic import create_synthetic_irt_dichotomous, create_synthetic_irt_polytomous
from girth import (rasch_jml, onepl_jml, twopl_jml, grm_jml, pcm_jml,
rasch_mml, onepl_mml, twopl_mml, twopl_mml_eap, grm_mml_eap, pcm_mml,
grm_mml, rasch_conditi... | [
"girth.standard_errors_bootstrap",
"numpy.random.default_rng",
"numpy.any",
"numpy.linspace",
"girth.synthetic.create_synthetic_irt_polytomous",
"unittest.main",
"unittest.skip",
"warnings.filterwarnings",
"girth.synthetic.create_synthetic_irt_dichotomous"
] | [((937, 970), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (960, 970), False, 'import warnings\n'), ((2760, 2790), 'unittest.skip', 'unittest.skip', ([], {'reason': '"""Github"""'}), "(reason='Github')\n", (2773, 2790), False, 'import unittest\n'), ((4105, 4135), 'unitte... |
"""
The :mod:`sklearn.utils` module includes various utilities.
"""
import numbers
import platform
import struct
import numpy as np
from scipy.sparse import issparse
import warnings
from .murmurhash import murmurhash3_32
from .validation import (as_float_array,
assert_all_finite,
... | [
"platform.python_implementation",
"struct.calcsize",
"numpy.ceil",
"numpy.asarray",
"scipy.sparse.issparse",
"numpy.max",
"numpy.issubdtype",
"numpy.zeros",
"numpy.isnan",
"warnings.warn",
"numpy.arange"
] | [((1403, 1435), 'platform.python_implementation', 'platform.python_implementation', ([], {}), '()\n', (1433, 1435), False, 'import platform\n'), ((2946, 2962), 'numpy.asarray', 'np.asarray', (['mask'], {}), '(mask)\n', (2956, 2962), True, 'import numpy as np\n'), ((2970, 3013), 'numpy.issubdtype', 'np.issubdtype', (['m... |
import numpy as np
import matplotlib.pyplot as pl
import torch
import torch.nn as nn
import torch.utils.data as data
from torch.autograd import Variable
import h5py
import shutil
from tqdm import tqdm
import matplotlib.animation as animation
from astropy.io import fits
import glob
import os
from skimage.feature import ... | [
"skimage.feature.register_translation",
"torch.cuda.is_available",
"astropy.io.fits.open",
"numpy.arange",
"numpy.flip",
"numpy.max",
"matplotlib.pyplot.close",
"numpy.min",
"numpy.meshgrid",
"glob.glob",
"numpy.std",
"matplotlib.pyplot.show",
"torch.device",
"numpy.roll",
"matplotlib.an... | [((458, 483), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (481, 483), False, 'import torch\n'), ((506, 550), 'torch.device', 'torch.device', (["('cuda' if self.cuda else 'cpu')"], {}), "('cuda' if self.cuda else 'cpu')\n", (518, 550), False, 'import torch\n'), ((1354, 1369), 'matplotlib.pypl... |
# <NAME>, Imaging Biomarkers and Computer-Aided Diagnosis Laboratory,
# National Institutes of Health Clinical Center, July 2019
"""Load and pre-process CT images in DeepLesion"""
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.morphology import binary_fill_holes, binary_openi... | [
"cv2.merge",
"numpy.ceil",
"numpy.ones",
"numpy.floor",
"os.path.join",
"numpy.max",
"numpy.sign",
"numpy.nonzero",
"cv2.resize"
] | [((4304, 4318), 'cv2.merge', 'cv2.merge', (['ims'], {}), '(ims)\n', (4313, 4318), False, 'import cv2\n'), ((6409, 6425), 'numpy.nonzero', 'np.nonzero', (['mask'], {}), '(mask)\n', (6419, 6425), True, 'import numpy as np\n'), ((1371, 1387), 'numpy.max', 'np.max', (['im_shape'], {}), '(im_shape)\n', (1377, 1387), True, '... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Chesapeake Bay High-Resolution Land Cover Project datasets."""
import abc
import os
import sys
from typing import Any, Callable, Dict, List, Optional, Sequence
import fiona
import numpy as np
import pyproj
import rasteri... | [
"os.path.join",
"torch.from_numpy",
"pyproj.CRS",
"rasterio.crs.CRS.from_epsg",
"numpy.concatenate",
"rasterio.mask.mask"
] | [((7954, 7994), 'os.path.join', 'os.path.join', (['"""DC_11001"""', '"""DC_11001.img"""'], {}), "('DC_11001', 'DC_11001.img')\n", (7966, 7994), False, 'import os\n'), ((11184, 11203), 'rasterio.crs.CRS.from_epsg', 'CRS.from_epsg', (['(3857)'], {}), '(3857)\n', (11197, 11203), False, 'from rasterio.crs import CRS\n'), (... |
""" Unit test file. """
import unittest
import numpy as np
from ..CellVar import CellVar as c
# pylint: disable=protected-access
class TestModel(unittest.TestCase):
"""
Unit test class for the cell class.
"""
def test_cellVar(self):
"""
Make sure cell state assignment is correct.
... | [
"numpy.array"
] | [((704, 738), 'numpy.array', 'np.array', (['[[1.0, 0.0], [0.0, 1.0]]'], {}), '([[1.0, 0.0], [0.0, 1.0]])\n', (712, 738), True, 'import numpy as np\n'), ((2027, 2061), 'numpy.array', 'np.array', (['[[1.0, 0.0], [0.0, 1.0]]'], {}), '([[1.0, 0.0], [0.0, 1.0]])\n', (2035, 2061), True, 'import numpy as np\n'), ((2457, 2491)... |
# %%
# from ._preprocessors import CensorData, Arcsinh, ReduceLocal
# from ..utils.general import make_iterable, _check_is_fitted, is_fitted
import pandas as pd
import numpy as np
import warnings
from skimage.measure import regionprops, regionprops_table
# from sklearn.preprocessing import StandardScaler
# %%
def e... | [
"skimage.measure.regionprops_table",
"pandas.DataFrame.from_dict",
"pandas.DataFrame",
"numpy.all",
"pandas.concat"
] | [((791, 848), 'skimage.measure.regionprops_table', 'regionprops_table', (['mask'], {'properties': "['label', 'centroid']"}), "(mask, properties=['label', 'centroid'])\n", (808, 848), False, 'from skimage.measure import regionprops, regionprops_table\n'), ((861, 890), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dic... |
import os,sys,time
import numpy as np
import copy
import math
import torch
import torch.nn.functional as F
from .utils import BayesianSGD
class Appr(object):
def __init__(self,model,args,lr_min=1e-6,lr_factor=3,lr_patience=5,clipgrad=1000):
self.model=model
self.device = args.device
self.... | [
"torch.mul",
"torch.as_tensor",
"torch.LongTensor",
"torch.stack",
"torch.exp",
"math.isnan",
"copy.deepcopy",
"torch.no_grad",
"time.time",
"numpy.random.shuffle"
] | [((6015, 6035), 'numpy.random.shuffle', 'np.random.shuffle', (['r'], {}), '(r)\n', (6032, 6035), True, 'import numpy as np\n'), ((6897, 6954), 'torch.as_tensor', 'torch.as_tensor', (['r'], {'device': 'self.device', 'dtype': 'torch.int64'}), '(r, device=self.device, dtype=torch.int64)\n', (6912, 6954), False, 'import to... |
from cgol import CGOL
import numpy as np
import time
print("Welcome to <NAME>'s solution for the Python Challenge of JDERobot for GSoC-2019!")
t = int(input("Please enter the time step value in ms (int): "))
t = np.clip(t, 50, 1000)
max_iterations = int(input("Please enter the maximum number of iterations (int): "))
... | [
"numpy.clip",
"cgol.CGOL",
"time.sleep"
] | [((214, 234), 'numpy.clip', 'np.clip', (['t', '(50)', '(1000)'], {}), '(t, 50, 1000)\n', (221, 234), True, 'import numpy as np\n'), ((337, 370), 'numpy.clip', 'np.clip', (['max_iterations', '(10)', '(1000)'], {}), '(max_iterations, 10, 1000)\n', (344, 370), True, 'import numpy as np\n'), ((376, 382), 'cgol.CGOL', 'CGOL... |
from shapey.visualization.histogram import HistogramPlot
import argparse
import numpy as np
import pandas as pd
import os
PROJECT_DIR = os.path.join(os.path.dirname(__file__), '..')
DATA_DIR = os.path.join(PROJECT_DIR, 'data')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='passes data di... | [
"shapey.visualization.histogram.HistogramPlot",
"os.makedirs",
"argparse.ArgumentParser",
"os.path.join",
"os.path.dirname",
"numpy.array",
"pandas.HDFStore"
] | [((194, 227), 'os.path.join', 'os.path.join', (['PROJECT_DIR', '"""data"""'], {}), "(PROJECT_DIR, 'data')\n", (206, 227), False, 'import os\n'), ((150, 175), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (165, 175), False, 'import os\n'), ((269, 355), 'argparse.ArgumentParser', 'argparse.Arg... |
# -*- coding: iso-8859-15 -*-
#
# profiler.py
#
# Copyright (C) 2016 <NAME>, Universidad de Granada
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... | [
"numpy.copy",
"numpy.mean",
"numpy.polyfit",
"numpy.append",
"numpy.array",
"numpy.empty",
"numpy.linalg.lstsq",
"numpy.arange"
] | [((4915, 4946), 'numpy.empty', 'np.empty', (['(pf_data.shape[0], 6)'], {}), '((pf_data.shape[0], 6))\n', (4923, 4946), True, 'import numpy as np\n'), ((5000, 5038), 'numpy.append', 'np.append', (['pf_data', 'aux_values'], {'axis': '(1)'}), '(pf_data, aux_values, axis=1)\n', (5009, 5038), True, 'import numpy as np\n'), ... |
"""Helper file for computing various statistics over our data such as mention
frequency, mention text frequency in the data (even if not labeled as an
anchor), ...
etc.
"""
import argparse
import logging
import multiprocessing
import os
import time
from collections import Counter
import marisa_trie
import nltk
impor... | [
"logging.basicConfig",
"numpy.ceil",
"argparse.ArgumentParser",
"tqdm.tqdm",
"os.path.join",
"multiprocessing.cpu_count",
"collections.Counter",
"multiprocessing.Pool",
"bootleg.utils.utils.ensure_dir",
"time.time",
"logging.info",
"logging.error"
] | [((509, 582), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(message)s"""'}), "(level=logging.INFO, format='%(asctime)s %(message)s')\n", (528, 582), False, 'import logging\n'), ((616, 641), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n',... |
import unittest
import numpy as np
from pax.datastructure import Event, Pulse
from pax import core
class TestZLE(unittest.TestCase):
def setUp(self):
self.pax = core.Processor(config_names='XENON100',
just_testing=True,
config_dict={
... | [
"unittest.main",
"numpy.array",
"pax.datastructure.Pulse",
"pax.core.Processor"
] | [((2725, 2740), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2738, 2740), False, 'import unittest\n'), ((178, 485), 'pax.core.Processor', 'core.Processor', ([], {'config_names': '"""XENON100"""', 'just_testing': '(True)', 'config_dict': "{'pax': {'plugin_group_names': ['test'], 'test': 'ZLE.SoftwareZLE'},\n ... |
"""
Variety of filters to detect areas inside the images.
Signal rich areas should have a large density, while the areas dominated by noise are
low in density.
"""
import cv2
import numpy as np
import scipy as sp
import scipy.ndimage
def keypoint_density(image,convolve_size,n_pix=10,hess=1600):
detector = cv2.xf... | [
"numpy.where",
"cv2.xfeatures2d.SURF_create",
"numpy.argmax",
"scipy.ndimage.filters.minimum_filter",
"numpy.array",
"numpy.zeros",
"scipy.ndimage.filters.maximum_filter",
"numpy.argmin",
"cv2.GaussianBlur",
"cv2.blur"
] | [((314, 364), 'cv2.xfeatures2d.SURF_create', 'cv2.xfeatures2d.SURF_create', ([], {'hessianThreshold': 'hess'}), '(hessianThreshold=hess)\n', (341, 364), False, 'import cv2\n'), ((439, 468), 'numpy.array', 'np.array', (['[i.pt for i in kps]'], {}), '([i.pt for i in kps])\n', (447, 468), True, 'import numpy as np\n'), ((... |
# Author: <NAME>
import json
import pandas as pd
from rnn.biLSTM_inference import biLSTM_inference
from torch import from_numpy
from numpy import load, copy
from flask import Flask, jsonify, request
from flask_cors import CORS
from rnn.parameter import FEATURES
app = Flask(__name__)
CORS(app)
time = '20200115-194901'... | [
"numpy.copy",
"rnn.biLSTM_inference.biLSTM_inference",
"flask_cors.CORS",
"flask.Flask",
"torch.from_numpy",
"json.load",
"flask.request.get_json",
"pandas.DataFrame",
"numpy.load",
"flask.jsonify"
] | [((268, 283), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (273, 283), False, 'from flask import Flask, jsonify, request\n'), ((284, 293), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (288, 293), False, 'from flask_cors import CORS\n'), ((396, 444), 'numpy.load', 'load', (["(filepath + 'unique_da... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... | [
"numpy.random.uniform"
] | [((2748, 2813), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(self.num_embeddings, self.embedding_dim)'}), '(size=(self.num_embeddings, self.embedding_dim))\n', (2765, 2813), True, 'import numpy as np\n')] |
# Copyright (c) 2020, NVIDIA CORPORATION.
"""
Tests for Streamz Dataframes (SDFs) built on top of cuDF DataFrames.
*** Borrowed from streamz.dataframe.tests | License at thirdparty/LICENSE ***
"""
from __future__ import division, print_function
import json
import operator
import numpy as np
import pandas as pd
impor... | [
"numpy.arange",
"pytest.mark.xfail",
"dask.dataframe.utils.assert_eq",
"pandas.Timedelta",
"json.dumps",
"pytest.param",
"streamz.dataframe.DataFrames",
"pytest.mark.parametrize",
"distributed.Client",
"pytest.importorskip",
"pytest.raises",
"streamz.dataframe.DataFrame",
"pytest.fixture",
... | [((548, 575), 'pytest.importorskip', 'pytest.importorskip', (['"""cudf"""'], {}), "('cudf')\n", (567, 575), False, 'import pytest\n'), ((579, 609), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (593, 609), False, 'import pytest\n'), ((750, 789), 'pytest.fixture', 'pytest.fix... |
import os
import numpy as np
import cv2
import albumentations
from PIL import Image
from torch.utils.data import Dataset
class SegmentationBase(Dataset):
def __init__(self,
data_csv, data_root, segmentation_root,
size=None, random_crop=False, interpolation="bicubic",
... | [
"numpy.eye",
"PIL.Image.open",
"os.path.join",
"albumentations.RandomCrop",
"numpy.array",
"albumentations.CenterCrop",
"albumentations.SmallestMaxSize"
] | [((2429, 2462), 'PIL.Image.open', 'Image.open', (["example['file_path_']"], {}), "(example['file_path_'])\n", (2439, 2462), False, 'from PIL import Image\n'), ((2708, 2749), 'PIL.Image.open', 'Image.open', (["example['segmentation_path_']"], {}), "(example['segmentation_path_'])\n", (2718, 2749), False, 'from PIL impor... |
# Copyright 2017 Google 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 agreed to in writing,... | [
"numpy.eye",
"math.ceil",
"numpy.sqrt",
"copy.deepcopy",
"numpy.random.choice",
"numpy.diag_indices",
"numpy.argmax",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"sklearn.metrics.pairwise.pairwise_kernels",
"numpy.outer",
"numpy.random.seed",
"numpy.min",
"copy.copy",
"sklearn.metrics.acc... | [((2421, 2454), 'numpy.random.seed', 'np.random.seed', (['self.random_state'], {}), '(self.random_state)\n', (2435, 2454), True, 'import numpy as np\n'), ((2643, 2728), 'sklearn.metrics.pairwise.pairwise_kernels', 'metrics.pairwise.pairwise_kernels', (['X_train'], {'metric': 'self.kernel', 'gamma': 'self.gamma'}), '(X_... |
###########################################
# Model for generating samples from model
#
###########################################
import torch
import torch.nn as nn
from torchtext.data import Iterator as BatchIter
import argparse
import numpy as np
import math
import time
from torch.autograd import Variable
import t... | [
"torch.manual_seed",
"data_utils.SentenceDataset",
"argparse.ArgumentParser",
"torch.LongTensor",
"torch.load",
"random.seed",
"data_utils.NarrativeClozeDataset",
"torch.exp",
"data_utils.load_vocab",
"torch.cuda.is_available",
"numpy.random.randint",
"numpy.random.seed",
"numpy.argmin",
"... | [((1155, 1180), 'data_utils.load_vocab', 'du.load_vocab', (['args.vocab'], {}), '(args.vocab)\n', (1168, 1180), True, 'import data_utils as du\n'), ((11363, 11407), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""DAVAE"""'}), "(description='DAVAE')\n", (11386, 11407), False, 'import argpa... |
import os
import numpy
from chainer_chemistry.dataset.preprocessors import preprocess_method_dict
from chainer_chemistry import datasets as D
from chainer_chemistry.datasets.numpy_tuple_dataset import NumpyTupleDataset
from rdkit import Chem
from tqdm import tqdm
import utils
class _CacheNamePolicy(object):
tr... | [
"os.path.exists",
"utils.load_npz",
"os.makedirs",
"tqdm.tqdm",
"os.path.join",
"utils.save_npz",
"rdkit.Chem.MolFromSmiles",
"chainer_chemistry.datasets.get_tox21",
"numpy.array",
"numpy.sum",
"os.path.isdir",
"rdkit.Chem.MolFromSmarts",
"chainer_chemistry.datasets.numpy_tuple_dataset.Numpy... | [((2215, 2247), 'os.path.exists', 'os.path.exists', (['policy.cache_dir'], {}), '(policy.cache_dir)\n', (2229, 2247), False, 'import os\n'), ((957, 1007), 'os.path.join', 'os.path.join', (['self.cache_dir', 'self.train_file_name'], {}), '(self.cache_dir, self.train_file_name)\n', (969, 1007), False, 'import os\n'), ((1... |
# 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... | [
"tensorflow.python.eager.graph_only_ops.graph_zeros_like",
"numpy.square",
"numpy.array",
"numpy.zeros",
"tensorflow.python.eager.graph_only_ops.graph_placeholder",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.platform.test.main"
] | [((1774, 1785), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (1783, 1785), False, 'from tensorflow.python.platform import test\n'), ((1215, 1263), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {'dtype': 'np.int32'}), '([[1, 2, 3], [4, 5, 6]], dtype=np.int32)\n', (1223, 1263), True, '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_ntuple
----------------------------------
Tests for TOPAS ntuple reading.
"""
# system imports
import unittest
import os.path
# third-party imports
import numpy as np
from numpy.testing import assert_array_almost_equal
from numpy.lib.recfunctions import append_... | [
"numpy.copy",
"numpy.testing.assert_array_almost_equal",
"topas2numpy.read_ntuple",
"numpy.lib.recfunctions.append_fields",
"unittest.main"
] | [((1526, 1549), 'topas2numpy.read_ntuple', 'read_ntuple', (['ascii_path'], {}), '(ascii_path)\n', (1537, 1549), False, 'from topas2numpy import read_ntuple\n'), ((1692, 1716), 'topas2numpy.read_ntuple', 'read_ntuple', (['binary_path'], {}), '(binary_path)\n', (1703, 1716), False, 'from topas2numpy import read_ntuple\n'... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import Cython.Compiler.Options
Cython.Compiler.Options.annotate = True
import numpy as np
ext_modules = [
Extension(
"create_graph",
["create_graph.pyx"],
extra_compile_args=['-fope... | [
"Cython.Build.cythonize",
"numpy.get_include"
] | [((509, 546), 'Cython.Build.cythonize', 'cythonize', (['ext_modules'], {'annotate': '(True)'}), '(ext_modules, annotate=True)\n', (518, 546), False, 'from Cython.Build import cythonize\n'), ((410, 426), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (424, 426), True, 'import numpy as np\n')] |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Catalog utility functions / classes."""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from astropy.coordinates import Angle, SkyCoord
__all__ = [
'coordinate_iau_format',
'ra_iau_format',
... | [
"astropy.coordinates.Angle",
"astropy.coordinates.SkyCoord",
"numpy.invert"
] | [((8488, 8544), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['table[lon]', 'table[lat]'], {'unit': 'unit', 'frame': 'frame'}), '(table[lon], table[lat], unit=unit, frame=frame)\n', (8496, 8544), False, 'from astropy.coordinates import Angle, SkyCoord\n'), ((11995, 12034), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([... |
import matplotlib.pyplot as plt
from numpy import corrcoef, mean, zeros
from copy import deepcopy
from scipy import spatial
import Krippendorff
########################################################################################
class Rater:
def __init__(self, ID):
self.ID = ID
self.matrix = self.ReadF... | [
"scipy.spatial.distance.squareform",
"matplotlib.pyplot.title",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"numpy.corrcoef",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"numpy.zeros",
"copy.deepcopy",
"matplotlib.pyplot.ylim",
"matplotlib.pypl... | [((4341, 4367), 'numpy.zeros', 'zeros', (['[48, 48]'], {'dtype': 'int'}), '([48, 48], dtype=int)\n', (4346, 4367), False, 'from numpy import corrcoef, mean, zeros\n'), ((4392, 4420), 'numpy.zeros', 'zeros', (['[48, 48]'], {'dtype': 'float'}), '([48, 48], dtype=float)\n', (4397, 4420), False, 'from numpy import corrcoef... |
# -*- coding: utf-8 -*-
"""Preview
Code for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'
submit to Transactions on Medical Imaging, 2020.
First Version: Created on 2020-05-13 (@author: <NAME>)
"""
import os
import numpy as np
from Code.utils.dataloader_MulClsLungInf_UNet import LungDataset... | [
"numpy.unique",
"os.makedirs",
"torch.utils.data.DataLoader",
"torchvision.transforms.Normalize",
"shutil.rmtree",
"torchvision.transforms.ToTensor"
] | [((1185, 1253), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(0)'}), '(test_dataset, batch_size=1, shuffle=False, num_workers=0)\n', (1195, 1253), False, 'from torch.utils.data import DataLoader\n'), ((2398, 2422), 'shutil.rmtree', 'shutil.r... |
import wandb
import argparse
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import scipy.fft as fft
import seaborn as sns
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
sns.set()
from torch.utils.data import DataLoader, ... | [
"wandb.log",
"torch.nn.CrossEntropyLoss",
"numpy.hstack",
"sklearn.metrics.classification_report",
"wandb.init",
"tools.utils.drop_top_right",
"torch.cuda.is_available",
"seaborn.scatterplot",
"src.models.supervised_classifier.test",
"src.utils.data_preparation.SupervisedDataset",
"scipy.fft.fft... | [((268, 277), 'seaborn.set', 'sns.set', ([], {}), '()\n', (275, 277), True, 'import seaborn as sns\n'), ((558, 620), 'sys.path.append', 'sys.path.append', (['"""/home/evangelos/workspace/Channel_Charting/"""'], {}), "('/home/evangelos/workspace/Channel_Charting/')\n", (573, 620), False, 'import sys\n'), ((1085, 1110), ... |
# Malaya Natural Language Toolkit
#
# Copyright (C) 2019 Malaya Project
# Licensed under the MIT License
# Author: huseinzol05 <<EMAIL>>
# URL: <https://malaya.readthedocs.io/>
# For license information, see https://github.com/huseinzol05/Malaya/blob/master/LICENSE
import tensorflow.compat.v1 as tf
from malaya.functio... | [
"tarfile.open",
"malaya.text.bpe.xlnet_tokenization",
"malaya.function.html._attention",
"tensorflow.compat.v1.device",
"tensorflow.compat.v1.get_default_graph",
"malaya.function.check_file",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.placeholder",
"numpy.mean",
"ma... | [((953, 978), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (976, 978), False, 'import collections\n'), ((1177, 1217), 'tensorflow.compat.v1.train.list_variables', 'tf.train.list_variables', (['init_checkpoint'], {}), '(init_checkpoint)\n', (1200, 1217), True, 'import tensorflow.compat.v1 as t... |
#!/usr/bin/env python3
#####!/usr/local/bin/python3
import os
import pytz
import click
import random
import logging
import harness
import datetime
import pandas as pd
import numpy as np
import ml_metrics as metrics
from tqdm import tqdm
from uuid import uuid4
from dateutil import parser
from config import init_confi... | [
"ml_metrics.mapk",
"pyspark.sql.SQLContext",
"config.init_config",
"numpy.array",
"logging.info",
"logging.warn",
"click.option",
"click.group",
"pandas.DataFrame",
"pyspark.SparkContext",
"click.command",
"dateutil.parser.parse",
"numpy.random.choice",
"report.ExcelReport",
"uuid.uuid4"... | [((473, 565), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)s %(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)s %(message)s')\n", (492, 565), False, 'import logging\n'), ((652, 686), 'config.init_config', 'init_config', ... |
# logistic_regression_kfold.py
# python 2.7.14
# logistic-regression with ROC Curve
# MNIST classify between 6 and 8
# <NAME>
from sklearn.model_selection import KFold
import numpy as np
import matplotlib.pyplot as plt
def logistic_regression(x, y, steps, lr):
w = initialize_weights(x.shape[1])
costs = []
... | [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.log",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.dot",
"matplotlib.pyplot.title",
"sklearn.model_selection.KFold",
"matplotlib.pyplot.ylim",
... | [((1869, 1892), 'numpy.zeros', 'np.zeros', (['feature_shape'], {}), '(feature_shape)\n', (1877, 1892), True, 'import numpy as np\n'), ((2827, 2897), 'numpy.genfromtxt', 'np.genfromtxt', (['"""MNIST_CV.csv"""'], {'delimiter': '""","""', 'dtype': 'int', 'skip_header': '(1)'}), "('MNIST_CV.csv', delimiter=',', dtype=int, ... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import random
import unittest
import numpy as np
import torch
from ml.rl.test.constant_reward.env import Env
from ml.rl.thrift.core.ttypes import (
DiscreteActionModelParameters,
RainbowDQNParameters,... | [
"logging.getLogger",
"torch.manual_seed",
"ml.rl.test.constant_reward.env.Env",
"ml.rl.thrift.core.ttypes.TrainingParameters",
"torch.mean",
"random.seed",
"ml.rl.thrift.core.ttypes.RLParameters",
"numpy.random.seed",
"ml.rl.thrift.core.ttypes.RainbowDQNParameters",
"ml.rl.training.dqn_trainer.DQN... | [((426, 453), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (443, 453), False, 'import logging\n'), ((761, 778), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (775, 778), True, 'import numpy as np\n'), ((787, 801), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (7... |
"""DyNA-PPO environment module."""
import editdistance
import numpy as np
from tf_agents.environments import py_environment
from tf_agents.specs import array_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import nest_utils
import flexs
from flexs.utils import sequence_utils as s_utils
c... | [
"tf_agents.trajectories.time_step.termination",
"tf_agents.trajectories.time_step.transition",
"tf_agents.trajectories.time_step.restart",
"flexs.utils.sequence_utils.one_hot_to_string",
"tf_agents.trajectories.time_step.time_step_spec",
"flexs.utils.sequence_utils.string_to_one_hot",
"tf_agents.specs.a... | [((2321, 2362), 'tf_agents.trajectories.time_step.time_step_spec', 'ts.time_step_spec', (['self._observation_spec'], {}), '(self._observation_spec)\n', (2338, 2362), True, 'from tf_agents.trajectories import time_step as ts\n'), ((8403, 8426), 'tf_agents.trajectories.time_step.restart', 'ts.restart', (['self._state'], ... |
import numpy as np
import sys
import os
sys.path.append(os.path.expanduser('~/darts/cnn'))
#from train_class import Train
OPS = ['max_pool_3x3',
'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
'sep_conv_5x5',
'dil_conv_3x3',
'dil_conv_5x5'
]
NUM_VERTICES = 4
INP... | [
"numpy.random.choice",
"numpy.mean",
"numpy.zeros",
"os.path.expanduser"
] | [((57, 90), 'os.path.expanduser', 'os.path.expanduser', (['"""~/darts/cnn"""'], {}), "('~/darts/cnn')\n", (75, 90), False, 'import os\n'), ((5826, 5849), 'numpy.zeros', 'np.zeros', (['(4 * max_paths)'], {}), '(4 * max_paths)\n', (5834, 5849), True, 'import numpy as np\n'), ((631, 650), 'numpy.mean', 'np.mean', (['val_l... |
"""
A unit test for function_caller in function_caller and for synthetic
functions in utils.euclidean_synthetic_functions.py
-- <EMAIL>
"""
# pylint: disable=invalid-name
# pylint: disable=no-member
import numpy as np
# Local imports
from ..utils import euclidean_synthetic_functions as esf
from ..utils.base_tes... | [
"numpy.ones",
"numpy.hstack",
"numpy.random.random",
"numpy.array",
"numpy.linspace"
] | [((2508, 2572), 'numpy.random.random', 'np.random.random', (['(self.num_test_points, func_caller.domain.dim)'], {}), '((self.num_test_points, func_caller.domain.dim))\n', (2524, 2572), True, 'import numpy as np\n'), ((3526, 3590), 'numpy.random.random', 'np.random.random', (['(self.num_test_points, func_caller.domain.d... |
import os
import librosa
import numpy as np
from pathlib import Path
from tqdm import tqdm
from shutil import copyfile
np.random.seed(87)
def split_data(dir, name, type):
files = librosa.util.find_files(dir)
output_dir = 'audio_splited/'
os.makedirs(output_dir, exist_ok=True)
np.random.... | [
"os.makedirs",
"librosa.util.find_files",
"pathlib.Path",
"tqdm.tqdm",
"os.path.join",
"numpy.random.seed",
"numpy.random.shuffle"
] | [((127, 145), 'numpy.random.seed', 'np.random.seed', (['(87)'], {}), '(87)\n', (141, 145), True, 'import numpy as np\n'), ((197, 225), 'librosa.util.find_files', 'librosa.util.find_files', (['dir'], {}), '(dir)\n', (220, 225), False, 'import librosa\n'), ((266, 304), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exi... |
import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def cross_entropy_2d(predict, target):
"""
Args:
predict:(n, c, h, w)
target:(n, h, w)
"""
assert not target.requires_grad
assert predict.dim() == 4
assert target.dim() == 3
... | [
"torch.log2",
"numpy.log2",
"torch.zeros",
"torch.nn.functional.cross_entropy"
] | [((922, 973), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['predict', 'target'], {'size_average': '(True)'}), '(predict, target, size_average=True)\n', (937, 973), True, 'import torch.nn.functional as F\n'), ((745, 759), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (756, 759), False, 'import torch... |
from __future__ import division, print_function
from typing import List, Tuple, Callable
import numpy as np
import scipy
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, nb_features=2, max_iteration=10, margin=1e-4):
'''
Args :
nb_features : Number of feature... | [
"numpy.array",
"numpy.sign",
"numpy.linalg.norm"
] | [((1864, 1875), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1872, 1875), True, 'import numpy as np\n'), ((1994, 2007), 'numpy.sign', 'np.sign', (['pred'], {}), '(pred)\n', (2001, 2007), True, 'import numpy as np\n'), ((2177, 2194), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (2191, 2194), True, '... |
# -*- coding: UTF-8 -*-
"""
:Script: spaced.py
:Author: <EMAIL>
:Modified: 2017-04-11
:Purpose: tools for working with numpy arrays
:
:Original sources:
:----------------
:n_spaced : ...\arraytools\geom\n_spaced.py
: - n_spaced(L=0, B=0, R=10, T=10, min_space=1, num=10, verbose=True)
: Produce num po... | [
"numpy.prod",
"textwrap.dedent",
"numpy.random.random_sample",
"numpy.sqrt",
"arcpytools_pnt.array_struct",
"numpy.set_printoptions",
"arcpytools_pnt.tweet",
"numpy.argsort",
"numpy.einsum",
"numpy.vstack",
"arcpytools_pnt.array_fc",
"numpy.triu",
"numpy.ma.masked_print_option.set_display"
] | [((1203, 1311), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'edgeitems': '(10)', 'linewidth': '(80)', 'precision': '(2)', 'suppress': '(True)', 'threshold': '(100)', 'formatter': 'ft'}), '(edgeitems=10, linewidth=80, precision=2, suppress=True,\n threshold=100, formatter=ft)\n', (1222, 1311), True, 'impor... |
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy
import numpy as np
import os
dirs = ['/n/fs/visualai-scr/yutingy/boids_res_20_64_validate_switch_label/test',
'/n/fs/visualai-scr/yutingy/boids_res_20_64_validate_switch_label_aux/test'
]
errs = {}
fig = plt.figure()
fo... | [
"numpy.mean",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((305, 317), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (315, 317), True, 'from matplotlib import pyplot as plt\n'), ((600, 612), 'matplotlib.pyplot.legend', 'plt.legend', ([], {})... |
import numpy as np
from random import random
from numba import njit
import random as rand
import matplotlib.pyplot as plt
class RotSurCode():
nbr_eq_classes = 4
def __init__(self, size):
self.system_size = size
self.qubit_matrix = np.zeros((self.system_size, self.system_size), dtype=np.uint8)... | [
"numpy.copy",
"numpy.less",
"numpy.sqrt",
"numpy.random.rand",
"numpy.where",
"numpy.nditer",
"numba.njit",
"matplotlib.pyplot.axis",
"numpy.count_nonzero",
"numpy.zeros",
"numpy.linspace",
"numpy.concatenate",
"numpy.meshgrid",
"random.random",
"matplotlib.pyplot.subplot",
"numpy.aran... | [((7787, 7808), 'numba.njit', 'njit', (['"""(uint8[:,:],)"""'], {}), "('(uint8[:,:],)')\n", (7791, 7808), False, 'from numba import njit\n'), ((7887, 7928), 'numba.njit', 'njit', (['"""(uint8[:,:], int64, int64, int64)"""'], {}), "('(uint8[:,:], int64, int64, int64)')\n", (7891, 7928), False, 'from numba import njit\n'... |
# Copyright (c) 2021 PaddlePaddle 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 ap... | [
"unittest.main",
"numpy.full",
"functools.partial",
"numpy.ones"
] | [((10794, 10809), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10807, 10809), False, 'import unittest\n'), ((1721, 1736), 'numpy.full', 'np.full', (['(3)', '(0.9)'], {}), '(3, 0.9)\n', (1728, 1736), True, 'import numpy as np\n'), ((1840, 1855), 'numpy.full', 'np.full', (['(3)', '(0.9)'], {}), '(3, 0.9)\n', (184... |
from datetime import datetime
import tempfile
import os
import json
import shutil
import numpy as np
import ray
from typing import Type
from ray.tune.logger import UnifiedLogger
from config.custom_config import Config
from ray.rllib.agents.trainer import Trainer
def select_policy(agent_id):
if agent_id == "pla... | [
"os.path.exists",
"os.listdir",
"numpy.random.rand",
"os.makedirs",
"ray.tune.logger.UnifiedLogger",
"numpy.random.choice",
"os.path.join",
"json.load",
"tempfile.mkdtemp",
"shutil.rmtree",
"datetime.datetime.today",
"json.dump"
] | [((5597, 5617), 'os.listdir', 'os.listdir', (['ckpt_dir'], {}), '(ckpt_dir)\n', (5607, 5617), False, 'import os\n'), ((7058, 7078), 'os.listdir', 'os.listdir', (['ckpt_dir'], {}), '(ckpt_dir)\n', (7068, 7078), False, 'import os\n'), ((7666, 7686), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n',... |
#! usr/bin/env python
# coding:utf-8
#=====================================================
# Copyright (C) 2020 * Ltd. All rights reserved.
#
# Author : Chen_Sheng19
# Editor : VIM
# Create time : 2020-06-09
# File name :
# Description : product TFRecord data from image file
#
#==========================... | [
"tensorflow.local_variables_initializer",
"tensorflow.train.Int64List",
"os.sep.join",
"tensorflow.TFRecordReader",
"tensorflow.gfile.MakeDirs",
"tensorflow.cast",
"os.walk",
"tensorflow.gfile.Exists",
"tensorflow.train.Coordinator",
"tensorflow.Session",
"tensorflow.gfile.DeleteRecursively",
... | [((3223, 3255), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['save_image_path'], {}), '(save_image_path)\n', (3238, 3255), True, 'import tensorflow as tf\n'), ((3305, 3339), 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['save_image_path'], {}), '(save_image_path)\n', (3322, 3339), True, 'import tensorflow as t... |
import rls
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from algos.tf2algos.base.off_policy import make_off_policy_class
from rls.modules import DoubleQ
class TD3(make_off_policy_class(mode='share')):
'''
Twin Delayed Deep Deterministic Policy Gradient, https://arxiv.org/abs... | [
"rls.modules.DoubleQ",
"tensorflow.shape",
"tensorflow.GradientTape",
"tensorflow.nn.softmax",
"rls.actor_discrete",
"tensorflow.reduce_mean",
"tensorflow_probability.distributions.Categorical",
"rls.actor_dpg",
"rls.critic_q_one",
"tensorflow.square",
"tensorflow.maximum",
"tensorflow.device"... | [((200, 235), 'algos.tf2algos.base.off_policy.make_off_policy_class', 'make_off_policy_class', ([], {'mode': '"""share"""'}), "(mode='share')\n", (221, 235), False, 'from algos.tf2algos.base.off_policy import make_off_policy_class\n'), ((5226, 5269), 'tensorflow.function', 'tf.function', ([], {'experimental_relax_shape... |
import numpy as np
from preprocess.hierarchical import TreeNodes
from preprocess import utils
from evaluation.metrics import compute_level_loss
from algorithms.MinT import recon_base_forecast
from algorithms.ERM import unbiased_recon
from algorithms import LSTNet, Optim
import torch
import torch.nn as nn
import math
im... | [
"itertools.chain",
"algorithms.LSTNet.Model",
"torch.nn.L1Loss",
"torch.load",
"math.sqrt",
"preprocess.hierarchical.TreeNodes",
"torch.nn.MSELoss",
"numpy.dot",
"torch.save",
"time.time",
"preprocess.utils.Data_utility",
"torch.cat"
] | [((4901, 4986), 'preprocess.utils.Data_utility', 'utils.Data_utility', (['(0.6)', '(0.2)', 'cuda', 'h', '(24 * 7)', 'data', 'TRAINING_METHOD'], {'normalize': '(2)'}), '(0.6, 0.2, cuda, h, 24 * 7, data, TRAINING_METHOD,\n normalize=2)\n', (4919, 4986), False, 'from preprocess import utils\n'), ((4995, 5013), 'algorit... |
import cPickle as pickle
import numpy as np
import theano
_mean = 0.0035805809921434142
_std = 542.48824133746177
def gen_phone(mdl, phones, noise_level):
terr_monitor = mdl.monitor.channels['test_objective']
terr = min(terr_monitor.val_record)
X = theano.tensor.dmatrix('X')
P = theano.tensor.dmatrix... | [
"numpy.sqrt",
"theano.function",
"numpy.asarray",
"numpy.zeros",
"scipy.io.wavfile.write",
"theano.tensor.dmatrix",
"numpy.arange"
] | [((264, 290), 'theano.tensor.dmatrix', 'theano.tensor.dmatrix', (['"""X"""'], {}), "('X')\n", (285, 290), False, 'import theano\n'), ((299, 325), 'theano.tensor.dmatrix', 'theano.tensor.dmatrix', (['"""P"""'], {}), "('P')\n", (320, 325), False, 'import theano\n'), ((365, 391), 'theano.function', 'theano.function', (['[... |
'''
https://github.com/christiancosgrove/pytorch-spectral-normalization-gan
chainer: https://github.com/pfnet-research/sngan_projection
'''
# ResNet generator and discriminator
import torch
from torch import nn
import torch.nn.functional as F
# from spectral_normalization import SpectralNorm
import numpy as np
from ... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"numpy.sqrt",
"torch.nn.Tanh",
"torch.nn.init.xavier_uniform_",
"torch.nn.Conv2d",
"torch.nn.utils.spectral_norm",
"torch.nn.Upsample",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.randn"
] | [((535, 577), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_features'], {'affine': '(False)'}), '(num_features, affine=False)\n', (549, 577), False, 'from torch import nn\n'), ((606, 652), 'torch.nn.Linear', 'nn.Linear', (['dim_embed', 'num_features'], {'bias': '(False)'}), '(dim_embed, num_features, bias=False)\n',... |
import logging, numpy as np, rpxdock as rp
log = logging.getLogger(__name__)
def filter_redundancy(xforms, body, scores=None, categories=None, every_nth=10, **kw):
kw = rp.Bunch(kw)
if scores is None:
scores = np.repeat(0, len(xforms))
if len(scores) == 0: return []
if categories is None:
cat... | [
"logging.getLogger",
"numpy.sqrt",
"numpy.unique",
"numpy.argsort",
"numpy.concatenate",
"rpxdock.Bunch"
] | [((50, 77), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (67, 77), False, 'import logging, numpy as np, rpxdock as rp\n'), ((174, 186), 'rpxdock.Bunch', 'rp.Bunch', (['kw'], {}), '(kw)\n', (182, 186), True, 'import logging, numpy as np, rpxdock as rp\n'), ((368, 387), 'numpy.argsort', '... |
import scipy
import scipy.ndimage
import os
import numpy as np
import random
import sys
import tensorflow as tf
from PIL import Image
from make_gather_conv import make_gather_conv
BATCH_SIZE = 16
PIXEL_GEOM_P = 0.2
MAX_OFFSET = 40
IMAGE_SIZE = 256
GATHER_SIZE = 7
ADAM_learning_rate = 0.001
INPUT_CHANNELS = 6
OUT_... | [
"make_gather_conv.make_gather_conv",
"numpy.random.geometric",
"scipy.ndimage.imread",
"tensorflow.reduce_mean",
"os.listdir",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.concat",
"numpy.stack",
"numpy.concatenate",
"tensorflow.train.AdamOptimizer",
"sys.stdout.flush",
"tenso... | [((373, 400), 'scipy.ndimage.imread', 'scipy.ndimage.imread', (['fname'], {}), '(fname)\n', (393, 400), False, 'import scipy\n'), ((580, 617), 'PIL.Image.fromarray', 'Image.fromarray', (['img_data'], {'mode': '"""RGB"""'}), "(img_data, mode='RGB')\n", (595, 617), False, 'from PIL import Image\n'), ((681, 699), 'os.list... |
#%%
from datetime import datetime
import pandas as pd
import numpy as np
from pandas.core import frame
import geopandas as gpd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
import statsmodels.api as sm
# %%
def process_index_pivot(vi_link, v_index):
v_index = str(v_index)
... | [
"numpy.mean",
"sklearn.ensemble.RandomForestRegressor",
"pandas.read_csv",
"matplotlib.pyplot.xticks",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"pydot.graph_from_dot_file",
"matplotlib.pyplot.style.use",
"numpy.array",
"sklearn.tree.expo... | [((1042, 1087), 'pandas.read_csv', 'pd.read_csv', (['"""sa_yield.csv"""'], {'index_col': '"""year"""'}), "('sa_yield.csv', index_col='year')\n", (1053, 1087), True, 'import pandas as pd\n'), ((1145, 1194), 'pandas.read_csv', 'pd.read_csv', (['"""sa_crop_rain.csv"""'], {'index_col': '"""year"""'}), "('sa_crop_rain.csv',... |
import gmpy
import numpy as np
from tqdm import tqdm
from mdpgen.mdp import MDP, AbstractMDP, UniformAbstractMDP
from mdpgen.vi import vi
from mdpgen.markov import generate_markov_mdp_pair, generate_non_markov_mdp_pair, is_markov
from mdpgen.value_fn import compare_value_fns, partial_ordering, sorted_order, sort_valu... | [
"numpy.allclose",
"mdpgen.mdp.AbstractMDP",
"numpy.array",
"mdpgen.vi.vi",
"mdpgen.value_fn.graph_value_fns",
"mdpgen.mdp.MDP",
"mdpgen.value_fn.sorted_order"
] | [((391, 537), 'numpy.array', 'np.array', (['[[0, 0.5, 0.5, 0, 0, 0], [0, 0, 0, 0.5, 0.5, 0], [0, 0, 0, 0, 0.5, 0.5], [1,\n 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0]]'], {}), '([[0, 0.5, 0.5, 0, 0, 0], [0, 0, 0, 0.5, 0.5, 0], [0, 0, 0, 0, 0.5,\n 0.5], [1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 0, 0, ... |
import numpy as np
MERONYMY = [
"component",
"member",
"portion",
"stuff",
"feature",
"place",
"in",
"is-a",
"attribute",
"attached",
"belongs-to"
]
M_UNKNOWN = -1
M_COMPONENT = 0
M_MEMBER = 1
M_PORTION = 2
M_STUFF = 3
M_FEATURE = 4
M_PLACE = 5
M_IN = 6
M_IS_A = 7
M_ATTRIBU... | [
"numpy.full"
] | [((412, 436), 'numpy.full', 'np.full', (['(11, 11)', '(False)'], {}), '((11, 11), False)\n', (419, 436), True, 'import numpy as np\n')] |
#!/usr/bin/python
import sys, os
import numpy as np
currentpath = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
sys.path.append(currentpath)
from TBotTools import pid, geometry, pgt
from time import time
import pygame
import pygame.gfxdraw
import pygame.locals as pgl
from collections import deque
fro... | [
"pygame.init",
"pygame.quit",
"numpy.random.rand",
"pygame.gfxdraw.filled_polygon",
"numpy.array",
"pygame.display.quit",
"numpy.sin",
"pygame.time.set_timer",
"sys.path.append",
"numpy.mod",
"collections.deque",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.joystick.init",
"... | [((131, 159), 'sys.path.append', 'sys.path.append', (['currentpath'], {}), '(currentpath)\n', (146, 159), False, 'import sys, os\n'), ((355, 374), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (372, 374), False, 'import pygame\n'), ((1358, 1407), 'TBotTools.pid.pid', 'pid.pid', (['s_kp', 's_ki', 's_kd', '... |
from __future__ import print_function
import numpy as np
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid, Circle, VBox, HBox, Button, TapTool
from bokeh.document import Document
from bokeh.session import Session
from bokeh.browserlib import view
document = Document()
session = Session(... | [
"bokeh.models.Circle",
"bokeh.browserlib.view",
"bokeh.session.Session",
"bokeh.models.TapTool",
"bokeh.models.VBox",
"numpy.linspace",
"bokeh.models.Button",
"bokeh.models.Plot",
"bokeh.document.Document",
"bokeh.models.HBox"
] | [((291, 301), 'bokeh.document.Document', 'Document', ([], {}), '()\n', (299, 301), False, 'from bokeh.document import Document\n'), ((312, 321), 'bokeh.session.Session', 'Session', ([], {}), '()\n', (319, 321), False, 'from bokeh.session import Session\n'), ((403, 424), 'numpy.linspace', 'np.linspace', (['(-2)', '(2)',... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 20:03:11 2020
@author: charl
"""
import pandas as pd
import names
import numpy as np
# Reformat dataframe output from pd.read_csv() on an Metrica open tracking data CSV file
# into a more user/database friendly format
def Reformat(data): # Input - a dataframe, Outp... | [
"numpy.insert",
"numpy.sqrt",
"pandas.concat",
"pandas.DataFrame",
"pandas.melt",
"names.get_full_name"
] | [((768, 841), 'pandas.melt', 'pd.melt', (['data'], {'id_vars': "['Period', 'Frame', 'Time [s]']", 'var_name': '"""player"""'}), "(data, id_vars=['Period', 'Frame', 'Time [s]'], var_name='player')\n", (775, 841), True, 'import pandas as pd\n'), ((918, 1024), 'pandas.DataFrame', 'pd.DataFrame', (["{'x_loc': melted['value... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 2 08:30:48 2019
@author: <NAME>
"""
# =============================================================================
# 1. SET PARAMETERS
# =============================================================================
p_s = 600
###MODEL PATCH SIZE
m... | [
"staintools.BrightnessStandardizer",
"os.listdir",
"keras.models.load_model",
"numpy.float32",
"os.path.join",
"staintools.read_image",
"numpy.array",
"numpy.zeros",
"numpy.expand_dims",
"staintools.StainNormalizer",
"random.randint",
"keras.preprocessing.image.load_img"
] | [((1240, 1275), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (1252, 1275), False, 'import os\n'), ((1284, 1306), 'keras.models.load_model', 'load_model', (['path_model'], {}), '(path_model)\n', (1294, 1306), False, 'from keras.models import load_model\n'), ((1576, 1628... |
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
:Name:
takahe
:Authors:
<NAME> (<EMAIL>)
:Version:
0.4
:Date:
Mar. 2013
:Description:
takahe is a multi-sentence compression module. Given a set of redundant
sentences, a word-graph is constructed by iteratively adding sentences to
it. The ... | [
"networkx.drawing.nx_agraph.write_dot",
"networkx.DiGraph",
"numpy.argmax",
"bisect.insort"
] | [((5135, 5147), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (5145, 5147), True, 'import networkx as nx\n'), ((35025, 35077), 'networkx.drawing.nx_agraph.write_dot', 'nx.drawing.nx_agraph.write_dot', (['self.graph', 'dot_file'], {}), '(self.graph, dot_file)\n', (35055, 35077), True, 'import networkx as nx\n'), (... |
r"""
Use this script to visualize the output of a trained speech-model.
Usage: python visualize.py /path/to/audio /path/to/training/json.json \
/path/to/model
"""
from __future__ import absolute_import, division, print_function
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplo... | [
"utils.load_model",
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"numpy.arange",
"matplotlib.use",
"numpy.exp",
"utils.argmax_decode",
"model.compile_output_fn",
"numpy.vstack",
"data_generator.DataGenerator",
"matplotlib.pyplot.subplots",
"numpy.save"
] | [((275, 296), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (289, 296), False, 'import matplotlib\n'), ((912, 927), 'data_generator.DataGenerator', 'DataGenerator', ([], {}), '()\n', (925, 927), False, 'from data_generator import DataGenerator\n'), ((1056, 1080), 'model.compile_output_fn', 'comp... |
# code-checked
# server-checked
import os
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.autograd import Variable
from model_mcdropout import DepthCompletionNet
from datasets import DatasetVirtualKITTIVal
from criterion import MaskedL2Gauss, RMSE
import ... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"torch.sqrt",
"torch.pow",
"torch.exp",
"numpy.argsort",
"numpy.array",
"numpy.arange",
"os.path.exists",
"numpy.mean",
"torch.unsqueeze",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.ylim",
... | [((396, 417), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (410, 417), False, 'import matplotlib\n'), ((2407, 2466), 'datasets.DatasetVirtualKITTIVal', 'DatasetVirtualKITTIVal', ([], {'virtualkitti_path': 'virtualkitti_path'}), '(virtualkitti_path=virtualkitti_path)\n', (2429, 2466), False, 'fr... |
from OpenGL.GLUT import *
from OpenGL.GL import *
import numpy as np
MAX_STEP = 4
def Recursion(step, width, center):
if step == 1:
curvature = NewCurvature()
#DrawColorPolygon(width, center, curvature)
new_center = center + [0,width/2*curvature]
Recursion(step+1, width/3.0, new_... | [
"numpy.random.random",
"numpy.array"
] | [((2983, 3001), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2999, 3001), True, 'import numpy as np\n'), ((3169, 3193), 'numpy.random.random', 'np.random.random', ([], {'size': '(3)'}), '(size=3)\n', (3185, 3193), True, 'import numpy as np\n'), ((3100, 3120), 'numpy.array', 'np.array', (['[0.0, 0.0]'],... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# rng = pd.date_range('1/1/2012', periods=100, freq='S')
# ts = pd.Series(np.random.randint(0,500,len(rng)), index=rng)
# print ts
# print ts.resample('5Min')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2... | [
"numpy.random.randn",
"pandas.date_range",
"matplotlib.pyplot.show"
] | [((425, 435), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (433, 435), True, 'import matplotlib.pyplot as plt\n'), ((271, 292), 'numpy.random.randn', 'np.random.randn', (['(1000)'], {}), '(1000)\n', (286, 292), True, 'import numpy as np\n'), ((300, 339), 'pandas.date_range', 'pd.date_range', (['"""1/1/2000""... |
import os
import tensorflow as tf
from PIL import Image
import numpy as np
# 验证码存放路径
IMAGE_PATH = "./pictest/"
# 验证码图片宽度
IMAGE_WIDTH = 60
# 验证码图片高度
IMAGE_HEIGHT = 24
# 验证集,用于模型验证的验证码图片的文件名
VALIDATION_IMAGE_NAME = []
# 存放训练好的模型的路径
MODEL_SAVE_PATH = './models/'
CHAR_SET_LEN = 10
CAPTCHA_LEN = 4
def get_image_file_na... | [
"tensorflow.equal",
"numpy.array",
"tensorflow.cast",
"os.listdir",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.matmul",
"tensorflow.ConfigProto",
"tensorflow.nn.conv2d",
"tensorflow.Variable",
"numpy.argmax",
"tensorflow.train.get_checkpoint_state",
"tensorflow.reshape",
"... | [((396, 415), 'os.listdir', 'os.listdir', (['imgPath'], {}), '(imgPath)\n', (406, 415), False, 'import os\n'), ((835, 871), 'numpy.zeros', 'np.zeros', (['(CAPTCHA_LEN * CHAR_SET_LEN)'], {}), '(CAPTCHA_LEN * CHAR_SET_LEN)\n', (843, 871), True, 'import numpy as np\n'), ((1087, 1119), 'os.path.join', 'os.path.join', (['fi... |
import numpy as np
class CachedSplineDistance:
"""
spline: An instance of VectorCubicSpline
configs: [{min: , max: , resolution: }...] for two dimension of the space spline is in.
"""
def __init__(self, spline, configs):
self.spline = spline
self.configs = configs
self.dist... | [
"numpy.array",
"numpy.zeros"
] | [((606, 644), 'numpy.zeros', 'np.zeros', (['(x_num_states, y_num_states)'], {}), '((x_num_states, y_num_states))\n', (614, 644), True, 'import numpy as np\n'), ((668, 706), 'numpy.zeros', 'np.zeros', (['(x_num_states, y_num_states)'], {}), '((x_num_states, y_num_states))\n', (676, 706), True, 'import numpy as np\n'), (... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 8 14:27:24 2018
@author: Meagatron
"""
#Matrix Profile Version 1.4.0
#A Python implementation of the matrix profile algorithm described in <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2016): 'Matrix Profile I: All Pairs Similarity Jo... | [
"numpy.sqrt",
"multiprocessing.cpu_count",
"numpy.array",
"scipy.fftpack.fft",
"numpy.mean",
"numpy.multiply",
"numpy.where",
"scipy.fftpack.ifft",
"numpy.real",
"pandas.rolling_std",
"random.shuffle",
"numpy.ones",
"numpy.std",
"time.time",
"numpy.minimum",
"pandas.rolling_mean",
"n... | [((2394, 2404), 'scipy.fftpack.fft', 'fft', (['query'], {}), '(query)\n', (2397, 2404), False, 'from scipy.fftpack import fft, ifft\n'), ((2509, 2525), 'scipy.fftpack.fft', 'fft', (['time_series'], {}), '(time_series)\n', (2512, 2525), False, 'from scipy.fftpack import fft, ifft\n'), ((2606, 2637), 'numpy.multiply', 'n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.