text stringlengths 213 32.3k |
|---|
import logging
from homeassistant.const import (
DEGREE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_ILLUMINANCE,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
ENERGY_WATT_HOUR,
FREQUENCY_HERTZ,
LENGTH_MILLIMETERS,
LIGHT_LUX,
PERCENTAGE,
POWER_WATT,
PRESSURE_HPA,
SPEED_KILO... |
import os
import shutil
import stat
from django.conf import settings
from translation_finder.finder import EXCLUDES
DEFAULT_DATA_DIR = os.path.join(settings.BASE_DIR, "data")
DEFAULT_TEST_DIR = os.path.join(settings.BASE_DIR, "data-test")
BUILD_DIR = os.path.join(settings.BASE_DIR, "build")
VENV_DIR = os.path.join(s... |
from adafruit_mcp230xx.mcp23017 import MCP23017 # pylint: disable=import-error
import board # pylint: disable=import-error
import busio # pylint: disable=import-error
import digitalio # pylint: disable=import-error
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassis... |
import pytest
from homeassistant.components.input_select import (
ATTR_OPTION,
ATTR_OPTIONS,
CONF_INITIAL,
DOMAIN,
SERVICE_SELECT_NEXT,
SERVICE_SELECT_OPTION,
SERVICE_SELECT_PREVIOUS,
SERVICE_SET_OPTIONS,
)
from homeassistant.const import (
ATTR_EDITABLE,
ATTR_ENTITY_ID,
AT... |
from functools import partial
import ipaddress
import getmac
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from . import MinecraftServer, helpers
from .const import ( # pylint: di... |
import pytest
from redbot.core.rpc import RPC, RPCMixin
from unittest.mock import MagicMock
__all__ = ["rpc", "rpcmixin", "cog", "existing_func", "existing_multi_func"]
@pytest.fixture()
def rpc():
return RPC()
@pytest.fixture()
def rpcmixin():
r = RPCMixin()
r.rpc = MagicMock(spec=RPC)
return r
... |
import keras
import keras.backend as K
import tensorflow as tf
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine import hyper_spaces
class MatchLSTM(BaseModel):
"""
Match LSTM model.
Examples:
>>> model = MatchLSTM()
>>> model.... |
import logging
from RFXtrx import ControlEvent, SensorEvent
from homeassistant.components.sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
)
from homeassistant.const import (
CONF_DEVICES,
DEVICE_CLASS_CURRENT,
DEVICE_CLA... |
import unittest
from absl import flags
from absl.testing import parameterized
import mock
from perfkitbenchmarker.linux_packages import gce_hpc_tools
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
_GITHASH = 'abcdef'
def _YumInstall():
vm = mock.Mock(RemoteCommand=mock.Mock(return_value=(_GITHASH, '... |
import json
from lark import Lark
from lark.reconstruct import Reconstructor
from _json_parser import json_grammar
test_json = '''
{
"empty_object" : {},
"empty_array" : [],
"booleans" : { "YES" : true, "NO" : false },
"numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
... |
from django.db import models
from weblate.trans.fields import RegexField
class Variant(models.Model):
component = models.ForeignKey("Component", on_delete=models.deletion.CASCADE)
variant_regex = RegexField(max_length=190)
key = models.CharField(max_length=190, db_index=True)
class Meta:
un... |
from pytest import mark
from cerberus import errors
from cerberus.tests import assert_fail, assert_success
@mark.parametrize(
("test_function", "document"),
[
(assert_success, {'this_field': {}}),
(assert_success, {'that_field': {}}),
(assert_success, {}),
(assert_fail, {'tha... |
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail import EmailMessage
from django.core.mail import send_mail
from django.template import loader
from django.utils.translation import activate
from django.utils.translation import get_language
from django.utils.translation... |
import aiohttp
from homeassistant import config_entries, setup
from homeassistant.components.nws.const import DOMAIN
from tests.async_mock import patch
async def test_form(hass, mock_simple_nws_config):
"""Test we get the form."""
hass.config.latitude = 35
hass.config.longitude = -90
await setup.a... |
import graphviz
from typing import Optional, Text, Iterable
from tensornetwork.network_components import AbstractNode
#pylint: disable=no-member
def to_graphviz(nodes: Iterable[AbstractNode],
graph: Optional[graphviz.Graph] = None,
include_all_names: bool = False,
engi... |
import numpy as np
from ...utils import verbose
from ._utils import _fetch_one, _data_path, _on_missing, AGE_SLEEP_RECORDS
from ._utils import _check_subjects
data_path = _data_path # expose _data_path(..) as data_path(..)
BASE_URL = 'https://physionet.org/physiobank/database/sleep-edfx/sleep-cassette/' # noqa: E... |
import os
from docutils.parsers.rst import directives
from docutils.parsers.rst.directives.images import Image, Figure
from nikola.plugin_categories import RestExtension
class Plugin(RestExtension):
"""Plugin for thumbnail directive."""
name = "rest_thumbnail"
def set_site(self, site):
"""Set... |
from nikola.plugin_categories import Taxonomy
from nikola import utils
class ClassifyTags(Taxonomy):
"""Classify the posts by tags."""
name = "classify_tags"
classification_name = "tag"
overview_page_variable_name = "tags"
overview_page_items_variable_name = "items"
more_than_one_classifica... |
from functools import partial
from twtxt.mentions import format_mentions
def mock_mention_format(name, url, expected_name, expected_url):
assert name == expected_name
assert url == expected_url
if name:
return '@' + name
else:
return name
def test_format_mentions():
texts = {'N... |
def combine_context_switchers(context_switchers):
"""Create a single context switcher from multiple switchers.
`context_switchers` is a list of functions that take a frame as an
argument and return a string to use as the new context label.
Returns a function that composites `context_switchers` functi... |
import json
import os
from tempfile import NamedTemporaryFile
from urllib.parse import urlparse
import yaml
from behave import given
from behave import when
from itest_utils import get_service_connection_string
from paasta_tools import marathon_tools
from paasta_tools import utils
from paasta_tools.api.client import... |
import unittest
import numpy as np
import numpy.testing as np_test
from pgmpy.models import NoisyOrModel
class TestNoisyOrModelInit(unittest.TestCase):
def test_init(self):
model = NoisyOrModel(
["x1", "x2", "x3"], [2, 3, 2], [[0.6, 0.4], [0.2, 0.4, 0.7], [0.1, 0.4]]
)
np_test... |
import asyncio
import logging
from arcam.fmj import ConnectionFailed
from arcam.fmj.client import Client
import async_timeout
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP
import homeassistant.helpers.config_validation as cv
from homeassistant... |
import unittest
import numpy as np
from chainer import testing
from chainercv.transforms import rotate_bbox
from chainercv.utils import generate_random_bbox
@testing.parameterize(*testing.product({
'angle': [180, 90, 0, -90, -180]
}))
class TestRotateBbox(unittest.TestCase):
def test_rotate_bbox(self):
... |
import posixpath
from absl import flags
from perfkitbenchmarker import os_types
from perfkitbenchmarker import vm_util
FLAGS = flags.FLAGS
flags.DEFINE_integer(
'gluster_replicas', 3,
'The number of Gluster replicas.')
flags.DEFINE_integer(
'gluster_stripes', 1,
'The number of Gluster stripes.')
d... |
from datetime import timedelta
from homeassistant.components.vera import SubscriptionRegistry
from homeassistant.core import HomeAssistant
from homeassistant.util.dt import utcnow
from tests.async_mock import MagicMock
from tests.common import async_fire_time_changed
async def test_subscription_registry(hass: Home... |
import json
import os
import time
from august.activity import (
ACTIVITY_ACTIONS_DOOR_OPERATION,
ACTIVITY_ACTIONS_DOORBELL_DING,
ACTIVITY_ACTIONS_DOORBELL_MOTION,
ACTIVITY_ACTIONS_DOORBELL_VIEW,
ACTIVITY_ACTIONS_LOCK_OPERATION,
DoorbellDingActivity,
DoorbellMotionActivity,
DoorbellView... |
from collections import OrderedDict
from contextlib import contextmanager
import time
from absl import flags
from perfkitbenchmarker import sample
MEASUREMENTS_FLAG_NAME = 'timing_measurements'
# Valid options that can be included in the flag's list value.
MEASUREMENTS_NONE = 'none'
MEASUREMENTS_END_TO_END_RUNTIME ... |
import os
import unittest
from perfkitbenchmarker import test_util
from perfkitbenchmarker.linux_benchmarks import mxnet_benchmark
class MxnetBenchmarkTestCase(unittest.TestCase,
test_util.SamplesTestMixin):
def setUp(self):
path = os.path.join(os.path.dirname(__file__), '..', 'd... |
import re
from collections import defaultdict
from appconf import AppConf
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import Group as DjangoGroup
from django.db import models
from django.db.models.signals import m2m_chang... |
from __future__ import print_function
import os
import sys
import argparse
import paramiko
SSH_DIRS = [os.path.expanduser('~/.ssh'), os.path.join(os.environ['STASH_ROOT'], '.ssh')]
key_mode = {'rsa': 'rsa', 'dsa': 'dss'}
def main(args):
ap = argparse.ArgumentParser(args)
ap.add_argument('-t', choices=('rsa... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from absl import flags
from perfkitbenchmarker import configs
from perfkitbenchmarker import disk
from perfkitbenchmarker import sample
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.... |
from .common import *
class TrashMixin(object):
def list_trash(self) -> list:
"""Retrieves top-level trash list"""
return self.BOReq.paginated_get(self.metadata_url + 'trash')
def move_to_trash(self, node_id: str) -> dict:
r = self.BOReq.put(self.metadata_url + 'trash/' + node_id)
... |
from typing import List
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import toggle_entity
from homeassistant.const import CONF_DOMAIN
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers... |
import os
from ._config import ROOT_DIR
from invoke import task
@task
def copyright(ctx):
""" list usage of copyright notices
The use of copyright notices should be limited to files that are likely
to be used in other projects, or to make appropriate attributions for code
taken from other projects... |
from unittest.mock import Mock
import pandas as pd
import pytest
import pytz
from qstrader.alpha_model.fixed_signals import FixedSignalsAlphaModel
@pytest.mark.parametrize(
'signals',
[
({'EQ:SPY': 0.75, 'EQ:AGG': 0.75, 'EQ:GLD': 0.75}),
({'EQ:SPY': -0.25, 'EQ:AGG': -0.25, 'EQ:GLD': -0.25})... |
import numpy as np
import unittest
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
from chainercv.experimental.links.model.fcis import FCISTrainChain
from chainercv.utils import mask_to_bbox
from tests.experimental_tests.links_tests.model_tests.fcis_tests.test_fcis \
... |
class Signal(object):
"""
This Class is representing a Signal which is corresponding to an input action that should start executing neuron
list when triggered
"""
def __init__(self, name=None, parameters=None):
self.name = name
self.parameters = parameters
def serialize(self):... |
import os
import os.path
import textwrap
import attr
import pytest
import bs4
from qutebrowser.utils import utils
def collect_tests():
basedir = os.path.dirname(__file__)
datadir = os.path.join(basedir, 'data', 'hints', 'html')
files = [f for f in os.listdir(datadir) if f != 'README.md']
return fil... |
from datetime import timedelta
from geizhals import Device, Geizhals
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.u... |
import logging
import redis
from docker_registry.core import lru
from . import config
logger = logging.getLogger(__name__)
redis_conn = None
cache_prefix = None
cfg = config.load()
def init():
enable_redis_cache(cfg.cache, cfg.storage_path)
enable_redis_lru(cfg.cache_lru, cfg.storage_path)
def enable... |
async def test_sending_location(hass, create_registrations, webhook_client):
"""Test sending a location via a webhook."""
resp = await webhook_client.post(
"/api/webhook/{}".format(create_registrations[1]["webhook_id"]),
json={
"type": "update_location",
"data": {
... |
import copy
import pytest
from molecule import scenarios
@pytest.fixture
def _instance(config_instance):
config_instance_1 = copy.deepcopy(config_instance)
config_instance_1.config['scenario']['name'] = 'two'
config_instance_1.molecule_file = \
config_instance_1.molecule_file.replace('default',... |
from os import environ
import ssl
import certifi
def client_context() -> ssl.SSLContext:
"""Return an SSL context for making requests."""
# Reuse environment variable definition from requests, since it's already a requirement
# If the environment variable has no value, fall back to using certs from cer... |
import pytest
from homeassistant.components.geonetnz_quakes import (
CONF_MINIMUM_MAGNITUDE,
CONF_MMI,
DOMAIN,
)
from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_RADIUS,
CONF_SCAN_INTERVAL,
CONF_UNIT_SYSTEM,
)
from tests.common import MockConfigEntry
@pytest.fix... |
import sys, os, tempfile, shutil
from os.path import join, dirname, abspath
import datetime, time
from six.moves import range
from logilab.common.testlib import TestCase, unittest_main
from logilab.common.shellutils import (globfind, find, ProgressBar,
RawInput)
from logilab.c... |
from unittest import TestCase
from weblate.checks.chars import (
BeginNewlineCheck,
BeginSpaceCheck,
DoubleSpaceCheck,
EndColonCheck,
EndEllipsisCheck,
EndExclamationCheck,
EndNewlineCheck,
EndQuestionCheck,
EndSemicolonCheck,
EndSpaceCheck,
EndStopCheck,
EscapedNewline... |
from __future__ import print_function
import os
import sys
import argparse
import zipfile
def main(args):
ap = argparse.ArgumentParser()
ap.add_argument('zipfile', help='')
ap.add_argument('list', nargs='+', help='')
ap.add_argument('-v', '--verbose', action='store_true', help='be more chatty')
... |
import copy
import json
import pytest
from homeassistant import data_entry_flow
from homeassistant.components import dialogflow, intent_script
from homeassistant.config import async_process_ha_core_config
from homeassistant.core import callback
from homeassistant.setup import async_setup_component
SESSION_ID = "a9b... |
from io import StringIO
from django.core.management import call_command
from django.test import SimpleTestCase
from weblate.trans.tests.test_commands import WeblateComponentCommandTestCase
from weblate.trans.tests.test_models import RepoTestCase
class ListSameCommandTest(RepoTestCase):
def setUp(self):
... |
import gc
import sys
import weakref
from flexx.util.testing import run_tests_if_main, skipif, skip, raises
from flexx.event.both_tester import run_in_both, this_is_js
from flexx.util.logging import capture_log
from flexx import event
loop = event.loop
logger = event.logger
## Greedy reactions
class MyObject1(ev... |
from __future__ import print_function
__docformat__ = "restructuredtext en"
try:
import readline
except ImportError:
readline = None
import os
import os.path as osp
import sys
from pdb import Pdb
import inspect
from logilab.common.compat import StringIO
try:
from IPython import PyColorize
except Import... |
import argparse
import glob
import os
import struct
import sys
def clamp_to_min_max(value, min, max):
if value > max:
value = max
elif value < min:
value = min
return value
def clamp_to_u8(value):
return clamp_to_min_max(value, 0, 255)
def parse_args():
parser = argparse.Argum... |
import unittest
import pandas as pd
import numpy as np
from pgmpy.estimators import MmhcEstimator, K2Score
from pgmpy.factors.discrete import TabularCPD
from pgmpy.models import BayesianModel
class TestMmhcEstimator(unittest.TestCase):
def setUp(self):
self.data1 = pd.DataFrame(
np.random.r... |
from django.conf.urls import url
from django.contrib import admin
from django.db.models import Sum
from django.forms import models, ValidationError
from django.http import HttpResponse
from django.template.loader import select_template
from django.urls import reverse
from django.utils import timezone
from django.utils... |
import urwid
choices = u'Chapman Cleese Gilliam Idle Jones Palin'.split()
def menu(title, choices):
body = [urwid.Text(title), urwid.Divider()]
for c in choices:
button = urwid.Button(c)
urwid.connect_signal(button, 'click', item_chosen, c)
body.append(urwid.AttrMap(button, None, focu... |
import sys
from unittest import TestCase
import numpy as np
import pandas as pd
from scattertext import LogOddsRatioUninformativeDirichletPrior, scale
from scattertext import ScatterChart
from scattertext.ScatterChart import CoordinatesNotRightException, TermDocMatrixHasNoMetadataException, \
NeedToInjectCoordin... |
import aiohttp
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.adguard import config_flow
from homeassistant.components.adguard.const import DOMAIN
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_SSL,
CONF_USERNAME,
CONF_VERIF... |
from __future__ import division
from builtins import range
import numpy as np
from .format_data import format_data as formatter
from .._shared.helpers import memoize
@memoize
def normalize(x, normalize='across', internal=False, format_data=True):
"""
Z-transform the columns or rows of an array, or list of ... |
import os
import tensorflow as tf
from datasets import dataset_utils
slim = tf.contrib.slim
VOC_LABELS = {
'none': (0, 'Background'),
'aeroplane': (1, 'Vehicle'),
'bicycle': (2, 'Vehicle'),
'bird': (3, 'Animal'),
'boat': (4, 'Vehicle'),
'bottle': (5, 'Indoor'),
'bus': (6, 'Vehicle'),
... |
import pytest
import sh
from molecule import config
from molecule.verifier.lint import yamllint
@pytest.fixture
def _patched_get_tests(mocker):
m = mocker.patch('molecule.verifier.lint.yamllint.Yamllint._get_tests')
m.return_value = ['test1', 'test2', 'test3']
return m
@pytest.fixture
def _verifier_l... |
import flatbuffers
class HelloNew(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsHelloNew(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = HelloNew()
x.Init(buf, n + offset)
return x
# HelloNew
def Init(self, buf,... |
from aioambient import Client
from aioambient.errors import AmbientError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY
from homeassistant.helpers import aiohttp_client
from .const import CONF_APP_KEY, DOMAIN # pylint: disable=unused-import
class Amb... |
from cerberus import Validator
from cerberus.tests import assert_fail, assert_normalized, assert_success
def test_allow_unknown_in_schema():
schema = {
'field': {
'type': 'dict',
'allow_unknown': True,
'schema': {'nested': {'type': 'string'}},
}
}
docum... |
import tests
import unittest
import sys
from pyVim import connect
from pyVmomi import vim
if sys.version_info >= (3, 3):
from unittest.mock import patch, MagicMock
else:
from mock import patch, MagicMock
class ConnectionTests(tests.VCRTestBase):
@tests.VCRTestBase.my_vcr.use_cassette('basic_connection... |
import glances_api
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_SCAN_INTERVAL,
CONF_SSL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import callba... |
import pytest
from homeassistant.auth.providers import homeassistant as hass_auth
from homeassistant.scripts import auth as script_auth
from tests.async_mock import Mock, patch
from tests.common import register_auth_provider
@pytest.fixture
def provider(hass):
"""Home Assistant auth provider."""
provider =... |
import logging
from homeassistant.components import litejet
from homeassistant.components.switch import SwitchEntity
ATTR_NUMBER = "number"
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the LiteJet switch platform."""
litejet_ = hass.d... |
from pycoolmasternet_async import CoolMasterNet
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.const import CONF_HOST, CONF_PORT
# pylint: disable=unused-import
from .const import AVAILABLE_MODES, CONF_SUPPORTED_MODES, DEFAULT_PORT, DOMAIN
MODES_SCHEMA = {vol.Required(mod... |
import asyncio
from collections.abc import Iterable
import logging
from typing import Optional, Sequence
from pysmartthings import Attribute, Capability
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN, ClimateEntity
from homeassistant.components.climate.const import (
ATTR_HVAC_MODE,
AT... |
import os
import pytest
from molecule import config
from molecule.verifier import goss
from molecule.verifier.lint import yamllint
@pytest.fixture
def _patched_ansible_verify(mocker):
m = mocker.patch('molecule.provisioner.ansible.Ansible.verify')
m.return_value = 'patched-ansible-verify-stdout'
retur... |
import my_pypi_dependency
from homeassistant import config_entries
from homeassistant.helpers import config_entry_flow
from .const import DOMAIN
async def _async_has_devices(hass) -> bool:
"""Return if there are devices that can be discovered."""
# TODO Check if there are any devices that can be discovered... |
import base64
import io
import logging
import smart_open.bytebuffer
import smart_open.constants
try:
import azure.storage.blob
import azure.core.exceptions
except ImportError:
MISSING_DEPS = True
logger = logging.getLogger(__name__)
_BINARY_TYPES = (bytes, bytearray, memoryview)
"""Allowed binary buffe... |
import unittest
import re
import os.path
import codecs
from mock import MagicMock, call, patch
from uiautomator import AutomatorDevice, Selector
class TestDevice(unittest.TestCase):
def setUp(self):
self.device = AutomatorDevice()
self.device.server = MagicMock()
self.device.server.jsonr... |
from django.test import TestCase
from weblate.checks.consistency import PluralsCheck, SamePluralsCheck, TranslatedCheck
from weblate.checks.models import Check
from weblate.checks.tests.test_checks import MockUnit
from weblate.trans.models import Change
from weblate.trans.tests.test_views import ViewTestCase
class ... |
import codecs
import platform
import six
try:
from shutil import get_terminal_size
except ImportError:
from backports.shutil_get_terminal_size import get_terminal_size
from colorama import init
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supp... |
import logging
from pyhap.const import CATEGORY_HUMIDIFIER
from homeassistant.components.humidifier.const import (
ATTR_HUMIDITY,
ATTR_MAX_HUMIDITY,
ATTR_MIN_HUMIDITY,
DEFAULT_MAX_HUMIDITY,
DEFAULT_MIN_HUMIDITY,
DEVICE_CLASS_DEHUMIDIFIER,
DEVICE_CLASS_HUMIDIFIER,
DOMAIN,
SERVICE_S... |
from homeassistant.components.group import (
DOMAIN,
GROUP_SCHEMA,
GroupIntegrationRegistry,
)
from homeassistant.config import GROUP_CONFIG_PATH
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.he... |
import numpy as np
import pytest
import tensornetwork as tn
from tensornetwork.block_sparse import (BlockSparseTensor, Index, BaseCharge,
U1Charge)
@pytest.mark.parametrize("num_charges", [1, 2])
def test_sparse_shape(num_charges):
np.random.seed(10)
dtype = np.float64
s... |
from typing import Dict
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DISKS
from homeassistant.helpers.typing import HomeAssistantType
from . import SynologyDSMDeviceEntity, SynologyDSMEntity
from .const... |
from itertools import cycle
from functools import partial
import numpy as np
from .utils import plt_show
def circular_layout(node_names, node_order, start_pos=90, start_between=True,
group_boundaries=None, group_sep=10):
"""Create layout arranging nodes on a circle.
Parameters
----... |
from __future__ import print_function
__docformat__ = "restructuredtext en"
import os
import glob
import shutil
import stat
import sys
import tempfile
import time
import fnmatch
import errno
import string
import random
import subprocess
from os.path import exists, isdir, islink, basename, join
from six import strin... |
import sys
import argparse
import openrazer.client
import openrazer.client.constants as c
def ripple_single_type() -> callable:
"""
Creates a simple callable which will convert int, int, int, float
:return: Function
:rtype: callable
"""
count = 0
def parse(arg_value):
nonlocal c... |
import cherrypy
from cherrypy.test import helper
class WSGI_VirtualHost_Test(helper.CPWebCase):
@staticmethod
def setup_server():
class ClassOfRoot(object):
def __init__(self, name):
self.name = name
@cherrypy.expose
def index(self):
... |
import posixpath
from absl import flags
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.linux_packages import cuda_toolkit
from perfkitbenchmarker.linux_packages import google_cloud_sdk
flags.DEFINE_string('nccl_version', '2.7.8-1',
'NCCL version to install. '
'I... |
import numpy as np
from numpy.testing import assert_allclose
import pytest
from scipy.signal import hilbert
from mne.connectivity import envelope_correlation
def _compute_corrs_orig(data):
# This is the version of the code by Sheraz and Denis.
# For this version (epochs, labels, time) must be -> (labels, ti... |
from homeassistant.components.accuweather.const import DOMAIN
from homeassistant.config_entries import (
ENTRY_STATE_LOADED,
ENTRY_STATE_NOT_LOADED,
ENTRY_STATE_SETUP_RETRY,
)
from homeassistant.const import STATE_UNAVAILABLE
from tests.async_mock import patch
from tests.common import MockConfigEntry
from... |
import functools
import os
import tempfile
from absl import flags
from perfkitbenchmarker import version
_PERFKITBENCHMARKER = 'perfkitbenchmarker'
_RUNS = 'runs'
_VERSIONS = 'versions'
_TEMP_DIR = os.path.join(tempfile.gettempdir(), _PERFKITBENCHMARKER)
flags.DEFINE_string('temp_dir', _TEMP_DIR, 'Temp directory P... |
import urllib
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.doorbird import CONF_CUSTOM_URL, CONF_TOKEN
from homeassistant.components.doorbird.const import CONF_EVENTS, DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from test... |
import time
from kalliope.core.NeuronModule import NeuronModule
class Systemdate(NeuronModule):
def __init__(self, **kwargs):
# get the cache if set by the user, if not, set it to false as it is not necessary
cache = kwargs.get('cache', None)
if cache is not None:
kwargs["cac... |
from unittest import mock
from aiohomekit import AccessoryDisconnectedError
from aiohomekit.testing import FakePairing
from homeassistant.components.climate.const import (
SUPPORT_TARGET_HUMIDITY,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY
from tests.compo... |
import logging
from homeassistant.components.alarm_control_panel import AlarmControlPanelEntity
from homeassistant.components.alarm_control_panel.const import SUPPORT_ALARM_ARM_AWAY
from homeassistant.const import (
ATTR_ATTRIBUTION,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_DISARMED,
)
from .const import DEFA... |
from __future__ import print_function, division
import warnings
from abc import abstractmethod
import datetime
from plumbum.lib import six
from plumbum.cli.termsize import get_terminal_size
import sys
class ProgressBase(six.ABC):
"""Base class for progress bars. Customize for types of progress bars.
:param ... |
import pytest
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.components import mqtt
from homeassistant.setup import async_setup_component
from tests.async_mock import patch
from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
def mock_finish_setup():
"""... |
import pytest
from qstrader.asset.cash import Cash
@pytest.mark.parametrize(
'currency,expected',
[
('USD', 'USD'),
('GBP', 'GBP'),
('EUR', 'EUR')
]
)
def test_cash(currency, expected):
"""
Tests that the Cash asset is correctly instantiated.
"""
cash = Cash(curre... |
import json
from libpurecool.const import (
FanPower,
FanSpeed,
FanState,
FocusMode,
HeatMode,
HeatState,
HeatTarget,
)
from libpurecool.dyson_pure_hotcool import DysonPureHotCool
from libpurecool.dyson_pure_hotcool_link import DysonPureHotCoolLink
from libpurecool.dyson_pure_state import ... |
import weakref
from ._action import BaseDescriptor
def emitter(func):
""" Decorator to turn a method of a Component into an
:class:`Emitter <flexx.event.Emitter>`.
An emitter makes it easy to emit specific events, and is also a
placeholder for documenting an event.
.. code-block:: python
... |
from bson.objectid import ObjectId
from flask import Blueprint, request
from app.commons import build_response
from app.intents.models import Intent
train = Blueprint('train_blueprint', __name__,
url_prefix='/train')
@train.route('/<story_id>/data', methods=['POST'])
def save_training_data(story_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import re
from absl import flags
from perfkitbenchmarker import linux_packages
from perfkitbenchmarker import sample
GIT_REPO = 'https://github.com/RedisLabs/memtier_benchmark'
GIT_... |
from httpobs.conf import API_ALLOW_VERBOSE_STATS_FROM_PUBLIC, API_COOLDOWN
from httpobs.scanner import STATES
from httpobs.scanner.grader import get_score_description, GRADES
from httpobs.scanner.utils import valid_hostname
from httpobs.website import add_response_headers, sanitized_api_response
from flask import Blu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.