code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#! /usr/bin/env python3
"""
Copyright 2021 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | [
"os.listdir",
"numpy.savez_compressed",
"os.makedirs",
"os.path.join",
"absl.app.run",
"absl.flags.DEFINE_boolean",
"absl.flags.mark_flag_as_required",
"os.path.isdir",
"sys.exit",
"yacos.info.ncc.Inst2Vec.remove_data_directory",
"yacos.info.ncc.Inst2Vec.extract",
"yacos.info.ncc.Inst2Vec.prep... | [((2962, 3029), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""dataset_directory"""', 'None', '"""Dataset directory"""'], {}), "('dataset_directory', None, 'Dataset directory')\n", (2981, 3029), False, 'from absl import app, flags, logging\n'), ((3082, 3147), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean... |
import strawberry
from pythonit_toolkit.api.extensions import SentryExtension
from users.admin_api.mutation import Mutation
from users.admin_api.query import Query
schema = strawberry.federation.Schema(
query=Query, mutation=Mutation, extensions=[SentryExtension]
)
| [
"strawberry.federation.Schema"
] | [((175, 270), 'strawberry.federation.Schema', 'strawberry.federation.Schema', ([], {'query': 'Query', 'mutation': 'Mutation', 'extensions': '[SentryExtension]'}), '(query=Query, mutation=Mutation, extensions=[\n SentryExtension])\n', (203, 270), False, 'import strawberry\n')] |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure
from numpy.random.mtrand import RandomState
from torch.utils.data import Dataset
def draw_samples(dataset: Dataset,
cols: int, rows: int,
width: float = 3, height: float = 3, fontsize: int = 8,
... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"numpy.random.RandomState"
] | [((556, 605), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(cols * width, rows * height)'}), '(figsize=(cols * width, rows * height))\n', (566, 605), True, 'import matplotlib.pyplot as plt\n'), ((415, 438), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (436, 438), True, 'import n... |
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session, session
from app.model.product import Product as ProductModel
from app.schema.product import ProductCreate, ProductUpdate, Product
def get_product(db: Session, product_id: int) -> ProductModel:
"""
Obtener un producto por Id
... | [
"fastapi.encoders.jsonable_encoder"
] | [((979, 1003), 'fastapi.encoders.jsonable_encoder', 'jsonable_encoder', (['db_ojb'], {}), '(db_ojb)\n', (995, 1003), False, 'from fastapi.encoders import jsonable_encoder\n')] |
from sklearn.svm import SVC
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import time
import argparse
import util
import numpy as np
import pandas as pd
def main(args):
X = pd.read_csv(args.data)
... | [
"sklearn.metrics.confusion_matrix",
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report",
"imblearn.over_sampling.SMOTE",
"numpy.array",
"time.time",
"sklearn.svm.SVC"
] | [((296, 318), 'pandas.read_csv', 'pd.read_csv', (['args.data'], {}), '(args.data)\n', (307, 318), True, 'import pandas as pd\n'), ((327, 351), 'pandas.read_csv', 'pd.read_csv', (['args.labels'], {}), '(args.labels)\n', (338, 351), True, 'import pandas as pd\n'), ((431, 468), 'sklearn.model_selection.train_test_split', ... |
#!/usr/bin/env python
#vim:fileencoding=UTF-8
import sys
import math
from numpy import histogram
if len(sys.argv) != 8:
print('Usage: SCRIPT [angle data] [polar data] [theta from] [theta to] [phi from] [phi to] [output prefix]')
print(' (theta and phi is in the unit of degree)')
sys.exit(2)
file_in... | [
"numpy.histogram",
"math.radians",
"sys.exit"
] | [((2015, 2048), 'numpy.histogram', 'histogram', (['theta'], {'bins': 'theta_bins'}), '(theta, bins=theta_bins)\n', (2024, 2048), False, 'from numpy import histogram\n'), ((2065, 2114), 'numpy.histogram', 'histogram', (['theta'], {'weights': 'weight', 'bins': 'theta_bins'}), '(theta, weights=weight, bins=theta_bins)\n',... |
import torch
from torch import nn
import torch.nn.functional as F
class BCEWithLogitsLossWithOHEM(nn.Module):
def __init__(self, ohem_ratio=1.0, pos_weight=None, eps=1e-7):
super(BCEWithLogitsLossWithOHEM, self).__init__()
self.criterion = nn.BCEWithLogitsLoss(reduction='none',
... | [
"torch.nn.BCEWithLogitsLoss",
"torch.no_grad",
"torch.nn.CrossEntropyLoss"
] | [((278, 339), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {'reduction': '"""none"""', 'pos_weight': 'pos_weight'}), "(reduction='none', pos_weight=pos_weight)\n", (298, 339), False, 'from torch import nn\n'), ((795, 810), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (808, 810), False, 'import torc... |
import glob, os
import sys
import urllib
from pathlib import Path
if __name__ == "__main__":
os.chdir(os.path.dirname(sys.argv[0]))
lecture_toc_md = []
lecture_root = "../lectures"
weeks = [week for week in os.listdir(lecture_root) if week.lower().startswith('week') and not week.lower().endswith('.md'... | [
"os.listdir",
"pathlib.Path",
"urllib.parse.quote",
"os.path.join",
"os.path.dirname"
] | [((107, 135), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (122, 135), False, 'import glob, os\n'), ((869, 907), 'os.path.join', 'os.path.join', (['lecture_root', 'week_title'], {}), '(lecture_root, week_title)\n', (881, 907), False, 'import glob, os\n'), ((1505, 1526), 'os.listdir', ... |
import os
import pytest
from deduplication.commands.search import search
from deduplication.tests.conftest import delete_output, mkdir_output, PROJECT_DIR, POTATOES_BASE_PATH, checkEqual
@pytest.mark.parametrize(
'tree_type, distance_metric, nearest_neighbors, leaf_size, parallel, batch_size, threshold, '
'... | [
"deduplication.commands.search.search",
"deduplication.tests.conftest.delete_output",
"deduplication.tests.conftest.checkEqual",
"os.path.join"
] | [((1078, 1239), 'deduplication.commands.search.search', 'search', (['df_dataset', 'output_path', 'tree_type', 'distance_metric', 'nearest_neighbors', 'leaf_size', 'parallel', 'batch_size', 'threshold', 'image_w', 'image_h', 'query', 'show'], {}), '(df_dataset, output_path, tree_type, distance_metric,\n nearest_neigh... |
import numpy as np
def skew(x: np.ndarray) -> np.ndarray:
"""
Args:
x: An array of shape (3,).
Returns:
The skew symmetric array of shape (3, 3).
"""
return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
| [
"numpy.array"
] | [((196, 260), 'numpy.array', 'np.array', (['[[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]'], {}), '([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])\n', (204, 260), True, 'import numpy as np\n')] |
import os
from argparse import ArgumentParser
from collections import defaultdict
from datetime import datetime
from typing import Tuple, Union
import dill
from flask import Flask, render_template, request
from form_model import InputFormNgram
from utils import generate_using_ngram_lm
LM_PATHS = {'ngram': 'ngram.lm.... | [
"flask.render_template",
"os.makedirs",
"flask.Flask",
"argparse.ArgumentParser",
"os.path.join",
"form_model.InputFormNgram",
"utils.generate_using_ngram_lm",
"datetime.datetime.now"
] | [((428, 443), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (433, 443), False, 'from flask import Flask, render_template, request\n'), ((668, 734), 'flask.render_template', 'render_template', (["(template_name + '.html')"], {'form': 'form', 'result': 'result'}), "(template_name + '.html', form=form, resul... |
import sys
import cv2
import numpy as np
import imutils
from imutils import paths
import argparse
class Orthomosaic:
def __init__(self, debug):
cv2.namedWindow("output", cv2.WINDOW_NORMAL)
self.no_raw_images = []
self.temp_image = []
self.final_image = []
self.debug = debug... | [
"cv2.resize",
"argparse.ArgumentParser",
"cv2.findHomography",
"numpy.float32",
"cv2.imshow",
"cv2.BFMatcher_create",
"numpy.array",
"cv2.ORB_create",
"cv2.destroyAllWindows",
"imutils.paths.list_images",
"numpy.concatenate",
"cv2.perspectiveTransform",
"cv2.waitKey",
"cv2.namedWindow",
... | [((158, 202), 'cv2.namedWindow', 'cv2.namedWindow', (['"""output"""', 'cv2.WINDOW_NORMAL'], {}), "('output', cv2.WINDOW_NORMAL)\n", (173, 202), False, 'import cv2\n'), ((381, 406), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (404, 406), False, 'import argparse\n'), ((2304, 2342), 'cv2.imshow... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from itsdangerous import TimestampSigner
import config
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
token_signer = TimestampSigner(config.SECRET_KEY)
from app.mod_auth.controller import mod_auth
from app.mod_bucketlists.... | [
"flask_sqlalchemy.SQLAlchemy",
"itsdangerous.TimestampSigner",
"flask.Flask"
] | [((127, 142), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (132, 142), False, 'from flask import Flask\n'), ((182, 197), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (192, 197), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((214, 248), 'itsdangerous.TimestampSigner', 'Ti... |
#!/usr/bin/env python3
import os, sys, re
menuentry_start = "menuentry"
def extract_menuentry(infile):
in_menuentry = False
for line in infile.readlines():
if in_menuentry:
if line.strip() == "}":
in_menuentry = False
print(line.rstrip())
pass
else:
print(line.rstri... | [
"os.environ.get",
"re.search"
] | [((446, 487), 're.search', 're.search', (['"""menuentry \'[^\']+\' (.*)"""', 'line'], {}), '("menuentry \'[^\']+\' (.*)", line)\n', (455, 487), False, 'import os, sys, re\n'), ((526, 577), 'os.environ.get', 'os.environ.get', (['"""GRUB_MENU_TITLE_ALT"""', '"""WCE Update"""'], {}), "('GRUB_MENU_TITLE_ALT', 'WCE Update')... |
import unittest
from random import Random
from typing import Sequence
from unittest import TestCase
from cogs.duel.DuelArena import DuelArena, DuelResult, DuelStatus
class AlwaysFirstRandom(Random):
def choice(self, seq: Sequence):
return seq[0]
class AlwaysSecondRandom(Random):
def choice(self, se... | [
"unittest.main"
] | [((3377, 3392), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3390, 3392), False, 'import unittest\n')] |
import csv
import oracles_headers
import os
from pymongo import MongoClient
cols = oracles_headers.oracles_columns
def output_headers(filename):
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
print("columns = {")
... | [
"csv.DictReader",
"os.path.isdir",
"os.mkdir",
"pymongo.MongoClient",
"csv.reader"
] | [((613, 626), 'pymongo.MongoClient', 'MongoClient', ([], {}), '()\n', (624, 626), False, 'from pymongo import MongoClient\n'), ((200, 249), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""\\""""'}), '(csvfile, delimiter=\',\', quotechar=\'"\')\n', (210, 249), False, 'import csv\n'), ... |
# -*- coding: utf-8 -*-
"""OSIRIS custom regions."""
import os
import argparse
import six
import glob
import subprocess
import astropy.units as u
from astropy.coordinates import SkyCoord, BaseCoordinateFrame, ICRS
from ...regions import Box, Circle, Region, Ruler, RegionFile
from .coords import OsirisInstrumentFrame
... | [
"argparse.FileType",
"argparse.ArgumentParser",
"subprocess.Popen",
"os.getcwd",
"os.path.abspath",
"six.text_type",
"glob.glob"
] | [((3570, 3587), 'glob.glob', 'glob.glob', (['impath'], {}), '(impath)\n', (3579, 3587), False, 'import glob\n'), ((4325, 4350), 'subprocess.Popen', 'subprocess.Popen', (['ds9args'], {}), '(ds9args)\n', (4341, 4350), False, 'import subprocess\n'), ((4432, 4532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([],... |
import unittest
from ParamSklearn.components.classification.multinomial_nb import \
MultinomialNB
from ParamSklearn.util import _test_classifier, _test_classifier_iterative_fit, \
get_dataset
import numpy as np
import sklearn.metrics
class MultinomialNBComponentTest(unittest.TestCase):
def test_default_... | [
"ParamSklearn.util.get_dataset",
"ParamSklearn.components.classification.multinomial_nb.MultinomialNB.get_hyperparameter_search_space",
"ParamSklearn.util._test_classifier_iterative_fit",
"ParamSklearn.util._test_classifier",
"numpy.nanmean",
"ParamSklearn.components.classification.multinomial_nb.Multinom... | [((1233, 1262), 'ParamSklearn.util.get_dataset', 'get_dataset', ([], {'dataset': '"""digits"""'}), "(dataset='digits')\n", (1244, 1262), False, 'from ParamSklearn.util import _test_classifier, _test_classifier_iterative_fit, get_dataset\n'), ((1431, 1478), 'ParamSklearn.components.classification.multinomial_nb.Multinom... |
## Copyright 2017 <NAME>
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, ... | [
"elasticsearch.Elasticsearch",
"csv.reader",
"argparse.ArgumentParser",
"sys.exit"
] | [((2984, 3091), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Python script to load a csv file into an index in elasticsearch"""'}), "(description=\n 'Python script to load a csv file into an index in elasticsearch')\n", (3007, 3091), False, 'import argparse\n'), ((1463, 1500), 'csv.... |
"""Tests for the serializers of the drf_auth app."""
from django.test import TestCase
from mixer.backend.django import mixer
from .. import serializers
class LoginSerializerTestCase(TestCase):
longMessage = True
def test_serializer(self):
user = mixer.blend('auth.User')
user.set_password('<... | [
"mixer.backend.django.mixer.blend"
] | [((267, 291), 'mixer.backend.django.mixer.blend', 'mixer.blend', (['"""auth.User"""'], {}), "('auth.User')\n", (278, 291), False, 'from mixer.backend.django import mixer\n'), ((1206, 1230), 'mixer.backend.django.mixer.blend', 'mixer.blend', (['"""auth.User"""'], {}), "('auth.User')\n", (1217, 1230), False, 'from mixer.... |
# importing the requests library
import requests
import json
access_token = None
def get_auth_header():
global access_token
header = {}
if not access_token:
access_token = get_access_token()
header["accept"] = "application/json"
header["Authorization"] = "{} {}".format(access_token["to... | [
"json.loads",
"requests.post"
] | [((603, 639), 'requests.post', 'requests.post', ([], {'url': 'url', 'data': 'payload'}), '(url=url, data=payload)\n', (616, 639), False, 'import requests\n'), ((656, 676), 'json.loads', 'json.loads', (['res.text'], {}), '(res.text)\n', (666, 676), False, 'import json\n'), ((996, 1016), 'json.loads', 'json.loads', (['re... |
"""Site config validation functionality to supplement the features that the schema gives us"""
from collections import defaultdict
from mitol.common.utils import first_or_none, partition_to_lists
from yamale import YamaleError
from yamale.schema.validationresults import ValidationResult
from websites.constants import... | [
"yamale.YamaleError",
"mitol.common.utils.partition_to_lists",
"mitol.common.utils.first_or_none",
"collections.defaultdict",
"websites.site_config_api.SiteConfig",
"yamale.schema.validationresults.ValidationResult"
] | [((2555, 2572), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2566, 2572), False, 'from collections import defaultdict\n'), ((3577, 3593), 'websites.site_config_api.SiteConfig', 'SiteConfig', (['data'], {}), '(data)\n', (3587, 3593), False, 'from websites.site_config_api import SiteConfig\n'), ... |
import cv2
# reading the image
image = cv2.imread(filename=r'.\img\Resized.jpg')
cv2.putText(image,"Bhanu",org=(100,300),fontFace=cv2.FONT_ITALIC,fontScale=4,color=(3,5,23),thickness=2,lineType=3)
cv2.putText(image,"Deepak",org=(00,100),fontFace=cv2.FONT_ITALIC,fontScale=4,color=(3,5,23),thickness=2,lineType=3)
# disp... | [
"cv2.imwrite",
"cv2.waitKeyEx",
"cv2.imshow",
"cv2.putText",
"cv2.destroyAllWindows",
"cv2.imread"
] | [((40, 82), 'cv2.imread', 'cv2.imread', ([], {'filename': '""".\\\\img\\\\Resized.jpg"""'}), "(filename='.\\\\img\\\\Resized.jpg')\n", (50, 82), False, 'import cv2\n'), ((82, 211), 'cv2.putText', 'cv2.putText', (['image', '"""Bhanu"""'], {'org': '(100, 300)', 'fontFace': 'cv2.FONT_ITALIC', 'fontScale': '(4)', 'color': ... |
import pandas as pd
import numpy as np
# County / Unitary Authorities Apr-2021
# NOMIS API - Population estimates - local authority based by five year age band
url = "https://www.nomisweb.co.uk/api/v01/dataset/NM_31_1.data.csv?geography=1807745025...1807745028,1807745030...1807745032,1807745034...1807745083,180774508... | [
"numpy.where",
"pandas.merge",
"pandas.DataFrame",
"pandas.read_csv"
] | [((800, 816), 'pandas.read_csv', 'pd.read_csv', (['url'], {}), '(url)\n', (811, 816), True, 'import pandas as pd\n'), ((2121, 2137), 'pandas.read_csv', 'pd.read_csv', (['url'], {}), '(url)\n', (2132, 2137), True, 'import pandas as pd\n'), ((3310, 3326), 'pandas.read_csv', 'pd.read_csv', (['url'], {}), '(url)\n', (3321,... |
#-*-coding:utf8-*-#
import os
from cv2 import cv2
from PIL import Image,ImageDraw
from datetime import datetime
import time
import tensorflow as tf
import numpy as np
import gender_train_data as train_data
from gender_train_data import labels_text
import matplotlib.pyplot as plt
# 人脸检测
class DetectFaces():
def _... | [
"tensorflow.transpose",
"numpy.array",
"PIL.ImageDraw.Draw",
"numpy.reshape",
"tensorflow.Session",
"cv2.cv2.resize",
"os.mkdir",
"cv2.cv2.cvtColor",
"tensorflow.get_default_graph",
"numpy.argmax",
"tensorflow.train.import_meta_graph",
"tensorflow.train.latest_checkpoint",
"matplotlib.pyplot... | [((8159, 8173), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8171, 8173), False, 'from datetime import datetime\n'), ((8264, 8278), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8276, 8278), False, 'from datetime import datetime\n'), ((576, 598), 'cv2.cv2.imread', 'cv2.imread', (['image_nam... |
"""
2018/03/10
目覚まし機能の改善のためのplayerControllerの作り直し
- オブジェクト指向の記述
- 分単位での時刻設定の実現
"""
import subprocess
import datetime
import sys
import RPi.GPIO as GPIO
import loader
# 制御用スイッチの番号
SWITCH = 27
def initialize():
# 準備を始める前に,スイッチが入っているかチェック
# gpio初期化
GPIO.setmode(GPIO.BCM)
GPIO.setup(SWI... | [
"loader.Loader",
"RPi.GPIO.setup",
"datetime.datetime.now",
"RPi.GPIO.input",
"subprocess.call",
"sys.exit",
"RPi.GPIO.setmode"
] | [((279, 301), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (291, 301), True, 'import RPi.GPIO as GPIO\n'), ((306, 333), 'RPi.GPIO.setup', 'GPIO.setup', (['SWITCH', 'GPIO.IN'], {}), '(SWITCH, GPIO.IN)\n', (316, 333), True, 'import RPi.GPIO as GPIO\n'), ((692, 715), 'datetime.datetime.now', 'da... |
"""
albert-base
wrapped_train_step w/ 32bsz, 1acc: 3.13 it/s; 3.51 it/s
wrapped train_step w/ skipping loss/acc allreduce: ? it/s, 3.54 it/s
wrapped train_step w/ skipping xla: ? it/s, 1.50 it/s
wrapped train_batch & wrapped_allreduce: 2.99 it/s, 3.42 it/s
Max per-GPU batch size (albert):
base:
- 512seq: 32 on p3dn w/... | [
"logging.getLogger",
"logging.StreamHandler",
"tensorflow.reduce_sum",
"horovod.tensorflow.init",
"tensorflow.norm",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.GradientTape",
"tensorflow.config.list_physical_devices",
"tensorflow.io.FixedLenFeature",
"transformers.TFAlbe... | [((1562, 1589), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1579, 1589), False, 'import logging\n'), ((2023, 2065), 'tensorflow.reshape', 'tf.reshape', (['(positions + flat_offsets)', '[-1]'], {}), '(positions + flat_offsets, [-1])\n', (2033, 2065), True, 'import tensorflow as tf\n'),... |
# Copyright 2017 Workonline Communications (Pty) Ltd. All rights reserved.
#
# The contents of this file are 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/LIC... | [
"djangolg.forms.form_factory",
"djangolg.views.helpers.get_src",
"djangolg.keys.AuthKey",
"django.http.JsonResponse",
"djangolg.exceptions.check_type",
"djangolg.methods.get_method",
"djangolg.exceptions.default_error_message",
"djangolg.lg.LookingGlass",
"djangolg.models.Log",
"djangolg.models.Lo... | [((2120, 2182), 'djangolg.exceptions.check_type', 'exceptions.check_type', ([], {'instance': 'request', 'classinfo': 'HttpRequest'}), '(instance=request, classinfo=HttpRequest)\n', (2141, 2182), False, 'from djangolg import events, exceptions, forms, keys, methods, models, settings\n'), ((3456, 3492), 'djangolg.methods... |
from flask import Blueprint
from .utils import singleton
mdict = Blueprint(
'mdict', __name__,
static_folder='static', template_folder='templates')
@singleton
class Config():
pass
def init_app(app):
Config.MDICT_DIR = app.config.get('MDICT_DIR')
Config.MDICT_CACHE = app.config.get('MDICT_CAC... | [
"flask.Blueprint"
] | [((69, 155), 'flask.Blueprint', 'Blueprint', (['"""mdict"""', '__name__'], {'static_folder': '"""static"""', 'template_folder': '"""templates"""'}), "('mdict', __name__, static_folder='static', template_folder=\n 'templates')\n", (78, 155), False, 'from flask import Blueprint\n')] |
# pylint: disable=no-self-use,protected-access
from unittest import TestCase, skip
from testfixtures import compare, StringComparison
from service.ws_re.register.authors import Authors
from service.ws_re.register.register_types.volume import VolumeRegister
from service.ws_re.register.test_base import BaseTestRegister... | [
"service.ws_re.register.test_base._TEST_REGISTER_PATH.joinpath",
"service.ws_re.register.register_types.volume.VolumeRegister.normalize_sort_key",
"testfixtures.StringComparison",
"testfixtures.compare",
"service.ws_re.volumes.Volumes",
"service.ws_re.register.test_base.copy_tst_data",
"unittest.skip",
... | [((5678, 5703), 'unittest.skip', 'skip', (['"""only for analysis"""'], {}), "('only for analysis')\n", (5682, 5703), False, 'from unittest import TestCase, skip\n'), ((478, 510), 'service.ws_re.register.test_base.copy_tst_data', 'copy_tst_data', (['"""I_1_base"""', '"""I_1"""'], {}), "('I_1_base', 'I_1')\n", (491, 510)... |
from flask import Flask
from flask import jsonify
import pandas as pd
import markdown
import requests
import os
app = Flask(__name__)
@app.route("/")
def index():
with open(os.path.dirname(app.root_path) + '/README.md','r') as markdown_file:
content = markdown_file.read()
return markdown.markdown... | [
"os.path.dirname",
"markdown.markdown",
"pandas.read_csv",
"flask.Flask"
] | [((120, 135), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (125, 135), False, 'from flask import Flask\n'), ((372, 473), 'pandas.read_csv', 'pd.read_csv', (['"""https://raw.githubusercontent.com/nychealth/coronavirus-data/master/boro.csv"""'], {}), "(\n 'https://raw.githubusercontent.com/nychealth/cor... |
# -*- coding: utf-8 -*-
"""
LoggedFS-python
Filesystem monitoring with Fuse and Python
https://github.com/pleiszenburg/loggedfs-python
setup.py: Used for package distribution
Copyright (C) 2017-2020 <NAME> <<EMAIL>>
<LICENSE_BLOCK>
The contents of this file are subject to the Apache License
Version 2 ("License")... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((2309, 2329), 'setuptools.find_packages', 'find_packages', (['"""src"""'], {}), "('src')\n", (2322, 2329), False, 'from setuptools import find_packages, setup\n'), ((1661, 1686), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1676, 1686), False, 'import os\n')] |
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as scs
from scipy.optimize import minimize
class DistrManager:
def __init__(
self, left_border: int = -1.8, right_border: int = 2, step: int = 0.2
) -> None:
self._left_border = left_border
... | [
"numpy.mean",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.legend",
"scipy.optimize.minimize",
"matplotlib.pyplot.plot",
"scipy.stats.norm.rvs",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((441, 501), 'numpy.arange', 'np.arange', (['self._left_border', 'self._right_border', 'self._step'], {}), '(self._left_border, self._right_border, self._step)\n', (450, 501), True, 'import numpy as np\n'), ((1683, 1758), 'scipy.optimize.minimize', 'minimize', (['self._minimize_mnm', '[beta_0, beta_1]'], {'args': '(x,... |
import os
import cv2
# 读取图像,然后将人脸识别并裁剪出来, 参考https://blog.csdn.net/wangkun1340378/article/details/72457975
def clip_image(input_dir, output_dir,size1):
images = os.listdir(input_dir)
for imagename in images:
imagepath = os.path.join(input_dir , imagename)
img = cv2.imread(imagepath)
... | [
"os.path.exists",
"cv2.imwrite",
"os.listdir",
"os.makedirs",
"os.path.join",
"cv2.CascadeClassifier",
"cv2.resize",
"cv2.imread"
] | [((171, 192), 'os.listdir', 'os.listdir', (['input_dir'], {}), '(input_dir)\n', (181, 192), False, 'import os\n'), ((247, 281), 'os.path.join', 'os.path.join', (['input_dir', 'imagename'], {}), '(input_dir, imagename)\n', (259, 281), False, 'import os\n'), ((298, 319), 'cv2.imread', 'cv2.imread', (['imagepath'], {}), '... |
"""twitterclone URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... | [
"django.urls.path"
] | [((1048, 1083), 'django.urls.path', 'path', (['""""""', 'landing_view'], {'name': '"""home"""'}), "('', landing_view, name='home')\n", (1052, 1083), False, 'from django.urls import path\n'), ((1089, 1127), 'django.urls.path', 'path', (['"""user/<int:user_id>/"""', 'user_view'], {}), "('user/<int:user_id>/', user_view)\... |
#!/usr/local/bin/python3
from PIL import Image
import sys, getopt
USAGE = 'USAGE:\n./image_encoding.py -d <image_file> # for decoding\n./image_encoding.py -e <text_file> <image_file> # for encoding'
ENCODING_BIT_COUNT = 2 # number of the least significant bits that will be used to encode the message
BIT_COUNT = 8 # nu... | [
"getopt.getopt",
"PIL.Image.open",
"sys.exit"
] | [((1489, 1511), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (1499, 1511), False, 'from PIL import Image\n'), ((2123, 2145), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (2133, 2145), False, 'from PIL import Image\n'), ((2858, 2868), 'sys.exit', 'sys.exit', ([], {})... |
#! /usr/local/bin
import fmri
# --
# Gen the data
# Run 1
#fmri.catreward.roi.exps.main.run_all('box_c', 'CatMean', 'get_trials_combined')
#fmri.catreward.roi.exps.main.run_all('box_s', 'CatMean', 'get_trials')
#fmri.catreward.roi.exps.main.run_all('nobox_c', 'Nobox', 'get_trials_combined')
#fmri.catreward.roi.exps.ma... | [
"fmri.catreward.roi.exps.main.run_all"
] | [((374, 451), 'fmri.catreward.roi.exps.main.run_all', 'fmri.catreward.roi.exps.main.run_all', (['"""box_s_fir"""', '"""CatMeanFir"""', '"""get_trials"""'], {}), "('box_s_fir', 'CatMeanFir', 'get_trials')\n", (410, 451), False, 'import fmri\n'), ((452, 543), 'fmri.catreward.roi.exps.main.run_all', 'fmri.catreward.roi.ex... |
# coding: utf-8
# Copyright (c) Alliance for Sustainable Energy, LLC
# Distributed under the terms of the Apache License, Version 2.0
from __future__ import division, unicode_literals
__author__ = "<NAME>, Ph.D."
__copyright__ = "Copyright 2015, Alliance for Sustainable Energy, LLC"
__version__ = "0.3.4"
__email__ = ... | [
"logging.getLogger",
"streamm.structures.dihedral.Dihedral",
"unittest.main"
] | [((418, 445), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (435, 445), False, 'import logging\n'), ((1613, 1628), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1626, 1628), False, 'import unittest\n'), ((658, 687), 'streamm.structures.dihedral.Dihedral', 'dihedral.Dihedral', (['(... |
__author__ = 'mpetyx'
from django.contrib.auth.models import User
from django.db import models
class Value(models.Model):
timestamp = models.DateField(auto_now_add=True)
metric = models.TextField()
class Buffer(models.Model):
description = models.TextField()
refresh_rate = models.FloatField()
cre... | [
"django.db.models.OneToOneField",
"django.db.models.FloatField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField"
] | [((140, 175), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (156, 175), False, 'from django.db import models\n'), ((189, 207), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (205, 207), False, 'from django.db import models\n'), ((255, 2... |
from xdoctest import checker
from xdoctest import directive
# from xdoctest import utils
def test_visible_lines():
"""
pytest testing/test_checker.py
"""
got = 'this is invisible\ronly this is visible'
print(got)
want = 'only this is visible'
assert checker.check_output(got, want)
def te... | [
"xdoctest.checker.check_output",
"xdoctest.directive.RuntimeState"
] | [((280, 311), 'xdoctest.checker.check_output', 'checker.check_output', (['got', 'want'], {}), '(got, want)\n', (300, 311), False, 'from xdoctest import checker\n'), ((572, 603), 'xdoctest.checker.check_output', 'checker.check_output', (['got', 'want'], {}), '(got, want)\n', (592, 603), False, 'from xdoctest import chec... |
from django.db import DEFAULT_DB_ALIAS
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--database', default=DEFAULT_DB_ALIAS,
help='Name of databas... | [
"django.core.management.call_command"
] | [((1201, 1390), 'django.core.management.call_command', 'call_command', (['"""migrate"""'], {'app_label': 'app', 'migration_name': 'name', 'database': "options['database']", 'plan': "options['plan']", 'interactive': "options['interactive']", 'verbosity': "options['verbosity']"}), "('migrate', app_label=app, migration_na... |
from collections import defaultdict
from functools import partial
from flask import Blueprint, request, jsonify, make_response, url_for
from flask.views import MethodView
from marshmallow import ValidationError
import pandas as pd
from solarforecastarbiter.utils import compute_aggregate
from sfa_api import spec
fro... | [
"sfa_api.utils.errors.BadAPIRequest",
"sfa_api.schema.ForecastSchema",
"sfa_api.schema.AggregateValuesSchema",
"sfa_api.utils.storage.get_storage",
"flask.jsonify",
"sfa_api.schema.AggregateUpdateSchema",
"sfa_api.utils.request_handling.validate_start_end",
"sfa_api.schema.AggregateSchema",
"sfa_api... | [((16748, 16923), 'sfa_api.spec.components.parameter', 'spec.components.parameter', (['"""aggregate_id"""', '"""path"""', '{\'schema\': {\'type\': \'string\', \'format\': \'uuid\'}, \'description\':\n "Resource\'s unique identifier.", \'required\': \'true\'}'], {}), '(\'aggregate_id\', \'path\', {\'schema\': {\'type... |
__author__ = 'alsherman'
import pandas as pd
import csv
import logging
logger = logging.getLogger(__name__)
class DataframeCreator:
""" Restructures and converts data from many formats (txt, zip, url, ...) into a pandas dataframe """
def __init__(self, source_metadata, sep=',', txt_helper=None, columns=No... | [
"logging.getLogger",
"logging.config.fileConfig",
"pandas.DataFrame",
"pandas.read_csv"
] | [((83, 110), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (100, 110), False, 'import logging\n'), ((2758, 2807), 'logging.config.fileConfig', 'logging.config.fileConfig', (['"""Logging/logging.conf"""'], {}), "('Logging/logging.conf')\n", (2783, 2807), False, 'import logging\n'), ((1331... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import operator
import numpy as np
from zarr.compat import integer_types, PY2, reduce
def normalize_shape(shape):
"""Convenience function to normalize the `shape` argument."""
if shape is None:
raise TypeErro... | [
"numpy.product",
"numpy.ceil",
"numpy.log10",
"zarr.compat.reduce",
"numpy.array"
] | [((1165, 1193), 'numpy.array', 'np.array', (['shape'], {'dtype': '"""=f8"""'}), "(shape, dtype='=f8')\n", (1173, 1193), True, 'import numpy as np\n'), ((1319, 1337), 'numpy.product', 'np.product', (['chunks'], {}), '(chunks)\n', (1329, 1337), True, 'import numpy as np\n'), ((2178, 2212), 'numpy.ceil', 'np.ceil', (['(ch... |
from django.utils import timezone, translation
class TimezoneMiddleware():
def process_request(self, request):
if request.user.is_authenticated():
timezone.activate(request.user.timezone)
else:
timezone.deactivate()
class LanguageMiddleware():
def process_request(self,... | [
"django.utils.timezone.activate",
"django.utils.translation.activate",
"django.utils.timezone.deactivate"
] | [((173, 213), 'django.utils.timezone.activate', 'timezone.activate', (['request.user.timezone'], {}), '(request.user.timezone)\n', (190, 213), False, 'from django.utils import timezone, translation\n'), ((240, 261), 'django.utils.timezone.deactivate', 'timezone.deactivate', ([], {}), '()\n', (259, 261), False, 'from dj... |
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from twilio.base.exceptions import TwilioRestException
from ohq.models import Course, Semester
from ohq.sms import sendSMS, sendSMSVerification, sendUpNextNotification
User = get_user_model()
class send... | [
"django.contrib.auth.get_user_model",
"ohq.sms.sendUpNextNotification",
"ohq.models.Course.objects.create",
"ohq.sms.sendSMSVerification",
"twilio.base.exceptions.TwilioRestException",
"ohq.sms.sendSMS",
"unittest.mock.patch",
"ohq.models.Semester.objects.create"
] | [((291, 307), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (305, 307), False, 'from django.contrib.auth import get_user_model\n'), ((348, 380), 'unittest.mock.patch', 'patch', (['"""ohq.sms.capture_message"""'], {}), "('ohq.sms.capture_message')\n", (353, 380), False, 'from unittest.mock im... |
# Copyright 2020 (c) Cognizant Digital Business, Evolutionary AI. All rights reserved. Issued under the Apache 2.0 License.
import numpy as np
np.show_config()
| [
"numpy.show_config"
] | [((144, 160), 'numpy.show_config', 'np.show_config', ([], {}), '()\n', (158, 160), True, 'import numpy as np\n')] |
import base64
import json
class Valve_Reistance( object ):
def __init__( self, render_template, redis_handle, app_files):
self.render_template = render_template
self.redis_handle = redis_handle
self.app_files = app_files
self.history = 14
... | [
"json.loads",
"base64.b64decode"
] | [((1426, 1457), 'base64.b64decode', 'base64.b64decode', (['base64_object'], {}), '(base64_object)\n', (1442, 1457), False, 'import base64\n'), ((2776, 2802), 'json.loads', 'json.loads', (['temp_data_json'], {}), '(temp_data_json)\n', (2786, 2802), False, 'import json\n'), ((3088, 3117), 'json.loads', 'json.loads', (['l... |
import config
from database import RedditOutfitsDatabase
from util_reddit import generate_thread_ids
'''
This script is ran according to Malefashionadvice's, Femalefashionadvice's, and Streetwear's weekly thread(s) schedules.
'''
def process_threads(thread_ids: list, database):
'''
Given a list of threads ID... | [
"database.RedditOutfitsDatabase",
"util_reddit.generate_thread_ids"
] | [((442, 534), 'database.RedditOutfitsDatabase', 'RedditOutfitsDatabase', (['"""reddit_outfits"""', '"""redditoutfits"""', 'config.redditoutfits_password'], {}), "('reddit_outfits', 'redditoutfits', config.\n redditoutfits_password)\n", (463, 534), False, 'from database import RedditOutfitsDatabase\n'), ((659, 725), ... |
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from time import time
import logging
from hcache import cached
from limix_math.linalg import sum2diag
from numpy import set_printoptions
from numpy import argmin
from numpy import zeros
from numpy import ... | [
"logging.getLogger",
"numpy.array",
"numpy.zeros",
"time.time",
"numpy.set_printoptions"
] | [((908, 935), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (925, 935), False, 'import logging\n'), ((3253, 3280), 'numpy.array', 'array', (['self._real_variances'], {}), '(self._real_variances)\n', (3258, 3280), False, 'from numpy import array\n'), ((4058, 4064), 'time.time', 'time', ([... |
# import pandas, numpy, and matplotlib
import pandas as pd
from feature_engine.encoding import OneHotEncoder
from category_encoders.hashing import HashingEncoder
from sklearn.model_selection import train_test_split
pd.set_option('display.width', 200)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_r... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"feature_engine.encoding.OneHotEncoder",
"category_encoders.hashing.HashingEncoder",
"pandas.set_option"
] | [((215, 250), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(200)'], {}), "('display.width', 200)\n", (228, 250), True, 'import pandas as pd\n'), ((251, 291), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(20)'], {}), "('display.max_columns', 20)\n", (264, 291), True, 'import p... |
#-----------------------------------------------------------------------------
# press-stitch.py
# Merges the three Press Switch games together
# pylint: disable=bad-indentation
#-----------------------------------------------------------------------------
import getopt
import hashlib
import os.path
import pathlib
imp... | [
"rpp.RenPyFileEliza",
"getopt.getopt",
"rpp.RenPyFileCiel",
"rpp.RenPyIf",
"hashlib.md5",
"zipfile.ZipFile",
"rpp.RenPyBlock",
"pathlib.Path",
"rpp.RenPyFileGoopy",
"copy.deepcopy",
"shutil.rmtree",
"rpp.RenPyFile",
"shutil.copy",
"sys.exit",
"press_stitch_archive.unpackArchive",
"csv.... | [((9798, 9809), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (9806, 9809), False, 'import sys\n'), ((9942, 9955), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (9953, 9955), False, 'import hashlib\n'), ((12145, 12174), 'shutil.copy', 'shutil.copy', (['srcFile', 'dstPath'], {}), '(srcFile, dstPath)\n', (12156, 1217... |
# change from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_model.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class double_conv(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.co... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Upsample",
"torchsummary.summary",
"torch.nn.ConvTranspose2d",
"torch.cat"
] | [((2686, 2715), 'torchsummary.summary', 'summary', (['model', '(3, 224, 224)'], {}), '(model, (3, 224, 224))\n', (2693, 2715), False, 'from torchsummary import summary\n'), ((1583, 1609), 'torch.cat', 'torch.cat', (['[x2, x1]'], {'dim': '(1)'}), '([x2, x1], dim=1)\n', (1592, 1609), False, 'import torch\n'), ((2220, 224... |
import oci
import time
from Modules.Classes import *
WaitRefresh = 10
def SubscribedRegions(config, auth):
regions = []
identity = oci.identity.IdentityClient(config, signer=auth)
regionDetails = identity.list_region_subscriptions(tenancy_id=config["tenancy"]).data
# Add subscribed regions to list
... | [
"oci.pagination.list_call_get_all_results",
"oci.identity.IdentityClient",
"time.sleep"
] | [((143, 191), 'oci.identity.IdentityClient', 'oci.identity.IdentityClient', (['config'], {'signer': 'auth'}), '(config, signer=auth)\n', (170, 191), False, 'import oci\n'), ((1165, 1213), 'oci.identity.IdentityClient', 'oci.identity.IdentityClient', (['config'], {'signer': 'auth'}), '(config, signer=auth)\n', (1192, 12... |
import numpy
from matplotlib import pyplot
def forward_difference(f, x0, h):
return (f(x0+h) - f(x0)) / h
def backward_difference(f, x0, h):
return (f(x0) - f(x0-h)) / h
def central_difference(f, x0, h):
return (f(x0+h) - f(x0-h)) / (2*h)
def euler(f, x_end, y0, N):
x, dx = numpy.linspace(0, x_end, N+... | [
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.cos",
"numpy.sin",
"numpy.zeros_like",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((293, 338), 'numpy.linspace', 'numpy.linspace', (['(0)', 'x_end', '(N + 1)'], {'retstep': '(True)'}), '(0, x_end, N + 1, retstep=True)\n', (307, 338), False, 'import numpy\n'), ((1152, 1175), 'numpy.zeros_like', 'numpy.zeros_like', (['h_all'], {}), '(h_all)\n', (1168, 1175), False, 'import numpy\n'), ((1198, 1221), '... |
from flask import Blueprint
from src.services.auth_service import auth
ping = Blueprint('ping', __name__)
@ping.route('/', methods=['GET'])
@ping.route('/ping', methods=['GET'])
def hello_world():
"""
Monitor endpoint
---
tags:
- ping
responses:
200:
description: Hello, world... | [
"flask.Blueprint"
] | [((80, 107), 'flask.Blueprint', 'Blueprint', (['"""ping"""', '__name__'], {}), "('ping', __name__)\n", (89, 107), False, 'from flask import Blueprint\n')] |
"""Tools for running :obj:`Flow` and :obj:`Job` objects using the Myqueue package.
Notes
-----
Myqueue heavily relies on the file system. To submit a workflow, one has to run:
mq workflow workflow.py DIRECTORY_PATTERNS
where workflow.py is a python script defining one workflow. For jobflow Flows, the
workflow.py file ... | [
"os.path.exists",
"datetime.datetime.utcnow",
"pathlib.Path.cwd",
"maggma.stores.JSONStore",
"os.path.join",
"monty.os.cd",
"jobflow.core.flow.get_flow",
"json.load",
"random.randint",
"json.dump"
] | [((1288, 1302), 'jobflow.core.flow.get_flow', 'get_flow', (['flow'], {}), '(flow)\n', (1296, 1302), False, 'from jobflow.core.flow import get_flow\n'), ((1585, 1595), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (1593, 1595), False, 'from pathlib import Path\n'), ((1943, 1981), 'os.path.join', 'os.path.join', (['r... |
import os
import argparse
from e2e_EL_evaluate.utils.write_xml import write_xml
from e2e_EL_evaluate.utils.check_xml_anno import check_xml_anno
from e2e_EL_evaluate.utils.gen_anno_from_xml import gen_anno_from_xml
def main(args):
assert os.path.isdir(args.input_dir)
os.makedirs(args.output_dir, exist_ok=True... | [
"argparse.ArgumentParser",
"os.makedirs",
"e2e_EL_evaluate.utils.gen_anno_from_xml.gen_anno_from_xml",
"e2e_EL_evaluate.utils.write_xml.write_xml",
"os.path.isdir",
"e2e_EL_evaluate.utils.check_xml_anno.check_xml_anno"
] | [((244, 273), 'os.path.isdir', 'os.path.isdir', (['args.input_dir'], {}), '(args.input_dir)\n', (257, 273), False, 'import os\n'), ((278, 321), 'os.makedirs', 'os.makedirs', (['args.output_dir'], {'exist_ok': '(True)'}), '(args.output_dir, exist_ok=True)\n', (289, 321), False, 'import os\n'), ((1033, 1076), 'argparse.A... |
from io import BytesIO
import pytest
from django.core.management import call_command
from reversion.models import Version
from datahub.company.test.factories import AdviserFactory
pytestmark = pytest.mark.django_db
def test_run(s3_stubber, caplog):
"""Test that the command updates the specified records (ignori... | [
"datahub.company.test.factories.AdviserFactory",
"reversion.models.Version.objects.get_for_object",
"django.core.management.call_command"
] | [((1154, 1218), 'django.core.management.call_command', 'call_command', (['"""update_adviser_contact_email"""', 'bucket', 'object_key'], {}), "('update_adviser_contact_email', bucket, object_key)\n", (1166, 1218), False, 'from django.core.management import call_command\n'), ((2543, 2622), 'django.core.management.call_co... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Test utility functions
"""
from unittest.mock import Mock, patch
import pytest
from ..text_extraction import ReadOCR
@pytest.fixture(name='text_extractor')
def fixture_text_extraction() -> ReadOCR:
"""Returns `Read... | [
"pytest.fixture",
"unittest.mock.patch.object"
] | [((220, 257), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""text_extractor"""'}), "(name='text_extractor')\n", (234, 257), False, 'import pytest\n'), ((868, 908), 'unittest.mock.patch.object', 'patch.object', (['ReadOCR', '"""invoke_read_api"""'], {}), "(ReadOCR, 'invoke_read_api')\n", (880, 908), False, 'from ... |
from music_collection_manager.models import MusicCollection
from music_collection_manager.utils import Config
def main():
MusicCollection(Config())
if __name__ == '__main__':
main()
| [
"music_collection_manager.utils.Config"
] | [((144, 152), 'music_collection_manager.utils.Config', 'Config', ([], {}), '()\n', (150, 152), False, 'from music_collection_manager.utils import Config\n')] |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from textwrap import dedent
import pytest
from pants.backend.java.compile.javac import rules as javac_rules
from pants.backend.java.dependency_inference.rules import rules as dep_inferen... | [
"pants.backend.java.dependency_inference.rules.rules",
"textwrap.dedent",
"pants.jvm.dependency_inference.artifact_mapper.UnversionedCoordinate",
"pants.jvm.resolve.coursier_setup.rules",
"pants.core.util_rules.config_files.rules",
"pants.core.util_rules.external_tool.rules",
"pants.jvm.util_rules.rules... | [((4847, 4914), 'pants.engine.addresses.Address', 'Address', (['""""""'], {'target_name': '"""lib"""', 'relative_file_path': '"""PrintDate.java"""'}), "('', target_name='lib', relative_file_path='PrintDate.java')\n", (4854, 4914), False, 'from pants.engine.addresses import Address, Addresses\n'), ((6216, 6283), 'pants.... |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
n, m = map(int, input().split())
ans = 0
if n >= m // 2:
print(m // 2)
else:
ans += n
ans += ((m - n * 2) // 4)
print(ans)
| [
"sys.setrecursionlimit"
] | [((38, 68), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 7)'], {}), '(10 ** 7)\n', (59, 68), False, 'import sys\n')] |
""" Pretty-print a table comparing DF vector threshold versus accuracy and cost """
import numpy as np
from pyscf import scf
from chemftr import df
from chemftr.molecule import rank_reduced_ccsd_t, cas_to_pyscf, pyscf_to_cas
def generate_costing_table(pyscf_mf,name='molecule',thresh_range=[0.0001],dE=0.001,chi=10,bet... | [
"chemftr.df.rank_reduce",
"chemftr.molecule.rank_reduced_ccsd_t",
"chemftr.df.compute_cost",
"chemftr.molecule.pyscf_to_cas",
"chemftr.df.compute_lambda",
"numpy.linalg.norm"
] | [((2562, 2654), 'chemftr.molecule.rank_reduced_ccsd_t', 'rank_reduced_ccsd_t', (['pyscf_mf'], {'eri_rr': 'None', 'use_kernel': 'use_kernel', 'no_triples': 'no_triples'}), '(pyscf_mf, eri_rr=None, use_kernel=use_kernel,\n no_triples=no_triples)\n', (2581, 2654), False, 'from chemftr.molecule import rank_reduced_ccsd_... |
import os
import datetime
import jwt
from functools import wraps
from flask import Flask, request, jsonify, abort, make_response, send_from_directory
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from flask_sqlalchemy imp... | [
"flask.send_from_directory",
"flask_cors.CORS",
"flask.Flask",
"models.User.query.filter_by",
"datetime.datetime.utcnow",
"os.path.join",
"flask.request.json.get",
"flask.make_response",
"werkzeug.utils.secure_filename",
"models.User",
"os.path.abspath",
"flask_sqlalchemy.SQLAlchemy",
"datet... | [((473, 516), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""high_loader_db.db"""'], {}), "(BASE_DIR, 'high_loader_db.db')\n", (485, 516), False, 'import os\n'), ((533, 566), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""uploads"""'], {}), "(BASE_DIR, 'uploads')\n", (545, 566), False, 'import os\n'), ((692, 707)... |
from tests.integration.create_token import create_token
from tests.integration.star_wars import star_wars_test_urls
from tests.integration.star_wars.star_wars_tests import StarWarsTestCase
class TestConfirmationPage(StarWarsTestCase):
def test_confirmation_page(self):
self.rogue_one_login_and_check_intro... | [
"tests.integration.create_token.create_token"
] | [((2577, 2607), 'tests.integration.create_token.create_token', 'create_token', (['"""rogue_one"""', '"""0"""'], {}), "('rogue_one', '0')\n", (2589, 2607), False, 'from tests.integration.create_token import create_token\n')] |
import unittest
import numpy as np
from fit1d.common.model import ModelMock
from fit1d.common.fit1d import FitData
class TestFitData(unittest.TestCase):
def setUp(self):
self.x = np.array([1,2, 3, 4])
self.y = np.array([10,20, 30, 40])
self.model = ModelMock({"param1": 5.5})
def test_... | [
"numpy.array",
"fit1d.common.fit1d.FitData",
"fit1d.common.model.ModelMock"
] | [((193, 215), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (201, 215), True, 'import numpy as np\n'), ((232, 258), 'numpy.array', 'np.array', (['[10, 20, 30, 40]'], {}), '([10, 20, 30, 40])\n', (240, 258), True, 'import numpy as np\n'), ((279, 305), 'fit1d.common.model.ModelMock', 'ModelMock',... |
import numpy as np
from quantities import Hz
from neo import AnalogSignal as AnalogSignal
n = np.array([[0.1, 0.1, 0.1, 0.1],
[-2.0, -2.0, -2.0, -4.0],
[0.1, 0.1, 0.1, 0.1],
[-0.1, -0.1, -0.1, -0.1],
[-0.1, -0.1, -0.1, -0.1],
[-3.0, -3.0, -3.0, -3.0... | [
"numpy.array",
"neo.AnalogSignal"
] | [((95, 307), 'numpy.array', 'np.array', (['[[0.1, 0.1, 0.1, 0.1], [-2.0, -2.0, -2.0, -4.0], [0.1, 0.1, 0.1, 0.1], [-\n 0.1, -0.1, -0.1, -0.1], [-0.1, -0.1, -0.1, -0.1], [-3.0, -3.0, -3.0, -\n 3.0], [0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1]]'], {}), '([[0.1, 0.1, 0.1, 0.1], [-2.0, -2.0, -2.0, -4.0], [0.1, 0.1, 0.... |
import tensorflow as tf
import numpy as np
import os
import pickle
import gzip
import urllib.request
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, Dropout
from keras.layers.normalization import BatchNormaliza... | [
"keras.layers.Conv2D",
"numpy.random.rand",
"keras.layers.Flatten",
"keras.models.Sequential",
"keras.layers.Dropout",
"keras.layers.Activation",
"keras.layers.Dense",
"keras.backend.set_learning_phase"
] | [((437, 449), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (447, 449), False, 'from keras.models import Sequential\n'), ((995, 1034), 'keras.backend.set_learning_phase', 'keras.backend.set_learning_phase', (['(False)'], {}), '(False)\n', (1027, 1034), False, 'import keras\n'), ((1085, 1114), 'numpy.random... |
from pathlib import Path
from time import perf_counter
basepath = r'C:\Users\b_r_l\OneDrive\Documents\code'
print(perf_counter())
path = Path(basepath)
all_items = [*path.rglob('*')]
dirs = filter(Path.is_dir, all_items)
print(len(all_items))
print('FIN', len([*dirs]), perf_counter())
| [
"time.perf_counter",
"pathlib.Path"
] | [((140, 154), 'pathlib.Path', 'Path', (['basepath'], {}), '(basepath)\n', (144, 154), False, 'from pathlib import Path\n'), ((117, 131), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (129, 131), False, 'from time import perf_counter\n'), ((273, 287), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (285,... |
import boto3
def SendMessage(queue_name, respondent):
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.get_queue_by_name(QueueName=queue_name)
queue.send_message(MessageBody=respondent)
#sqs.send_message(QueueUrl = queue_url, DelaySeconds=0, MessageBody = respondent)
| [
"boto3.resource"
] | [((65, 111), 'boto3.resource', 'boto3.resource', (['"""sqs"""'], {'region_name': '"""us-east-1"""'}), "('sqs', region_name='us-east-1')\n", (79, 111), False, 'import boto3\n')] |
from qpet import qpet
import unittest
class DailyTest(unittest.TestCase):
def test_basic(self):
pass
if __name__ == '__main__':
unittest.main()
| [
"unittest.main"
] | [((147, 162), 'unittest.main', 'unittest.main', ([], {}), '()\n', (160, 162), False, 'import unittest\n')] |
# Copyright (c) 2015 <NAME>
#
# See the file LICENSE.txt for copying permission.
import unittest
import random
from gameboard.gameboard import Gameboard, Direction
from gameboard.coordinate import Coordinate
class TestBoard(unittest.TestCase):
def setUp(self):
self.board = Gameboard()
def test_64_sq... | [
"unittest.main",
"gameboard.gameboard.Gameboard",
"random.randrange"
] | [((14841, 14856), 'unittest.main', 'unittest.main', ([], {}), '()\n', (14854, 14856), False, 'import unittest\n'), ((289, 300), 'gameboard.gameboard.Gameboard', 'Gameboard', ([], {}), '()\n', (298, 300), False, 'from gameboard.gameboard import Gameboard, Direction\n'), ((14079, 14102), 'random.randrange', 'random.randr... |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest.ip_messaging import TwilioIpMessagingClient
# Initialize the Client
account = "<KEY>"
token = "<PASSWORD>"
client = TwilioIpMessagingClient(account, token)
# Create role
service = client.services.get(sid="ISXXXXXXXXXXXXXXXXXXXXX... | [
"twilio.rest.ip_messaging.TwilioIpMessagingClient"
] | [((207, 246), 'twilio.rest.ip_messaging.TwilioIpMessagingClient', 'TwilioIpMessagingClient', (['account', 'token'], {}), '(account, token)\n', (230, 246), False, 'from twilio.rest.ip_messaging import TwilioIpMessagingClient\n')] |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
f... | [
"vispy.testing.run_tests_if_main",
"vispy.scene.widgets.ViewBox"
] | [((1592, 1611), 'vispy.testing.run_tests_if_main', 'run_tests_if_main', ([], {}), '()\n', (1609, 1611), False, 'from vispy.testing import run_tests_if_main\n'), ((450, 477), 'vispy.scene.widgets.ViewBox', 'ViewBox', ([], {'camera': '"""turntable"""'}), "(camera='turntable')\n", (457, 477), False, 'from vispy.scene.widg... |
import itertools
class SeatMatrix:
OCCUPIED = '#'
EMPTY = 'L'
FLOOR = '.'
def __init__(self, arr):
self.matrix = arr
self.num_rows = len(self.matrix)
self.num_cols = len(self.matrix[0])
def get_seat_val(self, r, c):
return self.matrix[r][c]
def count_immediate... | [
"itertools.product"
] | [((1194, 1235), 'itertools.product', 'itertools.product', (['[-1, 0, 1]', '[-1, 0, 1]'], {}), '([-1, 0, 1], [-1, 0, 1])\n', (1211, 1235), False, 'import itertools\n')] |
import json
from channels.generic.websocket import AsyncWebsocketConsumer, AsyncJsonWebsocketConsumer
from Net640.apps.chat.models import Message
from Net640.errors import NotEnoughSpace
class ChatConsumer(AsyncWebsocketConsumer):
"""
Class-consumer, which will accept WebSocket connections and
process ws... | [
"Net640.apps.chat.models.Message",
"json.loads",
"json.dumps"
] | [((1114, 1135), 'json.loads', 'json.loads', (['text_data'], {}), '(text_data)\n', (1124, 1135), False, 'import json\n'), ((1263, 1331), 'Net640.apps.chat.models.Message', 'Message', ([], {'author': 'self.user', 'chat_room': 'self.room_name', 'content': 'content'}), '(author=self.user, chat_room=self.room_name, content=... |
#!/usr/bin/python3
#############################################################################################
# Program by <NAME> #
# Email: <EMAIL> #
# Created on Decemb... | [
"collections.namedtuple",
"collections.defaultdict"
] | [((676, 719), 'collections.namedtuple', 'namedtuple', (['"""Results"""', "['sorted', 'cyclic']"], {}), "('Results', ['sorted', 'cyclic'])\n", (686, 719), False, 'from collections import defaultdict, namedtuple\n'), ((834, 850), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (845, 850), False, 'from... |
import colorlog
import logging
import socket
from collections import defaultdict
from typing import Callable, Optional, Union
class EventEmitter:
def __init__(self) -> None:
self._event_handlers = defaultdict(list)
def on(self, event: str, f: Callable) -> None:
self._event_handlers[event].app... | [
"logging.getLogger",
"logging.StreamHandler",
"socket.socket",
"collections.defaultdict",
"colorlog.ColoredFormatter"
] | [((848, 871), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (865, 871), False, 'import logging\n'), ((1001, 1024), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1022, 1024), False, 'import logging\n'), ((1452, 1471), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\... |
# -*- coding: utf-8 -*-
# trump-net (c) <NAME>
from nose.plugins.attrib import attr
from .mixins import DiamondTestCase
class BasicTestCase(DiamondTestCase):
def test_basic(self):
"ensure the minimum test works"
assert True
@attr("skip")
def test_skip(self):
assert False
| [
"nose.plugins.attrib.attr"
] | [((253, 265), 'nose.plugins.attrib.attr', 'attr', (['"""skip"""'], {}), "('skip')\n", (257, 265), False, 'from nose.plugins.attrib import attr\n')] |
import sys, re, os
from enum import Enum
class ElseLanguage:
def __init__(self, output, language: str, punctuation: str, valid_identifier: str, indentation: int, version: str, copyright: str, start_rule: str) -> None:
self.output: str = output
self.language: str = language
self.punctuation:... | [
"enum.Enum",
"re.compile"
] | [((1333, 1362), 're.compile', 're.compile', (['"""^[A-Za-z0-9_]+$"""'], {}), "('^[A-Za-z0-9_]+$')\n", (1343, 1362), False, 'import sys, re, os\n'), ((1386, 1445), 'enum.Enum', 'Enum', (['"""SubstituteType"""', '"""AUTO_SUBSTITUTE NOAUTO_SUBSTITUTE"""'], {}), "('SubstituteType', 'AUTO_SUBSTITUTE NOAUTO_SUBSTITUTE')\n", ... |
from ironman.utilities import chunks
def test_chunks():
assert list(chunks('abc', 1)) == ['a', 'b', 'c']
assert list(chunks('abc', 2)) == ['ab', 'c']
assert list(chunks('abc', 3)) == ['abc']
| [
"ironman.utilities.chunks"
] | [((74, 90), 'ironman.utilities.chunks', 'chunks', (['"""abc"""', '(1)'], {}), "('abc', 1)\n", (80, 90), False, 'from ironman.utilities import chunks\n'), ((127, 143), 'ironman.utilities.chunks', 'chunks', (['"""abc"""', '(2)'], {}), "('abc', 2)\n", (133, 143), False, 'from ironman.utilities import chunks\n'), ((176, 19... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: production.py
@time: 2018-03-16 09:59
"""
from __future__ import unicode_literals
from datetime import datetime
from flask import (
request,
flash,
render_template,
url_for,
redirect,
abort,
jsonify,
... | [
"flask.render_template",
"flask.request.args.get",
"app_backend.forms.production.ProductionSelectForm",
"app_backend.app.config.get",
"app_backend.forms.production.ProductionEditForm",
"flask.jsonify",
"app_backend.api.quotation_items.count_quotation_items",
"flask.flash",
"app_backend.permissions.p... | [((1694, 1753), 'flask.Blueprint', 'Blueprint', (['"""production"""', '__name__'], {'url_prefix': '"""/production"""'}), "('production', __name__, url_prefix='/production')\n", (1703, 1753), False, 'from flask import request, flash, render_template, url_for, redirect, abort, jsonify, Blueprint\n'), ((1778, 1813), 'app_... |
from selenium.webdriver import Firefox
url = 'http://selenium.dunossauro.live/aula_05_c.html'
firefox = Firefox()
firefox.get(url)
def melhor_filme(browser, filme, email, telefone):
"""Preenche o formulário do melhor filme de 2020."""
browser.find_element_by_name('filme').send_keys(filme)
browser.find... | [
"selenium.webdriver.Firefox"
] | [((107, 116), 'selenium.webdriver.Firefox', 'Firefox', ([], {}), '()\n', (114, 116), False, 'from selenium.webdriver import Firefox\n')] |
"""
Auxiliar retrievers parsing
---------------------------
Tools and utilities to parse heterogenous ways to give retriever information
in order to obtain retriever objects.
"""
import numpy as np
from retrievers import BaseRetriever
from collectionretrievers import RetrieverManager
from pySpatialTools.Discretizat... | [
"pySpatialTools.Discretization._discretization_parsing_creation",
"numpy.ones",
"collectionretrievers.RetrieverManager",
"numpy.where",
"numpy.array",
"numpy.concatenate"
] | [((5014, 5067), 'pySpatialTools.Discretization._discretization_parsing_creation', '_discretization_parsing_creation', (['discretization_info'], {}), '(discretization_info)\n', (5046, 5067), False, 'from pySpatialTools.Discretization import _discretization_parsing_creation\n'), ((6084, 6137), 'pySpatialTools.Discretizat... |
from rest_framework import serializers
from . import models
class HelloSerializer(serializers.Serializer):
"""Serialzes a name field for testing our APIView"""
name = serializers.CharField(max_length=10)
class UserProfileSerializer(serializers.ModelSerializer): #The ModelSerializer uses a meta to configure... | [
"rest_framework.serializers.CharField"
] | [((177, 213), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(10)'}), '(max_length=10)\n', (198, 213), False, 'from rest_framework import serializers\n')] |
from sleep_tracking.utils import get_root_directory
import os
from abc import ABC, abstractmethod
import pandas as pd
import numpy as np
from typing import List
class AbstractFeature(ABC):
WINDOW_SIZE = 10 * 30 - 15
EPOCH_DURATION = 30
def __init__(self, name):
self.name = name
@abstractme... | [
"numpy.atleast_2d",
"numpy.amin",
"numpy.where",
"sleep_tracking.utils.get_root_directory",
"pandas.concat",
"numpy.interp",
"numpy.amax"
] | [((1141, 1179), 'pandas.concat', 'pd.concat', (['features'], {'ignore_index': '(True)'}), '(features, ignore_index=True)\n', (1150, 1179), True, 'import pandas as pd\n'), ((439, 459), 'sleep_tracking.utils.get_root_directory', 'get_root_directory', ([], {}), '()\n', (457, 459), False, 'from sleep_tracking.utils import ... |
'''
This is a sample class for a model. You may choose to use it as-is or make any changes to it.
This has been provided just to give you an idea of how to structure your model class.
'''
import numpy as np
import time
from openvino.inference_engine import IENetwork, IECore
import os
import cv2
import argparse
import s... | [
"cv2.resize",
"openvino.inference_engine.IECore",
"openvino.inference_engine.IENetwork"
] | [((1276, 1284), 'openvino.inference_engine.IECore', 'IECore', ([], {}), '()\n', (1282, 1284), False, 'from openvino.inference_engine import IENetwork, IECore\n'), ((2008, 2033), 'cv2.resize', 'cv2.resize', (['image', '(w, h)'], {}), '(image, (w, h))\n', (2018, 2033), False, 'import cv2\n'), ((792, 843), 'openvino.infer... |
import pandas as pd
from sklearn.metrics import accuracy_score, recall_score
import models
import qa_experimenters
from interpreters import baseline_interpreter
# disable info logging for datasets
qa_experimenters.datasets.logging.set_verbosity_error()
# load models
model_classif = models.Model_Classification()
mode... | [
"qa_experimenters.SQuADExperimenter",
"models.Model_QA",
"sklearn.metrics.recall_score",
"models.Model_Classification",
"qa_experimenters.datasets.logging.set_verbosity_error",
"qa_experimenters.SQuADShiftsExperimenter",
"pandas.DataFrame",
"sklearn.metrics.accuracy_score"
] | [((199, 254), 'qa_experimenters.datasets.logging.set_verbosity_error', 'qa_experimenters.datasets.logging.set_verbosity_error', ([], {}), '()\n', (252, 254), False, 'import qa_experimenters\n'), ((286, 315), 'models.Model_Classification', 'models.Model_Classification', ([], {}), '()\n', (313, 315), False, 'import model... |
import os
import logging
from pathlib import Path
from collections import UserDict
import yaml
import tree_hugger.setup_logging
from tree_hugger.exceptions import QueryFileNotFoundError
class Query(UserDict):
data = {}
def __init__(self, query_file_path: str, query_file_content: str):
self.query_f... | [
"yaml.load",
"tree_hugger.exceptions.QueryFileNotFoundError",
"pathlib.Path"
] | [((562, 621), 'tree_hugger.exceptions.QueryFileNotFoundError', 'QueryFileNotFoundError', (['f"""Cound not find {query_file_path}"""'], {}), "(f'Cound not find {query_file_path}')\n", (584, 621), False, 'from tree_hugger.exceptions import QueryFileNotFoundError\n'), ((715, 751), 'yaml.load', 'yaml.load', (['f'], {'Loade... |
# -*- coding: utf-8 -*-
# copyright: (c) 2020 by <NAME>.
# license: Apache 2.0, see LICENSE for more details.
'''Argufy is an inspection based CLI parser.'''
import inspect
import logging
import sys
import typing
from argparse import ArgumentParser, Namespace, _SubParsersAction
# from dataclasses import is_dataclass
f... | [
"logging.getLogger",
"logging.StreamHandler",
"inspect.getmembers",
"inspect.stack",
"argufy.formatter.ArgufyHelpFormatter.font",
"inspect.getmodule",
"inspect.isclass",
"inspect.signature",
"argufy.argument.Argument",
"docstring_parser.parse",
"inspect.isfunction",
"typing.TypeVar"
] | [((658, 685), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (675, 685), False, 'import logging\n'), ((732, 770), 'typing.TypeVar', 'TypeVar', (['"""F"""'], {'bound': 'Callable[..., Any]'}), "('F', bound=Callable[..., Any])\n", (739, 770), False, 'from typing import Any, Callable, Dict, L... |
from ..solution import Solution
from math import ceil, floor
from statistics import median, mean
def abs_diff(a, b) -> int:
return int(abs(a - b))
def sum_to(n: int) -> int:
return int((n * (n + 1)) / 2)
def median_cost(crabs_pos) -> int:
med_pos = int(median(crabs_pos))
return sum([abs_diff(pos,... | [
"statistics.mean",
"statistics.median",
"math.ceil",
"math.floor"
] | [((403, 418), 'statistics.mean', 'mean', (['crabs_pos'], {}), '(crabs_pos)\n', (407, 418), False, 'from statistics import median, mean\n'), ((272, 289), 'statistics.median', 'median', (['crabs_pos'], {}), '(crabs_pos)\n', (278, 289), False, 'from statistics import median, mean\n'), ((470, 485), 'math.floor', 'floor', (... |
from telegram.bot import Bot
from telegram.ext import CommandHandler, CallbackContext
from telegram import Update, Message
from typing import List
class Darter:
def __init__(self, bot: Bot):
self.bot = bot
def getCommands(self) -> List[CommandHandler]:
return [CommandHandler("dart", self.dart... | [
"telegram.ext.CommandHandler"
] | [((288, 321), 'telegram.ext.CommandHandler', 'CommandHandler', (['"""dart"""', 'self.dart'], {}), "('dart', self.dart)\n", (302, 321), False, 'from telegram.ext import CommandHandler, CallbackContext\n'), ((339, 372), 'telegram.ext.CommandHandler', 'CommandHandler', (['"""dice"""', 'self.dice'], {}), "('dice', self.dic... |
import arcpy
import os
import sys
import math
from arcpy import env
surface1 = arcpy.GetParameterAsText(0)
surface2 = arcpy.GetParameterAsText(1)
new_first_surface = arcpy.GetParameterAsText(2)
new_second_surface = arcpy.GetParameterAsText(3)
tolerance = arcpy.GetParameter(4)
def search_intersect(surf... | [
"arcpy.CopyFeatures_management",
"arcpy.Near3D_3d",
"arcpy.CreateFeatureclass_management",
"arcpy.Array",
"arcpy.da.SearchCursor",
"arcpy.Point",
"arcpy.da.InsertCursor",
"arcpy.Polygon",
"arcpy.SelectLayerByAttribute_management",
"arcpy.GetParameter",
"arcpy.GetParameterAsText",
"arcpy.Select... | [((86, 113), 'arcpy.GetParameterAsText', 'arcpy.GetParameterAsText', (['(0)'], {}), '(0)\n', (110, 113), False, 'import arcpy\n'), ((126, 153), 'arcpy.GetParameterAsText', 'arcpy.GetParameterAsText', (['(1)'], {}), '(1)\n', (150, 153), False, 'import arcpy\n'), ((177, 204), 'arcpy.GetParameterAsText', 'arcpy.GetParamet... |
import math
import random
from typing import Optional
from lib.sc2.position import Point2
from lib.sc2.units import Units
import lib.sc2.constants as const
from lambdanaut.builds import Builds
from lambdanaut.expiringlist import ExpiringList
from lambdanaut.const2 import Messages, ResourceManagerCommands
from lambdan... | [
"lambdanaut.expiringlist.ExpiringList",
"random.randint",
"lib.sc2.position.Point2"
] | [((704, 718), 'lambdanaut.expiringlist.ExpiringList', 'ExpiringList', ([], {}), '()\n', (716, 718), False, 'from lambdanaut.expiringlist import ExpiringList\n'), ((14703, 14724), 'random.randint', 'random.randint', (['(9)', '(11)'], {}), '(9, 11)\n', (14717, 14724), False, 'import random\n'), ((10878, 10893), 'lib.sc2.... |
# Based on the implementation in django-postgres but with various fixes
# and form-integration.
#
# Once Django 1.8 supports this ootb this module can be removed.
import uuid
from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ug... | [
"django.utils.translation.ugettext_lazy",
"uuid.UUID",
"django.core.exceptions.ValidationError",
"psycopg2.extras.register_uuid",
"uuid.uuid4"
] | [((381, 396), 'psycopg2.extras.register_uuid', 'register_uuid', ([], {}), '()\n', (394, 396), False, 'from psycopg2.extras import register_uuid\n'), ((536, 573), 'django.utils.translation.ugettext_lazy', '_', (['"""\'%(value)s\' is not a valid UUID."""'], {}), '("\'%(value)s\' is not a valid UUID.")\n', (537, 573), Tru... |
import os
import responses
from cryptography.fernet import Fernet
from thx_bot.commands.login_wallet import login_wallet
from thx_bot.models.channels import Channel
from thx_bot.models.users import User
from thx_bot.services.thx_api_client import ACTIVATION_URL
from thx_bot.services.thx_api_client import URL_GET_TOKE... | [
"os.getenv",
"thx_bot.models.users.User",
"responses.add",
"thx_bot.models.channels.Channel",
"thx_bot.commands.login_wallet.login_wallet"
] | [((429, 517), 'responses.add', 'responses.add', (['responses.POST', 'URL_GET_TOKEN'], {'json': "{'access_token': 123}", 'status': '(200)'}), "(responses.POST, URL_GET_TOKEN, json={'access_token': 123},\n status=200)\n", (442, 517), False, 'import responses\n'), ((518, 584), 'responses.add', 'responses.add', (['respo... |
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESEncryption:
def __init__(self, key: str, salt: str, iterations: int):
self.key = self.__get_sha256(text=key, salt=salt, iterations=iterations)
@staticmethod
def __get_sha256(text: str, salt: str = "", i... | [
"Crypto.Random.new",
"Crypto.Cipher.AES.new",
"base64.b64decode"
] | [((731, 787), 'Crypto.Cipher.AES.new', 'AES.new', ([], {'key': 'self.key', 'mode': 'AES.MODE_CBC', 'iv': 'init_vector'}), '(key=self.key, mode=AES.MODE_CBC, iv=init_vector)\n', (738, 787), False, 'from Crypto.Cipher import AES\n'), ((1182, 1210), 'base64.b64decode', 'base64.b64decode', (['ciphertext'], {}), '(ciphertex... |
# Copyright © 2013, 2014, 2017 <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
# There is NO WARRANTY.
"""Import a list of 'interesting' URL... | [
"shared.url_database.ensure_database",
"shared.url_database.add_url_string",
"re.compile",
"sys.stderr.flush",
"sys.stderr.write",
"shared.url_database.add_site"
] | [((3028, 3056), 're.compile', 're.compile', (['"""(?i)^[a-z]+://"""'], {}), "('(?i)^[a-z]+://')\n", (3038, 3056), False, 'import re\n'), ((726, 765), 'shared.url_database.ensure_database', 'url_database.ensure_database', (['self.args'], {}), '(self.args)\n', (754, 765), False, 'from shared import url_database\n'), ((31... |
import unittest
from swmm_mpc.rpt_ele import rpt_ele
class test_rpt_ele(unittest.TestCase):
test_rpt_file = "example.rpt"
rpt = rpt_ele(test_rpt_file)
def test_total_flood(self):
true_flood_vol = 0.320
self.assertEqual(true_flood_vol, self.rpt.total_flooding)
def test_get_start_line(... | [
"unittest.main",
"swmm_mpc.rpt_ele.rpt_ele"
] | [((138, 160), 'swmm_mpc.rpt_ele.rpt_ele', 'rpt_ele', (['test_rpt_file'], {}), '(test_rpt_file)\n', (145, 160), False, 'from swmm_mpc.rpt_ele import rpt_ele\n'), ((878, 893), 'unittest.main', 'unittest.main', ([], {}), '()\n', (891, 893), False, 'import unittest\n')] |