code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# coding: utf-8
import os
import logging.config
from webspider import setting
LOG_FILE_PATH = os.path.join(setting.BASE_DIR, 'log', 'spider_log.txt')
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'default': {
'format': '%(asctime)s- %(module)s:%(l... | [
"os.path.join"
] | [((96, 151), 'os.path.join', 'os.path.join', (['setting.BASE_DIR', '"""log"""', '"""spider_log.txt"""'], {}), "(setting.BASE_DIR, 'log', 'spider_log.txt')\n", (108, 151), False, 'import os\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate dummy data for tests/examples
"""
import numpy as np
def dummy_gauss_image(x=None, y=None,
xhalfrng=1.5, yhalfrng=None, xcen=0.5, ycen=0.9,
xnpts=1024, ynpts=None, xsigma=0.55, ysigma=0.25,
nois... | [
"numpy.random.random",
"numpy.exp",
"silx.sx.enable_gui",
"numpy.linspace",
"numpy.meshgrid",
"sloth.gui.plot.plot1D.Plot1D",
"sloth.gui.plot.plot2D.Plot2D"
] | [((1478, 1495), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (1489, 1495), True, 'import numpy as np\n'), ((1509, 1600), 'numpy.exp', 'np.exp', (['(-((xx - xcen) ** 2 / (2 * xsigma ** 2) + (yy - ycen) ** 2 / (2 * ysigma ** 2))\n )'], {}), '(-((xx - xcen) ** 2 / (2 * xsigma ** 2) + (yy - ycen) ** 2 ... |
"""
Copyright 2021 Dynatrace 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, software
... | [
"dynatrace.pagination.PaginatedList"
] | [((1268, 1370), 'dynatrace.pagination.PaginatedList', 'PaginatedList', (['NetworkZone', 'self.__http_client'], {'target_url': 'self.ENDPOINT', 'list_item': '"""networkZones"""'}), "(NetworkZone, self.__http_client, target_url=self.ENDPOINT,\n list_item='networkZones')\n", (1281, 1370), False, 'from dynatrace.paginat... |
import numpy as np
from numpy.random import RandomState
from numpy.testing import assert_allclose
from nnlib.l_layer.backward import linear_backward, linear_backward_activation, model_backward
from nnlib.utils.derivative import sigmoid_backward, relu_backward
from nnlib.utils.activation import sigmoid, relu
def test... | [
"nnlib.utils.activation.sigmoid",
"nnlib.l_layer.backward.linear_backward",
"nnlib.utils.activation.relu",
"numpy.testing.assert_allclose",
"numpy.array",
"nnlib.l_layer.backward.model_backward",
"numpy.random.RandomState"
] | [((351, 365), 'numpy.random.RandomState', 'RandomState', (['(1)'], {}), '(1)\n', (362, 365), False, 'from numpy.random import RandomState\n'), ((465, 517), 'nnlib.l_layer.backward.linear_backward', 'linear_backward', (['dZ', '(A, 1, W)'], {'alpha': '(0)', 'keep_prob': '(1)'}), '(dZ, (A, 1, W), alpha=0, keep_prob=1)\n',... |
"""Uploaded data to nuuuwan/news_lk:data branch."""
from news_lk import scrape
if __name__ == '__main__':
scrape.scrape_and_dump()
| [
"news_lk.scrape.scrape_and_dump"
] | [((112, 136), 'news_lk.scrape.scrape_and_dump', 'scrape.scrape_and_dump', ([], {}), '()\n', (134, 136), False, 'from news_lk import scrape\n')] |
from schematics import Model
from schematics.types import IntType, UUIDType, StringType, BooleanType
from ingredients_db.models.region import RegionState, Region
from ingredients_http.schematics.types import ArrowType, EnumType
class RequestCreateRegion(Model):
name = StringType(required=True, min_length=3)
... | [
"ingredients_http.schematics.types.EnumType",
"schematics.types.IntType",
"schematics.types.UUIDType",
"schematics.types.StringType",
"schematics.types.BooleanType",
"ingredients_http.schematics.types.ArrowType"
] | [((276, 315), 'schematics.types.StringType', 'StringType', ([], {'required': '(True)', 'min_length': '(3)'}), '(required=True, min_length=3)\n', (286, 315), False, 'from schematics.types import IntType, UUIDType, StringType, BooleanType\n'), ((333, 358), 'schematics.types.StringType', 'StringType', ([], {'required': '(... |
#!/usr/bin/env python3
from src.cli import Cli
from src.core import Orchestrator
def main():
config, args = Cli.parse_and_validate()
Orchestrator.launch_modules(config, args.modules, args.targets, args.audit)
if __name__ == '__main__':
main() | [
"src.cli.Cli.parse_and_validate",
"src.core.Orchestrator.launch_modules"
] | [((114, 138), 'src.cli.Cli.parse_and_validate', 'Cli.parse_and_validate', ([], {}), '()\n', (136, 138), False, 'from src.cli import Cli\n'), ((143, 218), 'src.core.Orchestrator.launch_modules', 'Orchestrator.launch_modules', (['config', 'args.modules', 'args.targets', 'args.audit'], {}), '(config, args.modules, args.ta... |
#!/cm/shared/languages/python-3.3.2/bin/python
# submit script for submission of mizuRoute simualtions
# <NAME> Oct 29 2019
#
# call this script from 'run_mizuRoute_templated_mswep050calib.py which creates a qsub job to submit to the HPC queue
# This script is actually called from 'call_pythonscript.sh' (which is need... | [
"datetime.datetime.now",
"os.path.basename",
"os.path.join",
"multiprocessing.Pool"
] | [((874, 911), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': 'ncpus'}), '(processes=ncpus)\n', (894, 911), False, 'import os, glob, subprocess, sys, shutil, multiprocessing\n'), ((578, 601), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (599, 601), False, 'import datetime\n'), ... |
from typing import Mapping, Any, Sequence
import numpy as np
import heapq
import math
from tqdm import tqdm
import scipy.optimize
import cvxpy as cvx
def n_bias(x_count: np.ndarray, bias: float):
# return np.sum(x_count[x_count >= bias])
clipped = np.clip(x_count - bias, a_min=0, a_max=None)
return n... | [
"numpy.clip",
"cvxpy.Variable",
"cvxpy.Problem",
"cvxpy.pos",
"cvxpy.sum",
"numpy.sum",
"numpy.zeros",
"numpy.array",
"heapq.heappop",
"numpy.argmin",
"numpy.round"
] | [((263, 307), 'numpy.clip', 'np.clip', (['(x_count - bias)'], {'a_min': '(0)', 'a_max': 'None'}), '(x_count - bias, a_min=0, a_max=None)\n', (270, 307), True, 'import numpy as np\n'), ((319, 334), 'numpy.sum', 'np.sum', (['clipped'], {}), '(clipped)\n', (325, 334), True, 'import numpy as np\n'), ((565, 580), 'cvxpy.Var... |
import json, os
## base spawner config
try:
c.Spawner.cmd = \
json.loads(os.environ['SPAWNER_CMD'])
except KeyError:
c.Spawner.cmd = [
'jupyterhub-singleuser', # OAuth wrapped jupyter instance server
'--KernelManager.transport=ipc', # -- all kernel comms over UNIX sockets
'--Ma... | [
"json.loads",
"os.environ.get"
] | [((531, 576), 'os.environ.get', 'os.environ.get', (['"""SPAWNER_DEFAULT_URL"""', '"""/lab"""'], {}), "('SPAWNER_DEFAULT_URL', '/lab')\n", (545, 576), False, 'import json, os\n'), ((75, 112), 'json.loads', 'json.loads', (["os.environ['SPAWNER_CMD']"], {}), "(os.environ['SPAWNER_CMD'])\n", (85, 112), False, 'import json,... |
__all__ = ['get_dataset']
def get_dataset(params):
if params['name'] == 'multimodal_points':
from datasets.multimodal_gaussian_2d import Dataset
return Dataset(params)
elif params['name'] == 'kicks':
from datasets.kicks import Dataset
return Dataset(params)
assert False and... | [
"datasets.kicks.Dataset"
] | [((174, 189), 'datasets.kicks.Dataset', 'Dataset', (['params'], {}), '(params)\n', (181, 189), False, 'from datasets.kicks import Dataset\n'), ((284, 299), 'datasets.kicks.Dataset', 'Dataset', (['params'], {}), '(params)\n', (291, 299), False, 'from datasets.kicks import Dataset\n')] |
# coding: utf-8
"""
Memsource REST API
Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis... | [
"six.iteritems"
] | [((7024, 7057), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (7037, 7057), False, 'import six\n')] |
import random
def get_random_bag():
"""Returns a bag with unique pieces. (Bag randomizer)"""
random_shapes = list(SHAPES)
random.shuffle(random_shapes)
return [Piece(0, 0, shape) for shape in random_shapes]
class Shape:
def __init__(self, code, blueprints):
self.code = code
self.... | [
"random.shuffle"
] | [((136, 165), 'random.shuffle', 'random.shuffle', (['random_shapes'], {}), '(random_shapes)\n', (150, 165), False, 'import random\n')] |
from django.shortcuts import render
# Python functions - user is going to request an url
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1> This is the music app homepage</h1>") | [
"django.http.HttpResponse"
] | [((185, 241), 'django.http.HttpResponse', 'HttpResponse', (['"""<h1> This is the music app homepage</h1>"""'], {}), "('<h1> This is the music app homepage</h1>')\n", (197, 241), False, 'from django.http import HttpResponse\n')] |
'''
@author <NAME>
Please contact <EMAIL>
'''
import math
import torch
class PositionalEmbedding(torch.nn.Module):
'''
Implementation of Positional Embedding.
'''
def __init__(self, hidden_size, device=torch.device("cpu")):
super().__init__()
self.hidden_size = hidden_size
s... | [
"torch.sin",
"torch.exp",
"math.log",
"torch.cos",
"torch.zeros",
"torch.arange",
"torch.device"
] | [((222, 241), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (234, 241), False, 'import torch\n'), ((333, 383), 'torch.zeros', 'torch.zeros', (['(10000)', 'hidden_size'], {'dtype': 'torch.float'}), '(10000, hidden_size, dtype=torch.float)\n', (344, 383), False, 'import torch\n'), ((515, 565), 'torch.... |
from tor4 import tensor
def test_tensor_sum():
a = tensor(data=[-1, 1, 2])
a_sum = a.sum()
assert a_sum.tolist() == 2
assert not a_sum.requires_grad
def test_tensor_sum_backward():
a = tensor(data=[-1, 1, 2.0], requires_grad=True)
a_sum = a.sum()
a_sum.backward()
assert a_sum.tolis... | [
"tor4.tensor"
] | [((57, 80), 'tor4.tensor', 'tensor', ([], {'data': '[-1, 1, 2]'}), '(data=[-1, 1, 2])\n', (63, 80), False, 'from tor4 import tensor\n'), ((210, 255), 'tor4.tensor', 'tensor', ([], {'data': '[-1, 1, 2.0]', 'requires_grad': '(True)'}), '(data=[-1, 1, 2.0], requires_grad=True)\n', (216, 255), False, 'from tor4 import tens... |
"""init module for natcap.invest."""
import dataclasses
import logging
import os
import sys
import pkg_resources
LOGGER = logging.getLogger('natcap.invest')
LOGGER.addHandler(logging.NullHandler())
__all__ = ['local_dir', ]
try:
__version__ = pkg_resources.get_distribution(__name__).version
except pkg_resources... | [
"logging.getLogger",
"logging.NullHandler",
"os.path.join",
"os.path.dirname",
"pkg_resources.get_distribution"
] | [((125, 159), 'logging.getLogger', 'logging.getLogger', (['"""natcap.invest"""'], {}), "('natcap.invest')\n", (142, 159), False, 'import logging\n'), ((178, 199), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (197, 199), False, 'import logging\n'), ((7822, 7850), 'os.path.dirname', 'os.path.dirname', ... |
import math
import sys
from fractions import Fraction
from random import uniform, randint
import decimal as dec
def log10_floor(f):
b, k = 1, -1
while b <= f:
b *= 10
k += 1
return k
def log10_ceil(f):
b, k = 1, 0
while b < f:
b *= 10
k += 1
return k
def log10_... | [
"random.uniform",
"math.ldexp",
"fractions.Fraction",
"decimal.localcontext",
"math.frexp",
"random.randint",
"decimal.Decimal"
] | [((851, 862), 'fractions.Fraction', 'Fraction', (['x'], {}), '(x)\n', (859, 862), False, 'from fractions import Fraction\n'), ((1539, 1552), 'math.frexp', 'math.frexp', (['x'], {}), '(x)\n', (1549, 1552), False, 'import math\n'), ((2540, 2553), 'math.frexp', 'math.frexp', (['x'], {}), '(x)\n', (2550, 2553), False, 'imp... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="example-pkg-vanderbeck", # Replace with your own username
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="A small example package",
long_descri... | [
"setuptools.find_packages"
] | [((465, 491), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (489, 491), False, 'import setuptools\n')] |
"""
Description: A Python module to use easily the osu!api V1.
Author: LostPy
License: MIT
Date: 2021-01-11
"""
import requests as req
import json
from . import from_json
base_url ='https://osu.ppy.sh/api'
urls = {
'beatmaps': base_url + '/get_beatmaps?',
'user': base_url + '/get_user?',
'scores': base_url + '/get... | [
"requests.get"
] | [((1126, 1166), 'requests.get', 'req.get', (["urls['beatmaps']"], {'params': 'params'}), "(urls['beatmaps'], params=params)\n", (1133, 1166), True, 'import requests as req\n'), ((1538, 1574), 'requests.get', 'req.get', (["urls['user']"], {'params': 'params'}), "(urls['user'], params=params)\n", (1545, 1574), True, 'imp... |
import glob
import matplotlib.pyplot as plt
import numpy as np
import sys
plt.ion()
data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_train.log'))
valid_data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_valid.log'))
for fname in data_files:
data = np.loadtxt(fname).reshape(-1, 3)
name = fname.split('/')[... | [
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ion",
"numpy.loadtxt",
"glob.glob"
] | [((75, 84), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (82, 84), True, 'import matplotlib.pyplot as plt\n'), ((527, 544), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(1)'}), '(loc=1)\n', (537, 544), True, 'import matplotlib.pyplot as plt\n'), ((104, 153), 'glob.glob', 'glob.glob', (["(sys.argv[1]... |
#!/usr/bin/python
# encoding: utf-8
from collections import Counter
from gist import create_workflow
from pprint import pprint as pp
import sys
import workflow
from workflow import Workflow, web
from workflow.background import run_in_background, is_running
def main(wf):
arg = wf.args[0]
wf.add_item(u"Set tok... | [
"gist.create_workflow"
] | [((431, 448), 'gist.create_workflow', 'create_workflow', ([], {}), '()\n', (446, 448), False, 'from gist import create_workflow\n')] |
import argparse
import glob
import os
import random
import re
from dataclasses import dataclass
from functools import partial
from math import ceil
from typing import List, Optional
import numpy as np
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
import util
tqdm.monitor_i... | [
"torch.cuda.manual_seed_all",
"torch.manual_seed",
"util.maybe_mkdir",
"math.ceil",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"argparse.ArgumentParser",
"util.get_logger",
"torch.load",
"random.seed",
"os.path.isfile",
"torch.cuda.is_available",
"functools.partial",
"numpy.random.seed",
... | [((340, 382), 'functools.partial', 'partial', (['tqdm'], {'bar_format': '"""{l_bar}{r_bar}"""'}), "(tqdm, bar_format='{l_bar}{r_bar}')\n", (347, 382), False, 'from functools import partial\n'), ((682, 699), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (693, 699), False, 'import random\n'), ((704, 724), 'nu... |
import cv2
import argparse
import numpy as np
def gray2bgr565(input_file, output_file):
img = np.fromfile(input_file, dtype=np.uint16)
img = img.reshape(480, 640)
# img = cv2.imread(input_file, cv2.IMREAD_ANYDEPTH)
ratio = np.amax(img) / 256
img8 = (img / ratio).astype('uint8')
img8 = cv2.cvtCo... | [
"cv2.imwrite",
"numpy.fromfile",
"argparse.ArgumentParser",
"cv2.cvtColor",
"numpy.amax"
] | [((99, 139), 'numpy.fromfile', 'np.fromfile', (['input_file'], {'dtype': 'np.uint16'}), '(input_file, dtype=np.uint16)\n', (110, 139), True, 'import numpy as np\n'), ((311, 349), 'cv2.cvtColor', 'cv2.cvtColor', (['img8', 'cv2.COLOR_GRAY2RGB'], {}), '(img8, cv2.COLOR_GRAY2RGB)\n', (323, 349), False, 'import cv2\n'), ((3... |
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import pdb
import sys
from ilqr.vehicle_model import Model
from ilqr.local_planner import LocalPlanner
from ilqr.constraints import Constraints
class iLQR():
def __init__(self, args, obstacle_bb, verbose=False):
... | [
"ilqr.constraints.Constraints",
"numpy.ones",
"numpy.linalg.eig",
"ilqr.local_planner.LocalPlanner",
"ilqr.vehicle_model.Model",
"numpy.diag",
"numpy.array",
"numpy.zeros",
"numpy.arctan2",
"matplotlib.pyplot.pause"
] | [((574, 592), 'ilqr.local_planner.LocalPlanner', 'LocalPlanner', (['args'], {}), '(args)\n', (586, 592), False, 'from ilqr.local_planner import LocalPlanner\n'), ((622, 633), 'ilqr.vehicle_model.Model', 'Model', (['args'], {}), '(args)\n', (627, 633), False, 'from ilqr.vehicle_model import Model\n'), ((661, 691), 'ilqr... |
import argparse
import itertools
import json
import logging
import os
import pickle
import time
import warnings
from collections import Counter, defaultdict
from typing import Dict, Any, List, Iterable, Tuple, Set
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import langdetect
import... | [
"logging.getLogger",
"gensim.corpora.Dictionary.load",
"data.DocumentCollection",
"text_processing.fix_file_based_id",
"gensim.models.LdaMulticore",
"util.open_by_ext",
"os.cpu_count",
"data.Document",
"argparse.ArgumentParser",
"util.json_read_lines",
"spacy.load",
"gensim.corpora.Dictionary"... | [((215, 294), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '"""ignore"""', 'category': 'UserWarning', 'module': '"""gensim"""'}), "(action='ignore', category=UserWarning, module='gensim')\n", (238, 294), False, 'import warnings\n'), ((807, 902), 'logging.basicConfig', 'logging.basicConfig', ([]... |
from google.cloud import storage
GCS_CLIENT = storage.Client()
GCS_BUCKET = GCS_CLIENT.get_bucket('senpai-io.appspot.com')
path = 'quandl-stage/backfill_data_jan2015_mar2018.csv'
blob = GCS_BUCKET.blob(path)
blob.upload_from_filename(filename='data_jan2015_mar2018.csv')
| [
"google.cloud.storage.Client"
] | [((47, 63), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (61, 63), False, 'from google.cloud import storage\n')] |
import numpy as np
from spacy.pipeline.sentencizer import Sentencizer
from glob import glob
from spacy.lang.en import English
def metrics(a, b):
from sklearn.metrics import f1_score, recall_score, precision_score, accuracy_score
return (accuracy_score(a, b),
recall_score(a, b),
precisi... | [
"hw2.ColgateSBD",
"sklearn.metrics.f1_score",
"spacy.lang.en.English",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"numpy.array",
"spacy.pipeline.sentencizer.Sentencizer",
"sklearn.metrics.accuracy_score",
"glob.glob"
] | [((471, 480), 'spacy.lang.en.English', 'English', ([], {}), '()\n', (478, 480), False, 'from spacy.lang.en import English\n'), ((514, 534), 'glob.glob', 'glob', (['"""marked-*.txt"""'], {}), "('marked-*.txt')\n", (518, 534), False, 'from glob import glob\n'), ((247, 267), 'sklearn.metrics.accuracy_score', 'accuracy_sco... |
from modules.mpulib import computeheading, attitudefromCompassGravity, RP_calculate, MadgwickQuaternionUpdate, Euler2Quat, quaternion_to_euler_angle, MPU9250_computeEuler
import socket, traceback
import csv
import struct
import sys, time, string, pygame
import pygame
import pygame.draw
import pygame.time
import numpy ... | [
"pygame.event.poll",
"pygame.init",
"numpy.array",
"numpy.linalg.norm",
"modules.euclid.Quaternion",
"modules.quaternion.QuaternionClass",
"numpy.cross",
"pygame.time.delay",
"modules.a3muse.quatNormalized",
"pygame.display.flip",
"numpy.subtract",
"modules.a3muse.RotMatToQuat",
"numpy.mat",... | [((1012, 1051), 'serial.Serial', 'serial.Serial', (['"""/dev/tty.usbmodem14411"""'], {}), "('/dev/tty.usbmodem14411')\n", (1025, 1051), False, 'import serial\n'), ((1556, 1569), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1567, 1569), False, 'import pygame\n'), ((1580, 1608), 'modules.EuclidObjects.Screen', 'Scree... |
from rest_framework import generics
from rest_framework import response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_api.serializers.doc_serializers import (DoctorRegisterSerializer,
DoctorUsersSerializer, DoctorLoginSerializer, Doct... | [
"jwt.decode",
"rest_api.send_mail.password_reset_token_created",
"rest_api.serializers.doc_serializers.DoctorRegisterSerializer",
"rest_api.send_mail.send_confirmation_email",
"doctorsUser.models.DoctorUser.objects.get",
"drf_yasg.utils.swagger_auto_schema",
"rest_framework.response.Response",
"doctor... | [((885, 909), 'doctorsUser.models.DoctorUser.objects.all', 'DoctorUser.objects.all', ([], {}), '()\n', (907, 909), False, 'from doctorsUser.models import DoctorUser\n'), ((961, 1105), 'drf_yasg.utils.swagger_auto_schema', 'swagger_auto_schema', ([], {'operation_description': '"""List doctor users (can add params(?searc... |
from google.appengine.ext import webapp
from wsgiref.handlers import CGIHandler
from model import Membership
from model import Group
from model import Transaction
class WhatHandler(webapp.RequestHandler):
def get(self):
page = self.request.get('p');
if page is None or page == '':
page = 1
else:... | [
"model.Transaction.gql",
"google.appengine.ext.webapp.WSGIApplication",
"wsgiref.handlers.CGIHandler"
] | [((1248, 1308), 'google.appengine.ext.webapp.WSGIApplication', 'webapp.WSGIApplication', (["[('/what', WhatHandler)]"], {'debug': '(True)'}), "([('/what', WhatHandler)], debug=True)\n", (1270, 1308), False, 'from google.appengine.ext import webapp\n'), ((710, 775), 'model.Transaction.gql', 'Transaction.gql', (["('ORDER... |
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import os
from torch.autograd import Variable
import argparse
import numpy as np
from torch.optim.lr_scheduler import *
from model.resnet import resnet101
from data_pre.FashionAI import fashion
pa... | [
"torch.nn.CrossEntropyLoss",
"argparse.ArgumentParser",
"torch.max",
"torchvision.transforms.RandomHorizontalFlip",
"model.resnet.resnet101",
"torchvision.transforms.RandomCrop",
"torch.nn.Linear",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"torchvision.transforms.Normalize",
... | [((325, 350), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (348, 350), False, 'import argparse\n'), ((1183, 1324), 'data_pre.FashionAI.fashion', 'fashion', (['"""/home/yhf/Challenge/FashionAI/STL_FashionAI/data/2base/Annotations/sum_labels.csv"""', 'transform_train', 'opt.attr'], {'train': '(... |
import arcade
import math
import LevelGenerator
import Textures
import Sounds
from Constants import TILE_SIZE, ROOM_WIDTH, ROOM_HEIGHT
from Mob import Mob
from Projectile import Projectile
class Player(Mob):
def __init__(self, x, y, keyboard):
self.keyboard = keyboard
self.movespeed = 2.5
... | [
"Textures.get_textures",
"Sounds.play",
"Textures.get_texture",
"math.atan2"
] | [((1010, 1036), 'Textures.get_texture', 'Textures.get_texture', (['(0)', '(4)'], {}), '(0, 4)\n', (1030, 1036), False, 'import Textures\n'), ((1074, 1100), 'Textures.get_texture', 'Textures.get_texture', (['(0)', '(5)'], {}), '(0, 5)\n', (1094, 1100), False, 'import Textures\n'), ((1133, 1163), 'Textures.get_textures',... |
import tensorflow as tf
from data_types.training_result import TrainingResult
from data_types.training_set import TrainingSet
from timeseries.build import compile_and_fit
from timeseries.window_generator import WindowGenerator
def evaluate_linear(
training_set: TrainingSet
) -> TrainingResult:
## LINEAR
... | [
"tensorflow.keras.layers.Dense",
"timeseries.window_generator.WindowGenerator",
"timeseries.build.compile_and_fit"
] | [((427, 541), 'timeseries.window_generator.WindowGenerator', 'WindowGenerator', ([], {'input_width': '(1)', 'label_width': '(1)', 'shift': '(1)', 'training_set': 'training_set', 'label_columns': "['T (degC)']"}), "(input_width=1, label_width=1, shift=1, training_set=\n training_set, label_columns=['T (degC)'])\n", (... |
import matplotlib.pyplot as plt
import numpy as np
from gpar.regression import GPARRegressor
from wbml.experiment import WorkingDirectory
import wbml.plot
if __name__ == "__main__":
wd = WorkingDirectory("_experiments", "synthetic", seed=1)
# Create toy data set.
n = 200
x = np.linspace(0, 1, n)
n... | [
"gpar.regression.GPARRegressor",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.fill_between",
"wbml.experiment.WorkingDirectory",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.stack",
"numpy.cos",
"matplotlib.pyplot.tight_layout",
"... | [((192, 245), 'wbml.experiment.WorkingDirectory', 'WorkingDirectory', (['"""_experiments"""', '"""synthetic"""'], {'seed': '(1)'}), "('_experiments', 'synthetic', seed=1)\n", (208, 245), False, 'from wbml.experiment import WorkingDirectory\n'), ((294, 314), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n'], {}), '(... |
#%%
import numpy as np
import pandas as pd
import bokeh.plotting
import bokeh.io
import bokeh.models
import growth.model
import growth.viz
const = growth.model.load_constants()
colors, palette = growth.viz.bokeh_style()
mapper = growth.viz.load_markercolors()
bokeh.io.output_file('../../figures/interactive/interac... | [
"numpy.ones_like",
"numpy.log10",
"numpy.arange",
"pandas.read_csv"
] | [((450, 477), 'numpy.arange', 'np.arange', (['(0.001)', '(50)', '(0.001)'], {}), '(0.001, 50, 0.001)\n', (459, 477), True, 'import numpy as np\n'), ((532, 619), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/main_figure_data/Fig4_ecoli_ribosomal_mass_fractions.csv"""'], {}), "(\n '../../data/main_figure_data/Fig... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField
from flask_babel import lazy_gettext as _l
from wtforms import StringField, TextAreaField, SubmitField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Email, ValidationError, Length, EqualTo
from app.models impo... | [
"wtforms.validators.Email",
"wtforms.validators.ValidationError",
"flask_wtf.file.FileAllowed",
"wtforms.SubmitField",
"wtforms.validators.Length",
"wtforms.validators.EqualTo",
"flask_babel.lazy_gettext",
"app.models.User.query.filter_by",
"wtforms.validators.DataRequired"
] | [((3492, 3521), 'wtforms.SubmitField', 'SubmitField', (['"""Reset Password"""'], {}), "('Reset Password')\n", (3503, 3521), False, 'from wtforms import StringField, TextAreaField, SubmitField, PasswordField, BooleanField\n'), ((3689, 3715), 'wtforms.SubmitField', 'SubmitField', (['"""Delete User"""'], {}), "('Delete Us... |
from helpers import poseRt
from frame import Frame
import time
import numpy as np
import g2o
import json
LOCAL_WINDOW = 20
#LOCAL_WINDOW = None
class Point(object):
# A Point is a 3-D point in the world
# Each Point is observed in multiple Frames
def __init__(self, mapp, loc, color, tid=None):
self.pt = np... | [
"numpy.sqrt",
"numpy.array",
"g2o.VertexCam",
"numpy.linalg.norm",
"numpy.mean",
"g2o.SparseOptimizer",
"json.dumps",
"numpy.dot",
"g2o.LinearSolverCholmodSE3",
"frame.Frame",
"g2o.OptimizationAlgorithmLevenberg",
"g2o.EdgeProjectP2MC",
"helpers.poseRt",
"json.loads",
"numpy.eye",
"g2o... | [((318, 331), 'numpy.array', 'np.array', (['loc'], {}), '(loc)\n', (326, 331), True, 'import numpy as np\n'), ((389, 403), 'numpy.copy', 'np.copy', (['color'], {}), '(color)\n', (396, 403), True, 'import numpy as np\n'), ((504, 555), 'numpy.array', 'np.array', (['[self.pt[0], self.pt[1], self.pt[2], 1.0]'], {}), '([sel... |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from utils.parse_config import *
from utils.utils import build_targets, to_cpu, non_max_suppression
import matplotlib.pyplot as plt
import matplotlib.patches as pa... | [
"torch.nn.BatchNorm2d",
"torch.nn.ZeroPad2d",
"torch.nn.LeakyReLU",
"torch.nn.ModuleList",
"torch.nn.Sequential",
"torch.nn.functional.sigmoid",
"torch.nn.Conv2d",
"torch.nn.functional.softplus"
] | [((1706, 1721), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1719, 1721), True, 'import torch.nn as nn\n'), ((854, 964), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'in_channels', 'kernel_size', 'stride', 'padding', 'dilation'], {'groups': 'in_channels', 'bias': 'bias'}), '(in_channels, in_channels, ... |
# -*- coding: utf-8 -*-
import os,urllib
class Dataset(object):
def __init__(self,opt=None):
if opt is not None:
self.setup(opt)
self.http_proxy= opt.__dict__.get("proxy","null")
else:
self.name="demo"
self.dirname="demo"
self.http_proxy="... | [
"os.path.exists",
"os.listdir",
"tarfile.open",
"urllib2.urlretrieve",
"zipfile.ZipFile",
"urllib.request.urlretrieve",
"urllib.request.install_opener",
"os.path.join",
"urllib.request.ProxyHandler",
"os.path.splitext",
"os.path.isfile",
"os.path.dirname",
"os.path.isdir",
"urllib.request.... | [((1078, 1109), 'os.path.exists', 'os.path.exists', (['self.saved_path'], {}), '(self.saved_path)\n', (1092, 1109), False, 'import os, urllib\n'), ((2717, 2751), 'os.path.join', 'os.path.join', (['self.root', 'self.name'], {}), '(self.root, self.name)\n', (2729, 2751), False, 'import os, urllib\n'), ((427, 459), 'os.pa... |
# coding:utf-8
from urllib.parse import urlencode, urljoin
from .client import Client
class API(Client):
HOST = None
PATH = None
TIMEOUT = 30
@classmethod
def _build_url(cls, path_args=None, params=None):
url = urljoin(cls.HOST, cls.PATH)
if path_args:
url = url.form... | [
"urllib.parse.urlencode",
"urllib.parse.urljoin"
] | [((244, 271), 'urllib.parse.urljoin', 'urljoin', (['cls.HOST', 'cls.PATH'], {}), '(cls.HOST, cls.PATH)\n', (251, 271), False, 'from urllib.parse import urlencode, urljoin\n'), ((442, 459), 'urllib.parse.urlencode', 'urlencode', (['params'], {}), '(params)\n', (451, 459), False, 'from urllib.parse import urlencode, urlj... |
import unittest
import io
from unittest import mock
from tests.lib.utils import INSPECT
from custom_image_cli.validation_tool import validation_helper
from custom_image_cli.validation_tool.validation_models.validation_models import \
ImageDetail, ImageManifest, EmrRelease
class TestValidationHelper(unittest.TestC... | [
"custom_image_cli.validation_tool.validation_models.validation_models.ImageDetail",
"unittest.mock.patch",
"custom_image_cli.validation_tool.validation_helper.validate_all",
"custom_image_cli.validation_tool.validation_helper.load_validation_info"
] | [((511, 561), 'unittest.mock.patch', 'mock.patch', (['"""sys.stdout"""'], {'new_callable': 'io.StringIO'}), "('sys.stdout', new_callable=io.StringIO)\n", (521, 561), False, 'from unittest import mock\n'), ((567, 657), 'unittest.mock.patch', 'mock.patch', (['"""custom_image_cli.validation_tool.validation_helper.load_val... |
# -*- coding: utf-8 -*-
import nltk
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
#from nltk import pos_tag
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
style.use('fivethirtyeight')
# Process text
raw_text = open("news_article.txt").read... | [
"nltk.pos_tag",
"os.times",
"nltk.ne_chunk",
"nltk.tokenize.word_tokenize",
"matplotlib.style.use",
"nltk.tag.StanfordNERTagger",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((233, 261), 'matplotlib.style.use', 'style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (242, 261), False, 'from matplotlib import style\n'), ((336, 359), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['raw_text'], {}), '(raw_text)\n', (349, 359), False, 'from nltk.tokenize import word_tokenize\... |
import streamlit as st
from streamlit import caching
import os
import torch
from src.core.detect import Detector
from src.core.utils import utils
from PIL import Image
import cv2
st.title('1stDayKit Object Detection')
st.write('1stDayKit is a high-level Deep Learning toolkit for solving generic tasks.')
uploaded_file... | [
"cv2.imwrite",
"streamlit.image",
"PIL.Image.open",
"streamlit.file_uploader",
"streamlit.write",
"streamlit.spinner",
"src.core.utils.utils.pil_to_cv2",
"src.core.detect.Detector",
"streamlit.title"
] | [((180, 218), 'streamlit.title', 'st.title', (['"""1stDayKit Object Detection"""'], {}), "('1stDayKit Object Detection')\n", (188, 218), True, 'import streamlit as st\n'), ((219, 315), 'streamlit.write', 'st.write', (['"""1stDayKit is a high-level Deep Learning toolkit for solving generic tasks."""'], {}), "(\n '1st... |
"""An Http API Client to interact with meross devices"""
from email import header
import logging
from types import MappingProxyType
from typing import List, MappingView, Optional, Dict, Any, Callable, Union
from enum import Enum
from uuid import uuid4
from hashlib import md5
from time import time
from json import (
... | [
"logging.getLogger",
"aiohttp.ClientSession",
"json.loads",
"json.dumps",
"async_timeout.timeout",
"uuid.uuid4",
"yarl.URL",
"time.time"
] | [((5651, 5679), 'yarl.URL', 'URL', (['f"""http://{host}/config"""'], {}), "(f'http://{host}/config')\n", (5654, 5679), False, 'from yarl import URL\n'), ((1032, 1039), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (1037, 1039), False, 'from uuid import uuid4\n'), ((1068, 1074), 'time.time', 'time', ([], {}), '()\n', (1072, ... |
import os
import json
import pytest
import pandas as pd
# TODO: revise the following constants when using new or revised CPS/PUF data
CPS_START_YEAR = 2014
PUF_START_YEAR = 2011
PUF_COUNT = 248591
LAST_YEAR = 2027
@pytest.fixture(scope='session')
def test_path():
return os.path.abspath(os.path.dirname(__file__)... | [
"pandas.read_csv",
"os.path.join",
"os.path.isfile",
"os.path.dirname",
"json.load",
"pytest.fixture"
] | [((219, 250), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (233, 250), False, 'import pytest\n'), ((325, 356), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (339, 356), False, 'import pytest\n'), ((509, 540), 'pytest.fixture'... |
from math import sqrt
import re
from curious.commands import Context
from curious.commands.exc import ConversionFailedError
from typing import Tuple
colour_pattern = re.compile(r'(#|0x)?([A-Za-z0-9]{1,6})')
RGB = Tuple[int, int, int]
class Colour:
"""
A class that represents a colour.
"""
def __ini... | [
"math.sqrt",
"curious.commands.exc.ConversionFailedError",
"curious.commands.Context.add_converter",
"re.compile"
] | [((168, 207), 're.compile', 're.compile', (['"""(#|0x)?([A-Za-z0-9]{1,6})"""'], {}), "('(#|0x)?([A-Za-z0-9]{1,6})')\n", (178, 207), False, 'import re\n'), ((3251, 3300), 'curious.commands.Context.add_converter', 'Context.add_converter', (['Colour', 'convert_hex_colour'], {}), '(Colour, convert_hex_colour)\n', (3272, 33... |
"""
Created on 9 Aug 2016
@author: <NAME> (<EMAIL>)
"""
import _csv
import sys
# --------------------------------------------------------------------------------------------------------------------
class Histogram(object):
"""
classdocs
"""
__HEADER_BIN = ".bin"
__HEADER_COUNT = ".count"
... | [
"_csv.writer"
] | [((1618, 1635), '_csv.writer', '_csv.writer', (['file'], {}), '(file)\n', (1629, 1635), False, 'import _csv\n')] |
import importlib
import sys
import pituophis
# check if the user is running the script with the correct number of arguments
if len(sys.argv) < 2:
# if not, print the usage
print('usage: pituophis [command] cd [options]')
print('Commands:')
print(' serve [options]')
print(' fetch [url] [options]')... | [
"importlib.import_module",
"pituophis.get",
"sys.stdout.buffer.write",
"pituophis.serve",
"sys.argv.index"
] | [((2471, 2655), 'pituophis.serve', 'pituophis.serve', ([], {'host': 'host', 'port': 'port', 'advertised_port': 'advertised_port', 'handler': 'pituophis.handle', 'pub_dir': 'pub_dir', 'alt_handler': 'alt_handler', 'send_period': 'send_period', 'debug': 'debug'}), '(host=host, port=port, advertised_port=advertised_port,\... |
"""
Every name reference is swapped for a call to ``__autoimport__``, which
will check if it's part of the locals or globals, falling back to trying
an import before giving up.
"""
from importlib import import_module
from ast import NodeTransformer, copy_location, fix_missing_locations, \
AST, Call, Name, Load, St... | [
"ast.Load",
"importlib.import_module",
"ast.copy_location",
"inspect.currentframe",
"ast.fix_missing_locations",
"ast.Str"
] | [((756, 785), 'ast.copy_location', 'copy_location', (['delegate', 'node'], {}), '(delegate, node)\n', (769, 785), False, 'from ast import NodeTransformer, copy_location, fix_missing_locations, AST, Call, Name, Load, Str, keyword\n'), ((794, 825), 'ast.fix_missing_locations', 'fix_missing_locations', (['delegate'], {}),... |
from PyQt5 import QtWidgets, QtCore, QtGui
from pyqtgraph import SignalProxy
class TaskWidget(QtWidgets.QWidget):
def __init__(self, task, rate_limit=0.01, parent=None):
super().__init__(parent=parent)
self.task = task
self.init_ui()
proxy_config = {
'signal': self.task... | [
"PyQt5.QtWidgets.QToolButton",
"PyQt5.QtCore.pyqtSlot",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QProgressBar",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QVBoxLayout",
"pyqtgraph.SignalProxy"
] | [((2192, 2215), 'PyQt5.QtCore.pyqtSlot', 'QtCore.pyqtSlot', (['object'], {}), '(object)\n', (2207, 2215), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((647, 674), 'pyqtgraph.SignalProxy', 'SignalProxy', ([], {}), '(**proxy_config)\n', (658, 674), False, 'from pyqtgraph import SignalProxy\n'), ((846, 869), '... |
# Generated by Django 2.1.5 on 2019-08-28 07:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0016_friends'),
]
operations = [
migrations.AlterModelOptions(
name='friends',
options={'verbose_name': 'Friend Lis... | [
"django.db.migrations.AlterModelOptions",
"django.db.migrations.RenameField"
] | [((214, 341), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""friends"""', 'options': "{'verbose_name': 'Friend List', 'verbose_name_plural': 'Friend List'}"}), "(name='friends', options={'verbose_name':\n 'Friend List', 'verbose_name_plural': 'Friend List'})\n", (242, 341... |
import tensorflow as tf
from tensorflow.compat.v1 import logging
logging.set_verbosity("INFO")
logging.info("TF Version:{}".format(tf.__version__))
try:
import horovod.tensorflow as hvd
no_horovod = False
except ModuleNotFoundError:
logging.warning("No horvod module, cannot perform distributed training")
... | [
"tensorflow.data.TFRecordDataset",
"tensorflow.io.gfile.glob",
"tensorflow.Variable",
"sonnet.optimizers.Adam",
"tensorflow.compat.v1.logging.warning",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.GradientTape",
"graph_nets.utils_tf.concat",
"tensorflow.constant",
"pprint.PrettyPrinte... | [((65, 94), 'tensorflow.compat.v1.logging.set_verbosity', 'logging.set_verbosity', (['"""INFO"""'], {}), "('INFO')\n", (86, 94), False, 'from tensorflow.compat.v1 import logging\n'), ((825, 855), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(2)'}), '(indent=2)\n', (845, 855), False, 'import pprint\n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project: Hangman
File: hangman.py
Author: <NAME>
Created: 2017-11-24
IDE: PyCharm Community Edition
Synopsis:
hangman.py [ARGUMENT]
Description:
A simple hangman game that runs in the command line.
... | [
"lib.get_ui_strings.get_language_list",
"lib.get_ui_strings.get_strings",
"matplotlib.image.imread",
"os.path.join",
"sys.exit",
"random.randint",
"matplotlib.pyplot.show"
] | [((2589, 2609), 'random.randint', 'random.randint', (['(1)', '_'], {}), '(1, _)\n', (2603, 2609), False, 'import random\n'), ((7938, 7975), 'os.path.join', 'os.path.join', (['"""resources"""', '"""lang.csv"""'], {}), "('resources', 'lang.csv')\n", (7950, 7975), False, 'import os\n'), ((7997, 8044), 'lib.get_ui_strings.... |
import json
import os
import typing
import codecs
import typing
import os
import json
import dill
from dataclasses import dataclass, field
ENCODED_PICKLE = "encodedpickle"
class TutorialJsonIOManager(typing.List[str]):
"""
TutorialJsonIOManager will read step results from a json file
"""
def __init_... | [
"json.load",
"os.get_terminal_size",
"dataclasses.field"
] | [((2495, 2522), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (2500, 2522), False, 'from dataclasses import dataclass, field\n'), ((2692, 2719), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (2697, 2719), False, 'from dataclas... |
import sys
sys.path.append('../')
sys.path.append('../..')
import cmbnncs.utils as utils
import cmbnncs.spherical as spherical
import cmbnncs.simulator as simulator
import numpy as np
import time
start_time = time.time()
def sim_Dust(dust_seed, frequ, amplitude_randn, spectralIndex_randn, temp_randn):
### ComDust ... | [
"numpy.random.choice",
"cmbnncs.simulator.DustComponents",
"cmbnncs.utils.savenpy",
"numpy.random.seed",
"cmbnncs.spherical.sphere2piecePlane",
"time.time",
"sys.path.append"
] | [((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((34, 58), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (49, 58), False, 'import sys\n'), ((209, 220), 'time.time', 'time.time', ([], {}), '()\n', (218, 220), False, 'impo... |
# Generated by Django 3.2.4 on 2021-07-22 09:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0175_lotv2_lots_v2_year_87d135_idx'),
('certificates', '0010_auto_20210509_1038'),
]
operations = [... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BigAutoField",
"django.db.models.CharField"
] | [((443, 539), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (462, 539), False, 'from django.db import migrations, m... |
from .datafetcher import fetch_measure_levels
from .stationdata import build_station_list, update_water_levels
from .flood import stations_highest_rel_level
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from floodsystem.station import inconsistent_typical_... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"datetime.timedelta",
"numpy.linspace",
"matplotlib.pyplot.tight_layout",
"numpy.poly1d",
"matplotlib.pyplot.title",
"floodsystem.station.inconsistent_typical_range_stat... | [((714, 759), 'floodsystem.station.inconsistent_typical_range_stations', 'inconsistent_typical_range_stations', (['stations'], {}), '(stations)\n', (749, 759), False, 'from floodsystem.station import inconsistent_typical_range_stations\n'), ((1054, 1098), 'matplotlib.pyplot.plot', 'plt.plot', (['dates', 'levels'], {'la... |
#!/usr/bin/env python
"""
LIVE STREAM TO YOUTUBE LIVE using FFMPEG -- from webcam
https://www.scivision.co/youtube-live-ffmpeg-livestream/
https://support.google.com/youtube/answer/2853702
Windows: get DirectShow device list from:
ffmpeg -list_devices true -f dshow -i dummy
"""
from youtubelive_ffmpeg import youtu... | [
"signal.signal",
"sys.platform.startswith",
"youtubelive_ffmpeg.youtubelive",
"argparse.ArgumentParser"
] | [((343, 373), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (366, 373), False, 'import sys\n'), ((470, 503), 'sys.platform.startswith', 'sys.platform.startswith', (['"""darwin"""'], {}), "('darwin')\n", (493, 503), False, 'import sys\n'), ((702, 746), 'signal.signal', 'signal.s... |
import unittest
from unittest.mock import patch, Mock
from werkzeug.datastructures import FileStorage
import io
import json
from app import app
from app.models.base import db
from app.models.user import User
from app.auth.views import UserPassportphotoView
from app.auth import views
class AuthUploadPassportPhotoTes... | [
"app.auth.views.UserPassportphotoView",
"app.models.base.db.drop_all",
"app.models.user.User",
"json.dumps",
"app.app.test_client",
"io.BytesIO",
"app.app.app_context",
"app.models.base.db.create_all",
"unittest.mock.patch.object"
] | [((899, 948), 'unittest.mock.patch.object', 'patch.object', (['views.UserPassportphotoView', '"""post"""'], {}), "(views.UserPassportphotoView, 'post')\n", (911, 948), False, 'from unittest.mock import patch, Mock\n'), ((387, 404), 'app.app.test_client', 'app.test_client', ([], {}), '()\n', (402, 404), False, 'from app... |
import os
import numpy as np
import pytest
from pennylane import qchem
from openfermion.hamiltonians import MolecularData
ref_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_ref_files")
table_1 = np.array(
[
[0.0, 0.0, 0.0, 0.0, 0.68238953],
[0.0, 1.0, 1.0, 0.0, 0.68238953]... | [
"numpy.allclose",
"pennylane.qchem.two_particle",
"os.path.join",
"os.path.realpath",
"numpy.array",
"pytest.mark.parametrize",
"pytest.raises",
"numpy.full"
] | [((222, 1390), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0, 0.68238953], [0.0, 1.0, 1.0, 0.0, 0.68238953], [1.0, \n 0.0, 0.0, 1.0, 0.68238953], [1.0, 1.0, 1.0, 1.0, 0.68238953], [0.0, 0.0,\n 2.0, 2.0, 0.17900058], [0.0, 1.0, 3.0, 2.0, 0.17900058], [1.0, 0.0, 2.0,\n 3.0, 0.17900058], [1.0, 1.0, 3.0, 3.0,... |
# Generated by Django 2.0 on 2018-02-14 13:39
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.SlugField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((356, 449), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (372, 449), False, 'from django.db import migrations, models\... |
from django.contrib import admin
from django import forms
from establishment.accounts.utils import get_user_search_fields
from .models import SocialApp, SocialAccount, SocialToken, SocialProvider
class SocialAppForm(forms.ModelForm):
class Meta:
model = SocialApp
exclude = []
widgets = {... | [
"establishment.accounts.utils.get_user_search_fields",
"django.contrib.admin.site.register",
"django.forms.TextInput"
] | [((1442, 1488), 'django.contrib.admin.site.register', 'admin.site.register', (['SocialApp', 'SocialAppAdmin'], {}), '(SocialApp, SocialAppAdmin)\n', (1461, 1488), False, 'from django.contrib import admin\n'), ((1489, 1539), 'django.contrib.admin.site.register', 'admin.site.register', (['SocialToken', 'SocialTokenAdmin'... |
"""GitHub tap class."""
from typing import List
from singer_sdk import Tap, Stream
from singer_sdk import typing as th # JSON schema typing helpers
from tap_github.streams import (
CommitsStream,
CommunityProfileStream,
IssueCommentsStream,
IssueEventsStream,
IssuesStream,
PullRequestsStream... | [
"tap_github.streams.CommunityProfileStream",
"tap_github.streams.RepositoryStream",
"tap_github.streams.IssueEventsStream",
"tap_github.streams.IssuesStream",
"singer_sdk.typing.Property",
"singer_sdk.typing.ObjectType",
"tap_github.streams.IssueCommentsStream",
"singer_sdk.typing.ArrayType",
"tap_g... | [((1306, 1329), 'tap_github.streams.CommitsStream', 'CommitsStream', ([], {'tap': 'self'}), '(tap=self)\n', (1319, 1329), False, 'from tap_github.streams import CommitsStream, CommunityProfileStream, IssueCommentsStream, IssueEventsStream, IssuesStream, PullRequestsStream, ReadmeStream, RepositoryStream\n'), ((1343, 13... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-10 08:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('org', '0001_initial'),
('event', '0002_auto_2018010... | [
"django.db.models.ForeignKey"
] | [((459, 570), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""org"""', 'to': '"""org.Org"""'}), "(null=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='org', to='org.Org')\n", (476, 570), False, 'from ... |
import digitalio
import pulseio
from smbusslave import SMBusSlave
IODIR = 0x00
IPOL = 0x01
GPINTEN = 0x02
DEFVAL = 0x03
INTCON = 0x04
IOCON = 0x05
GPPU = 0x06
INTF = 0x07
INTCAP = 0x08
GPIO = 0x09
OLAT = 0x0a
IOCON_SEQOP = 1 << 5
IOCON_ODR = 1 << 2
IOCON_INTPOL = 1 << 1
# Pull up on interrupt pins are not supported... | [
"digitalio.DigitalInOut",
"pulseio.PulseIn"
] | [((752, 782), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['intpin'], {}), '(intpin)\n', (774, 782), False, 'import digitalio\n'), ((7334, 7366), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['self.pin'], {}), '(self.pin)\n', (7356, 7366), False, 'import digitalio\n'), ((9199, 9231), 'digitalio.Digital... |
###############################
# MODULE: Object settings #
# AUTHOR: <NAME> #
# LAST UPDATE: 08/04/2019 #
###############################
import copy
from enum import Enum, IntEnum
from direct.gui.OnscreenText import TransparencyAttrib
BLACK = (0.15, 0.15, 0.15, 1)
#BLACK = (0.0, 0.0, 0.0, 1)
WHITE = (0... | [
"copy.deepcopy"
] | [((4084, 4123), 'copy.deepcopy', 'copy.deepcopy', (['self.modeles[render_obj]'], {}), '(self.modeles[render_obj])\n', (4097, 4123), False, 'import copy\n'), ((4537, 4584), 'copy.deepcopy', 'copy.deepcopy', (['self.modeles[RenderObject.PLANE]'], {}), '(self.modeles[RenderObject.PLANE])\n', (4550, 4584), False, 'import c... |
# encoding: utf-8
'''
Match articles with annotated data
'''
from collections import defaultdict
import argparse
from blamepipeline.preprocess.dataloader import Dataset
case1, case2 = 0, 0
def match_data(source):
dataset = Dataset(source)
articles = dataset.get_articles()
entries = dataset.get_entries... | [
"blamepipeline.preprocess.dataloader.Dataset",
"collections.defaultdict",
"argparse.ArgumentParser"
] | [((233, 248), 'blamepipeline.preprocess.dataloader.Dataset', 'Dataset', (['source'], {}), '(source)\n', (240, 248), False, 'from blamepipeline.preprocess.dataloader import Dataset\n'), ((344, 361), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (355, 361), False, 'from collections import defaultd... |
import tensorflow as tf
i = tf.compat.v1.constant(0, name="Hole")
c = lambda i: tf.compat.v1.less(i, 10)
b = lambda i: tf.compat.v1.add(i, 1)
r = tf.compat.v1.while_loop(c, b, [i], name="While")
| [
"tensorflow.compat.v1.while_loop",
"tensorflow.compat.v1.less",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.add"
] | [((29, 66), 'tensorflow.compat.v1.constant', 'tf.compat.v1.constant', (['(0)'], {'name': '"""Hole"""'}), "(0, name='Hole')\n", (50, 66), True, 'import tensorflow as tf\n'), ((148, 196), 'tensorflow.compat.v1.while_loop', 'tf.compat.v1.while_loop', (['c', 'b', '[i]'], {'name': '"""While"""'}), "(c, b, [i], name='While')... |
import unittest
import decimal
import prosperpy
def get_prices():
prices = ['90.704', '92.900', '92.978', '91.802', '92.665', '92.684', '92.302', '92.773', '92.537', '92.949',
'93.204', '91.067', '89.832', '89.744', '90.399', '90.739', '88.018', '88.087', '88.844', '90.778',
'90.542',... | [
"prosperpy.overlays.BollingerBands",
"decimal.Decimal"
] | [((353, 375), 'decimal.Decimal', 'decimal.Decimal', (['price'], {}), '(price)\n', (368, 375), False, 'import decimal\n'), ((936, 982), 'prosperpy.overlays.BollingerBands', 'prosperpy.overlays.BollingerBands', (['prices[:20]'], {}), '(prices[:20])\n', (969, 982), False, 'import prosperpy\n'), ((1046, 1072), 'decimal.Dec... |
import os
import math
from scapy.all import *
from pytest_main import eth_config
from pytest_main import dump_eth_config
def getstatusoutput(cmd):
pipe = os.popen(cmd + " 2>&1", 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts=0
if text[-1:] == "\n": text = text[:-1]
return sts,... | [
"os.popen"
] | [((161, 189), 'os.popen', 'os.popen', (["(cmd + ' 2>&1')", '"""r"""'], {}), "(cmd + ' 2>&1', 'r')\n", (169, 189), False, 'import os\n')] |
import os
import sys
import time
import torch
import torch.nn as nn
import random
import numpy as np
import torchvision.transforms as transforms
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_ROOT = os.path.join(FILE_DIR, '../../../data')
sys.path.append(os.path.join(FILE_DIR, '../'))
sys.path.append(os.pa... | [
"utils.Partition",
"os.path.join",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.RandomCrop",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"os.path.abspath",
"torchvision.transforms.ToTensor",
"numpy.load",
"numpy.arange",
"numpy.random.shuffle"
] | [((212, 251), 'os.path.join', 'os.path.join', (['FILE_DIR', '"""../../../data"""'], {}), "(FILE_DIR, '../../../data')\n", (224, 251), False, 'import os\n'), ((173, 198), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (188, 198), False, 'import os\n'), ((268, 297), 'os.path.join', 'os.path.joi... |
# HANGMAN GAME
from collections import namedtuple
import main
game_board = namedtuple('game_board', ['board', 'mistakes', 'letters', 'status'])
def welcome():
"""Starts the game."""
print("Welcome")
word = main._choose_word()
_print_start_game()
_print_start_spaces(word)
game_board.letters = []... | [
"main._hint",
"collections.namedtuple",
"main._choose_word"
] | [((76, 144), 'collections.namedtuple', 'namedtuple', (['"""game_board"""', "['board', 'mistakes', 'letters', 'status']"], {}), "('game_board', ['board', 'mistakes', 'letters', 'status'])\n", (86, 144), False, 'from collections import namedtuple\n'), ((219, 238), 'main._choose_word', 'main._choose_word', ([], {}), '()\n... |
# ------------------------------------------------------------------------------
# Joyous events models
# ------------------------------------------------------------------------------
import datetime as dt
from django.db import models
from django.db.models.query import ModelIterable
from django.utils import timezone
f... | [
"wagtail.admin.edit_handlers.FieldPanel",
"wagtail.images.edit_handlers.ImageChooserPanel",
"datetime.timedelta",
"django.utils.translation.gettext_lazy"
] | [((1105, 1125), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1117, 1125), True, 'import datetime as dt\n'), ((1135, 1155), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(2)'}), '(days=2)\n', (1147, 1155), True, 'import datetime as dt\n'), ((2707, 2722), 'django.utils.translation.ge... |
# coding: utf-8
from unittest import TestCase
import os
import ibm_watson
import pytest
import json
import time
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions
@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None,
reason=... | [
"ibm_watson.NaturalLanguageUnderstandingV1",
"ibm_watson.natural_language_understanding_v1.EntitiesOptions",
"os.getenv",
"ibm_watson.natural_language_understanding_v1.KeywordsOptions"
] | [((490, 553), 'ibm_watson.NaturalLanguageUnderstandingV1', 'ibm_watson.NaturalLanguageUnderstandingV1', ([], {'version': '"""2018-03-16"""'}), "(version='2018-03-16')\n", (531, 553), False, 'import ibm_watson\n'), ((233, 283), 'os.getenv', 'os.getenv', (['"""NATURAL_LANGUAGE_UNDERSTANDING_APIKEY"""'], {}), "('NATURAL_L... |
from . import common as cmmn
import logging
import uuid
from typing import Optional
from instauto.api.structs import Surface
logger = logging.getLogger(__name__)
class _Base(cmmn.Base):
_csrftoken: str = None
radio_type: str = 'wifi-none'
device_id: str = None
_uid: str = None
_uuid: str = None
... | [
"logging.getLogger",
"uuid.uuid4"
] | [((136, 163), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (153, 163), False, 'import logging\n'), ((3079, 3091), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3089, 3091), False, 'import uuid\n')] |
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.toolbar import MDToolbar
class Menus():
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(self):
box_central = MDBoxLayout(orientation='vertical')
# criar componentes
toolbar = MDToo... | [
"kivymd.uix.toolbar.MDToolbar",
"kivymd.uix.boxlayout.MDBoxLayout"
] | [((233, 268), 'kivymd.uix.boxlayout.MDBoxLayout', 'MDBoxLayout', ([], {'orientation': '"""vertical"""'}), "(orientation='vertical')\n", (244, 268), False, 'from kivymd.uix.boxlayout import MDBoxLayout\n'), ((315, 343), 'kivymd.uix.toolbar.MDToolbar', 'MDToolbar', ([], {'title': '"""App Salva"""'}), "(title='App Salva')... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 13 23:29:22 2022
@author: Tommaso
"""
from setuptools import setup
VERSION = '0.2.8'
DESCRIPTION = 'A python package for bspline curve approximation using deep learning'
# Setting up
setup(
name='deep-b-spline-approximation',
packages=['deep_b_spline_approximati... | [
"setuptools.setup"
] | [((233, 1255), 'setuptools.setup', 'setup', ([], {'name': '"""deep-b-spline-approximation"""', 'packages': "['deep_b_spline_approximation']", 'version': 'VERSION', 'author': '"""<NAME>"""', 'author_email': '"""<<EMAIL>>"""', 'description': 'DESCRIPTION', 'long_description_content_type': '"""text/markdown"""', 'url': '"... |
from argparse import ArgumentParser
import os
from displ.pwscf.parseScf import fermi_from_scf
from displ.wannier.wannier_util import global_config
from displ.wannier.build import Update_Disentanglement
def _main():
parser = ArgumentParser(description="Update disentanglement window in W90 input")
parser.add_arg... | [
"displ.pwscf.parseScf.fermi_from_scf",
"displ.wannier.wannier_util.global_config",
"argparse.ArgumentParser",
"os.path.expandvars",
"os.path.join",
"displ.wannier.build.Update_Disentanglement"
] | [((229, 301), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Update disentanglement window in W90 input"""'}), "(description='Update disentanglement window in W90 input')\n", (243, 301), False, 'from argparse import ArgumentParser\n'), ((1005, 1020), 'displ.wannier.wannier_util.global_config', 'g... |
import unittest
from credentialData import CredentialData
class TestCredentials(unittest.TestCase):
def setUp(self):
"""
setUp method
"""
self.new_credential = CredentialData("Instagram", "mimi", "mireille")
def test_init(self):
"""
testing initialization
... | [
"unittest.main",
"credentialData.CredentialData.display_credentials",
"credentialData.CredentialData"
] | [((1056, 1071), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1069, 1071), False, 'import unittest\n'), ((199, 246), 'credentialData.CredentialData', 'CredentialData', (['"""Instagram"""', '"""mimi"""', '"""mireille"""'], {}), "('Instagram', 'mimi', 'mireille')\n", (213, 246), False, 'from credentialData import ... |
import numbers
import random
import math
import torch
from scripts.study_case.ID_13.torch_geometric.transforms import LinearTransformation
class RandomRotate(object):
def __init__(self, degrees, axis=0):
if isinstance(degrees, numbers.Number):
degrees = (-abs(degrees), abs(degrees))
a... | [
"math.cos",
"torch.tensor",
"random.uniform",
"math.sin"
] | [((554, 570), 'math.sin', 'math.sin', (['degree'], {}), '(degree)\n', (562, 570), False, 'import math\n'), ((572, 588), 'math.cos', 'math.cos', (['degree'], {}), '(degree)\n', (580, 588), False, 'import math\n'), ((497, 526), 'random.uniform', 'random.uniform', (['*self.degrees'], {}), '(*self.degrees)\n', (511, 526), ... |
from flask import Flask, render_template, Response
from .OverlayCamera import OverlayCamera
from .settings import ROUTE
app = Flask(__name__)
def gen(camera):
"""Video streaming generator function."""
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type... | [
"flask.Flask"
] | [((130, 145), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'from flask import Flask, render_template, Response\n')] |
"""Implements the :py:class:`SearchClient` class."""
from typing import Any, List
from datetime import datetime, timezone
from pymongo.collation import Collation
import pymongo
__all__ = ['SearchClient']
class SearchClient:
"""This class executes search queries."""
def __init__(self, *, db: pymongo.databa... | [
"datetime.datetime.now",
"pymongo.collation.Collation"
] | [((4670, 4696), 'datetime.datetime.now', 'datetime.now', (['timezone.utc'], {}), '(timezone.utc)\n', (4682, 4696), False, 'from datetime import datetime, timezone\n'), ((6111, 6126), 'pymongo.collation.Collation', 'Collation', (['"""en"""'], {}), "('en')\n", (6120, 6126), False, 'from pymongo.collation import Collation... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... | [
"enum.IntEnum"
] | [((1680, 1715), 'enum.IntEnum', 'IntEnum', (['"""RepaintResultEnum"""', '_dict'], {}), "('RepaintResultEnum', _dict)\n", (1687, 1715), False, 'from enum import IntEnum\n')] |
############################################################
import pytesseract
import os
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
#############################################################
R_... | [
"os.path.dirname",
"os.listdir",
"os.path.join"
] | [((690, 715), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (705, 715), False, 'import os\n'), ((753, 778), 'os.listdir', 'os.listdir', (['abs_folder_in'], {}), '(abs_folder_in)\n', (763, 778), False, 'import os\n'), ((1317, 1364), 'os.path.join', 'os.path.join', (['abs_folder_out_pdf', "(na... |
"""
pdict.py -- Implement a (remote) persistent dictionary that is accessed over
a socket. The backend dictionary could be dbshelve, BSDDB, or
even a relational table of (key, blob).
*** The purpose is to have a bullet-proof, separate-process, persistent dictionary
that is very fast, globa... | [
"os.path.exists",
"twisted.application.service.Application",
"twisted.application.service.IServiceCollection",
"socket.socket",
"bsddb3.dbshelve.open",
"pickle.dumps",
"os.makedirs",
"os.path.join",
"os.path.splitext",
"os.chmod",
"os.path.split",
"os.path.dirname",
"twisted.application.inte... | [((890, 910), 'sciflo.utils.ScifloConfigParser', 'ScifloConfigParser', ([], {}), '()\n', (908, 910), False, 'from sciflo.utils import ScifloConfigParser, validateDirectory\n'), ((1079, 1128), 'os.path.join', 'os.path.join', (['WorkUnitCacheDir', 'WorkUnitCacheFile'], {}), '(WorkUnitCacheDir, WorkUnitCacheFile)\n', (109... |
import timeit
# bro, probably could just use %timeit if
# you are on ipython. :-P
starttime = timeit.default_timer()
"""
your code here
"""
endtime = timeit.default_timer()
print(endtime - starttime)
| [
"timeit.default_timer"
] | [((96, 118), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (116, 118), False, 'import timeit\n'), ((154, 176), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (174, 176), False, 'import timeit\n')] |
import os
import re
from subprocess import call
from time import sleep
supervisor_dir = "/etc/supervisor/conf.d/"
_, _, files = next(os.walk(supervisor_dir))
for f in files:
m = re.match("(hortiradar-worker\d)\.conf", f)
if m:
worker = m.group(1)
call(["supervisorctl", "restart", worker])
... | [
"time.sleep",
"re.match",
"subprocess.call",
"os.walk"
] | [((136, 159), 'os.walk', 'os.walk', (['supervisor_dir'], {}), '(supervisor_dir)\n', (143, 159), False, 'import os\n'), ((186, 230), 're.match', 're.match', (['"""(hortiradar-worker\\\\d)\\\\.conf"""', 'f'], {}), "('(hortiradar-worker\\\\d)\\\\.conf', f)\n", (194, 230), False, 'import re\n'), ((275, 317), 'subprocess.ca... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ykdl.util.html import default_proxy_handler, get_content
from ykdl.util.match import match1, matchall
from ykdl.extractor import VideoExtractor
from ykdl.videoinfo import VideoInfo
from ykdl.compact import install_opener, build_opener, HTTPCookieProcessor
import json... | [
"string.maketrans",
"ykdl.compact.build_opener",
"base64.b64encode",
"ykdl.util.match.matchall",
"uuid.uuid4",
"ykdl.videoinfo.VideoInfo",
"ykdl.util.match.match1",
"ykdl.compact.HTTPCookieProcessor",
"time.time",
"ykdl.util.html.get_content"
] | [((565, 590), 'string.maketrans', 'maketrans', (["b'+/='", "b'_~-'"], {}), "(b'+/=', b'_~-')\n", (574, 590), False, 'from string import maketrans\n'), ((630, 642), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (640, 642), False, 'import uuid\n'), ((1367, 1387), 'ykdl.videoinfo.VideoInfo', 'VideoInfo', (['self.name'], {... |
from instagram.client import InstagramAPI
from pprint import pprint
test_access_token = "1890268.7c3f1ab.e1c64ca8df38410099d98bff8a868bb6"
api = InstagramAPI(access_token=test_access_token)
pprint( api.user_recent_media())
| [
"instagram.client.InstagramAPI"
] | [((147, 191), 'instagram.client.InstagramAPI', 'InstagramAPI', ([], {'access_token': 'test_access_token'}), '(access_token=test_access_token)\n', (159, 191), False, 'from instagram.client import InstagramAPI\n')] |
""" Actor registry for rodario framework """
# local
from rodario import get_redis_connection
from rodario.exceptions import RegistrationException
# pylint: disable=C1001
class _RegistrySingleton(object):
""" Singleton for actor registry """
def __init__(self, prefix=None):
"""
Initialize t... | [
"rodario.get_redis_connection",
"rodario.exceptions.RegistrationException"
] | [((432, 454), 'rodario.get_redis_connection', 'get_redis_connection', ([], {}), '()\n', (452, 454), False, 'from rodario import get_redis_connection\n'), ((917, 969), 'rodario.exceptions.RegistrationException', 'RegistrationException', (['"""Failed adding member to set"""'], {}), "('Failed adding member to set')\n", (9... |
#!/usr/bin/env python3
# Copyright 2019, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
# Reads ms task measurement results from CSV files.
#
# If the path to the results is not given it is read from the following environment variables:
# * SCHED_MSRESULTS
# * SCHED_RESULTS and SCHED_HOST... | [
"re.compile",
"os.path.join",
"os.path.isdir",
"csv.reader",
"os.walk"
] | [((637, 702), 're.compile', 're.compile', (['"""^ms_([^(]+)\\\\(([0-9]+)\\\\)@([^_]+)_(energy|time).csv"""'], {}), "('^ms_([^(]+)\\\\(([0-9]+)\\\\)@([^_]+)_(energy|time).csv')\n", (647, 702), False, 'import re\n'), ((4642, 4657), 'os.walk', 'os.walk', (['mspath'], {}), '(mspath)\n', (4649, 4657), False, 'import os\n'),... |
import time
from prometheus_client import start_http_server, Gauge, Enum
from temper import Temper
def main():
port = 9204
t = Temper()
label_names = ['vendorid','productid','busnum','devnum']
temp_c = Gauge('temper_internal_temperature_celsius', 'Temperature in °C', label_names)
humid = Gauge('tem... | [
"prometheus_client.start_http_server",
"temper.Temper",
"time.sleep",
"prometheus_client.Gauge"
] | [((136, 144), 'temper.Temper', 'Temper', ([], {}), '()\n', (142, 144), False, 'from temper import Temper\n'), ((219, 297), 'prometheus_client.Gauge', 'Gauge', (['"""temper_internal_temperature_celsius"""', '"""Temperature in °C"""', 'label_names'], {}), "('temper_internal_temperature_celsius', 'Temperature in °C', labe... |
#!/usr/bin/env python
"""SPECFIT.PY - Generic stellar abundance determination software
"""
from __future__ import print_function
__authors__ = '<NAME> <<EMAIL>>'
__version__ = '20200711' # yyyymmdd
import os
import shutil
import contextlib, io, sys
import numpy as np
import warnings
from astropy.io import fits
fr... | [
"numpy.hstack",
"matplotlib.pyplot.ylabel",
"scipy.interpolate.interp1d",
"dlnpyutils.utils.basiclogger",
"numpy.array",
"numpy.argsort",
"dlnpyutils.utils.interp",
"numpy.isfinite",
"copy.deepcopy",
"synple.synple.read_model",
"doppler.rv.tweakcontinuum",
"numpy.arange",
"os.remove",
"os.... | [((681, 702), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (695, 702), False, 'import matplotlib\n'), ((872, 941), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""numpy.dtype size changed"""'}), "('ignore', message='numpy.dtype size changed')\n", (895, 9... |
# author: <NAME>
# date: 2020-11-25
"""
This script Splits the raw cleaned data to train and test splits
based on the user input and saves them into two separate csv files
Usage: clean_data.py --input_file_path=<input_file_path> --saving_path_train=<saving_path_train> --saving_path_test=<saving_path_test> --test_s... | [
"sklearn.model_selection.train_test_split",
"docopt.docopt",
"pandas.read_csv"
] | [((814, 829), 'docopt.docopt', 'docopt', (['__doc__'], {}), '(__doc__)\n', (820, 829), False, 'from docopt import docopt\n'), ((1543, 1571), 'pandas.read_csv', 'pd.read_csv', (['input_file_path'], {}), '(input_file_path)\n', (1554, 1571), True, 'import pandas as pd\n'), ((2072, 2131), 'sklearn.model_selection.train_tes... |
import base64
import json
import os
import tempfile
import uuid
import zipfile
from io import BytesIO
import werkzeug
from flask import Blueprint, jsonify, request
from ..config import get_config
from ..dataset import convert_ndarray_to_image, import_csv_as_mdp_dataset
from ..models.dataset import Dataset, DatasetSch... | [
"tempfile.TemporaryDirectory",
"os.path.getsize",
"zipfile.ZipFile",
"os.path.join",
"io.BytesIO",
"flask.request.form.get",
"uuid.uuid1",
"werkzeug.utils.secure_filename",
"flask.Blueprint",
"flask.jsonify"
] | [((383, 413), 'flask.Blueprint', 'Blueprint', (['"""dataset"""', '__name__'], {}), "('dataset', __name__)\n", (392, 413), False, 'from flask import Blueprint, jsonify, request\n'), ((1947, 1976), 'os.path.getsize', 'os.path.getsize', (['dataset_path'], {}), '(dataset_path)\n', (1962, 1976), False, 'import os\n'), ((356... |
"""
Update release numbers in various places, according to a release.ini file places at the project root
"""
import configparser
import logging
import sys
from configparser import ConfigParser
from pathlib import Path
from typing import Optional, Tuple
import click
from bump_release import helpers
from bump_release.h... | [
"logging.basicConfig",
"bump_release.helpers.update_file",
"click.argument",
"logging.debug",
"bump_release.helpers.load_release_file",
"pathlib.Path",
"click.option",
"bump_release.helpers.updates_yaml_file",
"pathlib.Path.cwd",
"logging.warning",
"bump_release.helpers.NothingToDoException",
... | [((503, 518), 'click.command', 'click.command', ([], {}), '()\n', (516, 518), False, 'import click\n'), ((520, 628), 'click.option', 'click.option', (['"""-r"""', '"""--release-file"""', '"""release_file"""'], {'help': '"""Release file path, default `./release.ini`"""'}), "('-r', '--release-file', 'release_file', help=... |
import numpy as np
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import matplotlib.pyplot as plt
import contractions # Expanding contractions
from nltk.stem.wordnet import WordNetLemmatizer
from sklearn.model_selection import tr... | [
"pandas.Series",
"numpy.unique",
"pandas.read_csv",
"nltk.corpus.stopwords.words",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.linear_model.LogisticRegression",
"nltk.tokenize.word_tokenize",
"sklearn.feature_... | [((1164, 1191), 'pandas.read_csv', 'pd.read_csv', (['"""df_truth.csv"""'], {}), "('df_truth.csv')\n", (1175, 1191), True, 'import pandas as pd\n'), ((2005, 2022), 'pandas.Series', 'pd.Series', (['n_text'], {}), '(n_text)\n', (2014, 2022), True, 'import pandas as pd\n'), ((3065, 3095), 'pandas.DataFrame', 'pd.DataFrame'... |
from prefect import task, Flow, Parameter
from prefect.tasks.prefect import StartFlowRun
from prefect.storage import GitHub
with Flow("token-test") as flow:
StartFlowRun(project_name="testing", flow_name="flow_must_fail")()
flow.storage = GitHub(repo="kvnkho/demos", path="/prefect/token_test.py")
flow.register("t... | [
"prefect.tasks.prefect.StartFlowRun",
"prefect.Flow",
"prefect.storage.GitHub"
] | [((245, 303), 'prefect.storage.GitHub', 'GitHub', ([], {'repo': '"""kvnkho/demos"""', 'path': '"""/prefect/token_test.py"""'}), "(repo='kvnkho/demos', path='/prefect/token_test.py')\n", (251, 303), False, 'from prefect.storage import GitHub\n'), ((130, 148), 'prefect.Flow', 'Flow', (['"""token-test"""'], {}), "('token-... |
import torch
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
hparams_file, overrides = 'train.yaml',''
PATH = './results/4234/save/CKPT+2021-04-17+16-05-06+00/model.ckpt'
# 加载超参数文件
with open(hparams_file) as fin:
hparams = load_hyperpyyaml(fin, overrides)
# 加载模型
model=hparams["model"]
model=mode... | [
"torch.mul",
"torch.expm1",
"torch.ones",
"speechbrain.dataio.dataio.write_audio",
"speechbrain.dataio.dataio.read_audio",
"torch.load",
"speechbrain.processing.features.spectral_magnitude",
"torch.no_grad",
"hyperpyyaml.load_hyperpyyaml",
"torch.log1p"
] | [((342, 358), 'torch.load', 'torch.load', (['PATH'], {}), '(PATH)\n', (352, 358), False, 'import torch\n'), ((757, 812), 'speechbrain.dataio.dataio.write_audio', 'sb.dataio.dataio.write_audio', (['tmpfile', 'noisy_wav', '(16000)'], {}), '(tmpfile, noisy_wav, 16000)\n', (785, 812), True, 'import speechbrain as sb\n'), (... |