text:
"""Tests for light platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, Mock

from flux_led.const import (
    COLOR_MODE_ADDRESSABLE as FLUX_COLOR_MODE_ADDRESSABLE,
    COLOR_MODE_CCT as FLUX_COLOR_MODE_CCT,
    COLOR_MODE_DIM as FLUX_COLOR_MODE_DIM,
    COLOR_MODE_RGB as FLUX_COLOR_MODE_RGB,
    COLOR_MODE_RGBW as FLUX_COLOR_MODE_RGBW,
    COLOR_MODE_RGBWW as FLUX_COLOR_MODE_RGBWW,
    COLOR_MODES_RGB_W as FLUX_COLOR_MODES_RGB_W,
    MODE_MUSIC,
    MultiColorEffects,
)
from flux_led.protocol import MusicMode
import pytest

from homeassistant.components import flux_led
from homeassistant.components.flux_led.const import (
    CONF_COLORS,
    CONF_CUSTOM_EFFECT_COLORS,
    CONF_CUSTOM_EFFECT_SPEED_PCT,
    CONF_CUSTOM_EFFECT_TRANSITION,
    CONF_EFFECT,
    CONF_SPEED_PCT,
    CONF_TRANSITION,
    DOMAIN,
    TRANSITION_JUMP,
)
from homeassistant.components.flux_led.light import (
    ATTR_BACKGROUND_COLOR,
    ATTR_FOREGROUND_COLOR,
    ATTR_LIGHT_SCREEN,
    ATTR_SENSITIVITY,
)
from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    ATTR_COLOR_MODE,
    ATTR_COLOR_TEMP,
    ATTR_EFFECT,
    ATTR_EFFECT_LIST,
    ATTR_HS_COLOR,
    ATTR_RGB_COLOR,
    ATTR_RGBW_COLOR,
    ATTR_RGBWW_COLOR,
    ATTR_SUPPORTED_COLOR_MODES,
    ATTR_WHITE,
    DOMAIN as LIGHT_DOMAIN,
)
from homeassistant.const import (
    ATTR_ENTITY_ID,
    CONF_HOST,
    CONF_MODE,
    CONF_NAME,
    STATE_OFF,
    STATE_ON,
    STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow

from . import (
    DEFAULT_ENTRY_TITLE,
    IP_ADDRESS,
    MAC_ADDRESS,
    _mocked_bulb,
    _patch_discovery,
    _patch_wifibulb,
    async_mock_device_turn_off,
    async_mock_device_turn_on,
)

from tests.common import MockConfigEntry, async_fire_time_changed

async def test_light_unique_id(hass: HomeAssistant) -> None:
    """Test a light unique id."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"
    entity_registry = er.async_get(hass)
    assert entity_registry.async_get(entity_id).unique_id == MAC_ADDRESS
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

async def test_light_goes_unavailable_and_recovers(hass: HomeAssistant) -> None:
    """Test a light goes unavailable and then recovers."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"
    entity_registry = er.async_get(hass)
    assert entity_registry.async_get(entity_id).unique_id == MAC_ADDRESS
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

    now = utcnow()
    bulb.async_update = AsyncMock(side_effect=RuntimeError)
    for i in range(10, 50, 10):
        async_fire_time_changed(hass, now + timedelta(seconds=i))
        await hass.async_block_till_done()
    state = hass.states.get(entity_id)
    assert state.state == STATE_UNAVAILABLE
    bulb.async_update = AsyncMock()
    for i in range(60, 100, 10):
        async_fire_time_changed(hass, now + timedelta(seconds=i))
        await hass.async_block_till_done()
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

async def test_light_no_unique_id(hass: HomeAssistant) -> None:
    """Test a light without a unique id."""
    config_entry = MockConfigEntry(
        domain=DOMAIN, data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE}
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    with _patch_discovery(no_device=True), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"
    entity_registry = er.async_get(hass)
    assert entity_registry.async_get(entity_id) is None
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

@pytest.mark.parametrize(
    "protocol,sw_version,model_num,model",
    [
        ("LEDENET_ORIGINAL", 1, 0x01, "Original LEDEDNET (0x35)"),
        ("LEDENET", 8, 0x33, "Magic Home Branded RGB Controller (0x33)"),
    ],
)
async def test_light_device_registry(
    hass: HomeAssistant, protocol: str, sw_version: int, model_num: int, model: str
) -> None:
    """Test a light device registry entry."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.version_num = sw_version
    bulb.protocol = protocol
    bulb.model_num = model_num
    bulb.model = model

    with _patch_discovery(no_device=True), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    device_registry = dr.async_get(hass)
    device = device_registry.async_get_device(
        identifiers={}, connections={(dr.CONNECTION_NETWORK_MAC, MAC_ADDRESS)}
    )
    assert device.sw_version == str(sw_version)
    assert device.model == model

async def test_rgb_light(hass: HomeAssistant) -> None:
    """Test an rgb light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.raw_state = bulb.raw_state._replace(model_num=0x33)  # RGB only model
    bulb.color_modes = {FLUX_COLOR_MODE_RGB}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(no_device=True), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()

    await async_mock_device_turn_off(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_OFF

    bulb.brightness = 0
    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGB_COLOR: (10, 10, 30)},
        blocking=True,
    )
    # If the bulb is off and we are using existing brightness
    # it has to be at least 1 or the bulb won't turn on
    bulb.async_set_levels.assert_called_with(10, 10, 30, brightness=1)
    bulb.async_set_levels.reset_mock()
    bulb.async_turn_on.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    # If its off and the device requires the turn on
    # command before setting brightness we need to make sure its called
    bulb.async_turn_on.assert_called_once()
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()
    await async_mock_device_turn_on(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_ON

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGB_COLOR: (10, 10, 30)},
        blocking=True,
    )
    # If the bulb is on and we are using existing brightness
    # and brightness was 0 it means we could not read it because
    # an effect is in progress so we use 255
    bulb.async_set_levels.assert_called_with(10, 10, 30, brightness=255)
    bulb.async_set_levels.reset_mock()

    bulb.brightness = 128
    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_HS_COLOR: (10, 30)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 191, 178, brightness=128)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 50)
    bulb.async_set_effect.reset_mock()

async def test_rgb_light_auto_on(hass: HomeAssistant) -> None:
    """Test an rgb light that does not need the turn on command sent."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.requires_turn_on = False
    bulb.raw_state = bulb.raw_state._replace(model_num=0x33)  # RGB only model
    bulb.color_modes = {FLUX_COLOR_MODE_RGB}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()

    await async_mock_device_turn_off(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_OFF

    bulb.brightness = 0
    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGB_COLOR: (10, 10, 30)},
        blocking=True,
    )
    # If the bulb is off and we are using existing brightness
    # it has to be at least 1 or the bulb won't turn on
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_levels.assert_called_with(10, 10, 30, brightness=1)
    bulb.async_set_levels.reset_mock()
    bulb.async_turn_on.reset_mock()

    # Should still be called with no kwargs
    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    await async_mock_device_turn_on(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_ON
    bulb.async_turn_on.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGB_COLOR: (10, 10, 30)},
        blocking=True,
    )
    # If the bulb is on and we are using existing brightness
    # and brightness was 0 it means we could not read it because
    # an effect is in progress so we use 255
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_levels.assert_called_with(10, 10, 30, brightness=255)
    bulb.async_set_levels.reset_mock()

    bulb.brightness = 128
    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_HS_COLOR: (10, 30)},
        blocking=True,
    )
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_levels.assert_called_with(255, 191, 178, brightness=128)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade"},
        blocking=True,
    )
    bulb.async_turn_on.assert_not_called()
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 50)
    bulb.async_set_effect.reset_mock()

async def test_rgb_cct_light(hass: HomeAssistant) -> None:
    """Test an rgb cct light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.raw_state = bulb.raw_state._replace(model_num=0x35)  # RGB & CCT model
    bulb.color_modes = {FLUX_COLOR_MODE_RGB, FLUX_COLOR_MODE_CCT}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["color_temp", "rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_HS_COLOR: (10, 30)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 191, 178, brightness=128)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 50)
    bulb.async_set_effect.reset_mock()
    bulb.color_mode = FLUX_COLOR_MODE_CCT
    bulb.getWhiteTemperature = Mock(return_value=(5000, 128))
    bulb.color_temp = 5000

    bulb.raw_state = bulb.raw_state._replace(
        red=0, green=0, blue=0, warm_white=1, cool_white=2
    )
    await async_mock_device_turn_on(hass, bulb)
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "color_temp"
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["color_temp", "rgb"]
    assert attributes[ATTR_COLOR_TEMP] == 200

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP: 370},
        blocking=True,
    )
    bulb.async_set_white_temp.assert_called_with(2702, 128)
    bulb.async_set_white_temp.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 255},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(255)
    bulb.async_set_brightness.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 128},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(128)
    bulb.async_set_brightness.reset_mock()

async def test_rgbw_light(hass: HomeAssistant) -> None:
    """Test an rgbw light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.color_modes = {FLUX_COLOR_MODE_RGBW}
    bulb.color_mode = FLUX_COLOR_MODE_RGBW
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgbw"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgbw"]
    assert attributes[ATTR_RGB_COLOR] == (255, 42, 42)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()
    bulb.is_on = True

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_RGBW_COLOR: (255, 255, 255, 255),
            ATTR_BRIGHTNESS: 128,
        },
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(128, 128, 128, 128)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGBW_COLOR: (255, 255, 255, 255)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 255, 255, 255)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGBW_COLOR: (255, 191, 178, 0)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 191, 178, 0)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade", ATTR_BRIGHTNESS: 255},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 100)
    bulb.async_set_effect.reset_mock()

async def test_rgb_or_w_light(hass: HomeAssistant) -> None:
    """Test an rgb or w light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.color_modes = FLUX_COLOR_MODES_RGB_W
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb", "white"]
    assert attributes[ATTR_RGB_COLOR] == (255, 0, 0)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()
    bulb.is_on = True

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()
    state = hass.states.get(entity_id)
    assert state.state == STATE_ON

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_RGB_COLOR: (255, 255, 255),
            ATTR_BRIGHTNESS: 128,
        },
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 255, 255, brightness=128)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade", ATTR_BRIGHTNESS: 255},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 100)
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_WHITE: 128,
        },
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(w=128)
    bulb.async_set_levels.reset_mock()

    bulb.color_mode = FLUX_COLOR_MODE_DIM

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_BRIGHTNESS: 100,
        },
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()

async def test_rgbcw_light(hass: HomeAssistant) -> None:
    """Test an rgbcw light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.raw_state = bulb.raw_state._replace(warm_white=1, cool_white=2)
    bulb.color_modes = {FLUX_COLOR_MODE_RGBWW, FLUX_COLOR_MODE_CCT}
    bulb.color_mode = FLUX_COLOR_MODE_RGBWW
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgbww"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["color_temp", "rgbww"]
    assert attributes[ATTR_HS_COLOR] == (3.237, 94.51)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()
    bulb.is_on = True

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_RGBWW_COLOR: (255, 255, 255, 0, 255),
            ATTR_BRIGHTNESS: 128,
        },
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(192, 192, 192, 192, 0)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGBWW_COLOR: (255, 255, 255, 255, 50)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 255, 255, 50, 255)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP: 154},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(r=0, b=0, g=0, w=0, w2=127)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP: 154, ATTR_BRIGHTNESS: 255},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(r=0, b=0, g=0, w=0, w2=255)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP: 290},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(r=0, b=0, g=0, w=102, w2=25)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_RGBWW_COLOR: (255, 191, 178, 0, 0)},
        blocking=True,
    )
    bulb.async_set_levels.assert_called_with(255, 191, 178, 0, 0)
    bulb.async_set_levels.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "random"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_once()
    bulb.async_set_effect.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "purple_fade"},
        blocking=True,
    )
    bulb.async_set_effect.assert_called_with("purple_fade", 50, 50)
    bulb.async_set_effect.reset_mock()
    bulb.effect = "purple_fade"
    bulb.brightness = 128

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 255},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(255)
    bulb.async_set_brightness.reset_mock()

async def test_white_light(hass: HomeAssistant) -> None:
    """Test a white light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.mode = "ww"
    bulb.protocol = None
    bulb.color_modes = {FLUX_COLOR_MODE_DIM}
    bulb.color_mode = FLUX_COLOR_MODE_DIM
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "brightness"
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["brightness"]
    assert ATTR_EFFECT_LIST in attributes  # single channel now supports effects

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 100},
        blocking=True,
    )
    bulb.async_set_brightness.assert_called_with(100)
    bulb.async_set_brightness.reset_mock()

async def test_no_color_modes(hass: HomeAssistant) -> None:
    """Test a light that has no color modes defined in the database."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.mode = "ww"
    bulb.protocol = None
    bulb.color_modes = set()
    bulb.color_mode = None
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_COLOR_MODE] == "onoff"
    assert ATTR_EFFECT_LIST in attributes  # single channel now supports effects

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)

    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()

async def test_rgb_light_custom_effects(hass: HomeAssistant) -> None:
    """Test an rgb light with a custom effect."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
        options={
            CONF_MODE: "auto",
            CONF_CUSTOM_EFFECT_COLORS: "[0,0,255], [255,0,0]",
            CONF_CUSTOM_EFFECT_SPEED_PCT: 88,
            CONF_CUSTOM_EFFECT_TRANSITION: TRANSITION_JUMP,
        },
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.color_modes = {FLUX_COLOR_MODE_RGB}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == [*bulb.effect_list, "custom"]
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()
    await async_mock_device_turn_off(hass, bulb)
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: "custom"},
        blocking=True,
    )
    bulb.effect = "custom"
    bulb.async_set_custom_pattern.assert_called_with(
        [[0, 0, 255], [255, 0, 0]], 88, "jump"
    )
    bulb.async_set_custom_pattern.reset_mock()
    await async_mock_device_turn_on(hass, bulb)

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_EFFECT] == "custom"

    await hass.services.async_call(
        LIGHT_DOMAIN,
        "turn_on",
        {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 55, ATTR_EFFECT: "custom"},
        blocking=True,
    )
    bulb.effect = "custom"
    bulb.async_set_custom_pattern.assert_called_with(
        [[0, 0, 255], [255, 0, 0]], 88, "jump"
    )
    bulb.async_set_custom_pattern.reset_mock()
    await async_mock_device_turn_on(hass, bulb)

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_EFFECT] == "custom"

@pytest.mark.parametrize("effect_colors", [":: CANNOT BE PARSED ::", None])
async def test_rgb_light_custom_effects_invalid_colors(
    hass: HomeAssistant, effect_colors: str
) -> None:
    """Test an rgb light with a invalid effect."""
    options = {
        CONF_MODE: "auto",
        CONF_CUSTOM_EFFECT_SPEED_PCT: 88,
        CONF_CUSTOM_EFFECT_TRANSITION: TRANSITION_JUMP,
    }
    if effect_colors:
        options[CONF_CUSTOM_EFFECT_COLORS] = effect_colors
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        options=options,
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.color_modes = {FLUX_COLOR_MODE_RGB}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

async def test_rgb_light_custom_effect_via_service(
    hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
    """Test an rgb light with a custom effect set via the service."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.color_modes = {FLUX_COLOR_MODE_RGB}
    bulb.color_mode = FLUX_COLOR_MODE_RGB
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_BRIGHTNESS] == 128
    assert attributes[ATTR_COLOR_MODE] == "rgb"
    assert attributes[ATTR_EFFECT_LIST] == bulb.effect_list
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["rgb"]
    assert attributes[ATTR_HS_COLOR] == (0, 100)

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()

    await async_mock_device_turn_off(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        DOMAIN,
        "set_custom_effect",
        {
            ATTR_ENTITY_ID: entity_id,
            CONF_COLORS: [[0, 0, 255], [255, 0, 0]],
            CONF_SPEED_PCT: 30,
            CONF_TRANSITION: "jump",
        },
        blocking=True,
    )
    bulb.async_set_custom_pattern.assert_called_with(
        [(0, 0, 255), (255, 0, 0)], 30, "jump"
    )
    bulb.async_set_custom_pattern.reset_mock()

    await hass.services.async_call(
        DOMAIN,
        "set_zones",
        {
            ATTR_ENTITY_ID: entity_id,
            CONF_COLORS: [[0, 0, 255], [255, 0, 0]],
            CONF_EFFECT: "running_water",
        },
        blocking=True,
    )
    bulb.async_set_zones.assert_called_with(
        [(0, 0, 255), (255, 0, 0)], 50, MultiColorEffects.RUNNING_WATER
    )
    bulb.async_set_zones.reset_mock()

    await hass.services.async_call(
        DOMAIN,
        "set_zones",
        {
            ATTR_ENTITY_ID: entity_id,
            CONF_COLORS: [[0, 0, 255], [255, 0, 0]],
            CONF_SPEED_PCT: 30,
        },
        blocking=True,
    )
    bulb.async_set_zones.assert_called_with(
        [(0, 0, 255), (255, 0, 0)], 30, MultiColorEffects.STATIC
    )
    bulb.async_set_zones.reset_mock()

async def test_addressable_light(hass: HomeAssistant) -> None:
    """Test an addressable light."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.raw_state = bulb.raw_state._replace(model_num=0x33)  # RGB only model
    bulb.color_modes = {FLUX_COLOR_MODE_ADDRESSABLE}
    bulb.color_mode = FLUX_COLOR_MODE_ADDRESSABLE
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"

    state = hass.states.get(entity_id)
    assert state.state == STATE_ON
    attributes = state.attributes
    assert attributes[ATTR_COLOR_MODE] == "onoff"
    assert ATTR_EFFECT_LIST in attributes
    assert attributes[ATTR_SUPPORTED_COLOR_MODES] == ["onoff"]

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_off.assert_called_once()

    await async_mock_device_turn_off(hass, bulb)
    assert hass.states.get(entity_id).state == STATE_OFF

    await hass.services.async_call(
        LIGHT_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True
    )
    bulb.async_turn_on.assert_called_once()
    bulb.async_turn_on.reset_mock()
    await async_mock_device_turn_on(hass, bulb)

async def test_music_mode_service(hass: HomeAssistant) -> None:
    """Test music mode service."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},
        unique_id=MAC_ADDRESS,
    )
    config_entry.add_to_hass(hass)
    bulb = _mocked_bulb()
    bulb.raw_state = bulb.raw_state._replace(model_num=0xA3)  # has music mode
    bulb.microphone = True
    with _patch_discovery(), _patch_wifibulb(device=bulb):
        await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
        await hass.async_block_till_done()

    entity_id = "light.bulb_rgbcw_ddeeff"
    assert hass.states.get(entity_id)

    bulb.effect = MODE_MUSIC
    bulb.is_on = False
    await hass.services.async_call(
        DOMAIN,
        "set_music_mode",
        {
            ATTR_ENTITY_ID: entity_id,
            ATTR_EFFECT: 12,
            ATTR_LIGHT_SCREEN: True,
            ATTR_SENSITIVITY: 50,
            ATTR_BRIGHTNESS: 50,
            ATTR_FOREGROUND_COLOR: [255, 0, 0],
            ATTR_BACKGROUND_COLOR: [0, 255, 0],
        },
        blocking=True,
    )
    bulb.async_set_music_mode.assert_called_once_with(
        sensitivity=50,
        brightness=50,
        mode=MusicMode.LIGHT_SCREEN.value,
        effect=12,
        foreground_color=(255, 0, 0),
        background_color=(0, 255, 0),
    )


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Boletín de la Academia Nacional de Ciencias de Córdoba 23: 486 (1919)

#### Original name
Puiggarina manaosensis Speg., 1919

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
$packageName = 'avgantivirusfree'
$packageSearch = "AVG"
$installerType = 'exe'
$validExitCodes = @(0)

$reg = Get-ItemProperty -Path @( 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
                                 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
                                 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' ) `
                        -ErrorAction:SilentlyContinue `
       | Where-Object   { $_.PSChildName -like "$packageSearch*" }

$unString = ($reg.UninstallString -Split ' /')[0]
$silentArgs = '/Appmode=Setup /uninstall /uilevel=Silent /dontrestart'

Uninstall-ChocolateyPackage -PackageName "$packageName" `
                              -FileType "$installerType" `
                              -SilentArgs "$silentArgs" `
                              -File "$unString" `
                              -ValidExitCodes $validExitCodes


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Scheduler: Scheduler::Terminates Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Scheduler

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Scheduler

Terminates

Public Member Functions |
List of all members

Scheduler::Terminates Class Reference

#include <terminates.h>

Inheritance diagram for Scheduler::Terminates:

  <map id="Scheduler::Terminates_map" name="Scheduler::Terminates_map">
<area href="classScheduler_1_1Event.html" alt="Scheduler::Event" shape="rect" coords="0,0,137,24"/>
</map>

Public Member Functions

 	Terminates (double time, bool renew=false)

void 	process () override

 	handle the the event TODO: 'process' is maybe not the best word for that, given that our simulator actually manipulated processes  More...

std::string 	getName () override

 	get the name of the event  More...

 Public Member Functions inherited from Scheduler::Event

 	Event (double time, bool renew=true)

 	Event constructor.  More...

void 	setTask (std::shared_ptr< Process > task)

 	if the event is specific to a task, set it here. TODO not all events have an associated task. This should be moved  More...

double 	getTime ()

 	get the time at which the event is scheduled  More...

virtual 	~Event ()

virtual void 	print ()

 	print information about the event  More...

Additional Inherited Members

 Protected Attributes inherited from Scheduler::Event

double 	time

bool 	renew

std::shared_ptr< Process > 	task {nullptr}

TriggeringEvent 	eventType {nothing}

 	The event type is need by the scheduling discipline, to determine if this kind of event triggers invokatio of that discipline.  More...

Detailed Description

This event is scheduled when a process terminates

Definition at line 23 of file terminates.h.

Constructor & Destructor Documentation

          Scheduler::Terminates::Terminates
          (
          double
          time,

          bool
          renew = false

          )

inline

Definition at line 26 of file terminates.h.

Member Function Documentation

          std::string Terminates::getName
          (
          	)

overridevirtual

get the name of the event

Returns

a string containing the name of the event

Implements Scheduler::Event.

Definition at line 36 of file terminates.cpp.

          void Terminates::process
          (
          	)

overridevirtual

handle the the event TODO: 'process' is maybe not the best word for that, given that our simulator actually manipulated processes

Implements Scheduler::Event.

Definition at line 24 of file terminates.cpp.

The documentation for this class was generated from the following files:

src/scheduler/events/terminates.h

src/scheduler/events/terminates.cpp

<address class="footer">
Generated on Sun Nov 26 2017 17:01:37 for Scheduler by

 1.8.11
</address>


text: SELECT status FROM REQUESTS WHERE rid=?


text:
/*
 * graph.h - graph method related classes
 *
 * Jun Korenaga, MIT/WHOI
 * January 1999
 */

#ifndef _TOMO_GRAPH_H_
#define _TOMO_GRAPH_H_

#include <list>
#include <array.h> // from mconv source
#include <geom.h>
#include "heap_deque.h"
#include "index.h"
#include "interface.h"

class TTCmp {
public:
    TTCmp(Array1d<double>& a) : data(a) {}
    bool operator()(int i, int j) const { return data(i)>data(j); }
private:
    Array1d<double>& data;
};

class GraphSolver2d {
public:
    GraphSolver2d(const SlownessMesh2d&, int xorder, int zorder);

    int xOrder() const { return fs_xorder; }
    int zOrder() const { return fs_zorder; }
    void solve(const Point2d& src);
    void solve_refl(const Point2d& src, const Interface2d& itf);
    void do_refl_downward();
    void limitRange(double xmin, double xmax);
    void delimitRange();
    void refineIfLong(double);
    double critLength() const { return crit_len; }

    void pickPath(const Point2d& rcv, Array1d<Point2d>& path) const;
    void pickPathThruWater(const Point2d& rcv, Array1d<Point2d>& path,
			   int&, int&) const;
    void pickReflPath(const Point2d& rcv, Array1d<Point2d>& path,
		      int&, int&) const;
    void pickReflPathThruWater(const Point2d& rcv, Array1d<Point2d>& path,
			       int&, int&, int&, int&) const;

    void printPath(ostream&) const;

private:
    void findRayEntryPoint(const Point2d& rcv, int& cur,
			   const Array1d<double>& nodetime) const;

    const SlownessMesh2d& smesh;
    int nnodes;
    bool is_solved, is_refl_solved, solve_refl_downward;
    Point2d src;
    int fs_xorder, fs_zorder;
    Array1d<int> prev_node, prev_node_down, prev_node_up;
    Array1d<double> ttime, ttime_down, ttime_up;
    list<int> C;
    TTCmp cmp, cmp_down, cmp_up;
    heap_deque<int,TTCmp> B, B_down, B_up;
    const Interface2d* itfp;
    typedef list<int>::const_iterator nodeBrowser;
    typedef list<int>::iterator nodeIterator;
    typedef heap_deque<int,TTCmp>::const_iterator heapBrowser;

    const double local_search_radius;
    double xmin, xmax;
    bool refine_if_long;
    double crit_len;
};

class ForwardStar2d {
public:
    ForwardStar2d(const Index2d& id, int ix, int iz);
    bool isIn(const Index2d&) const;

private:
    const Index2d& orig;
    int xorder, zorder;
};

#endif /* _TOMO_GRAPH_H_ */


text:
using System;

namespace Exceptionless.Core.Models {
    public class WebHookStack {
        public string Id { get; set; }
        public string Url => String.Concat(Settings.Current.BaseURL, "/stack/", Id);
        public string Title { get; set; }
        public string Description { get; set; }

        public TagSet Tags { get; set; }
        public string RequestPath { get; set; }
        public string Type { get; set; }
        public string TargetMethod { get; set; }
        public string ProjectId { get; set; }
        public string ProjectName { get; set; }
        public string OrganizationId { get; set; }
        public string OrganizationName { get; set; }
        public int TotalOccurrences { get; set; }
        public DateTime FirstOccurrence { get; set; }
        public DateTime LastOccurrence { get; set; }
        public DateTime? DateFixed { get; set; }
        public string FixedInVersion { get; set; }
        public bool IsRegression { get; set; }
        public bool IsCritical { get; set; }
    }
}


text:
package com.modulo7.musicstatmodels.representation.metadata;

/**
 * Created by asanyal on 6/29/2015.
 *
 * Different types of scales that in existence in western music.
 *
 * Major Scale : Standard major scale, also called the happy sounding scale
 * Minor Scale : Standard minor scale, also called the sad sounding scale
 */
public enum ScaleType {

    MAJOR("MAJOR"),
    MINOR("MINOR"),
    UNKNOWN("UNKNOWN");

    private final String scale;

    ScaleType(final String scale) {
        this.scale = scale.toUpperCase();
    }

    /**
     * Gets the scale type given a string representation
     * @param inputStr
     * @return
     */
    public static ScaleType getScaleTypeFromString(final String inputStr) {
        String actualStr = inputStr.toUpperCase();

        if (actualStr.equals("MAJOR") || actualStr.equals("MAJ")) {
            return MAJOR;
        } else if (actualStr.equals("MINOR") || actualStr.equals("MIN")) {
            return MINOR;
        } else {
            return UNKNOWN;
        }
    }

    /**
     * Gets the string representation of the scale
     * @return
     */
    public String getScale() {
        return scale;
    }
}


text:
"use strict";
var http = require('http'),
    url = require('url'),
    formidable = require('formidable'),
    fs = require('fs');
var highlight,
    $style = 'default',     //可选项:ascetic,brown_paper,dark,default,far,github,idea,ir_black,magula,school_book,sunburst,vs,zenburn
    style;
    try{
        highlight = require('highlight').Highlight;
        style = fs.readFileSync( "node_modules/highlight/lib/vendor/highlight.js/styles/" + $style + ".css",'utf-8');
    }catch(e){
        highlight = function(){ return '
hightlight is required!
'; };
        style = 'h1{text-align:center}';
    }
exports.execute = function(req, resp){
    if( req.method === 'POST' ){
        var form = new formidable.IncomingForm(), fields = {};
        form.on('field', function(field, value) {
            fields[field] = value;
        }).on('end',function(){
            resp.writeHead(200, {"Content-Type": "application/json"});
            resp.end( JSON.stringify({
                code: fields.code,
                output: highlight(fields.code),
                style: style
            }) );
        });
        return form.parse(req);
    }

    var query = decodeURI( url.parse( req.url ).query), data = '',
        $url = /.*(http[s]?[:])/.test(query) ? query.replace(/.*(http[s]?[:])/,"$1") : 'http://' + req.headers.host + query;
    http.get($url, function(res) {
        resp.writeHead(res.statusCode, {"Content-Type": "text/html"});
        res.setEncoding('utf-8');
        res.on('data',function(d){
            data += d;
        }).on('end',function(){
            resp.end( '<!DOCTYPE html><meta charset="UTF-8" /><title>' + $url.split('/').pop() + '</title>
' + highlight(data) + '
');
        });
    }).on('error', function(e) {
        resp.writeHead(500, {"Content-Type": "text/html"});
          resp.end( e.stack.toString().replace(/\n/g,"
") );
    });
};
exports.parse = function(code){
    return {
        code: code,
        output: highlight(code),
        style: style
    };
};


text:
<ion-view view-title="Playlists">
  <ion-content>
    <ion-list>
      <ion-item class="item-icon-right" ng-repeat="p in playlists" ui-sref="tab.playlists-detail({id:p.id})">

{{p.name}}

      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>


text:
..
   Copyright 2014 Novartis Institutes for Biomedical Research

   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
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Model
=====

Overview
--------

The steps in a RNA-Seq sequence of operations are captured in a model.
The purpose is to formalize the steps enough to simplify the use of various tools for each step,
yet permit enough flexibility to allow an easy integration of additional tools and
approaches.

A canonical graph of steps for RNA-Seq is shown below.

.. note::

   There is no enforcement that a sequence of steps adheres strictly to this.
   The model is also defining the notion of `activities`, and it is possible
   that one step performs several activities (this will be the case for
   an in-house monolithic pipeline, for example). This feature allows
   us to integrate such steps into the comparison.

The model is directly used to provide an unified execution scheme (see :ref:`unified-execution-label`),
and constitutes the basis for writing "recipes" (see :ref:`recipes-label`).

.. note-canonical-model-begin

.. graphviz::

     digraph RNASeq {
     "Genomes"->"References";
     "Genomes"[label="repository of genomes", shape=invhouse, colorscheme=set36, style=filled, fillcolor=1];
     "References" -> "IndexedReference" -> "Alignment";
     "References"[shape=invhouse, colorscheme=set36, style=filled, fillcolor=1];
     "IndexedReference"[label="Indexed References", colorscheme=set36, style=filled, fillcolor=2];
     "SequencingReads" -> "Alignment";
     "SequencingReads"[label="Sequencing Reads", shape=invhouse, colorscheme=set36, style=filled, fillcolor=5];
     "Alignment" -> "Counts";
     "TranscriptAnnotation" -> "Alignment";
     "Alignment"[colorscheme=set36, style=filled, fillcolor=2];
     "Genomes"->"TranscriptAnnotation";
     "TranscriptAnnotation" -> "Counts";
     "TranscriptAnnotation"[label="Transcript Annotations", shape=invhouse, colorscheme=set36, style=filled, fillcolor=1];
     "Counts" -> "NormalizedCounts";
     "Counts"[colorscheme=set36, style=filled, fillcolor=3];
     "NormalizedCounts" -> "AbundanceEstimates";
     "NormalizedCounts"[label="Normalized Counts", colorscheme=set36, style=filled, fillcolor=3];
     "SampleInformation" -> "DifferentialExpression";
     "SampleInformation"[label="Sample Information", shape=invhouse, colorscheme=set36, style=filled, fillcolor=5];
     "Sample"->"SampleInformation";
     "Sample"->"SequencingReads";
     "Sample"[shape=invhouse, colorscheme=set36, style=filled, fillcolor=5];
     "AbundanceEstimates"->"DifferentialExpression";
     "TranscriptAnnotation" -> "AbundanceEstimates";
     "AbundanceEstimates"[label="Abundance Estimates", colorscheme=set36, style=filled, fillcolor=4];
     "DifferentialExpression"[label="Differential Expression", shape=invhouse, colorscheme=set36, style=filled, fillcolor=6];
     }

.. note-canonical-model-end

.. _sec-activities-label:

Activities
----------

Steps can perform one or several activities.
The list of possible activities is in :class:`ACTIVITY`

Inheritance diagram
-------------------

.. inheritance-diagram:: railroadtracks.rnaseq
   :parts: 1

Docstrings
----------

.. automodule:: railroadtracks.rnaseq
   :members:
   :special-members: __init__


text:
from flask import Flask
import os

# The following import will fail if the typing package overwrote the builtin.
from typing import Any, Optional, Sequence, Tuple

app = Flask(__name__)

@app.route('/')
def hello():
  return 'PASS'

if __name__ == '__main__':
  app.run(port=os.environ['PORT'], debug=True)


text:
package estrategia;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class ImprimeJanela implements Imprime {

	public void imprime(Documento doc) {

		// Gráfico/Janela
		JFrame janela = new JFrame(doc.getTitulo());
		janela.add(new JTextArea(doc.getTexto()));
		janela.setSize(400, 300);
		janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		janela.setVisible(true);
	}

}


text:
# 一行代码轻松切换5种默认动画

此篇文章为BaseRecyclerViewAdapterHelper源码解读第三篇,[开源库地址](https://github.com/CymChad/BaseRecyclerViewAdapterHelper),如果没有看过之前2篇文章的同学可以先去看看,大神可直接跳过.

[BaseRecyclerViewAdapterHelper源码解读(一) 封装简单的adapter和万能的BaseViewHolder](http://blog.csdn.net/xfhy_/article/details/78274652)

[BaseRecyclerViewAdapterHelper源码解读(二) 添加header和footer](http://blog.csdn.net/xfhy_/article/details/78274867)

今天给大家带来BaseRecyclerViewAdapterHelper是如何添加动画的.由于本人才学尚浅,如有有不对的地方,欢迎指正,谢谢.

# 一,定义5种默认动画类型

这5种动画是默认的,外界可以直接使用者5种动画,当然也支持自定义.

## BaseAnimation  动画的父类
```java
public interface BaseAnimation {
    /**
     * 返回一个Animator数组,方便扩展,可以在view上加多个动画
     * @param view
     * @return
     */
    Animator[] getAnimators(View view);
}
```

下面再看看实现类

## AlphaInAnimation
```java
/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 * 渐显
 */
public class AlphaInAnimation implements BaseAnimation {
    /**
     * 默认透明度从0
     */
    private static final float DEFAULT_ALPHA_FROM = 0f;
    private final float mFrom;

    public AlphaInAnimation() {
        this(DEFAULT_ALPHA_FROM);
    }

    public AlphaInAnimation(float from) {
        mFrom = from;
    }

    @Override
    public Animator[] getAnimators(View view) {
        //返回一个Animator数组    将动画附加到view上,透明度从mFrom-1f
        return new Animator[]{ObjectAnimator.ofFloat(view, "alpha", mFrom, 1f)};
    }
}
```
其实就是设置一个属性动画在view上,然后将Animator数组返回,外界就可以直接调用
anim.setDuration(mDuration).start();设置动画时长并开启加载动画了.

## ScaleInAnimation
```java
/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 * 缩放
 */
public class ScaleInAnimation implements BaseAnimation {
    private static final float DEFAULT_SCALE_FROM = .5f;
    private final float mFrom;

    public ScaleInAnimation() {
        this(DEFAULT_SCALE_FROM);
    }

    public ScaleInAnimation(float from) {
        mFrom = from;
    }

    @Override
    public Animator[] getAnimators(View view) {
        //设置scaleX和scaleY都从mFrom-1f
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", mFrom, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", mFrom, 1f);
        return new ObjectAnimator[]{scaleX, scaleY};
    }
}
```

## SlideInBottomAnimation
```java
/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 * 从下往上
 */
public class SlideInBottomAnimation implements BaseAnimation {
    @Override
    public Animator[] getAnimators(View view) {
        //这里设置的是view的纵坐标,从view.getMeasuredHeight()-0,相当于从下往上移动自身的高度
        return new Animator[]{
                ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
        };
    }
}
```

## SlideInLeftAnimation
```java
/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 * 从左往右
 */
public class SlideInLeftAnimation implements BaseAnimation {
    @Override
    public Animator[] getAnimators(View view) {
        //view 的translationX 从 -顶层root view的宽度~0
        return new Animator[]{
                ObjectAnimator.ofFloat(view, "translationX", -view.getRootView().getWidth(), 0)
        };
    }
}
```
## SlideInRightAnimation

```java
/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 * 从右往左
 */
public class SlideInRightAnimation implements BaseAnimation {
    @Override
    public Animator[] getAnimators(View view) {
        //view 的translationX 从 顶层root view的宽度~0
        return new Animator[]{
                ObjectAnimator.ofFloat(view, "translationX", view.getRootView().getWidth(), 0)
        };
    }
}

```

## SlideInTopAnimation
从上往下,这是我自己加的,感觉这种动画效果很不错嘛
```java
/**
 * author feiyang
 * create at 2017/10/19 10:37
 * description:从上往下
 */
public class SlideInTopAnimation implements BaseAnimation {

    @Override
    public Animator[] getAnimators(View view) {
        return new Animator[]{
                ObjectAnimator.ofFloat(view, "translationY", -view.getMeasuredHeight(), 0)};
    }
}
```

# 二,再看看BaseQuickAdapter

```java
    //Animation
    /**
     * Use with {@link #openLoadAnimation}
     */
    public static final int ALPHAIN = 0x00000001;
    /**
     * Use with {@link #openLoadAnimation}
     */
    public static final int SCALEIN = 0x00000002;
    /**
     * Use with {@link #openLoadAnimation}
     */
    public static final int SLIDEIN_BOTTOM = 0x00000003;
    /**
     * Use with {@link #openLoadAnimation}
     */
    public static final int SLIDEIN_LEFT = 0x00000004;
    /**
     * Use with {@link #openLoadAnimation}
     */
    public static final int SLIDEIN_RIGHT = 0x00000005;

    @IntDef({ALPHAIN, SCALEIN, SLIDEIN_BOTTOM, SLIDEIN_LEFT, SLIDEIN_RIGHT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface AnimationType {
    }

    /**
     * 动画只执行1次?
     */
    private boolean mFirstOnlyEnable = true;
    /**
     * 开启了动画?
     */
    private boolean mOpenAnimationEnable = false;
    private Interpolator mInterpolator = new LinearInterpolator();
    /**
     * 动画播放时长
     */
    private int mDuration = 300;
    /**
     * 上一个在播放动画的item的位置
     */
    private int mLastPosition = -1;

    /**
     * 自定义的动画
     */
    private BaseAnimation mCustomAnimation;
    /**
     * 当前选择使用哪种动画
     */
    private BaseAnimation mSelectAnimation = new AlphaInAnimation();

```
上面就是定义了5种默认的动画
- ALPHAIN 渐显
- SCALEIN 缩放
- SLIDEIN_BOTTOM 从下到上
- SLIDEIN_LEFT 从左到右
- SLIDEIN_RIGHT 从右到左

并且下面还定义了AnimationType,这里是注解类型有点类似于枚举,就是当使用@AnimationType修饰的参数时只能使用上面的5种动画常量中的1种.关于枚举,其实很有必要学习一下,在很多时候可以规范我们的编码,可以看看Airsaid大神写的[Android 中注解的使用](https://juejin.im/post/59bf5e1c518825397176d126).

后面是一些其他的属性,已加入详细注释.

## 设置从哪个item开始执行动画
```java
    /**
     * up fetch end
     * 设置count个不执行动画
     */
    public void setNotDoAnimationCount(int count) {
        mLastPosition = count;
    }
```
可以看到,将mLastPosition设置为count,mLastPosition之前的item是不会被加载动画了.

## 当视图附加到窗口时,开始执行动画

```java
    /**
     * Called when a view created by this adapter has been attached to a window.
     * simple to solve item will layout using all
     *
     * {@link #setFullSpan(RecyclerView.ViewHolder)}
     *
     * @param holder
     */
    @Override
    public void onViewAttachedToWindow(K holder) {
        super.onViewAttachedToWindow(holder);
        int type = holder.getItemViewType();
        if (type == EMPTY_VIEW || type == HEADER_VIEW || type == FOOTER_VIEW || type ==
                LOADING_VIEW) {
            //设置为跨区域  比如是StaggeredGridLayoutManager时,header或者footer等应该如何展示
            setFullSpan(holder);
        } else {
            //添加动画到holder的itemView上,并执行动画
            addAnimation(holder);
        }
    }

    /**
     * add animation when you want to show time
     * 添加动画到item上并执行动画
     * @param holder
     */
    private void addAnimation(RecyclerView.ViewHolder holder) {
        // 判断是否开启了动画
        if (mOpenAnimationEnable) {
            //  !isFirstOnly            这一次item的位置>上一次加载动画item的位置
            if (!mFirstOnlyEnable || holder.getLayoutPosition() > mLastPosition) {
                BaseAnimation animation = null;
                //判断是否是自定义了动画
                if (mCustomAnimation != null) {
                    animation = mCustomAnimation;
                } else {
                    //没有自定义,则使用默认的动画
                    animation = mSelectAnimation;
                }
                // 遍历定义到holder.itemView上的动画  BaseAnimation使用的getAnimators()是获取动画数组,方便扩展
                // 如果用户需要自定义动画的话,则可以在一个item上同时加入多个动画,然后下面让这些动画依次执行
                for (Animator anim : animation.getAnimators(holder.itemView)) {
                    //开启动画
                    startAnim(anim, holder.getLayoutPosition());
                }
                //记录这一次执行动画的item
                mLastPosition = holder.getLayoutPosition();
            }
        }
    }

    /**
     * set anim to start when loading
     * 开启动画并设置插值器
     * @param anim
     * @param index
     */
    protected void startAnim(Animator anim, int index) {
        anim.setDuration(mDuration).start();
        anim.setInterpolator(mInterpolator);
    }
```
- 当view被添加到window时,给view附加动画到上面去,然后开始执行动画.
- 在addAnimation()时首先是判断了是否开启动画,再判断是否是只需要显示一次,再根据是否是自定义的动画然后生成不同的animation,遍历Animator数组开始依次执行动画.

## 设置动画类型

``` java
 /**
     * Set the view animation type.
     * 设置动画类型
     * @param animationType One of {@link #ALPHAIN}, {@link #SCALEIN}, {@link #SLIDEIN_BOTTOM},
     *                      {@link #SLIDEIN_LEFT}, {@link #SLIDEIN_RIGHT}.
     */
    public void openLoadAnimation(@AnimationType int animationType) {
        //标志着需要加载动画
        this.mOpenAnimationEnable = true;
        //用户没有自定义动画  是使用的默认动画
        mCustomAnimation = null;
        //根据用户传入的类型初始化应该使用哪种动画
        switch (animationType) {
            case ALPHAIN:
                mSelectAnimation = new AlphaInAnimation();
                break;
            case SCALEIN:
                mSelectAnimation = new ScaleInAnimation();
                break;
            case SLIDEIN_BOTTOM:
                mSelectAnimation = new SlideInBottomAnimation();
                break;
            case SLIDEIN_LEFT:
                mSelectAnimation = new SlideInLeftAnimation();
                break;
            case SLIDEIN_RIGHT:
                mSelectAnimation = new SlideInRightAnimation();
                break;
            default:
                break;
        }
    }

    /**
     * Set Custom ObjectAnimator
     * 自定义动画
     * @param animation ObjectAnimator
     */
    public void openLoadAnimation(BaseAnimation animation) {
        //标志着需要加载动画
        this.mOpenAnimationEnable = true;
        //初始化自定义动画
        this.mCustomAnimation = animation;
    }

    /**
     * To open the animation when loading
     * 开启动画,这种情况下会默认开启:渐显动画
     */
    public void openLoadAnimation() {
        this.mOpenAnimationEnable = true;
    }

    /**
     * {@link #addAnimation(RecyclerView.ViewHolder)}
     * 设置动画是否只加载一次
     * @param firstOnly true just show anim when first loading false show anim when load the data
     *                  every time  true:第一次显示时才加载动画   false:每次都加载动画
     */
    public void isFirstOnly(boolean firstOnly) {
        this.mFirstOnlyEnable = firstOnly;
    }
```
这里主要是做一些配置信息的初始化
- 动画类型
- 自定义动画配置
- 是否只需要加载一次

## 总结

- 其实今天的重点**是onViewAttachedToWindow(),当view被添加到window时,通过holder找到view,给view依次执行动画.**
- 其他的都是一些修饰,比如在开源库中自带了几种默认的动画效果可以提供给开发者选择,显得更加人性化.
- 其次,该开源库这样设计之后不仅调用简单,只需一行代码.而且还支持自定义动画.
- 再其次,该开源库真的超级强大,大家有空多看看源码,收获颇多.
- 最后,感谢开发者的无私奉献,该开源库地址:https://github.com/CymChad/BaseRecyclerViewAdapterHelper


text:
"""
The Tornado Framework
By Ali Pesaranghader
University of Ottawa, Ontario, Canada
E-mail: apesaran -at- uottawa -dot- ca / alipsgh -at- gmail -dot- com
"""

class DriftDetectionEvaluator:
    """This class is used to evaluate a drift detection method."""

    @staticmethod
    def calculate_dl_tp_fp_fn(located_points, actual_points, interval):

        actual_drift_points = actual_points.copy()

        num_actual_drifts = len(actual_points)
        num_located_drift_points = len(located_points)

        drift_detection_tp = 0
        drift_detection_dl = []
        for located in located_points:
            for actual in actual_points:
                if actual <= located <= actual + interval:
                    drift_detection_tp += 1
                    drift_detection_dl.append(located - actual - (actual_drift_points.index(actual) + 1))
                    actual_points.remove(actual)
                    break
        drift_detection_dl = sum(drift_detection_dl) + (num_actual_drifts - len(drift_detection_dl)) * interval
        drift_detection_dl /= num_actual_drifts
        drift_detection_fp = num_located_drift_points - drift_detection_tp
        drift_detection_fn = num_actual_drifts - drift_detection_tp

        return drift_detection_dl, drift_detection_tp, drift_detection_fp, drift_detection_fn


text:
import { listenOn } from '@/helpers';

class TouchSupport {
  _bindEvents () {
    const body = this.modules.renderer.body;

    listenOn(body.root, 'touchstart', (event) => {
      document.documentElement.classList.add('jsr_lockscreen');

      event = event.targetTouches.item(0);
      event.bubbles = true;
      event.cancelable = true;
      const mouseEvent = new MouseEvent('mousedown', event);
      event.target.dispatchEvent(mouseEvent);
    });

    listenOn(document, 'touchmove', (event) => {
      event = event.targetTouches.item(0);
      event.bubbles = true;
      event.cancelable = true;
      const mouseEvent = new MouseEvent('mousemove', event);
      event.target.dispatchEvent(mouseEvent);
    });

    listenOn(document, 'touchend', (event) => {
      document.documentElement.classList.remove('jsr_lockscreen');

      event = event.changedTouches.item(0);
      event.bubbles = true;
      event.cancelable = true;
      const mouseEvent = new MouseEvent('mouseup', event);
      event.target.dispatchEvent(mouseEvent);
    });
  }

  /* API */
  build ({ config, modules, logger }) {
    this.logger = logger;
    this.config = config;
    this.modules = modules;

    this._bindEvents();
  }
}

export default {
  name: 'touchSupport',
  Klass: TouchSupport
};


text:
package org.axonframework.quickstart.annotated;

import org.axonframework.quickstart.api.CreateToDoItemCommand;
import org.axonframework.quickstart.api.MarkCompletedCommand;
import org.axonframework.quickstart.api.ToDoItemCompletedEvent;
import org.axonframework.quickstart.api.ToDoItemCreatedEvent;
import org.axonframework.test.FixtureConfiguration;
import org.axonframework.test.Fixtures;
import org.junit.*;

/**
 * @author Jettro Coenradie
 */
public class ToDoItemTest {

    private FixtureConfiguration<ToDoItem> fixture;

    @Before
    public void setUp() throws Exception {
        fixture = Fixtures.newGivenWhenThenFixture(ToDoItem.class);
    }

    @Test
    public void testCreateToDoItem() throws Exception {
        fixture.given()
               .when(new CreateToDoItemCommand("todo1", "Need to implement the aggregate"))
               .expectEvents(new ToDoItemCreatedEvent("todo1", "Need to implement the aggregate"));
    }

    @Test
    public void testMarkToDoItemAsCompleted() throws Exception {
        fixture.given(new ToDoItemCreatedEvent("todo1", "Need to implement the aggregate"))
               .when(new MarkCompletedCommand("todo1"))
               .expectEvents(new ToDoItemCompletedEvent("todo1"));
    }
}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using MS.Utility;
using MS.Internal;

#if PBTCOMPILER
using System.Reflection;

namespace MS.Internal.Markup
#else

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using MS.Internal.Media;

namespace System.Windows.Markup
#endif
{
    /// <summary>
    ///     XamlVector3DCollectionSerializer is used to persist collections of 3D vectors in Baml
    /// </summary>

    internal class XamlVector3DCollectionSerializer : XamlSerializer
    {
#region Construction

        /// <summary>
        ///     Constructor for XamlVector3DCollectionSerializer
        /// </summary>
        /// <remarks>
        ///     This constructor will be used under
        ///     the following two scenarios
        ///     1. Convert a string to a custom binary representation stored in BAML
        ///     2. Convert a custom binary representation back into a Brush
        /// </remarks>
        internal XamlVector3DCollectionSerializer()
        {
        }

#endregion Construction

#region Conversions

        /// <summary>
        ///   Convert a string into a compact binary representation and write it out
        ///   to the passed BinaryWriter.
        /// </summary>
        public override bool ConvertStringToCustomBinary (
            BinaryWriter   writer,           // Writer into the baml stream
            string         stringValue)      // String to convert
        {
            return XamlSerializationHelper.SerializeVector3D( writer, stringValue ) ;
        }

#if !PBTCOMPILER

        /// <summary>
        ///   Convert a compact binary representation of a collection
        ///     into a Point3DCollection into and instance
        /// </summary>
        /// <remarks>
        /// This is called ONLY from the Parser and is not a general internal method.
        /// </remarks>
        public override object ConvertCustomBinaryToObject(
            BinaryReader reader)
        {
            return Vector3DCollection.DeserializeFrom( reader ) ;
        }

        /// <summary>
        ///   Convert a compact binary representation of a collection
        ///     into a Point3DCollection into and instance
        /// </summary>
        /// <remarks>
        /// This is called ONLY from the Parser and is not a general internal method.
        /// </remarks>
        public static object StaticConvertCustomBinaryToObject(
            BinaryReader reader)
        {
            return Vector3DCollection.DeserializeFrom( reader ) ;
        }
#endif

#endregion Conversions

    }
}


text:
title: Doing the unexpected constitutes poor design
categories: IT Related
date: 2006-04-11 00:39:00 +10:00
---

 I just went to a website for a company that a friend now works for. They have included a search engine in their site. Given that I am interested in the contents of this site, I thought I would give the search a go.

 No matter what search criteria I enter, I get taken to a FAQ page. So is this a bug in their code, or were there just no results and they assumed that I would figure that out?

 This is a great example of poor design. If the user is expecting results, don't give them something else. If there really are no results, just say so. Don't take the user somewhere they didn't ask for.

 Here ends the rant.


text:
#ifndef EVALUATE_H_INCLUDED
#define EVALUATE_H_INCLUDED

#include <string>

#include "types.h"

class Position;

namespace Eval {

const Value Tempo = Value(17); // Must be visible to search

void init();
Value evaluate(const Position& pos);
std::string trace(const Position& pos);

}

#endif // #ifndef EVALUATE_H_INCLUDED


text:
package org.ldp4j.tutorial.client;

enum Command {

	EXIT("exit","Terminate the client shell",ExitCommandProcessor.class),
	CLEAR("clear","Clear the console",ClearCommandProcessor.class),
	HELP("help","Show the client shell help",HelpCommandProcessor.class),
	LIST_REPRESENTATIONS("list-cached-representations","Show the list of cached representations",ListCachedRepresentationsCommandProcessor.class),
	SHOW_REPRESENTATION("show-cached-representation","Show the cached representation of a given resource",ShowCachedRepresentationCommandProcessor.class),
	RETRIEVE("retrieve-resource","Retrieve a LDP resource",RetrieveCommandProcessor.class),
	DELETE("delete-resource","Delete a LDP resource",DeleteCommandProcessor.class),
	MODIFY("modify-resource","Modify a LDP resource",ModifyCommandProcessor.class),
	CREATE("create-resource","Create a LDP resource",CreateCommandProcessor.class),
	;

	private String commandName;
	private String commandDescription;
	private Class<? extends CommandProcessor> clazz;

	Command(String name, String description, Class<? extends CommandProcessor> clazz) {
		this.commandName = name;
		this.commandDescription = description;
		this.clazz = clazz;
	}

	static Command fromString(String name) {
		Command targetCmd=null;
		for(Command cmd:values()) {
			if(cmd.commandName.equalsIgnoreCase(name)) {
				targetCmd=cmd;
				break;
			}
		}
		return targetCmd;
	}

	CommandProcessor createProcessor() {
		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new IllegalStateException("Could not prepare processor for command '"+this.commandName+"' ("+this.clazz.getCanonicalName()+")",e);
		}
	}

	public String commandDescription() {
		return this.commandDescription;
	}

	public String commandName() {
		return this.commandName;
	}

}


text:
<?php

/*
 * PatternList class
 * @author Jake Josol
 * @description A list for holding Regular Expression patterns
 */

class PatternList extends Warp\Utils\PatternList {}

?>


text:
CGImageRef CGImageFromANImage (ANImageObj * anImageObj) {
#if TARGET_OS_IPHONE
	return [anImageObj CGImage];
#elif TARGET_OS_MAC
	CGImageSourceRef source;
#if __has_feature(objc_arc) == 1
	source = CGImageSourceCreateWithData((__bridge CFDataRef)[anImageObj TIFFRepresentation], NULL);
#else
	source = CGImageSourceCreateWithData((CFDataRef)[anImageObj TIFFRepresentation], NULL);
#endif
	CGImageRef maskRef = CGImageSourceCreateImageAtIndex(source, 0, NULL);
	CFRelease(source);
#if __has_feature(objc_arc) == 1
	CGImageRef autoreleased = (__bridge CGImageRef)CGImageReturnAutoreleased(maskRef);
	CGImageRelease(maskRef);
	return autoreleased;
#else
	CGImageContainer * container = [CGImageContainer imageContainerWithImage:maskRef];
	CGImageRelease(maskRef);
	return [container image];
#endif
#endif
}

ANImageObj * ANImageFromCGImage (CGImageRef imageRef) {
#if TARGET_OS_IPHONE
	return [UIImage imageWithCGImage:imageRef];
#elif TARGET_OS_MAC
	NSImage * image = [[NSImage alloc] initWithCGImage:imageRef size:NSZeroSize];
#if __has_feature(objc_arc) == 1
	return image;
#else
	return [image autorelease];
#endif
#endif
}


text:
<?php

namespace ForsakenIvoryCoffin\Parsers\DocumentParsers;

use ForsakenIvoryCoffin\Parsers\DocumentParserInterface;
use ForsakenIvoryCoffin\Parsers\ElementParserInterface;

/**
 * Parse a XML file using SAX
 *
 * @author Patrick
 */
class SaxParser implements DocumentParserInterface
{

    const BLOCK_SIZE = 4096;

    /**
     *
     * @var resource
     */
    private $parser;

    /**
     *
     * @var ElementParserInterface
     */
    private $elementParser;

    /**
     *
     * @var string
     */
    private $filepath;

    /**
     * Constructor sets the xml_parser object
     */
    public function __construct()
    {
        $this->parser = xml_parser_create();
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, true);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    }

    /**
     * Parse the xml file
     *
     * @throws \Exception When the file could not be opened or a parser error occured.
     */
    public function parse()
    {
        if (!($fp = fopen($this->filepath, 'r'))) {
            $msg = sprintf("Could not open file: %s", $this->filepath);
            throw new \Exception($msg);
        }

        while ($data = fread($fp, self::BLOCK_SIZE)) {
            if (!xml_parse($this->parser, $data, feof($fp))) {

                //Could not parse, throw exception
                $errorString = xml_error_string($this->parser);
                $lineNumber  = xml_get_current_line_number($this->parser);
                $msg         = "Parse error: %s at line %s";
                throw new \Exception(sprintf($msg, $errorString, $lineNumber));
            }
        }
        fclose($fp);
    }

    /**
     *
     * @param string $filePath
     */
    public function setFile($filePath)
    {
        $this->filepath = $filePath;
    }

    /**
     *
     * @param \ForsakenIvoryCoffin\Parsers\ElementParserInterface $elementParser
     */
    public function setElementParser(ElementParserInterface $elementParser)
    {
        $this->elementParser = $elementParser;
        $startCallable       = array($this, 'callStart');
        $endCallable         = array($this, 'callEnd');
        $dataCallable        = array($this, 'callContent');
        xml_set_element_handler($this->parser, $startCallable, $endCallable);
        xml_set_character_data_handler($this->parser, $dataCallable);
    }

    /**
     * Free the xml_parser object
     */
    public function __destruct()
    {
        xml_parser_free($this->parser);
    }

    /**
     * Adapter for ElementParser->parseStart()
     *
     * @param resource $p
     * @param string $elementName
     * @param array $attributes
     */
    private function callStart($p, $elementName, array $attributes)
    {
        $this->elementParser->parseStart($elementName, $attributes);
    }

    /**
     * Adapter for ElementParser->parseEnd()
     *
     * @param resource $p
     * @param string $elementName
     */
    private function callEnd($p, $elementName)
    {
        $this->elementParser->parseEnd($elementName);
    }

    /**
     * Adapter for ElementParser->parseContent()
     *
     * @param resource $p
     * @param string $content
     */
    private function callContent($p, $content)
    {
        // Only parseContent when there is more then just whitespace
        if (strlen(trim($content)) > 0) {
            $this->elementParser->parseContent($content);
        }
    }

}


text:
extern "C" {
#include <stdint.h>
}

#include <cstddef>
#include <memory>
#include <ostream>
#include <string>

namespace utils {
namespace datetime {

/// Represents a time delta to describe deadlines.
///
/// Because we use this class to handle deadlines, we currently do not support
/// negative deltas.
class delta {
public:
    /// The amount of seconds in the time delta.
    int64_t seconds;

    /// The amount of microseconds in the time delta.
    unsigned long useconds;

    delta(void);
    delta(const int64_t, const unsigned long);

    static delta from_microseconds(const int64_t);
    int64_t to_microseconds(void) const;

    bool operator==(const delta&) const;
    bool operator!=(const delta&) const;
    bool operator<(const delta&) const;
    bool operator<=(const delta&) const;
    bool operator>(const delta&) const;
    bool operator>=(const delta&) const;

    delta operator+(const delta&) const;
    delta& operator+=(const delta&);
    // operator- and operator-= do not exist because we do not support negative
    // deltas.  See class docstring.
    delta operator*(const std::size_t) const;
    delta& operator*=(const std::size_t);
};

std::ostream& operator<<(std::ostream&, const delta&);

/// Represents a fixed date/time.
///
/// Timestamps are immutable objects and therefore we can simply use a shared
/// pointer to hide the implementation type of the date.  By not using an auto
/// pointer, we don't have to worry about providing our own copy constructor and
/// assignment opertor.
class timestamp {
    struct impl;

    /// Pointer to the shared internal implementation.
    std::shared_ptr< impl > _pimpl;

    timestamp(std::shared_ptr< impl >);

public:
    static timestamp from_microseconds(const int64_t);
    static timestamp from_values(const int, const int, const int,
                                 const int, const int, const int,
                                 const int);
    static timestamp now(void);

    std::string strftime(const std::string&) const;
    std::string to_iso8601_in_utc(void) const;
    int64_t to_microseconds(void) const;
    int64_t to_seconds(void) const;

    bool operator==(const timestamp&) const;
    bool operator!=(const timestamp&) const;
    bool operator<(const timestamp&) const;
    bool operator<=(const timestamp&) const;
    bool operator>(const timestamp&) const;
    bool operator>=(const timestamp&) const;

    timestamp operator+(const delta&) const;
    timestamp& operator+=(const delta&);
    timestamp operator-(const delta&) const;
    timestamp& operator-=(const delta&);
    delta operator-(const timestamp&) const;
};

std::ostream& operator<<(std::ostream&, const timestamp&);

void set_mock_now(const int, const int, const int, const int, const int,
                  const int, const int);
void set_mock_now(const timestamp&);

}  // namespace datetime
}  // namespace utils

#endif // !defined(UTILS_DATETIME_HPP)


text:
<!--
  ~ Copyright (c) Microsoft Corporation. All rights reserved.
  ~ Licensed under the MIT License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.azure</groupId>
    <artifactId>azure-client-sdk-parent</artifactId>
    <version>1.7.0</version> <!-- {x-version-update;com.azure:azure-client-sdk-parent;current} -->
    <relativePath>../../parents/azure-client-sdk-parent</relativePath>
  </parent>

  <groupId>com.azure</groupId>
  <artifactId>azure-core-serializer-json-jackson</artifactId>
  <packaging>jar</packaging>
  <version>1.1.0-beta.1</version> <!-- {x-version-update;com.azure:azure-core-serializer-json-jackson;current} -->

  <name>Microsoft Azure Jackson JSON Serializer Library</name>
  <description>This package contains the Jackson JSON serializer client plugin for azure-core.</description>
  <url>https://github.com/Azure/azure-sdk-for-java</url>

  <licenses>
    <license>
      <name>The MIT License (MIT)</name>
      <url>http://opensource.org/licenses/MIT</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <distributionManagement>
    <site>
      <id>azure-java-build-docs</id>
      <url>${site.url}/site/${project.artifactId}</url>
    </site>
  </distributionManagement>

  <scm>
    <url>https://github.com/Azure/azure-sdk-for-java</url>
    <connection>scm:git:https://github.com/Azure/azure-sdk-for-java.git</connection>
    <developerConnection>scm:git:https://github.com/Azure/azure-sdk-for-java.git</developerConnection>
  </scm>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <legal><![CDATA[[INFO] Any downloads listed may be third party software.  Microsoft grants you no rights for third party software.]]></legal>
  </properties>

  <developers>
    <developer>
      <id>microsoft</id>
      <name>Microsoft</name>
    </developer>
  </developers>

  <dependencies>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core</artifactId>
      <version>1.10.0-beta.1</version> <!-- {x-version-update;com.azure:azure-core;current} -->
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.6.2</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-api;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>5.6.2</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-engine;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <version>5.6.2</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-params;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>3.3.3</version><!-- {x-version-update;org.mockito:mockito-core;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-test</artifactId>
      <version>3.3.9.RELEASE</version> <!-- {x-version-update;io.projectreactor:reactor-test;external_dependency} -->
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
      <id>java-lts</id>
      <activation>
        <jdk>[11,)</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M3</version> <!-- {x-version-update;org.apache.maven.plugins:maven-surefire-plugin;external_dependency} -->
            <configuration>
              <argLine>
                --add-exports com.azure.core.serializer.json.jackson/com.azure.core.serializer.json.jackson=com.fasterxml.jackson.databind
                --add-opens com.azure.core.serializer.json.jackson/com.azure.core.serializer.json.jackson=com.fasterxml.jackson.databind
                --add-opens com.azure.core.serializer.json.jackson/com.azure.core.serializer.json.jackson=ALL-UNNAMED
              </argLine>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
class AddMeetingIdsToAttendees < ActiveRecord::Migration
  def change
  	add_column :attendees, :meeting_id, :integer
  end
end


text:
<?php

namespace ZRayExtension;

class Module extends \ZRay\ZRayModule
{
    public function config()
    {
        return array(
            'extension' => array(
                'name' => 'CodeIgniter',
            ),
            'panels' => array(
                'codingstandard' => array(
                    'display' => true,
                    'logo' => 'images/codingstandard.png',
                    'menuTitle' => 'Coding standard',
                    'panelTitle' => 'Coding standard',
                    'searchId' => 'codeigniter-coding-search',
                    'pagerId' => 'codeigniter-coding-pager',
                ),
                'cache' => array(
                    'display' => true,
                    'logo' => 'images/cache.png',
                    'menuTitle' => 'Cache',
                    'panelTitle' => 'Cache Info',
                    'searchId' => 'codeigniter-cache-search',
                ),
                'request' => array(
                    'display' => true,
                    'logo' => 'images/request.png',
                    'menuTitle' => 'Request',
                    'panelTitle' => 'Request Info',
                    'searchId' => 'codeigniter-request-search',
                ),
                'helpers' => array(
                    'display' => true,
                    'logo' => 'images/helper.png',
                    'menuTitle' => 'Helpers',
                    'panelTitle' => 'Loaded helpers',
                    'searchId' => 'codeigniter-helpers-search',
                ),
                'models' => array(
                    'display' => true,
                    'logo' => 'images/model.png',
                    'menuTitle' => 'Models',
                    'panelTitle' => 'Loaded models',
                    'searchId' => 'codeigniter-models-search',
                ),
                'libraries' => array(
                    'display' => true,
                    'logo' => 'images/library.png',
                    'menuTitle' => 'Libraries',
                    'panelTitle' => 'Loaded libraries',
                    'searchId' => 'codeigniter-libraries-search',
                ),
                'hooks' => array(
                    'display' => true,
                    'logo' => 'images/hook.png',
                    'menuTitle' => 'Hooks',
                    'panelTitle' => 'Active hooks',
                    'searchId' => 'codeigniter-hooks-search',
                ),
                'views' => array(
                    'display' => true,
                    'logo' => 'images/view.png',
                    'menuTitle' => 'Views',
                    'panelTitle' => 'Loaded views',
                ),
                'configuration' => array(
                    'display' => true,
                    'logo' => 'images/config.png',
                    'menuTitle' => 'Configuration',
                    'panelTitle' => 'Configuration',
                    'searchId' => 'codeigniter-configuration-search',
                    'pagerId' => 'codeigniter-configuration-pager',
                ),
                'installation' => array(
                    'display' => true,
                    'logo' => 'logo.png',
                    'menuTitle' => 'Installation',
                    'panelTitle' => 'Installation',
                ),
            )
        );
    }
}


text:
function C = plot_confusionmat(gt, pred, labels, savePath, fTitle)
%PLOT_CONFUSIONMAT plot confusion matrix from classification results
%   gt::
%       Nx1 ground truth labels
%   pred::
%       Nx1 predicted labels
%   labels::
%       Nx1 cell, label names
%   savePath:: []
%       path to save the figure as pdf file
%       if specified, figure will be closed automatically
%   fTitle:: 'confusion matrix'
%       title of figure

if ~exist('fTitle','var') || isempty(fTitle),
    fTitle = 'confusion matrix';
end
if ~exist('savePath','var') || isempty(savePath),
    savePath = [];
end

C = confusionmat(gt,pred);
S = sum(C,2);
S(S==0)=1;
C = bsxfun(@rdivide, C, S);

figure(1); clf;
imagesc(C); colormap(gray);
title(fTitle);
axis square; colorbar;

labels = cellfun(@(s) strrep(s,'_',' '), labels, 'UniformOutput', false);

% set(gca, 'XTick', 1:length(labels), 'XTickLabel', labels);
set(gca, 'XTick', 1:length(labels), 'XTickLabel', []);
set(gca, 'YTick', 1:length(labels), 'YTickLabel', labels);

drawnow;
if ~isempty(savePath),
    print(1, savePath, '-dpdf');
    close(1);
end