code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#!/usr/bin/env python3
# pyEZmock.py: this file is part of the pyEZmock package.
#
# pyEZmock: Python wrapper of Effective Zel'dovich approximation mock (EZmock).
#
# Github repository:
# https://github.com/cheng-zhao/pyEZmock
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charg... | [
"copy.deepcopy",
"os.remove",
"subprocess.Popen",
"os.path.isdir",
"cosmoEZ.flatLCDM",
"os.mkdir",
"glob.glob",
"numpy.ceil",
"matplotlib.pyplot.savefig",
"os.rename",
"os.access",
"os.path.isfile",
"os.path.abspath",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.figure",
"js... | [((18415, 18441), 'copy.deepcopy', 'copy.deepcopy', (['self._param'], {}), '(self._param)\n', (18428, 18441), False, 'import copy\n'), ((20269, 20291), 'os.path.isfile', 'os.path.isfile', (['script'], {}), '(script)\n', (20283, 20291), False, 'import os\n'), ((26004, 26036), 'matplotlib.pyplot.figure', 'plt.figure', ([... |
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics.classification import accuracy_score, f1_score
def prediction_score(train_X, train_y, test_X, test_y, metric, model):
# if the train labels are always the same
value... | [
"numpy.ones_like",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.classification.f1_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.classification.accuracy_score"
] | [((1018, 1045), 'sklearn.metrics.classification.f1_score', 'f1_score', (['test_y', 'test_pred'], {}), '(test_y, test_pred)\n', (1026, 1045), False, 'from sklearn.metrics.classification import accuracy_score, f1_score\n'), ((479, 499), 'numpy.ones_like', 'np.ones_like', (['test_y'], {}), '(test_y)\n', (491, 499), True, ... |
# -*- coding: utf-8 -*-
# Requires PIL (pillow) and NumPy
# Copyright (C) <NAME>, 2016
# License: MIT
import os
import json
import codecs
from PIL import Image
from io import BytesIO
import numpy as np
class Hexagram(object):
"""
Generate and write a hexagram to PNG
Input is an iterable of six binary di... | [
"os.path.exists",
"PIL.Image.fromarray",
"numpy.ones",
"os.makedirs",
"os.path.join",
"io.BytesIO",
"numpy.zeros",
"numpy.vstack",
"codecs.open"
] | [((2132, 2152), 'numpy.vstack', 'np.vstack', (['container'], {}), '(container)\n', (2141, 2152), True, 'import numpy as np\n'), ((2440, 2471), 'PIL.Image.fromarray', 'Image.fromarray', (['self.generated'], {}), '(self.generated)\n', (2455, 2471), False, 'from PIL import Image\n'), ((2629, 2676), 'os.path.join', 'os.pat... |
import numpy as np
class BriansBrain:
def apply(self, current, neighbors):
result = np.zeros_like(current)
sum_one = np.zeros_like(current)
for key in neighbors:
sum_one += (neighbors[key]==1).astype(int)
current_state = current.copy()
zero = (current_state ==0)... | [
"numpy.zeros_like",
"numpy.logical_and"
] | [((97, 119), 'numpy.zeros_like', 'np.zeros_like', (['current'], {}), '(current)\n', (110, 119), True, 'import numpy as np\n'), ((138, 160), 'numpy.zeros_like', 'np.zeros_like', (['current'], {}), '(current)\n', (151, 160), True, 'import numpy as np\n'), ((490, 517), 'numpy.logical_and', 'np.logical_and', (['zero', 'two... |
import numpy as np
def count(LM):
co = 0
if LM.shape[0]>2:
index = np.argwhere(LM==1)[:5]
for it in index:
lm_ = np.delete(LM,it[0],0)
lm_ = np.delete(lm_,it[1]-1,0)
lm_ = np.delete(lm_,it[0],1)
lm = np.delete(lm_,it[1]-1,1)
L... | [
"numpy.array",
"numpy.argwhere",
"numpy.delete"
] | [((1208, 1221), 'numpy.array', 'np.array', (['LMn'], {}), '(LMn)\n', (1216, 1221), True, 'import numpy as np\n'), ((84, 104), 'numpy.argwhere', 'np.argwhere', (['(LM == 1)'], {}), '(LM == 1)\n', (95, 104), True, 'import numpy as np\n'), ((150, 173), 'numpy.delete', 'np.delete', (['LM', 'it[0]', '(0)'], {}), '(LM, it[0]... |
#!/opt/anaconda/envs/env_hazard_index/bin/python
import atexit
import cioppy
ciop = cioppy.Cioppy()
import xarray as xr
import numpy as np
import pandas as pd
import geopandas as gpd
import datetime
import sys
import gdal
from urllib.parse import urlparse
import os
SUCCESS = 0
ERR_RESOLUTION = 10
ERR_STAGEIN = 20
ERR... | [
"gdal.GetDriverByName",
"gdal.ParseCommandLine",
"pandas.to_datetime",
"os.remove",
"gdal.SetConfigOption",
"numpy.exp",
"numpy.empty",
"geopandas.GeoDataFrame",
"atexit.register",
"numpy.ceil",
"gdal.Translate",
"pandas.DatetimeIndex",
"numpy.isnan",
"numpy.vectorize",
"gdal.Open",
"u... | [((85, 100), 'cioppy.Cioppy', 'cioppy.Cioppy', ([], {}), '()\n', (98, 100), False, 'import cioppy\n'), ((854, 873), 'urllib.parse.urlparse', 'urlparse', (['enclosure'], {}), '(enclosure)\n', (862, 873), False, 'from urllib.parse import urlparse\n'), ((2597, 2642), 'numpy.vectorize', 'np.vectorize', (['remove_nan'], {'o... |
import numpy as np
import sys
BEGIN_DEBUG=True
def log(string,filename="log.txt"):
np.set_printoptions(threshold='nan')
if BEGIN_DEBUG == True:
output = sys.stdout
outputfile = open("E:\\"+filename, "a")
sys.stdout = outputfile
print("------------------------");
print(s... | [
"numpy.set_printoptions"
] | [((89, 125), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '"""nan"""'}), "(threshold='nan')\n", (108, 125), True, 'import numpy as np\n')] |
""" Demonstrates how to define a multivariate Gaussian Random Field,
sample a realization and plot it.
"""
import numpy as np
import torch
from meslas.means import LinearMean
from meslas.covariance.spatial_covariance_functions import Matern32
from meslas.covariance.cross_covariances import UniformMixing
from meslas.c... | [
"meslas.means.LinearMean",
"meslas.random_fields.DiscreteGRF.from_model",
"meslas.plotting.plot_grid_values",
"meslas.covariance.spatial_covariance_functions.Matern32",
"numpy.sqrt",
"numpy.array",
"torch.tensor",
"meslas.covariance.heterotopic.FactorCovariance",
"meslas.random_fields.GRF",
"mesla... | [((782, 812), 'meslas.covariance.spatial_covariance_functions.Matern32', 'Matern32', ([], {'lmbda': '(0.1)', 'sigma': '(1.0)'}), '(lmbda=0.1, sigma=1.0)\n', (790, 812), False, 'from meslas.covariance.spatial_covariance_functions import Matern32\n'), ((924, 976), 'meslas.covariance.heterotopic.FactorCovariance', 'Factor... |
import epics
import time
import pylab as P
import os
import matplotlib.pyplot as plt
import numpy
from scipy import signal
import glob
from datetime import datetime
outfname = "/tmp/data.txt"
pwelch_ratio = 8; # to set size of nperseg
def extract_data(datafp, first=0, last=0, filt=1):
cmd = "/usr/local/controls/... | [
"numpy.sqrt",
"numpy.diff",
"matplotlib.pyplot.figure",
"os.system",
"numpy.loadtxt",
"pylab.log",
"glob.glob",
"matplotlib.pyplot.show"
] | [((482, 496), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (491, 496), False, 'import os\n'), ((711, 773), 'glob.glob', 'glob.glob', (["('/data/smurf_data/%s/*/outputs/*.dat*' % '20190215')"], {}), "('/data/smurf_data/%s/*/outputs/*.dat*' % '20190215')\n", (720, 773), False, 'import glob\n'), ((1039, 1063), 'num... |
"""Financial projection for photovailtic system."""
# Utilities
import numpy as np
# Local
from .models import FinancialCalc
# Functions
def financial_calc(energy_by_month, kwh_cost, module, inverter, system):
"""
Returns:
- The month money savings of electrical coute derived of pv system.
-... | [
"numpy.array"
] | [((1651, 1668), 'numpy.array', 'np.array', (['consume'], {}), '(consume)\n', (1659, 1668), True, 'import numpy as np\n'), ((1716, 1730), 'numpy.array', 'np.array', (['cost'], {}), '(cost)\n', (1724, 1730), True, 'import numpy as np\n')] |
# SPDX-FileCopyrightText: : 2017-2020 The PyPSA-Eur Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
# coding: utf-8
"""
Adds extra extendable components to the clustered and simplified network.
Relevant Settings
-----------------
.. code:: yaml
costs:
year:
USD2013_to_EUR2013:
dico... | [
"logging.getLogger",
"numpy.sort",
"pypsa.Network",
"add_electricity.load_costs",
"add_electricity._add_missing_carriers_from_costs",
"add_electricity.add_nice_carrier_names",
"_helpers.mock_snakemake",
"_helpers.configure_logging"
] | [((2666, 2693), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2683, 2693), False, 'import logging\n'), ((2886, 2938), 'add_electricity._add_missing_carriers_from_costs', '_add_missing_carriers_from_costs', (['n', 'costs', 'carriers'], {}), '(n, costs, carriers)\n', (2918, 2938), False, ... |
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# neural network class definition
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, hiddenlayers, outputnodes, learningrate):
# set number of nodes in each input, hidde... | [
"numpy.array",
"numpy.dot",
"numpy.transpose"
] | [((1864, 1922), 'numpy.dot', 'numpy.dot', (['self.who[self.hiddenlayers - 1]', 'hidden_outputs'], {}), '(self.who[self.hiddenlayers - 1], hidden_outputs)\n', (1873, 1922), False, 'import numpy\n'), ((3419, 3454), 'numpy.dot', 'numpy.dot', (['self.who', 'hidden_outputs'], {}), '(self.who, hidden_outputs)\n', (3428, 3454... |
import csv
import cv2
import numpy as np
from keras.models import Model, Sequential
from keras.layers import Input, Convolution2D, Flatten, Dense, Dropout, Lambda, Activation, MaxPooling2D
import matplotlib.pyplot as plt
adjust_angles = [0, 0.25, -0.25]
def load_data():
"""
Load images and angles data collec... | [
"keras.layers.Convolution2D",
"cv2.imread",
"keras.layers.Flatten",
"keras.layers.MaxPooling2D",
"keras.layers.Lambda",
"keras.models.Sequential",
"numpy.array",
"keras.layers.Input",
"keras.layers.Dropout",
"matplotlib.pyplot.figure",
"keras.models.Model",
"keras.layers.Activation",
"cv2.cv... | [((961, 977), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (969, 977), True, 'import numpy as np\n'), ((992, 1014), 'numpy.array', 'np.array', (['measurements'], {}), '(measurements)\n', (1000, 1014), True, 'import numpy as np\n'), ((1476, 1518), 'cv2.resize', 'cv2.resize', (['frame_cropped'], {'dsize': '... |
import numpy as np
import time
nodes = []
class node:
def __init__(self, symbol):
self.symbol = symbol
self.edges = []
self.shortest_distance = float('inf')
self.shortest_path_via = None
nodes.append(self)
def add_edge(self, node, distance):
edge = [node, dist... | [
"numpy.array",
"time.perf_counter"
] | [((2561, 2580), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2578, 2580), False, 'import time\n'), ((2607, 3024), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0], [0, \n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0,\n 0... |
##################################################################
#
# Trap calibration with stage oscillation (by <NAME>)
# Ref: Tolic-Norrelykke et al. (2006)
#
##################################################################
from __future__ import division, print_function, absolute_import
import numpy as ... | [
"numpy.mean",
"numpy.arange",
"numpy.fft.fft",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"nptdms.TdmsFile"
] | [((1934, 1964), 'nptdms.TdmsFile', 'TdmsFile', (["(self.fname + '.tdms')"], {}), "(self.fname + '.tdms')\n", (1942, 1964), False, 'from nptdms import TdmsFile\n'), ((3442, 3464), 'numpy.mean', 'np.mean', (['PSD_X'], {'axis': '(0)'}), '(PSD_X, axis=0)\n', (3449, 3464), True, 'import numpy as np\n'), ((3494, 3516), 'nump... |
"""
These are some scripts used in testing multiple particles.
"""
import time
import datetime
import numpy as np
from particle import Particle
#==============================================================================
def fill_particles(diameter, density, births, lifetime, initial_positions, u0):
# somePart... | [
"numpy.array",
"datetime.timedelta",
"time.time",
"particle.Particle"
] | [((720, 743), 'numpy.array', 'np.array', (['someParticles'], {}), '(someParticles)\n', (728, 743), True, 'import numpy as np\n'), ((799, 834), 'numpy.array', 'np.array', (['[[x0, y] for y in list_y]'], {}), '([[x0, y] for y in list_y])\n', (807, 834), True, 'import numpy as np\n'), ((916, 927), 'time.time', 'time.time'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Library with PME calculation functions, provides utility for Private Equity analysis.
@author: <NAME> (<EMAIL>)
"""
import pandas as pd
import numpy as np
import scipy.optimize
from datetime import date
#Helper functions
def nearest(series, lookup, debug = False):
... | [
"numpy.log",
"datetime.date",
"numpy.timedelta64",
"pandas.concat",
"pandas.to_datetime"
] | [((3929, 3956), 'pandas.to_datetime', 'pd.to_datetime', (['dates_index'], {}), '(dates_index)\n', (3943, 3956), True, 'import pandas as pd\n'), ((7370, 7397), 'pandas.to_datetime', 'pd.to_datetime', (['dates_index'], {}), '(dates_index)\n', (7384, 7397), True, 'import pandas as pd\n'), ((10043, 10058), 'numpy.log', 'np... |
import os
import pickle
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
OUT_PATH = "/Users/lindronics/workspace/4th_year/out/kfold"
final_report = {}
for path, _, files in os.walk(OUT_PATH):
for fname in files:
if fname.endswith(".pickle") and "report" in fname:
... | [
"os.path.join",
"pickle.load",
"numpy.array",
"pprint.pprint",
"os.walk"
] | [((204, 221), 'os.walk', 'os.walk', (['OUT_PATH'], {}), '(OUT_PATH)\n', (211, 221), False, 'import os\n'), ((916, 936), 'pprint.pprint', 'pprint', (['final_report'], {}), '(final_report)\n', (922, 936), False, 'from pprint import pprint\n'), ((394, 408), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (405, 408), F... |
import drawing
import itertools
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d as a3
import matplotlib.animation as animation
class PolyhedronExtension:
@classmethod
def fromBounds(cls, lb, ub):
"""
Return a new Polyhedron representing an n-dimensional box spanni... | [
"numpy.eye",
"numpy.hstack",
"matplotlib.pyplot.gca",
"drawing.draw_convhull",
"numpy.asarray",
"matplotlib.animation.ArtistAnimation",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.cos",
"itertools.izip",
"numpy.sin",
"numpy.zeros_like",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.p... | [((366, 398), 'numpy.asarray', 'np.asarray', (['lb'], {'dtype': 'np.float64'}), '(lb, dtype=np.float64)\n', (376, 398), True, 'import numpy as np\n'), ((412, 444), 'numpy.asarray', 'np.asarray', (['ub'], {'dtype': 'np.float64'}), '(ub, dtype=np.float64)\n', (422, 444), True, 'import numpy as np\n'), ((1693, 1756), 'ite... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from config import params, data, w2v
class RNN(nn.Module):
def __init__(self, params, data):
super(RNN, self).__init__()
sel... | [
"torch.nn.Dropout",
"gensim.models.keyedvectors.KeyedVectors.load_word2vec_format",
"torch.from_numpy",
"numpy.array",
"numpy.zeros",
"numpy.random.uniform",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.GRU"
] | [((1360, 1446), 'torch.nn.Embedding', 'nn.Embedding', (['self.NUM_EMBEDDINGS', 'self.WORD_DIM'], {'padding_idx': '(self.VOCAB_SIZE + 1)'}), '(self.NUM_EMBEDDINGS, self.WORD_DIM, padding_idx=self.\n VOCAB_SIZE + 1)\n', (1372, 1446), True, 'import torch.nn as nn\n'), ((1577, 1704), 'torch.nn.GRU', 'nn.GRU', (['self.WO... |
from datetime import datetime
import os
import math
import logging
import warnings
from visnav.algo.tools import PositioningException
warnings.filterwarnings("ignore", module='quaternion', lineno=21)
import numpy as np
import cv2
import sys
from visnav.render.render import RenderEngine
from visnav.al... | [
"logging.getLogger",
"math.sqrt",
"visnav.algo.keypoint.KeypointAlgo",
"os.path.exists",
"visnav.algo.tools.angle_between_lat_lon_roll",
"os.listdir",
"visnav.missions.rosetta.RosettaSystemModel",
"visnav.render.render.RenderEngine",
"numpy.subtract",
"numpy.ones",
"math.degrees",
"numpy.any",... | [((144, 209), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'module': '"""quaternion"""', 'lineno': '(21)'}), "('ignore', module='quaternion', lineno=21)\n", (167, 209), False, 'import warnings\n'), ((451, 478), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (4... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
multiple labels classifier
"""
import nltk
from nltk.stem import WordNetLemmatizer
import zipfile
import pandas as pd
import numpy as np
import pickle
from collections import Counter
import gzip
import random
import sklearn
from wordcloud import WordCloud
import matpl... | [
"sklearn.feature_extraction.text.TfidfTransformer",
"gzip.open",
"matplotlib.pyplot.ylabel",
"nltk.classify.scikitlearn.SklearnClassifier",
"numpy.array",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"pandas.DataFrame",
"random.shuffle",
"sklearn.metrics.precision_recall_fscore_support",
"pickle.lo... | [((8474, 8490), 'random.seed', 'random.seed', (['(777)'], {}), '(777)\n', (8485, 8490), False, 'import random\n'), ((8495, 8515), 'random.shuffle', 'random.shuffle', (['sets'], {}), '(sets)\n', (8509, 8515), False, 'import random\n'), ((10193, 10248), 'numpy.mean', 'np.mean', (['[(tag in genreslist[id]) for id in genre... |
import cv2
import random
import numpy as np
import os
#import redis
#from getfile import get_image_size,get_stride,get_image_path,get_image_bs
import argparse
#path=get_image_path()
#stride=get_stride()
#image_size=get_image_size()
#batch_size=get_image_bs()
def parse_args():
parser=argparse.ArgumentParser(descript... | [
"numpy.asarray",
"numpy.zeros",
"cv2.imread",
"argparse.ArgumentParser"
] | [((288, 336), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""inference"""'}), "(description='inference')\n", (311, 336), False, 'import argparse\n'), ((1298, 1314), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1308, 1314), False, 'import cv2\n'), ((1459, 1510), 'numpy.zeros',... |
import operator, msgpack, nltk, math, sys, os
from nltk.corpus import stopwords
from datetime import datetime
from tqdm import tqdm
from argparse import ArgumentParser
import numpy as np
import dateutil.parser
from utils import settings, liwc_keys, lsm_keys, open_for_write, DEFAULT_TIMEZONE
from normalizer import e... | [
"utils.liwc_keys.index",
"os.listdir",
"nltk.corpus.stopwords.words",
"argparse.ArgumentParser",
"nltk.word_tokenize",
"numpy.average",
"msgpack.packb",
"tqdm.tqdm",
"utils.DEFAULT_TIMEZONE.localize",
"numpy.array",
"sys.exit",
"normalizer.expand_text",
"utils.open_for_write",
"mention_gra... | [((2098, 2124), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (2113, 2124), False, 'from nltk.corpus import stopwords\n'), ((3155, 3171), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (3169, 3171), False, 'from argparse import ArgumentParser\n'), ((5860, 58... |
import pickle
import operator
import numpy as np
import csv
import os.path
with open ('y_test', 'rb') as f:
y_test=pickle.load(f)
dicvocab={}
f=open("data/vocab.csv")
vocab=csv.reader(f)
for word in vocab:
if word[0]!='':
dicvocab[int(word[0])-1]=word[1]
f.close()
label_size=y_test.shape[1]
topics=["/A... | [
"pickle.load",
"csv.reader",
"numpy.argmax"
] | [((176, 189), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (186, 189), False, 'import csv\n'), ((760, 785), 'numpy.argmax', 'np.argmax', (['y_test'], {'axis': '(1)'}), '(y_test, axis=1)\n', (769, 785), True, 'import numpy as np\n'), ((117, 131), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (128, 131), False... |
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
import numpy as np
import warnings
from zipfile import ZipFile, ZIP_DEFLATED
from scipy.ndimage.morphology import distance_transform_edt, binary_fill_holes
from scipy.ndimage.measure... | [
"numpy.sqrt",
"numpy.argsort",
"numpy.sin",
"numpy.arange",
"numpy.isscalar",
"numpy.zeros_like",
"numpy.asarray",
"numpy.max",
"numpy.stack",
"numpy.linspace",
"numpy.empty",
"scipy.ndimage.measurements.find_objects",
"warnings.warn",
"six.moves.map",
"six.moves.zip",
"gputools.OCLPro... | [((2365, 2418), 'gputools.OCLArray.empty', 'OCLArray.empty', (['(a.shape + (n_rays,))'], {'dtype': 'np.float32'}), '(a.shape + (n_rays,), dtype=np.float32)\n', (2379, 2418), False, 'from gputools import OCLProgram, OCLArray, OCLImage\n'), ((2431, 2506), 'gputools.OCLProgram', 'OCLProgram', ([], {'src_str': '_ocl_kernel... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
from astropy import units as u
from astropy.coordinates import Angle
from astropy.io import fits
from astropy.table import Table
from gammapy.maps import MapAxis, MapAxes
from gammapy.utils.array import array_stats_str
fro... | [
"logging.getLogger",
"matplotlib.pyplot.ylabel",
"numpy.nanmin",
"astropy.coordinates.Angle",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"gammapy.utils.scripts.make_path",
"numpy.linspace",
"numpy.nanmax",
"gammapy.utils.gauss.Gauss2DPDF",
"matplotlib.pyplot.ylim",
... | [((516, 543), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (533, 543), False, 'import logging\n'), ((2150, 2162), 'astropy.coordinates.Angle', 'Angle', (['width'], {}), '(width)\n', (2155, 2162), False, 'from astropy.coordinates import Angle\n'), ((2177, 2187), 'astropy.coordinates.Angl... |
import numpy as np
from scipy.sparse.csgraph import connected_components as inner_conn_comp
def dot_matrix(X):
X_norm = X - np.mean(X, axis=0)
X_norm /= np.max(np.linalg.norm(X, axis=1))
return X_norm.dot(X_norm.T)
def connected_components(sym_mat, thresh=1e-4):
binary_mat = sym_mat > sym_mat.max() ... | [
"numpy.abs",
"numpy.mean",
"numpy.log10",
"scipy.sparse.csgraph.connected_components",
"numpy.linalg.norm"
] | [((350, 413), 'scipy.sparse.csgraph.connected_components', 'inner_conn_comp', (['binary_mat'], {'directed': '(False)', 'return_labels': '(True)'}), '(binary_mat, directed=False, return_labels=True)\n', (365, 413), True, 'from scipy.sparse.csgraph import connected_components as inner_conn_comp\n'), ((555, 566), 'numpy.a... |
"""
:author: hxq, shy
"""
import numpy as np
from mindspore import ops
DIV = ops.Div()
def l2_regularizer(input_x, axis=1):
"""
:param input_x:
:param axis:
:return:
"""
return DIV(input_x, ((input_x**2).sum(axis=axis, keepdims=True))**0.5)
def set_rng_seed(seed):
"""
:param seed:
... | [
"mindspore.ops.Div",
"numpy.random.seed"
] | [((78, 87), 'mindspore.ops.Div', 'ops.Div', ([], {}), '()\n', (85, 87), False, 'from mindspore import ops\n'), ((344, 364), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (358, 364), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# This is designed as a reference implementation of the UVHDF5 specification. It shows a conversion of SMA data in the UVFITS format to the UVHDF5 format.
import argparse
parser = argparse.ArgumentParser(description="Convert SMA FITS files into UVHDF5 file format.")
parser.add_argument("FITS", ... | [
"numpy.tile",
"argparse.ArgumentParser",
"numpy.any",
"h5py.File",
"numpy.squeeze",
"astropy.io.fits.open",
"numpy.arange"
] | [((205, 296), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert SMA FITS files into UVHDF5 file format."""'}), "(description=\n 'Convert SMA FITS files into UVHDF5 file format.')\n", (228, 296), False, 'import argparse\n'), ((580, 600), 'astropy.io.fits.open', 'fits.open', (['arg... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import h5py
import collections as cl
import numpy as np
from isce3 import antenna as ant
class AntennaParser:
"""Class for parsing NISAR Antenna HDF5 file.
Parameters
----------
filename : str
filename of HDF5 antenna file.
Attributes
... | [
"numpy.ceil",
"collections.namedtuple",
"h5py.File",
"numpy.linspace",
"numpy.zeros",
"numpy.interp"
] | [((1036, 1093), 'h5py.File', 'h5py.File', (['filename'], {'mode': '"""r"""', 'libver': '"""latest"""', 'swmr': '(True)'}), "(filename, mode='r', libver='latest', swmr=True)\n", (1045, 1093), False, 'import h5py\n'), ((7225, 7287), 'numpy.linspace', 'np.linspace', (['beam_first.angle[0]', 'beam_last.angle[-1]', 'num_ang... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 15:21:31 2019
@author: qinayan
"""
import os
import numpy as np
def find_DEM_bn(eta):
#-------------
# find the boundary index
#-------------
nrows,ncols = eta.shape
eta_vector = eta.flatten()*1.0
validID = np.where(eta_vector>0... | [
"numpy.where",
"os.getcwd",
"os.chdir",
"numpy.array",
"numpy.save"
] | [((1201, 1223), 'numpy.array', 'np.array', (['bn_ID_unique'], {}), '(bn_ID_unique)\n', (1209, 1223), True, 'import numpy as np\n'), ((1244, 1259), 'numpy.array', 'np.array', (['bn_ID'], {}), '(bn_ID)\n', (1252, 1259), True, 'import numpy as np\n'), ((1285, 1305), 'numpy.array', 'np.array', (['ghostbn_ID'], {}), '(ghost... |
import numpy as np
from sklearn.metrics.scorer import _BaseScorer
from solnml.components.utils.constants import CLS_TASKS, IMG_CLS
from solnml.datasets.base_dl_dataset import DLDataset
from solnml.components.evaluators.base_dl_evaluator import get_estimator_with_parameters
from solnml.components.ensemble.dl_ensemble.b... | [
"functools.reduce",
"numpy.array",
"solnml.components.models.img_classification.nn_utils.nn_aug.aug_hp_space.get_test_transforms",
"solnml.components.evaluators.base_dl_evaluator.get_estimator_with_parameters"
] | [((4078, 4098), 'numpy.array', 'np.array', (['final_pred'], {}), '(final_pred)\n', (4086, 4098), True, 'import numpy as np\n'), ((2462, 2580), 'solnml.components.evaluators.base_dl_evaluator.get_estimator_with_parameters', 'get_estimator_with_parameters', (['self.task_type', 'config', 'self.max_epoch', 'dataset', 'self... |
"""
Created on Tue Jul 28 12:19:11 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
import time
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPoo... | [
"horovod.tensorflow.keras.size",
"tensorflow.keras.layers.BatchNormalization",
"horovod.tensorflow.keras.callbacks.MetricAverageCallback",
"horovod.tensorflow.keras.callbacks.LearningRateWarmupCallback",
"horovod.tensorflow.keras.init",
"horovod.tensorflow.keras.rank",
"numpy.mean",
"tensorflow.keras.... | [((1339, 1349), 'horovod.tensorflow.keras.init', 'hvd.init', ([], {}), '()\n', (1347, 1349), True, 'import horovod.tensorflow.keras as hvd\n'), ((1432, 1483), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (1476, 1483), True, 'im... |
from skillmodels.estimation.parse_params import parse_params
from skillmodels.estimation.parse_params import restore_unestimated_quantities
import numpy as np
from skillmodels.fast_routines.kalman_filters import normal_unscented_predict
from skillmodels.fast_routines.kalman_filters import sqrt_unscented_predict
from sk... | [
"skillmodels.fast_routines.kalman_filters.sqrt_unscented_predict",
"skillmodels.estimation.parse_params.restore_unestimated_quantities",
"skillmodels.fast_routines.kalman_filters.sqrt_probit_update",
"numpy.log",
"skillmodels.fast_routines.kalman_filters.normal_unscented_predict",
"skillmodels.fast_routin... | [((2098, 2144), 'skillmodels.estimation.parse_params.restore_unestimated_quantities', 'restore_unestimated_quantities', ([], {}), '(**restore_args)\n', (2128, 2144), False, 'from skillmodels.estimation.parse_params import restore_unestimated_quantities\n'), ((2149, 2190), 'skillmodels.estimation.parse_params.parse_para... |
import numpy as np
import math
# Convert point-spread function to optical transfer function
def psf2otf(psf, outSize=None):
# Prepare psf for conversion
data = prepare_psf(psf, outSize)
# Compute the OTF
otf = np.fft.fftn(data)
return np.complex64(otf)
def prepare_psf(psf, outSize=None, dtype=None):
if ... | [
"numpy.roll",
"numpy.int32",
"numpy.fft.fftn",
"numpy.zeros",
"numpy.float32",
"numpy.complex64"
] | [((220, 237), 'numpy.fft.fftn', 'np.fft.fftn', (['data'], {}), '(data)\n', (231, 237), True, 'import numpy as np\n'), ((248, 265), 'numpy.complex64', 'np.complex64', (['otf'], {}), '(otf)\n', (260, 265), True, 'import numpy as np\n'), ((361, 376), 'numpy.float32', 'np.float32', (['psf'], {}), '(psf)\n', (371, 376), Tru... |
import matplotlib.pyplot as plt
import mxnet as mx
import numpy as np
from mxnet import autograd
from NLP.src.training import utils
def train(train_data, model, loss, epochs, batch_size,
context, trainer, freeze_embedding=False):
"""
Train an RNN model, given the input list
param train_data: tr... | [
"mxnet.nd.sum",
"matplotlib.pyplot.grid",
"mxnet.autograd.record",
"NLP.src.training.utils.get_batch",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.arange"
] | [((1810, 1820), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1818, 1820), True, 'import matplotlib.pyplot as plt\n'), ((1825, 1845), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (1835, 1845), True, 'import matplotlib.pyplot as plt\n'), ((1850, 1868), 'matplotlib.pyplot.y... |
#%% [markdown]
# # Contrastive Hebbian Learning
#
# Contrastive Hebbian Learning (CHL) is an algorithm that can be used to perform supervised learning in a neural network. It unites the power of backpropagation with the plausibility of Hebbian learning, and is thus a favorite of researchers in computational neuroscien... | [
"matplotlib.pyplot.imshow",
"numpy.copy",
"matplotlib.pyplot.ylabel",
"numpy.random.random",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.exp",
"numpy.sum",
"numpy.zeros",
"numpy.array",
"numpy.random.seed",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots",
"numpy.ar... | [((7251, 7268), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (7265, 7268), True, 'import numpy as np\n'), ((7276, 7299), 'numpy.zeros', 'np.zeros', (['(1, n_inputs)'], {}), '((1, n_inputs))\n', (7284, 7299), True, 'import numpy as np\n'), ((7358, 7381), 'numpy.zeros', 'np.zeros', (['(1, n_hidden)'], {... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 16:23:57 2019
@author: hitansh
"""
import numpy as np
import os
import sys
# import tarfile
import tensorflow as tf
# import zipfile
# from distutils.version import StrictVersion
# from collections import defaultdict
# from io import StringIO
# f... | [
"numpy.uint8",
"tensorflow.gfile.GFile",
"sys.path.append",
"os.walk",
"tensorflow.Graph",
"os.path.exists",
"tensorflow.Session",
"tensorflow.GraphDef",
"os.mkdir",
"tensorflow.get_default_graph",
"object_detection.utils.label_map_util.create_category_index_from_labelmap",
"tensorflow.import_... | [((587, 608), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (602, 608), False, 'import sys\n'), ((1176, 1237), 'os.chdir', 'os.chdir', (['"""../../../data/TensorFlow/workspace/training_demo/"""'], {}), "('../../../data/TensorFlow/workspace/training_demo/')\n", (1184, 1237), False, 'import os\n')... |
"""
Multi-node example (GPU)
"""
import os
import numpy as np
import torch
from test_tube import HyperOptArgumentParser, Experiment
from pytorch_lightning import Trainer
from examples.new_project_templates.lightning_module_template import LightningTemplateModel
SEED = 2334
torch.manual_seed(SEED)
np.random.seed(SEED)... | [
"torch.manual_seed",
"os.path.join",
"os.path.realpath",
"examples.new_project_templates.lightning_module_template.LightningTemplateModel.add_model_specific_args",
"pytorch_lightning.Trainer",
"numpy.random.seed",
"test_tube.Experiment",
"test_tube.HyperOptArgumentParser",
"examples.new_project_temp... | [((276, 299), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (293, 299), False, 'import torch\n'), ((300, 320), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (314, 320), True, 'import numpy as np\n'), ((546, 577), 'examples.new_project_templates.lightning_module_template.Ligh... |
import numpy as np
import multiprocessing
OPTIMAL_CHUNK_SIZE_EFAST = 50
get_chunk_size_eFAST = lambda num_params: min(OPTIMAL_CHUNK_SIZE_EFAST, num_params)
def random_samples(iterations, num_params, seed=None):
"""Random standard uniform sampling for all iterations and parameters with an option of fixing random ... | [
"numpy.tile",
"numpy.ceil",
"numpy.random.rand",
"numpy.ones",
"numpy.sin",
"numpy.floor",
"numpy.fill_diagonal",
"numpy.kron",
"numpy.linspace",
"numpy.zeros",
"numpy.random.seed",
"multiprocessing.Pool",
"numpy.random.uniform",
"numpy.vstack",
"numpy.full",
"numpy.transpose",
"nump... | [((627, 647), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (641, 647), True, 'import numpy as np\n'), ((662, 700), 'numpy.random.rand', 'np.random.rand', (['iterations', 'num_params'], {}), '(iterations, num_params)\n', (676, 700), True, 'import numpy as np\n'), ((1521, 1541), 'numpy.random.seed',... |
# MIT Licence
# Methods to predict the SSIM, taken from
# https://github.com/Po-Hsun-Su/pytorch-ssim/blob/master/pytorch_ssim/__init__.py
from math import exp
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def gaussian(window_size, sigma):
gauss = torch.Tensor(
[
... | [
"torch.nn.functional.conv2d",
"numpy.transpose",
"cv2.imread",
"numpy.expand_dims"
] | [((884, 948), 'torch.nn.functional.conv2d', 'F.conv2d', (['img1', 'window'], {'padding': '(window_size // 2)', 'groups': 'channel'}), '(img1, window, padding=window_size // 2, groups=channel)\n', (892, 948), True, 'import torch.nn.functional as F\n'), ((959, 1023), 'torch.nn.functional.conv2d', 'F.conv2d', (['img2', 'w... |
'''
XlPy/Link_Finder/search/single
______________________________
Checks if a sequenced peptide matches back to an unsequenced,
theoretical peptide massfingerprint.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.... | [
"collections.namedtuple",
"xldlib.utils.iterables.num_product",
"numpy.where",
"xldlib.chemical.Molecule",
"numpy.array",
"models.data.unpack_data.__get__",
"copy.deepcopy",
"xlpy.tools.mass.PrecursorMass.calculate_mass.__get__"
] | [((1147, 1189), 'collections.namedtuple', 'namedtuple', (['"""MS1"""', '"""ends basemass mass mz"""'], {}), "('MS1', 'ends basemass mass mz')\n", (1157, 1189), False, 'from collections import namedtuple\n'), ((1202, 1259), 'collections.namedtuple', 'namedtuple', (['"""Search"""', '"""ends basemass mass mz ppm exper z""... |
import numpy as np
def sqsum(a):
"""
Calculate the squared sum of a list
Parameters
----------
a: list
the list of numbers to be calculated
Return
------
float
the squared sum
Examples
--------
>>> a = [1, 2, 3]
>>> sqsum(a)
14
"""
a... | [
"numpy.array",
"numpy.sum"
] | [((323, 334), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (331, 334), True, 'import numpy as np\n'), ((346, 360), 'numpy.sum', 'np.sum', (['(a ** 2)'], {}), '(a ** 2)\n', (352, 360), True, 'import numpy as np\n')] |
from __future__ import print_function
import numpy
import collections
from typing import Mapping, Union, Sequence, MutableSequence, Tuple, Any
from typing import Optional, Callable, TypeVar, Iterable, List, cast
InitialState = Union[MutableSequence[complex], int, numpy.ndarray]
# This should be Anything subscriptable... | [
"numpy.array",
"numpy.zeros",
"typing.TypeVar"
] | [((382, 394), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (389, 394), False, 'from typing import Optional, Callable, TypeVar, Iterable, List, cast\n'), ((5447, 5500), 'numpy.zeros', 'numpy.zeros', (['(2 ** n, 2 ** n)'], {'dtype': 'numpy.complex128'}), '((2 ** n, 2 ** n), dtype=numpy.complex128)\n', (5458... |
from __future__ import print_function
import argparse
import os
# from torchvision.datasets import ImageFolder
import myDataset
import networks
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from PIL imp... | [
"torch.nn.CrossEntropyLoss",
"torch.nn.L1Loss",
"torch.max",
"torch.cuda.is_available",
"torch.sum",
"os.path.exists",
"argparse.ArgumentParser",
"networks.init_weights",
"numpy.random.seed",
"torchvision.transforms.ToTensor",
"torch.autograd.Variable",
"torchvision.transforms.RandomHorizontal... | [((530, 585), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch NI vs CG"""'}), "(description='PyTorch NI vs CG')\n", (553, 585), False, 'import argparse\n'), ((2585, 2610), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (2599, 2610), True, 'import nump... |
import os
import numpy as np
from numpy.lib.stride_tricks import as_strided
import nibabel as nib
def nib_load(file_name):
proxy = nib.load(file_name)
data = proxy.get_data().astype('float32')
proxy.uncache()
return data
def crop(x, ksize, stride=3):
shape = (np.array(x.shape[:3]) - ksize)/stride ... | [
"nibabel.load",
"os.path.join",
"numpy.lib.stride_tricks.as_strided",
"numpy.array",
"numpy.pad"
] | [((765, 801), 'os.path.join', 'os.path.join', (['root', 'subj', "(name + '_')"], {}), "(root, subj, name + '_')\n", (777, 801), False, 'import os\n'), ((945, 1006), 'numpy.pad', 'np.pad', (['x0', '((0, 0), (0, 0), (0, 1), (0, 0))'], {'mode': '"""constant"""'}), "(x0, ((0, 0), (0, 0), (0, 1), (0, 0)), mode='constant')\n... |
# Turn image to animated gif using 3 animation modes: "explode" "melt" "diffuse"
import PIL.Image as Image
import numpy as np
#------------------input parameterss---------------------------------------------------------------
InputImage="Input.jpg" # Input image patg
OutputGifName="Out.gif" # Output gif file ... | [
"numpy.random.randint",
"PIL.Image.open",
"numpy.random.rand",
"PIL.Image.fromarray"
] | [((703, 725), 'PIL.Image.open', 'Image.open', (['InputImage'], {}), '(InputImage)\n', (713, 725), True, 'import PIL.Image as Image\n'), ((1128, 1148), 'numpy.random.randint', 'np.random.randint', (['w'], {}), '(w)\n', (1145, 1148), True, 'import numpy as np\n'), ((1166, 1186), 'numpy.random.randint', 'np.random.randint... |
"""Bounds module for functions related to coordinate bounds."""
import collections
from typing import Dict, List, Optional, Tuple
import cf_xarray as cfxr # noqa: F401
import numpy as np
import xarray as xr
from typing_extensions import Literal, get_args
from xcdat.logger import setup_custom_logger
logger = setup_c... | [
"numpy.insert",
"numpy.clip",
"typing_extensions.get_args",
"xarray.register_dataset_accessor",
"numpy.append",
"numpy.array",
"xarray.DataArray",
"xcdat.logger.setup_custom_logger"
] | [((313, 340), 'xcdat.logger.setup_custom_logger', 'setup_custom_logger', (['"""root"""'], {}), "('root')\n", (332, 340), False, 'from xcdat.logger import setup_custom_logger\n'), ((509, 524), 'typing_extensions.get_args', 'get_args', (['Coord'], {}), '(Coord)\n', (517, 524), False, 'from typing_extensions import Litera... |
import numpy as np
from scipy.io import loadmat
from utils.dataset import load_label_files, load_labels, load_weights
from data_loader.util import load_challenge_data
import torch
import torch.nn.functional as F
class ChallengeMetric():
def __init__(self, input_directory, alphas):
# challengeMetric init... | [
"data_loader.util.load_challenge_data",
"numpy.all",
"utils.dataset.load_label_files",
"numpy.nansum",
"torch.load",
"scipy.io.loadmat",
"numpy.any",
"numpy.ix_",
"numpy.array",
"numpy.zeros",
"numpy.nanmean",
"numpy.isnan",
"utils.dataset.load_weights",
"numpy.sum",
"numpy.shape",
"ut... | [((8954, 8981), 'utils.dataset.load_label_files', 'load_label_files', (['label_dir'], {}), '(label_dir)\n', (8970, 8981), False, 'from utils.dataset import load_label_files, load_labels, load_weights\n'), ((9054, 9112), 'utils.dataset.load_labels', 'load_labels', (['label_files', 'normal_class', 'equivalent_classes'], ... |
# coding=utf8
import numpy as np
class LabelSpreading:
def __init__(self, alpha=0.2, max_iter=30, tol=1e-3):
"""
:param alpha: clamping factor between (0,1)
:param max_iter: maximum number of iterations
:param tol: convergence tolerance
"""
self.alpha = alpha
... | [
"numpy.abs",
"numpy.power",
"numpy.where",
"numpy.argmax",
"numpy.any",
"numpy.diag",
"numpy.sum",
"numpy.dot"
] | [((1043, 1060), 'numpy.sum', 'np.sum', (['w'], {'axis': '(1)'}), '(w, axis=1)\n', (1049, 1060), True, 'import numpy as np\n'), ((1091, 1115), 'numpy.power', 'np.power', (['d', '(-1 / 2.0)', 'd'], {}), '(d, -1 / 2.0, d)\n', (1099, 1115), True, 'import numpy as np\n'), ((1127, 1137), 'numpy.diag', 'np.diag', (['d'], {}),... |
#!/usr/bin/env python
from matplotlib import pyplot as P
import numpy as N
from load import ROOT as R
import gna.constructors as C
import pytest
@pytest.mark.parametrize('edges', [N.linspace(0.0, 10.0, 11), N.geomspace(0.1, 1000.0, 5)])
def test_histedges_v01(edges):
centers = 0.5*(edges[1:]+edges[:-1])
width... | [
"gna.constructors.Histogram",
"numpy.geomspace",
"load.ROOT.HistEdges",
"numpy.linspace",
"numpy.arange"
] | [((363, 387), 'numpy.arange', 'N.arange', (['(edges.size - 1)'], {}), '(edges.size - 1)\n', (371, 387), True, 'import numpy as N\n'), ((398, 422), 'gna.constructors.Histogram', 'C.Histogram', (['edges', 'data'], {}), '(edges, data)\n', (409, 422), True, 'import gna.constructors as C\n'), ((433, 446), 'load.ROOT.HistEdg... |
# 15/05/2020, <NAME>, Edinburgh
# Tidying up codes that plot rho/Paulin-Henriksson stats
# by having some of the functions in here.
import numpy as np
from scipy.stats import binned_statistic_2d
from astropy.io import fits
import time
import glob
def interpolate2D(X, Y, grid): #(It's linear) ... | [
"numpy.sqrt",
"astropy.io.fits.open",
"numpy.cov",
"scipy.stats.binned_statistic_2d",
"glob.glob",
"numpy.average",
"numpy.interp",
"numpy.std",
"time.time",
"numpy.intersect1d",
"numpy.ones_like",
"numpy.logical_and",
"numpy.append",
"numpy.sum",
"numpy.zeros",
"numpy.random.randint",... | [((1190, 1221), 'numpy.intersect1d', 'np.intersect1d', (['idx_ra', 'idx_dec'], {}), '(idx_ra, idx_dec)\n', (1204, 1221), True, 'import numpy as np\n'), ((1431, 1498), 'scipy.stats.binned_statistic_2d', 'binned_statistic_2d', (['Y', 'X', '(Q * w)'], {'statistic': '"""sum"""', 'bins': 'num_XY_bins'}), "(Y, X, Q * w, stat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : basic_utils.py
# Author : <NAME>, <NAME>
# Email : <EMAIL>, <EMAIL>
# Date : 09.08.2019
# Last Modified Date: 15.08.2019
# Last Modified By : Chi Han, Jiayuan Mao
#
# This file is part of the VCML codebase
# Distri... | [
"numpy.array",
"sys.getsizeof"
] | [((2502, 2520), 'sys.getsizeof', 'sys.getsizeof', (['obj'], {}), '(obj)\n', (2515, 2520), False, 'import sys\n'), ((634, 650), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (642, 650), True, 'import numpy as np\n')] |
import gym
import pybulletgym
from gym import Wrapper,spaces
from torch.optim import Adam
from nn_builder.pytorch.NN import NN
import torch.nn.functional as F
import random
import numpy as np
from stable_baselines3 import SAC
import torch
from torch import nn
class DIAYN_Skill_Wrapper(Wrapper):
def __init__(self, ... | [
"torch.nn.functional.softmax",
"torch.nn.CrossEntropyLoss",
"numpy.log",
"torch.Tensor",
"gym.spaces.Box",
"numpy.array",
"nn_builder.pytorch.NN.NN",
"gym.Wrapper.__init__",
"random.randint"
] | [((346, 373), 'gym.Wrapper.__init__', 'Wrapper.__init__', (['self', 'env'], {}), '(self, env)\n', (362, 373), False, 'from gym import Wrapper, spaces\n'), ((577, 735), 'nn_builder.pytorch.NN.NN', 'NN', ([], {'input_dim': 'self.state_size', 'layers_info': '[self.hidden_size, self.hidden_size, self.num_skills]', 'hidden_... |
from unittest import TestCase
import unittest
from equadratures import *
import numpy as np
from copy import deepcopy
def model(x):
return x[0]**2 + x[1]**3 - x[0]*x[1]**2
class TestF(TestCase):
def test_tensor_grid_with_nans(self):
# Without Nans!
param = Parameter(distribution='uniform', lo... | [
"unittest.main",
"numpy.testing.assert_almost_equal",
"numpy.asarray",
"copy.deepcopy"
] | [((1472, 1487), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1485, 1487), False, 'import unittest\n'), ((718, 739), 'copy.deepcopy', 'deepcopy', (['model_evals'], {}), '(model_evals)\n', (726, 739), False, 'from copy import deepcopy\n'), ((772, 797), 'numpy.asarray', 'np.asarray', (['[1, 3, 9, 13]'], {}), '([1,... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: <NAME>
## ECE Department, Rutgers University
## Email: <EMAIL>
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##+++++++... | [
"numpy.abs",
"numpy.allclose",
"numpy.fmax",
"torch.LongTensor",
"torch.Tensor",
"nose.runmodule",
"torch.cuda.DoubleTensor",
"encoding.functions.NonMaxSuppression",
"torch.ByteTensor",
"torch.autograd.gradcheck"
] | [((620, 663), 'numpy.allclose', 'np.allclose', (['npa', 'npb'], {'rtol': 'rtol', 'atol': 'atol'}), '(npa, npb, rtol=rtol, atol=atol)\n', (631, 663), True, 'import numpy as np\n'), ((1197, 1263), 'torch.autograd.gradcheck', 'gradcheck', (['encoding.functions.aggregate', 'input'], {'eps': 'EPS', 'atol': 'ATOL'}), '(encod... |
from openwater.split import split_time_series
import numpy as np
def test_create_split_windows():
grp = {
'DummyModel':{
'inputs':np.zeros((1,1,10000))
}
}
BREAKS = [
[100,1000,5000],
[0,100,1000,5000],
[100,1000,5000,10000],
[0,100,1000,5000,1... | [
"numpy.zeros",
"openwater.split.split_time_series"
] | [((846, 878), 'openwater.split.split_time_series', 'split_time_series', (['grp', '(11)', 'None'], {}), '(grp, 11, None)\n', (863, 878), False, 'from openwater.split import split_time_series\n'), ((377, 411), 'openwater.split.split_time_series', 'split_time_series', (['grp', '(10)', 'breaks'], {}), '(grp, 10, breaks)\n'... |
from server.models.postgis.mapping_issues import MappingIssueCategory
from server.models.postgis.task import TaskMappingIssue, TaskHistory, Task
from server.models.postgis.user import User
from server.models.postgis.project import Project
from server.models.postgis.statuses import TaskStatus
from server.models.dtos.map... | [
"server.models.postgis.task.Task.get_all_tasks",
"server.models.postgis.mapping_issues.MappingIssueCategory.get_by_id",
"server.services.stats_service.StatsService.get_user_contributions",
"server.models.postgis.mapping_issues.MappingIssueCategory.create_from_dto",
"numpy.zeros",
"copy.deepcopy",
"serve... | [((789, 832), 'server.models.postgis.mapping_issues.MappingIssueCategory.get_by_id', 'MappingIssueCategory.get_by_id', (['category_id'], {}), '(category_id)\n', (819, 832), False, 'from server.models.postgis.mapping_issues import MappingIssueCategory\n'), ((1387, 1437), 'server.models.postgis.mapping_issues.MappingIssu... |
#!/usr/bin/env python3
'''A reference implementation of Bloom filter-based Iris-Code indexing.'''
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2017 Hochschule Darmstadt"
__license__ = "License Agreement provided by Hochschule Darmstadt(https://github.com/dasec/bloom-filter-iris-indexing/blob/master/hda-license... | [
"numpy.mean",
"copy.deepcopy",
"argparse.ArgumentParser",
"timeit.default_timer",
"math.log",
"numpy.array",
"numpy.std",
"operator.itemgetter"
] | [((547, 624), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Bloom filter-based Iris-Code indexing."""'}), "(description='Bloom filter-based Iris-Code indexing.')\n", (570, 624), False, 'import argparse\n'), ((11022, 11029), 'timeit.default_timer', 'timer', ([], {}), '()\n', (11027, 1102... |
# coding: utf-8
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
__all__ = ['Ackley','Sphere','Rosenbrock','Beale','GoldsteinPrice','Booth',
'BukinN6','Matyas','LeviN13','ThreeHumpCamel','Easom','Eggholder',
'McCormick','Schaffer... | [
"numpy.sqrt",
"numpy.array",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.close",
"numpy.exp",
"os.path.isdir",
"os.mkdir",
"numpy.meshgrid",
"numpy.random.normal",
"numpy.tile",
"matplotlib.pyplot.savefig",
"numpy.floor",
"numpy.square",
"numpy.cos",
"mpl_toolkits.mplot3d.Axes3D",
... | [((1464, 1497), 'numpy.array', 'np.array', (['([0] * self.variable_num)'], {}), '([0] * self.variable_num)\n', (1472, 1497), True, 'import numpy as np\n'), ((1528, 1561), 'numpy.array', 'np.array', (['([0] * self.variable_num)'], {}), '([0] * self.variable_num)\n', (1536, 1561), True, 'import numpy as np\n'), ((1592, 1... |
import json
import wml_utils as wmlu
import numpy as np
import os
import cv2 as cv
import sys
import random
from iotoolkit.labelme_toolkit import get_labels_and_bboxes
def get_files(dir_path, sub_dir_name):
img_dir = os.path.join(dir_path, sub_dir_name,'images')
label_dir = os.path.join(dir_path, sub_dir_name... | [
"wml_utils.recurse_get_filepath_in_dir",
"img_utils.imread",
"numpy.array",
"matplotlib.pyplot.imshow",
"os.path.exists",
"numpy.reshape",
"object_detection_tools.visualization.draw_bboxes_and_maskv2",
"numpy.max",
"numpy.stack",
"numpy.min",
"sys.stdout.flush",
"numpy.maximum",
"wml_utils.h... | [((223, 269), 'os.path.join', 'os.path.join', (['dir_path', 'sub_dir_name', '"""images"""'], {}), "(dir_path, sub_dir_name, 'images')\n", (235, 269), False, 'import os\n'), ((285, 341), 'os.path.join', 'os.path.join', (['dir_path', 'sub_dir_name', '"""v2.0"""', '"""polygons"""'], {}), "(dir_path, sub_dir_name, 'v2.0', ... |
import gym
import random
import torch
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
#%matplotlib inline
from unityagents import UnityEnvironment
import numpy as np
import argparse
import sys
env = UnityEnvironment(file_name="Banana_Windows_x86_64/Banana.exe")
# get the default brai... | [
"numpy.mean",
"collections.deque",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"dqn_agent.Agent",
"unityagents.UnityEnvironment",
"matplotlib.pyplot.figure",
"sys.exit",
"matplotlib.pyplot.show"
] | [((234, 296), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': '"""Banana_Windows_x86_64/Banana.exe"""'}), "(file_name='Banana_Windows_x86_64/Banana.exe')\n", (250, 296), False, 'from unityagents import UnityEnvironment\n'), ((1451, 1468), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '... |
from io import StringIO
from collections import OrderedDict
import numpy as np
import scipy.linalg as sl
import pandas as pd
import pytest
import matmodlab2 as mml
runid = 'simulation_output'
def compare_dataframes(frame1, frame2, tol=1.0e-12):
head1 = frame1.keys()
head2 = frame2.keys()
passed = True
... | [
"numpy.allclose",
"matmodlab2.MaterialPointSimulator",
"pandas.read_csv",
"pytest.mark.skip",
"numpy.log",
"matmodlab2.ElasticMaterial",
"pytest.mark.parametrize"
] | [((668, 686), 'pytest.mark.skip', 'pytest.mark.skip', ([], {}), '()\n', (684, 686), False, 'import pytest\n'), ((708, 768), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""stretch"""', '[1.5, 1.001, 0.999, 0.5]'], {}), "('stretch', [1.5, 1.001, 0.999, 0.5])\n", (731, 768), False, 'import pytest\n'), ((770, ... |
import numpy as np
import scipy.linalg
from numpy.linalg import cond, norm
from scipy.linalg import toeplitz
from scipy.linalg import solve_triangular
import time
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
PI = np.pi
CRED = '\033[91m'
CGREEN = '\033[32m'
CEND = ... | [
"numpy.linalg.cond",
"seaborn.set_style",
"numpy.linalg.norm",
"numpy.arange",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.matmul",
"scipy.linalg.solve_triangular",
"numpy.unravel_index",
"pandas.DataFrame",
"numpy.tri",
"numpy.abs",
"numpy.eye",
"matplotlib.pyplot.savefig"... | [((237, 262), 'seaborn.set_style', 'sns.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (250, 262), True, 'import seaborn as sns\n'), ((13615, 13641), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (13625, 13641), True, 'import matplotlib.pyplot as plt\n'), ((13641,... |
"""siunit - A module to support dimensioned arithmetic using the SI system.
Dimensioned numbers are instances of siunit.Dn(). Arithmetic between Dn's
with incompatible units raises TypeError. Arithmetic between Dn's with
compatible units produces a result with appropriate units. For example, ::
>>> m=Dn('3kg')
... | [
"numpy.array",
"math.sqrt"
] | [((30602, 30619), 'math.sqrt', 'math_sqrt', (['self.n'], {}), '(self.n)\n', (30611, 30619), True, 'from math import sqrt as math_sqrt\n'), ((25248, 25258), 'numpy.array', 'array', (['num'], {}), '(num)\n', (25253, 25258), False, 'from numpy import array\n')] |
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee <EMAIL> #
# #
# version 1.0 ... | [
"matplotlib.pyplot.gca",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.sin",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((1106, 1118), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1116, 1118), True, 'import matplotlib.pyplot as plt\n'), ((1157, 1202), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', '(64)'], {'endpoint': '(True)'}), '(-np.pi, np.pi, 64, endpoint=True)\n', (1168, 1202), True, 'import numpy as np\n... |
# Copyright (c) 2019 <NAME> (<EMAIL>)
"""
@author: <NAME>
base class for CG models and solvers
"""
import abc
from typing import Iterable
import numpy as np
#from cgmodsel.models.model_base import get_modeltype
from cgmodsel.models.model_pwsl import ModelPWSL
from cgmodsel.models.model_pw import ModelPW
from cgmodsel... | [
"cgmodsel.models.model_pw.ModelPW",
"numpy.prod",
"numpy.sqrt",
"numpy.log",
"numpy.diag",
"numpy.sum",
"numpy.zeros",
"cgmodsel.utils.grp_soft_shrink",
"numpy.empty",
"numpy.isnan",
"cgmodsel.models.model_pwsl.ModelPWSL",
"cgmodsel.utils.l21norm",
"numpy.cumsum"
] | [((955, 970), 'numpy.empty', 'np.empty', (['n_cat'], {}), '(n_cat)\n', (963, 970), True, 'import numpy as np\n'), ((1328, 1348), 'numpy.zeros', 'np.zeros', (['(dim, dim)'], {}), '((dim, dim))\n', (1336, 1348), True, 'import numpy as np\n'), ((1296, 1312), 'numpy.sqrt', 'np.sqrt', (['sigma_r'], {}), '(sigma_r)\n', (1303... |
import numpy as np
from scipy.special import j0 as BesselJ0, j1 as BesselJ1, jn as BesselJ
from scipy.optimize import root
def shoot_S1(central_value: float,
w: float,
R: np.ndarray,
coeffs: np.ndarray,
S_harmonics: np.ndarray = None) -> np.ndarray:
"""
Shoo... | [
"numpy.abs",
"numpy.empty_like",
"numpy.arange"
] | [((779, 795), 'numpy.empty_like', 'np.empty_like', (['R'], {}), '(R)\n', (792, 795), True, 'import numpy as np\n'), ((3829, 3839), 'numpy.abs', 'np.abs', (['S1'], {}), '(S1)\n', (3835, 3839), True, 'import numpy as np\n'), ((1904, 1932), 'numpy.arange', 'np.arange', (['(0)', 'N_harmonics', '(1)'], {}), '(0, N_harmonics... |
from typing import List
from io import BytesIO
import numpy as np
from PIL import Image
from fastapi import FastAPI, Request, File, UploadFile
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.m... | [
"PIL.Image.fromarray",
"fastapi.FastAPI",
"fastapi.responses.StreamingResponse",
"PIL.Image.open",
"io.BytesIO",
"fastapi.templating.Jinja2Templates",
"numpy.array",
"fastapi.staticfiles.StaticFiles",
"fastapi.File"
] | [((304, 313), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (311, 313), False, 'from fastapi import FastAPI, Request, File, UploadFile\n'), ((396, 434), 'fastapi.templating.Jinja2Templates', 'Jinja2Templates', ([], {'directory': '"""templates"""'}), "(directory='templates')\n", (411, 434), False, 'from fastapi.templa... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | [
"numpy.abs",
"qiskit.circuit.QuantumCircuit",
"numpy.conj",
"numpy.conjugate",
"qiskit.circuit.QuantumRegister"
] | [((4755, 4787), 'qiskit.circuit.QuantumRegister', 'QuantumRegister', (['(1)', '"""work_qubit"""'], {}), "(1, 'work_qubit')\n", (4770, 4787), False, 'from qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression\n'), ((4807, 4857), 'qiskit.circuit.QuantumCircuit', 'QuantumCircuit', (['... |
import numpy as np
import cv2
def transform_matrix():
# Define 4 source points
#test1_src = np.float32([[499, 530], [844, 530], [1008, 630], [362, 630]])
straight2_src = np.float32([[557, 475], [729, 475], [961, 630], [345, 630]])
src = straight2_src
# Define 4 destination points
#test1_dst... | [
"cv2.warpPerspective",
"numpy.float32",
"cv2.getPerspectiveTransform"
] | [((184, 244), 'numpy.float32', 'np.float32', (['[[557, 475], [729, 475], [961, 630], [345, 630]]'], {}), '([[557, 475], [729, 475], [961, 630], [345, 630]])\n', (194, 244), True, 'import numpy as np\n'), ((404, 464), 'numpy.float32', 'np.float32', (['[[500, 300], [800, 300], [800, 680], [500, 680]]'], {}), '([[500, 300... |
"""
A collection of PyTorch utility functions and module subclasses
"""
import torch
import torch.nn as nn
import numpy as np
from torch.autograd import grad
from torch.optim.lr_scheduler import _LRScheduler
from torch.distributions import constraints
from torch.distributions.transforms import Transform
_NP_TO_PT = {... | [
"torch.tanh",
"numpy.isclose",
"torch.log",
"torch.eye",
"torch.nn.Parameter",
"torch.autograd.grad",
"torch.finfo",
"torch.distributions.constraints.interval",
"torch.cat"
] | [((1342, 1361), 'numpy.isclose', 'np.isclose', (['vary', '(0)'], {}), '(vary, 0)\n', (1352, 1361), True, 'import numpy as np\n'), ((3316, 3344), 'torch.distributions.constraints.interval', 'constraints.interval', (['(-1)', '(+1)'], {}), '(-1, +1)\n', (3336, 3344), False, 'from torch.distributions import constraints\n')... |
import torch
import torch.nn as nn
import torchvision
import torch.backends.cudnn as cudnn
import torch.optim
import os
import sys
import argparse
import time
import DCE.dce_model
import numpy as np
from torchvision import transforms
from PIL import Image
import glob
import time
from tqdm import tqdm
# os.environ['CUDA... | [
"PIL.Image.open",
"os.listdir",
"torch.load",
"tqdm.tqdm",
"numpy.asarray",
"torch.from_numpy",
"torch.no_grad",
"torchvision.utils.save_image",
"glob.glob"
] | [((418, 440), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (428, 440), False, 'from PIL import Image\n'), ((1129, 1186), 'torchvision.utils.save_image', 'torchvision.utils.save_image', (['enhanced_image', 'result_path'], {}), '(enhanced_image, result_path)\n', (1157, 1186), False, 'import tor... |
import pandas as pd
import numpy as np
import random as rd
class Color_learning:
def __init__(self, feature, labls, entradas, oculta, saida, inst, lr, ephoca, ohl):
self.feature = feature
self.labels = labls
self.input = entradas
self.output = saida
self.hidden = ... | [
"numpy.log",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.dot",
"numpy.vstack",
"numpy.savetxt",
"random.randint"
] | [((4575, 4604), 'numpy.vstack', 'np.vstack', (['[green, red, blue]'], {}), '([green, red, blue])\n', (4584, 4604), True, 'import numpy as np\n'), ((4615, 4655), 'numpy.array', 'np.array', (['([0] * 10 + [1] * 10 + [2] * 10)'], {}), '([0] * 10 + [1] * 10 + [2] * 10)\n', (4623, 4655), True, 'import numpy as np\n'), ((467... |
import csv
from scipy import ndimage
import numpy as np
import cv2
#Reading data from CSV
lines = []
with open('data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
i=0
for line in reader:
if(i==0):
i = i+1
else:
lines.append(li... | [
"keras.layers.Flatten",
"keras.layers.convolutional.Convolution2D",
"cv2.flip",
"keras.layers.pooling.MaxPooling2D",
"keras.layers.Lambda",
"keras.models.Sequential",
"scipy.ndimage.imread",
"numpy.array",
"keras.layers.Cropping2D",
"keras.layers.Dense",
"csv.reader"
] | [((1301, 1327), 'numpy.array', 'np.array', (['augmented_images'], {}), '(augmented_images)\n', (1309, 1327), True, 'import numpy as np\n'), ((1338, 1370), 'numpy.array', 'np.array', (['augmented_measurements'], {}), '(augmented_measurements)\n', (1346, 1370), True, 'import numpy as np\n'), ((1581, 1593), 'keras.models.... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
#########################################################################
# > File Name: get_seqdata.py
# > Author: <NAME>
# > Mail: <EMAIL>
# > Created Time: 2019年03月20日 星期三 00时07分18秒
#########################################################################
from _... | [
"os.listdir",
"os.path.join",
"pickle.load",
"numpy.array",
"cv2.resize",
"numpy.transpose"
] | [((926, 974), 'os.path.join', 'os.path.join', (['self.data_dir', 'self.sample_fs[idx]'], {}), '(self.data_dir, self.sample_fs[idx])\n', (938, 974), False, 'import os\n'), ((790, 810), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (800, 810), False, 'import os\n'), ((1044, 1058), 'pickle.load', 'pickle... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 16:31:04 2019
@author: macfa
"""
import numpy as np
import scipy
import matplotlib.pyplot as plt
import librosa
import soundfile as sf
import os
from config import PARAS
import warnings
warnings.filterwarnings('ignore')
audio_path = '../../100_download/separated_data... | [
"librosa.util.normalize",
"os.makedirs",
"mel_dealer.mel_converter.signal_to_melspec",
"soundfile.write",
"numpy.split",
"mel_dealer.mel_converter.m",
"warnings.filterwarnings",
"os.walk",
"librosa.load"
] | [((239, 272), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (262, 272), False, 'import warnings\n'), ((503, 522), 'os.walk', 'os.walk', (['audio_path'], {}), '(audio_path)\n', (510, 522), False, 'import os\n'), ((766, 805), 'mel_dealer.mel_converter.signal_to_melspec', 'm... |
import numpy as np
import tensorflow as tf
import json
import pickle
import data_utils
import plotting
import model
import utils
from time import time
from eICU_synthetic_dataset_generation import batch_size
from mmd import median_pairwise_distance, mix_rbf_mmd2_and_ratio
tf.logging.set_verbosity(tf.logging.ERROR)
... | [
"utils.rgan_options_parser",
"tensorflow.logging.set_verbosity",
"utils.load_settings_from_file",
"numpy.save",
"plotting.visualise_at_epoch",
"data_utils.get_batch",
"model.train_epoch",
"tensorflow.placeholder",
"tensorflow.Session",
"mmd.mix_rbf_mmd2_and_ratio",
"mmd.median_pairwise_distance"... | [((276, 318), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (300, 318), True, 'import tensorflow as tf\n'), ((402, 429), 'utils.rgan_options_parser', 'utils.rgan_options_parser', ([], {}), '()\n', (427, 429), False, 'import utils\n'), ((680, 723), 'd... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class backWarp(nn.Module):
"""
A class for creating a backwarping object.
This is used for backwarping to an image:
Given optical flow from frame I0 to I1 --> F_0_1 and frame I1,
it generates I0 <-... | [
"torch.nn.functional.grid_sample",
"torch.stack",
"torch.tensor",
"numpy.linspace",
"numpy.arange"
] | [((1976, 2002), 'torch.stack', 'torch.stack', (['(x, y)'], {'dim': '(3)'}), '((x, y), dim=3)\n', (1987, 2002), False, 'import torch\n'), ((2075, 2140), 'torch.nn.functional.grid_sample', 'torch.nn.functional.grid_sample', (['img', 'grid'], {'padding_mode': '"""border"""'}), "(img, grid, padding_mode='border')\n", (2106... |
import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
model = Sequential()
model.add(Dense(units=50, input_dim=1, activation='relu'))
model.add(Dense(units=50, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"keras.models.Sequential",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"matplotlib.pyplot.scatter",
"keras.layers.Dense",
"matplotlib.pyplot.title",
"csv.reader",
"matplotlib.pyplot.legend",
... | [((19, 39), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (33, 39), True, 'import numpy as np\n'), ((148, 160), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (158, 160), False, 'from keras.models import Sequential\n'), ((722, 741), 'numpy.array', 'np.array', (['fr_corn_x'], {}), '(fr... |
#!/usr/bin/env python3
import numpy as np
M = np.array(
(
[1, -1, 0, 0, 0, 0, 0, 0],
[0.4, 0.4, 0, -1, 0, 0, 0, 0],
[0.6, 0.6, -1, 0, 0, 0, 0, 0],
[0, 0, 0, -0.75, 0, 1, 0, 0],
[-1, 0, 0, 0, 1, 1, 0, 0],
[0, -1, 0, 0, 0, 0, 1, 1],
[0, 0, 0, -1, 0, 1, 0, 1],
... | [
"numpy.array",
"numpy.linalg.inv",
"numpy.matmul"
] | [((48, 298), 'numpy.array', 'np.array', (['([1, -1, 0, 0, 0, 0, 0, 0], [0.4, 0.4, 0, -1, 0, 0, 0, 0], [0.6, 0.6, -1, 0,\n 0, 0, 0, 0], [0, 0, 0, -0.75, 0, 1, 0, 0], [-1, 0, 0, 0, 1, 1, 0, 0], [\n 0, -1, 0, 0, 0, 0, 1, 1], [0, 0, 0, -1, 0, 1, 0, 1], [1, 1, 0, 0, 0, 0,\n 0, 0])'], {}), '(([1, -1, 0, 0, 0, 0, 0, ... |
#! /usr/bin/env python3
import numpy as np
FIRST_VALUE = 1
NVALUES = 16
LAST_VALUE = FIRST_VALUE + NVALUES
PACKET_LEN = 4
fin = open('input.txt', 'w') # 入力ファイル
fr11 = open('r11.txt', 'w') # 比較ファイル
fr12 = open('r12.txt', 'w') # 比較ファイル
fr22 = open('r22.txt', 'w') # 比較ファイル
fqt11 = open('qt11.txt', 'w') # 比較ファイル
fqt12 = ... | [
"numpy.array",
"numpy.linalg.qr"
] | [((437, 463), 'numpy.array', 'np.array', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (445, 463), True, 'import numpy as np\n'), ((471, 497), 'numpy.array', 'np.array', (['[[1, 2], [3, 9]]'], {}), '([[1, 2], [3, 9]])\n', (479, 497), True, 'import numpy as np\n'), ((505, 535), 'numpy.array', 'np.array', (['[[21, ... |
import numpy as np
from sknet.network_construction import KNNConstructor
class ModularityLabelPropagation():
"""
Semi-supervised method that propagates labels to instances not
classified using the Modularity Propagation method.
Attributes
----------
generated_y_ : {ndarray, pandas series}, s... | [
"numpy.array",
"sknet.network_construction.KNNConstructor",
"numpy.isnan"
] | [((2279, 2312), 'sknet.network_construction.KNNConstructor', 'KNNConstructor', (['(5)'], {'sep_comp': '(False)'}), '(5, sep_comp=False)\n', (2293, 2312), False, 'from sknet.network_construction import KNNConstructor\n'), ((6195, 6206), 'numpy.array', 'np.array', (['Q'], {}), '(Q)\n', (6203, 6206), True, 'import numpy a... |
import numpy as np
from mlp_train import *
# Predict classes from weights
def output(inputs, weights, biases):
"""Get the output of a trained MLP for a given set of inputs."""
return forward_propagation(inputs, weights, biases)[-1]
def predict_single(output):
"""Convert MLP outputs into class predictions,... | [
"numpy.mean",
"numpy.argmax"
] | [((377, 397), 'numpy.argmax', 'np.argmax', (['output', '(1)'], {}), '(output, 1)\n', (386, 397), True, 'import numpy as np\n'), ((556, 586), 'numpy.mean', 'np.mean', (['(predictions == labels)'], {}), '(predictions == labels)\n', (563, 586), True, 'import numpy as np\n')] |
# Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... | [
"json.JSONEncoder.default",
"numpy.asarray",
"os.path.dirname",
"json.load",
"numpy.save",
"json.dump",
"numpy.load"
] | [((2719, 2754), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'obj'], {}), '(self, obj)\n', (2743, 2754), False, 'import json\n'), ((2857, 2907), 'numpy.asarray', 'np.asarray', (["dct['__ndarray__']"], {'dtype': "dct['dtype']"}), "(dct['__ndarray__'], dtype=dct['dtype'])\n", (2867, 2907), True, 'imp... |
# coding=utf-8
import json
import re
from typing import List
import pandas as pd
from collections import defaultdict
from dataclasses import dataclass
import numpy as np
from backend.integrations import database
def normalize_test_name(tests: np.ndarray):
"""
Normalize test names to match database.
- ... | [
"backend.integrations.database.get_test_execution_times",
"numpy.where",
"re.match",
"collections.defaultdict",
"json.load",
"backend.integrations.database.get_test_name_fails",
"numpy.all",
"re.search"
] | [((870, 902), 're.match', 're.match', (['"""(.*\\\\..+)\\\\+.+"""', 'test'], {}), "('(.*\\\\..+)\\\\+.+', test)\n", (878, 902), False, 'import re\n'), ((1347, 1363), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1358, 1363), False, 'from collections import defaultdict\n'), ((2666, 2723), 'backend... |
import numpy as np
import pygame as pg
class Tiles(object):
def __init__(self, size):
"""
:param size: How many tiles wide and high
"""
self.size = size
self.screen_rect = pg.display.get_surface().get_rect()
self.screen_width = self.screen_rect.width
self.s... | [
"pygame.display.get_surface",
"pygame.draw.rect",
"numpy.empty",
"pygame.Color",
"pygame.Rect"
] | [((639, 662), 'pygame.Color', 'pg.Color', (['"""GreenYellow"""'], {}), "('GreenYellow')\n", (647, 662), True, 'import pygame as pg\n'), ((689, 710), 'pygame.Color', 'pg.Color', (['"""LawnGreen"""'], {}), "('LawnGreen')\n", (697, 710), True, 'import pygame as pg\n'), ((1015, 1056), 'numpy.empty', 'np.empty', (['(self.si... |
import pandas as pd
import numpy as np
import netCDF4 as nc
from .subroutines import *
class SpecificDoses(pd.DataFrame):
"""A class for specific dose estimates akin to dosimetry measurements
High resolution data allows for personal and ambient dose estimation without the need for
direct measurement. Thi... | [
"pandas.DataFrame.from_records",
"numpy.mean",
"numpy.median",
"numpy.amin",
"pandas.read_csv",
"numpy.average",
"pandas.DatetimeIndex",
"numpy.sum",
"numpy.zeros",
"numpy.std",
"numpy.amax",
"numpy.var"
] | [((7021, 7033), 'numpy.zeros', 'np.zeros', (['(24)'], {}), '(24)\n', (7029, 7033), True, 'import numpy as np\n'), ((10556, 11298), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', ([], {'columns': "['Seated', 'Kneeling', 'Standing erect arms down', 'Standing erect arms up',\n 'Standing bowing']", 'index... |
import numpy as np
from sklearn.preprocessing import MinMaxScaler as mms
import ONN_Simulation_Class as ONN_Cls
from plot_scatter_matrix import plot_scatter_matrix
import ONN_Setups
import training_onn as train
import test_trained_onns as test
import create_datasets
from sklearn import preprocessing
import sys
sys.path... | [
"numpy.linspace",
"sys.path.append",
"numpy.argmax",
"ONN_Simulation_Class.ONN_Simulation"
] | [((312, 334), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (327, 334), False, 'import sys\n'), ((367, 391), 'ONN_Simulation_Class.ONN_Simulation', 'ONN_Cls.ONN_Simulation', ([], {}), '()\n', (389, 391), True, 'import ONN_Simulation_Class as ONN_Cls\n'), ((1135, 1155), 'numpy.linspace', 'np.li... |
'''
util.py
the utility functions of the project
'''
import os
import sys
from warnings import warn
from datetime import datetime
from pathlib import Path
from importlib import import_module
import torch
import torch.nn as nn
import frontend
import util.audio as audio
from config import config
import numpy as np
impor... | [
"util.wavenet_util.is_mulaw",
"matplotlib.pyplot.ylabel",
"util.wavenet_util.is_scalar_input",
"util.audio.inv_mulaw",
"torch.from_numpy",
"torch.cuda.is_available",
"util.wavenet_util.is_mulaw_quantize",
"librosa.display.waveplot",
"torch.arange",
"numpy.flip",
"model.Decoder",
"matplotlib.py... | [((333, 354), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (347, 354), False, 'import matplotlib\n'), ((550, 575), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (573, 575), False, 'import torch\n'), ((1819, 2165), 'model.Encoder', 'Encoder', (['n_vocab', 'embed_dim'], ... |
"""Fuzzy K-means clustering"""
# ==============================================================================
# Author: <NAME> <ammarsherif90 [at] gmail [dot] com >
# License: MIT
# ==============================================================================
# =====================================================... | [
"numpy.sum",
"numpy.zeros",
"sklearn.utils.check_random_state"
] | [((2284, 2316), 'numpy.zeros', 'np.zeros', (['(n_points, n_clusters)'], {}), '((n_points, n_clusters))\n', (2292, 2316), True, 'import numpy as np\n'), ((3285, 3316), 'numpy.sum', 'np.sum', (['(fmm ** self.__m)'], {'axis': '(0)'}), '(fmm ** self.__m, axis=0)\n', (3291, 3316), True, 'import numpy as np\n'), ((3621, 3655... |
import numpy as np
import matplotlib.pyplot as plt
def penalty(t, k):
return np.log(1+np.exp(k*t))/k
# return k * t / (k - t + 1)
temp_lb = 310
temp = np.linspace(temp_lb-1, temp_lb+2, 1000)
k = 10
diff = temp_lb-temp
p = penalty(diff, k)
plt.close('all')
plt.figure()
plt.plot(diff, 1445*p)
plt.plot(diff,... | [
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
] | [((163, 206), 'numpy.linspace', 'np.linspace', (['(temp_lb - 1)', '(temp_lb + 2)', '(1000)'], {}), '(temp_lb - 1, temp_lb + 2, 1000)\n', (174, 206), True, 'import numpy as np\n'), ((253, 269), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (262, 269), True, 'import matplotlib.pyplot as plt\n'... |
import numpy as np
import unittest
from network_attack_simulator.envs.action import Action
from network_attack_simulator.envs.machine import Machine
A_COST = 10
class MachineTestCase(unittest.TestCase):
def setUp(self):
self.test_r = 5000.0
self.services = np.asarray([True, False, True])
... | [
"unittest.main",
"network_attack_simulator.envs.action.Action",
"numpy.asarray",
"network_attack_simulator.envs.machine.Machine"
] | [((2902, 2917), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2915, 2917), False, 'import unittest\n'), ((281, 312), 'numpy.asarray', 'np.asarray', (['[True, False, True]'], {}), '([True, False, True])\n', (291, 312), True, 'import numpy as np\n'), ((336, 366), 'network_attack_simulator.envs.machine.Machine', 'M... |
import numpy as np
from datetime import datetime
import System
from System import Array
from DHI.Generic.MikeZero import eumUnit, eumQuantity
from DHI.Generic.MikeZero.DFS import (
DfsFileFactory,
DfsFactory,
DfsSimpleType,
DataValueType,
)
from DHI.Generic.MikeZero.DFS.dfs123 import Dfs1Builder
from .... | [
"DHI.Generic.MikeZero.DFS.DfsFileFactory.Dfs1FileOpenEdit",
"datetime.datetime.strptime",
"DHI.Generic.MikeZero.eumQuantity.Create",
"DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen",
"datetime.datetime.now",
"DHI.Generic.MikeZero.DFS.dfs123.Dfs1Builder.Create",
"System.DateTime",
"numpy.ndarra... | [((1138, 1177), 'DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen', 'DfsFileFactory.DfsGenericOpen', (['filename'], {}), '(filename)\n', (1167, 1177), False, 'from DHI.Generic.MikeZero.DFS import DfsFileFactory, DfsFactory, DfsSimpleType, DataValueType\n'), ((3210, 3251), 'DHI.Generic.MikeZero.DFS.DfsFileFactory.... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 14:27:45 2018
@author: aceituno
"""
import data_processing as dp
import matplotlib.pyplot as plt
import numpy as np
path_fig = './'
showPlots = True
savePlots = True
def plot_spiking_rate_with_learning(spikesInitial, spikesFinal, neurons, ti... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"data_processing.spike_timing_evolution",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"data_processing.spike_timing_evolution_percentiles",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.fill_between",
"nump... | [((371, 401), 'numpy.linspace', 'np.linspace', (['(0)', 'timePlot', 'bins'], {}), '(0, timePlot, bins)\n', (382, 401), True, 'import numpy as np\n'), ((472, 525), 'matplotlib.pyplot.hist', 'plt.hist', (['times', 'bins'], {'alpha': '(0.5)', 'label': '"""Before STDP"""'}), "(times, bins, alpha=0.5, label='Before STDP')\n... |
import numpy as np
#import simpleaudio as sa
import scipy.io.wavfile as sw
'''
def audioplay(fs, y):
yout = np.iinfo(np.int16).max / np.max(np.abs(y)) * y
yout = yout.astype(np.int16)
play_obj = sa.play_buffer(yout, y.ndim, 2, fs)
'''
def wavread(wavefile):
fs, y = sw.read(wavefile)
if y.dtype == ... | [
"numpy.abs",
"numpy.iinfo",
"scipy.io.wavfile.read",
"scipy.io.wavfile.write"
] | [((284, 301), 'scipy.io.wavfile.read', 'sw.read', (['wavefile'], {}), '(wavefile)\n', (291, 301), True, 'import scipy.io.wavfile as sw\n'), ((1057, 1085), 'scipy.io.wavfile.write', 'sw.write', (['wavefile', 'fs', 'data'], {}), '(wavefile, fs, data)\n', (1065, 1085), True, 'import scipy.io.wavfile as sw\n'), ((758, 770)... |
import numpy as np
# Compute element-wise square of vector
def vsquare(V):
R = np.power(V, 2)
| [
"numpy.power"
] | [((85, 99), 'numpy.power', 'np.power', (['V', '(2)'], {}), '(V, 2)\n', (93, 99), True, 'import numpy as np\n')] |
#author:<NAME>
#insitution: MIT
import matplotlib.pyplot as plt
import time
import numpy as np
try:
from HAPILite import CalcCrossSection
except:
from ..HAPILite import CalcCrossSection
WaveNumber = np.arange(0,10000,0.001)
StartTime = time.time()
CrossSection = CalcCrossSection("CO2",Temp=1000.0,WN_Grid=... | [
"matplotlib.pyplot.plot",
"HAPILite.CalcCrossSection",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"time.time",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((211, 237), 'numpy.arange', 'np.arange', (['(0)', '(10000)', '(0.001)'], {}), '(0, 10000, 0.001)\n', (220, 237), True, 'import numpy as np\n'), ((249, 260), 'time.time', 'time.time', ([], {}), '()\n', (258, 260), False, 'import time\n'), ((277, 367), 'HAPILite.CalcCrossSection', 'CalcCrossSection', (['"""CO2"""'], {'... |
import numpy as np
import general as gen
def cluster(dataArray, k, dim, dNo, t):
# reps = gen.initializeRandom(dataArray, k, dim, dNo)
# print(reps)
# reps = np.array([[1], [2], [3]])
reps = np.array([[1], [11], [28]])
print(reps)
for itr in range(t):
n = []
# print(dataArray)
... | [
"numpy.array",
"general.findmeanofcluster",
"general.clustering_k_means"
] | [((209, 236), 'numpy.array', 'np.array', (['[[1], [11], [28]]'], {}), '([[1], [11], [28]])\n', (217, 236), True, 'import numpy as np\n'), ((339, 386), 'general.clustering_k_means', 'gen.clustering_k_means', (['dataArray', 'k', 'reps', 'dNo'], {}), '(dataArray, k, reps, dNo)\n', (361, 386), True, 'import general as gen\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.