code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Copyright 2017-present Open Networking Foundation
#
# 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 ag... | [
"json.dumps"
] | [((1022, 1040), 'json.dumps', 'json.dumps', (['config'], {}), '(config)\n', (1032, 1040), False, 'import json\n'), ((1384, 1402), 'json.dumps', 'json.dumps', (['config'], {}), '(config)\n', (1394, 1402), False, 'import json\n'), ((1628, 1646), 'json.dumps', 'json.dumps', (['config'], {}), '(config)\n', (1638, 1646), Fa... |
import torch
from torch import nn
import torch.nn.functional as F
from src.nets_utils import make_pad_mask, to_device
class AttLoc(nn.Module):
"""location-aware attention
Reference: Attention-Based Models for Speech Recognition
(https://arxiv.org/pdf/1506.07503.pdf)
:param int enc_dim: odim of e... | [
"src.nets_utils.make_pad_mask",
"torch.nn.Conv2d",
"torch.nn.functional.softmax",
"torch.nn.Linear",
"torch.tanh"
] | [((764, 791), 'torch.nn.Linear', 'nn.Linear', (['enc_dim', 'att_dim'], {}), '(enc_dim, att_dim)\n', (773, 791), False, 'from torch import nn\n'), ((821, 860), 'torch.nn.Linear', 'nn.Linear', (['dec_dim', 'att_dim'], {'bias': '(False)'}), '(dec_dim, att_dim, bias=False)\n', (830, 860), False, 'from torch import nn\n'), ... |
# Copyright <NAME> 2017
"""
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
distri... | [
"numpy.copy",
"pyopencl.enqueue_copy",
"test.test_common.build_kernel",
"test.test_common.offset_type",
"test.test_common.ll_to_cl",
"pyopencl.LocalMemory"
] | [((1051, 1106), 'test.test_common.ll_to_cl', 'test_common.ll_to_cl', (['ll_code', '"""mykernel"""'], {'num_clmems': '(1)'}), "(ll_code, 'mykernel', num_clmems=1)\n", (1071, 1106), False, 'from test import test_common\n'), ((1192, 1234), 'pyopencl.enqueue_copy', 'cl.enqueue_copy', (['q', 'int_data_gpu', 'int_data'], {})... |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647188
#
# For det... | [
"os.path.join"
] | [((2181, 2211), 'os.path.join', 'os.path.join', (['"""cargo"""', '"""cargo"""'], {}), "('cargo', 'cargo')\n", (2193, 2211), False, 'import os\n')] |
import openc2
import pytest
import json
import sys
def test_actuator_requested():
@openc2.v10.CustomActuator("x-thing", [("id", openc2.properties.StringProperty())])
class MyCustomActuator(object):
pass
foo = MyCustomActuator(id="id")
assert foo
assert foo.id == "id"
bar = openc2.uti... | [
"pytest.raises",
"openc2.v10.CustomActuator",
"openc2.properties.StringProperty"
] | [((399, 424), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (412, 424), False, 'import pytest\n'), ((612, 637), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (625, 637), False, 'import pytest\n'), ((863, 888), 'pytest.raises', 'pytest.raises', (['ValueError'], {})... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import argparse
params = {'axes.labelsize': 14,
'axes.titlesize': 16,
'xtick.labelsize': 12,
'ytick.labelsize': 12,
'legend.fontsize': 14}
plt.rcParams.update(params)
if __name__ == '__main__':
msg = ... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"numpy.append",
"matplotlib.pyplot.rcParams.update",
"numpy.loadtxt",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((253, 280), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (['params'], {}), '(params)\n', (272, 280), True, 'import matplotlib.pyplot as plt\n'), ((346, 386), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'msg'}), '(description=msg)\n', (369, 386), False, 'import argparse\n'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def process_xml_string(xml_string):
"""
Функция из текста выдирает строку с xml --
она должна начинаться на < и заканчиваться >
"""
start = xml_string.index('<')
end = xml_string.rindex('>')
return xml_string[start:e... | [
"lxml.etree.tostring",
"lxml.etree.fromstring",
"xml.dom.minidom.parseString"
] | [((845, 873), 'lxml.etree.fromstring', 'etree.fromstring', (['xml_string'], {}), '(xml_string)\n', (861, 873), False, 'from lxml import etree\n'), ((548, 571), 'xml.dom.minidom.parseString', 'parseString', (['xml_string'], {}), '(xml_string)\n', (559, 571), False, 'from xml.dom.minidom import parseString\n'), ((885, 94... |
"""
Run equivalent circuit model (ECM) for battery cell and compare to HPPC data.
Plot HPPC voltage data and ECM voltage. Plot absolute voltage difference
between HPPC data and ECM.
"""
import matplotlib.pyplot as plt
import params
from ecm import CellHppcData
from ecm import EquivCircModel
from utils import config_... | [
"matplotlib.pyplot.show",
"ecm.CellHppcData.process",
"ecm.EquivCircModel",
"utils.config_ax",
"matplotlib.pyplot.subplots"
] | [((516, 547), 'ecm.CellHppcData.process', 'CellHppcData.process', (['file_hppc'], {}), '(file_hppc)\n', (536, 547), False, 'from ecm import CellHppcData\n'), ((555, 583), 'ecm.EquivCircModel', 'EquivCircModel', (['data', 'params'], {}), '(data, params)\n', (569, 583), False, 'from ecm import EquivCircModel\n'), ((861, ... |
import networkx as nx
import matplotlib.pyplot as plt
import re
if __name__ == '__main__':
G = nx.Graph()
f = open('res.txt','r')
cnt = 0
prev = None
for line in f.readlines():
if line.find('END') != -1:
prev = None
cnt+=1
print(cnt)
... | [
"matplotlib.pyplot.show",
"re.findall",
"networkx.Graph",
"networkx.degree",
"matplotlib.pyplot.savefig"
] | [((105, 115), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (113, 115), True, 'import networkx as nx\n'), ((658, 670), 'networkx.degree', 'nx.degree', (['G'], {}), '(G)\n', (667, 670), True, 'import networkx as nx\n'), ((861, 871), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (869, 871), True, 'import matp... |
""" Temporary wrappers around cli commands until we agree on a better approach to running LSST. """
import os
import subprocess
import tempfile
from huntsman.drp.core import get_logger
# Default search directory for pipeline files
PIPELINE_DIR = os.path.expandvars("${OBS_HUNTSMAN}/pipelines")
def _run_pipetask_cmd(... | [
"tempfile.NamedTemporaryFile",
"huntsman.drp.core.get_logger",
"os.path.isabs",
"subprocess.check_output",
"os.path.expandvars",
"os.path.join"
] | [((248, 295), 'os.path.expandvars', 'os.path.expandvars', (['"""${OBS_HUNTSMAN}/pipelines"""'], {}), "('${OBS_HUNTSMAN}/pipelines')\n", (266, 295), False, 'import os\n'), ((1049, 1089), 'subprocess.check_output', 'subprocess.check_output', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (1072, 1089), False, 'imp... |
import collections
from spira.yevon.gdsii.base import __Element__
from spira.core.typed_list import TypedList
from spira.core.parameters.restrictions import RestrictType
from spira.core.parameters.descriptor import ParameterDescriptor
from spira.core.transformable import Transformable
class __ElementList__(TypedList... | [
"copy.deepcopy",
"spira.yevon.geometry.nets.net_list.NetList",
"spira.yevon.gdsii.cell_list.CellList",
"spira.yevon.geometry.bbox_info.BoundaryInfo",
"spira.core.parameters.restrictions.RestrictType"
] | [((3131, 3140), 'spira.yevon.geometry.nets.net_list.NetList', 'NetList', ([], {}), '()\n', (3138, 3140), False, 'from spira.yevon.geometry.nets.net_list import NetList\n'), ((3330, 3340), 'spira.yevon.gdsii.cell_list.CellList', 'CellList', ([], {}), '()\n', (3338, 3340), False, 'from spira.yevon.gdsii.cell_list import ... |
# Copyright 2021 The KubeEdge 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 or agreed to in... | [
"sedna.common.class_factory.ClassFactory.register"
] | [((768, 804), 'sedna.common.class_factory.ClassFactory.register', 'ClassFactory.register', (['ClassType.MTL'], {}), '(ClassType.MTL)\n', (789, 804), False, 'from sedna.common.class_factory import ClassFactory, ClassType\n')] |
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Github @SeniorKullken 2020-01-07
# Github @SeniorKullken 2020-01-04
#
# Show Linux/Raspian status/information on LCD-Display
# Row1: Show local HostName = HostName
# Row2: Show local IP-address = IP
#
# -----Prerequisite------------------------------
# Display: 160... | [
"argparse.ArgumentParser",
"subprocess.check_output",
"os.popen",
"socket.gethostname",
"datetime.datetime.now",
"rpi_lcd.LCD"
] | [((2094, 2216), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Display system status on a LCD-display."""', 'epilog': '"""Need addional hardware!"""'}), "(description=\n 'Display system status on a LCD-display.', epilog='Need addional hardware!'\n )\n", (2117, 2216), False, 'import... |
# (C) Copyright Artificial Brain 2021.
#
# 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 ... | [
"quantumcat.circuit.QCircuit",
"quantumcat.applications.protein_folding.CCRCA",
"quantumcat.applications.protein_folding.CCRCA_INVERSE"
] | [((2334, 2346), 'quantumcat.circuit.QCircuit', 'QCircuit', (['(20)'], {}), '(20)\n', (2342, 2346), False, 'from quantumcat.circuit import QCircuit\n'), ((3596, 3629), 'quantumcat.applications.protein_folding.CCRCA', 'CCRCA', (['self.circuit', 'self.arglist'], {}), '(self.circuit, self.arglist)\n', (3601, 3629), False, ... |
from stompy.simple import Client
import sys
import time
import threading
import random
import os
time.sleep(0.5)
queue_name = "/queue/test4"
stomp = Client()
stomp.connect()
def get_random_time():
rand = random.random()
rand = rand * 500
rand = rand / 1000
return rand
def send_message(body, retries=20):
try:... | [
"threading.Thread",
"os.remove",
"stompy.simple.Client",
"os.path.exists",
"time.sleep",
"random.random"
] | [((99, 114), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (109, 114), False, 'import time\n'), ((153, 161), 'stompy.simple.Client', 'Client', ([], {}), '()\n', (159, 161), False, 'from stompy.simple import Client\n'), ((905, 934), 'os.path.exists', 'os.path.exists', (['"""account.txt"""'], {}), "('account.tx... |
# Copyright 2021, 2022 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 agreed to in writin... | [
"threading.Thread",
"functools.partial",
"json.load",
"asyncio.sleep",
"collections.deque",
"logging.getLogger",
"starlette.responses.JSONResponse",
"asyncio.get_running_loop",
"starlette.routing.Mount",
"threading.Event",
"logging.config.dictConfig",
"starlette.routing.Route",
"os.getenv",
... | [((2057, 2064), 'threading.Event', 'Event', ([], {}), '()\n', (2062, 2064), False, 'from threading import Thread, Event\n'), ((2175, 2208), 'collections.deque', 'deque', (['[0]', 'TIMINGS_BUFFER_LENGTH'], {}), '([0], TIMINGS_BUFFER_LENGTH)\n', (2180, 2208), False, 'from collections import deque\n'), ((2279, 2314), 'log... |
# -*- coding: utf-8 -*-
"""
MeCabを使った形態素解析でテキストをベクトル化するやつです。
"""
import MeCab
from collections import Counter
class keitaiso:
def __init__(self, use_PoW=['名詞','動詞','形容詞','副詞','記号'], stop_words=[], use_words=[], user_dic_files=[]):
"""
ARGUMENT
----------------
use_PoW [list]:
... | [
"collections.Counter",
"MeCab.Tagger"
] | [((1677, 1709), 'MeCab.Tagger', 'MeCab.Tagger', (['arg_user_dic_files'], {}), '(arg_user_dic_files)\n', (1689, 1709), False, 'import MeCab\n'), ((2466, 2485), 'collections.Counter', 'Counter', (['processing'], {}), '(processing)\n', (2473, 2485), False, 'from collections import Counter\n')] |
# Generated by Django 2.2.6 on 2019-11-07 21:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team', '0002_auto_20191107_1940'),
]
operations = [
migrations.AlterField(
model_name='teammembertranslation',
name=... | [
"django.db.models.CharField"
] | [((346, 390), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(225)'}), "(default='', max_length=225)\n", (362, 390), False, 'from django.db import migrations, models\n')] |
import numpy as np
from PIL import Image
import h5py
from astropy.io import fits
from astropy.table import Table
from astropy.convolution import convolve
from astropy.cosmology import WMAP7 as cosmo
import astropy.units as u
from astropy import wcs
import glob
import pickle
import os
import matplotlib.pyplot as plt
... | [
"matplotlib.pyplot.title",
"astropy.convolution.convolve",
"numpy.sum",
"astropy.io.fits.PrimaryHDU",
"astropy.cosmology.WMAP7.luminosity_distance",
"numpy.isnan",
"matplotlib.pyplot.figure",
"astropy.io.fits.Header",
"numpy.random.randint",
"numpy.rot90",
"pickle.load",
"glob.glob",
"numpy.... | [((1392, 1417), 'numpy.array', 'np.array', (["['i', 'r', 'g']"], {}), "(['i', 'r', 'g'])\n", (1400, 1417), True, 'import numpy as np\n'), ((1470, 1522), 'numpy.array', 'np.array', (["['_00', '_01', '_02', '_03', '_04', '_05']"], {}), "(['_00', '_01', '_02', '_03', '_04', '_05'])\n", (1478, 1522), True, 'import numpy as... |
#!/bin/env python3
import os.path
from typing import Any, IO
import yaml
def main():
d = os.path.join(os.path.dirname(__file__),
"..", "docs", "reference")
d = os.path.normpath(d)
print(f"generating {d}/readme.md")
f = open(os.path.join(d, "settings.yaml"))
doc = yaml.full_lo... | [
"yaml.full_load"
] | [((308, 325), 'yaml.full_load', 'yaml.full_load', (['f'], {}), '(f)\n', (322, 325), False, 'import yaml\n')] |
a#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 13:44:45 2018
Name: khalednakhleh
"""
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, LSTM
from keras import regularizers
import pandas as pd
from sklearn.model_selection import train_test_spli... | [
"matplotlib.pyplot.title",
"keras.regularizers.l2",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.figure",
"keras.layers.Dense",
"keras.models.Sequentia... | [((462, 486), 'pandas.read_csv', 'pd.read_csv', (['"""clean.csv"""'], {}), "('clean.csv')\n", (473, 486), True, 'import pandas as pd\n'), ((1123, 1173), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'y_train'], {'test_size': '(0.25)'}), '(X_train, y_train, test_size=0.25)\n', (1139, 1173)... |
""" run_pkl2json reads all pkl files in the given folder structure and converts
them to json
"""
import sys
import os
import pickle
import glob
import json
# ###############
# Get folder path
# ###############
# Checky python version.
# This code should be run using the python version used to create the pkl
# fi... | [
"json.dump",
"ipdb.set_trace",
"os.path.isdir",
"os.path.isfile",
"pickle.load",
"glob.glob"
] | [((834, 855), 'os.path.isdir', 'os.path.isdir', (['f_path'], {}), '(f_path)\n', (847, 855), False, 'import os\n'), ((1048, 1064), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (1062, 1064), False, 'import ipdb\n'), ((873, 903), 'glob.glob', 'glob.glob', (["(f_path + '**/*.pkl')"], {}), "(f_path + '**/*.pkl')\n"... |
#! /usr/bin/python
#--------------------------------------------------------------------
# PROGRAM : write_to_nc.py
# CREATED BY : hjkim @IIS.2017-10-17 06:23:16.129216
# MODIFED BY :
#
# USAGE : $ ./write_to_nc.py
#
# DESCRIPTION:
#------------------------------------------------------cf0.2@20120401
import ... | [
"netCDF4.Dataset",
"numpy.ma.masked_equal",
"collections.OrderedDict"
] | [((1405, 1444), 'netCDF4.Dataset', 'Dataset', (['outpath', '"""w"""'], {'format': '"""NETCDF4"""'}), "(outpath, 'w', format='NETCDF4')\n", (1412, 1444), False, 'from netCDF4 import Dataset\n'), ((1534, 1610), 'collections.OrderedDict', 'OrderedDict', (["(('time', None), ('pixel', None), ('lat', None), ('lon', None))"],... |
# Copyright 2022 Meta Platforms authors and The HuggingFace Team. 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
#
# U... | [
"json.dump",
"numpy.moveaxis",
"transformers.FlavaFeatureExtractor.from_pretrained",
"transformers.utils.is_vision_available",
"transformers.FlavaProcessor",
"transformers.BertTokenizerFast.from_pretrained",
"pytest.raises",
"tempfile.mkdtemp",
"transformers.BertTokenizer.from_pretrained",
"random... | [((1016, 1037), 'transformers.utils.is_vision_available', 'is_vision_available', ([], {}), '()\n', (1035, 1037), False, 'from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available\n'), ((1426, 1444), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1442, 1444), False, 'import tempfile\n'), ((1... |
from selenium import webdriver
import time
url = 'https://qzone.qq.com/'
driver = webdriver.Chrome()
driver.get(url)
el_frame = driver.find_element_by_xpath('//*[@id="login_frame"]')
time.sleep(2)
driver.switch_to.frame(el_frame)
time.sleep(2)
driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
time.s... | [
"selenium.webdriver.Chrome",
"time.sleep"
] | [((83, 101), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {}), '()\n', (99, 101), False, 'from selenium import webdriver\n'), ((186, 199), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (196, 199), False, 'import time\n'), ((233, 246), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (243, 246), False,... |
import requests
import json
#API Key
key = "5b4eb360-0397-415e-b0a9-e38738177f6e"
#List of countries supported by the API and their short forms
countryList = {"BE": "Belgium","BG": "Bulgaria", "BR": "Brazil", "CA": "Canada", "CZ": "Czech Republic", "DE" :"Germany", "ES": "Spain", "FR": "France", "GB":"United Kingdom"... | [
"json.loads",
"requests.get"
] | [((1512, 1536), 'requests.get', 'requests.get', (['apiRequest'], {}), '(apiRequest)\n', (1524, 1536), False, 'import requests\n'), ((1550, 1575), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1560, 1575), False, 'import json\n')] |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | [
"polyaxon.exceptions.PolypodException",
"polyaxon.polypod.common.mounts.get_connections_context_mount",
"polyaxon.polypod.common.env_vars.get_connection_env_var",
"polyaxon.polypod.common.env_vars.get_env_from_secret",
"polyaxon.polypod.common.containers.patch_container",
"polyaxon.polypod.common.env_vars... | [((2328, 2357), 'polyaxon.utils.list_utils.to_list', 'to_list', (['env'], {'check_none': '(True)'}), '(env, check_none=True)\n', (2335, 2357), False, 'from polyaxon.utils.list_utils import to_list\n'), ((3355, 3474), 'polyaxon.polypod.common.containers.patch_container', 'patch_container', ([], {'container': 'container'... |
import csv
fixed_crime = []
fixed_bike = []
with open('CrimeEvents_new.csv') as crime_file:
with open('BikeThefts.csv') as bike_file:
crime_reader = csv.reader(crime_file, delimiter=',')
bike_reader = csv.reader(bike_file, delimiter=',')
bike_index = 0
for row in bike_reader:
... | [
"csv.reader",
"csv.writer"
] | [((1274, 1351), 'csv.writer', 'csv.writer', (['csv_file'], {'delimiter': '""","""', 'quotechar': '"""\\""""', 'quoting': 'csv.QUOTE_MINIMAL'}), '(csv_file, delimiter=\',\', quotechar=\'"\', quoting=csv.QUOTE_MINIMAL)\n', (1284, 1351), False, 'import csv\n'), ((1490, 1567), 'csv.writer', 'csv.writer', (['csv_file'], {'d... |
# -*- coding: utf-8 -*-
import os
import telebot
import time
import random
from telebot import types
from pymongo import MongoClient
import threading
import traceback
import requests
import config
client1=os.environ['database']
client=MongoClient(client1)
db=client.chlenomer
idgroup=db.ids
iduser=db.ids_people
users =... | [
"pymongo.MongoClient",
"threading.Timer",
"random.randint",
"telebot.types.InlineKeyboardButton",
"config.about",
"time.ctime",
"random.choice",
"time.sleep",
"traceback.format_exc",
"telebot.types.InlineKeyboardMarkup",
"telebot.TeleBot"
] | [((236, 256), 'pymongo.MongoClient', 'MongoClient', (['client1'], {}), '(client1)\n', (247, 256), False, 'from pymongo import MongoClient\n'), ((889, 911), 'telebot.TeleBot', 'telebot.TeleBot', (['token'], {}), '(token)\n', (904, 911), False, 'import telebot\n'), ((1989, 2009), 'config.about', 'config.about', (['m', 'b... |
# coding=utf-8
# Copyright 2018 The Nizza 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 or ... | [
"tensorflow.nn.embedding_lookup",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.train.get_global_step"
] | [((2046, 2113), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'train_op': 'train_op'}), '(mode=mode, loss=loss, train_op=train_op)\n', (2072, 2113), True, 'import tensorflow as tf\n'), ((2776, 2820), 'tensorflow.variable_scope', 'tf.variable_scope', (["('%s_em... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium_ui.conftest import print_timing
from selenium_ui.jira.modules import _wait_until
from util.conf import JIRA_SETTINGS
APPLICATION_URL = JIRA_SETTINGS.server_url
timeout = 20
def custom_action(we... | [
"selenium.webdriver.support.expected_conditions.visibility_of_element_located"
] | [((583, 642), 'selenium.webdriver.support.expected_conditions.visibility_of_element_located', 'ec.visibility_of_element_located', (["(By.ID, 'plugin-element')"], {}), "((By.ID, 'plugin-element'))\n", (615, 642), True, 'from selenium.webdriver.support import expected_conditions as ec\n'), ((918, 979), 'selenium.webdrive... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from dateutil.parser import parse
from pytz import timezone
def strip_timezone(datestr):
parsed = parse(datestr)
... | [
"dateutil.parser.parse",
"pytz.timezone"
] | [((301, 315), 'dateutil.parser.parse', 'parse', (['datestr'], {}), '(datestr)\n', (306, 315), False, 'from dateutil.parser import parse\n'), ((345, 370), 'pytz.timezone', 'timezone', (['"""Europe/Warsaw"""'], {}), "('Europe/Warsaw')\n", (353, 370), False, 'from pytz import timezone\n')] |
from flask import request, jsonify, g
from flask import Blueprint
from sqlalchemy import or_
from application.utils.filter import filter_city, sort_result
from ..utils.query import QueryHelper
from ..utils.esquery import EsqueryHelper
from ..models import Area,City,Neighborhood
from ..utils.auth import requires_auth, ... | [
"flask.Blueprint",
"json.loads",
"flask.request.args.get",
"index.limiter.limit",
"flask.jsonify"
] | [((742, 771), 'flask.Blueprint', 'Blueprint', (['"""nearby"""', '__name__'], {}), "('nearby', __name__)\n", (751, 771), False, 'from flask import Blueprint\n'), ((896, 928), 'index.limiter.limit', 'limiter.limit', (['rate_limit_from_g'], {}), '(rate_limit_from_g)\n', (909, 928), False, 'from index import app, db, es, r... |
from django.db import models
from django.urls import reverse
class Timestamp(models.Model):
# Fields
last_updated = models.DateTimeField(auto_now=True, editable=False)
created = models.DateTimeField(auto_now_add=True, editable=False)
class Meta:
abstract = True
class Ticket(Timestamp):
... | [
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.urls.reverse",
"django.db.models.IntegerField",
"django.db.models.DecimalField",
"django.db.models.DateTimeField"
] | [((126, 177), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'editable': '(False)'}), '(auto_now=True, editable=False)\n', (146, 177), False, 'from django.db import models\n'), ((192, 247), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', '... |
# Parse the MeSH source files for MeSH id to UNII mappings
# Works for both desc and supp XML files
import xml.etree.ElementTree as ET
from collections import defaultdict
import pandas as pd
def parse_file(fname):
"""Parse XML version of MeSH (desc and supp files) to give MeSH ID to
UNII mappings."""
def... | [
"collections.defaultdict",
"xml.etree.ElementTree.parse",
"pandas.DataFrame"
] | [((1622, 1637), 'xml.etree.ElementTree.parse', 'ET.parse', (['fname'], {}), '(fname)\n', (1630, 1637), True, 'import xml.etree.ElementTree as ET\n'), ((1675, 1692), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1686, 1692), False, 'from collections import defaultdict\n'), ((1982, 1999), 'pandas... |
import csv
import tqdm
import argparse
from src.model.trip import Trip
from src.util import log, date
from src.model.user import User
from src.services import random_api
from src.db.sqlalchemy import db_session
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('input_file', type=str)
... | [
"csv.reader",
"argparse.ArgumentParser",
"src.services.random_api.get_random_personality",
"src.db.sqlalchemy.db_session",
"src.util.date.to_string",
"src.model.user.User"
] | [((245, 270), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (268, 270), False, 'import argparse\n'), ((1320, 1355), 'src.services.random_api.get_random_personality', 'random_api.get_random_personality', ([], {}), '()\n', (1353, 1355), False, 'from src.services import random_api\n'), ((1630, 16... |
"""
IP Manipulation functions - Helper function for IpGrouping
- String, Decimal and Binary format transformations
- Astrix notation
- Binary Intervals utils
"""
import math
''' IP Conversions '''
def IpStringToDecimal(str_ip):
"""
:param str_ip: IPv4 in string notation, e.g. 10.0.0.1
:return: IPv4 in ... | [
"math.log"
] | [((2117, 2141), 'math.log', 'math.log', (['(start ^ end)', '(2)'], {}), '(start ^ end, 2)\n', (2125, 2141), False, 'import math\n')] |
from munerator.games import Game
def test_game_mapstring():
expected_mapstring = ("set g_warmup 0;set g_doWarmup 0;set g_spawnprotect 2000;set g_speed 320;"
"set g_gravity 800;set g_knockback 1000;set map_restart 0;set g_instantgib 0;"
"set g_vampire 0;set g_reg... | [
"munerator.games.Game"
] | [((534, 555), 'munerator.games.Game', 'Game', (['"""mapname"""', '(0)', '(4)'], {}), "('mapname', 0, 4)\n", (538, 555), False, 'from munerator.games import Game\n'), ((1128, 1161), 'munerator.games.Game', 'Game', (['"""mapname"""', '(0)', '(4)', '"""instagib"""'], {}), "('mapname', 0, 4, 'instagib')\n", (1132, 1161), F... |
import tensorflow as tf
a=tf.Variable(tf.ones([3,3]))
b=tf.Variable(tf.ones([3,3]))
c=a*tf.cast(tf.equal(tf.reduce_mean(a),0),tf.float32)
d=tf.equal(tf.reduce_mean(a),1)
with tf.Session() as s:
s.run(tf.initialize_all_variables())
d=s.run(c)
pass
| [
"tensorflow.ones",
"tensorflow.Session",
"tensorflow.reduce_mean",
"tensorflow.initialize_all_variables"
] | [((39, 54), 'tensorflow.ones', 'tf.ones', (['[3, 3]'], {}), '([3, 3])\n', (46, 54), True, 'import tensorflow as tf\n'), ((69, 84), 'tensorflow.ones', 'tf.ones', (['[3, 3]'], {}), '([3, 3])\n', (76, 84), True, 'import tensorflow as tf\n'), ((150, 167), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['a'], {}), '(a)\n', (1... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
f1_score,
make_scorer,
precision_score,
recall_score,
average_precision_score,
auc
)
def plot_confusi... | [
"numpy.trace",
"numpy.sum",
"seaborn.heatmap",
"numpy.asarray",
"sklearn.metrics.confusion_matrix"
] | [((808, 835), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['tar', 'pred'], {}), '(tar, pred)\n', (824, 835), False, 'from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score, make_scorer, precision_score, recall_score, average_precision_score, auc\n'), ((1466, 1588), 's... |
import argparse
import csv
from typing import IO, Dict, List
def main() -> None:
parser = get_parser()
args = parser.parse_args()
with open(args.bed) as bed_file_handle, open(
args.mnemonics
) as mnemonics_file_handle, open(
args.output_filename, "w", newline=""
) as output_file_ha... | [
"csv.reader",
"csv.writer",
"argparse.ArgumentParser"
] | [((601, 665), 'csv.reader', 'csv.reader', (['bed_file_handle'], {'delimiter': '"""\t"""', 'lineterminator': '"""\n"""'}), "(bed_file_handle, delimiter='\\t', lineterminator='\\n')\n", (611, 665), False, 'import csv\n'), ((686, 772), 'csv.writer', 'csv.writer', (['output_file_handle'], {'delimiter': '"""\t"""', 'lineter... |
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Listens on 2 ports and relays between them.
Listens to ports A an... | [
"socket.socket",
"time.sleep"
] | [((1756, 1769), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1766, 1769), False, 'import time\n'), ((837, 886), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (850, 886), False, 'import socket\n'), ((1159, 1174), 'time.sleep', 'time.sl... |
from classes.cargo import Cargo
from classes.engine import EletricEngine, GasEngine
from classes.vehicle import Vehicle
from classes.powersource import Battery, GasTank, SolarPanel
from classes.path import Coordinate, Path
from datetime import datetime
import pytz
class Model:
# This class manages world models
... | [
"classes.engine.EletricEngine",
"classes.powersource.GasTank",
"classes.engine.GasEngine",
"classes.powersource.SolarPanel",
"classes.cargo.Cargo",
"classes.powersource.Battery",
"classes.vehicle.Vehicle",
"classes.path.Coordinate",
"datetime.datetime",
"pytz.timezone",
"classes.path.Path"
] | [((416, 436), 'classes.powersource.Battery', 'Battery', (['(90)', '(60)', '(7.7)'], {}), '(90, 60, 7.7)\n', (423, 436), False, 'from classes.powersource import Battery, GasTank, SolarPanel\n'), ((507, 525), 'classes.powersource.GasTank', 'GasTank', (['(25)', '(24)', '(6)'], {}), '(25, 24, 6)\n', (514, 525), False, 'fro... |
from flask import render_template
from newsapp.errors import bp
from newsapp.errors.descriptions import DESCRIPTIONS
@bp.app_errorhandler(400)
def bad_request(error):
return render_template("error.html", error=DESCRIPTIONS[404]), 400
@bp.app_errorhandler(404)
def not_found_error(error):
return render_templ... | [
"newsapp.errors.bp.app_errorhandler",
"flask.render_template"
] | [((121, 145), 'newsapp.errors.bp.app_errorhandler', 'bp.app_errorhandler', (['(400)'], {}), '(400)\n', (140, 145), False, 'from newsapp.errors import bp\n'), ((244, 268), 'newsapp.errors.bp.app_errorhandler', 'bp.app_errorhandler', (['(404)'], {}), '(404)\n', (263, 268), False, 'from newsapp.errors import bp\n'), ((371... |
import json
import os
from openpyxl import Workbook
from openpyxl import load_workbook
packaglistfilepath = os.path.join(os.getcwd(), 'packagelist.json')
buildrequire_filepath = os.path.join(os.getcwd(), 'buildrequiresfile.json')
excelfile = os.path.join(os.getcwd(), 'packagelist.xlsx')
def get_requires(packagelist, ... | [
"os.getcwd",
"openpyxl.load_workbook",
"json.load",
"openpyxl.Workbook"
] | [((122, 133), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (131, 133), False, 'import os\n'), ((192, 203), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (201, 203), False, 'import os\n'), ((256, 267), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (265, 267), False, 'import os\n'), ((1097, 1107), 'openpyxl.Workbook', 'Workbo... |
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import RANGE_SEXO, TIPO_TELEFONE, YES_NO_CHOICES
class TipoUsuario(models.Model):
descricao = models.CharField(
max_length=30, verbose_name=('Descrição'), unique=Tru... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.utils.translation.ugettext_lazy",
"django.db.models.DateField"
] | [((241, 311), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'verbose_name': '"""Descrição"""', 'unique': '(True)'}), "(max_length=30, verbose_name='Descrição', unique=True)\n", (257, 311), False, 'from django.db import models\n'), ((541, 611), 'django.db.models.CharField', 'models.CharFi... |
"""
Helper functions for image manipulation
"""
from __future__ import absolute_import, division
import numpy as np
from skimage.util import img_as_float
__all__ = ['to_norm', 'un_norm']
def to_norm(arr):
"""
Helper function to normalise/scale an array. This is needed for example
for scikit-image which... | [
"skimage.util.img_as_float",
"numpy.array"
] | [((742, 771), 'numpy.array', 'np.array', (['arr'], {'dtype': '"""double"""'}), "(arr, dtype='double')\n", (750, 771), True, 'import numpy as np\n'), ((782, 816), 'skimage.util.img_as_float', 'img_as_float', (['arr'], {'force_copy': '(True)'}), '(arr, force_copy=True)\n', (794, 816), False, 'from skimage.util import img... |
import sys
import shutil
import subprocess
import chromedriver_autoinstaller
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import web... | [
"selenium.webdriver.support.expected_conditions.presence_of_element_located",
"subprocess.Popen",
"selenium.webdriver.chrome.options.Options",
"chromedriver_autoinstaller.install",
"selenium.webdriver.Chrome",
"chromedriver_autoinstaller.get_chrome_version",
"shutil.rmtree",
"selenium.webdriver.suppor... | [((1394, 1562), 'subprocess.Popen', 'subprocess.Popen', (['"""C:\\\\\\\\Program Files (x86)\\\\\\\\Google\\\\\\\\Chrome\\\\\\\\Application\\\\\\\\chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\\\\\\\\chrometemp\\""""'], {}), '(\n \'C:\\\\\\\\Program Files (x86)\\\\\\\\Google\\\\\\\\Chrome\\\\\\\\Applica... |
"""Fourier matrix."""
import numpy as np
def fourier(dim: int) -> np.ndarray:
r"""
Generate the Fourier transform matrix [WikDFT]_.
Generates the `dim`-by-`dim` unitary matrix that implements the quantum
Fourier transform.
The Fourier matrix is defined as:
.. math::
W_N = \frac{1}{N... | [
"numpy.power",
"numpy.arange",
"numpy.exp",
"numpy.sqrt"
] | [((1630, 1660), 'numpy.exp', 'np.exp', (['(2 * 1.0j * np.pi / dim)'], {}), '(2 * 1.0j * np.pi / dim)\n', (1636, 1660), True, 'import numpy as np\n'), ((1714, 1731), 'numpy.arange', 'np.arange', (['(0)', 'dim'], {}), '(0, dim)\n', (1723, 1731), True, 'import numpy as np\n'), ((1673, 1690), 'numpy.arange', 'np.arange', (... |
"""isort:skip_file"""
# pylint: disable=unused-argument
# pylint: disable=reimported
from dagster import ResourceDefinition, graph, job
# start_resource_example
from dagster import resource
class ExternalCerealFetcher:
def fetch_new_cereals(self, start_ts, end_ts):
pass
@resource
def cereal_fetcher(in... | [
"dagster.job",
"dagster.build_resources",
"dagster.build_init_resource_context",
"dagster.op",
"dagster.resource",
"dagster.ResourceDefinition.mock_resource"
] | [((520, 559), 'dagster.op', 'op', ([], {'required_resource_keys': "{'database'}"}), "(required_resource_keys={'database'})\n", (522, 559), False, 'from dagster import graph, op\n'), ((990, 1058), 'dagster.resource', 'resource', ([], {'required_resource_keys': "{'foo'}", 'config_schema': "{'bar': str}"}), "(required_res... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | [
"oci.util.formatted_flat_dict",
"oci.util.value_allowed_none_or_none_sentinel"
] | [((21409, 21434), 'oci.util.formatted_flat_dict', 'formatted_flat_dict', (['self'], {}), '(self)\n', (21428, 21434), False, 'from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel\n'), ((11075, 11139), 'oci.util.value_allowed_none_or_none_sentinel', 'value_allowed_none_or_none_sent... |
import librosa
import numpy as np
import pandas as pd
import os
# 512 samples per frame at 44.1kHz is around 86 fps
def build_features(y, sr, n_fft=4096, hop_length=512):
params = {
'n_fft': n_fft,
'hop_length': hop_length
}
S, phase = librosa.magphase(librosa.stft(y, **params))
feature... | [
"librosa.feature.rms",
"numpy.abs",
"pandas.read_csv",
"numpy.empty",
"numpy.asarray",
"numpy.floor",
"numpy.zeros",
"numpy.flipud",
"os.path.exists",
"numpy.ones",
"librosa.cqt",
"librosa.feature.spectral_flatness",
"numpy.linspace",
"librosa.hz_to_octs",
"librosa.stft"
] | [((656, 704), 'librosa.feature.spectral_flatness', 'librosa.feature.spectral_flatness', ([], {'S': 'S'}), '(S=S, **params)\n', (689, 704), False, 'import librosa\n'), ((727, 781), 'librosa.feature.rms', 'librosa.feature.rms', ([], {'S': 'S', 'frame_length': "params['n_fft']"}), "(S=S, frame_length=params['n_fft'])\n", ... |
import torch
import torch.nn as nn
from utils.network_utils import *
from networks.architectures.base_modules import *
from networks.architectures.constructors.resnet import constructor
class UNetEncoder(nn.Module):
def __init__(self, opt, nf):
super(UNetEncoder, self).__init__()
ic, oc, norm_type, act_type = \
... | [
"torch.nn.MaxPool2d",
"torch.nn.ReLU",
"networks.architectures.constructors.resnet.constructor"
] | [((1474, 1519), 'networks.architectures.constructors.resnet.constructor', 'constructor', (['constructor_mode', 'ic', '(True)', 's', 'd'], {}), '(constructor_mode, ic, True, s, d)\n', (1485, 1519), False, 'from networks.architectures.constructors.resnet import constructor\n'), ((1534, 1543), 'torch.nn.ReLU', 'nn.ReLU', ... |
from database.models import Graph, UserProfile, Media, Vendor, Action, Community, Data, Tag, TagCollection, UserActionRel,RealEstateUnit
from _main_.utils.massenergize_errors import MassEnergizeAPIError, InvalidResourceError, ServerError, CustomMassenergizeError, NotAuthorizedError
from _main_.utils.massenergize_respon... | [
"database.models.Community.objects.filter",
"database.models.UserProfile.objects.filter",
"database.models.Action.objects.get",
"database.models.Graph.objects.prefetch_related",
"database.models.Community.objects.get",
"traceback.print_exc",
"database.models.Graph.objects.filter",
"database.models.Use... | [((2449, 2501), 'database.models.TagCollection.objects.get_or_create', 'TagCollection.objects.get_or_create', ([], {'name': '"""Category"""'}), "(name='Category')\n", (2484, 2501), False, 'from database.models import Graph, UserProfile, Media, Vendor, Action, Community, Data, Tag, TagCollection, UserActionRel, RealEsta... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... | [
"os.path.dirname",
"os.path.exists",
"mpp.common.lib.PSQL.PSQL.run_sql_command",
"gppylib.commands.base.Command",
"tinctest.lib.run_shell_command"
] | [((1201, 1328), 'mpp.common.lib.PSQL.PSQL.run_sql_command', 'PSQL.run_sql_command', (['("select \'command_found_\' || datname from pg_database where datname like \'" +\n self.db_name + "\'")'], {}), '(\n "select \'command_found_\' || datname from pg_database where datname like \'"\n + self.db_name + "\'")\n',... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
from unittest import TestCase
import filters as f
from filters.test import BaseFilterTestCase
from mock import Mock, patch
from cornode import Address, BadApiResponse, cor... | [
"cornode.adapter.MockAdapter",
"cornode.TryteString",
"cornode.commands.extended.prepare_transfer.PrepareTransferCommand",
"cornode.TryteString.from_string",
"mock.patch",
"six.text_type",
"cornode.crypto.types.Seed",
"cornode.Tag",
"cornode.cornode",
"mock.Mock",
"six.binary_type",
"cornode.c... | [((9597, 9610), 'cornode.adapter.MockAdapter', 'MockAdapter', ([], {}), '()\n', (9608, 9610), False, 'from cornode.adapter import MockAdapter\n'), ((9630, 9666), 'cornode.commands.extended.prepare_transfer.PrepareTransferCommand', 'PrepareTransferCommand', (['self.adapter'], {}), '(self.adapter)\n', (9652, 9666), False... |
def pytest_configure():
from django.conf import settings
settings.configure(
ROOT_URLCONF='tests.urls',
SIGAUTH_URL_NAMES_WHITELIST=['url-one'],
MIDDLEWARE=['tests.middleware.TestSignatureCheckMiddleware'],
SIGNATURE_SECRET='super secret',
SECRET_KEY='test-key',
)
| [
"django.conf.settings.configure"
] | [((65, 279), 'django.conf.settings.configure', 'settings.configure', ([], {'ROOT_URLCONF': '"""tests.urls"""', 'SIGAUTH_URL_NAMES_WHITELIST': "['url-one']", 'MIDDLEWARE': "['tests.middleware.TestSignatureCheckMiddleware']", 'SIGNATURE_SECRET': '"""super secret"""', 'SECRET_KEY': '"""test-key"""'}), "(ROOT_URLCONF='test... |
## ImGui Renderer Components: Input
## Input UI components for ImGui.
## Imports
import os
import subprocess
import platform
import imgui
## Classes
class GeneralUiFunctions():
"""
Adds functions for generalized, more complex UI features like external linkouts.
"""
## Functions
def linkoutButton(s... | [
"imgui.begin_tooltip",
"imgui.end_tooltip",
"subprocess.Popen",
"imgui.get_font_size",
"imgui.text",
"imgui.text_unformatted",
"imgui.same_line",
"platform.system",
"imgui.is_item_hovered",
"imgui.button",
"imgui.pop_text_wrap_pos",
"os.startfile"
] | [((557, 581), 'imgui.text', 'imgui.text', (['f"""{title}: """'], {}), "(f'{title}: ')\n", (567, 581), False, 'import imgui\n'), ((590, 607), 'imgui.same_line', 'imgui.same_line', ([], {}), '()\n', (605, 607), False, 'import imgui\n'), ((619, 656), 'imgui.button', 'imgui.button', (['f"""... {filepath[-32:]}"""'], {}), "... |
import os
class Settings(object):
def __init__(self):
"""initialize the settings of game."""
# screen settings
self.SCREEN_WIDTH = 960
self.SCREEN_HEIGHT = 640
self.SCREEN_SIZE = (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
self.BG_COLOR = (100, 100, 100)
self.... | [
"os.path.abspath",
"os.path.join"
] | [((414, 457), 'os.path.join', 'os.path.join', (['self.BASE_DIR', '"""img/game.tmx"""'], {}), "(self.BASE_DIR, 'img/game.tmx')\n", (426, 457), False, 'import os\n'), ((363, 388), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (378, 388), False, 'import os\n')] |
from urllib.parse import urlparse
def test_should_redirect_to_landing_page_on_root(test_client):
resp = test_client.get('/', follow_redirects=False)
assert urlparse(resp.location).path == '/join'
assert resp.status_code == 302
def test_should_render_landing_page(test_client):
resp = test_client.get(... | [
"urllib.parse.urlparse"
] | [((166, 189), 'urllib.parse.urlparse', 'urlparse', (['resp.location'], {}), '(resp.location)\n', (174, 189), False, 'from urllib.parse import urlparse\n')] |
import numpy as np
import tensorflow as tf
from run_seg_partnet import tf_IoU_per_shape, result_callback, get_probabilities, ComputeGraphSeg
def test_tf_iou_per_shape():
# following logit and label are for one 3D model that belongs in category C1 which has 3 parts
logit = tf.Variable(initial_value=np.array([... | [
"numpy.sum",
"run_seg_partnet.result_callback",
"tensorflow.global_variables_initializer",
"run_seg_partnet.tf_IoU_per_shape",
"tensorflow.Session",
"run_seg_partnet.get_probabilities",
"numpy.array",
"run_seg_partnet.ComputeGraphSeg.set_weights"
] | [((2454, 2479), 'run_seg_partnet.get_probabilities', 'get_probabilities', (['logits'], {}), '(logits)\n', (2471, 2479), False, 'from run_seg_partnet import tf_IoU_per_shape, result_callback, get_probabilities, ComputeGraphSeg\n'), ((2742, 2785), 'run_seg_partnet.ComputeGraphSeg.set_weights', 'ComputeGraphSeg.set_weight... |
import os
import win32com.client as client
text = """
This sample document is generated by WdBibTeX.
Sample citation\\cite{enArticle1}.
英語文献の引用例\\cite{enArticle1}。
Multiple citations example\\cite{enArticle2,enArticle3,enArticle4}.
複数文献の引用例\\cite{enArticle2,enArticle3,enArticle4}。
Examples of Japanese reference\\cite... | [
"win32com.client.Dispatch",
"os.path.abspath"
] | [((509, 544), 'win32com.client.Dispatch', 'client.Dispatch', (['"""Word.Application"""'], {}), "('Word.Application')\n", (524, 544), True, 'import win32com.client as client\n'), ((683, 708), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (698, 708), False, 'import os\n')] |
import pypbbot
import setuptools # type: ignore
import os
import sys
sys.path.insert(0, os.path.abspath('src'))
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="pypbbot",
version=pypbbot.__version__,
author="Kale1d0",
author_email="<EMAIL>"... | [
"os.path.abspath",
"setuptools.find_packages"
] | [((89, 111), 'os.path.abspath', 'os.path.abspath', (['"""src"""'], {}), "('src')\n", (104, 111), False, 'import os\n'), ((538, 575), 'setuptools.find_packages', 'setuptools.find_packages', ([], {'where': '"""src"""'}), "(where='src')\n", (562, 575), False, 'import setuptools\n')] |
from django.db import models
import qrcode
from io import BytesIO
from django.core.files import File
from PIL import Image, ImageDraw
# Create your models here.
class website(models.Model):
name = models.CharField(max_length=220)
qrcodes = models.ImageField(upload_to='qr_codes',blank=True)
def __str__(se... | [
"PIL.Image.new",
"io.BytesIO",
"django.core.files.File",
"django.db.models.CharField",
"django.db.models.ImageField",
"PIL.ImageDraw.Draw"
] | [((203, 235), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(220)'}), '(max_length=220)\n', (219, 235), False, 'from django.db import models\n'), ((250, 301), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""qr_codes"""', 'blank': '(True)'}), "(upload_to='qr_codes', bl... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="context-manager-patma",
version="0.0.1", # don't change version for now, early development
author="decorator-factory",
author_email="<EMAIL>",
description="Pattern matching with context m... | [
"setuptools.find_packages"
] | [((503, 529), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (527, 529), False, 'import setuptools\n')] |
from gevent import monkey
monkey.patch_all()
import uuid
import requests
import getopt
import sys
sys.path.append('..')
sys.path.append('../../../config')
from repository import Repository
import config
import pandas as pd
import time
import find_critical_path
repo = Repository()
CRIT_FUNCS = {'wordcount': ['start', ... | [
"sys.path.append",
"pandas.DataFrame",
"find_critical_path.analyze",
"uuid.uuid4",
"getopt.getopt",
"gevent.monkey.patch_all",
"time.time",
"requests.post",
"repository.Repository"
] | [((27, 45), 'gevent.monkey.patch_all', 'monkey.patch_all', ([], {}), '()\n', (43, 45), False, 'from gevent import monkey\n'), ((99, 120), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (114, 120), False, 'import sys\n'), ((121, 155), 'sys.path.append', 'sys.path.append', (['"""../../../config"""'... |
from hypothesis.searchstrategy import SearchStrategies
from hypothesis.flags import Flags
from random import random
import time
def assume(condition):
if not condition:
raise UnsatisfiedAssumption()
class Verifier(object):
def __init__(self,
search_strategies=None,
... | [
"random.random",
"hypothesis.searchstrategy.SearchStrategies",
"time.time"
] | [((1050, 1061), 'time.time', 'time.time', ([], {}), '()\n', (1059, 1061), False, 'import time\n'), ((647, 665), 'hypothesis.searchstrategy.SearchStrategies', 'SearchStrategies', ([], {}), '()\n', (663, 665), False, 'from hypothesis.searchstrategy import SearchStrategies\n'), ((1115, 1126), 'time.time', 'time.time', ([]... |
import unittest
import requests
import json
import yaml
import jsonschema
from src.utils.config import init_config
_API_URL = 'http://localhost:5000'
config = init_config()
_INDEX_NAMES = [
config['index_prefix'] + '.index1',
config['index_prefix'] + '.index2',
]
_SCHEMAS_PATH = 'src/server/method_schemas.yam... | [
"jsonschema.validate",
"json.dumps",
"requests.delete",
"yaml.safe_load",
"requests.get",
"src.utils.config.init_config",
"requests.post"
] | [((161, 174), 'src.utils.config.init_config', 'init_config', ([], {}), '()\n', (172, 174), False, 'from src.utils.config import init_config\n'), ((370, 388), 'yaml.safe_load', 'yaml.safe_load', (['fd'], {}), '(fd)\n', (384, 388), False, 'import yaml\n'), ((2736, 2799), 'requests.delete', 'requests.delete', (["(config['... |
from textwrap import dedent
import os
import shutil
import sys
import tempfile
LOG_NONE = 0
LOG_ERROR = 1
LOG_INFO = 2
LOG_DEBUG = 3
__version__ = "0.0.3"
__all__ = [
"move", "copy",
"LOG_NONE", "LOG_ERROR", "LOG_INFO", "LOG_DEBUG"
]
class FSItem(object):
def __init__(self, src_path, dest_path):
... | [
"tempfile.NamedTemporaryFile",
"os.remove",
"os.mkdir",
"os.path.isdir",
"shutil.copy2",
"os.path.dirname",
"os.path.exists",
"shutil.move",
"os.rmdir",
"os.path.split"
] | [((3451, 3476), 'os.path.split', 'os.path.split', (['basis_path'], {}), '(basis_path)\n', (3464, 3476), False, 'import os\n'), ((3486, 3563), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': "(basename + '_')", 'dir': 'dirname', 'delete': '(False)'}), "(prefix=basename + '_', dir=dirname, d... |
import unittest
from solution import Solution
class TestContains(unittest.TestCase):
def setUp(self):
self.solution = Solution()
pass
def test_case_1(self):
s = "abab"
self.assertEqual(self.solution.repeated_strings(s=s), True)
def test_case_2(self):
s = "abcab... | [
"unittest.TextTestRunner",
"solution.Solution"
] | [((132, 142), 'solution.Solution', 'Solution', ([], {}), '()\n', (140, 142), False, 'from solution import Solution\n'), ((544, 580), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (567, 580), False, 'import unittest\n')] |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import plotly.express as px
from datetime import datetime
# ext_style = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__... | [
"datetime.datetime.strftime",
"dash.Dash",
"dash_html_components.H2",
"pandas.read_csv",
"dash_html_components.Div",
"dash_core_components.RadioItems",
"dash.dependencies.Input",
"pandas.to_datetime",
"dash_core_components.Tab",
"dash_html_components.Figcaption",
"dash_core_components.Graph",
... | [((302, 321), 'dash.Dash', 'dash.Dash', (['__name__'], {}), '(__name__)\n', (311, 321), False, 'import dash\n'), ((515, 554), 'pandas.read_csv', 'pd.read_csv', (['covid_tracker_states_daily'], {}), '(covid_tracker_states_daily)\n', (526, 554), True, 'import pandas as pd\n'), ((575, 610), 'pandas.to_datetime', 'pd.to_da... |
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as L
import efficientnet.tfkeras as efn
from mrcnn.config import Config as mcConfig
from mrcnn import model as mcmodel
class ProcessingStep:
def __init__(self):
pass
def apply(self, data):
pass
class Prep... | [
"efficientnet.tfkeras.EfficientNetB7",
"tensorflow.keras.layers.Dense",
"cv2.cvtColor",
"tensorflow.keras.layers.GlobalAveragePooling2D",
"cv2.resize"
] | [((548, 584), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (560, 584), False, 'import cv2\n'), ((1616, 1694), 'efficientnet.tfkeras.EfficientNetB7', 'efn.EfficientNetB7', ([], {'input_shape': '(256, 256, 3)', 'weights': 'None', 'include_top': '(False)'}), '(input_sha... |
import logging
import json
import time
import boto3
from botocore.config import Config as BotoCoreConfig
from botocore.exceptions import ClientError
import signal
from abc import ABCMeta, abstractmethod
from threading import Thread, Lock
logger = logging.getLogger('stefuna')
_default_sigterm_handler = signal.signal... | [
"threading.Thread",
"json.loads",
"boto3.client",
"json.dumps",
"botocore.config.Config",
"threading.Lock",
"time.time",
"time.sleep",
"signal.signal",
"logging.getLogger"
] | [((249, 277), 'logging.getLogger', 'logging.getLogger', (['"""stefuna"""'], {}), "('stefuna')\n", (266, 277), False, 'import logging\n'), ((307, 352), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'signal.SIG_DFL'], {}), '(signal.SIGTERM, signal.SIG_DFL)\n', (320, 352), False, 'import signal\n'), ((7693, 7748),... |
from .persistence import agent_data
import random
import json
import os.path
def generate_players_config_from_db(game_type, num_players):
agent_ids = agent_data.get_agents(game_type=game_type,
has_file=True,
fields=['owner', 'name'])
... | [
"random.sample",
"json.load",
"random.choice"
] | [((353, 390), 'random.sample', 'random.sample', (['agent_ids', 'num_players'], {}), '(agent_ids, num_players)\n', (366, 390), False, 'import random\n'), ((1004, 1019), 'json.load', 'json.load', (['conf'], {}), '(conf)\n', (1013, 1019), False, 'import json\n'), ((2479, 2510), 'random.choice', 'random.choice', (['registe... |
from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 107:
Crie um módulo chamado moeda.py que tenha as funções
incorporadas aumentar(), diminuir(), dobro() e metade().
Faça também um programa que importe esse módulo e use
algumas dessas funções.
''')
import moeda
p = float(input... | [
"moeda.dobro",
"moeda.metade",
"os.system",
"moeda.aumentar",
"moeda.diminuir"
] | [((28, 70), 'os.system', 'system', (["('cls' if name == 'nt' else 'clear')"], {}), "('cls' if name == 'nt' else 'clear')\n", (34, 70), False, 'from os import system, name\n'), ((373, 388), 'moeda.metade', 'moeda.metade', (['p'], {}), '(p)\n', (385, 388), False, 'import moeda\n'), ((418, 432), 'moeda.dobro', 'moeda.dobr... |
from typing import Callable
from threading import Thread as _Thread
from concurrent.futures import ThreadPoolExecutor as _ThreadPoolExecutor
class Promise:
"""Base promise class"""
def __init__(self, callback: Callable, *args, **kwargs):
# Main callback
self.callback = callback
self.a... | [
"threading.Thread",
"concurrent.futures.ThreadPoolExecutor"
] | [((1162, 1191), 'threading.Thread', '_Thread', ([], {'target': 'self._execute'}), '(target=self._execute)\n', (1169, 1191), True, 'from threading import Thread as _Thread\n'), ((1370, 1391), 'concurrent.futures.ThreadPoolExecutor', '_ThreadPoolExecutor', ([], {}), '()\n', (1389, 1391), True, 'from concurrent.futures im... |
"""
@author : <NAME>
@date : 1 - 23 - 2021
The loss functions are really simple. You just need to understand whether it is a classification or regression task.
All losses will be set in the model.finalize() model.
"""
import numpy as np
import warnings
from scipy.special import softmax as sfmx_indiv
warnings.filterwa... | [
"numpy.apply_along_axis",
"numpy.power",
"numpy.log",
"warnings.filterwarnings"
] | [((303, 361), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (326, 361), False, 'import warnings\n'), ((1222, 1259), 'numpy.apply_along_axis', 'np.apply_along_axis', (['sfmx_indiv', '(1)', 'x'], {}), '(sfmx_indiv, 1, x)\... |
import json
import pathlib
import sys
from tracer import tracer
def service(request):
"""
Trace service function used by the serveless framework.
It can be tested locally with the functions-framework package.
Request method must be POST (or OPTIONS for CORS), and contain the Content-Type set to appli... | [
"pathlib.Path",
"tracer.tracer.Tracer",
"json.dumps"
] | [((1878, 1970), 'json.dumps', 'json.dumps', (['tracer_response'], {'check_circular': '(False)', 'indent': 'indent', 'separators': 'separators'}), '(tracer_response, check_circular=False, indent=indent, separators\n =separators)\n', (1888, 1970), False, 'import json\n'), ((1751, 1780), 'tracer.tracer.Tracer', 'tracer... |
"""
Django settings for meiduo_mall project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os... | [
"os.path.dirname",
"os.path.join",
"datetime.timedelta",
"pathlib.Path"
] | [((10045, 10096), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""utils/fastdfs/client.conf"""'], {}), "(BASE_DIR, 'utils/fastdfs/client.conf')\n", (10057, 10096), False, 'import os\n'), ((581, 611), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""apps"""'], {}), "(BASE_DIR, 'apps')\n", (593, 611), False, 'import o... |
import pickle
from typing import * # pylint: disable=W0401,W0614
class Seq2SeqConfig:
def __init__(self, **kwargs: Dict[str, Any]):
for key, value in kwargs.items():
setattr(self, key, value)
def save(self, file_path: str) -> None:
with open(file_path, "wb") as handle:
... | [
"pickle.dump",
"pickle.load"
] | [((322, 381), 'pickle.dump', 'pickle.dump', (['self', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(self, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (333, 381), False, 'import pickle\n'), ((515, 534), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (526, 534), False, 'import pickle\n')] |
#!/usr/bin/env python3
import sys
def test_we_can_import_module():
import assert_raises
def test_context_manager_exists():
import assert_raises
assert_raises.assert_raises
def test_context_manager_raises_exception():
import assert_raises
with assert_raises.assert_raises(Exception):
1 / 0... | [
"assert_raises.assert_raises",
"pytest.main"
] | [((901, 939), 'pytest.main', 'pytest.main', (['([__file__] + sys.argv[1:])'], {}), '([__file__] + sys.argv[1:])\n', (912, 939), False, 'import pytest\n'), ((267, 305), 'assert_raises.assert_raises', 'assert_raises.assert_raises', (['Exception'], {}), '(Exception)\n', (294, 305), False, 'import assert_raises\n'), ((400,... |
from twisted.logger import Logger
log = Logger("fakeports")
class LogMessages:
PORT_PROBE = "[PROBE] {src_ip}:{dst_port}"
SERVICE_PROBE = "[SERVICE_PROBE] {src_ip}:{dst_port} Probe: {probe} Reply: {reply}"
SERVICE_STARTED = "[SERVICE] Started"
CONNECTION = "[CONNECTION] {src_ip}:{dst_port}" | [
"twisted.logger.Logger"
] | [((40, 59), 'twisted.logger.Logger', 'Logger', (['"""fakeports"""'], {}), "('fakeports')\n", (46, 59), False, 'from twisted.logger import Logger\n')] |
import numpy as np
import keras.backend.tensorflow_backend as backend
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Activation, Flatten
from keras.optimizers import Adam
from keras.callbacks import TensorBoard
import tensorflow as tf
from collections import deque
imp... | [
"numpy.random.seed",
"game.VanilaGame",
"tensorflow.compat.v1.InteractiveSession",
"random.sample",
"keras.models.Sequential",
"tensorflow.executing_eagerly",
"numpy.random.randint",
"collections.deque",
"keras.layers.Flatten",
"numpy.max",
"random.seed",
"keras.layers.MaxPooling2D",
"tensor... | [((432, 454), 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), '()\n', (452, 454), True, 'import tensorflow as tf\n'), ((1106, 1130), 'game.VanilaGame', 'VanilaGame', (['(300)', '(300)', '(30)'], {}), '(300, 300, 30)\n', (1116, 1130), False, 'from game import VanilaGame, Snake, Food, Board\n'), ((1193,... |
"""Testing for Linear model module."""
import numpy as np
import pytest
from sklearn.base import is_regressor
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.exceptions import NotFittedError
from pyrcn.linear_model import IncrementalRegression
from sklearn... | [
"pyrcn.linear_model.IncrementalRegression",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_diabetes",
"numpy.random.RandomState",
"pytest.raises",
"numpy.matmul",
"numpy.linspace",
"numpy.array_split",
"numpy.testing.assert_allclose",
"sklearn.base.is_regressor",
"sklearn.lin... | [((374, 404), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (387, 404), False, 'from sklearn.datasets import load_diabetes\n'), ((479, 504), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (500, 504), True, 'import numpy as np\n'... |
import torch
import torch.nn as nn
import numpy as np
from ._cdht.dht_func import C_dht
class DHT_Layer(nn.Module):
def __init__(self, input_dim, dim, numAngle, numRho):
super(DHT_Layer, self).__init__()
self.fist_conv = nn.Sequential(
nn.Conv2d(input_dim, dim, 1),
nn.BatchN... | [
"torch.nn.BatchNorm2d",
"torch.nn.Conv2d",
"torch.nn.ReLU"
] | [((269, 297), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_dim', 'dim', '(1)'], {}), '(input_dim, dim, 1)\n', (278, 297), True, 'import torch.nn as nn\n'), ((311, 330), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['dim'], {}), '(dim)\n', (325, 330), True, 'import torch.nn as nn\n'), ((344, 353), 'torch.nn.ReLU', 'nn.ReLU', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Model for fitting an absorption profile to spectral data. """
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = ["ProfileFittingModel"]
import logging
import numpy as np
import scipy.optimize as op... | [
"numpy.nanpercentile",
"numpy.abs",
"numpy.nanmedian",
"numpy.floor",
"numpy.ones",
"numpy.isnan",
"numpy.mean",
"numpy.exp",
"astropy.constants.c.to",
"numpy.polyval",
"numpy.std",
"numpy.isfinite",
"numpy.max",
"numpy.log10",
"numpy.nansum",
"numpy.ones_like",
"scipy.optimize.curve... | [((632, 659), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (649, 659), False, 'import logging\n'), ((1077, 1126), 'numpy.exp', 'np.exp', (['(-(x - position) ** 2 / (2.0 * sigma ** 2))'], {}), '(-(x - position) ** 2 / (2.0 * sigma ** 2))\n', (1083, 1126), True, 'import numpy as np\n'), (... |
from services.entities.User import User
from services.data_access.UserRepository import CachedUserRepository
from dateutil.parser import parse as parse_date
class DuplicateUserException(Exception):
pass
class UserService:
def __init__(self, repository = None):
repository = repository or CachedUserRepo... | [
"services.data_access.UserRepository.CachedUserRepository"
] | [((306, 328), 'services.data_access.UserRepository.CachedUserRepository', 'CachedUserRepository', ([], {}), '()\n', (326, 328), False, 'from services.data_access.UserRepository import CachedUserRepository\n')] |
"""GraphQL resolver functionality"""
from ariadne import (
MutationType,
ObjectType,
ScalarType,
gql,
make_executable_schema,
snake_case_fallback_resolvers,
)
from boxwise_flask.auth_helper import authorization_test
from boxwise_flask.graph_ql.mutation_defs import mutation_defs
from boxwise_fla... | [
"boxwise_flask.models.base.Base.get_from_id",
"ariadne.gql",
"boxwise_flask.auth_helper.authorization_test",
"ariadne.ScalarType",
"ariadne.ObjectType",
"boxwise_flask.models.user.User.get_all_users",
"boxwise_flask.models.user.User.get_user",
"boxwise_flask.models.base.Base.get_for_organisation",
"... | [((552, 571), 'ariadne.ObjectType', 'ObjectType', (['"""Query"""'], {}), "('Query')\n", (562, 571), False, 'from ariadne import MutationType, ObjectType, ScalarType, gql, make_executable_schema, snake_case_fallback_resolvers\n'), ((583, 597), 'ariadne.MutationType', 'MutationType', ([], {}), '()\n', (595, 597), False, ... |
# importing the required libraries
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
# initialising the flask app
app = Flask(__name__)
# The path for uploading the file
@app.route('/')
def upload_file():
return render_template('upload.html')
@app.route('/upload', meth... | [
"flask.Flask",
"flask.render_template",
"werkzeug.utils.secure_filename"
] | [((163, 178), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (168, 178), False, 'from flask import Flask, render_template, request\n'), ((261, 291), 'flask.render_template', 'render_template', (['"""upload.html"""'], {}), "('upload.html')\n", (276, 291), False, 'from flask import Flask, render_template, re... |
from zipfile import ZipFile
import subprocess
import Constants
import Config
import requests
import time
import shutil
import os
import time
import traceback
from pathlib import Path
def main():
try:
print(Constants.UpdaterLaunched)
#wait 3 seconds
print(Constants.wait)
time.sleep(... | [
"os.startfile",
"traceback.print_exc",
"zipfile.ZipFile",
"os.getcwd",
"time.sleep",
"Config.checkINI",
"pathlib.Path",
"Config.initConfig",
"requests.get",
"shutil.copyfileobj",
"Config.writeConfig"
] | [((3290, 3303), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (3300, 3303), False, 'import time\n'), ((309, 322), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (319, 322), False, 'import time\n'), ((368, 385), 'Config.checkINI', 'Config.checkINI', ([], {}), '()\n', (383, 385), False, 'import Config\n'), ((9... |
import pytest
import optunaz.three_step_opt_build_merge
from optunaz.config import ModelMode, OptimizationDirection
from optunaz.config.optconfig import (
OptimizationConfig,
Ridge,
Lasso,
PLS,
RandomForestRegressor,
)
from optunaz.datareader import Dataset
from optunaz.descriptors import ECFP, MAC... | [
"optunaz.descriptors.ECFP_counts.new",
"optunaz.config.optconfig.PLS.new",
"optunaz.config.optconfig.Ridge.new",
"optunaz.config.optconfig.RandomForestRegressor.new",
"optunaz.config.optconfig.Lasso.new",
"optunaz.descriptors.MACCS_keys.new",
"optunaz.config.optconfig.OptimizationConfig.Settings",
"op... | [((613, 711), 'optunaz.datareader.Dataset', 'Dataset', ([], {'input_column': '"""canonical"""', 'response_column': '"""molwt"""', 'training_dataset_file': 'file_drd2_50'}), "(input_column='canonical', response_column='molwt',\n training_dataset_file=file_drd2_50)\n", (620, 711), False, 'from optunaz.datareader impor... |
# Based on
# huggingface/notebooks/examples/language_modeling_from_scratch.ipynb
import argparse
import tempfile
import pandas as pd
import torch
from datasets import load_dataset
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
Trainer,
TrainingArguments,
)
import ray
... | [
"datasets.load_dataset",
"pandas.DataFrame",
"transformers.AutoConfig.from_pretrained",
"ray.init",
"argparse.ArgumentParser",
"transformers.AutoModelForCausalLM.from_config",
"ray.data.from_huggingface",
"transformers.AutoTokenizer.from_pretrained",
"tempfile.mkdtemp",
"torch.cuda.is_available",
... | [((3747, 3940), 'ray.train.huggingface.HuggingFaceTrainer', 'HuggingFaceTrainer', ([], {'trainer_init_per_worker': 'train_function', 'scaling_config': "{'num_workers': num_workers, 'use_gpu': use_gpu}", 'datasets': "{'train': ray_train, 'evaluation': ray_validation}"}), "(trainer_init_per_worker=train_function, scaling... |
import os
from configuration.DataPackageServerConstants import DataPackageServerConstants
from configuration.LoggingConstants import LoggingConstants
from pathlib import PurePath
class CreateStartupFilesController:
def __init__(self):
self.file_dir = os.path.dirname(os.path.realpath(__file__))
self.... | [
"os.mkdir",
"os.path.realpath",
"configuration.DataPackageServerConstants.DataPackageServerConstants",
"configuration.LoggingConstants.LoggingConstants"
] | [((279, 305), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (295, 305), False, 'import os\n'), ((575, 602), 'os.mkdir', 'os.mkdir', (['self.dp_directory'], {}), '(self.dp_directory)\n', (583, 602), False, 'import os\n'), ((661, 690), 'os.mkdir', 'os.mkdir', (['self.logs_directory'], {}), '... |
from multiprocessing import Pool
def multi_process_lst(lst, apply_on_chunk, chunk_size=1000, n_processes=1, args=None):
'''
applies apply_on_chunk on lst using n_processes each gets chunk_size items from lst each time
'''
chunks = split(lst, n_processes)
chunks = flatten_iterable(group(c, chunk_si... | [
"multiprocessing.Pool"
] | [((470, 487), 'multiprocessing.Pool', 'Pool', (['n_processes'], {}), '(n_processes)\n', (474, 487), False, 'from multiprocessing import Pool\n')] |
# BSD 3-Clause License.
#
# Copyright (c) 2019-2021 <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this li... | [
"romcomma.gpr.tf.device",
"time.time",
"romcomma.gpr.GP.copy",
"romcomma.gsa.GSA",
"romcomma.data.Fold"
] | [((2197, 2203), 'time.time', 'time', ([], {}), '()\n', (2201, 2203), False, 'from time import time\n'), ((2310, 2316), 'time.time', 'time', ([], {}), '()\n', (2314, 2316), False, 'from time import time\n'), ((3212, 3233), 'romcomma.gpr.tf.device', 'gpr.tf.device', (['device'], {}), '(device)\n', (3225, 3233), False, 'f... |
from django.contrib import admin
from my_site import models
# Register your models here.
admin.site.register(models.UserInfo)
admin.site.register(models.UserToken)
admin.site.register(models.FreeCourse)
admin.site.register(models.SeniorCourse)
admin.site.register(models.GoodsCategory)
admin.site.register(models.Goods)
... | [
"django.contrib.admin.site.register"
] | [((89, 125), 'django.contrib.admin.site.register', 'admin.site.register', (['models.UserInfo'], {}), '(models.UserInfo)\n', (108, 125), False, 'from django.contrib import admin\n'), ((126, 163), 'django.contrib.admin.site.register', 'admin.site.register', (['models.UserToken'], {}), '(models.UserToken)\n', (145, 163), ... |
from airflow.utils.email import send_email
def notify_email(context) -> None:
"""Send custom email alerts."""
# email title.
title = "Airflow alert: {} Failed".format(context['task_instance'].task_id)
# email contents
body = """
Hi Everyone, <br>
<br>
There's been an error in the {} ... | [
"airflow.utils.email.send_email"
] | [((449, 483), 'airflow.utils.email.send_email', 'send_email', (['"""<EMAIL>"""', 'title', 'body'], {}), "('<EMAIL>', title, body)\n", (459, 483), False, 'from airflow.utils.email import send_email\n')] |
import glob
import os
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
#import importlib
#import logisRegresANA
def main():
np.random.seed(1) # shuffle random seed generator
# Ising model parameters
L=40 # linear system size
J=-1.0 # Ising interaction
T=np.linspace(0.... | [
"pickle.dump",
"numpy.random.seed",
"sklearn.model_selection.train_test_split",
"pickle.load",
"numpy.where",
"numpy.linspace",
"numpy.unpackbits",
"os.path.expanduser",
"numpy.concatenate"
] | [((167, 184), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (181, 184), True, 'import numpy as np\n'), ((306, 332), 'numpy.linspace', 'np.linspace', (['(0.25)', '(4.0)', '(16)'], {}), '(0.25, 4.0, 16)\n', (317, 332), True, 'import numpy as np\n'), ((815, 832), 'pickle.load', 'pickle.load', (['file'], {... |
import random
import string
import pytest
def random_string() -> str:
return "".join(random.choice(string.ascii_lowercase) for i in range(10))
@pytest.fixture
def license() -> str:
return random_string()
@pytest.fixture
def package() -> str:
return random_string()
@pytest.fixture
def version() -> s... | [
"random.choice",
"random.randint"
] | [((372, 394), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (386, 394), False, 'import random\n'), ((92, 129), 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), '(string.ascii_lowercase)\n', (105, 129), False, 'import random\n')] |
import numpy as np
import pytest
from unittest import TestCase
from unittest.mock import MagicMock
from mvc.controllers.eval import EvalController
from tests.test_utils import DummyNetwork, DummyMetrics
from tests.test_utils import make_input, make_output
class TestEvalController:
def setup_method(self):
... | [
"mvc.controllers.eval.EvalController",
"tests.test_utils.make_output",
"unittest.mock.MagicMock",
"tests.test_utils.DummyMetrics",
"numpy.zeros",
"tests.test_utils.make_input",
"tests.test_utils.DummyNetwork",
"pytest.raises",
"numpy.random.random",
"numpy.random.randint",
"pytest.mark.parametri... | [((524, 571), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""batch"""', '[True, False]'], {}), "('batch', [True, False])\n", (547, 571), False, 'import pytest\n'), ((1231, 1278), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""batch"""', '[True, False]'], {}), "('batch', [True, False])\n", (125... |