code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import matplotlib.pyplot as plt
import numpy as np
trainmetrics = [-7.827264757844233, -6.539122052193318, -5.46885741580931, -4.860724952141639]
testmetrics = [-7.624574522874662, -6.11743100622369, -5.002220748941359, -4.422560242520135]
trainmetrics = np.round(trainmetrics, decimals=3)
testmetrics = np.round(testm... | [
"numpy.linspace",
"matplotlib.pyplot.plot",
"numpy.round",
"matplotlib.pyplot.show"
] | [((257, 291), 'numpy.round', 'np.round', (['trainmetrics'], {'decimals': '(3)'}), '(trainmetrics, decimals=3)\n', (265, 291), True, 'import numpy as np\n'), ((306, 339), 'numpy.round', 'np.round', (['testmetrics'], {'decimals': '(3)'}), '(testmetrics, decimals=3)\n', (314, 339), True, 'import numpy as np\n'), ((396, 41... |
"""
从Kafka 中读取股价信息,
Spark Streaming 输出10秒时间窗的滑动均值作为预测。
"""
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
from pyspark.sql.functions import from_json
import pyspark.sql.types as spark_type
import pyspark.sql.functions as F
from pyspark.sql.function... | [
"pyspark.sql.functions.window",
"pyspark.sql.functions.col",
"pyspark.sql.functions.avg",
"pyspark.sql.SparkSession.builder.appName",
"pyspark.sql.functions.count"
] | [((427, 484), 'pyspark.sql.SparkSession.builder.appName', 'SparkSession.builder.appName', (['"""StructuredStreaming_Kafka"""'], {}), "('StructuredStreaming_Kafka')\n", (455, 484), False, 'from pyspark.sql import SparkSession\n'), ((1382, 1400), 'pyspark.sql.functions.col', 'F.col', (['"""cnt_close"""'], {}), "('cnt_clo... |
import warnings
def deprecate_module_attribute(mod, deprecated):
"""Return a wrapped object that warns about deprecated accesses"""
deprecated = set(deprecated)
class Wrapper(object):
def __getattr__(self, attr):
if attr in deprecated:
warnings.warn("Property %s is dep... | [
"warnings.warn"
] | [((287, 336), 'warnings.warn', 'warnings.warn', (["('Property %s is deprecated' % attr)"], {}), "('Property %s is deprecated' % attr)\n", (300, 336), False, 'import warnings\n'), ((472, 521), 'warnings.warn', 'warnings.warn', (["('Property %s is deprecated' % attr)"], {}), "('Property %s is deprecated' % attr)\n", (485... |
import gym
import tensorflow as tf
import numpy as np
INPUT_SIZE = 4
HIDDEN_UNIT_NUM = 4
OUTPUT_SIZE = 1
LEARNING_RATE = 0.01
DISCOUNT_RATE = 0.95
def Cartpole_policy():
initializer = tf.contrib.layers.variance_scaling_initializer()
X = tf.placeholder(tf.float32, shape=(None, INPUT_SIZE))
hidden = tf.laye... | [
"numpy.mean",
"tensorflow.to_float",
"tensorflow.contrib.layers.variance_scaling_initializer",
"tensorflow.placeholder",
"tensorflow.train.Saver",
"tensorflow.log",
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"tensorflow.nn.sigmoid",
"tensorflow.concat",
"numpy.concatenate",... | [((190, 238), 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), '()\n', (236, 238), True, 'import tensorflow as tf\n'), ((247, 299), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, INPUT_SIZE)'}), '(tf.float32, shape=(Non... |
from datetime import datetime
import os
from collections import defaultdict
import os
import yaml
from .postgresql_manager import PostgreSQL_Manager
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
class OpenDataWriter(object):
def __init__(self, config):
self._config = config
allowed_fie... | [
"os.path.exists",
"os.makedirs",
"os.path.join",
"os.path.dirname",
"yaml.safe_load"
] | [((178, 203), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (193, 203), False, 'import os\n'), ((443, 508), 'os.path.join', 'os.path.join', (['ROOT_DIR', '""".."""', '"""cfg_lists"""', 'config.field_data_file'], {}), "(ROOT_DIR, '..', 'cfg_lists', config.field_data_file)\n", (455, 508), Fals... |
import json
import logging
import os
import re
import sys
import urllib.parse
from urllib.error import HTTPError, URLError
from urllib.request import Request
import praw
import requests
import yaml
from shared.exceptions import AlreadyProcessed
def load_configuration():
conf_file = os.path.join(os.path.dirname(... | [
"logging.basicConfig",
"json.dumps",
"requests.head",
"os.path.dirname",
"yaml.safe_load",
"praw.Reddit",
"shared.exceptions.AlreadyProcessed",
"logging.error",
"re.search"
] | [((759, 800), 'praw.Reddit', 'praw.Reddit', ([], {'site_name': "CONFIG['BOT_NAME']"}), "(site_name=CONFIG['BOT_NAME'])\n", (770, 800), False, 'import praw\n'), ((1671, 1791), 're.search', 're.search', (['"""https?://(www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)"""', 'string'], {... |
""" change images between different color spaces """
import cv2 as cv
import numpy as np
from imagewizard.helpers import helpers
def img2grayscale(img,
to_binary: bool = False,
to_zero: bool = False,
inverted: bool = False,
trunc: bool = False,
... | [
"cv2.merge",
"imagewizard.helpers.helpers.format_image_to_PIL",
"imagewizard.helpers.helpers.format_output_order_input_BGR",
"imagewizard.helpers.helpers.format_output_order_input_RGB",
"cv2.threshold",
"numpy.asarray",
"numpy.array",
"imagewizard.helpers.helpers.calculate_distance",
"cv2.split",
... | [((1014, 1043), 'imagewizard.helpers.helpers.image2BGR', 'helpers.image2BGR', (['img', 'order'], {}), '(img, order)\n', (1031, 1043), False, 'from imagewizard.helpers import helpers\n'), ((2143, 2195), 'imagewizard.helpers.helpers.format_output_order_input_BGR', 'helpers.format_output_order_input_BGR', (['gs_img', 'ord... |
import os, json, ystockquote, re, datetime
from datetime import datetime, timedelta
from flask import Flask, url_for, render_template, request, g, abort
app = Flask(__name__)
# Index page
@app.route('/')
def index():
return render_template('index.html')
# Symbol lookup
@app.route('/lookup', methods=['GET'])
def... | [
"flask.render_template",
"flask.request.args.get",
"ystockquote.get_change_percent_change",
"flask.Flask",
"json.dumps",
"ystockquote.get_last_trade_price",
"ystockquote.get_company_name",
"datetime.datetime.now",
"datetime.datetime.today",
"re.sub",
"datetime.timedelta"
] | [((160, 175), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (165, 175), False, 'from flask import Flask, url_for, render_template, request, g, abort\n'), ((230, 259), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (245, 259), False, 'from flask import Flask, ur... |
import os
import pygame
import random
from level_2.module import background_module
from level_2.module import foreground_module
from level_2.module import player_module
class Olaf():
"""
Describes bird obstacles.
"""
# Loading bird images
num_of_imgs = 9
path = r'level_2/Utils/Pics/Obstacles/OlafAndReindeer/'... | [
"level_2.module.background_module.bg.get_width",
"random.uniform",
"random.choice",
"pygame.mask.from_surface"
] | [((1438, 1461), 'random.uniform', 'random.uniform', (['(50)', '(300)'], {}), '(50, 300)\n', (1452, 1461), False, 'import random\n'), ((674, 697), 'random.choice', 'random.choice', (['num_list'], {}), '(num_list)\n', (687, 697), False, 'import random\n'), ((1478, 1510), 'level_2.module.background_module.bg.get_width', '... |
import os
import re
import pickle
import numpy as np
import logging
import spacy
import scipy
import sklearn
from sklearn.feature_extraction.text import (
HashingVectorizer,
CountVectorizer,
TfidfVectorizer,
)
import alsim.paths
AMP_MAP = { # used to clean up a few HTML entities still hanging around in t... | [
"logging.getLogger",
"spacy.load",
"scipy.sparse.csr_matrix.tocsr",
"sklearn.feature_extraction.text.CountVectorizer",
"pickle.load",
"os.path.join",
"sklearn.preprocessing.StandardScaler",
"sklearn.feature_extraction.text.TfidfVectorizer",
"spacy.tokenizer.Tokenizer",
"re.findall"
] | [((824, 852), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (834, 852), False, 'import spacy\n'), ((875, 911), 'spacy.tokenizer.Tokenizer', 'spacy.tokenizer.Tokenizer', (['nlp.vocab'], {}), '(nlp.vocab)\n', (900, 911), False, 'import spacy\n'), ((1398, 1486), 'os.path.join', 'os.pa... |
import pytest
from seleniumbase import BaseCase
from qa327_test.conftest import base_url
from unittest.mock import patch
from qa327.models import db, User, Ticket
from werkzeug.security import generate_password_hash, check_password_hash
test_user = User(
email='<EMAIL>',
name='Test',
password=generate_pas... | [
"unittest.mock.patch",
"qa327.models.Ticket",
"werkzeug.security.generate_password_hash"
] | [((380, 467), 'qa327.models.Ticket', 'Ticket', ([], {'name': '"""test ticket yo"""', 'quantity': '"""10"""', 'price': '"""10"""', 'expiration_date': '(20201201)'}), "(name='test ticket yo', quantity='10', price='10', expiration_date=\n 20201201)\n", (386, 467), False, 'from qa327.models import db, User, Ticket\n'), ... |
"""
Copyright 2021 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | [
"testlib.awscluster.AWSClusterFactory"
] | [((759, 778), 'testlib.awscluster.AWSClusterFactory', 'AWSClusterFactory', ([], {}), '()\n', (776, 778), False, 'from testlib.awscluster import AWSClusterFactory\n')] |
## Centre of Pressure Uncertainty for Virtual Character Control
## McGill Computer Graphics Lab
##
## Released under the MIT license. This code is free to be modified
## and distributed.
##
## Author: <NAME>, <EMAIL>
## Last Updated: Sep 02, 2016
## ------------------------------------------------------------... | [
"threading.Thread.__init__",
"pygame.event.pump",
"pygame.display.set_caption",
"traceback.format_exc",
"pygame.quit",
"pygame.init",
"pygame.event.get",
"pygame.Surface",
"threading.Lock",
"pygame.display.flip",
"pygame.display.set_mode",
"pygame.display.set_icon",
"sys.stderr.write",
"py... | [((477, 484), 'Queue.Queue', 'Queue', ([], {}), '()\n', (482, 484), False, 'from Queue import Queue\n'), ((866, 897), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (891, 897), False, 'import threading\n'), ((1232, 1248), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1246... |
import pytest
from mixer.backend.django import mixer
from pagos.forms import *
from pagos.models import *
pytestmark = pytest.mark.django_db
class TestDonationForm:
def test_form(self):
form = DonationForm(data={})
card_type = mixer.blend('pagos.CardType', alias='visa', card_type='visa')
a... | [
"mixer.backend.django.mixer.blend"
] | [((249, 310), 'mixer.backend.django.mixer.blend', 'mixer.blend', (['"""pagos.CardType"""'], {'alias': '"""visa"""', 'card_type': '"""visa"""'}), "('pagos.CardType', alias='visa', card_type='visa')\n", (260, 310), False, 'from mixer.backend.django import mixer\n')] |
'''
A utility for generating a custom logger that outputs to console and
error log file.
'''
import logging
import sys
def get_logger(filename: str) -> logging.Logger:
'''
Parameters:
----------
filename (str): The string that will become the name of the error log file
Returns:
--------
... | [
"logging.basicConfig",
"logging.StreamHandler",
"logging.FileHandler",
"logging.getLogger"
] | [((411, 473), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': 'f"""logs/{filename}.log"""', 'mode': '"""w"""'}), "(filename=f'logs/{filename}.log', mode='w')\n", (430, 473), False, 'import logging\n'), ((495, 528), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n',... |
"""
Django settings for suministrospr project.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
import sentry_sdk
from configurations import Configuration... | [
"configurations.values.ListValue",
"configurations.values.SecretValue",
"sentry_sdk.integrations.django.DjangoIntegration",
"configurations.values.BooleanValue",
"os.path.join",
"os.path.dirname",
"configurations.values.TupleValue",
"configurations.values.IntegerValue",
"configurations.values.Value"... | [((644, 664), 'configurations.values.SecretValue', 'values.SecretValue', ([], {}), '()\n', (662, 664), False, 'from configurations import Configuration, values\n'), ((748, 774), 'configurations.values.BooleanValue', 'values.BooleanValue', (['(False)'], {}), '(False)\n', (767, 774), False, 'from configurations import Co... |
#!/usr/bin/env python3
import sys
import os
import glob
import subprocess
import argparse
desc = \
"""
Script for transferring plotfiles over from HPSS using htar. It should be run in the launch
directory for the problem. It optionally takes a list of plotfile basenames (without the .tar) - if
no plotfiles are suppli... | [
"os.path.exists",
"argparse.ArgumentParser",
"subprocess.run",
"os.path.join",
"os.getcwd",
"os.chdir",
"os.mkdir"
] | [((1098, 1139), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (1121, 1139), False, 'import argparse\n'), ((1413, 1424), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1422, 1424), False, 'import os\n'), ((1712, 1746), 'os.path.join', 'os.path.join', (['cwd', ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-29 18:22
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import money.models
class Migration(migrations.Migration):
initial = True
dependencies ... | [
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((508, 565), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (539, 565), False, 'from django.db import migrations, models\n'), ((6350, 6445), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'djang... |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
n = int(readline())
a = readline().rstrip().decode()
print(a.replace(' ', ','))
| [
"sys.setrecursionlimit"
] | [((116, 146), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 7)'], {}), '(10 ** 7)\n', (137, 146), False, 'import sys\n')] |
import json
import logging
import os
import subprocess
LOGGER = logging.getLogger('gullveig-agent')
def invoke_external_module(module):
cmd = module['cmd'].split()
LOGGER.debug('Invoking internal module %s', module['id'])
if len(cmd) == 0:
raise RuntimeError('Empty command for module %s' % modu... | [
"logging.getLogger",
"json.loads",
"os.access",
"subprocess.run",
"os.path.isfile"
] | [((65, 100), 'logging.getLogger', 'logging.getLogger', (['"""gullveig-agent"""'], {}), "('gullveig-agent')\n", (82, 100), False, 'import logging\n'), ((566, 609), 'subprocess.run', 'subprocess.run', (['cmd'], {'stdout': 'subprocess.PIPE'}), '(cmd, stdout=subprocess.PIPE)\n', (580, 609), False, 'import subprocess\n'), (... |
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.node as node
import logging
from pathlib import Path
logging.basicConfig(level=logging.DEBUG)
AUTOSYNTH_MULTIPLE_COMMITS = True
gapic = gcp.GAPICMicrogenerator()
spanner = gapic.typescript_library(
'spanner', 'v1',
proto_path='goog... | [
"logging.basicConfig",
"synthtool.copy",
"synthtool.gcp.GAPICMicrogenerator",
"synthtool.languages.node.postprocess_gapic_library",
"synthtool.gcp.CommonTemplates"
] | [((131, 171), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (150, 171), False, 'import logging\n'), ((216, 241), 'synthtool.gcp.GAPICMicrogenerator', 'gcp.GAPICMicrogenerator', ([], {}), '()\n', (239, 241), True, 'import synthtool.gcp as gcp\n'), ((1506, 1540... |
from auto_pilot.data.world_map import WorldMap
from auto_pilot.common.param import Param
from auto_pilot.data.path import Path
from auto_pilot.common.registrable import Registrable
from typing import TypeVar
T = TypeVar('T')
class RouteFinder(Registrable):
def find_route(self, *params) -> Path:
raise NotI... | [
"auto_pilot.common.registrable.Registrable.by_name",
"typing.TypeVar"
] | [((212, 224), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (219, 224), False, 'from typing import TypeVar\n'), ((467, 500), 'auto_pilot.common.registrable.Registrable.by_name', 'Registrable.by_name', (['class_choice'], {}), '(class_choice)\n', (486, 500), False, 'from auto_pilot.common.registrable import ... |
"""
This module contains all string representations of all day filter options, used by :class:`~cms.forms.events.event_filter_form.EventFilterForm` and
:class:`~cms.views.events.event_list_view.EventListView`:
* ``ALL_DAY``: Only events which are all day long
* ``NOT_ALL_DAY``: Exclude events which are all day long
... | [
"django.utils.translation.ugettext_lazy"
] | [((732, 756), 'django.utils.translation.ugettext_lazy', '_', (['"""All day long events"""'], {}), "('All day long events')\n", (733, 756), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((777, 805), 'django.utils.translation.ugettext_lazy', '_', (['"""Not all day long events"""'], {}), "('Not all d... |
"""Unit test for RemoteValueSensor objects."""
import pytest
from xknx import XKNX
from xknx.dpt import DPTArray, DPTBase, DPTBinary, DPTValue1Ucount
from xknx.exceptions import ConversionError, CouldNotParseTelegram
from xknx.remote_value import RemoteValueNumeric, RemoteValueSensor
class TestRemoteValueSensor:
... | [
"xknx.dpt.DPTArray",
"xknx.XKNX",
"xknx.dpt.DPTBase.__recursive_subclasses__",
"xknx.remote_value.RemoteValueNumeric",
"xknx.dpt.DPTValue1Ucount.to_knx",
"pytest.raises",
"xknx.dpt.DPTBinary",
"xknx.remote_value.RemoteValueSensor"
] | [((462, 468), 'xknx.XKNX', 'XKNX', ([], {}), '()\n', (466, 468), False, 'from xknx import XKNX\n'), ((484, 532), 'xknx.remote_value.RemoteValueSensor', 'RemoteValueSensor', ([], {'xknx': 'xknx', 'value_type': '"""pulse"""'}), "(xknx=xknx, value_type='pulse')\n", (501, 532), False, 'from xknx.remote_value import RemoteV... |
import torch
import torch.nn as nn
import numpy as np
import scipy.io as scio
import os
import matplotlib.pyplot as plt
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
torch.manual_seed(1)
np.random.seed(1)
lapl_op = [[[[ 0, 0, -1/12, 0, 0],
[ 0, 0, 4/3, 0, 0],
[-1/12, 4/3... | [
"torch.manual_seed",
"matplotlib.pyplot.savefig",
"scipy.io.savemat",
"numpy.ones",
"numpy.roll",
"numpy.random.random",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.random.seed",
"numpy.concatenate",
"numpy.meshgr... | [((162, 182), 'torch.manual_seed', 'torch.manual_seed', (['(1)'], {}), '(1)\n', (179, 182), False, 'import torch\n'), ((184, 201), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (198, 201), True, 'import numpy as np\n'), ((4640, 4656), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (4648, 46... |
import os
from transformers import util
EXCLUDE_IDS = [617, 8890] # Coins(Shilo Village) # Coins(Mage Training Arena)
def build_requirements(requirements):
if not requirements:
return []
new_requirements = []
for key, value in requirements.items():
new_requirements.append({"skill": ke... | [
"transformers.util.getFiles",
"os.path.join",
"transformers.util.prepare_workspace",
"transformers.util.getFilenames"
] | [((611, 646), 'transformers.util.prepare_workspace', 'util.prepare_workspace', (['output_path'], {}), '(output_path)\n', (633, 646), False, 'from transformers import util\n'), ((692, 717), 'transformers.util.getFiles', 'util.getFiles', (['input_path'], {}), '(input_path)\n', (705, 717), False, 'from transformers import... |
#usr/bin/env python
#-*- coding:utf-8- -*-
import pygame
pygame.init() # pygame初始化,必须有,且必须在开头
font = pygame.font.SysFont("Arial", 20)
# print(pygame.font.get_fonts()) | [
"pygame.font.SysFont",
"pygame.init"
] | [((59, 72), 'pygame.init', 'pygame.init', ([], {}), '()\n', (70, 72), False, 'import pygame\n'), ((104, 136), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""Arial"""', '(20)'], {}), "('Arial', 20)\n", (123, 136), False, 'import pygame\n')] |
###########################################################################
###########################################################################
# SPyH
###########################################################################
#########################################################... | [
"matplotlib.pyplot.draw",
"matplotlib.pyplot.MaxNLocator",
"matplotlib.collections.PolyCollection",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.Normalize",
"matplotlib.pyplot.xlabel",
"matplotlib.colorbar.ColorbarBase",
"numpy.swapaxes",
"matplotlib.pyplot.figure",
"m... | [((614, 648), 'matplotlib.rc', 'matplotlib.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (627, 648), False, 'import matplotlib\n'), ((1829, 1860), 'matplotlib.pyplot.Normalize', 'plt.Normalize', (['propMin', 'propMax'], {}), '(propMin, propMax)\n', (1842, 1860), True, 'import matplotlib.pyplot... |
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon En... | [
"django.test.RequestFactory",
"django.contrib.auth.get_user_model",
"dateutil.parser.parse",
"query.search.search_query.SearchQuery",
"query.search.alert_search_results.AlertSearchResults",
"tests.fixture_manager.get_fixtures"
] | [((1195, 1240), 'tests.fixture_manager.get_fixtures', 'get_fixtures', (["['alerts', 'comments', 'users']"], {}), "(['alerts', 'comments', 'users'])\n", (1207, 1240), False, 'from tests.fixture_manager import get_fixtures\n'), ((1258, 1274), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (1272... |
from scripts.Astar import a_star
from scripts import sprite_classes
import random
from scripts import animations
from scripts.abilities import empty_atk
"""
The AI classes provide a collection of helpful decision makers for sprites.
Each method takes in some parameters and returns the desired object back to its sprite... | [
"scripts.Astar.a_star"
] | [((1410, 1458), 'scripts.Astar.a_star', 'a_star', (['self.sprite.pos', 'sprite_target.pos', 'grid'], {}), '(self.sprite.pos, sprite_target.pos, grid)\n', (1416, 1458), False, 'from scripts.Astar import a_star\n'), ((1843, 1878), 'scripts.Astar.a_star', 'a_star', (['self.sprite.pos', 'goal', 'grid'], {}), '(self.sprite.... |
from flask import Flask, render_template, abort
import wlin_server
app = Flask(__name__)
w = wlin_server.WLinServer()
@app.route('/')
def client_list():
return render_template('connected_client_list.html', client_list=w.wl_client_list)
@app.route('/stat/<name>')
def client_stat(name):
c = None
for i i... | [
"flask.render_template",
"flask.abort",
"wlin_server.WLinServer",
"flask.Flask"
] | [((74, 89), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (79, 89), False, 'from flask import Flask, render_template, abort\n'), ((94, 118), 'wlin_server.WLinServer', 'wlin_server.WLinServer', ([], {}), '()\n', (116, 118), False, 'import wlin_server\n'), ((168, 243), 'flask.render_template', 'render_templ... |
#import robot file to create fleet
from robot import Robot
class Fleet:
def __init__(self) :
self.robot = []
self.create_fleet()
def create_fleet(self):
terminator = Robot('terminator')
self.robot.append(terminator)
r2d2 = Robot('R2D2')
self.robot.append(r2d2... | [
"robot.Robot"
] | [((203, 222), 'robot.Robot', 'Robot', (['"""terminator"""'], {}), "('terminator')\n", (208, 222), False, 'from robot import Robot\n'), ((276, 289), 'robot.Robot', 'Robot', (['"""R2D2"""'], {}), "('R2D2')\n", (281, 289), False, 'from robot import Robot\n'), ((338, 351), 'robot.Robot', 'Robot', (['"""R5D4"""'], {}), "('R... |
from protocolbuffers import Consts_pb2, UI_pb2, InteractionOps_pb2, MoveInMoveOut_pb2
from distributor import shared_messages
from distributor.ops import SplitHouseholdDialog, SendUIMessage
from distributor.system import Distributor
from google.protobuf import text_format
from objects import ALL_HIDDEN_REASONS
from obj... | [
"services.current_zone_id",
"distributor.ops.SendUIMessage",
"services.sim_info_manager",
"protocolbuffers.UI_pb2.HouseholdDisplayInfo",
"distributor.system.Distributor.instance",
"services.venue_service",
"sims.sim_spawner.SimSpawner.spawn_sim",
"ui.ui_dialog_notification.TunableUiDialogNotificationS... | [((839, 1108), 'ui.ui_dialog_notification.TunableUiDialogNotificationSnippet', 'TunableUiDialogNotificationSnippet', ([], {'description': '"""\n The notification that is displayed when a household is moved in next\n door.\n Passed in token is the household name of the household that ends up\n ... |
from channels.models import Channel
from core.models import PublicIdModel, TimeStampedModel, TitleModel
from core.models.image_models import content_file_name
from django.db import models
from envs.models import Attributes
class Content(
TimeStampedModel, PublicIdModel, TitleModel
):
channel = models.Foreign... | [
"django.db.models.JSONField",
"django.db.models.FileField",
"django.db.models.ForeignKey"
] | [((306, 405), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Channel', 'models.DO_NOTHING'], {'related_name': '"""content"""', 'blank': '(False)', 'null': '(False)'}), "(Channel, models.DO_NOTHING, related_name='content', blank\n =False, null=False)\n", (323, 405), False, 'from django.db import models\n'), (... |
"""
Main class of the confultimate module
"""
import json
from jsonmerge import merge
class ConfUltimate( ):
"""A config Manager"""
__instance = None
def __init__( self, json_data ):
"""Initialize"""
self.__json_data = json_data
@staticmethod
def load( json_path_list ):
"... | [
"json.load"
] | [((641, 659), 'json.load', 'json.load', (['fson_fp'], {}), '(fson_fp)\n', (650, 659), False, 'import json\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import os
import sys
import http.client
#from http import HTTPStatus # not support on python3.4
import argparse
import ssl
class Request(object):
def __init__(self):
self.use_https = False
self._text = None
self.req = None
... | [
"ssl.SSLContext",
"socket.socket",
"argparse.ArgumentParser"
] | [((2428, 2453), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2451, 2453), False, 'import argparse\n'), ((1482, 1531), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (1495, 1531), False, 'import socket\n'), ((1577, 1... |
from __future__ import division, print_function
import tensorflow as tf
import wave, os, sys
import soundfile as sf
import numpy as np
import librosa
from datetime import datetime
def create_adam_optimizer(learning_rate, momentum):
return tf.train.AdamOptimizer(learning_rate=learning_rate, epsilon=1e-6)
def cre... | [
"sys.stdout.flush",
"os.path.exists",
"tensorflow.one_hot",
"tensorflow.variable_scope",
"tensorflow.train.RMSPropOptimizer",
"os.makedirs",
"tensorflow.train.MomentumOptimizer",
"tensorflow.reshape",
"tensorflow.train.exponential_decay",
"os.path.join",
"tensorflow.train.get_checkpoint_state",
... | [((245, 311), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'epsilon': '(1e-06)'}), '(learning_rate=learning_rate, epsilon=1e-06)\n', (267, 311), True, 'import tensorflow as tf\n'), ((373, 447), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', ([]... |
import os
import sys
import json
import datetime
import urllib.request
from rtree import index
from .util import get_distance
API_BASE_URL = "https://airnowapi.org/aq/data/"
PARAMS = "O3,PM25,NO2,SO2"
RETURN_TYPE = "a"
RETURN_FORMAT = "application/json"
API_KEY = os.environ['AIRNOW_KEY']
CA_BOUNDING_BOX = "-124.644883... | [
"datetime.datetime.now",
"json.loads",
"rtree.index.Index"
] | [((2184, 2208), 'json.loads', 'json.loads', (['api_response'], {}), '(api_response)\n', (2194, 2208), False, 'import json\n'), ((2283, 2296), 'rtree.index.Index', 'index.Index', ([], {}), '()\n', (2294, 2296), False, 'from rtree import index\n'), ((2578, 2601), 'datetime.datetime.now', 'datetime.datetime.now', ([], {})... |
# Copyright 2014 healthcheck-as-a-service authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from flask_admin import BaseView, expose
class HealthcheckAdmin(BaseView):
@expose('/')
def index(self):
return self.render('in... | [
"flask_admin.expose"
] | [((257, 268), 'flask_admin.expose', 'expose', (['"""/"""'], {}), "('/')\n", (263, 268), False, 'from flask_admin import BaseView, expose\n'), ((364, 375), 'flask_admin.expose', 'expose', (['"""/"""'], {}), "('/')\n", (370, 375), False, 'from flask_admin import BaseView, expose\n'), ((475, 486), 'flask_admin.expose', 'e... |
from flask import Flask
from flask_restful import Api
from app import views
from app.apis import Calculator
def create_app():
app = Flask(__name__)
app.debug = True
api = Api(app)
api.add_resource(Calculator, '/cal_num')
app.register_blueprint(views.bp)
return app
| [
"flask_restful.Api",
"flask.Flask"
] | [((138, 153), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (143, 153), False, 'from flask import Flask\n'), ((185, 193), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (188, 193), False, 'from flask_restful import Api\n')] |
#!/usr/bin/env python3
"""
###################
last changes
edidted the data processing.py
duplicate_processing funciton
added the product id to 'query' dict
###################
"""
"""
Program: front_module
File: front_module.py
Version: V1.0
Date: 10.05.18
Function: creates and reciv... | [
"cgi.FieldStorage",
"middle_output_preliminar.middle_to_db",
"ors_modules.data_processing_ors.determine_type_of_middle_output",
"cgitb.enable",
"codecs.open"
] | [((941, 955), 'cgitb.enable', 'cgitb.enable', ([], {}), '()\n', (953, 955), False, 'import cgitb, cgi, codecs, unittest, tempfile\n'), ((1848, 1870), 'codecs.open', 'codecs.open', (['file', '"""r"""'], {}), "(file, 'r')\n", (1859, 1870), False, 'import cgitb, cgi, codecs, unittest, tempfile\n'), ((10815, 10847), 'middl... |
# Generated by Django 3.2 on 2021-04-09 03:59
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.... | [
"datetime.datetime",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.DateTimeField",
"django.db.models.BigAutoField",
"django.db.models.ImageField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((279, 336), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (310, 336), False, 'from django.db import migrations, models\n'), ((499, 595), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
# Librerias Django
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView
... | [
"django.utils.translation.ugettext_lazy",
"django.contrib.auth.decorators.login_required",
"django.urls.reverse"
] | [((2671, 2709), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""base:login"""'}), "(login_url='base:login')\n", (2685, 2709), False, 'from django.contrib.auth.decorators import login_required\n'), ((494, 503), 'django.utils.translation.ugettext_lazy', '_', (['"""Name"""'], {}),... |
import numpy as np
from PIL import Image
from scipy import special
# PSF functions
def scalar_a(x):
if x == 0:
return 1.0
else:
return (special.jn(1,2*np.pi*x)/(np.pi*x))**2
a = np.vectorize(scalar_a)
def s_b(x, NA=0.8, n=1.33):
if x == 0:
return 0
else:
return (NA/n)**... | [
"scipy.special.jn",
"numpy.abs",
"PIL.Image.fromarray",
"PIL.Image.open",
"numpy.sqrt",
"numpy.fft.fftfreq",
"numpy.array",
"numpy.int",
"numpy.fft.ifftshift",
"numpy.pad",
"numpy.vectorize"
] | [((203, 225), 'numpy.vectorize', 'np.vectorize', (['scalar_a'], {}), '(scalar_a)\n', (215, 225), True, 'import numpy as np\n'), ((365, 382), 'numpy.vectorize', 'np.vectorize', (['s_b'], {}), '(s_b)\n', (377, 382), True, 'import numpy as np\n'), ((1124, 1146), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '... |
from PyQt5 import QtWidgets, QtGui
class JumpSlider(QtWidgets.QSlider):
'''Custom Slider class for click->jump behaviour
Arguments:
QtWidgets {QSlider} -- Base class
'''
def __init__(self, *args):
QtWidgets.QSlider.__init__(self, *args)
def mousePressEvent(self, e):
'''Handle mouse press event
Argum... | [
"PyQt5.QtWidgets.QSlider.__init__"
] | [((210, 249), 'PyQt5.QtWidgets.QSlider.__init__', 'QtWidgets.QSlider.__init__', (['self', '*args'], {}), '(self, *args)\n', (236, 249), False, 'from PyQt5 import QtWidgets, QtGui\n')] |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
from pathlib import Path
import pytest
import spacy
from jina import Document, DocumentArray, Executor
from ...spacy_text_encoder import SpacyTextEncoder
def test_config():
ex = Executor.load_c... | [
"spacy.blank",
"pathlib.Path",
"jina.Document",
"os.path.join",
"pytest.raises"
] | [((1686, 1703), 'spacy.blank', 'spacy.blank', (['"""xx"""'], {}), "('xx')\n", (1697, 1703), False, 'import spacy\n'), ((1726, 1753), 'os.path.join', 'os.path.join', (['tmpdir', '"""xx1"""'], {}), "(tmpdir, 'xx1')\n", (1738, 1753), False, 'import os\n'), ((1803, 1820), 'spacy.blank', 'spacy.blank', (['"""xx"""'], {}), "... |
from PIL import ImageGrab
import pyautogui
import time
class Coordinates():
replayBtn=(461,507)
dinosaur=(170,515)
def restartGame():
pyautogui.click(Coordinates.replayBtn)
def pressSpace():
pyautogui.keyDown('space')
time.sleep(0.05)
print("Jump")
pyautogui.keyUp('space')
restartGame()
ti... | [
"pyautogui.keyUp",
"pyautogui.keyDown",
"time.sleep",
"pyautogui.click"
] | [((318, 331), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (328, 331), False, 'import time\n'), ((148, 186), 'pyautogui.click', 'pyautogui.click', (['Coordinates.replayBtn'], {}), '(Coordinates.replayBtn)\n', (163, 186), False, 'import pyautogui\n'), ((209, 235), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""s... |
import sys
import os
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
lib_path = os.path.abspath(os.path.join(sys.path[0], '..'))
sys.path.append(lib_path)
from src.basic_cv_tool import *
'''This is the script for project No.4 which consists of all the required
assignments.
'''
def gauss_process(imag... | [
"os.path.join",
"sys.path.remove",
"sys.path.append"
] | [((21, 84), 'sys.path.remove', 'sys.path.remove', (['"""/opt/ros/kinetic/lib/python2.7/dist-packages"""'], {}), "('/opt/ros/kinetic/lib/python2.7/dist-packages')\n", (36, 84), False, 'import sys\n'), ((145, 170), 'sys.path.append', 'sys.path.append', (['lib_path'], {}), '(lib_path)\n', (160, 170), False, 'import sys\n'... |
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module for XGBoost disambiguation of explicit relations.
Attributes:
XGBoostExplicitSenser (class):
class that xgboost sense prediction of explicit relations
"""
##################################################################
# Imports
from __... | [
"dsenser.utils.timeit"
] | [((823, 872), 'dsenser.utils.timeit', 'timeit', (['"""Training explicit XGBoost classifier..."""'], {}), "('Training explicit XGBoost classifier...')\n", (829, 872), False, 'from dsenser.utils import timeit\n')] |
"""
General helpers needed by the other tests.
"""
import difflib
import os
import babelsubs
def get_data_file_path(file_name):
return os.path.join(os.path.dirname(__file__), 'data', file_name)
def get_subs(file_name,language='en'):
return babelsubs.load_from_file(get_data_file_path(file_name), language=lan... | [
"os.path.dirname"
] | [((155, 180), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (170, 180), False, 'import os\n')] |
from distutils.command.build import build
from geo import stations_with_river
from geo import stations_by_river
from floodsystem.stationdata import build_station_list
from geo import rivers_by_station_number
stations = build_station_list()
N = 11
station_number = rivers_by_station_number(stations, N)
print (station_n... | [
"geo.rivers_by_station_number",
"floodsystem.stationdata.build_station_list"
] | [((220, 240), 'floodsystem.stationdata.build_station_list', 'build_station_list', ([], {}), '()\n', (238, 240), False, 'from floodsystem.stationdata import build_station_list\n'), ((265, 302), 'geo.rivers_by_station_number', 'rivers_by_station_number', (['stations', 'N'], {}), '(stations, N)\n', (289, 302), False, 'fro... |
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
from django.utils.functional import empty
from django.test.utils import get_runner
if __name__ == "__main__":
def run_tests(subtest):
test_module = 'tests.' + subtest
os.environ['DJANGO_SETTINGS_MODULE'] =... | [
"django.setup",
"os.environ.get",
"django.test.utils.get_runner",
"sys.exit"
] | [((646, 659), 'sys.exit', 'sys.exit', (['ret'], {}), '(ret)\n', (654, 659), False, 'import sys\n'), ((355, 369), 'django.setup', 'django.setup', ([], {}), '()\n', (367, 369), False, 'import django\n'), ((391, 411), 'django.test.utils.get_runner', 'get_runner', (['settings'], {}), '(settings)\n', (401, 411), False, 'fro... |
import requests
from bs4 import BeautifulSoup
from django.conf import settings
from django.utils import timezone
from requests.exceptions import ConnectTimeout, HTTPError, ReadTimeout
from laundry.models import LaundryRoom, LaundrySnapshot
HALL_URL = f"{settings.LAUNDRY_URL}/?location="
def update_machine_object(c... | [
"django.utils.timezone.localtime",
"laundry.models.LaundryRoom.objects.all",
"requests.get",
"bs4.BeautifulSoup",
"laundry.models.LaundrySnapshot.objects.create",
"laundry.models.LaundryRoom.objects.get",
"laundry.models.LaundrySnapshot.objects.filter"
] | [((1703, 1745), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content', '"""html.parser"""'], {}), "(page.content, 'html.parser')\n", (1716, 1745), False, 'from bs4 import BeautifulSoup\n'), ((4062, 4082), 'django.utils.timezone.localtime', 'timezone.localtime', ([], {}), '()\n', (4080, 4082), False, 'from django.utils... |
import asyncio
import random
import pytest
from aioredis_cluster import ClusterClosedError, RedisClusterError
async def test_cluster_close(cluster, event_loop):
cl = await cluster()
await cl.execute("set", "key", "value")
pool = await cl.keys_master("key")
await pool.client_pause(100)
get_tas... | [
"random.choice",
"pytest.raises",
"asyncio.sleep"
] | [((1439, 1459), 'random.choice', 'random.choice', (['pools'], {}), '(pools)\n', (1452, 1459), False, 'import random\n'), ((1669, 1689), 'random.choice', 'random.choice', (['pools'], {}), '(pools)\n', (1682, 1689), False, 'import random\n'), ((2033, 2053), 'random.choice', 'random.choice', (['pools'], {}), '(pools)\n', ... |
from asyncio_pool import AioPool
from asyncio_pool.results import getres
from functools import partial
from yabba.utils import C, target_tasks
import aiohttp
import asyncio
import ssl
import sys
async def worker(args):
url, username, password = args
try:
async with aiohttp.ClientSession(
c... | [
"yabba.utils.target_tasks",
"asyncio_pool.AioPool",
"aiohttp.BasicAuth",
"aiohttp.TCPConnector",
"asyncio.get_event_loop"
] | [((1415, 1503), 'yabba.utils.target_tasks', 'target_tasks', (['http_target_factory', 'combo_factory', 'username_factory', 'password_factory'], {}), '(http_target_factory, combo_factory, username_factory,\n password_factory)\n', (1427, 1503), False, 'from yabba.utils import C, target_tasks\n'), ((1378, 1402), 'asynci... |
import math
import time
#compute \pi using formula shown below:
#\pi=\int_{0}^{1}\frac{4}{1+x^2}dx \sim =\frac{1}{n}\sum_{i=0}^{n-1}\frac{4}{1+(\frac{i+0.5}{n})^2}
#
def compute_pi(num_step):
h=1.0/num_step
s=0.0
for i in range(num_step):
x=h*(i+0.5)
s+=4.0/(1.0+x**2)
return s*h
def mai... | [
"time.time"
] | [((352, 363), 'time.time', 'time.time', ([], {}), '()\n', (361, 363), False, 'import time\n'), ((511, 522), 'time.time', 'time.time', ([], {}), '()\n', (520, 522), False, 'import time\n')] |
# imports needed for the following examples
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial.distance as distance
import scipy.cluster.hierarchy as hierarchy
# read a local file (path is relative to python's working directory)
# sep, header=True/None
infile = '../data/PO_asof... | [
"scipy.cluster.hierarchy.dendrogram",
"scipy.spatial.distance.pdist",
"numpy.log",
"scipy.cluster.hierarchy.linkage",
"pandas.read_table",
"numpy.log2",
"scipy.cluster.hierarchy.fcluster",
"matplotlib.pyplot.show"
] | [((340, 385), 'pandas.read_table', 'pd.read_table', (['infile'], {'sep': '"""|"""', 'thousands': '""","""'}), "(infile, sep='|', thousands=',')\n", (353, 385), True, 'import pandas as pd\n'), ((678, 701), 'numpy.log2', 'np.log2', (["grouped['amt']"], {}), "(grouped['amt'])\n", (685, 701), True, 'import numpy as np\n'),... |
import io
import csv
from django.db import connections
from django.db.models import Count, Case, When, IntegerField
from capdb.models import Reporter, Jurisdiction, CaseMetadata, Snippet, Court
import json
from capweb.templatetags.api_url import api_url
from tqdm import tqdm
def update_all():
update_map_numbers()... | [
"capdb.models.CaseMetadata.objects.all",
"django.db.models.IntegerField",
"django.db.models.Count",
"capdb.models.Snippet",
"json.dumps",
"csv.writer",
"tqdm.tqdm",
"capweb.templatetags.api_url.api_url",
"capdb.models.Reporter.objects.order_by",
"capdb.models.Jurisdiction.objects.order_by",
"dja... | [((819, 832), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (830, 832), False, 'import io\n'), ((846, 910), 'csv.writer', 'csv.writer', (['output'], {'delimiter': '"""\t"""', 'quoting': 'csv.QUOTE_NONNUMERIC'}), "(output, delimiter='\\t', quoting=csv.QUOTE_NONNUMERIC)\n", (856, 910), False, 'import csv\n'), ((927, 94... |
import logging
import requests
from discord import Embed
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.model import SlashCommandOptionType
from discord_slash.utils.manage_commands import create_choice, create_option
from random import randint
logger = logging.getLogger(__name__)... | [
"logging.getLogger",
"discord_slash.utils.manage_commands.create_option",
"discord_slash.cog_ext.cog_subcommand",
"logging.warning",
"requests.get",
"discord_slash.utils.manage_commands.create_choice",
"discord.Embed",
"logging.error"
] | [((293, 320), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (310, 320), False, 'import logging\n'), ((1102, 1217), 'discord_slash.cog_ext.cog_subcommand', 'cog_ext.cog_subcommand', ([], {'name': '"""breeds"""', 'base': '"""cat"""', 'description': '"""Get a list of cat breeds and their br... |
# Environments
# Put all custom environments here
import numpy as np
import gym
import logging
logger = logging.getLogger(__name__)
import sys
sys.path.append("../gym_tetris")
from gym_tetris import TetrisEnvironment
# can just download premade tetris environment online
# to register, look at torchkit (good example ... | [
"logging.getLogger",
"sys.path.append"
] | [((104, 131), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (121, 131), False, 'import logging\n'), ((144, 176), 'sys.path.append', 'sys.path.append', (['"""../gym_tetris"""'], {}), "('../gym_tetris')\n", (159, 176), False, 'import sys\n')] |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_multilabel_classification
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import CCA
def plot_hyperplane(clf, min_x, max_x, linest... | [
"matplotlib.pyplot.ylabel",
"sklearn.cross_decomposition.CCA",
"numpy.where",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"numpy.min",
"matplotlib.pyplot.ylim",
"mat... | [((2112, 2138), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (2122, 2138), True, 'import matplotlib.pyplot as plt\n'), ((2147, 2245), 'sklearn.datasets.make_multilabel_classification', 'make_multilabel_classification', ([], {'n_classes': '(2)', 'n_labels': '(1)', 'allow_u... |
from abc import ABC, abstractmethod
import torch.nn as nn
import torch
class AbstractEmbedding(ABC):
"""
param word_embedding_size size of inputs (only used for pooling)
returns sentence embedding size
"""
@abstractmethod
def get_size(self, word_embedding_size: int) -> int:
pass
@abstractmethod
... | [
"torch.isnan"
] | [((514, 536), 'torch.isnan', 'torch.isnan', (['embedding'], {}), '(embedding)\n', (525, 536), False, 'import torch\n')] |
# -- encoding: UTF-8 --
import os
from spo.cache import Cache
from spotipy.client import Spotify as _Spotify, SpotifyException
SpotifyException = SpotifyException
class Spotify(_Spotify):
auth_token = None
auth_username = os.environ.get("SPOTIFY_USERNAME")
def __init__(self, auth=None):
if auth ... | [
"spo.cache.Cache",
"os.environ.get"
] | [((233, 267), 'os.environ.get', 'os.environ.get', (['"""SPOTIFY_USERNAME"""'], {}), "('SPOTIFY_USERNAME')\n", (247, 267), False, 'import os\n'), ((856, 898), 'spo.cache.Cache', 'Cache', (['"""spotify_cache"""'], {'max_life': '(86400 * 7)'}), "('spotify_cache', max_life=86400 * 7)\n", (861, 898), False, 'from spo.cache ... |
from ipywidgets import DOMWidget, trait_types
from traitlets import Unicode, Int
from .geotiff_to_png import geotiff_to_png
EXTENSION_VERSION="0.1.0"
class Rej(DOMWidget):
_view_name = Unicode('RejDOMWidget').tag(sync=True)
_model_name = Unicode('RejModel').tag(sync=True)
_view_module = Unicode('ceresima... | [
"traitlets.Unicode"
] | [((192, 215), 'traitlets.Unicode', 'Unicode', (['"""RejDOMWidget"""'], {}), "('RejDOMWidget')\n", (199, 215), False, 'from traitlets import Unicode, Int\n'), ((249, 268), 'traitlets.Unicode', 'Unicode', (['"""RejModel"""'], {}), "('RejModel')\n", (256, 268), False, 'from traitlets import Unicode, Int\n'), ((303, 330), ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 <NAME>.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
""" Migratie class voor dit deel van de applicatie "... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.TimeField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.CharField"
] | [((699, 792), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (715, 792), False, 'from django.db import migrations, models\... |
"""Configuration.from_dict() tests."""
from pytest import mark, raises
CONFIG_OPTIONS_1 = {
"section1": {
"value1": "1",
},
"section2": {
"value2": "2",
},
}
CONFIG_OPTIONS_2 = {
"section1": {
"value1": "11",
"value11": "11",
},
"section3": {
"value... | [
"pytest.mark.parametrize",
"pytest.raises"
] | [((1533, 1576), 'pytest.mark.parametrize', 'mark.parametrize', (['"""config_type"""', "['strict']"], {}), "('config_type', ['strict'])\n", (1549, 1576), False, 'from pytest import mark, raises\n'), ((1682, 1725), 'pytest.mark.parametrize', 'mark.parametrize', (['"""config_type"""', "['strict']"], {}), "('config_type', ... |
"""kvcheetah - Sprite API"""
from math import sqrt
from kivy.graphics import (
Color,
InstructionGroup,
PopMatrix,
PushMatrix,
Rectangle,
Rotate,
Translate
)
from kivy.logger import Logger
#Classes
#==============================================================================
class Spri... | [
"kivy.graphics.Translate",
"kivy.graphics.PushMatrix",
"kivy.graphics.InstructionGroup",
"math.sqrt",
"kivy.graphics.Rectangle",
"kivy.logger.Logger.warning",
"kivy.graphics.Rotate",
"kivy.graphics.Color",
"kivy.graphics.PopMatrix"
] | [((544, 562), 'kivy.graphics.InstructionGroup', 'InstructionGroup', ([], {}), '()\n', (560, 562), False, 'from kivy.graphics import Color, InstructionGroup, PopMatrix, PushMatrix, Rectangle, Rotate, Translate\n'), ((583, 598), 'kivy.graphics.Translate', 'Translate', (['(0)', '(0)'], {}), '(0, 0)\n', (592, 598), False, ... |
import json
import logging
import sys
from ...executor.azcli._AzCliExecutor import AzCliExecutor
from ...constants import Constant
from ...creator.creator import Creator
from ...entity.AzCli import AzCli
from ...exception import DHCPCreationException
from ...entity.CustomerResource import CustomerResource
from ...enti... | [
"json.dumps",
"logging.info"
] | [((912, 942), 'json.dumps', 'json.dumps', (['dhcp_data.__dict__'], {}), '(dhcp_data.__dict__)\n', (922, 942), False, 'import json\n'), ((1315, 1350), 'logging.info', 'logging.info', (['"""Created DHCP server"""'], {}), "('Created DHCP server')\n", (1327, 1350), False, 'import logging\n')] |
from app.extensions import db
class User(db.Document):
"""User model """
username = db.StringField()
password = db.StringField()
def to_json2(self):
"""Returns a json representantion of the user.
:returns: a json object.
"""
return {
'id': str(self.id),... | [
"app.extensions.db.StringField"
] | [((96, 112), 'app.extensions.db.StringField', 'db.StringField', ([], {}), '()\n', (110, 112), False, 'from app.extensions import db\n'), ((128, 144), 'app.extensions.db.StringField', 'db.StringField', ([], {}), '()\n', (142, 144), False, 'from app.extensions import db\n')] |
# Copyright (c) 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | [
"sahara.utils.openstack.nova.get_flavor",
"six.add_metaclass",
"sahara.context.ctx",
"six.iteritems",
"six.iterkeys",
"oslo_log.log.getLogger"
] | [((776, 803), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (793, 803), True, 'from oslo_log import log as logging\n'), ((807, 837), 'six.add_metaclass', 'six.add_metaclass', (['abc.ABCMeta'], {}), '(abc.ABCMeta)\n', (824, 837), False, 'import six\n'), ((5600, 5631), 'six.iteritems'... |
#!/usr/bin/env python3
# ver 0.1 - coding python by <NAME> on 2/26/2017
# ver 0.2 - save .npz file for outputfile on 12/2/2017
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='block average 1D Profile from np.savetxt file')
## args
parse... | [
"numpy.mean",
"hjung.time.end_print",
"hjung.time.init",
"argparse.ArgumentParser",
"hjung.blockavg.print_init",
"numpy.column_stack",
"hjung.io.read_simple",
"numpy.savetxt",
"numpy.std",
"hjung.blockavg.check",
"numpy.save",
"hjung.blockavg.main_1d"
] | [((158, 308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter', 'description': '"""block average 1D Profile from np.savetxt file"""'}), "(formatter_class=argparse.\n ArgumentDefaultsHelpFormatter, description=\n 'block average 1D Profile from ... |
import os
import sys
import json
import psycopg2
import settings
import datetime
from list_ip_addr import list_ip
def import_idea_to_uniq(line):
conn = psycopg2.connect("dbname='" + settings.DB_NAME + "'\
user='" + settings.DB_USER + "'\
password='" + set... | [
"psycopg2.connect",
"list_ip_addr.list_ip"
] | [((159, 408), 'psycopg2.connect', 'psycopg2.connect', (['("dbname=\'" + settings.DB_NAME + "\' user=\'" +\n settings.DB_USER + "\' password=\'" +\n settings.DB_PASS + "\' host=\'" + settings.\n DB_HOST + "\'")'], {}), '("dbname... |
import requests.exceptions
from urllib.parse import urlparse, urlunparse
from bs4 import BeautifulSoup
import random
import time
from .logger import SearchLogger
def read_web_page(url):
"""
Sends an HTTP request given the url, and returns the body of the response as a text (string), or None
:param url: st... | [
"urllib.parse.urlparse",
"random.randrange",
"urllib.parse.urlunparse",
"time.sleep",
"bs4.BeautifulSoup",
"time.time"
] | [((2539, 2552), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (2547, 2552), False, 'from urllib.parse import urlparse, urlunparse\n'), ((2564, 2643), 'urllib.parse.urlunparse', 'urlunparse', (["[parsed_url.scheme, parsed_url.netloc, parsed_url.path, '', '', '']"], {}), "([parsed_url.scheme, parsed_url.... |
# -*- coding: utf-8 -*-
import numpy as np
class Schrodinger:
def __init__(self, V0, c, basis_size, basis_function, fxn):
'''Creates a system to calculate the schrodinger equation
Args:
V0 (float): Initial Potential Energy
c (float): Constant to be used in Schrodinger equation
... | [
"numpy.exp",
"numpy.linspace",
"numpy.polynomial.legendre.legder",
"numpy.zeros"
] | [((709, 732), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', '(2000)'], {}), '(0, 2, 2000)\n', (720, 732), True, 'import numpy as np\n'), ((1256, 1294), 'numpy.exp', 'np.exp', (['(-2.0j * n * np.pi * self.x / l)'], {}), '(-2.0j * n * np.pi * self.x / l)\n', (1262, 1294), True, 'import numpy as np\n'), ((1396, 1435), ... |
# -*- coding: utf-8 -*-
from expects import expect
from mamba import describe, context, before
from spec.ui._ipod_helpers import *
from spec.ui._fixture import update_environment
with describe('ipodio rm') as _:
@before.all
def setup_all():
update_environment(_)
bootstrap_ipod(_.mountpoint_... | [
"mamba.describe",
"mamba.context",
"spec.ui._fixture.update_environment",
"expects.expect"
] | [((188, 209), 'mamba.describe', 'describe', (['"""ipodio rm"""'], {}), "('ipodio rm')\n", (196, 209), False, 'from mamba import describe, context, before\n'), ((262, 283), 'spec.ui._fixture.update_environment', 'update_environment', (['_'], {}), '(_)\n', (280, 283), False, 'from spec.ui._fixture import update_environme... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... | [
"googlecloudsdk.command_lib.util.declarative.python_command_util.RunExport",
"googlecloudsdk.command_lib.compute.flags.GetDefaultScopeLister",
"googlecloudsdk.command_lib.util.declarative.python_command_util.BuildHelpText",
"googlecloudsdk.command_lib.compute.url_maps.flags.UrlMapArgument",
"googlecloudsdk.... | [((1170, 1213), 'googlecloudsdk.calliope.base.ReleaseTracks', 'base.ReleaseTracks', (['base.ReleaseTrack.ALPHA'], {}), '(base.ReleaseTrack.ALPHA)\n', (1188, 1213), False, 'from googlecloudsdk.calliope import base\n'), ((1309, 1366), 'googlecloudsdk.command_lib.util.declarative.python_command_util.BuildHelpText', 'decla... |
# -*- coding: utf-8 -*-
import shlex
import subprocess
from unittest import TestCase
import pandas
from pandas.testing import assert_frame_equal
from tstoolbox import tstoolbox, tsutils
class TestConvert(TestCase):
def setUp(self):
dr = pandas.date_range("2000-01-01", periods=2, freq="D")
ts = ... | [
"pandas.Series",
"shlex.split",
"subprocess.Popen",
"tstoolbox.tsutils.memory_optimize",
"tstoolbox.tstoolbox.convert",
"pandas.DataFrame",
"pandas.testing.assert_frame_equal",
"pandas.date_range"
] | [((254, 306), 'pandas.date_range', 'pandas.date_range', (['"""2000-01-01"""'], {'periods': '(2)', 'freq': '"""D"""'}), "('2000-01-01', periods=2, freq='D')\n", (271, 306), False, 'import pandas\n'), ((320, 355), 'pandas.Series', 'pandas.Series', (['[4.5, 4.6]'], {'index': 'dr'}), '([4.5, 4.6], index=dr)\n', (333, 355),... |
from django.contrib import admin
from .models import Book
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = [field.name for field in Book._meta.get_fields()]
| [
"django.contrib.admin.register"
] | [((61, 81), 'django.contrib.admin.register', 'admin.register', (['Book'], {}), '(Book)\n', (75, 81), False, 'from django.contrib import admin\n')] |
#!/usr/bin/env python3
## MIT License
##
## Copyright (c) 2019 <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 ... | [
"numpy.intersect1d",
"numpy.roll",
"numpy.unique",
"numpy.arange",
"rule_handlers.Ruleset",
"sys.stderr.flush",
"numpy.iinfo",
"object_packer.ObjectPacker",
"numpy.max",
"sys.stderr.write",
"numpy.lexsort",
"numpy.zeros",
"numpy.empty",
"numpy.nextafter",
"numpy.concatenate",
"numpy.fu... | [((1677, 1698), 'sys.stderr.write', 'sys.stderr.write', (['msg'], {}), '(msg)\n', (1693, 1698), False, 'import sys\n'), ((1700, 1718), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), '()\n', (1716, 1718), False, 'import sys\n'), ((1636, 1679), 'sys.stderr.write', 'sys.stderr.write', (["('\\x08' * _log_last_length)"],... |
import pytest
from .permissions import Permissions, parse_template, LiteralToken, PlaceholderToken, ReValidator, mkperm, Placeholder
perms = Permissions('intrustd+perm://photos.intrustd.com')
CommentAllPerm = perms.permission('/comment')
GalleryPerm = perms.permission('/gallery')
UploadPerm = perms.permission('/uplo... | [
"pytest.raises"
] | [((2188, 2213), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2201, 2213), False, 'import pytest\n'), ((2429, 2454), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2442, 2454), False, 'import pytest\n'), ((2664, 2689), 'pytest.raises', 'pytest.raises', (['ValueEr... |
from django import forms
from django.conf import settings
from email_devino.client import DevinoClient
from email_devino.client import DevinoException
class SendMessage(forms.Form):
recipient_name = forms.CharField()
recipient_email = forms.EmailField()
sender_email = forms.ChoiceField(widget=forms.Selec... | [
"django.forms.ChoiceField",
"django.forms.EmailField",
"email_devino.client.DevinoClient",
"django.forms.CharField"
] | [((206, 223), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (221, 223), False, 'from django import forms\n'), ((246, 264), 'django.forms.EmailField', 'forms.EmailField', ([], {}), '()\n', (262, 264), False, 'from django import forms\n'), ((284, 334), 'django.forms.ChoiceField', 'forms.ChoiceField', ([]... |
# Generated by Django 2.1 on 2019-07-12 00:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0009_document_color'),
]
operations = [
migrations.AlterField(
model_name='document',
name='color',
... | [
"django.db.models.CharField"
] | [((328, 471), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('util', 'Utilities'), ('cloth', 'Cloths'), ('book', 'Books'), ('toy', 'Toys')\n ]", 'default': '"""green"""', 'max_length': '(15)'}), "(choices=[('util', 'Utilities'), ('cloth', 'Cloths'), (\n 'book', 'Books'), ('toy', 'Toys')], d... |
"""
All interactions with KLEE
"""
import json
import operator
import re
import shutil
import subprocess
import tempfile
import signal
import time
import os
from collections import OrderedDict
from os import listdir, path, makedirs, killpg, getpgid, setsid
from .config import KLEEBIN
from .constants import ERRORFILE... | [
"os.path.exists",
"collections.OrderedDict",
"os.getpgid",
"os.listdir",
"os.makedirs",
"subprocess.Popen",
"subprocess.CalledProcessError",
"os.path.join",
"subprocess.TimeoutExpired",
"time.sleep",
"os.path.isdir",
"tempfile.mkdtemp",
"os.path.basename",
"shutil.rmtree",
"json.load",
... | [((618, 725), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'cwd': 'cwd', 'preexec_fn': 'setsid'}), '(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n cwd=cwd, preexec_fn=setsid)\n', (634, 725), False, 'import subprocess\n'), ((4512, 45... |
"""Common code for testing."""
import sys
from pathlib import Path
import geopandas
import pandas as pd
import pytest
try:
import matplotlib
import matplotlib.pyplot as plt
except ImportError:
matplotlib = False
plt = None
if matplotlib and sys.platform == "darwin":
matplotlib.use("qt5agg")
# I... | [
"swn.SurfaceWaterNetwork.from_lines",
"geopandas.read_file",
"pathlib.Path",
"matplotlib.use",
"pandas.read_csv",
"swn.compat.ignore_shapely_warnings_for_object_array",
"pytest.fixture",
"pandas.to_datetime"
] | [((543, 588), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'autouse': '(True)'}), "(scope='session', autouse=True)\n", (557, 588), False, 'import pytest\n'), ((757, 787), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (771, 787), False, 'import pytest\n... |
from django.core.files.storage import FileSystemStorage
import uuid
import os
class UUIDStorage(FileSystemStorage):
def get_available_name(self, name, **kwargs):
filename, file_extension = os.path.splitext(name)
dirname = os.path.dirname(name)
name = os.path.join(dirname, str(uuid.uuid4()... | [
"os.path.dirname",
"os.path.splitext",
"uuid.uuid4"
] | [((204, 226), 'os.path.splitext', 'os.path.splitext', (['name'], {}), '(name)\n', (220, 226), False, 'import os\n'), ((245, 266), 'os.path.dirname', 'os.path.dirname', (['name'], {}), '(name)\n', (260, 266), False, 'import os\n'), ((308, 320), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (318, 320), False, 'import uui... |
# -*- coding: utf-8 -*-
"""
This module implements a kaeldioscope effect renderer.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from builtins import range
from math import sin, cos, pi, atan2
from asciimatics.re... | [
"math.cos",
"builtins.range",
"math.sin",
"math.atan2"
] | [((2598, 2628), 'builtins.range', 'range', (['(self._canvas.width // 2)'], {}), '(self._canvas.width // 2)\n', (2603, 2628), False, 'from builtins import range\n'), ((2652, 2678), 'builtins.range', 'range', (['self._canvas.height'], {}), '(self._canvas.height)\n', (2657, 2678), False, 'from builtins import range\n'), (... |
from bs4 import BeautifulSoup
import urlparse
import datetime
from scraper import *
class General(Scraper):
def log_index_page(self):
"""Logs the index page, used for test purposes"""
url = self.url_provider.get_page_url('overview')
res = self.open_url(url)
self.logger.info(res.rea... | [
"datetime.datetime.strptime",
"urlparse.parse_qs"
] | [((593, 655), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['datetime_data', '"""%d.%m.%Y %H:%M:%S"""'], {}), "(datetime_data, '%d.%m.%Y %H:%M:%S')\n", (619, 655), False, 'import datetime\n'), ((1705, 1736), 'urlparse.parse_qs', 'urlparse.parse_qs', (["link['href']"], {}), "(link['href'])\n", (1722, 173... |
#!/usr/bin/env python3
from rich.live import Live
from rich.markdown import Markdown
from rich.padding import Padding
from rich.layout import Layout
class Presentation:
def __init__(self, content):
self.slides = [slide_content.strip() for slide_content in content.split("---\n")]
print(self.slides... | [
"rich.live.Live",
"rich.markdown.Markdown"
] | [((461, 467), 'rich.live.Live', 'Live', ([], {}), '()\n', (465, 467), False, 'from rich.live import Live\n'), ((814, 847), 'rich.markdown.Markdown', 'Markdown', (['self.slides[self.index]'], {}), '(self.slides[self.index])\n', (822, 847), False, 'from rich.markdown import Markdown\n')] |
#!/usr/bin/env python3
import os
import re
'''
Script to disable dns leaks with openvpn config files in ubuntu 16.04
'''
openvpnDir = "/etc/openvpn"
pattern = ".*ovpn"
newString = """
script-security 2
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf
"""
items = os.listdir(openvpnDir)
for i... | [
"os.listdir",
"re.match"
] | [((291, 313), 'os.listdir', 'os.listdir', (['openvpnDir'], {}), '(openvpnDir)\n', (301, 313), False, 'import os\n'), ((352, 375), 're.match', 're.match', (['pattern', 'item'], {}), '(pattern, item)\n', (360, 375), False, 'import re\n')] |
"""
DeCliff filter contributed by Minecraft Forums user "DrRomz"
Originally posted here:
http://www.minecraftforum.net/topic/13807-mcedit-minecraft-world-editor-compatible-with-mc-beta-18/page__st__3940__p__7648793#entry7648793
"""
from numpy import zeros, array
import itertools
from pymclevel import alphaMaterials
a... | [
"numpy.array",
"numpy.zeros"
] | [((780, 807), 'numpy.zeros', 'zeros', (['(256,)'], {'dtype': '"""bool"""'}), "((256,), dtype='bool')\n", (785, 807), False, 'from numpy import zeros, array\n'), ((4745, 4798), 'numpy.zeros', 'zeros', (['(schema.Width, schema.Length)'], {'dtype': '"""float32"""'}), "((schema.Width, schema.Length), dtype='float32')\n", (... |
from django.contrib import admin
from app import models
admin.site.register(models.Profile)
admin.site.register(models.QuestionLike)
admin.site.register(models.AnswerLike)
admin.site.register(models.Tag)
admin.site.register(models.Question)
admin.site.register(models.Answer)
| [
"django.contrib.admin.site.register"
] | [((57, 92), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Profile'], {}), '(models.Profile)\n', (76, 92), False, 'from django.contrib import admin\n'), ((93, 133), 'django.contrib.admin.site.register', 'admin.site.register', (['models.QuestionLike'], {}), '(models.QuestionLike)\n', (112, 133), ... |
# Copyright 2016 Google Inc. 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 applicable law or a... | [
"threading.Lock"
] | [((997, 1013), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1011, 1013), False, 'import threading\n')] |
#/u/GoldenSights
import praw # simple interface to the reddit API, also handles rate limiting of requests
import time
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/
USERAGENT = ""
#This is a sho... | [
"praw.Reddit",
"sqlite3.connect",
"time.sleep"
] | [((811, 836), 'sqlite3.connect', 'sqlite3.connect', (['"""sql.db"""'], {}), "('sql.db')\n", (826, 836), False, 'import sqlite3\n'), ((1177, 1199), 'praw.Reddit', 'praw.Reddit', (['USERAGENT'], {}), '(USERAGENT)\n', (1188, 1199), False, 'import praw\n'), ((2361, 2377), 'time.sleep', 'time.sleep', (['WAIT'], {}), '(WAIT)... |
import torch
from .solvers import FixedGridODESolver
from .rk_common import rk4_alt_step_func
class Euler(FixedGridODESolver):
order = 1
def __init__(self, eps=0., **kwargs):
super(Euler, self).__init__(**kwargs)
self.eps = torch.as_tensor(eps, dtype=self.dtype, device=self.device)
def _... | [
"torch.as_tensor"
] | [((251, 309), 'torch.as_tensor', 'torch.as_tensor', (['eps'], {'dtype': 'self.dtype', 'device': 'self.device'}), '(eps, dtype=self.dtype, device=self.device)\n', (266, 309), False, 'import torch\n'), ((558, 616), 'torch.as_tensor', 'torch.as_tensor', (['eps'], {'dtype': 'self.dtype', 'device': 'self.device'}), '(eps, d... |
"""
Dihedral angle effect
=====================
Effect of dihedral on the lift coefficient slope of rectangular wings.
References
----------
.. [1] <NAME>., *Low-Speed Aerodynamics*, 2nd ed, Cambridge University
Press, 2001: figure 12.21
"""
import time
import matplotlib.pyplot as plt
import numpy as np
import e... | [
"matplotlib.pyplot.grid",
"ezaero.vlm.steady.WingParameters",
"matplotlib.pyplot.ylabel",
"ezaero.vlm.steady.FlightConditions",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"ezaero.vlm.steady.MeshParameters",
"matplotlib.pyplot.figure",
"ezaero.vlm.steady.Simulation",
"nu... | [((353, 364), 'time.time', 'time.time', ([], {}), '()\n', (362, 364), False, 'import time\n'), ((504, 533), 'ezaero.vlm.steady.MeshParameters', 'vlm.MeshParameters', ([], {'m': '(8)', 'n': '(30)'}), '(m=8, n=30)\n', (522, 533), True, 'import ezaero.vlm.steady as vlm\n'), ((610, 658), 'ezaero.vlm.steady.FlightConditions... |
import os
import cv2
from tqdm import tqdm
import config as cfg
image_folder = cfg.ndvi_image_dir_colored
images = [img for img in os.listdir(image_folder)
if img.endswith(cfg.image_extension)]
images.sort(key=lambda x: int(x.split('.')[0]))
images = images[cfg.image_range]
height, width, layers = cv2.... | [
"os.listdir",
"tqdm.tqdm",
"os.path.join",
"cv2.VideoWriter"
] | [((380, 469), 'cv2.VideoWriter', 'cv2.VideoWriter', ([], {'filename': 'cfg.video_name', 'fourcc': '(0)', 'fps': '(10)', 'frameSize': '(width, height)'}), '(filename=cfg.video_name, fourcc=0, fps=10, frameSize=(width,\n height))\n', (395, 469), False, 'import cv2\n'), ((554, 566), 'tqdm.tqdm', 'tqdm', (['images'], {}... |
from unittest.mock import call
from os3_rll.tests import OS3RLLTestCase
from os3_rll.tests.fixture import player_model_fixture
from os3_rll.actions.player import reset_player_password
class TestAddPlayer(OS3RLLTestCase):
def setUp(self) -> None:
self.player = self.set_up_patch("os3_rll.actions.player.Pla... | [
"os3_rll.actions.player.reset_player_password",
"unittest.mock.call",
"os3_rll.tests.fixture.player_model_fixture"
] | [((361, 383), 'os3_rll.tests.fixture.player_model_fixture', 'player_model_fixture', ([], {}), '()\n', (381, 383), False, 'from os3_rll.tests.fixture import player_model_fixture\n'), ((592, 627), 'os3_rll.actions.player.reset_player_password', 'reset_player_password', (['"""<PASSWORD>"""'], {}), "('<PASSWORD>')\n", (613... |
import torch
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import thinplate as tps
from numpy.testing import assert_allclose
def test_pytorch_grid():
c_dst = np.array([
[0., 0],
[1., 0],
[1, 1],
[0, 1],
], dtype=np.float32)
c_src =... | [
"thinplate.tps_grid",
"numpy.testing.assert_allclose",
"numpy.array",
"torch.tensor",
"thinplate.tps_theta_from_points"
] | [((199, 263), 'numpy.array', 'np.array', (['[[0.0, 0], [1.0, 0], [1, 1], [0, 1]]'], {'dtype': 'np.float32'}), '([[0.0, 0], [1.0, 0], [1, 1], [0, 1]], dtype=np.float32)\n', (207, 263), True, 'import numpy as np\n'), ((456, 495), 'thinplate.tps_theta_from_points', 'tps.tps_theta_from_points', (['c_src', 'c_dst'], {}), '(... |
"""Test Color class"""
import pytest
import simpleparam as param
class TestColor(object):
"""Test Color class"""
@staticmethod
def test_creation_hex():
"""Test Color - correct initilization"""
value = "#FFF000"
color = param.Color(value=value)
assert color.value == value
... | [
"simpleparam.Color",
"pytest.raises"
] | [((259, 283), 'simpleparam.Color', 'param.Color', ([], {'value': 'value'}), '(value=value)\n', (270, 283), True, 'import simpleparam as param\n'), ((465, 489), 'simpleparam.Color', 'param.Color', ([], {'value': 'value'}), '(value=value)\n', (476, 489), True, 'import simpleparam as param\n'), ((667, 691), 'simpleparam.C... |
from PIL import Image
import json
import os
import re
import sys
# Getting palette
# /absolute/path/to/Pxls
convertpath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
# /absolute/path/to/Pxls/pxls.conf
configpath = convertpath + '\\pxls.conf'
configfile = open(configpath, 'r+')
co... | [
"os.path.realpath",
"PIL.Image.open",
"re.search"
] | [((858, 879), 'PIL.Image.open', 'Image.open', (['imagePath'], {}), '(imagePath)\n', (868, 879), False, 'from PIL import Image\n'), ((906, 930), 'PIL.Image.open', 'Image.open', (['placemapPath'], {}), '(placemapPath)\n', (916, 930), False, 'from PIL import Image\n'), ((583, 622), 're.search', 're.search', (['"""^palette... |