code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import RepeatVector
from keras.layers import TimeDistributed
from keras.utils import plot_model
def Autoencoder(series_length):
"""
Return a keras model of autoencoder
:par... | [
"keras.layers.LSTM",
"keras.utils.plot_model",
"keras.layers.Dense",
"numpy.array",
"keras.models.Sequential",
"keras.layers.RepeatVector"
] | [((371, 383), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (381, 383), False, 'from keras.models import Sequential\n'), ((748, 803), 'numpy.array', 'np.array', (['[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]'], {}), '([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])\n', (756, 803), True, 'import numpy as n... |
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# 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... | [
"logging.FileHandler",
"logging.basicConfig",
"traceback.extract_stack",
"logging.Formatter",
"importlib.reload",
"warnings.warn",
"logging.getLogger"
] | [((1836, 1851), 'importlib.reload', 'reload', (['logging'], {}), '(logging)\n', (1842, 1851), False, 'from importlib import reload\n'), ((4407, 4430), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (4424, 4430), False, 'import logging\n'), ((2977, 3007), 'logging.Formatter', 'logging.Formatter', ... |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
Containers for unresolved resonance parameters
"""
import fractions
import abc
from PoPs import database as PoPsDatabas... | [
"xData.Documentation.documentation.Documentation",
"fudge.warning.URRdomainMismatch",
"PoPs.database.database.parseXMLNodeAsClass",
"xData.ancestry.ancestry.__init__",
"fudge.abstractClasses.component.__init__",
"pqu.PQU.floatToShortestString",
"pqu.PQU.PQU",
"fudge.suites.suite.__init__"
] | [((900, 1002), 'fudge.abstractClasses.component.__init__', 'abstractClassesModule.component.__init__', (['self'], {'allowedClasses': '(tabulatedWidths, energyIntervals)'}), '(self, allowedClasses=(\n tabulatedWidths, energyIntervals))\n', (940, 1002), True, 'from fudge import suites as suitesModule, abstractClasses ... |
from django.db import models
class Cancel(models.Model):
grade = models.IntegerField(blank=False, null=False)
cancel_date = models.DateTimeField(blank=True, null=True)
supplementary_date = models.DateTimeField(blank=True, null=True)
subject = models.CharField(max_length=100, blank=False, null=False)
... | [
"django.db.models.DateTimeField",
"django.db.models.IntegerField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((71, 115), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(False)', 'null': '(False)'}), '(blank=False, null=False)\n', (90, 115), False, 'from django.db import models\n'), ((134, 177), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)'}), '(bl... |
"""
Generates the baseline examples for use in the tests. If the visuals change,
this file needs to be re-run to generate new baselines.
"""
import shutil
import chess
import numpy as np
import matplotlib.pyplot as plt
from chessplotlib import plot_board, plot_move, mark_move, mark_square
with open("test/boards.txt",... | [
"chess.Move.from_uci",
"chessplotlib.mark_square",
"chessplotlib.plot_move",
"chessplotlib.mark_move",
"chess.Board",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.gca",
"chessplotlib.plot_board",
"matplotlib.pyplot.savefig"
] | [((947, 980), 'chess.Move.from_uci', 'chess.Move.from_uci', (['move_ucis[0]'], {}), '(move_ucis[0])\n', (966, 980), False, 'import chess\n'), ((989, 1016), 'chess.Board', 'chess.Board', (['starting_board'], {}), '(starting_board)\n', (1000, 1016), False, 'import chess\n'), ((1022, 1031), 'matplotlib.pyplot.gca', 'plt.g... |
import operator
import re
import os
import json
import logging
from collections import Counter
from tqdm import tqdm
import colorlog
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
#####################
# Hyperparameters
#####################
CONTEXT_LENGTH = 100
CAPTIO... | [
"colorlog.basicConfig",
"json.load",
"re.split",
"os.makedirs",
"os.path.exists",
"colorlog.info",
"numpy.argsort",
"numpy.sort",
"collections.Counter",
"operator.itemgetter",
"os.path.join",
"sklearn.feature_extraction.text.TfidfTransformer",
"re.sub",
"re.compile"
] | [((387, 432), 'os.path.join', 'os.path.join', (['""".."""', '""".."""', '"""data"""', '"""Instagram"""'], {}), "('..', '..', 'data', 'Instagram')\n", (399, 432), False, 'import os\n'), ((478, 542), 'os.path.join', 'os.path.join', (['DATA_ROOT_PATH', '"""json"""', '"""insta-caption-train.json"""'], {}), "(DATA_ROOT_PATH... |
from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class StageToRedshiftOperator(BaseOperator):
ui_color = '#358140'
copy_sql = """
COPY {}
FROM '{}'
... | [
"airflow.contrib.hooks.aws_hook.AwsHook",
"airflow.hooks.postgres_hook.PostgresHook"
] | [((1183, 1238), 'airflow.contrib.hooks.aws_hook.AwsHook', 'AwsHook', (['self.aws_credential_id'], {'client_type': '"""redshift"""'}), "(self.aws_credential_id, client_type='redshift')\n", (1190, 1238), False, 'from airflow.contrib.hooks.aws_hook import AwsHook\n'), ((1307, 1359), 'airflow.hooks.postgres_hook.PostgresHo... |
# Generated by Django 3.1.7 on 2021-03-15 20:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20210314_1638'),
]
operations = [
migrations.AlterField... | [
"django.db.models.CharField",
"django.db.models.OneToOneField",
"django.db.models.ImageField"
] | [((408, 464), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(1200)', 'null': '(True)'}), '(blank=True, max_length=1200, null=True)\n', (424, 464), False, 'from django.db import migrations, models\n'), ((593, 649), 'django.db.models.CharField', 'models.CharField', ([], {'blank... |
from API import API
rpc = API()
print(" [x] Requesting current prices")
response = rpc.getWeekBTC()
print(" [.] Got %r" % response) | [
"API.API"
] | [((26, 31), 'API.API', 'API', ([], {}), '()\n', (29, 31), False, 'from API import API\n')] |
from tests.iter_version_dev.V1_0_0.task_bask import NLPTask
from tests.iter_version_dev.V1_0_0.train_inference_io import PredictionOutput
from tests.iter_version_dev.V1_0_0.dataset_ner import NerIterableDataset, NerDataset
from tests.iter_version_dev.V1_0_0.common import Split
from tests.iter_version_dev.V1_0_0.metric... | [
"tests.iter_version_dev.V1_0_0.dataset_ner.NerDataset",
"tests.iter_version_dev.V1_0_0.metric.ner_metrics"
] | [((736, 919), 'tests.iter_version_dev.V1_0_0.dataset_ner.NerDataset', 'NerDataset', ([], {'data_dir': 'data_dir', 'tokenizer': 'self.tokenizer', 'label_map': 'label2id', 'pretrain_type': 'self.pretrain_type', 'max_seq_length': 'self.train_args.max_seq_length', 'mode': 'Split.train'}), '(data_dir=data_dir, tokenizer=sel... |
# encoding: utf-8
"""
@author: <NAME>
@contact: <EMAIL>
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = [
'Mish',
'Swish',
'MemoryEfficientSwish',
'GELU']
class Mish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x... | [
"torch.sigmoid",
"torch.pow",
"torch.nn.functional.softplus",
"math.sqrt"
] | [((861, 877), 'torch.sigmoid', 'torch.sigmoid', (['i'], {}), '(i)\n', (874, 877), False, 'import torch\n'), ((544, 560), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (557, 560), False, 'import torch\n'), ((679, 695), 'torch.sigmoid', 'torch.sigmoid', (['i'], {}), '(i)\n', (692, 695), False, 'import torch\n')... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
name = models.CharField(max_length=50)
pNumber = models.CharField(max_length=50)
location = models.CharField(max_length=50)
website = models.CharField(max_length=150)
categ... | [
"django.db.models.FileField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.FloatField"
] | [((139, 170), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (155, 170), False, 'from django.db import models\n'), ((185, 216), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (201, 216), False, 'from django.db im... |
# -*- coding: utf-8 -*-
# imagecodecs/setup.py
"""Imagecodecs package setuptools script."""
import sys
import re
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
buildnumber = '' # 'post0'
with open('imagecodecs/_imagecodecs.pyx') as fh:
co... | [
"setuptools.Extension",
"setuptools.setup",
"setuptools.command.build_ext.build_ext.finalize_options",
"numpy.get_include",
"re.search"
] | [((6352, 6371), 'setuptools.setup', 'setup', ([], {}), '(**setup_args)\n', (6357, 6371), False, 'from setuptools import setup, Extension\n'), ((3348, 3551), 'setuptools.Extension', 'Extension', (['"""imagecodecs._imagecodecs_lite"""', "['imagecodecs/imagecodecs.c', 'imagecodecs/_imagecodecs_lite' + ext]"], {'include_di... |
from webthing import Property, Thing, Value
import kupcimat.util
def create_value_forwarder(value_receiver, value_converter=None):
def value_forwarder(value):
kupcimat.util.execute_async(value_receiver(value))
def value_forwarder_with_converter(value):
kupcimat.util.execute_async(value_recei... | [
"webthing.Property",
"webthing.Thing.__init__"
] | [((597, 668), 'webthing.Thing.__init__', 'Thing.__init__', (['self', 'uri_id', 'title', "['TemperatureSensor']", 'description'], {}), "(self, uri_id, title, ['TemperatureSensor'], description)\n", (611, 668), False, 'from webthing import Property, Thing, Value\n'), ((1398, 1468), 'webthing.Thing.__init__', 'Thing.__ini... |
import os
import re
import sys
import numpy as np
from scipy.io import loadmat
import pandas as pd
DEFAULT_MAT_FILE = './data/nut_data_reps.mat'
DEFAULT_OUT_DIR = './output'
CSV_FILENAME = 'nes-lter-nutrient.csv'
if len(sys.argv) < 3:
in_mat_file = DEFAULT_MAT_FILE
out_dir = DEFAULT_OUT_DIR
else:
assert... | [
"pandas.DataFrame",
"scipy.io.loadmat",
"os.path.exists",
"numpy.isnan",
"pandas.Series"
] | [((448, 475), 'os.path.exists', 'os.path.exists', (['in_mat_file'], {}), '(in_mat_file)\n', (462, 475), False, 'import os\n'), ((534, 557), 'os.path.exists', 'os.path.exists', (['out_dir'], {}), '(out_dir)\n', (548, 557), False, 'import os\n'), ((639, 676), 'scipy.io.loadmat', 'loadmat', (['in_mat_file'], {'squeeze_me'... |
"""
Unit tests for vector databases.
$Id: testvectordb.py,v 1.3 2005/06/28 03:00:28 jp Exp $
"""
import unittest
import pickle
from plastk import rand
from plastk.fnapprox.vectordb import *
from plastk.utils import *
from Numeric import array,arange
class TestVectorDB(unittest.TestCase):
dim = 2
N = 1000
... | [
"pickle.loads",
"unittest.TestSuite",
"Numeric.array",
"unittest.makeSuite",
"Numeric.arange",
"plastk.rand.seed",
"plastk.rand.uniform",
"pickle.dumps"
] | [((2187, 2207), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (2205, 2207), False, 'import unittest\n'), ((331, 344), 'Numeric.array', 'array', (['(x, y)'], {}), '((x, y))\n', (336, 344), False, 'from Numeric import array, arange\n'), ((438, 453), 'plastk.rand.seed', 'rand.seed', (['(0)', '(0)'], {}), '... |
from OpenGLCffi.GLX import params
@params(api='glx', prms=['dpy', 'readCtx', 'writeCtx', 'readTarget', 'writeTarget', 'readOffset', 'writeOffset', 'size'])
def glXCopyBufferSubDataNV(dpy, readCtx, writeCtx, readTarget, writeTarget, readOffset, writeOffset, size):
pass
@params(api='glx', prms=['dpy', 'readCtx', 'writ... | [
"OpenGLCffi.GLX.params"
] | [((35, 159), 'OpenGLCffi.GLX.params', 'params', ([], {'api': '"""glx"""', 'prms': "['dpy', 'readCtx', 'writeCtx', 'readTarget', 'writeTarget', 'readOffset',\n 'writeOffset', 'size']"}), "(api='glx', prms=['dpy', 'readCtx', 'writeCtx', 'readTarget',\n 'writeTarget', 'readOffset', 'writeOffset', 'size'])\n", (41, 1... |
import unittest
from src.flight_model.model import create_database, Session, Airline
from src.flight_model.logic import create_airport
from src.flight_model.logic import create_flight, list_flights
from src.flight_model.logic import create_airline, list_airlines, get_airline, delete_airline, update_airline
from src.fli... | [
"src.flight_model.logic.list_airlines",
"src.flight_model.logic.create_airline",
"src.flight_model.logic.delete_airline",
"src.flight_model.logic.create_flight",
"src.flight_model.logic.get_airline",
"src.flight_model.model.create_database",
"src.flight_model.logic.create_airport",
"src.flight_model.l... | [((449, 466), 'src.flight_model.model.create_database', 'create_database', ([], {}), '()\n', (464, 466), False, 'from src.flight_model.model import create_database, Session, Airline\n'), ((475, 500), 'src.flight_model.logic.create_airline', 'create_airline', (['"""EasyJet"""'], {}), "('EasyJet')\n", (489, 500), False, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
from spell_checker import check
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('text')
args = parser.parse_args()
result = check(args.text)
print('\033[32m{}\03... | [
"spell_checker.check",
"argparse.ArgumentParser"
] | [((177, 202), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (200, 202), False, 'import argparse\n'), ((279, 295), 'spell_checker.check', 'check', (['args.text'], {}), '(args.text)\n', (284, 295), False, 'from spell_checker import check\n')] |
from setuptools import setup
setup(
name = "docklet",
version = "0.1",
py_modules = ["client"],
install_requires=[
'click',
'requests'
],
entry_points='''
[console_scripts]
docklet=client:main
''',
)
| [
"setuptools.setup"
] | [((31, 219), 'setuptools.setup', 'setup', ([], {'name': '"""docklet"""', 'version': '"""0.1"""', 'py_modules': "['client']", 'install_requires': "['click', 'requests']", 'entry_points': '"""\n [console_scripts]\n docklet=client:main\n """'}), '(name=\'docklet\', version=\'0.1\', py_modules=[\'client\']... |
from django.urls import path, re_path
from tokenapi.decorators import token_required
from .views import authentication
from .views import healthcheck
from .views import login
from .views import logout
from .views import main
from .views import register
from .views import users
from .views import validate
from .views i... | [
"tokenapi.decorators.token_required",
"django.urls.path"
] | [((856, 918), 'django.urls.path', 'path', (['"""v1.0/register"""', 'register.register_view'], {'name': '"""register"""'}), "('v1.0/register', register.register_view, name='register')\n", (860, 918), False, 'from django.urls import path, re_path\n'), ((954, 1079), 'django.urls.path', 'path', (['"""v1.0/recover_password_... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
import torch
from torch import nn
from cvpods.engine import SimpleRunner
from torch.utils.data import Dataset
class SimpleDataset(Dataset):
def __init__(self, length=100):
self.data_list = torch.rand(length, 3, 3)
... | [
"torch.device",
"torch.nn.Linear",
"torch.cuda.is_available",
"torch.rand"
] | [((294, 318), 'torch.rand', 'torch.rand', (['length', '(3)', '(3)'], {}), '(length, 3, 3)\n', (304, 318), False, 'import torch\n'), ((637, 657), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (649, 657), False, 'import torch\n'), ((1127, 1152), 'torch.cuda.is_available', 'torch.cuda.is_available', ([],... |
#sample script that reads ngrok info from localhost:4040 and create Cisco Spark Webhook
#typicall ngrok is called "ngrok http 8080" to redirect localhost:8080 to Internet
#accesible ngrok url
#
#To use script simply launch ngrok, then launch this script. After ngrok is killed, run this
#script a second time to re... | [
"requests.packages.urllib3.disable_warnings",
"json.loads",
"ciscosparkapi.CiscoSparkAPI",
"requests.get",
"re.search",
"sys.exit"
] | [((442, 486), 'requests.packages.urllib3.disable_warnings', 'requests.packages.urllib3.disable_warnings', ([], {}), '()\n', (484, 486), False, 'import requests\n'), ((988, 1005), 'ciscosparkapi.CiscoSparkAPI', 'CiscoSparkAPI', (['at'], {}), '(at)\n', (1001, 1005), False, 'from ciscosparkapi import CiscoSparkAPI, Webhoo... |
import datetime
import h5py
import numpy as np
import torch
from torch.utils import data
import torch.nn.functional as F
import soundfile as sf
from transformData import mu_law_encode,quan_mu_law_encode
sampleSize = 16384 * 60
sample_rate = 16384 * 60
class Dataset(data.Dataset):
def __init__(self, listx, rootx... | [
"numpy.random.uniform",
"numpy.random.seed",
"transformData.mu_law_encode",
"numpy.random.randint",
"datetime.datetime.now",
"numpy.concatenate"
] | [((722, 738), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (736, 738), True, 'import numpy as np\n'), ((997, 1013), 'transformData.mu_law_encode', 'mu_law_encode', (['x'], {}), '(x)\n', (1010, 1013), False, 'from transformData import mu_law_encode, quan_mu_law_encode\n'), ((1026, 1042), 'transformData.mu_la... |
import os
from aiohttp.test_utils import unittest_run_loop
from conf import settings
from tests import BaseTestCase
class RequestIntegrationTest(BaseTestCase):
async def setUpAsync(self):
await super().setUpAsync()
await self.connection.execute("""
INSERT INTO data (id, type, message... | [
"os.path.exists"
] | [((5504, 5597), 'os.path.exists', 'os.path.exists', (['f"""{settings.MEDIA_PATH}/wordcloud__{self.from_date}__{self.to_date}.png"""'], {}), "(\n f'{settings.MEDIA_PATH}/wordcloud__{self.from_date}__{self.to_date}.png')\n", (5518, 5597), False, 'import os\n'), ((6338, 6429), 'os.path.exists', 'os.path.exists', (['f""... |
# -*- coding: utf-8 -*-
from nose.tools import assert_equal, assert_in
from vcards import VCard, VCardParser
TOTO_CARD = """BEGIN:VCARD
VERSION:3.0
N:Toto;Tutu;;;
FN:<NAME>
ORG:python;
item1.EMAIL;type=INTERNET;type=pref:<EMAIL>
REV:2013-08-29T21:50:13Z
UID:1234-5678-9000-1
END:VCARD"""
APPLE_CARD = """BEGIN:VCARD
VE... | [
"nose.tools.assert_in",
"vcards.VCardParser",
"vcards.VCard",
"nose.tools.assert_equal"
] | [((912, 928), 'vcards.VCard', 'VCard', (['TOTO_CARD'], {}), '(TOTO_CARD)\n', (917, 928), False, 'from vcards import VCard, VCardParser\n'), ((937, 974), 'nose.tools.assert_equal', 'assert_equal', (['TOTO_CARD', 'card.content'], {}), '(TOTO_CARD, card.content)\n', (949, 974), False, 'from nose.tools import assert_equal,... |
# -*- coding:utf-8 -*-
# email:<EMAIL>
# create: 2020/12/3
from torch.utils.data import Dataset
import lmdb
import six
import sys
from PIL import Image
from utils.log import logger
from_ch = [
u',', u'!', u':', u'(', u')', u';', u'—', u'“', u'”', u'‘', u'’', u'~', u'√', u'℃', u'¥', u'в', u'[', u']', u'|',
u'•'... | [
"six.BytesIO",
"utils.log.logger.error",
"PIL.Image.open",
"lmdb.open",
"sys.exit"
] | [((1171, 1246), 'lmdb.open', 'lmdb.open', (['data_root'], {'max_dbs': '(3)', 'readonly': '(True)', 'lock': '(False)', 'readahead': '(False)'}), '(data_root, max_dbs=3, readonly=True, lock=False, readahead=False)\n', (1180, 1246), False, 'import lmdb\n'), ((3720, 3820), 'lmdb.open', 'lmdb.open', (['data_root'], {'max_re... |
#!/usr/bin/env python
import sys
def main():
lines = sys.stdin.read().strip().split('\n')
for l in lines:
aligns = [tuple(map(int, a.split('-'))) for a in l.strip().split()]
rev_aligns = [(a[1], a[0]) for a in aligns]
rev_aligns.sort()
print(' '.join([f'{a}-{b}' for a, b in rev_... | [
"sys.stdin.read"
] | [((58, 74), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (72, 74), False, 'import sys\n')] |
import tushare as ts
a = ts.get_hist_data('600848') #一次性获取全部日k线数据
# print(a)
print(type(a)) | [
"tushare.get_hist_data"
] | [((26, 52), 'tushare.get_hist_data', 'ts.get_hist_data', (['"""600848"""'], {}), "('600848')\n", (42, 52), True, 'import tushare as ts\n')] |
import shlex
from instr_spasm import *
MACROS = ["EUVAL", "ESET", "EGET", "ECALL", "EPUSH"]
# TODO: "CMPJE", "CMPJNE", "CMPJZ", "CMPJNZ", "CMPJL", "CMPJLE", "CMPJG", "CMPJGE"]
REGISTERS = {"SRIP":0, "SRSP":1, "SRAX":4, "SRBX":5, "SRCX":6, "SRDX":7,
"RIP":0, "RSP":1, "RAX":4, "RBX":5, "RCX":6, "R... | [
"shlex.split"
] | [((1213, 1234), 'shlex.split', 'shlex.split', (['line_sep'], {}), '(line_sep)\n', (1224, 1234), False, 'import shlex\n')] |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class SearchTwitterUser(FlaskForm):
twname = StringField('Username', default='Twitter', validators=[DataRequired(), Length(min=2, max=20)])
... | [
"wtforms.SubmitField",
"wtforms.validators.DataRequired",
"wtforms.validators.Length"
] | [((332, 353), 'wtforms.SubmitField', 'SubmitField', (['"""Sumbit"""'], {}), "('Sumbit')\n", (343, 353), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((279, 293), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (291, 293), False, 'from wtforms.validators imp... |
import numpy as np
import os
import sys
import tensorflow as tf
from imutils.video import VideoStream
import cv2
import imutils
import time
from imutils.video import FPS
from sklearn.metrics import pairwise
import copy
import pathlib
from collections import defaultdict
colors = np.random.uniform(0, 255, size=(100, 3))... | [
"numpy.random.uniform",
"cv2.putText",
"cv2.rectangle"
] | [((280, 320), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(255)'], {'size': '(100, 3)'}), '(0, 255, size=(100, 3))\n', (297, 320), True, 'import numpy as np\n'), ((864, 937), 'cv2.rectangle', 'cv2.rectangle', (['image_np', '(xmin, ymin)', '(xmin + w, ymin + h)', '(0, 0, 0)', '(3)'], {}), '(image_np, (xmin, y... |
import csv
from collections import defaultdict
import random
from typing import Tuple, List
import time
import pickle
from tqdm import tqdm
import os.path
def write_dataset(data, filename: str):
"""Saves processed_samples to .pickle file"""
with open(filename, 'wb') as handle:
pickle.dump(data, handl... | [
"tqdm.tqdm",
"pickle.dump",
"csv.reader",
"random.shuffle",
"random.choice",
"collections.defaultdict",
"random.seed"
] | [((1454, 1471), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1465, 1471), False, 'from collections import defaultdict\n'), ((1811, 1845), 'csv.reader', 'csv.reader', (['qtexts'], {'delimiter': '"""\t"""'}), "(qtexts, delimiter='\\t')\n", (1821, 1845), False, 'import csv\n'), ((1865, 1920), 'tq... |
import tensorflow as tf
from functools import reduce
from operator import mul
from tensorflow.contrib.rnn.python.ops.core_rnn_cell import _linear
from tensorflow.python.util import nest
#source https://github.com/IsaacChanghau/Dense_BiLSTM/blob/master/models/nns.py
def dense(inputs, hidden_dim, use_bias=True, scope=... | [
"tensorflow.nn.softmax",
"tensorflow.keras.initializers.glorot_normal",
"tensorflow.nn.relu",
"tensorflow.constant_initializer",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.name_scope",
"tensorflow.nn.sigmoid",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.python.util.n... | [((3100, 3129), 'tensorflow.reshape', 'tf.reshape', (['tensor', 'out_shape'], {}), '(tensor, out_shape)\n', (3110, 3129), True, 'import tensorflow as tf\n'), ((3589, 3621), 'tensorflow.reshape', 'tf.reshape', (['tensor', 'target_shape'], {}), '(tensor, target_shape)\n', (3599, 3621), True, 'import tensorflow as tf\n'),... |
import sys
import logging
import flask
import traceback
from werkzeug.serving import make_server
import threading
from hypertrace.agent import Agent
def setup_custom_logger(name):
try:
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-... | [
"threading.Thread.__init__",
"logging.FileHandler",
"werkzeug.serving.make_server",
"flask.Flask",
"logging.StreamHandler",
"logging.Formatter",
"traceback.format_exc",
"sys.exc_info",
"hypertrace.agent.Agent",
"flask.Response",
"logging.getLogger"
] | [((1506, 1527), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (1517, 1527), False, 'import flask\n'), ((2312, 2319), 'hypertrace.agent.Agent', 'Agent', ([], {}), '()\n', (2317, 2319), False, 'from hypertrace.agent import Agent\n'), ((204, 302), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': ... |
import os, sys
import typing
import argparse
import itertools
class ArgumentParser(argparse.ArgumentParser):
def _get_action_from_name(self, name):
"""Given a name, get the Action instance registered with this parser.
If only it were made available in the ArgumentError object. It is
passed ... | [
"sys.exc_info"
] | [((739, 753), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (751, 753), False, 'import os, sys\n')] |
# -*- utf-8 -*-
from openpyxl import Workbook, load_workbook
from openpyxl.compat import range
from openpyxl.utils import get_column_letter
import random
import string
def get_isbn():
v0 = random.randint(1, 1000)
v1 = random.randint(1, 10)
v2 = random.randint(1, 1000)
v3 = random.randint(1, 100000)
... | [
"random.randint",
"openpyxl.Workbook",
"random.choice",
"openpyxl.compat.range",
"openpyxl.utils.get_column_letter"
] | [((196, 219), 'random.randint', 'random.randint', (['(1)', '(1000)'], {}), '(1, 1000)\n', (210, 219), False, 'import random\n'), ((229, 250), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (243, 250), False, 'import random\n'), ((260, 283), 'random.randint', 'random.randint', (['(1)', '(1000)']... |
import json
import sys
with open("version-"+sys.argv[1] +"-sidebars.json",'r') as json_file:
data = json.load(json_file)
version="version-"+sys.argv[1] +"-"
data['version-'+sys.argv[1] +'-docs'] = data.pop('docs')
docs = data['version-'+sys.argv[1] +'-docs']
val= []
# update version in getting started
for value... | [
"json.dump",
"json.load"
] | [((105, 125), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (114, 125), False, 'import json\n'), ((1608, 1644), 'json.dump', 'json.dump', (['data', 'json_file'], {'indent': '(2)'}), '(data, json_file, indent=2)\n', (1617, 1644), False, 'import json\n'), ((1737, 1757), 'json.load', 'json.load', (['json... |
import asyncio
import logging
import os
import rospy
_logger = logging.getLogger("arospy.client")
async def spin():
"""
Wait until ROS node is shutdown. Yields activity to other threads.
@raise ROSInitException: if node is not in a properly initialized state
"""
if not rospy.core.is_initialized(... | [
"os.getpid",
"asyncio.sleep",
"rospy.core.is_shutdown",
"logging.getLogger",
"rospy.exceptions.ROSInitException",
"rospy.core.is_initialized",
"rospy.core.get_node_uri",
"rospy.core.get_caller_id"
] | [((64, 98), 'logging.getLogger', 'logging.getLogger', (['"""arospy.client"""'], {}), "('arospy.client')\n", (81, 98), False, 'import logging\n'), ((294, 321), 'rospy.core.is_initialized', 'rospy.core.is_initialized', ([], {}), '()\n', (319, 321), False, 'import rospy\n'), ((337, 424), 'rospy.exceptions.ROSInitException... |
# coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... | [
"six.iteritems"
] | [((11970, 12003), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (11983, 12003), False, 'import six\n')] |
import yaml
import chainer
import source.yaml_utils as yaml_utils
from argparser import args
config = yaml_utils.Config(yaml.load(open(args.config_path)))
chainer.cuda.get_device_from_id(args.gpu).use()
gen_conf = config.models['generator']
gen = yaml_utils.load_model(gen_conf['fn'], gen_conf['name'], gen_conf['args... | [
"chainer.cuda.get_device_from_id",
"source.yaml_utils.load_model",
"chainer.serializers.load_npz"
] | [((250, 323), 'source.yaml_utils.load_model', 'yaml_utils.load_model', (["gen_conf['fn']", "gen_conf['name']", "gen_conf['args']"], {}), "(gen_conf['fn'], gen_conf['name'], gen_conf['args'])\n", (271, 323), True, 'import source.yaml_utils as yaml_utils\n'), ((372, 445), 'source.yaml_utils.load_model', 'yaml_utils.load_... |
import os
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from bpe import Config
from bpe.agent import agents_bpe
from bpe.dataset.datasets_bpe import SARADataset
from bpe.functional.utils import cycle, mov... | [
"tqdm.tqdm",
"numpy.random.seed",
"bpe.dataset.datasets_bpe.SARADataset",
"argparse.ArgumentParser",
"bpe.agent.agents_bpe.Agent3x_bpe",
"bpe.Config",
"bpe.functional.utils.cycle",
"bpe.Config.__dict__.items",
"bpe.model.networks_bpe.AutoEncoder_bpe",
"torch.nn.DataParallel",
"bpe.functional.uti... | [((1162, 1187), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1185, 1187), False, 'import argparse\n'), ((2575, 2587), 'bpe.Config', 'Config', (['args'], {}), '(args)\n', (2581, 2587), False, 'from bpe import Config\n'), ((2624, 2660), 'bpe.model.networks_bpe.AutoEncoder_bpe', 'networks_bpe.A... |
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.utils.extmath import cartesian
# import matplotlib.pyplot as plt
class MPHP:
'''Multidimensional Periodic Hawkes Process
Captures rates with periodic component depending on the day of week
'''
def __init__(self... | [
"numpy.abs",
"numpy.sum",
"numpy.floor",
"numpy.random.exponential",
"numpy.ones",
"numpy.arange",
"numpy.tile",
"numpy.exp",
"numpy.multiply",
"numpy.linalg.eig",
"numpy.append",
"numpy.max",
"numpy.divide",
"numpy.vectorize",
"numpy.ceil",
"numpy.triu_indices",
"numpy.all",
"nump... | [((354, 364), 'numpy.ones', 'np.ones', (['(7)'], {}), '(7)\n', (361, 364), True, 'import numpy as np\n'), ((875, 900), 'numpy.linalg.eig', 'np.linalg.eig', (['self.alpha'], {}), '(self.alpha)\n', (888, 900), True, 'import numpy as np\n'), ((1641, 1660), 'numpy.max', 'np.max', (['self.mu_day'], {}), '(self.mu_day)\n', (... |
import torch
import torch.nn as nn
class custom_loss(nn.Module):
def __init__(self,lambda_entropy):
super(custom_loss, self).__init__()
self.lambda_entropy = lambda_entropy
def forward(self, neg_entropy, answer_loss, policy_gradient_losses=None,layout_loss =None):
answer = torch.mean(a... | [
"torch.mean"
] | [((308, 331), 'torch.mean', 'torch.mean', (['answer_loss'], {}), '(answer_loss)\n', (318, 331), False, 'import torch\n'), ((698, 732), 'torch.mean', 'torch.mean', (['policy_gradient_losses'], {}), '(policy_gradient_losses)\n', (708, 732), False, 'import torch\n'), ((674, 697), 'torch.mean', 'torch.mean', (['answer_loss... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import logging
__logger__ = logging.getLogger('pybsd')
class PyBSDError(Exception):
"""Base PyBSD Exception. It is only used to except any PyBSD error and never raised
Attributes
----------
msg : :py:cl... | [
"logging.getLogger"
] | [((127, 153), 'logging.getLogger', 'logging.getLogger', (['"""pybsd"""'], {}), "('pybsd')\n", (144, 153), False, 'import logging\n')] |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"jax.numpy.pad",
"jax.numpy.concatenate",
"jax.numpy.zeros_like",
"functools.reduce",
"jax.example_libraries.stax.FanOut",
"jax.example_libraries.stax.FanInConcat",
"warnings.warn",
"jax.numpy.broadcast_to"
] | [((1445, 1462), 'jax.example_libraries.stax.FanOut', 'ostax.FanOut', (['num'], {}), '(num)\n', (1457, 1462), True, 'import jax.example_libraries.stax as ostax\n'), ((6543, 6566), 'jax.example_libraries.stax.FanInConcat', 'ostax.FanInConcat', (['axis'], {}), '(axis)\n', (6560, 6566), True, 'import jax.example_libraries.... |
from pydantic import BaseModel, Field, UUID4
from typing import Optional
from uuid import uuid4
from api.models import type_str, validators
class EventRemediationBase(BaseModel):
"""Represents a remediation that can be applied to an event to denote which tasks were taken to clean up after
the attack."""
... | [
"api.models.validators.prevent_none",
"pydantic.Field"
] | [((355, 444), 'pydantic.Field', 'Field', ([], {'description': '"""An optional human-readable description of the event remediation"""'}), "(description=\n 'An optional human-readable description of the event remediation')\n", (360, 444), False, 'from pydantic import BaseModel, Field, UUID4\n'), ((477, 532), 'pydantic... |
import numpy as np
import matplotlib.pyplot as plt
n_files = 100
path = './experiments/test9/PES'
name = '/test9_PES_f_'
n_iterations = 100
log_regret = np.zeros((n_iterations,n_files))
time = np.zeros((n_iterations,n_files))
real_opt = 0.#test7:4.389940124468381 #test5:-0.5369910241891562#test-0.42973174#test_linear... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.std",
"numpy.savetxt",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.mean"
] | [((154, 187), 'numpy.zeros', 'np.zeros', (['(n_iterations, n_files)'], {}), '((n_iterations, n_files))\n', (162, 187), True, 'import numpy as np\n'), ((195, 228), 'numpy.zeros', 'np.zeros', (['(n_iterations, n_files)'], {}), '((n_iterations, n_files))\n', (203, 228), True, 'import numpy as np\n'), ((720, 747), 'numpy.z... |
import argparse
from tools.utils import *
import os
from net import generator
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def parse_args():
desc = "AnimeGAN"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--checkpoint_dir', type=str, default='../checkpoint/' + 'AnimeGAN_Hayao_lsgan_... | [
"net.generator.G_net",
"os.path.join",
"argparse.ArgumentParser",
"os.path.basename"
] | [((174, 215), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (197, 215), False, 'import argparse\n'), ((635, 685), 'os.path.join', 'os.path.join', (['checkpoint_dir', "(model_name + '.ckpt')"], {}), "(checkpoint_dir, model_name + '.ckpt')\n", (647, 685), Fal... |
from typing import Tuple
import torch
from torch import nn
from mmderain.models.layers import SELayer
from mmderain.models.registry import BACKBONES
class DCCL(nn.Module):
"""Dilated Conv Concatenation Layer"""
def __init__(self, planes: int) -> None:
super().__init__()
self.conv1 = nn.Con... | [
"mmderain.models.registry.BACKBONES.register_module",
"torch.nn.PReLU",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.BatchNorm2d",
"mmderain.models.layers.SELayer"
] | [((2505, 2532), 'mmderain.models.registry.BACKBONES.register_module', 'BACKBONES.register_module', ([], {}), '()\n', (2530, 2532), False, 'from mmderain.models.registry import BACKBONES\n'), ((314, 387), 'torch.nn.Conv2d', 'nn.Conv2d', (['planes', 'planes'], {'kernel_size': '(3)', 'stride': '(1)', 'dilation': '(3)', 'p... |
import ConfigParser
config = ConfigParser.ConfigParser()
print ("Hello! Thanks for using flairbot by jackson1442.\nThis script will walk\
you through the creation of your configuration file.\nFirst thing's first - \
please read the README in the package before starting.")
cfgfile = open('botconfig.ini', 'w')
#-- BASI... | [
"ConfigParser.ConfigParser"
] | [((29, 56), 'ConfigParser.ConfigParser', 'ConfigParser.ConfigParser', ([], {}), '()\n', (54, 56), False, 'import ConfigParser\n')] |
from typing import OrderedDict
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.dispatch import Signal
from imagekit import ImageSpec
from imagekit.processors import ResizeToFill
from rest_framework.pagination import LimitOffsetPagination... | [
"imagekit.processors.ResizeToFill",
"django.core.exceptions.ImproperlyConfigured",
"django.dispatch.Signal",
"django.apps.apps.get_model"
] | [((383, 391), 'django.dispatch.Signal', 'Signal', ([], {}), '()\n', (389, 391), False, 'from django.dispatch import Signal\n'), ((442, 501), 'django.apps.apps.get_model', 'apps.get_model', (['settings.PRODUCT_MODEL'], {'require_ready': '(False)'}), '(settings.PRODUCT_MODEL, require_ready=False)\n', (456, 501), False, '... |
import pygame
from random import randint
import numpy as np
# Programa por Magnus e Rudigus
pygame.init()
screen = pygame.display.set_mode((620, 620))
myfont = pygame.font.SysFont("monospace", 30, 1)
done = False
is_blue = 0
quantBlocos = [10, 10]
blocos = []
minas = np.zeros((quantBlocos[0], quantBlocos[1]))
minas[... | [
"pygame.mouse.get_pressed",
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"pygame.Rect",
"numpy.zeros",
"pygame.init",
"pygame.display.flip",
"pygame.mouse.get_pos",
"numpy.random.shuffle"
] | [((94, 107), 'pygame.init', 'pygame.init', ([], {}), '()\n', (105, 107), False, 'import pygame\n'), ((117, 152), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(620, 620)'], {}), '((620, 620))\n', (140, 152), False, 'import pygame\n'), ((162, 201), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""monospace... |
#!/usr/bin/env python
"""Script to run RM2 ALM case."""
import argparse
import os
import subprocess
from subprocess import call, check_output
import numpy as np
import pandas as pd
import glob
import foampy
from foampy.dictionaries import replace_value
import shutil
from pyrm2tf import processing as pr
def get_mesh_... | [
"pandas.DataFrame",
"os.mkdir",
"os.remove",
"argparse.ArgumentParser",
"os.path.isdir",
"pandas.read_csv",
"foampy.clean",
"subprocess.check_output",
"pyrm2tf.processing.calc_perf",
"foampy.dictionaries.read_single_line_value",
"os.path.isfile",
"numpy.arange",
"subprocess.call",
"numpy.l... | [((709, 784), 'foampy.dictionaries.read_single_line_value', 'foampy.dictionaries.read_single_line_value', (['"""controlDict"""'], {'keyword': '"""deltaT"""'}), "('controlDict', keyword='deltaT')\n", (751, 784), False, 'import foampy\n'), ((1206, 1226), 'pyrm2tf.processing.calc_perf', 'pr.calc_perf', ([], {'t1': '(3.0)'... |
"""Unit tests for the route authentication plugin."""
import logging
import unittest
from datetime import datetime, timezone
from unittest.mock import Mock
import bottle
from routes.plugins import AuthPlugin, InjectionPlugin
class AuthPluginTest(unittest.TestCase):
"""Unit tests for the route authentication an... | [
"unittest.mock.Mock",
"datetime.datetime.max.replace",
"logging.disable",
"datetime.datetime.min.replace",
"bottle.app",
"routes.plugins.InjectionPlugin",
"routes.plugins.AuthPlugin"
] | [((451, 468), 'logging.disable', 'logging.disable', ([], {}), '()\n', (466, 468), False, 'import logging\n'), ((498, 504), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (502, 504), False, 'from unittest.mock import Mock\n'), ((873, 904), 'logging.disable', 'logging.disable', (['logging.NOTSET'], {}), '(logging.NOTSET... |
# PAM interface in python
# sudo apt-get install libpam-python bluetooth libbluetooth-dev gobject
# sudo pip install pybluez
# Import required modules
import subprocess
import sys
import os
import bluetooth, time
def doAuth(pamh):
"""Do Authentication here"""
search_time = 10
# Hardcoded the data for now
addr = ... | [
"bluetooth.lookup_name",
"bluetooth.find_service"
] | [((356, 395), 'bluetooth.lookup_name', 'bluetooth.lookup_name', (['addr'], {'timeout': '(20)'}), '(addr, timeout=20)\n', (377, 395), False, 'import bluetooth, time\n'), ((408, 444), 'bluetooth.find_service', 'bluetooth.find_service', ([], {'address': 'addr'}), '(address=addr)\n', (430, 444), False, 'import bluetooth, t... |
import os
from pypdflite.pdflite import PDFLite
from pypdflite.pdfobjects.pdfcolor import PDFColor
def HtmlTest2(test_dir):
writer = PDFLite(os.path.join(test_dir, "tests/HTMLtest2.pdf"))
document = writer.get_document()
document.add_text('Sample text')
document.add_newline(2)
red = PDFColor(nam... | [
"os.path.join",
"pypdflite.pdfobjects.pdfcolor.PDFColor"
] | [((308, 328), 'pypdflite.pdfobjects.pdfcolor.PDFColor', 'PDFColor', ([], {'name': '"""red"""'}), "(name='red')\n", (316, 328), False, 'from pypdflite.pdfobjects.pdfcolor import PDFColor\n'), ((340, 361), 'pypdflite.pdfobjects.pdfcolor.PDFColor', 'PDFColor', ([], {'name': '"""blue"""'}), "(name='blue')\n", (348, 361), F... |
from datetime import datetime
class FlightInfo:
def __init__(self, node_id, height):
self.node_id: int = node_id
self.height: int = height
self.start_time: int = datetime.utcnow().timestamp()
def reset_start_time(self):
self.start_time = datetime.utcnow().timestamp()
| [
"datetime.datetime.utcnow"
] | [((192, 209), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (207, 209), False, 'from datetime import datetime\n'), ((281, 298), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (296, 298), False, 'from datetime import datetime\n')] |
from fastapi import FastAPI
from rest_introduction_app.api.challenges.challenge_6 import challenge_6
app = FastAPI(
title='Excursion od Diatlov Pass',
description="Prepare your backback, you're gonna need it!",
version="0.1",
docs_url="/",
redoc_url=None
)
app.include_router(router=challenge_6.ro... | [
"fastapi.FastAPI"
] | [((109, 266), 'fastapi.FastAPI', 'FastAPI', ([], {'title': '"""Excursion od Diatlov Pass"""', 'description': '"""Prepare your backback, you\'re gonna need it!"""', 'version': '"""0.1"""', 'docs_url': '"""/"""', 'redoc_url': 'None'}), '(title=\'Excursion od Diatlov Pass\', description=\n "Prepare your backback, you\'... |
import numpy as np
import argparse
from matplotlib import pyplot as plt
rewards = []
EPOSIDES = 250
lineStyle = ['-b','--r','.g']
def plot(f, arr, strLabel):
strLine = f.readline()
start = strLine.find('INFO')
if start != -1:
start += len('INFO:')
tittle = strLine[start:-1]
else :
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"numpy.asarray",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"argparse.FileType"
] | [((601, 636), 'numpy.asarray', 'np.asarray', (['rewards'], {'dtype': 'np.float'}), '(rewards, dtype=np.float)\n', (611, 636), True, 'import numpy as np\n'), ((675, 698), 'numpy.arange', 'np.arange', (['(0)', 'rewardLen'], {}), '(0, rewardLen)\n', (684, 698), True, 'import numpy as np\n'), ((703, 720), 'matplotlib.pyplo... |
from django.test import TestCase
from django.utils import timezone
from django.utils.translation import activate
from api.accounts.models import MyUser
from api.enums import TeamStateTypes
from api.team.models import Team
from api.tournaments.models import Tournament
activate('en-us')
class Tournaments(TestCase):
... | [
"django.utils.translation.activate",
"api.accounts.models.MyUser.objects.create",
"django.utils.timezone.now",
"django.utils.timezone.timedelta",
"api.team.models.Team.objects.create",
"api.tournaments.models.Tournament.objects.create"
] | [((270, 287), 'django.utils.translation.activate', 'activate', (['"""en-us"""'], {}), "('en-us')\n", (278, 287), False, 'from django.utils.translation import activate\n'), ((405, 712), 'api.tournaments.models.Tournament.objects.create', 'Tournament.objects.create', ([], {'name': '"""<NAME>"""', 'gender': '"""mixed"""',... |
import importlib.util
import io
import textwrap
import tokenize
from pegen.build import compile_c_extension
from pegen.grammar import GrammarParser
from pegen.c_generator import CParserGenerator
from pegen.python_generator import PythonParserGenerator
from pegen.tokenizer import Tokenizer, grammar_tokenizer
def gener... | [
"textwrap.dedent",
"io.StringIO",
"pegen.c_generator.CParserGenerator",
"pegen.python_generator.PythonParserGenerator",
"tokenize.generate_tokens"
] | [((374, 387), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (385, 387), False, 'import io\n'), ((399, 432), 'pegen.python_generator.PythonParserGenerator', 'PythonParserGenerator', (['rules', 'out'], {}), '(rules, out)\n', (420, 432), False, 'from pegen.python_generator import PythonParserGenerator\n'), ((1157, 1176)... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
##packages
import pandas as pd
import pickle
import numpy as np
from collections import Counter
# In[13]:
class PostProcess():
def __init__(self):
pass
def load_obj(self, name):
with open(name + '.pkl... | [
"collections.Counter",
"pickle.dump",
"pickle.load",
"pandas.Series"
] | [((4919, 4946), 'collections.Counter', 'Counter', (['data.connected_adr'], {}), '(data.connected_adr)\n', (4926, 4946), False, 'from collections import Counter\n'), ((355, 388), 'pickle.load', 'pickle.load', (['f'], {'encoding': '"""latin1"""'}), "(f, encoding='latin1')\n", (366, 388), False, 'import pickle\n'), ((492,... |
import simulator
import os
import json
import subprocess
import yaml
def getFilePath(i):
return "result_data/result_"+str(i)+".yaml"
# DIR = 'result_data' #要统计的文件夹
# file_num = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
# print (file_num )
def extract_output(stdout):
... | [
"json.loads"
] | [((449, 462), 'json.loads', 'json.loads', (['p'], {}), '(p)\n', (459, 462), False, 'import json\n')] |
# -*- coding: utf-8 -*-
"""
Module that loads data distributed at http://jmcauley.ucsd.edu/data/amazon/
The dataset was presented on the following papers:
<NAME>, <NAME>. 2016. Ups and downs: Modeling the visual evolution of fashion
trends with one-class collaborative filtering. WWW.
<NAME>, <NAME>, <NAME>, <NAME>. ... | [
"nltk.tokenize.word_tokenize",
"numpy.asarray",
"numpy.array",
"multidomain_sentiment.dataset.common.create_dataset",
"nltk.download",
"multidomain_sentiment.word_embedding.load_word_embedding",
"six.iteritems",
"logging.getLogger"
] | [((534, 567), 'nltk.download', 'nltk.download', ([], {'info_or_id': '"""punkt"""'}), "(info_or_id='punkt')\n", (547, 567), False, 'import nltk\n'), ((814, 841), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (831, 841), False, 'import logging\n'), ((1410, 1438), 'numpy.asarray', 'np.asarr... |
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name:
# Purpose:
#
# Author: hekai
#-------------------------------------------------------------------------------
import sys
import os
print(sys.path)
cmd_res = os.popen("dir... | [
"os.popen"
] | [((307, 322), 'os.popen', 'os.popen', (['"""dir"""'], {}), "('dir')\n", (315, 322), False, 'import os\n')] |
import os
import numpy as np
import sys
import SimpleITK as sitk
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from data_io_utils import DataIO
class MaskBoundingUtils:
def __init__(self):
print('init MaskBoundingUtils class')
@staticmethod
def extract_mask_file_bounding(infile, i... | [
"os.path.abspath",
"os.makedirs",
"SimpleITK.ReadImage",
"os.path.dirname",
"data_io_utils.DataIO.load_dicom_series",
"data_io_utils.DataIO.load_nii_image",
"SimpleITK.GetArrayFromImage",
"data_io_utils.DataIO.save_medical_info_and_data",
"numpy.where",
"numpy.array",
"SimpleITK.WriteImage",
"... | [((7520, 7546), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['image_file'], {}), '(image_file)\n', (7534, 7546), True, 'import SimpleITK as sitk\n'), ((7561, 7586), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['mask_file'], {}), '(mask_file)\n', (7575, 7586), True, 'import SimpleITK as sitk\n'), ((7734, 7769), 'os.makedirs... |
# Import the Africa's Talking module here
import africastalking
#Define credentials here
username = "sandbox NAME"
api_key = "YOUR API KEY"
#Authenticate with the service
africastalking.initialize(username, api_key)
#Define the airtime service
airtime = africastalking.Airtime
#Define user variables
phone_number = ... | [
"africastalking.initialize"
] | [((173, 217), 'africastalking.initialize', 'africastalking.initialize', (['username', 'api_key'], {}), '(username, api_key)\n', (198, 217), False, 'import africastalking\n')] |
import serial
from binascii import hexlify, unhexlify
class LCDControl():
def __init__(self):
self._s = serial.Serial('/dev/ttyACM0', 9600)
def clear(self):
self.reset_cursor()
self._s.write(b'\xFE\x51')
def reset_cursor(self):
self._s.write(b'\xFE\x45\x00')
def write... | [
"serial.Serial",
"binascii.unhexlify"
] | [((117, 152), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyACM0"""', '(9600)'], {}), "('/dev/ttyACM0', 9600)\n", (130, 152), False, 'import serial\n'), ((465, 480), 'binascii.unhexlify', 'unhexlify', (['data'], {}), '(data)\n', (474, 480), False, 'from binascii import hexlify, unhexlify\n')] |
import os
import shlex
import sys
from string import Template
from typing import Dict, List, Tuple
SectionType = Dict[str, str]
ConfigType = Dict[str, SectionType]
ArgvType = List[str]
def format_argv(args=None):
args = args or sys.argv[:]
args[0] = os.path.basename(args[0])
args = [f'"{x}"' if " " in x ... | [
"traceback.print_exc",
"os.path.basename",
"shlex.split",
"string.Template",
"sys.exit"
] | [((261, 286), 'os.path.basename', 'os.path.basename', (['args[0]'], {}), '(args[0])\n', (277, 286), False, 'import os\n'), ((481, 510), 'os.path.basename', 'os.path.basename', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (497, 510), False, 'import os\n'), ((2385, 2401), 'sys.exit', 'sys.exit', (['result'], {}), '(result)\... |
import filecmp
folderpath = 'D:/miscellaneous_icons/'
for x in range(1, 108):
for y in range(x + 1, 108):
filename1 = str(x) + '.txt'
filename2 = str(y) + '.txt'
filepath1 = folderpath + filename1
filepath2 = folderpath + filename2
isIdentical = filecmp.cmp(filepath1, filepath2)
if isIdentical =... | [
"filecmp.cmp"
] | [((265, 298), 'filecmp.cmp', 'filecmp.cmp', (['filepath1', 'filepath2'], {}), '(filepath1, filepath2)\n', (276, 298), False, 'import filecmp\n')] |
#!/usr/bin/env python
import asyncio
import logging
import time
from decimal import Decimal
from typing import AsyncIterable, Dict, List, Optional
import pandas as pd
from hummingbot.connector.exchange.coinbase_pro import coinbase_pro_constants as CONSTANTS
from hummingbot.connector.exchange.coinbase_pro.coinbase_pr... | [
"hummingbot.core.utils.async_utils.safe_gather",
"hummingbot.connector.exchange.coinbase_pro.coinbase_pro_order_book_tracker_entry.CoinbaseProOrderBookTrackerEntry",
"hummingbot.connector.exchange.coinbase_pro.coinbase_pro_utils.CoinbaseProRESTRequest",
"asyncio.sleep",
"decimal.Decimal",
"pandas.Timestam... | [((2754, 2796), 'hummingbot.connector.exchange.coinbase_pro.coinbase_pro_utils.build_coinbase_pro_web_assistant_factory', 'build_coinbase_pro_web_assistant_factory', ([], {}), '()\n', (2794, 2796), False, 'from hummingbot.connector.exchange.coinbase_pro.coinbase_pro_utils import CoinbaseProRESTRequest, build_coinbase_p... |
import os
import numpy as np
import torch
import gym
from ..data import ReplayBuffer
from .base import Trainer
class OffPolicyTrainer(Trainer):
"""
A wrap of off-policy training procedure.
Off-policy agents: DQN (and its variants), DDPG, TD3, SAC
Parameters
----------
agent: Agent
A... | [
"torch.no_grad"
] | [((2716, 2731), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2729, 2731), False, 'import torch\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as distributions
from .dcgan import DCGANGenerator, DCGANDiscriminator
__all__ = ['InfoGANGenerator', 'InfoGANDiscriminator']
class InfoGANGenerator(DCGANGenerator):
r"""Generator for InfoGAN based on the Deep Convolutio... | [
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.BatchNorm2d",
"torch.nn.Linear",
"torch.nn.LeakyReLU"
] | [((6103, 6129), 'torch.nn.Linear', 'nn.Linear', (['d', 'self.dim_dis'], {}), '(d, self.dim_dis)\n', (6112, 6129), True, 'import torch.nn as nn\n'), ((6156, 6183), 'torch.nn.Linear', 'nn.Linear', (['d', 'self.dim_cont'], {}), '(d, self.dim_cont)\n', (6165, 6183), True, 'import torch.nn as nn\n'), ((6211, 6238), 'torch.n... |
import tkSimpleDialog
import tkMessageBox
import Tkinter
import ProgressBarView
import ScrolledText
import logging
import ThreadsConnector
import Queue
import gettext
import sys
import scpp_switch
from twisted.internet import reactor
_ = gettext.gettext
class ActionWindow(tkSimpleDialog.Dialog):
def __init__(se... | [
"tkSimpleDialog.Dialog.wait_window",
"tkSimpleDialog.Dialog.__init__",
"ScrolledText.ScrolledText",
"Tkinter.Label",
"sys.exit",
"logging.getLogger",
"tkSimpleDialog.Dialog.buttonbox",
"tkSimpleDialog.Dialog.ok",
"tkSimpleDialog.Dialog.destroy",
"tkSimpleDialog.Dialog.cancel",
"scpp_switch.stop_... | [((651, 693), 'logging.getLogger', 'logging.getLogger', (['self.__class__.__name__'], {}), '(self.__class__.__name__)\n', (668, 693), False, 'import logging\n'), ((995, 1062), 'tkSimpleDialog.Dialog.__init__', 'tkSimpleDialog.Dialog.__init__', (['self', 'self.aw_parent', 'self.aw_title'], {}), '(self, self.aw_parent, s... |
import asyncio
import threading
from utils import createID
class StoppableThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
... | [
"utils.createID",
"threading.Event"
] | [((242, 259), 'threading.Event', 'threading.Event', ([], {}), '()\n', (257, 259), False, 'import threading\n'), ((494, 506), 'utils.createID', 'createID', (['(12)'], {}), '(12)\n', (502, 506), False, 'from utils import createID\n')] |
"""
Lambda function to validate status of EMR cluster post launch
"""
import json
from src.util.log import setup_logging
from src.util.emrlib import get_emr_cluster_status, get_cluster_id, get_cluster_metadata
from src.util.emrlib import get_cluster_name, delete_security_group, empty_sg_rules, get_network_interface_a... | [
"src.util.exceptions.EMRClusterValidationException",
"src.util.commlib.construct_error_response",
"src.util.log.setup_logging",
"src.util.emrlib.get_emr_cluster_status",
"src.util.emrlib.empty_sg_rules",
"src.util.emrlib.get_cluster_metadata",
"src.util.emrlib.get_cluster_name",
"src.util.emrlib.get_n... | [((649, 702), 'src.util.log.setup_logging', 'setup_logging', (['api_request_id', 'context.aws_request_id'], {}), '(api_request_id, context.aws_request_id)\n', (662, 702), False, 'from src.util.log import setup_logging\n'), ((1546, 1593), 'src.util.emrlib.get_emr_cluster_status', 'get_emr_cluster_status', (['cluster_id'... |
# coding: utf-8
import socketserver
import os
# Copyright 2013 <NAME>, <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
#
# Unle... | [
"os.path.abspath",
"os.path.isdir",
"os.getcwd",
"os.path.exists",
"socketserver.TCPServer"
] | [((3194, 3243), 'socketserver.TCPServer', 'socketserver.TCPServer', (['(HOST, PORT)', 'MyWebServer'], {}), '((HOST, PORT), MyWebServer)\n', (3216, 3243), False, 'import socketserver\n'), ((1251, 1290), 'os.path.abspath', 'os.path.abspath', (['(root_path + request[1])'], {}), '(root_path + request[1])\n', (1266, 1290), ... |
from django.db import models
class VIP_User(models.Model):
name = models.CharField(max_length=10, verbose_name='名稱', default='')
line_id = models.CharField(max_length=60, verbose_name='line_id', default='')
actived = models.BooleanField(verbose_name='啟用', default=False)
class Meta:
ordering = ... | [
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((71, 133), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'verbose_name': '"""名稱"""', 'default': '""""""'}), "(max_length=10, verbose_name='名稱', default='')\n", (87, 133), False, 'from django.db import models\n'), ((148, 215), 'django.db.models.CharField', 'models.CharField', ([], {'max... |
import pybullet as p
import time
import pybullet_data
import pathlib
import debugvisualizer
physicsClient = p.connect(p.GUI)
p.setAdditionalSearchPath(str(pathlib.Path(__file__).parent.absolute()) + "/simple_pig")
p.setGravity(0,0,0)
planeId = p.loadURDF("plane.urdf")
dt = 1./60.
p.setTimeStep(dt)
lastCameraDistanc... | [
"pybullet.stepSimulation",
"pybullet.setGravity",
"pybullet.getBasePositionAndOrientation",
"time.time",
"time.sleep",
"pybullet.removeBody",
"pathlib.Path",
"pybullet.setTimeStep",
"pybullet.getDebugVisualizerCamera",
"pybullet.connect",
"debugvisualizer.object_is_in_frame",
"pybullet.loadURD... | [((109, 125), 'pybullet.connect', 'p.connect', (['p.GUI'], {}), '(p.GUI)\n', (118, 125), True, 'import pybullet as p\n'), ((216, 237), 'pybullet.setGravity', 'p.setGravity', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (228, 237), True, 'import pybullet as p\n'), ((246, 270), 'pybullet.loadURDF', 'p.loadURDF', (['"""pla... |
import numpy as np
class Network:
def __init__(self):
self.L1 = Layer(layer_width=2, input_width=1, bias=[0, -1])
def forward(self, x):
x = self.L1.forward(x)
return np.sum(x)
def update_weights(self, adj):
self.L1.update_weights(adj)
class Layer:
def __init__(self,... | [
"numpy.zeros",
"numpy.random.uniform",
"numpy.sum",
"numpy.array"
] | [((201, 210), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (207, 210), True, 'import numpy as np\n'), ((1019, 1055), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'input_shape'], {}), '(0, 1, input_shape)\n', (1036, 1055), True, 'import numpy as np\n'), ((407, 428), 'numpy.zeros', 'np.zeros', (['layer_wi... |
# Solve the given maze, using DFS, for passed initial and final endpoints,
# or default - initial: top-left cell, final: bottom-right cell
from copy import deepcopy
# Reset the cells' prefixes to a new_prefix, for code reuse
def resetPrefix(maze_obj, new_prefix):
maze = maze_obj.maze
dim = maze_obj.... | [
"copy.deepcopy"
] | [((670, 688), 'copy.deepcopy', 'deepcopy', (['maze_obj'], {}), '(maze_obj)\n', (678, 688), False, 'from copy import deepcopy\n')] |
import datetime
from django.test import TestCase
from django.test.client import Client
from django.core.management import call_command
from django.test.utils import override_settings
import haystack
from visitors.models import Visitor
TEST_INDEX = {
'default': {
'ENGINE': 'haystack.backends.elasticsearc... | [
"datetime.date",
"haystack.connections.reload",
"visitors.models.Visitor.objects.bulk_create",
"django.test.client.Client",
"django.core.management.call_command",
"django.test.utils.override_settings"
] | [((781, 831), 'django.test.utils.override_settings', 'override_settings', ([], {'HAYSTACK_CONNECTIONS': 'TEST_INDEX'}), '(HAYSTACK_CONNECTIONS=TEST_INDEX)\n', (798, 831), False, 'from django.test.utils import override_settings\n'), ((902, 910), 'django.test.client.Client', 'Client', ([], {}), '()\n', (908, 910), False,... |
from PIL import Image
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy
matrix=[]
for i in range(85):
matrix.append([])
for j in range(85):
matrix[i].append([])
for k in range(85):
matrix[i][j].append(0)
im = Image.open('detect.jpg')
im = im.conve... | [
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"PIL.Image.open"
] | [((282, 306), 'PIL.Image.open', 'Image.open', (['"""detect.jpg"""'], {}), "('detect.jpg')\n", (292, 306), False, 'from PIL import Image\n'), ((1616, 1626), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1624, 1626), True, 'import matplotlib.pyplot as plt\n'), ((1689, 1701), 'matplotlib.pyplot.figure', 'plt.fi... |
import psycopg2
dbname = 'project'
host = 'localhost'
user = 'postgres'
password = '<PASSWORD>' #postgres on laptop, root on desktop
conn = psycopg2.connect(host=host, dbname = dbname, user = user, password = password)
cursor = conn.cursor()
command = '''
insert into Options values ('8001', 'blue','V6','manua... | [
"psycopg2.connect"
] | [((143, 215), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': 'host', 'dbname': 'dbname', 'user': 'user', 'password': 'password'}), '(host=host, dbname=dbname, user=user, password=password)\n', (159, 215), False, 'import psycopg2\n')] |
# Example Case 1 - Fig. 9 (Fredlund & Krahn, 1977)
from pybimstab.slope import AnthropicSlope
from pybimstab.slipsurface import CircularSurface
from pybimstab.slices import MaterialParameters, Slices
from pybimstab.slopestabl import SlopeStabl
slope = AnthropicSlope(slopeHeight=40, slopeDip=[2, 1],
... | [
"pybimstab.slopestabl.SlopeStabl",
"pybimstab.slipsurface.CircularSurface",
"pybimstab.slices.MaterialParameters",
"pybimstab.slices.Slices",
"pybimstab.slope.AnthropicSlope"
] | [((252, 339), 'pybimstab.slope.AnthropicSlope', 'AnthropicSlope', ([], {'slopeHeight': '(40)', 'slopeDip': '[2, 1]', 'crownDist': '(60)', 'toeDist': '(30)', 'depth': '(20)'}), '(slopeHeight=40, slopeDip=[2, 1], crownDist=60, toeDist=30,\n depth=20)\n', (266, 339), False, 'from pybimstab.slope import AnthropicSlope\n... |
# This sample demonstrates invoking the McAfee Threat Intelligence Exchange (TIE)
# DXL service to retrieve the reputation of a file and certificate (as identified
# by their hashes). Further, this example demonstrates using the constants classes
# to examine specific fields within the reputation responses.
from __fut... | [
"os.path.abspath",
"dxlclient.client.DxlClient",
"dxlbootstrap.util.MessageUtils.dict_to_json",
"dxlclient.client_config.DxlClientConfig.create_dxl_config_from_file",
"dxltieclient.constants.FileEnterpriseAttrib.to_localtime_string",
"dxltieclient.constants.CertEnterpriseAttrib.to_localtime_string",
"dx... | [((1002, 1058), 'dxlclient.client_config.DxlClientConfig.create_dxl_config_from_file', 'DxlClientConfig.create_dxl_config_from_file', (['CONFIG_FILE'], {}), '(CONFIG_FILE)\n', (1045, 1058), False, 'from dxlclient.client_config import DxlClientConfig\n'), ((1711, 1728), 'dxlclient.client.DxlClient', 'DxlClient', (['conf... |
import pytest
from chords.request import Request
from .conftest import DummyResource, DummyPool
from chords.exceptions import UnsatisfiableRequestError
from chords.pool import RandomPool, WeightedRandomPool
@pytest.fixture
def pool():
return DummyPool(int)
def test_add(pool):
length = len(pool.all())... | [
"chords.request.Request",
"pytest.raises",
"pytest.mark.parametrize",
"chords.pool.WeightedRandomPool",
"chords.pool.RandomPool"
] | [((1057, 1108), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""exclusive"""', '[False, True]'], {}), "('exclusive', [False, True])\n", (1080, 1108), False, 'import pytest\n'), ((1164, 1210), 'chords.request.Request', 'Request', (['int'], {'exclusive': 'exclusive', 'max_value': '(1)'}), '(int, exclusive=exc... |
# download data from here: https://press.liacs.nl/mirflickr/mirdownload.html
# import hashlib
# with open("mirflickr25k.zip","rb") as f:
# md5_obj = hashlib.md5()
# md5_obj.update(f.read())
# hash_code = md5_obj.hexdigest()
# print(str(hash_code).upper() == "A23D0A8564EE84CDA5622A6C2F947785")
import o... | [
"numpy.random.permutation",
"numpy.zeros",
"os.listdir",
"os.path.join"
] | [((359, 395), 'numpy.zeros', 'np.zeros', (['(25000, 38)'], {'dtype': 'np.int8'}), '((25000, 38), dtype=np.int8)\n', (367, 395), True, 'import numpy as np\n'), ((480, 506), 'os.listdir', 'os.listdir', (['label_dir_name'], {}), '(label_dir_name)\n', (490, 506), False, 'import os\n'), ((796, 842), 'numpy.random.permutatio... |
import sys, pygame
from player import Player
from vector2 import *
from random import randint, uniform
from math import sin, cos, floor
worldseed = uniform(-65536, 65535)
size = scrwidth, scrheight = 1100, 700
speed = [2, 2]
black = 0, 0, 0
circlepos = [scrwidth / 2, scrheight / 2]
screen = pygame.display.set_mode(siz... | [
"random.randint",
"random.uniform",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"player.Player",
"math.floor",
"pygame.init",
"math.sin",
"pygame.display.flip",
"math.cos",
"pygame.image.load",
"pygame.key.get_pressed",
"sys.exit"
] | [((149, 171), 'random.uniform', 'uniform', (['(-65536)', '(65535)'], {}), '(-65536, 65535)\n', (156, 171), False, 'from random import randint, uniform\n'), ((293, 322), 'pygame.display.set_mode', 'pygame.display.set_mode', (['size'], {}), '(size)\n', (316, 322), False, 'import sys, pygame\n'), ((333, 386), 'pygame.disp... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 01:03:24 2021
@author: Mahfuz_Shazol
"""
import numpy as np
X=np.array([
[4,2],
[-5,-3]
])
result =np.linalg.det(X)
print(result)
N=np.array([
[-4,1],
[-8,2]
])
result =np.linalg.det(N)
print(result) | [
"numpy.linalg.det",
"numpy.array"
] | [((115, 143), 'numpy.array', 'np.array', (['[[4, 2], [-5, -3]]'], {}), '([[4, 2], [-5, -3]])\n', (123, 143), True, 'import numpy as np\n'), ((165, 181), 'numpy.linalg.det', 'np.linalg.det', (['X'], {}), '(X)\n', (178, 181), True, 'import numpy as np\n'), ((201, 229), 'numpy.array', 'np.array', (['[[-4, 1], [-8, 2]]'], ... |
from tree_node import TreeLinkNode
# Populating Next Right Pointers in Each Node II
# use only constant space
# in problem I, assume it's a perfect tree (all leaves are at the same level, and every parent has two children)
# in problem II, no longer assume it's a perfect tree
# Idea: build the next relationship in th... | [
"tree_node.TreeLinkNode"
] | [((437, 452), 'tree_node.TreeLinkNode', 'TreeLinkNode', (['(0)'], {}), '(0)\n', (449, 452), False, 'from tree_node import TreeLinkNode\n')] |
import unittest
import os
class TestCase(unittest.TestCase):
ROOT_DIR = os.path.realpath(os.path.join(__file__, '..', '..'))
def add_patch(self, patch):
patch.start()
self.patches.append(patch)
def setUp(self):
self.patches = []
def tearDown(self):
for p in self.patch... | [
"os.path.join"
] | [((94, 128), 'os.path.join', 'os.path.join', (['__file__', '""".."""', '""".."""'], {}), "(__file__, '..', '..')\n", (106, 128), False, 'import os\n')] |
import sys
import re
from collections import defaultdict
line_re = re.compile('^Step (.+) must.*step (.+) can begin.$')
def get_starting_nodes(ins):
for node, in_count in ins.items():
if in_count == 0:
yield node
def solve(lines):
nodes = defaultdict(list)
ins = defaultdict(int)
... | [
"collections.defaultdict",
"re.compile"
] | [((68, 120), 're.compile', 're.compile', (['"""^Step (.+) must.*step (.+) can begin.$"""'], {}), "('^Step (.+) must.*step (.+) can begin.$')\n", (78, 120), False, 'import re\n'), ((272, 289), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (283, 289), False, 'from collections import defaultdict\n'... |
# Generated by Django 3.1.14 on 2022-03-08 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("polio", "0044_merge_20220224_1136"),
]
operations = [
migrations.AlterField(
model_name="campaign",
name="virus",
... | [
"django.db.models.CharField"
] | [((337, 497), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[('PV1', 'PV1'), ('PV2', 'PV2'), ('PV3', 'PV3'), ('cVDPV2', 'cVDPV2'), (\n 'WPV1', 'WPV1')]", 'max_length': '(6)', 'null': '(True)'}), "(blank=True, choices=[('PV1', 'PV1'), ('PV2', 'PV2'), (\n 'PV3', 'PV3'), ('cV... |
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('发布日期')
def __str__(self):
question = {
'id': self.id,
'text': self.que... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.utils.timezone.now",
"django.db.models.IntegerField",
"datetime.timedelta",
"django.db.models.DateTimeField"
] | [((137, 169), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (153, 169), False, 'from django.db import models\n'), ((186, 214), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""发布日期"""'], {}), "('发布日期')\n", (206, 214), False, 'from django.db import ... |
from django.db.models.query import QuerySet
from django.test import TestCase
from waldur_core.core import WaldurExtension
class ViewsetsTest(TestCase):
def test_default_ordering_must_be_defined_for_all_viewsets(self):
for ext in WaldurExtension.get_extensions():
try:
views = ... | [
"waldur_core.core.WaldurExtension.get_extensions"
] | [((244, 276), 'waldur_core.core.WaldurExtension.get_extensions', 'WaldurExtension.get_extensions', ([], {}), '()\n', (274, 276), False, 'from waldur_core.core import WaldurExtension\n')] |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch import optim
import numpy as np
class CoarseNetwork(nn.Module):
def __init__(self):
super(CoarseNetwork, self).__init__()
self.coarse1 = nn.Sequential(
nn.Conv2d(3, 96, 11, ... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.Linear",
"torch.nn.MaxPool2d"
] | [((1960, 1996), 'torch.cat', 'torch.cat', (['(x, coarse_output)'], {'dim': '(1)'}), '((x, coarse_output), dim=1)\n', (1969, 1996), False, 'import torch\n'), ((299, 322), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(96)', '(11)', '(4)'], {}), '(3, 96, 11, 4)\n', (308, 322), True, 'import torch.nn as nn\n'), ((336, 345), '... |
import json
import os
def get_fixture(filename):
path = os.path.dirname(os.path.dirname(__file__))
with open(path + "/tests/fixtures/{}.json".format(filename)) as json_file:
data = json.load(json_file)
return data
| [
"os.path.dirname",
"json.load"
] | [((78, 103), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (93, 103), False, 'import os\n'), ((200, 220), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (209, 220), False, 'import json\n')] |
"""
https://circuitdigest.com/microcontroller-projects/license-plate-recognition-using-raspberry-pi-and-opencv
"""
import logging
import typing as t
import imutils
import numpy as np
import pytesseract
from cv2 import cv2
from car_plate_recognizer.handlers.base import BaseHandler, Plate, save_img
logger = logging.g... | [
"cv2.cv2.Canny",
"cv2.cv2.arcLength",
"cv2.cv2.drawContours",
"cv2.cv2.bitwise_and",
"cv2.cv2.bilateralFilter",
"numpy.zeros",
"cv2.cv2.findContours",
"cv2.cv2.resize",
"pytesseract.image_to_string",
"cv2.cv2.approxPolyDP",
"numpy.min",
"numpy.where",
"numpy.max",
"imutils.grab_contours",
... | [((311, 338), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (328, 338), False, 'import logging\n'), ((1650, 1689), 'cv2.cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1662, 1689), False, 'from cv2 import cv2\n'), ((1726, 1763), 'cv... |