code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import time
import numpy as np
import paddle
from env import DinoGame
from model import Model
resize_shape = (1, 30, 90) # 训练缩放的大小
save_model_path = "models/model.pdparams" # 保存模型路径
FPS = 25 # 控制游戏截图帧数
def main():
# 初始化游戏
env = DinoGame()
# 图像输入形状和动作维度
obs_dim = env.observation_space.shape[0]
... | [
"paddle.load",
"paddle.argmax",
"model.Model",
"numpy.expand_dims",
"time.time",
"env.DinoGame",
"paddle.to_tensor"
] | [((244, 254), 'env.DinoGame', 'DinoGame', ([], {}), '()\n', (252, 254), False, 'from env import DinoGame\n'), ((378, 404), 'model.Model', 'Model', (['obs_dim', 'action_dim'], {}), '(obs_dim, action_dim)\n', (383, 404), False, 'from model import Model\n'), ((562, 573), 'time.time', 'time.time', ([], {}), '()\n', (571, 5... |
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université
# "Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. "
from mpi4py import MPI
import numpy as np
from nest_elephant_tvb.transformation.communic... | [
"numpy.sum",
"mpi4py.MPI.Status",
"numpy.empty",
"numpy.array",
"numpy.concatenate"
] | [((830, 842), 'mpi4py.MPI.Status', 'MPI.Status', ([], {}), '()\n', (840, 842), False, 'from mpi4py import MPI\n'), ((973, 995), 'numpy.empty', 'np.empty', (['(1)'], {'dtype': '"""b"""'}), "(1, dtype='b')\n", (981, 995), True, 'import numpy as np\n'), ((1049, 1071), 'numpy.empty', 'np.empty', (['(1)'], {'dtype': '"""i""... |
#import joblib
import pickle
import numpy as np
tasks = [# Pushing
{'task': 'push' , 'obj_init_pos': np.array([0, 0.6 , 0.02]) , 'goal_pos': np.array([0, 0.81, 0.02]) , 'door_pos': np.array([0, 1.0, 0.3])} ,
{'task': 'push' , 'obj_init_pos': np.array([0, 0.6 , 0.02]) , 'goal_pos': np.array([-0.15, 0.77 , 0.02... | [
"pickle.dump",
"numpy.array"
] | [((1081, 1105), 'pickle.dump', 'pickle.dump', (['tasks', 'fobj'], {}), '(tasks, fobj)\n', (1092, 1105), False, 'import pickle\n'), ((105, 129), 'numpy.array', 'np.array', (['[0, 0.6, 0.02]'], {}), '([0, 0.6, 0.02])\n', (113, 129), True, 'import numpy as np\n'), ((145, 170), 'numpy.array', 'np.array', (['[0, 0.81, 0.02]... |
import torch
import torch.nn as nn
t = torch.tensor([[0, 0], [1, 2], [2, 3]])
idx = torch.tensor([0, 1, 2, 0, 0, 1])
t[idx]
import gym
import gym_car_intersect
import numpy as np
env = gym.make('CarIntersect-v1')
env.reset()
for _ in range(500):
env.render()
a = np.random.choice(5)
_, _, done, _ = env.st... | [
"gym.make",
"torch.tensor",
"numpy.random.choice"
] | [((40, 78), 'torch.tensor', 'torch.tensor', (['[[0, 0], [1, 2], [2, 3]]'], {}), '([[0, 0], [1, 2], [2, 3]])\n', (52, 78), False, 'import torch\n'), ((85, 117), 'torch.tensor', 'torch.tensor', (['[0, 1, 2, 0, 0, 1]'], {}), '([0, 1, 2, 0, 0, 1])\n', (97, 117), False, 'import torch\n'), ((188, 215), 'gym.make', 'gym.make'... |
# Original code from https://github.com/araffin/robotics-rl-srl
# Authors: <NAME>, <NAME>, <NAME>
from constants import *
import cv2
import numpy as np
import torch
import os
def create_figure_and_sliders(name, state_dim):
"""
Creating a window for the latent space visualization,
and another one for the ... | [
"os.path.isdir",
"cv2.waitKey",
"torch.load",
"cv2.imshow",
"torch.Tensor",
"numpy.array",
"cv2.resizeWindow",
"cv2.destroyAllWindows",
"cv2.getWindowProperty",
"os.listdir",
"cv2.namedWindow"
] | [((457, 497), 'cv2.namedWindow', 'cv2.namedWindow', (['name', 'cv2.WINDOW_NORMAL'], {}), '(name, cv2.WINDOW_NORMAL)\n', (472, 497), False, 'import cv2\n'), ((502, 534), 'cv2.resizeWindow', 'cv2.resizeWindow', (['name', '(500)', '(500)'], {}), '(name, 500, 500)\n', (518, 534), False, 'import cv2\n'), ((539, 576), 'cv2.n... |
import geometry # local module
import data_generator # local module
import numpy as np
from keras import backend as K
from keras.preprocessing.image import Iterator
K.set_image_data_format('channels_first')
class DirectoryIterator(Iterator):
"""Iterator yielding data from a Numpy array.
Builds on keras.pr... | [
"keras.backend.image_data_format",
"keras.backend.floatx",
"numpy.asarray",
"keras.backend.set_image_data_format",
"numpy.random.randint"
] | [((169, 210), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_first"""'], {}), "('channels_first')\n", (192, 210), True, 'from keras import backend as K\n'), ((2021, 2042), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (2040, 2042), True, 'from keras import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import params
metaparams = {
'figure size' : params.fgz,
'bins' : params.bi... | [
"matplotlib.pyplot.subplot",
"numpy.load",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.tril",
"matplotlib.ticker.NullLocator",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.arange",
"matplotlib.pyplot.subplots_adjust",
"numpy.diag",
"matplotlib.pyplot.xticks",
"numpy.unique"
] | [((1353, 1372), 'numpy.unique', 'np.unique', (['self.lbl'], {}), '(self.lbl)\n', (1362, 1372), True, 'import numpy as np\n'), ((1402, 1420), 'numpy.arange', 'np.arange', (['self.nf'], {}), '(self.nf)\n', (1411, 1420), True, 'import numpy as np\n'), ((1507, 1540), 'numpy.meshgrid', 'np.meshgrid', (['self.feat', 'self.fe... |
""" Setup the preCICE interface and execute the coupled solver.
Usage: python3 aeroelastic_two_way.py config.xml participant-name mesh-name
"""
from __future__ import division
# ensure packages are available at linux distribution level (not using virtual environment)
import argparse
import subprocess
import numpy a... | [
"subprocess.run",
"local_context.PRECICE_FOLDER.mkdir",
"argparse.ArgumentParser",
"numpy.savetxt",
"precice_post.write_solver_output_to_file",
"precice.action_write_iteration_checkpoint",
"numpy.array",
"numpy.loadtxt",
"precice.action_read_iteration_checkpoint",
"precice.Interface",
"local_con... | [((1220, 1339), 'subprocess.run', 'subprocess.run', (["(SOLVER_PYTHON_PATH[solver] + ' ' + module)"], {'cwd': '"""../."""', 'shell': '(True)', 'check': '(True)', 'capture_output': '(True)'}), "(SOLVER_PYTHON_PATH[solver] + ' ' + module, cwd='../.', shell\n =True, check=True, capture_output=True)\n", (1234, 1339), Fa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os
import xarray as xr
from ooi_data_explorations.common import inputs, load_gc_thredds, m2m_collect, m2m_request, get_vocabulary, \
update_dataset, ENCODINGS
from ooi_data_explorations.qartod.qc_processing import parse_qc
# load configuratio... | [
"ooi_data_explorations.common.update_dataset",
"os.path.abspath",
"ooi_data_explorations.common.m2m_collect",
"os.path.dirname",
"numpy.isnan",
"ooi_data_explorations.common.m2m_request",
"ooi_data_explorations.common.load_gc_thredds",
"numpy.array",
"ooi_data_explorations.qartod.qc_processing.parse... | [((9894, 9906), 'ooi_data_explorations.qartod.qc_processing.parse_qc', 'parse_qc', (['ds'], {}), '(ds)\n', (9902, 9906), False, 'from ooi_data_explorations.qartod.qc_processing import parse_qc\n'), ((14730, 14742), 'ooi_data_explorations.qartod.qc_processing.parse_qc', 'parse_qc', (['ds'], {}), '(ds)\n', (14738, 14742)... |
import numpy as np
import os
import cv2
import pickle as pkl
import torch
from tqdm import tqdm
import pandas as pd
# Detection imports
from hpe3d.models import hmr
from hpe3d.utils.img_utils import FakeCamera
from hpe3d.utils.kp_utils import get_joints_from_bvh, bbox_from_kp2d
import hpe3d.utils.config as cfg
devic... | [
"hpe3d.utils.img_utils.FakeCamera",
"os.mkdir",
"pickle.dump",
"pandas.read_csv",
"numpy.einsum",
"hpe3d.utils.kp_utils.get_joints_from_bvh",
"cv2.FileStorage",
"hpe3d.models.hmr",
"torch.cuda.is_available",
"numpy.array",
"torch.device",
"numpy.eye",
"hpe3d.utils.kp_utils.bbox_from_kp2d",
... | [((407, 412), 'hpe3d.models.hmr', 'hmr', ([], {}), '()\n', (410, 412), False, 'from hpe3d.models import hmr\n'), ((348, 373), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (371, 373), False, 'import torch\n'), ((324, 344), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (33... |
import numpy as np
import matplotlib.pyplot as plt
import math
from thes_graphics.heat_map_plot.plot_heat_map import plot_heat_map
num_values = 9
num_values = math.pow(math.ceil(math.sqrt(num_values)), 2)
arr = np.linspace(-10, 20, num_values)
reshape_len = int(math.sqrt(num_values))
arr_reshaped = np.reshape(arr, ... | [
"math.sqrt",
"matplotlib.pyplot.figure",
"numpy.reshape",
"numpy.linspace",
"thes_graphics.heat_map_plot.plot_heat_map.plot_heat_map"
] | [((215, 247), 'numpy.linspace', 'np.linspace', (['(-10)', '(20)', 'num_values'], {}), '(-10, 20, num_values)\n', (226, 247), True, 'import numpy as np\n'), ((304, 347), 'numpy.reshape', 'np.reshape', (['arr', '(reshape_len, reshape_len)'], {}), '(arr, (reshape_len, reshape_len))\n', (314, 347), True, 'import numpy as n... |
# Joint IDs and Connectivity
#
# <NAME> <<EMAIL>>
import numpy as np
def get_joint_names_dict(joint_names):
return {name: i for i, name in enumerate(joint_names)}
def get_ikea_joint_names():
return [
"nose", # 0
"left eye", # 1
"right eye", # 2
"left ear", # 3
"right e... | [
"numpy.array"
] | [((5516, 6039), 'numpy.array', 'np.array', (['[[255.0, 0.0, 85.0], [255.0, 85.0, 0.0], [255.0, 170.0, 0.0], [255.0, 255.0,\n 0.0], [170.0, 255.0, 0.0], [85.0, 255.0, 0.0], [0.0, 255.0, 0.0], [\n 255.0, 0.0, 0.0], [0.0, 255.0, 85.0], [0.0, 255.0, 170.0], [0.0, 255.0,\n 255.0], [0.0, 170.0, 255.0], [0.0, 85.0, 2... |
import calendar
import pickle as pkl
import pandas as pd
import numpy as np
import random
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistG... | [
"pandas.DataFrame",
"pickle.dump",
"sklearn.ensemble.HistGradientBoostingClassifier",
"numpy.random.seed",
"pandas.read_csv",
"sklearn.model_selection.cross_val_score",
"sklearn.preprocessing.MinMaxScaler",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.model_selection.KFold",
"random.seed",
"s... | [((477, 494), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (488, 494), False, 'import random\n'), ((495, 515), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (509, 515), True, 'import numpy as np\n'), ((560, 592), 'pandas.read_csv', 'pd.read_csv', (['"""./kickstarter.csv"""'], {}), "('.... |
"""
Benchmark the communication bandwidth with Ray + NCCL.
We use the python binding cupy.nccl to call NCCL.
Usage:
python3 profile_communication.py
"""
import argparse
import time
import os
import cupy as cp
from cupy.cuda import nccl
import numpy as np
import ray
MB = 1 << 20
GB = 1 << 30
def do_all_reduce(co... | [
"ray.init",
"ray.remote",
"argparse.ArgumentParser",
"numpy.ravel",
"cupy.ones",
"cupy.cuda.nccl.get_unique_id",
"time.sleep",
"time.time",
"os.environ.get",
"numpy.max",
"cupy.cuda.Device",
"ray.cluster_resources"
] | [((1030, 1052), 'ray.remote', 'ray.remote', ([], {'num_gpus': '(1)'}), '(num_gpus=1)\n', (1040, 1052), False, 'import ray\n'), ((8530, 8555), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8553, 8555), False, 'import argparse\n'), ((8803, 8827), 'ray.init', 'ray.init', ([], {'address': '"""aut... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"numpy.zeros"
] | [((1065, 1100), 'numpy.zeros', 'np.zeros', (['(num_cameras, camera_dim)'], {}), '((num_cameras, camera_dim))\n', (1073, 1100), True, 'import numpy as np\n'), ((1133, 1166), 'numpy.zeros', 'np.zeros', (['(num_points, point_dim)'], {}), '((num_points, point_dim))\n', (1141, 1166), True, 'import numpy as np\n'), ((1198, 1... |
import pickle
import re
import tqdm
from typing import List, Tuple
import sling
import time
import os
from collections import defaultdict
import numpy as np
class SlingExtractor(object):
def load_kb(self, root_dir: str = 'local/data/e/wiki'):
print('loading and indexing kb ...')
start = time.time(... | [
"tqdm.tqdm",
"sling.Store",
"re.finditer",
"time.time",
"collections.defaultdict",
"os.path.join",
"numpy.random.shuffle",
"re.compile"
] | [((4187, 4214), 're.compile', 're.compile', (['"""= = [^=]+ = ="""'], {}), "('= = [^=]+ = =')\n", (4197, 4214), False, 'import re\n'), ((4363, 4378), 'tqdm.tqdm', 'tqdm.tqdm', (['data'], {}), '(data)\n', (4372, 4378), False, 'import tqdm\n'), ((310, 321), 'time.time', 'time.time', ([], {}), '()\n', (319, 321), False, '... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
"""
All reading and writing operations of kapture objects in CSV like files
"""
import datetime
import io
import os
import os.path as path
import re
from collections import namedtuple
from typing import Any, List, Optional, Set, Type, Union
import numpy ... | [
"kapture.RecordsDepth",
"kapture.io.features.matching_pairs_from_dirpath",
"kapture.PoseTransform",
"kapture.io.features.get_matches_fullpath",
"kapture.Points3d",
"kapture.RecordsWifi",
"os.path.isfile",
"kapture.RecordsLidar",
"kapture.PoseTransform.__new__",
"os.path.join",
"kapture.RecordWif... | [((5754, 5777), 're.compile', 're.compile', (['"""\\\\s*,\\\\s*"""'], {}), "('\\\\s*,\\\\s*')\n", (5764, 5777), False, 'import re\n'), ((34394, 34454), 'collections.namedtuple', 'namedtuple', (['"""ImageFeatureConfig"""', "['name', 'dtype', 'dsize']"], {}), "('ImageFeatureConfig', ['name', 'dtype', 'dsize'])\n", (34404... |
import numpy as np
import cv2
import scipy.ndimage as ndi
img = cv2.imread('pictures/02.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
smooth = ndi.filters.median_filter(gray, size=2)
edges = smooth > 200
lines = cv2.HoughLines(edges.astype(np.uint8), 0.5, np.pi/180, 120)
for line in lines:
for rho,theta in ... | [
"cv2.line",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imread",
"numpy.sin",
"numpy.cos",
"cv2.imshow",
"scipy.ndimage.filters.median_filter"
] | [((65, 94), 'cv2.imread', 'cv2.imread', (['"""pictures/02.png"""'], {}), "('pictures/02.png')\n", (75, 94), False, 'import cv2\n'), ((102, 139), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (114, 139), False, 'import cv2\n'), ((149, 188), 'scipy.ndimage.filters.med... |
import logging
from functools import partial
import numpy as np
from matplotlib.ticker import AutoLocator, MaxNLocator, LogLocator
from matplotlib.ticker import (LogFormatterMathtext, ScalarFormatter,
FuncFormatter)
from ..core.data import CategoricalComponent
from ..core.decorators impor... | [
"functools.partial",
"matplotlib.ticker.AutoLocator",
"logging.debug",
"scipy.stats.scoreatpercentile",
"numpy.empty",
"numpy.asarray",
"matplotlib.ticker.LogLocator",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"numpy.nanmin",
"numpy.hstack",
"matplotlib.ticker.FuncFormatter",
"numpy... | [((840, 893), 'logging.debug', 'logging.debug', (['"""image shape: %s, view: %s"""', 'shp', 'view'], {}), "('image shape: %s, view: %s', shp, view)\n", (853, 893), False, 'import logging\n'), ((2458, 2513), 'scipy.stats.scoreatpercentile', 'stats.scoreatpercentile', (['values.flat', 'plo'], {'limit': 'limits'}), '(valu... |
import numpy as np
import warnings
from scipy.io import loadmat
from LFSpy import LocalFeatureSelection
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.pipeline import Pipeline
from sklearn import datasets
im... | [
"matplotlib.pyplot.title",
"sklearn.datasets.load_iris",
"numpy.random.seed",
"scipy.io.loadmat",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.random.normal",
"LFSpy.LocalFeatureSelection",
"sklearn.svm.LinearSVC",
"matplotlib.pyplot.subplots",
"sklearn.ensemble.... | [((351, 370), 'numpy.random.seed', 'np.random.seed', (['(905)'], {}), '(905)\n', (365, 370), True, 'import numpy as np\n'), ((4708, 4730), 'numpy.arange', 'np.arange', (['(0)', '(1001)', '(25)'], {}), '(0, 1001, 25)\n', (4717, 4730), True, 'import numpy as np\n'), ((5210, 5222), 'matplotlib.pyplot.figure', 'plt.figure'... |
import numpy as np
import sys
import yaml
import argparse
import torch
parser = argparse.ArgumentParser(description='Convert LASER model to Marian weight file.')
parser.add_argument('--laser', help='Path to LASER PyTorch model', required=True)
parser.add_argument('--marian', help='Output path for Marian weight file',... | [
"argparse.ArgumentParser",
"numpy.copy",
"torch.load",
"yaml.dump",
"numpy.transpose",
"numpy.savez",
"numpy.atleast_2d"
] | [((82, 168), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert LASER model to Marian weight file."""'}), "(description=\n 'Convert LASER model to Marian weight file.')\n", (105, 168), False, 'import argparse\n'), ((372, 394), 'torch.load', 'torch.load', (['args.laser'], {}), '(ar... |
import numpy as np
IMG_SHAPE = (1280, 720) # x, y
# Lane pixel extraction thresholds:
SATURATION_THRESHOLD = (155, 255)
SOBEL_X_ABS_SCALED_THRESHOLD = (40, 140)
# Key x and y coordinates for perspective transform:
LANE_START_X_LEFT = 185
LANE_START_X_RIGHT = IMG_SHAPE[0] - 150
LANE_WIDTH = LANE_START_X_RIGHT - LANE... | [
"numpy.array"
] | [((673, 872), 'numpy.array', 'np.array', (['[(X_MIDDLE - APEX_X_OFFSET_LEFT, APEX_Y), (LANE_START_X_LEFT, IMG_SHAPE[1] -\n 1), (LANE_START_X_RIGHT, IMG_SHAPE[1] - 1), (X_MIDDLE +\n APEX_X_OFFSET_RIGHT, APEX_Y)]'], {'dtype': 'np.float32'}), '([(X_MIDDLE - APEX_X_OFFSET_LEFT, APEX_Y), (LANE_START_X_LEFT, \n IMG_... |
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.framework import ops
def unpool_with_argmax(pool, ind, name = None, ksize=[1, 2, 2, 1], upsample=[-1,-1]):
"""
Unpooling layer after max_pool_with_argmax.
Args:
pool: max po... | [
"tensorflow.nn.batch_normalization",
"tensorflow.range",
"tensorflow.nn.relu",
"tensorflow.reshape",
"tensorflow.nn.bias_add",
"tensorflow.variable_scope",
"tensorflow.concat",
"tensorflow.ones_like",
"tensorflow.nn.max_pool",
"tensorflow.nn.conv2d",
"tensorflow.split",
"tensorflow.scatter_nd"... | [((2161, 2200), 'tensorflow.get_variable', 'tf.get_variable', (['name', 'shape', 'trainable'], {}), '(name, shape, trainable)\n', (2176, 2200), True, 'import tensorflow as tf\n'), ((3892, 3920), 'tensorflow.nn.relu', 'tf.nn.relu', (['input'], {'name': 'name'}), '(input, name=name)\n', (3902, 3920), True, 'import tensor... |
import unittest
import yaml
import numpy as np
import network_attack_simulator.envs.loader as loader
from network_attack_simulator.envs.loader import INTERNET, DMZ, SENSITIVE, USER
from network_attack_simulator.envs.machine import Machine
class LoaderTestCase(unittest.TestCase):
def test_load_yaml_file_non_exist... | [
"numpy.random.seed",
"network_attack_simulator.envs.loader.generate_config",
"network_attack_simulator.envs.loader.generate_firewalls",
"network_attack_simulator.envs.loader.generate_topology",
"unittest.main",
"numpy.full",
"network_attack_simulator.envs.loader.generate_machines",
"numpy.equal",
"n... | [((17553, 17568), 'unittest.main', 'unittest.main', ([], {}), '()\n', (17566, 17568), False, 'import unittest\n'), ((801, 828), 'network_attack_simulator.envs.loader.load_yaml_file', 'loader.load_yaml_file', (['file'], {}), '(file)\n', (822, 828), True, 'import network_attack_simulator.envs.loader as loader\n'), ((1759... |
import pandas as pd
import numpy as np
import altair as alt
import matplotlib.pyplot as plt
def get_first_row(s):
return s.iloc[0]
#Reads the first line of line of data and determines if data is categorical, quantitative or nominal
def auto_get_data_type(df):
type_dict = dict()
columns = list(df.columns... | [
"pandas.DataFrame",
"pandas.NamedAgg",
"matplotlib.pyplot.show",
"altair.Y",
"altair.Chart",
"pandas.to_datetime",
"numpy.array",
"pandas.to_numeric"
] | [((4392, 4418), 'pandas.DataFrame', 'pd.DataFrame', (['summary_dict'], {}), '(summary_dict)\n', (4404, 4418), True, 'import pandas as pd\n'), ((8313, 8323), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8321, 8323), True, 'import matplotlib.pyplot as plt\n'), ((2979, 3003), 'altair.Y', 'alt.Y', (['y_name'], ... |
import math
import logging
import re
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pygest as ge
from pygest.convenience import bids_val, dict_from_bids, short_cmp, p_string
from pygest.algorithms import pct_similarity
from scipy.stats import ttest_ind
... | [
"pygest.algorithms.pct_similarity",
"seaborn.heatmap",
"seaborn.kdeplot",
"numpy.polyfit",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"os.path.join",
"numpy.nanmean",
"pandas.DataFrame",
"numpy.std",
"seaborn.swarmplot",
"numpy.append",
"pygest.convenien... | [((1797, 1843), 'numpy.arange', 'np.arange', (['dist_min', 'dist_max', '(dist_max / bins)'], {}), '(dist_min, dist_max, dist_max / bins)\n', (1806, 1843), True, 'import numpy as np\n'), ((3612, 3642), 'pygest.corr', 'ge.corr', (['X', 'Y'], {'method': 'r_method'}), '(X, Y, method=r_method)\n', (3619, 3642), True, 'impor... |
from typing import (Callable, Optional, List, TypeVar, Tuple, Dict, Union)
from cytoolz.curried import ( # type: ignore
curry, compose, flip, nth, concat, itemmap, groupby, filter)
from returns.maybe import Maybe, Nothing
import numpy as np
import torch
from .config import Config
from .base import Data
A = Type... | [
"numpy.dot",
"torch.sum",
"cytoolz.curried.nth",
"returns.maybe.Maybe.from_optional",
"numpy.exp",
"numpy.linalg.norm",
"torch.sort",
"typing.TypeVar",
"torch.inverse",
"cytoolz.curried.filter",
"cytoolz.curried.compose",
"cytoolz.curried.itemmap"
] | [((316, 328), 'typing.TypeVar', 'TypeVar', (['"""A"""'], {}), "('A')\n", (323, 328), False, 'from typing import Callable, Optional, List, TypeVar, Tuple, Dict, Union\n'), ((432, 438), 'cytoolz.curried.nth', 'nth', (['(0)'], {}), '(0)\n', (435, 438), False, 'from cytoolz.curried import curry, compose, flip, nth, concat,... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"model_search.metric_fns.combine_metric_fns",
"model_search.metric_fns.create_num_parameters_metric_fn",
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.enable_v2_behavior",
"tensorflow.compat.v2.constant",
"numpy.float32",
"tensorflow.compat.v2.compat.v1.initializers.local_variables",
"tensor... | [((18365, 18388), 'tensorflow.compat.v2.enable_v2_behavior', 'tf.enable_v2_behavior', ([], {}), '()\n', (18386, 18388), True, 'import tensorflow.compat.v2 as tf\n'), ((18391, 18405), 'tensorflow.compat.v2.test.main', 'tf.test.main', ([], {}), '()\n', (18403, 18405), True, 'import tensorflow.compat.v2 as tf\n'), ((6458,... |
import math
import numpy as np
from .traj import Trajectory
# UED cross sections (computed by ELSEPA for a 3.7 MeV e- beam with default settings)
_ued_cross_sections = {
1: 3.92943e-04,
2: 5.96348e-04,
3: 3.89833e-03,
4: 6.17327e-03,
5: 7.76737e-03,
6: 8.74560e-03,
7: 9.42320e-03,
8: ... | [
"numpy.zeros_like",
"numpy.exp",
"math.sqrt"
] | [((3287, 3303), 'numpy.zeros_like', 'np.zeros_like', (['R'], {}), '(R)\n', (3300, 3303), True, 'import numpy as np\n'), ((3435, 3499), 'math.sqrt', 'math.sqrt', (['(_ued_cross_sections[N[A]] * _ued_cross_sections[N[B]])'], {}), '(_ued_cross_sections[N[A]] * _ued_cross_sections[N[B]])\n', (3444, 3499), False, 'import ma... |
"""
Copyright (c) 2018-2021, <NAME>. All rights reserved.
Licensed under BSD-3 Clause, https://opensource.org/licenses/BSD-3-Clause
"""
# Import the libSIA python bindings and numpy
import pysia as sia
import numpy as np
import argparse
# Import plotting helpers
import matplotlib.pyplot as plt
import matplotlib.cm a... | [
"argparse.ArgumentParser",
"matplotlib.pyplot.box",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"pysia.NonlinearGaussianDynamicsCT",
"numpy.identity",
"numpy.linspace",
"pysia.Runner",
"matplotlib.pyplot.show",
"pysia.EKF",
"pysia.PF",
... | [((1032, 1073), 'pysia.NonlinearGaussianDynamicsCT', 'sia.NonlinearGaussianDynamicsCT', (['f', 'Q', 'dt'], {}), '(f, Q, dt)\n', (1063, 1073), True, 'import pysia as sia\n'), ((1514, 1558), 'pysia.NonlinearGaussianMeasurementCT', 'sia.NonlinearGaussianMeasurementCT', (['h', 'R', 'dt'], {}), '(h, R, dt)\n', (1548, 1558),... |
import os
import pandas as pd
import numpy as np
import torch
import torch.utils.data as data
from torchsample.transforms import RandomRotate, RandomTranslate, RandomFlip, ToTensor, Compose, RandomAffine
from torchvision import transforms
INPUT_DIM = 224
MAX_PIXEL_VAL = 255
MEAN = 58.09
STDDEV = 49.73
class MRData(... | [
"numpy.stack",
"numpy.load",
"torch.utils.data.DataLoader",
"torch.FloatTensor",
"torchsample.transforms.RandomRotate",
"torchsample.transforms.RandomTranslate",
"torchsample.transforms.RandomFlip",
"numpy.min",
"numpy.max",
"torch.Tensor"
] | [((5026, 5096), 'torch.utils.data.DataLoader', 'data.DataLoader', (['train_data'], {'batch_size': '(1)', 'num_workers': '(4)', 'shuffle': '(True)'}), '(train_data, batch_size=1, num_workers=4, shuffle=True)\n', (5041, 5096), True, 'import torch.utils.data as data\n'), ((5237, 5306), 'torch.utils.data.DataLoader', 'data... |
import pandas
import numpy as np
from keras.preprocessing import image
from keras.layers import Conv2D,Flatten, Dense, Dropout, MaxPool2D
from keras.optimizers import Adam
from keras.models import Sequential
from keras import regularizers
from keras.optimizers import Adam
import scipy.misc
import tensorflow as tf
impor... | [
"numpy.argmax",
"cv2.waitKey",
"keras.layers.Dropout",
"cv2.cvtColor",
"keras.layers.MaxPool2D",
"keras.layers.Flatten",
"cv2.imshow",
"cv2.VideoCapture",
"keras.layers.Dense",
"keras.layers.Conv2D",
"keras.models.Sequential",
"cv2.destroyAllWindows",
"cv2.resize"
] | [((734, 746), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (744, 746), False, 'from keras.models import Sequential\n'), ((2234, 2253), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2250, 2253), False, 'import cv2\n'), ((3214, 3237), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([],... |
"""
Module containing tasks for morphological operations
Credits:
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2019-2020 <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME> (Sinergise)
... | [
"numpy.logical_or.reduce",
"numpy.expand_dims",
"numpy.unique"
] | [((1865, 1889), 'numpy.unique', 'np.unique', (['feature_array'], {}), '(feature_array)\n', (1874, 1889), True, 'import numpy as np\n'), ((2332, 2388), 'numpy.logical_or.reduce', 'np.logical_or.reduce', (['(eroded_masks + other_masks)'], {'axis': '(0)'}), '(eroded_masks + other_masks, axis=0)\n', (2352, 2388), True, 'im... |
import types
import json
import sys
import re
import numpy
from datetime import datetime
import odc
from urllib.parse import urlparse, parse_qs
# Logging Levels
Trace = 0
Debug = 1
Info = 2
Warn = 3
Error = 4
Critical = 5
# Exact string values for Event parameters which are passed as strings
# EventTypes, ConnectStat... | [
"json.loads",
"json.dumps",
"urllib.parse.parse_qs",
"odc.log",
"datetime.datetime.now",
"numpy.random.randint",
"numpy.random.normal",
"sys.exc_info",
"odc.SetTimer",
"re.search",
"urllib.parse.urlparse"
] | [((1497, 1531), 'odc.log', 'odc.log', (['self.guid', 'Trace', 'message'], {}), '(self.guid, Trace, message)\n', (1504, 1531), False, 'import odc\n'), ((1575, 1609), 'odc.log', 'odc.log', (['self.guid', 'Error', 'message'], {}), '(self.guid, Error, message)\n', (1582, 1609), False, 'import odc\n'), ((1652, 1686), 'odc.l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import logging
import numpy as np
import os
import re
from collections import OrderedDict
from hashlib import md5
from astropy.io import fits
from astropy.stats i... | [
"astropy.stats.sigma_clip",
"numpy.ones_like",
"numpy.abs",
"numpy.std",
"scipy.signal.medfilt",
"logging.getLogger",
"numpy.where",
"numpy.array",
"numpy.gradient"
] | [((525, 552), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (542, 552), False, 'import logging\n'), ((2138, 2166), 'scipy.signal.medfilt', 'signal.medfilt', (['flux', 'window'], {}), '(flux, window)\n', (2152, 2166), False, 'from scipy import interpolate, ndimage, polyfit, poly1d, optimi... |
#!/usr/bin/env python3
r"""myfile.exam
To edit examination paper
-------------------------------
Path: examsystem/exam.py
Author: William/2016-01-02
"""
import collections
import pathlib
import datetime
import copy
import numpy as np
from pylatex import *
from pylatex.base_classes import *
fro... | [
"pathlib.Path",
"semester.Semester",
"numpy.random.choice"
] | [((6332, 6349), 'pathlib.Path', 'pathlib.Path', (['"""~"""'], {}), "('~')\n", (6344, 6349), False, 'import pathlib\n'), ((1147, 1166), 'semester.Semester', 'semester.Semester', ([], {}), '()\n', (1164, 1166), False, 'import semester\n'), ((7458, 7484), 'numpy.random.choice', 'np.random.choice', (['problems'], {}), '(pr... |
import numpy as np
from matplotlib import pyplot as plt
from movement_handling import move, confine_particles, get_dead_indices
from prey.agent import Prey
import keyboard
from matplotlib.font_manager import FontProperties
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "cm"
plt.rcParams.upda... | [
"numpy.isin",
"numpy.sin",
"numpy.arange",
"movement_handling.confine_particles",
"matplotlib.font_manager.FontProperties",
"numpy.append",
"numpy.cumsum",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.fignum_exists",
"matplotlib.pyplot.show",
"numpy.cos... | [((303, 341), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 12}"], {}), "({'font.size': 12})\n", (322, 341), True, 'from matplotlib import pyplot as plt\n'), ((348, 364), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {}), '()\n', (362, 364), False, 'from matplotlib.font... |
from . import config, utils
import IPython as ipy
import matplotlib.pyplot as plt
import torch
import torch_geometric as tg
import torch_geometric.data
from tqdm.auto import tqdm
import copy
import itertools as it
import os
import time
import numpy as np
def train_epoch(model, opt, loader, max_grad_norm=config.max_g... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"itertools.cycle",
"torch.no_grad",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.show",
"numpy.average",
"torch.optim.lr_scheduler.CyclicLR",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"tqdm.auto.tqdm",
"matpl... | [((389, 430), 'tqdm.auto.tqdm', 'tqdm', (['loader'], {'desc': '"""batches"""', 'leave': '(False)'}), "(loader, desc='batches', leave=False)\n", (393, 430), False, 'from tqdm.auto import tqdm\n'), ((4004, 4041), 'tqdm.auto.tqdm.write', 'tqdm.write', (['f"""dump path: {dump_path}"""'], {}), "(f'dump path: {dump_path}')\n... |
'''
datecreated: 190930
objective: want to use opencv to make some kind of animated plotting tool.
KJG190930: using cv2 is MUCH MUCH faster, will use this instead of matplotlib
KJG190930: at this point, will use tkinter to try and control the rectangle
KJG191001: tkinter now functional, with multi-key input. now capabl... | [
"tkinter.StringVar",
"threading.Thread",
"numpy.radians",
"cv2.polylines",
"cv2.waitKey",
"cv2.destroyAllWindows",
"numpy.ones",
"time.time",
"numpy.sin",
"numpy.array",
"numpy.cos",
"tkinter.Frame",
"tkinter.IntVar",
"cv2.imshow",
"tkinter.Label",
"tkinter.Tk"
] | [((7387, 7431), 'threading.Thread', 'threading.Thread', ([], {'target': 'dw.run', 'daemon': '(True)'}), '(target=dw.run, daemon=True)\n', (7403, 7431), False, 'import threading\n'), ((1155, 1177), 'cv2.imshow', 'cv2.imshow', (['title', 'img'], {}), '(title, img)\n', (1165, 1177), False, 'import cv2\n'), ((1181, 1195), ... |
import numpy as np
import matplotlib.pyplot as plt
bin_labels = np.loadtxt(fname="histogramdata", dtype=float, usecols=(0))
hist_data = np.loadtxt(fname="histogramdata", dtype=float, usecols=(1))
bin_labels = [round(x,2) for x in bin_labels]
plt.plot(bin_labels, hist_data)
plt.show()
| [
"matplotlib.pyplot.show",
"numpy.loadtxt",
"matplotlib.pyplot.plot"
] | [((77, 134), 'numpy.loadtxt', 'np.loadtxt', ([], {'fname': '"""histogramdata"""', 'dtype': 'float', 'usecols': '(0)'}), "(fname='histogramdata', dtype=float, usecols=0)\n", (87, 134), True, 'import numpy as np\n'), ((150, 207), 'numpy.loadtxt', 'np.loadtxt', ([], {'fname': '"""histogramdata"""', 'dtype': 'float', 'usec... |
import numpy as np
import matplotlib.pylab as plt
def bin_data(data, minimum=None, maximum=None, bin_size=None, bin_number=100, normalised=True):
"""Returns the (normalised) number count of a data set with values within defined bins.
Parameters
----------
data : array_like
The data to be binn... | [
"numpy.std",
"numpy.histogram",
"numpy.max",
"numpy.arange",
"numpy.min",
"numpy.linspace",
"numpy.array",
"numpy.mean",
"numpy.where",
"numpy.log10",
"numpy.sqrt"
] | [((1293, 1347), 'numpy.histogram', 'np.histogram', (['data'], {'bins': '_bin_edge', 'density': 'normalised'}), '(data, bins=_bin_edge, density=normalised)\n', (1305, 1347), True, 'import numpy as np\n'), ((915, 927), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (921, 927), True, 'import numpy as np\n'), ((970, 98... |
from PIL import Image
import numpy as np
import os
def change_type(ann_org, ann_dir):
try:
os.makedirs(ann_dir, exist_ok=True)
print("create dir " + ann_dir)
except:
pass
for root, dirs, files in os.walk(ann_org):
continue
for file in files:
img_path_org = ann_... | [
"os.makedirs",
"os.walk",
"PIL.Image.open",
"numpy.array",
"PIL.Image.fromarray"
] | [((235, 251), 'os.walk', 'os.walk', (['ann_org'], {}), '(ann_org)\n', (242, 251), False, 'import os\n'), ((105, 140), 'os.makedirs', 'os.makedirs', (['ann_dir'], {'exist_ok': '(True)'}), '(ann_dir, exist_ok=True)\n', (116, 140), False, 'import os\n'), ((391, 415), 'PIL.Image.open', 'Image.open', (['img_path_org'], {}),... |
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
from PIL import Image
import random
import matplotlib.pyplot as plt
"""
Created on Mon May 21 18:41:43 2018
@author: <NAME>
VSM code with TensorFlow-v1.4
"""
def findTopK(scores, trainids, k):
recommend_list = tf.nn.top_k(input=s... | [
"matplotlib.pyplot.title",
"tensorflow.gather_nd",
"tensorflow.reshape",
"tensorflow.setdiff1d",
"tensorflow.matmul",
"tensorflow.multiply",
"tensorflow.divide",
"numpy.arange",
"numpy.mean",
"random.randint",
"tensorflow.size",
"numpy.std",
"tensorflow.matrix_diag",
"tensorflow.cast",
"... | [((435, 472), 'tensorflow.setdiff1d', 'tf.setdiff1d', (['recommend_ids', 'trainids'], {}), '(recommend_ids, trainids)\n', (447, 472), True, 'import tensorflow as tf\n'), ((2005, 2025), 'tensorflow.divide', 'tf.divide', (['dcg', 'idcg'], {}), '(dcg, idcg)\n', (2014, 2025), True, 'import tensorflow as tf\n'), ((2225, 226... |
import io
import cv2
import numpy as np
from PIL import Image
import skvideo.io
from tqdm import tqdm
import argparse
from utils import process_image
parser = argparse.ArgumentParser()
parser.add_argument("--input", dest='input', type=str, default="test.mp4")
parser.add_argument("--output", dest='output', type=str, d... | [
"PIL.Image.fromarray",
"numpy.asarray",
"tqdm.tqdm",
"argparse.ArgumentParser"
] | [((161, 186), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (184, 186), False, 'import argparse\n'), ((749, 778), 'tqdm.tqdm', 'tqdm', (['videogen'], {'total': 'maximum'}), '(videogen, total=maximum)\n', (753, 778), False, 'from tqdm import tqdm\n'), ((863, 880), 'numpy.asarray', 'np.asarray',... |
#!/usr/bin/env python3
from sys import argv
import re
import struct
from numpy import array
def readsepheader(filename):
lines=open(filename,"r").readlines()
header={}
for l in lines:
allgroups=l.split()
for i in allgroups:
mtch=(re.match("(.+)=(.+)",i))
if mtch!=No... | [
"struct.unpack",
"numpy.array",
"re.match"
] | [((272, 296), 're.match', 're.match', (['"""(.+)=(.+)"""', 'i'], {}), "('(.+)=(.+)', i)\n", (280, 296), False, 'import re\n'), ((1145, 1168), 'struct.unpack', 'struct.unpack', (['"""f"""', 'rec'], {}), "('f', rec)\n", (1158, 1168), False, 'import struct\n'), ((1212, 1220), 'numpy.array', 'array', (['a'], {}), '(a)\n', ... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pyprobml_utils import save_fig
xs = np.linspace(-1,1,21)
a = -1
b = 1
px = 1/(b-a) * np.ones(len(xs))
fn = lambda x: x**2
ys = fn(xs)
#analytic
ppy = 1/(2*np.sqrt(ys))
#monte carlo
n = 1000
samples = np.random.uniform(a,b, size=n)
sampl... | [
"numpy.random.uniform",
"pyprobml_utils.save_fig",
"matplotlib.pyplot.show",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.sqrt"
] | [((115, 137), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(21)'], {}), '(-1, 1, 21)\n', (126, 137), True, 'import numpy as np\n'), ((284, 315), 'numpy.random.uniform', 'np.random.uniform', (['a', 'b'], {'size': 'n'}), '(a, b, size=n)\n', (301, 315), True, 'import numpy as np\n'), ((349, 379), 'matplotlib.pyplot.... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 7 20:15:19 2021
@author: Christian
"""
import hysteresis as hys
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
# from matplotlib.animation import FuncAnimation
import numpy as np
# Add this function to s... | [
"matplotlib.pyplot.plot",
"matplotlib.animation.FuncAnimation",
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.subplots"
] | [((370, 384), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (382, 384), True, 'import matplotlib.pyplot as plt\n'), ((945, 965), 'numpy.array', 'np.array', (['NframesOut'], {}), '(NframesOut)\n', (953, 965), True, 'import numpy as np\n'), ((2977, 3000), 'numpy.arange', 'np.arange', (['self.Nframes'], ... |
from keras import backend as K
import os
def set_keras_backend(backend):
if K.backend() != backend:
os.environ['KERAS_BACKEND'] = backend
try:
from importlib import reload
reload(K) # Python 2.7
except NameError:
try:
from importlib impor... | [
"imp.reload",
"numpy.random.seed",
"keras.preprocessing.sequence.pad_sequences",
"sklearn.model_selection.train_test_split",
"keras.backend.set_image_dim_ordering",
"keras.layers.pooling.MaxPooling1D",
"os.path.join",
"pandas.merge",
"os.path.exists",
"numpy.genfromtxt",
"keras.layers.Flatten",
... | [((552, 582), 'keras.backend.set_image_dim_ordering', 'K.set_image_dim_ordering', (['"""tf"""'], {}), "('tf')\n", (576, 582), True, 'from keras import backend as K\n'), ((1539, 1566), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (1553, 1566), True, 'import numpy as np\n'), ((1633, 16... |
#
# Copyright 2019-2020 <NAME>
# 2018, 2020 <NAME>
#
# ### MIT license
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | [
"NuMPI.Tools.Reduction",
"numpy.testing.assert_almost_equal",
"numpy.testing.assert_allclose",
"numpy.zeros",
"muFFT.FFT",
"numpy.sin",
"numpy.cos",
"numpy.linspace",
"pytest.mark.parametrize",
"ContactMechanics.PeriodicFFTElasticHalfSpace",
"numpy.sqrt"
] | [((1553, 1618), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nx, ny"""', '[(64, 33), (65, 32), (64, 64)]'], {}), "('nx, ny', [(64, 33), (65, 32), (64, 64)])\n", (1576, 1618), False, 'import pytest\n'), ((2735, 2807), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nx, ny"""', '[(8, 15), (8, 4... |
import cv2
import json
import os
import yaml
from pycocotools.coco import COCO
import numpy as np
import pycocotools.mask as maskUtils
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
class GetAnn():
'''
get map of coco imgid and annotation which fit our gaussian dataset
'''
def ... | [
"yaml.load",
"pycocotools.mask.decode",
"pycocotools.coco.COCO",
"numpy.squeeze",
"pycocotools.mask.frPyObjects",
"cv2.findContours"
] | [((1761, 1783), 'pycocotools.coco.COCO', 'COCO', (['annFile_instance'], {}), '(annFile_instance)\n', (1765, 1783), False, 'from pycocotools.coco import COCO\n'), ((2446, 2465), 'pycocotools.coco.COCO', 'COCO', (['annFile_stuff'], {}), '(annFile_stuff)\n', (2450, 2465), False, 'from pycocotools.coco import COCO\n'), ((3... |
# -*- coding: utf-8 -*-
_show_plots_ = False
import time
import numpy
import quantarhei as qr
from quantarhei.qm.liouvillespace.integrodiff.integrodiff \
import IntegrodiffPropagator
print("")
print("***********************************************************")
print("* ... | [
"quantarhei.qm.liouvillespace.integrodiff.integrodiff.IntegrodiffPropagator",
"quantarhei.Molecule",
"numpy.trace",
"quantarhei.ReducedDensityMatrix",
"matplotlib.pyplot.show",
"quantarhei.Aggregate",
"matplotlib.pyplot.plot",
"quantarhei.KTHierarchyPropagator",
"quantarhei.KTHierarchy",
"numpy.ze... | [((954, 980), 'quantarhei.Aggregate', 'qr.Aggregate', (['[m1, m2, m3]'], {}), '([m1, m2, m3])\n', (966, 980), True, 'import quantarhei as qr\n'), ((1211, 1237), 'quantarhei.TimeAxis', 'qr.TimeAxis', (['(0.0)', '(500)', '(1.0)'], {}), '(0.0, 500, 1.0)\n', (1222, 1237), True, 'import quantarhei as qr\n'), ((2263, 2290), ... |
import natsort
import numpy as np
import torch
import os
from torchvision.transforms import transforms
from medpy.io import load
class DatasetSignalAndNoiseSamples(torch.utils.data.Dataset):
def __init__(self, e, split):
self.split = split
self.path_noise_samples = os.path.join(e.path_noise_sampl... | [
"os.walk",
"torchvision.transforms.transforms.ToTensor",
"torchvision.transforms.transforms.Normalize",
"numpy.random.rand",
"os.path.join",
"natsort.natsorted"
] | [((289, 330), 'os.path.join', 'os.path.join', (['e.path_noise_samples', 'split'], {}), '(e.path_noise_samples, split)\n', (301, 330), False, 'import os\n'), ((366, 408), 'os.path.join', 'os.path.join', (['e.path_signal_samples', 'split'], {}), '(e.path_signal_samples, split)\n', (378, 408), False, 'import os\n'), ((477... |
import os
import json
import cv2
import numpy as np
import random
from shapely import wkt
from shapely.geometry import Polygon
import torch
from torch.utils.data import Dataset, DataLoader
from utils import preprocess
import torchvision.transforms as transforms
import multiprocessing
multiprocessing.set_start_method(... | [
"torch.utils.data.DataLoader",
"cv2.cvtColor",
"multiprocessing.set_start_method",
"numpy.zeros",
"cv2.fillPoly",
"cv2.imread",
"numpy.array",
"torch.utils.data.random_split",
"torchvision.transforms.Normalize",
"utils.preprocess",
"os.path.join",
"os.listdir",
"shapely.wkt.loads",
"torchv... | [((287, 334), 'multiprocessing.set_start_method', 'multiprocessing.set_start_method', (['"""spawn"""', '(True)'], {}), "('spawn', True)\n", (319, 334), False, 'import multiprocessing\n'), ((8676, 8733), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['dataset', '[n_train, n_test]'], {}), '(dataset, ... |
from __future__ import print_function, absolute_import, unicode_literals, division
import csv
import random
from collections import OrderedDict
import pandas as pd
import nltk
import numpy as np
from keras_preprocessing.sequence import pad_sequences
from nltk import word_tokenize
import json
from sklearn import pre... | [
"pandas.read_csv",
"numpy.ones",
"numpy.mean",
"nltk.tag.StanfordPOSTagger",
"pandas.read_table",
"nltk.word_tokenize",
"pandas.DataFrame",
"classify.visualization.print_nb_actions_miniclips_train_test_eval",
"numpy.random.rand",
"keras.preprocessing.text.Tokenizer",
"classify.visualization.prin... | [((937, 952), 'nltk.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (950, 952), False, 'from nltk import PorterStemmer\n'), ((1101, 1158), 'nltk.tag.StanfordPOSTagger', 'StanfordPOSTagger', (['"""english-bidirectional-distsim.tagger"""'], {}), "('english-bidirectional-distsim.tagger')\n", (1118, 1158), False, 'from ... |
import matplotlib.pyplot as plt
import numpy as np
print(f'Loading {__file__}')
def align_gisaxs_height(rang=0.3, point=31, der=False):
yield from bp.rel_scan([pil1M], piezo.y, -rang, rang, point)
ps(der=der)
yield from bps.mv(piezo.y, ps.cen)
def align_gisaxs_th(rang=0.3, point=31):
... | [
"matplotlib.pyplot.close",
"numpy.int"
] | [((2537, 2553), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2546, 2553), True, 'import matplotlib.pyplot as plt\n'), ((3676, 3692), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (3685, 3692), True, 'import matplotlib.pyplot as plt\n'), ((5028, 5044), 'matplotli... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 15:48:47 2018
@author: r.dewinter
"""
import numpy as np
def TBTD(x):
y = x[0]
x1 = x[1]
x2 = x[2]
fvolume = (x1*((16+y**2)**0.5)) + (x2*((1+y**2)**0.5))
fstress = (20*((16+y**2)**0.5))/(y*x1)
fstressBC = (80*((1+y**2)**0.5)... | [
"numpy.array"
] | [((434, 462), 'numpy.array', 'np.array', (['[fvolume, fstress]'], {}), '([fvolume, fstress])\n', (442, 462), True, 'import numpy as np\n'), ((464, 486), 'numpy.array', 'np.array', (['[g1, g2, g3]'], {}), '([g1, g2, g3])\n', (472, 486), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = '<EMAIL>'
"""
加载数据
"""
import sys
import codecs
import pickle
import numpy as np
from utils import map_item2id
def load_vocs(paths):
"""
加载vocs
Args:
paths: list of str, voc路径
Returns:
vocs: list of dict
"""
vocs ... | [
"pickle.load",
"utils.map_item2id",
"numpy.zeros",
"codecs.open"
] | [((2030, 2081), 'numpy.zeros', 'np.zeros', (['(sentences_count, max_len)'], {'dtype': '"""int32"""'}), "((sentences_count, max_len), dtype='int32')\n", (2038, 2081), True, 'import numpy as np\n'), ((2158, 2219), 'numpy.zeros', 'np.zeros', (['(sentences_count, max_len, word_len)'], {'dtype': '"""int32"""'}), "((sentence... |
import numpy as np
from collections import Counter, defaultdict
from itertools import chain, tee, islice
from scipy.sparse import csc_matrix, csr_matrix
from tqdm import tqdm
def get_ngrams(doc, ngram_range=(1,1)):
for n in range(ngram_range[0],ngram_range[1]+1):
tlst = doc
while True:
a, b = tee... | [
"tqdm.tqdm",
"numpy.logical_and",
"numpy.zeros",
"numpy.ones",
"collections.defaultdict",
"numpy.argsort",
"numpy.array",
"itertools.islice",
"itertools.tee"
] | [((705, 718), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (716, 718), False, 'from collections import Counter, defaultdict\n'), ((801, 813), 'tqdm.tqdm', 'tqdm', (['corpus'], {}), '(corpus)\n', (805, 813), False, 'from tqdm import tqdm\n'), ((2818, 2850), 'numpy.zeros', 'np.zeros', (['X.shape[1]'], {'dt... |
import logging
import numpy as np
from typing import Sequence
from tenacity import retry, wait_random_exponential, retry_if_result
import geode.models as m
from geode.utils import marshall_to, point_to_str
from .distance_matrix import map_from_distance_matrix_response
from .geocoding import map_from_address
from .mode... | [
"geode.models.distance_matrix.Result",
"tenacity.retry_if_result",
"numpy.array",
"tenacity.wait_random_exponential",
"geode.utils.point_to_str",
"logging.getLogger"
] | [((408, 427), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (425, 427), False, 'import logging\n'), ((633, 702), 'tenacity.wait_random_exponential', 'wait_random_exponential', ([], {'multiplier': '(0.1)', 'min': '(0.1)', 'max': '(2)', 'exp_base': '(1.5)'}), '(multiplier=0.1, min=0.1, max=2, exp_base=1.5)\... |
"""
Module implements the scaler.
"""
from typing import List, Union
import numpy as np
from monty.json import MSONable
class StandardScaler(MSONable):
"""
StandardScaler follows the sklean manner with addition of
dictionary representation.
"""
def __init__(self, mean: Union[List, np.ndarray] = ... | [
"numpy.std",
"numpy.mean"
] | [((835, 858), 'numpy.mean', 'np.mean', (['target'], {'axis': '(0)'}), '(target, axis=0)\n', (842, 858), True, 'import numpy as np\n'), ((873, 895), 'numpy.std', 'np.std', (['target'], {'axis': '(0)'}), '(target, axis=0)\n', (879, 895), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import pytest
import rpy2.robjects as robjects
from spatstat_interface.interface import SpatstatInterface
from spatstat_interface.utils import to_pandas_data_frame
@pytest.fixture
def spatstat():
spatstat = SpatstatInterface(update=True)
spatstat.import_package("core", ... | [
"numpy.random.rand",
"spatstat_interface.interface.SpatstatInterface",
"rpy2.robjects.FloatVector",
"spatstat_interface.utils.to_pandas_data_frame"
] | [((253, 283), 'spatstat_interface.interface.SpatstatInterface', 'SpatstatInterface', ([], {'update': '(True)'}), '(update=True)\n', (270, 283), False, 'from spatstat_interface.interface import SpatstatInterface\n'), ((438, 461), 'rpy2.robjects.FloatVector', 'robjects.FloatVector', (['B'], {}), '(B)\n', (458, 461), True... |
import ultra
import move
import time
import numpy as np
move.setup()
def rotateDegRight():
move.move(100,'no','right',0.8)
time.sleep(.0181)
move.motorStop()
time.sleep(.05)
def rotateDegLeft():
move.move(100,'no','left',0.8)
time.sleep(.01935)
move.motorStop()
... | [
"move.setup",
"numpy.zeros",
"time.sleep",
"move.move",
"move.motorStop",
"numpy.sin",
"numpy.cos",
"ultra.checkdist",
"move.destroy"
] | [((56, 68), 'move.setup', 'move.setup', ([], {}), '()\n', (66, 68), False, 'import move\n'), ((100, 134), 'move.move', 'move.move', (['(100)', '"""no"""', '"""right"""', '(0.8)'], {}), "(100, 'no', 'right', 0.8)\n", (109, 134), False, 'import move\n'), ((140, 158), 'time.sleep', 'time.sleep', (['(0.0181)'], {}), '(0.01... |
"""
Adapted from keras example cifar10_cnn.py
Train ResNet-18 on the CIFAR10 small images dataset.
GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10.py
"""
from __future__ import print_function
from tensorflow ... | [
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"utils.feature_learning_utils.default_parameters",
"argparse.ArgumentParser",
"dataset.dataset_utils.bad_res102",
"os.getcwd",
"tensorflow.keras.datasets.cifar100.load_data",
"pretrained_teachers.style_nets.parametric_net_befe",
"pretrained_te... | [((794, 816), 'os.getenv', 'os.getenv', (['"""LSB_JOBID"""'], {}), "('LSB_JOBID')\n", (803, 816), False, 'import os\n'), ((1063, 1083), 'utils.feature_learning_utils.default_parameters', 'default_parameters', ([], {}), '()\n', (1081, 1083), False, 'from utils.feature_learning_utils import default_parameters\n'), ((1093... |
import pandas as pd
import numpy as np
from itertools import product, combinations
from functools import reduce
from operator import and_
class BaseSwapAuditor():
"""Baseclass for shared functionality between all swap auditors."""
def __init__(self, data, predictor, id_column, protected_classes, target_col):... | [
"numpy.log",
"itertools.combinations",
"itertools.product",
"functools.reduce",
"pandas.concat"
] | [((11113, 11137), 'pandas.concat', 'pd.concat', (['non_sg_frames'], {}), '(non_sg_frames)\n', (11122, 11137), True, 'import pandas as pd\n'), ((1683, 1711), 'itertools.product', 'product', (['*values_for_classes'], {}), '(*values_for_classes)\n', (1690, 1711), False, 'from itertools import product, combinations\n'), ((... |
# Original implementation by <NAME> can be found using the following link: https://github.com/ryansmcgee/seirsplus
# Copyright (c) 2020 by <NAME>, <NAME>, BIOMATH, Ghent University. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import... | [
"numpy.random.binomial",
"matplotlib.cycler",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"pandas.plotting.register_matplotlib_converters",
"numpy.mean",
"numpy.array",
"numpy.exp",
"numpy.matmul"
] | [((655, 687), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (685, 687), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((1103, 1140), 'matplotlib.cycler', 'matplotlib.cycler', (['"""color"""', 'Okabe_Ito'], {}), "('color', Okabe_Ito)\n", (... |
from librosa import core
import numpy as np
def change_speed(input_signal, rate):
"""Change the playback speed of an audio signal
Parameters
----------
input_signal : numpy.array
Input array, must have numerical type.
rate : numeric
Desired rate of change to the speed.
To i... | [
"librosa.core.phase_vocoder",
"librosa.core.istft",
"numpy.iinfo",
"librosa.core.stft"
] | [((1146, 1169), 'librosa.core.stft', 'core.stft', (['input_signal'], {}), '(input_signal)\n', (1155, 1169), False, 'from librosa import core\n'), ((1245, 1294), 'librosa.core.phase_vocoder', 'core.phase_vocoder', (['frequency_domain_signal', 'rate'], {}), '(frequency_domain_signal, rate)\n', (1263, 1294), False, 'from ... |
import numpy as np
import nengo
import nengo_function_space as nfs
domain = np.linspace(-1, 1, 200)
# define your function
def gaussian(mag, mean, sd):
return mag * np.exp(-(domain-mean)**2/(2*sd**2))
# build the function space
fs = nfs.FunctionSpace(
nfs.Function(
gaussian,
mean=nengo.dist... | [
"nengo.dists.Uniform",
"numpy.exp",
"numpy.linspace",
"nengo.Network",
"nengo.Connection",
"nengo.Ensemble"
] | [((78, 101), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(200)'], {}), '(-1, 1, 200)\n', (89, 101), True, 'import numpy as np\n'), ((422, 437), 'nengo.Network', 'nengo.Network', ([], {}), '()\n', (435, 437), False, 'import nengo\n'), ((538, 591), 'nengo.Ensemble', 'nengo.Ensemble', ([], {'n_neurons': '(2000)', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# test mpi4py
# exc: mpiexec.openmpi -n 6 ./test02.py
import mpi4py.MPI as mpi
from numpy import array
from point import Point
comm = mpi.COMM_WORLD
rank = comm.rank
siz = comm.size
if rank == 0:
print("[%d] nb of procs: %d" % (rank,siz))
vals = [Point(1, ... | [
"numpy.array",
"point.Point"
] | [((311, 328), 'point.Point', 'Point', (['(1)', '(5)', '(3.14)'], {}), '(1, 5, 3.14)\n', (316, 328), False, 'from point import Point\n'), ((329, 345), 'numpy.array', 'array', (['[3, 4, 8]'], {}), '([3, 4, 8])\n', (334, 345), False, 'from numpy import array\n')] |
import numpy as np
import sklearn.mixture
import torch
from postproc.ml_tools.gmm import GaussianMixture
import unittest
def test_em_matches_sklearn():
"""
Assert that log-probabilities (E-step) and parameter updates (M-step) approximately match those of sklearn.
"""
d = 20
n_components = np.ran... | [
"unittest.main",
"torch.ones",
"torch.randn",
"numpy.random.RandomState",
"numpy.random.randint",
"postproc.ml_tools.gmm.GaussianMixture"
] | [((314, 339), 'numpy.random.randint', 'np.random.randint', (['(1)', '(100)'], {}), '(1, 100)\n', (331, 339), True, 'import numpy as np\n'), ((367, 388), 'torch.randn', 'torch.randn', (['(40)', '(1)', 'd'], {}), '(40, 1, d)\n', (378, 388), False, 'import torch\n'), ((507, 558), 'postproc.ml_tools.gmm.GaussianMixture', '... |
import unittest
import numpy as np
import pytest
import tiledb
from slaid.commons import Mask
from slaid.commons.base import ImageInfo, Slide
from slaid.commons.dask import Mask as DaskMask
from slaid.commons.ecvl import BasicSlide as EcvlSlide
from slaid.commons.openslide import BasicSlide as OpenSlide
IMAGE = 'tes... | [
"unittest.main",
"tiledb.open",
"numpy.array",
"slaid.commons.base.ImageInfo.create",
"pytest.mark.parametrize",
"pytest.mark.skip"
] | [((341, 435), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""slide_cls,args"""', '[(Slide, (EcvlSlide,)), (Slide, (OpenSlide,))]'], {}), "('slide_cls,args', [(Slide, (EcvlSlide,)), (Slide, (\n OpenSlide,))])\n", (364, 435), False, 'import pytest\n'), ((851, 945), 'pytest.mark.parametrize', 'pytest.mark.... |
import unittest, os, json
from ovejero import bnn_inference, data_tools, bnn_alexnet, model_trainer
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import gc
# Eliminate TF warning in tests
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
class BNNInferenceTest(unittest.TestCas... | [
"tensorflow.random.set_seed",
"os.mkdir",
"os.remove",
"numpy.random.seed",
"numpy.abs",
"pandas.read_csv",
"numpy.ones",
"gc.collect",
"os.path.isfile",
"numpy.mean",
"numpy.tile",
"numpy.random.normal",
"numpy.diag",
"ovejero.data_tools.normalize_lens_parameters",
"pandas.DataFrame",
... | [((1522, 1633), 'ovejero.model_trainer.prepare_tf_record', 'model_trainer.prepare_tf_record', (['self.cfg', 'self.root_path', 'self.tf_record_path', 'self.final_params', '"""train"""'], {}), "(self.cfg, self.root_path, self.\n tf_record_path, self.final_params, 'train')\n", (1553, 1633), False, 'from ovejero import ... |
import numpy as np
import scipy.linalg as scl
import itertools
from numpy import ndarray
import sys
from scipy import stats
from typing import Sequence, Union, Any, Optional, List, Tuple, Dict
from sklearn.linear_model import Lasso as skLasso
import warnings
class Regressor:
""" Base class implementing ordinary l... | [
"numpy.diag",
"numpy.trace",
"numpy.sum",
"numpy.eye",
"scipy.linalg.diagsvd",
"numpy.zeros",
"numpy.linalg.cond",
"numpy.append",
"scipy.linalg.svd",
"numpy.mean",
"numpy.linalg.inv",
"scipy.stats.t.interval",
"itertools.product",
"warnings.warn",
"sklearn.linear_model.Lasso",
"numpy.... | [((16602, 16628), 'itertools.product', 'itertools.product', (['*orders'], {}), '(*orders)\n', (16619, 16628), False, 'import itertools\n'), ((17198, 17208), 'scipy.linalg.svd', 'scl.svd', (['x'], {}), '(x)\n', (17205, 17208), True, 'import scipy.linalg as scl\n'), ((5198, 5227), 'numpy.linalg.cond', 'np.linalg.cond', (... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections.abc import Iterable
import distillation.architectures.feature_extractors.utils as futils
import distillation.architectures.feature_extractors.VGG_ImageNet as VGG_ImageNet
import distillation.architectures.feature_ext... | [
"torch.nn.Parameter",
"torch.nn.Sequential",
"torch.nn.functional.conv2d",
"torch.FloatTensor",
"torch.nn.functional.normalize",
"numpy.sqrt"
] | [((5872, 5912), 'torch.nn.Parameter', 'nn.Parameter', (['weight'], {'requires_grad': '(True)'}), '(weight, requires_grad=True)\n', (5884, 5912), True, 'import torch.nn as nn\n'), ((6353, 6390), 'torch.nn.functional.normalize', 'F.normalize', (['x'], {'p': '(2)', 'dim': '(1)', 'eps': '(1e-12)'}), '(x, p=2, dim=1, eps=1e... |
__author__ = 'joseph'
import numpy as np
class ActivationFunction(object):
def activation(self, x):
pass
def derivative(self, x):
pass
class LinearActivation(ActivationFunction):
def activation(self, x):
return x
def derivative(self, x):
return np.ones(x.shape)
d... | [
"numpy.tanh",
"numpy.exp",
"numpy.ones"
] | [((300, 316), 'numpy.ones', 'np.ones', (['x.shape'], {}), '(x.shape)\n', (307, 316), True, 'import numpy as np\n'), ((1174, 1184), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (1181, 1184), True, 'import numpy as np\n'), ((1310, 1320), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (1317, 1320), True, 'import numpy a... |
from pycolate.grid_engine import grid
import numpy as np
class MeanFieldSandpile:
def __init__(
self,
initconfig: list,
theshold: int,
dissipation_amount: int,
graphics: bool = True,
rulebook: dict = None,
):
self._theshold = theshold
self._diss... | [
"numpy.random.default_rng",
"numpy.where",
"pycolate.grid_engine.grid"
] | [((1340, 1363), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1361, 1363), True, 'import numpy as np\n'), ((1134, 1172), 'pycolate.grid_engine.grid', 'grid', (['self._config', 'self._rulebook', '(30)'], {}), '(self._config, self._rulebook, 30)\n', (1138, 1172), False, 'from pycolate.grid_engin... |
from statsmodels.tsa.arima_model import AR
from pandas import read_csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
def main():
filepath=os.path.abspath(os.curdir)
series = read_csv(filepath+"/2.csv", header=0, index_col=0, squeeze=True)
series.columns = ['a', 'b', 'c', 'd']
se... | [
"pandas.DataFrame",
"os.path.abspath",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"statsmodels.tsa.arima_model.AR",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((175, 201), 'os.path.abspath', 'os.path.abspath', (['os.curdir'], {}), '(os.curdir)\n', (190, 201), False, 'import os\n'), ((213, 279), 'pandas.read_csv', 'read_csv', (["(filepath + '/2.csv')"], {'header': '(0)', 'index_col': '(0)', 'squeeze': '(True)'}), "(filepath + '/2.csv', header=0, index_col=0, squeeze=True)\n"... |
import json
import os
import pickle
from pathlib import Path
from typing import List, NamedTuple, Tuple
import numpy as np
import pandas as pd
import PIL.Image
import pycocotools.mask as coco_mask
from src.config.config import NUM_CLASSES
def use_sc_cam_format(data: dict, with_pillow=False):
"""
convert inp... | [
"json.dump",
"numpy.load",
"numpy.save",
"json.load",
"pickle.dump",
"pycocotools.mask.merge",
"numpy.empty",
"numpy.zeros",
"numpy.clip",
"pathlib.Path",
"pickle.load",
"numpy.where",
"numpy.eye",
"os.path.join",
"numpy.all"
] | [((1823, 1863), 'numpy.save', 'np.save', (['label_200_path', 'train_label_200'], {}), '(label_200_path, train_label_200)\n', (1830, 1863), True, 'import numpy as np\n'), ((1868, 1906), 'numpy.save', 'np.save', (['label_20_path', 'train_label_20'], {}), '(label_20_path, train_label_20)\n', (1875, 1906), True, 'import nu... |
from ...isa.inst import *
import numpy as np
class Fcvt_wu_s(Inst):
name = 'fcvt.wu.s'
def golden(self):
if 'val1' in self.keys():
if self['val1'] < 0 or np.isneginf(self['val1']):
return 0
if self['val1'] > ((1<<32)-1) or np.isposinf(self['val1']) or np.isnan(s... | [
"numpy.isneginf",
"numpy.isposinf",
"numpy.isnan"
] | [((184, 209), 'numpy.isneginf', 'np.isneginf', (["self['val1']"], {}), "(self['val1'])\n", (195, 209), True, 'import numpy as np\n'), ((281, 306), 'numpy.isposinf', 'np.isposinf', (["self['val1']"], {}), "(self['val1'])\n", (292, 306), True, 'import numpy as np\n'), ((310, 332), 'numpy.isnan', 'np.isnan', (["self['val1... |
# Author: <NAME>
#
# The purpose of this program is to, given a file name containing
# data collected from the instruments attached to the bubble chamber,
# create a data structure capable of storing the instruments and
# their readouts. The information for any given instrument should
# then be easily accessible ... | [
"numpy.set_printoptions",
"numpy.sum",
"numpy.zeros",
"numpy.ones",
"numpy.histogram",
"numpy.diff",
"numpy.array",
"numpy.mean",
"numpy.int32",
"numpy.float64",
"numpy.ndarray"
] | [((539, 576), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.nan'}), '(threshold=np.nan)\n', (558, 576), True, 'import numpy as np\n'), ((985, 999), 'numpy.zeros', 'np.zeros', (['tick'], {}), '(tick)\n', (993, 999), True, 'import numpy as np\n'), ((1017, 1031), 'numpy.zeros', 'np.zeros', (['tic... |
import random
import numpy as np
import os
import pytest
from ding.utils.plot_helper import plot
@pytest.mark.unittest
def test_plot():
rewards1 = np.array([0, 0.1, 0, 0.2, 0.4, 0.5, 0.6, 0.9, 0.9, 0.9])
rewards2 = np.array([0, 0, 0.1, 0.4, 0.5, 0.5, 0.55, 0.8, 0.9, 1])
rewards = np.concatenate((rewards1... | [
"ding.utils.plot_helper.plot",
"os.path.exists",
"numpy.random.random",
"numpy.array",
"numpy.concatenate"
] | [((154, 210), 'numpy.array', 'np.array', (['[0, 0.1, 0, 0.2, 0.4, 0.5, 0.6, 0.9, 0.9, 0.9]'], {}), '([0, 0.1, 0, 0.2, 0.4, 0.5, 0.6, 0.9, 0.9, 0.9])\n', (162, 210), True, 'import numpy as np\n'), ((226, 281), 'numpy.array', 'np.array', (['[0, 0, 0.1, 0.4, 0.5, 0.5, 0.55, 0.8, 0.9, 1]'], {}), '([0, 0, 0.1, 0.4, 0.5, 0.5... |
from __future__ import absolute_import
from .. import BuiltinFunction, FixedNumericInput
import numpy as np
import functools
from six.moves import zip
@BuiltinFunction.register
def abs(halos, vals):
if not hasattr(vals[0], '__len__'): # Avoid norm failing if abs is called on a single number (issue 110)
... | [
"six.moves.zip",
"numpy.asarray",
"functools.partial"
] | [((2373, 2390), 'six.moves.zip', 'zip', (['vals1', 'vals2'], {}), '(vals1, vals2)\n', (2376, 2390), False, 'from six.moves import zip\n'), ((412, 454), 'functools.partial', 'functools.partial', (['np.linalg.norm'], {'axis': '(-1)'}), '(np.linalg.norm, axis=-1)\n', (429, 454), False, 'import functools\n'), ((2455, 2482)... |
"""
In this module the data for SVMs is generated and local variables declared
"""
import os
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from definitions import SEED, ROOT_DIR
NUMBER_OF_SAMPLES = 10
Xm, Ym = make_moons(NUMBER_OF_SAMPLES, random_state... | [
"matplotlib.pyplot.xlim",
"os.mkdir",
"matplotlib.pyplot.ylim",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"os.path.isdir",
"sklearn.datasets.make_moons",
"numpy.arange",
"matplotlib.pyplot.subplots"
] | [((278, 338), 'sklearn.datasets.make_moons', 'make_moons', (['NUMBER_OF_SAMPLES'], {'random_state': 'SEED', 'noise': '(0.34)'}), '(NUMBER_OF_SAMPLES, random_state=SEED, noise=0.34)\n', (288, 338), False, 'from sklearn.datasets import make_moons\n'), ((347, 424), 'pandas.read_csv', 'pd.read_csv', (["(ROOT_DIR + '/data/d... |
import threading
import os
import numpy as np
import numpy.testing
import pytest
from qa4sm_reader.comparing import QA4SMComparison, SpatialExtentError
from qa4sm_reader.img import QA4SMImg
import pandas as pd
import matplotlib.pyplot as plt
# for profiling with cProfile, on the command line run
# python -m cProfil... | [
"qa4sm_reader.comparing.QA4SMComparison",
"matplotlib.pyplot.close",
"os.path.dirname",
"qa4sm_reader.img.QA4SMImg",
"numpy.array"
] | [((625, 655), 'qa4sm_reader.comparing.QA4SMComparison', 'QA4SMComparison', (['testfile_path'], {}), '(testfile_path)\n', (640, 655), False, 'from qa4sm_reader.comparing import QA4SMComparison, SpatialExtentError\n'), ((1225, 1258), 'qa4sm_reader.comparing.QA4SMComparison', 'QA4SMComparison', (['double_img_paths'], {}),... |
import numpy as np
import argparse
import os
import math
import copy
from .. import MI
from .. import IO
from .. import sge
from .. import structures
from .. import modify_seed
from .. import type_conversions
from .. import matchmaker
from .. import statistic_tests
def handler():
parser = argparse.ArgumentParser(... | [
"copy.deepcopy",
"numpy.random.seed",
"argparse.ArgumentParser",
"math.ceil",
"numpy.arange",
"numpy.array",
"numpy.random.permutation",
"numpy.array_split",
"os.path.join"
] | [((296, 321), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (319, 321), False, 'import argparse\n'), ((6115, 6165), 'numpy.array_split', 'np.array_split', (['profiles_initial', 'number_of_chunks'], {}), '(profiles_initial, number_of_chunks)\n', (6129, 6165), True, 'import numpy as np\n'), ((61... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Main class to update the RADAR/STATION database and run queries to retrieve
specific data
Note that I use spark because there is currently no way to use SQL queries
with dask
"""
from pyspark import SparkConf
from pyspark import SparkContext
from pyspark.sql import ... | [
"pyspark.SparkContext",
"pyspark.SparkConf",
"glob.glob",
"numpy.unique",
"logging.error",
"os.path.exists",
"datetime.datetime.utcfromtimestamp",
"numpy.max",
"copy.deepcopy",
"os.path.basename",
"os.path.realpath",
"logging.WARN",
"time.sleep",
"numpy.min",
"textwrap.dedent",
"fnmatc... | [((430, 441), 'pyspark.SparkConf', 'SparkConf', ([], {}), '()\n', (439, 441), False, 'from pyspark import SparkConf\n'), ((1214, 1245), 'numpy.array', 'np.array', (['constants.METSTATIONS'], {}), '(constants.METSTATIONS)\n', (1222, 1245), True, 'import numpy as np\n'), ((859, 878), 'logging.getLogger', 'logging.getLogg... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from pearsonLinearCorrelationCoefficient import pearson_linear_correlation_coefficient
def linear_regression(filename: str):
df = pd.read_csv(filename, delimiter=',')
number_of_rows = df.shape[0]
df_hat = df.sum() / number_of_rows
... | [
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig"
] | [((207, 243), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'delimiter': '""","""'}), "(filename, delimiter=',')\n", (218, 243), True, 'import pandas as pd\n'), ((695, 731), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'delimiter': '""","""'}), "(filename, delimiter=',')\n", (706, 731), True, 'import pandas as... |
from abc import ABC, abstractmethod
import numpy as np
from .blobs import Blob
from nptyping import NDArray, Float
from typing import Any
class BlobFactory(ABC):
"""Abstract class used by 2d propagating blob model to specify blob
parameters."""
@abstractmethod
def sample_blobs(
self, Ly: floa... | [
"numpy.random.uniform",
"numpy.random.exponential",
"numpy.zeros",
"numpy.ones",
"numpy.random.gamma",
"numpy.sort",
"numpy.random.normal",
"numpy.sqrt"
] | [((3462, 3481), 'numpy.zeros', 'np.zeros', (['num_blobs'], {}), '(num_blobs)\n', (3470, 3481), True, 'import numpy as np\n'), ((3499, 3550), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': 'Ly', 'size': 'num_blobs'}), '(low=0.0, high=Ly, size=num_blobs)\n', (3516, 3550), True, 'import numpy a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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 agree... | [
"tensorflow.train.Int64List",
"SimpleITK.ReadImage",
"tensorflow.train.Features",
"SimpleITK.GetArrayFromImage",
"numpy.int32"
] | [((1398, 1424), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['image_path'], {}), '(image_path)\n', (1412, 1424), True, 'import SimpleITK as sitk\n'), ((1476, 1505), 'SimpleITK.GetArrayFromImage', 'sitk.GetArrayFromImage', (['image'], {}), '(image)\n', (1498, 1505), True, 'import SimpleITK as sitk\n'), ((1528, 1547), 'num... |
import numpy as np
import pytest
import torch
from probflow.distributions import Deterministic
from probflow.utils.torch_distributions import get_TorchDeterministic
tod = torch.distributions
def is_close(a, b, tol=1e-3):
return np.abs(a - b) < tol
def test_TorchDeterministic():
"""Tests the TorchDetermini... | [
"probflow.utils.torch_distributions.get_TorchDeterministic",
"torch.ones",
"numpy.abs",
"pytest.raises",
"torch.zeros",
"probflow.distributions.Deterministic",
"torch.tensor"
] | [((367, 391), 'probflow.utils.torch_distributions.get_TorchDeterministic', 'get_TorchDeterministic', ([], {}), '()\n', (389, 391), False, 'from probflow.utils.torch_distributions import get_TorchDeterministic\n'), ((883, 898), 'probflow.distributions.Deterministic', 'Deterministic', ([], {}), '()\n', (896, 898), False,... |
import torch
import torch.nn.functional as F
import torchvision
from tqdm import tqdm
from torch.autograd import Function
from sklearn.metrics import auc
from sklearn.metrics import confusion_matrix, mean_squared_error
from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve
from skimage import filt... | [
"numpy.sum",
"numpy.isnan",
"numpy.shape",
"torch.no_grad",
"skimage.filters.threshold_otsu",
"cv2.imwrite",
"torch.squeeze",
"torch.zeros",
"sklearn.metrics.mean_squared_error",
"tqdm.tqdm",
"sklearn.metrics.roc_auc_score",
"torch.max",
"numpy.squeeze",
"torch.unsqueeze",
"numpy.concate... | [((1092, 1148), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['true_vessel_arr', 'pred_vessel_arr', 'average'], {}), '(true_vessel_arr, pred_vessel_arr, average)\n', (1105, 1148), False, 'from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve\n'), ((1225, 1261), 'skimage.filters.threshold_ot... |
import math
import numpy as np
from Box2D import b2FixtureDef, b2CircleShape, b2Transform
import game.physics
class Circle:
def __init__(self, position, radius, weight, movable = True):
self.position = np.array(position)
self.velocity = np.array([0, 0])
self.radius = radius
self.... | [
"numpy.array",
"Box2D.b2CircleShape"
] | [((218, 236), 'numpy.array', 'np.array', (['position'], {}), '(position)\n', (226, 236), True, 'import numpy as np\n'), ((261, 277), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (269, 277), True, 'import numpy as np\n'), ((1147, 1175), 'numpy.array', 'np.array', (['self.body.position'], {}), '(self.body.p... |
import librosa
import madmom
from madmom.features.beats import *
from scipy import signal
import numpy as np
def peak_picking(beat_times, total_samples, kernel_size, offset):
# smoothing the beat function
cut_off_norm = len(beat_times)/total_samples*100/2
b, a = signal.butter(1, cut_off_norm)
beat_tim... | [
"librosa.zero_crossings",
"scipy.signal.filtfilt",
"numpy.argmax",
"numpy.median",
"librosa.feature.zero_crossing_rate",
"scipy.signal.medfilt",
"numpy.array",
"librosa.feature.chroma_cqt",
"scipy.signal.butter",
"librosa.get_duration"
] | [((277, 307), 'scipy.signal.butter', 'signal.butter', (['(1)', 'cut_off_norm'], {}), '(1, cut_off_norm)\n', (290, 307), False, 'from scipy import signal\n'), ((325, 358), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'beat_times'], {}), '(b, a, beat_times)\n', (340, 358), False, 'from scipy import signal\n'),... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 18:02:07 2018
@author: ron
A test function for the smoothing module
"""
from myptv.traj_smoothing_mod import smooth_trajectories
from numpy import loadtxt
def test_smoothing():
'''
A test for the smoothing module by smoothing three trajectories.
'''
... | [
"myptv.traj_smoothing_mod.smooth_trajectories",
"numpy.loadtxt"
] | [((391, 405), 'numpy.loadtxt', 'loadtxt', (['fname'], {}), '(fname)\n', (398, 405), False, 'from numpy import loadtxt\n'), ((448, 497), 'myptv.traj_smoothing_mod.smooth_trajectories', 'smooth_trajectories', (['traj_list', 'window', 'polyorder'], {}), '(traj_list, window, polyorder)\n', (467, 497), False, 'from myptv.tr... |
"""
Implements two-dimensional functions for modeling.
.. include:: ../include/links.rst
"""
import warnings
from IPython import embed
import numpy as np
from scipy import special
from astropy.modeling import functional_models
class Sersic2D(functional_models.Sersic2D):
"""
A 2D Sersic distribution.
Ar... | [
"numpy.radians",
"numpy.power",
"numpy.square",
"numpy.exp",
"scipy.special.gammaincinv",
"scipy.special.gamma"
] | [((2027, 2065), 'scipy.special.gammaincinv', 'special.gammaincinv', (['(2.0 * self.n)', '(0.5)'], {}), '(2.0 * self.n, 0.5)\n', (2046, 2065), False, 'from scipy import special\n'), ((2263, 2293), 'numpy.power', 'np.power', (['self.bn', '(-2 * self.n)'], {}), '(self.bn, -2 * self.n)\n', (2271, 2293), True, 'import numpy... |
import numpy as np
import math
def get_num_windows(image_height, image_width, window_height, window_width, overlap=True, overlap_corners=True):
"""Return the number of height and width windows to generate
Args:
image_height: Height of the image in pixels.
image_width: Width of the image in pix... | [
"numpy.pad",
"numpy.zeros",
"math.ceil"
] | [((2692, 2779), 'numpy.zeros', 'np.zeros', (['(total_windows, window_height, window_width, image.shape[2])', 'image.dtype'], {}), '((total_windows, window_height, window_width, image.shape[2]),\n image.dtype)\n', (2700, 2779), True, 'import numpy as np\n'), ((6942, 7029), 'numpy.zeros', 'np.zeros', (['(image_height,... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import uuid
import os
import glob
import math
import logging
import numpy as np
from os.path import join
import cv2
import argparse
import torch
from torch import nn
import torch.nn.functional as F
i... | [
"torch.cat",
"cv2.warpAffine",
"numpy.sin",
"torch.nn.init.constant_",
"torch.utils.model_zoo.load_url",
"line_detection_module.models.networks.DCNv2.dcn_v2.DCN",
"torch.load",
"torch.nn.functional.max_pool2d",
"cv2.resize",
"numpy.partition",
"numpy.log2",
"torch.nn.Conv2d",
"torch.nn.Batch... | [((673, 700), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (690, 700), False, 'import logging\n'), ((948, 1037), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kerne... |
# Year 2022
# Based on fink-broker.org code
# https://github.com/astrolabsoftware/fink-science/tree/master/fink_science/xmatch
# Adapted by <NAME>
import io
import csv
import logging
import requests
import numpy as np
import pandas as pd
def generate_csv(s: str, lists: list) -> str:
""" Make a string (CSV format... | [
"pandas.DataFrame",
"io.StringIO",
"csv.writer",
"logging.warning",
"pandas.merge",
"numpy.transpose",
"numpy.array",
"requests.post"
] | [((928, 941), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (939, 941), False, 'import io\n'), ((955, 1003), 'csv.writer', 'csv.writer', (['output'], {'quoting': 'csv.QUOTE_NONNUMERIC'}), '(output, quoting=csv.QUOTE_NONNUMERIC)\n', (965, 1003), False, 'import csv\n'), ((4635, 4901), 'requests.post', 'requests.post', ... |
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from datetime import datetime
from keras.models import load_model
model = load_model('chatbot_model.h5') #Load trained model output from train_chatbot.py as an input to chatgui.py
import json
import ra... | [
"keras.models.load_model",
"nltk.stem.WordNetLemmatizer",
"random.choice",
"numpy.array",
"nltk.word_tokenize"
] | [((65, 84), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (82, 84), False, 'from nltk.stem import WordNetLemmatizer\n'), ((193, 223), 'keras.models.load_model', 'load_model', (['"""chatbot_model.h5"""'], {}), "('chatbot_model.h5')\n", (203, 223), False, 'from keras.models import load_model\n'), ... |
import numpy as np
import math
import scipy.ndimage
def frequest(im, orientim, kernel_size, minWaveLength, maxWaveLength):
"""
Based on https://pdfs.semanticscholar.org/ca0d/a7c552877e30e1c5d87dfcfb8b5972b0acd9.pdf pg.14
Function to estimate the fingerprint ridge frequency within a small block
of a fi... | [
"numpy.abs",
"numpy.sum",
"numpy.double",
"math.atan2",
"numpy.median",
"numpy.fix",
"numpy.zeros",
"numpy.ones",
"numpy.shape",
"numpy.sin",
"numpy.where",
"numpy.reshape",
"numpy.cos",
"numpy.array",
"numpy.mean",
"numpy.sqrt"
] | [((596, 608), 'numpy.shape', 'np.shape', (['im'], {}), '(im)\n', (604, 608), True, 'import numpy as np\n'), ((791, 811), 'numpy.cos', 'np.cos', (['(2 * orientim)'], {}), '(2 * orientim)\n', (797, 811), True, 'import numpy as np\n'), ((856, 876), 'numpy.sin', 'np.sin', (['(2 * orientim)'], {}), '(2 * orientim)\n', (862,... |
# Code example for ICP taking a sequence of point clouds relatively close
# and build a map with them.
# It assumes that: 3D point clouds are used, they were recorded in sequence
# and they are express in sensor frame.
import numpy as np
from pypointmatcher import pointmatcher as pm, pointmatchersupport as pms
PM = ... | [
"numpy.identity",
"pypointmatcher.pointmatchersupport.Parametrizable.Parameters",
"pypointmatcher.pointmatchersupport.validateFile"
] | [((389, 420), 'pypointmatcher.pointmatchersupport.Parametrizable.Parameters', 'pms.Parametrizable.Parameters', ([], {}), '()\n', (418, 420), True, 'from pypointmatcher import pointmatcher as pm, pointmatchersupport as pms\n'), ((1390, 1419), 'pypointmatcher.pointmatchersupport.validateFile', 'pms.validateFile', (['conf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.