code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
import bisect
if not nums:
return -1
n = len(nums)
k = n
for i in range(1, n):
if nums[i - 1] > ... | [
"bisect.bisect_left"
] | [((439, 475), 'bisect.bisect_left', 'bisect.bisect_left', (['nums', 'target', '*r'], {}), '(nums, target, *r)\n', (457, 475), False, 'import bisect\n')] |
import sys
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QUrl
from PySide2.QtCore import QCoreApplication
from PySide2.QtCore import QObject, Signal, Slot, Property
class Number(QObject):
__val = 0
@Signal
def numberChanged(self):
... | [
"PySide2.QtCore.Slot",
"PySide2.QtCore.Property",
"PySide2.QtQml.QQmlApplicationEngine",
"sys.exit",
"PySide2.QtCore.QUrl",
"PySide2.QtGui.QGuiApplication"
] | [((334, 343), 'PySide2.QtCore.Slot', 'Slot', (['int'], {}), '(int)\n', (338, 343), False, 'from PySide2.QtCore import QObject, Signal, Slot, Property\n'), ((564, 623), 'PySide2.QtCore.Property', 'Property', (['int', 'get_number', 'set_number'], {'notify': 'numberChanged'}), '(int, get_number, set_number, notify=numberC... |
#!/usr/bin/env python3
import argparse, os, sys, time, shutil, tqdm
import warnings, json, gzip
import numpy as np
import copy
from sklearn.model_selection import GroupKFold
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader, ... | [
"numpy.isin",
"numpy.random.seed",
"argparse.ArgumentParser",
"misc_utils.evaluator",
"os.path.isfile",
"torch.device",
"time.asctime",
"torch.nn.MSELoss",
"torch.nn.BCELoss",
"torch.utils.data.DataLoader",
"torch.matmul",
"functools.partial",
"copy.deepcopy",
"tqdm.tqdm",
"torch.manual_... | [((409, 445), 'functools.partial', 'functools.partial', (['print'], {'flush': '(True)'}), '(print, flush=True)\n', (426, 445), False, 'import functools\n'), ((1081, 1103), 'os.path.isfile', 'os.path.isfile', (['in_dir'], {}), '(in_dir)\n', (1095, 1103), False, 'import argparse, os, sys, time, shutil, tqdm\n'), ((1739, ... |
import unittest
from app.main.util.data_validation import validate_region_name
class TestCorrectRegionValidation(unittest.TestCase):
def test_correct_region_validation(self):
correct_region_simple = "Argentina"
correct_region_with_spaces = "United%20Kingdom"
correct_region_with_hiphen =... | [
"unittest.main",
"app.main.util.data_validation.validate_region_name"
] | [((1961, 1976), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1974, 1976), False, 'import unittest\n'), ((418, 461), 'app.main.util.data_validation.validate_region_name', 'validate_region_name', (['correct_region_simple'], {}), '(correct_region_simple)\n', (438, 461), False, 'from app.main.util.data_validation i... |
""" TensorMONK :: layers :: Activations """
__all__ = ["Activations"]
import torch
import torch.nn as nn
import torch.nn.functional as F
def maxout(tensor: torch.Tensor) -> torch.Tensor:
if not tensor.size(1) % 2 == 0:
raise ValueError("MaxOut: tensor.size(1) must be divisible by n_splits"
... | [
"torch.ones",
"torch.nn.functional.selu",
"torch.nn.functional.prelu",
"torch.nn.functional.relu6",
"torch.nn.functional.gelu",
"torch.sigmoid",
"torch.nn.functional.leaky_relu",
"torch.nn.functional.relu",
"torch.nn.functional.elu",
"torch.nn.functional.softplus",
"numpy.prod",
"torch.tanh"
] | [((4037, 4051), 'torch.nn.functional.relu', 'F.relu', (['tensor'], {}), '(tensor)\n', (4043, 4051), True, 'import torch.nn.functional as F\n'), ((4112, 4127), 'torch.nn.functional.relu6', 'F.relu6', (['tensor'], {}), '(tensor)\n', (4119, 4127), True, 'import torch.nn.functional as F\n'), ((4187, 4222), 'torch.nn.functi... |
__author__ = 'luchenhua'
EtoF = {'bread': 'du pain', 'wine': 'du vin', 'eats': 'mange', 'drinks': 'bois', 'likes': 'aime', 1: 'un',
'6.00': '6.00'}
print(EtoF)
print(EtoF.keys())
print(EtoF.keys)
del EtoF[1]
print(EtoF)
def translateWord(word, dictionary):
if word in dictionary:
return dictionary... | [
"string.lower"
] | [((1161, 1176), 'string.lower', 'string.lower', (['s'], {}), '(s)\n', (1173, 1176), False, 'import string\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
class WideResNet:
def __init__(self, nk, input_shape, num_classes, weight_decay, keep_prob, data_format='channels_last'):
assert len(nk) == 2
assert (nk[0... | [
"tensorflow.trainable_variables",
"tensorflow.get_collection",
"tensorflow.identity",
"tensorflow.layers.max_pooling2d",
"tensorflow.InteractiveSession",
"tensorflow.layers.batch_normalization",
"tensorflow.nn.softmax",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.nn.relu",
"tensorflow... | [((680, 716), 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), '()\n', (714, 716), True, 'import tensorflow as tf\n'), ((952, 1012), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': 'shape', 'name': '"""images"""'}), "(dtype=tf.float32, shape... |
# Not currently used; in case I ever turn this into a formal package
import setuptools
with open('README.md', 'r') as f:
long_description = f.read()
with open('requirements.txt') as f:
install_requires = f.read().split('\n')
install_requires = [x for x in install_requires if x != '']
setuptools.setup(
... | [
"setuptools.find_packages"
] | [((584, 610), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (608, 610), False, 'import setuptools\n')] |
#coding:utf-8
#################################
#Copyright(c) 2014 dtysky
#################################
import G2R,os
class MovieDefine(G2R.DefineSyntax):
def Creat(self,Flag,US,FS,DictHash):
DictHash=G2R.DefineSyntax.Creat(self,Flag,US,FS,DictHash)
if DictHash[Flag]==G2R.DHash(US.Args[Flag]):
return DictH... | [
"G2R.DHash",
"G2R.DefineSyntax.Creat",
"os.path.splitext"
] | [((209, 261), 'G2R.DefineSyntax.Creat', 'G2R.DefineSyntax.Creat', (['self', 'Flag', 'US', 'FS', 'DictHash'], {}), '(self, Flag, US, FS, DictHash)\n', (231, 261), False, 'import G2R, os\n'), ((279, 303), 'G2R.DHash', 'G2R.DHash', (['US.Args[Flag]'], {}), '(US.Args[Flag])\n', (288, 303), False, 'import G2R, os\n'), ((541... |
from setuptools import setup
import os
from collections import OrderedDict
try:
long_description = ""
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
except:
print('Curr dir:', os.getcwd())
long_description = open('../../README.md').read()
setup(name='geograpy3',
... | [
"collections.OrderedDict",
"os.getcwd"
] | [((734, 937), 'collections.OrderedDict', 'OrderedDict', (["(('Documentation', 'https://geograpy3.netlify.app'), ('Code',\n 'https://github.com/somnathrakshit/geograpy3'), ('Issue tracker',\n 'https://github.com/somnathrakshit/geograpy3/issues'))"], {}), "((('Documentation', 'https://geograpy3.netlify.app'), ('Cod... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params... | [
"django.urls.reverse",
"rest_framework.test.APIClient",
"django.contrib.auth.get_user_model"
] | [((209, 231), 'django.urls.reverse', 'reverse', (['"""user:create"""'], {}), "('user:create')\n", (216, 231), False, 'from django.urls import reverse\n'), ((244, 265), 'django.urls.reverse', 'reverse', (['"""user:token"""'], {}), "('user:token')\n", (251, 265), False, 'from django.urls import reverse\n'), ((275, 293), ... |
from pyowm import OWM
import csv
from datetime import datetime
from os import environ, stat, path, access, R_OK, mkdir
API_key = environ.get('API_key')
if API_key is None:
from creds import API_key
fields = ["date", "windspeed", "humidity", "temperature", "status"]
now = datetime.now()
cities = ["Praha", "Pl... | [
"os.mkdir",
"pyowm.OWM",
"os.stat",
"os.path.isdir",
"os.environ.get",
"os.path.isfile",
"datetime.datetime.now",
"os.access"
] | [((131, 153), 'os.environ.get', 'environ.get', (['"""API_key"""'], {}), "('API_key')\n", (142, 153), False, 'from os import environ, stat, path, access, R_OK, mkdir\n'), ((281, 295), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (293, 295), False, 'from datetime import datetime\n'), ((973, 985), 'pyowm.OWM... |
from serialize import save_to, load_from
from keras.models import Model
class GenericModel(object):
def __init__( self, inputs, outputs, loss, metrics, optimizer, loss_weights=None, sample_weight_mode=None):
"""
params:
inputs: (tuple)
outputs: (tuple)
loss: (fu... | [
"serialize.save_to",
"keras.models.Model",
"serialize.load_from"
] | [((448, 485), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (453, 485), False, 'from keras.models import Model\n'), ((1617, 1647), 'serialize.save_to', 'save_to', (['self.model', 'self.name'], {}), '(self.model, self.name)\n', (1624, 1647), False,... |
from sedac_gpw_parser import population
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.colors as colors
import os
file_lons = np.arange(-180, 180, 40)
file_lats = np.arange(90, -20, -50)
DATA_FOLDER = os.path.expanduser("~") + "/.srtm30/"
def get_population_data(country_id):
pop = ... | [
"numpy.sum",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.round",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.zeros_like",
"numpy.isfinite",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.nansum",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot... | [((154, 178), 'numpy.arange', 'np.arange', (['(-180)', '(180)', '(40)'], {}), '(-180, 180, 40)\n', (163, 178), True, 'import numpy as np\n'), ((191, 214), 'numpy.arange', 'np.arange', (['(90)', '(-20)', '(-50)'], {}), '(90, -20, -50)\n', (200, 214), True, 'import numpy as np\n'), ((229, 252), 'os.path.expanduser', 'os.... |
from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, \
send_joined_embed, send_remove_embed
from moderation_module.storage import GuildLoggingConfig
from alento_bot import StorageManager
from discord.ext import commands
import moderation_module.text
import ... | [
"discord.ext.commands.command",
"moderation_module.guild_logging.commands.send_remove_embed",
"moderation_module.guild_logging.commands.guild_logging_control",
"moderation_module.guild_logging.commands.send_joined_embed",
"discord.ext.commands.has_permissions",
"discord.ext.commands.Cog.listener",
"mode... | [((354, 383), 'logging.getLogger', 'logging.getLogger', (['"""main_bot"""'], {}), "('main_bot')\n", (371, 383), False, 'import logging\n'), ((706, 750), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'administrator': '(True)'}), '(administrator=True)\n', (730, 750), False, 'from discord.ext i... |
import os
import re
from drkns.exception import MissingGenerationTemplateDirectoryException, \
MissingGenerationTemplateException, MultipleGenerationTemplateException
_template_directory = '.drknsgeneration'
_template_file_re = re.compile(r'^.*\.template\..*$')
def get_generation_template_path(from_path: str) ... | [
"drkns.exception.MissingGenerationTemplateException",
"os.path.exists",
"drkns.exception.MultipleGenerationTemplateException",
"drkns.exception.MissingGenerationTemplateDirectoryException",
"os.path.join",
"os.listdir",
"re.compile"
] | [((235, 269), 're.compile', 're.compile', (['"""^.*\\\\.template\\\\..*$"""'], {}), "('^.*\\\\.template\\\\..*$')\n", (245, 269), False, 'import re\n'), ((353, 397), 'os.path.join', 'os.path.join', (['from_path', '_template_directory'], {}), '(from_path, _template_directory)\n', (365, 397), False, 'import os\n'), ((616... |
from __future__ import division, print_function
from typing import List, Tuple, Callable
import numpy as np
import scipy
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, nb_features=2, max_iteration=10, margin=1e-4):
'''
Args :
nb_features : Number of feature... | [
"numpy.dot",
"numpy.linalg.norm",
"numpy.random.shuffle"
] | [((1280, 1304), 'numpy.linalg.norm', 'np.linalg.norm', (['features'], {}), '(features)\n', (1294, 1304), True, 'import numpy as np\n'), ((1444, 1466), 'numpy.random.shuffle', 'np.random.shuffle', (['seq'], {}), '(seq)\n', (1461, 1466), True, 'import numpy as np\n'), ((1516, 1543), 'numpy.dot', 'np.dot', (['self.w', 'fe... |
# -*- coding: utf-8 -*-
#!/usr/bin/python3
"""
"""
# =============================================================================
# Imports
# =============================================================================
import cv2
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
# M... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"cv2.imread"
] | [((481, 513), 'cv2.imread', 'cv2.imread', (['"""data/lena_std.tiff"""'], {}), "('data/lena_std.tiff')\n", (491, 513), False, 'import cv2\n'), ((528, 545), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (538, 545), True, 'from matplotlib import pyplot as plt\n'), ((546, 556), 'matplotlib.pyplot.... |
import numpy as np
import os
import time
np.set_printoptions(threshold=np.inf)
def input(fname):
day_dir = os.path.realpath(__file__).split('/')[:-1]
fname = os.path.join('/',*day_dir, fname)
data = []
with open(fname) as f:
for line in f:
data.append(line.strip())
return data... | [
"numpy.set_printoptions",
"os.path.realpath",
"time.time",
"numpy.array",
"os.path.join"
] | [((42, 79), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (61, 79), True, 'import numpy as np\n'), ((1513, 1524), 'time.time', 'time.time', ([], {}), '()\n', (1522, 1524), False, 'import time\n'), ((1629, 1640), 'time.time', 'time.time', ([], {}), '()\n', (1638,... |
# Copyright 2017-2021 The GPflow Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"deprecated.deprecated"
] | [((1023, 1178), 'deprecated.deprecated', 'deprecated', ([], {'reason': 'f"""The gpflow.utilities.utilities module is deprecated and will be removed in GPflow 2.3; use gpflow.utilities.{name} instead."""'}), "(reason=\n f'The gpflow.utilities.utilities module is deprecated and will be removed in GPflow 2.3; use gpflo... |
"""Check Python docstrings validate as reStructuredText (RST).
This is a plugin for the tool flake8 tool for checking Python
soucre code.
"""
import logging
import re
import sys
import textwrap
import tokenize as tk
from itertools import chain, dropwhile
try:
from StringIO import StringIO
except ImportError: #... | [
"textwrap.dedent",
"io.StringIO",
"sys.stdin.read",
"re.compile",
"codecs.lookup",
"restructuredtext_lint.lint",
"io.TextIOWrapper",
"io.open",
"itertools.chain",
"logging.getLogger",
"tokenize.generate_tokens"
] | [((5198, 5225), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (5215, 5225), False, 'import logging\n'), ((926, 982), 're.compile', 're.compile', (['"""^[ \\\\t\\\\f]*#.*?coding[:=][ \\\\t]*([-\\\\w.]+)"""'], {}), "('^[ \\\\t\\\\f]*#.*?coding[:=][ \\\\t]*([-\\\\w.]+)')\n", (936, 982), Fal... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `youtube_sm_parser` package."""
import pytest
import unittest.mock
import deepdiff
import collections
import os
import xmltodict
import json
from youtube_sm_parser import youtube_sm_parser
def rel_fn(fn):
dir_name = os.path.dirname(os.path.realpath(_... | [
"json.load",
"youtube_sm_parser.youtube_sm_parser.get_entries",
"os.path.realpath",
"youtube_sm_parser.youtube_sm_parser.extract_feeds",
"youtube_sm_parser.youtube_sm_parser.parse_args",
"youtube_sm_parser.youtube_sm_parser.format_dict",
"youtube_sm_parser.youtube_sm_parser.feed_to_dicts",
"pytest.rai... | [((2265, 2320), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""f"""', "['json', 'lines', 'yaml']"], {}), "('f', ['json', 'lines', 'yaml'])\n", (2288, 2320), False, 'import pytest\n'), ((3089, 3267), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""out_format, expected, line_format"""', '[[\'json... |
"""Quantum Router."""
import collections
class Router:
# TODO: Remove this when we have more methods
# pylint:disable=too-few-public-methods
"""A quantum router.
A quantum router object represents a quantum router that is part of a quantum network. Quantum
routers are interconnected by quantum li... | [
"collections.OrderedDict"
] | [((846, 871), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (869, 871), False, 'import collections\n')] |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
from ai4all_api import views
schema_view = get_schema_view(title='AI4All backend API')
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.reg... | [
"django.conf.urls.include",
"django.conf.urls.url",
"rest_framework.routers.DefaultRouter",
"rest_framework.schemas.get_schema_view"
] | [((187, 230), 'rest_framework.schemas.get_schema_view', 'get_schema_view', ([], {'title': '"""AI4All backend API"""'}), "(title='AI4All backend API')\n", (202, 230), False, 'from rest_framework.schemas import get_schema_view\n'), ((294, 309), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (3... |
from keras.models import load_model
# from matplotlib.font_manager import FontProperties
import cv2
import numpy as np
import exptBikeNYC
size =10
model = exptBikeNYC.build_model(False)
model.load_weights('MODEL/c3.p3.t3.resunit4.lr0.0002.best.h5')
f = open("area.csv", "r")
# 临时存储某时间的人数
person_num = []
# 存储各时间的人数尺寸(n... | [
"exptBikeNYC.build_model",
"numpy.array"
] | [((156, 186), 'exptBikeNYC.build_model', 'exptBikeNYC.build_model', (['(False)'], {}), '(False)\n', (179, 186), False, 'import exptBikeNYC\n'), ((1330, 1347), 'numpy.array', 'np.array', (['train_y'], {}), '(train_y)\n', (1338, 1347), True, 'import numpy as np\n'), ((1260, 1278), 'numpy.array', 'np.array', (['train_x1']... |
# Generated by Django 2.1.5 on 2019-02-14 13:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('places', '0037_hostel'),
('article', '0002_textarticle_place'),
]
operations = [
migrations.RenameFi... | [
"django.db.models.ForeignKey",
"django.db.models.ImageField",
"django.db.migrations.RenameField"
] | [((301, 395), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""imagearticle"""', 'old_name': '"""user"""', 'new_name': '"""created_by"""'}), "(model_name='imagearticle', old_name='user', new_name\n ='created_by')\n", (323, 395), False, 'from django.db import migrations, models\n'... |
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from datetime import datetime
LOGDIR = '/tmp/17springAI/mnist/objectiveFunc/' + datetime.now().strftime('%Y%m%d-%H%M%S') + '/'
def activation(act_func, logit):
if act_func == "relu":
return tf.nn.relu(log... | [
"tensorflow.contrib.keras.losses.mean_squared_error",
"tensorflow.reset_default_graph",
"tensorflow.reshape",
"tensorflow.train.AdamOptimizer",
"tensorflow.matmul",
"numpy.mean",
"tensorflow.GPUOptions",
"tensorflow.truncated_normal",
"tensorflow.nn.softmax",
"tensorflow.nn.relu",
"tensorflow.nn... | [((4916, 4971), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""./MNIST_data"""'], {'one_hot': '(True)'}), "('./MNIST_data', one_hot=True)\n", (4941, 4971), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((601, 635), 'tensorflow.summary.histog... |
import copy # for copying something in Python
import unicodedata
import multiprocessing as mp
from multiprocessing import Manager
import gc
import numpy as np
class WSUtils():
def __init__(self, VNDict):
##################################################################################################
... | [
"unicodedata.normalize",
"copy.deepcopy",
"multiprocessing.Manager",
"multiprocessing.Process"
] | [((3859, 3903), 'unicodedata.normalize', 'unicodedata.normalize', (['"""NFC"""', "(u'' + line_pos)"], {}), "('NFC', u'' + line_pos)\n", (3880, 3903), False, 'import unicodedata\n'), ((14261, 14280), 'copy.deepcopy', 'copy.deepcopy', (['lbls'], {}), '(lbls)\n', (14274, 14280), False, 'import copy\n'), ((24148, 24157), '... |
import unittest
import numpy as np
from rastervision.core.class_map import (ClassItem, ClassMap)
from rastervision.evaluations.segmentation_evaluation import (
SegmentationEvaluation)
from rastervision.label_stores.segmentation_raster_file import (
SegmentationInputRasterFile)
from rastervision.label_stores.s... | [
"unittest.main",
"numpy.ones",
"rastervision.core.class_map.ClassItem",
"rastervision.label_stores.segmentation_raster_file.SegmentationInputRasterFile",
"rastervision.label_stores.segmentation_raster_file_test.TestingRasterSource",
"rastervision.evaluations.segmentation_evaluation.SegmentationEvaluation"... | [((2129, 2144), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2142, 2144), False, 'import unittest\n'), ((658, 692), 'numpy.ones', 'np.ones', (['(5, 5, 3)'], {'dtype': 'np.uint8'}), '((5, 5, 3), dtype=np.uint8)\n', (665, 692), True, 'import numpy as np\n'), ((773, 807), 'rastervision.label_stores.segmentation_ra... |
from importlib.metadata import version
try:
__version__ = version(__name__)
except:
pass | [
"importlib.metadata.version"
] | [((63, 80), 'importlib.metadata.version', 'version', (['__name__'], {}), '(__name__)\n', (70, 80), False, 'from importlib.metadata import version\n')] |
# Plot / Form
# Display a plot inside a form.
# ---
from synth import FakeCategoricalSeries
from h2o_wave import site, data, ui
page = site['/demo']
n = 20
f = FakeCategoricalSeries()
v = page.add('example', ui.form_card(
box='1 1 4 5',
items=[
ui.text_xl('Example 1'),
ui.visualization(
... | [
"h2o_wave.ui.text_xl",
"synth.FakeCategoricalSeries",
"h2o_wave.ui.mark"
] | [((162, 185), 'synth.FakeCategoricalSeries', 'FakeCategoricalSeries', ([], {}), '()\n', (183, 185), False, 'from synth import FakeCategoricalSeries\n'), ((263, 286), 'h2o_wave.ui.text_xl', 'ui.text_xl', (['"""Example 1"""'], {}), "('Example 1')\n", (273, 286), False, 'from h2o_wave import site, data, ui\n'), ((539, 562... |
from django.db.models import Q
from model_utils.models import now
from rest_framework.filters import BaseFilterBackend
class OwnerFilter(BaseFilterBackend):
"""过滤属于当前用户的数据"""
def filter_queryset(self, request, queryset, view):
current = request.user
return queryset.filter(owner=current)
cla... | [
"django.db.models.Q"
] | [((608, 622), 'django.db.models.Q', 'Q', ([], {'end__lt': 'now'}), '(end__lt=now)\n', (609, 622), False, 'from django.db.models import Q\n'), ((582, 598), 'django.db.models.Q', 'Q', ([], {'start__gt': 'now'}), '(start__gt=now)\n', (583, 598), False, 'from django.db.models import Q\n'), ((544, 559), 'django.db.models.Q'... |
import math
from scrollingtext import ScrollingText
from widget import Widget
class TextList(Widget):
_text_margin = 1
_selected = None # type: None | int
def __init__(self, position, size, font, empty_items_text):
super(TextList, self).__init__(position, size)
self._font = font
... | [
"scrollingtext.ScrollingText"
] | [((829, 931), 'scrollingtext.ScrollingText', 'ScrollingText', (['(self._text_margin, line_y)', '(width - 2 * self._text_margin, text_height)', 'font', '""""""'], {}), "((self._text_margin, line_y), (width - 2 * self._text_margin,\n text_height), font, '')\n", (842, 931), False, 'from scrollingtext import ScrollingTe... |
"""Monty hall paradox
Wiki:
https://en.wikipedia.org/wiki/Fermat_primality_test
"""
import math
import random
def ferma(number: int, k: int = 100) -> bool:
"""Тест простоты Ферма
Wiki:
https://en.wikipedia.org/wiki/Fermat_primality_test
:param number: проверяемое число
:type number: in... | [
"random.randint",
"math.gcd"
] | [((696, 727), 'math.gcd', 'math.gcd', (['random_number', 'number'], {}), '(random_number, number)\n', (704, 727), False, 'import math\n'), ((570, 595), 'random.randint', 'random.randint', (['(1)', 'number'], {}), '(1, number)\n', (584, 595), False, 'import random\n')] |
"""Snakemake wrapper for PALADIN alignment"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, <NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
from os import path
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=False, stderr=True)
r = snakemak... | [
"snakemake.shell.shell"
] | [((796, 916), 'snakemake.shell.shell', 'shell', (['"""paladin align -f {min_orf_len} -t {snakemake.threads} {extra} {index_base} {r} {output_cmd} {outfile}"""'], {}), "(\n 'paladin align -f {min_orf_len} -t {snakemake.threads} {extra} {index_base} {r} {output_cmd} {outfile}'\n )\n", (801, 916), False, 'from snake... |
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline 缩放
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (12, 8)
# Normal distributed x and y vector with mean 0 and standard deviation 1
x = np.random.normal(0, 1, 200)
y = np.random.normal(0, 1, 200)
X = np.vstack((x, y)) # 2xn
# 缩放
sx, sy ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.style.use",
"numpy.array",
"numpy.random.normal",
"numpy.vstack"
] | [((76, 99), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (89, 99), True, 'import matplotlib.pyplot as plt\n'), ((219, 246), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(200)'], {}), '(0, 1, 200)\n', (235, 246), True, 'import numpy as np\n'), ((251, 278), 'numpy... |
import mock
from six import StringIO
from grab import GrabTimeoutError, Grab
from grab.spider import Spider, Task
from tests.util import BaseGrabTestCase, build_spider, run_test_if, GLOBAL
# That URLs breaks Grab's URL normalization process
# with error "label empty or too long"
INVALID_URL = 'http://13354&altProduc... | [
"grab.Grab",
"tests.util.build_spider",
"mock.patch",
"six.StringIO",
"grab.spider.Task",
"tests.util.run_test_if"
] | [((3930, 4060), 'tests.util.run_test_if', 'run_test_if', (["(lambda : GLOBAL['network_service'] == 'multicurl' and GLOBAL[\n 'grab_transport'] == 'pycurl')", '"""multicurl & pycurl"""'], {}), "(lambda : GLOBAL['network_service'] == 'multicurl' and GLOBAL[\n 'grab_transport'] == 'pycurl', 'multicurl & pycurl')\n",... |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField,BooleanField
from wtforms.validators import DataRequired,EqualTo,Email
from ..models import User
from wtforms import ValidationError
class RegistrationForm(FlaskForm):
email=StringField('Your email address',validators=[DataR... | [
"wtforms.ValidationError",
"wtforms.validators.Email",
"wtforms.BooleanField",
"wtforms.SubmitField",
"wtforms.validators.EqualTo",
"wtforms.validators.DataRequired"
] | [((635, 656), 'wtforms.SubmitField', 'SubmitField', (['"""submit"""'], {}), "('submit')\n", (646, 656), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1184, 1211), 'wtforms.BooleanField', 'BooleanField', (['"""remember me"""'], {}), "('remember me')\n", (1196, 1211), False, 'fr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 11 16:22:17 2021
@author: mike_ubuntu
"""
import numpy as np
from functools import reduce
import copy
import gc
import time
import datetime
import pickle
import warnings
import epde.globals as global_var
import torch
from epde.decorators import H... | [
"epde.interface.token_family.TF_Pool",
"numpy.abs",
"numpy.maximum",
"epde.supplementary.Population_Sort",
"numpy.ones",
"gc.collect",
"numpy.isclose",
"numpy.random.randint",
"numpy.arange",
"numpy.mean",
"torch.flatten",
"numpy.multiply",
"numpy.copy",
"numpy.std",
"numpy.ndim",
"num... | [((728, 742), 'numpy.copy', 'np.copy', (['Input'], {}), '(Input)\n', (735, 742), True, 'import numpy as np\n'), ((21638, 21697), 'epde.decorators.Reset_equation_status', 'Reset_equation_status', ([], {'reset_input': '(False)', 'reset_output': '(True)'}), '(reset_input=False, reset_output=True)\n', (21659, 21697), False... |
from django.contrib import admin
from members.models import Member
# Register your models here.
class MemberAdmin(admin.ModelAdmin):
'''
Admin View for Member
'''
list_display = ('full_name', 'email', 'phone_number',)
admin.site.register(Member, MemberAdmin)
| [
"django.contrib.admin.site.register"
] | [((240, 280), 'django.contrib.admin.site.register', 'admin.site.register', (['Member', 'MemberAdmin'], {}), '(Member, MemberAdmin)\n', (259, 280), False, 'from django.contrib import admin\n')] |
# encoding: utf-8
from __future__ import print_function
import term
import humanfriendly
class RequestStorage(object):
""" Stores statistics about single request """
def __init__(self):
self.queryset_stats = []
def add_queryset_storage_instance(self, queryset_storage):
self.queryset_st... | [
"term.writeLine",
"humanfriendly.format_size",
"term.write"
] | [((733, 801), 'term.writeLine', 'term.writeLine', (['"""\n\t ERASERHEAD STATS \n"""', 'term.bold', 'term.reverse'], {}), '("""\n\t ERASERHEAD STATS \n""", term.bold, term.reverse)\n', (747, 801), False, 'import term\n'), ((921, 984), 'term.write', 'term.write', (['"""\t TOTAL WASTED MEMORY: """', 'term.bold', 'term.rev... |
from easydict import EasyDict as edict
# init
__C_SHHA = edict()
cfg_data = __C_SHHA
__C_SHHA.TRAIN_SIZE = (512,1024)
__C_SHHA.DATA_PATH = '../ProcessedData/SHHA/'
__C_SHHA.TRAIN_LST = 'train.txt'
__C_SHHA.VAL_LST = 'val.txt'
__C_SHHA.VAL4EVAL = 'val_gt_loc.txt'
__C_SHHA.MEAN_STD = ([0.410824894905, 0.37063497304... | [
"easydict.EasyDict"
] | [((59, 66), 'easydict.EasyDict', 'edict', ([], {}), '()\n', (64, 66), True, 'from easydict import EasyDict as edict\n')] |
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2021-02-25 20:06:08
# @Last Modified by: <NAME>
# @Last Modified time: 2021-02-25 20:06:12
import json
import logging
import socket
from os import environ
from monitoring.constants import (
ARM_AWAY,
ARM_STAY,
LOG_IPC,
MONITOR_ARM_AWAY,
MONITOR... | [
"socket.socket",
"logging.getLogger",
"json.dumps"
] | [((772, 798), 'logging.getLogger', 'logging.getLogger', (['LOG_IPC'], {}), '(LOG_IPC)\n', (789, 798), False, 'import logging\n'), ((855, 904), 'socket.socket', 'socket.socket', (['socket.AF_UNIX', 'socket.SOCK_STREAM'], {}), '(socket.AF_UNIX, socket.SOCK_STREAM)\n', (868, 904), False, 'import socket\n'), ((2676, 2695),... |
""" Functionality to analyse bias triangles
@author: amjzwerver
"""
#%%
import numpy as np
import qcodes
import qtt
import qtt.pgeometry
import matplotlib.pyplot as plt
from qcodes.plots.qcmatplotlib import MatPlot
from qtt.data import diffDataset
def plotAnalysedLines(clicked_pts, linePoints1_2, linePt3_vert, li... | [
"numpy.abs",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.figure",
"numpy.linalg.norm",
"matplotlib.pyplot.gca",
"numpy.round",
"qtt.pgeometry.intersect2lines",
"qtt.pgeometry.plot2Dline",
"qtt.pgeometry.dehom",
"qtt.pgeometry.fitPlane",
"qtt.data.diffDataset",
"matplotlib.pyplot.get_fignums",
... | [((918, 974), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePoints1_2', '""":c"""'], {'alpha': '(0.5)'}), "(linePoints1_2, ':c', alpha=0.5)\n", (942, 974), False, 'import qtt\n'), ((980, 1035), 'qtt.pgeometry.plot2Dline', 'qtt.pgeometry.plot2Dline', (['linePt3_vert', '""":b"""'], {'alpha': '(0.4)'}), "... |
from django.db import models
import iipimage.fields
import iipimage.storage
import sculpture.constants
from .base_model import BaseModel
from .contributor import Contributor
from .image_status import ImageStatus
class BaseImage (BaseModel):
"""Abstract model for all images."""
SOURCE_FORMATS = (('analogu... | [
"django.db.models.ForeignKey",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.CharField"
] | [((659, 753), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ImageStatus'], {'related_name': '"""%(app_label)s_%(class)s_images"""', 'blank': '(True)'}), "(ImageStatus, related_name=\n '%(app_label)s_%(class)s_images', blank=True)\n", (676, 753), False, 'from django.db import models\n'), ((777, 882), 'django... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='isobar',
version='0.1.1',
description='A Python library to express and manipulate musical patterns',
long_description = open("README.md", "r").read(),
long_description_content_type = "text/markdown",
author='<NAME>'... | [
"setuptools.find_packages"
] | [((410, 425), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (423, 425), False, 'from setuptools import setup, find_packages\n')] |
# Copyright 2015 <NAME>
#
# 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 w... | [
"sys.stderr.write",
"vector.Vector",
"draw.round_corners"
] | [((2554, 2605), 'draw.round_corners', 'draw.round_corners', (['P', 'CORNER_RADIUS', 'CORNER_POINTS'], {}), '(P, CORNER_RADIUS, CORNER_POINTS)\n', (2572, 2605), False, 'import draw\n'), ((2698, 2763), 'sys.stderr.write', 'sys.stderr.write', (["('Frame is %.1fx%.1f inches\\n' % (width, height))"], {}), "('Frame is %.1fx%... |
import json
from django.test import TestCase, Client
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from .models import User, SignUpCode
from .auth import auth_token, passwd_token
class UserTestCase(TestCase):
"""User test case"""
def setUp(self):
... | [
"django.urls.reverse",
"json.dumps",
"django.test.Client"
] | [((735, 743), 'django.test.Client', 'Client', ([], {}), '()\n', (741, 743), False, 'from django.test import TestCase, Client\n'), ((1041, 1068), 'django.urls.reverse', 'reverse', (['"""signup-available"""'], {}), "('signup-available')\n", (1048, 1068), False, 'from django.urls import reverse\n'), ((1318, 1340), 'django... |
""" Ship Graveyard Simulator Prologue
"""
#pylint: disable=C0103
from protonfixes import util
def main():
""" needs builtin vulkan-1
"""
util.set_environment('WINEDLLOVERRIDES','vulkan-1=b')
| [
"protonfixes.util.set_environment"
] | [((152, 206), 'protonfixes.util.set_environment', 'util.set_environment', (['"""WINEDLLOVERRIDES"""', '"""vulkan-1=b"""'], {}), "('WINEDLLOVERRIDES', 'vulkan-1=b')\n", (172, 206), False, 'from protonfixes import util\n')] |
from tests.utils import W3CTestCase
class TestFlexbox_Flex110Unitless(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flex-1-1-0-unitless'))
| [
"tests.utils.W3CTestCase.find_tests"
] | [((103, 166), 'tests.utils.W3CTestCase.find_tests', 'W3CTestCase.find_tests', (['__file__', '"""flexbox_flex-1-1-0-unitless"""'], {}), "(__file__, 'flexbox_flex-1-1-0-unitless')\n", (125, 166), False, 'from tests.utils import W3CTestCase\n')] |
import setuptools
setuptools.setup(
name='pynetem',
version='0.1',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/manojrege/pynetem',
description='A Python wrapper library for network emulation on MacOS',
long_description=open('README.md').read(),
license=open('LICENSE... | [
"setuptools.find_packages"
] | [((344, 370), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (368, 370), False, 'import setuptools\n')] |
import face_recognition
import cv2
import numpy as np
import os
import re
from itertools import chain
known_people_folder='./database'
def scan_known_people(known_people_folder):
known_names = []
known_face_encodings = []
for file in image_files_in_folder(known_people_folder):
basename = os.path.... | [
"face_recognition.compare_faces",
"numpy.argmin",
"cv2.rectangle",
"cv2.imshow",
"os.path.join",
"cv2.cvtColor",
"face_recognition.face_encodings",
"cv2.destroyAllWindows",
"cv2.resize",
"face_recognition.face_distance",
"os.path.basename",
"cv2.waitKey",
"re.match",
"os.listdir",
"cv2.p... | [((1610, 1629), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1626, 1629), False, 'import cv2\n'), ((5245, 5268), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5266, 5268), False, 'import cv2\n'), ((2053, 2091), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HLS'], {... |
from socketclient import Client
import socketio
import csv
from random import randrange
import threading
import time
def toni(car_id):
sio = None
try:
sio = socketio.Client(ssl_verify=False)
sio.connect('http://localhost:3003/')
except socketio.exceptions.ConnectionError:
print('[E... | [
"csv.reader",
"socketio.Client",
"socketclient.Client",
"time.sleep",
"random.randrange"
] | [((1035, 1054), 'socketclient.Client', 'Client', (['sio', 'car_id'], {}), '(sio, car_id)\n', (1041, 1054), False, 'from socketclient import Client\n'), ((1066, 1080), 'random.randrange', 'randrange', (['(469)'], {}), '(469)\n', (1075, 1080), False, 'from random import randrange\n'), ((175, 208), 'socketio.Client', 'soc... |
# SpeechToText of multiple audio files in a directory
# Using this code snippet you can convert multiple audio files from specific directory to the text format
# It will make seperate .txt files for each audio file into the given directory path and will save the transcriptions of all audio files into those .txt files
... | [
"symbl.Audio.process_file",
"os.path.join",
"os.listdir"
] | [((1164, 1190), 'os.path.join', 'join', (['directory_path', 'file'], {}), '(directory_path, file)\n', (1168, 1190), False, 'from os.path import isfile, join\n'), ((1203, 1226), 'os.listdir', 'listdir', (['directory_path'], {}), '(directory_path)\n', (1210, 1226), False, 'from os import listdir\n'), ((1237, 1263), 'os.p... |
import os
import sys
import h5py
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--root', help='path to root directory')
args = parser.parse_args()
root = args.root
fname = os.path.join(root, 'metadata/train.txt')
flist = [os.path.join(root, 'h5', line.strip())
fo... | [
"h5py.File",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.median",
"numpy.savetxt",
"numpy.zeros",
"os.path.join"
] | [((79, 104), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (102, 104), False, 'import argparse\n'), ((220, 260), 'os.path.join', 'os.path.join', (['root', '"""metadata/train.txt"""'], {}), "(root, 'metadata/train.txt')\n", (232, 260), False, 'import os\n'), ((357, 402), 'os.path.join', 'os.pat... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=import-error,print-statement,relative-import,protected-access
"""Unit tests for name_style_converter.py."""
import unittest
from name_st... | [
"name_style_converter.NameStyleConverter",
"name_style_converter.tokenize_name"
] | [((6291, 6324), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""HTMLElement"""'], {}), "('HTMLElement')\n", (6309, 6324), False, 'from name_style_converter import NameStyleConverter\n'), ((6451, 6487), 'name_style_converter.NameStyleConverter', 'NameStyleConverter', (['"""someSuperThing"""'], {})... |
from django.conf.urls import url
from product.views import CategoryView, CategoryIndexView
urlpatterns = [
url(r'^(?P<parent_slugs>([-\w]+/)*)?(?P<slug>[-\w]+)/$', CategoryView.as_view(), name='satchmo_category'),
url(r'^$', CategoryIndexView.as_view(), name='satchmo_category_index'),
] | [
"product.views.CategoryIndexView.as_view",
"product.views.CategoryView.as_view"
] | [((170, 192), 'product.views.CategoryView.as_view', 'CategoryView.as_view', ([], {}), '()\n', (190, 192), False, 'from product.views import CategoryView, CategoryIndexView\n'), ((235, 262), 'product.views.CategoryIndexView.as_view', 'CategoryIndexView.as_view', ([], {}), '()\n', (260, 262), False, 'from product.views i... |
import socket
from enum import IntEnum
from typing import Dict, List
from base64 import b64decode, b64encode
UTF_8 = 'utf-8'
class Stage(IntEnum):
START = 1
TRANSFER = 2
CHECKID = 3
CHECK = 4
SHOW = 5
SEND = 6
class BaseMsg:
def get_bytes(self) -> bytes:
return str(self).encod... | [
"socket.socket",
"base64.b64encode",
"base64.b64decode"
] | [((3752, 3766), 'base64.b64decode', 'b64decode', (['res'], {}), '(res)\n', (3761, 3766), False, 'from base64 import b64decode, b64encode\n'), ((2101, 2150), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (2114, 2150), False, 'import socket\n')... |
import time
import datetime
import itertools
from wtforms import fields#, widgets
try:
from wtforms.fields import _unset_value as unset_value
except ImportError:
from wtforms.utils import unset_value
from .widgets import (
DateTimePickerWidget,
TimePickerWidget,
Select2Widget,
Select2TagsWidge... | [
"itertools.chain",
"datetime.time",
"time.strptime",
"mytrade.utils._",
"itertools.repeat"
] | [((7843, 7893), 'itertools.chain', 'itertools.chain', (['self.validators', 'extra_validators'], {}), '(self.validators, extra_validators)\n', (7858, 7893), False, 'import itertools\n'), ((8306, 8328), 'itertools.repeat', 'itertools.repeat', (['None'], {}), '(None)\n', (8322, 8328), False, 'import itertools\n'), ((3262,... |
from pathlib import Path
from novel_tools.framework import Processor
from novel_tools.common import NovelData, ACC, FieldMetadata
class PathTransformer(Processor, ACC):
"""
Given `in_dir`, this transformer will replace all `Path` fields with the paths relative to its `in_dir`.
"""
@staticmethod
d... | [
"novel_tools.common.FieldMetadata"
] | [((394, 490), 'novel_tools.common.FieldMetadata', 'FieldMetadata', (['"""in_dir"""', '"""Path"""'], {'description': '"""The parent directory for all the novel data."""'}), "('in_dir', 'Path', description=\n 'The parent directory for all the novel data.')\n", (407, 490), False, 'from novel_tools.common import NovelDa... |
import pandas as pd
def values_to_df(values):
data = []
for n, v in values.items():
data.append([
n.localname, v.to_value().get_value(), v.unit
])
return pd.DataFrame(
data,
columns = ["name", "value", "unit"]
)
def instance_to_df(inst):
columns = [... | [
"pandas.DataFrame"
] | [((199, 252), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['name', 'value', 'unit']"}), "(data, columns=['name', 'value', 'unit'])\n", (211, 252), True, 'import pandas as pd\n'), ((1326, 1361), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'columns'}), '(data, columns=columns)\n', (1338, 13... |
import flask
import pyodbc
# Initializes app and database connection
app = flask.Flask('biosphere', template_folder='templates')
db_conn = conn = pyodbc.connect(
'Driver={SQL Server};'
'Server=DESKTOP-QR078NF\SQLEXPRESS;'
'Database=BIOSPHERE;'
'Trusted_Connection=yes;'
)
# Function to hand... | [
"flask.Flask",
"flask.render_template",
"pyodbc.connect"
] | [((80, 133), 'flask.Flask', 'flask.Flask', (['"""biosphere"""'], {'template_folder': '"""templates"""'}), "('biosphere', template_folder='templates')\n", (91, 133), False, 'import flask\n'), ((152, 277), 'pyodbc.connect', 'pyodbc.connect', (['"""Driver={SQL Server};Server=DESKTOP-QR078NF\\\\SQLEXPRESS;Database=BIOSPHER... |
import argparse
import time
import numpy as np
import pyvisa
# Parse folder path, file name, and measurement parameters from command line
# arguments. Remember to include the "python" keyword before the call to the
# python file from the command line, e.g. python example.py "arg1" "arg2".
# Folder paths must use for... | [
"numpy.absolute",
"pyvisa.ResourceManager",
"argparse.ArgumentParser",
"time.time",
"numpy.array"
] | [((366, 456), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Measure and save max power point tracking data"""'}), "(description=\n 'Measure and save max power point tracking data')\n", (389, 456), False, 'import argparse\n'), ((1727, 1747), 'numpy.absolute', 'np.absolute', (['V_start... |
#!/usr/local/bin/python3.6
#-*- coding: utf-8 -*-
#Author WangJiang@2019 15810438848 <EMAIL>
#All rights reserved
################################################################################################################
from colorama import init, Fore, Back, Style
###############################################... | [
"colorama.init"
] | [((691, 711), 'colorama.init', 'init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (695, 711), False, 'from colorama import init, Fore, Back, Style\n')] |
from unittest import TestCase
from unittest.mock import patch
from nose.tools import istest
from convertfrom.main import convert, main
class EntryPointTest(TestCase):
@istest
@patch('convertfrom.main.sys')
@patch('convertfrom.main.print')
@patch('convertfrom.main.convert')
def prints_converted_r... | [
"unittest.mock.patch",
"convertfrom.main.main",
"convertfrom.main.convert"
] | [((188, 217), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.sys"""'], {}), "('convertfrom.main.sys')\n", (193, 217), False, 'from unittest.mock import patch\n'), ((223, 254), 'unittest.mock.patch', 'patch', (['"""convertfrom.main.print"""'], {}), "('convertfrom.main.print')\n", (228, 254), False, 'from unittes... |
import os
import boto3
from slackclient import SlackClient
from lunchbot import logging
logger = logging.getLogger(__name__)
class Slack(object):
client = None
@staticmethod
def get_client():
if Slack.client is not None:
logger.debug("Using cached Slack client")
return... | [
"boto3.resource",
"lunchbot.logging.getLogger",
"slackclient.SlackClient"
] | [((101, 128), 'lunchbot.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (118, 128), False, 'from lunchbot import logging\n'), ((462, 486), 'slackclient.SlackClient', 'SlackClient', (['slack_token'], {}), '(slack_token)\n', (473, 486), False, 'from slackclient import SlackClient\n'), ((804, ... |
from __future__ import division
from __future__ import print_function
from evaluation import get_roc_score, clustering_latent_space
from input_data import load_adj_feature
from kcore import compute_kcore, expand_embedding
from model import *
from optimizer import OptimizerAE, OptimizerVAE
from preprocessing impo... | [
"numpy.save",
"kcore.expand_embedding",
"numpy.std",
"tensorflow.global_variables_initializer",
"tensorflow.placeholder_with_default",
"tensorflow.sparse_tensor_to_dense",
"tensorflow.Session",
"kcore.compute_kcore",
"time.time",
"scipy.sparse.triu",
"numpy.mean",
"input_data.load_adj_feature"... | [((3122, 3209), 'input_data.load_adj_feature', 'load_adj_feature', (['"""../Cross-talk/Fegs_1.npy"""', '"""../Cross-talk/Cross-talk_Matrix.txt"""'], {}), "('../Cross-talk/Fegs_1.npy',\n '../Cross-talk/Cross-talk_Matrix.txt')\n", (3138, 3209), False, 'from input_data import load_adj_feature\n'), ((4033, 4044), 'time.... |
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon En... | [
"aggregator.filters.models.Filter.objects._find_enabled_filters_by_type",
"aggregator.filters.models.Filter",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"aggregator.filters.models.Filter.objects._create_timeframe",
"tests.fixture_manager.get_fixtures",
"aggregator.filters.mode... | [((1299, 1351), 'tests.fixture_manager.get_fixtures', 'get_fixtures', (["['followees', 'filters', 'reservoirs']"], {}), "(['followees', 'filters', 'reservoirs'])\n", (1311, 1351), False, 'from tests.fixture_manager import get_fixtures\n'), ((1605, 1648), 'django.contrib.contenttypes.models.ContentType.objects.get_for_m... |
#!/usr/bin/env python3
# This file reads in "HTML" from a call to
# thrift --gen html ....
# and does some post-processing to it.
# 1. It wraps struct headers + div definitions
# in a div.
# 2. It reorders struct divs to be alphabetically
# ordered.
from bs4 import BeautifulSoup
import fileinput
import loggin... | [
"fileinput.input",
"logging.getLogger",
"logging.basicConfig"
] | [((425, 446), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (444, 446), False, 'import logging\n'), ((460, 496), 'logging.getLogger', 'logging.getLogger', (['"""make_nice_lines"""'], {}), "('make_nice_lines')\n", (477, 496), False, 'import logging\n'), ((547, 564), 'fileinput.input', 'fileinput.input'... |
import math
def two_point_distance(x1, y1, x2, y2):
"""
Calculates distance between two given points.
x1 - X Value of Point 1
y1 - Y Value of Point 1
x2 - X Value of Point 2
y2 - Y Value of Point 2
"""
return math.fabs(math.hypot(x2 - x1, y2 - y1))
def get_closest_enemy(search_squa... | [
"math.hypot"
] | [((255, 283), 'math.hypot', 'math.hypot', (['(x2 - x1)', '(y2 - y1)'], {}), '(x2 - x1, y2 - y1)\n', (265, 283), False, 'import math\n')] |
from collections import Counter
t = int(input())
for _ in range(t):
s = input()
firstOne = -1
lastOne = -1
for i in range(len(s)):
if s[i] == '1':
if firstOne == -1:
firstOne = i
else:
lastOne = i
if firstOne > -1 and lastOne > -1:
... | [
"collections.Counter"
] | [((330, 358), 'collections.Counter', 'Counter', (['s[firstOne:lastOne]'], {}), '(s[firstOne:lastOne])\n', (337, 358), False, 'from collections import Counter\n')] |
import numpy as np
import pandas as pd
from dstk.preprocessing import (onehot_encode,
mark_binary,
nan_to_binary,
num_to_str)
# Create test data
df = pd.DataFrame()
df['numeric1'] = [0, 1, 0, 0, 1, 1]
df['numeric2'] = [1.0... | [
"pandas.DataFrame",
"dstk.preprocessing.nan_to_binary",
"numpy.isnan",
"dstk.preprocessing.onehot_encode",
"dstk.preprocessing.num_to_str",
"dstk.preprocessing.mark_binary"
] | [((248, 262), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (260, 262), True, 'import pandas as pd\n'), ((597, 625), 'dstk.preprocessing.num_to_str', 'num_to_str', (['df', "['numeric1']"], {}), "(df, ['numeric1'])\n", (607, 625), False, 'from dstk.preprocessing import onehot_encode, mark_binary, nan_to_binary, ... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test():
for itype in ["i8", "u8", "i32", "u32", "i64"]:
form = ak.forms.ListO... | [
"awkward.forms.EmptyForm"
] | [((337, 357), 'awkward.forms.EmptyForm', 'ak.forms.EmptyForm', ([], {}), '()\n', (355, 357), True, 'import awkward as ak\n')] |
import logging
import time
from io import IOBase
from typing import Callable
from typing import Any
from .base import Context
from tftpy.states import Start
logger = logging.getLogger('tftpy.context.server')
class Server(Context):
"""The context for the server."""
def __init__(self, host... | [
"tftpy.states.Start",
"logging.getLogger",
"time.time"
] | [((179, 220), 'logging.getLogger', 'logging.getLogger', (['"""tftpy.context.server"""'], {}), "('tftpy.context.server')\n", (196, 220), False, 'import logging\n'), ((1275, 1286), 'tftpy.states.Start', 'Start', (['self'], {}), '(self)\n', (1280, 1286), False, 'from tftpy.states import Start\n'), ((1980, 1991), 'time.tim... |
from functools import partial
from pyramid.view import view_defaults
from pyramid.view import view_config
from c2cgeoform.schema import GeoFormSchemaNode
from c2cgeoform.views.abstract_views import ListField
from deform.widget import FormWidget
from c2cgeoportal_admin.schemas.treegroup import children_schema_node
fro... | [
"functools.partial",
"deform.widget.FormWidget",
"c2cgeoportal_admin.schemas.treegroup.children_schema_node",
"pyramid.view.view_config",
"pyramid.view.view_defaults",
"c2cgeoportal_admin.schemas.metadata.metadatas_schema_node.clone",
"c2cgeoportal_admin.schemas.treeitem.parent_id_node"
] | [((594, 624), 'functools.partial', 'partial', (['ListField', 'LayerGroup'], {}), '(ListField, LayerGroup)\n', (601, 624), False, 'from functools import partial\n'), ((926, 973), 'pyramid.view.view_defaults', 'view_defaults', ([], {'match_param': '"""table=layer_groups"""'}), "(match_param='table=layer_groups')\n", (939... |
import os
import wave
from io import BytesIO, BufferedIOBase
from tempfile import NamedTemporaryFile
import pytest
from audoai.noise_removal import NoiseRemovalClient
@pytest.fixture()
def noise_removal() -> NoiseRemovalClient:
api_key = os.environ['AUDO_API_KEY']
base_url = os.environ['AUDO_BASE_URL']
n... | [
"wave.open",
"tempfile.NamedTemporaryFile",
"pytest.fixture",
"pytest.raises",
"audoai.noise_removal.NoiseRemovalClient"
] | [((171, 187), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (185, 187), False, 'import pytest\n'), ((401, 417), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (415, 417), False, 'import pytest\n'), ((335, 372), 'audoai.noise_removal.NoiseRemovalClient', 'NoiseRemovalClient', (['api_key', 'base_url'], {})... |
import re
from janome.tokenizer import Tokenizer
# rules : {boolean function(word):label}
# txt: str
def rule_base_ner(rules,txt):
tokenizer = Tokenizer()
tokens = tokenizer.tokenize(txt)
history = []
for t in tokens:
word = t.surface
for rule,label in rules.items():
if rule... | [
"janome.tokenizer.Tokenizer",
"re.sub"
] | [((148, 159), 'janome.tokenizer.Tokenizer', 'Tokenizer', ([], {}), '()\n', (157, 159), False, 'from janome.tokenizer import Tokenizer\n'), ((449, 486), 're.sub', 're.sub', (['word', '(tag1 + word + tag2)', 'txt'], {}), '(word, tag1 + word + tag2, txt)\n', (455, 486), False, 'import re\n')] |
# Notes:
# For fixing multi-press See: https://raspberrypi.stackexchange.com/questions/28955/unwanted-multiple-presses-when-using-gpio-button-press-detection
# Supported file types: https://picamera.readthedocs.io/en/release-1.10/api_camera.html#picamera.camera.PiCamera.capture
# 'jpeg' - Write a JPEG file
# 'png... | [
"camera_handler.stop_camera",
"document_handler.check_for_folders",
"camera_handler.start_camera"
] | [((5870, 5912), 'document_handler.check_for_folders', 'document_handler.check_for_folders', (['config'], {}), '(config)\n', (5904, 5912), False, 'import document_handler\n'), ((6207, 6242), 'camera_handler.start_camera', 'camera_handler.start_camera', (['config'], {}), '(config)\n', (6234, 6242), False, 'import camera_... |
import time
from revscoring import Datasource, Feature, Model
from revscoring.datasources.revision_oriented import revision
from revscoring.scoring import ModelInfo
from revscoring.scoring.statistics import Classification
def process_last_two_in_rev_id(rev_id):
last_two = str(rev_id)[-2:]
if len(last_two) ==... | [
"revscoring.Feature",
"revscoring.scoring.ModelInfo",
"time.sleep",
"revscoring.Datasource",
"revscoring.scoring.statistics.Classification"
] | [((411, 510), 'revscoring.Datasource', 'Datasource', (['"""revision.last_two_in_rev_id"""', 'process_last_two_in_rev_id'], {'depends_on': '[revision.id]'}), "('revision.last_two_in_rev_id', process_last_two_in_rev_id,\n depends_on=[revision.id])\n", (421, 510), False, 'from revscoring import Datasource, Feature, Mod... |
# -*- coding: utf-8 -*-
# 创建信号
import datetime
import dictdiffer
from django.dispatch import Signal
from django.apps import apps as django_apps
import json
def format_value(value):
"""格式化数据"""
if isinstance(value, datetime.datetime):
return value.strftime('%Y-%m-%d %H:%M:%S')
return value
def s... | [
"dictdiffer.diff",
"dictdiffer.utils.dot_lookup",
"django.dispatch.Signal",
"django.apps.apps.get_model"
] | [((2227, 2235), 'django.dispatch.Signal', 'Signal', ([], {}), '()\n', (2233, 2235), False, 'from django.dispatch import Signal\n'), ((2251, 2298), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['old_data', 'new_data']"}), "(providing_args=['old_data', 'new_data'])\n", (2257, 2298), False, 'from django.di... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | [
"os.path.isdir",
"glob.glob"
] | [((2372, 2397), 'glob.glob', 'glob.glob', (['"""guidelines/*"""'], {}), "('guidelines/*')\n", (2381, 2397), False, 'import glob\n'), ((2512, 2535), 'os.path.isdir', 'os.path.isdir', (['filename'], {}), '(filename)\n', (2525, 2535), False, 'import os\n')] |
from django.contrib import admin
from . import models
@admin.register(models.Lamp)
class LampAdmin(admin.ModelAdmin):
list_display = ('name', 'is_on', 'brightness')
ordering = ('name',)
@admin.register(models.WorkingPeriod)
class WorkingPeriodAdmin(admin.ModelAdmin):
list_display = ('lamp', 'brightne... | [
"django.contrib.admin.register"
] | [((58, 85), 'django.contrib.admin.register', 'admin.register', (['models.Lamp'], {}), '(models.Lamp)\n', (72, 85), False, 'from django.contrib import admin\n'), ((201, 237), 'django.contrib.admin.register', 'admin.register', (['models.WorkingPeriod'], {}), '(models.WorkingPeriod)\n', (215, 237), False, 'from django.con... |
import json
from typing import (
Any,
Dict,
List,
Optional,
)
import unittest
from unittest import (
mock,
)
import urllib.parse
from more_itertools import (
one,
)
import requests
from app_test_case import (
LocalAppTestCase,
)
from azul import (
cached_property,
config,
)
from az... | [
"unittest.main",
"azul.service.hca_response_v5.FileSearchResponse.add_facets",
"more_itertools.one",
"service.test_pagination.parse_url_qs",
"json.dumps",
"azul.indexer.BundleFQID",
"unittest.mock.patch",
"azul.config.es_index_name",
"azul.logging.configure_test_logging",
"requests.get",
"azul.i... | [((820, 844), 'azul.logging.configure_test_logging', 'configure_test_logging', ([], {}), '()\n', (842, 844), False, 'from azul.logging import configure_test_logging\n'), ((95908, 95961), 'unittest.mock.patch', 'mock.patch', (['"""azul.portal_service.PortalService._crud"""'], {}), "('azul.portal_service.PortalService._c... |
#! /usr/bin/env python3
import os
import sys
def error(msg):
print(msg)
print(f"Usage: {sys.argv[0]} FILE.gitp8")
print(" Converts FILE.gitp8 in merge-friendly format to FILE.p8 in pico-8 format.")
sys.exit(1)
if len(sys.argv) < 2 or len(sys.argv) > 2:
error("Exactly 1 argument required.")
if n... | [
"os.path.exists",
"sys.exit"
] | [((1872, 1900), 'os.path.exists', 'os.path.exists', (["(base + '.p8')"], {}), "(base + '.p8')\n", (1886, 1900), False, 'import os\n'), ((217, 228), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (225, 228), False, 'import sys\n'), ((323, 350), 'os.path.exists', 'os.path.exists', (['sys.argv[1]'], {}), '(sys.argv[1])\n... |
"""Utilities for multiprocessing."""
from contextlib import contextmanager
import logging
import time
from dask.distributed import Client, LocalCluster, progress
from dask_jobqueue import PBSCluster
import numpy as np
_logger = logging.getLogger(__name__)
def map_function(function, function_args, pbs=False, **clust... | [
"dask.distributed.Client",
"dask.distributed.LocalCluster",
"time.sleep",
"numpy.shape",
"dask.distributed.progress",
"numpy.array",
"dask_jobqueue.PBSCluster",
"logging.getLogger"
] | [((230, 257), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (247, 257), False, 'import logging\n'), ((2557, 2572), 'dask.distributed.Client', 'Client', (['cluster'], {}), '(cluster)\n', (2563, 2572), False, 'from dask.distributed import Client, LocalCluster, progress\n'), ((2619, 2632), ... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# CloudWatch Custom Widget sample: call any read-only AWS API and return raw results in JSON
import boto3
import json
import os
import re
DOCS = """
## Make an AWS Call
Calls any (read-only) AWS API and displays the ... | [
"re.sub",
"boto3.client",
"json.dumps"
] | [((1108, 1129), 'boto3.client', 'boto3.client', (['service'], {}), '(service)\n', (1120, 1129), False, 'import boto3\n'), ((1233, 1280), 'json.dumps', 'json.dumps', (['result'], {'sort_keys': '(True)', 'default': 'str'}), '(result, sort_keys=True, default=str)\n', (1243, 1280), False, 'import json\n'), ((901, 939), 're... |
import time
from testtools import TestResult
from logging import (
Formatter,
Logger,
INFO,
)
from six import b
from mimeparse import parse_mime_type
from testtools import TestCase
from testlogging import SubunitHandler
from testlogging.testing import StreamResultDouble
class SubunitHandlerTest(Test... | [
"testtools.TestResult",
"testlogging.testing.StreamResultDouble",
"testlogging.SubunitHandler",
"logging.Logger",
"logging.Formatter",
"mimeparse.parse_mime_type",
"time.time",
"six.b"
] | [((419, 439), 'testlogging.testing.StreamResultDouble', 'StreamResultDouble', ([], {}), '()\n', (437, 439), False, 'from testlogging.testing import StreamResultDouble\n'), ((463, 479), 'testlogging.SubunitHandler', 'SubunitHandler', ([], {}), '()\n', (477, 479), False, 'from testlogging import SubunitHandler\n'), ((546... |
import numpy as np
import gym
import gym_carsim
from gym import spaces
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory
ENV_NAME = ... | [
"rl.memory.SequentialMemory",
"rl.agents.dqn.DQNAgent",
"numpy.random.seed",
"gym.make",
"keras.layers.Activation",
"keras.layers.Flatten",
"rl.policy.BoltzmannQPolicy",
"keras.optimizers.Adam",
"gym.ObservationWrapper.__init__",
"keras.layers.Dense",
"gym.spaces.Box",
"keras.models.Sequential... | [((1015, 1033), 'gym.make', 'gym.make', (['ENV_NAME'], {}), '(ENV_NAME)\n', (1023, 1033), False, 'import gym\n'), ((1061, 1085), 'numpy.random.seed', 'np.random.seed', (['(98283476)'], {}), '(98283476)\n', (1075, 1085), True, 'import numpy as np\n'), ((1422, 1434), 'keras.models.Sequential', 'Sequential', ([], {}), '()... |
#!/usr/bin/env python
# encoding: utf-8
"""
pytimeNSW
~~~~~~~~~~~~~
A easy-use module to solve the datetime needs by string.
:copyright: (c) 2017 by <NAME> <<EMAIL>>
:license: MIT, see LICENSE for more details.
"""
import datetime
import calendar
from .filter import BaseParser
bp = BaseParser.... | [
"datetime.date",
"datetime.date.today",
"datetime.timedelta",
"datetime.datetime.min.time",
"calendar.monthrange",
"datetime.datetime.now"
] | [((762, 783), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (781, 783), False, 'import datetime\n'), ((796, 819), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (817, 819), False, 'import datetime\n'), ((892, 918), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}),... |
from pyml.tree.regression import DecisionTreeRegressor
from pyml.metrics.pairwise import euclidean_distance
import numpy as np
# TODO: 使用平方误差,还是绝对值误差,还是Huber Loss
class GradientBoostingRegression():
def __init__(self,
learning_rate=0.1,
base_estimator=DecisionTreeRegressor,
n_estimators=500... | [
"numpy.zeros",
"pyml.metrics.pairwise.euclidean_distance",
"numpy.array"
] | [((2317, 2533), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9, \n 10], [4, 5, 6, 7, 8, 9, 10, 11], [5, 6, 7, 8, 9, 10, 11, 12], [6, 7, 8,\n 9, 10, 11, 12, 13], [7, 8, 9, 10, 11, 12, 13, 14]]'], {}), '([[1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 9], [3... |
class TestSet5:
def test_challenge33(self):
from cryptopals.set5.challenge33 import challenge33
assert challenge33(), "The result does not match the expected value"
def test_challenge34(self):
from cryptopals.set5.challenge34 import challenge34
assert challenge34(), "The resul... | [
"cryptopals.set5.challenge34.challenge34",
"cryptopals.set5.challenge33.challenge33",
"cryptopals.set5.challenge35.challenge35"
] | [((124, 137), 'cryptopals.set5.challenge33.challenge33', 'challenge33', ([], {}), '()\n', (135, 137), False, 'from cryptopals.set5.challenge33 import challenge33\n'), ((295, 308), 'cryptopals.set5.challenge34.challenge34', 'challenge34', ([], {}), '()\n', (306, 308), False, 'from cryptopals.set5.challenge34 import chal... |
from pymarkauth import MarkDown
with MarkDown('../README.md') as doc:
sec = doc.section("PyMarkAuth")
sec.paragraphs(
'With PyMarkAuth you can author markdown code simply from python code.'
' To view the source code that generated this readme, take a look at the examples directory!',
)
... | [
"pymarkauth.MarkDown"
] | [((38, 62), 'pymarkauth.MarkDown', 'MarkDown', (['"""../README.md"""'], {}), "('../README.md')\n", (46, 62), False, 'from pymarkauth import MarkDown\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#############################################################################
# Copyright (c): 2021, Huawei Tech. Co., Ltd.
# FileName : agent_collect.py
# Version :
# Date : 2021-4-7
# Description : Receives and stores agent data.
###########################... | [
"common.logger.CreateLogger",
"os.path.dirname",
"service.datafactory.storage.insert_data_to_database.SaveData"
] | [((794, 829), 'common.logger.CreateLogger', 'CreateLogger', (['"""debug"""', '"""server.log"""'], {}), "('debug', 'server.log')\n", (806, 829), False, 'from common.logger import CreateLogger\n'), ((522, 547), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (537, 547), False, 'import os\n'), ((... |
from selenium import webdriver
from realtimekeyword import getNaverRealtimekeyword
import time
from bs4 import BeautifulSoup
class TistoryPostingBot:
def __init__(self,driver, dir, id,password):
self.id = id
self.dir =dir
self.password = password
self.driver = driver
retur... | [
"time.sleep"
] | [((1323, 1336), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1333, 1336), False, 'import time\n')] |
#form.py
from flask_wtf import FlaskForm
from wtforms import StringField , PasswordField , SubmitField , BooleanField #導入用途是為了建立表單
from wtforms.validators import DataRequired, Length , Email , EqualTo , ValidationError #導入用途是為了建立表單 ValidationError是檢視重複輸入
from app.models import User
class RegisterForm(Flask... | [
"wtforms.validators.Length",
"wtforms.validators.Email",
"wtforms.BooleanField",
"wtforms.SubmitField",
"app.models.User.query.filter_by",
"wtforms.validators.EqualTo",
"wtforms.validators.DataRequired",
"wtforms.validators.ValidationError"
] | [((755, 778), 'wtforms.SubmitField', 'SubmitField', (['"""Register"""'], {}), "('Register')\n", (766, 778), False, 'from wtforms import StringField, PasswordField, SubmitField, BooleanField\n'), ((1465, 1489), 'wtforms.BooleanField', 'BooleanField', (['"""Remember"""'], {}), "('Remember')\n", (1477, 1489), False, 'from... |
# was stanza.models.pos.model
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence
from biaffine import BiaffineScorer
from hlstm import HighwayLSTM
from dropout import WordDropout
... | [
"torch.nn.Dropout",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.from_numpy",
"biaffine.BiaffineScorer",
"torch.nn.ModuleList",
"dropout.WordDropout",
"torch.nn.CrossEntropyLoss",
"torch.cat",
"torch.nn.utils.rnn.PackedSequence",
"torch.zeros",
"torch.randn",
"torch.nn.Linear",
"hlstm.H... | [((2077, 2308), 'hlstm.HighwayLSTM', 'HighwayLSTM', (['input_size', "self.args['tag_hidden_dim']", "self.args['tag_num_layers']"], {'batch_first': '(True)', 'bidirectional': '(True)', 'dropout': "self.args['dropout']", 'rec_dropout': "self.args['tag_rec_dropout']", 'highway_func': 'torch.tanh'}), "(input_size, self.arg... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | [
"heat.engine.constraints.AllowedValues",
"heat.engine.constraints.CustomConstraint",
"heat.engine.support.SupportStatus",
"heat.common.i18n._",
"heat.common.exception.Error"
] | [((867, 906), 'heat.engine.support.SupportStatus', 'support.SupportStatus', ([], {'version': '"""2014.2"""'}), "(version='2014.2')\n", (888, 906), False, 'from heat.engine import support\n'), ((1816, 1856), 'heat.common.i18n._', '_', (['"""Human readable name for the secret."""'], {}), "('Human readable name for the se... |
import os
import torch
from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log
from torch.distributed import init_process_group
def init_w_ps(builder):
from patrickstar.runtime import initialize_engine
config = CONFIG.copy()
rank = int(os.environ['RANK'])
world_size = int(os.environ['WOR... | [
"zero.common.utils.CONFIG.get",
"torch.cuda.set_per_process_memory_fraction",
"torch.distributed.init_process_group",
"patrickstar.runtime.initialize_engine",
"torch.cuda.set_device",
"zero.common.utils.get_gpu_memory_mb",
"zero.common.utils.CONFIG.copy"
] | [((234, 247), 'zero.common.utils.CONFIG.copy', 'CONFIG.copy', ([], {}), '()\n', (245, 247), False, 'from zero.common.utils import CONFIG, get_gpu_memory_mb, print_log\n'), ((414, 523), 'torch.distributed.init_process_group', 'init_process_group', ([], {'rank': 'rank', 'world_size': 'world_size', 'init_method': 'f"""tcp... |
#!/usr/bin/env python
import rospy
import random
import time
import os
from gazebo_msgs.srv import SpawnModel, DeleteModel
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Pose
import pdb;
class Respawn():
def __init__(self):
self.modelPath = os.path.dirname(os.path.realpath(__file__))... | [
"rospy.Subscriber",
"os.path.realpath",
"rospy.ServiceProxy",
"time.sleep",
"rospy.loginfo",
"random.randrange",
"rospy.wait_for_service",
"geometry_msgs.msg.Pose"
] | [((488, 494), 'geometry_msgs.msg.Pose', 'Pose', ([], {}), '()\n', (492, 494), False, 'from geometry_msgs.msg import Pose\n'), ((1072, 1141), 'rospy.Subscriber', 'rospy.Subscriber', (['"""gazebo/model_states"""', 'ModelStates', 'self.checkModel'], {}), "('gazebo/model_states', ModelStates, self.checkModel)\n", (1088, 11... |
"""Unit tests for orbitpy.util module.
"""
import unittest
import numpy as np
from numpy.core.numeric import tensordot
from instrupy.util import Orientation
from instrupy import Instrument
from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft
import orbitpy.util
import propcov
from util.spacecrafts import sp... | [
"orbitpy.util.OrbitState.from_json",
"orbitpy.util.OrbitState.state_from_dict",
"propcov.Rvector6",
"numpy.deg2rad",
"orbitpy.util.SpacecraftBus.from_json",
"propcov.AbsoluteDate.fromJulianDate",
"instrupy.Instrument.from_json",
"orbitpy.util.OrbitState.date_from_dict",
"orbitpy.util.Spacecraft.from... | [((442, 515), 'orbitpy.util.OrbitState.date_from_dict', 'OrbitState.date_from_dict', (["{'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75}"], {}), "({'@type': 'JULIAN_DATE_UT1', 'jd': 2459270.75})\n", (467, 515), False, 'from orbitpy.util import OrbitState, SpacecraftBus, Spacecraft\n'), ((582, 713), 'orbitpy.util.OrbitSta... |