text:
"""
Support for Homematic devices.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/homematic/
"""
import os
import time
import logging
from datetime import timedelta
from functools import partial

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN,
                                 CONF_USERNAME, CONF_PASSWORD, CONF_PLATFORM,
                                 ATTR_ENTITY_ID)
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers import discovery
from homeassistant.config import load_yaml_config_file
from homeassistant.util import Throttle

DOMAIN = 'homematic'
REQUIREMENTS = ["pyhomematic==0.1.14"]

HOMEMATIC = None
HOMEMATIC_LINK_DELAY = 0.5

MIN_TIME_BETWEEN_UPDATE_HUB = timedelta(seconds=300)
MIN_TIME_BETWEEN_UPDATE_VAR = timedelta(seconds=60)

DISCOVER_SWITCHES = 'homematic.switch'
DISCOVER_LIGHTS = 'homematic.light'
DISCOVER_SENSORS = 'homematic.sensor'
DISCOVER_BINARY_SENSORS = 'homematic.binary_sensor'
DISCOVER_COVER = 'homematic.cover'
DISCOVER_CLIMATE = 'homematic.climate'

ATTR_DISCOVER_DEVICES = 'devices'
ATTR_PARAM = 'param'
ATTR_CHANNEL = 'channel'
ATTR_NAME = 'name'
ATTR_ADDRESS = 'address'
ATTR_VALUE = 'value'

EVENT_KEYPRESS = 'homematic.keypress'
EVENT_IMPULSE = 'homematic.impulse'

SERVICE_VIRTUALKEY = 'virtualkey'
SERVICE_SET_VALUE = 'set_value'

HM_DEVICE_TYPES = {
    DISCOVER_SWITCHES: ['Switch', 'SwitchPowermeter'],
    DISCOVER_LIGHTS: ['Dimmer'],
    DISCOVER_SENSORS: ['SwitchPowermeter', 'Motion', 'MotionV2',
                       'RemoteMotion', 'ThermostatWall', 'AreaThermostat',
                       'RotaryHandleSensor', 'WaterSensor', 'PowermeterGas',
                       'LuxSensor', 'WeatherSensor', 'WeatherStation'],
    DISCOVER_CLIMATE: ['Thermostat', 'ThermostatWall', 'MAXThermostat'],
    DISCOVER_BINARY_SENSORS: ['ShutterContact', 'Smoke', 'SmokeV2', 'Motion',
                              'MotionV2', 'RemoteMotion', 'WeatherSensor',
                              'TiltSensor'],
    DISCOVER_COVER: ['Blind']
}

HM_IGNORE_DISCOVERY_NODE = [
    'ACTUAL_TEMPERATURE',
    'ACTUAL_HUMIDITY'
]

HM_ATTRIBUTE_SUPPORT = {
    'LOWBAT': ['Battery', {0: 'High', 1: 'Low'}],
    'ERROR': ['Sabotage', {0: 'No', 1: 'Yes'}],
    'RSSI_DEVICE': ['RSSI', {}],
    'VALVE_STATE': ['Valve', {}],
    'BATTERY_STATE': ['Battery', {}],
    'CONTROL_MODE': ['Mode', {0: 'Auto', 1: 'Manual', 2: 'Away', 3: 'Boost'}],
    'POWER': ['Power', {}],
    'CURRENT': ['Current', {}],
    'VOLTAGE': ['Voltage', {}],
    'WORKING': ['Working', {0: 'No', 1: 'Yes'}],
}

HM_PRESS_EVENTS = [
    'PRESS_SHORT',
    'PRESS_LONG',
    'PRESS_CONT',
    'PRESS_LONG_RELEASE'
]

HM_IMPULSE_EVENTS = [
    'SEQUENCE_OK'
]

_LOGGER = logging.getLogger(__name__)

CONF_RESOLVENAMES_OPTIONS = [
    'metadata',
    'json',
    'xml',
    False
]

CONF_LOCAL_IP = 'local_ip'
CONF_LOCAL_PORT = 'local_port'
CONF_REMOTE_IP = 'remote_ip'
CONF_REMOTE_PORT = 'remote_port'
CONF_RESOLVENAMES = 'resolvenames'
CONF_DELAY = 'delay'
CONF_VARIABLES = 'variables'

DEVICE_SCHEMA = vol.Schema({
    vol.Required(CONF_PLATFORM): "homematic",
    vol.Required(ATTR_NAME): cv.string,
    vol.Required(ATTR_ADDRESS): cv.string,
    vol.Optional(ATTR_CHANNEL, default=1): vol.Coerce(int),
    vol.Optional(ATTR_PARAM): cv.string,
})

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_LOCAL_IP): cv.string,
        vol.Optional(CONF_LOCAL_PORT, default=8943): cv.port,
        vol.Required(CONF_REMOTE_IP): cv.string,
        vol.Optional(CONF_REMOTE_PORT, default=2001): cv.port,
        vol.Optional(CONF_RESOLVENAMES, default=False):
            vol.In(CONF_RESOLVENAMES_OPTIONS),
        vol.Optional(CONF_USERNAME, default="Admin"): cv.string,
        vol.Optional(CONF_PASSWORD, default=""): cv.string,
        vol.Optional(CONF_DELAY, default=0.5): vol.Coerce(float),
        vol.Optional(CONF_VARIABLES, default=False): cv.boolean,
    }),
}, extra=vol.ALLOW_EXTRA)

SCHEMA_SERVICE_VIRTUALKEY = vol.Schema({
    vol.Required(ATTR_ADDRESS): cv.string,
    vol.Required(ATTR_CHANNEL): vol.Coerce(int),
    vol.Required(ATTR_PARAM): cv.string,
})

SCHEMA_SERVICE_SET_VALUE = vol.Schema({
    vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
    vol.Required(ATTR_VALUE): cv.match_all,
})

def virtualkey(hass, address, channel, param):
    """Send virtual keypress to homematic controlller."""
    data = {
        ATTR_ADDRESS: address,
        ATTR_CHANNEL: channel,
        ATTR_PARAM: param,
    }

    hass.services.call(DOMAIN, SERVICE_VIRTUALKEY, data)

def set_value(hass, entity_id, value):
    """Change value of homematic system variable."""
    data = {
        ATTR_ENTITY_ID: entity_id,
        ATTR_VALUE: value,
    }

    hass.services.call(DOMAIN, SERVICE_SET_VALUE, data)

# pylint: disable=unused-argument,too-many-locals
def setup(hass, config):
    """Setup the Homematic component."""
    global HOMEMATIC, HOMEMATIC_LINK_DELAY
    from pyhomematic import HMConnection

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    local_ip = config[DOMAIN].get(CONF_LOCAL_IP)
    local_port = config[DOMAIN].get(CONF_LOCAL_PORT)
    remote_ip = config[DOMAIN].get(CONF_REMOTE_IP)
    remote_port = config[DOMAIN].get(CONF_REMOTE_PORT)
    resolvenames = config[DOMAIN].get(CONF_RESOLVENAMES)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)
    HOMEMATIC_LINK_DELAY = config[DOMAIN].get(CONF_DELAY)
    use_variables = config[DOMAIN].get(CONF_VARIABLES)

    if remote_ip is None or local_ip is None:
        _LOGGER.error("Missing remote CCU/Homegear or local address")
        return False

    # Create server thread
    bound_system_callback = partial(_system_callback_handler, hass, config)
    HOMEMATIC = HMConnection(local=local_ip,
                             localport=local_port,
                             remote=remote_ip,
                             remoteport=remote_port,
                             systemcallback=bound_system_callback,
                             resolvenames=resolvenames,
                             rpcusername=username,
                             rpcpassword=password,
                             interface_id="homeassistant")

    # Start server thread, connect to peer, initialize to receive events
    HOMEMATIC.start()

    # Stops server when Homeassistant is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, HOMEMATIC.stop)
    hass.config.components.append(DOMAIN)

    # regeister homematic services
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN, SERVICE_VIRTUALKEY,
                           _hm_service_virtualkey,
                           descriptions[DOMAIN][SERVICE_VIRTUALKEY],
                           schema=SCHEMA_SERVICE_VIRTUALKEY)

    entities = []

    ##
    # init HM variable
    variables = HOMEMATIC.getAllSystemVariables() if use_variables else {}
    hm_var_store = {}
    if variables is not None:
        for key, value in variables.items():
            varia = HMVariable(key, value)
            hm_var_store.update({key: varia})
            entities.append(varia)

    # add homematic entites
    entities.append(HMHub(hm_var_store, use_variables))
    component.add_entities(entities)

    ##
    # register set_value service if exists variables
    if not variables:
        return True

    def _service_handle_value(service):
        """Set value on homematic variable object."""
        variable_list = component.extract_from_service(service)

        value = service.data[ATTR_VALUE]

        for hm_variable in variable_list:
            hm_variable.hm_set(value)

    hass.services.register(DOMAIN, SERVICE_SET_VALUE,
                           _service_handle_value,
                           descriptions[DOMAIN][SERVICE_SET_VALUE],
                           schema=SCHEMA_SERVICE_SET_VALUE)

    return True

# pylint: disable=too-many-branches
def _system_callback_handler(hass, config, src, *args):
    """Callback handler."""
    if src == 'newDevices':
        _LOGGER.debug("newDevices with: %s", str(args))
        # pylint: disable=unused-variable
        (interface_id, dev_descriptions) = args
        key_dict = {}
        # Get list of all keys of the devices (ignoring channels)
        for dev in dev_descriptions:
            key_dict[dev['ADDRESS'].split(':')[0]] = True

        # Register EVENTS
        # Search all device with a EVENTNODE that include data
        bound_event_callback = partial(_hm_event_handler, hass)
        for dev in key_dict:
            if dev not in HOMEMATIC.devices:
                continue

            hmdevice = HOMEMATIC.devices.get(dev)
            # have events?
            if len(hmdevice.EVENTNODE) > 0:
                _LOGGER.debug("Register Events from %s", dev)
                hmdevice.setEventCallback(callback=bound_event_callback,
                                          bequeath=True)

        # If configuration allows autodetection of devices,
        # all devices not configured are added.
        if key_dict:
            for component_name, discovery_type in (
                    ('switch', DISCOVER_SWITCHES),
                    ('light', DISCOVER_LIGHTS),
                    ('cover', DISCOVER_COVER),
                    ('binary_sensor', DISCOVER_BINARY_SENSORS),
                    ('sensor', DISCOVER_SENSORS),
                    ('climate', DISCOVER_CLIMATE)):
                # Get all devices of a specific type
                found_devices = _get_devices(discovery_type, key_dict)

                # When devices of this type are found
                # they are setup in HA and an event is fired
                if found_devices:
                    # Fire discovery event
                    discovery.load_platform(hass, component_name, DOMAIN, {
                        ATTR_DISCOVER_DEVICES: found_devices
                    }, config)

def _get_devices(device_type, keys):
    """Get the Homematic devices."""
    device_arr = []

    # pylint: disable=too-many-nested-blocks
    for key in keys:
        device = HOMEMATIC.devices[key]
        class_name = device.__class__.__name__
        metadata = {}

        # is class supported by discovery type
        if class_name not in HM_DEVICE_TYPES[device_type]:
            continue

        # Load metadata if needed to generate a param list
        if device_type == DISCOVER_SENSORS:
            metadata.update(device.SENSORNODE)
        elif device_type == DISCOVER_BINARY_SENSORS:
            metadata.update(device.BINARYNODE)

        params = _create_params_list(device, metadata, device_type)
        if params:
            # Generate options for 1...n elements with 1...n params
            for channel in range(1, device.ELEMENT + 1):
                _LOGGER.debug("Handling %s:%i", key, channel)
                if channel in params:
                    for param in params[channel]:
                        name = _create_ha_name(
                            name=device.NAME,
                            channel=channel,
                            param=param
                        )
                        device_dict = {
                            CONF_PLATFORM: "homematic",
                            ATTR_ADDRESS: key,
                            ATTR_NAME: name,
                            ATTR_CHANNEL: channel
                        }
                        if param is not None:
                            device_dict.update({ATTR_PARAM: param})

                        # Add new device
                        try:
                            DEVICE_SCHEMA(device_dict)
                            device_arr.append(device_dict)
                        except vol.MultipleInvalid as err:
                            _LOGGER.error("Invalid device config: %s",
                                          str(err))
                else:
                    _LOGGER.debug("Channel %i not in params", channel)
        else:
            _LOGGER.debug("Got no params for %s", key)
    _LOGGER.debug("%s autodiscovery: %s", device_type, str(device_arr))
    return device_arr

def _create_params_list(hmdevice, metadata, device_type):
    """Create a list from HMDevice with all possible parameters in config."""
    params = {}
    merge = False

    # use merge?
    if device_type in (DISCOVER_SENSORS, DISCOVER_BINARY_SENSORS):
        merge = True

    # Search in sensor and binary metadata per elements
    for channel in range(1, hmdevice.ELEMENT + 1):
        param_chan = []
        for node, meta_chan in metadata.items():
            try:
                # Is this attribute ignored?
                if node in HM_IGNORE_DISCOVERY_NODE:
                    continue
                if meta_chan == 'c' or meta_chan is None:
                    # Only channel linked data
                    param_chan.append(node)
                elif channel == 1:
                    # First channel can have other data channel
                    param_chan.append(node)
            except (TypeError, ValueError):
                _LOGGER.error("Exception generating %s (%s)",
                              hmdevice.ADDRESS, str(metadata))

        # default parameter is merge is off
        if len(param_chan) == 0 and not merge:
            param_chan.append(None)

        # Add to channel
        if len(param_chan) > 0:
            params.update({channel: param_chan})

    _LOGGER.debug("Create param list for %s with: %s", hmdevice.ADDRESS,
                  str(params))
    return params

def _create_ha_name(name, channel, param):
    """Generate a unique object name."""
    # HMDevice is a simple device
    if channel == 1 and param is None:
        return name

    # Has multiple elements/channels
    if channel > 1 and param is None:
        return "{} {}".format(name, channel)

    # With multiple param first elements
    if channel == 1 and param is not None:
        return "{} {}".format(name, param)

    # Multiple param on object with multiple elements
    if channel > 1 and param is not None:
        return "{} {} {}".format(name, channel, param)

def setup_hmdevice_discovery_helper(hmdevicetype, discovery_info,
                                    add_callback_devices):
    """Helper to setup Homematic devices with discovery info."""
    for config in discovery_info[ATTR_DISCOVER_DEVICES]:
        _LOGGER.debug("Add device %s from config: %s",
                      str(hmdevicetype), str(config))

        # create object and add to HA
        new_device = hmdevicetype(config)
        new_device.link_homematic()

        add_callback_devices([new_device])

    return True

def _hm_event_handler(hass, device, caller, attribute, value):
    """Handle all pyhomematic device events."""
    try:
        channel = int(device.split(":")[1])
        address = device.split(":")[0]
        hmdevice = HOMEMATIC.devices.get(address)
    except (TypeError, ValueError):
        _LOGGER.error("Event handling channel convert error!")
        return

    # is not a event?
    if attribute not in hmdevice.EVENTNODE:
        return

    _LOGGER.debug("Event %s for %s channel %i", attribute,
                  hmdevice.NAME, channel)

    # keypress event
    if attribute in HM_PRESS_EVENTS:
        hass.bus.fire(EVENT_KEYPRESS, {
            ATTR_NAME: hmdevice.NAME,
            ATTR_PARAM: attribute,
            ATTR_CHANNEL: channel
        })
        return

    # impulse event
    if attribute in HM_IMPULSE_EVENTS:
        hass.bus.fire(EVENT_KEYPRESS, {
            ATTR_NAME: hmdevice.NAME,
            ATTR_CHANNEL: channel
        })
        return

    _LOGGER.warning("Event is unknown and not forwarded to HA")

def _hm_service_virtualkey(call):
    """Callback for handle virtualkey services."""
    address = call.data.get(ATTR_ADDRESS)
    channel = call.data.get(ATTR_CHANNEL)
    param = call.data.get(ATTR_PARAM)

    if address not in HOMEMATIC.devices:
        _LOGGER.error("%s not found for service virtualkey!", address)
        return
    hmdevice = HOMEMATIC.devices.get(address)

    # if param exists for this device
    if param not in hmdevice.ACTIONNODE:
        _LOGGER.error("%s not datapoint in hm device %s", param, address)
        return

    # channel exists?
    if channel > hmdevice.ELEMENT:
        _LOGGER.error("%i is not a channel in hm device %s", channel, address)
        return

    # call key
    hmdevice.actionNodeData(param, 1, channel)

class HMHub(Entity):
    """The Homematic hub. I.e. CCU2/HomeGear."""

    def __init__(self, variables_store, use_variables=False):
        """Initialize Homematic hub."""
        self._state = STATE_UNKNOWN
        self._store = variables_store
        self._use_variables = use_variables

        self.update()

    @property
    def name(self):
        """Return the name of the device."""
        return 'Homematic'

    @property
    def state(self):
        """Return the state of the entity."""
        return self._state

    @property
    def device_state_attributes(self):
        """Return device specific state attributes."""
        return {}

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return "mdi:gradient"

    @property
    def available(self):
        """Return true if device is available."""
        return True if HOMEMATIC is not None else False

    def update(self):
        """Update Hub data and all HM variables."""
        self._update_hub_state()
        self._update_variables_state()

    @Throttle(MIN_TIME_BETWEEN_UPDATE_HUB)
    def _update_hub_state(self):
        """Retrieve latest state."""
        if HOMEMATIC is None:
            return
        state = HOMEMATIC.getServiceMessages()
        self._state = STATE_UNKNOWN if state is None else len(state)

    @Throttle(MIN_TIME_BETWEEN_UPDATE_VAR)
    def _update_variables_state(self):
        """Retrive all variable data and update hmvariable states."""
        if HOMEMATIC is None or not self._use_variables:
            return
        variables = HOMEMATIC.getAllSystemVariables()
        if variables is not None:
            for key, value in variables.items():
                if key in self._store:
                    self._store.get(key).hm_update(value)

class HMVariable(Entity):
    """The Homematic system variable."""

    def __init__(self, name, state):
        """Initialize Homematic hub."""
        self._state = state
        self._name = name

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def state(self):
        """Return the state of the entity."""
        return self._state

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return "mdi:code-string"

    @property
    def should_poll(self):
        """Return false. Homematic Hub object update variable."""
        return False

    def hm_update(self, value):
        """Update variable over Hub object."""
        if value != self._state:
            self._state = value
            self.update_ha_state()

    def hm_set(self, value):
        """Set variable on homematic controller."""
        if HOMEMATIC is not None:
            if isinstance(self._state, bool):
                value = cv.boolean(value)
            else:
                value = float(value)
            HOMEMATIC.setSystemVariable(self._name, value)
            self._state = value
            self.update_ha_state()

class HMDevice(Entity):
    """The Homematic device base object."""

    # pylint: disable=too-many-instance-attributes
    def __init__(self, config):
        """Initialize a generic Homematic device."""
        self._name = config.get(ATTR_NAME)
        self._address = config.get(ATTR_ADDRESS)
        self._channel = config.get(ATTR_CHANNEL)
        self._state = config.get(ATTR_PARAM)
        self._data = {}
        self._hmdevice = None
        self._connected = False
        self._available = False

        # Set param to uppercase
        if self._state:
            self._state = self._state.upper()

        # Generate name
        if not self._name:
            self._name = _create_ha_name(name=self._address,
                                         channel=self._channel,
                                         param=self._state)

    @property
    def should_poll(self):
        """Return false. Homematic states are pushed by the XML RPC Server."""
        return False

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def assumed_state(self):
        """Return true if unable to access real state of the device."""
        return not self._available

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

    @property
    def device_state_attributes(self):
        """Return device specific state attributes."""
        attr = {}

        # no data available to create
        if not self.available:
            return attr

        # Generate an attributes list
        for node, data in HM_ATTRIBUTE_SUPPORT.items():
            # Is an attributes and exists for this object
            if node in self._data:
                value = data[1].get(self._data[node], self._data[node])
                attr[data[0]] = value

        # static attributes
        attr['ID'] = self._hmdevice.ADDRESS

        return attr

    def link_homematic(self):
        """Connect to Homematic."""
        # device is already linked
        if self._connected:
            return True

        # pyhomematic is loaded
        if HOMEMATIC is None:
            return False

        # Does a HMDevice from pyhomematic exist?
        if self._address in HOMEMATIC.devices:
            # Init
            self._hmdevice = HOMEMATIC.devices[self._address]
            self._connected = True

            # Check if Homematic class is okay for HA class
            _LOGGER.info("Start linking %s to %s", self._address, self._name)
            try:
                # Init datapoints of this object
                self._init_data()
                if HOMEMATIC_LINK_DELAY:
                    # We delay / pause loading of data to avoid overloading
                    # of CCU / Homegear when doing auto detection
                    time.sleep(HOMEMATIC_LINK_DELAY)
                self._load_data_from_hm()
                _LOGGER.debug("%s datastruct: %s", self._name, str(self._data))

                # Link events from pyhomatic
                self._subscribe_homematic_events()
                self._available = not self._hmdevice.UNREACH
                _LOGGER.debug("%s linking done", self._name)
            # pylint: disable=broad-except
            except Exception as err:
                self._connected = False
                _LOGGER.error("Exception while linking %s: %s",
                              self._address, str(err))
        else:
            _LOGGER.debug("%s not found in HOMEMATIC.devices", self._address)

    def _hm_event_callback(self, device, caller, attribute, value):
        """Handle all pyhomematic device events."""
        _LOGGER.debug("%s received event '%s' value: %s", self._name,
                      attribute, value)
        have_change = False

        # Is data needed for this instance?
        if attribute in self._data:
            # Did data change?
            if self._data[attribute] != value:
                self._data[attribute] = value
                have_change = True

        # If available it has changed
        if attribute is 'UNREACH':
            self._available = bool(value)
            have_change = True

        # If it has changed data point, update HA
        if have_change:
            _LOGGER.debug("%s update_ha_state after '%s'", self._name,
                          attribute)
            self.update_ha_state()

    def _subscribe_homematic_events(self):
        """Subscribe all required events to handle job."""
        channels_to_sub = {}

        # Push data to channels_to_sub from hmdevice metadata
        for metadata in (self._hmdevice.SENSORNODE, self._hmdevice.BINARYNODE,
                         self._hmdevice.ATTRIBUTENODE,
                         self._hmdevice.WRITENODE, self._hmdevice.EVENTNODE,
                         self._hmdevice.ACTIONNODE):
            for node, channel in metadata.items():
                # Data is needed for this instance
                if node in self._data:
                    # chan is current channel
                    if channel == 'c' or channel is None:
                        channel = self._channel
                    # Prepare for subscription
                    try:
                        if int(channel) >= 0:
                            channels_to_sub.update({int(channel): True})
                    except (ValueError, TypeError):
                        _LOGGER("Invalid channel in metadata from %s",
                                self._name)

        # Set callbacks
        for channel in channels_to_sub:
            _LOGGER.debug("Subscribe channel %s from %s",
                          str(channel), self._name)
            self._hmdevice.setEventCallback(callback=self._hm_event_callback,
                                            bequeath=False,
                                            channel=channel)

    def _load_data_from_hm(self):
        """Load first value from pyhomematic."""
        if not self._connected:
            return False

        # Read data from pyhomematic
        for metadata, funct in (
                (self._hmdevice.ATTRIBUTENODE,
                 self._hmdevice.getAttributeData),
                (self._hmdevice.WRITENODE, self._hmdevice.getWriteData),
                (self._hmdevice.SENSORNODE, self._hmdevice.getSensorData),
                (self._hmdevice.BINARYNODE, self._hmdevice.getBinaryData)):
            for node in metadata:
                if node in self._data:
                    self._data[node] = funct(name=node, channel=self._channel)

        return True

    def _hm_set_state(self, value):
        """Set data to main datapoint."""
        if self._state in self._data:
            self._data[self._state] = value

    def _hm_get_state(self):
        """Get data from main datapoint."""
        if self._state in self._data:
            return self._data[self._state]
        return None

    def _init_data(self):
        """Generate a data dict (self._data) from the Homematic metadata."""
        # Add all attributes to data dict
        for data_note in self._hmdevice.ATTRIBUTENODE:
            self._data.update({data_note: STATE_UNKNOWN})

        # init device specified data
        self._init_data_struct()

    def _init_data_struct(self):
        """Generate a data dict from the Homematic device metadata."""
        raise NotImplementedError


text:
//Declare an integer variable and assign it with the value 254 in hexadecimal format (0x##).
//Use Windows Calculator to find its hexadecimal representation.
//Print the variable and ensure that the result is 254.

using System;

class VariableInHex
{
    static void Main()
    {
        int num = 0x00FE;

        Console.WriteLine(num);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>Documentation of {{className}}</title>
		<link rel="stylesheet" href="../../../../../styles/dbm/documentation/main.css" />
		<link rel="stylesheet" href="../../../../../styles/dbm/documentation/class.css" />

Dbm documentation

						Index

						<form action="https://www.google.co.uk/cse/publicurl" method="GET">
							<input type="hidden" name="cx" value="006746230495882673940:ilr36kbyhjo" />
							<input type="text" name="q" value="" />
						</form>

Point

dbm.core.data.points.Point

BaseObject

A point.

Subclasses

Class has no subclasses.

Dependencies

VariableAliases

Import code

var Point = dbm.importClass("dbm.core.data.points.Point");

Full code

dbm.registerClass("dbm.core.data.points.Point", "dbm.core.BaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.core.data.points.Point");
	//"use strict";

	//Self reference
	var Point = dbm.importClass("dbm.core.data.points.Point");

	//Error report

	//Dependencies

	//Utils
	var VariableAliases = dbm.importClass("dbm.utils.data.VariableAliases");

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.core.data.points.Point");

		this.superCall();

		this.x = 0;
		this.y = 0;
		this.z = 0;
		this.w = 1;

		return this;
	};

	/**
	 * Sets up the values from the first two values in the array
	 *
	 * @param	aArray	An array containing the x and y value.
	 */
	objectFunctions.setupFromArray = function(aArray) {
		switch(aArray.length) {
			default:
			case 4:
				this.w = aArray[3];
			case 3:
				this.z = aArray[2];
			case 2:
				this.y = aArray[1];
			case 1:
				this.x = aArray[0];
			case 0:
		}
	};

	/**
	 * Duplicates the object without the data flow connections.
	 *
	 * @return	The newly created object.
	 */
	objectFunctions.duplicate = function() {
		var theObject = (new ClassReference()).init();
		theObject.x = this.x;
		theObject.y = this.y;
		theObject.z = this.z;
		theObject.w = this.w;
		return theObject;
	};

	objectFunctions.setValues = function(aX, aY, aZ, aW) {
		//console.log("dbm.core.data.points.Point::setValues");
		//console.log(aX, aY, aZ, aW);
		this.x = VariableAliases.valueWithDefault(aX, 0);
		this.y = VariableAliases.valueWithDefault(aY, 0);
		this.z = VariableAliases.valueWithDefault(aZ, 0);
		this.w = VariableAliases.valueWithDefault(aW, 1);

		return this;
	};

	objectFunctions._toString_getAttributes = function(aReturnArray) {
		this.superCall(aReturnArray);

		aReturnArray.push("x: " + this.x);
		aReturnArray.push("y: " + this.y);
		aReturnArray.push("z: " + this.z);

	};

	staticFunctions.create = function(aX, aY, aZ, aW) {
		//console.log("dbm.core.data.points.Point::create (static)");
		//console.log(aX, aY, aZ, aW);
		var newPoint = ClassReference._createAndInitClass(ClassReference);
		newPoint.setValues(aX, aY, aZ, aW);

		return newPoint;
	};

	staticFunctions.getLengthOfVectorValues2d = function(aX, aY) {
		//console.log("dbm.core.data.points.Point::getLengthOfVectorValues2d (static)");
		//console.log(aX, aY);
		return Math.sqrt(Math.pow(aX, 2)+Math.pow(aY, 2));
	};

	staticFunctions.getLengthOfVectorValues3d = function(aX, aY, aZ) {
		//console.log("dbm.core.data.points.Point::getLengthOfVectorValues3d (static)");
		//console.log(aX, aY, aZ);
		return Math.sqrt(Math.pow(aX, 2)+Math.pow(aY, 2)+Math.pow(aZ, 2));
	};

	staticFunctions.copyPointValues3d = function(aInputPoint, aOutputPoint) {
		//console.log("dbm.core.data.points.Point::copyPointValues3d (static)");
		aOutputPoint.x = aInputPoint.x;
		aOutputPoint.y = aInputPoint.y;
		aOutputPoint.z = aInputPoint.z;
	};

	staticFunctions.adjustPointsArrayLength = function(aArray, aDifference) {
		if(aDifference < 0) {
			aDifference *= -1;
			for(var i = 0; i < aDifference; i++) {
				var currentPoint = aArray.pop();
				currentPoint.destroy();
			}
		}
		else {
			for(var i = 0; i < aDifference; i++) {
				aArray.push(ClassReference.create());
			}
		}
	};

	staticFunctions.setValues3d = function(aPoint, aX, aY, aZ) {
		aPoint.x = aX;
		aPoint.y = aY;
		aPoint.z = aZ;
	};
})

Local variables

Local functions

					_init():self

Constructor

Arguments

Function has no arguments

Return value

Self. Function is linkable.

Full code

objectFunctions._init = function() {
		//console.log("dbm.core.data.points.Point");

		this.superCall();

		this.x = 0;
		this.y = 0;
		this.z = 0;
		this.w = 1;

		return this;
	}

					setupFromArray(aArray):void

Sets up the values from the first two values in the array

Arguments

aArray - An array containing the x and y value.

Return value

Function has no return value.

Full code

objectFunctions.setupFromArray = function(aArray) {
		switch(aArray.length) {
			default:
			case 4:
				this.w = aArray[3];
			case 3:
				this.z = aArray[2];
			case 2:
				this.y = aArray[1];
			case 1:
				this.x = aArray[0];
			case 0:
		}
	}

					duplicate():The newly created object.

Duplicates the object without the data flow connections.

Arguments

Function has no arguments

Return value

The newly created object. - The newly created object.

Full code

objectFunctions.duplicate = function() {
		var theObject = (new ClassReference()).init();
		theObject.x = this.x;
		theObject.y = this.y;
		theObject.z = this.z;
		theObject.w = this.w;
		return theObject;
	}

					setValues(aX, aY, aZ, aW):self

Arguments

aX

aY

aZ

aW

Return value

Self. Function is linkable.

Full code

objectFunctions.setValues = function(aX, aY, aZ, aW) {
		//console.log("dbm.core.data.points.Point::setValues");
		//console.log(aX, aY, aZ, aW);
		this.x = VariableAliases.valueWithDefault(aX, 0);
		this.y = VariableAliases.valueWithDefault(aY, 0);
		this.z = VariableAliases.valueWithDefault(aZ, 0);
		this.w = VariableAliases.valueWithDefault(aW, 1);

		return this;
	}

					_toString_getAttributes(aReturnArray):void

Arguments

aReturnArray

Return value

Function has no return value.

Full code

objectFunctions._toString_getAttributes = function(aReturnArray) {
		this.superCall(aReturnArray);

		aReturnArray.push("x: " + this.x);
		aReturnArray.push("y: " + this.y);
		aReturnArray.push("z: " + this.z);

	}

Static variables

Static functions

					create(aX, aY, aZ, aW):Unknown

Arguments

aX

aY

aZ

aW

Return value

Unknown

Full code

staticFunctions.create = function(aX, aY, aZ, aW) {
		//console.log("dbm.core.data.points.Point::create (static)");
		//console.log(aX, aY, aZ, aW);
		var newPoint = ClassReference._createAndInitClass(ClassReference);
		newPoint.setValues(aX, aY, aZ, aW);

		return newPoint;
	}

					getLengthOfVectorValues2d(aX, aY):Unknown

Arguments

aX

aY

Return value

Unknown

Full code

staticFunctions.getLengthOfVectorValues2d = function(aX, aY) {
		//console.log("dbm.core.data.points.Point::getLengthOfVectorValues2d (static)");
		//console.log(aX, aY);
		return Math.sqrt(Math.pow(aX, 2)+Math.pow(aY, 2));
	}

					getLengthOfVectorValues3d(aX, aY, aZ):Unknown

Arguments

aX

aY

aZ

Return value

Unknown

Full code

staticFunctions.getLengthOfVectorValues3d = function(aX, aY, aZ) {
		//console.log("dbm.core.data.points.Point::getLengthOfVectorValues3d (static)");
		//console.log(aX, aY, aZ);
		return Math.sqrt(Math.pow(aX, 2)+Math.pow(aY, 2)+Math.pow(aZ, 2));
	}

					copyPointValues3d(aInputPoint, aOutputPoint):void

Arguments

aInputPoint

aOutputPoint

Return value

Function has no return value.

Full code

staticFunctions.copyPointValues3d = function(aInputPoint, aOutputPoint) {
		//console.log("dbm.core.data.points.Point::copyPointValues3d (static)");
		aOutputPoint.x = aInputPoint.x;
		aOutputPoint.y = aInputPoint.y;
		aOutputPoint.z = aInputPoint.z;
	}

					adjustPointsArrayLength(aArray, aDifference):void

Arguments

aArray

aDifference

Return value

Function has no return value.

Full code

staticFunctions.adjustPointsArrayLength = function(aArray, aDifference) {
		if(aDifference < 0) {
			aDifference *= -1;
			for(var i = 0; i < aDifference; i++) {
				var currentPoint = aArray.pop();
				currentPoint.destroy();
			}
		}
		else {
			for(var i = 0; i < aDifference; i++) {
				aArray.push(ClassReference.create());
			}
		}
	}

					setValues3d(aPoint, aX, aY, aZ):void

Arguments

aPoint

aX

aY

aZ

Return value

Function has no return value.

Full code

staticFunctions.setValues3d = function(aPoint, aX, aY, aZ) {
		aPoint.x = aX;
		aPoint.y = aY;
		aPoint.z = aZ;
	}

				Documentation exported with dbm.


text:
package xhsun.gw2app.steve.backend.injection.module;

import android.content.Context;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import xhsun.gw2app.steve.backend.data.wrapper.account.AccountDB;
import xhsun.gw2app.steve.backend.data.wrapper.character.CharacterDB;
import xhsun.gw2app.steve.backend.data.wrapper.common.CurrencyDB;
import xhsun.gw2app.steve.backend.data.wrapper.common.ItemDB;
import xhsun.gw2app.steve.backend.data.wrapper.common.MiscDB;
import xhsun.gw2app.steve.backend.data.wrapper.common.SkinDB;
import xhsun.gw2app.steve.backend.data.wrapper.storage.BankDB;
import xhsun.gw2app.steve.backend.data.wrapper.storage.InventoryDB;
import xhsun.gw2app.steve.backend.data.wrapper.storage.MaterialDB;
import xhsun.gw2app.steve.backend.data.wrapper.storage.WardrobeDB;
import xhsun.gw2app.steve.backend.data.wrapper.wallet.WalletDB;

/**
 * Module class for database classes
 *
 * @author xhsun
 * @since 2017-03-29
 */
@Module
public class DatabaseModule {
	private Context context;

	public DatabaseModule(Context context) {
		this.context = context;
	}

	@Provides
	@Singleton
	CurrencyDB providesCurrencyDB() {
		return new CurrencyDB(context);
	}

	@Provides
	@Singleton
	ItemDB providesItemDB() {
		return new ItemDB(context);
	}

	@Provides
	@Singleton
	SkinDB providesSkinDB() {
		return new SkinDB(context);
	}

	@Provides
	@Singleton
	MiscDB providesMiscDB() {
		return new MiscDB(context);
	}

	@Provides
	@Singleton
	AccountDB providesAccountDB() {
		return new AccountDB(context);
	}

	@Provides
	@Singleton
	CharacterDB providesCharacterDB() {
		return new CharacterDB(context);
	}

	@Provides
	@Singleton
	WalletDB providesWalletDB() {
		return new WalletDB(context);
	}

	@Provides
	@Singleton
	InventoryDB providesInventoryDB() {
		return new InventoryDB(context);
	}

	@Provides
	@Singleton
	BankDB providesBankDB() {
		return new BankDB(context);
	}

	@Provides
	@Singleton
	MaterialDB providesMaterialDB() {
		return new MaterialDB(context);
	}

	@Provides
	@Singleton
	WardrobeDB providesWardrobeDB() {
		return new WardrobeDB(context);
	}

}


text:
require 'test_helper'

class PlaceTest < ActiveSupport::TestCase
  %i(one two three four).each do |name|
    test "#{name} is valid" do
      assert places(name).valid?
    end
  end

  test "returns codes" do
    assert_equal 3, Place.codes.length
  end

  test "finds places with ok checks" do
    assert_equal [places(:one)], Place.ok
  end

  test "finds places with not ok checks" do
    assert_equal [places(:two)], Place.not
  end

  test "sets code on validation" do
    place = Place.new url: "http://example.com/"
    place.valid?
    assert_match(/\h{32}/, place.code)
  end

  test "excludes places without telegram" do
    assert Place.all.exclude?(places(:four))
  end

  test "returns checked places" do
    assert_equal 2, Place.checked.count
  end

  test "returns title" do
    assert_equal "010010001_0001", places(:one).title
  end

  test "returns was checked" do
    assert places(:one).checked?
  end

  test "returns was not checked" do
    refute places(:three).checked?
  end

  test "returns pdf url" do
    assert_equal \
      "http://www.resultados.gob.ar/bltgetelegr/01/001/0001/010010001_0001.pdf",
      places(:one).pdf_url
  end

  test "does not return pdf url without telegram" do
    assert_nil places(:four).pdf_url
  end
end


text:
package com.linecorp.armeria.server.metrics;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

import org.junit.Test;

import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.logging.RequestLogListener;

public class RequestLogListenerTest {
    @Test
    public void testComposition() throws Exception {
        // Given
        final int[] executeCounters = { 0 };

        RequestLogListener consumer = log -> executeCounters[0]++;

        RequestLogListener finalConsumer = consumer.andThen(consumer).andThen(consumer);

        // When
        finalConsumer.onRequestLog(mock(RequestLog.class));

        // Then
        assertEquals("onRequestLog() should be invoked 3 times", 3, executeCounters[0]);
    }
}


text:
package com.google.cloud.apigeeregistry.v1.samples;

// [START apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_Apispecname_sync]
import com.google.cloud.apigeeregistry.v1.ApiSpec;
import com.google.cloud.apigeeregistry.v1.ApiSpecName;
import com.google.cloud.apigeeregistry.v1.RegistryClient;

public class SyncDeleteApiSpecRevisionApispecname {

  public static void main(String[] args) throws Exception {
    syncDeleteApiSpecRevisionApispecname();
  }

  public static void syncDeleteApiSpecRevisionApispecname() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RegistryClient registryClient = RegistryClient.create()) {
      ApiSpecName name = ApiSpecName.of("[PROJECT]", "[LOCATION]", "[API]", "[VERSION]", "[SPEC]");
      ApiSpec response = registryClient.deleteApiSpecRevision(name);
    }
  }
}
// [END apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_Apispecname_sync]


text:
using System;
using UnityEngine;

/// <summary>
/// Dewarp is responsible for generating the dewarp meshes
/// used for warp calibration.
///
/// Author: Christoffer A Træen
/// </summary>
public class Dewarp
{
    /// <summary>
    /// Holds the positions for the Dewarp mesh
    /// </summary>
    [Serializable]
    public class DewarpMeshPosition
    {

        [Header("Mesh calibarted vertecies(Do not add extra verts)")]
        public Vector3[] verts;

        /// <summary>
        /// Holds generated vertecies: filled if verts are empty
        /// </summary>
        public Vector3[] generatedVerts;

    };

    /// <summary>
    /// The vertices size on the x axis
    /// </summary>
    public int xSize { get; private set; } = 7;

    /// <summary>
    /// The vertices size on the y axis
    /// </summary>
    public int ySize { get; private set; } = 7;

    /// <summary>
    /// The game object name for the dewarp mesh
    /// </summary>
    private readonly string objectName = "Dewarp Mesh For:";

    /// <summary>
    /// Holds the gameobject reference for the dewarp mesh
    /// </summary>
    private GameObject dewarpObject;

    /// <summary>
    /// Holds the reference to the dewarp mesh
    /// </summary>
    private Mesh warpMesh;

    /// <summary>
    /// Holds the reference to the dewarp mesh filter
    /// </summary>
    private MeshFilter warpMeshFilter;

    /// <summary>
    /// Render materioal
    /// </summary>
    private Material renderMaterial;

    private DewarpMeshPosition _calibratedVerticesPositions;

    /// <summary>
    /// Holds the calibrated dewarp positions
    /// </summary>
    public DewarpMeshPosition CalibratedVerticesPositions
    {
        get { return this._calibratedVerticesPositions; }
        private set
        {
            if (value == null)
            {
                throw new ArgumentException("Vertices positions object cant be null");
            }
            this._calibratedVerticesPositions = value;
        }
    }

    private Material _postProcessMaterial;

    /// <summary>
    /// Holds the Post process material for the mesh.
    /// </summary>
    /// <value></value>
    private Material PostProcessMaterial
    {
        get { return this._postProcessMaterial; }
        set
        {
            if (value == null)
            {
                throw new ArgumentException("Missing postprocess material");
            }
            this._postProcessMaterial = value;
        }
    }

    private RenderTexture _cameraTexture;

    /// <summary>
    /// Holds the Render texture for the render camera
    /// </summary>
    /// <value></value>
    private RenderTexture CameraTexture
    {
        get { return this._cameraTexture; }
        set
        {
            if (value == null)
            {
                throw new ArgumentException("Missing camera texture");
            }
            this._cameraTexture = value;
        }
    }

    /// <summary>
    /// Creates a new dewarp mesh game object, and sets the nessecary dependncies for generation of the mesh.
    ///
    /// /// The dewarp mesh takes a post process material, Dewarp mesh verticies positions and a render texture.
    /// The Post process material can be the UniCave postprocess material which enables edge blending and debugging.
    /// The DewarpMeshPositions is positions of imported verticies from config. So it can generate a mesh based
    /// on your loaded mesh calibration.
    /// The render texture is for the camera displaying this dewarp mesh.
    ///
    /// </summary>
    /// <param name="name">the name of the gameobject</param>
    /// <param name="postProcessMaterial">post process material</param>
    /// <param name="vertices">positions of verticies from calibartion</param>
    /// <param name="cameraTexture">render texture for the camera</param>
    public Dewarp(string name, Material postProcessMaterial, DewarpMeshPosition verticesPositions, RenderTexture cameraTexture)
    {

        dewarpObject = new GameObject(objectName + name);

        this.PostProcessMaterial = postProcessMaterial;
        this.CalibratedVerticesPositions = verticesPositions;
        this.CameraTexture = cameraTexture;
        this.GenerateMesh();
        this.GenerateAndAssignMaterials(name);
    }

    /// <summary>
    /// Sets the resolution of the warp mesh.
    /// The total resolution will be x*y
    /// </summary>
    /// <param name="x">vertices on the x axis</param>
    /// <param name="y">vertices on the y axis</param>
    public void SetMeshResolution(int x = 2, int y = 2)
    {
        if (x < 2) throw new ArgumentException("X must atleast have 2 vertices");
        if (y < 2) throw new ArgumentException("Y must atleast have 2 vertices");
        this.xSize = x;
        this.ySize = y;
    }

    /// <summary>
    /// Generates the dewarp mesh and assign the .
    /// </summary>
    private void GenerateMesh()
    {
        this.warpMeshFilter = dewarpObject.AddComponent<MeshFilter>();
        this.warpMeshFilter.mesh = Generate();
    }

    /// <summary>
    /// Creates the materials and textures for the dewarp mesh
    /// </summary>
    private void GenerateAndAssignMaterials(string nameForMaterial)
    {

        this.renderMaterial = new Material(this._postProcessMaterial);
        this.renderMaterial.name = $"Material for {nameForMaterial}";

        this.renderMaterial.mainTexture = this._cameraTexture;
        this.dewarpObject.AddComponent<MeshRenderer>().material = this.renderMaterial;
    }

    /// <summary>
    /// Sets the layer of where the gameobject should render.
    /// </summary>
    /// <param name="layer">the layer to render on</param>
    public void SetPostprocessLayer(int layer)
    {
        if (!this.dewarpObject) throw new NullReferenceException("Cant set layer, game object is null");
        this.dewarpObject.layer = layer;
    }

    /// <summary>
    /// Generates the dewarp mesh.
    /// The mesh has a total of <c>xSize*ySize</c> vertices.
    /// Normals, tangtents, UVs and triangles are automaticaly generated.
    ///
    /// Vertices starts from bottom left.
    /// </summary>
    /// <returns>returns the generated mesh</returns>
    private Mesh Generate()
    {
        this.warpMesh = new Mesh();
        this.warpMesh.name = "Warp mesh";

        this._calibratedVerticesPositions.generatedVerts = new Vector3[(this.xSize + 1) * (this.ySize + 1)];
        Vector2[] uv = new Vector2[this._calibratedVerticesPositions.generatedVerts.Length];
        Vector4[] tangents = new Vector4[this._calibratedVerticesPositions.generatedVerts.Length];
        Vector4 tangent = new Vector4(1f, 0f, 0f, -1f);

        decimal xx = xSize;
        decimal yy = ySize;

        decimal ymodifier = (2 / yy);
        decimal lastY = -1;

        decimal xmodifier = (2 / xx);
        decimal lastX = -1;

        // Set verices positions and generate uvs and tangents
        for (int i = 0, y = 0; y <= ySize; y++)
        {
            for (int x = 0; x <= xSize; x++, i++)
            {
                if (this._calibratedVerticesPositions.verts.Length == this._calibratedVerticesPositions.generatedVerts.Length)
                {
                    this._calibratedVerticesPositions.generatedVerts[i] = new Vector3((float) this._calibratedVerticesPositions.verts[i].x, (float) this._calibratedVerticesPositions.verts[i].y);
                }
                else
                {
                    this._calibratedVerticesPositions.generatedVerts[i] = new Vector3((float) lastX, (float) lastY);
                }
                uv[i] = new Vector2((float) x / xSize, (float) y / ySize);
                tangents[i] = tangent;
                lastX += (decimal) xmodifier;

            }
            lastY += (decimal) ymodifier;
            lastX = -1;
        }

        // Generates mesh triangles
        int[] triangles = new int[xSize * ySize * 6];
        for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++)
        {
            for (int x = 0; x < xSize; x++, ti += 6, vi++)
            {
                triangles[ti] = vi;
                triangles[ti + 3] = triangles[ti + 2] = vi + 1;
                triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
                triangles[ti + 5] = vi + xSize + 2;
            }
        }
        this.warpMesh.vertices = this._calibratedVerticesPositions.generatedVerts;
        this.warpMesh.triangles = triangles;
        this.warpMesh.uv = uv;
        this.warpMesh.tangents = tangents;
        this.warpMesh.RecalculateNormals();
        this.warpMesh.RecalculateTangents();
        if (this._calibratedVerticesPositions.verts.Length == 0)
        {
            this._calibratedVerticesPositions.verts = this._calibratedVerticesPositions.generatedVerts;
        }

        return this.warpMesh;

    }

    /// <summary>
    /// Returns the GameObject for the dewarp mesh
    /// </summary>
    /// <returns>GameObject for the dewarp mesh</returns>
    public GameObject GetDewarpGameObject()
    {
        return this.dewarpObject;
    }

    /// <summary>
    /// Returns the Dewarp mesh
    /// </summary>
    /// <returns>reference of the warp mesh</returns>
    public Mesh GetDewarpMesh()
    {
        return this.warpMesh;
    }

    /// <summary>
    /// Returns the Dewarp mesh filter
    /// </summary>
    /// <returns>reference of the warp mesh filter </returns>
    public MeshFilter GetDewarpMeshFilter()
    {
        return this.warpMeshFilter;
    }

}


text:
"""groupby procedure for recipes"""

import fnmatch
import logging

from typing import List

from .. helpers import debuggable, mkfunc
from .. model.ingredient import DataPointIngredient
from .. model.chef import Chef

logger = logging.getLogger('groupby')

@debuggable
def groupby(chef: Chef, ingredients: List[DataPointIngredient], result, **options) -> DataPointIngredient:
    """group ingredient data by column(s) and run aggregate function

    .. highlight:: yaml

    Procedure format:

    ::

       procedure: groupby
       ingredients:  # list of ingredient id
         - ingredient_id
       result: str  # new ingredient id
       options:
         groupby: str or list  # column(s) to group
         aggregate: dict  # function block
         transform: dict  # function block
         filter: dict  # function block

    The function block should have below format:

    ::

      aggregate:
        column1: func_name1
        column2: func_name2

    or

    ::

        aggrgrate:
          column1:
            function: func_name
            param1: foo
            param2: baz

    wildcard is supported in the column names. So ``aggreagte: {"*": "sum"}`` will run on every indicator in
    the ingredient

    Keyword Args
    ------------
    groupby : `str` or `list`
        the column(s) to group, can be a list or a string
    insert_key : `dict`
        manually insert keys in to result. This is useful when we want to add back the
        aggregated column and set them to one value. For example ``geo: global`` inserts
        the ``geo`` column with all values are "global"
    aggregate
    transform
    filter : `dict`, optinoal
        the function to run. only one of `aggregate`, `transform` and `filter` should be supplied.

    Note
    ----
    - Only one of ``aggregate``, ``transform`` or ``filter`` can be used in one procedure.
    - Any columns not mentioned in groupby or functions are dropped.
    """
    assert len(ingredients) == 1, "procedure only support 1 ingredient for now."

    # ingredient = chef.dag.get_node(ingredients[0]).evaluate()
    ingredient = ingredients[0]
    logger.info("groupby: " + ingredient.id)
    data = ingredient.get_data()
    by = options.pop('groupby')
    if 'insert_key' in options:
        insert_key = options.pop('insert_key')
    else:
        insert_key = dict()

    # only one of aggregate/transform/filter should be in options.
    assert len(list(options.keys())) == 1
    comp_type = list(options.keys())[0]
    assert comp_type in ['aggregate', 'transform', 'filter']

    if comp_type == 'aggregate':  # only aggregate should change the key of ingredient
        if isinstance(by, list):
            newkey = ','.join(by)
        else:
            newkey = by
            by = [by]
        logger.debug("changing the key to: " + str(newkey))
    else:
        newkey = ingredient.key
        by = [by]

    newdata = dict()

    for name_tmpl, func in options[comp_type].items():
        func = mkfunc(func)
        indicator_names = fnmatch.filter(data.keys(), name_tmpl)
        for k in indicator_names:
            df = data[k].compute()
            if comp_type == 'aggregate':
                newdata[k] = (df.groupby(by=by).agg({k: func})
                              .reset_index().dropna())
            if comp_type == 'transform':
                df = df.set_index(ingredient.key)
                levels = [df.index.names.index(x) for x in by]
                newdata[k] = (df.groupby(level=levels)[k].transform(func)
                              .reset_index().dropna())
            if comp_type == 'filter':
                df = df.set_index(ingredient.key)
                levels = [df.index.names.index(x) for x in by]
                newdata[k] = (df.groupby(level=levels)[k].filter(func)
                              .reset_index().dropna())
            for col, val in insert_key.items():
                newdata[k][col] = val
                newkey = newkey + ',' + col

    return DataPointIngredient.from_procedure_result(result, newkey, data_computed=newdata)


text:
//========= Copyright Valve Corporation ============//
#include "pathtools.h"
//#include "hmdplatform_private.h"
//#include "vrcommon/strtools.h"

#if defined( _WIN32)
#include <Windows.h>
#include <direct.h>
#include <Shobjidl.h>
#include <KnownFolders.h>
#elif defined OSX
#include <mach-o/dyld.h>
#include <dlfcn.h>
#include "osxfilebridge.h"
#define _S_IFDIR S_IFDIR     // really from tier0/platform.h which we dont have yet
#define _MAX_PATH MAX_PATH   // yet another form of _PATH define we use
#elif defined(__linux__)
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#endif

#include <sys/stat.h>

#include <algorithm>

//TODO: proper linux compatibility
#ifdef __linux__
#include <shared/linuxcompathack.h>
#endif

/** Returns the path (including filename) to the current executable */
std::string Path_GetExecutablePath()
{
	bool bSuccess = false;
	char rchPath[ 1024 ];
	size_t nBuff = sizeof(rchPath);
#if defined( _WIN32 )
	bSuccess = ::GetModuleFileNameA(NULL, rchPath, (DWORD)nBuff) > 0;
#elif defined OSX
	uint32_t _nBuff = nBuff;
	bSuccess = _NSGetExecutablePath(rchPath, &_nBuff) == 0;
	rchPath[nBuff-1] = '\0';
#elif defined __linux__
	ssize_t nRead = readlink("/proc/self/exe", rchPath, nBuff-1 );
	if ( nRead != -1 )
	{
		rchPath[ nRead ] = 0;
		bSuccess = true;
	}
	else
	{
		rchPath[ 0 ] = '\0';
	}
#else
	AssertMsg( false, "Implement Plat_GetExecutablePath" );
#endif

	if( bSuccess )
		return rchPath;
	else
		return "";
}

/** Returns the path of the current working directory */
std::string Path_GetWorkingDirectory()
{
	std::string sPath;
	char buf[ 1024 ];
#if defined( _WIN32 )
	sPath = _getcwd( buf, sizeof( buf ) );
#else
	sPath = getcwd( buf, sizeof( buf ) );
#endif
	return sPath;
}

/** Sets the path of the current working directory. Returns true if this was successful. */
bool Path_SetWorkingDirectory( const std::string & sPath )
{
	bool bSuccess;
#if defined( _WIN32 )
	bSuccess = 0 == _chdir( sPath.c_str() );
#else
	bSuccess = 0 == chdir( sPath.c_str() );
#endif
	return bSuccess;
}

std::string Path_GetModulePath()
{
#if defined( _WIN32 )
	char path[32768];
	HMODULE hm = NULL;

	if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
		(LPCSTR) &Path_GetModulePath,
		&hm))
	{
		int ret = GetLastError();
		fprintf(stderr, "GetModuleHandle returned %d\n", ret);
		return "";
	}
	GetModuleFileNameA(hm, path, sizeof(path));
	FreeLibrary( hm );
	return path;
#else
	Dl_info dl_info;
	dladdr((void *)Path_GetModulePath, &dl_info);
	return dl_info.dli_fname;
#endif
}

/** Returns the specified path without its filename */
std::string Path_StripFilename( const std::string & sPath, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	std::string::size_type n = sPath.find_last_of( slash );
	if( n == std::string::npos )
		return sPath;
	else
		return std::string( sPath.begin(), sPath.begin() + n );
}

/** returns just the filename from the provided full or relative path. */
std::string Path_StripDirectory( const std::string & sPath, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	std::string::size_type n = sPath.find_last_of( slash );
	if( n == std::string::npos )
		return sPath;
	else
		return std::string( sPath.begin() + n + 1, sPath.end() );
}

/** returns just the filename with no extension of the provided filename.
* If there is a path the path is left intact. */
std::string Path_StripExtension( const std::string & sPath )
{
	for( std::string::const_reverse_iterator i = sPath.rbegin(); i != sPath.rend(); i++ )
	{
		if( *i == '.' )
		{
			return std::string( sPath.begin(), i.base() - 1 );
		}

		// if we find a slash there is no extension
		if( *i == '\\' || *i == '/' )
			break;
	}

	// we didn't find an extension
	return sPath;
}

bool Path_IsAbsolute( const std::string & sPath )
{
	if( sPath.empty() )
		return false;

	if( sPath.find( ':' ) != std::string::npos )
		return true;

	if( sPath[0] == '\\' || sPath[0] == '/' )
		return true;

	return false;
}

/** Makes an absolute path from a relative path and a base path */
std::string Path_MakeAbsolute( const std::string & sRelativePath, const std::string & sBasePath, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	if( Path_IsAbsolute( sRelativePath ) )
		return sRelativePath;
	else
	{
		if( !Path_IsAbsolute( sBasePath ) )
			return "";

		std::string sCompacted = Path_Compact( Path_Join( sBasePath, sRelativePath, slash ), slash );
		if( Path_IsAbsolute( sCompacted ) )
			return sCompacted;
		else
			return "";
	}
}

/** Fixes the directory separators for the current platform */
std::string Path_FixSlashes( const std::string & sPath, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	std::string sFixed = sPath;
	for( std::string::iterator i = sFixed.begin(); i != sFixed.end(); i++ )
	{
		if( *i == '/' || *i == '\\' )
			*i = slash;
	}

	return sFixed;
}

char Path_GetSlash()
{
#if defined(_WIN32)
	return '\\';
#else
	return '/';
#endif
}

/** Jams two paths together with the right kind of slash */
std::string Path_Join( const std::string & first, const std::string & second, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	// only insert a slash if we don't already have one
	std::string::size_type nLen = first.length();
#if defined(_WIN32)
	if( first.back() == '\\' || first.back() == '/' )
	    nLen--;
#else
	char last_char = first[first.length()-1];
	if (last_char == '\\' || last_char == '/')
	    nLen--;
#endif

	return first.substr( 0, nLen ) + std::string( 1, slash ) + second;
}

std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, char slash )
{
	return Path_Join( Path_Join( first, second, slash ), third, slash );
}

std::string Path_Join( const std::string & first, const std::string & second, const std::string & third, const std::string &fourth, char slash )
{
	return Path_Join( Path_Join( Path_Join( first, second, slash ), third, slash ), fourth, slash );
}

std::string Path_Join(
	const std::string & first,
	const std::string & second,
	const std::string & third,
	const std::string & fourth,
	const std::string & fifth,
	char slash )
{
	return Path_Join( Path_Join( Path_Join( Path_Join( first, second, slash ), third, slash ), fourth, slash ), fifth, slash );
}

/** Removes redundant <dir>/.. elements in the path. Returns an empty path if the
* specified path has a broken number of directories for its number of ..s */
std::string Path_Compact( const std::string & sRawPath, char slash )
{
	if( slash == 0 )
		slash = Path_GetSlash();

	std::string sPath = Path_FixSlashes( sRawPath, slash );
	std::string sSlashString( 1, slash );

	// strip out all /./
	for( std::string::size_type i = 0; (i + 3) < sPath.length();  )
	{
		if( sPath[ i ] == slash && sPath[ i+1 ] == '.' && sPath[ i+2 ] == slash )
		{
			sPath.replace( i, 3, sSlashString );
		}
		else
		{
			++i;
		}
	}

	// get rid of trailing /. but leave the path separator
	if( sPath.length() > 2 )
	{
		std::string::size_type len = sPath.length();
		if( sPath[ len-1 ] == '.'  && sPath[ len-2 ] == slash )
		{
		  // sPath.pop_back();
		  sPath[len-1] = 0;  // for now, at least
		}
	}

	// get rid of leading ./
	if( sPath.length() > 2 )
	{
		if( sPath[ 0 ] == '.'  && sPath[ 1 ] == slash )
		{
			sPath.replace( 0, 2, "" );
		}
	}

	// each time we encounter .. back up until we've found the previous directory name
	// then get rid of both
	std::string::size_type i = 0;
	while( i < sPath.length() )
	{
		if( i > 0 && sPath.length() - i >= 2
			&& sPath[i] == '.'
			&& sPath[i+1] == '.'
			&& ( i + 2 == sPath.length() || sPath[ i+2 ] == slash )
			&& sPath[ i-1 ] == slash )
		{
			// check if we've hit the start of the string and have a bogus path
			if( i == 1 )
				return "";

			// find the separator before i-1
			std::string::size_type iDirStart = i-2;
			while( iDirStart > 0 && sPath[ iDirStart - 1 ] != slash )
				--iDirStart;

			// remove everything from iDirStart to i+2
			sPath.replace( iDirStart, (i - iDirStart) + 3, "" );

			// start over
			i = 0;
		}
		else
		{
			++i;
		}
	}

	return sPath;
}

#define MAX_UNICODE_PATH			32768
#define MAX_UNICODE_PATH_IN_UTF8	( MAX_UNICODE_PATH * 4 )

/** Returns the path to the current DLL or exe */
std::string GetThisModulePath()
{
	// gets the path of vrclient.dll itself
#ifdef WIN32
	HMODULE hmodule = NULL;

	::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCTSTR>(GetThisModulePath), &hmodule);

	wchar_t *pwchPath = new wchar_t[MAX_UNICODE_PATH];
	char *pchPath = new char[ MAX_UNICODE_PATH_IN_UTF8 ];
	::GetModuleFileNameW( hmodule, pwchPath, MAX_UNICODE_PATH );
	WideCharToMultiByte( CP_UTF8, 0, pwchPath, -1, pchPath, MAX_UNICODE_PATH_IN_UTF8, NULL, NULL );
	delete[] pwchPath;

	std::string sPath = pchPath;
	delete [] pchPath;
	return sPath;

#elif defined( OSX ) || defined( __linux__ )
	// get the addr of a function in vrclient.so and then ask the dlopen system about it
	Dl_info info;
	dladdr( (void *)GetThisModulePath, &info );
	return info.dli_fname;
#endif

}

/** returns true if the specified path exists and is a directory */
bool Path_IsDirectory( const std::string & sPath )
{
	std::string sFixedPath = Path_FixSlashes( sPath );
	if( sFixedPath.empty() )
		return false;
	char cLast = sFixedPath[ sFixedPath.length() - 1 ];
	if( cLast == '/' || cLast == '\\' )
		sFixedPath.erase( sFixedPath.end() - 1, sFixedPath.end() );

	// see if the specified path actually exists.
	struct	stat	buf;
	if ( stat ( sFixedPath.c_str(), &buf ) == -1)
	{
		return false;
	}

#if defined(__linux__)
	return S_ISDIR( buf.st_mode );
#else
	return ( buf.st_mode & _S_IFDIR ) != 0;
#endif
}

//-----------------------------------------------------------------------------
// Purpose: returns true if the the path exists
//-----------------------------------------------------------------------------
bool Path_Exists( const std::string & sPath )
{
	std::string sFixedPath = Path_FixSlashes( sPath );
	if( sFixedPath.empty() )
		return false;

	struct stat buf;
	if ( stat ( sFixedPath.c_str(), &buf ) == -1)
	{
		return false;
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: helper to find a directory upstream from a given path
//-----------------------------------------------------------------------------
std::string Path_FindParentDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName )
{
	std::string strFoundPath = "";
	std::string strCurrentPath = Path_FixSlashes( strStartDirectory );
	if ( strCurrentPath.length() == 0 )
		return "";

	bool bExists = Path_Exists( strCurrentPath );
	std::string strCurrentDirectoryName = Path_StripDirectory( strCurrentPath );
	if ( bExists && stricmp( strCurrentDirectoryName.c_str(), strDirectoryName.c_str() ) == 0 )
		return strCurrentPath;

	while( bExists && strCurrentPath.length() != 0 )
	{
		strCurrentPath = Path_StripFilename( strCurrentPath );
		strCurrentDirectoryName = Path_StripDirectory( strCurrentPath );
		bExists = Path_Exists( strCurrentPath );
		if ( bExists && stricmp( strCurrentDirectoryName.c_str(), strDirectoryName.c_str() ) == 0 )
			return strCurrentPath;
	}

	return "";
}

//-----------------------------------------------------------------------------
// Purpose: helper to find a subdirectory upstream from a given path
//-----------------------------------------------------------------------------
std::string Path_FindParentSubDirectoryRecursively( const std::string &strStartDirectory, const std::string &strDirectoryName )
{
	std::string strFoundPath = "";
	std::string strCurrentPath = Path_FixSlashes( strStartDirectory );
	if ( strCurrentPath.length() == 0 )
		return "";

	bool bExists = Path_Exists( strCurrentPath );
	while( bExists && strCurrentPath.length() != 0 )
	{
		strCurrentPath = Path_StripFilename( strCurrentPath );
		bExists = Path_Exists( strCurrentPath );

		if( Path_Exists( Path_Join( strCurrentPath, strDirectoryName ) ) )
		{
			strFoundPath = Path_Join( strCurrentPath, strDirectoryName );
			break;
		}
	}
	return strFoundPath;
}

//-----------------------------------------------------------------------------
// Purpose: reading and writing files in the vortex directory
//-----------------------------------------------------------------------------
unsigned char * Path_ReadBinaryFile( const std::string &strFilename, int *pSize )
{
	FILE *f;
#if defined( POSIX )
	f = fopen( strFilename.c_str(), "rb" );
#else
	errno_t err = fopen_s(&f, strFilename.c_str(), "rb");
	if ( err != 0 )
	{
		f = NULL;
	}
#endif

	unsigned char* buf = NULL;

	if ( f != NULL )
	{
		fseek(f, 0, SEEK_END);
		int size = ftell(f);
		fseek(f, 0, SEEK_SET);

		buf = new unsigned char[size];
		if (buf && fread(buf, size, 1, f) == 1)
		{
			if (pSize)
				*pSize = size;
		}
		else
		{
			delete[] buf;
			buf = 0;
		}

		fclose(f);
	}

	return buf;
}

std::string Path_ReadTextFile( const std::string &strFilename )
{
	// doing it this way seems backwards, but I don't
	// see an easy way to do this with C/C++ style IO
	// that isn't worse...
	int size;
	unsigned char* buf = Path_ReadBinaryFile( strFilename, &size );
	if (!buf)
		return "";

	// convert CRLF -> LF
	int outsize = 1;
	for (int i=1; i < size; i++)
	{
		if (buf[i] == '\n' && buf[i-1] == '\r') // CRLF
			buf[outsize-1] = '\n'; // ->LF
		else
			buf[outsize++] = buf[i]; // just copy
	}

	std::string ret((char *)buf, (char *)(buf + outsize));
	delete[] buf;
	return ret;
}

bool Path_WriteStringToTextFile( const std::string &strFilename, const char *pchData )
{
	FILE *f;
#if defined( POSIX )
	f = fopen( strFilename.c_str(), "w" );
#else
	errno_t err = fopen_s(&f, strFilename.c_str(), "w");
	if ( err != 0 )
	{
		f = NULL;
	}
#endif

	bool ok = false;

	if ( f != NULL )
	{
		ok = fputs( pchData, f) >= 0;
		fclose(f);
	}

	return ok;
}


text:
package com.todoapp.todo;

import com.todoapp.cache.MapCacheContainer;
import com.todoapp.logging.Log;
import com.todoapp.startup.ApplicationStartupEvent;

import java.time.Instant;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.IntStream;

import javax.ejb.Stateless;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

@Stateless
public class TodoItems {

  @Inject
  Log log;

  @Inject
  MapCacheContainer<String, TodoItem> cacheMap;

  /**
   * Automatically inserts sample todo items when application starts.
   *
   * @param applicationStartupEvent - the event when application is started
   */
  public void createSampleTodoItems(@Observes ApplicationStartupEvent applicationStartupEvent) {
    log.info("Creating sample todo items...");
    IntStream.rangeClosed(1, 5).forEach(this::createRandomTodoItem);
    log.info("Sample todo items created.");
  }

  private void createRandomTodoItem(int item) {
    TodoItem todoItem = createTodoItem("new item " + item, item % 2 == 0);
    log.info("Created sample todo item {0}: {1}", item, todoItem);
  }

  /**
   * Creates a todo item with given title and completion and insert it to the application cache.
   *
   * @param title - a title for the todo item
   * @param completed - completed status for the todo item
   * @return - todo item
   */
  public TodoItem createTodoItem(String title, boolean completed) {
    TodoItem createdTodoItem = new TodoItem.Builder()
        .id(TodoItemId.generate())
        .created(Instant.now().toEpochMilli())
        .completed(completed)
        .title(title)
        .build();
    cacheMap.put(createdTodoItem.getId(), createdTodoItem);
    return createdTodoItem;
  }

  public Collection<TodoItem> getAllTodoItems() {
    return cacheMap.values();
  }

  public Optional<TodoItem> getTodoItem(String todoItemId) {
    return Optional.ofNullable(cacheMap.get(todoItemId));
  }

  /**
   * Removes the todo item by provided id.
   *
   * @param todoItemId - id of a todo item that needs to be removed
   * @return - the removed todo item or empty optional if todo item not found
   */
  public Optional<TodoItem> deleteTodoItem(String todoItemId) {
    return Optional.ofNullable(cacheMap.remove(todoItemId));
  }

  /**
   * Updates a toodo item based on provided id, title and completion status.
   *
   * @param todoItemId - id of an todo item that needs to be updated
   * @param title - an title f
   * @param completed - completion status
   * @return updated todo item or empty optional if todo item not found
   */
  public Optional<TodoItem> updateTodoItem(String todoItemId, String title, boolean completed) {
    Optional<TodoItem> todoItemOptional = Optional.ofNullable(this.cacheMap.get(todoItemId));

    if (todoItemOptional.isPresent()) {
      TodoItem storedTodoItem = todoItemOptional.get();
      storedTodoItem.setCompleted(completed);
      storedTodoItem.setTitle(title);
      return Optional.of(storedTodoItem);
    }

    return todoItemOptional;
  }

}


text:
var map;
//map = new google.maps.Map(document.getElementById('map-overlay'), mapOptions);

var LUND = new google.maps.LatLng(55.7038997,13.1935328);
var LUSEM = new google.maps.LatLng(55.710581,13.213371);
var STATION = new google.maps.LatLng(55.7068014,13.197996);
var TORGET = new google.maps.LatLng(55.7030733,13.1932168);
var HOSPITAL = new google.maps.LatLng(55.7117458,13.1985968);

var current_location;

var latitude;
var longitude;
var accuracy;

var geolocation0;
var geolocation1;
var geolocation2;
var geolocation3;
var geolocation4;
var geolocation5;
var geolocation6;
var geolocation7;

var geocoder;

var battery;

function checkBattery() {

	document.getElementById("batterycharging").innerHTML = battery.charging;
	document.getElementById("batterylevel").innerHTML = battery.level;
	document.getElementById("batterysupported").innerHTML = "Battery API is supported.";

}

function renderMap() {
	//Map rendering

  	var mapOptions = {
    	zoom: 14,
    	center: LUND,
    	mapTypeId: google.maps.MapTypeId.HYBRID
  	};

  	map = new google.maps.Map(document.getElementById('map-overlay'), mapOptions);

	/*
  	map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');

	var marker1 = new google.maps.Marker({
    	map:map,
    	draggable:true,
    	animation: google.maps.Animation.DROP,
    	position: LUND,
		title:"Lund Municipality"
  	});

  	var marker2 = new google.maps.Marker({
    	map:map,
    	draggable:true,
    	animation: google.maps.Animation.DROP,
    	position: LUSEM,
		title:"Hello World!"
  	});

  	var marker3 = new google.maps.Marker({
    	map:map,
    	draggable:true,
    	animation: google.maps.Animation.DROP,
    	position: STATION,
		title:"Hello World!"
  	});

  	var marker4 = new google.maps.Marker({
    	map:map,
    	draggable:true,
    	animation: google.maps.Animation.DROP,
    	position: TORGET,
		title:"Hello World!"
  	});

  	var marker5 = new google.maps.Marker({
    	map:map,
    	draggable:true,
    	animation: google.maps.Animation.DROP,
    	position: HOSPITAL,
		title:"Hello World!"
  	});

  	var currentMarker = new google.maps.Marker({
    	map:map,
    	draggable:false,
    	animation: google.maps.Animation.DROP,
    	position: current_location,
		title:"CURRENT LOCATION!"
  	});

  	var trafficLayer = new google.maps.TrafficLayer();
  	trafficLayer.setMap(map);

  	var bikeLayer = new google.maps.BicyclingLayer();
  	bikeLayer.setMap(map);

  	var transitLayer = new google.maps.TransitLayer();
  	transitLayer.setMap(map);

  	var contentString = '
'+
      '
'+
      '
'+
      '
Uluru
'+
      '
'+
      '
Lund Municipality - Wolcome to Lund Municipality
'+
      '
'+
      '
';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  google.maps.event.addListener(marker1, 'click', function() {
    infowindow.open(map,marker1);
  });
  infowindow.open(map,marker1);

	// To add the marker to the map, call setMap();
	//marker.setMap(map);

	google.maps.event.addListener(marker1, 'click', toggleBounce);

	var heatMapData = [
 		{location: new google.maps.LatLng(55.712,13.185328), weight: 0.5}, new google.maps.LatLng(55.7038993,13.1935377),
   		{location: new google.maps.LatLng(55.709,13.183532), weight: 2},
  		{location: new google.maps.LatLng(55.71899,13.19328), weight: 3},
		{location: new google.maps.LatLng(55.729,13.203532), weight: 2}, new google.maps.LatLng(55.703892,13.1935666),
  		{location: new google.maps.LatLng(55.71,13.2035328), weight: 0.5},
  		{location: new google.maps.LatLng(55.717,13.213532), weight: 3},
  		{location: new google.maps.LatLng(55.697,13.2135328), weight: 2}, new google.maps.LatLng(55.703896,13.193588),
  		{location: new google.maps.LatLng(55.6989,13.21), weight: 0.5}, new google.maps.LatLng(55.703847,13.19355),
	  	{location: new google.maps.LatLng(55.699,13.2035328), weight: 2},
	  	{location: new google.maps.LatLng(55.7,13.2033532), weight: 3}
	];

	var heatmap = new google.maps.visualization.HeatmapLayer({
	  data: heatMapData
	});
	heatmap.setMap(map);
	*/
}

function GetLocation(location) {

	geocoder = new google.maps.Geocoder();

    latitude = location.coords.latitude;
    longitude = location.coords.longitude;
    accuracy = location.coords.accuracy;

    //alert("Latitude: "+latitude);
    //alert("Longitude: "+longitude);
    //alert("Accuracy: "+accuracy);

	current_location = new google.maps.LatLng(latitude,longitude);
	geocoder.geocode({'latLng': current_location}, function(results, status)  {

      if (status == google.maps.GeocoderStatus.OK) {

      	geolocation0 = results[0].formatted_address;
      	geolocation1 = results[1].formatted_address;
      	geolocation2 = results[2].formatted_address;
      	geolocation3 = results[3].formatted_address;
      	geolocation4 = results[4].formatted_address;
      	geolocation5 = results[5].formatted_address;
      	geolocation6 = results[6].formatted_address;
      	geolocation7 = results[7].formatted_address;

		if (document.getElementById("geolocation0")) {
			document.getElementById("geolocation0").innerHTML = geolocation0;
			document.getElementById("geolocation1").innerHTML = geolocation1;
			document.getElementById("geolocation2").innerHTML = geolocation2;
			document.getElementById("geolocation3").innerHTML = geolocation3;
			document.getElementById("geolocation4").innerHTML = geolocation4;
			document.getElementById("geolocation5").innerHTML = geolocation5;
			document.getElementById("geolocation6").innerHTML = geolocation6;
			document.getElementById("geolocation7").innerHTML = geolocation7;

			document.getElementById("latitude").innerHTML = latitude;
			document.getElementById("longitude").innerHTML = longitude;
			document.getElementById("accuracy").innerHTML = accuracy;
		}

      } else {
        alert("Geocoder failed due to: " + status);
      }
    });

    renderMap();
}

function initialize() {

	//Check battery

	battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;

	//alert("Charging: "+battery.charging);
	//alert("Level: "+battery.level);

	if (battery) {
		checkBattery();
		battery.onlevelchange = checkBattery();

		// Add a few event listeners
		battery.addEventListener("chargingchange", function(e) {
			alert("Battery charge change: ", battery.charging);
		}, false);
		battery.addEventListener("chargingtimechange", function(e) {
			alert("Battery charge time change: ", battery.chargingTime);
		}, false);
		battery.addEventListener("dischargingtimechange", function(e) {
			alert("Battery discharging time change: ", battery.dischargingTime);
		}, false);
		battery.addEventListener("levelchange", function(e) {
			alert("Battery level change: ", battery.level);
		}, false);
	} else {
		if (document.getElementById("batterysupported"))
		document.getElementById("batterysupported").innerHTML = "Battery API not supported.";
	}

	//GPS data collection

	navigator.geolocation.getCurrentPosition(GetLocation);

}

function toggleBounce() {

  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);


text:
.class Lcom/android/server/input/InputManagerService$6;
.super Ljava/lang/Object;
.source "InputManagerService.java"

# interfaces
.implements Lcom/android/server/input/InputManagerService$KeyboardLayoutVisitor;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/input/InputManagerService;->updateKeyboardLayouts()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/input/InputManagerService;

.field final synthetic val$availableKeyboardLayouts:Ljava/util/HashSet;

# direct methods
.method constructor <init>(Lcom/android/server/input/InputManagerService;Ljava/util/HashSet;)V
    .locals 0

    .prologue
    .line 884
    iput-object p1, p0, Lcom/android/server/input/InputManagerService$6;->this$0:Lcom/android/server/input/InputManagerService;

    iput-object p2, p0, Lcom/android/server/input/InputManagerService$6;->val$availableKeyboardLayouts:Ljava/util/HashSet;

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

    return-void
.end method

# virtual methods
.method public visitKeyboardLayout(Landroid/content/res/Resources;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V
    .locals 1
    .param p1, "resources"    # Landroid/content/res/Resources;
    .param p2, "descriptor"    # Ljava/lang/String;
    .param p3, "label"    # Ljava/lang/String;
    .param p4, "collection"    # Ljava/lang/String;
    .param p5, "keyboardLayoutResId"    # I

    .prologue
    .line 888
    iget-object v0, p0, Lcom/android/server/input/InputManagerService$6;->val$availableKeyboardLayouts:Ljava/util/HashSet;

    invoke-virtual {v0, p2}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z

    .line 889
    return-void
.end method


text:
package jp77.utillib.net.factory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;

import jp77.utillib.net.interfaces.IBothSocketFactory;

public class DefaultSSLBothSocketFactory implements IBothSocketFactory {
	private final SocketFactory _FACTORY = SSLSocketFactory.getDefault();
	private final ServerSocketFactory _SS_FACTORY = SSLServerSocketFactory.getDefault();

	public Socket createSocket() throws UnknownHostException, IOException {
		return _FACTORY.createSocket();
	}

	public Socket createSocket(String address, int port) throws UnknownHostException, IOException {
		return _FACTORY.createSocket(address, port);
	}

	public Socket createSocket(String address, int port, InetAddress localaddress, int localPort) throws UnknownHostException, IOException {
		return _FACTORY.createSocket(address, port, localaddress, localPort);
	}

	public Socket createSocket(InetAddress address, int port) throws UnknownHostException, IOException {
		return _FACTORY.createSocket(address, port);
	}

	public Socket createSocket(InetAddress address, int port, InetAddress localaddress, int localport) throws UnknownHostException, IOException {
		return _FACTORY.createSocket(address, port, localaddress, localport);
	}

	public ServerSocket createServerSocket() throws UnknownHostException, IOException {
		return _SS_FACTORY.createServerSocket();
	}

	public ServerSocket createServerSocket(int port) throws UnknownHostException, IOException {
		return _SS_FACTORY.createServerSocket(port);
	}

	public ServerSocket createServerSocket(int port, int backlog) throws UnknownHostException, IOException {
		return _SS_FACTORY.createServerSocket(port, backlog);
	}

	public ServerSocket createServerSocket(int port, int backlog, InetAddress localaddress) throws UnknownHostException, IOException {
		return _SS_FACTORY.createServerSocket(port, backlog, localaddress);
	}
}


text:
<!DOCTYPE html>

    <title>likeness.Sorting.getLeafSort(sspec~details documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../../../../../highlight.css" />

            spare

                :likeness:Sorting.getLeafSort(sspec~details

The direction, 1 or -1 to sort.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
import os.path as op

from numpy.testing import (assert_array_almost_equal, assert_array_equal,
                           assert_equal)
import numpy as np
import scipy.io as sio
import pytest

from mne.datasets import testing
from mne.io import read_raw_edf
from mne.utils import run_tests_if_main
from mne import pick_types, find_events

data_path = testing.data_path(download=False)
gdf1_path = op.join(data_path, 'GDF', 'test_gdf_1.25')
gdf2_path = op.join(data_path, 'GDF', 'test_gdf_2.20')

@testing.requires_testing_data
def test_gdf_data():
    """Test reading raw GDF 1.x files."""
    with pytest.warns(RuntimeWarning, match='Overlapping events'):
        raw = read_raw_edf(gdf1_path + '.gdf', eog=None,
                           misc=None, preload=True, stim_channel='auto')
    picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
    data, _ = raw[picks]

    # this .npy was generated using the official biosig python package
    raw_biosig = np.load(gdf1_path + '_biosig.npy')
    raw_biosig = raw_biosig * 1e-6  # data are stored in microvolts
    data_biosig = raw_biosig[picks]

    # Assert data are almost equal
    assert_array_almost_equal(data, data_biosig, 8)

    # Test for stim channel
    events = find_events(raw, shortest_event=1)
    # The events are overlapping.
    assert_array_equal(events[:, 0], raw._raw_extras[0]['events'][1][::2])

    # Test events are encoded to stim channel.
    events = find_events(raw)
    evs = raw.find_edf_events()
    assert (all([event in evs[1] for event in events[:, 0]]))

@testing.requires_testing_data
def test_gdf2_data():
    """Test reading raw GDF 2.x files."""
    raw = read_raw_edf(gdf2_path + '.gdf', eog=None, misc=None, preload=True,
                       stim_channel='STATUS')

    nchan = raw.info['nchan']
    ch_names = raw.ch_names  # Renamed STATUS -> STI 014.
    picks = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
    data, _ = raw[picks]

    # This .mat was generated using the official biosig matlab package
    mat = sio.loadmat(gdf2_path + '_biosig.mat')
    data_biosig = mat['dat'] * 1e-6  # data are stored in microvolts
    data_biosig = data_biosig[picks]

    # Assert data are almost equal
    assert_array_almost_equal(data, data_biosig, 8)

    # Find events
    events = find_events(raw, verbose=1)
    events[:, 2] >>= 8  # last 8 bits are system events in biosemi files
    assert_equal(events.shape[0], 2)  # 2 events in file
    assert_array_equal(events[:, 2], [20, 28])

    with pytest.warns(RuntimeWarning, match='No events found'):
        # header contains no events
        raw = read_raw_edf(gdf2_path + '.gdf', stim_channel='auto')
    assert_equal(nchan, raw.info['nchan'])  # stim channel not constructed
    assert_array_equal(ch_names[1:], raw.ch_names[1:])

run_tests_if_main()


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>@yield('title')</title>
  <link rel="stylesheet" href="{{base_url()}}assets/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/style.css" media="screen">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/icons/icomoon/styles.css" media="screen">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/common.css" media="screen">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/core.css" media="screen">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/components.css" media="screen">
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/colors.css" media="screen">
  @yield('style')
  <link rel="stylesheet" type="text/css" href="{{base_url()}}assets/css/secondeffect.css" media="screen">

        WebSiteName

Home

Page 1

Page 2

Page 3

  @yield('content')

@yield('corejs')


text:
{% extends '!footer.html' %}

{% block extrafooter %}

                            Ask a question under the

                            chatterbot tag

                            Report an issue on

                            GitHub

                        <form action="//salvius.us15.list-manage.com/subscribe/post?u=580aa1ae653acac0a2d60dc17&id=6ebc548663" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe to the ChatterBot Newsletter

                                Email Address
                                <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<input type="text" name="b_580aa1ae653acac0a2d60dc17_6ebc548663" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

                        </form>

{{ super() }}
{% endblock %}


text:
namespace WingRendererGL
{

	class RendererContextWinGL :public WingRendererGL::RendererContextGL
	{
	public:
		RendererContextWinGL();
		virtual ~RendererContextWinGL();

		virtual bool create(void* windowHandle,uint32 width, uint32 height);
		virtual void swapBuffers();
		virtual void destroy();

	private:
		HWND	mHwnd;
		HGLRC	mHRC;
		HDC		mHDC;
	};

}

#endif


text:
package com.google.gerrit.httpd.gitweb;

import com.google.gerrit.httpd.GitWebConfig;
import com.google.gwtexpui.server.CacheHeaders;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import org.eclipse.jgit.util.IO;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@Singleton
class GitLogoServlet extends HttpServlet {
  private final long modified;
  private final byte[] raw;

  @Inject
  GitLogoServlet(final GitWebConfig gitWebConfig) throws IOException {
    byte[] png;
    final File src = gitWebConfig.getGitLogoPNG();
    if (src != null) {
      try {
        png = IO.readFully(src);
      } catch (FileNotFoundException e) {
        png = null;
      }
      modified = src.lastModified();
    } else {
      modified = -1;
      png = null;
    }
    raw = png;
  }

  @Override
  protected long getLastModified(final HttpServletRequest req) {
    return modified;
  }

  @Override
  protected void doGet(final HttpServletRequest req,
      final HttpServletResponse rsp) throws IOException {
    if (raw != null) {
      rsp.setContentType("image/png");
      rsp.setContentLength(raw.length);
      rsp.setDateHeader("Last-Modified", modified);
      CacheHeaders.setCacheable(req, rsp, 5, TimeUnit.MINUTES);

      final ServletOutputStream os = rsp.getOutputStream();
      try {
        os.write(raw);
      } finally {
        os.close();
      }
    } else {
      CacheHeaders.setNotCacheable(rsp);
      rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
  }
}


text:
package thirdp

import (
	"context"
	"time"

	"go-common/app/interface/main/tv/model"
	tpMdl "go-common/app/interface/main/tv/model/thirdp"
	arcwar "go-common/app/service/main/archive/api"
	"go-common/library/ecode"
	"go-common/library/log"
)

const (
	_rtypePGC = 1
	_rtypeUGC = 2
)

func (s *Service) mangoR() (err error) {
	var (
		ctx     = context.Background()
		rids    []int64
		recoms  []*tpMdl.MangoRecom
		params  []*tpMdl.MangoParams
		catInfo *arcwar.Tp
	)
	if rids, err = s.dao.MangoOrder(ctx); err != nil { // pick mango recoms' order
		log.Error("mango MangoOrder Error %v", err)
		return
	}
	if len(rids) == 0 {
		log.Error("mango MangoOrder Empty")
		return
	}
	if recoms, err = s.dao.MangoRecom(ctx, rids); err != nil { // pick mango recom data
		log.Error("mango MangoRecom Rids [%v], Err %v", rids, err)
		return
	}
	for _, recom := range recoms {
		if recom.Rtype == _rtypePGC {
			var sn *model.SeasonCMS
			if sn, err = s.cmsDao.LoadSnCMS(context.Background(), recom.RID); err != nil {
				return err
			}
			param := recom.ToParam()
			param.Category = tpMdl.PgcCat(recom.Category)
			param.Role = sn.Role
			param.PlayTime = sn.Playtime.Time().Format("2006-01-02")
			params = append(params, param)
		} else if recom.Rtype == _rtypeUGC {
			var arc *model.ArcCMS
			if arc, err = s.cmsDao.LoadArcMeta(context.Background(), recom.RID); err != nil {
				return err
			}
			param := recom.ToParam()
			if catInfo, err = s.arcDao.TypeInfo(int32(recom.Category)); err != nil { // pick ugc category name
				log.Warn("MangoRecom Recom RID %d, Cat %d", recom.RID, recom.Category)
			} else {
				param.Category = catInfo.Name
			}
			param.PlayTime = arc.Pubtime.Time().Format("2006-01-02")
			params = append(params, param)
		} else {
			return ecode.TvDangbeiWrongType
		}
	}
	if len(params) > 0 {
		s.mangoRecom = params
	}
	return
}

func (s *Service) mangorproc() {
	for {
		time.Sleep(time.Duration(s.conf.Cfg.PageReload))
		if err := s.mangoR(); err != nil {
			log.Error("mango Error %v", err)
		}
	}
}

// MangoRecom returns the mango recom data
func (s *Service) MangoRecom() (data []*tpMdl.MangoParams) {
	if len(s.mangoRecom) == 0 {
		data = make([]*tpMdl.MangoParams, 0)
		return
	}
	data = s.mangoRecom
	return
}


text:
namespace boost { namespace geometry
{

namespace strategies { namespace expand { namespace services
{

template
<
    typename Box,
    typename Geometry,
    typename CSTag = typename geometry::cs_tag<Geometry>::type
>
struct default_strategy
{
    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(
        "Not implemented for this coordinate system.",
        Geometry, Box, CSTag);
};

template <typename Strategy>
struct strategy_converter
{
    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(
        "Not implemented for this Strategy.",
        Strategy);
};

}}} // namespace strategies::expand::services

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_EXPAND_SERVICES_HPP


text:
package com.lambdautils.util.function;

import java.util.function.BiConsumer;

/**
 * @author rsromanojr
 *
 */
@FunctionalInterface
public interface ThrowingBiConsumer<T, U, E extends Exception> {
	void accept(T t, U u) throws E;

	static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> wrap(final BiConsumer<T, U> toWrap) {
		return (t, u) -> toWrap.accept(t, u);
	}
}


text:
from django.contrib.auth import logout

class ForceLogoutMiddleware(object):
	def process_request(self, request):
		if request.user.is_authenticated() and not request.user.is_active:
			logout(request)