text:
(function(window, document, undefined) {
	"use strict";

	angular.module('angularWidgets')
		.factory('widgetDatatable', ['$compile', '$http', 'widgetBase', 'widgetColumn', 'widgetPaginator', 'widgetFacet', '$wgMessages', DatatableWidget])
		.directive('wgDatatable', ['widgetDatatable', DatatableDirective]);

	function DatatableWidget($compile, $http, widgetBase, widgetColumn, widgetPaginator, widgetFacet, $wgMessages) {

		AngularWidgets.configureWidget('datatable', {
			emptyMessage: 'No rows found.',
			item: 'item',
			itemId: null,
			items: [],
			value: [],
			caption: null,
			selectionMode: null,
			onRowSelect: null,
			onRowUnselect: null,
			rows: 10,
			paginator: false,
			onBuildRow: null,
			loadOnRender: true,
			loadOnDemand: false,
			responsive: false, // reflow, TODO flip-scroll
			onError: function(datatable, context, event) {

				if ($wgMessages.isVisible()) {
					$wgMessages.addErrorMessage('Datatable error', context.error);
				}
				else {
					$wgMessages.showErrorMessage('Datatable error', context.error);
				}

				AngularWidgets.$log.error(context);
			}
		});

		var widget = {};

		widget.template = '

';

		widget.buildWidget = function(scope, element, attrs) {
			return new widget.DataTable(scope, element, attrs);
		};

		widget.create = function(scope, container, options) {

			var element = angular.element(this.template);

			container.append(element);

			return new widget.DataTable(scope, element, options);
		};

		widget.DataTable = function DataTable(scope, element, options) {

			this.columns = [];
			this.options = {};
			this.element = element;
			this.scope = scope;
			this.selection = [];
			this.firstLoad = true;
			this.sorts = [];

			this.constructor = function(scope, element, options) {

				this.table = this.element.findAllSelector('table');

				this.determineOptions(options);

				this.setItems(this.options.itemsBind ? this.scope.$eval(this.options.items) : this.options.items);

				var $this = this;

				if (this.options.restriction) {
					this.restriction = this.scope.$eval(this.options.restriction);
				}

				if (this.options.paginator) {

					this.paginator = widgetPaginator.buildWidget(this.scope, null, {
						rows: this.options.rows,
						dataLoader: this.items,
						onChangePageListener: function(page) {
							$this.refresh();
						}
					});

					this.element.append(this.paginator.element);

					this.dataModel = new AngularWidgets.PaginatedDataModel({
						rows: this.options.rows,
						dataSource: this.items,
						paginator: this.paginator
					});
				}
				else if (this.options.loadOnDemand) {

					this.onDemandDataModel = new AngularWidgets.OnDemandDataModel({
						rows: this.options.rows,
						dataSource: this.items,
						onChangePageListener: function(page) {
							$this.refresh();
						}
					});

					this.dataModel = this.onDemandDataModel;
				}
				else {
					this.dataModel = new AngularWidgets.BasicDataModel({
						dataSource: this.items
					});
				}

				this.determineTransclude();

				if (this.options.columns) {
					this.columns = this.options.columns;
				}

				if (!this.columns.length) {
					this.determineColumnInfo();
				}

				if (this.options.responsive) {
					this.element.addClass('pui-datatable-reflow');
				}

				this.buildFacets();
				this.buildCaption();
				this.buildColumnHeaders();
				this.renderBody();

				if (this.isSortingEnabled()) {
					this.initSorting();
				}

				this.changeScope();

				widgetBase.createBindAndAssignIfNecessary(this, "getCurrentPage,goToPage,refresh");

				if (this.options.loadOnRender) {
					this.refresh();
				}
			};

			this.addSelection = function(item) {

				if (!this.isSelected(item)) {
					if (this.options.itemId) {
						this.selection.push(this.getItemId(item));
					}
					else {
						this.selection.push(item);
					}
				}
			};

			this.buildBody = function() {

				var tbody = this.table.childrenSelector("tbody");

				this.tbody = tbody;

				tbody.data("dataTable", this);

				var row = angular.element('
 0" />');

				tbody.append(row);

				var rowEmpty = angular.element('
' + this.options.emptyMessage + '
');

				tbody.append(rowEmpty);

				for (var i = 0, t = this.columns.length; i < t; i++) {

					var column = this.columns[i],
					td = angular.element('

').findAllSelector('td');
					td.attr('data-title', column.headerText || column.field);

					if (column.contents) {
						td.append(column.contents);
					}
					else {
						td.append(angular.element(''));
					}

					row.append(td);
				}

				$compile(this.element.contents())(this.scope);
			};

			this.buildCaption = function() {
				if (this.options.caption) {
					this.caption = angular.element('

' + this.options.caption + '

')
								.childrenSelector('caption')
								.prependTo(this.table);
				}
			};

			this.buildFacets = function() {

				if (this.facets) {
					if (this.facets.header) {
						var header = angular.element('

')
								.prependTo(this.element)
								.append(this.facets.header.transclude());
					}

					if (this.facets.footer) {
						var footer = angular.element('

')
								.appendTo(this.element)
								.append(this.facets.footer.transclude());
					}
				}
			};

			this.determineColumnInfo = function() {
				if (!this.isHttpDataSource()) {
					for (var property in this.items.allData[0]) {
						this.columns.push({
							element: null,
							field: property,
							headerText: property,
							sortable: false,
							sortBy: property
						});
					}
				}
			};

			this.buildColumnHeaders = function() {

				this.thead = this.element.findAllSelector('thead');

				if (this.columns) {

					var $this = this;

					var tr = angular.element('

')
								.findAllSelector('tr');

					angular.forEach(this.columns, function(column) {

						// Elements are created as child of div tag. And if not valid html, it is not created.
						var th = angular.element('

')
								.findAllSelector('th');

						th.data('sortBy', column.sortBy);

						if (column.headerText) {
							th.text(column.headerText);
						}

						if (column.sortable) {
							th.addClass('pui-sortable-column').append('');
							th.data('order', 1);
						}

						tr.append(th);
					});

					this.thead.append(tr);
				}
			};

			this.getItemId = function(item) {
				return item[this.options.itemId];
			};

			this.changeScope = function() {

				var $this = this;

				if (this.options.itemsBind) {
					this.scope.$watch(this.options.items, function(newValue, oldValue) {
						if (newValue !== oldValue) {
							$this.setValue(newValue);
							$this.refresh();
						}
					});
				}
			};

			this.determineOptions = function(options) {
				this.options = widgetBase.determineOptions(this.scope, AngularWidgets.getConfiguration().widgets.datatable, options, ['onRowSelect', 'onRowUnselect']);
				this.options.itemsBind = angular.isString(options.items);
			};

			this.createRequest = function() {

				var request = {
					first: this.dataModel.getFirst(),
					sorts: this.sorts
				};

				if (this.restriction) {

					request.restriction = this.restriction.createRequest();

					if (!AngularWidgets.equals(this.lastRestriction, request.restriction)) {
						request.first = 0;
						this.dataModel.onChangeRestriction();
					}

					this.lastRestriction = request.restriction;
				}

				if (this.dataModel.getPageSize) {
					request.pageSize = this.dataModel.getPageSize();
				}

				return request;
			};

			this.initSelection = function(tr, item) {

				tr.hover(function() {
					if (!tr.hasClass('ui-state-highlight')) {
						tr.addClass('ui-state-hover');
					}
				}, function() {
					if (!tr.hasClass('ui-state-highlight')) {
						tr.removeClass('ui-state-hover');
					}
				});

				var $this = this;

				tr.bind('click', function(evt) {
					if (evt.target.nodeName === 'TD') {
						var selected = tr.hasClass('ui-state-highlight'),
						metaKey = evt.metaKey || evt.ctrlKey,
						shiftKey = evt.shiftKey;

						//unselect a selected row if metakey is on
						if (selected && metaKey) {
							$this.unselectRow(tr, false);
						}
						else {
							//unselect previous selection if this is single selection or multiple one with no keys
							if ($this.isSingleSelection() || ($this.isMultipleSelection() && !metaKey && !shiftKey)) {
								$this.unselectAllRows();
							}

							$this.selectRow(tr, false);
						}
					}
				});
			};

			this.initSorting = function() {

				var sortableColumns = this.thead.childrenSelector('tr').childrenSelector('.pui-sortable-column');

				widgetBase.hoverAndFocus(sortableColumns);

				sortableColumns.hover(function() {
					var column = angular.element(this);
					if (!column.hasClass('ui-state-active')) {
						column.addClass('ui-state-hover');
					}
				}, function() {
					var column = angular.element(this);
					if (!column.hasClass('ui-state-active')) {
						column.removeClass('ui-state-hover');
					}
				});

				var $this = this;

				sortableColumns.click(function(e) {
					var column = angular.element(e.target.nodeName === 'TH' ? e.target : e.target.parentNode),
					sortBy = column.data('sortBy'),
					order = column.data('order'),
					siblings = column.siblings(),
					activeColumns = AngularWidgets.filter(siblings, function(item) {
						return angular.element(item).hasClass('ui-state-active');
					}),
					sortIcon = column.childrenSelector('.pui-sortable-column-icon');

					if (activeColumns.length > 0) {
						angular.forEach(activeColumns, function(activeColumn) {
							angular.element(activeColumn)
							.data('order', 1)
							.removeClass('ui-state-active')
							.children('span.pui-sortable-column-icon')
							.removeClass('ui-icon-triangle-1-n ui-icon-triangle-1-s');
						});
					}

					$this.sort(sortBy, order == 1 ? 'ASC' : 'DESC');

					//update state
					column.data('order', -1 * order);

					column.removeClass('ui-state-hover').addClass('ui-state-active');
					sortIcon.removeClass('ui-icon-carat-2-n-s');
					if (order === -1) {
						sortIcon.removeClass('fa-sort-asc').addClass('fa-sort-desc');
					}
					else if (order === 1) {
						sortIcon.removeClass('fa-sort-desc').addClass('fa-sort-asc');
					}
				});
			};

			this.isHttpDataSource = function() {
				return this.items instanceof window.AngularWidgets.HttpDataSource;
			};

			this.isSingleSelection = function() {
				return this.options.selectionMode === 'single';
			};

			this.isMultipleSelection = function() {
				return this.options.selectionMode === 'multiple';
			};

			this.isSortingEnabled = function() {

				if (this.columns) {
					for (var i = 0, t = this.columns.length; i < t; i++) {
						if (this.columns[i].sortable) {
							return true;
						}
					}
				}

				return false;
			};

			this.determineTransclude = function() {

				var divTransclude = angular.element(this.element.children()[0]).children()[0];

				var columns = widgetColumn.determineColumnsOptions(divTransclude);

				this.facets = widgetFacet.determineFacetsOptions(divTransclude);

				if (columns) {
					this.columns = columns;
				}

				// Delete transclude div
				angular.element(divTransclude).remove();
			};

			this.refresh = function() {

				var $this = this;

				this.dataModel.load(this.createRequest(),
					function() {
						$this.onLoadData();
					},
					function(response) {
						$this.options.onError($this.bindInstance, response, 'load');
					}
				);
			};

			this.onLoadData = function() {

				if (this.firstLoad) {

					this.firstLoad = false;

					if (this.options.paginator) {
						this.paginator.render();
					}
				}
				else {
					if (this.options.paginator) {
						this.paginator.update();
					}
				}

				this.renderRows();

				if (this.options.loadOnDemand && this.onDemandLoader === undefined) {

					this.onDemandLoader = angular.element('

');

					this.element.append(this.onDemandLoader);

					var watcher = scrollMonitor.create(this.onDemandLoader);

					var $this = this;

					watcher.enterViewport(function() {
						if ($this.dataModel.hasMoreRows()) {
							var tr = angular.element('

');
							$this.tbody.append(tr);
							$this.onDemandDataModel.nextPage();
						}
					});
				}
			};

			this.renderBody = function() {
				this.tbody = this.table.childrenSelector("tbody");
			};

			this.removeRow = function(row) {
				var scope = row.data('itemScope');
				if (scope) scope.$destroy();
				row.remove();
			};

			this.removeRows = function(rows) {
				for (var i=0,t=rows.length; i<t; i++) {
					this.removeRow(angular.element(rows[i]));
				}
			};

			this.renderRows = function() {

 				var $this = this;

				var children = Array.prototype.slice.call(this.tbody.children());

				if ($this.dataModel.getData().length > 0) {

					angular.forEach($this.dataModel.getData(), function (item, index) {

						var oldTr;

						if (children.length > 0) {
							oldTr = angular.element(children[0]);
						}

						var itemKey = $this.options.item ? $this.options.item : 'item',
							itemScope = $this.scope.$new(false, $this.scope);

						itemScope[itemKey] = item;

						var tr = angular.element('
')
									.addClass(index % 2 === 0 ? 'pui-even' : 'pui-odd');

						// Store childscope for destroy
						tr.data('itemScope', itemScope);

						for (var i = 0, t = $this.columns.length; i < t; i++) {

							var column = $this.columns[i],
							td = angular.element('

').findAllSelector('td');
							td.attr('data-title', column.headerText || column.field);

							if (column.contents) {
								td.append(column.contents);
							}
							else {
								td.append(angular.element(''));
							}

							tr.append(td);
						}

						tr.data('item', item);

						if ($this.options.selectionMode) {
							$this.initSelection(tr, item);
						}

						if ($this.options.selectionMode && $this.isSelected(item)) {
							tr.addClass("ui-state-highlight");
						}

						//if ($this.options.onBuildRow) {
						//	$this.options.onBuildRow(this, scope, element, attrs);
						//}

						$compile(tr)(itemScope);

						if (oldTr) {
							oldTr.after(tr);
							$this.removeRow(oldTr);
							children.shift();
						}
						else {
							$this.tbody.append(tr);
						}
					});

					$this.removeRows(children);
				}
				else {
					$this.removeRows(children);

					$this.tbody.append(angular.element('
' + this.options.emptyMessage + '
'));
				}
            };

			this.cleanAndDestroyChildrenScope = function() {

				for (var i=0,l=this.childrenScope.length; i<l; i++) {
					this.childrenScope[i].$destroy();
				}

				this.childrenScope = [];
            };

			this.clearSelection = function() {
				this.selection = [];
			};

			this.removeSelection = function(item) {

				if (!this.isSelected(item)) {
					if (this.options.itemId) {
						this.selection.splice(this.selection.indexOf(this.getItemId(item)), 1);
					}
					else {
						this.selection.splice(this.selection.indexOf(item), 1);
					}
				}
			};

			this.selectRow = function(row, silent) {

				var item = row.data('item');

				row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true);

				this.addSelection(item);

				if (!silent && this.options.onRowSelect) {
					this.options.onRowSelect('rowSelect', item);
				}
			};

			this.setItems = function(value) {
				this.items = widgetBase.determineDataSource(value);
			};

			this.sort = function(attribute, order) {

				this.sorts = [{ attribute: attribute, order: order }];

				this.refresh();
			};

			this.getCurrentPage = function() {
				return this.options.paginator ? this.paginator.getCurrentPage() : 0;
			};

			this.goToPage = function(page) {
				this.paginator.goToPage(page);
			};

			this.unselectAllRows = function(silent) {

				if (this.selection.length > 0) {

					this.tbody.children('tr.ui-state-highlight').removeClass('ui-state-highlight').attr('aria-selected', false);

					if (!silent && this.options.onRowUnselect) {
						this.options.onRowUnselect('rowUnselectAll', null);
					}

					this.selection = [];
				}
			};

			this.unselectRow = function(row, silent) {

				var item = row.data('item');

				row.removeClass('ui-state-highlight').attr('aria-selected', false);

				this.removeSelection(item);

				if (!silent && this.options.onRowUnselect) {
					this.options.onRowUnselect('rowUnselect', item);
				}
			};

			this.isSelected = function(item) {
				return AngularWidgets.inArray(this.selection, this.options.itemId ? this.getItemId(item) : item);
			};

			this.constructor(scope, element, options);
		};

		return widget;
	}

	function DatatableDirective(widgetDatatable) {
		return {
			restrict: 'E',
			priority: 50,
			transclude: true,
			scope: true,
			link: function(scope, element, attrs, ctrl) {
				widgetDatatable.buildWidget(scope, element, attrs);
			},
			replace: true,
			template: widgetDatatable.template
		};
	}

}(window, document));


text:
import { VSBuffer } from 'vs/base/common/buffer';
import * as platform from 'vs/base/common/platform';

export interface IFullSemanticTokensDto {
	id: number;
	type: 'full';
	data: Uint32Array;
}

export interface IDeltaSemanticTokensDto {
	id: number;
	type: 'delta';
	deltas: { start: number; deleteCount: number; data?: Uint32Array }[];
}

export type ISemanticTokensDto = IFullSemanticTokensDto | IDeltaSemanticTokensDto;

const enum EncodedSemanticTokensType {
	Full = 1,
	Delta = 2
}

function reverseEndianness(arr: Uint8Array): void {
	for (let i = 0, len = arr.length; i < len; i += 4) {
		// flip bytes 0<->3 and 1<->2
		const b0 = arr[i + 0];
		const b1 = arr[i + 1];
		const b2 = arr[i + 2];
		const b3 = arr[i + 3];
		arr[i + 0] = b3;
		arr[i + 1] = b2;
		arr[i + 2] = b1;
		arr[i + 3] = b0;
	}
}

function toLittleEndianBuffer(arr: Uint32Array): VSBuffer {
	const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
	if (!platform.isLittleEndian()) {
		// the byte order must be changed
		reverseEndianness(uint8Arr);
	}
	return VSBuffer.wrap(uint8Arr);
}

function fromLittleEndianBuffer(buff: VSBuffer): Uint32Array {
	const uint8Arr = buff.buffer;
	if (!platform.isLittleEndian()) {
		// the byte order must be changed
		reverseEndianness(uint8Arr);
	}
	if (uint8Arr.byteOffset % 4 === 0) {
		return new Uint32Array(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.length / 4);
	} else {
		// unaligned memory access doesn't work on all platforms
		const data = new Uint8Array(uint8Arr.byteLength);
		data.set(uint8Arr);
		return new Uint32Array(data.buffer, data.byteOffset, data.length / 4);
	}
}

export function encodeSemanticTokensDto(semanticTokens: ISemanticTokensDto): VSBuffer {
	const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
	let offset = 0;
	dest[offset++] = semanticTokens.id;
	if (semanticTokens.type === 'full') {
		dest[offset++] = EncodedSemanticTokensType.Full;
		dest[offset++] = semanticTokens.data.length;
		dest.set(semanticTokens.data, offset); offset += semanticTokens.data.length;
	} else {
		dest[offset++] = EncodedSemanticTokensType.Delta;
		dest[offset++] = semanticTokens.deltas.length;
		for (const delta of semanticTokens.deltas) {
			dest[offset++] = delta.start;
			dest[offset++] = delta.deleteCount;
			if (delta.data) {
				dest[offset++] = delta.data.length;
				dest.set(delta.data, offset); offset += delta.data.length;
			} else {
				dest[offset++] = 0;
			}
		}
	}
	return toLittleEndianBuffer(dest);
}

function encodeSemanticTokensDtoSize(semanticTokens: ISemanticTokensDto): number {
	let result = 0;
	result += (
		+ 1 // id
		+ 1 // type
	);
	if (semanticTokens.type === 'full') {
		result += (
			+ 1 // data length
			+ semanticTokens.data.length
		);
	} else {
		result += (
			+ 1 // delta count
		);
		result += (
			+ 1 // start
			+ 1 // deleteCount
			+ 1 // data length
		) * semanticTokens.deltas.length;
		for (const delta of semanticTokens.deltas) {
			if (delta.data) {
				result += delta.data.length;
			}
		}
	}
	return result;
}

export function decodeSemanticTokensDto(_buff: VSBuffer): ISemanticTokensDto {
	const src = fromLittleEndianBuffer(_buff);
	let offset = 0;
	const id = src[offset++];
	const type: EncodedSemanticTokensType = src[offset++];
	if (type === EncodedSemanticTokensType.Full) {
		const length = src[offset++];
		const data = src.subarray(offset, offset + length); offset += length;
		return {
			id: id,
			type: 'full',
			data: data
		};
	}
	const deltaCount = src[offset++];
	const deltas: { start: number; deleteCount: number; data?: Uint32Array }[] = [];
	for (let i = 0; i < deltaCount; i++) {
		const start = src[offset++];
		const deleteCount = src[offset++];
		const length = src[offset++];
		let data: Uint32Array | undefined;
		if (length > 0) {
			data = src.subarray(offset, offset + length); offset += length;
		}
		deltas[i] = { start, deleteCount, data };
	}
	return {
		id: id,
		type: 'delta',
		deltas: deltas
	};
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (C) 2004-2009 Jive Software. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;

namespace org.xmpp.util
{
	/// <summary>
	/// A wrapper implementation for cached values, suitable for {@link Map} based
	/// caches where a significant portion of keys matches the corresponding value
	/// exactly.
	/// </summary>
	public class ValueWrapper<T>
	{
		private const long serialVersionUID = -9054807517127343156L;

		/// <summary>
		/// Indication of how the key of this cache entry represents the cache value.
		/// </summary>
		public enum RepresentationType
		{
			/// <summary>
			/// The key that maps to this {@link ValueWrapper} instance cannot be
			/// used to generate a valid value.
			/// </summary>
			ILLEGAL,

			/// <summary>
			/// The generated value based on the key that maps to this
			/// {@link ValueWrapper} would be an exact duplicate of the key. To
			/// conserve memory, this wrapped value instance will not have a value
			/// set. Use the key that points to this wrapper instead.
			/// </summary>
			USE_KEY,

			/// <summary>
			/// The key that maps to this {@link ValueWrapper} can be used to
			/// generate a valid value. The generated value is wrapped in this
			/// {@link ValueWrapper} instance.
			/// </summary>
			USE_VALUE
		}

		/// <summary>
		/// The value that is wrapped.
		/// </summary>
		private readonly T value;

		/// <summary>
		/// Indicates how the key that maps to this value can be used to extract the
		/// value from the cache entry.
		/// </summary>
		private readonly RepresentationType representation;

		/// <summary>
		/// Constructs an empty wrapper. This wrapper either is used to indicate that
		/// the key that maps to this value: cannot be used to generate a valid
		/// value, or, is an exact duplicate of the generated value.
		/// </summary>
		/// <param name="representation">Key representation indicator.</param>
		/// <exception cref="">An {@link IllegalArgumentException} is thrown if the argument is
		/// <tt>USE_VALUE</tt>.</exception>
		public ValueWrapper(RepresentationType representation)
		{
			if (representation == RepresentationType.USE_VALUE)
				throw new ArgumentException();

			this.representation = representation;
			this.value = default(T);
		}

		/// <summary>
		/// Wraps a value while using the <tt>USE_VALUE</tt> representation.
		/// </summary>
		/// <param name="value">The value that is wrapped.</param>
		public ValueWrapper(T value)
		{
			this.representation = RepresentationType.USE_VALUE;
			this.value = value;
		}

		/// <summary>
		/// Returns the wrapped value, or <tt>null</tt> if the representation used in
		/// this instance is not USE_VALUE;
		/// </summary>
		/// <returns>the wrapped value</returns>
		public T Value {
			get { return value; }
		}

		public RepresentationType Representation {
			get { return representation; }
		}
	}
}


text:
package com.cloudhopper.commons.gsm;

// third party imports
import com.cloudhopper.commons.util.*;

/**
 * Utility methods for working with GSM mobile technologies.
 *
 * @author joelauer
 */
public class GsmUtil {

    /**
     * Converts an address to a BCD-encoded byte array.  Any odd-length address
     * such as "10950" will have an 0xF byte added as the most signification
     * digit onto the end.  Used inside PDUs to encode addresses.  For example,
     * "10950" will look like this byte[] afterwards [0x01 0x59 0xf0].
     * @param address The address to encode such as "10950" or "13135554272"
     * @return A BCD-encoded byte array such as [0x01 0x59 0xf0] for "10950" or
     *      [0x31 0x31 0x55 0x45 0x72 0xf2] for "13135554272".  Will return a
     *      zero-length byte[] for an empty address.
     * @throws NullPointerException If the address is null
     * @throws IllegalArgumentException If the address does not contain only digits
     */
    public static byte[] toBcd(String address) throws NullPointerException, IllegalArgumentException {
        if (address == null) {
            throw new NullPointerException("Address cannot be null for BCD encoding");
        }

        if (!StringUtil.containsOnlyDigits(address)) {
            throw new IllegalArgumentException("Address must only contain digits");
        }

        // make sure this address is always an even length
        if (address.length() % 2 != 0) {
            // add an extra F onto the end
            address = address + "F";
        }

        // calculate length of final byte[]
        int bytes_len = address.length() / 2;
        byte[] bcd = new byte[bytes_len];

        for (int i = 0; i < bytes_len; i++) {
            StringBuilder chunk = new StringBuilder(address.substring(i * 2, (i * 2) + 2));
            // reverse the digits since its BCD encoded
            chunk.reverse();
            // get the byte
            byte[] bytes = HexUtil.toByteArray(chunk.toString());
            //byte[] bytes = ByteUtil.decodeHex(chunk.toString(), 2);
            // add this byte onto our total
            bcd[i] = bytes[0];
        }

        return bcd;
    }

    public static byte toSubmitInfo(boolean replyPath, boolean udhIndicator,
            boolean deliveryReceipt, int validityPeriodFormat, boolean rejectDuplicates)
            throws IllegalArgumentException {

        // generate proper submit info
        byte info = 0;

        // 7 0 TP-Reply -Path Reply path no set
        if (replyPath) {
            info |= (1 << 7);
        }

        // 6 0 TP-User-Data -header-indicator Indication that user data doesn't contain additional header.
        if (udhIndicator) {
            info |= (1 << 6);
        }

        // 5 0 TP-Status -Report-Request Not requested
        if (deliveryReceipt) {
            info |= (1 << 5);
        }

        // 4 1 TP-Validity -Period-Format Relative format (bits 4 and 3)
        // 3 0 TP-Validity -Period-Format Relative format (bits 4 and 3)
        //			4 3 (bits)
        //			0 0 TP-VP field not present
        //			1 0 TP-VP field present - relative format
        //			0 1 TP-VP field present - enhanced format
        //			1 1 TP-VP field present - absolute format
        if (validityPeriodFormat == GsmConstants.VP_FORMAT_RELATIVE) {
            info |= (1 << 4);
        } else if (validityPeriodFormat == GsmConstants.VP_FORMAT_ENHANCED) {
            info |= (1 << 3);
        } else if (validityPeriodFormat == GsmConstants.VP_FORMAT_ABSOLUTE) {
            info |= (1 << 4);
            info |= (1 << 3);
        } else if (validityPeriodFormat == GsmConstants.VP_FORMAT_NONE) {
            // zero by default so we don't add any bits
        } else {
            throw new IllegalArgumentException("Invalid validity period format");
        }

        // 2 0 TP-Rejected -Dublicates Do not reject duplicates in SC
        //		- 0 Instruct the SC to accept an SMS-SUBMIT for an SM still held in the
        //		SC which has the same TP-MR and the same TP-DA as a previously submitted SM from the
        //		same OA.
        //		- 1 Instruct the SC to reject an SMS-SUBMIT for an SM still held in the
        //		SC which has the same TP-MR and the same TP-DA as the previously submitted SM from the
        //		same OA. In this case an appropriate TP-FCS value will be returned in the
        //		SMS-SUBMIT-REPORT.
        if (rejectDuplicates) {
            info |= (1 << 2);
        }

        // 1 0 TP-Message -Type-Indicator type:SMS-SUBMIT (from phone to network), (bits 1 and 0)
        // 0 1 TP-Message -Type-Indicator type:SMS-SUBMIT (from phone to network), (bits 1 and 0)
        /**
        0 0 SMS-DELIVER (in the direction SC to MS)
        0 0 SMS-DELIVER REPORT (in the direction MS to SC)
        1 0 SMS-STATUS-REPORT (in the direction SC to MS)
        1 0 SMS-COMMAND (in the direction MS to SC)
        0 1 SMS-SUBMIT (in the direction MS to SC)
        0 1 SMS-SUBMIT-REPORT (in the direction SC to MS)
        1 1 Reserved
         */
        // set to SMS-SUBMIT
        info |= (1 << 0);

        return info;
    }

    /**
     * NOTE: Use getShortMessageUserData
     * @deprecated
     * @see #getShortMessageUserData(byte[])
     */
    static public byte[] removeUserDataHeader(byte[] shortMessage) {
        return getShortMessageUserData(shortMessage);
    }

    /**
     * Gets the "User Data" part of a short message byte array. Only call this
     * method if the short message contains a user data header. This method will
     * take the value of the first byte ("N") as the length of the user
     * data header, then remove ("N+1") bytes from the the short message and
     * return the remaining bytes as the "User Data".
     * @param shortMessage The byte array representing the entire message including
     *      a user data header and user data.  A null will return null.  An
     *      empty byte array will return an empty byte array.  A byte array
     *      not containing enough data will throw an IllegalArgumentException.
     * @return A byte array of the user data (minus the user data header)
     * @throws IllegalArgumentException If the byte array does not contain
     *      enough data to fit both the user data header and user data.
     */
    static public byte[] getShortMessageUserData(byte[] shortMessage) throws IllegalArgumentException {
        if (shortMessage == null) {
            return null;
        }

        if (shortMessage.length == 0) {
            return shortMessage;
        }

        // the entire length of UDH is the first byte + the length
        int userDataHeaderLength = ByteUtil.decodeUnsigned(shortMessage[0]) + 1;

        // is there enough data?
        if (userDataHeaderLength > shortMessage.length) {
            throw new IllegalArgumentException("User data header length exceeds short message length [shortMessageLength=" + shortMessage.length + ", userDataHeaderLength=" + userDataHeaderLength + "]");
        }

        // create a new message with the header removed
        int newShortMessageLength = shortMessage.length - userDataHeaderLength;
        byte[] newShortMessage = new byte[newShortMessageLength];

        System.arraycopy(shortMessage, userDataHeaderLength, newShortMessage, 0, newShortMessageLength);

        return newShortMessage;
    }

    /**
     * Gets the "User Data Header" part of a short message byte array. Only call this
     * method if the short message contains a user data header. This method will
     * take the value of the first byte ("N") as the length of the user
     * data header and return the first ("N+1") bytes from the the short message.
     * @param shortMessage The byte array representing the entire message including
     *      a user data header and user data.  A null will return null.  An
     *      empty byte array will return an empty byte array.  A byte array
     *      not containing enough data will throw an IllegalArgumentException.
     * @return A byte array of the user data header (minus the user data)
     * @throws IllegalArgumentException If the byte array does not contain
     *      enough data to fit both the user data header and user data.
     */
    static public byte[] getShortMessageUserDataHeader(byte[] shortMessage) throws IllegalArgumentException {
        if (shortMessage == null) {
            return null;
        }

        if (shortMessage.length == 0) {
            return shortMessage;
        }

        // the entire length of UDH is the first byte + the length
        int userDataHeaderLength = ByteUtil.decodeUnsigned(shortMessage[0]) + 1;

        // is there enough data?
        if (userDataHeaderLength > shortMessage.length) {
            throw new IllegalArgumentException("User data header length exceeds short message length [shortMessageLength=" + shortMessage.length + ", userDataHeaderLength=" + userDataHeaderLength + "]");
        }

        // is the user data header the only part of the payload (optimization)
        if (userDataHeaderLength == shortMessage.length) {
            return shortMessage;
        }

        // create a new message with just the header
        byte[] userDataHeader = new byte[userDataHeaderLength];
        System.arraycopy(shortMessage, 0, userDataHeader, 0, userDataHeaderLength);

        return userDataHeader;
    }

    /**
     * Creates multiple short messages (that include a user data header) by
     * splitting the binaryShortMessage data into 134 byte parts.  If the
     * binaryShortMessage does not need to be concatenated (less than or equal
     * to 140 bytes), this method will return NULL.
     *

     * WARNING: This method only works on binary short messages that use 8-bit
     * bytes.  Short messages using 7-bit data or packed 7-bit data will not
     * be correctly handled by this method.
     *

     * For example, will take a byte message (in hex, 138 bytes long)
     *

     *   01020304...85<byte 134>87888990
     *

     * Would be split into 2 parts as follows (in hex, with user data header)

     *   050003CC020101020304...85<byte 134>

     *   050003CC020287888990

     *

     * http://en.wikipedia.org/wiki/Concatenated_SMS
     *
     * @param binaryShortMessage The 8-bit binary short message to create the
     *      concatenated short messages from.
     * @param referenceNum The CSMS reference number that will be used in the
     *      user data header.
     * @return NULL if the binaryShortMessage does not need concatenated or
     *      an array of byte arrays representing each chunk (including UDH).
     * @throws IllegalArgumentException
     */
    static public byte[][] createConcatenatedBinaryShortMessages(byte[] binaryShortMessage, byte referenceNum) throws IllegalArgumentException {
        if (binaryShortMessage == null) {
            return null;
        }
        // if the short message does not need to be concatenated
        if (binaryShortMessage.length <= 140) {
            return null;
        }

        // since the UDH will be 6 bytes, we'll split the data into chunks of 134
        int numParts = (int) (binaryShortMessage.length / 134) + (binaryShortMessage.length % 134 != 0 ? 1 : 0);
        //logger.debug("numParts=" + numParts);

        byte[][] shortMessageParts = new byte[numParts][];

        for (int i = 0; i < numParts; i++) {
            // default this part length to max of 134
            int shortMessagePartLength = 134;
            if ((i + 1) == numParts) {
                // last part (only need to add remainder)
                shortMessagePartLength = binaryShortMessage.length - (i * 134);
            }

            //logger.debug("part " + i + " len: " + shortMessagePartLength);

            // part will be UDH (6 bytes) + length of part
            byte[] shortMessagePart = new byte[6 + shortMessagePartLength];
            // Field 1 (1 octet): Length of User Data Header, in this case 05.
            shortMessagePart[0] = (byte) 0x05;
            // Field 2 (1 octet): Information Element Identifier, equal to 00 (Concatenated short messages, 8-bit reference number)
            shortMessagePart[1] = (byte) 0x00;
            // Field 3 (1 octet): Length of the header, excluding the first two fields; equal to 03
            shortMessagePart[2] = (byte) 0x03;
            // Field 4 (1 octet): 00-FF, CSMS reference number, must be same for all the SMS parts in the CSMS
            shortMessagePart[3] = referenceNum;
            // Field 5 (1 octet): 00-FF, total number of parts. The value shall remain constant for every short message which makes up the concatenated short message. If the value is zero then the receiving entity shall ignore the whole information element
            shortMessagePart[4] = (byte) numParts;
            // Field 6 (1 octet): 00-FF, this part's number in the sequence. The value shall start at 1 and increment for every short message which makes up the concatenated short message. If the value is zero or greater than the value in Field 5 then the receiving entity shall ignore the whole information element. [ETSI Specification: GSM 03.40 Version 5.3.0: July 1996]
            shortMessagePart[5] = (byte) (i + 1);

            // copy this part's user data onto the end
            System.arraycopy(binaryShortMessage, (i * 134), shortMessagePart, 6, shortMessagePartLength);
            shortMessageParts[i] = shortMessagePart;
        }

        return shortMessageParts;
    }
}


text:
StiGame Sprite Editor
========

This is a simple sprite assembler, you put your image into a sprite and you can save it into the format of StiGame Sprite.

This is only supporting PNG image at the moment.

### Dependency

We are using PyQt4 for Gui. So you need to get this python library to make this tool work.

This application is developed with Python-2.7 and tested with Python-2.7-x86_64 on Windows 7.

###TO DO

 - Multiselect of images

 - Direction VarFile support

 - File filter for ~~open~~ and save dialog

 - Resource file support
    - New resource
    - delete resource
    - Resource rename
    - save support

 - File superclass ?


text:
<?php
namespace DatabaseRouter\Models;

use Vegas\Db\Decorator\CollectionAbstract;

class Route extends CollectionAbstract
{
    public $name;
    public $identifier; // identifier + route name = unique key
    public $priority;
    public $url;

    public function _getSource()
    {
        return 'vegas_routes';
    }

    public function getIdentifier()
    {
        return $this->identifier;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getUrl()
    {
        return $this->url;
    }

    public function getPriority()
    {
        return $this->priority;
    }
}


text:
package me.panavtec.katas.gameoflife;

public class CellState {
  public static final int DEAD = 0;
  public static final int ALIVE = 1;
}


text:
package com.haulmont.chile.core.datatypes.impl;

import com.google.common.collect.ImmutableMap;
import com.haulmont.cuba.client.testsupport.CubaClientTestCase;
import com.haulmont.cuba.core.sys.AppContext;
import mockit.Expectations;
import org.junit.Ignore;

import java.util.Locale;

public class AbstractDatatypeTestCase extends CubaClientTestCase {

    protected Locale ruLocale;
    protected Locale enGbLocale;

    public void setUp() {
        ruLocale = Locale.forLanguageTag("ru");
        enGbLocale = Locale.forLanguageTag("en_GB");

        addEntityPackage("com.haulmont.cuba");
        setupInfrastructure();

        new Expectations() {
            {
                AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.gui"; minTimes = 0;
                globalConfig.getAvailableLocales(); result = ImmutableMap.of("ru", ruLocale, "en_GB", enGbLocale); minTimes = 0;
            }
        };
        messages.init();
    }
}


text:
package bio.terra.service.snapshot.flight.duos;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;

import bio.terra.common.category.Unit;
import bio.terra.model.DuosFirecloudGroupModel;
import bio.terra.stairway.FlightContext;
import bio.terra.stairway.FlightMap;
import java.util.UUID;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.context.ActiveProfiles;

@RunWith(MockitoJUnitRunner.StrictStubs.class)
@ActiveProfiles({"google", "unittest"})
@Category(Unit.class)
public class SnapshotDuosFlightUtilsTest {

  @Mock FlightContext context;

  @Test
  public void testGetFirecloudGroup() {
    FlightMap workingMap = new FlightMap();
    when(context.getWorkingMap()).thenReturn(workingMap);

    assertNull(SnapshotDuosFlightUtils.getFirecloudGroup(context));

    DuosFirecloudGroupModel group = new DuosFirecloudGroupModel().id(UUID.randomUUID());
    workingMap.put(SnapshotDuosMapKeys.FIRECLOUD_GROUP, group);
    assertThat(SnapshotDuosFlightUtils.getFirecloudGroup(context), equalTo(group));
  }

  @Test
  public void testGetDuosFirecloudGroupId() {
    assertNull(SnapshotDuosFlightUtils.getDuosFirecloudGroupId(null));
    assertNull(SnapshotDuosFlightUtils.getDuosFirecloudGroupId(new DuosFirecloudGroupModel()));

    UUID id = UUID.randomUUID();
    DuosFirecloudGroupModel groupWithId = new DuosFirecloudGroupModel().id(id);
    assertThat(SnapshotDuosFlightUtils.getDuosFirecloudGroupId(groupWithId), equalTo(id));
  }
}


text:
module GrapeApiary
  class SampleGenerator
    attr_reader :resource, :root

    delegate :unique_params, to: :resource

    def initialize(resource)
      @resource = resource
      @root     = resource.key.singularize
    end

    def sample(id = false)
      array = resource.unique_params.map do |param|
        next if param.name == root

        [param.name, param.example]
      end

      hash = Hash[array.compact]

      hash = hash.reverse_merge(id: Config.generate_id) if id
      hash = { root => hash } if Config.include_root

      hash
    end

    def request
      hash = sample

      return unless hash.present?

      # format json spaces for blueprint markdown
      JSON
        .pretty_generate(hash)
        .gsub('{', (' ' * 14) + '{')
        .gsub('}', (' ' * 14) + '}')
        .gsub(/\ {2}\"/, (' ' * 16) + '"')
    end

    def response(list = false)
      return unless (hash = sample(true)).present?

      pretty_response_for(list ? [hash] : hash)
    end

    private

    # rubocop:disable Metrics/AbcSize
    def pretty_response_for(hash)
      JSON
        .pretty_generate(hash)
        .gsub('[', (' ' * 12) + '[')
        .gsub(']', (' ' * 12) + ']')
        .gsub('{', (' ' * 14) + '{')
        .gsub('}', (' ' * 14) + '}')
        .gsub(/\ {2}\"/, (' ' * 16) + '"')
    end
    # rubocop:enable Metrics/AbcSize
  end
end


text:
import pytest
import numpy as np
from ..run_beamplasma import initial
from pythonpic.helper_functions.physics import did_it_thermalize
from . import on_failure
#
@pytest.mark.parametrize(["L", "T", "should_it_thermalize"], [
    (2*np.pi, 60, False),
    (0.2*np.pi, 60, False),
    ])
def test_twostream_likeness(L, T, should_it_thermalize):
    run_name = f"BP_TWOSTREAM_{L}"
    S = initial(run_name, L=L, T=T).test_run()
    assert (did_it_thermalize(S)[:2] == should_it_thermalize).all(), ("Incorrect thermalization",
                                                                      S.plots(*on_failure, alpha=0.5))


text:
package com.github.kimutansk.awsiot

import java.io.{ByteArrayInputStream, InputStream, InputStreamReader}
import java.nio.file.{Files, Paths}
import java.security.cert.{CertificateFactory, X509Certificate}
import java.security.{KeyPair, KeyStore, Security}
import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLSocketFactory, TrustManagerFactory}

import org.bouncycastle.cert.X509CertificateHolder
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import org.bouncycastle.openssl.{PEMKeyPair, PEMParser}

/** Factory for [[javax.net.ssl.SSLSocketFactory]] instances. */
object SocketFactoryGenerator {

  /**
   * Generate [[javax.net.ssl.SSLSocketFactory]] from pem file paths.
   *
   * @param rootCaFilePath Root CA file path
   * @param certFilePath Certificate file path
   * @param keyFilePath Private key file path
   * @return Generated [[javax.net.ssl.SSLSocketFactory]]
   */
  def generateFromFilePath(rootCaFilePath:String, certFilePath:String, keyFilePath:String):SSLSocketFactory = {
    Security.addProvider(new BouncyCastleProvider())

    // load Root CA certificate
    val rootCaParser:PEMParser  = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(rootCaFilePath)))))
    val rootCaCertHolder:X509CertificateHolder = rootCaParser.readObject().asInstanceOf[X509CertificateHolder]
    val rootCaCert:X509Certificate = convertToJavaCertificate(rootCaCertHolder)
    rootCaParser.close()

    // load Server certificate
    val certParser:PEMParser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(certFilePath)))))
    val serverCertHolder:X509CertificateHolder = certParser.readObject.asInstanceOf[X509CertificateHolder]
    val serverCert:X509Certificate = convertToJavaCertificate(serverCertHolder)
    certParser.close()

    // load Private Key
    val keyParser:PEMParser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFilePath)))))
    val pemKeyPair:PEMKeyPair = keyParser.readObject.asInstanceOf[PEMKeyPair]
    val keyPair:KeyPair = new JcaPEMKeyConverter().getKeyPair(pemKeyPair)
    keyParser.close()

    // Root CA certificate is used to authenticate server
    val rootCAKeyStore:KeyStore = KeyStore.getInstance(KeyStore.getDefaultType())
    rootCAKeyStore.load(null, null)
    rootCAKeyStore.setCertificateEntry("ca-certificate", convertToJavaCertificate(rootCaCertHolder))
    val tmf:TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(rootCAKeyStore);

    // client key and certificates are sent to server so it can authenticate us
    val ks:KeyStore  = KeyStore.getInstance(KeyStore.getDefaultType())
    ks.load(null, null)
    ks.setCertificateEntry("certificate", serverCert)
    ks.setKeyEntry("private-key", keyPair.getPrivate(), "DummyPassword".toCharArray, Array(serverCert))
    val kmf:KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(ks, "DummyPassword".toCharArray());

    // finally, create SSL socket factory
    val context:SSLContext = SSLContext.getInstance("TLSv1.2")
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)

    context.getSocketFactory()
  }

  def convertToJavaCertificate(certificateHolder:X509CertificateHolder):X509Certificate = {
     val is:InputStream = new ByteArrayInputStream(certificateHolder.toASN1Structure.getEncoded);
    try {
      CertificateFactory.getInstance("X.509").generateCertificate(is).asInstanceOf[X509Certificate]
    } finally is.close()
  }
}


text:
package c37;

public class C37 {

	public static int a=999;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
        System.out.println("C37---main");
	}

}


text:
/**
 * Default state model.
 *
 * This implementation only contains <key,value> pairs. This model contains no relation to the actual user session.
 */
Ext.define('hlx.base.state.Model', {

    extend: 'Ext.data.Model',

    idProperty: 'name',

    fields: [
        {
            name: 'name',
            type: 'string'
        },
        {
            name: 'value',
            type: 'string'
        }
    ]

});/*******************************************************************************
 * Copyright (c) 2012 by Jan Philipp, Herrmann & Lenz Solutions GmbH
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

/**
 * Default state store.
 *
 * This implementation relies on a simple remote HTTP based storage.
 */
Ext.define('hlx.base.state.Store', {

    extend  : 'Ext.data.Store',
    requires: [ 'hlx.base.state.Model' ],

    model: 'hlx.base.state.Model',

    pageSize: -1,

    proxy: {
        type  : 'ajax',
        //url   : 'cookies.json',
        url: '/portal/portal/patric/BreadCrumb/WorkspaceWindow?action=b&cacheability=PAGE&action_type=HTTPProvider&action=storage',
        reader: {
            type: 'json',
            root: 'data'
        },
        writer: {
            type: 'json'
        }
    }

});/*******************************************************************************
 * Copyright (c) 2012 by Jan Philipp, Herrmann & Lenz Solutions GmbH
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

/**
 * A StateProvider solution for Ext JS applications using backend driven states via HTTP.
 *
 * The default configuration enables buffering to avoid multiple write requests.
 */
Ext.define('hlx.base.state.HttpProvider', {

    extend: 'Ext.state.Provider',

    requires: [ 'hlx.base.state.Store' ],

    uses: [ 'Ext.state.Provider', 'Ext.util.Observable' ],

    /**
     * The internal store.
     */
    store: null,

    /**
     * If set to true (not default), the store will be loaded at startup.
     */
    storeSyncOnLoadEnabled: true,

    /**
     * If set to true (default), the store's write event will be buffered to avoid multiple calls at the same time.
     */
    buffered: true,

    /**
     * Defines the buffer time (in milliseconds) for the buffered store.
     */
    writeBuffer: 2000,

    /**
     * Callback which will be called on the first store load. This requires storeSyncOnLoadEnabled = true.
     */
    onFirstLoad: Ext.emptyFn,

    constructor: function (config) {
        config = config || {};
        var me = this;
        Ext.apply(me, config);

        if (!me.store) {
            me.store = me.buildStore();
        }

        /**
         * Unless we found a better solution, the following lines ensure that the component's constructor will be
         * returned only if the store was loaded the first time.
         *
         * See also: http://www.sencha.com/forum/showthread.php?141207
         */
        if (me.storeSyncOnLoadEnabled) {
            // Have to block in order to load the store before leaving the
            // constructor, otherwise, the first query may be against an
            // empty store. There must be a better way...
            var oldValue = Ext.data.Connection.prototype.async;
            Ext.data.Connection.prototype.async = false;
            me.store.load({
                callback: me.onFirstLoad
            });
            Ext.data.Connection.prototype.async = oldValue;
        }

        // Call super
        me.callParent(arguments);

        if (me.buffered) {
            me.on({
                'statechange': {
                    scope : me,
                    buffer: me.writeBuffer,
                    fn    : me.sync
                }
            });
        } else {
            me.on({
                'statechange': {
                    scope: me,
                    fn   : me.sync
                }
            });
        }
    },

    set: function (name, value) {
        var me = this, pos = me.store.find('name', name), row;

        if (pos > -1) {
            row = me.store.getAt(pos);
            row.set('value', me.encodeValue(value));
        } else {
            me.store.add({
                name : name,
                value: me.encodeValue(value)
            });
        }

        me.fireEvent('statechange', me, name, value);
    },

    get: function (name, defaultValue) {
        var me = this, pos = me.store.findExact('name', name), row, value;
        if (pos > -1) {
            row = me.store.getAt(pos);
            value = me.decodeValue(row.get('value'));
        } else {
            value = defaultValue;
        }
        return value;
    },

    clear: function (name) {
        var me = this, pos = me.store.find('name', name);
        if (pos > -1) {
            me.store.removeAt(pos);
            me.fireEvent('statechange', me, name, null);
        }
    },

    sync: function () {
        this.store.sync();
    },

    buildStore: function () {
        return Ext.create('hlx.base.state.Store');
    }

});


text: module.exports = require("external2");


text:
package com.zmq.shopmall.activity;

import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.yinglan.keyboard.HideUtil;
import com.zmq.shopmall.R;
import com.zmq.shopmall.R2;
import com.zmq.shopmall.adapter.HotSearchAdapter;
import com.zmq.shopmall.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/6/10.
 */

public class SearchActivity extends BaseActivity {
    @BindView(R2.id.iv_back)
    ImageView ivBack; //返回
    @BindView(R2.id.et_search)
    EditText etSearch; //搜索输入框
    @BindView(R2.id.iv_voice)
    ImageView ivVoice;
    @BindView(R2.id.tv_search)
    TextView tvSearch; //搜索
    @BindView(R2.id.rv_hot_search)
    RecyclerView rvHotSearch; //热搜列表

    private List<String> hotSearchList;
    private HotSearchAdapter hotSearchAdapter;
    private boolean isClear;

    public SearchActivity() {
        super(R.layout.activity_search_library);
    }

    @Override
    protected void initView() {
        HideUtil.init(this);
        setHotSearchList();
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexWrap(FlexWrap.WRAP); //设置是否换行
        layoutManager.setFlexDirection(FlexDirection.ROW); //设置子元素的排列方向 默认水平排列
        layoutManager.setAlignItems(AlignItems.STRETCH);//沿副轴对齐(单行起作用) 高度充满
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);//沿主轴左对齐
        rvHotSearch.setLayoutManager(layoutManager);
        hotSearchAdapter = new HotSearchAdapter(hotSearchList);
        rvHotSearch.setAdapter(hotSearchAdapter);
        hotSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showShortToast(hotSearchList.get(position) + "");
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0){
                    ivVoice.setImageResource(R.mipmap.cp_ic_search_clear);
                    isClear = true;
                }else {
                    ivVoice.setImageResource(R.mipmap.ic_voice_library);
                    isClear = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R2.id.iv_back, R2.id.tv_search, R2.id.iv_voice})
    void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.iv_voice) {
            if (isClear) {
                etSearch.setText("");
            } else {
                showShortToast("语音");
            }

        } else if (i == R.id.tv_search) {
            startActivityAndFinish(SearchDetailActivity.class);

        } else {
        }
    }

    /**
     * 模拟热搜数据
     */
    private void setHotSearchList() {
        hotSearchList = new ArrayList<>();
        hotSearchList.add("无糖奶粉");
        hotSearchList.add("抽纸99-50");
        hotSearchList.add("数码收纳包");
        hotSearchList.add("计步器");
        hotSearchList.add("小米放大器");
        hotSearchList.add("茅台酒");
        hotSearchList.add("迷你洗衣机");
        hotSearchList.add("炼狱蝰蛇");
        hotSearchList.add("虾片");
        hotSearchList.add("肉脯199-100");
        hotSearchList.add("祛斑199-100");
        hotSearchList.add("月光宝盒");
        hotSearchList.add("洗衣机");
        hotSearchList.add("筹资");
        hotSearchList.add("硝酸铵");
    }
}


text:
"use strict";

const EventEmitter = require('events');
const evts = new EventEmitter();

const needle = require('needle');

let lastValues = {
	temperature: NaN,
	humidity: NaN
};

function update () {
	needle.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Cluj-Napoca%22)%20and%20u%3D%27c%27&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys', function (err, response) {
		if (err) {
			console.log(err);
			return;
		}

		try {
			let temperature = parseInt(response.body.query.results.channel.item.condition.temp, 10);
			let humidity = parseInt(response.body.query.results.channel.atmosphere.humidity, 10);

			if (lastValues.temperature !== temperature || lastValues.humidity !== humidity) {
				lastValues.temperature = temperature;
				lastValues.humidity = humidity;

				evts.emit('change', lastValues);
			}
		} catch (e) {
			console.log(e);
		}
	});
}
setInterval(() => {
	update();
}, 60 * 1000);
update();

exports.get = function () {
	return lastValues;
};

exports.evts = evts;


text:
require 'spec_helper'

describe 'earlyoom' do

  describe command('earlyoom -h') do
    its(:exit_status) { should eq 1 }
  end

  describe service('earlyoom') do
    it { should be_running }
  end
end


text:
<?php

use function DI\factory;
use function DI\object;
use Interop\Container\ContainerInterface;
use PhpParser\Parser;
use PhpSchool\BackToBasics\Exercise\FirstStringsFirst;
use PhpSchool\BackToBasics\Exercise\Numbers;
use PhpSchool\BackToBasics\Exercise\Variables;

return [
    // Exercises
    Variables::class         => factory(function (ContainerInterface $c) {
        return new Variables($c->get(Parser::class));
    }),
    FirstStringsFirst::class => factory(function (ContainerInterface $c) {
        return new FirstStringsFirst($c->get(Parser::class));
    }),
    Numbers::class => factory(function (ContainerInterface $c) {
        return new Numbers($c->get(Parser::class));
    }),
];


text:
package org.sejda.sambox.pdmodel.interactive.annotation;

import org.sejda.sambox.cos.COSDictionary;
import org.sejda.sambox.cos.COSName;
import org.sejda.sambox.pdmodel.common.filespecification.FileSpecifications;
import org.sejda.sambox.pdmodel.common.filespecification.PDFileSpecification;

/**
 * This is the class that represents a file attachement.
 *
 * @author Ben Litchfield
 */
public class PDAnnotationFileAttachment extends PDAnnotationMarkup
{
    /**
     * See get/setAttachmentName.
     */
    public static final String ATTACHMENT_NAME_PUSH_PIN = "PushPin";
    /**
     * See get/setAttachmentName.
     */
    public static final String ATTACHMENT_NAME_GRAPH = "Graph";
    /**
     * See get/setAttachmentName.
     */
    public static final String ATTACHMENT_NAME_PAPERCLIP = "Paperclip";
    /**
     * See get/setAttachmentName.
     */
    public static final String ATTACHMENT_NAME_TAG = "Tag";

    /**
     * The type of annotation.
     */
    public static final String SUB_TYPE = "FileAttachment";

    /**
     * Constructor.
     */
    public PDAnnotationFileAttachment()
    {
        getCOSObject().setName(COSName.SUBTYPE, SUB_TYPE);
    }

    /**
     * Creates a Link annotation from a COSDictionary, expected to be a correct object definition.
     *
     * @param field the PDF object to represent as a field.
     */
    public PDAnnotationFileAttachment(COSDictionary field)
    {
        super(field);
    }

    /**
     * Return the attached file.
     *
     * @return The attached file.
     */
    public PDFileSpecification getFile()
    {
        return FileSpecifications.fileSpecificationFor(getCOSObject().getDictionaryObject("FS"));
    }

    /**
     * Set the attached file.
     *
     * @param file The file that is attached.
     */
    public void setFile(PDFileSpecification file)
    {
        getCOSObject().setItem("FS", file);
    }

    /**
     * This is the name used to draw the type of attachment. See the ATTACHMENT_NAME_XXX constants.
     *
     * @return The name that describes the visual cue for the attachment.
     */
    public String getAttachmentName()
    {
        return getCOSObject().getNameAsString(COSName.NAME, ATTACHMENT_NAME_PUSH_PIN);
    }

    /**
     * Set the name used to draw the attachment icon. See the ATTACHMENT_NAME_XXX constants.
     *
     * @param name The name of the visual icon to draw.
     */
    public void setAttachmentName(String name)
    {
        getCOSObject().setName(COSName.NAME, name);
    }
}


text:
package gov.nih.nci.cacore.workbench.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.log4j.Logger;

public final class WorkbenchPropertiesManager {

	private static final Logger log = Logger.getLogger(WorkbenchPropertiesManager.class);

	Properties deployProperties=null;

	public WorkbenchPropertiesManager(String deployPropsFilePath) {
		super();

		deployProperties = new Properties();
		try {

			InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(deployPropsFilePath);
			if (is == null){
				is = new FileInputStream(deployPropsFilePath);
			}

			deployProperties.load(is);
		} catch (IOException e) {
			log.error("ERROR :: Failed to load properties from " + deployPropsFilePath);
			e.printStackTrace();
		}
	}

	public WorkbenchPropertiesManager(String[] deployPropertiesFilePathArr) {
		super();

		deployProperties = new Properties();
		try {
			for (String deployPropsFilePath : deployPropertiesFilePathArr){
				log.debug("* * * Loading properties for file: " + deployPropsFilePath);

				InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(deployPropsFilePath);
				if (is == null){
					is = new FileInputStream(deployPropsFilePath);
				}

				deployProperties.load(is);
			}

			Enumeration<Object> keys = deployProperties.keys();
			while (keys.hasMoreElements()){
				String key = (String)keys.nextElement();
				log.debug("* * *  key: " + key + "; value: "+deployProperties.getProperty(key));
			}

		} catch (IOException e) {
			log.error("ERROR :: Failed to load properties from " + deployPropertiesFilePathArr);
			e.printStackTrace();
		}
	}

	public String getDeployPropertyValue(String propertyKey) {
		return deployProperties.getProperty(propertyKey);
	}

	public Properties getDeployProperties() {
		return deployProperties;
	}

}


text:
const state = {
  type: 0,
  infoVisible: false,
  baseInfo: ''
}
const mutations = {
  showInfo(state, payload) {
    state.infoVisible = true
    state.type = payload.type
    state.baseInfo = payload.info
  },
  hideInfo(state) {
    state.infoVisible = false
  }
}

export default {
  state,
  mutations
}


text:
package net.gree.aurora.domain.clustergroup;

/**
 * {@link ClusterGroupRepository}のためのファクトリ。
 */
public final class ClusterGroupRepositoryFactory {

    private ClusterGroupRepositoryFactory() {

    }

    /**
     * {@link ClusterGroupRepository}を生成する。
     *
     * @return {@link ClusterGroupRepository}
     */
    public static ClusterGroupRepository create() {
        return new ClusterGroupRepositoryImpl();
    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Tournament Schema
 */
var TournamentSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Tournament name',
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Tournament', TournamentSchema);


text:
package org.jiemamy.entity.io.gen.model.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import javax.persistence.TemporalType;

import org.jiemamy.entity.io.convensition.PersistenceConvention;
import org.jiemamy.entity.io.gen.desc.AttributeDesc;
import org.jiemamy.entity.io.gen.model.AttributeModel;
import org.jiemamy.entity.io.gen.model.AttributeModelFactory;
import org.jiemamy.utils.ClassUtil;

/**
 * {@link AttributeModelFactory}の実装クラス。
 *
 * @author j5ik2o
 */
public class AttributeModelFactoryImpl implements AttributeModelFactory {

	/** カラム名を表示する場合{@code true} */
	protected boolean showColumnName;

	/** カラム定義を表示する場合{@code true} */
	protected boolean showColumnDefinition;

	/** {@link TemporalType}を使用する場合{@code true} */
	protected boolean useTemporalType;

	/** 永続化層の命名規約 */
	protected PersistenceConvention persistenceConvention;

	/**
	 * インスタンスを生成する。
	 *
	 * @param persistenceConvention 永続化層の命名規約
	 * @param showColumnName カラム名を表示する場合{@code true}
	 * @param showColumnDefinition カラム定義を表示する場合{@code true}
	 * @param useTemporalType {@link TemporalType}を使用する場合{@code true}
	 */
	public AttributeModelFactoryImpl(PersistenceConvention persistenceConvention, boolean showColumnName,
			boolean showColumnDefinition, boolean useTemporalType) {
		this.persistenceConvention = persistenceConvention;
		this.showColumnName = showColumnName;
		this.showColumnDefinition = showColumnDefinition;
		this.useTemporalType = useTemporalType;
	}

	/**
	 * 属性のクラスを処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doAttributeClass(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		if (useTemporalType && attributeDesc.isTemporal()) {
			attributeModel.setTemporalType(attributeDesc.getTemporalType());
			attributeModel.setAttributeClass(Date.class);
		} else {
			attributeModel.setAttributeClass(attributeDesc.getAttributeClass());
		}
	}

	/**
	 * カラム定義を処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doColumnDefinition(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		attributeModel.setColumnDefinition(attributeDesc.getColumnDefinition());
		attributeModel.setUnsupportedColumnType(attributeDesc.isUnsupportedColumnType());
	}

	/**
	 * カラム名を処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doColumnName(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		String realColumnName = attributeDesc.getColumnName();
		String convertedColumnName = persistenceConvention.fromPropertyNameToColumnName(attributeModel.getName());
		if (showColumnName || !realColumnName.equalsIgnoreCase(convertedColumnName)) {
			attributeModel.setColumnName(realColumnName);
		}
	}

	/**
	 * 長さを処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doLength(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		if (attributeDesc.getLength() < 1) {
			return;
		}
		Class<?> clazz = ClassUtil.getWrapperClassIfPrimitive(attributeDesc.getAttributeClass());
		if (!Number.class.isAssignableFrom(clazz) && !Date.class.isAssignableFrom(clazz)
				&& !Calendar.class.isAssignableFrom(clazz)) {
			attributeModel.setLength(attributeDesc.getLength());
		}
	}

	/**
	 * 精度を処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doPrecision(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		if (attributeDesc.getPrecision() < 1) {
			return;
		}
		Class<?> clazz = ClassUtil.getWrapperClassIfPrimitive(attributeDesc.getAttributeClass());
		if (Number.class.isAssignableFrom(clazz)) {
			attributeModel.setPrecision(attributeDesc.getPrecision());
		}
	}

	/**
	 * スケールを処理する。
	 *
	 * @param attributeModel 属性モデル
	 * @param attributeDesc 属性記述
	 */
	protected void doScale(AttributeModel attributeModel, AttributeDesc attributeDesc) {
		if (attributeDesc.getScale() < 1) {
			return;
		}
		Class<?> clazz = ClassUtil.getWrapperClassIfPrimitive(attributeDesc.getAttributeClass());
		if (clazz == BigDecimal.class || clazz == Float.class || clazz == Double.class) {
			attributeModel.setScale(attributeDesc.getScale());
		}
	}

	public AttributeModel getAttributeModel(AttributeDesc attributeDesc) {
		AttributeModel attributeModel = new AttributeModel();
		attributeModel.setName(attributeDesc.getName());
		attributeModel.setId(attributeDesc.isId());
		attributeModel.setGenerationType(attributeDesc.getGenerationType());
		attributeModel.setInitialValue(attributeDesc.getInitialValue());
		attributeModel.setAllocationSize(attributeDesc.getAllocationSize());
		attributeModel.setLob(attributeDesc.isLob());
		attributeModel.setTransient(attributeDesc.isTransient());
		attributeModel.setVersion(attributeDesc.isVersion());
		attributeModel.setNullable(attributeDesc.isNullable());
		attributeModel.setUnique(attributeDesc.isUnique());
		attributeModel.setColumnTypeName(attributeDesc.getColumnTypeName());
		attributeModel.setComment(attributeDesc.getComment());
		doAttributeClass(attributeModel, attributeDesc);
		doColumnName(attributeModel, attributeDesc);
		if (showColumnDefinition) {
			doColumnDefinition(attributeModel, attributeDesc);
		} else {
			doLength(attributeModel, attributeDesc);
			doPrecision(attributeModel, attributeDesc);
			doScale(attributeModel, attributeDesc);
		}
		return attributeModel;
	}
}


text:
get '/' do
	if session[:user_id] == nil
		@user = User.new
		if params[:error]
			@error = params[:error]
		end
	  	erb :"static/index"
	else
		redirect "/users/#{session[:user_id]}"
	end
end


text:
Module message_box_rpc
======================

Module message_box_rpc

* [Function Index](#index)
* [Function Details](#functions)

Function Index

call/2

Function Details

call/2

`call(Fun, Args) -> any()`


text:
package org.overlord.rtgov.ui.provider.switchyard;

import org.overlord.rtgov.ui.server.i18n.AbstractMessages;

/**
 * I18N messages.
 *
 * @author eric.wittmann@redhat.com
 */
public class Messages extends AbstractMessages {

    public static final Messages i18n = new Messages();

    /**
     * Constructor.
     */
    public Messages() {
        super(Messages.class);
    }

}


text: {{image.file}}


text:
var isExist = ClipMenu.require('v8cgi/html');
if (!isExist) {
    throw new Error('Could not find the library');
}

var lines = clipText.split('\n');

for (var i = 0; i < lines.length; i++) {
    lines[i] = HTML.escape(lines[i]);
}

return lines.join('\n');


text:
package skinny.micro

/**
 * Represents unstable access to servlet objects managed by containers from unmanaged threads.
 */
class UnstableAccessException(attribute: String)
    extends RuntimeException(UnstableAccessException.message(attribute)) {

}

object UnstableAccessException {

  def message(attribute: String): String = {
    s"""
      |
      |------------------------------------------------------
      |
      |  !!! Concurrency Issue Detected !!!
      |
      |  Accessing $attribute from unmanaged threads, inside Future blocks in most cases, is too dangerous.
      |
      |  Objects managed by Servlet containers should be accessed on main threads.
      |
      |  Fix your code to copy needed values from $attribute as read-only ones before entering Future blocks.
      |
      |  Or, if you accept the risk, set the web controller's #unstableAccessValidationEnabled as false (default: true).
      |
      |------------------------------------------------------
      |""".stripMargin
  }

}