text:
"""Representation of Z-Wave sensors."""
from __future__ import annotations

from collections.abc import Mapping
import logging
from typing import cast

import voluptuous as vol
from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandClass, ConfigurationValueType, NodeStatus
from zwave_js_server.const.command_class.meter import (
    RESET_METER_OPTION_TARGET_VALUE,
    RESET_METER_OPTION_TYPE,
)
from zwave_js_server.model.node import Node as ZwaveNode
from zwave_js_server.model.value import ConfigurationValue
from zwave_js_server.util.command_class.meter import get_meter_type

from homeassistant.components.sensor import (
    DOMAIN as SENSOR_DOMAIN,
    SensorDeviceClass,
    SensorEntity,
    SensorEntityDescription,
    SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import (
    ATTR_METER_TYPE,
    ATTR_METER_TYPE_NAME,
    ATTR_VALUE,
    DATA_CLIENT,
    DOMAIN,
    ENTITY_DESC_KEY_BATTERY,
    ENTITY_DESC_KEY_CO,
    ENTITY_DESC_KEY_CO2,
    ENTITY_DESC_KEY_CURRENT,
    ENTITY_DESC_KEY_ENERGY_MEASUREMENT,
    ENTITY_DESC_KEY_ENERGY_TOTAL_INCREASING,
    ENTITY_DESC_KEY_HUMIDITY,
    ENTITY_DESC_KEY_ILLUMINANCE,
    ENTITY_DESC_KEY_MEASUREMENT,
    ENTITY_DESC_KEY_POWER,
    ENTITY_DESC_KEY_POWER_FACTOR,
    ENTITY_DESC_KEY_PRESSURE,
    ENTITY_DESC_KEY_SIGNAL_STRENGTH,
    ENTITY_DESC_KEY_TARGET_TEMPERATURE,
    ENTITY_DESC_KEY_TEMPERATURE,
    ENTITY_DESC_KEY_TOTAL_INCREASING,
    ENTITY_DESC_KEY_VOLTAGE,
    SERVICE_RESET_METER,
)
from .discovery import ZwaveDiscoveryInfo
from .discovery_data_template import (
    NumericSensorDataTemplate,
    NumericSensorDataTemplateData,
)
from .entity import ZWaveBaseEntity
from .helpers import get_device_id, get_valueless_base_unique_id

LOGGER = logging.getLogger(__name__)

STATUS_ICON: dict[NodeStatus, str] = {
    NodeStatus.ALIVE: "mdi:heart-pulse",
    NodeStatus.ASLEEP: "mdi:sleep",
    NodeStatus.AWAKE: "mdi:eye",
    NodeStatus.DEAD: "mdi:robot-dead",
    NodeStatus.UNKNOWN: "mdi:help-rhombus",
}

ENTITY_DESCRIPTION_KEY_MAP: dict[str, SensorEntityDescription] = {
    ENTITY_DESC_KEY_BATTERY: SensorEntityDescription(
        ENTITY_DESC_KEY_BATTERY,
        device_class=SensorDeviceClass.BATTERY,
        entity_category=EntityCategory.DIAGNOSTIC,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_CURRENT: SensorEntityDescription(
        ENTITY_DESC_KEY_CURRENT,
        device_class=SensorDeviceClass.CURRENT,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_VOLTAGE: SensorEntityDescription(
        ENTITY_DESC_KEY_VOLTAGE,
        device_class=SensorDeviceClass.VOLTAGE,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_ENERGY_MEASUREMENT: SensorEntityDescription(
        ENTITY_DESC_KEY_ENERGY_MEASUREMENT,
        device_class=SensorDeviceClass.ENERGY,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_ENERGY_TOTAL_INCREASING: SensorEntityDescription(
        ENTITY_DESC_KEY_ENERGY_TOTAL_INCREASING,
        device_class=SensorDeviceClass.ENERGY,
        state_class=SensorStateClass.TOTAL_INCREASING,
    ),
    ENTITY_DESC_KEY_POWER: SensorEntityDescription(
        ENTITY_DESC_KEY_POWER,
        device_class=SensorDeviceClass.POWER,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_POWER_FACTOR: SensorEntityDescription(
        ENTITY_DESC_KEY_POWER_FACTOR,
        device_class=SensorDeviceClass.POWER_FACTOR,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_CO: SensorEntityDescription(
        ENTITY_DESC_KEY_CO,
        device_class=SensorDeviceClass.CO,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_CO2: SensorEntityDescription(
        ENTITY_DESC_KEY_CO2,
        device_class=SensorDeviceClass.CO2,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_HUMIDITY: SensorEntityDescription(
        ENTITY_DESC_KEY_HUMIDITY,
        device_class=SensorDeviceClass.HUMIDITY,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_ILLUMINANCE: SensorEntityDescription(
        ENTITY_DESC_KEY_ILLUMINANCE,
        device_class=SensorDeviceClass.ILLUMINANCE,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_PRESSURE: SensorEntityDescription(
        ENTITY_DESC_KEY_PRESSURE,
        device_class=SensorDeviceClass.PRESSURE,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_SIGNAL_STRENGTH: SensorEntityDescription(
        ENTITY_DESC_KEY_SIGNAL_STRENGTH,
        device_class=SensorDeviceClass.SIGNAL_STRENGTH,
        entity_category=EntityCategory.DIAGNOSTIC,
        entity_registry_enabled_default=False,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_TEMPERATURE: SensorEntityDescription(
        ENTITY_DESC_KEY_TEMPERATURE,
        device_class=SensorDeviceClass.TEMPERATURE,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_TARGET_TEMPERATURE: SensorEntityDescription(
        ENTITY_DESC_KEY_TARGET_TEMPERATURE,
        device_class=SensorDeviceClass.TEMPERATURE,
        state_class=None,
    ),
    ENTITY_DESC_KEY_MEASUREMENT: SensorEntityDescription(
        ENTITY_DESC_KEY_MEASUREMENT,
        device_class=None,
        state_class=SensorStateClass.MEASUREMENT,
    ),
    ENTITY_DESC_KEY_TOTAL_INCREASING: SensorEntityDescription(
        ENTITY_DESC_KEY_TOTAL_INCREASING,
        device_class=None,
        state_class=SensorStateClass.TOTAL_INCREASING,
    ),
}

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up Z-Wave sensor from config entry."""
    client: ZwaveClient = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT]

    @callback
    def async_add_sensor(info: ZwaveDiscoveryInfo) -> None:
        """Add Z-Wave Sensor."""
        entities: list[ZWaveBaseEntity] = []

        if info.platform_data:
            data: NumericSensorDataTemplateData = info.platform_data
        else:
            data = NumericSensorDataTemplateData()
        entity_description = ENTITY_DESCRIPTION_KEY_MAP.get(
            data.entity_description_key or "", SensorEntityDescription("base_sensor")
        )

        if info.platform_hint == "string_sensor":
            entities.append(
                ZWaveStringSensor(config_entry, client, info, entity_description)
            )
        elif info.platform_hint == "numeric_sensor":
            entities.append(
                ZWaveNumericSensor(
                    config_entry,
                    client,
                    info,
                    entity_description,
                    data.unit_of_measurement,
                )
            )
        elif info.platform_hint == "list_sensor":
            entities.append(
                ZWaveListSensor(config_entry, client, info, entity_description)
            )
        elif info.platform_hint == "config_parameter":
            entities.append(
                ZWaveConfigParameterSensor(
                    config_entry, client, info, entity_description
                )
            )
        elif info.platform_hint == "meter":
            entities.append(
                ZWaveMeterSensor(config_entry, client, info, entity_description)
            )
        else:
            LOGGER.warning(
                "Sensor not implemented for %s/%s",
                info.platform_hint,
                info.primary_value.propertyname,
            )
            return

        async_add_entities(entities)

    @callback
    def async_add_node_status_sensor(node: ZwaveNode) -> None:
        """Add node status sensor."""
        async_add_entities([ZWaveNodeStatusSensor(config_entry, client, node)])

    config_entry.async_on_unload(
        async_dispatcher_connect(
            hass,
            f"{DOMAIN}_{config_entry.entry_id}_add_{SENSOR_DOMAIN}",
            async_add_sensor,
        )
    )

    config_entry.async_on_unload(
        async_dispatcher_connect(
            hass,
            f"{DOMAIN}_{config_entry.entry_id}_add_node_status_sensor",
            async_add_node_status_sensor,
        )
    )

    platform = entity_platform.async_get_current_platform()
    platform.async_register_entity_service(
        SERVICE_RESET_METER,
        {
            vol.Optional(ATTR_METER_TYPE): vol.Coerce(int),
            vol.Optional(ATTR_VALUE): vol.Coerce(int),
        },
        "async_reset_meter",
    )

class ZwaveSensorBase(ZWaveBaseEntity, SensorEntity):
    """Basic Representation of a Z-Wave sensor."""

    def __init__(
        self,
        config_entry: ConfigEntry,
        client: ZwaveClient,
        info: ZwaveDiscoveryInfo,
        entity_description: SensorEntityDescription,
        unit_of_measurement: str | None = None,
    ) -> None:
        """Initialize a ZWaveSensorBase entity."""
        super().__init__(config_entry, client, info)
        self.entity_description = entity_description
        self._attr_native_unit_of_measurement = unit_of_measurement

        # Entity class attributes
        self._attr_force_update = True
        self._attr_name = self.generate_name(include_value_name=True)

class ZWaveStringSensor(ZwaveSensorBase):
    """Representation of a Z-Wave String sensor."""

    @property
    def native_value(self) -> str | None:
        """Return state of the sensor."""
        if self.info.primary_value.value is None:
            return None
        return str(self.info.primary_value.value)

    @property
    def native_unit_of_measurement(self) -> str | None:
        """Return unit of measurement the value is expressed in."""
        if self.info.primary_value.metadata.unit is None:
            return None
        return str(self.info.primary_value.metadata.unit)

class ZWaveNumericSensor(ZwaveSensorBase):
    """Representation of a Z-Wave Numeric sensor."""

    @callback
    def on_value_update(self) -> None:
        """Handle scale changes for this value on value updated event."""
        self._attr_native_unit_of_measurement = (
            NumericSensorDataTemplate()
            .resolve_data(self.info.primary_value)
            .unit_of_measurement
        )

    @property
    def native_value(self) -> float:
        """Return state of the sensor."""
        if self.info.primary_value.value is None:
            return 0
        return round(float(self.info.primary_value.value), 2)

    @property
    def native_unit_of_measurement(self) -> str | None:
        """Return unit of measurement the value is expressed in."""
        if self._attr_native_unit_of_measurement is not None:
            return self._attr_native_unit_of_measurement
        if self.info.primary_value.metadata.unit is None:
            return None

        return str(self.info.primary_value.metadata.unit)

class ZWaveMeterSensor(ZWaveNumericSensor):
    """Representation of a Z-Wave Meter CC sensor."""

    @property
    def extra_state_attributes(self) -> Mapping[str, int | str] | None:
        """Return extra state attributes."""
        if meter_type := get_meter_type(self.info.primary_value):
            return {
                ATTR_METER_TYPE: meter_type.value,
                ATTR_METER_TYPE_NAME: meter_type.name,
            }
        return None

    async def async_reset_meter(
        self, meter_type: int | None = None, value: int | None = None
    ) -> None:
        """Reset meter(s) on device."""
        node = self.info.node
        primary_value = self.info.primary_value
        options = {}
        if meter_type is not None:
            options[RESET_METER_OPTION_TYPE] = meter_type
        if value is not None:
            options[RESET_METER_OPTION_TARGET_VALUE] = value
        args = [options] if options else []
        await node.endpoints[primary_value.endpoint].async_invoke_cc_api(
            CommandClass.METER, "reset", *args, wait_for_result=False
        )
        LOGGER.debug(
            "Meters on node %s endpoint %s reset with the following options: %s",
            node,
            primary_value.endpoint,
            options,
        )

class ZWaveListSensor(ZwaveSensorBase):
    """Representation of a Z-Wave Numeric sensor with multiple states."""

    def __init__(
        self,
        config_entry: ConfigEntry,
        client: ZwaveClient,
        info: ZwaveDiscoveryInfo,
        entity_description: SensorEntityDescription,
        unit_of_measurement: str | None = None,
    ) -> None:
        """Initialize a ZWaveListSensor entity."""
        super().__init__(
            config_entry, client, info, entity_description, unit_of_measurement
        )

        # Entity class attributes
        self._attr_name = self.generate_name(
            include_value_name=True,
            alternate_value_name=self.info.primary_value.property_name,
            additional_info=[self.info.primary_value.property_key_name],
        )

    @property
    def native_value(self) -> str | None:
        """Return state of the sensor."""
        if self.info.primary_value.value is None:
            return None
        if (
            str(self.info.primary_value.value)
            not in self.info.primary_value.metadata.states
        ):
            return str(self.info.primary_value.value)
        return str(
            self.info.primary_value.metadata.states[str(self.info.primary_value.value)]
        )

    @property
    def extra_state_attributes(self) -> dict[str, str] | None:
        """Return the device specific state attributes."""
        # add the value's int value as property for multi-value (list) items
        return {ATTR_VALUE: self.info.primary_value.value}

class ZWaveConfigParameterSensor(ZwaveSensorBase):
    """Representation of a Z-Wave config parameter sensor."""

    def __init__(
        self,
        config_entry: ConfigEntry,
        client: ZwaveClient,
        info: ZwaveDiscoveryInfo,
        entity_description: SensorEntityDescription,
        unit_of_measurement: str | None = None,
    ) -> None:
        """Initialize a ZWaveConfigParameterSensor entity."""
        super().__init__(
            config_entry, client, info, entity_description, unit_of_measurement
        )
        self._primary_value = cast(ConfigurationValue, self.info.primary_value)

        # Entity class attributes
        self._attr_name = self.generate_name(
            include_value_name=True,
            alternate_value_name=self.info.primary_value.property_name,
            additional_info=[self.info.primary_value.property_key_name],
            name_suffix="Config Parameter",
        )

    @property
    def native_value(self) -> str | None:
        """Return state of the sensor."""
        if self.info.primary_value.value is None:
            return None
        if (
            self._primary_value.configuration_value_type == ConfigurationValueType.RANGE
            or (
                not str(self.info.primary_value.value)
                in self.info.primary_value.metadata.states
            )
        ):
            return str(self.info.primary_value.value)
        return str(
            self.info.primary_value.metadata.states[str(self.info.primary_value.value)]
        )

    @property
    def extra_state_attributes(self) -> dict[str, str] | None:
        """Return the device specific state attributes."""
        if self._primary_value.configuration_value_type == ConfigurationValueType.RANGE:
            return None
        # add the value's int value as property for multi-value (list) items
        return {ATTR_VALUE: self.info.primary_value.value}

class ZWaveNodeStatusSensor(SensorEntity):
    """Representation of a node status sensor."""

    _attr_should_poll = False
    _attr_entity_category = EntityCategory.DIAGNOSTIC

    def __init__(
        self, config_entry: ConfigEntry, client: ZwaveClient, node: ZwaveNode
    ) -> None:
        """Initialize a generic Z-Wave device entity."""
        self.config_entry = config_entry
        self.client = client
        self.node = node
        name: str = (
            self.node.name
            or self.node.device_config.description
            or f"Node {self.node.node_id}"
        )
        # Entity class attributes
        self._attr_name = f"{name}: Node Status"
        self._base_unique_id = get_valueless_base_unique_id(client, node)
        self._attr_unique_id = f"{self._base_unique_id}.node_status"
        # device is precreated in main handler
        self._attr_device_info = DeviceInfo(
            identifiers={get_device_id(self.client, self.node)},
        )
        self._attr_native_value: str = node.status.name.lower()

    async def async_poll_value(self, _: bool) -> None:
        """Poll a value."""
        # pylint: disable=no-self-use
        LOGGER.error(
            "There is no value to refresh for this entity so the zwave_js.refresh_value "
            "service won't work for it"
        )

    @callback
    def _status_changed(self, _: dict) -> None:
        """Call when status event is received."""
        self._attr_native_value = self.node.status.name.lower()
        self.async_write_ha_state()

    @property
    def icon(self) -> str | None:
        """Icon of the entity."""
        return STATUS_ICON[self.node.status]

    async def async_added_to_hass(self) -> None:
        """Call when entity is added."""
        # Add value_changed callbacks.
        for evt in ("wake up", "sleep", "dead", "alive"):
            self.async_on_remove(self.node.on(evt, self._status_changed))
        self.async_on_remove(
            async_dispatcher_connect(
                self.hass,
                f"{DOMAIN}_{self.unique_id}_poll_value",
                self.async_poll_value,
            )
        )
        self.async_on_remove(
            async_dispatcher_connect(
                self.hass,
                f"{DOMAIN}_{self._base_unique_id}_remove_entity",
                self.async_remove,
            )
        )
        self.async_write_ha_state()


text:
package com.theoriginalbit.framework.peripheral.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Use this to only enable a peripheral or method when certain mods are found installed in
 * the Minecraft instance, the values should be Mod IDs
 *
 * @author theoriginalbit
 * @since 8/11/14
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Requires {
    public String[] modIds();

    public boolean allRequired() default false;
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

using Xunit;

using Latem.Runtime;
using Latem.Runtime.Instructions;
using Latem.Runtime.Instructions.Implementation;

namespace Latem.Tests
{
    public class InstructionTests
    {
        [Fact]
        public void StoreConstant_ShouldWriteTheValueToMemory()
        {
            var vm = new VirtualMachine(
                5,
                new List<IInstruction> {
                    new StoreConstantInstruction(0, true),
                }
            );

            vm.Execute();

            Assert.True(vm.GetMemoryValueAt(0));
        }

        [Fact]
        public void GotoConstant_ShouldGotoTheSpecifiedInstructionIndex()
        {
            var vm = new VirtualMachine(
                5,
                new List<IInstruction> {
                    new GotoConstantInstruction(2),
                    new StoreConstantInstruction(0, true),
                    new StoreConstantInstruction(1, true)
                }
            );

            vm.Execute();

            Assert.False(vm.GetMemoryValueAt(0));
            Assert.True(vm.GetMemoryValueAt(1));
        }
    }
}


text:
/* Preload handles the preload info from HashPath */
function Preload(hashPath){
	this.hashPath = hashPath;
	this.rowPreload = false;
	this.init();
}

/* INIT */
/* init preload object */
Preload.prototype.init = function(){
// 	http://dive.local/app_dev.php#browser\entity\http://purl.org/collections/nl/dive/entity/kb-loc-Akihito

	if (!this.hashPath.getAction()){ return; }
	console.log('Action: ',this.hashPath.getAction());
	switch(this.hashPath.getAction()){
		case 'browser':
			switch(this.hashPath.parameters[0]){
				case 'entity':
					Global.search.setKeywords('Entity:'+this.hashPath.parameters[1]);
					this.rowPreload = true;
				break;
				case 'collection':
					Global.search.setKeywords('Collection:'+this.hashPath.parameters[1]);
					this.rowPreload = true;
				break;
			}
		break;
		case 'about':
			$('#help-button').click();
		break;
		/*case 'gallery':
			switch(this.hashPath.parameters[0]){
				case 'entity':
					Global.gallery.loadEntity(this.hashPath.parameters[1]);
				break;
				case 'collection':
					Global.gallery.loadCollection(this.hashPath.parameters[1]);
				break;
			}
		break;*/
	}
}


text:
<!DOCTYPE html>

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

  <meta name="viewport" content="width=device-width">

Work Experience

Projects

Education

Skills Chart


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
	<RelativeLayout
        android:id="@+id/title_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
	    <RelativeLayout
	        android:id="@+id/title_bar"
	        android:visibility="gone"
	        style="@style/aliwx_common_title_style" >

	        <TextView
	            android:id="@+id/left_button"
	            style="@style/aliwx_common_title_left_btn_shadow"
	            android:visibility="?attr/aliwx_title_leftbutton_visible"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content" />

	        <TextView
	            android:id="@+id/title_self_title"
	            style="@style/aliwx_self_title_text_shadow"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"
	            android:layout_centerInParent="true"
	            android:ellipsize="middle"
	            android:gravity="center"
	            android:includeFontPadding="false"
	            android:paddingLeft="90dp"
	            android:paddingRight="90dp"
	            android:singleLine="true" />

	        <RelativeLayout
	            android:id="@+id/update_message_layout"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"
	            android:layout_centerInParent="true"
	            android:singleLine="true"
	            android:visibility="gone" >

	            <ProgressBar
	                android:id="@+id/update_message_progressbar"
	                style="?android:attr/progressBarStyleSmall"
	                android:layout_width="21dip"
	                android:layout_height="21dip"
	                android:layout_centerVertical="true"
	                android:indeterminate="true"
	                android:indeterminateDrawable="@drawable/aliwx_my_progress" />

	            <TextView
	                android:id="@+id/update_message_text"
	                style="@style/aliwx_self_title_text_shadow"
	                android:layout_width="wrap_content"
	                android:layout_height="wrap_content"
	                android:layout_centerVertical="true"
	                android:layout_marginLeft="4dp"
	                android:layout_toRightOf="@+id/update_message_progressbar"
	                android:singleLine="true"
	                android:text="@string/aliwx_updating_messsage" />
	        </RelativeLayout>

    </RelativeLayout>
</RelativeLayout>
    <LinearLayout
        android:id="@+id/net_warn"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/aliwx_net_alert_height"
        android:background="@color/aliwx_third_text_color"
        android:gravity="center"
        android:visibility="gone" >

        <ImageView
            android:id="@+id/net_alert_icon"
            android:layout_width="@dimen/aliwx_net_alert_icon_size"
            android:layout_height="@dimen/aliwx_net_alert_icon_size"
            android:scaleType="centerInside"
            android:src="@drawable/aliwx_no_network_icn" />

        <TextView
            android:id="@+id/net_alert_toast"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="@string/aliwx_net_null_setting"
            android:textColor="@android:color/white"
            android:textSize="@dimen/aliwx_common_text_size" />
    </LinearLayout>

</LinearLayout>


text:
<?php

/**
 * @namespace
 */
namespace Zend\Controller\Router;

/**
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Route {
    public function match($path);
    public function assemble($data = array(), $reset = false, $encode = false);
    public static function getInstance(\Zend\Config\Config $config);
}


text:
package org.continuity.lctl.schema;

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

import org.continuity.lctl.timeseries.ContextRecord;
import org.continuity.lctl.validation.ContextValidityReport;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 * Describes which kind of variables are allowed in contexts.
 *
 * @author Henning Schulz
 *
 */
@JsonPropertyOrder({ "ignore-by-default", "auto-detect", "variables" })
public class ContextSchema {

	@JsonProperty("ignore-by-default")
	@JsonInclude(Include.NON_ABSENT)
	private Optional<IgnoreByDefaultValue> ignoreByDefault = Optional.empty();

	@JsonProperty("auto-detect")
	@JsonInclude(Include.NON_ABSENT)
	private boolean autoDetect = true;

	@JsonInclude(Include.NON_EMPTY)
	private Map<String, VariableSchema> variables = new HashMap<>();

	/**
	 * Optional property whether all context variables should be ignored for forecasting. Default is
	 * {@link IgnoreByDefaultValue#ONLY_NEW};
	 *
	 * @return
	 */
	public Optional<IgnoreByDefaultValue> getIgnoreByDefault() {
		return ignoreByDefault;
	}

	@JsonIgnore
	public IgnoreByDefaultValue ignoreByDefault() {
		return ignoreByDefault.orElse(IgnoreByDefaultValue.ONLY_NEW);
	}

	public void setIgnoreByDefault(Optional<IgnoreByDefaultValue> ignoreByDefault) {
		this.ignoreByDefault = ignoreByDefault;
	}

	public boolean getAutoDetect() {
		return autoDetect;
	}

	public void setAutoDetect(boolean autoDetect) {
		this.autoDetect = autoDetect;
	}

	public Map<String, VariableSchema> getVariables() {
		return variables;
	}

	public void setVariables(Map<String, VariableSchema> variables) {
		this.variables = variables;
	}

	public ContextValidityReport validate(ContextRecord record) {
		ContextValidityReport report = new ContextValidityReport();

		if (record.getNumeric() != null) {
			for (String var : record.getNumeric().keySet()) {
				validate(var, VariableType.NUMERIC, report);
			}
		}

		if (record.getString() != null) {
			for (String var : record.getString().keySet()) {
				validate(var, VariableType.STRING, report);
			}
		}

		if (record.getBoolean() != null) {
			for (String var : record.getBoolean()) {
				validate(var, VariableType.BOOLEAN, report);
			}
		}

		return report;
	}

	private void validate(String name, VariableType type, ContextValidityReport report) {
		VariableSchema varSchema = getVariables().get(name);

		if (varSchema == null) {
			if (autoDetect) {
				report.reportNewlyAdded(name, type);
			} else {
				report.reportUnknown(name, type);
			}
		} else if (varSchema.getType() != type) {
			report.reportWrongType(name, varSchema.getType(), type);
		}
	}

}


text:
package com.cchtw.sfy.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cchtw.sfy.R;
import com.cchtw.sfy.activity.SignDetailActivity;
import com.cchtw.sfy.api.ApiRequest;
import com.cchtw.sfy.api.JsonHttpHandler;
import com.cchtw.sfy.uitls.Constant;
import com.cchtw.sfy.uitls.SharedPreferencesHelper;
import com.cchtw.sfy.uitls.ToastHelper;
import com.cchtw.sfy.uitls.dialog.DialogHelper;
import com.itech.message.APP_120009;
import com.itech.message.Result_120023;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 */
public class SignRecycleAdapter extends RecycleBaseAdapter {

    private Context context;
    public SharedPreferencesHelper mSharedPreferences;

    public SignRecycleAdapter(Context context) {
        super(context);
        this.context = context;
        mSharedPreferences =  SharedPreferencesHelper.getInstance(context);
    }

    public SignRecycleAdapter(View headerView, Context context) {
        super(context);
        mHeaderView = headerView;
    }

    @Override
    public boolean hasHeader() {
        return false;
    }

    @Override
    public View onCreateItemView(ViewGroup parent, int viewType) {
        return getLayoutInflater(parent.getContext()).inflate(R.layout.item_sign,null);
    }

    @Override
    protected RecycleBaseAdapter.ViewHolder onCreateItemViewHolder(View view, int viewType) {
        return new ViewHolder(viewType, view);
    }

    @Override
    protected void onBindItemViewHolder(RecycleBaseAdapter.ViewHolder holder, int position) {
        super.onBindItemViewHolder(holder, position);
        SignRecycleAdapter.ViewHolder new_holder = (ViewHolder) holder;
        final Result_120023 signBean = (Result_120023) _data.get(position);
        new_holder.tv_sign_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//跳转到详情
                goToSignDetail(signBean);
            }
        });
        new_holder.tv_give_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//放弃签约
                giveUpSign(signBean);
            }
        });
//      签约类型判断
        switch (signBean.getState()){
            case "1":
//                ImageHelper.displayImage("drawable://" + R.drawable.ic_unsign, new_holder.iv_sign_stye);
                new_holder.iv_sign_stye.setImageResource(R.drawable.ic_unsign);
                new_holder.tv_give_up.setTextColor(Color.parseColor("#FF0000"));

                break;
            case "2":
//                ImageHelper.displayImage("drawable://" + R.drawable.ic_sign_finish, new_holder.iv_sign_stye);
                new_holder.iv_sign_stye.setImageResource(R.drawable.ic_sign_finish);
                new_holder.tv_give_up.setEnabled(false);
                new_holder.tv_give_up.setClickable(false);
                new_holder.tv_give_up.setTextColor(Color.parseColor("#ebebeb"));
                break;
            case "3":
//                ImageHelper.displayImage("drawable://" + R.drawable.ic_unfinish, new_holder.iv_sign_stye);
                new_holder.iv_sign_stye.setImageResource(R.drawable.ic_unfinish);
                new_holder.tv_give_up.setEnabled(false);
                new_holder.tv_give_up.setClickable(false);
                new_holder.tv_give_up.setTextColor(Color.parseColor("#ebebeb"));

                break;
            default:
//                ImageHelper.displayImage("drawable://" + R.drawable.ic_unfinish, new_holder.iv_sign_stye);
//                new_holder.iv_sign_stye.setImageResource(R.drawable.ic_unfinish);
                new_holder.tv_give_up.setTextColor(Color.parseColor("#FF0000"));

                break;
        }

//      姓名
        new_holder.tv_sign_name.setText(signBean.getAccountName());
//      手机号码
        new_holder.tv_phone_number.setText(signBean.getMobile());
//      身份证号
        new_holder.tv_id_number.setText(signBean.getIdCard());
//      银行卡号
        new_holder.tv_card_number.setText(signBean.getAccountNo());

    }

    private void goToSignDetail(Result_120023 signBean){
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", signBean);
        intent.putExtras(bundle);
        intent.setClass(context, SignDetailActivity.class);
        context.startActivity(intent);
    }

    private void giveUpSign(final Result_120023 signBean){
        DialogHelper.showProgressDialog(context, "正在处理,请稍候...", true, false);
        APP_120009 app = new APP_120009();
        app.setMerchantId(signBean.getMerchantId());
        app.setIdCard(signBean.getIdCard());
        app.setAccountNo(signBean.getAccountNo());
        app.setUserName(SharedPreferencesHelper.getString(Constant.PHONE,""));
        ApiRequest.requestData(app, SharedPreferencesHelper.getString(Constant.PHONE, ""), new JsonHttpHandler(context) {
            @Override
            public void onDo(JSONObject responseJsonObject) {
                APP_120009 app120009 = JSON.parseObject(responseJsonObject.toString(), APP_120009.class);
                    if (app120009.getDetailCode().equals("0000")) {
                        removeItem(signBean);
                    }
                ToastHelper.ShowToast(app120009.getDetailInfo());
            }

            @Override
            public void onDo(JSONArray responseJsonArray) {

            }

            @Override
            public void onDo(String responseString) {

            }

            @Override
            public void onFinish() {
                DialogHelper.dismissProgressDialog();
            }
        });

    }
    public static class ViewHolder extends RecycleBaseAdapter.ViewHolder {
        public TextView tv_sign_name;
        public TextView tv_phone_number;
        public TextView tv_id_number;
        public TextView tv_card_number;
        public ImageView iv_sign_stye;
        public TextView tv_sign_detail;
        public TextView tv_give_up;
        public ViewHolder(int viewType, View view) {
            super(viewType, view);
            tv_sign_name = (TextView) view.findViewById(R.id.tv_sign_name);
            tv_phone_number  = (TextView) view.findViewById(R.id.tv_phone_number);
            tv_id_number = (TextView) view.findViewById(R.id.tv_id_number);
            tv_card_number = (TextView) view.findViewById(R.id.tv_card_number);
            iv_sign_stye = (ImageView) view.findViewById(R.id.iv_sign_stye);
            tv_sign_detail = (TextView) view.findViewById(R.id.tv_sign_detail);
            tv_give_up  = (TextView) view.findViewById(R.id.tv_give_up);
        }
    }
}


text:
/* global __dirname */

function SubPage2() {}

module.exports = SubPage2;

SubPage2.exports = {
    view: __dirname,
    //style: __dirname,
    setup: function(app) {
        app.get(this.href, function(page, model, params, next) {
            page.renderAll();
        });
    }
};


text:
<?xml version="1.0" encoding="UTF-8"?>

<document
  xmlns="http://maven.apache.org/XDOC/2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>Releases</title>
  </properties>

        JIRA change log

        Manual change log

Apache Log4j 2 is not compatible with the previous versions. Please have the following in mind
        when upgrading to Log4j 2 in your project:

Log4j 2.4 and greater requires Java 7, versions 2.0-alpha1 to 2.3 required Java 6.

The XML configuration has been simplified and is not compatible with Log4j 1.x

Configuration via property files is supported from version 2.4, but is not compatible with Log4j 1.x.

Configuration via JSON or YAML is supported.

Although Log4j 2 is not directly compatible with Log4j 1.x a compatibility bridge
          has been provided to reduce the need to make coding changes.

</document>


text:
package org.jnosql.artemis.key.query;

import org.jnosql.artemis.Repository;
import org.jnosql.artemis.key.KeyValueRepositoryProducer;
import org.jnosql.artemis.key.KeyValueTemplate;
import org.jnosql.artemis.key.KeyValueTemplateProducer;
import org.jnosql.diana.api.key.BucketManager;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.lang.reflect.Proxy;
import java.util.Objects;

@ApplicationScoped
class DefaultKeyValueRepositoryProducer implements KeyValueRepositoryProducer {

    @Inject
    private KeyValueTemplateProducer producer;

    @Override
    public <E, ID, T extends Repository<E, ID>> T get(Class<T> repositoryClass, BucketManager manager) {
        Objects.requireNonNull(repositoryClass, "repository class is required");
        Objects.requireNonNull(manager, "manager class is required");
        KeyValueTemplate template = producer.get(manager);
        return get(repositoryClass, template);
    }

    @Override
    public <E, ID, T extends Repository<E, ID>> T get(Class<T> repositoryClass, KeyValueTemplate template) {
        Objects.requireNonNull(repositoryClass, "repository class is required");
        Objects.requireNonNull(template, "template class is required");

        KeyValueRepositoryProxy<T> handler = new KeyValueRepositoryProxy<>(repositoryClass, template);
        return (T) Proxy.newProxyInstance(repositoryClass.getClassLoader(),
                new Class[]{repositoryClass},
                handler);
    }
}


text:
<?php

/*
 * This file is part of the eluceo/iCal package.
 *
 * (c) 2022 Markus Poerschke <markus@poerschke.nrw>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Eluceo\iCal\Presentation\Component\Property\Value;

use DateInterval;
use DateTimeImmutable;
use Eluceo\iCal\Presentation\Component\Property\Value;

final class DurationValue extends Value
{
    private DateInterval $duration;

    public function __construct(DateInterval $duration)
    {
        $this->duration = $duration;
    }

    public function __toString(): string
    {
        $duration = $this->getNormalizedDateInterval();
        $durationAsString = $duration->invert === 1 ? '-P' : 'P';

        $days = abs($duration->days);
        if ($days > 0) {
            $durationAsString .= $days . 'D';
        }

        $hours = abs($duration->h);
        $minutes = abs($duration->i);
        $seconds = abs($duration->s);
        if ($hours > 0 || $minutes > 0 || $seconds > 0) {
            $durationAsString .= 'T';

            if ($hours > 0) {
                $durationAsString .= $hours . 'H';
            }

            if ($minutes > 0) {
                $durationAsString .= $minutes . 'M';
            }

            if ($seconds > 0) {
                $durationAsString .= $seconds . 'S';
            }
        }

        return $durationAsString;
    }

    /**
     * Normalizes the date interval.
     *
     * If the date interval is created from string,
     * then interval and days property are empty.
     *
     * Only date intervals that are created as a result from a diff
     * of two dates contains the correct values.
     *
     * @see https://www.php.net/manual/de/class.dateinterval.php
     */
    private function getNormalizedDateInterval(): DateInterval
    {
        $baseDate = (new DateTimeImmutable())->setTimestamp(0);
        $nextDate = $baseDate->sub($this->duration);

        return $nextDate->diff($baseDate);
    }
}


text:
using UnityEngine;
using System.Collections;

public class CueShootScript : MonoBehaviour {

    public GameObject LeftHand;
    public GameObject RightHand;

    SixenseHand LeftHandCode;
    SixenseHand RightHandCode;

    private Vector3 prevPosition;
    private Vector3 velocity;

    private Vector3 RightHandPrevPosition;

    bool positionLocked;
    public static bool resetting;

	// Use this for initialization
	void Start () {
        LeftHandCode = LeftHand.GetComponent<SixenseHand>();
        RightHandCode = RightHand.GetComponent<SixenseHand>();
        resetting = false;
	}

	// Update is called once per frame
    void Update()
    {
        positionLocked = false;
        if (RightHandCode.isActive)
        {
            if (LeftHandCode.m_controller.GetButton(SixenseButtons.TRIGGER))
            {
                transform.LookAt(GameObject.Find("Hand - Left").transform.position);
                if (RightHandCode.m_controller.GetButtonDown(SixenseButtons.TRIGGER))
                {
                    RightHandPrevPosition = RightHand.transform.position;
                }
                if (RightHandCode.m_controller.GetButton(SixenseButtons.TRIGGER))
                {
                    Vector3 RightHandInCueReferenceMovement = transform.InverseTransformDirection(RightHand.transform.position - RightHandPrevPosition);
                    transform.Translate(new Vector3(0, 0, RightHandInCueReferenceMovement.z));
                    positionLocked = true;
                    RightHandPrevPosition = RightHand.transform.position;
                    if (!resetting)
                        GetComponent<BoxCollider>().enabled = true;
                }
            }
            else
            {
                transform.localEulerAngles = RightHand.transform.eulerAngles + new Vector3(0, 270, 0);
                GetComponent<BoxCollider>().enabled = false;
            }

            if (RightHandCode.m_controller.GetButtonDown(SixenseButtons.THREE))
            {
                GameObject.Find("WhiteBall").transform.position = new Vector3(0, 1.026f, 0);
                GameObject.Find("WhiteBall").rigidbody.velocity = new Vector3(0, 0, 0);
                GameObject.Find("WhiteBall").rigidbody.angularVelocity = Vector3.zero;
            }
            if (!positionLocked)
            {
                transform.position = RightHand.transform.position;
            }
            velocity = (transform.position - prevPosition) / Time.deltaTime;
            prevPosition = transform.position;
        }
    }

    void OnCollisionEnter(Collision c)
    {
        c.rigidbody.AddForce((velocity / 1.5f) * 20);
        GetComponent<BoxCollider>().enabled = false;
        resetting = true;
    }
}


text:
layout: post
title: "Animations and Touch Events"
description: View animations vs property animations and touch events handling
modified:
categories: blog
author: florina_muntenescu
excerpt: Did you ever had problems with touch events on views after they were animated? Here's why.
tags: [Android, Animations, Touch Events, UI]
image:
date: 2016-05-20T15:39:55-04:00
---

Android offers two main animation frameworks: **view animation** and **property animation**. Each of these is fairly easy to implement. However, the main difference can be seen when you need to handle touch events on views that have changed their position after animation. Let's see how both of these animation frameworks work, how they can be implemented and which one you should use for touch events.

## Task
When tapping a ``View``, we need to translate it up by 75% of its height. When tapping on the area where the ``View`` was initially, our ``View`` should slide back down.

Translate a view up and down by 75%.

## View Animations

**View animations** provide an easy to use API for animating the contents of a view object. This framework supports translation, rotation, growing and shrinking of a view. You can define these animations either in XML or programmatically.

The implementation of the view translation animation in **XML** contains the following in the animation resource file:

{% highlight XML %}
<set android:fillAfter="true"
     android:shareInterpolator="false">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromAlpha="0.0"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toAlpha="1.0"
        android:toXDelta="0%"
        android:toYDelta="-75%" />
</set>
{% endhighlight %}

Then then animation needs to be loaded in the code.
{% highlight java %}
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.translate_up);
view.startAnimation(animation);
{% endhighlight %}

Translating a view **programmatically** requires defining the animation and just calling start on the view that needs to be animated.
{% highlight java %}
TranslateAnimation animation = new TranslateAnimation(0, 0, 0, toYDelta);
animation.setFillAfter(true);
animation.setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));
view.startAnimation(animation);
{% endhighlight %}
Where the ``toYDelta`` is the change in Y axis that needs to be applied.

## Property Animations

The **property animation** framework was introduced in Android 3.0 and allows the animation of any object, not just ``View``s. It offers a broader function scope - for example, the background color of a ``View`` can also be animated - and has a slightly better performance than the view animations.

Implementing a view translation can be easily done programmatically.
{% highlight java %}
view.animate().translationYBy(animateByPx);
{% endhighlight %}
Where the ``animateByPx`` is the amount of pixels the view is translated on the Y axis.

## Handling Touch Events

The main difference between view and property animations lies in whether the ``View`` is modified or not. With view animations, the ``View`` gets drawn in another position, but the actual ``View`` does not move. So, this means that the view will not react to touch events on the area where it is drawn, but rather in the area where it was before the animation started.
With property animations, the object actually gets moved. Therefore it will react to touch events on its new location on the screen.

For a better understanding on how the touch area changes, we have implemented a selector for our ``View``'s background, allowing us to set two different colors depending on the pressed state of the view: pink for pressed and blue for not pressed.

Here's what happens after translating the ``View`` using view animations: when touching the area that is above the original location of the ``View``, the ``View`` does not react. The touch events are caught by the area outside it.

Touch events on the new position of the view, after a view animation was applied.

When touching the area containing the initial position of the ``View``, we see that the area of the ``View``that is still drawn over the original position reacts to our touch events.

Touch events on the initial position of the view, after a view animation was applied.

With the property animations implementation we see that the ``View`` reacts to touch events exactly as expected, no matter where the touch events happen.

Touch events with property animations.

## Conclusion

Both view and property animations are easy to implement. Use the one that's more convenient for you, but when needing to implement touch events on a ``View`` that was already animated, you should use **property animations**.

Check out the implementation of view and property translation animations in this GitHub repo.
See the view animation and property animation Android API guides for detailed information.


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////

package gnu.trove.list;

//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////

import gnu.trove.function.*;
import gnu.trove.procedure.*;
import gnu.trove.TDoubleCollection;

import java.io.Serializable;
import java.util.Random;

/**
 * Interface for Trove list implementations.
 */
public interface TDoubleList extends TDoubleCollection {
    /**
     * Returns the value that is used to represent null. The default
     * value is generally zero, but can be changed during construction
     * of the collection.
     *
     * @return the value that represents null
     */
    public double getNoEntryValue();

    /**
     * Returns the number of values in the list.
     *
     * @return the number of values in the list.
     */
    public int size();

    /**
     * Tests whether this list contains any values.
     *
     * @return true if the list is empty.
     */
    public boolean isEmpty();

    /**
     * Adds <tt>val</tt> to the end of the list, growing as needed.
     *
     * @param val an double value
     * @return true if the list was modified by the add operation
     */
    public boolean add(double val);

    /**
     * Adds the values in the array <tt>vals</tt> to the end of the
     * list, in order.
     *
     * @param vals an double[] value
     */
    public void add( double[] vals );

    /**
     * Adds a subset of the values in the array <tt>vals</tt> to the
     * end of the list, in order.
     *
     * @param vals an double[] value
     * @param offset the offset at which to start copying
     * @param length the number of values to copy.
     */
    public void add( double[] vals, int offset, int length );

   /**
     * Inserts <tt>value</tt> into the list at <tt>offset</tt>.  All
     * values including and to the right of <tt>offset</tt> are shifted
     * to the right.
     *
     * @param offset an int value
     * @param value an double value
     */
    public void insert( int offset, double value );

    /**
     * Inserts the array of <tt>values</tt> into the list at
     * <tt>offset</tt>.  All values including and to the right of
     * <tt>offset</tt> are shifted to the right.
     *
     * @param offset an int value
     * @param values an double[] value
     */
    public void insert( int offset, double[] values );

    /**
     * Inserts a slice of the array of <tt>values</tt> into the list
     * at <tt>offset</tt>.  All values including and to the right of
     * <tt>offset</tt> are shifted to the right.
     *
     * @param offset an int value
     * @param values an double[] value
     * @param valOffset the offset in the values array at which to
     * start copying.
     * @param len the number of values to copy from the values array
     */
    public void insert( int offset, double[] values, int valOffset, int len );

    /**
     * Returns the value at the specified offset.
     *
     * @param offset an int value
     * @return an double value
     */
    public double get( int offset );

    /**
     * Sets the value at the specified offset.
     *
     * @param offset an int value
     * @param val an double value
	 *
	 * @return	The value previously at the given index.
     */
    public double set( int offset, double val );

    /**
     * Replace the values in the list starting at <tt>offset</tt> with
     * the contents of the <tt>values</tt> array.
     *
     * @param offset the first offset to replace
     * @param values the source of the new values
     */
    public void set( int offset, double[] values );

    /**
     * Replace the values in the list starting at <tt>offset</tt> with
     * <tt>length</tt> values from the <tt>values</tt> array, starting
     * at valOffset.
     *
     * @param offset the first offset to replace
     * @param values the source of the new values
     * @param valOffset the first value to copy from the values array
     * @param length the number of values to copy
     */
    public void set( int offset, double[] values, int valOffset, int length );

    /**
     * Sets the value at the specified offset and returns the
     * previously stored value.
     *
     * @param offset an int value
     * @param val an double value
     * @return the value previously stored at offset.
     */
    public double replace( int offset, double val );

    /**
     * Flushes the internal state of the list, resetting the capacity
     * to the default.
     */
    public void clear();

    /**
     * Removes <tt>value</tt> from the list.
     *
     * @param value an double value
     * @return true if the list was modified by the remove operation.
     */
    public boolean remove( double value );

    /**
     * Removes <tt>value</tt> at a given offset from the list.
     *
     * @param offset an int value that represents
     *               the offset to the element to be removed
     * @return an <tt>double</tt> that is the value removed.
     */
    public double removeAt( int offset );

    /**
     * Removes <tt>length</tt> values from the list, starting at
     * <tt>offset</tt>
     *
     * @param offset an int value
     * @param length an int value
     */
    public void remove( int offset, int length );

    /**
     * Transform each value in the list using the specified function.
     *
     * @param function a TDoubleFunction value
     */
    public void transformValues( TDoubleFunction function );

    /**
     * Reverse the order of the elements in the list.
     */
    public void reverse();

    /**
     * Reverse the order of the elements in the range of the list.
     *
     * @param from the inclusive index at which to start reversing
     * @param to the exclusive index at which to stop reversing
     */
    public void reverse( int from, int to );

    /**
     * Shuffle the elements of the list using the specified random
     * number generator.
     *
     * @param rand a Random value
     */
    public void shuffle( Random rand );

    /**
     * Returns a sublist of this list.
     *
     * @param begin low endpoint (inclusive) of the subList.
     * @param end high endpoint (exclusive) of the subList.
     * @return sublist of this list from begin, inclusive to end, exclusive.
     * @throws IndexOutOfBoundsException - endpoint out of range
     * @throws IllegalArgumentException - endpoints out of order (end > begin)
     */
    public TDoubleList subList( int begin, int end );

    /**
     * Copies the contents of the list into a native array.
     *
     * @return an double[] value
     */
    public double[] toArray();

    /**
     * Copies a slice of the list into a native array.
     *
     * @param offset the offset at which to start copying
     * @param len the number of values to copy.
     * @return an double[] value
     */
    public double[] toArray( int offset, int len );

    /**
     * Copies a slice of the list into a native array.
     *
     *
If the list fits in the specified array with room to spare (i.e.,
     * the array has more elements than the list), the element in the array
     * immediately following the end of the list is set to
     * <tt>{@link #getNoEntryValue()}</tt>.
     * (This is useful in determining the length of the list only if
     * the caller knows that the list does not contain any "null" elements.)
     *
     *
NOTE: Trove does not allocate a new array if the array passed in is
     * not large enough to hold all of the data elements.  It will instead fill
     * the array passed in.
     *
     * @param dest the array to copy into.
     * @return the array passed in.
     */
    public double[] toArray( double[] dest );

    /**
     * Copies a slice of the list into a native array.
     *
     * @param dest the array to copy into.
     * @param offset the offset where the first value should be copied
     * @param len the number of values to copy.
     * @return the array passed in.
     */
    public double[] toArray( double[] dest, int offset, int len );

    /**
     * Copies a slice of the list into a native array.
     *
     * @param dest the array to copy into.
     * @param source_pos the offset of the first value to copy
     * @param dest_pos the offset where the first value should be copied
     * @param len the number of values to copy.
     * @return the array passed in.
     */
    public double[] toArray( double[] dest, int source_pos, int dest_pos, int len );

    /**
     * Applies the procedure to each value in the list in ascending
     * (front to back) order.
     *
     * @param procedure a TDoubleProcedure value
     * @return true if the procedure did not terminate prematurely.
     */
    public boolean forEach( TDoubleProcedure procedure );

    /**
     * Applies the procedure to each value in the list in descending
     * (back to front) order.
     *
     * @param procedure a TDoubleProcedure value
     * @return true if the procedure did not terminate prematurely.
     */
    public boolean forEachDescending( TDoubleProcedure procedure );

    /**
     * Sort the values in the list (ascending) using the Sun quicksort
     * implementation.
     *
     * @see java.util.Arrays#sort
     */
    public void sort();

    /**
     * Sort a slice of the list (ascending) using the Sun quicksort
     * implementation.
     *
     * @param fromIndex the index at which to start sorting (inclusive)
     * @param toIndex the index at which to stop sorting (exclusive)
     * @see java.util.Arrays#sort
     */
    public void sort( int fromIndex, int toIndex );

    /**
     * Fills every slot in the list with the specified value.
     *
     * @param val the value to use when filling
     */
    public void fill( double val );

    /**
     * Fills a range in the list with the specified value.
     *
     * @param fromIndex the offset at which to start filling (inclusive)
     * @param toIndex the offset at which to stop filling (exclusive)
     * @param val the value to use when filling
     */
    public void fill( int fromIndex, int toIndex, double val );

    /**
     * Performs a binary search for <tt>value</tt> in the entire list.
     * Note that you must @{link #sort sort} the list before
     * doing a search.
     *
     * @param value the value to search for
     * @return the absolute offset in the list of the value, or its
     * negative insertion point into the sorted list.
     */
    public int binarySearch( double value );

    /**
     * Performs a binary search for <tt>value</tt> in the specified
     * range.  Note that you must @{link #sort sort} the list
     * or the range before doing a search.
     *
     * @param value the value to search for
     * @param fromIndex the lower boundary of the range (inclusive)
     * @param toIndex the upper boundary of the range (exclusive)
     * @return the absolute offset in the list of the value, or its
     * negative insertion point into the sorted list.
     */
    public int binarySearch( double value, int fromIndex, int toIndex );

    /**
     * Searches the list front to back for the index of
     * <tt>value</tt>.
     *
     * @param value an double value
     * @return the first offset of the value, or -1 if it is not in
     * the list.
     * @see #binarySearch for faster searches on sorted lists
     */
    public int indexOf( double value );

    /**
     * Searches the list front to back for the index of
     * <tt>value</tt>, starting at <tt>offset</tt>.
     *
     * @param offset the offset at which to start the linear search
     * (inclusive)
     * @param value an double value
     * @return the first offset of the value, or -1 if it is not in
     * the list.
     * @see #binarySearch for faster searches on sorted lists
     */
    public int indexOf( int offset, double value );

    /**
     * Searches the list back to front for the last index of
     * <tt>value</tt>.
     *
     * @param value an double value
     * @return the last offset of the value, or -1 if it is not in
     * the list.
     * @see #binarySearch for faster searches on sorted lists
     */
    public int lastIndexOf( double value );

    /**
     * Searches the list back to front for the last index of
     * <tt>value</tt>, starting at <tt>offset</tt>.
     *
     * @param offset the offset at which to start the linear search
     * (exclusive)
     * @param value an double value
     * @return the last offset of the value, or -1 if it is not in
     * the list.
     * @see #binarySearch for faster searches on sorted lists
     */
    public int lastIndexOf( int offset, double value );

    /**
     * Searches the list for <tt>value</tt>
     *
     * @param value an double value
     * @return true if value is in the list.
     */
    public boolean contains( double value );

    /**
     * Searches the list for values satisfying <tt>condition</tt> in
     * the manner of the *nix <tt>grep</tt> utility.
     *
     * @param condition a condition to apply to each element in the list
     * @return a list of values which match the condition.
     */
    public TDoubleList grep( TDoubleProcedure condition );

    /**
     * Searches the list for values which do not satisfy
     * <tt>condition</tt>.  This is akin to *nix grep -v.
     *
     * @param condition a condition to apply to each element in the list
     * @return a list of values which do not match the condition.
     */
    public TDoubleList inverseGrep( TDoubleProcedure condition );

    /**
     * Finds the maximum value in the list.
     *
     * @return the largest value in the list.
     * @exception IllegalStateException if the list is empty
     */
    public double max();

    /**
     * Finds the minimum value in the list.
     *
     * @return the smallest value in the list.
     * @exception IllegalStateException if the list is empty
     */
    public double min();
}


text:
'use strict';
/* Global let Declarations */
var app = app || {};
(function(module){

  let schools = [];
  let projects = [];

  $('#portfolio').on('click', showProjects);
  function showProjects(){
    $('.content section').hide();
    $('.projects').show();
  }
  $('#education').on('click', showEducation);
  function showEducation(){
    $('.content section').hide();
    $('.education').show();
  }
  $('#home').on('click', showAll);
  function showAll() {
    $('.content section').show();
  }

  $('.hamburger').on('click', showNav);
  function showNav(){
    $('nav section').toggle(400);
  }

  function Project(projectObj){
    this.name = projectObj.title;
    this.url = projectObj.url;
    this.about = projectObj.about;
  }

  function School(schoolObj) {
    this.name = schoolObj.name;
    this.startDate = schoolObj.startDate;
    this.endDate = schoolObj.endDate;
    this.award = schoolObj.award;
  }

  Project.prototype.toHTML = function(){
    let content = Handlebars.compile($('#project-template').html());
    return content(this);
  }
  School.prototype.toHTML = function(){
    let content = Handlebars.compile($('#school-template').html());
    return content(this);
  }
  function render(dataArray){
    dataArray.forEach(function(singleData){
      $('.content').append(singleData.toHTML());
    });
  }
  if (localStorage.projectData){
    JSON.parse(localStorage.projectData).forEach(function(object){ projects.push(new Project(object)); });
    render(projects);
  }else {
    $.get('data/projects.json', function(result){
      localStorage.setItem('projectData', JSON.stringify(result));
      projects = result.map(function(obj){
        return new Project(obj)
      });
      render(projects);
    });
  }
  if (localStorage.schoolData){
    JSON.parse(localStorage.schoolData).forEach(function(object){schools.push(new School(object)); });
    render(schools);
  }else {
    $.get('data/schools.json', function(result){
      localStorage.setItem('schoolData', JSON.stringify(result));
      result.forEach(function(object){
        schools.push(new School(object));
      });
      render(schools);
    });
  }
  let projectWordCount = () => {
    return projects
        .map((project) => project.about.split(' '))
        .reduce((sum, words) => {
          return sum + words.length;
        }, 0);
  }
  $('.content').append(`<p> Project word count: ${projectWordCount()}`);

})(app)


text:
..
    Warning: Do not edit this file. It is automatically generated from the
    software project's code and your changes will be overwritten.

    The tool to generate this file lives in openstack-doc-tools repository.

    Please make any changes needed in the code, then run the
    autogenerate-config-doc tool from the openstack-doc-tools repository, or
    ask for help on the documentation mailing list, IRC channel or meeting.

.. _ironic-glance:

.. list-table:: Description of glance configuration options
   :header-rows: 1
   :class: config-ref-table

   * - Configuration option = Default value
     - Description
   * - **[glance]**
     -
   * - ``allowed_direct_url_schemes`` =
     - (List) A list of URL schemes that can be downloaded directly via the direct_url. Currently supported schemes: [file].
   * - ``auth_strategy`` = ``keystone``
     - (String) Authentication strategy to use when connecting to glance.
   * - ``glance_api_insecure`` = ``False``
     - (Boolean) Allow to perform insecure SSL (https) requests to glance.
   * - ``glance_api_servers`` = ``None``
     - (List) A list of the glance api servers available to ironic. Prefix with https:// for SSL-based glance API servers. Format is [hostname|IP]:port.
   * - ``glance_cafile`` = ``None``
     - (String) Optional path to a CA certificate bundle to be used to validate the SSL certificate served by glance. It is used when glance_api_insecure is set to False.
   * - ``glance_host`` = ``$my_ip``
     - (String) Default glance hostname or IP address.
   * - ``glance_num_retries`` = ``0``
     - (Integer) Number of retries when downloading an image from glance.
   * - ``glance_port`` = ``9292``
     - (Port number) Default glance port.
   * - ``glance_protocol`` = ``http``
     - (String) Default protocol to use when connecting to glance. Set to https for SSL.
   * - ``swift_account`` = ``None``
     - (String) The account that Glance uses to communicate with Swift. The format is "AUTH_uuid". "uuid" is the UUID for the account configured in the glance-api.conf. Required for temporary URLs when Glance backend is Swift. For example: "AUTH_a422b2-91f3-2f46-74b7-d7c9e8958f5d30". Swift temporary URL format: "endpoint_url/api_version/[account/]container/object_id"
   * - ``swift_api_version`` = ``v1``
     - (String) The Swift API version to create a temporary URL for. Defaults to "v1". Swift temporary URL format: "endpoint_url/api_version/[account/]container/object_id"
   * - ``swift_container`` = ``glance``
     - (String) The Swift container Glance is configured to store its images in. Defaults to "glance", which is the default in glance-api.conf. Swift temporary URL format: "endpoint_url/api_version/[account/]container/object_id"
   * - ``swift_endpoint_url`` = ``None``
     - (String) The "endpoint" (scheme, hostname, optional port) for the Swift URL of the form "endpoint_url/api_version/[account/]container/object_id". Do not include trailing "/". For example, use "https://swift.example.com". If using RADOS Gateway, endpoint may also contain /swift path; if it does not, it will be appended. Required for temporary URLs.
   * - ``swift_store_multiple_containers_seed`` = ``0``
     - (Integer) This should match a config by the same name in the Glance configuration file. When set to 0, a single-tenant store will only use one container to store all images. When set to an integer value between 1 and 32, a single-tenant store will use multiple containers to store images, and this value will determine how many containers are created.
   * - ``swift_temp_url_cache_enabled`` = ``False``
     - (Boolean) Whether to cache generated Swift temporary URLs. Setting it to true is only useful when an image caching proxy is used. Defaults to False.
   * - ``swift_temp_url_duration`` = ``1200``
     - (Integer) The length of time in seconds that the temporary URL will be valid for. Defaults to 20 minutes. If some deploys get a 401 response code when trying to download from the temporary URL, try raising this duration. This value must be greater than or equal to the value for swift_temp_url_expected_download_start_delay
   * - ``swift_temp_url_expected_download_start_delay`` = ``0``
     - (Integer) This is the delay (in seconds) from the time of the deploy request (when the Swift temporary URL is generated) to when the IPA ramdisk starts up and URL is used for the image download. This value is used to check if the Swift temporary URL duration is large enough to let the image download begin. Also if temporary URL caching is enabled this will determine if a cached entry will still be valid when the download starts. swift_temp_url_duration value must be greater than or equal to this option's value. Defaults to 0.
   * - ``swift_temp_url_key`` = ``None``
     - (String) The secret token given to Swift to allow temporary URL downloads. Required for temporary URLs.
   * - ``temp_url_endpoint_type`` = ``swift``
     - (String) Type of endpoint to use for temporary URLs. If the Glance backend is Swift, use "swift"; if it is CEPH with RADOS gateway, use "radosgw".


text:
const possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

/**
 * @param  {number=10} length
 * @returns string
 */
export function randomString(length: number = 10): string
{
  let text: string = '';
  for(var i = 0; i < length; i++) {
    text += possibleChars.charAt(
      Math.floor(Math.random() * possibleChars.length)
    );
  }

  return text;
}

/**
 */
export function generateId()
{
  return randomString() + (new Date().getTime());
};


text:
//
//  FlashCardFrontSideController.m
//  FlashCards
//
//  Created by Raul Chacon on 12/4/11.
//  Copyright (c) 2011 Student. All rights reserved.
//

#import "FlashCardFrontSideController.h"
#import "FlashCardBackSideController.h"
#import "FlashCardListController.h"
#import "DatabaseModel.h"
#import "FlashCardModel.h"
#import "WebViewController.h"

@implementation FlashCardFrontSideController
@synthesize frontSideLabel, stringForFrontSideToPassToBackSide, listView, subjectTitleFromFlashCardList, flashCardPosition, flashCards, databaseModel, backSideController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// set definition of flash card for rear side of flash card
- (void) setTextForBackSideController
{
    NSLog(@"setTextForBackSideController");
    self.backSideController = [self.storyboard instantiateViewControllerWithIdentifier:@"FlashCardBackSideController"];

    if(self.backSideController.backSideString == nil)
    {
        self.backSideController.backSideString = [[NSMutableString alloc] init ];
    }

    [self.backSideController.backSideString setString:self.stringForFrontSideToPassToBackSide];
}

// push to flash card back side controller with custom animation
- (void) flipToBackSide
{
    [self setTextForBackSideController];

    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:0.80];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];

    [self.navigationController pushViewController:backSideController animated:NO];
    [UIView commitAnimations];
}

// get all flash cards for current subject in order to have access to them for swiping
- (void) getSimilarFlashCards
{
    // get all flash cards for current subject
    int parentSubjectId = [self.databaseModel selectIdFromSubjectsWhere:self.subjectTitleFromFlashCardList];
    self.flashCards = [self.databaseModel selectAllFromFlashCardsWhereIsHidden:0 subjectId:parentSubjectId];
}

// Show previous flash card after swipe gesture
- (void) showPreviousFlashCard
{
    [self getSimilarFlashCards];

    if(self.flashCardPosition != 0)
    {
        //[self getFlashCardsForSwiping: @"previous"];
        self.flashCardPosition = self.flashCardPosition - 1;

        // update question text
        self.frontSideLabel.text = [[self.flashCards objectAtIndex:self.flashCardPosition] title];

        [UIView beginAnimations:@"View Flip" context:nil];
        [UIView setAnimationDuration:0.80];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        [UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];

        // update answer text
        [self.stringForFrontSideToPassToBackSide setString:[[self.flashCards objectAtIndex:self.flashCardPosition] getDefinition]];

        // update text for back side controller
        [self setTextForBackSideController];

        [UIView commitAnimations];
    }

}

// Show next flash card after swipe gesture
- (void) showNextFlashCard
{
    [self getSimilarFlashCards];

    NSLog(@"CURRENT POSITION %d == %d", self.flashCardPosition, self.flashCards.count);

    if(self.flashCardPosition != self.flashCards.count - 1)
    {
        //[self getFlashCardsForSwiping: @"next"];
        self.flashCardPosition = self.flashCardPosition + 1;

        // update question text
        self.frontSideLabel.text = [[self.flashCards objectAtIndex:self.flashCardPosition] title];

        [UIView beginAnimations:@"View Flip" context:nil];
        [UIView setAnimationDuration:0.80];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        [UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:NO];

        // update answer text
        [self.stringForFrontSideToPassToBackSide setString:[[self.flashCards objectAtIndex:self.flashCardPosition] getDefinition]];

        // update text for back side controller
        [self setTextForBackSideController];

        [UIView commitAnimations];
    }
}

// add swipe left, right and double tap gestures to view
-(void) addGestures
{
    // create swipe left gesture recognizer
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(showPreviousFlashCard)];
    swipeLeft.numberOfTouchesRequired = 1;
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeLeft];

    // create swipe right gesture recognizer
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(showNextFlashCard)];
    swipeRight.numberOfTouchesRequired = 1;
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipeRight];

    // add double tap gesture recognizer to switch to back side controller
    UITapGestureRecognizer *doubleTap =
    [[UITapGestureRecognizer alloc]
     initWithTarget:self
     action:@selector(flipToBackSide)];
    doubleTap.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:doubleTap];

}

// ensure navigation bar shows up since it is hidden on back side controller
- (void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Question";

    [self addGestures];

    // set background image
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"IndexCard.png"]];
    self.view.backgroundColor = background;

    // get reference to flash card list controller
    if(self.databaseModel == nil)
    {
        databaseModel = [[DatabaseModel alloc]init];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// set data in segue destination controller
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    NSLog(@"segue identifier is: %@", [segue identifier]);

    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"pushToWikipedia"])
    {
        // Get reference to the destination view controller
        WebViewController *webViewController = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        webViewController.flashCardTitle = [[NSMutableString alloc]init ];
        [webViewController.flashCardTitle setString: self.frontSideLabel.text];
    }
}

@end


text:
package org.apache.commons.jcs.auxiliary.lateral.socket.tcp;

import java.util.Random;

import junit.framework.TestCase;

import org.apache.commons.jcs.JCS;
import org.apache.commons.jcs.access.CacheAccess;
import org.apache.commons.jcs.engine.CacheElement;
import org.apache.commons.jcs.engine.behavior.ICacheElement;

/**
 * Tests the issue remove on put fuctionality.
 * @author asmuts
 */
public class LateralTCPIssueRemoveOnPutUnitTest
    extends TestCase
{
    /** Should log data go to system out. */
    private static boolean isSysOut = true;

    /** The port the server will listen to. */
    private final int serverPort = 1118;

    /**
     * Constructor for the TestDiskCache object.
     *

     * @param testName
     */
    public LateralTCPIssueRemoveOnPutUnitTest( String testName )
    {
        super( testName );
    }

    /**
     * Test setup
     */
    @Override
    public void setUp()
    {
        System.setProperty( "jcs.auxiliary.LTCP.attributes.TcpServers", "localhost:" + serverPort );

        JCS.setConfigFilename( "/TestTCPLateralIssueRemoveCache.ccf" );
    }

    /**
     * @throws Exception
     */
    public void testPutLocalPutRemoteGetBusyVerifyRemoved()
        throws Exception
    {
        this.runTestForRegion( "region1", 1, 200, 1 );
    }

    /**
     * Verify that a standard put works. Get the cache configured from a file. Create a tcp service
     * to talk to that cache. Put via the service. Verify that the cache got the data.
     *

     * @throws Exception
     */
    public void testStandardPut()
        throws Exception
    {
        String region = "region1";

        CacheAccess<String, String> cache = JCS.getInstance( region );

        Thread.sleep( 100 );

        TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes();
        lattr2.setTcpListenerPort( 1102 );
        lattr2.setTransmissionTypeName( "TCP" );
        lattr2.setTcpServer( "localhost:" + serverPort );
        lattr2.setIssueRemoveOnPut( false );
        // should still try to remove
        // lattr2.setAllowPut( false );

        // Using the lateral, this service will put to and remove from
        // the cache instance above.
        // The cache thinks it is different since the listenerid is different
        LateralTCPService<String, String> service = new LateralTCPService<String, String>( lattr2 );
        service.setListenerId( 123456 );

        String keyToBeRemovedOnPut = "test1_notremoved";

        ICacheElement<String, String> element1 = new CacheElement<String, String>( region, keyToBeRemovedOnPut, region
            + ":data-this shouldn't get removed, it should get to the cache." );
        service.update( element1 );

        Thread.sleep( 1000 );

        Object testObj = cache.get( keyToBeRemovedOnPut );
        p( "testStandardPut, test object = " + testObj );
        assertNotNull( "The test object should not have been removed by a put.", testObj );
    }

    /**
     * This tests issues tons of puts. It also check to see that a key that was put in was removed
     * by the clients remove command.
     *

     * @param region Name of the region to access
     * @param range
     * @param numOps
     * @param testNum
     * @exception Exception If an error occurs
     */
    public void runTestForRegion( String region, int range, int numOps, int testNum )
        throws Exception
    {

        boolean show = true;// false;

        CacheAccess<String, String> cache = JCS.getInstance( region );

        Thread.sleep( 100 );

        TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes();
        lattr2.setTcpListenerPort( 1102 );
        lattr2.setTransmissionTypeName( "TCP" );
        lattr2.setTcpServer( "localhost:" + serverPort );
        lattr2.setIssueRemoveOnPut( true );
        // should still try to remove
        lattr2.setAllowPut( false );

        // Using the lateral, this service will put to and remove from
        // the cache instance above.
        // The cache thinks it is different since the listenerid is different
        LateralTCPService<String, String> service = new LateralTCPService<String, String>( lattr2 );
        service.setListenerId( 123456 );

        String keyToBeRemovedOnPut = "test1";
        cache.put( keyToBeRemovedOnPut, "this should get removed." );

        ICacheElement<String, String> element1 = new CacheElement<String, String>( region, keyToBeRemovedOnPut, region
            + ":data-this shouldn't get there" );
        service.update( element1 );

        try
        {
            for ( int i = 1; i < numOps; i++ )
            {
                Random ran = new Random( i );
                int n = ran.nextInt( 4 );
                int kn = ran.nextInt( range );
                String key = "key" + kn;

                ICacheElement<String, String> element = new CacheElement<String, String>( region, key, region + ":data" + i
                    + " junk asdfffffffadfasdfasf " + kn + ":" + n );
                service.update( element );
                if ( show )
                {
                    p( "put " + key );
                }

                if ( i % 100 == 0 )
                {
                    System.out.println( cache.getStats() );
                }

            }
            p( "Finished cycle of " + numOps );
        }
        catch ( Exception e )
        {
            p( e.toString() );
            e.printStackTrace( System.out );
            throw e;
        }

        CacheAccess<String, String> jcs = JCS.getInstance( region );
        String key = "testKey" + testNum;
        String data = "testData" + testNum;
        jcs.put( key, data );
        String value = jcs.get( key );
        assertEquals( "Couldn't put normally.", data, value );

        // make sure the items we can find are in the correct region.
        for ( int i = 1; i < numOps; i++ )
        {
            String keyL = "key" + i;
            String dataL = jcs.get( keyL );
            if ( dataL != null )
            {
                assertTrue( "Incorrect region detected.", dataL.startsWith( region ) );
            }

        }

        Thread.sleep( 200 );

        Object testObj = cache.get( keyToBeRemovedOnPut );
        p( "runTestForRegion, test object = " + testObj );
        assertNull( "The test object should have been removed by a put.", testObj );

    }

    /**
     * @param s String to be printed
     */
    public static void p( String s )
    {
        if ( isSysOut )
        {
            System.out.println( s );
        }
    }
}


text:
require_relative '../genetic_algorithm'
require_relative '../tree'

# Proof-of-concept genetic algorithm that scrambles a tree and tries to
# achieve the original structure.
#
class RnaSec::GeneticAlgorithm::Runner

  # @param [RnaSec::Tree::Root] src Fully-populated tree
  # @param [Fixnum] popsize   Desired population size
  # @param [Float]  terminate % of population that must be equal to the source
  # @param [Float]  mutation  % of population to mutate
  # @param [Fixnum]  submutation  # of times to mutate mutants
  #
  def initialize(src, popsize, terminate, mutation, submutation)
    @src       = src
    @srcpos    = src.get_child_positions()
    @popsize   = popsize
    @terminate = terminate
    @mutation  = mutation
    @submutation = submutation
  end

  # Run the genetic algorithm.
  #
  # == Algorithm
  #
  # 1. Create initial random population
  #
  # 2. Loop:
  #    a. Perform random point mutations on a percentage of the population.
  #       This increases the population size.
  #    b. Get the fitness of the population
  #    c. Greedily select the most fit until the population has been reduced.
  #    d. See how many are equal to the original
  #    e. Terminate if terminating condition has been met
  #
  # @return [void]
  #
  def run
    population = create_initial_pop()

    i = 0
    while true
      # mutate
      to_mut = population.sample(@mutation * @popsize)
      to_mut.each do |t|
        mutant = RnaSec::GeneticAlgorithm::Operators.point_mutation(t)
        @submutation.times do
          mutant = RnaSec::GeneticAlgorithm::Operators.point_mutation(mutant)
        end
        population << mutant
      end

      # get fitness of the population
      fits   = fitness_pop(population)
      sorted = sort_by_fitness(population, fits)

      # greedily select the top performers
      population = sorted.take(@popsize)

      # re-evaluate fitnesses (for ordering)
      fits = fitness_pop(population)

      # determine how many are identical to @src
      eql_to_orig = 0
      fits.each do |f|
        eql_to_orig += 1 if f == 0
      end

      puts "generation #{i}, #{eql_to_orig}/#{@popsize} are the original"
      if eql_to_orig >= (@terminate * @popsize)
        puts ">=#{@terminate * 100} are equal"
        break
      end

      i += 1
    end
  end

  private

  # Returns a randomized initial population.
  #
  # @return [RnaSec::Tree::Root[]]
  #
  def create_initial_pop
    population = []

    until population.size == @popsize
      population << scramble_tree(@src, @src.size)
    end

    population
  end

  # Randomizes parts of a tree by removing elements and inserting them
  # randomly.
  #
  # @param [RnaSec::Tree::Root] tree  Tree structure
  # @param [Fixnum]             n     Number of nodes to scramble
  #
  # @return [RnaSec::Tree::Root] Randomized tree.
  #
  def scramble_tree(tree, n)
    mutated = tree.clone()
    n.times do
      mutated = RnaSec::GeneticAlgorithm::Operators::point_mutation(mutated)
    end

    mutated
  end

  # Returns the fitness of a single tree compared to the original.
  #
  # This takes the source's nucleotide positions and compares them to
  # the current <tt>tree</tt>. For every mismatch, a -1 is added to the
  # score. A score of 0 indicates the tree is identical to the original.
  #
  # @param [RnaSec::Tree::Root] tree
  # @return [Fixnum]
  #
  def fitness(tree)
    poss = tree.get_child_positions()
    score = 0

    poss.zip(@srcpos) do |pos, src|
      score -= 1 if pos != src
    end

    score
  end

  # Returns the fitness of an entire population.
  #
  # @param [RnaSec::Tree::Root[]] pop Population of Root trees
  # @return [Fixnum[]]
  #
  def fitness_pop(pop)
    fitnesses = []
    pop.each do |p|
      fitnesses << fitness(p)
    end

    fitnesses
  end

  # Returns the population sorted by fitness.
  #
  # @param [RnaSec::Tree::Root[]] pop
  # @param [Fixnum[]] fitnesses
  # @return [RnaSec::Tree::Root[]]
  #
  def sort_by_fitness(pop, fitnesses)
    h = {}
    pop.each_with_index { |p, i| h[p] = fitnesses[i] }
    sorted = h.sort { |a, b| b[1] <=> a[1] } # descending order

    # restore back from [ [:foo, 2], [:bar, 3]] => [:foo, :bar]
    sorted.map { |x| x[0] }
  end

end


text:
<?php

/**
 * Description of BootstrapTests
 *
 * @author seyfer
 */

use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);

/**
 * Test bootstrap, for setting up autoloading
 */
class BootstrapTests
{

    static $modulesToInclude = [];
    static $modulesToTest = ['ZendMover'];

    /**
     * @var ServiceManager
     */
    protected static $serviceManager;

    /**
     * @return ServiceManager
     */
    public static function getServiceManager()
    {
        return static::$serviceManager;
    }

    /**
     *
     */
    public static function init()
    {
        error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING | E_STRICT);
        chdir(__DIR__);

        $zf2ModulePaths = [dirname(dirname(__DIR__))];
        if (($path = static::findParentPath('vendor'))) {
            $zf2ModulePaths[] = $path;
        }
        if (($path = static::findParentPath('module')) !== $zf2ModulePaths[0]) {
            $zf2ModulePaths[] = $path;
        }

        static::initAutoloader();

        $modules = array_merge(self::$modulesToInclude, self::$modulesToTest);
        // use ModuleManager to load this module and it's dependencies
        $config = [
            'module_listener_options' => [
                'module_paths' => $zf2ModulePaths,
                'config_glob_paths' => [
                    dirname(dirname(dirname(__DIR__))) . '/config/autoload/{,*.}{global,local}.php',
                ],
            ],
            'modules' => $modules,
        ];

        $serviceManager = new ServiceManager(new ServiceManagerConfig());
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();

        static::$serviceManager = $serviceManager;
    }

    /**
     *
     */
    public static function chroot()
    {
        $rootPath = dirname(static::findParentPath('module'));
        chdir($rootPath);
    }

    /**
     *
     */
    protected static function initAutoloader()
    {
        $vendorPath = static::findParentPath('vendor');

        $zf2Path = getenv('ZF2_PATH');
        if (!$zf2Path) {
            if (defined('ZF2_PATH')) {
                $zf2Path = ZF2_PATH;
            } elseif (is_dir($vendorPath . '/ZF2/library')) {
                $zf2Path = $vendorPath . '/ZF2/library';
            } elseif (is_dir($vendorPath . '/zendframework/zendframework/library')) {
                $zf2Path = $vendorPath . '/zendframework/zendframework/library';
            }
        }

        if (!$zf2Path) {
            throw new \RuntimeException(
                'Unable to load ZF2. Run `php composer.phar install` or'
                . ' define a ZF2_PATH environment variable.'
            );
        }

        if (file_exists($vendorPath . '/autoload.php')) {
            include $vendorPath . '/autoload.php';
        }

        $namespaces = [
            __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
        ];

        //find all modules tests foler and namespace
        $modulesPath = self::findParentPath('module');
        foreach (self::$modulesToTest as $moduleToTest) {
            $moduleToTestName = $moduleToTest . "Test";
            $namespaces = array_merge($namespaces, [
                $moduleToTestName => $modulesPath . DIRECTORY_SEPARATOR . $moduleToTest . DIRECTORY_SEPARATOR .
                    'tests' . DIRECTORY_SEPARATOR . $moduleToTestName,
            ]);
        }

        include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
        AutoloaderFactory::factory([
            'Zend\Loader\StandardAutoloader' => [
                'autoregister_zf' => true,
                'namespaces' => $namespaces,
            ],
        ]);
    }

    /**
     * @param $path
     * @return bool|string
     */
    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) {
                return false;
            }
            $previousDir = $dir;
        }

        return $dir . '/' . $path;
    }

}

BootstrapTests::init();
BootstrapTests::chroot();


text:
namespace ospray {
namespace mpi {
using namespace std::chrono;
using namespace mpicommon;

static bool DETAILED_LOGGING = false;

// DistributedRaycastRenderer definitions /////////////////////////////////

DistributedRaycastRenderer::DistributedRaycastRenderer()
    : mpiGroup(mpicommon::worker.dup())
{
  ispcEquivalent = ispc::DistributedRaycastRenderer_create(this);

  DETAILED_LOGGING =
      utility::getEnvVar<int>("OSPRAY_DP_API_TRACING").value_or(0);

  if (DETAILED_LOGGING) {
    auto job_name =
        utility::getEnvVar<std::string>("OSPRAY_JOB_NAME").value_or("log");
    std::string statsLogFile = job_name + std::string("-rank")
        + std::to_string(mpiGroup.rank) + ".txt";
    statsLog = rkcommon::make_unique<std::ofstream>(statsLogFile.c_str());
  }
}

DistributedRaycastRenderer::~DistributedRaycastRenderer()
{
  if (DETAILED_LOGGING) {
    *statsLog << "\n" << std::flush;
  }
}

void DistributedRaycastRenderer::commit()
{
  Renderer::commit();

  ispc::DistributedRaycastRenderer_set(getIE(),
      getParam<int>("aoSamples", 0),
      getParam<float>("aoDistance", getParam<float>("aoRadius", 1e20f)),
      getParam<bool>("shadows", getParam<int>("shadowsEnabled", 0)),
      getParam<float>("volumeSamplingRate", 1.f));
}

std::shared_ptr<TileOperation> DistributedRaycastRenderer::tileOperation()
{
  return std::make_shared<AlphaCompositeTileOperation>();
}

std::string DistributedRaycastRenderer::toString() const
{
  return "ospray::mpi::DistributedRaycastRenderer";
}

} // namespace mpi
} // namespace ospray


text:
package org.pac4j.oauth.profile.yahoo;

import org.pac4j.oauth.profile.JsonObject;

/**
 * This class represents a Yahoo image.
 *
 * @author Jerome Leleu
 * @since 1.1.0
 */
public final class YahooImage extends JsonObject {

    private static final long serialVersionUID = 5378229852266815223L;

    private String imageUrl;

    private Integer width;

    private Integer height;

    private String size;

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }
}


text: declare export default class A<T> extends B<T> { x: number }


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Tests.Core.Controllers.Messaging.Builders
{
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Services.Social.Subscriptions.Entities;

    internal class SubscriptionTypeBuilder
    {
        private int subscriptionTypeId;
        private string subscriptionName;
        private string friendlyName;
        private int desktopModuleId;

        internal SubscriptionTypeBuilder()
        {
            this.subscriptionTypeId = 1;
            this.subscriptionName = "MySubscriptionType";
            this.friendlyName = "My Subscription Type";
            this.desktopModuleId = Null.NullInteger;
        }

        internal SubscriptionTypeBuilder WithSubscriptionTypeId(int subscriptionTypeId)
        {
            this.subscriptionTypeId = subscriptionTypeId;
            return this;
        }

        internal SubscriptionTypeBuilder WithSubscriptionName(string subscriptionName)
        {
            this.subscriptionName = subscriptionName;
            return this;
        }

        internal SubscriptionType Build()
        {
            return new SubscriptionType
            {
                SubscriptionTypeId = this.subscriptionTypeId,
                SubscriptionName = this.subscriptionName,
                DesktopModuleId = this.desktopModuleId,
                FriendlyName = this.friendlyName,
            };
        }
    }
}


text:
{% extends "descriptor/descriptor_view_base.html" %}

{% load staticfiles %}

{% block title_header_big %}
{{ block.super }}
Edit {{descriptor_type}} Descriptor
{% endblock %}

{% block left_sidebar %}
{% include 'click/click_project_left_sidebar.html' %}
{% endblock %}

{% block breadcrumb_body %}
{{ block.super }}

{{project_overview_data.name}}

    {{descriptor_type}} Descriptors

{{descriptor_id}}

{% endblock %}

{% block tab_pane_button_list %}
{{ block.super }}

                    Editor

{% endblock %}

{% block nav_buttons_list %}
    {{ block.super }}

                    <button id="save" type="button" class="btn btn-block btn-primary btn-sm" onclick="update(this.id)">
                         Save
                    </button>

                    <button id="save_show_graph" type="button" class="btn btn-block btn-primary btn-sm"
                            onclick="update(this.id)"> Save and Show Graph
                    </button>

                    <button type="button" class="btn btn-block btn-primary btn-sm" onclick="goToGraph()"> Show Graph
                    </button>

{% endblock %}

{% block tab_pane_list %}
{{ block.super }}

                    <textarea id="code_editor">
                    </textarea>

{% endblock %}

{% block resource_block %}
{{ block.super }}

{% endblock %}