code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import logging
import os
import shutil
import time
from datetime import datetime, timedelta
from typing import List
# todo: test tar, rsync and pg_dump
from .command import mysqldump, gzip, tar, rsync
from .utils.paths import PathOrStr, to_path
class VPSBackupUtils:
def __init__(self, backup_dest: PathOrStr):
... | [
"logging.basicConfig",
"logging.getLogger",
"datetime.datetime.fromtimestamp",
"os.makedirs",
"os.scandir",
"datetime.datetime.now",
"shutil.rmtree",
"datetime.timedelta"
] | [((326, 421), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(levelname)-8s] %(asctime)s %(message)s"""', 'level': 'logging.INFO'}), "(format='[%(levelname)-8s] %(asctime)s %(message)s',\n level=logging.INFO)\n", (345, 421), False, 'import logging\n'), ((468, 495), 'logging.getLogger', 'logging.... |
from django.contrib import admin
# Register your models here.
from .models import Project
admin.site.register(Project) | [
"django.contrib.admin.site.register"
] | [((94, 122), 'django.contrib.admin.site.register', 'admin.site.register', (['Project'], {}), '(Project)\n', (113, 122), False, 'from django.contrib import admin\n')] |
from copy import copy
class Shared:
dictio = {}
def apply(con, tab_name):
query = "SELECT FIELDNAME, DOMNAME, KEYFLAG, CHECKTABLE, ROLLNAME FROM "+con.table_prefix+"DD03VV WHERE TABNAME = '"+tab_name+"' ORDER BY POSITION"
df = con.execute_read_sql(
query, ["FIELDNAME", "DOMNAME", "KEYFLAG", "CHE... | [
"copy.copy"
] | [((617, 646), 'copy.copy', 'copy', (['Shared.dictio[tab_name]'], {}), '(Shared.dictio[tab_name])\n', (621, 646), False, 'from copy import copy\n')] |
import matplotlib.pyplot as plt
from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.figure(dpi=128, figsize=(10, 6))
plt.scatter(rw.x_values, rw.y_values, c='red', edgecolors='none', s=40)
plt.title("squares numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Squares of Value', fon... | [
"random_walk.RandomWalk",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((73, 85), 'random_walk.RandomWalk', 'RandomWalk', ([], {}), '()\n', (83, 85), False, 'from random_walk import RandomWalk\n'), ((102, 138), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(128)', 'figsize': '(10, 6)'}), '(dpi=128, figsize=(10, 6))\n', (112, 138), True, 'import matplotlib.pyplot as plt\n'), ((1... |
from lrabbit_scrapy.spider import LrabbitSpider
from lrabbit_scrapy.common_utils.network_helper import RequestSession
from lrabbit_scrapy.common_utils.print_log_helper import LogUtils
from lrabbit_scrapy.common_utils.all_in_one import FileStore
import os
from lrabbit_scrapy.common_utils.mysql_helper import MysqlClient
... | [
"lrabbit_scrapy.common_utils.all_in_one.FileStore",
"parsel.Selector",
"lrabbit_scrapy.common_utils.network_helper.RequestSession",
"os.getcwd",
"lrabbit_scrapy.common_utils.print_log_helper.LogUtils.log_running",
"lrabbit_scrapy.common_utils.print_log_helper.LogUtils.log_finish"
] | [((1383, 1399), 'lrabbit_scrapy.common_utils.network_helper.RequestSession', 'RequestSession', ([], {}), '()\n', (1397, 1399), False, 'from lrabbit_scrapy.common_utils.network_helper import RequestSession\n'), ((1429, 1457), 'lrabbit_scrapy.common_utils.network_helper.RequestSession', 'RequestSession', ([], {'proxies':... |
from typing import Tuple
import math
import random
from scripts.probability.distributions import normal_cdf, inverse_normal_cdf
from scripts.hypothesis_and_inference.statistical_hypothesis_testing import (
normal_probability_below,
normal_probability_above,
normal_approximation_to_binomial,
normal_uppe... | [
"scripts.hypothesis_and_inference.statistical_hypothesis_testing.normal_probability_above",
"math.sqrt",
"scripts.hypothesis_and_inference.statistical_hypothesis_testing.normal_approximation_to_binomial",
"scripts.hypothesis_and_inference.statistical_hypothesis_testing.normal_probability_below",
"scripts.hy... | [((930, 973), 'scripts.hypothesis_and_inference.statistical_hypothesis_testing.normal_approximation_to_binomial', 'normal_approximation_to_binomial', (['(1000)', '(0.5)'], {}), '(1000, 0.5)\n', (962, 973), False, 'from scripts.hypothesis_and_inference.statistical_hypothesis_testing import normal_probability_below, norm... |
""" boosts and favs """
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.shortcuts import redirect
from django.utils.decorators import method_d... | [
"django.http.HttpResponseBadRequest",
"django.core.cache.cache.delete",
"django.http.HttpResponse",
"django.utils.decorators.method_decorator",
"bookwyrm.models.Favorite.objects.get",
"bookwyrm.models.Boost.objects.filter",
"bookwyrm.models.Status.objects.get",
"django.http.HttpResponseNotFound",
"b... | [((458, 507), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {'name': '"""dispatch"""'}), "(login_required, name='dispatch')\n", (474, 507), False, 'from django.utils.decorators import method_decorator\n'), ((1077, 1126), 'django.utils.decorators.method_decorator', 'method_decorato... |
#!/usr/bin/env python3
"""
Date : 2021-09-12
Purpose: encrypt all numbers
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Jump the Five',
formatter_class=argparse.Argume... | [
"argparse.ArgumentParser"
] | [((219, 332), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Jump the Five"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Jump the Five', formatter_class=\n argparse.ArgumentDefaultsHelpFormatter)\n", (242, 332), False, 'import argparse\n')] |
# -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
import logging
from shot_detector.features.norms import L1Norm
from shot_detector.features.norms import L2Norm
from sh... | [
"logging.getLogger",
"shot_detector.filters.dsl.DslPlainFilter.dsl_kwargs_decorator"
] | [((445, 472), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (462, 472), False, 'import logging\n'), ((479, 594), 'shot_detector.filters.dsl.DslPlainFilter.dsl_kwargs_decorator', 'DslPlainFilter.dsl_kwargs_decorator', (["('norm_function', (int, str), ['l', 'nm', 'norm', 'f', 'fun', 'funct... |
import base64
import random
import string
from itertools import compress
import yaml
from loguru import logger
from .git_database import create_commit, create_ref, get_contents, get_ref
from .github_api import create_pr, find_existing_pr
from .http_requests import get_request
from .parse_image_tags import get_image_t... | [
"random.sample",
"yaml.safe_dump",
"loguru.logger.info",
"base64.b64encode",
"yaml.safe_load"
] | [((1307, 1327), 'yaml.safe_load', 'yaml.safe_load', (['resp'], {}), '(resp)\n', (1321, 1327), False, 'import yaml\n'), ((1393, 1437), 'loguru.logger.info', 'logger.info', (['"""Updating JupyterHub config..."""'], {}), "('Updating JupyterHub config...')\n", (1404, 1437), False, 'from loguru import logger\n'), ((2365, 24... |
import copy
from pathlib import Path
import pickle
import fire
import second.data.kitti_dataset as kitti_ds
import second.data.nuscenes_dataset as nu_ds
from second.data.all_dataset import create_groundtruth_database
def kitti_data_prep(root_path):
kitti_ds.create_kitti_info_file(root_path)
kitti... | [
"second.data.nuscenes_dataset.create_nuscenes_infos",
"pathlib.Path",
"fire.Fire",
"second.data.kitti_dataset.create_kitti_info_file",
"second.data.kitti_dataset.create_reduced_point_cloud"
] | [((267, 309), 'second.data.kitti_dataset.create_kitti_info_file', 'kitti_ds.create_kitti_info_file', (['root_path'], {}), '(root_path)\n', (298, 309), True, 'import second.data.kitti_dataset as kitti_ds\n'), ((315, 361), 'second.data.kitti_dataset.create_reduced_point_cloud', 'kitti_ds.create_reduced_point_cloud', (['r... |
from django.test import TestCase
from django.contrib.auth.models import User
import datetime
from backend.models import Company, ContractApplication, FreelanceApplication, PermanentApplication
# Test Company Model
class CompanyModelTestCase(TestCase):
def setUp(self):
User.objects.create_user(username="T... | [
"backend.models.Company.objects.get",
"backend.models.FreelanceApplication.objects.get",
"backend.models.ContractApplication.objects.get",
"backend.models.PermanentApplication.objects.get",
"backend.models.Company.objects.create",
"datetime.date.today",
"django.contrib.auth.models.User.objects.get",
"... | [((284, 330), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""Test User"""'}), "(username='Test User')\n", (308, 330), False, 'from django.contrib.auth.models import User\n'), ((351, 389), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'... |
from keyboard_alike import reader
class BarCodeReader(reader.Reader):
"""
This class supports Lindy USB bar code scanner configured to work as a keyboard
http://www.lindy.co.uk/accessories-c9/input-devices-c357/barcode-scanners-c360/barcode-scanner-ccd-usb-p1352
"""
pass
if __name__ == "__main__... | [
"keyboard_alike.reader.disconnect",
"keyboard_alike.reader.read",
"keyboard_alike.reader.initialize"
] | [((396, 415), 'keyboard_alike.reader.initialize', 'reader.initialize', ([], {}), '()\n', (413, 415), False, 'from keyboard_alike import reader\n'), ((453, 472), 'keyboard_alike.reader.disconnect', 'reader.disconnect', ([], {}), '()\n', (470, 472), False, 'from keyboard_alike import reader\n'), ((426, 439), 'keyboard_al... |
"""change project_id in ExecutorGroup to nullable
Revision ID: 735e81eedae4
Revises: <PASSWORD>
Create Date: 2020-01-11 07:16:41.259814
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = N... | [
"sqlalchemy.INTEGER"
] | [((428, 440), 'sqlalchemy.INTEGER', 'sa.INTEGER', ([], {}), '()\n', (438, 440), True, 'import sqlalchemy as sa\n'), ((583, 595), 'sqlalchemy.INTEGER', 'sa.INTEGER', ([], {}), '()\n', (593, 595), True, 'import sqlalchemy as sa\n')] |
# -*- coding: utf-8 -*-
"""
数据获取、存储的中心调度模块
@author: <NAME>
"""
try:
import queue
except ImportError:
import Queue as queue
import os
import pickle
import pandas as pd
import datetime
from threading import Thread
from .fetch import get_ticks_tushare, get_stock_info, get_auth_factor
from .utils import hdf_key... | [
"pickle.dump",
"os.path.join",
"pickle.load",
"os.path.dirname",
"pandas.read_hdf",
"pandas.date_range",
"datetime.timedelta",
"Queue.Queue",
"warnings.filterwarnings",
"pandas.to_datetime"
] | [((339, 372), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (362, 372), False, 'import warnings\n'), ((399, 424), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (414, 424), False, 'import os\n'), ((2622, 2643), 'pandas.to_datetime', 'pd.to_datet... |
import os
import numpy as np
import cv2
from enhance_image import Image_Loader_Utils#, Adjust_Bright_Illumination, Illumination_Finder, Adjust_Darkness
def correct_image_illumination(path):
h,w,ci,gi = Image_Loader_Utils(path).convert_img_to_array()
return ci
def template_matcher(template_gray, image_to_... | [
"os.listdir",
"numpy.where",
"cv2.minMaxLoc",
"cv2.cvtColor",
"enhance_image.Image_Loader_Utils",
"cv2.matchTemplate",
"cv2.imread"
] | [((432, 517), 'cv2.matchTemplate', 'cv2.matchTemplate', (['image_to_be_checked_gray', 'template_gray', 'cv2.TM_CCOEFF_NORMED'], {}), '(image_to_be_checked_gray, template_gray, cv2.TM_CCOEFF_NORMED\n )\n', (449, 517), False, 'import cv2\n'), ((553, 571), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['res'], {}), '(res)\n', (56... |
#file:///C:/Program%20Files/Dymola%202019/Modelica/Library/python_interface/doc/index.html
import os
# Import dymola package
from dymola.dymola_interface import DymolaInterface
# Start the interface
dymola = DymolaInterface()
# Location of your local AixLib clone
dir_aixlib = r"C:\Users\hinack\Dropbox\09_Modelica_Li... | [
"dymola.dymola_interface.DymolaInterface",
"os.path.join"
] | [((210, 227), 'dymola.dymola_interface.DymolaInterface', 'DymolaInterface', ([], {}), '()\n', (225, 227), False, 'from dymola.dymola_interface import DymolaInterface\n'), ((468, 506), 'os.path.join', 'os.path.join', (['dir_aixlib', '"""package.mo"""'], {}), "(dir_aixlib, 'package.mo')\n", (480, 506), False, 'import os\... |
#!/usr/bin/env python3
"""Test that all GOATOOLS package dirs are in the setup.py file"""
# pylint: disable=wrong-import-position
from os import walk
from os.path import join
from os.path import abspath
import sys
sys.argv = [abspath(__file__), '--help']
from setup import NAME # goatools
from setup import PACKAGE... | [
"os.path.abspath",
"os.path.join"
] | [((227, 244), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (234, 244), False, 'from os.path import abspath\n'), ((1170, 1186), 'os.path.join', 'join', (['REPO', 'NAME'], {}), '(REPO, NAME)\n', (1174, 1186), False, 'from os.path import join\n')] |
import time
import csv
import pickle
from libproxmox import Proxmox
proxmox = Proxmox()
CSV_DIR = "./deployment.csv"
print("[INFO ] Reading deployment from:", CSV_DIR)
print("[INFO ] Deleting deployment")
row_count = 0
with open(CSV_DIR, "r") as file:
csvfile = csv.reader(file)
next(csvfile, None) # sk... | [
"libproxmox.Proxmox",
"csv.reader",
"time.sleep"
] | [((80, 89), 'libproxmox.Proxmox', 'Proxmox', ([], {}), '()\n', (87, 89), False, 'from libproxmox import Proxmox\n'), ((274, 290), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (284, 290), False, 'import csv\n'), ((454, 467), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (464, 467), False, 'import time\n... |
from tkinter import Tk, Label, Button, StringVar, Entry, BooleanVar, \
Checkbutton, E, W, END, TclError, messagebox
import genpw
genpw.TEXFRIENDLY = False
genpw.RECURSIVE = True
fenstarr = []
def fkt(event=None):
global t1, myfont, mycolor, v1, v2, v3, v4
try:
if v1.get() == v2.get() == v3.get(... | [
"tkinter.messagebox.showerror",
"tkinter.Entry",
"tkinter.Checkbutton",
"tkinter.BooleanVar",
"tkinter.Button",
"tkinter.StringVar",
"tkinter.Tk",
"tkinter.Label"
] | [((1406, 1410), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (1408, 1410), False, 'from tkinter import Tk, Label, Button, StringVar, Entry, BooleanVar, Checkbutton, E, W, END, TclError, messagebox\n'), ((1417, 1490), 'tkinter.Label', 'Label', (['top'], {'text': '"""Wählen Sie den gewünschten Zeichenvorrat:"""', 'font': 'myfon... |
import yaml
from options.base import BaseOptions
class CustomOptions(BaseOptions):
def __init__(self):
super(CustomOptions, self).__init__()
BaseOptions.initialize(self)
configure_stream = open(self.opt.configure_file, 'r')
experiment_config = yaml.load(configure_stream)
i... | [
"yaml.load",
"options.base.BaseOptions.initialize"
] | [((164, 192), 'options.base.BaseOptions.initialize', 'BaseOptions.initialize', (['self'], {}), '(self)\n', (186, 192), False, 'from options.base import BaseOptions\n'), ((283, 310), 'yaml.load', 'yaml.load', (['configure_stream'], {}), '(configure_stream)\n', (292, 310), False, 'import yaml\n')] |
import numpy as np
import re
import math
import yaml
import importlib
def read_rle(path):
with open(path, "r") as f:
clean_lines = []
for line in f.readlines():
if line[0] != '#': # skip comments
if line[0] == 'x': # get header
header = line
... | [
"math.ceil",
"importlib.import_module",
"math.floor",
"numpy.logical_or",
"yaml.safe_load",
"numpy.zeros",
"numpy.rot90",
"re.findall"
] | [((651, 695), 'numpy.zeros', 'np.zeros', (['(shape_x, shape_y)'], {'dtype': 'np.uint8'}), '((shape_x, shape_y), dtype=np.uint8)\n', (659, 695), True, 'import numpy as np\n'), ((2183, 2214), 'importlib.import_module', 'importlib.import_module', (['module'], {}), '(module)\n', (2206, 2214), False, 'import importlib\n'), ... |
# Copyright (c) 2018 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython
"""
Run all snippets from the examples/snippets/ directory
and display a summary at the end.
"""
from common import *
import glob
import os
impo... | [
"os.path.basename",
"os.path.join",
"subprocess.call",
"sys.exit"
] | [((421, 455), 'os.path.join', 'os.path.join', (['SNIPPETS_DIR', '"""*.py"""'], {}), "(SNIPPETS_DIR, '*.py')\n", (433, 455), False, 'import os\n'), ((659, 701), 'subprocess.call', 'subprocess.call', (['[sys.executable, snippet]'], {}), '([sys.executable, snippet])\n', (674, 701), False, 'import subprocess\n'), ((1529, 1... |
"""An emulation of the opentrons magnetic module.
The purpose is to provide a fake backend that responds to GCODE commands.
"""
import logging
from typing import Optional
from opentrons.drivers.mag_deck.driver import GCODES
from opentrons.hardware_control.emulation.parser import Parser, Command
from .abstract_emulato... | [
"logging.getLogger"
] | [((356, 383), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (373, 383), False, 'import logging\n')] |
from PIL import Image, ImageDraw, ImageFont
import libs
font_w = 12
tex_w = 1024
tex_h = 512
font = ImageFont.truetype('simsun.ttc', font_w)
image = Image.new(mode='RGBA', size=(tex_w, tex_h))
draw_table = ImageDraw.Draw(im=image)
y = 1
charMapF = open("CSE3.tbl", "r", encoding="utf-16")
chars = []
while(True):
t... | [
"PIL.Image.new",
"PIL.ImageFont.truetype",
"PIL.ImageDraw.Draw",
"libs.writeInt1",
"libs.writeInt2",
"libs.writeInt2BE"
] | [((100, 140), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""simsun.ttc"""', 'font_w'], {}), "('simsun.ttc', font_w)\n", (118, 140), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((149, 192), 'PIL.Image.new', 'Image.new', ([], {'mode': '"""RGBA"""', 'size': '(tex_w, tex_h)'}), "(mode='RGBA', size=(tex... |
import requests
import json
import base64
import redis
import os
def handle(st):
# parse Github event
req = json.loads(st)
minutes = 1
minutes_val = os.getenv("cache-minutes")
if minutes_val != None:
minutes = int(minutes_val)
loginName = req["sender"]["login"]
try:
redis... | [
"json.loads",
"requests.post",
"os.getenv",
"json.dumps",
"redis.StrictRedis",
"base64.standard_b64decode"
] | [((117, 131), 'json.loads', 'json.loads', (['st'], {}), '(st)\n', (127, 131), False, 'import json\n'), ((167, 193), 'os.getenv', 'os.getenv', (['"""cache-minutes"""'], {}), "('cache-minutes')\n", (176, 193), False, 'import os\n'), ((859, 925), 'requests.post', 'requests.post', (['"""http://gateway:8080/function/get-ava... |
#!/usr/bin/env python
'''
Dashboard: A graphical interface to view the status of various systems on
NaviGator and a control panel to interact with the running system.
'''
import functools
import os
from navigator_alarm import AlarmListener
from navigator_msgs.msg import Hosts, Host
from python_qt_binding import QtC... | [
"navigator_alarm.AlarmListener",
"remote_control_lib.RemoteControl",
"python_qt_binding.QtCore.QTimer.singleShot",
"python_qt_binding.QtGui.QWidget",
"python_qt_binding.loadUi",
"rospy.get_param",
"functools.wraps",
"rospy.Time.now",
"navigator_msgs.msg.Host",
"navigator_msgs.msg.Hosts",
"rospkg... | [((883, 898), 'python_qt_binding.QtGui.QWidget', 'QtGui.QWidget', ([], {}), '()\n', (896, 898), False, 'from python_qt_binding import QtGui\n'), ((1175, 1204), 'python_qt_binding.loadUi', 'loadUi', (['ui_file', 'self._widget'], {}), '(ui_file, self._widget)\n', (1181, 1204), False, 'from python_qt_binding import loadUi... |
from collections import namedtuple
from fs import open_fs
Iteration = namedtuple("Iteration", ["first", "last", "value"])
def mark_iterable_ends(iterable):
iterator = iter(iterable)
try:
value = next(iterator)
except StopIteration:
return
first = True
for item in iterator:
... | [
"fs.open_fs",
"collections.namedtuple"
] | [((72, 123), 'collections.namedtuple', 'namedtuple', (['"""Iteration"""', "['first', 'last', 'value']"], {}), "('Iteration', ['first', 'last', 'value'])\n", (82, 123), False, 'from collections import namedtuple\n'), ((510, 521), 'fs.open_fs', 'open_fs', (['fs'], {}), '(fs)\n', (517, 521), False, 'from fs import open_fs... |
"""Module about the selector element."""
import enum
import numpy as np
from .element import ElementId, Element
@enum.unique
class Symmetry(enum.Enum):
"""List the available kind of symmetry."""
SYMMETRY_NONE = enum.auto()
SYMMETRY_X = enum.auto()
SYMMETRY_Y = enum.auto()
SYMMETRY_XY = enum.auto... | [
"numpy.max",
"numpy.asarray",
"enum.auto",
"numpy.min"
] | [((223, 234), 'enum.auto', 'enum.auto', ([], {}), '()\n', (232, 234), False, 'import enum\n'), ((252, 263), 'enum.auto', 'enum.auto', ([], {}), '()\n', (261, 263), False, 'import enum\n'), ((281, 292), 'enum.auto', 'enum.auto', ([], {}), '()\n', (290, 292), False, 'import enum\n'), ((311, 322), 'enum.auto', 'enum.auto'... |
import torch
import warnings
from torch.optim.optimizer import Optimizer, required
import math
import itertools as it
import torch.optim as optim
warnings.filterwarnings("once")
def get_optimizer(optimizer: str = 'Adam',
lookahead: bool = False,
model=None,
separa... | [
"itertools.chain",
"torch.optim.Adam",
"math.sqrt",
"torch.empty_like",
"torch.exp",
"torch.zeros_like",
"warnings.filterwarnings"
] | [((146, 177), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""once"""'], {}), "('once')\n", (169, 177), False, 'import warnings\n'), ((993, 1018), 'torch.optim.Adam', 'optim.Adam', (['params'], {'lr': 'lr'}), '(params, lr=lr)\n', (1003, 1018), True, 'import torch.optim as optim\n'), ((30291, 30319), 'iterto... |
# Copyright 2021 The Forte Authors. 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 required by applicable ... | [
"tempfile.TemporaryDirectory",
"ft.onto.base_ontology.CrossDocEntityRelation",
"ft.onto.base_ontology.Sentence",
"forte.data.caster.MultiPackBoxer",
"forte.data.readers.DirPackReader",
"forte.data.readers.MultiPackDirectoryReader",
"os.path.join",
"forte.processors.writers.PackIdJsonPackWriter",
"fo... | [((2795, 2885), 'ddt.data', 'data', (["(True, 'pickle')", "(False, 'pickle')", "(True, 'jsonpickle')", "(False, 'jsonpickle')"], {}), "((True, 'pickle'), (False, 'pickle'), (True, 'jsonpickle'), (False,\n 'jsonpickle'))\n", (2799, 2885), False, 'from ddt import data, ddt\n'), ((5851, 5941), 'ddt.data', 'data', (["(T... |
'''
Created by: <NAME>
Created on: 9/17/2020
'''
import inspect
import logging
import os
import pydre
from pydre.project import Project
logger = logging.getLogger('PydreLogger')
class Pydre:
'''PyDre handler that mediates all pydre functionality accessed by the GUI.
'''
@staticmethod
def run(app, ... | [
"logging.getLogger",
"os.path.join",
"pydre.project.Project",
"inspect.getfile"
] | [((147, 179), 'logging.getLogger', 'logging.getLogger', (['"""PydreLogger"""'], {}), "('PydreLogger')\n", (164, 179), False, 'import logging\n'), ((613, 653), 'pydre.project.Project', 'Project', (['project_file', 'progress_bar', 'app'], {}), '(project_file, progress_bar, app)\n', (620, 653), False, 'from pydre.project ... |
import io
import os
import re
import time
import gevent
from gevent import monkey
monkey.patch_all()
import requests
#网站自带的函数封装了一个类,改变了一下保存路径,发现一个bug:zipfile没有open属性
class Pdf2TableAPI:
def invoke_api(self, api, filename, company_name, file_name_without_pdf):
# 异步执行
output_format = 'zip' # or json... | [
"os.path.exists",
"os.listdir",
"requests.post",
"tarfile.open",
"zipfile.ZipFile",
"gevent.monkey.patch_all",
"os.path.join",
"io.BytesIO",
"time.sleep",
"os.getcwd",
"gevent.joinall",
"re.findall",
"time.time"
] | [((82, 100), 'gevent.monkey.patch_all', 'monkey.patch_all', ([], {}), '()\n', (98, 100), False, 'from gevent import monkey\n'), ((6035, 6046), 'time.time', 'time.time', ([], {}), '()\n', (6044, 6046), False, 'import time\n'), ((6112, 6123), 'time.time', 'time.time', ([], {}), '()\n', (6121, 6123), False, 'import time\n... |
# -*- coding: utf-8 -*-
import unittest
def binary_search(sorted_list: list, first: int, last: int, target: int) -> int:
mid = int((first + last) / 2)
if first > last:
return 0
elif target == sorted_list[mid]:
return 1
else:
if target > sorted_list[mid]:
return bi... | [
"unittest.main"
] | [((1139, 1154), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1152, 1154), False, 'import unittest\n')] |
from transformers import (AutoModelForTokenClassification,
AutoModelForSequenceClassification,
TrainingArguments,
AutoTokenizer,
AutoConfig,
Trainer)
from biobert_ner.utils_ner import (con... | [
"logging.getLogger",
"biobert_ner.utils_ner.NerTestDataset",
"torch.nn.CrossEntropyLoss",
"transformers.TrainingArguments",
"os.path.join",
"bilstm_crf_ner.model.ner_model.NERModel",
"numpy.argmax",
"ehr.HealthRecord",
"annotations.Entity",
"biobert_ner.utils_ner.get_labels",
"biobert_re.utils_r... | [((929, 956), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (946, 956), False, 'import logging\n'), ((1251, 1300), 'biobert_ner.utils_ner.get_labels', 'get_labels', (['"""biobert_ner/dataset_full/labels.txt"""'], {}), "('biobert_ner/dataset_full/labels.txt')\n", (1261, 1300), False, 'fro... |
#!/usr/bin/env python
import re
import logging
import webapp2
import email
import datetime as dt
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import db
import WSF
import pst
import unicodedata
class Alert(db.Model):
body = db.TextProperty() # alert content... | [
"re.split",
"google.appengine.ext.db.Query",
"logging.warn",
"datetime.time",
"google.appengine.ext.db.TextProperty",
"re.compile",
"datetime.datetime.strptime",
"google.appengine.ext.db.IntegerProperty",
"google.appengine.ext.db.DateTimeProperty",
"pst.toPacific",
"datetime.datetime.now",
"un... | [((282, 299), 'google.appengine.ext.db.TextProperty', 'db.TextProperty', ([], {}), '()\n', (297, 299), False, 'from google.appengine.ext import db\n'), ((334, 354), 'google.appengine.ext.db.IntegerProperty', 'db.IntegerProperty', ([], {}), '()\n', (352, 354), False, 'from google.appengine.ext import db\n'), ((402, 440)... |
from django.utils.deprecation import MiddlewareMixin
from django.http.response import HttpResponse
from .utils import get_page_by_path
import logging
logger = logging.getLogger(__name__)
class DeepPageTemplateRendererMiddleware(MiddlewareMixin):
''' The goal of this middleware is find the respective page by UR... | [
"logging.getLogger",
"django.http.response.HttpResponse"
] | [((162, 189), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (179, 189), False, 'import logging\n'), ((1068, 1095), 'django.http.response.HttpResponse', 'HttpResponse', (['rendered_page'], {}), '(rendered_page)\n', (1080, 1095), False, 'from django.http.response import HttpResponse\n')] |
from os import path
import boto3
import argparse
ALLOWED_VISIBILITIES = ['private', 'public-read']
client = None
def init_arguments(args_parser=None):
if not args_parser:
return
args_parser.add_argument('s3_access_key', help='S3 storage access key.', type=str)
args_parser.add_argument('s3_secre... | [
"os.path.isfile",
"boto3.client",
"os.path.basename",
"argparse.ArgumentParser"
] | [((1629, 1654), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1652, 1654), False, 'import argparse\n'), ((2016, 2178), 'boto3.client', 'boto3.client', (['"""s3"""'], {'region_name': 'args.s3_region', 'endpoint_url': 'args.s3_endpoint', 'aws_access_key_id': 'args.s3_access_key', 'aws_secret_ac... |
import pyautogui
import time
def findCoord():
DELAY = 0.25
last_x, last_y, last_rgb = None, None, None
while 1:
x, y = pyautogui.position()
rgb = pyautogui.pixel(x, y)
if x == last_x and y == last_y and rgb == last_rgb:
continue
_x, _y = (str(x).rjust(4) for x... | [
"pyautogui.pixel",
"pyautogui.position",
"pyautogui.screenshot",
"time.sleep"
] | [((542, 603), 'pyautogui.screenshot', 'pyautogui.screenshot', (['name'], {'region': '(x1, y1, x2 - x1, y2 - y1)'}), '(name, region=(x1, y1, x2 - x1, y2 - y1))\n', (562, 603), False, 'import pyautogui\n'), ((721, 777), 'pyautogui.screenshot', 'pyautogui.screenshot', (['name'], {'region': '(x1, y1, wid, height)'}), '(nam... |
'''
Copyright (c) 2014 Dzakub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublice... | [
"wave.open",
"threading.Lock",
"time.strftime",
"threading.Event",
"os.path.isfile",
"sys.exit",
"threading.Thread",
"pyaudio.PyAudio"
] | [((1245, 1262), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (1260, 1262), False, 'import pyaudio\n'), ((1627, 1644), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1642, 1644), False, 'import threading\n'), ((1686, 1702), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1700, 1702), False, '... |
"""
Top-level Flask application for HXL Proxy
<NAME>
January 2015
License: Public Domain
Documentation: http://hxlstandard.org
"""
import os
from flask import Flask, g, request
from flask.ext.cache import Cache
import werkzeug.datastructures
# Main application object
app = Flask(__name__)
app.config.from_object('h... | [
"flask.ext.cache.Cache",
"os.environ.get",
"flask.Flask"
] | [((279, 294), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (284, 294), False, 'from flask import Flask, g, request\n'), ((349, 383), 'os.environ.get', 'os.environ.get', (['"""HXL_PROXY_CONFIG"""'], {}), "('HXL_PROXY_CONFIG')\n", (363, 383), False, 'import os\n'), ((524, 598), 'flask.ext.cache.Cache', 'Ca... |
"""
Setup script for the customcolour package
"""
from setuptools import setup
from setuptools import find_packages
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='customcolour',
version='0.1',
description=('A library of tools for transforming and creating' +
... | [
"setuptools.find_packages"
] | [((595, 610), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (608, 610), False, 'from setuptools import find_packages\n')] |
import argparse
import logging
import os
import time
import sys
from tqdm import tqdm
from chains.binance import MockBinance
from thorchain.thorchain import ThorchainState, ThorchainClient
from utils.common import Transaction, Coin, get_rune_asset
from chains.aliases import get_alias
# Init logging
logging.basicConfi... | [
"sys.exit",
"argparse.ArgumentParser",
"thorchain.thorchain.ThorchainState",
"chains.aliases.get_alias",
"tqdm.tqdm",
"utils.common.get_rune_asset",
"os.environ.get",
"thorchain.thorchain.ThorchainClient",
"time.sleep",
"logging.fatal",
"os.exit",
"time.time",
"utils.common.Coin",
"logging... | [((437, 453), 'utils.common.get_rune_asset', 'get_rune_asset', ([], {}), '()\n', (451, 453), False, 'from utils.common import Transaction, Coin, get_rune_asset\n'), ((481, 506), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (504, 506), False, 'import argparse\n'), ((391, 425), 'os.environ.get'... |
import requests
import os
import urllib.request#下载
import logging#日志
from lxml import etree#选择器
from urllib.error import URLError#异常
logging.basicConfig(level=logging.INFO,
format = '%(asctime)s-%(message)s')
looger = logging.getLogger(__name__)
headers = {'user-agent': 'my-app/0.0.1'}
def getHTML... | [
"logging.basicConfig",
"logging.getLogger",
"os.makedirs",
"os.path.join",
"requests.get",
"logging.error"
] | [((134, 207), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s-%(message)s"""'}), "(level=logging.INFO, format='%(asctime)s-%(message)s')\n", (153, 207), False, 'import logging\n'), ((239, 266), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name_... |
import fnmatch
import json
import logging
import os
import re
from collections import Counter
from operator import itemgetter
import en_core_web_sm
from spacy.matcher import Matcher
from gamechangerml.configs.config import DefaultConfig as Config
import gamechangerml.src.modelzoo.semantic.term_extract.version_ as v
... | [
"logging.getLogger",
"en_core_web_sm.load",
"os.listdir",
"os.path.join",
"operator.itemgetter",
"spacy.matcher.Matcher",
"collections.Counter",
"os.path.isdir",
"fnmatch.fnmatch",
"json.load",
"re.sub"
] | [((329, 361), 'logging.getLogger', 'logging.getLogger', (['"""gamechanger"""'], {}), "('gamechanger')\n", (346, 361), False, 'import logging\n'), ((2022, 2045), 'spacy.matcher.Matcher', 'Matcher', (['self.nlp.vocab'], {}), '(self.nlp.vocab)\n', (2029, 2045), False, 'from spacy.matcher import Matcher\n'), ((2303, 2329),... |
from functools import lru_cache
from operator import itemgetter
from enum import Enum
from hashlib import md5
import os
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from mabed.corpus import Corpus
from mabed.mabed import MABED
import json
import pickle
import marshal
import gc
import time
from d... | [
"pickle.dump",
"gc.enable",
"os.makedirs",
"hashlib.md5",
"gc.disable",
"time.monotonic",
"marshal.dump",
"pickle.load",
"operator.itemgetter",
"os.path.isfile",
"os.path.dirname",
"re.sub",
"marshal.load",
"json.load",
"functools.lru_cache",
"json.dump",
"os.remove"
] | [((1586, 1609), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (1595, 1609), False, 'from functools import lru_cache\n'), ((503, 515), 'gc.disable', 'gc.disable', ([], {}), '()\n', (513, 515), False, 'import gc\n'), ((2395, 2410), 'functools.lru_cache', 'lru_cache', (['(1000)'], {}),... |
import os
import pendulum
from datetime import date, timedelta
import datetime
from dateutil import tz
#==================================================================================================================================
# ... | [
"datetime.datetime",
"datetime.datetime.utcnow",
"dateutil.tz.gettz",
"dateutil.tz.tzutc",
"pendulum.timezone",
"datetime.timedelta"
] | [((548, 585), 'pendulum.timezone', 'pendulum.timezone', (['"""Asia/Ho_Chi_Minh"""'], {}), "('Asia/Ho_Chi_Minh')\n", (565, 585), False, 'import pendulum\n'), ((596, 624), 'dateutil.tz.gettz', 'tz.gettz', (['"""Asia/Ho_Chi_Minh"""'], {}), "('Asia/Ho_Chi_Minh')\n", (604, 624), False, 'from dateutil import tz\n'), ((637, 6... |
from nltk.tokenize.treebank import TreebankWordTokenizer
def treebank_tokenizer(sentence, max_length=0):
"""
Tokenize and truncate sentence
:param sentence: str, a sentence string
:param max_length: int, max token included in the result, 0 for unlimited
:return: list, a list of token
"""
#... | [
"nltk.tokenize.treebank.TreebankWordTokenizer"
] | [((385, 408), 'nltk.tokenize.treebank.TreebankWordTokenizer', 'TreebankWordTokenizer', ([], {}), '()\n', (406, 408), False, 'from nltk.tokenize.treebank import TreebankWordTokenizer\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'第 0009 题:一个HTML文件,找出里面的链接。'
__author__ = 'Drake-Z'
import os, re
from html.parser import HTMLParser
from html.entities import name2codepoint
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (variables, ... | [
"re.match"
] | [((400, 428), 're.match', 're.match', (['"""http(.*?)"""', 'value'], {}), "('http(.*?)', value)\n", (408, 428), False, 'import os, re\n')] |
#!/usr/bin/env python3
from dataclasses import dataclass
import struct
import xlsxwriter
from pokemon_data import Move, Type
def mem_to_z64(addr):
# Offset found by guess and check may vary between roms
return addr - 0x3000
class CONSTANTS:
class RENTAL_OFFSETS:
# Source: https://datacrystal.r... | [
"pokemon_data.Move",
"struct.unpack",
"xlsxwriter.Workbook",
"pokemon_data.Type"
] | [((2408, 2458), 'struct.unpack', 'struct.unpack', (["('>' + 'B' * count_bytes)", 'data_bytes'], {}), "('>' + 'B' * count_bytes, data_bytes)\n", (2421, 2458), False, 'import struct\n'), ((2833, 2876), 'struct.unpack', 'struct.unpack', (["('>' + 'B' * count)", 'val_bytes'], {}), "('>' + 'B' * count, val_bytes)\n", (2846,... |
import json
import logging
import os
import boto3
s3_client = boto3.client("s3")
topic_arn = os.getenv("TOPIC_ARN")
def lambda_handler(event, context):
""" """
logging.info(event)
# The name of the model created in the Pipeline CreateModelStep
bucket_name = event["bucket_name"]
key_name = event... | [
"json.dumps",
"boto3.client",
"logging.info",
"os.getenv"
] | [((64, 82), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (76, 82), False, 'import boto3\n'), ((95, 117), 'os.getenv', 'os.getenv', (['"""TOPIC_ARN"""'], {}), "('TOPIC_ARN')\n", (104, 117), False, 'import os\n'), ((172, 191), 'logging.info', 'logging.info', (['event'], {}), '(event)\n', (184, 191), Fa... |
import os, io, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
print("Running Tests for Uniprot Class")
os.system(currentdir + "\\Uniprot_tests.py")
print("")
print("Running Tests for NCBI Class")... | [
"os.path.dirname",
"sys.path.insert",
"os.system",
"inspect.currentframe"
] | [((127, 154), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (142, 154), False, 'import os, io, sys, inspect\n'), ((155, 184), 'sys.path.insert', 'sys.path.insert', (['(0)', 'parentdir'], {}), '(0, parentdir)\n', (170, 184), False, 'import os, io, sys, inspect\n'), ((228, 272), 'os.system... |
"""
Tools to process galaxy spectra .fits files from SDSS-II Legacy survey.
Authored by <NAME> 02/13/16
"""
# TODO: add parameter descriptions to SpecProcessor, normalize, and process_fits
from __future__ import absolute_import, print_function, division
import numpy as np
from scipy import interp
import time
import... | [
"numpy.mean",
"numpy.log10",
"scipy.interp",
"numpy.zeros",
"numpy.isnan",
"sys.exit",
"time.time",
"numpy.arange"
] | [((3424, 3527), 'numpy.mean', 'np.mean', (['spectra[:, (10 ** self.loglam_grid > 4400.0) * (10 ** self.loglam_grid < \n 4450.0)]'], {'axis': '(1)'}), '(spectra[:, (10 ** self.loglam_grid > 4400.0) * (10 ** self.\n loglam_grid < 4450.0)], axis=1)\n', (3431, 3527), True, 'import numpy as np\n'), ((4282, 4293), 'tim... |
from unittest.mock import PropertyMock
from uuid import uuid4
import pytest
from pytest_httpx import HTTPXMock
from playlist_organizer.client.spotify.client import SpotifyClient
from playlist_organizer.client.spotify.settings import SpotifySettings
@pytest.fixture()
def settings():
return SpotifySettings(api_ho... | [
"playlist_organizer.client.spotify.client.SpotifyClient",
"playlist_organizer.client.spotify.settings.SpotifySettings",
"unittest.mock.PropertyMock",
"pytest.mark.parametrize",
"uuid.uuid4",
"pytest.fixture"
] | [((254, 270), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (268, 270), False, 'import pytest\n'), ((343, 359), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (357, 359), False, 'import pytest\n'), ((647, 771), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""response_filenames"""', "[('spotif... |
import random
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework import viewsets
from rest_framework import decorators as drf_decorators
from rest_framework.request import Request
from rest_framework.response import Response
from extension import defines as e... | [
"random.shuffle",
"drf_yasg.utils.swagger_auto_schema",
"rest_framework.response.Response",
"extension.serializers.GetExtensionFieldsSerializer",
"rest_framework.decorators.action"
] | [((503, 555), 'rest_framework.decorators.action', 'drf_decorators.action', ([], {'detail': '(False)', 'methods': "['GET']"}), "(detail=False, methods=['GET'])\n", (524, 555), True, 'from rest_framework import decorators as drf_decorators\n'), ((588, 832), 'drf_yasg.utils.swagger_auto_schema', 'swagger_auto_schema', ([]... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class StructureMap_GroupSchema:
"""
A Map of relationships between 2 structures ... | [
"pyspark.sql.types.StringType",
"spark_fhir_schemas.stu3.complex_types.structuremap_rule.StructureMap_RuleSchema.get_schema",
"spark_fhir_schemas.stu3.complex_types.extension.ExtensionSchema.get_schema",
"spark_fhir_schemas.stu3.complex_types.structuremap_input.StructureMap_InputSchema.get_schema"
] | [((3524, 3536), 'pyspark.sql.types.StringType', 'StringType', ([], {}), '()\n', (3534, 3536), False, 'from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType\n'), ((4925, 4937), 'pyspark.sql.types.StringType', 'StringType', ([], {}), '()\n', (4935, 4937), False, 'from pyspark.sql.types im... |
import sys
import time
class ProgressBar(object):
"""ProgressBar"""
def __init__(self, progressname = 'Progress',total = 100, current = 0, flushfreq = 0.001):
self.total = total
self.current = current
self.progressname = progressname
self.flushfreq = flushfreq
@property
def percentage(self):
return int(... | [
"sys.stdout.flush",
"time.sleep",
"sys.stdout.write"
] | [((632, 650), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (648, 650), False, 'import sys\n'), ((653, 683), 'sys.stdout.write', 'sys.stdout.write', (['self.content'], {}), '(self.content)\n', (669, 683), False, 'import sys\n'), ((686, 704), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (702, 70... |
import numpy as np
import pathlib
import cv2
import pandas as pd
import copy
import os
import logging
import json
class COCOTest:
'''
Minimal pytorch dataset class for loading COCO test dataset,
which has only images and no annotations.
'''
def __init__(self, root):
self.root = os.path.ab... | [
"os.path.join",
"json.load",
"cv2.cvtColor",
"os.path.abspath",
"cv2.imread"
] | [((310, 331), 'os.path.abspath', 'os.path.abspath', (['root'], {}), '(root)\n', (325, 331), False, 'import os\n'), ((362, 427), 'os.path.join', 'os.path.join', (['root', '"""annotations"""', '"""image_info_test-dev2017.json"""'], {}), "(root, 'annotations', 'image_info_test-dev2017.json')\n", (374, 427), False, 'import... |
''' A module containing distance metrics for angles etc.
'''
from math import pi
import autograd.numpy as np
import tensorflow as tf
def angle_diff(theta1, theta2):
''' An angle subtraction method.
'''
if isinstance(theta1, tf.Tensor) or isinstance(theta2, tf.Tensor):
delta = tf.mod(theta1 - thet... | [
"autograd.numpy.abs",
"tensorflow.mod",
"autograd.numpy.mod",
"tensorflow.abs"
] | [((636, 649), 'autograd.numpy.abs', 'np.abs', (['delta'], {}), '(delta)\n', (642, 649), True, 'import autograd.numpy as np\n'), ((611, 624), 'tensorflow.abs', 'tf.abs', (['delta'], {}), '(delta)\n', (617, 624), True, 'import tensorflow as tf\n'), ((300, 336), 'tensorflow.mod', 'tf.mod', (['(theta1 - theta2 - pi)', '(2 ... |
import cairo
import vector
from .widget import Widget
class Window(Widget):
clickable = False
mousable = False
scale = None
image_resolution = None
_image = None
def __init__(self, resource_manager):
Widget.__init__(self, resource_manager)
self._image = resource_ma... | [
"vector.Scale"
] | [((490, 508), 'vector.Scale', 'vector.Scale', (['(1)', '(1)'], {}), '(1, 1)\n', (502, 508), False, 'import vector\n')] |
import argparse
import json
from typing import Any, cast, Dict
from ..lib import api, args as _args, errors, reporting, utils, workflows as _workflows
from ..lib.parsing import parse_workflow_inputs
async def call(args: Dict[str, Any], cromwell: api.CromwellAPI) -> None:
"""Execute the subcommand.
Args:
... | [
"json.loads",
"typing.cast"
] | [((3121, 3147), 'json.loads', 'json.loads', (['workflowInputs'], {}), '(workflowInputs)\n', (3131, 3147), False, 'import json\n'), ((3169, 3196), 'json.loads', 'json.loads', (['workflowOptions'], {}), '(workflowOptions)\n', (3179, 3196), False, 'import json\n'), ((3217, 3243), 'json.loads', 'json.loads', (['workflowLab... |
# Generated by Django 3.1 on 2020-08-25 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0002_answer_questions'),
]
operations = [
migrations.AlterField(
model_name='answer',
name='text... | [
"django.db.models.CharField"
] | [((342, 387), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'unique': '(True)'}), '(max_length=200, unique=True)\n', (358, 387), False, 'from django.db import migrations, models\n')] |
import re
from ast import literal_eval
from typing import Dict, Union
import boto3
import botocore
from pendant import aws
__all__ = ['S3Uri', 's3api_head_object', 's3api_object_exists', 's3_object_exists']
class S3Uri(object):
"""An S3 URI which conforms to RFC 3986 formatting.
Args:
path: The S... | [
"pendant.aws.cli",
"boto3.resource",
"ast.literal_eval",
"re.compile"
] | [((608, 630), 're.compile', 're.compile', (['"""^s3://.*"""'], {}), "('^s3://.*')\n", (618, 630), False, 'import re\n'), ((654, 678), 're.compile', 're.compile', (['"""^(s3://).*"""'], {}), "('^(s3://).*')\n", (664, 678), False, 'import re\n'), ((699, 734), 're.compile', 're.compile', (['"""^s3://[^/\\\\n]+/?(.*)?"""']... |
print("-"*20)
print("Festa de Ano Novo")
print("-"*20)
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print("Feliz Ano Novo!") | [
"time.sleep"
] | [((124, 132), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (129, 132), False, 'from time import sleep\n')] |
import sys, os, time
from importlib import reload
import eureka.S3_data_reduction.s3_reduce as s3
import eureka.S4_generate_lightcurves.s4_genLC as s4
eventlabel = 'wasp43b'
reload(s3)
ev3 = s3.reduceJWST(eventlabel)
reload(s4)
ev4 = s4.lcJWST(ev3.eventlabel, ev3.workdir, md=ev3)
| [
"eureka.S4_generate_lightcurves.s4_genLC.lcJWST",
"importlib.reload",
"eureka.S3_data_reduction.s3_reduce.reduceJWST"
] | [((176, 186), 'importlib.reload', 'reload', (['s3'], {}), '(s3)\n', (182, 186), False, 'from importlib import reload\n'), ((193, 218), 'eureka.S3_data_reduction.s3_reduce.reduceJWST', 's3.reduceJWST', (['eventlabel'], {}), '(eventlabel)\n', (206, 218), True, 'import eureka.S3_data_reduction.s3_reduce as s3\n'), ((220, ... |
import logging
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.template.loader import render_to_string
from django.utils.encoding import smart_text
from django.con... | [
"logging.getLogger",
"django.contrib.auth.get_user_model",
"django.contrib.messages.warning",
"django.utils.encoding.smart_text",
"django.contrib.auth.models.User.objects.get",
"django.template.loader.render_to_string"
] | [((624, 640), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (638, 640), False, 'from django.contrib.auth import get_user_model\n'), ((1702, 1729), 'logging.getLogger', 'logging.getLogger', (['"""viewas"""'], {}), "('viewas')\n", (1719, 1729), False, 'import logging\n'), ((4419, 4523), 'djang... |
import numpy as np
from .population import Population
from spike_swarm_sim.utils import eigendecomposition, normalize
class CMA_EA_Population(Population):
def __init__(self, *args, **kwargs):
super(CMA_EA_Population, self).__init__(*args, **kwargs)
self.mu = int(.5 * self.pop_size)
... | [
"numpy.clip",
"numpy.eye",
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.arange",
"numpy.random.random",
"numpy.log",
"numpy.diag",
"numpy.outer",
"numpy.linalg.norm",
"numpy.zeros_like",
"numpy.triu"
] | [((3401, 3431), 'numpy.linalg.eig', 'np.linalg.eig', (['self.strategy_C'], {}), '(self.strategy_C)\n', (3414, 3431), True, 'import numpy as np\n'), ((3450, 3473), 'numpy.diag', 'np.diag', (['(self.D ** -0.5)'], {}), '(self.D ** -0.5)\n', (3457, 3473), True, 'import numpy as np\n'), ((4031, 4054), 'numpy.eye', 'np.eye',... |
# -*- coding: utf-8 -*-
"""
Script Name: Widget.py
Author: <NAME>/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
from PySide2.QtWidgets import QWidget
from pyPLM.Gui import AppIcon
from pyPLM.se... | [
"pyPLM.Gui.AppIcon",
"pyPLM.settings.AppSettings"
] | [((788, 805), 'pyPLM.settings.AppSettings', 'AppSettings', (['self'], {}), '(self)\n', (799, 805), False, 'from pyPLM.settings import AppSettings\n'), ((703, 724), 'pyPLM.Gui.AppIcon', 'AppIcon', (['(32)', 'self.key'], {}), '(32, self.key)\n', (710, 724), False, 'from pyPLM.Gui import AppIcon\n')] |
from lazysql import Base, update_all, viewtable, db
class User(Base):
__tablename__ = 'users'
user_id = ('SERIAL', 'PRIMARY KEY')
username = ('varchar(256)', 'NOT NULL')
class Post(Base):
__tablename__ = 'posts'
post_id = ('SERIAL', 'PRIMARY KEY')
text = ('varchar', 'NOT NULL')
update_all()... | [
"lazysql.db.close",
"lazysql.viewtable",
"lazysql.update_all"
] | [((308, 320), 'lazysql.update_all', 'update_all', ([], {}), '()\n', (318, 320), False, 'from lazysql import Base, update_all, viewtable, db\n'), ((477, 487), 'lazysql.db.close', 'db.close', ([], {}), '()\n', (485, 487), False, 'from lazysql import Base, update_all, viewtable, db\n'), ((459, 474), 'lazysql.viewtable', '... |
from market import app
from tools import cls
def page():
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=8080)
def run():
page()
# thread = threading.Thread(target=page)
# thread.start()
# code
try:
run()
except ImportError:
run()
cls()
| [
"tools.cls",
"market.app.run"
] | [((98, 144), 'market.app.run', 'app.run', ([], {'debug': '(True)', 'host': '"""0.0.0.0"""', 'port': '(8080)'}), "(debug=True, host='0.0.0.0', port=8080)\n", (105, 144), False, 'from market import app\n'), ((294, 299), 'tools.cls', 'cls', ([], {}), '()\n', (297, 299), False, 'from tools import cls\n')] |
from setuptools import setup
setup(
name='abyss2pano',
version='0.1',
description='Command line tool to stitch recordings from the abyss rig',
url='',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['abyss2pano'],
zip_safe=False,
scripts=['bin/abyss2pano.py'],... | [
"setuptools.setup"
] | [((31, 357), 'setuptools.setup', 'setup', ([], {'name': '"""abyss2pano"""', 'version': '"""0.1"""', 'description': '"""Command line tool to stitch recordings from the abyss rig"""', 'url': '""""""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['abyss2pano']", 'zip_saf... |
from django.conf.urls import url
from . import views
app_name = 'crud_app'
urlpatterns = [
# /students/
url(r'^$', views.index, name='index'),
# /students/id<1>
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# /students/add
url(r'add/$', views.StudentCreate.as_view(), ... | [
"django.conf.urls.url"
] | [((114, 150), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (117, 150), False, 'from django.conf.urls import url\n'), ((695, 740), 'django.conf.urls.url', 'url', (['"""contact/$"""', 'views.index'], {'name': '"""contact"""'}), "('contact/$'... |
import ujson as json
import sys
import gzip
#import seolib as seo
from collections import defaultdict
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import urllib.request, re
import time
# a function to return a domain's rank
# alexaMap dict for caching
alexaMap = {}
def obtainAlexa(url):
... | [
"re.search",
"os.path.exists",
"os.listdir",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"gzip.open",
"ujson.dump",
"matplotlib.pyplot.clf",
"os.path.join",
"time.sleep",
"os.path.isdir",
"collections.defaultdict",
"os.mkdir",
"matplotlib.pyplot.tight_layout",
"ujson.loads",... | [((3506, 3515), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3513, 3515), True, 'import matplotlib.pyplot as plt\n'), ((3680, 3698), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (3690, 3698), True, 'import matplotlib.pyplot as plt\n'), ((3700, 3716), 'matplotlib.pyplot.title', 'pl... |
"""
Manages a hub for easier access in UCSC genome browser
"""
import os
from config import PUBLISH_URL_PATH_HUB, PUBLISH_DIR, TRACK_DESCRIPTION_TEMPALTE
__author__ = 'eranroz'
def add_track(track_name, url_name, short_label, long_label, description_html=None, genome="hg19"):
"""
Adds description for the new... | [
"os.path.exists",
"csv.DictReader",
"argparse.ArgumentParser",
"os.makedirs",
"data_provider.SeqLoader.load_result_dict",
"os.path.join",
"os.path.basename",
"tempfile.NamedTemporaryFile",
"data_provider.SeqLoader.build_bed",
"data_provider.SeqLoader.build_bedgraph"
] | [((693, 741), 'os.path.join', 'os.path.join', (['PUBLISH_DIR', 'genome', '"""trackDb.txt"""'], {}), "(PUBLISH_DIR, genome, 'trackDb.txt')\n", (705, 741), False, 'import os\n'), ((4606, 4642), 'os.path.join', 'os.path.join', (['PUBLISH_DIR', '"""hub.txt"""'], {}), "(PUBLISH_DIR, 'hub.txt')\n", (4618, 4642), False, 'impo... |
#!/usr/bin/env python3
from codekit.codetools import debug, error, info
from codekit import codetools, pygithub
import argparse
import datetime
import sys
import textwrap
def parse_args():
"""Parse command-line arguments"""
prog = 'github-get-ratelimit'
parser = argparse.ArgumentParser(
prog=pro... | [
"textwrap.dedent",
"codekit.pygithub.login_github",
"codekit.pygithub.debug_ratelimit",
"codekit.codetools.debug_lvl_from_env",
"codekit.codetools.error",
"sys.exit",
"codekit.codetools.setup_logging"
] | [((1282, 1317), 'codekit.codetools.setup_logging', 'codetools.setup_logging', (['args.debug'], {}), '(args.debug)\n', (1305, 1317), False, 'from codekit import codetools, pygithub\n'), ((1340, 1407), 'codekit.pygithub.login_github', 'pygithub.login_github', ([], {'token_path': 'args.token_path', 'token': 'args.token'})... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
python_version = sys.version_info
install_deps = []
with open('requirements.txt') as file_requirements:
install_deps = file_requirements.read().splitlines()
version = ''
with open('VERSION') as f:
version = f.readline().strip()
se... | [
"setuptools.find_packages"
] | [((541, 576), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['ez_setup']"}), "(exclude=['ez_setup'])\n", (554, 576), False, 'from setuptools import setup, find_packages\n')] |
__author__ = 'INVESTIGACION'
import datetime, time
def obtieneTime():
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')
return st
def minusSet(x,y):
x_y = list(set(x) - set(y))
return x_y | [
"datetime.datetime.fromtimestamp",
"time.time"
] | [((81, 92), 'time.time', 'time.time', ([], {}), '()\n', (90, 92), False, 'import datetime, time\n'), ((102, 137), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['ts'], {}), '(ts)\n', (133, 137), False, 'import datetime, time\n')] |
import webapp2
from app.handlers import base, bot, settings
app = webapp2.WSGIApplication([
webapp2.Route('/login', base.LoginHandler, name='login'),
webapp2.Route('/logout', base.LogoutHandler, name='logout'),
webapp2.Route('/403', base.Page403, name='403'),
('/webhook', bot.WebhookHandler),
('/'... | [
"webapp2.Route"
] | [((98, 154), 'webapp2.Route', 'webapp2.Route', (['"""/login"""', 'base.LoginHandler'], {'name': '"""login"""'}), "('/login', base.LoginHandler, name='login')\n", (111, 154), False, 'import webapp2\n'), ((160, 219), 'webapp2.Route', 'webapp2.Route', (['"""/logout"""', 'base.LogoutHandler'], {'name': '"""logout"""'}), "(... |
import traceback
from logging import getLogger
logger = getLogger("__main__").getChild(__name__)
def write_excel_from_df(df, file_path, sheet_name):
logger.debug("start")
try:
logger.debug("try")
df.to_excel(file_path, sheet_name=sheet_name, index=False)
logger.info("success")
exc... | [
"logging.getLogger",
"traceback.format_exc"
] | [((57, 78), 'logging.getLogger', 'getLogger', (['"""__main__"""'], {}), "('__main__')\n", (66, 78), False, 'from logging import getLogger\n'), ((425, 447), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (445, 447), False, 'import traceback\n')] |
from setuptools import setup
with open("requirements.txt") as f :
requirements = f.read().splitlines()
setup(
name="pubsub-pytoolbox",
version="0.0.1",
packages=["pubsub", "pubsub.op"],
install_requires=requirements
)
| [
"setuptools.setup"
] | [((111, 227), 'setuptools.setup', 'setup', ([], {'name': '"""pubsub-pytoolbox"""', 'version': '"""0.0.1"""', 'packages': "['pubsub', 'pubsub.op']", 'install_requires': 'requirements'}), "(name='pubsub-pytoolbox', version='0.0.1', packages=['pubsub',\n 'pubsub.op'], install_requires=requirements)\n", (116, 227), Fals... |
import unittest
import numpy as np
from tnpy.linalg import KrylovExpm
class TestLinAlg(unittest.TestCase):
def test_eigshmv(self):
# self.assertEqual(True, False)
pass
class TestKrylovExpm(unittest.TestCase):
def test_construct_krylov_space(self):
mat = np.random.random((50, 50))
... | [
"unittest.main",
"tnpy.linalg.KrylovExpm",
"numpy.random.random"
] | [((468, 483), 'unittest.main', 'unittest.main', ([], {}), '()\n', (481, 483), False, 'import unittest\n'), ((292, 318), 'numpy.random.random', 'np.random.random', (['(50, 50)'], {}), '((50, 50))\n', (308, 318), True, 'import numpy as np\n'), ((332, 352), 'numpy.random.random', 'np.random.random', (['(50)'], {}), '(50)\... |
"""
3D Point Cloud Visualization
Original Author: https://github.com/argoai/argoverse-api
Modified by <NAME>
Date October 2019
"""
import os
import numpy as np
import argparse
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
from mpl_toolkits.mplot3d import Axes3D
from mayavi import mlab
from t... | [
"os.path.exists",
"mayavi.mlab.points3d",
"mayavi.mlab.view",
"numpy.sqrt",
"os.makedirs",
"os.path.join",
"mayavi.mlab.figure",
"mayavi.mlab.close",
"numpy.array",
"mayavi.mlab.plot3d",
"numpy.concatenate",
"os.system",
"numpy.load"
] | [((1871, 2023), 'mayavi.mlab.points3d', 'mlab.points3d', (['points[:, 0]', 'points[:, 1]', 'points[:, 2]', 'per_pt_color_strengths'], {'mode': '"""point"""', 'colormap': 'colormap', 'color': 'fixed_color', 'figure': 'fig'}), "(points[:, 0], points[:, 1], points[:, 2],\n per_pt_color_strengths, mode='point', colormap... |
from __future__ import print_function, division
import sys
import os, os.path
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
period_rng = (50, 300)
rp_rng = (0.75, 20)
# Read synthetic catalog
koi_file = sys.argv[1]
kois = pd.read_hdf(koi_file, 'kois'... | [
"numpy.ones_like",
"matplotlib.use",
"scipy.optimize.minimize",
"os.path.splitext",
"numpy.diff",
"emcee.EnsembleSampler",
"numpy.exp",
"numpy.array",
"numpy.sum",
"numpy.isfinite",
"corner.corner",
"numpy.load",
"numpy.random.randn",
"pandas.read_hdf"
] | [((137, 158), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (151, 158), False, 'import matplotlib\n'), ((292, 321), 'pandas.read_hdf', 'pd.read_hdf', (['koi_file', '"""kois"""'], {}), "(koi_file, 'kois')\n", (303, 321), True, 'import pandas as pd\n'), ((446, 472), 'numpy.load', 'np.load', (['com... |
#######################################################################
# Tests for clone_cmd.py module
#######################################################################
import unittest
import tempfile
import shutil
import os
from auto_process_ngs.auto_processor import AutoProcess
from auto_process_ngs.mock impo... | [
"auto_process_ngs.auto_processor.AutoProcess",
"os.path.exists",
"auto_process_ngs.commands.clone_cmd.clone",
"os.rename",
"os.path.join",
"os.getcwd",
"os.chdir",
"auto_process_ngs.mock.UpdateAnalysisDir",
"os.path.isfile",
"os.path.isdir",
"tempfile.mkdtemp",
"os.mkdir",
"shutil.rmtree",
... | [((753, 800), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'suffix': '"""TestAutoProcessClone"""'}), "(suffix='TestAutoProcessClone')\n", (769, 800), False, 'import tempfile\n'), ((884, 895), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (893, 895), False, 'import os\n'), ((934, 953), 'os.chdir', 'os.chdir', (['self.dir... |
from re import S
from numpy.core.numeric import NaN
import streamlit as st
import pandas as pd
import numpy as np
st.title('world gdp')
@st.cache
def load_data(path):
data = pd.read_csv(path)
data.columns = data.columns.str.lower()
return data
data = load_data("data/gdp.csv")
if st.checkbox('show raw dat... | [
"streamlit.checkbox",
"pandas.read_csv",
"streamlit.line_chart",
"streamlit.write",
"streamlit.subheader",
"streamlit.sidebar.selectbox",
"pandas.DataFrame",
"streamlit.title"
] | [((115, 136), 'streamlit.title', 'st.title', (['"""world gdp"""'], {}), "('world gdp')\n", (123, 136), True, 'import streamlit as st\n'), ((295, 323), 'streamlit.checkbox', 'st.checkbox', (['"""show raw data"""'], {}), "('show raw data')\n", (306, 323), True, 'import streamlit as st\n'), ((348, 375), 'streamlit.checkbo... |
from scipy import interpolate
import random
import numpy as np
import matplotlib.pyplot as plt
import math
from types import SimpleNamespace
from gym_space_racer.geometry import intersect, intersection
class CircularMap:
"""Generate random map in shape of circle"""
PRECISION = 100
def __init__(self, n=10,... | [
"numpy.random.normal",
"scipy.interpolate.splprep",
"matplotlib.pyplot.plot",
"gym_space_racer.geometry.intersection",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"scipy.interpolate.splev",
"numpy.random.seed",
"numpy.random.randint",
"math.atan2",
"numpy.sin",
"numpy.hypot",
"numpy.co... | [((466, 491), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (480, 491), True, 'import numpy as np\n'), ((1617, 1660), 'matplotlib.pyplot.plot', 'plt.plot', (['self.start[0]', 'self.start[1]', '"""x"""'], {}), "(self.start[0], self.start[1], 'x')\n", (1625, 1660), True, 'import matplotlib.... |
import uuid
import readtime
from uuid import uuid4
from django.utils import timezone
from datetime import datetime
from django.shortcuts import reverse
from django.utils.text import slugify
from django.db import models
from django.contrib.auth import get_user_model
from django_countries.fields import CountryField
from ... | [
"django.contrib.auth.get_user_model",
"readtime.of_text",
"django.utils.text.slugify",
"ckeditor_uploader.fields.RichTextUploadingField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"taggit.managers.TaggableManager",
"django.db.models.ImageFiel... | [((608, 624), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (622, 624), False, 'from django.contrib.auth import get_user_model\n'), ((785, 824), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (805, 824), False, 'from djang... |
import os.path
import os
import sys
import math
import argparse
import time
import random
from collections import OrderedDict
import torch
import options.options as option
from utils import util
from data import create_dataloader, create_dataset
from models import create_model
from utils.logger import Logger, PrintLo... | [
"utils.util.psnr",
"utils.util.mkdir_and_rename",
"numpy.arange",
"utils.util.tensor2img",
"argparse.ArgumentParser",
"sampler.generate_code_samples",
"utils.util.save_img",
"random.randint",
"collections.OrderedDict",
"utils.util.mkdir",
"data.create_dataloader",
"utils.logger.Logger",
"tim... | [((521, 532), 'time.time', 'time.time', ([], {}), '()\n', (530, 532), False, 'import time\n'), ((2176, 2189), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2187, 2189), False, 'from collections import OrderedDict\n'), ((2660, 2685), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', ... |
import asyncio
from unittest.mock import Mock
import pytest
from pysandra.core import SBytes
from pysandra.dispatcher import Dispatcher
def get_mock_coro(return_value):
# @asyncio.coroutine
async def mock_coro(*args, **kwargs):
return return_value(*args, **kwargs)
return Mock(wraps=mock_coro)
... | [
"pysandra.dispatcher.Dispatcher",
"unittest.mock.Mock",
"pysandra.core.SBytes"
] | [((297, 318), 'unittest.mock.Mock', 'Mock', ([], {'wraps': 'mock_coro'}), '(wraps=mock_coro)\n', (301, 318), False, 'from unittest.mock import Mock\n'), ((359, 390), 'pysandra.dispatcher.Dispatcher', 'Dispatcher', (['"""blank"""', 'None', 'None'], {}), "('blank', None, None)\n", (369, 390), False, 'from pysandra.dispat... |
from PIL import Image, ImageDraw
img = Image.new("RGB", (100, 100), (88, 88, 88))
draw = ImageDraw.Draw(img)
if 0:
draw.line((0, 0) + img.size, fill="red")
draw.line((0, img.size[1], img.size[0], 0), fill="blue")
if 0:
draw.point((75, 50), fill="red")
draw.rectangle([20, 50, 30, 65], fill="green", outli... | [
"PIL.Image.new",
"PIL.ImageDraw.Draw"
] | [((40, 82), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(100, 100)', '(88, 88, 88)'], {}), "('RGB', (100, 100), (88, 88, 88))\n", (49, 82), False, 'from PIL import Image, ImageDraw\n'), ((91, 110), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (105, 110), False, 'from PIL import Image, ImageDraw\n... |
import asyncio
import aio_pika
from tweb.web import HttpServer
from tweb.handler import BaseHandler
from tweb.router import router
from tweb.utils.plugins import plugins
from tweb.pubsub import AmqpPublishSubscribe
url = 'amqp://guest:guest@127.0.0.1:5672/'
queue_name = 'test:channel'
class MySubscribe(AmqpPublishSub... | [
"tweb.utils.plugins.plugins.register",
"tweb.web.HttpServer",
"tweb.router.router",
"aio_pika.connect_robust",
"asyncio.get_event_loop",
"tweb.utils.plugins.plugins.loading"
] | [((606, 617), 'tweb.router.router', 'router', (['"""/"""'], {}), "('/')\n", (612, 617), False, 'from tweb.router import router\n'), ((917, 929), 'tweb.web.HttpServer', 'HttpServer', ([], {}), '()\n', (927, 929), False, 'from tweb.web import HttpServer\n'), ((934, 974), 'tweb.utils.plugins.plugins.register', 'plugins.re... |
import sys
import random
sizes = [1, 100, 10000, 100000]
# Lists
list_sizes = []
for size in sizes:
int_list = [i for i in range(size)]
list_sizes.append(sys.getsizeof(int_list))
# Sets
set_sizes = []
for size in sizes:
int_set = {i for i in range(size)}
set_sizes.append(sys.getsizeof(int_set))
tup_... | [
"sys.getsizeof"
] | [((164, 187), 'sys.getsizeof', 'sys.getsizeof', (['int_list'], {}), '(int_list)\n', (177, 187), False, 'import sys\n'), ((291, 313), 'sys.getsizeof', 'sys.getsizeof', (['int_set'], {}), '(int_set)\n', (304, 313), False, 'import sys\n'), ((410, 432), 'sys.getsizeof', 'sys.getsizeof', (['int_tup'], {}), '(int_tup)\n', (4... |
import numpy as np
a1 = np.ones((2, 3), int)
print(a1)
# [[1 1 1]
# [1 1 1]]
a2 = np.full((2, 3), 2)
print(a2)
# [[2 2 2]
# [2 2 2]]
print(np.block([a1, a2]))
# [[1 1 1 2 2 2]
# [1 1 1 2 2 2]]
print(np.block([[a1], [a2]]))
# [[1 1 1]
# [1 1 1]
# [2 2 2]
# [2 2 2]]
print(np.block([[a1, a2], [a2, a1]]))
# [[1 ... | [
"numpy.full",
"numpy.block",
"numpy.ones"
] | [((25, 45), 'numpy.ones', 'np.ones', (['(2, 3)', 'int'], {}), '((2, 3), int)\n', (32, 45), True, 'import numpy as np\n'), ((85, 103), 'numpy.full', 'np.full', (['(2, 3)', '(2)'], {}), '((2, 3), 2)\n', (92, 103), True, 'import numpy as np\n'), ((531, 544), 'numpy.full', 'np.full', (['(6)', '(3)'], {}), '(6, 3)\n', (538,... |
"""Template tags tests."""
# pylint: disable=redefined-outer-name
import pytest
from rough_trade_calendar.templatetags import rough_trade_calendar
@pytest.fixture
def context(rf):
return {"request": rf.get("http://testserver/some/page")}
@pytest.mark.django_db
def test_webcal_url(context, location):
"""T... | [
"rough_trade_calendar.templatetags.rough_trade_calendar.webcal_url"
] | [((360, 410), 'rough_trade_calendar.templatetags.rough_trade_calendar.webcal_url', 'rough_trade_calendar.webcal_url', (['context', 'location'], {}), '(context, location)\n', (391, 410), False, 'from rough_trade_calendar.templatetags import rough_trade_calendar\n')] |
from flask import Flask, render_template
import requests
from flask_sqlalchemy import SQLAlchemy
from os import getenv
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URI')
db = SQLAlchemy(app)
class Fighters(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Colu... | [
"flask.render_template",
"requests.post",
"os.getenv",
"flask.Flask",
"requests.get",
"flask_sqlalchemy.SQLAlchemy"
] | [((126, 141), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (131, 141), False, 'from flask import Flask, render_template\n'), ((182, 204), 'os.getenv', 'getenv', (['"""DATABASE_URI"""'], {}), "('DATABASE_URI')\n", (188, 204), False, 'from os import getenv\n'), ((210, 225), 'flask_sqlalchemy.SQLAlchemy', '... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
# Add renderSDK path to sys.path
renderSDK_path = r'D:\gitlab\renderSDK'
sys.path.append(renderSDK_path)
from renderSDK.Rayvision import Rayvision
# 1.Log in
rayvision = Rayvision(domain_name='task.foxrenderfarm.com', platform='2', access_id='xxx', access_key='... | [
"renderSDK.Rayvision.Rayvision",
"sys.path.append"
] | [((130, 161), 'sys.path.append', 'sys.path.append', (['renderSDK_path'], {}), '(renderSDK_path)\n', (145, 161), False, 'import sys\n'), ((229, 366), 'renderSDK.Rayvision.Rayvision', 'Rayvision', ([], {'domain_name': '"""task.foxrenderfarm.com"""', 'platform': '"""2"""', 'access_id': '"""xxx"""', 'access_key': '"""xxx""... |
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
from pprint import pformat
from typing import Any, Dict
import pytest
from models_library.projects_nodes import Node, PortLink
from models_library.projects_nodes_io import DatCoreFileLink, SimCoreFileLink
@pytest... | [
"models_library.projects_nodes_io.SimCoreFileLink",
"models_library.projects_nodes.Node.parse_obj",
"pprint.pformat",
"pytest.mark.parametrize",
"pytest.fixture"
] | [((314, 330), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (328, 330), False, 'import pytest\n'), ((1370, 1442), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""model_cls"""', '(SimCoreFileLink, DatCoreFileLink)'], {}), "('model_cls', (SimCoreFileLink, DatCoreFileLink))\n", (1393, 1442), False, 'im... |
import numpy as np
from ophyd import EpicsMotor, EpicsScaler, PVPositioner, EpicsSignal
from ophyd import SimDetector
from ophyd import ProsilicaDetector
from ophyd.userapi import *
import logging
from pyOlog.OlogHandler import OlogHandler
# Undulator
epu1_gap = PVPositioner('XF:23ID-ID{EPU:1-Ax:Gap}Pos-SP',
... | [
"ophyd.EpicsSignal",
"ophyd.EpicsMotor",
"pyOlog.OlogHandler.OlogHandler",
"ophyd.PVPositioner"
] | [((267, 496), 'ophyd.PVPositioner', 'PVPositioner', (['"""XF:23ID-ID{EPU:1-Ax:Gap}Pos-SP"""'], {'readback': '"""XF:23ID-ID{EPU:1-Ax:Gap}Pos-I"""', 'stop': '"""SR:C23-ID:G1A{EPU:1-Ax:Gap}-Mtr.STOP"""', 'stop_val': '(1)', 'done': '"""XF:23ID-ID{EPU:1-Ax:Gap}Pos-Sts"""', 'done_val': '(0)', 'name': '"""epu2_gap"""'}), "('X... |
from data_generation.models.story_models import Intent, Story, Utterance
from rasa.shared.nlu.state_machine.state_machine_models import (
IntentWithExamples,
)
from typing import Optional, List, Tuple
import gspread
import pandas as pd
import os
def _pull_sheet_data(worksheet) -> pd.DataFrame:
data = worksh... | [
"pandas.DataFrame",
"gspread.service_account",
"data_generation.models.story_models.Utterance",
"os.getenv"
] | [((1901, 1943), 'os.getenv', 'os.getenv', (['"""SERVICE_ACCOUNT_KEY_JSON_PATH"""'], {}), "('SERVICE_ACCOUNT_KEY_JSON_PATH')\n", (1910, 1943), False, 'import os\n'), ((379, 414), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'headers'}), '(data, columns=headers)\n', (391, 414), True, 'import pandas as pd\n'... |
import metrics.evaluation as e
import metrics.evaluation
def get_evaluation(y_test, y_pred):
flat_y_test = [i for subl in y_test for i in subl]
flat_y_pred = [i for subl in y_pred for i in subl]
H,I,D = e.compute_HID(flat_y_test, flat_y_pred)
Precision, Recall, FScore = e.compute_PRF(H,I,D)
evalu... | [
"metrics.evaluation.compute_HID",
"metrics.evaluation.compute_PRF"
] | [((217, 256), 'metrics.evaluation.compute_HID', 'e.compute_HID', (['flat_y_test', 'flat_y_pred'], {}), '(flat_y_test, flat_y_pred)\n', (230, 256), True, 'import metrics.evaluation as e\n'), ((289, 311), 'metrics.evaluation.compute_PRF', 'e.compute_PRF', (['H', 'I', 'D'], {}), '(H, I, D)\n', (302, 311), True, 'import me... |