text:
function highlight(words, wordNum) {
	$('#lyrics').html("");
	var el = $('');
	var text = '';
	for (var i=0; i < wordNum; i++){
		text += words[i] + " ";
	}
	console.log("text", text);
	el.html(text);
	$('#lyrics').append(el);

	$('#lyrics').append($(''+words[wordNum]+''));

	el = $('');
	text = '';
	for (var i=wordNum+1; i < words.length; i++) {
		text += " " + words[i];

	}
	el.html(text);
	$('#lyrics').append(el);
}

var globalTimes = [];
var globalCount = -1;

function saveTime(word) {
	globalTimes.push({word: word , time: (new Date()).getTime()});
};

function getPauseTimes(times) {
    var ret = [];

    ret.push({time: 0, word: times[0].word});
	for (var i = 1; i < times.length; i++) {
        ret.push({time: times[i].time - times[i - 1].time, word: times[i].word});
	}
    return ret;
}

function timeString(times) {
    times = getPauseTimes(times);
	var ret = '';
	for (var i = 0; i < times.length; i++) {
		ret += times[i].word + ': ' + times[i].time + '\n';
	}
	return ret;
}

//need to set time being passed into setInterval
function demoHighlight(words, times, count) {
    if (count >= times.length) {
        return;
    }
    console.log('timeout', times[count].time, 'count', count);
	 setTimeout(function() {
	 	highlight(words, count);
        count = count + 1;
	 	demoHighlight(words, times, count);
	 }, times[count].time);
}

//make array 2D to account for line breaks

$(function() {

	var lyrics = $('#lyrics');
	var words = lyrics.html().split(" ").filter(function(x) {return x != ''}); //array of words

	console.log(words);

	var timestamps;
	var counter = 0;

	console.log('hello');

	$("#play").click(function() {
        demoHighlight(words, getPauseTimes(globalTimes), 0);
	});

	$(document).keypress(function(e) {
		globalCount = globalCount + 1;
		if (globalCount >= words.length) {
			return;
		}

		highlight(words, globalCount);
		saveTime(words[globalCount]);
		$('#times').html(timeString(globalTimes));
	});
});


text:
import assert from 'assert'
import sinon from 'sinon'
import { handle } from 'api/collectMetricsData'
import { Metric } from 'model/metrics'
import { MetricsStoreProxy } from 'api/utils'

describe('collectMetricsData', () => {
  let shouldAdminPostDatapointsMock
  beforeEach(() => {
    shouldAdminPostDatapointsMock = sinon.stub(MockService.prototype, 'shouldAdminPostDatapoints').returns(false)
  })

  afterEach(() => {
    MetricsStoreProxy.prototype.query.restore()
    Metric.prototype.collect.restore()
    MockService.prototype.shouldAdminPostDatapoints.restore()
  })

  it('should collect the new data for each metric', async () => {
    const metrics = [new Metric({metricID: '1', type: 'Mock'}), new Metric({metricID: '2', type: 'Mock'})]
    sinon.stub(MetricsStoreProxy.prototype, 'query').returns(metrics)
    const stub = sinon.stub(Metric.prototype, 'collect').returns()

    await handle({}, null, (error, result) => {
      assert(error === null)
      assert(stub.callCount === metrics.length)
    })
  })

  it('should resolve all promises', async () => {
    const metrics = [new Metric({metricID: '1', type: 'Mock'}), new Metric({metricID: '2', type: 'Mock'})]
    sinon.stub(MetricsStoreProxy.prototype, 'query').returns(metrics)
    let numResolved = 0
    const stub = sinon.stub(Metric.prototype, 'collect')
    stub.onFirstCall().returns(new Promise(resolve => {
      numResolved++
      resolve()
    })).onSecondCall().returns(new Promise(resolve => {
      numResolved++
      resolve()
    }))

    await handle({}, null, (error, result) => {
      assert(error === null)
      assert(stub.callCount === metrics.length)
      assert(numResolved === metrics.length)
    })
  })

  it('should not collect the new data if the admin should post datapoints ', async () => {
    shouldAdminPostDatapointsMock.returns(true)
    sinon.stub(MetricsStoreProxy.prototype, 'query').returns([new Metric({metricID: '1', type: 'Mock'})])
    const stub = sinon.stub(Metric.prototype, 'collect').returns()

    await handle({}, null, (error, result) => {
      assert(error === null)
      assert(stub.notCalled)
    })
  })

  it('should return error if the promise is rejected', async () => {
    const metrics = [new Metric({metricID: '1', type: 'Mock'}), new Metric({metricID: '2', type: 'Mock'})]
    sinon.stub(MetricsStoreProxy.prototype, 'query').returns(metrics)
    sinon.stub(Metric.prototype, 'collect').returns(new Promise((resolve, reject) => {
      reject(new Error())
    }))

    return await handle({}, null, (error, result) => {
      assert(error.match(/Error/))
    })
  })

  it('should return error on exception thrown', async () => {
    sinon.stub(MetricsStoreProxy.prototype, 'query').throws()
    sinon.stub(Metric.prototype, 'collect').throws()

    return await handle({}, null, (error, result) => {
      assert(error.match(/Error/))
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/TrafficType.h>
#include <aws/ec2/model/LogDestinationType.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/Tag.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes a flow log.

See Also:
   AWS API
   * Reference

   */
  class AWS_EC2_API FlowLog
  {
  public:
    FlowLog();
    FlowLog(const Aws::Utils::Xml::XmlNode& xmlNode);
    FlowLog& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The date and time the flow log was created.

     */
    inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; }

    /**
     *
The date and time the flow log was created.

     */
    inline bool CreationTimeHasBeenSet() const { return m_creationTimeHasBeenSet; }

    /**
     *
The date and time the flow log was created.

     */
    inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; }

    /**
     *
The date and time the flow log was created.

     */
    inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); }

    /**
     *
The date and time the flow log was created.

     */
    inline FlowLog& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;}

    /**
     *
The date and time the flow log was created.

     */
    inline FlowLog& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;}

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline const Aws::String& GetDeliverLogsErrorMessage() const{ return m_deliverLogsErrorMessage; }

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline bool DeliverLogsErrorMessageHasBeenSet() const { return m_deliverLogsErrorMessageHasBeenSet; }

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline void SetDeliverLogsErrorMessage(const Aws::String& value) { m_deliverLogsErrorMessageHasBeenSet = true; m_deliverLogsErrorMessage = value; }

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline void SetDeliverLogsErrorMessage(Aws::String&& value) { m_deliverLogsErrorMessageHasBeenSet = true; m_deliverLogsErrorMessage = std::move(value); }

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline void SetDeliverLogsErrorMessage(const char* value) { m_deliverLogsErrorMessageHasBeenSet = true; m_deliverLogsErrorMessage.assign(value); }

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline FlowLog& WithDeliverLogsErrorMessage(const Aws::String& value) { SetDeliverLogsErrorMessage(value); return *this;}

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline FlowLog& WithDeliverLogsErrorMessage(Aws::String&& value) { SetDeliverLogsErrorMessage(std::move(value)); return *this;}

    /**
     *
Information about the error that occurred. Rate limited
     * indicates that CloudWatch Logs throttling has been applied for one or more
     * network interfaces, or that you've reached the limit on the number of log groups
     * that you can create. Access error indicates that the IAM role
     * associated with the flow log does not have sufficient permissions to publish to
     * CloudWatch Logs. Unknown error indicates an internal error.

     */
    inline FlowLog& WithDeliverLogsErrorMessage(const char* value) { SetDeliverLogsErrorMessage(value); return *this;}

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline const Aws::String& GetDeliverLogsPermissionArn() const{ return m_deliverLogsPermissionArn; }

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline bool DeliverLogsPermissionArnHasBeenSet() const { return m_deliverLogsPermissionArnHasBeenSet; }

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline void SetDeliverLogsPermissionArn(const Aws::String& value) { m_deliverLogsPermissionArnHasBeenSet = true; m_deliverLogsPermissionArn = value; }

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline void SetDeliverLogsPermissionArn(Aws::String&& value) { m_deliverLogsPermissionArnHasBeenSet = true; m_deliverLogsPermissionArn = std::move(value); }

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline void SetDeliverLogsPermissionArn(const char* value) { m_deliverLogsPermissionArnHasBeenSet = true; m_deliverLogsPermissionArn.assign(value); }

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline FlowLog& WithDeliverLogsPermissionArn(const Aws::String& value) { SetDeliverLogsPermissionArn(value); return *this;}

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline FlowLog& WithDeliverLogsPermissionArn(Aws::String&& value) { SetDeliverLogsPermissionArn(std::move(value)); return *this;}

    /**
     *
The ARN of the IAM role that posts logs to CloudWatch Logs.

     */
    inline FlowLog& WithDeliverLogsPermissionArn(const char* value) { SetDeliverLogsPermissionArn(value); return *this;}

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline const Aws::String& GetDeliverLogsStatus() const{ return m_deliverLogsStatus; }

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline bool DeliverLogsStatusHasBeenSet() const { return m_deliverLogsStatusHasBeenSet; }

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline void SetDeliverLogsStatus(const Aws::String& value) { m_deliverLogsStatusHasBeenSet = true; m_deliverLogsStatus = value; }

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline void SetDeliverLogsStatus(Aws::String&& value) { m_deliverLogsStatusHasBeenSet = true; m_deliverLogsStatus = std::move(value); }

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline void SetDeliverLogsStatus(const char* value) { m_deliverLogsStatusHasBeenSet = true; m_deliverLogsStatus.assign(value); }

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline FlowLog& WithDeliverLogsStatus(const Aws::String& value) { SetDeliverLogsStatus(value); return *this;}

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline FlowLog& WithDeliverLogsStatus(Aws::String&& value) { SetDeliverLogsStatus(std::move(value)); return *this;}

    /**
     *
The status of the logs delivery (SUCCESS |
     * FAILED).

     */
    inline FlowLog& WithDeliverLogsStatus(const char* value) { SetDeliverLogsStatus(value); return *this;}

    /**
     *
The flow log ID.

     */
    inline const Aws::String& GetFlowLogId() const{ return m_flowLogId; }

    /**
     *
The flow log ID.

     */
    inline bool FlowLogIdHasBeenSet() const { return m_flowLogIdHasBeenSet; }

    /**
     *
The flow log ID.

     */
    inline void SetFlowLogId(const Aws::String& value) { m_flowLogIdHasBeenSet = true; m_flowLogId = value; }

    /**
     *
The flow log ID.

     */
    inline void SetFlowLogId(Aws::String&& value) { m_flowLogIdHasBeenSet = true; m_flowLogId = std::move(value); }

    /**
     *
The flow log ID.

     */
    inline void SetFlowLogId(const char* value) { m_flowLogIdHasBeenSet = true; m_flowLogId.assign(value); }

    /**
     *
The flow log ID.

     */
    inline FlowLog& WithFlowLogId(const Aws::String& value) { SetFlowLogId(value); return *this;}

    /**
     *
The flow log ID.

     */
    inline FlowLog& WithFlowLogId(Aws::String&& value) { SetFlowLogId(std::move(value)); return *this;}

    /**
     *
The flow log ID.

     */
    inline FlowLog& WithFlowLogId(const char* value) { SetFlowLogId(value); return *this;}

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline const Aws::String& GetFlowLogStatus() const{ return m_flowLogStatus; }

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline bool FlowLogStatusHasBeenSet() const { return m_flowLogStatusHasBeenSet; }

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline void SetFlowLogStatus(const Aws::String& value) { m_flowLogStatusHasBeenSet = true; m_flowLogStatus = value; }

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline void SetFlowLogStatus(Aws::String&& value) { m_flowLogStatusHasBeenSet = true; m_flowLogStatus = std::move(value); }

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline void SetFlowLogStatus(const char* value) { m_flowLogStatusHasBeenSet = true; m_flowLogStatus.assign(value); }

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline FlowLog& WithFlowLogStatus(const Aws::String& value) { SetFlowLogStatus(value); return *this;}

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline FlowLog& WithFlowLogStatus(Aws::String&& value) { SetFlowLogStatus(std::move(value)); return *this;}

    /**
     *
The status of the flow log (ACTIVE).

     */
    inline FlowLog& WithFlowLogStatus(const char* value) { SetFlowLogStatus(value); return *this;}

    /**
     *
The name of the flow log group.

     */
    inline const Aws::String& GetLogGroupName() const{ return m_logGroupName; }

    /**
     *
The name of the flow log group.

     */
    inline bool LogGroupNameHasBeenSet() const { return m_logGroupNameHasBeenSet; }

    /**
     *
The name of the flow log group.

     */
    inline void SetLogGroupName(const Aws::String& value) { m_logGroupNameHasBeenSet = true; m_logGroupName = value; }

    /**
     *
The name of the flow log group.

     */
    inline void SetLogGroupName(Aws::String&& value) { m_logGroupNameHasBeenSet = true; m_logGroupName = std::move(value); }

    /**
     *
The name of the flow log group.

     */
    inline void SetLogGroupName(const char* value) { m_logGroupNameHasBeenSet = true; m_logGroupName.assign(value); }

    /**
     *
The name of the flow log group.

     */
    inline FlowLog& WithLogGroupName(const Aws::String& value) { SetLogGroupName(value); return *this;}

    /**
     *
The name of the flow log group.

     */
    inline FlowLog& WithLogGroupName(Aws::String&& value) { SetLogGroupName(std::move(value)); return *this;}

    /**
     *
The name of the flow log group.

     */
    inline FlowLog& WithLogGroupName(const char* value) { SetLogGroupName(value); return *this;}

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline const Aws::String& GetResourceId() const{ return m_resourceId; }

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline bool ResourceIdHasBeenSet() const { return m_resourceIdHasBeenSet; }

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline void SetResourceId(const Aws::String& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline void SetResourceId(Aws::String&& value) { m_resourceIdHasBeenSet = true; m_resourceId = std::move(value); }

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline void SetResourceId(const char* value) { m_resourceIdHasBeenSet = true; m_resourceId.assign(value); }

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline FlowLog& WithResourceId(const Aws::String& value) { SetResourceId(value); return *this;}

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline FlowLog& WithResourceId(Aws::String&& value) { SetResourceId(std::move(value)); return *this;}

    /**
     *
The ID of the resource on which the flow log was created.

     */
    inline FlowLog& WithResourceId(const char* value) { SetResourceId(value); return *this;}

    /**
     *
The type of traffic captured for the flow log.

     */
    inline const TrafficType& GetTrafficType() const{ return m_trafficType; }

    /**
     *
The type of traffic captured for the flow log.

     */
    inline bool TrafficTypeHasBeenSet() const { return m_trafficTypeHasBeenSet; }

    /**
     *
The type of traffic captured for the flow log.

     */
    inline void SetTrafficType(const TrafficType& value) { m_trafficTypeHasBeenSet = true; m_trafficType = value; }

    /**
     *
The type of traffic captured for the flow log.

     */
    inline void SetTrafficType(TrafficType&& value) { m_trafficTypeHasBeenSet = true; m_trafficType = std::move(value); }

    /**
     *
The type of traffic captured for the flow log.

     */
    inline FlowLog& WithTrafficType(const TrafficType& value) { SetTrafficType(value); return *this;}

    /**
     *
The type of traffic captured for the flow log.

     */
    inline FlowLog& WithTrafficType(TrafficType&& value) { SetTrafficType(std::move(value)); return *this;}

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline const LogDestinationType& GetLogDestinationType() const{ return m_logDestinationType; }

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline bool LogDestinationTypeHasBeenSet() const { return m_logDestinationTypeHasBeenSet; }

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline void SetLogDestinationType(const LogDestinationType& value) { m_logDestinationTypeHasBeenSet = true; m_logDestinationType = value; }

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline void SetLogDestinationType(LogDestinationType&& value) { m_logDestinationTypeHasBeenSet = true; m_logDestinationType = std::move(value); }

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline FlowLog& WithLogDestinationType(const LogDestinationType& value) { SetLogDestinationType(value); return *this;}

    /**
     *
Specifies the type of destination to which the flow log data is published.
     * Flow log data can be published to CloudWatch Logs or Amazon S3.

     */
    inline FlowLog& WithLogDestinationType(LogDestinationType&& value) { SetLogDestinationType(std::move(value)); return *this;}

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline const Aws::String& GetLogDestination() const{ return m_logDestination; }

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline bool LogDestinationHasBeenSet() const { return m_logDestinationHasBeenSet; }

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline void SetLogDestination(const Aws::String& value) { m_logDestinationHasBeenSet = true; m_logDestination = value; }

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline void SetLogDestination(Aws::String&& value) { m_logDestinationHasBeenSet = true; m_logDestination = std::move(value); }

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline void SetLogDestination(const char* value) { m_logDestinationHasBeenSet = true; m_logDestination.assign(value); }

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline FlowLog& WithLogDestination(const Aws::String& value) { SetLogDestination(value); return *this;}

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline FlowLog& WithLogDestination(Aws::String&& value) { SetLogDestination(std::move(value)); return *this;}

    /**
     *
Specifies the destination to which the flow log data is published. Flow log
     * data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If
     * the flow log publishes to CloudWatch Logs, this element indicates the Amazon
     * Resource Name (ARN) of the CloudWatch Logs log group to which the data is
     * published. If the flow log publishes to Amazon S3, this element indicates the
     * ARN of the Amazon S3 bucket to which the data is published.

     */
    inline FlowLog& WithLogDestination(const char* value) { SetLogDestination(value); return *this;}

    /**
     *
The format of the flow log record.

     */
    inline const Aws::String& GetLogFormat() const{ return m_logFormat; }

    /**
     *
The format of the flow log record.

     */
    inline bool LogFormatHasBeenSet() const { return m_logFormatHasBeenSet; }

    /**
     *
The format of the flow log record.

     */
    inline void SetLogFormat(const Aws::String& value) { m_logFormatHasBeenSet = true; m_logFormat = value; }

    /**
     *
The format of the flow log record.

     */
    inline void SetLogFormat(Aws::String&& value) { m_logFormatHasBeenSet = true; m_logFormat = std::move(value); }

    /**
     *
The format of the flow log record.

     */
    inline void SetLogFormat(const char* value) { m_logFormatHasBeenSet = true; m_logFormat.assign(value); }

    /**
     *
The format of the flow log record.

     */
    inline FlowLog& WithLogFormat(const Aws::String& value) { SetLogFormat(value); return *this;}

    /**
     *
The format of the flow log record.

     */
    inline FlowLog& WithLogFormat(Aws::String&& value) { SetLogFormat(std::move(value)); return *this;}

    /**
     *
The format of the flow log record.

     */
    inline FlowLog& WithLogFormat(const char* value) { SetLogFormat(value); return *this;}

    /**
     *
The tags for the flow log.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
The tags for the flow log.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
The tags for the flow log.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The tags for the flow log.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
The tags for the flow log.

     */
    inline FlowLog& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
The tags for the flow log.

     */
    inline FlowLog& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The tags for the flow log.

     */
    inline FlowLog& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
The tags for the flow log.

     */
    inline FlowLog& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

    /**
     *
The maximum interval of time, in seconds, during which a flow of packets is
     * captured and aggregated into a flow log record.

When a network interface
     * is attached to a Nitro-based
     * instance, the aggregation interval is always 60 seconds (1 minute) or less,
     * regardless of the specified value.

Valid Values: 60 |
     * 600

     */
    inline int GetMaxAggregationInterval() const{ return m_maxAggregationInterval; }

    /**
     *
The maximum interval of time, in seconds, during which a flow of packets is
     * captured and aggregated into a flow log record.

When a network interface
     * is attached to a Nitro-based
     * instance, the aggregation interval is always 60 seconds (1 minute) or less,
     * regardless of the specified value.

Valid Values: 60 |
     * 600

     */
    inline bool MaxAggregationIntervalHasBeenSet() const { return m_maxAggregationIntervalHasBeenSet; }

    /**
     *
The maximum interval of time, in seconds, during which a flow of packets is
     * captured and aggregated into a flow log record.

When a network interface
     * is attached to a Nitro-based
     * instance, the aggregation interval is always 60 seconds (1 minute) or less,
     * regardless of the specified value.

Valid Values: 60 |
     * 600

     */
    inline void SetMaxAggregationInterval(int value) { m_maxAggregationIntervalHasBeenSet = true; m_maxAggregationInterval = value; }

    /**
     *
The maximum interval of time, in seconds, during which a flow of packets is
     * captured and aggregated into a flow log record.

When a network interface
     * is attached to a Nitro-based
     * instance, the aggregation interval is always 60 seconds (1 minute) or less,
     * regardless of the specified value.

Valid Values: 60 |
     * 600

     */
    inline FlowLog& WithMaxAggregationInterval(int value) { SetMaxAggregationInterval(value); return *this;}

  private:

    Aws::Utils::DateTime m_creationTime;
    bool m_creationTimeHasBeenSet;

    Aws::String m_deliverLogsErrorMessage;
    bool m_deliverLogsErrorMessageHasBeenSet;

    Aws::String m_deliverLogsPermissionArn;
    bool m_deliverLogsPermissionArnHasBeenSet;

    Aws::String m_deliverLogsStatus;
    bool m_deliverLogsStatusHasBeenSet;

    Aws::String m_flowLogId;
    bool m_flowLogIdHasBeenSet;

    Aws::String m_flowLogStatus;
    bool m_flowLogStatusHasBeenSet;

    Aws::String m_logGroupName;
    bool m_logGroupNameHasBeenSet;

    Aws::String m_resourceId;
    bool m_resourceIdHasBeenSet;

    TrafficType m_trafficType;
    bool m_trafficTypeHasBeenSet;

    LogDestinationType m_logDestinationType;
    bool m_logDestinationTypeHasBeenSet;

    Aws::String m_logDestination;
    bool m_logDestinationHasBeenSet;

    Aws::String m_logFormat;
    bool m_logFormatHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;

    int m_maxAggregationInterval;
    bool m_maxAggregationIntervalHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
namespace WpfAnalyzers;

using System.Collections.Generic;
using System.Threading;
using Gu.Roslyn.AnalyzerExtensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

internal static class AttributeExt
{
    internal static IEnumerable<AttributeSyntax> FindAttributes(CompilationUnitSyntax assemblyInfo, QualifiedType expectedType, SemanticModel semanticModel, CancellationToken cancellationToken)
    {
        foreach (var attributeList in assemblyInfo.AttributeLists)
        {
            foreach (var candidate in attributeList.Attributes)
            {
                if (semanticModel.TryGetNamedType(candidate, expectedType, cancellationToken, out _))
                {
                    yield return candidate;
                }
            }
        }
    }
}


text:
package pl.touk.nussknacker.ui.security.oauth2.jwt

import pdi.jwt.JwtUtils
import pdi.jwt.exceptions.JwtLengthException
import pl.touk.nussknacker.engine.util.SensitiveDataMasker

case class RawJwtToken(token: String) {

  // claim can have some personal data like e-mail and signature can be used for session hijacking
  def masked: String = (List(header, SensitiveDataMasker.mask(claim)) ::: sigOpt.map(SensitiveDataMasker.mask) :: Nil).mkString(".")

  lazy val (header, claim, sigOpt) = {
    val parts = JwtUtils.splitString(token, '.')

    val signature = parts.length match {
      case 2 => None
      case 3 => Some(parts(2))
      case _ =>
        throw new JwtLengthException(
          s"Expected token [$token] to be composed of 2 or 3 parts separated by dots."
        )
    }

    (parts(0), parts(1), signature)
  }

}


text:
/**
 * @author Geert Fokke [geert@sector22.com]
 * @www sector22.com
 * @module sector22/core/mixin
 */

var log                     = require('../debug/Log').getInstance();

/**
 * @mixin logMixin
 */
logMixin = {};

/**
* Function to log a debug message,
* @protected
* @function logDebug
* @param var_args {...object} - messages and/or data to log.
*/
logMixin.logDebug = function ( var_args ) {

    // super fast Array.unshift()
    // @see: https://jsperf.com/array-unshift-vs-prepend/39
    var length = arguments.length, args = new Array(length + 1);
    while(length) args[length--] = arguments[length];
    args[0] = this;

    log.debug.apply( this, args );

}
/**
 * Function to log a info message,
 * @protected
 * @function logInfo
 * @param var_args {...object} - messages and/or data to log.
 */
logMixin.logInfo = function ( var_args ) {

    // super fast Array.unshift()
    // @see: https://jsperf.com/array-unshift-vs-prepend/39
    var length = arguments.length, args = new Array(length + 1);
    while(length) args[length--] = arguments[length];
    args[0] = this;

    log.info.apply( this, args );
}
/**
 * Function to log a warning message,
 * @protected
 * @function logWarn
 * @param var_args {...object} - messages and/or data to log.
 */
logMixin.logWarn = function ( var_args ) {

    // super fast Array.unshift()
    // @see: https://jsperf.com/array-unshift-vs-prepend/39
    var length = arguments.length, args = new Array(length + 1);
    while(length) args[length--] = arguments[length];
    args[0] = this;

    log.warn.apply( this, args );

}
/**
 * Function to log a error message,
 * @protected
 * @function logError
 * @param var_args {...object} - messages and/or data to log.
 */
logMixin.logError = function ( var_args ) {

    // super fast Array.unshift()
    // @see: https://jsperf.com/array-unshift-vs-prepend/39
    var length = arguments.length, args = new Array(length + 1);
    while(length) args[length--] = arguments[length];
    args[0] = this;

    log.error.apply( this, args );

}
/**
 * Function to log a fatal error message,
 * @protected
 * @function logFatal
 * @param var_args {...object} - messages and/or data to log.
 */
logMixin.logFatal = function ( var_args ) {

    // super fast Array.unshift()
    // @see: https://jsperf.com/array-unshift-vs-prepend/39
    var length = arguments.length, args = new Array(length + 1);
    while(length) args[length--] = arguments[length];
    args[0] = this;

    log.fatal.apply( this, args );

}

/**
 * Adds the mixin functionality to the constructors prototype
 * @param constructor {function}
 * @param opt_unsafe {boolean=false} won't double check if we are overwriting anything if true
 */
logMixin.apply = function ( constructor, opt_unsafe ) {

    var proto = constructor.prototype;

    if( !opt_unsafe && (
        proto[ 'logDebug' ] !== undefined ||
        proto[ 'logInfo' ] !== undefined ||
        proto[ 'logWarn' ] !== undefined ||
        proto[ 'logError' ] !== undefined ||
        proto[ 'logFatal' ] !== undefined ) ) {

        throw new Error( 'Failed to apply the mixin because some property name is already taken!' );

    }

    proto.logDebug              = logMixin.logDebug;
    proto.logInfo               = logMixin.logInfo;
    proto.logWarn               = logMixin.logWarn;
    proto.logError              = logMixin.logError;
    proto.logFatal              = logMixin.logFatal;

};

if( typeof Object.freeze === 'function') Object.freeze(logMixin) // lock the object to minimize accidental changes

module.exports = logMixin;


text:
Additional header content

Gets or sets the headers.

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
public ColumnHeadersModel Headers { get; set; }
```

**VB**

``` VB
Public Property Headers As ColumnHeadersModel
	Get
	Set
```

#### Property Value
Type: ColumnHeadersModel
The headers.

## Remarks
\[Missing <remarks> documentation for "P:iTin.Export.Model.TableModel.Headers"\]

## See Also

#### Reference
TableModel Class
iTin.Export.Model Namespace


text:
Additional header content

Gets or sets the preferred posterior delimiter for field.

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
public string FieldSufix { get; set; }
```

**VB**

``` VB
Public Property FieldSufix As String
	Get
	Set
```

#### Property Value
Type: String
The preferred posterior delimiter for field. The default is an empty string ("").

## Remarks

**ITEE Object Element Usage**

``` XML
<Settings FieldSufix="string" .../>
```

## See Also

#### Reference
TemplateWriterSettingsModel Class
iTin.Export.Model Namespace


text:
var assert = require('assert'),
    path = require('path'),
    fs = require('fs'),
    resetHosts = require('./helpers/reset-hosts'),
    setHost = require('../src/set-host');

describe('setHost', function() {

  afterEach(function() {
    resetHosts(2);
  });

  it('should update an existing hostname entry', function() {
    var filePath = path.resolve(__dirname, 'data/hosts_2');
    setHost('::2', 'file', filePath);
    assert.equal(fs.readFileSync(filePath).toString(), '# short\n::2 file\n');
  });

  it('should add a new host', function() {
    var filePath = path.resolve(__dirname, 'data/hosts_2');
    setHost('::1', 'is-the-loneliest-number', filePath);
    assert.equal(fs.readFileSync(filePath).toString(), '# short\n::1 file\n\n::1 is-the-loneliest-number');
  });
});


text:
'use strict';

const http = require('http');
const assert = require('assert');

const Gofer = require('gofer');

function withTestApp(app) {
  before(function(done) {
    const self = this;
    self.server = http.createServer(app).listen(0, function() {
      self.baseUrl = 'http://127.0.0.1:' + self.server.address().port;
      self.client = new Gofer({
        globalDefaults: { baseUrl: self.baseUrl }
      });
      done();
    });
  });

  return {
    describeRequest: describeRequest,
    assertStatusCode: assertStatusCode,
    itSends: itSends
  };
}

function describeRequest(method, uri, fn) {
  describe(`${method} ${uri}`, function() {
    before(function() {
      const self = this;
      return this.client.fetch({
        method: method,
        uri: uri,
        maxStatusCode: 600
      }).getResponse().then(function(res) {
        self.response = res;
      });
    });

    fn();
  });
}

function assertStatusCode(statusCode) {
  before('verify statusCode', function() {
    assert.equal(this.response.statusCode, statusCode);
  });
}

function itSends(body) {
  it(`sends ${JSON.stringify(body)}`, function() {
    assert.equal(this.response.body, body);
  });
}

module.exports = withTestApp;


text:
/* Machine
 * Defines interfaces to talk to docker machine
 */

var spawn = require('child_process').spawn;

var Machine = function (path, name) {
    this.path = path;
    this.name = name;
    this.driver = 'amazonec2';
    this.aws_key = '';
    this.aws_secret = '';
    this.vpc = '';
    this.zone = 'b';
    this.region = '';
};

Machine.prototype.createMachine = function(callback) {
  var self = this;
  this.exists(function(error, flag) {
    if (flag) {
      callback(null, true);
    } else {
      self.create(function (err, output) {
        if (err) { callback(err) }
        else callback(null, output);
      });
    }
  })
};

Machine.prototype.create = function(callback) {
    this.executor(['-D', 'create',
      '--driver', this.driver,
      '--amazonec2-access-key', this.aws_key,
      '--amazonec2-secret-key', this.aws_secret,
      '--amazonec2-vpc-id', this.vpc,
      '--amazonec2-zone', this.zone,
      '--amazonec2-region', this.region,
      this.name], callback);
};

Machine.prototype.start = function(callback) {
    this.executor(['start', this.name], callback);
};

Machine.prototype.stop = function(callback) {
    this.executor(['stop', this.name], callback);
};

Machine.prototype.env = function(callback) {
    this.executor(['env', this.name], callback);
};

Machine.prototype.getEnv = function(callback) {
  var self = this;
  this.getMachineIP(function (error, ip) {
    if (error) { callback(error) }
    else {
      callback(null, {
        DOCKER_TLS_VERIFY : "1",
        DOCKER_HOST : "tcp://" + ip.replace('\n', '') + ":2376",
        DOCKER_CERT_PATH : process.env.HOME + '/.docker/machine/machines/' + self.name,
        DOCKER_MACHINE_NAME : self.name
      });
    }
  });
};

Machine.prototype.exists = function(callback) {
  var self = this;
  this.executor(['ls', '-q'], function(error, machines) {
    if (error) callback(error)
    else {
      var machine_array = machines.split('\n');
      if (machine_array.indexOf(self.name) < 0) {
        callback(null, false);
      } else {
        callback(null, true);
      }
    }
  })
};

Machine.prototype.getMachineIP = function(callback) {
  var self = this;
  this.executor(['ip', this.name], function(err, ip) {
    if (err) {
      callback(err, ip);
    } else {
      self.ip = ip.replace('\n', '');
      callback(null, self.ip);
    }
  });
};

Machine.prototype.executor = function(args, callback) {
  var options = {
    cwd : this.path
  }
  var cmd = spawn('docker-machine', args, options);
  var output = '',
    error = '';

  cmd.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
    output += data;
  });

  cmd.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
    error += data;
  });

  cmd.on('close', function (code) {
    console.log('child process exited with code ' + code);
    // callback(output, error);
    if (code) {
      callback(error, output);
    } else {
      callback(null, output);
    }
  });
};

module.exports = Machine;


text:
@interface ACRoomsViewController () <UITableViewDataSource, UITableViewDelegate, ACCreateRoomViewControllerDelegate>

@property (nonatomic, readonly) UITableView     *tableView;
@property (nonatomic, strong) NSArray           *rooms;
@property (nonatomic, strong) UIButton *addRoomButton;
@end

@implementation ACRoomsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"CHAT";

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didUpdateRoomsNotification:) name:ACSDKDidUpdateRoomsNotification object:nil];

    _tableView = [UITableView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[ACTableViewRoomCell class] forCellReuseIdentifier:@"ACRoomCell"];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];

    _addRoomButton = [UIButton new];
    [_addRoomButton setTitle:@"+" forState:UIControlStateNormal];
    [_addRoomButton setBackgroundColor:[UIColor colorWithRed:142./255. green:136./255. blue:250/255. alpha:1]];
    [_addRoomButton setClipsToBounds:YES];

    [_addRoomButton addTarget:self action:@selector(addRoomAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addRoomButton];
    self.rooms = [ACSDK defaultInstance].rooms;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    self.tableView.frame = self.view.bounds;

    CGFloat buttonSide = 50;
    _addRoomButton.layer.cornerRadius = buttonSide/2.f;
    _addRoomButton.frame = CGRectMake(self.view.frame.size.width-buttonSide-buttonSide/2, self.view.frame.size.height-buttonSide-buttonSide/2, buttonSide, buttonSide);
}

- (void)addRoomAction:(id)sender {
    ACCreateRoomViewController *vc = [ACCreateRoomViewController new];
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - ACCreateRoomViewControllerDelegate

- (void)didCreateRoom:(ACRoomModel *)roomModel {
    [self.navigationController pushViewController:[[ACChatViewController alloc] initWithRoom:roomModel] animated:YES];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.rooms.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80.;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ACTableViewRoomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACRoomCell"];
    if (!cell) {
        cell = [[ACTableViewRoomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ACRoomCell"];
    }
    ACRoomModel *roomModel = self.rooms[indexPath.row];
    [cell setupWithModel:roomModel];
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    BOOL hasUnread = ([(ACRoomModel*)self.rooms[indexPath.row] hasUnreadMessages]);

    UIColor *unreadColor = [UIColor colorWithRed:246./255. green:245./255. blue:250/255. alpha:1.];
    UIColor *backgroundColor = hasUnread ? unreadColor : [UIColor whiteColor];
    [cell setBackgroundColor:backgroundColor];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    ACRoomModel *roomModel = self.rooms[indexPath.row];
    [self.navigationController pushViewController:[[ACChatViewController alloc] initWithRoom:roomModel] animated:YES];

}

#pragma mark - notifications

- (void)didUpdateRoomsNotification:(NSNotification *)notification {
    self.rooms = notification.userInfo[ACRoomsKey];
    [self.tableView reloadData];
}

@end


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xamarin.Forms;

namespace XamForms.Controls
{
	public partial class Calendar : ContentView
	{
		List<Grid> WeekNumbers;
		List<Label> weekNumberLabels;

		#region NumberOfWeekTextColor

		public static readonly BindableProperty NumberOfWeekTextColorProperty =
		  BindableProperty.Create(nameof(NumberOfWeekTextColor), typeof(Color), typeof(Calendar), Color.FromHex("#aaaaaa"),
								  propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeNumberOfWeekTextColor((Color)newValue, (Color)oldValue));

		protected void ChangeNumberOfWeekTextColor(Color newValue, Color oldValue)
		{
			if (newValue == oldValue) return;
			weekNumberLabels.ForEach(l => l.TextColor = newValue);
		}

		/// <summary>
		/// Gets or sets the text color of the number of the week labels.
		/// </summary>
		/// <value>The color of the weekdays text.</value>
		public Color NumberOfWeekTextColor
		{
			get { return (Color)GetValue(NumberOfWeekTextColorProperty); }
			set { SetValue(NumberOfWeekTextColorProperty, value); }
		}

		public static readonly BindableProperty NumberOfWeekBackgroundColorProperty =
			BindableProperty.Create(nameof(NumberOfWeekBackgroundColor), typeof(Color), typeof(Calendar), Color.Transparent,
									propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeNumberOfWeekBackgroundColor((Color)newValue, (Color)oldValue));

		protected void ChangeNumberOfWeekBackgroundColor(Color newValue, Color oldValue)
		{
			if (newValue == oldValue) return;
			weekNumberLabels.ForEach(l => l.BackgroundColor = newValue);
		}

		/// <summary>
		/// Gets or sets the background color of the number of the week labels.
		/// </summary>
		/// <value>The color of the number of the weeks background.</value>
		public Color NumberOfWeekBackgroundColor
		{
			get { return (Color)GetValue(NumberOfWeekBackgroundColorProperty); }
			set { SetValue(NumberOfWeekBackgroundColorProperty, value); }
		}

		#endregion

		#region NumberOfWeekFontSize

		public static readonly BindableProperty NumberOfWeekFontSizeProperty =
			BindableProperty.Create(nameof(NumberOfWeekFontSize), typeof(double), typeof(Calendar), 14.0,
									propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeNumberOfWeekFontSize((double)newValue, (double)oldValue));

		protected void ChangeNumberOfWeekFontSize(double newValue, double oldValue)
		{
			if (Math.Abs(newValue - oldValue) < 0.01) return;
			WeekNumbers?.ForEach((obj) => obj.WidthRequest = newValue*( Device.RuntimePlatform == Device.iOS ? 1.5 : 2.2));
			weekNumberLabels.ForEach(l => l.FontSize = newValue);
		}

		/// <summary>
		/// Gets or sets the font size of the number of the week labels.
		/// </summary>
		/// <value>The size of the weekdays font.</value>
		public double NumberOfWeekFontSize
		{
			get { return (double)GetValue(NumberOfWeekFontSizeProperty); }
			set { SetValue(NumberOfWeekFontSizeProperty, value); }
		}

		#endregion

		#region NumberOfWeekFontAttributes

		public static readonly BindableProperty NumberOfWeekFontAttributesProperty =
			BindableProperty.Create(nameof(NumberOfWeekFontAttributes), typeof(FontAttributes), typeof(Calendar), FontAttributes.None,
									propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeNumberOfWeekFontAttributes((FontAttributes)newValue, (FontAttributes)oldValue));

		protected void ChangeNumberOfWeekFontAttributes(FontAttributes newValue, FontAttributes oldValue)
		{
			if (newValue == oldValue) return;
			weekNumberLabels.ForEach(l => l.FontAttributes = newValue);
		}

		/// <summary>
		/// Gets or sets the font attributes of the number of the week labels.
		/// </summary>
		public FontAttributes NumberOfWeekFontAttributes
		{
			get { return (FontAttributes)GetValue(NumberOfWeekFontAttributesProperty); }
			set { SetValue(NumberOfWeekFontAttributesProperty, value); }
		}

		#endregion

		#region NumberOfWeekFontFamily

		public static readonly BindableProperty NumberOfWeekFontFamilyProperty =
					BindableProperty.Create(nameof(NumberOfWeekFontFamily), typeof(string), typeof(Calendar), default(string),
									propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeNumberOfWeekFontFamily((string)newValue, (string)oldValue));

		protected void ChangeNumberOfWeekFontFamily(string newValue, string oldValue)
		{
			if (newValue == oldValue) return;
			weekNumberLabels.ForEach(l => l.FontFamily = newValue);
		}

		/// <summary>
		/// Gets or sets the font family of the number of the week labels.
		/// </summary>
		public string NumberOfWeekFontFamily
		{
			get { return GetValue(NumberOfWeekFontFamilyProperty) as string; }
			set { SetValue(NumberOfWeekFontFamilyProperty, value); }
		}

		#endregion

		#region ShowNumberOfWeek

		public static readonly BindableProperty ShowNumberOfWeekProperty =
			BindableProperty.Create(nameof(ShowNumberOfWeek), typeof(bool), typeof(Calendar), false,
									propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ShowHideElements());

		/// <summary>
		/// Gets or sets wether to show the number of the week labels.
		/// </summary>
		/// <value>The weekdays show.</value>
		public bool ShowNumberOfWeek
		{
			get { return (bool)GetValue(ShowNumberOfWeekProperty); }
			set { SetValue(ShowNumberOfWeekProperty, value); }
		}

		#endregion

		#region CalendarWeekRule

		public static readonly BindableProperty CalendarWeekRuleProperty =
			BindableProperty.Create(nameof(CalendarWeekRule), typeof(CalendarWeekRule), typeof(Calendar), CalendarWeekRule.FirstFourDayWeek,
			propertyChanged: (bindable, oldValue, newValue) =>
			{
				var calendar = (bindable as Calendar);
				var start = calendar.CalendarStartDate(calendar.StartDate).Date;
				for (int i = 0; i < calendar.buttons.Count; i++)
				{
					calendar.ChangeWeekNumbers(start, i);

					start = start.AddDays(1);
					if (i != 0 && (i + 1) % 42 == 0)
					{
						start = calendar.CalendarStartDate(start);
					}
				}
			});

		/// <summary>
		/// Gets or sets what CalendarWeekRule to use for the week numbers
		/// </summary>
		/// <value>The weekdays show.</value>
		public CalendarWeekRule CalendarWeekRule
		{
			get { return (CalendarWeekRule)GetValue(CalendarWeekRuleProperty); }
			set { SetValue(CalendarWeekRuleProperty, value); }
		}

		#endregion

		protected void ChangeWeekNumbers(DateTime start, int i)
		{
			if (!ShowNumberOfWeek) return;
			CultureInfo ciCurr = CultureInfo.CurrentCulture;
			var weekNum = ciCurr.Calendar.GetWeekOfYear(start, CalendarWeekRule.FirstFourDayWeek, StartDay);
			weekNumberLabels[(i / 7)].Text = string.Format("{0}", weekNum);
		}

		protected void ShowHideElements()
		{
			if (MainCalendars.Count < 1) return;
			ContentView.Children.Clear();
			dayLabels.Clear();
			for (var i = 0; i < ShowNumOfMonths; i++)
			{
				var main = MainCalendars[i] as Layout;

				if (ShowInBetweenMonthLabels && i > 0)
				{
					var label = new Label
					{
						FontSize = TitleLabel.FontSize,
						VerticalTextAlignment = TitleLabel.VerticalTextAlignment,
						HorizontalTextAlignment = TitleLabel.HorizontalTextAlignment,
						FontAttributes = TitleLabel.FontAttributes,
						TextColor = TitleLabel.TextColor,
						HorizontalOptions = LayoutOptions.FillAndExpand,
						Text = ""
					};
					if (TitleLabels == null)
					{
						TitleLabels = new List<Label>(ShowNumOfMonths);
					}
					TitleLabels.Add(label);
					/*if (i == ShowNumOfMonths - 1)
					{
						MonthNavigationLayout.Children.Remove(TitleRightArrow);
						ContentView.Children.Add(new StackLayout {
							Orientation = StackOrientation.Horizontal,
							Padding = new Thickness(TitleLeftArrow.FontSize*1.5,0,0,0), Children = { label, TitleRightArrow }
						});
					}
					else
					{*/
						ContentView.Children.Add(label);
					//}
				}

				if (ShowNumberOfWeek)
				{
					main = new StackLayout
					{
						Padding = 0,
						Spacing = 0,
						VerticalOptions = LayoutOptions.FillAndExpand,
						HorizontalOptions = LayoutOptions.FillAndExpand,
						Orientation = StackOrientation.Horizontal,
						Children = { WeekNumbers[i], MainCalendars[i] }
					};
				}

				if (WeekdaysShow)
				{
					var columDef = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
					var dl = new Grid { VerticalOptions = LayoutOptions.Start, RowSpacing = 0, ColumnSpacing = 0, Padding = 0 };
					dl.ColumnDefinitions = new ColumnDefinitionCollection { columDef, columDef, columDef, columDef, columDef, columDef, columDef };
					var marginFront = NumberOfWeekFontSize * 1.5;
					if (Device.RuntimePlatform == Device.Windows) marginFront = NumberOfWeekFontSize * 2.5;
					if (ShowNumberOfWeek) dl.Padding = new Thickness(marginFront, 0, 0, 0);

					for (int c = 0; c < 7; c++)
					{
                        dayLabels.Add(new Label
                        {
                            HorizontalOptions = LayoutOptions.FillAndExpand,
                            VerticalOptions = LayoutOptions.FillAndExpand,
                            HorizontalTextAlignment = TextAlignment.Center,
                            VerticalTextAlignment = TextAlignment.Center,
							BackgroundColor = WeekdaysBackgroundColor,
							TextColor = WeekdaysTextColor,
							FontSize = WeekdaysFontSize,
							FontFamily = WeekdaysFontFamily,
							FontAttributes = WeekdaysFontAttributes
						});
						dl.Children.Add(dayLabels.Last(), c, 0);
					}

					var stack = new StackLayout
					{
						Padding = 0,
						Spacing = 0,
						VerticalOptions = LayoutOptions.FillAndExpand,
						HorizontalOptions = LayoutOptions.FillAndExpand,
						Orientation = StackOrientation.Vertical,
						Children = { dl, main }
					};
					ContentView.Children.Add(stack);
				}
				else
				{
					ContentView.Children.Add(main);
				}
			}
		}
	}
}


text:
/* global angular:false */

angular
.module('ndslabs-login')

/**
 * The controller for our "Login" View
 *
 * @author lambert8
 * @see https://opensource.ncsa.illinois.edu/confluence/display/~lambert8/3.%29+Controllers%2C+Scopes%2C+and+Partial+Views
 */
.controller('LoginController', [ '$scope', '$rootScope', '$cookies', '$routeParams', '$location', '$window', '$log', '$uibModal', 'AuthInfo', 'Project', 'NdsLabsApi', 'DashboardAppPath', 'HomePathSuffix', 'CookieOptions', '$uibModalStack', 'ServerData', 'ProductName', 'ReturnRoute', 'SigninUrl',
    function($scope, $rootScope, $cookies, $routeParams, $location, $window, $log, $uibModal, authInfo, Project, NdsLabsApi, DashboardAppPath, HomePathSuffix, CookieOptions, $uibModalStack, ServerData, ProductName, ReturnRoute, SigninUrl) {
  "use strict";

  $rootScope.rd = '';
  if ($routeParams.rd) {
    ReturnRoute = $routeParams.rd;
    $rootScope.rd = encodeURIComponent(ReturnRoute);
  }

  $scope.productName = ProductName;

  // Grab our injected AuthInfo from the provider
  $scope.settings = authInfo.get();

  $scope.$watch(function() { return Project.project; }, function(newValue, oldValue) { $scope.project = newValue; });

  $scope.enableOAuth = SigninUrl.indexOf("/oauth2/") !== -1;
  $scope.signinLink = $scope.enableOAuth ? SigninUrl : '/login/' + ($rootScope.rd ? 'rd=' : '');

  // User should not be here if OAuth is enabled...
  // Navigate them to the correct place
  if ($scope.enableOAuth) {
    $window.location.href = $scope.signinLink;
    return;
  };

  $scope.clickCreateAccountLink = function() {
    if ($scope.enableOAuth) { return false; }
    $window.location.href = '/login/register' + ($rootScope.rd ? '?rd=' + $rootScope.rd : '')
  };

  $scope.clickForgotPasswordLink = function() {
    if ($scope.enableOAuth) { return false; }
    $window.location.href = '/login/recover' + ($rootScope.rd ? '?rd=' + $rootScope.rd : '')
  };

  /**
   * Start a local session by asking the server for a token
   */
  $scope.login = function() {
    $log.debug("Logging in!");
    $scope.progressMessage = 'Please wait...';
    $scope.errorMessage = '';

    // POST to /authenticate to create a token
    NdsLabsApi.postAuthenticate({
      "auth": {
        "username": $scope.settings.namespace,
        "password": $scope.settings.password
      }
    }).then(function(data, xhr) {
      $scope.errorMessage = '';

      // TODO: cauth server should set this for us, but doesn't seem to be working
      // FIXME: parameterize domain or connect to cauth endpoint
      $cookies.put('namespace', $scope.settings.namespace, CookieOptions);
      $cookies.put('token', data.token, CookieOptions);

      $log.debug("Logged in!");
      //getProject();

      // HACK: this pattern does not scale very well
      // If we were given an "rd" parameter, redirect to it on successful login
      var rd = $routeParams.rd;
      if (rd) {
        $window.location.href = rd;
      } else {
        $window.location.href = DashboardAppPath + HomePathSuffix;
      }
    }, function(response) {
      var body = response.body || { 'Error': 'Something went wrong. Is the server running?' };
      $scope.errorMessage = response.status === 401 ? 'Invalid username or password' : body.Error;
      $log.error("Error logging in!");
    }).finally(function() {
      $scope.progressMessage = '';
    });
  };

  /**
   * End our local session by deleting our token. This will bounce the
   * user back out to the login page, forcing them to re-authenticate
   * TODO: How do we end the session server-side?
   */
  $scope.logout = function() {
    $log.debug("Logging out!");

    // TODO: DELETE /authenticate to delete a token in the backend?
    //NdsLabsApi.deleteAuthenticate().then(function(data, xhr) {
      $scope.errorMessage = '';
      $scope.progressMessage = '';
      $log.debug("Logging out!");
      authInfo.purge();
    /*}, function(response) {
      $log.error("Error logging out!");
    }).finally(function() {*/
    //});
  };
}]);


text:
import { Component } from '@angular/core';
import { Weapon } from './weapon';

@Component({
  selector: 'weapons',
  templateUrl: 'weapons.component.html'
})

export class WeaponsComponent {
  public weapons: Weapon[] = [new Weapon(), new Weapon(), new Weapon()];
}
;


text:
package org.htrace.impl;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.trace.HBaseHTraceConfiguration;
import org.apache.hadoop.hbase.util.Bytes;
import org.htrace.HTraceConfiguration;
import org.htrace.Sampler;
import org.htrace.Span;
import org.htrace.SpanReceiver;
import org.htrace.TimelineAnnotation;
import org.htrace.Trace;
import org.htrace.TraceScope;
import org.htrace.protobuf.generated.SpanProtos;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * HBase is an open source distributed datastore.
 * This span receiver store spans into HBase.
 * HTrace spans are queued into a blocking queue.
 * From there background worker threads will send them
 * to a HBase database.
 */
public class HBaseSpanReceiver implements SpanReceiver {
  private static final Log LOG = LogFactory.getLog(HBaseSpanReceiver.class);

  public static final String COLLECTOR_QUORUM_KEY = "htrace.hbase.collector-quorum";
  public static final String DEFAULT_COLLECTOR_QUORUM = "127.0.0.1";
  public static final String ZOOKEEPER_CLIENT_PORT_KEY = "htrace.hbase.zookeeper.property.clientPort";
  public static final int DEFAULT_ZOOKEEPER_CLIENT_PORT = 2181;
  public static final String ZOOKEEPER_ZNODE_PARENT_KEY = "htrace.hbase.zookeeper.znode.parent";
  public static final String DEFAULT_ZOOKEEPER_ZNODE_PARENT = "/hbase";
  public static final String NUM_THREADS_KEY = "htrace.hbase.num-threads";
  public static final int DEFAULT_NUM_THREADS = 1;
  public static final String MAX_SPAN_BATCH_SIZE_KEY = "htrace.hbase.batch.size";
  public static final int DEFAULT_MAX_SPAN_BATCH_SIZE = 100;
  public static final String TABLE_KEY = "htrace.hbase.table";
  public static final String DEFAULT_TABLE = "htrace";
  public static final String COLUMNFAMILY_KEY = "htrace.hbase.columnfamily";
  public static final String DEFAULT_COLUMNFAMILY = "s";
  public static final String INDEXFAMILY_KEY = "htrace.hbase.indexfamily";
  public static final String DEFAULT_INDEXFAMILY = "i";
  public static final byte[] INDEX_SPAN_QUAL = Bytes.toBytes("s");
  public static final byte[] INDEX_TIME_QUAL = Bytes.toBytes("t");

  /**
   * How long this receiver will try and wait for all threads to shutdown.
   */
  private static final int SHUTDOWN_TIMEOUT = 30;

  /**
   * How many errors in a row before we start dropping traces on the floor.
   */
  private static final int MAX_ERRORS = 10;

  /**
   * The queue that will get all HTrace spans that are to be sent.
   */
  private final BlockingQueue queue;

  /**
   * Boolean used to signal that the threads should end.
   */
  private final AtomicBoolean running = new AtomicBoolean(true);

  /**
   * The thread factory used to create new ExecutorService.
   *

   * This will be the same factory for the lifetime of this object so that
   * no thread names will ever be duplicated.
   */
  private final ThreadFactory tf;

  ////////////////////
  /// Variables that will change on each call to configure()
  ///////////////////
  private ExecutorService service;
  private HTraceConfiguration conf;
  private Configuration hconf;
  private byte[] table;
  private byte[] cf;
  private byte[] icf;
  private int maxSpanBatchSize;

  public HBaseSpanReceiver() {
    this.queue = new ArrayBlockingQueue(1000);
    this.tf = new ThreadFactoryBuilder().setDaemon(true)
                                        .setNameFormat("hbaseSpanReceiver-%d")
                                        .build();
  }

  @Override
  public void configure(HTraceConfiguration conf) {
    this.conf = conf;
    this.hconf = HBaseConfiguration.create();
    this.table = Bytes.toBytes(conf.get(TABLE_KEY, DEFAULT_TABLE));
    this.cf = Bytes.toBytes(conf.get(COLUMNFAMILY_KEY, DEFAULT_COLUMNFAMILY));
    this.icf = Bytes.toBytes(conf.get(INDEXFAMILY_KEY, DEFAULT_INDEXFAMILY));
    this.maxSpanBatchSize = conf.getInt(MAX_SPAN_BATCH_SIZE_KEY,
                                        DEFAULT_MAX_SPAN_BATCH_SIZE);
    String quorum = conf.get(COLLECTOR_QUORUM_KEY, DEFAULT_COLLECTOR_QUORUM);
    hconf.set(HConstants.ZOOKEEPER_QUORUM, quorum);
    String znodeParent = conf.get(ZOOKEEPER_ZNODE_PARENT_KEY, DEFAULT_ZOOKEEPER_ZNODE_PARENT);
    hconf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, znodeParent);
    int clientPort = conf.getInt(ZOOKEEPER_CLIENT_PORT_KEY, DEFAULT_ZOOKEEPER_CLIENT_PORT);
    hconf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, clientPort);

    // If there are already threads runnnig tear them down.
    if (this.service != null) {
      this.service.shutdownNow();
      this.service = null;
    }
    int numThreads = conf.getInt(NUM_THREADS_KEY, DEFAULT_NUM_THREADS);
    this.service = Executors.newFixedThreadPool(numThreads, tf);
    for (int i = 0; i < numThreads; i++) {
      this.service.submit(new WriteSpanRunnable());
    }
  }

  private class WriteSpanRunnable implements Runnable {
    private HConnection hconnection;
    private HTableInterface htable;

    public WriteSpanRunnable() {
    }

    /**
     * This runnable sends a HTrace span to the HBase.
     */
    @Override
    public void run() {
      SpanProtos.Span.Builder sbuilder = SpanProtos.Span.newBuilder();
      SpanProtos.TimelineAnnotation.Builder tlbuilder =
          SpanProtos.TimelineAnnotation.newBuilder();
      List dequeuedSpans = new ArrayList(maxSpanBatchSize);
      long errorCount = 0;

      while (running.get() || queue.size() > 0) {
        Span firstSpan = null;
        try {
          // Block for up to a second. to try and get a span.
          // We only block for a little bit in order to notice
          // if the running value has changed
          firstSpan = queue.poll(1, TimeUnit.SECONDS);

          // If the poll was successful then it's possible that there
          // will be other spans to get. Try and get them.
          if (firstSpan != null) {
            // Add the first one that we got
            dequeuedSpans.add(firstSpan);
            // Try and get up to 100 queues
            queue.drainTo(dequeuedSpans, maxSpanBatchSize - 1);
          }
        } catch (InterruptedException ie) {
          // Ignored.
        }
        startClient();
        if (dequeuedSpans.isEmpty()) {
          try {
            this.htable.flushCommits();
          } catch (IOException e) {
            LOG.error("failed to flush writes to HBase.");
            closeClient();
          }
          continue;
        }

        try {
          for (Span span : dequeuedSpans) {
            sbuilder.clear()
                    .setTraceId(span.getTraceId())
                    .setParentId(span.getParentId())
                    .setStart(span.getStartTimeMillis())
                    .setStop(span.getStopTimeMillis())
                    .setSpanId(span.getSpanId())
                    .setProcessId(span.getProcessId())
                    .setDescription(span.getDescription());
            for (TimelineAnnotation ta : span.getTimelineAnnotations()) {
              sbuilder.addTimeline(tlbuilder.clear()
                                            .setTime(ta.getTime())
                                            .setMessage(ta.getMessage())
                                            .build());
            }
            Put put = new Put(Bytes.toBytes(span.getTraceId()));
            put.add(HBaseSpanReceiver.this.cf,
                    sbuilder.build().toByteArray(),
                    null);
            if (span.getParentId() == Span.ROOT_SPAN_ID) {
              put.add(HBaseSpanReceiver.this.icf,
                      INDEX_TIME_QUAL,
                      Bytes.toBytes(span.getStartTimeMillis()));
              put.add(HBaseSpanReceiver.this.icf,
                      INDEX_SPAN_QUAL,
                      sbuilder.build().toByteArray());
            }
            this.htable.put(put);
          }
          // clear the list for the next time through.
          dequeuedSpans.clear();
          // reset the error counter.
          errorCount = 0;
        } catch (Exception e) {
          errorCount += 1;
          // If there have been ten errors in a row start dropping things.
          if (errorCount < MAX_ERRORS) {
            try {
              queue.addAll(dequeuedSpans);
            } catch (IllegalStateException ex) {
              LOG.error("Drop " + dequeuedSpans.size() +
                        " span(s) because writing to HBase failed.");
            }
          }
          closeClient();
          try {
            // Since there was an error sleep just a little bit to try and allow the
            // HBase some time to recover.
            Thread.sleep(500);
          } catch (InterruptedException e1) {
            // Ignored
          }
        }
      }
      closeClient();
    }

    /**
     * Close out the connection.
     */
    private void closeClient() {
      // close out the transport.
      try {
        if (this.htable != null) {
          this.htable.close();
          this.htable = null;
        }
        if (this.hconnection != null) {
          this.hconnection.close();
          this.hconnection = null;
        }
      } catch (IOException e) {
        LOG.warn("Failed to close HBase connection. " + e.getMessage());
      }
    }

    /**
     * Re-connect to HBase
     */
    private void startClient() {
      if (this.htable == null) {
        try {
          hconnection = HConnectionManager.createConnection(hconf);
          htable = hconnection.getTable(table);
        } catch (IOException e) {
          LOG.warn("Failed to create HBase connection. " + e.getMessage());
        }
      }
    }
  }

  /**
   * Close the receiver.
   *

   * This tries to shutdown thread pool.
   *
   * @throws IOException
   */
  @Override
  public void close() throws IOException {
    running.set(false);
    service.shutdown();
    try {
      if (!service.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
        LOG.error("Was not able to process all remaining spans upon closing in: " +
            SHUTDOWN_TIMEOUT + " " + TimeUnit.SECONDS +
            ". Left Spans could be dropped.");
       }
    } catch (InterruptedException e1) {
      LOG.warn("Thread interrupted when terminating executor.", e1);
    }
  }

  @Override
  public void receiveSpan(Span span) {
    if (running.get()) {
      try {
        this.queue.add(span);
      } catch (IllegalStateException e) {
        // todo: supress repeating error logs.
        LOG.error("Error trying to append span (" +
            span.getDescription() +
            ") to the queue. Blocking Queue was full.");
      }
    }
  }

  /**
   * Run basic test.
   * @throws IOException
   */
  public static void main(String[] args) throws Exception {
    HBaseSpanReceiver receiver = new HBaseSpanReceiver();
    receiver.configure(new HBaseHTraceConfiguration(HBaseConfiguration.create()));
    Trace.addReceiver(receiver);
    TraceScope parent =
        Trace.startSpan("HBaseSpanReceiver.main.parent", Sampler.ALWAYS);
    Thread.sleep(10);
    long traceid = parent.getSpan().getTraceId();
    TraceScope child1 =
        Trace.startSpan("HBaseSpanReceiver.main.child.1");
    Thread.sleep(10);
    TraceScope child2 =
        Trace.startSpan("HBaseSpanReceiver.main.child.2", parent.getSpan());
    Thread.sleep(10);
    TraceScope gchild =
        Trace.startSpan("HBaseSpanReceiver.main.grandchild");
    Trace.addTimelineAnnotation("annotation 1.");
    Thread.sleep(10);
    Trace.addTimelineAnnotation("annotation 2.");
    gchild.close();
    Thread.sleep(10);
    child2.close();
    Thread.sleep(10);
    child1.close();
    parent.close();
    receiver.close();
    System.out.println("trace id: " + traceid);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <createDate>2017-02-17T04:46:13Z</createDate>
    <policyArea>
      <name>Health</name>
    </policyArea>
    <notes />
    <version>1.0.0</version>
    <relatedBills />
    <actions>
      <item>
        <actionDate>2017-02-17</actionDate>
        <committee>
          <name>Health Subcommittee</name>
          <systemCode>hsif14</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>House committee actions</name>
          1
        </sourceSystem>
        <text>Referred to the Subcommittee on Health.</text>
        <type>Committee</type>
      </item>
      <item>
        <text>Referred to the House Committee on Energy and Commerce.</text>
        <actionDate>2017-02-16</actionDate>
        <committee>
          <name>Energy and Commerce Committee</name>
          <systemCode>hsif00</systemCode>
        </committee>
        <links />
        <type>IntroReferral</type>
        <sourceSystem>
          <name>House floor actions</name>
          2
        </sourceSystem>
        <actionCode>H11100</actionCode>
      </item>
      <item>
        <text>Introduced in House</text>
        <actionDate>2017-02-16</actionDate>
        <committee />
        <links />
        <type>IntroReferral</type>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <actionCode>Intro-H</actionCode>
      </item>
      <item>
        <text>Introduced in House</text>
        <actionDate>2017-02-16</actionDate>
        <committee />
        <links />
        <type>IntroReferral</type>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <actionCode>1000</actionCode>
      </item>
      <actionTypeCounts>
        <introducedInHouse>1</introducedInHouse>
        <placeholderTextForH>1</placeholderTextForH>
        <billReferrals>1</billReferrals>
        <introducedInTheHouse>1</introducedInTheHouse>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>4</houseOfRepresentatives>
      </actionByCounts>
    </actions>
    <originChamber>House</originChamber>
    <cosponsors />
    <introducedDate>2017-02-16</introducedDate>
    <sponsors>
      <item>
        <bioguideId>L000576</bioguideId>
        <lastName>Long</lastName>
        <firstName>Billy</firstName>
        <fullName>Rep. Long, Billy [R-MO-7]</fullName>
        <middleName />
        <identifiers>
          <bioguideId>L000576</bioguideId>
          <lisID>2033</lisID>
          <gpoId>8015</gpoId>
        </identifiers>
        <byRequestType />
        <state>MO</state>
        <district>7</district>
        <party>R</party>
      </item>
    </sponsors>
    <cboCostEstimates />
    <titles>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Medicaid Cost-Sharing Waiver Flexibility Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <title>Medicaid Cost-Sharing Waiver Flexibility Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <title>To amend title XIX of the Social Security Act to provide greater State flexibility and innovation through Medicaid cost-sharing waivers.</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Display Title</titleType>
        <title>Medicaid Cost-Sharing Waiver Flexibility Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
    </titles>
    <congress>115</congress>
    <billNumber>1166</billNumber>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <name>Energy and Commerce Committee</name>
          <chamber>House</chamber>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-02-16T15:07:40Z</date>
            </item>
          </activities>
          <systemCode>hsif00</systemCode>
          <subcommittees>
            <item>
              <activities>
                <item>
                  <name>Referred to</name>
                  <date>2017-02-17T19:09:56Z</date>
                </item>
              </activities>
              <systemCode>hsif14</systemCode>
              <name>Health Subcommittee</name>
            </item>
          </subcommittees>
        </item>
      </billCommittees>
    </committees>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. LONG:H.R. 1166.Congress has the power to enact this legislation pursuantto the following:Article I, Section 8, Clause 18 of the United StatesConstitution[Page H1305]
]]></constitutionalAuthorityStatementText>
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Health</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Aging</name>
          </item>
          <item>
            <name>Disability and paralysis</name>
          </item>
          <item>
            <name>Hearing, speech, and vision care</name>
          </item>
          <item>
            <name>Medicaid</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <amendments />
    <committeeReports />
    <summaries>
      <billSummaries>
        <item>
          <updateDate>2017-02-16T05:00:00Z</updateDate>
          <lastSummaryUpdateDate>2017-06-15T18:08:32Z</lastSummaryUpdateDate>
          <actionDate>2017-02-16</actionDate>
          <text><![CDATA[
Medicaid Cost-Sharing Waiver Flexibility Act of 2017

This bill amends title XIX (Medicaid) of the Social Security Act to allow a state Medicaid program operating under a waiver to impose cost sharing or similar charges with respect to individuals who qualify for medical assistance for reasons other than being aged, blind, or disabled. Current law allows a program to impose such charges only if the waiver is for a demonstration project that meets specified requirements.
]]></text>
          <versionCode>00</versionCode>
          <actionDesc>Introduced in House</actionDesc>
          <name>Introduced in House</name>
        </item>
      </billSummaries>
    </summaries>
    <title>Medicaid Cost-Sharing Waiver Flexibility Act of 2017</title>
    <updateDate>2017-06-19T21:15:31Z</updateDate>
    <laws />
    <billType>HR</billType>
    <recordedVotes />
    <calendarNumbers />
    <latestAction>
      <links />
      <text>Referred to the Subcommittee on Health.</text>
      <actionDate>2017-02-17</actionDate>
    </latestAction>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
package v1beta1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	kmapi "kmodules.xyz/client-go/api/v1"
)

const (
	ResourceKindBackupSession     = "BackupSession"
	ResourceSingularBackupSession = "backupsession"
	ResourcePluralBackupSession   = "backupsessions"
)

// +genclient
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// +kubebuilder:object:root=true
// +kubebuilder:resource:path=backupsessions,singular=backupsession,categories={stash,appscode,all}
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Invoker-Type",type="string",JSONPath=".spec.invoker.kind"
// +kubebuilder:printcolumn:name="Invoker-Name",type="string",JSONPath=".spec.invoker.name"
// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase"
// +kubebuilder:printcolumn:name="Duration",type="string",JSONPath=".status.sessionDuration"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp"
type BackupSession struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	Spec              BackupSessionSpec   `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
	Status            BackupSessionStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

type BackupSessionSpec struct {
	// Invoker refers to the BackupConfiguration or BackupBatch being used to invoke this backup session
	// +optional
	Invoker BackupInvokerRef `json:"invoker,omitempty" protobuf:"bytes,1,opt,name=invoker"`
}

// +kubebuilder:validation:Enum=Pending;Skipped;Running;Succeeded;Failed;Unknown
type BackupSessionPhase string

const (
	BackupSessionPending   BackupSessionPhase = "Pending"
	BackupSessionSkipped   BackupSessionPhase = "Skipped"
	BackupSessionRunning   BackupSessionPhase = "Running"
	BackupSessionSucceeded BackupSessionPhase = "Succeeded"
	BackupSessionFailed    BackupSessionPhase = "Failed"
	BackupSessionUnknown   BackupSessionPhase = "Unknown"
)

// +kubebuilder:validation:Enum=Succeeded;Failed
type HostBackupPhase string

const (
	HostBackupSucceeded HostBackupPhase = "Succeeded"
	HostBackupFailed    HostBackupPhase = "Failed"
)

// +kubebuilder:validation:Enum=Pending;Succeeded;Running;Failed
type TargetPhase string

const (
	TargetBackupPending   TargetPhase = "Pending"
	TargetBackupSucceeded TargetPhase = "Succeeded"
	TargetBackupRunning   TargetPhase = "Running"
	TargetBackupFailed    TargetPhase = "Failed"
)

type BackupSessionStatus struct {
	// Phase indicates the overall phase of the backup process for this BackupSession. Phase will be "Succeeded" only if
	// phase of all hosts are "Succeeded". If any of the host fail to complete backup, Phase will be "Failed".
	// +optional
	Phase BackupSessionPhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=BackupSessionPhase"`
	// SessionDuration specify total time taken to complete current backup session (sum of backup duration of all targets)
	// +optional
	SessionDuration string `json:"sessionDuration,omitempty" protobuf:"bytes,2,opt,name=sessionDuration"`
	// Targets specify the backup status of individual targets
	// +optional
	Targets []BackupTargetStatus `json:"targets,omitempty" protobuf:"bytes,3,rep,name=targets"`
	// Conditions shows condition of different operations/steps of the backup process
	// +optional
	Conditions []kmapi.Condition `json:"conditions,omitempty" protobuf:"bytes,4,rep,name=conditions"`
}

type BackupTargetStatus struct {
	// Ref refers to the backup target
	// +optional
	Ref TargetRef `json:"ref,omitempty" protobuf:"bytes,1,opt,name=ref"`
	// TotalHosts specifies total number of hosts for this target that will be backed up for a BackupSession
	// +optional
	TotalHosts *int32 `json:"totalHosts,omitempty" protobuf:"varint,2,opt,name=totalHosts"`
	// Phase indicates backup phase of this target
	// +optional
	Phase TargetPhase `json:"phase,omitempty" protobuf:"bytes,3,opt,name=phase"`
	// Stats shows statistics of individual hosts for this backup session
	// +optional
	Stats []HostBackupStats `json:"stats,omitempty" protobuf:"bytes,4,rep,name=stats"`
	// PreBackupActions specifies a list of actions that the backup process should execute before taking backup
	// +optional
	PreBackupActions []string `json:"preBackupActions,omitempty" protobuf:"bytes,5,rep,name=preBackupActions"`
	// PostBackupActions specifies a list of actions that the backup process should execute after taking backup
	// +optional
	PostBackupActions []string `json:"postBackupActions,omitempty" protobuf:"bytes,6,rep,name=postBackupActions"`
}

type HostBackupStats struct {
	// Hostname indicate name of the host that has been backed up
	// +optional
	Hostname string `json:"hostname,omitempty" protobuf:"bytes,1,opt,name=hostname"`
	// Phase indicates backup phase of this host
	// +optional
	Phase HostBackupPhase `json:"phase,omitempty" protobuf:"bytes,2,opt,name=phase,casttype=HostBackupPhase"`
	// Snapshots specifies the stats of individual snapshots that has been taken for this host in current backup session
	// +optional
	Snapshots []SnapshotStats `json:"snapshots,omitempty" protobuf:"bytes,3,rep,name=snapshots"`
	// Duration indicates total time taken to complete backup for this hosts
	// +optional
	Duration string `json:"duration,omitempty" protobuf:"bytes,4,opt,name=duration"`
	// Error indicates string value of error in case of backup failure
	// +optional
	Error string `json:"error,omitempty" protobuf:"bytes,5,opt,name=error"`
}

type SnapshotStats struct {
	// Name indicates the name of the backup snapshot created for this host
	Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`
	// Path indicates the directory that has been backed up in this snapshot
	Path string `json:"path,omitempty" protobuf:"bytes,2,opt,name=path"`
	// TotalSize indicates the size of data to backup in target directory
	TotalSize string `json:"totalSize,omitempty" protobuf:"bytes,7,opt,name=totalSize"`
	// Uploaded indicates size of data uploaded to backend for this snapshot
	Uploaded string `json:"uploaded,omitempty" protobuf:"bytes,4,opt,name=uploaded"`
	// ProcessingTime indicates time taken to process the target data
	ProcessingTime string `json:"processingTime,omitempty" protobuf:"bytes,5,opt,name=processingTime"`
	// FileStats shows statistics of files of this snapshot
	FileStats FileStats `json:"fileStats,omitempty" protobuf:"bytes,6,opt,name=fileStats"`
}

type FileStats struct {
	// TotalFiles shows total number of files that has been backed up
	TotalFiles *int64 `json:"totalFiles,omitempty" protobuf:"varint,1,opt,name=totalFiles"`
	// NewFiles shows total number of new files that has been created since last backup
	NewFiles *int64 `json:"newFiles,omitempty" protobuf:"varint,2,opt,name=newFiles"`
	// ModifiedFiles shows total number of files that has been modified since last backup
	ModifiedFiles *int64 `json:"modifiedFiles,omitempty" protobuf:"varint,3,opt,name=modifiedFiles"`
	// UnmodifiedFiles shows total number of files that has not been changed since last backup
	UnmodifiedFiles *int64 `json:"unmodifiedFiles,omitempty" protobuf:"varint,4,opt,name=unmodifiedFiles"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type BackupSessionList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	Items           []BackupSession `json:"items,omitempty" protobuf:"bytes,2,rep,name=items"`
}


text:
.. Documentation master file, created by
   sphinx-quickstart on Mon Jul  4 22:43:48 2016.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Laboratorium N250
==================================================================

Laboratorium N250 oleh PSTI Universitas Bandar Lampung.

Silakan baca atau unduh PDFnya di http://labn250.readthedocs.io/. Dokumentasi ini merupakan hasil *build* otomatis dari repository GitHub dokumentasi kolaboratif di https://github.com/kampusubl/laboratorium-n250.

Daftar Isi:

.. toctree::
   :maxdepth: 3

   fikta2016/index

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`