code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from __future__ import print_function
import tensorflow as tf
import keras
from tensorflow.keras.models import load_model
from keras import backend as K
from keras.layers import Input
import numpy as np
import subprocess
from tensorloader import TensorLoader as tl
import matplotlib.pyplot as plt
from matplotlib.backend... | [
"argparse.ArgumentParser",
"tensorloader.TensorLoader.readTensors",
"tensorloader.TensorLoader.getSeqSigTensor",
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"numpy.concatenate",
"numpy.moveaxis",
"time.time",
"tensorloader.TensorLoader.getPEASFeatures"
] | [((632, 696), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""CoRE-ATAC Prediction Tool"""'}), "(description='CoRE-ATAC Prediction Tool')\n", (655, 696), False, 'import argparse\n'), ((1478, 1495), 'tensorflow.keras.models.load_model', 'load_model', (['model'], {}), '(model)\n', (1488, 14... |
# Generated by Django 2.2.16 on 2020-12-11 12:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('survey', '0001_initial'),
]
operations = [
migrations.AddField(
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((397, 483), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(15)', 'null': '(True)', 'verbose_name': '"""IP Address"""'}), "(blank=True, max_length=15, null=True, verbose_name=\n 'IP Address')\n", (413, 483), False, 'from django.db import migrations, models\n'), ((606, 693... |
from opentera.db.Base import db, BaseModel
from enum import Enum
import random
from datetime import datetime, timedelta
import uuid
class TeraSessionStatus(Enum):
STATUS_NOTSTARTED = 0
STATUS_INPROGRESS = 1
STATUS_COMPLETED = 2
STATUS_CANCELLED = 3
STATUS_TERMINATED = 4
class TeraSession(db.Mod... | [
"opentera.db.Base.db.session.commit",
"random.randint",
"opentera.db.Base.db.Column",
"opentera.db.models.TeraParticipant.TeraParticipant.get_participant_by_id",
"opentera.db.Base.db.String",
"opentera.db.Base.db.TIMESTAMP",
"opentera.db.Base.db.Sequence",
"opentera.db.models.TeraUser.TeraUser.get_use... | [((1151, 1187), 'opentera.db.Base.db.Column', 'db.Column', (['db.String'], {'nullable': '(False)'}), '(db.String, nullable=False)\n', (1160, 1187), False, 'from opentera.db.Base import db, BaseModel\n'), ((1295, 1343), 'opentera.db.Base.db.Column', 'db.Column', (['db.Integer'], {'nullable': '(False)', 'default': '(0)'}... |
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['LuongAttention', 'BahdanauAttention']
class LuongAttention(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
self.attention = nn.Linear(hidden_size * 2, hidden_size)... | [
"torch.tanh",
"torch.nn.functional.softmax",
"torch.tensor",
"torch.sum",
"torch.nn.Linear",
"torch.FloatTensor",
"torch.rand"
] | [((281, 320), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size * 2)', 'hidden_size'], {}), '(hidden_size * 2, hidden_size)\n', (290, 320), True, 'import torch.nn as nn\n'), ((408, 447), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size * 2)', 'hidden_size'], {}), '(hidden_size * 2, hidden_size)\n', (417, 447), True, 'impo... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.minard_troops import minard_troops
def test_minard_troops():
"""Test module minard_troops.py by downloading
minard_troops.csv and testing sha... | [
"observations.r.minard_troops.minard_troops",
"tempfile.mkdtemp",
"shutil.rmtree"
] | [((390, 408), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (406, 408), False, 'import tempfile\n'), ((431, 455), 'observations.r.minard_troops.minard_troops', 'minard_troops', (['test_path'], {}), '(test_path)\n', (444, 455), False, 'from observations.r.minard_troops import minard_troops\n'), ((513, 537), ... |
import sys
from decorator import decorator
from fabric.api import env, hide, parallel, run, settings
from fabric.tasks import execute
env.shell = '/bin/bash -l -c -o pipefail'
env.keepalive = 60
env.timeout = 60
def parallel_task(server_side=True):
@decorator
def _parallel_task(task, *args, **kargs):
... | [
"fabric.api.run",
"fabric.api.hide",
"fabric.api.settings",
"sys.exit",
"fabric.api.parallel"
] | [((455, 519), 'fabric.api.settings', 'settings', ([], {'user': 'self.user', 'password': 'self.password', 'warn_only': '(True)'}), '(user=self.user, password=self.password, warn_only=True)\n', (463, 519), False, 'from fabric.api import env, hide, parallel, run, settings\n'), ((979, 999), 'fabric.api.run', 'run', (['*arg... |
#!/usr/bin/env python
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from tweetbot import tweet_config
from argparse import ArgumentParser
def test_parse_arguments():
# set test config file to use
test_config_file = 'tests/test_files/test_... | [
"tweetbot.tweet_config.tweet_config"
] | [((379, 434), 'tweetbot.tweet_config.tweet_config', 'tweet_config.tweet_config', ([], {'config_file': 'test_config_file'}), '(config_file=test_config_file)\n', (404, 434), False, 'from tweetbot import tweet_config\n'), ((557, 584), 'tweetbot.tweet_config.tweet_config', 'tweet_config.tweet_config', ([], {}), '()\n', (58... |
import os
import shutil
from PIL import Image
import imageio
from sanic.response import file
from core.gif import hackGif
from core.tool import checkSuffix
# 拉伸处理图片函数
def fillImg(suffix, imgPath, thumbPath, ow, oh):
image = Image.open(imgPath)
thumb = image.resize((ow, oh), Image.ANTIALIAS)
thumb.save(thu... | [
"PIL.Image.open",
"sanic.response.file",
"PIL.Image.new",
"core.tool.checkSuffix",
"shutil.rmtree",
"imageio.imread",
"imageio.mimsave"
] | [((230, 249), 'PIL.Image.open', 'Image.open', (['imgPath'], {}), '(imgPath)\n', (240, 249), False, 'from PIL import Image\n'), ((422, 441), 'PIL.Image.open', 'Image.open', (['imgPath'], {}), '(imgPath)\n', (432, 441), False, 'from PIL import Image\n'), ((982, 1001), 'PIL.Image.open', 'Image.open', (['imgPath'], {}), '(... |
from argparse import ArgumentParser
from burplist.utils.misc import remove_stale_products_prices
from scrapy.commands import ScrapyCommand
class Command(ScrapyCommand):
requires_project = False
default_settings = {'LOG_ENABLED': True}
def syntax(self) -> str:
return '[options]'
def short_de... | [
"burplist.utils.misc.remove_stale_products_prices",
"scrapy.commands.ScrapyCommand.add_options"
] | [((498, 537), 'scrapy.commands.ScrapyCommand.add_options', 'ScrapyCommand.add_options', (['self', 'parser'], {}), '(self, parser)\n', (523, 537), False, 'from scrapy.commands import ScrapyCommand\n'), ((798, 837), 'burplist.utils.misc.remove_stale_products_prices', 'remove_stale_products_prices', (['opts.days'], {}), '... |
from __future__ import absolute_import
from django.db import models
from django.utils.translation import ugettext_lazy
from smsgateway.enums import (OPERATOR_CHOICES, OPERATOR_UNKNOWN, GATEWAY_CHOICES, DIRECTION_CHOICES, DIRECTION_INBOUND,
PRIORITIES, PRIORITY_MEDIUM, PRIORITY_DEFERRED)
... | [
"django.db.models.DateTimeField",
"django.utils.translation.ugettext_lazy",
"django.db.models.CharField"
] | [((2265, 2307), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'datetime.now'}), '(default=datetime.now)\n', (2285, 2307), False, 'from django.db import models\n'), ((2519, 2594), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(1)', 'choices': 'PRIORITIES', 'default':... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | [
"ducktape.utils.util.wait_until",
"kafkatest.services.verifiable_consumer.VerifiableConsumer",
"kafkatest.services.kafka.TopicPartition",
"ducktape.mark.matrix",
"kafkatest.services.verifiable_producer.VerifiableProducer"
] | [((7887, 7955), 'ducktape.mark.matrix', 'matrix', ([], {'clean_shutdown': '[True, False]', 'bounce_mode': "['all', 'rolling']"}), "(clean_shutdown=[True, False], bounce_mode=['all', 'rolling'])\n", (7893, 7955), False, 'from ducktape.mark import matrix\n'), ((9862, 9931), 'ducktape.mark.matrix', 'matrix', ([], {'clean_... |
import bodo
import pandas as pd
@bodo.jit(distributed=['vec'])
def add(vec, scalar):
return bodo.gatherv(vec + (scalar * 10))
def main():
ix = bodo.get_rank() + 1
data = None
new_data = None
new_data_t = None
if ix == 1:
data = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6], 3: [7, 8, 9]... | [
"pandas.DataFrame",
"bodo.barrier",
"bodo.jit",
"bodo.get_rank",
"bodo.scatterv",
"bodo.gatherv"
] | [((35, 64), 'bodo.jit', 'bodo.jit', ([], {'distributed': "['vec']"}), "(distributed=['vec'])\n", (43, 64), False, 'import bodo\n'), ((98, 129), 'bodo.gatherv', 'bodo.gatherv', (['(vec + scalar * 10)'], {}), '(vec + scalar * 10)\n', (110, 129), False, 'import bodo\n'), ((562, 581), 'bodo.scatterv', 'bodo.scatterv', (['d... |
import time
import cv2
import numpy as np
from numba import njit
from scipy.ndimage import correlate
from sklearn.linear_model import Ridge
def compute_image_grads(image):
kernel_hor = np.array([-1, 0, 1], dtype=np.float32).reshape(1, 3)
kernel_ver = kernel_hor.T
grad_hor = correlate(image.astype(... | [
"numpy.reshape",
"numpy.sqrt",
"numpy.argpartition",
"sklearn.linear_model.Ridge",
"numpy.square",
"numpy.exp",
"numpy.array",
"numpy.maximum",
"time.time"
] | [((425, 455), 'numpy.maximum', 'np.maximum', (['grad_hor', 'grad_ver'], {}), '(grad_hor, grad_ver)\n', (435, 455), True, 'import numpy as np\n'), ((568, 633), 'numpy.array', 'np.array', (['[[1, -2, 1], [-2, 4, -2], [1, -2, 1]]'], {'dtype': 'np.float32'}), '([[1, -2, 1], [-2, 4, -2], [1, -2, 1]], dtype=np.float32)\n', (... |
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import QuantumCircuit
def get_example_circuit():
# initialize
qreg = QuantumRegister(8, name='q')
creg = ClassicalRegister(8)
init = QuantumCircuit(qreg, creg)
# create equal superposition
init.h(0)
init.h(... | [
"qiskit.QuantumCircuit",
"qiskit.QuantumRegister",
"qiskit.ClassicalRegister"
] | [((163, 191), 'qiskit.QuantumRegister', 'QuantumRegister', (['(8)'], {'name': '"""q"""'}), "(8, name='q')\n", (178, 191), False, 'from qiskit import QuantumRegister\n'), ((203, 223), 'qiskit.ClassicalRegister', 'ClassicalRegister', (['(8)'], {}), '(8)\n', (220, 223), False, 'from qiskit import ClassicalRegister\n'), ((... |
from tqdm import tqdm
import torch as tc
import pdb
import os , sys
import math
import fitlog
import re
from utils.scorer import get_f1
from utils.train_util import pad_sents , get_data_from_batch
from utils.write_keyfile import write_keyfile
def before_test(C , logger , dataset , models):
if isinstance(models , tc... | [
"torch.no_grad",
"utils.write_keyfile.write_keyfile",
"os.makedirs",
"torch.device"
] | [((425, 444), 'torch.device', 'tc.device', (['C.device'], {}), '(C.device)\n', (434, 444), True, 'import torch as tc\n'), ((1323, 1358), 'utils.write_keyfile.write_keyfile', 'write_keyfile', (['test_data', 'generator'], {}), '(test_data, generator)\n', (1336, 1358), False, 'from utils.write_keyfile import write_keyfile... |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class GroupDetail(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | [
"six.iteritems"
] | [((13782, 13815), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (13795, 13815), False, 'import six\n')] |
import itertools
sequence_array = []
def recaman(a:int):
if a == 0:
sequence_array.append(a)
elif a > 0 and sequence_array[a-1]-a>0 and sequence_array[a-1]-a not in sequence_array:
sequence_array.append(sequence_array[a-1]-a)
else:
sequence_array.append(sequence_array[a-1]+a)
... | [
"itertools.islice"
] | [((574, 608), 'itertools.islice', 'itertools.islice', (['gen', 'index', 'None'], {}), '(gen, index, None)\n', (590, 608), False, 'import itertools\n')] |
from django.contrib import admin
from reversion.admin import VersionAdmin
from django.contrib.flatpages.admin import FlatPage, FlatPageAdmin
from .models import HostedPicture
admin.site.unregister(FlatPage)
@admin.register(FlatPage)
class FlatPageVersionedAdmin(VersionAdmin, FlatPageAdmin):
pass
@admin.regist... | [
"django.contrib.admin.site.unregister",
"django.contrib.admin.register"
] | [((177, 208), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['FlatPage'], {}), '(FlatPage)\n', (198, 208), False, 'from django.contrib import admin\n'), ((212, 236), 'django.contrib.admin.register', 'admin.register', (['FlatPage'], {}), '(FlatPage)\n', (226, 236), False, 'from django.contrib import ... |
import logging
import sys
# Handles loading/unloading command modules. ###
class CmdHandler:
def __init__(self, irc):
self.log = logging.getLogger('pyTwitchbot.modHandler')
self.irc = irc
self.commands = {}
self.privcmds = {}
self.hooks = {}
self.modules = {}
... | [
"logging.getLogger",
"sys.modules.pop"
] | [((145, 188), 'logging.getLogger', 'logging.getLogger', (['"""pyTwitchbot.modHandler"""'], {}), "('pyTwitchbot.modHandler')\n", (162, 188), False, 'import logging\n'), ((4580, 4625), 'sys.modules.pop', 'sys.modules.pop', (["('modules.cmds.cmd_' + module)"], {}), "('modules.cmds.cmd_' + module)\n", (4595, 4625), False, ... |
import unittest
import subprocess
class TestPapermill(unittest.TestCase):
def test_papermill(self):
result = subprocess.run([
'papermill',
'/input/tests/data/notebook.ipynb',
'-',
], stdout=subprocess.PIPE)
self.assertEqual(0, result.returncode)
... | [
"subprocess.run"
] | [((123, 221), 'subprocess.run', 'subprocess.run', (["['papermill', '/input/tests/data/notebook.ipynb', '-']"], {'stdout': 'subprocess.PIPE'}), "(['papermill', '/input/tests/data/notebook.ipynb', '-'],\n stdout=subprocess.PIPE)\n", (137, 221), False, 'import subprocess\n')] |
# from expenses.models import *
from expenses.serializers import *
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
from dj... | [
"django.db.models.Q"
] | [((642, 654), 'django.db.models.Q', 'Q', ([], {'user': 'None'}), '(user=None)\n', (643, 654), False, 'from django.db.models import Q\n'), ((657, 682), 'django.db.models.Q', 'Q', ([], {'user': 'self.request.user'}), '(user=self.request.user)\n', (658, 682), False, 'from django.db.models import Q\n'), ((1047, 1085), 'dja... |
"""
Met Grid
--------
Grids for meterological stuff
"""
import os
import numpy as np
from multigrids import TemporalGrid, common
# try:
from atm.tools import stack_rasters
# except ImportError:
# from ..tools import stack_rasters
class MetGridShapeError(Exception):
"""Raised if data shape is not corr... | [
"numpy.memmap",
"os.path.join"
] | [((608, 646), 'numpy.memmap', 'np.memmap', (['args[3]'], {'dtype': 'dt', 'mode': '"""r"""'}), "(args[3], dtype=dt, mode='r')\n", (617, 646), True, 'import numpy as np\n'), ((2028, 2076), 'os.path.join', 'os.path.join', (['path', "(filename_start + '_fdd.yaml')"], {}), "(path, filename_start + '_fdd.yaml')\n", (2040, 20... |
import numpy as np
import pandas as pd
def dummyColumns(X: pd.DataFrame) -> pd.DataFrame:
"""
Transform categorical columns adding dummy columns with 0, 1 values
Args:
X (pd.DataFrame): input pandas dataframe.
Returns:
X (TYPE): output dataframe with dummy variables.
"""
# ... | [
"pandas.get_dummies",
"pandas.concat"
] | [((500, 525), 'pandas.get_dummies', 'pd.get_dummies', (['X[column]'], {}), '(X[column])\n', (514, 525), True, 'import pandas as pd\n'), ((550, 583), 'pandas.concat', 'pd.concat', (['[X, dummyCols]'], {'axis': '(1)'}), '([X, dummyCols], axis=1)\n', (559, 583), True, 'import pandas as pd\n')] |
# -*- coding: utf-8 -*-
# dcf
# ---
# A Python library for generating discounted cashflows.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.5, copyright Sunday, 21 November 2021
# Website: https://github.com/sonntagsgesicht/dcf
# License: Apache License 2.0 (see LICENSE fil... | [
"math.exp",
"math.sqrt",
"math.log"
] | [((4290, 4305), 'math.exp', 'math.exp', (['log_y'], {}), '(log_y)\n', (4298, 4305), False, 'import math\n'), ((4722, 4738), 'math.exp', 'math.exp', (['(-log_y)'], {}), '(-log_y)\n', (4730, 4738), False, 'import math\n'), ((5153, 5168), 'math.exp', 'math.exp', (['log_y'], {}), '(log_y)\n', (5161, 5168), False, 'import m... |
"""A plot of the deltas for erosion between scenarios."""
import os
import sys
from pyiem.dep import read_env
from pyiem.util import logger, get_dbconn
from tqdm import tqdm
import numpy as np
LOG = logger()
def readfile(fn, lengths):
"""Our env reader."""
try:
df = read_env(fn)
except Exception... | [
"os.listdir",
"numpy.average",
"tqdm.tqdm",
"os.path.join",
"pyiem.util.get_dbconn",
"pyiem.util.logger",
"sys.exit",
"pyiem.dep.read_env"
] | [((201, 209), 'pyiem.util.logger', 'logger', ([], {}), '()\n', (207, 209), False, 'from pyiem.util import logger, get_dbconn\n'), ((698, 716), 'pyiem.util.get_dbconn', 'get_dbconn', (['"""idep"""'], {}), "('idep')\n", (708, 716), False, 'from pyiem.util import logger, get_dbconn\n'), ((1266, 1281), 'tqdm.tqdm', 'tqdm',... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def chatbot(request):
return render(request=request, template_name="chat.html")
| [
"django.shortcuts.render"
] | [((145, 195), 'django.shortcuts.render', 'render', ([], {'request': 'request', 'template_name': '"""chat.html"""'}), "(request=request, template_name='chat.html')\n", (151, 195), False, 'from django.shortcuts import render\n')] |
# Copyright (c) 2020 Microsoft Corporation. All rights reserved.
# Released under Apache 2.0 license as described in the file LICENSE.
# Authors: <NAME>
from learning.protos.Response_pb2 import Response, Prediction
from learning.model import GenericModel
import torch
import torch.nn as nn
import torch.optim as optim
... | [
"torch.nn.functional.softmax",
"torch.as_tensor",
"torch.nn.CrossEntropyLoss",
"learning.protos.Response_pb2.Prediction",
"torch.set_grad_enabled",
"learning.model.GenericModel",
"learning.protos.Response_pb2.Response"
] | [((700, 728), 'torch.as_tensor', 'torch.as_tensor', (['[choiceIdx]'], {}), '([choiceIdx])\n', (715, 728), False, 'import torch\n'), ((828, 854), 'learning.model.GenericModel', 'GenericModel', (["cfg['model']"], {}), "(cfg['model'])\n", (840, 854), False, 'from learning.model import GenericModel\n'), ((1339, 1360), 'tor... |
# Copyright 2018 Databricks, 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 or agreed to in writi... | [
"re.sub",
"os.path.join",
"pandas.read_csv"
] | [((1078, 1098), 'pandas.read_csv', 'pandas.read_csv', (['url'], {}), '(url)\n', (1093, 1098), False, 'import pandas\n'), ((2772, 2818), 'os.path.join', 'os.path.join', (['temp_folder_path', '"""diamonds.csv"""'], {}), "(temp_folder_path, 'diamonds.csv')\n", (2784, 2818), False, 'import os\n'), ((2993, 3045), 'os.path.j... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
In order to accomodate 100x100 flores performance tags,
we need to increase the size of metadata_json.
"""
from yoyo import step
__depend... | [
"yoyo.step"
] | [((427, 483), 'yoyo.step', 'step', (['"""ALTER TABLE scores MODIFY metadata_json LONGTEXT"""'], {}), "('ALTER TABLE scores MODIFY metadata_json LONGTEXT')\n", (431, 483), False, 'from yoyo import step\n')] |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as torchnn
import torch.optim as optim
import models.nn as nn
import models.cnn as cnn
import models.rnn as rnn
def test_nn(net):
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,... | [
"torch.max",
"torchvision.datasets.CIFAR10",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torchvision.transforms.ToTensor"
] | [((377, 473), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': '"""./data"""', 'train': '(False)', 'download': '(True)', 'transform': 'transform'}), "(root='./data', train=False, download=True,\n transform=transform)\n", (405, 473), False, 'import torchvision\n'), ((544, 629), 'torch.uti... |
import sys
import spotipy.util as util
def retrieve_or_request_token(username, scopes):
token = util.prompt_for_user_token(username, ' '.join(scopes))
if token:
print("Token retrieved for", username, "for the scopes of", ','.join(scopes))
return token
else:
print("Error: Can't get token for", userna... | [
"sys.exit"
] | [((328, 338), 'sys.exit', 'sys.exit', ([], {}), '()\n', (336, 338), False, 'import sys\n')] |
#%%
import pandas as pd
import numpy as np
#%%
# Load the File
df21 = pd.read_csv('data/Smashwords21/smashwords_april_2021.csv')
# %%
# check total rows vs. total UNIQUE links (expect some duplicates)
len(df21), len(df21.Link.unique())
#%%
# drop duplicates
df21 = df21.drop_duplicates('Link')
#%%
# Glance at high and... | [
"numpy.isinf",
"pandas.read_csv"
] | [((71, 129), 'pandas.read_csv', 'pd.read_csv', (['"""data/Smashwords21/smashwords_april_2021.csv"""'], {}), "('data/Smashwords21/smashwords_april_2021.csv')\n", (82, 129), True, 'import pandas as pd\n'), ((1554, 1569), 'numpy.isinf', 'np.isinf', (['words'], {}), '(words)\n', (1562, 1569), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 15:04:09 2019
@author: EMG
EPMA Microsegregation Analysis
"""
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import seaborn as sns
import matplotlib.pyplot as plt
import ... | [
"matplotlib.pyplot.ylabel",
"numpy.log",
"pandas.read_excel",
"statsmodels.api.OLS",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"prettytable.PrettyTable",
"statsmodels.api.add_constant",
"matplotlib.... | [((1001, 1024), 'pandas.read_excel', 'pd.read_excel', (['filename'], {}), '(filename)\n', (1014, 1024), True, 'import pandas as pd\n'), ((1902, 1933), 'matplotlib.pyplot.scatter', 'plt.scatter', (['Fe', 'Si'], {'label': '"""Si"""'}), "(Fe, Si, label='Si')\n", (1913, 1933), True, 'import matplotlib.pyplot as plt\n'), ((... |
######################################################################
#
# File: test/integration/__init__.py
#
# Copyright 2020 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
import os
def get_b2_au... | [
"os.environ.get"
] | [((356, 400), 'os.environ.get', 'os.environ.get', (['"""B2_TEST_APPLICATION_KEY_ID"""'], {}), "('B2_TEST_APPLICATION_KEY_ID')\n", (370, 400), False, 'import os\n'), ((526, 567), 'os.environ.get', 'os.environ.get', (['"""B2_TEST_APPLICATION_KEY"""'], {}), "('B2_TEST_APPLICATION_KEY')\n", (540, 567), False, 'import os\n'... |
"""Book related views."""
from django.views.generic import DetailView, ListView
from django.shortcuts import get_object_or_404
from BookClub.models import Book, BookReview, BookList, BookShelf
class BookDetailView(DetailView):
"""Render the details, reviews and actions for a book."""
model = Book
template... | [
"BookClub.models.Book.objects.get",
"BookClub.models.BookShelf.objects.filter",
"django.shortcuts.get_object_or_404",
"BookClub.models.BookReview.objects.filter",
"BookClub.models.BookList.objects.filter"
] | [((980, 1016), 'BookClub.models.BookReview.objects.filter', 'BookReview.objects.filter', ([], {'book': 'book'}), '(book=book)\n', (1005, 1016), False, 'from BookClub.models import Book, BookReview, BookList, BookShelf\n'), ((1731, 1766), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Book'], {'pk': 'book... |
# Generated by Django 3.2 on 2021-04-16 07:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='LogEntity',
fields=[
('id', models.BigAutoFie... | [
"django.db.models.GenericIPAddressField",
"django.db.models.IntegerField",
"django.db.models.SmallIntegerField",
"django.db.models.BigAutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((303, 399), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (322, 399), False, 'from django.db import migrations, m... |
import pandas as pd
import numpy as np
import time
import sys
import json
from jsmin import jsmin
from collections import Counter
import os.path
from xlrd.biffh import XLRDError
from aenum import IntEnum
import time
# set up logging (to console)
import logging
logger = logging.getLogger(__name__)
logger.setLevel(loggi... | [
"logging.getLogger",
"pandas.isnull",
"json.loads",
"logging.StreamHandler",
"logging.Formatter",
"time.strftime",
"pandas.to_numeric",
"pandas.read_excel",
"pandas.DataFrame",
"pandas.ExcelWriter",
"pandas.concat"
] | [((271, 298), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (288, 298), False, 'import logging\n'), ((342, 390), 'logging.Formatter', 'logging.Formatter', (['"""[%(levelname)s] %(message)s"""'], {}), "('[%(levelname)s] %(message)s')\n", (359, 390), False, 'import logging\n'), ((401, 441)... |
#!/usr/bin/env python
import sys
if __name__ == "__main__":
import processgddp
processgddp.main(sys.argv[1:])
| [
"processgddp.main"
] | [((88, 118), 'processgddp.main', 'processgddp.main', (['sys.argv[1:]'], {}), '(sys.argv[1:])\n', (104, 118), False, 'import processgddp\n')] |
'''
Created on Mar 21, 2013
@author: <NAME> <<EMAIL>>
███████████████████████████████████████████████████████████████████████████████
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding... | [
"logging.getLogger",
"collections.defaultdict"
] | [((1205, 1238), 'logging.getLogger', 'logging.getLogger', (['"""sfm.Explorer"""'], {}), "('sfm.Explorer')\n", (1222, 1238), False, 'import logging\n'), ((3851, 3880), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (3874, 3880), False, 'import collections\n')] |
# :coding: utf-8
# :copyright: Copyright (c) 2021 strack
"""Describe the distribution to distutils."""
# Import third-party modules
import os
from setuptools import find_packages
from setuptools import setup
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
README_PATH = os.path.join(ROOT_PATH, 'README.md')
r... | [
"os.path.realpath",
"setuptools.find_packages",
"os.path.join"
] | [((281, 317), 'os.path.join', 'os.path.join', (['ROOT_PATH', '"""README.md"""'], {}), "(ROOT_PATH, 'README.md')\n", (293, 317), False, 'import os\n'), ((239, 265), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (255, 265), False, 'import os\n'), ((901, 916), 'setuptools.find_packages', 'fin... |
# Generated by Django 2.1.7 on 2019-05-10 07:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('elections', '0048_presidentcandidatebiography'),
]
operations = [
migrations.CreateModel(
name=... | [
"django.db.models.EmailField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((5401, 5468), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Gimimo data"""'}), "(blank=True, null=True, verbose_name='Gimimo data')\n", (5417, 5468), False, 'from django.db import migrations, models\n'), ((5610, 5683), 'django.db.models.CharField', 'm... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
import sqlalchemy
import pandas as pd
import json
from sodapy import Socrata
from pprint import pprint
from sys import argv
# Connection strings
from db_connection import *
try:
SQLALCHEMY_DATABASE_URI = '%s+%s://%s:%s@%s:%s/%s' % (DB_TYPE, DB... | [
"pandas.read_sql_table",
"sqlalchemy.create_engine"
] | [((713, 803), 'sqlalchemy.create_engine', 'sqlalchemy.create_engine', (['SQLALCHEMY_DATABASE_URI'], {'pool_size': 'POOL_SIZE', 'max_overflow': '(0)'}), '(SQLALCHEMY_DATABASE_URI, pool_size=POOL_SIZE,\n max_overflow=0)\n', (737, 803), False, 'import sqlalchemy\n'), ((930, 966), 'pandas.read_sql_table', 'pd.read_sql_t... |
import os
import unittest
import tensorflow as tf
physical_devices = tf.config.list_physical_devices('GPU')
for device in physical_devices:
tf.config.experimental.set_memory_growth(device, True)
loader = unittest.TestLoader()
test_dir = os.path.join(__file__, "..", "PR_test")
suite = loader.discover(test_dir)
ru... | [
"tensorflow.config.experimental.set_memory_growth",
"os.path.join",
"tensorflow.config.list_physical_devices",
"unittest.TextTestRunner",
"unittest.TestLoader"
] | [((69, 107), 'tensorflow.config.list_physical_devices', 'tf.config.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (100, 107), True, 'import tensorflow as tf\n'), ((210, 231), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (229, 231), False, 'import unittest\n'), ((243, 282), 'os.path.join', ... |
from discord.ext import commands
import random
import discord
class jojo:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def jojo(self, context, member: discord.Member):
"""Give someone <NAME>!"""
author = context.message.author.mentio... | [
"random.choice",
"discord.ext.commands.command",
"discord.Colour.blue"
] | [((141, 176), 'discord.ext.commands.command', 'commands.command', ([], {'pass_context': '(True)'}), '(pass_context=True)\n', (157, 176), False, 'from discord.ext import commands\n'), ((624, 646), 'random.choice', 'random.choice', (['choices'], {}), '(choices)\n', (637, 646), False, 'import random\n'), ((729, 750), 'dis... |
from django.views.generic import TemplateView
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
import json
from .models import Coordinates, RouteRequest
from .openstreetmaps import main_as_function
#from django.contrib.... | [
"django.shortcuts.render",
"django.http.JsonResponse",
"json.dumps",
"django.shortcuts.redirect",
"django.utils.http.is_safe_url"
] | [((768, 799), 'json.dumps', 'json.dumps', (['list_of_coordinates'], {}), '(list_of_coordinates)\n', (778, 799), False, 'import json\n'), ((1103, 1161), 'django.shortcuts.render', 'render', (['request', '"""pages/home.html"""'], {'context': '{}', 'status': '(200)'}), "(request, 'pages/home.html', context={}, status=200)... |
# Copyright 2016 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 ag... | [
"unittest.main",
"six.moves.range",
"pyu2f.apdu.CommandApdu"
] | [((3151, 3166), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3164, 3166), False, 'import unittest\n'), ((1422, 1450), 'pyu2f.apdu.CommandApdu', 'apdu.CommandApdu', (['(0)', '(1)', '(3)', '(4)'], {}), '(0, 1, 3, 4)\n', (1438, 1450), False, 'from pyu2f import apdu\n'), ((1923, 1938), 'six.moves.range', 'range', (... |
"""Reddit rss process"""
import feedparser
import pytz
import redis
import re
from datetime import datetime
from dateutil import parser
from config import REDIS_URL
from utils.log_utils import error_log, info_log
REDDIT_URL_REGEX = '.*reddit.com/r/{}/.*'
class RedditRss:
"""
REDDIT RSS
... | [
"redis.from_url",
"dateutil.parser.parse",
"feedparser.parse",
"utils.log_utils.error_log",
"datetime.datetime.now",
"utils.log_utils.info_log"
] | [((384, 409), 'redis.from_url', 'redis.from_url', (['REDIS_URL'], {}), '(REDIS_URL)\n', (398, 409), False, 'import redis\n'), ((661, 690), 'utils.log_utils.info_log', 'info_log', (['"""reading rss"""', '(True)'], {}), "('reading rss', True)\n", (669, 690), False, 'from utils.log_utils import error_log, info_log\n'), ((... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('development', '0035_developmentproject_misc_textareas'),
]
operations = [
migrations.CreateModel(
... | [
"django.db.models.PositiveIntegerField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((388, 481), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'serialize': '(False)', 'auto_created': '(True)', 'verbose_name': '"""ID"""'}), "(primary_key=True, serialize=False, auto_created=True,\n verbose_name='ID')\n", (404, 481), False, 'from django.db import migrations, models\... |
# 脚本名称: 音频播放器
# 时间: 2021、4、20
# 参考内容来源链接 https://www.youtube.com/watch?v=uziilzjhf_g
# 需要用的模块
# pygame 需要下载,pip install pygame
# pygame 文档链接:https://www.pygame.org/docs/ref/mixer.html
# https://www.pygame.org/docs/ref/key.html
# tkinter 为python标准接口,具体文档阅读,https://docs.python.org/zh-cn/3.7/library/tkinte... | [
"os.listdir",
"pygame.init",
"pygame.mixer.music.pause",
"tkinter.Button",
"pygame.mixer.music.set_volume",
"os.chdir",
"tkinter.StringVar",
"tkinter.Scale",
"tkinter.Tk",
"pygame.mixer.music.unload",
"tkinter.Label",
"pygame.mixer.music.play",
"pygame.mixer.music.stop",
"pygame.mixer.init... | [((391, 399), 'tkinter.Tk', 'tkr.Tk', ([], {}), '()\n', (397, 399), True, 'import tkinter as tkr\n'), ((601, 634), 'os.chdir', 'os.chdir', (['"""C:/Users/Public/Music"""'], {}), "('C:/Users/Public/Music')\n", (609, 634), False, 'import os\n'), ((646, 658), 'os.listdir', 'os.listdir', ([], {}), '()\n', (656, 658), False... |
from rest_framework import decorators, permissions, status, viewsets
from rest_framework.response import Response
from lego.apps.feeds.attr_cache import AttrCache
from .feed_manager import feed_manager
from .models import NotificationFeed, PersonalFeed, UserFeed
from .serializers import (
AggregatedFeedSerializer... | [
"rest_framework.response.Response",
"rest_framework.decorators.action",
"lego.apps.feeds.attr_cache.AttrCache"
] | [((2754, 2841), 'rest_framework.decorators.action', 'decorators.action', ([], {'detail': '(False)', 'serializer_class': 'MarkSerializer', 'methods': "['POST']"}), "(detail=False, serializer_class=MarkSerializer, methods=[\n 'POST'])\n", (2771, 2841), False, 'from rest_framework import decorators, permissions, status... |
import logging
import unittest
from pkg2 import get_one
log = logging.getLogger(__name__)
log.debug("module imported")
def test():
log.debug("test run")
assert get_one() == 1
def test_fail():
log.debug("test_fail run")
assert get_one() == 2
class Tests(unittest.TestCase):
def test_fail2(self... | [
"logging.getLogger",
"pkg2.get_one"
] | [((65, 92), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (82, 92), False, 'import logging\n'), ((172, 181), 'pkg2.get_one', 'get_one', ([], {}), '()\n', (179, 181), False, 'from pkg2 import get_one\n'), ((248, 257), 'pkg2.get_one', 'get_one', ([], {}), '()\n', (255, 257), False, 'from p... |
# Copyright 2021 - 2022 Universität Tübingen, DKFZ and EMBL
# for the German Human Genome-Phenome Archive (GHGA)
#
# 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/... | [
"ucs.domain.models.FileInfoExternal.from_orm",
"ghga_service_chassis_lib.postgresql.SyncPostgresqlConnector",
"sqlalchemy.future.select",
"ghga_service_chassis_lib.postgresql.PostgresqlConfigBase",
"sqlalchemy.dialects.postgresql.UUID",
"ucs.domain.interfaces.outbound.file_info.FileInfoNotFoundError",
"... | [((1352, 1370), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (1368, 1370), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((1664, 1858), 'sqlalchemy.Column', 'Column', (['String'], {'nullable': '(False)', 'unique': '(True)', 'doc': "('ID used to refer to thi... |
# Generated by Django 3.2.4 on 2021-06-12 20:34
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Publication',
fields=[
('id', models.BigAut... | [
"django.db.models.CharField",
"django.db.models.BigAutoField"
] | [((307, 403), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (326, 403), False, 'from django.db import migrations, m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... | [
"os.path.exists",
"mock.patch",
"subprocess.check_call",
"os.path.join",
"requests.get",
"vcr.VCR.ensure_suffix",
"os.path.realpath",
"shutil.rmtree",
"time.sleep",
"copy.deepcopy",
"pytest.fixture",
"yagocd.session.Session",
"sys.stdout.write"
] | [((2464, 2495), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (2478, 2495), False, 'import pytest\n'), ((2571, 2587), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2585, 2587), False, 'import pytest\n'), ((2778, 2807), 'pytest.fixture', 'pytest.fixture', ([], {'sc... |
# Copyright 2014 Intel Corporation
# 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 requi... | [
"tackerclient.tests.unit.test_cli10.MyApp",
"tackerclient.tests.unit.test_cli10.MyResp",
"mock.patch.object",
"tackerclient.tests.unit.test_cli10.end_url",
"tackerclient.tacker.v1_0._get_resource_plural",
"tackerclient.tests.unit.test_cli10.MyComparator",
"tackerclient.tests.unit.test_utils.ContainsKeyV... | [((1318, 1364), 'mock.patch.object', 'mock.patch.object', (['TackerCommand', '"""get_client"""'], {}), "(TackerCommand, 'get_client')\n", (1335, 1364), False, 'import mock\n'), ((2562, 2616), 'tackerclient.tacker.v1_0._get_resource_plural', 'tackerV1_0._get_resource_plural', (['resource', 'self.client'], {}), '(resourc... |
"""
Copyright (C) 2019 <NAME> <<EMAIL>>
MIT License
"""
import datetime
import multiprocessing
import time
from datetime import datetime
import logging
import zmq
from message_handler import MessageHandler
from utils import setup_logging
class ZMQSubscriberQueue(multiprocessing.Process, MessageHandler):
def _... | [
"multiprocessing.Event",
"multiprocessing.Process.__init__",
"utils.setup_logging",
"zmq.Context",
"datetime.datetime.now",
"multiprocessing.get_logger",
"_10_manager.ServiceManager",
"utils.initializer",
"time.time",
"multiprocessing.Queue"
] | [((5284, 5307), 'multiprocessing.Event', 'multiprocessing.Event', ([], {}), '()\n', (5305, 5307), False, 'import multiprocessing\n'), ((5313, 5339), 'utils.initializer', 'initializer', (['logging.DEBUG'], {}), '(logging.DEBUG)\n', (5324, 5339), False, 'from utils import setup_logging, initializer\n'), ((5365, 5388), 'm... |
from SlowRecorder import SlowRecorder
import sys
if __name__ == "__main__":
app = SlowRecorder()
app.startApp()
sys.exit(app.app.exec_()) | [
"SlowRecorder.SlowRecorder"
] | [((88, 102), 'SlowRecorder.SlowRecorder', 'SlowRecorder', ([], {}), '()\n', (100, 102), False, 'from SlowRecorder import SlowRecorder\n')] |
# -*- coding: utf-8 -*-
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('cpovc_forms', '0028_auto_20210212_1153'),
('cpovc_registry', '0002_auto_20180712_1945'),
]
operations = [
migrations.CreateMod... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((3167, 3214), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""cpovc_manage.NOTTTravel"""'}), "(to='cpovc_manage.NOTTTravel')\n", (3184, 3214), False, 'from django.db import migrations, models\n'), ((3340, 3387), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""cpovc_manage.NOTTT... |
import numpy as np
def flux(x):
return 0.5 * np.square(x)
def minf(a,b):
# if b<=0:
# return flux(b)
# elif a>=0:
# return flux(a)
# else:
# return 0.0
return (b <= 0) * flux(b) + (a >= 0) * flux(a)
def maxf(a,b):
return np.maximum(flux(a),flux(b))
| [
"numpy.square"
] | [((50, 62), 'numpy.square', 'np.square', (['x'], {}), '(x)\n', (59, 62), True, 'import numpy as np\n')] |
import numpy as np
import zmq
from meta_mb.logger import logger
import gym
from gym import spaces
from meta_mb.meta_envs.base import MetaEnv
import time
class PR2Env(MetaEnv, gym.utils.EzPickle):
PR2_GAINS = np.array([3.09, 1.08, 0.393, 0.674, 0.111, 0.152, 0.098])
def __init__(self):
# self.goal = n... | [
"numpy.clip",
"numpy.mean",
"numpy.ones",
"gym.spaces.Box",
"numpy.array",
"gym.utils.EzPickle.__init__",
"numpy.concatenate",
"numpy.linalg.norm",
"numpy.frombuffer",
"zmq.Context"
] | [((214, 271), 'numpy.array', 'np.array', (['[3.09, 1.08, 0.393, 0.674, 0.111, 0.152, 0.098]'], {}), '([3.09, 1.08, 0.393, 0.674, 0.111, 0.152, 0.098])\n', (222, 271), True, 'import numpy as np\n'), ((1011, 1024), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (1022, 1024), False, 'import zmq\n'), ((1190, 1207), 'numpy... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"click.argument",
"pathlib.Path",
"click.group",
"click.option",
"datetime.datetime.utcnow",
"tempfile.NamedTemporaryFile",
"click.version_option",
"google.protobuf.text_format.MessageToString",
"sys.exit",
"docuploader.protos.metadata_pb2.Metadata",
"pkg_resources.get_distribution"
] | [((1127, 1140), 'click.group', 'click.group', ([], {}), '()\n', (1138, 1140), False, 'import click\n'), ((1142, 1202), 'click.version_option', 'click.version_option', ([], {'message': '"""%(version)s"""', 'version': 'VERSION'}), "(message='%(version)s', version=VERSION)\n", (1162, 1202), False, 'import click\n'), ((124... |
"""Magic 8-Ball
Simulates the classic Magic 8-Ball toy, with some ZeroBot twists...
"""
from __future__ import annotations
import random
import re
from collections import deque
from dataclasses import dataclass
from enum import Enum, unique
from string import Template
from typing import Optional, Union
from ZeroBot... | [
"ZeroBot.common.CommandParser",
"collections.deque",
"string.Template",
"re.compile",
"ZeroBot.feature.chat.fetch_phrase",
"random.choices",
"re.search"
] | [((3360, 3450), 'ZeroBot.common.CommandParser', 'CommandParser', (['"""8ball"""', '"""Shake ZeroBot\'s 8-Ball and receive an answer to your desires"""'], {}), '(\'8ball\',\n "Shake ZeroBot\'s 8-Ball and receive an answer to your desires")\n', (3373, 3450), False, 'from ZeroBot.common import CommandParser\n'), ((7603... |
# Offline DQM for HLT_Mu3er1p5_PFJet100er2p5_PFMETX_PFMHTX_IDTight (X = 70, 80, 90)
# <NAME> 2018
import FWCore.ParameterSet.Config as cms
from DQMOffline.Trigger.SusyMonitor_cfi import hltSUSYmonitoring
SoftMuHardJetMETSUSYmonitoring = hltSUSYmonitoring.clone()
SoftMuHardJetMETSUSYmonitoring.FolderName = cms.string... | [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.Sequence",
"FWCore.ParameterSet.Config.vstring",
"DQMOffline.Trigger.SusyMonitor_cfi.hltSUSYmonitoring.clone",
"FWCore.ParameterSet.Config.double",
"FWCore.ParameterSet.Config.InputTag",
"FWCore.ParameterSet.Config.vdouble",
"FWCore.Para... | [((240, 265), 'DQMOffline.Trigger.SusyMonitor_cfi.hltSUSYmonitoring.clone', 'hltSUSYmonitoring.clone', ([], {}), '()\n', (263, 265), False, 'from DQMOffline.Trigger.SusyMonitor_cfi import hltSUSYmonitoring\n'), ((310, 350), 'FWCore.ParameterSet.Config.string', 'cms.string', (['"""HLT/SUSY/SoftMuHardJetMET/"""'], {}), "... |
import redis
from singleton_decorator import singleton
@singleton
class RedisConn:
def __init__(self):
host = 'localhost'
port = 6379
self.client = redis.Redis(host=host, port=port, db=0)
def get_client(self):
return self.client
| [
"redis.Redis"
] | [((178, 217), 'redis.Redis', 'redis.Redis', ([], {'host': 'host', 'port': 'port', 'db': '(0)'}), '(host=host, port=port, db=0)\n', (189, 217), False, 'import redis\n')] |
from sklearn import linear_model
from sklearn.preprocessing import Imputer
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator
from sklearn.ensemble import GradientBoostingRegressor
class Regressor(BaseEstimator):
def __init__(self):
self.reg = Pipeline([
('imputer', Im... | [
"sklearn.preprocessing.Imputer",
"sklearn.ensemble.GradientBoostingRegressor"
] | [((318, 344), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {'strategy': '"""median"""'}), "(strategy='median')\n", (325, 344), False, 'from sklearn.preprocessing import Imputer\n'), ((373, 426), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {'max_depth': '(6)', 'subsample': '(0.8)'... |
# -*- coding: utf-8 -*-
"""
损失函数
Authors: dongrenguang(<EMAIL>)
Date: 2021/10/17
"""
import numpy as np
from ..core import Node
from ..operator import SoftMax
class LossFunction(Node):
"""损失函数抽象类
"""
pass
class PerceptionLoss(LossFunction):
"""感知机损失
"""
def compute(self):
# 输入为正时为0,... | [
"numpy.where",
"numpy.log"
] | [((575, 613), 'numpy.where', 'np.where', (['(parent.value >= 0.0)', '(0.0)', '(-1)'], {}), '(parent.value >= 0.0, 0.0, -1)\n', (583, 613), True, 'import numpy as np\n'), ((361, 428), 'numpy.where', 'np.where', (['(self.parents[0].value >= 0.0)', '(0.0)', '(-self.parents[0].value)'], {}), '(self.parents[0].value >= 0.0,... |
import sys
import socket
import os
from datetime import datetime
import emoji
import logging
from logging.config import dictConfig
import requests
# gRPC stuff
import grpc
from six import b
import whereami_pb2
import whereami_pb2_grpc
METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/'
METADATA_HEADER... | [
"os.getenv",
"whereami_pb2_grpc.WhereamiStub",
"logging.config.dictConfig",
"logging.warning",
"logging.info",
"requests.get",
"grpc.insecure_channel",
"datetime.datetime.now",
"sys.exc_info",
"whereami_pb2.Empty",
"socket.gethostname"
] | [((372, 672), 'logging.config.dictConfig', 'dictConfig', (["{'version': 1, 'formatters': {'default': {'format':\n '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'}}, 'handlers':\n {'wsgi': {'class': 'logging.StreamHandler', 'stream':\n 'ext://sys.stdout', 'formatter': 'default'}}, 'root': {'level': 'IN... |
import numpy as np
X = np.array([
[1,0,0],
[-1,10,0],
[-1,-1,0],
])
y = np.array([-1,1,1])
def perceptron_sgd(X, Y):
w = np.zeros(len(X[0]))
eta = 1
epochs = 20
for t in range(epochs):
for i, x in enumerate(X):
if (np.dot(X[i], w)*Y[i]) <= 0:
prin... | [
"numpy.array",
"numpy.dot"
] | [((24, 71), 'numpy.array', 'np.array', (['[[1, 0, 0], [-1, 10, 0], [-1, -1, 0]]'], {}), '([[1, 0, 0], [-1, 10, 0], [-1, -1, 0]])\n', (32, 71), True, 'import numpy as np\n'), ((91, 111), 'numpy.array', 'np.array', (['[-1, 1, 1]'], {}), '([-1, 1, 1])\n', (99, 111), True, 'import numpy as np\n'), ((272, 287), 'numpy.dot',... |
import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from torch.autograd import grad
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from tensorboardX import SummaryWriter... | [
"torch.tanh",
"torch.distributions.Normal",
"tensorboardX.SummaryWriter",
"argparse.ArgumentParser",
"torch.FloatTensor",
"torch.exp",
"torch.nn.MSELoss",
"numpy.array",
"torch.cuda.is_available",
"torch.tensor",
"torch.nn.Linear",
"torch.zeros",
"torch.clamp",
"torch.cat"
] | [((418, 443), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (441, 443), False, 'import argparse\n'), ((354, 379), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (377, 379), False, 'import torch\n'), ((3324, 3349), 'torch.nn.Linear', 'nn.Linear', (['state_dim', '(512)']... |
import json
import os
import pathlib
import pickle
import shutil
import tempfile
from abc import ABCMeta, abstractmethod
from datetime import datetime
from typing import Optional, Iterable, Mapping, Any, Set, Dict, List, MutableMapping, Union, Tuple
import logging
import arrow
from anyio import open_file
from deepdiff ... | [
"logging.getLogger",
"bring.transform.pipeline.Pipeline",
"anyio.open_file",
"pickle.dumps",
"frkl.common.regex.replace_var_names_in_obj",
"pickle.loads",
"frkl.args.arg.explode_arg_dict",
"frkl.common.types.isinstance_or_subclass",
"os.path.exists",
"pathlib.Path",
"shutil.move",
"json.dumps"... | [((1420, 1446), 'logging.getLogger', 'logging.getLogger', (['"""bring"""'], {}), "('bring')\n", (1437, 1446), False, 'import logging\n'), ((5119, 5137), 'os.environ.items', 'os.environ.items', ([], {}), '()\n', (5135, 5137), False, 'import os\n'), ((1266, 1421), 'frkl.common.exceptions.FrklException', 'FrklException', ... |
'''
File [ eval_metrics.py ]
Author [ <NAME> (NTUEE) ]
Synopsis [ Evaluation metrics. ]
'''
import edit_distance as ed
def split_sequence(seq, mode='word'):
''' Split sequence by word or characters. '''
if mode in ['word', 'phone']:
return seq.split(' ')
elif mode == 'char':... | [
"edit_distance.SequenceMatcher"
] | [((594, 626), 'edit_distance.SequenceMatcher', 'ed.SequenceMatcher', ([], {'a': 'ref', 'b': 'hyp'}), '(a=ref, b=hyp)\n', (612, 626), True, 'import edit_distance as ed\n'), ((953, 985), 'edit_distance.SequenceMatcher', 'ed.SequenceMatcher', ([], {'a': 'ref', 'b': 'hyp'}), '(a=ref, b=hyp)\n', (971, 985), True, 'import ed... |
import datetime
import unittest
# 5 years from now (more or less)
fiveyrsfuture = datetime.datetime.utcnow() + datetime.timedelta(5*365)
class Test_static_view_use_subpath_False(unittest.TestCase):
def _getTargetClass(self):
from pyramid.static import static_view
return static_view
def _makeO... | [
"datetime.timedelta",
"pyramid.request.Request",
"datetime.datetime.utcnow"
] | [((83, 109), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (107, 109), False, 'import datetime\n'), ((112, 139), 'datetime.timedelta', 'datetime.timedelta', (['(5 * 365)'], {}), '(5 * 365)\n', (130, 139), False, 'import datetime\n'), ((823, 847), 'pyramid.request.Request', 'Request', ([], {'... |
import functools
import jax
from jax import lax
import jax.numpy as jnp
import math
from distla_core.utils import misc
from distla_core.utils import pops
from distla_core.utils import vops
##############################################################################
# TSQR
##########################################... | [
"jax.lax.fori_loop",
"distla_core.utils.vops._indices_vec",
"math.log2",
"distla_core.utils.vops.get_columns",
"distla_core.utils.vops.outer",
"jax.numpy.linalg.qr",
"jax.numpy.full",
"jax.numpy.dot",
"distla_core.utils.pops.eye",
"jax.numpy.linalg.solve",
"distla_core.utils.vops.add_to_diagonal... | [((8850, 8897), 'functools.partial', 'functools.partial', (['jax.jit'], {'static_argnums': '(2,)'}), '(jax.jit, static_argnums=(2,))\n', (8867, 8897), False, 'import functools\n'), ((9583, 9630), 'functools.partial', 'functools.partial', (['jax.jit'], {'static_argnums': '(2,)'}), '(jax.jit, static_argnums=(2,))\n', (96... |
import unittest
import urllib.parse
from app.services import RandomPasswdGenerator
class TestRandomPasswdGenerator(unittest.TestCase):
def test_random_string_length(self):
size = 6
generator = RandomPasswdGenerator(size=size)
random_str = generator.generate()
self.assert... | [
"app.services.RandomPasswdGenerator"
] | [((217, 249), 'app.services.RandomPasswdGenerator', 'RandomPasswdGenerator', ([], {'size': 'size'}), '(size=size)\n', (238, 249), False, 'from app.services import RandomPasswdGenerator\n'), ((410, 435), 'app.services.RandomPasswdGenerator', 'RandomPasswdGenerator', (['(20)'], {}), '(20)\n', (431, 435), False, 'from app... |
"""
This plugin adds support for the "Ashata Relay Board" family of USB controlled relay boards as a device. This device
can then be accessed by the ufotest system through the device manager. Relay channels can be switched on and off
individually. The Ashata Relay Boards are compatible with linux by using the system li... | [
"time.sleep",
"ufotest.devices.Expose",
"ufotest.util.run_command",
"ufotest.hooks.Action",
"types.MethodType"
] | [((4083, 4108), 'ufotest.hooks.Action', 'Action', (['"""pre_prepare"""', '(10)'], {}), "('pre_prepare', 10)\n", (4089, 4108), False, 'from ufotest.hooks import Action, Filter\n'), ((4501, 4531), 'ufotest.hooks.Action', 'Action', (['"""register_devices"""', '(10)'], {}), "('register_devices', 10)\n", (4507, 4531), False... |
"""
Alternative implementations of segmented regression routines.
"""
# Author: <NAME>
# License: BSD 3 clause
import numpy as np
from segreg.model.alt import regression_alt, one_bkpt_segreg_alt,\
likelihood_util
try:
from numba import jit
except ImportError as e:
from segreg.mockjit import jit
# cache... | [
"numpy.copy",
"segreg.model.alt.regression_alt.ols_terms",
"numpy.isscalar",
"numpy.logical_and",
"numpy.searchsorted",
"segreg.model.alt.likelihood_util.loglikelihood",
"segreg.model.alt.likelihood_util.rss_line_segment",
"numpy.append",
"numpy.array",
"segreg.model.alt.regression_alt.mat_by_hand... | [((6142, 6160), 'segreg.mockjit.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (6145, 6160), False, 'from segreg.mockjit import jit\n'), ((7457, 7475), 'segreg.mockjit.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (7460, 7475), False, 'from segreg.mockjit import jit\n'), ((8069, 8100)... |
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
class UserProfileManager(BaseUserManager):
"""Manager for user profiles"""
def create_u... | [
"django.db.models.EmailField",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((1160, 1206), 'django.db.models.EmailField', 'models.EmailField', ([], {'max_length': '(255)', 'unique': '(True)'}), '(max_length=255, unique=True)\n', (1177, 1206), False, 'from django.db import models\n'), ((1214, 1246), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=2... |
#DataFormatFunctions
import numpy as np
from PIL import Image
from HelperClasses import *
from ValueDefinitions import *
def createMNISTVector(filename):
image = Image.open(filename).convert("L") #Convert to greyscale
width, height = image.size
assert (width==IMG_WIDTH and height==IMG_HEIGHT)
imgDa... | [
"numpy.zeros",
"PIL.Image.open"
] | [((359, 384), 'numpy.zeros', 'np.zeros', (['(IMG_PIXELS, 1)'], {}), '((IMG_PIXELS, 1))\n', (367, 384), True, 'import numpy as np\n'), ((623, 648), 'numpy.zeros', 'np.zeros', (['(IMG_PIXELS, 1)'], {}), '((IMG_PIXELS, 1))\n', (631, 648), True, 'import numpy as np\n'), ((838, 871), 'numpy.zeros', 'np.zeros', (['(IMG_HEIGH... |
from keanu.vertex import Gamma
from keanu import BayesNet
from keanu.network_io import ProtobufLoader, JsonLoader, ProtobufSaver, DotSaver, JsonSaver
def test_can_save_and_load(tmpdir) -> None:
PROTO_FILE_NAME = str(tmpdir.join("test.proto"))
JSON_FILE_NAME = str(tmpdir.join("test.json"))
DOT_FILE_NAME = s... | [
"keanu.network_io.DotSaver",
"keanu.vertex.Gamma",
"keanu.network_io.JsonSaver",
"keanu.network_io.ProtobufSaver",
"keanu.network_io.ProtobufLoader",
"keanu.network_io.JsonLoader"
] | [((361, 376), 'keanu.vertex.Gamma', 'Gamma', (['(1.0)', '(1.0)'], {}), '(1.0, 1.0)\n', (366, 376), False, 'from keanu.vertex import Gamma\n'), ((563, 581), 'keanu.network_io.ProtobufSaver', 'ProtobufSaver', (['net'], {}), '(net)\n', (576, 581), False, 'from keanu.network_io import ProtobufLoader, JsonLoader, ProtobufSa... |
import os
import tempfile
from contextlib import (ExitStack,
contextmanager)
from functools import partial
from typing import (Any,
Dict,
Iterable,
Optional)
import click
import pytest
import strictyaml
from hypothesis import given
fr... | [
"strictyaml.as_document",
"functools.partial",
"os.unlink",
"contextlib.ExitStack",
"tempfile.NamedTemporaryFile",
"hypothesis.given",
"monty.monty.files_paths",
"pytest.raises"
] | [((406, 588), 'hypothesis.given', 'given', (['strategies.settings', 'strategies.templates_directories_paths', 'strategies.template_repositories_names', 'strategies.temporary_directories', 'strategies.github_access_tokens'], {}), '(strategies.settings, strategies.templates_directories_paths,\n strategies.template_rep... |
# Serial and sequential floating text across multiple clients!
# Use case: Demonstrate connecting multiple clients in the network
from time import sleep
from os import get_terminal_size, name, system
from figlets import letters
from utilities import transform_figlets, print_figlet_array, get_local_ip
from server import... | [
"server.CerealServer",
"utilities.print_figlet_array",
"utilities.get_local_ip",
"os.get_terminal_size",
"utilities.transform_figlets",
"time.sleep",
"os.system",
"client.CerealClient"
] | [((382, 401), 'os.get_terminal_size', 'get_terminal_size', ([], {}), '()\n', (399, 401), False, 'from os import get_terminal_size, name, system\n'), ((490, 521), 'utilities.transform_figlets', 'transform_figlets', (['letters[fig]'], {}), '(letters[fig])\n', (507, 521), False, 'from utilities import transform_figlets, p... |
#!/usr/bin/env python
# for triggerDict['Azimuth'][trigerDict['Energy']]:
# for key = 'maxType':
# if triggerDict[key] == 'counterXX':
import pylab as pl
import sys
import pickle
f = open(sys.argv[1], 'rb')
mydict = pickle.load(f)
print(mydict)
AzimuthList = list(mydict.values())[0]
maxTypeList = list(... | [
"pickle.dump",
"pickle.load"
] | [((232, 246), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (243, 246), False, 'import pickle\n'), ((2805, 2858), 'pickle.dump', 'pickle.dump', (['GRB', 'f'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(GRB, f, protocol=pickle.HIGHEST_PROTOCOL)\n', (2816, 2858), False, 'import pickle\n')] |
import re
import six
from sqlalchemy import inspect
from jet_bridge_base.exceptions.validation_error import ValidationError
def serialize_validation_error(exc):
def process(e, root=False):
if isinstance(e.detail, dict):
return dict(map(lambda x: (x[0], process(x[1])), e.detail.items()))
... | [
"sqlalchemy.inspect",
"six.text_type",
"jet_bridge_base.exceptions.validation_error.ValidationError",
"re.search"
] | [((1913, 1944), 'jet_bridge_base.exceptions.validation_error.ValidationError', 'ValidationError', (['"""Query failed"""'], {}), "('Query failed')\n", (1928, 1944), False, 'from jet_bridge_base.exceptions.validation_error import ValidationError\n'), ((963, 985), 'six.text_type', 'six.text_type', (['message'], {}), '(mes... |
import random
import bintrees
import threading
from itertools import count
from collections import Counter
import tensorflow as tf
from joblib import Parallel, delayed
from lib.ops import get_available_gpus
from lib.trainer import SampleBasedTrainer
class MultiGPUTrainer:
def __init__(self, name, make_model,
... | [
"tensorflow.device",
"tensorflow.InteractiveSession",
"tensorflow.variable_scope",
"random.Random",
"threading.Lock",
"tensorflow.get_default_session",
"bintrees.FastRBTree",
"collections.Counter",
"tensorflow.train.GradientDescentOptimizer",
"threading.get_ident",
"tensorflow.assign_add",
"jo... | [((341, 361), 'lib.ops.get_available_gpus', 'get_available_gpus', ([], {}), '()\n', (359, 361), False, 'from lib.ops import get_available_gpus\n'), ((4060, 4076), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (4074, 4076), False, 'import threading\n'), ((6579, 6596), 'random.Random', 'random.Random', (['(42)'],... |
import chess
import numpy as np
class State:
def __init__(self, board=None):
if board is None:
self.board = chess.Board()
else:
self.board = board
def serialize(self) -> np.ndarray:
"""
Convert board into matrix representation for use with numpy.
... | [
"chess.scan_reversed",
"numpy.zeros",
"chess.Board"
] | [((699, 718), 'numpy.zeros', 'np.zeros', (['(8 * 8 + 5)'], {}), '(8 * 8 + 5)\n', (707, 718), True, 'import numpy as np\n'), ((862, 878), 'numpy.zeros', 'np.zeros', (['(64 + 5)'], {}), '(64 + 5)\n', (870, 878), True, 'import numpy as np\n'), ((897, 953), 'chess.scan_reversed', 'chess.scan_reversed', (['self.board.occupi... |
from distutils.core import setup
requirements = [
'django==2.0.2',
'bitshares==0.1.11',
'graphenelib==0.5.9',
'social-auth-app-django==2.1.0',
'vk==2.0.2',
'google-auth==1.4.1',
'google-auth-httplib2==0.0.3',
'google-api-python-client==1.6.5',
'facebook-sdk==2.0.0',
'django-cors... | [
"distutils.core.setup"
] | [((365, 600), 'distutils.core.setup', 'setup', ([], {'name': '"""utschool-faucet"""', 'version': '"""1.0"""', 'url': '"""https://github.com/u-transnet/utschool-faucet"""', 'license': '"""MIT"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""Faucet for UT-SCHOOL project"""', 'requires': ... |
import asyncio
import websockets
import struct
async def hello():
async with websockets.connect('ws://localhost:8777') as websocket:
x = [
0xaa,
0x02,
0x01,
0x01,
0xa, 0x0, 0x0, 0x0,
0x01,
0x40, 0xe2, 0x1, 0x0,
... | [
"asyncio.get_event_loop",
"websockets.connect"
] | [((82, 123), 'websockets.connect', 'websockets.connect', (['"""ws://localhost:8777"""'], {}), "('ws://localhost:8777')\n", (100, 123), False, 'import websockets\n'), ((720, 744), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (742, 744), False, 'import asyncio\n')] |
#!/usr/bin/env python3
# https://www.codewars.com/kata/evaluate-mathematical-expression
import re
from enum import Enum
from functools import wraps
from pprint import pprint
# def combinators?
# match epsilons? should match_x always have atleast one character?
TokenType = Enum("TokenType", "space lparen rparen unop ... | [
"functools.wraps",
"re.match",
"pprint.pprint",
"enum.Enum"
] | [((276, 331), 'enum.Enum', 'Enum', (['"""TokenType"""', '"""space lparen rparen unop binop num"""'], {}), "('TokenType', 'space lparen rparen unop binop num')\n", (280, 331), False, 'from enum import Enum\n'), ((403, 417), 'pprint.pprint', 'pprint', (['tokens'], {}), '(tokens)\n', (409, 417), False, 'from pprint import... |
"""
Copyright (c) 2012 <NAME> <http://sixpinetrees.blogspot.com/>
2017 Nordic Semiconductor ASA
Implementation of the lowest-level Resource class.
"""
import message
from constants import *
from itertools import chain
from types import NoResource, UnallowedMethod, UnsupportedMethod
class CoapResource(o... | [
"types.UnsupportedMethod",
"types.UnallowedMethod",
"message.Message.AckMessage"
] | [((1639, 1658), 'types.UnsupportedMethod', 'UnsupportedMethod', ([], {}), '()\n', (1656, 1658), False, 'from types import NoResource, UnallowedMethod, UnsupportedMethod\n'), ((1763, 1780), 'types.UnallowedMethod', 'UnallowedMethod', ([], {}), '()\n', (1778, 1780), False, 'from types import NoResource, UnallowedMethod, ... |
from talon.voice import Context, Key, Str, press
context = Context('latex')
# if true, insert a \ prefix by default
insert_prefix = True
def latex_on():
global insert_prefix
insert_prefix = True
print("latex on")
def latex_off():
global insert_prefix
insert_prefix = False
print("latex off"... | [
"talon.voice.Str",
"talon.voice.Context"
] | [((60, 76), 'talon.voice.Context', 'Context', (['"""latex"""'], {}), "('latex')\n", (67, 76), False, 'from talon.voice import Context, Key, Str, press\n'), ((1448, 1454), 'talon.voice.Str', 'Str', (['w'], {}), '(w)\n', (1451, 1454), False, 'from talon.voice import Context, Key, Str, press\n'), ((1670, 1676), 'talon.voi... |
# _*_ coding: utf-8 _*_
import json
from flask import jsonify, request, flash, render_template
from . import web
from helper import is_isbn_or_key
from yushu_book import YuShuBook
from app.forms.book import SearchForm
from app.view_models.book import BookViewModel, BookCollection
__author__ = "吴飞鸿"
__date__ = "2019/... | [
"flask.render_template",
"flask.flash",
"helper.is_isbn_or_key",
"app.view_models.book.BookViewModel",
"app.view_models.book.BookCollection",
"app.forms.book.SearchForm",
"yushu_book.YuShuBook"
] | [((455, 479), 'app.forms.book.SearchForm', 'SearchForm', (['request.args'], {}), '(request.args)\n', (465, 479), False, 'from app.forms.book import SearchForm\n'), ((492, 508), 'app.view_models.book.BookCollection', 'BookCollection', ([], {}), '()\n', (506, 508), False, 'from app.view_models.book import BookViewModel, ... |
import asyncio
from signal import SIGTERM
from custom import *
from setup import database_setup
from Accessory import Accessory
bot = config.bot
@bot.event
async def on_ready():
# bot.loop.add_signal_handler(
# SIGTERM, lambda: asyncio.ensure_future(terminate())
# )
await database_setup()
... | [
"Accessory.Accessory.set_prefixes",
"Accessory.Accessory.ensure_integrity",
"setup.database_setup",
"Accessory.Accessory.remove"
] | [((298, 314), 'setup.database_setup', 'database_setup', ([], {}), '()\n', (312, 314), False, 'from setup import database_setup\n'), ((326, 354), 'Accessory.Accessory.ensure_integrity', 'Accessory.ensure_integrity', ([], {}), '()\n', (352, 354), False, 'from Accessory import Accessory\n'), ((571, 600), 'Accessory.Access... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import numpy as np
from model.losses import FocalLoss, RegL1Loss, RegLoss, RegWeightedL1Loss
from model.decode import multi_pose_decode
from model.utils import _sigmoid, flip_tensor, flip_lr_off, ... | [
"torch.nn.L1Loss",
"model.losses.RegL1Loss",
"torch.nn.MSELoss",
"model.losses.FocalLoss",
"model.losses.RegWeightedL1Loss",
"model.losses.RegLoss"
] | [((633, 644), 'model.losses.FocalLoss', 'FocalLoss', ([], {}), '()\n', (642, 644), False, 'from model.losses import FocalLoss, RegL1Loss, RegLoss, RegWeightedL1Loss\n'), ((667, 685), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (683, 685), False, 'import torch\n'), ((707, 718), 'model.losses.FocalLoss', 'F... |
import ast
import typing
from .primitiveBlocks import AST__slots__, ASTNone, ASTSelf, dirFunc, getAttrFunc, typingIterableAST, typingOptionalAST, typingUnionAST
def genTypingOptional(tp):
return ast.Subscript(
value=typingOptionalAST,
slice=ast.Index(value=tp),
)
def genTypingUnion(tps: typing.Union[ast.Subs... | [
"ast.Index",
"ast.Load",
"ast.arg",
"ast.Store",
"ast.Call",
"ast.Str"
] | [((815, 860), 'ast.Call', 'ast.Call', ([], {'func': 'dirFunc', 'args': '[o]', 'keywords': '[]'}), '(func=dirFunc, args=[o], keywords=[])\n', (823, 860), False, 'import ast\n'), ((249, 268), 'ast.Index', 'ast.Index', ([], {'value': 'tp'}), '(value=tp)\n', (258, 268), False, 'import ast\n'), ((588, 607), 'ast.Index', 'as... |
"""Module about the default values."""
import os
from pathlib import Path
import json
rcParams = {
"unit": 1.,
"origin": [0., 0., 0.],
"dimensions": [32, 32, 32],
"plotter": {
"window_size": [1280, 720],
"show_edges": True,
"line_width": 3,
"advanced": False,
"... | [
"pathlib.Path.home",
"os.environ.get",
"json.dump"
] | [((2920, 2931), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (2929, 2931), False, 'from pathlib import Path\n'), ((3020, 3061), 'os.environ.get', 'os.environ.get', (['env_variable', 'config_file'], {}), '(env_variable, config_file)\n', (3034, 3061), False, 'import os\n'), ((3268, 3289), 'json.dump', 'json.dump',... |
import logging
import unittest
import numpy as np
import torch
from reagent.core import types as rlt
from reagent.evaluation.evaluation_data_page import EvaluationDataPage
from reagent.evaluation.ope_adapter import OPEstimatorAdapter
from reagent.ope.estimators.contextual_bandits_estimators import (
DMEstimator,
... | [
"logging.getLogger",
"reagent.evaluation.evaluation_data_page.EvaluationDataPage.create_from_tensors_seq2slate",
"torch.LongTensor",
"torch.eye",
"reagent.test.evaluation.test_evaluation_data_page.FakeSeq2SlateTransformerNet",
"reagent.ope.estimators.contextual_bandits_estimators.IPSEstimator",
"reagent... | [((552, 579), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (569, 579), False, 'import logging\n'), ((2703, 2731), 'reagent.test.evaluation.test_evaluation_data_page.FakeSeq2SlateRewardNetwork', 'FakeSeq2SlateRewardNetwork', ([], {}), '()\n', (2729, 2731), False, 'from reagent.test.evalu... |
# ---------------------------------------------------------------------
# Juniper.JUNOSe.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pyth... | [
"re.compile"
] | [((610, 771), 're.compile', 're.compile', (['"""Juniper\\\\s+(Edge Routing Switch )?(?P<platform>.+?)$.+Version\\\\s+(?P<version>.+?)\\\\s*\\\\[BuildId (?P<build>\\\\d+)"""', '(re.MULTILINE | re.DOTALL)'], {}), "(\n 'Juniper\\\\s+(Edge Routing Switch )?(?P<platform>.+?)$.+Version\\\\s+(?P<version>.+?)\\\\s*\\\\[Buil... |
import os
ROOT = os.path.dirname(os.path.abspath(__file__)) + '/../'
from ...psf import GaussianPSF, FilePSF, FunctionPSF
from ...filter import Filter
from ...utils.one_filter import OneFilter
'''
Information on IRAC detector with Filter objects, PSF objects including resolution and zero-magnitude fluxes.
'''
IRAC1_... | [
"os.path.abspath"
] | [((33, 58), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (48, 58), False, 'import os\n')] |
import pytest
from django.contrib.admin.sites import AdminSite
from apps.sms.admin import SmsAdmin
from apps.sms.models import Sms
@pytest.mark.django_db
def test_sms_admin_qs(request, sms, user):
admin = SmsAdmin(model=Sms, admin_site=AdminSite())
request.user = user
request.user.is_superuser = True
... | [
"django.contrib.admin.sites.AdminSite"
] | [((243, 254), 'django.contrib.admin.sites.AdminSite', 'AdminSite', ([], {}), '()\n', (252, 254), False, 'from django.contrib.admin.sites import AdminSite\n')] |
from cdec_maps import cdec
import pytest
import pandas as pd
def test_read_simple():
c = cdec.Reader()
df = c._read_station_data('FPT', '1', 'H', '2020-01-01', '2020-02-01')
assert not df.empty
assert len(df) == 745
assert df['VALUE'].iloc[0] == pytest.approx(104.31)
assert df['VALUE'].index[0... | [
"cdec_maps.cdec.Reader",
"pandas.Timestamp",
"pytest.approx"
] | [((95, 108), 'cdec_maps.cdec.Reader', 'cdec.Reader', ([], {}), '()\n', (106, 108), False, 'from cdec_maps import cdec\n'), ((391, 404), 'cdec_maps.cdec.Reader', 'cdec.Reader', ([], {}), '()\n', (402, 404), False, 'from cdec_maps import cdec\n'), ((685, 698), 'cdec_maps.cdec.Reader', 'cdec.Reader', ([], {}), '()\n', (69... |