text:
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "hm_parser.h"

#include "hm_buffer.h"

#include "hm_array.h"

#include "http-parser/http_parser.h"

#define MIN_BUFFER_SPACE 1024

#define MAX_HEADERS 512
#define INIT_HEADERS 8
#define GROW_HEADERS 8

#define MAX_CHUNKS 512
#define INIT_CHUNKS 16
#define GROW_CHUNKS 16

#define MAX_PIECES  4096
#define INIT_PIECES ((INIT_HEADERS * 2) + INIT_CHUNKS)
#define GROW_PIECES 128

typedef enum {
	hm_piece_url = 0,
	hm_piece_header_field,
	hm_piece_header_value,
	hm_piece_body,
	hm_piece_none,
} hm_piece_t;

#define HM_PIECE_INVALID (UINT16_MAX)

typedef struct HMPiece HMPiece;

struct HMPiece {
	hm_len_t    start;  /**< offset to start of piece in the buffer. */
	hm_len_t    end;    /**< offset to end of piece in the buffer. */
};

/**
 * HTTP message object.
 *
 * @ingroup Objects
 */
struct HMParser {
	http_parser parser;   /**< embedded http_parser. */
	HMPiece       *pieces;
	uint32_t      state: 10;
	uint32_t      last_id: 3;
	uint32_t      is_eof: 1;
	/* HTTP Message fields. */
	hm_idx_t      url_idx;
	hm_idx_t      headers_start;
	hm_idx_t      headers_end;
	hm_idx_t      body_start;
	hm_idx_t      body_end;

	hm_len_t      parsed_off;   /**< http parser offset. */
	hm_len_t      buf_len;      /**< number of bytes in buffer. */
	HMBuffer      *buf;         /**< buffer to hold raw http message. */
	/* tmp data */
	HMHeader tmp_header;
};

static void hm_parser_clear_message(HMParser *hm_parser) {
	/* clear parser state. */
	hm_parser->state = HM_PARSER_STATE_NONE;
	hm_parser->last_id = hm_piece_none;
	/* clear HTTP Message fields */
	hm_array_set_count(hm_parser->pieces, 0);
	hm_parser->url_idx = HM_PIECE_INVALID;
	hm_parser->headers_start = HM_PIECE_INVALID;
	hm_parser->headers_end = HM_PIECE_INVALID;
	hm_parser->body_start = HM_PIECE_INVALID;
	hm_parser->body_end = HM_PIECE_INVALID;
}

static HMParser *hm_parser_new(int is_request) {
	HMParser* hm_parser;
	http_parser* parser;

	hm_parser = (HMParser *)malloc(sizeof(HMParser));
	/* init. http parser. */
	parser = &(hm_parser->parser);
	if(is_request) {
		parser->type = HTTP_REQUEST;
	} else {
		parser->type = HTTP_RESPONSE;
	}
	/* allocate piece array. */
	hm_array_new(hm_parser->pieces, INIT_PIECES);
	/* allocate buffer. */
	hm_parser->buf = hm_buffer_new(MIN_BUFFER_SPACE);

	/* initialize parser state. */
	hm_parser_reset(hm_parser);

	return hm_parser;
}

HMParser *hm_parser_new_response() {
	return hm_parser_new(0);
}

HMParser *hm_parser_new_request() {
	return hm_parser_new(1);
}

static void hm_parser_compact_buffer(HMParser *hm_parser, size_t offset) {
	size_t len = hm_parser->buf_len;

	/* Trim some data from the start of the buffer. */
	if(offset < len) {
		/* Compact the buffer. */
		char *data = (char *)hm_buffer_data(hm_parser->buf);
		len -= offset;
		memmove(data, data + offset, len);
		hm_parser->parsed_off -= offset;
		hm_parser->buf_len = len;
	} else {
		/* Trimmed the whole buffer. */
		hm_parser->parsed_off = 0;
		hm_parser->buf_len = 0;
	}
}

void hm_parser_next_message(HMParser *hm_parser) {
	/* remove previous message from buffer. */
	hm_parser_compact_buffer(hm_parser, hm_parser->parsed_off);

	hm_parser_clear_message(hm_parser);
}

void hm_parser_reset(HMParser* hm_parser) {
	http_parser* parser = &(hm_parser->parser);

	http_parser_init(parser, parser->type);
	parser->data = (char *)hm_buffer_data(hm_parser->buf);
	/* clear buffer state. */
	hm_parser->parsed_off = 0;
	hm_parser->buf_len = 0;
	hm_parser->is_eof = false;

	hm_parser_clear_message(hm_parser);
}

void hm_parser_free(HMParser* hm_parser) {
	hm_buffer_free(hm_parser->buf);
	hm_parser->buf = NULL;
	hm_array_free(hm_parser->pieces);
	hm_parser->pieces = NULL;
	free(hm_parser);
}

/* in-place string tolower, for HTTP headers. */
static void hm_str_lower(char *p, size_t len) {
	char *p_end = p + len;
	for(; p < p_end; p++) {
		char c = *p;
		if(c >= 'A' && c <= 'Z') {
			*p = c + 32;
		}
	}
}

#define HM_PARSER_ARY_GROW_CHECK(hm_parser, _ary, _idx, _grow, _max) do { \
	typeof((hm_parser)->_ary) ary = (hm_parser)->_ary; \
	size_t count = hm_array_count(ary); \
	size_t cap = hm_array_capacity(ary); \
	(_idx) = count; \
	count++; \
	if(count >= cap) { \
		if(cap == (_max)) { \
			return -1; \
		} else { \
			cap += (_grow); \
			if(cap > (_max)) cap = (_max); \
			hm_array_resize(ary, cap); \
			if(ary == NULL) return -1; \
			(hm_parser)->_ary = ary; \
		} \
	} \
	hm_array_set_count(ary, count); \
} while(0)

#define HM_PARSER_PIECES_GROW_CHECK(hm_parser, _idx) \
	HM_PARSER_ARY_GROW_CHECK(hm_parser, pieces, _idx, GROW_PIECES, MAX_PIECES)

/* push piece. */
static int http_push_piece(http_parser* parser, hm_piece_t piece_id, const char *data, size_t len) {
	HMParser *hm_parser = (HMParser*)parser;
	const char *data_start = (const char *)parser->data;
	size_t start = data - data_start;
	uint32_t idx;
	HMPiece *piece;
	bool append_to_last = false;

	/* check if we need to append data to last piece. */
	if(hm_parser->last_id == piece_id) {
		append_to_last = true;
		/* don't merge large body pieces. */
		if(piece_id == hm_piece_body && len > 512) {
			append_to_last = false;
		}
	}

	if(append_to_last) {
		size_t end;
		/* append data to last piece. */
		idx = hm_array_count(hm_parser->pieces) - 1;
		piece = hm_parser->pieces + idx;
		/* check for buffer gaps. */
		end = piece->end;
		if(end != start) {
			char *end_ptr = ((char *)parser->data) + end;
			/* close gap for this piece. */
			memmove(end_ptr, data, len);
		}
		piece->end = end + len;
		return 0;
	}

	/* start new piece. */
	HM_PARSER_PIECES_GROW_CHECK(hm_parser, idx);

	hm_parser->last_id = piece_id;

	/* initialize new piece. */
	piece = hm_parser->pieces + idx;
	piece->start = start;
	piece->end = start + len;
	return 0;
}

static int hm_parser_message_begin_cb(http_parser* parser) {
	HMParser *hm_parser = (HMParser*)parser;
	if(hm_parser->state != HM_PARSER_STATE_NONE) {
		hm_parser_clear_message(hm_parser);
	}
	hm_parser->state = HM_PARSER_STATE_MESSAGE_BEGIN;
	hm_parser->last_id = hm_piece_none;
	return 0;
}

static int hm_parser_status_complete_cb(http_parser* parser) {
	HMParser *hm_parser = (HMParser*)parser;
	hm_parser->state = HM_PARSER_STATE_STATUS_COMPLETE;
	hm_parser->last_id = hm_piece_none;
	return 0;
}

static int hm_parser_url_cb(http_parser* parser, const char* data, size_t len) {
	HMParser *hm_parser = (HMParser*)parser;
	hm_parser->state = HM_PARSER_STATE_URL;
	if(hm_parser->url_idx == HM_PIECE_INVALID) {
		hm_parser->url_idx = hm_array_count(hm_parser->pieces);
	}
	return http_push_piece(parser, hm_piece_url, data, len);
}

static int hm_parser_header_field_cb(http_parser* parser, const char* data, size_t len) {
	HMParser *hm_parser = (HMParser*)parser;
	if(hm_parser->state >= HM_PARSER_STATE_HEADERS_COMPLETE) {
		/* ignore Trailers for now. */
		return 0;
	}
	hm_parser->state = HM_PARSER_STATE_HEADERS;
	if(hm_parser->headers_start == HM_PIECE_INVALID) {
		hm_parser->headers_start = hm_array_count(hm_parser->pieces);
		hm_parser->headers_end = hm_parser->headers_start;
	}
	return http_push_piece(parser, hm_piece_header_field, data, len);
}

static int hm_parser_header_value_cb(http_parser* parser, const char* data, size_t len) {
	HMParser *hm_parser = (HMParser*)parser;
	if(hm_parser->state >= HM_PARSER_STATE_HEADERS_COMPLETE) {
		/* ignore Trailers for now. */
		return 0;
	}
	hm_parser->state = HM_PARSER_STATE_HEADERS;
	return http_push_piece(parser, hm_piece_header_value, data, len);
}

static int hm_parser_headers_complete_cb(http_parser* parser) {
	HMParser *hm_parser = (HMParser*)parser;
	hm_parser->state = HM_PARSER_STATE_HEADERS_COMPLETE;
	hm_parser->last_id = hm_piece_none;
	/* mark end of headers. */
	if(hm_parser->headers_start != HM_PIECE_INVALID) {
		hm_parser->headers_end = hm_array_count(hm_parser->pieces);
	}
	if(parser->type == HTTP_RESPONSE) {
		http_parser_pause(parser, 1);
	}
	return 0;
}

static int hm_parser_body_cb(http_parser* parser, const char* data, size_t len) {
	HMParser *hm_parser = (HMParser*)parser;
	hm_parser->state = HM_PARSER_STATE_BODY;
	if(len == 0) return 0;
	/* mark start of body pieces. */
	if(hm_parser->body_start == HM_PIECE_INVALID) {
		hm_parser->body_start = hm_array_count(hm_parser->pieces);
		hm_parser->body_end = hm_parser->body_start;
		hm_parser->last_id = hm_piece_none;
	}
	return http_push_piece(parser, hm_piece_body, data, len);
}

static int hm_parser_message_complete_cb(http_parser* parser) {
	HMParser *hm_parser = (HMParser*)parser;
	hm_parser->state = HM_PARSER_STATE_MESSAGE_COMPLETE;
	hm_parser->last_id = hm_piece_none;
	http_parser_pause(parser, 1);
	return 0;
}

static int hm_parser_resume_parse(HMParser *hm_parser, char *data, size_t data_len) {
	http_parser*  parser = &(hm_parser->parser);

	static const http_parser_settings settings = {
		.on_message_begin    = hm_parser_message_begin_cb,
		.on_url              = hm_parser_url_cb,
		.on_status_complete  = hm_parser_status_complete_cb,
		.on_header_field     = hm_parser_header_field_cb,
		.on_header_value     = hm_parser_header_value_cb,
		.on_headers_complete = hm_parser_headers_complete_cb,
		.on_body             = hm_parser_body_cb,
		.on_message_complete = hm_parser_message_complete_cb
	};

	/* resume http parser. */
	size_t nparsed = http_parser_execute(parser, &settings, data, data_len);
	if(nparsed > 0) {
		hm_parser->parsed_off += nparsed;
		if(hm_parser->state == HM_PARSER_STATE_HEADERS) {
			hm_parser->headers_end = hm_array_count(hm_parser->pieces);
		}
		if(hm_parser->state == HM_PARSER_STATE_BODY) {
			hm_parser->body_end = hm_array_count(hm_parser->pieces);
		}
	}
	/* check for error. */
	if(parser->http_errno != HPE_OK) {
		/* check if parser was paused. */
		if(parser->http_errno == HPE_PAUSED) {
			/* resume parser. */
			http_parser_pause(parser, 0);
			/* check if buffer is also empty. */
			if(hm_parser->parsed_off == hm_parser->buf_len) {
				hm_parser->state |= HM_PARSER_STATE_NEEDS_INPUT;
			}
		} else {
			/* return -1 to indicate a parser error. */
			hm_parser->state |= HM_PARSER_STATE_ERROR;
		}
		return -1;
	}

	return nparsed;
}

size_t hm_parser_prepare_buffer(HMParser *hm_parser, size_t len) {
	HMBuffer *buf = hm_parser->buf;
	size_t cap = hm_buffer_capacity(buf);
	size_t buf_len = hm_parser->buf_len;
	size_t available;
	/* buffer length should never be larger then the current capacity. */
	assert(cap >= buf_len);
	available = cap - buf_len;
	/* check if we should try to grow the buffer. */
	if(available < len) {
		size_t new_cap = buf_len + len;
		/* check for overflow. */
		if(new_cap <= buf_len) {
			/* ignore bad request to grow buffer. */
			return 0; /* return zero to signal bad value. */
		}
		buf = hm_buffer_resize(buf, new_cap);
		if(buf) {
			/* update parser's buffer. */
			hm_parser->buf = buf;
			hm_parser->parser.data = (char *)hm_buffer_data(buf);
			cap = hm_buffer_capacity(buf);
			available = cap - buf_len;
		} else {
			/* failed to grow buffer. */
			available = 0;
		}
	}
	return available;
}

uint8_t *hm_parser_get_buffer(HMParser *hm_parser) {
	uint8_t *data = hm_buffer_data(hm_parser->buf);
	data += hm_parser->buf_len;
	return data;
}

size_t hm_parser_get_buffer_capacity(HMParser *hm_parser) {
	size_t cap = hm_buffer_capacity(hm_parser->buf);
	cap -= hm_parser->buf_len;
	return cap;
}

size_t hm_parser_append_data(HMParser *hm_parser, const char *data, size_t len) {
	size_t space = hm_parser_prepare_buffer(hm_parser, len);
	if(space < len) {
		len = space;
	}
	memcpy(hm_parser_get_buffer(hm_parser), data, len);
	hm_parser->buf_len += len;
	hm_parser->state &= ~HM_PARSER_STATE_NEEDS_INPUT;

	return len;
}

bool hm_parser_append_buffer_bytes(HMParser *hm_parser, size_t len) {
	size_t cap = hm_buffer_capacity(hm_parser->buf);
	size_t buf_len = hm_parser->buf_len;
	size_t new_len = buf_len + len;
	/* check for integer/capacity overflow. */
	if(new_len < buf_len || new_len > cap) {
		/* invalid `len` value. */
		return false;
	}
	hm_parser->buf_len = new_len;
	hm_parser->state &= ~HM_PARSER_STATE_NEEDS_INPUT;
	return true;
}

void hm_parser_eof(HMParser *hm_parser) {
	hm_parser->is_eof = true;
	/* remove the NEEDS_INPUT flag to allow parser to resume. */
	hm_parser->state &= ~HM_PARSER_STATE_NEEDS_INPUT;
}

int hm_parser_execute(HMParser* hm_parser) {
	char *data = hm_parser->parser.data;
	size_t data_len = hm_parser->buf_len;
	size_t parsed_off = hm_parser->parsed_off;
	int rc = 0;

	/* check if parser needs input or is already in an error state. */
	if(hm_parser->state & (HM_PARSER_STATE_NEEDS_INPUT|HM_PARSER_STATE_ERROR)) {
		return hm_parser->state;
	}

	/* Calculate how much data is unparsed. */
	data_len -= parsed_off;
	data += parsed_off;

	if(data_len > 0) {
		/* have data to parse. */
		rc = hm_parser_resume_parse(hm_parser, data, data_len);
		if(rc < 0) {
			/* paused or error. */
			return hm_parser->state;
		}
		data_len -= rc;
		if(data_len == 0 && hm_parser->is_eof) {
			data += rc;
			/* finished parsing buffer.  Now signal EOF. */
			hm_parser_resume_parse(hm_parser, data, 0);
			hm_parser->state |= HM_PARSER_STATE_NEEDS_INPUT;
		}
	} else {
		if(hm_parser->is_eof) {
			/* signal EOF. */
			hm_parser_resume_parse(hm_parser, data, 0);
			hm_parser->state |= HM_PARSER_STATE_NEEDS_INPUT;
		} else {
			/* need data. */
			hm_parser->state |= HM_PARSER_STATE_NEEDS_INPUT;
		}
	}

	return hm_parser->state;
}

const char *hm_parser_get_url(HMParser *hm_parser, size_t *len) {
	const char *str = NULL;
	hm_idx_t idx = hm_parser->url_idx;
	assert(len != NULL);
	if(idx != HM_PIECE_INVALID) {
		HMPiece *piece = hm_parser->pieces + idx;
		str = hm_parser->parser.data + piece->start;
		*len = piece->end - piece->start;
	}
	return str;
}

uint32_t hm_parser_count_headers(HMParser *hm_parser) {
	uint32_t headers_start = hm_parser->headers_start;
	uint32_t headers_end = hm_parser->headers_end;
	assert(headers_start <= headers_end);
	if(headers_start == HM_PIECE_INVALID) {
		return 0;
	}
	return (headers_end - headers_start) >> 1;
}

void hm_parser_clear_headers(HMParser *hm_parser) {
	hm_parser->headers_start = HM_PIECE_INVALID;
	hm_parser->headers_end = HM_PIECE_INVALID;
}

#include "hm_header_ids.h"

HMHeader *hm_parser_get_header(HMParser *hm_parser, uint32_t idx) {
	HMHeader *head = NULL;
	uint32_t headers_start = hm_parser->headers_start;
	uint32_t headers_end = hm_parser->headers_end;
	uint32_t count = headers_end - headers_start;
	const hm_header_id *id;
	HMPiece  *piece;
	char *data;
	char *name;
	size_t name_len;

	/* check for headers. */
	if(headers_start == HM_PIECE_INVALID) {
		/* no headers. */
		return head;
	}
	/* validate 'idx'. */
	idx *= 2; /* each header has two pieces. */
	if(idx >= count) {
		/* idx out of bounds. */
		return head;
	}
	idx += headers_start;

	/* get name & value pieces. */
	data = hm_parser->parser.data;
	piece = hm_parser->pieces + idx;

	/* fill tmp. HMHeader. */
	head = &(hm_parser->tmp_header);
	name = data + piece->start;
	name_len = piece->end - piece->start;
	/* lookup header in id map. */
	id = hm_header_ids_lookup(name, name_len);
	if(id) {
		/* found common header, use id for faster processing. */
		head->name_id = id->id;
		head->name = NULL;
		head->name_len = 0;
	} else {
		/*
		 * Convert unknown HTTP headers to lower case.
		 */
		hm_str_lower(name, name_len);
		head->name = name;
		head->name_len = name_len;
	}
	piece++;
	head->value = data + piece->start;
	head->value_len = piece->end - piece->start;

	return head;
}

const char *hm_parser_next_body(HMParser *hm_parser, size_t *len) {
	const char *str = NULL;
	hm_idx_t idx = hm_parser->body_start;
	assert(len != NULL);
	if(idx != HM_PIECE_INVALID) {
		HMPiece *piece = hm_parser->pieces + idx;
		str = hm_parser->parser.data + piece->start;
		*len = piece->end - piece->start;
		/* consume piece. */
		idx++;
		if(idx >= hm_parser->body_end) {
			idx = HM_PIECE_INVALID; /* no more pieces. */
			hm_parser->body_end = HM_PIECE_INVALID;
		}
		hm_parser->body_start = idx;
	}
	return str;
}

int hm_parser_should_keep_alive(HMParser *hm_parser) {
	return http_should_keep_alive(&hm_parser->parser);
}

int hm_parser_is_upgrade(HMParser *hm_parser) {
	return hm_parser->parser.upgrade;
}

int hm_parser_method(HMParser *hm_parser) {
	return hm_parser->parser.method;
}

const char *hm_parser_method_str(HMParser *hm_parser) {
	return http_method_str(hm_parser->parser.method);
}

int hm_parser_version(HMParser *hm_parser) {
	return ((hm_parser->parser.http_major) << 16) + (hm_parser->parser.http_minor);
}

int hm_parser_status_code(HMParser *hm_parser) {
	return hm_parser->parser.status_code;
}

int hm_parser_is_error(HMParser *hm_parser) {
	return (hm_parser->parser.http_errno != HPE_OK && hm_parser->parser.http_errno != HPE_PAUSED);
}

int hm_parser_error(HMParser *hm_parser) {
	return hm_parser->parser.http_errno;
}

const char *hm_parser_error_name(HMParser *hm_parser) {
	return http_errno_name(hm_parser->parser.http_errno);
}

const char *hm_parser_error_description(HMParser *hm_parser) {
	return http_errno_description(hm_parser->parser.http_errno);
}


text:
define([
    '../index.js',
    './demo-ctrl',
    './demo-state'
], function (rbOverlayModeless, demoCtrl, demoState) {
    var demo = angular
        .module('rb-overlay-modeless-demo', [
            rbOverlayModeless.name
        ])
        .config(demoState)
        .controller('demo-rb-overlay-modeless-ctrl', demoCtrl);

    return demo;
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Engine.StateManagement.EntityManagement.Entity;

namespace Engine.Graphics.Renderer
{
    /// <summary>
    /// This object handling the rendering so that everything rendered at the same time.  Instead of ones and twos
    /// </summary>
    public class GraphicsQueueRenderer : GraphicsRenderer
    {
        private Queue<IDrawable> drawTargets;

        public GraphicsQueueRenderer()
        {

        }
        /// <summary>
        /// The goal of this method is to draw the elements registered in batches.
        /// </summary>
        /// <param name="gameTime"></param>
        public void batchDraw(GameTime gameTime)
        {
            if(drawTargets == null)
                return;

            var spritebatch = SpriteBatchSingleton.SingleSpriteBatch;
            //order by draw order.
            //TODO: Verify that this does the proper ordering
            drawTargets.OrderBy(x => x.DrawOrder);
            var drawElements = new Queue<IDrawable>(drawTargets);
            Console.WriteLine("Number of drawElements = " + drawElements.Count);
            spritebatch.Begin();
            //okay now we need to iterate based on draw order and draw each element.
            foreach (IDrawable element in drawElements)
            {
                //tell the element to draw itself.
                element.Draw(gameTime);
            }

            spritebatch.End();

            //we now need to clear the queue elements.
            drawTargets.Clear();
        }

        public void registerDrawable(IDrawable d)
        {
            if (drawTargets == null)
            {
                drawTargets = new Queue<IDrawable>();
            }

            drawTargets.Enqueue(d);
        }

       public void registerDrawableEntity(IEntity d)
        {
            if (d.isDrawable())
            {
                registerDrawable(d.getDrawable());
            }
        }
    }
}


text:
package eu.mosaic_cloud.connectors.mq.core.callbacks;

import eu.mosaic_cloud.callbacks.core.CallbackArguments;
import eu.mosaic_cloud.connectors.mq.core.ResourceAccessor;

public abstract class ResourceAccessorCallbackArguments<_Accessor_ extends ResourceAccessor, _Type_ extends ResourceAccessorCallbackType>
		implements
			CallbackArguments
{
	ResourceAccessorCallbackArguments (final _Accessor_ accessor, final _Type_ type)
	{
		super ();
		this.accessor = accessor;
		this.type = type;
	}

	public final _Accessor_ accessor;
	public final _Type_ type;
}


text:
Package.describe({
  summary: 'A meteor package that makes social sharing easy',
  git: 'https://github.com/meteorclub/shareit',
  version: '1.0.2',
  name: "joshowens:shareit"
});

Package.onUse(function(api) {
  api.versionsFrom("METEOR@1.2");
  api.use(['less', 'templating', 'underscore', 'jquery'], 'client');
  api.use(['fortawesome:fontawesome@4.2.0'], 'client');

  api.imply('spiderable', ['client', 'server']);
  api.addFiles([
    'shareit.js',
    'client/views/social.html',
    'client/views/social.js',
    'client/views/social.less',
    'client/views/facebook/facebook.html',
    'client/views/facebook/facebook.js',
    'client/views/twitter/twitter.html',
    'client/views/twitter/twitter.js',
    'client/views/googleplus/googleplus.html',
    'client/views/googleplus/googleplus.js',
    'client/views/pinterest/pinterest.html',
    'client/views/pinterest/pinterest.js'
  ], 'client');

  api.export('ShareIt', 'client');
});

Package.onTest(function (api) {
  api.use(['tinytest',
    'test-helpers',
    'templating',
    ])
    api.use('joshowens:shareit');

  api.addFiles([
    'tests/client.html',
    'tests/client.js'
  ], 'client');
});


text:
using namespace wotreplay;

const std::vector<packet_t> &game_t::get_packets() const {
    return packets;
}

const std::string &game_t::get_map_name() const {
    return arena.name;
}

const std::string &game_t::get_game_mode() const {
    return game_mode;
}

const arena_t &game_t::get_arena() const {
    return arena;
}

const std::set<int> &game_t::get_team(int team_id) const {
    return teams[team_id];
}

uint32_t game_t::get_recorder_id() const {
    return recorder_id;
}

bool game_t::find_property(uint32_t clock, uint32_t player_id, property_t property, packet_t &out) const {
    // inline function function for using with stl to finding the range with the same clock
    auto has_same_clock = [&](const packet_t &target) -> bool  {
        // packets without clock are included
        return target.has_property(property_t::clock)
            && target.clock() == clock;
    };

    // find first packet with same clock
    auto it_clock_begin = std::find_if(packets.cbegin(), packets.cend(), has_same_clock);
    // find last packet with same clock
    auto it_clock_end = std::find_if_not(it_clock_begin, packets.cend(), has_same_clock);

    auto is_related_with_property = [&](const packet_t &target) -> bool {
        return target.has_property(property_t::clock) &&
            target.has_property(property_t::player_id) &&
            target.has_property(property) &&
            target.player_id() == player_id;
    };

    auto it = std::find_if(it_clock_begin, it_clock_end, is_related_with_property);
    bool found = it != it_clock_end;

    if (!found) {
        auto result_after = std::find_if(it_clock_end, packets.end(), is_related_with_property);
        auto it_clock_rbegin = packets.crbegin() + (packets.size() - (it_clock_begin - packets.begin()));
        auto result_before = std::find_if(it_clock_rbegin, packets.crend(), is_related_with_property);

        if(result_after != packets.cend() && result_before != packets.crend()) {
            // if both iterators point to items within the collection
            auto cmp_by_clock = [](const packet_t &left, const packet_t &right) -> int {
                return left.clock() <= right.clock();
            };
            out = std::min(*result_before, *result_after, cmp_by_clock);
            found = true;
        } else if (result_after == packets.end() && result_before != packets.rend()) {
            // only result_before points to item in collection
            out = *result_before;
            found = true;
        } else if (result_after != packets.end() && result_before == packets.rend()) {
            // only result_after points to item in collection
            out = *result_after;
            found = true;
        }
    } else {
        out = *it;
    }

    return found;
}

int game_t::get_team_id(int player_id) const {
    auto it = std::find_if(teams.begin(), teams.end(), [&](const std::set<int> &team) {
        return team.find(player_id) != team.end();
    });
    return it == teams.end() ? -1 : (static_cast<int>(it - teams.begin()));
}

const version_t &game_t::get_version() const {
    return version;
}

const buffer_t &game_t::get_game_begin() const {
    return game_begin;
}

const buffer_t &game_t::get_game_end() const {
    return game_end;
}

const buffer_t &game_t::get_raw_replay() const {
    return replay;
}

void wotreplay::write_parts_to_file(const game_t &game) {
    std::ofstream game_begin("out/game_begin.json", std::ios::binary | std::ios::ate);
    std::copy(game.get_game_begin().begin(),
              game.get_game_begin().end(),
              std::ostream_iterator<char>(game_begin));
    game_begin.close();

    std::ofstream game_end("out/game_end.json", std::ios::binary | std::ios::ate);
    std::copy(game.get_game_end().begin(),
              game.get_game_end().end(),
              std::ostream_iterator<char>(game_end));
    game_end.close();

    std::ofstream replay_content("out/replay.dat", std::ios::binary | std::ios::ate);
    std::copy(game.get_raw_replay().begin(),
              game.get_raw_replay().end(),
              std::ostream_iterator<char>(replay_content));
}

std::tuple<float, float> wotreplay::get_2d_coord(const std::tuple<float, float, float> &position, const bounding_box_t &bounding_box, int width, int height)
{
    float min_x, max_x, min_y, max_y;
    std::tie(min_x, min_y) = bounding_box.bottom_left;
    std::tie(max_x, max_y) = bounding_box.upper_right;
    // std::tie(x,z,y) = position;
    float x = std::get<0>(position);
    float y = std::get<2>(position);
    x = (x - min_x) * (width - 1) / (max_x - min_x + 1)  ;
    y = (max_y - y) * (height - 1) / (max_y - min_y + 1) ;
    return std::make_tuple(x,y);
}

void wotreplay::show_map_boundaries(const game_t &game, const std::vector<packet_t> &packets) {
    float min_x = 0.f,
        min_y = 0.f,
        max_x = 0.f,
        max_y = 0.f;

    for (const packet_t &packet : packets) {
        if (packet.type() != 0xa) {
            continue;
        }

        uint32_t player_id = packet.player_id();
        // only take into account positions of 'valid' players.
        if (game.get_team_id(player_id) != -1) {
            // update the boundaries
            auto position = packet.position();
            min_x = std::min(min_x, std::get<0>(position));
            min_y = std::min(min_y, std::get<2>(position));
            max_x = std::max(max_x, std::get<0>(position));
            max_y = std::max(max_y, std::get<2>(position));
            break;
        }
    }

    printf("The boundaries of used positions in this replay are: min_x = %f max_x = %f min_y = %f max_y = %f\n", min_x, max_x, min_y, max_y);
}

version_t::version_t(const std::string & text)
    : text(text)
{
    regex re(R"(v\.(\d+)\.(\d+)\.(\d+))");
    smatch match;
    if (regex_search(text, match, re)) {
        major = boost::lexical_cast<int>(match[2]);
        minor = boost::lexical_cast<int>(match[3]);
    } else {
        regex re(R"((\d+)[\.,] *(\d+)[\.,] *(\d+)[\.,]? *(\d+))");
        if (regex_search(text, match, re)) {
            major = boost::lexical_cast<int>(match[2]);
            minor = boost::lexical_cast<int>(match[3]);
        } else {
            major = 0;
            minor = 0;
        }
    }
}

double wotreplay::dist(const std::tuple<float, float, float> &begin,
                   const std::tuple<float, float, float> &end) {
    float dy = std::get<2>(begin) - std::get<2>(end),
    dx = std::get<0>(begin) - std::get<0>(end),
    dz = std::get<1>(begin) - std::get<1>(end);

    return std::sqrt(dy * dy + dx * dx);
}

int wotreplay::get_start_packet (const game_t &game, double skip) {
    std::unordered_map<int, packet_t> last_packets;
    int i = 0;

    for (const auto &packet : game.get_packets()) {
        i++;

        if (!packet.has_property(property_t::position)) {
            continue;
        }

        int player_id = packet.player_id(),
        team_id = game.get_team_id(player_id);

        if (team_id < 0) {
            continue; // belongs to no team
        }

        auto last = last_packets.find(player_id);
        if (last != last_packets.end()) {
            int distance = dist(last->second.position(), packet.position());
            if (distance > 0.01) {
                break;
            }
        }

        last_packets[player_id] = packet;
    }

    const auto &packets = game.get_packets();

    if (i < packets.size()) {
        float clock = packets[i].clock(),
        offset = skip;
        for (auto it = packets.begin() + i; it != packets.end(); ++it) {
            if (it->has_property(property_t::clock) &&
                it->clock() >= clock + offset) {
                break;
            }
            ++i;
        }
    }

    return i;
}

const player_t &game_t::get_player(int player) const {
    return players.at(player);
}


text:
'use strict';

angular.module('fileBrowserApp').filter('bytes', [
  function () {
    return function(bytes, precision) {
      if (bytes === 0) {
        return '0 B';
      }

      if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) {
        return '-';
      }

      var isNegative = bytes < 0;
      if (isNegative) {
        bytes = -bytes;
      }

      if (typeof precision === 'undefined') {
        precision = 1;
      }

      var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      var exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
      var number = (bytes / Math.pow(1024, Math.floor(exponent))).toFixed(precision);

      return (isNegative ? '-' : '') +  number +  ' ' + units[exponent];
    };
  }
]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<xpath
xmlns:foo="http://examplotron.com/namespaces/example"
expr="/foo:bar"/>


text:
package org.apache.jackrabbit.core;

import java.security.Principal;
import java.util.Calendar;

import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.AccessControlPolicy;
import javax.jcr.security.AccessControlPolicyIterator;
import javax.jcr.security.Privilege;

import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.core.security.principal.GroupPrincipals;
import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.jackrabbit.test.NotExecutableException;
import org.apache.jackrabbit.test.RepositoryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** NodeImplTest... */
public class NodeImplTest extends AbstractJCRTest {

    private static Logger log = LoggerFactory.getLogger(NodeImplTest.class);

    protected void setUp() throws Exception {
        super.setUp();
        if (!(testRootNode instanceof NodeImpl) && !(testRootNode.getSession() instanceof SessionImpl)) {
            throw new NotExecutableException();
        }
    }

    public static void changeReadPermission(Principal principal, Node n, boolean allowRead) throws RepositoryException, NotExecutableException {
        SessionImpl s = (SessionImpl) n.getSession();
        JackrabbitAccessControlList acl = null;
        AccessControlManager acMgr = s.getAccessControlManager();
        AccessControlPolicyIterator it = acMgr.getApplicablePolicies(n.getPath());
        while (it.hasNext()) {
            AccessControlPolicy acp = it.nextAccessControlPolicy();
            if (acp instanceof JackrabbitAccessControlList) {
                acl = (JackrabbitAccessControlList) acp;
                break;
            }
        }
        if (acl == null) {
            AccessControlPolicy[] acps = acMgr.getPolicies(n.getPath());
            for (AccessControlPolicy acp : acps) {
                if (acp instanceof JackrabbitAccessControlList) {
                    acl = (JackrabbitAccessControlList) acp;
                    break;
                }
            }
        }

        if (acl != null) {
            acl.addEntry(principal, new Privilege[] {acMgr.privilegeFromName(Privilege.JCR_READ)}, allowRead);
            acMgr.setPolicy(n.getPath(), acl);
            s.save();
        } else {
            // no JackrabbitAccessControlList found.
            throw new NotExecutableException();
        }
    }

    public static Principal getReadOnlyPrincipal(RepositoryHelper helper) throws RepositoryException, NotExecutableException {
        SessionImpl s = (SessionImpl) helper.getReadOnlySession();
        try {
            for (Principal p : s.getSubject().getPrincipals()) {
                if (!GroupPrincipals.isGroup(p)) {
                    return p;
                }
            }
        } finally {
            s.logout();
        }
        throw new NotExecutableException();
    }

    /**
     * Test case for #JCR-1729. Note, that test will only be executable with
     * a security configurations that allows to set Deny-ACEs.
     *
     * @throws RepositoryException
     * @throws NotExecutableException
     */
    public void testIsCheckedOut() throws RepositoryException, NotExecutableException {
        Node n = testRootNode.addNode(nodeName1);
        NodeImpl testNode = (NodeImpl) n.addNode(nodeName2);
        testRootNode.save();

        Principal principal = getReadOnlyPrincipal(getHelper());
        changeReadPermission(principal, n, false);
        changeReadPermission(principal, testNode, true);

        Session readOnly = getHelper().getReadOnlySession();
        try {
            NodeImpl tn = (NodeImpl) readOnly.getItem(testNode.getPath());
            assertTrue(tn.isCheckedOut());

            n.addMixin(mixVersionable);
            testRootNode.save();
            n.checkin();

            assertFalse(tn.isCheckedOut());
        } finally {
            readOnly.logout();
            // reset the denied read-access
            n.checkout();
            changeReadPermission(principal, n, true);
        }
    }

    public void testAddNodeUuid() throws RepositoryException, NotExecutableException {
        String uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6";
        Node n = testRootNode.addNode(nodeName1);
        Node testNode = ((NodeImpl) n).addNodeWithUuid(nodeName2, uuid);
        testNode.addMixin(NodeType.MIX_REFERENCEABLE);
        testRootNode.getSession().save();
        assertEquals(
                "Node identifier should be: " + uuid,
                uuid, testNode.getIdentifier());
    }

    public void testAddNodeUuidCollision() throws RepositoryException, NotExecutableException {
        String uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6";
        Node n = testRootNode.addNode(nodeName1);
        Node testNode1 = ((NodeImpl) n).addNodeWithUuid(nodeName2, uuid);
        testNode1.addMixin(NodeType.MIX_REFERENCEABLE);
        testRootNode.getSession().save();

        try {
            ((NodeImpl) n).addNodeWithUuid(nodeName2, uuid);
            fail("UUID collision not detected by addNodeWithUuid");
        } catch (ItemExistsException e) {
        }
    }
    /**
     * Test case for JCR-2336. Setting jcr:data (of type BINARY) must convert
     * the String value to a binary.
     *
     * @throws RepositoryException -
     */
    public void testSetPropertyConvertValue() throws RepositoryException {
        Node content = testRootNode.addNode("jcr:content", "nt:resource");
        content.setProperty("jcr:lastModified", Calendar.getInstance());
        content.setProperty("jcr:mimeType", "text/plain");
        content.setProperty("jcr:data", "Hello");
        superuser.save();
    }

    public void testSetPropertyConvertToString() throws RepositoryException {
        Node n = testRootNode.addNode(nodeName1, "nt:folder");
        n.addMixin("mix:title");
        // must convert to string there is no other definition for this property
        Property p = n.setProperty("jcr:title", 123);
        assertEquals(PropertyType.nameFromValue(PropertyType.STRING),
                PropertyType.nameFromValue(p.getType()));
    }

    public void testSetPropertyExplicitType() throws RepositoryException {
        Node n = testRootNode.addNode(nodeName1, ntUnstructured);
        n.addMixin("mix:title");
        Property p = n.setProperty("jcr:title", "foo");
        assertEquals(PropertyType.nameFromValue(PropertyType.STRING),
                PropertyType.nameFromValue(p.getType()));
        assertEquals(PropertyType.nameFromValue(PropertyType.STRING),
                PropertyType.nameFromValue(p.getDefinition().getRequiredType()));
        p.remove();
        // must use residual definition from nt:unstructured
        p = n.setProperty("jcr:title", 123);
        assertEquals(PropertyType.nameFromValue(PropertyType.LONG),
                PropertyType.nameFromValue(p.getType()));
        assertEquals(PropertyType.nameFromValue(PropertyType.UNDEFINED),
                PropertyType.nameFromValue(p.getDefinition().getRequiredType()));
    }

    public void testSetPropertyConvertMultiValued() throws RepositoryException {
        Node n = testRootNode.addNode(nodeName1, "test:canSetProperty");
        // must convert to long there is no other definition for this property
        Property p = n.setProperty("LongMultiple", new String[]{"123", "456"});
        assertEquals(PropertyType.nameFromValue(PropertyType.LONG),
                PropertyType.nameFromValue(p.getType()));
    }

    /**
     * Test case for JCR-2130 and JCR-2408.
     *
     * @throws RepositoryException
     */
    public void testAddRemoveMixin() throws RepositoryException {
        // add mix:title to a nt:folder node and set jcr:title property
        Node n = testRootNode.addNode(nodeName1, "nt:folder");
        n.addMixin("mix:title");
        n.setProperty("jcr:title", "blah blah");
        testRootNode.getSession().save();

        // remove mix:title, jcr:title should be gone as there's no matching
        // definition in nt:folder
        n.removeMixin("mix:title");
        testRootNode.getSession().save();
        assertFalse(n.hasProperty("jcr:title"));

        // add mix:title to a nt:unstructured node and set jcr:title property
        Node n1 = testRootNode.addNode(nodeName2, ntUnstructured);
        n1.addMixin("mix:title");
        n1.setProperty("jcr:title", "blah blah");
        assertEquals(
                n1.getProperty("jcr:title").getDefinition().getDeclaringNodeType().getName(),
                "mix:title");

        // remove mix:title, jcr:title should stay since it adopts the residual
        // property definition declared in nt:unstructured
        testRootNode.getSession().save();

        n1.removeMixin("mix:title");
        testRootNode.getSession().save();
        assertTrue(n1.hasProperty("jcr:title"));

        assertEquals(
                n1.getProperty("jcr:title").getDefinition().getDeclaringNodeType().getName(),
                ntUnstructured);

        // add mix:referenceable to a nt:unstructured node, jcr:uuid is
        // automatically added
        Node n2 = testRootNode.addNode(nodeName3, ntUnstructured);
        n2.addMixin(mixReferenceable);
        testRootNode.getSession().save();

        // remove mix:referenceable, jcr:uuid should always get removed
        // since it is a protcted property
        n2.removeMixin(mixReferenceable);
        testRootNode.getSession().save();
        assertFalse(n2.hasProperty("jcr:uuid"));
    }

    /**
     * Test corruption in session / persistence state after
     * {@link ReferentialIntegrityException}.
     *
     * @see JCR-2503
     */
    public void testReferentialIntegrityCorruption() throws Exception {
        Session session = testRootNode.getSession();
        Node root = testRootNode.addNode("testReferentialIntegrityCorruption");

        // Create test nodes P1 and P2
        Node nodeP1 = root.addNode("P1");
        nodeP1.addMixin("mix:referenceable");
        Node nodeP2 = root.addNode("P2");
        nodeP2.addMixin("mix:referenceable");
        session.save();

        // Create reference from P2 to P1 and save
        nodeP2.setProperty("referencetoP1", nodeP1);
        session.save();

        // Add node P3
        Node nodeP3 = root.addNode("P3");
        nodeP3.addMixin("mix:referenceable");

        // And try to remove P1 while P2 still references P1
        nodeP1.remove();
        try {
            session.save();
        } catch (ReferentialIntegrityException expected) {
            // Got ReferentialIntegrityException as expected
        }

        // Remove P2 and save again, this will succeed. As P1, P2
        // should be removed and P3 should exist
        try {
            nodeP2.remove();
            session.save();
        } catch (Exception e) {
            String msg =
                "JCR-2503: Saving delete after"
                + " ReferentialIntegrityException failed";
            log.error(msg, e);
            fail(msg);
        }

        try {
            nodeP3 = session.getNodeByIdentifier(nodeP3.getIdentifier());
        } catch (Exception e) {
            String msg =
                "JCR-2503: Retrieving P3 by uuid failed. Corrupt session?";
            log.error(msg, e);
            fail(msg);
        }

        try {
            nodeP3.remove();
            session.save();
        } catch (Exception e) {
            String msg = "JCR-2503: Removing P3 failed. Corrupt session?";
            log.error(msg, e);
            fail(msg);
        }

        try {
            root = testRootNode.getNode("testReferentialIntegrityCorruption");
            for (Node ignore : JcrUtils.getChildNodes(root)) {
            }
        } catch (Exception e) {
            String msg = "JCR-2503: Failed to scan empty node. Corrupt session?";
            log.error(msg, e);
            fail(msg);
        }

        root.remove();
        session.save();
    }

    /**
     * Test corruption in session / persistence state after
     * {@link ReferentialIntegrityException}.
     *

     * This is a variant of {@link #testReferentialIntegrityCorruption()}
     * that checks that {@link Node#getPath()} works after the save operation.
     *
     * @see JCR-3018
     */
    public void testReferentialIntegrityCorruptionGetPath() throws Exception {
        Session session = testRootNode.getSession();
        Node root = testRootNode.addNode("testReferentialIntegrityCorruption");

        // Create test nodes P1 and P2
        Node nodeP1 = root.addNode("P1");
        nodeP1.addMixin("mix:referenceable");
        Node nodeP2 = root.addNode("P2");
        nodeP2.addMixin("mix:referenceable");
        session.save();

        // Create reference from P2 to P1 and save
        nodeP2.setProperty("referencetoP1", nodeP1);
        session.save();

        // Add node P3
        Node nodeP3 = root.addNode("P3");
        nodeP3.addMixin("mix:referenceable");

        String nodeP3path = nodeP3.getPath();

        // And try to remove P1 while P2 still references P1
        nodeP1.remove();
        try {
            session.save();
        } catch (ReferentialIntegrityException expected) {
            // Got ReferentialIntegrityException as expected
        }

        // Remove P2 and save again, this will succeed. As P1, P2
        // should be removed and P3 should exist
        try {
            nodeP2.remove();
            session.save();
        } catch (Exception e) {
            String msg = "JCR-3018: Saving delete after"
                    + " ReferentialIntegrityException failed";
            log.error(msg, e);
            fail(msg);
        }

        try {
            assertEquals(nodeP3path, nodeP3.getPath());
            nodeP3 = session.getNodeByIdentifier(nodeP3.getIdentifier());
        } catch (Exception e) {
            String msg = "JCR-3018: getting path of P3 failed. Corrupt session?";
            log.error(msg, e);
            fail(msg);
        }

        root.remove();
        session.save();
    }

    public void testBracketsInNodeName() throws Exception {
        final Node root = testRootNode.addNode("testBracketsInNodeName");

        final String[] childNames = { "{A}", "B}", "{C", "(D)", "E)", "(F", };

        for (String name : childNames) {
            root.addNode(name);
            root.getSession().save();
            assertTrue("Expecting child " + name + " to have been created", root.hasNode(name));
        }
    }
}


text:
package org.kie.uberfire.social.activities.client.widgets.timeline.regular;

import java.util.List;
import java.util.Map;

import com.github.gwtbootstrap.client.ui.Container;
import com.github.gwtbootstrap.client.ui.Paragraph;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.errai.bus.client.api.base.MessageBuilder;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.kie.uberfire.social.activities.client.widgets.item.SimpleItemWidget;
import org.kie.uberfire.social.activities.client.widgets.item.SocialItemExpandedWidget;
import org.kie.uberfire.social.activities.client.widgets.item.model.SimpleItemWidgetModel;
import org.kie.uberfire.social.activities.client.widgets.item.model.SocialItemExpandedWidgetModel;
import org.kie.uberfire.social.activities.client.widgets.timeline.regular.model.RecentUpdatesModel;
import org.kie.uberfire.social.activities.client.widgets.timeline.regular.model.SocialTimelineWidgetModel;
import org.kie.uberfire.social.activities.client.widgets.timeline.regular.model.UpdateItem;
import org.kie.uberfire.social.activities.model.SocialActivitiesEvent;
import org.kie.uberfire.social.activities.service.SocialTimeLineRepositoryAPI;
import org.kie.uberfire.social.activities.service.SocialTimelineRulesQueryAPI;
import org.uberfire.backend.vfs.Path;
import org.uberfire.backend.vfs.VFSService;

public class SocialTimelineWidget extends Composite {

    @UiField
    Container itemsPanel;

    private SocialTimelineWidgetModel model;

    public void init( SocialTimelineWidgetModel model ) {
        this.model = model;
        initWidget( uiBinder.createAndBindUi( this ) );
        if ( model.isDroolsQuery() ) {
            createDroolsQuerySocialItemsWidget( model );
        } else {
            createRegularQuerySocialItemsWidget( model );
        }
    }

    private void createRegularQuerySocialItemsWidget( final SocialTimelineWidgetModel model ) {

        MessageBuilder.createCall( new RemoteCallback<List<SocialActivitiesEvent>>() {
            public void callback( List<SocialActivitiesEvent> events ) {

                if ( events.isEmpty() ) {
                    displayNoEvents();
                } else {
                    createEventsWidget( events, model );
                }
            }
        }, SocialTimeLineRepositoryAPI.class ).getLastEventTimeline( model.getSocialEventType().name() );
    }

    private void createEventsWidget( List<SocialActivitiesEvent> events,
                                     final SocialTimelineWidgetModel model ) {
        for ( final SocialActivitiesEvent event : events ) {
            if ( event.hasLink() ) {
                createSimpleWidgetWithLink( event );                 ;
            } else {
                createSimpleWidget( event );
            }
        }
    }

    private void createSimpleWidgetWithLink( final SocialActivitiesEvent event ) {

        final SimpleItemWidgetModel itemModel = new SimpleItemWidgetModel(model, event.getType(),
                event.getTimestamp(),
                event.getLinkLabel(),
                event.getLinkTarget(),
                event.getLinkType(),
                event.getDescription(),
                event.getAdicionalInfos(),
                model.getSocialUser())
                .withLinkCommand( model.getLinkCommand() )
                .withLinkParams( event.getLinkParams() );

        if ( event.isVFSLink() ) {
            MessageBuilder.createCall( new RemoteCallback<Path>() {
                public void callback( Path path ) {
                    itemModel.withLinkPath( path );
                    addItemWidget( itemModel );

                }
            }, VFSService.class ).get( event.getLinkTarget() );
        } else {
            addItemWidget( itemModel );
        }
    }

    private void createSimpleWidget( SocialActivitiesEvent event ) {
        SimpleItemWidgetModel rowModel = new SimpleItemWidgetModel( model, event.getType(),
                event.getTimestamp(),
                event.getDescription(),
                event.getAdicionalInfos() )
                .withLinkParams( event.getLinkParams() );

        addItemWidget( rowModel );
    }

    private void addItemWidget( SimpleItemWidgetModel model ) {
        SimpleItemWidget simple = GWT.create( SimpleItemWidget.class );
        simple.init( model );
        itemsPanel.add( simple );
    }

    private void createDroolsQuerySocialItemsWidget( final SocialTimelineWidgetModel model ) {
        MessageBuilder.createCall( new RemoteCallback<List<SocialActivitiesEvent>>() {
            public void callback( List<SocialActivitiesEvent> events ) {
                RecentUpdatesModel recentUpdatesModel = RecentUpdatesModel.generate( events );
                Map<String, List<UpdateItem>> updateItems = recentUpdatesModel.getUpdateItems();
                if ( updateItems.keySet().isEmpty() ) {
                    displayNoEvents();
                } else {
                    createExpandedItemsWidget( recentUpdatesModel, updateItems, model );
                }
            }
        }, SocialTimelineRulesQueryAPI.class ).executeSpecificRule( model.getGlobals(), model.getDrlName(), model.getMaxResults() );
    }

    private void createExpandedItemsWidget( RecentUpdatesModel recentUpdatesModel,
                                            Map<String, List<UpdateItem>> updateItems,
                                            SocialTimelineWidgetModel model ) {
        for ( final String fileName : updateItems.keySet() ) {
            SocialItemExpandedWidget widget = GWT.create( SocialItemExpandedWidget.class );
            widget.init( new SocialItemExpandedWidgetModel( fileName, recentUpdatesModel.getUpdateItems( fileName ), model ) );
            itemsPanel.add( widget );
        }
    }

    private void displayNoEvents() {
        itemsPanel.add( new Paragraph( "There are no social events...yet!" ) );
    }

    interface MyUiBinder extends UiBinder<Widget, SocialTimelineWidget> {

    }

    private static MyUiBinder uiBinder = GWT.create( MyUiBinder.class );

}


text:
class MultiYearChartsController < ApplicationController
  layout 'multi_year_charts'

  before_action :ensure_valid_config
  before_action :require_user, except: :index

  def index
    @scenarios = user_scenarios
    @multi_year_charts = user_multi_year_charts

    respond_to do |format|
      format.html
      format.js do
        render(params[:wants] == 'scenarios' ? 'scenarios' : 'index')
      end
    end
  end

  # Creates a new MultiYearChart record based on the scenario specified in the
  # params.
  #
  # Redirects to the external MYC app when successful.
  #
  # POST /multi_year_charts
  def create
    result = CreateMultiYearChart.call(
      current_user.saved_scenarios.find(params.require(:scenario_id)),
      current_user
    )

    if result.successful?
      redirect_to helpers.myc_url(result.value), allow_other_host: true
    else
      flash.now[:error] = result.errors.join(', ')

      @scenarios = user_scenarios
      @multi_year_charts = user_multi_year_charts

      render :index, status: :unprocessable_entity
    end
  end

  # Removes a MultiYearChart record.
  #
  # DELETE /multi_year_charts/:id
  def destroy
    DeleteMultiYearChart.call(
      current_user.multi_year_charts.find(params.require(:id))
    )

    redirect_to multi_year_charts_path
  end

  private

  def user_scenarios
    return [] unless current_user

    scenarios = current_user
      .saved_scenarios
      .order('created_at DESC')
      .page(params[:page])
      .per(50)

    SavedScenario.batch_load(scenarios)

    scenarios
  end

  def user_multi_year_charts
    return [] unless current_user

    current_user
      .multi_year_charts
      .where(area_code: Api::Area.keys)
      .order(created_at: :desc)
      .page(params[:page])
      .per(50)
  end

  def ensure_valid_config
    return if Settings.multi_year_charts_url

    redirect_to root_path,
      notice: 'Missing multi_year_charts_url setting in config.yml'
  end
end


text:
package com.lieve.online.shiro.service;

import com.lieve.online.shiro.dao.UserDao;
import com.lieve.online.shiro.dao.UserDaoImpl;
import com.lieve.online.shiro.entity.User;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 *
User: Zhang Kaitao
 *
Date: 14-1-28
 *
Version: 1.0
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();
    private PasswordHelper passwordHelper = new PasswordHelper();

    /**
     * 创建用户
     * @param user
     */
    public User createUser(User user) {
        //加密密码
        passwordHelper.encryptPassword(user);
        return userDao.createUser(user);
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    public void changePassword(Long userId, String newPassword) {
        User user =userDao.findOne(userId);
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        userDao.updateUser(user);
    }

    /**
     * 添加用户-角色关系
     * @param userId
     * @param roleIds
     */
    public void correlationRoles(Long userId, Long... roleIds) {
        userDao.correlationRoles(userId, roleIds);
    }

    /**
     * 移除用户-角色关系
     * @param userId
     * @param roleIds
     */
    public void uncorrelationRoles(Long userId, Long... roleIds) {
        userDao.uncorrelationRoles(userId, roleIds);
    }

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    public Set<String> findRoles(String username) {
        return userDao.findRoles(username);
    }

    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    public Set<String> findPermissions(String username) {
        return userDao.findPermissions(username);
    }

}


text:
<?php

namespace Drupal\Tests\statistics\Kernel\Migrate\d6;

use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;

/**
 * Tests the migration of node counter data to Drupal 8.
 *
 * @group statistics
 */
class MigrateNodeCounterTest extends MigrateDrupal6TestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'content_translation',
    'language',
    'menu_ui',
    'node',
    'statistics',
    'text',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installEntitySchema('node');
    $this->installConfig('node');
    $this->installSchema('node', ['node_access']);
    $this->installSchema('statistics', ['node_counter']);

    $this->executeMigrations([
      'language',
      'd6_filter_format',
      'd6_user_role',
      'd6_node_settings',
      'd6_user',
      'd6_node_type',
      'd6_language_content_settings',
      'd6_node',
      'd6_node_translation',
      'statistics_node_counter',
    ]);
  }

  /**
   * Tests migration of node counter.
   */
  public function testStatisticsSettings() {
    $this->assertNodeCounter(1, 2, 0, 1421727536);
    $this->assertNodeCounter(2, 1, 0, 1471428059);
    $this->assertNodeCounter(3, 1, 0, 1471428153);
    $this->assertNodeCounter(4, 1, 1, 1478755275);
    $this->assertNodeCounter(5, 1, 1, 1478755314);
    $this->assertNodeCounter(10, 5, 1, 1521137459);
    $this->assertNodeCounter(12, 3, 0, 1521137469);

    // Tests that translated node counts include all translation counts.
    $this->executeMigration('statistics_node_translation_counter');
    $this->assertNodeCounter(10, 8, 2, 1521137463);
    $this->assertNodeCounter(12, 5, 1, 1521137470);
  }

  /**
   * Asserts various aspects of a node counter.
   *
   * @param int $nid
   *   The node ID.
   * @param int $total_count
   *   The expected total count.
   * @param int $day_count
   *   The expected day count.
   * @param int $timestamp
   *   The expected timestamp.
   */
  protected function assertNodeCounter($nid, $total_count, $day_count, $timestamp) {
    /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
    $statistics = $this->container->get('statistics.storage.node')->fetchView($nid);
    // @todo Remove casting after https://www.drupal.org/node/2926069 lands.
    $this->assertSame($total_count, (int) $statistics->getTotalCount());
    $this->assertSame($day_count, (int) $statistics->getDayCount());
    $this->assertSame($timestamp, (int) $statistics->getTimestamp());
  }

}


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

import java.io.IOException;
import java.util.List;

import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * TestTableInputFormatScan part 1.
 * @see TestTableInputFormatScanBase
 */
@Category(LargeTests.class)
public class TestTableInputFormatScan1 extends TestTableInputFormatScanBase {

  /**
   * Tests a MR scan using specific start and stop rows.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testScanEmptyToEmpty()
  throws IOException, InterruptedException, ClassNotFoundException {
    testScan(null, null, null);
  }

  /**
   * Tests a MR scan using specific start and stop rows.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testScanEmptyToAPP()
  throws IOException, InterruptedException, ClassNotFoundException {
    testScan(null, "app", "apo");
  }

  /**
   * Tests a MR scan using specific start and stop rows.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testScanEmptyToBBA()
  throws IOException, InterruptedException, ClassNotFoundException {
    testScan(null, "bba", "baz");
  }

  /**
   * Tests a MR scan using specific start and stop rows.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testScanEmptyToBBB()
  throws IOException, InterruptedException, ClassNotFoundException {
    testScan(null, "bbb", "bba");
  }

  /**
   * Tests a MR scan using specific start and stop rows.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testScanEmptyToOPP()
  throws IOException, InterruptedException, ClassNotFoundException {
    testScan(null, "opp", "opo");
  }

  /**
   * Tests a MR scan using specific number of mappers. The test table has 25 regions,
   * and all region sizes are set as 0 as default. The average region size is 1 (the smallest
   * positive). When we set hbase.mapreduce.input.ratio as -1, all regions will be cut into two
   * MapRedcue input splits, the number of MR input splits should be 50; when we set hbase
   * .mapreduce.input.ratio as 100, the sum of all region sizes is less then the average region
   * size, all regions will be combined into 1 MapRedcue input split.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testGetSplits() throws IOException, InterruptedException, ClassNotFoundException {
    HTable table = new HTable(TEST_UTIL.getConfiguration(), TABLE_NAME);
    List<HRegionLocation> locs = table.getAllRegionLocations();

    testNumOfSplits("-1", locs.size()*2);
    table.close();
    testNumOfSplits("100", 1);
  }

  /**
   * Tests the getSplitKey() method in TableInputFormatBase.java
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws InterruptedException
   */
  @Test
  public void testGetSplitsPoint() throws IOException, InterruptedException,
  ClassNotFoundException {
    // Test Case 1: "aaabcdef" and "aaaff", split point is "aaad".
    byte[] start1 = { 'a', 'a', 'a', 'b', 'c', 'd', 'e', 'f' };
    byte[] end1 = { 'a', 'a', 'a', 'f', 'f' };
    byte[] splitPoint1 = { 'a', 'a', 'a', 'd' };
    testGetSplitKey(start1, end1, splitPoint1, true);

    // Test Case 2: "111000" and "1125790", split point is "111b".
    byte[] start2 = { '1', '1', '1', '0', '0', '0' };
    byte[] end2 = { '1', '1', '2', '5', '7', '9', '0' };
    byte[] splitPoint2 = { '1', '1', '1', 'b' };
    testGetSplitKey(start2, end2, splitPoint2, true);

    // Test Case 3: "aaaaaa" and "aab", split point is "aaap".
    byte[] start3 = { 'a', 'a', 'a', 'a', 'a', 'a' };
    byte[] end3 = { 'a', 'a', 'b' };
    byte[] splitPoint3 = { 'a', 'a', 'a', 'p' };
    testGetSplitKey(start3, end3, splitPoint3, true);

    // Test Case 4: "aaa" and "aaaz", split point is "aaaM".
    byte[] start4 = { 'a', 'a', 'a' };
    byte[] end4 = { 'a', 'a', 'a', 'z' };
    byte[] splitPoint4 = { 'a', 'a', 'a', 'M' };
    testGetSplitKey(start4, end4, splitPoint4, true);

    // Test Case 5: "aaa" and "aaba", split point is "aaap".
    byte[] start5 = { 'a', 'a', 'a' };
    byte[] end5 = { 'a', 'a', 'b', 'a' };
    byte[] splitPoint5 = { 'a', 'a', 'a', 'p' };
    testGetSplitKey(start5, end5, splitPoint5, true);

    // Test Case 6: empty key and "hhhqqqwww", split point is "h"
    byte[] start6 = {};
    byte[] end6 = { 'h', 'h', 'h', 'q', 'q', 'q', 'w', 'w' };
    byte[] splitPoint6 = { 'h' };
    testGetSplitKey(start6, end6, splitPoint6, true);

    // Test Case 7: "ffffaaa" and empty key, split point depends on the mode we choose(text key or
    // binary key).
    byte[] start7 = { 'f', 'f', 'f', 'f', 'a', 'a', 'a' };
    byte[] end7 = {};
    byte[] splitPointText7 = { 'f', '~', '~', '~', '~', '~', '~'  };
    byte[] splitPointBinary7 = { 'f', 127, 127, 127, 127, 127, 127  };
    testGetSplitKey(start7, end7, splitPointText7, true);
    testGetSplitKey(start7, end7, splitPointBinary7, false);

    // Test Case 8: both start key and end key are empty. Split point depends on the mode we
    // choose (text key or binary key).
    byte[] start8 = {};
    byte[] end8 = {};
    byte[] splitPointText8 = { 'O' };
    byte[] splitPointBinary8 = { 0 };
    testGetSplitKey(start8, end8, splitPointText8, true);
    testGetSplitKey(start8, end8, splitPointBinary8, false);

    // Test Case 9: Binary Key example
    byte[] start9 = { 13, -19, 126, 127 };
    byte[] end9 = { 13, -19, 127, 0 };
    byte[] splitPoint9 = { 13, -19, 127, -64 };
    testGetSplitKey(start9, end9, splitPoint9, false);
  }
}


text:
RSpec.describe Hyrax::Arkivo::SchemaValidator do
  let(:item) { JSON.parse(FactoryBot.json(:post_item)) }

  it 'ensures a token is included' do
    expect do
      described_class.new(item.except('token')).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'token'/)
  end

  it 'ensures a metadata section is included' do
    expect do
      described_class.new(item.except('metadata')).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'metadata'/)
  end

  it 'ensures a file section is included' do
    expect do
      described_class.new(item.except('file')).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'file'/)
  end

  it 'ensures the metadata has a title' do
    item['metadata'].delete('title')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'title'/)
  end

  it 'ensures the metadata has license' do
    item['metadata'].delete('license')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'license'/)
  end

  it 'ensures the file has a b64-encoded content' do
    item['file'].delete('base64')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'base64'/)
  end

  it 'ensures the file has a checksum' do
    item['file'].delete('md5')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'md5'/)
  end

  it 'ensures the file has a filename' do
    item['file'].delete('filename')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'filename'/)
  end

  it 'ensures the file has a content type' do
    item['file'].delete('contentType')
    expect do
      described_class.new(item).call
    end.to raise_error(Hyrax::Arkivo::InvalidItem, /required property of 'contentType'/)
  end
end


text:
/*
 * Workspace API
 * Agent API
 *
 * OpenAPI spec version: 9.0.000.97.4639
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package com.genesys.internal.workspace.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ActivatechannelsData
 */
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2022-03-03T19:45:16.214Z")
public class ActivatechannelsData {
  @SerializedName("agentId")
  private String agentId = null;

  @SerializedName("placeName")
  private String placeName = null;

  @SerializedName("dn")
  private String dn = null;

  @SerializedName("queueName")
  private String queueName = null;

  /**
   * The workmode.
   */
  @JsonAdapter(AgentWorkModeEnum.Adapter.class)
  public enum AgentWorkModeEnum {
    AUTOIN("AutoIn"),

    MANUALIN("ManualIn");

    private String value;

    AgentWorkModeEnum(String value) {
      this.value = value;
    }

    public String getValue() {
      return value;
    }

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

    public static AgentWorkModeEnum fromValue(String text) {
      for (AgentWorkModeEnum b : AgentWorkModeEnum.values()) {
        if (String.valueOf(b.value).equals(text)) {
          return b;
        }
      }
      return null;
    }

    public static class Adapter extends TypeAdapter<AgentWorkModeEnum> {
      @Override
      public void write(final JsonWriter jsonWriter, final AgentWorkModeEnum enumeration) throws IOException {
        jsonWriter.value(enumeration.getValue());
      }

      @Override
      public AgentWorkModeEnum read(final JsonReader jsonReader) throws IOException {
        String value = jsonReader.nextString();
        return AgentWorkModeEnum.fromValue(String.valueOf(value));
      }
    }
  }

  @SerializedName("agentWorkMode")
  private AgentWorkModeEnum agentWorkMode = null;

  @SerializedName("dynamicPhoneNumber")
  private String dynamicPhoneNumber = null;

  @SerializedName("autoCompleteCall")
  private Boolean autoCompleteCall = null;

  @SerializedName("channels")
  private List<String> channels = null;

  public ActivatechannelsData agentId(String agentId) {
    this.agentId = agentId;
    return this;
  }

   /**
   * The unique ID of the agent.
   * @return agentId
  **/
  @ApiModelProperty(value = "The unique ID of the agent.")
  public String getAgentId() {
    return agentId;
  }

  public void setAgentId(String agentId) {
    this.agentId = agentId;
  }

  public ActivatechannelsData placeName(String placeName) {
    this.placeName = placeName;
    return this;
  }

   /**
   * The name of the place to use for the agent. You must provide either the place name or DN.
   * @return placeName
  **/
  @ApiModelProperty(value = "The name of the place to use for the agent. You must provide either the place name or DN.")
  public String getPlaceName() {
    return placeName;
  }

  public void setPlaceName(String placeName) {
    this.placeName = placeName;
  }

  public ActivatechannelsData dn(String dn) {
    this.dn = dn;
    return this;
  }

   /**
   * The DN (number) to use for the agent. You must provide either the place name or DN.
   * @return dn
  **/
  @ApiModelProperty(value = "The DN (number) to use for the agent. You must provide either the place name or DN.")
  public String getDn() {
    return dn;
  }

  public void setDn(String dn) {
    this.dn = dn;
  }

  public ActivatechannelsData queueName(String queueName) {
    this.queueName = queueName;
    return this;
  }

   /**
   * The queue name.
   * @return queueName
  **/
  @ApiModelProperty(value = "The queue name.")
  public String getQueueName() {
    return queueName;
  }

  public void setQueueName(String queueName) {
    this.queueName = queueName;
  }

  public ActivatechannelsData agentWorkMode(AgentWorkModeEnum agentWorkMode) {
    this.agentWorkMode = agentWorkMode;
    return this;
  }

   /**
   * The workmode.
   * @return agentWorkMode
  **/
  @ApiModelProperty(value = "The workmode.")
  public AgentWorkModeEnum getAgentWorkMode() {
    return agentWorkMode;
  }

  public void setAgentWorkMode(AgentWorkModeEnum agentWorkMode) {
    this.agentWorkMode = agentWorkMode;
  }

  public ActivatechannelsData dynamicPhoneNumber(String dynamicPhoneNumber) {
    this.dynamicPhoneNumber = dynamicPhoneNumber;
    return this;
  }

   /**
   * An optional dynamic phone number to use for the agent.
   * @return dynamicPhoneNumber
  **/
  @ApiModelProperty(value = "An optional dynamic phone number to use for the agent.")
  public String getDynamicPhoneNumber() {
    return dynamicPhoneNumber;
  }

  public void setDynamicPhoneNumber(String dynamicPhoneNumber) {
    this.dynamicPhoneNumber = dynamicPhoneNumber;
  }

  public ActivatechannelsData autoCompleteCall(Boolean autoCompleteCall) {
    this.autoCompleteCall = autoCompleteCall;
    return this;
  }

   /**
   * Specifies if calls should automatically be completed for the session. Defaults to true if not provided.
   * @return autoCompleteCall
  **/
  @ApiModelProperty(value = "Specifies if calls should automatically be completed for the session. Defaults to true if not provided.")
  public Boolean isAutoCompleteCall() {
    return autoCompleteCall;
  }

  public void setAutoCompleteCall(Boolean autoCompleteCall) {
    this.autoCompleteCall = autoCompleteCall;
  }

  public ActivatechannelsData channels(List<String> channels) {
    this.channels = channels;
    return this;
  }

  public ActivatechannelsData addChannelsItem(String channelsItem) {
    if (this.channels == null) {
      this.channels = new ArrayList<String>();
    }
    this.channels.add(channelsItem);
    return this;
  }

   /**
   * An array of strings that correspond to the channels you want to activate.
   * @return channels
  **/
  @ApiModelProperty(value = "An array of strings that correspond to the channels you want to activate.")
  public List<String> getChannels() {
    return channels;
  }

  public void setChannels(List<String> channels) {
    this.channels = channels;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ActivatechannelsData activatechannelsData = (ActivatechannelsData) o;
    return Objects.equals(this.agentId, activatechannelsData.agentId) &&
        Objects.equals(this.placeName, activatechannelsData.placeName) &&
        Objects.equals(this.dn, activatechannelsData.dn) &&
        Objects.equals(this.queueName, activatechannelsData.queueName) &&
        Objects.equals(this.agentWorkMode, activatechannelsData.agentWorkMode) &&
        Objects.equals(this.dynamicPhoneNumber, activatechannelsData.dynamicPhoneNumber) &&
        Objects.equals(this.autoCompleteCall, activatechannelsData.autoCompleteCall) &&
        Objects.equals(this.channels, activatechannelsData.channels);
  }

  @Override
  public int hashCode() {
    return Objects.hash(agentId, placeName, dn, queueName, agentWorkMode, dynamicPhoneNumber, autoCompleteCall, channels);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class ActivatechannelsData {\n");

    sb.append("    agentId: ").append(toIndentedString(agentId)).append("\n");
    sb.append("    placeName: ").append(toIndentedString(placeName)).append("\n");
    sb.append("    dn: ").append(toIndentedString(dn)).append("\n");
    sb.append("    queueName: ").append(toIndentedString(queueName)).append("\n");
    sb.append("    agentWorkMode: ").append(toIndentedString(agentWorkMode)).append("\n");
    sb.append("    dynamicPhoneNumber: ").append(toIndentedString(dynamicPhoneNumber)).append("\n");
    sb.append("    autoCompleteCall: ").append(toIndentedString(autoCompleteCall)).append("\n");
    sb.append("    channels: ").append(toIndentedString(channels)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
using System;

namespace OctoAwesome.Network
{
    /// <summary>
    /// Double buffered network stream implementation.
    /// </summary>
    public class OctoNetworkStream
    {
        private byte[] readBuffer;
        private byte[] writeBuffer;

        private readonly byte[] bufferA;
        private readonly byte[] bufferB;

        private readonly object readLock;
        private readonly object writeLock;

        private readonly int writeLength;
        private readonly int readLength;

        private int maxReadCount;

        private int readPosition;
        private int writePosition;

        private bool writingProcess;

        /// <summary>
        /// Initializes a new instance of the <see cref="OctoNetworkStream"/> class.
        /// </summary>
        /// <param name="capacity">The buffer capacity per buffer.</param>
        public OctoNetworkStream(int capacity = 1024)
        {
            bufferA = new byte[capacity];
            bufferB = new byte[capacity];
            readBuffer = bufferA;
            writeBuffer = bufferB;
            readLength = capacity;
            writeLength = capacity;
            readPosition = 0;
            writePosition = 0;
            readLock = new object();
            writeLock = new object();
        }

        /// <summary>
        /// Writes a given range from a byte buffer to the stream.
        /// </summary>
        /// <param name="buffer">The buffer array to write to the stream.</param>
        /// <param name="offset">The buffer slice offset to get from <paramref name="buffer"/>.</param>
        /// <param name="count">The buffer slice count to get from <paramref name="buffer"/>.</param>
        /// <returns>The number of bytes written.</returns>
        public int Write(byte[] buffer, int offset, int count)
        {
            writingProcess = true;

            SwapBuffer();

            var maxCopy = writeLength - writePosition;

            if (maxCopy < count)
                count = maxCopy;

            if (maxCopy < 1)
            {
                writingProcess = false;
                return maxCopy;
            }

            lock (writeLock)
                Buffer.BlockCopy(buffer, offset, writeBuffer, writePosition, count);

            writePosition += count;

            writingProcess = false;

            return count;
        }

        /// <summary>
        /// Writes a single byte to the stream.
        /// </summary>
        /// <param name="data">The single byte to write.</param>
        /// <returns>The number of bytes that where written.</returns>
        public int Write(byte data)
        {
            writingProcess = true;

            SwapBuffer();

            if (writeLength == writePosition)
            {
                writingProcess = false;
                return 0;
            }

            lock (writeLock)
                writeBuffer[writePosition++] = data;

            writingProcess = false;

            return 1;
        }

        /// <summary>
        /// Reads from the stream into a buffer.
        /// </summary>
        /// <param name="buffer">The buffer to read into.</param>
        /// <param name="offset">The slice buffer offset to start reading into.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <returns>The actually read number of bytes.</returns>
        public int Read(byte[] buffer, int offset, int count)
        {
            if (!writingProcess)
                SwapBuffer();

            var maxCopy = maxReadCount - readPosition;

            if (maxCopy < 1)
                return maxCopy;

            if (maxCopy < count)
                count = maxCopy;

            lock (readLock)
                Buffer.BlockCopy(readBuffer, readPosition, buffer, offset, count);

            readPosition += count;

            return count;
        }

        /// <summary>
        /// Gets the number of bytes available with a maximum value of <paramref name="count"/>.
        /// </summary>
        /// <param name="count">The maximum data to make available.</param>
        /// <returns>The available number of readable bytes in the stream.</returns>
        public int DataAvailable(int count)
        {
            if (!writingProcess)
                SwapBuffer();

            var maxCopy = maxReadCount - readPosition;

            if (maxCopy < 1)
                return maxCopy;

            if (maxCopy < count)
                count = maxCopy;

            return count;
        }

        private void SwapBuffer()
        {
            lock (readLock)
                lock (writeLock)
                {
                    if (readPosition > maxReadCount)
                        throw new IndexOutOfRangeException("ReadPosition is greater than MaxReadCount in OctoNetworkStream");
                    if (readPosition < maxReadCount)
                        return;

                    (writeBuffer, readBuffer) = (readBuffer, writeBuffer);
                    maxReadCount = writePosition;
                    writePosition = 0;
                    readPosition = 0;
                }
        }

    }
}


text:
package org.apache.flume.serialization;

import com.google.common.base.Charsets;
import org.apache.flume.annotations.InterfaceAudience;
import org.apache.flume.annotations.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;

/**
 *
This class makes the following assumptions:

 *

 *
The underlying file is not changing while it is being read

 *

 *
 *
The ability to {@link #reset()} is dependent on the underlying {@link
 * PositionTracker} instance's durability semantics.

 *
 *
A note on surrogate pairs:

 *
 *
The logic for decoding surrogate pairs is as follows:
 * If no character has been decoded by a "normal" pass, and the buffer still has remaining bytes,
 * then an attempt is made to read 2 characters in one pass.
 * If it succeeds, then the first char (high surrogate) is returned;
 * the second char (low surrogate) is recorded internally,
 * and is returned at the next call to {@link #readChar()}.
 * If it fails, then it is assumed that EOF has been reached.

 *
 *
Impacts on position, mark and reset: when a surrogate pair is decoded, the position
 * is incremented by the amount of bytes taken to decode the entire pair (usually, 4).
 * This is the most reasonable choice since it would not be advisable
 * to reset a stream to a position pointing to the second char in a pair of surrogates:
 * such a dangling surrogate would not be properly decoded without its counterpart.

 *
 *
Thus the behaviour of mark and reset is as follows:

 *
 *

 *
If {@link #mark()} is called after a high surrogate pair has been returned by
 *   {@link #readChar()}, the marked position will be that of the character following
 *   the low surrogate, not that of the low surrogate itself.

 *
If {@link #reset()} is called after a high surrogate pair has been returned by
 *   {@link #readChar()}, the low surrogate is always returned by the next call to
 *   {@link #readChar()}, before the stream is actually reset to the last marked
 *   position.

 *

 *
 *
This ensures that no dangling high surrogate could ever be read as long as
 * the same instance is used to read the whole pair. However, if {@link #reset()}
 * is called after a high surrogate pair has been returned by {@link #readChar()},
 * and a new instance of ResettableFileInputStream is used to resume reading,
 * then the low surrogate char will be lost,
 * resulting in a corrupted sequence of characters (dangling high surrogate).
 * This situation is hopefully extremely unlikely to happen in real life.
 *

 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class ResettableFileInputStream extends ResettableInputStream
    implements RemoteMarkable, LengthMeasurable {

  Logger logger = LoggerFactory.getLogger(ResettableFileInputStream.class);

  public static final int DEFAULT_BUF_SIZE = 16384;

  /**
   * The minimum acceptable buffer size to store bytes read
   * from the underlying file. A minimum size of 8 ensures that the
   * buffer always has enough space to contain multi-byte characters,
   * including special sequences such as surrogate pairs, Byte Order Marks, etc.
   */
  public static final int MIN_BUF_SIZE = 8;

  private final File file;
  private final PositionTracker tracker;
  private final FileInputStream in;
  private final FileChannel chan;
  private final ByteBuffer buf;
  private final CharBuffer charBuf;
  private final byte[] byteBuf;
  private final long fileSize;
  private final CharsetDecoder decoder;
  private long position;
  private long syncPosition;
  private int maxCharWidth;

  /**
   * Whether this instance holds a low surrogate character.
   */
  private boolean hasLowSurrogate = false;

  /**
   * A low surrogate character read from a surrogate pair.
   * When a surrogate pair is found, the high (first) surrogate pair
   * is returned upon a call to {@link #read()},
   * while the low (second) surrogate remains stored in memory,
   * to be returned at the next call to {@link #read()}.
   */
  private char lowSurrogate;

  /**
   *
   * @param file
   *        File to read
   *
   * @param tracker
   *        PositionTracker implementation to make offset position durable
   *
   * @throws FileNotFoundException If the file to read does not exist
   * @throws IOException If the position reported by the tracker cannot be sought
   */
  public ResettableFileInputStream(File file, PositionTracker tracker)
      throws IOException {
    this(file, tracker, DEFAULT_BUF_SIZE, Charsets.UTF_8, DecodeErrorPolicy.FAIL);
  }

  /**
   *
   * @param file
   *        File to read
   *
   * @param tracker
   *        PositionTracker implementation to make offset position durable
   *
   * @param bufSize
   *        Size of the underlying buffer used for input. If lesser than {@link #MIN_BUF_SIZE},
   *        a buffer of length {@link #MIN_BUF_SIZE} will be created instead.
   *
   * @param charset
   *        Character set used for decoding text, as necessary
   *
   * @param decodeErrorPolicy
   *        A {@link DecodeErrorPolicy} instance to determine how
   *        the decoder should behave in case of malformed input and/or
   *        unmappable character.
   *
   * @throws FileNotFoundException If the file to read does not exist
   * @throws IOException If the position reported by the tracker cannot be sought
   */
  public ResettableFileInputStream(File file, PositionTracker tracker,
      int bufSize, Charset charset, DecodeErrorPolicy decodeErrorPolicy)
      throws IOException {
    this.file = file;
    this.tracker = tracker;
    this.in = new FileInputStream(file);
    this.chan = in.getChannel();
    this.buf = ByteBuffer.allocateDirect(Math.max(bufSize, MIN_BUF_SIZE));
    buf.flip();
    this.byteBuf = new byte[1]; // single byte
    this.charBuf = CharBuffer.allocate(2); // two chars for surrogate pairs
    charBuf.flip();
    this.fileSize = file.length();
    this.decoder = charset.newDecoder();
    this.position = 0;
    this.syncPosition = 0;
    if (charset.name().startsWith("UTF-8")) {
      // some JDKs wrongly report 3 bytes max
      this.maxCharWidth = 4;
    } else if (charset.name().startsWith("UTF-16")) {
      // UTF_16BE and UTF_16LE wrongly report 2 bytes max
      this.maxCharWidth = 4;
    } else if (charset.name().startsWith("UTF-32")) {
      // UTF_32BE and UTF_32LE wrongly report 4 bytes max
      this.maxCharWidth = 8;
    } else {
      this.maxCharWidth = (int) Math.ceil(charset.newEncoder().maxBytesPerChar());
    }

    CodingErrorAction errorAction;
    switch (decodeErrorPolicy) {
      case FAIL:
        errorAction = CodingErrorAction.REPORT;
        break;
      case REPLACE:
        errorAction = CodingErrorAction.REPLACE;
        break;
      case IGNORE:
        errorAction = CodingErrorAction.IGNORE;
        break;
      default:
        throw new IllegalArgumentException(
            "Unexpected value for decode error policy: " + decodeErrorPolicy);
    }
    decoder.onMalformedInput(errorAction);
    decoder.onUnmappableCharacter(errorAction);

    seek(tracker.getPosition());
  }

  @Override
  public synchronized int read() throws IOException {
    int len = read(byteBuf, 0, 1);
    if (len == -1) {
      return -1;
    // len == 0 should never happen
    } else if (len == 0) {
      return -1;
    } else {
      return byteBuf[0] & 0xFF;
    }
  }

  @Override
  public synchronized int read(byte[] b, int off, int len) throws IOException {
    logger.trace("read(buf, {}, {})", off, len);

    if (position >= fileSize) {
      return -1;
    }

    if (!buf.hasRemaining()) {
      refillBuf();
    }

    int rem = buf.remaining();
    if (len > rem) {
      len = rem;
    }
    buf.get(b, off, len);
    incrPosition(len, true);
    return len;
  }

  @Override
  public synchronized int readChar() throws IOException {

    // Check whether we are in the middle of a surrogate pair,
    // in which case, return the last (low surrogate) char of the pair.
    if (hasLowSurrogate) {
      hasLowSurrogate = false;
      return lowSurrogate;
    }

    // The decoder can have issues with multi-byte characters.
    // This check ensures that there are at least maxCharWidth bytes in the buffer
    // before reaching EOF.
    if (buf.remaining() < maxCharWidth) {
      buf.clear();
      buf.flip();
      refillBuf();
    }

    int start = buf.position();
    charBuf.clear();
    charBuf.limit(1);

    boolean isEndOfInput = false;
    if (position >= fileSize) {
      isEndOfInput = true;
    }

    CoderResult res = decoder.decode(buf, charBuf, isEndOfInput);
    if (res.isMalformed() || res.isUnmappable()) {
      res.throwException();
    }

    int delta = buf.position() - start;

    charBuf.flip();

    // Found a single char
    if (charBuf.hasRemaining()) {
      char c = charBuf.get();
      incrPosition(delta, true);
      return c;
    }

    // Found nothing, but the byte buffer has not been entirely consumed.
    // This situation denotes the presence of a surrogate pair
    // that can only be decoded if we have a 2-char buffer.
    if (buf.hasRemaining()) {
      charBuf.clear();
      // increase the limit to 2
      charBuf.limit(2);
      // decode 2 chars in one pass
      res = decoder.decode(buf, charBuf, isEndOfInput);
      if (res.isMalformed() || res.isUnmappable()) {
        res.throwException();
      }
      charBuf.flip();
      // Check if we successfully decoded 2 chars
      if (charBuf.remaining() == 2) {
        char highSurrogate = charBuf.get();
        // save second (low surrogate) char for later consumption
        lowSurrogate = charBuf.get();
        // Check if we really have a surrogate pair
        if (!Character.isHighSurrogate(highSurrogate) || !Character.isLowSurrogate(lowSurrogate)) {
          // This should only happen in case of bad sequences (dangling surrogate, etc.)
          logger.warn("Decoded a pair of chars, but it does not seem to be a surrogate pair: {} {}",
                      (int)highSurrogate, (int)lowSurrogate);
        }
        hasLowSurrogate = true;
        // consider the pair as a single unit and increment position normally
        delta = buf.position() - start;
        incrPosition(delta, true);
        // return the first (high surrogate) char of the pair
        return highSurrogate;
      }
    }

    // end of file
    incrPosition(delta, false);
    return -1;

  }

  private void refillBuf() throws IOException {
    buf.compact();
    chan.position(position); // ensure we read from the proper offset
    chan.read(buf);
    buf.flip();
  }

  @Override
  public void mark() throws IOException {
    tracker.storePosition(tell());
  }

  @Override
  public void markPosition(long position) throws IOException {
    tracker.storePosition(position);
  }

  @Override
  public long getMarkPosition() throws IOException {
    return tracker.getPosition();
  }

  @Override
  public void reset() throws IOException {
    seek(tracker.getPosition());
  }

  @Override
  public long length() throws IOException {
    return file.length();
  }

  @Override
  public long tell() throws IOException {
    logger.trace("Tell position: {}", syncPosition);

    return syncPosition;
  }

  @Override
  public synchronized void seek(long newPos) throws IOException {
    logger.trace("Seek to position: {}", newPos);

    // check to see if we can seek within our existing buffer
    long relativeChange = newPos - position;
    if (relativeChange == 0) return; // seek to current pos => no-op

    long newBufPos = buf.position() + relativeChange;
    if (newBufPos >= 0 && newBufPos < buf.limit()) {
      // we can reuse the read buffer
      buf.position((int)newBufPos);
    } else {
      // otherwise, we have to invalidate the read buffer
      buf.clear();
      buf.flip();
    }

    // clear decoder state
    decoder.reset();

    // perform underlying file seek
    chan.position(newPos);

    // reset position pointers
    position = syncPosition = newPos;
  }

  private void incrPosition(int incr, boolean updateSyncPosition) {
    position += incr;
    if (updateSyncPosition) {
      syncPosition = position;
    }
  }

  @Override
  public void close() throws IOException {
    tracker.close();
    in.close();
  }

}


text:
import React from "react";
import { observable, runInAction } from "mobx";
import { observer, inject } from "mobx-react";
import { CONFIG_STORE, ConfigStore } from "../stores/ConfigStore";
import { Task, TaskType, MachinePreference, BinaryRequirement, LimitFlag, RPMLimitation, FileRequirements, ConfigState } from "../stores/model";
import LimitationForm from "./formComponents/LimitationForm";
import TextInput from "./formComponents/TextInput";
import TextArea from "./formComponents/TextArea";
import Checkbox from "./formComponents/Checkbox";
import Select from "./formComponents/Select";
import Button from "./Button";

type TaskFormProps = {
    task: Task
    configStore?: ConfigStore;
}

class TaskForm extends React.PureComponent<TaskFormProps> {

    @observable
    task?: Task;

    @observable
    taskState?: ConfigState

    componentDidMount() {
        const task = this.props.task
        this.taskState = task.id === "" ? "create" : "update"
        this.task = { ...task }
    }

    componentDidUpdate() {
        const task = this.props.task
        const state = this.props.configStore!.configState
        if (state !== this.taskState) {
            runInAction(() => {
                this.task = { ...task }
                this.taskState = state
            })
            return
        }
        if (state === "update" && this.task!.id !== task.id) {
            runInAction(() => {
                this.task = { ...task }
            })
        }
    }

    onIdChange = (value: string) => {
        this.task!.id = value
    }

    onTypeChange = (value: string) => {
        this.task!.type = value as TaskType
    }

    onSCMPollScheduleChange = (value: string) => {
        this.task!.scmPollSchedule = value
    }

    onMachinePreferenceChange = (value: string) => {
        this.task!.machinePreference = value as MachinePreference
    }

    onSourcesChange = (value: boolean) => {
        this.task!.fileRequirements.source = value
    }

    onScriptChange = (value: string) => {
        this.task!.script = value
    }

    onBinaryChange = (value: string) => {
        this.task!.fileRequirements.binary = value as BinaryRequirement
    }

    onXmlTemplateChange = (value: string) => {
        this.task!.xmlTemplate = value
    }

    onRPMLimitationFlagChange = (value: string) => {
        this.task!.rpmLimitation.flag = value as LimitFlag
    }

    onRPMLimitationGlobChange = (value: string) => {
        this.task!.rpmLimitation.glob = value
    }

    onSubmit = () => {
        const configStore = this.props.configStore!
        switch (this.taskState) {
            case "create":
                configStore.createConfig(this.task!)
                break
            case "update":
                configStore.updateConfig(this.task!)
                break;
        }
    }

    renderRPMLimitaion = (rpmLimitation: RPMLimitation) => {
        let flag: LimitFlag
        let glob: string
        if (!rpmLimitation) {
            flag = "NONE"
            glob = ""
        } else {
            flag = rpmLimitation.flag || "NONE"
            glob = rpmLimitation.glob || ""
        }
        return (

RPM limitation

                    <Select
                        onChange={this.onRPMLimitationFlagChange}
                        options={["NONE", "WHITELIST", "BLACKLIST"]}
                        value={flag} />
                    {
                        flag !== "NONE" &&
                        <TextInput
                            label={"glob"}
                            onChange={this.onRPMLimitationGlobChange}
                            placeholder={"Enter glob"}
                            value={glob} />
                    }

        )
    }

    renderFileRequirementsForm = (fileRequirements: FileRequirements) => {
        let requireSources = false
        let binaryRequirement: BinaryRequirement = "NONE"
        if (fileRequirements) {
            requireSources = fileRequirements.source || false
            binaryRequirement = fileRequirements.binary || "NONE"
        }
        return (

file requirements

                    <Checkbox
                        label="require sources"
                        onChange={this.onSourcesChange}
                        value={requireSources} />
                    <Select
                        label={"binary requirements"}
                        onChange={this.onBinaryChange}
                        options={["NONE", "BINARY", "BINARIES"]}
                        value={binaryRequirement} />

        )
    }

    render() {
        const configStore = this.props.configStore!;
        if (!this.task) {
            return null
        }
        const configState = configStore.configState
        const { id, fileRequirements, platformLimitation, productLimitation } = this.task;
        return (
            <fieldset>
                <TextInput
                    label={"Task id"}
                    onChange={this.onIdChange}
                    value={id} />
                <Select
                    label={"type"}
                    onChange={this.onTypeChange}
                    options={["BUILD", "TEST"]}
                    value={this.task.type} />
                <Select
                    label={"machine preference"}
                    onChange={this.onMachinePreferenceChange}
                    options={["VM", "VM_ONLY", "HW", "HW_ONLY"]}
                    value={this.task.machinePreference} />
                <TextInput
                    label={"SCM poll schedule"}
                    onChange={this.onSCMPollScheduleChange}
                    value={this.task.scmPollSchedule}>
                </TextInput>
                <TextInput
                    label={"script"}
                    value={this.task.script}
                    onChange={this.onScriptChange}
                    placeholder={"Enter path to bash script"} />
                <LimitationForm
                    label={"platform limitations"}
                    limitation={platformLimitation}
                    items={configStore.platforms} />
                <LimitationForm
                    label={"product limitations"}
                    limitation={productLimitation}
                    items={configStore.products} />
                {this.renderFileRequirementsForm(fileRequirements)}
                <TextArea
                    label={"xml template"}
                    onChange={this.onXmlTemplateChange}
                    placeholder={"Enter xml template for post build tasks"}
                    value={this.task.xmlTemplate} />
                {this.renderRPMLimitaion(this.task.rpmLimitation)}
                <Button onClick={this.onSubmit}>{configState}</Button>

                {JSON.stringify(this.task)}
            </fieldset>
        );
    }
}

export default inject(CONFIG_STORE)(observer(TaskForm));