code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
# convert csv files to .md files with front-matter
import sys
import csv
import frontmatter
from pathlib import Path
from itertools import chain
from decimal import Decimal
table = {}
def dump(_table):
for name, row in table[_table].items():
directory = "content/%s" % _table
... | [
"decimal.Decimal",
"pathlib.Path",
"frontmatter.dump",
"frontmatter.Post",
"itertools.chain.from_iterable"
] | [((2190, 2217), 'itertools.chain.from_iterable', 'chain.from_iterable', (['ranges'], {}), '(ranges)\n', (2209, 2217), False, 'from itertools import chain\n'), ((733, 755), 'frontmatter.Post', 'frontmatter.Post', (['text'], {}), '(text)\n', (749, 755), False, 'import frontmatter\n'), ((885, 910), 'frontmatter.dump', 'fr... |
import torch
from torch.nn.utils import parameters_to_vector, vector_to_parameters
from torch.distributions.kl import kl_divergence as kl
from baselines import logger
from proj.utils.saver import SnapshotSaver
from proj.utils.tqdm_util import trange
from proj.utils.torch_util import flat_grad
from proj.common.models im... | [
"baselines.logger.dumpkvs",
"torch.nn.MSELoss",
"proj.common.sampling.parallel_samples_collector",
"proj.common.env_makers.VecEnvMaker",
"proj.common.sampling.compute_pg_vars",
"proj.common.hf_util.conjugate_gradient",
"torch.distributions.kl.kl_divergence",
"baselines.logger.get_dir",
"proj.common.... | [((1288, 1306), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (1304, 1306), False, 'import torch\n'), ((1350, 1400), 'proj.common.sampling.parallel_samples_collector', 'parallel_samples_collector', (['vec_env', 'policy', 'steps'], {}), '(vec_env, policy, steps)\n', (1376, 1400), False, 'from proj.common.sam... |
import logging
import os
config = {
'version': 1,
'formatters': {
'console': {
'format' : '%(message)s',
},
'default': {
'format' : '%(asctime)s %(levelname)-8s %(module)s.%(funcName)s -- %(message)s',
'datefmt' : '%Y-%m-%d %H:%M:%S',
},
}... | [
"os.path.dirname",
"os.path.exists",
"os.makedirs"
] | [((1774, 1826), 'os.path.dirname', 'os.path.dirname', (["config['handlers'][key]['filename']"], {}), "(config['handlers'][key]['filename'])\n", (1789, 1826), False, 'import os\n'), ((1842, 1865), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (1856, 1865), False, 'import os\n'), ((1879, 1899), 'o... |
""" Rasterize
Module to rasterize a shapely polygon to a Numpy Array
Author: <NAME>
(University of Antwerp, Belgium)
"""
import numpy as np
from rasterio.features import rasterize as rasterioRasterize
from shapely.geometry import Polygon, MultiPolygon, Point
from np2Geotiff import *
def rasterize(mpol, res ... | [
"numpy.flip",
"numpy.ceil",
"shapely.geometry.Polygon",
"numpy.zeros",
"shapely.geometry.MultiPolygon",
"numpy.min",
"numpy.rot90",
"numpy.max",
"numpy.array"
] | [((2038, 2060), 'numpy.zeros', 'np.zeros', (['(rows, cols)'], {}), '((rows, cols))\n', (2046, 2060), True, 'import numpy as np\n'), ((3295, 3315), 'numpy.flip', 'np.flip', (['arr'], {'axis': '(0)'}), '(arr, axis=0)\n', (3302, 3315), True, 'import numpy as np\n'), ((1301, 1321), 'shapely.geometry.MultiPolygon', 'MultiPo... |
# admin page unit tests.
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
# allow us to generate URLs for our Django admin page.
from django.test import Client
# will allow us to make test requests to our application in our unit tests.
class AdminSiteTe... | [
"django.urls.reverse",
"django.contrib.auth.get_user_model",
"django.test.Client"
] | [((566, 574), 'django.test.Client', 'Client', ([], {}), '()\n', (572, 574), False, 'from django.test import Client\n'), ((1660, 1697), 'django.urls.reverse', 'reverse', (['"""admin:core_user_changelist"""'], {}), "('admin:core_user_changelist')\n", (1667, 1697), False, 'from django.urls import reverse\n'), ((2848, 2902... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2009-2015 <NAME>
#
# This program 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, either version 3 of the License, or
# (at your option) any l... | [
"datetime.date.today"
] | [((2283, 2298), 'datetime.date.today', 'dt.date.today', ([], {}), '()\n', (2296, 2298), True, 'import datetime as dt\n')] |
import json
import PIL
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import tensor
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms
import torchvision.models as... | [
"torch.nn.Dropout",
"numpy.argmax",
"torch.nn.NLLLoss",
"torchvision.transforms.Normalize",
"torch.no_grad",
"torch.utils.data.DataLoader",
"torchvision.transforms.RandomRotation",
"torch.load",
"torch.exp",
"torch.nn.Linear",
"torchvision.transforms.CenterCrop",
"torchvision.models.vgg16",
... | [((1349, 1408), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['train_dir'], {'transform': 'train_transforms'}), '(train_dir, transform=train_transforms)\n', (1369, 1408), False, 'from torchvision import datasets, transforms\n'), ((1421, 1478), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', ... |
from django.urls import reverse
from django.views.generic import RedirectView
from mymoney.apps.bankaccounts.models import BankAccount
class HomePageRedirectView(RedirectView):
"""
Homepage view which redirect user on:
- login page for anonymous
- bank transaction list page of the only one available ... | [
"mymoney.apps.bankaccounts.models.BankAccount.objects.get_user_bankaccounts",
"django.urls.reverse"
] | [((567, 614), 'mymoney.apps.bankaccounts.models.BankAccount.objects.get_user_bankaccounts', 'BankAccount.objects.get_user_bankaccounts', (['user'], {}), '(user)\n', (608, 614), False, 'from mymoney.apps.bankaccounts.models import BankAccount\n'), ((802, 830), 'django.urls.reverse', 'reverse', (['"""bankaccounts:list"""... |
"""Tests for measure_mapping file."""
from claims_to_quality.analyzer import measure_mapping
from claims_to_quality.analyzer.calculation import intersecting_diagnosis_measure
from claims_to_quality.analyzer.calculation.patient_process_measure import PatientProcessMeasure
from claims_to_quality.analyzer.datasource impor... | [
"claims_to_quality.config.config.reload_config",
"claims_to_quality.analyzer.measure_mapping.get_all_measure_ids",
"claims_to_quality.analyzer.measure_mapping.get_measure_calculators",
"pytest.raises",
"claims_to_quality.analyzer.measure_mapping.get_measure_calculator",
"claims_to_quality.config.config.ge... | [((499, 559), 'claims_to_quality.analyzer.measure_mapping.get_measure_calculator', 'measure_mapping.get_measure_calculator', ([], {'measure_number': '"""047"""'}), "(measure_number='047')\n", (537, 559), False, 'from claims_to_quality.analyzer import measure_mapping\n'), ((763, 786), 'pytest.raises', 'pytest.raises', (... |
import tkinter
import random
import pygame
import BlackJack
import subprocess as sub
p = sub.Popen('./BlackJack',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output)
root.mainloop()
# root = tkinter.Tk()
# root.geometry('480x460')
# roo... | [
"subprocess.Popen"
] | [((91, 149), 'subprocess.Popen', 'sub.Popen', (['"""./BlackJack"""'], {'stdout': 'sub.PIPE', 'stderr': 'sub.PIPE'}), "('./BlackJack', stdout=sub.PIPE, stderr=sub.PIPE)\n", (100, 149), True, 'import subprocess as sub\n')] |
"""
Python helper for Semantic Versioning (http://semver.org/)
"""
from __future__ import print_function
import argparse
import collections
from functools import wraps
import re
import sys
__version__ = '2.9.0'
__author__ = '<NAME>'
__author_email__ = '<EMAIL>'
__maintainer__ = '<NAME>'
__maintainer_email__ = "<EMAI... | [
"argparse.ArgumentParser",
"re.match",
"functools.wraps",
"collections.OrderedDict",
"doctest.testmod",
"re.compile"
] | [((334, 765), 're.compile', 're.compile', (['"""\n ^\n (?P<major>(?:0|[1-9][0-9]*))\n \\\\.\n (?P<minor>(?:0|[1-9][0-9]*))\n \\\\.\n (?P<patch>(?:0|[1-9][0-9]*))\n (\\\\-(?P<prerelease>\n (?:0|[1-9A-Za-z-][0-9A-Za-z-]*)\n (\\\\.(?:0|[1-9A-Za-z-][0-9... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver as FirefoxDriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.remote.webdriver import WebDriver as RemoteDriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import loggi... | [
"selenium.webdriver.common.desired_capabilities.DesiredCapabilities.FIREFOX.copy",
"selenium.webdriver.remote.webdriver.WebDriver",
"selenium.webdriver.firefox.options.Options",
"selenium.webdriver.firefox.webdriver.WebDriver",
"logging.getLogger"
] | [((402, 429), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (419, 429), False, 'import logging\n'), ((593, 602), 'selenium.webdriver.firefox.options.Options', 'Options', ([], {}), '()\n', (600, 602), False, 'from selenium.webdriver.firefox.options import Options\n'), ((1197, 1231), 'sele... |
#!/usr/bin/env python
import os.path
import sys
from setuptools import find_packages, setup
PACKAGE_NAME = "autofile"
if sys.version_info < (3, 8, 0):
sys.stderr.write(f"ERROR: You need Python 3.8 or later to use {PACKAGE_NAME}.\n")
exit(1)
# we'll import stuff from the source tree, let's ensure is on the ... | [
"sys.stderr.write",
"setuptools.find_packages"
] | [((159, 245), 'sys.stderr.write', 'sys.stderr.write', (['f"""ERROR: You need Python 3.8 or later to use {PACKAGE_NAME}.\n"""'], {}), "(\n f'ERROR: You need Python 3.8 or later to use {PACKAGE_NAME}.\\n')\n", (175, 245), False, 'import sys\n'), ((1226, 1267), 'setuptools.find_packages', 'find_packages', ([], {'exclud... |
try:
from zcrmsdk.src.com.zoho.crm.api.exception import SDKException
from zcrmsdk.src.com.zoho.crm.api.util import Constants
except Exception:
from ..exception import SDKException
from ..util import Constants
class PickListValue(object):
def __init__(self):
"""Creates an instance of PickListValue"""
self.__... | [
"zcrmsdk.src.com.zoho.crm.api.exception.SDKException"
] | [((983, 1079), 'zcrmsdk.src.com.zoho.crm.api.exception.SDKException', 'SDKException', (['Constants.DATA_TYPE_ERROR', '"""KEY: display_value EXPECTED TYPE: str"""', 'None', 'None'], {}), "(Constants.DATA_TYPE_ERROR,\n 'KEY: display_value EXPECTED TYPE: str', None, None)\n", (995, 1079), False, 'from zcrmsdk.src.com.z... |
#!/usr/bin/env python
# setup
# Setup script for installing calypso
#
# Author: <NAME> <<EMAIL>>
# Created: Wed Mar 15 12:56:08 2017 -0400
#
# Copyright (C) 2015 University of Maryland
# For license information, see LICENSE.txt
#
# ID: setup.py [] <EMAIL> $
"""
Setup script for installing calypso
"""
#############... | [
"setuptools.setup",
"setuptools.find_packages"
] | [((1148, 1247), 'setuptools.find_packages', 'find_packages', ([], {'where': '"""."""', 'exclude': "('tests', 'bin', 'docs', 'fixtures', 'register', 'notebooks')"}), "(where='.', exclude=('tests', 'bin', 'docs', 'fixtures',\n 'register', 'notebooks'))\n", (1161, 1247), False, 'from setuptools import find_packages\n')... |
# Generated by Django 3.0.1 on 2019-12-22 09:15
from django.db import migrations, models
from software_mining.models import Project, Build
def add_projects(apps, schema_editor):
data = Build.objects.values('project_name').annotate(c=models.Count('build_id'))
for item in data:
Project.objects.get_or_... | [
"django.db.migrations.RunPython",
"software_mining.models.Project.objects.get_or_create",
"django.db.models.Count",
"software_mining.models.Build.objects.values"
] | [((297, 353), 'software_mining.models.Project.objects.get_or_create', 'Project.objects.get_or_create', ([], {'name': "item['project_name']"}), "(name=item['project_name'])\n", (326, 353), False, 'from software_mining.models import Project, Build\n'), ((529, 595), 'django.db.migrations.RunPython', 'migrations.RunPython'... |
from setuptools import setup, find_packages
setup(name='microgrid',
version='0.0.1',
description='Multi-Agent Microgrid Environment',
url='https://github.com/hepengli/multiagent-microgrid-envs',
author='<NAME>',
author_email='<EMAIL>',
packages=find_packages(),
include_package... | [
"setuptools.find_packages"
] | [((282, 297), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (295, 297), False, 'from setuptools import setup, find_packages\n')] |
"""Test that javac is installed."""
import subprocess
from labm8.py import test
FLAGS = test.FLAGS
def test_javac_help():
"""Test that javac is installed."""
subprocess.check_call(["/usr/bin/javac", "-help"])
if __name__ == "__main__":
test.Main()
| [
"subprocess.check_call",
"labm8.py.test.Main"
] | [((166, 216), 'subprocess.check_call', 'subprocess.check_call', (["['/usr/bin/javac', '-help']"], {}), "(['/usr/bin/javac', '-help'])\n", (187, 216), False, 'import subprocess\n'), ((248, 259), 'labm8.py.test.Main', 'test.Main', ([], {}), '()\n', (257, 259), False, 'from labm8.py import test\n')] |
'''
Go through all artwork jsons and produce an index for
level0, level1, level2
Outputs a json collection
Does not preserve relationships between the levels
'''
import json
from os import walk
# use dict to elimiate duplicated entries as new entries
# are added as {'value of id': 'value of name'}
level0 = {}
... | [
"os.walk",
"json.loads",
"json.dumps"
] | [((410, 426), 'os.walk', 'walk', (['targetpath'], {}), '(targetpath)\n', (414, 426), False, 'from os import walk\n'), ((1078, 1133), 'json.dumps', 'json.dumps', (['data'], {'sort_keys': '(True)', 'separators': "(',', ':')"}), "(data, sort_keys=True, separators=(',', ':'))\n", (1088, 1133), False, 'import json\n'), ((56... |
from contextlib import redirect_stdout
def save_cfg(cfg, path):
with open(path, 'w') as f:
with redirect_stdout(f): print(cfg.dump())
def load_cfg(dir):
from mnists.config import cfg
cfg.merge_from_file(dir)
return cfg
| [
"mnists.config.cfg.dump",
"mnists.config.cfg.merge_from_file",
"contextlib.redirect_stdout"
] | [((205, 229), 'mnists.config.cfg.merge_from_file', 'cfg.merge_from_file', (['dir'], {}), '(dir)\n', (224, 229), False, 'from mnists.config import cfg\n'), ((109, 127), 'contextlib.redirect_stdout', 'redirect_stdout', (['f'], {}), '(f)\n', (124, 127), False, 'from contextlib import redirect_stdout\n'), ((135, 145), 'mni... |
import unittest
from Mojo.ObjectMapper.Fields import StringField, IntegerField, BooleanField, FloatField, ListField, ObjectIDField, DateTimeField
from Mojo.ObjectMapper.ModelPrototype import Model
from datetime import datetime
from tornado.ioloop import IOLoop
from tornado import testing
import Mojo.ServerHelpers.Run... | [
"Mojo.Backends.AsyncmongoBackend.asyncmongo_backend.Session",
"Mojo.ObjectMapper.Fields.StringField",
"Mojo.ObjectMapper.Fields.ListField",
"tornado.ioloop.IOLoop.instance",
"Mojo.ObjectMapper.Fields.ObjectIDField",
"Mojo.ObjectMapper.Fields.DateTimeField",
"Mojo.ObjectMapper.Fields.BooleanField",
"da... | [((367, 380), 'Mojo.ObjectMapper.Fields.StringField', 'StringField', ([], {}), '()\n', (378, 380), False, 'from Mojo.ObjectMapper.Fields import StringField, IntegerField, BooleanField, FloatField, ListField, ObjectIDField, DateTimeField\n'), ((419, 434), 'Mojo.ObjectMapper.Fields.ObjectIDField', 'ObjectIDField', ([], {... |
# -*- coding: utf-8 -*-
import exifread, requests, os, optparse
class Pic_Location:
def __init__(self, pic_dir='', pic=''):
self.pic_dir, self.pic = pic_dir, pic
# 百度ak信息,可自行申请
self.ak = '<KEY>'
def run(self):
return self.dir_file() if self.pic_dir else [self.exifread_infos(se... | [
"optparse.OptionParser",
"os.path.isdir",
"os.path.exists",
"exifread.process_file",
"requests.get",
"os.path.join",
"os.listdir"
] | [((2293, 2316), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (2314, 2316), False, 'import exifread, requests, os, optparse\n'), ((754, 778), 'exifread.process_file', 'exifread.process_file', (['f'], {}), '(f)\n', (775, 778), False, 'import exifread, requests, os, optparse\n'), ((398, 427), 'os.pa... |
from ffclub.base import admin
from django.contrib.admin import ModelAdmin
from .models import *
class ColorBundleAdmin(ModelAdmin):
list_filter = ['bg_color', 'font_color']
class ThemeCategoryAdmin(ModelAdmin):
search_fields = ['title', 'description']
list_filter = ['enabled']
class ThemeTemplateAdmin... | [
"ffclub.base.admin.site.register"
] | [((673, 723), 'ffclub.base.admin.site.register', 'admin.site.register', (['ColorBundle', 'ColorBundleAdmin'], {}), '(ColorBundle, ColorBundleAdmin)\n', (692, 723), False, 'from ffclub.base import admin\n'), ((724, 778), 'ffclub.base.admin.site.register', 'admin.site.register', (['ThemeCategory', 'ThemeCategoryAdmin'], ... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ImageViewSet, AlbumViewSet, UserViewSet
router = DefaultRouter()
router.register(r'image', ImageViewSet)
router.register(r'album', AlbumViewSet)
router.register(r'user', UserViewSet)
urlpatterns = [
path('', ... | [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((156, 171), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (169, 171), False, 'from rest_framework.routers import DefaultRouter\n'), ((320, 340), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (327, 340), False, 'from django.urls import path, include\n')] |
from instauto.api.client import ApiClient
import instauto.api.actions.structs.search as se
# This returns the first 10 search results, for 'instagram'.
client = ApiClient.initiate_from_file('.instauto.save')
obj = se.Username("instagram", 10)
response = client.search_username(obj)
| [
"instauto.api.actions.structs.search.Username",
"instauto.api.client.ApiClient.initiate_from_file"
] | [((162, 208), 'instauto.api.client.ApiClient.initiate_from_file', 'ApiClient.initiate_from_file', (['""".instauto.save"""'], {}), "('.instauto.save')\n", (190, 208), False, 'from instauto.api.client import ApiClient\n'), ((215, 243), 'instauto.api.actions.structs.search.Username', 'se.Username', (['"""instagram"""', '(... |
#!/usr/bin/python3
import logging
import os
import sys
import termcolor
class Env:
@staticmethod
def get_environment(env_name: str, default: str = '', required: bool = False) -> str:
env: str = os.environ.get(env_name, default)
if required and (default == '') and (env == ''):
sys.... | [
"os.environ.get",
"termcolor.colored",
"logging.getLogger"
] | [((794, 821), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (811, 821), False, 'import logging\n'), ((213, 246), 'os.environ.get', 'os.environ.get', (['env_name', 'default'], {}), '(env_name, default)\n', (227, 246), False, 'import os\n'), ((325, 396), 'termcolor.colored', 'termcolor.col... |
global cjk_list
global unicode_list
global cjk_jian_list
global cjk_jian_fan_list
global cjk_fan_list
global cjk_count
global unicode_count
import os, sys
global main_directory
#if packaged by pyinstaller
#ref: https://stackoverflow.com/questions/404744/determining-application-path-in-a-python-exe-gen... | [
"os.getcwd",
"os.path.dirname",
"os.path.realpath"
] | [((462, 493), 'os.path.dirname', 'os.path.dirname', (['sys.executable'], {}), '(sys.executable)\n', (477, 493), False, 'import os, sys\n'), ((820, 846), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (836, 846), False, 'import os, sys\n'), ((873, 903), 'os.path.dirname', 'os.path.dirname', ... |
#
# Copyright (c) 2019 <NAME>. All rights reserved.
#
# This product and it's source code is protected by patents, copyright laws and
# international copyright treaties, as well as other intellectual property
# laws and treaties. The product is licensed, not sold.
#
# The source code and sample programs in this package... | [
"configparser.ConfigParser"
] | [((833, 860), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (858, 860), False, 'import configparser\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# To allow python to run these tests as main script
import functools
import multiprocessing
import sys
import os
import threading
import types
from random import randint
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))... | [
"threading.Thread",
"functools.partial",
"random.randint",
"pyzmp.Node",
"os.path.dirname",
"multiprocessing.Manager",
"types.MethodType",
"time.sleep",
"pytest.main",
"time.time",
"pytest.mark.timeout"
] | [((571, 593), 'pytest.mark.timeout', 'pytest.mark.timeout', (['(5)'], {}), '(5)\n', (590, 593), False, 'import pytest\n'), ((1014, 1036), 'pytest.mark.timeout', 'pytest.mark.timeout', (['(5)'], {}), '(5)\n', (1033, 1036), False, 'import pytest\n'), ((1419, 1441), 'pytest.mark.timeout', 'pytest.mark.timeout', (['(5)'], ... |
import discord
import random
import requests
import json
import Util
from discord.ext import commands
from dpymenus import Page, PaginatedMenu
class Forest(commands.Cog):
"""
Contains commands regarding Blue Forest
"""
def __init__(self, client):
self.client = client
@commands.command(name = 'forest_leaderboa... | [
"random.randint",
"discord.ext.commands.command",
"Util.ErrorHandler",
"requests.get"
] | [((279, 431), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""forest_leaderboard"""', 'aliases': "['flb', 'forest_lb', 'cflb', 'bflb']", 'help': '"""Fetches top 10 users from Blue Forest Leaderboard."""'}), "(name='forest_leaderboard', aliases=['flb', 'forest_lb',\n 'cflb', 'bflb'], help='Fetch... |
import re
import django.db
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from .forms import PetForm, UpdateForm
from .models im... | [
"re.match",
"django.urls.reverse",
"django.shortcuts.get_object_or_404",
"django.shortcuts.render",
"django.http.HttpResponseRedirect"
] | [((457, 552), 'django.shortcuts.render', 'render', (['request', '"""communication_app/index.html"""', "{'my_pets': my_pets, 'pet_form': pet_form}"], {}), "(request, 'communication_app/index.html', {'my_pets': my_pets,\n 'pet_form': pet_form})\n", (463, 552), False, 'from django.shortcuts import render, get_object_or... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
def do_eject():
GPIO.output(17, True)
time.sleep(0.1)
GPIO.output(17, False)
class Handler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.... | [
"RPi.GPIO.setmode",
"http.server.HTTPServer",
"RPi.GPIO.cleanup",
"RPi.GPIO.setup",
"time.sleep",
"RPi.GPIO.output"
] | [((120, 142), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (132, 142), True, 'import RPi.GPIO as GPIO\n'), ((143, 167), 'RPi.GPIO.setup', 'GPIO.setup', (['(17)', 'GPIO.OUT'], {}), '(17, GPIO.OUT)\n', (153, 167), True, 'import RPi.GPIO as GPIO\n'), ((648, 681), 'http.server.HTTPServer', 'HTTPS... |
''' Routine tasks for keeping your library tidy '''
from datetime import timedelta
from django.utils import timezone
from fedireads import books_manager
from fedireads import models
def sync_book_data():
''' update books with any changes to their canonical source '''
expiry = timezone.now() - timedelta(days=1)... | [
"django.utils.timezone.now",
"datetime.timedelta",
"fedireads.books_manager.update_book",
"fedireads.models.Edition.objects.filter"
] | [((286, 300), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (298, 300), False, 'from django.utils import timezone\n'), ((303, 320), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (312, 320), False, 'from datetime import timedelta\n'), ((501, 532), 'fedireads.books_manager.updat... |
# !/usr/bin/dev python
# -*- coding:utf-8 -*-
"""
reference:
http://www.wooyun.org/bugs/wooyun-2015-0104157
http://www.beebeeto.com/pdb/poc-2015-0086/
"""
import re
import urllib
import urllib2
import base64
import random
def get_vote_links(args):
vul_url = args
vote_url = '%sindex.php?m=v... | [
"re.finditer",
"base64.b64encode",
"random.randint",
"urllib.urlencode"
] | [((416, 480), 're.finditer', 're.finditer', (['"""<a href=.*?subjectid=(?P<id>\\\\d+)"""', 'res', 're.DOTALL'], {}), "('<a href=.*?subjectid=(?P<id>\\\\d+)', res, re.DOTALL)\n", (427, 480), False, 'import re\n'), ((842, 869), 'base64.b64encode', 'base64.b64encode', (['file_name'], {}), '(file_name)\n', (858, 869), Fals... |
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from mozbadges.views import placeholder_view
import views
urlpatterns = patterns('',
(r'^teams', include(patterns('',
# /teams.json
url(r'^\.json$', views.team_list, name='json'),
(r'^/', include... | [
"django.conf.urls.defaults.url"
] | [((248, 294), 'django.conf.urls.defaults.url', 'url', (['"""^\\\\.json$"""', 'views.team_list'], {'name': '"""json"""'}), "('^\\\\.json$', views.team_list, name='json')\n", (251, 294), False, 'from django.conf.urls.defaults import patterns, url, include\n'), ((368, 406), 'django.conf.urls.defaults.url', 'url', (['"""^$... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 序列化一个对象
Desc :
"""
import pickle
def serailize_object():
data = [1, 2, 3]
f = open('somefile', 'wb')
pickle.dump(data, f)
# 将对象转储为字符串
s = pickle.dumps(data)
# Restore from a file
f = open('somefile', 'rb')
data = pickle.load... | [
"pickle.loads",
"pickle.dump",
"pickle.load",
"pickle.dumps"
] | [((175, 195), 'pickle.dump', 'pickle.dump', (['data', 'f'], {}), '(data, f)\n', (186, 195), False, 'import pickle\n'), ((221, 239), 'pickle.dumps', 'pickle.dumps', (['data'], {}), '(data)\n', (233, 239), False, 'import pickle\n'), ((309, 323), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (320, 323), False, 'impo... |
import pkgutil
import importlib
from packetracer.packetracer import Packet
module_packetracer = importlib.import_module("packetracer")
for importer, modname, ispkg in pkgutil.walk_packages(path=module_packetracer.__path__,
prefix=module_packetracer.__name__ + ".",
onerror=lambda x: None):
if ispkg:
#print(">>> ... | [
"packetracer.packetracer.Packet.__subclasses__",
"pkgutil.walk_packages",
"importlib.import_module"
] | [((97, 135), 'importlib.import_module', 'importlib.import_module', (['"""packetracer"""'], {}), "('packetracer')\n", (120, 135), False, 'import importlib\n'), ((169, 295), 'pkgutil.walk_packages', 'pkgutil.walk_packages', ([], {'path': 'module_packetracer.__path__', 'prefix': "(module_packetracer.__name__ + '.')", 'one... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"termcolor.cprint"
] | [((868, 911), 'termcolor.cprint', 'cprint', (["('\\n[DEBUG]%s:%s' % (component, msg))"], {}), "('\\n[DEBUG]%s:%s' % (component, msg))\n", (874, 911), False, 'from termcolor import cprint\n')] |
# -*- coding: utf-8 -*-
"""
This module consists of minimal working examples (MWEs) presenting how to use
the network interface and the implemented defense mechanisms.
"""
import defense_mechanisms as dms
import networks
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
# Let... | [
"networks.VGG19",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",
"keras.applications.vgg16.preprocess_input",
"defense_mechanisms.aggregate_predict_n_by"
] | [((423, 467), 'keras.preprocessing.image.load_img', 'image.load_img', (['path'], {'target_size': '(224, 224)'}), '(path, target_size=(224, 224))\n', (437, 467), False, 'from keras.preprocessing import image\n'), ((478, 501), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (496,... |
from ImageTypes import ImageTypes
class Satellite(object):
"""
http://satellite.imd.gov.in/dynamic/satfaq.pdf
"""
INSAT3D = "INSAT-3D-IMAGER"
KALPANA1 = "KALPANA-1"
BASE_URL = "http://satellite.imd.gov.in/archive/"
def __init__(self, sat_name):
self.image_type = None
self.... | [
"ImageTypes.ImageTypes"
] | [((363, 383), 'ImageTypes.ImageTypes', 'ImageTypes', (['sat_name'], {}), '(sat_name)\n', (373, 383), False, 'from ImageTypes import ImageTypes\n')] |
"""Тесты для проверки статуса дивидендов."""
import pandas as pd
import pytest
from poptimizer.data.views import div_status
from poptimizer.data.views.crop import div
from poptimizer.shared import col
def test_new_div_all(mocker):
"""Проверка типа и структуры результата."""
fake_raw_df = pd.DataFrame(
... | [
"pandas.DataFrame",
"pandas.testing.assert_frame_equal",
"poptimizer.data.views.div_status._new_div_all",
"poptimizer.data.views.div_status.new_dividends",
"pytest.approx",
"poptimizer.data.views.div_status.dividends_validation"
] | [((1091, 1295), 'pandas.DataFrame', 'pd.DataFrame', (["[['2020-10-01', 1], ['2020-10-02', 2], ['2021-02-27', None], ['2020-10-03',\n 3], ['2020-10-04', 4]]"], {'columns': '[col.DATE, col.DIVIDENDS]', 'index': "['NKNC', 'PLZL', 'T-RM', 'KZOS', 'TTLK']"}), "([['2020-10-01', 1], ['2020-10-02', 2], ['2021-02-27', None],... |
# python3
# Copyright 2020 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 applicab... | [
"ml_pipeline_gen.parsers.parse_yaml",
"os.path.dirname",
"jinja2.PackageLoader",
"jinja2.Environment",
"pathlib.Path",
"os.path.join"
] | [((1014, 1044), 'ml_pipeline_gen.parsers.parse_yaml', 'parse_yaml', (['template_spec_path'], {}), '(template_spec_path)\n', (1024, 1044), False, 'from ml_pipeline_gen.parsers import parse_yaml\n'), ((1096, 1164), 'jinja2.PackageLoader', 'jinja.PackageLoader', (['"""ml_pipeline_gen"""', "current_spec['template_dir']"], ... |
#!/usr/bin/env python3
import os
from datetime import datetime
import re
from dataclasses import dataclass
import pathlib
import numpy as np
import scipy.stats as stats
from analysis.parser.common import parse_contiki
@dataclass(frozen=True)
class LengthStats:
length: int
seconds: float
def us_to_s(us: int... | [
"argparse.ArgumentParser",
"os.path.basename",
"analysis.parser.common.parse_contiki",
"numpy.mean",
"scipy.stats.sem",
"scipy.stats.describe",
"dataclasses.dataclass",
"re.compile"
] | [((223, 245), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (232, 245), False, 'from dataclasses import dataclass\n'), ((474, 521), 're.compile', 're.compile', (['"""sha256\\\\(([0-9]+)\\\\), ([0-9]+) us"""'], {}), "('sha256\\\\(([0-9]+)\\\\), ([0-9]+) us')\n", (484, 521), False, ... |
import requests
from watson_developer_cloud import SpeechToTextV1, watson_service
from .speech_to_text import SpeechToText
from .speech_to_text_exception import SpeechToTextException
class WatsonSpeechToText(SpeechToText):
def __init__(self, credentials):
username = credentials.get('username')
pa... | [
"watson_developer_cloud.SpeechToTextV1",
"requests.get"
] | [((673, 725), 'watson_developer_cloud.SpeechToTextV1', 'SpeechToTextV1', ([], {'username': 'username', 'password': 'password'}), '(username=username, password=password)\n', (687, 725), False, 'from watson_developer_cloud import SpeechToTextV1, watson_service\n'), ((2061, 2084), 'requests.get', 'requests.get', (['audio_... |
#
#
# Author : fcbruce <<EMAIL>>
#
# Time : Tue 23 May 2017 22:32:41
#
#
import cv2
import sys
if __name__ == '__main__':
path = sys.argv[1]
img = cv2.imread(path)
sift = cv2.SIFT()
#sift = cv2.xfeatures2d.SIFT_create()
features = sift.detect(img)
for feature in features:
cv2.circle(... | [
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"cv2.SIFT",
"cv2.imshow"
] | [((158, 174), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (168, 174), False, 'import cv2\n'), ((187, 197), 'cv2.SIFT', 'cv2.SIFT', ([], {}), '()\n', (195, 197), False, 'import cv2\n'), ((445, 468), 'cv2.imshow', 'cv2.imshow', (['"""SIFT"""', 'img'], {}), "('SIFT', img)\n", (455, 468), False, 'import cv2\n')... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# file_name = input("Enter file name suffix (after Rpi_data_readings_cyclic_flow_rate): ")
file_path = "./Data_from_PropValves/Rpi_data_readings_cyclic_flow_rate_def2.csv"
header_names = ['Time', 'Actual Value' , 'Set Value', 'Pressure', 'Mass']
d... | [
"pandas.read_csv",
"matplotlib.pyplot.show"
] | [((324, 366), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'names': 'header_names'}), '(file_path, names=header_names)\n', (335, 366), True, 'import pandas as pd\n'), ((608, 618), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (616, 618), True, 'import matplotlib.pyplot as plt\n')] |
"""
message.py
"""
import logging, uuid, time
from types import SimpleNamespace
import marshmallow as ma
from microbot.util import make_uuid, make_time
log = logging.getLogger(__name__)
class Message(SimpleNamespace):
pass
class MessageSchema(ma.Schema):
# what is the purpose of this message
# ex. "in... | [
"marshmallow.fields.Int",
"marshmallow.validate.OneOf",
"marshmallow.fields.UUID",
"marshmallow.fields.Raw",
"marshmallow.fields.Str",
"logging.getLogger"
] | [((160, 187), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (177, 187), False, 'import logging, uuid, time\n'), ((545, 596), 'marshmallow.fields.Int', 'ma.fields.Int', ([], {'default': 'make_time', 'missing': 'make_time'}), '(default=make_time, missing=make_time)\n', (558, 596), True, 'i... |
# -*- coding: utf-8 -*-
#
# This module is part of the GeoTag-X PyBossa plugin.
# It contains implementations for custom filters.
#
# Authors:
# - <NAME> (<EMAIL>)
# - <NAME> (<EMAIL>)
#
# Copyright (c) 2016 UNITAR/UNOSAT
#
# The MIT License (MIT)
# Permission is hereby granted, free of charge, to any person obtaining ... | [
"math.exp",
"flask.Blueprint",
"json.loads",
"math.fabs",
"pybossa.exporter.json_export.JsonExporter",
"json.dumps",
"flask.jsonify",
"flask.current_app.config.keys",
"pybossa.cache.projects.get",
"numpy.unique"
] | [((1366, 1413), 'flask.Blueprint', 'Blueprint', (['"""geotagx-geojson-exporter"""', '__name__'], {}), "('geotagx-geojson-exporter', __name__)\n", (1375, 1413), False, 'from flask import Blueprint, current_app, jsonify\n'), ((2134, 2148), 'pybossa.exporter.json_export.JsonExporter', 'JsonExporter', ([], {}), '()\n', (21... |
# Generated by Django 2.0.5 on 2018-05-26 19:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | [
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.FloatField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.IntegerField",
... | [((276, 333), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (307, 333), False, 'from django.db import migrations, models\n'), ((6214, 6339), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', ... |
from .base_array import *
from .state_variables_array import *
import cantera as ct
import numpy as np
import scipy.interpolate as interp
class PressureArray(StateVariablesArray):
'''Variable array for pressure'''
def __init__(self, parent, var=None):
super().__init__(parent, var)
self.name = ... | [
"scipy.interpolate.interp1d",
"numpy.multiply"
] | [((814, 857), 'scipy.interpolate.interp1d', 'interp.interp1d', (['dis', 'phi_cgs'], {'kind': '"""cubic"""'}), "(dis, phi_cgs, kind='cubic')\n", (829, 857), True, 'import scipy.interpolate as interp\n'), ((1396, 1422), 'numpy.multiply', 'np.multiply', (['R_s', 'coef_a_V'], {}), '(R_s, coef_a_V)\n', (1407, 1422), True, '... |
from django.db import models
from django.core.exceptions import ValidationError
from .enums import ACCESS_CHOICES
from ..models import GroupModel
from datetime import date
def validate_previous_board(obj):
if obj.predecessor:
# Ensure the board is not set as its own predecessor
if obj.predecessor.... | [
"django.db.models.OneToOneField",
"django.core.exceptions.ValidationError",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateField"
] | [((572, 606), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (588, 606), False, 'from django.db import models\n'), ((627, 703), 'django.db.models.DateField', 'models.DateField', ([], {'default': 'date.today', 'null': '(False)', 'blank': '(False)', 'editable': ... |
from PyQt5 import QtCore
from PyQt5 import QtNetwork
from plugins.log import Plugin as Plugin_log
class App(QtCore.QCoreApplication):
def __init__(self):
super().__init__([])
self.isServer = True
self.isClient = False
self.running = False
self.plugins = {"log":Plugin_log(s... | [
"PyQt5.QtCore.QTimer",
"plugins.log.Plugin"
] | [((352, 367), 'PyQt5.QtCore.QTimer', 'QtCore.QTimer', ([], {}), '()\n', (365, 367), False, 'from PyQt5 import QtCore\n'), ((308, 324), 'plugins.log.Plugin', 'Plugin_log', (['self'], {}), '(self)\n', (318, 324), True, 'from plugins.log import Plugin as Plugin_log\n')] |
import os
saveDir = "/external/rprshnas01/netdata_kcni/edlab/temp_dataknights/patrickTesting/"
os.chdir(saveDir)
f = open('helloworld.txt','w')
f.write('Working Directory is:' + os.getcwd())
f.close() | [
"os.getcwd",
"os.chdir"
] | [((97, 114), 'os.chdir', 'os.chdir', (['saveDir'], {}), '(saveDir)\n', (105, 114), False, 'import os\n'), ((181, 192), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (190, 192), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
NHK COVID-19 Dataset
Data link: https://www3.nhk.or.jp/n-data/opendata/coronavirus/nhk_news_covid19_prefectures_daily_data.csv
Q: How it works?
A: It gets NHK COVID-19 dataset automatically and saves as working csv, then plots them.
Q: How to use th... | [
"pandas.DataFrame",
"matplotlib.dates.MonthLocator",
"matplotlib.pyplot.show",
"matplotlib.dates.DateFormatter",
"matplotlib.ticker.NullFormatter",
"requests.get",
"matplotlib.pyplot.subplots",
"pandas.concat",
"matplotlib.pyplot.grid"
] | [((3059, 3093), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': '[]', 'columns': '[]'}), '(index=[], columns=[])\n', (3071, 3093), True, 'import pandas as pd\n'), ((3104, 3138), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': '[]', 'columns': '[]'}), '(index=[], columns=[])\n', (3116, 3138), True, 'import pandas ... |
from pytest import raises
from skrt.containers import defaultnamedtuple
Name = defaultnamedtuple('Name', 'first', 'last', middle='', prefix='Mr.')
def test_positional_arg_assignment():
john_doe = Name('John', 'Doe')
assert john_doe.first == 'John'
assert john_doe.last == 'Doe'
def test_missing_positi... | [
"skrt.containers.defaultnamedtuple",
"pytest.raises"
] | [((82, 149), 'skrt.containers.defaultnamedtuple', 'defaultnamedtuple', (['"""Name"""', '"""first"""', '"""last"""'], {'middle': '""""""', 'prefix': '"""Mr."""'}), "('Name', 'first', 'last', middle='', prefix='Mr.')\n", (99, 149), False, 'from skrt.containers import defaultnamedtuple\n'), ((342, 359), 'pytest.raises', '... |
import os
import re
import requests
from requests.exceptions import HTTPError
from bs4 import BeautifulSoup
from scing.config import Config
def handle_download(site_url: str):
def err_eula():
msg = """
You must first sign the 10x Genomics End User Software License Agreement:
Please run the following comma... | [
"bs4.BeautifulSoup",
"re.search",
"requests.get",
"scing.config.Config"
] | [((465, 473), 'scing.config.Config', 'Config', ([], {}), '()\n', (471, 473), False, 'from scing.config import Config\n'), ((612, 651), 'requests.get', 'requests.get', (['site_url'], {'cookies': 'cookies'}), '(site_url, cookies=cookies)\n', (624, 651), False, 'import requests\n'), ((750, 793), 'bs4.BeautifulSoup', 'Beau... |
import numpy
import rospy
#from my_fetch_train import robot_gazebo_env_goal
import base_env
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from nav_msgs.msg import Odometry
from fetch_train.srv import EePose, EePoseRequest, EeRpy, EeRpyRequest, EeTraj, EeTrajRequest, JointTraj, JointTrajRequest... | [
"rospy.logerr",
"rospy.Subscriber",
"rospy.wait_for_message",
"rospy.Publisher",
"rospy.Rate",
"rospy.is_shutdown",
"rospy.logdebug",
"rospy.init_node"
] | [((1259, 1324), 'rospy.Subscriber', 'rospy.Subscriber', (['self.state_topic', 'StateMsg', 'self.state_callback'], {}), '(self.state_topic, StateMsg, self.state_callback)\n', (1275, 1324), False, 'import rospy\n'), ((1352, 1414), 'rospy.Publisher', 'rospy.Publisher', (['self.control_topic', 'ControlMsg'], {'queue_size':... |
from django.urls import path
from django.conf.urls import url
from voucher.views import VoucherDetail, CreateVoucherList, upload_email_list, upload_code_list, upload_manual_codes, assign_codes, get_num_codes, CreateOrganizationInVoucherList, VoucherTypeList, get_codes_from_email, get_codes_by_code_list, get_codes_by_v... | [
"voucher.views.VoucherDetail.as_view",
"django.urls.path",
"voucher.views.CreateOrganizationInVoucherList.as_view",
"voucher.views.VoucherTypeList.as_view",
"voucher.views.CreateVoucherList.as_view"
] | [((464, 530), 'django.urls.path', 'path', (['"""voucher/email-list"""', 'upload_email_list'], {'name': '"""upload-email"""'}), "('voucher/email-list', upload_email_list, name='upload-email')\n", (468, 530), False, 'from django.urls import path\n'), ((537, 600), 'django.urls.path', 'path', (['"""voucher/code-list"""', '... |
import csv
import string
from nltk.corpus import wordnet as wn
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk import pos_tag
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
from itertools import product
test_sent = "This is Brendan's test sentence, it contains GAS an... | [
"csv.reader",
"nltk.pos_tag",
"nltk.corpus.wordnet.synsets",
"nltk.corpus.wordnet.wup_similarity",
"nltk.corpus.stopwords.words",
"itertools.product",
"nltk.stem.wordnet.WordNetLemmatizer",
"nltk.tokenize.word_tokenize"
] | [((521, 549), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['noPunctuation'], {}), '(noPunctuation)\n', (534, 549), False, 'from nltk.tokenize import sent_tokenize, word_tokenize\n'), ((567, 589), 'nltk.pos_tag', 'pos_tag', (['sentenceWords'], {}), '(sentenceWords)\n', (574, 589), False, 'from nltk import pos_tag\n... |
#!/usr/bin/env python
# vim:set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
import setuptools
from setuptools.command.build_py import build_py
from sphinx.setup_command import BuildDoc
import py_compile
import glob
import os
import codecs
import re
here = os.path.abspath(os.path.dirname(__file__))
def read(*par... | [
"os.path.join",
"os.path.dirname",
"py_compile.compile",
"os.path.isfile",
"glob.glob",
"setuptools.command.build_py.build_py.run",
"re.search"
] | [((278, 303), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (293, 303), False, 'import os\n'), ((501, 574), 're.search', 're.search', (['"""^__version__ = [\'\\\\"]([^\'\\\\"]*)[\'\\\\"]"""', 'version_file', 're.M'], {}), '(\'^__version__ = [\\\'\\\\"]([^\\\'\\\\"]*)[\\\'\\\\"]\', version_fi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_geometric as pyg
class GNNStack(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers, dropout, emb=False):
super(GNNStack, self).__init__()
conv_model = pyg.nn.SAGEConv
self.convs... | [
"torch.nn.Dropout",
"torch.nn.ModuleList",
"torch.nn.functional.dropout",
"torch.nn.functional.nll_loss",
"torch.nn.functional.log_softmax",
"torch.nn.Linear",
"torch.nn.functional.relu"
] | [((323, 338), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (336, 338), True, 'import torch.nn as nn\n'), ((1170, 1193), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['x'], {'dim': '(1)'}), '(x, dim=1)\n', (1183, 1193), True, 'import torch.nn.functional as F\n'), ((1243, 1266), 'torch.nn.functional.... |
import numpy as np
import torch
from sklearn.metrics import roc_auc_score, precision_recall_curve, jaccard_score, f1_score
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.initialized = False
self.val = None
self.avg = None
... | [
"numpy.round",
"numpy.multiply",
"sklearn.metrics.roc_auc_score"
] | [((1800, 1829), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['target', 'output'], {}), '(target, output)\n', (1813, 1829), False, 'from sklearn.metrics import roc_auc_score, precision_recall_curve, jaccard_score, f1_score\n'), ((474, 498), 'numpy.multiply', 'np.multiply', (['val', 'weight'], {}), '(val, weight)\... |
from simulation.simulation import Simulation
from utilities.time import count_elapsed_time
@count_elapsed_time
def run(n):
simulation = Simulation(n)
solutions = simulation.start2()
print("------------------")
print("Solutions")
print(len(solutions.get_solutions()))
# for i in solutions.get_so... | [
"simulation.simulation.Simulation"
] | [((142, 155), 'simulation.simulation.Simulation', 'Simulation', (['n'], {}), '(n)\n', (152, 155), False, 'from simulation.simulation import Simulation\n'), ((616, 629), 'simulation.simulation.Simulation', 'Simulation', (['n'], {}), '(n)\n', (626, 629), False, 'from simulation.simulation import Simulation\n'), ((1089, 1... |
from django.contrib import admin
from django.contrib.auth.models import Group, User
admin.site.site_header = 'Payment Administration'
admin.site.unregister(Group)
admin.site.unregister(User)
| [
"django.contrib.admin.site.unregister"
] | [((136, 164), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['Group'], {}), '(Group)\n', (157, 164), False, 'from django.contrib import admin\n'), ((165, 192), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['User'], {}), '(User)\n', (186, 192), False, 'from django.contrib import ... |
"""
11725 : 트리의 부모 찾기
URL : https://www.acmicpc.net/problem/11725
Input #1 :
7
1 6
6 3
3 5
4 1
2 4
4 7
Output #1 :
4
6
1
3
1
4
Input #2 :
12
1 2
1 3
2 4
3 5... | [
"sys.setrecursionlimit"
] | [((550, 584), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(2 ** 31 - 1)'], {}), '(2 ** 31 - 1)\n', (571, 584), False, 'import sys\n')] |
# -*- coding: utf-8 -*-
from unittest import TestCase
import pytest
from pdfrw import PdfDict
from pdfrw import PdfName
from pdf_annotate.config import constants
from pdf_annotate.config.graphics_state import GraphicsState
class TestGraphicsState(TestCase):
def test_blank(self):
pdf_dict = GraphicsStat... | [
"pytest.raises",
"pdfrw.PdfName",
"pdf_annotate.config.graphics_state.GraphicsState"
] | [((477, 673), 'pdf_annotate.config.graphics_state.GraphicsState', 'GraphicsState', ([], {'line_width': '(2)', 'line_cap': 'constants.LINE_CAP_ROUND', 'line_join': 'constants.LINE_JOIN_MITER', 'miter_limit': '(1.404)', 'dash_array': '[[1], 0]', 'stroke_transparency': '(0.7)', 'fill_transparency': '(0.5)'}), '(line_width... |
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework import permissions
from chinookapi.models import Artist, Album, MediaType, Genre, Track
from chinookapi.serializers import UserSerializer, TrackSerializer
from django_filters import rest_framework as filters
fr... | [
"chinookapi.models.Track.objects.all",
"django.contrib.auth.models.User.objects.all"
] | [((684, 702), 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (700, 702), False, 'from django.contrib.auth.models import User\n'), ((1081, 1100), 'chinookapi.models.Track.objects.all', 'Track.objects.all', ([], {}), '()\n', (1098, 1100), False, 'from chinookapi.models import Artist,... |
"""Integration test cases for the users route."""
import os
from typing import Any
from aiohttp import hdrs
from aiohttp.test_utils import TestClient as _TestClient
import jwt
import pytest
from pytest_mock import MockFixture
ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95"
@pytest.fixture
def token() -> str:
"""Cr... | [
"os.getenv",
"jwt.encode"
] | [((356, 379), 'os.getenv', 'os.getenv', (['"""JWT_SECRET"""'], {}), "('JWT_SECRET')\n", (365, 379), False, 'import os\n'), ((488, 526), 'jwt.encode', 'jwt.encode', (['payload', 'secret', 'algorithm'], {}), '(payload, secret, algorithm)\n', (498, 526), False, 'import jwt\n'), ((645, 668), 'os.getenv', 'os.getenv', (['""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lic... | [
"copy.deepcopy",
"arch.api.utils.log_utils.getLogger",
"federatedml.param.predict_param.PredictParam.check",
"federatedml.param.predict_param.PredictParam",
"federatedml.param.evaluation_param.EvaluateParam",
"federatedml.param.dataio_param.DataIOParam.check",
"federatedml.param.evaluation_param.Evaluat... | [((1114, 1135), 'arch.api.utils.log_utils.getLogger', 'log_utils.getLogger', ([], {}), '()\n', (1133, 1135), False, 'from arch.api.utils import log_utils\n'), ((5065, 5078), 'federatedml.param.dataio_param.DataIOParam', 'DataIOParam', ([], {}), '()\n', (5076, 5078), False, 'from federatedml.param.dataio_param import Da... |
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from django.contrib.sessions.models import Session
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--delete',
action='store_true',
dest='delete',
... | [
"django.contrib.sessions.models.Session.objects.all",
"optparse.make_option"
] | [((612, 633), 'django.contrib.sessions.models.Session.objects.all', 'Session.objects.all', ([], {}), '()\n', (631, 633), False, 'from django.contrib.sessions.models import Session\n'), ((234, 342), 'optparse.make_option', 'make_option', (['"""--delete"""'], {'action': '"""store_true"""', 'dest': '"""delete"""', 'defaul... |
# ------------------------------------------------------------------------------
# This module contains utility functions used throughout the application.
# ------------------------------------------------------------------------------
import os
import shutil
import re
import sys
import unicodedata
from . import filt... | [
"unicodedata.normalize",
"os.path.abspath",
"os.remove",
"os.makedirs",
"os.path.join",
"os.path.isdir",
"os.path.getsize",
"shutil.copy2",
"shutil.get_terminal_size",
"os.path.exists",
"os.path.dirname",
"os.path.isfile",
"os.path.getmtime",
"shutil.rmtree",
"re.sub",
"os.listdir",
... | [((3839, 3904), 're.compile', 're.compile', (['"""\n (["\'])@root/(.*?)([#].*?)?\\\\1\n"""', 're.VERBOSE'], {}), '("""\n (["\'])@root/(.*?)([#].*?)?\\\\1\n""", re.VERBOSE)\n', (3849, 3904), False, 'import re\n'), ((417, 439), 'os.path.isdir', 'os.path.isdir', (['dirpath'], {}), '(dirpath)\n', (430, 439), False, '... |
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import io
def data_gen(num=100):
"""
Generates random samples for plotting
"""
a = np.random.normal(size=num)
return a
def plot_raw(a):... | [
"io.BytesIO",
"pywebio.start_server",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.close",
"PIL.Image.open",
"matplotlib.pyplot.figure",
"numpy.random.normal",
"matplotlib.pyplot.gcf"
] | [((263, 289), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'num'}), '(size=num)\n', (279, 289), True, 'import numpy as np\n'), ((362, 373), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (371, 373), True, 'import matplotlib.pyplot as plt\n'), ((378, 405), 'matplotlib.pyplot.figure', 'plt.figure',... |
from io import StringIO
import pytest
from hypothesis import given, settings
import hypothesis.strategies as hst
from lxml import etree
from qcodes.instrument_drivers.tektronix.AWG70002A import AWG70002A
from qcodes.instrument_drivers.tektronix.AWG70000A import AWG70000A
import qcodes.instrument.sims as sims
visalib ... | [
"io.StringIO",
"qcodes.instrument_drivers.tektronix.AWG70002A.AWG70002A",
"pytest.fixture",
"qcodes.instrument.sims.__file__.replace",
"hypothesis.settings",
"qcodes.instrument_drivers.tektronix.AWG70000A.AWG70000A._makeWFMXFileHeader",
"hypothesis.strategies.booleans",
"pytest.raises",
"qcodes.inst... | [((322, 390), 'qcodes.instrument.sims.__file__.replace', 'sims.__file__.replace', (['"""__init__.py"""', '"""Tektronix_AWG70000A.yaml@sim"""'], {}), "('__init__.py', 'Tektronix_AWG70000A.yaml@sim')\n", (343, 390), True, 'import qcodes.instrument.sims as sims\n'), ((394, 426), 'pytest.fixture', 'pytest.fixture', ([], {'... |
#!/usr/bin/env python
import scipy.stats
from sklearn.metrics import mean_squared_error
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import jinja2
from jinja2 import Template
import os
import subprocess
import matplotlib
import json
pgf_with_latex = {"pgf.texsystem": 'pdflatex'}
matplotlib.r... | [
"matplotlib.pyplot.title",
"numpy.load",
"pandas.read_csv",
"github.Github",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"numpy.round",
"os.path.abspath",
"matplotlib.rcParams.update",
"numpy.int",
"numpy.linspace",
"sklearn.metrics.mean_squared_error",
"i... | [((308, 350), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (['pgf_with_latex'], {}), '(pgf_with_latex)\n', (334, 350), False, 'import matplotlib\n'), ((496, 522), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (506, 522), True, 'import matplotlib.pyplot as pl... |
#!/usr/bin/env python
'''
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")... | [
"subprocess.Popen",
"logging.getLogger",
"sys.exc_info"
] | [((842, 861), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (859, 861), False, 'import logging\n'), ((2549, 2623), 'subprocess.Popen', 'subprocess.Popen', (['[script]'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '([script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n', (2565, 2623... |
from solutions.runner.runner import SolutionRunner
SolutionRunner().run_all() | [
"solutions.runner.runner.SolutionRunner"
] | [((51, 67), 'solutions.runner.runner.SolutionRunner', 'SolutionRunner', ([], {}), '()\n', (65, 67), False, 'from solutions.runner.runner import SolutionRunner\n')] |
from distutils.core import setup
from setuptools import find_packages
setup(
name='smooth',
version='0.2.0',
packages=find_packages(),
package_data={'smooth.examples': ['example_timeseries/*.csv']},
license='GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007',
long_description=open... | [
"setuptools.find_packages"
] | [((131, 146), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (144, 146), False, 'from setuptools import find_packages\n')] |
"""Setup reasoner-util package."""
from setuptools import setup
with open("README.md", "r") as stream:
long_description = stream.read()
setup(
name="reasoner-util",
version="1.0.0",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/TranslatorSRI/reasoner-util",
description="... | [
"setuptools.setup"
] | [((142, 667), 'setuptools.setup', 'setup', ([], {'name': '"""reasoner-util"""', 'version': '"""1.0.0"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://github.com/TranslatorSRI/reasoner-util"""', 'description': '"""Utilities for manipulating for TRAPI JSON components"""', 'long_descripti... |
import os
from utils import timex
CONFIG = [
dict(
name='cbsl-gov-lk-economy-snapshot',
url='https://www.cbsl.gov.lk/en/sri-lanka-economy-snapshot',
left_top=[1020, 280],
width_height=[860, 1040],
header='#SriLanka #Economy Snapshot by @CBSL',
footer='#lka',
... | [
"os.path.join"
] | [((5569, 5662), 'os.path.join', 'os.path.join', (['"""https://www.google.com"""', '"""maps/@6.9157334,79.8575813,14.41z/data=!5m1!1e1"""'], {}), "('https://www.google.com',\n 'maps/@6.9157334,79.8575813,14.41z/data=!5m1!1e1')\n", (5581, 5662), False, 'import os\n'), ((5984, 6059), 'os.path.join', 'os.path.join', (['... |
"""Sensor Entity for EZSP counters."""
from datetime import timedelta
import logging
from typing import Any, Callable, Dict, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers import entity
from homeassistant.helpers.typing import HomeAssistantType
from zigpy.state import Counter... | [
"datetime.timedelta",
"logging.getLogger"
] | [((443, 470), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (460, 470), False, 'import logging\n'), ((487, 508), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(20)'}), '(seconds=20)\n', (496, 508), False, 'from datetime import timedelta\n')] |
from ctci.p4_1 import Graph, Node
def test_graph_route_exists():
g = Graph()
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.children = [node2, node3]
node4 = Node(4)
g.nodes.append(node1)
assert g.route_exists(node1, node3)
assert not g.route_exists(node1, node4)
| [
"ctci.p4_1.Graph",
"ctci.p4_1.Node"
] | [((74, 81), 'ctci.p4_1.Graph', 'Graph', ([], {}), '()\n', (79, 81), False, 'from ctci.p4_1 import Graph, Node\n'), ((95, 102), 'ctci.p4_1.Node', 'Node', (['(1)'], {}), '(1)\n', (99, 102), False, 'from ctci.p4_1 import Graph, Node\n'), ((115, 122), 'ctci.p4_1.Node', 'Node', (['(2)'], {}), '(2)\n', (119, 122), False, 'fr... |
import torch
from torch import nn
import torch.nn.functional as F
from .video import LSTM, ConvLSTM
from .audio import CreateSincNet
__all__ = ['MultiModal_DeepFakeDetector']
class VideoStream(nn.Module):
def __init__(
self, num_classes, latent_dim=512, lstm_layers=1, hidden_dim=1024,
b... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.load",
"torch.nn.BatchNorm1d",
"torch.cat",
"torch.nn.Linear",
"torch.no_grad"
] | [((1929, 1990), 'torch.nn.Linear', 'nn.Linear', (['(2 * hidden_dim if bidirectional else hidden_dim)', '(1)'], {}), '(2 * hidden_dim if bidirectional else hidden_dim, 1)\n', (1938, 1990), False, 'from torch import nn\n'), ((4491, 4523), 'torch.cat', 'torch.cat', (['[video, audio]'], {'dim': '(1)'}), '([video, audio], d... |
import numpy as np
import random as rnd
import re
attr_finder = re.compile('^.*\\t(.*\\t.*)$')
LINES_TO_READ_FROM_FILES = 1000
N_LINES_TO_SAMPLE = 320
def choose_entities(file_path):
with open(file_path) as opened:
hunred_lines = opened.readlines()[:LINES_TO_READ_FROM_FILES]
chosen_lines = rnd.s... | [
"random.sample",
"re.compile"
] | [((65, 95), 're.compile', 're.compile', (['"""^.*\\\\t(.*\\\\t.*)$"""'], {}), "('^.*\\\\t(.*\\\\t.*)$')\n", (75, 95), False, 'import re\n'), ((315, 358), 'random.sample', 'rnd.sample', (['hunred_lines', 'N_LINES_TO_SAMPLE'], {}), '(hunred_lines, N_LINES_TO_SAMPLE)\n', (325, 358), True, 'import random as rnd\n'), ((2500... |
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic.simple import direct_to_template, redirect_to
admin.autodiscover()
urlpatterns = patterns('',
# Apps
url(r'^admin/', include(admin.site.urls)),
#V... | [
"django.contrib.admin.autodiscover",
"django.conf.urls.defaults.url",
"django.conf.urls.defaults.include"
] | [((201, 221), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (219, 221), False, 'from django.contrib import admin\n'), ((364, 441), 'django.conf.urls.defaults.url', 'url', (['"""^logout/"""', '"""django.contrib.auth.views.logout_then_login"""'], {'name': '"""logout"""'}), "('^logout/', 'dj... |
import requests
from urllib3.exceptions import InsecureRequestWarning
from pprint import pprint
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
if __name__ == "__main__":
url = "https://netbox.lasthop.io/api/"
response = requests.get(url, verify=False)
print("\nStatus C... | [
"requests.packages.urllib3.disable_warnings",
"pprint.pprint",
"requests.get"
] | [((96, 171), 'requests.packages.urllib3.disable_warnings', 'requests.packages.urllib3.disable_warnings', ([], {'category': 'InsecureRequestWarning'}), '(category=InsecureRequestWarning)\n', (138, 171), False, 'import requests\n'), ((267, 298), 'requests.get', 'requests.get', (['url'], {'verify': '(False)'}), '(url, ver... |
"""
需求:使用redis工具包里面的StrictRedis类,操作redis数据库里面的string数据类型
"""
from redis import StrictRedis
if __name__ == '__main__':
try:
# 创建StrictRedis对象
sr = StrictRedis(host='192.168.103.129', port=6379, db=1)
# 调用对象方法,操作string
# 新增
result = sr.set('name','test_sr')
print(result)
# 修改
# sr.set('name', 'test... | [
"redis.StrictRedis"
] | [((155, 207), 'redis.StrictRedis', 'StrictRedis', ([], {'host': '"""192.168.103.129"""', 'port': '(6379)', 'db': '(1)'}), "(host='192.168.103.129', port=6379, db=1)\n", (166, 207), False, 'from redis import StrictRedis\n')] |
# Generated by Django 2.0.7 on 2018-08-02 16:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("api", "0002_auto_20180731_1428"),
]
operations = [
migrations.AlterField(
model_name="kubemetri... | [
"django.db.models.ForeignKey"
] | [((366, 486), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""metrics"""', 'to': '"""api.KubePod"""'}), "(blank=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='metrics', to='api.KubePod')\n", (383, 4... |
#!/usr/bin/env python
"""MeerKAT galactic to celestial coordinate conversion tool
Returns CSV target catalogue for OPT input
"""
from __future__ import print_function
from astropy import units as u
from astropy.coordinates import Galactic, ICRS
from astropy.coordinates import SkyCoord
import argparse
import sys
fr... | [
"astropy.coordinates.SkyCoord",
"argparse.ArgumentParser"
] | [((500, 621), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': 'usage', 'description': 'description', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(usage=usage, description=description,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (523, 621), False, 'import arg... |
# 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.
import unittest
from fairseq.data import iterators, ListDataset
class TestIterators(unittest.TestCase):
def test_counting_iterator_inde... | [
"unittest.main",
"fairseq.data.iterators.ShardedIterator",
"fairseq.data.ListDataset",
"fairseq.data.iterators.GroupedIterator",
"fairseq.data.iterators.EpochBatchIterator",
"fairseq.data.iterators.BufferedIterator",
"fairseq.data.iterators.CountingIterator"
] | [((7429, 7445), 'fairseq.data.ListDataset', 'ListDataset', (['ref'], {}), '(ref)\n', (7440, 7445), False, 'from fairseq.data import iterators, ListDataset\n'), ((7456, 7606), 'fairseq.data.iterators.EpochBatchIterator', 'iterators.EpochBatchIterator', ([], {'dataset': 'dataset', 'collate_fn': 'dataset.collater', 'batch... |
import os
import pathlib
import unittest.mock
import dotenv
import pytest
def pytest_report_header(config) -> str:
"""Pytest headers."""
return "package: modmail"
@pytest.fixture(autouse=True, scope="package")
def patch_embeds():
"""Run the patch embed method. This is normally run by modmail.__main__, ... | [
"dotenv.load_dotenv",
"pytest.exit",
"pathlib.Path",
"pytest.fixture"
] | [((177, 222), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)', 'scope': '"""package"""'}), "(autouse=True, scope='package')\n", (191, 222), False, 'import pytest\n'), ((757, 802), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)', 'scope': '"""package"""'}), "(autouse=True, scope='package')\n"... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>
from flask import request
from .common import Resource
class LogEvents(Resource):
def modified_attr_name(self):... | [
"flask.request.method.lower"
] | [((406, 428), 'flask.request.method.lower', 'request.method.lower', ([], {}), '()\n', (426, 428), False, 'from flask import request\n')] |
# Given the root of a binary tree, the level of its root is 1,
# the level of its children is 2, and so on.
#
# Return the smallest level X such that the sum of all the values of
# nodes at level X is maximal.
#
# 1
# /\
# 7 0
# /\
# 7 -8
#
# Input: [1,7,0,7,-8,null,null]
# Output: 2
# Explanation:
... | [
"collections.deque"
] | [((701, 720), 'collections.deque', 'collections.deque', ([], {}), '()\n', (718, 720), False, 'import collections\n')] |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import ast
import unidiff
import sys
def read_file(filename):
with open(filename, 'r') as fin:
return fin.read()
def line_num_for_phrase_in_file(phrase, filename):
with open(filename,'r') as f:
for (i, line) in enumerate(f):
if phrase... | [
"sys.stdin.read",
"ast.get_docstring",
"unidiff.PatchSet.from_string",
"ast.NodeVisitor.visit",
"ast.parse"
] | [((5301, 5317), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (5315, 5317), False, 'import sys\n'), ((604, 624), 'ast.parse', 'ast.parse', (['code_text'], {}), '(code_text)\n', (613, 624), False, 'import ast\n'), ((4236, 4291), 'unidiff.PatchSet.from_string', 'unidiff.PatchSet.from_string', (['content'], {'enco... |
import urllib2
from pagemodel.html import (Node, StrictNode, Text, ShallowText, Attr,
Html, StrictHtml, ThisClass, Constant)
from pagemodel.bsoup import PageModel
from libdict.models import Models
from libdict.cache import Cache
__all__ = ["models", "MacmillanCache"]
models = Models("macmillan")
class Exampl... | [
"pagemodel.html.Constant",
"pagemodel.html.Text",
"pagemodel.html.Node",
"libdict.models.Models",
"pagemodel.html.Attr",
"pagemodel.html.Node.list",
"pagemodel.html.Node.optional",
"urllib2.urlopen"
] | [((286, 305), 'libdict.models.Models', 'Models', (['"""macmillan"""'], {}), "('macmillan')\n", (292, 305), False, 'from libdict.models import Models\n'), ((5131, 5151), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {}), '(url)\n', (5146, 5151), False, 'import urllib2\n'), ((480, 504), 'pagemodel.html.Node.optional', ... |
#!/usr/bin/env python3
import os
import os.path
import argparse
import sys
import logging
import re
from glob import glob
from clean_utils import *
def clean_by_cutadapt(logger, project_dir, remove_patterns, remove=True):
cutadapt_result_folder = os.path.join(project_dir, "intermediate_data", "cutadapt", "result"... | [
"os.path.abspath",
"argparse.ArgumentParser",
"logging.basicConfig",
"sys.exit",
"os.path.join",
"logging.getLogger"
] | [((253, 321), 'os.path.join', 'os.path.join', (['project_dir', '"""intermediate_data"""', '"""cutadapt"""', '"""result"""'], {}), "(project_dir, 'intermediate_data', 'cutadapt', 'result')\n", (265, 321), False, 'import os\n'), ((551, 616), 'os.path.join', 'os.path.join', (['project_dir', '"""preprocessing"""', '"""fast... |
# -*- coding: utf-8 -*-
# @Time : 2021/3/21 14:22
# @Author : <NAME>
# @FileName: check_len_graph.py
import dgl
a, _ = dgl.load_graphs("graph/train_wikihop_30000_36350_graphs.dgl")
# b, _ = dgl.load_graphs("graph/dev_wikihop_3701_5129_graphs.dgl")
# c, _ = dgl.load_graphs("graph/dev_wikihop_0_3700_graphs.dgl")
pri... | [
"dgl.load_graphs"
] | [((124, 185), 'dgl.load_graphs', 'dgl.load_graphs', (['"""graph/train_wikihop_30000_36350_graphs.dgl"""'], {}), "('graph/train_wikihop_30000_36350_graphs.dgl')\n", (139, 185), False, 'import dgl\n')] |
import traceback
from flask import Blueprint, jsonify
errors = Blueprint('errors', __name__)
@errors.app_errorhandler(Exception)
def handle_exception(error):
message = [str(x) for x in error.args]
status_code = error.code if hasattr(error, 'code') else 500
print(traceback.format_exc())
response = {
... | [
"flask.jsonify",
"flask.Blueprint",
"traceback.format_exc"
] | [((64, 93), 'flask.Blueprint', 'Blueprint', (['"""errors"""', '__name__'], {}), "('errors', __name__)\n", (73, 93), False, 'from flask import Blueprint, jsonify\n'), ((278, 300), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (298, 300), False, 'import traceback\n'), ((598, 615), 'flask.jsonify', 'js... |
#===============================================================================
# wxpyobus - obus client gui in python.
#
# @file dlgabout.py
#
# @brief wxpython obus client about dialog
#
# @author <EMAIL>
#
# Copyright (c) 2013 Parrot S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms,... | [
"wx.Dialog.__init__",
"wx.Bitmap",
"wx.StaticLine",
"wx.BoxSizer",
"os.path.dirname",
"wx.StaticText",
"wx.Button",
"wx.StaticBitmap",
"wx.GetApp"
] | [((2265, 2290), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2280, 2290), False, 'import os\n'), ((2334, 2359), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2349, 2359), False, 'import os\n'), ((2593, 2632), 'wx.Dialog.__init__', 'wx.Dialog.__init__', (['self'... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Bonjour tout le monde !")
| [
"django.http.HttpResponse"
] | [((130, 169), 'django.http.HttpResponse', 'HttpResponse', (['"""Bonjour tout le monde !"""'], {}), "('Bonjour tout le monde !')\n", (142, 169), False, 'from django.http import HttpResponse\n')] |
from collections.abc import (
Iterable,
)
from eth_utils.toolz import (
peek,
)
from ssz.sedes import (
List,
boolean,
bytes_sedes,
empty_list,
)
def is_sedes(obj):
"""
Check if `obj` is a sedes object.
A sedes object is characterized by having the methods
`serialize(obj)` an... | [
"eth_utils.toolz.peek",
"ssz.sedes.List"
] | [((494, 503), 'eth_utils.toolz.peek', 'peek', (['obj'], {}), '(obj)\n', (498, 503), False, 'from eth_utils.toolz import peek\n'), ((870, 889), 'ssz.sedes.List', 'List', (['element_sedes'], {}), '(element_sedes)\n', (874, 889), False, 'from ssz.sedes import List, boolean, bytes_sedes, empty_list\n')] |