code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 10 14:16:55 2022
@author: <NAME>
"""
import time
import pandas as pd
import colorcet as cc
import numpy as np
import datetime as dt
from bokeh.io import show, curdoc
from bokeh.plotting import figure
from bokeh.themes import built_in_themes
from bokeh.layouts ... | [
"bokeh.models.ColumnDataSource",
"pandas.read_csv",
"bokeh.models.CrosshairTool",
"bokeh.models.IndexFilter",
"bokeh.models.BoxZoomTool",
"bokeh.io.curdoc",
"bokeh.palettes.linear_palette",
"bokeh.models.Div",
"bokeh.transform.LinearColorMapper",
"bokeh.models.Label",
"pandas.to_datetime",
"bo... | [((870, 929), 'pandas.read_csv', 'pd.read_csv', (['"""US_Energy.csv"""'], {'delimiter': '""","""', 'na_values': '"""--"""'}), "('US_Energy.csv', delimiter=',', na_values='--')\n", (881, 929), True, 'import pandas as pd\n'), ((1744, 1794), 'pandas.to_datetime', 'pd.to_datetime', (['cleaned_data.index'], {'format': '"""%... |
# Data-enriching GAN (DeGAN)/ DCGAN for retrieving images from a trained classifier
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import t... | [
"argparse.ArgumentParser",
"dcgan_model.Generator",
"torch.randn",
"torch.full",
"numpy.random.randint",
"torch.device",
"torchvision.transforms.Normalize",
"torch.nn.functional.normalize",
"alexnet.AlexNet",
"torch.nn.BCELoss",
"random.randint",
"torchvision.transforms.Scale",
"torch.load",... | [((652, 667), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (665, 667), False, 'from tensorboardX import SummaryWriter\n'), ((870, 895), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (893, 895), False, 'import argparse\n'), ((2663, 2690), 'random.seed', 'random.seed', (['opt... |
import flax.linen as nn
import jax.numpy as jnp
from graphmlp_flax.models import GMLP
def test_instance():
net = GMLP(feature_dim=128, hidden_dim=128, num_classes=10, dtype=jnp.float32)
assert isinstance(net, nn.Module)
| [
"graphmlp_flax.models.GMLP"
] | [((121, 193), 'graphmlp_flax.models.GMLP', 'GMLP', ([], {'feature_dim': '(128)', 'hidden_dim': '(128)', 'num_classes': '(10)', 'dtype': 'jnp.float32'}), '(feature_dim=128, hidden_dim=128, num_classes=10, dtype=jnp.float32)\n', (125, 193), False, 'from graphmlp_flax.models import GMLP\n')] |
from tensorflow.keras.preprocessing import image
import numpy as np
from .augment_and_mix import augment_and_mix
import albumentations
def segmentation_alb(input_image, label, mean, std, augmentation_dict):
transforms = get_aug(augmentation_dict)
if len(transforms) > 0:
aug = albumentations.Compose(t... | [
"albumentations.Compose",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"numpy.random.randint",
"albumentations.OneOf"
] | [((2096, 2137), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'image.ImageDataGenerator', ([], {}), '(**data_gen_args)\n', (2120, 2137), False, 'from tensorflow.keras.preprocessing import image\n'), ((2157, 2198), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'image.ImageDataGenerator', ([], {... |
import os
import cv2
import numpy as np
from pathlib import Path
from tqdm import tqdm
class AnimeFaceDetector(object):
def __init__(self, cascade_file="lbpcascade_animeface.xml"):
if not os.path.isfile(cascade_file):
raise RuntimeError("lbpcascade_animeface.xml not found")
self.cascade ... | [
"cv2.equalizeHist",
"tqdm.tqdm",
"cv2.cvtColor",
"cv2.rectangle",
"cv2.imread",
"pathlib.Path",
"os.path.isfile",
"cv2.CascadeClassifier",
"sys.stderr.write",
"sys.exit"
] | [((1114, 1131), 'pathlib.Path', 'Path', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (1118, 1131), False, 'from pathlib import Path\n'), ((322, 357), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['cascade_file'], {}), '(cascade_file)\n', (343, 357), False, 'import cv2\n'), ((407, 450), 'cv2.cvtColor', 'cv2.cvtColor'... |
########
# there are some special methods of class
# which are formed: __a_name()__ --> methods, which are surrounded by double __
# let's start
import datetime
class Person:
# constructor
def __init__(self, first, last, birthday):
self.first = first
self.last = last
self.birthday = bi... | [
"datetime.date.today",
"datetime.datetime"
] | [((631, 652), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (650, 652), False, 'import datetime\n'), ((1464, 1495), 'datetime.datetime', 'datetime.datetime', (['(1993)', '(10)', '(10)'], {}), '(1993, 10, 10)\n', (1481, 1495), False, 'import datetime\n'), ((1538, 1568), 'datetime.datetime', 'datetime.d... |
from flask import Blueprint, request, make_response
from utils import send_resp, logger
from notes import Notes
from authentication import Authentication
from validator import validate
notes_api = Blueprint('notes_api', __name__)
notes = Notes()
authentication = Authentication()
@notes_api.route("/<id>", methods=["... | [
"validator.validate",
"utils.send_resp",
"flask.Blueprint",
"flask.request.headers.get",
"notes.Notes",
"authentication.Authentication",
"utils.logger.exception"
] | [((200, 232), 'flask.Blueprint', 'Blueprint', (['"""notes_api"""', '__name__'], {}), "('notes_api', __name__)\n", (209, 232), False, 'from flask import Blueprint, request, make_response\n'), ((241, 248), 'notes.Notes', 'Notes', ([], {}), '()\n', (246, 248), False, 'from notes import Notes\n'), ((266, 282), 'authenticat... |
#!/usr/bin/python3
# Copyright 2018-2019 <NAME> @ alvarob96 in GitHub
# See LICENSE for details.
from datetime import datetime, date
import json
from random import randint
import pandas as pd
import pkg_resources
import requests
import unidecode
from lxml.html import fromstring
from investpy.utils.user_agent import... | [
"unidecode.unidecode",
"investpy.utils.data.Data",
"investpy.utils.user_agent.get_random",
"random.randint",
"datetime.date",
"json.dumps",
"investpy.data.bonds_data.bonds_as_list",
"lxml.html.fromstring",
"investpy.data.bonds_data.bond_countries_as_list",
"investpy.data.bonds_data.bonds_as_dict",... | [((1948, 1968), 'investpy.data.bonds_data.bonds_as_df', 'bonds_as_df', (['country'], {}), '(country)\n', (1959, 1968), False, 'from investpy.data.bonds_data import bonds_as_df, bonds_as_list, bonds_as_dict\n'), ((3518, 3540), 'investpy.data.bonds_data.bonds_as_list', 'bonds_as_list', (['country'], {}), '(country)\n', (... |
from abc_exercise_randomizer.note_length import NoteLength
from abc_exercise_randomizer.note_value import NoteValue
class Note:
__TIE = "-"
def __init__(self, value: NoteValue, length: NoteLength, tie: bool):
self.__value = value
self.__length = length
self.__tie = tie
@property
... | [
"abc_exercise_randomizer.note_length.NoteLength",
"abc_exercise_randomizer.note_value.NoteValue"
] | [((547, 570), 'abc_exercise_randomizer.note_value.NoteValue', 'NoteValue', (['self.__value'], {}), '(self.__value)\n', (556, 570), False, 'from abc_exercise_randomizer.note_value import NoteValue\n'), ((594, 619), 'abc_exercise_randomizer.note_length.NoteLength', 'NoteLength', (['self.__length'], {}), '(self.__length)\... |
import uuid
from django.contrib.gis.db import models
from django.contrib.postgres.fields import JSONField
from django.contrib.gis.geos import GEOSGeometry
from django.http.request import HttpRequest
from osmchadjango.changeset.filters import ChangesetFilter
from osmchadjango.feature.filters import FeatureFilter
from ... | [
"django.contrib.gis.db.models.ForeignKey",
"json.loads",
"shapely.ops.unary_union",
"django.contrib.gis.db.models.CharField",
"django.contrib.gis.db.models.GeometryField",
"osmchadjango.feature.filters.FeatureFilter",
"django.contrib.gis.db.models.UUIDField",
"osmchadjango.changeset.filters.ChangesetF... | [((602, 672), 'django.contrib.gis.db.models.UUIDField', 'models.UUIDField', ([], {'primary_key': '(True)', 'default': 'uuid.uuid4', 'editable': '(False)'}), '(primary_key=True, default=uuid.uuid4, editable=False)\n', (618, 672), False, 'from django.contrib.gis.db import models\n'), ((684, 728), 'django.contrib.gis.db.m... |
# Copyright 2022 Cisco Systems, Inc. and its affiliates
#
# 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 l... | [
"torch.nn.Dropout",
"torch.flatten",
"torch.utils.data.Subset",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"torch.nn.Conv2d",
"torchvision.transforms.Normalize",
"torch.nn.functional.nll_loss",
"torch.nn.functional.max_pool2d",
"flame.config.Config",
"torch.nn.Linear",
"torch.nn... | [((1120, 1147), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1137, 1147), False, 'import logging\n'), ((4572, 4611), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (4595, 4611), False, 'import argparse\n'), ((4728, 4747), 'f... |
from django.core.management.base import BaseCommand
from core.models import Lottery
class Command(BaseCommand):
help = 'Delete lottery data'
def handle(self, *args, **options):
Lottery.objects.all().delete()
| [
"core.models.Lottery.objects.all"
] | [((196, 217), 'core.models.Lottery.objects.all', 'Lottery.objects.all', ([], {}), '()\n', (215, 217), False, 'from core.models import Lottery\n')] |
import socket
import re
import platform
import subprocess
def getLocalIP():
"""
Returns the actual ip of the local machine.
This code figures out what source address would be used if some traffic
were to be sent out to some well known address on the Internet.
In this case, a Google DNS se... | [
"subprocess.check_output",
"socket.socket",
"socket.gethostname",
"platform.system",
"re.compile"
] | [((830, 942), 're.compile', 're.compile', (['"""((25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)\\\\.){3}(25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)"""'], {}), "(\n '((25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)\\\\.){3}(25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)'\n )\n", (840, 942), False, 'import... |
#!/usr/bin/env python3
# Copyright (c) 2020 - 2021 <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... | [
"datetime.datetime.strptime",
"logging.getLogger"
] | [((698, 725), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (715, 725), False, 'import logging\n'), ((827, 886), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['field[:19]', '"""%Y-%m-%dT%H:%M:%S"""'], {}), "(field[:19], '%Y-%m-%dT%H:%M:%S')\n", (853, 886), False, 'import ... |
paraview_plugin_version = '0.0.4'
"""
These are ParaView plugins based on PVGeo for the wtools package
"""
from paraview.util.vtkAlgorithm import *
import PVGeo
from PVGeo.base import InterfacedBaseReader, ReaderBase
from PVGeo import _helpers
import sys
import os
sys.path.append(os.path.dirname(__file__))
import wtoo... | [
"wtools.load_pickle",
"PVGeo.base.InterfacedBaseReader.__init__",
"PVGeo.base.InterfacedBaseReader.get_timestep_values",
"PVGeo.base.InterfacedBaseReader.set_time_delta",
"PVGeo._helpers.getRequestedTime",
"PVGeo.dataFrameToTable",
"os.path.dirname",
"PVGeo._helpers.update_time_steps",
"PVGeo.base.R... | [((282, 307), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (297, 307), False, 'import os\n'), ((630, 675), 'PVGeo.base.InterfacedBaseReader.__init__', 'InterfacedBaseReader.__init__', (['self'], {}), '(self, **kwargs)\n', (659, 675), False, 'from PVGeo.base import InterfacedBaseReader, Read... |
import sys
import uuid
import argparse
import pprint as pp
# import pydantic
import boto3
from botocore.exceptions import ClientError
s3 = boto3.resource('s3')
s3client = boto3.client('s3')
lambdaclient = boto3.client('lambda')
s3control = boto3.client('s3control')
sts = boto3.client("sts")
# Utils
def get_availabl... | [
"argparse.ArgumentParser",
"boto3.client",
"uuid.uuid1",
"boto3.resource",
"sys.exit"
] | [((142, 162), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (156, 162), False, 'import boto3\n'), ((174, 192), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (186, 192), False, 'import boto3\n'), ((208, 230), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
import six
from pathlib2 import Path
from ..frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...model import Framework
class PatchMegEngineMo... | [
"pathlib2.Path"
] | [((2989, 3003), 'pathlib2.Path', 'Path', (['filename'], {}), '(filename)\n', (2993, 3003), False, 'from pathlib2 import Path\n')] |
from database.adatabase import ADatabase
import pandas as pd
from cryptography.fernet import Fernet
import os
header_key = os.getenv("ROSTERKEY")
encryption_key = os.getenv("ENCRYPTIONKEY")
class CometRoster(ADatabase):
def __init__(self):
super().__init__("comet_roster")
def get_user_trade_p... | [
"os.getenv"
] | [((123, 145), 'os.getenv', 'os.getenv', (['"""ROSTERKEY"""'], {}), "('ROSTERKEY')\n", (132, 145), False, 'import os\n'), ((163, 189), 'os.getenv', 'os.getenv', (['"""ENCRYPTIONKEY"""'], {}), "('ENCRYPTIONKEY')\n", (172, 189), False, 'import os\n')] |
from http import HTTPStatus
from django.contrib.auth.models import Permission
from django.templatetags.static import static
from django.test import TestCase
from django.urls import reverse
from users.models import User
from ..utility import request_with_user
from ...forms import BaseMachineForm, EditMachineForm
from ... | [
"django.urls.reverse",
"django.templatetags.static.static",
"users.models.User.objects.create_user",
"django.contrib.auth.models.Permission.objects.get"
] | [((5393, 5455), 'users.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': 'username', 'password': 'password'}), '(username=username, password=password)\n', (5417, 5455), False, 'from users.models import User\n'), ((5484, 5533), 'django.contrib.auth.models.Permission.objects.get', 'Permissio... |
import datetime
from django.conf import settings
from django.contrib import admin
from django.urls import reverse
from django.utils.formats import localize
from django.utils.html import format_html
from automationlookup.models import UserLookup
from mediaplatform_jwp.api import delivery as api
from .models import Vi... | [
"django.contrib.admin.site.register",
"django.urls.reverse",
"django.contrib.admin.register",
"datetime.datetime.fromtimestamp",
"mediaplatform_jwp.api.delivery.player_embed_url",
"django.utils.html.format_html"
] | [((351, 400), 'django.contrib.admin.site.register', 'admin.site.register', (['UserLookup', 'admin.ModelAdmin'], {}), '(UserLookup, admin.ModelAdmin)\n', (370, 400), False, 'from django.contrib import admin\n'), ((404, 434), 'django.contrib.admin.register', 'admin.register', (['CachedResource'], {}), '(CachedResource)\n... |
import sys
k = int(sys.stdin.readline().strip())
stack = list()
for i in range(k):
item = int(sys.stdin.readline().strip())
if item == 0:
stack.pop()
else:
stack.append(item)
total = 0
for i in stack:
total += i
sys.stdout.write(str(total))
| [
"sys.stdin.readline"
] | [((20, 40), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (38, 40), False, 'import sys\n'), ((101, 121), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (119, 121), False, 'import sys\n')] |
import os as os_
import sys
import subprocess
platform_targets = (
# (os, arch, ext, compression)
('darwin', 'amd64', '', 'tar.gz'), # macOS
('linux', 'amd64', '', 'tar.gz'), # Ubuntu, ...
('windows', '386', '.exe', 'zip'), # Windows 32 bit
('windows', 'amd64', '.exe', 'zip'), # Windows 64 bit
... | [
"subprocess.run",
"os.remove",
"sys.stdout.flush",
"os.path.exists"
] | [((572, 590), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (588, 590), False, 'import sys\n'), ((595, 739), 'subprocess.run', 'subprocess.run', (['f"""GOOS={os} GOARCH={arch} go build -o build/{output_name}"""'], {'shell': '(True)', 'stdout': 'subprocess.DEVNULL', 'stderr': 'subprocess.DEVNULL'}), "(f'GOOS... |
# -*- coding: utf-8 -*-
import pytest
from sherlock.common.protocols import RedshiftExportProtocol
@pytest.fixture
def redshift_export_encoder():
return RedshiftExportProtocol()
@pytest.mark.parametrize("input_value, expected_value", [
('hello\nworld', 'hello\\nworld'), # embedded \n
('hello\... | [
"sherlock.common.protocols.RedshiftExportProtocol",
"pytest.mark.parametrize"
] | [((188, 455), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_value, expected_value"""', "[('hello\\nworld', 'hello\\\\nworld'), ('hello\\rworld', 'hello\\\\rworld'), (\n 'hello|world', 'hello\\\\|world'), ('hello\\\\world', 'hello\\\\\\\\world'), (\n 'hello\\\\\\nworld', 'hello\\\\\\\\\\\\nworl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=too-many-lines
'''Asset objects are objects that store per-instance data for Context objects.
They are necessary because Context objects are flyweights and, because of that,
cannot carry instance data.
'''
# IMPORT STANDARD LIBRARIES
# scspell-id: 3c62... | [
"functools.partial",
"six.iterkeys",
"ways.get_parse_order",
"re.match",
"six.moves.zip",
"collections.OrderedDict",
"six.iteritems",
"re.sub",
"os.getenv"
] | [((15881, 15906), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (15904, 15906), False, 'import collections\n'), ((15939, 15994), 'functools.partial', 'functools.partial', (['context.get_str'], {'display_tokens': '(True)'}), '(context.get_str, display_tokens=True)\n', (15956, 15994), False, 'im... |
#!/usr/bin/env python3
import boto3
import click
import os,subprocess,sys,time
from botocore.exceptions import ClientError
from tabulate import tabulate
def getpath(val,path):
if '.' in path:
head,tail = path.split('.',2)
return getpath(val[head],tail)
else:
return val[path]
def extr... | [
"subprocess.run",
"click.argument",
"boto3.client",
"click.option",
"click.File",
"click.echo",
"time.sleep",
"tabulate.tabulate",
"click.group",
"os.getenv",
"sys.exit"
] | [((707, 720), 'click.group', 'click.group', ([], {}), '()\n', (718, 720), False, 'import click\n'), ((758, 816), 'click.option', 'click.option', (['"""--name"""'], {'default': 'None', 'help': '"""Instance name"""'}), "('--name', default=None, help='Instance name')\n", (770, 816), False, 'import click\n'), ((816, 882), ... |
import onnx
loaded = onnx.load('lenet.onnx') | [
"onnx.load"
] | [((22, 45), 'onnx.load', 'onnx.load', (['"""lenet.onnx"""'], {}), "('lenet.onnx')\n", (31, 45), False, 'import onnx\n')] |
"""
Louvain no isolation first then inserting.
"""
import numpy as np
import json
import sys
import os
import argparse
sys.path.append(os.path.abspath('../lib/'))
from dataloader.dataloader import dataloader
from model.siamodel import RSN
from module.semiclusters import prepare_cluster_list, Top_Down_Louvain_with_tes... | [
"dataloader.dataloader.dataloader",
"os.path.abspath",
"evaluation.evaluation.ClusterEvaluation",
"module.semiclusters.Top_Down_Louvain_with_test_cluster_done_avg_link_list",
"argparse.ArgumentParser",
"model.siamodel.RSN",
"os.makedirs",
"module.clusters.Louvain_no_isolation",
"os.path.exists",
"... | [((136, 162), 'os.path.abspath', 'os.path.abspath', (['"""../lib/"""'], {}), "('../lib/')\n", (151, 162), False, 'import os\n'), ((2061, 2364), 'kit.messager.messager', 'messager', ([], {'save_path': 'save_path', 'types': "['train_data_file', 'val_data_file', 'test_data_file', 'load_model_name',\n 'save_model_name',... |
# ------------------------------------------------------------------------------#
# (1)
# Write min. 2 functions which handle the reading, processing and visualization
# of a time series of transactions for one location (dependant on an argument)
# (you can use the sum, mean or median) for the transactions on one day.... | [
"pandas.read_csv",
"pylab.show",
"matplotlib.pyplot.show",
"pandas.DataFrame"
] | [((628, 638), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (636, 638), True, 'import matplotlib.pyplot as plt\n'), ((858, 868), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (866, 868), True, 'import matplotlib.pyplot as plt\n'), ((1115, 1148), 'pandas.read_csv', 'pd.read_csv', (['"""data/cc_data_1... |
from copy import deepcopy
import tensorflow as tf
class EpochTrainer:
def __init__(
self, name, iterator, net, Loss, loss_coeffs=None, coeffs={}, log_freq=100, training=True
):
self.name = name
self.iterator = iterator
self.log_freq = log_freq
self.ph = {}
# d... | [
"tensorflow.placeholder",
"copy.deepcopy",
"tensorflow.train.AdamOptimizer"
] | [((433, 449), 'copy.deepcopy', 'deepcopy', (['coeffs'], {}), '(coeffs)\n', (441, 449), False, 'from copy import deepcopy\n'), ((1031, 1062), 'tensorflow.placeholder', 'tf.placeholder', (['"""float32"""', 'None'], {}), "('float32', None)\n", (1045, 1062), True, 'import tensorflow as tf\n'), ((1082, 1208), 'tensorflow.tr... |
#!/usr/bin/env python
"""
mini.py: minifies and compresses static content.
yuicompressor, htmlcompressor, uglifyjs, and lessc are run against the
CSS, JS, HTML. Then CSS, JS, and images are GZipped.
The result is a tar archive pumped to stdout.
"""
""" Version history
1.0.0 - Initial build (Based off... | [
"shutil.ignore_patterns",
"subprocess.Popen",
"optparse.OptionParser",
"os.path.basename",
"os.getcwd",
"os.path.isdir",
"os.path.dirname",
"time.time",
"os.path.splitext",
"traceback.format_exc",
"os.path.join",
"os.listdir",
"re.compile"
] | [((756, 767), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (765, 767), False, 'import os\n'), ((780, 808), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (795, 808), False, 'import os\n'), ((8434, 8448), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (8446, 8448), False, 'fro... |
import os
import unittest
from ...BaseTestCase import BaseTestCase
from kombi.Crawler import Crawler
from kombi.Crawler.Fs import FsCrawler
from kombi.Crawler.Fs import FileCrawler
from kombi.Crawler.PathHolder import PathHolder
from kombi.Crawler.Fs.Render import ExrRenderCrawler
from kombi.Crawler.Fs.Image import Exr... | [
"unittest.main",
"kombi.Crawler.Crawler.register",
"os.path.basename",
"kombi.Crawler.Fs.FsCrawler.test",
"os.path.dirname",
"kombi.Crawler.Fs.FsCrawler.createFromPath",
"kombi.Crawler.Crawler.registeredNames",
"os.path.splitext",
"kombi.Crawler.Crawler.createFromJson",
"kombi.Crawler.Crawler.regi... | [((603, 678), 'os.path.join', 'os.path.join', (['__dir', '"""images"""', '"""RND_ass_lookdev_default_beauty_tt.1001.exr"""'], {}), "(__dir, 'images', 'RND_ass_lookdev_default_beauty_tt.1001.exr')\n", (615, 678), False, 'import os\n'), ((702, 774), 'os.path.join', 'os.path.join', (['__dir', '"""images"""', '"""RND-TST-S... |
import cerberus
import dateutil.parser
TYPES = {
'simple': cerberus.Validator(
{
'foo': {
'required': True,
'type': 'string',
},
},
),
'complex': cerberus.Validator(
{
'boolean': {
'required': True,... | [
"cerberus.Validator"
] | [((65, 130), 'cerberus.Validator', 'cerberus.Validator', (["{'foo': {'required': True, 'type': 'string'}}"], {}), "({'foo': {'required': True, 'type': 'string'}})\n", (83, 130), False, 'import cerberus\n'), ((232, 638), 'cerberus.Validator', 'cerberus.Validator', (["{'boolean': {'required': True, 'type': 'boolean'}, 'i... |
from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter
from sqlalchemy.orm import Session
from .. import schemas, database, models, oauth2
router = APIRouter(
prefix="/like",
tags=['Like']
)
@router.post("/", status_code=status.HTTP_201_CREATED)
def like(like: schemas.Like, db: Ses... | [
"fastapi.HTTPException",
"fastapi.Depends",
"fastapi.APIRouter"
] | [((176, 216), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/like"""', 'tags': "['Like']"}), "(prefix='/like', tags=['Like'])\n", (185, 216), False, 'from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter\n'), ((327, 351), 'fastapi.Depends', 'Depends', (['database.get_db'], {}), '(data... |
import torch
from mmlib.schema.environment import Environment
from mmlib.schema.restorable_object import StateDictRestorableObjectWrapper
from mmlib.util.helper import class_name, source_file
class TrainSaveInfo:
def __init__(self, train_service_wrapper: StateDictRestorableObjectWrapper, train_kwargs: dict):
... | [
"mmlib.util.helper.source_file",
"mmlib.util.helper.class_name"
] | [((411, 445), 'mmlib.util.helper.source_file', 'source_file', (['train_service_wrapper'], {}), '(train_service_wrapper)\n', (422, 445), False, 'from mmlib.util.helper import class_name, source_file\n'), ((486, 519), 'mmlib.util.helper.class_name', 'class_name', (['train_service_wrapper'], {}), '(train_service_wrapper)\... |
from __future__ import annotations
import csv
from typing import Any, Dict, List, Optional, TextIO, Type, TypeVar, cast
import dcp.storage.base as storage
import pandas as pd
import sqlalchemy as sa
import sqlalchemy.types as satypes
from commonmodel import (
DEFAULT_FIELD_TYPE,
Boolean,
Date,
DateTim... | [
"typing.TypeVar",
"dcp.storage.base.get_api",
"csv.reader",
"dcp.utils.data.is_maybe_csv"
] | [((916, 934), 'typing.TypeVar', 'TypeVar', (['"""CsvFile"""'], {}), "('CsvFile')\n", (923, 934), False, 'from typing import Any, Dict, List, Optional, TextIO, Type, TypeVar, cast\n'), ((1583, 1598), 'dcp.utils.data.is_maybe_csv', 'is_maybe_csv', (['s'], {}), '(s)\n', (1595, 1598), False, 'from dcp.utils.data import inf... |
from playgrounds.opencv import face_detection
from playgrounds.keras_models.features.dog_cat import detect_dog_cat
from playgrounds.keras_models.features.multi_dector import featureDetector
from playgrounds.keras_models.features.face_recognition import face_recognition_detector
from playgrounds.keras_models.features.gi... | [
"playgrounds.keras_models.features.dog_cat.detect_dog_cat.DogCatFeature",
"playgrounds.keras_models.features.face_recognition.face_recognition_detector.FaceRecognition",
"playgrounds.keras_models.features.multi_dector.featureDetector.FeatureDetector",
"playgrounds.keras_models.features.girl_boy.girl_boy_featu... | [((422, 452), 'playgrounds.keras_models.features.dog_cat.detect_dog_cat.DogCatFeature', 'detect_dog_cat.DogCatFeature', ([], {}), '()\n', (450, 452), False, 'from playgrounds.keras_models.features.dog_cat import detect_dog_cat\n'), ((476, 509), 'playgrounds.keras_models.features.multi_dector.featureDetector.FeatureDete... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import struct
import sys
import inspect
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/nfcpy')
import nfc
service_code = 0x090f
num_blocks = 20
def connected(tag):
# tag のメソッド一覧を出す
print(type(tag))
print(inspect.getmembers(tag, inspect.i... | [
"os.path.abspath",
"nfc.ContactlessFrontend",
"inspect.getmembers"
] | [((344, 374), 'nfc.ContactlessFrontend', 'nfc.ContactlessFrontend', (['"""usb"""'], {}), "('usb')\n", (367, 374), False, 'import nfc\n'), ((287, 328), 'inspect.getmembers', 'inspect.getmembers', (['tag', 'inspect.ismethod'], {}), '(tag, inspect.ismethod)\n', (305, 328), False, 'import inspect\n'), ((130, 155), 'os.path... |
import importlib
import json as jm
from pylaut.pylautlang import lib
class MissingDataError(Exception):
pass
class LibraryError(Exception):
pass
class LibraryVersionError(LibraryError):
pass
class SoundLaw():
"""
A wrapper class for a set of sound changes.
Includes all the nice human-rea... | [
"json.loads",
"importlib.import_module",
"json.dumps",
"pylaut.pylautlang.lib.get_library",
"importlib.util.spec_from_file_location",
"importlib.util.module_from_spec"
] | [((3730, 3753), 'json.dumps', 'jm.dumps', (['obj'], {'indent': '(2)'}), '(obj, indent=2)\n', (3738, 3753), True, 'import json as jm\n'), ((5985, 6008), 'json.dumps', 'jm.dumps', (['obj'], {'indent': '(2)'}), '(obj, indent=2)\n', (5993, 6008), True, 'import json as jm\n'), ((1081, 1099), 'json.loads', 'jm.loads', (['jso... |
#Setting up database for Integration engine
#Starting with sqlAlchemy
#<NAME> September 2016
import sys
from sqlalchemy import Column, Table, ForeignKey, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from ... | [
"sqlalchemy_utils.create_database",
"sqlalchemy_utils.database_exists",
"sqlalchemy.String",
"sqlalchemy.ForeignKey",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.orm.relationship",
"sqlalchemy.Column",
"sqlalchemy.create_engine"
] | [((402, 420), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (418, 420), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((5863, 5900), 'sqlalchemy.create_engine', 'create_engine', (['settings.db_connection'], {}), '(settings.db_connection)\n', (5876, 5900), Fa... |
__author__ = 'jbjohnso'
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Lenovo Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... | [
"threading.Thread",
"atexit.register",
"os.remove",
"os.chmod",
"socket.socket"
] | [((977, 1026), 'socket.socket', 'socket.socket', (['socket.AF_UNIX', 'socket.SOCK_STREAM'], {}), '(socket.AF_UNIX, socket.SOCK_STREAM)\n', (990, 1026), False, 'import socket\n'), ((1156, 1186), 'atexit.register', 'atexit.register', (['self.shutdown'], {}), '(self.shutdown)\n', (1171, 1186), False, 'import atexit\n'), (... |
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import DetailView, UpdateView
from django.contrib.auth.models import User
from accounts.forms import UserProfileForm
from accounts.models import UserProfile
class ProfileDetailView(DetailView):
model = User
templ... | [
"django.urls.reverse"
] | [((879, 897), 'django.urls.reverse', 'reverse', (['"""profile"""'], {}), "('profile')\n", (886, 897), False, 'from django.urls import reverse\n')] |
import os
import cv2
import gym
import torch
import random
import numpy as np
from six import iteritems
from datetime import datetime
def seed(seed):
torch.cuda.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
def evaluate_policy(env, policy, eval_episodes=10, max_tim... | [
"numpy.uint8",
"numpy.random.seed",
"numpy.multiply",
"os.makedirs",
"torch.manual_seed",
"torch.cuda.manual_seed",
"numpy.expand_dims",
"os.path.exists",
"cv2.addWeighted",
"random.seed",
"numpy.array",
"cv2.applyColorMap",
"cv2.resize"
] | [((156, 184), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (178, 184), False, 'import torch\n'), ((189, 212), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (206, 212), False, 'import torch\n'), ((217, 237), 'numpy.random.seed', 'np.random.seed', (['seed'], {}),... |
from django.shortcuts import render, redirect
from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect
import datetime
from apartments.models import Apartment, Contract
from authentication.forms import RegisterForm
from authentication.models import Profile
from django.db.models impor... | [
"apartments.models.Apartment.objects.filter",
"django.contrib.messages.success",
"django.http.HttpResponseRedirect",
"apartments.models.Apartment.objects.get",
"datetime.datetime.today",
"django.shortcuts.redirect",
"django.contrib.messages.error",
"django.db.models.Q",
"authentication.forms.Registe... | [((4593, 4652), 'apartments.models.Apartment.objects.filter', 'Apartment.objects.filter', ([], {'original_owner': 'request.user.email'}), '(original_owner=request.user.email)\n', (4617, 4652), False, 'from apartments.models import Apartment, Contract\n'), ((4729, 4768), 'authentication.models.Profile.objects.get', 'Pro... |
import json
import traceback
from typing import Dict, cast
import ansible_runner
import demistomock as demisto # noqa: F401
import ssh_agent_setup
from CommonServerPython import * # noqa: F401
# Dict to Markdown Converter adapted from https://github.com/PolBaladas/torsimany/
def dict2md(json_block, depth=0):
m... | [
"demistomock.args",
"ssh_agent_setup.setup",
"demistomock.command",
"traceback.format_exc",
"demistomock.params",
"ansible_runner.run"
] | [((2881, 3058), 'ansible_runner.run', 'ansible_runner.run', ([], {'inventory': 'inventory', 'host_pattern': '"""all"""', 'module': 'command', 'quiet': '(True)', 'omit_event_data': '(True)', 'ssh_key': 'sshkey', 'module_args': 'module_args', 'forks': 'fork_count'}), "(inventory=inventory, host_pattern='all', module=comm... |
from unittest import mock
import chainer
import numpy as np
import pytest
from deep_sentinel.models.dnn.model.layers import mid
chainer.global_config.train = False
chainer.global_config.enable_backprop = False
@pytest.fixture
def activate_func():
m = mock.MagicMock()
m.side_effect = lambda x: x
return ... | [
"unittest.mock.MagicMock",
"deep_sentinel.models.dnn.model.layers.mid.MidLayer",
"numpy.arange",
"numpy.array",
"pytest.mark.parametrize"
] | [((433, 610), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data, n_units"""', '[([[[0, 0], [0, 0]], [[0, 0], [0, 0]]], 5), ([[[0], [0], [0], [0]], [[0], [\n 0], [0], [0]]], 4), ([[[0, 0, 0], [0, 0, 0]]], 3)]'], {}), "('data, n_units', [([[[0, 0], [0, 0]], [[0, 0], [0, \n 0]]], 5), ([[[0], [0], [0],... |
"""used to verify methods in ckanCompare
"""
import logging
import pytest
# pylint: disable=logging-format-interpolation
LOGGER = logging.getLogger(__name__)
def test_package_list_Test(CKANWrapperTest):
pkgNamesTest = CKANWrapperTest.getPackageNames()
LOGGER.debug(f"pkgNamesTest count: {len(pkgNamesTe... | [
"logging.getLogger"
] | [((134, 161), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (151, 161), False, 'import logging\n')] |
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class TopNIoUAssigner(BaseAssigner):
"""Assign a corresponding gt bbox or background to each bbox.... | [
"torch.nonzero",
"torch.sort"
] | [((5686, 5726), 'torch.sort', 'torch.sort', (['overlaps', '(0)'], {'descending': '(True)'}), '(overlaps, 0, descending=True)\n', (5696, 5726), False, 'import torch\n'), ((5893, 5933), 'torch.sort', 'torch.sort', (['overlaps', '(1)'], {'descending': '(True)'}), '(overlaps, 1, descending=True)\n', (5903, 5933), False, 'i... |
#!/usr/bin/env python
"""Manage Protobuf Metadata for Birdsong Project"""
import pickle
import metadata_pb2
from datetime import datetime
import pytz
import json
import pickle
from operator import attrgetter
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
__au... | [
"json.dump",
"json.load",
"metadata_pb2.Session",
"google.protobuf.json_format.ParseDict",
"pytz.timezone",
"google.protobuf.json_format.MessageToDict"
] | [((715, 737), 'metadata_pb2.Session', 'metadata_pb2.Session', ([], {}), '()\n', (735, 737), False, 'import metadata_pb2\n'), ((17974, 18151), 'google.protobuf.json_format.MessageToDict', 'MessageToDict', (['self.sess'], {'including_default_value_fields': '(True)', 'preserving_proto_field_name': '(True)', 'use_integers_... |
import os
import logging
from environment import DEBUG_MODE
# path for databases or config files
if not os.path.exists('data/'):
os.mkdir('data/')
# set logging format
formatter = logging.Formatter("[{asctime}] [{levelname}] [{name}] {message}", style="{")
# logger for writing to file
file_logger = logging.File... | [
"os.mkdir",
"logging.FileHandler",
"logging.StreamHandler",
"os.path.exists",
"logging.Formatter",
"logging.getLogger"
] | [((187, 263), 'logging.Formatter', 'logging.Formatter', (['"""[{asctime}] [{levelname}] [{name}] {message}"""'], {'style': '"""{"""'}), "('[{asctime}] [{levelname}] [{name}] {message}', style='{')\n", (204, 263), False, 'import logging\n'), ((308, 346), 'logging.FileHandler', 'logging.FileHandler', (['"""data/events.lo... |
import glob
import gzip
import json
import os
from hoover.users import get_user_ids
def get_tweet_ids(tweet_ids_file):
tweet_ids = set()
with open(tweet_ids_file, 'rt') as f:
for line in f:
tid = line.strip()
if len(tid) > 0:
tweet_ids.add(tid)
print('{} twe... | [
"gzip.open",
"json.loads",
"json.dumps",
"hoover.users.get_user_ids"
] | [((554, 574), 'hoover.users.get_user_ids', 'get_user_ids', (['infile'], {}), '(infile)\n', (566, 574), False, 'from hoover.users import get_user_ids\n'), ((1365, 1388), 'gzip.open', 'gzip.open', (['infile', '"""rt"""'], {}), "(infile, 'rt')\n", (1374, 1388), False, 'import gzip\n'), ((2757, 2782), 'json.dumps', 'json.d... |
from flask import jsonify, make_response, abort, current_app
from flask_restful import reqparse
from homeautomation.models import StockProduct
from homeautomation.schemas import ProductSchema
from .base import BaseResource
class StockCategoryProducts(BaseResource):
"""
Api to return all subCategorys of the ... | [
"flask_restful.reqparse.RequestParser",
"flask.abort",
"flask.current_app.logger.debug",
"flask.jsonify",
"homeautomation.schemas.ProductSchema"
] | [((585, 609), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (607, 609), False, 'from flask_restful import reqparse\n'), ((1090, 1100), 'flask.abort', 'abort', (['(405)'], {}), '(405)\n', (1095, 1100), False, 'from flask import jsonify, make_response, abort, current_app\n'), ((1142,... |
from django.db import models
from twitteruser.models import TwitterUser
from django.utils.timezone import now
# Create your models here.
class Tweet(models.Model):
title = models.CharField(max_length=40)
body = models.CharField(max_length=140)
dt_posted = models.DateTimeField(default=now)
posted_by ... | [
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.models.ForeignKey"
] | [((180, 211), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)'}), '(max_length=40)\n', (196, 211), False, 'from django.db import models\n'), ((223, 255), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(140)'}), '(max_length=140)\n', (239, 255), False, 'from django.db ... |
#!/usr/bin/env python3
#Python program to write into and read from a csv file
import csv
with open("data.csv", 'w') as file:
writer = csv.writer(file)
writer.writerow(["name", "age", "gender"])
writer.writerow(["Swathi", 15, "F"])
writer.writerow(["Santosh", 25, "M"])
with open("data.csv") as file:
... | [
"csv.reader",
"csv.writer"
] | [((140, 156), 'csv.writer', 'csv.writer', (['file'], {}), '(file)\n', (150, 156), False, 'import csv\n'), ((332, 348), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (342, 348), False, 'import csv\n')] |
import os
import compiler
import interp_Pvar
import type_check_Pvar
from utils import run_tests, run_one_test
compiler = compiler.Compiler()
if False:
run_one_test(os.getcwd() + '/tests/var/zero.py', 'var',
compiler, 'var',
type_check_Pvar.TypeCheckPvar().type_check_P,
... | [
"os.getcwd",
"interp_Pvar.InterpPvar",
"type_check_Pvar.TypeCheckPvar",
"compiler.Compiler"
] | [((122, 141), 'compiler.Compiler', 'compiler.Compiler', ([], {}), '()\n', (139, 141), False, 'import compiler\n'), ((169, 180), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (178, 180), False, 'import os\n'), ((263, 294), 'type_check_Pvar.TypeCheckPvar', 'type_check_Pvar.TypeCheckPvar', ([], {}), '()\n', (292, 294), Fals... |
# Copyright (C) 2016-2021 Alibaba Group Holding Limited
#
# 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 l... | [
"tensorflow.core.protobuf.cluster_pb2.ClusterDef",
"socket.socket",
"json.dumps",
"efl.exporter.export",
"time.sleep",
"socket.gethostname",
"multiprocessing.Queue",
"multiprocessing.Process",
"tensorflow.python.training.server_lib.ClusterSpec"
] | [((1974, 2009), 'efl.exporter.export', 'exporter.export', (['"""ServiceDiscovery"""'], {}), "('ServiceDiscovery')\n", (1989, 2009), False, 'from efl import exporter\n'), ((4288, 4330), 'efl.exporter.export', 'exporter.export', (['"""start_service_discovery"""'], {}), "('start_service_discovery')\n", (4303, 4330), False... |
import unittest
import libtorrent as lt
class GenerateFingerprintTest(unittest.TestCase):
@unittest.skip("https://github.com/arvidn/libtorrent/issues/5985")
def test_generate(self) -> None:
# full version
self.assertEqual(
lt.generate_fingerprint_bytes(b"ABCD", 1, 2, 3, 4), # typ... | [
"unittest.skip",
"libtorrent.fingerprint",
"libtorrent.generate_fingerprint_bytes",
"libtorrent.generate_fingerprint"
] | [((98, 163), 'unittest.skip', 'unittest.skip', (['"""https://github.com/arvidn/libtorrent/issues/5985"""'], {}), "('https://github.com/arvidn/libtorrent/issues/5985')\n", (111, 163), False, 'import unittest\n'), ((1067, 1132), 'unittest.skip', 'unittest.skip', (['"""https://github.com/arvidn/libtorrent/issues/5988"""']... |
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
class TestCommands(TestCase):
def test_index_contracts_with_metadata(self):
command = "index_contracts_with_metadata"
buf = StringIO()
call_command(command, stdout=buf)
self.a... | [
"django.core.management.call_command",
"io.StringIO"
] | [((253, 263), 'io.StringIO', 'StringIO', ([], {}), '()\n', (261, 263), False, 'from io import StringIO\n'), ((272, 305), 'django.core.management.call_command', 'call_command', (['command'], {'stdout': 'buf'}), '(command, stdout=buf)\n', (284, 305), False, 'from django.core.management import call_command\n'), ((498, 508... |
from django.contrib import admin
from .models import userdetails
admin.site.register(userdetails)
# Register your models here.
| [
"django.contrib.admin.site.register"
] | [((66, 98), 'django.contrib.admin.site.register', 'admin.site.register', (['userdetails'], {}), '(userdetails)\n', (85, 98), False, 'from django.contrib import admin\n')] |
from typing import List
import logging
from ROAR.utilities_module.data_structures_models import Transform
from collections import deque
from ROAR.planning_module.abstract_planner import AbstractPlanner
class MissionPlanner(AbstractPlanner):
def __init__(self, agent, **kwargs):
super().__init__(agent=agent... | [
"collections.deque",
"logging.getLogger"
] | [((353, 380), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (370, 380), False, 'import logging\n'), ((416, 423), 'collections.deque', 'deque', ([], {}), '()\n', (421, 423), False, 'from collections import deque\n')] |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import missingno as ms
import re
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.ensemble import RandomForestClassifier
from sklear... | [
"sklearn.ensemble.RandomForestClassifier",
"pandas.DataFrame",
"sklearn.feature_extraction.text.CountVectorizer",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.confusion_matrix",
"re.sub",
"sklearn.feat... | [((496, 522), 'pandas.read_csv', 'pd.read_csv', (['"""dataset.csv"""'], {}), "('dataset.csv')\n", (507, 522), True, 'import pandas as pd\n'), ((669, 774), 're.sub', 're.sub', (['"""(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])"""', '""" """', '"""Hahahahahaa chal janu zaroor 😂😂😂😂😂"""'], {}), "('(@[A-Za-z0-9]+)|([^0-... |
from unittest import TestCase
from mock import Mock
from common.wrappers.command_wrapper import CommandWrapper
class TestCommandWrapper(TestCase):
def setUp(self):
self.si = Mock()
self.logger = Mock()
self.connection_detail = Mock()
self.pv_service = Mock()
self.pv_servic... | [
"common.wrappers.command_wrapper.CommandWrapper",
"mock.Mock"
] | [((189, 195), 'mock.Mock', 'Mock', ([], {}), '()\n', (193, 195), False, 'from mock import Mock\n'), ((218, 224), 'mock.Mock', 'Mock', ([], {}), '()\n', (222, 224), False, 'from mock import Mock\n'), ((258, 264), 'mock.Mock', 'Mock', ([], {}), '()\n', (262, 264), False, 'from mock import Mock\n'), ((291, 297), 'mock.Moc... |
import graphene_django_optimizer as gql_optimizer
from ...payment import models
from ...payment.interface import TokenConfig
from ...payment.utils import fetch_customer_id, gateway_get_client_token
from ..utils import filter_by_query_param
PAYMENT_SEARCH_FIELDS = ["id"]
def resolve_payments(info, query):
querys... | [
"graphene_django_optimizer.query"
] | [((453, 488), 'graphene_django_optimizer.query', 'gql_optimizer.query', (['queryset', 'info'], {}), '(queryset, info)\n', (472, 488), True, 'import graphene_django_optimizer as gql_optimizer\n')] |
from builtins import object
from nineml.exceptions import (
NineMLSerializationError, NineMLMissingSerializationError,
NineMLUnexpectedMultipleSerializationError)
from nineml.reference import Reference
from nineml.annotations import Annotations
from nineml.utils import validate_identifier
class BaseNode(objec... | [
"nineml.utils.validate_identifier"
] | [((6397, 6422), 'nineml.utils.validate_identifier', 'validate_identifier', (['name'], {}), '(name)\n', (6416, 6422), False, 'from nineml.utils import validate_identifier\n')] |
from unittest import mock
import pytest
from aes.files import decrypt_file, encrypt_file
# pylint: disable=redefined-outer-name
@pytest.fixture(params=["file.txt", "foo/file.txt", "folder/doc.pdf"])
def filepath(request):
return request.param
@pytest.fixture(params=[None, "new-password"])
def password(reques... | [
"pytest.fixture",
"unittest.mock.patch.stopall",
"aes.files.encrypt_file",
"unittest.mock.patch",
"aes.files.decrypt_file"
] | [((134, 203), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['file.txt', 'foo/file.txt', 'folder/doc.pdf']"}), "(params=['file.txt', 'foo/file.txt', 'folder/doc.pdf'])\n", (148, 203), False, 'import pytest\n'), ((255, 300), 'pytest.fixture', 'pytest.fixture', ([], {'params': "[None, 'new-password']"}), "(params=... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
from __future__ import print_function
from __future__ import division
from six.moves import range
import os
import glob
import sys
import datetime
import subprocess
d... | [
"os.makedirs",
"os.path.basename",
"os.getcwd",
"os.path.exists",
"datetime.datetime.now",
"os.path.join"
] | [((1074, 1099), 'os.path.basename', 'os.path.basename', (['dirname'], {}), '(dirname)\n', (1090, 1099), False, 'import os\n'), ((1397, 1420), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1418, 1420), False, 'import datetime\n'), ((987, 1016), 'os.path.exists', 'os.path.exists', (['"""evaluations... |
import random
import unittest
import binary_search
SEARCH_METHODS = (binary_search.iterative_s, binary_search.recursive_s)
class TestBinarySearch(unittest.TestCase):
def testSearchEmptyList(self):
l = []
for search in SEARCH_METHODS:
self.assertIsNone(search(l, 1))
def testSearchSingleElement(se... | [
"unittest.main",
"random.randint"
] | [((1502, 1517), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1515, 1517), False, 'import unittest\n'), ((1118, 1146), 'random.randint', 'random.randint', (['(1)', '(100000000)'], {}), '(1, 100000000)\n', (1132, 1146), False, 'import random\n'), ((1182, 1210), 'random.randint', 'random.randint', (['(1)', '(10000... |
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, StandardOptions
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input',
dest='input',
required=True,
help='Input file to... | [
"apache_beam.Map",
"argparse.ArgumentParser",
"apache_beam.Filter",
"apache_beam.io.ReadFromText",
"apache_beam.Pipeline",
"apache_beam.options.pipeline_options.PipelineOptions",
"apache_beam.CombinePerKey",
"apache_beam.io.WriteToText"
] | [((135, 160), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (158, 160), False, 'import argparse\n'), ((642, 672), 'apache_beam.options.pipeline_options.PipelineOptions', 'PipelineOptions', (['pipeline_args'], {}), '(pipeline_args)\n', (657, 672), False, 'from apache_beam.options.pipeline_optio... |
#!/usr/bin python3
""" Stats functions for the GUI """
import time
import os
import warnings
from math import ceil, sqrt
import numpy as np
from lib.Serializer import PickleSerializer
class SavedSessions(object):
""" Saved Training Session """
def __init__(self, sessions_data):
self.serializer = P... | [
"numpy.poly1d",
"warnings.simplefilter",
"math.ceil",
"numpy.polyfit",
"time.gmtime",
"time.time",
"os.path.isfile",
"os.path.join"
] | [((515, 539), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (529, 539), False, 'import os\n'), ((1785, 1796), 'time.time', 'time.time', ([], {}), '()\n', (1794, 1796), False, 'import time\n'), ((1925, 1973), 'os.path.join', 'os.path.join', (['self.modeldir', '"""trainingstats.fss"""'], {}), "(... |
import json
import os
import re
import zlib
import markovify
import requests
from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import Signal, receiver
from django_rq import job as queue_job
from TwitterAPI import TwitterAPI
from .exceptions import TwitterA... | [
"django.dispatch.Signal",
"json.loads",
"os.path.dirname",
"django.dispatch.receiver",
"markovify.NewlineText",
"os.environ.get",
"requests.get",
"os.path.join",
"re.sub"
] | [((429, 463), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['account']"}), "(providing_args=['account'])\n", (435, 463), False, 'from django.dispatch import Signal, receiver\n'), ((490, 524), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['account']"}), "(providing_args=['account'])\n", (... |
from uuid import UUID
from crosswalk_client.exceptions import MalformedUUID
def validate_target_uuid_arg(function):
"""
Target UUIDs are used to set foreign keys and should be either a valid UUID
or None to unset the foreign key.
"""
def wrapper(*args, **kwargs):
uuid = args[2]
i... | [
"crosswalk_client.exceptions.MalformedUUID"
] | [((389, 429), 'crosswalk_client.exceptions.MalformedUUID', 'MalformedUUID', (['"""Invalid UUID for target"""'], {}), "('Invalid UUID for target')\n", (402, 429), False, 'from crosswalk_client.exceptions import MalformedUUID\n')] |
''' Extensions of the contextlib library '''
from contextlib import contextmanager
from functools import wraps
def safecontextmanager(func):
''' Behaves similarly to context manager, but if an exception occurs during the context execution, we ensure
that the cleanup code is called prior to re-raising the... | [
"contextlib.contextmanager",
"functools.wraps"
] | [((1439, 1450), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1444, 1450), False, 'from functools import wraps\n'), ((1924, 1952), 'contextlib.contextmanager', 'contextmanager', (['wrapped_func'], {}), '(wrapped_func)\n', (1938, 1952), False, 'from contextlib import contextmanager\n')] |
import sys
from inspect import signature
import pytest
from parametrize.utils import copy_code, copy_func
@pytest.mark.skipif(
sys.version_info >= (3, 8), reason="On PY38 builtin CodeType.replace method is used"
)
def test_copy_code():
def f():
return locals()["a"]
copied_without_changes = copy... | [
"parametrize.utils.copy_code",
"pytest.raises",
"pytest.mark.skipif",
"inspect.signature"
] | [((111, 220), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(sys.version_info >= (3, 8))'], {'reason': '"""On PY38 builtin CodeType.replace method is used"""'}), "(sys.version_info >= (3, 8), reason=\n 'On PY38 builtin CodeType.replace method is used')\n", (129, 220), False, 'import pytest\n'), ((316, 337), 'parame... |
import sys
payload = ''
payload += 'a'*(0x00007fffffffea28 - 0x00007fffffffe810)
payload += '\x20\x0d\x40\x00' + '\x00'*4 # 0x400d20
payload += 'dummystr'
payload += '\x20\x0d\x60\x00' + '\x00'*4 # 0x600d20
payload += '\n'
payload += 'LIBC_FATAL_STDERR_=1\n' # for getc
sys.stdout.write(payload)
| [
"sys.stdout.write"
] | [((274, 299), 'sys.stdout.write', 'sys.stdout.write', (['payload'], {}), '(payload)\n', (290, 299), False, 'import sys\n')] |
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
def images_from_samples(samples, dimensions=(5, 5), epoch=None, save=True):
# Remove channel dimension if present
if samples.ndim > 3 and samples.shape[-1] == 1:
samples = samples.squeeze(axis=3)
fig = plt.figure(figsize=di... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"tensorflow.summary.scalar",
"matplotlib.pyplot.imshow",
"tensorflow.reduce_mean",
"matplotlib.pyplot.axis",
"tensorflow.placeholder",
"matplotlib.pyplot.figure",
"tensorflow.summary.FileWriter",
"tensorflow.summary.histogram",
"tensorflow.n... | [((299, 329), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'dimensions'}), '(figsize=dimensions)\n', (309, 329), True, 'import matplotlib.pyplot as plt\n'), ((781, 791), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (789, 791), True, 'import matplotlib.pyplot as plt\n'), ((2053, 2114), 'tensorfl... |
'''
daily_subset_and_rename.py
Purpose: copy images from times X to Y for each day to new folder, optionally rename using batch_rename.py
'''
import os
import sys
import glob
import re
import shutil
import batch_rename
def int2padstr(int_val):
"""
:param int_val:
:return:
"""
if int_val < 10:
... | [
"os.mkdir",
"argparse.ArgumentParser",
"shutil.copy2",
"os.path.exists",
"batch_rename.main",
"os.path.join",
"re.compile"
] | [((1004, 1045), 're.compile', 're.compile', (["(time_range + ':\\\\d{2}:\\\\d{2}')"], {}), "(time_range + ':\\\\d{2}:\\\\d{2}')\n", (1014, 1045), False, 'import re\n'), ((2302, 2327), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2325, 2327), False, 'import argparse\n'), ((1450, 1463), 'os.mk... |
import requests
import sys
import os
from pyspark.sql import SparkSession
def MongoDB():
# Pass the valid MongoDB uri. format: mongodb://local(or)RemoteIP/databaseName.collectionName
spark = SparkSession \
.builder \
.master("local") \
.appName("MongoDB_Python") \
.config("spark.mongodb.output.uri", ... | [
"pyspark.sql.SparkSession.builder.master"
] | [((200, 236), 'pyspark.sql.SparkSession.builder.master', 'SparkSession.builder.master', (['"""local"""'], {}), "('local')\n", (227, 236), False, 'from pyspark.sql import SparkSession\n')] |
from __future__ import division
from io import BytesIO
import os
import os.path as op
import numpy as np
from PIL import Image
from traits.api import String, Tuple, provides
from .cacheing_decorators import lru_cache
from .i_tile_manager import ITileManager
from .tile_manager import TileManager
@provides(ITileMan... | [
"io.BytesIO",
"numpy.load",
"os.path.isdir",
"traits.api.provides",
"os.path.exists",
"PIL.Image.fromarray",
"os.path.join",
"os.listdir"
] | [((303, 325), 'traits.api.provides', 'provides', (['ITileManager'], {}), '(ITileManager)\n', (311, 325), False, 'from traits.api import String, Tuple, provides\n'), ((1880, 1896), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1890, 1896), False, 'import os\n'), ((872, 890), 'numpy.load', 'np.load', (['tile_p... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
TWITTER_API_KEY="buR7ZaXdML975jbgGyb7jfWNS"
TWITTER_API_KEY_SECRET="<KEY>"
BASILICA_KEY="<KEY>"
class ... | [
"os.path.dirname"
] | [((36, 61), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (51, 61), False, 'import os\n')] |
#!/usr/bin/env python
import random
import time
import tdl
WIDTH = 80
HEIGHT = 40
class LifeBoard():
def __init__(self, width, height):
self.width = width
self.height = height
self.live_cells = set()
self.wrap = True
def set(self, x, y, value):
if value:
... | [
"tdl.init",
"tdl.event.get",
"time.sleep",
"tdl.get_fps",
"tdl.flush"
] | [((2528, 2551), 'tdl.init', 'tdl.init', (['WIDTH', 'HEIGHT'], {}), '(WIDTH, HEIGHT)\n', (2536, 2551), False, 'import tdl\n'), ((3721, 3736), 'tdl.event.get', 'tdl.event.get', ([], {}), '()\n', (3734, 3736), False, 'import tdl\n'), ((5646, 5657), 'tdl.flush', 'tdl.flush', ([], {}), '()\n', (5655, 5657), False, 'import t... |
"""fuzzy searching allowing subsitutions and insertions, but no deletions"""
__all__ = [
'find_near_matches_no_deletions_ngrams',
]
import array
from fuzzysearch.common import Match
from fuzzysearch.search_exact import search_exact
def _expand(subsequence, sequence, max_substitutions, max_insertions,
... | [
"fuzzysearch.common.Match",
"fuzzysearch.search_exact.search_exact",
"array.array"
] | [((589, 633), 'array.array', 'array.array', (['"""L"""', '([0] * (max_insertions + 1))'], {}), "('L', [0] * (max_insertions + 1))\n", (600, 633), False, 'import array\n'), ((2808, 2894), 'fuzzysearch.search_exact.search_exact', 'search_exact', (['subsequence[ngram_start:ngram_end]', 'sequence', 'start_index', 'end_inde... |
import numpy as np
from time import time
from keras.datasets import mnist
from tmu.tsetlin_machine import TMCoalescedClassifier
import copy
clauses = 64
T = int(clauses*0.75)
s = 5.0
patch_size = 3
resolution = 8
number_of_state_bits = 8
(X_train_org, Y_train), (X_test_org, Y_test) = mnist.load_data()
Y_train=Y_t... | [
"tmu.tsetlin_machine.TMCoalescedClassifier",
"keras.datasets.mnist.load_data",
"numpy.empty",
"time.time",
"numpy.savez_compressed"
] | [((290, 307), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (305, 307), False, 'from keras.datasets import mnist\n'), ((401, 509), 'numpy.empty', 'np.empty', (['(X_train_org.shape[0], X_train_org.shape[1], X_train_org.shape[2], resolution)'], {'dtype': 'np.uint8'}), '((X_train_org.shape[0], X_t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#========================================
# Libraries
#========================================
import io
import pandas as pd
from bokeh.models import Panel, Div
#========================================
# Parameters
#========================================
# dtype de... | [
"pandas.DataFrame",
"io.StringIO",
"bokeh.models.Div"
] | [((2202, 2218), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (2214, 2218), True, 'import pandas as pd\n'), ((2371, 2506), 'bokeh.models.Div', 'Div', ([], {'name': 'WN_FILENAME', 'id': 'WID_FILENAME', 'text': "(WPROP_FILENAME['text'] % WPROP_FILENAME['default_text'])", 'width': "WPROP_FILENAME['width']"})... |
import unittest
import numpy as np
import scipy.stats as st
from ..analysis import LinearRegression
from ..analysis.exc import MinimumSizeError, NoDataError
from ..data import UnequalVectorLengthError, Vector
class MyTestCase(unittest.TestCase):
def test_350_LinRegress_corr(self):
"""Test the Linear Regr... | [
"unittest.main",
"numpy.random.seed",
"scipy.stats.norm.rvs"
] | [((8507, 8522), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8520, 8522), False, 'import unittest\n'), ((360, 385), 'numpy.random.seed', 'np.random.seed', (['(987654321)'], {}), '(987654321)\n', (374, 385), True, 'import numpy as np\n'), ((1115, 1140), 'numpy.random.seed', 'np.random.seed', (['(987654321)'], {}... |
# -*- coding: utf-8 -*-
from openre.agent.decorators import action
from openre.agent.server.decorators import start_process
from openre.agent.server.helpers import stop_process
from openre.agent.server.state import is_running
import sys
import subprocess
import os
from openre import BASE_PATH
import uuid
import re
@a... | [
"subprocess.Popen",
"uuid.uuid4",
"os.getcwd",
"tempfile.gettempdir",
"openre.agent.server.decorators.start_process",
"openre.agent.decorators.action",
"openre.agent.server.state.is_running",
"openre.agent.server.helpers.stop_process",
"re.search",
"os.path.join",
"os.access"
] | [((319, 345), 'openre.agent.decorators.action', 'action', ([], {'namespace': '"""server"""'}), "(namespace='server')\n", (325, 345), False, 'from openre.agent.decorators import action\n'), ((1092, 1115), 'openre.agent.server.decorators.start_process', 'start_process', (['"""domain"""'], {}), "('domain')\n", (1105, 1115... |
"""Vanilla Policy Gradient (REINFORCE)."""
import copy
from collections import OrderedDict
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn as nn
from rlkit.util import tensor_util as tu
from rlkit.torch.torch_rl_algorithm import TorchOnlineTrainer
from rlkit.torch.vpg.util import ... | [
"torch.ones",
"copy.deepcopy",
"torch.nn.MSELoss",
"torch.distributions.kl.kl_divergence",
"torch.zeros_like",
"rlkit.torch.vpg.util.filter_valids",
"rlkit.torch.vpg.util.compute_advantages",
"torch.clamp",
"rlkit.torch.vpg.util.pad_to_last",
"collections.OrderedDict",
"torch.nn.functional.softp... | [((1798, 1810), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1808, 1810), True, 'from torch import nn as nn\n'), ((3925, 3953), 'copy.deepcopy', 'copy.deepcopy', (['self.policy_n'], {}), '(self.policy_n)\n', (3938, 3953), False, 'import copy\n'), ((3986, 3999), 'collections.OrderedDict', 'OrderedDict', ([], {})... |
import os
import IPython
import random
early_setup="""
chmod +x 7zz
chmod +x ffmpeg
apt install mediainfo
apt install python3-libtorrent
7z x All_Needy_Fonts.7z -o/usr/share/fonts/ -y
rm /usr/share/fonts/pHalls*
fc-cache -f
touch /content/INSTALLED
"""
logger_code="""
import logging
import sys
loggi... | [
"IPython.get_ipython",
"IPython.display.clear_output",
"os.system"
] | [((1026, 1071), 'os.system', 'os.system', (['"""chmod +x /content/early_setup.sh"""'], {}), "('chmod +x /content/early_setup.sh')\n", (1035, 1071), False, 'import os\n'), ((1136, 1166), 'IPython.display.clear_output', 'IPython.display.clear_output', ([], {}), '()\n', (1164, 1166), False, 'import IPython\n'), ((1079, 11... |
"""
백준 1967번 : 트리의 지름
"""
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
# dfs로 한 점 기준으로 거리를 잴 수 있다.
def dfs(start, weight):
for i in tree[start]:
node, w = i
if dist[node] == -1:
dist[node] = weight + w
dfs(node, weight + w)
node = int(input())
tree = ... | [
"sys.setrecursionlimit"
] | [((37, 67), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 9)'], {}), '(10 ** 9)\n', (58, 67), False, 'import sys\n')] |
import os # library
import discord # library
from discord import client # library
import asyncpg # library
import os # library
# THIS IS THE TRIGGER PREFIX OF UR COMMANDS, LIKE ".BAN" "/BAN" "!BAN" "?BAN" "$BAN"
intents=discord.Intents.default()
intents.members=True
client = commands.Bot(command_prefix="PREFIX HERE",... | [
"discord.Intents.default",
"discord.client.load_extension",
"discord.client.run",
"asyncpg.create_pool",
"os.listdir"
] | [((222, 247), 'discord.Intents.default', 'discord.Intents.default', ([], {}), '()\n', (245, 247), False, 'import discord\n'), ((369, 389), 'os.listdir', 'os.listdir', (['"""./cogs"""'], {}), "('./cogs')\n", (379, 389), False, 'import os\n'), ((855, 872), 'discord.client.run', 'client.run', (['token'], {}), '(token)\n',... |
#!/usr/bin/env python3
#This sample reading the 3D acceleration data.
#Install LoRa HAT library with "pip3 install turta-lorahat"
#Raspberry Pi Configuration
# - You should enable SPI and I2C from the Raspberry Pi's configuration.
# To do so, type 'sudo raspi-config' to the terminal, then go to 'Interfacing Options' ... | [
"turta_lorahat.Turta_Accel.AccelTiltSensor",
"time.sleep"
] | [((432, 461), 'turta_lorahat.Turta_Accel.AccelTiltSensor', 'Turta_Accel.AccelTiltSensor', ([], {}), '()\n', (459, 461), False, 'from turta_lorahat import Turta_Accel\n'), ((868, 878), 'time.sleep', 'sleep', (['(0.2)'], {}), '(0.2)\n', (873, 878), False, 'from time import sleep\n')] |
"""
wlan configuration
"""
from tkinter import ttk
from typing import TYPE_CHECKING
import grpc
from core.gui.dialogs.dialog import Dialog
from core.gui.errors import show_grpc_error
from core.gui.themes import PADX, PADY
from core.gui.widgets import ConfigFrame
if TYPE_CHECKING:
from core.gui.app import Applic... | [
"tkinter.ttk.Button",
"core.gui.widgets.ConfigFrame",
"core.gui.errors.show_grpc_error",
"tkinter.ttk.Frame"
] | [((1176, 1220), 'core.gui.widgets.ConfigFrame', 'ConfigFrame', (['self.top', 'self.app', 'self.config'], {}), '(self.top, self.app, self.config)\n', (1187, 1220), False, 'from core.gui.widgets import ConfigFrame\n'), ((1469, 1488), 'tkinter.ttk.Frame', 'ttk.Frame', (['self.top'], {}), '(self.top)\n', (1478, 1488), Fals... |
import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
original_w = [] # Load weights from other framework
original_b = [] # Load biases from other framework
n_inputs = 28 * 28
n_hidden1 = 10
X = tf.placeholder(tf.float32, shape=(None, n_inputs), name="X")
hidden1 = fully_connected(X, n_hidd... | [
"tensorflow.contrib.layers.fully_connected",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"tensorflow.assign",
"tensorflow.get_variable"
] | [((224, 284), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, n_inputs)', 'name': '"""X"""'}), "(tf.float32, shape=(None, n_inputs), name='X')\n", (238, 284), True, 'import tensorflow as tf\n'), ((295, 341), 'tensorflow.contrib.layers.fully_connected', 'fully_connected', (['X', 'n_hidden1... |
import datetime
import re
from typing import Optional
import discord
from discord.ext import commands
import humanize
from bot import AUDITION_CHAT_CHANNEL
from logger import getLogger
l = getLogger("main")
class Moderation(commands.Cog, description="Moderation tools."):
def __init__(self, bot):
self.... | [
"discord.utils.get",
"logger.getLogger",
"discord.ext.commands.command",
"discord.ext.commands.has_any_role"
] | [((192, 209), 'logger.getLogger', 'getLogger', (['"""main"""'], {}), "('main')\n", (201, 209), False, 'from logger import getLogger\n'), ((336, 558), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""trial"""', 'aliases': "['make-trial', 'make-trial-curator', 'make-curator', 'add-trial']", 'brief': ... |
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM, GRU
from keras.utils.data_utils import get_file
from keras.optimizers import RMSprop
import numpy as np
import sys
import time
import random
import sys
import os
import re
from io import... | [
"sys.stdout.write",
"numpy.abs",
"numpy.argmax",
"numpy.random.multinomial",
"sys.stdout.flush",
"numpy.exp",
"keras.layers.core.Activation",
"keras.layers.core.Dropout",
"re.sub",
"io.StringIO",
"keras.layers.recurrent.GRU",
"keras.layers.core.Dense",
"keras.optimizers.RMSprop",
"numpy.co... | [((947, 961), 'io.StringIO', 'StringIO', (['text'], {}), '(text)\n', (955, 961), False, 'from io import StringIO\n'), ((1428, 1465), 'numpy.zeros', 'np.zeros', (['(batch_size, 1, char_count)'], {}), '((batch_size, 1, char_count))\n', (1436, 1465), True, 'import numpy as np\n'), ((1474, 1508), 'numpy.zeros', 'np.zeros',... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
# htt... | [
"ironic.drivers.modules.ipminative.NativeIPMIPower",
"ironic.drivers.modules.ipmitool.IPMIPower",
"ironic.drivers.modules.ssh.SSHPower",
"ironic.drivers.modules.pxe.VendorPassthru",
"ironic.drivers.modules.pxe.PXEDeploy"
] | [((1344, 1364), 'ironic.drivers.modules.ipmitool.IPMIPower', 'ipmitool.IPMIPower', ([], {}), '()\n', (1362, 1364), False, 'from ironic.drivers.modules import ipmitool\n'), ((1387, 1402), 'ironic.drivers.modules.pxe.PXEDeploy', 'pxe.PXEDeploy', ([], {}), '()\n', (1400, 1402), False, 'from ironic.drivers.modules import p... |
from Main.AlphaZero.DistributedSelfPlay import Constants as C
from Main.AlphaZero.Oracle import GraphOptimizer, OracleCommands
from Main import Hyperparameters, MachineSpecificSettings
# from keras import backend as K
# import tensorflow as tf
import numpy as np
ORACLE_PIPE = None
K = None
tf = None
de... | [
"numpy.random.random",
"numpy.array"
] | [((2710, 2788), 'numpy.array', 'np.array', (['([[1, 1, 1, 1, 1, 1, 1]] * Hyperparameters.AMOUNT_OF_GAMES_PER_WORKER)'], {}), '([[1, 1, 1, 1, 1, 1, 1]] * Hyperparameters.AMOUNT_OF_GAMES_PER_WORKER)\n', (2718, 2788), True, 'import numpy as np\n'), ((2607, 2625), 'numpy.random.random', 'np.random.random', ([], {}), '()\n'... |
#!/usr/bin/env python
# Original code (Python 2) from <NAME>; <NAME>; <NAME>; <NAME>; J.He;
# "Sentinel-2 MultiSpectral Instrument (MSI) data processing for aquatic science applications: Demonstrations and validations"
# suplementary data "Program for generating Sentinel-2's high-resolution angle coefficients"
# at ht... | [
"xml.etree.ElementTree.parse",
"numpy.matrix",
"rasterio.open",
"math.sqrt",
"math.atan2",
"math.radians",
"math.tan",
"os.path.dirname",
"numpy.zeros",
"numpy.transpose",
"math.sin",
"math.acos",
"logging.info",
"skimage.transform.resize",
"math.cos",
"numpy.array"
] | [((901, 917), 'math.sqrt', 'math.sqrt', (['(1 - E)'], {}), '(1 - E)\n', (910, 917), False, 'import math\n'), ((1720, 1742), 'math.radians', 'math.radians', (['latitude'], {}), '(latitude)\n', (1732, 1742), False, 'import math\n'), ((1757, 1774), 'math.sin', 'math.sin', (['lat_rad'], {}), '(lat_rad)\n', (1765, 1774), Fa... |
#Import required Image library
from PIL import Image, ImageDraw, ImageFont
#Taking Input From user
path = input("Input the path of the image: ")
path = path.strip('""')
im = Image.open(path)
width, height = im.size
#Taking input for the text
text = input('Enter the text for the watermark: ' )
font = ImageF... | [
"PIL.ImageFont.truetype",
"PIL.ImageDraw.Draw",
"PIL.Image.open"
] | [((181, 197), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (191, 197), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((314, 349), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""arial.ttf"""', '(20)'], {}), "('arial.ttf', 20)\n", (332, 349), False, 'from PIL import Image, ImageDraw, Imag... |
import torch
from typing import Optional, List
from PIL import Image
from torch import Tensor
import torchvision as tv
import cv2
import json
import os
import numpy as np
MAX_DIM = 299
def read_json(file_name):
with open(file_name) as handle:
out = json.load(handle)
return out
def nested_tensor_fro... | [
"torch.ones",
"PIL.Image.new",
"json.load",
"os.path.join",
"numpy.copy",
"numpy.zeros",
"numpy.bincount",
"torchvision.transforms.ToTensor",
"numpy.array",
"numpy.ravel_multi_index",
"torch.zeros",
"torchvision.transforms.Normalize",
"cv2.inRange",
"cv2.resize",
"torchvision.transforms.... | [((2927, 2969), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'expected_size', '(0, 0, 0)'], {}), "('RGB', expected_size, (0, 0, 0))\n", (2936, 2969), False, 'from PIL import Image\n'), ((3248, 3323), 'cv2.resize', 'cv2.resize', (['image', '(0, 0)'], {'fx': 'ratio', 'fy': 'ratio', 'interpolation': 'cv2.INTER_AREA'}), '(... |
"""
Created on Wed Jun 17 14:01:23 2020
Calculate graph properties
@author: Jyotika.bahuguna
"""
import os
import glob
import numpy as np
import pylab as pl
import scipy.io as sio
from copy import copy, deepcopy
import pickle
import matplotlib.cm as cm
import pdb
import h5py
import pand... | [
"bct.centrality.module_degree_zscore",
"numpy.copy",
"numpy.median",
"bct.modularity_louvain_und_sign",
"bct.participation_coef_sign",
"bct.centrality.participation_coef",
"numpy.argsort",
"numpy.where",
"numpy.arange",
"bct.local_assortativity_wu_sign",
"collections.Counter",
"bct.modularity.... | [((686, 711), 'numpy.arange', 'np.arange', (['(0.0)', '(1.5)', '(0.17)'], {}), '(0.0, 1.5, 0.17)\n', (695, 711), True, 'import numpy as np\n'), ((784, 809), 'numpy.arange', 'np.arange', (['(0.0)', '(1.5)', '(0.17)'], {}), '(0.0, 1.5, 0.17)\n', (793, 809), True, 'import numpy as np\n'), ((1595, 1631), 'bct.local_assorta... |
from sanic import Sanic
from sanic.views import HTTPMethodView
import jinja2_sanic
import jinja2
async def test_jinja2_filter(test_client):
app = Sanic("test_jinja2_render")
# setup
def simple_func(last_name):
return "Y.{last_name}".format(last_name=last_name)
jinja2_sanic.setup(
app... | [
"jinja2_sanic.template",
"sanic.Sanic",
"jinja2.DictLoader"
] | [((152, 179), 'sanic.Sanic', 'Sanic', (['"""test_jinja2_render"""'], {}), "('test_jinja2_render')\n", (157, 179), False, 'from sanic import Sanic\n'), ((530, 571), 'jinja2_sanic.template', 'jinja2_sanic.template', (['"""templates.jinja2"""'], {}), "('templates.jinja2')\n", (551, 571), False, 'import jinja2_sanic\n'), (... |