text:
(function($, F){

	F.Pager = F.Class.extend(/** @lends FooTable.Pager */{
		/**
		 * The pager object contains the page number and direction to page to.
		 * @constructs
		 * @extends FooTable.Class
		 * @param {number} total - The total number of pages available.
		 * @param {number} current - The current page number.
		 * @param {number} size - The number of rows per page.
		 * @param {number} page - The page number to goto.
		 * @param {boolean} forward - A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
		 * @returns {FooTable.Pager}
		 */
		construct: function(total, current, size, page, forward){
			/**
			 * The total number of pages available.
			 * @type {number}
			 */
			this.total = total;
			/**
			 * The current page number.
			 * @type {number}
			 */
			this.current = current;
			/**
			 * The number of rows per page.
			 * @type {number}
			 */
			this.size = size;
			/**
			 * The page number to goto.
			 * @type {number}
			 */
			this.page = page;
			/**
			 * A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
			 * @type {boolean}
			 */
			this.forward = forward;
		}
	});

})(jQuery, FooTable);
(function($, F){
	F.Paging = F.Component.extend(/** @lends FooTable.Paging */{
		/**
		 * The paging component adds a pagination control to the table allowing users to navigate table rows via pages.
		 * @constructs
		 * @extends FooTable.Component
		 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
		 * @returns {FooTable.Filtering}
		 */
		construct: function(table){
			// call the base constructor
			this._super(table, table.o.paging.enabled);

			/* PROTECTED */
			/**
			 * An object containing the strings used by the paging buttons.
			 * @type {{ first: string, prev: string, next: string, last: string }}
			 */
			this.strings = table.o.paging.strings;

			/* PUBLIC */
			/**
			 * The current page number to display.
			 * @instance
			 * @type {number}
			 */
			this.current = table.o.paging.current;
			/**
			 * The number of rows to display per page.
			 * @instance
			 * @type {number}
			 */
			this.size = table.o.paging.size;
			/**
			 * The maximum number of page links to display at once.
			 * @type {number}
			 */
			this.limit = table.o.paging.limit;
			/**
			 * The position of the pagination control within the paging rows cell.
			 * @type {string}
			 */
			this.position = table.o.paging.position;
			/**
			 * The format string used to generate the text displayed under the pagination control.
			 * @type {string}
			 */
			this.countFormat = table.o.paging.countFormat;
			/**
			 * The total number of pages.
			 * @instance
			 * @type {number}
			 */
			this.total = -1;
			/**
			 * The jQuery row object that contains all the paging specific elements.
			 * @instance
			 * @type {jQuery}
			 */
			this.$row = null;
			/**
			 * The jQuery cell object that contains the pagination control and total count.
			 * @instance
			 * @type {jQuery}
			 */
			this.$cell = null;
			/**
			 * The jQuery object that contains the links for the pagination control.
			 * @type {jQuery}
			 */
			this.$pagination = null;
			/**
			 * The jQuery object that contains the row count.
			 * @type {jQuery}
			 */
			this.$count = null;
			/**
			 * Whether or not the pagination row is detached from the table.
			 * @type {boolean}
			 */
			this.detached = false;

			/* PRIVATE */
			/**
			 * A number indicating the previous page displayed.
			 * @private
			 * @type {number}
			 */
			this._previous = 1;
			/**
			 * Used to hold the number of rows in the {@link FooTable.Rows#array} before paging is applied.
			 * @type {number}
			 * @private
			 */
			this._total = 0;
		},

		/* PROTECTED */
		/**
		 * Checks the supplied data and options for the paging component.
		 * @instance
		 * @protected
		 * @param {object} data - The jQuery data object from the parent table.
		 * @fires FooTable.Paging#"preinit.ft.paging"
		 */
		preinit: function(data){
			var self = this;
			/**
			 * The preinit.ft.paging event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
			 * Calling preventDefault on this event will disable the component.
			 * @event FooTable.Paging#"preinit.ft.paging"
			 * @param {jQuery.Event} e - The jQuery.Event object for the event.
			 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
			 * @param {object} data - The jQuery data object of the table raising the event.
			 */
			this.ft.raise('preinit.ft.paging', [data]).then(function(){
				if (self.ft.$el.hasClass('footable-paging'))
					self.enabled = true;
				self.enabled = F.is.boolean(data.paging)
					? data.paging
					: self.enabled;

				if (!self.enabled) return;

				self.size = F.is.number(data.pagingSize)
					? data.pagingSize
					: self.size;

				self.current = F.is.number(data.pagingCurrent)
					? data.pagingCurrent
					: self.current;

				self.limit = F.is.number(data.pagingLimit)
					? data.pagingLimit
					: self.limit;

				if (self.ft.$el.hasClass('footable-paging-left'))
					self.position = 'left';
				if (self.ft.$el.hasClass('footable-paging-center'))
					self.position = 'center';
				if (self.ft.$el.hasClass('footable-paging-right'))
					self.position = 'right';

				self.position = F.is.string(data.pagingPosition)
					? data.pagingPosition
					: self.position;

				self.countFormat = F.is.string(data.pagingCountFormat)
					? data.pagingCountFormat
					: self.countFormat;

				self.total = Math.ceil(self.ft.rows.all.length / self.size);
			}, function(){
				self.enabled = false;
			});
		},
		/**
		 * Initializes the paging component for the plugin using the supplied table and options.
		 * @instance
		 * @protected
		 * @fires FooTable.Paging#"init.ft.paging"
		 */
		init: function(){
			/**
			 * The init.ft.paging event is raised before its UI is generated.
			 * Calling preventDefault on this event will disable the component.
			 * @event FooTable.Paging#"init.ft.paging"
			 * @param {jQuery.Event} e - The jQuery.Event object for the event.
			 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
			 */
			var self = this;
			this.ft.raise('init.ft.paging').then(function(){
				self.$create();
			}, function(){
				self.enabled = false;
			});
		},
		/**
		 * Destroys the paging component removing any UI generated from the table.
		 * @instance
		 * @protected
		 * @fires FooTable.Paging#"destroy.ft.paging"
		 */
		destroy: function () {
			/**
			 * The destroy.ft.paging event is raised before its UI is removed.
			 * Calling preventDefault on this event will prevent the component from being destroyed.
			 * @event FooTable.Paging#"destroy.ft.paging"
			 * @param {jQuery.Event} e - The jQuery.Event object for the event.
			 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
			 */
			var self = this;
			this.ft.raise('destroy.ft.paging').then(function(){
				self.ft.$el.removeClass('footable-paging')
					.find('tfoot > tr.footable-paging').remove();
				self.detached = false;
			});
		},
		/**
		 * Performs the actual paging against the {@link FooTable.Rows#current} array removing all rows that are not on the current visible page.
		 * @instance
		 * @protected
		 */
		predraw: function(){
			this.total = Math.ceil(this.ft.rows.array.length / this.size);
			this.current = this.current > this.total ? this.total : (this.current < 1 ? 1 : this.current);
			if (this.ft.rows.array.length > this.size){
				this.ft.rows.array = this.ft.rows.array.splice((this.current - 1) * this.size, this.size);
			}
		},
		/**
		 * Updates the paging UI setting the state of the pagination control.
		 * @instance
		 * @protected
		 */
		draw: function(){
			if (this.total <= 1){
				if (!this.detached){
					this.$row.detach();
					this.detached = true;
				}
			} else {
				if (this.detached){
					var $tfoot = this.ft.$el.children('tfoot');
					if ($tfoot.length == 0){
						$tfoot = $('<tfoot/>');
						this.ft.$el.append($tfoot);
					}
					this.$row.appendTo($tfoot);
					this.detached = false;
				}
				this.$cell.attr('colspan', this.ft.columns.visibleColspan);
				this._createLinks();
				this._setVisible(this.current, this.current > this._previous);
				this._setNavigation(true);
			}
		},
		/**
		 * Creates the paging UI from the current options setting the various jQuery properties of this component.
		 * @instance
		 * @protected
		 */
		$create: function(){
			var position = 'footable-paging-center';
			switch (this.position){
				case 'left': position = 'footable-paging-left'; break;
				case 'right': position = 'footable-paging-right'; break;
			}
			this.ft.$el.addClass('footable-paging').addClass(position);
			this.$cell = $('<td/>').attr('colspan', this.ft.columns.visibleColspan);
			var $tfoot = this.ft.$el.children('tfoot');
			if ($tfoot.length == 0){
				$tfoot = $('<tfoot/>');
				this.ft.$el.append($tfoot);
			}
			this.$row = $('<tr/>', { 'class': 'footable-paging' }).append(this.$cell).appendTo($tfoot);
			this.$pagination = $('<ul/>', { 'class': 'pagination' }).on('click.footable', 'a.footable-page-link', { self: this }, this._onPageClicked);
			this.$count = $('<span/>', { 'class': 'label label-default' });
			this.$cell.append(this.$pagination, $('<div/>', {'class': 'divider'}), this.$count);
			this.detached = false;
			this._createLinks();
		},

		/* PUBLIC */
		/**
		 * Pages to the first page.
		 * @instance
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		first: function(){
			return this._set(1);
		},
		/**
		 * Pages to the previous page.
		 * @instance
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		prev: function(){
			return this._set(this.current - 1 > 0 ? this.current - 1 : 1);
		},
		/**
		 * Pages to the next page.
		 * @instance
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		next: function(){
			return this._set(this.current + 1 < this.total ? this.current + 1 : this.total);
		},
		/**
		 * Pages to the last page.
		 * @instance
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		last: function(){
			return this._set(this.total);
		},
		/**
		 * Pages to the specified page.
		 * @instance
		 * @param {number} page - The page number to go to.
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		goto: function(page){
			return this._set(page > this.total ? this.total : (page < 1 ? 1 : page));
		},
		/**
		 * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
		 * @instance
		 */
		prevPages: function(){
			var page = this.$pagination.children('li.footable-page.visible:first').data('page') - 1;
			this._setVisible(page, true);
			this._setNavigation(false);
		},
		/**
		 * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
		 * @instance
		 */
		nextPages: function(){
			var page = this.$pagination.children('li.footable-page.visible:last').data('page') + 1;
			this._setVisible(page, false);
			this._setNavigation(false);
		},
		/**
		 * Gets or sets the current page size
		 * @instance
		 * @param {number} [value] - The new page size to use.
		 * @returns {(number|undefined)}
		 */
		pageSize: function(value){
			if (!F.is.number(value)){
				return this.size;
			}
			this.size = value;
			this.total = Math.ceil(this.ft.rows.all.length / this.size);
			if (F.is.jq(this.$row)) this.$row.remove();
			this.$create();
			this.ft.draw();
		},

		/* PRIVATE */
		/**
		 * Performs the required steps to handle paging including the raising of the {@link FooTable.Paging#"before.ft.paging"} and {@link FooTable.Paging#"after.ft.paging"} events.
		 * @instance
		 * @private
		 * @param {number} page - The page to set.
		 * @returns {jQuery.Promise}
		 * @fires FooTable.Paging#"before.ft.paging"
		 * @fires FooTable.Paging#"after.ft.paging"
		 */
		_set: function(page){
			var self = this,
				pager = new F.Pager(self.total, self.current, self.size, page, page > self.current);
			/**
			 * The before.ft.paging event is raised before a sort is applied and allows listeners to modify the pager or cancel it completely by calling preventDefault on the jQuery.Event object.
			 * @event FooTable.Paging#"before.ft.paging"
			 * @param {jQuery.Event} e - The jQuery.Event object for the event.
			 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
			 * @param {FooTable.Pager} pager - The pager that is about to be applied.
			 */
			return self.ft.raise('before.ft.paging', [pager]).then(function(){
				pager.page = pager.page > pager.total ? pager.total	: pager.page;
				pager.page = pager.page < 1 ? 1 : pager.page;
				if (self.current == page) return $.when();
				self._previous = self.current;
				self.current = pager.page;
				return self.ft.draw().then(function(){
					/**
					 * The after.ft.paging event is raised after a pager has been applied.
					 * @event FooTable.Paging#"after.ft.paging"
					 * @param {jQuery.Event} e - The jQuery.Event object for the event.
					 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
					 * @param {FooTable.Pager} pager - The pager that has been applied.
					 */
					self.ft.raise('after.ft.paging', [pager]);
				});
			});
		},
		/**
		 * Creates the pagination links using the current state of the plugin. If the total number of pages is the same as
		 * the last time this function was executed it does nothing.
		 * @instance
		 * @private
		 */
		_createLinks: function(){
			if (this._total === this.total) return;
			var self = this,
				multiple = self.total > 1,
				link = function(attr, html, klass){
					return $('<li/>', {
						'class': klass
					}).attr('data-page', attr)
						.append($('<a/>', {
							'class': 'footable-page-link',
							href: '#'
						}).data('page', attr).html(html));
				};
			self.$pagination.empty();
			if (multiple) {
				self.$pagination.append(link('first', self.strings.first, 'footable-page-nav'));
				self.$pagination.append(link('prev', self.strings.prev, 'footable-page-nav'));
				if (self.limit > 0 && self.limit < self.total){
					self.$pagination.append(link('prev-limit', self.strings.prevPages, 'footable-page-nav'));
				}
			}
			for (var i = 0, $li; i < self.total; i++){
				$li = link(i + 1, i + 1, 'footable-page');
				self.$pagination.append($li);
			}
			if (multiple){
				if (self.limit > 0 && self.limit < self.total){
					self.$pagination.append(link('next-limit', self.strings.nextPages, 'footable-page-nav'));
				}
				self.$pagination.append(link('next', self.strings.next, 'footable-page-nav'));
				self.$pagination.append(link('last', self.strings.last, 'footable-page-nav'));
			}
			self._total = self.total;
		},
		/**
		 * Sets the state for the navigation links of the pagination control and optionally sets the active class state on the current page link.
		 * @instance
		 * @private
		 * @param {boolean} active - Whether or not to set the active class state on the individual page links.
		 */
		_setNavigation: function(active){
			if (this.current == 1) {
				this.$pagination.children('li[data-page="first"],li[data-page="prev"]').addClass('disabled');
			} else {
				this.$pagination.children('li[data-page="first"],li[data-page="prev"]').removeClass('disabled');
			}

			if (this.current == this.total) {
				this.$pagination.children('li[data-page="next"],li[data-page="last"]').addClass('disabled');
			} else {
				this.$pagination.children('li[data-page="next"],li[data-page="last"]').removeClass('disabled');
			}

			if ((this.$pagination.children('li.footable-page.visible:first').data('page') || 1) == 1) {
				this.$pagination.children('li[data-page="prev-limit"]').addClass('disabled');
			} else {
				this.$pagination.children('li[data-page="prev-limit"]').removeClass('disabled');
			}

			if ((this.$pagination.children('li.footable-page.visible:last').data('page') || this.limit) == this.total) {
				this.$pagination.children('li[data-page="next-limit"]').addClass('disabled');
			} else {
				this.$pagination.children('li[data-page="next-limit"]').removeClass('disabled');
			}

			if (this.limit > 0 && this.total < this.limit){
				this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').hide();
			} else {
				this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').show();
			}

			if (active){
				this.$pagination.children('li.footable-page').removeClass('active').filter('li[data-page="' + this.current + '"]').addClass('active');
			}
		},
		/**
		 * Sets the visible page using the supplied parameters.
		 * @instance
		 * @private
		 * @param {number} page - The page to make visible.
		 * @param {boolean} right - If set to true the supplied page will be the right most visible pagination link.
		 */
		_setVisible: function(page, right){
			if (this.limit > 0 && this.total > this.limit){
				if (!this.$pagination.children('li.footable-page[data-page="'+page+'"]').hasClass('visible')){
					var start = 0, end = 0;
					if (right == true){
						end = page > this.total ? this.total : page;
						start = end - this.limit;
					} else {
						start = page < 1 ? 0 : page - 1;
						end = start + this.limit;
					}
					if (start < 0){
						start = 0;
						end = this.limit > this.total ? this.total : this.limit;
					}
					if (end > this.total){
						end = this.total;
						start = this.total - this.limit < 0 ? 0 : this.total - this.limit;
					}
					this.$pagination.children('li.footable-page').removeClass('visible').slice(start, end).addClass('visible');
				}
			} else {
				this.$pagination.children('li.footable-page').removeClass('visible').slice(0, this.total).addClass('visible');
			}
			var first = (this.size * (page - 1)) + 1,
				last = this.size * page,
				totalRows = this.ft.rows.all.length;
			if (this.ft.rows.array.length == 0){
				first = 0;
				last = 0;
			} else {
				last = last > totalRows ? totalRows : last;
			}
			this._setCount(page, this.total, first, last, totalRows);
		},
		/**
		 * Uses the countFormat option to generate the text using the supplied parameters.
		 * @param {number} currentPage - The current page.
		 * @param {number} totalPages - The total number of pages.
		 * @param {number} pageFirst - The first row number of the current page.
		 * @param {number} pageLast - The last row number of the current page.
		 * @param {number} totalRows - The total number of rows.
		 * @private
		 */
		_setCount: function(currentPage, totalPages, pageFirst, pageLast, totalRows){
			this.$count.text(this.countFormat.replace(/\{CP}/g, currentPage)
				.replace(/\{TP}/g, totalPages)
				.replace(/\{PF}/g, pageFirst)
				.replace(/\{PL}/g, pageLast)
				.replace(/\{TR}/g, totalRows));
		},
		/**
		 * Handles the click event for all links in the pagination control.
		 * @instance
		 * @private
		 * @param {jQuery.Event} e - The event object for the event.
		 */
		_onPageClicked: function(e){
			e.preventDefault();
			if ($(e.target).closest('li').is('.active,.disabled')) return;

			var self = e.data.self, page = $(this).data('page');
			switch(page){
				case 'first': self.first();
					return;
				case 'prev': self.prev();
					return;
				case 'next': self.next();
					return;
				case 'last': self.last();
					return;
				case 'prev-limit': self.prevPages();
					return;
				case 'next-limit': self.nextPages();
					return;
				default: self._set(page);
					return;
			}
		}
	});

	F.components.core.register('paging', F.Paging, 0);

})(jQuery, FooTable);
(function(F){
	/**
	 * An object containing the paging options for the plugin. Added by the {@link FooTable.Paging} component.
	 * @type {object}
	 * @prop {boolean} enabled=false - Whether or not to allow paging on the table.
	 * @prop {string} countFormat="{CP} of {TP}" - A string format used to generate the page count text.
	 * @prop {number} current=1 - The page number to display.
	 * @prop {number} limit=5 - The maximum number of page links to display at once.
	 * @prop {string} position="center" - The string used to specify the alignment of the pagination control.
	 * @prop {number} size=10 - The number of rows displayed per page.
	 * @prop {object} strings - An object containing the strings used by the paging buttons.
	 * @prop {string} strings.first="«" - The string used for the 'first' button.
	 * @prop {string} strings.prev="‹" - The string used for the 'previous' button.
	 * @prop {string} strings.next="›" - The string used for the 'next' button.
	 * @prop {string} strings.last="»" - The string used for the 'last' button.
	 * @prop {string} strings.prevPages="..." - The string used for the 'previous X pages' button.
	 * @prop {string} strings.nextPages="..." - The string used for the 'next X pages' button.
	 */
	F.Defaults.prototype.paging = {
		enabled: false,
		countFormat: '{CP} of {TP}',
		current: 1,
		limit: 5,
		position: 'center',
		size: 10,
		strings: {
			first: '«',
			prev: '‹',
			next: '›',
			last: '»',
			prevPages: '...',
			nextPages: '...'
		}
	};
})(FooTable);
(function(F){
	/**
	 * Navigates to the specified page number. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @param {number} num - The page number to go to.
	 * @returns {jQuery.Promise}
	 * @fires FooTable.Paging#paging_changing
	 * @fires FooTable.Paging#paging_changed
	 * @see FooTable.Paging#goto
	 */
	F.Table.prototype.gotoPage = function(num){
		return this.use(F.Paging).goto(num);
	};

	/**
	 * Navigates to the next page. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @returns {jQuery.Promise}
	 * @fires FooTable.Paging#paging_changing
	 * @fires FooTable.Paging#paging_changed
	 * @see FooTable.Paging#next
	 */
	F.Table.prototype.nextPage = function(){
		return this.use(F.Paging).next();
	};

	/**
	 * Navigates to the previous page. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @returns {jQuery.Promise}
	 * @fires FooTable.Paging#paging_changing
	 * @fires FooTable.Paging#paging_changed
	 * @see FooTable.Paging#prev
	 */
	F.Table.prototype.prevPage = function(){
		return this.use(F.Paging).prev();
	};

	/**
	 * Navigates to the first page. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @returns {jQuery.Promise}
	 * @fires FooTable.Paging#paging_changing
	 * @fires FooTable.Paging#paging_changed
	 * @see FooTable.Paging#first
	 */
	F.Table.prototype.firstPage = function(){
		return this.use(F.Paging).first();
	};

	/**
	 * Navigates to the last page. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @returns {jQuery.Promise}
	 * @fires FooTable.Paging#paging_changing
	 * @fires FooTable.Paging#paging_changed
	 * @see FooTable.Paging#last
	 */
	F.Table.prototype.lastPage = function(){
		return this.use(F.Paging).last();
	};

	/**
	 * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @see FooTable.Paging#nextPages
	 */
	F.Table.prototype.nextPages = function(){
		return this.use(F.Paging).nextPages();
	};

	/**
	 * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
	 * @instance
	 * @see FooTable.Paging#prevPages
	 */
	F.Table.prototype.prevPages = function(){
		return this.use(F.Paging).prevPages();
	};

	/**
	 * Gets or sets the current page size
	 * @instance
	 * @param {number} [value] - The new page size to use.
	 * @returns {(number|undefined)}
	 * @see FooTable.Paging#pageSize
	 */
	F.Table.prototype.pageSize = function(value){
		return this.use(F.Paging).pageSize(value);
	};
})(FooTable);


text:
package java.io;

/**
 * The lowest-level representation of a file, device, or
 * socket. If is often used for wrapping an operating system "handle". Some
 * I/O classes can be queried for the FileDescriptor they are operating on, and
 * this descriptor can subsequently be used during the instantiation of another
 * I/O class, so that the new object will reuse it.
 *

 * The FileDescriptor class also contains static fields representing the
 * system's standard input, output and error streams. These can be used directly
 * if desired, but it is recommended to go through System.in, System.out, and
 * System.err streams respectively.
 *

 * Applications should not create new FileDescriptors.
 *
 * @see FileInputStream#getFD()
 * @see FileOutputStream#getFD()
 * @see RandomAccessFile#getFD()
 */
public final class FileDescriptor {

    /**
     * The FileDescriptor representing standard input.
     */
    public static final FileDescriptor in = new FileDescriptor();

    /**
     * FileDescriptor representing standard out.
     */
    public static final FileDescriptor out = new FileDescriptor();

    /**
     * FileDescriptor representing standard error.
     */
    public static final FileDescriptor err = new FileDescriptor();

    // BEGIN android-changed
    // file descriptors are only int on android
    /**
     * Represents a link to any underlying OS resources for this FileDescriptor.
     * A value of -1 indicates that this FileDescriptor is invalid.
     */
    int descriptor = -1;
    // END android-changed

    boolean readOnly = false;

    static {
        in.descriptor = 0;
        out.descriptor = 1;
        err.descriptor = 2;
    }

    /**
     * Constructs a new FileDescriptor containing an invalid handle. The
     * contained handle is usually modified by native code at a later point.
     */
    public FileDescriptor() {
        super();
    }

    /**
     * Ensures that data which is buffered within the underlying implementation
     * is written out to the appropriate device before returning.
     *
     * @throws SyncFailedException
     *             when the operation fails.
     */
    public void sync() throws SyncFailedException {
        // if the descriptor is a read-only one, do nothing
        if (!readOnly) {
            syncImpl();
        }
    }

    private native void syncImpl() throws SyncFailedException;

    /**
     * Indicates whether this FileDescriptor is valid.
     *
     * @return {@code true} if this FileDescriptor is valid, {@code false}
     *         otherwise.
     */
    public boolean valid() {
        return descriptor != -1;
    }

    @Override public String toString() {
        return "FileDescriptor[" + descriptor + "]";
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Neos\Flow\Tests\Unit\ObjectManagement;

require_once(__DIR__ . '/Fixture/BasicClass.php');

use Neos\Flow\ObjectManagement\ObjectManager;
use Neos\Flow\Tests\Unit\ObjectManagement\Fixture\BasicClass;
use Neos\Flow\Tests\UnitTestCase;
use Neos\Flow\ObjectManagement\Configuration\Configuration as ObjectConfiguration;

class ObjectManagerTest extends UnitTestCase
{
    public function factoryGenerationDataProvider()
    {
        return [
            'generatePrototype' => [
                'scope' => ObjectConfiguration::SCOPE_PROTOTYPE,
                'factoryCalls' => 2
            ],
            'generateSingleton' => [
                'scope' => ObjectConfiguration::SCOPE_SINGLETON,
                'factoryCalls' => 1
            ]
        ];
    }

    /**
     * @test
     * @dataProvider factoryGenerationDataProvider
     *
     * @param integer $scope
     * @param integer $factoryCalls
     */
    public function getFactoryGeneratedPrototypeObject($scope, $factoryCalls)
    {
        /** @var ObjectManager $objectManager */
        $objectManager = $this->getMockBuilder(ObjectManager::class)
            ->disableOriginalConstructor()
            ->setMethods(['buildObjectByFactory'])->getMock();
        $objectManager->expects($this->exactly($factoryCalls))
            ->method('buildObjectByFactory')->will($this->returnCallback(function () {
                return new BasicClass();
            }));

        $objects = [
            BasicClass::class => [
                'f' => 'SomeFactory',
                's' => $scope
            ]
        ];
        $objectManager->setObjects($objects);

        $object1 = $objectManager->get(BasicClass::class);
        $object2 = $objectManager->get(BasicClass::class);

        if ($scope == ObjectConfiguration::SCOPE_PROTOTYPE) {
            $this->assertNotSame($object1, $object2);
        } else {
            $this->assertSame($object1, $object2);
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta zingiberi T.S. Ramakr.

### Remarks
null


text:
@import "tailwindcss/base";

@import "fonts.css";

@import "tailwindcss/components";
@import "tailwindcss/utilities";

@import "custom.css";


text:
package internal

import (
	"strings"
)

func parseFullAppID(appid string) (partition, domain, displayID string) {
	if i := strings.Index(appid, "~"); i != -1 {
		partition, appid = appid[:i], appid[i+1:]
	}
	if i := strings.Index(appid, ":"); i != -1 {
		domain, appid = appid[:i], appid[i+1:]
	}
	return partition, domain, appid
}

// appID returns "appid" or "domain.com:appid".
func appID(fullAppID string) string {
	_, dom, dis := parseFullAppID(fullAppID)
	if dom != "" {
		return dom + ":" + dis
	}
	return dis
}


text:
package org.apache.taverna.activities.spreadsheet.servicedescriptions;

import java.awt.Color;
import java.net.URI;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.apache.taverna.workbench.activityicons.ActivityIconSPI;
import org.apache.taverna.workbench.configuration.colour.ColourManager;

/**
 * UI icon for the SpreadsheetImport Activity.
 *
 * @author David Withers
 */
public class SpreadsheetImportActivityIcon implements ActivityIconSPI {

	public static final String SPREADSHEET_COLOUR_HTML = "#40e0d0";
	public static final Color SPREADSHEET_COLOUR = Color.decode(SPREADSHEET_COLOUR_HTML);

	private static Icon icon = null;

	@Override
	public int canProvideIconScore(URI activityType) {
		if (SpreadsheetImportTemplateService.ACTIVITY_TYPE.equals(activityType))
			return DEFAULT_ICON + 1;
		else
			return NO_ICON;
	}

	@Override
	public Icon getIcon(URI activityType) {
		return getSpreadsheetImportIcon();
	}

	public static Icon getSpreadsheetImportIcon() {
		if (icon == null) {
			icon = new ImageIcon(
					SpreadsheetImportActivityIcon.class.getResource("/spreadsheet-import.png"));
		}
		return icon;
	}

	public void setColourManager(ColourManager colourManager) {
		colourManager.setPreferredColour(
				"http://ns.taverna.org.uk/2010/activity/spreadsheet-import",
				SPREADSHEET_COLOUR);
	}

}


text:
#include "streams/curl.h"

#ifdef GIT_CURL

#include <curl/curl.h>

#include "stream.h"
#include "git2/transport.h"
#include "buffer.h"
#include "global.h"
#include "vector.h"
#include "proxy.h"

/* This is for backwards compatibility with curl<7.45.0. */
#ifndef CURLINFO_ACTIVESOCKET
# define CURLINFO_ACTIVESOCKET CURLINFO_LASTSOCKET
# define GIT_CURL_BADSOCKET -1
# define git_activesocket_t long
#else
# define GIT_CURL_BADSOCKET CURL_SOCKET_BAD
# define git_activesocket_t curl_socket_t
#endif

typedef struct {
	git_stream parent;
	CURL *handle;
	curl_socket_t socket;
	char curl_error[CURL_ERROR_SIZE + 1];
	git_cert_x509 cert_info;
	git_strarray cert_info_strings;
	git_proxy_options proxy;
	git_cred *proxy_cred;
} curl_stream;

int git_curl_stream_global_init(void)
{
	if (curl_global_init(CURL_GLOBAL_ALL) != 0) {
		giterr_set(GITERR_NET, "could not initialize curl");
		return -1;
	}

	/* `curl_global_cleanup` is provided by libcurl */
	git__on_shutdown(curl_global_cleanup);
	return 0;
}

static int seterr_curl(curl_stream *s)
{
	giterr_set(GITERR_NET, "curl error: %s\n", s->curl_error);
	return -1;
}

GIT_INLINE(int) error_no_credentials(void)
{
	giterr_set(GITERR_NET, "proxy authentication required, but no callback provided");
	return GIT_EAUTH;
}

static int apply_proxy_creds(curl_stream *s)
{
	CURLcode res;
	git_cred_userpass_plaintext *userpass;

	if (!s->proxy_cred)
		return GIT_ENOTFOUND;

	userpass = (git_cred_userpass_plaintext *) s->proxy_cred;
	if ((res = curl_easy_setopt(s->handle, CURLOPT_PROXYUSERNAME, userpass->username)) != CURLE_OK)
		return seterr_curl(s);
	if ((res = curl_easy_setopt(s->handle, CURLOPT_PROXYPASSWORD, userpass->password)) != CURLE_OK)
		return seterr_curl(s);

	return 0;
}

static int ask_and_apply_proxy_creds(curl_stream *s)
{
	int error;
	git_proxy_options *opts = &s->proxy;

	if (!opts->credentials)
		return error_no_credentials();

	/* TODO: see if PROXYAUTH_AVAIL helps us here */
	git_cred_free(s->proxy_cred);
	s->proxy_cred = NULL;
	giterr_clear();
	error = opts->credentials(&s->proxy_cred, opts->url, NULL, GIT_CREDTYPE_USERPASS_PLAINTEXT, opts->payload);
	if (error == GIT_PASSTHROUGH)
		return error_no_credentials();
	if (error < 0) {
		if (!giterr_last())
			giterr_set(GITERR_NET, "proxy authentication was aborted by the user");
		return error;
	}

	if (s->proxy_cred->credtype != GIT_CREDTYPE_USERPASS_PLAINTEXT) {
		giterr_set(GITERR_NET, "credentials callback returned invalid credential type");
		return -1;
	}

	return apply_proxy_creds(s);
}

static int curls_connect(git_stream *stream)
{
	curl_stream *s = (curl_stream *) stream;
	git_activesocket_t sockextr;
	long connect_last = 0;
	int failed_cert = 0, error;
	bool retry_connect;
	CURLcode res;

	/* Apply any credentials we've already established */
	error = apply_proxy_creds(s);
	if (error < 0 && error != GIT_ENOTFOUND)
		return seterr_curl(s);

	do {
		retry_connect = 0;
		res = curl_easy_perform(s->handle);

		curl_easy_getinfo(s->handle, CURLINFO_HTTP_CONNECTCODE, &connect_last);

		/* HTTP 407 Proxy Authentication Required */
		if (connect_last == 407) {
			if ((error = ask_and_apply_proxy_creds(s)) < 0)
				return error;

			retry_connect = true;
		}
	} while (retry_connect);

	if (res != CURLE_OK && res != CURLE_PEER_FAILED_VERIFICATION)
		return seterr_curl(s);
	if (res == CURLE_PEER_FAILED_VERIFICATION)
		failed_cert = 1;

	if ((res = curl_easy_getinfo(s->handle, CURLINFO_ACTIVESOCKET, &sockextr)) != CURLE_OK) {
		return seterr_curl(s);
	}

	if (sockextr == GIT_CURL_BADSOCKET) {
		giterr_set(GITERR_NET, "curl socket is no longer valid");
		return -1;
	}

	s->socket = sockextr;

	if (s->parent.encrypted && failed_cert)
		return GIT_ECERTIFICATE;

	return 0;
}

static int curls_certificate(git_cert **out, git_stream *stream)
{
	int error;
	CURLcode res;
	struct curl_slist *slist;
	struct curl_certinfo *certinfo;
	git_vector strings = GIT_VECTOR_INIT;
	curl_stream *s = (curl_stream *) stream;

	if ((res = curl_easy_getinfo(s->handle, CURLINFO_CERTINFO, &certinfo)) != CURLE_OK)
		return seterr_curl(s);

	/* No information is available, can happen with SecureTransport */
	if (certinfo->num_of_certs == 0) {
		s->cert_info.parent.cert_type = GIT_CERT_NONE;
		s->cert_info.data             = NULL;
		s->cert_info.len              = 0;
		return 0;
	}

	if ((error = git_vector_init(&strings, 8, NULL)) < 0)
		return error;

	for (slist = certinfo->certinfo[0]; slist; slist = slist->next) {
		char *str = git__strdup(slist->data);
		GITERR_CHECK_ALLOC(str);
		git_vector_insert(&strings, str);
	}

	/* Copy the contents of the vector into a strarray so we can expose them */
	s->cert_info_strings.strings = (char **) strings.contents;
	s->cert_info_strings.count   = strings.length;

	s->cert_info.parent.cert_type = GIT_CERT_STRARRAY;
	s->cert_info.data             = &s->cert_info_strings;
	s->cert_info.len              = strings.length;

	*out = &s->cert_info.parent;

	return 0;
}

static int curls_set_proxy(git_stream *stream, const git_proxy_options *proxy_opts)
{
	int error;
	CURLcode res;
	curl_stream *s = (curl_stream *) stream;

	git_proxy_options_clear(&s->proxy);
	if ((error = git_proxy_options_dup(&s->proxy, proxy_opts)) < 0)
		return error;

	if ((res = curl_easy_setopt(s->handle, CURLOPT_PROXY, s->proxy.url)) != CURLE_OK)
		return seterr_curl(s);

	if ((res = curl_easy_setopt(s->handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY)) != CURLE_OK)
		return seterr_curl(s);

	return 0;
}

static int wait_for(curl_socket_t fd, bool reading)
{
	int ret;
	fd_set infd, outfd, errfd;

	FD_ZERO(&infd);
	FD_ZERO(&outfd);
	FD_ZERO(&errfd);

	assert(fd >= 0);
	FD_SET(fd, &errfd);
	if (reading)
		FD_SET(fd, &infd);
	else
		FD_SET(fd, &outfd);

	if ((ret = select(fd + 1, &infd, &outfd, &errfd, NULL)) < 0) {
		giterr_set(GITERR_OS, "error in select");
		return -1;
	}

	return 0;
}

static ssize_t curls_write(git_stream *stream, const char *data, size_t len, int flags)
{
	int error;
	size_t off = 0, sent;
	CURLcode res;
	curl_stream *s = (curl_stream *) stream;

	GIT_UNUSED(flags);

	do {
		if ((error = wait_for(s->socket, false)) < 0)
			return error;

		res = curl_easy_send(s->handle, data + off, len - off, &sent);
		if (res == CURLE_OK)
			off += sent;
	} while ((res == CURLE_OK || res == CURLE_AGAIN) && off < len);

	if (res != CURLE_OK)
		return seterr_curl(s);

	return len;
}

static ssize_t curls_read(git_stream *stream, void *data, size_t len)
{
	int error;
	size_t read;
	CURLcode res;
	curl_stream *s = (curl_stream *) stream;

	do {
		if ((error = wait_for(s->socket, true)) < 0)
			return error;

		res = curl_easy_recv(s->handle, data, len, &read);
	} while (res == CURLE_AGAIN);

	if (res != CURLE_OK)
		return seterr_curl(s);

	return read;
}

static int curls_close(git_stream *stream)
{
	curl_stream *s = (curl_stream *) stream;

	if (!s->handle)
		return 0;

	curl_easy_cleanup(s->handle);
	s->handle = NULL;
	s->socket = 0;

	return 0;
}

static void curls_free(git_stream *stream)
{
	curl_stream *s = (curl_stream *) stream;

	curls_close(stream);
	git_strarray_free(&s->cert_info_strings);
	git_proxy_options_clear(&s->proxy);
	git_cred_free(s->proxy_cred);
	git__free(s);
}

int git_curl_stream_new(git_stream **out, const char *host, const char *port)
{
	curl_stream *st;
	CURL *handle;
	int iport = 0, error;

	st = git__calloc(1, sizeof(curl_stream));
	GITERR_CHECK_ALLOC(st);

	handle = curl_easy_init();
	if (handle == NULL) {
		giterr_set(GITERR_NET, "failed to create curl handle");
		git__free(st);
		return -1;
	}

	if ((error = git__strntol32(&iport, port, strlen(port), NULL, 10)) < 0) {
		git__free(st);
		return error;
	}

	curl_easy_setopt(handle, CURLOPT_URL, host);
	curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, st->curl_error);
	curl_easy_setopt(handle, CURLOPT_PORT, iport);
	curl_easy_setopt(handle, CURLOPT_CONNECT_ONLY, 1);
	curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 1);
	curl_easy_setopt(handle, CURLOPT_CERTINFO, 1);
	curl_easy_setopt(handle, CURLOPT_HTTPPROXYTUNNEL, 1);
	curl_easy_setopt(handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);

	/* curl_easy_setopt(handle, CURLOPT_VERBOSE, 1); */

	st->parent.version = GIT_STREAM_VERSION;
	st->parent.encrypted = 0; /* we don't encrypt ourselves */
	st->parent.proxy_support = 1;
	st->parent.connect = curls_connect;
	st->parent.certificate = curls_certificate;
	st->parent.set_proxy = curls_set_proxy;
	st->parent.read = curls_read;
	st->parent.write = curls_write;
	st->parent.close = curls_close;
	st->parent.free = curls_free;
	st->handle = handle;

	*out = (git_stream *) st;
	return 0;
}

#else

#include "stream.h"

int git_curl_stream_global_init(void)
{
	return 0;
}

int git_curl_stream_new(git_stream **out, const char *host, const char *port)
{
	GIT_UNUSED(out);
	GIT_UNUSED(host);
	GIT_UNUSED(port);

	giterr_set(GITERR_NET, "curl is not supported in this version");
	return -1;
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NiL.JS.Core;

namespace IntegrationTests.Core
{
    [TestClass]
    public class ParserTests
    {
        [TestMethod]
        public void ValidateShouldNotUpdateIndexIfReturnedFalse()
        {
            var index = 0;
            var text = "1234";

            var result = Parser.Validate(text, "12", ref index);

            Assert.IsFalse(result);
            Assert.AreEqual(0, index);
        }
    }
}


text:
/* Attention!
*  To maintain compliance with Nordic Semiconductor ASA's Bluetooth profile
*  qualification listings, this section of source code must not be modified.
*/

#include "lib_aci.h"
#include "services.h"
#include "battery.h"
#include "lib_battery_level.h"
#include "hrm_definitions.h"

static uint8_t battery_data_buffer[BATTERY_DATA_BUFF_SIZE];
static uint8_t batt_data_buff_insert_ptr;
static uint8_t batt_data_buff_fetch_ptr;

static uint32_t ADC_output_value;
static float calculated_mvolts;
static float AIN_mvolts;
static float supply_mvolts;
static uint8_t battery_perc_level;

static uint32_t timestamp;

static uint8_t batt_percentage_simulated = 100;
static uint8_t previous_battery_level      = NO_DATA;
static uint8_t battery_level_on_disconnect = NO_DATA;
static uint8_t percent_level_on_connect    = NO_DATA;

void init_battery_data_buffers()
{
	int i;

	for(i=0;i<BATTERY_DATA_BUFF_SIZE;i++)
	{
		battery_data_buffer[i] = NO_DATA;
	}
	batt_data_buff_fetch_ptr = 0;
	batt_data_buff_insert_ptr = 0;
}

uint8_t insert_data_into_battery_buffer(uint8_t battery_percent_level)
{
	if(battery_data_buffer[batt_data_buff_insert_ptr] != NO_DATA)
	{
		return BUFFER_FULL;
	}
	else
	{
		battery_data_buffer[batt_data_buff_insert_ptr] = battery_percent_level;

		//Move data-buffer insert pointer location
		if(batt_data_buff_insert_ptr == (BATTERY_DATA_BUFF_SIZE - 1))
			batt_data_buff_insert_ptr = 0;
		else
			batt_data_buff_insert_ptr++;

		return SUCCESS;
	}
}

uint8_t send_data_from_battery_buffer(aci_state_t * aci_state)
{
		if(battery_data_buffer[batt_data_buff_fetch_ptr] == NO_DATA)
		{
			return BUFFER_EMPTY;
		}
		else
		{
			update_battery(aci_state, battery_data_buffer[batt_data_buff_fetch_ptr]);    //Send data from the buffer over the air
			battery_data_buffer[batt_data_buff_fetch_ptr] = NO_DATA;                     //Erase the data from the buffer we just sent

			//Move data-buffer fetch pointer location
			if(batt_data_buff_fetch_ptr == (BATTERY_DATA_BUFF_SIZE - 1))
				batt_data_buff_fetch_ptr = 0;
			else
				batt_data_buff_fetch_ptr++;

			return SUCCESS;
		}
}

bool get_battery_evolution(uint8_t *diff, uint8_t curr_batt_level)
{
  bool is_discharging = false;

  if (curr_batt_level != previous_battery_level)
  {
    if (curr_batt_level < previous_battery_level)
    {
      *diff = previous_battery_level - curr_batt_level;
      is_discharging = true;
    }
    else
    {
      *diff = curr_batt_level - previous_battery_level;
      is_discharging = false;
    }
  }
  return (is_discharging);
}

uint8_t measure_battery(aci_state_t *aci_state)
{
  analogReference(INTERNAL);                            //Set the ADC reference as the 1.1V internal band gap voltage
  delay(2);                                             //Create small delay to allow the reference voltage to settle before sampling
  ADC_output_value = analogRead(BATTERY_AIN_PIN);       //sample 10 bit battery measurement
  timestamp = millis();                                 //Mark timestamp for the ADC sampling.
  calculated_mvolts = ((float)ADC_output_value)/1023*REFERNCE_VOLTAGE_MVOLT;  //transform sample value into millivolts At AIN
  calculated_mvolts += OFFSET_ERROR_CALIBRATION_FACTOR; //Calibration for observed ADC offset error. Modify as needed.
  calculated_mvolts *= GAIN_ERROR_CALIBRATION_FACTOR;   //Calibration for observed ADC gain error. Modify as needed.
  AIN_mvolts = calculated_mvolts;                       //Store the voltage value on the analog input pin
  supply_mvolts = calculated_mvolts * (R2_RESISTANCE_KOHM + R1_RESISTANCE_KOHM) / R2_RESISTANCE_KOHM;  //Calculate the supply voltage

  //transform millivolt measurement into percent value. Only suitable for 6x1.5V=9V alkaline battery.
  //Battery level transfer function may be inaccurate. Modify as needed.
  battery_perc_level = lib_battery_level_percent_alkaline_9_volt(supply_mvolts);

  return battery_perc_level;
}

uint8_t get_simulated_battery_value(void)
{
	batt_percentage_simulated--;
	if(batt_percentage_simulated < 1)
	{
		batt_percentage_simulated = 100;
	}
	return batt_percentage_simulated;
}

void print_battery_measurement_data(void)
{
	//Print ADC value, AIN voltage, Supply voltage and battery level
	Serial.print(F("Time: "));
	Serial.print(timestamp);
	Serial.print(F("ms    ADC value (10 bit): "));
	Serial.print(ADC_output_value);
	Serial.print(F("    AIN voltage: "));
	Serial.print(AIN_mvolts);
	Serial.print(F("mV    Supply voltage: "));
	Serial.print(supply_mvolts);
	Serial.print(F("mV    Battery level: "));
	Serial.print(battery_perc_level);
	Serial.println(F("%"));
}

void send_battery_update(aci_state_t *aci_state, uint8_t percent_level)
{
  if (lib_aci_send_data(PIPE_BATTERY_BATTERY_LEVEL_TX, &percent_level, sizeof(percent_level)))        //Sending battery level over the air
  {
    aci_state->data_credit_available--;
  }
}

void update_battery(aci_state_t * aci_state, uint8_t percent_level)
{
  uint8_t level_difference = 0;
  get_battery_evolution(&level_difference, percent_level);

  if (level_difference >= BATTERY_LVL_CHANGE_THRESHOLD)
  {
    lib_aci_set_local_data(aci_state, PIPE_BATTERY_BATTERY_LEVEL_SET, &percent_level, sizeof(percent_level));   //Set battery level
    previous_battery_level = percent_level;

    if(lib_aci_is_pipe_available(aci_state, PIPE_BATTERY_BATTERY_LEVEL_TX))
    {
      if(aci_state->data_credit_available > 0)
      {
		send_battery_update(aci_state, percent_level);
      }
    }
  }
}

void battery_on_pipe_status(aci_state_t *aci_stat)
{
  if (percent_level_on_connect != battery_level_on_disconnect)
  {
    if(lib_aci_is_pipe_available(aci_stat, PIPE_BATTERY_BATTERY_LEVEL_TX))
    {
      lib_aci_send_data(PIPE_BATTERY_BATTERY_LEVEL_TX, &percent_level_on_connect, sizeof(percent_level_on_connect));
    }
  }
}

void battery_on_connect(aci_state_t *aci_stat, uint8_t percent_level)
{
  percent_level_on_connect = percent_level;
  lib_aci_set_local_data(aci_stat, PIPE_BATTERY_BATTERY_LEVEL_SET, &percent_level, sizeof(percent_level));
}

void battery_on_disconnect(uint8_t percent_level)
{
  battery_level_on_disconnect = percent_level;
}


text:
public class AddBinary{
	public static String addBinary(String a,String b){
		int point = 0;
		int maxLen = a.length()<b.length()?b.length():a.length();
		StringBuilder resString=new StringBuilder();
		boolean isUpper=false;
		while(point < maxLen){
			int tmpA=0,tmpB=0;
			tmpA = point<a.length()?Integer.parseInt(String.valueOf(a.charAt(a.length()-point-1))):0;
			tmpB = point<b.length()?Integer.parseInt(String.valueOf(b.charAt(b.length()-point-1))):0;
			System.out.println("a:"+tmpA);
			System.out.println("b:"+tmpB);
			int tmpSum = tmpA+tmpB;
			tmpSum+=isUpper?1:0;
			isUpper = tmpSum>1?true:false;
			resString.insert(0,tmpSum%2);
			++point;
			System.out.println(tmpSum);
		}
		if(isUpper){
			resString.insert(0,"1");
		}
		System.out.println(resString.toString());
		return resString.toString();
	}
	public static void main(String[] args){
		if(addBinary("1010","1011").equals("10101")){
			System.out.println("sucess");
		}
		else{
			System.out.println("fail");
		}
	}
}


text:
package org.apache.livy.thriftserver.session;

import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.spark.SparkContext;
import org.apache.spark.launcher.SparkLauncher;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.StructField;
import org.junit.Test;
import static org.junit.Assert.*;

public class ColumnBufferTest {

  @Test
  public void testColumnBuffer() throws Exception {
    String warehouse = Files.createTempDirectory("spark-warehouse-").toFile().getAbsolutePath();

    SparkSession session = SparkSession.builder()
      .master("local")
      .appName(getClass().getName())
      .config("spark.sql.warehouse.dir", warehouse)
      .getOrCreate();

    try {
      SQLContext spark = session.sqlContext();

      TestBean tb = new TestBean();
      tb.setId(1);
      tb.setBool(true);
      tb.setBt((byte) 127);
      tb.setSh((short) 42);
      tb.setLg(84);
      tb.setFl(1.23f);
      tb.setDbl(4.567d);
      tb.setDecimal(new BigDecimal("1.23450"));
      tb.setDesc("one");
      tb.setLst(Arrays.asList(1));
      tb.setM(new HashMap<>());
      tb.getM().put("one", 1);
      tb.setBin(new byte[] { 0x08, 0x16, 0x24, 0x32 });
      tb.setChild(new NestedBean());
      tb.getChild().setId(2);
      tb.getChild().setM(new HashMap<>());
      tb.getChild().getM().put("two", 2);

      Encoder<TestBean> encoder = Encoders.bean(TestBean.class);
      Dataset<TestBean> ds = spark.createDataset(Arrays.asList(tb), encoder);

      ds.write().format("parquet").saveAsTable("types_test");

      ResultSet rs = new ResultSet(SparkUtils.translateSchema(ds.schema()));
      for (Row r : spark.table("types_test").collectAsList()) {
        Object[] cols = new Object[r.length()];
        for (int i = 0; i < cols.length; i++) {
          cols[i] = r.get(i);
        }
        rs.addRow(cols);
      }

      // The order of columns in the schema is not necessarily the order in which the
      // bean methods are declared. So this is a little more complicated than it should.
      ColumnBuffer[] cols = rs.getColumns();
      int idx = 0;

      for (StructField f : ds.schema().fields()) {
        switch (f.name()) {
        case "id":
          assertEquals(Integer.valueOf(tb.getId()), cols[idx++].get(0));
          break;
        case "bool":
          assertEquals(Boolean.valueOf(tb.getBool()), cols[idx++].get(0));
          break;
        case "bt":
          assertEquals(Byte.valueOf(tb.getBt()), cols[idx++].get(0));
          break;
        case "sh":
          assertEquals(Short.valueOf(tb.getSh()), cols[idx++].get(0));
          break;
        case "lg":
          assertEquals(Long.valueOf(tb.getLg()), cols[idx++].get(0));
          break;
        case "fl":
          assertEquals(Float.valueOf(tb.getFl()), cols[idx++].get(0));
          break;
        case "dbl":
          assertEquals(Double.valueOf(tb.getDbl()), cols[idx++].get(0));
          break;
        case "decimal":
          assertEquals(tb.getDecimal().stripTrailingZeros().toString(), cols[idx++].get(0));
          break;
        case "desc":
          assertEquals(tb.getDesc(), cols[idx++].get(0));
          break;
        case "lst":
          assertEquals("[1]", cols[idx++].get(0));
          break;
        case "m":
          assertEquals("{\"one\":1}", cols[idx++].get(0));
          break;
        case "bin":
          {
            byte[] data = ((ByteBuffer) cols[idx++].get(0)).array();
            assertTrue(Arrays.equals(tb.getBin(), data));
          }
          break;
        case "child":
          // The expected string follows empirical evidence that the Spark bean encoder
          // generates schemas ordered by the field name.
          assertEquals("{\"id\":2,\"m\":{\"two\":2}}", cols[idx++].get(0));
          break;
        default:
          fail("Unexpected schema field: " + f.name());
        }
      }
    } finally {
      session.stop();
    }
  }

  @Test
  public void testNullsAndResizing() {
    ColumnBuffer col = new ColumnBuffer(DataType.INTEGER);
    for (int i = 0; i < ColumnBuffer.DEFAULT_SIZE * 20; i++) {
      if (i % 13 == 0) {
        col.add(null);
      } else {
        col.add(i);
      }
    }

    int[] values = (int[]) col.getValues();
    BitSet nulls = col.getNulls();
    for (int i = 0; i < ColumnBuffer.DEFAULT_SIZE * 20; i++) {
      if (i % 13 == 0) {
        assertTrue(nulls.get(i));
      } else {
        assertFalse(nulls.get(i));
        assertEquals(i, values[i]);
      }
    }
  }

  @Test
  public void testStringColumn() {
    int nonNullCount = ColumnBuffer.DEFAULT_SIZE * 5;
    int nullCount = ColumnBuffer.DEFAULT_SIZE * 2;

    ColumnBuffer col = new ColumnBuffer(DataType.STRING);
    for (int i = 0; i < nonNullCount; i++) {
      col.add(String.valueOf(i));
    }

    for (int i = 0; i < nullCount; i++) {
      col.add(null);
    }

    @SuppressWarnings("unchecked")
    List<String> values = (List<String>) col.getValues();
    BitSet nulls = col.getNulls();
    assertEquals(nonNullCount + nullCount, values.size());
    for (int i = 0; i < nonNullCount; i++) {
      assertEquals(String.valueOf(i), values.get(i));
      assertFalse(nulls.get(i));
    }
    for (int i = nonNullCount; i < nonNullCount + nullCount; i++) {
      assertEquals(ColumnBuffer.EMPTY_STRING, values.get(i));
      assertTrue(nulls.get(i));
    }
  }

  @Test
  public void testBinaryColumn() {
    int nonNullCount = ColumnBuffer.DEFAULT_SIZE * 5;
    int nullCount = ColumnBuffer.DEFAULT_SIZE * 2;

    ColumnBuffer col = new ColumnBuffer(DataType.BINARY);
    for (int i = 0; i < nonNullCount; i++) {
      byte[] buf = new byte[Integer.SIZE];
      ByteBuffer.wrap(buf).putInt(i);
      col.add(buf);
    }

    for (int i = 0; i < nullCount; i++) {
      col.add(null);
    }

    @SuppressWarnings("unchecked")
    List<ByteBuffer> values = (List<ByteBuffer>) col.getValues();
    BitSet nulls = col.getNulls();
    assertEquals(nonNullCount + nullCount, values.size());
    for (int i = 0; i < nonNullCount; i++) {
      assertEquals(i, values.get(i).getInt());
      assertFalse(nulls.get(i));
    }
    for (int i = nonNullCount; i < nonNullCount + nullCount; i++) {
      assertEquals(ColumnBuffer.EMPTY_BUFFER, values.get(i));
      assertTrue(nulls.get(i));
    }
  }

  @Test
  public void testExtractSubset() {
    testExtractSubsetWithType(DataType.BOOLEAN, new Object[]{true, false, true, false, null});
    testExtractSubsetWithType(DataType.BYTE,
      new Object[]{(byte)0, (byte)1, (byte)2, (byte)3, null});
    testExtractSubsetWithType(DataType.SHORT,
      new Object[]{(short)0, (short)1, (short)2, (short)3, null});
    testExtractSubsetWithType(DataType.INTEGER, new Object[]{1, 2, 3, 4, null});
    testExtractSubsetWithType(DataType.LONG, new Object[]{1L, 2L, 3L, 4L, null});
    testExtractSubsetWithType(DataType.FLOAT, new Object[]{1.0f, 2.0f, 3.0f, 4.0f, null});
    testExtractSubsetWithType(DataType.DOUBLE, new Object[]{1.0, 2.0, 3.0, 4.0, null});
    testExtractSubsetWithType(DataType.BINARY, new Object[]{
      new byte[]{0, 1},
      new byte[]{0},
      new byte[]{},
      new byte[]{0, 1, 2},
      null});
    testExtractSubsetWithType(DataType.STRING, new Object[]{"a", "b", "c", "d", null});

    // When null bits is less than currentSize
    ColumnBuffer buffer = new ColumnBuffer(DataType.STRING);
    buffer.add(null);
    buffer.add("a");
    buffer.add("b");
    ColumnBuffer subset = buffer.extractSubset(2);
    assertEquals(2, subset.size());
    assertNull(subset.get(0));
    assertEquals("a", subset.get(1));
    assertTrue(subset.getNulls().get(0));

    // When value array length is less than currentSize
    buffer = new ColumnBuffer(DataType.STRING);
    for (int i = 0; i < 110; i++) {
      buffer.add(null);
    }
    subset = buffer.extractSubset(110);
    BitSet nullBits = subset.getNulls();
    assertEquals(110, subset.size());
    for (int i = 0; i < 110; i++) {
      assertNull(subset.get(i));
      assertTrue(nullBits.get(i));
    }
    assertEquals(0, buffer.size());
  }

  private void testExtractSubsetWithType(
      DataType type,
      Object[] initValues) {
    ColumnBuffer buffer = new ColumnBuffer(type);

    // Check the passed in test data
    // The number of initial value for test should be 5
    assertEquals(5, initValues.length);
    // The last one should be null
    assertNull(initValues[4]);

    for (int i = 0; i < initValues.length; i++) {
      buffer.add(initValues[i]);
      // Binary column buffer will wrap byte[] in a ByteBuffer
      // We update initValues for the following comparision for Binary ColumnBuffer
      if (type == DataType.BINARY && initValues[i] != null) {
        initValues[i] = ByteBuffer.wrap((byte[]) initValues[i]);
      }
    }

    ColumnBuffer buffer1 = buffer.extractSubset(100);
    assertEquals(5, buffer1.size());
    // null bit should be set
    assertTrue(buffer1.getNulls().get(4));
    assertEquals(initValues[0], buffer1.get(0));
    assertEquals(initValues[1], buffer1.get(1));
    assertEquals(initValues[2], buffer1.get(2));
    assertEquals(initValues[3], buffer1.get(3));
    assertEquals(initValues[4], buffer1.get(4));
    assertEquals(0, buffer.size());

    // extract negative index
    ColumnBuffer buffer2 = buffer1.extractSubset(-1);
    assertEquals(0, buffer2.size());
    assertEquals(5, buffer1.size());

    // Extract single element
    ColumnBuffer buffer3 = buffer1.extractSubset(1);
    assertEquals(1, buffer3.size());
    assertFalse(buffer3.getNulls().get(0));
    assertEquals(initValues[0], buffer3.get(0));
    assertEquals(4, buffer1.size());

    // null bits should not be set
    ColumnBuffer buffer4 = buffer1.extractSubset(2);
    assertEquals(0, buffer4.getNulls().size());
    assertEquals(initValues[1], buffer4.get(0));
    assertEquals(initValues[2], buffer4.get(1));
    assertEquals(2, buffer1.size());
  }

  public static class TestBean {
    private int id;
    private boolean bool;
    private byte bt;
    private short sh;
    private long lg;
    private float fl;
    private double dbl;
    private BigDecimal decimal;
    private String desc;
    private List<Integer> lst;
    private Map<String, Integer> m;
    private byte[] bin;
    private NestedBean child;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public boolean getBool() { return bool; }
    public void setBool(boolean bool) { this.bool = bool; }

    public byte getBt() { return bt; }
    public void setBt(byte bt) { this.bt = bt; }

    public short getSh() { return sh; }
    public void setSh(short sh) { this.sh = sh; }

    public long getLg() { return lg; }
    public void setLg(long lg) { this.lg = lg; }

    public float getFl() { return fl; }
    public void setFl(float fl) { this.fl = fl; }

    public double getDbl() { return dbl; }
    public void setDbl(double dbl) { this.dbl = dbl; }

    public BigDecimal getDecimal() { return decimal; }
    public void setDecimal(BigDecimal decimal) { this.decimal = decimal; }

    public String getDesc() { return desc; }
    public void setDesc(String desc) { this.desc = desc; }

    public List<Integer> getLst() { return lst; }
    public void setLst(List<Integer> lst) { this.lst = lst; }

    public Map<String, Integer> getM() { return m; }
    public void setM(Map<String, Integer> m) { this.m = m; }

    public byte[] getBin() { return bin; }
    public void setBin(byte[] bin) { this.bin = bin; }

    public NestedBean getChild() { return child; }
    public void setChild(NestedBean child) {
      this.child = child;
    };
  }

  public static class NestedBean {
    private int id;
    private Map<String, Integer> m;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public Map<String, Integer> getM() { return m; }
    public void setM(Map<String, Integer> m) { this.m = m; }
  }

}


text:
package aia.routing

import java.util.Date
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._

import akka.actor._
import akka.pattern.ask
import akka.routing._
import scala.concurrent.Await

import org.scalatest.{MustMatchers, BeforeAndAfterAll, WordSpecLike}
import akka.testkit._

class PerfRoutingTest
  extends TestKit(ActorSystem("PerfRoutingTest"))
  with MustMatchers
  with WordSpecLike
  with BeforeAndAfterAll {

  override def afterAll() = {
    system.terminate()
  }

  "The routerGroup" must {
    "use manage routees" in {
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val router = system.actorOf(RoundRobinGroup(List()).props(), "router")
      val props = Props(new GetLicense(endProbe.ref))
      val creator = system.actorOf(Props( new DynamicRouteeSizer(2, props, router)),"DynamicRouteeSizer")
      Thread.sleep(100)
      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      router ! msg

      val procMsg = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      creator ! PreferredSize(4)
      Thread.sleep(1000)

      creator ! PreferredSize(2)
      Thread.sleep(1000)

      router ! msg
      val procMsg2 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg2)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      router ! Broadcast(PoisonPill)
      Thread.sleep(1000)

      router ! msg
      val procMsg3 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg3)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      system.stop(router)
      system.stop(creator)
    }
    "survive killed actor ref routee" in {
      val termProbe = TestProbe()
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val router = system.actorOf(RoundRobinGroup(List()).props(), "router-test2")
      val props = Props(new GetLicense(endProbe.ref))
      val creator = system.actorOf(Props(new WrongDynamicRouteeSizer(2, props, router)),"DynamicRouteeSizer-test2")
      Thread.sleep(100)

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      val routee = routees.get(0).asInstanceOf[ActorRefRoutee]
      termProbe.watch(routee.ref)
      termProbe.watch(router)
      routee.send(PoisonPill, endProbe.ref)
      termProbe.expectTerminated(routee.ref)
      termProbe.expectNoMsg
      termProbe.unwatch(router)
      system.stop(creator)
    }
    "survive killed routee" in {
      val termProbe = TestProbe()
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val router = system.actorOf(RoundRobinGroup(List()).props(), "router-test3")
      val props = Props(new GetLicense(endProbe.ref))
      val creator = system.actorOf(Props( new DynamicRouteeSizer(2, props, router)),"DynamicRouteeSizer-test3")
      Thread.sleep(100)
      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      routees.get(0).send(PoisonPill, endProbe.ref)

      termProbe.watch(router)
      //// ActorSelectionRoutee을 사용하기 때문에 라우터가 종료되지 않는다
      termProbe.expectNoMsg
      termProbe.unwatch(router)

      val future2 = router.ask(GetRoutees)(1 second)
      val routeesMsg2 = Await.result(future2, 1.second).asInstanceOf[Routees]
      routeesMsg2.getRoutees.size must be (2)
      import collection.JavaConverters._
      for(routee <- routeesMsg2.getRoutees.asScala) {
        routees.get(0).send(msg, endProbe.ref)
      }
      val procMsg1 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg1)
      val procMsg2 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg2)
      system.stop(router)
      system.stop(creator)
    }

    "use manage routees2" in {
      val termProbe = TestProbe()
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val router = system.actorOf(RoundRobinGroup(List()).props(), "router-test4")
      val props = Props(new GetLicense(endProbe.ref))
      val creator = system.actorOf(Props( new DynamicRouteeSizer2(2, props, router)),"DynamicRouteeSizer2-test4")
      Thread.sleep(100)
      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      router ! msg

      val procMsg = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      creator ! PreferredSize(4)
      Thread.sleep(1000)

      creator ! PreferredSize(2)
      Thread.sleep(2000)

      router ! msg
      val procMsg2 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg2)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      router ! Broadcast(PoisonPill)

      termProbe.watch(router)
      termProbe.expectTerminated(router)

      system.stop(router)
      system.stop(creator)
    }

    "Use recreated routees" in {
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val creator = system.actorOf(Props( new GetLicenseCreator2(2, endProbe.ref)),"GetLicenseCreator-test5")
      val paths = List(
        "/user/GetLicenseCreator-test5/GetLicense0",
        "/user/GetLicenseCreator-test5/GetLicense1"
      )
      val router = system.actorOf(RoundRobinGroup(paths).props(), "router-test5")

      creator ! "KillFirst"

      Thread.sleep(100)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      router ! msg

      val procMsg = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      creator ! "KillFirst"
      Thread.sleep(100)

      router ! msg

      val procMsg2 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg2)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      creator ! "KillFirst"
      Thread.sleep(100)

      router ! msg

      val procMsg3 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg3)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      system.stop(router)
      system.stop(creator)
    }
    "Use recreated routees using broadcast" in {
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val creator = system.actorOf(Props( new GetLicenseCreator2(2, endProbe.ref)),"GetLicenseCreator-test6")
      val paths = List(
        "/user/GetLicenseCreator-test6/GetLicense0",
        "/user/GetLicenseCreator-test6/GetLicense1"
      )
      val router = system.actorOf(RoundRobinGroup(paths).props(), "groupRouter-test6")

      deadProbe.expectNoMsg()
      router ! Broadcast(PoisonPill)
      deadProbe.expectNoMsg()

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)
      router ! msg

      val procMsg2 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg2)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      router ! msg

      val procMsg3 = endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      println("Received: "+ procMsg3)
      endProbe.expectNoMsg()
      deadProbe.expectNoMsg()

      system.stop(router)
      system.stop(creator)
    }
    "route between created routers 2" in {
      val endProbe = TestProbe()
      val deadProbe = TestProbe()
      system.eventStream.subscribe(
        deadProbe.ref,
        classOf[DeadLetter])

      val creator = system.actorOf(Props( new GetLicenseCreator(2, endProbe.ref)),"GetLicenseCreator2-test7")
      val paths = List(
        "/user/GetLicenseCreator2-test7/GetLicense0",
        "/user/GetLicenseCreator2-test7/GetLicense1"
      )
      val router = system.actorOf(RoundRobinGroup(paths).props(), "router-test7")

      creator ! "KillFirst"

      Thread.sleep(1000)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      router ! msg

      val deadMsg = deadProbe.expectMsgType[DeadLetter](1 second)
      println(deadMsg)
      router ! msg

      endProbe.expectMsgType[PerformanceRoutingMessage](1 second)
      router ! msg

      deadProbe.expectMsgType[DeadLetter](1 second)
      system.stop(router)
      system.stop(creator)
    }
  }
  "The Router supervision" must {
    "restart all routees" in {
      val router = system.actorOf(
        RoundRobinPool(5).props(
          Props[TestSuper]), "roundrobinRouter-test1")
      router ! "exception"
      Thread.sleep(1000)
      system.stop(router)
    }
    "restart one routee" in {
      val router = system.actorOf(
        RoundRobinPool(5, supervisorStrategy = SupervisorStrategy.defaultStrategy).props(
          Props[TestSuper]), "roundrobinRouter-test2")
      router ! "exception"
      Thread.sleep(1000)
      system.stop(router)
    }
  }
    "The Router" must {
    "routes using roundrobin" in {

      val endProbe = TestProbe()
      val router = system.actorOf(
        RoundRobinPool(5).props(
          Props(new GetLicense(endProbe.ref, 250 millis))), "roundrobinRouter")

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      for (index <- 0 until 10) {
        router ! msg
      }
      val processedMessages = endProbe.receiveN(10, 5 seconds).collect
      { case m: PerformanceRoutingMessage => m }
      processedMessages.size must be(10)

      val grouped = processedMessages.groupBy(_.processedBy)
      grouped.values.foreach(listProcessedByOneActor =>
        listProcessedByOneActor must have size (2))

      system.stop(router)
    }
    "routes using smallest mailbox" in {

      val endProbe = TestProbe()

      val router = system.actorOf(SmallestMailboxPool(2).props(Props(
        new GetLicense(endProbe.ref))), "smallestMailboxRouter-test1")

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      routees.size must be (2)
      routees.get(0).send(SetService("250", 250 millis), endProbe.ref)
      routees.get(1).send(SetService("500", 500 millis), endProbe.ref)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      for (index <- 0 until 10) {
        Thread.sleep(200)
        router ! msg
      }
      val processedMessages = endProbe.receiveN(10, 5 seconds).collect { case m: PerformanceRoutingMessage => m }
      processedMessages.size must be(10)
      val grouped = processedMessages.groupBy(_.processedBy)
      val msgProcessedByActor1 = grouped.get(Some("250"))
        .getOrElse(Seq())
      val msgProcessedByActor2 = grouped.get(Some("500"))
        .getOrElse(Seq())
      msgProcessedByActor1 must have size (7)
      msgProcessedByActor2 must have size (3)

      system.stop(router)
    }
    "routes using smallest mailbox with addRoutee" in {

      val endProbe = TestProbe()

      val router = system.actorOf(SmallestMailboxPool(0).props(Props(new GetLicense(endProbe.ref, 250 millis))), "smallestMailboxRouter-test2")

      val actor1 = system.actorOf(Props(new GetLicense(endProbe.ref, 250 millis)),"250")
      val actor2 = system.actorOf(Props(new GetLicense(endProbe.ref, 500 millis)),"500")
      router ! AddRoutee(ActorRefRoutee(actor1))
      router ! AddRoutee(ActorRefRoutee(actor2))

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      routees.size must be (2)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      for (index <- 0 until 10) {
        Thread.sleep(200)
        router ! msg
      }
      val processedMessages = endProbe.receiveN(10, 5 seconds).collect { case m: PerformanceRoutingMessage => m }
      processedMessages.size must be(10)
      val grouped = processedMessages.groupBy(_.processedBy)
      val msgProcessedByActor1 = grouped.get(Some("250"))
        .getOrElse(Seq())
      val msgProcessedByActor2 = grouped.get(Some("500"))
        .getOrElse(Seq())
      msgProcessedByActor1 must have size (7)
      msgProcessedByActor2 must have size (3)

      system.stop(router)
    }
    "routes using balancedRouter" in {

      val testSystem = ActorSystem("balancedRouter")
      val endProbe = TestProbe()(testSystem)

      val router = system.actorOf(BalancingPool(2).props(Props(
        new GetLicense(endProbe.ref))), "BalancingPoolRouter")

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      routees.size must be (2)
      routees.get(0).send(SetService("250", 250 millis), endProbe.ref)
      routees.get(1).send(SetService("500", 500 millis), endProbe.ref)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      for (index <- 0 until 10) {
        router ! msg
      }
      val processedMessages = endProbe.receiveN(10, 5 seconds).collect { case m: PerformanceRoutingMessage => m }
      processedMessages.size must be(10)
      println(processedMessages)
      val grouped = processedMessages.groupBy(_.processedBy)
      val msgProcessedByActor1 = grouped.get(Some("250"))
        .getOrElse(Seq())
      val msgProcessedByActor2 = grouped.get(Some("500"))
        .getOrElse(Seq())

      msgProcessedByActor1.size must be(7 +- 1)
      msgProcessedByActor2.size must be(3 +- 1)
      testSystem.terminate()

      system.stop(router)
    }
    "create routes using BalancingPool and using direct" in {

      val testSystem = ActorSystem("balance",
        ConfigFactory.load("balance"))
      val endProbe = TestProbe()(testSystem)
      val router = system.actorOf(BalancingPool(2).props(Props(
        new GetLicense(endProbe.ref))), "BalancingPoolRouter2")

      val future = router.ask(GetRoutees)(1 second)
      val routeesMsg = Await.result(future, 1.second).asInstanceOf[Routees]
      val routees = routeesMsg.getRoutees
      routees.size must be (2)
      routees.get(0).send(SetService("250", 250 millis), endProbe.ref)
      routees.get(1).send(SetService("500", 500 millis), endProbe.ref)

      val msg = PerformanceRoutingMessage(
        ImageProcessing.createPhotoString(new Date(), 60, "123xyz"),
        None,
        None)

      for (index <- 0 until 10) {
        routees.get(0).send(msg, endProbe.ref)
      }
      val processedMessages = endProbe.receiveN(10, 5 seconds).collect { case m: PerformanceRoutingMessage => m }
      processedMessages.size must be(10)
      val grouped = processedMessages.groupBy(_.processedBy)
      val msgProcessedByActor1 = grouped.get(Some("250"))
        .getOrElse(Seq())
      val msgProcessedByActor2 = grouped.get(Some("500"))
        .getOrElse(Seq())
      msgProcessedByActor1.size must be(7 +- 1)
      msgProcessedByActor2.size must be(3 +- 1)
      testSystem.terminate()

      system.stop(router)
    }
  }
}