code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from typing import Sequence, Union
import numpy as np
from scipy.ndimage.interpolation import rotate as np_rotate
from PIL.Image import Image
from torch import Tensor, tensor
from torchvision.transforms.functional import rotate
class ImageRotation(object):
def __init__(self, degree):
self.degree = degree... | [
"torch.tensor",
"torchvision.transforms.functional.rotate",
"PIL.Image.Image.fromarray",
"scipy.ndimage.interpolation.rotate"
] | [((443, 491), 'scipy.ndimage.interpolation.rotate', 'np_rotate', (['img'], {'angle': 'self.degree', 'reshape': '(False)'}), '(img, angle=self.degree, reshape=False)\n', (452, 491), True, 'from scipy.ndimage.interpolation import rotate as np_rotate\n'), ((1291, 1311), 'PIL.Image.Image.fromarray', 'Image.fromarray', (['i... |
# Course: CS261 - Data Structures
# Author: <NAME>
# Assignment: 06
# Description: Directed graph implementation.
from collections import deque
import heapq
class DirectedGraph:
"""
Class to implement directed weighted graph
- duplicate edges not allowed
- loops not allowed
- only positive edge w... | [
"heapq.heappop",
"heapq.heappush",
"collections.deque"
] | [((5981, 5988), 'collections.deque', 'deque', ([], {}), '()\n', (5986, 5988), False, 'from collections import deque\n'), ((7389, 7423), 'heapq.heappush', 'heapq.heappush', (['vertices', '(0, src)'], {}), '(vertices, (0, src))\n', (7403, 7423), False, 'import heapq\n'), ((8897, 8904), 'collections.deque', 'deque', ([], ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2020/5/14 20:41
# @Author: Mecthew
import time
import numpy as np
import pandas as pd
import scipy
from sklearn.svm import LinearSVC
from sklearn.linear_model import logistic
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import ac... | [
"sklearn.metrics.accuracy_score",
"numpy.abs",
"numpy.eye",
"scipy.sparse.diags",
"numpy.power",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.svm.LinearSVC",
"numpy.argmax",
"numpy.array",
"numpy.concatenate",
"scipy.sparse.coo_matrix",
"pandas.DataFrame",
"sklearn.linear_model.logistic.L... | [((452, 470), 'utils.logger.get_logger', 'get_logger', (['"""INFO"""'], {}), "('INFO')\n", (462, 470), False, 'from utils.logger import get_logger\n'), ((1327, 1338), 'time.time', 'time.time', ([], {}), '()\n', (1336, 1338), False, 'import time\n'), ((2410, 2461), 'numpy.concatenate', 'np.concatenate', (['[x_train_feat... |
import os
import scrapy
from scrapy.crawler import CrawlerProcess
import requests
from disaster_data.sources.noaa_coast.utils import get_geoinfo, get_fgdcinfo
class NoaaImageryCollections(scrapy.Spider):
name = 'noaa-coast-imagery-collections'
start_urls = [
'https://coast.noaa.gov/htdata/raster2/... | [
"scrapy.crawler.CrawlerProcess",
"requests.get",
"disaster_data.sources.noaa_coast.utils.get_fgdcinfo"
] | [((498, 634), 'scrapy.crawler.CrawlerProcess', 'CrawlerProcess', (["{'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',\n 'FEED_FORMAT': 'json', 'FEED_URI': outfile}"], {}), "({'USER_AGENT':\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'FEED_FORMAT':\n 'json', 'FEED_URI': outfile})\... |
import pytest
from rlo import factory
@pytest.mark.parametrize("use_subtree_match_edges", [True, False])
@pytest.mark.parametrize("loss", ["pinball=0.6", "huber"])
def test_torch_model_from_config(use_subtree_match_edges, loss):
# Check we can construct a Model
config = {
"num_embeddings": 3,
... | [
"pytest.mark.parametrize",
"rlo.factory.single_regressor_from_config",
"rlo.factory.torch_model_from_config",
"rlo.factory.data_converter_from_config"
] | [((42, 107), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""use_subtree_match_edges"""', '[True, False]'], {}), "('use_subtree_match_edges', [True, False])\n", (65, 107), False, 'import pytest\n'), ((109, 166), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""loss"""', "['pinball=0.6', 'huber']"... |
# coding=utf-8
# Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | [
"cx_Freeze.Executable",
"cx_Freeze.setup"
] | [((860, 1144), 'cx_Freeze.setup', 'setup', ([], {'name': '"""pyprobe"""', 'version': '"""1.0"""', 'description': '"""x"""', 'options': "{'build_exe': {'include_files': includefiles, 'packages': packages,\n 'excludes': [], 'includes': ['requests']}, 'bdist_mac': {'bundle_name':\n 'pyprobe'}}", 'executables': 'exec... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import redirect, request, session
from werkzeug.except... | [
"indico.core.db.db.session.commit",
"indico.modules.events.static.tasks.build_static_site.delay",
"indico.modules.events.static.views.WPStaticSites.render_template",
"indico.modules.events.static.models.static.StaticSite.get_one",
"indico.modules.events.static.models.static.StaticSite.requested_dt.desc",
... | [((929, 1023), 'indico.modules.events.static.views.WPStaticSites.render_template', 'WPStaticSites.render_template', (['"""static_sites.html"""', 'self.event'], {'static_sites': 'static_sites'}), "('static_sites.html', self.event, static_sites\n =static_sites)\n", (958, 1023), False, 'from indico.modules.events.stati... |
from os import path
import autolens as al
import autolens.plot as aplt
from test_autogalaxy.simulators.imaging import instrument_util
test_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "..", "..")
def pixel_scale_from_instrument(instrument):
"""
Returns the pixel scale from... | [
"autolens.Tracer.from_galaxies",
"autolens.plot.Tracer.figures",
"os.path.join",
"autolens.plot.Imaging.subplot_imaging",
"os.path.realpath",
"autolens.plot.imaging.individual",
"test_autogalaxy.simulators.imaging.instrument_util.pixel_scale_from_instrument",
"autolens.plot.Output",
"autolens.Simula... | [((5330, 5389), 'test_autogalaxy.simulators.imaging.instrument_util.grid_from_instrument', 'instrument_util.grid_from_instrument', ([], {'instrument': 'instrument'}), '(instrument=instrument)\n', (5366, 5389), False, 'from test_autogalaxy.simulators.imaging import instrument_util\n'), ((5585, 5627), 'autolens.Tracer.fr... |
from .conftest import GoProCameraTest
from socket import timeout
from urllib import error
class GpControlSetTest(GoProCameraTest):
def test_gp_control_set(self):
# on success, this is an empty json blob
self.responses['/gp/gpControl/setting/foo/bar'] = '{}'
assert '{}' == self.goprocam.gp... | [
"socket.timeout"
] | [((600, 609), 'socket.timeout', 'timeout', ([], {}), '()\n', (607, 609), False, 'from socket import timeout\n')] |
from system.db import db
from telegram_bot.handlers.utils.decorators import remember_new_user, \
send_typing, write_logs
from telegram_bot.handlers.utils.menu_entries import MenuEntry
from telegram_bot.handlers.utils.reply_markup import create_main_reply_markup
from telegram_bot.models import User
@write_logs
@se... | [
"system.db.db.session.query",
"system.db.db.session.commit",
"telegram_bot.handlers.utils.reply_markup.create_main_reply_markup"
] | [((540, 559), 'system.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (557, 559), False, 'from system.db import db\n'), ((685, 711), 'telegram_bot.handlers.utils.reply_markup.create_main_reply_markup', 'create_main_reply_markup', ([], {}), '()\n', (709, 711), False, 'from telegram_bot.handlers.utils.reply... |
# -*- coding: utf-8-*-
import os
import base64
import tempfile
import pypinyin
from aip import AipSpeech
from . import utils, config, constants
from robot import logging
from pathlib import Path
from pypinyin import lazy_pinyin
from pydub import AudioSegment
from abc import ABCMeta, abstractmethod
from .sdk import Tenc... | [
"os.path.exists",
"aip.AipSpeech",
"pathlib.Path",
"os.path.join",
"pypinyin.lazy_pinyin",
"base64.b64decode",
"tempfile.NamedTemporaryFile",
"pydub.AudioSegment.silent",
"robot.logging.getLogger",
"pydub.AudioSegment.from_wav"
] | [((370, 397), 'robot.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (387, 397), False, 'from robot import logging\n'), ((1518, 1565), 'os.path.join', 'os.path.join', (['constants.CONFIG_PATH', 'self.voice'], {}), '(constants.CONFIG_PATH, self.voice)\n', (1530, 1565), False, 'import os\n'),... |
# -*- coding: utf-8 -*-
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# pylint: disable= no-member, arguments-differ, invalid-name
#
# Utilities for using pre-trained models.
import torch
from dgl.data.utils import _get_dgl_url, download
from .molecule... | [
"torch.load",
"dgl.data.utils.download",
"dgl.data.utils._get_dgl_url"
] | [((1234, 1261), 'dgl.data.utils._get_dgl_url', '_get_dgl_url', (['model_postfix'], {}), '(model_postfix)\n', (1246, 1261), False, 'from dgl.data.utils import _get_dgl_url, download\n'), ((1340, 1404), 'dgl.data.utils.download', 'download', (['url_to_pretrained'], {'path': 'local_pretrained_path', 'log': 'log'}), '(url_... |
import numpy as np
import unittest
from chainer.dataset import DatasetMixin
from chainer import testing
from chainercv.utils import assert_is_bbox_dataset
from chainercv.utils import generate_random_bbox
class BboxDataset(DatasetMixin):
def __init__(self, options=(), empty_bbox=False):
self.options = o... | [
"chainercv.utils.generate_random_bbox",
"numpy.random.randint",
"chainer.testing.run_module",
"chainercv.utils.assert_is_bbox_dataset"
] | [((2565, 2603), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (2583, 2603), False, 'from chainer import testing\n'), ((451, 494), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(3, 48, 64)'}), '(0, 256, size=(3, 48, 64))\n', (468... |
"""Provide default settgins"""
from pathlib import Path
BIOPIPEN_DIR = Path(__file__).parent.parent.resolve()
REPORT_DIR = BIOPIPEN_DIR / "reports"
SCRIPT_DIR = BIOPIPEN_DIR / "scripts"
| [
"pathlib.Path"
] | [((72, 86), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (76, 86), False, 'from pathlib import Path\n')] |
#!/usr/bin/python3
import shutil
import os
import base64
from time import sleep
import flask
import requests.exceptions
import blueprint
from flask_cors import CORS
from confhttpproxy import ProxyRouter, ProxyRouterException
from flask import Flask, jsonify
import rest_routes
from lmsrvcore.utilities.migrate import... | [
"flask_cors.CORS",
"flask.Flask",
"base64.b64encode",
"time.sleep",
"flask.jsonify",
"os.path.exists",
"os.listdir",
"lmsrvcore.utilities.migrate.migrate_work_dir_structure_v2",
"os.path.isdir",
"os.unlink",
"gtmcore.labbook.lock.reset_all_locks",
"gtmcore.auth.identity.get_identity_manager_cl... | [((688, 709), 'gtmcore.logging.LMLogger.get_logger', 'LMLogger.get_logger', ([], {}), '()\n', (707, 709), False, 'from gtmcore.logging import LMLogger\n'), ((3657, 3678), 'flask.Flask', 'Flask', (['"""lmsrvlabbook"""'], {}), "('lmsrvlabbook')\n", (3662, 3678), False, 'from flask import Flask, jsonify\n'), ((3695, 3709)... |
import click
import logging
import sys
from typing import Tuple
from kubails.commands import helpers
from kubails.services.config_store import ConfigStore
from kubails.services.service import Service
from kubails.resources.templates import SERVICE_TEMPLATES
from kubails.utils.command_helpers import log_command_args_fac... | [
"logging.getLogger",
"click.Choice",
"click.argument",
"click.group",
"click.option",
"kubails.services.service.Service",
"sys.exit",
"kubails.utils.command_helpers.log_command_args_factory",
"kubails.commands.helpers.generate_service",
"kubails.services.config_store.ConfigStore"
] | [((336, 363), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (353, 363), False, 'import logging\n'), ((383, 436), 'kubails.utils.command_helpers.log_command_args_factory', 'log_command_args_factory', (['logger', '"""Service \'{}\' args"""'], {}), '(logger, "Service \'{}\' args")\n', (407,... |
from math import exp,sqrt
from random import randrange
class neurone:
def __init__(self,a,b):
self.a=a
self.b=b
def proceed(self,z):
t = z[0]*self.a + z[1]*self.b
return 1/(1+exp(-t))
n = 100
X_app = [(randrange(-500,501)/1000,randrange(-500,501)/1000) for i in range(n)]
Y_app ... | [
"math.exp",
"random.randrange"
] | [((244, 264), 'random.randrange', 'randrange', (['(-500)', '(501)'], {}), '(-500, 501)\n', (253, 264), False, 'from random import randrange\n'), ((269, 289), 'random.randrange', 'randrange', (['(-500)', '(501)'], {}), '(-500, 501)\n', (278, 289), False, 'from random import randrange\n'), ((216, 223), 'math.exp', 'exp',... |
import json
import datetime
import mimetypes
from urllib.parse import urlparse
from arcgis import env
from arcgis.gis import GIS
from arcgis.gis import Item
from ._ref import reference
class JournalStoryMap(object):
"""
Represents a Journal Story Map
=============== ===================================... | [
"urllib.parse.urlparse",
"json.dumps",
"uuid.uuid4",
"os.path.dirname",
"datetime.datetime.now",
"mimetypes.guess_type"
] | [((1826, 1854), 'json.dumps', 'json.dumps', (['self._properties'], {}), '(self._properties)\n', (1836, 1854), False, 'import json\n'), ((23626, 23658), 'urllib.parse.urlparse', 'urlparse', (['self._gis._con.baseurl'], {}), '(self._gis._con.baseurl)\n', (23634, 23658), False, 'from urllib.parse import urlparse\n'), ((68... |
import sys
import os
sys.path.append(os.getcwd())
import argparse
import numpy as np
import pmdarima
import torch
import torch.nn.functional as F
from torch import nn
from fusions.common_fusions import Stack
from unimodals.common_models import LSTMWithLinear
from datasets.stocks.get_data import get_dataloader
parser... | [
"torch.ones_like",
"argparse.ArgumentParser",
"datasets.stocks.get_data.get_dataloader",
"torch.mean",
"os.getcwd",
"torch.nn.MSELoss",
"torch.tensor",
"torch.cat",
"pmdarima.arima.auto_arima"
] | [((323, 348), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (346, 348), False, 'import argparse\n'), ((692, 764), 'datasets.stocks.get_data.get_dataloader', 'get_dataloader', (['stocks', 'stocks', '[args.target_stock]'], {'modality_first': '(True)'}), '(stocks, stocks, [args.target_stock], mod... |
import os
from tests import PMGTestCase
from tests.fixtures import dbfixture, CommitteeQuestionData
class TestQuestionAnswer(PMGTestCase):
def setUp(self):
super(TestQuestionAnswer, self).setUp()
self.fx = dbfixture.data(CommitteeQuestionData,)
self.fx.setup()
def tearDown(self):
... | [
"tests.fixtures.dbfixture.data"
] | [((229, 266), 'tests.fixtures.dbfixture.data', 'dbfixture.data', (['CommitteeQuestionData'], {}), '(CommitteeQuestionData)\n', (243, 266), False, 'from tests.fixtures import dbfixture, CommitteeQuestionData\n')] |
from datetime import datetime
# Rest framework
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, UpdateModelMixin, CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import Generic... | [
"datetime.datetime.min.time",
"datetime.datetime.strptime",
"csv_analyzer.apps.mongodb.utils.MongoDBConnection",
"csv_analyzer.apps.dataset.tasks.populate_dataset_file.delay",
"rest_framework.response.Response",
"csv_analyzer.apps.dataset.serializers.DataSetModelSerializer",
"csv_analyzer.apps.dataset.m... | [((3654, 3712), 'rest_framework.decorators.action', 'action', ([], {'detail': '(True)', 'methods': "['POST']", 'url_path': '"""add-file"""'}), "(detail=True, methods=['POST'], url_path='add-file')\n", (3660, 3712), False, 'from rest_framework.decorators import action\n'), ((1623, 1637), 'rest_framework.response.Respons... |
import csv
import os
import shutil
from datetime import datetime
from grid import *
#from cluster import *
from regions import *
start_time = datetime.now()
print("Allocating...")
#grid2
#gridSystem = GridSystem(-74.04, -73.775, 5, 40.63, 40.835, 5)
#gridname = "grid2"
#grid3
#gridSystem = GridSystem(-74.02, -73.9... | [
"datetime.datetime.now"
] | [((144, 158), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (156, 158), False, 'from datetime import datetime\n'), ((1233, 1247), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1245, 1247), False, 'from datetime import datetime\n')] |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | [
"haiku._src.stateful.grad",
"haiku._src.stateful.cond",
"jax.ad.deflinear",
"numpy.testing.assert_allclose",
"haiku._src.stateful.remat",
"absl.testing.absltest.main",
"jax.numpy.array",
"haiku._src.stateful.jit",
"haiku._src.base.set_state",
"jax.core.Primitive",
"haiku._src.stateful.value_and_... | [((5840, 5873), 'jax.core.Primitive', 'jax.core.Primitive', (['"""hk_callback"""'], {}), "('hk_callback')\n", (5858, 5873), False, 'import jax\n'), ((5933, 5963), 'jax.ad.deflinear', 'jax.ad.deflinear', (['prim', 'b_impl'], {}), '(prim, b_impl)\n', (5949, 5963), False, 'import jax\n'), ((6456, 6471), 'absl.testing.absl... |
def run_rename(args):
from pocketbook.address_book import AddressBook
from pocketbook.key_store import KeyStore
address_book = AddressBook()
key_store = KeyStore()
# make sure that the new name is not present either as a key, or as an address
new_present = args.new in address_book.keys() or ar... | [
"pocketbook.key_store.KeyStore",
"pocketbook.address_book.AddressBook"
] | [((140, 153), 'pocketbook.address_book.AddressBook', 'AddressBook', ([], {}), '()\n', (151, 153), False, 'from pocketbook.address_book import AddressBook\n'), ((170, 180), 'pocketbook.key_store.KeyStore', 'KeyStore', ([], {}), '()\n', (178, 180), False, 'from pocketbook.key_store import KeyStore\n')] |
from app.database import MOCK_PRODUCT_DATA
import re
from app.products.base_handler import BaseHandler
class ProductInfoHandler(BaseHandler):
"""
A class used to represent a mini-bot to handle product queries.
"""
def __init__(self) -> None:
super().__init__()
def create_match_paterns(se... | [
"re.compile"
] | [((389, 445), 're.compile', 're.compile', (['"""(price|cost|how much|money)"""', 're.IGNORECASE'], {}), "('(price|cost|how much|money)', re.IGNORECASE)\n", (399, 445), False, 'import re\n'), ((489, 541), 're.compile', 're.compile', (['"""(stock|how many|amount)"""', 're.IGNORECASE'], {}), "('(stock|how many|amount)', r... |
import sys
import copy
import pprint
pp = pprint.PrettyPrinter(width=120)
import inspect
import numpy as np
from .. import __version__
from .. import qcvars
from ..driver.driver_helpers import print_variables
from ..exceptions import *
from ..molecule import Molecule
from ..pdict import PreservingDict
from .worker im... | [
"json.loads",
"psi4.core.Matrix.from_serial",
"json.dumps",
"sys._getframe",
"pprint.PrettyPrinter",
"copy.deepcopy"
] | [((42, 73), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'width': '(120)'}), '(width=120)\n', (62, 73), False, 'import pprint\n'), ((1234, 1256), 'copy.deepcopy', 'copy.deepcopy', (['options'], {}), '(options)\n', (1247, 1256), False, 'import copy\n'), ((1881, 1900), 'json.dumps', 'json.dumps', (['psi4rec'], {... |
import unittest
from typing import Dict, List
from src.math_challenge import Challenge, DEFAULT_EMPTY_ANS
from src.student_info import StudentInfo
class TestChallenge(unittest.TestCase):
def test_preprocess(self):
self.assertEqual(Challenge.preprocess_ans("a. 37th floor, b. 42nd floor, c. 39th floor, d. ... | [
"unittest.main",
"src.math_challenge.Challenge.preprocess_ans",
"src.math_challenge.Challenge.load_gold_answers",
"src.math_challenge.Challenge.load_student_answers"
] | [((1739, 1754), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1752, 1754), False, 'import unittest\n'), ((975, 1043), 'src.math_challenge.Challenge.load_gold_answers', 'Challenge.load_gold_answers', ([], {'fp': '"""test_data/test_correct_answers.csv"""'}), "(fp='test_data/test_correct_answers.csv')\n", (1002, 10... |
import hlt
import logging
from collections import OrderedDict
# GAME START
game = hlt.Game("Spoof_v7")
logging.info('Starting my %s bot!', game._name)
TURN = 0
def navigate(ship, entity, multiplier = 1):
navigate_command = ship.navigate(
ship.closest_point_to(entity),
game_map,
speed=int(h... | [
"hlt.entity.Position",
"logging.info",
"hlt.Game"
] | [((83, 103), 'hlt.Game', 'hlt.Game', (['"""Spoof_v7"""'], {}), "('Spoof_v7')\n", (91, 103), False, 'import hlt\n'), ((104, 151), 'logging.info', 'logging.info', (['"""Starting my %s bot!"""', 'game._name'], {}), "('Starting my %s bot!', game._name)\n", (116, 151), False, 'import logging\n'), ((2005, 2030), 'hlt.entity.... |
import pytest
from eph.horizons import *
@pytest.fixture(params=[
('earth', '399'),
('\'earth\'', '399'),
('Earth', '399'),
('399', '399'),
('\'399\'', '399'),
('pluto', 'pluto'),
])
def codify_obj_data(request):
return request.param
def test_codify_obj(codify_obj_data):
data, resul... | [
"pytest.fixture"
] | [((45, 182), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[(\'earth\', \'399\'), ("\'earth\'", \'399\'), (\'Earth\', \'399\'), (\'399\', \'399\'), (\n "\'399\'", \'399\'), (\'pluto\', \'pluto\')]'}), '(params=[(\'earth\', \'399\'), ("\'earth\'", \'399\'), (\'Earth\',\n \'399\'), (\'399\', \'399\'), ("\'39... |
import os
import shutil
def delete_configs(config, dataset, username):
if config != 'all':
paths = [os.path.join('user_data', username, dataset, config)]
else:
paths = [os.path.join('user_data', username, dataset, d) for d in
os.listdir(os.path.join('user_data', username, data... | [
"os.path.join",
"shutil.rmtree"
] | [((558, 612), 'os.path.join', 'os.path.join', (['APP_ROOT', '"""user_data"""', 'username', 'dataset'], {}), "(APP_ROOT, 'user_data', username, dataset)\n", (570, 612), False, 'import os\n'), ((655, 674), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (668, 674), False, 'import shutil\n'), ((476, 495), 's... |
import os
import bz2
import json
import random
import pickle
from collections import defaultdict, Counter
from tqdm import tqdm
import torch
from data.crosswoz.data_process.dst.trade_preprocess import (
EXPERIMENT_DOMAINS,
Lang,
get_seq,
get_slot_information,
)
class CNEmbedding:
def __init__(s... | [
"os.path.exists",
"random.uniform",
"data.crosswoz.data_process.dst.trade_preprocess.Lang",
"torch.log",
"pickle.dump",
"torch.stack",
"os.path.join",
"tqdm.tqdm",
"pickle.load",
"collections.Counter",
"data.crosswoz.data_process.dst.trade_preprocess.get_seq",
"collections.defaultdict",
"dat... | [((2716, 2732), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (2727, 2732), False, 'from collections import defaultdict, Counter\n'), ((7173, 7203), 'data.crosswoz.data_process.dst.trade_preprocess.get_slot_information', 'get_slot_information', (['ontology'], {}), '(ontology)\n', (7193, 7203), Fal... |
from django.conf.urls import url
from django.views.generic import TemplateView
from reports import views
urlpatterns = [
url(r'balance/$', views.balance, name='report_balance'),
url(r'performance/$', views.performance, name='report_performance'),
url(r'last_activity/$', views.last_activity, name='last_ac... | [
"django.views.generic.TemplateView.as_view",
"django.conf.urls.url",
"reports.views.CollectionListView.as_view"
] | [((128, 182), 'django.conf.urls.url', 'url', (['"""balance/$"""', 'views.balance'], {'name': '"""report_balance"""'}), "('balance/$', views.balance, name='report_balance')\n", (131, 182), False, 'from django.conf.urls import url\n'), ((189, 255), 'django.conf.urls.url', 'url', (['"""performance/$"""', 'views.performanc... |
from pycam.Utils.events import get_event_handler, get_mainloop
class ProgressContext:
def __init__(self, title):
self._title = title
self._progress = get_event_handler().get("progress")
def __enter__(self):
if self._progress:
self._progress.update(text=self._title, percen... | [
"pycam.Utils.events.get_mainloop",
"pycam.Utils.events.get_event_handler"
] | [((680, 694), 'pycam.Utils.events.get_mainloop', 'get_mainloop', ([], {}), '()\n', (692, 694), False, 'from pycam.Utils.events import get_event_handler, get_mainloop\n'), ((173, 192), 'pycam.Utils.events.get_event_handler', 'get_event_handler', ([], {}), '()\n', (190, 192), False, 'from pycam.Utils.events import get_ev... |
#! /usr/bin/env python
# License: Apache 2.0. See LICENSE file in root directory.
#
# For simple behaviors that can run syncronously, Python provides
# a simple way to implement this. Add the work of your behavior
# in the execute_cb callback
#
import rospy
import actionlib
import behavior_common.msg
import time
imp... | [
"rospy.init_node",
"actionlib.SimpleActionServer",
"time.sleep",
"rospy.Rate",
"rospy.spin",
"rospy.get_name",
"rospy.Publisher",
"rospy.loginfo",
"actionlib.SimpleActionClient"
] | [((5135, 5167), 'rospy.init_node', 'rospy.init_node', (['"""ship_behavior"""'], {}), "('ship_behavior')\n", (5150, 5167), False, 'import rospy\n'), ((5218, 5230), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (5228, 5230), False, 'import rospy\n'), ((1132, 1266), 'actionlib.SimpleActionServer', 'actionlib.SimpleActionS... |
from collections import defaultdict, namedtuple
import torch
# When using the sliding window trick for long sequences,
# we take the representation of each token with maximal context.
# Take average of the BERT embeddings of these BPE sub-tokens
# as the embedding for the word.
# Take *weighted* average of the word ... | [
"torch.mean",
"collections.namedtuple",
"collections.defaultdict",
"torch.Tensor"
] | [((4069, 4111), 'collections.namedtuple', 'namedtuple', (['"""DocSpan"""', "['start', 'length']"], {}), "('DocSpan', ['start', 'length'])\n", (4079, 4111), False, 'from collections import defaultdict, namedtuple\n'), ((1781, 1808), 'torch.mean', 'torch.mean', (['out_features', '(0)'], {}), '(out_features, 0)\n', (1791,... |
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
(r'^$', 'suggestions.views.list_all'),
(r'^post/$', 'suggestions.views.add_suggestion'),
(r'^vote/(?P<suggestion_id>.*)/$', 'suggestions.views.add_vote'),
(r'^unvote/(?P<suggestion_id>.*)/$', 'suggestions.views.remove_v... | [
"django.conf.urls.defaults.patterns"
] | [((76, 389), 'django.conf.urls.defaults.patterns', 'patterns', (['""""""', "('^$', 'suggestions.views.list_all')", "('^post/$', 'suggestions.views.add_suggestion')", "('^vote/(?P<suggestion_id>.*)/$', 'suggestions.views.add_vote')", "('^unvote/(?P<suggestion_id>.*)/$', 'suggestions.views.remove_vote')", "('^close/(?P<s... |
import json
import os.path
class StorageHelper:
__document = None
__path = None
@staticmethod
def write(key, data):
StorageHelper.__init()
StorageHelper.__document[key] = json.dumps(data)
StorageHelper.__store()
@staticmethod
def read(key):
StorageHelper.__ini... | [
"json.load",
"json.loads",
"json.dumps",
"json.dump"
] | [((206, 222), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (216, 222), False, 'import json\n'), ((433, 449), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (443, 449), False, 'import json\n'), ((1129, 1170), 'json.dump', 'json.dump', (['StorageHelper.__document', 'file'], {}), '(StorageHelper.__docu... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | [
"os.path.exists",
"os.path.getsize",
"collections.namedtuple",
"random.uniform",
"os.makedirs",
"os.path.join",
"time.sleep",
"six.moves.urllib.request.urlretrieve",
"shutil.copy"
] | [((954, 1007), 'collections.namedtuple', 'collections.namedtuple', (['"""Dataset"""', "['data', 'target']"], {}), "('Dataset', ['data', 'target'])\n", (976, 1007), False, 'import collections\n'), ((1019, 1086), 'collections.namedtuple', 'collections.namedtuple', (['"""Datasets"""', "['train', 'validation', 'test']"], {... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import sys
import argparse
import os
import re
import sqlite3
import requests
import bs4
from termcolor import colored
# Python2 compatibility
if sys.version_info[0] == 2:
reload(sys)
sys.setdefaultencoding('utf-8')
# Default data... | [
"sys.setdefaultencoding",
"termcolor.colored",
"argparse.ArgumentParser",
"re.compile",
"os.path.join",
"re.match",
"requests.get",
"bs4.BeautifulSoup",
"os.mkdir",
"sys.exit",
"re.sub",
"os.path.expanduser"
] | [((273, 304), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (295, 304), False, 'import sys\n'), ((373, 396), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (391, 396), False, 'import os\n'), ((1115, 1152), 'requests.get', 'requests.get', (['url'], {... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Title: GCN models
Description:
The original Graph convolutional network model and GCN layer.
Refer to: https://arxiv.org/abs/1609.02907
"""
# =======================================
# @author Zhibin.Lu
# @email <EMAIL>
# =======================================
imp... | [
"torch.nn.Dropout",
"torch.zeros",
"torch.randn"
] | [((1233, 1257), 'torch.nn.Dropout', 'nn.Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (1243, 1257), True, 'import torch.nn as nn\n'), ((2688, 2712), 'torch.nn.Dropout', 'nn.Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (2698, 2712), True, 'import torch.nn as nn\n'), ((1148, 1174), 'torch.zeros', 'torch.... |
#Method-1 guess the number game
import random
number = random.randint(1,10)
guess = 0
count = 0
print("You can exit the game anytime. Just enter 'exit'.")
while guess != number and guess != "exit":
guess = input("Guess a number between 1 to 10 :- ")
if guess == "exit":
print("Closing the game...")
... | [
"random.randint"
] | [((56, 77), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (70, 77), False, 'import random\n')] |
"""Solvates a host, inserts guest(s) into solvated host, equilibrates
"""
import os
import time
import tempfile
import numpy as np
from rdkit import Chem
from md import builders, minimizer
from fe import pdb_writer, free_energy
from ff import Forcefield
from ff.handlers.deserialize import deserialize_handlers
from t... | [
"rdkit.Chem.SDMolSupplier",
"os.remove",
"os.path.exists",
"rdkit.Chem.MolFromPDBFile",
"argparse.ArgumentParser",
"docking.report.too_much_force",
"numpy.linspace",
"fe.free_energy.AbsoluteFreeEnergy",
"numpy.concatenate",
"docking.report.report_step",
"timemachine.lib.custom_ops.Context",
"t... | [((2726, 2769), 'md.builders.build_protein_system', 'builders.build_protein_system', (['host_pdbfile'], {}), '(host_pdbfile)\n', (2755, 2769), False, 'from md import builders, minimizer\n'), ((2798, 2840), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': '""".pdb"""', 'text': '(True)'}), "(suffix='.pdb', text=Tr... |
import unittest
from unittest import TestCase
from src.gifGenerator import GifGenerator
class TestGifGenerator(TestCase):
def setUp(self) -> None:
self.gg = GifGenerator()
def test_set_text_position(self):
position = (50, 90)
self.gg.setTextPosition(position)
self.assertEqua... | [
"unittest.main",
"src.gifGenerator.GifGenerator"
] | [((659, 674), 'unittest.main', 'unittest.main', ([], {}), '()\n', (672, 674), False, 'import unittest\n'), ((173, 187), 'src.gifGenerator.GifGenerator', 'GifGenerator', ([], {}), '()\n', (185, 187), False, 'from src.gifGenerator import GifGenerator\n')] |
"""
pyexcel.sources.file
~~~~~~~~~~~~~~~~~~~
Representation of file sources
:copyright: (c) 2015-2016 by Onni Software Ltd.
:license: New BSD License
"""
from pyexcel import params
from pyexcel.factory import FileSource
from pyexcel.sources.rendererfactory import RendererFactory
from... | [
"pyexcel.sources.rendererfactory.RendererFactory.register_renderers",
"pyexcel.sources.rendererfactory.RendererFactory.renderer_factories.keys",
"pyexcel.sources.rendererfactory.RendererFactory.get_renderer"
] | [((358, 412), 'pyexcel.sources.rendererfactory.RendererFactory.register_renderers', 'RendererFactory.register_renderers', (['renderer.renderers'], {}), '(renderer.renderers)\n', (392, 412), False, 'from pyexcel.sources.rendererfactory import RendererFactory\n'), ((459, 509), 'pyexcel.sources.rendererfactory.RendererFac... |
import pathlib
from setuptools import setup, find_packages
HERE = pathlib.Path(__file__).parent
VERSION = '0.1.0'
PACKAGE_NAME = 'MDF_DALEC_GRASS'
AUTHOR = '<NAME>'
AUTHOR_EMAIL = '<EMAIL>'
URL = 'https://github.com/vmyrgiotis/MDF_DALEC_GRASS'
LICENSE = 'MIT'
DESCRIPTION = 'A Bayesian model-data fusion algorithm for... | [
"setuptools.find_packages",
"pathlib.Path"
] | [((67, 89), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (79, 89), False, 'import pathlib\n'), ((874, 889), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (887, 889), False, 'from setuptools import setup, find_packages\n')] |
import setuptools
from croo import croo_args
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='croo',
version=croo_args.__version__,
scripts=['bin/croo'],
python_requires='>3.4.1',
author='<NAME>',
author_email='<EMAIL>',
description='CRomwell Outp... | [
"setuptools.find_packages"
] | [((484, 538), 'setuptools.find_packages', 'setuptools.find_packages', ([], {'exclude': "['examples', 'docs']"}), "(exclude=['examples', 'docs'])\n", (508, 538), False, 'import setuptools\n')] |
from typing import Dict
import numpy as np
from ..envs.env import StructuralModel
from ..utils.lik_func import *
from ..utils.useful_class import ParameterGrid
class Estimator(ABC):
"""An Estimator takes in a (trained) solver and relevant params
and outputs estimated structural params
"""
def __... | [
"numpy.append",
"numpy.eye"
] | [((1986, 2027), 'numpy.eye', 'np.eye', (["self.estimator_params['n_moment']"], {}), "(self.estimator_params['n_moment'])\n", (1992, 2027), True, 'import numpy as np\n'), ((2800, 2824), 'numpy.append', 'np.append', (['moments', 'mean'], {}), '(moments, mean)\n', (2809, 2824), True, 'import numpy as np\n'), ((2898, 2926)... |
from django.db import models
from django.contrib.auth.models import User
class Link(models.Model):
url = models.URLField()
title = models.CharField(max_length=255)
reporter = models.ForeignKey(
User,
on_delete=models.SET_NULL,
related_name='reported_links',
null=True,
... | [
"django.db.models.URLField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.ForeignKey"
] | [((111, 128), 'django.db.models.URLField', 'models.URLField', ([], {}), '()\n', (126, 128), False, 'from django.db import models\n'), ((141, 173), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (157, 173), False, 'from django.db import models\n'), ((189, 299), 'dj... |
from prometheus_client import Counter
from raiden.utils.typing import TokenAmount
from raiden_libs.metrics import ( # noqa: F401, pylint: disable=unused-import
ERRORS_LOGGED,
EVENTS_EXCEPTIONS_RAISED,
EVENTS_PROCESSING_TIME,
MESSAGES_EXCEPTIONS_RAISED,
MESSAGES_PROCESSING_TIME,
REGISTRY,
E... | [
"raiden_libs.metrics.get_metrics_for_label"
] | [((950, 991), 'raiden_libs.metrics.get_metrics_for_label', 'get_metrics_for_label', (['REWARD_CLAIMS', 'who'], {}), '(REWARD_CLAIMS, who)\n', (971, 991), False, 'from raiden_libs.metrics import ERRORS_LOGGED, EVENTS_EXCEPTIONS_RAISED, EVENTS_PROCESSING_TIME, MESSAGES_EXCEPTIONS_RAISED, MESSAGES_PROCESSING_TIME, REGISTR... |
# modified from TikNib/tiknib/ida/fetch_funcdata_v7.5.py
import os
import sys
import string
from hashlib import sha1
from collections import defaultdict
import time
import pprint as pp
import idautils
import idc
import idaapi
import ida_pro
import ida_nalt
import ida_bytes
sys.path.append(os.path.... | [
"idc.get_idb_path",
"idautils.DataRefsFrom",
"idautils.Functions",
"hashlib.sha1",
"idc.get_func_name",
"os.path.exists",
"idc.get_str_type",
"idaapi.get_imagebase",
"tiknib.utils.store_func_data",
"ida_nalt.get_input_file_path",
"tiknib.utils.get_arch",
"traceback.print_exc",
"idaapi.get_fu... | [((9548, 9558), 'tiknib.utils.init_idc', 'init_idc', ([], {}), '()\n', (9556, 9558), False, 'from tiknib.utils import demangle, get_arch, init_idc, parse_fname, store_func_data\n'), ((312, 339), 'os.path.abspath', 'os.path.abspath', (['"""./TikNib"""'], {}), "('./TikNib')\n", (327, 339), False, 'import os\n'), ((600, 6... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: MIT-0
*
* 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... | [
"json.dumps",
"aws_lambda_powertools.Logger"
] | [((1343, 1361), 'aws_lambda_powertools.Logger', 'Logger', ([], {'child': '(True)'}), '(child=True)\n', (1349, 1361), False, 'from aws_lambda_powertools import Logger\n'), ((7209, 7238), 'json.dumps', 'json.dumps', (['AI_OPT_OUT_POLICY'], {}), '(AI_OPT_OUT_POLICY)\n', (7219, 7238), False, 'import json\n')] |
import numpy
import pandas
import hts.hierarchy
from hts.functions import (
_create_bl_str_col,
get_agg_series,
get_hierarchichal_df,
to_sum_mat,
)
def test_sum_mat_uv(uv_tree):
mat, sum_mat_labels = to_sum_mat(uv_tree)
assert isinstance(mat, numpy.ndarray)
shp = mat.shape
assert shp[... | [
"hts.functions.get_hierarchichal_df",
"hts.functions._create_bl_str_col",
"hts.functions.get_agg_series",
"numpy.array",
"pandas.DataFrame",
"numpy.testing.assert_array_equal",
"hts.functions.to_sum_mat"
] | [((223, 242), 'hts.functions.to_sum_mat', 'to_sum_mat', (['uv_tree'], {}), '(uv_tree)\n', (233, 242), False, 'from hts.functions import _create_bl_str_col, get_agg_series, get_hierarchichal_df, to_sum_mat\n'), ((448, 467), 'hts.functions.to_sum_mat', 'to_sum_mat', (['mv_tree'], {}), '(mv_tree)\n', (458, 467), False, 'f... |
import os
import warnings
warnings.simplefilter('always')
test_dir = os.path.dirname(os.path.abspath(__file__))
DATABASES = {
'default': {
'NAME': os.path.join(test_dir, 'db.sqlite'),
'ENGINE': 'django.db.backends.sqlite3',
},
}
USE_I18N = True
USE_L10N = True
INSTALLED_APPS = [
'django.... | [
"warnings.simplefilter",
"os.path.abspath",
"os.path.join"
] | [((26, 57), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (47, 57), False, 'import warnings\n'), ((86, 111), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (101, 111), False, 'import os\n'), ((549, 584), 'os.path.join', 'os.path.join', (['test_dir',... |
import json
import logging
import unittest
from typing import Dict
from SPARQLWrapper import JSONLD
from obasparql.query_manager import QueryManager, QUERIES_TYPES, QUERY_TYPE_GET_ONE_USER
from obasparql.utils import generate_uri
from tests.settings import *
logger = logging.getLogger('testing')
graph_user = generat... | [
"logging.getLogger",
"json.loads",
"obasparql.query_manager.QueryManager",
"obasparql.utils.generate_uri",
"unittest.main"
] | [((271, 299), 'logging.getLogger', 'logging.getLogger', (['"""testing"""'], {}), "('testing')\n", (288, 299), False, 'import logging\n'), ((313, 362), 'obasparql.utils.generate_uri', 'generate_uri', (['model_catalog_graph_base', '"""<EMAIL>"""'], {}), "(model_catalog_graph_base, '<EMAIL>')\n", (325, 362), False, 'from ... |
import argparse
import logging
log = logging.getLogger(__name__)
def get_main_parser():
parser = argparse.ArgumentParser(prog="tpi")
return parser
def main(argv=None):
parser = get_main_parser()
args = parser.parse_args(argv)
log.debug(args)
| [
"logging.getLogger",
"argparse.ArgumentParser"
] | [((38, 65), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (55, 65), False, 'import logging\n'), ((104, 139), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""tpi"""'}), "(prog='tpi')\n", (127, 139), False, 'import argparse\n')] |
from flask import render_template, Blueprint
hello_blueprint = Blueprint('hello', __name__)
@hello_blueprint.route('/')
@hello_blueprint.route('/hello')
def index():
return render_template('index.html')
| [
"flask.render_template",
"flask.Blueprint"
] | [((64, 92), 'flask.Blueprint', 'Blueprint', (['"""hello"""', '__name__'], {}), "('hello', __name__)\n", (73, 92), False, 'from flask import render_template, Blueprint\n'), ((179, 208), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (194, 208), False, 'from flask import rende... |
"""Query graph utilities."""
import re
from bmt import Toolkit
BMT = Toolkit()
def get_subcategories(category):
"""Get sub-categories, according to the Biolink model."""
return [
descendant.replace("_", "")
for descendant in BMT.get_descendants(category, formatted=True, reflexive=True)
]... | [
"re.sub",
"bmt.Toolkit"
] | [((71, 80), 'bmt.Toolkit', 'Toolkit', ([], {}), '()\n', (78, 80), False, 'from bmt import Toolkit\n'), ((413, 451), 're.sub', 're.sub', (['"""(?<!^)(?=[A-Z])"""', '"""_"""', 'string'], {}), "('(?<!^)(?=[A-Z])', '_', string)\n", (419, 451), False, 'import re\n')] |
from pathlib import Path
import shutil
import unittest
import numpy as np
import siml.optimize as optimize
import siml.setting as setting
class TestOptimize(unittest.TestCase):
def test_generate_dict(self):
main_setting = setting.MainSetting.read_settings_yaml(
Path('tests/data/deform/optun... | [
"siml.setting.MainSetting.read_settings_yaml",
"pathlib.Path",
"numpy.max",
"shutil.rmtree",
"siml.optimize.Objective",
"siml.optimize.Study",
"siml.setting.DBSetting"
] | [((349, 387), 'siml.optimize.Objective', 'optimize.Objective', (['main_setting', 'None'], {}), '(main_setting, None)\n', (367, 387), True, 'import siml.optimize as optimize\n'), ((1979, 2007), 'siml.optimize.Study', 'optimize.Study', (['main_setting'], {}), '(main_setting)\n', (1993, 2007), True, 'import siml.optimize ... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponseRedirect, HttpResponseBadRequest
from django.urls.base import reverse
from django.utils import timezone
from django.views.generic import (
CreateView,
DayArchiveView,
DetailView,
RedirectView,
Templ... | [
"django.http.response.HttpResponseBadRequest",
"django.urls.base.reverse",
"qanda.models.Question.objects.get",
"qanda.service.elasticsearch.search_for_questions",
"qanda.forms.AnswerForm",
"qanda.forms.AnswerAcceptanceForm",
"django.utils.timezone.now",
"qanda.models.Question.objects.all",
"qanda.m... | [((1243, 1265), 'qanda.models.Question.objects.all', 'Question.objects.all', ([], {}), '()\n', (1263, 1265), False, 'from qanda.models import Question, Answer\n'), ((1456, 1476), 'qanda.models.Answer.objects.all', 'Answer.objects.all', ([], {}), '()\n', (1474, 1476), False, 'from qanda.models import Question, Answer\n'... |
# 888 888
# 888 888
# 888 888
# .d8888b 88888b. 8888b. 88888b. .d88b. .d88b. 888 .d88b. .d88b.
# d88P" 888 "88b "88b 888 "88b d88P"88b d8P Y8b 888 d88... | [
"logging.getLogger",
"click.Choice",
"incubator.bootstrap_cli.mermaid_generator.mermaid.RoundedNode",
"cognite.client.data_classes.Group",
"time.sleep",
"incubator.bootstrap_cli.configuration.BootstrapValidationError",
"incubator.bootstrap_cli.configuration.SharedAccess",
"incubator.bootstrap_cli.conf... | [((6062, 6089), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (6079, 6089), False, 'import logging\n'), ((9008, 9057), 'typing.TypeVar', 'TypeVar', (['"""T_BootstrapCore"""'], {'bound': '"""BootstrapCore"""'}), "('T_BootstrapCore', bound='BootstrapCore')\n", (9015, 9057), False, 'from ty... |
from typing import List, Dict
from pyhcl.ir.low_ir import *
from pyhcl.ir.low_prim import *
from pyhcl.passes._pass import Pass
from pyhcl.passes.utils import get_binary_width
DEFAULT_READ_LATENCY = 0
DEFAULT_WRITE_LATENCY = 1
@dataclass
class ExpandMemory(Pass):
def run(self, c: Circuit):
def get_mem_po... | [
"pyhcl.passes.utils.get_binary_width"
] | [((1136, 1173), 'pyhcl.passes.utils.get_binary_width', 'get_binary_width', (['target.mem.typ.size'], {}), '(target.mem.typ.size)\n', (1152, 1173), False, 'from pyhcl.passes.utils import get_binary_width\n')] |
import logging
import time
import os
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
format = "%(asctime)s %(levelname)-10s %(message)s"
id = time.strftime("%Y%m%d-%H%M%S")
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def for... | [
"logging.getLogger",
"os.path.exists",
"logging.StreamHandler",
"os.makedirs",
"logging.Formatter",
"time.strftime",
"logging.Formatter.format",
"logging.FileHandler",
"logging.Formatter.__init__",
"logging.addLevelName"
] | [((161, 191), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), "('%Y%m%d-%H%M%S')\n", (174, 191), False, 'import time\n'), ((1155, 1199), 'logging.addLevelName', 'logging.addLevelName', (['PASS_LEVEL_NUM', '"""PASS"""'], {}), "(PASS_LEVEL_NUM, 'PASS')\n", (1175, 1199), False, 'import logging\n'), ((1612... |
from fastapi import Depends, HTTPException, Path, status
from pydantic import UUID4
from api.dependencies.database import get_repository
from db.errors import EntityDoesNotExist, ResourceIsNotDeployed
from db.repositories.user_resources import UserResourceRepository
from db.repositories.workspace_services import Works... | [
"api.dependencies.database.get_repository",
"fastapi.Path",
"fastapi.HTTPException"
] | [((946, 955), 'fastapi.Path', 'Path', (['...'], {}), '(...)\n', (950, 955), False, 'from fastapi import Depends, HTTPException, Path, status\n'), ((1168, 1177), 'fastapi.Path', 'Path', (['...'], {}), '(...)\n', (1172, 1177), False, 'from fastapi import Depends, HTTPException, Path, status\n'), ((1691, 1700), 'fastapi.P... |
import unittest
from payroll import *
class P2Test(unittest.TestCase):
def setUp(self):
self.emp = payroll.Employee('12-3456789', 'John', 'Doe', '123 Anystreet', 'Anytown', 'Anystate', '98765')
def testHourly(self):
rate = 35.5
self.emp.make_hourly(rate)
for d in range(10):
... | [
"unittest.main"
] | [((1000, 1015), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1013, 1015), False, 'import unittest\n')] |
# Copyright 2017-2020 Palantir Technologies, Inc.
# Copyright 2021- Python Language Server Contributors.
import logging
from pylsp import hookimpl, _utils
log = logging.getLogger(__name__)
@hookimpl
def pylsp_hover(document, position):
code_position = _utils.position_to_jedi_linecolumn(document, position)
... | [
"logging.getLogger",
"pylsp._utils.position_to_jedi_linecolumn"
] | [((164, 191), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (181, 191), False, 'import logging\n'), ((261, 315), 'pylsp._utils.position_to_jedi_linecolumn', '_utils.position_to_jedi_linecolumn', (['document', 'position'], {}), '(document, position)\n', (295, 315), False, 'from pylsp impo... |
import flask
import telebot
import words
from dotenv import load_dotenv
load_dotenv()
app = flask.Flask(__name__)
bot = telebot.TeleBot(environ.get("TG_TOKEN"), threaded=False)
WEBHOOK_URL_PATH = "/%s/" % (environ.get("TG_TOKEN"))
# # Remove webhook, it fails sometimes the set if there is a previous webhook
# bot.re... | [
"words.Words",
"flask.Flask",
"dotenv.load_dotenv"
] | [((74, 87), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (85, 87), False, 'from dotenv import load_dotenv\n'), ((94, 115), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (105, 115), False, 'import flask\n'), ((1004, 1017), 'words.Words', 'words.Words', ([], {}), '()\n', (1015, 1017), False,... |
# -*- coding: utf-8 -*-
"""
Gist embedding plugin for Pelican
=================================
This plugin allows you to embed `Gists`_ into your posts.
.. _Gists: https://gist.github.com/
"""
from __future__ import unicode_literals
import hashlib
import logging
import os
import re
import codecs
import pygments
lo... | [
"logging.getLogger",
"os.path.exists",
"hashlib.md5",
"pelican.signals.initialized.connect",
"re.compile",
"pelican.signals.article_generator_finalized.connect",
"os.makedirs",
"pygments.highlight",
"pygments.formatters.HtmlFormatter",
"jinja2.Template",
"requests.get",
"pygments.lexers.get_le... | [((327, 354), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (344, 354), False, 'import logging\n'), ((368, 478), 're.compile', 're.compile', (['"""(<p>\\\\[gist:id\\\\=([0-9a-fA-F]+)(,file\\\\=([^\\\\],]+))?(,filetype\\\\=([a-zA-Z]+))?\\\\]</p>)"""'], {}), "(\n '(<p>\\\\[gist:id\\\\=(... |
"""
A script that reads a file from the web and
returns the all the words having frequency in between two words passed
"""
import re
from nltk.corpus import stopwords
import requests
from operator import itemgetter
def run(url, word1, word2):
freq = {} # keep the freq of each word in the file
freq[word1] = 0... | [
"re.sub",
"requests.get"
] | [((1318, 1349), 're.sub', 're.sub', (['"""[^a-z]"""', '""" """', 'sentence'], {}), "('[^a-z]', ' ', sentence)\n", (1324, 1349), False, 'import re\n'), ((580, 734), 'requests.get', 'requests.get', (['url'], {'headers': "{'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.... |
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# 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... | [
"tensorflow.distribute.MirroredStrategy",
"six.moves.range",
"tensorflow.distribute.NcclAllReduce",
"tensorflow.distribute.OneDeviceStrategy"
] | [((2941, 3028), 'tensorflow.distribute.MirroredStrategy', 'tf.distribute.MirroredStrategy', ([], {'devices': 'devices', 'cross_device_ops': 'cross_device_ops'}), '(devices=devices, cross_device_ops=\n cross_device_ops)\n', (2971, 3028), True, 'import tensorflow as tf\n'), ((2311, 2358), 'tensorflow.distribute.OneDev... |
import os
# from signal import pause
from gpiozero import Button
from datetime import datetime
def take_screen():
screen_btn = Button(2)
while True:
if screen_btn.is_pressed:
timestamp = datetime.now()
cmd = "scrot -u d 5 $n {}.png".format('screen_' + str(timestamp))
... | [
"datetime.datetime.now",
"os.system",
"gpiozero.Button"
] | [((132, 141), 'gpiozero.Button', 'Button', (['(2)'], {}), '(2)\n', (138, 141), False, 'from gpiozero import Button\n'), ((221, 235), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (233, 235), False, 'from datetime import datetime\n'), ((326, 340), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (335, 34... |
# -*- coding: utf-8 -*-
"""
@author: david
"""
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay
class ModelEvaluatio... | [
"numpy.copy",
"numpy.unique",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"seaborn.heatmap",
"sklearn.metrics.RocCurveDisplay.from_predictions",
"matplotlib.pyplot.figure",
"sklearn.metrics.Pr... | [((701, 723), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'kFolds'}), '(n_splits=kFolds)\n', (706, 723), False, 'from sklearn.model_selection import KFold\n'), ((509, 521), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (518, 521), True, 'import numpy as np\n'), ((1287, 1312), 'sklearn.metrics.confu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/20 8:15
# @Author : HaiFeng
# @Email : <EMAIL>
from setuptools import setup
import os
this_directory = os.path.abspath(os.path.dirname(__file__))
# 读取文件内容
def read_file(filename):
with open(os.path.join(this_directory, filename), encoding='u... | [
"os.path.dirname",
"os.path.join"
] | [((192, 217), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (207, 217), False, 'import os\n'), ((269, 307), 'os.path.join', 'os.path.join', (['this_directory', 'filename'], {}), '(this_directory, filename)\n', (281, 307), False, 'import os\n')] |
import math
import numpy as np
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from tqdm import tqdm
from model import CharRNN
from data import TextDataset, TextConverter
class Trainer(object):
def __init__(self, args):
self.args = args
... | [
"torch.nn.CrossEntropyLoss",
"data.TextConverter",
"numpy.random.choice",
"torch.topk",
"data.TextDataset",
"tqdm.tqdm",
"torch.LongTensor",
"model.CharRNN",
"math.sqrt",
"numpy.array",
"torch.sum",
"torch.save",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.device"
] | [((334, 383), 'torch.device', 'torch.device', (["('cuda' if self.args.cuda else 'cpu')"], {}), "('cuda' if self.args.cuda else 'cpu')\n", (346, 383), False, 'import torch\n'), ((709, 768), 'data.TextConverter', 'TextConverter', (['self.args.txt'], {'max_vocab': 'self.args.max_vocab'}), '(self.args.txt, max_vocab=self.a... |
import pytest
from d3rlpy.models.torch.encoders import PixelEncoder
from d3rlpy.models.torch.encoders import PixelEncoderWithAction
from d3rlpy.models.torch.encoders import VectorEncoder
from d3rlpy.models.torch.encoders import VectorEncoderWithAction
from d3rlpy.encoders import create_encoder_factory
from d3rlpy.enco... | [
"d3rlpy.encoders.PixelEncoderFactory",
"pytest.mark.parametrize",
"d3rlpy.encoders.VectorEncoderFactory",
"d3rlpy.encoders.create_encoder_factory"
] | [((404, 463), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""observation_shape"""', '[(4, 84, 84)]'], {}), "('observation_shape', [(4, 84, 84)])\n", (427, 463), False, 'import pytest\n'), ((465, 514), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""action_size"""', '[None, 2]'], {}), "('action_... |
# -*- coding: utf-8 -*-
#import game
from glob import glob
file1 = glob("01_face_dataset.py")
file2 = glob("02_face_training.py")
import facedataset
import facetrain
import cv2
import numpy as np
import os
from PIL import Image
#facedataset.first()
#facetrain.second()
recognizer = cv2.face.LBPHFaceRecognizer_create()
... | [
"cv2.rectangle",
"facetrain.second",
"cv2.face.LBPHFaceRecognizer_create",
"facedataset.first",
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.CascadeClassifier",
"cv2.waitKey",
"glob.glob"
] | [((67, 93), 'glob.glob', 'glob', (['"""01_face_dataset.py"""'], {}), "('01_face_dataset.py')\n", (71, 93), False, 'from glob import glob\n'), ((102, 129), 'glob.glob', 'glob', (['"""02_face_training.py"""'], {}), "('02_face_training.py')\n", (106, 129), False, 'from glob import glob\n'), ((283, 319), 'cv2.face.LBPHFace... |
# This DAG is for running python scripts to generate static visualisation data
# from syncthing every month end
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.dummy_operator import Dumm... | [
"datetime.timedelta",
"airflow.utils.dates.days_ago",
"airflow.operators.python_operator.PythonOperator",
"airflow.DAG"
] | [((1235, 1327), 'airflow.DAG', 'DAG', (['"""clix_static_visuals_dag"""'], {'default_args': 'default_args', 'schedule_interval': '"""@monthly"""'}), "('clix_static_visuals_dag', default_args=default_args, schedule_interval\n ='@monthly')\n", (1238, 1327), False, 'from airflow import DAG\n'), ((4152, 4344), 'airflow.o... |
from flask import Flask, request, jsonify, render_template_string
import redis
import requests
import re
import json
import sys
app = Flask(__name__)
@app.route('/getid/<username>')
def getid(username):
red = redis.Redis(host="redis_users")
return red.get(username).decode()
@app.route('/useraction', methods... | [
"requests.post",
"flask.Flask",
"requests.get",
"redis.Redis",
"flask.request.json.get",
"flask.request.form.get",
"re.sub"
] | [((134, 149), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (139, 149), False, 'from flask import Flask, request, jsonify, render_template_string\n'), ((215, 246), 'redis.Redis', 'redis.Redis', ([], {'host': '"""redis_users"""'}), "(host='redis_users')\n", (226, 246), False, 'import redis\n'), ((360, 384)... |
####################################################
# (C) <NAME>, 2016, All Rights Reserved
#
# File Name: app.py
#
# Creation Date: 28-12-2016
#
# Created By: <NAME>
#
# Purpose:
#
####################################################
from __future__ import print_function
from credentialfile import CredentialFile
fro... | [
"credentialfile.CredentialFile",
"ststoken.StsToken"
] | [((462, 547), 'credentialfile.CredentialFile', 'CredentialFile', ([], {'path': "options['credential_file']", 'profile': "options['profile_name']"}), "(path=options['credential_file'], profile=options['profile_name']\n )\n", (476, 547), False, 'from credentialfile import CredentialFile\n'), ((614, 644), 'ststoken.Sts... |
import re
from backend.projectfiles.GenericProjectFile import GenericProjectFile
QUOTE = r'(?:["|\'])'
STRING = r'([\w\.\-\+]+)'
GAV_REGEXP = QUOTE + '(?:' + ":".join([STRING, STRING, STRING]) + ')' + QUOTE
class GradleProjectFile(GenericProjectFile):
""" Gradle project file implementation to extract dependenc... | [
"re.match"
] | [((445, 485), 're.match', 're.match', (["('.*' + GAV_REGEXP + '.*')", 'line'], {}), "('.*' + GAV_REGEXP + '.*', line)\n", (453, 485), False, 'import re\n')] |
from django.urls import path
from whitelist_api.views import AddTorrentInfoHash, RemoveTorrentInfoHash
app_name = 'whitelist_api'
urlpatterns = [
path('add-torrent-info-hash/', AddTorrentInfoHash.as_view()),
path('del-torrent-info-hash/', RemoveTorrentInfoHash.as_view()),
]
| [
"whitelist_api.views.RemoveTorrentInfoHash.as_view",
"whitelist_api.views.AddTorrentInfoHash.as_view"
] | [((184, 212), 'whitelist_api.views.AddTorrentInfoHash.as_view', 'AddTorrentInfoHash.as_view', ([], {}), '()\n', (210, 212), False, 'from whitelist_api.views import AddTorrentInfoHash, RemoveTorrentInfoHash\n'), ((250, 281), 'whitelist_api.views.RemoveTorrentInfoHash.as_view', 'RemoveTorrentInfoHash.as_view', ([], {}), ... |
from Stack import Stack
def main():
stack = Stack()
stack.push(0)
stack.push(1)
stack.push(2)
stack.push(3)
assert stack.data == [0, 1, 2, 3]
assert stack.capacity == 4
assert stack.size == 4
popped = stack.pop()
assert popped == 3
popped = stack.pop()
assert popped =... | [
"Stack.Stack"
] | [((50, 57), 'Stack.Stack', 'Stack', ([], {}), '()\n', (55, 57), False, 'from Stack import Stack\n')] |
import numpy as np
import pytest
from pandas.core.frame import DataFrame
from bender.importers import DataImporters
from bender.model_loaders import ModelLoaders
from bender.model_trainer.decision_tree import DecisionTreeClassifierTrainer
from bender.split_strategies import SplitStrategies
pytestmark = pytest.mark.as... | [
"bender.model_trainer.decision_tree.DecisionTreeClassifierTrainer",
"bender.split_strategies.SplitStrategies.ratio",
"bender.importers.DataImporters.literal",
"bender.model_loaders.ModelLoaders.literal",
"numpy.all",
"pandas.core.frame.DataFrame"
] | [((686, 731), 'pandas.core.frame.DataFrame', 'DataFrame', (["{'x': [2, -3, 4], 'y': [2, -3, 4]}"], {}), "({'x': [2, -3, 4], 'y': [2, -3, 4]})\n", (695, 731), False, 'from pandas.core.frame import DataFrame\n'), ((886, 912), 'numpy.all', 'np.all', (['(expected == result)'], {}), '(expected == result)\n', (892, 912), Tru... |
#!/usr/bin/env python3
# Goshu IRC Bot
# written by <NAME> <<EMAIL>>
# licensed under the ISC license
"""extends several builtin functions and provides helper functions
The default Python library is extensive and well-stocked. There are some
times however, you wish a small task was taken care of for you. This module
i... | [
"os.path.exists",
"json.loads",
"os.listdir",
"sys.path.insert",
"girc.formatting.escape",
"importlib.import_module",
"re.compile",
"datetime.datetime.fromtimestamp",
"imp.reload",
"os.path.join",
"os.path.splitext",
"requests.get",
"os.path.isfile",
"os.path.isdir",
"http_status.Status"... | [((15914, 15933), 're.compile', 're.compile', (['_str_td'], {}), '(_str_td)\n', (15924, 15933), False, 'import re\n'), ((8631, 8644), 'pyquery.PyQuery', 'pq', (['input_xml'], {}), '(input_xml)\n', (8633, 8644), True, 'from pyquery import PyQuery as pq\n'), ((11787, 11811), 'xml.sax.saxutils.unescape', 'saxutils.unescap... |
from flask_wtf import FlaskForm
from wtforms import SubmitField, SelectField, IntegerField, FloatField, StringField
from wtforms.validators import DataRequired
import pandas as pd
uniq_vals = pd.read_csv("data/unique_cat_vals.csv", index_col=0)
class InputData(FlaskForm):
car = SelectField(label="Car", choices=u... | [
"wtforms.validators.DataRequired",
"wtforms.SubmitField",
"pandas.read_csv"
] | [((193, 245), 'pandas.read_csv', 'pd.read_csv', (['"""data/unique_cat_vals.csv"""'], {'index_col': '(0)'}), "('data/unique_cat_vals.csv', index_col=0)\n", (204, 245), True, 'import pandas as pd\n'), ((1151, 1183), 'wtforms.SubmitField', 'SubmitField', (['"""Predict the price"""'], {}), "('Predict the price')\n", (1162,... |
from wordcloud2 import wordcloud as W
import os
from PIL import Image
stwords = {"us", "will"}
print("==Obama's==")
cs = W.randomscheme() #:Set1_8
as_ = W.randomangles() #(0,90,45,-45)
dens = 0.5 #not too high
wca = W.wordcloud(
W.processtext(open(W.pkgdir(W.WordCloud)+"/res/Barack Obama's First Inaugural Address... | [
"wordcloud2.wordcloud.GIF",
"os.makedirs",
"PIL.Image.new",
"wordcloud2.wordcloud.randomangles",
"wordcloud2.wordcloud.pkgdir",
"wordcloud2.wordcloud.randomscheme",
"wordcloud2.wordcloud.gif_generate"
] | [((123, 139), 'wordcloud2.wordcloud.randomscheme', 'W.randomscheme', ([], {}), '()\n', (137, 139), True, 'from wordcloud2 import wordcloud as W\n'), ((155, 171), 'wordcloud2.wordcloud.randomangles', 'W.randomangles', ([], {}), '()\n', (169, 171), True, 'from wordcloud2 import wordcloud as W\n'), ((2016, 2065), 'PIL.Ima... |
# Copyright (c) <NAME>, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import itk
import module_kits.itk_kit as itk_kit
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
class nbCurvesLevelSet(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_man... | [
"module_base.ModuleBase.close",
"module_mixins.ScriptedConfigModuleMixin.__init__",
"module_kits.itk_kit.utils.setupITKObjectProgress",
"module_mixins.ScriptedConfigModuleMixin.close",
"module_base.ModuleBase.__init__"
] | [((336, 377), 'module_base.ModuleBase.__init__', 'ModuleBase.__init__', (['self', 'module_manager'], {}), '(self, module_manager)\n', (355, 377), False, 'from module_base import ModuleBase\n'), ((1208, 1285), 'module_mixins.ScriptedConfigModuleMixin.__init__', 'ScriptedConfigModuleMixin.__init__', (['self', 'configList... |
"""
Sep 21 -- A few of the plots used in analysis, very far from a complete list, and probably most are too specific to be
useful again.
Moved useful functions from here.
"""
from __future__ import annotations
from typing import List, Callable, Optional, Union, TYPE_CHECKING
import numpy as np
from dat_analysis.anal... | [
"dat_analysis.plotting.plotly.hover_info.HoverInfo"
] | [((2160, 2236), 'dat_analysis.plotting.plotly.hover_info.HoverInfo', 'HoverInfo', ([], {'name': '"""Dat"""', 'func': '(lambda dat: dat.datnum)', 'precision': '""".d"""', 'units': '""""""'}), "(name='Dat', func=lambda dat: dat.datnum, precision='.d', units='')\n", (2169, 2236), False, 'from dat_analysis.plotting.plotly.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 23:54:16 2021
@author: rolandvarga
"""
import gym
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.signal import savgol_filter
import pickle
#%matplotlib qt
#%matplotlib inline
# Set to 1 to repeat SARSA learning (With... | [
"matplotlib.pyplot.ylabel",
"scipy.signal.savgol_filter",
"numpy.array",
"gym.make",
"numpy.arange",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"numpy.... | [((973, 1002), 'gym.make', 'gym.make', (['"""SphericalRobot-v0"""'], {}), "('SphericalRobot-v0')\n", (981, 1002), False, 'import gym\n'), ((2376, 2411), 'numpy.array', 'np.array', (['[6, 6, 2 * np.pi / env.c]'], {}), '([6, 6, 2 * np.pi / env.c])\n', (2384, 2411), True, 'import numpy as np\n'), ((2458, 2478), 'numpy.arr... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 15:33:47 2019
@author: Bogoclu
"""
import typing
import multiprocessing as mp
import warnings
import numpy as np
from scipy import stats
from .space import FullSpace
from duqo.proba import DS, MC, SUSE, ISPUD, FORM
from duqo.doe.lhs import make_doe
def _check_obj_w... | [
"numpy.mean",
"numpy.ones",
"duqo.doe.lhs.make_doe",
"scipy.stats.norm",
"numpy.logical_not",
"multiprocessing.cpu_count",
"numpy.array",
"numpy.zeros",
"numpy.std",
"warnings.warn",
"numpy.var"
] | [((1245, 1274), 'numpy.array', 'np.array', (['use_std'], {'dtype': 'bool'}), '(use_std, dtype=bool)\n', (1253, 1274), True, 'import numpy as np\n'), ((2344, 2358), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (2356, 2358), True, 'import multiprocessing as mp\n'), ((9965, 10008), 'numpy.ones', 'np.ones... |
import tensorflow as tf
import numpy as np
from dps.register import RegisterBank
from dps.env import TensorFlowEnv
from dps.utils import Param, Config
def build_env():
return PathDiscovery()
config = Config(
build_env=build_env,
curriculum=[
dict(shape=(2, 2), threshold=6),
dict(shape=(... | [
"numpy.product",
"tensorflow.equal",
"tensorflow.shape",
"dps.register.RegisterBank",
"tensorflow.split",
"dps.utils.Param",
"numpy.random.randint",
"tensorflow.argmax",
"tensorflow.clip_by_value",
"numpy.concatenate",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.minimum"
] | [((740, 747), 'dps.utils.Param', 'Param', ([], {}), '()\n', (745, 747), False, 'from dps.utils import Param, Config\n'), ((760, 767), 'dps.utils.Param', 'Param', ([], {}), '()\n', (765, 767), False, 'from dps.utils import Param, Config\n'), ((780, 787), 'dps.utils.Param', 'Param', ([], {}), '()\n', (785, 787), False, '... |
# -*- coding: utf-8 -*-
import requests
class Query:
'''Implements queries to the Github API using GraphQL
'''
def __init__(self, token, max_page_size=100, min_page_size=5):
self._token = token
self._max_page_size = max_page_size
self._min_page_size = min_page_size
self.a... | [
"inspect.currentframe",
"requests.adapters.HTTPAdapter",
"requests.Session",
"urllib3.util.retry.Retry"
] | [((13434, 13556), 'urllib3.util.retry.Retry', 'Retry', ([], {'total': 'retries', 'read': 'retries', 'connect': 'retries', 'backoff_factor': 'backoff_factor', 'status_forcelist': 'status_forcelist'}), '(total=retries, read=retries, connect=retries, backoff_factor=\n backoff_factor, status_forcelist=status_forcelist)\... |
from typing import List
import matplotlib.pyplot as plt
class Mortgage:
"""
A mortgage overview of the total burden (incl. interest) and the monthly fees per fixed period
"""
def __init__(self, mortgage_amount, burden, periods, monthly_fees, name):
self.mortgage_amount = int(mortgage_amount)... | [
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.tight_layout"
] | [((2593, 2611), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2609, 2611), True, 'import matplotlib.pyplot as plt\n'), ((2776, 2850), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', 'nr_mortgages'], {'figsize': '(nr_mortgages * 3, 8)', 'sharey': '"""row"""'}), "(2, nr_mortgages, figsiz... |
#!/usr/bin/env python
#
# Copyright 2018-2019 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | [
"tarfile.open",
"glob.iglob",
"zipfile.ZipFile",
"time.sleep",
"sys.exit",
"os.remove",
"os.listdir",
"tarfile.is_tarfile",
"os.path.isdir",
"utils.cos.COSWrapper",
"os.path.getsize",
"utils.wml.WMLWrapper",
"os.path.isfile",
"re.sub",
"utils.config.YAMLReader",
"os.makedirs",
"os.pa... | [((6583, 6644), 'utils.debug.debug', 'debug', (['"""Using the following configuration settings: """', 'config'], {}), "('Using the following configuration settings: ', config)\n", (6588, 6644), False, 'from utils.debug import debug\n'), ((30449, 30527), 'os.path.join', 'os.path.join', (["config['local_download_director... |
"""A simple Google-style logging wrapper."""
import logging
import time
import traceback
import os
import sys
import gflags as flags
FLAGS = flags.FLAGS
def format_message(record):
try:
record_message = "%s" % (record.msg % record.args)
except TypeError:
record_message = record.msg
retu... | [
"logging.getLogger",
"logging.StreamHandler",
"traceback.extract_stack",
"logging.captureWarnings",
"gflags.ArgumentSerializer",
"logging.Formatter.format",
"gflags.BooleanFlag.__init__",
"logging._levelToName.get",
"logging.Formatter.__init__",
"os.path.basename",
"logging.FileHandler",
"logg... | [((2868, 2887), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (2885, 2887), False, 'import logging\n'), ((2905, 2938), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (2926, 2938), False, 'import logging\n'), ((2956, 2989), 'logging.StreamHandler', 'logging.Stream... |
import unittest
from typing import Any
from coiny.core import CoinPrice, CoinyQueue, CoinySession, price_now_url, price_task
from coiny.utils import NullCoinPrice
class HasJson:
def __init__(self, data) -> None:
self.data = data
async def __aenter__(self):
return self
async def __aexit_... | [
"coiny.core.CoinPrice",
"coiny.core.CoinyQueue",
"coiny.core.price_now_url",
"coiny.core.CoinySession",
"coiny.core.price_task"
] | [((534, 546), 'coiny.core.CoinyQueue', 'CoinyQueue', ([], {}), '()\n', (544, 546), False, 'from coiny.core import CoinPrice, CoinyQueue, CoinySession, price_now_url, price_task\n'), ((565, 579), 'coiny.core.CoinySession', 'CoinySession', ([], {}), '()\n', (577, 579), False, 'from coiny.core import CoinPrice, CoinyQueue... |
#!/usr/bin/env python
import math
import os
import numpy as np
import time
import sys
import copy
import rospy
import moveit_msgs.msg
import geometry_msgs.msg
import random
import csv
from sensor_msgs.msg import JointState
from gazebo_msgs.msg import LinkStates
from gazebo_msgs.msg import LinkState
from std_msgs.msg i... | [
"panda_rl.srv.StepActionResponse",
"rospy.init_node",
"rospy.Service",
"rospy.wait_for_message",
"numpy.append",
"moveit_commander.MoveGroupCommander",
"numpy.array",
"rospy.spin",
"numpy.linalg.norm",
"numpy.round"
] | [((523, 570), 'moveit_commander.MoveGroupCommander', 'moveit_commander.MoveGroupCommander', (['group_name'], {}), '(group_name)\n', (558, 570), False, 'import moveit_commander\n'), ((583, 610), 'numpy.array', 'np.array', (['[1, 0, 0.0075, 0]'], {}), '([1, 0, 0.0075, 0])\n', (591, 610), True, 'import numpy as np\n'), ((... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | [
"qiskit.pulse.exceptions.PulseError",
"re.compile"
] | [((1541, 1588), 'qiskit.pulse.exceptions.PulseError', 'PulseError', (['"""Pulse duration should be integer."""'], {}), "('Pulse duration should be integer.')\n", (1551, 1588), False, 'from qiskit.pulse.exceptions import PulseError\n'), ((2292, 2327), 're.compile', 're.compile', (['"""[a-zA-Z][a-zA-Z0-9_]*"""'], {}), "(... |
import unittest
import numpy as np
import pandas as pd
import mlsurvey as mls
class TestData(unittest.TestCase):
def test_to_dict_dict_should_be_set(self):
"""
:test : mlsurvey.model.Data.to_dict()
:condition : x,y, y_pred data are filled.
:main_result : the dictionary generated... | [
"pandas.DataFrame",
"numpy.array",
"mlsurvey.sl.models.DataPandas",
"mlsurvey.sl.models.DataPandas.from_dict"
] | [((369, 401), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (377, 401), True, 'import numpy as np\n'), ((414, 430), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (422, 430), True, 'import numpy as np\n'), ((448, 464), 'numpy.array', 'np.array', (['[1, 0]'], {}),... |
# encoding:utf-8
import requests
import base64
import time
'''
通用文字识别
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
access_token = '' # 百度AI的token access 详情请去看文档
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
f... | [
"requests.post",
"time.sleep"
] | [((544, 600), 'requests.post', 'requests.post', (['request_url'], {'data': 'params', 'headers': 'headers'}), '(request_url, data=params, headers=headers)\n', (557, 600), False, 'import requests\n'), ((1111, 1126), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (1121, 1126), False, 'import time\n')] |
from random import shuffle
import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
import cv2
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
from PIL import Image
from .RepulsionLoss.my_repulsion_loss import repulsion
def preprocess_input(image):
image /= 255
... | [
"numpy.random.rand",
"PIL.Image.new",
"torch.max",
"torch.pow",
"torch.eq",
"numpy.array",
"torch.unsqueeze",
"numpy.concatenate",
"torch.zeros_like",
"torch.le",
"torch.ones_like",
"torch.abs",
"random.shuffle",
"torch.ge",
"cv2.cvtColor",
"torch.lt",
"torch.clamp",
"PIL.Image.ope... | [((734, 756), 'torch.clamp', 'torch.clamp', (['iw'], {'min': '(0)'}), '(iw, min=0)\n', (745, 756), False, 'import torch\n'), ((766, 788), 'torch.clamp', 'torch.clamp', (['ih'], {'min': '(0)'}), '(ih, min=0)\n', (777, 788), False, 'import torch\n'), ((890, 916), 'torch.clamp', 'torch.clamp', (['ua'], {'min': '(1e-08)'})... |