code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from flask import current_app as app
from .cart_product import Cart_Product
class Cart:
def __init__(self, id, pid, quantity):
self.id = id
self.pid = pid
self.quantity = quantity
@staticmethod
def get(id):
try:
rows = app.db.execute('''
SELECT p.id... | [
"flask.current_app.db.execute"
] | [((997, 1063), 'flask.current_app.db.execute', 'app.db.execute', (['"""\n SELECT *\n FROM Cart\n """'], {}), '("""\n SELECT *\n FROM Cart\n """)\n', (1011, 1063), True, 'from flask import current_app as app\n'), ((278, 650), 'flask.current_app.db.execute', 'app.db.execute', (['... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="simple_peewee_flask_webapi",
version="1.0.0",
author="<NAME>",
author_email="<EMAIL>",
description="Simple peewee Flask WEB-API",
long_description=long_description,
lon... | [
"setuptools.find_packages"
] | [((522, 566), 'setuptools.find_packages', 'setuptools.find_packages', ([], {'exclude': "('tests',)"}), "(exclude=('tests',))\n", (546, 566), False, 'import setuptools\n')] |
#!/usr/bin/python
import os
import io
import sys
import json
import shutil
import pandas
import dataLib
import datetime
# PIL - the Python Image Library, used for bitmap image manipulation.
import PIL
import PIL.ImageFont
import PIL.ImageDraw
# ReportLab - used for PDF document generation.
import reportlab.lib.units
... | [
"pandas.DataFrame",
"PIL.Image.new",
"os.makedirs",
"pandas.read_csv",
"dataLib.loadConfig",
"dataLib.yearCohortToGroup",
"datetime.datetime",
"datetime.datetime.strptime",
"datetime.timedelta",
"shutil.move",
"datetime.datetime.now",
"os.listdir"
] | [((1375, 1409), 'dataLib.loadConfig', 'dataLib.loadConfig', (["['dataFolder']"], {}), "(['dataFolder'])\n", (1393, 1409), False, 'import dataLib\n'), ((1606, 1645), 'os.makedirs', 'os.makedirs', (['historyRoot'], {'exist_ok': '(True)'}), '(historyRoot, exist_ok=True)\n', (1617, 1645), False, 'import os\n'), ((1656, 172... |
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from main.forms import SignupForm
from django.core.paginator i... | [
"main.models.ClubList.objects.get",
"django.core.urlresolvers.reverse",
"main.models.ClubList.objects.filter",
"django.shortcuts.render",
"main.forms.SignupForm",
"main.models.ClubList.objects.order_by"
] | [((595, 638), 'main.models.ClubList.objects.order_by', 'ClubList.objects.order_by', (['"""-ClubMemberSum"""'], {}), "('-ClubMemberSum')\n", (620, 638), False, 'from main.models import ClubList\n'), ((650, 704), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', "{'clublists': clublist}"], {}), "(requ... |
# Copyright (c) 2020 <NAME>
# Licensed under the MIT License
"""A module that contains caching helpers.
"""
from functools import update_wrapper
__all__ = ["cached"]
def cached(func):
"""Decorator that caches result of method or function.
"""
cache = {}
def wrapper(*args, **kwargs):
key =... | [
"functools.update_wrapper"
] | [((542, 571), 'functools.update_wrapper', 'update_wrapper', (['wrapper', 'func'], {}), '(wrapper, func)\n', (556, 571), False, 'from functools import update_wrapper\n')] |
from collections import deque
import random
import rank_based
class ReplayBuffer(object):
def __init__(self, buffer_size, batch_size=32, learn_start=2000, steps=100000, rand_s=False):
self.buffer_size = buffer_size
self.num_experiences = 0
self.buffer = deque()
self.rand_s = rand_... | [
"random.sample",
"rank_based.Experience",
"collections.deque"
] | [((285, 292), 'collections.deque', 'deque', ([], {}), '()\n', (290, 292), False, 'from collections import deque\n'), ((548, 575), 'rank_based.Experience', 'rank_based.Experience', (['conf'], {}), '(conf)\n', (569, 575), False, 'import rank_based\n'), ((680, 718), 'random.sample', 'random.sample', (['self.buffer', 'batc... |
import json
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive",
]
credentials = service_account.Credentials.from_service_account_info(
json.loads(os.environ["GOOG... | [
"googleapiclient.discovery.build",
"json.loads"
] | [((381, 427), 'googleapiclient.discovery.build', 'build', (['"""sheets"""', '"""v4"""'], {'credentials': 'credentials'}), "('sheets', 'v4', credentials=credentials)\n", (386, 427), False, 'from googleapiclient.discovery import build\n'), ((293, 341), 'json.loads', 'json.loads', (["os.environ['GOOGLE_SERVICE_ACCOUNT']"]... |
import pytest
import numpy as np
from spexxy.grid import GridAxis, ValuesGrid
@pytest.fixture()
def number_grid():
# define grid
grid = np.array([
[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[2, 3, 4, 5, 6],
[4, 5, 6, 7, 8]
])
# define axes
ax1 = GridAxis(name='x', values=l... | [
"numpy.array",
"spexxy.grid.ValuesGrid",
"pytest.fixture"
] | [((82, 98), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (96, 98), False, 'import pytest\n'), ((147, 225), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8]]'], {}), '([[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8]])\n', (155, 225), True, 'im... |
from CybORG.Agents import BaseAgent
from CybORG.Shared import Results
from CybORG.Shared.Actions import PrivilegeEscalate, ExploitRemoteService, DiscoverRemoteSystems, Impact, \
DiscoverNetworkServices, Sleep
class B_lineAgent(BaseAgent):
def __init__(self):
self.action = 0
self.target_ip_addr... | [
"CybORG.Shared.Actions.DiscoverNetworkServices",
"CybORG.Shared.Actions.Impact",
"CybORG.Shared.Actions.ExploitRemoteService",
"CybORG.Shared.Actions.DiscoverRemoteSystems",
"CybORG.Shared.Actions.PrivilegeEscalate"
] | [((1329, 1405), 'CybORG.Shared.Actions.DiscoverRemoteSystems', 'DiscoverRemoteSystems', ([], {'session': 'session', 'agent': '"""Red"""', 'subnet': 'self.last_subnet'}), "(session=session, agent='Red', subnet=self.last_subnet)\n", (1350, 1405), False, 'from CybORG.Shared.Actions import PrivilegeEscalate, ExploitRemoteS... |
import time
from .daemon import Daemon
def main():
daemon = Daemon()
while True:
daemon.tick()
files = daemon.get_email_files()
for file in files:
try:
daemon.handle_email(file)
except Exception:
daemon.on_error()
time.s... | [
"time.sleep"
] | [((314, 327), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (324, 327), False, 'import time\n')] |
from __future__ import division
import json
from time import time
from random import randint, choice
from threading import Timer
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import WebSocketHandler
class RepeatedTimer(object):
def __init__(self, interval, functio... | [
"threading.Timer",
"argparse.ArgumentParser",
"json.loads",
"random.randint",
"tornado.ioloop.IOLoop",
"random.choice",
"json.dumps",
"time.time",
"tornado.web.Application"
] | [((4029, 4054), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4052, 4054), False, 'import argparse\n'), ((4229, 4237), 'tornado.ioloop.IOLoop', 'IOLoop', ([], {}), '()\n', (4235, 4237), False, 'from tornado.ioloop import IOLoop\n'), ((4336, 4367), 'tornado.web.Application', 'Application', (["... |
###################################################
#
# Script to:
# - Load the images and extract the patches
# - Define the neural network
# - define the training
#
##################################################
import numpy as np
import configparser
from keras.utils import multi_gpu_model
... | [
"numpy.random.seed",
"tensorflow.zeros_like",
"keras.models.Model",
"keras.layers.Input",
"keras.callbacks.LearningRateScheduler",
"keras.layers.concatenate",
"sys.setrecursionlimit",
"keras.layers.Reshape",
"keras.backend.pow",
"keras.optimizers.SGD",
"keras.backend.flatten",
"configparser.Ra... | [((759, 787), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./lib/"""'], {}), "(0, './lib/')\n", (774, 787), False, 'import sys\n'), ((1289, 1316), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(4000)'], {}), '(4000)\n', (1310, 1316), False, 'import sys\n'), ((18411, 18441), 'configparser.RawConfigParser', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
from loglizer import InvariantsMiner, PCA, IsolationForest, OneClassSVM, LogClustering, LR
from loglizer import dataloader, preprocessing
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output_dir", metavar="DIR", h... | [
"argparse.ArgumentParser",
"loglizer.IsolationForest",
"loglizer.InvariantsMiner",
"loglizer.LR",
"loglizer.preprocessing.FeatureExtractor",
"loglizer.dataloader.load_data",
"loglizer.PCA",
"loglizer.LogClustering",
"os.path.expanduser",
"loglizer.OneClassSVM"
] | [((238, 263), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (261, 263), False, 'import argparse\n'), ((651, 712), 'os.path.expanduser', 'os.path.expanduser', (["(args.output_dir + args.dataset_name + '/')"], {}), "(args.output_dir + args.dataset_name + '/')\n", (669, 712), False, 'import os\n'... |
#
# Classes representing available types and their P4 equivalent.
#
from typing import Dict, List, Tuple
import ctypes
from functools import lru_cache
class KnownType:
"""
Base class of available types.
"""
pass
class uint8_t(KnownType):
def get_p4_type() -> str:
return 'bit<8>'
def... | [
"ctypes.c_uint8",
"ctypes.c_uint16",
"functools.lru_cache",
"ctypes.c_uint64",
"ctypes.c_uint32"
] | [((2624, 2647), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (2633, 2647), False, 'from functools import lru_cache\n'), ((498, 515), 'ctypes.c_uint8', 'ctypes.c_uint8', (['v'], {}), '(v)\n', (512, 515), False, 'import ctypes\n'), ((866, 884), 'ctypes.c_uint16', 'ctypes.c_uint16', (... |
"""Tests for gdrive_sync tasks"""
from datetime import datetime
import pytest
import pytz
from gdrive_sync import tasks
from gdrive_sync.conftest import LIST_FILE_RESPONSES, LIST_VIDEO_RESPONSES
from gdrive_sync.constants import (
DRIVE_API_FILES,
DRIVE_FILE_FIELDS,
DRIVE_FOLDER_FILES_FINAL,
DRIVE_FOL... | [
"gdrive_sync.tasks.transcode_drive_file_video.delay",
"gdrive_sync.factories.DriveFileFactory.create_batch",
"gdrive_sync.tasks.stream_drive_file_to_s3.delay",
"gdrive_sync.tasks.import_website_files.delay",
"gdrive_sync.tasks.import_recent_files.delay",
"gdrive_sync.factories.DriveApiQueryTrackerFactory.... | [((697, 754), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shared_id"""', "[None, 'testDrive']"], {}), "('shared_id', [None, 'testDrive'])\n", (720, 754), False, 'import pytest\n'), ((756, 822), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""drive_creds"""', '[None, \'{"key": "value"}\']'], ... |
# -*- coding: utf-8 -*-
from setuptools import setup
import os
from setuptools import setup, find_packages
import versioneer
long_description = open("README.md").read()
install_requires = []
setup(
name="exdir",
packages=find_packages(),
include_package_data=True,
version=versioneer.get_version(),
... | [
"versioneer.get_version",
"setuptools.find_packages",
"versioneer.get_cmdclass"
] | [((234, 249), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (247, 249), False, 'from setuptools import setup, find_packages\n'), ((294, 318), 'versioneer.get_version', 'versioneer.get_version', ([], {}), '()\n', (316, 318), False, 'import versioneer\n'), ((333, 358), 'versioneer.get_cmdclass', 'version... |
from discord.ext import commands
from PIL import Image
import discord, datetime, re
import PIL, shutil, os, random
class MineBase:
def __init__(self, member):
self.grid = [[0 for x in range(12)] for y in range(12)]
self.grid_show = [[0 for x in range(12)] for y in range(12)]
self.file = f"... | [
"os.remove",
"discord.ext.commands.command",
"random.randint",
"discord.File",
"PIL.Image.open",
"shutil.copy"
] | [((2463, 2481), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (2479, 2481), False, 'from discord.ext import commands\n'), ((385, 432), 'shutil.copy', 'shutil.copy', (['"""assets/mine/board.png"""', 'self.file'], {}), "('assets/mine/board.png', self.file)\n", (396, 432), False, 'import PIL, shuti... |
#!/usr/bin/env python
from setuptools import Command, setup
import sys
class PyPandoc(Command):
description = 'Generates the documentation in reStructuredText format.'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def convert(self, infile... | [
"pypandoc.convert"
] | [((415, 446), 'pypandoc.convert', 'pypandoc.convert', (['infile', '"""rst"""'], {}), "(infile, 'rst')\n", (431, 446), False, 'import pypandoc\n')] |
import pytest
from core import WordsRepository
@pytest.mark.parametrize(
"input_words,forget_letters,remaining_words",
[
("urger,ribat,anorn,stram,sofar", "ugo", "ribat,stram")
]
)
def test_forget_letters(input_words, forget_letters, remaining_words):
input_words = tuple(input_words.split(','... | [
"pytest.mark.parametrize",
"core.WordsRepository"
] | [((51, 184), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_words,forget_letters,remaining_words"""', "[('urger,ribat,anorn,stram,sofar', 'ugo', 'ribat,stram')]"], {}), "('input_words,forget_letters,remaining_words', [(\n 'urger,ribat,anorn,stram,sofar', 'ugo', 'ribat,stram')])\n", (74, 184), Fals... |
import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.applications.resnet50 import ResNet50
from keras.applications.inception_v3 import InceptionV3
from keras.applications.xception import Xception
# from efficientnet.keras import EfficientNetB3
from keras_preprocessing.i... | [
"keras.applications.xception.Xception",
"keras.layers.Dropout",
"keras.models.Model",
"keras.layers.GlobalAveragePooling2D",
"keras.applications.resnet50.ResNet50",
"keras.layers.Dense",
"keras.layers.Conv2D",
"keras.applications.inception_v3.InceptionV3",
"keras.layers.MaxPooling2D"
] | [((2085, 2122), 'keras.models.Model', 'Model', (['base_model.input', 'last_Dense_2'], {}), '(base_model.input, last_Dense_2)\n', (2090, 2122), False, 'from keras.models import Model\n'), ((774, 832), 'keras.applications.resnet50.ResNet50', 'ResNet50', ([], {'include_top': 'include_top', 'input_shape': 'input_shape'}), ... |
import numpy as np
from copy import copy
from .base import Simplifier
from ... import operations
from ...analyzers import SplitAnalysis
class ConvertBatchNorm(Simplifier):
ANALYSES = {"is_split": SplitAnalysis}
def visit_BatchNormalization(self, operation: operations.BatchNormalization):
input_op =... | [
"numpy.zeros",
"numpy.diag",
"copy.copy",
"numpy.sqrt"
] | [((481, 528), 'numpy.sqrt', 'np.sqrt', (['(operation.variance + operation.epsilon)'], {}), '(operation.variance + operation.epsilon)\n', (488, 528), True, 'import numpy as np\n'), ((941, 955), 'copy.copy', 'copy', (['input_op'], {}), '(input_op)\n', (945, 955), False, 'from copy import copy\n'), ((832, 879), 'numpy.zer... |
# Copyright 2021 Huawei Technologies 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 law or agreed to... | [
"mindspore.ops.ReduceMean",
"mindspore.ops.ReduceMax",
"mindspore.nn.Dropout",
"mindspore.ops.Identity",
"mindspore.nn.Dense"
] | [((927, 958), 'mindspore.ops.ReduceMean', 'ops.ReduceMean', ([], {'keep_dims': '(False)'}), '(keep_dims=False)\n', (941, 958), False, 'from mindspore import ops\n'), ((1502, 1531), 'mindspore.nn.Dense', 'nn.Dense', (['in_chs', 'num_classes'], {}), '(in_chs, num_classes)\n', (1510, 1531), False, 'from mindspore import n... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'layouts/base_project_main.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
d... | [
"PyQt4.QtGui.QWidget",
"PyQt4.QtGui.QLabel",
"PyQt4.QtGui.QCheckBox",
"PyQt4.QtGui.QVBoxLayout",
"PyQt4.QtGui.QSizePolicy",
"PyQt4.QtGui.QFont",
"PyQt4.QtGui.QGroupBox",
"PyQt4.QtGui.QApplication.translate",
"PyQt4.QtGui.QSlider",
"PyQt4.QtGui.QMenu",
"PyQt4.QtGui.QDockWidget",
"PyQt4.QtGui.QA... | [((467, 531), 'PyQt4.QtGui.QApplication.translate', 'QtGui.QApplication.translate', (['context', 'text', 'disambig', '_encoding'], {}), '(context, text, disambig, _encoding)\n', (495, 531), False, 'from PyQt4 import QtCore, QtGui\n'), ((849, 924), 'PyQt4.QtGui.QSizePolicy', 'QtGui.QSizePolicy', (['QtGui.QSizePolicy.Pre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 14:54:12 2018
@author: maximov
"""
import torch
import torch.nn as nn
import torch.utils.data
from torch.nn import functional as F
from arch.base_network import BaseNetwork
from arch.normalization import get_nonspade_norm_layer
from arch.archi... | [
"torch.nn.ReflectionPad2d",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.cat",
"torch.nn.Upsample",
"arch.architecture.SPADEResnetBlock",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.LeakyReLU"
] | [((1275, 1311), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', 'input_nc', '(3)'], {'padding': '(1)'}), '(3, input_nc, 3, padding=1)\n', (1284, 1311), True, 'import torch.nn as nn\n'), ((1506, 1541), 'arch.architecture.SPADEResnetBlock', 'SPADEResnetBlock', (['input_ch', '(64)', 'opt'], {}), '(input_ch, 64, opt)\n', (1522, 1... |
import logging
from pkg.compiler import compile_template
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event: dict, context: object) -> dict:
# event = {
# "requestId": "1234567890",
# "fragment": {...}
# }
ret = event.copy()
try:
ret["fragment"]... | [
"pkg.compiler.compile_template",
"logging.getLogger"
] | [((68, 87), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (85, 87), False, 'import logging\n'), ((323, 358), 'pkg.compiler.compile_template', 'compile_template', (["event['fragment']"], {}), "(event['fragment'])\n", (339, 358), False, 'from pkg.compiler import compile_template\n')] |
import tensorflow as tf
import numpy as np
import chess
#load the saved model
model=tf.keras.models.load_model('openlock_model')
#rest explained in nntest.py
probmodel=tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
PieceNum={'p':'0','n':'1','b':'2','r':'3','q':'4','k':'5','.':'6'}
def numreprgen(re... | [
"tensorflow.keras.models.load_model",
"numpy.argmax",
"tensorflow.keras.layers.Softmax",
"chess.Board",
"chess.BaseBoard"
] | [((85, 129), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""openlock_model"""'], {}), "('openlock_model')\n", (111, 129), True, 'import tensorflow as tf\n'), ((778, 791), 'chess.Board', 'chess.Board', ([], {}), '()\n', (789, 791), False, 'import chess\n'), ((820, 837), 'chess.BaseBoard', 'che... |
import json
import functools
from os import path, mkdir, getcwd
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import TypeDecorator, Unicode
from sqlalchemy_media import Image, ImageValidator, ImageProcessor, ImageAnalyzer, StoreManager, \
FileSystemStore
from sqlalchemy_... | [
"functools.partial",
"os.mkdir",
"json.loads",
"os.getcwd",
"flask.Flask",
"os.path.exists",
"json.dumps",
"flask_sqlalchemy.SQLAlchemy",
"sqlalchemy_media.ImageProcessor",
"sqlalchemy_media.ImageAnalyzer",
"sqlalchemy_media.ImageValidator",
"os.path.join"
] | [((401, 444), 'os.path.join', 'path.join', (['WORKING_DIR', '"""static"""', '"""avatars"""'], {}), "(WORKING_DIR, 'static', 'avatars')\n", (410, 444), False, 'from os import path, mkdir, getcwd\n'), ((452, 467), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (457, 467), False, 'from flask import Flask, req... |
# Copyright (c) Facebook, Inc. 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.
import torch.nn as nn
import torch.nn.functional as F
from foundations import hparams
from lottery.desc import LotteryDesc
from models import ... | [
"torch.nn.Sequential",
"foundations.hparams.ModelHparams",
"lottery.desc.LotteryDesc",
"foundations.hparams.TrainingHparams",
"torch.nn.Conv2d",
"torch.nn.CrossEntropyLoss",
"torch.nn.BatchNorm2d",
"pruning.sparse_global.PruningHparams",
"torch.nn.Linear",
"torch.nn.functional.relu",
"foundation... | [((1672, 1736), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(32)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(3, 32, kernel_size=3, stride=1, padding=1, bias=False)\n', (1681, 1736), True, 'import torch.nn as nn\n'), ((1755, 1773), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(32)']... |
# Utilities
import pickle
from math import pi, cos, sin, asin, sqrt
def saveFile(filename, data):
with open(filename, "wb") as f:
pickle.dump(data, f)
def loadFile(filename):
with open(filename, "rb") as f:
return pickle.load(f)
def coordToDeg(coord):
return coord[0] + coord[1] / 60 + co... | [
"pickle.dump",
"math.asin",
"math.sqrt",
"math.sin",
"pickle.load",
"math.cos"
] | [((937, 944), 'math.cos', 'cos', (['y1'], {}), '(y1)\n', (940, 944), False, 'from math import pi, cos, sin, asin, sqrt\n'), ((954, 961), 'math.cos', 'cos', (['y2'], {}), '(y2)\n', (957, 961), False, 'from math import pi, cos, sin, asin, sqrt\n'), ((998, 1021), 'math.sqrt', 'sqrt', (['(f1 + f2 * f3 * f4)'], {}), '(f1 + ... |
#!/usr/bin/env python3
from navicatGA.selfies_solver import SelfiesGenAlgSolver
from navicatGA.score_modifiers import score_modifier
from navicatGA.wrappers_selfies import (
sc2smiles,
sc2mol_structure,
mol_structure2depictions,
)
from navicatGA.quantum_wrappers_selfies import sc2gap
from navicatGA.wrapper... | [
"navicatGA.wrappers_selfies.sc2mw",
"navicatGA.quantum_wrappers_selfies.sc2gap",
"navicatGA.wrappers_selfies.sc2smiles",
"navicatGA.wrappers_selfies.sc2logp",
"navicatGA.wrappers_selfies.mol_structure2depictions",
"navicatGA.wrappers_selfies.sc2mol_structure"
] | [((2011, 2052), 'navicatGA.wrappers_selfies.sc2mol_structure', 'sc2mol_structure', (['solver.best_individual_'], {}), '(solver.best_individual_)\n', (2027, 2052), False, 'from navicatGA.wrappers_selfies import sc2smiles, sc2mol_structure, mol_structure2depictions\n'), ((2057, 2106), 'navicatGA.wrappers_selfies.mol_stru... |
import madlib
for i in range(0, 100):
print(madlib.get_madlib())
| [
"madlib.get_madlib"
] | [((49, 68), 'madlib.get_madlib', 'madlib.get_madlib', ([], {}), '()\n', (66, 68), False, 'import madlib\n')] |
from karabo.simulation.coordinate_helper import east_north_to_long_lat
from karabo.simulation.east_north_coordinate import EastNorthCoordinate
class Station:
def __init__(self, position: EastNorthCoordinate,
parent_longitude: float = 0,
parent_latitude: float = 0,
... | [
"karabo.simulation.coordinate_helper.east_north_to_long_lat"
] | [((585, 670), 'karabo.simulation.coordinate_helper.east_north_to_long_lat', 'east_north_to_long_lat', (['position.x', 'position.y', 'parent_longitude', 'parent_latitude'], {}), '(position.x, position.y, parent_longitude,\n parent_latitude)\n', (607, 670), False, 'from karabo.simulation.coordinate_helper import east_... |
import numpy as np
import matplotlib.pyplot as plt
import timeit
import random
import math
def insertionSort(a):
for i in range(1,len(a)):
value = a[i]
pos = i
while (pos > 0 and value < a[pos-1]):
a[pos] = a[pos-1]
pos = pos-1
a[pos] = value
def countingSort(a,max):
m = max+1
co... | [
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.plot",
"timeit.default_timer",
"matplotlib.pyplot.axis",
"numpy.append",
"numpy.mean",
"numpy.random.randint",
"numpy.array"
] | [((1790, 1822), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (1807, 1822), True, 'import numpy as np\n'), ((1927, 1939), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1935, 1939), True, 'import numpy as np\n'), ((1945, 1957), 'numpy.array', 'np.array', (['[]'],... |
from .Const import Const
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By... | [
"selenium.webdriver.chrome.service.Service",
"selenium.webdriver.support.expected_conditions.presence_of_element_located",
"selenium.webdriver.ChromeOptions",
"requests.get",
"bs4.BeautifulSoup",
"selenium.webdriver.support.ui.WebDriverWait"
] | [((571, 596), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (594, 596), False, 'from selenium import webdriver\n'), ((3251, 3324), 'bs4.BeautifulSoup', 'BeautifulSoup', (['self.seleniumWebDriver.page_source'], {'features': '"""html.parser"""'}), "(self.seleniumWebDriver.page_source, f... |
# -*- coding: utf-8 -*-
import unittest
from openprocurement.auctions.tessel.tests.base import BaseTesselAuctionWebTest
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.core.tests.document import (
AuctionDocumentResourceTestMixin,
AuctionDocumentWithDSResourceTestMixin... | [
"unittest.main",
"openprocurement.auctions.core.tests.base.snitch",
"unittest.makeSuite",
"unittest.TestSuite"
] | [((771, 801), 'openprocurement.auctions.core.tests.base.snitch', 'snitch', (['patch_auction_document'], {}), '(patch_auction_document)\n', (777, 801), False, 'from openprocurement.auctions.core.tests.base import snitch\n'), ((983, 1013), 'openprocurement.auctions.core.tests.base.snitch', 'snitch', (['patch_auction_docu... |
# This file is part of astro_metadata_translator.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code... | [
"astropy.coordinates.EarthLocation.from_geodetic",
"re.match",
"posixpath.join",
"astropy.io.fits.open",
"astropy.coordinates.Angle",
"astropy.coordinates.EarthLocation.of_site"
] | [((1121, 1170), 'posixpath.join', 'posixpath.join', (['CORRECTIONS_RESOURCE_ROOT', '"""CFHT"""'], {}), "(CORRECTIONS_RESOURCE_ROOT, 'CFHT')\n", (1135, 1170), False, 'import posixpath\n'), ((1431, 1447), 'astropy.coordinates.Angle', 'Angle', (['(0 * u.deg)'], {}), '(0 * u.deg)\n', (1436, 1447), False, 'from astropy.coor... |
import logging
from rich.logging import RichHandler
from rich.traceback import install
install(max_frames=1)
FORMAT = '%(message)s'
logging.basicConfig(
level='INFO',
format=FORMAT,
datefmt='[%X]',
handlers=[RichHandler(rich_tracebacks=True)]
)
log = logging.getLogger('rich')
| [
"rich.traceback.install",
"rich.logging.RichHandler",
"logging.getLogger"
] | [((89, 110), 'rich.traceback.install', 'install', ([], {'max_frames': '(1)'}), '(max_frames=1)\n', (96, 110), False, 'from rich.traceback import install\n'), ((271, 296), 'logging.getLogger', 'logging.getLogger', (['"""rich"""'], {}), "('rich')\n", (288, 296), False, 'import logging\n'), ((227, 260), 'rich.logging.Rich... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.program_list,
name='program_list'
),
url(
regex=r'(?P<program_slug>[-\w]+)/$',
view=vi... | [
"django.conf.urls.url"
] | [((157, 218), 'django.conf.urls.url', 'url', ([], {'regex': '"""^$"""', 'view': 'views.program_list', 'name': '"""program_list"""'}), "(regex='^$', view=views.program_list, name='program_list')\n", (160, 218), False, 'from django.conf.urls import url\n'), ((255, 350), 'django.conf.urls.url', 'url', ([], {'regex': '"""(... |
"""Custom TestCase and helpers for connectmessages tests."""
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
from django.utils.timezone import ... | [
"model_mommy.mommy.make",
"django.core.urlresolvers.reverse",
"django.test.RequestFactory",
"django.utils.timezone.now",
"django.contrib.auth.get_user_model",
"django.contrib.messages.storage.fallback.FallbackStorage"
] | [((561, 577), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (575, 577), False, 'from django.contrib.auth import get_user_model\n'), ((1201, 1218), 'model_mommy.mommy.make', 'mommy.make', (['Group'], {}), '(Group)\n', (1211, 1218), False, 'from model_mommy import mommy\n'), ((1446, 1506), 'mo... |
from django.urls import include, path
from videos.views import manage_videos, manage_videos_search
app_name = 'videos'
urlpatterns = [
path('videos', manage_videos, name='manage_videos'),
path('videos/search', manage_videos_search, name='manage_videos_search')
]
| [
"django.urls.path"
] | [((142, 193), 'django.urls.path', 'path', (['"""videos"""', 'manage_videos'], {'name': '"""manage_videos"""'}), "('videos', manage_videos, name='manage_videos')\n", (146, 193), False, 'from django.urls import include, path\n'), ((199, 271), 'django.urls.path', 'path', (['"""videos/search"""', 'manage_videos_search'], {... |
# coding=utf-8
from __future__ import absolute_import
import logging
def init_logging(debug):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
if debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger('eodatasets').setLevel(logging.INFO)
| [
"logging.getLogger",
"logging.basicConfig"
] | [((101, 168), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(levelname)s %(message)s"""'}), "(format='%(asctime)s %(levelname)s %(message)s')\n", (120, 168), False, 'import logging\n'), ((191, 210), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (208, 210), False, 'import l... |
from typing import Iterable, Sized, Collection, Callable, Tuple
from typing import Union, Optional, overload
from labml.internal.monitor import monitor_singleton as _internal
def clear():
_internal().clear()
def func(name, *,
is_silent: bool = False,
is_timed: bool = True,
is_partial... | [
"labml.internal.monitor.monitor_singleton"
] | [((195, 206), 'labml.internal.monitor.monitor_singleton', '_internal', ([], {}), '()\n', (204, 206), True, 'from labml.internal.monitor import monitor_singleton as _internal\n'), ((1217, 1228), 'labml.internal.monitor.monitor_singleton', '_internal', ([], {}), '()\n', (1226, 1228), True, 'from labml.internal.monitor im... |
import sys
from django.shortcuts import render, get_object_or_404
from bleet.models import Bleet
from users.models import Follow, Profile
from django.contrib.auth.models import User
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from django.contrib.aut... | [
"bleet.models.Bleet.objects.all",
"users.models.Follow.objects.filter",
"bleet.models.Bleet.objects.filter"
] | [((4809, 4828), 'bleet.models.Bleet.objects.all', 'Bleet.objects.all', ([], {}), '()\n', (4826, 4828), False, 'from bleet.models import Bleet\n'), ((1089, 1121), 'users.models.Follow.objects.filter', 'Follow.objects.filter', ([], {'user': 'user'}), '(user=user)\n', (1110, 1121), False, 'from users.models import Follow,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
import numpy as np
import PIL.Image as Image
import time
import cv2
from pyfirmata import Ar... | [
"tensorflow.train.import_meta_graph",
"numpy.argmax",
"cv2.waitKey",
"tensorflow.Session",
"time.sleep",
"cv2.VideoCapture",
"time.time",
"pyfirmata.Arduino",
"cv2.setMouseCallback",
"cv2.destroyWindow",
"PIL.Image.fromarray",
"tensorflow.get_default_graph",
"cv2.imshow",
"cv2.namedWindow"... | [((334, 357), 'pyfirmata.Arduino', 'Arduino', (['"""/dev/ttyACM0"""'], {}), "('/dev/ttyACM0')\n", (341, 357), False, 'from pyfirmata import Arduino\n'), ((1122, 1141), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(2)'], {}), '(2)\n', (1138, 1141), False, 'import cv2\n'), ((1206, 1233), 'cv2.namedWindow', 'cv2.namedWindow... |
from unittest import TestCase
from class_odd_and_prime_number import Number
class TestNumber(TestCase):
def test_number_init(self):
valid_number = Number(5)
self.assertEqual(valid_number.value, 5)
| [
"class_odd_and_prime_number.Number"
] | [((162, 171), 'class_odd_and_prime_number.Number', 'Number', (['(5)'], {}), '(5)\n', (168, 171), False, 'from class_odd_and_prime_number import Number\n')] |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="shazamio",
version="0.0.5",
author="dotX12",
description="Is a FREE asynchronous library from reverse engineered Shazam API written in Python 3.6+ with asyncio and aiohttp. I... | [
"setuptools.find_packages"
] | [((638, 664), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (662, 664), False, 'import setuptools\n')] |
#!/usr/bin/env python
# coding: utf-8
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import errno
import filecmp
import os
import plistlib
import shutil
import stat
import subprocess
impo... | [
"os.mkdir",
"argparse.ArgumentParser",
"os.lchmod",
"plistlib.dump",
"shutil.rmtree",
"filecmp.cmp",
"os.path.join",
"os.utime",
"subprocess.check_call",
"os.path.exists",
"shutil.copyfile",
"stat.S_ISDIR",
"stat.S_ISLNK",
"stat.S_ISREG",
"os.stat",
"os.path.basename",
"os.listdir",
... | [((1904, 1928), 'stat.S_ISLNK', 'stat.S_ISLNK', (['st.st_mode'], {}), '(st.st_mode)\n', (1916, 1928), False, 'import stat\n'), ((1968, 1992), 'stat.S_ISREG', 'stat.S_ISREG', (['st.st_mode'], {}), '(st.st_mode)\n', (1980, 1992), False, 'import stat\n'), ((2023, 2047), 'stat.S_ISDIR', 'stat.S_ISDIR', (['st.st_mode'], {})... |
from .metric import Metric, metric_path
import pandas as pd
import math
class JobMakespanMetric(Metric):
def __init__(self, plot, scenarios):
super().__init__(plot, scenarios)
self.name = "job_makespan"
self.x_axis_label = "Job makespan (seconds)"
def get_data(self, scenario):
... | [
"math.isnan"
] | [((905, 925), 'math.isnan', 'math.isnan', (['makespan'], {}), '(makespan)\n', (915, 925), False, 'import math\n')] |
from sg.StanfordGap import StanfordGap
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
class StanfordGapDemo(object):
def run(self):
"""
Run the Stanford Gap Statistic Analysis on the iris data set presented in
http://sciki... | [
"sklearn.datasets.load_iris",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"sg.StanfordGap.StanfordGap"
] | [((473, 491), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (487, 491), True, 'import numpy as np\n'), ((507, 527), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (525, 527), False, 'from sklearn import datasets\n'), ((566, 583), 'numpy.zeros', 'np.zeros', (['(20, 1)'], {}), '(... |
import logging
import numpy as np
import glob
from beis_indicators import project_dir
from beis_indicators.geo import NutsCoder, LepCoder
from beis_indicators.indicators import points_to_indicator, save_indicator
from beis_indicators.travel.travel_work_processing import get_travel_work_data
import pandas a... | [
"pandas.read_csv",
"beis_indicators.indicators.save_indicator",
"beis_indicators.travel.travel_work_processing.get_travel_work_data",
"beis_indicators.indicators.points_to_indicator",
"beis_indicators.geo.LepCoder",
"logging.getLogger",
"beis_indicators.geo.NutsCoder"
] | [((337, 364), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (354, 364), False, 'import logging\n'), ((484, 506), 'beis_indicators.travel.travel_work_processing.get_travel_work_data', 'get_travel_work_data', ([], {}), '()\n', (504, 506), False, 'from beis_indicators.travel.travel_work_pro... |
from collections import defaultdict
from os.path import abspath
from os.path import expanduser
from os.path import isdir
from os.path import isfile
from os.path import join
import sys
from types import ModuleType
from typing import Any
from typing import Callable
from typing import DefaultDict
from typing import Dict
f... | [
"ddtrace.internal.utils.get_argument_value",
"os.path.abspath",
"ddtrace.internal.logger.get_logger",
"sys.meta_path.insert",
"os.path.isdir",
"typing.cast",
"importlib.util.find_spec",
"collections.defaultdict",
"sys.modules._add_to_meta_path",
"os.path.isfile",
"sys.modules.values",
"sys.met... | [((621, 641), 'ddtrace.internal.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (631, 641), False, 'from ddtrace.internal.logger import get_logger\n'), ((1062, 1109), 'ddtrace.internal.utils.get_argument_value', 'get_argument_value', (['args', 'kwargs', '(3)', '"""mod_name"""'], {}), "(args, kwarg... |
#!/usr/bin/env python3
from typing import Optional, Tuple
import torch
from .. import settings
from ..distributions import Delta, MultivariateNormal
from ..lazy import DiagLazyTensor, MatmulLazyTensor, SumLazyTensor, lazify
from ..module import Module
from ..utils import linear_cg
from ..utils.broadcasting import _m... | [
"torch.ones_like",
"torch.randn_like",
"torch.cat",
"torch.zeros_like"
] | [((3044, 3081), 'torch.zeros_like', 'torch.zeros_like', (['interp_mean[..., 0]'], {}), '(interp_mean[..., 0])\n', (3060, 3081), False, 'import torch\n'), ((7576, 7598), 'torch.ones_like', 'torch.ones_like', (['zeros'], {}), '(zeros)\n', (7591, 7598), False, 'import torch\n'), ((8373, 8412), 'torch.cat', 'torch.cat', ([... |
# Generated by Django 3.0.6 on 2020-06-26 09:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sessions', '0001_initial'),
('core', '0004_auto_20200603_1414'),
]
operations = [
migrations.Create... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.EmailField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"
] | [((405, 498), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (421, 498), False, 'from django.db import migrations, models\... |
from . import Loader
import pandas as pd
class SOFROISLoader(Loader):
dataset = 'SOFR'
fileglob = 'SOFR_OIS_*.csv'
columns = ['Trade Date', 'Exchange Code', 'Currency','Commodity Code',
'Short Description','Long Description', 'Curve Date', 'Offset',
'Discount Factor', 'Fo... | [
"pandas.read_csv"
] | [((813, 848), 'pandas.read_csv', 'pd.read_csv', (['file'], {'low_memory': '(False)'}), '(file, low_memory=False)\n', (824, 848), True, 'import pandas as pd\n')] |
#!/usr/bin/python
import numpy as np
import pylab as plt
import seaborn as sns
sns.set_context("poster")
#with open("traj.dat") as f:
# data = f.read()
#
# data = data.split('\n')
#
# x = [row.split(' ')[0] for row in data]
# y = [row.split(' ')[1] for row in data]
#
# fig = plt.figure()
#
# ax1 = f... | [
"pylab.show",
"numpy.genfromtxt",
"pylab.plot",
"pylab.subplot",
"pylab.savefig",
"pylab.ylim",
"pylab.xlabel",
"pylab.legend",
"seaborn.set_context"
] | [((81, 106), 'seaborn.set_context', 'sns.set_context', (['"""poster"""'], {}), "('poster')\n", (96, 106), True, 'import seaborn as sns\n'), ((551, 567), 'pylab.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (562, 567), True, 'import pylab as plt\n'), ((591, 619), 'numpy.genfromtxt', 'np.genfromtxt', ([], {'fname'... |
"""
This example acts as a keyboard to peer devices.
"""
# import board
import sys
import time
import adafruit_ble
from adafruit_ble.advertising import Advertisement
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from adafruit_ble.s... | [
"sys.stdout.write",
"sys.stdin.read",
"adafruit_hid.keyboard.Keyboard",
"adafruit_ble.services.standard.hid.HIDService",
"time.sleep",
"adafruit_hid.keyboard_layout_us.KeyboardLayoutUS",
"adafruit_ble.BLERadio",
"adafruit_ble.advertising.Advertisement",
"adafruit_ble.services.standard.device_info.De... | [((514, 526), 'adafruit_ble.services.standard.hid.HIDService', 'HIDService', ([], {}), '()\n', (524, 526), False, 'from adafruit_ble.services.standard.hid import HIDService\n'), ((541, 643), 'adafruit_ble.services.standard.device_info.DeviceInfoService', 'DeviceInfoService', ([], {'software_revision': 'adafruit_ble.__v... |
"""
Defining standard tensorflow optimizers as modules.
"""
import tensorflow as tf
from deeplearning import module
from deeplearning import tf_util as U
class SGD(module.Optimizer):
ninputs = 1
def __init__(self, name, loss, lr=1e-4, momentum=0.0, clip_norm=None):
super().__init__(name, loss)
... | [
"deeplearning.tf_util.flatgrad",
"tensorflow.placeholder",
"tensorflow.Variable",
"tensorflow.train.MomentumOptimizer",
"tensorflow.gradients",
"tensorflow.train.AdamOptimizer",
"tensorflow.clip_by_global_norm",
"tensorflow.get_default_session"
] | [((495, 543), 'tensorflow.Variable', 'tf.Variable', (['self.lr'], {'name': '"""lr"""', 'trainable': '(False)'}), "(self.lr, name='lr', trainable=False)\n", (506, 543), True, 'import tensorflow as tf\n'), ((575, 625), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '()', 'name': '"""lr_ph"""'}), "... |
'''font.py: Class to manage individual fonts.'''
import os
import codecs
from typing import Dict, Any, Optional
from fontTools.ttLib import TTFont
from fonty.lib.variants import FontAttribute
from fonty.lib.font_name_ids import FONT_NAMEID_FAMILY, FONT_NAMEID_FAMILY_PREFFERED, \
FON... | [
"os.path.abspath",
"fontTools.ttLib.TTFont",
"os.makedirs",
"os.path.basename",
"os.path.isdir",
"codecs.decode",
"os.path.dirname",
"os.path.exists",
"os.path.isfile",
"os.path.splitext",
"fonty.lib.install.install_fonts",
"os.path.join",
"fonty.lib.variants.FontAttribute.parse"
] | [((1406, 1425), 'fonty.lib.install.install_fonts', 'install_fonts', (['self'], {}), '(self)\n', (1419, 1425), False, 'from fonty.lib.install import install_fonts\n'), ((2199, 2229), 'fontTools.ttLib.TTFont', 'TTFont', ([], {'file': 'self.path_to_font'}), '(file=self.path_to_font)\n', (2205, 2229), False, 'from fontTool... |
from flask import g, abort, redirect, url_for
from app.instances import db
from app.models.Post import Post
from app.models.Answer import Answer
from app.models.PostVote import PostVote
from app.models.AnswerVote import AnswerVote
# noinspection PyUnresolvedReferences
import app.routes.post
# noinspection PyUnresolve... | [
"app.models.PostVote.PostVote",
"app.instances.db.session.commit",
"flask.abort",
"app.models.Answer.Answer.query.filter_by",
"app.models.Post.Post.query.filter_by",
"app.models.AnswerVote.AnswerVote.query.filter_by",
"app.models.AnswerVote.AnswerVote",
"app.instances.db.session.add",
"app.models.Po... | [((553, 563), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (558, 563), False, 'from flask import g, abort, redirect, url_for\n'), ((914, 924), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (919, 924), False, 'from flask import g, abort, redirect, url_for\n'), ((2092, 2102), 'flask.abort', 'abort', (['(401)... |
from keras.models import load_model
import numpy as np
from encoding import encode
from encoding import decode
model = load_model('Model-0.1.hf')
post_title = input("What do you want to know from u/rogersimon10? \n")
post_title = "What’s the worst thing you’ve eaten out of politeness?"
encoded_title = np.array(encode... | [
"keras.models.load_model",
"encoding.decode",
"encoding.encode"
] | [((120, 146), 'keras.models.load_model', 'load_model', (['"""Model-0.1.hf"""'], {}), "('Model-0.1.hf')\n", (130, 146), False, 'from keras.models import load_model\n'), ((512, 534), 'encoding.decode', 'decode', (['encoded_answer'], {}), '(encoded_answer)\n', (518, 534), False, 'from encoding import decode\n'), ((314, 34... |
import os
import sys
import numpy as np
import pytest
from matchms import Spectrum
from spec2vec import Spec2Vec
from spec2vec import SpectrumDocument
path_root = os.path.dirname(os.getcwd())
sys.path.insert(0, os.path.join(path_root, "matchmsextras"))
from matchmsextras.library_search import library_matching
def te... | [
"matchmsextras.library_search.library_matching",
"os.getcwd",
"spec2vec.SpectrumDocument",
"numpy.array",
"pytest.approx",
"os.path.join",
"numpy.all"
] | [((180, 191), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (189, 191), False, 'import os\n'), ((212, 252), 'os.path.join', 'os.path.join', (['path_root', '"""matchmsextras"""'], {}), "(path_root, 'matchmsextras')\n", (224, 252), False, 'import os\n'), ((1240, 1554), 'matchmsextras.library_search.library_matching', 'libr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit Tests
__author__: <NAME>, <NAME>, <NAME>
"""
import os
import sys
import unittest
import numpy as np
from scipy.io import loadmat
sys.path.append(".")
from inferactively.distributions import Categorical, Dirichlet # nopep8
class TestDirichlet(unittest.TestCa... | [
"sys.path.append",
"unittest.main",
"numpy.array_equal",
"numpy.log",
"scipy.io.loadmat",
"inferactively.distributions.Dirichlet",
"os.getcwd",
"numpy.isclose",
"numpy.array",
"numpy.random.rand"
] | [((189, 209), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (204, 209), False, 'import sys\n'), ((5509, 5524), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5522, 5524), False, 'import unittest\n'), ((368, 379), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {}), '()\n', (377, 3... |
from sqladmin.helpers import secure_filename
def test_secure_filename(monkeypatch):
assert secure_filename("My cool movie.mov") == "My_cool_movie.mov"
assert secure_filename("../../../etc/passwd") == "etc_passwd"
assert (
secure_filename("i contain cool \xfcml\xe4uts.txt")
== "i_contain_co... | [
"sqladmin.helpers.secure_filename"
] | [((97, 133), 'sqladmin.helpers.secure_filename', 'secure_filename', (['"""My cool movie.mov"""'], {}), "('My cool movie.mov')\n", (112, 133), False, 'from sqladmin.helpers import secure_filename\n'), ((168, 206), 'sqladmin.helpers.secure_filename', 'secure_filename', (['"""../../../etc/passwd"""'], {}), "('../../../etc... |
import os, sys, time, re
import cv2
import deeptool
sameImages= []
cachedImages = None
def isSameImage(imghist, checkhist):
ret = cv2.compareHist(imghist, checkhist, 0)
ret2 = cv2.compareHist(imghist, checkhist, 1)
ret3 = cv2.compareHist(imghist, checkhist, 2)
ret4 = cv2.compareHist(imghist, checkhis... | [
"os.unlink",
"os.path.isdir",
"cv2.calcHist",
"deeptool.listDir",
"time.time",
"cv2.imread",
"sys.stdout.flush",
"cv2.compareHist",
"cv2.resize",
"re.compile"
] | [((137, 175), 'cv2.compareHist', 'cv2.compareHist', (['imghist', 'checkhist', '(0)'], {}), '(imghist, checkhist, 0)\n', (152, 175), False, 'import cv2\n'), ((187, 225), 'cv2.compareHist', 'cv2.compareHist', (['imghist', 'checkhist', '(1)'], {}), '(imghist, checkhist, 1)\n', (202, 225), False, 'import cv2\n'), ((237, 27... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 23 14:54:35 2017
@author: user
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from typing import Any
from typing import Dict
from typing import List
... | [
"rasa_nlu.tokenizers.Token",
"yaha.Cuttor",
"sys.setdefaultencoding"
] | [((630, 661), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (652, 661), False, 'import sys\n'), ((798, 806), 'yaha.Cuttor', 'Cuttor', ([], {}), '()\n', (804, 806), False, 'from yaha import Cuttor\n'), ((1689, 1707), 'rasa_nlu.tokenizers.Token', 'Token', (['word', 'start'], {}... |
from models import *
from utils import *
from tensorboard_logger import configure, log_value
import os
try:
os.makedirs('../train_logs')
except OSError:
pass
vgg19_exc = VGG19_extractor(torchvision.models.vgg19(pretrained=True))
vgg19_exc = vgg19_exc.cuda()
E1 = Encoder(n_res_blocks=10)
D1 = Decoder(n_res_bl... | [
"tensorboard_logger.log_value",
"os.makedirs"
] | [((113, 141), 'os.makedirs', 'os.makedirs', (['"""../train_logs"""'], {}), "('../train_logs')\n", (124, 141), False, 'import os\n'), ((4121, 4160), 'tensorboard_logger.log_value', 'log_value', (['"""L2_term"""', 'mean_L2_term', 'eph'], {}), "('L2_term', mean_L2_term, eph)\n", (4130, 4160), False, 'from tensorboard_logg... |
import torch
import math
class Node:
def __init__(self, state, probs, value, length, moves, terminal = False):
self.state = state
self.moves = torch.nonzero(moves)
self.P = probs[self.moves].view(-1)
self.P = self.P / self.P.sum()
self.value = value
self.length = len... | [
"torch.zeros",
"torch.argmax",
"torch.nonzero"
] | [((164, 184), 'torch.nonzero', 'torch.nonzero', (['moves'], {}), '(moves)\n', (177, 184), False, 'import torch\n'), ((402, 438), 'torch.zeros', 'torch.zeros', (['size'], {'dtype': 'torch.int32'}), '(size, dtype=torch.int32)\n', (413, 438), False, 'import torch\n'), ((458, 475), 'torch.zeros', 'torch.zeros', (['size'], ... |
# Third-party Libraries
from flask_restful import Resource, reqparse
import pyvo
from astropy.io.votable import parse
class Search(Resource):
def __init__(self) -> None:
super().__init__()
self.service = pyvo.dal.TAPService("http://voparis-tap-planeto.obspm.fr/tap")
def get(self, database):
... | [
"flask_restful.reqparse.RequestParser",
"pyvo.dal.TAPService"
] | [((226, 288), 'pyvo.dal.TAPService', 'pyvo.dal.TAPService', (['"""http://voparis-tap-planeto.obspm.fr/tap"""'], {}), "('http://voparis-tap-planeto.obspm.fr/tap')\n", (245, 288), False, 'import pyvo\n'), ((552, 576), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (574, 576), False, '... |
# -*- coding: utf-8 -*-
################################################################################
# | #
# | ______________________________________________________________ #
# | :~8a.`~888a:::::::::::::::88......88:::::::::... | [
"pysqlite2.dbapi2.connect",
"resources.lib.modules.control.makeFile",
"hashlib.md5",
"time.time"
] | [((5827, 5861), 'resources.lib.modules.control.makeFile', 'control.makeFile', (['control.dataPath'], {}), '(control.dataPath)\n', (5843, 5861), False, 'from resources.lib.modules import control\n'), ((5873, 5902), 'pysqlite2.dbapi2.connect', 'db.connect', (['control.cacheFile'], {}), '(control.cacheFile)\n', (5883, 590... |
import torch
from utils.model_utils import *
#Class conditional loglikelihood!
def elbo_recon(prediction,target):
error = (prediction - target).view(prediction.size(0), -1)
error = error ** 2
error = torch.sum(error, dim=-1)
return error
def calculate_ELBO(model,real_images):
with torch.no_grad():... | [
"torch.logsumexp",
"torch.stack",
"torch.cat",
"torch.no_grad",
"torch.sum",
"torch.log",
"torch.tensor"
] | [((213, 237), 'torch.sum', 'torch.sum', (['error'], {'dim': '(-1)'}), '(error, dim=-1)\n', (222, 237), False, 'import torch\n'), ((304, 319), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (317, 319), False, 'import torch\n'), ((728, 743), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (741, 743), False, 'imp... |
import pytest
from docs_src.async_constructor import main
@pytest.mark.anyio("asyncio")
async def test_async_constructor() -> None:
await main()
| [
"docs_src.async_constructor.main",
"pytest.mark.anyio"
] | [((62, 90), 'pytest.mark.anyio', 'pytest.mark.anyio', (['"""asyncio"""'], {}), "('asyncio')\n", (79, 90), False, 'import pytest\n'), ((145, 151), 'docs_src.async_constructor.main', 'main', ([], {}), '()\n', (149, 151), False, 'from docs_src.async_constructor import main\n')] |
from glob import glob
import cv2
import os
import sys
import yaml
import matplotlib as mpl
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from ellipses import LSqEllipse # The code is pulled from https://github.com/bdhammel/least-squares-ellipse-fitting
import time
# This annotation s... | [
"numpy.polyfit",
"numpy.argmax",
"numpy.argmin",
"matplotlib.pyplot.figure",
"yaml.safe_load",
"os.path.join",
"matplotlib.pyplot.close",
"os.path.exists",
"ellipses.LSqEllipse",
"matplotlib.pyplot.subplots",
"skimage.io.imread",
"matplotlib.pyplot.show",
"os.path.basename",
"numpy.float",... | [((1337, 1365), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (1353, 1365), False, 'import os\n'), ((8092, 8104), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8102, 8104), True, 'import matplotlib.pyplot as plt\n'), ((9034, 9045), 'sys.exit', 'sys.exit', (['(0)'], {}), ... |
import numpy as np
from VariableUnittest import VariableUnitTest
from gwlfe.Output.AvAnimalNSum import AnimalN
class TestAnimalN(VariableUnitTest):
def test_AnimalN(self):
z = self.z
np.testing.assert_array_almost_equal(
AnimalN.AnimalN_f(z.NYrs, z.NGPctManApp, z.GrazingAnimal_0, z.Nu... | [
"gwlfe.Output.AvAnimalNSum.AnimalN.AnimalN",
"gwlfe.Output.AvAnimalNSum.AnimalN.AnimalN_f"
] | [((256, 649), 'gwlfe.Output.AvAnimalNSum.AnimalN.AnimalN_f', 'AnimalN.AnimalN_f', (['z.NYrs', 'z.NGPctManApp', 'z.GrazingAnimal_0', 'z.NumAnimals', 'z.AvgAnimalWt', 'z.AnimalDailyN', 'z.NGAppNRate', 'z.Prec', 'z.DaysMonth', 'z.NGPctSoilIncRate', 'z.GRPctManApp', 'z.GRAppNRate', 'z.GRPctSoilIncRate', 'z.NGBarnNRate', 'z... |
import numpy as np
from math import log10
from math import sqrt
import time
import networkx as nx
import matplotlib.pyplot as plt
import pydot
import csv
class Graph(object):
def __init__(self):
self.root = None #root/source node is the start of the graph/tree and multicast source
self.nodes = []
... | [
"csv.writer",
"numpy.zeros",
"pydot.Dot",
"math.log10",
"pydot.Edge"
] | [((11302, 11331), 'pydot.Dot', 'pydot.Dot', ([], {'graph_type': '"""graph"""'}), "(graph_type='graph')\n", (11311, 11331), False, 'import pydot\n'), ((15441, 15472), 'numpy.zeros', 'np.zeros', (['(200, 200)'], {'dtype': '"""f"""'}), "((200, 200), dtype='f')\n", (15449, 15472), True, 'import numpy as np\n'), ((15965, 15... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ytu
def test_is_youtube():
tests = [
('http://youtu.be/zoLVUxKCWhY', True),
('http://www.youtube.com/watch?v=VvRC0wxM-yM', True),
('http://wwwwwwyoutube.com/watch?v=VvRC0wxM-yM', False),
('http://example.com/zoLVUxKCWhY', False)
... | [
"ytu.is_youtube",
"ytu.video_id"
] | [((362, 382), 'ytu.is_youtube', 'ytu.is_youtube', (['t[0]'], {}), '(t[0])\n', (376, 382), False, 'import ytu\n'), ((2048, 2066), 'ytu.video_id', 'ytu.video_id', (['t[0]'], {}), '(t[0])\n', (2060, 2066), False, 'import ytu\n')] |
import mock
import unittest
import dbt.adapters
import dbt.flags as flags
from pyhive import hive
from dbt.adapters.spark import SparkAdapter
import agate
from .utils import config_from_parts_or_dicts, inject_adapter
class TestSparkAdapter(unittest.TestCase):
def setUp(self):
flags.STRICT_MODE = True
... | [
"dbt.adapters.spark.SparkAdapter",
"mock.patch.object"
] | [((1673, 1693), 'dbt.adapters.spark.SparkAdapter', 'SparkAdapter', (['config'], {}), '(config)\n', (1685, 1693), False, 'from dbt.adapters.spark import SparkAdapter\n'), ((2400, 2420), 'dbt.adapters.spark.SparkAdapter', 'SparkAdapter', (['config'], {}), '(config)\n', (2412, 2420), False, 'from dbt.adapters.spark import... |
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
ShemaView = get_schema_view(
openapi.Info(
title='Multauth Example API',
default_version='v1',
description='Authentication flow: email, password and passcode (using Google Authenticator... | [
"drf_yasg.openapi.Info"
] | [((146, 333), 'drf_yasg.openapi.Info', 'openapi.Info', ([], {'title': '"""Multauth Example API"""', 'default_version': '"""v1"""', 'description': '"""Authentication flow: email, password and passcode (using Google Authenticator or similar app)"""'}), "(title='Multauth Example API', default_version='v1',\n descriptio... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 00:22:32 2020
@author: <NAME>
"""
import os
import copy
from typing import Union, Any
try:
import simplejson as json
except ImportError:
import json
from .plugins.base_file import BaseFilePlugin, _info
from .exceptions.file_exceptions impo... | [
"copy.deepcopy",
"os.path.exists",
"os.path.splitext",
"os.path.join",
"os.listdir"
] | [((2111, 2138), 'os.path.join', 'os.path.join', (['path', '"""index"""'], {}), "(path, 'index')\n", (2123, 2138), False, 'import os\n'), ((7278, 7297), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (7291, 7297), False, 'import copy\n'), ((1855, 1886), 'os.path.exists', 'os.path.exists', (['(file_name + ... |
#!/usr/bin/python3
# driver_trips.py: summarize miles per driver and show a list for each
# driver of the trips they took.
# Two approaches are demonstrated:
# - Two queries. First query retrieves the summary values, second the
# list entries. Print the list entries, preceding the list for each
# driver with the... | [
"cookbook.connect"
] | [((589, 607), 'cookbook.connect', 'cookbook.connect', ([], {}), '()\n', (605, 607), False, 'import cookbook\n')] |
# Generated by Django 3.1.6 on 2021-02-12 07:40
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Region',... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.PositiveIntegerField",
"django.db.models.AutoField",
"django.db.models.DecimalField",
"django.db.models.DateField"
] | [((365, 458), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (381, 458), False, 'from django.db import migrations, models\... |
from unicodedata import normalize
def normalizar(texto: str) -> str:
"""
Normalize um texto qualquer.
Substitui os caracteres especiais do texto.
Exemplo:
>>> normalizar(' AçúcAR ')
'acucar'
"""
texto = normalize('NFKD', texto)
texto = texto.encode('iso-8859-1', 'ignore').decode(... | [
"unicodedata.normalize"
] | [((239, 263), 'unicodedata.normalize', 'normalize', (['"""NFKD"""', 'texto'], {}), "('NFKD', texto)\n", (248, 263), False, 'from unicodedata import normalize\n')] |
import multiprocessing as mp
import itertools
QUEUE = mp.Queue()
class Routine(mp.Process):
def __init__(self, number: int, *args, **kwargs):
mp.Process.__init__(self, *args, **kwargs)
self.number = number
def target(self, number: int) -> int:
return 2 * number
def run(self):
result = self.target(s... | [
"multiprocessing.Process.__init__",
"multiprocessing.Queue"
] | [((56, 66), 'multiprocessing.Queue', 'mp.Queue', ([], {}), '()\n', (64, 66), True, 'import multiprocessing as mp\n'), ((150, 192), 'multiprocessing.Process.__init__', 'mp.Process.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (169, 192), True, 'import multiprocessing as mp\n')] |
import subprocess
import json
def main(set_path):
for (problem_id, line) in enumerate(open(set_path).readlines()):
if line.strip() == "":
continue
problem_id = problem_id + 1
submission_id, globalist_source_problem = line.split(' ')
globalist_source_problem = int(globa... | [
"json.dump",
"subprocess.run",
"fire.Fire"
] | [((869, 884), 'fire.Fire', 'fire.Fire', (['main'], {}), '(main)\n', (878, 884), False, 'import fire\n'), ((405, 538), 'subprocess.run', 'subprocess.run', (['f"""curl "https://icfpc.sx9.jp/submission?submission_id={submission_id}" > "tmp.txt\\""""'], {'shell': '(True)', 'check': '(True)'}), '(\n f\'curl "https://icfp... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
from functions_feat_extraction import image_to_features
from project_5_utils import stitch_together
def draw_labeled_bounding_boxes(img, labeled_frame, num_objects):
"""
Starting from labeled regions, draw enclosing rectangles in the original colo... | [
"cv2.rectangle",
"functions_feat_extraction.image_to_features",
"cv2.imshow",
"project_5_utils.stitch_together",
"numpy.copy",
"cv2.cvtColor",
"numpy.max",
"numpy.int",
"matplotlib.pyplot.subplots",
"cv2.resize",
"matplotlib.pyplot.show",
"cv2.waitKey",
"numpy.min",
"numpy.concatenate",
... | [((1030, 1068), 'numpy.zeros', 'np.zeros', ([], {'shape': '(h, w)', 'dtype': 'np.uint8'}), '(shape=(h, w), dtype=np.uint8)\n', (1038, 1068), True, 'import numpy as np\n'), ((1393, 1455), 'cv2.threshold', 'cv2.threshold', (['heatmap', 'threshold', '(255)'], {'type': 'cv2.THRESH_BINARY'}), '(heatmap, threshold, 255, type... |
import os
from mpl_toolkits import mplot3d
from matplotlib import cm
import matplotlib.pyplot as plt
import pandas as pd
def plot_3d(data, x, y, z):
ax = plt.axes(projection="3d")
ax.plot_trisurf(df[x], df[y], df[z], cmap=cm.Blues)
ax.set_xticks(df[x].values)
ax.set_yticks(df[y].values)
ax.set_xl... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.axes",
"pandas.read_csv",
"os.path.dirname",
"matplotlib.pyplot.figure"
] | [((160, 185), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (168, 185), True, 'import matplotlib.pyplot as plt\n'), ((446, 497), 'pandas.read_csv', 'pd.read_csv', (['"""../data/csv/calculation.csv"""'], {'sep': '""";"""'}), "('../data/csv/calculation.csv', sep=';')\n", (... |
from factory import Faker
from factory.django import DjangoModelFactory
class IntegerInputDefinitionFactory(DjangoModelFactory):
key = Faker("pystr", min_chars=3, max_chars=50)
required = Faker("pybool")
description = Faker("sentence")
min_value = Faker("pyint", min_value=-20, max_value=-10)
max_v... | [
"factory.Faker"
] | [((141, 182), 'factory.Faker', 'Faker', (['"""pystr"""'], {'min_chars': '(3)', 'max_chars': '(50)'}), "('pystr', min_chars=3, max_chars=50)\n", (146, 182), False, 'from factory import Faker\n'), ((198, 213), 'factory.Faker', 'Faker', (['"""pybool"""'], {}), "('pybool')\n", (203, 213), False, 'from factory import Faker\... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for changing internal_only property of a Bot."""
import logging
from google.appengine.api import taskqueue
from google.appeng... | [
"dashboard.common.stored_object.Get",
"google.appengine.api.taskqueue.add",
"dashboard.models.anomaly.Anomaly.GetAlertsForTest",
"dashboard.common.datastore_hooks.SetPrivilegedRequest",
"dashboard.common.utils.OldStyleTestKey",
"dashboard.models.graph_data.TestMetadata.query",
"logging.info",
"dashboa... | [((1456, 1492), 'logging.info', 'logging.info', (['"""MASTERS: %s"""', 'masters'], {}), "('MASTERS: %s', masters)\n", (1468, 1492), False, 'import logging\n'), ((2562, 2600), 'dashboard.common.datastore_hooks.SetPrivilegedRequest', 'datastore_hooks.SetPrivilegedRequest', ([], {}), '()\n', (2598, 2600), False, 'from das... |
import json
import ueimporter.version as version
def test_ueimporter_json_with_tag_will_succeed():
version_dict = {
'GitReleaseTag': '4.27.1-release'
}
assert version.UEImporterJson(
version_dict).git_release_tag == '4.27.1-release'
def test_ueimporter_json_without_key_will_yield_empty_... | [
"ueimporter.version.UEImporterJson",
"ueimporter.version.from_git_release_tag",
"ueimporter.version.from_build_version_json",
"json.dumps"
] | [((678, 714), 'ueimporter.version.UEImporterJson', 'version.UEImporterJson', (['version_dict'], {}), '(version_dict)\n', (700, 714), True, 'import ueimporter.version as version\n'), ((1638, 1714), 'json.dumps', 'json.dumps', (["{'MajorVersion': '4', 'MinorVersion': '27', 'PatchVersion': '1'}"], {}), "({'MajorVersion': ... |
####################
# ES-DOC CIM Questionnaire
# Copyright (c) 2015 ES-DOC. All rights reserved.
#
# University of Colorado, Boulder
# http://cires.colorado.edu/
#
# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].
####################
__author_... | [
"django.core.urlresolvers.reverse",
"Q.questionnaire.q_utils.FuzzyInt",
"ipdb.set_trace"
] | [((2621, 2637), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (2635, 2637), False, 'import ipdb\n'), ((2006, 2068), 'django.core.urlresolvers.reverse', 'reverse', (['"""project"""'], {'kwargs': "{'project_name': 'current_project'}"}), "('project', kwargs={'project_name': 'current_project'})\n", (2013, 2068), Fa... |
import argparse
import csv
def findCategory(status):
# Received state
if "Fingerprint Fee Was Received" in status:
return 1
elif "Expedite Request Denied" in status:
return 1
elif "Case Was Received" in status:
return 1
elif "Case Was Reopened" in status:
return 1
... | [
"csv.writer",
"csv.reader",
"argparse.ArgumentParser"
] | [((3411, 3436), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3434, 3436), False, 'import argparse\n'), ((3714, 3753), 'csv.reader', 'csv.reader', (['inputcsvfile'], {'delimiter': '""","""'}), "(inputcsvfile, delimiter=',')\n", (3724, 3753), False, 'import csv\n'), ((3774, 3853), 'csv.writer'... |
import json
import pandas as pd
import plotly.express as px
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from urllib.request import urlopen
app = dash.Dash(external_stylesheets=[dbc.t... | [
"json.load",
"dash.Dash",
"dash_core_components.DatePickerSingle",
"pandas.read_csv",
"dash_html_components.Div",
"urllib.request.urlopen",
"dash_core_components.RadioItems",
"dash_bootstrap_components.Button",
"dash.dependencies.Input",
"dash_html_components.P",
"dash_core_components.Graph",
... | [((283, 337), 'dash.Dash', 'dash.Dash', ([], {'external_stylesheets': '[dbc.themes.BOOTSTRAP]'}), '(external_stylesheets=[dbc.themes.BOOTSTRAP])\n', (292, 337), False, 'import dash\n'), ((763, 935), 'dash_core_components.RadioItems', 'dcc.RadioItems', ([], {'id': '"""datatype"""', 'options': "[{'label': 'Infection Rate... |
from __future__ import annotations
import threading
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from typing import Tuple, List
import random
from pyobs.object import Object
from pyobs.utils.enums import MotionStatus
class SimTelescope(Object):
"""A simulated telescope o... | [
"numpy.radians",
"threading.RLock",
"random.gauss",
"astropy.coordinates.SkyCoord",
"pyobs.object.Object.__init__",
"numpy.sqrt"
] | [((1494, 1532), 'pyobs.object.Object.__init__', 'Object.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (1509, 1532), False, 'from pyobs.object import Object\n'), ((2538, 2555), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (2553, 2555), False, 'import threading\n'), ((4115, 4153), 'astropy.c... |
# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from ip_proxies.spiders.base import BaseSpider
from ip_proxies.items import IpProxiesItem
from ip_proxies.settings import TEST_URLS, LOG_FILE
class JiangxianliSpider(BaseSpider):
name = 'jiangxianli'
# allowed_domains = ['jiangxian... | [
"random.choice",
"ip_proxies.settings.LOG_FILE.replace",
"ip_proxies.items.IpProxiesItem",
"scrapy.Request"
] | [((429, 473), 'ip_proxies.settings.LOG_FILE.replace', 'LOG_FILE.replace', (['"""log/"""', 'f"""log/{name}__"""', '(1)'], {}), "('log/', f'log/{name}__', 1)\n", (445, 473), False, 'from ip_proxies.settings import TEST_URLS, LOG_FILE\n'), ((819, 834), 'ip_proxies.items.IpProxiesItem', 'IpProxiesItem', ([], {}), '()\n', (... |
# coding: utf-8
"""
Main commands available for flatisfy.
"""
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import os
import flatisfy.filters
from flatisfy import database
from flatisfy import email
from flatisfy.models import flat as flat_model
from flatis... | [
"flatisfy.web.app.get_app",
"flatisfy.fetch.load_flats_from_db",
"flatisfy.filters.metadata.init",
"flatisfy.fetch.fetch_details",
"flatisfy.email.send_notification",
"collections.defaultdict",
"flatisfy.fetch.fetch_flats",
"os.utime",
"flatisfy.database.init_db",
"os.path.join",
"flatisfy.model... | [((584, 611), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (601, 611), False, 'import logging\n'), ((1237, 1279), 'flatisfy.filters.metadata.init', 'metadata.init', (['flats_list', 'constraint_name'], {}), '(flats_list, constraint_name)\n', (1250, 1279), False, 'from flatisfy.filters im... |
import uvicorn
from fastapi import FastAPI, Depends
from sqlalchemy.orm import declarative_base, sessionmaker
from fastapi_quickcrud import CrudMethods
from fastapi_quickcrud import crud_router_builder
from fastapi_quickcrud import sqlalchemy_to_pydantic
from fastapi_quickcrud.misc.memory_sql import sync_memory_db
ap... | [
"fastapi_quickcrud.sqlalchemy_to_pydantic",
"fastapi_quickcrud.crud_router_builder",
"sqlalchemy.ForeignKey",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.orm.relationship",
"uvicorn.run",
"fastapi.FastAPI",
"sqlalchemy.Column",
"fastapi.Depends",
"fastapi_quickcrud.misc.memory_sql.s... | [((324, 333), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (331, 333), False, 'from fastapi import FastAPI, Depends\n'), ((342, 360), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (358, 360), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((555, 573), 'sql... |
##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | [
"relstorage.tests.mock.Mock",
"relstorage.tests.MockCursor"
] | [((946, 958), 'relstorage.tests.MockCursor', 'MockCursor', ([], {}), '()\n', (956, 958), False, 'from relstorage.tests import MockCursor\n'), ((1529, 1541), 'relstorage.tests.MockCursor', 'MockCursor', ([], {}), '()\n', (1539, 1541), False, 'from relstorage.tests import MockCursor\n'), ((2404, 2416), 'relstorage.tests.... |
r"""
Definition
----------
The scattering intensity $I(q)$ is calculated as
.. math::
I(q) = \begin{cases}
A q^{-m1} + \text{background} & q <= q_c \\
C q^{-m2} + \text{background} & q > q_c
\end{cases}
where $q_c$ = the location of the crossover from one slope to the other,
$A$ = the scaling coeffi... | [
"numpy.empty",
"numpy.errstate",
"numpy.power"
] | [((2794, 2813), 'numpy.empty', 'empty', (['q.shape', '"""d"""'], {}), "(q.shape, 'd')\n", (2799, 2813), False, 'from numpy import inf, power, empty, errstate\n'), ((2852, 2877), 'numpy.errstate', 'errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (2860, 2877), False, 'from numpy import inf, power, emp... |
#!/usr/bin/env python
#
# manage.py 用于启动程序以及其他的程序任务
import os
# from flask import Flask
# from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from flask_debugtoolbar import DebugToolbarExtension
app.config.from_object(os.en... | [
"flask_script.Manager",
"flask_migrate.Migrate",
"flask_debugtoolbar.DebugToolbarExtension",
"app.app.config.from_object"
] | [((292, 342), 'app.app.config.from_object', 'app.config.from_object', (["os.environ['APP_SETTINGS']"], {}), "(os.environ['APP_SETTINGS'])\n", (314, 342), False, 'from app import app, db\n'), ((354, 370), 'flask_migrate.Migrate', 'Migrate', (['app', 'db'], {}), '(app, db)\n', (361, 370), False, 'from flask_migrate impor... |
import ShuntingYard_RE
import ThompsonConstruct
def runTests():
# List of ["Regular Expression", ["Strings"...]]
# (Infix Regular Expressions)
tests = [
["(a.b|b*)", ["", "ab", "b", "bb", "a"]],
["a.(b.b)*.a", ["aa", "bb", "abba", "aba"]],
["1.(0.0)*.1", ["11",... | [
"ThompsonConstruct.toNFA",
"ShuntingYard_RE.toPostfix"
] | [((533, 565), 'ShuntingYard_RE.toPostfix', 'ShuntingYard_RE.toPostfix', (['infix'], {}), '(infix)\n', (558, 565), False, 'import ShuntingYard_RE\n'), ((632, 664), 'ThompsonConstruct.toNFA', 'ThompsonConstruct.toNFA', (['postfix'], {}), '(postfix)\n', (655, 664), False, 'import ThompsonConstruct\n')] |
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
SCOPES = ['https://www.googleapis.com/auth/calendar.events',
'https://www.googleap... | [
"pickle.dump",
"google.auth.transport.requests.Request",
"os.path.exists",
"pickle.load",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file"
] | [((699, 725), 'os.path.exists', 'os.path.exists', (['token_path'], {}), '(token_path)\n', (713, 725), False, 'import os\n'), ((795, 813), 'pickle.load', 'pickle.load', (['token'], {}), '(token)\n', (806, 813), False, 'import pickle\n'), ((1061, 1121), 'google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file... |