text:
"""Device for Zigbee Home Automation."""
from __future__ import annotations

import asyncio
from datetime import timedelta
from enum import Enum
import logging
import random
import time
from typing import Any

from zigpy import types
import zigpy.exceptions
from zigpy.profiles import PROFILES
import zigpy.quirks
from zigpy.zcl.clusters.general import Groups
import zigpy.zdo.types as zdo_types

from homeassistant.const import ATTR_COMMAND, ATTR_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
    async_dispatcher_connect,
    async_dispatcher_send,
)
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import HomeAssistantType

from . import channels, typing as zha_typing
from .const import (
    ATTR_ARGS,
    ATTR_ATTRIBUTE,
    ATTR_AVAILABLE,
    ATTR_CLUSTER_ID,
    ATTR_COMMAND_TYPE,
    ATTR_DEVICE_TYPE,
    ATTR_ENDPOINT_ID,
    ATTR_ENDPOINT_NAMES,
    ATTR_ENDPOINTS,
    ATTR_IEEE,
    ATTR_LAST_SEEN,
    ATTR_LQI,
    ATTR_MANUFACTURER,
    ATTR_MANUFACTURER_CODE,
    ATTR_MODEL,
    ATTR_NEIGHBORS,
    ATTR_NODE_DESCRIPTOR,
    ATTR_NWK,
    ATTR_POWER_SOURCE,
    ATTR_QUIRK_APPLIED,
    ATTR_QUIRK_CLASS,
    ATTR_RSSI,
    ATTR_SIGNATURE,
    ATTR_VALUE,
    CLUSTER_COMMAND_SERVER,
    CLUSTER_COMMANDS_CLIENT,
    CLUSTER_COMMANDS_SERVER,
    CLUSTER_TYPE_IN,
    CLUSTER_TYPE_OUT,
    EFFECT_DEFAULT_VARIANT,
    EFFECT_OKAY,
    POWER_BATTERY_OR_UNKNOWN,
    POWER_MAINS_POWERED,
    SIGNAL_AVAILABLE,
    SIGNAL_UPDATE_DEVICE,
    UNKNOWN,
    UNKNOWN_MANUFACTURER,
    UNKNOWN_MODEL,
)
from .helpers import LogMixin

_LOGGER = logging.getLogger(__name__)
CONSIDER_UNAVAILABLE_MAINS = 60 * 60 * 2  # 2 hours
CONSIDER_UNAVAILABLE_BATTERY = 60 * 60 * 6  # 6 hours
_UPDATE_ALIVE_INTERVAL = (60, 90)
_CHECKIN_GRACE_PERIODS = 2

class DeviceStatus(Enum):
    """Status of a device."""

    CREATED = 1
    INITIALIZED = 2

class ZHADevice(LogMixin):
    """ZHA Zigbee device object."""

    def __init__(
        self,
        hass: HomeAssistantType,
        zigpy_device: zha_typing.ZigpyDeviceType,
        zha_gateway: zha_typing.ZhaGatewayType,
    ):
        """Initialize the gateway."""
        self.hass = hass
        self._zigpy_device = zigpy_device
        self._zha_gateway = zha_gateway
        self._available = False
        self._available_signal = f"{self.name}_{self.ieee}_{SIGNAL_AVAILABLE}"
        self._checkins_missed_count = 0
        self.unsubs = []
        self.quirk_applied = isinstance(self._zigpy_device, zigpy.quirks.CustomDevice)
        self.quirk_class = (
            f"{self._zigpy_device.__class__.__module__}."
            f"{self._zigpy_device.__class__.__name__}"
        )

        if self.is_mains_powered:
            self._consider_unavailable_time = CONSIDER_UNAVAILABLE_MAINS
        else:
            self._consider_unavailable_time = CONSIDER_UNAVAILABLE_BATTERY
        keep_alive_interval = random.randint(*_UPDATE_ALIVE_INTERVAL)
        self.unsubs.append(
            async_track_time_interval(
                self.hass, self._check_available, timedelta(seconds=keep_alive_interval)
            )
        )
        self._ha_device_id = None
        self.status = DeviceStatus.CREATED
        self._channels = channels.Channels(self)

    @property
    def device_id(self):
        """Return the HA device registry device id."""
        return self._ha_device_id

    def set_device_id(self, device_id):
        """Set the HA device registry device id."""
        self._ha_device_id = device_id

    @property
    def device(self) -> zha_typing.ZigpyDeviceType:
        """Return underlying Zigpy device."""
        return self._zigpy_device

    @property
    def channels(self) -> zha_typing.ChannelsType:
        """Return ZHA channels."""
        return self._channels

    @channels.setter
    def channels(self, value: zha_typing.ChannelsType) -> None:
        """Channels setter."""
        assert isinstance(value, channels.Channels)
        self._channels = value

    @property
    def name(self):
        """Return device name."""
        return f"{self.manufacturer} {self.model}"

    @property
    def ieee(self):
        """Return ieee address for device."""
        return self._zigpy_device.ieee

    @property
    def manufacturer(self):
        """Return manufacturer for device."""
        if self._zigpy_device.manufacturer is None:
            return UNKNOWN_MANUFACTURER
        return self._zigpy_device.manufacturer

    @property
    def model(self):
        """Return model for device."""
        if self._zigpy_device.model is None:
            return UNKNOWN_MODEL
        return self._zigpy_device.model

    @property
    def manufacturer_code(self):
        """Return the manufacturer code for the device."""
        if self._zigpy_device.node_desc.is_valid:
            return self._zigpy_device.node_desc.manufacturer_code
        return None

    @property
    def nwk(self):
        """Return nwk for device."""
        return self._zigpy_device.nwk

    @property
    def lqi(self):
        """Return lqi for device."""
        return self._zigpy_device.lqi

    @property
    def rssi(self):
        """Return rssi for device."""
        return self._zigpy_device.rssi

    @property
    def last_seen(self):
        """Return last_seen for device."""
        return self._zigpy_device.last_seen

    @property
    def is_mains_powered(self):
        """Return true if device is mains powered."""
        return self._zigpy_device.node_desc.is_mains_powered

    @property
    def device_type(self):
        """Return the logical device type for the device."""
        node_descriptor = self._zigpy_device.node_desc
        return (
            node_descriptor.logical_type.name if node_descriptor.is_valid else UNKNOWN
        )

    @property
    def power_source(self):
        """Return the power source for the device."""
        return (
            POWER_MAINS_POWERED if self.is_mains_powered else POWER_BATTERY_OR_UNKNOWN
        )

    @property
    def is_router(self):
        """Return true if this is a routing capable device."""
        return self._zigpy_device.node_desc.is_router

    @property
    def is_coordinator(self):
        """Return true if this device represents the coordinator."""
        return self._zigpy_device.node_desc.is_coordinator

    @property
    def is_end_device(self):
        """Return true if this device is an end device."""
        return self._zigpy_device.node_desc.is_end_device

    @property
    def is_groupable(self):
        """Return true if this device has a group cluster."""
        return self.is_coordinator or (
            self.available and self.async_get_groupable_endpoints()
        )

    @property
    def skip_configuration(self):
        """Return true if the device should not issue configuration related commands."""
        return self._zigpy_device.skip_configuration

    @property
    def gateway(self):
        """Return the gateway for this device."""
        return self._zha_gateway

    @property
    def device_automation_triggers(self):
        """Return the device automation triggers for this device."""
        triggers = {
            ("device_offline", "device_offline"): {
                "device_event_type": "device_offline"
            }
        }

        if hasattr(self._zigpy_device, "device_automation_triggers"):
            triggers.update(self._zigpy_device.device_automation_triggers)

        return triggers

    @property
    def available_signal(self):
        """Signal to use to subscribe to device availability changes."""
        return self._available_signal

    @property
    def available(self):
        """Return True if device is available."""
        return self._available

    @available.setter
    def available(self, new_availability: bool) -> None:
        """Set device availability."""
        self._available = new_availability

    @property
    def zigbee_signature(self) -> dict[str, Any]:
        """Get zigbee signature for this device."""
        return {
            ATTR_NODE_DESCRIPTOR: str(self._zigpy_device.node_desc),
            ATTR_ENDPOINTS: self._channels.zigbee_signature,
        }

    @classmethod
    def new(
        cls,
        hass: HomeAssistantType,
        zigpy_dev: zha_typing.ZigpyDeviceType,
        gateway: zha_typing.ZhaGatewayType,
        restored: bool = False,
    ):
        """Create new device."""
        zha_dev = cls(hass, zigpy_dev, gateway)
        zha_dev.channels = channels.Channels.new(zha_dev)
        zha_dev.unsubs.append(
            async_dispatcher_connect(
                hass,
                SIGNAL_UPDATE_DEVICE.format(zha_dev.channels.unique_id),
                zha_dev.async_update_sw_build_id,
            )
        )
        return zha_dev

    @callback
    def async_update_sw_build_id(self, sw_version: int):
        """Update device sw version."""
        if self.device_id is None:
            return
        self._zha_gateway.ha_device_registry.async_update_device(
            self.device_id, sw_version=f"0x{sw_version:08x}"
        )

    async def _check_available(self, *_):
        if self.last_seen is None:
            self.update_available(False)
            return

        difference = time.time() - self.last_seen
        if difference < self._consider_unavailable_time:
            self.update_available(True)
            self._checkins_missed_count = 0
            return

        if (
            self._checkins_missed_count >= _CHECKIN_GRACE_PERIODS
            or self.manufacturer == "LUMI"
            or not self._channels.pools
        ):
            self.update_available(False)
            return

        self._checkins_missed_count += 1
        self.debug(
            "Attempting to checkin with device - missed checkins: %s",
            self._checkins_missed_count,
        )
        try:
            pool = self._channels.pools[0]
            basic_ch = pool.all_channels[f"{pool.id}:0x0000"]
        except KeyError:
            self.debug("does not have a mandatory basic cluster")
            self.update_available(False)
            return
        res = await basic_ch.get_attribute_value(ATTR_MANUFACTURER, from_cache=False)
        if res is not None:
            self._checkins_missed_count = 0

    def update_available(self, available: bool) -> None:
        """Update device availability and signal entities."""
        availability_changed = self.available ^ available
        self.available = available
        if availability_changed and available:
            # reinit channels then signal entities
            self.hass.async_create_task(self._async_became_available())
            return
        if availability_changed and not available:
            self._channels.zha_send_event(
                {
                    "device_event_type": "device_offline",
                },
            )
        async_dispatcher_send(self.hass, f"{self._available_signal}_entity")

    async def _async_became_available(self) -> None:
        """Update device availability and signal entities."""
        await self.async_initialize(False)
        async_dispatcher_send(self.hass, f"{self._available_signal}_entity")

    @property
    def device_info(self):
        """Return a device description for device."""
        ieee = str(self.ieee)
        time_struct = time.localtime(self.last_seen)
        update_time = time.strftime("%Y-%m-%dT%H:%M:%S", time_struct)
        return {
            ATTR_IEEE: ieee,
            ATTR_NWK: self.nwk,
            ATTR_MANUFACTURER: self.manufacturer,
            ATTR_MODEL: self.model,
            ATTR_NAME: self.name or ieee,
            ATTR_QUIRK_APPLIED: self.quirk_applied,
            ATTR_QUIRK_CLASS: self.quirk_class,
            ATTR_MANUFACTURER_CODE: self.manufacturer_code,
            ATTR_POWER_SOURCE: self.power_source,
            ATTR_LQI: self.lqi,
            ATTR_RSSI: self.rssi,
            ATTR_LAST_SEEN: update_time,
            ATTR_AVAILABLE: self.available,
            ATTR_DEVICE_TYPE: self.device_type,
            ATTR_SIGNATURE: self.zigbee_signature,
        }

    async def async_configure(self):
        """Configure the device."""
        self.debug("started configuration")
        await self._channels.async_configure()
        self.debug("completed configuration")
        entry = self.gateway.zha_storage.async_create_or_update_device(self)
        self.debug("stored in registry: %s", entry)

        if self._channels.identify_ch is not None and not self.skip_configuration:
            await self._channels.identify_ch.trigger_effect(
                EFFECT_OKAY, EFFECT_DEFAULT_VARIANT
            )

    async def async_initialize(self, from_cache=False):
        """Initialize channels."""
        self.debug("started initialization")
        await self._channels.async_initialize(from_cache)
        self.debug("power source: %s", self.power_source)
        self.status = DeviceStatus.INITIALIZED
        self.debug("completed initialization")

    @callback
    def async_cleanup_handles(self) -> None:
        """Unsubscribe the dispatchers and timers."""
        for unsubscribe in self.unsubs:
            unsubscribe()

    @callback
    def async_update_last_seen(self, last_seen):
        """Set last seen on the zigpy device."""
        if self._zigpy_device.last_seen is None and last_seen is not None:
            self._zigpy_device.last_seen = last_seen

    @property
    def zha_device_info(self):
        """Get ZHA device information."""
        device_info = {}
        device_info.update(self.device_info)
        device_info["entities"] = [
            {
                "entity_id": entity_ref.reference_id,
                ATTR_NAME: entity_ref.device_info[ATTR_NAME],
            }
            for entity_ref in self.gateway.device_registry[self.ieee]
        ]

        # Return the neighbor information
        device_info[ATTR_NEIGHBORS] = [
            {
                "device_type": neighbor.neighbor.device_type.name,
                "rx_on_when_idle": neighbor.neighbor.rx_on_when_idle.name,
                "relationship": neighbor.neighbor.relationship.name,
                "extended_pan_id": str(neighbor.neighbor.extended_pan_id),
                "ieee": str(neighbor.neighbor.ieee),
                "nwk": str(neighbor.neighbor.nwk),
                "permit_joining": neighbor.neighbor.permit_joining.name,
                "depth": str(neighbor.neighbor.depth),
                "lqi": str(neighbor.neighbor.lqi),
            }
            for neighbor in self._zigpy_device.neighbors
        ]

        # Return endpoint device type Names
        names = []
        for endpoint in (ep for epid, ep in self.device.endpoints.items() if epid):
            profile = PROFILES.get(endpoint.profile_id)
            if profile and endpoint.device_type is not None:
                # DeviceType provides undefined enums
                names.append({ATTR_NAME: profile.DeviceType(endpoint.device_type).name})
            else:
                names.append(
                    {
                        ATTR_NAME: f"unknown {endpoint.device_type} device_type "
                        "of 0x{endpoint.profile_id:04x} profile id"
                    }
                )
        device_info[ATTR_ENDPOINT_NAMES] = names

        reg_device = self.gateway.ha_device_registry.async_get(self.device_id)
        if reg_device is not None:
            device_info["user_given_name"] = reg_device.name_by_user
            device_info["device_reg_id"] = reg_device.id
            device_info["area_id"] = reg_device.area_id
        return device_info

    @callback
    def async_get_clusters(self):
        """Get all clusters for this device."""
        return {
            ep_id: {
                CLUSTER_TYPE_IN: endpoint.in_clusters,
                CLUSTER_TYPE_OUT: endpoint.out_clusters,
            }
            for (ep_id, endpoint) in self._zigpy_device.endpoints.items()
            if ep_id != 0
        }

    @callback
    def async_get_groupable_endpoints(self):
        """Get device endpoints that have a group 'in' cluster."""
        return [
            ep_id
            for (ep_id, clusters) in self.async_get_clusters().items()
            if Groups.cluster_id in clusters[CLUSTER_TYPE_IN]
        ]

    @callback
    def async_get_std_clusters(self):
        """Get ZHA and ZLL clusters for this device."""

        return {
            ep_id: {
                CLUSTER_TYPE_IN: endpoint.in_clusters,
                CLUSTER_TYPE_OUT: endpoint.out_clusters,
            }
            for (ep_id, endpoint) in self._zigpy_device.endpoints.items()
            if ep_id != 0 and endpoint.profile_id in PROFILES
        }

    @callback
    def async_get_cluster(self, endpoint_id, cluster_id, cluster_type=CLUSTER_TYPE_IN):
        """Get zigbee cluster from this entity."""
        clusters = self.async_get_clusters()
        return clusters[endpoint_id][cluster_type][cluster_id]

    @callback
    def async_get_cluster_attributes(
        self, endpoint_id, cluster_id, cluster_type=CLUSTER_TYPE_IN
    ):
        """Get zigbee attributes for specified cluster."""
        cluster = self.async_get_cluster(endpoint_id, cluster_id, cluster_type)
        if cluster is None:
            return None
        return cluster.attributes

    @callback
    def async_get_cluster_commands(
        self, endpoint_id, cluster_id, cluster_type=CLUSTER_TYPE_IN
    ):
        """Get zigbee commands for specified cluster."""
        cluster = self.async_get_cluster(endpoint_id, cluster_id, cluster_type)
        if cluster is None:
            return None
        return {
            CLUSTER_COMMANDS_CLIENT: cluster.client_commands,
            CLUSTER_COMMANDS_SERVER: cluster.server_commands,
        }

    async def write_zigbee_attribute(
        self,
        endpoint_id,
        cluster_id,
        attribute,
        value,
        cluster_type=CLUSTER_TYPE_IN,
        manufacturer=None,
    ):
        """Write a value to a zigbee attribute for a cluster in this entity."""
        cluster = self.async_get_cluster(endpoint_id, cluster_id, cluster_type)
        if cluster is None:
            return None

        try:
            response = await cluster.write_attributes(
                {attribute: value}, manufacturer=manufacturer
            )
            self.debug(
                "set: %s for attr: %s to cluster: %s for ept: %s - res: %s",
                value,
                attribute,
                cluster_id,
                endpoint_id,
                response,
            )
            return response
        except zigpy.exceptions.ZigbeeException as exc:
            self.debug(
                "failed to set attribute: %s %s %s %s %s",
                f"{ATTR_VALUE}: {value}",
                f"{ATTR_ATTRIBUTE}: {attribute}",
                f"{ATTR_CLUSTER_ID}: {cluster_id}",
                f"{ATTR_ENDPOINT_ID}: {endpoint_id}",
                exc,
            )
            return None

    async def issue_cluster_command(
        self,
        endpoint_id,
        cluster_id,
        command,
        command_type,
        *args,
        cluster_type=CLUSTER_TYPE_IN,
        manufacturer=None,
    ):
        """Issue a command against specified zigbee cluster on this entity."""
        cluster = self.async_get_cluster(endpoint_id, cluster_id, cluster_type)
        if cluster is None:
            return None
        if command_type == CLUSTER_COMMAND_SERVER:
            response = await cluster.command(
                command, *args, manufacturer=manufacturer, expect_reply=True
            )
        else:
            response = await cluster.client_command(command, *args)

        self.debug(
            "Issued cluster command: %s %s %s %s %s %s %s",
            f"{ATTR_CLUSTER_ID}: {cluster_id}",
            f"{ATTR_COMMAND}: {command}",
            f"{ATTR_COMMAND_TYPE}: {command_type}",
            f"{ATTR_ARGS}: {args}",
            f"{ATTR_CLUSTER_ID}: {cluster_type}",
            f"{ATTR_MANUFACTURER}: {manufacturer}",
            f"{ATTR_ENDPOINT_ID}: {endpoint_id}",
        )
        return response

    async def async_add_to_group(self, group_id):
        """Add this device to the provided zigbee group."""
        try:
            await self._zigpy_device.add_to_group(group_id)
        except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
            self.debug(
                "Failed to add device '%s' to group: 0x%04x ex: %s",
                self._zigpy_device.ieee,
                group_id,
                str(ex),
            )

    async def async_remove_from_group(self, group_id):
        """Remove this device from the provided zigbee group."""
        try:
            await self._zigpy_device.remove_from_group(group_id)
        except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
            self.debug(
                "Failed to remove device '%s' from group: 0x%04x ex: %s",
                self._zigpy_device.ieee,
                group_id,
                str(ex),
            )

    async def async_add_endpoint_to_group(self, endpoint_id, group_id):
        """Add the device endpoint to the provided zigbee group."""
        try:
            await self._zigpy_device.endpoints[int(endpoint_id)].add_to_group(group_id)
        except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
            self.debug(
                "Failed to add endpoint: %s for device: '%s' to group: 0x%04x ex: %s",
                endpoint_id,
                self._zigpy_device.ieee,
                group_id,
                str(ex),
            )

    async def async_remove_endpoint_from_group(self, endpoint_id, group_id):
        """Remove the device endpoint from the provided zigbee group."""
        try:
            await self._zigpy_device.endpoints[int(endpoint_id)].remove_from_group(
                group_id
            )
        except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
            self.debug(
                "Failed to remove endpoint: %s for device '%s' from group: 0x%04x ex: %s",
                endpoint_id,
                self._zigpy_device.ieee,
                group_id,
                str(ex),
            )

    async def async_bind_to_group(self, group_id, cluster_bindings):
        """Directly bind this device to a group for the given clusters."""
        await self._async_group_binding_operation(
            group_id, zdo_types.ZDOCmd.Bind_req, cluster_bindings
        )

    async def async_unbind_from_group(self, group_id, cluster_bindings):
        """Unbind this device from a group for the given clusters."""
        await self._async_group_binding_operation(
            group_id, zdo_types.ZDOCmd.Unbind_req, cluster_bindings
        )

    async def _async_group_binding_operation(
        self, group_id, operation, cluster_bindings
    ):
        """Create or remove a direct zigbee binding between a device and a group."""

        zdo = self._zigpy_device.zdo
        op_msg = "0x%04x: %s %s, ep: %s, cluster: %s to group: 0x%04x"
        destination_address = zdo_types.MultiAddress()
        destination_address.addrmode = types.uint8_t(1)
        destination_address.nwk = types.uint16_t(group_id)

        tasks = []

        for cluster_binding in cluster_bindings:
            if cluster_binding.endpoint_id == 0:
                continue
            if (
                cluster_binding.id
                in self._zigpy_device.endpoints[
                    cluster_binding.endpoint_id
                ].out_clusters
            ):
                op_params = (
                    self.nwk,
                    operation.name,
                    str(self.ieee),
                    cluster_binding.endpoint_id,
                    cluster_binding.id,
                    group_id,
                )
                zdo.debug(f"processing {op_msg}", *op_params)
                tasks.append(
                    (
                        zdo.request(
                            operation,
                            self.ieee,
                            cluster_binding.endpoint_id,
                            cluster_binding.id,
                            destination_address,
                        ),
                        op_msg,
                        op_params,
                    )
                )
        res = await asyncio.gather(*(t[0] for t in tasks), return_exceptions=True)
        for outcome, log_msg in zip(res, tasks):
            if isinstance(outcome, Exception):
                fmt = f"{log_msg[1]} failed: %s"
            else:
                fmt = f"{log_msg[1]} completed: %s"
            zdo.debug(fmt, *(log_msg[2] + (outcome,)))

    def log(self, level, msg, *args):
        """Log a message."""
        msg = f"[%s](%s): {msg}"
        args = (self.nwk, self.model) + args
        _LOGGER.log(level, msg, *args)


text:
Bootstrap-Help-Manager (BHM) uses [VertebrateJS][3] and [jQuery][2] to provide a framework and console for managing help icons and content across an entire site.

On the client side, including [VertebrateJS][3] and `bhm.client.min.js` totals around 10k.

The console is provided as a jQuery plugin. It will send ajax requests to the helpers and pages handling scripts to manage the database backend. Two [PHP][4] handlers with a [MySQL][5] database setup have been provided which could be used to provide the necessary functionality. Any other server-side / database method could be created pretty simply.

BHM adds glyphicon help icons to all kinds of HTML elements. When a user clicks the help icon, a bootstrap modal is shown with the help content defined in the console.

The console features basic adding, deleting of pages and helpers, as well as CKEDITOR for editing the help content. Modal size may be defined.

Helpers are defined using [jQuery](1) selectors. The same helper may be applied to multiple elements on the page.

## Requirements & Installation

[jQuery][1], [Bootstrap][2], and [VertebrateJS][3] (included).

## Client-Side Setup

### Install on Pages in Domain

Include [jQuery][1], [Bootstrap][2] and:

```html
<script src="external/vertebratejs/vertebrate.min.js"></script>
<script src="build/bhm.client.js"></script>
```

Initialize [jQuery][1] plugin with proper urls for server-side scripts and
client templates:

```JavaScript
$('body').BHMClient({
    templateurl: "templates/bhm.client.html",
    clienturl: "src/bhm.client.php",
    indexpage: "index.html"
});
```

#### settings

```
templateurl: "/location/of/bhm.client.html",
clienturl: "/location/of/bhm.client.php",
indexpage: "string or array, see below"
```

For `indexpage` the setting can be either string or array. When BHM is unable to find helps for that page, it will try adding that string (or each string in the array) to the end of the `window.location.pathname` and see if that returns a page.

Example:

```
indexpage: ["index.html","index.php","default.php"]
```
or
```
indexpage: "index.html"
```

### Customizing Help icons

Customize the help icons by changing the template located at `templates/bhm.helpers.html`.

## Server-Side Setup

### PHP

The provided PHP scripts only require a MYSQLI connection setup at the top of the file (define `$db` as the connection).

### MySQL

See `sql/MySQL.sql` for default setup scripts.

Default tables are `bhm_pages`, `bhm_helpers` and (since v0.5.0) `bhm_relationships`.

### Console

Include [jQuery][1], [Bootstrap][2] and:

```html
<script src="external/ckeditor/ckeditor.js"></script>
<script src="external/vertebratejs/vertebrate.min.js"></script>
<script src="build/bhm.console.js"></script>
```

And initialize the console with the jQuery plugin, defining urls for templates
and server-side scripts:

```javascript
$(function() {
    $('#helpsManager').BHMConsole({
        templateurl: "templates/bhm.console.html",
        helpersurl: "src/bhm.helpers.php",
        pagesurl: "src/bhm.pages.php"
    });
})
```

## Using the Console

The admin console assigns helpers to DOM elements.

1. Create a new page by clicking "Add New Page" button.
2. At the prompt, enter the full pathname (everything including the / AFTER .com / .net / .edu / .etc. a/k/a `window.location.pathname`)
3. A new page and helper will be automatically created and saved.
4. Set "Field Selecter" as a [jQuery][1] selector that will select the items on that page you would like to add the help icon to.
5. Set the title of the modal dialog window with "Modal Title".
6. Specify the size as large if desired.
7. Edit the modal content with the "Edit" button.
8. Save

Note:

1. Deleting all the helpers for a page will also delete that page from the database.
2. ALWAYS add "index.html" (i.e. the appropriate index/default filename) to the end of the url
for pages. Then use the `indexpage` setting in `$().BHMClient()` at initialization to help
BHM find the correct page model.
3. Helpers may exist on multiple pages. Bootstrap `info` class is added to helpers on multiple pages.

## Notes about Server-Side / Database Setup for non PHP / MySQL Implementation

The setup queries in `src/sql/MySQL.sql` should work for _most_ SQL databases.

Follow the comments in the three PHP files carefully to understand the JSON
data that the client and server JS files expect. Here's a basic help model:

```JSON
helper: {
    "id": "1",                       //unique ID from bhm_helpers
    "field_selecter": ".bhm-helper", //CSS/jQuery selector to attach help icon to
    "large": "1",                    //1 or 0 - 1 is large
    "page_ids": "2,3",               //comma-separated page ids, not used for client
    "title": "Help with Something",  //title of modal when help pops up
    "html": "<p>Modal Content</p>"   //html content of help modal
}
```

Page models are:
```JSON
page: {
    "id": "1",              //unique ID from bhm_pages
    "url": "/foo/bar.html"  //unique URL of page - always include 'index.html'
}
```

[1]: https://jquery.com/
[2]: http://getBootstrap.com
[3]: https://github.com/psalmody/vertebratejs
[4]: http://php.net/
[5]: http://dev.mysql.com/

redpajama_set_name: RedPajamaGithub


text:
package cn.felord.wepay.ali.sdk.api.response;

import cn.felord.wepay.ali.sdk.api.AlipayResponse;

/**
 * ALIPAY API: koubei.craftsman.data.provider.modify response.
 *
 * @author auto create
 * @version $Id: $Id
 */
public class KoubeiCraftsmanDataProviderModifyResponse extends AlipayResponse {

	private static final long serialVersionUID = 2486446543313833333L;

}


text:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <meta name="GENERATOR" content="Mozilla/4.72 [en] (X11; U; Linux 2.2.14-5.0 i686) [Netscape]">
   <meta name="Author" content="Emmanuel Cecchet">
   <title>RUBiS: Registration</title>

Home

Register

Browse

Sell

About me

Welcome to RUBiS online registration

It's completely free !!!
Just fill the following form to register and get your account !

<form action="/rubis_servlets/servlet/edu.rice.rubis.servlets.RegisterUser" method=POST>

First Name:

<input type=text size=20 name=firstname>

Last Name:

<input type=text size=20 name=lastname>

Nick Name:

<input type=text size=20 name=nickname>

Password:

<input type=password size=20 name=password>

Email address:

<input type=text size=50 name=email>

Region where you live:

<input type=text size=20 name=region>  (List available regions)

<input type=submit value="Register now!">

RUBiS (C) 2001 - Rice University/INRIA


text:
<?php
require_once("inc/header.inc.php");
?>

Edit

<?php
require_once "inc/triggers.inc.php";
if (isset($_SESSION['mailcow_cc_loggedin']) &&
		isset($_SESSION['mailcow_cc_role']) &&
		$_SESSION['mailcow_cc_loggedin'] == "yes" &&
		$_SESSION['mailcow_cc_role'] != "user") {
	if (isset($_GET['alias'])) {
		if (!filter_var($_GET["alias"], FILTER_VALIDATE_EMAIL) || empty($_GET["alias"])) {
			echo 'Incorrect form data';
		}
		else {
			$alias = mysqli_real_escape_string($link, $_GET["alias"]);
			if (mysqli_num_rows(mysqli_query($link, "SELECT address, domain FROM alias WHERE address='$alias' AND (domain IN (SELECT domain from domain_admins WHERE username='$logged_in_as') OR 'admin'='$logged_in_role');")) > 0) {
			$result = mysqli_fetch_assoc(mysqli_query($link, "SELECT active, goto FROM alias WHERE address='$alias'"));
?>

Change alias attributes for <?=$alias;?>

				<form class="form-horizontal" role="form" method="post">
				<input type="hidden" name="address" value="<?=$alias;?>">

						Destination address(es) (comma-separated values):

							<textarea class="form-control" autocapitalize="none" autocorrect="off" rows="10" name="goto"><?=$result['goto'] ?></textarea>

							<input type="checkbox" name="active" <?php if (isset($result['active']) && $result['active']=="1") { echo "checked"; }; ?>> Active

							<button type="submit" name="trigger_mailbox_action" value="editalias" class="btn btn-success btn-sm">Submit</button>

				</form>
<?php
			}
			else {
				echo 'Item not found or no permission.';
			}
		}
	}
	elseif (isset($_GET['domain_admin'])) {
		if (!ctype_alnum(str_replace(array('@', '.', '-'), '', $_GET["domain_admin"])) || empty($_GET["domain_admin"])) {
			echo 'Incorrect form data';
		}
		else {
			$domain_admin = mysqli_real_escape_string($link, $_GET["domain_admin"]);
			if (mysqli_num_rows(mysqli_query($link, "SELECT username FROM domain_admins WHERE username='$domain_admin'")) > 0 && $logged_in_role == "admin") {
			$result = mysqli_fetch_assoc(mysqli_query($link, "SELECT * FROM domain_admins WHERE username='$domain_admin'"));
	?>

Change assigned domains for domain administrator <?=$domain_admin;?>

				<form class="form-horizontal" role="form" method="post">
				<input type="hidden" name="username" value="<?=$domain_admin;?>">

						Target domain (hold CTRL to select multiple domains):

							<select name="domain[]" multiple>
<?php
$result_selected = mysqli_query($link, "SELECT domain FROM domain WHERE domain IN (SELECT domain FROM domain_admins WHERE username='".$domain_admin."')");
while ($row_selected = mysqli_fetch_array($result_selected)):
?>
	<option selected><?=$row_selected['domain'];?></option>
<?php
endwhile;
$result_unselected = mysqli_query($link, "SELECT domain FROM domain WHERE domain NOT IN (SELECT domain FROM domain_admins WHERE username='".$domain_admin."')");
while ($row_unselected = mysqli_fetch_array($result_unselected)):
?>
	<option><?=$row_unselected['domain'];?></option>
<?php
endwhile;
?>
							</select>

						Password:

						<input type="password" class="form-control" name="password" id="password" placeholder="Unchanged if empty">

						Password (repeat):

						<input type="password" class="form-control" name="password2" id="password2">

							<input type="checkbox" name="active" <?php if (isset($result['active']) && $result['active']=="1") { echo "checked"; }; ?>> Active

							<button type="submit" name="trigger_mailbox_action" value="editdomainadmin" class="btn btn-success btn-sm">Submit</button>

				</form>
	<?php
			}
			else {
				echo 'Item not found or no permission.';
			}
		}
	}
	elseif (isset($_GET['domain'])) {
		if (!is_valid_domain_name($_GET["domain"]) || empty($_GET["domain"])) {
			echo 'Incorrect form data';
		}
		else {
			$domain = mysqli_real_escape_string($link, $_GET["domain"]);
			if (mysqli_fetch_array(mysqli_query($link, "SELECT domain FROM domain WHERE domain='$domain' AND ((domain IN (SELECT domain from domain_admins WHERE username='$logged_in_as') OR 'admin'='$logged_in_role'))"))) {
			$result = mysqli_fetch_assoc(mysqli_query($link, "SELECT * FROM domain WHERE domain='$domain'"));
	?>

Change settings for domain <?=$domain;?>

				<form class="form-horizontal" role="form" method="post">
				<input type="hidden" name="domain" value="<?=$domain;?>">

						Description:

						<input type="text" class="form-control" name="description" id="description" value="<?=htmlspecialchars($result['description']);?>">

						Max. aliases:

						<input type="number" class="form-control" name="aliases" id="aliases" value="<?=$result['aliases'];?>">

						Max. mailboxes:

						<input type="number" class="form-control" name="mailboxes" id="mailboxes" value="<?=$result['mailboxes'];?>">

						Max. size per mailbox (MB):

						<input type="number" class="form-control" name="maxquota" id="maxquota" value="<?=$result['maxquota'];?>">

						Domain quota:

						<input type="number" class="form-control" name="quota" id="quota" value="<?=$result['quota'];?>">

						Backup MX options:

							<input type="checkbox" name="backupmx" <?php if (isset($result['backupmx']) && $result['backupmx']=="1") { echo "checked"; }; ?>> Relay domain

							<input type="checkbox" name="relay_all_recipients" <?php if (isset($result['relay_all_recipients']) && $result['relay_all_recipients']=="1") { echo "checked"; }; ?>> Relay all recipient addresses

If you choose not to relay all recipient addresses, a mailbox must be created for each recipient on this server.

							<input type="checkbox" name="active" <?php if (isset($result['active']) && $result['active']=="1") { echo "checked"; }; ?>> Active

							<button type="submit" name="trigger_mailbox_action" value="editdomain" class="btn btn-success btn-sm">Submit</button>

				</form>
	<?php
			}
			else {
				echo 'Item not found or no permission.';
			}
		}
	}
	elseif (isset($_GET['mailbox'])) {
		if (!filter_var($_GET["mailbox"], FILTER_VALIDATE_EMAIL) || empty($_GET["mailbox"])) {
			echo 'Incorrect form data';
		}
		else {
			$mailbox = mysqli_real_escape_string($link, $_GET["mailbox"]);
			if (mysqli_num_rows(mysqli_query($link, "SELECT username, domain FROM mailbox WHERE username='".$mailbox."' AND ((domain IN (SELECT domain from domain_admins WHERE username='".$logged_in_as."') OR 'admin'='".$logged_in_role."'))")) > 0) {
			$result = mysqli_fetch_assoc(mysqli_query($link, "SELECT username, domain, name, round(sum(quota / 1048576)) as quota, active FROM mailbox WHERE username='".$mailbox."'"));
	?>

Change settings for mailbox <?=$mailbox;?>

				<form class="form-horizontal" role="form" method="post">
				<input type="hidden" name="username" value="<?=$result['username'];?>">

						Name:

						<input type="text" class="form-control" name="name" id="name" value="<?=$result['name'];?>">

						Quota (MB), 0 = unlimited:

						<input type="number" class="form-control" name="quota" id="quota" value="<?=$result['quota'];?>">

						Sender ACL:

							<select title="Search users..." style="width:100%" name="sender_acl[]" size="10" multiple>
							<?php
							$result_goto_from_alias = mysqli_query($link, "SELECT address FROM alias
								WHERE goto='".$mailbox."'");
							while ($row_goto_from_alias = mysqli_fetch_array($result_goto_from_alias)):
							?>
								<option selected disabled="disabled"><?=$row_goto_from_alias['address'];?></option>
							<?php
							endwhile;

							$result_selected_sender_acl = mysqli_query($link, "SELECT send_as FROM sender_acl
								WHERE logged_in_as='".$mailbox."'");
							while ($row_selected_sender_acl = mysqli_fetch_array($result_selected_sender_acl)):
								?>
									<option selected><?=$row_selected_sender_acl['send_as'];?></option>
								<?php
							endwhile;

							$result_unselected_sender_acl = mysqli_query($link, "SELECT address FROM alias
								WHERE goto!='".$mailbox."' AND
								domain='".$result['domain']."' AND
								address NOT IN (SELECT send_as FROM sender_acl WHERE logged_in_as='".$mailbox."')");
							while ($row_unselected_sender_acl = mysqli_fetch_array($result_unselected_sender_acl)):
							?>
								<option><?=$row_unselected_sender_acl['address'];?></option>
							<?php
							endwhile;
							?>
							</select>

Usernames and aliases cannot be removed from sender list.

						Password:

						<input type="password" class="form-control" name="password" id="password" placeholder="Unchanged if empty">

						Password (repeat):

						<input type="password" class="form-control" name="password2" id="password2">

							<input type="checkbox" name="active" <?php if (isset($result['active']) && $result['active']=="1") { echo "checked"; }; ?>> Active

							<button type="submit" name="trigger_mailbox_action" value="editmailbox" class="btn btn-success btn-sm">Submit</button>

				</form>
	<?php
			}
			else {
				echo 'Item not found or no permission.';
			}
		}
	}
	else {
		echo '
Error:  No action specified.
';
	}
}
elseif (isset($_SESSION['mailcow_cc_loggedin']) &&
		isset($_SESSION['mailcow_cc_role']) &&
		$_SESSION['mailcow_cc_loggedin'] == "yes" &&
		$_SESSION['mailcow_cc_role'] == "user") {
	if (isset($_GET['dav'])) {
		if (!filter_var($_GET["dav"], FILTER_VALIDATE_EMAIL) || empty($_GET["dav"])) {
			echo 'Incorrect form data';
		}
		else {
			$dav = mysqli_real_escape_string($link, $_GET["dav"]);
			if ($dav == $logged_in_as) {
?>

Change DAV folder properties

Share your calendars with other users.

				<form class="form-horizontal" role="form" method="post">

Read-only

						<select title="Search users..." style="width:100%" name="cal_ro_share[]" size="5" multiple>
						<?php
						$result_rcrs = mysqli_query($link, "SELECT email FROM principals
							WHERE id IN (SELECT member_id FROM groupmembers
								WHERE principal_id IN (SELECT id FROM principals
									WHERE uri='principals/$logged_in_as/calendar-proxy-read'))");
						while ($row_cal_ro_selected = mysqli_fetch_array($result_rcrs)):
						?>
							<option selected><?=$row_cal_ro_selected['email'];?></option>
						<?php
						endwhile;

						$result_rcru = mysqli_query($link, "SELECT email FROM principals
							WHERE id NOT IN (SELECT member_id FROM groupmembers
								WHERE principal_id IN (SELECT id FROM principals
									WHERE uri='principals/$logged_in_as/calendar-proxy-read'))
							AND email IS NOT NULL
							AND email!='$logged_in_as'");
						while ($row_cal_ro_unselected = mysqli_fetch_array($result_rcru)):
						?>
							<option><?=$row_cal_ro_unselected['email'];?></option>
						<?php
						endwhile;
						?>
						</select>

Read-write

						<select title="Search users..." style="width:100%" name="cal_rw_share[]" size="5" multiple>
						<?php
						$result_rcrws = mysqli_query($link, "SELECT email FROM principals
							WHERE id IN (SELECT member_id FROM groupmembers
								WHERE principal_id IN (SELECT id FROM principals
									WHERE uri='principals/$logged_in_as/calendar-proxy-write'))");
						while ($row_cal_rw_selected = mysqli_fetch_array($result_rcrws)):
						?>
							<option selected><?=$row_cal_rw_selected['email'];?></option>
						<?php
						endwhile;
						$result_rcrwu = mysqli_query($link, "SELECT email FROM principals
							WHERE id NOT IN (SELECT member_id FROM groupmembers
								WHERE principal_id IN (SELECT id FROM principals
									WHERE uri='principals/$logged_in_as/calendar-proxy-write'))
							AND email IS NOT NULL
							AND email!='$logged_in_as'");
						while ($row_cal_rw_unselected = mysqli_fetch_array($result_rcrwu)):
						?>
							<option><?=$row_cal_rw_unselected['email'];?></option>
						<?php
						endwhile;
						?>
						</select>

Edit or delete address books and calendars below.

Note: Default address books and calendars cannot be deleted.

						Type
						Display name
						Delete

					<?php
					$result_row_cal = mysqli_query($link, "SELECT id, uri, displayname FROM calendars WHERE principaluri='principals/$logged_in_as'");
					while ($row_cal = mysqli_fetch_array($result_row_cal)):
					?>

						Calendar, Tasks
						<input type="text" style="width:100%" name="cal_displayname[<?=$row_cal['id'];?>]" value="<?=$row_cal['displayname'];?>">
						<?php
						if ($row_cal['uri'] != "default"):
						?>
						<input type="checkbox" name="cal_delete[]" value="<?=$row_cal['id'];?>">
						<?php
						else:
						?>
						<input type="checkbox" disabled>
						<?php
						endif;
						?>

					<?php
					endwhile;
					$result_row_adb = mysqli_query($link, "SELECT id, uri, displayname FROM addressbooks WHERE principaluri='principals/$logged_in_as'");
					while ($row_adb = mysqli_fetch_array($result_row_adb)):
					?>

						Address book
						<input type="text" style="width:100%" name="adb_displayname[<?=$row_adb['id'];?>]" value="<?=$row_adb['displayname'];?>">
						<?php
						if ($row_adb['uri'] != "default"):
						?>
						<input type="checkbox" name="adb_delete[]" value="<?=$row_adb['id'];?>">
						<?php
						else:
						?>
						<input type="checkbox" disabled>
						<?php
						endif;
						?>

					<?php
					endwhile;
					?>

						<button type="submit" name="trigger_mailbox_action" value="editdav" class="btn btn-success btn-sm">Apply</button>

				</form>
	<?php
			}
			else {
				echo 'Item not found or no permission.';
			}
		}
	}
	else {
		echo '
Error:  No valid action specified.
';
	}
}
else {
	echo '
Permission denied';
}
?>

<a href="<?=$_SESSION['return_to'];?>">← go back

<?php
require_once("inc/footer.inc.php");
?>


text:
.class public Landroid/app/StatusBarManager;
.super Ljava/lang/Object;
.source "StatusBarManager.java"

# static fields
.field public static final DISABLE_BACK:I = 0x400000

.field public static final DISABLE_CLOCK:I = 0x800000

.field public static final DISABLE_EXPAND:I = 0x10000

.field public static final DISABLE_HOME:I = 0x200000

.field public static final DISABLE_MASK:I = 0x3ff0000

.field public static final DISABLE_NAVIGATION:I = 0x1200000
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final DISABLE_NONE:I = 0x0

.field public static final DISABLE_NOTIFICATION_ALERTS:I = 0x40000

.field public static final DISABLE_NOTIFICATION_ICONS:I = 0x20000

.field public static final DISABLE_NOTIFICATION_TICKER:I = 0x80000
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final DISABLE_RECENT:I = 0x1000000

.field public static final DISABLE_SEARCH:I = 0x2000000

.field public static final DISABLE_SYSTEM_INFO:I = 0x100000

.field public static final NAVIGATION_HINT_BACK_ALT:I = 0x1

.field public static final NAVIGATION_HINT_IME_SHOWN:I = 0x2

.field private static final TAG:Ljava/lang/String; = "StatusBarManager"

.field public static final WINDOW_NAVIGATION_BAR:I = 0x2

.field public static final WINDOW_STATE_HIDDEN:I = 0x2

.field public static final WINDOW_STATE_HIDING:I = 0x1

.field public static final WINDOW_STATE_SHOWING:I = 0x0

.field public static final WINDOW_STATUS_BAR:I = 0x1

# instance fields
.field private mContext:Landroid/content/Context;

.field private mService:Lcom/android/internal/statusbar/IStatusBarService;

.field private mToken:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/content/Context;)V
    .locals 1
    .param p1, "context"    # Landroid/content/Context;

    .prologue
    .line 85
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 81
    new-instance v0, Landroid/os/Binder;

    invoke-direct {v0}, Landroid/os/Binder;-><init>()V

    iput-object v0, p0, Landroid/app/StatusBarManager;->mToken:Landroid/os/IBinder;

    .line 86
    iput-object p1, p0, Landroid/app/StatusBarManager;->mContext:Landroid/content/Context;

    .line 87
    return-void
.end method

.method private declared-synchronized getService()Lcom/android/internal/statusbar/IStatusBarService;
    .locals 2

    .prologue
    .line 90
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Landroid/app/StatusBarManager;->mService:Lcom/android/internal/statusbar/IStatusBarService;

    if-nez v0, :cond_0

    .line 91
    const-string/jumbo v0, "statusbar"

    invoke-static {v0}, Landroid/os/ServiceManager;->getService(Ljava/lang/String;)Landroid/os/IBinder;

    move-result-object v0

    invoke-static {v0}, Lcom/android/internal/statusbar/IStatusBarService$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v0

    iput-object v0, p0, Landroid/app/StatusBarManager;->mService:Lcom/android/internal/statusbar/IStatusBarService;

    .line 93
    iget-object v0, p0, Landroid/app/StatusBarManager;->mService:Lcom/android/internal/statusbar/IStatusBarService;

    if-nez v0, :cond_0

    .line 94
    const-string v0, "StatusBarManager"

    const-string/jumbo v1, "warning: no STATUS_BAR_SERVICE"

    invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 97
    :cond_0
    iget-object v0, p0, Landroid/app/StatusBarManager;->mService:Lcom/android/internal/statusbar/IStatusBarService;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    return-object v0

    .line 90
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method public static windowStateToString(I)Ljava/lang/String;
    .locals 1
    .param p0, "state"    # I

    .prologue
    .line 200
    const/4 v0, 0x1

    if-ne p0, v0, :cond_0

    const-string v0, "WINDOW_STATE_HIDING"

    .line 203
    :goto_0
    return-object v0

    .line 201
    :cond_0
    const/4 v0, 0x2

    if-ne p0, v0, :cond_1

    const-string v0, "WINDOW_STATE_HIDDEN"

    goto :goto_0

    .line 202
    :cond_1
    if-nez p0, :cond_2

    const-string v0, "WINDOW_STATE_SHOWING"

    goto :goto_0

    .line 203
    :cond_2
    const-string v0, "WINDOW_STATE_UNKNOWN"

    goto :goto_0
.end method

# virtual methods
.method public collapsePanels()V
    .locals 3

    .prologue
    .line 136
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 137
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 138
    invoke-interface {v1}, Lcom/android/internal/statusbar/IStatusBarService;->collapsePanels()V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 144
    :cond_0
    return-void

    .line 140
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 142
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public disable(I)V
    .locals 4
    .param p1, "what"    # I

    .prologue
    .line 106
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 107
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 108
    iget-object v2, p0, Landroid/app/StatusBarManager;->mToken:Landroid/os/IBinder;

    iget-object v3, p0, Landroid/app/StatusBarManager;->mContext:Landroid/content/Context;

    invoke-virtual {v3}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, p1, v2, v3}, Lcom/android/internal/statusbar/IStatusBarService;->disable(ILandroid/os/IBinder;Ljava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 114
    :cond_0
    return-void

    .line 110
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 112
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public expandNotificationsPanel()V
    .locals 3

    .prologue
    .line 121
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 122
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 123
    invoke-interface {v1}, Lcom/android/internal/statusbar/IStatusBarService;->expandNotificationsPanel()V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 129
    :cond_0
    return-void

    .line 125
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 127
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public expandSettingsPanel()V
    .locals 3

    .prologue
    .line 151
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 152
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 153
    invoke-interface {v1}, Lcom/android/internal/statusbar/IStatusBarService;->expandSettingsPanel()V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 159
    :cond_0
    return-void

    .line 155
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 157
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public hideSimIndicator(Landroid/content/ComponentName;)V
    .locals 6
    .param p1, "componentName"    # Landroid/content/ComponentName;

    .prologue
    .line 268
    if-nez p1, :cond_1

    const-string/jumbo v1, "null"

    .line 270
    .local v1, "pkgName":Ljava/lang/String;
    :goto_0
    :try_start_0
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Hide SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 271
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v2

    .line 272
    .local v2, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v2, :cond_0

    .line 273
    iget-object v3, p0, Landroid/app/StatusBarManager;->mService:Lcom/android/internal/statusbar/IStatusBarService;

    invoke-interface {v3}, Lcom/android/internal/statusbar/IStatusBarService;->hideSimIndicator()V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 280
    :cond_0
    return-void

    .line 268
    .end local v1    # "pkgName":Ljava/lang/String;
    .end local v2    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :cond_1
    invoke-virtual {p1}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v1

    goto :goto_0

    .line 275
    .restart local v1    # "pkgName":Ljava/lang/String;
    :catch_0
    move-exception v0

    .line 276
    .local v0, "ex":Landroid/os/RemoteException;
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Hide SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " occurs exception."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 278
    new-instance v3, Ljava/lang/RuntimeException;

    invoke-direct {v3, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v3
.end method

.method public removeIcon(Ljava/lang/String;)V
    .locals 3
    .param p1, "slot"    # Ljava/lang/String;

    .prologue
    .line 176
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 177
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 178
    invoke-interface {v1, p1}, Lcom/android/internal/statusbar/IStatusBarService;->removeIcon(Ljava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 184
    :cond_0
    return-void

    .line 180
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 182
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public setIcon(Ljava/lang/String;IILjava/lang/String;)V
    .locals 7
    .param p1, "slot"    # Ljava/lang/String;
    .param p2, "iconId"    # I
    .param p3, "iconLevel"    # I
    .param p4, "contentDescription"    # Ljava/lang/String;

    .prologue
    .line 163
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v0

    .line 164
    .local v0, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v0, :cond_0

    .line 165
    iget-object v1, p0, Landroid/app/StatusBarManager;->mContext:Landroid/content/Context;

    invoke-virtual {v1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v2

    move-object v1, p1

    move v3, p2

    move v4, p3

    move-object v5, p4

    invoke-interface/range {v0 .. v5}, Lcom/android/internal/statusbar/IStatusBarService;->setIcon(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 172
    :cond_0
    return-void

    .line 168
    .end local v0    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v6

    .line 170
    .local v6, "ex":Landroid/os/RemoteException;
    new-instance v1, Ljava/lang/RuntimeException;

    invoke-direct {v1, v6}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v1
.end method

.method public setIconVisibility(Ljava/lang/String;Z)V
    .locals 3
    .param p1, "slot"    # Ljava/lang/String;
    .param p2, "visible"    # Z

    .prologue
    .line 188
    :try_start_0
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v1

    .line 189
    .local v1, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v1, :cond_0

    .line 190
    invoke-interface {v1, p1, p2}, Lcom/android/internal/statusbar/IStatusBarService;->setIconVisibility(Ljava/lang/String;Z)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 196
    :cond_0
    return-void

    .line 192
    .end local v1    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :catch_0
    move-exception v0

    .line 194
    .local v0, "ex":Landroid/os/RemoteException;
    new-instance v2, Ljava/lang/RuntimeException;

    invoke-direct {v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v2
.end method

.method public showSimIndicator(Landroid/content/ComponentName;Ljava/lang/String;)V
    .locals 6
    .param p1, "componentName"    # Landroid/content/ComponentName;
    .param p2, "businessType"    # Ljava/lang/String;

    .prologue
    .line 219
    if-nez p1, :cond_1

    const-string/jumbo v1, "null"

    .line 221
    .local v1, "pkgName":Ljava/lang/String;
    :goto_0
    :try_start_0
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Show SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, ", businiss is "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 222
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v2

    .line 223
    .local v2, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v2, :cond_0

    .line 224
    const-wide/16 v4, -0x1

    invoke-interface {v2, p2, v4, v5}, Lcom/android/internal/statusbar/IStatusBarService;->showSimIndicator(Ljava/lang/String;J)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 231
    :cond_0
    return-void

    .line 219
    .end local v1    # "pkgName":Ljava/lang/String;
    .end local v2    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :cond_1
    invoke-virtual {p1}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v1

    goto :goto_0

    .line 226
    .restart local v1    # "pkgName":Ljava/lang/String;
    :catch_0
    move-exception v0

    .line 227
    .local v0, "ex":Landroid/os/RemoteException;
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Show SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " occurs exception."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 229
    new-instance v3, Ljava/lang/RuntimeException;

    invoke-direct {v3, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v3
.end method

.method public showSimIndicator(Landroid/content/ComponentName;Ljava/lang/String;J)V
    .locals 7
    .param p1, "componentName"    # Landroid/content/ComponentName;
    .param p2, "businessType"    # Ljava/lang/String;
    .param p3, "indicatorID"    # J

    .prologue
    .line 245
    if-nez p1, :cond_1

    const-string/jumbo v1, "null"

    .line 247
    .local v1, "pkgName":Ljava/lang/String;
    :goto_0
    :try_start_0
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Show SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, ", businiss is "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, ", indicatorID is "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p3, p4}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 249
    invoke-direct {p0}, Landroid/app/StatusBarManager;->getService()Lcom/android/internal/statusbar/IStatusBarService;

    move-result-object v2

    .line 250
    .local v2, "svc":Lcom/android/internal/statusbar/IStatusBarService;
    if-eqz v2, :cond_0

    .line 251
    invoke-interface {v2, p2, p3, p4}, Lcom/android/internal/statusbar/IStatusBarService;->showSimIndicator(Ljava/lang/String;J)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 258
    :cond_0
    return-void

    .line 245
    .end local v1    # "pkgName":Ljava/lang/String;
    .end local v2    # "svc":Lcom/android/internal/statusbar/IStatusBarService;
    :cond_1
    invoke-virtual {p1}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v1

    goto :goto_0

    .line 253
    .restart local v1    # "pkgName":Ljava/lang/String;
    :catch_0
    move-exception v0

    .line 254
    .local v0, "ex":Landroid/os/RemoteException;
    const-string v3, "StatusBarManager"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Show SIM indicator from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " occurs exception."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 256
    new-instance v3, Ljava/lang/RuntimeException;

    invoke-direct {v3, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    throw v3
.end method


text:
px4_add_board(
	PLATFORM nuttx
	VENDOR px4
	MODEL fmu-v4pro
	LABEL default
	TOOLCHAIN arm-none-eabi
	ARCHITECTURE cortex-m4
	CONSTRAINED_MEMORY
	ROMFSROOT px4fmu_common
	IO px4_io-v2_default
	UAVCAN_INTERFACES 2
	SERIAL_PORTS
		GPS1:/dev/ttyS3
		TEL1:/dev/ttyS1
		TEL2:/dev/ttyS2
		TEL3:/dev/ttyS0
		TEL4:/dev/ttyS6
	DRIVERS
		adc/ads1115
		adc/board_adc
		barometer # all available barometer drivers
		batt_smbus
		camera_capture
		camera_trigger
		differential_pressure # all available differential pressure drivers
		distance_sensor # all available distance sensor drivers
		dshot
		gps
		#heater
		#imu # all available imu drivers
		imu/analog_devices/adis16448
		imu/invensense/icm20602
		imu/invensense/icm20608g
		imu/invensense/icm20948 # required for ak09916 mag
		imu/invensense/mpu9250
		irlock
		lights # all available light drivers
		magnetometer # all available magnetometer drivers
		optical_flow # all available optical flow drivers
		osd
		pca9685
		pca9685_pwm_out
		#power_monitor/ina226
		#protocol_splitter
		pwm_input
		pwm_out_sim
		pwm_out
		px4io
		roboclaw
		rpm
		smart_battery/batmon
		telemetry # all available telemetry drivers
		tone_alarm
		uavcan
	MODULES
		airspeed_selector
		attitude_estimator_q
		battery_status
		camera_feedback
		commander
		dataman
		ekf2
		esc_battery
		events
		flight_mode_manager
		fw_att_control
		fw_pos_control_l1
		gyro_calibration
		gyro_fft
		land_detector
		landing_target_estimator
		load_mon
		local_position_estimator
		logger
		mavlink
		mc_att_control
		mc_hover_thrust_estimator
		mc_pos_control
		mc_rate_control
		#micrortps_bridge
		navigator
		rc_update
		rover_pos_control
		sensors
		sih
		temperature_compensation
		uuv_att_control
		uuv_pos_control
		vmount
		vtol_att_control
	SYSTEMCMDS
		bl_update
		#dmesg
		dumpfile
		esc_calib
		gpio
		hardfault_log
		i2cdetect
		led_control
		mft
		mixer
		motor_ramp
		motor_test
		mtd
		nshterm
		param
		perf
		pwm
		reboot
		reflect
		sd_bench
		system_time
		top
		topic_listener
		tune_control
		uorb
		usb_connected
		ver
		work_queue
	EXAMPLES
		fake_gps
		#fake_imu
		#fake_magnetometer
		#fixedwing_control # Tutorial code from https://px4.io/dev/example_fixedwing_control
		#hello
		#hwtest # Hardware test
		#matlab_csv_serial
		#px4_mavlink_debug # Tutorial code from http://dev.px4.io/en/debug/debug_values.html
		#px4_simple_app # Tutorial code from http://dev.px4.io/en/apps/hello_sky.html
		#rover_steering_control # Rover example app
		#uuv_example_app
		#work_item
	)


text:
namespace claire {
namespace protorpc {

static bool g_protorpc_healthy = true;

void BuiltinServiceImpl::HeartBeat(RpcControllerPtr& controller,
                                   const HeartBeatRequestPtr& request,
                                   const HeartBeatResponse* response_prototype,
                                   const RpcDoneCallback& done)
{
    HeartBeatResponse response;
    if (g_protorpc_healthy)
    {
        response.set_status("Ok");
    }
    else
    {
        response.set_status("Bad");
    }
    done(controller, &response);
}

void BuiltinServiceImpl::Services(RpcControllerPtr& controller,
                                  const ServicesRequestPtr& request,
                                  const ServicesResponse* response_prototype,
                                  const RpcDoneCallback& done)
{
    ServicesResponse response;
    for (auto it = services_.cbegin(); it != services_.cend(); ++it)
    {
        if (it->second == this)
        {
            continue;
        }
        response.add_services()->set_name(it->second->GetDescriptor()->full_name());
    }
    done(controller, &response);
}

void BuiltinServiceImpl::GetFileSet(RpcControllerPtr& controller,
                                    const GetFileSetRequestPtr& request,
                                    const GetFileSetResponse* response_prototype,
                                    const RpcDoneCallback& done)
{
    GetFileSetResponse response;
    for (int i = 0; i < request->names_size(); i++)
    {
        auto it = services_.find(request->names(i));
        if (it != services_.end())
        {
            auto file = response.mutable_file_set()->add_file();
            it->second->GetDescriptor()->file()->CopyTo(file);
        }
    }
    done(controller, &response);
}

} // namespace protorpc
} // namespace claire


text:
<?php
namespace Siegelion\System\Hook;

use Siegelion\System\Framework\BaseBundle\AbstrackHook;

class PostRuntimeKernel extends AbstrackHook
{
    public function initQueue()
    {

    }
}


text: Starter project for AthenaHacks 2017 workshop


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "productos".
 *
 * @property integer $id
 * @property string $nombre
 * @property string $detalle
 * @property string $precio_lista
 * @property string $precio_venta
 * @property string $nombre_foto
 * @property string $stock
 * @property string $stock_minimo
 */
class Productos extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'productos';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nombre', 'precio_lista', 'precio_venta', 'nombre_foto'], 'required'],
            [['precio_lista', 'precio_venta','stock', 'stock_minimo'], 'number'],
            [['nombre'], 'string', 'max' => 60],
            [['detalle'], 'string', 'max' => 120],
            [['nombre_foto'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'nombre' => 'Nombre',
            'detalle' => 'Detalle',
            'precio_lista' => 'Precio Lista',
            'precio_venta' => 'Precio Venta',
            'nombre_foto' => 'Nombre Foto',
            'stock' => 'Stock',
            'stock_minimo' => 'Stock Minimo',
        ];
    }

    public function getProductos() {
        return $this->hasMany(Productos::className(), ['prod_id' => 'id']);
    }
}


text:
<!--
Description: Iacute
Expect:      feed['title'] == 'testing \xcd entity'
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>testing Í entity</title>
</feed>


text:
import './_confirmation.sass'
import templateUrl from './confirmation.html'

/** @ngInject */
export function ConfirmationDirective ($uibPosition, $window) {
  var directive = {
    restrict: 'AE',
    scope: {
      id: '@?confirmationId',
      position: '@?confirmationPosition',
      title: '@?confirmationTitle',
      message: '@?confirmationMessage',
      triggerOnValue: '=?confirmationTriggerValue',
      trigger: '@?confirmationTrigger',
      ok: '@?confirmationOkText',
      cancel: '@?confirmationCancelText',
      onOk: '&confirmationOnOk',
      onCancel: '&?confirmationOnCancel',
      okStyle: '@?confirmationOkStyle',
      confirmIf: '&?confirmationIf',
      showCancel: '=?confirmationShowCancel',
      itemsTitle: '@?confirmationItemsTitle',
      items: '=?confirmationItems',
      itemNameField: '@?confirmationItemNameField'
    },
    link: link,
    controller: ConfirmationController,
    controllerAs: 'vm',
    bindToController: true
  }

  return directive

  function link (scope, element, attrs, controller) {
    controller.activate({
      getOffset: getOffset,
      getPosition: getPosition,
      size: getSizeOfConfirmation()
    })

    if (angular.isDefined(controller.triggerOnValue)) {
      scope.$watch(function () {
        return controller.triggerOnValue
      },
      function (newValue) {
        if (newValue === true) {
          controller.onTrigger()
        }
      })
    } else {
      element.on(attrs.confirmationTrigger || 'click', controller.onTrigger)
    }

    function getOffset () {
      return $window.pageYOffset
    }

    function getPosition () {
      return $uibPosition.offset(element)
    }

    // Private

    function getSizeOfConfirmation () {
      var height, width
      var sizerMessage = attrs.confirmationMessage || __('For Sizing')
      var sizer = angular.element('

' +
        '

' + sizerMessage +
        '

' +
        '<button type="button" class="confirmation__button btn-rounded">' +
        __('For Sizing') +
        '</button>' +
        '

')

      sizer.css('visibility', 'hidden')
      element.parent().append(sizer)
      height = sizer.prop('offsetHeight')
      width = sizer.prop('offsetWidth')
      sizer.detach()

      return {
        height: height,
        width: width
      }
    }
  }

  /** @ngInject */
  function ConfirmationController ($scope, $uibModal, lodash) {
    var vm = this

    var modalOptions = {
      templateUrl,
      scope: $scope
    }

    vm.top = 0
    vm.left = 0

    vm.activate = activate
    vm.onTrigger = onTrigger

    vm.collapseItemsThreshold = 5
    vm.toggleShowItems = function () {
      vm.showItems = !vm.showItems
    }

    function activate (api) {
      angular.extend(vm, api)
      vm.position = angular.isDefined(vm.position) ? vm.position : 'top-center'
      vm.title = angular.isDefined(vm.title) ? vm.title : false
      vm.message = angular.isDefined(vm.message) ? vm.message : __('Are you sure you wish to proceed?')
      vm.ok = angular.isDefined(vm.ok) ? vm.ok : 'Ok'
      vm.cancel = angular.isDefined(vm.cancel) ? vm.cancel : __('Cancel')
      vm.onCancel = angular.isDefined(vm.onCancel) ? vm.onCancel : angular.noop
      vm.okClass = angular.isDefined(vm.okStyle) ? 'btn-' + vm.okStyle : ''
      vm.confirmIf = angular.isDefined(vm.confirmIf) ? vm.confirmIf : lodash.constant(true)
      vm.showCancel = angular.isDefined(vm.showCancel) ? vm.showCancel : true
    }

    function onTrigger () {
      var position = getModalPosition()
      var modal

      vm.showItems = false
      vm.useCollapse = angular.isArray(vm.items) && (vm.items.length > vm.collapseItemsThreshold)

      if (vm.confirmIf()) {
        vm.left = position.left
        vm.top = position.top - vm.getOffset()

        modal = $uibModal.open(modalOptions)
        modal.result.then(onOk, onCancel)
      } else {
        vm.onOk()
      }

      function onOk () {
        vm.onOk()
      }

      function onCancel () {
        vm.onCancel()
      }
    }

    // Grafted in from ui.bootstraps $uibPosition.positionElements()
    function getModalPosition () {
      var posParts = vm.position.split('-')
      var pos0 = posParts[0]
      var pos1 = posParts[1] || 'center'
      var hostElPos = vm.getPosition()
      var targetElPos = {}

      var targetElWidth = vm.size.width
      var targetElHeight = vm.size.height

      var shiftWidth = {
        center: widthCenter,
        left: widthLeft,
        right: widthRight
      }

      var shiftHeight = {
        center: heightCenter,
        top: heightTop,
        bottom: heightBottom
      }

      switch (pos0) {
        case 'right':
          targetElPos = {
            top: shiftHeight[pos1](),
            left: shiftWidth[pos0]()
          }
          break
        case 'left':
          targetElPos = {
            top: shiftHeight[pos1](),
            left: hostElPos.left - targetElWidth
          }
          break
        case 'bottom':
          targetElPos = {
            top: shiftHeight[pos0](),
            left: shiftWidth[pos1]()
          }
          break
        default:
          targetElPos = {
            top: hostElPos.top - targetElHeight,
            left: shiftWidth[pos1]()
          }
          break
      }

      return targetElPos

      function widthRight () {
        return hostElPos.left + hostElPos.width
      }

      function widthLeft () {
        return hostElPos.left
      }

      function widthCenter () {
        return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2
      }

      function heightBottom () {
        return hostElPos.top + hostElPos.height
      }

      function heightTop () {
        return hostElPos.top
      }

      function heightCenter () {
        return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2
      }
    }
  }
}


text:
package org.springframework.cloud.context.named;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.aot.AotDetector;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.AnnotationConfigRegistry;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.MapPropertySource;
import org.springframework.util.Assert;

/**
 * Creates a set of child contexts that allows a set of Specifications to define the beans
 * in each child context.
 *
 * Ported from spring-cloud-netflix FeignClientFactory and SpringClientFactory
 *
 * @param <C> specification
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Tommy Karlsson
 * @author Olga Maciaszek-Sharma
 */
public abstract class NamedContextFactory<C extends NamedContextFactory.Specification>
		implements DisposableBean, ApplicationContextAware {

	private final String propertySourceName;

	private final String propertyName;

	private final Map<String, GenericApplicationContext> contexts = new ConcurrentHashMap<>();

	private Map<String, C> configurations = new ConcurrentHashMap<>();

	private ApplicationContext parent;

	private Class<?> defaultConfigType;

	public NamedContextFactory(Class<?> defaultConfigType, String propertySourceName, String propertyName) {
		this.defaultConfigType = defaultConfigType;
		this.propertySourceName = propertySourceName;
		this.propertyName = propertyName;
	}

	@Override
	public void setApplicationContext(ApplicationContext parent) throws BeansException {
		this.parent = parent;
	}

	public ApplicationContext getParent() {
		return parent;
	}

	public void setConfigurations(List<C> configurations) {
		for (C client : configurations) {
			this.configurations.put(client.getName(), client);
		}
	}

	public Set<String> getContextNames() {
		return new HashSet<>(this.contexts.keySet());
	}

	@Override
	public void destroy() {
		Collection<GenericApplicationContext> values = this.contexts.values();
		for (GenericApplicationContext context : values) {
			// This can fail, but it never throws an exception (you see stack traces
			// logged as WARN).
			context.close();
		}
		this.contexts.clear();
	}

	protected GenericApplicationContext getContext(String name) {
		if (!this.contexts.containsKey(name)) {
			synchronized (this.contexts) {
				if (!this.contexts.containsKey(name)) {
					this.contexts.put(name, createContext(name));
				}
			}
		}
		return this.contexts.get(name);
	}

	public void addContext(String contextId, GenericApplicationContext context) {
		Assert.notNull(contextId, "contextId cannot be null.");
		Assert.notNull(context, "context cannot be null.");
		contexts.put(contextId, context);
	}

	public GenericApplicationContext createContext(String name) {
		GenericApplicationContext context = buildContext(name);
		registerBeans(name, context);
		context.refresh();
		return context;
	}

	public void registerBeans(String name, GenericApplicationContext context) {
		Assert.isInstanceOf(AnnotationConfigRegistry.class, context);
		AnnotationConfigRegistry registry = (AnnotationConfigRegistry) context;
		if (this.configurations.containsKey(name)) {
			for (Class<?> configuration : this.configurations.get(name).getConfiguration()) {
				registry.register(configuration);
			}
		}
		for (Map.Entry<String, C> entry : this.configurations.entrySet()) {
			if (entry.getKey().startsWith("default.")) {
				for (Class<?> configuration : entry.getValue().getConfiguration()) {
					registry.register(configuration);
				}
			}
		}
		registry.register(PropertyPlaceholderAutoConfiguration.class, this.defaultConfigType);
	}

	public GenericApplicationContext buildContext(String name) {
		GenericApplicationContext context;
		if (this.parent != null) {
			// jdk11 issue
			// https://github.com/spring-cloud/spring-cloud-netflix/issues/3101
			// https://github.com/spring-cloud/spring-cloud-openfeign/issues/475
			DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
			if (parent instanceof ConfigurableApplicationContext) {
				beanFactory.setBeanClassLoader(
						((ConfigurableApplicationContext) parent).getBeanFactory().getBeanClassLoader());
			}
			else {
				beanFactory.setBeanClassLoader(parent.getClassLoader());
			}
			context = AotDetector.useGeneratedArtifacts() ? new GenericApplicationContext(beanFactory)
					: new AnnotationConfigApplicationContext(beanFactory);
			context.setClassLoader(parent.getClassLoader());
		}
		else {
			context = AotDetector.useGeneratedArtifacts() ? new GenericApplicationContext()
					: new AnnotationConfigApplicationContext();
		}
		context.getEnvironment().getPropertySources().addFirst(
				new MapPropertySource(this.propertySourceName, Collections.singletonMap(this.propertyName, name)));
		if (this.parent != null) {
			// Uses Environment from parent as well as beans
			context.setParent(this.parent);
		}
		context.setDisplayName(generateDisplayName(name));
		return context;
	}

	protected String generateDisplayName(String name) {
		return this.getClass().getSimpleName() + "-" + name;
	}

	public <T> T getInstance(String name, Class<T> type) {
		GenericApplicationContext context = getContext(name);
		try {
			return context.getBean(type);
		}
		catch (NoSuchBeanDefinitionException e) {
			// ignore
		}
		return null;
	}

	public <T> ObjectProvider<T> getLazyProvider(String name, Class<T> type) {
		return new ClientFactoryObjectProvider<>(this, name, type);
	}

	public <T> ObjectProvider<T> getProvider(String name, Class<T> type) {
		GenericApplicationContext context = getContext(name);
		return context.getBeanProvider(type);
	}

	public <T> T getInstance(String name, Class<?> clazz, Class<?>... generics) {
		ResolvableType type = ResolvableType.forClassWithGenerics(clazz, generics);
		return getInstance(name, type);
	}

	@SuppressWarnings("unchecked")
	public <T> T getInstance(String name, ResolvableType type) {
		GenericApplicationContext context = getContext(name);
		String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, type);
		if (beanNames.length > 0) {
			for (String beanName : beanNames) {
				if (context.isTypeMatch(beanName, type)) {
					return (T) context.getBean(beanName);
				}
			}
		}
		return null;
	}

	public <T> Map<String, T> getInstances(String name, Class<T> type) {
		GenericApplicationContext context = getContext(name);

		return BeanFactoryUtils.beansOfTypeIncludingAncestors(context, type);
	}

	public Map<String, C> getConfigurations() {
		return configurations;
	}

	/**
	 * Specification with name and configuration.
	 */
	public interface Specification {

		String getName();

		Class<?>[] getConfiguration();

	}

}


text:
package com.easycodebox.login.shiro.filter;

import org.apache.shiro.util.ThreadContext;

import javax.servlet.*;
import java.io.IOException;
import java.util.Map;

/**
 * 删除{@link ThreadContext}中需要删除的线程变量
 * @author WangXiaoJin
 */
public class ThreadContextFilter implements Filter {

	/**
	 * 标记是否可删除
	 */
	public static final String REMOVABLE_KEY_PREFIX = "REMOVABLE-";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} finally {
			Map<Object, Object> resources = ThreadContext.getResources();
			if (resources != null) {
				for (Object key : resources.keySet()) {
					if (key != null && key instanceof String) {
						if (((String) key).startsWith(REMOVABLE_KEY_PREFIX)) {
							ThreadContext.remove(key);
						}
					}
				}
			}
		}
	}

	@Override
	public void destroy() {

	}

}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('goals', '0147_category_grouping'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='category',
            options={'verbose_name': 'Category', 'permissions': (('view_category', 'Can view Categories'), ('decline_category', 'Can Decline Categories'), ('publish_category', 'Can Publish Categories')), 'ordering': ['grouping', 'order', 'title'], 'verbose_name_plural': 'Categories'},
        ),
        migrations.AlterField(
            model_name='category',
            name='grouping',
            field=models.IntegerField(default=-1, choices=[(-1, 'General'), (0, 'Get ready for college'), (1, 'Succeed in College'), (2, 'Help your student succeed')], blank=True, null=True),
        ),
    ]


text:
#ifndef SpeechRecognitionError_h
#define SpeechRecognitionError_h

#include "modules/EventModules.h"
#include "modules/ModulesExport.h"
#include "modules/speech/SpeechRecognitionErrorInit.h"
#include "wtf/text/WTFString.h"

namespace blink {

class MODULES_EXPORT SpeechRecognitionError final : public Event {
    DEFINE_WRAPPERTYPEINFO();
public:
    enum ErrorCode {
        // FIXME: This is an unspecified error and Chromium should stop using it.
        ErrorCodeOther = 0,

        ErrorCodeNoSpeech = 1,
        ErrorCodeAborted = 2,
        ErrorCodeAudioCapture = 3,
        ErrorCodeNetwork = 4,
        ErrorCodeNotAllowed = 5,
        ErrorCodeServiceNotAllowed = 6,
        ErrorCodeBadGrammar = 7,
        ErrorCodeLanguageNotSupported = 8
    };

    static PassRefPtrWillBeRawPtr<SpeechRecognitionError> create(ErrorCode, const String&);
    static PassRefPtrWillBeRawPtr<SpeechRecognitionError> create();
    static PassRefPtrWillBeRawPtr<SpeechRecognitionError> create(const AtomicString&, const SpeechRecognitionErrorInit&);

    const String& error() { return m_error; }
    const String& message() { return m_message; }

    virtual const AtomicString& interfaceName() const override;

    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        Event::trace(visitor);
    }

private:
    SpeechRecognitionError(const String&, const String&);
    SpeechRecognitionError(const AtomicString&, const SpeechRecognitionErrorInit&);

    String m_error;
    String m_message;
};

} // namespace blink

#endif // SpeechRecognitionError_h


text:
- bunyan@0.20.0
- GH-346 `server.toString()` crashes (Alex Whitman)
- GH-193 support `next('name_of_route')`

## 2.3.4

- GH-343 default to 'identity' for accept-encoding
- GH-342 client support for PATCH
- Pick up spdy@1.4.6 (doesn't ship all the example garbage)

## 2.3.3

- Stop logging client_req in bunyan output
- GH-319 make DTrace optional
- GH-335 Content-Type'd routes not accepting array (Pedro Palazón)

## 2.3.2

- pick up bunyan 0.18.3
- server.address() returning null causes server.url to deref null

## 2.3.1

- GH-335 Content-Type'd routes not correct when only Accept-Extension varies,
         part deux (switch to `negotiator`, drop `mimeparse`).

## 2.3.0

- GH-335 Content-Type'd routes not correct when only Accept-Extension varies
- GH-332 Cache-Control max-age should show minutes (Ben Hutchison)
- GH-329 Wrong values in res.methods on some cases
- GH-327 server.versionedUse('1.2.3', function (req, res, next) {}) (Tim Kuijsten)
- GH-326 non-default origins not working, Chrome requires allow/origin and
         allow users to append to CORS array (John Fieber/Damon Oehlman)
- GH-323 <path>/?<querystring> broken
- GH-322 add `req.route`, which contains the original params for the
         route (Tim Kuijsten)
- GH-312 bodyParser() should return buffers when data is binary (Tim Kuijsten)
- GH-318 Allow use of 'requestBodyOnGet' option in bodyParser (@geebee)

## 2.2.1

- GH-283 broke versioned, typed routes. Fix.
- node-http-signature@0.9.11

## 2.2.0

- GH-316 drop `clone`, and just shallow copy (Trent Mick)
- GH-284 preflight requests not working without access-control-request-headers
- GH-283 versioned routes should use maximum match, not first (Colin O'Brien)
- dtrace probes for restify clients
- node-dtrace-provider@0.2.8
- backoff@2.0.0 and necessary changes

## 2.1.1

- revert to backoff@1.2.0

## 2.1.0

- GH-284 built-in CORS
- GH-290 next.ifError
- GH-291 fix overwriting `options.type` in createJSONClient (Trent Mick)
- GH-297 default document serving in static plugin (Adam Argo)
- GH-299 gzip plugin doesn't play nice with content-length (Ben Hale)
- GH-301 support private keys w/passphrase (Erik Kristensen)
- GH-302 responseTime cleanup
- Move to `node-backoff` and rework retry logic in HttpClient
- Support keep-alive by default in HttpClient

## 2.0.4

- GH-280 req.params cached by router
- RequestCaptureStream should support outputting to multiple streams
- Default uncaughtException handler should check if headers have been sent

## 2.0.2/2.0.3

- GH-278 missing events on route errors
- Undo `RestError` `constructorOpt` from 2.0.1

## 2.0.1

- GH-269 plugin to make curl happy
- RestError not honoring `constructorOpt` from `cause`
- GH-271 bump to dtrace 0.2.6 (fix build on Mountain Lion)

# Legacy Releases

## 1.4.2

- logging typo (Pedro Candel)
- response `beforeSend` event (Paul Bouzakis)

## 1.4.1

- GH-130 Allow restify and express to coexist.
- GH-129 format HttpErrors as well as RestErrors (Domenic Denicola)
- GH-127 add absolute uri to request (Paul Bouzakis)
- GH-124 `req.query` is `undefined` if no query string was sent
- GH-123 Generated DTrace probe names should be valid
- GH-122 Response._writeHead can cause infinite loop (Trent Mick)
- GH-120 Allow server.patch (Paul Bouzakis)
- GH-119 defaultResponseHeaders not settable
- GH-113 document `return next(false)`

## 1.4.0

- GH-116 More friendly error objects (Domenic Denicola)
- GH-115 Client hangs on server "hard kills" (i.e., RST)
- GH-111 JSON parser only works on objects (not arrays)
- GH-110 emit expectContinue (Paul Bouzakis)
- Fix "undefined" log message in string_client.js
- GH-107
  - Go back to hacking up http.prototype for performance reasons
  - Default to keep-alive on for HTTP/1.1 requests
  - Misc fixes after refactoring.
- GH-109 routes not honoring regex flags.
- GH-108 server missing `listening` event.
- Audit logger optionally logs request/response bodies
- Require http-signature@0.9.9/ctype@0.5.0 (node 0.7 compatible)

## 1.3.0

- GH-100 Make DTrace an optional dependency, and stub it out if not found.
- res.link API not allowing sprintf style sets.
- Support for `socketPath` in client API (alternative to url).
- OPTIONS api not returning access-control-allow-methods header (Steve Mason).
- Allow null passwords in HTTP basic auth (Andrew Robinson).
- set `req.files` on multipart file uploads (Andrew Robinson).

## 1.2.0

- Don't rely on instanceof checks for Errors in response.
- Change route.run log level from trace to debug on next(err).
- Add `res.link` API (wrap up sending a Link: response header).
- GH-98 req.secure needs to return a boolean, not an object
- GH-97 Malformed URI results in server crash
- GH-94 leverage `qs` module for object notation in query string.

## 1.1.1

- dependency version bumps
- res.header accepts sprintf-style arguments
- GH-95 Make restify compatible with node-logging (Andrew Robinson)
- GH-93 Minimal port of express pre-conditions (Dominic Barnes)
- GH-92 Make X-Response-Time configurable (Shaun Berryman)
- GH-87 server.listen on port as string (Andrew Sliwinski)

## 1.1.0

- GH-86 Bunyan version bump.
- Conditional Request plugin tests and fixes for some errors (Mike Williams).
- GH-83 pluggable storage engine for throttling, and LRU for default engine.
- GH-77 `server.on('uncaughtException', function (req, res, route, err) {});`
- GH-79 Docs typo(s).

## 1.0.1

- Version bump bunyan to 0.6.4.

## 1.0.0

- Makefile restructure (use Joyent templates)
- GH-20 HttpClient connectTimeout.
- Allow parser plugins to allow "override" params
- Proper handling of Expect: 100
- multipart/form-data plugin
- Added a 'header' event on res.writeHead
- GH-72 Wrong server name in response header on 404/405/...
- RegExp mounts throw a TypeError
- Allow pre handlers to update request url
- try/catch around route running
- Bundled audit logger (via bunyan)
- strict adherence to RFC3986 for URL encoding
- range versioning changed to be an array of explicit versions
- Switch from log4js to [bunyan](https://github.com/trentm/node-bunyan)
- Official version of `ConditionalRequest` plugin (Falco Nogatz)
- order formatters on response such that JSON/text are before custom ones
- RestErrors can use format strings
- date plugin has bad log check

## 1.0.0-rc2

- GH-66 Support for charSets in responses
- GH-65 Initial version of etag plugin (Falco Nogatz)
- GH-68 res.header() can serialize Date objects to RFC1123
- GH-67 Set some default response headers earlier (access-control-*)
- http-client should auto insert the date header
- GH-64 Support for a pre-routing chain
- JsonClient should "upcast" errors to RestErrors if it can
- GH-63 res.send(204) returning a body of 204
- GH-61 Make bodyParser merging into req.params optional
- Make Error objects backwards compatible with older restify (httpCode/restCode)
- GH-57, GH-62 range versioning on server (Diego Torres)
- GH-59 routes with just '/' are returning 404
- DTrace *-done actually firing content-length (was always 0)
- [Issue 56] Support streaming downloads
- Modify server.on('after') to emit the `Route` object, rather than the name.

## 1.0.0-rc1

(Started maintaining this log 21 January 2012. For earlier change information
you'll have to dig into the commit history.)


text:
package p01_weekdays;

public class Main {

	public static void main(String[] args) {

		WeeklyCalendar wc = new WeeklyCalendar();
		wc.addEntry("Friday", "sleep");
		wc.addEntry("Monday", "sport");
		Iterable<WeeklyEntry> schedule = wc.getWeeklySchedule();
		for (WeeklyEntry we : schedule) {
			System.out.println(we);
		}
	}

}


text:
layout: default
cover: 'http://www.abisolutions.org.uk/website/images/ConferencesHR.jpg'
---

Geraldy

            I am a person.

    {% capture currentDate %}{{'now' | date: '%s' }}{% endcapture %}

      {% for post in site.posts  %}

        {% capture blogDate %}{{post.date | date: '%b %-d, %Y' }}{% endcapture %}

        {% if blogDate >= currentDate %}

                 {% if post.cover %}

                          {% endif %}

{{ post.title }}

          by {{ site.title }}  on <time class="published" datetime="">{{ post.date | date: "%b %-d, %Y" }}</time>

        Read More

        {% endif %}

      {% endfor %}

  sparkleattack.github.io