code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 02:57:27 2020
@author: philippe
"""
from argparse import ArgumentParser
import numpy as np
import tensorflow as tf
from sys import argv
from config import Config
from model import Model
# preprocessed android distribution
args_type="java-small-model"... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"config.Config.get_default_config",
"sys.argv.append",
"model.Model",
"tensorflow.set_random_seed",
"config.Config.get_debug_config"
] | [((706, 727), 'sys.argv.append', 'argv.append', (['"""--data"""'], {}), "('--data')\n", (717, 727), False, 'from sys import argv\n'), ((729, 751), 'sys.argv.append', 'argv.append', (['args_data'], {}), '(args_data)\n', (740, 751), False, 'from sys import argv\n'), ((770, 791), 'sys.argv.append', 'argv.append', (['"""--... |
import numpy as np
import sklearn.mixture
import multiprocessing
class GMM():
def __init__(self, means, covariances, weights):
"""
Gaussian Mixture Model Distribution class for calculation of log likelihood and sampling.
Parameters
----------
means : 2-D array_like of shap... | [
"numpy.sqrt"
] | [((1115, 1141), 'numpy.sqrt', 'np.sqrt', (['(1.0 / covariances)'], {}), '(1.0 / covariances)\n', (1122, 1141), True, 'import numpy as np\n')] |
__author__ = 'mason'
from domain_orderFulfillment import *
from timer import DURATION
from state import state
import numpy as np
'''
This is a randomly generated problem
'''
def GetCostOfMove(id, r, loc1, loc2, dist):
return 1 + dist
def GetCostOfLookup(id, item):
return max(1, np.random.beta(2, 2))
def Ge... | [
"numpy.random.beta",
"numpy.random.normal"
] | [((291, 311), 'numpy.random.beta', 'np.random.beta', (['(2)', '(2)'], {}), '(2, 2)\n', (305, 311), True, 'import numpy as np\n'), ((375, 399), 'numpy.random.normal', 'np.random.normal', (['(5)', '(0.5)'], {}), '(5, 0.5)\n', (391, 399), True, 'import numpy as np\n'), ((453, 475), 'numpy.random.normal', 'np.random.normal... |
import logging
from copy import deepcopy
from time import time
from typing import Optional, Union
import numpy as np
from mne.epochs import BaseEpochs
from sklearn.base import clone
from sklearn.metrics import get_scorer
from sklearn.model_selection import (
LeaveOneGroupOut,
StratifiedKFold,
StratifiedShu... | [
"sklearn.model_selection._validation._score",
"numpy.full_like",
"copy.deepcopy",
"numpy.concatenate",
"sklearn.model_selection.cross_val_score",
"logging.getLogger",
"time.time",
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.get_scorer",
"numpy.any",
"sklearn.model_selection.Stratified... | [((531, 558), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (548, 558), False, 'import logging\n'), ((8108, 8141), 'sklearn.metrics.get_scorer', 'get_scorer', (['self.paradigm.scoring'], {}), '(self.paradigm.scoring)\n', (8118, 8141), False, 'from sklearn.metrics import get_scorer\n'), (... |
import numpy as np
def z_score(roa: float, capital_ratio: float, past_roas: np.ndarray) -> float:
r"""Z-score
A measure of bank insolvency risk, defined as:
$$
\text{Z-score} = \frac{\text{ROA}+\text{CAR}}{\sigma_{\text{ROA}}}
$$
where $\text{ROA}$ is the bank's ROA, $\text{CAR}$ is the ban... | [
"numpy.std"
] | [((2518, 2535), 'numpy.std', 'np.std', (['past_roas'], {}), '(past_roas)\n', (2524, 2535), True, 'import numpy as np\n')] |
import matplotlib
matplotlib.use('Agg')
from dataloaders.visual_genome import VGDataLoader, VG
import numpy as np
from functools import reduce
import torch
from sklearn.metrics import accuracy_score
from config import ModelConfig
from lib.pytorch_misc import optimistic_restore
from lib.evaluation.sg_eval import BasicSc... | [
"numpy.load",
"dataloaders.visual_genome.VG.splits",
"lib.pytorch_misc.load_reslayer4",
"collections.defaultdict",
"lib.fpn.box_intersections_cpu.bbox.bbox_overlaps",
"torch.load",
"os.path.exists",
"dill.load",
"lib.pytorch_misc.optimistic_restore",
"numpy.random.choice",
"lib.evaluation.sg_eva... | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((699, 805), 'numpy.load', 'np.load', (['"""/home/guoyuyu/guoyuyu/code/code_by_myself/scene_graph/dataset_analysis/size_index.npy"""'], {}), "(\n '/home/guoyuyu/guoyuyu/code/code_by_myself/scene... |
"""Return a scalar type which is common to the input arrays."""
import numpy
import numpoly
from .common import implements
@implements(numpy.common_type)
def common_type(*arrays):
"""
Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point... | [
"numpoly.aspolynomial",
"numpy.common_type"
] | [((1260, 1286), 'numpy.common_type', 'numpy.common_type', (['*arrays'], {}), '(*arrays)\n', (1277, 1286), False, 'import numpy\n'), ((1144, 1171), 'numpoly.aspolynomial', 'numpoly.aspolynomial', (['array'], {}), '(array)\n', (1164, 1171), False, 'import numpoly\n')] |
# Copyright 2019 Xilinx 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, ... | [
"cv2.imread",
"numpy.array",
"tensorflow.Graph",
"os.path.join",
"cv2.resize"
] | [((773, 825), 'numpy.array', 'np.array', (['[B_MEAN, G_MEAN, R_MEAN]'], {'dtype': 'np.float32'}), '([B_MEAN, G_MEAN, R_MEAN], dtype=np.float32)\n', (781, 825), True, 'import numpy as np\n'), ((834, 877), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0]'], {'dtype': 'np.float32'}), '([1.0, 1.0, 1.0], dtype=np.float32)\n', ... |
#!/usr/bin/env python
"order triplets by the sum of their two elements"
import numpy as np
from keras.layers import LSTM, Input
from keras.models import Model
from keras.utils.np_utils import to_categorical
from PointerLSTM import PointerLSTM
#
x_file = 'data/x_sums.csv'
y_file = 'data/y_sums.csv'
split_at = 9000... | [
"keras.layers.LSTM",
"numpy.asarray",
"keras.models.Model",
"PointerLSTM.PointerLSTM",
"keras.utils.np_utils.to_categorical",
"numpy.loadtxt",
"keras.layers.Input"
] | [((472, 516), 'numpy.loadtxt', 'np.loadtxt', (['x_file'], {'delimiter': '""","""', 'dtype': 'int'}), "(x_file, delimiter=',', dtype=int)\n", (482, 516), True, 'import numpy as np\n'), ((521, 565), 'numpy.loadtxt', 'np.loadtxt', (['y_file'], {'delimiter': '""","""', 'dtype': 'int'}), "(y_file, delimiter=',', dtype=int)\... |
""" Unit tests for skycomponents
"""
import logging
import unittest
import astropy.units as u
import numpy
from astropy.coordinates import SkyCoord
from data_models.polarisation import PolarisationFrame
from processing_components.image.operations import export_image_to_fits
from processing_components.imaging.base ... | [
"unittest.main",
"processing_components.simulation.testing_support.create_named_configuration",
"processing_components.image.operations.export_image_to_fits",
"numpy.abs",
"processing_components.simulation.testing_support.create_test_image",
"processing_components.imaging.base.predict_skycomponent_visibil... | [((709, 736), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (726, 736), False, 'import logging\n'), ((6247, 6262), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6260, 6262), False, 'import unittest\n'), ((884, 925), 'processing_components.simulation.testing_support.create_named_co... |
import random
from datetime import datetime
from multiprocessing import Pool
import numpy as np
from scipy.optimize import minimize
def worker_func(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
return (self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
... | [
"scipy.optimize.minimize",
"random.randint",
"numpy.zeros",
"numpy.array",
"multiprocessing.Pool",
"numpy.dot",
"datetime.datetime.now"
] | [((1492, 1504), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1500, 1504), True, 'import numpy as np\n'), ((2290, 2316), 'numpy.dot', 'np.dot', (['r', 'self.data[m][k]'], {}), '(r, self.data[m][k])\n', (2296, 2316), True, 'import numpy as np\n'), ((3264, 3281), 'multiprocessing.Pool', 'Pool', ([], {'processes': '... |
'''
Plot likelihood approximation along training
'''
# Modules
# =======================================================================================================================
import os
import sys
import shutil
import subprocess
import tqdm
import numpy as np
import pandas as pd
import torch
from torch.dist... | [
"numpy.random.seed",
"torch.cat",
"torch.mm",
"numpy.arange",
"pyro.clear_param_store",
"torch.no_grad",
"os.chdir",
"probcox.PCox",
"matplotlib.pyplot.close",
"torch.zeros",
"matplotlib.pyplot.subplots",
"torch.manual_seed",
"numpy.asarray",
"probcox.TVC",
"probcox.CoxPartialLikelihood"... | [((486, 519), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (509, 519), False, 'import warnings\n'), ((573, 593), 'numpy.random.seed', 'np.random.seed', (['(5256)'], {}), '(5256)\n', (587, 593), True, 'import numpy as np\n'), ((594, 617), 'torch.manual_seed', 'torch.manua... |
import os
from eulerangles import euler2mat
import numpy as np
import math
import cv2
import torch
import torch.nn.functional as F
from torchvision import transforms
import matplotlib.cm as cm
from google_drive_downloader import GoogleDriveDownloader
from affine_transform import affineTransform
# label vector
# label_... | [
"numpy.arctan2",
"eulerangles.euler2mat",
"matplotlib.cm.get_cmap",
"cv2.vconcat",
"numpy.argmax",
"numpy.ones",
"numpy.sin",
"cv2.rectangle",
"os.path.join",
"cv2.line",
"torch.nn.functional.grid_sample",
"cv2.cvtColor",
"torch.load",
"os.path.exists",
"numpy.logical_and.reduce",
"num... | [((1160, 1191), 'os.path.join', 'os.path.join', (['modeldir', 'exp_str'], {}), '(modeldir, exp_str)\n', (1172, 1191), False, 'import os\n'), ((1214, 1263), 'os.path.join', 'os.path.join', (['model_exp_dir', '"""checkpoint_best.pt"""'], {}), "(model_exp_dir, 'checkpoint_best.pt')\n", (1226, 1263), False, 'import os\n'),... |
import numpy as np
from .. import Lump, lump_tag
@lump_tag(3, 'LUMP_VERTICES')
class VertexLump(Lump):
def __init__(self, bsp, lump_id):
super().__init__(bsp, lump_id)
self.vertices = np.array([])
def parse(self):
reader = self.reader
self.vertices = np.frombuffer(reader.read... | [
"numpy.dtype",
"numpy.array"
] | [((507, 625), 'numpy.dtype', 'np.dtype', (["[('vpi', np.uint32, (1,)), ('vni', np.uint32, (1,)), ('uv', np.float32, (2,\n )), ('unk', np.int32, (1,))]"], {}), "([('vpi', np.uint32, (1,)), ('vni', np.uint32, (1,)), ('uv', np.\n float32, (2,)), ('unk', np.int32, (1,))])\n", (515, 625), True, 'import numpy as np\n')... |
import math
import random
import time
import numpy as np
import scipy
from numpy.random import RandomState
from scipy.spatial.distance import cdist, pdist, squareform
from scipy.stats import gamma, norm
SIGMAS_HSIC = [x for x in range(35000,85000,5000)]
def kernelMatrixGaussian(m, m2, sigma=None):
"""
Cal... | [
"numpy.trace",
"numpy.argmax",
"numpy.ones",
"numpy.exp",
"numpy.mat",
"numpy.atleast_2d",
"numpy.copy",
"numpy.std",
"numpy.transpose",
"numpy.identity",
"numpy.random.RandomState",
"scipy.spatial.distance.sqeuclidean",
"numpy.random.shuffle",
"numpy.diagonal",
"scipy.spatial.distance.c... | [((602, 629), 'scipy.spatial.distance.cdist', 'cdist', (['m', 'm2', '"""sqeuclidean"""'], {}), "(m, m2, 'sqeuclidean')\n", (607, 629), False, 'from scipy.spatial.distance import cdist, pdist, squareform\n'), ((860, 894), 'numpy.exp', 'np.exp', (['(gamma * pairwise_distances)'], {}), '(gamma * pairwise_distances)\n', (8... |
import re
import librosa
import numpy as np
import torch
from torch.nn import functional as F
def _tokenize_text(sentence):
w = re.findall(r"[\w']+", str(sentence))
return w
def create_audio_features(mel_spec, max_audio_STFT_nframes):
audio = np.zeros((mel_spec.shape[0], max_audio_STFT_nframes), dtype=... | [
"torch.ones",
"torch.stack",
"librosa.core.time_to_frames",
"numpy.ceil",
"numpy.floor",
"numpy.zeros",
"torch.cat",
"torch.max",
"torch.zeros",
"torch.nn.functional.normalize",
"torch.tensor",
"torch.from_numpy"
] | [((260, 331), 'numpy.zeros', 'np.zeros', (['(mel_spec.shape[0], max_audio_STFT_nframes)'], {'dtype': 'np.float32'}), '((mel_spec.shape[0], max_audio_STFT_nframes), dtype=np.float32)\n', (268, 331), True, 'import numpy as np\n'), ((349, 399), 'numpy.zeros', 'np.zeros', (['max_audio_STFT_nframes'], {'dtype': 'np.float32'... |
import numpy as np
from scipy import interpolate
from scipy import optimize
import warnings
def calculate_smax(spin_C=False):
r"""Returns maximal saturation factor.
Args:
spin_C (float): unpaired spin concentration in units of Molar
Returns:
smax (float): maximal saturation factor
.... | [
"numpy.polyfit",
"numpy.polyval",
"numpy.real",
"warnings.warn",
"numpy.diag",
"numpy.sqrt"
] | [((6212, 6255), 'numpy.sqrt', 'np.sqrt', (['(1.0j * (omega_e - omega_H) * tcorr)'], {}), '(1.0j * (omega_e - omega_H) * tcorr)\n', (6219, 6255), True, 'import numpy as np\n'), ((6265, 6308), 'numpy.sqrt', 'np.sqrt', (['(1.0j * (omega_e + omega_H) * tcorr)'], {}), '(1.0j * (omega_e + omega_H) * tcorr)\n', (6272, 6308), ... |
# Copyright (C) 2021 <NAME>, <NAME>
#
# SPDX-License-Identifier: MIT
"""Motors and a class bundling two motors together"""
from controller import Motor
import numpy as np
class IDPGate(Motor):
def __init__(self, name):
super().__init__(name)
def open(self):
"""Opens the robot gate"""
... | [
"numpy.array"
] | [((2536, 2584), 'numpy.array', 'np.array', (['[f_drive + r_drive, f_drive - r_drive]'], {}), '([f_drive + r_drive, f_drive - r_drive])\n', (2544, 2584), True, 'import numpy as np\n')] |
from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.pylab import *
import matplotlib.colors as colors
import pandas as pd
import math
import numpy as np
import geopandas as gp
__all__ = ['plot_network_admcolmap_betweenness',
'plot_socioeconomic_attribute',
'trun... | [
"matplotlib.pyplot.colorbar",
"numpy.percentile",
"matplotlib.pyplot.cm.ScalarMappable",
"numpy.arange",
"matplotlib.pyplot.gcf",
"numpy.linspace",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.ylabel",
"math.log",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlab... | [((689, 718), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 9)'}), '(figsize=(12, 9))\n', (701, 718), True, 'from matplotlib import pyplot as plt\n'), ((1874, 1909), 'matplotlib.pyplot.cm.ScalarMappable', 'plt.cm.ScalarMappable', ([], {'cmap': '"""Greys"""'}), "(cmap='Greys')\n", (1895, 1909), Tr... |
import numpy as np
from didyprog.reference.local import HardMaxOp, SparseMaxOp, SoftMaxOp
def make_data():
rng = np.random.RandomState(0)
return rng.randint(-10, 10, size=10)
def test_hardmax():
x = make_data()
op = HardMaxOp()
max_x, argmax_x = op.max(x)
assert np.all(x <= max_x)
asser... | [
"numpy.sum",
"didyprog.reference.local.HardMaxOp",
"didyprog.reference.local.SparseMaxOp",
"didyprog.reference.local.SoftMaxOp",
"numpy.random.RandomState",
"numpy.all"
] | [((120, 144), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (141, 144), True, 'import numpy as np\n'), ((237, 248), 'didyprog.reference.local.HardMaxOp', 'HardMaxOp', ([], {}), '()\n', (246, 248), False, 'from didyprog.reference.local import HardMaxOp, SparseMaxOp, SoftMaxOp\n'), ((292, 3... |
from collections import defaultdict
import numpy
try:
# try importing the C version and set docstring
from .hv import hypervolume as __hv
except ImportError:
# fallback on python version
from .pyhv import hypervolume as __hv
def argsortNondominated(losses, k, first_front_only=False):
"""Sort inp... | [
"numpy.argmax",
"collections.defaultdict",
"numpy.max",
"numpy.array",
"numpy.concatenate"
] | [((1185, 1202), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1196, 1202), False, 'from collections import defaultdict\n'), ((1379, 1395), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1390, 1395), False, 'from collections import defaultdict\n'), ((1419, 1436), 'collectio... |
import numpy as np
class NoControllerFound(Exception):
"""Raised when there is no common controller for the sampled systems"""
pass
class NumericalProblem(Exception):
pass
class LQRSyntheziser:
def __init__(self, uncertainStateSpaceModel, Q, R, settings):
self.ussm = uncertainStateSpaceMo... | [
"numpy.linalg.norm"
] | [((542, 581), 'numpy.linalg.norm', 'np.linalg.norm', (['Q'], {'ord': '(2)', 'keepdims': '(True)'}), '(Q, ord=2, keepdims=True)\n', (556, 581), True, 'import numpy as np\n'), ((599, 638), 'numpy.linalg.norm', 'np.linalg.norm', (['R'], {'ord': '(2)', 'keepdims': '(True)'}), '(R, ord=2, keepdims=True)\n', (613, 638), True... |
import random
import numpy as np
class MNIST_DS(object):
def __init__(self, train_dataset, test_dataset):
self.__train_labels_idx_map = {}
self.__test_labels_idx_map = {}
self.__train_data = train_dataset.data
self.__test_data = test_dataset.data
self.__train_labels = tra... | [
"numpy.where",
"numpy.unique"
] | [((488, 521), 'numpy.unique', 'np.unique', (['self.__train_labels_np'], {}), '(self.__train_labels_np)\n', (497, 521), True, 'import numpy as np\n'), ((618, 650), 'numpy.unique', 'np.unique', (['self.__test_labels_np'], {}), '(self.__test_labels_np)\n', (627, 650), True, 'import numpy as np\n'), ((811, 852), 'numpy.whe... |
import numpy as np
from os import path
try:
from mahotas.io import freeimage
except OSError:
import pytest
pytestmark = pytest.mark.skip
def test_freeimage(tmpdir):
img = np.arange(256).reshape((16,16)).astype(np.uint8)
fname = tmpdir.join('mahotas_test.png')
freeimage.imsave(fname, img)
... | [
"mahotas.io.freeimage.imsave",
"mahotas.io.freeimage.imreadfromblob",
"mahotas.io.freeimage.imsavetoblob",
"mahotas.io.freeimage.read_multipage",
"numpy.zeros",
"mahotas.io.freeimage.imread",
"os.path.dirname",
"mahotas.io.freeimage.write_multipage",
"numpy.arange",
"numpy.all"
] | [((288, 316), 'mahotas.io.freeimage.imsave', 'freeimage.imsave', (['fname', 'img'], {}), '(fname, img)\n', (304, 316), False, 'from mahotas.io import freeimage\n'), ((328, 351), 'mahotas.io.freeimage.imread', 'freeimage.imread', (['fname'], {}), '(fname)\n', (344, 351), False, 'from mahotas.io import freeimage\n'), ((3... |
# -------------------------------------------------------------------------------
# Licence:
# Copyright (c) 2012-2018 <NAME>
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF AN... | [
"scipy.stats.norm.cdf",
"numpy.sort",
"numpy.mean",
"numpy.std"
] | [((1261, 1281), 'numpy.sort', 'np.sort', (['self.values'], {}), '(self.values)\n', (1268, 1281), True, 'import numpy as np\n'), ((1356, 1394), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['self.values', 'mean', 'std'], {}), '(self.values, mean, std)\n', (1370, 1394), False, 'from scipy import stats\n'), ((1301, 1321), '... |
import copy
import gc
import os
import pickle
import re
import sys
import tempfile
import unittest
import numpy as np
from sklearn.exceptions import NotFittedError
try:
from deep_ner.elmo_ner import ELMo_NER
from deep_ner.utils import load_dataset
from deep_ner.quality import calculate_prediction_quality
... | [
"pickle.dump",
"os.remove",
"deep_ner.elmo_ner.ELMo_NER.check_Xy",
"gc.collect",
"os.path.isfile",
"pickle.load",
"os.path.join",
"deep_ner.elmo_ner.ELMo_NER.detect_token_labels",
"unittest.main",
"os.path.dirname",
"re.escape",
"deep_ner.elmo_ner.ELMo_NER.calculate_indices_of_named_entities",... | [((72267, 72293), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (72280, 72293), False, 'import unittest\n'), ((1090, 1143), 'deep_ner.elmo_ner.ELMo_NER', 'ELMo_NER', ([], {'elmo_hub_module_handle': 'self.ELMO_HUB_MODULE'}), '(elmo_hub_module_handle=self.ELMO_HUB_MODULE)\n', (1098, 114... |
from sys import stdin
from copy import copy, deepcopy
import time
import argparse
import numpy
def parseFileInput(in_file, cnf): # Parse
cnf.append(list())
for line in in_file:
tokens = line.split()
if len(tokens) > 0 and tokens[0] not in ("p", "c"):
for token in tokens:
... | [
"copy.deepcopy",
"argparse.ArgumentParser",
"copy.copy",
"time.time",
"numpy.arange"
] | [((1349, 1358), 'copy.copy', 'copy', (['cnf'], {}), '(cnf)\n', (1353, 1358), False, 'from copy import copy, deepcopy\n'), ((3357, 3370), 'copy.deepcopy', 'deepcopy', (['cnf'], {}), '(cnf)\n', (3365, 3370), False, 'from copy import copy, deepcopy\n'), ((4252, 4263), 'time.time', 'time.time', ([], {}), '()\n', (4261, 426... |
# -*- coding:UTF8 -*-
import numpy as np
import sys,os
import math
from tools.loadData import load_array
from tools import ulti
path = os.getcwd()
def Schmidt_procedure(mat, m, n):
# mat_B = mat.copy()
Q = np.zeros((m,n))
R = np.zeros((n,n))
for col in range(n):
curr_col = mat[:,col]
... | [
"os.getcwd",
"numpy.square",
"numpy.zeros",
"tools.loadData.load_array",
"tools.ulti.print_array",
"numpy.matmul",
"tools.ulti.rank_of_matrix",
"sys.exit"
] | [((137, 148), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (146, 148), False, 'import sys, os\n'), ((218, 234), 'numpy.zeros', 'np.zeros', (['(m, n)'], {}), '((m, n))\n', (226, 234), True, 'import numpy as np\n'), ((242, 258), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (250, 258), True, 'import numpy as ... |
import math
import numpy as np
from collections import defaultdict
from .common import beta_binomial_model, gamma_poission_model, requires_keys
@requires_keys('threads[].children')
def discussion_score(asset, k=1, theta=2):
"""
description:
en: Estimated number of comments this asset will get.
... | [
"collections.defaultdict",
"math.isnan",
"numpy.sum"
] | [((2347, 2364), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2358, 2364), False, 'from collections import defaultdict\n'), ((548, 557), 'numpy.sum', 'np.sum', (['X'], {}), '(X)\n', (554, 557), True, 'import numpy as np\n'), ((2466, 2482), 'math.isnan', 'math.isnan', (['p_id'], {}), '(p_id)\n',... |
import potential
import wavefunction
import numpy as np
import pytest
import random
def test_delta_potential():
x = np.linspace(-50, 50, 40000)
depths = np.linspace(0.1, 10, 10)
for d in depths:
v = potential.DeltaPotential1D(d)
assert(v.get_delta_depth() == d)
assert(v.get_number... | [
"numpy.meshgrid",
"wavefunction.correlation",
"random.randint",
"potential.QuadraticPotential1D",
"numpy.testing.assert_almost_equal",
"numpy.testing.assert_allclose",
"potential.UniformField1D",
"itertools.combinations",
"pytest.raises",
"numpy.sort",
"potential.DeltaPotential1D",
"numpy.lins... | [((122, 149), 'numpy.linspace', 'np.linspace', (['(-50)', '(50)', '(40000)'], {}), '(-50, 50, 40000)\n', (133, 149), True, 'import numpy as np\n'), ((163, 187), 'numpy.linspace', 'np.linspace', (['(0.1)', '(10)', '(10)'], {}), '(0.1, 10, 10)\n', (174, 187), True, 'import numpy as np\n'), ((809, 836), 'numpy.linspace', ... |
#!/usr/bin/env python
# coding: utf-8
# ### Define all functions
# In[1]:
import cv2
import csv
import numpy as np
import os
# In[2]:
def getCSVRows(dataPath, skipHeader=False):
"""
Returns the rows from a driving log with base directory `dataPath`.
If the file include headers, pass `skipHeader=True... | [
"matplotlib.pyplot.title",
"csv.reader",
"keras.layers.Cropping2D",
"sklearn.model_selection.train_test_split",
"keras.callbacks.LearningRateScheduler",
"cv2.cvtColor",
"keras.layers.Flatten",
"matplotlib.pyplot.show",
"keras.callbacks.ModelCheckpoint",
"keras.layers.Dropout",
"matplotlib.pyplot... | [((5196, 5236), 'sklearn.model_selection.train_test_split', 'train_test_split', (['samples'], {'test_size': '(0.2)'}), '(samples, test_size=0.2)\n', (5212, 5236), False, 'from sklearn.model_selection import train_test_split\n'), ((5946, 6073), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'che... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import scipy.integrate
import scipy.special
import collections
import fisx
import logging
from contextlib import contextmanager
from ..utils import instance
from ..utils import cache
from ..utils import listtools
from ..math import fit1d
from ..math.utils... | [
"numpy.triu",
"numpy.abs",
"numpy.empty",
"matplotlib.pyplot.figure",
"numpy.isclose",
"numpy.arange",
"numpy.exp",
"numpy.diag",
"pandas.DataFrame",
"numpy.full_like",
"matplotlib.pyplot.imshow",
"numpy.transpose",
"numpy.insert",
"numpy.cumsum",
"numpy.max",
"numpy.linspace",
"coll... | [((798, 825), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (815, 825), False, 'import logging\n'), ((6749, 6770), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (6768, 6770), False, 'import collections\n'), ((13637, 13663), 'numpy.empty', 'np.empty', (['(self.nlayers + ... |
import itertools
import math
import random
import time
from typing import *
import keras
import sklearn.metrics
import numpy as np
import PythonExtras.Normalizer as Normalizer
from PythonExtras import numpy_extras as npe
class KerasBatchedCallback(keras.callbacks.Callback):
def on_macro_batch_start(self, macr... | [
"math.ceil",
"random.shuffle",
"numpy.ones",
"numpy.var",
"time.time",
"numpy.mean",
"numpy.round",
"itertools.chain"
] | [((4074, 4105), 'itertools.chain', 'itertools.chain', (['trainX', 'trainY'], {}), '(trainX, trainY)\n', (4089, 4105), False, 'import itertools\n'), ((4128, 4157), 'itertools.chain', 'itertools.chain', (['testX', 'testY'], {}), '(testX, testY)\n', (4143, 4157), False, 'import itertools\n'), ((5271, 5325), 'math.ceil', '... |
"""Return pie chart showing class distribution of dataset.
Based on Bokeh pie chart gallery example available at:
https://docs.bokeh.org/en/latest/docs/gallery/pie_chart.html
"""
# %% Imports
# Standard system imports
from math import pi
# Related third party imports
from bokeh.models import ColumnDataSource
from bo... | [
"bokeh.transform.cumsum",
"bokeh.models.ColumnDataSource",
"bokeh.plotting.figure",
"numpy.unique"
] | [((1395, 1488), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (["{'angle': angle, 'color': colors, 'classes': CLASSES, 'counts': COUNTS}"], {}), "({'angle': angle, 'color': colors, 'classes': CLASSES,\n 'counts': COUNTS})\n", (1411, 1488), False, 'from bokeh.models import ColumnDataSource\n'), ((1697, 1930), ... |
'''
Created on Jul 13, 2017
@author: <NAME>, <NAME>
'''
import numpy as np
from collections import Iterable
def _create_structured_vector(size, fields, copy=False):
''' create np.array of structure filled with default values
Args:
shape: tuple, shape of the array
fields: list of tuples of (... | [
"numpy.copy",
"numpy.dtype",
"numpy.rec.array",
"numpy.where",
"numpy.array"
] | [((1040, 1053), 'numpy.dtype', 'np.dtype', (['dts'], {}), '(dts)\n', (1048, 1053), True, 'import numpy as np\n'), ((1176, 1206), 'numpy.rec.array', 'np.rec.array', (['values'], {'dtype': 'dt'}), '(values, dtype=dt)\n', (1188, 1206), True, 'import numpy as np\n'), ((3434, 3475), 'numpy.rec.array', 'np.rec.array', (['a[0... |
import os
import cv2 as cv
import argparse
import numpy as np
import math
import shutil
rootdir = "/mnt/data/datasets/PID_YOLO" #images+labels acquire from
savepath = "/mnt/data/datasets/PID_YOLO/divide" # images+labels save in
#rootdir = "D:/Download/PID_YOLO"
#savepath = "D:/Download/PID_YOLO/train"
... | [
"os.makedirs",
"math.ceil",
"os.path.isdir",
"cv2.imwrite",
"numpy.zeros",
"cv2.rectangle",
"shutil.rmtree",
"os.path.join",
"os.listdir"
] | [((673, 696), 'os.path.isdir', 'os.path.isdir', (['savepath'], {}), '(savepath)\n', (686, 696), False, 'import os\n'), ((729, 750), 'os.makedirs', 'os.makedirs', (['savepath'], {}), '(savepath)\n', (740, 750), False, 'import os\n'), ((864, 883), 'os.listdir', 'os.listdir', (['rootdir'], {}), '(rootdir)\n', (874, 883), ... |
#!/usr/bin/env python
# flake8: noqa
"""Tests `nineturn.core.tf_functions` package."""
import numpy as np
import tensorflow as tf
from nineturn.core.config import set_backend
from nineturn.core.backends import TENSORFLOW
from tests.core.common_functions import *
arr1 = np.random.rand(3, 4)
def test_to_te... | [
"nineturn.core.tf_functions.nt_layers_list",
"nineturn.core.config.set_backend",
"nineturn.core.tf_functions.reshape_tensor",
"numpy.random.rand",
"nineturn.core.tf_functions._to_tensor"
] | [((280, 300), 'numpy.random.rand', 'np.random.rand', (['(3)', '(4)'], {}), '(3, 4)\n', (294, 300), True, 'import numpy as np\n'), ((384, 407), 'nineturn.core.config.set_backend', 'set_backend', (['TENSORFLOW'], {}), '(TENSORFLOW)\n', (395, 407), False, 'from nineturn.core.config import set_backend\n'), ((600, 623), 'ni... |
"""validate.py: Utilities for validating input."""
# Standard imports
import numpy as np
import pandas as pd
import pdb
# MAVE-NN imports
from mavenn.src.reshape import _get_shape_and_return_1d_array
from mavenn.src.error_handling import check, handle_errors
# Define built-in alphabets to use with MAVE-NN
alphabet_d... | [
"mavenn.src.reshape._get_shape_and_return_1d_array",
"numpy.array",
"mavenn.src.error_handling.check"
] | [((339, 369), 'numpy.array', 'np.array', (["['A', 'C', 'G', 'T']"], {}), "(['A', 'C', 'G', 'T'])\n", (347, 369), True, 'import numpy as np\n'), ((382, 412), 'numpy.array', 'np.array', (["['A', 'C', 'G', 'U']"], {}), "(['A', 'C', 'G', 'U'])\n", (390, 412), True, 'import numpy as np\n'), ((429, 543), 'numpy.array', 'np.a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" File utilities comparable to similarly named bash utils: rm_rf(), rm_f(), and mkdir_p()
dataset1.0 is in files like: PPE1.rar PPE2.zip PPE3.zip PP4.7zip
dataset2.0 is in gs:/Buckets/safety_monitoring/data/obj/supplemental/"""
from __future__ import print_function, unic... | [
"os.remove",
"pandas.read_csv",
"future.standard_library.install_aliases",
"numpy.empty",
"os.path.isfile",
"os.path.join",
"builtins.open",
"os.path.exists",
"nlpia.constants.logging.getLogger",
"io.StringIO",
"os.path.basename",
"re.match",
"pandas.to_datetime",
"os.rmdir",
"builtins.s... | [((552, 586), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (584, 586), False, 'from future import standard_library\n'), ((1108, 1135), 'nlpia.constants.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1125, 1135), False, 'from nlpia.consta... |
from typing import Optional, List, Sequence
import pandas as pd
import numpy as np
from scipy import stats
import sha_calc as sha_calc
from gmhazard_calc.im import IM, IMType, to_im_list, to_string_list
from gmhazard_calc import gm_data
from gmhazard_calc import site
from gmhazard_calc import constants
from gmhazard_... | [
"numpy.isin",
"gmhazard_calc.im.to_im_list",
"numpy.sum",
"numpy.allclose",
"numpy.ones",
"numpy.argmin",
"gmhazard_calc.disagg.run_ensemble_disagg",
"pandas.DataFrame",
"numpy.full",
"gmhazard_calc.hazard.run_branches_hazard",
"pandas.concat",
"gmhazard_calc.site_source.get_distance_df",
"g... | [((3380, 3432), 'gmhazard_calc.hazard.run_ensemble_hazard', 'hazard.run_ensemble_hazard', (['ensemble', 'site_info', 'IMj'], {}), '(ensemble, site_info, IMj)\n', (3406, 3432), False, 'from gmhazard_calc import hazard\n'), ((4756, 4821), 'gmhazard_calc.shared.compute_adj_branch_weights', 'shared.compute_adj_branch_weigh... |
import os
import torch as T
import numpy as np
class OUActionNoise(object):
def __init__(self, mu, sigma=0.15, theta=.2, dt=1e-2, x0=None):
self.theta = theta
self.mu = mu
self.sigma = sigma
self.dt = dt
self.x0 = x0
self.reset()
def __call__(self):
x = ... | [
"torch.mean",
"numpy.random.choice",
"numpy.zeros_like",
"torch.nn.init.uniform_",
"torch.nn.functional.mse_loss",
"numpy.zeros",
"torch.add",
"torch.nn.LayerNorm",
"torch.cuda.is_available",
"numpy.random.normal",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.tensor",
"numpy.sqrt"... | [((841, 881), 'numpy.zeros', 'np.zeros', (['(self.memory_size, *inp_shape)'], {}), '((self.memory_size, *inp_shape))\n', (849, 881), True, 'import numpy as np\n'), ((914, 954), 'numpy.zeros', 'np.zeros', (['(self.memory_size, *inp_shape)'], {}), '((self.memory_size, *inp_shape))\n', (922, 954), True, 'import numpy as n... |
from numpy import ma
from osgeo import gdal
from shapely.geometry import shape
def lat_long_to_idx(gt, lon, lat):
"""
Take a geotransform and calculate the array indexes for the given lat,long.
:param gt: GDAL geotransform (e.g. gdal.Open(x).GetGeoTransform()).
:type gt: GDAL Geotransform ... | [
"osgeo.gdal.Open",
"numpy.ma.masked_values"
] | [((764, 798), 'osgeo.gdal.Open', 'gdal.Open', (['ascii', 'gdal.GA_ReadOnly'], {}), '(ascii, gdal.GA_ReadOnly)\n', (773, 798), False, 'from osgeo import gdal\n'), ((978, 1021), 'numpy.ma.masked_values', 'ma.masked_values', (['image', 'nodata'], {'copy': '(False)'}), '(image, nodata, copy=False)\n', (994, 1021), False, '... |
# Copyright 2021 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.ipu.scopes.ipu_scope",
"tensorflow.compiler.plugin.poplar.tests.test_utils.create_single_increasing_dataset",
"tensorflow.python.ipu.config.IPUConfig",
"tensorflow.python.ipu.ops.image_ops.normalise_image",
"tensorflow.python.ipu.loops.repeat",
"numpy.zeros",
"numpy.ones",
"tensorfl... | [((5697, 5714), 'tensorflow.python.platform.googletest.main', 'googletest.main', ([], {}), '()\n', (5712, 5714), False, 'from tensorflow.python.platform import googletest\n'), ((2197, 2208), 'tensorflow.python.ipu.config.IPUConfig', 'IPUConfig', ([], {}), '()\n', (2206, 2208), False, 'from tensorflow.python.ipu.config ... |
# use Python 3 style print function rather than Python 2 print statements:
from __future__ import print_function
def read_asc_file(file_path, verbose=True):
"""
Read in a file in ESRI ASCII raster format,
which consists of a header describing the grid followed by
values on the grid.
For more i... | [
"numpy.arange",
"numpy.meshgrid",
"numpy.flipud",
"numpy.loadtxt"
] | [((1443, 1476), 'numpy.loadtxt', 'np.loadtxt', (['file_path'], {'skiprows': '(6)'}), '(file_path, skiprows=6)\n', (1453, 1476), True, 'import numpy as np\n'), ((1612, 1629), 'numpy.flipud', 'np.flipud', (['values'], {}), '(values)\n', (1621, 1629), True, 'import numpy as np\n'), ((1754, 1771), 'numpy.meshgrid', 'np.mes... |
'''
____ __ __ __ __ _ __
/_ / ___ _/ / ___ ___ ___________ / /__ / /__/ /_____(_) /__
/ /_/ _ `/ _ \/ _ \/ -_) __/___/ -_) / -_) '_/ __/ __/ / '_/
/___/\_,_/_//_/_//_/\__/_/ \__/_/\__/_/\_\\__/_/ /_/_/\_\
Copyright 2021 ZAHNER-elek<NAME> GmbH & Co. KG
Permission... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"matplotlib.ticker.EngFormatter"
] | [((3109, 3137), 'matplotlib.ticker.EngFormatter', 'EngFormatter', ([], {'unit': 'xAxisUnit'}), '(unit=xAxisUnit)\n', (3121, 3137), False, 'from matplotlib.ticker import EngFormatter\n'), ((3400, 3418), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (3412, 3418), True, 'import matplotlib... |
import h5py
if h5py.get_config().mpi == False:
import warnings
warnings.warn("h5py not MPI enabled. Discontinuing test.")
import sys
sys.exit(0)
import underworld as uw
import numpy as np
mesh = uw.mesh.FeMesh_Cartesian(elementRes=(128,128))
swarm = uw.swarm.Swarm(mesh)
# create some variables to tra... | [
"underworld.swarm.Swarm",
"h5py.get_config",
"h5py.File",
"os.remove",
"random.randint",
"numpy.zeros",
"sys.exit",
"underworld.swarm.layouts.PerCellSpaceFillerLayout",
"numpy.array",
"underworld.mesh.FeMesh_Cartesian",
"warnings.warn",
"numpy.unique"
] | [((212, 259), 'underworld.mesh.FeMesh_Cartesian', 'uw.mesh.FeMesh_Cartesian', ([], {'elementRes': '(128, 128)'}), '(elementRes=(128, 128))\n', (236, 259), True, 'import underworld as uw\n'), ((268, 288), 'underworld.swarm.Swarm', 'uw.swarm.Swarm', (['mesh'], {}), '(mesh)\n', (282, 288), True, 'import underworld as uw\n... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import numpy as np
def FakeQuantization8BitsRowwise(data):
min_el = np.mi... | [
"caffe2.python.workspace.FetchBlob",
"caffe2.python.workspace.GlobalInit",
"caffe2.python.core.Net",
"caffe2.python.workspace.FeedBlob",
"numpy.asarray",
"caffe2.python.workspace.RunNetOnce",
"caffe2.python.workspace.RunOperatorOnce",
"numpy.min",
"numpy.max",
"caffe2.python.core.CreateOperator",
... | [((315, 335), 'numpy.min', 'np.min', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (321, 335), True, 'import numpy as np\n'), ((349, 369), 'numpy.max', 'np.max', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (355, 369), True, 'import numpy as np\n'), ((646, 753), 'caffe2.python.core.CreateOperator', 'core.CreateO... |
'''
WES.2018.03.01
'''
import numpy as np
import numpy.random as npr
from scipy.special import psi, gammaln
from collections import namedtuple
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
#%%
class ElasticNet(object):
'''
This is a singl... | [
"sklearn.preprocessing.StandardScaler",
"numpy.sum",
"numpy.abs",
"numpy.ones",
"numpy.isnan",
"numpy.shape",
"numpy.mean",
"numpy.linalg.norm",
"numpy.exp",
"numpy.multiply",
"numpy.copy",
"numpy.std",
"numpy.insert",
"numpy.reshape",
"numpy.matlib.repmat",
"numpy.divide",
"numpy.si... | [((3196, 3241), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': '(True)', 'with_std': '(True)'}), '(with_mean=True, with_std=True)\n', (3210, 3241), False, 'from sklearn.preprocessing import StandardScaler\n'), ((4592, 4608), 'numpy.shape', 'np.shape', (['self.x'], {}), '(self.x)\n', (4600,... |
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... | [
"unittest.main",
"numpy.random.seed",
"pyscf.gto.Mole",
"numpy.eye",
"ctypes.c_int",
"numpy.empty",
"numpy.allclose",
"numpy.zeros",
"numpy.einsum",
"numpy.fft.fftfreq",
"numpy.random.random",
"pyscf.gto.ft_ao.ft_ao",
"numpy.exp",
"pyscf.lib.load_library",
"numpy.arange",
"numpy.dot",
... | [((759, 785), 'pyscf.lib.load_library', 'lib.load_library', (['"""libpbc"""'], {}), "('libpbc')\n", (775, 785), False, 'from pyscf import lib\n'), ((792, 802), 'pyscf.gto.Mole', 'gto.Mole', ([], {}), '()\n', (800, 802), False, 'from pyscf import gto\n'), ((920, 941), 'numpy.random.seed', 'numpy.random.seed', (['(12)'],... |
import ctypes
import math
import os
import os.path
import typing
from nidigital import enums
import nidigital
from nidigital.history_ram_cycle_information import HistoryRAMCycleInformation
from nitsm.codemoduleapi import SemiconductorModuleContext as SMContext
import nitsm.codemoduleapi
import nitsm.enums
import numpy... | [
"os.getpid",
"nidevtools.digital.close_sessions",
"nidevtools.digital._apply_lut_per_site_to_per_instrument",
"nidevtools.digital._apply_lut_per_instrument_to_per_site",
"nidevtools.digital._apply_lut_per_instrument_to_per_site_per_pin",
"nidevtools.digital._apply_lut_per_site_per_pin_to_per_instrument",
... | [((2270, 2304), 'pytest.mark.pin_map', 'pytest.mark.pin_map', (['pin_file_name'], {}), '(pin_file_name)\n', (2289, 2304), False, 'import pytest\n'), ((2306, 2362), 'pytest.mark.filterwarnings', 'pytest.mark.filterwarnings', (['"""ignore::DeprecationWarning"""'], {}), "('ignore::DeprecationWarning')\n", (2332, 2362), Fa... |
import os
import logging
from collections import OrderedDict
from random import randint
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch
from d... | [
"numpy.maximum",
"torch.cat",
"detectron2.modeling.GeneralizedRCNNWithTTA",
"detectron2.engine.default_argument_parser",
"myILOD.utils.register.my_register",
"detectron2.data.build_detection_train_loader",
"os.path.join",
"detectron2.checkpoint.DetectionCheckpointer",
"detectron2.data.build.DatasetF... | [((8700, 8709), 'detectron2.config.get_cfg', 'get_cfg', ([], {}), '()\n', (8707, 8709), False, 'from detectron2.config import get_cfg\n'), ((8855, 8879), 'detectron2.engine.default_setup', 'default_setup', (['cfg', 'args'], {}), '(cfg, args)\n', (8868, 8879), False, 'from detectron2.engine import DefaultTrainer, defaul... |
import openseespy.opensees as ops
import pandas as pd
import csv
import os
import numpy as np
import random
import math
from functions import *
import column
# Create a dictionary to store the column section design parameters
data = {'P': [],'My': [],'Mz': [],'Width': [],'Depth': [],'D_rebar': [],
'w_g': [],... | [
"os.remove",
"numpy.random.random_sample",
"pandas.read_csv",
"numpy.empty",
"column.Column",
"os.path.isfile",
"pandas.DataFrame",
"openseespy.opensees.logFile",
"random.randint",
"openseespy.opensees.wipe",
"openseespy.opensees.model",
"numpy.linspace",
"csv.writer",
"math.ceil",
"open... | [((893, 908), 'column.Column', 'column.Column', ([], {}), '()\n', (906, 908), False, 'import column\n'), ((924, 955), 'openseespy.opensees.logFile', 'ops.logFile', (['logName', '"""-noEcho"""'], {}), "(logName, '-noEcho')\n", (935, 955), True, 'import openseespy.opensees as ops\n'), ((1135, 1148), 'csv.writer', 'csv.wr... |
# Game of Life
# Program by: <NAME>
# <EMAIL>
# github.com/angeeranaser
# Project referenced from https://robertheaton.com/2018/07/20/project-2-game-of-life/
import numpy as np
import main
def test_dead_cells_no_neighbors(): # Do dead cells with no live neighbors stay dead?
init = np.array([
[0... | [
"main.next_board",
"main.prettify",
"numpy.array",
"numpy.array_equal"
] | [((298, 341), 'numpy.array', 'np.array', (['[[0, 0, 0], [0, 0, 0], [0, 0, 0]]'], {}), '([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n', (306, 341), True, 'import numpy as np\n'), ((435, 478), 'numpy.array', 'np.array', (['[[0, 0, 0], [0, 0, 0], [0, 0, 0]]'], {}), '([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n', (443, 478), True, 'impor... |
import numpy as np
from math import log, gamma
''' Gammaln function of scipy.special library'''
def gammaln(a):
b = []
for i in np.nditer(a):
b.append(gamma(i))
b = np.array(b).reshape(a.shape)
b = np.log(np.absolute(b))
return b
def assess_dimension(spectrum, rank, n_samples):
"""... | [
"numpy.absolute",
"numpy.maximum",
"numpy.log",
"numpy.sum",
"numpy.eye",
"numpy.nditer",
"numpy.empty_like",
"math.gamma",
"numpy.array",
"numpy.linalg.inv",
"numpy.dot",
"math.log",
"numpy.sqrt"
] | [((140, 152), 'numpy.nditer', 'np.nditer', (['a'], {}), '(a)\n', (149, 152), True, 'import numpy as np\n'), ((1718, 1741), 'numpy.empty_like', 'np.empty_like', (['spectrum'], {}), '(spectrum)\n', (1731, 1741), True, 'import numpy as np\n'), ((233, 247), 'numpy.absolute', 'np.absolute', (['b'], {}), '(b)\n', (244, 247),... |
"""
Classes for assigning configurations in a batch to threads
Created on Feb 12, 2020
@author: <NAME> (<EMAIL>)
"""
from logging import getLogger
from math import isinf
from numpy import array
log = getLogger(__name__)
class BatchComposer(object):
"""Class for assigning configurations in a batch to threads
A... | [
"math.isinf",
"numpy.array",
"logging.getLogger"
] | [((203, 222), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (212, 222), False, 'from logging import getLogger\n'), ((1234, 1258), 'math.isinf', 'isinf', (['result.build_time'], {}), '(result.build_time)\n', (1239, 1258), False, 'from math import isinf\n'), ((4035, 4049), 'numpy.array', 'array', ... |
import matplotlib.pyplot as plt
import os
import pickle
import math
import datetime
import argparse
import csv
import re
from enum import Enum
class Tally():
def __init__(self):
self.data = {}
def record(self, e):
if e in self.data.keys():
self.data[e] += 1
else:
... | [
"pickle.dump",
"copy.deepcopy",
"numpy.flip",
"argparse.ArgumentParser",
"math.sqrt",
"csv.reader",
"numpy.abs",
"os.walk",
"re.match",
"datetime.datetime",
"numpy.shape",
"numpy.mean",
"numpy.array",
"os.path.join",
"numpy.sqrt"
] | [((7481, 7506), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7504, 7506), False, 'import argparse\n'), ((8431, 8463), 'os.path.join', 'os.path.join', (['"""."""', 'args.data_dir'], {}), "('.', args.data_dir)\n", (8443, 8463), False, 'import os\n'), ((8561, 8585), 'os.walk', 'os.walk', (['pat... |
"""BART based chatbot implementation."""
from typing import Dict
import numpy as np
import scipy.special as scp
import onnxruntime as rt
from npc_engine.services.text_generation.text_generation_base import TextGenerationAPI
from tokenizers import Tokenizer
import os
import json
class BartChatbot(TextGenera... | [
"json.load",
"os.path.join",
"numpy.asarray",
"os.path.exists",
"numpy.zeros",
"numpy.argpartition",
"numpy.arange",
"scipy.special.softmax",
"onnxruntime.SessionOptions",
"numpy.concatenate"
] | [((2232, 2251), 'onnxruntime.SessionOptions', 'rt.SessionOptions', ([], {}), '()\n', (2249, 2251), True, 'import onnxruntime as rt\n'), ((2902, 2946), 'os.path.join', 'os.path.join', (['model_path', '"""added_tokens.txt"""'], {}), "(model_path, 'added_tokens.txt')\n", (2914, 2946), False, 'import os\n'), ((2959, 2992),... |
import glob
import math
import os
import os.path as osp
import random
import time
from collections import OrderedDict
import torch
import cv2
import numpy as np
import copy
from ..utils.image import gaussian_radius, draw_umich_gaussian, draw_msra_gaussian
from ..utils.common import xyxy2xywh
from ..tra... | [
"random.shuffle",
"torch.cat",
"numpy.clip",
"os.path.isfile",
"glob.glob",
"random.randint",
"numpy.max",
"numpy.loadtxt",
"cv2.resize",
"copy.deepcopy",
"math.ceil",
"numpy.fliplr",
"random.random",
"os.path.isdir",
"numpy.zeros",
"cv2.VideoCapture",
"cv2.imread",
"numpy.array",
... | [((742, 761), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (755, 761), False, 'import os\n'), ((1707, 1727), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (1717, 1727), False, 'import cv2\n'), ((1945, 2005), 'cv2.resize', 'cv2.resize', (['img0', '(self.width, self.height)', 'cv2.INTER... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
import contextlib
import numpy as np
import pathlib
if TYPE_CHECKING:
import collections.abc
__all__ = [
"expand",
"temporary_seed",
]
def expand(path: str, dir: Optional[str] = None) -> str:
"""Expand relative path or pa... | [
"numpy.random.get_state",
"pathlib.Path",
"numpy.random.seed",
"numpy.random.set_state"
] | [((1017, 1038), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (1036, 1038), True, 'import numpy as np\n'), ((1072, 1092), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1086, 1092), True, 'import numpy as np\n'), ((1137, 1163), 'numpy.random.set_state', 'np.random.set_state', (... |
"""
Provides analysis tools for wind data.
"""
import matplotlib.pyplot as plt
import pandas
from pandas import DataFrame, Grouper
from windrose import WindroseAxes
from scipy import stats
import numpy as np
from .classes import WindTurbine
def boxplot(data, fields=None, labels=None, **box_kwargs):
"""
Draw... | [
"pandas.DataFrame",
"windrose.WindroseAxes.from_ax",
"scipy.stats.exponweib.fit",
"scipy.stats.exponweib.pdf",
"numpy.arange",
"pandas.Grouper",
"matplotlib.pyplot.subplots",
"pandas.concat"
] | [((1969, 1983), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1981, 1983), True, 'import matplotlib.pyplot as plt\n'), ((4077, 4164), 'windrose.WindroseAxes.from_ax', 'WindroseAxes.from_ax', ([], {'theta_labels': "['E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E']"}), "(theta_labels=['E', 'N-E', 'N', '... |
print("Importing libraries...")
import cv2
import numpy as np
import os
import random
import h5py
data_directory = "./data" #insert the directory you'll be working with
img_size = 128
categories = ["Positive", "Negative"]
training_data = []
def create_training_data():
for category in categories:
... | [
"h5py.File",
"random.shuffle",
"numpy.array",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((944, 973), 'random.shuffle', 'random.shuffle', (['training_data'], {}), '(training_data)\n', (958, 973), False, 'import random\n'), ((1536, 1584), 'h5py.File', 'h5py.File', (['"""./concrete_crack_image_data.h5"""', '"""w"""'], {}), "('./concrete_crack_image_data.h5', 'w')\n", (1545, 1584), False, 'import h5py\n'), (... |
import numpy as np
import timeit
embeddings = np.genfromtxt("embeddings.txt", delimiter=',')
def test():
embeddings1 = embeddings[0:1]
embeddings2 = embeddings[1:10001]
embeddings1 = embeddings1/np.linalg.norm(embeddings1, axis=1, keepdims=True)
embeddings2 = embeddings2/np.linalg.norm(embeddings2, ... | [
"numpy.subtract",
"timeit.repeat",
"numpy.square",
"numpy.genfromtxt",
"numpy.max",
"numpy.linalg.norm"
] | [((47, 93), 'numpy.genfromtxt', 'np.genfromtxt', (['"""embeddings.txt"""'], {'delimiter': '""","""'}), "('embeddings.txt', delimiter=',')\n", (60, 93), True, 'import numpy as np\n'), ((354, 391), 'numpy.subtract', 'np.subtract', (['embeddings1', 'embeddings2'], {}), '(embeddings1, embeddings2)\n', (365, 391), True, 'im... |
import pandas as pd
import numpy as np
import librosa
import random
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
def f0_to_2d(f0, sr, n_fft, f0_max):
# default shape = 100
f0 = f0[0]
shape0 = max(int(f0_max*n... | [
"numpy.load",
"random.randint",
"pandas.read_csv",
"numpy.zeros",
"numpy.array",
"librosa.load"
] | [((500, 533), 'numpy.array', 'np.array', (['f0_2d'], {'dtype': 'np.float32'}), '(f0_2d, dtype=np.float32)\n', (508, 533), True, 'import numpy as np\n'), ((875, 893), 'pandas.read_csv', 'pd.read_csv', (['table'], {}), '(table)\n', (886, 893), True, 'import pandas as pd\n'), ((1212, 1250), 'numpy.load', 'np.load', (["(se... |
import glob
import os.path
import cv2 as cv
import skimage.io
import numpy as np
import pandas as pd
import itertools as it
from skimage import measure
from copy import copy, deepcopy
from AffineCa2p.cellpose import models, utils
from AffineCa2p.FAIM.asift import affine_detect
from multiprocessing.pool impor... | [
"AffineCa2p.cellpose.utils.normalize99",
"numpy.sum",
"numpy.abs",
"numpy.clip",
"skimage.measure.find_contours",
"glob.glob",
"cv2.normalize",
"AffineCa2p.FAIM.find_obj.filter_matches",
"AffineCa2p.FAIM.find_obj.init_feature",
"pandas.DataFrame",
"skimage.segmentation.find_boundaries",
"cv2.w... | [((3374, 3430), 'cv2.normalize', 'cv.normalize', (['Template', 'Template', '(0)', '(255)', 'cv.NORM_MINMAX'], {}), '(Template, Template, 0, 255, cv.NORM_MINMAX)\n', (3386, 3430), True, 'import cv2 as cv\n'), ((9276, 9292), 'numpy.size', 'np.size', (['img2', '(1)'], {}), '(img2, 1)\n', (9283, 9292), True, 'import numpy ... |
from PIL import Image
import numpy as np
def get_image_array(image_path):
image = Image.open(image_path)
array_from_image = np.array(image)
return array_from_image
def coalesce_into_column(multidir_image_array):
single_array = []
a,b,c = multidir_image_array.shape
# we are hitti... | [
"numpy.corrcoef",
"numpy.array",
"PIL.Image.open"
] | [((95, 117), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (105, 117), False, 'from PIL import Image\n'), ((139, 154), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (147, 154), True, 'import numpy as np\n'), ((756, 820), 'numpy.corrcoef', 'np.corrcoef', (['[array[:slice_] for array ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 08:59:19 2020
@author: Timothe
"""
import re
import numpy as np
def QuickRegexp(Line,regex,**kwargs):
"""Line : input string to be processed
regex : input regex, can be easily designed at : https://regex101.com/
kwargs :
case = False / True : ca... | [
"re.finditer",
"numpy.zeros",
"numpy.ones",
"re.split"
] | [((509, 563), 're.finditer', 're.finditer', (['regex', 'Line', '(re.MULTILINE | re.IGNORECASE)'], {}), '(regex, Line, re.MULTILINE | re.IGNORECASE)\n', (520, 563), False, 'import re\n'), ((591, 629), 're.finditer', 're.finditer', (['regex', 'Line', 're.MULTILINE'], {}), '(regex, Line, re.MULTILINE)\n', (602, 629), Fals... |
import os
import logging
import collections
import yaml
import numpy as np
# from matplotlib import pyplot as plt
import graphviz as gv
import LCTM.metrics
from mathtools import utils, metrics
from blocks.core import labels as labels_lib
from blocks.core import blockassembly
logger = logging.getLogger(__name__)
d... | [
"yaml.dump",
"collections.defaultdict",
"mathtools.metrics.falsePositives",
"mathtools.utils.saveVariable",
"mathtools.utils.computeSegments",
"os.path.join",
"mathtools.metrics.falseNegatives",
"blocks.core.blockassembly.AssemblyAction",
"numpy.nanmean",
"mathtools.utils.copyFile",
"os.path.exi... | [((289, 316), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (306, 316), False, 'import logging\n'), ((396, 437), 'mathtools.metrics.truePositives', 'metrics.truePositives', (['pred_seq', 'true_seq'], {}), '(pred_seq, true_seq)\n', (417, 437), False, 'from mathtools import utils, metrics\... |
# --------------------------------------------------------
# Tensorflow VCL
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
"""
Generating training instance
"""
from __future__ import absolute_import
from __future__ import divis... | [
"numpy.maximum",
"numpy.empty",
"numpy.floor",
"numpy.ones",
"pickle.load",
"numpy.round",
"random.randint",
"os.path.exists",
"tensorflow.TensorShape",
"numpy.random.shuffle",
"functools.partial",
"copy.deepcopy",
"numpy.minimum",
"numpy.asarray",
"numpy.concatenate",
"numpy.zeros",
... | [((4698, 4719), 'numpy.zeros', 'np.zeros', (['(64, 64, 2)'], {}), '((64, 64, 2))\n', (4706, 4719), True, 'import numpy as np\n'), ((6309, 6353), 'numpy.zeros', 'np.zeros', (['(num_joints + 1, 2)'], {'dtype': '"""int32"""'}), "((num_joints + 1, 2), dtype='int32')\n", (6317, 6353), True, 'import numpy as np\n'), ((7235, ... |
import warnings
import os
import math
import numpy as np
import PIL
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from ofa.imagenet_classification.data_providers.base_provider import DataProvider
from ofa.utils.my_dataloader.my_random_resize_crop import ... | [
"torchvision.transforms.ColorJitter",
"torchvision.transforms.RandomAffine",
"ofa.utils.my_dataloader.my_random_resize_crop.MyRandomResizedCrop.get_candidate_image_size",
"math.ceil",
"os.path.exists",
"torchvision.datasets.ImageFolder",
"torchvision.transforms.Compose",
"numpy.array",
"torchvision.... | [((4314, 4364), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['self.train_path', '_transforms'], {}), '(self.train_path, _transforms)\n', (4334, 4364), True, 'import torchvision.datasets as datasets\n'), ((4589, 4638), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['self.test_path', '_tra... |
"""simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__copyright__ = "Copyright 2020, Ginger Lab"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
from math import pi
from scipy.integrate import odeint
import ffta
# Set constant 2 * pi.
PI2 = 2 * p... | [
"numpy.divide",
"numpy.seterr",
"scipy.integrate.odeint",
"numpy.allclose",
"numpy.mod",
"ffta.pixel.Pixel",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"numpy.cos",
"numpy.sqrt"
] | [((3697, 3723), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (3706, 3723), True, 'import numpy as np\n'), ((4654, 4698), 'numpy.linspace', 'np.linspace', (['(0)', 'self.total_time'], {'num': 'num_pts'}), '(0, self.total_time, num=num_pts)\n', (4665, 4698), True, 'import numpy as... |
"""
Dataset stored as NPY files in directory or
as NPZ dictionary.
"""
import os
import numpy as np
import torch
from ..tools import np_of_torchdefaultdtype
from .database import Database
from .restarter import Restartable
class DirectoryDatabase(Database, Restartable):
"""
Database stored as NPY files in a... | [
"numpy.load",
"os.path.join",
"os.listdir"
] | [((3824, 3837), 'numpy.load', 'np.load', (['file'], {}), '(file)\n', (3831, 3837), True, 'import numpy as np\n'), ((1487, 1508), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (1497, 1508), False, 'import os\n'), ((2741, 2770), 'os.path.join', 'os.path.join', (['directory', 'file'], {}), '(directory,... |
import ray
import torch
import os
import time
import numpy as np
import numpy.random as rd
from collections import deque
import datetime
from copy import deepcopy
from ray_elegantrl.buffer import ReplayBuffer, ReplayBufferMP
from ray_elegantrl.evaluate import RecordEpisode, RecordEvaluate, Evaluator
from ray_elegantrl.... | [
"numpy.random.seed",
"numpy.ones",
"numpy.clip",
"torch.set_default_dtype",
"ray.put",
"numpy.random.randint",
"shutil.rmtree",
"ray_elegantrl.evaluate.RecordEvaluate",
"ray_elegantrl.evaluate.RecordEpisode",
"datetime.datetime.now",
"copy.deepcopy",
"ray.method",
"numpy.tanh",
"torch.manu... | [((11571, 11596), 'ray.method', 'ray.method', ([], {'num_returns': '(1)'}), '(num_returns=1)\n', (11581, 11596), False, 'import ray\n'), ((17025, 17050), 'ray.method', 'ray.method', ([], {'num_returns': '(1)'}), '(num_returns=1)\n', (17035, 17050), False, 'import ray\n'), ((26763, 26776), 'ray.put', 'ray.put', (['args'... |
#!/usr/bin/python3
#-*- coding: UTF-8 -*-
import collections
import numpy as np
import tensorflow as tf
'''
author: log16
Data: 2017/5/4
'''
#-------------------------------数据预处理---------------------------#
poetry_file =r'C:\Users\huaru\PycharmProjects\LSTM_CNN\data\poetry.txt'
# 诗集
poetrys = []
wi... | [
"tensorflow.trainable_variables",
"tensorflow.reshape",
"tensorflow.ConfigProto",
"tensorflow.matmul",
"tensorflow.train.latest_checkpoint",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.assign",
"numpy.full",
"tensorflow.nn.softmax",
"numpy.copy",
"tensorflow.variable_scope",
"tensorfl... | [((1151, 1181), 'collections.Counter', 'collections.Counter', (['all_words'], {}), '(all_words)\n', (1170, 1181), False, 'import collections\n'), ((3538, 3582), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[batch_size, None]'], {}), '(tf.int32, [batch_size, None])\n', (3552, 3582), True, 'import tensorflo... |
"""This module provides a complicated algorithm for making voxels out of regularly
gridded points. Considering that this algorithm is rather complex, we are keeping
it in its own module until we can simplify it, clean up the code, and make it
capable of handling non-uniformly gridded points
"""
__all__ = [
'Voxeli... | [
"numpy.stack",
"vtk.vtkUnstructuredGrid",
"numpy.average",
"numpy.concatenate",
"vtk.vtkPoints",
"vtk.vtkDoubleArray",
"numpy.ones",
"numpy.rad2deg",
"numpy.around",
"numpy.min",
"vtk.util.numpy_support.numpy_to_vtkIdTypeArray",
"vtk.numpy_interface.dataset_adapter.WrapDataObject",
"numpy.ar... | [((1667, 1687), 'vtk.vtkDoubleArray', 'vtk.vtkDoubleArray', ([], {}), '()\n', (1685, 1687), False, 'import vtk\n'), ((1888, 1908), 'vtk.vtkDoubleArray', 'vtk.vtkDoubleArray', ([], {}), '()\n', (1906, 1908), False, 'import vtk\n'), ((4306, 4360), 'numpy.stack', 'np.stack', (['(x - dx / 2, y - dy / 2, z - dz / 2)'], {'ax... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"pickle.loads",
"cirq.testing.EqualsTester",
"cirq.GridQid.square",
"cirq.GridQubit.rect",
"cirq.GridQubit.square",
"cirq.CircuitDiagramInfo",
"cirq.GridQid.from_diagram",
"cirq.GridQubit",
"cirq.testing.OrderTester",
"pytest.raises",
"numpy.array",
"cirq.GridQid.rect",
"pytest.mark.parametr... | [((8679, 8757), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dtype"""', '(np.int8, np.int16, np.int32, np.int64, int)'], {}), "('dtype', (np.int8, np.int16, np.int32, np.int64, int))\n", (8702, 8757), False, 'import pytest\n'), ((701, 721), 'cirq.GridQubit', 'cirq.GridQubit', (['(3)', '(4)'], {}), '(3, 4... |
####################
# George Mason University - ECE612
# <NAME> - Spring 2017
#
# Final Project
# spectrum.py
# Implements a numpy FFT in Python 3.4
# and scales the results to fit on an LED array
####################
import numpy as np
#samplerate: Choose a sample rate of 44.1 KHz, the same sample rate used for ... | [
"numpy.fft.rfft",
"numpy.sum",
"numpy.abs",
"numpy.power",
"numpy.log2",
"numpy.append",
"numpy.array",
"numpy.log10"
] | [((1161, 1191), 'numpy.array', 'np.array', (['[min_freq, max_freq]'], {}), '([min_freq, max_freq])\n', (1169, 1191), True, 'import numpy as np\n'), ((1274, 1295), 'numpy.log10', 'np.log10', (['bin_mapping'], {}), '(bin_mapping)\n', (1282, 1295), True, 'import numpy as np\n'), ((1921, 1946), 'numpy.power', 'np.power', (... |
# some_file.py
import sys
import time
import json
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/tf/jovyan/work')
import logging
import numpy as np
import os
import tensorflow as tf
import numpy.random as rnd
from sklearn.metrics import f1_score, precision_recall_fscore_support
from sklearn.e... | [
"numpy.random.seed",
"sklearn.ensemble.IsolationForest",
"numpy.put",
"ad_examples.common.utils.dataframe_to_matrix",
"sklearn.neighbors.LocalOutlierFactor",
"numpy.zeros",
"sys.path.insert",
"time.clock",
"ad_examples.common.utils.read_csv",
"json.dumps",
"sklearn.metrics.f1_score",
"numpy.ar... | [((102, 139), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""/tf/jovyan/work"""'], {}), "(1, '/tf/jovyan/work')\n", (117, 139), False, 'import sys\n'), ((965, 992), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (982, 992), False, 'import logging\n'), ((4018, 4029), 'numpy.zeros', 'np... |
# The script contains definition of different elements to be analyzed
# from spectra obtained from Olympus Delta XRF
# The definition includes element name from periodic table,
# the beam number, which is the most suitable for the element,
# Savitzky-Golay filter window length
# integration limits for peak integration... | [
"numpy.array"
] | [((943, 963), 'numpy.array', 'np.array', (['[[1.5, 2]]'], {}), '([[1.5, 2]])\n', (951, 963), True, 'import numpy as np\n'), ((1016, 1055), 'numpy.array', 'np.array', (['[[9.3, 10.2], [10.75, 12.25]]'], {}), '([[9.3, 10.2], [10.75, 12.25]])\n', (1024, 1055), True, 'import numpy as np\n')] |
import random
import numpy as np
import torch
import torch.nn as nn
class res_MLPBlock(nn.Module):
"""Skippable MLPBlock with relu"""
def __init__(self, width):
super(res_MLPBlock, self).__init__()
self.block = nn.Sequential(nn.Linear(width, width), nn.ReLU(), nn.BatchNorm1d(width)) # nn.Laye... | [
"torch.ones_like",
"torch.nn.ReLU",
"numpy.random.seed",
"torch.nn.Sequential",
"torch.manual_seed",
"torch.nn.BatchNorm1d",
"random.seed",
"torch.nn.Linear"
] | [((1337, 1364), 'torch.nn.Sequential', 'nn.Sequential', (['*self.layers'], {}), '(*self.layers)\n', (1350, 1364), True, 'import torch.nn as nn\n'), ((251, 274), 'torch.nn.Linear', 'nn.Linear', (['width', 'width'], {}), '(width, width)\n', (260, 274), True, 'import torch.nn as nn\n'), ((276, 285), 'torch.nn.ReLU', 'nn.R... |
#!/usr/bin/python2.7
import tensorflow as tf
import numpy as np
import os
from scipy.ndimage.filters import gaussian_filter1d
from utils.helper_functions import get_label_length_seq
class ModelCNN:
def __init__(self, nRows, nCols):
self.input_vid = tf.placeholder('float', [None, nRows, nCols, 1], nam... | [
"utils.helper_functions.get_label_length_seq",
"scipy.ndimage.filters.gaussian_filter1d",
"numpy.argmax",
"tensorflow.reshape",
"tensorflow.nn.l2_normalize",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.nn.conv2d",
"tensorflow.truncated_normal",
"os.path.exists",
"tensorflow.placehold... | [((268, 334), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, nRows, nCols, 1]'], {'name': '"""input_vid"""'}), "('float', [None, nRows, nCols, 1], name='input_vid')\n", (282, 334), True, 'import tensorflow as tf\n'), ((357, 420), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None,... |
import csv
import os
import time
import uuid
import pickle
from random import randint
import numpy as np
import pandas as pd
from hyperopt import STATUS_OK, Trials, fmin, hp, tpe
from sklearn.metrics import mean_squared_error as mse
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
... | [
"sklearn.model_selection.train_test_split",
"hyperopt.fmin",
"numpy.argmin",
"data.connect_db",
"numpy.sin",
"hyperopt.hp.quniform",
"os.path.join",
"random.randint",
"data.fetch_data",
"os.path.exists",
"hyperopt.Trials",
"sklearn.metrics.mean_squared_error",
"hyperopt.hp.uniform",
"csv.w... | [((375, 411), 'os.path.join', 'os.path.join', (['"""models"""', '"""models.pkl"""'], {}), "('models', 'models.pkl')\n", (387, 411), False, 'import os\n'), ((429, 464), 'os.path.join', 'os.path.join', (['"""models"""', '"""train.log"""'], {}), "('models', 'train.log')\n", (441, 464), False, 'import os\n'), ((477, 504), ... |
"""Perturbation-based probabilistic ODE solver."""
from typing import Callable, Optional
import numpy as np
import scipy.integrate
from probnum import problems
from probnum.diffeq import perturbed, stepsize
from probnum.typing import ArrayLike, FloatLike
__all__ = ["perturbsolve_ivp"]
METHODS = {
"RK45": scipy... | [
"probnum.diffeq.stepsize.ConstantSteps",
"probnum.diffeq.perturbed.scipy_wrapper.WrappedScipyRungeKutta",
"probnum.diffeq.stepsize.AdaptiveSteps",
"probnum.diffeq.stepsize.propose_firststep",
"numpy.asarray"
] | [((7486, 7573), 'probnum.diffeq.perturbed.scipy_wrapper.WrappedScipyRungeKutta', 'perturbed.scipy_wrapper.WrappedScipyRungeKutta', (['METHODS[method]'], {'steprule': 'steprule'}), '(METHODS[method], steprule=\n steprule)\n', (7532, 7573), False, 'from probnum.diffeq import perturbed, stepsize\n'), ((8134, 8199), 'pr... |
"""
==============================
Embla file reader from python
==============================
This script is a python version of : https://github.com/gpiantoni/hgse_private/blob/master/ebmread.m
Version 0.21
Author: <NAME> <EMAIL>
date: 3.20.2021
"""
import numpy as np
from struct import unpack
import datetim... | [
"numpy.frombuffer",
"struct.unpack",
"datetime.timedelta",
"datetime.datetime"
] | [((1396, 1454), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'seconds', 'microseconds': 'microsec'}), '(seconds=seconds, microseconds=microsec)\n', (1414, 1454), False, 'import datetime\n'), ((1249, 1278), 'struct.unpack', 'unpack', (['(se + num_type)', 'buffer'], {}), '(se + num_type, buffer)\n', (1255... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"numpy.stack",
"numpy.sum",
"numpy.zeros",
"numpy.ones",
"numpy.isnan",
"numpy.any",
"numpy.where",
"numpy.array",
"numpy.nanmean"
] | [((3373, 3418), 'numpy.array', 'np.array', (['expected_overlaps'], {'dtype': 'np.float32'}), '(expected_overlaps, dtype=np.float32)\n', (3381, 3418), True, 'import numpy as np\n'), ((3745, 3774), 'numpy.zeros', 'np.zeros', (['max_len', 'np.float32'], {}), '(max_len, np.float32)\n', (3753, 3774), True, 'import numpy as ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/14 22:51
# @Author : <NAME>
# @Site : www.jackokie.com
# @File : file_2_1.py
# @Software: PyCharm
# @contact: <EMAIL>
import numpy as np
import matplotlib.pyplot as plt
# matplotlib.rc('font', size=30)
fig = plt.figure(figsize=(8,6), dpi=160)
ax ... | [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.xlabel"
] | [((282, 317), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)', 'dpi': '(160)'}), '(figsize=(8, 6), dpi=160)\n', (292, 317), True, 'import matplotlib.pyplot as plt\n'), ((585, 607), 'numpy.arange', 'np.arange', (['(-5)', '(10)', '(0.1)'], {}), '(-5, 10, 0.1)\n', (594, 607), True, 'import numpy as np\... |
import time
from collections import OrderedDict, defaultdict
from functools import reduce, wraps
from inspect import signature
import matplotlib.pyplot as plt
from rfho import as_list
import tensorflow as tf
import rfho as rf
try:
from IPython.display import IFrame
import IPython
except ImportError:
pr... | [
"os.mkdir",
"os.remove",
"datetime.datetime.datetime.now",
"tensorflow.get_collection",
"numpy.shape",
"os.path.isfile",
"tensorflow.get_default_graph",
"os.path.join",
"rfho.simple_name",
"_pickle.load",
"numpy.random.randn",
"numpy.savetxt",
"os.path.exists",
"rfho.as_list",
"inspect.s... | [((801, 829), 'os.getenv', 'os.getenv', (['"""RFHO_EXP_FOLDER"""'], {}), "('RFHO_EXP_FOLDER')\n", (810, 829), False, 'import os\n'), ((2631, 2670), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename, **savefig_kwargs)\n', (2642, 2670), True, 'import matplotlib.pyplot as plt\n'), ((5758, 5774), '... |
import numpy as np
import mdtraj as md
__all__ = ["COM", "index_atom_name", "atom_name_COM", "shift_COM", "parse_CG_pdb", "parse_AA_pdb"]
def COM(trj, inds):
return md.compute_center_of_mass(trj.atom_slice(inds))
def index_atom_name(trj, name):
return np.where(name == np.array([atom.name for atom in trj.to... | [
"numpy.where",
"numpy.array"
] | [((884, 901), 'numpy.array', 'np.array', (['CG_bead'], {}), '(CG_bead)\n', (892, 901), True, 'import numpy as np\n'), ((1185, 1202), 'numpy.array', 'np.array', (['AA_bead'], {}), '(AA_bead)\n', (1193, 1202), True, 'import numpy as np\n'), ((569, 597), 'numpy.where', 'np.where', (['(name == bead_array)'], {}), '(name ==... |
import numpy as np
from .. import utilities
POSITION_VALUES = np.array([[30, -12, 0, -1, -1, 0, -12, 30],
[-12, -15, -3, -3, -3, -3, -15, -12],
[0, -3, 0, -1, -1, 0, -3, 0],
[-1, -3, -1, -1, -1, -1, -3, -1],
... | [
"numpy.multiply",
"numpy.array"
] | [((63, 359), 'numpy.array', 'np.array', (['[[30, -12, 0, -1, -1, 0, -12, 30], [-12, -15, -3, -3, -3, -3, -15, -12], [0,\n -3, 0, -1, -1, 0, -3, 0], [-1, -3, -1, -1, -1, -1, -3, -1], [-1, -3, -1,\n -1, -1, -1, -3, -1], [0, -3, 0, -1, -1, 0, -3, 0], [-12, -15, -3, -3, -\n 3, -3, -15, -12], [30, -12, 0, -1, -1, 0... |
"""
Модуль работы над инклинометрией скважины
<NAME>. <NAME>. 18.07.2019 г.
"""
import pandas as pd
import numpy as np
import scipy.interpolate as interpolate
# TODO добавить логику для проверки ошибок - "защиту от дурака"
# TODO проверить методы интерполяции - где уместно линейную, где кубическую?
# TODO проверить... | [
"pandas.read_excel",
"scipy.interpolate.interp1d",
"numpy.asarray"
] | [((1890, 1921), 'pandas.read_excel', 'pd.read_excel', (['path_to_file_str'], {}), '(path_to_file_str)\n', (1903, 1921), True, 'import pandas as pd\n'), ((3120, 3284), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["self.deviation_survey_dataframe['Глубина конца интервала, м']", "self.deviation_survey_dataframe... |
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
if len(sys.argv) < 2:
print('No data file found ...')
sys.exit()
data = pd.read_csv(sys.argv[1])
#data=pd.read_csv("data2.txt")
data = data.sample(frac=1)
#nor_data=(data-data.mean())/data.std() #Wh... | [
"numpy.size",
"matplotlib.pyplot.show",
"pandas.read_csv",
"matplotlib.pyplot.axes",
"numpy.hstack",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.dot",
"sys.exit"
] | [((191, 215), 'pandas.read_csv', 'pd.read_csv', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (202, 215), True, 'import pandas as pd\n'), ((351, 365), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (359, 365), True, 'import numpy as np\n'), ((421, 447), 'numpy.array', 'np.array', (['nor_data[:, 0:2]'], {}), '(nor_d... |
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import cv2
import os
import sys
# scipt dirctory
yolo_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0,yolo_dir)
from util import *
import argparse
import os.path as osp
from darknet import Darkne... | [
"sys.path.pop",
"torch.cuda.synchronize",
"darknet.Darknet",
"torch.nn.Sequential",
"torch.autograd.Variable",
"os.path.realpath",
"torch.FloatTensor",
"sys.path.insert",
"torch.cuda.is_available",
"numpy.array",
"torch.nn.Linear",
"torch.no_grad",
"torch.min"
] | [((208, 236), 'sys.path.insert', 'sys.path.insert', (['(0)', 'yolo_dir'], {}), '(0, yolo_dir)\n', (223, 236), False, 'import sys\n'), ((384, 399), 'sys.path.pop', 'sys.path.pop', (['(0)'], {}), '(0)\n', (396, 399), False, 'import sys\n'), ((1199, 1224), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '(... |
from comodels import penn
import numpy as np
def test_rolling_sum():
a = np.array([1, 2, 3, 4, 5])
window = 2
expected = [3, 5, 7, 9]
assert penn.rolling_sum(a, window).tolist() == expected
| [
"comodels.penn.rolling_sum",
"numpy.array"
] | [((79, 104), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (87, 104), True, 'import numpy as np\n'), ((159, 186), 'comodels.penn.rolling_sum', 'penn.rolling_sum', (['a', 'window'], {}), '(a, window)\n', (175, 186), False, 'from comodels import penn\n')] |
"""Compile BBox position from meta file into training vector.
The training output `y` is a feature map with 5 features: label, BBox centre
relative to anchor, and BBox absolute width/height.
The label values, ie the entries in y[0, :, :], are non-negative integers. A
label of zero always means background.
"""
import ... | [
"argparse.ArgumentParser",
"numpy.mean",
"bz2.open",
"os.path.join",
"os.path.abspath",
"numpy.zeros_like",
"os.path.exists",
"feature_utils.downsampleMatrix",
"inspect_feature.main",
"multiprocessing.Pool",
"sys.exit",
"numpy.count_nonzero",
"feature_utils.ft2im",
"os.path.isdir",
"nump... | [((717, 777), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compile training data"""'}), "(description='Compile training data')\n", (740, 777), False, 'import argparse\n'), ((1376, 1401), 'os.path.isdir', 'os.path.isdir', (['param.path'], {}), '(param.path)\n', (1389, 1401), False, 'imp... |
import numpy as np
import taichi as ti
def cook_image_to_bytes(img):
"""
Takes a NumPy array or Taichi tensor of any type.
Returns a NumPy array of uint8.
This is used by ti.imwrite and ti.imdisplay.
"""
if not isinstance(img, np.ndarray):
img = img.to_numpy()
if img.dtype in [np.... | [
"taichi.imshow",
"io.BytesIO",
"taichi.GUI",
"numpy.ascontiguousarray",
"numpy.iinfo",
"numpy.clip",
"taichi.core.imread",
"taichi.core.imwrite",
"taichi.core.C_memcpy",
"numpy.ndarray"
] | [((1611, 1636), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['img'], {}), '(img)\n', (1631, 1636), True, 'import numpy as np\n'), ((1700, 1748), 'taichi.core.imwrite', 'ti.core.imwrite', (['filename', 'ptr', 'resx', 'resy', 'comp'], {}), '(filename, ptr, resx, resy, comp)\n', (1715, 1748), True, 'import taichi ... |
from config import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from getpass import getpass
from os import remove
import zipfile
import pandas as pd
import numpy as np
from lxml import etree as et
def _parseBgeXml(f):
timestamp = []
consumed = []
... | [
"pandas.DataFrame",
"os.remove",
"zipfile.ZipFile",
"selenium.webdriver.Firefox",
"selenium.webdriver.FirefoxProfile",
"getpass.getpass",
"time.sleep",
"lxml.etree.iterparse",
"numpy.array",
"pandas.Series"
] | [((399, 460), 'lxml.etree.iterparse', 'et.iterparse', (['f'], {'tag': '"""{http://naesb.org/espi}IntervalReading"""'}), "(f, tag='{http://naesb.org/espi}IntervalReading')\n", (411, 460), True, 'from lxml import etree as et\n'), ((1570, 1596), 'selenium.webdriver.FirefoxProfile', 'webdriver.FirefoxProfile', ([], {}), '(... |
import numpy as np
import seaborn as sns
from numpy import genfromtxt
from matplotlib import pyplot as plt
from sklearn.decomposition import FastICA
import pandas as pd
# data = genfromtxt('Z:/nani/experiment/aldoh/dry laugh/dry laugh_2019.06.01_12.26.08.csv', skip_header=1, delimiter=',')
# data = genfromtxt('Z:/nani/... | [
"matplotlib.pyplot.title",
"sklearn.decomposition.FastICA",
"pickle.dump",
"matplotlib.pyplot.show",
"scipy.signal.welch",
"matplotlib.pyplot.plot",
"seaborn.heatmap",
"pandas.read_csv",
"numpy.transpose",
"numpy.genfromtxt",
"matplotlib.pyplot.subplots",
"seaborn.despine",
"matplotlib.pyplo... | [((3629, 3674), 'numpy.genfromtxt', 'genfromtxt', (['loc'], {'skip_header': '(1)', 'delimiter': '""","""'}), "(loc, skip_header=1, delimiter=',')\n", (3639, 3674), False, 'from numpy import genfromtxt\n'), ((3680, 3721), 'pandas.read_csv', 'pd.read_csv', (['loc'], {'header': 'None', 'skiprows': '(1)'}), '(loc, header=N... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | [
"numpy.abs",
"numpy.maximum",
"quantization.unified_quantization_handler.out_qs_constraint",
"quantization.multiplicative.scaling_qtypes.MultMulBiasScaleQType",
"math.pow",
"numpy.max",
"quantization.qtype.QType",
"quantization.unified_quantization_handler.in_qs_constraint",
"copy.deepcopy",
"nump... | [((1998, 2037), 'logging.getLogger', 'logging.getLogger', (["('nntool.' + __name__)"], {}), "('nntool.' + __name__)\n", (2015, 2037), False, 'import logging\n'), ((3113, 3245), 'quantization.unified_quantization_handler.options', 'options', (['NE16_WEIGHT_BITS_OPTION', 'FORCE_EXTERNAL_SIZE_OPTION', 'NARROW_WEIGHTS_OPTI... |
import datetime as dt
import numpy as np
from sqlalchemy import create_engine, func
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.ext.automap import automap_base
import sqlalchemy
from flask import Flask, jsonify, render_template
app = Flask(__name__)
# Database setup
engine = create_engine("sqlit... | [
"sqlalchemy.func.avg",
"numpy.ravel",
"flask.Flask",
"datetime.date",
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.orm.Session",
"flask.jsonify",
"sqlalchemy.func.min",
"datetime.timedelta",
"flask.render_template",
"sqlalchemy.create_engine",
"sqlalchemy.ext.automap.automap_base",
"sqlalchemy... | [((257, 272), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (262, 272), False, 'from flask import Flask, jsonify, render_template\n'), ((300, 398), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///Resources/hawaii.sqlite"""'], {'connect_args': "{'check_same_thread': False}"}), "('sqlite:///Res... |
import matplotlib
matplotlib.use('Qt4Agg')
import pylab
import crash_on_ipy
import matplotlib.pyplot as plt
from pydmd import MrDMD
from pydmd import DMD
import numpy as np
from past.utils import old_div
def create_sample_data():
x = np.linspace(-10, 10, 80)
t = np.linspace(0, 20, 1600)
Xm, ... | [
"matplotlib.pyplot.title",
"numpy.resize",
"matplotlib.pyplot.clf",
"pydmd.DMD",
"numpy.shape",
"pydmd.MrDMD",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.exp",
"numpy.meshgrid",
"numpy.random.randn",
"numpy.power",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"numpy.real",
"mat... | [((19, 43), 'matplotlib.use', 'matplotlib.use', (['"""Qt4Agg"""'], {}), "('Qt4Agg')\n", (33, 43), False, 'import matplotlib\n'), ((1456, 1480), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(80)'], {}), '(-10, 10, 80)\n', (1467, 1480), True, 'import numpy as np\n'), ((1486, 1510), 'numpy.linspace', 'np.linspace'... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import random
import uuid
import scipy.stats as stat
from math import log, gamma, exp, pi, sqrt, erf, atan
from scipy.special import gammainc
from scipy.interpolate import interp1d
import sys
def Exponential_rate(t,rate, alpha):
return rate... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.yscale",
"numpy.sum",
"numpy.isnan",
"scipy.stats.cauchy.pdf",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.arange",
"numpy.product",
"numpy.exp",
"numpy.mean",
"scipy.interpolate.interp1d",
"scipy.stats.cauchy.fit",
"scipy.stats.... | [((704, 729), 'scipy.special.gammainc', 'gammainc', (['alpha', '(beta * t)'], {}), '(alpha, beta * t)\n', (712, 729), False, 'from scipy.special import gammainc\n'), ((34210, 34233), 'numpy.random.randint', 'np.random.randint', (['(0)', 'L'], {}), '(0, L)\n', (34227, 34233), True, 'import numpy as np\n'), ((34451, 3447... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.