text:
#ifndef __ARCH_ARM_KVM_ARMV8_CPU_HH__
#define __ARCH_ARM_KVM_ARMV8_CPU_HH__

#include <vector>

#include "arch/arm/intregs.hh"
#include "arch/arm/kvm/base_cpu.hh"
#include "arch/arm/miscregs.hh"

struct ArmV8KvmCPUParams;

/**
 * This is an implementation of a KVM-based ARMv8-compatible CPU.
 *
 * Known limitations:
 *

 *
 *
The system-register-based generic timer can only be simulated
 *       by the host kernel. Workaround: Use a memory mapped timer
 *       instead to simulate the timer in gem5.
 *
 *
Simulating devices (e.g., the generic timer) in the host
 *       kernel requires that the host kernel also simulates the
 *       GIC.
 *
 *
ID registers in the host and in gem5 must match for switching
 *       between simulated CPUs and KVM. This is particularly
 *       important for ID registers describing memory system
 *       capabilities (e.g., ASID size, physical address size).
 *
 *
Switching between a virtualized CPU and a simulated CPU is
 *       currently not supported if in-kernel device emulation is
 *       used. This could be worked around by adding support for
 *       switching to the gem5 (e.g., the KvmGic) side of the device
 *       models. A simpler workaround is to avoid in-kernel device
 *       models altogether.
 *
 *

 *
 */
class ArmV8KvmCPU : public BaseArmKvmCPU
{
  public:
    ArmV8KvmCPU(ArmV8KvmCPUParams *params);
    virtual ~ArmV8KvmCPU();

    void startup() override;

    void dump() const override;

  protected:
    void updateKvmState() override;
    void updateThreadContext() override;

  protected:
    /** Mapping between integer registers in gem5 and KVM */
    struct IntRegInfo {
        IntRegInfo(uint64_t _kvm, IntRegIndex _idx, const char *_name)
            : kvm(_kvm), idx(_idx), name(_name) {}

        /** Register index in KVM */
        uint64_t kvm;
        /** Register index in gem5 */
        IntRegIndex idx;
        /** Name to use in debug dumps */
        const char *name;
    };

    /** Mapping between misc registers in gem5 and registers in KVM */
    struct MiscRegInfo {
        MiscRegInfo(uint64_t _kvm, MiscRegIndex _idx, const char *_name)
            : kvm(_kvm), idx(_idx), name(_name) {}

        /** Register index in KVM */
        uint64_t kvm;
        /** Register index in gem5 */
        MiscRegIndex idx;
        /** Name to use in debug dumps */
        const char *name;
    };

    /**
     * Get a map between system registers in kvm and gem5 registers
     *
     * This method returns a mapping between system registers in kvm
     * and misc regs in gem5. The actual mapping is only created the
     * first time the method is called and stored in a cache
     * (ArmV8KvmCPU::sysRegMap).
     *
     * @return Vector of kvm<->misc reg mappings.
     */
    const std::vector<ArmV8KvmCPU::MiscRegInfo> &getSysRegMap() const;

    /** Mapping between gem5 integer registers and integer registers in kvm */
    static const std::vector<ArmV8KvmCPU::IntRegInfo> intRegMap;
    /** Mapping between gem5 misc registers registers and registers in kvm */
    static const std::vector<ArmV8KvmCPU::MiscRegInfo> miscRegMap;
    /** Mapping between gem5 ID misc registers registers and registers in kvm */
    static const std::vector<ArmV8KvmCPU::MiscRegInfo> miscRegIdMap;

    /** Cached mapping between system registers in kvm and misc regs in gem5 */
    mutable std::vector<ArmV8KvmCPU::MiscRegInfo> sysRegMap;
};

#endif // __ARCH_ARM_KVM_ARMV8_CPU_HH__


text:
<?php

namespace Breeze\View\Driver\Tests;

/**
 * @see Breeze\Application
 */
use Breeze\Application;

/**
 * @see Breeze\View\Driver\Dwoo
 */
use Breeze\View\Driver\Dwoo;

/**
 * @see Breeze\Plugins\Tests\PluginTestCase
 */
use Breeze\Plugins\Tests\PluginTestCase;

/**
 * The test case for the {@link Breeze\View\Driver\Dwoo} class.
 *
 * @package    Breeze
 * @subpackage Tests
 * @author     Jeff Welch <whatthejeff@gmail.com>
 * @copyright  2010-2011 Jeff Welch <whatthejeff@gmail.com>
 * @license    https://github.com/whatthejeff/breeze/blob/master/LICENSE New BSD License
 * @link       http://breezephp.com/
 */
class DwooTest extends PluginTestCase
{
    /**
     * The path to the plugin file.
     *
     * @param string
     */
    static protected $_pluginPath = 'Breeze/plugins/Dwoo.php';
    /**
     * The name of the plugin
     *
     * @param string
     */
    static protected $_pluginName = 'Dwoo';

    /**
     * The driver object for testing.
     *
     * @param Breeze\View\Driver\Dwoo
     */
    protected $_driver;

    /**
     * Sets up the test case for {@link Breeze\View\Driver\Dwoo}.
     *
     * @return void
     */
    public function setUp()
    {
        if (!\Breeze\Tests\TEST_DWOO) {
            $this->markTestSkipped('Dwoo is not available for testing');
        }

        $this->_application = $this->getMock(
            'Breeze\\Application', array(), array(), '', FALSE
        );
        $this->_driver = new Dwoo(
            $this->_application, \Breeze\Tests\FIXTURES_PATH . '/Dwoo'
        );
    }

    /**
     * Tests {@link Breeze\View\Driver\Dwoo::fetch()} with an invalid template.
     */
    public function testFetchWithInvalidTemplate()
    {
        $this->setExpectedException(
            '\\InvalidArgumentException', 'is not a valid template.'
        );
        $this->_driver->fetch('DOES NOT EXIST');
    }

    /**
     * Tests {@link Breeze\View\Driver\Dwoo::fetch()} without variables.
     */
    public function testFetchWithNoVariables()
    {
        $this->assertSame(
            'Hello World', $this->_driver->fetch('template.tpl')
        );
    }

    /**
     * Tests {@link Breeze\View\Driver\Dwoo::fetch()} with variables.
     */
    public function testFetchWithVariables()
    {
        $this->assertSame(
            'Hello Jeff',
            $this->_driver->fetch(
                'template.tpl', array('name'=>'Jeff')
            )
        );
    }

    /**
     * Tests that the plugin was loaded correctly.
     */
    public function testPluginLoaded()
    {
        $config = array(
            'template_engine'    => 'Dwoo',
            'template_extension' => '.tpl',
            'template_options'   => array(
                'compile_dir' => 'compiled',
                'cache_dir'   => 'cache')
        );

        $this->_setupMockedDependencies();
        $this->_configurations->expects($this->once())
                              ->method('set')
                              ->with($this->equalTo($config));
        $this->_mockApplication();
    }
}

redpajama_set_name: RedPajamaGithub


text:
require "opentok/client"
require "opentok/archive"
require "opentok/archive_list"

module OpenTok
  # A class for working with OpenTok 2.0 archives.
  class Archives

    # @private
    def initialize(client)
      @client = client
    end

    # Starts archiving an OpenTok 2.0 session.
    #
    # Clients must be actively connected to the OpenTok session for you to successfully start
    # recording an archive.
    #
    # You can only record one archive at a time for a given session. You can only record archives
    # of sessions that use the OpenTok Media Router (sessions with the media mode set to routed);
    # you cannot archive sessions with the media mode set to relayed.
    #
    # @param [String] session_id The session ID of the OpenTok session to archive.
    # @param [Hash] options  A hash with the key 'name' or :name.
    # @option options [String] :name This is the name of the archive. You can use this name
    #   to identify the archive. It is a property of the Archive object, and it is a property
    #   of archive-related events in the OpenTok.js library.
    #
    # @return [Archive] The Archive object, which includes properties defining the archive,
    #   including the archive ID.
    #
    # @raise [OpenTokArchiveError] The archive could not be started. The request was invalid or
    #   the session has no connected clients.
    # @raise [OpenTokAuthenticationError] Authentication failed while starting an archive.
    #   Invalid API key.
    # @raise [OpenTokArchiveError] The archive could not be started. The session ID does not exist.
    # @raise [OpenTokArchiveError] The archive could not be started. The session could be
    #   peer-to-peer or the session is already being recorded.
    # @raise [OpenTokArchiveError] The archive could not be started.
    def create(session_id, options = {})
      raise ArgumentError, "session_id not provided" if session_id.to_s.empty?
      opts = Hash.new
      opts[:name] = options[:name].to_s || options["name"].to_s
      archive_json = @client.start_archive(session_id, opts)
      Archive.new self, archive_json
    end

    # Gets an Archive object for the given archive ID.
    #
    # @param [String] archive_id The archive ID.
    #
    # @return [Archive] The Archive object.
    # @raise [OpenTokArchiveError] The archive could not be retrieved. The archive ID is invalid.
    # @raise [OpenTokAuthenticationError] Authentication failed while retrieving the archive.
    #   Invalid API key.
    # @raise [OpenTokArchiveError] The archive could not be retrieved.
    def find(archive_id)
      raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
      archive_json = @client.get_archive(archive_id.to_s)
      Archive.new self, archive_json
    end

    # Returns an ArchiveList, which is an array of archives that are completed and in-progress,
    # for your API key.
    #
    # @param [Hash] options  A hash with keys defining which range of archives to retrieve.
    # @option options [integer] :offset Optional. The index offset of the first archive. 0 is offset
    #   of the most recently started archive. 1 is the offset of the archive that started prior to
    #   the most recent archive. If you do not specify an offset, 0 is used.
    # @option options [integer] :count Optional. The number of archives to be returned. The maximum
    #   number of archives returned is 1000.
    #
    # @return [ArchiveList] An ArchiveList object, which is an array of Archive objects.
    def all(options = {})
      raise ArgumentError, "Limit is invalid" unless options[:count].nil? or (0..100).include? options[:count]
      archive_list_json = @client.list_archives(options[:offset], options[:count])
      ArchiveList.new self, archive_list_json
    end

    # Stops an OpenTok archive that is being recorded.
    #
    # Archives automatically stop recording after 90 minutes or when all clients have disconnected
    # from the session being archived.
    #
    # @param [String] archive_id The archive ID of the archive you want to stop recording.
    #
    # @return [Archive] The Archive object corresponding to the archive being stopped.
    #
    # @raise [OpenTokArchiveError] The archive could not be stopped. The request was invalid.
    # @raise [OpenTokAuthenticationError] Authentication failed while stopping an archive.
    # @raise [OpenTokArchiveError] The archive could not be stopped. The archive ID does not exist.
    # @raise [OpenTokArchiveError] The archive could not be stopped. The archive is not currently
    #   recording.
    # @raise [OpenTokArchiveError] The archive could not be started.
    def stop_by_id(archive_id)
      raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
      archive_json = @client.stop_archive(archive_id)
      Archive.new self, archive_json
    end

    # Deletes an OpenTok archive.
    #
    # You can only delete an archive which has a status of "available", "uploaded", or "deleted".
    # Deleting an archive removes its record from the list of archives. For an "available" archive,
    # it also removes the archive file, making it unavailable for download. For a "deleted"
    # archive, the archive remains deleted.
    #
    # @param [String] archive_id The archive ID of the archive you want to delete.
    #
    # @raise [OpenTokAuthenticationError] Authentication failed or an invalid archive ID was given.
    # @raise [OpenTokArchiveError] The archive could not be deleted. The status must be
    #   'available', 'deleted', or 'uploaded'.
    # @raise [OpenTokArchiveError] The archive could not be deleted.
    def delete_by_id(archive_id)
      raise ArgumentError, "archive_id not provided" if archive_id.to_s.empty?
      response = @client.delete_archive(archive_id)
      (200..300).include? response.code
    end

  end
end


text:
import logging
import time

from kinesis_producer import KinesisProducer

logging.basicConfig(level=logging.DEBUG)
logging.getLogger('botocore').setLevel(logging.WARNING)

log = logging.getLogger(__name__)

config = dict(
    aws_region='us-east-1',
    buffer_size_limit=200000,
    buffer_time_limit=0.2,
    kinesis_concurrency=4,
    kinesis_max_retries=10,
    record_delimiter='\n',
    stream_name='jz-python-devlocal',
    )

k = KinesisProducer(config=config)

payload = '{MSG:%%05i %s}' % ('X' * 1000)

try:
    print ' <> MSGS'
    for msg_id in range(50000):
        record = payload % msg_id
        k.send(record)
        # time.sleep(0.2)

    # time.sleep(5)
except KeyboardInterrupt:
    pass
finally:
    print ' <> CLOSE'
    k.close()

    print ' <> JOIN'
    k.join()

    print ' <> QUIT'


text:
WINRT_EXPORT namespace winrt {

namespace impl {

template <typename D>
struct produce<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdRegistrationResult> : produce_base<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdRegistrationResult>
{
    HRESULT __stdcall get_Status(Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationStatus * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Status());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_IPAddress(abi_arg_out<Windows::Networking::IHostName> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().IPAddress());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_HasInstanceNameChanged(bool * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().HasInstanceNameChanged());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceInstance> : produce_base<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceInstance>
{
    HRESULT __stdcall get_DnssdServiceInstanceName(abi_arg_out<hstring> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().DnssdServiceInstanceName());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall put_DnssdServiceInstanceName(abi_arg_in<hstring> value) noexcept override
    {
        try
        {
            this->shim().DnssdServiceInstanceName(*reinterpret_cast<const hstring *>(&value));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_HostName(abi_arg_out<Windows::Networking::IHostName> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().HostName());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall put_HostName(abi_arg_in<Windows::Networking::IHostName> value) noexcept override
    {
        try
        {
            this->shim().HostName(*reinterpret_cast<const Windows::Networking::HostName *>(&value));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Port(uint16_t * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Port());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall put_Port(uint16_t value) noexcept override
    {
        try
        {
            this->shim().Port(value);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Priority(uint16_t * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Priority());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall put_Priority(uint16_t value) noexcept override
    {
        try
        {
            this->shim().Priority(value);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Weight(uint16_t * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Weight());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall put_Weight(uint16_t value) noexcept override
    {
        try
        {
            this->shim().Weight(value);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_TextAttributes(abi_arg_out<Windows::Foundation::Collections::IMap<hstring, hstring>> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().TextAttributes());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_RegisterStreamSocketListenerAsync1(abi_arg_in<Windows::Networking::Sockets::IStreamSocketListener> socket, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult>> result) noexcept override
    {
        try
        {
            *result = detach(this->shim().RegisterStreamSocketListenerAsync(*reinterpret_cast<const Windows::Networking::Sockets::StreamSocketListener *>(&socket)));
            return S_OK;
        }
        catch (...)
        {
            *result = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_RegisterStreamSocketListenerAsync2(abi_arg_in<Windows::Networking::Sockets::IStreamSocketListener> socket, abi_arg_in<Windows::Networking::Connectivity::INetworkAdapter> adapter, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult>> result) noexcept override
    {
        try
        {
            *result = detach(this->shim().RegisterStreamSocketListenerAsync(*reinterpret_cast<const Windows::Networking::Sockets::StreamSocketListener *>(&socket), *reinterpret_cast<const Windows::Networking::Connectivity::NetworkAdapter *>(&adapter)));
            return S_OK;
        }
        catch (...)
        {
            *result = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_RegisterDatagramSocketAsync1(abi_arg_in<Windows::Networking::Sockets::IDatagramSocket> socket, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult>> result) noexcept override
    {
        try
        {
            *result = detach(this->shim().RegisterDatagramSocketAsync(*reinterpret_cast<const Windows::Networking::Sockets::DatagramSocket *>(&socket)));
            return S_OK;
        }
        catch (...)
        {
            *result = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_RegisterDatagramSocketAsync2(abi_arg_in<Windows::Networking::Sockets::IDatagramSocket> socket, abi_arg_in<Windows::Networking::Connectivity::INetworkAdapter> adapter, abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult>> result) noexcept override
    {
        try
        {
            *result = detach(this->shim().RegisterDatagramSocketAsync(*reinterpret_cast<const Windows::Networking::Sockets::DatagramSocket *>(&socket), *reinterpret_cast<const Windows::Networking::Connectivity::NetworkAdapter *>(&adapter)));
            return S_OK;
        }
        catch (...)
        {
            *result = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceInstanceFactory> : produce_base<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceInstanceFactory>
{
    HRESULT __stdcall abi_Create(abi_arg_in<hstring> dnssdServiceInstanceName, abi_arg_in<Windows::Networking::IHostName> hostName, uint16_t port, abi_arg_out<Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceInstance> result) noexcept override
    {
        try
        {
            *result = detach(this->shim().Create(*reinterpret_cast<const hstring *>(&dnssdServiceInstanceName), *reinterpret_cast<const Windows::Networking::HostName *>(&hostName), port));
            return S_OK;
        }
        catch (...)
        {
            *result = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceWatcher> : produce_base<D, Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceWatcher>
{
    HRESULT __stdcall add_Added(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance>> handler, event_token * token) noexcept override
    {
        try
        {
            *token = detach(this->shim().Added(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance> *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_Added(event_token token) noexcept override
    {
        try
        {
            this->shim().Added(token);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall add_EnumerationCompleted(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable>> handler, event_token * token) noexcept override
    {
        try
        {
            *token = detach(this->shim().EnumerationCompleted(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_EnumerationCompleted(event_token token) noexcept override
    {
        try
        {
            this->shim().EnumerationCompleted(token);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall add_Stopped(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable>> handler, event_token * token) noexcept override
    {
        try
        {
            *token = detach(this->shim().Stopped(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_Stopped(event_token token) noexcept override
    {
        try
        {
            this->shim().Stopped(token);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Status(Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcherStatus * status) noexcept override
    {
        try
        {
            *status = detach(this->shim().Status());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_Start() noexcept override
    {
        try
        {
            this->shim().Start();
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_Stop() noexcept override
    {
        try
        {
            this->shim().Stop();
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

}

namespace Windows::Networking::ServiceDiscovery::Dnssd {

template <typename D> event_token impl_IDnssdServiceWatcher<D>::Added(const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance> & handler) const
{
    event_token token {};
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->add_Added(get(handler), &token));
    return token;
}

template <typename D> event_revoker<IDnssdServiceWatcher> impl_IDnssdServiceWatcher<D>::Added(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance> & handler) const
{
    return impl::make_event_revoker<D, IDnssdServiceWatcher>(this, &ABI::Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceWatcher::remove_Added, Added(handler));
}

template <typename D> void impl_IDnssdServiceWatcher<D>::Added(event_token token) const
{
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->remove_Added(token));
}

template <typename D> event_token impl_IDnssdServiceWatcher<D>::EnumerationCompleted(const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> & handler) const
{
    event_token token {};
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->add_EnumerationCompleted(get(handler), &token));
    return token;
}

template <typename D> event_revoker<IDnssdServiceWatcher> impl_IDnssdServiceWatcher<D>::EnumerationCompleted(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> & handler) const
{
    return impl::make_event_revoker<D, IDnssdServiceWatcher>(this, &ABI::Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceWatcher::remove_EnumerationCompleted, EnumerationCompleted(handler));
}

template <typename D> void impl_IDnssdServiceWatcher<D>::EnumerationCompleted(event_token token) const
{
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->remove_EnumerationCompleted(token));
}

template <typename D> event_token impl_IDnssdServiceWatcher<D>::Stopped(const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> & handler) const
{
    event_token token {};
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->add_Stopped(get(handler), &token));
    return token;
}

template <typename D> event_revoker<IDnssdServiceWatcher> impl_IDnssdServiceWatcher<D>::Stopped(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcher, Windows::IInspectable> & handler) const
{
    return impl::make_event_revoker<D, IDnssdServiceWatcher>(this, &ABI::Windows::Networking::ServiceDiscovery::Dnssd::IDnssdServiceWatcher::remove_Stopped, Stopped(handler));
}

template <typename D> void impl_IDnssdServiceWatcher<D>::Stopped(event_token token) const
{
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->remove_Stopped(token));
}

template <typename D> Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcherStatus impl_IDnssdServiceWatcher<D>::Status() const
{
    Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceWatcherStatus status {};
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->get_Status(&status));
    return status;
}

template <typename D> void impl_IDnssdServiceWatcher<D>::Start() const
{
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->abi_Start());
}

template <typename D> void impl_IDnssdServiceWatcher<D>::Stop() const
{
    check_hresult(static_cast<const IDnssdServiceWatcher &>(static_cast<const D &>(*this))->abi_Stop());
}

template <typename D> Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationStatus impl_IDnssdRegistrationResult<D>::Status() const
{
    Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationStatus value {};
    check_hresult(static_cast<const IDnssdRegistrationResult &>(static_cast<const D &>(*this))->get_Status(&value));
    return value;
}

template <typename D> Windows::Networking::HostName impl_IDnssdRegistrationResult<D>::IPAddress() const
{
    Windows::Networking::HostName value { nullptr };
    check_hresult(static_cast<const IDnssdRegistrationResult &>(static_cast<const D &>(*this))->get_IPAddress(put(value)));
    return value;
}

template <typename D> bool impl_IDnssdRegistrationResult<D>::HasInstanceNameChanged() const
{
    bool value {};
    check_hresult(static_cast<const IDnssdRegistrationResult &>(static_cast<const D &>(*this))->get_HasInstanceNameChanged(&value));
    return value;
}

template <typename D> Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance impl_IDnssdServiceInstanceFactory<D>::Create(hstring_ref dnssdServiceInstanceName, const Windows::Networking::HostName & hostName, uint16_t port) const
{
    Windows::Networking::ServiceDiscovery::Dnssd::DnssdServiceInstance result { nullptr };
    check_hresult(static_cast<const IDnssdServiceInstanceFactory &>(static_cast<const D &>(*this))->abi_Create(get(dnssdServiceInstanceName), get(hostName), port, put(result)));
    return result;
}

template <typename D> hstring impl_IDnssdServiceInstance<D>::DnssdServiceInstanceName() const
{
    hstring value;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_DnssdServiceInstanceName(put(value)));
    return value;
}

template <typename D> void impl_IDnssdServiceInstance<D>::DnssdServiceInstanceName(hstring_ref value) const
{
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->put_DnssdServiceInstanceName(get(value)));
}

template <typename D> Windows::Networking::HostName impl_IDnssdServiceInstance<D>::HostName() const
{
    Windows::Networking::HostName value { nullptr };
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_HostName(put(value)));
    return value;
}

template <typename D> void impl_IDnssdServiceInstance<D>::HostName(const Windows::Networking::HostName & value) const
{
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->put_HostName(get(value)));
}

template <typename D> uint16_t impl_IDnssdServiceInstance<D>::Port() const
{
    uint16_t value {};
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_Port(&value));
    return value;
}

template <typename D> void impl_IDnssdServiceInstance<D>::Port(uint16_t value) const
{
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->put_Port(value));
}

template <typename D> uint16_t impl_IDnssdServiceInstance<D>::Priority() const
{
    uint16_t value {};
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_Priority(&value));
    return value;
}

template <typename D> void impl_IDnssdServiceInstance<D>::Priority(uint16_t value) const
{
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->put_Priority(value));
}

template <typename D> uint16_t impl_IDnssdServiceInstance<D>::Weight() const
{
    uint16_t value {};
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_Weight(&value));
    return value;
}

template <typename D> void impl_IDnssdServiceInstance<D>::Weight(uint16_t value) const
{
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->put_Weight(value));
}

template <typename D> Windows::Foundation::Collections::IMap<hstring, hstring> impl_IDnssdServiceInstance<D>::TextAttributes() const
{
    Windows::Foundation::Collections::IMap<hstring, hstring> value;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->get_TextAttributes(put(value)));
    return value;
}

template <typename D> Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> impl_IDnssdServiceInstance<D>::RegisterStreamSocketListenerAsync(const Windows::Networking::Sockets::StreamSocketListener & socket) const
{
    Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> result;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->abi_RegisterStreamSocketListenerAsync1(get(socket), put(result)));
    return result;
}

template <typename D> Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> impl_IDnssdServiceInstance<D>::RegisterStreamSocketListenerAsync(const Windows::Networking::Sockets::StreamSocketListener & socket, const Windows::Networking::Connectivity::NetworkAdapter & adapter) const
{
    Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> result;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->abi_RegisterStreamSocketListenerAsync2(get(socket), get(adapter), put(result)));
    return result;
}

template <typename D> Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> impl_IDnssdServiceInstance<D>::RegisterDatagramSocketAsync(const Windows::Networking::Sockets::DatagramSocket & socket) const
{
    Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> result;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->abi_RegisterDatagramSocketAsync1(get(socket), put(result)));
    return result;
}

template <typename D> Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> impl_IDnssdServiceInstance<D>::RegisterDatagramSocketAsync(const Windows::Networking::Sockets::DatagramSocket & socket, const Windows::Networking::Connectivity::NetworkAdapter & adapter) const
{
    Windows::Foundation::IAsyncOperation<Windows::Networking::ServiceDiscovery::Dnssd::DnssdRegistrationResult> result;
    check_hresult(static_cast<const IDnssdServiceInstance &>(static_cast<const D &>(*this))->abi_RegisterDatagramSocketAsync2(get(socket), get(adapter), put(result)));
    return result;
}

inline DnssdRegistrationResult::DnssdRegistrationResult() :
    DnssdRegistrationResult(activate_instance<DnssdRegistrationResult>())
{}

inline DnssdServiceInstance::DnssdServiceInstance(hstring_ref dnssdServiceInstanceName, const Windows::Networking::HostName & hostName, uint16_t port) :
    DnssdServiceInstance(get_activation_factory<DnssdServiceInstance, IDnssdServiceInstanceFactory>().Create(dnssdServiceInstanceName, hostName, port))
{}

}

}


text:
package org.apache.hadoop.hive.ql.optimizer.lineage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.ExtractOperator;
import org.apache.hadoop.hive.ql.exec.ForwardOperator;
import org.apache.hadoop.hive.ql.exec.GroupByOperator;
import org.apache.hadoop.hive.ql.exec.JoinOperator;
import org.apache.hadoop.hive.ql.exec.LateralViewJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.SelectOperator;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.hooks.LineageInfo;
import org.apache.hadoop.hive.ql.hooks.LineageInfo.BaseColumnInfo;
import org.apache.hadoop.hive.ql.hooks.LineageInfo.Dependency;
import org.apache.hadoop.hive.ql.hooks.LineageInfo.DependencyType;
import org.apache.hadoop.hive.ql.hooks.LineageInfo.TableAliasInfo;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.lib.Utils;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.RowResolver;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.AggregationDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.JoinDesc;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.ReduceSinkDesc;

/**
 * Operator factory for the rule processors for lineage.
 */
public class OpProcFactory {

  /**
   * Returns the parent operator in the walk path to the current operator.
   *
   * @param stack The stack encoding the path.
   *
   * @return Operator The parent operator in the current path.
   */
  protected static Operator<? extends OperatorDesc> getParent(Stack<Node> stack) {
    return (Operator<? extends OperatorDesc>)Utils.getNthAncestor(stack, 1);
  }

  /**
   * Processor for Script and UDTF Operators.
   */
  public static class TransformLineage extends DefaultLineage implements NodeProcessor {

    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      // LineageCTx
      LineageCtx lCtx = (LineageCtx) procCtx;

      // The operators
      Operator<? extends OperatorDesc> op = (Operator<? extends OperatorDesc>)nd;
      Operator<? extends OperatorDesc> inpOp = getParent(stack);

      // Create a single dependency list by concatenating the dependencies of all
      // the cols
      Dependency dep = new Dependency();
      DependencyType new_type = LineageInfo.DependencyType.SCRIPT;
      dep.setType(LineageInfo.DependencyType.SCRIPT);
      // TODO: Fix this to a non null value.
      dep.setExpr(null);

      LinkedHashSet<BaseColumnInfo> col_set = new LinkedHashSet<BaseColumnInfo>();
      for(ColumnInfo ci : inpOp.getSchema().getSignature()) {
        Dependency d = lCtx.getIndex().getDependency(inpOp, ci);
        if (d != null) {
          new_type = LineageCtx.getNewDependencyType(d.getType(), new_type);
          col_set.addAll(d.getBaseCols());
        }
      }

      dep.setType(new_type);
      dep.setBaseCols(new ArrayList<BaseColumnInfo>(col_set));

      // This dependency is then set for all the colinfos of the script operator
      for(ColumnInfo ci : op.getSchema().getSignature()) {
        lCtx.getIndex().putDependency(op, ci, dep);
      }

      return null;
    }

  }

  /**
   * Processor for TableScan Operator. This actually creates the base column mappings.
   */
  public static class TableScanLineage extends DefaultLineage implements NodeProcessor {

    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      ParseContext pctx = lCtx.getParseCtx();

      // Table scan operator.
      TableScanOperator top = (TableScanOperator)nd;
      org.apache.hadoop.hive.ql.metadata.Table t = top.getConf().getTableMetadata();
      Table tab = t.getTTable();

      // Generate the mappings
      RowSchema rs = top.getSchema();
      List<FieldSchema> cols = t.getAllCols();
      Map<String, FieldSchema> fieldSchemaMap = new HashMap<String, FieldSchema>();
      for(FieldSchema col : cols) {
        fieldSchemaMap.put(col.getName(), col);
      }

      Iterator<VirtualColumn> vcs = VirtualColumn.getRegistry(pctx.getConf()).iterator();
      while (vcs.hasNext()) {
        VirtualColumn vc = vcs.next();
        fieldSchemaMap.put(vc.getName(), new FieldSchema(vc.getName(),
            vc.getTypeInfo().getTypeName(), ""));
      }

      TableAliasInfo tai = new TableAliasInfo();
      tai.setAlias(top.getConf().getAlias());
      tai.setTable(tab);
      for(ColumnInfo ci : rs.getSignature()) {
        // Create a dependency
        Dependency dep = new Dependency();
        BaseColumnInfo bci = new BaseColumnInfo();
        bci.setTabAlias(tai);
        bci.setColumn(fieldSchemaMap.get(ci.getInternalName()));

        // Populate the dependency
        dep.setType(LineageInfo.DependencyType.SIMPLE);
        // TODO: Find out how to get the expression here.
        dep.setExpr(null);
        dep.setBaseCols(new ArrayList<BaseColumnInfo>());
        dep.getBaseCols().add(bci);

        // Put the dependency in the map
        lCtx.getIndex().putDependency(top, ci, dep);
      }

      return null;
    }

  }

  /**
   * Processor for Join Operator.
   */
  public static class JoinLineage extends DefaultLineage implements NodeProcessor {
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      // Assert that there is atleast one item in the stack. This should never
      // be called for leafs.
      assert(!stack.isEmpty());

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      JoinOperator op = (JoinOperator)nd;
      JoinDesc jd = op.getConf();

      // The input operator to the join is always a reduce sink operator
      ReduceSinkOperator inpOp = (ReduceSinkOperator)getParent(stack);
      ReduceSinkDesc rd = inpOp.getConf();
      int tag = rd.getTag();

      // Iterate over the outputs of the join operator and merge the
      // dependencies of the columns that corresponding to the tag.
      int cnt = 0;
      List<ExprNodeDesc> exprs = jd.getExprs().get((byte)tag);
      for(ColumnInfo ci : op.getSchema().getSignature()) {
        if (jd.getReversedExprs().get(ci.getInternalName()) != tag) {
          continue;
        }

        // Otherwise look up the expression corresponding to this ci
        ExprNodeDesc expr = exprs.get(cnt++);
        Dependency dependency = ExprProcFactory.getExprDependency(lCtx, inpOp, expr);
        lCtx.getIndex().mergeDependency(op, ci, dependency);
      }

      return null;
    }

  }

  /**
   * Processor for Join Operator.
   */
  public static class LateralViewJoinLineage extends DefaultLineage implements NodeProcessor {
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      // Assert that there is atleast one item in the stack. This should never
      // be called for leafs.
      assert(!stack.isEmpty());

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      LateralViewJoinOperator op = (LateralViewJoinOperator)nd;
      boolean isUdtfPath = true;
      Operator<? extends OperatorDesc> inpOp = getParent(stack);
      ArrayList<ColumnInfo> cols = inpOp.getSchema().getSignature();

      if (inpOp instanceof SelectOperator) {
        isUdtfPath = false;
      }

      // Dirty hack!!
      // For the select path the columns are the ones at the end of the
      // current operators schema and for the udtf path the columns are
      // at the beginning of the operator schema.
      ArrayList<ColumnInfo> out_cols = op.getSchema().getSignature();
      int out_cols_size = out_cols.size();
      int cols_size = cols.size();
      if (isUdtfPath) {
        int cnt = 0;
        while (cnt < cols_size) {
          lCtx.getIndex().mergeDependency(op, out_cols.get(cnt),
              lCtx.getIndex().getDependency(inpOp, cols.get(cnt)));
          cnt++;
        }
      }
      else {
        int cnt = cols_size - 1;
        while (cnt >= 0) {
          lCtx.getIndex().mergeDependency(op, out_cols.get(out_cols_size - cols_size + cnt),
              lCtx.getIndex().getDependency(inpOp, cols.get(cnt)));
          cnt--;
        }
      }
      return null;
    }

  }

  /**
   * Processor for Select operator.
   */
  public static class SelectLineage extends DefaultLineage implements NodeProcessor {
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      LineageCtx lctx = (LineageCtx)procCtx;
      SelectOperator sop = (SelectOperator)nd;

      // if this is a selStarNoCompute then this select operator
      // is treated like a default operator, so just call the super classes
      // process method.
      if (sop.getConf().isSelStarNoCompute()) {
        return super.process(nd, stack, procCtx, nodeOutputs);
      }

      // Otherwise we treat this as a normal select operator and look at
      // the expressions.

      ArrayList<ColumnInfo> col_infos = sop.getSchema().getSignature();
      int cnt = 0;
      for(ExprNodeDesc expr : sop.getConf().getColList()) {
        lctx.getIndex().putDependency(sop, col_infos.get(cnt++),
            ExprProcFactory.getExprDependency(lctx, getParent(stack), expr));
      }

      return null;
    }

  }

  /**
   * Processor for GroupBy operator.
   */
  public static class GroupByLineage extends DefaultLineage implements NodeProcessor {
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {

      LineageCtx lctx = (LineageCtx)procCtx;
      GroupByOperator gop = (GroupByOperator)nd;
      ArrayList<ColumnInfo> col_infos = gop.getSchema().getSignature();
      Operator<? extends OperatorDesc> inpOp = getParent(stack);
      int cnt = 0;

      for(ExprNodeDesc expr : gop.getConf().getKeys()) {
        lctx.getIndex().putDependency(gop, col_infos.get(cnt++),
            ExprProcFactory.getExprDependency(lctx, inpOp, expr));
      }

      for(AggregationDesc agg : gop.getConf().getAggregators()) {
        // Concatenate the dependencies of all the parameters to
        // create the new dependency
        Dependency dep = new Dependency();
        DependencyType new_type = LineageInfo.DependencyType.EXPRESSION;
        // TODO: Get the actual string here.
        dep.setExpr(null);
        LinkedHashSet<BaseColumnInfo> bci_set = new LinkedHashSet<BaseColumnInfo>();
        for(ExprNodeDesc expr : agg.getParameters()) {
          Dependency expr_dep = ExprProcFactory.getExprDependency(lctx, inpOp, expr);
          if (expr_dep != null) {
            new_type = LineageCtx.getNewDependencyType(expr_dep.getType(), new_type);
            bci_set.addAll(expr_dep.getBaseCols());
          }
        }

        // If the bci_set is empty, this means that the inputs to this
        // aggregate function were all constants (e.g. count(1)). In this case
        // the aggregate function is just dependent on all the tables that are in
        // the dependency list of the input operator.
        if (bci_set.isEmpty()) {
          Set<TableAliasInfo> tai_set = new LinkedHashSet<TableAliasInfo>();
          if (inpOp.getSchema() != null && inpOp.getSchema().getSignature() != null ) {
            for(ColumnInfo ci : inpOp.getSchema().getSignature()) {
              Dependency inp_dep = lctx.getIndex().getDependency(inpOp, ci);
              // The dependency can be null as some of the input cis may not have
              // been set in case of joins.
              if (inp_dep != null) {
                for(BaseColumnInfo bci : inp_dep.getBaseCols()) {
                  new_type = LineageCtx.getNewDependencyType(inp_dep.getType(), new_type);
                  tai_set.add(bci.getTabAlias());
                }
              }
            }
          }

          // Create the BaseColumnInfos and set them in the bci_set
          for(TableAliasInfo tai : tai_set) {
            BaseColumnInfo bci = new BaseColumnInfo();
            bci.setTabAlias(tai);
            // This is set to null to reflect that the dependency is not on any
            // particular column of the table.
            bci.setColumn(null);
            bci_set.add(bci);
          }
        }

        dep.setBaseCols(new ArrayList<BaseColumnInfo>(bci_set));
        dep.setType(new_type);
        lctx.getIndex().putDependency(gop, col_infos.get(cnt++), dep);
      }

      return null;
    }

  }

  /**
   * Union processor.
   * In this case we call mergeDependency as opposed to putDependency
   * in order to account for visits from different parents.
   */
  public static class UnionLineage extends DefaultLineage implements NodeProcessor {

    protected static final Log LOG = LogFactory.getLog(OpProcFactory.class.getName());

    @SuppressWarnings("unchecked")
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {
      // Assert that there is atleast one item in the stack. This should never
      // be called for leafs.
      assert(!stack.isEmpty());

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      Operator<? extends OperatorDesc> op = (Operator<? extends OperatorDesc>)nd;

      // Get the row schema of the input operator.
      // The row schema of the parent operator
      Operator<? extends OperatorDesc> inpOp = getParent(stack);
      RowSchema rs = op.getSchema();
      ArrayList<ColumnInfo> inp_cols = inpOp.getSchema().getSignature();
      int cnt = 0;
      for(ColumnInfo ci : rs.getSignature()) {
        Dependency inp_dep = lCtx.getIndex().getDependency(inpOp, inp_cols.get(cnt++));
        if (inp_dep != null) {
          lCtx.getIndex().mergeDependency(op, ci, inp_dep);
        }
      }
      return null;
    }
  }

  /**
   * ReduceSink processor.
   */
  public static class ReduceSinkLineage implements NodeProcessor {

    protected static final Log LOG = LogFactory.getLog(OpProcFactory.class.getName());

    @SuppressWarnings("unchecked")
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {
      // Assert that there is atleast one item in the stack. This should never
      // be called for leafs.
      assert(!stack.isEmpty());

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      ReduceSinkOperator rop = (ReduceSinkOperator)nd;

      Operator<? extends OperatorDesc> inpOp = getParent(stack);
      int cnt = 0;

      // The keys are included only in case the reduce sink feeds into
      // a group by operator through a chain of forward operators
      Operator<? extends OperatorDesc> op = rop.getChildOperators().get(0);
      while (op instanceof ForwardOperator) {
        op = op.getChildOperators().get(0);
      }

      if (op instanceof GroupByOperator) {
        ArrayList<ColumnInfo> col_infos = rop.getSchema().getSignature();
        for(ExprNodeDesc expr : rop.getConf().getKeyCols()) {
          lCtx.getIndex().putDependency(rop, col_infos.get(cnt++),
              ExprProcFactory.getExprDependency(lCtx, inpOp, expr));
        }
        for(ExprNodeDesc expr : rop.getConf().getValueCols()) {
          lCtx.getIndex().putDependency(rop, col_infos.get(cnt++),
              ExprProcFactory.getExprDependency(lCtx, inpOp, expr));
        }
      } else if (op instanceof ExtractOperator) {
        ArrayList<ColumnInfo> col_infos = rop.getSchema().getSignature();
        for(ExprNodeDesc expr : rop.getConf().getValueCols()) {
          lCtx.getIndex().putDependency(rop, col_infos.get(cnt++),
              ExprProcFactory.getExprDependency(lCtx, inpOp, expr));
        }
      } else {
        RowResolver resolver = lCtx.getParseCtx().getOpParseCtx().get(rop).getRowResolver();
        ReduceSinkDesc desc = rop.getConf();
        List<ExprNodeDesc> keyCols = desc.getKeyCols();
        ArrayList<String> keyColNames = desc.getOutputKeyColumnNames();
        for (int i = 0; i < keyCols.size(); i++) {
          // order-bys, joins
          String[] nm = resolver.reverseLookup(Utilities.ReduceField.KEY + "." + keyColNames.get(i));
          if (nm == null) {
            continue;   // key in values
          }
          ColumnInfo column = resolver.get(nm[0], nm[1]);
          lCtx.getIndex().putDependency(rop, column,
              ExprProcFactory.getExprDependency(lCtx, inpOp, keyCols.get(i)));
        }
        List<ExprNodeDesc> valCols = desc.getValueCols();
        ArrayList<String> valColNames = desc.getOutputValueColumnNames();
        for (int i = 0; i < valCols.size(); i++) {
          // todo: currently, bucketing,etc. makes RS differently with those for order-bys or joins
          String[] nm = resolver.reverseLookup(valColNames.get(i));
          if (nm == null) {
            // order-bys, joins
            nm = resolver.reverseLookup(Utilities.ReduceField.VALUE + "." + valColNames.get(i));
          }
          ColumnInfo column = resolver.get(nm[0], nm[1]);
          lCtx.getIndex().putDependency(rop, column,
              ExprProcFactory.getExprDependency(lCtx, inpOp, valCols.get(i)));
        }
      }

      return null;
    }
  }

  /**
   * Default processor. This basically passes the input dependencies as such
   * to the output dependencies.
   */
  public static class DefaultLineage implements NodeProcessor {

    protected static final Log LOG = LogFactory.getLog(OpProcFactory.class.getName());

    @SuppressWarnings("unchecked")
    @Override
    public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
        Object... nodeOutputs) throws SemanticException {
      // Assert that there is atleast one item in the stack. This should never
      // be called for leafs.
      assert(!stack.isEmpty());

      // LineageCtx
      LineageCtx lCtx = (LineageCtx) procCtx;
      Operator<? extends OperatorDesc> op = (Operator<? extends OperatorDesc>)nd;

      // Get the row schema of the input operator.
      // The row schema of the parent operator
      Operator<? extends OperatorDesc> inpOp = getParent(stack);
      RowSchema rs = op.getSchema();
      ArrayList<ColumnInfo> inp_cols = inpOp.getSchema().getSignature();
      int cnt = 0;
      for(ColumnInfo ci : rs.getSignature()) {
        lCtx.getIndex().putDependency(op, ci,
            lCtx.getIndex().getDependency(inpOp, inp_cols.get(cnt++)));
      }
      return null;
    }
  }

  public static NodeProcessor getJoinProc() {
    return new JoinLineage();
  }

  public static NodeProcessor getLateralViewJoinProc() {
    return new LateralViewJoinLineage();
  }

  public static NodeProcessor getTSProc() {
    return new TableScanLineage();
  }

  public static NodeProcessor getTransformProc() {
    return new TransformLineage();
  }

  public static NodeProcessor getSelProc() {
    return new SelectLineage();
  }

  public static NodeProcessor getGroupByProc() {
    return new GroupByLineage();
  }

  public static NodeProcessor getUnionProc() {
    return new UnionLineage();
  }

  public static NodeProcessor getReduceSinkProc() {
    return new ReduceSinkLineage();
  }

  public static NodeProcessor getDefaultProc() {
    return new DefaultLineage();
  }

}


text:
package de.leanovate.dose.cart.connectors

import com.twitter.finagle.Http
import java.net.URLEncoder
import de.leanovate.dose.cart.cartconfig
import org.jboss.netty.handler.codec.http._
import java.nio.charset.Charset
import de.leanovate.dose.cart.model.ActiveProduct
import de.leanovate.dose.cart.util.Json
import de.leanovate.dose.cart.logging.CorrelationContext
import com.twitter.finagle.tracing.{DefaultTracer, TracingFilter, Trace}
import de.leanovate.dose.cart.model.ActiveProduct
import scala.Some

object ProductConnector {
  val productTracer = new TracingFilter[HttpRequest, HttpResponse](DefaultTracer, "product-service")
  val charset = Charset.forName("UTF-8")

  def getProduct(productId: String) = {

    val client = Http.newService(cartconfig.productHost())
    val request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
      "/products/" + URLEncoder.encode(productId, "UTF-8"))
    request.headers().add("User-Agent", "Finagle/Netty")
    request.headers().add("Accept", "application/json")
    request.headers().add("Host", "product-service")
    request.headers().add("X-CorrelationId", CorrelationContext.correlationId)

    productTracer.apply(request, client).map {
      response =>
        if (response.getStatus.getCode == 200) {
          Some(Json.readValue(response.getContent.toString(charset), classOf[ActiveProduct]))
        } else {
          None
        }
    }
  }
}


text:
<?php
class InstallAppController extends AppController {

    function beforeFilter() {

    }

}
?>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<config>
    <enable-sounds>true</enable-sounds>
    <http-agent-port>8080</http-agent-port>
    <max-notifications>15</max-notifications>
    <notification-duration>120000</notification-duration>
</config>


text:
{{template config_path="design/email/header_template"}}

{{trans "%name," name=$customer.getName()}}

                {{trans "Some of your points will expire soon!"}}

{{trans "Hurry up and use your points before expiry date."}}

            {{trans "Some of your points (%points points) will expire soon." points=$points |raw}}

            {{trans "You have %days day(s) to use your points, otherwise you will loose them." days=$days |raw}}

            {{trans "Visit us on our store in order to use your points."}}

{{template config_path="design/email/footer_template"}}


text:
import './polyfills';
import { initializeIcons } from '@uifabric/icons';
import React from 'react';
import * as ReactDOM from 'react-dom';
import App from './pages/App';
import { lightTheme } from './theme/light';
import { loadTheme } from '@uifabric/styling';
import 'react-app-polyfill/ie11';
import LogService from './utils/LogService';

LogService.initialize();
initializeIcons();
loadTheme(lightTheme); // make sure we load a custom theme before anything else, custom theme has custom semantic colors

LogService.startTrackPage('shell');

ReactDOM.render(<App />, document.getElementById('root') as HTMLElement);


text:
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder;

/// <summary>
/// Options for the WelcomePageMiddleware.
/// </summary>
public class WelcomePageOptions
{
    /// <summary>
    /// Specifies which requests paths will be responded to. Exact matches only. Leave null to handle all requests.
    /// </summary>
    public PathString Path { get; set; }
}


text:
import tl = require('azure-pipelines-task-lib');
import { DeploymentFactory } from '../deploymentProvider/DeploymentFactory';
import { WindowsWebAppRunFromZipProvider } from '../deploymentProvider/WindowsWebAppRunFromZipProvider'
import { IWebAppDeploymentProvider } from '../deploymentProvider/IWebAppDeploymentProvider';
import { TaskParametersUtility, TaskParameters, DeploymentType } from '../operations/TaskParameters';
import { stringify } from 'querystring';
import { PackageType } from 'azure-pipelines-tasks-webdeployment-common-v4/packageUtility';
import { getMockEndpoint } from '../node_modules/azure-pipelines-tasks-azure-arm-rest-v2/Tests/mock_utils';
import { mockAzureARMPreDeploymentSteps, mockRunFromZipSettings }  from "./mock_utils";

getMockEndpoint();
mockAzureARMPreDeploymentSteps();
mockRunFromZipSettings();

export class WindowsWebAppRunFromZipProviderL0Tests  {

    public static async startWindowsWebAppRunFromZipProviderL0Tests() {
        await WindowsWebAppRunFromZipProviderL0Tests.testForPreDeploymentSteps_RunFromZipProvider();
        await WindowsWebAppRunFromZipProviderL0Tests.testForPreDeploymentStepsWithSlotEnabled_RunFromZipProvider();
        await WindowsWebAppRunFromZipProviderL0Tests.testForUpdateDeploymentStatus_RunFromZipProvider();
        await WindowsWebAppRunFromZipProviderL0Tests.testForDeployWebAppStep_RunFromZipProvider();
        await WindowsWebAppRunFromZipProviderL0Tests.testForDeployWebAppStepForFolder_RunFromZipProvider();
    }

    public static async testForPreDeploymentSteps_RunFromZipProvider() {
        try {
            var taskParameters: TaskParameters = TaskParametersUtility.getParameters();
            var windowsWebAppRunFromZipProvider : WindowsWebAppRunFromZipProvider  = new WindowsWebAppRunFromZipProvider(taskParameters);
            await windowsWebAppRunFromZipProvider.PreDeploymentStep();
            tl.setResult(tl.TaskResult.Succeeded, 'PreDeployment steps for run from zip should succeeded');
        } catch(error) {
            tl.setResult(tl.TaskResult.Failed, 'PreDeployment steps for built in run from zip failed with error');
        }
    }

    public static async testForPreDeploymentStepsWithSlotEnabled_RunFromZipProvider() {
        try {
            var taskParameters: TaskParameters = TaskParametersUtility.getParameters();
            taskParameters.DeployToSlotOrASEFlag = true;
            taskParameters.ResourceGroupName = "MOCK_RESOURCE_GROUP_NAME";
            var windowsWebAppRunFromZipProvider : WindowsWebAppRunFromZipProvider  = new WindowsWebAppRunFromZipProvider(taskParameters);
            await windowsWebAppRunFromZipProvider.PreDeploymentStep();
            tl.setResult(tl.TaskResult.Succeeded, 'PreDeployment steps for run from zip with slot enabled should succeeded');
        } catch(error) {
            tl.setResult(tl.TaskResult.Failed, 'PreDeployment steps for run from zip with slot enabled failed with error');
        }
    }

    public static async testForUpdateDeploymentStatus_RunFromZipProvider() {
        try {
            var taskParameters: TaskParameters = TaskParametersUtility.getParameters();
            taskParameters.ScriptType = "Run Script";
            var windowsWebAppRunFromZipProvider : WindowsWebAppRunFromZipProvider  = new WindowsWebAppRunFromZipProvider(taskParameters);
            await windowsWebAppRunFromZipProvider.PreDeploymentStep();
            await windowsWebAppRunFromZipProvider.UpdateDeploymentStatus(true);
        } catch(error) {
            tl.setResult(tl.TaskResult.Failed, 'UpdateDeploymentStatus for run from zip steps should succeeded but failed with error');
        }
    }

    public static async testForDeployWebAppStep_RunFromZipProvider() {
        try {
            var taskParameters: TaskParameters = TaskParametersUtility.getParameters();
            taskParameters.Package.getPackageType = () :PackageType => {return PackageType.zip};
            taskParameters.Package.getPath = () :string => { return "webAppPkg.zip" };
            var windowsWebAppRunFromZipProvider : WindowsWebAppRunFromZipProvider  = new WindowsWebAppRunFromZipProvider(taskParameters);
            await windowsWebAppRunFromZipProvider.PreDeploymentStep();
            await windowsWebAppRunFromZipProvider.DeployWebAppStep();
            tl.setResult(tl.TaskResult.Succeeded, 'DeployWebAppStep for run from zip steps with zip package succeeded');
        } catch(error) {
            tl.setResult(tl.TaskResult.Failed, 'DeployWebAppStep for run from zip steps with zip package should succeeded but failed with error');
        }
    }

    public static async testForDeployWebAppStepForFolder_RunFromZipProvider() {
        try {
            var taskParameters: TaskParameters = TaskParametersUtility.getParameters();
            taskParameters.Package.getPackageType = () :PackageType => {return PackageType.folder};
            taskParameters.Package.getPath = () :string => { return "webAppPkg" };
            var windowsWebAppRunFromZipProvider : WindowsWebAppRunFromZipProvider  = new WindowsWebAppRunFromZipProvider(taskParameters);
            await windowsWebAppRunFromZipProvider.PreDeploymentStep();
            await windowsWebAppRunFromZipProvider.DeployWebAppStep();
            tl.setResult(tl.TaskResult.Succeeded, 'DeployWebAppStep for run from zip steps with folder package succeeded');
        } catch(error) {
            tl.setResult(tl.TaskResult.Failed, 'DeployWebAppStep for run from zip steps with folder package should succeeded but failed with error');
        }
    }

}

WindowsWebAppRunFromZipProviderL0Tests.startWindowsWebAppRunFromZipProviderL0Tests();


text:
"""Example program to show how to read a multi-channel time series from LSL."""

from pylsl import StreamInlet, resolve_stream

# first resolve an EEG stream on the lab network
print("looking for an EEG stream...")
streams = resolve_stream('type', 'EEG')

# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])

while True:
    # get a new sample (you can also omit the timestamp part if you're not
    # interested in it)
    sample, timestamp = inlet.pull_sample()
    print(timestamp, sample)


text:
/* @flow */

import { GetStateArguments, GetStateResponse, ModulesInject } from '../../flow_interfaces';
import operationConstants from '../../constants/operations';

export function getOperation(): string {
  return operationConstants.PNGetStateOperation;
}

export function validateParams(modules: ModulesInject) {
  let { config } = modules;

  if (!config.subscribeKey) return 'Missing Subscribe Key';
}

export function getURL(modules: ModulesInject, incomingParams: GetStateArguments): string {
  let { config } = modules;
  let { uuid = config.UUID, channels = [] } = incomingParams;
  let stringifiedChannels = channels.length > 0 ? channels.join(',') : ',';
  return '/v2/presence/sub-key/' + config.subscribeKey + '/channel/' + stringifiedChannels + '/uuid/' + uuid;
}

export function getRequestTimeout({ config }: ModulesInject): number {
  return config.getTransactionTimeout();
}

export function isAuthSupported(): boolean {
  return true;
}

export function prepareParams(modules: ModulesInject, incomingParams: GetStateArguments): Object {
  let { channelGroups = [] } = incomingParams;
  const params = {};

  if (channelGroups.length > 0) {
    params['channel-group'] = channelGroups.join(',');
  }

  return params;
}

export function handleResponse(modules: ModulesInject, serverResponse: Object, incomingParams: GetStateArguments): GetStateResponse {
  let { channels = [], channelGroups = [] } = incomingParams;
  let channelsResponse = {};

  if (channels.length === 1 && channelGroups.length === 0) {
    channelsResponse[channels[0]] = serverResponse.payload;
  } else {
    channelsResponse = serverResponse.payload;
  }

  return { channels: channelsResponse };
}


text:
<?php

namespace Algolia\SearchBundle\EventListener;

use Algolia\SearchBundle\SearchService;
use Doctrine\Common\EventSubscriber;
use Doctrine\Persistence\Event\LifecycleEventArgs;

/**
 * @internal
 */
final class SearchIndexerSubscriber implements EventSubscriber
{
    /**
     * @var SearchService
     */
    private $searchService;

    /**
     * @var array<int, string>
     */
    private $subscribedEvents;

    /**
     * @param array<int, string> $subscribedEvents
     */
    public function __construct(SearchService $searchService, $subscribedEvents)
    {
        $this->searchService     = $searchService;
        $this->subscribedEvents  = $subscribedEvents;
    }

    /**
     * @return array<int, string>
     */
    public function getSubscribedEvents()
    {
        return $this->subscribedEvents;
    }

    /**
     * @return void
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        $this->searchService->index($args->getObjectManager(), $args->getObject());
    }

    /**
     * @return void
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        $this->searchService->index($args->getObjectManager(), $args->getObject());
    }

    /**
     * @return void
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $this->searchService->remove($args->getObjectManager(), $object = $args->getObject());
    }
}


text:
package cherry.fundamental.testtool.stub;

public interface Stub<T> {

	boolean hasNext();

	T next();

	T peek();

	String peekType();

	boolean isMock();

	Object nextMock();

	Object peekMock();

	boolean isThrowable();

	Class<? extends Throwable> nextThrowable();

	Class<? extends Throwable> peekThrowable();

	boolean isRepeated();

	Stub<?> setRepeated(boolean repeated);

	Stub<T> clear();

	<E extends T> Stub<T> alwaysReturn(E value);

	<E extends T> Stub<T> alwaysReturn(E value, String type);

	<E extends T> Stub<T> thenReturn(E value);

	<E extends T> Stub<T> thenReturn(E value, String type);

	Stub<T> alwaysMock(Object mock);

	Stub<T> thenMock(Object mock);

	Stub<T> alwaysThrows(Class<? extends Throwable> klass);

	Stub<T> thenThrows(Class<? extends Throwable> klass);

}


text:
package com.navercorp.pinpoint.web.dao.hbase.stat.v2;

import com.navercorp.pinpoint.common.server.bo.codec.stat.DirectBufferDecoder;
import com.navercorp.pinpoint.common.server.bo.stat.AgentStatType;
import com.navercorp.pinpoint.common.server.bo.stat.DirectBufferBo;
import com.navercorp.pinpoint.web.dao.stat.DirectBufferDao;
import com.navercorp.pinpoint.web.mapper.stat.AgentStatMapperV2;
import com.navercorp.pinpoint.web.vo.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Roy Kim
 */
@Repository("directBufferDaoV2")
public class HbaseDirectBufferDaoV2 implements DirectBufferDao {

    @Autowired
    private DirectBufferDecoder directBufferDecoder;

    @Autowired
    private HbaseAgentStatDaoOperationsV2 operations;

    @Override
    public List<DirectBufferBo> getAgentStatList(String agentId, Range range) {
        AgentStatMapperV2<DirectBufferBo> mapper = operations.createRowMapper(directBufferDecoder, range);
        return operations.getAgentStatList(AgentStatType.DIRECT_BUFFER, mapper, agentId, range);
    }

    @Override
    public boolean agentStatExists(String agentId, Range range) {
        AgentStatMapperV2<DirectBufferBo> mapper = operations.createRowMapper(directBufferDecoder, range);
        return operations.agentStatExists(AgentStatType.DIRECT_BUFFER, mapper, agentId, range);
    }

}


text:
package com.pacific.mapper;

import com.pacific.domain.dto.ApplicationDto;
import com.pacific.domain.entity.Application;
import com.pacific.domain.query.ApplicationQuery;

import java.util.List;

public interface ApplicationMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Application record);

    int insertSelective(Application record);

    Application selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Application record);

    int updateByPrimaryKey(Application record);

    List<Application> queryAllApplicationByState(String state);

    List<ApplicationDto> queryAllApplicationByParam(ApplicationQuery applicationQuery);

    int queryTotalApplication(ApplicationQuery applicationQuery);

    Application selectByApplicationCode(String applicationCode);
}


text:
<?php

namespace ClickNow\Checker\Process;

use ClickNow\Checker\Exception\InvalidArgumentException;
use ClickNow\Checker\Repository\FilesCollection;
use Doctrine\Common\Collections\ArrayCollection;

class ArgumentsCollection extends ArrayCollection
{
    /**
     * For executable.
     *
     * @param string $executable
     *
     * @return \ClickNow\Checker\Process\ArgumentsCollection
     */
    public static function forExecutable($executable)
    {
        return new self([$executable]);
    }

    /**
     * Add optional argument.
     *
     * @param string $argument
     * @param string $value
     *
     * @return void
     */
    public function addOptionalArgument($argument, $value)
    {
        if (!$value) {
            return;
        }

        $this->add(sprintf($argument, $value));
    }

    /**
     * Add optional argument with separated value.
     *
     * @param string $argument
     * @param string $value
     *
     * @return void
     */
    public function addOptionalArgumentWithSeparatedValue($argument, $value)
    {
        if (!$value) {
            return;
        }

        $this->add($argument);
        $this->add($value);
    }

    /**
     * Add optional comma separated argument.
     *
     * @param string $argument
     * @param array  $values
     * @param string $delimiter
     *
     * @return void
     */
    public function addOptionalCommaSeparatedArgument($argument, array $values, $delimiter = ',')
    {
        if (!count($values)) {
            return;
        }

        $this->add(sprintf($argument, implode($delimiter, $values)));
    }

    /**
     * Add optional comma separated argument with separated value.
     *
     * @param string $argument
     * @param array  $values
     * @param string $delimiter
     *
     * @return void
     */
    public function addOptionalCommaSeparatedArgumentWithSeparatedValue($argument, array $values, $delimiter = ',')
    {
        if (!count($values)) {
            return;
        }

        $this->add($argument);
        $this->add(implode($delimiter, $values));
    }

    /**
     * Add argument array.
     *
     * @param string $argument
     * @param array  $values
     *
     * @return void
     */
    public function addArgumentArray($argument, array $values)
    {
        foreach ($values as $value) {
            $this->add(sprintf($argument, $value));
        }
    }

    /**
     * Add argument array with separated value.
     *
     * @param string $argument
     * @param array  $values
     *
     * @return void
     */
    public function addArgumentArrayWithSeparatedValue($argument, array $values)
    {
        foreach ($values as $value) {
            $this->add(sprintf($argument, $value));
            $this->add($value);
        }
    }

    /**
     * Add separated argument array.
     *
     * @param string $argument
     * @param array  $values
     *
     * @return void
     */
    public function addSeparatedArgumentArray($argument, array $values)
    {
        if (!count($values)) {
            return;
        }

        $this->add($argument);

        foreach ($values as $value) {
            $this->add($value);
        }
    }

    /**
     * Add required argument.
     *
     * @param string $argument
     * @param string $value
     *
     * @throws \ClickNow\Checker\Exception\InvalidArgumentException
     *
     * @return void
     */
    public function addRequiredArgument($argument, $value)
    {
        if (!$value) {
            throw new InvalidArgumentException(sprintf('The argument `%s` is required.', $argument));
        }

        $this->add(sprintf($argument, $value));
    }

    /**
     * Add files.
     *
     * @param \ClickNow\Checker\Repository\FilesCollection $files
     *
     * @return void
     */
    public function addFiles(FilesCollection $files)
    {
        $this->addArgumentArray('%s', $files->getAllPaths());
    }

    /**
     * Add comma separated files.
     *
     * @param \ClickNow\Checker\Repository\FilesCollection $files
     *
     * @return void
     */
    public function addCommaSeparatedFiles(FilesCollection $files)
    {
        $this->addOptionalCommaSeparatedArgument('%s', $files->getAllPaths());
    }
}


text:
require 'spec_helper'

require 'launcher/template'

describe Launcher::Template do

  include FakeFS::SpecHelpers

  let(:file_path) { "file.cloudformation" }

  let(:template) { build(:template) }

  before do
    File.open(file_path, "wb") do |f|
      f.write template.to_json
    end
    @template = Launcher::Template.new(file_path)
  end

  subject { @template }

  it { should be_kind_of(Launcher::Message) }
  it_behaves_like "a class that stores messages"

  it { should respond_to(:file) }
  it { should respond_to(:json) }
  it { should respond_to(:file_path) }
  it { should respond_to(:filename) }
  it { should respond_to(:name) }
  it { should respond_to(:parameters) }
  it { should respond_to(:mappings) }
  it { should respond_to(:resources) }
  it { should respond_to(:outputs) }
  it { should respond_to(:defaulted_parameters) }
  it { should respond_to(:non_defaulted_parameters) }

  it "should retrieve the correct filename" do
    expect(@template.filename).to eq file_path
  end

  it "should retrieve the correct template name" do
    expect(@template.name).to eq file_path.split(".")[0]
  end

  describe "the return of valid?" do

    describe "when the template is valid" do
      describe "when AWS is configured" do
        before {
          Launcher::Config::AWS.stub(:configured?) { true }
          AWS::CloudFormation.any_instance.stub(:validate_template) { {} }
        }

        it "should not send any message" do
          expect { |b|
            @template.message_handler &b
            @template.valid?
          }.to_not yield_control
        end

        it { should be_valid }

      end
    end

    describe "when the template is not valid" do

      describe "when there are no resources defined" do
        before { @template.stub(:resources) { {} } }
        it { should_not be_valid }
      end

      describe "when AWS is not configured" do
        before { Launcher::Config::AWS.stub(:configured?) { false } }

        it "should send a warning message" do
          @template.should_receive(:message).at_least(:once) do |msg, opts|
            expect(opts[:type]).to eq(:warn) if opts && opts.include?(:type)
          end
          @template.valid?
        end
      end

      describe "when AWS is configured" do

        let(:aws_error_message) { "The template is invalid" }

        before {
          Launcher::Config::AWS.stub(:configured?) { true }
          AWS::CloudFormation.any_instance.stub(:validate_template) {
            { :message => aws_error_message }
          }
        }

        it "should send the message" do
          @template.should_receive(:message).at_least(:once) do |msg, opts|
            expect(msg).to eq(aws_error_message)
          end
          @template.valid?
        end

        it { should_not be_valid }
      end
    end

  end

  describe "when a new template is initialized" do

    it "should recall the #file_path" do
      expect(@template.file_path).to eq file_path
    end

    it "should read the file contents" do
      expect(@template.read).to eq template.to_json
    end

    describe "and I request the json" do
      it "should return a hash" do
        expect(@template.json).to be_a(Hash)
      end

      it "should parse the contents of the file" do
        expect(@template.json).to eq(template)
      end
    end

  end

  describe "return value of #defaulted_parameters" do
    it "should be a hash" do
      expect(@template.defaulted_parameters).to be_a(Hash)
    end

    it "should be the correct parameters" do
      expected = @template.parameters.keep_if { |k,v| v.has_key?(:Default) }
      expect(@template.defaulted_parameters).to eq expected
    end
  end

  describe "return value of #non_defaulted_parameters" do
    it "should be a hash" do
      expect(@template.non_defaulted_parameters).to be_a(Hash)
    end

    it "should be the correct parameters" do
      expected = @template.parameters.reject { |k,v| v.has_key?(:Default) }
      expect(@template.non_defaulted_parameters).to eq expected
    end
  end

  describe "return value of #parameters" do
    it "should be a hash" do
      expect(@template.parameters).to be_a(Hash)
    end

    it "should be the correct contents" do
      expect(@template.parameters).to eq(template[:Parameters])
    end
  end

  describe "return value of #mappings" do
    it "should be a hash" do
      expect(@template.mappings).to be_a(Hash)
    end

    it "should be the correct contents" do
      expect(@template.mappings).to eq(template[:Mappings])
    end
  end

  describe "return value of #resources" do
    it "should be a hash" do
      expect(@template.resources).to be_a(Hash)
    end

    it "should be the correct contents" do
      expect(@template.resources).to eq(template[:Resources])
    end
  end

  describe "return value of #outputs" do
    it "should be a hash" do
      expect(@template.outputs).to be_a(Hash)
    end

    it "should be the correct contents" do
      expect(@template.outputs).to eq(template[:Outputs])
    end
  end

end


text:
A task manager that utilizes requestIdleCallback api to run tasks safely on the browser.

[![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg?style=flat-square)](https://github.com/avivshaked/IdleTaskQue/blob/master/LICENSE)
[![npm](https://img.shields.io/npm/v/idle-task-que.svg?style=flat-square)](https://www.npmjs.com/package/idle-task-que)
[![Build Status](https://travis-ci.org/avivshaked/IdleTaskQue.svg?branch=master)](https://travis-ci.org/avivshaked/IdleTaskQue)

From [Using requestIdleCallback](https://developers.google.com/web/updates/2015/08/using-requestidlecallback) by [Paul Lewis](https://developers.google.com/web/resources/contributors#paullewis):

>Many sites and apps have a lot of scripts to execute. Your JavaScript often needs to be run as soon as possible, but at the same time you don't want it to get in the user's way. If you send analytics data when the user is scrolling the page, or you append elements to the DOM while they happen to be tapping on the button, your web app can become unresponsive, resulting in a poor user experience.

IdleTaskQue uses requestIdleCallback api to mitigate the issues mentioned above. It also provides a shim fallback for agents that do not have that api. It is a list of tasks, that executes the tasks with ideally minimal impact to the user experience,

## Contents
- [How to include](#how-to-include)
  - [Include script](#include-script)
  - [Include with commonjs](#include-with-commonjs)
- [How to use](#how-to-use)
  - [Adding Tasks](#adding-tasks)
  - [Adding immediate tasks](#adding-immediate-tasks)
  - [Adding non immediate tasks](#adding-non-immediate-tasks)
  - [Executing the que](#executing-the-que)
  - [Removing a task](#removing-a-task)
  - [Clearing the que](#clearing-the-que)
  - [Flushing the que](#flushing-the-que)
  - [Different requestIdleCallback implementation](#different-requestidlecallback-implementation)
- [API](#api)
  - [Task](#task)
  - [IdleTaskQue](#idletaskque)
  - [Module](#module)
## How to include
First you need to install.
```bash
npm install --save idle-task-que
```

You can include in one of two ways:
### Include script
Use a script tag. Including as a script tag will place `IdleTaskQue` object on the window object.
 ```html
  <script src="/node_modules/idle-task-que/dist/inde.min.js"></script>
 ```
Make sure to include the min file, as it is the one that exposes `IdleTaskQue` on the window object. Referencing the unminified file requires commonjs support.

To create a new instance of the que:
```js
const que = IdleTaskQue.create();
```
If you want to access the constructor directly, you can use it like this (though you shouldn't)
```js
const que = new IdleTaskQue.default();
```

### Include with commonjs
Use commonjs pattern to include.
```js
import IdleTaskQue from 'idle-task-que';

const que = new IdleTaskQue();
```
Or
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();
```
## How to use
### Adding tasks
Import the que factory (you can import the constructor and use the new keyword as well), create a new que, and use the **add** method.
Under the hood, a new Task instance is created and either directly executed via **runTaskOnIdle** method on the instance, or it is added to the que and executed later.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, options1);
que.add(taskFunction2, options2);
que.add(taskFunction3);
```
The **add** method returns an integer that is the id of the task for that que. It can be later used to remove the task from the que.

The **add** method accepts two arguments. The first argument is a function. The second argument is an optional options object.

The *options* object contains:
* *context*: [optional] anything. defaults to empty literal object. This value is passed as the first (and only) argument to the task function when it is invoked.
* *binding*: [optional] anything. defaults to empty literal object. This value will be used as the calling site for the task function. If the task function is unbound, and `this` reference will refer to this value.
* *timeout*: [optional] number. Defaults to 0. This value is passed to requestIdleCallback api. When the value is greater then 0, the api will try and fire the task function before the timeout expires.
* *isRunOnce*: [optional] boolean. Defaults to true. If this value is true, once the task function is executed, it will be removed from the que. If the value is false, the task function will be executed every time **run** method is executed.
* *isImmediate*: [optional] boolean. Defaults to true. If this value is true, the task will go directly to execution on idle frame. This is useful for ad hoc tasks that can be deferred to later. A good example for this is tracking.
 If the value is false, the task will be added to a que that will only be executed when the **run** method is called. This is useful for example for listeners callbacks.
* *requestIdleCallback*: [optional] function. Defaults to native requestIdleCallback or the provided shim. This property should be populated if you want to supply a different shim for requestIdleCallback.
### Adding immediate tasks
Immediate tasks are function that should be executed as soon as there's an idle frame.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

// Because of the defaults, isImmediate and isRunOnce are set to true.
// The taskFunction will be executed as soon as there's an idle frame.
que.add(taskFunction);
```
### Adding non immediate tasks
Non immediate tasks are functions that should be executed at a later stage, when there's an idle frame. A good example for this is scroll listener callbacks.
The functions will be executed when **run** method is called.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

window.addEventListener('scroll', que.run);
```
Is is worth mentioning that scroll listeners should be throttled, even when using IdleTaskQue.
### Executing the que
To execute the tasks registered in a que, simply call **run** method.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

que.run();
```
The run method is bound to the instance, so it can be passed safely as a callback.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

window.addEventListener('scroll', que.run);
```

### Removing a task
There are two ways to remove a task. The first way is to use the task function as an identifier.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

que.remove(taskFunction2);
```
The remove method goes through all the registered tasks, and removes all tasks that use that task function.
Another caveat worth mentioning is that it is not possible to remove immediate tasks, because they are not registered to the que for later execution.

The second way to remove a task function from the que is to use the id that is returned when you add a task.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

const id = que.add(taskFunction, { isImmediate: false, isRunOnce: false });

que.removeById(id);
```
### Clearing the que
If for some reason you need to remove all the tasks from the que, use the **clear** method.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

que.clear();
que.run(); // <- nothing happens because all tasks have been cleared.
```
### Flushing the que
If you need to execute all the tasks immediately and do not want to wait for an idle frame, use the **flush** method.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction1, { isImmediate: false, isRunOnce: false });
que.add(taskFunction2, { isImmediate: false, isRunOnce: false });
que.add(taskFunction3, { isImmediate: false, isRunOnce: false });

que.flush();
```
The flush method will run all the tasks immediately, and clear the que. A good use case for this might be on beforeunload event.
The flush method is bound to the instance, so it can be passed safely as a callback.
### Different requestIdleCallback implementation
You might want to provide a different shim than the one shipped with this library. The current shim does very little and is mostly there to prevent the library from breaking in agents that do not support requestIdleCallback.
A good example of a more complicated shim is [PixelsCommander/requestIdleCallback-polyfill](https://github.com/PixelsCommander/requestIdleCallback-polyfill). This library does much more and prevents operation from being executed while user performing some actions on interface.
To Use this polyfill you can consume it before consuming IdleTaskQue. The library will place the polyfill on the global object, and that will be used by IdleTaskQue.
Make sure to place it before consuming IdleTaskQue, otherwise the polyfill will not take effect.

Another way to set a different implementation of requestIdleCallback is to provide your own function to the constructor.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = new IdleTaskQue({ requestIdleCallback: yourOwnImplementation });
```

There's a third way of providing your own implementation. It can be done when adding a new task.
```js
import { createIdleTaskQue } from 'idle-task-que';

const que = createIdleTaskQue();

que.add(taskFunction, { requestIdleCallback: yourOwnImplementation });
```
The alternate implementation will only take effect in the execution of that particular task.

Don't forget to bind your implementation if it has internal references to `this`.

# API
## Task
Ideally you should not use Task directly. IdleTaskQue will create a new task every time an **add** is being called on an instance.
If however you find you want to use Task directly, this is it's api.
### new Task(taskFn, id[, options])
Creates a new instance.

**Arguments:**
* taskFn: Function. This is the function that will be executed by the Task.
* id: number. There are no restrictions on the number.
* options: Object [optional].
  * *context*: [optional] anything. defaults to empty literal object. This value is passed as the first (and only) argument to the task function when it is invoked.
  * *binding*: [optional] anything. defaults to empty literal object. This value will be used as the calling site for the task function. If the task function is unbound, and `this` reference will refer to this value.
  * *timeout*: [optional] number. Defaults to 0. This value is passed to requestIdleCallback api. When the value is greater then 0, the api will try and fire the task function before the timeout expires.
  * *isRunOnce*: [optional] boolean. Defaults to true. If this value is true, once the task function is executed, the registered task function will be nullified. If the value is false, the task function will be executed every time **runTask** method is executed.
  * *isImmediate*: [optional] boolean. Defaults to true. This property is irrelevant for the Task instance.
  * *requestIdleCallback*: [optional] function. Defaults to native requestIdleCallback or the provided shim. This property should be populated if you want to supply a different shim for requestIdleCallback.

**returns:**
An instance of Task.

### runTask()
Executes the registered function. The task will either be executed using requestIdleCallback if the instance has timeout that is greater than zero, or executed directly if timeout is zero.
The task function will be executed with the the instance's binding as the calling site, and the instance's context will be passed as the first and only argument to the task.
### RunTaskOnIdle()
Executes the registered function. The task will be executed using requestIdleCallback event if the instance's timeout is zero.
The task function will be executed with the the instance's binding as the calling site, and the instance's context will be passed as the first and only argument to the task.
### flush()
Executes the registered function immediately without waiting for an idle frame. It also nullifies the task function. Once this method is used, any additional runTask, runTaskOnIdle, and flush executions will have no effect.
### isTaskFunction(taskFn)
Returns true if the received function is equal to the registered function.

**Arguments:**
* taskFn: Function.

**Returns:**

Boolean.
### setRunOnce(state)
**arguments:**
* state: boolean. If true will set the registered task function to run once. If false will set the registered function to run multiple times.
### (Property) timeout: number
Returns the timeout value.
### (Property) isRunOnce: boolean
Returns the value of isRunOnce.
### (Property) isImmediate: boolean
Returns the value of isImmediate.
### (Property) id: number
Returns the value of id.
## IdleTaskQue
This constructor is the main tool of this library. Most actions will be done with an instance of this constructor.
### new IdleTaskQue([config])
Returns an instance of IdleTaskQue.

**Arguments:**
* config: Object [optional].
  * requestIdleCallback: Function. Should comply with requestIdleCallback API.

**Returns:**

An instance of IdleTaskQue.

### add(taskFn[ ,options])
Adds a task function to the que.

**Arguments:**
* taskFn: Function. This function will be used to create a new Task. The task instance will be registered or executed.
* options: Object [optional].
  * *context*: [optional] anything. defaults to empty literal object. This value is passed as the first (and only) argument to the task function when it is invoked.
  * *binding*: [optional] anything. defaults to empty literal object. This value will be used as the calling site for the task function. If the task function is unbound, and `this` reference will refer to this value.
  * *timeout*: [optional] number. Defaults to 0. This value is passed to requestIdleCallback api. When the value is greater then 0, the api will try and fire the task function before the timeout expires.
  * *isRunOnce*: [optional] boolean. Defaults to true. If this value is true, once the task function is executed, it will be removed from the que. If the value is false, the task function will be executed every time **run** method is executed.
  * *isImmediate*: [optional] boolean. Defaults to true. If this value is true, the task will go directly to execution on idle frame. This is useful for ad hoc tasks that can be deferred to later. A good example for this is tracking.
 If the value is false, the task will be added to a que that will only be executed when the **run** method is called. This is useful for example for listeners callbacks.
  * *requestIdleCallback*: [optional] function. Defaults to native requestIdleCallback or the provided shim. This property should be populated if you want to supply a different shim for requestIdleCallback.

**Returns:**

An in id number. That id can be used later to remove the registered task.

### run()
Executes all the registered tasks using requestIdleCallback.

### remove(taskFn)
Removes all the tasks from the que that have that function.

**Arguments:**
* taskFn: Function.

### removeById(taskId)
Removes a task from the que. The task must have an id that is equal to the received taskId.

**Arguments:**
* taskId: number.

**Returns:**

Boolean. True if the task was successfully removed. False if the task was not found.

### clear()
Removes all tasks from the que without executing them.

### flush()
Executes all the tasks immediately and removes them from the que.

### #(Property)# length
Returns the number of tasks in the que.

## Module
These are the exports of the module:
### default
This is the IdleTaskQue constructor.
### requestIdleCallback
This exposes as a bound function either the native implementation or the default used shim.
### cancelIdleCallback
This exposes as a bound function either the native implementation or the default used shim.
### createIdleTaskQue
A factory method that is used to create new IdleTaskQue instances. The function signature is the same as the IdleTaskQue constructor, but the `new` keyword is not used.
### create (alias for createIdleTaskQue)
A factory method that is used to create new IdleTaskQue instances. The function signature is the same as the IdleTaskQue constructor, but the `new` keyword is not used.


text:
package com.lovecws.mumu.system.dao;

import com.lovecws.mumu.common.core.dao.BaseDao;
import com.lovecws.mumu.system.entity.SysUser;

public interface SysUserDao extends BaseDao<SysUser> {

}