code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'window_history.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow
class History(QMainWindow):
d... | [
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QDateEdit",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtCore.QRect",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QPlainTextEdit",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtCore.QMetaObject.connectSlotsByName"
... | [((466, 489), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', (['self'], {}), '(self)\n', (483, 489), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((584, 621), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', (['self.centralwidget'], {}), '(self.centralwidget)\n', (601, 621), False, 'from PyQt5 import QtCore,... |
from eth2spec.test.context import spec_state_test, with_all_phases
from eth2spec.test.helpers.epoch_processing import (
run_epoch_processing_with
)
def run_process_historical_roots_update(spec, state):
yield from run_epoch_processing_with(spec, state, 'process_historical_roots_update')
@with_all_phases
@spe... | [
"eth2spec.test.helpers.epoch_processing.run_epoch_processing_with"
] | [((223, 296), 'eth2spec.test.helpers.epoch_processing.run_epoch_processing_with', 'run_epoch_processing_with', (['spec', 'state', '"""process_historical_roots_update"""'], {}), "(spec, state, 'process_historical_roots_update')\n", (248, 296), False, 'from eth2spec.test.helpers.epoch_processing import run_epoch_processi... |
import pytest
from caia.items.items_job_config import ItemsJobConfig
from caia.items.steps.get_last_timestamp import GetLastTimestamp
def test_get_last_timestamp_default_timestamp():
config = {
'storage_dir': '/tmp',
'last_success_lookup': 'tests/storage/items/items_last_success.txt'
}
j... | [
"caia.items.items_job_config.ItemsJobConfig",
"caia.items.steps.get_last_timestamp.GetLastTimestamp",
"pytest.raises"
] | [((332, 362), 'caia.items.items_job_config.ItemsJobConfig', 'ItemsJobConfig', (['config', '"""test"""'], {}), "(config, 'test')\n", (346, 362), False, 'from caia.items.items_job_config import ItemsJobConfig\n'), ((389, 417), 'caia.items.steps.get_last_timestamp.GetLastTimestamp', 'GetLastTimestamp', (['job_config'], {}... |
from keras import backend as K
from keras import optimizers
from keras.layers import BatchNormalization as BN, Concatenate, Dense, Input, Lambda,Dropout
from keras.models import Model
from models.common import sse, bce, mmd, sampling, kl_regu
from keras.losses import mean_squared_error,binary_crossentropy
import numpy... | [
"keras.backend.stack",
"numpy.random.seed",
"keras.losses.binary_crossentropy",
"keras.layers.Dropout",
"keras.optimizers.Adam",
"keras.models.Model",
"tensorflow.set_random_seed",
"keras.layers.Concatenate",
"keras.layers.Dense",
"keras.backend.mean",
"keras.layers.Lambda",
"models.common.kl_... | [((531, 549), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (545, 549), True, 'import numpy as np\n'), ((558, 577), 'tensorflow.set_random_seed', 'set_random_seed', (['(42)'], {}), '(42)\n', (573, 577), False, 'from tensorflow import set_random_seed\n'), ((678, 717), 'keras.layers.Input', 'Input', ([... |
from pathlib import Path
import pytest
from code_scanner.enums import FileType
from code_scanner.file_info import FileInfo
@pytest.fixture
def file_info():
"""
Returns a test python file info
"""
return FileInfo(Path('/tmp/test.py'), FileType.SOURCE_CODE)
@pytest.fixture
def another_file_info():
... | [
"pytest.raises",
"pytest.mark.parametrize",
"pathlib.Path"
] | [((1003, 1164), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""updated_name,expected_full_name"""', "[('/tmp/new.py', 'SOURCE_CODE-/tmp/new.py'), ('/tmp/tests.py',\n 'SOURCE_CODE-/tmp/tests.py')]"], {}), "('updated_name,expected_full_name', [('/tmp/new.py',\n 'SOURCE_CODE-/tmp/new.py'), ('/tmp/tests.... |
# -*- coding: utf-8 -*-
import numpy as np
from DictLearner import DictLearner
import scipy.sparse.linalg
"""The inference code was adapted from <NAME>'s sparsenet implementation,
available on github."""
class FISTALearner(DictLearner):
def __init__(self, data, learnrate, nunits, lam = 0.4, niter... | [
"numpy.fmin",
"numpy.fmax",
"numpy.abs",
"numpy.zeros",
"numpy.sqrt"
] | [((940, 982), 'numpy.zeros', 'np.zeros', (['(self.Q.shape[0], data.shape[1])'], {}), '((self.Q.shape[0], data.shape[1]))\n', (948, 982), True, 'import numpy as np\n'), ((889, 906), 'numpy.fmax', 'np.fmax', (['(x - t)', '(0)'], {}), '(x - t, 0)\n', (896, 906), True, 'import numpy as np\n'), ((907, 924), 'numpy.fmin', 'n... |
from rest_framework import serializers
from drf_queryfields import QueryFieldsMixin
from django.db.models import Sum, F, DecimalField
import decimal
import database.models as models
# Customer
class CustomerSerializer(QueryFieldsMixin, serializers.ModelSerializer):
class Meta:
model = models.Customer
... | [
"decimal.Decimal",
"rest_framework.serializers.IntegerField",
"rest_framework.serializers.CharField",
"database.models.InvoiceProduct.objects.get",
"database.models.Invoice.objects.create",
"database.models.Product.objects.get",
"database.models.InvoiceProduct.objects.create",
"rest_framework.serializ... | [((446, 519), 'rest_framework.serializers.DecimalField', 'serializers.DecimalField', ([], {'max_digits': '(15)', 'decimal_places': '(3)', 'read_only': '(True)'}), '(max_digits=15, decimal_places=3, read_only=True)\n', (470, 519), False, 'from rest_framework import serializers\n'), ((698, 771), 'rest_framework.serialize... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import calendar
import datetime
import re
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.utils import timezone
from dateutil.relativedelta import relativedelta
from django.contrib.auth.decorators import ... | [
"djanban.apps.dev_times.models.DailySpentTime.objects.filter",
"django.utils.timezone.now",
"djanban.apps.base.auth.get_user_boards",
"dateutil.relativedelta.relativedelta",
"django.core.mail.EmailMultiAlternatives",
"django.shortcuts.render",
"django.template.loader.get_template",
"djanban.apps.base.... | [((1276, 1350), 'django.shortcuts.render', 'render', (['request', '"""daily_spent_times/list.html"""', "parameters['replacements']"], {}), "(request, 'daily_spent_times/list.html', parameters['replacements'])\n", (1282, 1350), False, 'from django.shortcuts import render\n'), ((2077, 2114), 'django.http.response.HttpRes... |
from nonebot import on_command
from nonebot.matcher import Matcher
from nonebot.adapters.onebot.v11 import GroupMessageEvent
from utils.utils import get_json
from utils.config_util import ConfigManager
status = on_command('status')
data = {
"server_url": "",
"uuid": "",
"remote_uuid": "",
"apikey": "... | [
"nonebot.on_command",
"utils.config_util.ConfigManager.register",
"utils.utils.get_json"
] | [((213, 233), 'nonebot.on_command', 'on_command', (['"""status"""'], {}), "('status')\n", (223, 233), False, 'from nonebot import on_command\n'), ((331, 372), 'utils.config_util.ConfigManager.register', 'ConfigManager.register', (['"""mc_status"""', 'data'], {}), "('mc_status', data)\n", (353, 372), False, 'from utils.... |
from datetime import timedelta
from LoggedSensor import LoggedSensor
class HumiditySensor(LoggedSensor):
def __init__(self, node):
super(HumiditySensor, self).__init__(type_id=2, max_measurements=500, holdoff_time=timedelta(minutes=1))
node.Humidity.subscribe_to_changes(self.on_property_changed)... | [
"datetime.timedelta"
] | [((229, 249), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(1)'}), '(minutes=1)\n', (238, 249), False, 'from datetime import timedelta\n')] |
import string
SWAGGER_UI_TEMPLATE = string.Template(
"""
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger_ui_static/swagger-ui.css" >
<link rel="icon" ... | [
"string.Template"
] | [((37, 1578), 'string.Template', 'string.Template', (['"""\n<!-- HTML for static distribution bundle build -->\n<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="UTF-8">\n <title>Swagger UI</title>\n <link rel="stylesheet" type="text/css" href="./swagger_ui_static/swagger-ui.css" >\n <link rel="i... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... | [
"edb.server.pgsql.dbops.Trigger",
"edb.server.pgsql.dbops.Function",
"edb.server.pgsql.dbops.Query",
"edb.server.pgsql.common.edgedb_name_to_pg_name",
"edb.server.pgsql.dbops.CompositeCommandGroup.__init__",
"edb.server.pgsql.common.quote_ident",
"edb.server.pgsql.dbops.CreateTrigger",
"edb.lang.commo... | [((1239, 1301), 'edb.lang.common.adapter.Adapter.__init__', 'adapter.Adapter.__init__', (['cls', 'name', 'bases', 'dct'], {'adapts': 'adapts'}), '(cls, name, bases, dct, adapts=adapts)\n', (1263, 1301), False, 'from edb.lang.common import adapter\n'), ((2419, 2454), 'edb.server.pgsql.common.edgedb_name_to_pg_name', 'co... |
#!/usr/bin/env python
import rospy
from math import cos, sin, atan, pi
import numpy as np
import yaml
import sys
from sensor_msgs.msg import LaserScan
from std_msgs.msg import Float64
import pdb
pub = rospy.Publisher('pid_error', Float64, queue_size=10)
# You can define constants in Python as uppercase global names ... | [
"rospy.Subscriber",
"numpy.asarray",
"rospy.Publisher",
"math.sin",
"std_msgs.msg.Float64",
"rospy.init_node",
"math.cos",
"rospy.spin"
] | [((203, 255), 'rospy.Publisher', 'rospy.Publisher', (['"""pid_error"""', 'Float64'], {'queue_size': '(10)'}), "('pid_error', Float64, queue_size=10)\n", (218, 255), False, 'import rospy\n'), ((712, 735), 'numpy.asarray', 'np.asarray', (['data.ranges'], {}), '(data.ranges)\n', (722, 735), True, 'import numpy as np\n'), ... |
"""
Utility functions go here.
SpiceBucks
"""
# ------------------------------------------------------------------
import sys
import numpy as np
from util.message import message
# ------------------------------------------------------------------
# -----------------------------------------------------------------... | [
"util.message.message.logError",
"util.message.message.logDebug",
"sys.exit"
] | [((944, 954), 'sys.exit', 'sys.exit', ([], {}), '()\n', (952, 954), False, 'import sys\n'), ((583, 633), 'util.message.message.logError', 'message.logError', (['"""Exit code must be an interger."""'], {}), "('Exit code must be an interger.')\n", (599, 633), False, 'from util.message import message\n'), ((676, 732), 'ut... |
import RPi.GPIO as GPIO
import time
from flask import Flask, render_template
import threading
app = Flask('dispener-server')
lock = threading.Lock()
last_treat = 0
TREAT_MIN_SECONDS = 2
GPIO.setmode(GPIO.BOARD)
control_pins = [7,11,13,15]
for pin in control_pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, 0... | [
"RPi.GPIO.setmode",
"RPi.GPIO.setup",
"flask.Flask",
"time.time",
"threading.Lock",
"time.sleep",
"flask.render_template",
"RPi.GPIO.output"
] | [((102, 126), 'flask.Flask', 'Flask', (['"""dispener-server"""'], {}), "('dispener-server')\n", (107, 126), False, 'from flask import Flask, render_template\n'), ((134, 150), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (148, 150), False, 'import threading\n'), ((189, 213), 'RPi.GPIO.setmode', 'GPIO.setmode', ... |
import os
from anasymod.generators.codegen import CodeGenerator
from anasymod.util import back2fwd, expand_searchpaths
from typing import Union
class ConfigFileObj(CodeGenerator):
def __init__(self, files, config_path, name):
super().__init__()
self.files = None
""" type(str) : m... | [
"anasymod.util.back2fwd",
"os.path.dirname",
"os.path.join"
] | [((6050, 6109), 'os.path.join', 'os.path.join', (['hdl_dir_root', 'self.fileset', 'self.name', '"""*.*v"""'], {}), "(hdl_dir_root, self.fileset, self.name, '*.*v')\n", (6062, 6109), False, 'import os\n'), ((1202, 1235), 'os.path.dirname', 'os.path.dirname', (['self.config_path'], {}), '(self.config_path)\n', (1217, 123... |
import requests
def extra_metadata_helper(project_url, headers):
"""
Build extra metadata dict to help with other integrations.
Parameters
----------
project_url: str
The url to the project info
headers: dict
Figshare Authorization header
Returns
-------
Extra... | [
"requests.get"
] | [((368, 410), 'requests.get', 'requests.get', (['project_url'], {'headers': 'headers'}), '(project_url, headers=headers)\n', (380, 410), False, 'import requests\n')] |
import os
import unittest
from copy import deepcopy
from uuid import uuid4
import pytest
from dotenv import load_dotenv
from culqi import __version__
from culqi.client import Culqi
from culqi.resources import Card
from .data import Data
class CardTest(unittest.TestCase):
# pylint: disable = too-many-public-met... | [
"unittest.main",
"copy.deepcopy",
"uuid.uuid4",
"pytest.mark.vcr",
"culqi.resources.Card",
"os.environ.get",
"dotenv.load_dotenv",
"culqi.client.Culqi"
] | [((1550, 1567), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (1565, 1567), False, 'import pytest\n'), ((1763, 1780), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (1778, 1780), False, 'import pytest\n'), ((2080, 2097), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (2095, 2097), False, 'im... |
import math
import torch
import torch.nn as nn
from models.modules import (gaussian_likelihood, gaussian_sample, View)
class VAE(nn.Module):
def __init__(self, image_shape, hidden_channels):
super().__init__()
self.encoder = nn.Sequential(*[
nn.Conv2d(3, 16, kernel_size=3, stride=1, pa... | [
"torch.nn.ReLU",
"torch.nn.ConvTranspose2d",
"torch.randn_like",
"torch.nn.Conv2d",
"torch.nn.BatchNorm1d",
"torch.cat",
"torch.exp",
"torch.nn.BatchNorm2d",
"torch.nn.Linear",
"models.modules.View",
"math.log",
"torch.nn.Flatten"
] | [((2049, 2068), 'torch.exp', 'torch.exp', (['z_logvar'], {}), '(z_logvar)\n', (2058, 2068), False, 'import torch\n'), ((2306, 2325), 'torch.exp', 'torch.exp', (['x_logvar'], {}), '(x_logvar)\n', (2315, 2325), False, 'import torch\n'), ((2687, 2724), 'torch.cat', 'torch.cat', (['[x[:16], x_mu[:16]]'], {'dim': '(0)'}), '... |
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
fig1=plt.figure()
ax1=fig1.add_subplot(1,1,1)
def animate(p):
plot_data=open('test1.txt','r').read()
line_data=plot_data.split('\n')
x1=[]
y1=[... | [
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.animation.FuncAnimation"
] | [((107, 139), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (120, 139), True, 'import matplotlib.pyplot as plt\n'), ((148, 160), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (158, 160), True, 'import matplotlib.pyplot as plt\n'), ((533, 585), 'm... |
# -*- mode: python; coding:utf-8; -*-
from __future__ import print_function
# A SCons tool to enable compilation of Erlang in SCons.
#
# Copyright © 2005 <NAME> "Pupeno" <NAME>
# Copyright © 2009, 2011, 2017 <NAME>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GN... | [
"subprocess.Popen",
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"os.path.splitext",
"os.access",
"SCons.Scanner.Scanner",
"SCons.Builder.Builder"
] | [((3896, 3992), 'SCons.Builder.Builder', 'Builder', ([], {'generator': 'erlangGenerator', 'src_suffix': '""".erl"""', 'emitter': 'addTarget', 'single_source': '(True)'}), "(generator=erlangGenerator, src_suffix='.erl', emitter=addTarget,\n single_source=True)\n", (3903, 3992), False, 'from SCons.Builder import Build... |
# -*- coding: utf-8 -*-
import scrapy
import json
import re
from locations.items import GeojsonPointItem
STATES = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',
'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ'... | [
"locations.items.GeojsonPointItem",
"re.findall",
"json.loads"
] | [((1207, 1225), 'json.loads', 'json.loads', (['stores'], {}), '(stores)\n', (1217, 1225), False, 'import json\n'), ((1312, 1384), 're.findall', 're.findall', (['"""(\\\\"LAT\\\\"), (\\\\")([+-]?([0-9]*[.])?[0-9]+)(\\\\")"""', 'loc_data'], {}), '(\'(\\\\"LAT\\\\"), (\\\\")([+-]?([0-9]*[.])?[0-9]+)(\\\\")\', loc_data)\n'... |
from url_shortener.form_filters import prepend_http, strip_value
def test_prepend_http():
assert prepend_http('example.com/') == 'http://example.com/'
assert prepend_http('http://example.com/') == 'http://example.com/'
assert prepend_http('https://example.com/') == 'https://example.com/'
assert prepen... | [
"url_shortener.form_filters.prepend_http",
"url_shortener.form_filters.strip_value"
] | [((103, 131), 'url_shortener.form_filters.prepend_http', 'prepend_http', (['"""example.com/"""'], {}), "('example.com/')\n", (115, 131), False, 'from url_shortener.form_filters import prepend_http, strip_value\n'), ((168, 203), 'url_shortener.form_filters.prepend_http', 'prepend_http', (['"""http://example.com/"""'], {... |
import time, os, sys
import logging
import json
import importlib
import threading
import pprint
import datetime
import gc
import re
import shutil
from configparser import ConfigParser
from pymongo import MongoClient
from bson.objectid import ObjectId
from subprocess import Popen
from threading import Lock, Thread
fro... | [
"pymongo.MongoClient",
"threading.Thread",
"importlib.import_module",
"bson.objectid.ObjectId",
"lib.saq.client.Alert",
"os.path.exists",
"re.match",
"datetime.datetime.now",
"time.sleep",
"threading.Lock",
"time.time",
"gc.collect",
"shutil.rmtree",
"configparser.ConfigParser",
"os.path... | [((413, 432), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (430, 432), False, 'import logging\n'), ((541, 555), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (553, 555), False, 'from configparser import ConfigParser\n'), ((792, 839), 'os.path.join', 'os.path.join', (['self.working', '"""... |
from inferelator import amusr_workflow
from inferelator import workflow
from inferelator.regression.base_regression import _RegressionWorkflowMixin
from inferelator.postprocessing.results_processor import ResultsProcessor
from inferelator.tests.artifacts.test_data import TestDataSingleCellLike, TEST_DATA, TEST_DATA_SPA... | [
"inferelator.amusr_workflow.create_task_data_class",
"inferelator.tests.artifacts.test_data.TEST_DATA_SPARSE.copy",
"inferelator.tests.artifacts.test_data.TEST_DATA.copy",
"numpy.array",
"inferelator.workflow._factory_build_inferelator"
] | [((1835, 1902), 'inferelator.amusr_workflow.create_task_data_class', 'amusr_workflow.create_task_data_class', ([], {'workflow_class': '"""single-cell"""'}), "(workflow_class='single-cell')\n", (1872, 1902), False, 'from inferelator import amusr_workflow\n'), ((867, 957), 'inferelator.workflow._factory_build_inferelator... |
"""blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | [
"post.feeds.LatestPostFeed",
"django.conf.urls.include",
"post.views.PostListByTag.as_view",
"post.views.PostListView.as_view",
"django.views.decorators.cache.cache_page",
"django.conf.urls.url",
"django.conf.urls.static.static"
] | [((2299, 2360), 'django.conf.urls.static.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n', (2305, 2360), False, 'from django.conf.urls.static import static\n'), ((1194, 1230), 'django.conf.urls.url', 'url', (['"""^fake-adm... |
import curses
import colorama
from colorama import Fore, Back, Style
colorama.init()
class menuInterface:
def __init__(self, menu):
self.info = menu
def print_menu(self,stdscr, selected_row_idx):
list = self.info
stdscr.clear()
h, w = stdscr.getmaxyx()
for idx, row in en... | [
"colorama.init",
"curses.color_pair",
"curses.curs_set",
"curses.init_pair"
] | [((69, 84), 'colorama.init', 'colorama.init', ([], {}), '()\n', (82, 84), False, 'import colorama\n'), ((1607, 1625), 'curses.curs_set', 'curses.curs_set', (['(0)'], {}), '(0)\n', (1622, 1625), False, 'import curses\n'), ((1659, 1718), 'curses.init_pair', 'curses.init_pair', (['(1)', 'curses.COLOR_BLACK', 'curses.COLOR... |
#
# MIT License
#
# Copyright (c) 2018 WillQ
#
# 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, publ... | [
"monkq.utils.timefunc.utc_datetime",
"pandas.tseries.frequencies.to_offset"
] | [((1969, 1997), 'pandas.tseries.frequencies.to_offset', 'to_offset', (['self.collect_freq'], {}), '(self.collect_freq)\n', (1978, 1997), False, 'from pandas.tseries.frequencies import DateOffset, to_offset\n'), ((2050, 2074), 'monkq.utils.timefunc.utc_datetime', 'utc_datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1... |
from solvers.rigidity_solver.models import *
import numpy as np
_scale = lambda arr: arr * 15
v = lambda x, y, z: np.array([x, y, z], dtype=np.double)
p = lambda x, y, z: (_scale(np.array([x, y, z], dtype=np.double)))
def lerp(p, q, weight):
return p + (q - p) * weight
def define(stage):
_p = {
"a": ... | [
"numpy.linalg.norm",
"numpy.cross",
"numpy.array",
"numpy.sqrt"
] | [((115, 151), 'numpy.array', 'np.array', (['[x, y, z]'], {'dtype': 'np.double'}), '([x, y, z], dtype=np.double)\n', (123, 151), True, 'import numpy as np\n'), ((180, 216), 'numpy.array', 'np.array', (['[x, y, z]'], {'dtype': 'np.double'}), '([x, y, z], dtype=np.double)\n', (188, 216), True, 'import numpy as np\n'), ((1... |
from urllib.parse import urlparse
def url_checker(url_site,
url_site_disallowed_path):
validator = False
for site_path in url_site_disallowed_path:
if site_path not in urlparse(url_site).path:
validator = True
continue
else:
validator =... | [
"urllib.parse.urlparse"
] | [((205, 223), 'urllib.parse.urlparse', 'urlparse', (['url_site'], {}), '(url_site)\n', (213, 223), False, 'from urllib.parse import urlparse\n')] |
import ctypes
import time
so7 = ctypes.CDLL("./so7.so")
t1 = ("ěščř ЩжΛλ"*10000).encode("utf-8")
t2 = ("<foobar>"*10000).encode("utf-8")
so7.concat.restype = ctypes.c_char_p
for i in range(100000):
t = so7.concat(t1, t2)
print(len(t))
time.sleep(0.001)
| [
"ctypes.CDLL",
"time.sleep"
] | [((33, 56), 'ctypes.CDLL', 'ctypes.CDLL', (['"""./so7.so"""'], {}), "('./so7.so')\n", (44, 56), False, 'import ctypes\n'), ((251, 268), 'time.sleep', 'time.sleep', (['(0.001)'], {}), '(0.001)\n', (261, 268), False, 'import time\n')] |
import discord
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from discord.ext import commands
from selenium import webdriver
# Selenium setup
options = webdriver.ChromeOptions()
options.add_argument("headless")
options.add_argument("log-level=3")
d... | [
"discord.Embed",
"time.sleep",
"discord.ext.commands.cooldown",
"selenium.webdriver.ChromeOptions",
"webdriver_manager.chrome.ChromeDriverManager",
"discord.ext.commands.Bot",
"discord.Client"
] | [((224, 249), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (247, 249), False, 'from selenium import webdriver\n'), ((452, 468), 'discord.Client', 'discord.Client', ([], {}), '()\n', (466, 468), False, 'import discord\n'), ((479, 511), 'discord.ext.commands.Bot', 'commands.Bot', ([], ... |
import re
# 태그 제거
def relace_tag(content):
cleaner = re.compile('<.*?>')
cleantext = re.sub(cleaner, '', content)
return cleantext | [
"re.sub",
"re.compile"
] | [((58, 77), 're.compile', 're.compile', (['"""<.*?>"""'], {}), "('<.*?>')\n", (68, 77), False, 'import re\n'), ((95, 123), 're.sub', 're.sub', (['cleaner', '""""""', 'content'], {}), "(cleaner, '', content)\n", (101, 123), False, 'import re\n')] |
import glob
import pickle
import gensim
import torch
from tqdm import tqdm
import nltk
nltk.download('wordnet')
# with open('F:/workspace/LdaSummarization/dictionary_large_2020_12_05.pkl', 'rb') as f:
# tm_dictionary = pickle.load(f)
with open('F:/workspace/LdaSummarization/lda_model_large_2020_12_08.pkl', 'rb... | [
"tqdm.tqdm",
"nltk.WordNetLemmatizer",
"torch.load",
"gensim.utils.simple_preprocess",
"pickle.load",
"glob.glob",
"nltk.download",
"nltk.SnowballStemmer"
] | [((90, 114), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (103, 114), False, 'import nltk\n'), ((386, 417), 'nltk.SnowballStemmer', 'nltk.SnowballStemmer', (['"""english"""'], {}), "('english')\n", (406, 417), False, 'import nltk\n'), ((888, 902), 'tqdm.tqdm', 'tqdm', (['pt_files'], {}), ... |
"""
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... | [
"os.environ.get",
"os.path.dirname"
] | [((365, 390), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (380, 390), False, 'import os\n'), ((1781, 1826), 'os.environ.get', 'os.environ.get', (['"""PG_NAME"""', '"""dts_test_project"""'], {}), "('PG_NAME', 'dts_test_project')\n", (1795, 1826), False, 'import os\n'), ((1844, 1869), 'os.en... |
# Copyright (c) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | [
"webkitpy.common.net.regressionwindow.RegressionWindow",
"webkitpy.common.net.buildbot.Build",
"webkitpy.tool.mocktool.MockBuilder"
] | [((1810, 1833), 'webkitpy.tool.mocktool.MockBuilder', 'MockBuilder', (['"""Builder1"""'], {}), "('Builder1')\n", (1821, 1833), False, 'from webkitpy.tool.mocktool import MockBuilder\n'), ((1849, 1872), 'webkitpy.tool.mocktool.MockBuilder', 'MockBuilder', (['"""Builder2"""'], {}), "('Builder2')\n", (1860, 1872), False, ... |
from random import shuffle
import os
from glob import glob
import shutil
import re
import tqdm
from multiprocessing import Pool
from normalise import normalise
months = {'jan.': 'January', 'feb.': 'February', 'mar.': 'March', 'apr.': 'April', 'may': 'May', 'jun.': 'June', 'jul.': 'July', 'aug.': 'August', 'sep.': 'S... | [
"tqdm.tqdm",
"re.split",
"os.makedirs",
"os.path.join",
"os.walk",
"os.popen",
"multiprocessing.Pool",
"shutil.copyfile",
"re.sub"
] | [((11438, 11494), 'tqdm.tqdm', 'tqdm.tqdm', (['files'], {'desc': "('Process for speaker: ' + speaker)"}), "(files, desc='Process for speaker: ' + speaker)\n", (11447, 11494), False, 'import tqdm\n'), ((12019, 12055), 'os.makedirs', 'os.makedirs', (['out_root'], {'exist_ok': '(True)'}), '(out_root, exist_ok=True)\n', (1... |
from cfiddle import *
from util import *
from fixtures import *
from cfiddle.source import FullyInstrumentedExecutable
from cfiddle.util import working_directory
import pytest
import tempfile
import os
def test_cfg(test_cpp):
assert isinstance(test_cpp, FullyInstrumentedExecutable)
with tempfile.Tempora... | [
"tempfile.TemporaryDirectory",
"os.path.join",
"os.path.exists"
] | [((304, 333), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (331, 333), False, 'import tempfile\n'), ((354, 381), 'os.path.join', 'os.path.join', (['d', '"""test.png"""'], {}), "(d, 'test.png')\n", (366, 381), False, 'import os\n'), ((396, 423), 'os.path.join', 'os.path.join', (['d', '... |
import os
import datetime
import json
import numpy as np
import itertools
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torchvision import transforms, datasets, models
import torch.nn.functional as F
from sklearn.metrics import roc_curve, auc
from matplotlib im... | [
"torchvision.transforms.ColorJitter",
"os.mkdir",
"torchvision.transforms.RandomHorizontalFlip",
"os.path.isdir",
"torchvision.transforms.RandomRotation",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"torchvision.transforms.RandomPerspective",
"cv2.imread",
"torchvision.... | [((577, 600), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (598, 600), False, 'from torchvision import transforms, datasets, models\n'), ((624, 646), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224)'], {}), '(224)\n', (641, 646), False, 'from torchvision import transform... |
from backend.services import services
from urllib.parse import urlparse
def parse_url(url):
'''
takes a validated url pointing to an item on
a supported streaming service and returns a
query to be used with other streaming services
Parameters:
url (str): the url to be parsed
Returns:
query (Qu... | [
"backend.services.services.keys",
"urllib.parse.urlparse"
] | [((412, 425), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (420, 425), False, 'from urllib.parse import urlparse\n'), ((471, 486), 'backend.services.services.keys', 'services.keys', ([], {}), '()\n', (484, 486), False, 'from backend.services import services\n')] |
# Copyright 2019 The Bazel 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 la... | [
"unittest.main"
] | [((3023, 3038), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3036, 3038), False, 'import unittest\n')] |
# example3.py
#
# Cached instances
import weakref
class Cached(type):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__cache = weakref.WeakValueDictionary()
def __call__(self, *args):
if args in self.__cache:
return self.__cache[args]
e... | [
"weakref.WeakValueDictionary"
] | [((178, 207), 'weakref.WeakValueDictionary', 'weakref.WeakValueDictionary', ([], {}), '()\n', (205, 207), False, 'import weakref\n')] |
import autoCorrection
import numpy as np
import unittest
class TestEndToEnd(unittest.TestCase):
def test_end_to_end(self):
counts = np.random.negative_binomial(n=20, p=0.2, size=(10, 8))
sf = np.ones((10, 8))
corrector = autoCorrection.correctors.AECorrector()
correction = correct... | [
"unittest.main",
"numpy.random.uniform",
"numpy.random.negative_binomial",
"numpy.ones",
"autoCorrection.correctors.AECorrector",
"numpy.round"
] | [((2475, 2490), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2488, 2490), False, 'import unittest\n'), ((147, 201), 'numpy.random.negative_binomial', 'np.random.negative_binomial', ([], {'n': '(20)', 'p': '(0.2)', 'size': '(10, 8)'}), '(n=20, p=0.2, size=(10, 8))\n', (174, 201), True, 'import numpy as np\n'), (... |
import os
import unittest
from unittest.mock import patch
import botocore.session
from botocore.stub import Stubber
from src.utils import secrets_manager_helper
session = botocore.session.get_session()
secretsmanager = session.create_client("secretsmanager", region_name=secrets_manager_helper.REGION)
class TestSecr... | [
"unittest.main",
"botocore.stub.Stubber",
"unittest.mock.patch.dict",
"src.utils.secrets_manager_helper.retrieve_secret"
] | [((513, 567), 'unittest.mock.patch.dict', 'patch.dict', (['os.environ', "{'variable': 'some_secret_id'}"], {}), "(os.environ, {'variable': 'some_secret_id'})\n", (523, 567), False, 'from unittest.mock import patch\n'), ((1155, 1170), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1168, 1170), False, 'import unitt... |
# Import all packages required
# Type annotation imports
from typing import Union
from typing import Tuple
# Other imports
import os
import glob
import h5py
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import numpy as np
import pandas as pd
from scipy import interpolate
#-... | [
"pandas.read_csv",
"numpy.mean",
"scipy.interpolate.interp1d",
"os.path.join",
"pandas.DataFrame",
"numpy.pad",
"os.path.abspath",
"numpy.multiply",
"datetime.timedelta",
"os.path.normpath",
"numpy.linspace",
"h5py.File",
"os.stat",
"os.path.basename",
"datetime.datetime.strptime",
"pa... | [((6149, 6261), 'pandas.DataFrame', 'pd.DataFrame', (["{'Start_timestamp': file_start_times, 'Filename': self.files,\n 'End_timestamp': file_end_times}"], {}), "({'Start_timestamp': file_start_times, 'Filename': self.files,\n 'End_timestamp': file_end_times})\n", (6161, 6261), True, 'import pandas as pd\n'), ((86... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2017 SML
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... | [
"discord.utils.get",
"box.Box",
"box.BoxList",
"os.makedirs",
"discord.Embed",
"cogs.utils.checks.mod_or_permissions",
"cogs.utils.dataIO.dataIO.is_valid_json",
"cogs.utils.dataIO.dataIO.load_json",
"datetime.datetime.utcnow",
"cogs.utils.checks.serverowner",
"__main__.send_cmd_help",
"discord... | [((1370, 1405), 'os.path.join', 'os.path.join', (['"""data"""', '"""votemanager"""'], {}), "('data', 'votemanager')\n", (1382, 1405), False, 'import os\n'), ((1413, 1448), 'os.path.join', 'os.path.join', (['PATH', '"""settings.json"""'], {}), "(PATH, 'settings.json')\n", (1425, 1448), False, 'import os\n'), ((3658, 370... |
#!/usr/bin/env python
# File: squares-enumerator.py
# Description: An SQL Synthesizer Using Query Reverse Engineering
# Author: <NAME>
# Created on: 22-02-2019 15:13:15
# Usage: python3 squaresEnumerator.py [flags|(-h for help)] specFile.in
# Python version: 3.6.4
from sys import argv
from string import *
import tyrel... | [
"tyrell.decider.Example",
"sqlparse.format",
"tyrell.interpreter.GeneralError",
"warnings.filterwarnings",
"sys.argv.append",
"itertools.permutations",
"tyrell.spec.parse",
"rpy2.robjects.r",
"os.walk",
"tyrell.logger.get_logger",
"re.sub"
] | [((785, 844), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RRuntimeWarning'}), "('ignore', category=RRuntimeWarning)\n", (808, 844), False, 'import warnings\n'), ((855, 875), 'tyrell.logger.get_logger', 'get_logger', (['"""tyrell"""'], {}), "('tyrell')\n", (865, 875), False, 'f... |
import PBRTv3Lex
import PBRTv3Yacc
from Directives import *
import sys
class PBRTv3Loader:
def importFile(self, filename):
data = open(filename).read()
sceneStructure = PBRTv3Yacc.parse(data)
return sceneStructure
def loadScene(self, sceneStructure):
scene = Scene()
... | [
"PBRTv3Yacc.parse"
] | [((191, 213), 'PBRTv3Yacc.parse', 'PBRTv3Yacc.parse', (['data'], {}), '(data)\n', (207, 213), False, 'import PBRTv3Yacc\n')] |
import re
import json
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
BROWSER_WAIT = 10
class APITest(LiveServerTestCase):
fixtures = ['demo.json']
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.impli... | [
"re.search",
"json.loads",
"selenium.webdriver.Firefox"
] | [((793, 834), 're.search', 're.search', (['"""<pre>(.*)</pre>"""', 'page_source'], {}), "('<pre>(.*)</pre>', page_source)\n", (802, 834), False, 'import re\n'), ((917, 938), 'json.loads', 'json.loads', (['page_json'], {}), '(page_json)\n', (927, 938), False, 'import json\n'), ((274, 293), 'selenium.webdriver.Firefox', ... |
from django.contrib.auth.models import User
from django.db import models
def generate_random_key():
return User.objects.make_random_password(length=16)
class TestingKey(models.Model):
key = models.CharField(blank=True, max_length=16)
is_used = models.BooleanField(default=False)
def save(self, *args... | [
"django.db.models.CharField",
"django.contrib.auth.models.User.objects.make_random_password",
"django.db.models.BooleanField"
] | [((113, 157), 'django.contrib.auth.models.User.objects.make_random_password', 'User.objects.make_random_password', ([], {'length': '(16)'}), '(length=16)\n', (146, 157), False, 'from django.contrib.auth.models import User\n'), ((202, 245), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_... |
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2016 by <NAME>
:mail: <EMAIL>.
:license: Apache 2.0, see LICENSE for more details.
"""
from flask_admin.contrib.sqla import ModelView
from ..models import FoFModel,get_all_fof
from logging import getLogger
from ..extensions import cache
from wtforms import PasswordField
lo... | [
"logging.getLogger",
"wtforms.PasswordField"
] | [((327, 338), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (336, 338), False, 'from logging import getLogger\n'), ((3824, 3845), 'wtforms.PasswordField', 'PasswordField', (['"""密码哈希"""'], {}), "('密码哈希')\n", (3837, 3845), False, 'from wtforms import PasswordField\n')] |
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
from collections import OrderedDict
script_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(script_dir)
sys.path.append(root_dir)
import emsdk # noqa
def version_to_list(version_string):
return [int(part) for pa... | [
"sys.path.append",
"os.path.abspath",
"emsdk.get_emscripten_releases_tot",
"os.path.dirname",
"subprocess.check_output",
"json.dumps",
"sys.exit",
"os.path.join",
"emsdk.load_releases_info",
"subprocess.check_call"
] | [((179, 206), 'os.path.dirname', 'os.path.dirname', (['script_dir'], {}), '(script_dir)\n', (194, 206), False, 'import os\n'), ((207, 232), 'sys.path.append', 'sys.path.append', (['root_dir'], {}), '(root_dir)\n', (222, 232), False, 'import sys\n'), ((141, 166), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}),... |
import datetime
import xml.etree.ElementTree as ET
from pathlib import Path
from banking_analytics.celery import app
from apps.banks.models import BalanceAccount, Bank, Region
from apps.cbrf.views import CBRF
@app.task
def get_accounts():
cb = CBRF()
response = cb.query(method='Form101IndicatorsEnumXML')
... | [
"xml.etree.ElementTree.parse",
"apps.cbrf.views.CBRF",
"apps.banks.models.BalanceAccount.objects.get_or_create",
"datetime.date.today",
"xml.etree.ElementTree.XMLParser",
"apps.banks.models.Region.objects.get_or_create",
"apps.banks.models.Bank.objects.get_or_create",
"pathlib.Path",
"datetime.datet... | [((252, 258), 'apps.cbrf.views.CBRF', 'CBRF', ([], {}), '()\n', (256, 258), False, 'from apps.cbrf.views import CBRF\n'), ((339, 388), 'pathlib.Path', 'Path', (['"""apps/banks/cbr_data/Form101IndicatorsEnum"""'], {}), "('apps/banks/cbr_data/Form101IndicatorsEnum')\n", (343, 388), False, 'from pathlib import Path\n'), (... |
""" Merges netCDF files covering the same month into one file.
Currently depends a lot on the input files having the right structure and
naming, i.e. a lot of assumptions are hardwired into this script. Maybe I'll
get to generalizing it by pulling information out of every file found, but for
now, this will have to do.... | [
"tempfile.TemporaryDirectory",
"os.path.join",
"xarray.open_dataset",
"dask.diagnostics.ProgressBar",
"xarray.merge",
"subprocess.call",
"pprint.pprint",
"tarfile.open",
"re.search"
] | [((2211, 2226), 'tempfile.TemporaryDirectory', 'TD', ([], {'dir': '"""./_T_"""'}), "(dir='./_T_')\n", (2213, 2226), True, 'from tempfile import TemporaryDirectory as TD\n'), ((3206, 3217), 'pprint.pprint', 'pp', (['netcdfs'], {}), '(netcdfs)\n', (3208, 3217), True, 'from pprint import pprint as pp\n'), ((3444, 3520), '... |
import unittest
from abc import ABC, abstractmethod
from Builder_models import MainData, Report, LeaveRecord
from Builders import Builder, BuilderFI,BuilderIT
from Directors import Director, DirectorCEO
class UtBuilder(unittest.TestCase):
def test_director(self):
myBuilder = BuilderFI()
director =... | [
"unittest.main",
"Builders.BuilderFI",
"Directors.DirectorCEO",
"Directors.Director",
"Builders.BuilderIT"
] | [((988, 1003), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1001, 1003), False, 'import unittest\n'), ((290, 301), 'Builders.BuilderFI', 'BuilderFI', ([], {}), '()\n', (299, 301), False, 'from Builders import Builder, BuilderFI, BuilderIT\n'), ((321, 348), 'Directors.Director', 'Director', ([], {'builder': 'myB... |
# -*- coding: utf-8 -*-
'''preggy 'like' assertions. For use with `expect()` (see `preggy.core`).
'''
# preggy assertions
# https://github.com/heynemann/preggy
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2013 <NAME> <EMAIL>
from __future__ import absolute_impor... | [
"difflib.SequenceMatcher",
"warnings.warn",
"preggy.utils.fix_string",
"re.compile"
] | [((1046, 1119), 're.compile', 're.compile', (['"""(\\\\033|\\\\x1b|\\\\x03)\\\\[([0-9]*[;])?[0-9]*m"""'], {'flags': 're.UNICODE'}), "('(\\\\033|\\\\x1b|\\\\x03)\\\\[([0-9]*[;])?[0-9]*m', flags=re.UNICODE)\n", (1056, 1119), False, 'import re\n'), ((1264, 1331), 're.compile', 're.compile', (['"""\\\\s+"""'], {'flags': '(... |
# Copyright 2017 Smartwaiver
#
# 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, ... | [
"unittest.main",
"smartwaiver.types.SmartwaiverGuardian",
"smartwaiver.types.SmartwaiverCustomField",
"factory.template",
"smartwaiver.types.SmartwaiverParticipant",
"sys.path.insert",
"factory.waiver",
"smartwaiver.types.SmartwaiverType",
"smartwaiver.types.SmartwaiverTemplate",
"factory.particip... | [((604, 629), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (619, 629), False, 'import sys\n'), ((10518, 10533), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10531, 10533), False, 'import unittest\n'), ((784, 806), 'factory.custom_field', 'factory.custom_field', ([], {}), '()... |
# Payment rest api serializers
from rest_framework import serializers
from rest_framework.serializers import (
SerializerMethodField,
IntegerField
)
from datetime import datetime
from ...payment.models import MpesaPayment
class MpesaPaymentUpdateSerializer(serializers.ModelSerializer):
status = Integer... | [
"rest_framework.serializers.IntegerField",
"rest_framework.serializers.SerializerMethodField"
] | [((313, 351), 'rest_framework.serializers.IntegerField', 'IntegerField', ([], {'max_value': '(1)', 'min_value': '(0)'}), '(max_value=1, min_value=0)\n', (325, 351), False, 'from rest_framework.serializers import SerializerMethodField, IntegerField\n'), ((726, 749), 'rest_framework.serializers.SerializerMethodField', 'S... |
#!/usr/bin/python
from __future__ import print_function
from icalendar import Calendar
import sys
def get_key_value(a):
val = ""
if a.has_key("UID"):
val = a["UID"]
elif a.has_key("DTSTART"):
val = a["DTSTART"]
elif a.has_key("DESCRIPTION"):
val = a["DESCRIPTION"]
elif a.h... | [
"sys.exit"
] | [((514, 525), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (522, 525), False, 'import sys\n')] |
# Copyright 2022 Google LLC
#
# 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, so... | [
"googlemaps.Client",
"os.environ.get",
"flask.Flask",
"flask.render_template"
] | [((678, 693), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (683, 693), False, 'from flask import Flask, render_template, request\n'), ((702, 732), 'googlemaps.Client', 'googlemaps.Client', ([], {'key': 'API_KEY'}), '(key=API_KEY)\n', (719, 732), False, 'import googlemaps\n'), ((1913, 1953), 'flask.render... |
from pathlib import Path
from subprocess import run
def add_file(file_name):
filepath = Path(file_name).resolve()
command = ["ipfs", "add", "-Q", filepath]
result = run(command, capture_output=True, text=True)
ipfs_hash = result.stdout.strip()
return {ipfs_hash: filepath}
def find_file_locati... | [
"subprocess.run",
"pathlib.Path"
] | [((180, 224), 'subprocess.run', 'run', (['command'], {'capture_output': '(True)', 'text': '(True)'}), '(command, capture_output=True, text=True)\n', (183, 224), False, 'from subprocess import run\n'), ((403, 447), 'subprocess.run', 'run', (['command'], {'capture_output': '(True)', 'text': '(True)'}), '(command, capture... |
import os
from wintermute import APP
def runserver():
port = int(os.environ.get('PORT', 5000))
APP.run(host='0.0.0.0', port=port, debug=True)
if __name__ == '__main__':
runserver()
| [
"os.environ.get",
"wintermute.APP.run"
] | [((105, 151), 'wintermute.APP.run', 'APP.run', ([], {'host': '"""0.0.0.0"""', 'port': 'port', 'debug': '(True)'}), "(host='0.0.0.0', port=port, debug=True)\n", (112, 151), False, 'from wintermute import APP\n'), ((71, 99), 'os.environ.get', 'os.environ.get', (['"""PORT"""', '(5000)'], {}), "('PORT', 5000)\n", (85, 99),... |
from typing import Dict, Any
from uuid import uuid4
from inventorycalculator.core.loaders.file_loader import FileLoader
from inventorycalculator.core.parsers.inventory_parser import InventoryParser
from inventorycalculator.core.repositories.dynamodb import DynamoDBTable
from inventorycalculator.core.storages.s3_storage... | [
"inventorycalculator.core.repositories.dynamodb.DynamoDBTable",
"uuid.uuid4",
"inventorycalculator.core.parsers.inventory_parser.InventoryParser",
"OneTicketLogging.elasticsearch_logger",
"inventorycalculator.core.storages.s3_storage.S3Storage",
"inventorycalculator.core.workers.aws_lambda.AwsLambda",
"... | [((673, 703), 'OneTicketLogging.elasticsearch_logger', 'elasticsearch_logger', (['__name__'], {}), '(__name__)\n', (693, 703), False, 'from OneTicketLogging import elasticsearch_logger\n'), ((718, 730), 'inventorycalculator.core.loaders.file_loader.FileLoader', 'FileLoader', ([], {}), '()\n', (728, 730), False, 'from i... |
from dataclasses import dataclass
@dataclass(frozen=True)
class Conf():
api_title: str
api_description: str
facilities_csv_fp: str
releases_csv_fp: str
waste_transfers_csv_fp: str
api_version: str
conf = Conf(
api_title='FIN-PRTR',
api_description=(
'The European Pollutant Re... | [
"dataclasses.dataclass"
] | [((37, 59), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (46, 59), False, 'from dataclasses import dataclass\n')] |
import unittest
import mock
import secretcrypt
from secretcrypt import StrictSecret, Secret
class TestSecret(unittest.TestCase):
@mock.patch('importlib.import_module')
def test_decrypt(self, mock_import_module):
mock_crypter_module = mock.MagicMock()
mock_crypter_module.__name__ = 'secretcry... | [
"secretcrypt.StrictSecret",
"mock.MagicMock",
"secretcrypt.Secret",
"mock.patch"
] | [((138, 175), 'mock.patch', 'mock.patch', (['"""importlib.import_module"""'], {}), "('importlib.import_module')\n", (148, 175), False, 'import mock\n'), ((1234, 1271), 'mock.patch', 'mock.patch', (['"""importlib.import_module"""'], {}), "('importlib.import_module')\n", (1244, 1271), False, 'import mock\n'), ((254, 270)... |
from .conftest import GoProCameraTest
from goprocam import GoProCamera
from socket import timeout
class GetMediaTest(GoProCameraTest):
def test_get_media_FS(self):
with self.monkeypatch.context() as m:
m.setattr(GoProCamera.GoPro, 'infoCamera', lambda s, x: 'FS')
m.setattr(GoProCam... | [
"socket.timeout"
] | [((1937, 1946), 'socket.timeout', 'timeout', ([], {}), '()\n', (1944, 1946), False, 'from socket import timeout\n')] |
from collections import deque
import itertools
def moving_average(iterable, n=3):
# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
# http://en.wikipedia.org/wiki/Moving_average
it = iter(iterable) # create an iterable object from input argument
d = deque(itertools.islice(it, n-1)) #... | [
"itertools.islice"
] | [((291, 318), 'itertools.islice', 'itertools.islice', (['it', '(n - 1)'], {}), '(it, n - 1)\n', (307, 318), False, 'import itertools\n')] |
# Copyright The PyTorch Lightning team.
#
# 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 i... | [
"flash.core.classification.FiftyOneLabels",
"flash.core.data.utils.download_data",
"flash.core.classification.Labels",
"torch.cuda.device_count",
"flash.image.ImageClassifier.load_from_checkpoint",
"flash.core.integrations.fiftyone.visualize",
"itertools.chain.from_iterable",
"flash.image.ImageClassif... | [((890, 966), 'flash.core.data.utils.download_data', 'download_data', (['"""https://pl-flash-data.s3.amazonaws.com/hymenoptera_data.zip"""'], {}), "('https://pl-flash-data.s3.amazonaws.com/hymenoptera_data.zip')\n", (903, 966), False, 'from flash.core.data.utils import download_data\n'), ((995, 1223), 'flash.image.Imag... |
# coding: utf-8
"""
Scubawhere API Documentation
This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
... | [
"six.iteritems"
] | [((4022, 4049), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (4031, 4049), False, 'from six import iteritems\n'), ((8411, 8438), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (8420, 8438), False, 'from six import iteritems\n'), ((12214, 12241), 's... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='tinydb-git',
version='0.2.dev1',
description='A git-based storage backend for tinydb.',
long_desc... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((474, 506), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (487, 506), False, 'from setuptools import setup, find_packages\n'), ((150, 175), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (165, 175), False, 'import os\n')] |
import dns
import subprocess
import dns.resolver
import traceback
import urllib3
urllib3.disable_warnings()
__domains = ['kh.ssl.ak.tiles.virtualearth.net', 'khstorelive.azureedge.net']
__default_ip = {
'kh.ssl.ak.tiles.virtualearth.net': '172.16.31.10',
'khstorelive.azureedge.net': '192.168.127.12... | [
"subprocess.run",
"dns.resolver.Resolver",
"traceback.print_exc",
"urllib3.disable_warnings"
] | [((88, 114), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (112, 114), False, 'import urllib3\n'), ((477, 583), 'subprocess.run', 'subprocess.run', (["['certutil', '-addstore', '-f', 'root', '.\\\\certs\\\\cert.crt']"], {'shell': '(True)', 'check': '(True)'}), "(['certutil', '-addstore', '-f... |
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize
import json
with open('../tokamaks.json') as f:
tokamaks = json.load(f)
tokamaks_names = []
radii = []
fig, ax = plt.subplots()
for tokamak in tokamaks:
if tokamak["configuration"] in ["tokamak", "stellarator"... | [
"json.load",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.tight_layout"
] | [((219, 233), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (231, 233), True, 'import matplotlib.pyplot as plt\n'), ((2428, 2443), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2436, 2443), True, 'import matplotlib.pyplot as plt\n'), ((2561, 2579), 'matplotlib.pyplot.tight_l... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import csv
import datetime
import io
import json
import pkgutil
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
import requests
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
f... | [
"pkgutil.get_data",
"io.StringIO",
"airbyte_cdk.sources.streams.http.requests_native_auth.Oauth2Authenticator",
"airbyte_cdk.sources.utils.transform.TypeTransformer",
"csv.DictReader",
"datetime.datetime.strptime"
] | [((4705, 4764), 'airbyte_cdk.sources.utils.transform.TypeTransformer', 'TypeTransformer', (['TransformConfig.DefaultSchemaNormalization'], {}), '(TransformConfig.DefaultSchemaNormalization)\n', (4720, 4764), False, 'from airbyte_cdk.sources.utils.transform import TransformConfig, TypeTransformer\n'), ((5148, 5174), 'io... |
# -*- coding: utf-8 -*-
import json
import re
import mock
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from geotrek.authent.tests import AuthentFixturesTest
from geotrek.common.tests import CommonTest
from geotrek.common.utils import LTE
from geotrek.authent.fa... | [
"django.core.urlresolvers.reverse",
"geotrek.core.models.Path.get_add_url",
"geotrek.core.factories.TrailFactory",
"geotrek.core.models.Trail.get_add_url",
"django.utils.translation.ugettext_lazy",
"geotrek.authent.factories.StructureFactory.create",
"json.loads",
"geotrek.core.factories.PathFactory",... | [((5928, 5993), 'mock.patch', 'mock.patch', (['"""mapentity.models.MapEntityMixin.get_attributes_html"""'], {}), "('mapentity.models.MapEntityMixin.get_attributes_html')\n", (5938, 5993), False, 'import mock\n'), ((719, 760), 'geotrek.authent.factories.PathManagerFactory', 'PathManagerFactory', ([], {'password': '"""<P... |
import json
import coreapi
import coreschema
from django.db.utils import IntegrityError
from django.shortcuts import get_object_or_404
from django.utils.datastructures import MultiValueDictKeyError
from numpydoc import docscrape
from rest_framework import status, schemas
from rest_framework.generics import ListAPIView... | [
"AnyTimeGridSearchCV.grids.models.DataSet.objects.get",
"json.loads",
"AnyTimeGridSearchCV.grids.models.GridSearch.objects.all",
"AnyTimeGridSearchCV.grids.anytime_search._convert_clf_param",
"AnyTimeGridSearchCV.grids.anytime_search.ESTIMATORS_DICT.keys",
"numpydoc.docscrape.ClassDoc",
"AnyTimeGridSear... | [((2201, 2225), 'AnyTimeGridSearchCV.grids.models.GridSearch.objects.all', 'GridSearch.objects.all', ([], {}), '()\n', (2223, 2225), False, 'from AnyTimeGridSearchCV.grids.models import GridSearch, CVResult, DataSet, CVResultScore\n'), ((2546, 2570), 'AnyTimeGridSearchCV.grids.models.GridSearch.objects.all', 'GridSearc... |
# Copyright (c) 2021. Universidad de Pinar del Rio
# This file is part of SCEIBA (sceiba.cu).
# SCEIBA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
from typing import Dict
from flask_babelex import lazy_gettext as _
from flas... | [
"iroko.vocabularies.models.Term",
"iroko.vocabularies.models.Vocabulary.query.all",
"invenio_db.db.session.add",
"invenio_db.db.session.delete",
"iroko.vocabularies.models.Vocabulary",
"invenio_db.db.session.query",
"iroko.vocabularies.marshmallow.term_node_schema.dump_term_node",
"iroko.vocabularies.... | [((17524, 17556), 'iroko.vocabularies.permissions.is_current_user_taxonomy_admin', 'is_current_user_taxonomy_admin', ([], {}), '()\n', (17554, 17556), False, 'from iroko.vocabularies.permissions import ObjectVocabularyEditor, is_current_user_taxonomy_admin\n'), ((18409, 18441), 'iroko.vocabularies.permissions.is_curren... |
import itertools
import ucd
ABC_LINES = '''
0040;COMMERCIAL AT;Po;0;ON;;;;;N;;;;;
0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061;
0042;LATIN CAPITAL LETTER B;Lu;0;L;;;;;N;;;;0062;
0043;LATIN CAPITAL LETTER C;Lu;0;L;;;;;N;;;;0063;
'''.strip()
def test_parse_line():
line_A = '0041;LATIN CAPITAL LETTER A;Lu;0;L;... | [
"ucd.index",
"ucd.parser",
"ucd.parse_line"
] | [((370, 392), 'ucd.parse_line', 'ucd.parse_line', (['line_A'], {}), '(line_A)\n', (384, 392), False, 'import ucd\n'), ((1502, 1522), 'ucd.parse_line', 'ucd.parse_line', (['line'], {}), '(line)\n', (1516, 1522), False, 'import ucd\n'), ((1533, 1552), 'ucd.index', 'ucd.index', (['[record]'], {}), '([record])\n', (1542, 1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import re
import codecs
from path import Path
wordlist = []
def main():
parser = argparse.ArgumentParser(description='rename dir based on files inside')
parser.add_argument('dirname', help='path of ... | [
"codecs.open",
"argparse.ArgumentParser",
"os.stat",
"path.Path",
"re.sub",
"re.compile"
] | [((199, 270), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""rename dir based on files inside"""'}), "(description='rename dir based on files inside')\n", (222, 270), False, 'import argparse\n'), ((381, 399), 'path.Path', 'Path', (['args.dirname'], {}), '(args.dirname)\n', (385, 399), Fa... |
from collections import namedtuple
from itertools import islice
from ..errors import Error as DriverError
from .errors import InterfaceError, OperationalError, ProgrammingError
Column = namedtuple(
'Column',
'name type_code display_size internal_size precision scale null_ok'
)
class Cursor(object):
cl... | [
"collections.namedtuple",
"itertools.islice"
] | [((189, 282), 'collections.namedtuple', 'namedtuple', (['"""Column"""', '"""name type_code display_size internal_size precision scale null_ok"""'], {}), "('Column',\n 'name type_code display_size internal_size precision scale null_ok')\n", (199, 282), False, 'from collections import namedtuple\n'), ((4985, 5009), 'i... |
"""CMS Plugins for the ``event_rsvp`` app."""
from django.utils.timezone import now
from django.utils.translation import ugettext as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Event
class CMSEventPlugin(CMSPluginBase):
name = _('Upcoming Events')
... | [
"django.utils.timezone.now",
"cms.plugin_pool.plugin_pool.register_plugin",
"django.utils.translation.ugettext"
] | [((654, 697), 'cms.plugin_pool.plugin_pool.register_plugin', 'plugin_pool.register_plugin', (['CMSEventPlugin'], {}), '(CMSEventPlugin)\n', (681, 697), False, 'from cms.plugin_pool import plugin_pool\n'), ((295, 315), 'django.utils.translation.ugettext', '_', (['"""Upcoming Events"""'], {}), "('Upcoming Events')\n", (2... |
import os
import sys
import json
import logging
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
import models
import worlds
class Executor(object):
STOP = 0
def __init__(self, config):
self.config = config
self.device = ... | [
"numpy.stack",
"torch.distributions.Categorical",
"torch.load",
"torch.nn.CrossEntropyLoss",
"numpy.zeros",
"models.load",
"torch.save",
"logging.info",
"worlds.load",
"numpy.arange",
"torch.no_grad",
"os.path.join",
"torch.tensor",
"torch.from_numpy"
] | [((391, 410), 'worlds.load', 'worlds.load', (['config'], {}), '(config)\n', (402, 410), False, 'import worlds\n'), ((1095, 1131), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'ignore_index': '(-1)'}), '(ignore_index=-1)\n', (1114, 1131), True, 'import torch.nn as nn\n'), ((2302, 2350), 'numpy.zeros', 'np.z... |
import torch
from elegantrl.agent import AgentPPO
from elegantrl.run import Arguments
from finrl.neo_finrl.data_processor import DataProcessor
from ray.rllib.agents.ppo import PPOTrainer, ppo
from stable_baselines3 import PPO
def trade(
start_date,
end_date,
ticker_list,
data_source,
time_interval... | [
"stable_baselines3.PPO.load",
"elegantrl.run.Arguments",
"ray.rllib.agents.ppo.PPOTrainer",
"ray.rllib.agents.ppo.ppo.DEFAULT_CONFIG.copy",
"elegantrl.agent.AgentPPO",
"finrl.neo_finrl.data_processor.DataProcessor"
] | [((486, 522), 'finrl.neo_finrl.data_processor.DataProcessor', 'DataProcessor', (['data_source'], {}), '(data_source, **kwargs)\n', (499, 522), False, 'from finrl.neo_finrl.data_processor import DataProcessor\n'), ((1329, 1357), 'elegantrl.run.Arguments', 'Arguments', ([], {'if_on_policy': '(True)'}), '(if_on_policy=Tru... |
from django.utils import timezone
from django.utils.translation import ugettext as _
from drf_spectacular.utils import (
OpenApiResponse,
extend_schema,
extend_schema_view,
)
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.generics import ... | [
"hacktheback.forms.models.Form.objects.filter",
"drf_spectacular.utils.OpenApiResponse",
"drf_spectacular.utils.extend_schema",
"rest_framework.response.Response",
"rest_framework.decorators.action",
"rest_framework.generics.get_object_or_404",
"hacktheback.rest.forms.openapi.id_or_type_parameter",
"h... | [((1740, 1784), 'drf_spectacular.utils.extend_schema', 'extend_schema', ([], {'tags': "['Hacker APIs', 'Forms']"}), "(tags=['Hacker APIs', 'Forms'])\n", (1753, 1784), False, 'from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_view\n'), ((3200, 3243), 'drf_spectacular.utils.extend_schema', '... |
import matplotlib.pyplot as plt
# import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI as sg
import matplotlib
import serial as ser
from serial import SerialException
from time import sleep
import glob
import os
# from pathlib import Path
from threading import... | [
"PySimpleGUI.Button",
"threading.Thread",
"serial.Serial",
"PySimpleGUI.Input",
"PySimpleGUI.Multiline",
"PySimpleGUI.Text",
"PySimpleGUI.Window",
"PySimpleGUI.popup_get_file",
"configparser.ConfigParser",
"PySimpleGUI.read_all_windows"
] | [((1436, 1450), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1448, 1450), False, 'from configparser import ConfigParser\n'), ((2560, 2615), 'PySimpleGUI.Window', 'sg.Window', (['"""Push Device Control"""', 'layout'], {'finalize': '(True)'}), "('Push Device Control', layout, finalize=True)\n", (2569, ... |
import requests
from bs4 import BeautifulSoup
res = requests.get('https://www.imdb.com/chart/top/')
html = res.text
soup = BeautifulSoup(html, 'html.parser')
tbody = soup.find('tbody')
trs = tbody.findAll('tr')
for tr in trs:
td = tr.find('td', {'class': 'titleColumn'})
print(td.a)
# movieId = td.a['href... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((52, 99), 'requests.get', 'requests.get', (['"""https://www.imdb.com/chart/top/"""'], {}), "('https://www.imdb.com/chart/top/')\n", (64, 99), False, 'import requests\n'), ((124, 158), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (137, 158), False, 'from bs4 imp... |
# -*- coding: utf-8 -*-
import json
import onmt
import onmt.io
import torch
import torch.cuda
from torch.autograd import Variable
from rouge import Rouge
class Reward():
def __init__(self, reward):
self.reward = reward
print("Reward : {}".format(reward))
if reward == "rouge":
... | [
"rouge.Rouge",
"torch.stack",
"torch.LongTensor",
"onmt.modules.Entailment_scorer",
"torch.Tensor",
"torch.rand",
"torch.sum"
] | [((335, 374), 'rouge.Rouge', 'Rouge', ([], {'metrics': "['rouge-l']", 'stats': "['f']"}), "(metrics=['rouge-l'], stats=['f'])\n", (340, 374), False, 'from rouge import Rouge\n'), ((625, 677), 'onmt.modules.Entailment_scorer', 'onmt.modules.Entailment_scorer', (['entail_model_path', '(0)'], {}), '(entail_model_path, 0)\... |
from fairseq.models import (
register_model,
register_model_architecture,
FairseqModel,
)
from pytorch_translate import vocab_reduction
from pytorch_translate.rnn import (
torch_find,
LSTMSequenceEncoder,
RNNEncoder,
RNNDecoder,
)
from .word_predictor import WordPredictor
class FairseqWord... | [
"pytorch_translate.vocab_reduction.set_arg_defaults",
"pytorch_translate.vocab_reduction.add_args",
"fairseq.models.register_model",
"pytorch_translate.rnn.RNNDecoder",
"fairseq.models.register_model_architecture"
] | [((1006, 1030), 'fairseq.models.register_model', 'register_model', (['"""rnn_wp"""'], {}), "('rnn_wp')\n", (1020, 1030), False, 'from fairseq.models import register_model, register_model_architecture, FairseqModel\n'), ((7616, 7663), 'fairseq.models.register_model_architecture', 'register_model_architecture', (['"""rnn... |
import readline
readline.parse_and_bind("tab: menu-complete")
import getch
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook()
class Completer:
def __init__(self, words):
... | [
"readline.parse_and_bind",
"readline.set_completer",
"readline.set_startup_hook",
"getch.getche",
"readline.insert_text"
] | [((16, 61), 'readline.parse_and_bind', 'readline.parse_and_bind', (['"""tab: menu-complete"""'], {}), "('tab: menu-complete')\n", (39, 61), False, 'import readline\n'), ((2841, 2886), 'readline.parse_and_bind', 'readline.parse_and_bind', (['"""tab: menu-complete"""'], {}), "('tab: menu-complete')\n", (2864, 2886), Fals... |
#
# Project SketchCNN
#
# Author: <NAME> (<EMAIL>),
# Copyright (c) 2018. All Rights Reserved.
#
# ==============================================================================
"""Convert LMDB to TFRecords
"""
import lmdb
import tensorflow as tf
import os
tfrecord_fn = r'path_to_tfrecord\train_db.tfrecords'
data... | [
"tensorflow.train.BytesList",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.train.Features",
"lmdb.open",
"os.path.join"
] | [((487, 527), 'tensorflow.python_io.TFRecordWriter', 'tf.python_io.TFRecordWriter', (['tfrecord_fn'], {}), '(tfrecord_fn)\n', (514, 527), True, 'import tensorflow as tf\n'), ((617, 649), 'os.path.join', 'os.path.join', (['data_dir', '"""lmdb_0"""'], {}), "(data_dir, 'lmdb_0')\n", (629, 649), False, 'import os\n'), ((65... |
import aiohttp
from urllib.parse import urljoin
from extensions.archive.archive_result import ArchiveResult
class ArchiveHandler:
archive_org_user_agent = "Durkabot (https://github.com/Durkastan/durkabot)"
domain = "http://web.archive.org"
save_url = urljoin(domain, 'save/')
def __init__(self, loop)... | [
"aiohttp.ClientSession",
"urllib.parse.urljoin",
"extensions.archive.archive_result.ArchiveResult"
] | [((266, 290), 'urllib.parse.urljoin', 'urljoin', (['domain', '"""save/"""'], {}), "(domain, 'save/')\n", (273, 290), False, 'from urllib.parse import urljoin\n'), ((345, 377), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {'loop': 'loop'}), '(loop=loop)\n', (366, 377), False, 'import aiohttp\n'), ((1149, 1180)... |
import copy
from django_countries import countries
from faker import Faker
import random
import string
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from TWLight.resources.factories import PartnerFactory, StreamFactory, VideoFactory, SuggestionFactory
fr... | [
"TWLight.resources.models.Language.objects.all",
"random.randint",
"faker.Faker",
"random.sample",
"django.contrib.auth.models.User.objects.filter",
"TWLight.resources.models.Stream.objects.all",
"random.choice",
"TWLight.resources.models.Partner.even_not_available.all",
"TWLight.resources.models.Ac... | [((837, 844), 'faker.Faker', 'Faker', ([], {}), '()\n', (842, 844), False, 'from faker import Faker\n'), ((869, 917), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'groups__name': '"""coordinators"""'}), "(groups__name='coordinators')\n", (888, 917), False, 'from django.contrib.auth.mod... |
from pytest import raises
import npk
filename = "testres/sample.npk"
sample = "testres/sample.txt"
key = (98521, 16322, 7163, 992)
class TestNpk(object):
def test_open_package(self):
pack = npk.package(filename, key)
pack.close()
def test_create_package(self):
pack = npk.package()
... | [
"npk.package",
"pytest.raises"
] | [((206, 232), 'npk.package', 'npk.package', (['filename', 'key'], {}), '(filename, key)\n', (217, 232), False, 'import npk\n'), ((305, 318), 'npk.package', 'npk.package', ([], {}), '()\n', (316, 318), False, 'import npk\n'), ((580, 606), 'npk.package', 'npk.package', (['filename', 'key'], {}), '(filename, key)\n', (591... |
#!/usr/bin/env python3
# wykys 2019
from numpy import ndarray
from awgn import awgn
WAV_PATH = '../wav/'
def wav(path: str, snr_db: float = None) -> list:
from scipy.io import wavfile
fs, s = wavfile.read(WAV_PATH + path)
if not (snr_db is None):
s = awgn(s, snr_db)
s = s / s.max()
retu... | [
"awgn.awgn",
"scipy.io.wavfile.read"
] | [((203, 232), 'scipy.io.wavfile.read', 'wavfile.read', (['(WAV_PATH + path)'], {}), '(WAV_PATH + path)\n', (215, 232), False, 'from scipy.io import wavfile\n'), ((275, 290), 'awgn.awgn', 'awgn', (['s', 'snr_db'], {}), '(s, snr_db)\n', (279, 290), False, 'from awgn import awgn\n')] |
#%%
from frontmatter import Frontmatter
import markdown
fp = 'testtemplate.md'
# %%
head_body = Frontmatter.read_file(fp)
type(head_body['body'])
# %%
bodyhtml = markdown.markdown(head_body['body'], extensions=['toc', 'tables','fenced_code'])
# bodyhtml = markdown.markdown(head_body['body'], extensions=['toc', 'tab... | [
"os.path.basename",
"os.walk",
"frontmatter.Frontmatter.read_file",
"markdown.markdown",
"os.path.splitext",
"markdown.Markdown",
"os.path.join",
"bs4.BeautifulSoup"
] | [((99, 124), 'frontmatter.Frontmatter.read_file', 'Frontmatter.read_file', (['fp'], {}), '(fp)\n', (120, 124), False, 'from frontmatter import Frontmatter\n'), ((166, 251), 'markdown.markdown', 'markdown.markdown', (["head_body['body']"], {'extensions': "['toc', 'tables', 'fenced_code']"}), "(head_body['body'], extensi... |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password, check_password
import datetime
import time
import random
from decorator import *
from app_cart.views import *
from .models import *
def getOrderByUser(user_id=None, mode="all"):
if user_... | [
"datetime.datetime.now",
"random.randint",
"time.time"
] | [((2532, 2558), 'random.randint', 'random.randint', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (2546, 2558), False, 'import random\n'), ((4817, 4840), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4838, 4840), False, 'import datetime\n'), ((2768, 2791), 'datetime.datetime.now', 'datetime.datet... |
from django.db import models
from reviewsapp.celebrities.models import Celebrity
from reviewsapp.core.behaviors import Filmable, Timestampable
class Network(models.Model):
name = models.CharField(max_length=100)
class TvShow(Filmable, Timestampable, models.Model):
premiere_date = models.DateField()
cas... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.DateField",
"django.db.models.ManytoMany"
] | [((186, 218), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (202, 218), False, 'from django.db import models\n'), ((294, 312), 'django.db.models.DateField', 'models.DateField', ([], {}), '()\n', (310, 312), False, 'from django.db import models\n'), ((329, 407), '... |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your op... | [
"PmvApp.msmsCmds.ComputeMSMS",
"PmvApp.msmsCmds.DisplayMSMS",
"PmvApp.Pmv.MolApp",
"PmvApp.msmsCmds.UndisplayMSMS"
] | [((1421, 1429), 'PmvApp.Pmv.MolApp', 'MolApp', ([], {}), '()\n', (1427, 1429), False, 'from PmvApp.Pmv import MolApp\n'), ((1598, 1611), 'PmvApp.msmsCmds.ComputeMSMS', 'ComputeMSMS', ([], {}), '()\n', (1609, 1611), False, 'from PmvApp.msmsCmds import ComputeMSMS, DisplayMSMS, UndisplayMSMS\n'), ((1760, 1773), 'PmvApp.m... |
from typing import Protocol, Union
import dataclasses
import numpy as np
class Motion(Protocol):
"""Protocol of a 1D motion."""
"""Shift of motion along time axis."""
offset: float
def at(self, t: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""Returns the position at time(s)."""
... | [
"numpy.vander",
"numpy.logical_and",
"numpy.isscalar",
"numpy.asarray",
"numpy.zeros",
"numpy.empty_like",
"dataclasses.field",
"numpy.atleast_1d",
"numpy.linalg.solve"
] | [((802, 831), 'dataclasses.field', 'dataclasses.field', ([], {'init': '(False)'}), '(init=False)\n', (819, 831), False, 'import dataclasses\n'), ((2260, 2276), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (2268, 2276), True, 'import numpy as np\n'), ((2285, 2296), 'numpy.zeros', 'np.zeros', (['(4)'], {}),... |
import subprocess
import argparse
from pathlib import Path
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def parse_TMscore(result):
lines = result.split('\n')
for line in lines:
line_split = line.split()
if len(line_split) == 0:
continue... | [
"pandas.DataFrame",
"argparse.ArgumentParser",
"pandas.read_csv",
"pandas.merge",
"subprocess.check_output",
"pathlib.Path",
"matplotlib.use"
] | [((97, 118), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (111, 118), False, 'import matplotlib\n'), ((718, 746), 'subprocess.check_output', 'subprocess.check_output', (['cmd'], {}), '(cmd)\n', (741, 746), False, 'import subprocess\n'), ((1390, 1499), 'pandas.DataFrame', 'pd.DataFrame', (["{'TM... |
import cv2
def img2sketch(photo, k_size):
#Read Image
img=cv2.imread(photo)
# Convert to Grey Image
grey_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Invert Image
invert_img=cv2.bitwise_not(grey_img)
#invert_img=255-grey_img
# Blur image
blur_img=cv2.GaussianBlur... | [
"cv2.GaussianBlur",
"cv2.bitwise_not",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"cv2.divide",
"cv2.imshow"
] | [((71, 88), 'cv2.imread', 'cv2.imread', (['photo'], {}), '(photo)\n', (81, 88), False, 'import cv2\n'), ((138, 175), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (150, 175), False, 'import cv2\n'), ((214, 239), 'cv2.bitwise_not', 'cv2.bitwise_not', (['grey_img'], {... |