code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Metafier V3: writes directly to output.mc
# Avoids memory errors for large programs
# Assumes the pattern width is less than or equal to 1024
# ===REQUIRES metatemplate11.mc===
import golly as g
import numpy as np
from shutil import copyfile
g.show("Retrieving selection...")
#Get the selection
selection = g.getselr... | [
"golly.getcells",
"numpy.reshape",
"golly.getselrect",
"golly.exit",
"golly.show",
"golly.addlayer",
"golly.open",
"numpy.zeros",
"shutil.copyfile",
"numpy.log2"
] | [((246, 279), 'golly.show', 'g.show', (['"""Retrieving selection..."""'], {}), "('Retrieving selection...')\n", (252, 279), True, 'import golly as g\n'), ((311, 325), 'golly.getselrect', 'g.getselrect', ([], {}), '()\n', (323, 325), True, 'import golly as g\n'), ((625, 646), 'golly.getcells', 'g.getcells', (['selection... |
import numpy as np
def sigmoid(x):
indp = np.where(x>=0)
indn = np.where(x<0)
tx = np.zeros(x.shape)
tx[indp] = 1./(1.+np.exp(-x[indp]))
tx[indn] = np.exp(x[indn])/(1.+np.exp(x[indn]))
return tx
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
def KL_divergence(x, y)... | [
"numpy.tile",
"numpy.sqrt",
"numpy.where",
"numpy.random.random",
"numpy.log",
"numpy.exp",
"numpy.sum",
"numpy.zeros"
] | [((57, 73), 'numpy.where', 'np.where', (['(x >= 0)'], {}), '(x >= 0)\n', (65, 73), True, 'import numpy as np\n'), ((83, 98), 'numpy.where', 'np.where', (['(x < 0)'], {}), '(x < 0)\n', (91, 98), True, 'import numpy as np\n'), ((106, 123), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (114, 123), True, 'im... |
import numpy as np
import torch
class Compose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms
to compose.
Example:
>>> transforms.Compose([
>>> transforms.MriNoise(),
... | [
"numpy.absolute",
"numpy.reshape"
] | [((722, 755), 'numpy.reshape', 'np.reshape', (['dat', '((1,) + dat.shape)'], {}), '(dat, (1,) + dat.shape)\n', (732, 755), True, 'import numpy as np\n'), ((822, 851), 'numpy.absolute', 'np.absolute', (["sample['target']"], {}), "(sample['target'])\n", (833, 851), True, 'import numpy as np\n')] |
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.mixture import GaussianMixture
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
import numpy as np
data = load_iris()
data.feature_names, data.target_names
X_train, X_test, y_train, y_t... | [
"sklearn.datasets.load_iris",
"sklearn.mixture.GaussianMixture",
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.KernelDensity",
"numpy.exp",
"matplotlib.pyplot.title",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.show"
] | [((239, 250), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (248, 250), False, 'from sklearn.datasets import load_iris\n'), ((326, 398), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data.data', 'data.target'], {'test_size': '(0.33)', 'random_state': '(3)'}), '(data.data, data.target... |
import numpy as np
import collections
from PIL import Image
from generic.data_provider.batchifier import AbstractBatchifier
from generic.data_provider.image_preprocessors import get_spatial_feat, resize_image
from generic.data_provider.nlp_utils import padder,padder_3d,padder_4d
from generic.data_provider.nlp_utils im... | [
"PIL.Image.fromarray",
"generic.data_provider.nlp_utils.Embeddings",
"generic.data_provider.nlp_utils.get_embeddings",
"numpy.asarray",
"generic.data_provider.nlp_utils.padder_4d",
"numpy.array",
"numpy.zeros",
"collections.defaultdict",
"generic.data_provider.nlp_utils.padder",
"generic.data_prov... | [((698, 733), 'numpy.array', 'np.array', (['[1, 0, 0]'], {'dtype': 'np.int32'}), '([1, 0, 0], dtype=np.int32)\n', (706, 733), True, 'import numpy as np\n'), ((748, 783), 'numpy.array', 'np.array', (['[0, 1, 0]'], {'dtype': 'np.int32'}), '([0, 1, 0], dtype=np.int32)\n', (756, 783), True, 'import numpy as np\n'), ((799, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 14:10:46 2019
@author: gui
"""
import sys, pygame
import numpy as np
from pygame.locals import *
import pygame.freetype
w = 600
h = 600
scale = 100
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
score = max_score = 0
pygame.init()
screen = pygame.... | [
"pygame.event.clear",
"pygame.init",
"pygame.draw.line",
"pygame.Surface",
"sys.exit",
"pygame.display.set_mode",
"numpy.random.choice",
"pygame.time.Clock",
"numpy.count_nonzero",
"pygame.event.wait",
"numpy.zeros",
"numpy.random.randint",
"pygame.display.set_caption",
"pygame.freetype.Sy... | [((290, 303), 'pygame.init', 'pygame.init', ([], {}), '()\n', (301, 303), False, 'import sys, pygame\n'), ((313, 344), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(w, h)'], {}), '((w, h))\n', (336, 344), False, 'import sys, pygame\n'), ((344, 389), 'pygame.display.set_caption', 'pygame.display.set_caption'... |
"""
DMRG for XXZ model.
"""
from typing import Type, Text
import tensornetwork as tn
import numpy as np
tn.set_default_backend('pytorch')
def initialize_spin_mps(N: int, D: int, dtype: Type[np.number]):
return tn.FiniteMPS.random([2] * N, [D] * (N - 1), dtype=dtype)
def initialize_XXZ_mpo(Jz: np.ndarray, Jxy: np.... | [
"numpy.ones",
"tensornetwork.set_default_backend",
"numpy.zeros",
"tensornetwork.FiniteDMRG",
"tensornetwork.FiniteXXZ",
"tensornetwork.FiniteMPS.random"
] | [((106, 139), 'tensornetwork.set_default_backend', 'tn.set_default_backend', (['"""pytorch"""'], {}), "('pytorch')\n", (128, 139), True, 'import tensornetwork as tn\n'), ((214, 270), 'tensornetwork.FiniteMPS.random', 'tn.FiniteMPS.random', (['([2] * N)', '([D] * (N - 1))'], {'dtype': 'dtype'}), '([2] * N, [D] * (N - 1)... |
import os
import sys
from datetime import datetime
from shutil import copyfile
import glob
import copy
import yaml
import torch
import networkx as nx
import numpy as np
from models.fourier_nn import FourierNet
from problems.dist_online_dense_problem import DistOnlineDensityProblem
from optimizers.dinno import DiNNO
f... | [
"optimizers.dinno.DiNNO",
"numpy.hstack",
"floorplans.lidar.lidar.RandomPoseLidarDataset",
"torch.nn.L1Loss",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"torch.sum",
"copy.deepcopy",
"torch.profiler.schedule",
"os.path.exists",
"floorplans.lidar.lidar.OnlineTrajectoryLidarDataset",
"proble... | [((535, 584), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.DoubleTensor'], {}), '(torch.DoubleTensor)\n', (564, 584), False, 'import torch\n'), ((1264, 1342), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_set', "conf['train_batch_size']"], {'shuffle': '(True)'}), "... |
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
import argparse
import datetime
import pickle
import csv
X, y = [], []
def load_dataset(infile):
global X, y... | [
"csv.DictReader",
"argparse.ArgumentParser",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_squared_error",
"numpy.array",
"sklearn.metrics.r2_score",
"sklearn.linear_model.LinearRegression"
] | [((773, 784), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (781, 784), True, 'import numpy as np\n'), ((844, 881), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (860, 881), False, 'from sklearn.model_selection import train_test_split... |
import pandas as pd
import numpy as np
from os.path import join, exists, split
from os import mkdir, makedirs, listdir
import gc
import matplotlib.pyplot as plt
import seaborn
from copy import deepcopy
from time import time
import pickle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('split_na... | [
"pickle.dump",
"argparse.ArgumentParser",
"numpy.logical_and",
"os.path.join",
"numpy.diff",
"numpy.datetime64",
"gc.collect",
"numpy.concatenate",
"numpy.timedelta64",
"time.time"
] | [((265, 290), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (288, 290), False, 'import argparse\n'), ((938, 960), 'numpy.timedelta64', 'np.timedelta64', (['(2)', '"""h"""'], {}), "(2, 'h')\n", (952, 960), True, 'import numpy as np\n'), ((1179, 1322), 'os.path.join', 'join', (['bern_path', '"""... |
#-----------------------------------------------------------------------------#
# #
# I M P O R T L I B R A R I E S #
# #
... | [
"torch.nn.GroupNorm",
"torch.nn.ReLU",
"torch.nn.BatchNorm2d",
"numpy.sqrt",
"torch.nn.Sequential",
"torch.load",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.functional.normalize",
"torch.nn.BatchNorm1d",
"torchvision.models.resnet.ResNet",
"torch.nn.MaxPool2d",
"torch.nn.... | [((12003, 12051), 'torchvision.models.resnet.ResNet', 'ResNet', (['BasicBlock', '[1, 1, 1, 1]'], {'num_classes': '(10)'}), '(BasicBlock, [1, 1, 1, 1], num_classes=10)\n', (12009, 12051), False, 'from torchvision.models.resnet import ResNet, BasicBlock\n'), ((12078, 12126), 'torchvision.models.resnet.ResNet', 'ResNet', ... |
import numpy as np
import pandas as pd
from vimms.old_unused_experimental.PythonMzmine import get_base_scoring_df
from vimms.Roi import make_roi
QCB_MZML2CHEMS_DICT = {'min_ms1_intensity': 1.75E5,
'mz_tol': 2,
'mz_units': 'ppm',
'min_length': 1,
... | [
"numpy.logical_and",
"vimms.old_unused_experimental.PythonMzmine.get_base_scoring_df",
"numpy.where",
"numpy.array",
"vimms.Roi.make_roi",
"numpy.nonzero",
"pandas.DataFrame",
"pandas.concat"
] | [((538, 788), 'vimms.Roi.make_roi', 'make_roi', (['mzml'], {'mz_tol': "mzml2chems_dict['mz_tol']", 'mz_units': "mzml2chems_dict['mz_units']", 'min_length': 'min_roi_length', 'min_intensity': "mzml2chems_dict['min_intensity']", 'start_rt': "mzml2chems_dict['start_rt']", 'stop_rt': "mzml2chems_dict['stop_rt']"}), "(mzml,... |
from typing import Optional, Callable, Any, List, Dict
import numpy as np
from functools import partial
import torch.nn as nn
import torch
from torch import Tensor
from ..layers.activations import lookup_act
from ..initialisations import lookup_normal_init
from .abs_block import AbsBlock
__all__ = ['FullyConnected',... | [
"torch.nn.Dropout",
"torch.nn.Sequential",
"torch.nn.ModuleList",
"numpy.floor",
"torch.nn.init.zeros_",
"numpy.sum",
"torch.nn.Linear",
"torch.nn.AlphaDropout",
"torch.cat"
] | [((6802, 6824), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (6815, 6824), True, 'import torch.nn as nn\n'), ((12441, 12467), 'torch.nn.ModuleList', 'nn.ModuleList', (['self.blocks'], {}), '(self.blocks)\n', (12454, 12467), True, 'import torch.nn as nn\n'), ((12911, 12941), 'torch.nn.init.z... |
#!/usr/bin/python
import argparse
import os
import numpy as np
from dolfyn.adv.rotate import orient2euler
import dolfyn.adv.api as avm
from dolfyn.adv.motion import correct_motion
# TODO: add option to rotate into earth or principal frame (include
# principal_angle_True in output).
script_dir = os.path.dirname(__fil... | [
"dolfyn.adv.motion.correct_motion",
"dolfyn.adv.rotate.orient2euler",
"argparse.ArgumentParser",
"os.path.dirname",
"numpy.array",
"dolfyn.adv.api.read_nortek"
] | [((299, 324), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (314, 324), False, 'import os\n'), ((335, 574), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""\n Perform motion correction of a Nortek Vector(.vec)\n file and save the output in earth(u: East, ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may ... | [
"tvm.relay.nn.dense",
"tvm.relay.Tuple",
"tvm.relay.op.contrib.dnnl.partition_for_dnnl",
"tvm.relay.Function",
"tvm.relay.create_executor",
"tvm.relay.cast",
"tvm.relay.nn.conv2d",
"tvm.relay.add",
"pytest.main",
"tvm.IRModule",
"tvm.transform.PassContext",
"tvm.relay.sigmoid",
"tvm.IRModule... | [((1700, 1738), 'itertools.combinations', 'itertools.combinations', (['result_dict', '(2)'], {}), '(result_dict, 2)\n', (1722, 1738), False, 'import itertools\n'), ((2222, 2231), 'tvm.cpu', 'tvm.cpu', ([], {}), '()\n', (2229, 2231), False, 'import tvm\n'), ((4040, 4082), 'tvm.relay.var', 'relay.var', (['"""x"""'], {'sh... |
import numpy as np
import scipy.stats as stats
from tbainfo import tbarequests
from sim_team import SimTeam
from match_score import Match, TeamScore, AllianceScore
import globals
CARGO_PT = 3
PANEL_PT = 2
AUTO1 = 3
AUTO2 = 6
CLIMB1 = 3
CLIMB2 = 6
CLIMB3 = 12
# returns a normal distribution truncated at the specified... | [
"numpy.mean",
"sim_team.SimTeam",
"globals.init",
"numpy.std",
"numpy.min",
"numpy.max",
"match_score.Match",
"scipy.stats.truncnorm",
"tbainfo.tbarequests",
"match_score.AllianceScore"
] | [((399, 472), 'scipy.stats.truncnorm', 'stats.truncnorm', (['((low - mean) / sd)', '((upp - mean) / sd)'], {'loc': 'mean', 'scale': 'sd'}), '((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)\n', (414, 472), True, 'import scipy.stats as stats\n'), ((3230, 3244), 'globals.init', 'globals.init', ([], {}), '()\n',... |
# pylint: disable=no-self-use,invalid-name
import random
from os.path import join
import numpy
from deep_qa.data.dataset_readers.squad_sentence_selection_reader import SquadSentenceSelectionReader
from deep_qa.testing.test_case import DeepQaTestCase
from overrides import overrides
class TestSquadSentenceSelectionRea... | [
"deep_qa.data.dataset_readers.squad_sentence_selection_reader.SquadSentenceSelectionReader",
"os.path.join",
"numpy.random.seed",
"random.seed"
] | [((3453, 3470), 'random.seed', 'random.seed', (['(1337)'], {}), '(1337)\n', (3464, 3470), False, 'import random\n'), ((3479, 3502), 'numpy.random.seed', 'numpy.random.seed', (['(1337)'], {}), '(1337)\n', (3496, 3502), False, 'import numpy\n'), ((3586, 3603), 'random.seed', 'random.seed', (['(1337)'], {}), '(1337)\n', (... |
import gym
# 生成仿真环境
env = gym.make('Taxi-v3')
# 重置仿真环境
obs = env.reset()
# 渲染环境当前状态
#env.render()
m = env.observation_space.n # size of the state space
n = env.action_space.n # size of action space
print(m,n)
print("出租车问题状态数量为{:d},动作数量为{:d}。".format(m, n))
import numpy as np
# Intialize the Q-table an... | [
"numpy.mean",
"numpy.random.rand",
"numpy.argmax",
"numpy.any",
"numpy.max",
"numpy.sum",
"numpy.zeros",
"gym.make",
"numpy.var"
] | [((30, 49), 'gym.make', 'gym.make', (['"""Taxi-v3"""'], {}), "('Taxi-v3')\n", (38, 49), False, 'import gym\n'), ((357, 373), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (365, 373), True, 'import numpy as np\n'), ((377, 393), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (385, 393), True, 'im... |
"""
The `methods` script contains functions for estimating the period of a star.
"""
import lightkurve as lk
import astropy.units as u
import numpy as np
from scipy.signal import find_peaks
from scipy import interpolate
from scipy.optimize import curve_fit
from scipy.ndimage import gaussian_filter1d
import warnings
i... | [
"scipy.optimize.curve_fit",
"jazzhands.WaveletTransformer",
"numpy.flip",
"numpy.mean",
"numpy.argmax",
"numpy.max",
"scipy.interpolate.interp1d",
"numpy.sum",
"lightkurve.LightCurve",
"numpy.correlate",
"numpy.nanmax",
"scipy.signal.find_peaks",
"numpy.nanmin",
"scipy.ndimage.gaussian_fil... | [((2827, 2995), 'scipy.optimize.curve_fit', 'curve_fit', (['_gaussian_fn', 'p', 'P'], {'p0': '[max_period, 0.1 * max_period, max_power]', 'bounds': '([lolim, 0.0, 0.9 * max_power], [uplim, 0.25 * max_period, 1.1 * max_power])'}), '(_gaussian_fn, p, P, p0=[max_period, 0.1 * max_period, max_power],\n bounds=([lolim, 0... |
import torch
import torch.nn as nn
from collections import OrderedDict
from PIL import Image
import numpy as np
def act(act_type, inplace=True, neg_slope=0.2, n_prelu=1):
# helper selecting activation
# neg_slope: for leakyrelu and init of prelu
# n_prelu: for p_relu num_parameters
act_type = act_type... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.LeakyReLU",
"torch.nn.Sequential",
"torch.nn.ReflectionPad2d",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.nn.PReLU",
"numpy.transpose",
"torch.nn.ReplicationPad2d"
] | [((2255, 2278), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (2268, 2278), True, 'import torch.nn as nn\n'), ((2919, 3050), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_nc', 'out_nc'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'dilation': 'dilation', 'bias': 'bias'... |
import pytest
pytest.importorskip('numpy')
import numpy as np
import pytest
import dask.array as da
from dask.array.utils import assert_eq
def test_linspace():
darr = da.linspace(6, 49, chunks=5)
nparr = np.linspace(6, 49)
assert_eq(darr, nparr)
darr = da.linspace(1.4, 4.9, chunks=5, num=13)
np... | [
"dask.array.linspace",
"dask.array.indices",
"pytest.mark.xfail",
"dask.array.utils.assert_eq",
"numpy.indices",
"dask.array.arange",
"numpy.linspace",
"pytest.importorskip",
"pytest.raises",
"numpy.arange"
] | [((14, 42), 'pytest.importorskip', 'pytest.importorskip', (['"""numpy"""'], {}), "('numpy')\n", (33, 42), False, 'import pytest\n'), ((2153, 2290), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Casting floats to ints is not supported since edgebehavior is not specified or guaranteed by NumPy."""'}), "(r... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd
import os
from scipy.stats import chi2_contingency
def chi_squared_yates(
no_Gold, no_Resections, no_No_Surgery,
no_Gold_absent_term, no_Resections_absent_term, no_No_Surgery_absent_t... | [
"matplotlib.pyplot.savefig",
"scipy.stats.chi2_contingency",
"seaborn.despine",
"matplotlib.pyplot.clf",
"os.path.join",
"seaborn.heatmap",
"matplotlib.pyplot.axis",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.yticks",
"numpy.around",
"pandas.DataFrame",
"matplotlib.pyplot.... | [((1095, 1116), 'scipy.stats.chi2_contingency', 'chi2_contingency', (['obs'], {}), '(obs)\n', (1111, 1116), False, 'from scipy.stats import chi2_contingency\n'), ((2516, 2651), 'numpy.array', 'np.array', (['[[no_Gold, no_No_Surgery + no_Resections], [no_Gold_absent_term, \n no_No_Surgery_absent_term + no_Resections_... |
# Code to split the dataset into train/validation/test.
import argparse
import os
import time
from collections import defaultdict
import math
import numpy as np
import csv
import hickle as hkl
import glob
from sklearn.model_selection import train_test_split
import pdb
import random
from generate_dat... | [
"sklearn.model_selection.train_test_split",
"csv.writer",
"numpy.random.seed",
"glob.glob"
] | [((360, 379), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (374, 379), True, 'import numpy as np\n'), ((426, 497), 'glob.glob', 'glob.glob', (['"""/data/INTERACTION-Dataset-DR-v1_1/processed_data/pkl/*ego*"""'], {}), "('/data/INTERACTION-Dataset-DR-v1_1/processed_data/pkl/*ego*')\n", (435, 497), F... |
from estimator_adaptative import EstimatorAdaptative
from mpl_toolkits.mplot3d import Axes3D
from grid_search import GridSearch
import matplotlib.pyplot as plt
import matplotlib as mpl
from utils import *
import numpy as np
import os
import sys
data_path = '../../databases'
PlotsDirectory = '../plots/Week2/task2/'
if... | [
"os.path.exists",
"estimator_adaptative.EstimatorAdaptative",
"os.makedirs",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"matplotlib.pyplot.show"
] | [((325, 355), 'os.path.exists', 'os.path.exists', (['PlotsDirectory'], {}), '(PlotsDirectory)\n', (339, 355), False, 'import os\n'), ((361, 388), 'os.makedirs', 'os.makedirs', (['PlotsDirectory'], {}), '(PlotsDirectory)\n', (372, 388), False, 'import os\n'), ((449, 471), 'numpy.array', 'np.array', (['[1050, 1200]'], {}... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012, <NAME>
# All rights reserved.
# This file is part of PyDSM.
# PyDSM is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... | [
"numpy.abs",
"numpy.log",
"numpy.zeros",
"scipy.signal.lfilter",
"scipy.signal.zpk2tf",
"scipy.signal.tf2zpk",
"numpy.seterr"
] | [((2394, 2405), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (2402, 2405), True, 'import numpy as np\n'), ((2432, 2460), 'scipy.signal.lfilter', 'sp.signal.lfilter', (['b', 'a', 'ins'], {}), '(b, a, ins)\n', (2449, 2460), True, 'import scipy as sp\n'), ((2243, 2263), 'scipy.signal.zpk2tf', 'sp.signal.zpk2tf', (['*h... |
# -*- coding: utf-8 -*-
import torch
import numpy as np
import torch.nn.functional as F
from nnlib.load_time_series import load_data
from nnlib.utils.general_utils import reshape_3d_rest
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("conv1D_cuda:2") # Uncomment this to run on GPU
np.random.... | [
"nnlib.load_time_series.load_data",
"torch.nn.functional.conv1d",
"torch.from_numpy",
"nnlib.utils.general_utils.reshape_3d_rest",
"numpy.array",
"numpy.random.seed",
"torch.device"
] | [((217, 236), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (229, 236), False, 'import torch\n'), ((310, 329), 'numpy.random.seed', 'np.random.seed', (['(231)'], {}), '(231)\n', (324, 329), True, 'import numpy as np\n'), ((430, 448), 'nnlib.load_time_series.load_data', 'load_data', (['dataset'], {})... |
import os
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.face.LBPHFaceRecognizer_create()
path='dataSet'
def getImagesWithID(path):
imagepaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagepath in imagepaths:
faceImg=Image.open(imagepath).conv... | [
"os.listdir",
"PIL.Image.open",
"os.path.join",
"cv2.face.LBPHFaceRecognizer_create",
"cv2.imshow",
"os.path.split",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.waitKey"
] | [((77, 113), 'cv2.face.LBPHFaceRecognizer_create', 'cv2.face.LBPHFaceRecognizer_create', ([], {}), '()\n', (111, 113), False, 'import cv2\n'), ((713, 736), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (734, 736), False, 'import cv2\n'), ((651, 664), 'numpy.array', 'np.array', (['IDs'], {}), '(IDs... |
import torch
import torchvision.transforms as T
import numpy as np
import cv2
from PIL import Image
class DictBatch(object):
def __init__(self, data):
"""
:param data: list of Dict of Tensors.
"""
self.keys = list(data[0].keys())
values = list(zip(*[list(d.values()) for d ... | [
"torchvision.transforms.ToPILImage",
"numpy.array",
"torchvision.transforms.Resize",
"cv2.resize",
"torchvision.transforms.ToTensor",
"torchvision.transforms.Compose",
"torch.cat"
] | [((1766, 1779), 'torchvision.transforms.Compose', 'T.Compose', (['ts'], {}), '(ts)\n', (1775, 1779), True, 'import torchvision.transforms as T\n'), ((2752, 2763), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2760, 2763), True, 'import numpy as np\n'), ((3459, 3492), 'cv2.resize', 'cv2.resize', (['image', '(new_h, ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 15:19:40 2022
@author: turnerp
"""
import traceback
import numpy as np
from skimage import exposure
import cv2
import tifffile
import os
from glob2 import glob
import pandas as pd
import mat4py
import datetime
import json
import matplotlib.pyplot as plt
import hashli... | [
"glob2.glob",
"tifffile.TiffFile",
"json.loads",
"numpy.where",
"os.path.isfile",
"numpy.array",
"pandas.DataFrame",
"os.path.abspath"
] | [((5494, 5520), 'glob2.glob', 'glob', (["(path + '\\\\**\\\\*.tif')"], {}), "(path + '\\\\**\\\\*.tif')\n", (5498, 5520), False, 'from glob2 import glob\n'), ((1575, 1695), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['path', 'file_name', 'folder', 'parent_folder', 'posX', 'posY', 'posZ',\n 'laser', 'times... |
import numpy as np
import datetime
from ..nets.lstm_network import ActorCritic
import torch
import torch.optim as optim
from tqdm import trange
from tensorboardX import SummaryWriter
class Agent(object):
def __init__(self, agent_name, input_channels, network_parameters, ppo_parameters=None, n_actions=3):
... | [
"tensorboardX.SummaryWriter",
"torch.load",
"torch.min",
"numpy.random.randint",
"torch.cuda.is_available",
"torch.zeros",
"tqdm.trange",
"torch.clamp",
"torch.device"
] | [((1304, 1329), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1327, 1329), False, 'import torch\n'), ((1352, 1395), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (1364, 1395), False, 'import torch\n'), ((3243, 3331), 'tqdm.tran... |
import numpy as np
from torch.utils.data import Dataset
class GraphDataset(Dataset):
def __init__(self, node_attributes, adj_matrices, labels):
super(GraphDataset, self).__init__()
num_nodes = []
for adj_matrix in adj_matrices:
num_nodes.append(adj_matrix.shape[0])
se... | [
"numpy.array",
"numpy.zeros"
] | [((531, 548), 'numpy.array', 'np.array', (['[label]'], {}), '([label])\n', (539, 548), True, 'import numpy as np\n'), ((828, 868), 'numpy.zeros', 'np.zeros', (['(self.max_size, self.max_size)'], {}), '((self.max_size, self.max_size))\n', (836, 868), True, 'import numpy as np\n'), ((1195, 1241), 'numpy.zeros', 'np.zeros... |
import re
import os
import sys
import random
import argparse
from datetime import datetime
import spacy
import msgpack, time
import numpy as np
import multiprocessing
import unicodedata
import collections
import torch
from torch.autograd import Variable
from apip import utils
from apip.model import DocReaderModel
p... | [
"apip.model.DocReaderModel",
"multiprocessing.cpu_count",
"argparse.ArgumentParser",
"torch.set_printoptions",
"spacy.load",
"apip.utils.add_arguments",
"apip.utils.score",
"numpy.take",
"random.random",
"unicodedata.normalize",
"msgpack.load",
"torch.Tensor",
"re.sub",
"torch.manual_seed"... | [((328, 397), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train a Document Reader model."""'}), "(description='Train a Document Reader model.')\n", (351, 397), False, 'import argparse\n'), ((413, 440), 'apip.utils.add_arguments', 'utils.add_arguments', (['parser'], {}), '(parser)\n', ... |
from abc import ABC, abstractmethod
import numpy as np
class Correlation(ABC):
"""
Abstract base class of all Correlations. Serves as a template for creating new Kriging correlation
functions.
"""
@abstractmethod
def c(self, x, s, params, dt=False, dx=False):
"""
Abstract meth... | [
"numpy.atleast_2d",
"numpy.minimum",
"numpy.size",
"numpy.sign",
"numpy.atleast_3d"
] | [((1213, 1252), 'numpy.minimum', 'np.minimum', (['after_parameters', 'comp_ones'], {}), '(after_parameters, comp_ones)\n', (1223, 1252), True, 'import numpy as np\n'), ((513, 529), 'numpy.atleast_2d', 'np.atleast_2d', (['x'], {}), '(x)\n', (526, 529), True, 'import numpy as np\n'), ((531, 547), 'numpy.atleast_2d', 'np.... |
import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import resnet
fX = theano.config.floatX
def test_zero_last_axis_partition_node():
network = tn.SequentialNode(
"s",
[tn.InputNode("i", shape=(No... | [
"treeano.sandbox.nodes.resnet._ZeroLastAxisPartitionNode",
"treeano.nodes.InputNode",
"numpy.arange"
] | [((464, 477), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (473, 477), True, 'import numpy as np\n'), ((293, 325), 'treeano.nodes.InputNode', 'tn.InputNode', (['"""i"""'], {'shape': '(None,)'}), "('i', shape=(None,))\n", (305, 325), True, 'import treeano.nodes as tn\n'), ((336, 398), 'treeano.sandbox.nodes.re... |
"""Random select substitution; save substituted structure and JSON info"""
import warnings
warnings.simplefilter('ignore')
import errno
import functools
import glob
import math
import os
import random
import re
import signal
import sys
import numpy as np
import pandas as pd
import pymatgen
import shry
from ase import... | [
"re.compile",
"shry.main.LabeledStructure.from_file",
"shry.core.Substitutor",
"signal.alarm",
"os.strerror",
"os.remove",
"pymatgen.core.composition.Composition",
"numpy.where",
"pymatgen.io.cif.CifParser",
"functools.wraps",
"os.path.isdir",
"pandas.DataFrame",
"warnings.simplefilter",
"... | [((91, 122), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (112, 122), False, 'import warnings\n'), ((2390, 2435), 're.compile', 're.compile', (['"""[A-z][a-z]*[0-9.\\\\+\\\\-]*[0-9.]*"""'], {}), "('[A-z][a-z]*[0-9.\\\\+\\\\-]*[0-9.]*')\n", (2400, 2435), False, 'import re\n')... |
from __future__ import print_function
from stompy.grid import unstructured_grid
import numpy as np
import logging
log=logging.getLogger(__name__)
from shapely import geometry
import xarray as xr
# TODO: migrate to xarray
from ...io import qnc
from ... import utils
# for now, only supports 2D/3D grid - no mix with 1D... | [
"logging.getLogger",
"numpy.diff",
"numpy.any",
"numpy.asanyarray",
"numpy.issubdtype",
"numpy.array",
"shapely.geometry.LineString",
"numpy.isnan",
"xarray.open_dataset"
] | [((118, 145), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'import logging\n'), ((13680, 13705), 'numpy.asanyarray', 'np.asanyarray', (['linestring'], {}), '(linestring)\n', (13693, 13705), True, 'import numpy as np\n'), ((14564, 14595), 'shapely.geometry.LineString',... |
import torch
import torch.nn.functional as F
import numpy as np
import math
import random
import sys
sys.path.append("../")
from causal_graphs.variable_distributions import _random_categ
from causal_discovery.datasets import InterventionalDataset
class GraphFitting(object):
def __init__(self, model, graph, num_... | [
"torch.bernoulli",
"math.ceil",
"random.shuffle",
"torch.eye",
"torch.sigmoid",
"numpy.argmax",
"torch.from_numpy",
"causal_graphs.variable_distributions._random_categ",
"numpy.random.multinomial",
"torch.arange",
"torch.nn.functional.cross_entropy",
"torch.no_grad",
"torch.zeros_like",
"c... | [((101, 123), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (116, 123), False, 'import sys\n'), ((4683, 4698), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4696, 4698), False, 'import torch\n'), ((9744, 9759), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9757, 9759), False, 'im... |
#this code is the workbench for q-learning
#it consists on a lifting particle that must reach a certain height
#it is only subjected to gravity
#Force applied to the particle might be fixed 9.9 or 9.7N
import numpy as np
import math
import random
import matplotlib.pyplot as plt
#INITIALIZE VARIABLES
####... | [
"numpy.ones",
"numpy.where",
"numpy.linspace",
"numpy.zeros",
"numpy.random.uniform",
"random.randint",
"numpy.random.permutation"
] | [((533, 589), 'numpy.linspace', 'np.linspace', (['(0)', '(Final_height + 10)', '(Final_height + 10 + 1)'], {}), '(0, Final_height + 10, Final_height + 10 + 1)\n', (544, 589), True, 'import numpy as np\n'), ((661, 691), 'numpy.linspace', 'np.linspace', (['(-10)', '(50)', 'n_speeds'], {}), '(-10, 50, n_speeds)\n', (672, ... |
from __future__ import print_function
import numpy as np
def IsPowerOfTwo(i):
"""Returns true if all entries of i are powers of two, False otherwise.
"""
return (i & (i - 1)) == 0 and i != 0
def Log2ofPowerof2(shape):
""" Returns powers of two exponent for each element of shape
"""
res = ... | [
"numpy.fft.irfft2",
"numpy.fft.rfft2",
"numpy.array",
"numpy.zeros",
"numpy.all"
] | [((320, 335), 'numpy.array', 'np.array', (['shape'], {}), '(shape)\n', (328, 335), True, 'import numpy as np\n'), ((923, 941), 'numpy.all', 'np.all', (['(N % 2 == 0)'], {}), '(N % 2 == 0)\n', (929, 941), True, 'import numpy as np\n'), ((1709, 1733), 'numpy.all', 'np.all', (['(LD_res == HD_res)'], {}), '(LD_res == HD_re... |
import numpy as np
import pytest # noqa: F401
from pandas_datareader._utils import RemoteDataError
from epymetheus.datasets import fetch_usstocks
# --------------------------------------------------------------------------------
def test_toomanyasset():
"""
Test if fetch_usstocks raises ValueError
when... | [
"epymetheus.datasets.fetch_usstocks",
"pytest.raises",
"numpy.isnan"
] | [((359, 384), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (372, 384), False, 'import pytest\n'), ((394, 423), 'epymetheus.datasets.fetch_usstocks', 'fetch_usstocks', ([], {'n_assets': '(1000)'}), '(n_assets=1000)\n', (408, 423), False, 'from epymetheus.datasets import fetch_usstocks\n'), (... |
import math
import numpy as np
import cv2
import sys
# # Implement the functions below.
def extract_red(image):
""" Returns the red channel of the input image. It is highly recommended to make a copy of the
input image in order to avoid modifying the original array. You can do this by calling:
temp_image... | [
"numpy.copy",
"numpy.mean",
"cv2.normalize",
"cv2.copyMakeBorder",
"numpy.std",
"numpy.floor",
"numpy.max",
"numpy.zeros",
"numpy.min",
"numpy.random.randn"
] | [((589, 612), 'numpy.copy', 'np.copy', (['image[:, :, 2]'], {}), '(image[:, :, 2])\n', (596, 612), True, 'import numpy as np\n'), ((1085, 1108), 'numpy.copy', 'np.copy', (['image[:, :, 1]'], {}), '(image[:, :, 1])\n', (1092, 1108), True, 'import numpy as np\n'), ((1588, 1611), 'numpy.copy', 'np.copy', (['image[:, :, 0]... |
import numpy as np
class IBM:
def __init__(self, config):
self.D = config["ibm"].get('vertical_mixing', 0) # Vertical mixing [m*2/s]
self.dt = config['dt']
self.x = np.array([])
self.y = np.array([])
self.pid = np.array([])
self.land_collision = config["ibm"].get('... | [
"numpy.intersect1d",
"numpy.random.rand",
"numpy.count_nonzero",
"numpy.array",
"numpy.round"
] | [((196, 208), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (204, 208), True, 'import numpy as np\n'), ((226, 238), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (234, 238), True, 'import numpy as np\n'), ((258, 270), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (266, 270), True, 'import numpy as np\n')... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 5 00:24:23 2021
@author: 34123
"""
import matplotlib.pyplot as plt
import numpy as np
import random
from scipy.stats import multivariate_normal
def plot_random_init_iris_sepal(df_full):
sepal_df = df_full.iloc[:,0:2]
sepal_df = np.array(sepal_df)
m1 = ... | [
"random.choice",
"matplotlib.pyplot.title",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"numpy.where",
"scipy.stats.multivariate_normal",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.axis",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.empty",
"matplotlib.py... | [((287, 305), 'numpy.array', 'np.array', (['sepal_df'], {}), '(sepal_df)\n', (295, 305), True, 'import numpy as np\n'), ((320, 343), 'random.choice', 'random.choice', (['sepal_df'], {}), '(sepal_df)\n', (333, 343), False, 'import random\n'), ((353, 376), 'random.choice', 'random.choice', (['sepal_df'], {}), '(sepal_df)... |
# -----------------------------------------------------------------------------------------------------------
# Funções auxiliares para predições
# -----------------------------------------------------------------------------------------------------------
import numpy as np
import pandas as pd
import matplotlib.pyplot... | [
"numpy.log2",
"pandas.concat",
"numpy.concatenate"
] | [((1084, 1122), 'pandas.concat', 'pd.concat', (['[train_coords, test_coords]'], {}), '([train_coords, test_coords])\n', (1093, 1122), True, 'import pandas as pd\n'), ((3661, 3699), 'pandas.concat', 'pd.concat', (['[train_coords, test_coords]'], {}), '([train_coords, test_coords])\n', (3670, 3699), True, 'import pandas ... |
import numpy as np
import torch
import torch.nn as nn
from habitat_baselines.common.utils import Flatten
from habitat_baselines.rl.models.simple_cnn import SimpleCNN
class Contiguous(nn.Module):
r"""Converts a tensor to be stored contiguously if it is not already so.
"""
def __init__(self):
super... | [
"habitat_baselines.common.utils.Flatten",
"torch.nn.ReLU",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"numpy.array",
"torch.nn.Linear",
"torch.nn.Module.__init__"
] | [((845, 869), 'torch.nn.Module.__init__', 'nn.Module.__init__', (['self'], {}), '(self)\n', (863, 869), True, 'import torch.nn as nn\n'), ((3679, 3703), 'torch.nn.Module.__init__', 'nn.Module.__init__', (['self'], {}), '(self)\n', (3697, 3703), True, 'import torch.nn as nn\n'), ((3948, 4019), 'numpy.array', 'np.array',... |
import unittest
import os, csv, json
import matplotlib.image as mpimg
import numpy as np
from numpy.testing import assert_array_equal
from skimage.measure import compare_ssim as ssim
from src.ea import evolutionary_algorithm
from src.ea.chromosome import Chromosome
class TestEA(unittest.TestCase):
def setUp(sel... | [
"src.ea.evolutionary_algorithm.EvolutionaryAlgorithm",
"skimage.measure.compare_ssim",
"matplotlib.image.imread",
"os.path.join",
"numpy.squeeze",
"os.path.dirname",
"src.ea.chromosome.Chromosome",
"json.load",
"csv.reader",
"numpy.testing.assert_array_equal"
] | [((343, 368), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (358, 368), False, 'import os, csv, json\n'), ((390, 437), 'os.path.join', 'os.path.join', (['rel_path', '"""test_images/00000.png"""'], {}), "(rel_path, 'test_images/00000.png')\n", (402, 437), False, 'import os, csv, json\n'), ((4... |
#!/usr/bin/python
"""
Utility script with functions used in lr classifier and cnn classifier.
For data preparation:
- get_train_test(): from dataframe, and specified columns, get train and test data and labels
- tokenize_text(): tokenize a list of texts, and return tokenized texts
- pad_texts(): add padding t... | [
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.utils.plot_model",
"numpy.array",
"numpy.arange",
"sklearn.preprocessing.LabelBinarizer",
"os.path.exists",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.style.use",
"contextlib.redirect_stdout"... | [((2120, 2180), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': 'test_size', 'random_state': '(42)'}), '(X, y, test_size=test_size, random_state=42)\n', (2136, 2180), False, 'from sklearn.model_selection import train_test_split\n'), ((2552, 2568), 'sklearn.preprocessing.LabelB... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 11 15:52:17 2022
@author: sylvain
"""
import numpy as np
from calendar import monthrange
import pandas as pd
# Hypotheses
eta_pp = 0.7 # Average efficiency of the plunger pumps
eta_surpr = 0.4 # average efficiency of the "surpresseur" pum... | [
"numpy.zeros",
"calendar.monthrange",
"pandas.read_csv",
"pandas.date_range"
] | [((1467, 1528), 'pandas.read_csv', 'pd.read_csv', (['"""PV_casamance - daily profiles.csv"""'], {'index_col': '(0)'}), "('PV_casamance - daily profiles.csv', index_col=0)\n", (1478, 1528), True, 'import pandas as pd\n'), ((2437, 2449), 'numpy.zeros', 'np.zeros', (['(24)'], {}), '(24)\n', (2445, 2449), True, 'import num... |
from qgis.core import *
from osgeo import gdal
import math
import numpy as np
import os
MARGIN = 0.01
def weightedFunction(x, y, x0, y0, weight):
# the current weighted Function is a simple sqrt((x-x0)^1 + (y-y0)^2)/w
return math.sqrt((x - x0) ** 2 + (y - y0) ** 2) / weight
#Get the points vector layer
pointsVecto... | [
"osgeo.gdal.Open",
"math.sqrt",
"numpy.zeros",
"os.system",
"osgeo.gdal.GetDriverByName"
] | [((806, 922), 'os.system', 'os.system', (['(\'gdal_rasterize -a z -ts 1000 1000 \' + extent_args + \' -l points "\' + sys.\n argv + \'" "./rasterPoints"\')'], {}), '(\'gdal_rasterize -a z -ts 1000 1000 \' + extent_args +\n \' -l points "\' + sys.argv + \'" "./rasterPoints"\')\n', (815, 922), False, 'import os\n')... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.stats import probplot, pearsonr
class PreparedData:
def __init__(self, inn):
self.original_data = inn
self.prepared_data = None
self.feature_labels = None
self.t... | [
"pandas.read_csv",
"numpy.max",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.gridspec.GridSpec",
"numpy.around",
"numpy.min",
"matplotlib.pyplot.subplot",
"pandas.to_datetime"
] | [((2381, 2411), 'pandas.read_csv', 'pd.read_csv', (['RAW_DATA'], {'sep': '""","""'}), "(RAW_DATA, sep=',')\n", (2392, 2411), True, 'import pandas as pd\n'), ((2709, 2721), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2719, 2721), True, 'import matplotlib.pyplot as plt\n'), ((2733, 2756), 'matplotlib.gri... |
import pkg_resources
import pathlib
import random
import numpy
import pandas
import json
import yaml
from collections import defaultdict
def define_amplicon(tmp, amplicons, reference_genome):
chosen_amplicon = tmp['name']
row = amplicons[amplicons.name == chosen_amplicon]
# PWF: this used to be >= but end... | [
"pandas.read_csv",
"pathlib.Path",
"numpy.logical_not",
"pkg_resources.resource_filename",
"numpy.sum",
"numpy.array",
"yaml.safe_load",
"collections.defaultdict",
"json.load"
] | [((2890, 2980), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['"""gpas_covid_synthetic_reads"""', '"""data/cov-lineages.csv"""'], {}), "('gpas_covid_synthetic_reads',\n 'data/cov-lineages.csv')\n", (2921, 2980), False, 'import pkg_resources\n'), ((3002, 3031), 'pandas.read_csv', 'pandas.rea... |
import warnings
from math import ceil
import numpy as np
import openmdao.api as om
from wisdem.landbosse.model.Manager import Manager
from wisdem.landbosse.model.DefaultMasterInputDict import DefaultMasterInputDict
from wisdem.landbosse.landbosse_omdao.OpenMDAODataframeCache import OpenMDAODataframeCache
from wisdem.l... | [
"wisdem.landbosse.landbosse_omdao.OpenMDAODataframeCache.OpenMDAODataframeCache.read_all_sheets_from_xlsx",
"wisdem.landbosse.landbosse_omdao.WeatherWindowCSVReader.read_weather_window",
"math.ceil",
"wisdem.landbosse.model.Manager.Manager",
"warnings.catch_warnings",
"wisdem.landbosse.model.DefaultMaster... | [((401, 426), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (424, 426), False, 'import warnings\n'), ((432, 501), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""numpy.ufunc size changed"""'}), "('ignore', message='numpy.ufunc size changed')\n", (455, 5... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from logger import setup_logger
from model import BiSeNet
from face_dataset import FaceMask
from loss import OhemCELoss
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.distributed as dist
import os
imp... | [
"loss.OhemCELoss",
"logger.setup_logger",
"numpy.array",
"torch.squeeze",
"os.path.exists",
"model.BiSeNet",
"os.listdir",
"numpy.where",
"torch.unsqueeze",
"numpy.max",
"torchvision.transforms.ToTensor",
"cv2.cvtColor",
"torchvision.transforms.Normalize",
"cv2.resize",
"face_dataset.Fac... | [((1175, 1187), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (1183, 1187), True, 'import numpy as np\n'), ((1311, 1405), 'cv2.resize', 'cv2.resize', (['vis_parsing_anno', 'None'], {'fx': 'stride', 'fy': 'stride', 'interpolation': 'cv2.INTER_NEAREST'}), '(vis_parsing_anno, None, fx=stride, fy=stride, interpolation... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 17:26:11 2019
@author: samghosal
"""
from __future__ import division
"""----------------------------------------------------------------------------------------------
README: Simple Python Code for Testing and evaluating the trained CNN mo... | [
"matplotlib.pyplot.ylabel",
"gzip.open",
"sklearn.metrics.classification_report",
"keras.utils.to_categorical",
"numpy.arange",
"matplotlib.pyplot.imshow",
"keras.backend.image_data_format",
"tensorflow.Session",
"matplotlib.pyplot.xlabel",
"numpy.random.seed",
"tensorflow.ConfigProto",
"sklea... | [((1102, 1144), 'keras.backend.tensorflow_backend._get_available_gpus', 'K.tensorflow_backend._get_available_gpus', ([], {}), '()\n', (1142, 1144), True, 'from keras import backend as K\n'), ((1154, 1193), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'GPU': 1}"}), "(device_count={'GPU': 1})\n", (... |
from portfolio import Portfolio, PM
import datetime as dt
from collections import OrderedDict
import utility
import copy
import numpy as np
class Backtester:
def __init__(self, universeObj, start=None, end=None):
if start is None:
start = universeObj.dateRange[0]
if end is None:
... | [
"collections.OrderedDict",
"portfolio.Portfolio",
"copy.deepcopy",
"portfolio.PM.getPortfolioDateRange",
"numpy.datetime64",
"datetime.timedelta"
] | [((937, 970), 'copy.deepcopy', 'copy.deepcopy', (['self.universe.data'], {}), '(self.universe.data)\n', (950, 970), False, 'import copy\n'), ((1771, 1784), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1782, 1784), False, 'from collections import OrderedDict\n'), ((588, 632), 'portfolio.PM.getPortfolioDa... |
# Graphics for Exploratory Analysis Script
# ==============================================================================
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# ^^^ pyforest auto-imports - don't write above this line
# ========================================... | [
"numpy.abs",
"seaborn.regplot",
"matplotlib.pyplot.savefig",
"numpy.sqrt",
"matplotlib.pyplot.xticks",
"seaborn.distplot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"seaborn.diverging_palette",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.bar",
"seab... | [((949, 997), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(1)', 'figsize': '(15, 10)'}), '(nrows=3, ncols=1, figsize=(15, 10))\n', (961, 997), True, 'import matplotlib.pyplot as plt\n'), ((1002, 1120), 'seaborn.distplot', 'sns.distplot', (['df[target]'], {'hist': '(False)', 'rug': '(Tr... |
import os
import csv
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import cv2
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Conv2D, MaxPooling2D, Cropping2D, Dropout
import pickle
from keras.callbacks import TensorBoard, ... | [
"keras.layers.Conv2D",
"pickle.dump",
"keras.layers.Flatten",
"keras.callbacks.ModelCheckpoint",
"cv2.flip",
"sklearn.model_selection.train_test_split",
"sklearn.utils.shuffle",
"keras.layers.Lambda",
"os.path.join",
"keras.models.Sequential",
"keras.callbacks.TensorBoard",
"numpy.array",
"k... | [((735, 775), 'sklearn.model_selection.train_test_split', 'train_test_split', (['samples'], {'test_size': '(0.2)'}), '(samples, test_size=0.2)\n', (751, 775), False, 'from sklearn.model_selection import train_test_split\n'), ((1974, 1986), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1984, 1986), False, ... |
from numpy import genfromtxt
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
''' ResNet-56 '''
train_error_52 = './epoch_error_train_52.csv'
train_error_52 = genfromtxt(train_error_52, delimiter=',')
valid_error_52 = './epoch_error_valid_52.csv'
valid_error_52 = genfromtxt(valid_error_52, de... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ticklabel_format",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylim",
"numpy.genfrom... | [((186, 227), 'numpy.genfromtxt', 'genfromtxt', (['train_error_52'], {'delimiter': '""","""'}), "(train_error_52, delimiter=',')\n", (196, 227), False, 'from numpy import genfromtxt\n'), ((291, 332), 'numpy.genfromtxt', 'genfromtxt', (['valid_error_52'], {'delimiter': '""","""'}), "(valid_error_52, delimiter=',')\n", (... |
"""Collection of classes for processed datasets."""
import os
import random
from glob import glob
from typing import List, Tuple
import numpy as np
import torch.utils.data
import torchvision.transforms
from facenet_pytorch import fixed_image_standardization
from torch import Tensor
from src.features import transform
... | [
"random.shuffle",
"os.path.join",
"os.path.splitext",
"src.features.transform.images_to_tensors",
"os.path.basename",
"numpy.load"
] | [((827, 850), 'numpy.load', 'np.load', (['self._filepath'], {}), '(self._filepath)\n', (834, 850), True, 'import numpy as np\n'), ((1257, 1293), 'src.features.transform.images_to_tensors', 'transform.images_to_tensors', (['*images'], {}), '(*images)\n', (1284, 1293), False, 'from src.features import transform\n'), ((20... |
'''
Created on Apr 15, 2016
Evaluate the performance of Top-K recommendation:
Protocol: leave-1-out evaluation
Measures: Hit Ratio and NDCG
(more details are in: <NAME>, et al. Fast Matrix Factorization for Online Recommendation with Implicit Feedback. SIGIR'16)
@author: hexiangnan
'''
import math
... | [
"numpy.array",
"time.time",
"math.log"
] | [((4202, 4208), 'time.time', 'time', ([], {}), '()\n', (4206, 4208), False, 'from time import time\n'), ((1067, 1082), 'numpy.array', 'np.array', (['items'], {}), '(items)\n', (1075, 1082), True, 'import numpy as np\n'), ((1767, 1782), 'numpy.array', 'np.array', (['items'], {}), '(items)\n', (1775, 1782), True, 'import... |
import numpy as np
import scipy.io as spio
from . import calc_R1_function_python_GEN
def calculate_r1_factor(proj, proj_angles, atom_positions, atomic_spec, atomic_numbers,
resolution,z_direction, b_factor, h_factor, axis_convention):
Result = calc_R1_function_python_GEN.calc_R1_function_... | [
"numpy.array"
] | [((403, 421), 'numpy.array', 'np.array', (['b_factor'], {}), '(b_factor)\n', (411, 421), True, 'import numpy as np\n'), ((423, 441), 'numpy.array', 'np.array', (['h_factor'], {}), '(h_factor)\n', (431, 441), True, 'import numpy as np\n'), ((443, 468), 'numpy.array', 'np.array', (['axis_convention'], {}), '(axis_convent... |
import json
import numpy as np
import matplotlib.pyplot as plt
def to_seconds(s):
hr, min, sec = [float(x) for x in s.split(':')]
return hr*3600 + min*60 + sec
def extract(gst_log, script_log, debug=False):
with open(gst_log, "r") as f:
lines = f.readlines()
id_s = "create:<v4l2src"
st_s ... | [
"matplotlib.pyplot.legend",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"json.load",
"json.dump",
"matplotlib.pyplot.show"
] | [((2646, 2667), 'matplotlib.pyplot.figure', 'plt.figure', (['"""v4l2src"""'], {}), "('v4l2src')\n", (2656, 2667), True, 'import matplotlib.pyplot as plt\n'), ((2937, 2949), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2947, 2949), True, 'import matplotlib.pyplot as plt\n'), ((2954, 2972), 'matplotlib.py... |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
data = np.load("scores.npy", allow_pickle=True).item()
fig, axs = plt.subplots(3, 1, figsize=(20, 20))
for i, score in enumerate(["insert", "delete", "irof"]):
ax = axs[i]
df = data[score]
for key in df:
if key=="rbm_flip_det... | [
"seaborn.distplot",
"numpy.load",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((141, 177), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'figsize': '(20, 20)'}), '(3, 1, figsize=(20, 20))\n', (153, 177), True, 'import matplotlib.pyplot as plt\n'), ((582, 592), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (590, 592), True, 'import matplotlib.pyplot as plt\n'), ((81, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 14:45:29 2019
@author: txuslopez
"""
'''
This Script is a RUN function which uses the cellular automation defined in 'biosystem.py' to classify data from the popular Iris Flower dataset. Error between predicted results is then calculated and c... | [
"sklearn.model_selection.GridSearchCV",
"numpy.sqrt",
"pandas.read_csv",
"sklearn.neighbors.KNeighborsClassifier",
"psutil.virtual_memory",
"scipy.stats.friedmanchisquare",
"numpy.array",
"numpy.nanmean",
"numpy.rot90",
"copy.deepcopy",
"skmultiflow.drift_detection.page_hinkley.PageHinkley",
"... | [((1422, 1449), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (1428, 1449), True, 'import matplotlib.pyplot as plt\n'), ((1450, 1480), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (1456, 1480), True, '... |
#!/usr/bin/env python
#python 3 compatibility
from __future__ import print_function
import rasterio
from scipy.io import netcdf
import numpy as np
import subprocess
import sys
from gdal import GDALGrid
from gmt import GMTGrid
def getCommandOutput(cmd):
"""
Internal method for calling external command.
@... | [
"subprocess.Popen",
"gmt.GMTGrid",
"gdal.GDALGrid.load",
"gmt.GMTGrid.load",
"numpy.arange"
] | [((520, 606), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (536, 606), False, 'import subprocess\n'), ((1119, 1141), 'gmt.GMTGrid', 'GMTGrid', (['data', 'geod... |
import numpy as np
import matplotlib.pyplot as plt
def gaussian_func(sigma, x):
return 1 / np.sqrt(2 * np.pi * (sigma ** 2)) * np.exp(-(x ** 2) / (2 * (sigma ** 2)))
def gaussian_random_generator(sigma=5, numbers=100000):
uniform_random_numbers = np.random.rand(numbers, 2)
rho = sigma * np.sqrt(-2 * np.... | [
"numpy.sqrt",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.log",
"numpy.max",
"numpy.exp",
"numpy.linspace",
"numpy.cos",
"numpy.min",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((259, 285), 'numpy.random.rand', 'np.random.rand', (['numbers', '(2)'], {}), '(numbers, 2)\n', (273, 285), True, 'import numpy as np\n'), ((555, 586), 'numpy.min', 'np.min', (['gaussian_random_numbers'], {}), '(gaussian_random_numbers)\n', (561, 586), True, 'import numpy as np\n'), ((603, 634), 'numpy.max', 'np.max',... |
import time
import edgeiq
import cv2
import numpy as np
import os
"""
Instance segmenataiom application used to count unique instances of bottles.
Instance Segmenataiom is currently not part of the alwaysai API's or Model Catalog.
This application demostartes how to implement instance segmenataiom using the
alwaysai pl... | [
"cv2.dnn.blobFromImage",
"cv2.rectangle",
"edgeiq.WebcamVideoStream",
"edgeiq.Streamer",
"cv2.dnn.readNetFromTensorflow",
"time.sleep",
"cv2.putText",
"numpy.array",
"numpy.random.seed",
"cv2.resize",
"edgeiq.FPS"
] | [((531, 549), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (545, 549), True, 'import numpy as np\n'), ((901, 955), 'cv2.dnn.readNetFromTensorflow', 'cv2.dnn.readNetFromTensorflow', (['weightsPath', 'configPath'], {}), '(weightsPath, configPath)\n', (930, 955), False, 'import cv2\n'), ((1117, 1129), ... |
# imports
import numpy as np
import matplotlib.pyplot as plt
""" Implementation of the Heaviside step Function
Defined as the integral of the dirac delta function."""
def _unit_step(n):
return 0 if n < 0 else 1
# vectorize function for increased performance
unit_step = np.vectorize(_unit_step)
# define inpu... | [
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.stem",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"numpy.vectorize",
"matplotlib.pyplot.step",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((281, 305), 'numpy.vectorize', 'np.vectorize', (['_unit_step'], {}), '(_unit_step)\n', (293, 305), True, 'import numpy as np\n'), ((333, 354), 'numpy.arange', 'np.arange', (['(-10)', '(11)', '(1)'], {}), '(-10, 11, 1)\n', (342, 354), True, 'import numpy as np\n'), ((405, 417), 'matplotlib.pyplot.figure', 'plt.figure'... |
import os
import random
import numpy as np
class EA_Util:
def __init__(self, gen_size, pop_size=30, eval_func=None, max_gen=50, early_stop=0):
self.gen_size = gen_size
self.pop_size = pop_size
self.max_gen = max_gen
self.early_stop = early_stop
if eval_func == None:... | [
"random.sample",
"random.choice",
"numpy.argsort",
"numpy.random.uniform",
"random.random"
] | [((1524, 1548), 'numpy.argsort', 'np.argsort', (['self.fitness'], {}), '(self.fitness)\n', (1534, 1548), True, 'import numpy as np\n'), ((627, 664), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'self.gen_size'}), '(size=self.gen_size)\n', (644, 664), True, 'import numpy as np\n'), ((1216, 1231), 'random.r... |
import numpy
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ic.brokenimf import *
# Instead of random, use evenly distributed numbers, just for testing
default_options = dict(random=False)
class TestMultiplePartIMF(amusetest.TestCase):
def test1(self):
print(... | [
"numpy.array"
] | [((1487, 1510), 'numpy.array', 'numpy.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (1498, 1510), False, 'import numpy\n')] |
#!/usr/bin/python
from typing import Dict, Union, Tuple, List
import numpy as np
from ..parameters import POI
from ..fitutils.api_check import is_valid_loss, is_valid_fitresult, is_valid_minimizer
from ..fitutils.api_check import is_valid_data, is_valid_pdf
from ..fitutils.utils import pll
"""
Module defining the bas... | [
"numpy.where",
"numpy.zeros",
"numpy.isnan",
"numpy.meshgrid",
"numpy.isinf"
] | [((16237, 16254), 'numpy.zeros', 'np.zeros', (['q.shape'], {}), '(q.shape)\n', (16245, 16254), True, 'import numpy as np\n'), ((16350, 16379), 'numpy.where', 'np.where', (['condition', 'zeros', 'q'], {}), '(condition, zeros, q)\n', (16358, 16379), True, 'import numpy as np\n'), ((16083, 16094), 'numpy.isnan', 'np.isnan... |
import numpy
from scipy.optimize import differential_evolution
def optim_matrix(A, B):
X = A.points.T
Y = B.points.T
bounds = [(-999999.0, 999999.0)] * 4
def f(p):
Z = numpy.array(p)
Z.shape = (2, 2)
y = numpy.dot(Z, X)
return numpy.linalg.norm(y - Y)
return dif... | [
"scipy.optimize.differential_evolution",
"numpy.exp",
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
] | [((317, 350), 'scipy.optimize.differential_evolution', 'differential_evolution', (['f', 'bounds'], {}), '(f, bounds)\n', (339, 350), False, 'from scipy.optimize import differential_evolution\n'), ((197, 211), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (208, 211), False, 'import numpy\n'), ((249, 264), 'numpy.d... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"numpy.random.default_rng",
"jax.numpy.arange",
"absl.testing.absltest.main",
"absl.testing.parameterized.named_parameters",
"jax.numpy.array",
"jax.tree_util.tree_map",
"tree_math.Vector",
"jax.tree_util.tree_leaves",
"jax.numpy.ones"
] | [((1532, 1672), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["*({'testcase_name': op.__name__, 'op': op} for op in [operator.pos,\n operator.neg, abs, operator.invert])"], {}), "(*({'testcase_name': op.__name__, 'op': op} for\n op in [operator.pos, operator.neg, abs, operator... |
import numpy as np
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from typing import *
import pandas as pd
import seaborn as sns
import math
sns.set()
class Accuracy(object):
def at_radii(self, radii: np.ndarray):
raise NotImplementedError()
class ApproximateAccuracy(Accur... | [
"seaborn.set",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.gca",
"math.log",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figu... | [((172, 181), 'seaborn.set', 'sns.set', ([], {}), '()\n', (179, 181), True, 'import seaborn as sns\n'), ((1961, 2012), 'numpy.arange', 'np.arange', (['(0)', '(max_radius + radius_step)', 'radius_step'], {}), '(0, max_radius + radius_step, radius_step)\n', (1970, 2012), True, 'import numpy as np\n'), ((2017, 2029), 'mat... |
from numpy import random
from matplotlib import pyplot
random.seed(12345)
sequence = random.normal(size=1000000, loc=30, scale=5)
pyplot.hist(sequence, bins=20)
pyplot.show()
| [
"numpy.random.normal",
"matplotlib.pyplot.hist",
"numpy.random.seed",
"matplotlib.pyplot.show"
] | [((56, 74), 'numpy.random.seed', 'random.seed', (['(12345)'], {}), '(12345)\n', (67, 74), False, 'from numpy import random\n'), ((86, 130), 'numpy.random.normal', 'random.normal', ([], {'size': '(1000000)', 'loc': '(30)', 'scale': '(5)'}), '(size=1000000, loc=30, scale=5)\n', (99, 130), False, 'from numpy import random... |
from collections import defaultdict
from math import *
from itertools import product
from logbook import Logger
import cv2
import numpy as np
import networkx as nx
import math
from tqdm import tqdm
# from palettable.cartocolors.qualitative import Pastel_10 as COLORS
from suppose.common import timing
from suppose.camer... | [
"numpy.sqrt",
"networkx.connected_component_subgraphs",
"cv2.projectPoints",
"numpy.ascontiguousarray",
"cv2.triangulatePoints",
"numpy.array",
"math.log",
"numpy.linalg.norm",
"pandas.read_pickle",
"logbook.Logger",
"networkx.DiGraph",
"cv2.convertPointsFromHomogeneous",
"pandas.DataFrame.f... | [((376, 392), 'logbook.Logger', 'Logger', (['"""pose3d"""'], {}), "('pose3d')\n", (382, 392), False, 'from logbook import Logger\n'), ((703, 790), 'cv2.undistortPoints', 'cv2.undistortPoints', (['pts2', 'camera_matrix', 'distortion_coefficients'], {'P': 'camera_matrix'}), '(pts2, camera_matrix, distortion_coefficients,... |
from abc import ABC, abstractmethod
from collections import OrderedDict
import numpy as np
import pandas as pd
from .mask import mask_module
from .modules import MaskedModule
from .utils import get_params
import tempfile, pathlib
import torch
class Pruning(ABC):
"""Base class for Pruning operations
"""
... | [
"tempfile.TemporaryDirectory",
"collections.OrderedDict",
"numpy.prod",
"pathlib.Path",
"torch.load",
"torch.save",
"pandas.DataFrame"
] | [((3099, 3128), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3126, 3128), False, 'import tempfile, pathlib\n'), ((3148, 3179), 'pathlib.Path', 'pathlib.Path', (['self._handle.name'], {}), '(self._handle.name)\n', (3160, 3179), False, 'import tempfile, pathlib\n'), ((3490, 3557), 'tor... |
"""
__Author__ : <NAME>
__desc__ : file for training an NCC model based on the data which has been genereated
"""
import tensorflow as tf
import json
import os
from collections import Counter
import random
import numpy as np
import pickle
class NCCTrain(object):
def __init__(self,fileName,trainSplitR... | [
"numpy.array",
"tensorflow.control_dependencies",
"tensorflow.nn.dropout",
"tensorflow.reduce_mean",
"numpy.mean",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.concat",
"tensorflow.nn.sigmoid",
"os.path.isdir",
"os.mkdir",
"numpy.concatenate",
"tensorflow.layers.batch_normaliz... | [((1605, 1640), 'os.path.join', 'os.path.join', (['self.saveDir', '"""model"""'], {}), "(self.saveDir, 'model')\n", (1617, 1640), False, 'import os\n'), ((1661, 1698), 'os.path.join', 'os.path.join', (['self.saveDir', '"""summary"""'], {}), "(self.saveDir, 'summary')\n", (1673, 1698), False, 'import os\n'), ((1706, 173... |
"""A module which implements the time frequency estimation.
Authors : <NAME> <<EMAIL>>
License : BSD 3-clause
Multitaper wavelet method
"""
import warnings
from math import sqrt
import numpy as np
from scipy import linalg
from scipy.fftpack import fftn, ifftn
from .utils import logger, verbose
from .dpss import dp... | [
"numpy.convolve",
"numpy.log10",
"matplotlib.pyplot.ylabel",
"math.sqrt",
"scipy.fftpack.fftn",
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.xlabel",
"numpy.asarray",
"numpy.exp",
"numpy.empty",
"warnings.warn",
"numpy.abs",... | [((1280, 1303), 'numpy.atleast_1d', 'np.atleast_1d', (['n_cycles'], {}), '(n_cycles)\n', (1293, 1303), True, 'import numpy as np\n'), ((2512, 2531), 'numpy.asarray', 'np.asarray', (['newsize'], {}), '(newsize)\n', (2522, 2531), True, 'import numpy as np\n'), ((2547, 2566), 'numpy.array', 'np.array', (['arr.shape'], {})... |
#!/usr/bin/env python3
'''Test total energies for a small set of systems.'''
import eminus
from eminus import Atoms, read_xyz, SCF
from numpy.testing import assert_allclose
# Total energies calculated with PWDFT.jl for He, H2, LiH, CH4, and Ne with same parameters as below
Etot_ref = [-2.54356557, -1.10228799, -0.7659... | [
"numpy.testing.assert_allclose",
"eminus.Atoms",
"eminus.read_xyz",
"eminus.SCF"
] | [((574, 606), 'eminus.read_xyz', 'read_xyz', (['f"""{path}/{system}.xyz"""'], {}), "(f'{path}/{system}.xyz')\n", (582, 606), False, 'from eminus import Atoms, read_xyz, SCF\n'), ((619, 661), 'eminus.Atoms', 'Atoms', ([], {'atom': 'atom', 'X': 'X', 'a': 'a', 'ecut': 'ecut', 's': 's'}), '(atom=atom, X=X, a=a, ecut=ecut, ... |
import numpy as np
import pytest
from probnum.diffeq.perturbedsolvers import _perturbation_functions
random_state = np.random.mtrand.RandomState(seed=1)
@pytest.fixture
def step():
return 0.2
@pytest.fixture
def solver_order():
return 4
@pytest.fixture
def noise_scale():
return 1
@pytest.fixture
d... | [
"pytest.mark.parametrize",
"numpy.testing.assert_allclose",
"numpy.random.mtrand.RandomState",
"numpy.sum"
] | [((118, 154), 'numpy.random.mtrand.RandomState', 'np.random.mtrand.RandomState', ([], {'seed': '(1)'}), '(seed=1)\n', (146, 154), True, 'import numpy as np\n'), ((356, 485), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""perturb_fct"""', '[_perturbation_functions.perturb_uniform, _perturbation_functions.\n... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
from rl import online_learners as ol
from rl.online_learners import base_algorithms as balg
def get_learner(optimizer, policy, scheduler, max_kl=None):
""" Return an first-order optimizer. """
x0 ... | [
"rl.online_learners.base_algorithms.Adam",
"numpy.random.geometric",
"numpy.where",
"rl.online_learners.base_algorithms.RobustAdaptiveSecondOrderUpdate",
"numpy.random.multinomial",
"numpy.sum",
"rl.online_learners.base_algorithms.AdaptiveSecondOrderUpdate",
"rl.online_learners.base_algorithms.TrustRe... | [((2057, 2082), 'numpy.random.geometric', 'np.random.geometric', (['prob'], {}), '(prob)\n', (2076, 2082), True, 'import numpy as np\n'), ((1259, 1269), 'numpy.sum', 'np.sum', (['p0'], {}), '(p0)\n', (1265, 1269), True, 'import numpy as np\n'), ((1306, 1334), 'numpy.random.multinomial', 'np.random.multinomial', (['(1)'... |
import os
import numpy as np
import pandas as pd
import h5py
from bmtk.utils.sonata.utils import add_hdf5_magic, add_hdf5_version
def create_single_pop_h5():
h5_file_old = h5py.File('spike_files/spikes.old.h5', 'r')
node_ids = h5_file_old['/spikes/gids']
timestamps = h5_file_old['/spikes/timestamps']
... | [
"pandas.Series",
"pandas.read_csv",
"bmtk.utils.sonata.utils.add_hdf5_version",
"bmtk.utils.sonata.utils.add_hdf5_magic",
"os.path.join",
"h5py.File",
"numpy.uint64"
] | [((179, 222), 'h5py.File', 'h5py.File', (['"""spike_files/spikes.old.h5"""', '"""r"""'], {}), "('spike_files/spikes.old.h5', 'r')\n", (188, 222), False, 'import h5py\n'), ((1797, 1852), 'pandas.read_csv', 'pd.read_csv', (['"""spike_files/spikes.multipop.csv"""'], {'sep': '""" """'}), "('spike_files/spikes.multipop.csv'... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | [
"jax.vmap",
"collections.namedtuple",
"jax.nn.sigmoid",
"flax.linen.initializers.xavier_uniform",
"flax.linen.Dense",
"dopamine.jax.networks.preprocess_atari_inputs",
"flax.linen.Conv",
"optax.apply_updates",
"dopamine.jax.agents.dqn.dqn_agent.target_q",
"functools.partial",
"numpy.linspace",
... | [((1134, 1227), 'collections.namedtuple', 'collections.namedtuple', (['"""dqn_network_with_random_rewards"""', "['q_values', 'aux_prediction']"], {}), "('dqn_network_with_random_rewards', ['q_values',\n 'aux_prediction'])\n", (1156, 1227), False, 'import collections\n'), ((5571, 5628), 'functools.partial', 'functool... |
import numpy as np
from scipy.optimize import minimize_scalar
import statsmodels.regression.linear_model as lm
from astropy.visualization import PercentileInterval
class InputError(Exception):
"""Raised when a required parameter is not included."""
def __init__(self, expression, message):
self.express... | [
"numpy.abs",
"statsmodels.regression.linear_model.WLS",
"numpy.any",
"numpy.array",
"numpy.sum",
"scipy.optimize.minimize_scalar",
"astropy.visualization.PercentileInterval"
] | [((707, 739), 'numpy.array', 'np.array', (['[(True) for _ in data]'], {}), '([(True) for _ in data])\n', (715, 739), True, 'import numpy as np\n'), ((512, 574), 'numpy.sum', 'np.sum', (['((data[mask] - x * model[mask]) ** 2 / sigma[mask] ** 2)'], {}), '((data[mask] - x * model[mask]) ** 2 / sigma[mask] ** 2)\n', (518, ... |
import socket
import sys
from ledapy.deconvolution import sdeconv_analysis
from numpy import array as npa
# import cvxEDA as cvx
import numpy as np
import neurokit2 as nk
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 8052)... | [
"numpy.array",
"neurokit2.eda_process",
"socket.socket"
] | [((204, 253), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (217, 253), False, 'import socket\n'), ((1158, 1178), 'numpy.array', 'npa', (['data_float_list'], {}), '(data_float_list)\n', (1161, 1178), True, 'from numpy import array as npa\n'),... |
import os
import shutil
import readdy
import tempfile
import unittest
import numpy as np
class TestTopologyReactionCount(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.dir = tempfile.mkdtemp("test-topology-reaction-count")
@classmethod
def tearDownClass(cls) -> None:
... | [
"numpy.random.normal",
"numpy.testing.assert_equal",
"readdy.Trajectory",
"readdy.StructuralReactionRecipe",
"tempfile.mkdtemp",
"shutil.rmtree",
"unittest.main",
"readdy.ReactionDiffusionSystem",
"numpy.testing.assert_array_equal"
] | [((3697, 3712), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3710, 3712), False, 'import unittest\n'), ((213, 261), 'tempfile.mkdtemp', 'tempfile.mkdtemp', (['"""test-topology-reaction-count"""'], {}), "('test-topology-reaction-count')\n", (229, 261), False, 'import tempfile\n'), ((324, 366), 'shutil.rmtree', '... |
import json
import os
import time
from abc import ABC
import numpy as np
import torch
import torchvision
from modules.trainer.regularization import weight_clipping
from tensorboardX import SummaryWriter
from torch.utils.data import DataLoader
from tqdm import tqdm
import utils
from modules.evaluator import Evaluation... | [
"utils.makedir_if_not_exist",
"os.path.exists",
"numpy.random.normal",
"time.asctime",
"modules.evaluator.Evaluation",
"tensorboardX.SummaryWriter",
"numpy.mean",
"json.dumps",
"os.path.join",
"modules.trainer.regularization.weight_clipping",
"torch.no_grad",
"numpy.array",
"utils.print_wlin... | [((709, 734), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (732, 734), False, 'import torch\n'), ((800, 825), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (823, 825), False, 'import torch\n'), ((1033, 1047), 'time.asctime', 'time.asctime', ([], {}), '()\n', (1045, 1... |
# Copyright 2020 NXP.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and th... | [
"pyqtgraph.Qt.QtGui.QVBoxLayout",
"pyqtgraph.Qt.QtGui.QWidget",
"numpy.column_stack",
"pyqtgraph.Qt.QtGui.QDialog",
"time.sleep",
"pyqtgraph.Qt.QtWidgets.QAction",
"pyqtgraph.Qt.QtGui.QApplication",
"pyqtgraph.Qt.QtGui.QFileDialog.getSaveFileName",
"pyqtgraph.mkPen",
"copy.deepcopy",
"pyqtgraph.... | [((2325, 2362), 'pyqtgraph.setConfigOption', 'pg.setConfigOption', (['"""background"""', '"""w"""'], {}), "('background', 'w')\n", (2343, 2362), True, 'import pyqtgraph as pg\n'), ((2363, 2400), 'pyqtgraph.setConfigOption', 'pg.setConfigOption', (['"""foreground"""', '"""k"""'], {}), "('foreground', 'k')\n", (2381, 240... |
from __future__ import print_function # Python 2.x
import os
import numpy as np
import pandas as pd
import h5py
import sys
import math
from fnmatch import fnmatch
# helper functions klusta analysis pipeline
def get_param_file(filename,params_folder):
found = False
params = []
for path, subdirs, files in ... | [
"numpy.mean",
"os.path.exists",
"numpy.repeat",
"os.makedirs",
"numpy.searchsorted",
"h5py.File",
"numpy.array",
"math.fabs",
"sys.exit",
"pandas.DataFrame",
"numpy.cumsum",
"os.walk",
"sys.stdout.write"
] | [((320, 342), 'os.walk', 'os.walk', (['params_folder'], {}), '(params_folder)\n', (327, 342), False, 'import os\n'), ((6986, 7014), 'h5py.File', 'h5py.File', (['kwx_filename', '"""r"""'], {}), "(kwx_filename, 'r')\n", (6995, 7014), False, 'import h5py\n'), ((8032, 8063), 'numpy.cumsum', 'np.cumsum', (['samples_sessions... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 12:31:14 2020
@author: nastavirs
"""
import tensorflow as tf
import numpy as np
def xavier_init(self, size):
in_dim = size[0]
out_dim = size[1]
xavier_stddev = np.sqrt(2/(in_dim + out_dim))
return tf.Variable(tf.trunc... | [
"numpy.sqrt",
"tensorflow.truncated_normal"
] | [((254, 285), 'numpy.sqrt', 'np.sqrt', (['(2 / (in_dim + out_dim))'], {}), '(2 / (in_dim + out_dim))\n', (261, 285), True, 'import numpy as np\n'), ((312, 372), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[in_dim, out_dim]'], {'stddev': 'xavier_stddev'}), '([in_dim, out_dim], stddev=xavier_stddev)\n', (331... |
import logging
import numpy as np
from scipy.stats import nbinom, poisson, binom
from scipy.special import gamma, factorial, gammaln, logsumexp, hyp2f1, hyp1f1, hyperu, factorial
class CountModel:
error_rate=0.01
class MultiplePoissonModel(CountModel):
def __init__(self, base_lambda, repeat_dist, certain_coun... | [
"scipy.special.hyperu",
"numpy.tile",
"scipy.special.gammaln",
"numpy.log",
"numpy.any",
"numpy.square",
"numpy.sum",
"numpy.zeros",
"numpy.array",
"numpy.empty",
"scipy.stats.poisson.logpmf",
"scipy.special.logsumexp",
"numpy.arange"
] | [((676, 706), 'numpy.tile', 'np.tile', (['allele_frequencies', '(2)'], {}), '(allele_frequencies, 2)\n', (683, 706), True, 'import numpy as np\n'), ((780, 803), 'numpy.arange', 'np.arange', (['n_duplicates'], {}), '(n_duplicates)\n', (789, 803), True, 'import numpy as np\n'), ((826, 866), 'numpy.zeros', 'np.zeros', (['... |
import numpy as np
import ds_format as ds
from rstoollib.algorithms import *
def postprocess(d):
"""Postprocess profile (prof) dataset d by calculating derived
variables."""
if 'zg' not in d and 'z' in d and 'lat' in d:
d['zg'] = calc_zg(d['z'], d['lat'])
if 'z' not in d and 'zg' in d and 'lat' in d:
d['z'] =... | [
"numpy.interp"
] | [((1065, 1115), 'numpy.interp', 'np.interp', (["d['p_lcl']", "d['p'][::-1]", "d['zg'][::-1]"], {}), "(d['p_lcl'], d['p'][::-1], d['zg'][::-1])\n", (1074, 1115), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import os
import re
import sounddevice as sd
from utils import read_wav, write_wav
import numpy as np
from threading import Thread
import argparse
class DeviceNotFoundError(Exception):
pass
def record_target(file_path, length, fs, channels=2, append=False):
"""Records audio and writ... | [
"numpy.abs",
"re.escape",
"sounddevice.rec",
"os.makedirs",
"argparse.ArgumentParser",
"sounddevice.query_hostapis",
"utils.read_wav",
"sounddevice.query_devices",
"os.path.isfile",
"utils.write_wav",
"numpy.vstack",
"os.path.abspath",
"threading.Thread",
"numpy.pad",
"numpy.transpose",
... | [((705, 768), 'sounddevice.rec', 'sd.rec', (['length'], {'samplerate': 'fs', 'channels': 'channels', 'blocking': '(True)'}), '(length, samplerate=fs, channels=channels, blocking=True)\n', (711, 768), True, 'import sounddevice as sd\n'), ((785, 808), 'numpy.transpose', 'np.transpose', (['recording'], {}), '(recording)\n... |
import pickle
from os.path import join
import numpy as np
import sys; sys.path.insert(0, '..'); sys.path.insert(0, '.')
from util import print_stats
file_path = '/data2/mengtial/Exp/ArgoVerse1.1/output/rt_htc_dconv2_ms_nm_s1.0/val/time_info.pkl'
time_info = pickle.load(open(file_path, 'rb'))
runtime_all_np = np.arr... | [
"numpy.array",
"sys.path.insert",
"util.print_stats"
] | [((72, 96), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (87, 96), False, 'import sys\n'), ((98, 121), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""."""'], {}), "(0, '.')\n", (113, 121), False, 'import sys\n'), ((314, 348), 'numpy.array', 'np.array', (["time_info['runtime_all']"... |
"""
Test for fake_data_generator.py
"""
import numpy as np
from deepchem.utils.fake_data_generator import FakeGraphGenerator, generate_edge_index, remove_self_loops
def test_fake_graph_dataset():
n_graphs = 10
n_node_features = 5
n_edge_features = 3
n_classes = 2
z_shape = 5
# graph-level labels
fgg = ... | [
"numpy.ones",
"numpy.unique",
"deepchem.utils.fake_data_generator.FakeGraphGenerator",
"numpy.array",
"deepchem.utils.fake_data_generator.remove_self_loops",
"deepchem.utils.fake_data_generator.generate_edge_index"
] | [((320, 500), 'deepchem.utils.fake_data_generator.FakeGraphGenerator', 'FakeGraphGenerator', ([], {'min_nodes': '(3)', 'max_nodes': '(10)', 'n_node_features': 'n_node_features', 'avg_degree': '(4)', 'n_edge_features': 'n_edge_features', 'n_classes': 'n_classes', 'task': '"""graph"""', 'z': 'z_shape'}), "(min_nodes=3, m... |
import datetime
import math
import re
import types
from typing import Any
from git import List
import numpy as np
import torch
from pandas import DataFrame as df
from PIL import Image
from torchvision import transforms
def getprice(img:List[Any], transform:Any, info:int,types:List[Any]):
val={}
for type in ty... | [
"numpy.mean",
"PIL.Image.open",
"torchvision.transforms.ToPILImage",
"math.log2",
"torch.from_numpy",
"numpy.diag",
"numpy.array",
"numpy.stack",
"numpy.outer",
"numpy.concatenate",
"re.search"
] | [((584, 606), 'numpy.mean', 'np.mean', (['item[162:192]'], {}), '(item[162:192])\n', (591, 606), True, 'import numpy as np\n'), ((616, 638), 'numpy.mean', 'np.mean', (['item[192:222]'], {}), '(item[192:222])\n', (623, 638), True, 'import numpy as np\n'), ((1868, 1890), 'numpy.stack', 'np.stack', (['[m1, n1, o1]'], {}),... |
# Copyright 2021 Google Inc. 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 applicable law or ag... | [
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.Graph",
"tensorflow.compat.v1.reduce_sum",
"unittest.mock.MagicMock",
"numpy.count_nonzero",
"numpy.testing.assert_almost_equal",
"numpy.array",
"tensorflow.compat.v1.sin",
"tensorflow.compat.v1.gradients",
"scipy.ndimage.gaussian_filter",
... | [((6359, 6374), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6372, 6374), False, 'import unittest\n'), ((3551, 3617), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['mask', 'self.expected_val'], {'decimal': '(2)'}), '(mask, self.expected_val, decimal=2)\n', (3581, 3617), True, 'import ... |
import numpy as np
# ==============================================================================
# Funcion que calcula el coeficiente de arrastre de una esfera en caida libre
# Funciona con Reynolds descde 0 hasta m'as all'a de 3e6
# ==============================================================================
def ... | [
"numpy.zeros",
"numpy.zeros_like",
"numpy.logical_and"
] | [((1750, 1761), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1758, 1761), True, 'import numpy as np\n'), ((1771, 1788), 'numpy.zeros_like', 'np.zeros_like', (['dv'], {}), '(dv)\n', (1784, 1788), True, 'import numpy as np\n'), ((505, 536), 'numpy.logical_and', 'np.logical_and', (['(Re > 0)', '(Re <= 1)'], {}), '(... |
import matplotlib.pyplot as plt
import numpy as np
trainmetrics = [-7.827264757844233, -6.539122052193318, -5.46885741580931, -4.860724952141639]
testmetrics = [-7.624574522874662, -6.11743100622369, -5.002220748941359, -4.422560242520135]
trainmetrics = np.round(trainmetrics, decimals=3)
testmetrics = np.round(testm... | [
"numpy.linspace",
"matplotlib.pyplot.plot",
"numpy.round",
"matplotlib.pyplot.show"
] | [((257, 291), 'numpy.round', 'np.round', (['trainmetrics'], {'decimals': '(3)'}), '(trainmetrics, decimals=3)\n', (265, 291), True, 'import numpy as np\n'), ((306, 339), 'numpy.round', 'np.round', (['testmetrics'], {'decimals': '(3)'}), '(testmetrics, decimals=3)\n', (314, 339), True, 'import numpy as np\n'), ((396, 41... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.