code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions used for data handling
"""
__author__ = "<NAME>, GIScience Research Group, Heidelberg University"
__email__ = "<EMAIL>"
import os
import yaml
from shapely.geometry import box
import numpy as np
import pandas as pd
import geopandas as gpd
import json
from nb_... | [
"os.path.exists",
"pandas.read_json",
"geopandas.read_file",
"os.path.join",
"yaml.load",
"nb_utils.utils.create_bbox",
"json.load",
"nb_utils.utils.reproject_to_utm",
"os.mkdir",
"pandas.DataFrame",
"pandas.concat",
"geopandas.GeoDataFrame"
] | [((3221, 3255), 'pandas.concat', 'pd.concat', (['loaded_tags_dfs'], {'axis': '(0)'}), '(loaded_tags_dfs, axis=0)\n', (3230, 3255), True, 'import pandas as pd\n'), ((3321, 3358), 'pandas.concat', 'pd.concat', (['loaded_context_dfs'], {'axis': '(0)'}), '(loaded_context_dfs, axis=0)\n', (3330, 3358), True, 'import pandas ... |
from warnings import warn
from tables.utilsextension import *
_warnmsg = ("utilsExtension is pending deprecation, import utilsextension instead. "
"You may use the pt2to3 tool to update your source code.")
warn(_warnmsg, DeprecationWarning, stacklevel=2)
| [
"warnings.warn"
] | [((224, 272), 'warnings.warn', 'warn', (['_warnmsg', 'DeprecationWarning'], {'stacklevel': '(2)'}), '(_warnmsg, DeprecationWarning, stacklevel=2)\n', (228, 272), False, 'from warnings import warn\n')] |
from functions import get_df, write_df
import geopy
from geopy import distance
"""
The function question3 takes in the latitude and longitude of potential distress locations,
and returns the nearest port with essential provisions such as water, fuel_oil and diesel.
"""
def question3(dataset_name, latitude, longitude)... | [
"geopy.distance.geodesic",
"functions.write_df",
"functions.get_df"
] | [((332, 340), 'functions.get_df', 'get_df', ([], {}), '()\n', (338, 340), False, 'from functions import get_df, write_df\n'), ((956, 1011), 'functions.write_df', 'write_df', (['answer3', 'dataset_name', '"""Table for Question 3"""'], {}), "(answer3, dataset_name, 'Table for Question 3')\n", (964, 1011), False, 'from fu... |
import pybullet as p
#p.connect(p.UDP,"192.168.86.100")
p.connect(p.SHARED_MEMORY)
p.resetSimulation()
objects = [p.loadURDF("plane.urdf", 0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,1.000000)]
objects = [p.loadURDF("samurai.urdf", 0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,1.000000)]
objects = [p... | [
"pybullet.resetJointState",
"pybullet.resetSimulation",
"pybullet.loadSDF",
"pybullet.connect",
"pybullet.createConstraint",
"pybullet.getNumJoints",
"pybullet.setGravity",
"pybullet.disconnect",
"pybullet.stepSimulation",
"pybullet.resetBasePositionAndOrientation",
"pybullet.loadURDF",
"pybul... | [((56, 82), 'pybullet.connect', 'p.connect', (['p.SHARED_MEMORY'], {}), '(p.SHARED_MEMORY)\n', (65, 82), True, 'import pybullet as p\n'), ((83, 102), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (100, 102), True, 'import pybullet as p\n'), ((681, 789), 'pybullet.createConstraint', 'p.createConstra... |
from __future__ import annotations
from typing import Optional, Dict, List, Union, Type, TYPE_CHECKING
from datetime import date, datetime
import pandas as pd
import numpy as np
import re
import locale
try:
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
except locale.Error:
# Readthedocs has a problem, but dif... | [
"pandas.isnull",
"locale.atof",
"locale.setlocale",
"pandas.read_csv",
"re.compile",
"datetime.datetime.strptime",
"pandas.StringDtype",
"typing.List",
"pandas.Index",
"pandas.read_excel",
"pandas.DataFrame",
"re.sub",
"pandas.Timestamp",
"pandas.concat",
"datetime.date.isoformat",
"pa... | [((212, 258), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '"""en_US.UTF-8"""'], {}), "(locale.LC_ALL, 'en_US.UTF-8')\n", (228, 258), False, 'import locale\n'), ((5556, 5573), 'typing.List', 'List', (['ColumnModel'], {}), '(ColumnModel)\n', (5560, 5573), False, 'from typing import Optional, Dict, List, Un... |
from __future__ import print_function
import json
from os.path import join, dirname
from watson_developer_cloud import ToneAnalyzerV3
from watson_developer_cloud.tone_analyzer_v3 import ToneInput
from pprint import pprint
# If service instance provides API key authentication
# service = ToneAnalyzerV3(
# ## url i... | [
"watson_developer_cloud.ToneAnalyzerV3",
"watson_developer_cloud.tone_analyzer_v3.ToneInput",
"pprint.pprint"
] | [((537, 662), 'watson_developer_cloud.ToneAnalyzerV3', 'ToneAnalyzerV3', ([], {'username': '"""f0ec47cc-5191-4421-8fca-<PASSWORD>917e1<PASSWORD>"""', 'password': '"""<PASSWORD>"""', 'version': '"""2017-09-21"""'}), "(username='f0ec47cc-5191-4421-8fca-<PASSWORD>917e1<PASSWORD>',\n password='<PASSWORD>', version='2017... |
import os
# Restrict the script to run on CPU
os.environ ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
# Import Keras Tensoflow Backend
# from keras import backend as K
import tensorflow as tf
# Configure it to use only specific CPU Cores
config = tf.ConfigProto(intra_op_parallelism_thre... | [
"tensorflow.local_variables_initializer",
"numpy.diagonal",
"os.path.exists",
"os.makedirs",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"IEOMAP_dataset_AC.dataset",
"os.path.dirname",
"IEOMAP_dataset_AC.IeomapSentenceItera... | [((280, 425), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'intra_op_parallelism_threads': '(4)', 'inter_op_parallelism_threads': '(4)', 'device_count': "{'CPU': 1, 'GPU': 0}", 'allow_soft_placement': '(True)'}), "(intra_op_parallelism_threads=4, inter_op_parallelism_threads\n =4, device_count={'CPU': 1, 'GPU':... |
import torch
DEVICE = 'cuda'
import math
import torch.optim as optim
from model import *
import os
import copy, gzip, pickle, time
data_dir = './drive/MyDrive/music_classification/Data'
classes = os.listdir(data_dir+'/images_original')
def fit(model, train_loader, train_len, optimizer, criterion):
model.train()
... | [
"os.listdir",
"math.ceil",
"pickle.dump",
"gzip.open",
"torch.max",
"pickle.load",
"torch.optim.lr_scheduler.StepLR",
"torch.no_grad",
"time.time"
] | [((196, 237), 'os.listdir', 'os.listdir', (["(data_dir + '/images_original')"], {}), "(data_dir + '/images_original')\n", (206, 237), False, 'import os\n'), ((376, 409), 'math.ceil', 'math.ceil', (['(train_len / batch_size)'], {}), '(train_len / batch_size)\n', (385, 409), False, 'import math\n'), ((4727, 4738), 'time.... |
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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 app... | [
"projectq.types.WeakQubitRef",
"math.acos",
"projectq.MainEngine",
"projectq.cengines.DummyEngine",
"math.sqrt",
"projectq.ops.All",
"pytest.fixture",
"projectq.libs.math.SubConstantModN",
"projectq.libs.math.AddConstantModN",
"projectq.ops.Rx",
"projectq.libs.math.SubConstant",
"numpy.eye",
... | [((2688, 2734), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['mapper', 'no_mapper']"}), "(params=['mapper', 'no_mapper'])\n", (2702, 2734), False, 'import pytest\n'), ((18744, 18847), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate_classes"""', '[(Ry, UniformlyControlledRy), (Rz, UniformlyCont... |
# from wx.lib.pubsub import pub
from pubsub import pub
import serial
import threading
import queue
import time
class ComReaderThread(threading.Thread):
'''
Creates a thread that continously reads from the serial connection
Puts result as a tuple (timestamp, data) in a queue
'''
def __init__(self... | [
"threading.Thread.__init__",
"pubsub.pub.sendMessage",
"time.sleep",
"threading.Event",
"threading.Thread.join",
"time.time"
] | [((347, 378), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (372, 378), False, 'import threading\n'), ((459, 476), 'threading.Event', 'threading.Event', ([], {}), '()\n', (474, 476), False, 'import threading\n'), ((1656, 1692), 'threading.Thread.join', 'threading.Thread.join', ([... |
from unittest.mock import patch
import pytest
from just_bin_it.endpoints.sources import HistogramSource
from tests.doubles.consumer import StubConsumer
TEST_MESSAGE = b"this is a byte message"
INVALID_FB = b"this is an invalid fb message"
class TestHistogramSource:
@pytest.fixture(autouse=True)
def prepare... | [
"tests.doubles.consumer.StubConsumer",
"pytest.raises",
"pytest.fixture",
"just_bin_it.endpoints.sources.HistogramSource",
"unittest.mock.patch"
] | [((276, 304), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (290, 304), False, 'import pytest\n'), ((738, 825), 'unittest.mock.patch', 'patch', (['"""just_bin_it.endpoints.sources.deserialise_hs00"""'], {'return_value': 'TEST_MESSAGE'}), "('just_bin_it.endpoints.sources.deserialis... |
#!/usr/bin/env python
"""
Copyright 2010-2019 University Of Southern California
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by appli... | [
"math.ceil",
"bband_utils.runprog",
"os.path.join",
"os.getcwd",
"os.chdir",
"os.path.basename",
"bband_utils.mkdirs",
"plot_srf.run",
"install_cfg.InstallCfg.getInstance",
"irikura_gen_srf_cfg.IrikuraGenSrfCfg"
] | [((1889, 1913), 'install_cfg.InstallCfg.getInstance', 'InstallCfg.getInstance', ([], {}), '()\n', (1911, 1913), False, 'from install_cfg import InstallCfg\n'), ((2274, 2311), 'os.path.join', 'os.path.join', (['a_outdir', '"""param_files"""'], {}), "(a_outdir, 'param_files')\n", (2286, 2311), False, 'import os\n'), ((23... |
"""test_models.py: runs tests on the models for digit."""
import pytest
from core.models import (Grade,
Subject,
Question,
Comment,
Option,
Topic,
Block,
... | [
"core.models.Option.objects.all",
"core.models.Topic.objects.all",
"core.models.Question.objects.filter",
"core.models.Block.objects.all",
"core.models.Question.objects.all",
"core.models.Grade.objects.create",
"core.models.Block.objects.filter",
"core.models.Topic.objects.create",
"core.models.Opti... | [((638, 665), 'core.models.Grade', 'Grade', ([], {'name': '"""Grade Example"""'}), "(name='Grade Example')\n", (643, 665), False, 'from core.models import Grade, Subject, Question, Comment, Option, Topic, Block, Syllabus, StateException\n'), ((715, 757), 'core.models.Subject', 'Subject', ([], {'name': '"""addition"""',... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader imp... | [
"django.shortcuts.render",
"django.contrib.auth.authenticate",
"django.contrib.messages.error",
"django.contrib.auth.login",
"django.shortcuts.redirect",
"django.template.loader.render_to_string",
"django.contrib.auth.decorators.login_required",
"django.contrib.messages.success",
"django.core.mail.E... | [((1835, 1867), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""home"""'}), "(login_url='home')\n", (1849, 1867), False, 'from django.contrib.auth.decorators import login_required\n'), ((2151, 2183), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'logi... |
import socket, datetime, os
from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal
from direct.distributed.DistributedObject import DistributedObject
from toontown.toonbase import ToontownGlobals
from toontown.uberdog import InGameNewsResponses
class DistributedInGameNewsMgr(DistributedObject):... | [
"direct.distributed.DistributedObject.DistributedObject.disable",
"direct.distributed.DistributedObject.DistributedObject.generate",
"direct.distributed.DistributedObject.DistributedObject.delete",
"direct.distributed.DistributedObject.DistributedObject.__init__"
] | [((434, 470), 'direct.distributed.DistributedObject.DistributedObject.__init__', 'DistributedObject.__init__', (['self', 'cr'], {}), '(self, cr)\n', (460, 470), False, 'from direct.distributed.DistributedObject import DistributedObject\n'), ((539, 569), 'direct.distributed.DistributedObject.DistributedObject.delete', '... |
#!/usr/bin/env python
# coding=utf-8
# vim:ts=4:sts=4:sw=4:et
#
# Author: <NAME>
# Date: 2017-11-24 21:10:35 +0100 (Fri, 24 Nov 2017)
#
# https://github.com/harisekhon/nagios-plugins
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn
#... | [
"harisekhon.utils.support_msg_api",
"traceback.format_exc",
"os.path.join",
"os.path.dirname",
"harisekhon.utils.validate_chars",
"sys.exit",
"sys.path.append"
] | [((1187, 1216), 'os.path.join', 'os.path.join', (['srcdir', '"""pylib"""'], {}), "(srcdir, 'pylib')\n", (1199, 1216), False, 'import os\n'), ((1217, 1240), 'sys.path.append', 'sys.path.append', (['libdir'], {}), '(libdir)\n', (1232, 1240), False, 'import sys\n'), ((1151, 1176), 'os.path.dirname', 'os.path.dirname', (['... |
from django.http import HttpResponse
from django.core.mail import send_mail
import json
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from GestiRED.models import User
from GestiRED.models import QualityControl, Phase, Resource, ResourceType,PhaseType
from django.core import se... | [
"json.loads",
"GestiRED.models.Resource.objects.filter",
"django.core.mail.send_mail",
"django.http.HttpResponse",
"json.dumps",
"GestiRED.models.QualityControl.objects.get",
"django.db.models.Q"
] | [((420, 451), 'django.http.HttpResponse', 'HttpResponse', (['"""GestiRED app UP"""'], {}), "('GestiRED app UP')\n", (432, 451), False, 'from django.http import HttpResponse\n'), ((2333, 2387), 'django.http.HttpResponse', 'HttpResponse', (['qs_json'], {'content_type': '"""application/json"""'}), "(qs_json, content_type=... |
from dataclasses import dataclass, field
from datetime import date, datetime, time, timezone
from pathlib import Path
from typing import Any, Dict, Optional, Union
import ciso8601
import pytest
from mashumaro import DataClassDictMixin
from mashumaro.exceptions import UnserializableField
from mashumaro.types import Se... | [
"datetime.datetime",
"datetime.time",
"ciso8601.parse_datetime",
"pathlib.Path",
"pytest.raises",
"datetime.date",
"datetime.datetime.fromisoformat",
"ciso8601.parse_datetime_as_naive",
"dataclasses.field"
] | [((562, 605), 'dataclasses.field', 'field', ([], {'metadata': "{'deserialize': 'ciso8601'}"}), "(metadata={'deserialize': 'ciso8601'})\n", (567, 605), False, 'from dataclasses import dataclass, field\n'), ((895, 938), 'dataclasses.field', 'field', ([], {'metadata': "{'deserialize': 'ciso8601'}"}), "(metadata={'deserial... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | [
"tensorflow.python.framework.ops.RegisterGradient",
"tensorflow.python.ops.gen_list_ops.tensor_list_push_back",
"tensorflow.python.ops.gen_list_ops.tensor_list_concat",
"tensorflow.python.ops.gen_list_ops.tensor_list_get_item",
"tensorflow.python.ops.gen_list_ops.tensor_list_gather",
"tensorflow.python.fr... | [((1248, 1294), 'tensorflow.python.framework.ops.NotDifferentiable', 'ops.NotDifferentiable', (['"""TensorListConcatLists"""'], {}), "('TensorListConcatLists')\n", (1269, 1294), False, 'from tensorflow.python.framework import ops\n'), ((1295, 1342), 'tensorflow.python.framework.ops.NotDifferentiable', 'ops.NotDifferent... |
import ast
import re
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import astunparse
from tests.common import AstunparseCommonTestCase
class DumpTestCase(AstunparseCommonTestCase, unittest.TestCase):
def assertASTEqual(self, dump1, dump2):
# undo the ... | [
"re.sub",
"ast.dump",
"astunparse.dump"
] | [((352, 393), 're.sub', 're.sub', (['"""(?<=[\\\\(\\\\[])\\\\n\\\\s+"""', '""""""', 'dump1'], {}), "('(?<=[\\\\(\\\\[])\\\\n\\\\s+', '', dump1)\n", (358, 393), False, 'import re\n'), ((407, 436), 're.sub', 're.sub', (['"""\\\\n\\\\s+"""', '""" """', 'dump1'], {}), "('\\\\n\\\\s+', ' ', dump1)\n", (413, 436), False, 'im... |
from django.urls import include, path
from .views import home, bike
urlpatterns = [
path("", home),
path("bike/<int:number>", bike)
] | [
"django.urls.path"
] | [((89, 103), 'django.urls.path', 'path', (['""""""', 'home'], {}), "('', home)\n", (93, 103), False, 'from django.urls import include, path\n'), ((109, 140), 'django.urls.path', 'path', (['"""bike/<int:number>"""', 'bike'], {}), "('bike/<int:number>', bike)\n", (113, 140), False, 'from django.urls import include, path\... |
"""
Remove Fragments not in Knowledgebase
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2019, Hong Kong University of Science and Technology"
__license__ = "3-clause BSD"
from argparse import ArgumentParser
import numpy as np
import pickle
parser = ArgumentParser(description="Build Files... | [
"argparse.ArgumentParser",
"numpy.where",
"numpy.empty",
"numpy.full",
"numpy.loadtxt"
] | [((281, 322), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Build Files"""'}), "(description='Build Files')\n", (295, 322), False, 'from argparse import ArgumentParser\n'), ((572, 706), 'numpy.loadtxt', 'np.loadtxt', (["('../%s/%s/%s.Homogenised.boundfrags_zeros.txt' % (args.datadir, args.\n ... |
"""Tests for core.billing.
Run this test from the project root
$ nosetests core.tests.billing_tests
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of ... | [
"core.billing.get_call_cost",
"core.billing.get_prefix_from_number",
"core.billing.get_sms_cost",
"core.billing.process_prices",
"core.billing.round_up_to_nearest_100",
"core.config_database.ConfigDB",
"core.billing.round_to_billable_unit",
"random.randint"
] | [((1081, 1107), 'core.config_database.ConfigDB', 'config_database.ConfigDB', ([], {}), '()\n', (1105, 1107), False, 'from core import config_database\n'), ((3018, 3059), 'core.billing.process_prices', 'process_prices', (['price_data', 'cls.config_db'], {}), '(price_data, cls.config_db)\n', (3032, 3059), False, 'from co... |
from django import forms
from django.forms import ModelForm
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from .choices import ActionChoice
from .choices import StatusApproval
from .models import GreencheckIp
from .models import GreencheckIpApprove
from .models impor... | [
"django.forms.HiddenInput",
"django.contrib.auth.get_user_model",
"django.core.exceptions.ValidationError"
] | [((366, 382), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (380, 382), False, 'from django.contrib.auth import get_user_model\n'), ((2116, 2135), 'django.forms.HiddenInput', 'forms.HiddenInput', ([], {}), '()\n', (2133, 2135), False, 'from django import forms\n'), ((2711, 2730), 'django.for... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
from tld import get_tld
__author__ = "<NAME>"
def get_domain(url):
'''
获取url中的全域名
:param url:
:return:
'''
res = get_tld(url, as_object=True)
return "{}.{}".format(res.subdomain, res.tld) | [
"tld.get_tld"
] | [((182, 210), 'tld.get_tld', 'get_tld', (['url'], {'as_object': '(True)'}), '(url, as_object=True)\n', (189, 210), False, 'from tld import get_tld\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: BSD-3-Clause
# Copyright © 2017-2019, GoodData Corporation. All rights reserved.
"""
FreeIPA Manager - entity module
Object representations of the entities configured in FreeIPA.
"""
import os
import re
import voluptuous
import yaml
from abc imp... | [
"yaml.dump",
"command.Command",
"re.match",
"voluptuous.Schema",
"os.path.split",
"os.unlink",
"errors.IntegrityError",
"errors.ConfigError"
] | [((10197, 10241), 'voluptuous.Schema', 'voluptuous.Schema', (['schemas.schema_hostgroups'], {}), '(schemas.schema_hostgroups)\n', (10214, 10241), False, 'import voluptuous\n'), ((10484, 10528), 'voluptuous.Schema', 'voluptuous.Schema', (['schemas.schema_usergroups'], {}), '(schemas.schema_usergroups)\n', (10501, 10528)... |
# pylint: skip-file
from athena_glue_service_logs.catalog_manager import BaseCatalogManager
def test_class_init(mocker):
mocker.patch.multiple(BaseCatalogManager, __abstractmethods__=set())
base_catalog = BaseCatalogManager('us-west-2', 'dbname', 'tablename', 's3://somewhere')
assert base_catalog.databas... | [
"athena_glue_service_logs.catalog_manager.BaseCatalogManager.create_table.assert_called_once",
"athena_glue_service_logs.catalog_manager.BaseCatalogManager.create_partitions.assert_called_once_with",
"athena_glue_service_logs.catalog_manager.BaseCatalogManager"
] | [((216, 288), 'athena_glue_service_logs.catalog_manager.BaseCatalogManager', 'BaseCatalogManager', (['"""us-west-2"""', '"""dbname"""', '"""tablename"""', '"""s3://somewhere"""'], {}), "('us-west-2', 'dbname', 'tablename', 's3://somewhere')\n", (234, 288), False, 'from athena_glue_service_logs.catalog_manager import Ba... |
from twisted.internet import reactor
reactor.listenTCP(8789, factory)
reactor.run() | [
"twisted.internet.reactor.listenTCP",
"twisted.internet.reactor.run"
] | [((37, 69), 'twisted.internet.reactor.listenTCP', 'reactor.listenTCP', (['(8789)', 'factory'], {}), '(8789, factory)\n', (54, 69), False, 'from twisted.internet import reactor\n'), ((70, 83), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (81, 83), False, 'from twisted.internet import reactor\n')] |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def visualize(dataframe, balltype):
df = dataframe
#Filter by balltype
res = df[df["pitch_type"] == balltype]
#Group by results
groups = res.groupby("description")
for name, group in groups:
if name ==... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"pandas.DataFrame",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((1524, 1545), 'pandas.read_csv', 'pd.read_csv', (['file_src'], {}), '(file_src)\n', (1535, 1545), True, 'import pandas as pd\n'), ((1552, 1569), 'pandas.DataFrame', 'pd.DataFrame', (['raw'], {}), '(raw)\n', (1564, 1569), True, 'import pandas as pd\n'), ((665, 674), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n'... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 25 13:17:49 2019
@author: Toonw
"""
import numpy as np
def vlen(a):
return (a[0]**2 + a[1]**2)**0.5
def add(v1,v2):
return (v1[0]+v2[0], v1[1]+v2[1])
def sub(v1,v2):
return (v1[0]-v2[0], v1[1]-v2[1])
def unit_vector(v):
vu = v / np.linalg.norm(v)
... | [
"numpy.dot",
"numpy.linalg.norm"
] | [((300, 317), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (314, 317), True, 'import numpy as np\n'), ((394, 408), 'numpy.dot', 'np.dot', (['v1', 'v2'], {}), '(v1, v2)\n', (400, 408), True, 'import numpy as np\n')] |
import unittest
#import tempfile
try:
from StringIO import StringIO
except:
from io import StringIO
import pyx12.error_handler
from pyx12.errors import EngineError # , X12PathError
import pyx12.x12context
import pyx12.params
from pyx12.test.x12testdata import datafiles
class X12fileTestCase(unittest.TestCas... | [
"io.StringIO"
] | [((482, 498), 'io.StringIO', 'StringIO', (['x12str'], {}), '(x12str)\n', (490, 498), False, 'from io import StringIO\n'), ((538, 548), 'io.StringIO', 'StringIO', ([], {}), '()\n', (546, 548), False, 'from io import StringIO\n'), ((609, 643), 'io.StringIO', 'StringIO', (['x12str'], {'encoding': '"""ascii"""'}), "(x12str... |
#!/usr/bin/env python
import os
import json
import tornado.ioloop
import tornado.log
import tornado.web
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
import jwt
import requests
API_KEY = os.environ.get('OPEN_WEATHER_MAP_KEY', None)
PROJECT_ID = os.environ.get('PRO... | [
"jwt.decode",
"google.auth.transport.requests.Request",
"json.dumps",
"os.environ.get",
"requests.get",
"google.oauth2.id_token.verify_oauth2_token"
] | [((243, 287), 'os.environ.get', 'os.environ.get', (['"""OPEN_WEATHER_MAP_KEY"""', 'None'], {}), "('OPEN_WEATHER_MAP_KEY', None)\n", (257, 287), False, 'import os\n'), ((301, 335), 'os.environ.get', 'os.environ.get', (['"""PROJECT_ID"""', 'None'], {}), "('PROJECT_ID', None)\n", (315, 335), False, 'import os\n'), ((1119,... |
from typing import Iterator, NamedTuple, Tuple
from cached_property import cached_property
from cv2 import Rodrigues
from pyquaternion import Quaternion
class Coordinates(NamedTuple):
"""
:param float x: X coordinate
:param float y: Y coordinate
"""
x: float
y: float
class ThreeDCoordinate... | [
"pyquaternion.Quaternion",
"cv2.Rodrigues"
] | [((1153, 1179), 'cv2.Rodrigues', 'Rodrigues', (['(e_x, e_y, e_z)'], {}), '((e_x, e_y, e_z))\n', (1162, 1179), False, 'from cv2 import Rodrigues\n'), ((1207, 1241), 'pyquaternion.Quaternion', 'Quaternion', ([], {'matrix': 'rotation_matrix'}), '(matrix=rotation_matrix)\n', (1217, 1241), False, 'from pyquaternion import Q... |
import sqlite3
import os
import datetime
__all__ = ['DMARCStorage', 'totimestamp']
def totimestamp(datetime_object):
if datetime_object.utcoffset() is not None:
utc_naive = datetime_object.replace(tzinfo=None) - datetime_object.utcoffset()
else:
utc_naive = datetime_object
return (utc_nai... | [
"datetime.datetime",
"os.path.exists",
"sqlite3.connect",
"os.makedirs",
"os.path.join"
] | [((562, 613), 'os.path.join', 'os.path.join', (['database_directory', 'database_filename'], {}), '(database_directory, database_filename)\n', (574, 613), False, 'import os\n'), ((730, 760), 'sqlite3.connect', 'sqlite3.connect', (['database_path'], {}), '(database_path)\n', (745, 760), False, 'import sqlite3\n'), ((629,... |
from setuptools import setup, find_packages
setup(
name="sumologic-sdk",
version="0.1.9",
packages=find_packages(),
install_requires=['requests>=2.2.1'],
# PyPI metadata
author="<NAME>, <NAME>",
author_email="<EMAIL>, <EMAIL>",
description="Sumo Logic Python SDK",
license="PSF",
... | [
"setuptools.find_packages"
] | [((112, 127), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (125, 127), False, 'from setuptools import setup, find_packages\n')] |
import copy
from django.conf import settings
from django.test.utils import override_settings
from rest_framework import status, test
class PermissionsTest(test.APITransactionTestCase):
"""
Abstract class for permissions tests.
Methods `get_urls_configs`, `get_users_with_permission`,
`get_users_witho... | [
"django.test.utils.override_settings",
"copy.deepcopy"
] | [((5168, 5203), 'copy.deepcopy', 'copy.deepcopy', (['settings.WALDUR_CORE'], {}), '(settings.WALDUR_CORE)\n', (5181, 5203), False, 'import copy\n'), ((5250, 5296), 'django.test.utils.override_settings', 'override_settings', ([], {'WALDUR_CORE': 'waldur_settings'}), '(WALDUR_CORE=waldur_settings)\n', (5267, 5296), False... |
import io
import time
import todoist
def test_stats_get(api_endpoint, api_token):
api = todoist.api.TodoistAPI(api_token, api_endpoint)
response = api.completed.get_stats()
assert 'days_items' in response
assert 'week_items' in response
assert 'karma_trend' in response
assert 'karma_last_upda... | [
"time.strftime",
"io.open",
"time.gmtime",
"time.time",
"todoist.api.TodoistAPI"
] | [((95, 142), 'todoist.api.TodoistAPI', 'todoist.api.TodoistAPI', (['api_token', 'api_endpoint'], {}), '(api_token, api_endpoint)\n', (117, 142), False, 'import todoist\n'), ((395, 442), 'todoist.api.TodoistAPI', 'todoist.api.TodoistAPI', (['api_token', 'api_endpoint'], {}), '(api_token, api_endpoint)\n', (417, 442), Fa... |
from setuptools import setup
import iotio
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="iot.io",
version=iotio.__version__,
packages=["iotio"],
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
description="A management API for connecting and managi... | [
"setuptools.setup"
] | [((112, 860), 'setuptools.setup', 'setup', ([], {'name': '"""iot.io"""', 'version': 'iotio.__version__', 'packages': "['iotio']", 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'description': '"""A management API for connecting and managing Clients via websocket connections."""', 'lo... |
import numpy as np
import tensorflow as tf
import os
from scipy.io import savemat
from scipy.io import loadmat
from scipy.misc import imread
from scipy.misc import imsave
from alexnet_face_classifier import *
import matplotlib.pyplot as plt
plt.switch_backend('agg')
class backprop_graph:
def __init__(self, num_... | [
"tensorflow.tensordot",
"tensorflow.placeholder",
"matplotlib.pyplot.switch_backend",
"numpy.max",
"tensorflow.gradients",
"tensorflow.nn.softmax",
"numpy.expand_dims",
"tensorflow.log"
] | [((243, 268), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (261, 268), True, 'import matplotlib.pyplot as plt\n'), ((1967, 1991), 'numpy.expand_dims', 'np.expand_dims', (['image', '(0)'], {}), '(image, 0)\n', (1981, 1991), True, 'import numpy as np\n'), ((2006, 2032), 'num... |
import pytest
from nesta.packages.misc_utils.guess_sql_type import guess_sql_type
@pytest.fixture
def int_data():
return [1,2,4,False]
@pytest.fixture
def text_data():
return ['a', True, 2,
('A very long sentence A very long sentence A '
'very long sentence A very long sentence'), 'd... | [
"nesta.packages.misc_utils.guess_sql_type.guess_sql_type"
] | [((502, 526), 'nesta.packages.misc_utils.guess_sql_type.guess_sql_type', 'guess_sql_type', (['int_data'], {}), '(int_data)\n', (516, 526), False, 'from nesta.packages.misc_utils.guess_sql_type import guess_sql_type\n'), ((595, 621), 'nesta.packages.misc_utils.guess_sql_type.guess_sql_type', 'guess_sql_type', (['float_d... |
# -*- coding: utf-8 -*-
'''活动管理接口'''
from flask import request
from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User
from model.role import identity
from flask_jwt_extended import (fresh_jwt_required)
def demand_activity_add(activity_id, data):
'''添加活动需求'''
for d... | [
"model.db.ActivityMember.delete",
"model.db.ActivityMember.create",
"model.db.Demand.find",
"model.db.Activity.update",
"model.db.database.atomic",
"model.db.Activity.findOne",
"model.role.identity.check_permission",
"model.db.ProjectMember.get",
"model.db.Demand.get",
"model.db.ActivityBase.creat... | [((1287, 1330), 'model.role.identity.check_permission', 'identity.check_permission', (['"""create"""', '"""task"""'], {}), "('create', 'task')\n", (1312, 1330), False, 'from model.role import identity\n'), ((2114, 2157), 'model.role.identity.check_permission', 'identity.check_permission', (['"""update"""', '"""task"""'... |
import tensorflow as tf
from tensorflow.python.training.session_run_hook import SessionRunArgs
# Define data loaders #####################################
# See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca
class IteratorInitializerHook(tf.train.SessionRunHook):
"""Hook to initialise data... | [
"tensorflow.python.training.session_run_hook.SessionRunArgs"
] | [((1490, 1514), 'tensorflow.python.training.session_run_hook.SessionRunArgs', 'SessionRunArgs', (['requests'], {}), '(requests)\n', (1504, 1514), False, 'from tensorflow.python.training.session_run_hook import SessionRunArgs\n'), ((2691, 2715), 'tensorflow.python.training.session_run_hook.SessionRunArgs', 'SessionRunAr... |
'''
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py
'''
import os
import re
impo... | [
"torch.split",
"random.shuffle",
"subprocess.Popen",
"torch.stack",
"torch.tensor",
"re.sub",
"torch.cat",
"re.search"
] | [((5585, 5605), 'random.shuffle', 'random.shuffle', (['data'], {}), '(data)\n', (5599, 5605), False, 'import random\n'), ((2451, 2480), 'torch.split', 'torch.split', (['output', '(1)'], {'dim': '(0)'}), '(output, 1, dim=0)\n', (2462, 2480), False, 'import torch\n'), ((2952, 2986), 'torch.cat', 'torch.cat', (['combined_... |
#!/usr/bin/env python3
from typing import Dict, AnyStr
from pathlib import Path
from ontopy import get_ontology
import dlite
from dlite.mappings import make_instance
# Setup dlite paths
thisdir = Path(__file__).parent.absolute()
rootdir = thisdir.parent.parent
workflow1dir = rootdir / '1-simple-workflow'
entitiesdir... | [
"dlite.mappings.make_instance",
"dlite.storage_path.append",
"ontopy.get_ontology",
"pathlib.Path",
"dlite.Collection",
"dlite.get_instance"
] | [((391, 441), 'dlite.storage_path.append', 'dlite.storage_path.append', (['f"""{entitiesdir}/*.json"""'], {}), "(f'{entitiesdir}/*.json')\n", (416, 441), False, 'import dlite\n'), ((1602, 1660), 'dlite.get_instance', 'dlite.get_instance', (['"""http://onto-ns.com/meta/0.1/Molecule"""'], {}), "('http://onto-ns.com/meta/... |
"""
Period benchmarks that rely only on tslibs. See benchmarks.period for
Period benchmarks that rely on other parts fo pandas.
"""
from pandas import Period
from pandas.tseries.frequencies import to_offset
class PeriodProperties:
params = (
["M", "min"],
[
"year",
"mont... | [
"pandas.tseries.frequencies.to_offset",
"pandas.Period"
] | [((731, 762), 'pandas.Period', 'Period', (['"""2012-06-01"""'], {'freq': 'freq'}), "('2012-06-01', freq=freq)\n", (737, 762), False, 'from pandas import Period\n'), ((966, 997), 'pandas.Period', 'Period', (['"""2012-06-01"""'], {'freq': 'freq'}), "('2012-06-01', freq=freq)\n", (972, 997), False, 'from pandas import Per... |
# -*- coding: utf-8 -
#
# This file is part of couchdbkit released under the MIT license.
# See the NOTICE for more information.
import os
import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'):
raise SystemExit("couchdbkit requires Python 2.5 or later.")
from setuptools import ... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((1191, 1223), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (1204, 1223), False, 'from setuptools import setup, find_packages\n'), ((540, 565), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (555, 565), False, 'import os\n')] |
""" $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... | [
"nn_dataflow.core.Network",
"nn_dataflow.core.Layer",
"nn_dataflow.core.ConvLayer",
"nn_dataflow.core.InputLayer",
"nn_dataflow.core.PoolingLayer",
"nn_dataflow.core.EltwiseLayer",
"nn_dataflow.core.FCLayer"
] | [((987, 1006), 'nn_dataflow.core.Network', 'Network', (['"""test_net"""'], {}), "('test_net')\n", (994, 1006), False, 'from nn_dataflow.core import Network\n'), ((1327, 1346), 'nn_dataflow.core.Network', 'Network', (['"""test_net"""'], {}), "('test_net')\n", (1334, 1346), False, 'from nn_dataflow.core import Network\n'... |
import torch
import torch.nn.functional as F
import pandas as pd
import numpy as np
from torch_geometric.data import Data
from torch_geometric.nn import GCNConv, PairNorm
from torch_geometric.utils.undirected import to_undirected
import random
import matplotlib.pyplot as plt
data_name = 'citeseer' # 'cora' or 'ci... | [
"torch.unique",
"matplotlib.pyplot.savefig",
"random.shuffle",
"pandas.DataFrame",
"torch.nn.LeakyReLU",
"torch_geometric.nn.GCNConv",
"torch_geometric.nn.PairNorm",
"torch.tensor",
"torch.arange",
"pandas.read_table",
"torch_geometric.utils.undirected.to_undirected",
"torch.nn.functional.cros... | [((466, 532), 'pandas.read_table', 'pd.read_table', (['data_content_path'], {'header': 'None', 'dtype': '{(0): np.str}'}), '(data_content_path, header=None, dtype={(0): np.str})\n', (479, 532), True, 'import pandas as pd\n'), ((541, 597), 'pandas.read_table', 'pd.read_table', (['data_edge_path'], {'header': 'None', 'dt... |
import datetime
import json
from django.conf import settings
from django.http import Http404
from django.utils import timezone
from django.views import generic
from .models import Event, FlatPage, News
class HomeView(generic.ListView):
"""
View for the first page called 'Home'.
"""
context_object_na... | [
"django.utils.timezone.now",
"datetime.timedelta",
"json.dumps"
] | [((2115, 2137), 'json.dumps', 'json.dumps', (['event_list'], {}), '(event_list)\n', (2125, 2137), False, 'import json\n'), ((609, 623), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (621, 623), False, 'from django.utils import timezone\n'), ((626, 685), 'datetime.timedelta', 'datetime.timedelta', ([], ... |
import random
import matplotlib.pyplot as plt
import wandb
import hydra
import torch
import torch.utils.data as data_utils
from model import ChessPiecePredictor
from torch import nn, optim
from google.cloud import storage
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datas... | [
"wandb.log",
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"torch.max",
"torchvision.transforms.Grayscale",
"wandb.init",
"torch.cuda.is_available",
"hydra.main",
"matplotlib.pyplot.xlabel",
"torchvision.datasets.ImageFolder",
"torchvision.transforms.ToTensor",
"matplotlib.pyplot.sa... | [((346, 401), 'hydra.main', 'hydra.main', ([], {'config_path': '"""../conf"""', 'config_name': '"""config"""'}), "(config_path='../conf', config_name='config')\n", (356, 401), False, 'import hydra\n'), ((552, 564), 'wandb.init', 'wandb.init', ([], {}), '()\n', (562, 564), False, 'import wandb\n'), ((570, 597), 'torch.m... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import os
from abc import ABC, abstractmethod
from fairseq import registry
from omegaconf import DictConfig
class BaseSco... | [
"os.path.dirname",
"fairseq.registry.setup_registry",
"importlib.import_module"
] | [((714, 766), 'fairseq.registry.setup_registry', 'registry.setup_registry', (['"""--scoring"""'], {'default': '"""bleu"""'}), "('--scoring', default='bleu')\n", (737, 766), False, 'from fairseq import registry\n'), ((1197, 1222), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1212, 1222), Fa... |
import copy
import unittest
import networkx as nx
import numpy as np
from scipy.special import erf
from dfn import Fluid, FractureNetworkThermal
class TestFractureNetworkThermal(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestFractureNetworkThermal, self).__init__(*args, **kwargs)
... | [
"networkx.MultiDiGraph",
"networkx.is_isomorphic",
"numpy.sqrt",
"numpy.ones",
"dfn.FractureNetworkThermal",
"numpy.array",
"numpy.linspace",
"scipy.special.erf",
"dfn.Fluid",
"unittest.main",
"numpy.meshgrid",
"copy.copy"
] | [((10801, 10816), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10814, 10816), False, 'import unittest\n'), ((432, 488), 'dfn.Fluid', 'Fluid', ([], {'density': 'rho_w', 'viscosity': 'mu_w', 'heat_capacity': 'cp_w'}), '(density=rho_w, viscosity=mu_w, heat_capacity=cp_w)\n', (437, 488), False, 'from dfn import Flu... |
"""
Author: <NAME>
"""
import numpy as np
import pandas as pd
from datetime import datetime
class TrackerFeeder(object):
"""
Feeder for the trackers of the FinanceHub database.
"""
def __init__(self, db_connect):
"""
Feeder construction
:param db_connect: sql connection engin... | [
"pandas.offsets.YearEnd",
"pandas.DataFrame",
"datetime.datetime.now",
"pandas.read_sql",
"pandas.to_datetime"
] | [((1256, 1297), 'pandas.read_sql', 'pd.read_sql', ([], {'sql': 'sql_query', 'con': 'self.conn'}), '(sql=sql_query, con=self.conn)\n', (1267, 1297), True, 'import pandas as pd\n'), ((1480, 1504), 'pandas.to_datetime', 'pd.to_datetime', (['df.index'], {}), '(df.index)\n', (1494, 1504), True, 'import pandas as pd\n'), ((1... |
# Copyright (c) 2018 European Organization for Nuclear Research.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LIC... | [
"oslo_config.cfg.ListOpt",
"oslo_config.cfg.OptGroup",
"oslo_config.cfg.StrOpt",
"oslo_config.cfg.IntOpt"
] | [((708, 820), 'oslo_config.cfg.OptGroup', 'cfg.OptGroup', (['"""reaper"""'], {'title': '"""Aardvark Service Options"""', 'help': '"""Configuration options for Aardvark service"""'}), "('reaper', title='Aardvark Service Options', help=\n 'Configuration options for Aardvark service')\n", (720, 820), False, 'from oslo_... |
"""
This file is part of LiberaForms.
# SPDX-FileCopyrightText: 2020 LiberaForms.org
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
import os, json
from flask import g, request, render_template, redirect
from flask import session, flash, Blueprint
from flask import send_file, after_this_request
from flask_babel imp... | [
"flask.render_template",
"liberaforms.models.invite.Invite.find_all",
"flask.g.current_user.toggle_new_form_notification",
"liberaforms.models.invite.Invite",
"liberaforms.models.form.Form.find",
"liberaforms.utils.utils.get_app_version",
"os.remove",
"liberaforms.models.user.User.find_all",
"flask.... | [((768, 837), 'flask.Blueprint', 'Blueprint', (['"""admin_bp"""', '__name__'], {'template_folder': '"""../templates/admin"""'}), "('admin_bp', __name__, template_folder='../templates/admin')\n", (777, 837), False, 'from flask import session, flash, Blueprint\n'), ((1506, 1522), 'liberaforms.models.user.User.find', 'Use... |
from Roteiro7.Roteiro7__funcoes import GrafoComPesos
# .:: Arquivo de Testes do Algoritmo de Dijkstra ::. #
# --------------------------------------------------------------------------- #
grafo_aula = GrafoComPesos(
['E', 'A', 'B', 'C', 'D'],
{
'E-A': 1,
'E-C': 10,
'A-B': 2,
'B... | [
"Roteiro7.Roteiro7__funcoes.GrafoComPesos"
] | [((203, 300), 'Roteiro7.Roteiro7__funcoes.GrafoComPesos', 'GrafoComPesos', (["['E', 'A', 'B', 'C', 'D']", "{'E-A': 1, 'E-C': 10, 'A-B': 2, 'B-C': 4, 'C-D': 3}"], {}), "(['E', 'A', 'B', 'C', 'D'], {'E-A': 1, 'E-C': 10, 'A-B': 2,\n 'B-C': 4, 'C-D': 3})\n", (216, 300), False, 'from Roteiro7.Roteiro7__funcoes import Gra... |
import pytest
from rest_framework import status
from rest_framework.test import APIClient
class TestBase:
__test__ = False
path = None
get_data = {}
put_data = {}
post_data = {}
delete_data = {}
requires_auth = True
implements_retrieve = False
implements_create = False
implemen... | [
"rest_framework.test.APIClient"
] | [((383, 394), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (392, 394), False, 'from rest_framework.test import APIClient\n')] |
from torchvision.datasets import ImageFolder
from torchvision import transforms
import random
import os
import torch
from torch.utils.data.dataloader import DataLoader
from utils import constants, get_default_device
from image_folder_with_path import ImageFolderWithPaths
def to_device(data, device):
"""Move tensor... | [
"torch.manual_seed",
"random.uniform",
"os.listdir",
"image_folder_with_path.ImageFolderWithPaths",
"torch.utils.data.dataloader.DataLoader",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.datasets.ImageFolder",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor"
] | [((1288, 1342), 'os.listdir', 'os.listdir', (['(constants.DATA_PATH + constants.TRAIN_PATH)'], {}), '(constants.DATA_PATH + constants.TRAIN_PATH)\n', (1298, 1342), False, 'import os\n'), ((1363, 1451), 'torchvision.datasets.ImageFolder', 'ImageFolder', (['(constants.DATA_PATH + constants.TRAIN_PATH)'], {'transform': 't... |
# import matplotlib
# matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors
import pytest
import tempfile
from calliope import Model
from calliope.utils import AttrDict
from calliope import analysis
from . import common
from .common import assert_almost_equal, solver, solver_io
import matplotlib.p... | [
"calliope.utils.AttrDict",
"calliope.analysis.plot_installed_capacities",
"calliope.analysis.plot_transmission",
"calliope.Model",
"calliope.analysis.get_group_share",
"calliope.analysis.get_unmet_demand_hours",
"calliope.analysis.plot_carrier_production",
"tempfile.NamedTemporaryFile",
"calliope.an... | [((333, 358), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (351, 358), True, 'import matplotlib.pyplot as plt\n'), ((429, 459), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (443, 459), False, 'import pytest\n'), ((1688, 1718), ... |
# 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
# d... | [
"unittest.mock.Mock",
"copy.deepcopy",
"json.dumps",
"unittest.mock.patch.object",
"cinder.volume.targets.spdknvmf.SpdkNvmf"
] | [((6393, 6413), 'copy.deepcopy', 'copy.deepcopy', (['BDEVS'], {}), '(BDEVS)\n', (6406, 6413), False, 'import copy\n'), ((6445, 6475), 'copy.deepcopy', 'copy.deepcopy', (['NVMF_SUBSYSTEMS'], {}), '(NVMF_SUBSYSTEMS)\n', (6458, 6475), False, 'import copy\n'), ((6963, 6997), 'json.dumps', 'json.dumps', (["{'result': self.b... |
""" This is algos.euler.transformer module.
This module is responsible for transforming raw candle data into training
samples usable to the Euler algorithm.
"""
import datetime
import decimal
from algos.euler.models import training_samples as ts
from core.models import instruments
from datasource.models import... | [
"datetime.datetime",
"datetime.time",
"core.models.instruments.get_all",
"datasource.models.candles.get_candles",
"algos.euler.models.training_samples.insert_many",
"algos.euler.models.training_samples.get_last",
"datetime.timedelta",
"decimal.Decimal"
] | [((343, 366), 'decimal.Decimal', 'decimal.Decimal', (['"""0.01"""'], {}), "('0.01')\n", (358, 366), False, 'import decimal\n'), ((3342, 3365), 'algos.euler.models.training_samples.get_last', 'ts.get_last', (['instrument'], {}), '(instrument)\n', (3353, 3365), True, 'from algos.euler.models import training_samples as ts... |
__doc__ = \
"""
=======================================================================================
Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`)
=======================================================================================
.. currentmodule:: mango.application.ma... | [
"sys.setdlopenflags",
"sys.platform.startswith",
"sys.getdlopenflags"
] | [((812, 844), 'sys.platform.startswith', 'sys.platform.startswith', (['"""linux"""'], {}), "('linux')\n", (835, 844), False, 'import sys\n'), ((882, 902), 'sys.getdlopenflags', 'sys.getdlopenflags', ([], {}), '()\n', (900, 902), False, 'import sys\n'), ((907, 955), 'sys.setdlopenflags', 'sys.setdlopenflags', (['(dl.RTL... |
# -*- coding: utf-8-unix -*-
import platform
######################################################################
# Platform specific headers
######################################################################
if platform.system() == 'Linux':
src = """
typedef bool BOOL;
"""
#############################... | [
"platform.system"
] | [((221, 238), 'platform.system', 'platform.system', ([], {}), '()\n', (236, 238), False, 'import platform\n')] |
import numpy as np
import math
from scipy.optimize import curve_fit
def calc_lorentzian(CestCurveS, x_calcentires, mask, config):
(rows, colums, z_slices, entires) = CestCurveS.shape
lorenzian = {key: np.zeros((rows, colums, z_slices), dtype=float) for key in config.lorenzian_keys}
for k in range(z_slice... | [
"scipy.optimize.curve_fit",
"numpy.zeros"
] | [((212, 259), 'numpy.zeros', 'np.zeros', (['(rows, colums, z_slices)'], {'dtype': 'float'}), '((rows, colums, z_slices), dtype=float)\n', (220, 259), True, 'import numpy as np\n'), ((1741, 1886), 'scipy.optimize.curve_fit', 'curve_fit', (['fit', 'x_calcentires', 'values'], {'bounds': '([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################
# File: network_models_LSTU.py
# Created Date: Tuesday February 25th 2020
# Author: <NAME>
# Email: <EMAIL>
# Last Modified: Tuesday, 25th February 2020 9:57:06 pm
# Modified By: <NAME>
# Copyright (c) 2020 Shan... | [
"tensorflow.contrib.slim.flatten",
"tensorflow.variable_scope",
"tflib.shape",
"tensorflow.shape",
"tensorflow.image.resize_bicubic",
"tensorflow.gradients",
"tensorflow.concat",
"tensorflow.random_uniform",
"tensorflow.sqrt",
"tensorflow.name_scope",
"functools.partial",
"tensorflow.reduce_me... | [((642, 682), 'functools.partial', 'partial', (['slim.conv2d'], {'activation_fn': 'None'}), '(slim.conv2d, activation_fn=None)\n', (649, 682), False, 'from functools import partial\n'), ((691, 741), 'functools.partial', 'partial', (['slim.conv2d_transpose'], {'activation_fn': 'None'}), '(slim.conv2d_transpose, activati... |
import backend as F
import numpy as np
import scipy as sp
import dgl
from dgl import utils
import unittest
from numpy.testing import assert_array_equal
np.random.seed(42)
def generate_rand_graph(n):
arr = (sp.sparse.random(n, n, density=0.1, format='coo') != 0).astype(np.int64)
return dgl.DGLGraph(arr, readon... | [
"numpy.testing.assert_equal",
"numpy.hstack",
"unittest.skipIf",
"backend.array_equal",
"backend.sum",
"dgl.random.seed",
"numpy.sort",
"scipy.sparse.random",
"numpy.random.seed",
"dgl.DGLGraph",
"dgl.contrib.sampling.NeighborSampler",
"backend.tensor",
"dgl.contrib.sampling.sampler.create_f... | [((153, 171), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (167, 171), True, 'import numpy as np\n'), ((7157, 7264), 'unittest.skipIf', 'unittest.skipIf', (["(dgl.backend.backend_name == 'tensorflow')"], {'reason': '"""Error occured when multiprocessing"""'}), "(dgl.backend.backend_name == 'tensorfl... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | [
"logging.getLogger",
"aws_orbit.remote_files.helm.install_chart",
"aws_orbit.__version__.endswith",
"os.path.dirname",
"aws_orbit.remote_files.helm.uninstall_chart",
"aws_orbit.remote_files.helm.create_team_charts_copy",
"aws_orbit.remote_files.helm.package_chart",
"aws_orbit.remote_files.helm.add_rep... | [((924, 954), 'logging.getLogger', 'logging.getLogger', (['"""aws_orbit"""'], {}), "('aws_orbit')\n", (941, 954), False, 'import logging\n'), ((981, 1006), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (996, 1006), False, 'import os\n'), ((1351, 1450), 'aws_orbit.remote_files.helm.create_tea... |
#! /usr/bin/env python
#
# 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... | [
"argparse.ArgumentParser",
"cinder.interface.util.get_backup_drivers",
"os.getcwd",
"os.chdir",
"os.path.dirname",
"cinder.interface.util.get_volume_drivers",
"cinder.interface.util.get_fczm_drivers",
"os.path.abspath",
"pprint.pprint"
] | [((709, 761), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""generate_driver_list"""'}), "(prog='generate_driver_list')\n", (732, 761), False, 'import argparse\n'), ((3748, 3773), 'cinder.interface.util.get_volume_drivers', 'util.get_volume_drivers', ([], {}), '()\n', (3771, 3773), False, 'from... |
""" econ/fred_view.py tests """
import unittest
from unittest import mock
from io import StringIO
import pandas as pd
# pylint: disable=unused-import
from gamestonk_terminal.econ.fred_view import get_fred_data # noqa: F401
fred_data_mock = """
,GDP
2019-01-01,21115.309
2019-04-01,21329.877
2019-07-01,21540.325
2019-... | [
"gamestonk_terminal.econ.fred_view.get_fred_data",
"io.StringIO",
"unittest.mock.patch"
] | [((474, 537), 'unittest.mock.patch', 'mock.patch', (['"""gamestonk_terminal.econ.fred_view.Fred.get_series"""'], {}), "('gamestonk_terminal.econ.fred_view.Fred.get_series')\n", (484, 537), False, 'from unittest import mock\n'), ((729, 763), 'gamestonk_terminal.econ.fred_view.get_fred_data', 'get_fred_data', (["['--nopl... |
import os
import configparser
from warnings import warn
def read_control_file(control_file):
# Initialize ConfigParser object
config = configparser.ConfigParser(
strict=True,
comment_prefixes=('/*', ';', '#'),
inline_comment_prefixes=('/*', ';', '#')
)
# Parse control file
... | [
"warnings.warn",
"configparser.ConfigParser"
] | [((145, 264), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {'strict': '(True)', 'comment_prefixes': "('/*', ';', '#')", 'inline_comment_prefixes': "('/*', ';', '#')"}), "(strict=True, comment_prefixes=('/*', ';', '#'),\n inline_comment_prefixes=('/*', ';', '#'))\n", (170, 264), False, 'import confi... |
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
import numpy as np
import pytest
from pymor.core.pickle import dumps, loads
from pymor.functions.... | [
"pymortests.pickling.assert_picklable_without_dumps_function",
"pymortests.fixtures.function.function_argument",
"pymor.core.pickle.dumps",
"numpy.ones",
"pymortests.fixtures.parameter.parameters_of_type",
"numpy.linspace",
"pymor.functions.basic.ConstantFunction",
"pytest.raises",
"numpy.zeros",
... | [((1045, 1087), 'pymortests.fixtures.parameter.parameters_of_type', 'parameters_of_type', (['f.parameter_type', '(4711)'], {}), '(f.parameter_type, 4711)\n', (1063, 1087), False, 'from pymortests.fixtures.parameter import parameters_of_type\n'), ((2526, 2552), 'pymortests.pickling.assert_picklable', 'assert_picklable',... |
import asyncio
from collections import defaultdict
from datetime import timedelta
import pytest
from yui.api import SlackAPI
from yui.bot import Bot
from yui.box import Box
from yui.types.slack.response import APIResponse
from yui.utils import json
from .util import FakeImportLib
def test_bot_init(event_loop, monk... | [
"yui.types.slack.response.APIResponse",
"yui.utils.json.dumps",
"yui.bot.Bot",
"datetime.timedelta",
"yui.box.Box"
] | [((509, 514), 'yui.box.Box', 'Box', ([], {}), '()\n', (512, 514), False, 'from yui.box import Box\n'), ((525, 567), 'yui.bot.Bot', 'Bot', (['bot_config', 'event_loop'], {'using_box': 'box'}), '(bot_config, event_loop, using_box=box)\n', (528, 567), False, 'from yui.bot import Bot\n'), ((2026, 2031), 'yui.box.Box', 'Box... |
import requests
from bs4 import BeautifulSoup
def recursiveUrl(url, link, depth):
if depth == 5:
return url
else:
print(link['href'])
page = requests.get(url + link['href'])
soup = BeautifulSoup(page.text, 'html.parser')
newlink = soup.find('a')
if len(newlink) =... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((457, 474), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (469, 474), False, 'import requests\n'), ((486, 525), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.text', '"""html.parser"""'], {}), "(page.text, 'html.parser')\n", (499, 525), False, 'from bs4 import BeautifulSoup\n'), ((174, 206), 'requests.get'... |
"""Tests for SEIR model in this repo
* Compares conserved quantities
* Compares model against SEIR wo social policies in limit to SIR
"""
from pandas import Series
from pandas.testing import assert_frame_equal, assert_series_equal
from bayes_chime.normal.models import SEIRModel, SIRModel
from pytest import fixture
fro... | [
"bayes_chime.normal.models.SEIRModel.simulation_step",
"bayes_chime.normal.models.SIRModel",
"bayes_chime.normal.models.SEIRModel",
"pytest.fixture",
"pandas.testing.assert_frame_equal",
"pandas.testing.assert_series_equal"
] | [((679, 704), 'pytest.fixture', 'fixture', ([], {'name': '"""seir_data"""'}), "(name='seir_data')\n", (686, 704), False, 'from pytest import fixture\n'), ((1185, 1196), 'bayes_chime.normal.models.SEIRModel', 'SEIRModel', ([], {}), '()\n', (1194, 1196), False, 'from bayes_chime.normal.models import SEIRModel, SIRModel\n... |
import numpy as np
from scipy.interpolate import interp1d
from pyTools import *
################################################################################
#~~~~~~~~~Log ops
################################################################################
def logPolyVal(p,x):
ord = p.order()
logs = []
... | [
"numpy.abs",
"numpy.ones_like",
"numpy.ones",
"numpy.log",
"scipy.interpolate.interp1d",
"numpy.array",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"numpy.meshgrid",
"numpy.zeros_like"
] | [((804, 836), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'y'], {'kind': 'interp_type'}), '(x, y, kind=interp_type)\n', (812, 836), False, 'from scipy.interpolate import interp1d\n'), ((1129, 1158), 'numpy.linspace', 'np.linspace', (['(0)', 'np.pi', 'ntheta'], {}), '(0, np.pi, ntheta)\n', (1140, 1158), True, 'impo... |
from setuptools import setup
setup(
name="ambient_api",
version="1.5.6",
packages=["ambient_api"],
url="https://github.com/avryhof/ambient_api",
license="MIT",
author="<NAME>",
author_email="<EMAIL>",
description="A Python class for accessing the Ambient Weather API.",
classifiers=[... | [
"setuptools.setup"
] | [((30, 524), 'setuptools.setup', 'setup', ([], {'name': '"""ambient_api"""', 'version': '"""1.5.6"""', 'packages': "['ambient_api']", 'url': '"""https://github.com/avryhof/ambient_api"""', 'license': '"""MIT"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""A Python class for accessing ... |
from collections import deque
class Solution:
"""
@param n: a positive integer
@return: the minimum number of replacements
"""
def integerReplacement(self, n):
# Write your code here
steps = 0
if n == 1:
return steps
queue = deque([n])
while q... | [
"collections.deque"
] | [((294, 304), 'collections.deque', 'deque', (['[n]'], {}), '([n])\n', (299, 304), False, 'from collections import deque\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.utils import timezone
# Create your models here.
# Create our new user class
class AccountUserManager(UserManager):
def _create_user(self, usern... | [
"django.utils.timezone.now"
] | [((673, 687), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (685, 687), False, 'from django.utils import timezone\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-05 18:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("careeropportunity", "0002_careeropportunity_job_type")]
operations = [
migrations.AddFie... | [
"django.db.models.DateField"
] | [((415, 483), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""søknadsfrist"""'}), "(blank=True, null=True, verbose_name='søknadsfrist')\n", (431, 483), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python3
import json
import argparse
import re
import datetime
import paramiko
import requests
# cmd ['ssh', 'smart',
# 'mkdir -p /home/levabd/smart-home-temp-humidity-monitor;
# cat - > /home/levabd/smart-home-temp-humidity-monitor/lr.json']
from miio import chuangmi_plug
from btlewrap import availabl... | [
"re.compile",
"paramiko.AutoAddPolicy",
"btlewrap.available_backends",
"requests.get",
"datetime.datetime.today",
"miio.chuangmi_plug.ChuangmiPlug",
"json.load",
"paramiko.SSHClient",
"json.dump",
"mitemp_bt.mitemp_bt_poller.MiTempBtPoller"
] | [((522, 534), 'json.load', 'json.load', (['f'], {}), '(f)\n', (531, 534), False, 'import json\n'), ((597, 687), 're.compile', 're.compile', (['"""[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}"""'], {}), "(\n '[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}')\n", (607... |
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#New record
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
data.shape
cenus=np.concatenate((new_record,data),axis=0)
cenus.... | [
"numpy.mean",
"numpy.concatenate",
"numpy.std",
"numpy.genfromtxt",
"warnings.filterwarnings"
] | [((82, 115), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (105, 115), False, 'import warnings\n'), ((203, 252), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (216, 252), True, 'i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scls', '0003_other_repos'),
]
operations = [
migrations.AlterField(
model_name='otherrepo',
name='ar... | [
"django.db.models.TextField",
"django.db.models.CharField"
] | [((343, 431), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'blank': '(True)', 'verbose_name': '"""Architecture"""', 'max_length': '(20)'}), "(default='', blank=True, verbose_name='Architecture',\n max_length=20)\n", (359, 431), False, 'from django.db import migrations, models\n'), ((5... |
#import external libraries used in code
import requests, json
import pycountry
print('Currency Exchange')
currencies = []
def findCurrency():
#Finds all avaliable currencies
allCurrency = (list(pycountry.currencies))
for x in allCurrency:
y = str(x)
y = y[18:21]
#Adds th... | [
"requests.get"
] | [((4912, 4929), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (4924, 4929), False, 'import requests, json\n')] |
# Copyright (C) 2018 <NAME>, <NAME>
# All rights reserved.
#
# This file is part of yambopy
#
from __future__ import print_function
from builtins import range
from yambopy import *
from qepy import *
import json
import matplotlib.pyplot as plt
import numpy as np
import sys
import argparse
import operator
def analyse_b... | [
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.savetxt",
"sys.exit",
"json.load",
"operator.itemgetter",
"matplotlib.pyplot.NullLocator",
"matplotlib.pyplot.legend"
] | [((4633, 4730), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Study convergence on BS calculations using ypp calls."""'}), "(description=\n 'Study convergence on BS calculations using ypp calls.')\n", (4656, 4730), False, 'import argparse\n'), ((3281, 3293), 'json.load', 'json.load',... |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 554539540
"""
"""
random actions, total chaos
"""
board = gamma_new(6, 8, 3, 17)
assert board i... | [
"part1.gamma_move",
"part1.gamma_board",
"part1.gamma_new",
"part1.gamma_golden_move",
"part1.gamma_delete",
"part1.gamma_busy_fields",
"part1.gamma_golden_possible",
"part1.gamma_free_fields"
] | [((283, 305), 'part1.gamma_new', 'gamma_new', (['(6)', '(8)', '(3)', '(17)'], {}), '(6, 8, 3, 17)\n', (292, 305), False, 'from part1 import gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new\n'), ((1502, 1520), 'part1.gamma_board', 'gamma_boa... |
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.utils import LayerMapping
from django.core.management.base import BaseCommand
from envergo.geodata.models import Zone
class Command(BaseCommand):
help = "Importe des zones à partir de shapefiles."
def add_arguments(self, parser):
... | [
"django.contrib.gis.gdal.DataSource",
"django.contrib.gis.utils.LayerMapping"
] | [((459, 480), 'django.contrib.gis.gdal.DataSource', 'DataSource', (['shapefile'], {}), '(shapefile)\n', (469, 480), False, 'from django.contrib.gis.gdal import DataSource\n'), ((555, 586), 'django.contrib.gis.utils.LayerMapping', 'LayerMapping', (['Zone', 'ds', 'mapping'], {}), '(Zone, ds, mapping)\n', (567, 586), Fals... |
import discord
from jshbot import utilities, data, configurations, plugins, logger
from jshbot.exceptions import BotException, ConfiguredBotException
from jshbot.commands import (
Command, SubCommand, Shortcut, ArgTypes, Attachment, Arg, Opt, MessageTypes, Response)
__version__ = '0.1.0'
CBException = ConfiguredB... | [
"jshbot.logger.warn",
"jshbot.data.get",
"jshbot.data.add",
"jshbot.commands.Response",
"jshbot.commands.Command",
"jshbot.exceptions.ConfiguredBotException",
"jshbot.data.remove"
] | [((309, 352), 'jshbot.exceptions.ConfiguredBotException', 'ConfiguredBotException', (['"""0.3 to 0.4 plugin"""'], {}), "('0.3 to 0.4 plugin')\n", (331, 352), False, 'from jshbot.exceptions import BotException, ConfiguredBotException\n'), ((655, 677), 'jshbot.commands.Response', 'Response', (['"""Converted."""'], {}), "... |
from tkinter import *
from PIL import Image, ImageTk
#python image library
#imagetk supports jpg image
a1 = Tk()
a1.geometry("455x244")
#for png image
#photo = PhotoImage(file="filename.png")
#a2 = Label(image = photo)
#a2.pack()
image = Image.open("PJXlVd.jpg")
photo = ImageTk.PhotoImage(image)
... | [
"PIL.Image.open",
"PIL.ImageTk.PhotoImage"
] | [((256, 280), 'PIL.Image.open', 'Image.open', (['"""PJXlVd.jpg"""'], {}), "('PJXlVd.jpg')\n", (266, 280), False, 'from PIL import Image, ImageTk\n'), ((290, 315), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', (['image'], {}), '(image)\n', (308, 315), False, 'from PIL import Image, ImageTk\n')] |
import os
import torch
from PIL import Image
from read_csv import csv_to_label_and_bbx
import numpy as np
from torch.utils.data import Subset, random_split, ConcatDataset
class NBIDataset(object):
def __init__(self, root, transforms, nob3=False):
self.root = root
self.transforms = transforms
... | [
"torch.manual_seed",
"torch.as_tensor",
"PIL.Image.open",
"os.listdir",
"torch.utils.data.random_split",
"os.path.join",
"torch.from_numpy",
"torch.tensor"
] | [((7492, 7513), 'torch.manual_seed', 'torch.manual_seed', (['(13)'], {}), '(13)\n', (7509, 7513), False, 'import torch\n'), ((7532, 7570), 'torch.utils.data.random_split', 'random_split', (['ds', '[46, 46, 46, 45, 45]'], {}), '(ds, [46, 46, 46, 45, 45])\n', (7544, 7570), False, 'from torch.utils.data import Subset, ran... |
# coding: utf-8
import functools
def memoize(fn):
known = dict()
@functools.wraps(fn)
def memoizer(*args):
if args not in known:
known[args] = fn(*args)
return known[args]
return memoizer
@memoize
def nsum(n):
'''返回前n个数字的和'''
assert(n >= 0), 'n must be >= 0'
... | [
"functools.wraps"
] | [((78, 97), 'functools.wraps', 'functools.wraps', (['fn'], {}), '(fn)\n', (93, 97), False, 'import functools\n')] |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
import warnings
from textwrap import dedent, fill
import numpy as np
import pandas as pd
from numpy.linalg import norm, inv
from scipy.linalg import solve as spsolve, LinAlgError
from scipy.integrate import trapz
from scipy import stats
from lifelines.... | [
"lifelines.utils.normalize",
"lifelines.plotting.set_kwargs_drawstyle",
"numpy.clip",
"lifelines.statistics.proportional_hazard_test",
"lifelines.utils.check_complete_separation",
"numpy.sqrt",
"lifelines.utils.check_low_var",
"lifelines.utils.string_justify",
"numpy.log",
"numpy.warnings.catch_wa... | [((10197, 10226), 'lifelines.utils.coalesce', 'coalesce', (['strata', 'self.strata'], {}), '(strata, self.strata)\n', (10205, 10226), False, 'from lifelines.utils import _get_index, _to_list, _to_tuple, _to_1d_array, inv_normal_cdf, normalize, qth_survival_times, coalesce, check_for_numeric_dtypes_or_raise, check_low_v... |
"""
Test configuration loading
@author aevans
"""
import os
from nlp_server.config import load_config
def test_load_config():
"""
Test loading a configuration
"""
current_dir = os.path.curdir
test_path = os.path.sep.join([current_dir, 'data', 'test_config.json'])
cfg = load_config.load_conf... | [
"os.path.sep.join",
"nlp_server.config.load_config.load_config"
] | [((229, 288), 'os.path.sep.join', 'os.path.sep.join', (["[current_dir, 'data', 'test_config.json']"], {}), "([current_dir, 'data', 'test_config.json'])\n", (245, 288), False, 'import os\n'), ((299, 333), 'nlp_server.config.load_config.load_config', 'load_config.load_config', (['test_path'], {}), '(test_path)\n', (322, ... |
import os, json, inspect
import mimetypes
from html2text import html2text
from RestrictedPython import compile_restricted, safe_globals
import RestrictedPython.Guards
import frappe
import frappe.utils
import frappe.utils.data
from frappe.website.utils import (get_shade, get_toc, get_next_link)
from frappe.modules impo... | [
"frappe._dict",
"frappe.db.get_default",
"frappe.msgprint",
"os.environ.get",
"inspect.isclass",
"RestrictedPython.compile_restricted"
] | [((969, 983), 'frappe._dict', 'frappe._dict', ([], {}), '()\n', (981, 983), False, 'import frappe\n'), ((620, 667), 'frappe.msgprint', 'frappe.msgprint', (['"""Please Enable Server Scripts"""'], {}), "('Please Enable Server Scripts')\n", (635, 667), False, 'import frappe\n'), ((852, 878), 'RestrictedPython.compile_rest... |
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of th... | [
"Microsoft.Scripting.Math.BigInteger",
"Microsoft.Scripting.Math.BigInteger.Subtract",
"Microsoft.Scripting.Math.BigInteger.RightShift",
"Microsoft.Scripting.Math.BigInteger.BitwiseOr",
"Microsoft.Scripting.Math.BigInteger.Add",
"Microsoft.Scripting.Math.BigInteger.ToInt64",
"Microsoft.Scripting.Math.Co... | [((924, 955), 'clr.AddReference', 'clr.AddReference', (['math_assembly'], {}), '(math_assembly)\n', (940, 955), False, 'import clr\n'), ((1317, 1395), 'Microsoft.Scripting.Math.BigInteger.Add', 'BigInteger.Add', (['(1)', '(99999999999999999999999999999999999999999999999999999999999)'], {}), '(1, 99999999999999999999999... |
import sys
import math
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class DecAtt(nn.Module):
def __init__(self, num_units, num_classes, embedding_size, dropout, device=0,
training=True, p... | [
"torch.squeeze",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.clamp",
"torch.transpose",
"torch.cat",
"torch.arange",
"torch.matmul",
"torch.sum",
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"torch.cuda.is_available",
"torch.nn.functional.softmax",
"torch.nn.Embedding"
] | [((1473, 1509), 'torch.nn.Embedding', 'nn.Embedding', (['max_sentence_length', '(1)'], {}), '(max_sentence_length, 1)\n', (1485, 1509), True, 'import torch.nn as nn\n'), ((1545, 1593), 'torch.nn.Linear', 'nn.Linear', (['embedding_size', 'num_units'], {'bias': '(False)'}), '(embedding_size, num_units, bias=False)\n', (1... |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch
import numpy as np
import cv2
import pdb
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def norm_angle(angle):
norm_angle = sigmoid(10 * (abs(angle) / 0.7853975 - 1))
return norm_angle
... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Sigmoid",
"torch.nn.Sequential",
"torch.stack",
"math.sqrt",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.Linear",
"math.exp",
"torch.cat"
] | [((413, 502), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=3, stride=stride, padding=1,\n bias=False)\n', (422, 502), True, 'import torch.nn as nn\n'), ((756, 778), 'torch.nn.BatchN... |
"""Serves the single page app web ui."""
import json
import tornado.gen
from ndscheduler import settings
from ndscheduler import utils
from ndscheduler.server.handlers import base
class Handler(base.BaseHandler):
"""Index page request handler."""
@tornado.gen.coroutine
def get(self):
"""Serve u... | [
"ndscheduler.utils.get_all_available_jobs",
"json.dumps"
] | [((391, 421), 'ndscheduler.utils.get_all_available_jobs', 'utils.get_all_available_jobs', ([], {}), '()\n', (419, 421), False, 'from ndscheduler import utils\n'), ((482, 503), 'json.dumps', 'json.dumps', (['meta_info'], {}), '(meta_info)\n', (492, 503), False, 'import json\n')] |
import spacy
from spacy.scorer import PRFScore
import typer
from pathlib import Path
from wasabi import Printer, table
import operator
import benepar
import clausecat_component
import clausecat_model
import clausecat_reader
import clause_segmentation
import clause_aggregation
msg = Printer()
def main(model_path: Pa... | [
"wasabi.Printer",
"spacy.load",
"clausecat_reader.ClausecatCorpus",
"wasabi.table",
"operator.itemgetter",
"typer.run",
"spacy.scorer.PRFScore"
] | [((285, 294), 'wasabi.Printer', 'Printer', ([], {}), '()\n', (292, 294), False, 'from wasabi import Printer, table\n'), ((419, 441), 'spacy.load', 'spacy.load', (['model_path'], {}), '(model_path)\n', (429, 441), False, 'import spacy\n'), ((455, 498), 'clausecat_reader.ClausecatCorpus', 'clausecat_reader.ClausecatCorpu... |
import pathlib
print(pathlib.Path(__file__).parent.resolve())
while True:
next_cmd = input("> ")
print(eval(next_cmd))
| [
"pathlib.Path"
] | [((22, 44), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (34, 44), False, 'import pathlib\n')] |
import logging
import os
import aiohttp.web
from connexion import AioHttpApp
from nlp_annotator_api.config.config import conf
from nlp_annotator_api.config.logging import setup_logging
from nlp_annotator_api.server.middleware.statsd_middleware import StatsdMiddleware
from nlp_annotator_api.server.signals.statsd_clien... | [
"logging.getLogger",
"nlp_annotator_api.config.logging.setup_logging",
"nlp_annotator_api.server.signals.statsd_client.statsd_client_factory",
"os.path.join",
"os.path.dirname",
"nlp_annotator_api.server.middleware.statsd_middleware.StatsdMiddleware"
] | [((352, 367), 'nlp_annotator_api.config.logging.setup_logging', 'setup_logging', ([], {}), '()\n', (365, 367), False, 'from nlp_annotator_api.config.logging import setup_logging\n'), ((382, 427), 'logging.getLogger', 'logging.getLogger', (['"""nlp_annotator_api.access"""'], {}), "('nlp_annotator_api.access')\n", (399, ... |