text:
package mil.nga.giat.geowave.datastore.accumulo.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;

import mil.nga.giat.geowave.core.index.ByteArrayId;
import mil.nga.giat.geowave.core.index.ByteArrayRange;
import mil.nga.giat.geowave.core.index.NumericIndexStrategy;
import mil.nga.giat.geowave.core.index.StringUtils;
import mil.nga.giat.geowave.core.index.sfc.data.MultiDimensionalNumericData;
import mil.nga.giat.geowave.core.store.CloseableIterator;
import mil.nga.giat.geowave.core.store.DataStoreEntryInfo;
import mil.nga.giat.geowave.core.store.ScanCallback;
import mil.nga.giat.geowave.core.store.DataStoreEntryInfo.FieldInfo;
import mil.nga.giat.geowave.core.store.adapter.AdapterPersistenceEncoding;
import mil.nga.giat.geowave.core.store.adapter.AdapterStore;
import mil.nga.giat.geowave.core.store.adapter.DataAdapter;
import mil.nga.giat.geowave.core.store.adapter.IndexedAdapterPersistenceEncoding;
import mil.nga.giat.geowave.core.store.adapter.WritableDataAdapter;
import mil.nga.giat.geowave.core.store.data.DataWriter;
import mil.nga.giat.geowave.core.store.data.PersistentDataset;
import mil.nga.giat.geowave.core.store.data.PersistentValue;
import mil.nga.giat.geowave.core.store.data.VisibilityWriter;
import mil.nga.giat.geowave.core.store.data.field.FieldReader;
import mil.nga.giat.geowave.core.store.data.field.FieldVisibilityHandler;
import mil.nga.giat.geowave.core.store.data.field.FieldWriter;
import mil.nga.giat.geowave.core.store.data.visibility.UnconstrainedVisibilityHandler;
import mil.nga.giat.geowave.core.store.data.visibility.UniformVisibilityWriter;
import mil.nga.giat.geowave.core.store.filter.DedupeFilter;
import mil.nga.giat.geowave.core.store.filter.FilterList;
import mil.nga.giat.geowave.core.store.filter.QueryFilter;
import mil.nga.giat.geowave.core.store.index.CommonIndexModel;
import mil.nga.giat.geowave.core.store.index.CommonIndexValue;
import mil.nga.giat.geowave.core.store.index.Index;
import mil.nga.giat.geowave.core.store.index.IndexStore;
import mil.nga.giat.geowave.core.store.query.Query;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloDataStore;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloOperations;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloRowId;
import mil.nga.giat.geowave.datastore.accumulo.BasicAccumuloOperations;
import mil.nga.giat.geowave.datastore.accumulo.ModelConvertingDataAdapter;
import mil.nga.giat.geowave.datastore.accumulo.Writer;
import mil.nga.giat.geowave.datastore.accumulo.metadata.AbstractAccumuloPersistence;
import mil.nga.giat.geowave.datastore.accumulo.metadata.AccumuloAdapterStore;
import mil.nga.giat.geowave.datastore.accumulo.metadata.AccumuloIndexStore;
import mil.nga.giat.geowave.datastore.accumulo.query.AccumuloConstraintsQuery;
import mil.nga.giat.geowave.datastore.accumulo.util.CloseableIteratorWrapper.ScannerClosableWrapper;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.ScannerBase;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.user.WholeRowIterator;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;

/**
 * A set of convenience methods for common operations on Accumulo within
 * GeoWave, such as conversions between GeoWave objects and corresponding
 * Accumulo objects.
 *
 */
public class AccumuloUtils
{
	private final static Logger LOGGER = Logger.getLogger(AccumuloUtils.class);
	public final static String ALT_INDEX_TABLE = "_GEOWAVE_ALT_INDEX";

	@SuppressWarnings({
		"rawtypes",
		"unchecked"
	})
	private static final UniformVisibilityWriter DEFAULT_VISIBILITY = new UniformVisibilityWriter(
			new UnconstrainedVisibilityHandler());

	public static Range byteArrayRangeToAccumuloRange(
			final ByteArrayRange byteArrayRange ) {
		final Text start = new Text(
				byteArrayRange.getStart().getBytes());
		final Text end = new Text(
				byteArrayRange.getEnd().getBytes());
		if (start.compareTo(end) > 0) {
			return null;
		}
		return new Range(
				new Text(
						byteArrayRange.getStart().getBytes()),
				true,
				Range.followingPrefix(new Text(
						byteArrayRange.getEnd().getBytes())),
				false);
	}

	public static TreeSet<Range> byteArrayRangesToAccumuloRanges(
			final List<ByteArrayRange> byteArrayRanges ) {
		if (byteArrayRanges == null) {
			final TreeSet<Range> range = new TreeSet<Range>();
			range.add(new Range());
			return range;
		}
		final TreeSet<Range> accumuloRanges = new TreeSet<Range>();
		for (final ByteArrayRange byteArrayRange : byteArrayRanges) {
			final Range range = byteArrayRangeToAccumuloRange(byteArrayRange);
			if (range == null) {
				continue;
			}
			accumuloRanges.add(range);
		}
		if (accumuloRanges.isEmpty()) {
			// implies full table scan
			accumuloRanges.add(new Range());
		}
		return accumuloRanges;
	}

	public static List<ByteArrayRange> constraintsToByteArrayRanges(
			final MultiDimensionalNumericData constraints,
			final NumericIndexStrategy indexStrategy ) {
		if ((constraints == null) || constraints.isEmpty()) {
			return new ArrayList<ByteArrayRange>(); // implies in negative and
			// positive infinity
		}
		else {
			return indexStrategy.getQueryRanges(constraints);
		}
	}

	public static List<ByteArrayRange> constraintsToByteArrayRanges(
			final MultiDimensionalNumericData constraints,
			final NumericIndexStrategy indexStrategy,
			final int maxRanges ) {
		if ((constraints == null) || constraints.isEmpty()) {
			return new ArrayList<ByteArrayRange>(); // implies in negative and
			// positive infinity
		}
		else {
			return indexStrategy.getQueryRanges(
					constraints,
					maxRanges);
		}
	}

	public static String getQualifiedTableName(
			final String tableNamespace,
			final String unqualifiedTableName ) {
		return ((tableNamespace == null) || tableNamespace.isEmpty()) ? unqualifiedTableName : tableNamespace + "_" + unqualifiedTableName;
	}

	public static Object decodeRow(
			final Key key,
			final Value value,
			final DataAdapter<?> adapter,
			final Index index ) {
		return decodeRow(
				key,
				value,
				adapter,
				null,
				index);
	}

	public static Object decodeRow(
			final Key key,
			final Value value,
			final DataAdapter<?> adapter,
			final QueryFilter clientFilter,
			final Index index ) {
		final AccumuloRowId rowId = new AccumuloRowId(
				key.getRow().copyBytes());
		return decodeRowObj(
				key,
				value,
				rowId,
				adapter,
				null,
				clientFilter,
				index,
				null);
	}

	@SuppressWarnings("unchecked")
	public static <T> T decodeRow(
			final Key key,
			final Value value,
			final AdapterStore adapterStore,
			final QueryFilter clientFilter,
			final Index index,
			final ScanCallback<T> scanCallback ) {
		final AccumuloRowId rowId = new AccumuloRowId(
				key.getRow().copyBytes());
		return (T) decodeRowObj(
				key,
				value,
				rowId,
				null,
				adapterStore,
				clientFilter,
				index,
				scanCallback);
	}

	public static Object decodeRow(
			final Key key,
			final Value value,
			final AccumuloRowId rowId,
			final AdapterStore adapterStore,
			final QueryFilter clientFilter,
			final Index index ) {
		return decodeRowObj(
				key,
				value,
				rowId,
				null,
				adapterStore,
				clientFilter,
				index,
				null);
	}

	private static <T> Object decodeRowObj(
			final Key key,
			final Value value,
			final AccumuloRowId rowId,
			final DataAdapter<T> dataAdapter,
			final AdapterStore adapterStore,
			final QueryFilter clientFilter,
			final Index index,
			final ScanCallback<T> scanCallback ) {
		final Pair<T, DataStoreEntryInfo> pair = decodeRow(
				key,
				value,
				rowId,
				dataAdapter,
				adapterStore,
				clientFilter,
				index,
				scanCallback);
		return pair != null ? pair.getLeft() : null;

	}

	@SuppressWarnings("unchecked")
	public static <T> Pair<T, DataStoreEntryInfo> decodeRow(
			final Key k,
			final Value v,
			final AccumuloRowId rowId,
			final DataAdapter<T> dataAdapter,
			final AdapterStore adapterStore,
			final QueryFilter clientFilter,
			final Index index,
			final ScanCallback<T> scanCallback ) {
		if ((dataAdapter == null) && (adapterStore == null)) {
			LOGGER.error("Could not decode row from iterator. Either adapter or adapter store must be non-null.");
			return null;
		}
		DataAdapter<T> adapter = dataAdapter;
		SortedMap<Key, Value> rowMapping;
		try {
			rowMapping = WholeRowIterator.decodeRow(
					k,
					v);
		}
		catch (final IOException e) {
			LOGGER.error("Could not decode row from iterator. Ensure whole row iterators are being used.");
			return null;
		}
		// build a persistence encoding object first, pass it through the
		// client filters and if its accepted, use the data adapter to
		// decode the persistence model into the native data type
		final PersistentDataset<CommonIndexValue> indexData = new PersistentDataset<CommonIndexValue>();
		final PersistentDataset<Object> extendedData = new PersistentDataset<Object>();
		// for now we are assuming all entries in a row are of the same type
		// and use the same adapter
		boolean adapterMatchVerified;
		ByteArrayId adapterId;
		if (adapter != null) {
			adapterId = adapter.getAdapterId();
			adapterMatchVerified = false;
		}
		else {
			adapterMatchVerified = true;
			adapterId = null;
		}
		final List<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>(
				rowMapping.size());

		for (final Entry<Key, Value> entry : rowMapping.entrySet()) {
			// the column family is the data element's type ID
			if (adapterId == null) {
				adapterId = new ByteArrayId(
						entry.getKey().getColumnFamilyData().getBackingArray());
			}

			if (adapter == null) {
				adapter = (DataAdapter<T>) adapterStore.getAdapter(adapterId);
				if (adapter == null) {
					LOGGER.error("DataAdapter does not exist");
					return null;
				}
			}
			if (!adapterMatchVerified) {
				if (!adapterId.equals(adapter.getAdapterId())) {
					return null;
				}
				adapterMatchVerified = true;
			}
			final ByteArrayId fieldId = new ByteArrayId(
					entry.getKey().getColumnQualifierData().getBackingArray());
			final CommonIndexModel indexModel;
			if (adapter instanceof ModelConvertingDataAdapter) {
				indexModel = ((ModelConvertingDataAdapter) adapter).convertModel(index.getIndexModel());
			}
			else {
				indexModel = index.getIndexModel();
			}
			// first check if this field is part of the index model
			final FieldReader<? extends CommonIndexValue> indexFieldReader = indexModel.getReader(fieldId);
			final byte byteValue[] = entry.getValue().get();
			if (indexFieldReader != null) {
				final CommonIndexValue indexValue = indexFieldReader.readField(byteValue);
				indexValue.setVisibility(entry.getKey().getColumnVisibilityData().getBackingArray());
				final PersistentValue<CommonIndexValue> val = new PersistentValue<CommonIndexValue>(
						fieldId,
						indexValue);
				indexData.addValue(val);
				fieldInfoList.add(getFieldInfo(
						val,
						byteValue,
						indexValue.getVisibility()));
			}
			else {
				// next check if this field is part of the adapter's
				// extended data model
				final FieldReader<?> extFieldReader = adapter.getReader(fieldId);
				if (extFieldReader == null) {
					// if it still isn't resolved, log an error, and
					// continue
					LOGGER.error("field reader not found for data entry, the value will be ignored");
					continue;
				}
				final Object value = extFieldReader.readField(byteValue);
				final PersistentValue<Object> val = new PersistentValue<Object>(
						fieldId,
						value);
				extendedData.addValue(val);
				fieldInfoList.add(getFieldInfo(
						val,
						byteValue,
						entry.getKey().getColumnVisibility().getBytes()));
			}
		}
		final IndexedAdapterPersistenceEncoding encodedRow = new IndexedAdapterPersistenceEncoding(
				adapterId,
				new ByteArrayId(
						rowId.getDataId()),
				new ByteArrayId(
						rowId.getInsertionId()),
				rowId.getNumberOfDuplicates(),
				indexData,
				extendedData);
		if ((clientFilter == null) || clientFilter.accept(encodedRow)) {
			// cannot get here unless adapter is found (not null)
			if (adapter == null) {
				LOGGER.error("Error, adapter was null when it should not be");
			}
			else {
				final Pair<T, DataStoreEntryInfo> pair = Pair.of(
						adapter.decode(
								encodedRow,
								index),
						new DataStoreEntryInfo(
								Arrays.asList(new ByteArrayId(
										k.getRowData().getBackingArray())),
								fieldInfoList));
				if (scanCallback != null) {
					scanCallback.entryScanned(
							pair.getRight(),
							pair.getLeft());
				}
				return pair;
			}
		}
		return null;
	}

	public static <T> DataStoreEntryInfo write(
			final WritableDataAdapter<T> writableAdapter,
			final Index index,
			final T entry,
			final Writer writer ) {
		return AccumuloUtils.write(
				writableAdapter,
				index,
				entry,
				writer,
				DEFAULT_VISIBILITY);
	}

	public static <T> DataStoreEntryInfo write(
			final WritableDataAdapter<T> writableAdapter,
			final Index index,
			final T entry,
			final Writer writer,
			final VisibilityWriter<T> customFieldVisibilityWriter ) {
		final DataStoreEntryInfo ingestInfo = getIngestInfo(
				writableAdapter,
				index,
				entry,
				customFieldVisibilityWriter);
		final List<Mutation> mutations = buildMutations(
				writableAdapter.getAdapterId().getBytes(),
				ingestInfo);

		writer.write(mutations);
		return ingestInfo;
	}

	public static <T> void removeFromAltIndex(
			final WritableDataAdapter<T> writableAdapter,
			final List<ByteArrayId> rowIds,
			final T entry,
			final Writer writer ) {

		final byte[] adapterId = writableAdapter.getAdapterId().getBytes();
		final byte[] dataId = writableAdapter.getDataId(
				entry).getBytes();

		final List<Mutation> mutations = new ArrayList<Mutation>();

		for (final ByteArrayId rowId : rowIds) {

			final Mutation mutation = new Mutation(
					new Text(
							dataId));
			mutation.putDelete(
					new Text(
							adapterId),
					new Text(
							rowId.getBytes()));

			mutations.add(mutation);
		}
		writer.write(mutations);
	}

	public static <T> void writeAltIndex(
			final WritableDataAdapter<T> writableAdapter,
			final DataStoreEntryInfo entryInfo,
			final T entry,
			final Writer writer ) {

		final byte[] adapterId = writableAdapter.getAdapterId().getBytes();
		final byte[] dataId = writableAdapter.getDataId(
				entry).getBytes();
		if ((dataId != null) && (dataId.length > 0)) {
			final List<Mutation> mutations = new ArrayList<Mutation>();

			for (final ByteArrayId rowId : entryInfo.getRowIds()) {

				final Mutation mutation = new Mutation(
						new Text(
								dataId));
				mutation.put(
						new Text(
								adapterId),
						new Text(
								rowId.getBytes()),
						new Value(
								"".getBytes(StringUtils.UTF8_CHAR_SET)));

				mutations.add(mutation);
			}
			writer.write(mutations);
		}
	}

	public static <T> List<Mutation> entryToMutations(
			final WritableDataAdapter<T> dataWriter,
			final Index index,
			final T entry,
			final VisibilityWriter<T> customFieldVisibilityWriter ) {
		final DataStoreEntryInfo ingestInfo = getIngestInfo(
				dataWriter,
				index,
				entry,
				customFieldVisibilityWriter);
		return buildMutations(
				dataWriter.getAdapterId().getBytes(),
				ingestInfo);
	}

	private static <T> List<Mutation> buildMutations(
			final byte[] adapterId,
			final DataStoreEntryInfo ingestInfo ) {
		final List<Mutation> mutations = new ArrayList<Mutation>();
		final List<FieldInfo> fieldInfoList = ingestInfo.getFieldInfo();
		for (final ByteArrayId rowId : ingestInfo.getRowIds()) {
			final Mutation mutation = new Mutation(
					new Text(
							rowId.getBytes()));
			for (final FieldInfo fieldInfo : fieldInfoList) {
				mutation.put(
						new Text(
								adapterId),
						new Text(
								fieldInfo.getDataValue().getId().getBytes()),
						new ColumnVisibility(
								fieldInfo.getVisibility()),
						new Value(
								fieldInfo.getWrittenValue()));
			}

			mutations.add(mutation);
		}
		return mutations;
	}

	/**
	 *
	 * @param dataWriter
	 * @param index
	 * @param entry
	 * @return List of zero or more matches
	 */
	public static <T> List<ByteArrayId> getRowIds(
			final WritableDataAdapter<T> dataWriter,
			final Index index,
			final T entry ) {
		final CommonIndexModel indexModel = index.getIndexModel();
		final AdapterPersistenceEncoding encodedData = dataWriter.encode(
				entry,
				indexModel);
		final List<ByteArrayId> insertionIds = encodedData.getInsertionIds(index);
		final List<ByteArrayId> rowIds = new ArrayList<ByteArrayId>(
				insertionIds.size());

		addToRowIds(
				rowIds,
				insertionIds,
				dataWriter.getDataId(
						entry).getBytes(),
				dataWriter.getAdapterId().getBytes(),
				encodedData.isDeduplicationEnabled());

		return rowIds;
	}

	private static <T> void addToRowIds(
			final List<ByteArrayId> rowIds,
			final List<ByteArrayId> insertionIds,
			final byte[] dataId,
			final byte[] adapterId,
			final boolean enableDeduplication ) {

		final int numberOfDuplicates = insertionIds.size() - 1;

		for (final ByteArrayId insertionId : insertionIds) {
			final byte[] indexId = insertionId.getBytes();
			// because the combination of the adapter ID and data ID
			// gaurantees uniqueness, we combine them in the row ID to
			// disambiguate index values that are the same, also adding
			// enough length values to be able to read the row ID again, we
			// lastly add a number of duplicates which can be useful as
			// metadata in our de-duplication
			// step
			rowIds.add(new ByteArrayId(
					new AccumuloRowId(
							indexId,
							dataId,
							adapterId,
							enableDeduplication ? numberOfDuplicates : -1).getRowId()));
		}
	}

	@SuppressWarnings({
		"rawtypes",
		"unchecked"
	})
	public static <T> DataStoreEntryInfo getIngestInfo(
			final WritableDataAdapter<T> dataWriter,
			final Index index,
			final T entry,
			final VisibilityWriter<T> customFieldVisibilityWriter ) {
		final CommonIndexModel indexModel;
		if (dataWriter instanceof ModelConvertingDataAdapter) {
			indexModel = ((ModelConvertingDataAdapter) dataWriter).convertModel(index.getIndexModel());
		}
		else {
			indexModel = index.getIndexModel();
		}

		final AdapterPersistenceEncoding encodedData = dataWriter.encode(
				entry,
				indexModel);
		final List<ByteArrayId> insertionIds = encodedData.getInsertionIds(index);
		final List<ByteArrayId> rowIds = new ArrayList<ByteArrayId>(
				insertionIds.size());
		final PersistentDataset extendedData = encodedData.getAdapterExtendedData();
		final PersistentDataset indexedData = encodedData.getCommonData();
		final List<PersistentValue> extendedValues = extendedData.getValues();
		final List<PersistentValue> commonValues = indexedData.getValues();

		final List<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>();

		if (!insertionIds.isEmpty()) {
			addToRowIds(
					rowIds,
					insertionIds,
					dataWriter.getDataId(
							entry).getBytes(),
					dataWriter.getAdapterId().getBytes(),
					encodedData.isDeduplicationEnabled());

			for (final PersistentValue fieldValue : commonValues) {
				final FieldInfo<T> fieldInfo = getFieldInfo(
						indexModel,
						fieldValue,
						entry,
						customFieldVisibilityWriter);
				if (fieldInfo != null) {
					fieldInfoList.add(fieldInfo);
				}
			}
			for (final PersistentValue fieldValue : extendedValues) {
				if (fieldValue.getValue() != null) {
					final FieldInfo<T> fieldInfo = getFieldInfo(
							dataWriter,
							fieldValue,
							entry,
							customFieldVisibilityWriter);
					if (fieldInfo != null) {
						fieldInfoList.add(fieldInfo);
					}
				}
			}
			return new DataStoreEntryInfo(
					rowIds,
					fieldInfoList);
		}
		LOGGER.warn("Indexing failed to produce insertion ids; entry [" + dataWriter.getDataId(
				entry).getString() + "] not saved.");
		return new DataStoreEntryInfo(
				Collections.EMPTY_LIST,
				Collections.EMPTY_LIST);

	}

	@SuppressWarnings({
		"rawtypes",
		"unchecked"
	})
	private static <T> FieldInfo<T> getFieldInfo(
			final DataWriter dataWriter,
			final PersistentValue<T> fieldValue,
			final T entry,
			final VisibilityWriter<T> customFieldVisibilityWriter ) {
		final FieldWriter fieldWriter = dataWriter.getWriter(fieldValue.getId());
		final FieldVisibilityHandler<T, Object> customVisibilityHandler = customFieldVisibilityWriter.getFieldVisibilityHandler(fieldValue.getId());
		if (fieldWriter != null) {
			final Object value = fieldValue.getValue();
			return new FieldInfo<T>(
					fieldValue,
					fieldWriter.writeField(value),
					merge(
							customVisibilityHandler.getVisibility(
									entry,
									fieldValue.getId(),
									value),
							fieldWriter.getVisibility(
									entry,
									fieldValue.getId(),
									value)));
		}
		else if (fieldValue.getValue() != null) {
			LOGGER.warn("Data writer of class " + dataWriter.getClass() + " does not support field for " + fieldValue.getValue());
		}
		return null;
	}

	@SuppressWarnings({
		"rawtypes",
		"unchecked"
	})
	private static <T> FieldInfo<T> getFieldInfo(
			final PersistentValue<T> fieldValue,
			final byte[] value,
			final byte[] visibility ) {
		return new FieldInfo<T>(
				fieldValue,
				value,
				visibility);
	}

	private static final byte[] BEG_AND_BYTE = "&".getBytes(StringUtils.UTF8_CHAR_SET);
	private static final byte[] END_AND_BYTE = ")".getBytes(StringUtils.UTF8_CHAR_SET);

	private static byte[] merge(
			final byte vis1[],
			final byte vis2[] ) {
		if ((vis1 == null) || (vis1.length == 0)) {
			return vis2;
		}
		else if ((vis2 == null) || (vis2.length == 0)) {
			return vis1;
		}

		final ByteBuffer buffer = ByteBuffer.allocate(vis1.length + 3 + vis2.length);
		buffer.putChar('(');
		buffer.put(vis1);
		buffer.putChar(')');
		buffer.put(BEG_AND_BYTE);
		buffer.put(vis2);
		buffer.put(END_AND_BYTE);
		return buffer.array();
	}

	/**
	 * Get Namespaces
	 *
	 * @param connector
	 */
	public static List<String> getNamespaces(
			final Connector connector ) {
		final List<String> namespaces = new ArrayList<String>();

		for (final String table : connector.tableOperations().list()) {
			final int idx = table.indexOf(AbstractAccumuloPersistence.METADATA_TABLE) - 1;
			if (idx > 0) {
				namespaces.add(table.substring(
						0,
						idx));
			}
		}
		return namespaces;
	}

	/**
	 * Get list of data adapters associated with the given namespace
	 *
	 * @param connector
	 * @param namespace
	 */
	public static List<DataAdapter<?>> getDataAdapters(
			final Connector connector,
			final String namespace ) {
		final List<DataAdapter<?>> adapters = new ArrayList<DataAdapter<?>>();

		final AdapterStore adapterStore = new AccumuloAdapterStore(
				new BasicAccumuloOperations(
						connector,
						namespace));

		final Iterator<DataAdapter<?>> itr = adapterStore.getAdapters();

		while (itr.hasNext()) {
			adapters.add(itr.next());
		}

		return adapters;
	}

	/**
	 * Get list of indices associated with the given namespace
	 *
	 * @param connector
	 * @param namespace
	 */
	public static List<Index> getIndices(
			final Connector connector,
			final String namespace ) {
		final List<Index> indices = new ArrayList<Index>();

		final IndexStore indexStore = new AccumuloIndexStore(
				new BasicAccumuloOperations(
						connector,
						namespace));

		final Iterator<Index> itr = indexStore.getIndices();

		while (itr.hasNext()) {
			indices.add(itr.next());
		}

		return indices;
	}

	/**
	 * Set splits on a table based on quantile distribution and fixed number of
	 * splits
	 *
	 * @param namespace
	 * @param index
	 * @param quantile
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 * @throws TableNotFoundException
	 */
	public static void setSplitsByQuantile(
			final Connector connector,
			final String namespace,
			final Index index,
			final int quantile )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		final SortedSet<Text> splits = new TreeSet<Text>();

		final CloseableIterator<Entry<Key, Value>> iterator = getIterator(
				connector,
				namespace,
				index);

		if (iterator == null) {
			LOGGER.error("could not get iterator instance, getIterator returned null");
			throw new IOException(
					"could not get iterator instance, getIterator returned null");
		}

		final int numberSplits = quantile - 1;
		BigInteger min = null;
		BigInteger max = null;

		while (iterator.hasNext()) {
			final Entry<Key, Value> entry = iterator.next();
			final byte[] bytes = entry.getKey().getRow().getBytes();
			final BigInteger value = new BigInteger(
					bytes);
			if ((min == null) || (max == null)) {
				min = value;
				max = value;
			}
			min = min.min(value);
			max = max.max(value);
		}

		final BigDecimal dMax = new BigDecimal(
				max);
		final BigDecimal dMin = new BigDecimal(
				min);
		BigDecimal delta = dMax.subtract(dMin);
		delta = delta.divideToIntegralValue(new BigDecimal(
				quantile));

		for (int ii = 1; ii <= numberSplits; ii++) {
			final BigDecimal temp = delta.multiply(BigDecimal.valueOf(ii));
			final BigInteger value = min.add(temp.toBigInteger());

			final Text split = new Text(
					value.toByteArray());
			splits.add(split);
		}

		final String tableName = AccumuloUtils.getQualifiedTableName(
				namespace,
				StringUtils.stringFromBinary(index.getId().getBytes()));
		connector.tableOperations().addSplits(
				tableName,
				splits);
		connector.tableOperations().compact(
				tableName,
				null,
				null,
				true,
				true);
	}

	/**
	 * Set splits on table based on equal interval distribution and fixed number
	 * of splits.
	 *
	 * @param namespace
	 * @param index
	 * @param numberSplits
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 * @throws TableNotFoundException
	 */
	public static void setSplitsByNumSplits(
			final Connector connector,
			final String namespace,
			final Index index,
			final int numberSplits )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		final long count = getEntries(
				connector,
				namespace,
				index);

		final CloseableIterator<Entry<Key, Value>> iterator = getIterator(
				connector,
				namespace,
				index);

		if (iterator == null) {
			LOGGER.error("Could not get iterator instance, getIterator returned null");
			throw new IOException(
					"Could not get iterator instance, getIterator returned null");
		}

		long ii = 0;
		final long splitInterval = count / numberSplits;
		final SortedSet<Text> splits = new TreeSet<Text>();
		while (iterator.hasNext()) {
			final Entry<Key, Value> entry = iterator.next();
			ii++;
			if (ii >= splitInterval) {
				ii = 0;
				splits.add(entry.getKey().getRow());
			}
		}

		final String tableName = AccumuloUtils.getQualifiedTableName(
				namespace,
				StringUtils.stringFromBinary(index.getId().getBytes()));
		connector.tableOperations().addSplits(
				tableName,
				splits);
		connector.tableOperations().compact(
				tableName,
				null,
				null,
				true,
				true);
	}

	/**
	 * Set splits on table based on fixed number of rows per split.
	 *
	 * @param namespace
	 * @param index
	 * @param numberRows
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 * @throws TableNotFoundException
	 */
	public static void setSplitsByNumRows(
			final Connector connector,
			final String namespace,
			final Index index,
			final long numberRows )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		final CloseableIterator<Entry<Key, Value>> iterator = getIterator(
				connector,
				namespace,
				index);

		if (iterator == null) {
			LOGGER.error("Unable to get iterator instance, getIterator returned null");
			throw new IOException(
					"Unable to get iterator instance, getIterator returned null");
		}

		long ii = 0;
		final SortedSet<Text> splits = new TreeSet<Text>();
		while (iterator.hasNext()) {
			final Entry<Key, Value> entry = iterator.next();
			ii++;
			if (ii >= numberRows) {
				ii = 0;
				splits.add(entry.getKey().getRow());
			}
		}

		final String tableName = AccumuloUtils.getQualifiedTableName(
				namespace,
				StringUtils.stringFromBinary(index.getId().getBytes()));
		connector.tableOperations().addSplits(
				tableName,
				splits);
		connector.tableOperations().compact(
				tableName,
				null,
				null,
				true,
				true);
	}

	/**
	 * Check if locality group is set.
	 *
	 * @param namespace
	 * @param index
	 * @param adapter
	 * @return
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 * @throws TableNotFoundException
	 */
	public static boolean isLocalityGroupSet(
			final Connector connector,
			final String namespace,
			final Index index,
			final DataAdapter<?> adapter )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		final AccumuloOperations operations = new BasicAccumuloOperations(
				connector,
				namespace);
		// get unqualified table name
		final String tableName = StringUtils.stringFromBinary(index.getId().getBytes());
		return operations.localityGroupExists(
				tableName,
				adapter.getAdapterId().getBytes());
	}

	/**
	 * Set locality group.
	 *
	 * @param namespace
	 * @param index
	 * @param adapter
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 * @throws TableNotFoundException
	 */
	public static void setLocalityGroup(
			final Connector connector,
			final String namespace,
			final Index index,
			final DataAdapter<?> adapter )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		final AccumuloOperations operations = new BasicAccumuloOperations(
				connector,
				namespace);
		// get unqualified table name
		final String tableName = StringUtils.stringFromBinary(index.getId().getBytes());
		operations.addLocalityGroup(
				tableName,
				adapter.getAdapterId().getBytes());
	}

	/**
	 * Get number of entries for a data adapter in an index.
	 *
	 * @param namespace
	 * @param index
	 * @param adapter
	 * @return
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 */
	public static long getEntries(
			final Connector connector,
			final String namespace,
			final Index index,
			final DataAdapter<?> adapter )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException {
		long counter = 0L;
		final AccumuloOperations operations = new BasicAccumuloOperations(
				connector,
				namespace);
		final AccumuloIndexStore indexStore = new AccumuloIndexStore(
				operations);
		final AccumuloAdapterStore adapterStore = new AccumuloAdapterStore(
				operations);
		if (indexStore.indexExists(index.getId()) && adapterStore.adapterExists(adapter.getAdapterId())) {
			final List<ByteArrayId> adapterIds = new ArrayList<ByteArrayId>();
			adapterIds.add(adapter.getAdapterId());
			final AccumuloConstraintsQuery accumuloQuery = new AccumuloConstraintsQuery(
					adapterIds,
					index);
			final CloseableIterator<?> iterator = accumuloQuery.query(
					operations,
					new AccumuloAdapterStore(
							operations),
					null);
			while (iterator.hasNext()) {
				counter++;
				iterator.next();
			}
			iterator.close();
		}
		return counter;
	}

	/**
	 * Get number of entries per index.
	 *
	 * @param namespace
	 * @param index
	 * @return
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 */
	public static long getEntries(
			final Connector connector,
			final String namespace,
			final Index index )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException {
		long counter = 0L;
		final AccumuloOperations operations = new BasicAccumuloOperations(
				connector,
				namespace);
		final AccumuloIndexStore indexStore = new AccumuloIndexStore(
				operations);
		if (indexStore.indexExists(index.getId())) {
			final AccumuloConstraintsQuery accumuloQuery = new AccumuloConstraintsQuery(
					index);
			final CloseableIterator<?> iterator = accumuloQuery.query(
					operations,
					new AccumuloAdapterStore(
							operations),
					null);
			while (iterator.hasNext()) {
				counter++;
				iterator.next();
			}
			iterator.close();
		}
		return counter;
	}

	/**
	 * Get number of entries per namespace.
	 *
	 * @param namespace
	 * @return
	 * @throws AccumuloException
	 * @throws AccumuloSecurityException
	 * @throws IOException
	 */
	public static long getEntries(
			final Connector connector,
			final String namespace )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException {
		long counter = 0L;
		final AccumuloDataStore dataStore = new AccumuloDataStore(
				new BasicAccumuloOperations(
						connector,
						namespace));
		if (dataStore != null) {
			final CloseableIterator<?> iterator = dataStore.query((Query) null);
			while (iterator.hasNext()) {
				counter++;
				iterator.next();
			}
			iterator.close();
		}
		return counter;
	}

	private static CloseableIterator<Entry<Key, Value>> getIterator(
			final Connector connector,
			final String namespace,
			final Index index )
			throws AccumuloException,
			AccumuloSecurityException,
			IOException,
			TableNotFoundException {
		CloseableIterator<Entry<Key, Value>> iterator = null;
		final AccumuloOperations operations = new BasicAccumuloOperations(
				connector);
		final AccumuloIndexStore indexStore = new AccumuloIndexStore(
				operations);
		final AccumuloAdapterStore adapterStore = new AccumuloAdapterStore(
				operations);

		if (indexStore.indexExists(index.getId())) {
			final String tableName = StringUtils.stringFromBinary(index.getId().getBytes());
			final ScannerBase scanner = operations.createBatchScanner(tableName);
			((BatchScanner) scanner).setRanges(AccumuloUtils.byteArrayRangesToAccumuloRanges(null));

			final IteratorSetting iteratorSettings = new IteratorSetting(
					10,
					"GEOWAVE_WHOLE_ROW_ITERATOR",
					WholeRowIterator.class);
			scanner.addScanIterator(iteratorSettings);

			final List<QueryFilter> clientFilters = new ArrayList<QueryFilter>();
			clientFilters.add(
					0,
					new DedupeFilter());

			final Iterator<Entry<Key, Value>> it = new IteratorWrapper(
					adapterStore,
					index,
					scanner.iterator(),
					new FilterList<QueryFilter>(
							clientFilters));

			iterator = new CloseableIteratorWrapper<Entry<Key, Value>>(
					new ScannerClosableWrapper(
							scanner),
					it);
		}
		return iterator;
	}

	private static class IteratorWrapper implements
			Iterator<Entry<Key, Value>>
	{

		private final Iterator<Entry<Key, Value>> scannerIt;
		private final AdapterStore adapterStore;
		private final Index index;
		private final QueryFilter clientFilter;
		private Entry<Key, Value> nextValue;

		public IteratorWrapper(
				final AdapterStore adapterStore,
				final Index index,
				final Iterator<Entry<Key, Value>> scannerIt,
				final QueryFilter clientFilter ) {
			this.adapterStore = adapterStore;
			this.index = index;
			this.scannerIt = scannerIt;
			this.clientFilter = clientFilter;
			findNext();
		}

		private void findNext() {
			while (scannerIt.hasNext()) {
				final Entry<Key, Value> row = scannerIt.next();
				final Object decodedValue = decodeRow(
						row,
						clientFilter,
						index);
				if (decodedValue != null) {
					nextValue = row;
					return;
				}
			}
			nextValue = null;
		}

		private Object decodeRow(
				final Entry<Key, Value> row,
				final QueryFilter clientFilter,
				final Index index ) {
			return AccumuloUtils.decodeRow(
					row.getKey(),
					row.getValue(),
					new AccumuloRowId(
							row.getKey()), // need to pass this, otherwise null
											// value for rowId gets dereferenced
											// later
					adapterStore,
					clientFilter,
					index);
		}

		@Override
		public boolean hasNext() {
			return nextValue != null;
		}

		@Override
		public Entry<Key, Value> next() {
			final Entry<Key, Value> previousNext = nextValue;
			findNext();
			return previousNext;
		}

		@Override
		public void remove() {}
	}
}


text:
package scala
package collection
package mutable

/** `ReusableBuilder` is a marker trait that indicates that a `Builder`
  *  can be reused to build more than one instance of a collection.  In
  *  particular, calling `result()` followed by `clear()` will produce a
  *  collection and reset the builder to begin building a new collection
  *  of the same type.
  *
  *  In general no method other than `clear()` may be called after `result()`.
  *  It is up to subclasses to implement and to document other allowed sequences
  *  of operations (e.g. calling other methods after `result()` in order to obtain
  *  different snapshots of a collection under construction).
  *
  *  @tparam  Elem  the type of elements that get added to the builder.
  *  @tparam  To    the type of collection that it produced.
  *
  *  @define multipleResults
  *
  *     This Builder can be reused after calling `result()` without an
  *     intermediate call to `clear()` in order to build multiple related results.
  */
trait ReusableBuilder[-Elem, +To] extends Builder[Elem, To] {
  /** Clears the contents of this builder.
    *  After execution of this method, the builder will contain no elements.
    *
    *  If executed immediately after a call to `result()`, this allows a new
    *  instance of the same type of collection to be built.
    */
  override def clear(): Unit    // Note: overriding for Scaladoc only!

  /** Produces a collection from the added elements.
    *
    *  After a call to `result`, the behavior of all other methods is undefined
    *  save for `clear()`.  If `clear()` is called, then the builder is reset and
    *  may be used to build another instance.
    *
    *  @return a collection containing the elements added to this builder.
    */
  override def result(): To    // Note: overriding for Scaladoc only!
}

redpajama_set_name: RedPajamaGithub


text:
<?php

// Disallow direct access to this file
defined('_JEXEC') or die('Restricted access');

?>

	<form action="index.php?option=com_community" method="post" name="adminForm" id="adminForm">

				<?php echo JText::_('COM_COMMUNITY_NUMBER'); ?>
				<input type="checkbox" name="toggle" value="" onclick="Joomla.checkAll(this)" />

					<?php echo JHTML::_('grid.sort',   JText::_('COM_COMMUNITY_NAME') , 'name', $this->lists['order_Dir'], $this->lists['order'] ); ?>

					<?php echo JText::_('COM_COMMUNITY_PARENT'); ?>

					<?php echo JText::_('COM_COMMUNITY_CATEGORY_DESCRIPTION'); ?>

					<?php echo JHTML::_('grid.sort',   JText::_('COM_COMMUNITY_GROUPS'), 'groups', $this->lists['order_Dir'], $this->lists['order'] ); ?>

					<?php echo JHTML::_('grid.sort',   JText::_('COM_COMMUNITY_GROUPS_MEMBER_S'), 'members', $this->lists['order_Dir'], $this->lists['order'] ); ?>

					<?php echo JHTML::_('grid.sort',   JText::_('ID'), 'id', $this->lists['order_Dir'], $this->lists['order'] ); ?>

<?php
		$i		= 0;

		foreach($this->categories as $category)
		{
?>

				<?php echo $i + 1; ?>
				<?php echo JHTML::_('grid.id', $i++, $category->id); ?>

					<?php echo JHTML::_('link', 'javascript:void(0);', $category->name, array('id' => 'group-title-' . $category->id , 'onclick'=>'azcommunity.editGroupCategory(\'' . $category->id . '\',\'' . JText::_('COM_COMMUNITY_CATEGORY_EDIT') . '\');')); ?>

				<?php echo $category->pname; ?>
				<td id="group-description-<?php echo $category->id; ?>">
					<?php echo $category->description;?>

					<a href="index.php?option=com_community&view=groups&category=<?php echo $category->id;?>">
						<?php echo $category->groupscount; ?>

				<?php echo $category->memberscount; ?>
				<?php echo $category->id; ?>

<?php
		}
?>

				<?php echo $this->pagination->getListFooter(); ?>

	<input type="hidden" name="view" value="groupcategories" />
	<input type="hidden" name="option" value="com_community" />
	<input type="hidden" name="task" value="groupcategories" />
	<input type="hidden" name="boxchecked" value="0" />
	<input type="hidden" name="filter_order" value="<?php echo $this->lists['order']; ?>" />
	<input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']; ?>" />
	</form>


text:
- Added to the **servicenow-update-ticket*** and ***servicenow-create-ticket*** commands the arguments: *reassignment_count*, *reopen_count*, *sys_updated_by* and *sys_updated_on*.
- Removed the arguments *display* and *escalation* from the ***servicenow-update-ticket*** and ***servicenow-create-ticket*** commands, as they are not supported in the API.
- Added the mentioned ticket fields in the arguments given to the ***servicenow-update-ticket*** and ***servicenow-create-ticket*** commands to the context data.
- Updated the Docker image to: *demisto/python3:3.9.1.14969*.

##### ServiceNow CMDB
- Updated the Docker image to: *demisto/python3:3.9.1.14969*.

#### Scripts
##### ServiceNowIncidentStatus
- Updated the Docker image to: *demisto/python3:3.9.1.14969*.


text:
package com.android.inputmethod.compat;

import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public final class CompatUtils {
    private static final String TAG = CompatUtils.class.getSimpleName();

    private CompatUtils() {
        // This utility class is not publicly instantiable.
    }

    public static Class<?> getClass(final String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

    public static Method getMethod(final Class<?> targetClass, final String name,
            final Class<?>... parameterTypes) {
        if (targetClass == null || TextUtils.isEmpty(name)) return null;
        try {
            return targetClass.getMethod(name, parameterTypes);
        } catch (SecurityException e) {
            // ignore
        } catch (NoSuchMethodException e) {
            // ignore
        }
        return null;
    }

    public static Field getField(final Class<?> targetClass, final String name) {
        if (targetClass == null || TextUtils.isEmpty(name)) return null;
        try {
            return targetClass.getField(name);
        } catch (SecurityException e) {
            // ignore
        } catch (NoSuchFieldException e) {
            // ignore
        }
        return null;
    }

    public static Constructor<?> getConstructor(final Class<?> targetClass,
            final Class<?> ... types) {
        if (targetClass == null || types == null) return null;
        try {
            return targetClass.getConstructor(types);
        } catch (SecurityException e) {
            // ignore
        } catch (NoSuchMethodException e) {
            // ignore
        }
        return null;
    }

    public static Object newInstance(final Constructor<?> constructor, final Object ... args) {
        if (constructor == null) return null;
        try {
            return constructor.newInstance(args);
        } catch (Exception e) {
            Log.e(TAG, "Exception in newInstance", e);
        }
        return null;
    }

    public static Object invoke(final Object receiver, final Object defaultValue,
            final Method method, final Object... args) {
        if (method == null) return defaultValue;
        try {
            return method.invoke(receiver, args);
        } catch (Exception e) {
            Log.e(TAG, "Exception in invoke", e);
        }
        return defaultValue;
    }

    public static Object getFieldValue(final Object receiver, final Object defaultValue,
            final Field field) {
        if (field == null) return defaultValue;
        try {
            return field.get(receiver);
        } catch (Exception e) {
            Log.e(TAG, "Exception in getFieldValue", e);
        }
        return defaultValue;
    }

    public static void setFieldValue(final Object receiver, final Field field, final Object value) {
        if (field == null) return;
        try {
            field.set(receiver, value);
        } catch (Exception e) {
            Log.e(TAG, "Exception in setFieldValue", e);
        }
    }
}


text:
package renaro.tinderlikesample.profile.dao;

import java.util.List;

import renaro.tinderlikesample.UserProfile;

/**
 * Created by renarosantos on 21/02/17.
 */
public abstract class ProfileDAO {

    public abstract List<UserProfile> fetchProfiles();

    public abstract int fetchRemainingVotes();

    public abstract boolean voteProfile(final UserProfile profile, final boolean vote);
}


text:
<?php
/**
 * ActivityTypeModel
 *
 * PHP version 5
 *
 * @category Class
 * @package  BumbalClient
 * @author   Swaagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Bumbal Client Api
 *
 * Bumbal API documentation
 *
 * OpenAPI spec version: 2.0
 * Contact: gerb@bumbal.eu
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace BumbalClient\Model;

use \ArrayAccess;

/**
 * ActivityTypeModel Class Doc Comment
 *
 * @category    Class
 * @package     BumbalClient
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class ActivityTypeModel implements ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      * @var string
      */
    protected static $swaggerModelName = 'ActivityTypeModel';

    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerTypes = [
        'id' => 'int',
        'name' => 'string'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerFormats = [
        'id' => 'int64',
        'name' => null
    ];

    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name, and the value is the original name
     * @var string[]
     */
    protected static $attributeMap = [
        'id' => 'id',
        'name' => 'name'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     * @var string[]
     */
    protected static $setters = [
        'id' => 'setId',
        'name' => 'setName'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     * @var string[]
     */
    protected static $getters = [
        'id' => 'getId',
        'name' => 'getName'
    ];

    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    public static function setters()
    {
        return self::$setters;
    }

    public static function getters()
    {
        return self::$getters;
    }

    const ID_1 = 1;
    const ID_2 = 2;
    const ID_3 = 3;
    const ID_4 = 4;
    const ID_5 = 5;
    const ID_6 = 6;
    const ID_9 = 9;
    const ID_10 = 10;
    const ID_11 = 11;
    const ID_13 = 13;
    const ID_14 = 14;
    const ID_15 = 15;
    const ID_16 = 16;
    const ID_17 = 17;
    const ID_18 = 18;
    const ID_19 = 19;
    const ID_20 = 20;
    const ID_21 = 21;
    const ID_26 = 26;
    const ID_27 = 27;
    const ID_28 = 28;
    const ID_29 = 29;
    const ID_30 = 30;
    const ID_31 = 31;
    const ID_32 = 32;
    const NAME_BREAKDOWN = 'breakdown';
    const NAME_BUNDLED = 'bundled';
    const NAME_CAR_END = 'car_end';
    const NAME_CAR_START = 'car_start';
    const NAME_CAR_WASH = 'car_wash';
    const NAME_COMBI = 'combi';
    const NAME_DEPOT = 'depot';
    const NAME_DRIVER_END = 'driver_end';
    const NAME_DRIVER_START = 'driver_start';
    const NAME_DROPOFF = 'dropoff';
    const NAME_GAS_REFILL = 'gas_refill';
    const NAME_INTERIOR_WASH = 'interior_wash';
    const NAME_MAINTENANCE = 'maintenance';
    const NAME_MAINTENANCE_PLANNED = 'maintenance_planned';
    const NAME_MAINTENANCE_UNPLANNED = 'maintenance_unplanned';
    const NAME_OTHER = 'other';
    const NAME_PAUSE = 'pause';
    const NAME_PICKUP = 'pickup';
    const NAME_ROUTE_END = 'route_end';
    const NAME_ROUTE_START = 'route_start';
    const NAME_SANITARY = 'sanitary';
    const NAME_STOP = 'stop';
    const NAME_UNPLANNED_STOP = 'unplanned_stop';
    const NAME_USER_OTHER = 'user_other';
    const NAME_WAIT = 'wait';

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public function getIdAllowableValues()
    {
        return [
            self::ID_1,
            self::ID_2,
            self::ID_3,
            self::ID_4,
            self::ID_5,
            self::ID_6,
            self::ID_9,
            self::ID_10,
            self::ID_11,
            self::ID_13,
            self::ID_14,
            self::ID_15,
            self::ID_16,
            self::ID_17,
            self::ID_18,
            self::ID_19,
            self::ID_20,
            self::ID_21,
            self::ID_26,
            self::ID_27,
            self::ID_28,
            self::ID_29,
            self::ID_30,
            self::ID_31,
            self::ID_32,
        ];
    }

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public function getNameAllowableValues()
    {
        return [
            self::NAME_BREAKDOWN,
            self::NAME_BUNDLED,
            self::NAME_CAR_END,
            self::NAME_CAR_START,
            self::NAME_CAR_WASH,
            self::NAME_COMBI,
            self::NAME_DEPOT,
            self::NAME_DRIVER_END,
            self::NAME_DRIVER_START,
            self::NAME_DROPOFF,
            self::NAME_GAS_REFILL,
            self::NAME_INTERIOR_WASH,
            self::NAME_MAINTENANCE,
            self::NAME_MAINTENANCE_PLANNED,
            self::NAME_MAINTENANCE_UNPLANNED,
            self::NAME_OTHER,
            self::NAME_PAUSE,
            self::NAME_PICKUP,
            self::NAME_ROUTE_END,
            self::NAME_ROUTE_START,
            self::NAME_SANITARY,
            self::NAME_STOP,
            self::NAME_UNPLANNED_STOP,
            self::NAME_USER_OTHER,
            self::NAME_WAIT,
        ];
    }

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     * @param mixed[] $data Associated array of property values initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['id'] = isset($data['id']) ? $data['id'] : null;
        $this->container['name'] = isset($data['name']) ? $data['name'] : null;
    }

    /**
     * show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalid_properties = [];

        $allowed_values = $this->getIdAllowableValues();
        if (!in_array($this->container['id'], $allowed_values)) {
            $invalid_properties[] = sprintf(
                "invalid value for 'id', must be one of '%s'",
                implode("', '", $allowed_values)
            );
        }

        $allowed_values = $this->getNameAllowableValues();
        if (!in_array($this->container['name'], $allowed_values)) {
            $invalid_properties[] = sprintf(
                "invalid value for 'name', must be one of '%s'",
                implode("', '", $allowed_values)
            );
        }

        return $invalid_properties;
    }

    /**
     * validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {

        $allowed_values = $this->getIdAllowableValues();
        if (!in_array($this->container['id'], $allowed_values)) {
            return false;
        }
        $allowed_values = $this->getNameAllowableValues();
        if (!in_array($this->container['name'], $allowed_values)) {
            return false;
        }
        return true;
    }

    /**
     * Gets id
     * @return int
     */
    public function getId()
    {
        return $this->container['id'];
    }

    /**
     * Sets id
     * @param int $id Unique Activity type ID. 1 (:pickup), 2 (:dropoff), 3 (:route_start), 4 (:route_end), 5 (:car_start), 6 (:car_end), 9 (:driver_start), 10 (:driver_end), 11 (:stop), 13 (:pause), 14 (:gas_refill), 15 (:maintenance_planned), 16 (:maintenance_unplanned), 17 (:user_other), 18 (:unplanned_stop), 19 (:wait), 20 (:breakdown), 21 (:sanitary), 26 (:maintenance), 27 (:car_wash), 28 (:depot), 29 (:combi), 30 (:interior_wash), 31 (:other), 32 (:bundled)
     * @return $this
     */
    public function setId($id)
    {
        $allowed_values = $this->getIdAllowableValues();
        if (!is_null($id) && !in_array($id, $allowed_values)) {
            throw new \InvalidArgumentException(
                sprintf(
                    "Invalid value for 'id', must be one of '%s'",
                    implode("', '", $allowed_values)
                )
            );
        }
        $this->container['id'] = $id;

        return $this;
    }

    /**
     * Gets name
     * @return string
     */
    public function getName()
    {
        return $this->container['name'];
    }

    /**
     * Sets name
     * @param string $name Activity Type Name. breakdown (:20), bundled (:32), car_end (:6), car_start (:5), car_wash (:27), combi (:29), depot (:28), driver_end (:10), driver_start (:9), dropoff (:2), gas_refill (:14), interior_wash (:30), maintenance (:26), maintenance_planned (:15), maintenance_unplanned (:16), other (:31), pause (:13), pickup (:1), route_end (:4), route_start (:3), sanitary (:21), stop (:11), unplanned_stop (:18), user_other (:17), wait (:19)
     * @return $this
     */
    public function setName($name)
    {
        $allowed_values = $this->getNameAllowableValues();
        if (!is_null($name) && !in_array($name, $allowed_values)) {
            throw new \InvalidArgumentException(
                sprintf(
                    "Invalid value for 'name', must be one of '%s'",
                    implode("', '", $allowed_values)
                )
            );
        }
        $this->container['name'] = $name;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
        }

        return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
static const SkScalar kTabCapWidth = 15;
static const SkScalar kTabTopCurveWidth = 4;
static const SkScalar kTabBottomCurveWidth = 3;

// Space between the edges of the tab's bounds and its content.
static const int kLeftPadding = 16;
static const int kTopPadding = 6;
static const int kRightPadding = 15;
static const int kBottomPadding = 5;

// The height of the "drop shadow" drawn across the top of the tab. We allow
// the containing window to consider this region part of the window caption
// rather than the tab, since we are otherwise starved for drag area.
static const int kDropShadowHeight = 2;

// By how much the bottom edge of the tab overlaps the top of the toolbar.
static const int kToolbarOverlap = 1;

// The space between the tab icon and the title.
static const int kIconTitleSpacing = 4;

// The space between the tab title and the close button.
static const int kTitleCloseButtonSpacing = 5;

// The ideal width of a tab, provided sufficient width is available.
static const int kStandardTitleWidth = 175;

// TODO(beng): figure out what these are used for.
static const int kCloseButtonVertFuzz = 0;
static const int kCloseButtonHorzFuzz = 5;

// The size (both width and height) of the tab icon.
static const int kIconSize = 16;

// The color of the text painted in tabs.
static const int kSelectedTitleColor = SK_ColorBLACK;

// How long the hover state takes.
static const int kHoverDurationMs = 90;

// How long the pulse throb takes.
static const int kPulseDurationMs = 200;

// How opaque to make the hover state (out of 1).
static const double kHoverOpacity = 0.33;

// Resources for rendering tabs.
static gfx::Font* title_font = NULL;
static int title_font_height = 0;
static SkBitmap* close_button_n = NULL;
static SkBitmap* close_button_h = NULL;
static SkBitmap* close_button_p = NULL;
static int close_button_height = 0;
static int close_button_width = 0;

static SkBitmap* waiting_animation_frames = NULL;
static SkBitmap* loading_animation_frames = NULL;
static SkBitmap* crashed_icon = NULL;
static int loading_animation_frame_count = 0;
static int waiting_animation_frame_count = 0;
static int waiting_to_loading_frame_count_ratio = 0;

Tab2::TabImage Tab2::tab_alpha_ = {0};
Tab2::TabImage Tab2::tab_active_ = {0};
Tab2::TabImage Tab2::tab_inactive_ = {0};

namespace {

////////////////////////////////////////////////////////////////////////////////
// TabCloseButton
//
//  This is a Button subclass that causes middle clicks to be forwarded to the
//  parent View by explicitly not handling them in OnMousePressed.
class TabCloseButton : public views::ImageButton {
 public:
  explicit TabCloseButton(views::ButtonListener* listener)
      : views::ImageButton(listener) {
  }
  virtual ~TabCloseButton() {}

  virtual bool OnMousePressed(const views::MouseEvent& event) {
    bool handled = ImageButton::OnMousePressed(event);
    // Explicitly mark midle-mouse clicks as non-handled to ensure the tab
    // sees them.
    return event.IsOnlyMiddleMouseButton() ? false : handled;
  }

  // We need to let the parent know about mouse state so that it
  // can highlight itself appropriately. Note that Exit events
  // fire before Enter events, so this works.
  virtual void OnMouseEntered(const views::MouseEvent& event) {
    ImageButton::OnMouseEntered(event);
    GetParent()->OnMouseEntered(event);
  }

  virtual void OnMouseExited(const views::MouseEvent& event) {
    ImageButton::OnMouseExited(event);
    GetParent()->OnMouseExited(event);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TabCloseButton);
};

void InitResources() {
  static bool initialized = false;
  if (!initialized) {
    // TODO(glen): Allow theming of these.
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));
    title_font_height = title_font->height();

    close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);
    close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);
    close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);
    close_button_width = close_button_n->width();
    close_button_height = close_button_n->height();

    Tab2::LoadTabImages();

    // The loading animation image is a strip of states. Each state must be
    // square, so the height must divide the width evenly.
    loading_animation_frames = rb.GetBitmapNamed(IDR_THROBBER);
    DCHECK(loading_animation_frames);
    DCHECK(loading_animation_frames->width() %
           loading_animation_frames->height() == 0);
    loading_animation_frame_count =
        loading_animation_frames->width() / loading_animation_frames->height();

    waiting_animation_frames = rb.GetBitmapNamed(IDR_THROBBER_WAITING);
    DCHECK(waiting_animation_frames);
    DCHECK(waiting_animation_frames->width() %
           waiting_animation_frames->height() == 0);
    waiting_animation_frame_count =
        waiting_animation_frames->width() / waiting_animation_frames->height();

    waiting_to_loading_frame_count_ratio =
        waiting_animation_frame_count / loading_animation_frame_count;

    crashed_icon = rb.GetBitmapNamed(IDR_SAD_FAVICON);

    initialized = true;
  }
}

int GetContentHeight() {
  // The height of the content of the Tab is the largest of the icon,
  // the title text and the close button graphic.
  int content_height = std::max(kIconSize, title_font_height);
  return std::max(content_height, close_button_height);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// Tab2, public:

Tab2::Tab2(Tab2Model* model)
    : model_(model),
      dragging_(false),
      removing_(false) {
  InitResources();

  // Add the Close Button.
  close_button_ = new TabCloseButton(this);
  close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);
  close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);
  close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);
  AddChildView(close_button_);

  hover_animation_.reset(new SlideAnimation(this));
  hover_animation_->SetSlideDuration(kHoverDurationMs);

  pulse_animation_.reset(new ThrobAnimation(this));
  pulse_animation_->SetSlideDuration(kPulseDurationMs);
}

Tab2::~Tab2() {
}

void Tab2::SetRemovingModel(Tab2Model* model) {
  removing_model_.reset(model);
  model_ = removing_model_.get();
}

bool Tab2::IsAnimating() const {
  return animator_.get() && animator_->IsAnimating();
}

views::Animator* Tab2::GetAnimator() {
  if (!animator_.get())
    animator_.reset(new views::Animator(this, model_->AsAnimatorDelegate()));
  return animator_.get();
}

// static
gfx::Size Tab2::GetMinimumUnselectedSize() {
  InitResources();

  gfx::Size minimum_size;
  minimum_size.set_width(kLeftPadding + kRightPadding);
  // Since we use bitmap images, the real minimum height of the image is
  // defined most accurately by the height of the end cap images.
  minimum_size.set_height(tab_active_.image_l->height());
  return minimum_size;
}

// static
gfx::Size Tab2::GetMinimumSelectedSize() {
  gfx::Size minimum_size = GetMinimumUnselectedSize();
  minimum_size.set_width(kLeftPadding + kIconSize + kRightPadding);
  return minimum_size;
}

// static
gfx::Size Tab2::GetStandardSize() {
  gfx::Size standard_size = GetMinimumUnselectedSize();
  standard_size.set_width(
      standard_size.width() + kIconTitleSpacing + kStandardTitleWidth);
  return standard_size;
}

void Tab2::AddTabShapeToPath(gfx::Path* path) const {
  SkScalar h = SkIntToScalar(height());
  SkScalar w = SkIntToScalar(width());

  path->moveTo(0, h);

  // Left end cap.
  path->lineTo(kTabBottomCurveWidth, h - kTabBottomCurveWidth);
  path->lineTo(kTabCapWidth - kTabTopCurveWidth, kTabTopCurveWidth);
  path->lineTo(kTabCapWidth, 0);

  // Connect to the right cap.
  path->lineTo(w - kTabCapWidth, 0);

  // Right end cap.
  path->lineTo(w - kTabCapWidth + kTabTopCurveWidth, kTabTopCurveWidth);
  path->lineTo(w - kTabBottomCurveWidth, h - kTabBottomCurveWidth);
  path->lineTo(w, h);

  // Close out the path.
  path->lineTo(0, h);
  path->close();
}

///////////////////////////////////////////////////////////////////////////////
// Tab2, views::ButtonListener implementation:

void Tab2::ButtonPressed(views::Button* sender) {
  if (sender == close_button_)
    model_->CloseTab(this);
}

////////////////////////////////////////////////////////////////////////////////
// Tab2, views::View overrides:

void Tab2::Layout() {
  gfx::Rect content_rect = GetLocalBounds(false);
  if (content_rect.IsEmpty())
    return;
  content_rect.Inset(kLeftPadding, kTopPadding, kRightPadding, kBottomPadding);

  int content_height = GetContentHeight();
  LayoutIcon(content_height, content_rect);
  LayoutCloseButton(content_height, content_rect);
  LayoutTitle(content_height, content_rect);
}

void Tab2::Paint(gfx::Canvas* canvas) {
  // Don't paint if we're narrower than we can render correctly. (This should
  // only happen during animations).
  if (width() < GetMinimumUnselectedSize().width())
    return;

  PaintTabBackground(canvas);
  if (ShouldShowIcon())
    PaintIcon(canvas);
  PaintTitle(canvas);
}

void Tab2::OnMouseEntered(const views::MouseEvent& e) {
  hover_animation_->SetTweenType(SlideAnimation::EASE_OUT);
  hover_animation_->Show();
}

void Tab2::OnMouseExited(const views::MouseEvent& e) {
  hover_animation_->SetTweenType(SlideAnimation::EASE_IN);
  hover_animation_->Hide();
}

bool Tab2::OnMousePressed(const views::MouseEvent& event) {
  if (event.IsLeftMouseButton()) {
    model_->SelectTab(this);
    model_->CaptureDragInfo(this, event);
  }
  return true;
}

bool Tab2::OnMouseDragged(const views::MouseEvent& event) {
  dragging_ = true;
  return model_->DragTab(this, event);
}

void Tab2::OnMouseReleased(const views::MouseEvent& event, bool canceled) {
  if (dragging_) {
    dragging_ = false;
    model_->DragEnded(this);
  }
}

void Tab2::ThemeChanged() {
  LoadTabImages();
  View::ThemeChanged();
}

void Tab2::ViewHierarchyChanged(bool is_add, views::View* parent,
                                views::View* child) {
  if (parent->GetThemeProvider())
    theme_provider_ = parent->GetThemeProvider();
}

ThemeProvider* Tab2::GetThemeProvider() {
  ThemeProvider* provider = View::GetThemeProvider();
  if (provider)
    return provider;

  if (theme_provider_)
    return theme_provider_;

  // return contents->profile()->GetThemeProvider();
  NOTREACHED() << "Unable to find a theme provider";
  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
// Tab2, views::AnimationDelegate implementation:

void Tab2::AnimationProgressed(const Animation* animation) {
  SchedulePaint();
}

void Tab2::AnimationCanceled(const Animation* animation) {
  AnimationEnded(animation);
}

void Tab2::AnimationEnded(const Animation* animation) {
  SchedulePaint();
}

////////////////////////////////////////////////////////////////////////////////
// Tab2, private:

void Tab2::LayoutIcon(int content_height, const gfx::Rect& content_rect) {
  showing_icon_ = ShouldShowIcon();
  if (showing_icon_) {
    int icon_y = kTopPadding + (content_height - kIconSize) / 2;
    icon_bounds_.SetRect(content_rect.x(), icon_y, kIconSize, kIconSize);
  } else {
    icon_bounds_.SetRect(content_rect.x(), content_rect.y(), 0, 0);
  }

  // Since we paint the icon manually instead of using a child view, we need
  // to adjust its bounds for RTL.
  icon_bounds_.set_x(MirroredLeftPointForRect(icon_bounds_));
}

void Tab2::LayoutCloseButton(int content_height,
                             const gfx::Rect& content_rect) {
  showing_close_button_ = ShouldShowCloseBox();
  if (showing_close_button_) {
    int close_button_top =
        kTopPadding + kCloseButtonVertFuzz +
        (content_height - close_button_height) / 2;
    // If the ratio of the close button size to tab width exceeds the maximum.
    close_button_->SetBounds(content_rect.width() + kCloseButtonHorzFuzz,
                             close_button_top, close_button_width,
                             close_button_height);
    close_button_->SetVisible(true);
  } else {
    close_button_->SetBounds(0, 0, 0, 0);
    close_button_->SetVisible(false);
  }
}

void Tab2::LayoutTitle(int content_height, const gfx::Rect& content_rect) {
  // Size the Title text to fill the remaining space.
  int title_left = icon_bounds_.right() + kIconTitleSpacing;
  int title_top = kTopPadding + (content_height - title_font_height) / 2;

  // If the user has big fonts, the title will appear rendered too far down on
  // the y-axis if we use the regular top padding, so we need to adjust it so
  // that the text appears centered.
  gfx::Size minimum_size = GetMinimumUnselectedSize();
  int text_height = title_top + title_font_height + kBottomPadding;
  if (text_height > minimum_size.height())
    title_top -= (text_height - minimum_size.height()) / 2;

  int title_width;
  if (close_button_->IsVisible()) {
    title_width = std::max(close_button_->x() -
                           kTitleCloseButtonSpacing - title_left, 0);
  } else {
    title_width = std::max(content_rect.width() - title_left, 0);
  }
  title_bounds_.SetRect(title_left, title_top, title_width, title_font_height);

  // Since we paint the title manually instead of using a child view, we need
  // to adjust its bounds for RTL.
  title_bounds_.set_x(MirroredLeftPointForRect(title_bounds_));
}

void Tab2::PaintIcon(gfx::Canvas* canvas) {
  if (animation_state_ != ANIMATION_NONE) {
    PaintLoadingAnimation(canvas);
  } else {
    canvas->save();
    canvas->ClipRectInt(0, 0, width(), height() - 4);
    SkBitmap icon = model_->GetIcon(this);
    if (!icon.isNull()) {
      // TODO(pkasting): Use code in tab_icon_view.cc:PaintIcon() (or switch
      // to using that class to render the icon).
      canvas->DrawBitmapInt(icon, 0, 0, icon.width(), icon.height(),
                            icon_bounds_.x(),
                            icon_bounds_.y() + icon_hiding_offset_,
                            kIconSize, kIconSize, true);
    }
    canvas->restore();
  }
}

void Tab2::PaintTitle(gfx::Canvas* canvas) {
  // Paint the Title.
  string16 title = model_->GetTitle(this);
  if (title.empty()) {
    if (model_->IsLoading(this))
      title = l10n_util::GetStringUTF16(IDS_TAB_LOADING_TITLE);
    else
      title = l10n_util::GetStringUTF16(IDS_TAB_UNTITLED_TITLE);
  } else {
    Browser::FormatTitleForDisplay(&title);
  }

  SkColor title_color = GetThemeProvider()->
      GetColor(model_->IsSelected(this) ?
          BrowserThemeProvider::COLOR_TAB_TEXT :
          BrowserThemeProvider::COLOR_BACKGROUND_TAB_TEXT);

  canvas->DrawStringInt(UTF16ToWideHack(title), *title_font, title_color,
                        title_bounds_.x(), title_bounds_.y(),
                        title_bounds_.width(), title_bounds_.height());
}

void Tab2::PaintTabBackground(gfx::Canvas* canvas) {
  if (model_->IsSelected(this)) {
    // Sometimes detaching a tab quickly can result in the model reporting it
    // as not being selected, so is_drag_clone_ ensures that we always paint
    // the active representation for the dragged tab.
    PaintActiveTabBackground(canvas);
  } else {
    // Draw our hover state.
    Animation* animation = hover_animation_.get();
    if (pulse_animation_->IsAnimating())
      animation = pulse_animation_.get();

    PaintInactiveTabBackground(canvas);
    if (animation->GetCurrentValue() > 0) {
      SkRect bounds;
      bounds.set(0, 0, SkIntToScalar(width()), SkIntToScalar(height()));
      canvas->saveLayerAlpha(&bounds,
          static_cast<int>(animation->GetCurrentValue() * kHoverOpacity * 0xff),
              SkCanvas::kARGB_ClipLayer_SaveFlag);
      canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
      PaintActiveTabBackground(canvas);
      canvas->restore();
    }
  }
}

void Tab2::PaintInactiveTabBackground(gfx::Canvas* canvas) {
  bool is_otr = model_->IsIncognito(this);

  // The tab image needs to be lined up with the background image
  // so that it feels partially transparent.  These offsets represent the tab
  // position within the frame background image.
  int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) +
      background_offset_.x();

  int tab_id;
  if (GetWidget() &&
      GetWidget()->GetWindow()->GetNonClientView()->UseNativeFrame()) {
    tab_id = IDR_THEME_TAB_BACKGROUND_V;
  } else {
    tab_id = is_otr ? IDR_THEME_TAB_BACKGROUND_INCOGNITO :
                      IDR_THEME_TAB_BACKGROUND;
  }

  SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(tab_id);

  // Draw left edge.  Don't draw over the toolbar, as we're not the foreground
  // tab.
  SkBitmap tab_l = skia::ImageOperations::CreateTiledBitmap(
      *tab_bg, offset, background_offset_.y(),
      tab_active_.l_width, height());
  SkBitmap theme_l = skia::ImageOperations::CreateMaskedBitmap(
      tab_l, *tab_alpha_.image_l);
  canvas->DrawBitmapInt(theme_l,
      0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
      0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
      false);

  // Draw right edge.  Again, don't draw over the toolbar.
  SkBitmap tab_r = skia::ImageOperations::CreateTiledBitmap(
      *tab_bg,
      offset + width() - tab_active_.r_width, background_offset_.y(),
      tab_active_.r_width, height());
  SkBitmap theme_r = skia::ImageOperations::CreateMaskedBitmap(
      tab_r, *tab_alpha_.image_r);
  canvas->DrawBitmapInt(theme_r,
      0, 0, theme_r.width(), theme_r.height() - kToolbarOverlap,
      width() - theme_r.width(), 0, theme_r.width(),
      theme_r.height() - kToolbarOverlap, false);

  // Draw center.  Instead of masking out the top portion we simply skip over it
  // by incrementing by kDropShadowHeight, since it's a simple rectangle.  And
  // again, don't draw over the toolbar.
  canvas->TileImageInt(*tab_bg,
     offset + tab_active_.l_width, background_offset_.y() + kDropShadowHeight,
     tab_active_.l_width, kDropShadowHeight,
     width() - tab_active_.l_width - tab_active_.r_width,
     height() - kDropShadowHeight - kToolbarOverlap);

  // Now draw the highlights/shadows around the tab edge.
  canvas->DrawBitmapInt(*tab_inactive_.image_l, 0, 0);
  canvas->TileImageInt(*tab_inactive_.image_c,
                       tab_inactive_.l_width, 0,
                       width() - tab_inactive_.l_width - tab_inactive_.r_width,
                       height());
  canvas->DrawBitmapInt(*tab_inactive_.image_r,
                        width() - tab_inactive_.r_width, 0);
}

void Tab2::PaintActiveTabBackground(gfx::Canvas* canvas) {
  int offset = GetX(views::View::APPLY_MIRRORING_TRANSFORMATION) +
      background_offset_.x();
  ThemeProvider* tp = GetThemeProvider();
  if (!tp)
    NOTREACHED() << "Unable to get theme provider";

  SkBitmap* tab_bg = GetThemeProvider()->GetBitmapNamed(IDR_THEME_TOOLBAR);

  // Draw left edge.
  SkBitmap tab_l = skia::ImageOperations::CreateTiledBitmap(
      *tab_bg, offset, 0, tab_active_.l_width, height());
  SkBitmap theme_l = skia::ImageOperations::CreateMaskedBitmap(
      tab_l, *tab_alpha_.image_l);
  canvas->DrawBitmapInt(theme_l, 0, 0);

  // Draw right edge.
  SkBitmap tab_r = skia::ImageOperations::CreateTiledBitmap(
      *tab_bg,
      offset + width() - tab_active_.r_width, 0,
      tab_active_.r_width, height());
  SkBitmap theme_r = skia::ImageOperations::CreateMaskedBitmap(
      tab_r, *tab_alpha_.image_r);
  canvas->DrawBitmapInt(theme_r, width() - tab_active_.r_width, 0);

  // Draw center.  Instead of masking out the top portion we simply skip over it
  // by incrementing by kDropShadowHeight, since it's a simple rectangle.
  canvas->TileImageInt(*tab_bg,
     offset + tab_active_.l_width, kDropShadowHeight,
     tab_active_.l_width, kDropShadowHeight,
     width() - tab_active_.l_width - tab_active_.r_width,
     height() - kDropShadowHeight);

  // Now draw the highlights/shadows around the tab edge.
  canvas->DrawBitmapInt(*tab_active_.image_l, 0, 0);
  canvas->TileImageInt(*tab_active_.image_c, tab_active_.l_width, 0,
      width() - tab_active_.l_width - tab_active_.r_width, height());
  canvas->DrawBitmapInt(*tab_active_.image_r, width() - tab_active_.r_width, 0);
}

void Tab2::PaintHoverTabBackground(gfx::Canvas* canvas, double opacity) {
  SkBitmap left = skia::ImageOperations::CreateBlendedBitmap(
                  *tab_inactive_.image_l, *tab_active_.image_l, opacity);
  SkBitmap center = skia::ImageOperations::CreateBlendedBitmap(
                    *tab_inactive_.image_c, *tab_active_.image_c, opacity);
  SkBitmap right = skia::ImageOperations::CreateBlendedBitmap(
                   *tab_inactive_.image_r, *tab_active_.image_r, opacity);

  canvas->DrawBitmapInt(left, 0, 0);
  canvas->TileImageInt(center, tab_active_.l_width, 0,
      width() - tab_active_.l_width - tab_active_.r_width, height());
  canvas->DrawBitmapInt(right, width() - tab_active_.r_width, 0);
}

void Tab2::PaintLoadingAnimation(gfx::Canvas* canvas) {
  SkBitmap* frames = (animation_state_ == ANIMATION_WAITING) ?
                      waiting_animation_frames : loading_animation_frames;
  int image_size = frames->height();
  int image_offset = animation_frame_ * image_size;
  int dst_y = (height() - image_size) / 2;

  // Just like with the Tab's title and icon, the position for the page
  // loading animation also needs to be mirrored if the View's UI layout is
  // right-to-left.
  int dst_x;
  if (UILayoutIsRightToLeft()) {
    dst_x = width() - kLeftPadding - image_size;
  } else {
    dst_x = kLeftPadding;
  }
  canvas->DrawBitmapInt(*frames, image_offset, 0, image_size,
                        image_size, dst_x, dst_y, image_size, image_size,
                        false);
}

int Tab2::IconCapacity() const {
  if (height() < GetMinimumUnselectedSize().height())
    return 0;
  return (width() - kLeftPadding - kRightPadding) / kIconSize;
}

bool Tab2::ShouldShowIcon() const {
  if (!model_->ShouldShowIcon(const_cast<Tab2*>(this))) {
    return false;
  } else if (model_->IsSelected(const_cast<Tab2*>(this))) {
    // The selected tab clips icon before close button.
    return IconCapacity() >= 2;
  }
  // Non-selected tabs clip close button before icon.
  return IconCapacity() >= 1;
}

bool Tab2::ShouldShowCloseBox() const {
  // The selected tab never clips close button.
  return model_->IsSelected(const_cast<Tab2*>(this)) || IconCapacity() >= 3;
}

// static
void Tab2::LoadTabImages() {
  // We're not letting people override tab images just yet.
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();

  tab_alpha_.image_l = rb.GetBitmapNamed(IDR_TAB_ALPHA_LEFT);
  tab_alpha_.image_r = rb.GetBitmapNamed(IDR_TAB_ALPHA_RIGHT);

  tab_active_.image_l = rb.GetBitmapNamed(IDR_TAB_ACTIVE_LEFT);
  tab_active_.image_c = rb.GetBitmapNamed(IDR_TAB_ACTIVE_CENTER);
  tab_active_.image_r = rb.GetBitmapNamed(IDR_TAB_ACTIVE_RIGHT);
  tab_active_.l_width = tab_active_.image_l->width();
  tab_active_.r_width = tab_active_.image_r->width();

  tab_inactive_.image_l = rb.GetBitmapNamed(IDR_TAB_INACTIVE_LEFT);
  tab_inactive_.image_c = rb.GetBitmapNamed(IDR_TAB_INACTIVE_CENTER);
  tab_inactive_.image_r = rb.GetBitmapNamed(IDR_TAB_INACTIVE_RIGHT);

  tab_inactive_.l_width = tab_inactive_.image_l->width();
  tab_inactive_.r_width = tab_inactive_.image_r->width();

  loading_animation_frames = rb.GetBitmapNamed(IDR_THROBBER);
  waiting_animation_frames = rb.GetBitmapNamed(IDR_THROBBER_WAITING);
}


text:
import { Clock } from '@styled-icons/fa-regular/Clock'
import { FormattedMessage } from 'react-intl'
import React from 'react'

import { IconWithText } from '../util/styledIcon'

const SimpleRealtimeAnnotation = () => (
  <div className="simple-realtime-annotation">
    <IconWithText Icon={Clock}>
      <FormattedMessage id="components.SimpleRealtimeAnnotation.usingRealtimeInfo" />
    </IconWithText>
  </div>
)

export default SimpleRealtimeAnnotation


text:
namespace cc {

class OutputSurface;
class ResourceProvider;

class CC_EXPORT DelegatingRenderer : public Renderer {
 public:
  static scoped_ptr<DelegatingRenderer> Create(
      RendererClient* client,
      OutputSurface* output_surface,
      ResourceProvider* resource_provider);
  virtual ~DelegatingRenderer();

  virtual const RendererCapabilities& Capabilities() const OVERRIDE;

  virtual bool CanReadPixels() const OVERRIDE;

  virtual void DrawFrame(RenderPassList* render_passes_in_draw_order) OVERRIDE;

  virtual void Finish() OVERRIDE {}

  virtual void SwapBuffers() OVERRIDE;
  virtual void ReceiveSwapBuffersAck(const CompositorFrameAck&) OVERRIDE;

  virtual void GetFramebufferPixels(void* pixels, gfx::Rect rect) OVERRIDE;

  virtual bool IsContextLost() OVERRIDE;

  virtual void SetVisible(bool visible) OVERRIDE;

  virtual void SendManagedMemoryStats(size_t bytes_visible,
                                      size_t bytes_visible_and_nearby,
                                      size_t bytes_allocated) OVERRIDE;

  virtual void SetDiscardBackBufferWhenNotVisible(bool discard) OVERRIDE;

 private:
  DelegatingRenderer(RendererClient* client,
                     OutputSurface* output_surface,
                     ResourceProvider* resource_provider);
  bool Initialize();

  OutputSurface* output_surface_;
  ResourceProvider* resource_provider_;
  RendererCapabilities capabilities_;
  CompositorFrame frame_for_swap_buffers_;
  bool visible_;

  DISALLOW_COPY_AND_ASSIGN(DelegatingRenderer);
};

}  // namespace cc

#endif  // CC_OUTPUT_DELEGATING_RENDERER_H_


text:
package zoom

import "fmt"

// GetUserPath - v2 path for getting a specific user
const GetUserPath = "/users/%s"

// GetUserOpts contains options for GetUser
type GetUserOpts struct {
	EmailOrID string         `url:"-"`
	LoginType *UserLoginType `url:"login_type,omitempty"` // use pointer so it can be null
}

// GetUser calls /users/{userId}, searching for a user by ID or email, using the default client
func GetUser(opts GetUserOpts) (User, error) {
	return defaultClient.GetUser(opts)
}

// GetUser calls /users/{userId}, searching for a user by ID or email, using a specific client
func (c *Client) GetUser(opts GetUserOpts) (User, error) {
	var ret = User{}
	return ret, c.requestV2(requestV2Opts{
		Method:        Get,
		Path:          fmt.Sprintf(GetUserPath, opts.EmailOrID),
		URLParameters: opts,
		Ret:           &ret,
	})
}


text:
'use strict';

const chai = require('chai');
const expect = chai.expect;
const Support = require('../../support');
const DataTypes = require('../../../../lib/data-types');
const Sequelize = require('../../../../lib/sequelize');
const current = Support.sequelize;

describe(Support.getTestDialectTeaser('Model'), () => {
  describe('findAll', () => {
    describe('separate with limit', () => {
      it('should not throw syntax error (union)', () => {
        // #9813 testcase
        const Project = current.define('Project', { name: DataTypes.STRING });
        const LevelTwo = current.define('LevelTwo', { name: DataTypes.STRING });
        const LevelThree = current.define('LevelThree', { type: DataTypes.INTEGER });

        Project.hasMany(LevelTwo);
        LevelTwo.belongsTo(Project);

        LevelTwo.hasMany(LevelThree, { as: 'type_ones' });
        LevelTwo.hasMany(LevelThree, { as: 'type_twos' });
        LevelThree.belongsTo(LevelTwo);

        return current.sync({ force: true }).then(() => {
          return Sequelize.Promise.all([
            Project.create({ name: 'testProject' }),
            LevelTwo.create({ name: 'testL21' }),
            LevelTwo.create({ name: 'testL22' })
          ]);
        }).spread((project, level21, level22) => {
          return Sequelize.Promise.all([
            project.addLevelTwo(level21),
            project.addLevelTwo(level22)
          ]);
        }).spread(() => {
          // one include case
          return Project.findAll({
            where: { name: 'testProject' },
            include: [
              {
                model: LevelTwo,
                include: [
                  {
                    model: LevelThree,
                    as: 'type_ones',
                    where: { type: 0 },
                    separate: true,
                    limit: 1,
                    order: [['createdAt', 'DESC']]
                  }
                ]
              }
            ]
          });
        }).then(projects => {
          expect(projects).to.have.length(1);
          expect(projects[0].LevelTwos).to.have.length(2);
          expect(projects[0].LevelTwos[0].type_ones).to.have.length(0);
          expect(projects[0].LevelTwos[1].type_ones).to.have.length(0);
        }, () => {
          expect.fail();
        }).then(() => {
          // two includes case
          return Project.findAll({
            where: { name: 'testProject' },
            include: [
              {
                model: LevelTwo,
                include: [
                  {
                    model: LevelThree,
                    as: 'type_ones',
                    where: { type: 0 },
                    separate: true,
                    limit: 1,
                    order: [['createdAt', 'DESC']]
                  },
                  {
                    model: LevelThree,
                    as: 'type_twos',
                    where: { type: 1 },
                    separate: true,
                    limit: 1,
                    order: [['createdAt', 'DESC']]
                  }
                ]
              }
            ]
          });
        }).then(projects => {
          expect(projects).to.have.length(1);
          expect(projects[0].LevelTwos).to.have.length(2);
          expect(projects[0].LevelTwos[0].type_ones).to.have.length(0);
          expect(projects[0].LevelTwos[1].type_ones).to.have.length(0);
        }, () => {
          expect.fail();
        });
      });
    });
  });
});


text:
"""Implement an API wrapper around Ikea Tradfri."""

from .coap_cli import api_factory as cli_api_factory
from .error import PyTradFriError, CommandError, NotFoundError
from .gateway import Gateway

__all__ = ['Gateway', 'cli_api_factory', 'PyTradFriError', 'CommandError',
           'NotFoundError']


text:
package com.google.template.soy.basicdirectives;

import com.google.common.collect.ImmutableSet;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.jssrc.restricted.SoyJsSrcPrintDirective;
import com.google.template.soy.phpsrc.restricted.PhpExpr;
import com.google.template.soy.phpsrc.restricted.SoyPhpSrcPrintDirective;
import com.google.template.soy.pysrc.restricted.PyExpr;
import com.google.template.soy.pysrc.restricted.SoyPySrcPrintDirective;
import com.google.template.soy.shared.restricted.Sanitizers;
import com.google.template.soy.shared.restricted.SoyJavaPrintDirective;
import com.google.template.soy.shared.restricted.SoyPurePrintDirective;

import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Implements the |filterImageDataUri directive, which only accepts data URI's corresponding to
 * images.
 *
 * <p>
 * Note that this directive is not autoescape cancelling, and can thus be
 * used in strict templates.  The directive returns its result as an object
 * of type SanitizedContent of kind URI.
 */
@Singleton
@SoyPurePrintDirective
final class FilterImageDataUriDirective implements SoyJavaPrintDirective, SoyJsSrcPrintDirective,
    SoyPySrcPrintDirective, SoyPhpSrcPrintDirective {

  private static final Set<Integer> VALID_ARGS_SIZES = ImmutableSet.of(0);

  @Inject
  public FilterImageDataUriDirective() {}

  @Override public String getName() {
    return "|filterImageDataUri";
  }

  @Override public final Set<Integer> getValidArgsSizes() {
    return VALID_ARGS_SIZES;
  }

  @Override public boolean shouldCancelAutoescape() {
    return false;
  }

  @Override public SoyValue applyForJava(SoyValue value, List<SoyValue> args) {
    return Sanitizers.filterImageDataUri(value);
  }

  @Override public JsExpr applyForJsSrc(JsExpr value, List<JsExpr> args) {
    return new JsExpr("soy.$$filterImageDataUri(" + value.getText() + ")", Integer.MAX_VALUE);
  }

  @Override public PyExpr applyForPySrc(PyExpr value, List<PyExpr> args) {
    return new PyExpr("sanitize.filter_image_data_uri(" + value.getText() + ")", Integer.MAX_VALUE);
  }

  @Override public PhpExpr applyForPhpSrc(PhpExpr value, List<PhpExpr> args) {
    return new PhpExpr("Sanitize::filterImageDataUri(" + value.getText() + ")", Integer.MAX_VALUE);
  }
}