code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from flask import Blueprint, jsonify, redirect, request
import pydantic
from conda_store_server import api, schema, utils
from conda_store_server.server.utils import get_conda_store, get_auth
from conda_store_server.server.auth import Permissions
app_api = Blueprint("api", __name__)
@app_api.route("/api/v1/")
def ... | [
"conda_store_server.api.list_conda_channels",
"conda_store_server.api.get_build",
"conda_store_server.api.get_environment",
"conda_store_server.api.list_conda_packages",
"conda_store_server.schema.CondaPackage.from_orm",
"conda_store_server.schema.Environment.from_orm",
"conda_store_server.schema.Build.... | [((260, 286), 'flask.Blueprint', 'Blueprint', (['"""api"""', '__name__'], {}), "('api', __name__)\n", (269, 286), False, 'from flask import Blueprint, jsonify, redirect, request\n'), ((345, 370), 'flask.jsonify', 'jsonify', (["{'status': 'ok'}"], {}), "({'status': 'ok'})\n", (352, 370), False, 'from flask import Bluepr... |
import pandas as pd
import numpy as numpy
from env import host, user, password
import os
from sklearn.model_selection import train_test_split
import sklearn.preprocessing
############################# Acquire Zillow #############################
# defines function to create a sql url using personal credentials... | [
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"os.path.isfile"
] | [((5683, 5736), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': '(0.2)', 'random_state': '(123)'}), '(df, test_size=0.2, random_state=123)\n', (5699, 5736), False, 'from sklearn.model_selection import train_test_split\n'), ((5758, 5823), 'sklearn.model_selection.train_test_split',... |
from blueqat import Circuit, ParametrizedCircuit
def compare_circuit(c1: Circuit, c2: Circuit) -> bool:
return repr(c1) == repr(c2)
def test_parametrized1():
assert compare_circuit(
ParametrizedCircuit().ry('a')[0].rz('b')[0].subs([1.2, 3.4]),
Circuit().ry(1.2)[0].rz(3.4)[0])
def test_parame... | [
"blueqat.ParametrizedCircuit",
"blueqat.Circuit"
] | [((584, 593), 'blueqat.Circuit', 'Circuit', ([], {}), '()\n', (591, 593), False, 'from blueqat import Circuit, ParametrizedCircuit\n'), ((544, 565), 'blueqat.ParametrizedCircuit', 'ParametrizedCircuit', ([], {}), '()\n', (563, 565), False, 'from blueqat import Circuit, ParametrizedCircuit\n'), ((270, 279), 'blueqat.Cir... |
import json
class ConfigObject(dict):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.load_attributes(kwargs)
def load_attributes(self, d):
for k, v in d.items():
if isinstance(v, dict):
self[k] = self.__class__(**v)
elif isinstan... | [
"json.dumps"
] | [((840, 886), 'json.dumps', 'json.dumps', (['self'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(self, indent=4, ensure_ascii=False)\n', (850, 886), False, 'import json\n')] |
import math
import pylab
from app import StandardRobot, LeastDistanceRobot, RandomWalkRobot, runSimulation
def timeNumberPlot(title, x_label, y_label, dim_length):
"""
Plots the relation between the number of robots and the average time
taken by different robots to clean a portion of the room.
"""
... | [
"pylab.title",
"pylab.scatter",
"app.runSimulation",
"pylab.plot",
"pylab.xlabel",
"pylab.legend",
"math.sqrt",
"pylab.ylabel",
"pylab.show"
] | [((833, 905), 'pylab.title', 'pylab.title', (['(title + f"""\n for room size of {dim_length}x{dim_length}""")'], {}), '(title + f"""\n for room size of {dim_length}x{dim_length}""")\n', (844, 905), False, 'import pylab\n'), ((905, 977), 'pylab.legend', 'pylab.legend', (["('StandardRobot', 'LeastDistanceRobot', 'RandomW... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from openvino.inference_engine import IECore
import openvino_model_experiment_package as omep
# Load an IR model
model = 'intel/human-pose-estimation-0001/FP16/human-pose-estimation-0001'
ie, net, exenet, inblobs, outblobs, inshapes, outshapes = omep.loa... | [
"matplotlib.pyplot.imshow",
"openvino_model_experiment_package.load_IR_model",
"openvino_model_experiment_package.display_heatmap",
"openvino_model_experiment_package.infer_ocv_image",
"cv2.cvtColor",
"cv2.imread",
"matplotlib.pyplot.show"
] | [((312, 337), 'openvino_model_experiment_package.load_IR_model', 'omep.load_IR_model', (['model'], {}), '(model)\n', (330, 337), True, 'import openvino_model_experiment_package as omep\n'), ((384, 408), 'cv2.imread', 'cv2.imread', (['"""people.jpg"""'], {}), "('people.jpg')\n", (394, 408), False, 'import cv2\n'), ((415... |
import large_image
import urllib
import pytest
@pytest.mark.parametrize("item, output", [
('590346ff8d777f16d01e054c', '/tmp/Huron.Image2_JPEG2K.tif')
])
def test_tiff_tile_source(item, output):
"""Check whether large_image can return a tile with tiff sources."""
test_url = 'https://data.kitware.com/api/v... | [
"urllib.urlretrieve",
"pytest.mark.parametrize",
"large_image.getTileSource"
] | [((50, 157), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""item, output"""', "[('590346ff8d777f16d01e054c', '/tmp/Huron.Image2_JPEG2K.tif')]"], {}), "('item, output', [('590346ff8d777f16d01e054c',\n '/tmp/Huron.Image2_JPEG2K.tif')])\n", (73, 157), False, 'import pytest\n'), ((357, 393), 'urllib.urlretr... |
import os
import sys
import pickle
import traceback
from XSTAF.core.logger import LOGGER
class ToolManager(object):
def __init__(self):
self.settings = {"ToolsLocation" : r"tools",
"ToolsConfigureFile" : "config.pickle"}
self.tool_name_list = []
... | [
"traceback.format_exc",
"os.listdir",
"pickle.dump",
"os.path.isabs",
"XSTAF.core.logger.LOGGER.info",
"os.path.join",
"pickle.load",
"os.path.isfile",
"os.path.isdir",
"os.path.abspath",
"sys.path.append",
"XSTAF.core.logger.LOGGER.warning"
] | [((1045, 1119), 'os.path.join', 'os.path.join', (['self.abs_tools_location', "self.settings['ToolsConfigureFile']"], {}), "(self.abs_tools_location, self.settings['ToolsConfigureFile'])\n", (1057, 1119), False, 'import os\n'), ((1453, 1493), 'sys.path.append', 'sys.path.append', (['self.abs_tools_location'], {}), '(sel... |
"""
One-time migration script from sqlalchemy models and sqlite database to custom ORM & PostgreSQL.
Not designed to work as part of the regular alembic system, merely placed here for archive purposes.
Should never need to run this again.
2021-05-03
"""
from datetime import datetime, timedelta
import sqlite3
from d... | [
"data.snapshot_data.SnapshotFrontpageModel",
"sqlite3.connect",
"data.user_data.UserData",
"datetime.datetime.utcnow",
"data.post_data.PostModel",
"utils.reddit.base36decode",
"data.post_data.PostData",
"utils.logger.logger.info",
"data.snapshot_data.SnapshotModel",
"datetime.datetime.fromisoforma... | [((599, 609), 'data.post_data.PostData', 'PostData', ([], {}), '()\n', (607, 609), False, 'from data.post_data import PostData, PostModel\n'), ((627, 641), 'data.snapshot_data.SnapshotData', 'SnapshotData', ([], {}), '()\n', (639, 641), False, 'from data.snapshot_data import SnapshotData, SnapshotModel, SnapshotFrontpa... |
from mfl_playoff_leagues import MFL
def run(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.poco... | [
"mfl_playoff_leagues.MFL"
] | [((503, 548), 'mfl_playoff_leagues.MFL', 'MFL', ([], {'year': "args['year']", 'league': "args['league']"}), "(year=args['year'], league=args['league'])\n", (506, 548), False, 'from mfl_playoff_leagues import MFL\n')] |
from pyObjective import Variable, Model
import numpy as np
"""This example script is written to demonstrate the use of classes, and how more complicated models can be built,
and still passed to the solver. As a rudimentary example, it has two cubes and a sphere, and we are trying to find
the dimensions such that the... | [
"pyObjective.Model",
"pyObjective.Variable"
] | [((1077, 1084), 'pyObjective.Model', 'Model', ([], {}), '()\n', (1082, 1084), False, 'from pyObjective import Variable, Model\n'), ((1158, 1201), 'pyObjective.Variable', 'Variable', (['"""r"""', '(1)', '(0.5, 2)', '"""sphere radius"""'], {}), "('r', 1, (0.5, 2), 'sphere radius')\n", (1166, 1201), False, 'from pyObjecti... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either ... | [
"pytest.fixture",
"telegram.InlineQueryResultVoice",
"telegram.InlineQueryResultGame",
"telegram.InlineKeyboardButton"
] | [((925, 954), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (939, 954), False, 'import pytest\n'), ((998, 1154), 'telegram.InlineQueryResultGame', 'InlineQueryResultGame', (['TestInlineQueryResultGame.id', 'TestInlineQueryResultGame.game_short_name'], {'reply_markup': 'TestInl... |
import pygame as pg
class Sheet:
"""
Represents tool for extracting sprites from spritesheet.
"""
def __init__(self, sheet_path):
"""
Constructor for the sheet tool.
Loading the spritesheet.
"""
self.spritesheet = pg.image.load(sheet_path).convert_alpha()
d... | [
"pygame.image.load",
"pygame.Surface"
] | [((582, 609), 'pygame.Surface', 'pg.Surface', (['(width, height)'], {}), '((width, height))\n', (592, 609), True, 'import pygame as pg\n'), ((272, 297), 'pygame.image.load', 'pg.image.load', (['sheet_path'], {}), '(sheet_path)\n', (285, 297), True, 'import pygame as pg\n')] |
from config import secret
from utils import getLogger
DEBUG = getLogger()
class MysqlConnection:
def __init__(self, database, server_name):
self.host = secret[server_name]['mysql']['host']
self.port = secret[server_name]['mysql']['port']
self.username = secret[server_name]['mysql']['username']
self... | [
"utils.getLogger"
] | [((62, 73), 'utils.getLogger', 'getLogger', ([], {}), '()\n', (71, 73), False, 'from utils import getLogger\n')] |
#from selenium.webdriver.remote import webdriver
from selenium import webdriver
#from selenium.webdriver.chrome import options
from page_objects import EntryPage, LoginPage, RedactionPage, ContactTracePage, AddNewRecordPage, AddDataToRecordPage, StageForPublishingPage, PublishDataPage, SettingsPage, Tools
import unitte... | [
"selenium.webdriver.Remote",
"selenium.webdriver.ChromeOptions",
"page_objects.SettingsPage",
"page_objects.EntryPage",
"selenium.webdriver.Chrome",
"page_objects.RedactionPage",
"os.environ.copy",
"page_objects.Tools",
"os.getcwd",
"page_objects.AddNewRecordPage",
"page_objects.LoginPage",
"p... | [((1398, 1423), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (1421, 1423), False, 'from selenium import webdriver\n'), ((1798, 1805), 'page_objects.Tools', 'Tools', ([], {}), '()\n', (1803, 1805), False, 'from page_objects import EntryPage, LoginPage, RedactionPage, ContactTracePage,... |
import unittest
import os
from subprocess import call
import z5py
import vigra
from test_class import McLuigiTestCase
class TestDataTasks(McLuigiTestCase):
@classmethod
def setUpClass(cls):
super(TestDataTasks, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestDataTa... | [
"os.path.exists",
"vigra.readHDF5",
"z5py.File",
"subprocess.call",
"unittest.main"
] | [((1069, 1084), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1082, 1084), False, 'import unittest\n'), ((537, 578), 'vigra.readHDF5', 'vigra.readHDF5', (['rag_path', '"""numberOfEdges"""'], {}), "(rag_path, 'numberOfEdges')\n", (551, 578), False, 'import vigra\n'), ((918, 973), 'subprocess.call', 'call', (["['p... |
# Generated by Django 3.0.8 on 2020-07-13 19:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("images", "0003_image_creation_date"),
]
operations = [
migrations.AddField(
model_name="image",... | [
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.FileField",
"django.db.models.BooleanField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((364, 422), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'verbose_name': '"""In feed"""'}), "(default=False, verbose_name='In feed')\n", (383, 422), False, 'from django.db import migrations, models\n'), ((550, 619), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], ... |
import numba
import numpy as np
from scipy.sparse import csr_matrix
from .base import BasePointer, GraphBlasContainer
from .context import handle_panic, return_error
from .exceptions import GrB_Info
class MatrixPtr(BasePointer):
def set_matrix(self, matrix):
self.instance = matrix
class Matrix(GraphBlas... | [
"scipy.sparse.csr_matrix",
"numpy.empty"
] | [((2755, 2796), 'numpy.empty', 'np.empty', (['(tmp_output_size,)'], {'dtype': 'dtype'}), '((tmp_output_size,), dtype=dtype)\n', (2763, 2796), True, 'import numpy as np\n'), ((2811, 2862), 'numpy.empty', 'np.empty', (['(tmp_output_size,)'], {'dtype': 'a_indices.dtype'}), '((tmp_output_size,), dtype=a_indices.dtype)\n', ... |
import json
import os
import shutil
import tempfile
from datetime import timedelta
from unittest import mock
from unittest import TestCase
from pytuber.storage import Registry
class RegistryTests(TestCase):
def tearDown(self):
Registry.clear()
Registry._obj = {}
def test_singleton(self):
... | [
"pytuber.storage.Registry.from_file",
"pytuber.storage.Registry.clear",
"os.path.join",
"pytuber.storage.Registry.get",
"pytuber.storage.Registry.set",
"pytuber.storage.Registry.persist",
"tempfile.mkdtemp",
"pytuber.storage.Registry",
"shutil.rmtree",
"datetime.timedelta",
"unittest.mock.patch"... | [((2027, 2066), 'unittest.mock.patch', 'mock.patch', (['"""pytuber.storage.time.time"""'], {}), "('pytuber.storage.time.time')\n", (2037, 2066), False, 'from unittest import mock\n'), ((242, 258), 'pytuber.storage.Registry.clear', 'Registry.clear', ([], {}), '()\n', (256, 258), False, 'from pytuber.storage import Regis... |
# -*- coding: utf-8 -*-
"""
file: module_topology_distmat_test.py
Unit tests for distance matrix computations
"""
import os
from pandas import DataFrame
from interact.md_system import System
from tests.module.unittest_baseclass import UnittestPythonCompatibility
class DistanceMatrixTests(UnittestPythonCompatibil... | [
"interact.md_system.System",
"os.path.dirname",
"os.path.join"
] | [((341, 366), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (356, 366), False, 'import os\n'), ((398, 441), 'os.path.join', 'os.path.join', (['currpath', '"""../files/1acj.pdb"""'], {}), "(currpath, '../files/1acj.pdb')\n", (410, 441), False, 'import os\n'), ((474, 518), 'os.path.join', 'os.... |
import typing
import bs4
import requests
class ScrapeAllComicIds():
def __call__(
self,
) -> typing.List[int]:
self.__find()
return self.__ids
def __find(
self,
) -> typing.NoReturn:
self.__ids = []
for q in self.__query:
self.__find_per_page(q)
def __find_per_page(
... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((385, 426), 'requests.get', 'requests.get', (['f"""{self.__base_url}{query}"""'], {}), "(f'{self.__base_url}{query}')\n", (397, 426), False, 'import requests\n'), ((461, 511), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['response.content', '"""html.parser"""'], {}), "(response.content, 'html.parser')\n", (478, 511), ... |
"""
Path Converter.
pymdownx.pathconverter
An extension for Python Markdown.
An extension to covert tag paths to relative or absolute:
Given an absolute base and a target relative path, this extension searches for file
references that are relative and converts them to a path relative
to the base path.
-or-
Given a... | [
"os.path.normpath",
"urllib.parse.urlunparse",
"os.path.join",
"re.compile"
] | [((2003, 2170), 're.compile', 're.compile', (['"""(?xus)\n (?P<attr>\n (?:\n (?P<name>\\\\s+(?:href|src)\\\\s*=\\\\s*)\n (?P<path>"[^"]*"|\'[^\']*\')\n )\n )\n """'], {}), '(\n """(?xus)\n (?P<attr>\n (?:\n (?P<name>\\\\s+(?:href|src)\\\\s*=\\\\s*)\n ... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import logging
from collections import defaultdict
from itertools import chain
from torch.nn.utils import clip_grad
from mmcv.utils import TORCH_VERSION, _BatchNorm, digit_version
# from ..dist_utils import allreduce_grads
# from ..fp16_utils import LossScal... | [
"torch.nn.utils.clip_grad.clip_grad_norm_",
"mmcv.runner.hooks.HOOKS.register_module"
] | [((612, 635), 'mmcv.runner.hooks.HOOKS.register_module', 'HOOKS.register_module', ([], {}), '()\n', (633, 635), False, 'from mmcv.runner.hooks import HOOKS, Hook\n'), ((1670, 1721), 'torch.nn.utils.clip_grad.clip_grad_norm_', 'clip_grad.clip_grad_norm_', (['params'], {}), '(params, **self.grad_clip)\n', (1695, 1721), F... |
import numpy as np
class CellularAutomationModel:
grid_width = 40
grid_height = 40
def __init__(self):
self.grid = self._randomised_grid()
def evolve(self):
"""
Evolve the current grid state using Conway's Game of Life algorithm.
:returns
dict: A dictiona... | [
"numpy.random.randint"
] | [((2271, 2333), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(self.grid_height, self.grid_width)'}), '(2, size=(self.grid_height, self.grid_width))\n', (2288, 2333), True, 'import numpy as np\n')] |
from encoder import Encoder
from decoder import Decoder
from parser import Parser
from baseline import *
from language_model import LanguageModel
from util import Reader
import dynet as dy
from misc import compute_eval_score, compute_perplexity
import os
initializers = {'glorot': dy.GlorotInitializer(),
... | [
"os.path.exists",
"dynet.ConstInitializer",
"encoder.Encoder",
"dynet.scalarInput",
"parser.Parser",
"util.Reader",
"os.path.join",
"dynet.UniformInitializer",
"decoder.Decoder",
"dynet.NormalInitializer",
"language_model.LanguageModel",
"misc.compute_eval_score",
"misc.compute_perplexity",
... | [((283, 305), 'dynet.GlorotInitializer', 'dy.GlorotInitializer', ([], {}), '()\n', (303, 305), True, 'import dynet as dy\n'), ((335, 360), 'dynet.ConstInitializer', 'dy.ConstInitializer', (['(0.01)'], {}), '(0.01)\n', (354, 360), True, 'import dynet as dy\n'), ((389, 415), 'dynet.UniformInitializer', 'dy.UniformInitial... |
#!/usr/bin/env python
# Copyright (c) 2019 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
import csv
import sys
import string
import optparse
from co... | [
"optparse.OptionGroup",
"collections.defaultdict",
"steelscript.netprofiler.core.hostgroup.HostGroupType.create",
"csv.Sniffer",
"sys.exit",
"steelscript.netprofiler.core.hostgroup.HostGroupType.find_by_name",
"steelscript.netprofiler.core.hostgroup.HostGroup",
"steelscript.commands.steel.prompt_yn",
... | [((1364, 1413), 'optparse.OptionGroup', 'optparse.OptionGroup', (['parser', '"""HostGroup Options"""'], {}), "(parser, 'HostGroup Options')\n", (1384, 1413), False, 'import optparse\n'), ((2399, 2416), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2410, 2416), False, 'from collections import de... |
from datasets.hscic.hscic_datasets import scrape as datasets_scrape
from datasets.hscic.hscic_indicators import scrape as indicators_scrape
def main(workspace):
datasets_scrape(workspace)
indicators_scrape(workspace) | [
"datasets.hscic.hscic_indicators.scrape",
"datasets.hscic.hscic_datasets.scrape"
] | [((170, 196), 'datasets.hscic.hscic_datasets.scrape', 'datasets_scrape', (['workspace'], {}), '(workspace)\n', (185, 196), True, 'from datasets.hscic.hscic_datasets import scrape as datasets_scrape\n'), ((201, 229), 'datasets.hscic.hscic_indicators.scrape', 'indicators_scrape', (['workspace'], {}), '(workspace)\n', (21... |
"""***********************************************************
*** Copyright Tektronix, Inc. ***
*** See www.tek.com/sample-license for licensing terms. ***
***********************************************************"""
import socket
import struct
import math
import time
import sys
echo_cmd =... | [
"time.time",
"socket.socket"
] | [((8559, 8570), 'time.time', 'time.time', ([], {}), '()\n', (8568, 8570), False, 'import time\n'), ((8616, 8665), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (8629, 8665), False, 'import socket\n'), ((10341, 10352), 'time.time', 'time.time'... |
import cv2
from dev_autopilot import autopilot
from emulation import get_bindings, clear_input
import threading
import kthread
from pynput import keyboard
from programInfo import showInfo
STATE = 0
def start_action():
stop_action()
kthread.KThread(target = autopilot, name = "EDAutopilot").start()
... | [
"pynput.keyboard.Listener",
"threading.enumerate",
"kthread.KThread",
"programInfo.showInfo",
"cv2.destroyAllWindows",
"emulation.get_bindings"
] | [((996, 1006), 'programInfo.showInfo', 'showInfo', ([], {}), '()\n', (1004, 1006), False, 'from programInfo import showInfo\n'), ((347, 370), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (368, 370), False, 'import cv2\n'), ((390, 411), 'threading.enumerate', 'threading.enumerate', ([], {}), '()\n... |
"""
Showcases correlated colour temperature computations.
"""
import colour
from colour.utilities import message_box
message_box("Correlated Colour Temperature Computations")
cmfs = colour.MSDS_CMFS["CIE 1931 2 Degree Standard Observer"]
illuminant = colour.SDS_ILLUMINANTS["D65"]
xy = colour.XYZ_to_xy(colour.sd_to_X... | [
"colour.temperature.uv_to_CCT_Robertson1968",
"colour.temperature.CCT_to_uv_Robertson1968",
"colour.CCT_to_xy",
"colour.temperature.xy_to_CCT_McCamy1992",
"colour.xy_to_XYZ",
"colour.xy_to_CCT",
"colour.temperature.CCT_to_xy_CIE_D",
"colour.CCT_to_uv",
"colour.temperature.CCT_to_uv_Krystek1985",
"... | [((119, 176), 'colour.utilities.message_box', 'message_box', (['"""Correlated Colour Temperature Computations"""'], {}), "('Correlated Colour Temperature Computations')\n", (130, 176), False, 'from colour.utilities import message_box\n'), ((411, 569), 'colour.utilities.message_box', 'message_box', (['f"""Converting to ... |
#!/usr/bin/env python
import drmaa
import shlex
from optparse import OptionParser
from sys import stderr, stdin, exit
from datetime import datetime
import traceback
def Stop(pool, jt, info):
'''Job failure function that stops synchronization.'''
pool.shall_stop = True
pool.all_done = False
pool.failed... | [
"shlex.split",
"optparse.OptionParser.__init__",
"datetime.datetime.now",
"sys.exit",
"traceback.print_exc",
"drmaa.Session"
] | [((1738, 1752), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1750, 1752), False, 'from datetime import datetime\n'), ((2930, 2944), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2942, 2944), False, 'from datetime import datetime\n'), ((6816, 6831), 'drmaa.Session', 'drmaa.Session', ([], {})... |
import sys
from collections import defaultdict
import torch
from varclr.utils.infer import MockArgs
from varclr.data.preprocessor import CodePreprocessor
if __name__ == "__main__":
ret = torch.load(sys.argv[2])
vars, embs = ret["vars"], ret["embs"]
embs /= embs.norm(dim=1, keepdim=True)
embs = embs.c... | [
"torch.topk",
"torch.load",
"collections.defaultdict",
"varclr.utils.infer.MockArgs"
] | [((194, 217), 'torch.load', 'torch.load', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (204, 217), False, 'import torch\n'), ((501, 517), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (512, 517), False, 'from collections import defaultdict\n'), ((424, 434), 'varclr.utils.infer.MockArgs', 'MockArgs', ... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.dnn.ipynb (unless otherwise specified).
__all__ = ['Multi_Layer_Perceptron', 'CollabFNet']
# Cell
import torch
import torch.nn as nn
import torch.nn.functional as F
# Cell
class Multi_Layer_Perceptron(nn.Module):
def __init__(self, args, num_users, nu... | [
"torch.nn.Sigmoid",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.ModuleList",
"torch.cat",
"torch.nn.Linear",
"torch.nn.Embedding"
] | [((562, 636), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings': 'self.num_users', 'embedding_dim': 'self.factor_num'}), '(num_embeddings=self.num_users, embedding_dim=self.factor_num)\n', (574, 636), True, 'import torch.nn as nn\n'), ((667, 741), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings':... |
import csv
import operator
if __name__ == "__main__":
# We use try-except statements to properly handle errors, as in case the
# input file does not exist in the directory.
try:
# We open the .csv file loading the filds separated by a ; delimiter:
csv_archivo_locales = open("Locales.csv", e... | [
"operator.itemgetter",
"csv.writer",
"csv.reader"
] | [((371, 417), 'csv.reader', 'csv.reader', (['csv_archivo_locales'], {'delimiter': '""";"""'}), "(csv_archivo_locales, delimiter=';')\n", (381, 417), False, 'import csv\n'), ((523, 570), 'csv.reader', 'csv.reader', (['csv_archivo_terrazas'], {'delimiter': '""";"""'}), "(csv_archivo_terrazas, delimiter=';')\n", (533, 570... |
#!/usr/bin/env python
import os
if not os.path.isfile("/proc/sys/fs/binfmt_misc/WSLInterop"):
# windows
LOGFILE = os.environ['LOCALAPPDATA'] + "\\AGS\\New World\\Game.log"
else:
# wsl
LOGFILE = os.popen('cmd.exe /c "echo %LocalAppData%"').read().strip() + "\\AGS\\New World\\Game.log"
LOGFILE = os.popen("wslpath ... | [
"os.path.isfile",
"os.popen"
] | [((40, 93), 'os.path.isfile', 'os.path.isfile', (['"""/proc/sys/fs/binfmt_misc/WSLInterop"""'], {}), "('/proc/sys/fs/binfmt_misc/WSLInterop')\n", (54, 93), False, 'import os\n'), ((200, 244), 'os.popen', 'os.popen', (['"""cmd.exe /c "echo %LocalAppData%\\""""'], {}), '(\'cmd.exe /c "echo %LocalAppData%"\')\n', (208, 24... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | [
"azure.mgmt.monitor.models.RuleMetricDataSource",
"azure.cli.command_modules.monitor.util.get_operator_map",
"azure.cli.command_modules.monitor.util.get_aggregation_map",
"azure.mgmt.monitor.models.RuleWebhookAction",
"azure.mgmt.monitor.models.ThresholdRuleCondition",
"knack.util.CLIError",
"azure.mgmt... | [((2428, 2467), 'azure.mgmt.monitor.models.RuleMetricDataSource', 'RuleMetricDataSource', (['None', 'metric_name'], {}), '(None, metric_name)\n', (2448, 2467), False, 'from azure.mgmt.monitor.models import ThresholdRuleCondition, RuleMetricDataSource\n'), ((2526, 2598), 'azure.mgmt.monitor.models.ThresholdRuleCondition... |
# !/usr/bin/env python
# -*- coding = utf-8 -*-
# @Author:wanghui
# @Time:
# @File:getStartActivityConfig.py
import configparser
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class GetStartActivityConfig(object):
def __init__(self):
self.config = configparser.ConfigParser()
s... | [
"os.path.abspath",
"os.path.join",
"configparser.ConfigParser"
] | [((169, 194), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (184, 194), False, 'import os\n'), ((283, 310), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (308, 310), False, 'import configparser\n'), ((429, 455), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""... |
"""Decorators used for adding functionality to the library."""
from deserialize.exceptions import NoDefaultSpecifiedException
def default(key_name, default_value):
"""A decorator function for mapping default values to key names."""
def store_defaults_map(class_reference):
"""Store the defaults map."... | [
"deserialize.exceptions.NoDefaultSpecifiedException"
] | [((1412, 1441), 'deserialize.exceptions.NoDefaultSpecifiedException', 'NoDefaultSpecifiedException', ([], {}), '()\n', (1439, 1441), False, 'from deserialize.exceptions import NoDefaultSpecifiedException\n'), ((1235, 1264), 'deserialize.exceptions.NoDefaultSpecifiedException', 'NoDefaultSpecifiedException', ([], {}), '... |
import configparser
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
config = configparser.ConfigParser()
config.read('alembic.ini')
connection_url = config['alembic']['sqlalchemy.url']
Engine = create_engine(connection_url, connect_args={'check_same_thread': False})
Session = sessionmaker... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"configparser.ConfigParser"
] | [((107, 134), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (132, 134), False, 'import configparser\n'), ((225, 297), 'sqlalchemy.create_engine', 'create_engine', (['connection_url'], {'connect_args': "{'check_same_thread': False}"}), "(connection_url, connect_args={'check_same_thread': Fa... |
# Copyright 2014-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | [
"wlauto.common.resources.File",
"wlauto.Executable",
"re.compile",
"os.path.join",
"wlauto.Parameter"
] | [((804, 836), 're.compile', 're.compile', (['"""Richards: (\\\\d+.*)"""'], {}), "('Richards: (\\\\d+.*)')\n", (814, 836), False, 'import re\n'), ((857, 890), 're.compile', 're.compile', (['"""DeltaBlue: (\\\\d+.*)"""'], {}), "('DeltaBlue: (\\\\d+.*)')\n", (867, 890), False, 'import re\n'), ((908, 938), 're.compile', 'r... |
'''
n-gram은 이와 같은 확률적 언어 모델의 대표적인 것으로서,
n개 단어의 연쇄를 확률적으로 표현해 두면 실제로
발성된 문장의 기록을 계산할 수 있다.
'''
# Step 1 : Bag of Words
from nltk.corpus import reuters
from collections import Counter, defaultdict
counts = Counter(reuters.words())
total_count = len(reuters.words())
# 공통적으로 가장 많이 나타나는 20개의 단어
print(counts.most_commo... | [
"nltk.corpus.reuters.sents",
"nltk.corpus.reuters.words",
"functools.reduce",
"collections.defaultdict",
"nltk.bigrams",
"random.random",
"nltk.trigrams"
] | [((1550, 1565), 'nltk.corpus.reuters.sents', 'reuters.sents', ([], {}), '()\n', (1563, 1565), False, 'from nltk.corpus import reuters\n'), ((217, 232), 'nltk.corpus.reuters.words', 'reuters.words', ([], {}), '()\n', (230, 232), False, 'from nltk.corpus import reuters\n'), ((252, 267), 'nltk.corpus.reuters.words', 'reut... |
import os
import requests
import urllib3.util.retry
import logging
import subprocess
import re
import pprint
from datetime import datetime, timedelta
import pygit2
from github import Github
from github.GithubException import UnknownObjectException
# Create logger with logging level set to all
LOGGER = logging.getLogg... | [
"logging.getLogger",
"logging.basicConfig",
"requests.Session",
"re.compile",
"datetime.datetime.strptime",
"pygit2.UserPass",
"subprocess.run",
"os.path.join",
"datetime.datetime.now",
"re.sub",
"datetime.timedelta",
"pygit2.clone_repository",
"re.search"
] | [((305, 332), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (322, 332), False, 'import logging\n'), ((333, 372), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (352, 372), False, 'import logging\n'), ((1484, 1597), 're.compile', '... |
from django.core.validators import MinLengthValidator
from django.contrib.auth.models import User
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.encoding import iri_to_u... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"mur.commonmark.commonmark",
"django.db.models.DateTimeField",
"mongo.objectid.ObjectId",
"django.core.validators.MinLengthValidator",
"django.utils.encoding.iri_to_uri",
"django.contrib.auth.validators.UnicodeUsernameValidator",
"django.d... | [((1314, 1345), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'Post'}), '(pre_save, sender=Post)\n', (1322, 1345), False, 'from django.dispatch import receiver\n'), ((562, 641), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(24)', 'default': '_objectid', 'editable': '(False)... |
# Import external modules.
from google.appengine.ext import ndb
import logging
# Import local modules.
from configAutocomplete import const as conf
from constants import Constants
class Survey(ndb.Model):
surveyId = ndb.StringProperty() # Primary key
title = ndb.StringProperty()
introduction = ndb.Str... | [
"google.appengine.ext.ndb.BooleanProperty",
"google.appengine.ext.ndb.StringProperty"
] | [((223, 243), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (241, 243), False, 'from google.appengine.ext import ndb\n'), ((273, 293), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (291, 293), False, 'from google.appengine.ext import ndb\n'), ((3... |
from django.contrib.auth import models as auth_models
from django.db import models
from django.urls import reverse
class User(auth_models.AbstractUser):
"""Extends default model to add project specific fields."""
birth_date = models.DateField(help_text="Employee Date of birth.")
address = models.TextFiel... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.BooleanField"
] | [((237, 290), 'django.db.models.DateField', 'models.DateField', ([], {'help_text': '"""Employee Date of birth."""'}), "(help_text='Employee Date of birth.')\n", (253, 290), False, 'from django.db import models\n'), ((305, 361), 'django.db.models.TextField', 'models.TextField', ([], {'help_text': '"""Employee permanent ... |
# test builtin sorted
try:
sorted
set
except:
import sys
print("SKIP")
sys.exit()
print(sorted(set(range(100))))
print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2)))
# need to use keyword argument
try:
sorted([], None)
except TypeError:
print("TypeError")
| [
"sys.exit"
] | [((91, 101), 'sys.exit', 'sys.exit', ([], {}), '()\n', (99, 101), False, 'import sys\n')] |
# -*- coding: utf-8 -*-
"""Serializer tests for the Mendeley addon."""
import pytest
from addons.base.tests.serializers import CitationAddonSerializerTestSuiteMixin
from addons.base.tests.utils import MockFolder
from addons.mendeley.tests.factories import MendeleyAccountFactory
from addons.mendeley.serializer import M... | [
"addons.base.tests.utils.MockFolder"
] | [((630, 642), 'addons.base.tests.utils.MockFolder', 'MockFolder', ([], {}), '()\n', (640, 642), False, 'from addons.base.tests.utils import MockFolder\n')] |
# -*- coding: utf-8 -*-
r"""
Information-set decoding for linear codes
Information-set decoding is a probabilistic decoding strategy that
essentially tries to guess `k` correct positions in the received word,
where `k` is the dimension of the code. A codeword agreeing with the
received word on the guessed position can... | [
"sage.all.vector",
"sage.misc.prandom.randint",
"itertools.product",
"sage.matrix.special.random_matrix",
"sage.all.binomial",
"time.process_time",
"sage.modules.free_module_element.random_vector"
] | [((22867, 22881), 'time.process_time', 'process_time', ([], {}), '()\n', (22879, 22881), False, 'from time import process_time\n'), ((23222, 23241), 'sage.modules.free_module_element.random_vector', 'random_vector', (['F', 'n'], {}), '(F, n)\n', (23235, 23241), False, 'from sage.modules.free_module_element import rando... |
import math
import tensorflow as tf
from mayo.log import log
from mayo.util import (
Percent, memoize_method, memoize_property, object_from_params)
from mayo.session.base import SessionBase
class Train(SessionBase):
mode = 'train'
def __init__(self, config):
super().__init__(config)
sel... | [
"tensorflow.expand_dims",
"math.floor",
"mayo.log.log.countdown",
"mayo.util.Percent",
"tensorflow.group",
"mayo.util.object_from_params",
"mayo.log.log.info",
"tensorflow.concat",
"tensorflow.add_n",
"mayo.log.log.demote",
"tensorflow.reduce_mean",
"math.isnan"
] | [((567, 593), 'mayo.util.object_from_params', 'object_from_params', (['params'], {}), '(params)\n', (585, 593), False, 'from mayo.util import Percent, memoize_method, memoize_property, object_from_params\n'), ((1175, 1201), 'mayo.util.object_from_params', 'object_from_params', (['params'], {}), '(params)\n', (1193, 120... |
def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
... | [
"lazysignup.models.LazyUser.objects.filter"
] | [((522, 556), 'lazysignup.models.LazyUser.objects.filter', 'LazyUser.objects.filter', ([], {'user': 'user'}), '(user=user)\n', (545, 556), False, 'from lazysignup.models import LazyUser\n')] |
# run.py
"""
Script for running a specific pipeline from a given yaml config file
"""
import os
import argparse
import yaml
from importlib import import_module
import numpy as np
import time
import pandas as pd
def import_from_path(path_to_module, obj_name = None):
"""
Import an object from a module based o... | [
"importlib.import_module",
"os.makedirs",
"argparse.ArgumentParser",
"pandas.read_csv",
"os.path.join",
"pandas.DataFrame.from_dict",
"yaml.safe_load",
"os.path.isdir",
"pandas.concat",
"pandas.DataFrame",
"time.time",
"numpy.arange"
] | [((525, 551), 'importlib.import_module', 'import_module', (['module_name'], {}), '(module_name)\n', (538, 551), False, 'from importlib import import_module\n'), ((691, 735), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (714, 735), False, 'import argp... |
import pygame
from pygame.sprite import Group
from button import Button
from game_stats import GameStats
from settings import Settings
from ship import Ship
from scoreboard import Scoreboard
import game_funcitons as gf
def run_game():
pygame.init()
pygame.mixer.init()
ai_settings = Settings()
screen =... | [
"ship.Ship",
"game_funcitons.create_fleet",
"pygame.init",
"game_stats.GameStats",
"game_funcitons.update_aliens",
"game_funcitons.play_music",
"pygame.display.set_mode",
"pygame.sprite.Group",
"button.Button",
"pygame.time.Clock",
"scoreboard.Scoreboard",
"game_funcitons.check_events",
"gam... | [((241, 254), 'pygame.init', 'pygame.init', ([], {}), '()\n', (252, 254), False, 'import pygame\n'), ((259, 278), 'pygame.mixer.init', 'pygame.mixer.init', ([], {}), '()\n', (276, 278), False, 'import pygame\n'), ((297, 307), 'settings.Settings', 'Settings', ([], {}), '()\n', (305, 307), False, 'from settings import Se... |
from enum import Enum, auto
from string import Template
class MessageRegister:
def __init__(self, dispatch_table=None):
self.dispatch = dict() if dispatch_table is None else dispatch_table
def register(self, ref):
def decorator(func):
self.dispatch[ref] = func
return func
return decorator
def get(sel... | [
"enum.auto"
] | [((496, 502), 'enum.auto', 'auto', ([], {}), '()\n', (500, 502), False, 'from enum import Enum, auto\n'), ((525, 531), 'enum.auto', 'auto', ([], {}), '()\n', (529, 531), False, 'from enum import Enum, auto\n')] |
import os
import shutil
import pychemia
import tempfile
import unittest
class MyTestCase(unittest.TestCase):
def test_incar(self):
"""
Test (pychemia.code.vasp) [INCAR parsing and writing] :
"""
print(os.getcwd())
iv = pychemia.code.vasp.read_incar('tests/data/vasp_0... | [
"pychemia.code.vasp.write_potcar",
"pychemia.code.vasp.VaspJob",
"pychemia.code.vasp.read_kpoints",
"pychemia.code.vasp.read_poscar",
"pychemia.code.vasp.read_incar",
"pychemia.code.vasp.VaspInput",
"shutil.rmtree",
"os.getcwd",
"os.chdir",
"pychemia.crystal.CrystalSymmetry",
"tempfile.mkdtemp",... | [((272, 329), 'pychemia.code.vasp.read_incar', 'pychemia.code.vasp.read_incar', (['"""tests/data/vasp_01/INCAR"""'], {}), "('tests/data/vasp_01/INCAR')\n", (301, 329), False, 'import pychemia\n'), ((422, 451), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (449, 451), False, 'import tem... |
import os
class Material:
def __init__(self, name, color, outputs):
self.name = name
self.color = color
self.outputs = outputs
materials = [Material("dilithium", 0xddcecb, ("DUST", "GEM")),
Material("iron", 0xafafaf, ("SHEET", "STICK", "DUST", "PLATE")),
Material("gold", 0xffff5d, ("D... | [
"os.system"
] | [((3652, 3666), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (3661, 3666), False, 'import os\n'), ((4616, 4630), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (4625, 4630), False, 'import os\n'), ((4854, 4868), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (4863, 4868), False, 'import os\n'), ((5098,... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | [
"google.cloud.monitoring_v3.proto.service_service_pb2.ListServiceLevelObjectivesRequest",
"google.cloud.monitoring_v3.proto.service_service_pb2.CreateServiceRequest",
"mock.patch",
"google.cloud.monitoring_v3.proto.service_service_pb2.DeleteServiceLevelObjectiveRequest",
"google.cloud.monitoring_v3.proto.se... | [((2109, 2149), 'google.cloud.monitoring_v3.proto.service_pb2.Service', 'service_pb2.Service', ([], {}), '(**expected_response)\n', (2128, 2149), False, 'from google.cloud.monitoring_v3.proto import service_pb2\n'), ((2260, 2317), 'mock.patch', 'mock.patch', (['"""google.api_core.grpc_helpers.create_channel"""'], {}), ... |
from typing import List
import torch
from detectron2.structures import ImageList, Boxes, Instances, pairwise_iou
from detectron2.modeling.box_regression import Box2BoxTransform
from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads
from detectron2.modeling.roi_heads.cascade_rcnn import CascadeR... | [
"torch.no_grad",
"detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register",
"detectron2.modeling.box_regression.Box2BoxTransform"
] | [((451, 480), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGISTRY.register', ([], {}), '()\n', (478, 480), False, 'from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads\n'), ((1495, 1524), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGIS... |
# coding=utf-8
# tensorflow tf.contrib.data api test
import tensorflow as tf
# file path
filename = ''
batch_size = 100
aa = (tf.contrib.data.TextLineDataset(filename)
.map((lambda line: tf.decode_csv(line, record_defaults=[['1'], ['1'], ['1']], field_delim='\t')))
.shuffle(buffer_size=1000)
.bat... | [
"tensorflow.decode_csv",
"tensorflow.contrib.data.TextLineDataset"
] | [((131, 172), 'tensorflow.contrib.data.TextLineDataset', 'tf.contrib.data.TextLineDataset', (['filename'], {}), '(filename)\n', (162, 172), True, 'import tensorflow as tf\n'), ((198, 274), 'tensorflow.decode_csv', 'tf.decode_csv', (['line'], {'record_defaults': "[['1'], ['1'], ['1']]", 'field_delim': '"""\t"""'}), "(li... |
'''
实验名称:音频播放
版本:v1.0
日期:2020.12
作者:01Studio
说明:MP3/WAV音频文件播放。使用物理按键控制
'''
#导入相关模块
import audio,time
from pyb import Switch
from machine import Pin
#构建音频对象
wm=audio.WM8978()
vol = 80 #音量初始化,80
######################
# 播放 USR按键
######################
play_flag = 0
def music_play():
global play_flag
play_fla... | [
"time.sleep_ms",
"audio.WM8978",
"machine.Pin",
"pyb.Switch"
] | [((161, 175), 'audio.WM8978', 'audio.WM8978', ([], {}), '()\n', (173, 175), False, 'import audio, time\n'), ((331, 339), 'pyb.Switch', 'Switch', ([], {}), '()\n', (337, 339), False, 'from pyb import Switch\n'), ((430, 460), 'machine.Pin', 'Pin', (['"""A0"""', 'Pin.IN', 'Pin.PULL_UP'], {}), "('A0', Pin.IN, Pin.PULL_UP)\... |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
lin_min = 0.0
lin_max = 0.0
ang_min = 0.0
ang_max = 0.0
def odom_cb(msg):
global lin_min, lin_max, ang_min, ang_max
if lin_min > msg.twist.twist.linear.x:
lin_min = msg.twist.twist.linear.x
if lin_max < msg.twist.twist.linear.x... | [
"rospy.init_node",
"rospy.Subscriber",
"rospy.loginfo",
"rospy.spin"
] | [((546, 639), 'rospy.loginfo', 'rospy.loginfo', (['"""linear: [%f, %f] angular: [%f, %f]"""', 'lin_min', 'lin_max', 'ang_min', 'ang_max'], {}), "('linear: [%f, %f] angular: [%f, %f]', lin_min, lin_max,\n ang_min, ang_max)\n", (559, 639), False, 'import rospy\n'), ((672, 721), 'rospy.init_node', 'rospy.init_node'... |
# this file is to store all custom classes
import tkinter as tk
# class to store tkinter window properties
# font: tk font dictionary {family, size, weight, slant, underline, overstrike}
# font color: string
# nrows: the number of rows of lyric displayed (integer greater than 0)
# width: window width (int greater tha... | [
"tkinter.Frame",
"tkinter.Label"
] | [((2419, 2492), 'tkinter.Frame', 'tk.Frame', (['root'], {'bg': '"""#2e2e2e"""', 'relief': '"""groove"""', 'bd': '(0)', 'highlightthickness': '(0)'}), "(root, bg='#2e2e2e', relief='groove', bd=0, highlightthickness=0)\n", (2427, 2492), True, 'import tkinter as tk\n'), ((2805, 2872), 'tkinter.Label', 'tk.Label', (['self.... |
"""
Unit test utilities.
"""
import textwrap
def clean_multiline_string( multiline_string, sep='\n' ):
"""
Dedent, split, remove first and last empty lines, rejoin.
"""
multiline_string = textwrap.dedent( multiline_string )
string_list = multiline_string.split( sep )
if not string_list[0]:
... | [
"textwrap.dedent"
] | [((206, 239), 'textwrap.dedent', 'textwrap.dedent', (['multiline_string'], {}), '(multiline_string)\n', (221, 239), False, 'import textwrap\n')] |
import asyncio
import json
def test_chunked_messages(plugin, read):
request = {
"jsonrpc": "2.0",
"method": "install_game",
"params": {
"game_id": "3"
}
}
message = json.dumps(request).encode() + b"\n"
read.side_effect = [message[:5], message[5:], b""]
a... | [
"json.dumps"
] | [((1232, 1251), 'json.dumps', 'json.dumps', (['request'], {}), '(request)\n', (1242, 1251), False, 'import json\n'), ((223, 242), 'json.dumps', 'json.dumps', (['request'], {}), '(request)\n', (233, 242), False, 'import json\n'), ((800, 819), 'json.dumps', 'json.dumps', (['request'], {}), '(request)\n', (810, 819), Fals... |
import os
import unittest
from ....BaseTestCase import BaseTestCase
from kombi.Crawler import Crawler
from kombi.Crawler.Fs.Image import ImageCrawler
from kombi.Crawler.PathHolder import PathHolder
class ImageCrawlerTest(BaseTestCase):
"""Test Image crawler."""
__singleFile = os.path.join(BaseTestCase.dataTes... | [
"unittest.main",
"kombi.Crawler.PathHolder.PathHolder"
] | [((2715, 2730), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2728, 2730), False, 'import unittest\n'), ((613, 642), 'kombi.Crawler.PathHolder.PathHolder', 'PathHolder', (['self.__singleFile'], {}), '(self.__singleFile)\n', (623, 642), False, 'from kombi.Crawler.PathHolder import PathHolder\n'), ((878, 909), 'ko... |
#!/usr/bin/env python
import unittest, asyncio, asynctest, websockets, json
from remote_params import HttpServer, Params, Server, Remote, create_sync_params, schema_list
from remote_params.WebsocketServer import WebsocketServer
class MockSocket:
def __init__(self):
self.close_count = 0
self.msgs = []
de... | [
"remote_params.Params",
"remote_params.schema_list",
"websockets.connect",
"unittest.main",
"remote_params.Server"
] | [((3672, 3687), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3685, 3687), False, 'import unittest, asyncio, asynctest, websockets, json\n'), ((513, 521), 'remote_params.Params', 'Params', ([], {}), '()\n', (519, 521), False, 'from remote_params import HttpServer, Params, Server, Remote, create_sync_params, sche... |
import warnings
import pandas as pd
from nltk.sentiment.vader import SentimentIntensityAnalyzer
warnings.filterwarnings("ignore")
def classify_comments(text_file, page_name):
"""
Description:
This function recives a text file and convert it into csv file to enable to label the comments inside that file, ... | [
"nltk.sentiment.vader.SentimentIntensityAnalyzer",
"pandas.read_csv",
"os.path.isdir",
"os.mkdir",
"warnings.filterwarnings"
] | [((98, 131), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (121, 131), False, 'import warnings\n'), ((668, 727), 'pandas.read_csv', 'pd.read_csv', (["('%s' % text_file)"], {'names': "['comments']", 'sep': '"""\t"""'}), "('%s' % text_file, names=['comments'], sep='\\t')\n"... |
import copy
import logging
import warnings
from kolibri.plugins.registry import registered_plugins
logger = logging.getLogger(__name__)
def __validate_config_option(
section, name, base_config_spec, plugin_specs, module_path
):
# Raise an error if someone tries to overwrite a base option
# except for th... | [
"logging.getLogger",
"copy.deepcopy"
] | [((110, 137), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (127, 137), False, 'import logging\n'), ((4187, 4218), 'copy.deepcopy', 'copy.deepcopy', (['base_config_spec'], {}), '(base_config_spec)\n', (4200, 4218), False, 'import copy\n')] |
from io import open
import time
import math
import torch
import torch.nn.functional as F
from config import MAX_LENGTH
from config import SOS_token
from config import EOS_token
from config import device
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2co... | [
"torch.tensor",
"time.time",
"io.open",
"math.floor"
] | [((2676, 2694), 'math.floor', 'math.floor', (['(s / 60)'], {}), '(s / 60)\n', (2686, 2694), False, 'import math\n'), ((2784, 2795), 'time.time', 'time.time', ([], {}), '()\n', (2793, 2795), False, 'import time\n'), ((2357, 2411), 'torch.tensor', 'torch.tensor', (['indexes'], {'dtype': 'torch.long', 'device': 'device'})... |
import os
import sys
import json
import argparse
import progressbar
from pathlib import Path
from random import shuffle
from time import time
import torch
from cpc.dataset import findAllSeqs
from cpc.feature_loader import buildFeature, FeatureModule, loadModel, buildFeature_batch
from cpc.criterion.clustering import kM... | [
"os.path.exists",
"cpc.dataset.findAllSeqs",
"cpc.feature_loader.buildFeature_batch",
"argparse.ArgumentParser",
"pathlib.Path",
"torch.nn.Sequential",
"cpc.criterion.clustering.kMeanCluster",
"torch.load",
"os.path.join",
"cpc.feature_loader.FeatureModule",
"os.path.dirname",
"argparse.Namesp... | [((710, 736), 'torch.load', 'torch.load', (['pathCheckpoint'], {}), '(pathCheckpoint)\n', (720, 736), False, 'import torch\n'), ((1152, 1245), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Quantize audio files using CPC Clustering Module."""'}), "(description=\n 'Quantize audio files... |
import glob
import os
import os.path
import sys
import shutil
import cPickle
from types import StringType, UnicodeType
from distutils.core import setup
from distutils.extension import Extension
from distutils.command.install import install
PY3K = sys.version_info[0] > 2
with open('README.rst') as inp:
long_descr... | [
"os.path.join",
"distutils.extension.Extension",
"numpy.get_include"
] | [((1721, 1820), 'distutils.extension.Extension', 'Extension', (['"""prody.proteins.cpairwise2"""', "['prody/proteins/cpairwise2.c']"], {'include_dirs': "['prody']"}), "('prody.proteins.cpairwise2', ['prody/proteins/cpairwise2.c'],\n include_dirs=['prody'])\n", (1730, 1820), False, 'from distutils.extension import Ex... |
import io
import json
from google.auth import compute_engine
from google.oauth2 import service_account
def gcp_credentials(service_account_file):
if service_account_file:
with io.open(service_account_file, 'r', encoding='utf-8') as json_fi:
credentials_info = json.load(json_fi)
creden... | [
"google.oauth2.service_account.Credentials.from_service_account_info",
"json.load",
"google.auth.compute_engine.Credentials",
"io.open"
] | [((328, 399), 'google.oauth2.service_account.Credentials.from_service_account_info', 'service_account.Credentials.from_service_account_info', (['credentials_info'], {}), '(credentials_info)\n', (381, 399), False, 'from google.oauth2 import service_account\n'), ((589, 617), 'google.auth.compute_engine.Credentials', 'com... |
import requests
import tweepy
import random
import time
import os
import bs4
from bs4 import BeautifulSoup
from pybooru import Moebooru
siteurl='https://www.sakugabooru.com/post/show/'
header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/53... | [
"random.choice",
"os.listdir",
"pybooru.Moebooru",
"os.path.join",
"requests.get",
"time.sleep",
"bs4.BeautifulSoup",
"tweepy.API",
"tweepy.OAuthHandler"
] | [((336, 384), 'pybooru.Moebooru', 'Moebooru', ([], {'site_url': '"""https://www.sakugabooru.com"""'}), "(site_url='https://www.sakugabooru.com')\n", (344, 384), False, 'from pybooru import Moebooru\n'), ((2143, 2180), 'requests.get', 'requests.get', (['posturl'], {'headers': 'header'}), '(posturl, headers=header)\n', (... |
"""
"""
from membership.web.urls import membership_urls
from public.web.urls import error_urls, public_urls, static_urls
from public.web.views import home
from wheezy.routing import url
locale_pattern = "{locale:(en|ru)}/"
locale_defaults = {"locale": "en"}
locale_urls = public_urls + membership_urls
locale_urls.app... | [
"wheezy.routing.url"
] | [((365, 411), 'wheezy.routing.url', 'url', (['""""""', 'home', 'locale_defaults'], {'name': '"""default"""'}), "('', home, locale_defaults, name='default')\n", (368, 411), False, 'from wheezy.routing import url\n')] |
from stheno import (
B, # Linear algebra backend
Graph, # Graph that keep track of the graphical model
GP, # Gaussian process
EQ, # Squared-exponential kernel
Matern12, # Matern-1/2 kernel
Matern52, # Matern-5/2 kernel
Delta, # Noise kernel
Normal, # Gaussian distribution
Dia... | [
"stheno.Delta",
"stheno.Diagonal",
"stheno.B.matmul",
"stheno.Graph",
"stheno.B.transpose",
"stheno.B.stack",
"stheno.B.dtype",
"stheno.Matern12",
"stheno.B.ones",
"stheno.B.shape",
"stheno.B.svd",
"stheno.EQ",
"stheno.Matern52",
"stheno.B.to_numpy",
"stheno.GP"
] | [((783, 790), 'stheno.Graph', 'Graph', ([], {}), '()\n', (788, 790), False, 'from stheno import B, Graph, GP, EQ, Matern12, Matern52, Delta, Normal, Diagonal, dense\n'), ((2162, 2170), 'stheno.B.svd', 'B.svd', (['K'], {}), '(K)\n', (2167, 2170), False, 'from stheno import B, Graph, GP, EQ, Matern12, Matern52, Delta, No... |
from os import listdir
from os.path import join
import os, errno
def getImageNum(rootDir):
return len(listdir(join(rootDir)))
def safeMkdir(path:str):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise | [
"os.path.join",
"os.makedirs"
] | [((175, 192), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (186, 192), False, 'import os, errno\n'), ((115, 128), 'os.path.join', 'join', (['rootDir'], {}), '(rootDir)\n', (119, 128), False, 'from os.path import join\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
from os.path import basename, exists, isdir, splitext
from sfzparser import SFZParser
def main(args=None):
fn = args[0]
bn = splitext(basename(fn))[0]
parser = SFZParser(fn)
fixed = False
for name, sect in parser.sections:
# fi... | [
"os.path.exists",
"os.path.isdir",
"os.path.basename",
"sfzparser.SFZParser",
"shutil.copy"
] | [((236, 249), 'sfzparser.SFZParser', 'SFZParser', (['fn'], {}), '(fn)\n', (245, 249), False, 'from sfzparser import SFZParser\n'), ((206, 218), 'os.path.basename', 'basename', (['fn'], {}), '(fn)\n', (214, 218), False, 'from os.path import basename, exists, isdir, splitext\n'), ((416, 425), 'os.path.isdir', 'isdir', ([... |
import unittest
from huobi.rest.client import HuobiRestClient
from huobi.rest.error import (
HuobiRestiApiError
)
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(dirname(dirname(dirname(__file__)))), '.env')
load_dotenv(dotenv_path)
class TestCommonEndpoint(... | [
"os.path.dirname",
"huobi.rest.client.HuobiRestClient",
"dotenv.load_dotenv"
] | [((268, 292), 'dotenv.load_dotenv', 'load_dotenv', (['dotenv_path'], {}), '(dotenv_path)\n', (279, 292), False, 'from dotenv import load_dotenv\n'), ((476, 537), 'huobi.rest.client.HuobiRestClient', 'HuobiRestClient', ([], {'access_key': 'access_key', 'secret_key': 'secret_key'}), '(access_key=access_key, secret_key=se... |
#
# Copyright 2017 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"flask.request.args.get",
"flask.flash",
"gerritviewer.common.get_gerrit_url",
"gerritviewer.common.get_connection",
"gerritviewer.common.get_version",
"flask.url_for",
"flask.Blueprint",
"flask.current_app.logger.error"
] | [((943, 974), 'flask.Blueprint', 'Blueprint', (['"""accounts"""', '__name__'], {}), "('accounts', __name__)\n", (952, 974), False, 'from flask import Blueprint, current_app, flash, Markup, render_template, request, redirect, url_for\n'), ((2600, 2626), 'flask.request.args.get', 'request.args.get', (['"""action"""'], {}... |
# Copyright (c) 2020, NVIDIA CORPORATION.
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Union, overload
from typing_extensions import Literal
import cudf
if TYPE_CHECKING:
from cudf.core.column import ColumnBase
class ColumnMethodsMixin:
_column: ColumnBase
_parent: O... | [
"cudf.core.index.as_index",
"cudf._lib.table.Table",
"cudf.Series"
] | [((1753, 1804), 'cudf._lib.table.Table', 'cudf._lib.table.Table', (['{self._parent.name: new_col}'], {}), '({self._parent.name: new_col})\n', (1774, 1804), False, 'import cudf\n'), ((2896, 2966), 'cudf.Series', 'cudf.Series', (['new_col'], {'name': 'self._parent.name', 'index': 'self._parent.index'}), '(new_col, name=s... |
# Example of Naive Bayes implemented from Scratch in Python
import csv
import random
import math
import xgboost as xgb
import matplotlib.pyplot as plt
import numpy as np
def loadCsv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [flo... | [
"math.pow",
"math.sqrt"
] | [((2999, 3018), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (3008, 3018), False, 'import math\n'), ((3595, 3613), 'math.pow', 'math.pow', (['stdev', '(2)'], {}), '(stdev, 2)\n', (3603, 3613), False, 'import math\n'), ((3726, 3748), 'math.sqrt', 'math.sqrt', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', ... |
from random import choice
from time import sleep
jokenpo = ['Pedra', 'Papel', 'Tesoura']
jokenposter_stainger = choice(jokenpo)
jogador = int(input('Qual a sua jogada?'
'\n1. Pedra'
'\n2. Papel'
'\n3. Tesoura'
'\nEscolha: '))
print('\nJO.... | [
"random.choice",
"time.sleep"
] | [((113, 128), 'random.choice', 'choice', (['jokenpo'], {}), '(jokenpo)\n', (119, 128), False, 'from random import choice\n'), ((325, 333), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (330, 333), False, 'from time import sleep\n'), ((350, 358), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (355, 358), False, 'from t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import stat
protoc_exec = None
def find_protoc():
global protoc_exec
if protoc_exec is not None:
return protoc_exec
script_dir = os.path.dirname(os.path.realpath(__file__))
if sys.platform[0:5].lower() == "linux":
protoc_ex... | [
"os.path.realpath",
"os.path.join",
"os.chmod"
] | [((590, 655), 'os.chmod', 'os.chmod', (['protoc_exec', '(stat.S_IRWXU + stat.S_IRWXG + stat.S_IRWXO)'], {}), '(protoc_exec, stat.S_IRWXU + stat.S_IRWXG + stat.S_IRWXO)\n', (598, 655), False, 'import os\n'), ((230, 256), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (246, 256), False, 'impo... |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import pytest
from django.test import RequestFactory
from django.urls import reverse
from doubles import allow, expect
from rest_framework import status
from apps.accounts.models.choices import ActionCategory
from apps.accounts.services.auth import AuthService
from apps... | [
"apps.accounts.tests.factories.pending_action.PendingActionFactory",
"doubles.allow",
"doubles.expect",
"django.urls.reverse"
] | [((579, 637), 'django.urls.reverse', 'reverse', (['"""accounts:confirm-email"""'], {'kwargs': "{'token': token}"}), "('accounts:confirm-email', kwargs={'token': token})\n", (586, 637), False, 'from django.urls import reverse\n'), ((751, 816), 'apps.accounts.tests.factories.pending_action.PendingActionFactory', 'Pending... |
"""OperatorWebSite class unit test."""
from __init__ import json, os, time, unittest, \
webdriver, WebDriverException, OperatorWebSite
class TestOperatorWebSite(unittest.TestCase):
"""Unit test class for OperatorWebSite."""
def load_data(self):
""" Load the data file. """
self.data = N... | [
"__init__.os.path.isfile",
"__init__.unittest.main",
"__init__.webdriver.Chrome",
"__init__.os.path.abspath",
"__init__.time.sleep",
"__init__.OperatorWebSite"
] | [((3089, 3104), '__init__.unittest.main', 'unittest.main', ([], {}), '()\n', (3102, 3104), False, 'from __init__ import json, os, time, unittest, webdriver, WebDriverException, OperatorWebSite\n'), ((344, 388), '__init__.os.path.abspath', 'os.path.abspath', (['"""data/sites/operators.json"""'], {}), "('data/sites/opera... |
from totality import Totality, Node, NodeId
def test_basic():
t = Totality()
coll = t.create_collection(username="system")
node_id = NodeId(node_type="facility")
node = Node(node_id, 34, -120, collection=coll)
print(node.to_doc())
assert t is not None | [
"totality.Node",
"totality.Totality",
"totality.NodeId"
] | [((71, 81), 'totality.Totality', 'Totality', ([], {}), '()\n', (79, 81), False, 'from totality import Totality, Node, NodeId\n'), ((146, 174), 'totality.NodeId', 'NodeId', ([], {'node_type': '"""facility"""'}), "(node_type='facility')\n", (152, 174), False, 'from totality import Totality, Node, NodeId\n'), ((186, 226),... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from fvcore.transforms import HFlipTransform
from detectron2.modeling.postprocessing import detector_postprocess
from detectron2.modeling.test_time_augmentation import GeneralizedRCNNWithTTA
class DensePoseGeneralizedRCNNWithTTA(Gene... | [
"detectron2.modeling.postprocessing.detector_postprocess"
] | [((2922, 2973), 'detectron2.modeling.postprocessing.detector_postprocess', 'detector_postprocess', (['merged_instances', '*orig_shape'], {}), '(merged_instances, *orig_shape)\n', (2942, 2973), False, 'from detectron2.modeling.postprocessing import detector_postprocess\n')] |
# -*- coding: utf-8 -*-
"""Generate charts for the ComPath GitHub Pages site."""
import click
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from more_click import verbose_option
from compath_resources import get_df
from compath_resources.constants import DATA_DIRECTORY, IMG_DIRECTORY
__a... | [
"matplotlib.pyplot.savefig",
"seaborn.set_theme",
"compath_resources.constants.DATA_DIRECTORY.joinpath",
"matplotlib.pyplot.close",
"compath_resources.get_df",
"matplotlib.pyplot.tight_layout",
"seaborn.countplot",
"click.command",
"pandas.concat",
"matplotlib.pyplot.subplots"
] | [((348, 363), 'click.command', 'click.command', ([], {}), '()\n', (361, 363), False, 'import click\n'), ((442, 473), 'seaborn.set_theme', 'sns.set_theme', ([], {'style': '"""darkgrid"""'}), "(style='darkgrid')\n", (455, 473), True, 'import seaborn as sns\n'), ((483, 572), 'compath_resources.get_df', 'get_df', ([], {'in... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 14:24:27 2019
@author: adarzi
"""
#Loading the libraries
import pandas as pd
import os
from os import sys
import pickle
#setting the directory
os.chdir(sys.path[0])
#loading the data:
data = pd.read_csv('../../Inputs/Trip_Data/AirSage_Data/trips_lon... | [
"os.chdir",
"pandas.read_csv",
"pandas.DataFrame.sort_index"
] | [((208, 229), 'os.chdir', 'os.chdir', (['sys.path[0]'], {}), '(sys.path[0])\n', (216, 229), False, 'import os\n'), ((262, 336), 'pandas.read_csv', 'pd.read_csv', (['"""../../Inputs/Trip_Data/AirSage_Data/trips_long_distance.csv"""'], {}), "('../../Inputs/Trip_Data/AirSage_Data/trips_long_distance.csv')\n", (273, 336), ... |
import math
H, N = [int(n) for n in input().split()]
A = []
B = []
for _ in range(N):
a, b = [int(n) for n in input().split()]
A.append(a)
B.append(b)
p = []
for i in range(N):
p.append(A[i] / B[i])
for pp in p:
pass
# print(pp)
maisu = []
for i in range(N):
maisu.append(math.ceil(H / A[i]))
for m ... | [
"math.ceil"
] | [((292, 311), 'math.ceil', 'math.ceil', (['(H / A[i])'], {}), '(H / A[i])\n', (301, 311), False, 'import math\n')] |
""" config.py
Microsimulation config for mulit-LAD MPI simulation
"""
import numpy as np
import glob
import neworder
# define some global variables describing where the starting population and the parameters of the dynamics come from
initial_populations = glob.glob("examples/people_multi/data/ssm_*_MSOA11_ppp_2011.cs... | [
"neworder.mpi.rank",
"neworder.Timeline",
"neworder.mpi.size",
"glob.glob"
] | [((258, 323), 'glob.glob', 'glob.glob', (['"""examples/people_multi/data/ssm_*_MSOA11_ppp_2011.csv"""'], {}), "('examples/people_multi/data/ssm_*_MSOA11_ppp_2011.csv')\n", (267, 323), False, 'import glob\n'), ((1171, 1212), 'neworder.Timeline', 'neworder.Timeline', (['(2011.25)', '(2050.25)', '[39]'], {}), '(2011.25, 2... |
# present and accept dispute processing
from flask import Blueprint, request, make_response, render_template, flash, redirect
from openarticlegauge.core import app
import openarticlegauge.util as util
import openarticlegauge.models as models
blueprint = Blueprint('issue', __name__)
@blueprint.route("/", methods=['... | [
"flask.render_template",
"openarticlegauge.util.request_wants_json",
"flask.flash",
"openarticlegauge.models.Issue.pull",
"flask.redirect",
"openarticlegauge.models.Issue",
"flask.make_response",
"flask.Blueprint",
"openarticlegauge.util.send_mail"
] | [((257, 285), 'flask.Blueprint', 'Blueprint', (['"""issue"""', '__name__'], {}), "('issue', __name__)\n", (266, 285), False, 'from flask import Blueprint, request, make_response, render_template, flash, redirect\n'), ((497, 522), 'openarticlegauge.util.request_wants_json', 'util.request_wants_json', ([], {}), '()\n', (... |
"""Tokenize a document.
*** NLTK tokenization and this module have been deprecated in favor of a
sklearn-based solution. However, NLTK may offer more options for tokenization,
stemming, etc., this module is retained for future reference.
"""
import re
import nltk
import toolz as tz
re_not_alpha = re.compile('[^a-zA... | [
"nltk.tokenize.word_tokenize",
"nltk.stem.lancaster.LancasterStemmer",
"nltk.corpus.stopwords.words",
"re.compile"
] | [((302, 325), 're.compile', 're.compile', (['"""[^a-zA-Z]"""'], {}), "('[^a-zA-Z]')\n", (312, 325), False, 'import re\n'), ((342, 380), 'nltk.corpus.stopwords.words', 'nltk.corpus.stopwords.words', (['"""english"""'], {}), "('english')\n", (369, 380), False, 'import nltk\n'), ((1215, 1253), 'nltk.stem.lancaster.Lancast... |
from unittest.mock import ANY, Mock, patch
import pytest
from streamlit_server_state.server_state_item import ServerStateItem
@pytest.fixture
def patch_is_rerunnable():
with patch(
"streamlit_server_state.server_state_item.is_rerunnable"
) as mock_is_rerunnable:
mock_is_rerunnable.return_val... | [
"unittest.mock.patch",
"unittest.mock.Mock",
"streamlit_server_state.server_state_item.ServerStateItem"
] | [((464, 470), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (468, 470), False, 'from unittest.mock import ANY, Mock, patch\n'), ((483, 500), 'streamlit_server_state.server_state_item.ServerStateItem', 'ServerStateItem', ([], {}), '()\n', (498, 500), False, 'from streamlit_server_state.server_state_item import ServerS... |
#!/usr/bin/env python
# Copyright (c) 2016, 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | [
"operator.attrgetter",
"struct.calcsize",
"os.path.exists",
"argparse.ArgumentParser",
"os.environ.get",
"os.path.join",
"struct.pack",
"os.path.split",
"commands.getstatusoutput",
"struct.unpack",
"os.path.basename",
"zlib.crc32"
] | [((1444, 1473), 'struct.calcsize', 'struct.calcsize', (['FS_ENTRY_FMT'], {}), '(FS_ENTRY_FMT)\n', (1459, 1473), False, 'import struct\n'), ((1761, 1790), 'commands.getstatusoutput', 'commands.getstatusoutput', (['cmd'], {}), '(cmd)\n', (1785, 1790), False, 'import commands\n'), ((2905, 2941), 'os.environ.get', 'os.envi... |
from functools import partial
from typing import List, Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
from torch import nn
from mmderain.models.common import sizeof
from mmderain.models.registry import BACKBONES
from mmderain.models.layers import SELayer_Modified
class ResidualBlock(nn.Modul... | [
"torch.nn.GroupNorm",
"torch.nn.Sigmoid",
"torch.nn.LeakyReLU",
"mmderain.models.common.sizeof",
"torch.nn.ModuleList",
"torch.nn.Sequential",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"mmderain.models.registry.BACKBONES.register_module",
"functools.partial",
"torch.nn.functional.relu... | [((8377, 8404), 'mmderain.models.registry.BACKBONES.register_module', 'BACKBONES.register_module', ([], {}), '()\n', (8402, 8404), False, 'from mmderain.models.registry import BACKBONES\n'), ((598, 629), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {'inplace': '(True)'}), '(0.2, inplace=True)\n', (610, 629), False... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-02-11 00:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('issue_order', '0004_auto_20170210_2358'),
]
operations = [
migrations.Alter... | [
"django.db.models.DecimalField",
"django.db.models.CharField",
"django.db.models.IntegerField"
] | [((411, 513), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'blank': '(True)', 'decimal_places': '(2)', 'max_digits': '(10)', 'null': '(True)', 'verbose_name': '"""Credit"""'}), "(blank=True, decimal_places=2, max_digits=10, null=True,\n verbose_name='Credit')\n", (430, 513), False, 'from django.db i... |
import dns
import dns.resolver
import dns.rdatatype
def dns_resolve(domain: str) -> list:
addrs = []
resolver = dns.resolver.Resolver(configure=False)
# Default to Google DNS
resolver.nameservers = ['8.8.8.8', '8.8.4.4']
try:
for answer in resolver.resolve(domain, 'A').response.answer:
... | [
"dns.resolver.Resolver"
] | [((123, 161), 'dns.resolver.Resolver', 'dns.resolver.Resolver', ([], {'configure': '(False)'}), '(configure=False)\n', (144, 161), False, 'import dns\n')] |
""""
File : kombu_messaging.py
Author : ian
Created : 09-28-2016
Last Modified By : ian
Last Modified On : 09-28-2016
***********************************************************************
The MIT License (MIT)
Copyright © 2016 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, t... | [
"uuid.UUID",
"re.compile",
"core.messaging.BrightsideMessageBody",
"uuid.uuid4",
"core.messaging.BrightsideMessageHeader",
"core.messaging.BrightsideMessage",
"core.messaging.BrightsideMessageType",
"core.exceptions.MessagingException"
] | [((2174, 2525), 're.compile', 're.compile', (['"""\n ( \\\\\\\\U........ # 8-digit hex escapes\n | \\\\\\\\u.... # 4-digit hex escapes\n | \\\\\\\\x.. # 2-digit hex escapes\n | \\\\\\\\[0-7]{1,3} # Octal escapes\n | \\\\\\\\N\\\\{[^}]+\\\\} # Unicode characters by name\n ... |
import numpy as np
def pline(x1, y1, x2, y2, x, y):
px = x2 - x1
py = y2 - y1
dd = px * px + py * py
u = ((x - x1) * px + (y - y1) * py) / max(1e-9, float(dd))
dx = x1 + u * px - x
dy = y1 + u * py - y
return dx * dx + dy * dy
def psegment(x1, y1, x2, y2, x, y):
px = x2 - x1
py =... | [
"numpy.array"
] | [((2149, 2165), 'numpy.array', 'np.array', (['nlines'], {}), '(nlines)\n', (2157, 2165), True, 'import numpy as np\n'), ((2167, 2184), 'numpy.array', 'np.array', (['nscores'], {}), '(nscores)\n', (2175, 2184), True, 'import numpy as np\n'), ((2056, 2106), 'numpy.array', 'np.array', (['[p + (q - p) * start, p + (q - p) ... |
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in wri... | [
"os.path.exists",
"monai.utils.module.optional_import",
"threading.Timer",
"os.path.join",
"os.path.realpath",
"platform.system",
"torch.cuda.is_available",
"monai.utils.module.get_torch_version_tuple",
"platform.python_version"
] | [((881, 904), 'os.path.realpath', 'path.realpath', (['__file__'], {}), '(__file__)\n', (894, 904), False, 'from os import path\n'), ((2056, 2088), 'os.path.join', 'path.join', (['dir_path', 'module_name'], {}), '(dir_path, module_name)\n', (2065, 2088), False, 'from os import path\n'), ((2606, 2631), 'torch.cuda.is_ava... |