text:
/* //////////////////////////////////////////////////////////////////////////////////////
 * trace
 */
#define TB_TRACE_MODULE_NAME            "value"
#define TB_TRACE_MODULE_DEBUG           (0)

/* //////////////////////////////////////////////////////////////////////////////////////
 * includes
 */
#include "value.h"
#include "../stream/stream.h"

/* //////////////////////////////////////////////////////////////////////////////////////
 * implementation
 */
tb_size_t tb_database_sql_value_size(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        if (!value->u.text.hint && value->u.text.data)
        {
            ((tb_database_sql_value_t*)value)->u.text.hint = tb_strlen(value->u.text.data);
        }
        return value->u.text.hint;
    case TB_DATABASE_SQL_VALUE_TYPE_BLOB32:
    case TB_DATABASE_SQL_VALUE_TYPE_BLOB16:
    case TB_DATABASE_SQL_VALUE_TYPE_BLOB8:
        return value->u.blob.size;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
#endif
        return 4;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
#endif
        return 8;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return 2;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return 1;
    default:
        tb_trace_e("unknown type: %lu", value->type);
        break;
    }

    return 0;
}
tb_int8_t tb_database_sql_value_int8(tb_database_sql_value_t const* value)
{
    return (tb_int8_t)tb_database_sql_value_int32(value);
}
tb_int16_t tb_database_sql_value_int16(tb_database_sql_value_t const* value)
{
    return (tb_int16_t)tb_database_sql_value_int32(value);
}
tb_int32_t tb_database_sql_value_int32(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_int32_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_int32_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_int32_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_int32_t)value->u.i8;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_int32_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_int32_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_int32_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_int32_t)value->u.u8;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return (tb_int32_t)value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return (tb_int32_t)value->u.d;
#endif
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? (tb_int32_t)tb_stoi32(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
tb_int64_t tb_database_sql_value_int64(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_int64_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_int64_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_int64_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_int64_t)value->u.i8;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_int64_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_int64_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_int64_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_int64_t)value->u.u8;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return (tb_int64_t)value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return (tb_int64_t)value->u.d;
#endif
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? (tb_int64_t)tb_stoi64(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
tb_uint8_t tb_database_sql_value_uint8(tb_database_sql_value_t const* value)
{
    return (tb_uint8_t)tb_database_sql_value_uint32(value);
}
tb_uint16_t tb_database_sql_value_uint16(tb_database_sql_value_t const* value)
{
    return (tb_uint16_t)tb_database_sql_value_uint32(value);
}
tb_uint32_t tb_database_sql_value_uint32(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_uint32_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_uint32_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_uint32_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_uint32_t)value->u.u8;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_uint32_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_uint32_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_uint32_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_uint32_t)value->u.i8;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return (tb_uint32_t)value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return (tb_uint32_t)value->u.d;
#endif
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? (tb_uint32_t)tb_stoi32(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
tb_uint64_t tb_database_sql_value_uint64(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_uint64_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_uint64_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_uint64_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_uint64_t)value->u.u8;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_uint64_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_uint64_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_uint64_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_uint64_t)value->u.i8;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return (tb_uint64_t)value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return (tb_uint64_t)value->u.d;
#endif
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? (tb_uint64_t)tb_stou64(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
tb_float_t tb_database_sql_value_float(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return (tb_float_t)value->u.d;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_float_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_float_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_float_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_float_t)value->u.i8;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_float_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_float_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_float_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_float_t)value->u.u8;
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? tb_stof(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
tb_double_t tb_database_sql_value_double(tb_database_sql_value_t const* value)
{
    // check
    tb_assert_and_check_return_val(value, 0);

    // done
    switch (value->type)
    {
    case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        return (tb_double_t)value->u.f;
    case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
        return value->u.d;
    case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        return (tb_double_t)value->u.i64;
    case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        return (tb_double_t)value->u.i32;
    case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        return (tb_double_t)value->u.i16;
    case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        return (tb_double_t)value->u.i8;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
        return (tb_double_t)value->u.u64;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        return (tb_double_t)value->u.u32;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        return (tb_double_t)value->u.u16;
    case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
        return (tb_double_t)value->u.u8;
    case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
        return value->u.text.data? tb_stod(value->u.text.data) : 0;
    default:
        tb_trace_e("unknown number type: %lu", value->type);
        break;
    }

    return 0;
}
#endif
tb_void_t tb_database_sql_value_set_null(tb_database_sql_value_t* value)
{
    // check
    tb_assert_and_check_return(value);

    // init null
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_NULL;
}
tb_void_t tb_database_sql_value_set_int8(tb_database_sql_value_t* value, tb_int8_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT8;
    value->u.i8         = number;
}
tb_void_t tb_database_sql_value_set_int16(tb_database_sql_value_t* value, tb_int16_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT16;
    value->u.i16        = number;
}
tb_void_t tb_database_sql_value_set_int32(tb_database_sql_value_t* value, tb_int32_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT32;
    value->u.i32        = number;
}
tb_void_t tb_database_sql_value_set_int64(tb_database_sql_value_t* value, tb_int64_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT64;
    value->u.i64            = number;
}
tb_void_t tb_database_sql_value_set_uint8(tb_database_sql_value_t* value, tb_uint8_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT8;
    value->u.u8         = number;
}
tb_void_t tb_database_sql_value_set_uint16(tb_database_sql_value_t* value, tb_uint16_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT16;
    value->u.u16        = number;
}
tb_void_t tb_database_sql_value_set_uint32(tb_database_sql_value_t* value, tb_uint32_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT32;
    value->u.u32        = number;
}
tb_void_t tb_database_sql_value_set_uint64(tb_database_sql_value_t* value, tb_uint64_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_INT64;
    value->u.u64        = number;
}
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
tb_void_t tb_database_sql_value_set_float(tb_database_sql_value_t* value, tb_float_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_FLOAT;
    value->u.f          = number;
}
tb_void_t tb_database_sql_value_set_double(tb_database_sql_value_t* value, tb_double_t number)
{
    // check
    tb_assert_and_check_return(value);

    // init number
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_DOUBLE;
    value->u.d          = number;
}
#endif
tb_void_t tb_database_sql_value_set_text(tb_database_sql_value_t* value, tb_char_t const* text, tb_size_t hint)
{
    // check
    tb_assert_and_check_return(value);

    // init text
    value->type         = TB_DATABASE_SQL_VALUE_TYPE_TEXT;
    value->u.text.data  = text;
    value->u.text.hint  = hint;
}
tb_void_t tb_database_sql_value_set_blob8(tb_database_sql_value_t* value, tb_byte_t const* data, tb_size_t size)
{
    // check
    tb_assert_and_check_return(value);

    // init blob
    value->type             = TB_DATABASE_SQL_VALUE_TYPE_BLOB8;
    value->u.blob.data      = data;
    value->u.blob.size      = size;
    value->u.blob.stream    = tb_null;

    // check size
    tb_assert(tb_database_sql_value_size(value) <= TB_MAXU8);
}
tb_void_t tb_database_sql_value_set_blob16(tb_database_sql_value_t* value, tb_byte_t const* data, tb_size_t size)
{
    // check
    tb_assert_and_check_return(value);

    // init blob
    value->type             = TB_DATABASE_SQL_VALUE_TYPE_BLOB16;
    value->u.blob.data      = data;
    value->u.blob.size      = size;
    value->u.blob.stream    = tb_null;

    // check size
    tb_assert(tb_database_sql_value_size(value) <= TB_MAXU16);
}
tb_void_t tb_database_sql_value_set_blob32(tb_database_sql_value_t* value, tb_byte_t const* data, tb_size_t size, tb_stream_ref_t stream)
{
    // check
    tb_assert_and_check_return(value);

    // check stream
    tb_hong_t stream_size = 0;
    if (stream)
    {
        // must be opened
        tb_assert_and_check_return(tb_stream_is_opened(stream));

        // the stream size
        stream_size = tb_stream_size(stream);
        tb_assert_and_check_return(stream_size >= 0 && stream_size < TB_MAXS32);
    }

    // init blob
    value->type             = TB_DATABASE_SQL_VALUE_TYPE_BLOB32;
    value->u.blob.data      = data;
    value->u.blob.size      = data? size : (tb_size_t)stream_size;
    value->u.blob.stream    = stream;

    // check size
    tb_assert(tb_database_sql_value_size(value) <= TB_MAXU32);
}


text:
class CreateSources < ActiveRecord::Migration[4.2]
  def change
    create_table :sources do |t|
      t.belongs_to :user, index: true
      t.string :name
      t.string :slogan
      t.string :avatar
      t.timestamps null: false
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

namespace ILRuntime.Runtime.Debugger
{
    public enum StepTypes
    {
        None,
        Into,
        Over,
        Out,
    }
}


text:
package org.vaadin.gridutil.client.renderer;

import com.vaadin.client.renderers.Renderer;
import com.vaadin.client.widget.grid.RendererCellReference;

/**
 * HTML-Drawer for boolean values
 *
 * @author Marten Prieß (http://www.non-rocket-science.com)
 * @version 1.0
 */
public class VBooleanRenderer implements Renderer<Boolean> {

	@Override
	public void render(final RendererCellReference cell, final Boolean data) {
		String output = "";
		cell.getElement()
				.setInnerHTML(output);
	}
}


text:
#pragma once
#include <aws/opsworks/OpsWorks_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/opsworks/model/ServiceError.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace OpsWorks
{
namespace Model
{
  /**
   *
Contains the response to a DescribeServiceErrors
   * request.

See Also:
   AWS
   * API Reference

   */
  class AWS_OPSWORKS_API DescribeServiceErrorsResult
  {
  public:
    DescribeServiceErrorsResult();
    DescribeServiceErrorsResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeServiceErrorsResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline const Aws::Vector<ServiceError>& GetServiceErrors() const{ return m_serviceErrors; }

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline void SetServiceErrors(const Aws::Vector<ServiceError>& value) { m_serviceErrors = value; }

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline void SetServiceErrors(Aws::Vector<ServiceError>&& value) { m_serviceErrors = std::move(value); }

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline DescribeServiceErrorsResult& WithServiceErrors(const Aws::Vector<ServiceError>& value) { SetServiceErrors(value); return *this;}

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline DescribeServiceErrorsResult& WithServiceErrors(Aws::Vector<ServiceError>&& value) { SetServiceErrors(std::move(value)); return *this;}

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline DescribeServiceErrorsResult& AddServiceErrors(const ServiceError& value) { m_serviceErrors.push_back(value); return *this; }

    /**
     *
An array of ServiceError objects that describe the specified
     * service errors.

     */
    inline DescribeServiceErrorsResult& AddServiceErrors(ServiceError&& value) { m_serviceErrors.push_back(std::move(value)); return *this; }

  private:
    Aws::Vector<ServiceError> m_serviceErrors;
  };

} // namespace Model
} // namespace OpsWorks
} // namespace Aws


text:
diff --git a/signatures/signed_by_ingresshuskytsai.md b/signatures/signed_by_ingresshuskytsai.md
new file mode 100644
index 0000000..6f3a8e7
--- a/signatures/signed_by_ingresshuskytsai.md
+++ b/signatures/signed_by_ingresshuskytsai.md
  A dad with two kids.
  I walk pride parade for years.
  I know how to teach my children.
+  I support Marriage Equality.


text:
"""Support for MQTT scenes."""
import logging

import voluptuous as vol

from homeassistant.components import scene
from homeassistant.components.scene import Scene
from homeassistant.const import CONF_ICON, CONF_NAME, CONF_PAYLOAD_ON, CONF_UNIQUE_ID
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType

from . import (
    ATTR_DISCOVERY_HASH,
    CONF_COMMAND_TOPIC,
    CONF_QOS,
    CONF_RETAIN,
    DOMAIN,
    PLATFORMS,
    MqttAvailability,
    MqttDiscoveryUpdate,
)
from .. import mqtt
from .discovery import MQTT_DISCOVERY_NEW, clear_discovery_hash

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "MQTT Scene"
DEFAULT_RETAIN = False

PLATFORM_SCHEMA = mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_COMMAND_TOPIC): mqtt.valid_publish_topic,
        vol.Optional(CONF_ICON): cv.icon,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_PAYLOAD_ON): cv.string,
        vol.Optional(CONF_UNIQUE_ID): cv.string,
        vol.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
    }
).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)

async def async_setup_platform(
    hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
    """Set up MQTT scene through configuration.yaml."""
    await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
    await _async_setup_entity(config, async_add_entities)

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up MQTT scene dynamically through MQTT discovery."""

    async def async_discover(discovery_payload):
        """Discover and add a MQTT scene."""
        discovery_data = discovery_payload.discovery_data
        try:
            config = PLATFORM_SCHEMA(discovery_payload)
            await _async_setup_entity(
                config, async_add_entities, config_entry, discovery_data
            )
        except Exception:
            clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
            raise

    async_dispatcher_connect(
        hass, MQTT_DISCOVERY_NEW.format(scene.DOMAIN, "mqtt"), async_discover
    )

async def _async_setup_entity(
    config, async_add_entities, config_entry=None, discovery_data=None
):
    """Set up the MQTT scene."""
    async_add_entities([MqttScene(config, config_entry, discovery_data)])

class MqttScene(
    MqttAvailability,
    MqttDiscoveryUpdate,
    Scene,
):
    """Representation of a scene that can be activated using MQTT."""

    def __init__(self, config, config_entry, discovery_data):
        """Initialize the MQTT scene."""
        self._state = False
        self._sub_state = None

        self._unique_id = config.get(CONF_UNIQUE_ID)

        # Load config
        self._setup_from_config(config)

        MqttAvailability.__init__(self, config)
        MqttDiscoveryUpdate.__init__(self, discovery_data, self.discovery_update)

    async def async_added_to_hass(self):
        """Subscribe to MQTT events."""
        await super().async_added_to_hass()

    async def discovery_update(self, discovery_payload):
        """Handle updated discovery message."""
        config = PLATFORM_SCHEMA(discovery_payload)
        self._setup_from_config(config)
        await self.availability_discovery_update(config)
        self.async_write_ha_state()

    def _setup_from_config(self, config):
        """(Re)Setup the entity."""
        self._config = config

    async def async_will_remove_from_hass(self):
        """Unsubscribe when removed."""
        await MqttAvailability.async_will_remove_from_hass(self)
        await MqttDiscoveryUpdate.async_will_remove_from_hass(self)

    @property
    def name(self):
        """Return the name of the scene."""
        return self._config[CONF_NAME]

    @property
    def unique_id(self):
        """Return a unique ID."""
        return self._unique_id

    @property
    def icon(self):
        """Return the icon."""
        return self._config.get(CONF_ICON)

    async def async_activate(self, **kwargs):
        """Activate the scene.

        This method is a coroutine.
        """
        mqtt.async_publish(
            self.hass,
            self._config[CONF_COMMAND_TOPIC],
            self._config[CONF_PAYLOAD_ON],
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
        )


text:
% Copyright 2021 Google LLC
%
% Use of this source code is governed by an MIT-style
% license that can be found in the LICENSE file or at
% https://opensource.org/licenses/MIT.

%!BIB program = biber
%!TeX program = lualatex
%!TeX spellcheck = en-US

\documentclass[hctr2.tex]{subfiles}
\begin{document}
\section{Introduction}
A symmetric encryption construction such as AES-GCM\cite{gcm}
will produce a ciphertext which is larger than
the plaintext, once the nonce and authentication tag are included. However,
there are situations such as disk sector encryption
where the ciphertext must be the same size as the
plaintext, and what is required is a tweakable
\emph{super-pseudorandom permutation} (SPRP):
a family of permutations indexed by tweak and input length,
which appear to be random permutations to an adversary without the key
who can make encryption and decryption queries\cite{cmc}.
\cite{adiantum} includes a detailed history of length-preserving encryption.
Where AES and multiplication in \(\GF(2^{128})\) are hardware-accelerated,
HCTR\cite{hctr} is among the most efficient
tweakable SPRP constructions, using
a single block cipher invocation and two \(\GF(2^{128})\) multiplications
per 16-byte block.

In this paper, we present
a specification (\autoref{specification})
and security bound (\autoref{security})
for a revised version, HCTR2, which
addresses the following issues:
\begin{itemize}
    \item \cite{kumarhctr} observes that HCTR's hash function
    is not almost-XOR-universal\cite{eadu} as claimed (\autoref{badhash}).
    HCTR2's hash function fixes this property.
    \item Separately,
    an error in the proof presented in \cite{hctrquad}
    invalidates the security bound claimed in that paper (\autoref{badproof}); with our revised
    mode we can claim a tighter bound.
    \item HCTR2 supports using tweaks of any length with a single key.
    \item HCTR's key is a block cipher key, plus an \(n\)-bit
    hash key. HCTR2's key is simply
    the block cipher key.
    \item We modify the hash function to allow more precomputation
    for greater performance.
    \item We specify endianness and the like for interoperability.
    \item We provide a sample implementation and test vectors.
\end{itemize}
We discuss our design decisions (\autoref{design})
and report on its implementation on x86-64 and ARM64 (\autoref{implementation}).
We know of no patents affecting HCTR2.
\subfile{hctr2fig.tex}
\end{document}


text:
package org.hibernate.examples.mapping.tree;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.*;
import org.hibernate.examples.model.AbstractHibernateEntity;
import org.hibernate.examples.model.HibernateTreeEntity;
import org.hibernate.examples.model.TreeNodePosition;
import org.hibernate.examples.utils.HashTool;
import org.hibernate.examples.utils.ToStringHelper;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.*;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * org.hibernate.examples.mapping.tree.TreeNode
 *
 * @author 배성혁 sunghyouk.bae@gmail.com
 * @since 2013. 12. 3. 오후 6:42
 */
@Entity
@org.hibernate.annotations.Cache(region = "example", usage = CacheConcurrencyStrategy.READ_WRITE)
@DynamicInsert
@DynamicUpdate
@Getter
@Setter
public class TreeNode extends AbstractHibernateEntity<Long> implements HibernateTreeEntity<TreeNode> {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Setter(AccessLevel.PROTECTED)
  private Long id;

  private String title;
  private String data;
  private String description;

  /**
   * 부모 노드
   */
  @ManyToOne(fetch = FetchType.LAZY)
  @LazyToOne(LazyToOneOption.PROXY)
  @JoinColumn(name = "ParentId")
  private TreeNode parent;

  /**
   * 자식 노드
   * mappedBy를 정의하여, child 마다 관리되도록 해야합니다.
   */
  @OneToMany(mappedBy = "parent", cascade = {CascadeType.ALL}, orphanRemoval = true)
  @LazyCollection(LazyCollectionOption.EXTRA)
  private Set<TreeNode> children = new LinkedHashSet<TreeNode>();

  /**
   * 노드의 TreeView 상에서의 위치
   */
  TreeNodePosition nodePosition = new TreeNodePosition();

  /**
   * 자식 노드를 추가합니다.
   */
  @Override
  public void addChild(TreeNode child) {
    child.setParent(this);
    children.add(child);
  }

  /**
   * 자식 노드를 삭제합니다.
   */
  @Override
  public void removeChild(TreeNode child) {
    if (children.contains(child)) {
      children.remove(child);
      child.setParent(null);
    }
  }

  @Override
  public int hashCode() {
    return HashTool.compute(title);
  }

  @Override
  public ToStringHelper buildStringHelper() {
    return super.buildStringHelper()
        .add("id", id)
        .add("title", title)
        .add("description", description);
  }

  private static final long serialVersionUID = 6573065680420748563L;
}


text:
<form id="updateForm" name="updateForm" role="form" ng-submit="updateEvent()">

                    Event Description
                    <textarea id="eventDescription" class="form-control" rows="8" placeholder="Description..." ng-model="op.event.description" required></textarea>

                    Venue
                    <input type="text" id="eventVenueName" class="form-control" placeholder="Venue name..." ng-model="op.event.venueName" required>

                    <ui-gmap-google-map center='op.map.center' zoom='op.map.zoom' events='op.map.events'>
                        <ui-gmap-marker coords="op.marker.coords" idkey="op.marker.id"></ui-gmap-marker>
                    </ui-gmap-google-map>

                    <button id="btnUpdateEvent" class="ladda-button pull-left" data-color="green" data-style="expand-right" data-size="s" ng-click="updateForm.submit()">
                        {{ op.eventID ? 'Update Event' : 'Create Event' }}
                    </button>

                    Event Name
                    <input type="text" id="eventName" class="form-control" placeholder="Event name..." ng-model="op.event.name" required>

                    Entry Type
                    <select id="entryType" class="form-control" ng-model="op.event.entryType.type" ng-options="t.type as t.label for t in op.entryTypes" required></select>

                    Minimum Team Size
                    <select id="minTeamSize" class="form-control" ng-model="op.event.entryType.minTeamSize" required>
                        <option value="2">Minimum 2</option>
                        <option value="3">Minimum 3</option>
                        <option value="4">Minimum 4</option>
                        <option value="5">Minimum 5</option>
                        <option value="6">Minimum 6</option>
                        <option value="7">Minimum 7</option>
                        <option value="8">Minimum 8</option>
                    </select>

                        Starts
                        <input type="datetime-local" id="startTime" class="form-control" ng-model="op.event.startTime" required>

                        Ends
                        <input type="datetime-local" id="endTime" class="form-control" ng-model="op.event.endTime" required>

                        Entry Fee ($)
                        <input type="number" id="entryFee" min="0" max="1000" class="form-control" ng-model="op.event.entryFee" required>

                        Maximum Entrants
                        <input type="number" id="maxEntrants" min="2" max="1000" class="form-control" ng-model="op.event.maxEntrants" required>

                        Invitational
                        Open Registration

                        Published
                        Not Published

</form>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class VideoWbSv extends CI_Controller
{
    public function index()
    {
        $this->load->view('teste');
    }

    public function cadastrar()
    {
        $this->load->view('template/html-header');
        $this->load->view('template/header');
        $this->load->view('template/aside');
        $this->load->view('video/formCadastrar');
        $this->load->view('template/footer');
        $this->load->view('template/html-footer');
    }

    public function processaCadastrar()
    {
        $titulo = $this->input->post('titulo');
        $descricao = $this->input->post('descricao');
        $especialidade = $this->input->post('especialidade');
        $link = $this->input->post('link');
        $this->load->model('VideoModel');
        if ($this->VideoModel->insert($titulo, $descricao, $especialidade, $link)) {
            $response = array('result' => 'true', 'msg' => 'Vídeo cadastrado com sucesso!');
        } else {
            $response = array('result' => 'false', 'msg' => 'O vídeo não foi cadastrado!');
        }
        echo json_encode($response);
    }

    public function processaBuscar($id)
    {
        $this->load->model('VideoModel');
        $result = $this->VideoModel->get($id);
        $response = array();
        foreach ($result as $row) {
            $json["id"] = $row->id;
            $json["titulo"] = $row->titulo;
            $json["descricao"] = $row->descricao;
            $json["especialidade"] = $row->especialidade;
            $json["link"] = $row->link;
            array_push($response, $json);
        }
        echo json_encode($response);
    }

    public function processaListar()
    {
        $this->load->model('VideoModel');
        $result = $this->VideoModel->getList();
        $response = array();
        foreach ($result as $row) {
            $json["id"] = $row->id;
            $json["titulo"] = $row->titulo;
            $json["descricao"] = $row->descricao;
            $json["especialidade"] = $row->especialidade;
            $json["link"] = $row->link;
            array_push($response, $json);
        }
        echo json_encode($response);
    }

    public function processaAtualizar($id)
    {
        $titulo = $this->input->post('titulo');
        $descricao = $this->input->post('descricao');
        $especialidade = $this->input->post('especialidade');
        $link = $this->input->post('link');
        $this->load->model('VideoModel');
        if ($this->VideoModel->update($titulo, $descricao, $especialidade, $link)) {
            $response = array('result' => 'true', 'msg' => 'Vídeo atualizado com sucesso!');
        } else {
            $response = array('result' => 'false', 'msg' => 'O vídeo não foi atualizado!');
        }
        echo json_encode($response);
    }

    public function processaRemover($id)
    {
        $this->load->model('VideoModel');
        if ($this->VideoModel->delete($id)) {
            $response = array('result' => 'true', 'msg' => 'Vídeo removido com sucesso!');
        } else {
            $response = array('result' => 'false', 'msg' => 'O vídeo não foi removido!');
        }
        echo json_encode($response);
    }
}


text:
package com.shade;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.util.Log;

import com.shade.states.MasterState;

public class Shade extends StateBasedGame {

    public static final String TITLE = "Shade";
    private static final String[] ICONS = {
        "icons/shade.16.gif",
        "icons/shade.24.gif",
        "icons/shade.32.gif",
        "icons/shade.128.gif"
    };

    public Shade() {
        super(TITLE);
    }

    @Override
    public void initStatesList(GameContainer container) throws SlickException {
        addState(new MasterState());
    }

    public static void main(String[] args) {
        try {
            Shade s = new Shade();
            AppGameContainer c = new AppGameContainer(s, 800, 600, false);
            c.setIcons(ICONS);
            c.setShowFPS(false);
            c.setTargetFrameRate(60);
            Log.setVerbose(true);
            c.start();
        } catch (SlickException e) {
            e.printStackTrace();
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.testah.runner (testah-junit 1.1.3 API)</title>
<meta name="date" content="2018-07-22">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.testah.runner

Classes

HttpAkkaRunner

TestahJUnitRunner


text:
package org.robolectric.shadows;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorDescription;
import android.accounts.AuthenticatorException;
import android.accounts.OnAccountsUpdateListener;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;

import java.io.IOException;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.robolectric.Shadows.shadowOf;

@RunWith(TestRunners.MultiApiWithDefaults.class)
public class ShadowAccountManagerTest {
  Application app;
  AccountManager am;

  @Before
  public void setUp() throws Exception {
    app = RuntimeEnvironment.application;
    am = AccountManager.get(app);
  }

  @Test
  public void testGet() {
    assertThat(am).isNotNull();
    assertThat(am).isSameAs(AccountManager.get(app));

    AccountManager activityAM = AccountManager.get(new Activity());
    assertThat(activityAM).isNotNull();
    assertThat(activityAM).isSameAs(am);
  }

  @Test
  public void testGetAccounts() {
    assertThat(am.getAccounts()).isNotNull();
    assertThat(am.getAccounts().length).isEqualTo(0);

    Account a1 = new Account("name_a", "type_a");
    shadowOf(am).addAccount(a1);
    assertThat(am.getAccounts()).isNotNull();
    assertThat(am.getAccounts().length).isEqualTo(1);
    assertThat(am.getAccounts()[0]).isSameAs(a1);

    Account a2 = new Account("name_b", "type_b");
    shadowOf(am).addAccount(a2);
    assertThat(am.getAccounts()).isNotNull();
    assertThat(am.getAccounts().length).isEqualTo(2);
    assertThat(am.getAccounts()[1]).isSameAs(a2);
  }

  @Test
  public void testGetAccountsByType() {
    assertThat(am.getAccountsByType("name_a")).isNotNull();
    assertThat(am.getAccounts().length).isEqualTo(0);

    Account a1 = new Account("name_a", "type_a");
    shadowOf(am).addAccount(a1);
    Account[] accounts = am.getAccountsByType("type_a");
    assertThat(accounts).isNotNull();
    assertThat(accounts.length).isEqualTo(1);
    assertThat(accounts[0]).isSameAs(a1);

    Account a2 = new Account("name_b", "type_b");
    shadowOf(am).addAccount(a2);
    accounts = am.getAccountsByType("type_a");
    assertThat(accounts).isNotNull();
    assertThat(accounts.length).isEqualTo(1);
    assertThat(accounts[0]).isSameAs(a1);

    Account a3 = new Account("name_c", "type_a");
    shadowOf(am).addAccount(a3);
    accounts = am.getAccountsByType("type_a");
    assertThat(accounts).isNotNull();
    assertThat(accounts.length).isEqualTo(2);
    assertThat(accounts[0]).isSameAs(a1);
    assertThat(accounts[1]).isSameAs(a3);
  }

  @Test
  public void addAuthToken() {
    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);

    am.setAuthToken(account, "token_type_1", "token1");
    am.setAuthToken(account, "token_type_2", "token2");

    assertThat(am.peekAuthToken(account, "token_type_1")).isEqualTo("token1");
    assertThat(am.peekAuthToken(account, "token_type_2")).isEqualTo("token2");
  }

  @Test
  public void setAuthToken_shouldNotAddTokenIfAccountNotPresent() {
    Account account = new Account("name", "type");
    am.setAuthToken(account, "token_type_1", "token1");
    assertThat(am.peekAuthToken(account, "token_type_1")).isNull();
  }

  @Test
  public void testAddAccountExplicitly_noPasswordNoExtras() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, null, null);

    assertThat(accountAdded).isTrue();
    assertThat(am.getAccountsByType("type").length).isEqualTo(1);
    assertThat(am.getAccountsByType("type")[0].name).isEqualTo("name");

    boolean accountAddedTwice = am.addAccountExplicitly(account, null, null);
    assertThat(accountAddedTwice).isFalse();

    account = new Account("another_name", "type");
    accountAdded = am.addAccountExplicitly(account, null, null);
    assertThat(accountAdded).isTrue();
    assertThat(am.getAccountsByType("type").length).isEqualTo(2);
    assertThat(am.getAccountsByType("type")[0].name).isEqualTo("name");
    assertThat(am.getAccountsByType("type")[1].name).isEqualTo("another_name");
    assertThat(am.getPassword(account)).isNull();

    try {
      am.addAccountExplicitly(null, null, null);
      fail("An illegal argument exception should have been thrown when trying to add a null account");
    } catch (IllegalArgumentException iae) {
      // NOP
    }
  }

  @Test
  public void testAddAccountExplicitly_withPassword() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, "passwd", null);

    assertThat(accountAdded).isTrue();
    assertThat(am.getPassword(account)).isEqualTo("passwd");
  }

  @Test
  public void testAddAccountExplicitly_withExtras() {
    Account account = new Account("name", "type");
    Bundle extras = new Bundle();
    extras.putString("key123", "value123");
    boolean accountAdded = am.addAccountExplicitly(account, null, extras);

    assertThat(accountAdded).isTrue();
    assertThat(am.getUserData(account, "key123")).isEqualTo("value123");
    assertThat(am.getUserData(account, "key456")).isNull();
  }

  @Test
  public void testGetSetUserData_addToInitiallyEmptyExtras() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, null, null);

    assertThat(accountAdded).isTrue();

    am.setUserData(account, "key123", "value123");
    assertThat(am.getUserData(account, "key123")).isEqualTo("value123");
  }

  @Test
  public void testGetSetUserData_overwrite() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, null, null);

    assertThat(accountAdded).isTrue();

    am.setUserData(account, "key123", "value123");
    assertThat(am.getUserData(account, "key123")).isEqualTo("value123");

    am.setUserData(account, "key123", "value456");
    assertThat(am.getUserData(account, "key123")).isEqualTo("value456");
  }

  @Test
  public void testGetSetUserData_remove() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, null, null);

    assertThat(accountAdded).isTrue();

    am.setUserData(account, "key123", "value123");
    assertThat(am.getUserData(account, "key123")).isEqualTo("value123");

    am.setUserData(account, "key123", null);
    assertThat(am.getUserData(account, "key123")).isNull();
  }

  @Test
  public void testGetSetPassword_setInAccountInitiallyWithNoPassword() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, null, null);

    assertThat(accountAdded).isTrue();
    assertThat(am.getPassword(account)).isNull();

    am.setPassword(account, "passwd");
    assertThat(am.getPassword(account)).isEqualTo("passwd");
  }

  @Test
  public void testGetSetPassword_overwrite() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, "passwd1", null);

    assertThat(accountAdded).isTrue();
    assertThat(am.getPassword(account)).isEqualTo("passwd1");

    am.setPassword(account, "passwd2");
    assertThat(am.getPassword(account)).isEqualTo("passwd2");
  }

  @Test
  public void testGetSetPassword_remove() {
    Account account = new Account("name", "type");
    boolean accountAdded = am.addAccountExplicitly(account, "passwd1", null);

    assertThat(accountAdded).isTrue();
    assertThat(am.getPassword(account)).isEqualTo("passwd1");

    am.setPassword(account, null);
    assertThat(am.getPassword(account)).isNull();
  }

  @Test
  public void testBlockingGetAuthToken() throws AuthenticatorException, OperationCanceledException, IOException {
    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);

    am.setAuthToken(account, "token_type_1", "token1");
    am.setAuthToken(account, "token_type_2", "token2");

    assertThat(am.blockingGetAuthToken(account, "token_type_1", false)).isEqualTo("token1");
    assertThat(am.blockingGetAuthToken(account, "token_type_2", false)).isEqualTo("token2");

    try {
      am.blockingGetAuthToken(null, "token_type_1", false);
      fail("blockingGetAuthToken() should throw an illegal argument exception if the account is null");
    } catch (IllegalArgumentException iae) {
      // Expected
    }
    try {
      am.blockingGetAuthToken(account, null, false);
      fail("blockingGetAuthToken() should throw an illegal argument exception if the auth token type is null");
    } catch (IllegalArgumentException iae) {
      // Expected
    }

    Account account1 = new Account("unknown", "type");
    assertThat(am.blockingGetAuthToken(account1, "token_type_1", false)).isNull();
  }

  @Test
  public void removeAccount_throwsIllegalArgumentException_whenPassedNullAccount() {
    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);

    try {
      am.removeAccount(null, null, null);
      fail("removeAccount() should throw an illegal argument exception if the account is null");
    } catch (IllegalArgumentException iae) {
      // Expected
    }
  }

  @Test
  public void removeAccount_doesNotRemoveAccountOfDifferentName() throws Exception {
    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);

    Account wrongAccount = new Account("wrong_name", "type");
    AccountManagerFuture<Boolean> future = am.removeAccount(wrongAccount, null, null);
    assertThat(future.getResult()).isFalse();
    assertThat(am.getAccountsByType("type")).isNotEmpty();
  }

  @Test
  public void removeAccount_does() throws Exception {
    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);

    AccountManagerFuture<Boolean> future = am.removeAccount(account, null, null);
    assertThat(future.getResult()).isTrue();
    assertThat(am.getAccountsByType("type")).isEmpty();
  }

  private static class TestOnAccountsUpdateListener implements OnAccountsUpdateListener {
    private int invocationCount = 0;

    @Override
    public void onAccountsUpdated(Account[] accounts) {
      invocationCount++;
    }

    public int getInvocationCount() {
      return invocationCount;
    }
  }

  @Test
  public void testAccountsUpdateListener() {
    TestOnAccountsUpdateListener listener = new TestOnAccountsUpdateListener();
    am.addOnAccountsUpdatedListener(listener, null, false);
    assertThat(listener.getInvocationCount()).isEqualTo(0);

    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);
    assertThat(listener.getInvocationCount()).isEqualTo(1);
  }

  @Test
  public void testAccountsUpdateListener_duplicate() {
    TestOnAccountsUpdateListener listener = new TestOnAccountsUpdateListener();
    am.addOnAccountsUpdatedListener(listener, null, false);
    am.addOnAccountsUpdatedListener(listener, null, false);
    assertThat(listener.getInvocationCount()).isEqualTo(0);

    Account account = new Account("name", "type");
    shadowOf(am).addAccount(account);
    assertThat(listener.getInvocationCount()).isEqualTo(1);
  }

  @Test
  public void testAccountsUpdateListener_updateImmediately() {
    TestOnAccountsUpdateListener listener = new TestOnAccountsUpdateListener();
    am.addOnAccountsUpdatedListener(listener, null, true);
    assertThat(listener.getInvocationCount()).isEqualTo(1);
  }

  @Test
  public void testAddAuthenticator() {
    shadowOf(am).addAuthenticator("type");
    AuthenticatorDescription[] result = am.getAuthenticatorTypes();
    assertThat(result.length).isEqualTo(1);
    assertThat(result[0].type).isEqualTo("type");
  }

  @Test
  public void invalidateAuthToken_noAccount() {
    am.invalidateAuthToken("type1", "token1");
  }

  @Test
  public void invalidateAuthToken_noToken() {
    Account account1 = new Account("name", "type1");
    shadowOf(am).addAccount(account1);
    am.invalidateAuthToken("type1", "token1");
  }

  @Test
  public void invalidateAuthToken_multipleAccounts() {
    Account account1 = new Account("name", "type1");
    shadowOf(am).addAccount(account1);

    Account account2 = new Account("name", "type2");
    shadowOf(am).addAccount(account2);

    am.setAuthToken(account1, "token_type_1", "token1");
    am.setAuthToken(account2, "token_type_1", "token1");

    assertThat(am.peekAuthToken(account1, "token_type_1")).isEqualTo("token1");
    assertThat(am.peekAuthToken(account2, "token_type_1")).isEqualTo("token1");

    // invalidate token for type1 account
    am.invalidateAuthToken("type1", "token1");
    assertThat(am.peekAuthToken(account1, "token_type_1")).isNull();
    assertThat(am.peekAuthToken(account2, "token_type_1")).isEqualTo("token1");

    // invalidate token for type2 account
    am.invalidateAuthToken("type2", "token1");
    assertThat(am.peekAuthToken(account1, "token_type_1")).isNull();
    assertThat(am.peekAuthToken(account2, "token_type_1")).isNull();
  }

  @Test
  public void invalidateAuthToken_multipleTokens() {
    Account account = new Account("name", "type1");
    shadowOf(am).addAccount(account);

    am.setAuthToken(account, "token_type_1", "token1");
    am.setAuthToken(account, "token_type_2", "token2");

    assertThat(am.peekAuthToken(account, "token_type_1")).isEqualTo("token1");
    assertThat(am.peekAuthToken(account, "token_type_2")).isEqualTo("token2");

    // invalidate token1
    am.invalidateAuthToken("type1", "token1");
    assertThat(am.peekAuthToken(account, "token_type_1")).isNull();
    assertThat(am.peekAuthToken(account, "token_type_2")).isEqualTo("token2");

    // invalidate token2
    am.invalidateAuthToken("type1", "token2");
    assertThat(am.peekAuthToken(account, "token_type_1")).isNull();
    assertThat(am.peekAuthToken(account, "token_type_2")).isNull();
  }

  @Test
  public void invalidateAuthToken_multipleTokenTypesSameToken() {
    Account account = new Account("name", "type1");
    shadowOf(am).addAccount(account);

    am.setAuthToken(account, "token_type_1", "token1");
    am.setAuthToken(account, "token_type_2", "token1");

    assertThat(am.peekAuthToken(account, "token_type_1")).isEqualTo("token1");
    assertThat(am.peekAuthToken(account, "token_type_2")).isEqualTo("token1");

    // invalidate token1
    am.invalidateAuthToken("type1", "token1");
    assertThat(am.peekAuthToken(account, "token_type_1")).isNull();
    assertThat(am.peekAuthToken(account, "token_type_2")).isNull();
  }

  @Test
  public void addAccount_noActivitySpecified() throws Exception {
    shadowOf(am).addAuthenticator("google.com");

    AccountManagerFuture<Bundle> result = am.addAccount("google.com", "auth_token_type", null, null, null, null, null);

    Bundle resultBundle = result.getResult();

    assertThat(resultBundle.getParcelable(AccountManager.KEY_INTENT)).isNotNull();
  }

  @Test
  public void addAccount_activitySpecified() throws Exception {
    shadowOf(am).addAuthenticator("google.com");

    AccountManagerFuture<Bundle> result = am.addAccount("google.com", "auth_token_type", null, null, new Activity(), null, null);

    Bundle resultBundle = result.getResult();

    assertThat(resultBundle.getString(AccountManager.KEY_ACCOUNT_TYPE)).isEqualTo("google.com");
    assertThat(resultBundle.getString(AccountManager.KEY_ACCOUNT_NAME)).isNotNull();
  }

  @Test
  public void addAccount_shouldCallCallback() throws Exception {
    shadowOf(am).addAuthenticator("google.com");

    AccountManagerCallback<Bundle> callback = mock(AccountManagerCallback.class);
    AccountManagerFuture<Bundle> result = am.addAccount("google.com", "auth_token_type", null, null, new Activity(), callback, null);
    verify(callback, never()).run(any(AccountManagerFuture.class));
    assertFalse(result.isDone());
    shadowOf(am).addAccount(new Account("thebomb@google.com", "google.com"));
    assertTrue(result.isDone());
    AccountManagerFutureMatcher<Bundle> matcher = new AccountManagerFutureMatcher<>(new BaseMatcher<Bundle>() {
      @Override
      public boolean matches(Object o) {
        return "thebomb@google.com".equals(((Bundle) o).getString(AccountManager.KEY_ACCOUNT_NAME));
      }

      @Override
      public void describeTo(Description description) {
        description.appendText("Expected thebomb@google.com");
      }
    });
    verify(callback).run(argThat(allOf(matcher, sameInstance(result))));
    Bundle resultBundle = result.getResult();

    assertThat(resultBundle.getString(AccountManager.KEY_ACCOUNT_TYPE)).isEqualTo("google.com");
    assertThat(resultBundle.getString(AccountManager.KEY_ACCOUNT_NAME)).isNotNull();
  }

  @Test
  public void addAccount_noAuthenticatorDefined() throws Exception {
    try {
      am.addAccount("unknown_account_type", "auth_token_type", null, null, new Activity(), null, null).getResult();
      fail("addAccount() should throw an authenticator exception if no authenticator was registered for this account type");
    } catch(AuthenticatorException e) {
      // Expected
    }
  }

  @Test
  public void addAccount_withOptionsShouldSupportGetNextAddAccountOptions() throws Exception {
    assertThat(shadowOf(am).getNextAddAccountOptions()).isNull();

    shadowOf(am).addAuthenticator("google.com");

    Bundle expectedAddAccountOptions = new Bundle();
    expectedAddAccountOptions.putString("option", "value");
    am.addAccount("google.com", "auth_token_type", null, expectedAddAccountOptions, new Activity(), null, null);

    Bundle actualAddAccountOptions = shadowOf(am).getNextAddAccountOptions();
    assertThat(shadowOf(am).getNextAddAccountOptions()).isNull();
    assertThat(actualAddAccountOptions).isEqualTo(expectedAddAccountOptions);
  }

  @Test
  public void addAccount_withOptionsShouldSupportPeekNextAddAccountOptions() throws Exception {
    assertThat(shadowOf(am).peekNextAddAccountOptions()).isNull();

    shadowOf(am).addAuthenticator("google.com");

    Bundle expectedAddAccountOptions = new Bundle();
    expectedAddAccountOptions.putString("option", "value");
    am.addAccount("google.com", "auth_token_type", null, expectedAddAccountOptions, new Activity(), null, null);

    Bundle actualAddAccountOptions = shadowOf(am).peekNextAddAccountOptions();
    assertThat(shadowOf(am).peekNextAddAccountOptions()).isNotNull();
    assertThat(actualAddAccountOptions).isEqualTo(expectedAddAccountOptions);
  }

  @Test
  @Config(sdk = {
      Build.VERSION_CODES.LOLLIPOP })
  public void addPreviousAccount() {
    Account account = new Account("name_a", "type_a");
    shadowOf(am).setPreviousAccountName(account, "old_name");
    assertThat(am.getPreviousName(account)).isEqualTo("old_name");
  }

  @Test
  public void testGetAsSystemService() throws Exception {
    AccountManager systemService = (AccountManager) app.getSystemService(Context.ACCOUNT_SERVICE);
    assertThat(systemService).isNotNull();
    assertThat(am).isEqualTo(systemService);
  }

  private static class AccountManagerFutureMatcher<T> extends BaseMatcher<AccountManagerFuture<T>> {

    private final Matcher<T> matcher;

    AccountManagerFutureMatcher(Matcher<T> matcher) { this.matcher = matcher; }

    @Override
    public boolean matches(Object o) {
      try {
        return matcher.matches(((AccountManagerFuture) o).getResult());
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }

    @Override
    public void describeTo(Description description) {
      matcher.describeTo(description);
    }
  }
}


text:
<?php

class Imap {

        // Open IMAP connection

        function cimap_open($host, $mailbox, $username, $password)
        {
            return imap_open('{'.$host.':143}'.$mailbox, $username, $password);
        }

        // Find number of msg in mailbox

        function cimap_num_msg($imap_connection)
        {
            return imap_num_msg($imap_connection);
        }

        // Find disk quota amount

        function cimap_get_quota($imap_connection)
        {
            $storage = $quota['STORAGE']= imap_get_quotaroot($imap_connection, "INBOX");

            function kilobyte($filesize)
            {
                return round($filesize / 1024, 2) . ' Mb';
            }

            return kilobyte($storage['usage']) . ' / ' . kilobyte($storage['limit']) . ' (' . round($storage['usage'] / $storage['limit'] * 100, 2) . '%)';
        }

    }

?>


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml
description: Polymer Starter Kit is full of amazing tricks! Let's do a quick introduction and see how to update the theme with custom properties.

{# wf_updated_on: 2015-06-14 #}
{# wf_published_on: 2015-06-14 #}
{# wf_youtube_id: xz-yixRxZN8 #}

# Polymer Starter Kit {: .page-title }

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="xz-yixRxZN8"
          data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>

## In this Week's Episode

### Demo source code
[https://github.com/Polymer/polycasts/tree/master/ep18-starter-kit/polymer-starter-kit](https://github.com/Polymer/polycasts/tree/master/ep18-starter-kit/polymer-starter-kit)

### Polymer Starter Kit
[https://developers.google.com/web/tools/polymer-starter-kit/](/web/tools/polymer-starter-kit/)

### Polymer Yeoman Generator
[https://github.com/yeoman/generator-polymer](https://github.com/yeoman/generator-polymer)

### Theming Elements -- Polycasts #17
[https://www.youtube.com/watch?v=omASiF85JzI&index=1&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN](https://www.youtube.com/watch?v=omASiF85JzI&index=1&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN)

### Give your element an API -- Polycasts #16
[https://www.youtube.com/watch?v=7jolqbtIdiY&index=1&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN](https://www.youtube.com/watch?v=7jolqbtIdiY&index=1&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN)

### Extending native elements -- Polycasts #15
[https://www.youtube.com/watch?v=OV8BvxpNQOs&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN](https://www.youtube.com/watch?v=OV8BvxpNQOs&list=PLOU2XLYxmsII5c3Mgw6fNYCzaWrsM3sMN)

Polymer Slack: [http://bit.ly/polymerslack](http://bit.ly/polymerslack)

Polymer G+ community: [https://plus.google.com/communities/115626364525706131031](https://plus.google.com/communities/115626364525706131031)

[Subscribe](https://goo.gl/mQyv5L) to the Google Developers Channel


text:
These samples demonstrate basic usage of the Authorized Buyers Real-Time
Bidding API.

# Getting Started

To run these samples, you'll need to do the following:

1. If you have not done so already, download and install
   [Python 3.6](https://www.python.org/downloads/release/python-360/), or any
   more recent version of Python 3.
1. Download and install the dependencies used in these samples by running the
   following command:

   ```
   $ pip install -r requirements.txt
   ```
1. For those unfamiliar with using OAuth 2.0 for authentication with Google
   APIs, you should read about the OAuth2
   [Service Account Flow](https://developers.google.com/accounts/docs/OAuth2ServiceAccount)
   because that is the flow used by these samples for authorization to access
   the Authorized Buyers Real-Time Bidding API.
1. Go to the [Google Developers Console](https://console.developers.google.com/)
   and open the menu. Click the `APIs & Services` option and then the
   `Credentials` tab. From here, you can either click the `Create credentials`
   button to create a new Service Account for use with this project, or find an
   existing one under `Manage service accounts`.
1. In the `Manage service accounts` page, you can generate a new key for the
   Service Account by clicking the ellipses in the proper row and selecting
   `Create key` in the resulting menu. This library only supports the JSON key
   files, so select that as the `Key type`. Click the `create` button and the
   file will be generated and downloaded to your computer. Place the JSON file
   in the sample directory. You will need the Service Account email on this
   page for the next step.
1. To authorize a Service Account to access your Authorized Buyers account via
   the API, go to the [Authorized Buyers UI](https://www.google.com/authorizedbuyers)
   and click the `Admin` drop-down menu in the in the navigation bar corner,
   and then click the `Account users` option. Click the `Link Service Account`
   button on this page and enter the Service Account's email to associate it
   with your Authorized Buyers Account.
1. Open **util.py** and update the `KEY_FILE` field to represent the
   path to the JSON key file you downloaded earlier. If you placed it in the
   sample directory, this should just be the filename.
1. Before attempting to run any of the samples, you should update any fields
   containing default values for data sent in API requests. Alternatively, you
   can also provide values for these fields at run-time as command-line
   arguments.

You should now be able to start any of the samples by navigating to their
directory and running them from the command line.


text:
SharePoint 2013 Extended Content Search Web Part

Project Description:
This web part extends the OOTB SharePoint Content Search Web Part to allow you to filter by target audience.

The Target Audience that is being used in this solution is the audience groups you set up in Central Administration.

Then in your Search Schema also in Central Administration, you need to make sure you have an entry for "TargetAudience" with the crawled properties mapped to "Audience, ows_Audience, ows_Target_x0020_Audiences".

Once you deploy the solution, you have to configure the web part to filter the audience by adding in TargetAudienceQuery.  This will filter off of the content's column titled TargetAudience that you set in the library of the content.  The only downfall to this is that you cannot test the query. No results will show.  After you click OK, results will appear and you can test by signing in as another user that is in each of those audience groups you have created.  I usually use a test account I've created that belongs to each of my audiences to test the results.

Special thanks to Srikanth Tiyyaguru who wrote this article:  http://www.codeproject.com/Tips/799307/Extend-Content-Search-web-part-to-add-Target-Audie

This gave me a good start! His solution goes off of the user's sharepoint groups if you need to filter off of that instead.  I had to use audiences.


text:
package io.strimzi.operator.common.operator.resource;

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import io.fabric8.kubernetes.client.dsl.Deletable;
import io.fabric8.kubernetes.client.dsl.Gettable;
import io.fabric8.kubernetes.client.dsl.Listable;
import io.fabric8.kubernetes.client.dsl.Watchable;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.ReconciliationLogger;
import io.vertx.core.AsyncResult;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;

import java.io.Closeable;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

public class ResourceSupport {
    public static final long DEFAULT_TIMEOUT_MS = 300_000;
    protected static final ReconciliationLogger LOGGER = ReconciliationLogger.create(ResourceSupport.class);

    private final Vertx vertx;

    ResourceSupport(Vertx vertx) {
        this.vertx = vertx;
    }

    /**
     * Asynchronously close the given {@code closeable} on a worker thread,
     * returning a Future which completes with the outcome.
     *
     * @param closeable The closeable
     * @return The Future
     */
    public Future<Void> closeOnWorkerThread(Closeable closeable) {
        return executeBlocking(
            blockingFuture -> {
                try {
                    LOGGER.debugOp("Closing {}", closeable);
                    closeable.close();
                    blockingFuture.complete();
                } catch (Throwable t) {
                    blockingFuture.fail(t);
                }
            });
    }

    <T> Future<T> executeBlocking(Handler<Promise<T>> blockingCodeHandler) {
        Promise<T> result = Promise.promise();
        vertx.createSharedWorkerExecutor("kubernetes-ops-pool")
                .executeBlocking(blockingCodeHandler, true, result);
        return result.future();
    }

    /**
     * Combines two completed AsyncResults, at least one of which has failed, returning
     * a single cause, possibly with suppressed exception.
     * If both AsyncResults have failed {@code primary} will be the main cause of failure and
     * {@code secondary} will be a suppressed exception.
     *
     * @param primary The primary failure.
     * @param secondary The secondary failure.
     * @return The cause.
     */
    private Throwable collectCauses(AsyncResult<?> primary,
                            AsyncResult<?> secondary) {
        Throwable cause = primary.cause();
        if (cause == null) {
            cause = secondary.cause();
        } else {
            if (secondary.failed()) {
                cause.addSuppressed(secondary.cause());
            }
        }
        return cause;
    }

    /**
     * Watches the given {@code watchable} using the given
     * {@code watchFn},
     * returning a Future which completes when {@code watchFn} returns non-null
     * to some event on the watchable, or after a timeout.
     *
     * The given {@code watchFn} will be invoked on a worker thread when the
     * Kubernetes resources changes, so may block.
     * When the {@code watchFn} returns non-null the watch will be closed and then
     * the future returned from this method will be completed on the context thread.
     *
     * In some cases such as resource deletion, it might happen that the resource is deleted already before the watch is
     * started and as a result the watch never completes. The {@code preCheckFn} will be invoked on a worker thread
     * after the watch has been created. It is expected to double check if we still need to wait for the watch to fire.
     * When the {@code preCheckFn} returns non-null the watch will be closed and the future returned from this method
     * will be completed with the result of the {@code preCheckFn} on the context thread. In the deletion example
     * described above, the {@code preCheckFn} can check if the resource still exists and close the watch in case it was
     * already deleted.
     *
     * @param reconciliation Reconciliation marker used for logging
     * @param watchable The watchable - used to watch the resource.
     * @param gettable The Gettable - used to get the resource in the pre-check.
     * @param operationTimeoutMs The timeout in ms.
     * @param watchFnDescription A description of what {@code watchFn} is watching for.
     *                           E.g. "observe ${condition} of ${kind} ${namespace}/${name}".
     * @param watchFn The function to determine if the event occured
     * @param preCheckFn Pre-check function to avoid situation when the watch is never fired because ot was started too late.
     * @param <T> The type of watched resource.
     * @param  The result type of the {@code watchFn}.
     *
     * @return A Futures which completes when the {@code watchFn} returns non-null
     * in response to some Kubenetes even on the watched resource(s).
     */
    <T, U> Future selfClosingWatch(Reconciliation reconciliation,
                                      Watchable<T> watchable,
                                      Gettable<T> gettable,
                                      long operationTimeoutMs,
                                      String watchFnDescription,
                                      BiFunction<Watcher.Action, T, U> watchFn,
                                      Function<T, U> preCheckFn) {

        return new Watcher<T>() {
            private final Promise<Watch> watchPromise;
            private final Promise donePromise;
            private final Promise resultPromise;
            private final long timerId;

            /* init */
            {
                this.watchPromise = Promise.promise();
                this.donePromise = Promise.promise();
                this.resultPromise = Promise.promise();
                this.timerId = vertx.setTimer(operationTimeoutMs,
                    ignored -> donePromise.tryFail(new TimeoutException("\"" + watchFnDescription + "\" timed out after " + operationTimeoutMs + "ms")));
                CompositeFuture.join(watchPromise.future(), donePromise.future()).onComplete(joinResult -> {
                    Future<Void> closeFuture;
                    if (watchPromise.future().succeeded()) {
                        closeFuture = closeOnWorkerThread(watchPromise.future().result());
                    } else {
                        closeFuture = Future.succeededFuture();
                    }

                    closeFuture.onComplete(closeResult ->
                        vertx.runOnContext(ignored2 -> {
                            LOGGER.debugCr(reconciliation, "Completing watch future");
                            if (joinResult.succeeded() && closeResult.succeeded()) {
                                resultPromise.complete(joinResult.result().resultAt(1));
                            } else {
                                resultPromise.fail(collectCauses(joinResult, closeResult));
                            }
                        }
                    ));
                });

                try {
                    Watch watch = watchable.watch(this);
                    LOGGER.debugCr(reconciliation, "Opened watch {} for evaluation of {}", watch, watchFnDescription);

                    // Pre-check is done after the watch is open to make sure we did not missed the event. In the worst
                    // case, both pre-check and watch complete the future. But at least one should always complete it.
                    U apply = preCheckFn.apply(gettable.get());
                    if (apply != null) {
                        LOGGER.debugCr(reconciliation, "Pre-check is already complete, no need to wait for the watch: {}", watchFnDescription);
                        donePromise.tryComplete(apply);
                        vertx.cancelTimer(timerId);
                    } else {
                        LOGGER.debugCr(reconciliation, "Pre-check is not complete yet, let's wait for the watch: {}", watchFnDescription);
                    }

                    watchPromise.complete(watch);
                } catch (Throwable t) {
                    watchPromise.fail(t);
                }
            }

            @Override
            public void eventReceived(Action action, T resource) {
                vertx.executeBlocking(
                    f -> {
                        try {
                            U apply = watchFn.apply(action, resource);
                            if (apply != null) {
                                LOGGER.debugCr(reconciliation, "Satisfied: {}", watchFnDescription);
                                f.tryComplete(apply);
                                vertx.cancelTimer(timerId);
                            } else {
                                LOGGER.debugCr(reconciliation, "Not yet satisfied: {}", watchFnDescription);
                            }
                        } catch (Throwable t) {
                            if (!f.tryFail(t)) {
                                LOGGER.debugCr(reconciliation, "Ignoring exception thrown while " +
                                        "evaluating watch {} because the future was already completed", watchFnDescription, t);
                            }
                        }
                    },
                    true,
                        donePromise);
            }

            @Override
            public void onClose(WatcherException cause) {

            }

        }.resultPromise.future();
    }

    /**
     * Asynchronously deletes the given resource(s), returning a Future which completes on the context thread.
     * Note: The API server can return asynchronously, meaning the resource is still accessible from the API server
     * after the returned Future completes. Use {@link #selfClosingWatch(Reconciliation, Watchable, Gettable, long, String, BiFunction, Function)}
     * to provide server-synchronous semantics.
     *
     * @param resource The resource(s) to delete.
     * @return A Future which completes on the context thread.
     */
    Future<Void> deleteAsync(Deletable resource) {
        return executeBlocking(
            blockingFuture -> {
                try {
                    // Returns TRUE when resource was deleted and FALSE when it was not found (see BaseOperation Fabric8 class)
                    // In both cases we return success since the end-result has been achieved
                    // Throws an exception for other errors
                    resource.delete();
                    blockingFuture.complete();
                } catch (Throwable t) {
                    blockingFuture.fail(t);
                }
            });
    }

    /**
     * Asynchronously gets the given resource, returning a Future which completes on the context thread.
     *
     * @param resource The resource(s) to get.
     * @return A Future which completes on the context thread.
     */
    <T> Future<T> getAsync(Gettable<T> resource) {
        return executeBlocking(
            blockingFuture -> {
                try {
                    blockingFuture.complete(resource.get());
                } catch (Throwable t) {
                    blockingFuture.fail(t);
                }
            });
    }

    /**
     * Asynchronously lists the matching resources, returning a Future which completes on the context thread.
     *
     * @param resource The resources to list.
     * @return A Future which completes on the context thread.
     */
    <T extends HasMetadata, L extends KubernetesResourceList<T>> Future<List<T>> listAsync(Listable<L> resource) {
        return executeBlocking(
            blockingFuture -> {
                try {
                    blockingFuture.complete(resource.list().getItems());
                } catch (Throwable t) {
                    blockingFuture.fail(t);
                }
            });
    }
}


text:
A simple web application that can check the status of SDL CIS micro services.

The health check web application functions as a simple proxy server. It provides http endpoints that can be called (without OAuth authentication),
these endpoints then call the configured SDL OData micro service, performs authentication and calls the configured URL. This way you can check if
the micro service works without having to handle the authentication.

Typical use case is to configure the endpoints provided in a load balancer which uses the web application to check the availability of a micro service.

In addition to the healt check functionality the web application also provides functionality to temporarily 'disable' a service by placing a file in a
(configurable) directory. This way it is possible to disable the service from the load balancer without actually stopping the service (making it easier to debug
or check issues).

## Installation

1. Unzip the distribution zip
2. Configure the services to monitor in `./config/services.json` (a default is provided)
3. Configure logging in `./configure/logback.xml` (change the directory where log files are written)

Optional:
* Change the port the web server is listening on by adding an `application.properties` file in `./config` and set the property `server.port` to the required port number.

### Securing passwords in the `services.json` file

Just like in SDL Web 8 (Tridion) cd_* configuration files it is possible to encrypt the passwords in the `services.json` file. Check the SDL Web documentation for the procedure (e.g. as described in point 3 [here](http://docs.sdl.com/LiveContent/content/en-US/SDL%20Web-v1/GUID-9419CF43-DA1E-477F-AEF2-4130115C4C9B)).
## Starting

1. Change to directory where the distribution zip was unpacked
2. Start the web application  `./bin/start.sh`

## Stopping

1. Change to directory where the distribution zip was unpacked
2. Stop the web application  `./bin/stop.sh`

## Usage

Once the web application is started it exposes a number of endpoints that can be used to check the status of a micro service or update the configuration of the web application.
The URLs return an HTTP status code and JSON string with details. If there are no problems with the checked micro service the HTTP status code 200 is returned. Otherwise 500 is returned.

* /status/<servicename>: Check the status of the named service (the service needs to be defined in `./config/services.json`)
* /all: returns the status of all configured services
* /reload: reloads the configured services (from `./config/services.json`)

Assuming that the web application is listening on the default port (8091) the URLs would be:
* <http://localhost:8091/status/discovery> (to check the discovery micro service)
* <http://localhost:8091/all>
* <http://localhost:8091/reload>

## Disabling services

If you want to use the functionality to disable services you need to configure a directory where the indicator files can be placed. This can be configured by
adding a file named `application.properties` to the `config` directory. In the `application.properties` file a property can be set with the name `config.disable.services.location`
which points to a directory where indicator files can be placed.

To disable a service named 'discovery' a file (can be empty) must be created in the configured directory with the same name as the service, in this example `discovery`.

## Building from source

To build from source you need to have a Java 8 SDK installed.

1. Check out the required version of the code
2. Run `gradlew.bat build'` if you are on windows or `./gradlew` if you are on Linux/Mac


text:
<component name="libraryTable">
  <library name="circleimageview-1.3.0">
    <ANNOTATIONS>
      <root url="jar://$PROJECT_DIR$/materialviewpagercontroller/build/intermediates/exploded-aar/de.hdodenhof/circleimageview/1.3.0/annotations.zip!/" />
    </ANNOTATIONS>
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/materialviewpagercontroller/build/intermediates/exploded-aar/de.hdodenhof/circleimageview/1.3.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/materialviewpagercontroller/build/intermediates/exploded-aar/de.hdodenhof/circleimageview/1.3.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/de.hdodenhof/circleimageview/1.3.0/6639a4f5789cb40cd59e7fc9e291867a6a0e6fb/circleimageview-1.3.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}

-- | Implementation of a "ListT done right" from:
-- http://www.haskell.org/haskellwiki/ListT_done_right_alternative.

module NLP.Nerf2.ListT
( ListT (..)
, empty
, singleton
, cons
, append
, foldListT
, liftList
) where

import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Error
import Control.Monad.Cont

import Control.Arrow

newtype ListT m a = ListT { runListT :: m (Maybe (a, ListT m a)) }

-- | An empty `ListT`.
empty :: Monad m => ListT m a
empty = ListT (return Nothing)

-- | A `ListT` with a single element.
singleton :: Monad m => a -> ListT m a
singleton = flip cons empty

-- | A cons operation.
cons :: Monad m => a -> ListT m a -> ListT m a
cons = curry (ListT . return . Just)

-- | Append two ListT transformers.
append :: Monad m => ListT m a -> ListT m a -> ListT m a
append (ListT m1) (ListT m2) = ListT $
    maybe m2 (return . Just . second (`append` ListT m2)) =<< m1

foldListT :: Monad m => (a -> m b -> m b) -> m b -> ListT m a -> m b
foldListT c n (ListT m) = maybe n (\(x,l) -> c x (foldListT c n l)) =<< m

-- In ListT from Control.Monad this one is the data constructor ListT, so sadly, this code can't be a drop-in replacement.
liftList :: Monad m => [a] -> ListT m a
liftList [] = ListT $ return Nothing
liftList (x:xs) = ListT . return $ Just (x, liftList xs)

instance Functor m => Functor (ListT m) where
  fmap f (ListT m) = ListT $ fmap (fmap $ f *** fmap f) m where

instance (Monad m) => Monad (ListT m) where
  return x = ListT . return $ Just (x, mzero)
  m >>= f = ListT $
    foldListT (\x l -> runListT $ f x `mplus` ListT l) (return Nothing) m

instance MonadTrans ListT where
  lift = ListT . liftM (\x -> Just (x, mzero))

instance Monad m => MonadPlus (ListT m) where
  mzero = empty
  mplus = append

-- These things typecheck, but I haven't made sure what they do is sensible.
instance (MonadIO m, Functor m) => MonadIO (ListT m) where
  liftIO = lift . liftIO

instance (MonadReader s m, Functor m) => MonadReader s (ListT m) where
  ask     = lift ask
  local f = ListT . local f . runListT

instance (MonadState s m, Functor m) => MonadState s (ListT m) where
  get = lift get
  put = lift . put

instance MonadCont m => MonadCont (ListT m) where
  callCC f = ListT $
    callCC $ \c -> runListT . f $ \a ->
      ListT . c $ Just (a, ListT $ return Nothing)

instance (MonadError e m) => MonadError e (ListT m) where
  throwError = lift . throwError
  -- I can't really decide between those two possible implementations.
  -- The first one is more like the IO monad works, the second one catches
  -- all possible errors in the list.
--  ListT m `catchError` h = ListT $ m `catchError` \e -> runListT (h e)
  (m :: ListT m a) `catchError` h = deepCatch m where
    deepCatch :: ListT m a -> ListT m a
    deepCatch (ListT xs) = ListT $ liftM (fmap $ second deepCatch) xs
      `catchError` \e -> runListT (h e)


text:
from flask import Flask, Markup
from markdown import markdown
from datetime import datetime

from reimu.blog import blog
from reimu.admin import admin
from reimu.auth import auth

# Initialize application
app = Flask(__name__)

# Load configuration
app.config.from_object('reimu.config')

# Register blueprints
app.register_blueprint(blog)
app.register_blueprint(admin)
app.register_blueprint(auth)

# Register filters
@app.template_filter('markdown')
def markdown_filter(data):
    return Markup(markdown(data))

@app.template_filter('ru_date')
def ru_date_filter(data):
    return datetime.strptime(data, '%Y-%m-%d').strftime('%d.%m.%Y')