code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import numpy as np
class simulated_parameter:
def __init__(self, parameter_name, parameter_mean, parameter_stddev, start_year, end_year):
self._parameter_name = parameter_name
self._parameter_mean = parameter_mean
self._parameter_stddev = parameter_stddev
self._start_year = start_... | [
"numpy.random.normal"
] | [((410, 495), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self._parameter_mean', 'scale': 'self._parameter_stddev', 'size': '(1)'}), '(loc=self._parameter_mean, scale=self._parameter_stddev, size=1\n )\n', (426, 495), True, 'import numpy as np\n')] |
import numpy as np
import keras.backend as K
from keras.layers import Layer
class LinearLayer(Layer):
""" linear regression score by using ids of user/item """
def __init__(self, num_user, num_item, **kwargs):
super(LinearLayer, self).__init__(**kwargs)
self.b_u = K.variable(np.zeros((num_user... | [
"keras.backend.reshape",
"numpy.zeros",
"keras.backend.gather"
] | [((887, 917), 'keras.backend.reshape', 'K.reshape', (['regression', '(-1, 1)'], {}), '(regression, (-1, 1))\n', (896, 917), True, 'import keras.backend as K\n'), ((302, 325), 'numpy.zeros', 'np.zeros', (['(num_user, 1)'], {}), '((num_user, 1))\n', (310, 325), True, 'import numpy as np\n'), ((390, 413), 'numpy.zeros', '... |
# Copyright 2020 Amazon Technologies, Inc. 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 appli... | [
"numpy.uint32",
"numpy.abs",
"numpy.floor",
"numpy.random.randint",
"unittest.main",
"gluoncv.model_zoo.get_model",
"numpy.finfo",
"numpy.max",
"mxnet.gpu",
"copy.deepcopy",
"mxnet.autograd.record",
"numpy.ceil",
"mxnet.gluon.loss.SoftmaxCrossEntropyLoss",
"mxnet.init.Xavier",
"utils.ber... | [((1062, 1080), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1065, 1080), False, 'from numba import jit\n'), ((1114, 1126), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (1123, 1126), True, 'import numpy as np\n'), ((1272, 1284), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (12... |
class Solution:
r"""
1.10 删除序列相同元素并保持顺序
>>> l = [1, 1, 2, 3, 3, 1, 2, 4]
>>> for i in Solution.solve(l):
... print(i)
1
2
3
4
"""
@staticmethod
def solve(items):
seen = set()
for i in items:
if i not in seen:
yield i
... | [
"doctest.testmod"
] | [((394, 411), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (409, 411), False, 'import doctest\n')] |
import logging
logger = logging.getLogger('app')
| [
"logging.getLogger"
] | [((25, 49), 'logging.getLogger', 'logging.getLogger', (['"""app"""'], {}), "('app')\n", (42, 49), False, 'import logging\n')] |
from mobao import app
from flask import render_template, request, g, redirect, url_for, session
from mobao.models import product, user
@app.route('/')
@app.route('/list')
def list_product():
return render_template('list.html', products=product.get_product_all())
@app.route('/login', methods=['GET', 'POST'])
def... | [
"mobao.models.product.get_product_all",
"flask.session.pop",
"mobao.app.route",
"mobao.models.user.authenticate_user",
"flask.url_for",
"flask.render_template"
] | [((138, 152), 'mobao.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (147, 152), False, 'from mobao import app\n'), ((154, 172), 'mobao.app.route', 'app.route', (['"""/list"""'], {}), "('/list')\n", (163, 172), False, 'from mobao import app\n'), ((272, 316), 'mobao.app.route', 'app.route', (['"""/login"""'], {'m... |
from google.cloud import storage
from google.oauth2 import service_account
from src import GCP_PROJECT, GCP_STORAGE_JSON, GCP_STORAGE_BUCKET_NAME
credentials = service_account.Credentials.from_service_account_file(GCP_STORAGE_JSON)
storage_client = storage.Client(project=GCP_PROJECT, credentials=credentials)
bucket ... | [
"google.oauth2.service_account.Credentials.from_service_account_file",
"google.cloud.storage.Client"
] | [((163, 234), 'google.oauth2.service_account.Credentials.from_service_account_file', 'service_account.Credentials.from_service_account_file', (['GCP_STORAGE_JSON'], {}), '(GCP_STORAGE_JSON)\n', (216, 234), False, 'from google.oauth2 import service_account\n'), ((252, 312), 'google.cloud.storage.Client', 'storage.Client... |
import sys
# import objgraph
a = ['a', 'b', 'c']
print(sys.getrefcount(a)) # print 2
b = a
print(b is a) # print True
print(sys.getrefcount(b)) # print 3
c = a
del c
print(sys.getrefcount(a)) # print 3
del a
print(sys.getrefcount(b)) # print 2
def foo(b):
# objgraph.show_backrefs([b], filename='... | [
"sys.getrefcount"
] | [((56, 74), 'sys.getrefcount', 'sys.getrefcount', (['a'], {}), '(a)\n', (71, 74), False, 'import sys\n'), ((140, 158), 'sys.getrefcount', 'sys.getrefcount', (['b'], {}), '(b)\n', (155, 158), False, 'import sys\n'), ((189, 207), 'sys.getrefcount', 'sys.getrefcount', (['a'], {}), '(a)\n', (204, 207), False, 'import sys\n... |
# /usr/lib64/env python3.6
# -*- coding: utf-8 -*-
import bs4
import requests
URL = 'https://picjumbo.com/?s='
def run():
busqueda = input('Write a category of image, like night, people, sports, etc: ')
url = '{}{}'.format(URL, busqueda)
web = requests.get(url)
soup = bs4.BeautifulSoup(web.content, 'h... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((258, 275), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (270, 275), False, 'import requests\n'), ((287, 332), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['web.content', '"""html.parser"""'], {}), "(web.content, 'html.parser')\n", (304, 332), False, 'import bs4\n')] |
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import sklearn
from sklearn import datasets
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from skle... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pandas.merge",
"sklearn.cluster.KMeans",
"sklearn.datasets.load_breast_cancer",
"matplotlib.pyplot.figure",
"sklearn.dec... | [((1256, 1271), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (1268, 1271), True, 'import pandas as pd\n'), ((1429, 1459), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (1432, 1459), False, 'from sklearn.decomposition import PCA\n'), ((1586, 161... |
# Originally auto-generated on 2021-02-15-12:14:48 -0500 EST
# By '--verbose --verbose x7.shell'
from unittest import TestCase
from x7.lib.annotations import tests
from x7.testing.support import Capture
with Capture() as ignored:
from x7 import shell
@tests(shell)
class TestModShell(TestCase):
"""Tests for s... | [
"x7.lib.annotations.tests",
"x7.testing.support.Capture"
] | [((259, 271), 'x7.lib.annotations.tests', 'tests', (['shell'], {}), '(shell)\n', (264, 271), False, 'from x7.lib.annotations import tests\n'), ((209, 218), 'x7.testing.support.Capture', 'Capture', ([], {}), '()\n', (216, 218), False, 'from x7.testing.support import Capture\n')] |
from django.contrib.auth.models import User
from rest_framework import serializers
from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer
from api.models import CategoryEntry, LinkEntry
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
... | [
"rest_framework.serializers.HyperlinkedRelatedField",
"taggit_serializer.serializers.TagListSerializerField"
] | [((440, 531), 'rest_framework.serializers.HyperlinkedRelatedField', 'serializers.HyperlinkedRelatedField', ([], {'many': '(True)', 'view_name': '"""link-detail"""', 'read_only': '(True)'}), "(many=True, view_name='link-detail',\n read_only=True)\n", (475, 531), False, 'from rest_framework import serializers\n'), ((7... |
from tools.wpt import revlist
def test_calculate_cutoff_date():
assert revlist.calculate_cutoff_date(3601, 3600, 0) == 3600
assert revlist.calculate_cutoff_date(3600, 3600, 0) == 3600
assert revlist.calculate_cutoff_date(3599, 3600, 0) == 0
assert revlist.calculate_cutoff_date(3600, 3600, 1) == 1
... | [
"tools.wpt.revlist.calculate_cutoff_date",
"tools.wpt.revlist.parse_epoch"
] | [((77, 121), 'tools.wpt.revlist.calculate_cutoff_date', 'revlist.calculate_cutoff_date', (['(3601)', '(3600)', '(0)'], {}), '(3601, 3600, 0)\n', (106, 121), False, 'from tools.wpt import revlist\n'), ((141, 185), 'tools.wpt.revlist.calculate_cutoff_date', 'revlist.calculate_cutoff_date', (['(3600)', '(3600)', '(0)'], {... |
from django.conf.urls import include, url
from django.contrib import admin
from content.view.createContent import *
from content.view.getContent import *
from content.view.readerGetContent import *
from content.view.readerWriteAContent import *
from content.view.readerGetChapterContent import *
urlpatterns = [
... | [
"django.conf.urls.url"
] | [((352, 392), 'django.conf.urls.url', 'url', (['"""^createAContent/$"""', 'createAContent'], {}), "('^createAContent/$', createAContent)\n", (355, 392), False, 'from django.conf.urls import include, url\n'), ((398, 438), 'django.conf.urls.url', 'url', (['"""^chapterContent/$"""', 'chapterContent'], {}), "('^chapterCont... |
import numpy as np
import pytz
from pandas._libs.tslibs import (
Resolution,
get_resolution,
)
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
def test_get_resolution_nano():
# don't return the fallback RESO_DAY
arr = np.array([1], dtype=np.int64)
res = get_resolution(arr)
assert res =... | [
"pandas._libs.tslibs.get_resolution",
"numpy.array"
] | [((244, 273), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (252, 273), True, 'import numpy as np\n'), ((284, 303), 'pandas._libs.tslibs.get_resolution', 'get_resolution', (['arr'], {}), '(arr)\n', (298, 303), False, 'from pandas._libs.tslibs import Resolution, get_resolution\n... |
import re
from datetime import datetime
from typing import List
import discord
from PIL import ImageColor
from d4dj_utils.master.card_master import CardMaster
from d4dj_utils.master.event_specific_bonus_master import EventSpecificBonusMaster
from d4dj_utils.master.skill_master import SkillMaster
from fluent.runtime.ty... | [
"re.fullmatch",
"miyu_bot.commands.master_filter.master_filter.data_attribute",
"datetime.datetime",
"PIL.ImageColor.getcolor",
"miyu_bot.commands.common.emoji.rarity_emoji_ids.values",
"datetime.datetime.now"
] | [((924, 983), 'miyu_bot.commands.master_filter.master_filter.data_attribute', 'data_attribute', (['"""name"""'], {'aliases': "['title']", 'is_sortable': '(True)'}), "('name', aliases=['title'], is_sortable=True)\n", (938, 983), False, 'from miyu_bot.commands.master_filter.master_filter import MasterFilter, data_attribu... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 22:17:48 2019
@author: Vivek
"""
'''
No. Company Revenue
(billion US dollars)
Headquarters
1 Glencore 209.2 Switzerland
2 BHP Billiton 69.4 Australia
3 Rio Tinto 45.1 United Kingdom
4 China Shenhua Energy 40 China
5 Vale 33.2 Brazil
'''
impo... | [
"matplotlib.pyplot.show",
"pandas.read_csv",
"pandas_datareader.data.DataReader",
"matplotlib.pyplot.subplot2grid",
"datetime.datetime",
"datetime.datetime.now"
] | [((471, 494), 'datetime.datetime', 'dt.datetime', (['(2018)', '(1)', '(1)'], {}), '(2018, 1, 1)\n', (482, 494), True, 'import datetime as dt\n'), ((502, 519), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (517, 519), True, 'import datetime as dt\n'), ((685, 733), 'pandas.read_csv', 'pd.read_csv', (['f[0... |
import re
from docx import Document
class DocxRedactor:
def __init__(self, doc_obj_path, regexes, replace_char):
self.doc_obj_path = doc_obj_path
self.regexes = regexes
self.replace_char = replace_char
def __redact_helper__(self, doc_obj):
"""
Helper function for the ... | [
"docx.Document",
"re.compile"
] | [((2432, 2459), 'docx.Document', 'Document', (['self.doc_obj_path'], {}), '(self.doc_obj_path)\n', (2440, 2459), False, 'from docx import Document\n'), ((499, 514), 're.compile', 're.compile', (['reg'], {}), '(reg)\n', (509, 514), False, 'import re\n')] |
"""
This file gives a bunch of functions for creating pandas dataframes from histories
"""
import pandas as pd
def rules2triples(ops_fsa):
"""
Makes strings and triples of rules in FSA
Arguments
ops_fsa : the operations FSA, no probs
Returns
list of ("lhs->e rhs", (lhs,rhs,e)) pairs
"... | [
"pandas.DataFrame"
] | [((1131, 1148), 'pandas.DataFrame', 'pd.DataFrame', (['tab'], {}), '(tab)\n', (1143, 1148), True, 'import pandas as pd\n'), ((2165, 2182), 'pandas.DataFrame', 'pd.DataFrame', (['tab'], {}), '(tab)\n', (2177, 2182), True, 'import pandas as pd\n'), ((7322, 7339), 'pandas.DataFrame', 'pd.DataFrame', (['tab'], {}), '(tab)\... |
import re
text = 'This is some text -- with punctuation.\nA second line'
pattern = r'.+'
no_newlines = re.compile(pattern)
'''Dotall is a flag related to multiline.Dot character matches
everything in the input text except newline character.'''
#matches anything except a newline character.
dotall = re.compile(patter... | [
"re.compile"
] | [((104, 123), 're.compile', 're.compile', (['pattern'], {}), '(pattern)\n', (114, 123), False, 'import re\n'), ((303, 333), 're.compile', 're.compile', (['pattern', 're.DOTALL'], {}), '(pattern, re.DOTALL)\n', (313, 333), False, 'import re\n')] |
#
# firebaseData.py
# TDX Desktop
# Created by <NAME> on 06/04/2021
#
import sys
import json
import io
import os
import csv
import pyrebase
import dataclasses
@dataclasses.dataclass
class FirebaseData:
def __post_init__(self, apiKey=None, authDomain=None, databaseURL=None, storageBucket=None, messagingSenderId=N... | [
"pyrebase.initialize_app"
] | [((1214, 1250), 'pyrebase.initialize_app', 'pyrebase.initialize_app', (['self.config'], {}), '(self.config)\n', (1237, 1250), False, 'import pyrebase\n')] |
import os
path = "F:\download\大咖读书会"
f = os.listdir(path)
for i in f:
oldname = path + '\\' + i
print(oldname)
newname = path + '\\' + i.split('.')[0]
print(newname)
os.rename(oldname, newname)
print("Done")
| [
"os.rename",
"os.listdir"
] | [((43, 59), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (53, 59), False, 'import os\n'), ((189, 216), 'os.rename', 'os.rename', (['oldname', 'newname'], {}), '(oldname, newname)\n', (198, 216), False, 'import os\n')] |
import os
import shutil
from random import randint
from typing import Any
from typing import Dict
from typing import List
from retrying import retry
from apysc._jslib import jslib_util
from tests import testing_helper
@retry(stop_max_attempt_number=15, wait_fixed=randint(10, 3000))
def test_get_jslib_... | [
"random.randint",
"os.path.dirname",
"apysc._jslib.jslib_util.get_jslib_file_names",
"os.path.isfile",
"tests.testing_helper.assert_raises",
"shutil.rmtree",
"apysc._jslib.jslib_util.export_jslib_to_specified_dir",
"apysc._jslib.jslib_util.get_jslib_abs_dir_path",
"os.listdir"
] | [((377, 410), 'apysc._jslib.jslib_util.get_jslib_file_names', 'jslib_util.get_jslib_file_names', ([], {}), '()\n', (408, 410), False, 'from apysc._jslib import jslib_util\n'), ((649, 684), 'apysc._jslib.jslib_util.get_jslib_abs_dir_path', 'jslib_util.get_jslib_abs_dir_path', ([], {}), '()\n', (682, 684), False, 'from a... |
'''
Created on Nov 1, 2021
@author: mballance
'''
import cocotb
import pybfms
from uart_bfms.uart_bfm import UartBfm
from rv_bfms.rv_data_in_bfm import ReadyValidDataInBFM
from rv_bfms.rv_data_out_bfm import ReadyValidDataOutBFM
class TestBack2BackUart(object):
async def init(self):
await pybfms.init... | [
"cocotb.test",
"pybfms.init",
"pybfms.find_bfm",
"cocotb.triggers.Timer"
] | [((1163, 1176), 'cocotb.test', 'cocotb.test', ([], {}), '()\n', (1174, 1176), False, 'import cocotb\n'), ((359, 390), 'pybfms.find_bfm', 'pybfms.find_bfm', (['""".*u_uart_bfm"""'], {}), "('.*u_uart_bfm')\n", (374, 390), False, 'import pybfms\n'), ((309, 322), 'pybfms.init', 'pybfms.init', ([], {}), '()\n', (320, 322), ... |
import sys
import argparse
from yolo import YOLO, detect_video
from PIL import Image
from keras.utils.generic_utils import Progbar
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageDraw, ImageFont
def detect_sequence_imgs(yolo, list_images, output_dir, save_img=False):
... | [
"os.mkdir",
"PIL.Image.new",
"keras.utils.generic_utils.Progbar",
"matplotlib.pyplot.show",
"os.makedirs",
"argparse.ArgumentParser",
"numpy.floor",
"os.path.exists",
"PIL.Image.open",
"PIL.Image.alpha_composite",
"numpy.array",
"yolo.YOLO.get_defaults",
"PIL.ImageDraw.Draw",
"argparse.Arg... | [((626, 647), 'keras.utils.generic_utils.Progbar', 'Progbar', ([], {'target': 'steps'}), '(target=steps)\n', (633, 647), False, 'from keras.utils.generic_utils import Progbar\n'), ((7588, 7647), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'argument_default': 'argparse.SUPPRESS'}), '(argument_default=arg... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 10:45:29 2020
@author: max
"""
from bs4 import BeautifulSoup
import requests
import re
from make_first_page import make_first_page
import numpy as np
import cv2
class Film():
def __init__(self,URL):
html = requests.get('http://www.99kubo.tv'+URL).text
... | [
"bs4.BeautifulSoup",
"re.sub",
"requests.get"
] | [((330, 357), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""lxml"""'], {}), "(html, 'lxml')\n", (343, 357), False, 'from bs4 import BeautifulSoup\n'), ((570, 597), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""lxml"""'], {}), "(html, 'lxml')\n", (583, 597), False, 'from bs4 import BeautifulSoup\n'), ((1347,... |
from __future__ import print_function, absolute_import
import filecmp
import os
from test.utils_test import BaseConnorTestCase
from testfixtures import TempDirectory
import connor.connor as connor
INPUT_DIR=os.path.realpath(os.path.dirname(__file__))
class ExamplesFunctionalTest(BaseConnorTestCase):
def test_ex... | [
"os.path.basename",
"connor.connor.main",
"os.path.dirname",
"os.path.isfile",
"filecmp.cmp",
"os.path.join",
"testfixtures.TempDirectory"
] | [((227, 252), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (242, 252), False, 'import os\n'), ((347, 362), 'testfixtures.TempDirectory', 'TempDirectory', ([], {}), '()\n', (360, 362), False, 'from testfixtures import TempDirectory\n'), ((1478, 1657), 'connor.connor.main', 'connor.main', (["... |
import logging
import dill
import pandas as pd
from fastapi import APIRouter
from pydantic import BaseModel, Field, validator
import joblib
from app.api.return_feedback import feedback
import numpy as np
from sklearn.preprocessing import LabelEncoder
# Connecting to fast API
log = logging.getLogger(__name__)
router =... | [
"pandas.DataFrame",
"pydantic.Field",
"pydantic.validator",
"pandas.to_datetime",
"pandas.to_numeric",
"app.api.return_feedback.feedback",
"logging.getLogger",
"fastapi.APIRouter"
] | [((284, 311), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (301, 311), False, 'import logging\n'), ((321, 332), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (330, 332), False, 'from fastapi import APIRouter\n'), ((481, 513), 'pydantic.Field', 'Field', (['...'], {'example': '"""Wa... |
from OpenGLCffi.EGL import params
@params(api='egl', prms=['dpy', 'attrib_list', 'layers', 'max_layers', 'num_layers'])
def eglGetOutputLayersEXT(dpy, attrib_list, layers, max_layers, num_layers):
pass
@params(api='egl', prms=['dpy', 'attrib_list', 'ports', 'max_ports', 'num_ports'])
def eglGetOutputPortsEXT(dpy, at... | [
"OpenGLCffi.EGL.params"
] | [((35, 123), 'OpenGLCffi.EGL.params', 'params', ([], {'api': '"""egl"""', 'prms': "['dpy', 'attrib_list', 'layers', 'max_layers', 'num_layers']"}), "(api='egl', prms=['dpy', 'attrib_list', 'layers', 'max_layers',\n 'num_layers'])\n", (41, 123), False, 'from OpenGLCffi.EGL import params\n'), ((206, 291), 'OpenGLCffi.... |
import argparse
import datetime
import json
import sys
import time
import traceback
from typing import Dict, List, Tuple
from . import __version__ as VERSION
from . import constants as C
from . import envfile
from .color import color
from .config import Config
from .logger import logger
from .image import DockerImage,... | [
"argparse.ArgumentParser",
"json.dumps",
"time.monotonic",
"traceback.format_exc",
"sys.exit"
] | [((418, 489), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Build container images faster ⚡️"""'}), "(description='Build container images faster ⚡️')\n", (441, 489), False, 'import argparse\n'), ((3547, 3563), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (3561, 3563), False, 'i... |
import unittest
import testutil
import shutil
import os
import time
import datetime
import hdbfs
import hdbfs.ark
import hdbfs.model
hdbfs.imgdb.MIN_THUMB_EXP = 4
class ThumbCases( testutil.TestCase ):
def setUp( self ):
self.init_env()
def tearDown( self ):
self.uninit_env()
def tes... | [
"unittest.main",
"hdbfs.Database"
] | [((5383, 5398), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5396, 5398), False, 'import unittest\n'), ((402, 418), 'hdbfs.Database', 'hdbfs.Database', ([], {}), '()\n', (416, 418), False, 'import hdbfs\n'), ((1192, 1208), 'hdbfs.Database', 'hdbfs.Database', ([], {}), '()\n', (1206, 1208), False, 'import hdbfs\... |
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
import matplotlib.pylab as plt
from sklearn.manifold import TSNE
import json, pickle
def load_json_data(json_path):
fea_dict = json.load(open(json_path))
fea_category_dict = {}
for key in fea_dict.keys():
cat = key[:key.find('_')]
if cat not in fea_cat... | [
"matplotlib.pylab.colorbar",
"sklearn.manifold.TSNE",
"numpy.array",
"numpy.matmul",
"matplotlib.pylab.cm.get_cmap",
"numpy.squeeze",
"matplotlib.pylab.subplots",
"numpy.unique",
"matplotlib.pylab.show"
] | [((1006, 1020), 'numpy.array', 'np.array', (['Data'], {}), '(Data)\n', (1014, 1020), True, 'import numpy as np\n'), ((1030, 1047), 'numpy.squeeze', 'np.squeeze', (['Label'], {}), '(Label)\n', (1040, 1047), True, 'import numpy as np\n'), ((1583, 1623), 'numpy.matmul', 'np.matmul', (['feas', "lda_paras['ProjectMat']"], {... |
import gdax
import os
API_KEY = os.environ['GDAX_API_KEY']
API_SECRET = os.environ['GDAX_API_SECRET']
API_PASS = os.environ['GDAX_API_PASS']
def main():
'''
Gets the current bitcoin price in usd and prints to the screen.
'''
client = gdax.AuthenticatedClient(API_KEY, API_SECRET, API_PASS)
ticker ... | [
"gdax.AuthenticatedClient"
] | [((253, 308), 'gdax.AuthenticatedClient', 'gdax.AuthenticatedClient', (['API_KEY', 'API_SECRET', 'API_PASS'], {}), '(API_KEY, API_SECRET, API_PASS)\n', (277, 308), False, 'import gdax\n')] |
from filters.FilterInterface import FilterInterface
import torch
import kornia
import kornia.augmentation as K
import torch.nn as nn
from util import str2bool
class WallpaperFilter(FilterInterface):
"""
Random tiled shifts in x and y with no loss
"""
@staticmethod
def add_settings(parser):
... | [
"torch.cat",
"torch.randint",
"torch.roll",
"torch.tensor"
] | [((687, 712), 'torch.randint', 'torch.randint', (['(0)', 'W', '(1,)'], {}), '(0, W, (1,))\n', (700, 712), False, 'import torch\n'), ((730, 755), 'torch.randint', 'torch.randint', (['(0)', 'H', '(1,)'], {}), '(0, H, (1,))\n', (743, 755), False, 'import torch\n'), ((984, 1029), 'torch.roll', 'torch.roll', (['row2'], {'sh... |
from typing import Dict, List, Optional
from xlab.base import time
from xlab.data.proto import data_entry_pb2, data_type_pb2
from xlab.data import importer
from xlab.data.importer.iex.api import batch
from xlab.net.proto import time_util
from xlab.util.status import errors
_DataType = data_type_pb2.DataType
_DataEntr... | [
"xlab.net.proto.time_util.from_time",
"xlab.net.proto.time_util.from_civil",
"xlab.util.status.errors.InvalidArgumentError",
"xlab.base.time.Now",
"xlab.base.time.ParseCivilTime",
"xlab.data.importer.iex.api.batch.IexBatchApi"
] | [((629, 648), 'xlab.data.importer.iex.api.batch.IexBatchApi', 'batch.IexBatchApi', ([], {}), '()\n', (646, 648), False, 'from xlab.data.importer.iex.api import batch\n'), ((1564, 1574), 'xlab.base.time.Now', 'time.Now', ([], {}), '()\n', (1572, 1574), False, 'from xlab.base import time\n'), ((924, 975), 'xlab.util.stat... |
import csv
import functools
import imghdr
import io
import itertools
import json
import unittest.mock
import flask
import flex
import PIL
import pytest
import requests
import spectrum_utils.spectrum as sus
import urllib.parse
from pyzbar import pyzbar
from metabolomics_spectrum_resolver import app
from metabolomics_s... | [
"flex.core.validate_api_response",
"metabolomics_spectrum_resolver.app.app.test_client",
"io.BytesIO",
"csv.reader",
"json.loads",
"spectrum_utils.spectrum.MsmsSpectrum",
"pyzbar.pyzbar.decode",
"flex.core.load",
"pytest.skip",
"json.dumps",
"imghdr.what",
"PIL.Image.open",
"metabolomics_spe... | [((443, 468), 'functools.lru_cache', 'functools.lru_cache', (['None'], {}), '(None)\n', (462, 468), False, 'import functools\n'), ((15792, 15849), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Mock seems to have some issues"""'}), "(reason='Mock seems to have some issues')\n", (15808, 15849), False, 'impo... |
import csv
from ebbe import Timer
from pelote import (
table_to_bipartite_graph,
monopartite_projection,
floatsam_threshold_learner,
)
from pelote.graph import largest_connected_component_order
with open("data/bipartite2.csv") as f:
bipartite = table_to_bipartite_graph(csv.DictReader(f), "account", "... | [
"ebbe.Timer",
"pelote.floatsam_threshold_learner",
"csv.DictReader",
"pelote.monopartite_projection",
"pelote.graph.largest_connected_component_order"
] | [((342, 404), 'pelote.monopartite_projection', 'monopartite_projection', (['bipartite', '"""account"""'], {'metric': '"""jaccard"""'}), "(bipartite, 'account', metric='jaccard')\n", (364, 404), False, 'from pelote import table_to_bipartite_graph, monopartite_projection, floatsam_threshold_learner\n'), ((433, 479), 'pel... |
"""Main file of this python package with the class Screenshots"""
# Standard library imports
import logging
# Third party imports
from char import char
# Local imports
from .class_screenshots import Screenshots
LOGGER = logging.getLogger("selenium_screenshots")
@char
def make_screenshot(
webdriver,
... | [
"logging.getLogger"
] | [((224, 265), 'logging.getLogger', 'logging.getLogger', (['"""selenium_screenshots"""'], {}), "('selenium_screenshots')\n", (241, 265), False, 'import logging\n')] |
import cv2 as cv
import numpy as np
def const_accel(dt = 1.0/30):
kf = cv.KalmanFilter(18, 6, 0)
state = np.zeros((18, 1), np.float32)
# Transition matrix position/orientation
tmp = np.eye(9, dtype=np.float32)
tmp[0:3, 3:6] = np.eye(3, dtype=np.float32) * dt
tmp[3:6, 6:9] = np.eye(3, dtyp... | [
"cv2.KalmanFilter",
"numpy.eye",
"numpy.zeros"
] | [((77, 102), 'cv2.KalmanFilter', 'cv.KalmanFilter', (['(18)', '(6)', '(0)'], {}), '(18, 6, 0)\n', (92, 102), True, 'import cv2 as cv\n'), ((115, 144), 'numpy.zeros', 'np.zeros', (['(18, 1)', 'np.float32'], {}), '((18, 1), np.float32)\n', (123, 144), True, 'import numpy as np\n'), ((205, 232), 'numpy.eye', 'np.eye', (['... |
import click
import sys
import pickle
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
from sklearn.naive_bayes import MultinomialNB
sys.path.append('src')
from data import read_processed_corpus, read_processed_category
@click.command()
@click.argument('in... | [
"sys.path.append",
"sklearn.naive_bayes.GaussianNB",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.preprocessing.LabelBinarizer",
"sklearn.naive_bayes.MultinomialNB",
"pickle.dump",
"sklearn.model_selection.train_test_split",
"sklearn.model_selection.cross_val_score",
"data.read_processed_corpus",... | [((195, 217), 'sys.path.append', 'sys.path.append', (['"""src"""'], {}), "('src')\n", (210, 217), False, 'import sys\n'), ((285, 300), 'click.command', 'click.command', ([], {}), '()\n', (298, 300), False, 'import click\n'), ((493, 529), 'click.option', 'click.option', (['"""--long"""'], {'is_flag': '(True)'}), "('--lo... |
# junkware setup.py
"""Setup script for Junwkare."""
import os
import sys
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
# Leave the following line to match the regexp [0-9]*\.[0-9]*\.[0-9]*
version = "0.0.1" # [major].[minor].[release]
... | [
"distutils.core.find_packages"
] | [((624, 656), 'distutils.core.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (637, 656), False, 'from distutils.core import setup, find_packages\n')] |
from datetime import datetime
from .downloader import get_pdf
from .config import papers
def main():
for paper_config in papers:
get_pdf(datetime.today(), paper_config) | [
"datetime.datetime.today"
] | [((151, 167), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (165, 167), False, 'from datetime import datetime\n')] |
from django.db.models import manager
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from pages.models import Page
from cs.api.serializers import CommentSerializer
from cs.models import Comment
class PageListSerializer(serializers.ModelSerializer):
url = serializers.... | [
"rest_framework.fields.SerializerMethodField",
"cs.api.serializers.CommentSerializer",
"cs.models.Comment.objects.filter",
"rest_framework.serializers.SerializerMethodField"
] | [((308, 343), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (341, 343), False, 'from rest_framework import serializers\n'), ((548, 571), 'rest_framework.fields.SerializerMethodField', 'SerializerMethodField', ([], {}), '()\n', (569, 571), False, 'from rest_fr... |
from typing import Any, Union, Dict, List, NewType, Callable
JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] # Simple JSON representation.
JSON = Dict[str, JSONType]
JWSPayload = NewType("JWSPayload", JSON)
JWSPayloadBytes = NewType("JWSPayloadBytes", bytes)
JOSEHeader = NewType("JOSE... | [
"typing.NewType"
] | [((212, 239), 'typing.NewType', 'NewType', (['"""JWSPayload"""', 'JSON'], {}), "('JWSPayload', JSON)\n", (219, 239), False, 'from typing import Any, Union, Dict, List, NewType, Callable\n'), ((259, 292), 'typing.NewType', 'NewType', (['"""JWSPayloadBytes"""', 'bytes'], {}), "('JWSPayloadBytes', bytes)\n", (266, 292), F... |
from math import radians, cos, sin
moves = []
def parse_line(line):
d, v = line[0], line[1:]
moves.append((d, int(v)))
with open('input', 'r') as f:
for line in f:
line = line.strip()
parse_line(line)
def rotate(waypoint, degrees):
r = radians(degrees)
x, y = waypoint
x_prim... | [
"math.radians",
"math.cos",
"math.sin"
] | [((273, 289), 'math.radians', 'radians', (['degrees'], {}), '(degrees)\n', (280, 289), False, 'from math import radians, cos, sin\n'), ((338, 344), 'math.cos', 'cos', (['r'], {}), '(r)\n', (341, 344), False, 'from math import radians, cos, sin\n'), ((351, 357), 'math.sin', 'sin', (['r'], {}), '(r)\n', (354, 357), False... |
import numpy as np
import numpy.linalg as la
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
import sys
import SBW_util as util
from matplotlib.animation import FuncAnimation
eps_u = 0.001 # 0.01
eps_v = 0.001 # 0.001
gamma_u = 0.005# 0.05
zeta = 0.0
alpha_v = 0... | [
"matplotlib.pyplot.plot",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.linalg.norm",
"numpy.exp",
"numpy.linalg.solve"
] | [((5835, 5847), 'numpy.zeros', 'np.zeros', (['(20)'], {}), '(20)\n', (5843, 5847), True, 'import numpy as np\n'), ((6402, 6415), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (6412, 6415), True, 'from matplotlib import pyplot as plt\n'), ((6416, 6431), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', '... |
"""
Hub for all fixtures used in the testing suite. Fixtures are created to run their functions
when a testing function requests it to be run.
apply_migrations():
- Accesses the alembic.ini file to configure a migration environment
- Runs the head migration, then downgrades
app():
- Instantiates a new app... | [
"alembic.config.Config",
"alembic.command.upgrade",
"warnings.filterwarnings",
"app.api.server.get_application",
"asgi_lifespan.LifespanManager",
"pytest.fixture",
"app.db.repositories.users.UsersRepository",
"httpx.AsyncClient",
"alembic.command.downgrade",
"app.models.user.UserCreate"
] | [((1203, 1234), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1217, 1234), False, 'import pytest\n'), ((1263, 1325), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", ... |
import logging
from re import search
from onto_tool import onto_tool
def test_action_message(caplog):
caplog.set_level(logging.INFO)
onto_tool.main([
'bundle', '-v', 'output', 'tests-output/bundle', 'tests/bundle/message.yaml'
])
logs = caplog.text
print(logs)
assert search(r'INFO.*T... | [
"onto_tool.onto_tool.main",
"re.search"
] | [((144, 242), 'onto_tool.onto_tool.main', 'onto_tool.main', (["['bundle', '-v', 'output', 'tests-output/bundle', 'tests/bundle/message.yaml']"], {}), "(['bundle', '-v', 'output', 'tests-output/bundle',\n 'tests/bundle/message.yaml'])\n", (158, 242), False, 'from onto_tool import onto_tool\n'), ((304, 354), 're.searc... |
import numpy as np
def read_pairs(pairs_filename):
pairs = []
with open(pairs_filename, 'r') as f:
for line in f.readlines()[1:]:
print(line)
pair = line.strip().split()
print('--',pair)
pairs.append(pair)
return np.array(pairs)
read_pair... | [
"numpy.array"
] | [((292, 307), 'numpy.array', 'np.array', (['pairs'], {}), '(pairs)\n', (300, 307), True, 'import numpy as np\n')] |
# Integration Tests
from tests.integration_tests import OK, client
from vtex import Vtex
import pytest
@pytest.fixture
def product_id():
return 1697
@pytest.fixture
def sku_id():
return 14362
@pytest.fixture
def sales_channel_id():
return 1
@pytest.fixture
def seller_id():
return 1
def test_ge... | [
"tests.integration_tests.client.catalog.get_product_specification",
"tests.integration_tests.client.catalog.get_sales_channel",
"tests.integration_tests.client.catalog.get_sales_channel_by_id",
"tests.integration_tests.client.catalog.get_category",
"tests.integration_tests.client.catalog.get_sku",
"tests.... | [((359, 389), 'tests.integration_tests.client.catalog.get_category', 'client.catalog.get_category', (['(2)'], {}), '(2)\n', (386, 389), False, 'from tests.integration_tests import OK, client\n'), ((483, 517), 'tests.integration_tests.client.catalog.get_category_tree', 'client.catalog.get_category_tree', ([], {}), '()\n... |
# coding: utf-8
import word2vec
import gensim
word2vec.word2phrase('./refined_text.txt', './wiki-phrase', verbose=True)
word2vec.word2vec('./wiki-phrase', './word2vec_model.bin', size=100, verbose=True)
word2vec.word2clusters('/Users/KYD/Documents/wiki_project/refined_text.txt', 'Users/KYD/Documents/wiki_project... | [
"word2vec.word2vec",
"word2vec.word2clusters",
"word2vec.word2phrase"
] | [((49, 122), 'word2vec.word2phrase', 'word2vec.word2phrase', (['"""./refined_text.txt"""', '"""./wiki-phrase"""'], {'verbose': '(True)'}), "('./refined_text.txt', './wiki-phrase', verbose=True)\n", (69, 122), False, 'import word2vec\n'), ((123, 209), 'word2vec.word2vec', 'word2vec.word2vec', (['"""./wiki-phrase"""', '"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
def get_env_total_dir(username, root_dir, bank):
user_dir = root_dir + "/" + username + "/"
workspace_dir = user_dir + "workspace-" + str(bank) + "/"
image_base_dir = workspace_dir + "images/"
json_base_dir = workspace_dir + "json/"
sparse_d... | [
"os.mkdir",
"os.path.exists"
] | [((688, 712), 'os.path.exists', 'os.path.exists', (['user_dir'], {}), '(user_dir)\n', (702, 712), False, 'import os\n'), ((722, 740), 'os.mkdir', 'os.mkdir', (['user_dir'], {}), '(user_dir)\n', (730, 740), False, 'import os\n'), ((752, 781), 'os.path.exists', 'os.path.exists', (['workspace_dir'], {}), '(workspace_dir)\... |
'''
data parameters
data: cora / dblp / arXiv / acm
split: train-test split used for the dataset
'''
data = "dblp"
split = 2
'''
model parameters
h: number of hidden dimensions
drop: hidden droput
relu: flag for relu non-linearity
'''
h = 1024
drop = 0.0
relu = False
'''
miscellaneous parameters
lr: learning rate... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.makedirs",
"torch.manual_seed",
"os.path.exists",
"torch.cuda.is_available",
"torch.device",
"inspect.currentframe",
"os.path.split",
"os.path.join",
"os.listdir",
"logging.getLogger"
] | [((704, 729), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (727, 729), False, 'import argparse\n'), ((738, 848), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Inductive Vertex Embedding on Multi-Relational Ordered Hypergraphs"""'}), "(description=\n 'Induct... |
''' Demonstrates linear regression with TensorFlow '''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# Set constants
N = 1000
learning_rate = 0.1
batch_size = 40 # the size of the part of the entire dataset, we... | [
"tensorflow.global_variables_initializer",
"numpy.empty",
"tensorflow.Session",
"tensorflow.pow",
"tensorflow.placeholder",
"numpy.random.randint",
"tensorflow.random_normal",
"numpy.random.normal",
"tensorflow.train.GradientDescentOptimizer"
] | [((443, 467), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'N'}), '(size=N)\n', (459, 467), True, 'import numpy as np\n'), ((477, 521), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.5)', 'scale': '(0.2)', 'size': 'N'}), '(loc=0.5, scale=0.2, size=N)\n', (493, 521), True, 'import numpy as np\n'... |
import streamlit as st
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier... | [
"sklearn.datasets.load_iris",
"streamlit.sidebar.slider",
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"sklearn.preprocessing.MinMaxScaler",
"streamlit.title",
"sklearn.preprocessing.MaxAbsScaler",
"streamlit.sidebar.selectbox"... | [((675, 764), 'streamlit.title', 'st.title', (['"""Effects of parameters and scaling on different classification algorithms"""'], {}), "(\n 'Effects of parameters and scaling on different classification algorithms')\n", (683, 764), True, 'import streamlit as st\n'), ((775, 848), 'streamlit.sidebar.selectbox', 'st.si... |
from math import inf as infinity
from os import system
import platform
# Make a list of the board
board = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
firstGame = True
def DisplayBoard():
# This function displays the board.
# For loop for each row and collum,
# and ... | [
"platform.system",
"os.system"
] | [((5809, 5822), 'os.system', 'system', (['"""cls"""'], {}), "('cls')\n", (5815, 5822), False, 'from os import system\n'), ((5843, 5858), 'os.system', 'system', (['"""clear"""'], {}), "('clear')\n", (5849, 5858), False, 'from os import system\n'), ((5737, 5754), 'platform.system', 'platform.system', ([], {}), '()\n', (5... |
#
from typing import List
import sys
import json
import numpy as np
from fairseq import pybleu
def process_bpe_symbol(sentence: str, bpe_symbol: str):
if bpe_symbol is not None:
sentence = (sentence + ' ').replace(bpe_symbol, '').rstrip()
return sentence
# =====
# algorithm helper
... | [
"numpy.abs",
"json.loads",
"numpy.zeros",
"numpy.random.randint",
"fairseq.pybleu.PyBleuScorer",
"numpy.arange",
"numpy.all"
] | [((745, 775), 'numpy.all', 'np.all', (['(match_score_arr >= 0.0)'], {}), '(match_score_arr >= 0.0)\n', (751, 775), True, 'import numpy as np\n'), ((857, 905), 'numpy.zeros', 'np.zeros', (['(1 + len1, 1 + len2)'], {'dtype': 'np.float32'}), '((1 + len1, 1 + len2), dtype=np.float32)\n', (865, 905), True, 'import numpy as ... |
import sys
from pathlib import Path
def colored_text(txt, color):
esc = "\x1b[{}m"
reset = esc.format(0)
code = esc.format(
{
"k": 30,
"r": 31,
"g": 32,
"y": 33,
"b": 34,
"m": 35,
"c": 36,
"w": 37,
... | [
"sys.stdout.write",
"pathlib.Path",
"sys.stdout.flush"
] | [((402, 421), 'sys.stdout.write', 'sys.stdout.write', (['x'], {}), '(x)\n', (418, 421), False, 'import sys\n'), ((426, 444), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (442, 444), False, 'import sys\n'), ((990, 996), 'pathlib.Path', 'Path', ([], {}), '()\n', (994, 996), False, 'from pathlib import Path\n... |
import time
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split, KFold
from dogFunctions import genData, genBatch
def convBlock( X, trn, nFilters, kernelSize, bnm ):
'''A block consisting of a convolution, a poolingi, and a batch normalization layer.'''
heInit = t... | [
"tensorflow.get_collection",
"tensorflow.reset_default_graph",
"tensorflow.layers.max_pooling2d",
"tensorflow.layers.batch_normalization",
"tensorflow.nn.softmax",
"tensorflow.nn.elu",
"tensorflow.placeholder_with_default",
"tensorflow.concat",
"tensorflow.placeholder",
"tensorflow.cast",
"dogFu... | [((319, 352), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (350, 352), True, 'import tensorflow as tf\n'), ((1017, 1050), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (1048, 1050), True, 'import tensorflow as tf\n'), (... |
"""
What I call functional tests, some people prefer to call acceptance tests, or end-to-end
tests. The main point is that these kinds of tests look at how the whole application func‐
tions, from the outside. Another term is black box test, because the test doesn’t know
anything about the internals of the system under ... | [
"unittest.main",
"selenium.webdriver.Firefox"
] | [((1106, 1138), 'unittest.main', 'unittest.main', ([], {'warnings': '"""ignore"""'}), "(warnings='ignore')\n", (1119, 1138), False, 'import unittest\n'), ((552, 571), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (569, 571), False, 'from selenium import webdriver\n')] |
import redis
import logging
import json
class redis_helper:
def __init__(self):
pool = redis.ConnectionPool(
host='t.cn', port=6379, decode_responses=True)
self.r = redis.Redis(connection_pool=pool)
logging.info('redis connecting')
def set_value(self, key, value):
... | [
"redis.Redis",
"logging.info",
"redis.ConnectionPool"
] | [((101, 168), 'redis.ConnectionPool', 'redis.ConnectionPool', ([], {'host': '"""t.cn"""', 'port': '(6379)', 'decode_responses': '(True)'}), "(host='t.cn', port=6379, decode_responses=True)\n", (121, 168), False, 'import redis\n'), ((199, 232), 'redis.Redis', 'redis.Redis', ([], {'connection_pool': 'pool'}), '(connectio... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__all__ = ["Summary"]
import fitsio
import numpy as np
try:
import matplotlib.pyplot as pl
except ImportError:
pl = None
else:
from matplotlib.ticker import MaxNLocator
from matplotlib.backends.backend_pdf impo... | [
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.abs",
"numpy.log",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.close",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"fitsio.read",
"matplotlib.pyplot.figure",
"numpy.all"
] | [((967, 1013), 'fitsio.read', 'fitsio.read', (['parent_response.target_pixel_file'], {}), '(parent_response.target_pixel_file)\n', (978, 1013), False, 'import fitsio\n'), ((1032, 1070), 'fitsio.read', 'fitsio.read', (["query['light_curve_file']"], {}), "(query['light_curve_file'])\n", (1043, 1070), False, 'import fitsi... |
# Generated by Django 2.2.1 on 2019-05-16 11:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('general', '0001_initial'),
]
operations = [
migr... | [
"django.db.models.FileField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.PositiveIntegerField",
"django.db.models.AutoField"
] | [((409, 502), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (425, 502), False, 'from django.db import migrations, models\... |
from typing import Dict, List, Tuple
from black import main
import matplotlib.pyplot as plt
import numpy as np
def _make_histogram(
reshaped_image: np.ndarray, threshold: float, bins: int = 5
) -> Tuple[List[int], np.ndarray]:
"""Fetch top colors from the histogram
Args:
reshaped_image (np.ndarr... | [
"numpy.histogramdd",
"numpy.unravel_index",
"numpy.argmin",
"numpy.min",
"numpy.where",
"numpy.array",
"numpy.max",
"numpy.mean",
"numpy.var",
"numpy.concatenate"
] | [((851, 906), 'numpy.histogramdd', 'np.histogramdd', (['reshaped_image'], {'bins': 'bins', 'range': 'ranges'}), '(reshaped_image, bins=bins, range=ranges)\n', (865, 906), True, 'import numpy as np\n'), ((2284, 2305), 'numpy.array', 'np.array', (['main_colors'], {}), '(main_colors)\n', (2292, 2305), True, 'import numpy ... |
"""initial
Revision ID: <KEY>
Revises:
Create Date: 2021-09-04 18:01:00.045883
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - p... | [
"alembic.op.drop_table",
"sqlalchemy.DateTime",
"alembic.op.f",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.String",
"sqlalchemy.Integer"
] | [((2057, 2081), 'alembic.op.drop_table', 'op.drop_table', (['"""answers"""'], {}), "('answers')\n", (2070, 2081), False, 'from alembic import op\n'), ((2145, 2167), 'alembic.op.drop_table', 'op.drop_table', (['"""tasks"""'], {}), "('tasks')\n", (2158, 2167), False, 'from alembic import op\n'), ((2235, 2259), 'alembic.o... |
import tensorflow as tf
def overlap_bbox(bbox_true, bbox_pred, mode = "normal"):
"""
bbox_true = [[x1, y1, x2, y2], ...] #(N, bbox)
bbox_pred = [[x1, y1, x2, y2], ...] #(M, bbox)
overlaps = pred & true iou matrix #(M, N)
"""
if mode not in ("normal", "foreground", "general", "complete", "d... | [
"tensorflow.logical_and",
"tensorflow.clip_by_value",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.reduce_max",
"tensorflow.concat",
"tensorflow.less_equal",
"tensorflow.minimum",
"tensorflow.tile",
"tensorflow.shape",
"tensorflow.where",
"tensorflow.keras.backend.epsilon",
"tenso... | [((596, 631), 'tensorflow.tile', 'tf.tile', (['bbox_pred', '[true_count, 1]'], {}), '(bbox_pred, [true_count, 1])\n', (603, 631), True, 'import tensorflow as tf\n'), ((662, 693), 'tensorflow.split', 'tf.split', (['bbox_true', '(4)'], {'axis': '(-1)'}), '(bbox_true, 4, axis=-1)\n', (670, 693), True, 'import tensorflow a... |
import cv2
import numpy as np
img = cv2.imread("imori.jpg").astype(np.float32)
H,W,C=img.shape
#gray scale
b = img[:,:,0].copy()
g = img[:,:,1].copy()
r = img[:,:,2].copy()
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b #0.2126+0.7152+0.0722 = 1
gray = gray.astype(np.uint8)
#filtersize
filtersize=3
pad=filtersize//2
o... | [
"cv2.waitKey",
"cv2.imwrite",
"cv2.destroyAllWindows",
"numpy.zeros",
"cv2.imread",
"numpy.max",
"numpy.min",
"cv2.imshow"
] | [((323, 378), 'numpy.zeros', 'np.zeros', (['(H + pad * 2, W + pad * 2, C)'], {'dtype': 'np.float'}), '((H + pad * 2, W + pad * 2, C), dtype=np.float)\n', (331, 378), True, 'import numpy as np\n'), ((695, 729), 'cv2.imwrite', 'cv2.imwrite', (['"""question13.jpg"""', 'out'], {}), "('question13.jpg', out)\n", (706, 729), ... |
""" Copyright start
Copyright (C) 2008 - 2021 Fortinet Inc.
All rights reserved.
FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE
Copyright end """
from connectors.core.connector import get_logger, ConnectorError
import boto3
from .constant import *
logger = get_logger('amazon-dynamodb')
class Dynam... | [
"boto3.client",
"connectors.core.connector.get_logger"
] | [((277, 306), 'connectors.core.connector.get_logger', 'get_logger', (['"""amazon-dynamodb"""'], {}), "('amazon-dynamodb')\n", (287, 306), False, 'from connectors.core.connector import get_logger, ConnectorError\n'), ((628, 783), 'boto3.client', 'boto3.client', (['"""dynamodb"""'], {'aws_access_key_id': 'self.aws_access... |
"""Module defining the main game screen."""
from typing import Optional
import pyxel
from bansoko.game.level import InputAction, Level
from bansoko.game.screens.gui_consts import GuiSprite, GuiPosition
from bansoko.game.screens.screen_factory import ScreenFactory
from bansoko.graphics import Point, Direction
... | [
"bansoko.graphics.Point",
"bansoko.graphics.animation.AnimationPlayer",
"pyxel.cls"
] | [((2623, 2635), 'pyxel.cls', 'pyxel.cls', (['(0)'], {}), '(0)\n', (2632, 2635), False, 'import pyxel\n'), ((6276, 6316), 'bansoko.graphics.animation.AnimationPlayer', 'AnimationPlayer', (['self.printing_animation'], {}), '(self.printing_animation)\n', (6291, 6316), False, 'from bansoko.graphics.animation import Animati... |
# Copyright 2021 Toyota Research Institute. All rights reserved.
# pylint: disable=unused-argument
from fvcore.transforms.transform import BlendTransform
from detectron2.data.transforms import RandomBrightness as _RandomBrightness
from detectron2.data.transforms import RandomContrast as _RandomContrast
from detectron... | [
"fvcore.transforms.transform.BlendTransform.register_type",
"fvcore.transforms.transform.BlendTransform"
] | [((648, 714), 'fvcore.transforms.transform.BlendTransform.register_type', 'BlendTransform.register_type', (['"""intrinsics"""', 'apply_no_op_intrinsics'], {}), "('intrinsics', apply_no_op_intrinsics)\n", (676, 714), False, 'from fvcore.transforms.transform import BlendTransform\n'), ((715, 771), 'fvcore.transforms.tran... |
from unittest import TestCase
from octopus.lib import paths
from octopus.modules.lantern import client
import json
class TestLantern(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_01_check(self):
lc = client.Lantern()
assert lc.check()
def test_0... | [
"json.load",
"octopus.modules.lantern.client.Lantern",
"octopus.lib.paths.rel2abs"
] | [((262, 278), 'octopus.modules.lantern.client.Lantern', 'client.Lantern', ([], {}), '()\n', (276, 278), False, 'from octopus.modules.lantern import client\n'), ((349, 365), 'octopus.modules.lantern.client.Lantern', 'client.Lantern', ([], {}), '()\n', (363, 365), False, 'from octopus.modules.lantern import client\n'), (... |
# Generated by Django 3.1 on 2020-09-24 20:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projectmanager', '0014_workunit_childs'),
]
operations = [
migrations.RemoveField(
model_name='wo... | [
"django.db.migrations.RemoveField",
"django.db.models.ForeignKey"
] | [((270, 330), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""workunit"""', 'name': '"""childs"""'}), "(model_name='workunit', name='childs')\n", (292, 330), False, 'from django.db import migrations, models\n'), ((476, 620), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], ... |
from django.test import TestCase
from hamcrest import assert_that, has_properties, has_property
from nectr.tutor.tests.factories import TutorFactory
class TestTutorFactory(TestCase):
def test_default_tutor_creation(self):
tutor = TutorFactory()
assert_that(tutor.base_user, has_property('username... | [
"hamcrest.has_property",
"nectr.tutor.tests.factories.TutorFactory"
] | [((246, 260), 'nectr.tutor.tests.factories.TutorFactory', 'TutorFactory', ([], {}), '()\n', (258, 260), False, 'from nectr.tutor.tests.factories import TutorFactory\n'), ((298, 322), 'hamcrest.has_property', 'has_property', (['"""username"""'], {}), "('username')\n", (310, 322), False, 'from hamcrest import assert_that... |
from flask import Flask
import sqlite3 as sql
app = Flask(__name__)
# routing
@app.route("/")
def hello():
print("hello called")
return "Hello World!"
''' or add url rule using add_url_rule function
def hello_world():
return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)
'''
# accepting a s... | [
"flask.Flask"
] | [((53, 68), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (58, 68), False, 'from flask import Flask\n')] |
import pandas as pd
from rdflib import URIRef, BNode, Literal, Graph
from rdflib.namespace import RDF, RDFS, FOAF, XSD
from rdflib import Namespace
import numpy as np
import math
import sys
import argparse
import json
import urllib
path = "/Users/nakamura/git/d_nagai/hpdb/docs/data/curation.json"
# jsonファイルを読み込む
f ... | [
"json.load"
] | [((380, 392), 'json.load', 'json.load', (['f'], {}), '(f)\n', (389, 392), False, 'import json\n')] |
'''
interactive plot/ graphical user interface to select an area for segmentation, and appropriate thresholds.
'''
from matplotlib.widgets import PolygonSelector, Button,Slider
from matplotlib import path
from matplotlib.image import AxesImage
from matplotlib.backend_bases import MouseEvent
from matplotlib.colors imp... | [
"numpy.load",
"matplotlib.pyplot.axes",
"matplotlib.widgets.Slider",
"numpy.mean",
"numpy.arange",
"matplotlib.widgets.PolygonSelector",
"matplotlib.pyplot.imread",
"numpy.round",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.meshgrid",
"os.path.exists",
"tkinter.filedialog.ask... | [((12274, 12335), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""mycmap"""', "['red', 'white']"], {}), "('mycmap', ['red', 'white'])\n", (12307, 12335), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((12384, 12398), 'matplotlib.pyplot.subplots', 'p... |
from __future__ import division
import time
from Model import Road
from Model import Lane
import numpy as np
import cv2 as cv
from types import NoneType
import numpy as np
import moviepy.editor as mpy
import matplotlib.pyplot as plt
from ImageProcessing.PerspectiveWrapper import PerspectiveWrapper
import tensorflow a... | [
"numpy.sum",
"matplotlib.pyplot.clf",
"numpy.ravel",
"matplotlib.pyplot.figure",
"cv2.line",
"get_model.get_model",
"numpy.copy",
"matplotlib.pyplot.imshow",
"ImageProcessing.PerspectiveWrapper.PerspectiveWrapper",
"Model.Road",
"tensorflow.compat.v1.Session",
"matplotlib.pyplot.pause",
"cv2... | [((608, 631), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (628, 631), True, 'from keras import backend as K\n'), ((688, 714), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (712, 714), True, 'import tensorflow as tf\n'), ((959, 994), 'tensorflow... |
from __future__ import annotations
import multiprocessing
import random
import time
import datetime
import rx
from rx.scheduler import ThreadPoolScheduler,NewThreadScheduler
from rx.scheduler import EventLoopScheduler
from rx import operators as ops
class Request:
def __init__(self, seed:str, duration_ms: int):
... | [
"random.randint",
"rx.scheduler.ThreadPoolScheduler",
"rx.repeat_value",
"rx.operators.subscribe_on",
"time.sleep",
"random.random",
"datetime.datetime.now"
] | [((1116, 1137), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1130, 1137), False, 'import random\n'), ((2749, 2790), 'rx.scheduler.ThreadPoolScheduler', 'ThreadPoolScheduler', (['optimal_thread_count'], {}), '(optimal_thread_count)\n', (2768, 2790), False, 'from rx.scheduler import ThreadPool... |
from ex111.UtilidadeCeV import moeda
from ex111.UtilidadeCeV import dado
valor = dado.leiadinheiro('Informe um valor: R$')
moeda.resumo(valor, 35, 22)
| [
"ex111.UtilidadeCeV.dado.leiadinheiro",
"ex111.UtilidadeCeV.moeda.resumo"
] | [((82, 123), 'ex111.UtilidadeCeV.dado.leiadinheiro', 'dado.leiadinheiro', (['"""Informe um valor: R$"""'], {}), "('Informe um valor: R$')\n", (99, 123), False, 'from ex111.UtilidadeCeV import dado\n'), ((124, 151), 'ex111.UtilidadeCeV.moeda.resumo', 'moeda.resumo', (['valor', '(35)', '(22)'], {}), '(valor, 35, 22)\n', ... |
# Generated by Django 3.2.3 on 2021-07-01 06:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0002_moneda'),
]
operations = [
migrations.AddField(
model_name='moneda',
name='descripcion',
f... | [
"django.db.models.CharField"
] | [((325, 368), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(50)'}), "(default='', max_length=50)\n", (341, 368), False, 'from django.db import migrations, models\n')] |
import itertools
import pytest
import ahpy
# Example from Saaty, <NAME>., 'Decision making with the analytic hierarchy process,'
# Int. J. Services Sciences, 1:1, 2008, pp. 83-98.
drinks = {('coffee', 'wine'): 9, ('coffee', 'tea'): 5, ('coffee', 'beer'): 2, ('coffee', 'soda'): 1,
('coffee', 'milk'): 1,
... | [
"itertools.permutations",
"pytest.approx",
"ahpy.Compose",
"itertools.combinations",
"pytest.raises",
"ahpy.Compare"
] | [((8185, 8207), 'ahpy.Compare', 'ahpy.Compare', (['"""a"""', 'a_m'], {}), "('a', a_m)\n", (8197, 8207), False, 'import ahpy\n'), ((8212, 8234), 'ahpy.Compare', 'ahpy.Compare', (['"""b"""', 'b_m'], {}), "('b', b_m)\n", (8224, 8234), False, 'import ahpy\n'), ((8239, 8261), 'ahpy.Compare', 'ahpy.Compare', (['"""c"""', 'c_... |
from easyhmm import sparsehmm, hmm
import numpy as np
obsProbList = np.array(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1/3, 1/3, 1/3), (0.75, 0.25, 0.0)), dtype = np.float32)
obsProbList = np.concatenate((obsProbList, obsProbList[::-1], obsProbList))
obsProbList += 1e-5
obsProbList ... | [
"numpy.sum",
"easyhmm.hmm.ViterbiDecoder",
"numpy.ones",
"numpy.array",
"numpy.concatenate"
] | [((72, 217), 'numpy.array', 'np.array', (['((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1 /\n 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0))'], {'dtype': 'np.float32'}), '(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, \n 0.0), (1 / 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0)), dtype=np... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
import dsz
import dsz.cmd
import dsz.data
import dsz.lp
class EventLogClear(dsz.data.Task):
def __init__(self, cmd=None):
d... | [
"dsz.cmd.data.ObjectGet",
"dsz.data.Task.__init__",
"dsz.cmd.data.Get",
"dsz.data.RegisterCommand"
] | [((1981, 2037), 'dsz.data.RegisterCommand', 'dsz.data.RegisterCommand', (['"""EventLogClear"""', 'EventLogClear'], {}), "('EventLogClear', EventLogClear)\n", (2005, 2037), False, 'import dsz\n'), ((319, 352), 'dsz.data.Task.__init__', 'dsz.data.Task.__init__', (['self', 'cmd'], {}), '(self, cmd)\n', (341, 352), False, ... |
import os
def parse_file(input_file):
with open(os.path.join(map_root, input_file)) as f:
lines = f.readlines()
filename = input_file.split("_")
name = '_'.join((filename[1], filename[2]))
with open(output_file, 'a') as f:
for line in lines:
data = line.split(",")
... | [
"os.path.join",
"os.listdir"
] | [((565, 585), 'os.listdir', 'os.listdir', (['map_root'], {}), '(map_root)\n', (575, 585), False, 'import os\n'), ((54, 88), 'os.path.join', 'os.path.join', (['map_root', 'input_file'], {}), '(map_root, input_file)\n', (66, 88), False, 'import os\n')] |
# Generated by Django 2.2 on 2019-05-13 11:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='wechatapp',
name='trade_type',
... | [
"django.db.models.URLField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ImageField",
"django.db.models.IntegerField"
] | [((327, 498), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('JSAPI', '公众号JSAPI'), ('NATIVE', '扫码支付'), ('APP', 'APP支付'), ('WAP',\n '网页WAP'), ('MINIAPP', '微信小程序')]", 'max_length': '(20)', 'verbose_name': '"""支付方式"""'}), "(choices=[('JSAPI', '公众号JSAPI'), ('NATIVE', '扫码支付'), ('APP',\n 'APP支付')... |
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from magnebot import Arm
from magnebot.paths import IK_ORIENTATIONS_RIGHT_PATH, IK_ORIENTATIONS_LEFT_PATH, IK_POSITIONS_PATH
from magnebot.ik.orientation import ORIENTATIONS
"""
Visualize the pre-calculated IK orientation solutions... | [
"PIL.Image.new",
"numpy.abs",
"PIL.ImageFont.truetype",
"pathlib.Path",
"numpy.arange",
"magnebot.paths.IK_POSITIONS_PATH.resolve",
"PIL.ImageDraw.Draw"
] | [((627, 651), 'pathlib.Path', 'Path', (['"""../doc/images/ik"""'], {}), "('../doc/images/ik')\n", (631, 651), False, 'from pathlib import Path\n'), ((1153, 1186), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', '(14)'], {}), '(font_path, 14)\n', (1171, 1186), False, 'from PIL import Image, ImageDraw, Ima... |
import random
data = ['goo', 'choki', 'pa']
data_choice = random.choice(data)
print(data_choice)
| [
"random.choice"
] | [((58, 77), 'random.choice', 'random.choice', (['data'], {}), '(data)\n', (71, 77), False, 'import random\n')] |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, os
sys.path.append('../')
from BAAlgorithmUtils.BSTUtil import BSTTree
def start1():
print('\n********************************')
trainSamples = [
{'key': 5, 'content': '5-1'},
{'key': 3, 'content': '3-1'},
{'key': 4, 'content': '4-... | [
"sys.path.append",
"BAAlgorithmUtils.BSTUtil.BSTTree"
] | [((58, 80), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (73, 80), False, 'import sys, os\n'), ((595, 604), 'BAAlgorithmUtils.BSTUtil.BSTTree', 'BSTTree', ([], {}), '()\n', (602, 604), False, 'from BAAlgorithmUtils.BSTUtil import BSTTree\n'), ((1594, 1603), 'BAAlgorithmUtils.BSTUtil.BSTTree',... |
#!/usr/bin/python3
from ninja import ninja_syntax
import os
import yaml
def remove_file_extension( filename: str ) -> str:
(root, _extension) = os.path.splitext( filename )
return root
def extract_extension( filename: str ) -> str:
(_root, extension) = os.path.splitext( filename )
return extension
B... | [
"yaml.load",
"os.path.splitext",
"os.path.basename"
] | [((602, 628), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (618, 628), False, 'import os\n'), ((150, 176), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (166, 176), False, 'import os\n'), ((268, 294), 'os.path.splitext', 'os.path.splitext', (['filename'], {})... |
import string
import random
import socket
import shutil
import os
import sys
import hashlib
import time
import Constant as const
import Function as func
####### STRINGHE
# Format string completa text con char per ottenere una stringa di lunghezza length
# Tested, fondamentale che il text passato sia stringa e la leng... | [
"os.stat",
"Function.roll_the_dice",
"socket.socket",
"shutil.get_terminal_size",
"random.choice",
"Function.error",
"time.time",
"os.listdir"
] | [((2706, 2742), 'random.choice', 'random.choice', (['[ip[0:15], ip[16:55]]'], {}), '([ip[0:15], ip[16:55]])\n', (2719, 2742), False, 'import random\n'), ((2980, 3007), 'os.listdir', 'os.listdir', (['const.FILE_COND'], {}), '(const.FILE_COND)\n', (2990, 3007), False, 'import os\n'), ((4688, 4715), 'os.listdir', 'os.list... |
from http import HTTPStatus
from privx_api.response import PrivXAPIResponse
from privx_api.base import BasePrivXAPI
from privx_api.enums import UrlEnum
class HostStoreAPI(BasePrivXAPI):
"""
Host store API.
"""
def create_host(self, host: dict) -> PrivXAPIResponse:
"""
Create a host, ... | [
"privx_api.response.PrivXAPIResponse"
] | [((514, 573), 'privx_api.response.PrivXAPIResponse', 'PrivXAPIResponse', (['response_status', 'HTTPStatus.CREATED', 'data'], {}), '(response_status, HTTPStatus.CREATED, data)\n', (530, 573), False, 'from privx_api.response import PrivXAPIResponse\n'), ((931, 985), 'privx_api.response.PrivXAPIResponse', 'PrivXAPIRespons... |
import logging
import copy
import json
from flask import Flask, request, jsonify, abort
import pylru
from constrained_decoding import create_constrained_decoder
from constrained_decoding.server import convert_token_annotations_to_spans, remap_constraint_indices
logging.basicConfig()
logger = logging.getLogger(__name... | [
"constrained_decoding.server.convert_token_annotations_to_spans",
"copy.deepcopy",
"logging.basicConfig",
"constrained_decoding.create_constrained_decoder",
"flask.Flask",
"flask.abort",
"constrained_decoding.server.remap_constraint_indices",
"json.dumps",
"pylru.lrucache",
"flask.jsonify",
"fla... | [((265, 286), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (284, 286), False, 'import logging\n'), ((296, 323), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (313, 323), False, 'import logging\n'), ((362, 377), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n'... |
from typing import Optional
import asyncio
import subprocess
import argparse
from config import env_vars, read_config
from lib.slack import send_message as slack_send
from pathlib import Path
import os
def parse_arguments():
parser = argparse.ArgumentParser(
description="Nginx config validation tool"
... | [
"subprocess.run",
"lib.slack.send_message",
"os.makedirs",
"argparse.ArgumentParser",
"asyncio.sleep"
] | [((240, 307), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Nginx config validation tool"""'}), "(description='Nginx config validation tool')\n", (263, 307), False, 'import argparse\n'), ((691, 709), 'os.makedirs', 'os.makedirs', (['mpath'], {}), '(mpath)\n', (702, 709), False, 'import ... |
import os
from searcher.es_search import SearchResults_ES
from searcher.corpus_manager import CorpusManager
#from searcher.models import QueryRequest, VisRequest
#from searcher.query_handler import QueryHandler
from searcher.corpus_manager import CorpusManager
from searcher.nlp_model_manager import NLPModelManager
from... | [
"pandas.DataFrame",
"tqdm.tqdm",
"numpy.errstate",
"searcher.es_search.SearchResults_ES",
"gensim.models.LdaModel",
"numpy.arange",
"searcher.corpus_manager.CorpusManager",
"gensim.models.CoherenceModel"
] | [((637, 666), 'searcher.corpus_manager.CorpusManager', 'CorpusManager', (['self.query_obj'], {}), '(self.query_obj)\n', (650, 666), False, 'from searcher.corpus_manager import CorpusManager\n'), ((752, 868), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.qu... |
#! /usr/bin/env python3
from argh import ArghParser # pip install argh
from bag.pathlib_complement import Path
def replace_many(
extensions: "Comma-separated file extensions to search", # type: ignore
text: "The text being sought", # type: ignore
replace: "The replacement text", # type: ignore
d... | [
"argh.ArghParser",
"bag.pathlib_complement.Path"
] | [((1231, 1275), 'argh.ArghParser', 'ArghParser', ([], {'description': 'replace_many.__doc__'}), '(description=replace_many.__doc__)\n', (1241, 1275), False, 'from argh import ArghParser\n'), ((433, 442), 'bag.pathlib_complement.Path', 'Path', (['dir'], {}), '(dir)\n', (437, 442), False, 'from bag.pathlib_complement imp... |
import numpy as np
from PulseGenerator import Pulse
# physical constants
planck = 4.13566751691e-15 # ev s
hbarfs = planck * 1e15 / (2 * np.pi) #ev fs
ev_nm = 1239.842
opt_t = np.linspace(900,1100,10)/hbarfs
def build_fitness_function(
nbins=30,
tl_duration=19.0,
e_carrier=2.22,
e_shap... | [
"numpy.load",
"numpy.sum",
"PulseGenerator.Pulse",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.random.rand",
"numpy.sqrt"
] | [((177, 203), 'numpy.linspace', 'np.linspace', (['(900)', '(1100)', '(10)'], {}), '(900, 1100, 10)\n', (188, 203), True, 'import numpy as np\n'), ((429, 456), 'numpy.load', 'np.load', (['"""operators/es.npy"""'], {}), "('operators/es.npy')\n", (436, 456), True, 'import numpy as np\n'), ((469, 499), 'numpy.load', 'np.lo... |
from django.conf import settings
from django.db import models
from .organization import Organization
from ..regions.region import Region
class UserProfile(models.Model):
"""
Data model representing a user profile
:param id: The database id of the user profile
Relationship fields:
:param user: ... | [
"django.db.models.ForeignKey",
"django.db.models.OneToOneField",
"django.db.models.ManyToManyField"
] | [((554, 654), 'django.db.models.OneToOneField', 'models.OneToOneField', (['settings.AUTH_USER_MODEL'], {'related_name': '"""profile"""', 'on_delete': 'models.CASCADE'}), "(settings.AUTH_USER_MODEL, related_name='profile',\n on_delete=models.CASCADE)\n", (574, 654), False, 'from django.db import models\n'), ((679, 74... |
# -*- coding:utf8 -*-
# !/usr/bin/env python
# Copyright 2017 Google Inc. 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... | [
"re.split",
"json.loads",
"future.standard_library.install_aliases",
"flask.Flask",
"urllib.request.urlopen",
"json.dumps",
"flask.jsonify",
"flask.request.json.get",
"flask.make_response",
"os.getenv"
] | [((732, 749), 'future.standard_library.install_aliases', 'install_aliases', ([], {}), '()\n', (747, 749), False, 'from future.standard_library import install_aliases\n'), ((1048, 1063), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1053, 1063), False, 'from flask import Flask\n'), ((1296, 1327), 'flask.r... |
import os, sys
import argparse
import numpy as np
import gzip
# image processing
from PIL import Image
import cv2
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
from estimators import estimate, estimators_list
data_output = 'data/generated'
def write_pr... | [
"sys.stdout.write",
"os.makedirs",
"argparse.ArgumentParser",
"estimators.estimate",
"os.path.exists",
"ipfml.processing.segmentation.divide_in_blocks",
"PIL.Image.open",
"numpy.arange",
"os.path.join",
"os.listdir"
] | [((720, 746), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (736, 746), False, 'import os, sys\n'), ((775, 890), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check complexity of each zone of scene using estimator during rendering"""'}), "(description=... |
from unittest.mock import create_autospec, sentinel
import pytest
from pyramid import httpexceptions
from lms.models import ReusedConsumerKey
from lms.resources import LTILaunchResource
from lms.resources._js_config import JSConfig
from lms.services import HAPIError
from lms.validation import ValidationError
from lms... | [
"lms.services.HAPIError",
"unittest.mock.create_autospec",
"pyramid.httpexceptions.HTTPForbidden",
"lms.models.ReusedConsumerKey",
"lms.views.exceptions.ExceptionViews",
"pyramid.httpexceptions.HTTPNotFound",
"lms.validation.ValidationError",
"pyramid.httpexceptions.HTTPBadRequest"
] | [((471, 500), 'pyramid.httpexceptions.HTTPNotFound', 'httpexceptions.HTTPNotFound', ([], {}), '()\n', (498, 500), False, 'from pyramid import httpexceptions\n'), ((736, 766), 'pyramid.httpexceptions.HTTPForbidden', 'httpexceptions.HTTPForbidden', ([], {}), '()\n', (764, 766), False, 'from pyramid import httpexceptions\... |