text:
package com.google.api.gax.httpjson;

import com.google.api.core.BetaApi;
import javax.annotation.Nullable;

// This class mimics the structure and behavior of the corresponding ClientCall from gRPC package as
// closely as possible.
/**
 * An instance of a call to a remote method. A call will send zero or more request messages to the
 * server and receive zero or more response messages back.
 *
 *
Instances are created by a {@link HttpJsonChannel} and used by stubs to invoke their remote
 * behavior.
 *
 *
{@link #start} must be called prior to calling any other methods, with the exception of {@link
 * #cancel}. Whereas {@link #cancel} must not be followed by any other methods, but can be called
 * more than once, while only the first one has effect.
 *
 *
Methods are potentially blocking but are designed to execute quickly. The implementations of
 * this class are expected to be thread-safe.
 *
 *
There is a race between {@link #cancel} and the completion/failure of the RPC in other ways.
 * If {@link #cancel} won the race, {@link HttpJsonClientCall.Listener#onClose Listener.onClose()}
 * is called with {@code statusCode} corresponding to {@link
 * com.google.api.gax.rpc.StatusCode.Code#CANCELLED CANCELLED}. Otherwise, {@link
 * HttpJsonClientCall.Listener#onClose Listener.onClose()} is called with whatever status the RPC
 * was finished. We ensure that at most one is called.
 *
 * @param <RequestT> type of message sent to the server
 * @param <ResponseT> type of message received one or more times from the server
 */
@BetaApi
public abstract class HttpJsonClientCall<RequestT, ResponseT> {
  /**
   * Callbacks for receiving metadata, response messages and completion status from the server.
   *
   *
Implementations are discouraged to block for extended periods of time. Implementations are
   * not required to be thread-safe, but they must not be thread-hostile. The caller is free to call
   * an instance from multiple threads, but only one call simultaneously.
   */
  @BetaApi
  public abstract static class Listener<T> {
    /**
     * The response headers have been received. Headers always precede messages.
     *
     * @param responseHeaders containing metadata sent by the server at the start of the response
     */
    public void onHeaders(HttpJsonMetadata responseHeaders) {}

    /**
     * A response message has been received. May be called zero or more times depending on whether
     * the call response is empty, a single message or a stream of messages.
     *
     * @param message returned by the server
     */
    public void onMessage(T message) {}

    /**
     * The ClientCall has been closed. Any additional calls to the {@code ClientCall} will not be
     * processed by the server. No further receiving will occur and no further notifications will be
     * made.
     *
     *
This method should not throw. If this method throws, there is no way to be notified of the
     * exception. Implementations should therefore be careful of exceptions which can accidentally
     * leak resources.
     *
     * @param statusCode the HTTP status code representing the result of the remote call
     * @param trailers metadata provided at call completion
     */
    public void onClose(int statusCode, HttpJsonMetadata trailers) {}
  }

  /**
   * Start a call, using {@code responseListener} for processing response messages.
   *
   *
It must be called prior to any other method on this class, except for {@link #cancel} which
   * may be called at any time.
   *
   * @param responseListener receives response messages
   * @param requestHeaders which can contain extra call metadata, e.g. authentication credentials.
   */
  public abstract void start(Listener<ResponseT> responseListener, HttpJsonMetadata requestHeaders);

  /**
   * Requests up to the given number of messages from the call to be delivered to {@link
   * HttpJsonClientCall.Listener#onMessage(Object)}. No additional messages will be delivered.
   *
   *
Message delivery is guaranteed to be sequential in the order received. In addition, the
   * listener methods will not be accessed concurrently. While it is not guaranteed that the same
   * thread will always be used, it is guaranteed that only a single thread will access the listener
   * at a time.
   *
   *
If called multiple times, the number of messages able to delivered will be the sum of the
   * calls.
   *
   *
This method is safe to call from multiple threads without external synchronization.
   *
   * @param numMessages the requested number of messages to be delivered to the listener. Must be
   *     non-negative.
   */
  public abstract void request(int numMessages);

  /**
   * Prevent any further processing for this {@code HttpJsonClientCall}. No further messages may be
   * sent or will be received. The server is not informed of cancellations. Cancellation is
   * permitted even if previously {@link #halfClose}d. Cancelling an already {@code cancel()}ed
   * {@code ClientCall} has no effect.
   *
   *
No other methods on this class can be called after this method has been called.
   *
   * @param message if not {@code null}, will appear as the description of the CANCELLED status
   * @param cause if not {@code null}, will appear as the cause of the CANCELLED status
   */
  public abstract void cancel(@Nullable String message, @Nullable Throwable cause);

  /**
   * Close the call for request message sending. Incoming response messages are unaffected. This
   * should be called when no more messages will be sent from the client.
   */
  public abstract void halfClose();

  /**
   * Send a request message to the server. May be called zero or more times but for unary and server
   * streaming calls it must be called not more than once.
   *
   * @param message message to be sent to the server.
   */
  public abstract void sendMessage(RequestT message);
}


text:
#include "stdafx.h"

#include <chrono>
#include "mscl/Exceptions.h"
#include "AsyncDigitalAnalogPacket.h"
#include "AsyncDigitalPacket.h"
#include "BeaconEchoPacket.h"
#include "BufferedLdcPacket.h"
#include "BufferedLdcPacket_v2.h"
#include "DiagnosticPacket.h"
#include "HclSmartBearing_CalPacket.h"
#include "HclSmartBearing_RawPacket.h"
#include "LdcPacket.h"
#include "LdcMathPacket.h"
#include "LdcMathPacket_aspp3.h"
#include "LdcPacket_v2.h"
#include "LdcPacket_v2_aspp3.h"
#include "RawAngleStrainPacket.h"
#include "RfSweepPacket.h"
#include "RollerPacket.h"
#include "ShmPacket.h"
#include "ShmPacket_v2_aspp3.h"
#include "SyncSamplingPacket.h"
#include "SyncSamplingMathPacket.h"
#include "SyncSamplingMathPacket_aspp3.h"
#include "SyncSamplingPacket_v2.h"
#include "SyncSamplingPacket_v2_aspp3.h"
#include "WirelessPacketCollector.h"
#include "mscl/MicroStrain/Wireless/NodeCommTimes.h"

namespace mscl
{
    WirelessPacketCollector::WirelessPacketCollector():
        m_dataPackets(MAX_DATA_BUFFER_SIZE),
        m_nodeDiscoveryPackets(MAX_DISCOVERY_BUFFER_SIZE)
    {
    }

    //required (if taken out, causes runtime error on destruction of WirelessPacketCollector)
    WirelessPacketCollector::~WirelessPacketCollector()
    {
    }

    void WirelessPacketCollector::addDataPacket(const WirelessPacket& packet)
    {
        //create a boost_lock for thread safety
        mutex_lock_guard lock(m_packetMutex);

        //update the last communication time
        NodeCommTimes::updateCommTime(packet.nodeAddress());

        WirelessPacket::PacketType packetType = packet.type();

        //update the device state for node data packets
        if(packetType != WirelessPacket::packetType_diagnostic &&
           packetType != WirelessPacket::packetType_rfScanSweep &&
           packetType != WirelessPacket::packetType_beaconEcho)
        {
            NodeCommTimes::updateDeviceState(packet.nodeAddress(), DeviceState::deviceState_sampling);
        }

        try
        {
            if(packet.asppVersion() == WirelessPacket::aspp_v3)
            {
                //ASPP v3 Packets

                //add a different packet depending on its type
                switch(packetType)
                {
                    case WirelessPacket::packetType_LDC_16ch:                   m_dataPackets.push_back(LdcPacket_v2_aspp3(packet));            break;
                    case WirelessPacket::packetType_LDC_math:                   m_dataPackets.push_back(LdcMathPacket_aspp3(packet));           break;
                    case WirelessPacket::packetType_SyncSampling_16ch:          m_dataPackets.push_back(SyncSamplingPacket_v2_aspp3(packet));   break;
                    case WirelessPacket::packetType_SyncSampling_math:          m_dataPackets.push_back(SyncSamplingMathPacket_aspp3(packet));  break;
                    case WirelessPacket::packetType_SHM:                        m_dataPackets.push_back(ShmPacket_v2_aspp3(packet));            break;
                    case WirelessPacket::packetType_rawAngleStrain:             m_dataPackets.push_back(RawAngleStrainPacket(packet));          break;  //same payload, no new parser
                    case WirelessPacket::packetType_diagnostic:                 m_dataPackets.push_back(DiagnosticPacket(packet));              break;  //same payload, no new parser
                    case WirelessPacket::packetType_rfScanSweep:                m_dataPackets.push_back(RfSweepPacket(packet));                 break;  //same payload, no new parser
                    case WirelessPacket::packetType_beaconEcho:                 m_dataPackets.push_back(BeaconEchoPacket(packet));              break;  //same payload, no new parser

                    //bad packet type, this function shouldn't have been called
                    default:
                        throw Error("Unknown Packet Type");
                }
            }
            else
            {
                //ASPP v1 and v2 Packets

                //add a different packet depending on its type
                switch(packetType)
                {
                    case WirelessPacket::packetType_LDC:                        m_dataPackets.push_back(LdcPacket(packet));                 break;
                    case WirelessPacket::packetType_SyncSampling:               m_dataPackets.push_back(SyncSamplingPacket(packet));        break;
                    case WirelessPacket::packetType_BufferedLDC:                m_dataPackets.push_back(BufferedLdcPacket(packet));         break;
                    case WirelessPacket::packetType_LDC_math:                   m_dataPackets.push_back(LdcMathPacket(packet));             break;
                    case WirelessPacket::packetType_LDC_16ch:                   m_dataPackets.push_back(LdcPacket_v2(packet));              break;
                    case WirelessPacket::packetType_SyncSampling_16ch:          m_dataPackets.push_back(SyncSamplingPacket_v2(packet));     break;
                    case WirelessPacket::packetType_SyncSampling_math:          m_dataPackets.push_back(SyncSamplingMathPacket(packet));    break;
                    case WirelessPacket::packetType_BufferedLDC_16ch:           m_dataPackets.push_back(BufferedLdcPacket_v2(packet));      break;
                    case WirelessPacket::packetType_AsyncDigital:               m_dataPackets.push_back(AsyncDigitalPacket(packet));        break;
                    case WirelessPacket::packetType_AsyncDigitalAnalog:         m_dataPackets.push_back(AsyncDigitalAnalogPacket(packet));  break;
                    case WirelessPacket::packetType_SHM:                        m_dataPackets.push_back(ShmPacket(packet));                 break;
                    case WirelessPacket::packetType_HclSmartBearing_Calibrated: m_dataPackets.push_back(HclSmartBearing_CalPacket(packet)); break;
                    case WirelessPacket::packetType_HclSmartBearing_Raw:        m_dataPackets.push_back(HclSmartBearing_RawPacket(packet)); break;
                    case WirelessPacket::packetType_rawAngleStrain:             m_dataPackets.push_back(RawAngleStrainPacket(packet));      break;
                    case WirelessPacket::packetType_beaconEcho:                 m_dataPackets.push_back(BeaconEchoPacket(packet));          break;
                    case WirelessPacket::packetType_rfScanSweep:                m_dataPackets.push_back(RfSweepPacket(packet));             break;
                    case WirelessPacket::packetType_diagnostic:                 m_dataPackets.push_back(DiagnosticPacket(packet));          break;
                    case WirelessPacket::packetType_roller:                     m_dataPackets.push_back(RollerPacket(packet));              break;

                    //bad packet type, this function shouldn't have been called
                    default:
                        throw Error("Unknown Packet Type");
                }
            }

            //notify the read thread, if it is waiting for data to be put into the buffer
            m_emptyBufferCondition.notify_one();
        }
        catch(std::exception&)
        {
            //there was an error building one of the packets, just return
        }
    }

    void WirelessPacketCollector::addNodeDiscoveryPacket(const WirelessPacket& packet)
    {
        //create a boost_lock for thread safety
        mutex_lock_guard lock(m_nodeDiscoveryMutex);

        //update the last communication time
        NodeCommTimes::updateCommTime(packet.nodeAddress());

        //add a Node Discovery packet to the node discovery packet container
        m_nodeDiscoveryPackets.push_back( NodeDiscovery(packet) );
    }

    WirelessDataPacket WirelessPacketCollector::getNextDataPacket(int timeout)
    {
        //create a scoped_lock for thread safety
        std::unique_lock<std::mutex> lock(m_packetMutex);

        //if there is no data to read and there is a timeout
        if(m_dataPackets.size() <= 0 && timeout > 0)
        {
            //wait for the timeout or data to come in
            m_emptyBufferCondition.wait_for(lock, std::chrono::milliseconds(timeout));
        }

        //make sure there are packets in the container
        if(m_dataPackets.size() <= 0)
        {
            throw Error_NoData();
        }

        //Get the WirelessDataPacket to be returned as the result
        WirelessDataPacket resultPacket = m_dataPackets.front();

        //remove this packet from the front of the circular buffer (moves everything else in the array down one)
        m_dataPackets.pop_front();

        //return the WirelessDataPacket
        return resultPacket;
    }

    void WirelessPacketCollector::getDataSweeps(std::vector<DataSweep>& sweeps, uint32 timeout, uint32 maxSweeps)
    {
        uint32 sweepCount = 0;

        //create a scoped_lock for thread safety
        std::unique_lock<std::mutex> lock(m_packetMutex);

        //while we still need to get more sweeps (or we want to get all the sweeps)
        while((sweepCount < maxSweeps) || (maxSweeps == 0))
        {
            //if there are no more sweeps in the current packet
            if(!m_currentDataPacket.moreSweeps())
            {
                //if there are no packets
                if(m_dataPackets.size() <= 0)
                {
                    //if there is a timeout and we haven't received any data
                    if(timeout > 0 && sweepCount == 0)
                    {
                        //wait for the timeout or data to come in
                        m_emptyBufferCondition.wait_for(lock, std::chrono::milliseconds(timeout));

                        //if there is no data (we timed out)
                        if(m_dataPackets.size() <= 0)
                        {
                            //break out of the while loop (we have no more data to give)
                            break;
                        }
                    }
                    //if there is no timeout, or if there is a timeout and we already got data
                    else
                    {
                        //break out of the while loop (we have no more data to give)
                        break;
                    }
                }

                //set the current data packet to the next data packet in the buffer
                m_currentDataPacket = m_dataPackets.front();

                //remove this packet from the front of the circular buffer (moves everything else in the array down one)
                m_dataPackets.pop_front();
            }

            //add the next sweep to the result
            sweeps.push_back(DataSweep());
            m_currentDataPacket.getNextSweep(sweeps.back());

            sweepCount++;
        }
    }

    uint32 WirelessPacketCollector::totalSweeps()
    {
        size_t total = 0;

        //create a scoped_lock for thread safety
        mutex_lock_guard lock(m_packetMutex);

        //add the sweeps that are left to be read in the current data packet
        total += m_currentDataPacket.numSweepsRemaining();

        circular_data_buffer::iterator itr;
        circular_data_buffer::iterator end = m_dataPackets.end();

        //loop over all the data packets that we have collected
        for(itr = m_dataPackets.begin(); itr != end; ++itr)
        {
            //add the sweeps of the data packet
            total += itr->numSweeps();
        }

        return static_cast<uint32>(total);
    }

    NodeDiscoveries WirelessPacketCollector::getNodeDiscoveries()
    {
        //create a scoped_lock for thread safety
        mutex_lock_guard lock(m_nodeDiscoveryMutex);

        NodeDiscoveries result;

        //loop through the buffer, removing items until it is empty
        while(!m_nodeDiscoveryPackets.empty())
        {
            //get the Node Discovery packet at the start of the buffer and store it in the result container
            result.push_back(m_nodeDiscoveryPackets.front());

            //remove the packet at the start of the buffer, move on to the next
            m_nodeDiscoveryPackets.pop_front();
        }

        //return the vector container
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace MaterialViewPager.Sample.Activities
{
	class MainActivity
	{
	}
}


text:
module OneviewCookbook
  module API2000
    module Synergy
      # VolumeAttachment API2000 Synergy provider
      class VolumeAttachmentProvider < OneviewCookbook::API2000::C7000::VolumeAttachmentProvider
      end
    end
  end
end


text:
package org.xito.dazzle.widget.table;

import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

/**
 * A Table that uses alternating row colors like on the mac
 * @author deane
 */
public class ScrollTable extends JTable {

    protected TableCellRenderer myDefaultRenderer;
    protected boolean drawSelectedColumn = false;
    protected Color selectedColumnColor;

    public ScrollTable() {
        super();
        init();
    }

    public ScrollTable(Object[][] data, String[] colNames) {
        super(data, colNames);
        init();
    }

    public ScrollTable(TableModel model) {
        super(model);
        init();
    }

    protected void init() {
        myDefaultRenderer = new ScrollTableCellRenderer();
    }

    /**
     * Get PreferredSize
     * @return Dimension
     */
    public Dimension getPreferredSize() {
        Dimension dim = super.getPreferredSize();

        if(getParent() instanceof JViewport) {
            int viewPortH = ((JViewport)getParent()).getHeight();
            if(viewPortH > dim.height) {
                dim.height = viewPortH;
            }
        }

        return dim;
    }

    /**
     * Paint the Component
     */
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        //draw fake rows
        TableHelper.drawExtendedBottomRows(this, g);

        //draw selected column
        if(drawSelectedColumn) {
            TableHelper.drawSelectedBottomCol(this, g, selectedColumnColor);
        }

        //draw vertical grid lines
        TableHelper.drawVerticalGrid(this, g);
    }

    public TableCellRenderer getDefaultRenderer(Class columnClass) {
        return myDefaultRenderer;
    }

}


text:
$(function(){

var flags = {
	'text': [
		{ value: 'x', label: 'is exactly' },
		{ value: 'c', label: 'contains' },
		{ value: 's', label: 'starts with' },
		{ value: 'e', label: 'ends with' },
	    { value: 'i', label: 'is not' }
	],
	'number': [
	    { value: 'x', label: 'is exactly' },
	    { value: 'g', label: 'is greater than' },
	    { value: 'l', label: 'is less than' },
	    { value: 'i', label: 'is not' }
	],
	'boolean-text': [
   	   	    { value: 'x', label: 'is exactly' },
	   	    { value: 'i', label: 'is not' }
	],
	'select': [
	   	    { value: 'x', label: 'is exactly' },
	   	    { value: 'i', label: 'is not' }
	],
};

var typeOptions = [];
if (document.operations) {
	for (var i = 0; i < document.operations.length; i++) {
		typeOptions.push({ value: i + 1, label: document.operations[i] });
	}
}

searchForm('#LatestSearch', {
	'result': { columnType: 'text', helptext: 'e.g. FAILED' },
	'clientid': { columnType: 'text' },
	'job': { columnType: 'text' },
	'reporttime': { columnType: 'number', helptext: 'YYYY/MM/DD [ hh:mm:ss ]' },
	'errors': { columnType: 'number' }
});

searchForm('#ClientsSearch', {
	'clientid': { columnType: 'text' },
	'totalreports': { columnType: 'number' },
	'tags': { columnType: 'boolean-text' }
});

searchForm('#ReportsSearch', {
	'result': { columnType: 'text', helptext: 'e.g. FAILED' },
	'clientid': { columnType: 'text' },
	'job': { columnType: 'text' },
	'reporttime': { columnType: 'number', helptext: 'YYYY/MM/DD [ hh:mm:ss ]' },
	'duration': { columnType: 'number', helptext: 'in seconds or hh:mm:ss' },
	'uploadsize': { columnType: 'number', helptext: 'in bytes or follow with KB/MB/GB' },
	'changedfiles': { columnType: 'number' },
	'errors': { columnType: 'number' }
});

searchForm('#ItemsSearch', {
	'logorder': { columnType: 'number' },
	'type': {
		columnType: 'select',
		options: typeOptions
	},
	'path': { columnType: 'text' },
	'size2': { columnType: 'number', helptext: 'in bytes or follow with KB/MB/GB' },
	'starttime': { columnType: 'number', helptext: '[ YYYY/MM/DD ] hh:mm:ss' },
	'duration': { columnType: 'number', helptext: 'in seconds or hh:mm:ss' },
	'result': { columnType: 'text', helptext: 'e.g. OK, xSocketTimeout' },
	'detail': { columnType: 'text' }
});

searchForm('#FileSearch', {
	'job': { columnType: 'text' },
	'reporttime': { columnType: 'number', helptext: 'YYYY/MM/DD [ hh:mm:ss ]' },
	'type': {
		columnType: 'select',
		options: typeOptions
	},
	'path': { columnType: 'text' },
	'size2': { columnType: 'number', helptext: 'in bytes or follow with KB/MB/GB' },
	'duration': { columnType: 'number', helptext: 'in seconds or hh:mm:ss' },
	'result': { columnType: 'text', helptext: 'e.g. OK, xSocketTimeout' },
	'detail': { columnType: 'text' }
});

function searchForm(selector, config) {
	$(selector).each(function(){
		var $this = $(this);
		var column = $('select:eq(0)', $this);
		var flag = $('select:eq(1)', $this);
		var text = $('input[type=text]', $this);
		var textParent = text.parent();
		var select = $('<select>').attr('name', 'search[text]');
		var helptext = '';

		text.addClass('helptext').focus(function() {
			if (text.hasClass('helptext')) {
				text.val('').removeClass('helptext');
			}
		}).blur(function() {
			if (text.val() == '') {
				text.val(helptext).addClass('helptext');
			}
		});

		// Setup the flags list when the column changes, and reset the 'text' box (optionally with helptext).
		column.bind('keyup change', function() {
			// Determine which flags will be used.
			var colConfig = config[column.val()];

			// Optionally set helptext.
			helptext = $.isDefined(colConfig.helptext) ? colConfig.helptext : '';

			// Reset the text box and optionally set helptext.
			//text.val('').blur();

			// Add the flags for this column.
			flag.empty();
			if (colConfig.columnType) {
				// Add the flags for this type.
				for (var i = 0; i < flags[colConfig.columnType].length; i++) {
					$('<option>').attr('value', flags[colConfig.columnType][i].value).text(flags[colConfig.columnType][i].label).appendTo(flag);
				}

				// Select 'is exactly'
				flag.val('x');

				if (colConfig.columnType == 'select') {
					text.detach();
					select.empty().appendTo(textParent);

					for (var i = 0; i < colConfig.options.length; i++) {
						select.append($('<option>').attr('value', colConfig.options[i].value).text(colConfig.options[i].label));
					}

					select[0].selectedIndex = 0;
				}
				else {
					select.detach();

					// Reset the text box and optionally set helptext.
					text.appendTo(textParent).val('').blur();
				}
			}
		});

		// Init the form.
		column[0].selectedIndex = 0;
		column.change();

		// Set a default value to the search boxes.
		// Used primarily when a criteria is removed.
		if ($.isDefined(document.initialSearchValues)) {
			column.val(document.initialSearchValues.column);
			column.change();
			flag.val(document.initialSearchValues.flag);
			text.focus().val(document.initialSearchValues.text);
		}
	});
}

});


text:
var s = require('node-static'),
  file = new s.Server('.');

var app = require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        file.serve(request, response);
    }).resume();
}).listen(8080);

module.exports = app;


text:
package org.apereo.cas.config;

import org.apereo.cas.aws.AmazonEnvironmentAwareClientBuilder;
import org.apereo.cas.dynamodb.DynamoDbTableUtils;
import org.apereo.cas.util.LoggingUtils;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;

import java.util.Map;
import java.util.Properties;

/**
 * This is {@link DynamoDbCloudConfigBootstrapConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@Configuration(value = "dynamoDbCloudConfigBootstrapConfiguration", proxyBeanMethods = false)
@Slf4j
@Getter
public class DynamoDbCloudConfigBootstrapConfiguration implements PropertySourceLocator {

    /**
     * Configuration table name.
     */
    public static final String TABLE_NAME = "DynamoDbCasProperties";

    /**
     * Configuration prefix.
     */
    public static final String CAS_CONFIGURATION_PREFIX = "cas.spring.cloud.dynamoDb";

    private static final long PROVISIONED_THROUGHPUT = 10;

    @SneakyThrows
    public static void createSettingsTable(final DynamoDbClient amazonDynamoDBClient, final boolean deleteTables) {
        val request = createCreateTableRequest();
        if (deleteTables) {
            val delete = DeleteTableRequest.builder().tableName(request.tableName()).build();
            LOGGER.debug("delete create request [{}] to remove table if necessary", delete);
            DynamoDbTableUtils.deleteTableIfExists(amazonDynamoDBClient, delete);
        }
        LOGGER.debug("Sending create request [{}] to create table", request);
        DynamoDbTableUtils.createTableIfNotExists(amazonDynamoDBClient, request);
        LOGGER.debug("Waiting until table [{}] becomes active...", request.tableName());
        DynamoDbTableUtils.waitUntilActive(amazonDynamoDBClient, request.tableName());
        val describeTableRequest = DescribeTableRequest.builder().tableName(request.tableName()).build();
        LOGGER.debug("Sending request [{}] to obtain table description...", describeTableRequest);
        val tableDescription = amazonDynamoDBClient.describeTable(describeTableRequest).table();
        LOGGER.debug("Located newly created table with description: [{}]", tableDescription);
    }

    @Override
    public PropertySource<?> locate(final Environment environment) {
        val props = new Properties();

        try {
            val builder = new AmazonEnvironmentAwareClientBuilder(CAS_CONFIGURATION_PREFIX, environment);
            val amazonDynamoDBClient = builder.build(DynamoDbClient.builder(), DynamoDbClient.class);
            val preventTableCreationOnStartup = builder.getSetting("prevent-table-creation-on-startup", Boolean.class);
            if (!preventTableCreationOnStartup) {
                createSettingsTable(amazonDynamoDBClient, false);
            }
            val scan = ScanRequest.builder().tableName(TABLE_NAME).build();
            LOGGER.debug("Scanning table with request [{}]", scan);
            val result = amazonDynamoDBClient.scan(scan);
            LOGGER.debug("Scanned table with result [{}]", scan);

            result.items()
                .stream()
                .map(DynamoDbCloudConfigBootstrapConfiguration::retrieveSetting)
                .forEach(p -> props.put(p.getKey(), p.getValue()));
        } catch (final Exception e) {
            LoggingUtils.error(LOGGER, e);
        }

        return new PropertiesPropertySource(getClass().getSimpleName(), props);
    }

    private static Pair<String, Object> retrieveSetting(final Map<String, AttributeValue> entry) {
        val name = entry.get(ColumnNames.NAME.getColumnName()).s();
        val value = entry.get(ColumnNames.VALUE.getColumnName()).s();
        return Pair.of(name, value);
    }

    private static CreateTableRequest createCreateTableRequest() {
        val name = ColumnNames.ID.getColumnName();
        return CreateTableRequest.builder()
            .attributeDefinitions(AttributeDefinition.builder().attributeName(name).attributeType(ScalarAttributeType.S).build())
            .keySchema(KeySchemaElement.builder().attributeName(name).keyType(KeyType.HASH).build())
            .provisionedThroughput(ProvisionedThroughput.builder()
                .readCapacityUnits(PROVISIONED_THROUGHPUT)
                .writeCapacityUnits(PROVISIONED_THROUGHPUT).build())
            .tableName(TABLE_NAME)
            .build();
    }

    @Getter
    @RequiredArgsConstructor
    public enum ColumnNames {

        /**
         * Column id.
         */
        ID("id"),
        /**
         * Column name.
         */
        NAME("name"),
        /**
         * Column value.
         */
        VALUE("value");

        private final String columnName;
    }
}


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

import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Get notification of assignment events. The invocations are inline
 * so make sure your implementation is fast else you'll slow hbase.
 */
@InterfaceAudience.Private
public interface AssignmentListener {
  /**
   * The region was opened on the specified server.
   * @param regionInfo The opened region.
   * @param serverName The remote servers name.
   */
  void regionOpened(final RegionInfo regionInfo, final ServerName serverName);

  /**
   * The region was closed on the region server.
   * @param regionInfo The closed region.
   */
  void regionClosed(final RegionInfo regionInfo);
}


text:
Once none of the tests are skipped and they are all passing, you can submit your solution using `exercism submit numbers.js`.

## Submitting Incomplete Solutions

It is possible to submit an incomplete solution so you can see how others have completed the exercise.

## Links

- [exercism CLI documentation][docs-exercism-cli]

[docs-exercism-cli]: https://exercism.org/docs/using/solving-exercises/working-locally


text:
package com.rasterfoundry.database

import doobie.implicits._

import org.scalatest._

class OrganizationFeatureDaoSpec
    extends FunSuite
    with Matchers
    with DBTestConfig {
  test("selection types") {
    OrganizationFeatureDao.query.list
      .transact(xa)
      .unsafeRunSync
      .length should be >= 0
  }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-nav-bar',
  templateUrl: './nav-bar.component.html',
  styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit {

	private loggedIn = false;

	constructor() { }

	toogle() {
		this.loggedIn = !this.loggedIn;
	}

	ngOnInit() {
	}

}


text:
from typing import Optional

import requests
from flask import Blueprint
from flask import jsonify
from flask import render_template
from flask import request

import config as conf

ner_api = Blueprint('ner_api', __name__)

NER_ENDPOINT_MOLD = 'http://127.0.0.1:{}/compute/'
MODEL_PORTS = {
    'en': int(conf.ner['en_model_port']),
    'it': int(conf.ner['it_model_port']),
    'fr': int(conf.ner['fr_model_port']),
    'de': int(conf.ner['de_model_port'])
}

# Opinion target route handling
def parse_output(output_path):
    f = open(output_path, 'r')
    pred_labels = []
    for line in f:
        line = line.strip()
        if len(line.split()) == 3:
            pred_label = line.split()[2]
            pred_labels.append(pred_label)
    return " ".join(pred_labels)

# NER route handling
@ner_api.route('')
def getNER():
    return render_template('ner/ner.html')

def _get_language(input: str) -> Optional[str]:
    """
    Calls the AIKO api to detect the language of the input text.
    :param input:
    :return:
    """
    headers = {
        'Accept': 'application/vnd.sca.langdetect.v1+json',
        'Content-Type': 'application/json',
        'AI-Enabler-Tenant': conf.ner['aiko_tenant'],
        'Authorization': conf.ner['aiko_token']
    }
    body = {'text': input}
    r = requests.post(conf.ner['aiko_langdetect_endpoint'], headers=headers, json=body)
    if not r.ok:
        message = ('ERROR: AIKO language detect did not answer. Response code: "{r.status_code}"; ' +
                   'Response body: "{}"').format(r.status_code, r.raw)
        raise SystemError(message)
    return r.json()['language']

def _get_endpoint(language: str) -> str:
    """
    There are 4 docker container listening to 4 different ports, one per language.
    This function returns the right port number for the input language.
    See the initialization script for more info.
    :param language:
    :return:
    """
    if language not in MODEL_PORTS:
        raise ValueError('unknown language: "{}"'.format(language))
    return NER_ENDPOINT_MOLD.format(MODEL_PORTS[language])

def _get_predictions(model_endpoint: str, input_text: str, use_gazetteers: bool = True):
    """
    Asks the container pointed by model_endpoint for predictions.
    :param model_endpoint:
    :param input_text:
    :param use_gazetteers:
    :return:
    """
    headers = {'Content-Type': 'application/json'}
    body = {
        'text': input_text
    }
    r = requests.post(model_endpoint, headers=headers, json=body)
    if not r.ok:
        message = 'Something went wrong: the docker container {} did not answer'.format(model_endpoint)
        raise SystemError(message)
    return r.json()

@ner_api.route('', methods=['POST'])
def submitNER():
    parameters = request.get_json(force=True)
    print("Demo NER:", parameters)
    txt = parameters['input']
    if request.method == 'POST':
        try:
            language = _get_language(txt)
            model_endpoint = _get_endpoint(language)
            annotations = _get_predictions(model_endpoint, txt, use_gazetteers=True)
            return jsonify(annotations)
        except Exception as e:
            print(e)


text:
package com.google.template.soy.msgs.restricted;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.Ascii;
import com.google.errorprone.annotations.Immutable;
import com.google.template.soy.msgs.SoyMsgException;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Objects;

/**
 * Represents a plural case value.
 *
 * <p>A plural case value can be either a number, or one of {@code ZERO}, {@code ONE}, {@code TWO},
 * {@code FEW}, {@code MANY} or {@code OTHER}. Here, a number is represented by the number {@code
 * explicitValue} with status set to EXPLICIT and the remaining by an enum value.
 *
 */
@Immutable
public final class SoyMsgPluralCaseSpec {

  /** The type. EXPLICIT indicating numeric, or one of the others indicating non-numeric. */
  public enum Type {
    EXPLICIT,
    ZERO,
    ONE,
    TWO,
    FEW,
    MANY,
    OTHER
  }

  /** Internal mapping of Type to String, reduces memory usage */
  private static final EnumMap<Type, String> TYPE_TO_STRING = new EnumMap<>(Type.class);

  static {
    for (Type t : EnumSet.allOf(Type.class)) {
      TYPE_TO_STRING.put(t, Ascii.toLowerCase(t.name()));
    }
  }

  /** ZERO, ONE, TWO, FEW, MANY or OTHER if the type is non-numeric, or EXPLICIT if numeric. */
  private final Type type;

  /** The numeric value if the type is numeric, -1 otherwise. */
  private final long explicitValue;

  /**
   * Constructs an object from a non-numeric value.
   *
   * @param typeStr String representation of the non-numeric value.
   * @throws IllegalArgumentException if typeStr (after converting to upper case) does not match
   *     with any of the enum types.
   */
  public SoyMsgPluralCaseSpec(String typeStr) {
    this(Type.valueOf(Ascii.toUpperCase(typeStr)));
  }

  /** Constructs an object from a non-numeric value. */
  public SoyMsgPluralCaseSpec(Type type) {
    this.type = checkNotNull(type);
    this.explicitValue = -1;
  }

  /**
   * Constructs an object from a numeric value. The field type is set to EXPLICIT, and explicitValue
   * is set to the numeric value given.
   *
   * @param explicitValue The numeric value.
   * @throws SoyMsgException if invalid numeric value.
   */
  public SoyMsgPluralCaseSpec(long explicitValue) {
    if (explicitValue >= 0) {
      type = Type.EXPLICIT;
      this.explicitValue = explicitValue;
    } else {
      throw new SoyMsgException("Negative plural case value.");
    }
  }

  /**
   * Get the type.
   *
   * @return The type. EXPLICIT if numeric.
   */
  public Type getType() {
    return type;
  }

  /**
   * Get the numeric value.
   *
   * @return if numeric, return the numeric value, else -1.
   */
  public long getExplicitValue() {
    return explicitValue;
  }

  @Override
  public String toString() {
    return (type == Type.EXPLICIT) ? "=" + explicitValue : TYPE_TO_STRING.get(type);
  }

  @Override
  public boolean equals(Object other) {
    if (!(other instanceof SoyMsgPluralCaseSpec)) {
      return false;
    }
    SoyMsgPluralCaseSpec otherSpec = (SoyMsgPluralCaseSpec) other;
    return type == otherSpec.type && explicitValue == otherSpec.explicitValue;
  }

  @Override
  public int hashCode() {
    return Objects.hash(SoyMsgPluralCaseSpec.class, type, explicitValue);
  }
}


text:
class Parents::NewslettersController < ApplicationController
  before_action :authenticate_user!

  def current
    @newest_newsletter = Newsletter.newest
  end

  def index
    @newsletters = Newsletter.for_current_school_year
  end

  def show
    @newsletter = Newsletter.find(params[:id])
  end
end


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _webpackLibSingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');

var _webpackLibSingleEntryPlugin2 = _interopRequireDefault(_webpackLibSingleEntryPlugin);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _webpack = require('webpack');

var _webpack2 = _interopRequireDefault(_webpack);

var _deepExtend = require('deep-extend');

var _deepExtend2 = _interopRequireDefault(_deepExtend);

var _es6Promise = require('es6-promise');

var _miscUtils = require('./misc/utils');

var ServiceWorker = (function () {
  function ServiceWorker(options) {
    _classCallCheck(this, ServiceWorker);

    this.entry = options.entry;
    this.output = options.output.replace(/^\//, '');
    this.basePath = (0, _miscUtils.pathToBase)(this.output, true);
    this.scope = options.scope ? options.scope + '' : void 0;
    this.events = !!options.events;
    this.navigateFallbackURL = options.navigateFallbackURL;

    this.ENTRY_NAME = 'serviceworker';
    this.CACHE_NAME = 'webpack-offline';
    this.SW_DATA_VAR = '__wpo';
  }

  _createClass(ServiceWorker, [{
    key: 'addEntry',
    value: function addEntry(plugin, compilation, compiler) {
      if (!this.entry) return _es6Promise.Promise.resolve();

      var name = plugin.entryPrefix + this.ENTRY_NAME;
      var childCompiler = compilation.createChildCompiler(name, {
        // filename: this.output
        filename: name
      });

      var data = JSON.stringify({
        data_var_name: this.SW_DATA_VAR
      });
      var loader = '!!' + _path2['default'].join(__dirname, 'misc/sw-loader.js') + '?' + data;
      var entry = loader + '!' + this.entry;

      childCompiler.context = compiler.context;
      childCompiler.apply(new _webpackLibSingleEntryPlugin2['default'](compiler.context, entry, name));

      (compiler.options.plugins || []).some(function (plugin) {
        if (plugin instanceof _webpack2['default'].optimize.UglifyJsPlugin) {
          var options = (0, _deepExtend2['default'])({}, plugin.options);

          options.test = new RegExp(name);
          childCompiler.apply(new _webpack2['default'].optimize.UglifyJsPlugin(options));

          return true;
        }
      });

      // Needed for HMR. offline-plugin doesn't support it,
      // but added just in case to prevent other errors
      childCompiler.plugin('compilation', function (compilation) {
        if (compilation.cache) {
          if (!compilation.cache[name]) {
            compilation.cache[name] = {};
          }

          compilation.cache = compilation.cache[name];
        }
      });

      return new _es6Promise.Promise(function (resolve, reject) {
        childCompiler.runAsChild(function (err, entries, childCompilation) {
          if (err) {
            reject(err);
            return;
          }

          resolve();
        });
      });
    }
  }, {
    key: 'apply',
    value: function apply(plugin, compilation, compiler) {
      var minify = (compiler.options.plugins || []).some(function (plugin) {
        return plugin instanceof _webpack2['default'].optimize.UglifyJsPlugin;
      });

      var source = this.getDataTemplate(plugin.caches, plugin, minify);

      if (this.entry) {
        var _name = plugin.entryPrefix + this.ENTRY_NAME;
        var asset = compilation.assets[_name];

        if (!asset) {
          compilation.errors.push(new Error('OfflinePlugin: ServiceWorker entry is not found in output assets'));

          return;
        }

        delete compilation.assets[_name];
        source += '\n\n' + asset.source();
      }

      compilation.assets[this.output] = (0, _miscUtils.getSource)(source);
    }
  }, {
    key: 'getDataTemplate',
    value: function getDataTemplate(data, plugin, minify) {
      var _this = this;

      var cache = function cache(key) {
        return (data[key] || []).map(_this.pathRewrite(plugin));
      };

      var hashesMap = Object.keys(plugin.hashesMap).reduce(function (result, hash) {
        var asset = plugin.hashesMap[hash];

        result[hash] = _this.pathRewrite(plugin)(asset);
        return result;
      }, {});

      return ('\n      var ' + this.SW_DATA_VAR + ' = ' + JSON.stringify({
        assets: {
          main: cache('main'),
          additional: cache('additional'),
          optional: cache('optional')
        },

        hashesMap: hashesMap,
        navigateFallbackURL: this.navigateFallbackURL,

        strategy: plugin.strategy,
        version: plugin.version,
        name: this.CACHE_NAME,
        relativePaths: plugin.relativePaths,
        alwaysRevalidate: plugin.alwaysRevalidate,
        preferOnline: plugin.preferOnline,
        ignoreSearch: plugin.ignoreSearch
      }, null, minify ? void 0 : '  ') + ';\n    ').trim();
    }
  }, {
    key: 'pathRewrite',
    value: function pathRewrite(plugin) {
      var _this2 = this;

      if (plugin.relativePaths) {
        return function (path) {
          return (0, _miscUtils.isAbsoluteURL)(path) ? path : _this2.basePath + path;
        };
      }

      return function (path) {
        return path;
      };
    }
  }, {
    key: 'getConfig',
    value: function getConfig(plugin) {
      return {
        output: plugin.publicPath + this.output,
        scope: this.scope,
        events: this.events
      };
    }
  }]);

  return ServiceWorker;
})();

exports['default'] = ServiceWorker;
module.exports = exports['default'];


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-history-of-pythagoras',
  templateUrl: './history-of-pythagoras.component.html',
  styleUrls: ['./history-of-pythagoras.component.scss']
})
export class HistoryOfPythagorasComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package saltr.exception;

public class SLTMissingFeaturesException extends SLTRuntimeException {
    public SLTMissingFeaturesException() {
        super("Features should be defined.");
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Macro BOOST_LOG_DECLARE_LOGGER</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="logging_sources.html#header.boost.log.sources.basic_logger_hpp" title="Header <boost/log/sources/basic_logger.hpp>">
<link rel="prev" href="BOOST_LOG_DECLARE_idm30101.html" title="Macro BOOST_LOG_DECLARE_LOGGER_TYPE">
<link rel="next" href="BOOST_LOG_DECLARE_idm30128.html" title="Macro BOOST_LOG_DECLARE_LOGGER_MT">

Macro BOOST_LOG_DECLARE_LOGGER

BOOST_LOG_DECLARE_LOGGER — The macro declares a narrow-char logger class that inherits a number of base classes.

Synopsis

// In header: <boost/log/sources/basic_logger.hpp>

BOOST_LOG_DECLARE_LOGGER(type_name, base_seq)

Description

Equivalent to BOOST_LOG_DECLARE_LOGGER_TYPE(type_name, char, base_seq, single_thread_model)

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

base_seq

A Boost.Preprocessor sequence of type identifiers of the base classes templates

type_name

The name of the logger class to declare

Copyright © 2007-2021 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: monguito-db.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: monguito-db.js

/**
 * Utility to perform CRUD operations over the localStorage, sessionStorage, or
 * any object implementing the Storage Interface defined by the W3C.<br><br>
 *
 * This library was inspired by MongoDB, and some of its functions are
 * syntactically similar to how they are in Mongo, with some differences
 * and limitations.<br><br>
 *
 * NOTE: This utility works synchronously.
 *
 * @example
 *    // An object to perform CRUD operations over the HTML5 localStorage.
 *    var db = new MonguitoDB(localStorage, "orders");
 *
 *    // An object to perform CRUD operations over the HTML5 sessionStorage.
 *    var db = new MonguitoDB(sessionStorage, ["orders", "users"]);
 *
 *    // An object to perform CRUD operations over collections stored in memory.
 *    var db = new MonguitoDB(null, ["orders", "users"]);
 *
 * @param {object|null} storage - Object providing the storage mechanism. You
 *    can send localStorage or sessionStorage if the browser supports HTML5.
 *    Send null to use the default mechanism which stores collections in memory.
 *    Alternatively, you can send your own object implementing the Storage
 *    Interface defined by the W3C.
 * @param {string|string[]} collections - Array containing the names of the
 *    collections to be manipulated (analogous to tables in a relational
 *    database). You can send a single name, or an array of names if you want
 *    to manipulate several collections.
 *
 * @see     http://www.w3.org/TR/webstorage/#the-storage-interface
 * @see     Collection
 * @author  Juan Cuartas
 * @version 0.0.1, Jun 2014
 *
 * @constructor
 */
exports.MonguitoDB = function(storage, collections) {
    util.validateArguments(arguments, 2, "MonguitoDB()");

    if (storage !== null && !util.isValidStorage(storage)) {
        throw new TypeError(
            "MonguitoDB(), invalid arg[0]:storage, expecting storage object."
        );
    }

    collections = [].concat(collections);

    if (!collections.length) {
        throw new TypeError(
            "MonguitoDB(), invalid arg[1]:collections, array can not be empty."
        );
    }

    for (var i = 0; i < collections.length; i++) {
        if (typeof collections[i] !== "string") {
            throw new TypeError(
                "MonguitoDB(), invalid arg[1]:collections, " +
                "expecting string or string[]."
            );
        }
    }

    for (i = 0; i < collections.length; i++) {
        if (!util.isValidVariableName(collections[i])) {
            throw new TypeError(
                "MonguitoDB(), invalid arg[1]:collections '" + collections[i] +
                "' is an invalid collection's name."
            );
        }
    }

    if (storage === null) {
        storage = new MemoryStorage();
    }

    for (i = 0; i < collections.length; i++) {
        if (!this[collections[i]]) {
            this[collections[i]] = new Collection(storage, collections[i]);
        }
    }
};

Index

Classes

Collection

Cursor

Document

MonguitoDB

    Documentation generated by JSDoc 3.2.2 on Thu May 14 2015 00:54:16 GMT-0500 (COT)


text:
package org.apache.activemq.artemis.jms.tests;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import java.io.Serializable;

import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport;
import org.junit.Test;

public class TopicTest extends JMSTestCase {
   // Constants -----------------------------------------------------

   // Static --------------------------------------------------------

   // Attributes ----------------------------------------------------

   // Constructors --------------------------------------------------

   // Public --------------------------------------------------------

   /**
    * The simplest possible topic test.
    */
   @Test
   public void testTopic() throws Exception {
      Connection conn = createConnection();

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer p = s.createProducer(ActiveMQServerTestCase.topic1);
      MessageConsumer c = s.createConsumer(ActiveMQServerTestCase.topic1);
      conn.start();

      p.send(s.createTextMessage("payload"));
      TextMessage m = (TextMessage) c.receive();

      ProxyAssertSupport.assertEquals("payload", m.getText());
   }

   @Test
   public void testTopic2() throws Exception {
      Connection conn = createConnection();

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer p = s.createProducer(ActiveMQServerTestCase.topic1);
      MessageConsumer c = s.createConsumer(ActiveMQServerTestCase.topic1);
      conn.start();

      p.send(s.createTextMessage("payload"));
      TextMessage m = (TextMessage) c.receive();

      ProxyAssertSupport.assertEquals("payload", m.getText());
   }

   @Test
   public void testTopicName() throws Exception {
      Topic topic = (Topic) ic.lookup("/topic/Topic1");
      ProxyAssertSupport.assertEquals("Topic1", topic.getTopicName());
   }

   /*
   * See http://jira.jboss.com/jira/browse/JBMESSAGING-399
   */
   @Test
   public void testRace() throws Exception {
      Connection conn = createConnection();

      Session sSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod = sSend.createProducer(ActiveMQServerTestCase.topic1);
      prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

      Session s1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session s2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session s3 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer c1 = s1.createConsumer(ActiveMQServerTestCase.topic1);
      MessageConsumer c2 = s2.createConsumer(ActiveMQServerTestCase.topic1);
      MessageConsumer c3 = s3.createConsumer(ActiveMQServerTestCase.topic1);

      final int numMessages = 500;

      TestListener l1 = new TestListener(numMessages);
      TestListener l2 = new TestListener(numMessages);
      TestListener l3 = new TestListener(numMessages);

      c1.setMessageListener(l1);
      c2.setMessageListener(l2);
      c3.setMessageListener(l3);

      conn.start();

      for (int i = 0; i < numMessages; i++) {
         byte[] blah = new byte[10000];
         String str = new String(blah);

         Wibble2 w = new Wibble2();
         w.s = str;
         ObjectMessage om = sSend.createObjectMessage(w);

         prod.send(om);
      }

      l1.waitForMessages();
      l2.waitForMessages();
      l3.waitForMessages();

      ProxyAssertSupport.assertFalse(l1.failed);
      ProxyAssertSupport.assertFalse(l2.failed);
      ProxyAssertSupport.assertFalse(l3.failed);
   }

   // Package protected ---------------------------------------------

   // Protected -----------------------------------------------------

   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------

   static class Wibble2 implements Serializable {

      private static final long serialVersionUID = -5146179676719808756L;

      String s;
   }

   static class TestListener implements MessageListener {

      boolean failed;

      int count;

      int num;

      TestListener(final int num) {
         this.num = num;
      }

      @Override
      public synchronized void onMessage(final Message m) {
         ObjectMessage om = (ObjectMessage) m;

         try {
            Wibble2 w = (Wibble2) om.getObject();
         }
         catch (Exception e) {
            failed = true;
         }

         count++;

         if (count == num) {
            notify();
         }
      }

      synchronized void waitForMessages() throws Exception {
         while (count < num) {
            this.wait();
         }
      }
   }

}


text:
Accompanying files to [my
talk](https://speakerdeck.com/frzng/what-is-wrong-with-js) about flaws
and shortcommings of JavaScript as a language and as a community.

## Description

*01* - Shows how bad, immaturiture and needless JavaScript
meta/reflection capabilities are.

It also shows original takes on defining getter which is not
sufficient due to other properties of the language but way simpler. To
me, it also shows why macros should among top priorities in language
developement.

*02* - Stupid example of [Sweeet.js](http://sweetjs.org)
macro. Originaly, I wanted to find a simple yet practical example from
[Clojure](http://clojure.org) and compare it with Sweet.js.

I actually think Sweet.js is nice, but the problem here is that even
though JavaScript is used to solve wide range of problems, the
community doesn't see that original syntax is very limiting in many
cases.

*03* - Comparison of ES6 generators with actor model from [IO
language](http://iolanguage.org). Honestly, it is not very comparable
because using actors lead to different design than use of coroutines.

One thing here is the syntax around generators which to me is
understable but still very unfortunate. `Yield` being a keyword and
that asterisc in generator definition are the worst I think.

[Koa](http://koajs.com) is a new take on the job commonly done by
[Connect](http://www.senchalabs.org/connect/) and
[Express.js](http://expressjs.com). The example code in IO is nearly
pseudo-code.

*04* - Asynchronicity has many faces even when you have only one
thread.


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using Windows.Data.Json;

namespace Json4Uwp
{
    [AttributeUsage(AttributeTargets.Property)]
    public class JSONKeyAttribute : Attribute
    {
        public JSONKeyAttribute(string name) { KeyName = name; }
        public string KeyName { get; set; }
    }

    [Flags]
    public enum StringifyOptions
    {
        None            = 0,
        LowerCamelCase  = 1,    // Convert the first letter of property name to lower case
    }

    public static class JSON
    {
        public static string Stringify(object value, StringifyOptions options = StringifyOptions.None)
        {
            if (value != null)
            {
                var buffer = new StringBuilder();
                GetSerializer(value.GetType())(buffer, value, options);
                return buffer.ToString();
            }
            return "null";
        }

        public static T Parse<T>(string json)
        {
            int index = 0;
            char nonSpace = '\0';
            foreach (var c in json)
            {
                if (!Char.IsWhiteSpace(c))
                {
                    nonSpace = c;
                    break;
                }
                ++index;
            }
            switch (nonSpace)
            {
                case '{':
                    return (T)CachedConverter<T>.Instance(JsonObject.Parse(json));
                case '[':
                    return (T)CachedConverter<T>.Instance(JsonArray.Parse(json));
                default:
                    return (T)CachedConverter<T>.Instance(JsonValue.Parse(json));
            }
        }

        public static bool TryParse<T>(string json, out T output)
        {
            output = default(T);
            try
            {
                output = Parse<T>(json);
                return true;
            }
            catch (Exception e)
            {
                Debug.Fail(e.Message);
            }
            return false;
        }

        #region Private Implementation: Serializer
        const string DATETIME_FORMAT = "yyyy-MM-ddTHH:mm:ss.fffZ";

        delegate void Serializer(StringBuilder output, object value, StringifyOptions options);

        static Serializer GetSerializer(Type type)
        {
            return (Serializer) typeof(CachedSerializer<>).MakeGenericType(type)
                    .GetField("Instance", BindingFlags.Static | BindingFlags.Public).GetValue(null);
        }

        static class CachedSerializer<T>
        {
            public static readonly Serializer Instance = GetSerializerForType(typeof(T));

            private static Serializer GetSerializerForType(Type type)
            {
                if (type == typeof(string))
                {
                    return WriteString;
                }
                var typeInfo = type.GetTypeInfo();
                if (!typeInfo.IsClass && !typeInfo.IsGenericType)
                {
                    if (type == typeof(bool))
                    {
                        return WriteBoolean;
                    }
                    if (typeInfo.IsPrimitive)
                    {
                        return WritePrimitive;
                    }
                    if (type == typeof(DateTimeOffset))
                    {
                        return WriteDateTimeOffset;
                    }
                    if (type == typeof(DateTime))
                    {
                        return WriteDateTime;
                    }
                }
                if (typeInfo.IsArray)
                {
                    return CreateArraySerializer(typeInfo);
                }
                if (typeof(IJsonValue).IsAssignableFrom(type))
                {
                    return WriteJsonValue;
                }
                // Dictionary detection should go before array
                if (typeof(IDictionary).IsAssignableFrom(type))
                {
                    return CreateMapSerializer(typeInfo);
                }
                if (typeof(IEnumerable).IsAssignableFrom(type))
                {
                    var dictType = IsGenericDictionary(typeInfo) ? typeInfo :
                        typeInfo.ImplementedInterfaces.FirstOrDefault(t => IsGenericDictionary(t.GetTypeInfo()))?.GetTypeInfo();
                    if (dictType != null)
                    {
                        var pairType = dictType.ImplementedInterfaces
                            .Select(t => t.GetTypeInfo())
                            .First(ti => ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                            .GenericTypeArguments[0].GetTypeInfo();
                        if (pairType.IsGenericType && pairType.GenericTypeArguments.Length >= 2)
                        {
                            return CreateGenericMapSerializer(pairType);
                        }
                    }
                    return CreateArraySerializer(typeInfo);
                }
                if (!typeInfo.IsAbstract && type != typeof(object))
                {
                    if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        return CreateNullableSerializer(typeInfo.GenericTypeArguments[0]);
                    }
                    return CreateObjectSerializer(type, typeInfo.IsSealed);
                }
                return WriteDynamicObject;
            }
        }

        static bool IsGenericDictionary(TypeInfo ti)
        {
            if (!ti.IsGenericType)
                return false;
            var td = ti.GetGenericTypeDefinition();
            return td == typeof(IDictionary<,>) || td == typeof(IReadOnlyDictionary<,>);
        }

        static void WriteString(StringBuilder output, object value, StringifyOptions options)
        {
            if (value == null)
                output.Append("null");
            else
                DoWriteString(output, (string)value);
        }

        static void DoWriteString(StringBuilder output, string str)
        {
            output.EnsureCapacity(output.Length + str.Length + 2);
            output.Append('"');
            foreach (char c in str)
            {
                switch (c)
                {
                    case '"': output.Append("\\\""); break;
                    case '\\': output.Append("\\\\"); break;
                    case '\b': output.Append("\\b"); break;
                    case '\f': output.Append("\\f"); break;
                    case '\n': output.Append("\\n"); break;
                    case '\r': output.Append("\\r"); break;
                    case '\t': output.Append("\\t"); break;
                    default:
                        if (c < 0x20)
                            output.Append("\\u00").Append(((int)c).ToString("x2"));
                        else if (c < 0x7f || c >= 0xa0)
                            output.Append(c);
                        break;
                }
            }
            output.Append('"');
        }

        static void WriteJsonValue(StringBuilder output, object value, StringifyOptions options)
        {
            output.Append(((IJsonValue)value).Stringify());
        }

        static void WriteBoolean(StringBuilder output, object value, StringifyOptions options)
        {
            output.Append((bool)value ? "true" : "false");
        }
        static void WritePrimitive(StringBuilder output, object value, StringifyOptions options)
        {
            output.Append(Convert.ToString(value, CultureInfo.InvariantCulture));
        }
        static void WriteDateTimeOffset(StringBuilder output, object value, StringifyOptions options)
        {
            output.Append('"')
                .Append(((DateTimeOffset)value).ToUniversalTime().ToString(DATETIME_FORMAT, CultureInfo.InvariantCulture))
                .Append('"');
        }
        static void WriteDateTime(StringBuilder output, object value, StringifyOptions options)
        {
            output.Append(((DateTime)value).ToUniversalTime().ToString(DATETIME_FORMAT, CultureInfo.InvariantCulture));
        }

        static Serializer CreateArraySerializer(TypeInfo typeInfo)
        {
            Type itemType;
            if (typeInfo.HasElementType)
                itemType = typeInfo.GetElementType();
            else if (typeInfo.IsGenericType && typeInfo.GenericTypeArguments.Length > 0)
                itemType = typeInfo.GenericTypeArguments[0];
            else
                itemType = null;

            if (itemType != null && itemType != typeof(object) && !itemType.GetTypeInfo().IsAbstract)
            {
                var itemSerializer = GetSerializer(itemType);
                return new ArrayWriteHelper((output, value, options) =>
                {
                    if (itemSerializer == null) // in case of recursion
                        itemSerializer = GetSerializer(itemType);
                    foreach (var item in (IEnumerable)value)
                    {
                        itemSerializer(output, item, options);
                        output.Append(',');
                    }
                }).Serializer;
            }
            return new ArrayWriteHelper((output, value, options) =>
            {
                foreach (var item in (IEnumerable)value)
                {
                    if (item == null)
                        output.Append("null");
                    else
                        GetSerializer(item.GetType())(output, item, options);
                    output.Append(',');
                }
            }).Serializer;
        }

        class ArrayWriteHelper
        {
            Serializer WriteContent;
            public ArrayWriteHelper(Serializer contentWriter) { WriteContent = contentWriter; }

            public void Serializer(StringBuilder output, object value, StringifyOptions options)
            {
                if (value == null)
                {
                    output.Append("null");
                }
                else
                {
                    output.Append('[');
                    int oldLength = output.Length;
                    WriteContent(output, value, options);
                    int newLength = output.Length;
                    if (oldLength != newLength)
                        output[newLength - 1] = ']';
                    else
                        output.Append(']');
                }
            }
        }

        static Serializer CreateMapSerializer(TypeInfo typeInfo)
        {
            if (typeInfo.IsGenericType && typeInfo.GenericTypeArguments.Length >= 2)
            {
                var valueType = typeInfo.GenericTypeArguments[1];
                if (valueType != typeof(object) && !valueType.GetTypeInfo().IsAbstract)
                {
                    var valueSerializer = GetSerializer(valueType);
                    return new MapWriteHelper((output, value, options) =>
                    {
                        if (valueSerializer == null) // in case of recursion
                            valueSerializer = GetSerializer(valueType);
                        foreach (DictionaryEntry item in (IDictionary)value)
                        {
                            DoWriteString(output, item.Key.ToString());
                            output.Append(':');
                            valueSerializer(output, item.Value, options);
                            output.Append(',');
                        }
                    }).Serializer;
                }
            }
            return new MapWriteHelper((output, value, options) =>
            {
                foreach (DictionaryEntry item in (IDictionary)value)
                {
                    DoWriteString(output, item.Key.ToString());
                    output.Append(':');
                    if (item.Value == null)
                        output.Append("null");
                    else
                        GetSerializer(item.Value.GetType())(output, item.Value, options);
                    output.Append(',');
                }
            }).Serializer;
        }

        static Serializer CreateGenericMapSerializer(TypeInfo pairType)
        {
            var keyProperty = pairType.GetDeclaredProperty("Key");
            var valueProperty = pairType.GetDeclaredProperty("Value");
            var valueType = pairType.GenericTypeArguments[1];
            var valueSerializer = GetSerializer(valueType);
            return new MapWriteHelper((output, value, options) =>
            {
                if (valueSerializer == null) // in case of recursion
                    valueSerializer = GetSerializer(valueType);
                foreach (var item in (IEnumerable)value)
                {
                    DoWriteString(output, keyProperty.GetValue(item).ToString());
                    output.Append(':');
                    valueSerializer(output, valueProperty.GetValue(item), options);
                    output.Append(',');
                }
            }).Serializer;
        }

        class MapWriteHelper
        {
            Serializer WriteContent;
            public MapWriteHelper(Serializer contentWriter) { WriteContent = contentWriter; }

            public void Serializer(StringBuilder output, object value, StringifyOptions options)
            {
                if (value == null)
                {
                    output.Append("null");
                }
                else
                {
                    output.Append('{');
                    int oldLength = output.Length;
                    WriteContent(output, value, options);
                    int newLength = output.Length;
                    if (oldLength != newLength)
                        output[newLength - 1] = '}';
                    else
                        output.Append('}');
                }
            }
        }

        static Serializer CreateNullableSerializer(Type innerType)
        {
            var innerSer = GetSerializer(innerType);
            return (output, value, options) =>
            {
                if (value == null)
                {
                    output.Append("null");
                }
                else
                {
                    if (innerSer == null) // in case of recursion
                        innerSer = GetSerializer(innerType);
                    innerSer(output, value, options);
                }
            };
        }

        static Serializer CreateObjectSerializer(Type type, bool sealedType)
        {
            var props = GetPropertySerializers(type);
            return (output, value, options) => {
                if (value == null)
                {
                    output.Append("null");
                }
                else
                {
                    if (sealedType || value.GetType() == type)
                    {
                        DoWriteObject(output, value, props, options);
                    }
                    else
                    {
                        DoWriteObject(output, value, GetPropertySerializers(value.GetType()), options);
                    }
                }
            };
        }

        static void DoWriteObject(StringBuilder output, object obj, PropertySerializer[] props, StringifyOptions options)
        {
            if (props.Length > 0)
            {
                output.Append('{');
                foreach (var entry in props)
                {
                    DoWriteString(output, (options & StringifyOptions.LowerCamelCase) != 0 ? ToLowerCamelCase(entry.Key) : entry.Key);
                    output.Append(':');
                    entry.WriteValue(output, obj, options);
                    output.Append(',');
                }
                output[output.Length - 1] = '}';
            }
            else
            {
                output.Append("{}");
            }
        }

        static string ToLowerCamelCase(string name)
        {
            if (name.Length > 0 && Char.IsUpper(name[0]))
            {
                return Char.ToLower(name[0]) + name.Substring(1);
            }
            return name;
        }

        static void WriteDynamicObject(StringBuilder output, object value, StringifyOptions options)
        {
            if (value == null)
            {
                output.Append("null");
            }
            else
            {
                var realType = value.GetType();
                if (realType != typeof(object))
                    GetSerializer(realType)(output, value, options);
                else
                    output.Append("{}");
            }
        }

        class PropertySerializer
        {
            public string Key;
            public Serializer WriteValue;
        }
        static PropertySerializer[] GetPropertySerializers(Type type)
        {
            var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var result = new PropertySerializer[props.Length];
            for (int i = 0, length = props.Length; i < length; ++i)
            {
                var prop = props[i];
                var attr = prop.GetCustomAttribute<JSONKeyAttribute>(true);
                var key = attr != null ? attr.KeyName : prop.Name;
                var writer = GetSerializer(prop.PropertyType);
                if (writer != null)
                {
                    result[i] = new PropertySerializer
                    {
                        Key = key,
                        WriteValue = (output, value, options) => writer(output, prop.GetValue(value), options)
                    };
                }
                else // happens when the type definition has recursion
                {
                    var propSer = result[i] = new PropertySerializer();
                    propSer.Key = key;
                    propSer.WriteValue = (output, value, options) =>
                    {
                        var newWriter = GetSerializer(prop.PropertyType);
                        newWriter(output, prop.GetValue(value), options);
                        propSer.WriteValue = (output2, value2, options2) => newWriter(output2, prop.GetValue(value2), options2);
                    };
                }
            }
            return result;
        }

        #endregion

        #region Private Implementation - Deserializer

        delegate object JConverter(IJsonValue input);

        static JConverter GetConverter(Type type)
        {
            return (JConverter) typeof(CachedConverter<>).MakeGenericType(type)
                .GetField("Instance", BindingFlags.Static | BindingFlags.Public).GetValue(null);
        }

        static class CachedConverter<T>
        {
            public static readonly JConverter Instance = GetConverterForType(typeof(T));

            private static JConverter GetConverterForType(Type type)
            {
                if (type == typeof(string))
                {
                    return ConvertToString;
                }
                var typeInfo = type.GetTypeInfo();
                if (!typeInfo.IsClass && !typeInfo.IsGenericType)
                {
                    if (typeInfo.IsPrimitive)
                    {
                        return primitiveConverters[type];
                    }
                    if (type == typeof(DateTimeOffset))
                    {
                        return ConvertToDateTimeOffset;
                    }
                    if (type == typeof(DateTime))
                    {
                        return ConvertToDateTime;
                    }
                }
                if (type.IsArray)
                {
                    return CreateArrayConverter(type);
                }
                if (typeof(IJsonValue).IsAssignableFrom(type))
                {
                    return NoConvertion;
                }
                if (typeof(IDictionary).IsAssignableFrom(type))    // this has to go BEFORE IEnumerable
                {
                    return CreateMapConverter(type, typeInfo);
                }
                var dictType = typeInfo.ImplementedInterfaces
                    .Select(t => t.GetTypeInfo())
                    .FirstOrDefault(ti => ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(IDictionary<,>));
                if (dictType != null)
                {
                    var colType = dictType.ImplementedInterfaces.First(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>));
                    return CreateGenericMapConverter(type, colType);
                }
                if (typeof(IEnumerable).IsAssignableFrom(type))
                {
                    var colType = typeInfo.ImplementedInterfaces.First(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>));
                    if (colType != null)
                    {
                        return CreateListConverter(type, colType);
                    }
                }
                else if (!typeInfo.IsAbstract && type != typeof(object))
                {
                    if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        return CreateNullableConverter(typeInfo.GenericTypeArguments[0]);
                    }
                    return CreateObjectConverter(type);
                }
                return ToObject;
            }
        }

        static readonly Dictionary<Type, JConverter> primitiveConverters = new Dictionary<Type, JConverter>
        {
            { typeof(bool),   (value) => value.GetBoolean() },
            { typeof(char),   (value) => (char)value.GetNumber() },
            { typeof(sbyte),  (value) => (sbyte)value.GetNumber() },
            { typeof(byte),   (value) => (byte)value.GetNumber() },
            { typeof(short),  (value) => (short)value.GetNumber() },
            { typeof(ushort), (value) => (ushort)value.GetNumber() },
            { typeof(int),    (value) => (int)value.GetNumber() },
            { typeof(uint),   (value) => (uint)value.GetNumber() },
            { typeof(long),   (value) => (long)value.GetNumber() },
            { typeof(ulong),  (value) => (ulong)value.GetNumber() },
            { typeof(float),  (value) => (float)value.GetNumber() },
            { typeof(double), (value) => value.GetNumber() },
        };

        static object ConvertToString(IJsonValue input)
        {
            return input.ValueType == JsonValueType.Null ? null : input.GetString();
        }
        static object ConvertToDateTimeOffset(IJsonValue input)
        {
            return input.ValueType == JsonValueType.Null ? DateTimeOffset.MinValue : DateTimeOffset.Parse(input.GetString());
        }
        static object ConvertToDateTime(IJsonValue input)
        {
            return input.ValueType == JsonValueType.Null ? DateTime.MinValue : DateTime.Parse(input.GetString());
        }

        static JConverter CreateArrayConverter(Type arrType)
        {
            var itemType = arrType.GetElementType();
            var itemConverter = GetConverter(itemType);
            return (value) =>
            {
                if (value.ValueType == JsonValueType.Null)
                    return null;
                if (itemConverter == null) // in case of recursion
                    itemConverter = GetConverter(itemType);
                var jarr = value.GetArray();
                int length = jarr.Count;
                var array = Array.CreateInstance(itemType, length);
                for (int i = 0; i < length; ++i)
                    array.SetValue(itemConverter(jarr[i]), i);
                return array;
            };
        }

        static JConverter CreateListConverter(Type listType, Type colType)
        {
            var itemType = colType.GenericTypeArguments[0];
            var addMethod = colType.GetMethod("Add", new[] { itemType });
            var itemConverter = GetConverter(itemType);
            return (value) =>
            {
                if (value.ValueType == JsonValueType.Null)
                    return null;
                if (itemConverter == null) // in case of recursion
                    itemConverter = GetConverter(itemType);
                var jarr = value.GetArray();
                int length = jarr.Count;
                var list = Activator.CreateInstance(listType);
                foreach (var item in jarr)
                    addMethod.Invoke(list, new[] { itemConverter(item) });
                return list;
            };
        }

        static JConverter CreateMapConverter(Type mapType, TypeInfo mapTypeInfo)
        {
            if (mapTypeInfo.IsGenericType && mapTypeInfo.GenericTypeArguments.Length >= 2)
            {
                var valueType = mapTypeInfo.GenericTypeArguments[1];
                var valueConverter = GetConverter(valueType);
                return (value) =>
                {
                    if (value.ValueType == JsonValueType.Null)
                        return null;
                    if (valueConverter == null) // in case of recursion
                        valueConverter = GetConverter(valueType);
                    var jobject = value.GetObject();
                    IDictionary map = (IDictionary)Activator.CreateInstance(mapType);
                    foreach (var item in jobject)
                        map.Add(item.Key, valueConverter(item.Value));
                    return map;
                };
            }
            else
            {
                return (value) =>
                {
                    if (value.ValueType == JsonValueType.Null)
                        return null;
                    var jobject = value.GetObject();
                    IDictionary map = (IDictionary)Activator.CreateInstance(mapType);
                    foreach (var item in jobject)
                        map.Add(item.Key, item.Value);
                    return map;
                };
            }
        }

        static JConverter CreateGenericMapConverter(Type mapType, Type colType)
        {
            var pairType = colType.GenericTypeArguments[0];
            var addMethod = colType.GetMethod("Add", new[] { pairType });
            var pairTypeInfo = pairType.GetTypeInfo();
            if (pairTypeInfo.IsGenericType && pairTypeInfo.GenericTypeArguments.Length >= 2)
            {
                var constor = pairType.GetConstructor(pairTypeInfo.GenericTypeArguments);
                var valueType = pairTypeInfo.GenericTypeArguments[1];
                var valueConverter = GetConverter(valueType);
                return (value) =>
                {
                    if (value.ValueType == JsonValueType.Null)
                        return null;
                    if (valueConverter == null) // in case of recursion
                        valueConverter = GetConverter(valueType);
                    var jobject = value.GetObject();
                    var map = Activator.CreateInstance(mapType);
                    foreach (var item in jobject)
                    {
                        var pair = constor.Invoke(new object[] { item.Key, valueConverter(item.Value) });
                        addMethod.Invoke(map, new[] { pair });
                    }
                    return map;
                };
            }
            else
            {
                var keyProperty = pairTypeInfo.GetDeclaredProperty("Key");
                var valueProperty = pairTypeInfo.GetDeclaredProperty("Value");
                return (value) =>
                {
                    if (value.ValueType == JsonValueType.Null)
                        return null;
                    var jobject = value.GetObject();
                    var map = Activator.CreateInstance(mapType);
                    foreach (var item in jobject)
                    {
                        var pair = Activator.CreateInstance(pairType);
                        keyProperty.SetValue(pair, item.Key);
                        valueProperty.SetValue(pair, item.Value);
                        addMethod.Invoke(map, new[] { pair });
                    }
                    return map;
                };
            }
        }

        static JConverter CreateNullableConverter(Type innerType)
        {
            var conv = GetConverter(innerType);
            return (value) =>
            {
                if (value.ValueType == JsonValueType.Null)
                    return null;
                if (conv == null) // in case of recursion
                    conv = GetConverter(innerType);
                return conv(value);
            };
        }

        static JConverter CreateObjectConverter(Type type)
        {
            var props = GetPropertyConverters(type);
            return (value) =>
            {
                if (value.ValueType == JsonValueType.Null)
                    return null;
                var jobj = value.GetObject();
                var obj = Activator.CreateInstance(type);
                IJsonValue propVal;
                foreach (var prop in props)
                {
                    if (jobj.TryGetValue(prop.Key, out propVal))
                        prop.SetProperty(propVal, obj);
                    else if (prop.TryLower && jobj.TryGetValue(Char.ToLower(prop.Key[0]) + prop.Key.Substring(1), out propVal))
                        prop.SetProperty(propVal, obj);
                }
                return obj;
            };
        }

        static object NoConvertion(IJsonValue input)
        {
            return input;
        }

        static object ToObject(IJsonValue input)
        {
            return input.ValueType == JsonValueType.Null ? null : input;
        }

        delegate void PropertySetter(IJsonValue value, object obj);
        class PropertyConverter
        {
            public string Key;
            public bool TryLower;
            public PropertySetter SetProperty;
        }
        static PropertyConverter[] GetPropertyConverters(Type type)
        {
            var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var result = new PropertyConverter[props.Length];
            for (int i = 0, length = props.Length; i < length; ++i)
            {
                var prop = props[i];
                var attr = prop.GetCustomAttribute<JSONKeyAttribute>(true);
                var key = attr != null ? attr.KeyName : prop.Name;
                var conv = GetConverter(prop.PropertyType);
                if (conv != null)
                {
                    result[i] = new PropertyConverter
                    {
                        Key = key,
                        TryLower = attr == null && Char.IsUpper(key[0]),
                        SetProperty = (value, obj) => prop.SetValue(obj, conv(value))
                    };
                }
                else // happens when the type definition has recursion
                {
                    var propConv = result[i] = new PropertyConverter();
                    propConv.Key = key;
                    propConv.TryLower = attr == null && Char.IsUpper(key[0]);
                    propConv.SetProperty = (value, obj) =>
                    {
                        var newConv = GetConverter(prop.PropertyType);
                        prop.SetValue(obj, newConv(value));
                        propConv.SetProperty = (value2, obj2) => prop.SetValue(obj2, newConv(value2));
                    };
                }
            }
            return result;
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>parent</artifactId>
        <groupId>com.github.dactiv.universe</groupId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>session-manager</artifactId>
    <packaging>jar</packaging>
    <name>session-manager</name>
    <description>session manager framework</description>
    <url>https://github.com/dactiv/universe</url>

    <dependencies>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>

        <!-- test begin -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>biz.paluch.redis</groupId>
            <artifactId>lettuce</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>

        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>

        </plugins>

    </build>

</project>


text:
appbone [![Build Status](https://travis-ci.org/appbone/appbone.svg)](https://travis-ci.org/appbone/appbone)
=======

App骨架