text stringlengths 213 32.3k |
|---|
import logging
from typing import List
import eiscp
from eiscp import eISCP
import voluptuous as vol
from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.const import (
DOMAIN,
SUPPORT_PLAY,
SUPPORT_PLAY_MEDIA,
SUPPORT_SELECT_... |
import asyncio
import logging
from types import MappingProxyType
from typing import Any, Dict, Iterable, Optional
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import Context, State
from homeassistant.helpers.typ... |
import os.path as op
import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_equal, assert_array_less)
from scipy import fftpack
from mne import read_events, Epochs, make_fixed_length_events
from mne.io import read_raw_fif
from mne.ti... |
from threading import Thread, Event
import requests
import time
import logging
logger = logging.getLogger(__name__)
class PandoraStatsPoller(Thread):
def __init__(self, port):
super(PandoraStatsPoller, self).__init__()
self._stop_run = Event()
self.buffer = []
self.port = port
... |
from django.test import TestCase
from zinnia.templating import append_position
from zinnia.templating import loop_template_list
class TemplateTestCase(TestCase):
"""Tests cases for template"""
def test_loop_template_list(self):
template = 'zinnia/template.html'
self.assertEqual(
... |
from .base_classes import Command, Container, Environment
from .package import Package
class Alignat(Environment):
"""Class that represents a aligned equation environment."""
#: Alignat environment cause compile errors when they do not contain items.
#: This is why it is omitted fully if they are empty.... |
from goalzero import exceptions
from homeassistant.components.goalzero.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from . import (
CONF_CONFIG_FLOW,
CONF_DATA,... |
import os
import subprocess
import threading
import time
import unittest
from absl import flags
import mock
from perfkitbenchmarker import errors
from perfkitbenchmarker import vm_util
from tests import pkb_common_test_case
import psutil
FLAGS = flags.FLAGS
class ShouldRunOnInternalIpAddressTestCase(
pkb_commo... |
from html import escape
from aiohttp import web
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import HTTP_OK
import homeassistant.helpers.config_validation as cv
CONTENT_TYPE_XML = "text/xml"
DOMAIN = "rss_feed_template"
CONFIG_SCHEMA = vol.Schema(
... |
from __future__ import absolute_import, division
import copy
import warnings
import numpy as np
from numpy import dot, zeros, eye
import scipy.linalg as linalg
from filterpy.common import pretty_str
class HInfinityFilter(object):
"""
H-Infinity filter. You are responsible for setting the
various state va... |
from homeassistant.components.group import GroupIntegrationRegistry
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_CUSTOM_BYPASS,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_TRIGGERED,
STATE_OFF,
)
from homeassistant.core import callback
from homeas... |
import copy
from datetime import datetime, timedelta
import logging
import re
import caldav
import voluptuous as vol
from homeassistant.components.calendar import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
CalendarEventDevice,
calculate_offset,
get_date,
is_offset_reached,
)
from homeassistant.cons... |
import errno
import voluptuous as vol
from wiffi import WiffiTcpServer
from homeassistant import config_entries
from homeassistant.const import CONF_PORT, CONF_TIMEOUT
from homeassistant.core import callback
from .const import ( # pylint: disable=unused-import
DEFAULT_PORT,
DEFAULT_TIMEOUT,
DOMAIN,
)
... |
from __future__ import division
import unittest
import numpy as np
import PIL.Image
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainercv.transforms import resize
from chainercv.utils import generate_random_bbox
from chainercv.utils import mask_to_bbox
from c... |
import numpy as np
import unittest
import chainer
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainercv.links.model.faster_rcnn import RegionProposalNetwork
@testing.parameterize(*(testing.product({
'B': [1],
'train': [True, False],
'scales': [Non... |
from django.conf import settings
from django.db import models
class ContributorAgreementManager(models.Manager):
def has_agreed(self, user, component):
cache_key = (user.pk, component.pk)
if cache_key not in user.cla_cache:
user.cla_cache[cache_key] = self.filter(
comp... |
from datetime import timedelta
import logging
from pyaftership.tracker import Tracking
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME, HTTP_OK
from homeassistant.helpers.aiohttp_client import async_get_cli... |
from ast import literal_eval
from nikola.plugin_categories import ShortcodePlugin
from nikola.utils import req_missing, load_data
try:
import pygal
except ImportError:
pygal = None
_site = None
class ChartShortcode(ShortcodePlugin):
"""Plugin for chart shortcode."""
name = "chart"
def handle... |
import pytest
import voluptuous as vol
from homeassistant.components.ecobee.util import ecobee_date, ecobee_time
def test_ecobee_date_with_valid_input():
"""Test that the date function returns the expected result."""
test_input = "2019-09-27"
assert ecobee_date(test_input) == test_input
def test_ecob... |
import copy
import datetime
import tempfile
from absl import flags
from perfkitbenchmarker import configs
from perfkitbenchmarker import dpb_service
from perfkitbenchmarker import errors
from perfkitbenchmarker import sample
from perfkitbenchmarker.dpb_service import BaseDpbService
from perfkitbenchmarker.providers.aw... |
from pylatex.base_classes import Environment, CommandBase, Arguments
from pylatex.package import Package
from pylatex import Document, Section, UnsafeCommand
from pylatex.utils import NoEscape
class ExampleEnvironment(Environment):
"""
A class representing a custom LaTeX environment.
This class represen... |
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.vacuum import DOMAIN, STATE_CLEANING, STATE_DOCKED
from homeassistant.helpers import device_registry
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
assert_li... |
import pytest
import cerberus
from cerberus.base import UnconcernedValidator
from cerberus.tests import assert_fail, assert_success
from cerberus.tests.conftest import sample_schema
def test_contextual_data_preservation():
class InheritedValidator(cerberus.Validator):
def __init__(self, *args, **kwargs)... |
import hmac
from typing import Any, Dict, Optional, cast
import voluptuous as vol
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, Logi... |
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_network
from typing import Any, Dict, List, Optional, Union, cast
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
... |
import os
import unittest
import platform
import urwid
from urwid.compat import PYTHON3
class EventLoopTestMixin(object):
def test_event_loop(self):
rd, wr = os.pipe()
evl = self.evl
out = []
def step1():
out.append("writing")
os.write(wr, "hi".encode('asc... |
from __future__ import print_function
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from diamond.collector import Collector
from netstat import NetstatCollector
################################################################################... |
import secrets
from typing import Dict
from aiohttp.web import Request, Response
import emoji
from nacl.secret import SecretBox
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.const i... |
from __future__ import print_function
import logging
import optparse
import pymongo
from .utils import do_db_auth, setup_logging
from ..arctic import Arctic
from ..hooks import get_mongodb_uri
logger = logging.getLogger(__name__)
def main():
usage = """usage: %prog [options]
Deletes the named library fr... |
import homeassistant.components.notify as notify_comp
from homeassistant.setup import async_setup_component
from tests.common import assert_setup_component
async def test_setup_full(hass):
"""Test valid configuration."""
await async_setup_component(
hass,
"homematic",
{"homematic": {... |
import json
from io import StringIO
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.urls import reverse
from jsonschema import validate
from weblate_schemas import load_schema
from weblate.lang.models import Language
fr... |
from datetime import timedelta
import logging
import threading
import aiohttp
from amcrest import AmcrestError, Http, LoginError
import voluptuous as vol
from homeassistant.auth.permissions.const import POLICY_CONTROL
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR
from homeassistant.compo... |
import asyncio
import json
import logging
from serial import SerialException
import serial_asyncio
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_VALUE_TEMPLATE, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback
impo... |
from typing import List
from typing import Mapping
from typing import Optional
import service_configuration_lib
from paasta_tools.kubernetes_tools import sanitised_cr_name
from paasta_tools.long_running_service_tools import LongRunningServiceConfig
from paasta_tools.long_running_service_tools import LongRunningServi... |
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
LightEntity,
)
from . import ElkEntity, create_elk_entities
from .const import DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Elk light platform."""
elk_data = hass.data[D... |
import unittest
import numpy as np
from pgmpy.factors.discrete import DiscreteFactor
from pgmpy.models import JunctionTree
from pgmpy.tests import help_functions as hf
class TestJunctionTreeCreation(unittest.TestCase):
def setUp(self):
self.graph = JunctionTree()
def test_add_single_node(self):
... |
import logging
import lw12
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_TRANSITION,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_EFFECT,
SUPPORT_TRANSITION,
LightEntity,
)
from homeassist... |
import struct
import time
import io
import cherrypy
from cherrypy._cpcompat import text_or_bytes
from cherrypy.lib import file_generator
from cherrypy.lib import is_closable_iterator
from cherrypy.lib import set_vary_header
_COMPRESSION_LEVEL_FAST = 1
_COMPRESSION_LEVEL_BEST = 9
def decode(encoding=None, default_... |
from typing import Dict
from synology_dsm.api.surveillance_station import SynoSurveillanceStation
from synology_dsm.api.surveillance_station.camera import SynoCamera
from homeassistant.components.camera import SUPPORT_STREAM, Camera
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typi... |
import pytest
import requests
import requests_mock
import homeassistant.components.facebox.image_processing as fb
import homeassistant.components.image_processing as ip
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_NAME,
CONF_FRIENDLY_NAME,
CONF_IP_ADDRESS,
CONF_PASSWORD,
CONF_PORT,
... |
from typing import Dict
from .model import Config, Integration
BASE = """
# This file is generated by script/hassfest/codeowners.py
# People marked here will be automatically requested for a review
# when the code that they own is touched.
# https://github.com/blog/2392-introducing-code-owners
# Home Assistant Core... |
import logging
from kalliope import Utils, BrainLoader
from kalliope.core import NeuronModule
from kalliope.core.NeuronModule import MissingParameterException
logging.basicConfig()
logger = logging.getLogger("kalliope")
class Brain(NeuronModule):
def __init__(self, **kwargs):
super(Brain, self).__init... |
import logging
from pyoppleio.OppleLightDevice import OppleLightDevice
import voluptuous as vol
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
PLATFORM_SCHEMA,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR_TEMP,
LightEntity,
)
from homeassistant.const import CONF_HOST, CON... |
from homeassistant import config_entries, setup
from homeassistant.components.profiler.const import DOMAIN
from tests.async_mock import patch
from tests.common import MockConfigEntry
async def test_form_user(hass):
"""Test we can setup by the user."""
await setup.async_setup_component(hass, "persistent_noti... |
import asyncio
import logging
from typing import Any, Dict, Iterable, Optional
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import Context, State
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import dt as dt_util
from . import (
ATTR_DATE,
ATTR_D... |
from __future__ import division
import numpy as np
import random
import six
from chainercv import utils
def random_distort(
img,
brightness_delta=32,
contrast_low=0.5, contrast_high=1.5,
saturation_low=0.5, saturation_high=1.5,
hue_delta=18):
"""A color related data augm... |
_DEV_NOTES = """
Overview of classes:
* PyComponent and JsComponent: the base class for creating Python/JS component.
* JSModule: represents a module in JS that corresponds to a Python module.
* Asset: represents an asset.
* Bundle: an Asset subclass to represent a collecton of JSModule's in one asset.
* AssetStore: ... |
import pandas as pd
import xarray as xr
from . import randn, requires_dask
try:
import dask # noqa: F401
except ImportError:
pass
def make_bench_data(shape, frac_nan, chunks):
vals = randn(shape, frac_nan)
coords = {"time": pd.date_range("2000-01-01", freq="D", periods=shape[0])}
da = xr.Data... |
import os
import pytest
from homeassistant import config as hass_config
from homeassistant.components.filesize import DOMAIN
from homeassistant.components.filesize.sensor import CONF_FILE_PATHS
from homeassistant.const import SERVICE_RELOAD
from homeassistant.setup import async_setup_component
from tests.async_mock... |
from datetime import datetime as dt
from sqlalchemy import (
Integer,
ForeignKey,
String,
DefaultClause,
func,
Column,
Text,
Boolean,
)
from sqlalchemy.orm import relationship
from sqlalchemy_utils import JSONType
from sqlalchemy_utils.types.arrow import ArrowType
from lemur.certifica... |
from lemur.plugins.bases import NotificationPlugin
class TestNotificationPlugin(NotificationPlugin):
title = "Test"
slug = "test-notification"
description = "Enables testing"
author = "Kevin Glisson"
author_url = "https://github.com/netflix/lemur.git"
def __init__(self, *args, **kwargs):
... |
from __future__ import division
from itertools import chain
from pygal import colors
from pygal.colors import darken, is_foreground_light, lighten
class Style(object):
"""Styling class containing colors for the css generation"""
plot_background = 'rgba(255, 255, 255, 1)'
background = 'rgba(249, 249, 2... |
import numpy as np
import six
from chainercv.utils.testing.assertions.assert_is_bbox import assert_is_bbox
def assert_is_detection_link(link, n_fg_class):
"""Checks if a link satisfies detection link APIs.
This function checks if a given link satisfies detection link APIs
or not.
If the link does n... |
from typing import Any
from typing import Mapping
from kazoo.client import KazooClient
from pyramid.view import view_config
from paasta_tools.api import settings
from paasta_tools.deployd.queue import ZKDelayDeadlineQueue
@view_config(route_name="deploy_queue.list", request_method="GET", renderer="json")
def list_... |
from flask import Flask
from flask import jsonify
from flasgger import Swagger
from flasgger import swag_from
app = Flask(__name__)
swag = Swagger(app)
@app.route("/example")
@swag_from({
"responses": {
400: {
"description": "Invalid action"
},
401: {
"description... |
def boot(application, config):
if config and config['origins']:
try:
from flask.ext.cors import CORS
for i in config.keys():
application.config['CORS_%s' % i.upper()] = config[i]
CORS(application)
except Exception as e:
raise Exception... |
from itertools import groupby
import numpy as np
import pandas as pd
def aggregate_returns(returns, convert_to):
"""
Aggregates returns by day, week, month, or year.
"""
def cumulate_returns(x):
return np.exp(np.log(1 + x).cumsum())[-1] - 1
if convert_to == 'weekly':
return retu... |
from contextlib import contextmanager
from typing import (
TYPE_CHECKING,
Any,
Dict,
Hashable,
Iterator,
Mapping,
Sequence,
Set,
Tuple,
Union,
cast,
)
import pandas as pd
from . import formatting, indexing
from .indexes import Indexes
from .merge import merge_coordinates_w... |
import os
import pytest
from PyQt5.QtCore import Qt
from qutebrowser.mainwindow import prompt as promptmod
from qutebrowser.utils import usertypes
class TestFileCompletion:
@pytest.fixture
def get_prompt(self, qtbot, config_stub, key_config_stub):
"""Get a function to display a prompt with a path.... |
import logging
import os.path
from gensim import interfaces, matutils
import dictionary # for constructing word->id mappings
logger = logging.getLogger('gensim.corpora.dmlcorpus')
class DmlConfig:
"""
DmlConfig contains parameters necessary for the abstraction of a 'corpus of
articles' (see the `DmlC... |
import logging
from http.client import (
HTTPConnection,
HTTPSConnection,
HTTPResponse,
)
from io import BytesIO
from vcr.request import Request
from vcr.errors import CannotOverwriteExistingCassetteException
from . import compat
log = logging.getLogger(__name__)
class VCRFakeSocket:
"""
A socke... |
import logging
import os
import re
import threading
import requests
import voluptuous as vol
from homeassistant.const import HTTP_OK
import homeassistant.helpers.config_validation as cv
from homeassistant.util import sanitize_filename
_LOGGER = logging.getLogger(__name__)
ATTR_FILENAME = "filename"
ATTR_SUBDIR = "... |
from homeassistant.components import google_assistant as ga
from homeassistant.core import Context
from homeassistant.setup import async_setup_component
from .test_http import DUMMY_CONFIG
async def test_request_sync_service(aioclient_mock, hass):
"""Test that it posts to the request_sync url."""
aioclient_... |
.encode('idna')
import gevent.monkey
gevent.monkey.patch_all()
import docker_registry.core.boto as coreboto
from docker_registry.core import compat
from docker_registry.core import exceptions
from docker_registry.core import lru
import logging
import os
import re
import time
import boto.exception
import boto.s3
im... |
import asyncio
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.media_player import DEVICE_CLASS_TV, MediaPlayerEntity
from homeassistant.components.media_player.const import (
MEDIA_TYPE_CHANNEL,
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_PLAY,
SUPPORT_PLAY_M... |
import errno
import glob
import os
import xml.etree.ElementTree as ElementTree
from meld.conf import _
from . import _vc
#: Simple enum constants for differentiating conflict cases.
CONFLICT_TYPE_MERGE, CONFLICT_TYPE_UPDATE = 1, 2
class Vc(_vc.Vc):
CMD = "svn"
NAME = "Subversion"
VC_DIR = ".svn"
... |
import os
import tempfile
from uuid import uuid4
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
class BaseStorage:
def __init__(self, name=None):
self.name = name
def save(self, data, mode='w'):
raise... |
import argparse
import sys
from paasta_tools import tron_tools
def parse_args():
parser = argparse.ArgumentParser(description="Cleans up stale Tron namespaces.")
parser.add_argument(
"-d",
"--soa-dir",
dest="soa_dir",
metavar="SOA_DIR",
default=tron_tools.DEFAULT_SOA_... |
from homeassistant.core import State
from homeassistant.setup import async_setup_component
VALID_TEXT1 = "Test text"
VALID_TEXT2 = "LoremIpsum"
INVALID_TEXT1 = "This text is too long!"
INVALID_TEXT2 = "Short"
async def test_reproducing_states(hass, caplog):
"""Test reproducing Input text states."""
# Setup... |
from django.contrib.messages import add_message, constants
def get_request(request):
"""Return Django request object even for DRF requests."""
return getattr(request, "_request", request)
def debug(request, message, extra_tags=""):
"""Add a message with the ``DEBUG`` level."""
if request is not Non... |
import logging
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import callback
from .const import (
COORDINATOR,
DOMAIN,
FLAME_ICON,
FLOW_OFF_ICON,
FLOW_ON_ICON,
IDLE_ICON,
)
from .sensor import ... |
import os.path
import subprocess
import perfkitbenchmarker
import pkg_resources
_STATIC_VERSION_FILE = 'version.txt'
def _GetVersion():
"""Gets the version from git or the static version file."""
# Try to pull the version from git.
root_dir = os.path.dirname(os.path.dirname(__file__))
git_dir = os.path.joi... |
from typing import Any, Callable, Dict, List, Optional
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
from . import WLEDDataUpdateCoordinator, WLED... |
import logging
import voluptuous as vol
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.components.vacuum import DOMAIN
from homeassistant.helpers.dispatcher import async_dispatc... |
import os.path as op
import gc
import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_equal,
assert_array_equal, assert_allclose)
from mne.datasets import testing
from mne import (read_forward_solution, apply_forward, apply_forward_raw,
... |
import logging
from typing import Dict, List
from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.helpers.entity import Entity
from .const import DOMAIN, MANUFACTURER, MODELS, SIGNAL_NAME
from .data_handler import NetatmoDataHandler
_LOGGER = logging.getLogger(__name__)
class NetatmoBase(Enti... |
import pytest
from homeassistant import core
from homeassistant.components import switch
from homeassistant.const import CONF_PLATFORM
from homeassistant.setup import async_setup_component
from tests.components.switch import common
@pytest.fixture(autouse=True)
def entities(hass):
"""Initialize the test switch... |
__version__ = '0.7.4'
import imp as pyimp # rename to avoid name conflict with objc_util
import logging
import logging.handlers
import os
import platform
import sys
from io import IOBase
import six
from six import BytesIO, StringIO
from six.moves.configparser import ConfigParser
# noinspection PyPep8Naming
from .s... |
from django.core.management.base import CommandError
from weblate.auth.models import User
from weblate.machinery import MACHINE_TRANSLATION_SERVICES
from weblate.trans.autotranslate import AutoTranslate
from weblate.trans.management.commands import WeblateTranslationCommand
from weblate.trans.models import Component
... |
import pytest
from qstrader.utils.console import GREEN, BLUE, CYAN, string_colour
@pytest.mark.parametrize(
"text,colour,expected",
[
('green colour', GREEN, "\x1b[1;32mgreen colour\x1b[0m"),
('blue colour', BLUE, "\x1b[1;34mblue colour\x1b[0m"),
('cyan colour', CYAN, "\x1b[1;36mcyan... |
import asyncio
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
from homeassistant.const import CONF_API_KEY, HTTP_OK
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.... |
from homeassistant.components import mqtt
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.util import slugify
from .definitions import DEFINITIONS
DOMAIN = "dsmr_reader"
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):... |
from pgmpy.estimators import StructureScore
class ScoreCache(StructureScore):
def __init__(self, base_scorer, data, max_size=10000, **kwargs):
"""
A wrapper class for StructureScore instances, which implement a decomposable score,
that caches local scores.
Based on the global deco... |
import os
import unittest
class RoslibPackagesTest(unittest.TestCase):
def test_find_node(self):
import roslib.packages
d = roslib.packages.get_pkg_dir('roslib')
p = os.path.join(d, 'test', 'fake_node.py')
self.assertEquals([p], roslib.packages.find_node('roslib', 'fake_node.py')... |
import sys
import textwrap
import pytest
from tests.helpers import utils
try:
from scripts.dev import run_vulture
except ImportError:
if hasattr(sys, 'frozen'):
# Tests aren't going to run anyways because of the mark
pass
else:
raise
pytestmark = [pytest.mark.not_frozen]
clas... |
from typing import cast
from PyQt5.QtCore import pyqtSlot, QObject, QEvent
from PyQt5.QtGui import QKeyEvent, QWindow
from PyQt5.QtWidgets import QApplication
from qutebrowser.keyinput import modeman
from qutebrowser.misc import quitter
from qutebrowser.utils import objreg
class EventFilter(QObject):
"""Globa... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
from absl.testing import parameterized
from compare_gan import datasets
from compare_gan import test_utils
from compare_gan.gans import consts as c
from compare_gan.gans.modular_gan impo... |
import datetime
from decimal import Decimal
# Third-party imports
from sqlalchemy.inspection import inspect
from flask_sqlalchemy import SQLAlchemy # pylint: disable=import-error,no-name-in-module
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
db = SQLAlchemy... |
from kombu.asynchronous import get_event_loop
from .base import Request, Headers, Response
__all__ = ('Client', 'Headers', 'Response', 'Request')
def Client(hub=None, **kwargs):
"""Create new HTTP client."""
from .curl import CurlClient
return CurlClient(hub, **kwargs)
def get_client(hub=None, **kwar... |
from __future__ import unicode_literals
import sys
import os
import inspect
import codecs
import argparse
import tempfile
import warnings
from collections import Counter
from multiprocessing import cpu_count
#hack to get imports working if running this as a script, or within a package
if __name__ == '__main__':
... |
from flask import Flask
from flask_restful import Api, Resource, abort, reqparse
from flasgger import Swagger, swag_from
app = Flask(__name__)
api = Api(app)
app.config['SWAGGER'] = {
'title': 'Flasgger RESTful',
'uiversion': 2
}
swag = Swagger(app)
TODOS = {
'todo1': {'task': 'build an API'},
'tod... |
from aiohttp import web
# Relic from the past. Kept here so we can run negative tests.
HTTP_HEADER_HA_AUTH = "X-HA-access"
def mock_real_ip(app):
"""Inject middleware to mock real IP.
Returns a function to set the real IP.
"""
ip_to_mock = None
def set_ip_to_mock(value):
nonlocal ip_to... |
import voluptuous as vol
CONF_SCHEMA = "schema"
LEGACY = "legacy"
STATE = "state"
MQTT_VACUUM_SCHEMA = vol.Schema(
{
vol.Optional(CONF_SCHEMA, default=LEGACY): vol.All(
vol.Lower, vol.Any(LEGACY, STATE)
)
}
)
def services_to_strings(services, service_to_string):
"""Convert S... |
import logging
from pydelijn.api import Passages
from pydelijn.common import HttpException
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP
from homeassistant.helpers.aiohttp_client import async_get_clientses... |
import logging
from urllib.parse import urlparse
import voluptuous as vol
from homeassistant import config_entries, exceptions
from homeassistant.components import ssdp
from homeassistant.components.remote import (
ATTR_ACTIVITY,
ATTR_DELAY_SECS,
DEFAULT_DELAY_SECS,
)
from homeassistant.const import CONF... |
import time
import mock
import pytest
from pysensu_yelp import Status
from paasta_tools.check_oom_events import compose_sensu_status
from paasta_tools.check_oom_events import latest_oom_events
from paasta_tools.check_oom_events import main
from paasta_tools.check_oom_events import read_oom_events_from_scribe
@pyte... |
from __future__ import print_function
# by Siddharth Duahantha
# 28 July 2017
import sys
import argparse
COW = r""" \ ^__^
\ (oo)\_______
(__)\ )\/\\
||----w |
|| ||
"""
def get_cow(text):
"""create a string of a cow saying thing... |
from datetime import timedelta
from functools import partial, wraps
from inspect import getmodule
import logging
from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import CATEGORY_OTHER
from homeassistant.components import cover, vacuum
from homeassistan... |
import asyncio
import voluptuous as vol
from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components.auth import indieauth
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const impor... |
import unittest
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import K2Score
class TestK2Score(unittest.TestCase):
def setUp(self):
self.d1 = pd.DataFrame(
data={"A": [0, 0, 1], "B": [0, 1, 0], "C": [1, 1, 0], "D": ["X", "Y", "Z"]}
)
self.m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.