code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import csv
import pandas as pd
score_clf = []
with open("_grover_clf.csv", "r") as f:
reader = csv.reader(f)
next(reader)
for r in reader:
score_clf += [float(r[1])]
score_reg = []
with open("_grover_reg.csv", "r") as f:
reader = csv.reader(f)
next(reader)
for r in reader:
scor... | [
"pandas.DataFrame",
"csv.reader"
] | [((504, 613), 'pandas.DataFrame', 'pd.DataFrame', (["{'ActivityClfVocab': score_clf, 'ActivityRegVocab': score_reg,\n 'ActivityIcVocab': score_ic}"], {}), "({'ActivityClfVocab': score_clf, 'ActivityRegVocab': score_reg,\n 'ActivityIcVocab': score_ic})\n", (516, 613), True, 'import pandas as pd\n'), ((100, 113), '... |
# Gain access to the Middle package
import os
import sys
sys.path.insert(1, os.path.abspath(os.pardir))
from datetime import date
from MiddleKit.Run.MySQLObjectStore import MySQLObjectStore
from Middle.Movie import Movie
from Middle.Person import Person
from Middle.Role import Role
def main():
# Set up the stor... | [
"MiddleKit.Run.MySQLObjectStore.MySQLObjectStore",
"Middle.Role.Role",
"Middle.Person.Person",
"datetime.date",
"os.path.abspath",
"Middle.Movie.Movie"
] | [((76, 102), 'os.path.abspath', 'os.path.abspath', (['os.pardir'], {}), '(os.pardir)\n', (91, 102), False, 'import os\n'), ((397, 415), 'MiddleKit.Run.MySQLObjectStore.MySQLObjectStore', 'MySQLObjectStore', ([], {}), '()\n', (413, 415), False, 'from MiddleKit.Run.MySQLObjectStore import MySQLObjectStore\n'), ((478, 485... |
# Running Orc 00
from orcs import Orc
orc = Orc(160, -48)
def setup():
global bg
bg = loadImage("field.png")
frameRate(15)
size(320, 320)
orc.loadPics()
orc.dy = 5
def draw():
background(bg)
orc.move()
orc.display()
| [
"orcs.Orc"
] | [((45, 58), 'orcs.Orc', 'Orc', (['(160)', '(-48)'], {}), '(160, -48)\n', (48, 58), False, 'from orcs import Orc\n')] |
#!/usr/bin/env python
from narwhal import repose
import unittest
from narwhal import conf
from narwhal import pathutil
import xmlrunner as _xmlrunner
import logging
import time
import argparse
import os
import deproxy
logger = logging.getLogger(__name__)
config_dir = pathutil.join(os.getcwd(), 'etc/repose')
deploym... | [
"logging.getLogger",
"unittest.TestSuite",
"narwhal.pathutil.create_folder",
"logging.basicConfig",
"argparse.ArgumentParser",
"deproxy.Deproxy",
"narwhal.conf.process_config_set",
"time.sleep",
"os.getcwd",
"os.path.dirname",
"narwhal.pathutil.clear_folder",
"narwhal.repose.wait_for_node_to_s... | [((229, 256), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (246, 256), False, 'import logging\n'), ((286, 297), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (295, 297), False, 'import os\n'), ((344, 355), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (353, 355), False, 'import os\n'), ((40... |
from category_keys import category_keys
from collections import Counter
import csv
import matplotlib.pyplot as plt
def get_torrent_list(file):
'''Function opens a torrent_dump csv file and creates a list where each element in the list represents a line of
the torrent dump file csv. The elements of this list ar... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"collections.Counter",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"csv.reader",
"matplotlib.pyplot.show"
] | [((1665, 1689), 'collections.Counter', 'Counter', (['categories_list'], {}), '(categories_list)\n', (1672, 1689), False, 'from collections import Counter\n'), ((2686, 2702), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2695, 2702), True, 'import matplotlib.pyplot as plt\n'), ((2707, 2725), 'ma... |
import cv2, base64, json, os, requests
import numpy as np
from fileTools import *
from trainTools import *
from imgTools import *
from eightPuzzle import *
with np.load('./record/knnTrainData.npz') as data:
print(data.files)
trainData = data['trainData']
responses = data['responses']
knn = cv2.... | [
"cv2.ml.KNearest_create",
"os.listdir",
"numpy.load"
] | [((316, 340), 'cv2.ml.KNearest_create', 'cv2.ml.KNearest_create', ([], {}), '()\n', (338, 340), False, 'import cv2, base64, json, os, requests\n'), ((500, 522), 'os.listdir', 'os.listdir', (['"""./source"""'], {}), "('./source')\n", (510, 522), False, 'import cv2, base64, json, os, requests\n'), ((162, 198), 'numpy.loa... |
import json
from rgd import datastore
from rgd.management.commands._data_helper import SynchronousTasksCommand
from . import _data_helper as helper
SUCCESS_MSG = 'Finished loading all landsat data.'
def _get_landsat_urls(count):
path = datastore.datastore.fetch('landsat_texas.json')
with open(path, 'r') as... | [
"rgd.datastore.datastore.fetch"
] | [((245, 292), 'rgd.datastore.datastore.fetch', 'datastore.datastore.fetch', (['"""landsat_texas.json"""'], {}), "('landsat_texas.json')\n", (270, 292), False, 'from rgd import datastore\n')] |
from collections import defaultdict
import async_timeout
import yarl
from factory import Factory, Faker, fuzzy
from yarl import URL
from openapi.testing import json_body
GROUPS = ("group1", "group2", "group3")
class SerieFactory(Factory):
class Meta:
model = dict
value = Faker("pydecimal", positiv... | [
"async_timeout.timeout",
"factory.Faker",
"factory.fuzzy.FuzzyChoice",
"collections.defaultdict",
"yarl.URL",
"openapi.testing.json_body"
] | [((294, 358), 'factory.Faker', 'Faker', (['"""pydecimal"""'], {'positive': '(True)', 'left_digits': '(6)', 'right_digits': '(5)'}), "('pydecimal', positive=True, left_digits=6, right_digits=5)\n", (299, 358), False, 'from factory import Factory, Faker, fuzzy\n'), ((370, 414), 'factory.Faker', 'Faker', (['"""date_time_b... |
"""
Defines types and operations related to MINC files.
"""
from dataclasses import dataclass
from os import PathLike
from typing import Literal, TypeVar, Generic, Optional
from civet.bases import DataFile
from civet.extraction.kernels import ngh_count_kernel
_M = TypeVar('_M', bound='GenericMinc')
_V = TypeVar('_V',... | [
"dataclasses.dataclass",
"typing.TypeVar"
] | [((267, 301), 'typing.TypeVar', 'TypeVar', (['"""_M"""'], {'bound': '"""GenericMinc"""'}), "('_M', bound='GenericMinc')\n", (274, 301), False, 'from typing import Literal, TypeVar, Generic, Optional\n'), ((307, 341), 'typing.TypeVar', 'TypeVar', (['"""_V"""'], {'bound': '"""GenericMinc"""'}), "('_V', bound='GenericMinc... |
from django.urls import reverse
from rest_framework import status
import pytest
@pytest.mark.django_db
def test_user_profile_api_get_success(user_account, api_client):
email = "<EMAIL>"
first_name = "John"
last_name = "Doe"
birthdate = "2021-04-01"
user = user_account(email=email, first_name=fi... | [
"django.urls.reverse"
] | [((439, 478), 'django.urls.reverse', 'reverse', (['"""api-v1-accounts:user-profile"""'], {}), "('api-v1-accounts:user-profile')\n", (446, 478), False, 'from django.urls import reverse\n'), ((1060, 1099), 'django.urls.reverse', 'reverse', (['"""api-v1-accounts:user-profile"""'], {}), "('api-v1-accounts:user-profile')\n"... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECRET_KEY = '<KEY>'
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.con... | [
"os.path.abspath",
"os.path.join"
] | [((2139, 2186), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""social_network/media/"""'], {}), "(BASE_DIR, 'social_network/media/')\n", (2151, 2186), False, 'import os\n'), ((70, 95), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (85, 95), False, 'import os\n'), ((1085, 1120), 'os.path.j... |
#!/usr/bin/env python
from distutils.core import setup
from setuptools import find_packages
setup(
name="mock_zendesk",
version="0.1",
description="Mock zendesk.com service and related utilities",
install_requires=["requests"],
packages=find_packages(),
)
| [
"setuptools.find_packages"
] | [((259, 274), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (272, 274), False, 'from setuptools import find_packages\n')] |
import math
def stripSuffix(name,delineator='_'):
'''
Return the portion of name minus the last element separated by the name delineator.
Useful for determining a name prefix from an existing object name.
@param name: String name to strip the suffix from
@type name: str
@param delineator: String delineator to sp... | [
"math.floor"
] | [((1563, 1580), 'math.floor', 'math.floor', (['depth'], {}), '(depth)\n', (1573, 1580), False, 'import math\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes_py.models.v1.ObjectReference import ObjectReference
from kubernetes_py.models.v1.AWSElasticBlockStoreVolumeSource import AWSEl... | [
"kubernetes_py.models.v1.SecretVolumeSource.SecretVolumeSource",
"kubernetes_py.utils.is_valid_string",
"kubernetes_py.models.v1.GCEPersistentDiskVolumeSource.GCEPersistentDiskVolumeSource",
"kubernetes_py.utils.is_valid_dict",
"kubernetes_py.models.v1.PersistentVolumeClaimVolumeSource.PersistentVolumeClaim... | [((2956, 3019), 'kubernetes_py.models.v1.AWSElasticBlockStoreVolumeSource.AWSElasticBlockStoreVolumeSource', 'AWSElasticBlockStoreVolumeSource', (["model['awsElasticBlockStore']"], {}), "(model['awsElasticBlockStore'])\n", (2988, 3019), False, 'from kubernetes_py.models.v1.AWSElasticBlockStoreVolumeSource import AWSEla... |
import requests
import json
from requests.exceptions import (
ConnectionError,
Timeout,
HTTPError,
)
from lib.json_parser import TextParser
from lib.log_gongik import Logger
from .__PRIVATE import IP, PORT_API, DOWNLOAD_KEY
class LogFileSender(object):
def __init__(self, target_file_dir: str) -> None:... | [
"requests.post",
"lib.json_parser.TextParser",
"json.dumps",
"lib.log_gongik.Logger"
] | [((340, 348), 'lib.log_gongik.Logger', 'Logger', ([], {}), '()\n', (346, 348), False, 'from lib.log_gongik import Logger\n'), ((871, 922), 'json.dumps', 'json.dumps', (["{'pw': self.key, 'log': whole_log_file}"], {}), "({'pw': self.key, 'log': whole_log_file})\n", (881, 922), False, 'import json\n'), ((989, 1035), 'req... |
#!/usr/bin/env python
# Adapted from https://github.com/mrafayaleem/kafka-jython
from __future__ import absolute_import, print_function
import argparse
import pprint
import sys
import threading
import traceback
from kafka.vendor.six.moves import range
from kafka import KafkaProducer
from test.fixtures import KafkaF... | [
"argparse.ArgumentParser",
"pprint.pprint",
"kafka.KafkaProducer",
"traceback.print_exception",
"kafka.vendor.six.moves.range",
"threading.Event",
"sys.exc_info",
"sys.exit",
"test.fixtures.KafkaFixture.instance",
"test.fixtures.ZookeeperFixture.instance"
] | [((490, 517), 'test.fixtures.ZookeeperFixture.instance', 'ZookeeperFixture.instance', ([], {}), '()\n', (515, 517), False, 'from test.fixtures import KafkaFixture, ZookeeperFixture\n'), ((4020, 4117), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This tool is used to verify the producer... |
# -*- coding: utf-8 -*-#
'''
# Name: LSTMCell_1_1
# Description: Implement the basic functions of lstm cell and linear cell
# Can't support batch input
# Author: super
# Date: 2020/6/18
'''
import sys
import math
import numpy as np
from MiniFramework.Layer import *
from MiniFramewo... | [
"numpy.dot",
"numpy.zeros",
"numpy.multiply"
] | [((556, 606), 'numpy.zeros', 'np.zeros', (['(4 * self.hidden_size, self.hidden_size)'], {}), '((4 * self.hidden_size, self.hidden_size))\n', (564, 606), True, 'import numpy as np\n'), ((625, 674), 'numpy.zeros', 'np.zeros', (['(4 * self.input_size, self.hidden_size)'], {}), '((4 * self.input_size, self.hidden_size))\n'... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('gists.urls')),
# url(r'^', include('githubauth.urls')),
url(r'^', include('publicsite.urls')),
)
| [
"django.conf.urls.include"
] | [((94, 115), 'django.conf.urls.include', 'include', (['"""gists.urls"""'], {}), "('gists.urls')\n", (101, 115), False, 'from django.conf.urls import patterns, include, url\n'), ((177, 203), 'django.conf.urls.include', 'include', (['"""publicsite.urls"""'], {}), "('publicsite.urls')\n", (184, 203), False, 'from django.c... |
# Copyright 2019 <NAME>
# Licensed under the MIT License (the "License").
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at https://mit-license.org
# February 2019
# This script tests color function of filterizePy package.
import pytest
import numpy as np
impo... | [
"filterizePy.greenscale.greenscale",
"numpy.array",
"numpy.array_equal",
"imghdr.what",
"pytest.raises"
] | [((495, 800), 'numpy.array', 'np.array', (['[[[255, 255, 255], [255, 255, 255], [255, 255, 255]], [[255, 255, 255], [\n 255, 255, 255], [255, 255, 255]], [[255, 255, 255], [255, 255, 255], [\n 255, 255, 255]], [[255, 255, 255], [255, 255, 255], [255, 255, 255]], [\n [255, 255, 255], [255, 255, 255], [255, 255,... |
"""Models an organization as configured in github
Via an instance of `Organization` the configuration can be retrieved and updated.
"""
import functools
import os
from . import dict_diff, utils
# These fields define the properties that are available in each of the subgroups of
# the configuration that can be found ... | [
"functools.reduce"
] | [((1779, 1820), 'functools.reduce', 'functools.reduce', (['os.path.join', 'url_parts'], {}), '(os.path.join, url_parts)\n', (1795, 1820), False, 'import functools\n'), ((2237, 2278), 'functools.reduce', 'functools.reduce', (['os.path.join', 'url_parts'], {}), '(os.path.join, url_parts)\n', (2253, 2278), False, 'import ... |
# Programowanie I R
# Pakiet NumPy
import numpy as np
arr_list = np.array([1, 2, 3, 4, 5])
print(arr_list)
print(type(arr_list))
print()
arr_tuple = np.array((1, 2, 3, 4, 5))
print(arr_tuple)
print(type(arr_tuple))
print()
arr = np.array(42)
print(arr)
print(arr.ndim)
print()
arr = np.array([[1, 2, 3], [4, 5, 6]... | [
"numpy.multiply",
"numpy.add",
"numpy.subtract",
"numpy.array",
"numpy.divide"
] | [((67, 92), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (75, 92), True, 'import numpy as np\n'), ((153, 178), 'numpy.array', 'np.array', (['(1, 2, 3, 4, 5)'], {}), '((1, 2, 3, 4, 5))\n', (161, 178), True, 'import numpy as np\n'), ((235, 247), 'numpy.array', 'np.array', (['(42)'], {}), '... |
# -*- coding: utf-8 -*-
import sys
import os
modulepath = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if modulepath not in sys.path:
sys.path.insert(0, modulepath)
from mdstudio.runner import main
from common_resources.resources_endpoints import Common_resources
if __name__ == '__main__':
... | [
"os.path.dirname",
"sys.path.insert",
"mdstudio.runner.main"
] | [((159, 189), 'sys.path.insert', 'sys.path.insert', (['(0)', 'modulepath'], {}), '(0, modulepath)\n', (174, 189), False, 'import sys\n'), ((322, 344), 'mdstudio.runner.main', 'main', (['Common_resources'], {}), '(Common_resources)\n', (326, 344), False, 'from mdstudio.runner import main\n'), ((89, 114), 'os.path.dirnam... |
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
def sliders(f, sliders_properties, wait_for_validation = False):
""" A light GUI to manually explore and tune the outputs of
a function.
slider_properties is a list of dicts (arguments for Slider )
def v... | [
"matplotlib.widgets.Slider",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((737, 752), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (749, 752), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2180), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2178, 2180), True, 'import matplotlib.pyplot as plt\n'), ((1267, 1344), 'matplotlib.pyplot.axes', 'plt.axes'... |
# ===============================================================================
# Copyright 2015 <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/LI... | [
"traitsui.api.Item"
] | [((1578, 1594), 'traitsui.api.Item', 'Item', (['"""username"""'], {}), "('username')\n", (1582, 1594), False, 'from traitsui.api import View, Item, VGroup\n'), ((1596, 1612), 'traitsui.api.Item', 'Item', (['"""password"""'], {}), "('password')\n", (1600, 1612), False, 'from traitsui.api import View, Item, VGroup\n'), (... |
import logging
from flask import flash
from flask import request
from flask import (url_for, redirect)
from flask.views import MethodView
from cert_viewer import helpers
from cert_viewer.forms import BitcoinForm, SimpleRegistrationForm
from cert_viewer.notifier import Notifier
from cert_viewer.views.__init__ import r... | [
"cert_viewer.forms.BitcoinForm",
"logging.debug",
"flask.flash",
"cert_viewer.views.__init__.render",
"flask.url_for",
"cert_viewer.helpers.obfuscate_email_display",
"cert_viewer.forms.SimpleRegistrationForm",
"cert_viewer.notifier.Notifier.factory",
"cert_viewer.introduction_store_bridge.insert_int... | [((430, 466), 'cert_viewer.forms.SimpleRegistrationForm', 'SimpleRegistrationForm', (['request.form'], {}), '(request.form)\n', (452, 466), False, 'from cert_viewer.forms import BitcoinForm, SimpleRegistrationForm\n'), ((1827, 1863), 'cert_viewer.forms.SimpleRegistrationForm', 'SimpleRegistrationForm', (['request.form'... |
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
def fabool(bool_):
"""Return a font-awesome boolean checkbox icon."""
if bool_:
txt = "<i class='fa fa-check-square-o' title'checked'></i>"
else:
txt = "... | [
"django.utils.safestring.mark_safe",
"django.template.Library"
] | [((87, 105), 'django.template.Library', 'template.Library', ([], {}), '()\n', (103, 105), False, 'from django import template\n'), ((382, 396), 'django.utils.safestring.mark_safe', 'mark_safe', (['txt'], {}), '(txt)\n', (391, 396), False, 'from django.utils.safestring import mark_safe\n')] |
# Plugin made by @okay_retard && @hellboi_atul...
# If Gonna kang then keep credits..don't edit/remove these lines...
# else gay
from telethon.tl.types import InputMessagesFilterMusic
from userbot.utils import admin_cmd
from telethon.tl.functions.messages import ImportChatInviteRequest
from telethon.errors.rpcerrorlist... | [
"userbot.utils.admin_cmd",
"telethon.tl.functions.messages.ImportChatInviteRequest"
] | [((367, 391), 'userbot.utils.admin_cmd', 'admin_cmd', (['"""sptfy ?(.*)"""'], {}), "('sptfy ?(.*)')\n", (376, 391), False, 'from userbot.utils import admin_cmd\n'), ((448, 497), 'telethon.tl.functions.messages.ImportChatInviteRequest', 'ImportChatInviteRequest', (['"""DdR2SUvJPBouSW4QlbJU4g"""'], {}), "('DdR2SUvJPBouSW... |
import pytest
from pycfmodel.model.cf_model import CFModel
from cfripper.model.enums import RuleGranularity, RuleMode, RuleRisk
from cfripper.model.result import Failure
from cfripper.rules.iam_roles import IAMRolesOverprivilegedRule
from tests.utils import compare_lists_of_failures, get_cfmodel_from
@pytest.fixture... | [
"cfripper.rules.iam_roles.IAMRolesOverprivilegedRule",
"cfripper.model.result.Failure",
"tests.utils.get_cfmodel_from",
"pytest.fixture",
"tests.utils.compare_lists_of_failures"
] | [((306, 322), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (320, 322), False, 'import pytest\n'), ((473, 489), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (487, 489), False, 'import pytest\n'), ((644, 660), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (658, 660), False, 'import pytest\n'), (... |
from iter_helpers import transpose
from iter_helpers import scalar_product
from utils import profile
from utils import timer
from linked_list import Node
from linked_list import flatten_linked_list
from os import stat
from os import listdir
from utils import calculate_stats
@profile
def some_function():
return su... | [
"linked_list.flatten_linked_list",
"iter_helpers.scalar_product",
"linked_list.Node",
"iter_helpers.transpose",
"utils.calculate_stats"
] | [((415, 443), 'iter_helpers.transpose', 'transpose', (['[[1, -1], [2, 3]]'], {}), '([[1, -1], [2, 3]])\n', (424, 443), False, 'from iter_helpers import transpose\n'), ((544, 593), 'iter_helpers.scalar_product', 'scalar_product', (["[1, '2', '3b', 4]", '[-1, 1, 2, -2]'], {}), "([1, '2', '3b', 4], [-1, 1, 2, -2])\n", (55... |
import sys
from models.lstm_vae import *
from models.lstm import *
from models.lstm_vae_output import *
from models.nn import *
from keras.models import model_from_json
import pickle as pkl
from functions import *
from constants import *
from scipy import spatial
from rake_nltk import Rake
import numpy as np
glove_pat... | [
"numpy.array",
"rake_nltk.Rake",
"numpy.argmax",
"scipy.spatial.KDTree"
] | [((2854, 2860), 'rake_nltk.Rake', 'Rake', ([], {}), '()\n', (2858, 2860), False, 'from rake_nltk import Rake\n'), ((6019, 6039), 'numpy.array', 'np.array', (['train_data'], {}), '(train_data)\n', (6027, 6039), True, 'import numpy as np\n'), ((8112, 8123), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (8120, 8123), T... |
# Diamond Miner is a game that is similar to Gold Miner, but there are nnn miners instead of 111 in this game.
# The mining area can be described as a plane. The nnn miners can be regarded as nnn points on the y-axis. There are nnn diamond mines in the mining area. We can regard them as nnn points on the x-axis. For so... | [
"math.sqrt"
] | [((950, 995), 'math.sqrt', 'sqrt', (['((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)'], {}), '((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)\n', (954, 995), False, 'from math import sqrt\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from glob import glob
import re
package_name = 'pyconsole'
version_str = re.search(r'^__version__\s+=\s+[\'"](.+)[\'"]',
open('%s/version.py' % (package_name, )).read(),
re.M).group(1)
setup(name=package_name,
... | [
"setuptools.find_packages"
] | [((523, 538), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (536, 538), False, 'from setuptools import setup, find_packages\n')] |
import eyekit
sentence = "The quick brown fox [jump]{stem_1}[ed]{suffix_1} over the lazy dog."
txt = eyekit.TextBlock(
sentence, position=(100, 500), font_face="Times New Roman", font_size=36
)
seq = eyekit.FixationSequence(
[
[106, 490, 0, 100],
[190, 486, 100, 200],
[230, 505, 200, 30... | [
"eyekit.FixationSequence",
"eyekit.TextBlock"
] | [((102, 196), 'eyekit.TextBlock', 'eyekit.TextBlock', (['sentence'], {'position': '(100, 500)', 'font_face': '"""Times New Roman"""', 'font_size': '(36)'}), "(sentence, position=(100, 500), font_face='Times New Roman',\n font_size=36)\n", (118, 196), False, 'import eyekit\n'), ((205, 517), 'eyekit.FixationSequence',... |
# Copyright 2020 The MathWorks, Inc.
import os
from pathlib import Path
import tempfile
import xml.etree.ElementTree as ET
import uuid
import shutil
def get_matlab_path():
which_matlab = shutil.which("matlab")
if which_matlab is None:
return None
return Path(which_matlab).resolve().parent.parent
... | [
"xml.etree.ElementTree.parse",
"os.getenv",
"pathlib.Path",
"pathlib.Path.home",
"shutil.which",
"os.environ.get",
"uuid.uuid4",
"tempfile.gettempdir",
"tempfile.mkstemp"
] | [((194, 216), 'shutil.which', 'shutil.which', (['"""matlab"""'], {}), "('matlab')\n", (206, 216), False, 'import shutil\n'), ((476, 517), 'xml.etree.ElementTree.parse', 'ET.parse', (["(matlab_path / 'VersionInfo.xml')"], {}), "(matlab_path / 'VersionInfo.xml')\n", (484, 517), True, 'import xml.etree.ElementTree as ET\n... |
import numpy as np
import matplotlib.pyplot as plt
import knn
def knn_plot(x, y, k):
plt.figure(figsize=(10, 10))
color = ['red', 'blue']
for label in np.unique(y):
p = x[y == label]
plt.scatter(p[:, 0], p[:, 1], s=3, c=color[label])
xmin = np.min(x[:, 0])
xmax = np.max(x[:, 0... | [
"numpy.unique",
"knn.knn",
"numpy.max",
"matplotlib.pyplot.contour",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"numpy.min",
"matplotlib.pyplot.title",
"numpy.arange"
] | [((93, 121), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (103, 121), True, 'import matplotlib.pyplot as plt\n'), ((169, 181), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (178, 181), True, 'import numpy as np\n'), ((280, 295), 'numpy.min', 'np.min', (['x[:, 0]'... |
import nltk
from sln_constructor import *
def test_normalize_word_pos_tag():
words = ["Jack", "like", "the", "flower", "and", "a", "bird", "which", "danced", "in", "the", "window"]
words = ["Jack", "is", "shit"]
print(nltk.pos_tag(words))
print(normalize_word_pos_tag(words))
def test_merge_neighbor_id... | [
"nltk.pos_tag"
] | [((998, 1017), 'nltk.pos_tag', 'nltk.pos_tag', (['words'], {}), '(words)\n', (1010, 1017), False, 'import nltk\n'), ((231, 250), 'nltk.pos_tag', 'nltk.pos_tag', (['words'], {}), '(words)\n', (243, 250), False, 'import nltk\n')] |
# flake8: noqa
import datetime
import uuid
from typing import Mapping, cast, MutableMapping
import json
from behave import given, when, then
from hamcrest import assert_that, equal_to, instance_of, none, less_than, is_not
from test.e2e.steps.common import make_request
from bookshop.sqlalchemy.model.Author import Auth... | [
"behave.given",
"json.loads",
"bookshop.db.drop_all",
"test.e2e.steps.common.make_request",
"datetime.datetime.utcnow",
"hamcrest.none",
"hamcrest.less_than",
"bookshop.sqlalchemy.model.Author.Author.query.filter",
"bookshop.db.create_all",
"datetime.timedelta",
"uuid.uuid4",
"behave.when",
... | [((1214, 1266), 'behave.given', 'given', (['"""I have the example "{app_name}" application"""'], {}), '(\'I have the example "{app_name}" application\')\n', (1219, 1266), False, 'from behave import given, when, then\n'), ((1524, 1572), 'behave.given', 'given', (['"""I put an example "{entity_type}" entity"""'], {}), '(... |
"""
api.py
"""
import requests
class Api:
"""First layer above HTTP API requests."""
def __init__(self, url, token, debug=False, timer=False):
"""Returns a new Cloudrun session."""
self.base_url = url.rstrip('/')
self.token = token
self.debug = debug
self.timer = t... | [
"requests.patch",
"requests.post",
"requests.get",
"requests.delete"
] | [((629, 675), 'requests.post', 'requests.post', (['url'], {'headers': 'headers', 'data': 'data'}), '(url, headers=headers, data=data)\n', (642, 675), False, 'import requests\n'), ((907, 944), 'requests.delete', 'requests.delete', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (922, 944), False, 'import ... |
from datetime import datetime, timedelta
import logging
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from vcweb.core.models import Participant, Institution, set_full_name
from vcweb.core.models import OstromlabFaqEntry
logger = logging.getLogger(__name__)
class C... | [
"logging.getLogger",
"vcweb.core.models.OstromlabFaqEntry.objects.get_or_create",
"vcweb.core.models.Institution.objects.get",
"vcweb.core.models.Participant.objects.get",
"vcweb.core.models.Participant",
"datetime.datetime.now",
"vcweb.core.models.Participant.objects.bulk_create",
"vcweb.core.models.... | [((283, 310), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (300, 310), False, 'import logging\n'), ((787, 843), 'vcweb.core.models.Institution.objects.get', 'Institution.objects.get', ([], {'name': '"""Arizona State University"""'}), "(name='Arizona State University')\n", (810, 843), Fa... |
from django.contrib import admin
from django.contrib.staticfiles.urls import static
from django.urls import path, include
from . import settings
#プロジェクトURL
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('ecsitecore.urls')),
path('accounts/', include('accounts.urls')),
]
# 開発サーバーでメディアを配信... | [
"django.urls.path",
"django.contrib.staticfiles.urls.static",
"django.urls.include"
] | [((346, 407), 'django.contrib.staticfiles.urls.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n', (352, 407), False, 'from django.contrib.staticfiles.urls import static\n'), ((177, 208), 'django.urls.path', 'path', (['"""ad... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.text import slugify
def add_slugs(apps, schema_editor):
StandupUser = apps.get_model('status', 'StandupUser')
# For every StandupUser that has a slug that's either null or '', we want t... | [
"django.utils.text.slugify",
"django.db.models.Q",
"django.db.migrations.RunPython"
] | [((725, 742), 'django.utils.text.slugify', 'slugify', (['username'], {}), '(username)\n', (732, 742), False, 'from django.utils.text import slugify\n'), ((947, 997), 'django.db.migrations.RunPython', 'migrations.RunPython', (['add_slugs', '(lambda x, y: None)'], {}), '(add_slugs, lambda x, y: None)\n', (967, 997), Fals... |
f = open ( 'tmp/db_init.json', 'w' )
import json
init_dict = {}
init_dict['admin'] = [('Alice', 'a'), ('Bob', 'b'), ('Curry', 'c'), ('王二狗', 'w'), ('李三蛋', 'l'), ('陈鸿宇', 'c')]
init_dict['buy'] = [("HK_TENCENT", 10.2, 100), ("APPLE", 1.2, 24), ("APPLE", 1.2, 24), ("BMW", 1.2, 24),
("爱康科技", 2.3, 30000)... | [
"json.dumps"
] | [((685, 740), 'json.dumps', 'json.dumps', (['init_dict'], {'indent': '(4)', 'separators': "(',', ': ')"}), "(init_dict, indent=4, separators=(',', ': '))\n", (695, 740), False, 'import json\n')] |
import re
patterns = ["term1", "term2"]
text = "This is a string with term1, not the other"
split_term = "@"
email = "<EMAIL>"
# for pattern in patterns:
# print("I'm searching for: " + pattern)
#
# if re.search(pattern, text):
# print("MATCH!")
# else:
# print("NO MATCH!")
print(re.spli... | [
"re.split",
"re.findall"
] | [((313, 340), 're.split', 're.split', (['split_term', 'email'], {}), '(split_term, email)\n', (321, 340), False, 'import re\n'), ((392, 448), 're.findall', 're.findall', (['"""match"""', '"""test phrase match in match middle"""'], {}), "('match', 'test phrase match in match middle')\n", (402, 448), False, 'import re\n'... |
#!/usr/bin/env python3
# Copyright (c) 2021, The University of Southern California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above cop... | [
"logic_form_graph.create_logic_form_graphs_from_logic_forms",
"argparse.ArgumentParser"
] | [((15378, 15403), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (15401, 15403), False, 'import argparse\n'), ((15939, 16001), 'logic_form_graph.create_logic_form_graphs_from_logic_forms', 'lfg.create_logic_form_graphs_from_logic_forms', (['args.logicforms'], {}), '(args.logicforms)\n', (15984,... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from permabots.models.base import PermabotsModel
@python_2_unicode_compatible
class MessengerMessage(PermabotsModel):
bot = models.ForeignKey('... | [
"django.utils.translation.ugettext_lazy",
"django.db.models.CharField"
] | [((786, 840), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'choices': 'TYPE_CHOICES'}), '(max_length=255, choices=TYPE_CHOICES)\n', (802, 840), False, 'from django.db import models\n'), ((423, 437), 'django.utils.translation.ugettext_lazy', '_', (['"""Sender Id"""'], {}), "('Sender Id'... |
import tensorflow as tf
# Generally, definitions of different layers of the network. Also, combinations of those layers
# to form a full network graph
# Set of functions for implementing the tensor module from Ng et al.
# https://cs.stanford.edu/~danqi/papers/nips2013.pdf
# closer to implementation by Ma et al.
# htt... | [
"tensorflow.tile",
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.random_normal",
"tensorflow.random_normal_initializer",
"tensorflow.concat",
"tensorflow.matmul",
"tensorflow.layers.conv1d",
"tensorflow.stack",
"tensorflow.summary.merge_all",... | [((1166, 1227), 'tensorflow.broadcast_to', 'tf.broadcast_to', (['var_w', '[batch_size, out_dim, in_dim, in_dim]'], {}), '(var_w, [batch_size, out_dim, in_dim, in_dim])\n', (1181, 1227), True, 'import tensorflow as tf\n'), ((1405, 1458), 'tensorflow.broadcast_to', 'tf.broadcast_to', (['var_v', '[batch_size, out_dim, in_... |
import pytest
pytestmark = pytest.mark.page('non_control_elements.html')
class TestLis(object):
def test_with_selectors_returns_the_matching_elements(self, browser):
assert list(browser.lis(class_name='nonlink')) == \
[browser.li(class_name='nonlink')]
def test_returns_the_correct_number... | [
"pytest.mark.page"
] | [((28, 73), 'pytest.mark.page', 'pytest.mark.page', (['"""non_control_elements.html"""'], {}), "('non_control_elements.html')\n", (44, 73), False, 'import pytest\n')] |
# Copyright (c) AIRBUS and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import numpy as np
import gym
from typing import Callable
from collections.abc import Iterable
from skde... | [
"numpy.sqrt",
"numpy.random.random_sample",
"numpy.random.random_integers",
"numpy.array",
"numpy.zeros",
"numpy.isnan",
"numpy.random.seed"
] | [((864, 883), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n', (872, 883), True, 'import numpy as np\n'), ((905, 924), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n', (913, 924), True, 'import numpy as np\n'), ((951, 970), 'numpy.zeros', 'np.zeros', (['nb_inputs'], {}), '(nb_inputs)\n',... |
from django.contrib import admin
from .models import Like, Post
from .models import Comment
# Register your models here.
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Like) | [
"django.contrib.admin.site.register"
] | [((123, 148), 'django.contrib.admin.site.register', 'admin.site.register', (['Post'], {}), '(Post)\n', (142, 148), False, 'from django.contrib import admin\n'), ((149, 177), 'django.contrib.admin.site.register', 'admin.site.register', (['Comment'], {}), '(Comment)\n', (168, 177), False, 'from django.contrib import admi... |
# Copyright 2017 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... | [
"tensorflow.python.ops.distributions.util.gen_new_seed",
"tensorflow.python.ops.standard_ops.tensordot",
"tensorflow.python.ops.standard_ops.matmul",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.layers.base.InputSpec",
"tensorflow.p... | [((18725, 18767), 'tensorflow.contrib.bayesflow.python.ops.layers_util.default_mean_field_normal_fn', 'layers_util.default_mean_field_normal_fn', ([], {}), '()\n', (18765, 18767), False, 'from tensorflow.contrib.bayesflow.python.ops import layers_util\n'), ((19082, 19140), 'tensorflow.contrib.bayesflow.python.ops.layer... |
from typing import Optional, Tuple
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from counter_app.database import Base, engine
from counter_app.routers import count
from counter_app.utils.constants import COMMIT_SHA, ENV, ApiTags
Base.metadata.create_all(bind=engine)
... | [
"fastapi.FastAPI",
"counter_app.database.Base.metadata.create_all",
"uvicorn.run"
] | [((281, 318), 'counter_app.database.Base.metadata.create_all', 'Base.metadata.create_all', ([], {'bind': 'engine'}), '(bind=engine)\n', (305, 318), False, 'from counter_app.database import Base, engine\n'), ((382, 416), 'fastapi.FastAPI', 'FastAPI', ([], {'openapi_tags': 'openapi_tags'}), '(openapi_tags=openapi_tags)\n... |
import csv
import os
import shutil
from os import listdir
from os.path import isfile, join
import subprocess
from collections import defaultdict
badTracks = set()
homeDir = "./"
for f in sorted(listdir(homeDir)):
if isfile(join(homeDir, f)) or f in ("output", 'analysis', 'hold') or "." in f:
continue
print("P... | [
"os.path.exists",
"os.listdir",
"os.makedirs",
"shutil.copy2",
"os.path.join",
"os.path.splitext",
"collections.defaultdict",
"subprocess.call",
"shutil.rmtree",
"csv.reader"
] | [((196, 212), 'os.listdir', 'listdir', (['homeDir'], {}), '(homeDir)\n', (203, 212), False, 'from os import listdir\n'), ((1027, 1055), 'os.path.join', 'join', (['homeDir', 'f', '"""word.csv"""'], {}), "(homeDir, f, 'word.csv')\n", (1031, 1055), False, 'from os.path import isfile, join\n'), ((1085, 1102), 'collections.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 22:08:25 2020
@author: andyq
"""
import torch.nn as nn
import torch.nn.functional as F
class CNN_LSTM(nn.Module):
def __init__(self):
super(CNN_LSTM,self).__init__()
self.conv1 = nn.Conv1d(1,3,kernel_size=20,stride=1,padding=... | [
"torch.nn.MaxPool1d",
"torch.nn.Dropout",
"torch.nn.LSTM",
"torch.nn.Linear",
"torch.nn.Conv1d"
] | [((274, 327), 'torch.nn.Conv1d', 'nn.Conv1d', (['(1)', '(3)'], {'kernel_size': '(20)', 'stride': '(1)', 'padding': '(19)'}), '(1, 3, kernel_size=20, stride=1, padding=19)\n', (283, 327), True, 'import torch.nn as nn\n'), ((345, 397), 'torch.nn.Conv1d', 'nn.Conv1d', (['(3)', '(6)'], {'kernel_size': '(10)', 'stride': '(1... |
### First draft of a Quantum Circuit object
import numpy as np
def kron(*args):
## multiple kronecker product
qb = np.array([[1.0]])
for q in args:
qb = np.kron(qb, q)
return qb
def n_kron(n, vector):
## n kronecker product with itself
ret = np.array([[1.0]])
for _... | [
"numpy.eye",
"numpy.sqrt",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.conjugate",
"numpy.kron",
"numpy.array",
"numpy.dot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((133, 150), 'numpy.array', 'np.array', (['[[1.0]]'], {}), '([[1.0]])\n', (141, 150), True, 'import numpy as np\n'), ((292, 309), 'numpy.array', 'np.array', (['[[1.0]]'], {}), '([[1.0]])\n', (300, 309), True, 'import numpy as np\n'), ((672, 681), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (678, 681), True, 'import... |
"""initialize models
Revision ID: 59df0866b02a
Revises:
Create Date: 2020-03-15 20:43:06.005586
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '59df0866b02a'
down_revision = None
branch_labels = None
depends_on = None... | [
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.text",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"alembic.op.f",
"sqlalchemy.Text",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Unicode",
"sqlalchemy.Integer",
"sqlalchemy.UniqueConstraint",
"sqlalchemy.dialects.postgresql.UUID",
"sqlalch... | [((3808, 3844), 'alembic.op.drop_table', 'op.drop_table', (['"""corona__association"""'], {}), "('corona__association')\n", (3821, 3844), False, 'from alembic import op\n'), ((4345, 4376), 'alembic.op.drop_table', 'op.drop_table', (['"""corona__person"""'], {}), "('corona__person')\n", (4358, 4376), False, 'from alembi... |
import socket
from django.conf import settings
from djutils.dashboard.provider import PanelProvider
from djutils.dashboard.registry import registry
try:
import psycopg2
except ImportError:
psycopg2 = None
def get_db_setting(key):
try:
return settings.DATABASES['default'][key]
except KeyError... | [
"socket.socket",
"djutils.dashboard.registry.registry.register"
] | [((7432, 7458), 'djutils.dashboard.registry.registry.register', 'registry.register', (['CPUInfo'], {}), '(CPUInfo)\n', (7449, 7458), False, 'from djutils.dashboard.registry import registry\n'), ((7482, 7522), 'djutils.dashboard.registry.registry.register', 'registry.register', (['RedisConnectedClients'], {}), '(RedisCo... |
import os
class Config(object):
# get a token from @BotFather
TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
# The Telegram API things
APP_ID = int(os.environ.get("APP_ID", 12345))
API_HASH = os.environ.get("API_HASH")
# Get these values from my.telegram.org
# Array to store users who... | [
"os.environ.get"
] | [((87, 121), 'os.environ.get', 'os.environ.get', (['"""TG_BOT_TOKEN"""', '""""""'], {}), "('TG_BOT_TOKEN', '')\n", (101, 121), False, 'import os\n'), ((218, 244), 'os.environ.get', 'os.environ.get', (['"""API_HASH"""'], {}), "('API_HASH')\n", (232, 244), False, 'import os\n'), ((758, 792), 'os.environ.get', 'os.environ... |
# Copyright 2018 AT&T Intellectual Property. All other 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... | [
"logging.getLogger",
"dateutil.parser.parse",
"collections.OrderedDict",
"subprocess.check_output",
"tempfile.TemporaryDirectory",
"json.loads",
"os.listdir",
"subprocess.check_call",
"datetime.datetime.utcnow",
"json.dumps",
"os.path.join",
"pegleg.engine.util.pegleg_managed_document.PeglegMa... | [((1140, 1167), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1157, 1167), False, 'import logging\n'), ((11663, 11725), 'yaml.add_representer', 'yaml.add_representer', (['block_literal', 'block_literal_representer'], {}), '(block_literal, block_literal_representer)\n', (11683, 11725), F... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(c) 2016 Nippon Telegraph and Telephone Corporation
#
# 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/lic... | [
"mock.patch",
"masakari_config.RecoveryControllerConfig",
"masakari_worker.RecoveryControllerWorker",
"os.path.abspath",
"fakes.FakeNovaServer",
"unittest.TextTestRunner",
"unittest.TestLoader"
] | [((1232, 1287), 'masakari_config.RecoveryControllerConfig', 'masakari_config.RecoveryControllerConfig', (['sample_config'], {}), '(sample_config)\n', (1272, 1287), False, 'import masakari_config\n'), ((3326, 3375), 'fakes.FakeNovaServer', 'nova_fakes.FakeNovaServer', (['"""uuid1"""', '"""stopped"""', '{}'], {}), "('uui... |
import numpy as np
class CrossEntropy(object):
def __init__(self):
pass
def forward(self, out, y):
loss = lambda x, y: -(y*np.log(x +.0001)) - ((1.01 - y) * np.log(1.01 - x))
if out.ndim > 1:
return np.mean(loss(out, y))
else:
return loss(ou... | [
"numpy.log",
"numpy.subtract"
] | [((383, 402), 'numpy.subtract', 'np.subtract', (['out', 'y'], {}), '(out, y)\n', (394, 402), True, 'import numpy as np\n'), ((195, 211), 'numpy.log', 'np.log', (['(1.01 - x)'], {}), '(1.01 - x)\n', (201, 211), True, 'import numpy as np\n'), ((161, 179), 'numpy.log', 'np.log', (['(x + 0.0001)'], {}), '(x + 0.0001)\n', (... |
import unittest
from Problem41 import find_largest_pandigital_prime, is_prime_number
class TestProblem41(unittest.TestCase):
def test_main_function(self):
self.assertEqual(find_largest_pandigital_prime(1, 9), 7652413, 'the result of the function does not match the expected result.')
self.assertEqua... | [
"unittest.main",
"Problem41.is_prime_number",
"Problem41.find_largest_pandigital_prime"
] | [((2343, 2358), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2356, 2358), False, 'import unittest\n'), ((185, 220), 'Problem41.find_largest_pandigital_prime', 'find_largest_pandigital_prime', (['(1)', '(9)'], {}), '(1, 9)\n', (214, 220), False, 'from Problem41 import find_largest_pandigital_prime, is_prime_numb... |
""" Authorization based on Allowed HOSTS lists."""
import fnmatch
import logging
from .base import BaseAuthzHandler
from navigator.conf import ALLOWED_HOSTS
from aiohttp import web
class authz_allow_hosts(BaseAuthzHandler):
"""
Allowed Hosts.
Check if Origin is on the Allowed Hosts List.
"""
as... | [
"fnmatch.fnmatch"
] | [((589, 617), 'fnmatch.fnmatch', 'fnmatch.fnmatch', (['origin', 'key'], {}), '(origin, key)\n', (604, 617), False, 'import fnmatch\n')] |
"""
Module for reading and indexing Starbound assets
"""
import os
import json
import re
import sqlite3
import logging
import starbound
import starbound.btreedb4
from assets.blueprints import Blueprints
from assets.items import Items
from assets.species import Species
from assets.player import Player
from assets.mon... | [
"re.compile",
"starbound.open_file",
"assets.items.Items",
"assets.species.Species",
"assets.techs.Techs",
"logging.exception",
"logging.info",
"assets.player.Player",
"os.walk",
"assets.common.asset_category",
"assets.blueprints.Blueprints",
"os.listdir",
"os.path.normpath",
"os.path.isdi... | [((529, 656), 're.compile', 're.compile', (['"""("(\\\\[\\\\s\\\\S]|[^"])*")|((^)?[^\\\\S\n]*/(?:\\\\*(.*?)\\\\*/[^\\\\S\n]*|/[^\n]*)($)?)"""', '(re.DOTALL | re.MULTILINE)'], {}), '(\n """("(\\\\[\\\\s\\\\S]|[^"])*")|((^)?[^\\\\S\n]*/(?:\\\\*(.*?)\\\\*/[^\\\\S\n]*|/[^\n]*)($)?)"""\n , re.DOTALL | re.MULTILINE)\n'... |
#!/usr/bin/env python
"""
synopsis:
Lazy Pirate client
Use zmq_poll to do a safe request-reply
To run, start lpserver and then randomly kill/restart it
Modified for async/ioloop: <NAME> <dkuhlman(at)davekuhlman(dot)org>
usage:
python lpclient.py
"""
import sys
from functools import partial
import ... | [
"zmq.eventloop.ioloop.IOLoop.current",
"zmq.eventloop.future.Context",
"functools.partial",
"zmq.eventloop.future.Poller",
"sys.exit"
] | [((688, 696), 'zmq.eventloop.future.Poller', 'Poller', ([], {}), '()\n', (694, 696), False, 'from zmq.eventloop.future import Context, Poller\n'), ((2401, 2410), 'zmq.eventloop.future.Context', 'Context', ([], {}), '()\n', (2408, 2410), False, 'from zmq.eventloop.future import Context, Poller\n'), ((2530, 2547), 'sys.e... |
"""Models for Short URL service."""
import os
from datetime import datetime
from models import ModelDefaultValueExt, Model
from models.field import (
TextField, UrlField, ArrayField, ObjectIDField, BooleanField
)
from strres.models import ShortUrl
class ShortUrlRecordModel(Model):
"""Model for a short URL re... | [
"os.environ.get",
"models.field.UrlField",
"models.field.ArrayField",
"models.field.BooleanField",
"models.field.TextField",
"models.field.ObjectIDField"
] | [((473, 527), 'models.field.TextField', 'TextField', (['"""cd"""'], {'default': 'ModelDefaultValueExt.Required'}), "('cd', default=ModelDefaultValueExt.Required)\n", (482, 527), False, 'from models.field import TextField, UrlField, ArrayField, ObjectIDField, BooleanField\n'), ((541, 595), 'models.field.UrlField', 'UrlF... |
#!/usr/bin/env python
""" Empirically simulate the birthday paradox
The birthday paradox is the surprisingly high change that two
people in a group of people share the same birthday.
See https://en.wikipedia.org/wiki/Birthday_problem for details.
"""
import random
from matplotlib import pyplot as plt
import numpy... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"numpy.cumsum",
"random.randint",
"matplotlib.pyplot.show"
] | [((956, 991), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of simulations"""'], {}), "('Number of simulations')\n", (966, 991), True, 'from matplotlib import pyplot as plt\n'), ((996, 1071), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of people in room when first birthday collision occurs"""'], {})... |
from unittest import TestCase
from api_buddy.utils.http import pack_query_params, unpack_query_params
from api_buddy.utils.exceptions import APIBuddyException
FIRST_NAME = 'George'
MIDDLE_NAME = 'Louis'
LAST_NAME = 'Costanza'
class TestPackParams(TestCase):
def test_parses_params_into_a_dict(self):
packe... | [
"api_buddy.utils.http.pack_query_params",
"api_buddy.utils.http.unpack_query_params"
] | [((331, 404), 'api_buddy.utils.http.pack_query_params', 'pack_query_params', (["[f'first_name={FIRST_NAME}', f'last_name={LAST_NAME}']"], {}), "([f'first_name={FIRST_NAME}', f'last_name={LAST_NAME}'])\n", (348, 404), False, 'from api_buddy.utils.http import pack_query_params, unpack_query_params\n'), ((746, 838), 'api_... |
import onnx
import torch
from onnx_pytorch.op_code_generators import OpCodeGenerator
class UpsampleOpCodeGenerator(OpCodeGenerator):
def __init__(self,
onnx_ver=onnx.defs.onnx_opset_version(),
torch_ver=torch.__version__):
super(UpsampleOpCodeGenerator, self).__init__(onnx_ver, t... | [
"onnx.defs.onnx_opset_version",
"onnx.numpy_helper.to_array"
] | [((182, 212), 'onnx.defs.onnx_opset_version', 'onnx.defs.onnx_opset_version', ([], {}), '()\n', (210, 212), False, 'import onnx\n'), ((633, 688), 'onnx.numpy_helper.to_array', 'onnx.numpy_helper.to_array', (['initializers[node.input[1]]'], {}), '(initializers[node.input[1]])\n', (659, 688), False, 'import onnx\n')] |
# coding=utf-8
# Copyright (c) 2016-2018, F5 Networks, 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 applicabl... | [
"f5_openstack_agent.lbaasv2.drivers.bigip.utils.get_filter",
"oslo_log.log.getLogger"
] | [((751, 778), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (768, 778), True, 'from oslo_log import log as logging\n'), ((5618, 5665), 'f5_openstack_agent.lbaasv2.drivers.bigip.utils.get_filter', 'get_filter', (['bigip', '"""partition"""', '"""eq"""', 'partition'], {}), "(bigip, 'pa... |
# Time: init: O(N), pick: O(logN)
# Space: O(N)
class Solution:
import random
def __init__(self, rects: List[List[int]]):
self.rects = rects
rect_areas = []
for rect in rects:
rect_areas.append(self.get_area(rect))
self.sum_areas = sum(rect_areas)
self.cum_... | [
"random.randint"
] | [((602, 635), 'random.randint', 'random.randint', (['(0)', 'self.sum_areas'], {}), '(0, self.sum_areas)\n', (616, 635), False, 'import random\n'), ((1443, 1471), 'random.randint', 'random.randint', (['min_x', 'max_x'], {}), '(min_x, max_x)\n', (1457, 1471), False, 'import random\n'), ((1471, 1499), 'random.randint', 'r... |
import copy
import datetime as dt
from airiam.find_unused.PolicyAnalyzer import PolicyAnalyzer
from airiam.find_unused.RuntimeIamScanner import RuntimeIamScanner
def filter_attachments_of_unused_entities(unused_policy_attachments, unused_users, unused_roles, redundant_groups) -> list:
unused_role_names = list(ma... | [
"datetime.datetime.now",
"datetime.datetime.fromisoformat",
"copy.deepcopy",
"airiam.find_unused.RuntimeIamScanner.RuntimeIamScanner",
"airiam.find_unused.PolicyAnalyzer.PolicyAnalyzer.is_policy_unused"
] | [((7566, 7591), 'copy.deepcopy', 'copy.deepcopy', (['group_list'], {}), '(group_list)\n', (7579, 7591), False, 'import copy\n'), ((8572, 8618), 'copy.deepcopy', 'copy.deepcopy', (["user['AttachedManagedPolicies']"], {}), "(user['AttachedManagedPolicies'])\n", (8585, 8618), False, 'import copy\n'), ((10997, 11069), 'air... |
import pytest
from word_embedding.grammarcategories import GrammarCategories
from word_embedding.spacy_model import SpacyModel
from word_embedding.token import Token
from word_embedding.dependency import Dependency
class TestModel:
def setup_method(self):
self.model = SpacyModel()
def test_load_test... | [
"word_embedding.spacy_model.SpacyModel",
"word_embedding.token.Token"
] | [((284, 296), 'word_embedding.spacy_model.SpacyModel', 'SpacyModel', ([], {}), '()\n', (294, 296), False, 'from word_embedding.spacy_model import SpacyModel\n'), ((747, 764), 'word_embedding.token.Token', 'Token', (['"""original"""'], {}), "('original')\n", (752, 764), False, 'from word_embedding.token import Token\n')... |
# Copyright (c) 2020 <NAME>
"""Unit tests for 'mech box'."""
import re
from unittest.mock import patch
from click.testing import CliRunner
from mech.mech_cli import cli
def test_mech_box_add_with_cloud():
"""Test 'mech box add' with cloud."""
runner = CliRunner()
with patch('mech.utils.cloud_run') as m... | [
"unittest.mock.patch",
"click.testing.CliRunner",
"re.search"
] | [((1082, 1100), 'unittest.mock.patch', 'patch', (['"""os.getcwd"""'], {}), "('os.getcwd')\n", (1087, 1100), False, 'from unittest.mock import patch\n'), ((1588, 1606), 'unittest.mock.patch', 'patch', (['"""os.getcwd"""'], {}), "('os.getcwd')\n", (1593, 1606), False, 'from unittest.mock import patch\n'), ((2128, 2146), ... |
import glob
import os
#os.system('python3 SendData.py ' + "IMU-data-2021-10-25-20:38:19.csv" )
os.system('python3 RecieveData.py' + " encrypted_fileofIMU.txt") | [
"os.system"
] | [((105, 169), 'os.system', 'os.system', (["('python3 RecieveData.py' + ' encrypted_fileofIMU.txt')"], {}), "('python3 RecieveData.py' + ' encrypted_fileofIMU.txt')\n", (114, 169), False, 'import os\n')] |
"""bulk transactions extension."""
import abc
from typing import Any, Dict, List, Optional
import attr
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel
from stac_fastapi.api.models import create_request_model
from stac_fastapi.api.routes import create_sync_endpoint
from stac_fastapi.types.extensi... | [
"stac_fastapi.api.models.create_request_model",
"stac_fastapi.api.routes.create_sync_endpoint",
"fastapi.APIRouter",
"attr.ib"
] | [((1623, 1632), 'attr.ib', 'attr.ib', ([], {}), '()\n', (1630, 1632), False, 'import attr\n'), ((1727, 1748), 'attr.ib', 'attr.ib', ([], {'default': 'None'}), '(default=None)\n', (1734, 1748), False, 'import attr\n'), ((1995, 2042), 'stac_fastapi.api.models.create_request_model', 'create_request_model', (['"""Items"""'... |
import codecademylib
import numpy as np
import matplotlib.pyplot as plt
survey_responses = ['Ceballos', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos','Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan',... | [
"numpy.mean",
"matplotlib.pyplot.hist",
"numpy.random.binomial",
"matplotlib.pyplot.show"
] | [((1378, 1409), 'numpy.mean', 'np.mean', (['(possible_surveys < 0.5)'], {}), '(possible_surveys < 0.5)\n', (1385, 1409), True, 'import numpy as np\n'), ((1565, 1614), 'matplotlib.pyplot.hist', 'plt.hist', (['possible_surveys'], {'bins': '(20)', 'range': '(0, 1)'}), '(possible_surveys, bins=20, range=(0, 1))\n', (1573, ... |
"""
Define discrete action spaces for Gym Retro environments with a limited set of button combos
"""
import gym
import numpy as np
import retro
class Discretizer(gym.ActionWrapper):
"""
Wrap a gym environment and make it use discrete actions.
Args:
combos: ordered list of lists of valid button co... | [
"numpy.array",
"retro.make"
] | [((1316, 1411), 'retro.make', 'retro.make', ([], {'game': '"""SonicTheHedgehog-Genesis"""', 'use_restricted_actions': 'retro.Actions.DISCRETE'}), "(game='SonicTheHedgehog-Genesis', use_restricted_actions=retro.\n Actions.DISCRETE)\n", (1326, 1411), False, 'import retro\n'), ((1501, 1544), 'retro.make', 'retro.make',... |
# coding: utf-8
# Revert Classification - Prediction
# ===
#
# Building a classifier to predict reverts and produce calibrated propensity scores for being reverted.
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
import bz2
import sqlite3
import difflib
import gzip
import json... | [
"pandas.read_pickle",
"argparse.ArgumentParser",
"pandas.read_csv",
"os.path.join",
"os.path.splitext",
"datetime.datetime.now",
"numpy.array",
"joblib.load",
"pandas.DataFrame",
"sklearn.preprocessing.scale"
] | [((731, 756), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (754, 756), False, 'import argparse\n'), ((978, 1067), 'os.path.join', 'os.path.join', (['"""/export/scratch2/levon003/repos/wiki-ores-feedback"""', '"""data"""', '"""derived"""'], {}), "('/export/scratch2/levon003/repos/wiki-ores-fee... |
from django.conf import settings
from django.core import management
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Helpful command to load all fixtures"
def handle(self, *args, **options):
if not settings.DEBUG:
raise CommandError("Co... | [
"django.core.management.base.CommandError",
"django.core.management.call_command"
] | [((362, 406), 'django.core.management.call_command', 'management.call_command', (['"""loaddata"""', '"""users"""'], {}), "('loaddata', 'users')\n", (385, 406), False, 'from django.core import management\n'), ((415, 459), 'django.core.management.call_command', 'management.call_command', (['"""loaddata"""', '"""tasks"""'... |
from skill_system.skill_deplayer import SkillDeployer
class SkillManager:
def func01(self):
print("SkillManager-func01")
deplayer = SkillDeployer()
deplayer.func02()
| [
"skill_system.skill_deplayer.SkillDeployer"
] | [((146, 161), 'skill_system.skill_deplayer.SkillDeployer', 'SkillDeployer', ([], {}), '()\n', (159, 161), False, 'from skill_system.skill_deplayer import SkillDeployer\n')] |
from typing import Tuple, Iterable, List, Union, TypeVar, ClassVar, Any
import numpy as np
import re
from .utils import split
State = np.array
Action = np.array
Reward = float
Done = bool
Datum = Tuple[State, Action, Reward, State, Done]
Data = Tuple[Iterable[State], Iterable[Action], Iterable[Reward], Iterable[State]... | [
"re.compile",
"numpy.random.choice",
"numpy.array",
"numpy.savez_compressed",
"numpy.load"
] | [((807, 833), 're.compile', 're.compile', (['"""[^/]+\\\\.npz$"""'], {}), "('[^/]+\\\\.npz$')\n", (817, 833), False, 'import re\n'), ((1711, 1769), 'numpy.random.choice', 'np.random.choice', (['num_data'], {'size': 'batch_size', 'replace': '(False)'}), '(num_data, size=batch_size, replace=False)\n', (1727, 1769), True,... |
"""
Tests for building models for parameter selection
"""
from collections import OrderedDict
import sympy
from pycalphad import variables as v
from espei.parameter_selection.model_building import build_feature_sets, build_candidate_models
from espei.sublattice_tools import generate_symmetric_group, sorted_interacti... | [
"sympy.Symbol",
"espei.parameter_selection.model_building.build_candidate_models",
"espei.parameter_selection.model_building.build_feature_sets",
"espei.sublattice_tools.generate_symmetric_group",
"sympy.log",
"espei.sublattice_tools.sorted_interactions"
] | [((633, 697), 'espei.parameter_selection.model_building.build_feature_sets', 'build_feature_sets', (['binary_temp_features', 'binary_excess_features'], {}), '(binary_temp_features, binary_excess_features)\n', (651, 697), False, 'from espei.parameter_selection.model_building import build_feature_sets, build_candidate_mo... |
#!/usr/bin/env python
import logging
import os
import sys
import argparse
from torch_scope import run
if __name__ == "__main__":
run()
| [
"torch_scope.run"
] | [((136, 141), 'torch_scope.run', 'run', ([], {}), '()\n', (139, 141), False, 'from torch_scope import run\n')] |
import json
from time import time
from agent.allin.allinAgentNP import AllinAgentNP
from league.game import GameEngine
from league.logger import GenericLogger
from logPlotter import LogfileCollector
def save_winrates_to_file(winrates):
with open('preflop_monte_carlo_winrates.json', 'w') as f:
f.write(json.dump... | [
"logPlotter.LogfileCollector",
"json.dumps",
"time.time"
] | [((757, 763), 'time.time', 'time', ([], {}), '()\n', (761, 763), False, 'from time import time\n'), ((830, 866), 'logPlotter.LogfileCollector', 'LogfileCollector', ([], {'output_folder': 'None'}), '(output_folder=None)\n', (846, 866), False, 'from logPlotter import LogfileCollector\n'), ((311, 331), 'json.dumps', 'json... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import subprocess
import time
import requests
import hcl
import distutils.spawn
from unittest import SkipTest
from tests.utils import get_config_file_path, load_config_file, create_client
logger = logging.getLogger(__name__)
class ServerManager(... | [
"logging.getLogger",
"tests.utils.create_client",
"os.getenv",
"tests.utils.get_config_file_path",
"subprocess.Popen",
"hcl.loads",
"requests.get",
"time.sleep",
"unittest.SkipTest",
"tests.utils.load_config_file"
] | [((270, 297), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (287, 297), False, 'import logging\n'), ((3805, 3878), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)... |
import importlib
from distutils import version
import pytest
def _importorskip(modname, minversion=None):
try:
mod = importlib.import_module(modname)
has = True
if minversion is not None:
if LooseVersion(mod.__version__) < LooseVersion(minversion):
raise Import... | [
"distutils.version.LooseVersion",
"importlib.import_module",
"pytest.mark.skipif"
] | [((414, 471), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has)'], {'reason': 'f"""requires {modname}"""'}), "(not has, reason=f'requires {modname}')\n", (432, 471), False, 'import pytest\n'), ((686, 715), 'distutils.version.LooseVersion', 'version.LooseVersion', (['vstring'], {}), '(vstring)\n', (706, 715), Fal... |
# Filename: filter.py
"""
LendingClub2 Filter Module
"""
# Standard libraries
import collections
from abc import abstractmethod
from abc import ABC
# lendingclub2
from lendingclub2.error import LCError
# pylint: disable=too-few-public-methods
class BorrowerTrait(ABC):
"""
Abstract base class to define bor... | [
"lendingclub2.error.LCError"
] | [((3049, 3062), 'lendingclub2.error.LCError', 'LCError', (['fstr'], {}), '(fstr)\n', (3056, 3062), False, 'from lendingclub2.error import LCError\n'), ((5083, 5113), 'lendingclub2.error.LCError', 'LCError', (['fstr'], {'details': 'details'}), '(fstr, details=details)\n', (5090, 5113), False, 'from lendingclub2.error im... |
import requests
import sys
import semver
from collections import MutableSequence
from . import __compatibility__
# vm version specification
# https://github.com/aeternity/protocol/blob/master/contracts/contract_vms.md#virtual-machines-on-the-%C3%A6ternity-blockchain
AEVM_NO_VM = 0
# fee calculation
GAS_PER_BYTE = 20
B... | [
"requests.get"
] | [((2305, 2346), 'requests.get', 'requests.get', (['f"""{self.api_url}/v2/status"""'], {}), "(f'{self.api_url}/v2/status')\n", (2317, 2346), False, 'import requests\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-03-09 14:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0003_auto_20170821_1735'),
]
operations = [
migrations.Alter... | [
"django.db.models.CharField"
] | [((409, 685), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('S', 'Submitted'), ('T', 'Submitted late'), ('F', 'Finished'), ('G',\n 'Being peer-reviewed/graded'), ('N', 'Nothing submitted yet'), ('A',\n 'Automated (internal)'), ('X', 'File has been deleted from webserver')]", 'default': '""... |
#!/usr/bin/python3
"""
/**
******************************************************************************
* @file dominant_attribute.py
* @author <NAME>
* $Rev: 1 $
* $Date: Sat Nov 17 15:12:04 CST 2018 $
* @brief Functions related to Dominant Attribute Algorithm
*************************************************... | [
"numpy.where",
"numpy.max",
"numpy.sum",
"numpy.min",
"pandas.DataFrame",
"numpy.log2",
"pandas.concat"
] | [((2703, 2717), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2715, 2717), True, 'import pandas as pd\n'), ((4603, 4673), 'numpy.sum', 'np.sum', (['(-(num_each_group / num_total) * conditional_entropy_each_group)'], {}), '(-(num_each_group / num_total) * conditional_entropy_each_group)\n', (4609, 4673), True, ... |
import asyncio
from sp110e.controller import Controller
async def main():
device = Controller('AF:00:10:01:C8:AF', timeout=2, retries=1)
await device.switch_on()
await device.set_brightness(255)
await device.set_color([0, 255, 0])
await device.set_white(0)
await device.set_speed(10)
await ... | [
"sp110e.controller.Controller"
] | [((89, 142), 'sp110e.controller.Controller', 'Controller', (['"""AF:00:10:01:C8:AF"""'], {'timeout': '(2)', 'retries': '(1)'}), "('AF:00:10:01:C8:AF', timeout=2, retries=1)\n", (99, 142), False, 'from sp110e.controller import Controller\n')] |
import typing as t
import typeapi
from databind.core.context import Context, format_context_trace, Location
from databind.core.settings import Settings
def test_format_context_trace():
settings = Settings()
location = Location.EMPTY
def no_convert(*a): raise NotImplementedError
ctx1 = Context(None, {'a': 1}... | [
"databind.core.context.format_context_trace",
"typeapi.of",
"databind.core.settings.Settings"
] | [((202, 212), 'databind.core.settings.Settings', 'Settings', ([], {}), '()\n', (210, 212), False, 'from databind.core.settings import Settings\n'), ((322, 350), 'typeapi.of', 'typeapi.of', (['t.Dict[str, int]'], {}), '(t.Dict[str, int])\n', (332, 350), False, 'import typeapi\n'), ((424, 439), 'typeapi.of', 'typeapi.of'... |
import requests
import sys
import getopt
import xml.etree.ElementTree as ET
url = 'https://dynamicdns.park-your-domain.com/update'
def print_usage():
print('\n')
print('Usage:')
print('namecheap_dydns.py -H <host> -d <yourdomain.com> -p <yourpassword>')
print('namecheap_dydns.py --host=<host> --domai... | [
"getopt.getopt",
"requests.get",
"sys.exit"
] | [((414, 449), 'requests.get', 'requests.get', (['"""https://ifconfig.me"""'], {}), "('https://ifconfig.me')\n", (426, 449), False, 'import requests\n'), ((1563, 1587), 'requests.get', 'requests.get', (['update_url'], {}), '(update_url)\n', (1575, 1587), False, 'import requests\n'), ((658, 723), 'getopt.getopt', 'getopt... |
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns('',
(r'^depender/', include('depender.urls')),
(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'depender/'})
)
| [
"django.conf.urls.defaults.include"
] | [((104, 128), 'django.conf.urls.defaults.include', 'include', (['"""depender.urls"""'], {}), "('depender.urls')\n", (111, 128), False, 'from django.conf.urls.defaults import patterns, include\n')] |
import os
import numpy as np
from src.base_class.vocoder.htk_io import HTK_Parm_IO
from util import file_util, log_util
log = log_util.get_logger("acoustic tool")
def interpolate_f0(data):
'''
interpolate F0, if F0 has already been interpolated, nothing will be changed after passing this function
:... | [
"numpy.reshape",
"util.log_util.get_logger",
"os.path.dirname",
"numpy.zeros",
"os.path.basename",
"numpy.concatenate",
"util.file_util.array_to_binary_file",
"src.base_class.vocoder.htk_io.HTK_Parm_IO"
] | [((129, 165), 'util.log_util.get_logger', 'log_util.get_logger', (['"""acoustic tool"""'], {}), "('acoustic tool')\n", (148, 165), False, 'from util import file_util, log_util\n'), ((364, 396), 'numpy.reshape', 'np.reshape', (['data', '(data.size, 1)'], {}), '(data, (data.size, 1))\n', (374, 396), True, 'import numpy a... |
from django.contrib import admin
import pytz
from .models import Event
from .forms import EventAdminForm
@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
raw_id_fields = ('attendees', 'facilitators', 'projects',)
form = EventAdminForm
def save_model(self, request, obj, form, change):
... | [
"pytz.timezone",
"django.contrib.admin.register"
] | [((109, 130), 'django.contrib.admin.register', 'admin.register', (['Event'], {}), '(Event)\n', (123, 130), False, 'from django.contrib import admin\n'), ((325, 352), 'pytz.timezone', 'pytz.timezone', (['obj.timezone'], {}), '(obj.timezone)\n', (338, 352), False, 'import pytz\n'), ((879, 906), 'pytz.timezone', 'pytz.tim... |
#! /usr/bin/python3
#
# MIT License
#
# Copyright (c) 2020 <NAME> (@cmorisse)
#
# 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
#... | [
"gettext.install",
"json.dumps",
"pkg_resources.get_distribution"
] | [((1526, 1546), 'gettext.install', 'gettext.install', (['ufw'], {}), '(ufw)\n', (1541, 1546), False, 'import gettext\n'), ((2958, 2986), 'json.dumps', 'json.dumps', (['output'], {'indent': '(4)'}), '(output, indent=4)\n', (2968, 2986), False, 'import json\n'), ((2576, 2613), 'pkg_resources.get_distribution', 'pkg_resou... |
from collections import OrderedDict
import os
from os import path as osp
import numpy as np
import torch
from torch import optim
from torch.distributions import Normal
from torch.utils.data import DataLoader
from torch.nn import functional as F
from torchvision.utils import save_image
from rlkit.data_management.images ... | [
"rlkit.torch.pytorch_util.randn",
"matplotlib.pyplot.savefig",
"numpy.arange",
"matplotlib.pyplot.clf",
"os.path.join",
"torch.stack",
"numpy.array",
"torch.norm",
"rlkit.torch.pytorch_util.get_numpy",
"torchvision.utils.save_image",
"torch.cat",
"rlkit.torch.pytorch_util.zeros"
] | [((2945, 2986), 'os.path.join', 'osp.join', (['self.log_dir', "('r%d.png' % epoch)"], {}), "(self.log_dir, 'r%d.png' % epoch)\n", (2953, 2986), True, 'from os import path as osp\n'), ((3179, 3218), 'rlkit.torch.pytorch_util.randn', 'ptu.randn', (['(64)', 'self.representation_size'], {}), '(64, self.representation_size)... |
import numpy as np
import torch.utils.data
def qm9_collate_batch(batch):
#print(batch)
drug1, drug2, label1, label2 = list(zip(*batch))
ddi_idxs1, ddi_idxs2 = collate_drug_pairs(drug1, drug2)
drug1 = (*collate_drugs(drug1), *ddi_idxs1)
drug2 = (*collate_drugs(drug2), *ddi_idxs2)
label1 = collate_labels(label1... | [
"numpy.stack",
"numpy.array",
"numpy.vstack",
"numpy.hstack"
] | [((1128, 1144), 'numpy.stack', 'np.stack', (['labels'], {}), '(labels)\n', (1136, 1144), True, 'import numpy as np\n'), ((1304, 1346), 'numpy.vstack', 'np.vstack', (["[d['atom_feat'] for d in drugs]"], {}), "([d['atom_feat'] for d in drugs])\n", (1313, 1346), True, 'import numpy as np\n'), ((1378, 1420), 'numpy.hstack'... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2012 <NAME>, Opera Software ASA
#
# 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
#
# Unl... | [
"linkify.Context",
"profiling.Profiler",
"diff.File.eliminateCommonPrefixes",
"reviewing.utils.renderDraftItems",
"gitutils.FetchCommits",
"htmlutils.getStaticResourceURI",
"textutils.summarize",
"reviewing.utils.collectReviewTeams",
"htmlutils.jsify",
"dbutils.describe_file",
"dbutils.Review.fr... | [((7456, 7476), 'profiling.Profiler', 'profiling.Profiler', ([], {}), '()\n', (7474, 7476), False, 'import profiling\n'), ((7805, 7860), 'dbutils.Review.fromId', 'dbutils.Review.fromId', (['db', 'review_id'], {'profiler': 'profiler'}), '(db, review_id, profiler=profiler)\n', (7826, 7860), False, 'import dbutils\n'), ((... |