code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import random
from time import sleep
from celery import chain, chord, shared_task, states
from django.core.files.base import ContentFile
from django.db import transaction
from django.utils import timezone
from eulxml import xmlmap
from extras.tasks import CurrentUserTaskMixin
from ows_client.request_builder import Cat... | [
"random.uniform",
"django.core.files.base.ContentFile",
"registry.models.DatasetMetadata.get_table_url",
"registry.models.DatasetMetadata.iso_metadata.create_from_parsed_metadata",
"django.db.transaction.atomic",
"eulxml.xmlmap.load_xmlobject_from_string",
"django.utils.timezone.now",
"registry.models... | [((648, 727), 'celery.shared_task', 'shared_task', ([], {'name': '"""async_harvest_service"""', 'bind': '(True)', 'base': 'CurrentUserTaskMixin'}), "(name='async_harvest_service', bind=True, base=CurrentUserTaskMixin)\n", (659, 727), False, 'from celery import chain, chord, shared_task, states\n'), ((1201, 1290), 'cele... |
from urllib import parse
def validate_url(url: str, label: str):
parsed = parse.urlparse(url)
if not all([parsed.scheme, parsed.netloc]):
raise ValueError("{label} entry '{url}' is not a valid url".format(label=label, url=url))
| [
"urllib.parse.urlparse"
] | [((80, 99), 'urllib.parse.urlparse', 'parse.urlparse', (['url'], {}), '(url)\n', (94, 99), False, 'from urllib import parse\n')] |
#!/usr/bin/env python3
import argparse
import sys
import time
from debugwire import DebugWire, DWException
from interfaces import FTDIInterface, SerialInterface
from devices import devices
from binparser import parse_binary
class DWProg:
BAR_LEN = 50
def main(self):
parser = argparse.ArgumentParser()... | [
"sys.exit",
"argparse.ArgumentParser",
"debugwire.DWException",
"debugwire.DebugWire",
"interfaces.SerialInterface",
"sys.stdout.flush",
"time.time",
"binparser.parse_binary"
] | [((295, 320), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (318, 320), False, 'import argparse\n'), ((7174, 7185), 'time.time', 'time.time', ([], {}), '()\n', (7183, 7185), False, 'import time\n'), ((7801, 7824), 'binparser.parse_binary', 'parse_binary', (['args.file'], {}), '(args.file)\n', ... |
import pytest
from traitlets import Any
from sepal_ui import sepalwidgets as sw
from sepal_ui.model import Model
class TestDatePicker:
def test_init(self):
# default init
datepicker = sw.DatePicker()
assert isinstance(datepicker, sw.DatePicker)
# exhaustive
datepicker =... | [
"sepal_ui.sepalwidgets.DatePicker",
"traitlets.Any"
] | [((209, 224), 'sepal_ui.sepalwidgets.DatePicker', 'sw.DatePicker', ([], {}), '()\n', (222, 224), True, 'from sepal_ui import sepalwidgets as sw\n'), ((321, 342), 'sepal_ui.sepalwidgets.DatePicker', 'sw.DatePicker', (['"""toto"""'], {}), "('toto')\n", (334, 342), True, 'from sepal_ui import sepalwidgets as sw\n'), ((861... |
from flask import Blueprint
from flask import request
from flask_restful import Api
from flask_restful import Resource
from app.organization.schemas import OrganizationCreatedSchema
from app.organization.schemas import OrganizationInputSchema
from app.organization.schemas import OrganizationListFilterSchema
from app.o... | [
"app.organization.utils.create_organization",
"flask_restful.Api",
"app.organization.schemas.OrganizationInputSchema",
"app.organization.schemas.OrganizationListFilterSchema",
"app.organization.utils.get_organizations",
"flask.Blueprint",
"app.organization.schemas.OrganizationListSchema",
"app.organiz... | [((498, 533), 'flask.Blueprint', 'Blueprint', (['"""organization"""', '__name__'], {}), "('organization', __name__)\n", (507, 533), False, 'from flask import Blueprint\n'), ((553, 573), 'flask_restful.Api', 'Api', (['organization_bp'], {}), '(organization_bp)\n', (556, 573), False, 'from flask_restful import Api\n'), (... |
# Generated by Django 2.1.1 on 2018-09-20 14:17
from django.db import migrations, models
import wargame.models
class Migration(migrations.Migration):
dependencies = [("wargame", "0009_auto_20180919_1923")]
operations = [
migrations.AlterField(
model_name="user",
name="userna... | [
"django.db.models.CharField"
] | [((343, 640), 'django.db.models.CharField', 'models.CharField', ([], {'error_messages': "{'unique': 'A user with that username already exists.'}", 'help_text': '"""Required. 150 characters or fewer. Letters, digits and @/+/-/_ only."""', 'max_length': '(150)', 'unique': '(True)', 'validators': '[wargame.models.custom_u... |
import math
import sys
from day14.ore import (parse_reactions, ore_required_stock, topological_order,
ore_required_topological, estimate_fuel_produced)
from day14.finders import bisect, secant
example = """5 ORE => 7 A
3 A => 10 B
1 A, 3 B => 1 C
5 C, 2 B => 1 FUEL"""
if __name__ == "__main__"... | [
"day14.ore.topological_order",
"day14.finders.secant",
"day14.ore.parse_reactions",
"day14.ore.estimate_fuel_produced",
"day14.ore.ore_required_topological",
"day14.finders.bisect",
"day14.ore.ore_required_stock"
] | [((527, 548), 'day14.ore.parse_reactions', 'parse_reactions', (['text'], {}), '(text)\n', (542, 548), False, 'from day14.ore import parse_reactions, ore_required_stock, topological_order, ore_required_topological, estimate_fuel_produced\n'), ((653, 685), 'day14.ore.ore_required_stock', 'ore_required_stock', (['reaction... |
try:
from fractions import Fraction
import datetime
import locale
import platform
import math
except ModuleNotFoundError as err:
print('「' + err.name + '」のモジュールが見つかりません。以下のコマンドラインでインストールしてください。')
print('>> pip install ' + err.name)
exit()
#組み込みフォーマットの分数の定義
BUILTIN_FORMATS_FRACTION = {
... | [
"math.ceil",
"locale.setlocale",
"math.floor",
"fractions.Fraction",
"platform.system"
] | [((4167, 4222), 'locale.setlocale', 'locale.setlocale', (['locale.LC_CTYPE', '"""Japanese_Japan.932"""'], {}), "(locale.LC_CTYPE, 'Japanese_Japan.932')\n", (4183, 4222), False, 'import locale\n'), ((1518, 1531), 'fractions.Fraction', 'Fraction', (['val'], {}), '(val)\n', (1526, 1531), False, 'from fractions import Frac... |
#!/usr/bin/env python
"""
Train an agent on Sonic using PPO2 from OpenAI Baselines.
"""
import tensorflow as tf
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
import baselines.ppo2.ppo2 as ppo2
import baselines.ppo2.policies as policies
import gym_remote.exceptions as gre
from sonic_util import make... | [
"tensorflow.ConfigProto",
"tensorflow.Session",
"baselines.common.vec_env.dummy_vec_env.DummyVecEnv"
] | [((412, 428), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (426, 428), True, 'import tensorflow as tf\n'), ((505, 530), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (515, 530), True, 'import tensorflow as tf\n'), ((699, 722), 'baselines.common.vec_env.dummy_vec_e... |
from abc import ABC, abstractmethod
from pyformlang.cfg import Variable
from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State
from project.grammars.rsm import RSM
from project.grammars.rsm_box import RSMBox
class BooleanMatrix(ABC):
"""
Boolean Matrix base class
Attributes
... | [
"pyformlang.finite_automaton.NondeterministicFiniteAutomaton",
"pyformlang.finite_automaton.State"
] | [((4510, 4554), 'pyformlang.finite_automaton.State', 'State', (['f"""{state.value}#{box_variable.value}"""'], {}), "(f'{state.value}#{box_variable.value}')\n", (4515, 4554), False, 'from pyformlang.finite_automaton import NondeterministicFiniteAutomaton, State\n'), ((6567, 6600), 'pyformlang.finite_automaton.Nondetermi... |
"""
Helper for loading datasets from a file
**Supported environment variables**
::
# to show debug, trace logging please export ``SHARED_LOG_CFG``
# to a debug logger json file. To turn on debugging for this
# library, you can export this variable to the repo's
# included file with the command:
e... | [
"spylunking.log.setup_logging.build_colorized_logger",
"analysis_engine.prepare_dict_for_algo.prepare_dict_for_algo"
] | [((554, 601), 'spylunking.log.setup_logging.build_colorized_logger', 'log_utils.build_colorized_logger', ([], {'name': '__name__'}), '(name=__name__)\n', (586, 601), True, 'import spylunking.log.setup_logging as log_utils\n'), ((1709, 1829), 'analysis_engine.prepare_dict_for_algo.prepare_dict_for_algo', 'prepare_utils.... |
from abc import ABCMeta
import re
from typing import Union, Optional
from aim.artifacts import Record
from aim.artifacts.artifact import Artifact
from aim.artifacts.proto.metric_pb2 import MetricRecord
from aim.artifacts.utils import validate_dict
class Metric(Artifact):
cat = ('metrics',)
def __init__(self... | [
"aim.artifacts.proto.metric_pb2.MetricRecord",
"aim.artifacts.utils.validate_dict",
"aim.artifacts.Record"
] | [((869, 934), 'aim.artifacts.utils.validate_dict', 'validate_dict', (['kwargs', '(str, int, float)', '(str, int, float, bool)'], {}), '(kwargs, (str, int, float), (str, int, float, bool))\n', (882, 934), False, 'from aim.artifacts.utils import validate_dict\n'), ((1922, 1936), 'aim.artifacts.proto.metric_pb2.MetricReco... |
from pddlgym.parser import PDDLDomainParser, PDDLProblemParser
from pddlgym.structs import LiteralConjunction
import pddlgym
import os
import numpy as np
from itertools import count
np.random.seed(0)
PDDLDIR = os.path.join(os.path.dirname(pddlgym.__file__), "pddl")
I, G, W, P, X, H = range(6)
TRAIN_GRID1 = np.arra... | [
"numpy.flipud",
"os.path.join",
"os.path.dirname",
"numpy.array",
"numpy.argwhere",
"numpy.empty",
"numpy.random.seed",
"pddlgym.parser.PDDLProblemParser.create_pddl_file"
] | [((182, 199), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (196, 199), True, 'import numpy as np\n'), ((313, 592), 'numpy.array', 'np.array', (['[[I, P, P, P, X, X, X, W, W, G], [W, W, X, P, X, W, W, X, X, P], [W, W, X,\n P, X, X, W, X, X, P], [W, W, X, P, X, X, X, X, X, P], [W, W, X, P, X, W,\n ... |
import unittest
from msdm.domains import GridWorld
class GridWorldTestCase(unittest.TestCase):
def test_feature_locations(self):
gw = GridWorld([
"cacg",
"sabb"])
fl = gw.feature_locations
lf = gw.location_features
fl2 = {}
for l, f in lf.items():
... | [
"msdm.domains.GridWorld"
] | [((148, 175), 'msdm.domains.GridWorld', 'GridWorld', (["['cacg', 'sabb']"], {}), "(['cacg', 'sabb'])\n", (157, 175), False, 'from msdm.domains import GridWorld\n'), ((473, 536), 'msdm.domains.GridWorld', 'GridWorld', (["['....#...g', '....#....', '#####....', 's........']"], {}), "(['....#...g', '....#....', '#####....... |
from random import random
import time
import xlrd
from fractions import gcd
from decimal import Decimal
from aggregator.converters.base import *
class CSVMarineTrafficConverter(BaseConverter):
_f = None
_max_rows = None
_sheet_data = None
header_row = 2
data_row = 4
def __init__(self, name... | [
"decimal.Decimal"
] | [((8539, 8571), 'decimal.Decimal', 'Decimal', (["('%d.%02d' % (v, v_next))"], {}), "('%d.%02d' % (v, v_next))\n", (8546, 8571), False, 'from decimal import Decimal\n')] |
#!/usr/bin/env python
# coding: utf-8
# In[16]:
import sys
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal
# In[17]:
arr = list()
# with open("./stock_price_close_value_last_10000.txt", "r") as fp:
with open(sys.argv[1], "r") as fp:
arr = fp.readli... | [
"matplotlib.pyplot.savefig"
] | [((931, 955), 'matplotlib.pyplot.savefig', 'plt.savefig', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (942, 955), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
"""
Main model architecture.
reference: https://github.com/andy840314/QANet-pytorch-
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .modules.cnn import DepthwiseSeparableConv
# revised two things: head set to 1, d_model set to 96
device = torch.device(... | [
"logging.getLogger",
"torch.mul",
"torch.nn.ZeroPad2d",
"torch.nn.init.constant_",
"torch.max",
"torch.sin",
"torch.cos",
"torch.cuda.is_available",
"torch.bmm",
"torch.nn.functional.softmax",
"torch.arange",
"torch.nn.init.xavier_uniform_",
"torch.nn.LayerNorm",
"torch.nn.init.kaiming_nor... | [((11877, 11904), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (11894, 11904), False, 'import logging\n'), ((2216, 2253), 'torch.nn.ZeroPad2d', 'nn.ZeroPad2d', (['(0, channels % 2, 0, 0)'], {}), '((0, channels % 2, 0, 0))\n', (2228, 2253), True, 'import torch.nn as nn\n'), ((332, 357), ... |
import bluetooth # Importing the Bluetooth Socket library
import time
from can_receive import CanReceive
can_receive_obj = CanReceive()
class BluetoothInterface:
def __init__(self):
self.start = 0
self.count = 1
self.host = ""
self.port = 1 # Pi uses port 1 for Bluetooth Commun... | [
"can_receive.CanReceive",
"bluetooth.BluetoothSocket",
"time.sleep"
] | [((125, 137), 'can_receive.CanReceive', 'CanReceive', ([], {}), '()\n', (135, 137), False, 'from can_receive import CanReceive\n'), ((350, 393), 'bluetooth.BluetoothSocket', 'bluetooth.BluetoothSocket', (['bluetooth.RFCOMM'], {}), '(bluetooth.RFCOMM)\n', (375, 393), False, 'import bluetooth\n'), ((932, 946), 'time.slee... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Count words in a text file
"""
import os
import time
import math
import string
import argparse
def round_to_decimals(num, decs):
"""
Round floating point number to some number of decimals
"""
factor = math.pow(10.0, decs)
return math.trunc(num * f... | [
"os.path.getsize",
"argparse.ArgumentParser",
"math.pow",
"math.trunc",
"time.time"
] | [((270, 290), 'math.pow', 'math.pow', (['(10.0)', 'decs'], {}), '(10.0, decs)\n', (278, 290), False, 'import math\n'), ((1942, 1967), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1965, 1967), False, 'import argparse\n'), ((302, 326), 'math.trunc', 'math.trunc', (['(num * factor)'], {}), '(nu... |
import numpy as np
import cv2 as cv
from imutils.video import WebcamVideoStream
import glob
import time
import math
class PoseEstimation():
def __init__(self, mtx, dist):
self.mtx = mtx
self.dist = dist
def detect_contourn(self, image, color):
hsv = cv.cvtColor(image, cv.CO... | [
"cv2.projectPoints",
"numpy.array",
"cv2.arcLength",
"cv2.solvePnPRansac",
"numpy.dot",
"numpy.concatenate",
"cv2.drawContours",
"numpy.ones",
"cv2.minEnclosingCircle",
"cv2.morphologyEx",
"cv2.circle",
"cv2.cvtColor",
"cv2.moments",
"numpy.shape",
"numpy.transpose",
"cv2.inRange",
"... | [((296, 332), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2HSV'], {}), '(image, cv.COLOR_BGR2HSV)\n', (307, 332), True, 'import cv2 as cv\n'), ((1092, 1131), 'cv2.inRange', 'cv.inRange', (['hsv', 'self.lower', 'self.upper'], {}), '(hsv, self.lower, self.upper)\n', (1102, 1131), True, 'import cv2 as cv\n'), (... |
############################
# written by <NAME> and <NAME>
############################
"""
Run the experiments - DEMO
"""
import os
import numpy as np
import pandas as pd
from load_data import *
from algorithms import *
from record_history import *
from util_func import *
from schedule_LR import *
... | [
"os.path.exists",
"os.makedirs"
] | [((488, 515), 'os.path.exists', 'os.path.exists', (['record_path'], {}), '(record_path)\n', (502, 515), False, 'import os\n'), ((522, 546), 'os.makedirs', 'os.makedirs', (['record_path'], {}), '(record_path)\n', (533, 546), False, 'import os\n'), ((557, 588), 'os.path.exists', 'os.path.exists', (['record_avg_path'], {}... |
"""
Rien de très intéressant à modifier ici. Va plutôt voir transforms.py
"""
from ui.crazyfiltersapp import CrazyFiltersApp
if __name__ == '__main__':
CrazyFiltersApp().run()
| [
"ui.crazyfiltersapp.CrazyFiltersApp"
] | [((158, 175), 'ui.crazyfiltersapp.CrazyFiltersApp', 'CrazyFiltersApp', ([], {}), '()\n', (173, 175), False, 'from ui.crazyfiltersapp import CrazyFiltersApp\n')] |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/core.ipynb (unless otherwise specified).
__all__ = ['StatsForecast']
# Cell
import inspect
import logging
from functools import partial
from os import cpu_count
import numpy as np
import pandas as pd
# Internal Cell
logging.basicConfig(
format='%(asctime)s %(name)... | [
"logging.getLogger",
"numpy.hstack",
"ray.is_initialized",
"inspect.signature",
"os.cpu_count",
"ray.util.multiprocessing.Pool",
"ray.available_resources",
"ray.init",
"pandas.date_range",
"numpy.arange",
"itertools.repeat",
"numpy.repeat",
"numpy.vstack",
"pandas.DataFrame",
"numpy.allc... | [((268, 384), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(name)s %(levelname)s: %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(format=\n '%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt=\n '%Y-%m-%d %H:%M:%S')\n", (287, 384), False, 'import logging\n'), ((... |
# /*
# * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# * SPDX-License-Identifier: MIT-0
# *
# * Permission is hereby granted, free of charge, to any person obtaining a copy of this
# * software and associated documentation files (the "Software"), to deal in the Software
# * without restrict... | [
"aws_cdk.aws_ec2.SubnetConfiguration"
] | [((1437, 1544), 'aws_cdk.aws_ec2.SubnetConfiguration', 'ec2.SubnetConfiguration', ([], {'subnet_type': 'ec2.SubnetType.PUBLIC', 'name': '"""public"""', 'cidr_mask': '(24)', 'reserved': '(False)'}), "(subnet_type=ec2.SubnetType.PUBLIC, name='public',\n cidr_mask=24, reserved=False)\n", (1460, 1544), True, 'import aws... |
from typing import List
from avalanche.evaluation.metric_results import MetricValue
from avalanche.evaluation.metric_utils import stream_type
from avalanche.logging.interactive_logging import InteractiveLogger
from tqdm import tqdm
from avalanche.training import BaseStrategy
from avalanche_rl.logging.strategy_logger i... | [
"avalanche.evaluation.metric_utils.stream_type",
"tqdm.tqdm.write"
] | [((2014, 2080), 'tqdm.tqdm.write', 'tqdm.write', (['"""\n-- >> Start of eval phase << --"""'], {'file': 'self.file'}), '("""\n-- >> Start of eval phase << --""", file=self.file)\n', (2024, 2080), False, 'from tqdm import tqdm\n'), ((2521, 2553), 'avalanche.evaluation.metric_utils.stream_type', 'stream_type', (['strateg... |
'''
Description:
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-... | [
"collections.namedtuple"
] | [((1717, 1759), 'collections.namedtuple', 'namedtuple', (['"""TestEntry"""', '"""n hidden_number"""'], {}), "('TestEntry', 'n hidden_number')\n", (1727, 1759), False, 'from collections import namedtuple\n')] |
import unittest
import numpy as np
import torch
from pyscf import gto
from torch.autograd import Variable, grad, gradcheck
from qmctorch.scf import Molecule
from qmctorch.wavefunction import SlaterJastrow
torch.set_default_tensor_type(torch.DoubleTensor)
def hess(out, pos):
# compute the jacobian
z = Variab... | [
"qmctorch.scf.Molecule",
"torch.manual_seed",
"torch.ones_like",
"pyscf.gto.M",
"torch.set_default_tensor_type",
"torch.autograd.grad",
"numpy.random.seed",
"qmctorch.wavefunction.SlaterJastrow",
"torch.allclose",
"torch.autograd.Variable",
"torch.autograd.gradcheck",
"torch.zeros",
"torch.r... | [((207, 256), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.DoubleTensor'], {}), '(torch.DoubleTensor)\n', (236, 256), False, 'import torch\n'), ((587, 611), 'torch.zeros', 'torch.zeros', (['jacob.shape'], {}), '(jacob.shape)\n', (598, 611), False, 'import torch\n'), ((1204, 1228), 'torch.z... |
"""
后端驱动适配基类
=================
各驱动请继承以下基类
"""
import abc
import asyncio
from dataclasses import dataclass, field
from typing import Any, Set, Dict, Type, Union, Optional, Callable, Awaitable, TYPE_CHECKING
from nonebot.log import logger
from nonebot.config import Env, Config
from nonebot.typing import T_BotConnectio... | [
"dataclasses.field",
"nonebot.log.logger.opt",
"asyncio.gather"
] | [((6680, 6707), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (6685, 6707), False, 'from dataclasses import dataclass, field\n'), ((7959, 7986), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (7964, 7986), False, 'from dataclas... |
# -*- coding: utf-8 -*-
"""Tests for go.vumitools.contact."""
from twisted.internet.defer import inlineCallbacks
from vumi.tests.helpers import VumiTestCase
from go.vumitools.tests.utils import model_eq
from go.vumitools.contact import (
ContactStore, ContactError, ContactNotFoundError)
from go.vumitools.opt_ou... | [
"go.vumitools.tests.utils.model_eq",
"go.vumitools.opt_out.OptOutStore.from_user_account",
"go.vumitools.contact.ContactStore.from_user_account",
"go.vumitools.tests.helpers.VumiApiHelper"
] | [((699, 743), 'go.vumitools.contact.ContactStore.from_user_account', 'ContactStore.from_user_account', (['user_account'], {}), '(user_account)\n', (729, 743), False, 'from go.vumitools.contact import ContactStore, ContactError, ContactNotFoundError\n'), ((922, 970), 'go.vumitools.contact.ContactStore.from_user_account'... |
"""Module that includes functionality to work with mcc data."""
import logging
from gino import exceptions
from sqlalchemy.exc import SQLAlchemyError
from app.db import db
from app.cache import cache, MCC_CODES_CACHE_KEY, MCC_CATEGORY_CACHE_KEY, MCC_CATEGORY_CACHE_EXPIRE
from app.utils.errors import DatabaseError
... | [
"logging.getLogger",
"app.utils.errors.DatabaseError",
"app.db.db.all",
"app.db.db.one",
"app.cache.cache.get",
"app.db.db.text",
"app.cache.MCC_CATEGORY_CACHE_KEY.format",
"app.cache.cache.set"
] | [((329, 356), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (346, 356), False, 'import logging\n'), ((480, 530), 'app.db.db.text', 'db.text', (['"""\n SELECT code FROM mcc;\n """'], {}), '("""\n SELECT code FROM mcc;\n """)\n', (487, 530), False, 'from app.db import d... |
import os
import random
from typing import Union
from copy import deepcopy as dcp
rd=lambda l:random.choice(list(l))
exts={
'':[''],
'archive':['archive'],
'qwq':['qwq','qwq1','qwq2','qwq3','qwq4','bmp'],
'pic':['png','jpg','jpeg','bmp','tif','tiff','gif',],
'gif':['gif'],
'tar':... | [
"os.path.exists",
"os.listdir",
"os.path.join",
"os.path.isfile",
"os.path.dirname",
"os.path.isdir",
"os.path.basename",
"copy.deepcopy",
"os.system"
] | [((2207, 2226), 'os.path.basename', 'os.path.basename', (['s'], {}), '(s)\n', (2223, 2226), False, 'import os\n'), ((3413, 3433), 'os.listdir', 'os.listdir', (['self.pth'], {}), '(self.pth)\n', (3423, 3433), False, 'import os\n'), ((4171, 4204), 'os.system', 'os.system', (['(\'explorer "\' + x + \'"\')'], {}), '(\'expl... |
from logging import warning, info
class Einfluxer:
def __init__(self, client, database, retentionPolicy):
self.Client = client
self.Database = database
self.retentionPolicy = retentionPolicy
if not self.DbExsist(self.Database):
self.CreateDb()
self.Cli... | [
"logging.info"
] | [((558, 583), 'logging.info', 'info', (['"""Creating Database"""'], {}), "('Creating Database')\n", (562, 583), False, 'from logging import warning, info\n')] |
from urllib import urlparse
def is_url(url: str):
"""
Code from https://stackoverflow.com/a/52455972
"""
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
| [
"urllib.urlparse"
] | [((146, 159), 'urllib.urlparse', 'urlparse', (['url'], {}), '(url)\n', (154, 159), False, 'from urllib import urlparse\n')] |
from icolos.core.workflow_steps.step import StepBase
from pydantic import BaseModel
from openmm.app import PDBFile
import parmed
from openff.toolkit.topology import Molecule, Topology
from openff.toolkit.typing.engines.smirnoff import ForceField
from openff.toolkit.utils import get_data_file_path
from icolos.utils.en... | [
"openff.toolkit.topology.Topology.from_openmm",
"os.path.join",
"openff.toolkit.topology.Molecule.from_smiles",
"icolos.utils.enums.step_enums.StepOpenFFEnum",
"parmed.openmm.load_topology"
] | [((511, 527), 'icolos.utils.enums.step_enums.StepOpenFFEnum', 'StepOpenFFEnum', ([], {}), '()\n', (525, 527), False, 'from icolos.utils.enums.step_enums import StepOpenFFEnum\n'), ((1231, 1288), 'openff.toolkit.topology.Topology.from_openmm', 'Topology.from_openmm', (['omm_topology'], {'unique_molecules': 'mols'}), '(o... |
import codecs
from contextlib import suppress
import logging
import os
from pathlib import Path
from typing import Union
import tempfile
_LOGGER = logging.getLogger(__name__)
def ensure_unique_string(preferred_string, current_strings):
test_string = preferred_string
current_strings_set = set(current_strings... | [
"logging.getLogger",
"stat.S_IFMT",
"os.walk",
"os.remove",
"os.path.exists",
"pathlib.Path",
"esphome.core.EsphomeError",
"subprocess.Popen",
"os.chmod",
"os.path.isdir",
"contextlib.suppress",
"os.unlink",
"tempfile.NamedTemporaryFile",
"os.path.dirname",
"shutil.copyfile",
"codecs.o... | [((149, 176), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (166, 176), False, 'import logging\n'), ((3719, 3732), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (3726, 3732), False, 'import os\n'), ((1517, 1587), 'subprocess.Popen', 'subprocess.Popen', (['args'], {'stdout': 'subproce... |
# 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 applicable law or agreed to in... | [
"oslo_config.cfg.BoolOpt",
"oslo_config.cfg.StrOpt"
] | [((653, 1890), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (['"""config_drive_format"""'], {'default': '"""iso9660"""', 'choices': "('iso9660', 'vfat')", 'help': '"""\nConfiguration drive format\n\nConfiguration drive format that will contain metadata attached to the\ninstance when it boots.\n\nPossible values:\n\n* iso966... |
import os
import dotenv
from app.bot import AutoSnipe
bot = AutoSnipe(".")
dotenv.load_dotenv()
token = os.getenv("TOKEN")
bot.run(token)
| [
"app.bot.AutoSnipe",
"os.getenv",
"dotenv.load_dotenv"
] | [((63, 77), 'app.bot.AutoSnipe', 'AutoSnipe', (['"""."""'], {}), "('.')\n", (72, 77), False, 'from app.bot import AutoSnipe\n'), ((78, 98), 'dotenv.load_dotenv', 'dotenv.load_dotenv', ([], {}), '()\n', (96, 98), False, 'import dotenv\n'), ((107, 125), 'os.getenv', 'os.getenv', (['"""TOKEN"""'], {}), "('TOKEN')\n", (116... |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Change address on Trade Channels."""
from test_framework.test_framework import BitcoinTestFramewo... | [
"os.path.join"
] | [((1103, 1164), 'os.path.join', 'os.path.join', (["(self.options.tmpdir + '/node0')", '"""litecoin.conf"""'], {}), "(self.options.tmpdir + '/node0', 'litecoin.conf')\n", (1115, 1164), False, 'import os\n')] |
"""
Based on django's caching template loader.
"""
import hashlib
import shpaml
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin
class Loader(BaseLoader):
is_usable = True
def __init__(self, loader... | [
"django.template.base.TemplateDoesNotExist",
"shpaml.convert_text",
"django.template.loader.make_origin",
"django.template.loader.get_template_from_string",
"django.template.loader.find_template_loader"
] | [((1484, 1510), 'django.template.base.TemplateDoesNotExist', 'TemplateDoesNotExist', (['name'], {}), '(name)\n', (1504, 1510), False, 'from django.template.base import TemplateDoesNotExist\n'), ((1178, 1204), 'django.template.base.TemplateDoesNotExist', 'TemplateDoesNotExist', (['name'], {}), '(name)\n', (1198, 1204), ... |
import asyncio
import gc
import time
import weakref
from koala.typing import *
from koala.logger import logger
__TIMER_ID = 0
def _gen_timer_id() -> int:
global __TIMER_ID
__TIMER_ID += 1
return __TIMER_ID
def _milli_seconds() -> int:
return int(time.time() * 1000)
class A... | [
"koala.logger.logger.error",
"time.time",
"koala.logger.logger.debug",
"asyncio.sleep"
] | [((909, 987), 'koala.logger.logger.debug', 'logger.debug', (["('ActorTimer:%s GC, ActorID:%s' % (self.timer_id, self._actor_id))"], {}), "('ActorTimer:%s GC, ActorID:%s' % (self.timer_id, self._actor_id))\n", (921, 987), False, 'from koala.logger import logger\n'), ((288, 299), 'time.time', 'time.time', ([], {}), '()\n... |
#Utility file of functions and imports
#Doles, Nix, Terlecky
#File includes standard imports and defined functions used in multiple project files
#
#
import random
import itertools
import numpy as np
import pandas as pd
import numpy as np
import glob
from sklearn.model_selection import train_test_split
from sklearn.e... | [
"numpy.array",
"random.random",
"sklearn.externals.joblib.load",
"numpy.argpartition"
] | [((2642, 2656), 'sklearn.externals.joblib.load', 'joblib.load', (['m'], {}), '(m)\n', (2653, 2656), False, 'from sklearn.externals import joblib\n'), ((4446, 4460), 'sklearn.externals.joblib.load', 'joblib.load', (['s'], {}), '(s)\n', (4457, 4460), False, 'from sklearn.externals import joblib\n'), ((5308, 5331), 'sklea... |
import time
from disk_cache import disk_cache
# @disk_cache("/dev/shm")
@disk_cache()
def slow_func(n):
import time
time.sleep(2)
return 0
def main():
# this takes ~2s for n=0
start = time.time()
result = slow_func(0)
print(time.time() - start)
# this takes ~2s for n=1
st... | [
"time.time",
"time.sleep",
"disk_cache.disk_cache"
] | [((76, 88), 'disk_cache.disk_cache', 'disk_cache', ([], {}), '()\n', (86, 88), False, 'from disk_cache import disk_cache\n'), ((128, 141), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (138, 141), False, 'import time\n'), ((210, 221), 'time.time', 'time.time', ([], {}), '()\n', (219, 221), False, 'import time\n')... |
import os
import random
import warnings
import numpy as np
from tqdm import tqdm
from PIL import Image, ImageFile
from torch.utils.data import Dataset
from taming.data.base import ImagePaths
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
def test_images(root, images):
passed_images = list... | [
"taming.data.base.ImagePaths",
"os.listdir",
"random.shuffle",
"tqdm.tqdm",
"os.path.join",
"warnings.catch_warnings",
"os.path.splitext",
"os.path.isfile",
"numpy.array",
"numpy.load",
"numpy.save"
] | [((340, 352), 'tqdm.tqdm', 'tqdm', (['images'], {}), '(images)\n', (344, 352), False, 'from tqdm import tqdm\n'), ((751, 782), 'os.path.join', 'os.path.join', (['root', '"""train.npy"""'], {}), "(root, 'train.npy')\n", (763, 782), False, 'import os\n'), ((798, 827), 'os.path.join', 'os.path.join', (['root', '"""val.npy... |
import exceRNApipeline.tasks.task_preprocess as task
import exceRNApipeline.tasks.slurm_job as slurm_job
from unittest import TestCase
from unittest.mock import patch
from io import StringIO
import sys
import re
import os
# overwrite the shell function because we don't want to really execute the
# commands.
task.she... | [
"exceRNApipeline.tasks.task_preprocess.main",
"re.findall",
"io.StringIO",
"re.search"
] | [((1227, 1255), 're.findall', 're.findall', (['"""hts_Stats"""', 'out'], {}), "('hts_Stats', out)\n", (1237, 1255), False, 'import re\n'), ((1020, 1031), 'exceRNApipeline.tasks.task_preprocess.main', 'task.main', ([], {}), '()\n', (1029, 1031), True, 'import exceRNApipeline.tasks.task_preprocess as task\n'), ((1326, 13... |
import pandas as pd
import webbrowser
class Song:
def __init__(self,track_name: str = None,artist_name: str = None,track_id: str = None,genre: str = None,popularity: float = None,valence: float = None,danceability: float = None,energy: float = None,loudness: float = None):
self.genre = genre
self.... | [
"webbrowser.open"
] | [((699, 721), 'webbrowser.open', 'webbrowser.open', (['_play'], {}), '(_play)\n', (714, 721), False, 'import webbrowser\n')] |
"""ローグライクシステムのオブジェクトに使える関数を提供する。"""
from broccoli import register
from broccoli import const
@register.function('roguelike.object.action', system='roguelike', attr='action', material='object')
def action(self):
# 4方向に攻撃できそうなのがいれば、攻撃する
for direction, x, y in self.get_4_positions():
tile = self.canvas.t... | [
"broccoli.register.function"
] | [((96, 199), 'broccoli.register.function', 'register.function', (['"""roguelike.object.action"""'], {'system': '"""roguelike"""', 'attr': '"""action"""', 'material': '"""object"""'}), "('roguelike.object.action', system='roguelike', attr=\n 'action', material='object')\n", (113, 199), False, 'from broccoli import re... |
import json
import numpy as np
from fairseq.criterions.data_utils.task_def import TaskType, DataFormat
def load_data(file_path, data_format, task_type, label_dict=None):
"""
:param file_path:
:param data_format:
:param task_type:
:param label_dict: map string label to numbers.
... | [
"numpy.argmax"
] | [((2001, 2018), 'numpy.argmax', 'np.argmax', (['labels'], {}), '(labels)\n', (2010, 2018), True, 'import numpy as np\n')] |
from causallift import generate_data
def generate_data_(params):
"""
# Generate simulated data
# "Sleeping dogs" (a.k.a. "do-not-disturb"; people who will "buy" if not
treated but will not "buy" if treated) can be simulated by negative values
in tau parameter.
# Observational data which includ... | [
"causallift.generate_data"
] | [((616, 639), 'causallift.generate_data', 'generate_data', ([], {}), '(**params)\n', (629, 639), False, 'from causallift import generate_data\n')] |
from django.conf import settings
from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.views.generic import TemplateView, FormView
import django_js_reverse.views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),
] | [
"django.views.generic.TemplateView.as_view"
] | [((236, 284), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""index.html"""'}), "(template_name='index.html')\n", (256, 284), False, 'from django.views.generic import TemplateView, FormView\n')] |
from urllib.parse import parse_qsl
import pytest
from precessor.excs import InvalidParameter, InvalidOperation
from precessor.ops import parse_operations
from precessor.params import parse_params
def test_erroneous_format():
with pytest.raises(InvalidParameter):
parse_params(parse_qsl('format=bmp'))
d... | [
"urllib.parse.parse_qsl",
"pytest.raises"
] | [((238, 269), 'pytest.raises', 'pytest.raises', (['InvalidParameter'], {}), '(InvalidParameter)\n', (251, 269), False, 'import pytest\n'), ((358, 389), 'pytest.raises', 'pytest.raises', (['InvalidParameter'], {}), '(InvalidParameter)\n', (371, 389), False, 'import pytest\n'), ((447, 478), 'pytest.raises', 'pytest.raise... |
#!/usr/bin/python3
#
# Copyright 2019, The Android Open Source Project
#
# 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 ... | [
"argparse.FileType",
"xml.etree.ElementTree.parse",
"argparse.ArgumentParser",
"xml.etree.ElementTree.tostring",
"os.path.join",
"os.getcwd",
"os.chdir",
"os.path.normpath",
"xml.dom.minidom.parseString",
"xml.etree.ElementInclude.include",
"logging.root.setLevel",
"xml.etree.ElementTree.SubEl... | [((1661, 1967), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parameter-Framework XML product strategies structure file generator.\n Exit with the number of (recoverable or not) ... |
from collections import Counter, namedtuple
from itertools import product
from operator import attrgetter
from random import randint
init_possible_codes = set(product([1, 2, 3, 4, 5, 6], repeat=4))
Feedback = namedtuple('Feedback', ['blacks', 'whites'])
ScoreData = namedtuple('ScoreData', ['guess', 'score', 'is_poss... | [
"operator.attrgetter",
"itertools.product",
"collections.namedtuple",
"collections.Counter"
] | [((212, 256), 'collections.namedtuple', 'namedtuple', (['"""Feedback"""', "['blacks', 'whites']"], {}), "('Feedback', ['blacks', 'whites'])\n", (222, 256), False, 'from collections import Counter, namedtuple\n'), ((269, 332), 'collections.namedtuple', 'namedtuple', (['"""ScoreData"""', "['guess', 'score', 'is_possible_... |
# Generated by Django 2.1.5 on 2020-01-04 14:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('robot', '0003_auto_20200104_1236'),
]
operations = [
migrations.AlterField(
model_name='appmodel',
name='insert_time... | [
"django.db.models.DateTimeField",
"django.db.models.BooleanField"
] | [((341, 401), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'verbose_name': '"""插入时间"""'}), "(auto_now_add=True, verbose_name='插入时间')\n", (361, 401), False, 'from django.db import migrations, models\n'), ((530, 586), 'django.db.models.DateTimeField', 'models.DateTimeField', (... |
# Copyright 2014 Netflix, Inc.
#
# 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... | [
"cloudaux.orchestration.aws.s3.get_bucket",
"security_monkey.decorators.record_exception",
"security_monkey.decorators.iter_account_region",
"cloudaux.aws.s3.list_buckets"
] | [((1433, 1497), 'security_monkey.decorators.record_exception', 'record_exception', ([], {'source': '"""s3-watcher"""', 'pop_exception_fields': '(True)'}), "(source='s3-watcher', pop_exception_fields=True)\n", (1449, 1497), False, 'from security_monkey.decorators import record_exception, iter_account_region\n'), ((1694,... |
from src.job import AutoHealthJob
def main():
AutoHealthJob()
if __name__ == '__main__':
main()
| [
"src.job.AutoHealthJob"
] | [((52, 67), 'src.job.AutoHealthJob', 'AutoHealthJob', ([], {}), '()\n', (65, 67), False, 'from src.job import AutoHealthJob\n')] |
import pysplishsplash
import gym
import pickle
import numpy as np
import torch
import argparse
import os,sys
import time
from scipy.ndimage import gaussian_filter,gaussian_filter1d
from scipy.stats import linregress
from scipy.spatial.transform import Rotation as R
import math
import matplotlib.pyplot as plt
from tqdm... | [
"TD3_particles.TD3",
"matplotlib.pyplot.ylabel",
"numpy.array",
"torch.cuda.is_available",
"scipy.ndimage.gaussian_filter",
"gym.make",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",... | [((1444, 1466), 'torch.cat', 'torch.cat', (['all_feat', '(0)'], {}), '(all_feat, 0)\n', (1453, 1466), False, 'import torch\n'), ((1482, 1504), 'torch.cat', 'torch.cat', (['all_part', '(0)'], {}), '(all_part, 0)\n', (1491, 1504), False, 'import torch\n'), ((2226, 2283), 'matplotlib.pyplot.plot', 'plt.plot', (['emp_avg']... |
import datetime
import time
import tweepy
from plyer import notification
from tweepy import OAuthHandler
import settings
# 監視したいキーワードのリスト
words = ["GitHub", "AWS", "Slack", "Gmail", "障害"]
auth = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
auth.set_access_token(settings.ACCESS_TOKEN, settings.ACCES... | [
"plyer.notification.notify",
"time.sleep",
"datetime.datetime.now",
"tweepy.API",
"tweepy.OAuthHandler"
] | [((199, 260), 'tweepy.OAuthHandler', 'OAuthHandler', (['settings.CONSUMER_KEY', 'settings.CONSUMER_SECRET'], {}), '(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)\n', (211, 260), False, 'from tweepy import OAuthHandler\n'), ((337, 353), 'tweepy.API', 'tweepy.API', (['auth'], {}), '(auth)\n', (347, 353), False, 'impor... |
import json
from os import getenv
from pathlib import Path
from typing import TypedDict, List, Any, Union
from .errors_modals import *
class User(TypedDict, total=False):
username: str
password: str
is_default: bool
last_login_time: str
consumed_bytes: int
last_login_result: str
class Conf... | [
"json.load",
"pathlib.Path.home",
"json.dump",
"os.getenv"
] | [((433, 444), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (442, 444), False, 'from pathlib import Path\n'), ((663, 685), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (672, 685), False, 'import json\n'), ((452, 478), 'os.getenv', 'getenv', (['"""IPGW_CONFIG_FILE"""'], {}), "('IPGW_CONFIG_F... |
import os
from catalog import app
app.run(debug=True, host=os.environ.get('CATALOG_HOST'), port=os.environ.get('CATALOG_PORT'))
| [
"os.environ.get"
] | [((60, 90), 'os.environ.get', 'os.environ.get', (['"""CATALOG_HOST"""'], {}), "('CATALOG_HOST')\n", (74, 90), False, 'import os\n'), ((97, 127), 'os.environ.get', 'os.environ.get', (['"""CATALOG_PORT"""'], {}), "('CATALOG_PORT')\n", (111, 127), False, 'import os\n')] |
from typing import List, Union
from src.config.settings import get_settings
from src.db.timescale_db.tsdb_connector_pool import TimescaleDBConnectorPool
from src.models.models.project import ProjectDB,Project
from src.models.models.time_series import TimeSeries, TimeSeriesProject, TimeSeriesSample
def query_time_ser... | [
"src.models.models.time_series.TimeSeriesSample",
"src.config.settings.get_settings"
] | [((2950, 2964), 'src.config.settings.get_settings', 'get_settings', ([], {}), '()\n', (2962, 2964), False, 'from src.config.settings import get_settings\n'), ((5482, 5517), 'src.models.models.time_series.TimeSeriesSample', 'TimeSeriesSample', ([], {'id': '(0)', 'sample': 'data'}), '(id=0, sample=data)\n', (5498, 5517),... |
"""Tests dict input objects for `tackle.providers.tackle.block` module."""
from tackle.main import tackle
def test_provider_system_hook_block_tackle(change_dir):
"""Simple block test."""
output = tackle('basic.yaml', no_input=True)
assert output['stuff'] == 'here'
assert 'things' not in output
def ... | [
"tackle.main.tackle"
] | [((206, 241), 'tackle.main.tackle', 'tackle', (['"""basic.yaml"""'], {'no_input': '(True)'}), "('basic.yaml', no_input=True)\n", (212, 241), False, 'from tackle.main import tackle\n'), ((435, 480), 'tackle.main.tackle', 'tackle', (['"""embedded_blocks.yaml"""'], {'no_input': '(True)'}), "('embedded_blocks.yaml', no_inp... |
import pandas as pd
import numpy as np
import quandl, math, datetime
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
df = quandl.g... | [
"datetime.datetime.fromtimestamp",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"numpy.array",
"quandl.get",
"matplotlib.style.use",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.scale",
"matplot... | [((284, 303), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (293, 303), False, 'from matplotlib import style\n'), ((312, 336), 'quandl.get', 'quandl.get', (['"""WIKI/GOOGL"""'], {}), "('WIKI/GOOGL')\n", (322, 336), False, 'import quandl, math, datetime\n'), ((844, 866), 'sklearn.preproces... |
import pytest
import requests
from requests import Response, Request
from fineract import BadArgsException, ResourceNotFoundException, BadCredentialsException, FineractException
from fineract.handlers import RequestHandler
class ExampleResponse(Response):
def __init__(self, code):
super(ExampleResponse, ... | [
"requests.Session",
"fineract.handlers.RequestHandler",
"requests.Request",
"pytest.mark.parametrize",
"pytest.raises"
] | [((5023, 5135), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""error_class"""', '[requests.ConnectionError, requests.ConnectTimeout, AttributeError]'], {}), "('error_class', [requests.ConnectionError, requests.\n ConnectTimeout, AttributeError])\n", (5046, 5135), False, 'import pytest\n'), ((2119, 2184)... |
# coding:utf-8
"""
@author : linkin
@email : <EMAIL>
@date : 2018-10-07
"""
import time
import asyncio
import logging
from components.dbhelper import Database
from config.DBsettings import _DB_SETTINGS
from config.DBsettings import _TABLE
from config.config import DETECT_HIGH_AM... | [
"logging.getLogger",
"time.sleep",
"asyncio.gather",
"asyncio.get_event_loop",
"components.dbhelper.Database"
] | [((583, 612), 'logging.getLogger', 'logging.getLogger', (['"""Detector"""'], {}), "('Detector')\n", (600, 612), False, 'import logging\n'), ((939, 961), 'components.dbhelper.Database', 'Database', (['_DB_SETTINGS'], {}), '(_DB_SETTINGS)\n', (947, 961), False, 'from components.dbhelper import Database\n'), ((988, 1010),... |
from typing import Any, Dict, Optional, cast
from django import forms
from django.core.exceptions import ValidationError
from django.forms.models import ModelChoiceIterator
class Autocomplete(forms.Select):
template_name = "reactivated/autocomplete"
def get_context(
self, name: str, value: Any, attr... | [
"django.forms.Widget.get_context",
"typing.cast"
] | [((391, 430), 'typing.cast', 'cast', (['ModelChoiceIterator', 'self.choices'], {}), '(ModelChoiceIterator, self.choices)\n', (395, 430), False, 'from typing import Any, Dict, Optional, cast\n'), ((933, 983), 'django.forms.Widget.get_context', 'forms.Widget.get_context', (['self', 'name', 'value', 'attrs'], {}), '(self,... |
# library
from redesigned_barnacle.config import load_config, parse_file
from redesigned_barnacle.eth import eth_start
from redesigned_barnacle.sparkline import Sparkline
from redesigned_barnacle.unit import temp_ftoc
from prometheus_express import start_http_server, CollectorRegistry, Counter, Gauge, Router
from bme28... | [
"bme280.BME280",
"prometheus_express.start_http_server",
"os.mount",
"prometheus_express.Gauge",
"esp32.raw_temperature",
"redesigned_barnacle.sparkline.Sparkline",
"machine.Pin",
"time.sleep",
"machine.SDCard",
"prometheus_express.Router",
"prometheus_express.CollectorRegistry",
"ssd1306.SSD1... | [((597, 632), 'prometheus_express.start_http_server', 'start_http_server', (['port'], {'address': 'ip'}), '(port, address=ip)\n', (614, 632), False, 'from prometheus_express import start_http_server, CollectorRegistry, Counter, Gauge, Router\n'), ((741, 756), 'bme280.BME280', 'BME280', ([], {'i2c': 'bus'}), '(i2c=bus)\... |
import logging
import httpx
import pytest
from collector import IHSClient
from tests.utils import MockAsyncDispatch
logger = logging.getLogger(__name__)
pytestmark = pytest.mark.asyncio
base_url = httpx.URL("http://127.0.0.1")
@pytest.fixture
def well_dispatcher():
yield MockAsyncDispatch(
{
... | [
"logging.getLogger",
"tests.utils.MockAsyncDispatch",
"collector.IHSClient.get_production",
"httpx.URL",
"collector.IHSClient.get_wells",
"pytest.mark.parametrize",
"collector.IHSClient.get_ids",
"pytest.raises",
"collector.IHSClient.get_areas",
"collector.IHSClient.get_ids_by_area"
] | [((128, 155), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (145, 155), False, 'import logging\n'), ((204, 233), 'httpx.URL', 'httpx.URL', (['"""http://127.0.0.1"""'], {}), "('http://127.0.0.1')\n", (213, 233), False, 'import httpx\n'), ((819, 889), 'pytest.mark.parametrize', 'pytest.mar... |
from views import db
from _config import DATABASE_PATH
import sqlite3
# from datetime import datetime
# migration of tasks table
# with sqlite3.connect(DATABASE_PATH) as conn:
# c = conn.cursor()
# c.execute('ALTER TABLE tasks RENAME TO old_tasks')
# db.create_all()
# c.execute("""SELECT name, due... | [
"views.db.create_all",
"sqlite3.connect"
] | [((735, 765), 'sqlite3.connect', 'sqlite3.connect', (['DATABASE_PATH'], {}), '(DATABASE_PATH)\n', (750, 765), False, 'import sqlite3\n'), ((859, 874), 'views.db.create_all', 'db.create_all', ([], {}), '()\n', (872, 874), False, 'from views import db\n')] |
import os
import uuid
from copy import deepcopy
import grpc
import aim.ext.transport.remote_tracking_pb2 as rpc_messages
import aim.ext.transport.remote_tracking_pb2_grpc as remote_tracking_pb2_grpc
from aim.ext.transport.message_utils import pack_stream, unpack_stream, raise_exception
from aim.ext.transport.config im... | [
"aim.ext.transport.remote_tracking_pb2.RequestHeader",
"aim.ext.transport.remote_tracking_pb2.ReleaseResourceRequest",
"os.getenv",
"aim.ext.transport.message_utils.raise_exception",
"grpc.secure_channel",
"aim.storage.treeutils.encode_tree",
"aim.ext.transport.message_utils.unpack_stream",
"grpc.inse... | [((536, 579), 'os.getenv', 'os.getenv', (['AIM_CLIENT_SSL_CERTIFICATES_FILE'], {}), '(AIM_CLIENT_SSL_CERTIFICATES_FILE)\n', (545, 579), False, 'import os\n'), ((928, 1000), 'aim.ext.transport.remote_tracking_pb2_grpc.RemoteTrackingServiceStub', 'remote_tracking_pb2_grpc.RemoteTrackingServiceStub', (['self._remote_chann... |
# =========================================================================
# This code built for the Competition of iNaturalist 2019 at FGVC6
# Part of MCEN90048 project
# This file contains a founction that converts datasets to tfrecords
# Modified from open sources by <NAME>
# The Univerivsity of Melbourne
# <EMAIL>... | [
"PIL.Image.open",
"io.BytesIO",
"PIL.ImageOps.expand",
"tensorflow.train.Int64List",
"tensorflow.train.BytesList",
"tensorflow.train.FloatList",
"tensorflow.python_io.TFRecordWriter",
"time.time"
] | [((1840, 1851), 'time.time', 'time.time', ([], {}), '()\n', (1849, 1851), False, 'import time\n'), ((2106, 2124), 'PIL.Image.open', 'Image.open', (['im_loc'], {}), '(im_loc)\n', (2116, 2124), False, 'from PIL import Image, ImageOps\n'), ((4530, 4541), 'time.time', 'time.time', ([], {}), '()\n', (4539, 4541), False, 'im... |
"""
shapeshift-cli
An unofficial cli for https://shapeshift.io
Usage:
shapeshift-cli email <email_address> <transaction_id>
shapeshift-cli info <have_currency> <want_currency>
shapeshift-cli ls
shapeshift-cli rate <have_currency> <want_currency>
shapeshift-cli shift [-f=<amount> | -a] [-e=<email>] <have_currency>... | [
"docopt.docopt",
"shapeshift_cli.shapeshift_cli.ShapeShift"
] | [((1094, 1106), 'shapeshift_cli.shapeshift_cli.ShapeShift', 'ShapeShift', ([], {}), '()\n', (1104, 1106), False, 'from shapeshift_cli.shapeshift_cli import ShapeShift\n'), ((1119, 1151), 'docopt.docopt', 'docopt', (['__doc__'], {'version': 'VERSION'}), '(__doc__, version=VERSION)\n', (1125, 1151), False, 'from docopt i... |
from unittest import mock
from io import StringIO
from snowfakery.data_generator import generate
class TestLocales:
def test_locales(self, generated_rows):
yaml = """
- var: snowfakery_locale
value: no_NO
- object: first
fields:
name:
fake: na... | [
"io.StringIO",
"unittest.mock.patch"
] | [((490, 541), 'unittest.mock.patch', 'mock.patch', (['"""snowfakery.utils.template_utils.Faker"""'], {}), "('snowfakery.utils.template_utils.Faker')\n", (500, 541), False, 'from unittest import mock\n'), ((569, 583), 'io.StringIO', 'StringIO', (['yaml'], {}), '(yaml)\n', (577, 583), False, 'from io import StringIO\n')] |
import logging
import pytest
from pricehist import exceptions
def test_handler_logs_debug_information(caplog):
with caplog.at_level(logging.DEBUG):
try:
with exceptions.handler():
raise exceptions.RequestError("Some message")
except SystemExit:
pass
a... | [
"pricehist.exceptions.handler",
"pytest.raises",
"pricehist.exceptions.RequestError"
] | [((518, 543), 'pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (531, 543), False, 'import pytest\n'), ((563, 583), 'pricehist.exceptions.handler', 'exceptions.handler', ([], {}), '()\n', (581, 583), False, 'from pricehist import exceptions\n'), ((603, 642), 'pricehist.exceptions.RequestError', ... |
from .base import IntegrationBaseTestCase
import mock
from beancmd import list_tubes
class ListTubesTestCase(IntegrationBaseTestCase):
def test_list_tubes(self):
for tube in ('foo', 'bar', 'baz'):
self.bs1.client.use(tube)
self.bs1.client.put_job('job_data')
parser = list... | [
"beancmd.list_tubes.run",
"mock.patch",
"beancmd.list_tubes.setup_parser"
] | [((316, 341), 'beancmd.list_tubes.setup_parser', 'list_tubes.setup_parser', ([], {}), '()\n', (339, 341), False, 'from beancmd import list_tubes\n'), ((460, 490), 'mock.patch', 'mock.patch', (['"""sys.stdout.write"""'], {}), "('sys.stdout.write')\n", (470, 490), False, 'import mock\n'), ((529, 549), 'beancmd.list_tubes... |
import os
host = os.getenv("SCRAPLI_SMOKE_HOST", None)
port = os.getenv("SCRAPLI_SMOKE_PORT", None)
user = os.getenv("SCRAPLI_SMOKE_USER", None)
password = os.getenv("SCRAPLI_SMOKE_PASS", None)
iosxe_device = {
"host": host or "172.18.0.11",
"port": port or 22,
"auth_username": user or "vrnetlab",
"au... | [
"os.getenv"
] | [((18, 55), 'os.getenv', 'os.getenv', (['"""SCRAPLI_SMOKE_HOST"""', 'None'], {}), "('SCRAPLI_SMOKE_HOST', None)\n", (27, 55), False, 'import os\n'), ((63, 100), 'os.getenv', 'os.getenv', (['"""SCRAPLI_SMOKE_PORT"""', 'None'], {}), "('SCRAPLI_SMOKE_PORT', None)\n", (72, 100), False, 'import os\n'), ((108, 145), 'os.gete... |
from database import Database
from collections import defaultdict
import converters
class RN:
db = None
def __init__(self, operacoes):
self.db = Database()
for o in operacoes:
self.db.addOperacao(o)
# Preço médio de compra ou de venda de um ativo.
def precoM... | [
"converters.toDecimal",
"database.Database"
] | [((173, 183), 'database.Database', 'Database', ([], {}), '()\n', (181, 183), False, 'from database import Database\n'), ((677, 704), 'converters.toDecimal', 'converters.toDecimal', (['o.qtd'], {}), '(o.qtd)\n', (697, 704), False, 'import converters\n'), ((726, 755), 'converters.toDecimal', 'converters.toDecimal', (['o.... |
"""Functions to generate plots of the flow field with VisIt."""
import os
import sys
import yaml
def visit_check_version(version):
# Check version of VisIt.
script_version = '2.12.1'
tested_versions = [script_version, '2.12.3']
print('VisIt version: {}\n'.format(version))
if version not in tested... | [
"visit.TimeSliderGetNStates",
"visit.SetActiveWindow",
"visit.MeshAttributes",
"visit.DefineVectorExpression",
"visit.PseudocolorAttributes",
"visit.SetView3D",
"yaml.load",
"visit.SaveWindowAttributes",
"visit.AnnotationAttributes",
"visit.CreateDatabaseCorrelation",
"os.remove",
"visit.Versi... | [((916, 927), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (925, 927), False, 'import os\n'), ((1570, 1589), 'visit.LaunchNowin', 'visit.LaunchNowin', ([], {}), '()\n', (1587, 1589), False, 'import visit\n'), ((1955, 2023), 'visit.CreateDatabaseCorrelation', 'visit.CreateDatabaseCorrelation', (['"""common"""', 'database... |
import decimal
import operator
from zcalc.lib import CalcError, op, reduce
round_rules_parse = {
'ceiling': decimal.ROUND_CEILING,
'down': decimal.ROUND_DOWN,
'floor': decimal.ROUND_FLOOR,
'half-down': decimal.ROUND_HALF_DOWN,
'half-even': decimal.ROUND_HALF_EVEN,
'half-up': decimal.ROUND_HALF_... | [
"decimal.getcontext",
"zcalc.lib.op",
"zcalc.lib.reduce",
"zcalc.lib.CalcError",
"decimal.Decimal"
] | [((456, 478), 'zcalc.lib.op', 'op', ([], {'aliases': "['+', 'a']"}), "(aliases=['+', 'a'])\n", (458, 478), False, 'from zcalc.lib import CalcError, op, reduce\n'), ((531, 553), 'zcalc.lib.op', 'op', ([], {'aliases': "['/', 'd']"}), "(aliases=['/', 'd'])\n", (533, 553), False, 'from zcalc.lib import CalcError, op, reduc... |
# -*- coding: utf-8 -*-
import datetime, json, logging, os, pprint, re
# from operator import itemgetter
import django, sqlalchemy
from disa_app import models_sqlalchemy as models_alch
from disa_app import settings_app
from disa_app.lib import person_common
from disa_app.models import MarkedForDeletion
from django.co... | [
"logging.getLogger",
"sqlalchemy.orm.sessionmaker",
"disa_app.models_sqlalchemy.Citation.display.contains",
"disa_app.models_sqlalchemy.Citation.comments.contains",
"disa_app.models_sqlalchemy.Person.last_name.contains",
"disa_app.models.MarkedForDeletion.objects.all",
"sqlalchemy.create_engine",
"dis... | [((465, 492), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (482, 492), False, 'import datetime, json, logging, os, pprint, re\n'), ((562, 607), 'sqlalchemy.create_engine', 'create_engine', (['settings_app.DB_URL'], {'echo': '(True)'}), '(settings_app.DB_URL, echo=True)\n', (575, 607), F... |
import numpy as np
# iterator for X with multiple observation sequences
# copied from hmmlearn
def iter_from_X_lengths(X, lengths):
if lengths is None:
yield 0, len(X)
else:
n_samples = X.shape[0]
end = np.cumsum(lengths).astype(np.int32)
start = end - lengths
if end[-1]... | [
"numpy.errstate",
"numpy.log",
"numpy.cumsum"
] | [((632, 660), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (643, 660), True, 'import numpy as np\n'), ((677, 686), 'numpy.log', 'np.log', (['a'], {}), '(a)\n', (683, 686), True, 'import numpy as np\n'), ((236, 254), 'numpy.cumsum', 'np.cumsum', (['lengths'], {}), '(lengths)\... |
import os
import datetime
import subprocess
import os.path
def normalize_time(month, day, hour, minute, round_to_nearest_5m=True):
if int(month) <= 9:
month = "0" + month
if int(day) <= 9:
day = "0" + day
if int(hour) <= 9:
hour = "0" + hour
if int(minute) <= 9:
minute ... | [
"os.path.exists",
"os.listdir",
"subprocess.Popen",
"os.getcwd",
"os.chdir",
"os.path.realpath"
] | [((1071, 1094), 'os.chdir', 'os.chdir', (['out_directory'], {}), '(out_directory)\n', (1079, 1094), False, 'import os\n'), ((1173, 1200), 'os.path.exists', 'os.path.exists', (['output_file'], {}), '(output_file)\n', (1187, 1200), False, 'import os\n'), ((1289, 1307), 'os.chdir', 'os.chdir', (['this_dir'], {}), '(this_d... |
import os.path as osp
from PIL import Image
import torchvision.transforms as transforms
from torch.utils.data import Dataset
class GBU(Dataset):
def __init__(self, path, indices_list, labels, stage="train"):
"""This is a dataloader for the processed good bad ugly dataset.
Assuming that the images... | [
"torchvision.transforms.CenterCrop",
"PIL.Image.open",
"torchvision.transforms.RandomHorizontalFlip",
"os.path.join",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"torchvision.transforms.RandomResizedCrop"
] | [((951, 1026), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (971, 1026), True, 'import torchvision.transforms as transforms\n'), ((1793, 1809), 'PIL.Image.open', 'Image.op... |
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
app_name = 'organizer'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', auth_views.login, {'template_name': 'organizer/login.html'}, name='login'),
url(r'^logout/$', auth_views.logout,... | [
"django.conf.urls.url"
] | [((147, 183), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (150, 183), False, 'from django.conf.urls import url\n'), ((187, 281), 'django.conf.urls.url', 'url', (['"""^login/$"""', 'auth_views.login', "{'template_name': 'organizer/login.ht... |
# Generated by Django 4.0.1 on 2022-01-09 06:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('spots', '0009_musical_audio_file_musical_cover_image_and_more'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.ForeignKey"
] | [((396, 505), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'to': '"""spots.album"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.SET_NULL, to='spots.album')\n", (413, 505), False, 'from django.... |
# 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, software
... | [
"gi.repository.Gtk.Grid",
"gi.repository.Gtk.TextView",
"sysbar.lib.session.SbSession",
"gi.repository.Gtk.Button",
"sysbar.ui.dialog.UiDialog",
"gi.repository.Gtk.CheckButton",
"sysbar.core.products.new.SbNewProduct",
"gi.repository.Gtk.ListStore",
"gi.repository.Gtk.Window.__init__",
"sysbar.cor... | [((576, 608), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (594, 608), False, 'import gi\n'), ((977, 1028), 'gi.repository.Gtk.Window.__init__', 'Gtk.Window.__init__', (['self'], {'window_position': '"""center"""'}), "(self, window_position='center')\n", (996, 1028),... |
"""Discover and load entry points from installed packages."""
# Copyright (c) <NAME> and contributors
# Distributed under the terms of the MIT license; see LICENSE file.
from contextlib import contextmanager
import glob
from importlib import import_module
import io
import itertools
import os.path as osp
import re
impo... | [
"re.split",
"importlib.import_module",
"zipfile.ZipFile",
"re.compile",
"os.path.join",
"os.path.isfile",
"os.path.dirname",
"os.path.isdir",
"io.TextIOWrapper",
"os.path.basename",
"zipfile.is_zipfile"
] | [((480, 618), 're.compile', 're.compile', (['"""\n(?P<modulename>\\\\w+(\\\\.\\\\w+)*)\n(:(?P<objectname>\\\\w+(\\\\.\\\\w+)*))?\n\\\\s*\n(\\\\[(?P<extras>.+)\\\\])?\n$\n"""', 're.VERBOSE'], {}), '(\n """\n(?P<modulename>\\\\w+(\\\\.\\\\w+)*)\n(:(?P<objectname>\\\\w+(\\\\.\\\\w+)*))?\n\\\\s*\n(\\\\[(?P<extras>.+)\\\... |
# Modules
import csv
import os
# Create empty list for csv file
polls=[]
# Create empty dictionary to record only candidate names
dict_polls={}
# Create empty dictionaty to summarize the total number votes per candidate name
dict_summary={}
#Get the data from the source
election_data_csv = os.path.join(... | [
"os.path.join",
"csv.reader"
] | [((307, 340), 'os.path.join', 'os.path.join', (['"""election_data.csv"""'], {}), "('election_data.csv')\n", (319, 340), False, 'import os\n'), ((1836, 1881), 'os.path.join', 'os.path.join', (['"""Pypoll"""', '"""election_output.txt"""'], {}), "('Pypoll', 'election_output.txt')\n", (1848, 1881), False, 'import os\n'), (... |
# -*- coding: utf-8 -*-
import vk_api, sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QApplication,
QLabel, QLineEdit, QPushButton, QTextEdit,
QFileDialog, QListWidget, QWidget)
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.tit... | [
"PyQt5.QtWidgets.QTextEdit",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtWidgets.QFileDialog.getOpenFileNames",
"PyQt5.QtWidgets.QListWidget",
"vk_api.VkUpload",
"PyQt5.QtCore.pyqtSlot",
"vk_api.VkApi",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QApplication",
"PyQt5.QtWidgets.QFileDialog.getOpenFileNam... | [((6058, 6080), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (6070, 6080), False, 'from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QPushButton, QTextEdit, QFileDialog, QListWidget, QWidget\n'), ((877, 887), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', ([], {}), '()\n', (885, ... |
import data
def main():
vScore = 0
iScore = 0
total = 0
lower = float(input('Enter the lowest score possible: '))
upper = float(input('Enter the highest score possible: '))
max = lower
min = upper
#print comments are to check if data is being read correctly.
infile = op... | [
"data.updateMax",
"data.validScore",
"data.updateMin",
"data.mean",
"data.midRange"
] | [((476, 516), 'data.validScore', 'data.validScore', (['lower', 'upper', 'testScore'], {}), '(lower, upper, testScore)\n', (491, 516), False, 'import data\n'), ((609, 639), 'data.updateMax', 'data.updateMax', (['max', 'testScore'], {}), '(max, testScore)\n', (623, 639), False, 'import data\n'), ((659, 689), 'data.update... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 22:55:34 2021
@author: logan
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys; sys.path.append("../../meshcnn")
from meshcnn.ops import MeshConv, DownSamp, ResBlock
import os
class DownSamp(nn.Module):
def... | [
"torch.nn.MaxPool1d",
"torch.nn.ReLU",
"meshcnn.ops.ResBlock",
"torch.nn.Sequential",
"os.path.join",
"torch.nn.functional.dropout",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"meshcnn.ops.MeshConv",
"sys.path.append",
"torch.nn.Conv1d",
"torch.cat"
] | [((189, 221), 'sys.path.append', 'sys.path.append', (['"""../../meshcnn"""'], {}), "('../../meshcnn')\n", (204, 221), False, 'import sys\n'), ((639, 697), 'meshcnn.ops.MeshConv', 'MeshConv', (['in_chan', 'out_chan'], {'mesh_file': 'mesh_file', 'stride': '(1)'}), '(in_chan, out_chan, mesh_file=mesh_file, stride=1)\n', (... |
# Copyright 2018 Red Hat, Inc.
#
# 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, so... | [
"os.path.dirname",
"testtools.matchers.MatchesRegex"
] | [((732, 757), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (747, 757), False, 'import os\n'), ((1803, 1818), 'testtools.matchers.MatchesRegex', 'MatchesRegex', (['r'], {}), '(r)\n', (1815, 1818), False, 'from testtools.matchers import MatchesRegex\n'), ((1487, 1528), 'testtools.matchers.Mat... |
#!/usr/bin/env python
'''get_market_prices.py: Fetch prices at regular intervals up to an event start.'''
import datetime
from os import rename
import time
import betfair
from betfair import Betfair
from betfair.models import MarketFilter
from betfair.constants import MarketProjection
import pymysql.cursors
client ... | [
"betfair.Betfair",
"os.rename",
"time.strftime",
"time.sleep",
"datetime.datetime.now",
"betfair.models.MarketFilter",
"betfair.constants.MarketProjection"
] | [((322, 376), 'betfair.Betfair', 'Betfair', (['"""APP_KEY"""', "('certs/api.crt', 'certs/api.key')"], {}), "('APP_KEY', ('certs/api.crt', 'certs/api.key'))\n", (329, 376), False, 'from betfair import Betfair\n'), ((454, 479), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (467, 479), Fals... |
import json, subprocess
from ... pyaz_utils import get_cli_name, get_params
def create(link, target, notes=None):
params = get_params(locals())
command = "az resource link create " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | [
"json.loads",
"subprocess.run"
] | [((235, 323), 'subprocess.run', 'subprocess.run', (['command'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(command, shell=True, stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n', (249, 323), False, 'import json, subprocess\n'), ((681, 769), 'subprocess.run', 'subprocess.run... |
# -*- coding: utf-8 -*-
# Pretty ~ Useful ~ Python
from pathlib import Path
__version__ = (
[
l
for l in open(str(Path(__file__).resolve().parents[1] / "pyproject.toml"))
.read()
.split("\n")
if "version" in l
][0]
.replace("version = ", "")
.strip('"')
)
| [
"pathlib.Path"
] | [((135, 149), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (139, 149), False, 'from pathlib import Path\n')] |
"""
Slackbot configuration
"""
import logging
from slackbot.utils.secrets import Secrets
secrets = Secrets()
BACKEND = 'Slack'
BOT_DATA_DIR = './data'
BOT_EXTRA_PLUGIN_DIR = './slackbot/plugins'
CORE_PLUGINS = ('ACLs', 'Help', 'Health', 'Utils')
BOT_LOG_FILE = BOT_DATA_DIR + '/err.log'
BOT_LOG_LEVEL = logging.INFO
... | [
"slackbot.utils.secrets.Secrets"
] | [((102, 111), 'slackbot.utils.secrets.Secrets', 'Secrets', ([], {}), '()\n', (109, 111), False, 'from slackbot.utils.secrets import Secrets\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 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
#
# Unl... | [
"magicdict.MagicDict.fromkeys",
"magicdict.MagicDict",
"pytest.raises"
] | [((826, 843), 'magicdict.MagicDict', 'MagicDict', (['sample'], {}), '(sample)\n', (835, 843), False, 'from magicdict import MagicDict\n'), ((953, 988), 'magicdict.MagicDict', 'MagicDict', (["[('a', 'b'), ('a', 'c')]"], {}), "([('a', 'b'), ('a', 'c')])\n", (962, 988), False, 'from magicdict import MagicDict\n'), ((1071,... |
"""
Computes the outputs for test data
"""
from helper_functions import *
from models import UNetDS64, MultiResUNet1D
import os
def predict_test_data():
"""
Computes the outputs for test data
and saves them in order to avoid recomputing
"""
length = 1024 # length of sig... | [
"models.MultiResUNet1D",
"models.UNetDS64",
"os.path.join"
] | [((481, 497), 'models.UNetDS64', 'UNetDS64', (['length'], {}), '(length)\n', (489, 497), False, 'from models import UNetDS64, MultiResUNet1D\n'), ((911, 933), 'models.MultiResUNet1D', 'MultiResUNet1D', (['length'], {}), '(length)\n', (925, 933), False, 'from models import UNetDS64, MultiResUNet1D\n'), ((597, 644), 'os.... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myproject.users.api.views import UserViewSet
from myproject.users.views import (
user_detail_view,
user_redirect_view,
user_update_view)
app_name = "users"
router = DefaultRouter()
router.register('users', UserView... | [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((271, 286), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (284, 286), False, 'from rest_framework.routers import DefaultRouter\n'), ((354, 374), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (361, 374), False, 'from django.urls import path, include\n')] |
import struct
from .address import Address
__all__ = ['LocalStation', 'RemoteStation']
class LocalStation(Address):
"""
LocalStation
"""
def __init__(self, addr):
self.addrType = Address.localStationAddr
self.addrNet = None
if isinstance(addr, int):
if (addr < 0) ... | [
"struct.pack"
] | [((423, 445), 'struct.pack', 'struct.pack', (['"""B"""', 'addr'], {}), "('B', addr)\n", (434, 445), False, 'import struct\n'), ((1212, 1234), 'struct.pack', 'struct.pack', (['"""B"""', 'addr'], {}), "('B', addr)\n", (1223, 1234), False, 'import struct\n')] |
import sys
import requests
import json
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
nifi_api_url = sys.argv[1]
prometheus_pushgateway_url = sys.argv[2]
artifact_id = sys.argv[3]
flow_file_loc = nifi_api_url + '/flow/templates'
alert_name = artifact_id + 'CheckTemplate'
def flow_files_queu... | [
"json.loads",
"prometheus_client.push_to_gateway",
"prometheus_client.CollectorRegistry",
"prometheus_client.Gauge",
"requests.get"
] | [((572, 591), 'prometheus_client.CollectorRegistry', 'CollectorRegistry', ([], {}), '()\n', (589, 591), False, 'from prometheus_client import CollectorRegistry, Gauge, push_to_gateway\n'), ((596, 673), 'prometheus_client.Gauge', 'Gauge', (['alert_name', '"""Last Unix time when change was pushed"""'], {'registry': 'regi... |