code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import time
import numpy as np
import copy
import sys
sys.path.append(".")
import ai.parameters
import ai.actionplanner
import ai.energyplanner
# get/set/update/check/
# random.choice(d.keys())
class BehaviourPlanner:
def __init__(self):
self.energy = ai.energyplanner.EnergyPlanner()
self.last_be... | [
"sys.path.append",
"copy.deepcopy",
"time.time",
"numpy.random.gamma",
"numpy.random.random",
"numpy.random.normal"
] | [((55, 75), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (70, 75), False, 'import sys\n'), ((538, 549), 'time.time', 'time.time', ([], {}), '()\n', (547, 549), False, 'import time\n'), ((2811, 2835), 'copy.deepcopy', 'copy.deepcopy', (['behaviour'], {}), '(behaviour)\n', (2824, 2835), False, 'imp... |
import json
import os
from typing import Dict, Iterator, Optional
import ndjson
from ps2_census import Query
from .queries import fire_group_query_factory
DATA_FILENAME = "fire-groups.ndjson"
QUERY_BATCH_SIZE: int = 10
def update_data_files(
service_id: str, directory: str, force_update: bool = False,
):
... | [
"os.remove",
"os.path.exists",
"ndjson.reader",
"json.dumps"
] | [((416, 440), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (430, 440), False, 'import os\n'), ((1737, 1753), 'ndjson.reader', 'ndjson.reader', (['f'], {}), '(f)\n', (1750, 1753), False, 'import ndjson\n'), ((548, 567), 'os.remove', 'os.remove', (['filepath'], {}), '(filepath)\n', (557, 567), ... |
# -*- coding: utf-8 -*-
import sys
import os
import pdb
import json
class CreateParams(object):
def __init__(self, strategy_name):
self._strategy_name = strategy_name
self._params_dict = {}
self.read_rule()
def set_params_scope(self, key, start, end, scope, params_dict):
... | [
"pdb.set_trace",
"json.dumps",
"json.loads"
] | [((3078, 3093), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (3091, 3093), False, 'import pdb\n'), ((2162, 2181), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (2172, 2181), False, 'import json\n'), ((3012, 3034), 'json.dumps', 'json.dumps', (['params_all'], {}), '(params_all)\n', (3022, 3034), F... |
"""Pytest configuration, fixtures, and plugins."""
# pylint: disable=redefined-outer-name
import shutil
import sys
import pytest
if sys.version_info.major > 2: # TODO remove after droping python 2
from pathlib import Path # pylint: disable=E
else:
from pathlib2 import Path # pylint: disable=E
TEST_ROOT = ... | [
"pathlib2.Path"
] | [((320, 334), 'pathlib2.Path', 'Path', (['__file__'], {}), '(__file__)\n', (324, 334), False, 'from pathlib2 import Path\n')] |
# Generated by Django 2.2.6 on 2019-10-14 17:06
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('project_core', '0031_import_organisations'),
]
operations = [
migrations.AddField(
model_name='keyw... | [
"django.db.models.CharField",
"django.db.models.DateTimeField"
] | [((377, 497), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'help_text': '"""Date and time at which the keyword was created"""'}), "(default=django.utils.timezone.now, help_text=\n 'Date and time at which the keyword was created')\n", (397, 497), False, 'from... |
import logging
import torch.nn as nn
import torch.nn.functional as F
from ..initializer import initialize_from_cfg
from ...extensions import DeformableConvInOne
from ...utils.bn_helper import setup_bn, rollback_bn, FREEZE
logger = logging.getLogger('global')
__all__ = [
'resnext_101_32x4d', 'resnext_101_32x8d',... | [
"torch.nn.ReLU",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.nn.functional.relu",
"torch.nn.MaxPool2d",
"logging.getLogger"
] | [((234, 261), 'logging.getLogger', 'logging.getLogger', (['"""global"""'], {}), "('global')\n", (251, 261), False, 'import logging\n'), ((550, 639), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, ke... |
"""
This module contains mathematically focused functions
"""
import numpy as np
from math import sin, cos
def normalise(vector):
"""Return a normalised vector"""
return vector / np.linalg.norm(vector)
def rotZ(theta):
"""
Return rotation matrix that rotates with repect to z axis with theta degress... | [
"numpy.roots",
"numpy.linalg.svd",
"numpy.sin",
"numpy.linalg.norm",
"numpy.exp",
"numpy.diag",
"numpy.linalg.solve",
"numpy.transpose",
"numpy.identity",
"numpy.append",
"math.cos",
"numpy.linspace",
"numpy.cross",
"math.sin",
"numpy.linalg.inv",
"numpy.cos",
"numpy.compress",
"nu... | [((833, 897), 'numpy.array', 'np.array', (['[[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]'], {}), '([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])\n', (841, 897), True, 'import numpy as np\n'), ((1666, 2065), 'numpy.array', 'np.array', (['[[-Kx * eps[2, 0] / eps[2, 2], -Kx * eps[2, 1] / eps[2, 2], 0, ... |
from color_detection import detect
from cube import Color
COLOR_BOUNDS = {
Color.BLUE: (20, 105, 190),
Color.GREEN: (70, 175, 100),
Color.ORANGE: (220, 105, 90),
Color.RED: (120, 30, 30),
Color.WHITE: (175, 180, 200),
Color.YELLOW: (170, 200, 120)
}
def test_green_detect():
bounds = [(1105... | [
"color_detection.detect"
] | [((674, 742), 'color_detection.detect', 'detect', (['"""tests/color_detection/cube_green.jpg"""', 'bounds', 'COLOR_BOUNDS'], {}), "('tests/color_detection/cube_green.jpg', bounds, COLOR_BOUNDS)\n", (680, 742), False, 'from color_detection import detect\n'), ((1327, 1396), 'color_detection.detect', 'detect', (['"""tests... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
import sys
n = int(sys.stdin.readline())
m... | [
"sys.stdin.readline"
] | [((297, 317), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (315, 317), False, 'import sys\n'), ((386, 406), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (404, 406), False, 'import sys\n')] |
# library: python-telegram-bot
import telegram
my_token = '' # bot token
chat_id = '' # telegram group or chat id
def sendTelegramMsg(msg, chat_id=chat_id, token=my_token):
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id=chat_id, text=msg)
| [
"telegram.Bot"
] | [((181, 206), 'telegram.Bot', 'telegram.Bot', ([], {'token': 'token'}), '(token=token)\n', (193, 206), False, 'import telegram\n')] |
# Nota: presionar enter después de que la info sea desplegada para limpiar la pantalla y volver al menú
# La función red puede tomar un poco de tiempo en ejecutarse por completo
from threading import Semaphore, Thread
import os, threading
#se utilizara para lograr la sincronización de los hilos
mutex = threading.Sem... | [
"threading.Thread",
"threading.Semaphore",
"os.system"
] | [((307, 329), 'threading.Semaphore', 'threading.Semaphore', (['(1)'], {}), '(1)\n', (326, 329), False, 'import os, threading\n'), ((1298, 1318), 'os.system', 'os.system', (['"""ps -auf"""'], {}), "('ps -auf')\n", (1307, 1318), False, 'import os, threading\n'), ((1483, 1503), 'os.system', 'os.system', (['"""sensors"""']... |
import io
import re
import numpy as np
class NamedPoints():
def __init__(self, fl):
data = np.genfromtxt(fl, dtype=None)
self.xyz = np.array([[l[1], l[2], l[3]] for l in data])
self.names = [l[0].decode('ascii') for l in data]
self.name_to_xyz = dict(zip(self.names, self.xyz))
cl... | [
"numpy.array",
"numpy.genfromtxt",
"re.compile"
] | [((374, 413), 're.compile', 're.compile', (['"""^([A-Za-z]+[\']?)([0-9]+)$"""'], {}), '("^([A-Za-z]+[\']?)([0-9]+)$")\n', (384, 413), False, 'import re\n'), ((441, 489), 're.compile', 're.compile', (['"""^([A-Za-z]+[\']?)([0-9]+)-([0-9]+)$"""'], {}), '("^([A-Za-z]+[\']?)([0-9]+)-([0-9]+)$")\n', (451, 489), False, 'impo... |
#-*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect
from clustering.form import ScreenOneForm
from clustering.modelStatic import Stats
from . import ecran1
import json
import csv
import re
def view_screen(request):
if request.method == 'POST': #just wo... | [
"django.shortcuts.render",
"clustering.form.ScreenOneForm",
"clustering.modelStatic.Stats"
] | [((350, 392), 'clustering.form.ScreenOneForm', 'ScreenOneForm', (['request.POST', 'request.FILES'], {}), '(request.POST, request.FILES)\n', (363, 392), False, 'from clustering.form import ScreenOneForm\n'), ((1257, 1305), 'django.shortcuts.render', 'render', (['request', '"""ecran1.html"""', "{'id_screen': 1}"], {}), "... |
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse, JsonResponse as DJsonResponse
from . import logic, models
import logging
import json
LOG = logging.getLogger()
def JsonResponse(*args, **kwargs):
kwargs["json_dumps_params"] = {"in... | [
"django.http.HttpResponse",
"json.loads",
"logging.getLogger",
"django.http.JsonResponse",
"django.views.decorators.http.require_http_methods"
] | [((225, 244), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (242, 244), False, 'import logging\n'), ((528, 565), 'django.views.decorators.http.require_http_methods', 'require_http_methods', (["['HEAD', 'GET']"], {}), "(['HEAD', 'GET'])\n", (548, 565), False, 'from django.views.decorators.http import requi... |
import math
import numpy as np
from numerical_analysis.splines.bezier import Bezier
from numerical_analysis.dependencies import Polynomial
from numerical_analysis.root_finding import newton_raphson_2x2
from numerical_analysis.dependencies.geometry import StraightLine, Circle
from output_lib.csv_lib import ScvExporter... | [
"numerical_analysis.root_finding.newton_raphson_2x2",
"numerical_analysis.dependencies.Polynomial",
"output_lib.plot_lib.PlotExporter",
"output_lib.csv_lib.ScvExporter",
"math.sqrt",
"numerical_analysis.splines.bezier.Bezier",
"output_lib.screen_lib.ScreenPrinter",
"math.sin",
"numerical_analysis.de... | [((1016, 1056), 'numerical_analysis.dependencies.geometry.StraightLine', 'StraightLine', (['[[0, [0, 0]], [1, [1, 1]]]'], {}), '([[0, [0, 0]], [1, [1, 1]]])\n', (1028, 1056), False, 'from numerical_analysis.dependencies.geometry import StraightLine, Circle\n'), ((1287, 1347), 'numpy.array', 'np.array', (['[[a, 0], [b, ... |
from django.contrib import admin
from categorie.views import categorie
from categorie.models import Category, MotCles, Theme
admin.site.site_header = 'FASTSMART'
admin.site.site_title = "Interface d'administration"
# Register your models here.
admin.site.register(Category)
admin.site.register(MotCles)
admin.site.reg... | [
"django.contrib.admin.site.register"
] | [((247, 276), 'django.contrib.admin.site.register', 'admin.site.register', (['Category'], {}), '(Category)\n', (266, 276), False, 'from django.contrib import admin\n'), ((277, 305), 'django.contrib.admin.site.register', 'admin.site.register', (['MotCles'], {}), '(MotCles)\n', (296, 305), False, 'from django.contrib imp... |
# Generated by Django 2.2.1 on 2019-11-18 10:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('annotationweb', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='task',
name='post_processing_meth... | [
"django.db.models.CharField",
"django.db.models.PositiveSmallIntegerField"
] | [((343, 443), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'help_text': '"""Name of post processing method to use"""', 'max_length': '(255)'}), "(default='', help_text=\n 'Name of post processing method to use', max_length=255)\n", (359, 443), False, 'from django.db import migrations,... |
# -*- coding: utf-8 -*-
"""
@FileName : lenet.py
@Description : None
@Author : 齐鲁桐
@Email : <EMAIL>
@Time : 2019-05-13 16:51
@Modify : None
"""
from __future__ import absolute_import, division, print_function
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
... | [
"torch.nn.Conv2d",
"torch.nn.Linear"
] | [((459, 482), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(6)', '(5, 5)'], {}), '(1, 6, (5, 5))\n', (468, 482), True, 'import torch.nn as nn\n'), ((559, 583), 'torch.nn.Conv2d', 'nn.Conv2d', (['(6)', '(16)', '(5, 5)'], {}), '(6, 16, (5, 5))\n', (568, 583), True, 'import torch.nn as nn\n'), ((603, 622), 'torch.nn.Linear',... |
from __future__ import division
import numpy as np
from sklearn import preprocessing as skpp
__all__ = ['pre', 'post', '_remove_constant', '_add_constant']
def pre(matrix):
"""
Take the training data and put everything needed to undo this operation later into a dictionary.
:param matrixTrain:
:... | [
"numpy.shape",
"numpy.var",
"sklearn.preprocessing.StandardScaler",
"numpy.invert"
] | [((1521, 1538), 'numpy.var', 'np.var', (['matrix', '(0)'], {}), '(matrix, 0)\n', (1527, 1538), True, 'import numpy as np\n'), ((567, 588), 'sklearn.preprocessing.StandardScaler', 'skpp.StandardScaler', ([], {}), '()\n', (586, 588), True, 'from sklearn import preprocessing as skpp\n'), ((1756, 1772), 'numpy.invert', 'np... |
# elasticsearch stuff that's completely separate from any models
import json
import requests
from letters.es_settings import ES_CLIENT, ES_ANALYZE, ES_MTERMVECTORS, ES_LETTER_URL, ES_SEARCH
from letters.models import Letter
def analyze_term(term, analyzer):
query = json.dumps({
"analyzer": anal... | [
"json.loads",
"letters.es_settings.ES_CLIENT.delete",
"json.dumps",
"letters.es_settings.ES_CLIENT.index",
"requests.get"
] | [((282, 330), 'json.dumps', 'json.dumps', (["{'analyzer': analyzer, 'text': term}"], {}), "({'analyzer': analyzer, 'text': term})\n", (292, 330), False, 'import json\n'), ((619, 752), 'json.dumps', 'json.dumps', (["{'ids': ids, 'parameters': {'fields': fields, 'offsets': 'false',\n 'positions': 'false', 'field_stati... |
import unittest
import numpy as np
from small_text.utils.data import list_length
class DataUtilsTest(unittest.TestCase):
def test_list_length(self):
self.assertEqual(10, list_length(list(range(10))))
self.assertEqual(10, list_length(np.random.rand(10, 2)))
| [
"numpy.random.rand"
] | [((257, 278), 'numpy.random.rand', 'np.random.rand', (['(10)', '(2)'], {}), '(10, 2)\n', (271, 278), True, 'import numpy as np\n')] |
# Copyright 2020 Makani Technologies 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... | [
"unittest.main",
"makani.avionics.network.network_util.MessageGraphVisitor",
"makani.avionics.network.network_util.CheckForUnintendedRecipients",
"makani.avionics.network.network_config.NetworkConfig",
"makani.avionics.network.network_util.MessageGraph",
"os.path.join"
] | [((1785, 1800), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1798, 1800), False, 'import unittest\n'), ((886, 944), 'os.path.join', 'os.path.join', (['makani.HOME', '"""avionics/network/network.yaml"""'], {}), "(makani.HOME, 'avionics/network/network.yaml')\n", (898, 944), False, 'import os\n'), ((972, 1010), '... |
from typing import List
from hibpcli.password import Password
from pykeepass import PyKeePass # type: ignore
def check_passwords_from_db(path: str, master_password: str) -> List[str]:
""" - """
kp = PyKeePass(path, password=master_password)
return [
entry for entry in kp.entries if Password(pass... | [
"pykeepass.PyKeePass",
"hibpcli.password.Password"
] | [((211, 252), 'pykeepass.PyKeePass', 'PyKeePass', (['path'], {'password': 'master_password'}), '(path, password=master_password)\n', (220, 252), False, 'from pykeepass import PyKeePass\n'), ((307, 340), 'hibpcli.password.Password', 'Password', ([], {'password': 'entry.password'}), '(password=entry.password)\n', (315, 3... |
from fastapi import APIRouter
import json
router = APIRouter()
@router.get('/receita/{produtorId}')
def buscar_receita(produtorId: int):
produtor = {}
with open('api/controllers/dados/receita.json') as file:
dados = json.load(file)
filtro = [
produtor['data'] for produtor in dad... | [
"json.load",
"fastapi.APIRouter"
] | [((51, 62), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (60, 62), False, 'from fastapi import APIRouter\n'), ((236, 251), 'json.load', 'json.load', (['file'], {}), '(file)\n', (245, 251), False, 'import json\n'), ((721, 736), 'json.load', 'json.load', (['file'], {}), '(file)\n', (730, 736), False, 'import json\... |
# https://zenpack-sdk.zenoss.com/en/2.0.0/changes.html
from ZenPacks.zenoss.ZenPackLib import zenpacklib
CFG = zenpacklib.load_yaml()
schema = CFG.zenpack_module.schema
| [
"ZenPacks.zenoss.ZenPackLib.zenpacklib.load_yaml"
] | [((111, 133), 'ZenPacks.zenoss.ZenPackLib.zenpacklib.load_yaml', 'zenpacklib.load_yaml', ([], {}), '()\n', (131, 133), False, 'from ZenPacks.zenoss.ZenPackLib import zenpacklib\n')] |
import os
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import cm
from matplotlib import rcParams
from sklearn import metrics
from sklearn import tree
rcParams["font.serif"] = "Times New Roman"
rcParams["font.family"] = "serif"
dirs = dict(m... | [
"numpy.sum",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.classification_report",
"numpy.argsort",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"numpy.round",
"os.path.join",
"numpy.unique",
"numpy.int8",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.close",
"numpy.int32",
"mat... | [((393, 467), 'os.path.join', 'os.path.join', (["('F:' + os.sep + 'Masterarbeit')", '"""THESIS"""', '"""general"""', '"""plots"""'], {}), "('F:' + os.sep + 'Masterarbeit', 'THESIS', 'general', 'plots')\n", (405, 467), False, 'import os\n'), ((484, 519), 'os.path.join', 'os.path.join', (["dirs['main']", '"""truth"""'], ... |
import random
print("-----------------------------------")
print("-------Rock, paper, scissors-------")
print("Welcome to the game!")
print("The game consists of three rounds.")
print("The winner is the one who scores more points.")
print("\t[r] - rock\n\t[s] - scissors\n\t[p] - paper")
player_score = 0
player_select ... | [
"random.choice"
] | [((555, 575), 'random.choice', 'random.choice', (['"""rps"""'], {}), "('rps')\n", (568, 575), False, 'import random\n')] |
from bluesky.magics import BlueskyMagics
import bluesky.plans as bp
import bluesky.plan_stubs as bps
import os
import pytest
import signal
from types import SimpleNamespace
class FakeIPython:
def __init__(self, user_ns):
self.user_ns = user_ns
def compare_msgs(actual, expected):
for a, e in zip(actu... | [
"bluesky.magics.BlueskyMagics.detectors.clear",
"os.getpid",
"bluesky.magics.BlueskyMagics.positioners.extend",
"pytest.warns",
"bluesky.magics.BlueskyMagics.positioners.clear",
"os.kill",
"pytest.raises",
"bluesky.plan_stubs.mv",
"pytest.mark.parametrize",
"types.SimpleNamespace",
"bluesky.magi... | [((494, 1323), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""pln,plnargs,magic,line,detectors_factory"""', "[(bps.mv, lambda hw: (hw.motor1, 2), 'mov', 'motor1 2', lambda hw: []), (\n bps.mv, lambda hw: (hw.motor1, 2, hw.motor2, 3), 'mov',\n 'motor1 2 motor2 3', lambda hw: []), (bps.mvr, lambda hw: ... |
import string
import numpy as np
import sys
import random
import os
from shutil import copyfile
import subprocess
from rpt_ele import rpt_ele
import update_process_model_input_file as up
import swmm_mpc as sm
def get_flood_cost_from_dict(rpt, node_flood_weight_dict):
node_flood_costs = []
for nodeid, weight i... | [
"sys.platform.startswith",
"os.remove",
"update_process_model_input_file.update_controls_and_hotstart",
"update_process_model_input_file.read_hs_filename",
"random.choice",
"subprocess.call",
"shutil.copyfile",
"numpy.squeeze",
"os.path.split",
"os.path.join"
] | [((7428, 7460), 'shutil.copyfile', 'copyfile', (['proc_inp', 'tmp_proc_inp'], {}), '(proc_inp, tmp_proc_inp)\n', (7436, 7460), False, 'from shutil import copyfile\n'), ((7508, 7537), 'update_process_model_input_file.read_hs_filename', 'up.read_hs_filename', (['proc_inp'], {}), '(proc_inp)\n', (7527, 7537), True, 'impor... |
import descarteslabs as dl
# The bounding box geometry of Haiti
haiti = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-74.520263671875,
17.98918266463051
],
[
... | [
"descarteslabs.scenes.display",
"descarteslabs.scenes.search"
] | [((755, 913), 'descarteslabs.scenes.search', 'dl.scenes.search', (["haiti['geometry']"], {'products': "['sentinel-2:L1C']", 'start_datetime': '"""2018-05-01"""', 'end_datetime': '"""2018-05-03"""', 'cloud_fraction': '(0.7)', 'limit': '(5)'}), "(haiti['geometry'], products=['sentinel-2:L1C'],\n start_datetime='2018-0... |
import xml.etree.ElementTree as ET
import requests
from bs4 import BeautifulSoup
from discord import Embed
from utils.classes.Hero import Hero
from utils.library import files
from utils.classes.Const import config
def get_last_update(url, embed=None):
try:
if embed is None:
embed = Embed(
... | [
"utils.classes.Hero.Hero",
"discord.Embed",
"xml.etree.ElementTree.fromstring",
"requests.get",
"bs4.BeautifulSoup"
] | [((1361, 1388), 'requests.get', 'requests.get', (['patch_summary'], {}), '(patch_summary)\n', (1373, 1388), False, 'import requests\n'), ((1400, 1428), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['response.text'], {}), '(response.text)\n', (1413, 1428), True, 'import xml.etree.ElementTree as ET\n'), ((1706, ... |
import logarithmoforecast
import pandas as pd
from pathlib import Path
def create_ml_dataframe(station_name, phase, pickle_dir=Path('pickles')):
path = pickle_dir / station_name
df_ml = pd.read_pickle(path / ("h_phase"+str(phase)))
df_ml.drop(columns=['ServiceDeliveryPoint'])
print(df_ml)
def main()... | [
"pathlib.Path"
] | [((129, 144), 'pathlib.Path', 'Path', (['"""pickles"""'], {}), "('pickles')\n", (133, 144), False, 'from pathlib import Path\n'), ((392, 411), 'pathlib.Path', 'Path', (['"""testPickles"""'], {}), "('testPickles')\n", (396, 411), False, 'from pathlib import Path\n')] |
from _context import sparse
from sparse import util
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.distributions as dist
import numpy as np
from argparse import ArgumentParser
from torch.utils.tensorboard import SummaryWriter
import random, tqdm, s... | [
"torch.nn.Dropout",
"torch.distributions.Categorical",
"argparse.ArgumentParser",
"sparse.util.inv",
"torch.bmm",
"torch.nn.Embedding",
"torch.cat",
"torch.randn",
"matplotlib.pyplot.figure",
"sparse.util.plot1d",
"torch.arange",
"torch.no_grad",
"torch.nn.functional.pad",
"sparse.util.plo... | [((355, 369), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (362, 369), True, 'import matplotlib as mpl\n'), ((635, 652), 'math.log2', 'math.log2', (['math.e'], {}), '(math.e)\n', (644, 652), False, 'import random, tqdm, sys, math\n'), ((774, 813), 'torch.nn.functional.softmax', 'F.softmax', (['(lnprob... |
# Daftar package yang kita pakai
from flask import Flask, request, jsonify, make_response
from flaskext.mysql import MySQL
from flask_restful import Resource, Api
# Create an instance of Flask
app = Flask(__name__)
# Create an instance of MySQL
mysql = MySQL()
# Create an instance of Flask RESTful API
api = Api(app)... | [
"flask_restful.Api",
"flask.request.form.get",
"flask.Flask",
"flaskext.mysql.MySQL",
"flask.jsonify"
] | [((200, 215), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (205, 215), False, 'from flask import Flask, request, jsonify, make_response\n'), ((255, 262), 'flaskext.mysql.MySQL', 'MySQL', ([], {}), '()\n', (260, 262), False, 'from flaskext.mysql import MySQL\n'), ((312, 320), 'flask_restful.Api', 'Api', (... |
import argparse
import yaml
from pathlib import Path
from . import name as package_name
from . import archive_org_repos
def _handle_args():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--config-yaml',
help='Set the YAML fi... | [
"yaml.load",
"argparse.ArgumentParser",
"pathlib.Path"
] | [((154, 233), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (177, 233), False, 'import argparse\n'), ((1081, 1120), 'yaml.load', 'yaml.load', (['file'], {'Loader': 'yaml.FullLoader'... |
from mechanicalsoup.stateful_browser import _BrowserState
import bs4
import cssselect
import logging
import lxml.html
import mechanicalsoup
import re
import requests
log = logging.getLogger(__name__)
# requests offers no easy way to customize the response class (response_hook
# and copy everything over to a new ins... | [
"bs4.BeautifulSoup",
"cssselect.HTMLTranslator",
"re.search",
"logging.getLogger"
] | [((174, 201), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (191, 201), False, 'import logging\n'), ((472, 498), 'cssselect.HTMLTranslator', 'cssselect.HTMLTranslator', ([], {}), '()\n', (496, 498), False, 'import cssselect\n'), ((4982, 5042), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', ([... |
from unittest import TestCase
from femtoweb import server
from femtoweb.server import (
CouldNotParse,
as_choice,
as_nonempty,
as_type,
get_file_path_content_type,
maybe_as,
with_default_as,
)
class Tester(TestCase):
def test_as_type_int(self):
as_int = as_type(int)
f... | [
"femtoweb.server.as_choice",
"femtoweb.server.get_file_path_content_type",
"femtoweb.server.as_type"
] | [((298, 310), 'femtoweb.server.as_type', 'as_type', (['int'], {}), '(int)\n', (305, 310), False, 'from femtoweb.server import CouldNotParse, as_choice, as_nonempty, as_type, get_file_path_content_type, maybe_as, with_default_as\n'), ((795, 809), 'femtoweb.server.as_type', 'as_type', (['float'], {}), '(float)\n', (802, ... |
from django import template
register = template.Library()
@register.filter()
def redact(text, case):
return case.redact_obj(text)
@register.filter()
def elide(text, case):
return case.elide_obj(text) | [
"django.template.Library"
] | [((41, 59), 'django.template.Library', 'template.Library', ([], {}), '()\n', (57, 59), False, 'from django import template\n')] |
from unittest import TestCase
from messageDecode import MessageDecode
import time
import unittest
__author__ = '<NAME>'
inputstring = "Hi @Ramki how are you (smiles)http://www.cubrid.org/blog/dev-platform/understanding-jvm-internals/"
messageTime = time.ctime()
class TestMessageDecode(TestCase):
def setUp(self)... | [
"unittest.main",
"time.ctime",
"messageDecode.MessageDecode"
] | [((251, 263), 'time.ctime', 'time.ctime', ([], {}), '()\n', (261, 263), False, 'import time\n'), ((1397, 1412), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1410, 1412), False, 'import unittest\n'), ((511, 526), 'messageDecode.MessageDecode', 'MessageDecode', ([], {}), '()\n', (524, 526), False, 'from messageDe... |
from discord import errors
from discord.ext import commands
import requests
import json
from modules.Search import queryAnime, queryChar
from utils.helpers import quick_embed
class ani(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
... | [
"discord.ext.commands.command",
"json.loads",
"discord.ext.commands.Cog.listener",
"discord.ext.commands.cooldown",
"modules.Search.queryChar",
"requests.post",
"modules.Search.queryAnime"
] | [((262, 285), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (283, 285), False, 'from discord.ext import commands\n'), ((365, 383), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (381, 383), False, 'from discord.ext import commands\n'), ((496, 514), 'discord.ext.c... |
#@<> Setup
testutil.deploy_sandbox(__mysql_sandbox_port1, "root")
#@<> Setup cluster
import mysqlsh
mydba = mysqlsh.connect_dba(__sandbox_uri1)
cluster = mydba.create_cluster("mycluster")
cluster.disconnect()
#@<> Catch error through mysqlsh.Error
try:
mydba.get_cluster("badcluster")
testutil.fail("<red>F... | [
"mysqlsh.connect_dba"
] | [((112, 147), 'mysqlsh.connect_dba', 'mysqlsh.connect_dba', (['__sandbox_uri1'], {}), '(__sandbox_uri1)\n', (131, 147), False, 'import mysqlsh\n')] |
import docspec
import pytest
@pytest.fixture
def module() -> docspec.Module:
module = docspec.Module('a', None, None, [
docspec.Class('foo', None, docspec.Docstring('This is class foo.', None), None, None, None, [
docspec.Data('val', None, None, 'int', '42'),
docspec.Function('__init__', None, None... | [
"docspec.Docstring",
"docspec.Argument",
"docspec.Location",
"docspec.Data"
] | [((579, 609), 'docspec.Location', 'docspec.Location', (['"""test.py"""', '(0)'], {}), "('test.py', 0)\n", (595, 609), False, 'import docspec\n'), ((156, 201), 'docspec.Docstring', 'docspec.Docstring', (['"""This is class foo."""', 'None'], {}), "('This is class foo.', None)\n", (173, 201), False, 'import docspec\n'), (... |
from pathlib import Path
from sphinx_rtd_theme import setup as base_setup
from ._version_git import __version__
# See https://www.sphinx-doc.org/en/master/development/theming.html
# #distribute-your-theme-as-a-python-package
def setup(app):
# Register the theme that can be referenced without adding a th... | [
"pathlib.Path",
"sphinx_rtd_theme.setup"
] | [((447, 462), 'sphinx_rtd_theme.setup', 'base_setup', (['app'], {}), '(app)\n', (457, 462), True, 'from sphinx_rtd_theme import setup as base_setup\n'), ((397, 411), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (401, 411), False, 'from pathlib import Path\n')] |
import socket
import time
import logging
import uuid
import random
from db.models import WeatherStation as WeatherStationModel, MetricType as MetricTypeModel, Metric as MetricModel
from db.create_db import session
from datetime import datetime
LOG_FORMAT = ('%(levelname) -5s %(asctime)s %(name) -5s %(funcName) -5s %(... | [
"uuid.uuid4",
"logging.debug",
"logging.basicConfig",
"random.uniform",
"db.models.WeatherStation",
"time.sleep",
"db.create_db.session.add",
"socket.gethostname",
"logging.info",
"db.create_db.session.commit",
"db.models.Metric",
"uuid.uuid5",
"db.create_db.session.merge",
"datetime.datet... | [((373, 428), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'LOG_FORMAT', 'level': 'LOG_LEVEL'}), '(format=LOG_FORMAT, level=LOG_LEVEL)\n', (392, 428), False, 'import logging\n'), ((544, 570), 'random.uniform', 'random.uniform', (['(15.0)', '(20.0)'], {}), '(15.0, 20.0)\n', (558, 570), False, 'import ra... |
from flask import Flask
import json
import os
import datetime
import sys
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask import render_template
from flask import request
sys.path.append('.')
from config import Config
app = Flask(__nam... | [
"sys.path.append",
"flask.Flask",
"os.popen",
"json.dumps",
"datetime.datetime.now",
"wtforms.SubmitField",
"flask.render_template",
"wtforms.validators.DataRequired"
] | [((254, 274), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (269, 274), False, 'import sys\n'), ((309, 324), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (314, 324), False, 'from flask import Flask\n'), ((4010, 4034), 'wtforms.SubmitField', 'SubmitField', (['"""Get Yaml!"""'], {}), ... |
import copy
import torch
import torch.nn as nn
from Result import Result
class Dlg:
def __init__(self, setting):
self.setting = setting
self.defenses = setting.defenses
self.criterion = nn.CrossEntropyLoss().to(setting.device)
self.gradient = None
self.dummy_data = None
... | [
"torch.add",
"torch.nn.CrossEntropyLoss",
"torch.randn",
"torch.softmax",
"Result.Result",
"torch.Tensor",
"torch.div",
"torch.optim.LBFGS"
] | [((3452, 3472), 'Result.Result', 'Result', (['self.setting'], {}), '(self.setting)\n', (3458, 3472), False, 'from Result import Result\n'), ((2985, 3063), 'torch.optim.LBFGS', 'torch.optim.LBFGS', (['[self.dummy_data, self.dummy_label]'], {'lr': "parameter['dlg_lr']"}), "([self.dummy_data, self.dummy_label], lr=paramet... |
# Generated by Django 3.1.12 on 2021-06-25 12:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0017_merge_20210624_1913'),
]
operations = [
migrations.DeleteModel(
name='SectionRecommendation',
),
]
| [
"django.db.migrations.DeleteModel"
] | [((226, 278), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'name': '"""SectionRecommendation"""'}), "(name='SectionRecommendation')\n", (248, 278), False, 'from django.db import migrations\n')] |
"""Implementation of delayed impact lending simulator based on Liu et al.
<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2018, July). Delayed
Impact of Fair Machine Learning. In International Conference on Machine
Learning. (https://arxiv.org/abs/1803.04383)
"""
import copy
import dataclasses
import os
from typing imp... | [
"copy.deepcopy",
"whynot.traceable_numpy.maximum",
"whynot.dynamics.Run",
"os.path.realpath",
"whynot.traceable_numpy.random.RandomState",
"whynot.simulators.delayed_impact.fico.get_data_args",
"whynot.traceable_numpy.log"
] | [((776, 799), 'whynot.simulators.delayed_impact.fico.get_data_args', 'get_FICO_data', (['DATAPATH'], {}), '(DATAPATH)\n', (789, 799), True, 'from whynot.simulators.delayed_impact.fico import get_data_args as get_FICO_data\n'), ((7453, 7480), 'whynot.traceable_numpy.random.RandomState', 'np.random.RandomState', (['seed'... |
from maya import cmds, mel
import wave, struct
import os.path, math, array, time
from cmath import exp,pi
class WavReader:
"""
This class is the responsible of managing the way the wav files open and their information
"""
def __init__(self, filePath):
# Save the path to the ... | [
"maya.cmds.timeControl",
"maya.cmds.deleteUI",
"maya.cmds.textFieldButtonGrp",
"maya.cmds.layout",
"maya.cmds.button",
"maya.cmds.createNode",
"maya.cmds.text",
"maya.cmds.intSliderGrp",
"maya.cmds.optionMenu",
"maya.cmds.menuItem",
"maya.cmds.columnLayout",
"maya.cmds.playbackOptions",
"may... | [((436, 460), 'wave.open', 'wave.open', (['filePath', '"""r"""'], {}), "(filePath, 'r')\n", (445, 460), False, 'import wave, struct\n'), ((2400, 2425), 'math.log', 'math.log', (['values_count', '(2)'], {}), '(values_count, 2)\n', (2408, 2425), False, 'import os.path, math, array, time\n'), ((7403, 7437), 'cmath.exp', '... |
from unittest import mock
import tensorflow as tf
class RealTfModel:
def __init__(self, model):
self.model = model
self.input = tf.ones([1, 2]) * 1
self.y_true = [[9.]]
self.loss = tf.keras.losses.MeanSquaredError()
@classmethod
def create(cls):
ones_init = tf.ker... | [
"tensorflow.ones",
"unittest.mock.create_autospec",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.layers.Dense",
"tensorflow.GradientTape"
] | [((220, 254), 'tensorflow.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {}), '()\n', (252, 254), True, 'import tensorflow as tf\n'), ((1101, 1144), 'unittest.mock.create_autospec', 'mock.create_autospec', (['tf.keras.layers.Dense'], {}), '(tf.keras.layers.Dense)\n', (1121, 1144), False, 'from... |
import json
from get_country_code import get_cc, get_continent
import networkx as nx
input_file = "24h_5k_users_followers_countries"
output_file = "graph_full"
total_entries = 0
with_country = 0
g = nx.DiGraph()
def increment_edge(n1, n2):
if n1 == n2:
return
increment_node(n1)
make_node(n2)
... | [
"networkx.DiGraph",
"json.loads",
"networkx.write_gexf",
"get_country_code.get_continent"
] | [((202, 214), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (212, 214), True, 'import networkx as nx\n'), ((1083, 1134), 'networkx.write_gexf', 'nx.write_gexf', (['g', "('graphs/' + output_file + '.gexf')"], {}), "(g, 'graphs/' + output_file + '.gexf')\n", (1096, 1134), True, 'import networkx as nx\n'), ((911, 92... |
"""Unit tests for instrupy.radiometer_model.
References: [1] Chapter 6,7 in "Microwave Radar and Radiometric Remote Sensing," <NAME> , <NAME> 2014
@TODO Include rectangular antenna tests
"""
import unittest
import json
import numpy as np
import sys, os
from instrupy.radiometer_model import PredetectionSectionPara... | [
"instrupy.radiometer_model.BalancedDikeRadiometerSystem.from_dict",
"instrupy.util.Antenna.from_dict",
"instrupy.radiometer_model.FixedScan.from_dict",
"instrupy.radiometer_model.TotalPowerRadiometerSystem.compute_integration_time",
"instrupy.radiometer_model.PredetectionSectionParams",
"instrupy.radiomet... | [((2357, 2413), 'instrupy.radiometer_model.TotalPowerRadiometerSystem.from_json', 'TotalPowerRadiometerSystem.from_json', (['self.tpr_sys1_json'], {}), '(self.tpr_sys1_json)\n', (2393, 2413), False, 'from instrupy.radiometer_model import RadiometerModel, SystemType, TotalPowerRadiometerSystem, UnbalancedDikeRadiometerS... |
from copy import deepcopy
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from django.conf import settings
from django.test import TestCase, override_settings
from rest_framework.test import APITestCase
from formidable.models import Formidable
from formidable.views import check... | [
"copy.deepcopy",
"formidable.models.Formidable.objects.create",
"formidable.views.check_callback_configuration",
"unittest.mock.patch",
"django.urls.reverse",
"django.test.override_settings"
] | [((546, 664), 'django.test.override_settings', 'override_settings', ([], {'FORMIDABLE_POST_CREATE_CALLBACK_SUCCESS': 'CALLBACK', 'FORMIDABLE_POST_CREATE_CALLBACK_FAIL': 'CALLBACK'}), '(FORMIDABLE_POST_CREATE_CALLBACK_SUCCESS=CALLBACK,\n FORMIDABLE_POST_CREATE_CALLBACK_FAIL=CALLBACK)\n', (563, 664), False, 'from djan... |
"""Main"""
import sys
sys.stderr = open("error.log", "w")
import time
# import msvcrt
import os
import subprocess
import cv2
import sqlite3
import numpy as np
from pyzbar import pyzbar
from easytello.tello import Tello
from httprequest import HTTPRequest
from easytello.tello_control import ControlCommand as CoCo
from ... | [
"numpy.abs",
"easytello.tello_control.ControlCommand",
"httprequest.HTTPRequest",
"easytello.tello.Tello",
"pyzbar.pyzbar.decode",
"time.sleep",
"sqlite3.connect",
"numpy.array",
"easytello.tello_control.TelloControl"
] | [((1007, 1014), 'easytello.tello.Tello', 'Tello', ([], {}), '()\n', (1012, 1014), False, 'from easytello.tello import Tello\n'), ((1058, 1072), 'easytello.tello_control.TelloControl', 'TelloControl', ([], {}), '()\n', (1070, 1072), False, 'from easytello.tello_control import TelloControl\n'), ((6642, 6655), 'time.sleep... |
#@ OpService ops
#@ Integer (value=128) xSize
#@ Integer (value=128) ySize
#@ Integer (value=128) zSize
#@OUTPUT ImgPlus phantom
#@OUTPUT ImgPlus convolved
from net.imglib2 import Point
from net.imglib2.algorithm.region.hypersphere import HyperSphere
# create an empty image
phantom=ops.create().img([xSize, ySize, zS... | [
"net.imglib2.algorithm.region.hypersphere.HyperSphere"
] | [((783, 816), 'net.imglib2.algorithm.region.hypersphere.HyperSphere', 'HyperSphere', (['phantom', 'location', '(5)'], {}), '(phantom, location, 5)\n', (794, 816), False, 'from net.imglib2.algorithm.region.hypersphere import HyperSphere\n')] |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: carbon.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflec... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor"
] | [((479, 505), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (503, 505), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((1118, 1414), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""timestamp"""', 'ful... |
import json
import json
import csv
import sys
import os
import random
import math
import string
from collections import namedtuple, Counter
# T2 Deliverable
# Assuming dataset is downloaded, open each json and extract text data
# Assuming metadata is downloaded, open and extract publish time per json article
def creat... | [
"json.load",
"os.makedirs",
"csv.DictReader",
"os.path.exists",
"collections.namedtuple",
"os.path.join",
"os.listdir"
] | [((485, 507), 'os.listdir', 'os.listdir', (['datasetDir'], {}), '(datasetDir)\n', (495, 507), False, 'import os\n'), ((1135, 1166), 'os.path.exists', 'os.path.exists', (['trainBeforePath'], {}), '(trainBeforePath)\n', (1149, 1166), False, 'import os\n'), ((1212, 1242), 'os.path.exists', 'os.path.exists', (['trainAfterP... |
import typing
import json
from pathlib import Path
from web3 import Web3
from web3.providers import BaseProvider
from web3.contract import Contract
class BridgePool:
"""
A class for interacting with the bridge pool contract.
"""
@staticmethod
def connect(address: str, provider: BaseProvider) -> ... | [
"pathlib.Path",
"json.load",
"web3.Web3"
] | [((343, 357), 'web3.Web3', 'Web3', (['provider'], {}), '(provider)\n', (347, 357), False, 'from web3 import Web3\n'), ((813, 827), 'web3.Web3', 'Web3', (['provider'], {}), '(provider)\n', (817, 827), False, 'from web3 import Web3\n'), ((487, 506), 'json.load', 'json.load', (['abi_file'], {}), '(abi_file)\n', (496, 506)... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=["GET", "POST"])
def home():
workers =[
{"id": 1, "name":"Worker1", "salary":1237.99},
{"id": 2, "name":"Worker2", "salary":5237.99},
{"id": 3, "name":"Worker5", "salary":5237.39}
]
return render_te... | [
"flask.Flask",
"flask.render_template"
] | [((57, 72), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (62, 72), False, 'from flask import Flask, render_template, request\n'), ((311, 361), 'flask.render_template', 'render_template', (['"""html/home.html"""'], {'workers': 'workers'}), "('html/home.html', workers=workers)\n", (326, 361), False, 'from ... |
from django.db import IntegrityError
from Poem.api import serializers
from Poem.api.views import NotFound
from Poem.poem import models as poem_models
from Poem.users.models import CustUser
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.response im... | [
"Poem.poem.models.GroupOfAggregations.objects.get",
"Poem.poem.models.GroupOfThresholdsProfiles.objects.get",
"Poem.poem.models.UserProfile.objects.get",
"Poem.poem.models.UserProfile.objects.create",
"Poem.users.models.CustUser.objects.get",
"Poem.users.models.CustUser.objects.create_user",
"rest_frame... | [((5546, 5601), 'Poem.users.models.CustUser.objects.get', 'CustUser.objects.get', ([], {'username': "request.data['username']"}), "(username=request.data['username'])\n", (5566, 5601), False, 'from Poem.users.models import CustUser\n'), ((5624, 5670), 'Poem.poem.models.UserProfile.objects.get', 'poem_models.UserProfile... |
import speech_recognition as sr
r = sr.Recognizer()
def listen():
with sr.Microphone(device_index = 2) as source:
r.adjust_for_ambient_noise(source)
r.pause_threshold = 2
print("Say Something");
audio = r.listen(source)
print("got it");
text = r.recognize_google(audio, language = "fr-FR")
print("You said :... | [
"speech_recognition.AudioFile",
"speech_recognition.Recognizer",
"speech_recognition.Microphone"
] | [((36, 51), 'speech_recognition.Recognizer', 'sr.Recognizer', ([], {}), '()\n', (49, 51), True, 'import speech_recognition as sr\n'), ((72, 101), 'speech_recognition.Microphone', 'sr.Microphone', ([], {'device_index': '(2)'}), '(device_index=2)\n', (85, 101), True, 'import speech_recognition as sr\n'), ((347, 370), 'sp... |
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto import Random
import logging
logger = logging.getLogger("root")
AES_KEY = '73f40f2c57eae727a4be171009cecf89'
def aes_encrypt(data):
if data:
bs = AES.block_size
pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
... | [
"Crypto.Random.new",
"Crypto.Cipher.AES.new",
"logging.getLogger"
] | [((105, 130), 'logging.getLogger', 'logging.getLogger', (['"""root"""'], {}), "('root')\n", (122, 130), False, 'import logging\n'), ((366, 400), 'Crypto.Cipher.AES.new', 'AES.new', (['AES_KEY', 'AES.MODE_CBC', 'iv'], {}), '(AES_KEY, AES.MODE_CBC, iv)\n', (373, 400), False, 'from Crypto.Cipher import AES\n'), ((772, 806... |
import os
import random
import time
import math
from datetime import timedelta
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as utils
import torch_geometric.transforms as T
from torch.autograd import V... | [
"torch.nn.Dropout",
"json.dump",
"torch.nn.MSELoss",
"cargonet.models.tempconv.TemporalConvNet",
"random.shuffle",
"os.path.realpath",
"torch.nn.BatchNorm1d",
"os.path.exists",
"datetime.datetime.now",
"math.log",
"torch.optim.lr_scheduler.ExponentialLR",
"pprint.pprint",
"torch.nn.Linear",
... | [((1874, 1893), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (1884, 1893), True, 'import torch.nn as nn\n'), ((1917, 1993), 'torch.nn.Linear', 'nn.Linear', (['(self.node_input_dim + self.edge_input_dim + 0)', 'self.embedding_dim'], {}), '(self.node_input_dim + self.edge_input_dim + 0, self.embedd... |
"""
Tutorial: Two patch Rosenzweig-MacArthur predator-prey model using Symbolic tools
For details, see
"Predator migration in response to prey density: What are the consequences?"
by <NAME> et al, J. Math Biol, Vol. 43, pp. 561-581, (2001)
"""
from __future__ import print_function
from PyDSTool import *
import matplo... | [
"matplotlib.pyplot.title",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.figure"
] | [((2735, 2801), 'matplotlib.pyplot.title', 'plt.title', (['"""Bifurcation diagram of equilibria in (k,D) parameters"""'], {}), "('Bifurcation diagram of equilibria in (k,D) parameters')\n", (2744, 2801), True, 'from matplotlib import pyplot as plt\n'), ((3850, 3879), 'matplotlib.pyplot.plot', 'plt.plot', (['(9.0)', "Hp... |
from enum import Enum
import numpy as np
def mean_squared_error(observed_value: np.ndarray, predicted_value: np.ndarray, axis: tuple = None) -> np.ndarray:
if axis is None:
return np.mean(np.square(np.subtract(observed_value, predicted_value)))
else:
return np.mean(np.square(np.subtract(obser... | [
"numpy.subtract"
] | [((213, 257), 'numpy.subtract', 'np.subtract', (['observed_value', 'predicted_value'], {}), '(observed_value, predicted_value)\n', (224, 257), True, 'import numpy as np\n'), ((303, 347), 'numpy.subtract', 'np.subtract', (['observed_value', 'predicted_value'], {}), '(observed_value, predicted_value)\n', (314, 347), True... |
import numpy as np
from PIL import Image
from PIL import ImageFilter
import matplotlib.pyplot as plt
import os
from itertools import permutations
from IPython.display import clear_output
from copy import deepcopy
from collections import namedtuple
# ---------------- Image utilities ----------------
def read_img(filen... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"PIL.Image.new",
"copy.deepcopy",
"matplotlib.pyplot.imshow",
"itertools.permutations",
"numpy.square",
"PIL.Image.open",
"matplotlib.pyplot.figure",
"numpy.array",
"collections.namedtuple",
"numpy.linspace",
"IPython.display.clear_outp... | [((380, 400), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (390, 400), False, 'from PIL import Image\n'), ((1631, 1658), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (1641, 1658), True, 'import matplotlib.pyplot as plt\n'), ((1979, 1994), 'matplot... |
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
import django
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
f... | [
"django.contrib.auth.decorators.login_required",
"app.models.User.objects.get",
"app.models.Mail.objects.count",
"app.models.User.objects.raw",
"app.models.Mail.objects.filter",
"django.utils.timezone.datetime",
"app.models.User.objects.filter",
"django.db.models.functions.TruncDate",
"django.db.mod... | [((581, 616), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""/login/"""'}), "(login_url='/login/')\n", (595, 616), False, 'from django.contrib.auth.decorators import login_required\n'), ((1218, 1253), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'lo... |
import datetime
from sqlalchemy import Column, Integer, Unicode, DateTime, ForeignKey
from sqlalchemy.orm import relation
from db import Base
class CreateCommand(Base):
"""語録を登録するコマンドを管理するModel
"""
__tablename__ = 'create_command'
id = Column(Integer, primary_key=True)
name = Column(Unicode(100)... | [
"sqlalchemy.Unicode",
"sqlalchemy.orm.relation",
"sqlalchemy.ForeignKey",
"sqlalchemy.Column"
] | [((256, 289), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (262, 289), False, 'from sqlalchemy import Column, Integer, Unicode, DateTime, ForeignKey\n'), ((414, 477), 'sqlalchemy.Column', 'Column', (['DateTime'], {'default': 'datetime.datetime.now', 'nullable... |
#!/usr/bin/env python3
# Write a Shannon entropy calculator: H = -sum(pi * log(pi))
# The values should come from the command line
# E.g. python3 entropy.py 0.4 0.3 0.2 0.1
# Put the probabilities into a new list
# Don't forget to convert them to numbers
import math
import sys
p = sys.argv[1:]
y = len(p)
H = 0
for i ... | [
"math.log"
] | [((376, 390), 'math.log', 'math.log', (['h', '(2)'], {}), '(h, 2)\n', (384, 390), False, 'import math\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import weakref
import gc
class SomeClass:
def __init__(self, name):
self.name = name
def __del__(self):
print(f"{self.name} is dying")
def __repr__(self):
return f"SomeClass[{self.name}]"
def __str__(self):
return self._... | [
"gc.collect",
"gc.disable",
"weakref.proxy"
] | [((363, 375), 'gc.disable', 'gc.disable', ([], {}), '()\n', (373, 375), False, 'import gc\n'), ((434, 450), 'weakref.proxy', 'weakref.proxy', (['b'], {}), '(b)\n', (447, 450), False, 'import weakref\n'), ((463, 479), 'weakref.proxy', 'weakref.proxy', (['a'], {}), '(a)\n', (476, 479), False, 'import weakref\n'), ((609, ... |
"""Fake client that polls different API endpoints
"""
import datetime
import logging
import time
import requests
logging.basicConfig(level=logging.DEBUG)
def run_requests():
host = 'http://test-app:5000'
paths = [
'/',
'/',
'/base-test?resp=200',
'/base-test?resp=500',
... | [
"logging.basicConfig",
"time.sleep",
"logging.info",
"requests.get",
"datetime.datetime.now"
] | [((116, 156), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (135, 156), False, 'import logging\n'), ((417, 464), 'logging.info', 'logging.info', (['f"""*** Starting Request Batch ***"""'], {}), "(f'*** Starting Request Batch ***')\n", (429, 464), False, 'impo... |
from numpy import random
import numpy as np
import matplotlib.pyplot as plt
import math
### Defining theta
theta = math.pi/4
### Generates count number of random values in the range [0, 1]
def getU(count):
u = []
for i in range(count):
key = random.rand()
u.append(key)
return u
def getX(u):
x = []
for t in... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"numpy.append",
"numpy.histogram",
"numpy.cumsum",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.gca",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"... | [((649, 686), 'numpy.append', 'np.append', (['data_set', '(data_set[-1] + 1)'], {}), '(data_set, data_set[-1] + 1)\n', (658, 686), True, 'import numpy as np\n'), ((707, 751), 'numpy.histogram', 'np.histogram', (['data'], {'bins': 'bins', 'density': '(False)'}), '(data, bins=bins, density=False)\n', (719, 751), True, 'i... |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from typing import Dict, List, Optional, Tuple
import torch
from torch import nn
import torch.nn.functional as F
from detectron2.config import configurable
from detectron2.data.detection_utils import convert_image_to_rgb
from detectro... | [
"detectron2.structures.ImageList.from_tensors",
"torch.jit.is_scripting",
"torch.cat",
"torch.randn",
"detectron2.utils.logger.log_first_n",
"detectron2.utils.visualizer.Visualizer",
"detectron2.utils.events.get_event_storage",
"torch.Tensor",
"torch.zeros",
"torch.split",
"torch.nn.Conv2d",
"... | [((1746, 1861), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.in_channels', '(self.out_channels - self.dv)', 'self.kernel_size'], {'stride': 'stride', 'padding': 'self.padding'}), '(self.in_channels, self.out_channels - self.dv, self.kernel_size,\n stride=stride, padding=self.padding)\n', (1755, 1861), False, 'from torch ... |
# Generated by Django 3.2.4 on 2021-06-30 13:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('distriblists', '0002_cop... | [
"django.db.models.ForeignKey",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField"
] | [((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((483, 720), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'l... |
# Generated by Django 2.2.6 on 2020-01-11 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_post_category'),
]
operations = [
migrations.AlterField(
model_name='post',
name='category',
... | [
"django.db.models.CharField"
] | [((328, 497), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('gadgets', 'Gadgets'), ('machine learning', 'Machine Learning'), (\n 'events', 'Events'), ('not', 'Not')]", 'default': '"""not"""', 'max_length': '(20)'}), "(choices=[('gadgets', 'Gadgets'), ('machine learning',\n 'Machine Learnin... |
import os
import configparser
config = configparser.ConfigParser()
config.read(os.environ['PARACHUTE_CONFIG_FILE'])
| [
"configparser.ConfigParser"
] | [((41, 68), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (66, 68), False, 'import configparser\n')] |
import os
print('1: {}\n1.14: {}\nTrue: {}\nFalse: {}\nHahA: {}\n'.format(type(1), type(1.14), type(True), type(False), type('HahA')))
os.system('pause')
| [
"os.system"
] | [((137, 155), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (146, 155), False, 'import os\n')] |
import sys
sys.path.append('.')
import asyncio
import time
import subprocess
import logging
logging.basicConfig(level=logging.DEBUG)
import pytest
from xwing.mailbox import init_node, start_node, spawn
from xwing.network.transport.socket.client import Client
FRONTEND_ADDRESS = '127.0.0.1:5555'
def setup_module(mo... | [
"sys.path.append",
"xwing.mailbox.spawn",
"subprocess.Popen",
"asyncio.get_event_loop",
"logging.basicConfig",
"asyncio.sleep",
"xwing.mailbox.init_node",
"time.sleep",
"xwing.mailbox.start_node",
"xwing.network.transport.socket.client.Client",
"pytest.mark.skip"
] | [((11, 31), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (26, 31), False, 'import sys\n'), ((93, 133), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (112, 133), False, 'import logging\n'), ((598, 616), 'pytest.mark.skip', 'pytest.mark.s... |
import sys
import numpy as np
file = sys.argv[-1]
with open(file) as f:
cnt = f.readlines()
count = []
distortion = []
calibration = []
linf = []
for line in cnt:
if line.startswith('Adversarial Example Found Successfully:'):
count.append(int(line.split(' ')[-2]))
distortion.append(eval(line.split(' ')[-6]))
e... | [
"numpy.median",
"numpy.min",
"numpy.mean",
"numpy.max"
] | [((493, 507), 'numpy.mean', 'np.mean', (['count'], {}), '(count)\n', (500, 507), True, 'import numpy as np\n'), ((509, 525), 'numpy.median', 'np.median', (['count'], {}), '(count)\n', (518, 525), True, 'import numpy as np\n'), ((527, 540), 'numpy.min', 'np.min', (['count'], {}), '(count)\n', (533, 540), True, 'import n... |
from django import forms
from django.contrib.auth.models import User
from captcha.fields import CaptchaField
from .models import *
class ProxyForm(forms.Form):
proxyvalue=forms.CharField(label='代理值',required=False)
class LoginForm(forms.Form):
username=forms.CharField(label='用户名',max_length=100,error_message... | [
"django.forms.Select",
"captcha.fields.CaptchaField",
"django.contrib.auth.models.User.objects.filter",
"django.forms.PasswordInput",
"django.forms.ValidationError",
"django.forms.CharField"
] | [((178, 222), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""代理值"""', 'required': '(False)'}), "(label='代理值', required=False)\n", (193, 222), False, 'from django import forms\n'), ((264, 352), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""用户名"""', 'max_length': '(100)', 'error_message... |
from test_runner import run_test
def sliding_window(string, char_set):
left, right, best_score = 0, 0, float('inf')
letter_map = {}
characters_encountered = 0
while right < len(string) or characters_encountered == len(char_set):
if characters_encountered != len(char_set):
curr_right = string[righ... | [
"test_runner.run_test"
] | [((831, 855), 'test_runner.run_test', 'run_test', (['sliding_window'], {}), '(sliding_window)\n', (839, 855), False, 'from test_runner import run_test\n')] |
import easycorrector.confusion_model.confusion_correct as confusion_correct
import easycorrector.ngram_model.ngram_correct as ngram_correct
import easycorrector.preprocess.preprocess as preprocess
import easycorrector.base_bert_model.base_bert_correct as base_bert_correct
import easycorrector.chinese_bert_model.chinese... | [
"easycorrector.preprocess.preprocess.preprocess",
"easycorrector.ngram_model.ngram_correct.correct",
"easycorrector.preprocess.cut_sentences.cut_sentence",
"collections.defaultdict",
"easycorrector.confusion_model.confusion_correct.correct",
"easycorrector.csc_pretrain_bert_model.csc_pretrain_bert_correct... | [((834, 861), 'easycorrector.preprocess.preprocess.preprocess', 'preprocess.preprocess', (['text'], {}), '(text)\n', (855, 861), True, 'import easycorrector.preprocess.preprocess as preprocess\n'), ((882, 908), 'easycorrector.preprocess.cut_sentences.cut_sentence', 'cut_sen.cut_sentence', (['text'], {}), '(text)\n', (9... |
from django.conf.urls import url
from ocfweb.api import hours
from ocfweb.api import lab
urlpatterns = [
url(r'^hours$', hours.get_hours_all, name='hours_all'),
url(r'^hours/today$', hours.get_hours_today, name='hours_today'),
url(r'^lab/desktops$', lab.desktop_usage, name='desktop_usage'),
]
| [
"django.conf.urls.url"
] | [((111, 164), 'django.conf.urls.url', 'url', (['"""^hours$"""', 'hours.get_hours_all'], {'name': '"""hours_all"""'}), "('^hours$', hours.get_hours_all, name='hours_all')\n", (114, 164), False, 'from django.conf.urls import url\n'), ((171, 234), 'django.conf.urls.url', 'url', (['"""^hours/today$"""', 'hours.get_hours_to... |
import time
from snake.utils import logger_levels
class Logger:
__log_level = logger_levels.NONE
@staticmethod
def set_log_level(level):
Logger.__log_level = level
@staticmethod
def log(level, sender, message):
if level >= Logger.__log_level:
print("[{}][{}][{}] - {}... | [
"time.ctime"
] | [((346, 358), 'time.ctime', 'time.ctime', ([], {}), '()\n', (356, 358), False, 'import time\n')] |
#
# (C) Copyright 2012 <NAME> <<EMAIL>>
# (C) Copyright 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope tha... | [
"urllib.urlencode",
"logging.getLogger",
"time.time"
] | [((1111, 1148), 'logging.getLogger', 'logging.getLogger', (['"""pyxmpp2.sasl.xfb"""'], {}), "('pyxmpp2.sasl.xfb')\n", (1128, 1148), False, 'import logging\n'), ((2346, 2374), 'urllib.urlencode', 'urllib.urlencode', (['out_params'], {}), '(out_params)\n', (2362, 2374), False, 'import time, urllib\n'), ((2278, 2289), 'ti... |
from typing import List, Any
from ply.lex import LexToken
from windyquery.ctx import Ctx
from windyquery.validator import ValidationError
from ._base import Base, StartInsertToken
TOKEN = 'INSERT'
class InsertToken(LexToken):
def __init__(self, value):
self.type = TOKEN
self.value = value
... | [
"windyquery.ctx.Ctx"
] | [((634, 659), 'windyquery.ctx.Ctx', 'Ctx', (['self.paramOffset', '[]'], {}), '(self.paramOffset, [])\n', (637, 659), False, 'from windyquery.ctx import Ctx\n')] |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: william
@contact: <EMAIL>
@site: http://www.xiaolewei.com
@file: catcher.py
@time: 12/04/2018 18:32
"""
from dc.core import db, config
import influxdb
class Catcher(object):
def __init__(self):
self._db = db.get_mysql_client(config.get('app.db.mysql'... | [
"dc.core.config.get",
"influxdb.InfluxDBClient"
] | [((337, 366), 'dc.core.config.get', 'config.get', (['"""app.db.influxdb"""'], {}), "('app.db.influxdb')\n", (347, 366), False, 'from dc.core import db, config\n'), ((392, 530), 'influxdb.InfluxDBClient', 'influxdb.InfluxDBClient', ([], {'host': "cfg['host']", 'port': "cfg['port']", 'username': "cfg['user']", 'password'... |
import numpy as np
import pytest
from artemis.general.nondeterminism_hunting import delete_vars, assert_variable_matches_between_runs, variable_matches_between_runs, \
reset_variable_tracker
def _runs_are_the_same(var_gen_1, var_gen_2, use_assert = False):
delete_vars(['_test_random_var_32r5477w32'])
for... | [
"artemis.general.nondeterminism_hunting.delete_vars",
"numpy.random.RandomState",
"artemis.general.nondeterminism_hunting.variable_matches_between_runs",
"pytest.raises",
"artemis.general.nondeterminism_hunting.reset_variable_tracker",
"artemis.general.nondeterminism_hunting.assert_variable_matches_betwee... | [((268, 312), 'artemis.general.nondeterminism_hunting.delete_vars', 'delete_vars', (["['_test_random_var_32r5477w32']"], {}), "(['_test_random_var_32r5477w32'])\n", (279, 312), False, 'from artemis.general.nondeterminism_hunting import delete_vars, assert_variable_matches_between_runs, variable_matches_between_runs, re... |
import os
import sys
dir1 = sys.argv[1]
dir2 = sys.argv[2]
def fn_matchingfile(inputfile,comparedir):
for dirName, subdirList, fileList in os.walk(comparedir):
# print('Found directory: %s' % dirName)
for fname in fileList:
if fname==inputfile:
with open('matchingfile.... | [
"os.walk",
"os.listdir"
] | [((469, 485), 'os.listdir', 'os.listdir', (['dir1'], {}), '(dir1)\n', (479, 485), False, 'import os\n'), ((146, 165), 'os.walk', 'os.walk', (['comparedir'], {}), '(comparedir)\n', (153, 165), False, 'import os\n')] |
# Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre a quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
import datetime
atual = datetime.date.today().year
maior = 0
menor = 0
for c in range( 0, 7):
ano = int(input('Digite o ano de nascimento: '))
if atual -... | [
"datetime.date.today"
] | [((183, 204), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (202, 204), False, 'import datetime\n')] |
import random
import string
# TODO: Method naming rule: verb
def random_digit_with_number(length_of_values: int=7) -> str:
choices = string.ascii_uppercase + string.digits + string.ascii_lowercase
random_value = ''.join(random.SystemRandom().choice(choices) for _ in range(length_of_values))
return random_... | [
"random.SystemRandom"
] | [((230, 251), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (249, 251), False, 'import random\n'), ((467, 488), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (486, 488), False, 'import random\n')] |
"""jia URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | [
"courses.views.CourseCatalog.as_view",
"courses.views.LessonRetrieve.as_view",
"courses.views.QuizCatalog.as_view",
"courses.views.CourseRetrieve.as_view",
"courses.views.QuizRetrieve.as_view",
"courses.views.SubLessonRetrieve.as_view",
"courses.views.SubLessonCatalog.as_view",
"courses.views.LessonCa... | [((868, 891), 'courses.views.LessonCatalog.as_view', 'LessonCatalog.as_view', ([], {}), '()\n', (889, 891), False, 'from courses.views import LessonCatalog, LessonRetrieve, SubLessonCatalog, SubLessonRetrieve, CourseCatalog, CourseRetrieve, QuizCatalog, QuizRetrieve\n'), ((949, 973), 'courses.views.LessonRetrieve.as_vi... |
import unittest
def _makeRootAndUser():
from Acquisition import Explicit
from Acquisition import Implicit
from AccessControl.rolemanager import RoleManager
class DummyContext(Implicit, RoleManager):
__roles__ = ('Manager',)
class DummyUser(Explicit):
def getRoles(self):
... | [
"zope.interface.verify.verifyClass",
"AccessControl.SecurityManagement.noSecurityManager",
"AccessControl.SecurityManagement.newSecurityManager",
"AccessControl.ImplPython.verifyAcquisitionContext",
"AccessControl.SecurityManagement.getSecurityManager"
] | [((1135, 1154), 'AccessControl.SecurityManagement.noSecurityManager', 'noSecurityManager', ([], {}), '()\n', (1152, 1154), False, 'from AccessControl.SecurityManagement import noSecurityManager\n'), ((1367, 1405), 'zope.interface.verify.verifyClass', 'verifyClass', (['IRoleManager', 'RoleManager'], {}), '(IRoleManager,... |
from __future__ import print_function
import time
from base import valDict, malicious
from sdk.actions import (
GetBlockHeight,
GetFrozenMap,
)
from sdk.cmd_call import (
KillNode,
)
from sdk.rpc_call import (
node_1,
)
def test_release():
print("Starting release test")
# checking if validat... | [
"sdk.cmd_call.KillNode",
"time.sleep",
"sdk.actions.GetFrozenMap",
"sdk.actions.GetBlockHeight"
] | [((349, 363), 'sdk.actions.GetFrozenMap', 'GetFrozenMap', ([], {}), '()\n', (361, 363), False, 'from sdk.actions import GetBlockHeight, GetFrozenMap\n'), ((433, 449), 'sdk.cmd_call.KillNode', 'KillNode', (['node_1'], {}), '(node_1)\n', (441, 449), False, 'from sdk.cmd_call import KillNode\n'), ((572, 588), 'sdk.actions... |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='flask-neomodel',
version='0.1',
description='Flask extension for OGM on neo4j python driver',
author="<NAME>",
author_email='<EMAIL>',
# url='',
license='MIT',
packages=['.'],
# package_data={
# main_package:... | [
"setuptools.setup"
] | [((55, 674), 'setuptools.setup', 'setup', ([], {'name': '"""flask-neomodel"""', 'version': '"""0.1"""', 'description': '"""Flask extension for OGM on neo4j python driver"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['.']", 'python_requires': '""">=3.4"""', 'instal... |
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | [
"adnc.model.utils.layer_norm",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"pytest.fixture",
"tensorflow.Session",
"tensorflow.constant",
"numpy.random.RandomState",
"numpy.random.randint"
] | [((751, 767), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (765, 767), False, 'import pytest\n'), ((864, 880), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (878, 880), False, 'import pytest\n'), ((837, 861), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (859, 861), True... |
from floodsystem.flood import stations_level_over_threshold, stations_highest_rel_level
from floodsystem.datafetcher import *
from floodsystem.plot import plot_water_level_with_fit
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.utils import sorted_by_key
from floodsystem.st... | [
"floodsystem.stationdata.build_station_list",
"floodsystem.flood.stations_level_over_threshold",
"floodsystem.stationdata.update_water_levels"
] | [((378, 398), 'floodsystem.stationdata.build_station_list', 'build_station_list', ([], {}), '()\n', (396, 398), False, 'from floodsystem.stationdata import build_station_list, update_water_levels\n'), ((403, 432), 'floodsystem.stationdata.update_water_levels', 'update_water_levels', (['stations'], {}), '(stations)\n', ... |
import socket
from pyadept.strutil import split_data
def create_server_socket(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket_pair = (host, port)
s.bind(socket_pair)
return s
def start_server(srv_socket, on_acc... | [
"pyadept.strutil.split_data",
"socket.socket",
"socket.recv",
"socket.sendall"
] | [((103, 152), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (116, 152), False, 'import socket\n'), ((721, 770), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (734, ... |
# -*- coding: utf-8 -*-
import time
import threading
import logging
from uuid import uuid1
from hashlib import md5
from django.core.cache import cache
from django.db import IntegrityError
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
class MiddlewareMixin(object):
pass
... | [
"statsd.StatsClient",
"django.core.cache.cache.set",
"time.time",
"uuid.uuid1",
"logging.getLogger"
] | [((427, 455), 'logging.getLogger', 'logging.getLogger', (['"""metrics"""'], {}), "('metrics')\n", (444, 455), False, 'import logging\n'), ((971, 1041), 'statsd.StatsClient', 'statsd.StatsClient', ([], {'host': 'conf.HOST', 'port': 'conf.PORT', 'prefix': 'conf.PREFIX'}), '(host=conf.HOST, port=conf.PORT, prefix=conf.PRE... |
#!/usr/bin/python
# Refactor by <NAME>
# This is refactor script from https://github.com/aruba/aruba-ansible-modules/blob/master/aruba_module_installer/aruba_module_installer.py
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from subprocess import check_output
from shutil import copytree, copyfile, ... | [
"argparse.ArgumentParser",
"os.path.isdir",
"subprocess.check_output",
"os.path.realpath",
"os.path.exists",
"shutil.copyfile",
"shutil.copytree"
] | [((1158, 1262), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': 'description', 'formatter_class': 'RawDescriptionHelpFormatter', 'epilog': 'epilog'}), '(description=description, formatter_class=\n RawDescriptionHelpFormatter, epilog=epilog)\n', (1172, 1262), False, 'from argparse import ArgumentPar... |