text:
"""Support for Ambient Weather Station Service."""
from __future__ import annotations

from aioambient import Client
from aioambient.errors import WebsocketError

from homeassistant.components.binary_sensor import (
    DEVICE_CLASS_CONNECTIVITY,
    DOMAIN as BINARY_SENSOR,
)
from homeassistant.components.sensor import DOMAIN as SENSOR
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    ATTR_LOCATION,
    ATTR_NAME,
    CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
    CONCENTRATION_PARTS_PER_MILLION,
    CONF_API_KEY,
    DEGREE,
    DEVICE_CLASS_BATTERY,
    DEVICE_CLASS_CO2,
    DEVICE_CLASS_HUMIDITY,
    DEVICE_CLASS_ILLUMINANCE,
    DEVICE_CLASS_PRESSURE,
    DEVICE_CLASS_TEMPERATURE,
    DEVICE_CLASS_TIMESTAMP,
    EVENT_HOMEASSISTANT_STOP,
    IRRADIATION_WATTS_PER_SQUARE_METER,
    LIGHT_LUX,
    PERCENTAGE,
    PRECIPITATION_INCHES,
    PRECIPITATION_INCHES_PER_HOUR,
    PRESSURE_INHG,
    SPEED_MILES_PER_HOUR,
    TEMP_FAHRENHEIT,
)
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.dispatcher import (
    async_dispatcher_connect,
    async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_call_later

from .const import (
    ATTR_LAST_DATA,
    ATTR_MONITORED_CONDITIONS,
    CONF_APP_KEY,
    DATA_CLIENT,
    DOMAIN,
    LOGGER,
)

PLATFORMS = [BINARY_SENSOR, SENSOR]

DATA_CONFIG = "config"

DEFAULT_SOCKET_MIN_RETRY = 15

TYPE_24HOURRAININ = "24hourrainin"
TYPE_BAROMABSIN = "baromabsin"
TYPE_BAROMRELIN = "baromrelin"
TYPE_BATT1 = "batt1"
TYPE_BATT10 = "batt10"
TYPE_BATT2 = "batt2"
TYPE_BATT3 = "batt3"
TYPE_BATT4 = "batt4"
TYPE_BATT5 = "batt5"
TYPE_BATT6 = "batt6"
TYPE_BATT7 = "batt7"
TYPE_BATT8 = "batt8"
TYPE_BATT9 = "batt9"
TYPE_BATT_CO2 = "batt_co2"
TYPE_BATTOUT = "battout"
TYPE_CO2 = "co2"
TYPE_DAILYRAININ = "dailyrainin"
TYPE_DEWPOINT = "dewPoint"
TYPE_EVENTRAININ = "eventrainin"
TYPE_FEELSLIKE = "feelsLike"
TYPE_HOURLYRAININ = "hourlyrainin"
TYPE_HUMIDITY = "humidity"
TYPE_HUMIDITY1 = "humidity1"
TYPE_HUMIDITY10 = "humidity10"
TYPE_HUMIDITY2 = "humidity2"
TYPE_HUMIDITY3 = "humidity3"
TYPE_HUMIDITY4 = "humidity4"
TYPE_HUMIDITY5 = "humidity5"
TYPE_HUMIDITY6 = "humidity6"
TYPE_HUMIDITY7 = "humidity7"
TYPE_HUMIDITY8 = "humidity8"
TYPE_HUMIDITY9 = "humidity9"
TYPE_HUMIDITYIN = "humidityin"
TYPE_LASTRAIN = "lastRain"
TYPE_MAXDAILYGUST = "maxdailygust"
TYPE_MONTHLYRAININ = "monthlyrainin"
TYPE_PM25 = "pm25"
TYPE_PM25_24H = "pm25_24h"
TYPE_PM25_BATT = "batt_25"
TYPE_PM25_IN = "pm25_in"
TYPE_PM25_IN_24H = "pm25_in_24h"
TYPE_PM25IN_BATT = "batt_25in"
TYPE_RELAY1 = "relay1"
TYPE_RELAY10 = "relay10"
TYPE_RELAY2 = "relay2"
TYPE_RELAY3 = "relay3"
TYPE_RELAY4 = "relay4"
TYPE_RELAY5 = "relay5"
TYPE_RELAY6 = "relay6"
TYPE_RELAY7 = "relay7"
TYPE_RELAY8 = "relay8"
TYPE_RELAY9 = "relay9"
TYPE_SOILHUM1 = "soilhum1"
TYPE_SOILHUM10 = "soilhum10"
TYPE_SOILHUM2 = "soilhum2"
TYPE_SOILHUM3 = "soilhum3"
TYPE_SOILHUM4 = "soilhum4"
TYPE_SOILHUM5 = "soilhum5"
TYPE_SOILHUM6 = "soilhum6"
TYPE_SOILHUM7 = "soilhum7"
TYPE_SOILHUM8 = "soilhum8"
TYPE_SOILHUM9 = "soilhum9"
TYPE_SOILTEMP1F = "soiltemp1f"
TYPE_SOILTEMP10F = "soiltemp10f"
TYPE_SOILTEMP2F = "soiltemp2f"
TYPE_SOILTEMP3F = "soiltemp3f"
TYPE_SOILTEMP4F = "soiltemp4f"
TYPE_SOILTEMP5F = "soiltemp5f"
TYPE_SOILTEMP6F = "soiltemp6f"
TYPE_SOILTEMP7F = "soiltemp7f"
TYPE_SOILTEMP8F = "soiltemp8f"
TYPE_SOILTEMP9F = "soiltemp9f"
TYPE_SOLARRADIATION = "solarradiation"
TYPE_SOLARRADIATION_LX = "solarradiation_lx"
TYPE_TEMP10F = "temp10f"
TYPE_TEMP1F = "temp1f"
TYPE_TEMP2F = "temp2f"
TYPE_TEMP3F = "temp3f"
TYPE_TEMP4F = "temp4f"
TYPE_TEMP5F = "temp5f"
TYPE_TEMP6F = "temp6f"
TYPE_TEMP7F = "temp7f"
TYPE_TEMP8F = "temp8f"
TYPE_TEMP9F = "temp9f"
TYPE_TEMPF = "tempf"
TYPE_TEMPINF = "tempinf"
TYPE_TOTALRAININ = "totalrainin"
TYPE_UV = "uv"
TYPE_WEEKLYRAININ = "weeklyrainin"
TYPE_WINDDIR = "winddir"
TYPE_WINDDIR_AVG10M = "winddir_avg10m"
TYPE_WINDDIR_AVG2M = "winddir_avg2m"
TYPE_WINDGUSTDIR = "windgustdir"
TYPE_WINDGUSTMPH = "windgustmph"
TYPE_WINDSPDMPH_AVG10M = "windspdmph_avg10m"
TYPE_WINDSPDMPH_AVG2M = "windspdmph_avg2m"
TYPE_WINDSPEEDMPH = "windspeedmph"
TYPE_YEARLYRAININ = "yearlyrainin"
SENSOR_TYPES = {
    TYPE_24HOURRAININ: ("24 Hr Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_BAROMABSIN: ("Abs Pressure", PRESSURE_INHG, SENSOR, DEVICE_CLASS_PRESSURE),
    TYPE_BAROMRELIN: ("Rel Pressure", PRESSURE_INHG, SENSOR, DEVICE_CLASS_PRESSURE),
    TYPE_BATT10: ("Battery 10", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT1: ("Battery 1", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT2: ("Battery 2", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT3: ("Battery 3", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT4: ("Battery 4", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT5: ("Battery 5", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT6: ("Battery 6", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT7: ("Battery 7", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT8: ("Battery 8", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT9: ("Battery 9", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATTOUT: ("Battery", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_BATT_CO2: ("CO2 Battery", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_CO2: ("co2", CONCENTRATION_PARTS_PER_MILLION, SENSOR, DEVICE_CLASS_CO2),
    TYPE_DAILYRAININ: ("Daily Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_DEWPOINT: ("Dew Point", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_EVENTRAININ: ("Event Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_FEELSLIKE: ("Feels Like", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_HOURLYRAININ: (
        "Hourly Rain Rate",
        PRECIPITATION_INCHES_PER_HOUR,
        SENSOR,
        None,
    ),
    TYPE_HUMIDITY10: ("Humidity 10", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY1: ("Humidity 1", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY2: ("Humidity 2", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY3: ("Humidity 3", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY4: ("Humidity 4", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY5: ("Humidity 5", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY6: ("Humidity 6", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY7: ("Humidity 7", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY8: ("Humidity 8", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY9: ("Humidity 9", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITY: ("Humidity", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_HUMIDITYIN: ("Humidity In", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_LASTRAIN: ("Last Rain", None, SENSOR, DEVICE_CLASS_TIMESTAMP),
    TYPE_MAXDAILYGUST: ("Max Gust", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_MONTHLYRAININ: ("Monthly Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_PM25_24H: (
        "PM25 24h Avg",
        CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
        SENSOR,
        None,
    ),
    TYPE_PM25_BATT: ("PM25 Battery", None, BINARY_SENSOR, DEVICE_CLASS_BATTERY),
    TYPE_PM25_IN: (
        "PM25 Indoor",
        CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
        SENSOR,
        None,
    ),
    TYPE_PM25_IN_24H: (
        "PM25 Indoor 24h Avg",
        CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
        SENSOR,
        None,
    ),
    TYPE_PM25: ("PM25", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, SENSOR, None),
    TYPE_PM25IN_BATT: (
        "PM25 Indoor Battery",
        None,
        BINARY_SENSOR,
        DEVICE_CLASS_BATTERY,
    ),
    TYPE_RELAY10: ("Relay 10", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY1: ("Relay 1", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY2: ("Relay 2", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY3: ("Relay 3", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY4: ("Relay 4", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY5: ("Relay 5", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY6: ("Relay 6", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY7: ("Relay 7", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY8: ("Relay 8", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_RELAY9: ("Relay 9", None, BINARY_SENSOR, DEVICE_CLASS_CONNECTIVITY),
    TYPE_SOILHUM10: ("Soil Humidity 10", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM1: ("Soil Humidity 1", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM2: ("Soil Humidity 2", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM3: ("Soil Humidity 3", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM4: ("Soil Humidity 4", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM5: ("Soil Humidity 5", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM6: ("Soil Humidity 6", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM7: ("Soil Humidity 7", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM8: ("Soil Humidity 8", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILHUM9: ("Soil Humidity 9", PERCENTAGE, SENSOR, DEVICE_CLASS_HUMIDITY),
    TYPE_SOILTEMP10F: (
        "Soil Temp 10",
        TEMP_FAHRENHEIT,
        SENSOR,
        DEVICE_CLASS_TEMPERATURE,
    ),
    TYPE_SOILTEMP1F: ("Soil Temp 1", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP2F: ("Soil Temp 2", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP3F: ("Soil Temp 3", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP4F: ("Soil Temp 4", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP5F: ("Soil Temp 5", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP6F: ("Soil Temp 6", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP7F: ("Soil Temp 7", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP8F: ("Soil Temp 8", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOILTEMP9F: ("Soil Temp 9", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_SOLARRADIATION: (
        "Solar Rad",
        IRRADIATION_WATTS_PER_SQUARE_METER,
        SENSOR,
        None,
    ),
    TYPE_SOLARRADIATION_LX: (
        "Solar Rad (lx)",
        LIGHT_LUX,
        SENSOR,
        DEVICE_CLASS_ILLUMINANCE,
    ),
    TYPE_TEMP10F: ("Temp 10", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP1F: ("Temp 1", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP2F: ("Temp 2", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP3F: ("Temp 3", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP4F: ("Temp 4", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP5F: ("Temp 5", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP6F: ("Temp 6", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP7F: ("Temp 7", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP8F: ("Temp 8", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMP9F: ("Temp 9", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMPF: ("Temp", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TEMPINF: ("Inside Temp", TEMP_FAHRENHEIT, SENSOR, DEVICE_CLASS_TEMPERATURE),
    TYPE_TOTALRAININ: ("Lifetime Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_UV: ("uv", "Index", SENSOR, None),
    TYPE_WEEKLYRAININ: ("Weekly Rain", PRECIPITATION_INCHES, SENSOR, None),
    TYPE_WINDDIR: ("Wind Dir", DEGREE, SENSOR, None),
    TYPE_WINDDIR_AVG10M: ("Wind Dir Avg 10m", DEGREE, SENSOR, None),
    TYPE_WINDDIR_AVG2M: ("Wind Dir Avg 2m", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_WINDGUSTDIR: ("Gust Dir", DEGREE, SENSOR, None),
    TYPE_WINDGUSTMPH: ("Wind Gust", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_WINDSPDMPH_AVG10M: ("Wind Avg 10m", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_WINDSPDMPH_AVG2M: ("Wind Avg 2m", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_WINDSPEEDMPH: ("Wind Speed", SPEED_MILES_PER_HOUR, SENSOR, None),
    TYPE_YEARLYRAININ: ("Yearly Rain", PRECIPITATION_INCHES, SENSOR, None),
}

CONFIG_SCHEMA = cv.deprecated(DOMAIN)

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Set up the Ambient PWS as config entry."""
    hass.data.setdefault(DOMAIN, {DATA_CLIENT: {}})

    if not config_entry.unique_id:
        hass.config_entries.async_update_entry(
            config_entry, unique_id=config_entry.data[CONF_APP_KEY]
        )
    session = aiohttp_client.async_get_clientsession(hass)

    try:
        ambient = AmbientStation(
            hass,
            config_entry,
            Client(
                config_entry.data[CONF_API_KEY],
                config_entry.data[CONF_APP_KEY],
                session=session,
            ),
        )
        hass.loop.create_task(ambient.ws_connect())
        hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = ambient
    except WebsocketError as err:
        LOGGER.error("Config entry failed: %s", err)
        raise ConfigEntryNotReady from err

    async def _async_disconnect_websocket(_: Event) -> None:
        await ambient.client.websocket.disconnect()

    config_entry.async_on_unload(
        hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_STOP, _async_disconnect_websocket
        )
    )

    return True

async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Unload an Ambient PWS config entry."""
    ambient = hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id)
    hass.async_create_task(ambient.ws_disconnect())

    return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)

async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Migrate old entry."""
    version = config_entry.version

    LOGGER.debug("Migrating from version %s", version)

    # 1 -> 2: Unique ID format changed, so delete and re-import:
    if version == 1:
        dev_reg = await hass.helpers.device_registry.async_get_registry()
        dev_reg.async_clear_config_entry(config_entry)

        en_reg = await hass.helpers.entity_registry.async_get_registry()
        en_reg.async_clear_config_entry(config_entry)

        version = config_entry.version = 2
        hass.config_entries.async_update_entry(config_entry)
    LOGGER.info("Migration to version %s successful", version)

    return True

class AmbientStation:
    """Define a class to handle the Ambient websocket."""

    def __init__(
        self, hass: HomeAssistant, config_entry: ConfigEntry, client: Client
    ) -> None:
        """Initialize."""
        self._config_entry = config_entry
        self._entry_setup_complete = False
        self._hass = hass
        self._ws_reconnect_delay = DEFAULT_SOCKET_MIN_RETRY
        self.client = client
        self.stations: dict[str, dict] = {}

    async def _attempt_connect(self) -> None:
        """Attempt to connect to the socket (retrying later on fail)."""

        async def connect(timestamp: int | None = None) -> None:
            """Connect."""
            await self.client.websocket.connect()

        try:
            await connect()
        except WebsocketError as err:
            LOGGER.error("Error with the websocket connection: %s", err)
            self._ws_reconnect_delay = min(2 * self._ws_reconnect_delay, 480)
            async_call_later(self._hass, self._ws_reconnect_delay, connect)

    async def ws_connect(self) -> None:
        """Register handlers and connect to the websocket."""

        def on_connect() -> None:
            """Define a handler to fire when the websocket is connected."""
            LOGGER.info("Connected to websocket")

        def on_data(data: dict) -> None:
            """Define a handler to fire when the data is received."""
            mac_address = data["macAddress"]
            if data != self.stations[mac_address][ATTR_LAST_DATA]:
                LOGGER.debug("New data received: %s", data)
                self.stations[mac_address][ATTR_LAST_DATA] = data
                async_dispatcher_send(
                    self._hass, f"ambient_station_data_update_{mac_address}"
                )

        def on_disconnect() -> None:
            """Define a handler to fire when the websocket is disconnected."""
            LOGGER.info("Disconnected from websocket")

        def on_subscribed(data: dict) -> None:
            """Define a handler to fire when the subscription is set."""
            for station in data["devices"]:
                if station["macAddress"] in self.stations:
                    continue
                LOGGER.debug("New station subscription: %s", data)

                # Only create entities based on the data coming through the socket.
                # If the user is monitoring brightness (in W/m^2), make sure we also
                # add a calculated sensor for the same data measured in lx:
                monitored_conditions = [
                    k for k in station["lastData"] if k in SENSOR_TYPES
                ]
                if TYPE_SOLARRADIATION in monitored_conditions:
                    monitored_conditions.append(TYPE_SOLARRADIATION_LX)
                self.stations[station["macAddress"]] = {
                    ATTR_LAST_DATA: station["lastData"],
                    ATTR_LOCATION: station.get("info", {}).get("location"),
                    ATTR_MONITORED_CONDITIONS: monitored_conditions,
                    ATTR_NAME: station.get("info", {}).get(
                        "name", station["macAddress"]
                    ),
                }
            # If the websocket disconnects and reconnects, the on_subscribed
            # handler will get called again; in that case, we don't want to
            # attempt forward setup of the config entry (because it will have
            # already been done):
            if not self._entry_setup_complete:
                self._hass.config_entries.async_setup_platforms(
                    self._config_entry, PLATFORMS
                )
                self._entry_setup_complete = True
            self._ws_reconnect_delay = DEFAULT_SOCKET_MIN_RETRY

        self.client.websocket.on_connect(on_connect)
        self.client.websocket.on_data(on_data)
        self.client.websocket.on_disconnect(on_disconnect)
        self.client.websocket.on_subscribed(on_subscribed)

        await self._attempt_connect()

    async def ws_disconnect(self) -> None:
        """Disconnect from the websocket."""
        await self.client.websocket.disconnect()

class AmbientWeatherEntity(Entity):
    """Define a base Ambient PWS entity."""

    def __init__(
        self,
        ambient: AmbientStation,
        mac_address: str,
        station_name: str,
        sensor_type: str,
        sensor_name: str,
        device_class: str | None,
    ) -> None:
        """Initialize the sensor."""
        self._ambient = ambient
        self._attr_device_class = device_class
        self._attr_device_info = {
            "identifiers": {(DOMAIN, mac_address)},
            "name": station_name,
            "manufacturer": "Ambient Weather",
        }
        self._attr_name = f"{station_name}_{sensor_name}"
        self._attr_should_poll = False
        self._attr_unique_id = f"{mac_address}_{sensor_type}"
        self._mac_address = mac_address
        self._sensor_type = sensor_type

    async def async_added_to_hass(self) -> None:
        """Register callbacks."""

        @callback
        def update() -> None:
            """Update the state."""
            if self._sensor_type == TYPE_SOLARRADIATION_LX:
                self._attr_available = (
                    self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get(
                        TYPE_SOLARRADIATION
                    )
                    is not None
                )
            else:
                self._attr_available = (
                    self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get(
                        self._sensor_type
                    )
                    is not None
                )

            self.update_from_latest_data()
            self.async_write_ha_state()

        self.async_on_remove(
            async_dispatcher_connect(
                self.hass, f"ambient_station_data_update_{self._mac_address}", update
            )
        )

        self.update_from_latest_data()

    @callback
    def update_from_latest_data(self) -> None:
        """Update the entity from the latest data."""
        raise NotImplementedError


text:
package org.gmock.sample;

public interface Collaborator {
    void documentAdded(String title);

    void documentChanged(String title);

    void documentRemoved(String title);

    byte voteForRemoval(String title);

    byte voteForRemovals(String[] title);
}

redpajama_set_name: RedPajamaGithub


text:
module DeviseTwoFactorable::Hooks
  module Sessions
    extend ActiveSupport::Concern
    include DeviseTwoFactorable::Controllers::UrlHelpers
    #
    # replaces Devise::SessionsController#create
    #
    def create
      resource = warden.authenticate!(auth_options)

      devise_stored_location = stored_location_for(resource) # Grab the current stored location before it gets lost by warden.logout

      otp_refresh_credentials_for(resource)

      if otp_challenge_required_on?(resource)
        challenge = resource.generate_otp_challenge!
        warden.logout
        store_location_for(resource, devise_stored_location) # restore the stored location
        respond_with resource, location: credential_path_for(resource, challenge: challenge)
      elsif otp_mandatory_on?(resource) # if mandatory, log in user but send him to the must activate otp
        set_flash_message(:notice, :signed_in_but_otp) if is_navigational_format?
        sign_in(resource_name, resource)
        respond_with resource, location: token_path_for(resource)
      else
        super
      end
    end

    private

    #
    # resource should be challenged for otp
    #
    def otp_challenge_required_on?(resource)
      return false unless resource.respond_to?(:otp_enabled) && resource.respond_to?(:otp_auth_secret)
      resource.otp_enabled && !is_otp_trusted_device_for?(resource)
    end

    #
    # the resource -should- have otp turned on, but it isn't
    #
    def otp_mandatory_on?(resource)
      return true if resource.class.otp_mandatory
      return false unless resource.respond_to?(:otp_mandatory)

      resource.otp_mandatory && !resource.otp_enabled
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Caps.Data.Model
{
    public class Tag
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [MaxLength(50)]
        public String Name { get; set; }

        [InverseProperty("Tag")]
        public ICollection<DbFileTag> Files { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Glass.Mapper.Configuration;
using NSubstitute;
using NUnit.Framework;
using Glass.Mapper.Configuration.Attributes;

namespace Glass.Mapper.Tests.Configuration.Attributes
{
    [TestFixture]
    public class NodeAttributeFixture
    {
        [Test]
        public void Does_PNodeAttribute_Extend_AbstractPropertyAttribute()
        {
            Assert.IsTrue(typeof(AbstractPropertyAttribute).IsAssignableFrom(typeof(NodeAttribute)));
        }

        [Test]
        [TestCase("Path")]
        [TestCase("Id")]
        public void Does_NodeAttribute_Have_Properties(string propertyName)
        {
            var properties = typeof(NodeAttribute).GetProperties();
            Assert.IsTrue(properties.Any(x => x.Name == propertyName));
        }

        #region Method - Configure

        [Test]
        public void Configure_DefaultValues_ConfigContainsDefaults()
        {
            //Assign
            var attr = new StubNodeAttribute();
            var config = new NodeConfiguration();
			var propertyInfo = typeof(StubItem).GetProperty("X");

            //Act
            attr.Configure(propertyInfo, config);

            //Assert
            Assert.AreEqual(propertyInfo, config.PropertyInfo);
            Assert.IsNull(config.Path);
            Assert.IsNull(config.Id);
        }

        [Test]
        public void Configure_PathHasValue_ConfigHasPathValue()
        {
            //Assign
            var attr = new StubNodeAttribute();
            var config = new NodeConfiguration();
			var propertyInfo = typeof(StubItem).GetProperty("X");
            var path = "some path";

            attr.Path = path;

            //Act
            attr.Configure(propertyInfo, config);

            //Assert
            Assert.AreEqual(propertyInfo, config.PropertyInfo);
            Assert.AreEqual(path, config.Path);
            Assert.IsNull(config.Id);
        }

        [Test]
        public void Configure_IdHasValue_ConfigHasIdValue()
        {
            //Assign
            var attr = new StubNodeAttribute();
            var config = new NodeConfiguration();
			var propertyInfo = typeof(StubItem).GetProperty("X");
            var id = "some id";

            attr.Id = id;

            //Act
            attr.Configure(propertyInfo, config);

            //Assert
            Assert.AreEqual(propertyInfo, config.PropertyInfo);
            Assert.AreEqual(id, config.Id);
            Assert.IsNull(config.Path);
        }

        #endregion

        #region Stubs

        private class StubNodeAttribute : NodeAttribute
        {
            public StubNodeAttribute()
            {
            }

            public override Mapper.Configuration.AbstractPropertyConfiguration Configure(System.Reflection.PropertyInfo propertyInfo)
            {
                throw new NotImplementedException();
            }
        }

		public class StubItem
		{
			public object X { get; set; }
		}

        #endregion
    }
}


text:
package com.hazelcast.internal.serialization.impl;

public final class SerializationConstants {

    // WARNING: DON'T CHANGE VALUES!
    // WARNING: DON'T ADD ANY NEW CONSTANT SERIALIZER!

    public static final int CONSTANT_TYPE_NULL = 0;

    public static final int CONSTANT_TYPE_PORTABLE = -1;

    public static final int CONSTANT_TYPE_DATA_SERIALIZABLE = -2;

    public static final int CONSTANT_TYPE_BYTE = -3;

    public static final int CONSTANT_TYPE_BOOLEAN = -4;

    public static final int CONSTANT_TYPE_CHAR = -5;

    public static final int CONSTANT_TYPE_SHORT = -6;

    public static final int CONSTANT_TYPE_INTEGER = -7;

    public static final int CONSTANT_TYPE_LONG = -8;

    public static final int CONSTANT_TYPE_FLOAT = -9;

    public static final int CONSTANT_TYPE_DOUBLE = -10;

    public static final int CONSTANT_TYPE_STRING = -11;

    public static final int CONSTANT_TYPE_BYTE_ARRAY = -12;

    public static final int CONSTANT_TYPE_BOOLEAN_ARRAY = -13;

    public static final int CONSTANT_TYPE_CHAR_ARRAY = -14;

    public static final int CONSTANT_TYPE_SHORT_ARRAY = -15;

    public static final int CONSTANT_TYPE_INTEGER_ARRAY = -16;

    public static final int CONSTANT_TYPE_LONG_ARRAY = -17;

    public static final int CONSTANT_TYPE_FLOAT_ARRAY = -18;

    public static final int CONSTANT_TYPE_DOUBLE_ARRAY = -19;

    public static final int CONSTANT_TYPE_STRING_ARRAY = -20;

    public static final int CONSTANT_TYPE_UUID = -21;

    public static final int CONSTANT_TYPE_SIMPLE_ENTRY = -22;

    public static final int CONSTANT_TYPE_SIMPLE_IMMUTABLE_ENTRY = -23;

    // ------------------------------------------------------------
    // DEFAULT SERIALIZERS

    public static final int JAVA_DEFAULT_TYPE_CLASS = -24;

    public static final int JAVA_DEFAULT_TYPE_DATE = -25;

    public static final int JAVA_DEFAULT_TYPE_BIG_INTEGER = -26;

    public static final int JAVA_DEFAULT_TYPE_BIG_DECIMAL = -27;

    public static final int JAVA_DEFAULT_TYPE_ARRAY = -28;

    public static final int JAVA_DEFAULT_TYPE_ARRAY_LIST = -29;

    public static final int JAVA_DEFAULT_TYPE_LINKED_LIST = -30;

    public static final int JAVA_DEFAULT_TYPE_COPY_ON_WRITE_ARRAY_LIST = -31;

    public static final int JAVA_DEFAULT_TYPE_HASH_MAP = -32;

    public static final int JAVA_DEFAULT_TYPE_CONCURRENT_SKIP_LIST_MAP = -33;

    public static final int JAVA_DEFAULT_TYPE_CONCURRENT_HASH_MAP = -34;

    public static final int JAVA_DEFAULT_TYPE_LINKED_HASH_MAP = -35;

    public static final int JAVA_DEFAULT_TYPE_TREE_MAP = -36;

    public static final int JAVA_DEFAULT_TYPE_HASH_SET = -37;

    public static final int JAVA_DEFAULT_TYPE_TREE_SET = -38;

    public static final int JAVA_DEFAULT_TYPE_LINKED_HASH_SET = -39;

    public static final int JAVA_DEFAULT_TYPE_COPY_ON_WRITE_ARRAY_SET = -40;

    public static final int JAVA_DEFAULT_TYPE_CONCURRENT_SKIP_LIST_SET = -41;

    public static final int JAVA_DEFAULT_TYPE_ARRAY_DEQUE = -42;

    public static final int JAVA_DEFAULT_TYPE_LINKED_BLOCKING_QUEUE = -43;

    public static final int JAVA_DEFAULT_TYPE_ARRAY_BLOCKING_QUEUE = -44;

    public static final int JAVA_DEFAULT_TYPE_PRIORITY_BLOCKING_QUEUE = -45;

    public static final int JAVA_DEFAULT_TYPE_DELAY_QUEUE = -46;

    public static final int JAVA_DEFAULT_TYPE_SYNCHRONOUS_QUEUE = -47;

    public static final int JAVA_DEFAULT_TYPE_LINKED_TRANSFER_QUEUE = -48;

    public static final int JAVA_DEFAULT_TYPE_PRIORITY_QUEUE = -49;

    public static final int JAVA_DEFAULT_TYPE_OPTIONAL = -50;

    // NUMBER OF CONSTANT SERIALIZERS...
    public static final int CONSTANT_SERIALIZERS_LENGTH = 51;

    // ------------------------------------------------------------
    // JAVA SERIALIZATION

    public static final int JAVA_DEFAULT_TYPE_SERIALIZABLE = -100;
    public static final int JAVA_DEFAULT_TYPE_EXTERNALIZABLE = -101;

    // ------------------------------------------------------------
    // LANGUAGE SPECIFIC SERIALIZERS
    // USED BY CLIENTS (Not deserialized by server)

    public static final int CSHARP_CLR_SERIALIZATION_TYPE = -110;
    public static final int PYTHON_PICKLE_SERIALIZATION_TYPE = -120;
    public static final int JAVASCRIPT_JSON_SERIALIZATION_TYPE = -130;
    public static final int GO_GOB_SERIALIZATION_TYPE = -140;

    // ------------------------------------------------------------
    // HIBERNATE SERIALIZERS

    public static final int HIBERNATE3_TYPE_HIBERNATE_CACHE_KEY = -200;
    public static final int HIBERNATE3_TYPE_HIBERNATE_CACHE_ENTRY = -201;

    public static final int HIBERNATE4_TYPE_HIBERNATE_CACHE_KEY = -202;
    public static final int HIBERNATE4_TYPE_HIBERNATE_CACHE_ENTRY = -203;

    public static final int HIBERNATE5_TYPE_HIBERNATE_CACHE_KEY = -204;
    public static final int HIBERNATE5_TYPE_HIBERNATE_CACHE_ENTRY = -205;
    public static final int HIBERNATE5_TYPE_HIBERNATE_NATURAL_ID_KEY = -206;

    //--------------------------------------------------------------
    // RESERVED FOR JET -300 to -400

    public static final int JET_SERIALIZER_FIRST = -300;
    public static final int JET_SERIALIZER_LAST = -399;

    private SerializationConstants() {
    }
}


text: Tests object revelation in the UI.


text:
#ifndef __GATT_DB_H
#define __GATT_DB_H

#if __cplusplus
extern "C" {
#endif

#include "bg_gattdb_def.h"

extern const struct bg_gattdb_def bg_gattdb_data;

#define gattdb_service_changed_char 3
#define gattdb_database_hash 6
#define gattdb_client_support_features 8
#define gattdb_device_name 11
#define gattdb_ota_control 23
#define gattdb_WoBLEChar_Rx 26
#define gattdb_WoBLEChar_Tx 28

#if __cplusplus
}
#endif

#endif // __GATT_DB_H


text:
include_recipe 'sc-mongodb::mongodb_org_repo' if node['mongodb']['install_method'] == 'mongodb-org'

# TODO: still need all of the tools?
# yum_package[autoconf, bison, flex, gcc, gcc-c++, gettext, kernel-devel, make, m4, ncurses-devel, patch]
build_essential 'build-tools'

config_type = node['mongodb']['is_mongos'] ? 'mongos' : 'mongod'

config = node['mongodb']['config'][config_type]
dbconfig_file = node['mongodb']['dbconfig_file'][config_type]
sysconfig_file = node['mongodb']['sysconfig_file'][config_type]

# prevent-install defaults, but don't overwrite
file "#{sysconfig_file} install" do
  path sysconfig_file
  content 'ENABLE_MONGODB=no'
  group node['mongodb']['root_group']
  owner 'root'
  mode '0644'
  action :create_if_missing
end

# just-in-case config file drop
template "#{dbconfig_file} install" do
  path dbconfig_file
  cookbook node['mongodb']['template_cookbook']
  source node['mongodb']['dbconfig_file']['template']
  group node['mongodb']['root_group']
  owner 'root'
  mode '0644'
  variables(
    config: config
  )
  helpers MongoDBConfigHelpers
  action :create_if_missing
end

# this package required by init script
package 'netcat' do
  only_if { platform_family?('debian') }
end

# and we install our own init file
if platform?('ubuntu') && node['platform_version'].to_f < 15.04
  init_file = File.join(node['mongodb']['init_dir'], "#{node['mongodb']['default_init_name']}.conf")
  mode = '0644'
else
  init_file = File.join(node['mongodb']['init_dir'], node['mongodb']['default_init_name'])
  mode = '0755'
end

template "#{init_file} install" do
  path init_file
  cookbook node['mongodb']['template_cookbook']
  source node['mongodb']['init_script_template']
  group node['mongodb']['root_group']
  owner 'root'
  mode mode
  variables(
    provides: 'mongod',
    dbconfig_file: dbconfig_file,
    sysconfig_file: sysconfig_file,
    ulimit: node['mongodb']['ulimit'],
    bind_ip: config['net']['bindIp'],
    port: config['net']['port']
  )
  action :create_if_missing
end

service 'mongod' do
  supports start: true, stop: true, restart: true, status: true
  action :enable
end

# Adjust the version number for RHEL style if needed
package_version = case node['platform_family']
                  when 'rhel'
                    if platform?('amazon')
                      "#{node['mongodb']['package_version']}-1.amzn1"
                    else
                      "#{node['mongodb']['package_version']}-1.el#{node['platform_version'].to_i}"
                    end
                  when 'fedora'
                    "#{node['mongodb']['package_version']}-1.el7"
                  else
                    node['mongodb']['package_version']
                  end

# Install
package node['mongodb']['package_name'] do
  options node['mongodb']['packager_options']
  action :install
  version package_version
  not_if { node['mongodb']['install_method'] == 'none' }
end

# Change needed so that updates work properly on debian based systems
if platform_family?('debian')
  deb_pkg_suffixes = %w(
    server
    shell
    tools
    mongos
  )
  deb_pkg_suffixes.each do |suffix|
    package "#{node['mongodb']['package_name']}-#{suffix}" do
      options node['mongodb']['packager_options']
      action :install
      version package_version
      not_if { node['mongodb']['install_method'] == 'none' }
    end
  end
end

# Create keyFile if specified
key_file_content = node['mongodb']['key_file_content']

if key_file_content
  file config['security']['keyFile'] do
    owner node['mongodb']['user']
    group node['mongodb']['group']
    mode  '0600'
    backup false
    content key_file_content
  end
end

node.default['mongodb']['config'][config_type]['security']['keyFile'] = nil if key_file_content.nil?

# create directory for pidfile
directory File.dirname(node['mongodb']['config']['mongod']['processManagement']['pidFilePath']) do
  owner node['mongodb']['user']
  group node['mongodb']['group']
  mode  '0755'
end


text:
package fibex.protocols.flexray;

/**
 * This interface defines all additional functionality of a FlexRay FIBEX controller over a standard FIBEX controller
 * @author TUM CREATE - RP3 - Philipp Mundhenk
 *
 */
public interface FlexRayController
{

}


text:
package io.amaze.bench.leader;

import com.google.common.util.concurrent.SettableFuture;
import io.amaze.bench.api.ActorKey;
import io.amaze.bench.cluster.actor.ActorConfig;
import io.amaze.bench.cluster.actor.ActorDeployInfo;
import io.amaze.bench.cluster.actor.ActorInputMessage;
import io.amaze.bench.cluster.actor.ActorSender;
import io.amaze.bench.cluster.agent.AgentKey;
import io.amaze.bench.cluster.registry.ActorRegistry;
import io.amaze.bench.cluster.registry.ActorRegistryListener;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.concurrent.Future;

import static java.util.Objects.requireNonNull;

/**
 * Created on 9/12/16.
 */
public final class Actors {

    private final ActorSender actorSender;
    private final ResourceManager resourceManager;
    private final ActorRegistry actorRegistry;

    public Actors(@NotNull final ActorSender actorSender,
                  @NotNull final ResourceManager resourceManager,
                  @NotNull final ActorRegistry actorRegistry) {

        this.actorSender = requireNonNull(actorSender);
        this.resourceManager = requireNonNull(resourceManager);
        this.actorRegistry = requireNonNull(actorRegistry);
    }

    public ActorHandle create(@NotNull final ActorConfig actorConfig) {
        requireNonNull(actorConfig);
        HandleRegistryListener handleRegistryListener = new HandleRegistryListener(actorSender, actorConfig);
        actorRegistry.addListener(handleRegistryListener);
        return handleRegistryListener.createActor();
    }

    public final class ActorHandle {
        private final SettableFuture<ActorConfig> actorCreated = SettableFuture.create();
        private final SettableFuture<ActorDeployInfo> actorInitialized = SettableFuture.create();
        private final SettableFuture<Throwable> actorFailed = SettableFuture.create();
        private final SettableFuture<Void> actorClosed = SettableFuture.create();

        private final ActorSender actorSender;
        private final ActorConfig config;

        ActorHandle(final ActorSender actorSender, final ActorConfig config) {
            this.actorSender = actorSender;
            this.config = config;
        }

        public void dumpMetrics() {
            actorSender.send(config.getKey(), ActorInputMessage.dumpMetrics());
        }

        public void bootstrap() {
            actorSender.send(config.getKey(), ActorInputMessage.bootstrap());
        }

        public void send(final String from, final Serializable message) {
            actorSender.send(config.getKey(), ActorInputMessage.message(from, message));
        }

        public Future<Void> close() {
            actorSender.send(config.getKey(), ActorInputMessage.close());
            return actorClosed;
        }

        public Future<ActorConfig> actorCreation() {
            return actorCreated;
        }

        public Future<ActorDeployInfo> actorInitialization() {
            return actorInitialized;
        }

        public Future<Throwable> actorFailure() {
            return actorFailed;
        }

        public Future<Void> actorTermination() {
            return actorClosed;
        }
    }

    private final class HandleRegistryListener implements ActorRegistryListener {
        private final ActorConfig config;
        private final ActorHandle handle;

        HandleRegistryListener(final ActorSender actorSender, final ActorConfig config) {
            this.config = config;
            this.handle = new ActorHandle(actorSender, config);
        }

        @Override
        public void onActorCreated(@NotNull final ActorKey key, @NotNull final AgentKey agent) {
            if (key.equals(config.getKey())) {
                handle.actorCreated.set(config);
            }
        }

        @Override
        public void onActorInitialized(@NotNull final ActorKey key, @NotNull final ActorDeployInfo deployInfo) {
            if (key.equals(config.getKey())) {
                handle.actorInitialized.set(deployInfo);
            }
        }

        @Override
        public void onActorFailed(@NotNull final ActorKey key, @NotNull final Throwable throwable) {
            if (key.equals(config.getKey())) {
                handle.actorFailed.set(throwable);

                handle.actorCreated.setException(throwable);
                handle.actorInitialized.setException(throwable);
                handle.actorClosed.setException(throwable);

                actorRegistry.removeListener(this);
            }
        }

        @Override
        public void onActorClosed(@NotNull final ActorKey key) {
            if (key.equals(config.getKey())) {
                handle.actorClosed.set(null);

                actorRegistry.removeListener(this);
            }
        }

        ActorHandle createActor() {
            resourceManager.createActor(config);
            return handle;
        }
    }
}


text:
#include "../thread/future.h"

namespace network {
namespace net {
/*
    Look for Google, if there is no reply then we have no internet,
    or the DNS isn't working or something. (or, of course Google is down...)
*/
bool is_connected() {
    int failed = system("ping -c 1 www.google.com");
    if(failed) {
        return false;
    }

    return true;
}

std::shared_future<bool> is_connected_async() {
    return thread::submit_task(&is_connected);
}

}
}


text:
using Ko.Navigation.ChromiumFx.Tests.Infra;
using Tests.Universal.NavigationTests;
using Xunit;
using Xunit.Abstractions;

namespace Ko.Navigation.ChromiumFx.Tests
{
    [Collection("Cfx Window Integrated")]
    public class HTMLViewControl_Ko_Cfx_Tests : HTMLViewControlTests
    {
        public HTMLViewControl_Ko_Cfx_Tests(CfxKoContext context, ITestOutputHelper testOutputHelper)
            : base(context, testOutputHelper)
        {
        }
    }
}


text:
title: Le L@bx à bordeaux au Forum economie collaborative
author: Michel-S.
layout: post
date: 2013-07-05
categories:
  - Non classé
---
Le L@bx était bien présent à la table ronde du Forum Economie Collaborative de Bordeaux :

JEUDI 04/07 et VENDREDI 05/07

Et notamment le vendredi matin pour la table ronde : 10h45 – 11h45 : Production contributive : la révolution industrielle des « Makers »

« Si les dix dernières années ont vu émerger de nouveaux modèles d'innovation et de collaboration sur le web, les dix prochaines verront les _Makers_ transposer ces enseignements à l'économie réelle", prédit Chris Anderson dans son ouvrage éponyme. L'économie de la contribution annoncée par Bernard Stiegler est-elle sur le point de se généraliser, du logiciel open source à la fabrication? Au-delà des prophéties, ce panel explorera les contours d'un nouveau paysage post-industriel : entre culture de « Do-It-Yourself », nouveaux lieux de création et de partage (Fablabs, hackerspaces, …), fabrication numérique et pratiques open source appliquées aux objets physiques. »

Avec OuiShare, INRIA, Le Fablab Toulouse et l'ENSCI …

http://www.bordeaux-economie-collaborative.org/


text:
from pymoku import Moku, MokuException, NoDataException
from pymoku.instruments import *
import time, logging, traceback

logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)

# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscilloscope()
m.attach_instrument(i)

try:
	i.set_samplerate(10)
	i.set_xmode(OSC_ROLL)
	i.commit()
	time.sleep(1)

	i.datalogger_stop()

	i.datalogger_start(start=0, duration=100, use_sd=False, ch1=True, ch2=False, filetype='net')

	while True:
		ch, idx, d = i.datalogger_get_samples(timeout=5)

		print("Received samples %d to %d from channel %d" % (idx, idx + len(d) - 1, ch))
except NoDataException as e:
	# This will be raised if we try and get samples but the session has finished.
	print(e)
except Exception as e:
	print(traceback.format_exc())
finally:
	i.datalogger_stop()
	m.close()


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/influxdata/telegraf/agent"
	"github.com/influxdata/telegraf/internal/config"

	_ "github.com/influxdata/telegraf/plugins/inputs/all"
	_ "github.com/influxdata/telegraf/plugins/outputs/all"
)

var fDebug = flag.Bool("debug", false,
	"show metrics as they're generated to stdout")
var fQuiet = flag.Bool("quiet", false,
	"run in quiet mode")
var fTest = flag.Bool("test", false, "gather metrics, print them out, and exit")
var fConfig = flag.String("config", "", "configuration file to load")
var fConfigDirectory = flag.String("config-directory", "",
	"directory containing additional *.conf files")
var fVersion = flag.Bool("version", false, "display the version")
var fSampleConfig = flag.Bool("sample-config", false,
	"print out full sample configuration")
var fPidfile = flag.String("pidfile", "", "file to write our pid to")
var fInputFilters = flag.String("input-filter", "",
	"filter the inputs to enable, separator is :")
var fOutputFilters = flag.String("output-filter", "",
	"filter the outputs to enable, separator is :")
var fUsage = flag.String("usage", "",
	"print usage for a plugin, ie, 'telegraf -usage mysql'")

var fInputFiltersLegacy = flag.String("filter", "",
	"filter the inputs to enable, separator is :")
var fOutputFiltersLegacy = flag.String("outputfilter", "",
	"filter the outputs to enable, separator is :")
var fConfigDirectoryLegacy = flag.String("configdirectory", "",
	"directory containing additional *.conf files")

// Telegraf version
//	-ldflags "-X main.Version=`git describe --always --tags`"
var Version string

const usage = `Telegraf, The plugin-driven server agent for collecting and reporting metrics.

Usage:

  telegraf <flags>

The flags are:

  -config <file>     configuration file to load
  -test              gather metrics once, print them to stdout, and exit
  -sample-config     print out full sample configuration to stdout
  -config-directory  directory containing additional *.conf files
  -input-filter      filter the input plugins to enable, separator is :
  -output-filter     filter the output plugins to enable, separator is :
  -usage             print usage for a plugin, ie, 'telegraf -usage mysql'
  -debug             print metrics as they're generated to stdout
  -quiet             run in quiet mode
  -version           print the version to stdout

Examples:

  # generate a telegraf config file:
  telegraf -sample-config > telegraf.conf

  # generate config with only cpu input & influxdb output plugins defined
  telegraf -sample-config -input-filter cpu -output-filter influxdb

  # run a single telegraf collection, outputing metrics to stdout
  telegraf -config telegraf.conf -test

  # run telegraf with all plugins defined in config file
  telegraf -config telegraf.conf

  # run telegraf, enabling the cpu & memory input, and influxdb output plugins
  telegraf -config telegraf.conf -input-filter cpu:mem -output-filter influxdb
`

func main() {
	reload := make(chan bool, 1)
	reload <- true
	for <-reload {
		reload <- false
		flag.Usage = func() { usageExit(0) }
		flag.Parse()

		if flag.NFlag() == 0 {
			usageExit(0)
		}

		var inputFilters []string
		if *fInputFiltersLegacy != "" {
			inputFilter := strings.TrimSpace(*fInputFiltersLegacy)
			inputFilters = strings.Split(":"+inputFilter+":", ":")
		}
		if *fInputFilters != "" {
			inputFilter := strings.TrimSpace(*fInputFilters)
			inputFilters = strings.Split(":"+inputFilter+":", ":")
		}

		var outputFilters []string
		if *fOutputFiltersLegacy != "" {
			outputFilter := strings.TrimSpace(*fOutputFiltersLegacy)
			outputFilters = strings.Split(":"+outputFilter+":", ":")
		}
		if *fOutputFilters != "" {
			outputFilter := strings.TrimSpace(*fOutputFilters)
			outputFilters = strings.Split(":"+outputFilter+":", ":")
		}

		if *fVersion {
			v := fmt.Sprintf("Telegraf - Version %s", Version)
			fmt.Println(v)
			return
		}

		if *fSampleConfig {
			config.PrintSampleConfig(inputFilters, outputFilters)
			return
		}

		if *fUsage != "" {
			if err := config.PrintInputConfig(*fUsage); err != nil {
				if err2 := config.PrintOutputConfig(*fUsage); err2 != nil {
					log.Fatalf("%s and %s", err, err2)
				}
			}
			return
		}

		var (
			c   *config.Config
			err error
		)

		if *fConfig != "" {
			c = config.NewConfig()
			c.OutputFilters = outputFilters
			c.InputFilters = inputFilters
			err = c.LoadConfig(*fConfig)
			if err != nil {
				log.Fatal(err)
			}
		} else {
			fmt.Println("You must specify a config file. See telegraf --help")
			os.Exit(1)
		}

		if *fConfigDirectoryLegacy != "" {
			err = c.LoadDirectory(*fConfigDirectoryLegacy)
			if err != nil {
				log.Fatal(err)
			}
		}

		if *fConfigDirectory != "" {
			err = c.LoadDirectory(*fConfigDirectory)
			if err != nil {
				log.Fatal(err)
			}
		}
		if len(c.Outputs) == 0 {
			log.Fatalf("Error: no outputs found, did you provide a valid config file?")
		}
		if len(c.Inputs) == 0 {
			log.Fatalf("Error: no inputs found, did you provide a valid config file?")
		}

		ag, err := agent.NewAgent(c)
		if err != nil {
			log.Fatal(err)
		}

		if *fDebug {
			ag.Config.Agent.Debug = true
		}

		if *fQuiet {
			ag.Config.Agent.Quiet = true
		}

		if *fTest {
			err = ag.Test()
			if err != nil {
				log.Fatal(err)
			}
			return
		}

		err = ag.Connect()
		if err != nil {
			log.Fatal(err)
		}

		shutdown := make(chan struct{})
		signals := make(chan os.Signal)
		signal.Notify(signals, os.Interrupt, syscall.SIGHUP)
		go func() {
			sig := <-signals
			if sig == os.Interrupt {
				close(shutdown)
			}
			if sig == syscall.SIGHUP {
				log.Printf("Reloading Telegraf config\n")
				<-reload
				reload <- true
				close(shutdown)
			}
		}()

		log.Printf("Starting Telegraf (version %s)\n", Version)
		log.Printf("Loaded outputs: %s", strings.Join(c.OutputNames(), " "))
		log.Printf("Loaded inputs: %s", strings.Join(c.InputNames(), " "))
		log.Printf("Tags enabled: %s", c.ListTags())

		if *fPidfile != "" {
			f, err := os.Create(*fPidfile)
			if err != nil {
				log.Fatalf("Unable to create pidfile: %s", err)
			}

			fmt.Fprintf(f, "%d\n", os.Getpid())

			f.Close()
		}

		ag.Run(shutdown)
	}
}

func usageExit(rc int) {
	fmt.Println(usage)
	os.Exit(rc)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace DoorsDemo.GumRuntimes.DefaultForms
{
    public partial class SliderRuntime
    {
        partial void CustomInitialize ()
        {
        }
    }
}


text:
package org.apache.camel.impl;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

/**
 * @version
 */
public class DefaultHeadersMapFactoryTest extends Assert {

    @Test
    public void testLookupCaseAgnostic() {
        Map<String, Object> map = new DefaultHeadersMapFactory().newMap();
        assertNull(map.get("foo"));

        map.put("foo", "cheese");

        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));
        assertEquals("cheese", map.get("FOO"));
    }

    @Test
    public void testConstructFromOther() {
        Map<String, Object> other = new DefaultHeadersMapFactory().newMap();
        other.put("Foo", "cheese");
        other.put("bar", 123);

        Map<String, Object> map = new DefaultHeadersMapFactory().newMap(other);

        assertEquals("cheese", map.get("FOO"));
        assertEquals("cheese", map.get("foo"));
        assertEquals("cheese", map.get("Foo"));

        assertEquals(123, map.get("BAR"));
        assertEquals(123, map.get("bar"));
        assertEquals(123, map.get("BaR"));
    }

    @Test
    public void testIsInstance() {
        Map<String, Object> map = new DefaultHeadersMapFactory().newMap();

        Map<String, Object> other = new DefaultHeadersMapFactory().newMap(map);
        other.put("Foo", "cheese");
        other.put("bar", 123);

        assertTrue(new DefaultHeadersMapFactory().isInstanceOf(map));
        assertTrue(new DefaultHeadersMapFactory().isInstanceOf(other));
        assertFalse(new DefaultHeadersMapFactory().isInstanceOf(new HashMap<>()));
    }

}


text:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/card_horizontal_margin"
    android:drawSelectorOnTop="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:layout_marginLeft="@dimen/activity_vertical_margin"
    android:layout_marginRight="@dimen/activity_vertical_margin"
    card_view:cardCornerRadius="2dp"
    card_view:cardElevation="3dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/storyTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
            android:textStyle="bold"
            android:layout_margin="10dp"
            android:layout_marginBottom="5dp"/>

        <TextView
            android:id="@+id/storyContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/storyTitle"
            android:layout_toLeftOf="@+id/storyDelete"
            android:layout_alignParentLeft="true"
            android:textAppearance="@android:style/TextAppearance.DeviceDefault.Small"
            android:textStyle="italic"
            android:layout_marginLeft="10dp"
            android:paddingBottom="10dp"
            android:layout_marginRight="10dp"/>

        <ImageButton
            android:id="@+id/storyDelete"
            android:layout_width="34dp"
            android:layout_height="36dp"
            android:layout_alignParentRight="true"
            android:layout_marginTop="10dp"
            android:background="@drawable/delete_button"
            android:layout_marginRight="10dp" />

    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
/** @jsx m */

"use strict";
require("./DropdownSelect.scss");

var _ = require("underscore");
var Dropdown = require("./Dropdown.js");

var DropdownSelect = {};

DropdownSelect.controller = function(options) {
  this.options = options.options;
  this.value = options.value;
  this.onchange = options.onchange;

  this.dropdownController = new Dropdown.controller({className: "DropdownSelect"});

  var _this = this;
  _this.handleClick = function(value) {
    return function() {
      if (value !== _this.value()) {
        _this.onchange(value);
      }
      _this.dropdownController.toggle();
    };
  };
};

DropdownSelect.view = function(ctrl) {
  var selectedValue = _.isUndefined(ctrl.value()) ? _.first(ctrl.options).value : ctrl.value();
  var label = _.findWhere(ctrl.options, {value: selectedValue}).content;

  var list = _.map(ctrl.options, function(option) {
    return
{option.content}
;
  });

  var content =
{list}
;

  return Dropdown.view(ctrl.dropdownController, content, label);
};

module.exports = DropdownSelect;