text stringlengths 213 32.3k |
|---|
import uuid
from nexia.home import NexiaHome
import requests_mock
from homeassistant.components.nexia.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from tests.async_mock import patch
from tests.common import MockConfigEntry, load_fixtur... |
import subprocess
import diamond.collector
from diamond.collector import str_to_bool
class NtpdCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(NtpdCollector, self).get_default_config_help()
config_help.update({
'ntpq_bin': 'Path to ... |
import dedupe
import dedupe.training as training
import unittest
class TrainingTest(unittest.TestCase):
def setUp(self):
field_definition = [{'field': 'name', 'type': 'String'}]
self.data_model = dedupe.Dedupe(field_definition).data_model
self.training_pairs = {
'match': [({"... |
import logging
import blebox_uniapi
from homeassistant.components.blebox.const import DOMAIN
from homeassistant.config_entries import ENTRY_STATE_NOT_LOADED, ENTRY_STATE_SETUP_RETRY
from .conftest import mock_config, patch_product_identify
async def test_setup_failure(hass, caplog):
"""Test that setup failure... |
import unittest
from unittest.mock import patch, Mock
from flask import Flask
from cryptography.x509 import DNSName
from lemur.plugins.lemur_acme import acme_handlers
class TestAcmeHandler(unittest.TestCase):
def setUp(self):
self.acme = acme_handlers.AcmeHandler()
# Creates a new Flask applica... |
import os.path as op
from numpy.testing import assert_array_equal
from scipy import io as sio
from mne.io import read_raw_eximia
from mne.io.tests.test_raw import _test_raw_reader
from mne.utils import run_tests_if_main
from mne.datasets.testing import data_path, requires_testing_data
@requires_testing_data
def te... |
import logging
from homeassistant.components.alarm_control_panel import DOMAIN, AlarmControlPanelEntity
from homeassistant.components.alarm_control_panel.const import SUPPORT_ALARM_ARM_AWAY
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED,
)
from homeas... |
import homeassistant.components.automation as automation
from homeassistant.core import CoreState
from homeassistant.setup import async_setup_component
from tests.async_mock import AsyncMock, patch
from tests.common import async_mock_service
async def test_if_fires_on_hass_start(hass):
"""Test the firing when H... |
import os
import shutil
import tempfile
from radicale import Application, config
from radicale.tests import BaseTest
from radicale.tests.helpers import get_file_content
class TestBaseRightsRequests(BaseTest):
"""Tests basic requests with rights."""
def setup(self):
self.configuration = config.load(... |
from homeassistant.components.zwave import switch
from tests.async_mock import patch
from tests.mock.zwave import MockEntityValues, MockNode, MockValue, value_changed
def test_get_device_detects_switch(mock_openzwave):
"""Test get_device returns a Z-Wave switch."""
node = MockNode()
value = MockValue(da... |
import asyncio
import aiodns
from mcstatus.pinger import PingResponse
from homeassistant.components.minecraft_server.const import (
DEFAULT_NAME,
DEFAULT_PORT,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from homeassistant... |
import pytest
import homeassistant.components.google as google
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.setup import async_setup_component
from tests.async_mock import patch
@pytest.fixture(name="google_setup")
def mock_google_setup(hass):
"""Mock the google set up ... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hostname(host):
assert 'delegated-instance-openstack' == host.check_output('hostname -s')
def test_etc_molecule_directory(host):... |
from nexia.const import (
OPERATION_MODE_AUTO,
OPERATION_MODE_COOL,
OPERATION_MODE_HEAT,
OPERATION_MODE_OFF,
SYSTEM_STATUS_COOL,
SYSTEM_STATUS_HEAT,
SYSTEM_STATUS_IDLE,
UNIT_FAHRENHEIT,
)
import voluptuous as vol
from homeassistant.components.climate import ClimateEntity
from homeassis... |
import pytest
import os
boto3 = pytest.importorskip("boto3")
import boto3 # NOQA
import botocore # NOQA
import vcr # NOQA
try:
from botocore import awsrequest # NOQA
botocore_awsrequest = True
except ImportError:
botocore_awsrequest = False
# skip tests if boto does not use vendored requests anymo... |
import logging
from homeassistant.helpers.entity import Entity
from . import DOMAIN
from .const import (
KEY_CONSUMER,
KEY_IDENTIFIER,
KEY_MEASUREMENT,
KEY_PARENT_MAC,
KEY_PARENT_NAME,
KEY_UNIT,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_add_... |
from __future__ import division
def normalize_float(f):
"""Round float errors"""
if abs(f - round(f)) < .0000000000001:
return round(f)
return f
def rgb_to_hsl(r, g, b):
"""Convert a color in r, g, b to a color in h, s, l"""
r = r or 0
g = g or 0
b = b or 0
r /= 255
g /=... |
import pytest
import homeassistant.components.automation as automation
from homeassistant.const import ATTR_ENTITY_ID, ENTITY_MATCH_ALL, SERVICE_TURN_OFF
from homeassistant.core import Context
from homeassistant.setup import async_setup_component
from tests.common import async_mock_service, mock_component
@pytest.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from absl.third_party import unittest3_backport
class TextTestResult(unittest3_backport.TextTestResult):
"""TestResult class that provides the default text result formatting."""
def __in... |
from app.wraps.login_wrap import login_required
from app import app
from app.utils import ResponseUtil, RequestUtil, AuthUtil
from app.database.model import History
# get history list
@app.route('/api/history/list', methods=['GET'])
@login_required()
def api_history_list():
# login user
user_id = RequestUtil... |
from ._action import BaseDescriptor
class Attribute(BaseDescriptor):
""" Attributes are (readonly, and usually static) values associated with
Component classes. They expose and document a value without
providing means of observing changes like ``Property`` does. (The
actual value is taken from ``comp... |
import pytest
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.sonos import DOMAIN
from homeassistant.const import CONF_HOSTS
from tests.async_mock import Mock, patch as patch
from tests.common import MockConfigEntry
@pytest.fixture(name="config_entry")
def config... |
from .base_classes import ContainerCommand, Command
from .package import Package
from .utils import NoEscape
class PageStyle(ContainerCommand):
r"""Allows the creation of new page styles."""
_latex_name = "fancypagestyle"
packages = [Package('fancyhdr')]
def __init__(self, name, *, header_thicknes... |
from sqlalchemy import BigInteger, Boolean, Column, ForeignKey, Integer, String
from lemur.database import db
class ApiKey(db.Model):
__tablename__ = "api_keys"
id = Column(Integer, primary_key=True)
name = Column(String)
user_id = Column(Integer, ForeignKey("users.id"))
ttl = Column(BigInteger)... |
from datetime import timedelta
import logging
import praw
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_MAXIMUM,
CONF_PASSWORD,
CONF_USERNAME,
)
import homeassistant.helpers.config_va... |
__all__ = ["BetterHtmlFormatter"]
__version__ = "0.1.4"
import enum
import re
import warnings
from pygments.formatters.html import HtmlFormatter
MANY_SPACES = re.compile("( +)")
def _sp_to_nbsp(m):
return " " * (m.end() - m.start())
class BetterLinenos(enum.Enum):
TABLE = "table"
OL = "ol"
c... |
import attr
from PyQt5.QtCore import QUrl, QPoint
import pytest
tabhistory = pytest.importorskip('qutebrowser.browser.webkit.tabhistory')
from qutebrowser.misc.sessions import TabHistoryItem as Item
from qutebrowser.utils import qtutils
pytestmark = pytest.mark.qt_log_ignore('QIODevice::read.*: device not open')
... |
from django.db.models import Q
from pyparsing import CaselessLiteral
from pyparsing import Combine
from pyparsing import OneOrMore
from pyparsing import Optional
from pyparsing import ParseResults
from pyparsing import StringEnd
from pyparsing import Word
from pyparsing import WordEnd
from pyparsing import alphas
fro... |
from copy import copy
from django.contrib.messages import ERROR
from django.test import SimpleTestCase
from django.urls import reverse
from weblate.trans.forms import SimpleUploadForm
from weblate.trans.models import ComponentList
from weblate.trans.tests.test_views import ViewTestCase
from weblate.trans.tests.utils... |
from homeassistant import config_entries, setup
from homeassistant.components.NEW_DOMAIN.const import (
DOMAIN,
OAUTH2_AUTHORIZE,
OAUTH2_TOKEN,
)
from homeassistant.helpers import config_entry_oauth2_flow
from tests.async_mock import patch
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
async def test_full_f... |
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_MESSAGE,
ATTR_TITLE,
DOMAIN,
SERVICE_NOTIFY,
)
from homeassistant.loader import bind_hass
@bind_hass
def send_message(hass, message, title=None, data=None):
"""Send a notification message."""
info = {ATTR_MESSAGE: message}
... |
from distutils.version import LooseVersion
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
from scipy import linalg
import pytest
from mne.utils import _sym_mat_pow, _reg_pinv, requires_version
@requires_version('numpy', '1.17') # pinv bugs
@pytest.mark.parametrize('dtype', (np.flo... |
from tesla_powerwall import MissingAttributeError, PowerwallUnreachableError
from homeassistant import config_entries, setup
from homeassistant.components.powerwall.const import DOMAIN
from homeassistant.const import CONF_IP_ADDRESS
from .mocks import _mock_powerwall_side_effect, _mock_powerwall_site_name
from test... |
import asyncio
import aiohttp
import homeassistant.components.rest.switch as rest
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
CONF_HEADERS,
CONF_NAME,
CONF_PLATFORM,
CONF_RESOURCE,
CONTENT_TYPE_JSON,
HTTP_INTERNAL_SERVER_ERROR,
HTT... |
import os
from celery import Celery
from celery.signals import task_failure
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weblate.settings")
app = Celery("weblate")
# Using a string here means the worker doesn't ... |
from time import time
from flexx import flx
class Test(flx.Widget):
def init(self):
self.t = time()
with flx.HFix():
self.label1 = flx.Label(flex=2, style='overflow-y:scroll; font-size:60%;')
flx.Widget(flex=1)
with flx.VFix(flex=2):
flx.Widg... |
from scattertext.Common import PAIR_PLOT_HTML_VIZ_FILE_NAME, PAIR_PLOT_WITHOUT_HALO_HTML_VIZ_FILE_NAME
from scattertext.categoryprojector.CategoryProjection import CategoryProjection, CategoryProjectionBase
from scattertext.viz.BasicHTMLFromScatterplotStructure import D3URLs, ExternalJSUtilts, PackedDataUtils
from sca... |
from pyownet.protocol import Error as ProtocolError
import pytest
from homeassistant.components.onewire.const import (
DEFAULT_OWSERVER_PORT,
DOMAIN,
PRESSURE_CBAR,
)
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
DEVICE_CLASS_CURRENT,
DEVICE_... |
import argparse
import chainer
import mxnet as mx
from chainercv.experimental.links import FCISResNet101
def main():
parser = argparse.ArgumentParser(
description='Script to convert mxnet params to chainer npz')
parser.add_argument(
'mxnet_param_file', metavar='mxnet-param-file',
hel... |
from unittest import mock
import pytest
from xarray.backends.lru_cache import LRUCache
def test_simple():
cache = LRUCache(maxsize=2)
cache["x"] = 1
cache["y"] = 2
assert cache["x"] == 1
assert cache["y"] == 2
assert len(cache) == 2
assert dict(cache) == {"x": 1, "y": 2}
assert lis... |
import unittest
from dedupe import predicates
from future.builtins import str
class TestPuncStrip(unittest.TestCase):
def test_sevenchar(self):
s1 = predicates.StringPredicate(predicates.sameSevenCharStartPredicate,
'foo')
assert s1({'foo': u'fo,18v*1vaad80... |
DEBUG_PROXY_ISSUES = False # True
import gc
import os
import os.path
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
try:
from urllib import pathname2url
except:
from urllib.request ... |
import tests
from pyVim import connect
class SoapAdapterTests(tests.VCRTestBase):
def test_invoke_method_login_session_exception(self):
def login_fail(*args, **kwargs):
raise vim_session.SESSION_EXCEPTIONS[0]()
stub = connect.SoapStubAdapter()
vim_session = connect.VimSessio... |
import aionotion
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.notion import DOMAIN, config_flow
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from tests.async_mock import AsyncMock, patch
from tests.common im... |
import unittest
from mock import Mock
from trashcli.restore import TrashDirectories
class TestTrashDirectories(unittest.TestCase):
def setUp(self):
volume_of = lambda x: "volume_of(%s)" % x
getuid = Mock(return_value=123)
environ = {'HOME': '~'}
self.trash_directories = TrashDire... |
import asyncio
from functools import partial
import logging
from tellduslive import DIM, TURNON, UP, Session
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_SCAN_INTERVAL
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher ... |
import numpy as np
import six
def assert_is_semantic_segmentation_link(link, n_class):
"""Checks if a link satisfies semantic segmentation link APIs.
This function checks if a given link satisfies semantic segmentation link
APIs or not.
If the link does not satifiy the APIs, this function raises an
... |
from pygal import Line
from pygal.style import (
DarkenStyle, DesaturateStyle, LightenStyle, LightStyle, RotateStyle,
SaturateStyle
)
STYLES = LightenStyle, DarkenStyle, SaturateStyle, DesaturateStyle, RotateStyle
def test_parametric_styles():
"""Test that no parametric produce the same result"""
ch... |
from .stateful_unit import StatefulUnit
class Vocabulary(StatefulUnit):
"""
Vocabulary class.
:param pad_value: The string value for the padding position.
:param oov_value: The string value for the out-of-vocabulary terms.
Examples:
>>> vocab = Vocabulary(pad_value='[PAD]', oov_value='[... |
import logging
from homeassistant.components import litejet
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
LightEntity,
)
_LOGGER = logging.getLogger(__name__)
ATTR_NUMBER = "number"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up l... |
from unittest import mock
from PyQt5.QtCore import Qt, PYQT_VERSION
import pytest
from qutebrowser.keyinput import basekeyparser, keyutils
from qutebrowser.utils import usertypes
# Alias because we need this a lot in here.
def keyseq(s):
return keyutils.KeySequence.parse(s)
def _create_keyparser(mode):
k... |
from datetime import timedelta
from prayer_times_calculator.exceptions import InvalidResponseError
from homeassistant import config_entries
from homeassistant.components import islamic_prayer_times
from homeassistant.setup import async_setup_component
from . import (
NEW_PRAYER_TIMES,
NEW_PRAYER_TIMES_TIMES... |
import vcr
from urllib.request import urlopen
def true_matcher(r1, r2):
return True
def false_matcher(r1, r2):
return False
def test_registered_true_matcher(tmpdir, httpbin):
my_vcr = vcr.VCR()
my_vcr.register_matcher("true", true_matcher)
testfile = str(tmpdir.join("test.yml"))
with my_v... |
import mock
from pyramid import testing
from paasta_tools.api.views.service import list_instances
from paasta_tools.api.views.service import list_services_for_cluster
@mock.patch(
"paasta_tools.api.views.service.list_all_instances_for_service", autospec=True
)
def test_list_instances(mock_list_all_instances_for... |
import numpy as np
from ...transforms import (combine_transforms, invert_transform, Transform,
_quat_to_affine, _fit_matched_points, apply_trans,
get_ras_to_neuromag_trans)
from ...utils import logger
from ..constants import FIFF
from .constants import CTF
def _... |
from absl import flags
from perfkitbenchmarker import vm_util
FLAGS = flags.FLAGS
JAVA_HOME = '/usr'
flags.DEFINE_string('openjdk_version', None, 'Version of openjdk to use. '
'By default, the version of openjdk is automatically '
'detected.')
def _OpenJdkPackage(vm, format... |
import diamond.collector
try:
import boto
boto
from boto.s3.connection import S3Connection
except ImportError:
boto = None
class S3BucketCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(S3BucketCollector, self).get_default_config_help()
... |
from homeassistant.components.mqtt.models import Message
from tests.common import MockConfigEntry
async def test_mqtt_abort_if_existing_entry(hass, mqtt_mock):
"""Check MQTT flow aborts when an entry already exist."""
MockConfigEntry(domain="tasmota").add_to_hass(hass)
result = await hass.config_entrie... |
import itertools
from datetime import datetime
from pytest import mark
from cerberus import errors, Validator
from cerberus.tests import (
assert_document_error,
assert_fail,
assert_has_error,
assert_not_has_error,
assert_success,
)
from cerberus.tests.conftest import sample_schema
def test_emp... |
from copy import deepcopy
import datetime
import os
from pathlib import Path
from unittest import mock
from PIL import UnidentifiedImageError
import pytest
import simplehound.core as hound
import homeassistant.components.image_processing as ip
import homeassistant.components.sighthound.image_processing as sh
from ho... |
import sys
PY2 = sys.version_info[0] == 2
_identity = lambda x: x
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
text_to_native = lambda s, enc: s.encode(enc)
iterkeys = lambda d: d.iterkeys()
it... |
from homeassistant.components.weather import WeatherEntity
from homeassistant.const import TEMP_CELSIUS
from .const import (
ATTR_API_CONDITION,
ATTR_API_FORECAST,
ATTR_API_HUMIDITY,
ATTR_API_PRESSURE,
ATTR_API_TEMPERATURE,
ATTR_API_WIND_BEARING,
ATTR_API_WIND_SPEED,
ATTRIBUTION,
D... |
import asyncio
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceDataType
from ho... |
import pytest
from homeassistant.components import stt
from homeassistant.setup import async_setup_component
@pytest.fixture(autouse=True)
async def setup_comp(hass):
"""Set up demo component."""
assert await async_setup_component(hass, stt.DOMAIN, {"stt": {"platform": "demo"}})
await hass.async_block_t... |
import argparse
import glob
import os
import time
import random
COLOURS = (b'\xFF\x00\x00', b'\x00\xFF\x00', b'\x00\x00\xFF', b'\xFF\xFF\x00', b'\xFF\x00\xFF', b'\x00\xFF\xFF')
def write_binary(driver_path, device_file, payload):
with open(os.path.join(driver_path, device_file), 'wb') as open_file:
ope... |
from absl import flags
FLAGS = flags.FLAGS
TF_MODELS_GIT = 'https://github.com/tensorflow/models.git'
flags.DEFINE_string('tensorflow_models_commit_hash',
'4fa82ae1cb08c374a44e2713e731f57d44bf7e61',
'git commit hash of desired TensorFlow models commit.')
def Install(vm):
""... |
import logging
from homeassistant.components.cover import (
ATTR_POSITION,
DEVICE_CLASS_SHADE,
DOMAIN,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverEntity,
)
from . import DOMAIN as CASETA_DOMAIN, LutronCasetaDevice
_LOGGER = logging.getLogger(__name__)
asy... |
import json
import requests
from requests.exceptions import ConnectionError
from datetime import datetime
from flask import current_app
from lemur.plugins import lemur_atlas as atlas
from lemur.plugins.bases.metric import MetricPlugin
def millis_since_epoch():
"""
current time since epoch in milliseconds
... |
import logging
from libpurecool.dyson import DysonAccount
import voluptuous as vol
from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_LAN... |
import argparse
import getpass
from socket import gaierror
import ephemeral_port_reserve
import mock
from mock import patch
from pytest import mark
from pytest import raises
from paasta_tools.cli import utils
from paasta_tools.marathon_tools import MarathonServiceConfig
from paasta_tools.utils import SystemPaastaCon... |
from wled import WLEDConnectionError
from homeassistant.components.wled.const import DOMAIN
from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY
from homeassistant.core import HomeAssistant
from tests.async_mock import MagicMock, patch
from tests.components.wled import init_integration
from tests.test_ut... |
revision = "318b66568358"
down_revision = "9f79024fe67b"
from alembic import op
def upgrade():
connection = op.get_bind()
# Delete duplicate entries
connection.execute("UPDATE certificates SET deleted = false WHERE deleted IS NULL")
def downgrade():
pass
|
import base
from docker_registry.core import compat
json = compat.json
class TestIndex(base.TestCase):
"""The Index module is fake at the moment
hence the unit tests only test the return codes
"""
def test_users(self):
# GET
resp = self.http_client.get('/v1/users/')
self.a... |
import os
import shlex
import shutil
import subprocess
import sys
import unittest
def run_cmd(cmd):
"""Run a command and return a tuple with (stdout, stderr, exit_code)"""
print('\n$ ' + cmd)
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subpro... |
import unittest
from chainer import testing
from chainer.testing import attr
from chainercv.datasets import sbd_instance_segmentation_label_names
from chainercv.datasets import SBDInstanceSegmentationDataset
from chainercv.utils import assert_is_instance_segmentation_dataset
try:
import scipy # NOQA
_avail... |
import pytest
from plumbum import local, SshMachine
from plumbum.path.utils import copy, delete, move
from plumbum._testtools import skip_on_windows
@skip_on_windows
class TestUtils:
def test_copy_move_delete(self):
from plumbum.cmd import touch
with local.tempdir() as dir:
(dir / "or... |
import logging
import numpy as np
import networkx as nx
from pgmpy.models import BayesianModel
from pgmpy.factors.continuous import LinearGaussianCPD
from pgmpy.factors.distributions import GaussianDistribution
class LinearGaussianBayesianNetwork(BayesianModel):
"""
A Linear Gaussian Bayesian Network is a ... |
import typing
from pathlib import Path
import pandas as pd
import keras
import matchzoo
_url = "https://nlp.stanford.edu/projects/snli/snli_1.0.zip"
def load_data(
stage: str = 'train',
task: str = 'classification',
target_label: str = 'entailment',
return_classes: bool = False
) -> typing.Union[m... |
from collections import deque
import os
from queue import Empty, LifoQueue as _LifoQueue
from . import exceptions
from .utils.compat import register_after_fork
from .utils.functional import lazy
def _after_fork_cleanup_resource(resource):
try:
resource.force_close_all()
except Exception:
pas... |
import os
import unittest
import mock
from perfkitbenchmarker.linux_benchmarks import stress_ng_benchmark
class StressngTestCase(unittest.TestCase):
def setUp(self):
super(StressngTestCase, self).setUp()
p = mock.patch(stress_ng_benchmark.__name__)
p.start()
self.addCleanup(p.stop)
path = o... |
import json
import unittest
from aiohttp.hdrs import CONTENT_TYPE
import defusedxml.ElementTree as ET
import requests
from homeassistant import const, setup
from homeassistant.components import emulated_hue
from homeassistant.components.emulated_hue import upnp
from homeassistant.const import CONTENT_TYPE_JSON, HTTP... |
from unittest.mock import Mock
import pandas as pd
import pytest
import pytz
from qstrader.portcon.order_sizer.long_short import (
LongShortLeveragedOrderSizer
)
@pytest.mark.parametrize(
"gross_leverage,expected",
[
(-1.0, None),
(0.0, None),
(0.01, 0.01),
(0.99, 0.99)... |
import asyncio
from unittest import mock
import pytest
import zigpy.profiles.zha
import zigpy.types as t
import zigpy.zcl.clusters
import homeassistant.components.zha.core.channels as zha_channels
import homeassistant.components.zha.core.channels.base as base_channels
import homeassistant.components.zha.core.const a... |
import glob
import os
import numpy as np
from chainercv.chainer_experimental.datasets.sliceable import GetterDataset
from chainercv.datasets.ade20k.ade20k_utils import get_ade20k
from chainercv.utils import read_image
from chainercv.utils import read_label
root = 'pfnet/chainercv/ade20k'
url = 'http://data.csail.mi... |
import logging
import voluptuous as vol
from homeassistant.components import pilight
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PAYLOAD, CONF_UNIT_OF_MEASUREMENT
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity imp... |
from typing import Any, List, Mapping
from PyQt5.QtCore import QByteArray, QDataStream, QIODevice, QUrl
from qutebrowser.utils import qtutils
def _serialize_items(items, current_idx, stream):
# {'currentItemIndex': 0,
# 'history': [{'children': [],
# 'documentSequenceNumber': 14850305255... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
def mobilenet(inputs,
num_classes=1000,
is_training=True,
width_multiplier=1,
scope='MobileNet'):
""" ... |
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_DATA,
PLATFORM_SCHEMA,
BaseNotificationService,
)
import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.template as template_helper
from .const import (
ATTR_ADDRESS,
ATTR_CHANNEL,
ATTR_INT... |
import re
from collections import Counter
from unittest import TestCase
from scattertext import whitespace_nlp
from scattertext.WhitespaceNLP import Tok, Doc, _regex_parse_sentence, whitespace_nlp_with_sentences
from scattertext.features.FeatsFromSpacyDoc import FeatsFromSpacyDoc
from scattertext.features.FeatsFromSp... |
from pyspark import SparkContext, SparkConf
from hyperopt import STATUS_OK
from hyperas.distributions import choice, uniform
import six.moves.cPickle as pickle
from elephas.hyperparam import HyperParamModel
def data():
"""Data providing function:
Make sure to have every relevant import statement included ... |
import unittest
from urwid.compat import B
import urwid
class TextTest(unittest.TestCase):
def setUp(self):
self.t = urwid.Text("I walk the\ncity in the night")
def test1_wrap(self):
expected = [B(t) for t in ("I walk the","city in ","the night ")]
got = self.t.render((10,))._text... |
from __future__ import division
import numpy as np
import chainer
import chainer.functions as F
def _elementwise_softmax_cross_entropy(x, t):
assert x.shape[:-1] == t.shape
shape = t.shape
x = F.reshape(x, (-1, x.shape[-1]))
t = F.flatten(t)
return F.reshape(
F.softmax_cross_entropy(x, ... |
import voluptuous as vol
from homeassistant.components.lock import PLATFORM_SCHEMA, LockEntity
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_LOCKED,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions impo... |
from queue import Queue
from threading import Event
from mock import Mock
from mock import patch
from pytest import raises
from paasta_tools.cli.cmds import mark_for_deployment
from paasta_tools.cli.cmds.mark_for_deployment import NoSuchCluster
from paasta_tools.cli.cmds.wait_for_deployment import get_latest_marked_... |
from matplotlib.ticker import FuncFormatter
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.dates as mdates
import numpy as np
import seaborn as sns
import qstrader.statistics.performance as perf
from qstrader.statistics.statistics import Statistics
f... |
from datetime import timedelta
import logging
from niluclient import (
CO,
CO2,
NO,
NO2,
NOX,
OZONE,
PM1,
PM10,
PM25,
POLLUTION_INDEX,
SO2,
create_location_client,
create_station_client,
lookup_stations_in_area,
)
import voluptuous as vol
from homeassistant.com... |
import logging
from homeassistant.const import CONF_NAME, STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import ToggleEntity
from .const import DOMAIN, SWITCH_TYPES
_LOGGING = logging.getLogger(__nam... |
import os
from perfkitbenchmarker import linux_packages
SHOC_GIT_URL = 'https://github.com/vetter/shoc.git'
SHOC_DIR = '%s/shoc' % linux_packages.INSTALL_DIR
SHOC_BIN_DIR = os.path.join(SHOC_DIR, 'bin')
SHOC_PATCH = 'shoc_config.patch'
APT_PACKAGES = 'wget automake git zip libopenmpi-dev'
def _IsShocInstalled(vm):... |
from absl import flags
from perfkitbenchmarker import disk
FLAGS = flags.FLAGS
class MesosDisk(disk.BaseDisk):
"""
Base class for Mesos Disks.
"""
def __init__(self, disk_spec):
super(MesosDisk, self).__init__(disk_spec)
self.mount_point = disk_spec.mount_point
def _Create(self):
return
d... |
from django.contrib.auth.models import AnonymousUser
from django.urls import reverse
from shop.models.cart import CartModel, CartItemModel
from shop.models.customer import CustomerModel
from shop.views.catalog import ProductListView, ProductRetrieveView, AddToCartView
import pytest
@pytest.mark.django_db
def test_ca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.