code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if os.getenv("STAGE", "") == "dev":
logger.setLevel(logging.DEBUG)
| [
"os.getenv",
"logging.getLogger"
] | [((35, 54), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (52, 54), False, 'import logging\n'), ((88, 110), 'os.getenv', 'os.getenv', (['"""STAGE"""', '""""""'], {}), "('STAGE', '')\n", (97, 110), False, 'import os\n')] |
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'web.pages.index', name='home'),
#url(r... | [
"django.contrib.admin.autodiscover",
"django.conf.urls.include",
"django.conf.urls.url"
] | [((197, 217), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (215, 217), False, 'from django.contrib import admin\n'), ((266, 307), 'django.conf.urls.url', 'url', (['"""^$"""', '"""web.pages.index"""'], {'name': '"""home"""'}), "('^$', 'web.pages.index', name='home')\n", (269, 307), False,... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def add_data_transformer(self):
self.transform = lambda x: torch.sigmoid(x).view(-1, 1, 28, 28)
def add_mask_transformer(self, temperature=.66, hard_sigmoid=(-.1, 1.1)):
"""
hard_sigmoid:
False: use sigmoid only
True: ... | [
"torch.nn.ReLU",
"torch.nn.ConvTranspose2d",
"torch.sigmoid",
"torch.nn.Linear",
"torch.nn.functional.hardtanh"
] | [((1543, 1587), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['self.DIM', '(1)', '(8)'], {'stride': '(2)'}), '(self.DIM, 1, 8, stride=2)\n', (1561, 1587), True, 'import torch.nn as nn\n'), ((1164, 1208), 'torch.nn.Linear', 'nn.Linear', (['latent_size', '(4 * 4 * 4 * self.DIM)'], {}), '(latent_size, 4 * 4 * 4 * se... |
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from .serializers import AddressSerializer
from .utils import get_geocode_response
class AddressDetails(APIView):
def post(self, request, format=None):
... | [
"rest_framework.response.Response",
"django.http.JsonResponse"
] | [((1027, 1077), 'rest_framework.response.Response', 'Response', (['data'], {'status': 'status.HTTP_400_BAD_REQUEST'}), '(data, status=status.HTTP_400_BAD_REQUEST)\n', (1035, 1077), False, 'from rest_framework.response import Response\n'), ((625, 651), 'rest_framework.response.Response', 'Response', (['geocode_response'... |
from absl import logging
import os.path
import tornado.ioloop
import tornado.web
from icubam.db import store
class BaseServer:
"""Base class for ICUBAM servers."""
def __init__(self, config, port):
self.config = config
self.port = port
self.routes = []
self.db = store.create_store_for_sqlite_db(s... | [
"icubam.db.store.create_store_for_sqlite_db"
] | [((286, 331), 'icubam.db.store.create_store_for_sqlite_db', 'store.create_store_for_sqlite_db', (['self.config'], {}), '(self.config)\n', (318, 331), False, 'from icubam.db import store\n')] |
# Generated by Django 1.10.8 on 2017-10-12 10:35
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='StartEnterpriseDeliveryReceipt',
f... | [
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.models.AutoField"
] | [((351, 444), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (367, 444), False, 'from django.db import migrations, models\... |
from django.db import models
class AttributeName(models.Model):
id = models.PositiveIntegerField(unique=True, db_index=True, primary_key=True)
nazev = models.CharField(max_length=100)
kod = models.CharField(blank=True, max_length=100)
zobrazit = models.BooleanField(blank=True, null=True)
def __st... | [
"django.db.models.TextField",
"django.db.models.URLField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.PositiveIntegerField",
"django.db.models.BooleanField",
"django.db.models.DateTimeField"
] | [((75, 148), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'unique': '(True)', 'db_index': '(True)', 'primary_key': '(True)'}), '(unique=True, db_index=True, primary_key=True)\n', (102, 148), False, 'from django.db import models\n'), ((161, 193), 'django.db.models.CharField', 'models.Cha... |
# encoding=utf-8
import base64
from datetime import datetime
from flask import json
from MentalUs import db, logger
class MTScale(db.Model):
__tablename__ = 'mtscales'
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String())
scale_introductions = db.Column(db.Text())
scale_con... | [
"MentalUs.db.Boolean",
"MentalUs.db.session.commit",
"MentalUs.logger.error",
"MentalUs.db.DateTime",
"MentalUs.db.Column",
"MentalUs.db.Integer",
"MentalUs.db.Text",
"MentalUs.db.PickleType",
"flask.json.dumps",
"flask.json.loads",
"MentalUs.db.session.add",
"MentalUs.db.String"
] | [((2125, 2164), 'MentalUs.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (2134, 2164), False, 'from MentalUs import db, logger\n'), ((193, 205), 'MentalUs.db.Integer', 'db.Integer', ([], {}), '()\n', (203, 205), False, 'from MentalUs import db, logger\n'), ((24... |
# -*- coding: utf-8 -*-
from load_model_from_file import load_model_from_json
import os, sys
from PIL import Image
import numpy as np
def load_img(path):
"""
"""
img = np.array(Image.open(path))[:, :, 0:3]
img = np.expand_dims(img, axis=0)
return img
def main():
"""
"""
hom... | [
"os.path.abspath",
"load_model_from_file.load_model_from_json",
"numpy.expand_dims",
"PIL.Image.open",
"os.path.join"
] | [((235, 262), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (249, 262), True, 'import numpy as np\n'), ((391, 448), 'os.path.join', 'os.path.join', (['home', 'sys.argv[1]', 'sys.argv[2]', 'sys.argv[3]'], {}), '(home, sys.argv[1], sys.argv[2], sys.argv[3])\n', (403, 448), False, '... |
# First, and before importing any Enthought packages, set the ETS_TOOLKIT
# environment variable to qt4, to tell Traits that we will use Qt.
from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor
from traits.api import HasTraits, Instance, on_trait_change
from traitsui.api import View, Item
from mayav... | [
"traits.api.Instance",
"PyQt4.QtGui.QAction.__init__",
"mayavi.mlab.triangular_mesh",
"traits.api.on_trait_change",
"utils.save_obj",
"mayavi.mlab.clf",
"PyQt4.QtGui.QVBoxLayout",
"numpy.zeros",
"time.time",
"PyQt4.QtGui.QSlider.__init__",
"reshaper.Reshaper",
"mayavi.core.ui.api.SceneEditor",... | [((732, 769), 'PyQt4.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['int', 'int', 'int', 'int'], {}), '(int, int, int, int)\n', (749, 769), False, 'from PyQt4 import QtGui, QtCore\n'), ((1226, 1248), 'PyQt4.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['int'], {}), '(int)\n', (1243, 1248), False, 'from PyQt4 import QtGui, QtC... |
import numpy as np
import os
import glob
import uproot as ur
import matplotlib.pyplot as plt
import time
import seaborn as sns
# import tensorflow as tf
from modules.graph_data import GraphDataGenerator
sns.set_context('poster')
data_dir = '/usr/workspace/hip/ML4Jets/regression_images/'
pion_files = np.sort(glob.glob(... | [
"uproot.open",
"modules.graph_data.GraphDataGenerator",
"seaborn.set_context",
"glob.glob"
] | [((203, 228), 'seaborn.set_context', 'sns.set_context', (['"""poster"""'], {}), "('poster')\n", (218, 228), True, 'import seaborn as sns\n'), ((372, 394), 'uproot.open', 'ur.open', (['pion_files[0]'], {}), '(pion_files[0])\n', (379, 394), True, 'import uproot as ur\n'), ((518, 652), 'modules.graph_data.GraphDataGenerat... |
import numpy as np
import pandas as pd
from ..median_word_length import MedianWordLength
from .test_utils import PrimitiveT, find_applicable_primitives, valid_dfs
class TestMedianWordLength(PrimitiveT):
primitive = MedianWordLength
def test_delimiter_override(self):
x = pd.Series(['This is a test fi... | [
"pandas.testing.assert_series_equal",
"pandas.Series"
] | [((291, 381), 'pandas.Series', 'pd.Series', (["['This is a test file.', 'This,is,second,line?', 'and;subsequent;lines...']"], {}), "(['This is a test file.', 'This,is,second,line?',\n 'and;subsequent;lines...'])\n", (300, 381), True, 'import pandas as pd\n'), ((444, 470), 'pandas.Series', 'pd.Series', (['[4.0, 4.5, ... |
# coding: utf-8
"""
TensorFlow tests.
"""
import os
import cmsml
from cmsml.util import tmp_file, tmp_dir
from . import CMSMLTestCase
class TensorFlowTestCase(CMSMLTestCase):
def __init__(self, *args, **kwargs):
super(TensorFlowTestCase, self).__init__(*args, **kwargs)
os.environ["CUDA_VISIB... | [
"cmsml.tensorflow.load_graph",
"os.path.exists",
"cmsml.tensorflow.save_graph",
"numpy.ones",
"cmsml.tensorflow.import_tf",
"cmsml.tensorflow.write_graph_summary",
"cmsml.util.tmp_file",
"cmsml.util.tmp_dir",
"os.listdir"
] | [((4007, 4035), 'cmsml.tensorflow.import_tf', 'cmsml.tensorflow.import_tf', ([], {}), '()\n', (4033, 4035), False, 'import cmsml\n'), ((582, 610), 'cmsml.tensorflow.import_tf', 'cmsml.tensorflow.import_tf', ([], {}), '()\n', (608, 610), False, 'import cmsml\n'), ((751, 779), 'cmsml.tensorflow.import_tf', 'cmsml.tensorf... |
"""
Required for reading from sensor board
"""
from pycoproc import Pycoproc
__version__ = '1.4.0'
class Pysense(Pycoproc):
def __init__(self, i2c=None, sda='P22', scl='P21'):
Pycoproc.__init__(self, i2c, sda, scl)
| [
"pycoproc.Pycoproc.__init__"
] | [((192, 230), 'pycoproc.Pycoproc.__init__', 'Pycoproc.__init__', (['self', 'i2c', 'sda', 'scl'], {}), '(self, i2c, sda, scl)\n', (209, 230), False, 'from pycoproc import Pycoproc\n')] |
import sys
# See also: https://github.com/saltstack/salt-pylint/blob/master/saltpylint/minpyver.py
class MinPy:
def __init__(self, major_version=3, minor_version=5, dot3_version=0):
self.MIN_PYTHON_MAJOR_VERSION=major_version
self.MIN_PYTHON_MINOR_VERSION=minor_version
self.MIN_PYTHON_DOT... | [
"sys.exit"
] | [((1051, 1091), 'sys.exit', 'sys.exit', (['self.FAILED_MIN_PYTHON_VERSION'], {}), '(self.FAILED_MIN_PYTHON_VERSION)\n', (1059, 1091), False, 'import sys\n'), ((1327, 1367), 'sys.exit', 'sys.exit', (['self.FAILED_MIN_PYTHON_VERSION'], {}), '(self.FAILED_MIN_PYTHON_VERSION)\n', (1335, 1367), False, 'import sys\n')] |
#/usr/bin/python3
from __future__ import absolute_import, division, print_function, unicode_literals
from keras import backend as K
import tensorflow as tf
from keras.layers import Layer, multiply, Embedding
from tensorflow.random import categorical
from tensorflow.contrib.distributions import Categorical
from cost ... | [
"keras.backend.dot",
"keras.backend.squeeze",
"tensorflow.random.categorical",
"keras.backend.expand_dims",
"keras.backend.sum",
"keras.backend.gather",
"cost.cost",
"tensorflow.contrib.distributions.Categorical",
"tensorflow.fill",
"keras.layers.multiply",
"keras.backend.stop_gradient",
"kera... | [((608, 624), 'keras.backend.sum', 'K.sum', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (613, 624), True, 'from keras import backend as K\n'), ((540, 564), 'keras.backend.gather', 'K.gather', (['inp'], {'indices': 'x'}), '(inp, indices=x)\n', (548, 564), True, 'from keras import backend as K\n'), ((671, 687), 'keras.lay... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-10 06:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... | [
"django.db.models.TextField",
"django.db.models.BinaryField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.EmailField",
"django.db.models.DateTimeField"
] | [((4084, 4171), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""mcfeely.Queue"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'mcfeely.Queue')\n", (4101, 4171), False, 'from django.db import migrations, models\n'), ((4289, 4404), 'djan... |
# This script is part of pyroglancer (https://github.com/SridharJagannathan/pyroglancer).
# Copyright (C) 2020 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either vers... | [
"pandas.DataFrame",
"json.dump",
"os.remove",
"os.makedirs",
"cloudvolume.Skeleton",
"os.path.basename",
"navis.core.NeuronList",
"os.path.exists",
"cloudvolume.datasource.precomputed.sharding.ShardingSpecification",
"pymaid.core.CatmaidNeuronList",
"cloudvolume.CloudVolume",
"numpy.array",
... | [((1968, 2040), 'numpy.array', 'np.array', (["(this_tn[['index', 'parent_ix']].values[1:] - 1)"], {'dtype': '"""uint32"""'}), "(this_tn[['index', 'parent_ix']].values[1:] - 1, dtype='uint32')\n", (1976, 2040), True, 'import numpy as np\n'), ((2057, 2109), 'cloudvolume.Skeleton', 'Skeleton', ([], {'segid': 'x.id', 'vert... |
from abc import ABC
from torch_geometric.datasets import CitationFull as pyg_CitationFull, \
WikiCS as pyg_WikiCS, Coauthor as pyg_Coauthor, Amazon as pyg_Amazon
from .base_graph import Adapter
import numpy as np
import networkx as nx
import torch
from tqdm import tqdm
class PyG(Adapter, ABC):
def __init__(s... | [
"networkx.DiGraph"
] | [((812, 824), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (822, 824), True, 'import networkx as nx\n')] |
import argparse
from .platform.aliyun import Aliyun
from prettytable import PrettyTable
def print_table(r, allow_keys=None):
x = PrettyTable()
# collect all possible keys
keys = []
for row in r:
keys += row.keys()
keys = sorted(list(set(keys)))
if allow_keys is not None:
... | [
"prettytable.PrettyTable",
"argparse.ArgumentParser"
] | [((139, 152), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (150, 152), False, 'from prettytable import PrettyTable\n'), ((559, 584), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (582, 584), False, 'import argparse\n')] |
# -*- coding: utf-8 -*-
from functools import reduce
from operator import mul
import numpy as np
from africanus.util.docs import DocstringTemplate
from africanus.util.numba import jit
@jit(nopython=True, nogil=True, cache=True)
def _nb_feed_rotation(parallactic_angles, feed_type, feed_rotation):
shape = paral... | [
"africanus.util.docs.DocstringTemplate",
"numpy.empty",
"numpy.sin",
"numpy.cos",
"functools.reduce",
"africanus.util.numba.jit"
] | [((191, 233), 'africanus.util.numba.jit', 'jit', ([], {'nopython': '(True)', 'nogil': '(True)', 'cache': '(True)'}), '(nopython=True, nogil=True, cache=True)\n', (194, 233), False, 'from africanus.util.numba import jit\n'), ((2279, 2934), 'africanus.util.docs.DocstringTemplate', 'DocstringTemplate', (['"""\nComputes th... |
''' 017 Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento
da hipotenusa'''
import math
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi = (co ** 2 + ca ** 2) ** (1/2)
prin... | [
"math.hypot"
] | [((357, 375), 'math.hypot', 'math.hypot', (['co', 'ca'], {}), '(co, ca)\n', (367, 375), False, 'import math\n')] |
# -*- coding: utf-8 -*-
import datetime
import uuid
from collections import abc
from typing import MutableSequence, Any, Optional, Sequence
import typing
import numpy as np
from .array import StateVector, CovarianceMatrix, PrecisionMatrix
from .base import Type
from .numeric import Probability
from .particle import P... | [
"uuid.uuid4",
"numpy.average",
"numpy.sum",
"numpy.argmax",
"numpy.array"
] | [((18291, 18369), 'numpy.average', 'np.average', (['self.particles.state_vector'], {'axis': '(1)', 'weights': 'self.particles.weight'}), '(self.particles.state_vector, axis=1, weights=self.particles.weight)\n', (18301, 18369), True, 'import numpy as np\n'), ((20756, 20784), 'numpy.argmax', 'np.argmax', (['self.state_ve... |
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URI") or "sqlite:///" + os.path.join(
basedir, "users.db"
)
app.config["SQLALCHEMY_DATABASE_URI... | [
"os.path.dirname",
"flask.Flask",
"os.environ.get",
"flask_sqlalchemy.SQLAlchemy",
"flask.render_template",
"os.path.join"
] | [((99, 114), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (104, 114), False, 'from flask import Flask, render_template\n'), ((382, 397), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (392, 397), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((141, 166), 'os.path.dirname', ... |
# coding=utf-8
import unittest
import sys
import logging
from mocking.IndigoDevice import IndigoDevice
from mocking.IndigoServer import Indigo
indigo = Indigo()
sys.modules['indigo'] = indigo
from Devices.Sensors.Shelly_Flood import Shelly_Flood
class Test_Shelly_Flood(unittest.TestCase):
def setUp(self):
... | [
"mocking.IndigoServer.Indigo",
"logging.getLogger",
"logging.NullHandler",
"Devices.Sensors.Shelly_Flood.Shelly_Flood.validateConfigUI",
"Devices.Sensors.Shelly_Flood.Shelly_Flood",
"mocking.IndigoDevice.IndigoDevice"
] | [((154, 162), 'mocking.IndigoServer.Indigo', 'Indigo', ([], {}), '()\n', (160, 162), False, 'from mocking.IndigoServer import Indigo\n'), ((364, 406), 'mocking.IndigoDevice.IndigoDevice', 'IndigoDevice', ([], {'id': '(123456)', 'name': '"""New Device"""'}), "(id=123456, name='New Device')\n", (376, 406), False, 'from m... |
"""Support for Solcast PV forecast."""
import json
import logging
import traceback
from datetime import datetime, timedelta
from enum import Enum
from operator import itemgetter
import aiohttp
import homeassistant.util.dt as dt_util
from homeassistant.components.recorder.models import Events
from homeassistant.compone... | [
"homeassistant.helpers.sun.get_astral_location",
"json.loads",
"homeassistant.util.dt.utcnow",
"json.dumps",
"datetime.datetime",
"aiohttp.ClientSession",
"isodate.parse_datetime",
"homeassistant.components.recorder.models.Events.time_fired.asc",
"homeassistant.helpers.event.async_call_later",
"tr... | [((865, 892), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (882, 892), False, 'import logging\n'), ((12818, 12849), 'homeassistant.helpers.sun.get_astral_location', 'get_astral_location', (['self._hass'], {}), '(self._hass)\n', (12837, 12849), False, 'from homeassistant.helpers.sun impo... |
#from .unet_model import *
#from .pretrained import *
import segmentation_models_pytorch as smp
def get_model(model_name, encoder_name, num_classes):
if model_name == 'UNet':
return smp.UNet(encoder_name, encoder_weights='imagenet', classes=num_classes, activation=None)
elif model_name == 'FPN':
... | [
"segmentation_models_pytorch.FPN",
"segmentation_models_pytorch.UNet"
] | [((197, 289), 'segmentation_models_pytorch.UNet', 'smp.UNet', (['encoder_name'], {'encoder_weights': '"""imagenet"""', 'classes': 'num_classes', 'activation': 'None'}), "(encoder_name, encoder_weights='imagenet', classes=num_classes,\n activation=None)\n", (205, 289), True, 'import segmentation_models_pytorch as smp... |
import os
from dataclasses import dataclass
@dataclass
class DirManager:
def __init__(self, **kwargs):
for var, path in kwargs.items():
setattr(self, var, path)
self.build_dirs()
def build_dirs(self) -> None:
for process_dir in vars(self).values():
if ... | [
"os.path.exists",
"os.makedirs"
] | [((324, 351), 'os.path.exists', 'os.path.exists', (['process_dir'], {}), '(process_dir)\n', (338, 351), False, 'import os\n'), ((353, 377), 'os.makedirs', 'os.makedirs', (['process_dir'], {}), '(process_dir)\n', (364, 377), False, 'import os\n')] |
#! -*- coding: utf-8 -*-
# 基础测试:GAU_alpha的mlm预测,和bert4keras版本比对一致
# 测试中长文本效果明显高于短文本效果
# 博客:https://kexue.fm/archives/9052
# 权重转换脚本:./convert_script/convert_GAU_alpha.py
from bert4torch.models import build_transformer_model
from bert4torch.tokenizers import Tokenizer
import torch
# 加载模型,请更换成自己的路径
config_path = 'F:/Pro... | [
"torch.argmax",
"bert4torch.models.build_transformer_model",
"bert4torch.tokenizers.Tokenizer",
"torch.no_grad",
"torch.tensor"
] | [((656, 696), 'bert4torch.tokenizers.Tokenizer', 'Tokenizer', (['dict_path'], {'do_lower_case': '(True)'}), '(dict_path, do_lower_case=True)\n', (665, 696), False, 'from bert4torch.tokenizers import Tokenizer\n'), ((705, 800), 'bert4torch.models.build_transformer_model', 'build_transformer_model', (['config_path', 'che... |
import pytest
import uuid
import json
from src.sls_tools.param_store import ParamStore, ParamStoreResult
@pytest.fixture
def key():
return 'TEST-KEY'
@pytest.fixture
def value():
return str(uuid.uuid4())
@pytest.fixture
def param_store_result(key, value):
return ParamStoreResult(key, value, None)
de... | [
"pytest.raises",
"uuid.uuid4",
"src.sls_tools.param_store.ParamStoreResult"
] | [((281, 315), 'src.sls_tools.param_store.ParamStoreResult', 'ParamStoreResult', (['key', 'value', 'None'], {}), '(key, value, None)\n', (297, 315), False, 'from src.sls_tools.param_store import ParamStore, ParamStoreResult\n'), ((202, 214), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (212, 214), False, 'import uuid\n... |
from transformers import RobertaTokenizer, RobertaModel
import torch
if __name__ == '__main__':
tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
model = RobertaModel.from_pretrained('roberta-large')
relations = open("./data/relations.txt", "r").read().splitlines()
relations.append("no rela... | [
"torch.save",
"transformers.RobertaTokenizer.from_pretrained",
"transformers.RobertaModel.from_pretrained",
"torch.cat"
] | [((113, 162), 'transformers.RobertaTokenizer.from_pretrained', 'RobertaTokenizer.from_pretrained', (['"""roberta-large"""'], {}), "('roberta-large')\n", (145, 162), False, 'from transformers import RobertaTokenizer, RobertaModel\n'), ((175, 220), 'transformers.RobertaModel.from_pretrained', 'RobertaModel.from_pretraine... |
from selenium import webdriver
from time import sleep
import pytest
import os
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as Ec
from selenium.webdriver.chrome.service import Service as ChromeService
optio... | [
"selenium.webdriver.chrome.service.Service",
"os.path.abspath",
"pytest.main",
"selenium.webdriver.ChromeOptions",
"selenium.webdriver.Chrome",
"selenium.webdriver.support.ui.WebDriverWait"
] | [((325, 350), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (348, 350), False, 'from selenium import webdriver\n'), ((495, 568), 'selenium.webdriver.chrome.service.Service', 'ChromeService', ([], {'executable_path': '"""D:\\\\install\\\\webdriver\\\\chromedriver.exe"""'}), "(executabl... |
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
# Create your views here.
from profileservice.models import Profile
from profileservice.serializers import ProfileSerializer
class ProfileViewset(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializ... | [
"profileservice.models.Profile.objects.all"
] | [((286, 307), 'profileservice.models.Profile.objects.all', 'Profile.objects.all', ([], {}), '()\n', (305, 307), False, 'from profileservice.models import Profile\n')] |
from optparse import OptionParser
import json
import sys
import os
usage = """
<Script> [Options]
[Options]
-h, --help Show this help message and exit.
-a, --add Goes straight to the add script phase
"""
# Load args
parser = OptionParser()
parser.add_option("-a", "--add", action="store_true", d... | [
"json.dump",
"json.load",
"optparse.OptionParser",
"os.listdir",
"sys.exit"
] | [((250, 264), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (262, 264), False, 'from optparse import OptionParser\n'), ((2776, 2793), 'os.listdir', 'os.listdir', (['"""../"""'], {}), "('../')\n", (2786, 2793), False, 'import os\n'), ((2263, 2290), 'json.dump', 'json.dump', (['data_store', 'file'], {}), '(d... |
import yaml
import pandas as pd
from tensorflow.keras import Input
from logging import Logger
import tensorflow as tf
import ml4ir.base.io.file_io as file_io
from ml4ir.base.data.tfrecord_helper import get_sequence_example_proto
from ml4ir.base.config.keys import FeatureTypeKey, TFRecordTypeKey, SequenceExampleTypeKey... | [
"pandas.DataFrame",
"ml4ir.base.io.file_io.read_yaml",
"yaml.safe_load",
"ml4ir.base.data.tfrecord_helper.get_sequence_example_proto"
] | [((17177, 17210), 'ml4ir.base.io.file_io.read_yaml', 'file_io.read_yaml', (['feature_config'], {}), '(feature_config)\n', (17194, 17210), True, 'import ml4ir.base.io.file_io as file_io\n'), ((17358, 17388), 'yaml.safe_load', 'yaml.safe_load', (['feature_config'], {}), '(feature_config)\n', (17372, 17388), False, 'impor... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 10 22:01:30 2017
@author: LZR
"""
import requests
import json
#获取通过Ajax加载的json数据
def get_json_data(offset):
headers = {
'Host': 'www.ele.me',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
'Acce... | [
"requests.get",
"json.dumps"
] | [((965, 1014), 'requests.get', 'requests.get', (['url'], {'headers': 'headers', 'params': 'params'}), '(url, headers=headers, params=params)\n', (977, 1014), False, 'import requests\n'), ((1777, 1826), 'json.dumps', 'json.dumps', (['results'], {'indent': '(2)', 'ensure_ascii': '(False)'}), '(results, indent=2, ensure_a... |
# Copyright Cartopy Contributors
#
# This file is part of Cartopy and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
from __future__ import (absolute_import, division, print_function)
import operator
import warnings
import matplotlib
i... | [
"numpy.arctan2",
"cartopy.mpl.ticker.LongitudeFormatter",
"numpy.isnan",
"numpy.clip",
"cartopy.mpl.ticker.LongitudeLocator",
"numpy.sin",
"numpy.arange",
"numpy.meshgrid",
"matplotlib.transforms.offset_copy",
"numpy.logical_or.reduce",
"shapely.geometry.Polygon",
"matplotlib.ticker.MaxNLocato... | [((732, 794), 'matplotlib.ticker.MaxNLocator', 'mticker.MaxNLocator', ([], {'nbins': '(9)', 'steps': '[1, 1.5, 1.8, 2, 3, 6, 10]'}), '(nbins=9, steps=[1, 1.5, 1.8, 2, 3, 6, 10])\n', (751, 794), True, 'import matplotlib.ticker as mticker\n'), ((813, 841), 'matplotlib.ticker.MaxNLocator', 'mticker.MaxNLocator', ([], {'nb... |
# -*- coding: utf-8 -*-
'''
Episode 4-1
'''
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
sys.path.append('storybuilder')
from storybuilder.builder.world import World
# DEFINE
TITLE = "凶器のない殺人"
# NOTE: outlines
ABSTRACT = """
何かの事件に関連していると$sherlockが警察に届ける。担当の$restradeがやってきて、... | [
"sys.path.append",
"os.path.dirname"
] | [((131, 162), 'sys.path.append', 'sys.path.append', (['"""storybuilder"""'], {}), "('storybuilder')\n", (146, 162), False, 'import sys\n'), ((94, 119), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (109, 119), False, 'import os\n')] |
import asyncio
import logging
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
class SchemaAccess:
def __init__(self, test_bed_options):
self.retries = test_bed_options.reconnection_retries
self.backoff = 0.3
self.staturs_forcelist = (500, 502,... | [
"logging.error",
"requests.adapters.HTTPAdapter",
"requests.Session",
"logging.info",
"urllib3.util.retry.Retry"
] | [((442, 460), 'requests.Session', 'requests.Session', ([], {}), '()\n', (458, 460), False, 'import requests\n'), ((477, 617), 'urllib3.util.retry.Retry', 'Retry', ([], {'total': 'self.retries', 'read': 'self.retries', 'connect': 'self.retries', 'backoff_factor': 'self.backoff', 'status_forcelist': 'self.staturs_forceli... |
import math
import subprocess
import einops as eo
from loguru import logger
import numpy as np
import pandas as pd
from PIL import Image
from scipy.signal import savgol_filter
import torch
from torch import optim, nn
from collections import Counter
from pytti import (
format_input,
set_t,
print_vram_usag... | [
"pandas.DataFrame",
"subprocess.run",
"scipy.signal.savgol_filter",
"loguru.logger.debug",
"IPython.display.display",
"pytti.rotoscoper.update_rotoscopers",
"pytti.vram_usage_mode",
"pytti.Transforms.animate_2d",
"pytti.Transforms.zoom_3d",
"pytti.format_input",
"numpy.array",
"pytti.freeze_vr... | [((1422, 1476), 'scipy.signal.savgol_filter', 'savgol_filter', (['df[key]', 'window_size', '(2)'], {'mode': '"""nearest"""'}), "(df[key], window_size, 2, mode='nearest')\n", (1435, 1476), False, 'from scipy.signal import savgol_filter\n'), ((17269, 17277), 'pytti.set_t', 'set_t', (['t'], {}), '(t)\n', (17274, 17277), F... |
# Copyright 2020, <NAME>, mailto:<EMAIL>
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... | [
"pprint.pformat",
"sys.exc_info"
] | [((1042, 1059), 'pprint.pformat', 'pprint.pformat', (['d'], {}), '(d)\n', (1056, 1059), False, 'import pprint\n'), ((1784, 1798), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1796, 1798), False, 'import sys\n'), ((1901, 1915), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1913, 1915), False, 'import sys\n'),... |
import argparse
import json
from tqdm import tqdm
from utils.annotation_processor import AnnotationProcessor, EvidenceType
import jsonlines
import os
def average(list):
return float(sum(list) / len(list))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--split', type=s... | [
"os.path.join",
"argparse.ArgumentParser",
"json.loads"
] | [((253, 278), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (276, 278), False, 'import argparse\n'), ((854, 870), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (864, 870), False, 'import json\n'), ((1239, 1255), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (1249, 1255), Fa... |
# encoding: utf-8
"""
@author: sherlock
@contact: <EMAIL>
"""
import logging
import torch
import torch.nn as nn
from ignite.engine import Engine
import pickle
from utils.reid_metric import R1_mAP, R1_mAP_reranking
from torch.autograd import Variable
from torch.nn import functional as F
import numpy as np
worddict_tmp... | [
"utils.reid_metric.R1_mAP_reranking",
"numpy.argmax",
"numpy.empty",
"numpy.zeros",
"torch.cuda.device_count",
"torch.nn.functional.softmax",
"ignite.engine.Engine",
"utils.reid_metric.R1_mAP",
"torch.nn.DataParallel",
"torch.no_grad",
"logging.getLogger",
"torch.from_numpy"
] | [((2872, 2890), 'ignite.engine.Engine', 'Engine', (['_inference'], {}), '(_inference)\n', (2878, 2890), False, 'from ignite.engine import Engine\n'), ((3118, 3162), 'logging.getLogger', 'logging.getLogger', (['"""reid_baseline.inference"""'], {}), "('reid_baseline.inference')\n", (3135, 3162), False, 'import logging\n'... |
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 ... | [
"unittest.main",
"server_plugin.volume.create_volume",
"server_plugin.volume.creation_validation",
"server_plugin.volume.delete_volume",
"mock.patch",
"server_plugin.volume.detach_volume",
"cloudify.mocks.MockCloudifyContext",
"server_plugin.volume._volume_operation",
"mock.Mock",
"mock.MagicMock"... | [((13577, 13592), 'unittest.main', 'unittest.main', ([], {}), '()\n', (13590, 13592), False, 'import unittest\n'), ((1114, 1264), 'cloudify.mocks.MockCloudifyContext', 'cfy_mocks.MockCloudifyContext', ([], {'node_id': '"""test"""', 'node_name': '"""test"""', 'properties': "{'use_external_resource': True, 'vcloud_config... |
import asyncio
import collections
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.base as s_base
class AQueue(s_base.Base):
'''
An async queue with chunk optimized sync compatible consumer.
'''
async def __anit__(self):
await s_base.Base.__anit__(self)
... | [
"synapse.lib.base.Base.__anit__",
"asyncio.Event",
"synapse.exc.BadArg",
"asyncio.Queue",
"collections.deque"
] | [((358, 373), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (371, 373), False, 'import asyncio\n'), ((1049, 1079), 'asyncio.Queue', 'asyncio.Queue', ([], {'maxsize': 'maxsize'}), '(maxsize=maxsize)\n', (1062, 1079), False, 'import asyncio\n'), ((2769, 2784), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (27... |
import os
import discord
from discord.ext import commands
COLOR = 0x9370DB
TOKEN = os.environ["BOT_TOKEN"]
INTENTS = discord.Intents.default()
INTENTS.members = True
INTENTS.presences = True
robot = commands.Bot(command_prefix="r! ", intents=INTENTS)
from .comms import *
from .events import * | [
"discord.Intents.default",
"discord.ext.commands.Bot"
] | [((119, 144), 'discord.Intents.default', 'discord.Intents.default', ([], {}), '()\n', (142, 144), False, 'import discord\n'), ((202, 253), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""r! """', 'intents': 'INTENTS'}), "(command_prefix='r! ', intents=INTENTS)\n", (214, 253), False, 'from discor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import types
import numpy
import scipy
import warnings
from scipy.signal import savgol_filter
import statsmodels.api as sm
lowess = sm.nonparametric.lowess
import logging
from scipy.signal import savgol_filter
import time
import sys
import copy
from datetime import datetim... | [
"numpy.isnan",
"numpy.argsort",
"numpy.mean",
"numpy.interp",
"multiprocessing.cpu_count",
"numpy.zeros_like",
"numpy.multiply",
"warnings.simplefilter",
"numpy.empty_like",
"warnings.catch_warnings",
"datetime.datetime.now",
"numpy.divide",
"copy.deepcopy",
"numpy.nan_like",
"numpy.medi... | [((2752, 2771), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (2765, 2771), False, 'import copy\n'), ((6424, 6446), 'numpy.empty_like', 'numpy.empty_like', (['data'], {}), '(data)\n', (6440, 6446), False, 'import numpy\n'), ((6455, 6477), 'numpy.empty_like', 'numpy.empty_like', (['data'], {}), '(data)\n... |
from __future__ import print_function
import time
import csv
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors
# If modifying these scopes, delete the file token... | [
"pickle.dump",
"google.auth.transport.requests.Request",
"csv.writer",
"time.strftime",
"pickle.load",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file",
"googleapiclient.discovery.build",
"time.localtime"
] | [((1334, 1373), 'googleapiclient.discovery.build', 'build', (['"""gmail"""', '"""v1"""'], {'credentials': 'creds'}), "('gmail', 'v1', credentials=creds)\n", (1339, 1373), False, 'from googleapiclient.discovery import build\n'), ((3136, 3152), 'time.localtime', 'time.localtime', ([], {}), '()\n', (3150, 3152), False, 'i... |
from tests.utils import assert_output
def test_lyx():
assert_output("lyxjinja",
"dexy:foo.py|idio:multiply",
"<< d['foo.py|idio']['multiply'] >>",
".tex")
| [
"tests.utils.assert_output"
] | [((59, 163), 'tests.utils.assert_output', 'assert_output', (['"""lyxjinja"""', '"""dexy:foo.py|idio:multiply"""', '"""<< d[\'foo.py|idio\'][\'multiply\'] >>"""', '""".tex"""'], {}), '(\'lyxjinja\', \'dexy:foo.py|idio:multiply\',\n "<< d[\'foo.py|idio\'][\'multiply\'] >>", \'.tex\')\n', (72, 163), False, 'from tests.... |
# Generated by Django 3.0.2 on 2020-04-18 00:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grades', '0019_merge_20200329_2049'),
]
operations = [
migrations.AddField(
model_name='course',
name='earned_points... | [
"django.db.models.IntegerField"
] | [((341, 371), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (360, 371), False, 'from django.db import migrations, models\n'), ((497, 527), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (516, 527), False, 'from djan... |
from strongr.schedulerdomain.model.scalingdrivers.abstract import AbstractScaleOut, AbstractScaleIn, \
AbstractVmTemplateRetriever
import uuid
import strongr.core
import strongr.core.gateways
import logging
import strongr.core.domain.schedulerdomain
from sqlalchemy import func, and_, or_
from strongr.schedulerd... | [
"sqlalchemy.func.sum",
"uuid.uuid4",
"strongr.schedulerdomain.model.Vm.state.in_",
"sqlalchemy.and_",
"strongr.schedulerdomain.model.Job.state.in_",
"sqlalchemy.func.max",
"datetime.datetime.utcnow",
"datetime.timedelta",
"sqlalchemy.func.count",
"strongr.schedulerdomain.model.Vm.vm_id.in_",
"lo... | [((1545, 1608), 'logging.getLogger', 'logging.getLogger', (["('schedulerdomain.' + self.__class__.__name__)"], {}), "('schedulerdomain.' + self.__class__.__name__)\n", (1562, 1608), False, 'import logging\n'), ((4346, 4409), 'logging.getLogger', 'logging.getLogger', (["('schedulerdomain.' + self.__class__.__name__)"], ... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from histocat.config import config
engine = create_engine(config.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
SessionLocal = sessionmak... | [
"sqlalchemy.create_engine",
"sqlalchemy.orm.sessionmaker"
] | [((139, 204), 'sqlalchemy.create_engine', 'create_engine', (['config.SQLALCHEMY_DATABASE_URI'], {'pool_pre_ping': '(True)'}), '(config.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)\n', (152, 204), False, 'from sqlalchemy import create_engine\n'), ((310, 370), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'autocom... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Resolver tests."""
from __future__ import absolute_import, print_function
import... | [
"uuid.uuid4",
"invenio_pidstore.models.PersistentIdentifier.create",
"invenio_pidstore.resolver.Resolver",
"pytest.raises",
"invenio_pidstore.models.PersistentIdentifier.get"
] | [((879, 891), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (889, 891), False, 'import uuid\n'), ((1290, 1411), 'invenio_pidstore.models.PersistentIdentifier.create', 'PersistentIdentifier.create', (['"""doi"""', '"""10.1234/foo"""'], {'status': 'PIDStatus.REGISTERED', 'object_type': '"""rec"""', 'object_uuid': 'rec_a'... |
from bs4 import BeautifulSoup
import requests
import csv
import sys
sys.path.append("..")
import mytemp
import util
url='https://www.ebay.com/b/Toys-Hobbies/220/bn_1865497?rt=nc&LH_BIN=1&LH_PrefLoc=6&rt=nc&_pgn='
def getlink():
f=open('ebay_toys.csv','w+',newline='',encoding='gb18030')
csv_write=c... | [
"sys.path.append",
"csv.reader",
"csv.writer",
"util.build_proxy_request",
"bs4.BeautifulSoup"
] | [((72, 93), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (87, 93), False, 'import sys\n'), ((2688, 2702), 'csv.writer', 'csv.writer', (['f2'], {}), '(f2)\n', (2698, 2702), False, 'import csv\n'), ((2723, 2741), 'csv.reader', 'csv.reader', (['f_read'], {}), '(f_read)\n', (2733, 2741), False, 'im... |
"""Parse data in the format:
Age Uncertainty
Sample data assumning a normal distrubtion with mean defined by Age and sigma
defined by Uncertainty
"""
import numpy as np
from scipy.stats import norm
from QuakeRates.dataman.event_dates import EventDate, EventSet
def parse_age_sigma(filename, sigma_level, event_order, ... | [
"QuakeRates.dataman.event_dates.EventDate",
"numpy.flip",
"numpy.genfromtxt",
"scipy.stats.norm.pdf",
"numpy.mean",
"numpy.array",
"numpy.arange",
"QuakeRates.dataman.event_dates.EventSet"
] | [((1036, 1092), 'numpy.genfromtxt', 'np.genfromtxt', (['filename'], {'delimiter': 'delimiter', 'names': '(True)'}), '(filename, delimiter=delimiter, names=True)\n', (1049, 1092), True, 'import numpy as np\n'), ((3467, 3487), 'QuakeRates.dataman.event_dates.EventSet', 'EventSet', (['event_list'], {}), '(event_list)\n', ... |
# Generated by Django 3.0.3 on 2020-07-10 21:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instrument', '0017_auto_20200710_1011'),
]
operations = [
migrations.AddField(
model_name='instrument',
name='extern... | [
"django.db.models.IntegerField"
] | [((346, 416), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""external id"""'}), "(blank=True, null=True, verbose_name='external id')\n", (365, 416), False, 'from django.db import migrations, models\n')] |
"""
author: thomaszdxsn
"""
import pytest
from scrapy.loader import ItemLoader
from SpiderNest.items.ip import IPItem
from SpiderNest.models.ip import IP
@pytest.mark.parametrize(
'params',
[
('0.1.125.221', '80', 'https', 'source', ['remark1', 'remark2'])
]
)
def test_ly_community_post_comment_i... | [
"pytest.mark.parametrize",
"SpiderNest.models.ip.IP",
"SpiderNest.items.ip.IPItem"
] | [((158, 263), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', "[('0.1.125.221', '80', 'https', 'source', ['remark1', 'remark2'])]"], {}), "('params', [('0.1.125.221', '80', 'https', 'source',\n ['remark1', 'remark2'])])\n", (181, 263), False, 'import pytest\n'), ((609, 619), 'SpiderNest.model... |
import json
import logging
import time
from typing import NamedTuple
from src.genome import GenomeMaker
from src.phylip.newick import NewickParser
from src.phylip.phylip import PhylipNeighborConstructor, PhylipTreeDistCalculator
from src.phylip.synteny_index import calculate_synteny_distance
from src.time_func import ... | [
"src.tree.fill_genome",
"logging.debug",
"src.tree.YuleTreeGenerator",
"src.phylip.phylip.PhylipTreeDistCalculator",
"src.phylip.newick.NewickParser",
"json.dumps",
"src.time_func.time_func",
"logging.info",
"time.monotonic",
"src.tree.TreeDesc",
"src.phylip.phylip.PhylipNeighborConstructor",
... | [((1592, 1730), 'logging.info', 'logging.info', (['"""Branch count: %s avg: %s median: %s expected: %s"""', 'branch_stats.count', 'branch_stats.average', 'branch_stats.median', 'scale'], {}), "('Branch count: %s avg: %s median: %s expected: %s',\n branch_stats.count, branch_stats.average, branch_stats.median, scale)... |
from pathlib import Path
import pkg_resources as pkg
__all__ = ["PATH_PYVOTCA", "PATH_TEST"]
# Environment data
PATH_PYVOTCA = Path(pkg.resource_filename('pyvotca', ''))
ROOT = PATH_PYVOTCA.parent
PATH_TEST = ROOT / "tests" / "files"
| [
"pkg_resources.resource_filename"
] | [((135, 171), 'pkg_resources.resource_filename', 'pkg.resource_filename', (['"""pyvotca"""', '""""""'], {}), "('pyvotca', '')\n", (156, 171), True, 'import pkg_resources as pkg\n')] |
#
# Copyright (c) 2013,2014, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the... | [
"os.path.isabs",
"os.path.dirname",
"os.path.join",
"ConfigParser.SafeConfigParser.__init__",
"re.compile"
] | [((1412, 1486), 're.compile', 're.compile', (['"""(?P<section>\\\\w+(?:\\\\.\\\\w+)*)\\\\.(?P<name>\\\\w+)=(?P<value>.*)"""'], {}), "('(?P<section>\\\\w+(?:\\\\.\\\\w+)*)\\\\.(?P<name>\\\\w+)=(?P<value>.*)')\n", (1422, 1486), False, 'import re\n'), ((2794, 2827), 'os.path.dirname', 'os.path.dirname', (['self.config_fil... |
import asyncio
from pathlib import Path
import aiohttp
from aiohttp import web
from .funnel import Funnel
from .utils import (
HttpRange,
RangeNotSupportedError,
convert_unit,
load_browser_cookies,
retry,
)
async def make_response(request, url, block_size, piece_size, cookies_from,
... | [
"aiohttp.web.Response",
"aiohttp.web.StreamResponse",
"aiohttp.ClientSession",
"pathlib.Path",
"aiohttp.web.FileResponse",
"aiohttp.web.Application"
] | [((2651, 2665), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (2655, 2665), False, 'from pathlib import Path\n'), ((2712, 2749), 'aiohttp.web.FileResponse', 'web.FileResponse', (["(ROOT / 'index.html')"], {}), "(ROOT / 'index.html')\n", (2728, 2749), False, 'from aiohttp import web\n'), ((3566, 3583), 'ai... |
from typing import TYPE_CHECKING, List, Optional
if TYPE_CHECKING:
from Platforms.Twitch.main_twitch import PhaazebotTwitch
import twitch_irc
from Utils.Classes.twitchchannelsettings import TwitchChannelSettings
from Utils.Classes.twitchuserstats import TwitchUserStats
from Platforms.Twitch.db import getTwitchChannel... | [
"Platforms.Twitch.commands.checkCommands",
"Platforms.Twitch.ownchannel.clientNameChannel",
"Platforms.Twitch.db.getTwitchChannelSettings",
"Platforms.Twitch.db.getTwitchChannelUsers",
"Platforms.Twitch.punish.checkPunish",
"Platforms.Twitch.levels.checkLevel"
] | [((873, 911), 'Platforms.Twitch.db.getTwitchChannelSettings', 'getTwitchChannelSettings', (['cls', 'Message'], {}), '(cls, Message)\n', (897, 911), False, 'from Platforms.Twitch.db import getTwitchChannelSettings, getTwitchChannelUsers\n'), ((1022, 1101), 'Platforms.Twitch.db.getTwitchChannelUsers', 'getTwitchChannelUs... |
#!/usr/bin/env python3
"""Examples:
setup.py sdist
setup.py bdist_wininst
"""
from setuptools import setup
if __name__ == "__main__":
setup()
| [
"setuptools.setup"
] | [((159, 166), 'setuptools.setup', 'setup', ([], {}), '()\n', (164, 166), False, 'from setuptools import setup\n')] |
# @brief: provides a method to solve the modified Ricatti Equation
import numpy as np
from scipy.linalg import solve_continuous_are
def createLowLevelParams(A, B, Q, R, g, w):
# A, B are control matrices
# Q, R are cost weights
# g = \gamma controls the sensitivity
# w is the magnitude of the noise
# deter... | [
"numpy.linalg.eigvals",
"numpy.linalg.inv",
"numpy.array",
"numpy.eye",
"numpy.linalg.cholesky"
] | [((445, 454), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (451, 454), True, 'import numpy as np\n'), ((941, 950), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (947, 950), True, 'import numpy as np\n'), ((956, 965), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (962, 965), True, 'import numpy as np\n'), ((974, 1040)... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import os
print('Welcome to the game!')
input('Press enter to continue: ')
print('')
print('- This is a population simulator for a fictional town.')
print('- The town starts with 20 people. With each year that passes, babies will be ... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"pandas.read_csv",
"os.getcwd",
"random.choice",
"random.random",
"numpy.where",
"pandas.concat"
] | [((1151, 1284), 'pandas.read_csv', 'pd.read_csv', (['"""https://raw.githubusercontent.com/MatthiasWinkelmann/firstname-database/master/firstnames.csv"""'], {'delimiter': '""";"""'}), "(\n 'https://raw.githubusercontent.com/MatthiasWinkelmann/firstname-database/master/firstnames.csv'\n , delimiter=';')\n", (1162, ... |
# -*- coding:utf-8 -*-
"""
"""
import datetime
import json
import os
import time
import numpy as np
import pandas as pd
from IPython.display import display, update_display, display_markdown
from tqdm.auto import tqdm
from ..utils import logging, fs, to_repr
logger = logging.get_logger(__name__)
class Callback():
... | [
"pandas.DataFrame",
"os.makedirs",
"IPython.display.display",
"time.time",
"tqdm.auto.tqdm",
"json.dumps",
"datetime.datetime.now",
"IPython.display.display_markdown",
"IPython.display.update_display",
"os.path.expanduser"
] | [((4884, 4924), 'os.makedirs', 'os.makedirs', (['dir_path'], {'exist_ok': 'exist_ok'}), '(dir_path, exist_ok=exist_ok)\n', (4895, 4924), False, 'import os\n'), ((5236, 5282), 'os.path.expanduser', 'os.path.expanduser', (['f"""{log_dir}/{running_dir}"""'], {}), "(f'{log_dir}/{running_dir}')\n", (5254, 5282), False, 'imp... |
import time
import boto3
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from moto import mock_timestreamwrite, settings
from moto.core import ACCOUNT_ID
@mock_timestreamwrite
def test_create_table():
ts = boto3.client("timestream-write", region_name=... | [
"pytest.raises",
"boto3.client",
"time.time"
] | [((275, 332), 'boto3.client', 'boto3.client', (['"""timestream-write"""'], {'region_name': '"""us-east-1"""'}), "('timestream-write', region_name='us-east-1')\n", (287, 332), False, 'import boto3\n'), ((1254, 1311), 'boto3.client', 'boto3.client', (['"""timestream-write"""'], {'region_name': '"""us-east-1"""'}), "('tim... |
# Copyright 2021 D-Wave Systems 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... | [
"dwave_networkx.zephyr_coordinates",
"dwave_networkx.zephyr_graph",
"dwave_networkx.generators.zephyr.zephyr_coordinates",
"dwave_networkx.zephyr_sublattice_mappings",
"dwave_networkx.chimera_graph"
] | [((793, 815), 'dwave_networkx.zephyr_graph', 'dnx.zephyr_graph', (['(1)', '(4)'], {}), '(1, 4)\n', (809, 815), True, 'import dwave_networkx as dnx\n'), ((1116, 1155), 'dwave_networkx.zephyr_graph', 'dnx.zephyr_graph', (['(1)', '(4)'], {'edge_list': 'edges'}), '(1, 4, edge_list=edges)\n', (1132, 1155), True, 'import dwa... |
# Infinite multiplying loop
from datetime import datetime
import time
#i = 1
i=1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
n=0
starttime = datetime.now()
print("Start")
while i>1:
i=i/2
print(i)
n=n+1
print("End")
finishtime = datetime.now()
print('... | [
"datetime.datetime.now"
] | [((206, 220), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (218, 220), False, 'from datetime import datetime\n'), ((298, 312), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (310, 312), False, 'from datetime import datetime\n')] |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import multiprocessing as mp
import platform
import sys
import textwrap
from . import console
from... | [
"textwrap.dedent",
"os.path.join",
"os.walk",
"platform.uname",
"os.path.isfile",
"sys.stdout.isatty",
"platform.machine",
"os.path.expanduser",
"multiprocessing.cpu_count"
] | [((523, 543), 'os.walk', 'os.walk', (['results_dir'], {}), '(results_dir)\n', (530, 543), False, 'import os\n'), ((791, 807), 'platform.uname', 'platform.uname', ([], {}), '()\n', (805, 807), False, 'import platform\n'), ((1047, 1088), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.asv-machine.json"""'], {}), "('... |
""" Copyright (c) 2015, Swedish Institute of Computer Science
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list ... | [
"logging.error"
] | [((1877, 1895), 'logging.error', 'logging.error', (['msg'], {}), '(msg)\n', (1890, 1895), False, 'import logging\n'), ((1970, 2027), 'logging.error', 'logging.error', (['"""Method not implemented in this DAO class"""'], {}), "('Method not implemented in this DAO class')\n", (1983, 2027), False, 'import logging\n'), ((2... |
import random
import time
import zlib
from concurrent.futures.thread import ThreadPoolExecutor
from pyquery import PyQuery
from NovelSpider import SpiderTools
from NovelSpider.DBhelper import default_dbhelper, DBhelper
class NovelResource:
def __init__(self, host: str, home_page: str, select_category: str,
... | [
"NovelSpider.SpiderTools.get_html",
"pyquery.PyQuery",
"NovelSpider.DBhelper.default_dbhelper.query_one",
"NovelSpider.DBhelper.default_dbhelper.query",
"NovelSpider.DBhelper.DBhelper",
"random.uniform",
"NovelSpider.SpiderTools.getRes",
"NovelSpider.DBhelper.default_dbhelper.update",
"NovelSpider.S... | [((13017, 13103), 'NovelSpider.DBhelper.DBhelper', 'DBhelper', ([], {'host': '"""localhost"""', 'user': '"""root"""', 'password': '"""<PASSWORD>"""', 'database': '"""novels"""'}), "(host='localhost', user='root', password='<PASSWORD>', database=\n 'novels')\n", (13025, 13103), False, 'from NovelSpider.DBhelper impor... |
#!/usr/bin/env python3
import schoolopy
import json
from termcolor import colored as c
import os
from datetime import datetime
HOME = os.getenv('HOME')
TOKENS_PATH = HOME + '/.sc.tokens.json'
CONFIG_PATH = HOME + '/.sc.config.json'
CACHES_PATH = HOME + '/.sc.caches.json'
# Load or generate API tokens
if os.path.isfi... | [
"json.dump",
"os.chmod",
"json.load",
"os.stat",
"schoolopy.Auth",
"getpass.getpass",
"termcolor.colored",
"os.path.isfile",
"datetime.datetime.fromtimestamp",
"os.getenv"
] | [((136, 153), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (145, 153), False, 'import os\n'), ((308, 335), 'os.path.isfile', 'os.path.isfile', (['TOKENS_PATH'], {}), '(TOKENS_PATH)\n', (322, 335), False, 'import os\n'), ((1257, 1284), 'os.path.isfile', 'os.path.isfile', (['CONFIG_PATH'], {}), '(CONFIG_... |
import random
from enum import Enum
from io import BytesIO
from PIL import Image, ImageDraw
from PIL.Image import Image as IMG
from typing import Iterable, Tuple, List, Optional
from .utils import get_pinyin, load_font, save_jpg
class GuessResult(Enum):
WIN = 0 # 猜出正确成语
LOSS = 1 # 达到最大可猜次数,未猜出正确成语
DUPL... | [
"PIL.ImageDraw.Draw",
"PIL.Image.new"
] | [((2229, 2281), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'self.block_size', 'self.border_color'], {}), "('RGB', self.block_size, self.border_color)\n", (2238, 2281), False, 'from PIL import Image, ImageDraw\n'), ((2420, 2463), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(inner_w, inner_h)', 'color'], {}), "('RGB'... |
#Daily coding problem number 18
#Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.
#BruteForce way
def maxesFromArray_BF(array, view_len):
maxes = []
for view in range(len(array) - view_len + 1):
maxes.append(max(ar... | [
"collections.deque"
] | [((558, 565), 'collections.deque', 'deque', ([], {}), '()\n', (563, 565), False, 'from collections import deque\n')] |
import click
import os
import json
from kite_metrics.loader import load_json_schema
from jsonschema import validate
@click.command()
@click.argument('input', type=click.File('rb'))
def main(input):
schema = json.loads(load_json_schema('kite_status'))
for line in input:
validate(instance=json.loads(lin... | [
"kite_metrics.loader.load_json_schema",
"json.loads",
"click.File",
"click.command"
] | [((119, 134), 'click.command', 'click.command', ([], {}), '()\n', (132, 134), False, 'import click\n'), ((224, 255), 'kite_metrics.loader.load_json_schema', 'load_json_schema', (['"""kite_status"""'], {}), "('kite_status')\n", (240, 255), False, 'from kite_metrics.loader import load_json_schema\n'), ((165, 181), 'click... |
import numpy as np
import cv2
import grpc
from tritonclient.grpc import service_pb2, service_pb2_grpc
import tritonclient.grpc.model_config_pb2 as mc
np.random.seed(123)
palette = np.random.randint(0, 256, (100, 3))
# url = '10.128.61.7:8001'
url = '127.0.0.1:8001'
model_name = 'bisenetv2'
model_version = '1'
... | [
"tritonclient.grpc.service_pb2.ModelInferRequest",
"tritonclient.grpc.service_pb2_grpc.GRPCInferenceServiceStub",
"numpy.random.seed",
"cv2.imwrite",
"numpy.frombuffer",
"grpc.insecure_channel",
"cv2.imread",
"tritonclient.grpc.service_pb2.ModelConfigRequest",
"numpy.random.randint",
"numpy.array"... | [((155, 174), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (169, 174), True, 'import numpy as np\n'), ((185, 220), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)', '(100, 3)'], {}), '(0, 256, (100, 3))\n', (202, 220), True, 'import numpy as np\n'), ((707, 749), 'grpc.insecure_channel... |
# https://wiki.freecadweb.org/Scripting_examples
# https://wiki.freecadweb.org/FeaturePython_Objects
import FreeCAD as App
def create(obj_name):
"""
Object creation method
"""
obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)
box(obj)
App.ActiveDocument.recompute()
ret... | [
"FreeCAD.ActiveDocument.addObject",
"FreeCAD.ActiveDocument.recompute"
] | [((201, 261), 'FreeCAD.ActiveDocument.addObject', 'App.ActiveDocument.addObject', (['"""App::FeaturePython"""', 'obj_name'], {}), "('App::FeaturePython', obj_name)\n", (229, 261), True, 'import FreeCAD as App\n'), ((281, 311), 'FreeCAD.ActiveDocument.recompute', 'App.ActiveDocument.recompute', ([], {}), '()\n', (309, 3... |
# coding: utf-8
from AsyncIteratorWrapper import AsyncIteratorWrapper
import asyncio
import functools
import aiohttp
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
from threading import Thread
headers={
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/we... | [
"threading.Thread",
"functools.partial",
"asyncio.get_event_loop",
"asyncio.sleep",
"tornado.platform.asyncio.AsyncIOMainLoop",
"aiohttp.ClientSession"
] | [((633, 671), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {'headers': 'headers'}), '(headers=headers)\n', (654, 671), False, 'import aiohttp\n'), ((2138, 2162), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2160, 2162), False, 'import asyncio\n'), ((2182, 2230), 'threading.Thread', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : tql-Python.
# @File : timer
# @Time : 2019-06-20 11:26
# @Author : yuanjie
# @Email : <EMAIL>
# @Software : PyCharm
# @Description :
import time
from contextlib import contextmanager
from .. import cprint
@contextmanage... | [
"time.time"
] | [((501, 512), 'time.time', 'time.time', ([], {}), '()\n', (510, 512), False, 'import time\n'), ((584, 595), 'time.time', 'time.time', ([], {}), '()\n', (593, 595), False, 'import time\n')] |
"""这个蓝图对应的是新闻页面的相关的操作"""
from flask import Blueprint
news_blue = Blueprint('news', __name__)
import info.moduels.news.views
| [
"flask.Blueprint"
] | [((66, 93), 'flask.Blueprint', 'Blueprint', (['"""news"""', '__name__'], {}), "('news', __name__)\n", (75, 93), False, 'from flask import Blueprint\n')] |
from __future__ import division
import math
import matplotlib as mpl
import numpy as np
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FixedLocator
from matplotlib.ticker import LogLocator
from matplotlib.ticker import FormatStrFormatter
fr... | [
"matplotlib.pyplot.clf",
"numpy.mean",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.autoscale",
"matplotlib.pyplot.rc",
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"numpy.linalg.eigvalsh",
"matplotlib.pyplot.ylabel",
... | [((1575, 1614), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""', 'size': '(43)'}), "('font', family='serif', size=43)\n", (1581, 1614), True, 'import matplotlib.pyplot as plt\n'), ((1697, 1713), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (1705, 1713), True, 'import numpy as n... |
#!/usr/bin/env false
"""TODO: Write
"""
# Internal packages (absolute references, distributed with Python)
from pathlib import Path
# External packages (absolute references, NOT distributed with Python)
# Library modules (absolute references, NOT packaged, in project)
from utility import my_assert as is_
from src_ge... | [
"utility.my_assert.not_none",
"pathlib.Path",
"src_gen.source.my_visitor_map.register",
"utility.my_assert.instance"
] | [((665, 694), 'src_gen.source.my_visitor_map.register', 'my_visitor_map.register', (['Path'], {}), '(Path)\n', (688, 694), False, 'from src_gen.source import my_visitor_map\n'), ((1060, 1095), 'src_gen.source.my_visitor_map.register', 'my_visitor_map.register', (['_Arguments'], {}), '(_Arguments)\n', (1083, 1095), Fals... |
import sys
import gym
import tensorflow as tf
import numpy as np
import random
import datetime
import os
from collections import deque
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
"""
Hyper Parameters
"""
GAMMA = 0.99 # discount factor for target Q
INITIAL_EPSILON = 0.8 # starting value of epsilon
FINAL_E... | [
"numpy.argmax",
"tensorflow.get_collection",
"random.sample",
"tensorflow.multiply",
"numpy.mean",
"numpy.arange",
"tensorflow.InteractiveSession",
"collections.deque",
"random.randint",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"tensorflow.summary.FileWriter",
"datetime.datetim... | [((1033, 1059), 'collections.deque', 'deque', ([], {'maxlen': 'AVERAGE_OVER'}), '(maxlen=AVERAGE_OVER)\n', (1038, 1059), False, 'from collections import deque\n'), ((3314, 3356), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, state_dim]'], {}), "('float', [None, state_dim])\n", (3328, 3356), True,... |
import numpy as np
from PIL import Image
from deephar.utils.io import WARNING
from deephar.utils.io import FAIL
from deephar.utils.io import printcn
from deephar.utils.pose import pa16j2d
from deephar.utils.pose import pa17j3d
from deephar.utils.pose import pa20j3d
from deephar.utils.colors import hex_colors
try:
... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.close",
"deephar.utils.io.printcn",
"numpy.zeros",
"matplotlib.pyplot.axis",
"numpy.ones",
"numpy.apply_along_axis",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.imsave",
"matplotlib.pyplot.gca"
] | [((3314, 3328), 'matplotlib.pyplot.axis', 'plt.axis', (['axis'], {}), '(axis)\n', (3322, 3328), True, 'import matplotlib.pyplot as plt\n'), ((5713, 5738), 'numpy.zeros', 'np.zeros', (['(num_joints, 3)'], {}), '((num_joints, 3))\n', (5721, 5738), True, 'import numpy as np\n'), ((5885, 5956), 'numpy.apply_along_axis', 'n... |
import os
import pytest
from biome.data.sources import DataSource
from tests import DaskSupportTest, TESTS_BASEPATH
FILES_PATH = os.path.join(TESTS_BASEPATH, "resources")
class DataSourceTest(DaskSupportTest):
def test_wrong_format(self):
with pytest.raises(TypeError):
DataSource(format="no... | [
"biome.data.sources.DataSource",
"pytest.raises",
"biome.data.sources.DataSource.add_supported_format",
"os.path.join"
] | [((132, 173), 'os.path.join', 'os.path.join', (['TESTS_BASEPATH', '"""resources"""'], {}), "(TESTS_BASEPATH, 'resources')\n", (144, 173), False, 'import os\n'), ((720, 776), 'biome.data.sources.DataSource.add_supported_format', 'DataSource.add_supported_format', (['"""new-format"""', 'ds_parser'], {}), "('new-format', ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import cupy as cp
import scipy.signal
import pytest
import resamcupy
@pytest.mark.parametrize('axis', [0, 1, 2])
def test_shape(axis):
sr_orig = 80
sr_new = sr_orig // 2
X = cp.random.randn(sr_orig, sr_orig, sr_orig)
Y = resamcupy.resample(X, sr_orig, ... | [
"cupy.zeros",
"cupy.ones",
"cupy.random.randn",
"pytest.mark.parametrize",
"pytest.mark.xfail",
"resamcupy.resample"
] | [((122, 164), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1, 2]'], {}), "('axis', [0, 1, 2])\n", (145, 164), False, 'import pytest\n'), ((482, 531), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'raises': 'ValueError', 'strict': '(True)'}), '(raises=ValueError, strict=True)\n', (499, 53... |
#!/usr/bin/python3
from __future__ import print_function
import tensorflow as tf
import math
from utility.generate_sample import generate_sample
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import os
#LSTM runs faster on CPU
os.environ['C... | [
"argparse.ArgumentParser",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.matmul",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.tight_layout",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.name_scope",
"tensorflow.compat.v1.placeholder",
"m... | [((349, 387), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (385, 387), True, 'import tensorflow as tf\n'), ((388, 409), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (402, 409), False, 'import matplotlib\n'), ((688, 798), 'argparse.Arg... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
script.module.metadatautils
Metacritic.py
Get metadata from Metacritic
"""
import os, sys
from .utils import get_json, requests, try_parse_int, log_msg
import bs4 as BeautifulSoup
from simplecache import use_cache
import json
class Metacritic(object):
"""... | [
"json.loads",
"kodidb.KodiDb",
"simplecache.SimpleCache",
"simplecache.use_cache",
"bs4.BeautifulSoup"
] | [((912, 924), 'simplecache.use_cache', 'use_cache', (['(2)'], {}), '(2)\n', (921, 924), False, 'from simplecache import use_cache\n'), ((1722, 1779), 'bs4.BeautifulSoup', 'BeautifulSoup.BeautifulSoup', (['html'], {'features': '"""html.parser"""'}), "(html, features='html.parser')\n", (1749, 1779), True, 'import bs4 as ... |
from setuptools import setup
setup(
name="example-playtex-project",
version="0.1.0",
license="Public Domain",
url="https://github.com/benburrill/playtex",
py_modules=["mpl"],
install_requires=["playtex", "matplotlib"],
)
| [
"setuptools.setup"
] | [((30, 227), 'setuptools.setup', 'setup', ([], {'name': '"""example-playtex-project"""', 'version': '"""0.1.0"""', 'license': '"""Public Domain"""', 'url': '"""https://github.com/benburrill/playtex"""', 'py_modules': "['mpl']", 'install_requires': "['playtex', 'matplotlib']"}), "(name='example-playtex-project', version... |
"""The tests for the Modbus sensor component."""
import copy
from dataclasses import dataclass
from datetime import timedelta
import logging
from unittest import mock
from pymodbus.exceptions import ModbusException
import pytest
from homeassistant.components.modbus.const import MODBUS_DOMAIN as DOMAIN, TCP
from homea... | [
"copy.deepcopy",
"pymodbus.exceptions.ModbusException",
"unittest.mock.MagicMock",
"homeassistant.util.dt.utcnow",
"homeassistant.setup.async_setup_component",
"tests.common.async_fire_time_changed",
"unittest.mock.patch",
"tests.common.mock_restore_cache",
"datetime.timedelta",
"logging.getLogger... | [((706, 733), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (723, 733), False, 'import logging\n'), ((1030, 1046), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (1044, 1046), False, 'from unittest import mock\n'), ((1908, 1932), 'copy.deepcopy', 'copy.deepcopy', (['do_co... |
"""
Simulates sending kibana events to the queue
Run conditions:
python3 fakeEvents.py
python3 fakeEvents.py <path/to/fake_data.json>
if no path is specified, assumes it is in the cwd
"""
import pika
import os
import sys
import json
import time
class Fake_Event_Data_Gen:
def __init__(self, amqp_url, file... | [
"json.loads",
"json.dumps",
"time.sleep",
"time.time",
"pika.URLParameters",
"pika.BlockingConnection"
] | [((411, 439), 'pika.URLParameters', 'pika.URLParameters', (['amqp_url'], {}), '(amqp_url)\n', (429, 439), False, 'import pika\n'), ((466, 501), 'pika.BlockingConnection', 'pika.BlockingConnection', (['parameters'], {}), '(parameters)\n', (489, 501), False, 'import pika\n'), ((1228, 1244), 'json.loads', 'json.loads', ([... |
import turtle
import random
r = 250
t = turtle.Pen()
t.setposition(0, -260)
while r > 0:
t.fillcolor(random.random(), random.random(), random.random())
t.pencolor((random.random(), random.random(), random.random()))
t.begin_fill()
t.circle(r)
t.end_fill()
r -= 10
turtle.Screen().exitonclick()
| [
"random.random",
"turtle.Pen",
"turtle.Screen"
] | [((40, 52), 'turtle.Pen', 'turtle.Pen', ([], {}), '()\n', (50, 52), False, 'import turtle\n'), ((106, 121), 'random.random', 'random.random', ([], {}), '()\n', (119, 121), False, 'import random\n'), ((123, 138), 'random.random', 'random.random', ([], {}), '()\n', (136, 138), False, 'import random\n'), ((140, 155), 'ran... |
import fiftyone as fo
import fiftyone.zoo as foz
food_list = [
"Apple", "Orange", "Pizza", "Hamburger", "French fries",
"Sandwich", "Cheese", "Burrito", "Banana",
"Pancake", "Coffee", "Tea", "Milk", "Salab",
"Cucumber", "Tomato", "Egg"]
dataset = foz.load_zoo_dataset(
"open-images-v6",
split=... | [
"fiftyone.zoo.load_zoo_dataset"
] | [((266, 454), 'fiftyone.zoo.load_zoo_dataset', 'foz.load_zoo_dataset', (['"""open-images-v6"""'], {'split': '"""validation"""', 'label_types': "['detections']", 'classes': 'food_list', 'max_samples': '(100)', 'seed': '(51)', 'shuffle': '(True)', 'dataset_name': '"""open-images-food"""'}), "('open-images-v6', split='val... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from app.models.base import BaseModel
class DocumentState(BaseModel):
EXPIRED = 1
STR_EXPIRED = _("Expired")
STATES = {
EXPIRED: STR_EXPIRED,
}
state_previous = models.ForeignKey('self', default=None, bl... | [
"django.db.models.ForeignKey",
"django.utils.translation.ugettext_lazy"
] | [((192, 204), 'django.utils.translation.ugettext_lazy', '_', (['"""Expired"""'], {}), "('Expired')\n", (193, 204), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((278, 371), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""self"""'], {'default': 'None', 'blank': '(True)', 'null': '(True)'... |
import numpy as np
from transformers import AdamW, get_scheduler
from transformers.tokenization_utils_base import BatchEncoding
def forward_wrapper_tuple(model, batch):
input_ids = batch['input_ids'].to(model.first_device)
attention_mask = batch['attention_mask'].to(model.first_device)
labels = batch['lab... | [
"transformers.tokenization_utils_base.BatchEncoding",
"numpy.isclose",
"numpy.linalg.norm",
"transformers.get_scheduler",
"transformers.AdamW"
] | [((1660, 1718), 'transformers.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'args.learning_rate'}), '(optimizer_grouped_parameters, lr=args.learning_rate)\n', (1665, 1718), False, 'from transformers import AdamW, get_scheduler\n'), ((1801, 1954), 'transformers.get_scheduler', 'get_scheduler', ([], {'name':... |
"""Same as 01.py, but reports speed"""
import os
import sys
if not os.path.abspath('../../../') in sys.path:
sys.path.append('../../../')
import swhlab
import matplotlib.pyplot as plt
import numpy as np
import time
if __name__=="__main__":
abfFile=R"X:\Data\DIC1\2013\08-2013\08-16-2013-DP\13816004.abf"
ab... | [
"sys.path.append",
"numpy.fft.ifft",
"swhlab.ABF",
"os.path.abspath",
"numpy.average",
"numpy.std",
"numpy.fft.fft",
"time.clock",
"numpy.array"
] | [((114, 142), 'sys.path.append', 'sys.path.append', (['"""../../../"""'], {}), "('../../../')\n", (129, 142), False, 'import sys\n'), ((322, 341), 'swhlab.ABF', 'swhlab.ABF', (['abfFile'], {}), '(abfFile)\n', (332, 341), False, 'import swhlab\n'), ((68, 96), 'os.path.abspath', 'os.path.abspath', (['"""../../../"""'], {... |
__author__ = 'Andrea'
from functions import encode
get_bin = lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
class Pitch(object):
step = None
alter = None
def __init__(self, pitch): # pitch contructor
if pitch is not None:
self.step = pitch.find('step')
sel... | [
"functions.encode"
] | [((1185, 1213), 'functions.encode', 'encode', (['self.pitch', 'self', 'kv'], {}), '(self.pitch, self, kv)\n', (1191, 1213), False, 'from functions import encode\n')] |
import numpy as np
from torch import nn
def num_parameters(self):
return sum(np.prod(p.shape) for p in self.parameters())
nn.Module.num_parameters = property(num_parameters)
from .graph_attention_layer import GraphAttentionNetwork, GraphAttentionLayer
from .utils import get_clones
from .node_transformer import P... | [
"numpy.prod"
] | [((82, 98), 'numpy.prod', 'np.prod', (['p.shape'], {}), '(p.shape)\n', (89, 98), True, 'import numpy as np\n')] |
"""
Author: <NAME>
This class runs tests comparing the genetic algorithm to the random agent
"""
import logging
import os
import json
import time
from random import randint
from chessenv.board import Board
from galgorithm.ga import GA
from ra.ra import RA
log = logging.getLogger('GA_Project')
class GATes... | [
"galgorithm.ga.GA",
"logging.getLogger",
"time.time"
] | [((276, 307), 'logging.getLogger', 'logging.getLogger', (['"""GA_Project"""'], {}), "('GA_Project')\n", (293, 307), False, 'import logging\n'), ((1931, 1944), 'galgorithm.ga.GA', 'GA', ([], {'size': 'size'}), '(size=size)\n', (1933, 1944), False, 'from galgorithm.ga import GA\n'), ((2603, 2639), 'galgorithm.ga.GA', 'GA... |