code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import unittest
import dace
import numpy as np
from dace.transformation.dataflow import MapTiling, OutLocalStorage
N = dace.symbol('N')
@dace.program
def arange():
out = np.ndarray([N], np.int32)
for i in dace.map[0:N]:
with dace.tasklet:
o >> out[i]
o = i
return out
cla... | [
"numpy.ones",
"dace.propagate_memlets_sdfg",
"dace.symbol",
"numpy.ndarray",
"unittest.main",
"numpy.arange"
] | [((120, 136), 'dace.symbol', 'dace.symbol', (['"""N"""'], {}), "('N')\n", (131, 136), False, 'import dace\n'), ((177, 202), 'numpy.ndarray', 'np.ndarray', (['[N]', 'np.int32'], {}), '([N], np.int32)\n', (187, 202), True, 'import numpy as np\n'), ((1422, 1437), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1435, ... |
import django
from django.test import TestCase
from django.template import Template, Context
class genericObj(object):
"""
A generic object for testing templatetags
"""
def __init__(self):
self.name = "test"
self.status = "ready"
def getOption(self, optionName):
... | [
"django.template.Template",
"django.template.Context"
] | [((685, 706), 'django.template.Context', 'Context', (['context_dict'], {}), '(context_dict)\n', (692, 706), False, 'from django.template import Template, Context\n'), ((716, 741), 'django.template.Template', 'Template', (['template_string'], {}), '(template_string)\n', (724, 741), False, 'from django.template import Te... |
import pytest
import rumps
from src.app_functions.menu.change_auto_login import change_auto_login
@pytest.fixture(name="basic_app")
def create_app():
"""Creates a basic app object with some variables to pass to functions
Returns:
rumps.App: Basic app
"""
app = rumps.App("TestApp")
app.set... | [
"pytest.fixture",
"rumps.App",
"src.app_functions.menu.change_auto_login.change_auto_login"
] | [((101, 133), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""basic_app"""'}), "(name='basic_app')\n", (115, 133), False, 'import pytest\n'), ((288, 308), 'rumps.App', 'rumps.App', (['"""TestApp"""'], {}), "('TestApp')\n", (297, 308), False, 'import rumps\n'), ((661, 689), 'src.app_functions.menu.change_auto_logi... |
# -*- coding: utf-8 -*-
"""VGG 19 architecture for CIFAR-100."""
import tensorflow as tf
from ._vgg import _vgg
from ..datasets.cifar100 import cifar100
from .testproblem import TestProblem
class cifar100_vgg19(TestProblem):
"""DeepOBS test problem class for the VGG 19 network on Cifar-100.
The CIFAR-100 ima... | [
"tensorflow.equal",
"tensorflow.losses.get_regularization_loss",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.argmax",
"tensorflow.cast"
] | [((2453, 2490), 'tensorflow.equal', 'tf.equal', (['self.dataset.phase', '"""train"""'], {}), "(self.dataset.phase, 'train')\n", (2461, 2490), True, 'import tensorflow as tf\n'), ((2724, 2799), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'labels': 'y', 'logit... |
import asyncio
import functools
import time
import weakref
from collections import defaultdict
from typing import AsyncIterable
from typing import Awaitable
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import TypeVar
T = TypeVar("T")
# NOTE: thi... | [
"functools._make_key",
"functools.wraps",
"collections.defaultdict",
"time.time",
"weakref.ref",
"typing.TypeVar"
] | [((294, 306), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (301, 306), False, 'from typing import TypeVar\n'), ((1062, 1116), 'functools._make_key', 'functools._make_key', (['args_for_key', 'kwargs'], {'typed': '(False)'}), '(args_for_key, kwargs, typed=False)\n', (1081, 1116), False, 'import functools\n'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""
Basis Pursuit DeNoising
=======================
This example demonstrates the use of class :class:`.admm.bpdn.... | [
"numpy.abs",
"builtins.input",
"sporco.util.grid_search",
"numpy.hstack",
"sporco.admm.bpdn.BPDN",
"numpy.zeros",
"numpy.random.seed",
"numpy.vstack",
"sporco.admm.bpdn.BPDN.Options",
"sporco.plot.figure",
"sporco.plot.subplot",
"numpy.logspace",
"numpy.random.randn",
"sporco.plot.plot"
] | [((1417, 1438), 'numpy.random.seed', 'np.random.seed', (['(12345)'], {}), '(12345)\n', (1431, 1438), True, 'import numpy as np\n'), ((1443, 1464), 'numpy.random.randn', 'np.random.randn', (['N', 'M'], {}), '(N, M)\n', (1458, 1464), True, 'import numpy as np\n'), ((1470, 1486), 'numpy.zeros', 'np.zeros', (['(M, 1)'], {}... |
import pygame
from game.game_logic.game import Game
import matplotlib.pyplot as plt
def main():
scores_history = []
GAME_COUNT = 2
for i in range(GAME_COUNT):
game = Game(400, "Snake AI")
score = game.start()
scores_history.append(score)
print("Game:", i)
plt.ylim(0, 3... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"game.game_logic.game.Game",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show"
] | [((307, 322), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(36)'], {}), '(0, 36)\n', (315, 322), True, 'import matplotlib.pyplot as plt\n'), ((384, 410), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Snake length"""'], {}), "('Snake length')\n", (394, 410), True, 'import matplotlib.pyplot as plt\n'), ((415, 439), ... |
import os
import sys
from glob import glob
def create_list(images_dir, output_file, img_ext=".jpg"):
ImgList = os.listdir(images_dir)
val_list = []
for img in ImgList:
img,ext = img.split(".")
val_list.append(img)
with open(os.path.join(images_dir, output_file),'w') as fid:
... | [
"os.listdir",
"os.path.join",
"sys.exit"
] | [((117, 139), 'os.listdir', 'os.listdir', (['images_dir'], {}), '(images_dir)\n', (127, 139), False, 'import os\n'), ((521, 532), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (529, 532), False, 'import sys\n'), ((265, 302), 'os.path.join', 'os.path.join', (['images_dir', 'output_file'], {}), '(images_dir, output_fil... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# src: http://datareview.info/article/prognozirovanie-ottoka-klientov-so-scikit-learn/
# In[ ]:
# Показатель оттока клиентов – бизнес-термин, описывающий
# насколько интенсивно клиенты покидают компанию или
# прекращают оплачивать товары или услуги.
# Это ключевой ... | [
"sklearn.metrics.confusion_matrix",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.precision_recall_fscore_support",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.accuracy_s... | [((1752, 1776), 'pandas.read_csv', 'pd.read_csv', (['"""churn.csv"""'], {}), "('churn.csv')\n", (1763, 1776), True, 'import pandas as pd\n'), ((2422, 2452), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': '(True)'}), '(with_mean=True)\n', (2436, 2452), False, 'from sklearn.preprocessing imp... |
import requests
import tarfile
import os
def download_file(url, directory):
local_filename = os.path.join(directory, url.split('/')[-1])
print ("Downloading %s --> %s"%(url, local_filename))
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:... | [
"tarfile.open",
"requests.get",
"os.path.split",
"os.path.basename",
"os.walk"
] | [((484, 504), 'os.path.split', 'os.path.split', (['fpath'], {}), '(fpath)\n', (497, 504), False, 'import os\n'), ((962, 980), 'os.walk', 'os.walk', (['startpath'], {}), '(startpath)\n', (969, 980), False, 'import os\n'), ((209, 239), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n... |
""" A bar graph.
(c) September 2017 by <NAME>
"""
import argparse
from collections import defaultdict
from keras.models import Sequential
from keras.layers import Dense, Activation
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import sys
np.set_printoptions(suppress=True, ... | [
"numpy.mean",
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.style.use",
"numpy.array",
"matplotlib.pyplot.tight_layout",
"numpy.std",
"matplotlib.pyplot.title",
"numpy.load"... | [((201, 222), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (215, 222), False, 'import matplotlib\n'), ((285, 334), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)', 'linewidth': '(200)'}), '(suppress=True, linewidth=200)\n', (304, 334), True, 'import numpy as np\n'), ... |
# SPDX-License-Identifier: Apache-2.0
"""Unit Tests for custom rnns."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import init_ops
from backend_test_base import Tf2OnnxBackendTest... | [
"tensorflow.contrib.seq2seq.BahdanauAttention",
"tensorflow.contrib.seq2seq.AttentionWrapper",
"tf2onnx.tf_loader.is_tf2",
"numpy.array",
"numpy.stack",
"tensorflow.sigmoid",
"tensorflow.concat",
"tensorflow.matmul",
"tensorflow.identity",
"tensorflow.python.ops.init_ops.constant_initializer",
"... | [((584, 592), 'tf2onnx.tf_loader.is_tf2', 'is_tf2', ([], {}), '()\n', (590, 592), False, 'from tf2onnx.tf_loader import is_tf2\n'), ((1563, 1627), 'numpy.array', 'np.array', (['[[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]'], {'dtype': 'np.float32'}), '([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]], dtype=np.float32)\n', (1571, 1627), T... |
#!/user/bin/env python3
# -*- coding: utf-8 -*-
#!/user/bin/env python3
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Email: <EMAIL>
# @Date: 04.2020
# Context: CHARM PROJECT - Harzard perception
"""
Module documentation.
"""
# Imports
import sys
#import os
# Global variables
# Class declarations
# Function decl... | [
"sys.exit"
] | [((444, 455), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (452, 455), False, 'import sys\n')] |
# Databricks notebook source
from pyspark.sql.types import *
from pyspark.sql import functions as F
import base64
import array
# COMMAND ----------
# s is a base64 encoded float[] with first element being the magnitude
def Base64ToFloatArray(s):
arr = array.array('f', base64.b64decode(s))
return (arr[0], arr[1:])... | [
"pyspark.sql.functions.udf",
"pyspark.sql.functions.lit",
"base64.b64decode"
] | [((646, 660), 'pyspark.sql.functions.udf', 'F.udf', (['"""float"""'], {}), "('float')\n", (651, 660), True, 'from pyspark.sql import functions as F\n'), ((273, 292), 'base64.b64decode', 'base64.b64decode', (['s'], {}), '(s)\n', (289, 292), False, 'import base64\n'), ((2664, 2680), 'pyspark.sql.functions.lit', 'F.lit', ... |
#! /usr/bin/env python3
from .base_miner import BasePostGradientMiner
import torch
from ..utils import loss_and_miner_utils as lmu
# adapted from
# https://github.com/chaoyuaw/incubator-mxnet/blob/master/example/gluon/
# /embedding_learning/model.py
class DistanceWeightedMiner(BasePostGradientMiner):
def __init_... | [
"torch.unique",
"torch.log",
"torch.max",
"torch.tensor",
"torch.sum"
] | [((548, 568), 'torch.unique', 'torch.unique', (['labels'], {}), '(labels)\n', (560, 568), False, 'import torch\n'), ((1681, 1720), 'torch.sum', 'torch.sum', (['weights'], {'dim': '(1)', 'keepdim': '(True)'}), '(weights, dim=1, keepdim=True)\n', (1690, 1720), False, 'import torch\n'), ((1090, 1109), 'torch.log', 'torch.... |
from functools import partial
from pulsar import Connection, Pool, get_actor
from pulsar.utils.pep import to_string
from pulsar.apps.data import RemoteStore
from pulsar.apps.ds import redis_parser
from .client import RedisClient, Pipeline, Consumer, ResponseError
from .pubsub import RedisPubSub, RedisChannels
class... | [
"pulsar.apps.ds.redis_parser",
"pulsar.Pool",
"pulsar.utils.pep.to_string",
"functools.partial",
"pulsar.get_actor"
] | [((1192, 1231), 'functools.partial', 'partial', (['RedisStoreConnection', 'Consumer'], {}), '(RedisStoreConnection, Consumer)\n', (1199, 1231), False, 'from functools import partial\n'), ((1776, 1832), 'pulsar.Pool', 'Pool', (['self.connect'], {'pool_size': 'pool_size', 'loop': 'self._loop'}), '(self.connect, pool_size... |
# Generated by Django 3.0.7 on 2020-06-16 05:23
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('tasks', '0004_auto_20200616_0116'),
]
operations = [
migrations.AddField(
model_name='userreward',
... | [
"django.db.models.DateTimeField"
] | [((369, 443), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'default': 'django.utils.timezone.now'}), '(auto_now_add=True, default=django.utils.timezone.now)\n', (389, 443), False, 'from django.db import migrations, models\n'), ((612, 647), 'django.db.models.DateTimeField', '... |
import deephaven.TableTools as tt
import deephaven.Plot as plt
t = tt.emptyTable(50)\
.update("X = i + 5", "XLow = X -1", "XHigh = X + 1", "Y = Math.random() * 5", "YLow = Y - 1", "YHigh = Y + 1", "USym = i % 2 == 0 ? `AAPL` : `MSFT`")
p = plt.plot("S1", t, "X", "Y").lineColor("black").show()
p2 = plt.plot("S1"... | [
"deephaven.Plot.catHistPlot",
"deephaven.Plot.plot3d",
"deephaven.Plot.plot",
"deephaven.Plot.figure",
"deephaven.Plot.histPlot",
"deephaven.Plot.piePlot",
"deephaven.TableTools.emptyTable",
"deephaven.Plot.catPlot",
"deephaven.Plot.plotBy",
"deephaven.TableTools.doubleCol",
"deephaven.Plot.erro... | [((1214, 1244), 'deephaven.Plot.piePlot', 'plt.piePlot', (['"""S1"""', 't', '"""X"""', '"""Y"""'], {}), "('S1', t, 'X', 'Y')\n", (1225, 1244), True, 'import deephaven.Plot as plt\n'), ((2181, 2245), 'deephaven.Plot.ohlcPlot', 'plt.ohlcPlot', (['"""Test1"""', 't', '"""Time"""', '"""Open"""', '"""High"""', '"""Low"""', '... |
# Copyright 2019 <NAME>
#
# 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 i... | [
"logging.getLogger",
"flask.render_template",
"rhoci.test.bp.route",
"flask.url_for"
] | [((757, 784), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (774, 784), False, 'import logging\n'), ((823, 841), 'rhoci.test.bp.route', 'bp.route', (['"""/index"""'], {}), "('/index')\n", (831, 841), False, 'from rhoci.test import bp\n'), ((843, 856), 'rhoci.test.bp.route', 'bp.route', (... |
import typing
from .core import Component
_Controller = typing.TypeVar('_Controller')
_ControllerType = typing.Type[_Controller]
ControllerFactory = typing.NewType('ControllerFactory', typing.Callable[[typing.Type], object])
_controller_factory: typing.Optional[ControllerFactory] = None
def controller(controller_cl... | [
"typing.NewType",
"typing.TypeVar"
] | [((58, 87), 'typing.TypeVar', 'typing.TypeVar', (['"""_Controller"""'], {}), "('_Controller')\n", (72, 87), False, 'import typing\n'), ((151, 226), 'typing.NewType', 'typing.NewType', (['"""ControllerFactory"""', 'typing.Callable[[typing.Type], object]'], {}), "('ControllerFactory', typing.Callable[[typing.Type], objec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import calendar
import csv
from datetime import datetime
import os
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_
from ..constants import CONST
from ..models import AccidentMarker
from ..utilities import init_flask, decode_hebrew, open_utf8
from ..imp... | [
"logging.basicConfig",
"datetime.datetime",
"requests.session",
"os.listdir",
"logging.warn",
"calendar.Calendar",
"xml.dom.minidom.Document",
"math.sqrt",
"xml.dom.minidom.parseString",
"csv.reader",
"flask_sqlalchemy.SQLAlchemy",
"logging.info",
"sqlalchemy.and_"
] | [((2034, 2074), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (2053, 2074), False, 'import logging\n'), ((2083, 2101), 'requests.session', 'requests.session', ([], {}), '()\n', (2099, 2101), False, 'import requests\n'), ((2180, 2207), 'xml.dom.minidom.parseSt... |
import unittest
from numpy.testing import assert_array_equal
import numpy as np
from libact.base.dataset import Dataset
from libact.models import LogisticRegression
from libact.query_strategies import VarianceReduction
from .utils import run_qs
class VarianceReductionTestCase(unittest.TestCase):
"""Variance red... | [
"unittest.main",
"numpy.array",
"libact.models.LogisticRegression"
] | [((936, 951), 'unittest.main', 'unittest.main', ([], {}), '()\n', (949, 951), False, 'import unittest\n'), ((879, 901), 'numpy.array', 'np.array', (['[4, 5, 2, 3]'], {}), '([4, 5, 2, 3])\n', (887, 901), True, 'import numpy as np\n'), ((759, 779), 'libact.models.LogisticRegression', 'LogisticRegression', ([], {}), '()\n... |
# Copyright 2015, Rackspace, US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | [
"openstack_dashboard.api.swift.swift_upload_object",
"openstack_dashboard.api.swift.swift_delete_container",
"openstack_dashboard.api.swift.swift_create_container",
"openstack_dashboard.api.swift.swift_copy_object",
"openstack_dashboard.api.swift.swift_create_pseudo_folder",
"openstack_dashboard.api.rest.... | [((1200, 1217), 'openstack_dashboard.api.rest.utils.ajax', 'rest_utils.ajax', ([], {}), '()\n', (1215, 1217), True, 'from openstack_dashboard.api.rest import utils as rest_utils\n'), ((1573, 1590), 'openstack_dashboard.api.rest.utils.ajax', 'rest_utils.ajax', ([], {}), '()\n', (1588, 1590), True, 'from openstack_dashbo... |
'''Load image/class/box from a annotation file.
The annotation file is organized as:
image_name #obj xmin ymin xmax ymax class_index ..
'''
from __future__ import print_function
import os
import sys
import os.path
import random
import numpy as np
import torch
import torch.utils.data as data
import torchvision.t... | [
"random.choice",
"random.randrange",
"torch.LongTensor",
"os.path.join",
"torch.Tensor",
"encoder.DataEncoder",
"random.random"
] | [((938, 951), 'encoder.DataEncoder', 'DataEncoder', ([], {}), '()\n', (949, 951), False, 'from encoder import DataEncoder\n'), ((2156, 2186), 'os.path.join', 'os.path.join', (['self.root', 'fname'], {}), '(self.root, fname)\n', (2168, 2186), False, 'import os\n'), ((3309, 3324), 'random.random', 'random.random', ([], {... |
# Lint as: python3
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | [
"lingvo.core.activations.ActivationLayer.Params",
"lingvo.core.builder_layers.ReshapeLayer.Params",
"lingvo.core.builder_layers.CreateNestedMapLayer.Params",
"lingvo.core.py_utils.NestedMap",
"lingvo.core.layers.DeterministicDropoutLayer.Params",
"lingvo.core.layers.FetchLayer.Params",
"lingvo.core.buil... | [((1971, 2006), 'lingvo.core.hyperparams.InstantiableParams', 'hyperparams.InstantiableParams', (['cls'], {}), '(cls)\n', (2001, 2006), False, 'from lingvo.core import hyperparams\n'), ((11168, 11203), 'lingvo.core.builder_layers.LinearLayer.Params', 'builder_layers.LinearLayer.Params', ([], {}), '()\n', (11201, 11203)... |
# -*- coding: utf-8 -*-
# file: preprocess.py
# author: jackie
# Copyright (C) 2021. All Rights Reserved.
import os
import pandas as pd
import argparse
import emoji
import re
from sklearn.model_selection import train_test_split
parser = argparse.ArgumentParser()
parser.add_argument("--inpath", type=str, required=True... | [
"os.path.exists",
"argparse.ArgumentParser",
"re.compile",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"os.makedirs",
"os.path.join",
"os.remove"
] | [((239, 264), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (262, 264), False, 'import argparse\n'), ((3310, 3336), 'os.path.exists', 'os.path.exists', (['dist_fname'], {}), '(dist_fname)\n', (3324, 3336), False, 'import os\n'), ((3428, 3447), 'pandas.read_csv', 'pd.read_csv', (['inpath'], {})... |
import os
import shutil
import requests
def get_cat(folder, name):
url = "http://consuming-python-services-api.azurewebsites.net/cats/random"
data = get_data_from_url(url)
save_image(folder, name, data)
def get_data_from_url(url):
response = requests.get(url, stream=True)
return response.raw
... | [
"os.path.join",
"shutil.copyfileobj",
"requests.get"
] | [((263, 293), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (275, 293), False, 'import requests\n'), ((372, 407), 'os.path.join', 'os.path.join', (['folder', "(name + '.jpg')"], {}), "(folder, name + '.jpg')\n", (384, 407), False, 'import os\n'), ((456, 486), 'shutil.copyfileo... |
# -*- coding: utf-8 -*-
"""
media info manager module.
"""
from pyrin.core.mixin import HookMixin
from pyrin.core.structs import Manager
import pyrin.utils.path as path_utils
from charma.media_info import MediaInfoPackage
from charma.media_info.interface import AbstractMediaInfoProvider
from charma.media_info.except... | [
"pyrin.utils.path.assert_is_file"
] | [((1994, 2025), 'pyrin.utils.path.assert_is_file', 'path_utils.assert_is_file', (['file'], {}), '(file)\n', (2019, 2025), True, 'import pyrin.utils.path as path_utils\n')] |
import unittest
from boxrec.parsers import FightParser
class MockResponse(object):
def __init__(self, content, encoding, url):
self.content= content
self.encoding = encoding
self.url = url
class TestFightParser(unittest.TestCase):
def setUp(self):
with open('mock_data/fights/... | [
"boxrec.parsers.FightParser"
] | [((413, 426), 'boxrec.parsers.FightParser', 'FightParser', ([], {}), '()\n', (424, 426), False, 'from boxrec.parsers import FightParser\n')] |
# Copyright 2012 OpenStack Foundation
# 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 requ... | [
"copy.deepcopy"
] | [((3031, 3056), 'copy.deepcopy', 'copy.deepcopy', (['self._info'], {}), '(self._info)\n', (3044, 3056), False, 'import copy\n')] |
import socket
import csv
import traceback
import threading
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
usrpass={}
def openfile():
filename="login_credentials.csv"
with open(filename,'r')as csvfile:
csv_file = csv.reader(csvfile, delimiter=",")
for col in csv_file:
usrpas... | [
"socket.gethostbyname",
"socket.gethostname",
"socket.socket",
"csv.reader"
] | [((62, 111), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (75, 111), False, 'import socket\n'), ((401, 421), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (419, 421), False, 'import socket\n'), ((427, 454), 'socket.gethostbyn... |
from itertools import product
from sklearn.base import clone
from sklearn.preprocessing import FunctionTransformer
from sklearn.model_selection import ParameterGrid
from imblearn.pipeline import Pipeline
from rlearn.utils import check_random_states
def check_pipelines(objects_list, random_state, n_runs):
"""Extra... | [
"rlearn.utils.check_random_states",
"sklearn.model_selection.ParameterGrid",
"sklearn.base.clone",
"itertools.product",
"imblearn.pipeline.Pipeline",
"sklearn.preprocessing.FunctionTransformer"
] | [((407, 448), 'rlearn.utils.check_random_states', 'check_random_states', (['random_state', 'n_runs'], {}), '(random_state, n_runs)\n', (426, 448), False, 'from rlearn.utils import check_random_states\n'), ((517, 539), 'itertools.product', 'product', (['*objects_list'], {}), '(*objects_list)\n', (524, 539), False, 'from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from clean_transcript import clean_transcript
ALPHABET_FILE_PATH = "/DeepSpeech/bin/bangor_welsh/alphabet.txt"
def validate_label(label):
clean = clean_transcript(ALPHABET_FILE_PATH)
cleaned, transcript = clean.clean(label)
if cleaned:
return transc... | [
"clean_transcript.clean_transcript"
] | [((201, 237), 'clean_transcript.clean_transcript', 'clean_transcript', (['ALPHABET_FILE_PATH'], {}), '(ALPHABET_FILE_PATH)\n', (217, 237), False, 'from clean_transcript import clean_transcript\n')] |
# Copyright (c) 2019-2020, NVIDIA CORPORATION. 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... | [
"torch.nn.functional.linear",
"torch.nn.Identity",
"torch.nn.Dropout",
"torch.nn.Embedding",
"torch.nn.ModuleList",
"torch.FloatTensor",
"torch.typename",
"torch.zeros_like",
"torch.cat",
"torch.arange",
"functools.partial",
"torch.nn.functional.log_softmax",
"torch.nn.ParameterList",
"tor... | [((13488, 13533), 'functools.partial', 'functools.partial', (['_init_weight'], {'default': '(0.02)'}), '(_init_weight, default=0.02)\n', (13505, 13533), False, 'import functools\n'), ((13547, 13592), 'functools.partial', 'functools.partial', (['_init_weight'], {'default': '(0.01)'}), '(_init_weight, default=0.01)\n', (... |
import json
import csv
import sys
import os
import re
import codecs
import logging
from logging.config import dictConfig
import click
import yaml
from sqlalchemy import create_engine
from jsontableschema_sql import Storage
from smart_open import smart_open
from . import postgres
from . import carto
csv.field_size_li... | [
"csv.field_size_limit",
"logging.getLogger",
"click.argument",
"json.loads",
"logging.basicConfig",
"os.getenv",
"click.group",
"click.option",
"sqlalchemy.create_engine",
"logging.config.dictConfig",
"re.match",
"csv.writer",
"yaml.load",
"json.dumps",
"smart_open.smart_open",
"jsonta... | [((303, 336), 'csv.field_size_limit', 'csv.field_size_limit', (['sys.maxsize'], {}), '(sys.maxsize)\n', (323, 336), False, 'import csv\n'), ((899, 912), 'click.group', 'click.group', ([], {}), '()\n', (910, 912), False, 'import click\n'), ((2014, 2042), 'click.argument', 'click.argument', (['"""table_name"""'], {}), "(... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli... | [
"subprocess.check_output",
"os.path.exists",
"nemo.utils.logging.info",
"json.loads",
"argparse.ArgumentParser",
"nemo.collections.asr.metrics.wer.WER",
"os.makedirs",
"nemo.collections.asr.models.EncDecCTCModel.from_pretrained",
"subprocess.run",
"os.path.join",
"torch.cuda.is_available",
"ne... | [((2469, 2494), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2492, 2494), False, 'import torch\n'), ((1409, 1448), 'os.path.join', 'os.path.join', (['sctk_dir', '"""bin"""', '"""sclite"""'], {}), "(sctk_dir, 'bin', 'sclite')\n", (1421, 1448), False, 'import os\n'), ((1598, 1617), 'os.path.ex... |
from manimlib.imports import *
from manimlib.utils import bezier
import numpy as np
class VectorInterpolator:
def __init__(self,points):
self.points = points
self.n = len(self.points)
self.dists = [0]
for i in range(len(self.points)):
self.dists += [np.linalg.norm(
... | [
"numpy.linalg.norm"
] | [((575, 641), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.points[(idx + 1) % self.n] - self.points[idx])'], {}), '(self.points[(idx + 1) % self.n] - self.points[idx])\n', (589, 641), True, 'import numpy as np\n'), ((300, 362), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.points[i] - self.points[(i + 1) % self.n]... |
from setuptools import setup
setup(name='rapid_plotly',
version='0.1',
description='Convenience functions to rapidly create beautiful Plotly graphs',
author='<NAME>',
author_email='<EMAIL>',
packages=['rapid_plotly'],
zip_safe=False)
| [
"setuptools.setup"
] | [((30, 247), 'setuptools.setup', 'setup', ([], {'name': '"""rapid_plotly"""', 'version': '"""0.1"""', 'description': '"""Convenience functions to rapidly create beautiful Plotly graphs"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'packages': "['rapid_plotly']", 'zip_safe': '(False)'}), "(name='rapid_... |
from __future__ import division
from unittest import skipIf, TestCase
import os
from pandas import DataFrame
import numpy as np
from numpy.testing import assert_array_equal
BACKEND_AVAILABLE = os.environ.get("ETS_TOOLKIT", "qt4") != "null"
if BACKEND_AVAILABLE:
from app_common.apptools.testing_utils import asser... | [
"app_common.apptools.testing_utils.assert_obj_gui_works",
"unittest.skipIf",
"os.environ.get",
"numpy.array",
"numpy.random.randn",
"numpy.testing.assert_array_equal"
] | [((5646, 5702), 'unittest.skipIf', 'skipIf', (['(not BACKEND_AVAILABLE)', '"""No UI backend available"""'], {}), "(not BACKEND_AVAILABLE, 'No UI backend available')\n", (5652, 5702), False, 'from unittest import skipIf, TestCase\n'), ((8462, 8518), 'unittest.skipIf', 'skipIf', (['(not BACKEND_AVAILABLE)', '"""No UI bac... |
from collections import namedtuple
# Basic example
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p[0] + p[1])
x, y = p
print(x, y)
print(p.x + p.y)
print(Point(x=11, y=22))
from collections import namedtuple
import csv
f = open("users.csv", "r")
next(f)
reader = csv.reader(f)
student_list = []
fo... | [
"collections.namedtuple",
"csv.reader"
] | [((60, 91), 'collections.namedtuple', 'namedtuple', (['"""Point"""', "['x', 'y']"], {}), "('Point', ['x', 'y'])\n", (70, 91), False, 'from collections import namedtuple\n'), ((286, 299), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (296, 299), False, 'import csv\n'), ((590, 620), 'collections.namedtuple', 'namedtu... |
#!/usr/bin/env python
from setuptools import setup
# Modified from http://stackoverflow.com/questions/2058802/
# how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package
def version():
import os
import re
init = os.path.join('dark', '__init__.py')
with open(init) as fp:
initDat... | [
"os.path.join",
"re.search"
] | [((242, 277), 'os.path.join', 'os.path.join', (['"""dark"""', '"""__init__.py"""'], {}), "('dark', '__init__.py')\n", (254, 277), False, 'import os\n'), ((346, 415), 're.search', 're.search', (['"""^__version__ = [\'\\\\"]([^\'\\\\"]+)[\'\\\\"]"""', 'initData', 're.M'], {}), '(\'^__version__ = [\\\'\\\\"]([^\\\'\\\\"]+... |
from __future__ import absolute_import
import os
import errno
from contextlib import contextmanager
__author__ = '<NAME>'
__copyright__ = 'Copyright 2013, The Materials Project'
__version__ = '0.1'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__date__ = '1/24/14'
@contextmanager
def cd(path):
"""
A Fabr... | [
"os.chdir",
"os.path.isdir",
"os.makedirs",
"os.getcwd"
] | [((593, 604), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (602, 604), False, 'import os\n'), ((609, 623), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (617, 623), False, 'import os\n'), ((668, 681), 'os.chdir', 'os.chdir', (['cwd'], {}), '(cwd)\n', (676, 681), False, 'import os\n'), ((1035, 1062), 'os.makedirs',... |
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for Amazon Kinesis Data Analytics SQL applications.]
# snippet-service:[kinesisanalytics]
# snippet-keyword:[Python]
# sn... | [
"datetime.datetime.now",
"random.random",
"random.choice",
"boto3.client"
] | [((1236, 1259), 'boto3.client', 'boto3.client', (['"""kinesis"""'], {}), "('kinesis')\n", (1248, 1259), False, 'import boto3\n'), ((1303, 1326), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1324, 1326), False, 'import datetime\n'), ((1411, 1465), 'random.choice', 'random.choice', (["['AAPL', 'AM... |
import numpy as np
import logging
import numbers
import torch
import math
import json
import sys
from torch.optim.lr_scheduler import LambdaLR
from torchvision.transforms.functional import pad
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
sel... | [
"logging.getLogger",
"logging.StreamHandler",
"logging.Formatter",
"numpy.max",
"torch.tensor",
"torch.cuda.is_available",
"json.load",
"json.dump"
] | [((3352, 3366), 'numpy.max', 'np.max', (['[w, h]'], {}), '([w, h])\n', (3358, 3366), True, 'import numpy as np\n'), ((4799, 4825), 'logging.getLogger', 'logging.getLogger', (['"""train"""'], {}), "('train')\n", (4816, 4825), False, 'import logging\n'), ((5465, 5500), 'torch.tensor', 'torch.tensor', (['[0.485, 0.456, 0.... |
import pytest
from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable
pytestmark = skip_if_pylint_unavailable()
@pytest.fixture(scope="module")
def test_case():
import pylint.testutils
from pylint_plugins import AssertRaisesWithoutMsg
class TestAssertRaisesWithou... | [
"pytest.fixture",
"tests.pylint_plugins.utils.skip_if_pylint_unavailable",
"tests.pylint_plugins.utils.extract_node",
"tests.pylint_plugins.utils.create_message"
] | [((125, 153), 'tests.pylint_plugins.utils.skip_if_pylint_unavailable', 'skip_if_pylint_unavailable', ([], {}), '()\n', (151, 153), False, 'from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable\n'), ((157, 187), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'})... |
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors
import csv
from scipy.stats import mode
import math as m
import os
import collections
#set working directory
#os.chdir("/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_15072... | [
"matplotlib.use",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"pandas.read_table"
] | [((57, 78), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (71, 78), False, 'import matplotlib\n'), ((897, 918), 'pandas.read_table', 'pd.read_table', (['file_1'], {}), '(file_1)\n', (910, 918), True, 'import pandas as pd\n'), ((931, 952), 'pandas.read_table', 'pd.read_table', (['file_2'], {}), '... |
import logging
from flask import Blueprint
from flask import Flask, render_template, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField, validators, SelectField, BooleanField
from wtforms.fields.html5 import IntegerRangeField
from wtforms.widgets import TextArea
import langid
from utils.u... | [
"wtforms.validators.NumberRange",
"wtforms.widgets.TextArea",
"flask.flash",
"wtforms.BooleanField",
"logging.exception",
"langid.lang_of_text",
"utils.utils.templated",
"flask.Blueprint",
"wtforms.validators.DataRequired",
"wtforms.validators.URL"
] | [((362, 391), 'flask.Blueprint', 'Blueprint', (['"""langid"""', '__name__'], {}), "('langid', __name__)\n", (371, 391), False, 'from flask import Blueprint\n'), ((1575, 1598), 'utils.utils.templated', 'templated', (['"""index.html"""'], {}), "('index.html')\n", (1584, 1598), False, 'from utils.utils import templated\n'... |
"""
BespokeFit
Creating bespoke parameters for individual molecules.
"""
import logging
import sys
from ._version import get_versions
versions = get_versions()
__version__ = versions["version"]
__git_revision__ = versions["full-revisionid"]
del get_versions, versions
# Silence verbose messages when running the CLI ... | [
"logging.getLogger",
"openff.bespokefit.utilities.logging.DeprecationWarningFilter"
] | [((689, 715), 'openff.bespokefit.utilities.logging.DeprecationWarningFilter', 'DeprecationWarningFilter', ([], {}), '()\n', (713, 715), False, 'from openff.bespokefit.utilities.logging import DeprecationWarningFilter\n'), ((595, 630), 'logging.getLogger', 'logging.getLogger', (['"""openff.toolkit"""'], {}), "('openff.t... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 03 11:06:37 2018
@author: vmg
"""
import sdf
import numpy as np
# Load 2006 LUT for interpolation
# 2006 Groeneveld Look-Up Table as presented in
# "2006 CHF Look-Up Table", Nuclear Engineering and Design 237, pp. 190-1922.
# This file requires the file 2006LUTdata.tx... | [
"sdf.Group",
"numpy.array",
"numpy.zeros",
"numpy.loadtxt",
"sdf.save",
"sdf.Dataset"
] | [((517, 695), 'numpy.array', 'np.array', (['(0.0, 50.0, 100.0, 300.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 2500.0, \n 3000.0, 3500.0, 4000.0, 4500.0, 5000.0, 5500.0, 6000.0, 6500.0, 7000.0,\n 7500.0, 8000.0)'], {}), '((0.0, 50.0, 100.0, 300.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, \n 2500.0, 3000.0, 3500.0, 4... |
import unittest
from pathlib import Path
from pprint import pprint
from vint.compat.itertools import zip_longest
from vint.linting.linter import Linter
from vint.linting.config.config_default_source import ConfigDefaultSource
class PolicyAssertion(unittest.TestCase):
class StubPolicySet(object):
def __ini... | [
"vint.linting.config.config_default_source.ConfigDefaultSource",
"pprint.pprint",
"vint.compat.itertools.zip_longest",
"pathlib.Path"
] | [((2791, 2835), 'pathlib.Path', 'Path', (['"""test"""', '"""fixture"""', '"""policy"""', '*filename'], {}), "('test', 'fixture', 'policy', *filename)\n", (2795, 2835), False, 'from pathlib import Path\n'), ((2016, 2034), 'pprint.pprint', 'pprint', (['violations'], {}), '(violations)\n', (2022, 2034), False, 'from pprin... |
import copy
import json
import logging
import os
import sys
import time
from collections import defaultdict
import numpy as np
import tensorflow as tf
from sklearn import decomposition
from .. import dp_logging
from . import labeler_utils
from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel
... | [
"logging.getLogger",
"tensorflow.reduce_sum",
"tensorflow.math.divide_no_nan",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.load_model",
"copy.deepcopy",
"tensorflow.reduce_mean",
"tensorflow.cast",
"tensorflow.math.minimum",
"tensorflow... | [((775, 806), 'logging.getLogger', 'logging.getLogger', (['"""tensorflow"""'], {}), "('tensorflow')\n", (792, 806), False, 'import logging\n'), ((859, 903), 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {}), '()\n', (901, 903), True, 'import tensorflow as tf\n'... |
# -*- coding: utf-8 -*-
#
# 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
#... | [
"flask.request.args.get",
"airflow.hooks.hive_hooks.HiveCliHook",
"json.dumps",
"pandas.set_option",
"airflow.hooks.presto_hook.PrestoHook",
"flask_admin.expose",
"flask.Blueprint",
"airflow.hooks.hive_hooks.HiveMetastoreHook",
"airflow.hooks.mysql_hook.MySqlHook"
] | [((1547, 1588), 'pandas.set_option', 'pd.set_option', (['"""display.max_colwidth"""', '(-1)'], {}), "('display.max_colwidth', -1)\n", (1560, 1588), True, 'import pandas as pd\n'), ((5719, 5861), 'flask.Blueprint', 'Blueprint', (['"""metastore_browser"""', '__name__'], {'template_folder': '"""templates"""', 'static_fold... |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
import stat
import tempfile
import threading
from typing import List
from sys import argv
import os
import requests
import shutil
import json
import yaml
import subprocess
from lib.composegenerator.v0.generate imp... | [
"os.listdir",
"os.chmod",
"lib.metadata.getSimpleAppRegistry",
"os.path.isdir",
"lib.composegenerator.v1.generate.createComposeConfigFromV1",
"lib.validate.findAndValidateApps",
"subprocess.check_output",
"yaml.dump",
"shutil.ignore_patterns",
"lib.appymlgenerator.convertComposeYMLToAppYML",
"re... | [((893, 928), 'os.path.join', 'os.path.join', (['scriptDir', '""".."""', '""".."""'], {}), "(scriptDir, '..', '..')\n", (905, 928), False, 'import os\n'), ((939, 969), 'os.path.join', 'os.path.join', (['nodeRoot', '"""apps"""'], {}), "(nodeRoot, 'apps')\n", (951, 969), False, 'import os\n'), ((985, 1021), 'os.path.join... |
# Based on local.py (c) 2012, <NAME> <<EMAIL>>
# Based on chroot.py (c) 2013, <NAME> <<EMAIL>>
# Based on func.py
# (c) 2014, <NAME> <<EMAIL>>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print... | [
"base64.b64encode",
"os.path.join",
"salt.client.LocalClient",
"os.path.normpath",
"ansible.errors.AnsibleError"
] | [((1432, 1448), 'salt.client.LocalClient', 'sc.LocalClient', ([], {}), '()\n', (1446, 1448), True, 'import salt.client as sc\n'), ((2497, 2519), 'os.path.normpath', 'os.path.normpath', (['path'], {}), '(path)\n', (2513, 2519), False, 'import os\n'), ((2535, 2569), 'os.path.join', 'os.path.join', (['prefix', 'normpath[1... |
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from servers.models import Compute
from create.models import Flavor
from instance.models import Instance
from libvirt import l... | [
"django.http.HttpResponseRedirect",
"vrtManager.util.randomMAC",
"servers.models.Compute.objects.get",
"django.utils.translation.ugettext_lazy",
"create.models.Flavor.objects.filter",
"vrtManager.create.wvmCreate",
"create.forms.NewVMForm",
"django.template.RequestContext",
"vrtManager.util.randomUU... | [((645, 676), 'servers.models.Compute.objects.get', 'Compute.objects.get', ([], {'id': 'host_id'}), '(id=host_id)\n', (664, 676), False, 'from servers.models import Compute\n'), ((583, 613), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', (['"""/login"""'], {}), "('/login')\n", (603, 613), False, 'from djan... |
import torch
__author__ = 'Andres'
def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
batch_size = real_data.size()[0]
alpha = torch.rand(batch_size, 1, 1, 1)
alpha = alpha.expand(real_data.size()).to(devi... | [
"torch.cuda.is_available",
"torch.autograd.Variable",
"torch.rand"
] | [((238, 269), 'torch.rand', 'torch.rand', (['batch_size', '(1)', '(1)', '(1)'], {}), '(batch_size, 1, 1, 1)\n', (248, 269), False, 'import torch\n'), ((150, 175), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (173, 175), False, 'import torch\n'), ((409, 466), 'torch.autograd.Variable', 'torch.... |
import os
import sys
import unittest
import torch
import torch._C
from pathlib import Path
from test_nnapi import TestNNAPI
from torch.testing._internal.common_utils import TEST_WITH_ASAN
# Make the helper files in test/ importable
pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.pa... | [
"torch.jit.trace",
"os.path.exists",
"torch._C._jit_to_backend",
"pathlib.Path",
"unittest.skipIf",
"torch.set_default_dtype",
"os.path.realpath",
"torch.nn.PReLU",
"torch.tensor",
"sys.path.append"
] | [((314, 347), 'sys.path.append', 'sys.path.append', (['pytorch_test_dir'], {}), '(pytorch_test_dir)\n', (329, 347), False, 'import sys\n'), ((1117, 1176), 'unittest.skipIf', 'unittest.skipIf', (['TEST_WITH_ASAN', '"""Unresolved bug with ASAN"""'], {}), "(TEST_WITH_ASAN, 'Unresolved bug with ASAN')\n", (1132, 1176), Fal... |
from PyQt5.QtWidgets import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox
from InftyDoubleSpinBox import InftyDoubleSpinBox
from PyQt5.QtCore import pyqtSignal, Qt
import helplib as hl
import numpy as np
class dataControlWidget(QGroupBox):
showErrorBars_changed = pyqtSignal(bool)
ignoreFirstPoint_changed ... | [
"PyQt5.QtCore.pyqtSignal",
"InftyDoubleSpinBox.InftyDoubleSpinBox",
"helplib.saveFilewithMetaData",
"numpy.float64",
"PyQt5.QtWidgets.QWidget.__init__",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QLabel",
"helplib.readFileForFitsDataAndStdErrorAndMetaData",
"PyQt5.QtWidgets.QCheckBox"
] | [((274, 290), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['bool'], {}), '(bool)\n', (284, 290), False, 'from PyQt5.QtCore import pyqtSignal, Qt\n'), ((322, 338), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['bool'], {}), '(bool)\n', (332, 338), False, 'from PyQt5.QtCore import pyqtSignal, Qt\n'), ((358, 380), 'PyQt5.QtCor... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-06 04:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trr', '0001_initial'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.PositiveIntegerField"
] | [((387, 425), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'null': '(True)'}), '(null=True)\n', (414, 425), False, 'from django.db import migrations, models\n')] |
#
# Copyright(c) 2020 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
from core.test_run_utils import TestRun
from utils.installer import install_iotrace, check_if_installed
from utils.iotrace import IotracePlugin
from utils.misc import kill_all_io
from test_tools.fio.fio import Fio
def dut_prepare... | [
"core.test_run_utils.TestRun.LOGGER.info",
"utils.misc.kill_all_io",
"test_tools.fio.fio.Fio",
"core.test_run_utils.TestRun.executor.run",
"utils.installer.check_if_installed",
"core.test_run_utils.TestRun.executor.run_expect_success",
"utils.installer.install_iotrace"
] | [((667, 672), 'test_tools.fio.fio.Fio', 'Fio', ([], {}), '()\n', (670, 672), False, 'from test_tools.fio.fio import Fio\n'), ((777, 814), 'core.test_run_utils.TestRun.LOGGER.info', 'TestRun.LOGGER.info', (['"""Killing all IO"""'], {}), "('Killing all IO')\n", (796, 814), False, 'from core.test_run_utils import TestRun\... |
from models import Song
from random import choice
def random_song(genre):
results = Song.query().filter(Song.genre==genre).fetch()
print(results)
songs = choice(results)
random_song = {
"title": songs.song,
"album": songs.album,
"artist": songs.artist.lower(),
"genre": g... | [
"models.Song.query",
"random.choice"
] | [((167, 182), 'random.choice', 'choice', (['results'], {}), '(results)\n', (173, 182), False, 'from random import choice\n'), ((89, 101), 'models.Song.query', 'Song.query', ([], {}), '()\n', (99, 101), False, 'from models import Song\n')] |
#!/usr/bin/python
# custom_dialect.py
import csv
csv.register_dialect("hashes", delimiter="#")
f = open('items3.csv', 'w')
with f:
writer = csv.writer(f, dialect="hashes")
writer.writerow(("pencils", 2))
writer.writerow(("plates", 1))
writer.writerow(("books", 4))
| [
"csv.register_dialect",
"csv.writer"
] | [((52, 97), 'csv.register_dialect', 'csv.register_dialect', (['"""hashes"""'], {'delimiter': '"""#"""'}), "('hashes', delimiter='#')\n", (72, 97), False, 'import csv\n'), ((150, 181), 'csv.writer', 'csv.writer', (['f'], {'dialect': '"""hashes"""'}), "(f, dialect='hashes')\n", (160, 181), False, 'import csv\n')] |
from typing import Optional
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, Email
from servicex.models import UserModel
class ProfileForm(FlaskForm):
name = StringField('Full Name', validators=[DataRequired(), Length(... | [
"wtforms.validators.Length",
"wtforms.validators.Email",
"wtforms.validators.DataRequired",
"wtforms.SubmitField"
] | [((681, 708), 'wtforms.SubmitField', 'SubmitField', (['"""Save Profile"""'], {}), "('Save Profile')\n", (692, 708), False, 'from wtforms import StringField, SelectField, SubmitField\n'), ((297, 311), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (309, 311), False, 'from wtforms.validators import ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import os, sys
import tensorflow as tf
import tf_slim as slim
from tensorflow.python.tools import freeze_graph
sys.path.append('../../')
from data.io.image_preprocess import short_side_resize_for_inference_data
from libs.configs... | [
"data.io.image_preprocess.short_side_resize_for_inference_data",
"tensorflow.shape",
"tensorflow.reset_default_graph",
"tensorflow.reshape",
"tensorflow.to_float",
"tensorflow.placeholder",
"tensorflow.train.Saver",
"tensorflow.Session",
"os.path.join",
"tensorflow.constant",
"libs.networks.buil... | [((203, 228), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (218, 228), False, 'import os, sys\n'), ((646, 717), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.uint8', 'shape': '[None, None, 3]', 'name': '"""input_img"""'}), "(dtype=tf.uint8, shape=[None, None, 3], name='... |
#
# 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, software
# ... | [
"heat.engine.resources.openstack.neutron.port.Port.properties_schema.items",
"heat.engine.resources.openstack.neutron.net.Net.properties_schema.items",
"heat.engine.resources.openstack.neutron.subnet.Subnet.properties_schema.items",
"copy.deepcopy"
] | [((816, 837), 'copy.deepcopy', 'copy.deepcopy', (['schema'], {}), '(schema)\n', (829, 837), False, 'import copy\n'), ((1094, 1127), 'heat.engine.resources.openstack.neutron.net.Net.properties_schema.items', 'net.Net.properties_schema.items', ([], {}), '()\n', (1125, 1127), False, 'from heat.engine.resources.openstack.n... |
import os
import pytest
from modelkit.assets import errors
from tests.conftest import skip_unless
def _perform_driver_error_object_not_found(driver):
with pytest.raises(errors.ObjectDoesNotExistError):
driver.download_object("someasset", "somedestination")
assert not os.path.isfile("somedestination"... | [
"os.path.isfile",
"tests.conftest.skip_unless",
"pytest.raises"
] | [((494, 532), 'tests.conftest.skip_unless', 'skip_unless', (['"""ENABLE_GCS_TEST"""', '"""True"""'], {}), "('ENABLE_GCS_TEST', 'True')\n", (505, 532), False, 'from tests.conftest import skip_unless\n'), ((693, 730), 'tests.conftest.skip_unless', 'skip_unless', (['"""ENABLE_S3_TEST"""', '"""True"""'], {}), "('ENABLE_S3_... |
from django.test import TestCase
from django.contrib.auth.models import User
from wiki.models import Page
# Create your tests here.
def test_detail_page(self):
""" Test to see if slug generated when saving a Page."""
# Create a user and save to the database
user = User.objects.create()
user.save()
... | [
"wiki.models.Page.objects.get",
"django.contrib.auth.models.User.objects.create",
"wiki.models.Page.objects.create",
"wiki.models.Page"
] | [((280, 301), 'django.contrib.auth.models.User.objects.create', 'User.objects.create', ([], {}), '()\n', (299, 301), False, 'from django.contrib.auth.models import User\n'), ((379, 449), 'wiki.models.Page', 'Page', ([], {'title': '"""My Detail Test Page"""', 'content': '"""details_test"""', 'author': 'user'}), "(title=... |
from datetime import datetime
from django.core.exceptions import FieldError
from django.db.models import CharField, F, Q
from django.db.models.expressions import SimpleCol
from django.db.models.fields.related_lookups import RelatedIsNull
from django.db.models.functions import Lower
from django.db.models.lookups import... | [
"datetime.datetime",
"django.db.models.sql.query.Query",
"django.db.models.F",
"django.test.utils.register_lookup",
"django.db.models.Q"
] | [((654, 667), 'django.db.models.sql.query.Query', 'Query', (['Author'], {}), '(Author)\n', (659, 667), False, 'from django.db.models.sql.query import Query\n'), ((968, 981), 'django.db.models.sql.query.Query', 'Query', (['Author'], {}), '(Author)\n', (973, 981), False, 'from django.db.models.sql.query import Query\n'),... |
# This notebook implements a proof-of-principle for
# Multi-Agent Common Knowledge Reinforcement Learning (MACKRL)
# The entire notebook can be executed online, no need to download anything
# http://pytorch.org/
from itertools import chain
import torch
import torch.nn.functional as F
from torch.multiprocessing import... | [
"torch.ger",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"torch.min",
"torch.multiprocessing.freeze_support",
"torch.sum",
"torch.nn.functional.softmax",
"numpy.repeat",
"matplotlib.pyplot.xlabel",
"torch.multiprocessing.Pool",
"numpy.stack",
"matplotlib.pyplot.yticks",
"ma... | [((370, 395), 'torch.multiprocessing.set_start_method', 'set_start_method', (['"""spawn"""'], {}), "('spawn')\n", (386, 395), False, 'from torch.multiprocessing import Pool, set_start_method, freeze_support\n'), ((2125, 2156), 'torch.ger', 'torch.ger', (['pi_dec[0]', 'pi_dec[1]'], {}), '(pi_dec[0], pi_dec[1])\n', (2134... |
import inspect
def get_default_args(func):
"""Get default arguments of a function.
"""
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
| [
"inspect.signature"
] | [((113, 136), 'inspect.signature', 'inspect.signature', (['func'], {}), '(func)\n', (130, 136), False, 'import inspect\n')] |
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule, Scale, bias_init_with_prob
from IPython import embed
INF = 1e8
... | [
"torch.nn.MSELoss",
"mmdet.core.bbox_overlaps",
"torch.arange",
"torch.nn.ModuleList",
"IPython.embed",
"mmdet.core.multiclass_nms",
"torch.meshgrid",
"torch.zeros_like",
"torch.abs",
"mmdet.core.multi_apply",
"torch.equal",
"mmdet.core.distance2bbox",
"torch.cat",
"mmdet.core.force_fp32",... | [((5325, 5374), 'mmdet.core.force_fp32', 'force_fp32', ([], {'apply_to': "('cls_scores', 'bbox_preds')"}), "(apply_to=('cls_scores', 'bbox_preds'))\n", (5335, 5374), False, 'from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps\n'), ((11008, 11057), 'mmdet.core.force_fp32', 'force... |
from itertools import (
chain,
)
import logging
from azul import (
config,
require,
)
from azul.logging import (
configure_script_logging,
)
from azul.terra import (
TDRClient,
TDRSourceName,
)
log = logging.getLogger(__name__)
def main():
configure_script_logging(log)
tdr = TDRClien... | [
"logging.getLogger",
"azul.logging.configure_script_logging",
"azul.require",
"azul.terra.TDRClient",
"azul.terra.TDRSourceName.parse",
"azul.config.catalogs.values"
] | [((226, 253), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (243, 253), False, 'import logging\n'), ((272, 301), 'azul.logging.configure_script_logging', 'configure_script_logging', (['log'], {}), '(log)\n', (296, 301), False, 'from azul.logging import configure_script_logging\n'), ((312... |
"""Base for all Classes.
Base mainly includes the description fields
"""
import logging
from typing import Optional
from .log import Log # type: ignore
class BaseLog:
"""
Set a base logging.
Use this as the base class for all your work. This adds a logging root.
"""
def __init__(self, log_roo... | [
"logging.getLogger"
] | [((563, 590), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (580, 590), False, 'import logging\n')] |
import subprocess
import re
programs = input('Separe the programs with a space: ').split()
secure_pattern = '[\w\d]'
for program in programs:
if not re.match(secure_pattern, program):
print("Sorry we can't check that program")
continue
process = subprocess. run(
['which', program],... | [
"subprocess.run",
"re.match"
] | [((276, 342), 'subprocess.run', 'subprocess.run', (["['which', program]"], {'capture_output': '(True)', 'text': '(True)'}), "(['which', program], capture_output=True, text=True)\n", (290, 342), False, 'import subprocess\n'), ((157, 190), 're.match', 're.match', (['secure_pattern', 'program'], {}), '(secure_pattern, pro... |
#!/usr/bin/env python
""" Provides the primary interface into the library """
from __future__ import annotations
import asyncio
import logging
from typing import Callable, Optional, Union
from . import utils
from . import controllers
from .networking.connection import Connection
from .networking.types import SSDPRes... | [
"logging.getLogger",
"asyncio.Queue",
"asyncio.get_running_loop",
"asyncio.sleep"
] | [((467, 495), 'logging.getLogger', 'logging.getLogger', (['"""pytheos"""'], {}), "('pytheos')\n", (484, 495), False, 'import logging\n'), ((1828, 1843), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (1841, 1843), False, 'import asyncio\n'), ((8845, 8871), 'asyncio.get_running_loop', 'asyncio.get_running_loop', ([... |
import time
import torch
import warnings
import numpy as np
from tianshou.env import BaseVectorEnv
from tianshou.data import Batch, ReplayBuffer,\
ListReplayBuffer
from tianshou.utils import MovAvg
class Collector(object):
"""docstring for Collector"""
def __init__(self, policy, env, buffer=None, stat_si... | [
"tianshou.utils.MovAvg",
"numpy.isscalar",
"numpy.where",
"tianshou.data.ReplayBuffer",
"time.sleep",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"tianshou.data.Batch",
"tianshou.data.ListReplayBuffer",
"warnings.warn",
"time.time"
] | [((1660, 1677), 'tianshou.utils.MovAvg', 'MovAvg', (['stat_size'], {}), '(stat_size)\n', (1666, 1677), False, 'from tianshou.utils import MovAvg\n'), ((1707, 1724), 'tianshou.utils.MovAvg', 'MovAvg', (['stat_size'], {}), '(stat_size)\n', (1713, 1724), False, 'from tianshou.utils import MovAvg\n'), ((2961, 2972), 'time.... |
from drink_partners.contrib.samples import partner_bar_legal
class TestSearchPartner:
async def test_should_return_bad_request_for_str_coordinates(
self,
client,
partner_search_with_str_coordinates_url
):
async with client.get(partner_search_with_str_coordinates_url) as respon... | [
"drink_partners.contrib.samples.partner_bar_legal"
] | [((995, 1014), 'drink_partners.contrib.samples.partner_bar_legal', 'partner_bar_legal', ([], {}), '()\n', (1012, 1014), False, 'from drink_partners.contrib.samples import partner_bar_legal\n')] |
import multiprocessing
from typing import List, Optional
import numpy as np
from ..util import dill_for_apply
class ImageSequenceWriter:
def __init__(self, pattern, writer, *, max_index=None):
if type(pattern) is not str:
raise ValueError("Pattern must be string")
if pattern.format(1... | [
"multiprocessing.get_context",
"multiprocessing.cpu_count"
] | [((1543, 1579), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""spawn"""'], {}), "('spawn')\n", (1570, 1579), False, 'import multiprocessing\n'), ((1497, 1524), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (1522, 1524), False, 'import multiprocessing\n')] |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# <NAME>
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | [
"Drawable.Drawable.__init__"
] | [((618, 641), 'Drawable.Drawable.__init__', 'Drawable.__init__', (['self'], {}), '(self)\n', (635, 641), False, 'from Drawable import Drawable\n')] |
# 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... | [
"matplotlib.backends.backend_wxagg.FigureCanvasWxAgg",
"matplotlib.use",
"cairis.core.Borg.Borg",
"matplotlib.figure.Figure",
"wx.ComboBox",
"wx.BoxSizer",
"os.getcwd",
"matplotlib.backends.backend_wxagg.NavigationToolbar2WxAgg",
"wx.Panel.__init__"
] | [((932, 955), 'matplotlib.use', 'matplotlib.use', (['"""WXAgg"""'], {}), "('WXAgg')\n", (946, 955), False, 'import matplotlib\n'), ((1619, 1666), 'wx.Panel.__init__', 'wx.Panel.__init__', (['self', 'parent', 'RISKSCATTER_ID'], {}), '(self, parent, RISKSCATTER_ID)\n', (1636, 1666), False, 'import wx\n'), ((1673, 1679), ... |
# Xlib.ext.xinput -- XInput extension module
#
# Copyright (C) 2012 Outpost Embedded, LLC
# <NAME> <<EMAIL>>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either versio... | [
"Xlib.protocol.rq.String8",
"Xlib.protocol.rq.Bool",
"Xlib.protocol.rq.List.__init__",
"Xlib.protocol.rq.ReplyLength",
"Xlib.protocol.rq.Card8",
"Xlib.protocol.rq.Card32",
"Xlib.protocol.rq.Card16",
"Xlib.protocol.rq.RequestLength",
"Xlib.protocol.rq.ValueField.__init__",
"array.array",
"Xlib.pr... | [((5938, 5960), 'Xlib.protocol.rq.LengthOf', 'rq.LengthOf', (['"""mask"""', '(2)'], {}), "('mask', 2)\n", (5949, 5960), False, 'from Xlib.protocol import rq\n'), ((6787, 6804), 'Xlib.protocol.rq.Card16', 'rq.Card16', (['"""type"""'], {}), "('type')\n", (6796, 6804), False, 'from Xlib.protocol import rq\n'), ((6811, 683... |
from typing import Union
from unittest import mock
import graphene
import pytest
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.template.defaultfilters import slugify
from graphene.utils.str_converters import to_camel_case
from saleor.core.taxes import zero_money
from sa... | [
"saleor.product.models.AttributeProduct.objects.create",
"saleor.core.taxes.zero_money",
"saleor.product.models.Attribute.objects.get_visible_to_user",
"saleor.product.models.Attribute.objects.create",
"saleor.product.models.Attribute.objects.all",
"saleor.product.models.Collection.objects.create",
"sal... | [((5264, 5314), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""is_staff"""', '(False, True)'], {}), "('is_staff', (False, True))\n", (5287, 5314), False, 'import pytest\n'), ((11645, 11709), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_deprecated_filter"""', '[True, False]'], {}), "('te... |
from pyinstrument import Profiler
p = Profiler(use_signal=False)
p.start()
def func(num):
if num == 0:
return
b = 0
for x in range(1,100000):
b += x
return func(num - 1)
func(900)
p.stop()
print(p.output_text())
with open('overflow_out.html', 'w') as f:
f.write(p.output_html(... | [
"pyinstrument.Profiler"
] | [((39, 65), 'pyinstrument.Profiler', 'Profiler', ([], {'use_signal': '(False)'}), '(use_signal=False)\n', (47, 65), False, 'from pyinstrument import Profiler\n')] |
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2019, Linaro Limited
#
from __future__ import print_function
from __future__ import division
import argparse
import sys
import struct
import re
import hashlib
try:
from elftools.elf.elffile import ELFFile
from elftools.elf.consta... | [
"argparse.FileType",
"hashlib.sha256",
"argparse.ArgumentParser",
"re.compile",
"elftools.elf.elffile.ELFFile",
"struct.pack",
"sys.exit"
] | [((1428, 1439), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1436, 1439), False, 'import sys\n'), ((11109, 11134), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (11132, 11134), False, 'import argparse\n'), ((12419, 12438), 'elftools.elf.elffile.ELFFile', 'ELFFile', (['args.input'], {}), '(... |
from django.contrib import admin
#from .models import *
from . import models
# Register your models here.
admin.site.register(models.ClimbModel)
| [
"django.contrib.admin.site.register"
] | [((108, 146), 'django.contrib.admin.site.register', 'admin.site.register', (['models.ClimbModel'], {}), '(models.ClimbModel)\n', (127, 146), False, 'from django.contrib import admin\n')] |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-4.0
import os
import cv2
from collections import namedtuple
import imageio
from PIL import Image
from random import randrange
import numpy as np
from sklearn.decomposition import PCA
from scipy.spatial.distance import... | [
"numpy.array",
"matplotlib.pyplot.imshow",
"os.path.exists",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.close",
"cv2.addWeighted",
"numpy.take",
"matplotlib.pyplot.scatter",
"collections.namedtuple",
"scipy.spatial.distance.squareform",
"matplotlib.use",
"scipy.spatial.distance.pdist",
... | [((370, 391), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (384, 391), False, 'import matplotlib\n'), ((939, 966), 'matplotlib.pyplot.imread', 'plt.imread', (['self.image_path'], {}), '(self.image_path)\n', (949, 966), True, 'import matplotlib.pyplot as plt\n'), ((993, 1020), 'cv2.imread', 'cv2... |
import re
import lxml.html
from openstates.utils import LXMLMixin
from billy.scrape.legislators import LegislatorScraper, Legislator
class DELegislatorScraper(LegislatorScraper,LXMLMixin):
jurisdiction = 'de'
def scrape(self, chamber, term):
url = {
'upper': 'http://legis.delaware.gov/l... | [
"re.search",
"billy.scrape.legislators.Legislator",
"re.compile"
] | [((2963, 3017), 'billy.scrape.legislators.Legislator', 'Legislator', (['term', 'chamber', 'district', 'name'], {'party': 'party'}), '(term, chamber, district, name, party=party)\n', (2973, 3017), False, 'from billy.scrape.legislators import LegislatorScraper, Legislator\n'), ((1858, 1880), 're.compile', 're.compile', (... |
import os
import numpy as np
save_stem='extra_vis_friday_harbor'
data_dir='../../data/sdk_new_100'
resolution=100
cre=False
source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm',
'VISli','VISpor','VISrl','VISa']
lambda_list = np.logspace(3,12,10)
scale_lambda=True
min_vox=0
# save_file_name='... | [
"os.path.abspath",
"numpy.logspace",
"os.path.join"
] | [((253, 275), 'numpy.logspace', 'np.logspace', (['(3)', '(12)', '(10)'], {}), '(3, 12, 10)\n', (264, 275), True, 'import numpy as np\n'), ((428, 480), 'os.path.join', 'os.path.join', (['"""../../data/connectivities"""', 'save_stem'], {}), "('../../data/connectivities', save_stem)\n", (440, 480), False, 'import os\n'), ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 09:42:39 2020
@author: niklas
"""
from mossepy.mosse_tracker import MOSSE
# choose position of object in first frame
# that should be done by mouse click
objPos = [256, 256]
# choose tracker type
tracker = MOSSE()
# initialize object position ... | [
"mossepy.mosse_tracker.MOSSE"
] | [((283, 290), 'mossepy.mosse_tracker.MOSSE', 'MOSSE', ([], {}), '()\n', (288, 290), False, 'from mossepy.mosse_tracker import MOSSE\n')] |
#!/usr/bin/env python
#coding:utf-8
import os
import RPi.GPIO as GPIO #
import json
from time import sleep #
from twython import Twython
f=open("tw_config.json",'r')
config=json.load(f)
f.close()
CONSUMER_KEY =config['consumer_key']
CONSUMER_SECRET =config['consumer_secret']
ACCESS_TOKEN =config['access_token']
ACCE... | [
"RPi.GPIO.cleanup",
"RPi.GPIO.add_event_detect",
"twython.Twython",
"RPi.GPIO.setup",
"RPi.GPIO.output",
"time.sleep",
"os.popen",
"json.load",
"RPi.GPIO.setmode"
] | [((175, 187), 'json.load', 'json.load', (['f'], {}), '(f)\n', (184, 187), False, 'import json\n'), ((954, 1021), 'twython.Twython', 'Twython', (['CONSUMER_KEY', 'CONSUMER_SECRET', 'ACCESS_TOKEN', 'ACCESS_SECRET'], {}), '(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET)\n', (961, 1021), False, 'from twython i... |
""" Unit tests for ``wheezy.templates.utils``.
"""
import unittest
class FindAllBalancedTestCase(unittest.TestCase):
""" Test the ``find_all_balanced``.
"""
def test_start_out(self):
""" The start index is out of range.
"""
from wheezy.template.utils import find_all_balanced
... | [
"wheezy.template.utils.find_all_balanced",
"wheezy.template.utils.find_balanced"
] | [((338, 367), 'wheezy.template.utils.find_all_balanced', 'find_all_balanced', (['"""test"""', '(10)'], {}), "('test', 10)\n", (355, 367), False, 'from wheezy.template.utils import find_all_balanced\n'), ((551, 581), 'wheezy.template.utils.find_all_balanced', 'find_all_balanced', (['"""test(["""', '(0)'], {}), "('test([... |
import json
from os import path
from tweepy import OAuthHandler, Stream
from tweepy.streaming import StreamListener
from sqlalchemy.orm.exc import NoResultFound
from database import session, Tweet, Hashtag, User
consumer_key = "0qFf4T2xPWVIycLmAwk3rDQ55"
consumer_secret = "<KEY>"
access_token = "<KEY>"
acces_token_... | [
"json.loads",
"database.Hashtag",
"tweepy.Stream",
"json.dumps",
"os.path.join",
"database.session.add",
"database.session.query",
"database.session.commit",
"json.dump",
"tweepy.OAuthHandler"
] | [((345, 388), 'tweepy.OAuthHandler', 'OAuthHandler', (['consumer_key', 'consumer_secret'], {}), '(consumer_key, consumer_secret)\n', (357, 388), False, 'from tweepy import OAuthHandler, Stream\n'), ((521, 556), 'os.path.join', 'path.join', (['directory', '"""tweets.json"""'], {}), "(directory, 'tweets.json')\n", (530, ... |
from flask import render_template, jsonify
from app import app
import random
@app.route('/')
@app.route('/index')
def index():
# Feature flags init goes here!
#
# noinspection PyDictCreation
flags = {
"welcome_text": "welcome to my python FF tutorial!"
}
# Flag goes here!
#... | [
"flask.render_template",
"random.uniform",
"app.app.route",
"random.randint",
"flask.jsonify"
] | [((81, 95), 'app.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (90, 95), False, 'from app import app\n'), ((97, 116), 'app.app.route', 'app.route', (['"""/index"""'], {}), "('/index')\n", (106, 116), False, 'from app import app\n'), ((461, 478), 'app.app.route', 'app.route', (['"""/map"""'], {}), "('/map')\n",... |
# encoding: utf-8
'''
@author: yangsen
@license:
@contact:
@software:
@file: numpy_mat.py
@time: 18-8-25 下午9:56
@desc:
'''
import numpy as np
a = np.arange(9).reshape(3,3)
# 行
a[1]
a[[1,2]]
a[np.array([1,2])]
# 列
a[:,1]
a[:,[1,2]]
a[:,np.array([1,2])] | [
"numpy.array",
"numpy.arange"
] | [((194, 210), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (202, 210), True, 'import numpy as np\n'), ((146, 158), 'numpy.arange', 'np.arange', (['(9)'], {}), '(9)\n', (155, 158), True, 'import numpy as np\n'), ((238, 254), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (246, 254), True, 'impo... |
import copy
from typing import Callable, Dict, List, Optional
import torch
import torch.nn as nn
import torch.optim as optim
from ai_traineree import DEVICE
from ai_traineree.agents import AgentBase
from ai_traineree.agents.agent_utils import soft_update
from ai_traineree.buffers import NStepBuffer, PERBuffer
from ai... | [
"ai_traineree.networks.heads.RainbowNet",
"ai_traineree.utils.to_tensor",
"torch.load",
"json.dump",
"ai_traineree.agents.agent_utils.soft_update",
"json.load",
"torch.sum",
"ai_traineree.buffers.PERBuffer",
"torch.linspace",
"torch.save",
"torch.no_grad",
"copy.copy",
"ai_traineree.buffers.... | [((5392, 5456), 'torch.linspace', 'torch.linspace', (['v_min', 'v_max', 'self.num_atoms'], {'device': 'self.device'}), '(v_min, v_max, self.num_atoms, device=self.device)\n', (5406, 5456), False, 'import torch\n'), ((5537, 5556), 'ai_traineree.buffers.PERBuffer', 'PERBuffer', ([], {}), '(**kwargs)\n', (5546, 5556), Fal... |
import pytest
from pathlib import Path
from blendtorch import btt
BLENDDIR = Path(__file__).parent/'blender'
class MyEnv(btt.env.OpenAIRemoteEnv):
def __init__(self, background=True, **kwargs):
super().__init__(version='1.0.0')
self.launch(scene=BLENDDIR/'env.blend', script=BLENDDIR /
... | [
"pytest.approx",
"pathlib.Path"
] | [((78, 92), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (82, 92), False, 'from pathlib import Path\n'), ((714, 732), 'pytest.approx', 'pytest.approx', (['(0.1)'], {}), '(0.1)\n', (727, 732), False, 'import pytest\n'), ((900, 918), 'pytest.approx', 'pytest.approx', (['(0.6)'], {}), '(0.6)\n', (913, 918),... |
from typing import Union, Iterable, List
import numpy as np
import pandas as pd
from ..models._transformer import _ArrayTransformer, _MultiArrayTransformer
class _DataFrameTransformer(_ArrayTransformer):
'''`_ArrayTransformer` wrapper for `pandas.DataFrame`.
'''
def __init__(self):
super().__in... | [
"pandas.DataFrame",
"numpy.cumsum"
] | [((1911, 1982), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {'index': 'self.index_samples', 'columns': 'self.index_features'}), '(df, index=self.index_samples, columns=self.index_features)\n', (1923, 1982), True, 'import pandas as pd\n'), ((3153, 3204), 'numpy.cumsum', 'np.cumsum', (['[tf.n_valid_features for tf in se... |
from PIL import Image
from PIL import ImageTk
import tkinter as tki
from tkinter import Toplevel, Scale
import threading
import datetime
import cv2
import os
import time
import platform
class TelloUI:
"""Wrapper class to enable the GUI."""
def __init__(self,tello,outputpath):
"""
Initial all t... | [
"PIL.Image.fromarray",
"tkinter.Toplevel",
"tkinter.Button",
"time.sleep",
"threading.Event",
"tkinter.Scale",
"datetime.datetime.now",
"tkinter.Tk",
"os.path.sep.join",
"platform.system",
"tkinter.Label",
"cv2.cvtColor",
"threading.Thread",
"tkinter.Frame",
"PIL.ImageTk.PhotoImage"
] | [((1269, 1277), 'tkinter.Tk', 'tki.Tk', ([], {}), '()\n', (1275, 1277), True, 'import tkinter as tki\n'), ((1358, 1424), 'tkinter.Button', 'tki.Button', (['self.root'], {'text': '"""Snapshot!"""', 'command': 'self.takeSnapshot'}), "(self.root, text='Snapshot!', command=self.takeSnapshot)\n", (1368, 1424), True, 'import... |
# Neural Networks Demystified
# Part 1: Data + Architecture
#
# Supporting code for short YouTube series on artificial neural networks.
#
# <NAME>
# @stephencwelch
import numpy as np
# X = (hours sleeping, hours studying), y = Score on test
X = np.array(([3,5], [5,1], [10,2]), dtype=float)
y = np.array(([75], [82], [... | [
"numpy.array",
"numpy.amax"
] | [((247, 295), 'numpy.array', 'np.array', (['([3, 5], [5, 1], [10, 2])'], {'dtype': 'float'}), '(([3, 5], [5, 1], [10, 2]), dtype=float)\n', (255, 295), True, 'import numpy as np\n'), ((297, 338), 'numpy.array', 'np.array', (['([75], [82], [93])'], {'dtype': 'float'}), '(([75], [82], [93]), dtype=float)\n', (305, 338), ... |
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def menubuttonclass(context, appname):
if appname == context['request'].resolver_match.func.view_class.__module__.split(".")[0]:
return "btn-primary"
else:
return "btn-default"
| [
"django.template.Library"
] | [((40, 58), 'django.template.Library', 'template.Library', ([], {}), '()\n', (56, 58), False, 'from django import template\n')] |