code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import pkg_resources
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx'
]
master_doc = 'index'
project = 'sprockets.mixins.sentry'
copyright = '2016-2018, AWeber Communications'
release = pkg_resources.get_distribution('sprockets.mixins.sentry').version
version = '.'.join(release.split('.')[0:1])
py... | [
"pkg_resources.get_distribution"
] | [((208, 265), 'pkg_resources.get_distribution', 'pkg_resources.get_distribution', (['"""sprockets.mixins.sentry"""'], {}), "('sprockets.mixins.sentry')\n", (238, 265), False, 'import pkg_resources\n')] |
from shuffle import SHUFFLE
import csv
shuffle=SHUFFLE()
documents=[]
labell=[]
negative=[]
positive=[]
file="dataset_twitter.csv"
dataset_names=['A','B','C','D','E','F']
Size=[500000,450000,350000,250000,150000,100000]
with open(file) as Data:
reader=csv.reader(Data)
records=list(reader)
... | [
"csv.writer",
"shuffle.SHUFFLE",
"csv.reader"
] | [((53, 62), 'shuffle.SHUFFLE', 'SHUFFLE', ([], {}), '()\n', (60, 62), False, 'from shuffle import SHUFFLE\n'), ((275, 291), 'csv.reader', 'csv.reader', (['Data'], {}), '(Data)\n', (285, 291), False, 'import csv\n'), ((650, 669), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (660, 669), False, 'import cs... |
# -*- coding: utf-8 -*-
"""Wrapper for running Melt preprocessing
"""
from snakemake.shell import shell
__author__ = "<NAME>"
__email__ = "<EMAIL>"
shell(
r"""
# -----------------------------------------------------------------------------
# Redirect stderr to log file by default and enable printing executed com... | [
"snakemake.shell.shell"
] | [((151, 728), 'snakemake.shell.shell', 'shell', (['"""\n# -----------------------------------------------------------------------------\n# Redirect stderr to log file by default and enable printing executed commands\nexec 2> >(tee -a "{snakemake.log}")\nset -x\n# --------------------------------------------------------... |
import os
import argparse
import shutil
import re
parser = argparse.ArgumentParser(description='Раскладываем фоточки')
parser.add_argument('--dest', metavar='DIR', type=str, required=True,
help='dir for result')
parser.add_argument('--pic-path', metavar='DIR', type=str, required=True,
... | [
"os.path.exists",
"shutil.make_archive",
"argparse.ArgumentParser",
"re.match",
"os.mkdir",
"shutil.copy",
"shutil.rmtree",
"os.walk"
] | [((61, 120), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Раскладываем фоточки"""'}), "(description='Раскладываем фоточки')\n", (84, 120), False, 'import argparse\n'), ((936, 955), 'os.mkdir', 'os.mkdir', (['args.dest'], {}), '(args.dest)\n', (944, 955), False, 'import os\n'), ((1549, ... |
"""
Author : <NAME>
Created At : 17 July 2019
Description : To read and write the JSON file
"""
import json
import os
# Author : <NAME>
# Reads data from the given json file and returns list/json
def read_json_data(data_source):
fp = open(data_source, encoding="utf8")
data = json.loads(fp.read())
retur... | [
"os.path.realpath",
"json.dump"
] | [((531, 564), 'json.dump', 'json.dump', (['data_source', 'json_file'], {}), '(data_source, json_file)\n', (540, 564), False, 'import json\n'), ((458, 484), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (474, 484), False, 'import os\n')] |
"""
Download the openfmri ds117 dataset and extract it into the designated
"study_path" folder.
"""
import argparse
import tarfile
from urllib.request import urlretrieve
from os import makedirs
from tqdm import tqdm
from config import fname
# Handle command line arguments
parser = argparse.ArgumentParser(description=... | [
"config.fname.subject_url",
"config.fname.subject_dir",
"os.makedirs",
"argparse.ArgumentParser",
"config.fname.subject_tarball",
"urllib.request.urlretrieve",
"config.fname.ds117_dir",
"tqdm.tqdm"
] | [((284, 328), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (307, 328), False, 'import argparse\n'), ((1305, 1347), 'os.makedirs', 'makedirs', (['fname.archive_dir'], {'exist_ok': '(True)'}), '(fname.archive_dir, exist_ok=True)\n', (1313, 1347), False... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 16:45:30 2017
@author: RunNing
"""
import random
import numpy as np
import matplotlib.pyplot as plt
import abc
class Algorithm(metaclass=abc.ABCMeta):
@abc.abstractmethod
def reset(self):
return
@abc.abstractmethod
def sel... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"numpy.log",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"random.randint",
"random.uniform",
"matplotlib.pyplot.savefig",
"numpy.ones",
"numpy.argmax",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyp... | [((5032, 5071), 'numpy.arange', 'np.arange', (['(play_rounds + 1)'], {'dtype': 'float'}), '(play_rounds + 1, dtype=float)\n', (5041, 5071), True, 'import numpy as np\n'), ((5737, 5764), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (5747, 5764), True, 'import matplotlib.... |
from libs.wikipedia import Wikipedia
from libs.mangadex import Mangadex
from libs.wolfram import Wolfram
from discord.ext import commands
from libs.jisho import Jisho
import wavelink
import aiohttp
class Bakerbot(commands.Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs... | [
"aiohttp.ClientSession",
"libs.jisho.Jisho.setup",
"libs.mangadex.Mangadex.setup",
"libs.wolfram.Wolfram.setup",
"wavelink.Client",
"libs.wikipedia.Wikipedia.setup"
] | [((345, 368), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (366, 368), False, 'import aiohttp\n'), ((393, 418), 'wavelink.Client', 'wavelink.Client', ([], {'bot': 'self'}), '(bot=self)\n', (408, 418), False, 'import wavelink\n'), ((499, 535), 'libs.mangadex.Mangadex.setup', 'Mangadex.setup', ([],... |
from django.shortcuts import redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from functools import wraps
# session登录认证
def login_required(fn):
@wraps(fn)
def wrapper(request, *args, **kwargs):
if request.session.get('user') is None:
if reque... | [
"django.shortcuts.redirect",
"functools.wraps",
"django.http.JsonResponse"
] | [((199, 208), 'functools.wraps', 'wraps', (['fn'], {}), '(fn)\n', (204, 208), False, 'from functools import wraps\n'), ((357, 444), 'django.http.JsonResponse', 'JsonResponse', (["{'code': 403, 'text': 'login required', 'result': None, 'errors': {}}"], {}), "({'code': 403, 'text': 'login required', 'result': None,\n ... |
from numpy.lib.twodim_base import mask_indices
from libs.MyType import *
import numpy as np
def getVecLength3D(v:Vec3D):
length=np.sqrt(v.x**2+v.y**2+v.z**2)
return length
def vectDot(v1:Vec3D,v2:Vec3D,default=True):#!这里改写了原来的方法,将default参数改为TRUE来使用原来的方法
if default:
l3=np.sqrt((v1.x-v2.x)**2+(v1.y-... | [
"numpy.sqrt",
"numpy.linalg.eig",
"numpy.power"
] | [((133, 172), 'numpy.sqrt', 'np.sqrt', (['(v.x ** 2 + v.y ** 2 + v.z ** 2)'], {}), '(v.x ** 2 + v.y ** 2 + v.z ** 2)\n', (140, 172), True, 'import numpy as np\n'), ((1212, 1230), 'numpy.linalg.eig', 'np.linalg.eig', (['mat'], {}), '(mat)\n', (1225, 1230), True, 'import numpy as np\n'), ((291, 360), 'numpy.sqrt', 'np.sq... |
import logging
from typing import List
from marshmallow_jsonapi import fields
from starlette.responses import Response
from starlette_jsonapi.fields import JSONAPIRelationship
from starlette_jsonapi.resource import BaseResource, BaseRelationshipResource
from starlette_jsonapi.responses import JSONAPIResponse
from sta... | [
"logging.getLogger",
"marshmallow_jsonapi.fields.Str",
"accounts.models.Team",
"starlette_jsonapi.fields.JSONAPIRelationship",
"accounts.models.Team.get_items",
"starlette_jsonapi.responses.JSONAPIResponse",
"accounts.models.Team.get_item"
] | [((472, 499), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (489, 499), False, 'import logging\n'), ((544, 570), 'marshmallow_jsonapi.fields.Str', 'fields.Str', ([], {'dump_only': '(True)'}), '(dump_only=True)\n', (554, 570), False, 'from marshmallow_jsonapi import fields\n'), ((582, 607... |
# sales / pickups / tries
# ['date' => Carbon::parse('2017-03-03 00:00:00'),'barcode' => 123],
# met de funcie get_random_entry krijg je random entry tussen de data: 2016-1-1 01:00:00' en '2017-12-31 01:00:00'
# in combinatie met de barcodes uit de set barcodes
import random
import time
barcodes = ['\'1234567891234\... | [
"time.localtime",
"random.random",
"time.strptime",
"random.randint"
] | [((1465, 1493), 'time.strptime', 'time.strptime', (['start', 'format'], {}), '(start, format)\n', (1478, 1493), False, 'import time\n'), ((1522, 1548), 'time.strptime', 'time.strptime', (['end', 'format'], {}), '(end, format)\n', (1535, 1548), False, 'import time\n'), ((1639, 1660), 'time.localtime', 'time.localtime', ... |
# # from selenium import webdriver
# # import time
# # from selenium.webdriver.chrome.options import Options
# #
# # chrome_options = Options()
# # # chrome_options.add_argument('--headless')
# # # chrome_options.add_argument('--disable-gpu')
# #
# # path = r'/usr/bin/chromedriver'
# # driver = webdriver.Chrome(chrome_... | [
"requests.get"
] | [((5033, 5122), 'requests.get', 'requests.get', ([], {'url': '"""https://s.taobao.com/search?q=%E5%8D%AB%E8%A1%A3"""', 'headers': 'headers'}), "(url='https://s.taobao.com/search?q=%E5%8D%AB%E8%A1%A3',\n headers=headers)\n", (5045, 5122), False, 'import requests\n')] |
#coding=utf-8
#!/usr/bin/env python
import pickle
from .harvesttext import HarvestText
from .resources import *
__version__ = '0.8.1.5'
def saveHT(htModel,filename):
with open(filename, "wb") as f:
htModel.prepared = False
htModel.hanlp_prepared = False
pickle.dump(htModel,f)
def loadHT(f... | [
"pickle.load",
"pickle.dump"
] | [((284, 307), 'pickle.dump', 'pickle.dump', (['htModel', 'f'], {}), '(htModel, f)\n', (295, 307), False, 'import pickle\n'), ((379, 393), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (390, 393), False, 'import pickle\n')] |
#!/usr/bin/env python
import yamale
import os
from colorama import Fore, Style
test_dir = os.path.dirname(os.path.abspath(__file__))
test_data_dir = os.path.join(test_dir, 'data')
prod_data = os.path.join(test_dir, '..', '_data', 'data.yml')
schema_file = os.path.join(test_dir, 'yamale_schema.yml')
schema = yamale.ma... | [
"os.path.abspath",
"yamale.make_data",
"os.path.join",
"yamale.make_schema"
] | [((151, 181), 'os.path.join', 'os.path.join', (['test_dir', '"""data"""'], {}), "(test_dir, 'data')\n", (163, 181), False, 'import os\n'), ((194, 243), 'os.path.join', 'os.path.join', (['test_dir', '""".."""', '"""_data"""', '"""data.yml"""'], {}), "(test_dir, '..', '_data', 'data.yml')\n", (206, 243), False, 'import o... |
import os
import subprocess
import uno
import unohelper
from com.sun.star.connection import NoConnectException
from com.sun.star.lang import IllegalArgumentException
class SpreadScript(object):
def __init__(self, file_name=None):
"""Initialise the class.
:arg str file_name: File name.
""... | [
"os.fork",
"os.path.abspath",
"subprocess.call",
"uno.getComponentContext"
] | [((684, 693), 'os.fork', 'os.fork', ([], {}), '()\n', (691, 693), False, 'import os\n'), ((1026, 1051), 'uno.getComponentContext', 'uno.getComponentContext', ([], {}), '()\n', (1049, 1051), False, 'import uno\n'), ((733, 872), 'subprocess.call', 'subprocess.call', (['(\'soffice --accept="socket,host=localhost,port=2002... |
from xarm.arm import *
import math
import time
grip_close()
def reset():
movej((500, 500, 500, 500, 500), 2000)
power_off()
#jDepart = (497, 426, 738, 55, 500)
jDepart = (497, 426, 700, 55, 500)
movej(jDepart, 2000)
eye_x = 10
z_up = 0
z_down = -18
#(495, 420, 700, 64, 502)
servo_coord = get_position(Fal... | [
"math.cos",
"math.sin"
] | [((1017, 1032), 'math.cos', 'math.cos', (['angle'], {}), '(angle)\n', (1025, 1032), False, 'import math\n'), ((1039, 1054), 'math.sin', 'math.sin', (['angle'], {}), '(angle)\n', (1047, 1054), False, 'import math\n')] |
from datetime import date, datetime
from pytz import utc
from parameterized import parameterized, param
import dateparser
from tests import BaseTestCase
class TestParseFunction(BaseTestCase):
def setUp(self):
super().setUp()
self.result = NotImplemented
@parameterized.expand([
param... | [
"datetime.datetime",
"datetime.datetime.min.time",
"parameterized.param",
"dateparser.parse",
"datetime.date"
] | [((3521, 3550), 'dateparser.parse', 'dateparser.parse', (['date_string'], {}), '(date_string)\n', (3537, 3550), False, 'import dateparser\n'), ((3652, 3719), 'dateparser.parse', 'dateparser.parse', (['date_string'], {'languages': 'languages', 'locales': 'locales'}), '(date_string, languages=languages, locales=locales)\... |
import fastscapelib_fortran as fs
import numpy as np
import xsimlab as xs
from .grid import UniformRectilinearGrid2D
@xs.process
class TotalVerticalMotion:
"""Sum up all vertical motions of bedrock and topographic surface,
respectively.
Vertical motions may result from external forcing, erosion and/or
... | [
"xsimlab.foreign",
"numpy.repeat",
"xsimlab.runtime",
"numpy.minimum",
"numpy.full_like",
"numpy.any",
"xsimlab.variable",
"numpy.empty_like",
"xsimlab.group",
"xsimlab.on_demand",
"xsimlab.index"
] | [((403, 429), 'xsimlab.group', 'xs.group', (['"""bedrock_upward"""'], {}), "('bedrock_upward')\n", (411, 429), True, 'import xsimlab as xs\n'), ((456, 482), 'xsimlab.group', 'xs.group', (['"""surface_upward"""'], {}), "('surface_upward')\n", (464, 482), True, 'import xsimlab as xs\n'), ((511, 539), 'xsimlab.group', 'xs... |
from django.core.mail import send_mail
from drugstore.celery import app
from django.template.loader import render_to_string
@app.task
def send_order_acceptance(data):
message = f'Thanks for your choice!\n' \
f'Your order # {data["id"]} will be delivered soon.'\
f'Total: {data[... | [
"django.core.mail.send_mail",
"django.template.loader.render_to_string"
] | [((351, 402), 'django.template.loader.render_to_string', 'render_to_string', (['"""email_template_order.html"""', 'data'], {}), "('email_template_order.html', data)\n", (367, 402), False, 'from django.template.loader import render_to_string\n'), ((408, 590), 'django.core.mail.send_mail', 'send_mail', ([], {'message': '... |
from __future__ import print_function
import time
import math
from sr.robot import *
"""++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"""
"""---------------- R.T.1 First Assignment --------------------"""
"""---------- By The Robotics Engineering Student -------------"""
"""--------------------- <NAME... | [
"time.sleep"
] | [((1360, 1379), 'time.sleep', 'time.sleep', (['seconds'], {}), '(seconds)\n', (1370, 1379), False, 'import time\n'), ((1679, 1698), 'time.sleep', 'time.sleep', (['seconds'], {}), '(seconds)\n', (1689, 1698), False, 'import time\n'), ((13951, 13964), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (13961, 13964), Fa... |
import tensorflow as tf
import numpy as np
FLAGS = tf.app.flags.FLAGS
def create_graph(model_file=None):
if not model_file:
model_file = FLAGS.model_file
#
with open(model_file, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_... | [
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.argmax",
"tensorflow.GraphDef",
"numpy.squeeze",
"tensorflow.import_graph_def",
"tensorflow.expand_dims",
"tensorflow.image.decode_jpeg"
] | [((495, 507), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (505, 507), True, 'import tensorflow as tf\n'), ((611, 656), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""input"""', 'dtype': 'tf.string'}), "(name='input', dtype=tf.string)\n", (625, 656), True, 'import tensorflow as tf\n'), ((669, 70... |
import numpy as np
from deepscratch.models.layers.activations.activation import Activation
class Softmax(Activation):
def __call__(self, data):
exp = np.exp(data - np.max(data, axis=-1, keepdims=True))
return exp / np.sum(exp, axis=-1, keepdims=True)
def backward(self, data):
soft... | [
"numpy.sum",
"numpy.max"
] | [((237, 272), 'numpy.sum', 'np.sum', (['exp'], {'axis': '(-1)', 'keepdims': '(True)'}), '(exp, axis=-1, keepdims=True)\n', (243, 272), True, 'import numpy as np\n'), ((178, 214), 'numpy.max', 'np.max', (['data'], {'axis': '(-1)', 'keepdims': '(True)'}), '(data, axis=-1, keepdims=True)\n', (184, 214), True, 'import nump... |
from datetime import date
ano = int(input('\033[30mQual ano você quer analisar? Coloque 0 para analisar o ano atual: '))
if ano == 0:
ano = date.today().year #Ele irá analisar o ano atual e dizer se ele é bissexto ou não.
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print(f'\033[1;30mO ano \033[1;34m{a... | [
"datetime.date.today"
] | [((144, 156), 'datetime.date.today', 'date.today', ([], {}), '()\n', (154, 156), False, 'from datetime import date\n')] |
from oauth.oauth import OAuthRequest, OAuthServer, build_authenticate_header,\
OAuthSignatureMethod_PLAINTEXT, OAuthSignatureMethod_HMAC_SHA1
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
import ast
OAUTH_REALM_KEY_NAME = getattr(settings, 'OAUTH_REALM_KEY_NAM... | [
"oauth.oauth.OAuthSignatureMethod_HMAC_SHA1",
"oauth.oauth.build_authenticate_header",
"django.http.HttpResponse",
"stores.DataStore",
"oauth.oauth.OAuthSignatureMethod_PLAINTEXT"
] | [((3145, 3198), 'oauth.oauth.build_authenticate_header', 'build_authenticate_header', ([], {'realm': 'OAUTH_REALM_KEY_NAME'}), '(realm=OAUTH_REALM_KEY_NAME)\n', (3170, 3198), False, 'from oauth.oauth import OAuthRequest, OAuthServer, build_authenticate_header, OAuthSignatureMethod_PLAINTEXT, OAuthSignatureMethod_HMAC_S... |
import sys
sys.path.append('../src')
import pytest
from collection import Collection
def setup_function():
global collection
collection = Collection()
def tear_down_function():
pass
def test_library():
collection.set_library("test_library")
library = collection.get_library()
assert library... | [
"sys.path.append",
"collection.Collection"
] | [((12, 37), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (27, 37), False, 'import sys\n'), ((149, 161), 'collection.Collection', 'Collection', ([], {}), '()\n', (159, 161), False, 'from collection import Collection\n')] |
import numpy as np
import tensorflow as tf
from util.default_util import *
from util.dual_encoder_util import *
from layer.basic import *
__all__ = ["Dense", "DoubleDense", "StackedDense", "StackedDoubleDense"]
class Dense(object):
"""dense layer"""
def __init__(self,
unit_dim,
... | [
"tensorflow.device",
"tensorflow.layers.Dense",
"tensorflow.variable_scope",
"tensorflow.random_uniform"
] | [((1236, 1286), 'tensorflow.variable_scope', 'tf.variable_scope', (['self.scope'], {'reuse': 'tf.AUTO_REUSE'}), '(self.scope, reuse=tf.AUTO_REUSE)\n', (1253, 1286), True, 'import tensorflow as tf\n'), ((1288, 1315), 'tensorflow.device', 'tf.device', (['self.device_spec'], {}), '(self.device_spec)\n', (1297, 1315), True... |
from typing import Dict, Optional
from enum import Enum, auto
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.tree import DecisionTreeClassifier
class ClassifierType(Enum):
DECISION_TREE = auto()
RANDOM_FOREST = auto()
RANDOM_FOREST_REGRESSOR = auto()
class GridS... | [
"sklearn.ensemble.RandomForestRegressor",
"sklearn.tree.DecisionTreeClassifier",
"enum.auto",
"sklearn.ensemble.RandomForestClassifier"
] | [((236, 242), 'enum.auto', 'auto', ([], {}), '()\n', (240, 242), False, 'from enum import Enum, auto\n'), ((263, 269), 'enum.auto', 'auto', ([], {}), '()\n', (267, 269), False, 'from enum import Enum, auto\n'), ((300, 306), 'enum.auto', 'auto', ([], {}), '()\n', (304, 306), False, 'from enum import Enum, auto\n'), ((35... |
import argparse
import os, os.path
import torch
import numpy as np
import soundfile as sf
def load_waveglow(args, parser):
if not args.from_repo:
return load_waveglow_from_hub()
return load_waveglow_from_repo(args, parser)
def load_waveglow_from_hub():
waveglow = torch.hub.load('nvidia/DeepLearn... | [
"torch.split",
"torch.hub.load",
"torch.log",
"argparse.ArgumentParser",
"torch.load",
"os.path.join",
"os.path.splitext",
"torch.exp",
"soundfile.write",
"numpy.zeros",
"torch.no_grad",
"inference.load_and_setup_model",
"waveglow.denoiser.Denoiser",
"torch.zeros",
"os.walk"
] | [((288, 361), 'torch.hub.load', 'torch.hub.load', (['"""nvidia/DeepLearningExamples:torchhub"""', '"""nvidia_waveglow"""'], {}), "('nvidia/DeepLearningExamples:torchhub', 'nvidia_waveglow')\n", (302, 361), False, 'import torch\n'), ((645, 748), 'inference.load_and_setup_model', 'load_and_setup_model', (['"""WaveGlow"""... |
import logging
import math
import time
from typing import Any, Dict, Iterator, Optional, Union
from allennlp.common import Tqdm
from allennlp.common import util as common_util
from allennlp.data.dataloader import TensorDict
from allennlp.nn import util as nn_util
from allennlp.training import Trainer, GradientDescentT... | [
"logging.getLogger",
"allennlp.training.util.get_metrics",
"allennlp.common.Tqdm.tqdm",
"torch.as_tensor",
"math.ceil",
"torch.distributed.barrier",
"allennlp.common.util.peak_gpu_memory",
"torch.isnan",
"torch.distributed.get_rank",
"allennlp.nn.util.move_to_device",
"allennlp.common.util.lazy_... | [((545, 572), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (562, 572), False, 'import logging\n'), ((576, 635), 'allennlp.training.Trainer.register', 'Trainer.register', (['"""gan"""'], {'constructor': '"""from_partial_objects"""'}), "('gan', constructor='from_partial_objects')\n", (592... |
import arcade
import imgui
import imgui.core
from imdemo.page import Page
class Rect(Page):
def draw(self):
imgui.begin("Rectangle")
draw_list = imgui.get_window_draw_list()
p1 = self.rel(20, 35)
p2 = self.rel(90, 80)
draw_list.add_rect(*p1, *p2, imgui.get_color_u32_rgba(1... | [
"imgui.begin",
"imgui.get_window_draw_list",
"imgui.get_color_u32_rgba",
"imgui.end"
] | [((123, 147), 'imgui.begin', 'imgui.begin', (['"""Rectangle"""'], {}), "('Rectangle')\n", (134, 147), False, 'import imgui\n'), ((168, 196), 'imgui.get_window_draw_list', 'imgui.get_window_draw_list', ([], {}), '()\n', (194, 196), False, 'import imgui\n'), ((509, 520), 'imgui.end', 'imgui.end', ([], {}), '()\n', (518, ... |
import tomotopy as tp
model = tp.DTModel()
print(model.alpha)
# print(model.eta)
print(model.lr_a)
print(model.lr_b)
print(model.lr_c)
print(model.num_timepoints)
print(model.num_docs_by_timepoint)
model.add_doc(["new", "document"], timepoint=0)
| [
"tomotopy.DTModel"
] | [((31, 43), 'tomotopy.DTModel', 'tp.DTModel', ([], {}), '()\n', (41, 43), True, 'import tomotopy as tp\n')] |
from machine import Pin
import onewire
import time, ds18x20
ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12, which is D6 on NodeMCU board.
ds_sensor = ds18x20.DS18X20(ow)
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
while True:
d... | [
"ds18x20.DS18X20",
"time.sleep_ms",
"time.sleep",
"machine.Pin"
] | [((167, 186), 'ds18x20.DS18X20', 'ds18x20.DS18X20', (['ow'], {}), '(ow)\n', (182, 186), False, 'import time, ds18x20\n'), ((82, 89), 'machine.Pin', 'Pin', (['(12)'], {}), '(12)\n', (85, 89), False, 'from machine import Pin\n'), ((346, 364), 'time.sleep_ms', 'time.sleep_ms', (['(750)'], {}), '(750)\n', (359, 364), False... |
#!/usr/bin/env python3
import argparse
from datetime import datetime
import ipaddress
import socket
import struct
import dateutil.parser
import pandas as pd
from common import *
N = 30
def main(args):
contents = read_lastb_db_contents(args.lastb_db_filename)
df = pd.DataFrame.from_records(contents)
df.co... | [
"pandas.DataFrame.from_records",
"datetime.datetime.now",
"struct.pack",
"argparse.ArgumentParser"
] | [((275, 310), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['contents'], {}), '(contents)\n', (300, 310), True, 'import pandas as pd\n'), ((2170, 2201), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['rows'], {}), '(rows)\n', (2195, 2201), True, 'import pandas as pd\n'), ((2302, 2327)... |
import argparse
from agutil import status_bar
import subprocess
import csv
import shutil
from qtl.annotation import Annotation
import tempfile
def run(args):
print("Parsing GTF")
gtf = Annotation(args.gtf.name)
print("Parsing GCT")
numRows = int(subprocess.check_output("wc -l %s" % args.gct.name, shell... | [
"csv.DictWriter",
"subprocess.check_output",
"argparse.FileType",
"csv.DictReader",
"argparse.ArgumentParser",
"agutil.status_bar.iter",
"shutil.copyfile",
"tempfile.NamedTemporaryFile",
"qtl.annotation.Annotation"
] | [((194, 219), 'qtl.annotation.Annotation', 'Annotation', (['args.gtf.name'], {}), '(args.gtf.name)\n', (204, 219), False, 'from qtl.annotation import Annotation\n'), ((428, 468), 'csv.DictReader', 'csv.DictReader', (['args.gct'], {'delimiter': '"""\t"""'}), "(args.gct, delimiter='\\t')\n", (442, 468), False, 'import cs... |
from django.test import TestCase
import requests
import responses
# lfs imports
from lfs.core.models import Country
from lfs.order.models import Order
from lfs.order.settings import PAID, PAYMENT_FAILED, PAYMENT_FLAGGED, SUBMITTED
from .models import CompropagoTransaction
from .views import compropago_webhook
class... | [
"lfs.order.models.Order.objects.all",
"lfs.core.models.Country.objects.get",
"lfs.order.models.Order"
] | [((463, 493), 'lfs.core.models.Country.objects.get', 'Country.objects.get', ([], {'code': '"""ie"""'}), "(code='ie')\n", (482, 493), False, 'from lfs.core.models import Country\n'), ((1145, 1238), 'lfs.order.models.Order', 'Order', ([], {'invoice_address': 'invoice_address', 'shipping_address': 'shipping_address', 'uui... |
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
# from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return get... | [
"django.forms.ValidationError"
] | [((543, 597), 'django.forms.ValidationError', 'forms.ValidationError', (['"""Not an @up.edu email address."""'], {}), "('Not an @up.edu email address.')\n", (564, 597), False, 'from django import forms\n')] |
import numpy as np
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
class EmotionDetector:
def __init__(self, ):
self.model = Sequential()
self.model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', inp... | [
"cv2.rectangle",
"cv2.imshow",
"tensorflow.keras.layers.Dense",
"cv2.destroyAllWindows",
"cv2.imdecode",
"cv2.CascadeClassifier",
"tensorflow.keras.layers.Conv2D",
"numpy.frombuffer",
"cv2.waitKey",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Dropout",
"numpy.argmax",
"cv2... | [((230, 242), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (240, 242), False, 'from tensorflow.keras.models import Sequential\n'), ((1088, 1176), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (["(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')"], {}), "(cv2.data.haarcascades ... |
import numpy as np # numerical tools
from scipy import integrate
from scipy import interpolate
c_light=299792.458#in km/s
#Find nearest value
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
#### DATA SN
def get_SN_info(targetname):
data_sn=np.loadtxt('Info_SNe_KAIT.txt',u... | [
"numpy.abs",
"numpy.trapz",
"numpy.where",
"numpy.size",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.zeros",
"numpy.polyval",
"numpy.concatenate",
"numpy.loadtxt",
"numpy.genfromtxt"
] | [((2997, 3038), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["MJD['B']", "mags['B']"], {}), "(MJD['B'], mags['B'])\n", (3017, 3038), False, 'from scipy import interpolate\n'), ((3051, 3105), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["MJD['B']", "(mags['B'] + emags['B'])"], {}), "(MJD['B'], mags... |
# Import the TextBlob class from the textblob library
from textblob import TextBlob
# Set a text to analyze
text = "Today is a beautiful day. Tomorrow looks like bad weather. is a"
# Create a blob object using the TextBlob class, with the text variable as a parameter
blob = TextBlob(text)
# We can see the sentences ... | [
"textblob.TextBlob"
] | [((277, 291), 'textblob.TextBlob', 'TextBlob', (['text'], {}), '(text)\n', (285, 291), False, 'from textblob import TextBlob\n')] |
import random
import string
from typing import Optional, List
from datetime import datetime, timedelta
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.middleware.cors import CORSMiddleware
from jose import JWTError, jw... | [
"fastapi.FastAPI",
"models.bind_engine",
"fastapi.security.OAuth2PasswordBearer",
"fastapi.HTTPException",
"uvicorn.run",
"datetime.datetime.utcnow",
"jose.jwt.decode",
"random.choice",
"passlib.context.CryptContext",
"jose.jwt.encode",
"datetime.datetime.now",
"models.Interest",
"models.Mee... | [((2028, 2060), 'models.create_db', 'create_db', (['"""sqlite:///db.sqlite"""'], {}), "('sqlite:///db.sqlite')\n", (2037, 2060), False, 'from models import User as UserInDB, Meeting as MeetingInDB, Participant, Interest, create_db, bind_engine, get_session\n'), ((2061, 2095), 'models.bind_engine', 'bind_engine', (['"""... |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright (C) 2020 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import atexit
import os
import shutil
import subprocess
imp... | [
"time.sleep",
"sys.exit",
"os.fork",
"sys.stderr.fileno",
"os.remove",
"os.path.exists",
"sys.stdin.fileno",
"os.kill",
"threading.Lock",
"subprocess.run",
"sys.stderr.flush",
"os.umask",
"os.getpid",
"sys.stdout.flush",
"atexit.register",
"shutil.which",
"sys.stderr.write",
"sys.s... | [((775, 791), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (789, 791), False, 'import threading\n'), ((2929, 2970), 'pkg.PackageManagerFactory.get_installer', 'pkg.PackageManagerFactory.get_installer', ([], {}), '()\n', (2968, 2970), False, 'import pkg\n'), ((3582, 3595), 'os.chdir', 'os.chdir', (['"""/"""'], ... |
__all__ = ("Command",)
import json
from django.apps import apps
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = (
"fix json fields in string format"
)
def fix_instance(self, instance, field):
if isinstance(getattr(instance, field), str):
... | [
"jsonfield.JSONField",
"django.apps.apps.get_models"
] | [((980, 997), 'django.apps.apps.get_models', 'apps.get_models', ([], {}), '()\n', (995, 997), False, 'from django.apps import apps\n'), ((950, 956), 'jsonfield.JSONField', 'step', ([], {}), '()\n', (954, 956), True, 'from jsonfield import JSONField as step\n')] |
"""This module implements uploading videos on YouTube via Selenium using metadata JSON file
to extract its title, description etc."""
from typing import DefaultDict, Optional
from selenium_firefox.firefox import Firefox, By, Keys
from collections import defaultdict
import json
import time
from youtube_uploader_sel... | [
"logging.basicConfig",
"logging.getLogger",
"random.uniform",
"pathlib.Path",
"pathlib.Path.cwd",
"collections.defaultdict",
"json.load"
] | [((394, 415), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (413, 415), False, 'import logging\n'), ((554, 570), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (565, 570), False, 'from collections import defaultdict\n'), ((1058, 1085), 'logging.getLogger', 'logging.getLogger', (['... |
"""
Implementation of the Deep Embedded Self-Organizing Map model
SOM layer
@author <NAME>
@version 1.0
"""
import tensorflow as tf
from tensorflow import keras # using Tensorflow's Keras API
from keras.engine.topology import Layer, InputSpec
class SOMLayer(Layer):
"""
Self-Organizing Map layer class with re... | [
"tensorflow.expand_dims",
"keras.engine.topology.InputSpec"
] | [((1225, 1242), 'keras.engine.topology.InputSpec', 'InputSpec', ([], {'ndim': '(2)'}), '(ndim=2)\n', (1234, 1242), False, 'from keras.engine.topology import Layer, InputSpec\n'), ((1377, 1429), 'keras.engine.topology.InputSpec', 'InputSpec', ([], {'dtype': 'tf.float32', 'shape': '(None, input_dim)'}), '(dtype=tf.float3... |
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# fetch 指在一个会话中可以同时运行多个OP,传递一个OP数组给会话
# feed
# 创建一个变量input1
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input2, input3)
# 乘法OP
mul = tf.multiply(input1, add)
with tf.Session() as sess:
# 这个... | [
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.add",
"tensorflow.multiply",
"tensorflow.constant"
] | [((146, 162), 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), '(3.0)\n', (157, 162), True, 'import tensorflow as tf\n'), ((172, 188), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (183, 188), True, 'import tensorflow as tf\n'), ((198, 214), 'tensorflow.constant', 'tf.constant', (['(5.0)'], {}... |
"""
Gradcam visualization ref modified from implementation by fchollet (https://keras.io/examples/vision/grad_cam)
"""
import cv2
import numpy as np
import os
import sys
import argparse
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Displa... | [
"utils.preprocess_image",
"cv2.imwrite",
"tensorflow.math.abs",
"argparse.ArgumentParser",
"tensorflow.multiply",
"model_modified.efficientdet_mod",
"tensorflow.keras.preprocessing.image.array_to_img",
"numpy.zeros",
"tensorflow.GradientTape",
"numpy.expand_dims",
"numpy.min",
"tensorflow.redu... | [((548, 638), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Gradcam visualization script for Efficientdet."""'}), "(description=\n 'Gradcam visualization script for Efficientdet.')\n", (571, 638), False, 'import argparse\n'), ((1693, 1812), 'model_modified.efficientdet_mod', 'efficie... |
from functools import singledispatchmethod
import ir
def walk(node):
"""
walk an expression depth first in post order, yielding everything but the original node
"""
if hasattr(node, "subexprs"):
for subexpr in node.subexprs:
yield from walk(subexpr)
yield subexpr
def... | [
"ir.IfElse",
"ir.WhileLoop",
"ir.ForLoop",
"ir.Function"
] | [((3109, 3148), 'ir.Function', 'ir.Function', (['node.name', 'node.args', 'body'], {}), '(node.name, node.args, body)\n', (3120, 3148), False, 'import ir\n'), ((3501, 3555), 'ir.IfElse', 'ir.IfElse', (['node.test', 'if_branch', 'else_branch', 'node.pos'], {}), '(node.test, if_branch, else_branch, node.pos)\n', (3510, 3... |
# 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.0
#
# Unless required by applicable law or a... | [
"common.Ref",
"utils.SubnetName",
"utils.NetworkName"
] | [((2722, 2751), 'utils.NetworkName', 'utils.NetworkName', (['deployment'], {}), '(deployment)\n', (2739, 2751), False, 'import utils\n'), ((2765, 2793), 'utils.SubnetName', 'utils.SubnetName', (['deployment'], {}), '(deployment)\n', (2781, 2793), False, 'import utils\n'), ((1977, 1997), 'common.Ref', 'common.Ref', (['n... |
from datetime import datetime
from tkinter import messagebox
import certifi
from pymongo import MongoClient
class ManageDB:
def __init__(self):
uri = "mongodb+srv://chatterji.so23d.mongodb.net/test?authSource=%24external&authMechanism=MONGODB-X509&retryWrites=true&w=majority"
self.client = MongoClie... | [
"certifi.where",
"datetime.datetime.now",
"tkinter.messagebox.showinfo"
] | [((1103, 1139), 'tkinter.messagebox.showinfo', 'messagebox.showinfo', (['"""Logging In"""', 'v'], {}), "('Logging In', v)\n", (1122, 1139), False, 'from tkinter import messagebox\n'), ((502, 517), 'certifi.where', 'certifi.where', ([], {}), '()\n', (515, 517), False, 'import certifi\n'), ((709, 723), 'datetime.datetime... |
"""
Start a child process that prints signals it receives
"""
import asyncio
import signal
import os
from functools import partial
import sys
from simpervisor import SupervisedProcess
signal_printer = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'signalprinter.py'
)
async def main():
count = ... | [
"asyncio.all_tasks",
"asyncio.Task.all_tasks",
"asyncio.gather",
"os.path.abspath",
"asyncio.get_event_loop"
] | [((652, 676), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (674, 676), False, 'import asyncio\n'), ((236, 261), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (251, 261), False, 'import os\n'), ((825, 853), 'asyncio.all_tasks', 'asyncio.all_tasks', ([], {'loop': 'loop... |
import click
from fs import errors
from fs.path import relpath, normpath
from fs.osfs import OSFS
from ._words2lines import words2lines
@click.command()
@click.argument('paths', nargs=-1, required=False)
@click.option('--force', '-f', is_flag=True, help='force skip instead of aborting')
@click.pass_context
def ls(ctx... | [
"click.confirm",
"click.argument",
"click.option",
"fs.path.normpath",
"click.command"
] | [((139, 154), 'click.command', 'click.command', ([], {}), '()\n', (152, 154), False, 'import click\n'), ((156, 205), 'click.argument', 'click.argument', (['"""paths"""'], {'nargs': '(-1)', 'required': '(False)'}), "('paths', nargs=-1, required=False)\n", (170, 205), False, 'import click\n'), ((207, 294), 'click.option'... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('movie/<int:pk>/', views.movie_details, name='movie-details'),
path('search/', views.SearchView.as_view(), name='search'),
path('search/results/', views.SearchResultsView.as_view(), name='search_res... | [
"django.urls.path"
] | [((70, 103), 'django.urls.path', 'path', (['""""""', 'views.home'], {'name': '"""home"""'}), "('', views.home, name='home')\n", (74, 103), False, 'from django.urls import path\n'), ((109, 175), 'django.urls.path', 'path', (['"""movie/<int:pk>/"""', 'views.movie_details'], {'name': '"""movie-details"""'}), "('movie/<int... |
# coding=utf-8
# Copyright 2021 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 t... | [
"tensorflow.train.Example"
] | [((833, 851), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (849, 851), True, 'import tensorflow as tf\n')] |
import os
import subprocess
import argparse
import torch
import json
# import h5py
import gzip, csv
import numpy as np
from tqdm import tqdm
from torch.nn.utils.rnn import pad_sequence
from transformers import *
def get_sentence_features(batches, tokenizer, model, device, maxlen=500):
features = tokenizer.batc... | [
"csv.DictWriter",
"argparse.ArgumentParser",
"gzip.open",
"os.makedirs",
"tqdm.tqdm",
"subprocess.run",
"numpy.memmap",
"os.path.join",
"os.path.isfile",
"torch.tensor",
"torch.cuda.is_available",
"torch.no_grad"
] | [((486, 541), 'torch.tensor', 'torch.tensor', (["features['attention_mask']"], {'device': 'device'}), "(features['attention_mask'], device=device)\n", (498, 541), False, 'import torch\n'), ((558, 608), 'torch.tensor', 'torch.tensor', (["features['input_ids']"], {'device': 'device'}), "(features['input_ids'], device=dev... |
#!/usr/bin/env python3
import argparse
import os
from datetime import datetime
from math import floor
from typing import Optional
import requests
from github import Github, Milestone, Repository
from github.Label import Label
def as_percentage(a: float, b: float) -> int:
if b == 0:
return 0
return f... | [
"requests.post",
"argparse.ArgumentParser",
"math.floor",
"os.environ.get",
"datetime.datetime.now"
] | [((319, 337), 'math.floor', 'floor', (['(a / b * 100)'], {}), '(a / b * 100)\n', (324, 337), False, 'from math import floor\n'), ((395, 420), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (418, 420), False, 'import argparse\n'), ((1037, 1051), 'datetime.datetime.now', 'datetime.now', ([], {}),... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import h2o
import sys
sys.path.insert(1,"../../../") # allow us to run this standalone
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimato... | [
"h2o.estimators.random_forest.H2ORandomForestEstimator",
"sys.path.insert",
"tests.pyunit_utils.locate",
"h2o.estimators.stackedensemble.H2OStackedEnsembleEstimator",
"h2o.estimators.gbm.H2OGradientBoostingEstimator",
"tests.pyunit_utils.standalone_test"
] | [((110, 141), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../../../"""'], {}), "(1, '../../../')\n", (125, 141), False, 'import sys\n'), ((1301, 1465), 'h2o.estimators.gbm.H2OGradientBoostingEstimator', 'H2OGradientBoostingEstimator', ([], {'distribution': '"""bernoulli"""', 'ntrees': '(10)', 'nfolds': 'nfolds',... |
# Generated by Django 2.1.2 on 2019-04-05 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hixny', '0003_hixnyprofile_user_accept'),
]
operations = [
migrations.AddField(
model_name='hixnyprofile',
name='cda... | [
"django.db.models.TextField"
] | [((349, 389), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'default': '""""""'}), "(blank=True, default='')\n", (365, 389), False, 'from django.db import migrations, models\n')] |
# Generated by Django 2.2.9 on 2021-03-10 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('explorations', '0002_auto_20210216_1626'),
]
operations = [
migrations.AddField(
model_name='datedmeasure',
name='me... | [
"django.db.models.TextField",
"django.db.models.BigIntegerField",
"django.db.models.CharField"
] | [((352, 397), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (374, 397), False, 'from django.db import migrations, models\n'), ((533, 578), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'blank': '(True)', 'nul... |
import time
from collections import ChainMap
from typing import Any, Callable, Literal, Optional, Sequence, TypedDict
from .dbapi import Cursor
RowType = dict[str, Any]
MessageTableType = TypedDict("Table", {"modified": list[RowType], "deleted": list[RowType]})
MessageType = TypedDict("Message", {"timestamp": int, "t... | [
"time.time",
"typing.TypedDict"
] | [((190, 263), 'typing.TypedDict', 'TypedDict', (['"""Table"""', "{'modified': list[RowType], 'deleted': list[RowType]}"], {}), "('Table', {'modified': list[RowType], 'deleted': list[RowType]})\n", (199, 263), False, 'from typing import Any, Callable, Literal, Optional, Sequence, TypedDict\n'), ((278, 356), 'typing.Type... |
# Copyright 2015 The TensorFlow 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.
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | [
"tensorflow.Graph",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.variable_scope",
"reader.ptb_raw_data",
"numpy.exp",
"config.get_config",
"tensorflow.train.import_meta_graph",
"tensorflow.name_scope",
"tensorflow.train.Supervisor",
"ptb_input.PTBInput",
"tensorflow.Conf... | [((2802, 2813), 'time.time', 'time.time', ([], {}), '()\n', (2811, 2813), False, 'import time\n'), ((3684, 3705), 'numpy.exp', 'np.exp', (['(costs / iters)'], {}), '(costs / iters)\n', (3690, 3705), True, 'import numpy as np\n'), ((4137, 4179), 'reader.ptb_raw_data', 'reader.ptb_raw_data', (['flags.FLAGS.data_path'], {... |
#! /usr/bin/env python3
# coding: utf-8
# modified example from https://weatherstack.com/documentation
import requests, hvac, getpass
# sets up the vault client, prompts for creds, and gather's the data
client = hvac.Client(url='http://localhost:8200')
client.auth.userpass.login(input("username: "), getpass.getpass(pr... | [
"hvac.Client",
"getpass.getpass",
"requests.get"
] | [((213, 253), 'hvac.Client', 'hvac.Client', ([], {'url': '"""http://localhost:8200"""'}), "(url='http://localhost:8200')\n", (224, 253), False, 'import requests, hvac, getpass\n'), ((621, 681), 'requests.get', 'requests.get', (['"""http://api.weatherstack.com/forecast"""', 'params'], {}), "('http://api.weatherstack.com... |
import math
def speed_of_sound(gamma, pressure, density):
return math.sqrt(gamma*(pressure/density))
def tip_speed(rpm, diameter):
"""
Assumes standard atmosphere sea level conditions
rpm
diameter: meters
returns: Mach speed at tip
"""
return ( (diameter * math.pi * rpm) / 60 ) / spee... | [
"math.sqrt"
] | [((70, 109), 'math.sqrt', 'math.sqrt', (['(gamma * (pressure / density))'], {}), '(gamma * (pressure / density))\n', (79, 109), False, 'import math\n')] |
import logging
import click
import obelisk
from pathlib import Path
logger = logging.getLogger(__name__)
@click.command()
@click.option("-c", "--convert", is_flag=True,
help="convert file (currently the only mode)")
@click.option("-i", "--input", prompt="Input filepath: ",
help="Input f... | [
"logging.getLogger",
"click.option",
"click.command",
"obelisk.FileSplitter"
] | [((80, 107), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (97, 107), False, 'import logging\n'), ((111, 126), 'click.command', 'click.command', ([], {}), '()\n', (124, 126), False, 'import click\n'), ((128, 225), 'click.option', 'click.option', (['"""-c"""', '"""--convert"""'], {'is_fla... |
import datetime
from test_plus.test import TestCase
from qa_tool.tests.helpers import RelevancyScoreBuilder, AlgorithmBuilder, SearchLocationBuilder
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from human_services.services_at_location.test... | [
"newcomers_guide.tests.helpers.create_topic",
"common.testhelpers.random_test_values.a_string",
"qa_tool.tests.helpers.RelevancyScoreBuilder",
"rest_framework.test.APIClient",
"datetime.datetime.now",
"human_services.services_at_location.tests.helpers.ServiceAtLocationBuilder",
"qa_tool.tests.helpers.Se... | [((609, 645), 'rest_framework.authtoken.models.Token.objects.create', 'Token.objects.create', ([], {'user': 'self.user'}), '(user=self.user)\n', (629, 645), False, 'from rest_framework.authtoken.models import Token\n'), ((671, 682), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (680, 682), False, 'fro... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError)... | [
"os.path.dirname",
"codecs.open",
"setuptools.find_packages",
"pypandoc.convert"
] | [((182, 204), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (194, 204), False, 'from os import path\n'), ((255, 291), 'pypandoc.convert', 'pypandoc.convert', (['"""README.md"""', '"""rst"""'], {}), "('README.md', 'rst')\n", (271, 291), False, 'import pypandoc\n'), ((463, 478), 'setuptools.find_... |
import inspect
from typing import Callable, Generic, TypeVar, Type, Union
from allennlp.common.params import Params
T = TypeVar("T")
class Lazy(Generic[T]):
"""
This class is for use when constructing objects using `FromParams`, when an argument to a
constructor has a _sequential dependency_ with anoth... | [
"inspect.isclass",
"allennlp.common.params.Params",
"typing.TypeVar"
] | [((123, 135), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (130, 135), False, 'from typing import Callable, Generic, TypeVar, Type, Union\n'), ((1844, 1872), 'inspect.isclass', 'inspect.isclass', (['constructor'], {}), '(constructor)\n', (1859, 1872), False, 'import inspect\n'), ((1968, 1978), 'allennlp.c... |
# LICENSE
# Copyright (c) 2013-2016, <NAME> (<EMAIL>)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... | [
"csv.CsvDataset.from_arff_dataset",
"arff.ArffDataset",
"optparse.OptionParser"
] | [((2635, 2677), 'optparse.OptionParser', 'OptionParser', ([], {'usage': '"""%prog [options] file"""'}), "(usage='%prog [options] file')\n", (2647, 2677), False, 'from optparse import OptionParser\n'), ((3241, 3263), 'arff.ArffDataset', 'ArffDataset', (['arff_file'], {}), '(arff_file)\n', (3252, 3263), False, 'from arff... |
"""
Flask-Tinyclients
=================
Tiny clients for REST services.
"""
import os
import re
from setuptools import setup, find_packages
def fpath(name):
return os.path.join(os.path.dirname(__file__), name)
def read(fname):
return open(fpath(fname)).read()
init_str = read(fpath('flask_tinyclients/__ini... | [
"os.path.dirname",
"re.findall",
"setuptools.find_packages"
] | [((468, 493), 're.findall', 're.findall', (['pattern', 'file'], {}), '(pattern, file)\n', (478, 493), False, 'import re\n'), ((184, 209), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (199, 209), False, 'import os\n'), ((829, 861), 'setuptools.find_packages', 'find_packages', ([], {'exclude'... |
import re
from os import path
from functools import partial
from nanome.util import Logs
import nanome
from .AdvancedSettings import AdvancedSettings
from nanome.api.ui import Dropdown,DropdownItem
MENU_PATH = path.join(path.dirname(path.realpath(__file__)), "json/menus/advanced_settings.json")
class MDAdvancedSettin... | [
"nanome.ui.Menu.io.from_json",
"nanome.util.color.Color",
"nanome.ui.LayoutNode",
"os.path.realpath",
"functools.partial",
"re.sub",
"nanome.api.ui.DropdownItem"
] | [((234, 257), 'os.path.realpath', 'path.realpath', (['__file__'], {}), '(__file__)\n', (247, 257), False, 'from os import path\n'), ((468, 506), 'nanome.ui.Menu.io.from_json', 'nanome.ui.Menu.io.from_json', (['MENU_PATH'], {}), '(MENU_PATH)\n', (495, 506), False, 'import nanome\n'), ((6472, 6494), 'nanome.ui.LayoutNode... |
from __future__ import absolute_import
from rest_framework import status
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint, ProjectSettingPermission
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework.rule import RuleSerializer
from s... | [
"sentry.web.decorators.transaction_start",
"sentry.integrations.slack.tasks.find_channel_id_for_rule.apply_async",
"rest_framework.response.Response",
"sentry.mediators.project_rules.Updater.run",
"sentry.api.serializers.rest_framework.rule.RuleSerializer",
"sentry.models.Rule.objects.get",
"sentry.api.... | [((627, 674), 'sentry.web.decorators.transaction_start', 'transaction_start', (['"""ProjectRuleDetailsEndpoint"""'], {}), "('ProjectRuleDetailsEndpoint')\n", (644, 674), False, 'from sentry.web.decorators import transaction_start\n'), ((1043, 1090), 'sentry.web.decorators.transaction_start', 'transaction_start', (['"""... |
from math import nan
import pandas as pd
import re
import requests
from textblob import TextBlob # For sentiment analysis.
class NoResults(Exception):
pass
def url_encode(string: str):
"""Take a raw input string and URL encode it."""
replacements = {"!": "%21", "#": "%23", "$": "%24", "&": "%26", "'":... | [
"pandas.Series",
"textblob.TextBlob",
"requests.get",
"pandas.DataFrame",
"re.sub",
"re.findall",
"pandas.to_datetime"
] | [((1158, 1182), 're.findall', 're.findall', (['regex', 'tweet'], {}), '(regex, tweet)\n', (1168, 1182), False, 'import re\n'), ((6541, 6610), 'pandas.to_datetime', 'pd.to_datetime', (["df['created_at']"], {'format': '"""%a %b %d %H:%M:%S +0000 %Y"""'}), "(df['created_at'], format='%a %b %d %H:%M:%S +0000 %Y')\n", (6555... |
import pathlib
import tempfile
import cbor2
from retry import retry
from pycardano import *
from .base import TestBase
class TestMint(TestBase):
@retry(tries=4, delay=6, backoff=2, jitter=(1, 3))
def test_mint(self):
address = Address(self.payment_vkey.hash(), network=self.NETWORK)
# Load ... | [
"retry.retry",
"tempfile.TemporaryDirectory",
"pathlib.Path"
] | [((155, 204), 'retry.retry', 'retry', ([], {'tries': '(4)', 'delay': '(6)', 'backoff': '(2)', 'jitter': '(1, 3)'}), '(tries=4, delay=6, backoff=2, jitter=(1, 3))\n', (160, 204), False, 'from retry import retry\n'), ((6172, 6221), 'retry.retry', 'retry', ([], {'tries': '(4)', 'delay': '(6)', 'backoff': '(2)', 'jitter': ... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gwells.settings")
from django.core.management import execute_from_command_line
from django.conf import settings
if settings.DEBUG:
if os.environ.get('RUN_MAIN') or os.enviro... | [
"os.environ.setdefault",
"ptvsd.enable_attach",
"os.environ.get",
"django.core.management.execute_from_command_line"
] | [((75, 141), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""gwells.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'gwells.settings')\n", (96, 141), False, 'import os\n'), ((651, 686), 'django.core.management.execute_from_command_line', 'execute_from_command_line', (['sys.argv']... |
# -*- coding: utf-8 -*-
"""djangoflash.context_processors test cases.
"""
from unittest import TestCase
from django.core.exceptions import SuspiciousOperation
from django.http import HttpRequest
from djangoflash.context_processors import CONTEXT_VAR, flash
from djangoflash.models import FlashScope
class FlashCont... | [
"djangoflash.models.FlashScope",
"django.http.HttpRequest",
"djangoflash.context_processors.flash"
] | [((483, 496), 'django.http.HttpRequest', 'HttpRequest', ([], {}), '()\n', (494, 496), False, 'from django.http import HttpRequest\n'), ((518, 530), 'djangoflash.models.FlashScope', 'FlashScope', ([], {}), '()\n', (528, 530), False, 'from djangoflash.models import FlashScope\n'), ((736, 755), 'djangoflash.context_proces... |
def pytest_configure():
import os
os.environ.setdefault('SUPERTOKENS_ENV', 'testing')
os.environ.setdefault('SUPERTOKENS_PATH', '../supertokens-root')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.Django.settings')
| [
"os.environ.setdefault"
] | [((42, 93), 'os.environ.setdefault', 'os.environ.setdefault', (['"""SUPERTOKENS_ENV"""', '"""testing"""'], {}), "('SUPERTOKENS_ENV', 'testing')\n", (63, 93), False, 'import os\n'), ((98, 162), 'os.environ.setdefault', 'os.environ.setdefault', (['"""SUPERTOKENS_PATH"""', '"""../supertokens-root"""'], {}), "('SUPERTOKENS... |
import collections
import gzip
import itertools
import os
import torch
import torchtext
import onmt.inputters
class SortedCounter(collections.Counter):
"""A Counter, with most_common replaced with a version
that sorts results by count and key, rather than just count.
The keys (counted elements) must be so... | [
"os.path.exists",
"os.makedirs",
"torch.load",
"os.path.join",
"torch.save"
] | [((5504, 5589), 'os.path.join', 'os.path.join', (["data_config['meta']['shard']['rootdir']", '"""transforms"""', 'segmentation'], {}), "(data_config['meta']['shard']['rootdir'], 'transforms',\n segmentation)\n", (5516, 5589), False, 'import os\n'), ((5607, 5643), 'os.makedirs', 'os.makedirs', (['vocabdir'], {'exist_... |
import os
import pathlib
import platform
import requests
import shutil
from zipfile import ZipFile
from PySide2 import QtCore
from PySide2 import QtWidgets
from github import Github
from github import Repository
from github import GithubException
from simple_installer import Logger
class Installer(QtCore.QObject):
... | [
"github.Github",
"pathlib.Path",
"os.getenv",
"zipfile.ZipFile",
"PySide2.QtWidgets.QMessageBox.question",
"PySide2.QtCore.Signal",
"requests.get",
"simple_installer.Logger.exception",
"platform.system",
"shutil.rmtree",
"simple_installer.Logger.info"
] | [((355, 370), 'PySide2.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (368, 370), False, 'from PySide2 import QtCore\n'), ((397, 412), 'PySide2.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (410, 412), False, 'from PySide2 import QtCore\n'), ((441, 456), 'PySide2.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\... |
# author: delta1037
# Date: 2022/01/11
# mail:<EMAIL>
import logging
import NotionDump
from NotionDump.Dump.database import Database
from NotionDump.Dump.dump import Dump
from NotionDump.Notion.Notion import NotionQuery
from NotionDump.utils import common_op
TOKEN_TEST = "<KEY>"
DB_TABLE_INLINE_ID = "3b40cf6b60fc49e... | [
"NotionDump.Dump.database.Database",
"NotionDump.Notion.Notion.NotionQuery",
"logging.exception",
"NotionDump.utils.common_op.save_json_to_file",
"NotionDump.Dump.dump.Dump"
] | [((491, 581), 'NotionDump.Dump.database.Database', 'Database', ([], {'database_id': 'DB_TABLE_INLINE_ID', 'query_handle': 'query', 'export_child_pages': '(False)'}), '(database_id=DB_TABLE_INLINE_ID, query_handle=query,\n export_child_pages=False)\n', (499, 581), False, 'from NotionDump.Dump.database import Database... |
import utils.envs as env
import json
import collections
class Extractor:
"""Extracts attributes for mobile from title."""
def __init__(self):
self.profiles = self.load_profiles()
self.bahasa_colors = self.load_bahasa_colors()
def extract_from_title(self, title):
"""Return high-pr... | [
"collections.OrderedDict"
] | [((9070, 9095), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (9093, 9095), False, 'import collections\n')] |
import matplotlib.pyplot as plt
from random import random
def display_result(vectors, clusters):
colors = [[random() for _ in range(3)] for _ in range(len(clusters))]
centroids_colors = [[1-x for x in color] for color in colors]
for cluster_index, (centroid, cluster) in enumerate(clusters.items()):
... | [
"random.random",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.show"
] | [((791, 801), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (799, 801), True, 'import matplotlib.pyplot as plt\n'), ((640, 696), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xs', 'ys'], {'c': 'colors[cluster_index]', 'marker': '"""."""'}), "(xs, ys, c=colors[cluster_index], marker='.')\n", (651, 696), True,... |
#!/usr/bin/env python3
""" Generate a "loading" or "waiting" animated gif. """
import math
import PIL.Image
import PIL.ImageDraw
SIZE = 16
TOTAL_DOTS = 8
VISUAL_DOTS = 4 # how many dots are visible in each frame.
DIAMETER = SIZE / 8.0
SECONDS = 1.25 # how long it takes to do a complete cycle.
OUTPUT = "loading.gi... | [
"math.cos",
"math.sin"
] | [((464, 502), 'math.sin', 'math.sin', (['(i / TOTAL_DOTS * 2 * math.pi)'], {}), '(i / TOTAL_DOTS * 2 * math.pi)\n', (472, 502), False, 'import math\n'), ((516, 554), 'math.cos', 'math.cos', (['(i / TOTAL_DOTS * 2 * math.pi)'], {}), '(i / TOTAL_DOTS * 2 * math.pi)\n', (524, 554), False, 'import math\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.colors
from pycocotools.coco import COCO
import numpy as np
import skimage.io as sio
from tqdm import tqdm
from PIL import Image
filecoco = "annotations_coco.json"
coco = COCO(filecoco)
catIDs = coco.getCatIds()
cats = coc... | [
"PIL.Image.fromarray",
"matplotlib.pyplot.imsave",
"tqdm.tqdm",
"pycocotools.coco.COCO",
"numpy.zeros"
] | [((268, 282), 'pycocotools.coco.COCO', 'COCO', (['filecoco'], {}), '(filecoco)\n', (272, 282), False, 'from pycocotools.coco import COCO\n'), ((1723, 1735), 'tqdm.tqdm', 'tqdm', (['imgIds'], {}), '(imgIds)\n', (1727, 1735), False, 'from tqdm import tqdm\n'), ((844, 883), 'numpy.zeros', 'np.zeros', (["(img['height'], im... |
from dataclasses import dataclass
import numpy as np
@dataclass(unsafe_hash=True)
class Fraction:
_numerator: int # Numerator
_denominator: int # Denomenator
def __init__(self, numerator, denominator):
self._numerator = numerator
self._denominator = denominator
gcd = np.g... | [
"numpy.gcd",
"dataclasses.dataclass"
] | [((56, 83), 'dataclasses.dataclass', 'dataclass', ([], {'unsafe_hash': '(True)'}), '(unsafe_hash=True)\n', (65, 83), False, 'from dataclasses import dataclass\n'), ((316, 346), 'numpy.gcd', 'np.gcd', (['numerator', 'denominator'], {}), '(numerator, denominator)\n', (322, 346), True, 'import numpy as np\n'), ((707, 748)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import yaml
import json
import urllib2
import csv
import re
with open('./config', 'r') as config_yaml:
config = yaml.load(config_yaml)
def update_output(docid, sentid, minerals, ages, locations, lemma):
output.append({
"doc... | [
"csv.DictWriter",
"re.sub",
"urllib2.urlopen",
"yaml.load"
] | [((196, 218), 'yaml.load', 'yaml.load', (['config_yaml'], {}), '(config_yaml)\n', (205, 218), False, 'import yaml\n'), ((5555, 5652), 'csv.DictWriter', 'csv.DictWriter', (['out'], {'fieldnames': "['docid', 'sentid', 'minerals', 'ages', 'locations', 'lemma']"}), "(out, fieldnames=['docid', 'sentid', 'minerals', 'ages',\... |
# -*- coding: utf-8 -*-
"""Generate data for examples"""
# author: <NAME>, <NAME>, Duke University; <NAME>, <NAME>
# Copyright Duke University 2020
# License: MIT
import pandas as pd
import numpy as np
def generate_uniform_given_importance(num_control=1000, num_treated=1000,
num... | [
"numpy.random.normal",
"numpy.array",
"numpy.dot",
"numpy.random.randint",
"pandas.concat",
"numpy.random.binomial"
] | [((578, 642), 'numpy.random.randint', 'np.random.randint', (['min_val', 'max_val'], {'size': '(num_control, num_cov)'}), '(min_val, max_val, size=(num_control, num_cov))\n', (595, 642), True, 'import numpy as np\n'), ((653, 717), 'numpy.random.randint', 'np.random.randint', (['min_val', 'max_val'], {'size': '(num_treat... |
import time
from ginette.i2c import I2C
class SHT30(object):
def __init__(self, addr=0x45, bus=1):
self.addr = addr
def get_temp_and_humid(self):
with I2C() as bus:
# SHT30 address, 0x44(68)
# Send measurement command, 0x2C(44)
# 0x06(06) High rep... | [
"ginette.i2c.I2C",
"time.sleep"
] | [((179, 184), 'ginette.i2c.I2C', 'I2C', ([], {}), '()\n', (182, 184), False, 'from ginette.i2c import I2C\n'), ((418, 433), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (428, 433), False, 'import time\n')] |
import pytest
from mock import patch
from backend.query_server import QueryServer
@pytest.fixture
def query_server(fake_queue_name, mock_pokedex):
yield QueryServer(fake_queue_name, mock_pokedex)
@pytest.fixture
def mock_query_server_publish():
with patch(
"backend.query_server.QueryServer._publish"... | [
"pytest.mark.parametrize",
"backend.query_server.QueryServer",
"mock.patch"
] | [((751, 2509), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""q_type, arg, expected_call, accepted, expected"""', "[('ID', '', None, False, []), ('ID', ' ', None, False, []), ('ID', 'a', 'a',\n True, {'a': '123'}), ('ID', ' a', 'a', True, {'a': '123'}), ('ID',\n ' a ', 'a', True, {'a': '123'}), ('ID'... |
import numpy
from scipy import integrate
def create_state_mtx(state, nx, ny, nz, dof):
state_mtx = numpy.zeros([nx, ny, nz, dof])
for k in range(nz):
for j in range(ny):
for i in range(nx):
for d in range(dof):
state_mtx[i, j, k, d] = state[d + i * dof +... | [
"scipy.integrate.cumtrapz",
"numpy.tanh",
"numpy.zeros",
"numpy.meshgrid",
"numpy.arange"
] | [((105, 135), 'numpy.zeros', 'numpy.zeros', (['[nx, ny, nz, dof]'], {}), '([nx, ny, nz, dof])\n', (116, 135), False, 'import numpy\n'), ((439, 470), 'numpy.zeros', 'numpy.zeros', (['(nx * ny * nz * dof)'], {}), '(nx * ny * nz * dof)\n', (450, 470), False, 'import numpy\n'), ((1224, 1244), 'numpy.meshgrid', 'numpy.meshg... |
import sys
from typing import Any, Optional, Iterable
from httpie.cookies import HTTPieCookiePolicy
from http import cookiejar # noqa
# Request does not carry the original policy attached to the
# cookie jar, so until it is resolved we change the global cookie
# policy. <https://github.com/psf/requests/issues/5449>
... | [
"importlib_metadata.metadata"
] | [((3345, 3381), 'importlib_metadata.metadata', 'importlib_metadata.metadata', (['package'], {}), '(package)\n', (3372, 3381), False, 'import importlib_metadata\n')] |
from __future__ import unicode_literals
import os
import appdirs
from reviewbot.config import config
from reviewbot.utils.api import get_api_root
from reviewbot.utils.filesystem import make_tempdir
from reviewbot.utils.log import get_logger
from reviewbot.utils.process import execute
logger = get_logger(__name__)
... | [
"reviewbot.utils.filesystem.make_tempdir",
"os.path.exists",
"os.makedirs",
"reviewbot.utils.log.get_logger",
"appdirs.site_data_dir",
"reviewbot.utils.api.get_api_root",
"reviewbot.utils.process.execute"
] | [((299, 319), 'reviewbot.utils.log.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (309, 319), False, 'from reviewbot.utils.log import get_logger\n'), ((4801, 4854), 'reviewbot.utils.api.get_api_root', 'get_api_root', ([], {'url': 'url', 'username': 'user', 'api_token': 'token'}), '(url=url, username=use... |
#!/usr/bin/env python3
import itertools as it
import random
import sys
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import numpy as np
import seaborn as sns
params = {
"axes.labelsize" : 16,
"xtick.labelsize" : 12,
"ytick.labelsize" : 12,
"text.usetex" : True,
"font.family... | [
"numpy.product",
"numpy.random.shuffle",
"numpy.ones",
"numpy.square",
"numpy.array_split",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"matplotlib.ticker.MaxNLocator",
"numpy.random.seed",
"itertools.combinations_with_replacement",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show... | [((1780, 1805), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (1794, 1805), True, 'import numpy as np\n'), ((2088, 2112), 'numpy.random.shuffle', 'np.random.shuffle', (['index'], {}), '(index)\n', (2105, 2112), True, 'import numpy as np\n'), ((3182, 3209), 'matplotlib.pyplot.rcParams.u... |
#!/usr/bin/env python2
'''
Unit tests for oc route
'''
# To run:
# ./oc_serviceaccount.py
#
# .
# Ran 1 test in 0.002s
#
# OK
import os
import sys
import unittest
import mock
# Removing invalid variable names for tests so that I can
# keep them brief
# pylint: disable=invalid-name,no-name-in-module
# Disable import-... | [
"sys.path.insert",
"mock.patch",
"oc_route.OCRoute.run_ansible",
"os.path.realpath",
"unittest.main",
"mock.call"
] | [((561, 592), 'sys.path.insert', 'sys.path.insert', (['(0)', 'module_path'], {}), '(0, module_path)\n', (576, 592), False, 'import sys\n'), ((849, 884), 'mock.patch', 'mock.patch', (['"""oc_route.OCRoute._run"""'], {}), "('oc_route.OCRoute._run')\n", (859, 884), False, 'import mock\n'), ((3879, 3914), 'mock.patch', 'mo... |
from torch.utils.data import Dataset
from PIL import Image
import os
import glob
from torchvision import transforms
class GanDataset(Dataset):
def __init__(self, data_folder, from_style, to_style, image_size):
self.data_folder = data_folder
self.image_size = image_size
if not os.path.exis... | [
"os.path.exists",
"PIL.Image.open",
"os.path.join",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor"
] | [((308, 335), 'os.path.exists', 'os.path.exists', (['data_folder'], {}), '(data_folder)\n', (322, 335), False, 'import os\n'), ((444, 493), 'os.path.join', 'os.path.join', (['data_folder', 'f"""{from_style}"""', '"""*.*"""'], {}), "(data_folder, f'{from_style}', '*.*')\n", (456, 493), False, 'import os\n'), ((536, 583)... |
import random
import string
from itertools import starmap
import discord
from discord.ext import commands
from ..utils.formats import escape_markdown
_prefixes = list(set(string.punctuation) - {'@', '#'})
class Prefix(commands.Converter):
async def convert(self, ctx, argument):
if not argument:
... | [
"discord.ext.commands.has_permissions",
"random.choice",
"discord.ext.commands.group",
"discord.ext.commands.BadArgument",
"discord.Embed"
] | [((969, 1034), 'discord.ext.commands.group', 'commands.group', ([], {'aliases': "['prefixes']", 'invoke_without_command': '(True)'}), "(aliases=['prefixes'], invoke_without_command=True)\n", (983, 1034), False, 'from discord.ext import commands\n'), ((1707, 1750), 'discord.ext.commands.has_permissions', 'commands.has_p... |
# Copyright (C) 2019 Intel Corporation
#
# 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 wri... | [
"cv2.rectangle",
"logging.debug",
"math.floor",
"numpy.hstack",
"cv2.imshow",
"numpy.array",
"numpy.linalg.norm",
"numpy.histogram",
"cv2.minMaxLoc",
"numpy.vstack",
"cv2.matchTemplate",
"cv2.blur",
"numpy.abs",
"collections.namedtuple",
"numpy.amin",
"numpy.average",
"cv2.cvtColor",... | [((982, 1028), 'collections.namedtuple', 'namedtuple', (['"""Rect"""', "['tl_x', 'tl_y', 'w', 'h']"], {}), "('Rect', ['tl_x', 'tl_y', 'w', 'h'])\n", (992, 1028), False, 'from collections import namedtuple\n'), ((1037, 1068), 'collections.namedtuple', 'namedtuple', (['"""Point"""', "['x', 'y']"], {}), "('Point', ['x', '... |
from django.contrib import admin
from user_profile.models import UProfile
# Register your models here.
class UProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(UProfile, UProfileAdmin)
| [
"django.contrib.admin.site.register"
] | [((155, 199), 'django.contrib.admin.site.register', 'admin.site.register', (['UProfile', 'UProfileAdmin'], {}), '(UProfile, UProfileAdmin)\n', (174, 199), False, 'from django.contrib import admin\n')] |
'''
@author: <NAME>
@author: <NAME>
@maintainer: <NAME>
@contact: <EMAIL>, <EMAIL>
@date: 14.08.2015
@version: 1.2+
@copyright: Copyright (c) 2015-2017, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
@license : BSD-2-Clause
'''
import numpy as np
from .module import Module
# -------------------------------
# Sum Pooling lay... | [
"numpy.sqrt",
"numpy.zeros",
"numpy.zeros_like",
"numpy.ones"
] | [((3131, 3152), 'numpy.zeros_like', 'np.zeros_like', (['self.X'], {}), '(self.X)\n', (3144, 3152), True, 'import numpy as np\n'), ((3881, 3903), 'numpy.zeros', 'np.zeros', (['self.X.shape'], {}), '(self.X.shape)\n', (3889, 3903), True, 'import numpy as np\n'), ((4871, 4908), 'numpy.zeros_like', 'np.zeros_like', (['self... |
#!/usr/bin/env python
#
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"pyxir.ops.input",
"pyxir.ops.conv2d",
"pyxir.ops.constant",
"numpy.array",
"pyxir.graph.xgraph_factory.XGraphFactory",
"unittest.main",
"pyxir.runtime.decentq_sim.runtime_decentq_sim.RuntimeDecentQSim"
] | [((1976, 1991), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1989, 1991), False, 'import unittest\n'), ((1139, 1174), 'pyxir.ops.input', 'px.ops.input', (['"""input"""', '[1, 1, 4, 4]'], {}), "('input', [1, 1, 4, 4])\n", (1151, 1174), True, 'import pyxir as px\n'), ((1187, 1215), 'pyxir.ops.constant', 'px.ops.c... |
"""Models for secret pages application."""
from django.db import models
from django.conf import settings
from django.template.loader import get_template, TemplateDoesNotExist
from django.core.exceptions import ValidationError
TEMPLATE_EXTENSION = '.html'
class SecretPage(models.Model):
"""Model for a secret pag... | [
"django.db.models.BooleanField",
"django.conf.settings.SECRET_PAGES_TEMPLATE_TEMPLATE.format",
"django.db.models.SlugField",
"django.db.models.CharField",
"django.template.loader.get_template"
] | [((338, 383), 'django.db.models.CharField', 'models.CharField', ([], {'unique': '(True)', 'max_length': '(150)'}), '(unique=True, max_length=150)\n', (354, 383), False, 'from django.db import models\n'), ((418, 447), 'django.db.models.SlugField', 'models.SlugField', ([], {'unique': '(True)'}), '(unique=True)\n', (434, ... |