code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from conans import ConanFile
from conans.tools import get
class SpdlogConan(ConanFile):
name = 'spdlog'
version = '0.9.0'
author = '<NAME> (<EMAIL>)'
url = 'http://github.com/hinrikg/conan-spdlog'
license = 'MIT'
settings = None
generators = 'cmake'
def source(self):
get('htt... | [
"conans.tools.get"
] | [((312, 370), 'conans.tools.get', 'get', (['"""https://github.com/gabime/spdlog/archive/v0.9.0.zip"""'], {}), "('https://github.com/gabime/spdlog/archive/v0.9.0.zip')\n", (315, 370), False, 'from conans.tools import get\n')] |
from matplotlib import pyplot as plt
from typing import Callable, Union
from tkinter import Toplevel
import tkinter as tk
import tkinter.ttk as ttk
from functools import partial
import numpy as np
from src.utils.MatplotlibTkinterIntegration import createPlot
from src.utils.State import State
from src.utils.constants i... | [
"tkinter.ttk.Button",
"matplotlib.pyplot.ylabel",
"tkinter.ttk.Entry",
"tkinter.ttk.Frame",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"tkinter.ttk.Label",
"matplotlib.pyplot.close",
"src.utils.MatplotlibTkinterIntegration.createPlot",
"tkinter.Toplevel",
"matplotlib.pyplot.subplot",
... | [((5844, 5861), 'tkinter.ttk.Frame', 'ttk.Frame', (['window'], {}), '(window)\n', (5853, 5861), True, 'import tkinter.ttk as ttk\n'), ((6017, 6076), 'tkinter.ttk.Button', 'ttk.Button', (['btnFrame'], {'text': '"""Show Fit"""', 'command': 'self.showFit'}), "(btnFrame, text='Show Fit', command=self.showFit)\n", (6027, 60... |
"""
.. _l-Speedup-pca:
Speed up scikit-learn inference with ONNX
=========================================
Is it possible to make :epkg:`scikit-learn` faster with ONNX?
That's question this example tries to answer. The scenario is
is the following:
* a model is trained
* it is converted into ONNX for inference
* it ... | [
"sklearn.datasets.make_regression",
"sklearn.decomposition.PCA",
"tqdm.tqdm",
"cpyquickhelper.numbers.speed_measure.measure_time",
"pyquickhelper.pycode.profiling.profile",
"pandas.DataFrame",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((1090, 1126), 'sklearn.datasets.make_regression', 'make_regression', (['(1000)'], {'n_features': '(20)'}), '(1000, n_features=20)\n', (1105, 1126), False, 'from sklearn.datasets import make_regression\n'), ((1642, 1654), 'tqdm.tqdm', 'tqdm', (['models'], {}), '(models)\n', (1646, 1654), False, 'from tqdm import tqdm\... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times"
P = np.array([[1, 0, 0, 0, 0, 0],
[0.5, 0, 0.5, 0, 0, 0],
[0, 0.5, 0, 0.5, 0, 0],
[0, 0, 0.5, 0, 0.5, 0],
[0, 0, 0, 0.5, 0, 0.5],
[0, 0, 0,... | [
"numpy.append",
"numpy.array",
"numpy.dot",
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((115, 266), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 0], [0.5, 0, 0.5, 0, 0, 0], [0, 0.5, 0, 0.5, 0, 0], [0, 0,\n 0.5, 0, 0.5, 0], [0, 0, 0, 0.5, 0, 0.5], [0, 0, 0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0, 0, 0], [0.5, 0, 0.5, 0, 0, 0], [0, 0.5, 0, 0.5, 0, 0\n ], [0, 0, 0.5, 0, 0.5, 0], [0, 0, 0, 0.5, 0, 0.5], [... |
import pytest
from asynctest import mock as async_mock
from ......core.protocol_registry import ProtocolRegistry
from ......messaging.base_handler import HandlerException
from ......messaging.request_context import RequestContext
from ......messaging.responder import MockResponder
from .....didcomm_prefix import DID... | [
"pytest.fixture",
"pytest.raises",
"asynctest.mock.MagicMock",
"asynctest.mock.CoroutineMock"
] | [((626, 642), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (640, 642), False, 'import pytest\n'), ((784, 829), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'connection_id': '"""test123"""'}), "(connection_id='test123')\n", (804, 829), True, 'from asynctest import mock as async_mock\n'), ((2747, 27... |
"""Input/output"""
import os
import wave
import numpy as np
def read_wave(file: os.PathLike) -> tuple[int, np.ndarray]:
"""Read WAV file into numpy array
NOTE: only mono audio is supported. Multi-channel audio is interlaced,
and would need to be de-interlaced into a 2D array.
Args:
file (o... | [
"numpy.frombuffer"
] | [((846, 881), 'numpy.frombuffer', 'np.frombuffer', (['buffer'], {'dtype': '_dtype'}), '(buffer, dtype=_dtype)\n', (859, 881), True, 'import numpy as np\n')] |
import os
import sys
cur_dir = os.path.dirname(__file__)
project_root = os.path.join(cur_dir,'..','..')
sys.path.append(project_root)
from utils.utils import ImageTransformer
from embedding.greedy_encoding import AutoEncoder
import numpy as np
import keras
from utils.utils import visualize_result_ae
model_path = o... | [
"keras.optimizers.Adam",
"utils.utils.ImageTransformer",
"embedding.greedy_encoding.AutoEncoder",
"utils.utils.visualize_result_ae",
"os.path.join",
"os.path.dirname",
"sys.path.append"
] | [((32, 57), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (47, 57), False, 'import os\n'), ((73, 106), 'os.path.join', 'os.path.join', (['cur_dir', '""".."""', '""".."""'], {}), "(cur_dir, '..', '..')\n", (85, 106), False, 'import os\n'), ((105, 134), 'sys.path.append', 'sys.path.append', ([... |
import numpy as np
import xarray as xr
from xbitinfo import get_keepbits
from . import _skip_slow, ensure_loaded, parameterized, randn, requires_dask
class GetKeepbits:
"""
Benchmark time and peak memory of `get_keepbits`.
"""
# https://asv.readthedocs.io/en/stable/benchmarks.html
timeout = 30.... | [
"numpy.array",
"xbitinfo.get_keepbits"
] | [((1752, 1793), 'xbitinfo.get_keepbits', 'get_keepbits', (['self.info_per_bit'], {}), '(self.info_per_bit, **kwargs)\n', (1764, 1793), False, 'from xbitinfo import get_keepbits\n'), ((1900, 1941), 'xbitinfo.get_keepbits', 'get_keepbits', (['self.info_per_bit'], {}), '(self.info_per_bit, **kwargs)\n', (1912, 1941), Fals... |
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# ALGORITHMS PERMUTATIONS STRINGS
import allure
import pytest
import unittest
from utils.log_func import print_log
from kyu_4.permutations.permutations import permutations
@allure.epic("4 kyu")
@allure.... | [
"allure.parent_suite",
"allure.tag",
"allure.sub_suite",
"allure.dynamic.severity",
"allure.story",
"allure.link",
"pytest.mark.skip",
"allure.dynamic.description_html",
"kyu_4.permutations.permutations.permutations",
"allure.epic",
"allure.suite",
"allure.dynamic.title",
"allure.feature",
... | [((291, 311), 'allure.epic', 'allure.epic', (['"""4 kyu"""'], {}), "('4 kyu')\n", (302, 311), False, 'import allure\n'), ((313, 345), 'allure.parent_suite', 'allure.parent_suite', (['"""Competent"""'], {}), "('Competent')\n", (332, 345), False, 'import allure\n'), ((347, 373), 'allure.suite', 'allure.suite', (['"""Algo... |
#!/usr/bin/env python
import numpy
from shogun import MSG_DEBUG
traindat = numpy.random.random_sample((10,10))
testdat = numpy.random.random_sample((10,10))
parameter_list=[[traindat,testdat,1.2],[traindat,testdat,1.4]]
def kernel_director_linear (fm_train_real=traindat,fm_test_real=testdat,scale=1.2):
try:
from sh... | [
"numpy.random.random_sample",
"shogun.LinearKernel",
"shogun.DirectorKernel.__init__",
"shogun.features",
"numpy.dot",
"shogun.Time",
"shogun.AvgDiagKernelNormalizer"
] | [((75, 111), 'numpy.random.random_sample', 'numpy.random.random_sample', (['(10, 10)'], {}), '((10, 10))\n', (101, 111), False, 'import numpy\n'), ((121, 157), 'numpy.random.random_sample', 'numpy.random.random_sample', (['(10, 10)'], {}), '((10, 10))\n', (147, 157), False, 'import numpy\n'), ((838, 864), 'shogun.featu... |
import networkx as nx
from entity.entity import Graph, Node
from node2vec import Node2Vec
import numpy as np
from gensim.models.word2vec import Word2Vec
from flask import current_app
from sklearn.decomposition import PCA
from sklearn import manifold
from algorithm.search_community import PyLouvain
from algorithm.simila... | [
"os.path.exists",
"gensim.models.word2vec.Word2Vec.load",
"algorithm.structure_correspond.find_structure_correspond",
"algorithm.search_community.PyLouvain.from_graph",
"pickle.dump",
"sklearn.decomposition.PCA",
"pickle.load",
"sklearn.manifold.TSNE",
"os.path.isfile",
"algorithm.similar_structur... | [((1520, 1527), 'entity.entity.Graph', 'Graph', ([], {}), '()\n', (1525, 1527), False, 'from entity.entity import Graph, Node\n'), ((2431, 2468), 'algorithm.similar_structure.get_similar_structure', 'get_similar_structure', (['name', 'nodes', 'k'], {}), '(name, nodes, k)\n', (2452, 2468), False, 'from algorithm.similar... |
import CIM2Matpower
# from scipy.io import savemat
cim_to_matpower_filename = 'CIM_to_Matpower_import'
cimfiles = ['./UCTE10_20090319_modified_EQ.xml',
'./UCTE10_20090319_modified_TP.xml',
'./UCTE10_20090319_modified_SV.xml']
boundary_profiles = []
mpc = CIM2Matpower.cim_to_mpc(cimfiles, b... | [
"CIM2Matpower.cim_to_mpc"
] | [((285, 337), 'CIM2Matpower.cim_to_mpc', 'CIM2Matpower.cim_to_mpc', (['cimfiles', 'boundary_profiles'], {}), '(cimfiles, boundary_profiles)\n', (308, 337), False, 'import CIM2Matpower\n')] |
import torch
import torch.nn as nn
from .base_color import *
import torch.utils.model_zoo as model_zoo
class SIGGRAPHGenerator(BaseColor):
def __init__(self, norm_layer=nn.BatchNorm2d, classes=529):
super(SIGGRAPHGenerator, self).__init__()
# Conv1
model1=[nn.Conv2d(4, 64, kernel_size=3, s... | [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.LeakyReLU",
"torch.nn.Softmax",
"torch.nn.Sequential",
"torch.utils.model_zoo.load_url",
"torch.nn.Conv2d",
"torch.nn.Upsample",
"torch.nn.ConvTranspose2d",
"torch.cat"
] | [((4756, 4778), 'torch.nn.Sequential', 'nn.Sequential', (['*model1'], {}), '(*model1)\n', (4769, 4778), True, 'import torch.nn as nn\n'), ((4801, 4823), 'torch.nn.Sequential', 'nn.Sequential', (['*model2'], {}), '(*model2)\n', (4814, 4823), True, 'import torch.nn as nn\n'), ((4846, 4868), 'torch.nn.Sequential', 'nn.Seq... |
"""URL Mapping."""
from django.conf.urls import url
from . import views
app_name = 'tutor'
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<tutor_id>[0-9]+)/book/$',
views.confirm_booking, name='confirm_booking'),
url(r'^(?P<tutor_id>[0-9]+)/book/co... | [
"django.conf.urls.url"
] | [((188, 275), 'django.conf.urls.url', 'url', (['"""^(?P<tutor_id>[0-9]+)/book/$"""', 'views.confirm_booking'], {'name': '"""confirm_booking"""'}), "('^(?P<tutor_id>[0-9]+)/book/$', views.confirm_booking, name=\n 'confirm_booking')\n", (191, 275), False, 'from django.conf.urls import url\n'), ((285, 373), 'django.con... |
"""
TextAttack Command Package for model benchmarking
--------------------------------------------------
"""
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
import scipy
import torch
import textattack
from textattack.commands import TextAttackCommand
from textattack.commands.attack.attack_args ... | [
"textattack.shared.utils.set_seed",
"textattack.commands.attack.attack_args_helpers.parse_model_from_args",
"textattack.commands.attack.attack_args.HUGGINGFACE_DATASET_BY_MODEL.keys",
"textattack.commands.attack.attack_args.TEXTATTACK_DATASET_BY_MODEL.keys",
"textattack.shared.AttackedText",
"textattack.c... | [((1103, 1130), 'textattack.commands.attack.attack_args_helpers.parse_model_from_args', 'parse_model_from_args', (['args'], {}), '(args)\n', (1124, 1130), False, 'from textattack.commands.attack.attack_args_helpers import add_dataset_args, add_model_args, parse_dataset_from_args, parse_model_from_args\n'), ((1149, 1178... |
#!/usr/bin/env python2.7
#
# PiCam SSTV Transmitterf
#
# Copyright (C) 2018 <NAME> <<EMAIL>>
# Released under GNU GPL v3 or later
#
# PiCamera API: https://picamera.readthedocs.io/en/release-1.12/api_camera.html
#
# This script is hacked together from the WenetPiCam class out of the Wenet project.
#
# Depe... | [
"traceback.format_exc",
"os.path.getsize",
"datetime.datetime.utcnow",
"picamera.PiCamera",
"time.sleep",
"os.path.isfile",
"subprocess.call",
"os.system",
"glob.glob"
] | [((2973, 2983), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (2981, 2983), False, 'from picamera import PiCamera\n'), ((5270, 5319), 'glob.glob', 'glob.glob', (["('%s_*.jpg' % self.temp_filename_prefix)"], {}), "('%s_*.jpg' % self.temp_filename_prefix)\n", (5279, 5319), False, 'import glob\n'), ((5690, 5737), 'os... |
# Copyright 2020 <NAME>, <NAME>, <NAME>, <NAME>, <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 la... | [
"utils.general.parse_gpu_ids",
"numpy.lib.pad",
"torch.cuda.is_available",
"torch.squeeze",
"os.path.exists",
"argparse.ArgumentParser",
"torch.unsqueeze",
"models.network_factory.get_network",
"torch.autograd.Variable",
"torchvision.transforms.Normalize",
"torch.nn.functional.relu",
"cv2.imre... | [((1053, 1124), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Reversing the cycle: single shot"""'}), "(description='Reversing the cycle: single shot')\n", (1076, 1124), False, 'import argparse\n'), ((2435, 2470), 'utils.general.parse_gpu_ids', 'general.parse_gpu_ids', (['args.gpu_ids']... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""test nb... | [
"pandas.read_pickle",
"msticpy.nbtools.ti_browser.get_ti_select_options",
"pathlib.Path",
"msticpy.nbtools.ti_browser.ti_details_display",
"pytest_check.is_in",
"pytest.fixture"
] | [((593, 623), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (607, 623), False, 'import pytest\n'), ((760, 783), 'pandas.read_pickle', 'pd.read_pickle', (['df_path'], {}), '(df_path)\n', (774, 783), True, 'import pandas as pd\n'), ((894, 927), 'msticpy.nbtools.ti_browser.get_... |
import pprint
import click
import fitz # pip install pymupdf
@click.command()
@click.argument("filepath", type=click.Path(exists=True))
def entrypoint(filepath):
pp = pprint.PrettyPrinter(indent=4)
with fitz.open(filepath) as doc:
pp.pprint(doc.metadata)
print(f"Scanned pages: {get_scanned_p... | [
"fitz.open",
"click.command",
"click.Path",
"pprint.PrettyPrinter"
] | [((66, 81), 'click.command', 'click.command', ([], {}), '()\n', (79, 81), False, 'import click\n'), ((175, 205), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (195, 205), False, 'import pprint\n'), ((215, 234), 'fitz.open', 'fitz.open', (['filepath'], {}), '(filepath)\n', (224... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from enocean.consolelogger import init_logging
from enocean.communicators.serialcommunicator import SerialCommunicator
from enocean.communicators.utils import send_to_tcp_socket
import sys
import traceback
try:
import queue
except ImportError:
import Queue as que... | [
"enocean.communicators.utils.send_to_tcp_socket",
"traceback.print_exc",
"enocean.communicators.serialcommunicator.SerialCommunicator",
"enocean.consolelogger.init_logging"
] | [((324, 338), 'enocean.consolelogger.init_logging', 'init_logging', ([], {}), '()\n', (336, 338), False, 'from enocean.consolelogger import init_logging\n'), ((354, 374), 'enocean.communicators.serialcommunicator.SerialCommunicator', 'SerialCommunicator', ([], {}), '()\n', (372, 374), False, 'from enocean.communicators... |
#!/usr/bin/env python
# Copyright 2018 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | [
"lib.logger.create",
"wget.download",
"lib.genesis.get_os_images_path",
"lib.config.Config",
"argparse.ArgumentParser",
"lib.logger.getlogger",
"lib.exception.UserException",
"lib.genesis.check_os_profile",
"sys.stdout.flush",
"hashlib.sha1"
] | [((1150, 1164), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (1162, 1164), False, 'import hashlib\n'), ((1452, 1470), 'lib.logger.getlogger', 'logger.getlogger', ([], {}), '()\n', (1468, 1470), True, 'import lib.logger as logger\n'), ((1601, 1620), 'lib.config.Config', 'Config', (['config_path'], {}), '(config_pat... |
import time
from kafka import KafkaProducer
import cv2
producer = KafkaProducer(bootstrap_servers=['10.252.133.3:9092'])
video = cv2.VideoCapture(1)
count =0
start_time = time.time()
if(video.isOpened()==False):
print("unable to read camera feed")
while(True):
success, frame = video.read()
resize = cv2.... | [
"cv2.imencode",
"kafka.KafkaProducer",
"cv2.VideoCapture",
"cv2.resize",
"time.time"
] | [((67, 121), 'kafka.KafkaProducer', 'KafkaProducer', ([], {'bootstrap_servers': "['10.252.133.3:9092']"}), "(bootstrap_servers=['10.252.133.3:9092'])\n", (80, 121), False, 'from kafka import KafkaProducer\n'), ((131, 150), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(1)'], {}), '(1)\n', (147, 150), False, 'import cv2\n'... |
import sqlite3
from flask import g
from app import app
DATABASE = './database.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
... | [
"app.app.open_resource",
"app.app.app_context",
"sqlite3.connect"
] | [((182, 207), 'sqlite3.connect', 'sqlite3.connect', (['DATABASE'], {}), '(DATABASE)\n', (197, 207), False, 'import sqlite3\n'), ((769, 786), 'app.app.app_context', 'app.app_context', ([], {}), '()\n', (784, 786), False, 'from app import app\n'), ((823, 864), 'app.app.open_resource', 'app.open_resource', (['"""schema.sq... |
"""
Lecture 15: Linear Programming
------------------------------
Linear programming is a method of optimization,
in this case minimization, of a set of parameters.
The goal is to find a vector
x in R^n
where given a vector
c in R^n
you want to minimize the scalar
product of x and c, given by
inner_product(x, c)
... | [
"flownetwork.FlowNetwork",
"scipy.optimize.linprog",
"graph.Graph"
] | [((1867, 1914), 'scipy.optimize.linprog', 'linprog', (['c', 'A_ub', 'b_ub'], {'method': '"""interior-point"""'}), "(c, A_ub, b_ub, method='interior-point')\n", (1874, 1914), False, 'from scipy.optimize import linprog\n'), ((2772, 2939), 'flownetwork.FlowNetwork', 'FlowNetwork', (['"""s"""', '"""t"""', "{('s', 'a'): 3, ... |
# 2019-11-19 19:43:48(JST)
# import collections
import math
import sys
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import a... | [
"sys.stdin.readline",
"math.sqrt"
] | [((433, 453), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (451, 453), False, 'import sys\n'), ((514, 526), 'math.sqrt', 'math.sqrt', (['n'], {}), '(n)\n', (523, 526), False, 'import math\n')] |
from unittest.mock import Mock, patch
import pytest
from requests import Response
from backend.common.frc_api import FRCAPI
from backend.common.sitevars.fms_api_secrets import (
ContentType as FMSApiSecretsContentType,
)
from backend.common.sitevars.fms_api_secrets import FMSApiSecrets
from backend.tasks_io.dataf... | [
"unittest.mock.Mock",
"backend.common.sitevars.fms_api_secrets.ContentType",
"unittest.mock.patch.object",
"pytest.fixture",
"backend.tasks_io.datafeeds.datafeed_fms_api.DatafeedFMSAPI"
] | [((487, 515), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (501, 515), False, 'import pytest\n'), ((687, 706), 'unittest.mock.Mock', 'Mock', ([], {'spec': 'Response'}), '(spec=Response)\n', (691, 706), False, 'from unittest.mock import Mock, patch\n'), ((861, 877), 'backend.tasks... |
from flask import Blueprint, session, redirect, url_for
babel_blueprint = Blueprint(
'babel',
__name__,
url_prefix="/babel"
)
@babel_blueprint.route('/<string:locale>')
def index(locale):
session['locale'] = locale
return redirect(url_for('blog.home'))
| [
"flask.Blueprint",
"flask.url_for"
] | [((75, 124), 'flask.Blueprint', 'Blueprint', (['"""babel"""', '__name__'], {'url_prefix': '"""/babel"""'}), "('babel', __name__, url_prefix='/babel')\n", (84, 124), False, 'from flask import Blueprint, session, redirect, url_for\n'), ((254, 274), 'flask.url_for', 'url_for', (['"""blog.home"""'], {}), "('blog.home')\n",... |
from datetime import datetime
import plotly.graph_objects as go
def viol_plot(d_from, cores_queued, cores_running, target, d_to='',
fig_out=''):
"""Violin distribution usage plot.
Parameters
-------
d_from: date str
Beginning of the query period, e.g. '2019-04-01T00:00:00'
c... | [
"plotly.graph_objects.Figure",
"datetime.datetime.now"
] | [((1153, 1164), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (1162, 1164), True, 'import plotly.graph_objects as go\n'), ((1078, 1092), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1090, 1092), False, 'from datetime import datetime\n')] |
from functools import reduce, partial
from operator import __rshift__
from typing import Mapping, Any, Union, Tuple, List
from hbutils.collection import nested_map
from hbutils.design import SingletonMark
from hbutils.string import truncate
from .base import BaseUnit, _to_unit, UnitProcessProxy, raw
from .build impor... | [
"functools.partial",
"hbutils.collection.nested_map",
"hbutils.design.SingletonMark"
] | [((14890, 14923), 'hbutils.design.SingletonMark', 'SingletonMark', (['"""CVALUE_UNIT_KEEP"""'], {}), "('CVALUE_UNIT_KEEP')\n", (14903, 14923), False, 'from hbutils.design import SingletonMark\n'), ((14943, 14983), 'hbutils.design.SingletonMark', 'SingletonMark', (['"""CVALUE_DEFAULT_REQUIRED"""'], {}), "('CVALUE_DEFAUL... |
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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 o... | [
"jax.random.PRNGKey",
"oryx.core.trace_util.stage",
"jax.numpy.sum",
"oryx.core.trace_util.get_shaped_aval",
"oryx.core.interpreters.propagate.propagate",
"jax.numpy.ndim",
"jax.tree_util.tree_flatten"
] | [((1987, 2004), 'jax.random.PRNGKey', 'random.PRNGKey', (['(0)'], {}), '(0)\n', (2001, 2004), False, 'from jax import random\n'), ((2091, 2121), 'jax.tree_util.tree_flatten', 'tree_util.tree_flatten', (['sample'], {}), '(sample)\n', (2113, 2121), False, 'from jax import tree_util\n'), ((2143, 2171), 'jax.tree_util.tree... |
"""
Title :RegularizationCallback.py
Description :Callback for custom weight regularization
Author :<NAME>
Date Created :23-03-2020
Date Modified :11-05-2020
version :1.1
python_version :3.6.6
"""
import keras
import numpy as np
from keras import backend as K
from laye... | [
"numpy.identity",
"numpy.ones",
"keras.backend.sum"
] | [((740, 755), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (747, 755), True, 'import numpy as np\n'), ((757, 771), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (768, 771), True, 'import numpy as np\n'), ((1133, 1179), 'keras.backend.sum', 'K.sum', (['current_weights[0][:, :, depth, neuron]'], {}... |
from django_filters import CharFilter
from django.utils.translation import gettext_lazy as _
from mapentity.filters import MapEntityFilterSet, PythonPolygonFilter
from geotrek.zoning.filters import ZoningFilterSet
from georiviere.maintenance.models import Intervention
from georiviere.watershed.filters import Watershe... | [
"mapentity.filters.PythonPolygonFilter",
"django.utils.translation.gettext_lazy"
] | [((430, 468), 'mapentity.filters.PythonPolygonFilter', 'PythonPolygonFilter', ([], {'field_name': '"""geom"""'}), "(field_name='geom')\n", (449, 468), False, 'from mapentity.filters import MapEntityFilterSet, PythonPolygonFilter\n'), ((497, 506), 'django.utils.translation.gettext_lazy', '_', (['"""Name"""'], {}), "('Na... |
from tests.cli_client.CLI import CLI
def main():
cli: CLI = CLI()
cli.mock_run()
if __name__ == "__main__":
main()
| [
"tests.cli_client.CLI.CLI"
] | [((66, 71), 'tests.cli_client.CLI.CLI', 'CLI', ([], {}), '()\n', (69, 71), False, 'from tests.cli_client.CLI import CLI\n')] |
from django.test import TestCase
from django.urls import reverse
from wagtail.contrib.settings.registry import Registry
from wagtail.tests.testapp.models import NotYetRegisteredSetting
from wagtail.tests.utils import WagtailTestUtils
class TestRegister(TestCase, WagtailTestUtils):
def setUp(self):
self.r... | [
"wagtail.contrib.settings.registry.Registry",
"django.urls.reverse"
] | [((330, 340), 'wagtail.contrib.settings.registry.Registry', 'Registry', ([], {}), '()\n', (338, 340), False, 'from wagtail.contrib.settings.registry import Registry\n'), ((735, 763), 'django.urls.reverse', 'reverse', (['"""wagtailadmin_home"""'], {}), "('wagtailadmin_home')\n", (742, 763), False, 'from django.urls impo... |
"""Print 'Hello World' every two seconds, using a coroutine."""
import trollius
from trollius import From
@trollius.coroutine
def greet_every_two_seconds():
while True:
print('Hello World')
yield From(trollius.sleep(2))
if __name__ == '__main__':
loop = trollius.get_event_loop()
try:
... | [
"trollius.sleep",
"trollius.get_event_loop"
] | [((283, 308), 'trollius.get_event_loop', 'trollius.get_event_loop', ([], {}), '()\n', (306, 308), False, 'import trollius\n'), ((224, 241), 'trollius.sleep', 'trollius.sleep', (['(2)'], {}), '(2)\n', (238, 241), False, 'import trollius\n')] |
# Copyright (c) 2014 Scality
#
# 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... | [
"cinder.i18n._LI",
"cinder.i18n._LW",
"re.compile",
"cinder.i18n._LE",
"oslo_concurrency.processutils.execute",
"cinder.volume.driver._attach_file",
"time.sleep",
"sys.exc_info",
"cinder.i18n._",
"six.reraise",
"cinder.volume.driver.delete_snapshot",
"oslo_log.log.getLogger",
"oslo_config.cf... | [((1350, 1377), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1367, 1377), True, 'from oslo_log import log as logging\n'), ((1662, 1737), 're.compile', 're.compile', (['"""^http://(\\\\d{1,3}\\\\.){3}\\\\d{1,3}(:\\\\d+)?/[a-zA-Z0-9\\\\-_\\\\/]*$"""'], {}), "('^http://(\\\\d{1,3}\\\... |
# 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 editing anomaly threshold configurations."""
from __future__ import print_function
from __future__ import division
from __fu... | [
"dashboard.common.request_handler.InvalidInputError",
"json.loads",
"json.dumps",
"dashboard.models.anomaly_config.AnomalyConfig.query"
] | [((2216, 2278), 'dashboard.common.request_handler.InvalidInputError', 'request_handler.InvalidInputError', (['"""No config contents given."""'], {}), "('No config contents given.')\n", (2249, 2278), False, 'from dashboard.common import request_handler\n'), ((2308, 2326), 'json.loads', 'json.loads', (['config'], {}), '(... |
# Volatility
# Copyright (C) 2009-2013 Volatility Foundation
# Copyright (C) <NAME> <<EMAIL>>
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version ... | [
"volatility.utils.load_as",
"volatility.obj.Object",
"volatility.obj.VolMagic",
"volatility.addrspace.BufferAddressSpace"
] | [((1330, 1370), 'volatility.utils.load_as', 'utils.load_as', (['config'], {'astype': '"""physical"""'}), "(config, astype='physical')\n", (1343, 1370), True, 'import volatility.utils as utils\n'), ((1390, 1411), 'volatility.utils.load_as', 'utils.load_as', (['config'], {}), '(config)\n', (1403, 1411), True, 'import vol... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 <NAME> <<EMAIL>>
"""USAGE: %(program)s MATRIX.mm [CLIP_DOCS] [CLIP_TERMS]
Check truncated SVD error for the algo in gensim, using a given corpus. This script
runs the decomposition with several internal parameters (number of requested factors,
iter... | [
"gensim.models.LsiModel",
"gensim.utils.FakeDict",
"sys.exit",
"numpy.linalg.norm",
"logging.info",
"numpy.save",
"numpy.multiply",
"bz2.BZ2File",
"gensim.corpora.MmCorpus",
"sys.stdout.flush",
"gensim.utils.grouper",
"time.time",
"logging.basicConfig",
"itertools.islice",
"numpy.diag",
... | [((2128, 2146), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2144, 2146), False, 'import sys\n'), ((2508, 2603), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',... |
from constants import *
from mobject.types.vectorized_mobject import VMobject
from utils.config_ops import digest_config
class ParametricFunction(VMobject):
CONFIG = {
"t_min": 0,
"t_max": 1,
"num_anchor_points": 100,
}
def __init__(self, function, **kwargs):
self.funct... | [
"mobject.types.vectorized_mobject.VMobject.__init__",
"utils.config_ops.digest_config"
] | [((343, 376), 'mobject.types.vectorized_mobject.VMobject.__init__', 'VMobject.__init__', (['self'], {}), '(self, **kwargs)\n', (360, 376), False, 'from mobject.types.vectorized_mobject import VMobject\n'), ((996, 1023), 'utils.config_ops.digest_config', 'digest_config', (['self', 'kwargs'], {}), '(self, kwargs)\n', (10... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | [
"pulumi.getter",
"pulumi.set",
"pulumi.ResourceOptions",
"pulumi.get"
] | [((4460, 4502), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""launchTemplateConfig"""'}), "(name='launchTemplateConfig')\n", (4473, 4502), False, 'import pulumi\n'), ((4964, 5013), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""targetCapacitySpecification"""'}), "(name='targetCapacitySpecification')\n", (497... |
from utils import json_request
irc_formatting = True
def format(number, sign = False):
if irc_formatting:
if sign:
return '\x02\x0304{:+}\x03\x02'.format(number)
else:
return '\x02\x0304{}\x03\x02'.format(number)
else:
if sign:
return '{:+}'.format(n... | [
"utils.json_request"
] | [((416, 466), 'utils.json_request', 'json_request', (['"""https://api.covid19api.com/summary"""'], {}), "('https://api.covid19api.com/summary')\n", (428, 466), False, 'from utils import json_request\n'), ((1080, 1214), 'utils.json_request', 'json_request', (['"""https://raw.githubusercontent.com/pcm-dpc/COVID-19/master... |
from flask import Flask
from test.chatelet.routes import chatelet
from extensions import mysql
app = Flask(__name__)
mysql.init_app(app)
app.register_blueprint(chatelet, url_prefix='/chatelet')
| [
"extensions.mysql.init_app",
"flask.Flask"
] | [((108, 123), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (113, 123), False, 'from flask import Flask\n'), ((125, 144), 'extensions.mysql.init_app', 'mysql.init_app', (['app'], {}), '(app)\n', (139, 144), False, 'from extensions import mysql\n')] |
from elasticsearch import Elasticsearch
es = Elasticsearch(['http://172.18.0.1:9200'])
docType = "doc"
def entitySearch(query):
indexName = "dbentityindex"
results=[]
###################################################
elasticResults=es.search(index=indexName,doc_type=docType, body={
... | [
"elasticsearch.Elasticsearch"
] | [((47, 88), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["['http://172.18.0.1:9200']"], {}), "(['http://172.18.0.1:9200'])\n", (60, 88), False, 'from elasticsearch import Elasticsearch\n')] |
# -*- coding: utf-8 -*-
import tensorflow as tf
import math
def multiplication_attention(query, doc, mask, name=None):
query = tf.expand_dims(query, axis=1)
query = tf.tile(query, [1, tf.shape(doc)[1], 1])
enc = tf.concat([doc, query], axis=2)
e = tf.layers.dense(enc, 1, kernel_initializer=tf.initializ... | [
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.reduce_sum",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.dropout",
"tensorflow.nn.softmax",
"tensorflow.zeros_initializer",
"tensorflow.reduce_mean",
"tensorflow.cast",
"tensorflow.concat",
"tensorflow.matmul",
"tensorflow.s... | [((132, 161), 'tensorflow.expand_dims', 'tf.expand_dims', (['query'], {'axis': '(1)'}), '(query, axis=1)\n', (146, 161), True, 'import tensorflow as tf\n'), ((225, 256), 'tensorflow.concat', 'tf.concat', (['[doc, query]'], {'axis': '(2)'}), '([doc, query], axis=2)\n', (234, 256), True, 'import tensorflow as tf\n'), ((4... |
from __future__ import unicode_literals
from django.db import models
from django.urls import reverse
class Style(models.Model):
image = models.ImageField(upload_to='styles/%Y/%m/%d/')
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class Photo(models.Model):
... | [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.urls.reverse",
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((143, 190), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""styles/%Y/%m/%d/"""'}), "(upload_to='styles/%Y/%m/%d/')\n", (160, 190), False, 'from django.db import models\n'), ((203, 235), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (... |
import glob
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
import fire
def _get_info_from_anaconda_info(info, split=":"):
info = info.strip("\n").replace(" ", "")
info_dict = {}
latest_key = ""
for line in info.splitlines():
if split in line:
... | [
"subprocess.check_output",
"os.path.exists",
"json.loads",
"pathlib.Path",
"pathlib.Path.home",
"os.environ.get",
"os.path.dirname",
"tempfile.NamedTemporaryFile",
"glob.glob"
] | [((2366, 2381), 'pathlib.Path', 'Path', (['cuda_home'], {}), '(cuda_home)\n', (2370, 2381), False, 'from pathlib import Path\n'), ((5378, 5393), 'pathlib.Path', 'Path', (['cuda_home'], {}), '(cuda_home)\n', (5382, 5393), False, 'from pathlib import Path\n'), ((697, 708), 'pathlib.Path.home', 'Path.home', ([], {}), '()\... |
import csv
import json
import sys
import argparse
import urllib.request
import logging
"""
This demonstration script fetches search results from the CAP cases endpoint and writes a subset of their fields to
a CSV file. It uses only the Python 3 standard library, so no additional installation is required.
... | [
"logging.getLogger",
"csv.writer",
"logging.basicConfig",
"argparse.ArgumentParser"
] | [((1232, 1263), 'logging.getLogger', 'logging.getLogger', (['"""api_to_csv"""'], {}), "('api_to_csv')\n", (1249, 1263), False, 'import logging\n'), ((2119, 2139), 'csv.writer', 'csv.writer', (['out_file'], {}), '(out_file)\n', (2129, 2139), False, 'import csv\n'), ((2753, 3028), 'argparse.ArgumentParser', 'argparse.Arg... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | [
"openstack.compute.v2.hypervisor.Hypervisor"
] | [((1316, 1339), 'openstack.compute.v2.hypervisor.Hypervisor', 'hypervisor.Hypervisor', ([], {}), '()\n', (1337, 1339), False, 'from openstack.compute.v2 import hypervisor\n'), ((1699, 1731), 'openstack.compute.v2.hypervisor.Hypervisor', 'hypervisor.Hypervisor', ([], {}), '(**EXAMPLE)\n', (1720, 1731), False, 'from open... |
import os
import tempfile
import unittest
from datetime import datetime
from unittest.mock import Mock
from collection_manager.entities import Collection
from collection_manager.entities.exceptions import CollectionConfigParsingError, CollectionConfigFileNotFoundError, \
RelativePathCollectionError, ConflictingPat... | [
"tempfile.TemporaryDirectory",
"unittest.mock.Mock",
"os.path.join",
"os.path.dirname",
"common.async_test_utils.AsyncTestUtils.AsyncMock",
"collection_manager.services.CollectionWatcher._run_periodically",
"datetime.datetime.now",
"tempfile.NamedTemporaryFile",
"common.async_test_utils.AsyncTestUti... | [((6858, 6919), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', (['"""w+b"""'], {'buffering': '(0)', 'delete': '(False)'}), "('w+b', buffering=0, delete=False)\n", (6885, 6919), False, 'import tempfile\n'), ((6942, 6971), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (696... |
#!/usr/bin/env python
"""Updates FileCheck checks in MIR tests.
This script is a utility to update MIR based tests with new FileCheck
patterns.
The checks added by this script will cover the entire body of each
function it handles. Virtual registers used are given names via
FileCheck patterns, so if you do want to c... | [
"UpdateTestChecks.common.MARCH_ARG_RE.search",
"UpdateTestChecks.common.RUN_LINE_RE.match",
"UpdateTestChecks.common.TRIPLE_IR_RE.match",
"argparse.ArgumentParser",
"re.compile",
"UpdateTestChecks.common.CHECK_RE.match",
"UpdateTestChecks.common.TRIPLE_ARG_RE.search",
"os.path.basename",
"UpdateTest... | [((952, 1000), 're.compile', 're.compile', (['""" *name: *(?P<func>[A-Za-z0-9_.-]+)"""'], {}), "(' *name: *(?P<func>[A-Za-z0-9_.-]+)')\n", (962, 1000), False, 'import re\n'), ((1022, 1048), 're.compile', 're.compile', (['""" *body: *\\\\|"""'], {}), "(' *body: *\\\\|')\n", (1032, 1048), False, 'import re\n'), ((1070, 1... |
from operator import add, mul
import pytest
from dask.diagnostics import ProgressBar
from dask.diagnostics.progress import format_time
from dask.threaded import get
from dask.context import _globals
dsk = {'a': 1,
'b': 2,
'c': (add, 'a', 'b'),
'd': (mul, 'a', 'b'),
'e': (mul, 'c', 'd')}
... | [
"dask.diagnostics.progress.format_time",
"dask.cache.Cache",
"pytest.importorskip",
"dask.diagnostics.ProgressBar",
"dask.threaded.get"
] | [((1891, 1920), 'pytest.importorskip', 'pytest.importorskip', (['"""cachey"""'], {}), "('cachey')\n", (1910, 1920), False, 'import pytest\n'), ((1991, 1999), 'dask.cache.Cache', 'Cache', (['c'], {}), '(c)\n', (1996, 1999), False, 'from dask.cache import Cache\n'), ((2598, 2611), 'dask.diagnostics.ProgressBar', 'Progres... |
import pytest
from django.db.models import Q
from helper import TestMigrations
class TestWithShackdataBase(TestMigrations):
app = "bookkeeping"
migrate_fixtures = ["tests/fixtures/test_shackspace_transactions.json"]
migrate_from = "0012_auto_20180617_1926"
@pytest.mark.xfail
@pytest.mark.django_db
class... | [
"byro.bookkeeping.models.Booking.objects.count",
"byro.bookkeeping.models.Transaction.objects.count",
"byro.bookkeeping.models.Booking.objects.filter",
"byro.bookkeeping.models.Account.objects.filter",
"django.db.models.Q",
"byro.bookkeeping.models.Account.objects.exclude"
] | [((2341, 2368), 'byro.bookkeeping.models.Transaction.objects.count', 'Transaction.objects.count', ([], {}), '()\n', (2366, 2368), False, 'from byro.bookkeeping.models import Transaction\n'), ((2683, 2706), 'byro.bookkeeping.models.Booking.objects.count', 'Booking.objects.count', ([], {}), '()\n', (2704, 2706), False, '... |
#!/usr/bin/env python3
from bisect import bisect_left
from pathlib import Path
import boto3
class S3Sync:
"""Class needed for syncing local direcory to a S3 bucket"""
def __init__(self):
"""Initialize class with boto3 client"""
self.s3 = boto3.client("s3")
def upload_object(self, source... | [
"boto3.client"
] | [((266, 284), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (278, 284), False, 'import boto3\n')] |
"""Basic result reporters."""
import csv
import json
import pickle
import signal
from collections import defaultdict
from itertools import chain
from multiprocessing import Process, SimpleQueue
from xml.sax.saxutils import escape as xml_escape
from snakeoil import pickling
from snakeoil.decorators import coroutine
f... | [
"signal.signal",
"json.loads",
"pickle.dump",
"multiprocessing.SimpleQueue",
"multiprocessing.Process",
"csv.writer",
"snakeoil.pickling.iter_stream",
"json.dumps",
"collections.defaultdict",
"xml.sax.saxutils.escape"
] | [((990, 1003), 'multiprocessing.SimpleQueue', 'SimpleQueue', ([], {}), '()\n', (1001, 1003), False, 'from multiprocessing import Process, SimpleQueue\n'), ((1034, 1078), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_DFL'], {}), '(signal.SIGINT, signal.SIG_DFL)\n', (1047, 1078), False, 'import signal\... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | [
"numpy.abs",
"numpy.isclose",
"cirq.rx",
"itertools.product",
"cirq.LineQubit",
"ast.literal_eval",
"cirq.Circuit",
"numpy.dot",
"numpy.sum",
"cirq.Simulator"
] | [((3897, 3930), 'ast.literal_eval', 'ast.literal_eval', (['protocol_string'], {}), '(protocol_string)\n', (3913, 3930), False, 'import ast\n'), ((5228, 5244), 'cirq.Simulator', 'cirq.Simulator', ([], {}), '()\n', (5242, 5244), False, 'import cirq\n'), ((6908, 6922), 'cirq.Circuit', 'cirq.Circuit', ([], {}), '()\n', (69... |
from sympy.external import import_module
from sympy.utilities import pytest
antlr4 = import_module("antlr4")
# disable tests if antlr4-python*-runtime is not present
if antlr4:
disabled = True
def test_no_import():
from sympy.parsing.latex import parse_latex
with pytest.raises(ImportError):
pa... | [
"sympy.external.import_module",
"sympy.utilities.pytest.raises",
"sympy.parsing.latex.parse_latex"
] | [((87, 110), 'sympy.external.import_module', 'import_module', (['"""antlr4"""'], {}), "('antlr4')\n", (100, 110), False, 'from sympy.external import import_module\n'), ((282, 308), 'sympy.utilities.pytest.raises', 'pytest.raises', (['ImportError'], {}), '(ImportError)\n', (295, 308), False, 'from sympy.utilities import... |
"""LVTUBEN URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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-based... | [
"django.urls.path",
"django.urls.include"
] | [((901, 933), 'django.urls.path', 'path', (['""""""', 'index'], {'name': '"""navigate"""'}), "('', index, name='navigate')\n", (905, 933), False, 'from django.urls import include, path\n'), ((1031, 1066), 'django.urls.path', 'path', (['"""login/"""', 'login'], {'name': '"""login"""'}), "('login/', login, name='login')\... |
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | [
"sahara.context.Context",
"fixtures.FakeLogger",
"random.Random",
"testtools.ExpectedException",
"sahara.context.ctx",
"sahara.context.set_ctx",
"sahara.context._wrapper",
"six.text_type",
"mock.MagicMock",
"sahara.context.ThreadGroup"
] | [((726, 741), 'random.Random', 'random.Random', ([], {}), '()\n', (739, 741), False, 'import random\n'), ((914, 1005), 'sahara.context.Context', 'context.Context', (['"""test_user"""', '"""tenant_1"""', '"""test_auth_token"""', '{}'], {'remote_semaphore': '"""123"""'}), "('test_user', 'tenant_1', 'test_auth_token', {},... |
from typing import List
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Enum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.constants import Role, Gender, Category
from app.database import Base
from app.utils.custom_type import ArrayOfEnum
# User Model Class
c... | [
"sqlalchemy.orm.relationship",
"sqlalchemy.DateTime",
"sqlalchemy.sql.func.now",
"sqlalchemy.ForeignKey",
"sqlalchemy.Enum",
"sqlalchemy.Column"
] | [((374, 419), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)', 'index': '(True)'}), '(Integer, primary_key=True, index=True)\n', (380, 419), False, 'from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Enum\n'), ((435, 474), 'sqlalchemy.Column', 'Column', (['String'], {'unique': '... |
import json
import torch
import numpy as np
from typing import Optional
from datasets.arrow_dataset import Dataset
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from seq2seq.utils.dataset import DataTrainingArguments, normalize, serialize_schema
from seq2seq.utils.trainer import Seq2SeqTraine... | [
"numpy.where",
"seq2seq.utils.dataset.serialize_schema",
"seq2seq.utils.trainer.EvalPrediction"
] | [((909, 1492), 'seq2seq.utils.dataset.serialize_schema', 'serialize_schema', ([], {'question': "ex['question']", 'db_path': "ex['db_path']", 'db_id': "ex['db_id']", 'db_column_names': "ex['db_column_names']", 'db_table_names': "ex['db_table_names']", 'schema_serialization_type': 'data_training_args.schema_serialization... |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | [
"pynini.lib.pynutil.insert",
"pynini.lib.pynutil.delete",
"nemo_text_processing.text_normalization.de.taggers.decimal.get_quantity",
"pynini.accep",
"pynini.cross"
] | [((1582, 1606), 'pynini.lib.pynutil.delete', 'pynutil.delete', (['""" komma"""'], {}), "(' komma')\n", (1596, 1606), False, 'from pynini.lib import pynutil\n'), ((2510, 2549), 'pynini.lib.pynutil.insert', 'pynutil.insert', (['""" preserve_order: true"""'], {}), "(' preserve_order: true')\n", (2524, 2549), False, 'from ... |
# port "loss analysis v5.xlsx" by <NAME> to python3
import openpyxl
import numpy as np
import sys
import os
import re
from collections import OrderedDict
import matplotlib.pyplot as plt
import warnings
# modules for this package
import analysis
from scipy import constants
T = 300 # TODO: make optional input?
Vth = ... | [
"numpy.polyfit",
"analysis.Rs_calc_2",
"numpy.array",
"numpy.isfinite",
"numpy.genfromtxt",
"analysis.find_nearest",
"analysis.ideal_FF",
"analysis.ideal_FF_series_shunt",
"numpy.dot",
"numpy.polyval",
"analysis.FF_loss_series",
"warnings.simplefilter",
"analysis.ideality_factor",
"collect... | [((27015, 27054), 'os.path.join', 'os.path.join', (['os.pardir', '"""example_cell"""'], {}), "(os.pardir, 'example_cell')\n", (27027, 27054), False, 'import os\n'), ((571, 582), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (579, 582), True, 'import numpy as np\n'), ((1371, 1407), 'numpy.trapz', 'np.trapz', (['(self... |
import os
for i in range(0,1):
# randomly generate flag and lambda expression
os.system("python3 compiler.py > expr.h")
# create directory
dir_name = "chall%u" % i
os.mkdir(dir_name)
# generate binary and move it to directory
os.system("gcc -Wall -s main.c -o lambda")
os.system("rm expr.h")
os.system("python3... | [
"os.system",
"os.mkdir"
] | [((81, 122), 'os.system', 'os.system', (['"""python3 compiler.py > expr.h"""'], {}), "('python3 compiler.py > expr.h')\n", (90, 122), False, 'import os\n'), ((170, 188), 'os.mkdir', 'os.mkdir', (['dir_name'], {}), '(dir_name)\n', (178, 188), False, 'import os\n'), ((234, 276), 'os.system', 'os.system', (['"""gcc -Wall ... |
import os
import numpy as np
import pkg_resources
from sklearn.pipeline import make_pipeline
import bob.io.base
import bob.io.image
from bob.pipelines.sample_loaders import AnnotationsLoader, CSVToSampleLoader
def test_sample_loader():
path = pkg_resources.resource_filename(
__name__, os.path.join("da... | [
"bob.pipelines.sample_loaders.CSVToSampleLoader",
"numpy.alltrue",
"os.path.join",
"sklearn.pipeline.make_pipeline",
"bob.pipelines.sample_loaders.AnnotationsLoader"
] | [((363, 466), 'bob.pipelines.sample_loaders.CSVToSampleLoader', 'CSVToSampleLoader', ([], {'data_loader': 'bob.io.base.load', 'dataset_original_directory': 'path', 'extension': '""".pgm"""'}), "(data_loader=bob.io.base.load, dataset_original_directory=\n path, extension='.pgm')\n", (380, 466), False, 'from bob.pipel... |
###############################################################################
# Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC.
#
# Produced at the Lawrence Livermore National Laboratory
#
# LLNL-CODE-716457
#
# All rights reserved.
#
# This file is part of Ascent.
#
# For details, see: http://asc... | [
"flow.Workspace",
"flow.wrap_function",
"flow.Workspace.register_filter_type",
"unittest.main",
"flow.Workspace.clear_supported_filter_types"
] | [((5708, 5723), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5721, 5723), False, 'import unittest\n'), ((4013, 4058), 'flow.Workspace.clear_supported_filter_types', 'flow.Workspace.clear_supported_filter_types', ([], {}), '()\n', (4056, 4058), False, 'import flow\n'), ((4067, 4113), 'flow.Workspace.register_fil... |
# Copyright 2015 IBM Corp.
#
# 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 agree... | [
"datetime.datetime",
"gettext.install",
"magnum.objects.base.MagnumObjectRegistry.obj_classes",
"mock.patch",
"magnum.common.context.RequestContext",
"oslo_versionedobjects.fixture.ObjectVersionChecker",
"magnum.objects.base.MagnumObjectSerializer",
"magnum.objects.base.MagnumObjectRegistry.register_i... | [((925, 950), 'gettext.install', 'gettext.install', (['"""magnum"""'], {}), "('magnum')\n", (940, 950), False, 'import gettext\n'), ((2287, 2331), 'magnum.objects.base.MagnumObjectRegistry.register_if', 'base.MagnumObjectRegistry.register_if', (['(False)'], {}), '(False)\n', (2324, 2331), False, 'from magnum.objects im... |
#!/usr/bin/env python3
# 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.
"""
Utilities that are useful for Mephisto-related scripts.
"""
from mephisto.abstractions.databases.local_database impo... | [
"mephisto.abstractions.databases.local_database.LocalMephistoDB",
"mephisto.operations.utils.get_mock_requester",
"mephisto.operations.utils.get_root_data_dir",
"os.path.join",
"omegaconf.OmegaConf.to_yaml",
"mephisto.abstractions.databases.local_singleton_database.MephistoSingletonDB"
] | [((1596, 1633), 'os.path.join', 'os.path.join', (['datapath', '"""database.db"""'], {}), "(datapath, 'database.db')\n", (1608, 1633), False, 'import os\n'), ((1555, 1574), 'mephisto.operations.utils.get_root_data_dir', 'get_root_data_dir', ([], {}), '()\n', (1572, 1574), False, 'from mephisto.operations.utils import ge... |
import sys
import os
import asyncio
import dscframework
import json
import keras
from keras.models import load_model
from data import build_dataset
import numpy as np
version = 1
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
model = load_model(("export/mdl_v%d.h5")%(version))
async def on_facedetect(head, data):
print... | [
"dscframework.Client",
"asyncio.get_event_loop",
"keras.models.load_model",
"json.dumps"
] | [((229, 270), 'keras.models.load_model', 'load_model', (["('export/mdl_v%d.h5' % version)"], {}), "('export/mdl_v%d.h5' % version)\n", (239, 270), False, 'from keras.models import load_model\n'), ((703, 745), 'dscframework.Client', 'dscframework.Client', (['"""ws://localhost:8080"""'], {}), "('ws://localhost:8080')\n",... |
import contextlib
import math
from collections import defaultdict
from time import perf_counter
from warnings import filterwarnings
import numpy
import dask
from dask.base import tokenize
from dask.dataframe.core import new_dd_object
from dask.distributed import Client, performance_report, wait
from dask.utils import... | [
"time.sleep",
"dask.distributed.wait",
"dask.base.tokenize",
"numpy.arange",
"time.perf_counter",
"dask.utils.format_bytes",
"numpy.random.seed",
"numpy.concatenate",
"numpy.random.permutation",
"dask.config.set",
"dask_cuda.utils.all_to_all",
"dask.distributed.performance_report",
"dask.uti... | [((976, 1003), 'numpy.random.seed', 'xp.random.seed', (['(2 ** 32 - 1)'], {}), '(2 ** 32 - 1)\n', (990, 1003), True, 'import numpy as xp\n'), ((4135, 4178), 'dask.dataframe.core.new_dd_object', 'new_dd_object', (['graph', 'name', 'meta', 'divisions'], {}), '(graph, name, meta, divisions)\n', (4148, 4178), False, 'from ... |
import torch
import pdb
import os
from torch.nn import functional as F
from argparse import ArgumentParser
import pytorch_lightning as pl
from pl_examples.basic_examples.mnist_datamodule import MNISTDataModule
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks.model_checkpoint impo... | [
"argparse.ArgumentParser",
"torch.device",
"torch.load",
"torch.stack",
"torch.argmax",
"os.path.isfile",
"pytorch_lightning.loggers.TensorBoardLogger",
"pytorch_lightning.Trainer",
"torch.nn.Linear",
"torch.nn.functional.cross_entropy",
"pytorch_lightning.callbacks.model_checkpoint.ModelCheckpo... | [((2484, 2500), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (2498, 2500), False, 'from argparse import ArgumentParser\n'), ((2600, 2614), 'shopty.ShoptyConfig', 'ShoptyConfig', ([], {}), '()\n', (2612, 2614), False, 'from shopty import ShoptyConfig\n'), ((2873, 2905), 'pl_examples.basic_examples.mnis... |
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
import torch
from layers.attention import MultiHeadedAttention
from layers.rezero import RezeroConnection
class Encoder(nn.Module):
def __init__(self, src_embed_size, ans_embed_size, hidden_size, dropout, bidir, n_head):
... | [
"torch.nn.MaxPool1d",
"layers.attention.MultiHeadedAttention",
"layers.rezero.RezeroConnection",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.Linear",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.nn.GRU"
] | [((387, 402), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', (['(4)'], {}), '(4)\n', (399, 402), True, 'import torch.nn as nn\n'), ((527, 630), 'torch.nn.GRU', 'nn.GRU', (['src_embed_size', 'gru_hidden_size', '(1)'], {'batch_first': '(True)', 'dropout': 'dropout', 'bidirectional': 'bidir'}), '(src_embed_size, gru_hidden_size, 1... |
#! /etc/bin/env python3
"""
transparent_images.py
Converts a RGB image to a RGBA image with transparency,
depending on colors in each of the four corners of the image.
"""
from collections import Counter
from glob import glob
from os import chdir, makedirs, path
import sys
from matplotlib.ima... | [
"os.path.exists",
"PIL.Image.open",
"PySimpleGUI.Popup",
"os.makedirs",
"PySimpleGUI.FolderBrowse",
"PySimpleGUI.In",
"os.path.splitext",
"matplotlib.image.imsave",
"PySimpleGUI.Text",
"os.chdir",
"numpy.array",
"PySimpleGUI.CloseButton",
"collections.Counter",
"PySimpleGUI.Window",
"glo... | [((722, 764), 'PySimpleGUI.Popup', 'sg.Popup', (['"""Cancel"""', '"""No filename supplied"""'], {}), "('Cancel', 'No filename supplied')\n", (730, 764), True, 'import PySimpleGUI as sg\n'), ((874, 886), 'os.chdir', 'chdir', (['fname'], {}), '(fname)\n', (879, 886), False, 'from os import chdir, makedirs, path\n'), ((90... |
import sqlalchemy
from sqlalchemy import Column, String, Integer, Float, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import requests
import json
from flask import Flask
Base = declarative_base()
engine = sqlalchemy.create_engine('postgres:/... | [
"sqlalchemy.orm.relationship",
"sqlalchemy.orm.sessionmaker",
"json.loads",
"sqlalchemy.create_engine",
"sqlalchemy.ForeignKey",
"requests.get",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Column"
] | [((256, 274), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (272, 274), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((284, 341), 'sqlalchemy.create_engine', 'sqlalchemy.create_engine', (['"""postgres://postgres@/postgres"""'], {}), "('postgres://postgres@/... |
from typing import List, Union, Optional
from dataclasses import dataclass, field
QUEUED = "QUEUED"
RECEIVED = "RECEIVED"
STARTED = "STARTED"
SUCCEEDED = "SUCCEEDED"
FAILED = "FAILED"
REJECTED = "REJECTED"
REVOKED = "REVOKED"
RETRY = "RETRY"
# CUSTOM STATES
RECOVERED = "RECOVERED" # Succeeded after many retries
CRIT... | [
"dataclasses.dataclass",
"dataclasses.field"
] | [((1937, 1948), 'dataclasses.dataclass', 'dataclass', ([], {}), '()\n', (1946, 1948), False, 'from dataclasses import dataclass, field\n'), ((4168, 4179), 'dataclasses.dataclass', 'dataclass', ([], {}), '()\n', (4177, 4179), False, 'from dataclasses import dataclass, field\n'), ((4525, 4536), 'dataclasses.dataclass', '... |
# Python program to draw square
# using Turtle Programming
import turtle
skk = turtle.Turtle()
for i in range(4):
skk.forward(50)
skk.right(90)
turtle.done()
# Python program to draw star
# using Turtle Programming
import turtle
star = turtle.Turtle()
star.right(75)
star.forward(100)
for i in range(4):
star.r... | [
"turtle.done",
"turtle.Turtle"
] | [((79, 94), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (92, 94), False, 'import turtle\n'), ((149, 162), 'turtle.done', 'turtle.done', ([], {}), '()\n', (160, 162), False, 'import turtle\n'), ((243, 258), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (256, 258), False, 'import turtle\n'), ((351, 364), 't... |
#!/usr/bin/env python3
import rospy
# Because of transformations
import tf_conversions
import tf2_ros
from geometry_msgs.msg import TransformStamped, PoseStamped, Quaternion
def handle_myo_pose(msg):
br = tf2_ros.TransformBroadcaster()
t = TransformStamped()
t.header.stamp = rospy.Time.now()
t.head... | [
"geometry_msgs.msg.TransformStamped",
"rospy.init_node",
"tf2_ros.TransformBroadcaster",
"rospy.Time.now",
"geometry_msgs.msg.Quaternion",
"rospy.spin",
"rospy.Subscriber"
] | [((213, 243), 'tf2_ros.TransformBroadcaster', 'tf2_ros.TransformBroadcaster', ([], {}), '()\n', (241, 243), False, 'import tf2_ros\n'), ((252, 270), 'geometry_msgs.msg.TransformStamped', 'TransformStamped', ([], {}), '()\n', (268, 270), False, 'from geometry_msgs.msg import TransformStamped, PoseStamped, Quaternion\n')... |
import unittest
from problems.arr import smallest_k1
class Test_SmallestK1(unittest.TestCase):
def setUp(self):
pass
def test_none(self):
arr = None
k = 3
actual = smallest_k1(arr, k)
expected = None
assert actual == expected
def test_case1(self):
... | [
"problems.arr.smallest_k1"
] | [((210, 229), 'problems.arr.smallest_k1', 'smallest_k1', (['arr', 'k'], {}), '(arr, k)\n', (221, 229), False, 'from problems.arr import smallest_k1\n'), ((392, 411), 'problems.arr.smallest_k1', 'smallest_k1', (['arr', 'k'], {}), '(arr, k)\n', (403, 411), False, 'from problems.arr import smallest_k1\n'), ((595, 614), 'p... |
from dataclasses import dataclass, field
import xleapp.templating as templating
from xleapp._authors import __authors__, __contributors__
from ..html import Contributor, HtmlPage, Template
@dataclass
class Index(HtmlPage):
"""Main index page for HTML report
Attributes:
authors (list): list of auth... | [
"dataclasses.field",
"xleapp.templating.get_contributors"
] | [((416, 433), 'dataclasses.field', 'field', ([], {'init': '(False)'}), '(init=False)\n', (421, 433), False, 'from dataclasses import dataclass, field\n'), ((472, 489), 'dataclasses.field', 'field', ([], {'init': '(False)'}), '(init=False)\n', (477, 489), False, 'from dataclasses import dataclass, field\n'), ((551, 591)... |
import time
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
import sklearn as sk
import numpy as np
from sklearn import svm
from sklearn import naive_bayes
from sklearn import tree
from sklearn import neighbors
from sklearn import ensemble
from sklearn import linear_model
f... | [
"time.time",
"pandas.plotting.register_matplotlib_converters"
] | [((1006, 1038), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (1036, 1038), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((3530, 3541), 'time.time', 'time.time', ([], {}), '()\n', (3539, 3541), False, 'import time\n'), ((3698, 3709), 'ti... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2019-08-03 15:25:12
# Project: news_qq
from pyspider.libs.base_handler import *
import re
import pymysql
import pymongo
# 文章正则
pattern_finance = re.compile('^(http|https)://finance.*')
pattern_artical = re.compile('^(http|https)://(.*?)-\d{8}.html(.*)')
pat... | [
"re.compile",
"pymysql.connect",
"re.match",
"pymongo.MongoClient",
"re.search"
] | [((208, 247), 're.compile', 're.compile', (['"""^(http|https)://finance.*"""'], {}), "('^(http|https)://finance.*')\n", (218, 247), False, 'import re\n'), ((266, 317), 're.compile', 're.compile', (['"""^(http|https)://(.*?)-\\\\d{8}.html(.*)"""'], {}), "('^(http|https)://(.*?)-\\\\d{8}.html(.*)')\n", (276, 317), False,... |
""" Factory methods to build Data objects from files
Implementation notes:
Each factory method conforms to the folowing structure, which
helps the GUI Frontend easily load data:
1) The first argument is a file name to open
2) The return value is a Data object
3) The function should be decorated with data_factory a... | [
"os.stat",
"glue.backends.get_timer",
"os.path.splitext",
"os.path.split",
"glue.core.contracts.contract",
"glue.config.data_factory",
"glue.qglue.parse_data",
"warnings.warn",
"glue.utils.as_list",
"os.path.abspath",
"glue.config.auto_refresh"
] | [((5974, 6068), 'glue.core.contracts.contract', 'contract', ([], {'path': '"""string"""', 'factory': '"""callable|None"""', 'returns': '"""inst($Data)|list(inst($Data))"""'}), "(path='string', factory='callable|None', returns=\n 'inst($Data)|list(inst($Data))')\n", (5982, 6068), False, 'from glue.core.contracts impo... |
import tensorflow as tf
POOLED_H = 7
POOLED_W = 7
def conv(name, inputs, nums_out, k_size, strides):
nums_in = inputs.shape[-1]
with tf.variable_scope(name):
W = tf.get_variable("W", [k_size, k_size, nums_in, nums_out], initializer=tf.random_normal_initializer(mean=0, stddev=0.01))
b = tf.get_v... | [
"tensorflow.nn.conv2d",
"tensorflow.nn.max_pool",
"tensorflow.variable_scope",
"tensorflow.nn.relu",
"tensorflow.random_normal_initializer",
"tensorflow.concat",
"tensorflow.image.crop_and_resize",
"tensorflow.exp",
"tensorflow.matmul",
"tensorflow.constant_initializer",
"tensorflow.square",
"... | [((554, 572), 'tensorflow.nn.relu', 'tf.nn.relu', (['inputs'], {}), '(inputs)\n', (564, 572), True, 'import tensorflow as tf\n'), ((610, 668), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['inputs', '[1, 2, 2, 1]', '[1, 2, 2, 1]', '"""SAME"""'], {}), "(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n", (624, 668), True, '... |
from flappy import _core
from flappy.geom import Matrix
class SpreadMethod(object):
PAD = 'pad'
REPEAT = 'repeat'
REFLECT = 'reflect'
_INT_MAP = {
PAD : 0,
REPEAT : 1,
REFLECT : 2,
}
class InterpolationMethod(object):
RGB = 'rgb'
LIN... | [
"flappy._core._Graphics.beginBitmapFill",
"flappy._core._Graphics.__init__",
"flappy.geom.Matrix",
"flappy._core._Graphics._beginGradientFill",
"flappy._core._Graphics.drawPath"
] | [((1619, 1656), 'flappy._core._Graphics.__init__', '_core._Graphics.__init__', (['self', 'owner'], {}), '(self, owner)\n', (1643, 1656), False, 'from flappy import _core\n'), ((1783, 1849), 'flappy._core._Graphics.beginBitmapFill', '_core._Graphics.beginBitmapFill', (['self', 'bitmap', 'mat', 'repeat', 'smooth'], {}), ... |
#!/usr/bin/env python3
# -*- coding = utf-8 -*-
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
def binary_focal_loss(gt, pred, *, gamma = 2.0, alpha = 0.25):
"""Implementation of binary focal loss.
This is the binary focal loss function from the paper on focal losses,
`... | [
"tensorflow.keras.backend.log",
"tensorflow.keras.backend.mean",
"tensorflow.keras.backend.epsilon",
"tensorflow.keras.backend.pow",
"tensorflow.cast"
] | [((1254, 1288), 'tensorflow.keras.backend.mean', 'K.mean', (['(cross_entropy + focal_loss)'], {}), '(cross_entropy + focal_loss)\n', (1260, 1288), True, 'from tensorflow.keras import backend as K\n'), ((2263, 2281), 'tensorflow.keras.backend.mean', 'K.mean', (['focal_loss'], {}), '(focal_loss)\n', (2269, 2281), True, '... |
#!/home/mark/Documents/Python-projects/django/IG-clone/virtual/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| [
"django.core.management.execute_from_command_line"
] | [((141, 179), 'django.core.management.execute_from_command_line', 'management.execute_from_command_line', ([], {}), '()\n', (177, 179), False, 'from django.core import management\n')] |
import pytest
from asdf import config_context, get_config
from asdf.asdf import AsdfFile, SerializationContext, open_asdf
from asdf.exceptions import AsdfWarning
from asdf.extension import AsdfExtensionList, ExtensionManager, ExtensionProxy
from asdf.tests.helpers import assert_no_warnings, yaml_to_asdf
from asdf.vers... | [
"asdf.extension.ExtensionProxy",
"asdf.extension.AsdfExtensionList",
"asdf.tests.helpers.yaml_to_asdf",
"asdf.tests.helpers.assert_no_warnings",
"pytest.warns",
"asdf.asdf.SerializationContext",
"pytest.raises",
"asdf.config_context",
"asdf.asdf.AsdfFile",
"asdf.versioning.AsdfVersion",
"asdf.as... | [((2883, 2893), 'asdf.asdf.AsdfFile', 'AsdfFile', ([], {}), '()\n', (2891, 2893), False, 'from asdf.asdf import AsdfFile, SerializationContext, open_asdf\n'), ((4263, 4329), 'asdf.asdf.AsdfFile', 'AsdfFile', ([], {'version': '"""1.5.0"""', 'extensions': '[extension_with_requirement]'}), "(version='1.5.0', extensions=[e... |
import requests
import re
#data = requests.get('http://dbpedia.org/data/Alice_and_Bob.json').json()
#print(data)
def getNumberOfLinks(url):
ret = 0
try:
url_json = str(url)+".json"
data = requests.get(url_json).json()
datastr = str(data);
# print(datastr)
ret = datastr... | [
"re.sub",
"requests.get"
] | [((215, 237), 'requests.get', 'requests.get', (['url_json'], {}), '(url_json)\n', (227, 237), False, 'import requests\n'), ((826, 849), 're.sub', 're.sub', (['""","""', '""" """', 'lines'], {}), "(',', ' ', lines)\n", (832, 849), False, 'import re\n')] |
#!/usr/bin/env python3
import unittest as ut
import subtest_fix
import os
import sys
import glob
import argparse
import copy
import tempfile
from itertools import combinations
import c4.cmany as cmany
import c4.cmany.util as util
import c4.cmany.main as main
import c4.cmany.cmake as cmake
from multiprocessing import... | [
"c4.cmany.util.setcwd",
"sys.path.insert",
"c4.cmany.System.default",
"c4.cmany.BuildType",
"multiprocessing.cpu_count",
"copy.deepcopy",
"unittest.main",
"c4.cmany.main.cmds.items",
"os.remove",
"c4.cmany.BuildType.default",
"os.path.exists",
"c4.cmany.util.runsyscmd",
"glob.glob",
"c4.cm... | [((418, 444), 'sys.path.insert', 'sys.path.insert', (['(0)', 'srcdir'], {}), '(0, srcdir)\n', (433, 444), False, 'import sys\n'), ((521, 546), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (536, 546), False, 'import os\n'), ((562, 606), 'os.environ.get', 'os.environ.get', (['"""CMANY_TEST_CO... |
# Copyright (c) 2021, Intel Corporation
#
# SPDX-License-Identifier: BSD-3-Clause
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (AutoMinorLocator, FuncFormatter, MaxNLocator,
For... | [
"matplotlib.ticker.LogLocator",
"matplotlib.pyplot.ylabel",
"numpy.array",
"matplotlib.ticker.MaxNLocator",
"matplotlib.ticker.AutoMinorLocator",
"numpy.histogram",
"numpy.full_like",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pyplot.close",
"numpy.issubdtype",
"matplotlib.pyplot.savefig",
... | [((108, 122), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (115, 122), True, 'import matplotlib as mpl\n'), ((595, 626), 'numpy.histogram', 'np.histogram', (['data'], {'bins': '"""sqrt"""'}), "(data, bins='sqrt')\n", (607, 626), True, 'import numpy as np\n'), ((1032, 1093), 'matplotlib.pyplot.subplots... |
import gc
from functools import reduce
from typing import Callable, Iterable, List, Optional, Tuple, TypeVar
import numpy as np
import pandas as pd
from .graph import AttrMap, Graph
from .trace import AddOp, TraceKey
from .utils import filter_not_null
from .utils.fs import IOAction
from .utils.ray import ray_iter
__... | [
"numpy.intersect1d",
"numpy.eye",
"numpy.prod",
"numpy.bitwise_or",
"numpy.union1d",
"numpy.unpackbits",
"numpy.bitwise_and",
"numpy.count_nonzero",
"numpy.zeros",
"gc.collect",
"typing.TypeVar"
] | [((854, 866), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (861, 866), False, 'from typing import Callable, Iterable, List, Optional, Tuple, TypeVar\n'), ((16024, 16049), 'numpy.eye', 'np.eye', (['size'], {'dtype': 'float'}), '(size, dtype=float)\n', (16030, 16049), True, 'import numpy as np\n'), ((17567,... |
import logging, re, json, subprocess, os, copy
from datetime import datetime, timedelta
import time
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext, loader
from django.db.models import Count
from django import ... | [
"django.template.RequestContext",
"django.utils.timezone.now",
"core.views.initRequest",
"datetime.timedelta",
"core.common.models.Users.objects.filter",
"django.core.paginator.Paginator"
] | [((2080, 2100), 'core.views.initRequest', 'initRequest', (['request'], {}), '(request)\n', (2091, 2100), False, 'from core.views import initRequest\n'), ((2460, 2480), 'core.views.initRequest', 'initRequest', (['request'], {}), '(request)\n', (2471, 2480), False, 'from core.views import initRequest\n'), ((4682, 4702), ... |
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='Administrador',password='<PASSWORD>', database='teste')
cursor = cnx.cursor()
tomorrow = datetime.now().date() + timedelta(days=0)
add_employee = ("INSERT INTO employees "
... | [
"datetime.datetime.now",
"datetime.timedelta",
"datetime.date"
] | [((259, 276), 'datetime.timedelta', 'timedelta', ([], {'days': '(0)'}), '(days=0)\n', (268, 276), False, 'from datetime import date, datetime, timedelta\n'), ((664, 681), 'datetime.date', 'date', (['(1977)', '(6)', '(14)'], {}), '(1977, 6, 14)\n', (668, 681), False, 'from datetime import date, datetime, timedelta\n'), ... |
import json
import logging
import kubernetes
from ocp_resources.node import Node
from ocp_resources.resource import NamespacedResource
from ocp_resources.utils import TimeoutWatch
LOGGER = logging.getLogger(__name__)
class ExecOnPodError(Exception):
def __init__(self, command, rc, out, err):
self.cmd ... | [
"logging.getLogger",
"ocp_resources.node.Node",
"kubernetes.client.CoreV1Api",
"ocp_resources.utils.TimeoutWatch",
"kubernetes.stream.stream"
] | [((193, 220), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (210, 220), False, 'import logging\n'), ((1318, 1376), 'kubernetes.client.CoreV1Api', 'kubernetes.client.CoreV1Api', ([], {'api_client': 'self.client.client'}), '(api_client=self.client.client)\n', (1345, 1376), False, 'import k... |
from unittest import TestCase
from haleasy import HALEasy
import responses
class TestHaleasyHaltalk(TestCase):
haltalk_root = '''{
"_links": {
"self": {
"href":"/"
},
"curies": [
{
"name": "ht",
"hr... | [
"responses.reset",
"responses.add",
"haleasy.HALEasy"
] | [((1955, 1972), 'responses.reset', 'responses.reset', ([], {}), '()\n', (1970, 1972), False, 'import responses\n'), ((1981, 2127), 'responses.add', 'responses.add', (['responses.GET', '"""http://haltalk.herokuapp.com.test_domain/"""'], {'body': 'self.haltalk_root', 'status': '(200)', 'content_type': '"""application/jso... |
import pytest
import numpy as np
import pdb
from .base import TestRefuter
def simple_linear_outcome_model(X_train, output_train):
# The outcome is a linear function of the confounder
# The slope is 1,2 and the intercept is 3
return lambda X_train: X_train[:,0] + 2*X_train[:,1] + 3
@pytest... | [
"pytest.mark.parametrize",
"pytest.mark.usefixtures"
] | [((314, 351), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""fixed_seed"""'], {}), "('fixed_seed')\n", (337, 351), False, 'import pytest\n'), ((398, 504), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['error_tolerence', 'estimator_method']", "[(0.03, 'iv.instrumental_variable')]"], {}), "(['err... |
#!/usr/bin/env python3
import os
import shutil
import unittest
import tempfile
import platform
import getpass
import tarfile
from gppylib.db import dbconn
from gppylib.gparray import GpArray
from contextlib import closing
from gppylib.commands import gp
from gppylib.commands.unix import Scp
from gppylib.commands.base... | [
"unittest.main",
"getpass.getuser",
"os.remove",
"os.path.exists",
"shutil.move",
"platform.system",
"os.mkdir",
"tempfile.NamedTemporaryFile",
"gppylib.commands.base.Command",
"unittest.skip",
"shutil.copy",
"platform.machine",
"gppylib.commands.gp.get_gphome",
"os.getenv",
"gppylib.db.... | [((522, 539), 'platform.system', 'platform.system', ([], {}), '()\n', (537, 539), False, 'import platform\n'), ((547, 565), 'platform.machine', 'platform.machine', ([], {}), '()\n', (563, 565), False, 'import platform\n'), ((802, 848), 'os.path.join', 'os.path.join', (['GPHOME', '"""share/packages/archive"""'], {}), "(... |
import cv2
import numpy as np
def filterClusters(clusters):
# Remove things with angle far from median
for i in range(len(clusters)):
cluster = clusters[i]
if len(cluster) > 9:
median = np.median([facelet[2] for facelet in cluster])
clusters[i] = [facelet for facelet... | [
"cv2.convexHull",
"numpy.median",
"cv2.contourArea"
] | [((227, 273), 'numpy.median', 'np.median', (['[facelet[2] for facelet in cluster]'], {}), '([facelet[2] for facelet in cluster])\n', (236, 273), True, 'import numpy as np\n'), ((742, 760), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (757, 760), False, 'import cv2\n'), ((784, 801), 'cv2.convexHull', 'cv2... |
import csv
import io
import os
from django.contrib.auth import get_user_model
from rest_framework import filters, status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.v... | [
"django.contrib.auth.get_user_model",
"rest_framework.response.Response",
"rest_framework.decorators.action",
"os.path.splitext"
] | [((1015, 1031), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (1029, 1031), False, 'from django.contrib.auth import get_user_model\n'), ((1338, 1375), 'rest_framework.decorators.action', 'action', ([], {'detail': '(False)', 'methods': "['GET']"}), "(detail=False, methods=['GET'])\n", (1344, ... |
import sys
def solve(opcodes):
for i in range(0, len(opcodes), 4):
if opcodes[i] == 1:
opcodes[opcodes[i + 3]] = opcodes[opcodes[i + 1]] + opcodes[opcodes[i + 2]]
elif opcodes[i] == 2:
opcodes[opcodes[i + 3]] = opcodes[opcodes[i + 1]] * opcodes[opcodes[i + 2]]
elif ... | [
"sys.exit"
] | [((961, 972), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (969, 972), False, 'import sys\n')] |