code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import asyncio
from aiomultiprocess import Worker
class Server:
def __init__(self, host, port, loop):
self.host = host
self.port = port
self.loop = loop
async def send_message(self, data: bytes):
_, writer, = await asyncio.open_connection(self.host, self.port, loop=self.loop)... | [
"asyncio.open_connection",
"asyncio.get_event_loop",
"asyncio.start_server"
] | [((968, 992), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (990, 992), False, 'import asyncio\n'), ((259, 320), 'asyncio.open_connection', 'asyncio.open_connection', (['self.host', 'self.port'], {'loop': 'self.loop'}), '(self.host, self.port, loop=self.loop)\n', (282, 320), False, 'import async... |
def simplificado(fracoes):
"""
Parâmetro: Uma lista contendo frações (em formato de string)
Return: Uma lista que pode conter números inteiros ou frações irredutíveis, ambos em formato de string.
"""
simplificados = list()
for fracao in fracoes:
if 'sqrt' not in fracao and '/' in fracao... | [
"math.sqrt"
] | [((2043, 2054), 'math.sqrt', 'sqrt', (['delta'], {}), '(delta)\n', (2047, 2054), False, 'from math import sqrt\n'), ((2027, 2038), 'math.sqrt', 'sqrt', (['delta'], {}), '(delta)\n', (2031, 2038), False, 'from math import sqrt\n'), ((2082, 2093), 'math.sqrt', 'sqrt', (['delta'], {}), '(delta)\n', (2086, 2093), False, 'f... |
import datetime
def review_time_fmt(time):
time_obj = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f000')
return time_obj.strftime("%s")
def log_message(category, msg, logfile, stdout_only=False):
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_msg = "%s - %s: %s" % (now, ca... | [
"datetime.datetime.strptime",
"datetime.datetime.now"
] | [((61, 120), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['time', '"""%Y-%m-%d %H:%M:%S.%f000"""'], {}), "(time, '%Y-%m-%d %H:%M:%S.%f000')\n", (87, 120), False, 'import datetime\n'), ((228, 251), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (249, 251), False, 'import datetime\n'... |
from flask import Flask, jsonify, send_from_directory
from flask_cors import CORS, cross_origin
from flask import request
import os
import sys
import time
from threading import Thread
import logging
from src_api.utils.logger import logger
from src_api.jsapi import Api
log = logging.getLogger(os.path.basename(__file__))... | [
"src_api.jsapi.Api",
"os.path.abspath",
"flask.request.args.get",
"os.path.basename",
"flask.Flask",
"flask_cors.cross_origin",
"flask.request.get_json"
] | [((380, 395), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (385, 395), False, 'from flask import Flask, jsonify, send_from_directory\n'), ((1485, 1499), 'flask_cors.cross_origin', 'cross_origin', ([], {}), '()\n', (1497, 1499), False, 'from flask_cors import CORS, cross_origin\n'), ((1598, 1612), 'flask_... |
#!/usr/bin/env python3
from flask import Flask, render_template
from flask import request, redirect, jsonify, url_for, flash
from sqlalchemy import create_engine, asc
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, CategoryItem, User
from flask import session as login_session
import r... | [
"flask.flash",
"json.dumps",
"flask.jsonify",
"flask.url_for",
"oauth2client.client.credentials_from_clientsecrets_and_code",
"flask.request.args.get",
"flask.request.headers.get",
"flask.redirect",
"requests.get",
"flask.render_template",
"flask.session.keys",
"database_setup.User",
"sqlalc... | [((561, 576), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (566, 576), False, 'from flask import Flask, render_template\n'), ((588, 679), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///movie_catalog.db"""'], {'connect_args': "{'check_same_thread': False}"}), "('sqlite:///movie_catalog.db', ... |
import numpy as np
from scipy.spatial.distance import cdist
# ========================================================================
# USAGE: [Coeff]=LLC_coding_appr(B,X,knn,lambda)
# Approximated Locality-constraint Linear Coding
#
# Inputs
# B -M x d codebook, M entries in a d-dim space
# X ... | [
"scipy.spatial.distance.cdist",
"numpy.trace",
"numpy.sum",
"numpy.zeros",
"numpy.ones",
"numpy.argsort",
"numpy.tile",
"numpy.eye"
] | [((707, 731), 'scipy.spatial.distance.cdist', 'cdist', (['X', 'B', '"""euclidean"""'], {}), "(X, B, 'euclidean')\n", (712, 731), False, 'from scipy.spatial.distance import cdist\n'), ((759, 787), 'numpy.zeros', 'np.zeros', (['(N, k_nn)', '"""int32"""'], {}), "((N, k_nn), 'int32')\n", (767, 787), True, 'import numpy as ... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import sys
from mixbox.binding_utils import *
from . import cybox_common
from . import dns_record_object
from . import uri_object
class DNSQuestionType(GeneratedsSuper):
"""The DNSQuestionType specifies the c... | [
"sys.stdout.write",
"mixbox.vendor.six.StringIO",
"sys.exit"
] | [((25949, 25960), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (25957, 25960), False, 'import sys\n'), ((27253, 27278), 'sys.stdout.write', 'sys.stdout.write', (['content'], {}), '(content)\n', (27269, 27278), False, 'import sys\n'), ((27283, 27305), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n... |
#!/usr/local/bin/python3
import sys
import os
try:
from dynamicjre import utils
except ModuleNotFoundError:
# assume pip3 install . has not been run
import utils
def main():
arguments = sys.argv
arguments.pop(0)
if len(arguments) == 0:
utils.print_usage_message()
return 1
... | [
"get_episode.latest",
"utils.print_usage_message",
"get_episode.with_episode_number",
"sys.stdin.readlines",
"utils.get_save_folder"
] | [((273, 300), 'utils.print_usage_message', 'utils.print_usage_message', ([], {}), '()\n', (298, 300), False, 'import utils\n'), ((378, 405), 'utils.print_usage_message', 'utils.print_usage_message', ([], {}), '()\n', (403, 405), False, 'import utils\n'), ((1356, 1403), 'get_episode.with_episode_number', 'get_episode.wi... |
#!/usr/bin/env python3
import argparse
import os
import re
import json
import xml.etree.ElementTree
import pdb
def is_excluded_ClCompile(ClCompile, config, platform):
# vcprojs have conditional ExcludedFromBuild childnodes, example:
# <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Static Rel... | [
"os.path.dirname",
"os.path.join",
"argparse.ArgumentParser",
"re.compile"
] | [((2421, 2453), 'os.path.dirname', 'os.path.dirname', (['vcproj_filename'], {}), '(vcproj_filename)\n', (2436, 2453), False, 'import os\n'), ((4429, 4454), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4452, 4454), False, 'import argparse\n'), ((835, 910), 're.compile', 're.compile', (['"""^\... |
from os import path
import yaml
import os
from django.conf import settings
from kubernetes import client, config
from kubernetes.client.rest import ApiException
def create_namespace(name):
body = client.V1Namespace()
body.metadata = client.V1ObjectMeta(name=name)
core_v1 = client.CoreV1Api()
resp = c... | [
"kubernetes.client.V1Namespace",
"kubernetes.client.V1DeleteOptions",
"kubernetes.client.V1ObjectMeta",
"kubernetes.client.CoreV1Api",
"kubernetes.config.load_kube_config",
"kubernetes.client.AppsV1Api",
"yaml.safe_load_all",
"yaml.safe_load",
"os.path.join"
] | [((203, 223), 'kubernetes.client.V1Namespace', 'client.V1Namespace', ([], {}), '()\n', (221, 223), False, 'from kubernetes import client, config\n'), ((244, 274), 'kubernetes.client.V1ObjectMeta', 'client.V1ObjectMeta', ([], {'name': 'name'}), '(name=name)\n', (263, 274), False, 'from kubernetes import client, config\n... |
import scrapy
from pygments import highlight
from pygments.lexers.html import HtmlLexer
from pygments.formatters import TerminalFormatter
class ThreadItem(scrapy.Item):
subject = scrapy.Field()
href = scrapy.Field()
class MessageItem(scrapy.Item):
subject = scrapy.Field()
author = scrapy.Field()
lastPostDate = s... | [
"scrapy.Field",
"scrapy.Request"
] | [((181, 195), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (193, 195), False, 'import scrapy\n'), ((204, 218), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (216, 218), False, 'import scrapy\n'), ((263, 277), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (275, 277), False, 'import scrapy\n'), ((288, 302), ... |
import pytest
@pytest.fixture(autouse=True)
def auto_refresh_db(fresh_db):
pass
| [
"pytest.fixture"
] | [((17, 45), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (31, 45), False, 'import pytest\n')] |
#!/usr/bin/env python3
# Copyright 2019 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | [
"neato_botvac.neato_driver.Encoders.from_state",
"neato_botvac.neato_driver.BotvacDriverCallbacks",
"neato_botvac.neato_driver.BotvacDriver",
"neato_botvac.neato_driver.BatteryStatus.from_state",
"neato_botvac.neato_driver.Accelerometer.from_state",
"neato_botvac.neato_driver.Scan"
] | [((941, 1059), 'neato_botvac.neato_driver.BotvacDriverCallbacks', 'BotvacDriverCallbacks', ([], {'encoders': '(lambda x: None)', 'battery': '(lambda x: None)', 'scan': '(lambda x: None)', 'accel': '(lambda x: None)'}), '(encoders=lambda x: None, battery=lambda x: None, scan\n =lambda x: None, accel=lambda x: None)\n... |
# --------------
# import packages
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Load Offers
offers = pd.read_excel(path, sheet_name=0)
# Load Transactions
transactions = pd.read_excel(path, sheet_name=1)
transactions['n'] = 1
# Merge dataframes
df ... | [
"pandas.read_excel",
"sklearn.cluster.KMeans",
"pandas.merge",
"sklearn.decomposition.PCA"
] | [((164, 197), 'pandas.read_excel', 'pd.read_excel', (['path'], {'sheet_name': '(0)'}), '(path, sheet_name=0)\n', (177, 197), True, 'import pandas as pd\n'), ((237, 270), 'pandas.read_excel', 'pd.read_excel', (['path'], {'sheet_name': '(1)'}), '(path, sheet_name=1)\n', (250, 270), True, 'import pandas as pd\n'), ((322, ... |
import math as m
from pympler.asizeof import asizeof
from fxutil.plotting import SaveFigure, evf, easy_prop_cycle
fmt_bytes = lambda s: (
lambda s, k: (s * 2 ** (-k * 10), ["B", "KiB", "MiB", "GiB", "TiB", "PiB"][k])
)(s, round(m.log(s) / m.log(2) / 10))
described_size = lambda desc, obj: (
lambda desc, fmt... | [
"math.log",
"pympler.asizeof.asizeof"
] | [((374, 386), 'pympler.asizeof.asizeof', 'asizeof', (['obj'], {}), '(obj)\n', (381, 386), False, 'from pympler.asizeof import asizeof\n'), ((235, 243), 'math.log', 'm.log', (['s'], {}), '(s)\n', (240, 243), True, 'import math as m\n'), ((246, 254), 'math.log', 'm.log', (['(2)'], {}), '(2)\n', (251, 254), True, 'import ... |
import numpy as np
import copy
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from betl.linear_system import DiscreteTimeLinearSystem as LinearSystem
from betl.linear_system import StateFeedbackLaw, ExcitingStateFeedbackLaw
from betl.synthesis.robust_lqr_synth import RLQRSyntheziser
from be... | [
"numpy.random.seed",
"seaborn.kdeplot",
"matplotlib.pyplot.figure",
"pickle.load",
"matplotlib.pyplot.close",
"matplotlib.rcParams.update",
"matplotlib.patches.FancyArrowPatch",
"matplotlib.pyplot.rcParams.update",
"utils.postprocessing_utils.initialize_plot",
"betl.linear_system.DiscreteTimeLinea... | [((569, 627), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.WARN'}), '(stream=sys.stdout, level=logging.WARN)\n', (588, 627), False, 'import logging\n'), ((825, 839), 'matplotlib.use', 'mpl.use', (['"""pgf"""'], {}), "('pgf')\n", (832, 839), True, 'import matplotlib as mp... |
import random
from .data import adjectives
from .models import PopularSite
def gen_site_url():
"""Returns a dict of url of a page at random interval and the year it was developed"""
random_key = random.choice(PopularSite.objects.values_list('id', flat=True))
site = PopularSite.objects.get(id=random_key)
... | [
"random.choice",
"random.randint"
] | [((456, 486), 'random.randint', 'random.randint', (['(100000)', '(999999)'], {}), '(100000, 999999)\n', (470, 486), False, 'import random\n'), ((626, 662), 'random.choice', 'random.choice', (['adjectives.ADJECTIVES'], {}), '(adjectives.ADJECTIVES)\n', (639, 662), False, 'import random\n'), ((334, 365), 'random.randint'... |
'''
Feature Engineering and model training
'''
import pickle
import pandas as pd
import numpy as np
from sklearn.decomposition import NMF
from sklearn.impute import KNNImputer
links = pd.DataFrame(pd.read_csv('links.csv'))
movies_ = pd.DataFrame(pd.read_csv('movies.csv'))
ratings = pd.DataFrame(pd.read_csv('ratings.cs... | [
"sklearn.decomposition.NMF",
"pandas.read_csv",
"pandas.merge",
"sklearn.impute.KNNImputer",
"numpy.dot",
"pickle.dumps"
] | [((701, 771), 'pandas.merge', 'pd.merge', ([], {'left': 'links', 'right': 'ratings', 'left_index': '(True)', 'right_index': '(True)'}), '(left=links, right=ratings, left_index=True, right_index=True)\n', (709, 771), True, 'import pandas as pd\n'), ((777, 896), 'pandas.merge', 'pd.merge', ([], {'left': 'links_ratings', ... |
#
# Copyright 2021 Espressif Systems (Shanghai) CO., LTD
#
# 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 l... | [
"construct.Int32ul.sizeof",
"corefile.ESPCoreDumpLoaderError",
"construct.Padding",
"construct.Int16ul.sizeof"
] | [((1008, 1042), 'construct.Padding', 'Padding', (['PRSTATUS_OFFSET_PR_CURSIG'], {}), '(PRSTATUS_OFFSET_PR_CURSIG)\n', (1015, 1042), False, 'from construct import Int16ul, Int32ul, Padding, Struct\n'), ((1307, 1375), 'construct.Padding', 'Padding', (['(PRSTATUS_SIZE - PRSTATUS_OFFSET_PR_REG - ELF_GREGSET_T_SIZE)'], {}),... |
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:jiangpinglei
"""
class SegmenterEvaluation():
def __init__(self, id2label_dict):
self.id2label_dict = id2label_dict
def evaluate(self, original_labels, predict_labels):
right, predict = self.get_order(original_labels, predict_labels)
... | [
"pickle.load"
] | [((2892, 2907), 'pickle.load', 'pickle.load', (['rf'], {}), '(rf)\n', (2903, 2907), False, 'import pickle\n')] |
import numpy as np
import decimal
import string
#homeworkLayout.py
print("""
<NAME>
ECON 411 / 611
Homework
""")
print("""
1. Record your name in an object (x = ...) and a description of yourself in
another object.
""")
#first name
first = "James"
#middle name
middle = "Lee"
#last name
last = "Caton"
#full name com... | [
"decimal.Decimal"
] | [((3246, 3266), 'decimal.Decimal', 'decimal.Decimal', (['val'], {}), '(val)\n', (3261, 3266), False, 'import decimal\n'), ((3269, 3289), 'decimal.Decimal', 'decimal.Decimal', (['(0.5)'], {}), '(0.5)\n', (3284, 3289), False, 'import decimal\n')] |
"""Custom sentence splitter."""
from typing import Optional
from spacy.language import Language
from spacy.tokens import Doc
from traiter.const import CLOSE, QUOTE
SENTENCE = 'traiter.sentence.v1'
EOS = """ . ? ! … """.split() # End Of Sentence
PREV_EOS = CLOSE + EOS
@Language.factory(SENTENCE)
class Sentence:
... | [
"spacy.language.Language.factory"
] | [((277, 303), 'spacy.language.Language.factory', 'Language.factory', (['SENTENCE'], {}), '(SENTENCE)\n', (293, 303), False, 'from spacy.language import Language\n')] |
# Python Standard Library Imports
import re
# Third Party (PyPI) Imports
import requests
import rollbar
import six.moves.urllib as urllib
# HTK Imports
from htk.lib.oembed.cachekeys import OembedResponseCache
from htk.lib.oembed.constants import *
from htk.utils.request import get_current_request
def get_oembed_htm... | [
"six.moves.urllib.parse.quote",
"htk.utils.request.get_current_request",
"re.match",
"rollbar.report_exc_info",
"requests.get",
"htk.lib.oembed.cachekeys.OembedResponseCache",
"re.sub"
] | [((896, 927), 'htk.lib.oembed.cachekeys.OembedResponseCache', 'OembedResponseCache', ([], {'prekey': 'url'}), '(prekey=url)\n', (915, 927), False, 'from htk.lib.oembed.cachekeys import OembedResponseCache\n'), ((2721, 2767), 're.sub', 're.sub', (['"""\\\\?feature=oembed"""', 'replacement', 'html'], {}), "('\\\\?feature... |
import bidict
import yaml
import os
from datetime import datetime
import pandas as pd
import pathpy
import multiprocessing
def load_config(config: str):
"""Custom function to load a config file with additional constructor
Parameters
----------
config : str
Path to the config.yaml file
Re... | [
"yaml.load",
"bidict.bidict",
"yaml.add_constructor",
"os.makedirs",
"os.path.exists",
"datetime.datetime.now",
"pandas.set_option",
"os.path.join",
"multiprocessing.cpu_count"
] | [((491, 526), 'yaml.add_constructor', 'yaml.add_constructor', (['"""!join"""', 'join'], {}), "('!join', join)\n", (511, 526), False, 'import yaml\n'), ((1103, 1127), 'bidict.bidict', 'bidict.bidict', (['temp_dict'], {}), '(temp_dict)\n', (1116, 1127), False, 'import bidict\n'), ((1597, 1638), 'pandas.set_option', 'pd.s... |
from django.contrib import admin
from profiles_api.models import Book,Author,UserProfile
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Book)
admin.site.register(Author)
| [
"django.contrib.admin.site.register"
] | [((119, 151), 'django.contrib.admin.site.register', 'admin.site.register', (['UserProfile'], {}), '(UserProfile)\n', (138, 151), False, 'from django.contrib import admin\n'), ((152, 177), 'django.contrib.admin.site.register', 'admin.site.register', (['Book'], {}), '(Book)\n', (171, 177), False, 'from django.contrib imp... |
#!/usr/bin/env python3
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GLine, GOval
from campy.gui.events.window import onwindowclosed
from campy.graphics.goptionpane import GOptionPane, ConfirmResult
def main():
window = GWindow(400, 400)
# Awkward! We need a window before we ... | [
"campy.graphics.goptionpane.GOptionPane.show_confirm_dialog",
"campy.graphics.gwindow.GWindow"
] | [((259, 276), 'campy.graphics.gwindow.GWindow', 'GWindow', (['(400)', '(400)'], {}), '(400, 400)\n', (266, 276), False, 'from campy.graphics.gwindow import GWindow\n'), ((397, 462), 'campy.graphics.goptionpane.GOptionPane.show_confirm_dialog', 'GOptionPane.show_confirm_dialog', (['"""Are you sure you want to quit?"""']... |
import pytest
from money import Currency
from money.exceptions import InvalidCurrencyFormat
def test_construction():
currency = Currency('USD')
assert currency.code == 'USD'
assert currency.precision == 2
assert currency.display_name() == 'US Dollar'
assert currency.symbol() == '$'
with pyt... | [
"pytest.raises",
"money.Currency"
] | [((135, 150), 'money.Currency', 'Currency', (['"""USD"""'], {}), "('USD')\n", (143, 150), False, 'from money import Currency\n'), ((426, 441), 'money.Currency', 'Currency', (['"""USD"""'], {}), "('USD')\n", (434, 441), False, 'from money import Currency\n'), ((494, 509), 'money.Currency', 'Currency', (['"""JPY"""'], {}... |
#SPDX-License-Identifier: MIT
import pandas as pd
import sqlalchemy as s
import numpy as np
import re
class GHTorrent(object):
"""Uses GHTorrent and other GitHub data sources and returns dataframes with interesting GitHub indicators"""
def __init__(self, dbstr):
"""
Connect to GHTorrent
... | [
"sqlalchemy.sql.text",
"numpy.timedelta64",
"pandas.to_datetime",
"pandas.Series",
"pandas.read_sql",
"sqlalchemy.create_engine",
"re.sub"
] | [((510, 532), 'sqlalchemy.create_engine', 's.create_engine', (['dbstr'], {}), '(dbstr)\n', (525, 532), True, 'import sqlalchemy as s\n'), ((3721, 3791), 'sqlalchemy.sql.text', 's.sql.text', (['"""SELECT users.id FROM users WHERE users.login = :username"""'], {}), "('SELECT users.id FROM users WHERE users.login = :usern... |
"""
Copyright (c) 2021 TU Darmstadt
Author: <NAME> <<EMAIL>>
License: Apache License 2.0
"""
from __future__ import print_function
import os
import torch
import argparse
from core.config import cfg
def add_global_arguments(parser):
#
# Model details
#
parser.add_argument("--snapshot-dir", type=str, ... | [
"os.makedirs",
"argparse.ArgumentParser",
"os.path.exists",
"torch.cuda.is_available",
"os.path.join",
"torch.get_num_threads"
] | [((1795, 1820), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1818, 1820), False, 'import torch\n'), ((1898, 1943), 'os.path.join', 'os.path.join', (['args.logdir', 'args.exp', 'args.run'], {}), '(args.logdir, args.exp, args.run)\n', (1910, 1943), False, 'import os\n'), ((2039, 2090), 'os.pat... |
# Captcha Auto Filler Programm
# Credits- <NAME>
# Instagram Handle- @rudra_shah_
# This is just an sample script improvements will be added later.
# It is also possible iwth selenium
# Instruction before using:
"""
* Just Run this programm and switch to captcha page...Boom You computer is now under the control and ... | [
"os.remove",
"pyautogui.typewrite",
"pyautogui.keyDown",
"pyscreenshot.grab",
"pytesseract.image_to_string",
"time.sleep",
"pyautogui.click"
] | [((1032, 1045), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (1042, 1045), False, 'import time\n'), ((1071, 1086), 'time.sleep', 'time.sleep', (['(4.7)'], {}), '(4.7)\n', (1081, 1086), False, 'import time\n'), ((1097, 1137), 'pyscreenshot.grab', 'pyscreenshot.grab', ([], {'bbox': '(x1, y1, x2, y2)'}), '(bbox=(x1... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import errno
import time
from indelvcf.logging_config import LogConf
# global configuration
import indelvcf.glv as glv
import subprocess as sbp
import pandas as pd
import indelvcf.utils as utl
from indelvcf.logging_config import LogConf
class R... | [
"indelvcf.utils.try_exec",
"indelvcf.glv.conf.ref.startswith",
"os.path.basename",
"os.getcwd",
"indelvcf.logging_config.LogConf.open_log",
"os.path.isfile",
"os.path.splitext",
"os.symlink",
"os.chdir",
"sys.exit"
] | [((435, 461), 'indelvcf.logging_config.LogConf.open_log', 'LogConf.open_log', (['__name__'], {}), '(__name__)\n', (451, 461), False, 'from indelvcf.logging_config import LogConf\n'), ((579, 607), 'indelvcf.glv.conf.ref.startswith', 'glv.conf.ref.startswith', (['"""/"""'], {}), "('/')\n", (602, 607), True, 'import indel... |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""
This represents the cotroller of the money program.
Here, the database connections are handled and
data is written back into the gui components.
"""
import argparse
import sys
import logging
import os
import fill_from_file as from_csv
from logging.handlers impo... | [
"logging.error",
"fill_from_file.populate",
"utils.input_client.check_category",
"os.path.dirname",
"logging.StreamHandler",
"utils.input_client.check_description",
"logging.Formatter",
"utils.file_checker.fileChecker",
"utils.input_client.check_date",
"utils.database.Database",
"sys.exit",
"s... | [((878, 915), 'logging.getLogger', 'logging.getLogger', (['"""money controller"""'], {}), "('money controller')\n", (895, 915), False, 'import logging\n'), ((1075, 1136), 'logging.handlers.RotatingFileHandler', 'RotatingFileHandler', (['logname'], {'maxBytes': '(1000000)', 'backupCount': '(2)'}), '(logname, maxBytes=10... |
import unittest
from sphinxcontrib.dotnetdomain import DotNetXRefMixin
class FieldTests(unittest.TestCase):
"""Test for xref fields"""
def test_split(self):
cls = DotNetXRefMixin()
self.assertEqual(
cls.split_refs('TFoo'),
[('TFoo', None)]
)
self.asse... | [
"sphinxcontrib.dotnetdomain.DotNetXRefMixin"
] | [((184, 201), 'sphinxcontrib.dotnetdomain.DotNetXRefMixin', 'DotNetXRefMixin', ([], {}), '()\n', (199, 201), False, 'from sphinxcontrib.dotnetdomain import DotNetXRefMixin\n')] |
from typing import Any
from unittest.mock import MagicMock, patch
from operatorcert import hydra
from requests import HTTPError, Response
def test_get_session_basic_auth(monkeypatch: Any) -> None:
monkeypatch.setenv("HYDRA_USERNAME", "user")
monkeypatch.setenv("HYDRA_PASSWORD", "password")
session = hyd... | [
"operatorcert.hydra.get",
"operatorcert.hydra._get_session",
"unittest.mock.patch",
"requests.Response",
"requests.HTTPError"
] | [((389, 406), 'unittest.mock.patch', 'patch', (['"""sys.exit"""'], {}), "('sys.exit')\n", (394, 406), False, 'from unittest.mock import MagicMock, patch\n'), ((536, 576), 'unittest.mock.patch', 'patch', (['"""operatorcert.hydra._get_session"""'], {}), "('operatorcert.hydra._get_session')\n", (541, 576), False, 'from un... |
import torch
# from torch_cluster import fps
import torch.nn as nn
from .utils import farthest_point_sampling, get_knn_idx, batched_index_select
# from .utils import three_interpolate, three_nn
class TransitionDown(nn.Module):
def __init__(self, feat_dim: int, out_feat_dim: int, k: int=16):
super().__init... | [
"torch.nn.ReLU",
"torch.norm",
"torch.nn.init.xavier_uniform_",
"torch.nn.BatchNorm1d",
"torch.nn.init.zeros_",
"torch.nn.Linear",
"torch.sum",
"torch.transpose"
] | [((343, 409), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', ([], {'num_features': 'out_feat_dim', 'eps': '(1e-05)', 'momentum': '(0.1)'}), '(num_features=out_feat_dim, eps=1e-05, momentum=0.1)\n', (357, 409), True, 'import torch.nn as nn\n'), ((488, 532), 'torch.nn.Linear', 'nn.Linear', (['feat_dim', 'out_feat_dim'], {'bia... |
"""Add original_nvr and rebuilt_nvr columns.
Revision ID: d6de0409fc74
Revises: 3f56425964cf
Create Date: 2017-10-10 12:57:59.802658
"""
# revision identifiers, used by Alembic.
revision = 'd6de0409fc74'
down_revision = '3f56425964cf'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column... | [
"sqlalchemy.String",
"alembic.op.drop_column"
] | [((509, 557), 'alembic.op.drop_column', 'op.drop_column', (['"""artifact_builds"""', '"""rebuilt_nvr"""'], {}), "('artifact_builds', 'rebuilt_nvr')\n", (523, 557), False, 'from alembic import op\n'), ((562, 611), 'alembic.op.drop_column', 'op.drop_column', (['"""artifact_builds"""', '"""original_nvr"""'], {}), "('artif... |
#!/usr/bin/env python3
from elektro_planner.read_setup import read_setup
from elektro_planner.create_roombook import create_roombook
from elektro_planner.calc_kabel import calc_wires
from elektro_planner.associate_anschluesse import associate_objects_to_walls_and_nodes
from pytest import approx
def test_fully_house(... | [
"elektro_planner.read_setup.read_setup",
"elektro_planner.calc_kabel.calc_wires",
"elektro_planner.associate_anschluesse.associate_objects_to_walls_and_nodes"
] | [((368, 389), 'elektro_planner.read_setup.read_setup', 'read_setup', (['yaml_file'], {}), '(yaml_file)\n', (378, 389), False, 'from elektro_planner.read_setup import read_setup\n'), ((533, 575), 'elektro_planner.associate_anschluesse.associate_objects_to_walls_and_nodes', 'associate_objects_to_walls_and_nodes', (['haus... |
from typing import List, Dict, Any, Union
import json
import re
from dictpy import DictSearch, Serializer
from rxnpy.chemical.lookup_tools.quantity_parsing import main_quantity_parse, reduce_quantity_list
from rxnpy.chemical.molecular_formula import MolecularFormula
from rxnpy import Quantity
iden = [
["InChI", ... | [
"json.loads",
"rxnpy.chemical.lookup_tools.quantity_parsing.main_quantity_parse",
"dictpy.DictSearch",
"json.dumps",
"pathlib.Path",
"rxnpy.chemical.molecular_formula.MolecularFormula",
"glob.glob",
"rxnpy.chemical.lookup_tools.quantity_parsing.reduce_quantity_list",
"re.search",
"os.chdir"
] | [((6646, 6660), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (6654, 6660), False, 'import os\n'), ((6678, 6701), 'glob.glob', 'glob.glob', (['"""cid_*.json"""'], {}), "('cid_*.json')\n", (6687, 6701), False, 'import glob\n'), ((2109, 2156), 'json.dumps', 'json.dumps', (['dict_out'], {'indent': '(2)', 'sort_keys'... |
"""Number Rules Tests
"""
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
import pytest
from vdate.rule.error import NotNumberError, NotIntegerError, NotFloatError, NotDecimalError
from vdate.rule.number import IsNumber, IsInteger, IsFloat, IsDecimal
from .base import BaseTest
class TestRuleNumber(Ba... | [
"vdate.rule.number.IsNumber",
"vdate.rule.number.IsInteger",
"vdate.rule.number.IsDecimal",
"vdate.rule.number.IsFloat",
"pytest.raises"
] | [((506, 535), 'pytest.raises', 'pytest.raises', (['NotNumberError'], {}), '(NotNumberError)\n', (519, 535), False, 'import pytest\n'), ((658, 688), 'pytest.raises', 'pytest.raises', (['NotIntegerError'], {}), '(NotIntegerError)\n', (671, 688), False, 'import pytest\n'), ((810, 838), 'pytest.raises', 'pytest.raises', ([... |
import os
import argparse
from yaml import safe_load
from app.constants import DEFAULT_STORY_POINTS_FIELD_NAME
from app.models import (
EnvConfig,
ManagerConfig,
ReportCommandLineArgs,
VisualizationCommandLineArgs,
)
def _get_config_file_configs(config_filename: str) -> ReportCommandLineArgs:
wi... | [
"argparse.ArgumentParser",
"yaml.safe_load",
"app.models.VisualizationCommandLineArgs",
"app.models.ReportCommandLineArgs",
"app.models.EnvConfig"
] | [((393, 424), 'app.models.ReportCommandLineArgs', 'ReportCommandLineArgs', ([], {}), '(**config)\n', (414, 424), False, 'from app.models import EnvConfig, ManagerConfig, ReportCommandLineArgs, VisualizationCommandLineArgs\n'), ((627, 665), 'app.models.VisualizationCommandLineArgs', 'VisualizationCommandLineArgs', ([], ... |
import json
import os
import requests
from urllib.parse import urljoin
from api.pycritter import parse_5e, damage_types
class Item:
def resolve_list(self,lst):
rl = []
for i in lst:
if type(i) == dict:
rl.append(Item(i))
elif type(i) == list:
... | [
"requests.get",
"api.pycritter.parse_5e"
] | [((849, 924), 'requests.get', 'requests.get', (["('https://api.open5e.com/' + resource_type + '/')"], {'params': 'terms'}), "('https://api.open5e.com/' + resource_type + '/', params=terms)\n", (861, 924), False, 'import requests\n'), ((1217, 1245), 'api.pycritter.parse_5e', 'parse_5e', (["data['actions'][a]"], {}), "(d... |
import numpy as np
import math
import fatpack
# import rainflow
import matplotlib.pyplot as plt
import pandas as pd
import h5py
# import seaborn as sns
from scipy.signal import savgol_filter
import scipy.stats as stats
def Goodman_method_correction(M_a,M_m,M_max):
M_u = 1.5*M_max
M_ar = M_a/(1-M_m/M_u)
... | [
"h5py.File",
"fatpack.find_reversals_racetrack_filtered",
"numpy.sum",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rcParams.update",
"fatpack.find_range_count",
"numpy.max",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"fatpack.find_rainflow_ranges",
"matplotlib... | [((720, 754), 'numpy.linspace', 'np.linspace', (['(0)', 'bins_max', 'bins_num'], {}), '(0, bins_max, bins_num)\n', (731, 754), True, 'import numpy as np\n'), ((801, 830), 'numpy.linspace', 'np.linspace', (['(0)', 'bins_max', '(501)'], {}), '(0, bins_max, 501)\n', (812, 830), True, 'import numpy as np\n'), ((833, 869), ... |
from pygame import *
from random import randint
import time as t
speed_p = 7
lost = 0
score = 0
score1 = 0
max_lost=3
w_width = 700
w_height = 600
window = display.set_mode((w_width,w_height))
display.set_caption("htpyz")
background = transform.scale(image.load("galaxy.jpg"), (w_width,w_height))
game = True
num_fire = ... | [
"random.randint",
"time.time"
] | [((2606, 2631), 'random.randint', 'randint', (['(80)', '(w_width - 80)'], {}), '(80, w_width - 80)\n', (2613, 2631), False, 'from random import randint\n'), ((2642, 2655), 'random.randint', 'randint', (['(1)', '(3)'], {}), '(1, 3)\n', (2649, 2655), False, 'from random import randint\n'), ((2738, 2763), 'random.randint'... |
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
from base.models import User
class AuditModelAdmin(admin.ModelAdmin):
exclude = ('created_by', 'updated_by',)
def save_model(self, request, obj, form, change):
if obj.__getstate__()['_state... | [
"django.contrib.admin.site.register"
] | [((508, 544), 'django.contrib.admin.site.register', 'admin.site.register', (['User', 'UserAdmin'], {}), '(User, UserAdmin)\n', (527, 544), False, 'from django.contrib import admin\n')] |
import numpy as np
from gridgeo.ugrid import ugrid
def _make_grid(coords):
if coords.ndim != 3:
raise ValueError(f"Expected 3 dimension array, got {coords.ndim}.")
M, N, L = coords.shape
polygons = np.concatenate(
(
coords[0:-1, 0:-1],
coords[0:-1, 1:],
... | [
"numpy.stack",
"numpy.meshgrid",
"numpy.isnan",
"gridgeo.ugrid.ugrid",
"numpy.concatenate"
] | [((221, 321), 'numpy.concatenate', 'np.concatenate', (['(coords[0:-1, 0:-1], coords[0:-1, 1:], coords[1:, 1:], coords[1:, 0:-1])'], {'axis': 'L'}), '((coords[0:-1, 0:-1], coords[0:-1, 1:], coords[1:, 1:],\n coords[1:, 0:-1]), axis=L)\n', (235, 321), True, 'import numpy as np\n'), ((6461, 6476), 'gridgeo.ugrid.ugrid'... |
# -*- coding: utf-8 -*-
import datetime
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from scrapy_redis.spiders import RedisCrawlSpider
from CQUPT_Spider.items import CquptSpiderItemLoader, CquptSpiderItem
from goose3 import Goose
from goose3.text import StopWordsChinese
class Explo... | [
"goose3.Goose",
"scrapy.linkextractors.LinkExtractor",
"datetime.datetime.now",
"CQUPT_Spider.items.CquptSpiderItem"
] | [((1016, 1060), 'goose3.Goose', 'Goose', (["{'stopwords_class': StopWordsChinese}"], {}), "({'stopwords_class': StopWordsChinese})\n", (1021, 1060), False, 'from goose3 import Goose\n'), ((437, 544), 'scrapy.linkextractors.LinkExtractor', 'LinkExtractor', ([], {'canonicalize': '(True)', 'allow_domains': '"""cqupt.edu.c... |
# Created by <NAME>.
import sys
import numpy as np
sys.path.append('../')
from envs import Maze
from itertools import product, tee
from utils import print_episode, eps_greedy_policy, create_greedy_policy, \
test_policy
'''
Tabular Dyna-Q used to find an optimal policy for the maze environment describ... | [
"sys.path.append",
"utils.test_policy",
"utils.print_episode",
"envs.Maze",
"utils.eps_greedy_policy",
"itertools.tee",
"utils.create_greedy_policy"
] | [((51, 73), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (66, 73), False, 'import sys\n'), ((763, 776), 'itertools.tee', 'tee', (['sa_pairs'], {}), '(sa_pairs)\n', (766, 776), False, 'from itertools import product, tee\n'), ((2043, 2080), 'utils.print_episode', 'print_episode', (['n_episodes'... |
import numpy as np
def get_PF_Results():
results=\
{
10:
{
0:
{
'delta' :
{
'Yyn': np.array
([
#10,0,deltaYyn
#BusTr_HV,Tr_LV,Load
1.0000001787261197, 0.9990664471050634, 0.9408623912831601,
0.9999997973033823, 0.9989329879720452, 0.9398981202882926... | [
"numpy.array"
] | [((116, 315), 'numpy.array', 'np.array', (['[1.0000001787261197, 0.9990664471050634, 0.9408623912831601, \n 0.9999997973033823, 0.9989329879720452, 0.9398981202882926, \n 1.000000023970535, 0.9990124767159095, 0.9422153531204793]'], {}), '([1.0000001787261197, 0.9990664471050634, 0.9408623912831601, \n 0.99999... |
import sys
import os.path
root_directory=os.path.abspath(os.path.join(os.path.abspath(__file__),"../../../"))
print(root_directory)
sys.path.append(root_directory) | [
"sys.path.append"
] | [((132, 163), 'sys.path.append', 'sys.path.append', (['root_directory'], {}), '(root_directory)\n', (147, 163), False, 'import sys\n')] |
"""Clustering-related mathematical functions.
"""
from typing import Optional
import numpy as np
import py4research.math.random as r
def kmeans(x: np.ndarray,
n_clusters: Optional[int] = 1,
max_iterations: Optional[int] = 100,
tol: Optional[float] = 1e-4) -> np.ndarray:
"""Perf... | [
"numpy.sum",
"py4research.math.random.generate_integer_random_number",
"numpy.zeros",
"numpy.argmin",
"numpy.mean",
"numpy.linalg.norm"
] | [((889, 938), 'numpy.zeros', 'np.zeros', (['(n_clusters, n_variables, n_dimensions)'], {}), '((n_clusters, n_variables, n_dimensions))\n', (897, 938), True, 'import numpy as np\n'), ((952, 971), 'numpy.zeros', 'np.zeros', (['n_samples'], {}), '(n_samples)\n', (960, 971), True, 'import numpy as np\n'), ((1077, 1123), 'p... |
# -*- coding: utf-8 -*-
"""
使用DBUtils数据库连接池中的连接,操作数据库
OperationalError: (2006, ‘MySQL server has gone away’)
"""
import json
import pymysql
import datetime
from DBUtils.PooledDB import PooledDB
import pymysql
import logging
class MysqlPool():
__pool = None # 连接池对象
__pool_cfg = {}
def __init__(self,db_... | [
"DBUtils.PooledDB.PooledDB"
] | [((1582, 2093), 'DBUtils.PooledDB.PooledDB', 'PooledDB', (['pymysql'], {'mincached': "__pool_cfg['mincached']", 'maxcached': "__pool_cfg['maxcached']", 'maxshared': "__pool_cfg['maxshared']", 'maxconnections': "__pool_cfg['maxconnections']", 'blocking': "__pool_cfg['blocking']", 'maxusage': "__pool_cfg['maxusage']", 's... |
import pytest
from django import forms
from gdpr_helpers.models import PrivacyEvent, PrivacyLog
from tests.forms import DummyForm
def test_legal_reason_group_as_form_fields(registration_legal_reason_group):
form_fields = registration_legal_reason_group.get_as_form_fields()
assert len(form_fields) == 2
as... | [
"gdpr_helpers.models.PrivacyEvent.objects.count",
"gdpr_helpers.models.PrivacyLog.objects.create_log",
"gdpr_helpers.models.PrivacyLog.objects.count",
"tests.forms.DummyForm",
"pytest.mark.parametrize",
"gdpr_helpers.models.PrivacyEvent.objects.get"
] | [((832, 943), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""privacy_registration, privacy_registration_valid"""', '[(True, True), (False, False)]'], {}), "('privacy_registration, privacy_registration_valid',\n [(True, True), (False, False)])\n", (855, 943), False, 'import pytest\n'), ((947, 1052), 'pyt... |
#!/usr/bin/env python3
import pytest
import sys
import fileinput
from os.path import splitext, abspath
def is_valid(number, r_min, r_max):
number = str(number).strip()
if not number.isnumeric() or len(number) != 6:
return False
inumber = int(number)
if inumber > r_max or inumber < r_min:
... | [
"os.path.abspath"
] | [((1076, 1093), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (1083, 1093), False, 'from os.path import splitext, abspath\n')] |
"""Test Hue init with multiple bridges."""
from unittest.mock import AsyncMock, Mock, patch
from aiohue.groups import Groups
from aiohue.lights import Lights
from aiohue.scenes import Scenes
from aiohue.sensors import Sensors
import pytest
from homeassistant import config_entries
from homeassistant.components import ... | [
"unittest.mock.patch.object",
"aiohue.sensors.Sensors",
"tests.common.MockConfigEntry",
"homeassistant.setup.async_setup_component",
"aiohue.groups.Groups",
"aiohue.scenes.Scenes",
"unittest.mock.Mock",
"unittest.mock.AsyncMock",
"unittest.mock.patch",
"aiohue.lights.Lights",
"homeassistant.comp... | [((4139, 4260), 'tests.common.MockConfigEntry', 'MockConfigEntry', ([], {'domain': 'hue.DOMAIN', 'data': "{'host': 'mock-host'}", 'connection_class': 'config_entries.CONN_CLASS_LOCAL_POLL'}), "(domain=hue.DOMAIN, data={'host': 'mock-host'},\n connection_class=config_entries.CONN_CLASS_LOCAL_POLL)\n", (4154, 4260), F... |
import json
import logging.handlers
import os
import uuid
import flask_security
import requests
import yaml
from flask import Blueprint
from flask import jsonify
from flask import render_template
from flask import request
from structlog import wrap_logger
import console.settings as settings
from console.helpers.excep... | [
"sdc.rabbit.QueuePublisher",
"uuid.uuid4",
"flask.Blueprint",
"json.loads",
"sdc.crypto.key_store.KeyStore",
"sdc.crypto.encrypter.encrypt",
"console.helpers.exceptions.ServiceError",
"console.helpers.exceptions.ClientError",
"flask.request.get_data",
"yaml.safe_load",
"flask.render_template",
... | [((544, 634), 'flask.Blueprint', 'Blueprint', (['"""submit_bp"""', '__name__'], {'static_folder': '"""static"""', 'template_folder': '"""templates"""'}), "('submit_bp', __name__, static_folder='static', template_folder=\n 'templates')\n", (553, 634), False, 'from flask import Blueprint\n'), ((914, 973), 'sdc.rabbit.... |
import numpy
import torch
from allennlp.modules.span_extractors import SpanExtractor, SelfAttentiveSpanExtractor
from allennlp.common.params import Params
class TestSelfAttentiveSpanExtractor:
def test_locally_normalised_span_extractor_can_build_from_params(self):
params = Params(
{
... | [
"torch.LongTensor",
"allennlp.modules.span_extractors.SelfAttentiveSpanExtractor",
"numpy.zeros",
"torch.randn",
"allennlp.modules.span_extractors.SpanExtractor.from_params",
"torch.tensor",
"allennlp.common.params.Params"
] | [((289, 401), 'allennlp.common.params.Params', 'Params', (["{'type': 'self_attentive', 'input_dim': 7, 'num_width_embeddings': 5,\n 'span_width_embedding_dim': 3}"], {}), "({'type': 'self_attentive', 'input_dim': 7, 'num_width_embeddings': 5,\n 'span_width_embedding_dim': 3})\n", (295, 401), False, 'from allennlp... |
from voteEvent.models import Choice, VoteEvent, Question
from rest_framework import serializers
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ['id', 'choice_text', 'votes']
depth = 2
class QuestionSerializer(serializers.ModelSerializer):
... | [
"voteEvent.models.Question.objects.create",
"voteEvent.models.Question.objects.get",
"voteEvent.models.VoteEvent.objects.create",
"voteEvent.models.Choice.objects.create",
"voteEvent.models.Choice.objects.get"
] | [((883, 925), 'voteEvent.models.VoteEvent.objects.create', 'VoteEvent.objects.create', ([], {}), '(**validated_data)\n', (907, 925), False, 'from voteEvent.models import Choice, VoteEvent, Question\n'), ((1053, 1114), 'voteEvent.models.Question.objects.create', 'Question.objects.create', ([], {'voteEvent': 'voteEvent'}... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest2 as unittest
all_suite = unittest.TestLoader().discover(os.path.dirname(__file__), "test_*.py")
| [
"os.path.dirname",
"unittest2.TestLoader"
] | [((129, 154), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (144, 154), False, 'import os\n'), ((98, 119), 'unittest2.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (117, 119), True, 'import unittest2 as unittest\n')] |
import logging
from flask import Flask, jsonify, Blueprint
from server.controller import tasks
bp = Blueprint('tasks', __name__)
logger = logging.getLogger()
@bp.route('/')
def view_base():
return jsonify({'status': 'success'})
@bp.route('/sleep/', methods=['POST'])
@bp.route('/sleep/<int:sleep_time>', methods=[... | [
"flask.Blueprint",
"server.controller.tasks.wait_task.AsyncResult",
"flask.jsonify",
"server.controller.tasks.wait_task.apply_async",
"logging.getLogger"
] | [((101, 129), 'flask.Blueprint', 'Blueprint', (['"""tasks"""', '__name__'], {}), "('tasks', __name__)\n", (110, 129), False, 'from flask import Flask, jsonify, Blueprint\n'), ((139, 158), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (156, 158), False, 'import logging\n'), ((203, 233), 'flask.jsonify', 'j... |
#!/usr/bin/env python3
""" MTCNN Face detection plugin """
from __future__ import absolute_import, division, print_function
import cv2
from keras.layers import Conv2D, Dense, Flatten, Input, MaxPool2D, Permute, PReLU
import numpy as np
from lib.model.session import KSession
from ._base import Detector, logger
cla... | [
"numpy.maximum",
"numpy.amin",
"numpy.empty",
"keras.layers.MaxPool2D",
"keras.layers.Input",
"numpy.multiply",
"numpy.power",
"keras.layers.Flatten",
"numpy.swapaxes",
"keras.layers.Permute",
"cv2.resize",
"numpy.repeat",
"numpy.minimum",
"numpy.fix",
"keras.layers.PReLU",
"keras.laye... | [((14833, 14864), 'numpy.where', 'np.where', (['(cls_prob >= threshold)'], {}), '(cls_prob >= threshold)\n', (14841, 14864), True, 'import numpy as np\n'), ((14920, 14962), 'numpy.fix', 'np.fix', (['((stride * boundingbox + 0) * scale)'], {}), '((stride * boundingbox + 0) * scale)\n', (14926, 14962), True, 'import nump... |
from django.urls import path
from rest_framework import renderers
from .views import PostViewSet, HashtagViewSet, PageViewSet
# from .views import PostHistoryViewSet
# app_name will help us do a reverse look-up latter.
app_name = "posts"
app_name = "hashtags"
app_name = "pages"
# app_name = "postshistory"
... | [
"django.urls.path"
] | [((1311, 1354), 'django.urls.path', 'path', (['"""posts/"""', 'post_list'], {'name': '"""post-list"""'}), "('posts/', post_list, name='post-list')\n", (1315, 1354), False, 'from django.urls import path\n'), ((1361, 1417), 'django.urls.path', 'path', (['"""posts/<int:pk>/"""', 'post_detail'], {'name': '"""post-detail"""... |
# Very simple model which saves its weights as well. Done without Keras and Estimator API. Just using the SavedModel API.
# Wanted to do it as vanilla TensorFlow as possible but it's just too pointlessly hard.
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import ... | [
"tensorflow.saved_model.simple_save",
"tensorflow.global_variables_initializer",
"tensorflow.argmax",
"os.path.realpath",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.zeros",
"tensorflow.matmul",
"tensorflow.log",
"tensorflow.examples.tutorials.mnist.input_data.... | [((413, 467), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""MNIST_data/"""'], {'one_hot': '(True)'}), "('MNIST_data/', one_hot=True)\n", (438, 467), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((508, 553), 'tensorflow.placeholder', 'tf.pl... |
# -*- coding:utf-8 -*-
# author:平手友梨奈ii
# e-mail:<EMAIL>
# datetime:1993/12/01
# filename:yolo4_tiny.py
# software: PyCharm
import keras
import keras.layers as layers
import keras.backend as K
import tensorflow as tf
class Mish(layers.Layer):
"""Mish activation"""
def __init__(self, **kwargs):
super... | [
"keras.Input",
"keras.regularizers.l2",
"keras.layers.LeakyReLU",
"keras.Model",
"keras.layers.MaxPool2D",
"keras.backend.softplus",
"keras.initializers.constant",
"keras.layers.Concatenate",
"keras.layers.UpSampling2D",
"keras.layers.ZeroPadding2D",
"keras.initializers.normal",
"tensorflow.sp... | [((4998, 5041), 'keras.Model', 'keras.Model', (['inputs', '[output_C4, output_C5]'], {}), '(inputs, [output_C4, output_C5])\n', (5009, 5041), False, 'import keras\n'), ((5103, 5135), 'keras.Input', 'keras.Input', ([], {'shape': '(416, 416, 3)'}), '(shape=(416, 416, 3))\n', (5114, 5135), False, 'import keras\n'), ((1851... |
from Doctors.models import DoctorsPost
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=DoctorsPost)
def index_doctors(sender, instance, **kwargs):
instance.indexing()
# setting for mapping in elasticsearch
# PUT doctor
# {
# "mappings": {
# "... | [
"django.dispatch.receiver"
] | [((126, 165), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'DoctorsPost'}), '(post_save, sender=DoctorsPost)\n', (134, 165), False, 'from django.dispatch import receiver\n')] |
"""
fftshift on OCLArrays
as of now, only supports even dimensions (as ifftshift == fftshift then ;)
kernels adapted from
<NAME>.
cufftShift: high performance CUDA-accelerated FFT-shift library.
Proc High Performance Computing Symposium.
2014.
<EMAIL>
"""
from __future__ import print_function, unicode_literals, ... | [
"numpy.iscomplexobj",
"gputools.OCLArray.empty_like",
"numpy.prod",
"numpy.int32",
"numpy.linspace",
"gputools.OCLArray.from_array",
"numpy.all"
] | [((6082, 6104), 'gputools.OCLArray.from_array', 'OCLArray.from_array', (['d'], {}), '(d)\n', (6101, 6104), False, 'from gputools import OCLArray, OCLProgram\n'), ((6117, 6139), 'gputools.OCLArray.empty_like', 'OCLArray.empty_like', (['d'], {}), '(d)\n', (6136, 6139), False, 'from gputools import OCLArray, OCLProgram\n'... |
import pytest
from tests.async_mock import AsyncMock
from galaxy.api.types import Subscription, SubscriptionGame, SubscriptionDiscovery
from galaxy.api.errors import BackendError
TEST_SUB_GAMES = [
SubscriptionGame(game_title='game_a', game_id='123'),
SubscriptionGame(game_title='game_b', game_id='321'),
... | [
"galaxy.api.errors.BackendError",
"pytest.raises",
"galaxy.api.types.Subscription",
"tests.async_mock.AsyncMock",
"galaxy.api.types.SubscriptionGame"
] | [((204, 256), 'galaxy.api.types.SubscriptionGame', 'SubscriptionGame', ([], {'game_title': '"""game_a"""', 'game_id': '"""123"""'}), "(game_title='game_a', game_id='123')\n", (220, 256), False, 'from galaxy.api.types import Subscription, SubscriptionGame, SubscriptionDiscovery\n'), ((262, 314), 'galaxy.api.types.Subscr... |
from google.appengine.ext import db
class Ad(db.Model):
created = db.DateTimeProperty(auto_now_add=True)
title = db.StringProperty()
blurb = db.StringProperty(multiline=True)
price = db.StringProperty()
price2 = db.IntegerProperty()
image = db.BlobProperty()
image_thumb = db.BlobProperty()
... | [
"google.appengine.ext.db.DateTimeProperty",
"google.appengine.ext.db.StringProperty",
"google.appengine.ext.db.BlobProperty",
"google.appengine.ext.db.EmailProperty",
"google.appengine.ext.db.BooleanProperty",
"google.appengine.ext.db.ListProperty",
"google.appengine.ext.db.PhoneNumberProperty",
"goog... | [((71, 109), 'google.appengine.ext.db.DateTimeProperty', 'db.DateTimeProperty', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (90, 109), False, 'from google.appengine.ext import db\n'), ((122, 141), 'google.appengine.ext.db.StringProperty', 'db.StringProperty', ([], {}), '()\n', (139, 141), False, 'from go... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2020 <NAME> <<EMAIL>>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, thi... | [
"pickle.loads",
"bidict.bidict",
"asyncio.sleep",
"asyncio.open_connection",
"struct.unpack",
"struct.pack",
"luxon.core.networking.pipe.Pipe",
"json.dumps",
"asyncio.Lock",
"asyncio.Queue",
"logging.getLogger",
"pickle.dumps"
] | [((1739, 1758), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1748, 1758), False, 'from logging import getLogger\n'), ((2258, 2304), 'struct.pack', 'struct.pack', (['"""!HQQ"""', 'pkt_type', 'channel', 'length'], {}), "('!HQQ', pkt_type, channel, length)\n", (2269, 2304), False, 'import struct\... |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
import sys
import torch.nn.init as init
affine_par = True
class HighResNetBlock(nn.Module):
def __init__(self, inplanes, outplanes, padding_=1, stride=1, dilation_ = 1):
super(HighResNetBlock, self)... | [
"torch.nn.PReLU",
"torch.nn.BatchNorm3d",
"torch.nn.ModuleList",
"torch.nn.Conv3d",
"torch.nn.ConvTranspose3d",
"torch.cat",
"torch.nn.init.kaiming_uniform",
"torch.nn.Upsample"
] | [((354, 463), 'torch.nn.Conv3d', 'nn.Conv3d', (['inplanes', 'outplanes'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': 'padding_', 'bias': '(False)', 'dilation': 'dilation_'}), '(inplanes, outplanes, kernel_size=3, stride=1, padding=padding_,\n bias=False, dilation=dilation_)\n', (363, 463), True, 'import torc... |
from django.conf.urls import url, include
from Bo_yuan import api
urlpatterns = [
# API
# 对接微信登陆 返回openid session_key
url(r'^code2session$', api.Code2SessionAPIView.as_view()),
# 用户信息
url(r'^users$', api.UsersAPIView.as_view()),
url(r'^users/(?P<pk>\d+)/$', api.UserAPIView.as_view()),
#... | [
"Bo_yuan.api.UserUpdateAPIView.as_view",
"Bo_yuan.api.JoinAPIView.as_view",
"Bo_yuan.api.BannerAPIView.as_view",
"Bo_yuan.api.CarAPIView.as_view",
"Bo_yuan.api.FwbAPIView.as_view",
"Bo_yuan.api.BrandsAPIView.as_view",
"Bo_yuan.api.UserLikeAPIView.as_view",
"Bo_yuan.api.CarTypeAPIView.as_view",
"Bo_y... | [((901, 931), 'django.conf.urls.url', 'url', (['"""^update-data$"""', 'api.year'], {}), "('^update-data$', api.year)\n", (904, 931), False, 'from django.conf.urls import url, include\n'), ((952, 993), 'django.conf.urls.url', 'url', (['"""^create-brands$"""', 'api.create_brands'], {}), "('^create-brands$', api.create_br... |
import json
import logging
from functools import total_ordering, cached_property
from typing import List, Union, Tuple, Optional
import plumbum
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.styles import get_style_by_name
... | [
"adfd.process.date_from_timestamp",
"pygments.lexers.get_lexer_by_name",
"adfd.db.lib.DbPost.get_post_ids_for_topic",
"adfd.process.slugify",
"logging.getLogger",
"pygments.formatters.html.HtmlFormatter",
"adfd.parse.ADFD_PARSER.to_html",
"adfd.metadata.PageMetadata",
"adfd.web.wsgi.NAV.replace_link... | [((529, 556), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (546, 556), False, 'import logging\n'), ((2012, 2044), 'adfd.web.wsgi.NAV.replace_links', 'NAV.replace_links', (['self._rawHtml'], {}), '(self._rawHtml)\n', (2029, 2044), False, 'from adfd.web.wsgi import NAV\n'), ((2099, 2135),... |
# File for the p4p Project
import numpy as np
__version__ = "0.0.1"
# initial values
g = -9.8
def abs_value(vector):
"""
Calculates the length of a vector
Args:
vector (np.array) Vector to get the length from the
Returns:
Length (float) Length of the Vector
"""
r... | [
"numpy.array",
"numpy.round",
"numpy.square",
"numpy.zeros"
] | [((553, 564), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (561, 564), True, 'import numpy as np\n'), ((4368, 4384), 'numpy.array', 'np.array', (['[0, g]'], {}), '([0, g])\n', (4376, 4384), True, 'import numpy as np\n'), ((6299, 6327), 'numpy.array', 'np.array', (['self.spring_matrix'], {}), '(self.spring_matrix)... |
from marshmallow import Schema, fields
class FragmentPagerInfoSchema(Schema):
previous = fields.String(required=True)
next = fields.String(required=True)
| [
"marshmallow.fields.String"
] | [((95, 123), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(True)'}), '(required=True)\n', (108, 123), False, 'from marshmallow import Schema, fields\n'), ((135, 163), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(True)'}), '(required=True)\n', (148, 163), False, 'from marshmallow... |
#
# Demo generator: you can do anything in make_case, complex calculation for
# case parameters, complex string manipulation, generation files, etc. The
# conf_root, dest_root and vpath will be passed so you know where all your
# files are.
#
import os
import string
from collections import OrderedDict
import bentoo.co... | [
"bentoo.common.helpers.make_jolly_virtual_topology",
"os.path.join",
"os.path.relpath"
] | [((626, 683), 'os.path.join', 'os.path.join', (['conf_root', '"""inputs"""', "(input_fn + '.template')"], {}), "(conf_root, 'inputs', input_fn + '.template')\n", (638, 683), False, 'import os\n'), ((1308, 1352), 'os.path.join', 'os.path.join', (['output_root', '"""bin"""', '"""panda_sd"""'], {}), "(output_root, 'bin', ... |
from hypothesis import given
from hypothesis.strategies import binary
from mitmproxy import options
from mitmproxy.connection import Client
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers.modes import Socks5Proxy
opts = options.Options()
tctx = C... | [
"hypothesis.strategies.binary",
"mitmproxy.connection.Client",
"mitmproxy.proxy.layers.modes.Socks5Proxy",
"mitmproxy.options.Options",
"mitmproxy.proxy.events.DataReceived"
] | [((294, 311), 'mitmproxy.options.Options', 'options.Options', ([], {}), '()\n', (309, 311), False, 'from mitmproxy import options\n'), ((327, 384), 'mitmproxy.connection.Client', 'Client', (["('client', 1234)", "('127.0.0.1', 8080)", '(1605699329)'], {}), "(('client', 1234), ('127.0.0.1', 8080), 1605699329)\n", (333, 3... |
from selenium import webdriver
def before_all(context):
context.browser = webdriver.PhantomJS()
context.browser.implicitly_wait(1)
context.server_url = 'http://localhost:8000'
def after_all(context):
context.browser.quit()
def before_feature(context, feature):
pass
| [
"selenium.webdriver.PhantomJS"
] | [((80, 101), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', ([], {}), '()\n', (99, 101), False, 'from selenium import webdriver\n')] |
from haystack import indexes
from haystack_static_pages.models import StaticPage
class StaticPageIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(
document=True, use_template=True,
template_name='staticpage_text.txt'
)
title = indexes.CharField(model_attr='title')
... | [
"haystack.indexes.CharField"
] | [((158, 251), 'haystack.indexes.CharField', 'indexes.CharField', ([], {'document': '(True)', 'use_template': '(True)', 'template_name': '"""staticpage_text.txt"""'}), "(document=True, use_template=True, template_name=\n 'staticpage_text.txt')\n", (175, 251), False, 'from haystack import indexes\n'), ((282, 319), 'ha... |
# Generated by Django 2.2.4 on 2019-08-11 14:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("user", "0006_add_company_information")]
operations = [
migrations.AlterField(
model_name="department",
name="type",
f... | [
"django.db.models.PositiveSmallIntegerField"
] | [((325, 572), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'choices': "[(0, 'ADMIN'), (1, 'DIRECTOR'), (2, 'DESIGN'), (3, 'FINANCE'), (4,\n 'SPONSORSHIP'), (5, 'HACKERXPERIENCE'), (6, 'LOGISTICS'), (7,\n 'MARKETING'), (8, 'PHOTOGRAPHY'), (9, 'STAFF'), (10, 'WEBDEV')]"}),... |
import os
import csv
import json
# import pandas
# import ntpath
def checkFolder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def saveTextFile(data, filename):
with open(filename,"w") as filewrite:
filewrite.write(str(data))
def saveCSV(data, filename):
... | [
"json.dump",
"csv.writer",
"os.makedirs",
"os.getcwd",
"os.path.exists",
"os.path.join"
] | [((905, 916), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (914, 916), False, 'import os\n'), ((930, 967), 'os.path.join', 'os.path.join', (['cwd', '"""data"""', 'defaultStr'], {}), "(cwd, 'data', defaultStr)\n", (942, 967), False, 'import os\n'), ((102, 124), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(fold... |
from common import initialize_test_yml_list_measurement
from view import VIEW
import logging
import pathlib as pl
import shutil
from nose.tools import raises
def export_fake_data_movie(flags_to_update, movie_name_suffix):
test_yml, test_animal, test_measu = initialize_test_yml_list_measurement()
view = VIEW... | [
"view.VIEW",
"logging.basicConfig",
"shutil.rmtree",
"common.initialize_test_yml_list_measurement",
"pathlib.Path",
"nose.tools.raises"
] | [((9275, 9293), 'nose.tools.raises', 'raises', (['ValueError'], {}), '(ValueError)\n', (9281, 9293), False, 'from nose.tools import raises\n'), ((265, 303), 'common.initialize_test_yml_list_measurement', 'initialize_test_yml_list_measurement', ([], {}), '()\n', (301, 303), False, 'from common import initialize_test_yml... |
import turtle
#turtle.shape("arrow")
#itay = turtle.clone()
#itay.shape("turtle")
#itay.goto(100,100)
#itay.goto(100,0)
#itay.right(90)
#itay.goto(200,0)
#itay.goto(200,100)
#itay.goto(100,100)
#charlie = turtle.clone()
#charlie.shape("triangle")
#charlie.penup()
#charlie.goto(100,-200)
#charlie.pendown()
#charlie.goto... | [
"turtle.mainloop",
"turtle.bgcolor",
"turtle.Turtle"
] | [((550, 565), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (563, 565), False, 'import turtle\n'), ((770, 785), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (783, 785), False, 'import turtle\n'), ((996, 1020), 'turtle.bgcolor', 'turtle.bgcolor', (['"""purple"""'], {}), "('purple')\n", (1010, 1020), False, ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as Data
import numpy as np
import os,time
import model
import h5py
import itertools
import utility
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
import ar... | [
"argparse.ArgumentParser",
"numpy.argmax",
"utility.encode_labels",
"model.CRNN2D_elu",
"utility.load_dataset_album_split_da",
"sklearn.metrics.f1_score",
"numpy.unique",
"model.CRNN2D_elu2",
"torch.utils.data.DataLoader",
"os.path.exists",
"utility.slice_songs_da",
"torch.cuda.device",
"tor... | [((2384, 2395), 'time.time', 'time.time', ([], {}), '()\n', (2393, 2395), False, 'import os, time\n'), ((7877, 7939), 'torch.utils.data.DataLoader', 'Data.DataLoader', ([], {'dataset': 'val_set', 'batch_size': 'bs', 'shuffle': '(False)'}), '(dataset=val_set, batch_size=bs, shuffle=False)\n', (7892, 7939), True, 'import... |
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
from random import randint
from act.utils import pad_batch
class ParityDataset(Dataset):
def __init__(self, size, len):
self.size = size
self.len = len
def __len__(self):
return self.len
def __getite... | [
"torch.randint",
"torch.stack",
"random.randint",
"torch.utils.data.DataLoader",
"torch.randperm",
"torch.arange",
"torch.zeros",
"torch.sum"
] | [((407, 459), 'torch.randint', 'torch.randint', (['(1)', 'self.size', '(1,)'], {'dtype': 'torch.uint8'}), '(1, self.size, (1,), dtype=torch.uint8)\n', (420, 459), False, 'import torch\n'), ((522, 547), 'torch.randperm', 'torch.randperm', (['self.size'], {}), '(self.size)\n', (536, 547), False, 'import torch\n'), ((1975... |
"""
Component Group Module
"""
# Local Library
from app.modules.entity.component_entity import ComponentEntity
from app.modules.entity.component_group_entity import ComponentGroupEntity
class ComponentGroup():
__component_group_entity = None
__component_entity = None
def __init__(self):
self.__... | [
"app.modules.entity.component_entity.ComponentEntity",
"app.modules.entity.component_group_entity.ComponentGroupEntity"
] | [((345, 367), 'app.modules.entity.component_group_entity.ComponentGroupEntity', 'ComponentGroupEntity', ([], {}), '()\n', (365, 367), False, 'from app.modules.entity.component_group_entity import ComponentGroupEntity\n'), ((402, 419), 'app.modules.entity.component_entity.ComponentEntity', 'ComponentEntity', ([], {}), '... |
# coding=utf-8
import struct
import unittest
from pamqp import constants, exceptions, frame
class TestCase(unittest.TestCase):
def test_invalid_protocol_header(self):
with self.assertRaises(exceptions.UnmarshalingException) as err:
frame.unmarshal(b'AMQP\x00\x00\t')
self.assertTr... | [
"pamqp.frame.unmarshal",
"struct.pack"
] | [((556, 582), 'struct.pack', 'struct.pack', (['""">BI"""', '(255)', '(0)'], {}), "('>BI', 255, 0)\n", (567, 582), False, 'import struct\n'), ((2087, 2120), 'struct.pack', 'struct.pack', (['""">HxxQ"""', '(8192)', '(32768)'], {}), "('>HxxQ', 8192, 32768)\n", (2098, 2120), False, 'import struct\n'), ((2574, 2598), 'struc... |
# 2019-11-28 00:55:58(JST)
import sys
def main():
digits = sorted(sys.stdin.readline().split())
if digits == list('1479'):
print('YES')
else:
print('NO')
if __name__ == '__main__':
main()
| [
"sys.stdin.readline"
] | [((77, 97), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (95, 97), False, 'import sys\n')] |
import numpy as np
import scipy.special as special
import scipy.optimize as optimization
import matplotlib.pyplot as plt
# this is a list of definitions that can be used to predict noise in KIDS
# right now it just contains the nessasary requirements for perdicting G-R noise in TiN
# I should expand it to include some... | [
"numpy.sum",
"matplotlib.pyplot.figure",
"numpy.exp",
"scipy.special.kv",
"numpy.meshgrid",
"matplotlib.pyplot.colorbar",
"numpy.reshape",
"numpy.linspace",
"numpy.asarray",
"scipy.optimize.curve_fit",
"scipy.special.digamma",
"numpy.min",
"matplotlib.pyplot.ylabel",
"numpy.vstack",
"num... | [((1777, 1810), 'numpy.reshape', 'np.reshape', (['t', '(t.shape[0], 1, 1)'], {}), '(t, (t.shape[0], 1, 1))\n', (1787, 1810), True, 'import numpy as np\n'), ((4509, 4537), 'numpy.where', 'np.where', (['(eps < 1 * 10 ** -8)'], {}), '(eps < 1 * 10 ** -8)\n', (4517, 4537), True, 'import numpy as np\n'), ((7207, 7232), 'num... |
import urllib.request
import re
ignore_chars = {'!','"',"'",'(',')','*',',','-','.','/','0','1','2','3','4','7','8',':',';','<','>','[',']','f','j','w','z' }
# https://gist.github.com/jarvisluong/f01e108e963092336f04c4b7dd6f7e45
def sanitize_word(s:str):
s = re.sub(r'à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ', "a", s)
... | [
"re.sub"
] | [((265, 316), 're.sub', 're.sub', (['"""à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ"""', '"""a"""', 's'], {}), "('à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ', 'a', s)\n", (271, 316), False, 'import re\n'), ((326, 365), 're.sub', 're.sub', (['"""è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ"""', '"""e"""', 's'], {}), "('è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ', 'e', s)\n", (332, ... |
from django.contrib import admin
from .models import SkinType, SkinConcern, Option, Question, Questionnaire, QuestionnaireEntry, QuestionnaireUserData
admin.site.register(SkinType)
admin.site.register(SkinConcern)
admin.site.register(Option)
admin.site.register(Question)
admin.site.register(Questionnaire)
admin.site.... | [
"django.contrib.admin.site.register"
] | [((153, 182), 'django.contrib.admin.site.register', 'admin.site.register', (['SkinType'], {}), '(SkinType)\n', (172, 182), False, 'from django.contrib import admin\n'), ((183, 215), 'django.contrib.admin.site.register', 'admin.site.register', (['SkinConcern'], {}), '(SkinConcern)\n', (202, 215), False, 'from django.con... |
from collections import defaultdict
def get_max_v_a_pair(world,
v_star,
state,
actions,
noise,
gamma):
v_a_pairs = []
for action in actions:
is_end, n_state = world.move_given_action(state, action)
... | [
"collections.defaultdict"
] | [((1194, 1219), 'collections.defaultdict', 'defaultdict', (['(lambda : 0.0)'], {}), '(lambda : 0.0)\n', (1205, 1219), False, 'from collections import defaultdict\n')] |
'''
Customization of look of Tkinter widgets
'''
import tkinter as tk
from tkinter import messagebox
class AppUI(tk.Frame):
def __init__(self, master=None):
# Initialize window
super().__init__(master)
self.master = master
self.master.title('Window Title')
# Center window
... | [
"tkinter.Button",
"tkinter.messagebox.showinfo",
"tkinter.Tk"
] | [((1494, 1501), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (1499, 1501), True, 'import tkinter as tk\n'), ((659, 795), 'tkinter.Button', 'tk.Button', (['self'], {'text': '"""Exit"""', 'command': 'self.master.destroy', 'activeforeground': '"""red"""', 'activebackground': '"""black"""', 'bg': '"""white"""', 'fg': '"""green... |
import requests
import json
import colorama as color
import termcolor as colors
color.init()
def status():
""" Checks the status of the API """
url = 'https://api.whatsonchain.com/v1/bsv/main/woc'
response = requests.get(url)
status_url = response.status_code
... | [
"colorama.init",
"termcolor.colored",
"requests.get"
] | [((84, 96), 'colorama.init', 'color.init', ([], {}), '()\n', (94, 96), True, 'import colorama as color\n'), ((250, 267), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (262, 267), False, 'import requests\n'), ((692, 711), 'requests.get', 'requests.get', (['url_2'], {}), '(url_2)\n', (704, 711), False, 'impor... |
# -*- coding: utf-8 -*-
# @Project : curve_fit
# @Time : 2019-05-27 14:51
# @Author : <NAME>
# @Email : <EMAIL>
# @File : continuous.py
import pickle
import numpy as np
from patsy import dmatrix
import statsmodels.api as sm
class Continuous:
def __init__(self, k=3):
self.model = None
se... | [
"statsmodels.api.GLM",
"pickle.dump",
"pickle.load",
"numpy.array",
"numpy.concatenate"
] | [((713, 724), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (721, 724), True, 'import numpy as np\n'), ((737, 748), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (745, 748), True, 'import numpy as np\n'), ((958, 969), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (966, 969), True, 'import numpy as np\n'), ((45... |
import time
import datetime
import os
import sys
import numpy as np
use_cntk = True
if use_cntk:
try:
base_directory = os.path.split(sys.executable)[0]
os.environ['PATH'] += ';' + base_directory
import cntk
os.environ['KERAS_BACKEND'] = 'cntk'
except ImportError:
print('... | [
"matplotlib.pyplot.title",
"keras.preprocessing.sequence.pad_sequences",
"cntk.layers.Embedding",
"matplotlib.pyplot.figure",
"numpy.arange",
"cntk.equal",
"cntk.layers.Dense",
"os.path.join",
"cntk.binary_cross_entropy",
"cntk.Evaluator",
"cntk.logging.ProgressPrinter",
"keras.layers.Flatten"... | [((777, 830), 'keras.datasets.imdb.load_data', 'keras.datasets.imdb.load_data', ([], {'num_words': 'max_features'}), '(num_words=max_features)\n', (806, 830), False, 'import keras\n'), ((945, 1011), 'keras.preprocessing.sequence.pad_sequences', 'keras.preprocessing.sequence.pad_sequences', (['x_train'], {'maxlen': 'max... |
# Expression evaluation routines
import claripy
def get_signed_range(se, expr):
"""
Calculate the range of the expression with signed boundaries
"""
size = expr.size()
umin = umax = smin = smax = None
if not sat_zero(se, expr):
try:
umin = se.min(expr, extra_constraints=[cl... | [
"claripy.Extract"
] | [((1415, 1456), 'claripy.Extract', 'claripy.Extract', (['(size - 1)', '(size - 1)', 'expr'], {}), '(size - 1, size - 1, expr)\n', (1430, 1456), False, 'import claripy\n'), ((1534, 1575), 'claripy.Extract', 'claripy.Extract', (['(size - 1)', '(size - 1)', 'expr'], {}), '(size - 1, size - 1, expr)\n', (1549, 1575), False... |
#%%
import numpy as np
from utils import *
#%%
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m)
a_prev -- Hidden state at timestep "t-1", numpy array of shape... | [
"numpy.multiply",
"numpy.tanh",
"numpy.sum",
"numpy.zeros",
"numpy.dot",
"numpy.concatenate"
] | [((2419, 2455), 'numpy.concatenate', 'np.concatenate', (['(a_prev, xt)'], {'axis': '(0)'}), '((a_prev, xt), axis=0)\n', (2433, 2455), True, 'import numpy as np\n'), ((5177, 5200), 'numpy.zeros', 'np.zeros', (['(n_a, m, T_x)'], {}), '((n_a, m, T_x))\n', (5185, 5200), True, 'import numpy as np\n'), ((5209, 5232), 'numpy.... |
from injector import inject
from pdip.cqrs import IQueryHandler
from pdip.dependency import IScoped
from tests.unittests.api.basic_app_with_cqrs.application.GetUser.GetUserMapping import GetUserMapping
from tests.unittests.api.basic_app_with_cqrs.application.GetUser.GetUserQuery import GetUserQuery
from tests.unittest... | [
"tests.unittests.api.basic_app_with_cqrs.application.GetUser.GetUserResponse.GetUserResponse"
] | [((805, 822), 'tests.unittests.api.basic_app_with_cqrs.application.GetUser.GetUserResponse.GetUserResponse', 'GetUserResponse', ([], {}), '()\n', (820, 822), False, 'from tests.unittests.api.basic_app_with_cqrs.application.GetUser.GetUserResponse import GetUserResponse\n')] |
from tkinter import *
from PIL import ImageTk, Image
import pymysql
from tkinter import messagebox
from tkinter import ttk
from datetime import datetime, timedelta
import decimal
class ATLzooAdminViewShow:
def __init__(self):
self.createAdminViewShowWindow()
self.buildAdminViewShowWindow(self.admin... | [
"tkinter.ttk.Treeview"
] | [((2243, 2313), 'tkinter.ttk.Treeview', 'ttk.Treeview', (['adminViewShowWindow'], {'columns': "('Name', 'Exhibit', 'Date')"}), "(adminViewShowWindow, columns=('Name', 'Exhibit', 'Date'))\n", (2255, 2313), False, 'from tkinter import ttk\n')] |
from django.db import models
from django.utils.translation import gettext as _
class Faq(models.Model):
title = models.CharField(max_length=250, verbose_name=_('faq title'))
description = models.CharField(max_length=250, verbose_name=_('faq description'))
is_published = models.BooleanField(default=True, v... | [
"django.db.models.ForeignKey",
"django.db.models.Manager",
"django.utils.translation.gettext"
] | [((366, 382), 'django.db.models.Manager', 'models.Manager', ([], {}), '()\n', (380, 382), False, 'from django.db import models\n'), ((536, 606), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Faq'], {'related_name': '"""items"""', 'on_delete': 'models.CASCADE'}), "(Faq, related_name='items', on_delete=models.CA... |
# Copyright 2015, Google, 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 writing, software d... | [
"jinja2.FileSystemLoader",
"google.appengine.ext.blobstore.create_upload_url",
"webapp2.WSGIApplication"
] | [((1465, 1564), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (["[('/provideurl', ProvideURL), ('/upload', SuccessHandler)]"], {'debug': '(True)'}), "([('/provideurl', ProvideURL), ('/upload',\n SuccessHandler)], debug=True)\n", (1488, 1564), False, 'import webapp2\n'), ((1067, 1144), 'google.appengine.ext.b... |