text:
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file ParticipantProxyData.cpp
 *
 */

#include <fastdds/rtps/builtin/data/ParticipantProxyData.h>

#include <fastdds/dds/log/Log.hpp>

#include <fastdds/rtps/builtin/BuiltinProtocols.h>
#include <fastdds/rtps/builtin/data/WriterProxyData.h>
#include <fastdds/rtps/builtin/data/ReaderProxyData.h>
#include <fastdds/rtps/builtin/discovery/participant/PDPSimple.h>
#include <fastdds/rtps/network/NetworkFactory.h>
#include <fastdds/rtps/resources/TimedEvent.h>
#include <fastrtps/utils/TimeConversion.h>

#include <fastdds/core/policy/ParameterList.hpp>
#include <fastdds/core/policy/QosPoliciesSerializer.hpp>
#include <fastrtps_deprecated/participant/ParticipantImpl.h>
#include <rtps/transport/shared_mem/SHMLocator.hpp>

#include "ProxyDataFilters.hpp"
#include "ProxyHashTables.hpp"

#include <mutex>
#include <chrono>

using namespace eprosima::fastrtps;
using ParameterList = eprosima::fastdds::dds::ParameterList;

namespace eprosima {
namespace fastrtps {
namespace rtps {

ParticipantProxyData::ParticipantProxyData(
        const RTPSParticipantAllocationAttributes& allocation)
    : m_protocolVersion(c_ProtocolVersion)
    , m_VendorId(c_VendorId_Unknown)
    , m_expectsInlineQos(false)
    , m_availableBuiltinEndpoints(0)
    , metatraffic_locators(allocation.locators.max_unicast_locators, allocation.locators.max_multicast_locators)
    , default_locators(allocation.locators.max_unicast_locators, allocation.locators.max_multicast_locators)
    , m_manualLivelinessCount ()
#if HAVE_SECURITY
    , security_attributes_(0UL)
    , plugin_security_attributes_(0UL)
#endif // if HAVE_SECURITY
    , isAlive(false)
    , m_properties(static_cast<uint32_t>(allocation.data_limits.max_properties))
    , lease_duration_event(nullptr)
    , should_check_lease_duration(false)
    , m_readers(new ProxyHashTable<ReaderProxyData>(allocation.readers))
    , m_writers(new ProxyHashTable<WriterProxyData>(allocation.writers))
{
    m_userData.set_max_size(static_cast<uint32_t>(allocation.data_limits.max_user_data));
}

ParticipantProxyData::ParticipantProxyData(
        const ParticipantProxyData& pdata)
    : m_protocolVersion(pdata.m_protocolVersion)
    , m_guid(pdata.m_guid)
    , m_VendorId(pdata.m_VendorId)
    , m_expectsInlineQos(pdata.m_expectsInlineQos)
    , m_availableBuiltinEndpoints(pdata.m_availableBuiltinEndpoints)
    , metatraffic_locators(pdata.metatraffic_locators)
    , default_locators(pdata.default_locators)
    , m_manualLivelinessCount ()
    , m_participantName(pdata.m_participantName)
    , m_key(pdata.m_key)
    , m_leaseDuration(pdata.m_leaseDuration)
#if HAVE_SECURITY
    , identity_token_(pdata.identity_token_)
    , permissions_token_(pdata.permissions_token_)
    , security_attributes_(pdata.security_attributes_)
    , plugin_security_attributes_(pdata.plugin_security_attributes_)
#endif // if HAVE_SECURITY
    , isAlive(pdata.isAlive)
    , m_properties(pdata.m_properties)
    , m_userData(pdata.m_userData)
    , lease_duration_event(nullptr)
    , should_check_lease_duration(false)
    // This method is only called when calling the participant discovery listener and the
    // corresponding DiscoveredParticipantInfo struct is created. Only participant info is used,
    // so there is no need to copy m_readers and m_writers
    , m_readers(nullptr)
    , m_writers(nullptr)
    , lease_duration_(pdata.lease_duration_)
{
}

ParticipantProxyData::~ParticipantProxyData()
{
    logInfo(RTPS_PARTICIPANT, m_guid);

    // delete all reader proxies
    if (m_readers)
    {
        for (ProxyHashTable<ReaderProxyData>::value_type val : *m_readers)
        {
            delete val.second;
        }

        delete m_readers;
    }

    // delete all writers proxies
    if (m_writers)
    {
        for (ProxyHashTable<WriterProxyData>::value_type val : *m_writers)
        {
            delete val.second;
        }

        delete m_writers;
    }

    if (lease_duration_event != nullptr)
    {
        delete lease_duration_event;
    }
}

uint32_t ParticipantProxyData::get_serialized_size(
        bool include_encapsulation) const
{
    uint32_t ret_val = include_encapsulation ? 4 : 0;

    // PID_PROTOCOL_VERSION
    ret_val += 4 + 4;

    // PID_VENDORID
    ret_val += 4 + 4;

    if (m_expectsInlineQos)
    {
        // PID_EXPECTS_INLINE_QOS
        ret_val += 4 + PARAMETER_BOOL_LENGTH;
    }

    // PID_PARTICIPANT_GUID
    ret_val += 4 + PARAMETER_GUID_LENGTH;

    // PID_METATRAFFIC_MULTICAST_LOCATOR
    ret_val += static_cast<uint32_t>((4 + PARAMETER_LOCATOR_LENGTH) * metatraffic_locators.multicast.size());

    // PID_METATRAFFIC_UNICAST_LOCATOR
    ret_val += static_cast<uint32_t>((4 + PARAMETER_LOCATOR_LENGTH) * metatraffic_locators.unicast.size());

    // PID_DEFAULT_UNICAST_LOCATOR
    ret_val += static_cast<uint32_t>((4 + PARAMETER_LOCATOR_LENGTH) * default_locators.unicast.size());

    // PID_DEFAULT_MULTICAST_LOCATOR
    ret_val += static_cast<uint32_t>((4 + PARAMETER_LOCATOR_LENGTH) * default_locators.multicast.size());

    // PID_PARTICIPANT_LEASE_DURATION
    ret_val += 4 + PARAMETER_TIME_LENGTH;

    // PID_BUILTIN_ENDPOINT_SET
    ret_val += 4 + PARAMETER_BUILTINENDPOINTSET_LENGTH;

    if (m_participantName.size() > 0)
    {
        // PID_ENTITY_NAME
        ret_val += fastdds::dds::ParameterSerializer<Parameter_t>::cdr_serialized_size(m_participantName);
    }

    if (m_userData.size() > 0)
    {
        // PID_USER_DATA
        ret_val += fastdds::dds::QosPoliciesSerializer<UserDataQosPolicy>::cdr_serialized_size(m_userData);
    }

    if (m_properties.size() > 0)
    {
        // PID_PROPERTY_LIST
        ret_val += fastdds::dds::ParameterSerializer<ParameterPropertyList_t>::cdr_serialized_size(m_properties);
    }

#if HAVE_SECURITY
    if (!identity_token_.class_id().empty())
    {
        // PID_IDENTITY_TOKEN
        ret_val += fastdds::dds::ParameterSerializer<Parameter_t>::cdr_serialized_size(identity_token_);
    }

    if (!permissions_token_.class_id().empty())
    {
        // PID_PERMISSIONS_TOKEN
        ret_val += fastdds::dds::ParameterSerializer<Parameter_t>::cdr_serialized_size(permissions_token_);
    }

    if ((security_attributes_ != 0UL) || (plugin_security_attributes_ != 0UL))
    {
        // PID_PARTICIPANT_SECURITY_INFO
        ret_val += 4 + PARAMETER_PARTICIPANT_SECURITY_INFO_LENGTH;
    }
#endif // if HAVE_SECURITY

    // PID_SENTINEL
    return ret_val + 4;
}

bool ParticipantProxyData::writeToCDRMessage(
        CDRMessage_t* msg,
        bool write_encapsulation)
{
    if (write_encapsulation)
    {
        if (!ParameterList::writeEncapsulationToCDRMsg(msg))
        {
            return false;
        }
    }

    {
        ParameterProtocolVersion_t p(fastdds::dds::PID_PROTOCOL_VERSION, 4);
        p.protocolVersion = this->m_protocolVersion;
        if (!fastdds::dds::ParameterSerializer<ParameterProtocolVersion_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    {
        ParameterVendorId_t p(fastdds::dds::PID_VENDORID, 4);
        p.vendorId[0] = this->m_VendorId[0];
        p.vendorId[1] = this->m_VendorId[1];
        if (!fastdds::dds::ParameterSerializer<ParameterVendorId_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    if (this->m_expectsInlineQos)
    {
        ParameterBool_t p(fastdds::dds::PID_EXPECTS_INLINE_QOS, PARAMETER_BOOL_LENGTH, m_expectsInlineQos);
        if (!fastdds::dds::ParameterSerializer<ParameterBool_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    {
        ParameterGuid_t p(fastdds::dds::PID_PARTICIPANT_GUID, PARAMETER_GUID_LENGTH, m_guid);
        if (!fastdds::dds::ParameterSerializer<ParameterGuid_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    for (const Locator_t& it : metatraffic_locators.multicast)
    {
        ParameterLocator_t p(fastdds::dds::PID_METATRAFFIC_MULTICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, it);
        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    for (const Locator_t& it : metatraffic_locators.unicast)
    {
        ParameterLocator_t p(fastdds::dds::PID_METATRAFFIC_UNICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, it);
        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    for (const Locator_t& it : default_locators.unicast)
    {
        ParameterLocator_t p(fastdds::dds::PID_DEFAULT_UNICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, it);
        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    for (const Locator_t& it : default_locators.multicast)
    {
        ParameterLocator_t p(fastdds::dds::PID_DEFAULT_MULTICAST_LOCATOR, PARAMETER_LOCATOR_LENGTH, it);
        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    {
        ParameterTime_t p(fastdds::dds::PID_PARTICIPANT_LEASE_DURATION, PARAMETER_TIME_LENGTH);
        p.time = m_leaseDuration;
        if (!fastdds::dds::ParameterSerializer<ParameterTime_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
    {
        ParameterBuiltinEndpointSet_t p(fastdds::dds::PID_BUILTIN_ENDPOINT_SET, PARAMETER_BUILTINENDPOINTSET_LENGTH);
        p.endpointSet = m_availableBuiltinEndpoints;
        if (!fastdds::dds::ParameterSerializer<ParameterBuiltinEndpointSet_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }

    if (m_participantName.size() > 0)
    {
        ParameterString_t p(fastdds::dds::PID_ENTITY_NAME, 0, m_participantName);
        if (!fastdds::dds::ParameterSerializer<ParameterString_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }

    if (m_userData.size() > 0)
    {
        if (!fastdds::dds::QosPoliciesSerializer<UserDataQosPolicy>::add_to_cdr_message(m_userData,
                msg))
        {
            return false;
        }
    }

    if (m_properties.size() > 0)
    {
        if (!fastdds::dds::ParameterSerializer<ParameterPropertyList_t>::add_to_cdr_message(m_properties, msg))
        {
            return false;
        }
    }

#if HAVE_SECURITY
    if (!identity_token_.class_id().empty())
    {
        ParameterToken_t p(fastdds::dds::PID_IDENTITY_TOKEN, 0);
        p.token = identity_token_;
        if (!fastdds::dds::ParameterSerializer<ParameterToken_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }

    if (!permissions_token_.class_id().empty())
    {
        ParameterToken_t p(fastdds::dds::PID_PERMISSIONS_TOKEN, 0);
        p.token = permissions_token_;
        if (!fastdds::dds::ParameterSerializer<ParameterToken_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }

    if ((security_attributes_ != 0UL) || (plugin_security_attributes_ != 0UL))
    {
        ParameterParticipantSecurityInfo_t p;
        p.security_attributes = security_attributes_;
        p.plugin_security_attributes = plugin_security_attributes_;
        if (!fastdds::dds::ParameterSerializer<ParameterParticipantSecurityInfo_t>::add_to_cdr_message(p, msg))
        {
            return false;
        }
    }
#endif // if HAVE_SECURITY

    return fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(msg);
}

bool ParticipantProxyData::readFromCDRMessage(
        CDRMessage_t* msg,
        bool use_encapsulation,
        const NetworkFactory& network,
        bool is_shm_transport_available)
{
    bool are_shm_metatraffic_locators_present = false;
    bool are_shm_default_locators_present = false;
    bool is_shm_transport_possible = false;

    auto param_process = [this, &network, &is_shm_transport_possible,
                    &are_shm_metatraffic_locators_present,
                    &are_shm_default_locators_present,
                    &is_shm_transport_available](CDRMessage_t* msg, const ParameterId_t& pid, uint16_t plength)
            {
                switch (pid)
                {
                    case fastdds::dds::PID_KEY_HASH:
                    {
                        ParameterKey_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterKey_t>::read_from_cdr_message(p, msg, plength))
                        {
                            return false;
                        }

                        GUID_t guid;
                        iHandle2GUID(guid, p.key);
                        m_guid = guid;
                        m_key = p.key;
                        break;
                    }
                    case fastdds::dds::PID_PROTOCOL_VERSION:
                    {
                        ParameterProtocolVersion_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterProtocolVersion_t>::read_from_cdr_message(p,
                                msg, plength))
                        {
                            return false;
                        }

                        if (p.protocolVersion.m_major < c_ProtocolVersion.m_major)
                        {
                            return false;
                        }
                        m_protocolVersion = p.protocolVersion;
                        break;
                    }
                    case fastdds::dds::PID_VENDORID:
                    {
                        ParameterVendorId_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterVendorId_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        m_VendorId[0] = p.vendorId[0];
                        m_VendorId[1] = p.vendorId[1];
                        is_shm_transport_available &= (m_VendorId == c_VendorId_eProsima);
                        break;
                    }
                    case fastdds::dds::PID_EXPECTS_INLINE_QOS:
                    {
                        ParameterBool_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterBool_t>::read_from_cdr_message(p, msg, plength))
                        {
                            return false;
                        }

                        m_expectsInlineQos = p.value;
                        break;
                    }
                    case fastdds::dds::PID_PARTICIPANT_GUID:
                    {
                        ParameterGuid_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterGuid_t>::read_from_cdr_message(p, msg, plength))
                        {
                            return false;
                        }

                        m_guid = p.guid;
                        m_key = p.guid;
                        break;
                    }
                    case fastdds::dds::PID_METATRAFFIC_MULTICAST_LOCATOR:
                    {
                        ParameterLocator_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        Locator_t temp_locator;
                        if (network.transform_remote_locator(p.locator, temp_locator))
                        {
                            ProxyDataFilters::filter_locators(
                                is_shm_transport_available,
                                &is_shm_transport_possible,
                                &are_shm_metatraffic_locators_present,
                                &metatraffic_locators,
                                temp_locator,
                                false);
                        }
                        break;
                    }
                    case fastdds::dds::PID_METATRAFFIC_UNICAST_LOCATOR:
                    {
                        ParameterLocator_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        Locator_t temp_locator;
                        if (network.transform_remote_locator(p.locator, temp_locator))
                        {
                            ProxyDataFilters::filter_locators(
                                is_shm_transport_available,
                                &is_shm_transport_possible,
                                &are_shm_metatraffic_locators_present,
                                &metatraffic_locators,
                                temp_locator,
                                true);
                        }
                        break;
                    }
                    case fastdds::dds::PID_DEFAULT_UNICAST_LOCATOR:
                    {
                        ParameterLocator_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        Locator_t temp_locator;
                        if (network.transform_remote_locator(p.locator, temp_locator))
                        {
                            ProxyDataFilters::filter_locators(
                                is_shm_transport_available,
                                &is_shm_transport_possible,
                                &are_shm_default_locators_present,
                                &default_locators,
                                temp_locator,
                                true);
                        }
                        break;
                    }
                    case fastdds::dds::PID_DEFAULT_MULTICAST_LOCATOR:
                    {
                        ParameterLocator_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterLocator_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        Locator_t temp_locator;
                        if (network.transform_remote_locator(p.locator, temp_locator))
                        {
                            ProxyDataFilters::filter_locators(
                                is_shm_transport_available,
                                &is_shm_transport_possible,
                                &are_shm_default_locators_present,
                                &default_locators,
                                temp_locator,
                                false);
                        }
                        break;
                    }
                    case fastdds::dds::PID_PARTICIPANT_LEASE_DURATION:
                    {
                        ParameterTime_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterTime_t>::read_from_cdr_message(p, msg, plength))
                        {
                            return false;
                        }

                        m_leaseDuration = p.time.to_duration_t();
                        lease_duration_ =
                                std::chrono::microseconds(TimeConv::Duration_t2MicroSecondsInt64(
                                            m_leaseDuration));
                        break;
                    }
                    case fastdds::dds::PID_BUILTIN_ENDPOINT_SET:
                    {
                        ParameterBuiltinEndpointSet_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterBuiltinEndpointSet_t>::read_from_cdr_message(p,
                                msg, plength))
                        {
                            return false;
                        }

                        m_availableBuiltinEndpoints = p.endpointSet;
                        break;
                    }
                    case fastdds::dds::PID_ENTITY_NAME:
                    {
                        ParameterString_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterString_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        m_participantName = p.getName();
                        break;
                    }
                    case fastdds::dds::PID_PROPERTY_LIST:
                    {
                        if (!fastdds::dds::ParameterSerializer<ParameterPropertyList_t>::read_from_cdr_message(
                                    m_properties, msg, plength))
                        {
                            return false;
                        }
                        break;
                    }
                    case fastdds::dds::PID_USER_DATA:
                    {
                        if (!fastdds::dds::QosPoliciesSerializer<UserDataQosPolicy>::read_from_cdr_message(m_userData,
                                msg, plength))
                        {
                            return false;
                        }
                        break;
                    }
                    case fastdds::dds::PID_IDENTITY_TOKEN:
                    {
#if HAVE_SECURITY
                        ParameterToken_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterToken_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        identity_token_ = std::move(p.token);
#else
                        logWarning(RTPS_PARTICIPANT, "Received PID_IDENTITY_TOKEN but security is disabled");
#endif // if HAVE_SECURITY
                        break;
                    }
                    case fastdds::dds::PID_PERMISSIONS_TOKEN:
                    {
#if HAVE_SECURITY
                        ParameterToken_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterToken_t>::read_from_cdr_message(p, msg,
                                plength))
                        {
                            return false;
                        }

                        permissions_token_ = std::move(p.token);
#else
                        logWarning(RTPS_PARTICIPANT, "Received PID_PERMISSIONS_TOKEN but security is disabled");
#endif // if HAVE_SECURITY
                        break;
                    }

                    case fastdds::dds::PID_PARTICIPANT_SECURITY_INFO:
                    {
#if HAVE_SECURITY
                        ParameterParticipantSecurityInfo_t p(pid, plength);
                        if (!fastdds::dds::ParameterSerializer<ParameterParticipantSecurityInfo_t>::
                                read_from_cdr_message(p, msg, plength))
                        {
                            return false;
                        }

                        security_attributes_ = p.security_attributes;
                        plugin_security_attributes_ = p.plugin_security_attributes;
#else
                        logWarning(RTPS_PARTICIPANT,
                                "Received PID_PARTICIPANT_SECURITY_INFO but security is disabled");
#endif // if HAVE_SECURITY
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }

                return true;
            };

    uint32_t qos_size;
    clear();
    try
    {
        return ParameterList::readParameterListfromCDRMsg(*msg, param_process, use_encapsulation, qos_size);
    }
    catch (std::bad_alloc& ba)
    {
        std::cerr << "bad_alloc caught: " << ba.what() << '\n';
        return false;
    }
}

void ParticipantProxyData::clear()
{
    m_protocolVersion = ProtocolVersion_t();
    m_guid = GUID_t();
    //set_VendorId_Unknown(m_VendorId);
    m_VendorId = c_VendorId_Unknown;
    m_expectsInlineQos = false;
    m_availableBuiltinEndpoints = 0;
    metatraffic_locators.unicast.clear();
    metatraffic_locators.multicast.clear();
    default_locators.unicast.clear();
    default_locators.multicast.clear();
    m_participantName = "";
    m_key = InstanceHandle_t();
    m_leaseDuration = Duration_t();
    lease_duration_ = std::chrono::microseconds::zero();
    isAlive = true;
#if HAVE_SECURITY
    identity_token_ = IdentityToken();
    permissions_token_ = PermissionsToken();
    security_attributes_ = 0UL;
    plugin_security_attributes_ = 0UL;
#endif // if HAVE_SECURITY
    m_properties.clear();
    m_properties.length = 0;
    m_userData.clear();
    m_userData.length = 0;
}

void ParticipantProxyData::copy(
        const ParticipantProxyData& pdata)
{
    m_protocolVersion = pdata.m_protocolVersion;
    m_guid = pdata.m_guid;
    m_VendorId[0] = pdata.m_VendorId[0];
    m_VendorId[1] = pdata.m_VendorId[1];
    m_availableBuiltinEndpoints = pdata.m_availableBuiltinEndpoints;
    metatraffic_locators = pdata.metatraffic_locators;
    default_locators = pdata.default_locators;
    m_participantName = pdata.m_participantName;
    m_leaseDuration = pdata.m_leaseDuration;
    lease_duration_ = std::chrono::microseconds(TimeConv::Duration_t2MicroSecondsInt64(pdata.m_leaseDuration));
    m_key = pdata.m_key;
    isAlive = pdata.isAlive;
    m_userData = pdata.m_userData;
    m_properties = pdata.m_properties;

    // This method is only called when a new participant is discovered.The destination of the copy
    // will always be a new ParticipantProxyData or one from the pool, so there is no need for
    // m_readers and m_writers to be copied

#if HAVE_SECURITY
    identity_token_ = pdata.identity_token_;
    permissions_token_ = pdata.permissions_token_;
    security_attributes_ = pdata.security_attributes_;
    plugin_security_attributes_ = pdata.plugin_security_attributes_;
#endif // if HAVE_SECURITY
}

bool ParticipantProxyData::updateData(
        ParticipantProxyData& pdata)
{
    metatraffic_locators = pdata.metatraffic_locators;
    default_locators = pdata.default_locators;
    m_leaseDuration = pdata.m_leaseDuration;
    isAlive = true;
    m_userData = pdata.m_userData;
    m_properties = pdata.m_properties;
#if HAVE_SECURITY
    identity_token_ = pdata.identity_token_;
    permissions_token_ = pdata.permissions_token_;
    security_attributes_ = pdata.security_attributes_;
    plugin_security_attributes_ = pdata.plugin_security_attributes_;
#endif // if HAVE_SECURITY
    auto new_lease_duration = std::chrono::microseconds(TimeConv::Duration_t2MicroSecondsInt64(m_leaseDuration));
    if (lease_duration_event != nullptr)
    {
        if (new_lease_duration < lease_duration_)
        {
            // Calculate next trigger.
            auto real_lease_tm = last_received_message_tm_ + new_lease_duration;
            auto next_trigger = real_lease_tm - std::chrono::steady_clock::now();
            lease_duration_event->cancel_timer();
            lease_duration_event->update_interval_millisec(
                (double)std::chrono::duration_cast<std::chrono::milliseconds>(next_trigger).count());
            lease_duration_event->restart_timer();
        }
    }
    lease_duration_ = new_lease_duration;
    return true;
}

void ParticipantProxyData::set_persistence_guid(
        const GUID_t& guid)
{
    // only valid values
    if (guid == c_Guid_Unknown)
    {
        return;
    }

    // generate pair
    std::pair<std::string, std::string> persistent_guid;
    persistent_guid.first = fastdds::dds::parameter_property_persistence_guid;

    std::ostringstream data;
    data << guid;
    persistent_guid.second = data.str();

    // if exists replace
    ParameterPropertyList_t::iterator it = std::find_if(
        m_properties.begin(),
        m_properties.end(),
        [&persistent_guid](const fastdds::dds::ParameterProperty_t& p)
        {
            return persistent_guid.first == p.first();
        });

    if (it != m_properties.end())
    {
        if (!it->modify(persistent_guid))
        {
            logError(RTPS_PARTICIPANT, "Failed to change property <"
                    << it->first() << " | " << it->second() << "> to <"
                    << persistent_guid.first << " | " << persistent_guid.second << ">");
        }
    }
    else
    {
        // if not exists add
        m_properties.push_back(persistent_guid.first, persistent_guid.second);
    }
}

GUID_t ParticipantProxyData::get_persistence_guid() const
{
    GUID_t persistent(c_Guid_Unknown);

    ParameterPropertyList_t::const_iterator it = std::find_if(
        m_properties.begin(),
        m_properties.end(),
        [](const fastdds::dds::ParameterProperty_t p)
        {
            return fastdds::dds::parameter_property_persistence_guid == p.first();
        });

    if (it != m_properties.end())
    {
        std::istringstream in(it->second());
        in >> persistent;
    }

    return persistent;
}

void ParticipantProxyData::set_sample_identity(
        const SampleIdentity& sid)
{
    fastdds::dds::set_proxy_property(sid, "PID_CLIENT_SERVER_KEY", m_properties);
}

SampleIdentity ParticipantProxyData::get_sample_identity() const
{
    return fastdds::dds::get_proxy_property<SampleIdentity>("PID_CLIENT_SERVER_KEY", m_properties);
}

void ParticipantProxyData::set_backup_stamp(
        const GUID_t& guid)
{
    fastdds::dds::set_proxy_property(guid, "PID_BACKUP_STAMP", m_properties);
}

GUID_t ParticipantProxyData::get_backup_stamp() const
{
    return fastdds::dds::get_proxy_property<GUID_t>("PID_BACKUP_STAMP", m_properties);
}

void ParticipantProxyData::assert_liveliness()
{
    last_received_message_tm_ = std::chrono::steady_clock::now();
}

} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Raven.Abstractions.Data;
using Raven.Abstractions.Indexing;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
using Raven.Client.Linq;
using Raven.Json.Linq;
using Raven.Storage.Esent.SchemaUpdates.Updates;
using Shared;

namespace SimpleIndex
{
	class Program
	{
	    public class UserSearchIndex : AbstractIndexCreationTask<User>
	    {
            public UserSearchIndex()
	        {
	            Map = users => from user in users
	                select new
	                {
	                    Query = new[]
	                    {
                            user.Name,
                            user.Email,
                            user.LastName,
                            user.Name + " " + user.LastName
	                    }.Concat(user.Email.Split('@')).ToArray()
	                };
	        }
	    }

	    public class UserSearchIndexWithDynamicFields: AbstractIndexCreationTask<User>
	    {
            //dynamic fields
	        public UserSearchIndexWithDynamicFields()
	        {
	            Map = users => from user in users
	                select new
	                {
                        user.Name,
                        user.Email,
                        //since Address is stored as Json object,
                        //and can be treated as tuple collection, we can do this
                        _ = user.Address.Select(x => CreateField(x.Key,x.Value))
	                };
	        }
	    }

		static void Main(string[] args)
		{
		    using (var store = new EmbeddableDocumentStore
		    {
		        RunInMemory = true
		    })
		    {
		        store.Initialize();
		        var users = GenerateUsers();

                using (var session = store.OpenSession())
		        {
		            foreach (var user in users)
		                session.Store(user);
                    session.SaveChanges();
		        }

                new UserSearchIndex().Execute(store);
                new UserSearchIndexWithDynamicFields().Execute(store);

		        using (var session = store.OpenSession())
		        {
		            var usersFromZhaoProvince = session.Advanced
                                                       .LuceneQuery<User, UserSearchIndexWithDynamicFields>()
                                                       .WaitForNonStaleResults()
                                                       .Search("Province","Zhao")
                                                       .ToList();

                    Console.WriteLine("Users from Zhao province (dynamic field in the index)");
		            foreach (var user in usersFromZhaoProvince)
                        Console.WriteLine(user);

                    Console.WriteLine("\n users with email domain 'foo.com'");
                    var usersByEmailDomain = session.Query<User,UserSearchIndex>()
                                                    .Customize(x => x.WaitForNonStaleResults())
                                                    .Search(x => x.Query,"foo.com")
                                                    .ToList();

                    foreach (var user in usersByEmailDomain)
                        Console.WriteLine(user);

                    Console.WriteLine("\n users with email domain 'foo.com' and name Bob");
                    var usersByEmailDomainAndName = session.Query<User, UserSearchIndex>()
                                                           .Search(x => x.Query, "foo.com Bob", options: SearchOptions.And)
                                                           .ToList();

                    foreach (var user in usersByEmailDomainAndName)
                        Console.WriteLine(user);
                }
		    }
		}

	    private static IEnumerable<User> GenerateUsers()
	    {
            yield return new User
            {
                Name = "Bob Lee",
                Email = "foobar2@foo.com",
                Address = RavenJObject.FromObject(new
                {
                    State = "Arizona",
                    Area = 51
                })
            };

            yield return new User
            {
                Name = "Bob Levi",
                Email = "foobar1@foo.com",
                Address = RavenJObject.FromObject(new
                {
                    State = "Arizona",
                    Area = 51
                })
            };

            yield return new User
            {
                Name = "John",
                Email = "john@foo.com",
                Address = RavenJObject.FromObject(new
                {
                    City = "Paris",
                    Street = "Sesame str.",
                    Country = "France"
                })
            };

            yield return new User
            {
                Name = "Kenny",
                Email = "kenny@bar.com",
                Address = RavenJObject.FromObject(new
                {
                    Country = "Zimbabwe"
                })
            };

            yield return new User
            {
                Name = "Sun Tsu",
                Email = "sun.tsu@bar.com",
                Address = RavenJObject.FromObject(new
                {
                    Country = "China",
                    Province = "Hao"
                })
            };

            yield return new User
            {
                Name = "john woo",
                Email = "john.woo@bar.com",
                Address = RavenJObject.FromObject(new
                {
                    Country = "China",
                    Province = "Hao"
                })
            };

            yield return new User
            {
                Name = "Lao Tse",
                Email = "lao.tse@bar.com",
                Address = RavenJObject.FromObject(new
                {
                    Country = "China",
                    Province = "Zhao"
                })
            };
            yield return new User
            {
                Name = "Kong Fu-Tse",
                Email = "kong-fu.tse@bar.com",
                Address = RavenJObject.FromObject(new
                {
                    City = "FooBar",
                    Country = "China",
                    Province = "Zhao"
                })
            };
        }
	}
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview Modified version of Silverlight.js to work with
 * the compiler's advanced modes. The API should be the same, except
 * that they're namespaced under goog.silverlight instead of Silverlight.
 *
 * We've also modified this so that the silverlight bootstrapper
 * does not run by default. If you need to start up silverlight, you
 * should explicitly call goog.silverlight.startup().
 *
 * @author nicksantos@google.com (Nick Santos) (ported to Closure)
 */

goog.provide('goog.silverlight');

/**
 * Counter of globalized event handlers
 * @type {number}
 */
goog.silverlight._silverlightCount = 0;

/**
 * Prevents onSilverlightInstalled from being called multiple
 * times
 * @type {boolean}
 */
goog.silverlight.__onSilverlightInstalledCalled = false;

/**
 * Prefix for fwlink URL's
 * @type {string}
 */
goog.silverlight.fwlinkRoot = 'http://go2.microsoft.com/fwlink/?LinkID=';

/**
 * Ensures that only one Installation State event is fired.
 * @type {boolean}
 */
goog.silverlight.__installationEventFired = false;

/**
 * Called by goog.silverlight.getSilverlight to notify the page that a user
 * has requested the Silverlight installer
 * @type {Function}
 */
goog.silverlight.onGetSilverlight = null;

/**
 * Called by Silverlight.waitForInstallCompletion when the page detects
 * that Silverlight has been installed. The event handler is not called
 * in upgrade scenarios.
 */
goog.silverlight.onSilverlightInstalled = function() {
  window.location.reload(false);
};

/**
 * Checks to see if the correct version is installed.
 * @param {?string=} version The silverlight version.
 * @return {boolean} Whether silverlight is installed.
 */
goog.silverlight.isInstalled = function(version) {
  if (version == undefined)
    version = null;

  var isVersionSupported = false;
  var container = null;

  try {
    var control = null;
    var tryNS = false;
    if (typeof ActiveXObject == 'undefined') {
      try {
        control = new ActiveXObject('AgControl.AgControl');
        if (version === null) {
          isVersionSupported = true;
        } else if (control.isVersionSupported(version)) {
          isVersionSupported = true;
        }
        control = null;
      } catch (e) {
        tryNS = true;
      }
    } else {
      tryNS = true;
    }
    if (tryNS) {
      var plugin = navigator.plugins['Silverlight Plug-In'];
      if (plugin) {
        if (version === null) {
          isVersionSupported = true;
        } else {
          var actualVer = plugin.description;
          if (actualVer === '1.0.30226.2')
            actualVer = '2.0.30226.2';
          var actualVerArray = actualVer.split('.');
          while (actualVerArray.length > 3) {
            actualVerArray.pop();
          }
          while (actualVerArray.length < 4) {
            actualVerArray.push(0);
          }
          var reqVerArray = version.split('.');
          while (reqVerArray.length > 4) {
            reqVerArray.pop();
          }

          var requiredVersionPart;
          var actualVersionPart;
          var index = 0;

          do {
            requiredVersionPart = parseInt(reqVerArray[index], 10);
            actualVersionPart = parseInt(actualVerArray[index], 10);
            index++;
          }
          while (index < reqVerArray.length &&
                 requiredVersionPart === actualVersionPart);

          if (requiredVersionPart <= actualVersionPart &&
              !isNaN(requiredVersionPart)) {
            isVersionSupported = true;
          }
        }
      }
    }
  } catch (e) {
    isVersionSupported = false;
  }

  return isVersionSupported;
};

/**
 * Occasionally checks for Silverlight installation status. If it
 * detects that Silverlight has been installed then it calls
 * Silverlight.onSilverlightInstalled();. This is only supported
 * if Silverlight was not previously installed on this computer.
 */
goog.silverlight.waitForInstallCompletion = function() {
  if (!goog.silverlight.isBrowserRestartRequired &&
      goog.silverlight.onSilverlightInstalled) {
    try {
      navigator.plugins.refresh();
    } catch (e) {
    }
    if (goog.silverlight.isInstalled(null) &&
        !goog.silverlight.__onSilverlightInstalledCalled) {
      goog.silverlight.onSilverlightInstalled();
      goog.silverlight.__onSilverlightInstalledCalled = true;
    } else {
      setTimeout(goog.silverlight.waitForInstallCompletion, 3000);
    }
  }
};

/**
 * Performs startup tasks.
 */
goog.silverlight.startup = function() {
  navigator.plugins.refresh();
  goog.silverlight.isBrowserRestartRequired =
      goog.silverlight.isInstalled(null);
  if (!goog.silverlight.isBrowserRestartRequired) {
    goog.silverlight.waitForInstallCompletion();
    if (!goog.silverlight.__installationEventFired) {
      goog.silverlight.onInstallRequired();
      goog.silverlight.__installationEventFired = true;
    }
  } else if (window.navigator.mimeTypes) {
    var mimeSL2 = navigator.mimeTypes['application/x-silverlight-2'];
    var mimeSL2b2 = navigator.mimeTypes['application/x-silverlight-2-b2'];
    var mimeSL2b1 = navigator.mimeTypes['application/x-silverlight-2-b1'];
    var mimeHighestBeta = mimeSL2b1;
    if (mimeSL2b2)
      mimeHighestBeta = mimeSL2b2;

    if (!mimeSL2 && (mimeSL2b1 || mimeSL2b2)) {
      if (!goog.silverlight.__installationEventFired) {
        goog.silverlight.onUpgradeRequired();
        goog.silverlight.__installationEventFired = true;
      }
    } else if (mimeSL2 && mimeHighestBeta) {
      if (mimeSL2.enabledPlugin &&
          mimeHighestBeta.enabledPlugin) {
        if (mimeSL2.enabledPlugin.description !=
            mimeHighestBeta.enabledPlugin.description) {
          if (!goog.silverlight.__installationEventFired) {
            goog.silverlight.onRestartRequired();
            goog.silverlight.__installationEventFired = true;
          }
        }
      }
    }
  }
};

/**
 * Inserts a Silverlight <object> tag or installation experience into
 * the HTML DOM based on the current installed state of
 * goog.silverlight.
 * @param {string} source The source file.
 * @param {Element} parentElement The place to render the tag.
 * @param {(string|null)=} opt_id A DOM id for the tag.
 * @param {Object=} opt_properties Properties for the tag. One of these should
 *     be version, to get the correct version of silverlight.
 * @param {Array.<Function>=} opt_events An array of functions, keyed by
 *     the name of the event that they should be listening on (e.g.,
 *     "onload"). What a weird API. The keys should be quoted if you're
 *     compiling with property renaming on.
 * @param {string=} opt_initParams The initParams property of SilverlightPlugin.
 * @param {Object=} opt_userContext Context to fire the events in. doesn't
 *     really work correctly. Use goog.bind instead.
 * @return {?string} The html for the object, if no rendering parent
 *     was specified.
 */
goog.silverlight.createObject =
    function(source, parentElement, opt_id, opt_properties,
             opt_events, opt_initParams, opt_userContext) {
  var slPluginHelper = {};
  var slProperties = opt_properties;
  var slEvents = opt_events;

  slPluginHelper.version = slProperties.version;
  slProperties.source = source;
  slPluginHelper.alt = slProperties.alt;

  // Rename properties to their tag property names. For backwards compatibility
  // with goog.silverlight.js version 1.0
  if (opt_initParams)
    slProperties.initParams = opt_initParams;
  if (slProperties.isWindowless && !slProperties.windowless)
    slProperties.windowless = slProperties.isWindowless;
  if (slProperties.framerate && !slProperties.maxFramerate)
    slProperties.maxFramerate = slProperties.framerate;
  if (opt_id && !slProperties.id)
    slProperties.id = opt_id;

  // remove elements which are not to be added to the instantiation tag
  delete slProperties.ignoreBrowserVer;
  delete slProperties.inplaceInstallPrompt;
  delete slProperties.version;
  delete slProperties.isWindowless;
  delete slProperties.framerate;
  delete slProperties.data;
  delete slProperties.src;
  delete slProperties.alt;

  // detect that the correct version of Silverlight is installed, else
  // display install
  var slPluginHtml;
  if (goog.silverlight.isInstalled(slPluginHelper.version)) {
    // move unknown events to the slProperties array
    for (var name in slEvents) {
      if (slEvents[name]) {
        if (name == 'onLoad' && typeof slEvents[name] == 'function' &&
            slEvents[name].length != 1) {
          var onLoadHandler = slEvents[name];
          slEvents[name] = function(sender) {
            return onLoadHandler(
                document.getElementById(/** @type {string} */ (opt_id)),
                opt_userContext,
                sender);
          };
        }
        var handlerName = goog.silverlight.getHandlerName(slEvents[name]);
        if (handlerName != null) {
          slProperties[name] = handlerName;
          slEvents[name] = null;
        } else {
          throw 'typeof events.' + name + " must be 'function' or 'string'";
        }
      }
    }
    slPluginHtml = goog.silverlight.buildHtml(slProperties);
  } else {
    // The control could not be instantiated. Show the installation prompt
    slPluginHtml = goog.silverlight.buildPromptHtml(slPluginHelper);
  }

  // insert or return the HTML
  if (parentElement) {
    parentElement.innerHTML = slPluginHtml;
  } else {
    return slPluginHtml;
  }
  return null;
};

/**
 * Create HTML that instantiates the control
 * @param {Object} slProperties The properties of the object.
 * @return {string} The HTML for the object.
 */
goog.silverlight.buildHtml = function(slProperties) {
  var htmlBuilder = [];

  htmlBuilder.push(
      '<object type=\"application/x-silverlight\" ' +
      'data="data:application/x-silverlight,"');
  if (slProperties.id != null) {
    htmlBuilder.push(
        ' id="' +
        goog.silverlight.htmlAttributeEncode(slProperties.id) + '"');
  }
  if (slProperties.width != null) {
    htmlBuilder.push(' width="' + slProperties.width + '"');
  }
  if (slProperties.height != null) {
    htmlBuilder.push(' height="' + slProperties.height + '"');
  }
  htmlBuilder.push(' >');

  delete slProperties.id;
  delete slProperties.width;
  delete slProperties.height;

  for (var name in slProperties) {
    if (slProperties[name]) {
      htmlBuilder.push(
          '<param name="' + goog.silverlight.htmlAttributeEncode(name) +
          '" value="' +
          goog.silverlight.htmlAttributeEncode(slProperties[name]) +
          '" />');
    }
  }
  htmlBuilder.push('<\/object>');
  return htmlBuilder.join('');
};

/**
 * takes a single parameter of all createObject
 * parameters enclosed in {}
 * @param {{source: string,
 *          parentElement: Element,
 *          id: string,
 *          properties: Object,
 *          events: Array.<Function>,
 *          initParams: string,
 *          context: Object}} params Named parameters of createObject.
 * @return {?string} See #createObject.
 */
goog.silverlight.createObjectEx = function(params) {
  // stupid hack to make compiler stop complaining.
  var unused = {properties: 0, events: 0, context: 0};

  var parameters = params;
  var html = goog.silverlight.createObject(
      parameters.source, parameters.parentElement, parameters.id,
      parameters.properties, parameters.events, parameters.initParams,
      parameters.context);
  if (parameters.parentElement == null) {
    return html;
  }
  return null;
};

/**
 * Builds the HTML to prompt the user to download and install Silverlight
 *
 * @param {{version: string, alt: string}} slPluginHelper Alt is an alternate
 *     link to silverlight. If no alternate is specified, a default will
 *     be used with the given version number.
 * @return {string} The UI.
 */
goog.silverlight.buildPromptHtml = function(slPluginHelper) {
  var slPluginHtml = '';
  var urlRoot = goog.silverlight.fwlinkRoot;
  var version = slPluginHelper.version;
  if (slPluginHelper.alt) {
    slPluginHtml = slPluginHelper.alt;
  } else {
    if (!version) {
      version = '';
    }
    slPluginHtml =
        "";
    slPluginHtml = slPluginHtml.replace('{1}', version);
    slPluginHtml = slPluginHtml.replace('{2}', urlRoot + '108181');
  }

  return slPluginHtml;
};

/**
 * Navigates the browser to the appropriate Silverlight installer
 * @param {string} version The silverlight version.
 */
goog.silverlight.getSilverlight = function(version) {
  if (goog.silverlight.onGetSilverlight) {
    goog.silverlight.onGetSilverlight();
  }

  var shortVer = '';
  var reqVerArray = String(version).split('.');
  if (reqVerArray.length > 1) {
    var majorNum = parseInt(reqVerArray[0], 10);
    if (isNaN(majorNum) || majorNum < 2) {
      shortVer = '1.0';
    } else {
      shortVer = reqVerArray[0] + '.' + reqVerArray[1];
    }
  }

  var verArg = '';

  if (shortVer.match(/^\d+\056\d+$/)) {
    verArg = '&v=' + shortVer;
  }

  goog.silverlight.followFWLink('149156' + verArg);
};

/**
 * Navigates to a url based on fwlinkid
 * @param {string} linkid The link suffix.
 */
goog.silverlight.followFWLink = function(linkid) {
  top.location = goog.silverlight.fwlinkRoot + String(linkid);
};

/**
 * Encodes special characters in input strings as charcodes
 * @param {?string} strInput String to encode, or null. If null
 *     is passed, we give null right back.
 * @return {?string} The encoded string, or null.
 */
goog.silverlight.htmlAttributeEncode = function(strInput) {
  var c;
  var retVal = '';

  if (strInput == null) {
    return null;
  }

  for (var cnt = 0; cnt < strInput.length; cnt++) {
    c = strInput.charCodeAt(cnt);

    if (((c > 96) && (c < 123)) ||
        ((c > 64) && (c < 91)) ||
        ((c > 43) && (c < 58) && (c != 47)) ||
        (c == 95)) {
      retVal = retVal + String.fromCharCode(c);
    } else {
      retVal = retVal + '&#' + c + ';';
    }
  }

  return retVal;
};

/**
 * Default error handling function
 * @param {SilverlightDependencyObject} sender dep object.
 * @param {SilverlightErrorEventArgs} args The event.
 */
goog.silverlight.defaultErrorHandler = function(sender, args) {
  var iErrorCode;
  var errorType = args.errorType;

  iErrorCode = args.errorCode;

  var errMsg = '\nSilverlight error message     \n';

  errMsg += 'ErrorCode: ' + iErrorCode + '\n';

  errMsg += 'ErrorType: ' + errorType + '       \n';
  errMsg += 'Message: ' + args.errorMessage + '     \n';

  if (errorType == 'ParserError') {
    errMsg += 'XamlFile: ' + args.xamlFile + '     \n';
    errMsg += 'Line: ' + args.lineNumber + '     \n';
    errMsg += 'Position: ' + args.charPosition + '     \n';
  } else if (errorType == 'RuntimeError') {
    if (args.lineNumber != 0) {
      errMsg += 'Line: ' + args.lineNumber + '     \n';
      errMsg += 'Position: ' + args.charPosition + '     \n';
    }
    errMsg += 'MethodName: ' + args.methodName + '     \n';
  }
  alert(errMsg);
};

/**
 * Releases event handler resources when the page is unloaded
 */
goog.silverlight.__cleanup = function() {
  for (var i = goog.silverlight._silverlightCount - 1; i >= 0; i--) {
    goog.global['__closure_slEvent' + i] = null;
  }
  goog.silverlight._silverlightCount = 0;
  if (window.removeEventListener) {
    window.removeEventListener('unload', goog.silverlight.__cleanup, false);
  } else {
    window.detachEvent('onunload', goog.silverlight.__cleanup);
  }
};

/**
 * Generates named event handlers for delegates.
 *
 * Attaches them to the global window with the name __closure_slEvent +
 * a unique id.
 *
 * @param {Function|string} handler A function to export.
 * @return {?string} The name of the handler.
 */
goog.silverlight.getHandlerName = function(handler) {
  var handlerName = '';
  if (typeof handler == 'string') {
    handlerName = handler;
  } else if (typeof handler == 'function') {
    if (goog.silverlight._silverlightCount == 0) {
      if (window.addEventListener) {
        window.addEventListener('unload', goog.silverlight.__cleanup, false);
      } else {
        window.attachEvent('onunload', goog.silverlight.__cleanup);
      }
    }
    var count = goog.silverlight._silverlightCount++;
    handlerName = '__closure_slEvent' + count;

    goog.global[handlerName] = handler;
  } else {
    handlerName = null;
  }
  return handlerName;
};

/**
 * Frees a handler created by getHandlerName.
 * @param {string} handlerName A handler name.
 */
goog.silverlight.disposeHandlerName = function(handlerName) {
  delete goog.global[handlerName];
};

/**
 * Called by version  verification control to notify the page that
 * an appropriate build of Silverlight is available. The page
 * should respond by injecting the appropriate Silverlight control
 */
goog.silverlight.onRequiredVersionAvailable = function() {

};

/**
 * Called by version verification control to notify the page that
 * an appropriate build of Silverlight is installed but not loaded.
 * The page should respond by injecting a clear and visible
 * "Thanks for installing. Please restart your browser and return
 * to mysite.com" or equivalent into the browser DOM
 */
goog.silverlight.onRestartRequired = function() {

};

/**
 * Called by version verification control to notify the page that
 * Silverlight must be upgraded. The page should respond by
 * injecting a clear, visible, and actionable upgrade message into
 * the DOM. The message must inform the user that they need to
 * upgrade Silverlight to use the page. They are already somewhat
 * familiar with the Silverlight product when they encounter this.
 * Silverlight should be mentioned so the user expects to see that
 * string in the installer UI. However, the Silverlight-powered
 * application should be the focus of the solicitation. The user
 * wants the app. Silverlight is a means to the app.
 *
 * The upgrade solicitation will have a button that directs
 * the user to the Silverlight installer. Upon click the button
 * should both kick off a download of the installer URL and replace
 * the Upgrade text with "Thanks for downloading. When the upgarde
 * is complete please restart your browser and return to
 * mysite.com" or equivalent.
 *
 * Note: For a more interesting upgrade UX we can use Silverlight
 * 1.0-style XAML for this upgrade experience. Contact PiotrP for
 * details.
 */
goog.silverlight.onUpgradeRequired = function() {

};

/**
 * Called by goog.silverlight.checkInstallStatus to notify the page
 * that Silverlight has not been installed by this user.
 * The page should respond by
 * injecting a clear, visible, and actionable upgrade message into
 * the DOM. The message must inform the user that they need to
 * download and install components needed to use the page.
 * Silverlight should be mentioned so the user expects to see that
 * string in the installer UI. However, the Silverlight-powered
 * application should be the focus of the solicitation. The user
 * wants the app. Silverlight is a means to the app.
 *
 * The installation solicitation will have a button that directs
 * the user to the Silverlight installer. Upon click the button
 * should both kick off a download of the installer URL and replace
 * the Upgrade text with "Thanks for downloading. When installation
 * is complete you may need to refresh the page to view this
 * content" or equivalent.
 */
goog.silverlight.onInstallRequired = function() {

};

/**
 * This function should be called at the beginning of a web page's
 * Silverlight error handler. It will determine if the required
 * version of Silverlight is installed and available in the
 * current process.
 *
 * During its execution the function will trigger one of the
 * Silverlight installation state events, if appropriate.
 *
 * Sender and Args should be passed through from  the calling
 * onError handler's parameters.
 *
 * The associated Sivlerlight <object> tag must have
 * minRuntimeVersion set and should have autoUpgrade set to false.
 *
 * @param {SilverlightDependencyObject} sender The sender.
 * @param {SilverlightErrorEventArgs} args The event arguments.
 * @return {boolean} Is the version available?
 */
goog.silverlight.isVersionAvailableOnError = function(sender, args) {
  var retVal = false;
  try {
    if (args.errorCode == 8001 && !goog.silverlight.__installationEventFired) {
      goog.silverlight.onUpgradeRequired();
      goog.silverlight.__installationEventFired = true;
    } else if (args.errorCode == 8002 &&
               !goog.silverlight.__installationEventFired) {
      goog.silverlight.onRestartRequired();
      goog.silverlight.__installationEventFired = true;
    }
    // this handles upgrades from 1.0. That control did not
    // understand the minRuntimeVerison parameter. It also
    // did not know how to parse XAP files, so would throw
    // Parse Error (5014). A Beta 2 control may throw 2106
    else if (args.errorCode == 5014 || args.errorCode == 2106) {
      if (goog.silverlight.__verifySilverlight2UpgradeSuccess(args.getHost())) {
        retVal = true;
      }
    } else {
      retVal = true;
    }
  } catch (e) {
  }
  return retVal;
};

/**
 * This function should be called at the beginning of a web page's
 * Silverlight onLoad handler. It will determine if the required
 * version of Silverlight is installed and available in the
 * current process.
 *
 * During its execution the function will trigger one of the
 * Silverlight installation state events, if appropriate.
 *
 * Sender should be passed through from the calling
 * onError handler's parameters.
 *
 * The associated Sivlerlight <object> tag must have
 * minRuntimeVersion set and should have autoUpgrade set to false.
 *
 * @param {SilverlightDependencyObject} sender The dep object.
 * @return {boolean} Is the version available?
 */
goog.silverlight.isVersionAvailableOnLoad = function(sender) {
  var retVal = false;
  try {
    if (goog.silverlight.__verifySilverlight2UpgradeSuccess(sender.getHost())) {
      retVal = true;
    }
  } catch (e) {
  }
  return retVal;
};

/**
 * This internal function helps identify installation state by
 * taking advantage of behavioral differences between the
 * 1.0 and 2.0 releases of goog.silverlight.
 * @param {SilverlightPlugin} host The dep object.
 * @return {boolean} If verification succeeded.
 */
goog.silverlight.__verifySilverlight2UpgradeSuccess = function(host) {
  var retVal = false;
  var version = '4.0.50401';
  var installationEvent = null;

  try {
    if (host.isVersionSupported(version + '.99')) {
      installationEvent = goog.silverlight.onRequiredVersionAvailable;
      retVal = true;
    } else if (host.isVersionSupported(version + '.0')) {
      installationEvent = goog.silverlight.onRestartRequired;
    } else {
      installationEvent = goog.silverlight.onUpgradeRequired;
    }

    if (installationEvent && !goog.silverlight.__installationEventFired) {
      installationEvent();
      goog.silverlight.__installationEventFired = true;
    }
  } catch (e) {
  }
  return retVal;
};


text:
var path = require('path'),
	gulp = require('gulp'),
	jshint = require('gulp-jshint'),
	jscs = require('gulp-jscs'),
	jshintReporter = require('jshint-stylish'),
	plugins = require('gulp-load-plugins')({
		config: path.join(__dirname, 'package.json')
	});

var config = {
	src: {
		files: 'src/**/*.js'
	},
	test: {
		files: 'test/**/*.test.js'
	}
};

gulp.task('jshint', function() {
	gulp.src([config.src.files, config.test.files])
	.pipe(jshint('.jshintrc'))
	.pipe(jshint.reporter(jshintReporter));
});

gulp.task('jscs', function() {
	gulp.src([config.src.files, config.test.files])
	.pipe(jscs())
    .pipe(jscs.reporter());
});

gulp.task('jscs-fix', function() {
	gulp.src(config.src.files)
	.pipe(jscs({fix: true}))
    .pipe(gulp.dest('src'));

	gulp.src(config.test.files)
	.pipe(jscs({fix: true}))
    .pipe(gulp.dest('test'));
});

function mochaRunnerFactory(reporter) {
	return plugins.mocha({
		reporter: reporter || config.reporter
	});
}

gulp.task('test-dot', function() {
	gulp.src(config.test.files, {read: false})
	.pipe(mochaRunnerFactory('dot'))
	.on('error', console.warn.bind(console));
});

gulp.task('test-spec', function() {
	gulp.src(config.test.files, {read: false})
	.pipe(mochaRunnerFactory('spec'))
	.on('error', console.warn.bind(console));
});

gulp.task('test', ['jshint', 'jscs', 'test-spec']);

gulp.task('watch', ['jshint', 'jscs', 'test-dot'], function() {
    gulp.watch(config.src.files, ['jshint', 'jscs', 'test-dot']);
});

gulp.task('default', ['watch']);

gulp.task('test-coverage', function(done) {
	gulp.src(config.src.files)
	.pipe(plugins.istanbul())
	.pipe(plugins.istanbul.hookRequire())
	.on('finish', function() {
		gulp.src(config.test.files, {
			cwd: process.env.PWD,
			read: false
		})
		.pipe(mochaRunnerFactory('dot'))
		.pipe(plugins.istanbul.writeReports())
		.on('end', function() {
			if (process.env.TRAVIS) {
				gulp.src('./coverage/**/lcov.info')
				.pipe(plugins.coveralls())
				.on('end', done);
			} else {
				done();
			}
		});
	});
});

gulp.task('pre-commit', ['jshint', 'jscs', 'test-coverage']);

gulp.task('pre-push', ['jshint', 'jscs', 'test-coverage'], function() {
	var coverageEnforcer = require('gulp-istanbul-enforcer');

	var options = {
		thresholds: {
			statements: 95,
			branches: 95,
			lines: 95,
			functions: 95
		},
		coverageDirectory: 'coverage',
		rootDirectory: process.env.PWD
	};

	return gulp.src('.')
		.pipe(coverageEnforcer(options));
});


text:
// Copyright © 2015 - Present RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.package.verifier.infrastructure.app.tasks
{
    using System.Timers;
    using infrastructure.messaging;
    using infrastructure.tasks;
    using messaging;

    public class StartupTask : ITask
    {
        private const double TIMER_INTERVAL = 15000;
        private readonly Timer _timer = new Timer();

        public void initialize()
        {
            _timer.Interval = TIMER_INTERVAL;
            _timer.Elapsed += timer_elapsed;
            _timer.Start();
            this.Log().Info(() => "{0} will send startup message in {1} milliseconds".format_with(GetType().Name, TIMER_INTERVAL));
        }

        public void shutdown()
        {
            if (_timer != null)
            {
                _timer.Stop();
                _timer.Dispose();
            }
        }

        private void timer_elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();

            this.Log().Info(() => "{0} is sending startup message".format_with(GetType().Name));

            EventManager.publish(new StartupMessage());
        }
    }
}


text:
package org.usfirst.frc.team6706.robot.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class MyAutoCommand2 extends CommandGroup {

    public MyAutoCommand2() {
    	addSequential(new GyroDriveCommand(0.5, 0.5), 1);
    	addParallel(new GetInBallCommand(), 2);
        addSequential(new CastOutBallCommand(), 2);
        // Add Commands here:
        // e.g. addSequential(new Command1());
        //      addSequential(new Command2());
        // these will run in order.

        // To run multiple commands at the same time,
        // use addParallel()
        // e.g. addParallel(new Command1());
        //      addSequential(new Command2());
        // Command1 and Command2 will run in parallel.

        // A command group will require all of the subsystems that each member
        // would require.
        // e.g. if Command1 requires chassis, and Command2 requires arm,
        // a CommandGroup containing them would require both the chassis and the
        // arm.
    }
}


text:
<?php

namespace Bschmitt\Amqp;

use Illuminate\Config\Repository;
use Closure;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @author Björn Schmitt <code@bjoern.io>
 */
class Consumer extends Request
{

    /**
     * @var int
     */
    protected $messageCount = 0;

    /**
     * @param string  $queue
     * @param Closure $closure
     * @return bool
     * @throws \Exception
     */
    public function consume(string $queue, Closure $closure) : bool
    {
        try {
            $this->messageCount = $this->getQueueMessageCount();

            if (!$this->getProperty('persistent') && $this->messageCount == 0) {
                throw new Exception\Stop();
            }

            /*
                queue: Queue from where to get the messages
                consumer_tag: Consumer identifier
                no_local: Don't receive messages published by this consumer.
                no_ack: Tells the server if the consumer will acknowledge the messages.
                exclusive: Request exclusive consumer access, meaning only this consumer can access the queue
                nowait:
                qos: The consumer-prefetch make it possible to limit the number of unacknowledged messages on a channel (or connection) when consuming.
                                    Or, in other words, don't dispatch a new message to a worker
                                    until it has processed and acknowledged the previous one
                callback: A PHP Callback
            */

            $object = $this;

            if ($this->getProperty('qos')) {
                $this->getChannel()->basic_qos(
                    $this->getProperty('qos_prefetch_size'),
                    $this->getProperty('qos_prefetch_count'),
                    $this->getProperty('qos_a_global')
                );
            }

            $this->getChannel()->basic_consume(
                $queue,
                $this->getProperty('consumer_tag'),
                $this->getProperty('consumer_no_local'),
                $this->getProperty('consumer_no_ack'),
                $this->getProperty('consumer_exclusive'),
                $this->getProperty('consumer_nowait'),
                function ($message) use ($closure, $object) {
                    $closure($message, $object);
                },
                null,
                $this->getProperty('consumer_properties')
            );

            // consume
            while (count($this->getChannel()->callbacks)) {
                $this->getChannel()->wait(null, false,
                    $this->getProperty('timeout') ? $this->getProperty('timeout') : 0
                );
            }
        } catch (\Exception $e) {
            if ($e instanceof Exception\Stop) {
                return true;
            }

            if ($e instanceof AMQPTimeoutException) {
                return true;
            }

            throw $e;
        }

        return true;
    }

    /**
     * Acknowledges a message
     *
     * @param AMQPMessage $message
     */
    public function acknowledge(AMQPMessage $message)
    {
        $message->getChannel()->basic_ack($message->getDeliveryTag());

        if ($message->body === 'quit') {
            $message->getChannel()->basic_cancel($message->getConsumerTag());
        }
    }

    /**
     * Rejects a message and requeues it if wanted (default: false)
     *
     * @param AMQPMessage $message
     * @param bool    $requeue
     */
    public function reject(AMQPMessage $message, bool $requeue = false)
    {
        $message->getChannel()->basic_reject($message->getDeliveryTag(), $requeue);
    }

    /**
     * Stops consumer when no message is left
     *
     * @throws Exception\Stop
     */
    public function stopWhenProcessed()
    {
        if (--$this->messageCount <= 0) {
            throw new Exception\Stop();
        }
    }
}


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const CollectionsBookmarkFontIcon = forwardRef<
  HTMLElement,
  FontIconProps
>(function CollectionsBookmarkFontIcon(props, ref) {
  return (
    <FontIcon {...props} ref={ref}>
      collections_bookmark
    </FontIcon>
  );
});


text:
package smp.components.staff.sequences;

import java.io.Serializable;
import java.util.ArrayList;

import smp.components.Values;

/**
 * A line of notes on the staff. This can include
 * notes, bookmarks, etc.
 * @author RehdBlob
 * @since 2012.09.19
 */
public class StaffNoteLine implements Serializable {

    /**
     * Generated serial ID
     */
    private static final long serialVersionUID = 3876410979457142750L;

    /**
     * This is the list of note volumes (we will use this later as an extension
     * to the usual volume-bar-sets-the-volume-of-the-whole-line thing.
     */
    private ArrayList<Integer> volumes;

    /** This is the volume of the entire StaffNoteLine */
    private int volume;

    /** This ArrayList holds staff notes inside it. */
    private ArrayList<StaffNote> notes;

    /** This ArrayList holds staff events in it. */
    private ArrayList<StaffEvent> marks;

    /**
     * Creates a new staff note line with the specified
     * line number.
     */
    public StaffNoteLine() {
        notes = new ArrayList<StaffNote>();
        marks = new ArrayList<StaffEvent>();
    }

    /**
     * Adds a note to the staff note line.
     * @param n The note to add to this StaffNoteLine.
     */
    public void add(StaffNote n) {
        notes.add(n);
    }

    /**
     * Adds an event to this staff note line.
     * @param e The event that we are trying to add.
     */
    public void addEvent(StaffEvent e) {
        marks.add(e);
    }

    /**
     * Deletes a note from the staff.
     * @param n The note to delete.
     * @return True if we successfully removed the note.
     */
    public boolean remove(StaffNote n) {
        return notes.remove(n);
    }

    /**
     * Deletes a note from the staff.
     * @param index The index which we are deleting from.
     * @return The deleted element.
     */
    public StaffNote remove(int index) {
        return notes.remove(index);
    }

    /**
     * Deletes an event from this staff note line.
     * @param e The event that we are trying to remove.
     * @return True if we successfully removed the event.
     */
    public boolean removeEvent(StaffEvent e) {
        return marks.remove(e);
    }

    /** @return Whether this StaffNoteLine contains the staff note already. */
    public boolean contains(StaffNote theNote) {
        return notes.contains(theNote);
    }

    /** @return The number of notes that are in this StaffNoteLine. */
    public int size() {
        return notes.size();
    }

    /** @return Whether the StaffNoteLine has any notes or not. */
    public boolean isEmpty() {
        return notes.isEmpty();
    }

    /**
     * @return The list of notes that this StaffNoteLine contains.
     */
    public ArrayList<StaffNote> getNotes() {
        return notes;
    }

    /** @return The list of volumes of the different notes. */
    public ArrayList<Integer> getVolumes() {
        return volumes;
    }

    /** @return The volume of this StaffNoteLine. */
    public int getVolume() {
        return volume;
    }

    /**
     * @param y The volume that we want to set this note line to.
     */
    public void setVolume(double y) {
        if (volume >= Values.MIN_VELOCITY &&
                volume <= Values.MAX_VELOCITY)
            volume = (int) y;
    }

    /**
     * @param vol A percentage (between 0 and 1) that we want
     * to scale this volume by.
     */
    public void setVolumePercent(double vol) {
        if (vol >= 0 && vol <= 1)
            volume = (int) (vol * Values.MAX_VELOCITY);
    }

    /**
     * @return The percent volume of this StaffNoteLine.
     */
    public double getVolumePercent() {
        return ((double) volume) / Values.MAX_VELOCITY;
    }

    @Override
    public String toString() {
        return notes.toString();
    }

}


text:
using UnityEngine;
using System.Collections;
using UniRx;
using UnityEngine.UI;

namespace UniRxWorkBook.Operators
{
    public class Answer_Lesson_7_Zip : MonoBehaviour
    {

        [SerializeField] private Text resultLabel;
        [SerializeField] private Button buttonLeft;
        [SerializeField] private Button buttonRight;

        private void Start()
        {
            var rightStream = buttonRight.OnClickAsObservable();
            var leftStream = buttonLeft.OnClickAsObservable();

            // Zipは複数のオペレータの値を1つずつまとめて流すオペレータである
            // 今回は2本のストリームを指定しているので、2本のストリームの両方のメッセージが1つずつ揃った時にメッセージを放流する
            // その際、第二引数に与えるデリゲートで値の加工が可能である(今回は値を使わないのでUnitを流している)
            //
            // また、Zipは内部にBufferいる点も重要である
            // 例えば以下のFirstを削除した状態で実行し、Leftを連続で3回押した後に、Rightを連続で3回押してみよう
            // (実行された回数がわかりやすいようにTextの更新を追記する形にしておく)
            leftStream
                .Zip(rightStream, (l, r) => Unit.Default)
                .First()
                .SubscribeToText(resultLabel, _ => resultLabel.text += "OK\n");
        }

    }
}


text:
@interface BJLSpringFlowLayout ()

@property (strong, nonatomic) UIDynamicAnimator *dynamicAnimator;
@property (nonatomic) UIDeviceOrientation currentOrientation;
@property (nonatomic) NSUInteger itemCount;

@end

@implementation BJLSpringFlowLayout

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        _currentOrientation = [[UIDevice currentDevice] orientation];
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    UIDeviceOrientation newOrientation = [[UIDevice currentDevice] orientation];

    if (!_dynamicAnimator) {
        _dynamicAnimator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self];
    }

    CGSize contentSize = [self collectionViewContentSize];
    NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];

    if ([items count] != _itemCount || _currentOrientation != newOrientation) {
        _itemCount = [items count];
        _currentOrientation = newOrientation;

        [_dynamicAnimator removeAllBehaviors];

        for (UICollectionViewLayoutAttributes *item in items) {
            UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:[item center]];
            spring.length = 0;
            spring.damping = 0.5;
            spring.frequency = 0.8;

            [_dynamicAnimator addBehavior:spring];
        }
    }
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    UIScrollView *scrollView = self.collectionView;
    CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;
    CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];

    for (UIAttachmentBehavior *spring in _dynamicAnimator.behaviors) {
        CGPoint anchorPoint = spring.anchorPoint;
        CGFloat distanceFromTouch = fabs(touchLocation.y - anchorPoint.y);
        CGFloat scrollResistance = distanceFromTouch / 500;

        UICollectionViewLayoutAttributes *item = [spring.items firstObject];
        CGPoint center = item.center;
        center.y += scrollDelta * scrollResistance; //MIN(scrollDelta, scrollDelta * scrollResistance);
        item.center = center;

        [_dynamicAnimator updateItemUsingCurrentState:item];
    }

    return NO;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return [_dynamicAnimator itemsInRect:rect];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [_dynamicAnimator layoutAttributesForCellAtIndexPath:indexPath];
}

@end


text:
package com.alamkanak.weekview;

import java.util.Calendar;
import java.util.List;

public interface WeekViewLoader {
    /**
     * Convert a date into a double that will be used to reference when you're loading data.
     *
     * All periods that have the same integer part, define one period. Dates that are later in time
     * should have a greater return value.
     *
     * @param instance the date
     * @return The period index in which the date falls (floating point number).
     */
    double toWeekViewPeriodIndex(Calendar instance);

    /**
     * Load the events within the period
     * @param periodIndex the period to load
     * @return A list with the events of this period
     */
    List<WeekViewEvent> onLoad(int periodIndex);
}


text:
require 'discordrb/api'
require 'discordrb/api/server'
require 'discordrb/api/invite'
require 'discordrb/api/user'
require 'discordrb/data'

module Discordrb
  # This mixin module does caching stuff for the library. It conveniently separates the logic behind
  # the caching (like, storing the user hashes or making API calls to retrieve things) from the Bot that
  # actually uses it.
  module Cache
    # Initializes this cache
    def init_cache
      @users = {}

      @servers = {}

      @channels = {}
      @pm_channels = {}

      @restricted_channels = []
    end

    # Gets a channel given its ID. This queries the internal channel cache, and if the channel doesn't
    # exist in there, it will get the data from Discord.
    # @param id [Integer] The channel ID for which to search for.
    # @param server [Server] The server for which to search the channel for. If this isn't specified, it will be
    #   inferred using the API
    # @return [Channel] The channel identified by the ID.
    def channel(id, server = nil)
      id = id.resolve_id

      raise Discordrb::Errors::NoPermission if @restricted_channels.include? id

      debug("Obtaining data for channel with id #{id}")
      return @channels[id] if @channels[id]

      begin
        begin
          response = API::Channel.resolve(token, id)
        rescue RestClient::ResourceNotFound
          return nil
        end
        channel = Channel.new(JSON.parse(response), self, server)
        @channels[id] = channel
      rescue Discordrb::Errors::NoPermission
        debug "Tried to get access to restricted channel #{id}, blacklisting it"
        @restricted_channels << id
        raise
      end
    end

    alias_method :group_channel, :channel

    # Gets a user by its ID.
    # @note This can only resolve users known by the bot (i.e. that share a server with the bot).
    # @param id [Integer] The user ID that should be resolved.
    # @return [User, nil] The user identified by the ID, or `nil` if it couldn't be found.
    def user(id)
      id = id.resolve_id
      return @users[id] if @users[id]

      LOGGER.out("Resolving user #{id}")
      begin
        response = API::User.resolve(token, id)
      rescue RestClient::ResourceNotFound
        return nil
      end
      user = User.new(JSON.parse(response), self)
      @users[id] = user
    end

    # Gets a server by its ID.
    # @note This can only resolve servers the bot is currently in.
    # @param id [Integer] The server ID that should be resolved.
    # @return [Server, nil] The server identified by the ID, or `nil` if it couldn't be found.
    def server(id)
      id = id.resolve_id
      return @servers[id] if @servers[id]

      LOGGER.out("Resolving server #{id}")
      begin
        response = API::Server.resolve(token, id)
      rescue RestClient::ResourceNotFound
        return nil
      end
      server = Server.new(JSON.parse(response), self)
      @servers[id] = server
    end

    # Gets a member by both IDs, or `Server` and user ID.
    # @param server_or_id [Server, Integer] The `Server` or server ID for which a member should be resolved
    # @param user_id [Integer] The ID of the user that should be resolved
    # @return [Member, nil] The member identified by the IDs, or `nil` if none could be found
    def member(server_or_id, user_id)
      server_id = server_or_id.resolve_id
      user_id = user_id.resolve_id

      server = server_or_id.is_a?(Server) ? server_or_id : self.server(server_id)

      return server.member(user_id) if server.member_cached?(user_id)

      LOGGER.out("Resolving member #{server_id} on server #{user_id}")
      begin
        response = API::Server.resolve_member(token, server_id, user_id)
      rescue RestClient::ResourceNotFound
        return nil
      end
      member = Member.new(JSON.parse(response), server, self)
      server.cache_member(member)
    end

    # Creates a PM channel for the given user ID, or if one exists already, returns that one.
    # It is recommended that you use {User#pm} instead, as this is mainly for internal use. However,
    # usage of this method may be unavoidable if only the user ID is known.
    # @param id [Integer] The user ID to generate a private channel for.
    # @return [Channel] A private channel for that user.
    def pm_channel(id)
      id = id.resolve_id
      return @pm_channels[id] if @pm_channels[id]
      debug("Creating pm channel with user id #{id}")
      response = API::User.create_pm(token, id)
      channel = Channel.new(JSON.parse(response), self)
      @pm_channels[id] = channel
    end

    alias_method :private_channel, :pm_channel

    # Ensures a given user object is cached and if not, cache it from the given data hash.
    # @param data [Hash] A data hash representing a user.
    # @return [User] the user represented by the data hash.
    def ensure_user(data)
      if @users.include?(data['id'].to_i)
        @users[data['id'].to_i]
      else
        @users[data['id'].to_i] = User.new(data, self)
      end
    end

    # Ensures a given server object is cached and if not, cache it from the given data hash.
    # @param data [Hash] A data hash representing a server.
    # @return [Server] the server represented by the data hash.
    def ensure_server(data)
      if @servers.include?(data['id'].to_i)
        @servers[data['id'].to_i]
      else
        @servers[data['id'].to_i] = Server.new(data, self)
      end
    end

    # Ensures a given channel object is cached and if not, cache it from the given data hash.
    # @param data [Hash] A data hash representing a channel.
    # @param server [Server, nil] The server the channel is on, if known.
    # @return [Channel] the channel represented by the data hash.
    def ensure_channel(data, server = nil)
      if @channels.include?(data['id'].to_i)
        @channels[data['id'].to_i]
      else
        @channels[data['id'].to_i] = Channel.new(data, self, server)
      end
    end

    # Requests member chunks for a given server ID.
    # @param id [Integer] The server ID to request chunks for.
    def request_chunks(id)
      @gateway.send_request_members(id, '', 0)
    end

    # Gets the code for an invite.
    # @param invite [String, Invite] The invite to get the code for. Possible formats are:
    #
    #    * An {Invite} object
    #    * The code for an invite
    #    * A fully qualified invite URL (e. g. `https://discordapp.com/invite/0A37aN7fasF7n83q`)
    #    * A short invite URL with protocol (e. g. `https://discord.gg/0A37aN7fasF7n83q`)
    #    * A short invite URL without protocol (e. g. `discord.gg/0A37aN7fasF7n83q`)
    # @return [String] Only the code for the invite.
    def resolve_invite_code(invite)
      invite = invite.code if invite.is_a? Discordrb::Invite
      invite = invite[invite.rindex('/') + 1..-1] if invite.start_with?('http', 'discord.gg')
      invite
    end

    # Gets information about an invite.
    # @param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
    # @return [Invite] The invite with information about the given invite URL.
    def invite(invite)
      code = resolve_invite_code(invite)
      Invite.new(JSON.parse(API::Invite.resolve(token, code)), self)
    end

    # Finds a channel given its name and optionally the name of the server it is in.
    # @param channel_name [String] The channel to search for.
    # @param server_name [String] The server to search for, or `nil` if only the channel should be searched for.
    # @param type [Integer, nil] The type of channel to search for (0: text, 1: private, 2: voice, 3: group), or `nil` if any type of
    #   channel should be searched for
    # @return [Array<Channel>] The array of channels that were found. May be empty if none were found.
    def find_channel(channel_name, server_name = nil, type: nil)
      results = []

      if /<#(?<id>\d+)>?/ =~ channel_name
        # Check for channel mentions separately
        return [channel(id)]
      end

      @servers.values.each do |server|
        server.channels.each do |channel|
          results << channel if channel.name == channel_name && (server_name || server.name) == server.name && (!type || (channel.type == type))
        end
      end

      results
    end

    # Finds a user given its username.
    # @param username [String] The username to look for.
    # @return [Array<User>] The array of users that were found. May be empty if none were found.
    def find_user(username)
      @users.values.find_all { |e| e.username == username }
    end
  end
end


text:
(function () {
'use strict';

  angular
    .module('app.controllers')
    .controller('UpdateRestController', UpdateRestController);

  function UpdateRestController(restData,
                                $state,
                                RestaurantService,
                                toastr,
                                $scope) {
    var vmRest = this;
    vmRest.rest = restData;
    vmRest.submitForm = submitForm;

    init();

    function init() {
      //update header controller values
      $scope.vmHeader.showNewRest = false;
      $scope.vmHeader.showNewMenu = false;
      $scope.vmHeader.onlyRests = false;
      $scope.vmHeader.searchForm = false;
    }

    function submitForm() {
      RestaurantService.updateRestaurant(vmRest.rest).then(function(resp){
        if (resp.errors) {
          angular.forEach(resp.errors, function(value, key) {
            toastr.error(value[0]);
          });
        }else{
          $state.go('home');
        }
      });
    }

  }

})();


text:
/**
 * This class provides access to the device contacts.
 * @constructor
 */

function Contact(jsonObject) {
	this.firstName = "";
	this.lastName = "";
    this.name = "";
    this.phones = {};
    this.emails = {};
	this.address = "";
}

Contact.prototype.displayName = function()
{
    // TODO: can be tuned according to prefs
	return this.name;
}

function ContactManager() {
	// Dummy object to hold array of contacts
	this.contacts = [];
	this.timestamp = new Date().getTime();
}

ContactManager.prototype.getAllContacts = function(successCallback, errorCallback, options) {
	PhoneGap.exec("Contacts.allContacts", GetFunctionName(successCallback), options);
}

// THE FUNCTIONS BELOW ARE iPHONE ONLY FOR NOW

ContactManager.prototype.newContact = function(contact, successCallback, options) {
    if (!options) options = {};
    options.successCallback = GetFunctionName(successCallback);

    PhoneGap.exec("Contacts.newContact", contact.firstName, contact.lastName, contact.phoneNumber,
        options);
}

ContactManager.prototype.chooseContact = function(successCallback, options) {
    PhoneGap.exec("Contacts.chooseContact", GetFunctionName(successCallback), options);
}

ContactManager.prototype.displayContact = function(contactID, errorCallback, options) {
    PhoneGap.exec("Contacts.displayContact", contactID, GetFunctionName(errorCallback), options);
}

ContactManager.prototype.removeContact = function(contactID, successCallback, options) {
    PhoneGap.exec("Contacts.removeContact", contactID, GetFunctionName(successCallback), options);
}

ContactManager.prototype.contactsCount = function(successCallback, errorCallback) {
	PhoneGap.exec("Contacts.contactsCount", GetFunctionName(successCallback));
}

PhoneGap.addConstructor(function() {
    if (typeof navigator.contacts == "undefined") navigator.contacts = new ContactManager();
});


text:
package net.oscartech.tesseract.common.bytes;

/**
 * Created by tylaar on 15/5/31.
 */
public interface Register<T> {
    T read();

    void write(T v);
}


text:
package org.apache.hadoop.hbase.regionserver;

import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.TreeMap;
import java.util.TreeSet;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValue.KVComparator;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * State and utility processing {@link HRegion#getClosestRowBefore(byte[], byte[])}.
 * Like {@link ScanDeleteTracker} and {@link ScanDeleteTracker} but does not
 * implement the {@link DeleteTracker} interface since state spans rows (There
 * is no update nor reset method).
 */
@InterfaceAudience.Private
class GetClosestRowBeforeTracker {
  private final KeyValue targetkey;
  // Any cell w/ a ts older than this is expired.
  private final long oldestts;
  private KeyValue candidate = null;
  private final KVComparator kvcomparator;
  // Flag for whether we're doing getclosest on a metaregion.
  private final boolean metaregion;
  // Offset and length into targetkey demarking table name (if in a metaregion).
  private final int rowoffset;
  private final int tablenamePlusDelimiterLength;

  // Deletes keyed by row.  Comparator compares on row portion of KeyValue only.
  private final NavigableMap<KeyValue, NavigableSet<KeyValue>> deletes;

  /**
   * @param c
   * @param kv Presume first on row: i.e. empty column, maximum timestamp and
   * a type of Type.Maximum
   * @param ttl Time to live in ms for this Store
   * @param metaregion True if this is hbase:meta or -ROOT- region.
   */
  GetClosestRowBeforeTracker(final KVComparator c, final KeyValue kv,
      final long ttl, final boolean metaregion) {
    super();
    this.metaregion = metaregion;
    this.targetkey = kv;
    // If we are in a metaregion, then our table name is the prefix on the
    // targetkey.
    this.rowoffset = kv.getRowOffset();
    int l = -1;
    if (metaregion) {
      l = KeyValue.getDelimiter(kv.getBuffer(), rowoffset, kv.getRowLength(),
        HConstants.DELIMITER) - this.rowoffset;
    }
    this.tablenamePlusDelimiterLength = metaregion? l + 1: -1;
    this.oldestts = System.currentTimeMillis() - ttl;
    this.kvcomparator = c;
    KeyValue.RowOnlyComparator rc = new KeyValue.RowOnlyComparator(this.kvcomparator);
    this.deletes = new TreeMap<KeyValue, NavigableSet<KeyValue>>(rc);
  }

  /**
   * @param kv
   * @return True if this kv is expired.
   */
  boolean isExpired(final KeyValue kv) {
    return HStore.isExpired(kv, this.oldestts);
  }

  /*
   * Add the specified KeyValue to the list of deletes.
   * @param kv
   */
  private void addDelete(final KeyValue kv) {
    NavigableSet<KeyValue> rowdeletes = this.deletes.get(kv);
    if (rowdeletes == null) {
      rowdeletes = new TreeSet<KeyValue>(this.kvcomparator);
      this.deletes.put(kv, rowdeletes);
    }
    rowdeletes.add(kv);
  }

  /*
   * @param kv Adds candidate if nearer the target than previous candidate.
   * @return True if updated candidate.
   */
  private boolean addCandidate(final KeyValue kv) {
    if (!isDeleted(kv) && isBetterCandidate(kv)) {
      this.candidate = kv;
      return true;
    }
    return false;
  }

  boolean isBetterCandidate(final KeyValue contender) {
    return this.candidate == null ||
      (this.kvcomparator.compareRows(this.candidate, contender) < 0 &&
        this.kvcomparator.compareRows(contender, this.targetkey) <= 0);
  }

  /*
   * Check if specified KeyValue buffer has been deleted by a previously
   * seen delete.
   * @param kv
   * @return true is the specified KeyValue is deleted, false if not
   */
  private boolean isDeleted(final KeyValue kv) {
    if (this.deletes.isEmpty()) return false;
    NavigableSet<KeyValue> rowdeletes = this.deletes.get(kv);
    if (rowdeletes == null || rowdeletes.isEmpty()) return false;
    return isDeleted(kv, rowdeletes);
  }

  /**
   * Check if the specified KeyValue buffer has been deleted by a previously
   * seen delete.
   * @param kv
   * @param ds
   * @return True is the specified KeyValue is deleted, false if not
   */
  public boolean isDeleted(final KeyValue kv, final NavigableSet<KeyValue> ds) {
    if (deletes == null || deletes.isEmpty()) return false;
    for (KeyValue d: ds) {
      long kvts = kv.getTimestamp();
      long dts = d.getTimestamp();
      if (d.isDeleteFamily()) {
        if (kvts <= dts) return true;
        continue;
      }
      // Check column
      int ret = Bytes.compareTo(kv.getBuffer(), kv.getQualifierOffset(),
          kv.getQualifierLength(),
        d.getBuffer(), d.getQualifierOffset(), d.getQualifierLength());
      if (ret <= -1) {
        // This delete is for an earlier column.
        continue;
      } else if (ret >= 1) {
        // Beyond this kv.
        break;
      }
      // Check Timestamp
      if (kvts > dts) return false;

      // Check Type
      switch (KeyValue.Type.codeToType(d.getType())) {
        case Delete: return kvts == dts;
        case DeleteColumn: return true;
        default: continue;
      }
    }
    return false;
  }

  /*
   * Handle keys whose values hold deletes.
   * Add to the set of deletes and then if the candidate keys contain any that
   * might match, then check for a match and remove it.  Implies candidates
   * is made with a Comparator that ignores key type.
   * @param kv
   * @return True if we removed k from candidates.
   */
  boolean handleDeletes(final KeyValue kv) {
    addDelete(kv);
    boolean deleted = false;
    if (!hasCandidate()) return deleted;
    if (isDeleted(this.candidate)) {
      this.candidate = null;
      deleted = true;
    }
    return deleted;
  }

  /**
   * Do right thing with passed key, add to deletes or add to candidates.
   * @param kv
   * @return True if we added a candidate
   */
  boolean handle(final KeyValue kv) {
    if (kv.isDelete()) {
      handleDeletes(kv);
      return false;
    }
    return addCandidate(kv);
  }

  /**
   * @return True if has candidate
   */
  public boolean hasCandidate() {
    return this.candidate != null;
  }

  /**
   * @return Best candidate or null.
   */
  public KeyValue getCandidate() {
    return this.candidate;
  }

  public KeyValue getTargetKey() {
    return this.targetkey;
  }

  /**
   * @param kv Current kv
   * @param firstOnRow on row kv.
   * @return True if we went too far, past the target key.
   */
  boolean isTooFar(final KeyValue kv, final KeyValue firstOnRow) {
    return this.kvcomparator.compareRows(kv, firstOnRow) > 0;
  }

  boolean isTargetTable(final KeyValue kv) {
    if (!metaregion) return true;
    // Compare start of keys row.  Compare including delimiter.  Saves having
    // to calculate where tablename ends in the candidate kv.
    return Bytes.compareTo(this.targetkey.getBuffer(), this.rowoffset,
        this.tablenamePlusDelimiterLength,
      kv.getBuffer(), kv.getRowOffset(), this.tablenamePlusDelimiterLength) == 0;
  }
}


text:
<?php

    $file = $_GET['filename'];

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$file."");
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: binary/octet-stream");
    readfile("assets/file/".$file);

?>


text:
package com.swfarm.biz.cs.web;

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

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

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.cs.bo.SearchEbayCsMessageSchedulesCriteria;

public class SearchEbayCsMessageSchedulesController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
	    SearchEbayCsMessageSchedulesCriteria criteria = new SearchEbayCsMessageSchedulesCriteria();
		String name = req.getParameter("name");
		if (StringUtils.isNotEmpty(name)) {
			criteria.setName(name);
		}
		Map<String,Object> dataMap = new HashMap<String,Object>();
		if (!(criteria.getName() == null)) {
			dataMap.put("criteria", criteria);
		}
		return new ModelAndView("forward:/cs/ebaycsmessageschedules.shtml",
				dataMap);
	}
}