text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Oobe Arc Terms of Service screen implementation.
 */

login.createScreen('ArcTermsOfServiceScreen', 'arc-tos',
  function() { return {
    EXTERNAL_API: [
      'setMetricsMode',
      'setBackupAndRestoreMode',
      'setLocationServicesMode',
      'setCountryCode'
    ],

    /** @override */
    decorate: function(element) {
      var closeButtons = document.querySelectorAll('.arc-overlay-close-button');
      for (var i = 0; i < closeButtons.length; i++) {
        closeButtons[i].addEventListener('click', this.hideOverlay.bind(this));
      }

      var termsView = $('arc-tos-view');
      var requestFilter = {
        urls: ['<all_urls>'],
        types: ['main_frame']
      };

      termsView.request.onErrorOccurred.addListener(
          this.onTermsViewErrorOccurred.bind(this), requestFilter);
      termsView.addEventListener('contentload',
          this.onTermsViewContentLoad.bind(this));

      // Open links from webview in overlay dialog.
      var self = this;
      termsView.addEventListener('newwindow', function(event) {
        event.preventDefault();
        self.showUrlOverlay(event.targetUrl);
      });

      termsView.addContentScripts([
        { name: 'postProcess',
          matches: ['https://play.google.com/*'],
          css: { files: ['playstore.css'] },
          js: { files: ['playstore.js'] },
          run_at: 'document_end'
        }]);

      $('arc-policy-link').onclick = function() {
        termsView.executeScript(
            {code: 'getPrivacyPolicyLink();'},
            function(results) {
              if (results && results.length == 1 &&
                  typeof results[0] == 'string') {
                self.showUrlOverlay(results[0]);
              } else {
                self.showUrlOverlay('https://www.google.com/policies/privacy/');
              }
            });
      };

      this.updateLocalizedContent();
    },

    /**
     * Sets current metrics mode.
     * @param {string} text Describes current metrics state.
     * @param {boolean} visible If metrics text is visible.
     */
    setMetricsMode: function(text, visible) {
      $('arc-text-metrics').hidden = !visible;
      $('arc-text-metrics').innerHTML = text;

      if (!visible) {
        return;
      }

      var self = this;
      var leanMoreStatisticsText =
          loadTimeData.getString('arcLearnMoreStatistics');
      $('learn-more-link-metrics').onclick = function() {
        self.showLearnMoreOverlay(leanMoreStatisticsText);
      };
    },

    /**
     * Applies current enabled/managed state to checkbox and text.
     * @param {string} checkBoxId Id of checkbox to set on/off.
     * @param {string} textId Id of text to set enabled state.
     * @param {boolean} enabled Defines the value of the checkbox.
     * @param {boolean} managed Defines whether this setting is set by policy.
     */
    setPreference(checkBoxId, textId, enabled, managed) {
      $(checkBoxId).checked = enabled;
      $(checkBoxId).disabled = managed;
      $(textId).disabled = managed;
    },

    /**
     * Sets current backup and restore mode.
     * @param {boolean} enabled Defines the value for backup and restore
     *                          checkbox.
     * @param {boolean} managed Defines whether this setting is set by policy.
     */
    setBackupAndRestoreMode: function(enabled, managed) {
      this.setPreference('arc-enable-backup-restore',
                         'arc-text-backup-restore',
                         enabled, managed);
    },

    /**
     * Sets current usage of location service opt in mode.
     * @param {boolean} enabled Defines the value for location service opt in.
     * @param {boolean} managed Defines whether this setting is set by policy.
     */
    setLocationServicesMode: function(enabled, managed) {
      this.setPreference('arc-enable-location-service',
                         'arc-text-location-service',
                         enabled, managed);
    },

    /**
     * Sets current country code for ToS.
     * @param {string} countryCode Country code based on current timezone.
     */
    setCountryCode: function(countryCode) {
      var scriptSetCountryCode = 'document.countryCode = \'' +
          countryCode.toLowerCase() + '\';';
      var termsView = $('arc-tos-view');
      termsView.removeContentScripts(['preProcess']);
      termsView.addContentScripts([
          { name: 'preProcess',
            matches: ['https://play.google.com/*'],
            js: { code: scriptSetCountryCode },
            run_at: 'document_start'
          }]);

      if (!$('arc-tos').hidden) {
        this.reloadPlayStore();
      }
    },

    /**
     * Buttons in Oobe wizard's button strip.
     * @type {array} Array of Buttons.
     */
    get buttons() {
      var buttons = [];

      var skipButton = this.ownerDocument.createElement('button');
      skipButton.id = 'arc-tos-skip-button';
      skipButton.textContent =
          loadTimeData.getString('arcTermsOfServiceSkipButton');
      skipButton.addEventListener('click', function(event) {
        $('arc-tos-skip-button').disabled = true;
        $('arc-tos-accept-button').disabled = true;
        chrome.send('arcTermsOfServiceSkip');
      });
      buttons.push(skipButton);

      var retryButton = this.ownerDocument.createElement('button');
      retryButton.id = 'arc-tos-retry-button';
      retryButton.textContent =
          loadTimeData.getString('arcTermsOfServiceRetryButton');
      retryButton.addEventListener('click', this.reloadPlayStore.bind(this));
      buttons.push(retryButton);

      var acceptButton = this.ownerDocument.createElement('button');
      acceptButton.id = 'arc-tos-accept-button';
      acceptButton.disabled = this.classList.contains('arc-tos-loading');
      acceptButton.classList.add('preserve-disabled-state');
      acceptButton.textContent =
          loadTimeData.getString('arcTermsOfServiceAcceptButton');
      acceptButton.addEventListener('click', function(event) {
        $('arc-tos-skip-button').disabled = true;
        $('arc-tos-accept-button').disabled = true;

        var isBackupRestoreEnabled = $('arc-enable-backup-restore').checked;
        var isLocationServiceEnabled = $('arc-enable-location-service').checked;

        chrome.send('arcTermsOfServiceAccept',
            [isBackupRestoreEnabled, isLocationServiceEnabled]);
      });
      buttons.push(acceptButton);

      return buttons;
    },

    /**
     * Returns the control which should receive initial focus.
     */
    get defaultControl() {
      return $('arc-tos-accept-button').disabled ? $('arc-tos-skip-button') :
                                                   $('arc-tos-accept-button');
    },

    /**
     * Sets learn more content text and shows it as overlay dialog.
     * @param {string} content HTML formatted text to show.
     */
    showLearnMoreOverlay: function(content) {
      $('arc-learn-more-content').innerHTML = content;
      $('arc-tos-overlay-content-text').hidden = false;
      $('arc-tos-overlay-text').hidden = false;
    },

    /**
     * Opens external URL in popup overlay.
     * @param {string} targetUrl URL to open.
     */
    showUrlOverlay: function(targetUrl) {
      $('arc-tos-overlay-webview').src = targetUrl;
      $('arc-tos-overlay-url').hidden = false;
    },

    /**
     * Hides overlay dialog.
     */
    hideOverlay: function() {
      $('arc-tos-overlay-text').hidden = true;
      $('arc-tos-overlay-url').hidden = true;
    },

    /**
     * Reloads Play Store.
     */
    reloadPlayStore: function() {
      this.termsError = false;
      var termsView = $('arc-tos-view');
      termsView.src = 'https://play.google.com/about/play-terms.html';
      this.classList.remove('arc-tos-loaded');
      this.classList.remove('error');
      this.classList.add('arc-tos-loading');
    },

    /**
     * Handles event when terms view is loaded.
     */
    onTermsViewContentLoad: function() {
      if (this.termsError) {
        return;
      }

      this.classList.remove('arc-tos-loading');
      this.classList.remove('error');
      this.classList.add('arc-tos-loaded');

      var acceptButton = $('arc-tos-accept-button');
      var skipButton = $('arc-tos-skip-button');

      acceptButton.disabled = false;
      if (document.activeElement != skipButton) {
        acceptButton.focus();
      }

      var termsView = $('arc-tos-view');
      var termsViewContainer = $('arc-tos-view-container');
      var setTermsHeight = function() {
        // Reset terms-view height in order to stabilize style computation.
        // For some reason, child webview affects final result.
        termsView.style.height = '0px';
        var style = window.getComputedStyle(termsViewContainer, null);
        var height = style.getPropertyValue('height');
        termsView.style.height = height;
      };
      setTimeout(setTermsHeight, 0);
    },

    /**
     * Handles event when terms view cannot be loaded.
     */
    onTermsViewErrorOccurred: function(details) {
      this.termsError = true;
      this.classList.remove('arc-tos-loading');
      this.classList.remove('arc-tos-loaded');
      this.classList.add('error');
    },

    /**
     * Event handler that is invoked just before the screen is shown.
     * @param {object} data Screen init payload.
     */
    onBeforeShow: function(data) {
      Oobe.getInstance().headerHidden = true;

      this.hideOverlay();
      this.reloadPlayStore();
    },

    /**
     * Updates localized content of the screen that is not updated via template.
     */
    updateLocalizedContent: function() {
      var self = this;

      var leanMoreBackupAndRestoreText =
          loadTimeData.getString('arcLearnMoreBackupAndRestore');
      $('learn-more-link-backup-restore').onclick = function() {
        self.showLearnMoreOverlay(leanMoreBackupAndRestoreText);
      };

      var leanMoreLocationServiceText =
          loadTimeData.getString('arcLearnMoreLocationService');
      $('learn-more-link-location-service').onclick = function() {
        self.showLearnMoreOverlay(leanMoreLocationServiceText);
      };
    }
  };
});


text:
namespace Open.HttpProxy
{
	public class ProtocolVersion
	{
		public static readonly ProtocolVersion Http10 = ProtocolVersion.Parse("http/1.0");
		public static readonly ProtocolVersion Http11 = ProtocolVersion.Parse("http/1.1");

		public string Protocol { get; }
		public int Major { get; }
		public int Minor { get; }

		public static ProtocolVersion Parse(string version)
		{
			var parts = version.Split('/');
			var numparts = parts[1].Split('.');
			var protocol = parts[0];
			var major = int.Parse(numparts[0]);
			var minor = int.Parse(numparts[1]);
			return new ProtocolVersion(protocol, major, minor);
		}

		private ProtocolVersion(string protocol, int major, int minor)
		{
			Protocol = protocol;
			Major = major;
			Minor = minor;
		}

		public override string ToString()
		{
			return $"{Protocol}/{Major}.{Minor}";
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
INSERT INTO flights
	(departure_time, arrival_time, status, origin_airport_id, destination_airport_id, airline_id)
	SELECT
	'2017-06-19 14:00:00' AS departure_time,
	'2017-06-21 11:00:00' AS arrival_time,
	CASE
		WHEN (a.airline_id % 4) = 0
			THEN 'Departing'
		WHEN (a.airline_id % 4) = 1
			THEN 'Delayed'
		WHEN (a.airline_id % 4) = 2
			THEN 'Arrived'
		WHEN (a.airline_id % 4) = 3
			THEN 'Canceled'
	END AS 'status',
	CEIL(SQRT(CHAR_LENGTH(a.airline_name))) AS 'origin_airport_id',
	CEIL(SQRT(CHAR_LENGTH(a.nationality))) AS 'destination_airport_id',
	a.airline_id
FROM airlines AS a
WHERE a.airline_id BETWEEN 1 AND 10;

# THE SELECTION FOR THE INSERT QUERY
SELECT
	'2017-06-19 14:00:00' AS departure_time,
	'2017-06-21 11:00:00' AS arrival_time,
	CASE
		WHEN (a.airline_id % 4) = 0
			THEN 'Departing'
		WHEN (a.airline_id % 4) = 1
			THEN 'Delayed'
		WHEN (a.airline_id % 4) = 2
			THEN 'Arrived'
		WHEN (a.airline_id % 4) = 3
			THEN 'Canceled'
	END AS 'status',
	CEIL(SQRT(CHAR_LENGTH(a.airline_name))) AS 'origin_airport_id',
	CEIL(SQRT(CHAR_LENGTH(a.nationality))) AS 'destination_airport_id',
	a.airline_id
FROM airlines AS a
WHERE a.airline_id BETWEEN 1 AND 10;

#UPDATE ALL ARRIVED FLIGHTS
UPDATE flights
SET flights.airline_id = 1
WHERE flights.`status` LIKE 'Arrived';

#UPDATE THE HIGHEST RATE AIRLINE
UPDATE tickets AS t
SET t.price = t.price * 1.5
	WHERE t.ticket_id = (SELECT
			t.ticket_id
	FROM flights AS f
	INNER JOIN tickets AS t
	ON f.flight_id=t.flight_id
	INNER JOIN airlines AS a
	ON f.airline_id=a.airline_id
	WHERE a.rating = (SELECT
			MAX(a.rating) AS max_rate
			FROM airlines AS a
			));

#SELECTION
SELECT
		t.ticket_id
FROM flights AS f
INNER JOIN tickets AS t
ON f.flight_id=t.flight_id
INNER JOIN airlines AS a
ON f.airline_id=a.airline_id
WHERE a.rating = (SELECT
		MAX(a.rating) AS max_rate
		FROM airlines AS a
		);


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenQA.Selenium;

namespace Selenium.Internal.SeleniumEmulation
{
    /// <summary>
    /// Defines the command for the setTimeout keyword.
    /// </summary>
    internal class SetTimeout : SeleneseCommand
    {
        private CommandTimer timer;

        /// <summary>
        /// Initializes a new instance of the <see cref="SetTimeout"/> class.
        /// </summary>
        /// <param name="timer">The <see cref="CommandTimer"/> object used to monitor timeouts for commands.</param>
        public SetTimeout(CommandTimer timer)
        {
            this.timer = timer;
        }

        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            if (locator == "0")
            {
                this.timer.Timeout = int.MaxValue;
            }
            else
            {
                this.timer.Timeout = int.Parse(locator, CultureInfo.InvariantCulture);
            }

            return null;
        }
    }
}


text:
<?php
return array (
  'Modules directory' => 'Modules overzicht',
  'Installed version:' => 'Geïnstalleerde versie:',
  'Latest compatible Version:' => 'Nieuwste compatibele versie:',
  'Update' => 'Update',
);


text:
if (jQuery) (function ($) {

    $.extend($.fn, {
        fileTree: function (o, h, r) {
            // Defaults
            if (!o) var o = {};
            if (o.root == undefined) o.root = '/';
            if (o.script == undefined) o.script = 'jqueryFileTree.php';
            if (o.folderEvent == undefined) o.folderEvent = 'click';
            if (o.expandSpeed == undefined) o.expandSpeed = 500;
            if (o.collapseSpeed == undefined) o.collapseSpeed = 500;
            if (o.expandEasing == undefined) o.expandEasing = null;
            if (o.collapseEasing == undefined) o.collapseEasing = null;
            if (o.multiFolder == undefined) o.multiFolder = true;
            if (o.loadMessage == undefined) o.loadMessage = 'Loading...';

            $(this).each(function () {

                function showTree(c, t) {
                    $(c).addClass('wait');
                    $(".jqueryFileTree.start").remove();
                    $.post(o.script, { dir: t }, function (data) {
                        $(c).find('.start').html('');
                        $(c).removeClass('wait').append(data);
                        if (o.root == t) {
                            $(c).find('UL:hidden').show();
                            if (typeof updateScroll == 'function')
                                setTimeout(updateScroll, 50);
                        }
                        else {
                            if (typeof updateScroll == 'function')
                                $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing, complete: updateScroll });
                            else
                                $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
                        }
                        bindTree(c);
                    });
                }

                function bindTree(t) {
                    $(t).find('LI A').bind(o.folderEvent, function () {
                        if ($(this).parent().hasClass('directory')) {
                            if ($(this).parent().hasClass('collapsed')) {
                                // Expand
                                if (!o.multiFolder) {
                                    if (typeof updateScroll == 'function')
                                        $(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing, complete: updateScroll });
                                    else
                                        $(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                    $(this).parent().parent().find('LI.directory').removeClass('expanded').addClass('collapsed');
                                }
                                $(this).parent().find('UL').remove(); // cleanup
                                showTree($(this).parent(), escape($(this).attr('rel'))); //.match( /.*\// )) );
                                $(this).parent().removeClass('collapsed').addClass('expanded');
                                if (typeof updateScroll == 'function')
                                    setTimeout(updateScroll, 100);
                            } else {
                                // Collapse
                                if (typeof updateScroll == 'function')
                                    $(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing, complete: updateScroll });
                                else
                                    $(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                $(this).parent().removeClass('expanded').addClass('collapsed');
                            }
                            if (r != undefined)
                                r($(this));
                        } else {
                            h($(this).attr('rel'));

                        }
                        return false;
                    });
                    // Prevent A from triggering the # on non-click events
                    if (o.folderEvent.toLowerCase != 'click') $(t).find('LI A').bind('click', function () { return false; });
                }
                // Loading message
                $(this).html('

' + o.loadMessage + '

');
                // Get the initial file list
                showTree($(this), escape(o.root));
            });
        }
    });

})(jQuery);


text:
namespace LinuxPackages.Web.Mvc.ViewModels.Packages
{
    public class RatePackageViewModel
    {
        public int Value { get; set; }

        public string PackageId { get; set; }
    }
}


text:
package com.pivotal.gemfirexd.internal.hadoop;

import hydra.Log;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import memscale.OffHeapHelper;

import util.TestException;

import com.gemstone.gemfire.cache.CustomEvictionAttributes;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.EvictionAction;
import com.gemstone.gemfire.cache.EvictionAlgorithm;
import com.gemstone.gemfire.cache.EvictionAttributes;
import com.gemstone.gemfire.cache.Operation;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.internal.cache.CachePerfStats;
import com.gemstone.gemfire.internal.cache.EntryEventImpl;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.RegionEntry;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.engine.ddl.GfxdEvictionCriteria;
import com.pivotal.gemfirexd.internal.engine.distributed.GfxdDumpLocalResultMessage;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.engine.management.GfxdManagementService;
import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeRegionKey;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.engine.store.RegionKey;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.SQLVarchar;
import com.pivotal.gemfirexd.jdbc.JdbcTestBase;

/**
 * Unit tests for GemFireXD EVICTION BY CRITERIA.
 */
public class EvictionByCriteriaTest extends JdbcTestBase {

  static final String HDFS_DIR = "./evictHDFS";

  public EvictionByCriteriaTest(String name) {
    super(name);
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
    delete(new File(HDFS_DIR));
  }

  @Override
  protected String reduceLogging() {
    return "config";
  }

  private void delete(File file) {
    if (!file.exists()) {
      return;
    }
    if (file.isDirectory()) {
      if (file.list().length == 0) {
        file.delete();
      } else {
        File[] files = file.listFiles();
        for (File f : files) {
          delete(f);
        }
        file.delete();
      }
    } else {
      file.delete();
    }
  }

  public void testDDLSupport() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    // eviction of data more than 10 seconds old
    final String evictClause = "{fn TIMESTAMPDIFF(SQL_TSI_SECOND, "
        + "ts, CURRENT_TIMESTAMP)} > 10";
    stmt.execute("create table e.evictTable("
        + "id varchar(20) primary key, qty int, ts timestamp"
        + ")  " +  getOffHeapSuffix() + " partition by column(id) "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria (" + evictClause
        + ") eviction frequency 8 seconds");

    LocalRegion lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    GemFireContainer container = (GemFireContainer)lr.getUserAttribute();
    CustomEvictionAttributes evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    EvictionAttributes defEvictAttrs = lr.getAttributes()
        .getEvictionAttributes();
    // check attributes
    assertEquals(DataPolicy.HDFS_PERSISTENT_PARTITION, lr.getAttributes()
        .getDataPolicy());
    assertEquals(EvictionAlgorithm.LRU_HEAP, defEvictAttrs.getAlgorithm());
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, defEvictAttrs.getAction());
    assertNotNull(evictionAttrs);
    assertEquals(0, evictionAttrs.getEvictorStartTime());
    assertEquals(8000, evictionAttrs.getEvictorInterval());
    GfxdEvictionCriteria criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());

    // some inserts
    for (int i = 1; i <= 10; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    // check doEvict API
    EntryEventImpl event;
    RegionEntry entry;
    for (int i = 1; i <= 10; i++) {
      CompactCompositeRegionKey key = new CompactCompositeRegionKey(
          new SQLVarchar(Integer.toString(i)), container.getExtraTableInfo());
      event = EntryEventImpl.create(lr, Operation.LOCAL_DESTROY, key, null, null,
          false, null);
      final LocalRegion dataRegion = lr.getDataRegionForWrite(event,
          Operation.LOCAL_DESTROY);
      entry = lr.basicGetEntryForLock(dataRegion, key);
      assertFalse(entry.isMarkedForEviction());
      event.setRegionEntry(entry);
      assertFalse(criteria.doEvict(event));
    }

    // sleep for 14 secs
    Thread.sleep(12000);
    // more inserts
    for (int i = 11; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    // check that criteria should correctly filter out the first 10 entries
    @SuppressWarnings("unchecked")
    Iterator<Map.Entry<Object, Object>> evictIter = criteria
        .getKeysToBeEvicted(System.currentTimeMillis(), lr);
    int numExpectedKeys = 10;
    final boolean[] expectedKeys = new boolean[numExpectedKeys];
    while (evictIter.hasNext()) {
      Map.Entry<Object, Object> e = evictIter.next();
      DataValueDescriptor key = ((RegionKey)e.getKey()).getKeyColumn(0);
      int keyValue = key.getInt();
      assertFalse(expectedKeys[keyValue - 1]);
      expectedKeys[keyValue - 1] = true;
      numExpectedKeys--;
    }
    assertEquals(0, numExpectedKeys);

    // check the doEvict API again
    for (int i = 1; i <= 10; i++) {
      CompactCompositeRegionKey key = new CompactCompositeRegionKey(
          new SQLVarchar(Integer.toString(i)), container.getExtraTableInfo());
      event = EntryEventImpl.create(lr, Operation.LOCAL_DESTROY, key, null, null,
          false, null);
      final LocalRegion dataRegion = lr.getDataRegionForWrite(event,
          Operation.LOCAL_DESTROY);
      entry = lr.basicGetEntryForLock(dataRegion, key);
      event.setRegionEntry(entry);
      assertTrue(criteria.doEvict(event));
      entry.clearMarkedForEviction();
      assertTrue(criteria.doEvict(event));
    }
    for (int i = 11; i <= 20; i++) {
      CompactCompositeRegionKey key = new CompactCompositeRegionKey(
          new SQLVarchar(Integer.toString(i)), container.getExtraTableInfo());
      event = EntryEventImpl.create(lr, Operation.LOCAL_DESTROY, key, null, null,
          false, null);
      final LocalRegion dataRegion = lr.getDataRegionForWrite(event,
          Operation.LOCAL_DESTROY);
      entry = lr.basicGetEntryForLock(dataRegion, key);
      assertFalse(entry.isMarkedForEviction());
      event.setRegionEntry(entry);
      assertFalse(criteria.doEvict(event));
    }
  }

  public void testEvictionService_AlterFrequency() throws Exception {
    reduceLogLevelForTest("config");

    setupConnection();

    Connection conn = jdbcConn;

    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    final String evictClause = "qty > 500";
    stmt.execute("create table e.evictTable("
        + "id varchar(20) primary key, qty int, ts timestamp"
        + ")  " + getOffHeapSuffix() + "  partition by column(id) "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria (" + evictClause
        + ") eviction frequency 15 seconds");

    LocalRegion lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    CustomEvictionAttributes evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    EvictionAttributes defEvictAttrs = lr.getAttributes()
        .getEvictionAttributes();
    // check attributes
    assertEquals(DataPolicy.HDFS_PERSISTENT_PARTITION, lr.getAttributes()
        .getDataPolicy());
    assertEquals(EvictionAlgorithm.LRU_HEAP, defEvictAttrs.getAlgorithm());
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, defEvictAttrs.getAction());
    assertNotNull(evictionAttrs);
    assertEquals(0, evictionAttrs.getEvictorStartTime());
    assertEquals(15000, evictionAttrs.getEvictorInterval());
    GfxdEvictionCriteria criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());

    // some inserts
    for (int i = 1; i <= 100; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    //no eviction yet. Hence all the keys will be present
    assertTrue(stmt.execute("select * from e.evictTable"));
    ResultSet rs = stmt.getResultSet();

    Set ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    assertEquals(100, ids.size());
    for (int i = 1; i <= 100; i++) {
      assertTrue(ids.contains(i));
    }

    //allow eviction to happen
    Thread.sleep(32000);
    assertTrue(stmt.execute("select * from e.evictTable"));
    rs = stmt.getResultSet();

    ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    //entries form 51 to 100 will be evicted
    assertEquals(50, ids.size());
    for (int i = 1; i <= 50; i++) {
      assertTrue(ids.contains(i));
    }

    //another entries added
    for (int i = 101; i <= 200; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    assertTrue(stmt.execute("select * from e.evictTable"));
    rs = stmt.getResultSet();

    ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    //no eviction yet hence previous 50 + recently added 100 entries present
    assertEquals(150, ids.size());

    //eviction start time and frequency is getting changed
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    String gmtStrDate = sdf.format(Calendar.getInstance().getTime());
    Date date = new Date(gmtStrDate);
    stmt.execute("ALTER TABLE e.evictTable SET EVICTION FREQUENCY 5 SECONDS START T '" + new Time(date.getTime()) + "'");
    lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    assertEquals(5000, evictionAttrs.getEvictorInterval());
    criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());

    //Sleep to allow eviction to happen by previous frequency of 15 sec. So 100(101-200) entries will be evicted
    Thread.sleep(30000);

    //another 100 entries added
    for (int i = 201; i <= 300; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    //this time new eviction frequency 5 sec will be used and and entries from 201 to 300 will be evicted.
    Thread.sleep(10000);
    assertTrue(stmt.execute("select * from e.evictTable"));
    rs = stmt.getResultSet();

    ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    assertEquals(50, ids.size());
  }

  public void testEvictionService() throws Exception {
    reduceLogLevelForTest("config");

    setupConnection();

    Connection conn = jdbcConn;

    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    // eviction of data more than 10 seconds old
    final String evictClause = "{fn TIMESTAMPDIFF(SQL_TSI_SECOND, "
        + "ts, CURRENT_TIMESTAMP)} > 10";
    stmt.execute("create table e.evictTable("
        + "id varchar(20) primary key, qty int, ts timestamp"
        + ")  " + getOffHeapSuffix() + "  partition by column(id) "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria (" + evictClause
        + ") eviction frequency 5 seconds");

    LocalRegion lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    //GemFireContainer container = (GemFireContainer)lr.getUserAttribute();
    CustomEvictionAttributes evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    EvictionAttributes defEvictAttrs = lr.getAttributes()
        .getEvictionAttributes();
    // check attributes
    assertEquals(DataPolicy.HDFS_PERSISTENT_PARTITION, lr.getAttributes()
        .getDataPolicy());
    assertEquals(EvictionAlgorithm.LRU_HEAP, defEvictAttrs.getAlgorithm());
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, defEvictAttrs.getAction());
    assertNotNull(evictionAttrs);
    assertEquals(0, evictionAttrs.getEvictorStartTime());
    assertEquals(5000, evictionAttrs.getEvictorInterval());
    GfxdEvictionCriteria criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());

    // some inserts
    for (int i = 1; i <= 10; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    // sleep for 17 secs
    Thread.sleep(17000);
    // more inserts
    for (int i = 11; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    assertTrue(stmt.execute("select * from e.evictTable"));
    ResultSet rs = stmt.getResultSet();

    Set ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      getLogger().info("The id is " + id);
      ids.add(id);
    }
    assertEquals(10, ids.size());
    // 0 - 10 should be evicted.
    for (int i = 11; i <= 20; i++) {
      assertTrue(ids.contains(i));
    }
    assertEquals(10, lr.getCachePerfStats().getEvictions());
    assertEquals(0, lr.getCachePerfStats().getEvictionsInProgress());
    assertEquals(30, lr.getCachePerfStats().getEvaluations());
  }

  public void testBug49900() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement st = conn.createStatement();

    try {
      // EVICTION BY CRITERIA for replicated persistent non-HDFS table
      st.execute("create table t1 (col1 int)  " + getOffHeapSuffix() + "  replicate persistent eviction by criteria (col1 > 0) evict incoming");
      fail("EVICTION BY CRITERIA is not supported for non-HDFS tables");
    }
    catch (SQLException e) {
      if (!(e.getSQLState().equals("0A000") && e.getMessage().equals(
          "Eviction By Criteria is not supported for non-HDFS Table."))) {
        throw e;
      }
    }

    try {
      // EVICTION BY CRITERIA for replicated non-HDFS table
      st.execute("create table t2 (col1 int)  " + getOffHeapSuffix() + "  replicate eviction by criteria (col1 > 0) evict incoming");
      fail("EVICTION BY CRITERIA is not supported for non-HDFS tables");
    }
    catch (SQLException e) {
      if (!(e.getSQLState().equals("0A000") && e.getMessage().equals(
          "Eviction By Criteria is not supported for non-HDFS Table."))) {
        throw e;
      }
    }

    try {
      // EVICTION BY CRITERIA for partitioned persistent non-HDFS table
      st.execute("create table t3 (col1 int)  " + getOffHeapSuffix() + "  partition by column (col1) persistent eviction by criteria (col1 > 0) evict incoming");
      fail("EVICTION BY CRITERIA is not supported for non-HDFS tables");
    }
    catch (SQLException e) {
      if (!(e.getSQLState().equals("0A000") && e.getMessage().equals(
          "Eviction By Criteria is not supported for non-HDFS Table."))) {
        throw e;
      }
    }

    try {
      // EVICTION BY CRITERIA for partitioned non-HDFS table
      st.execute("create table t4 (col1 int)  " + getOffHeapSuffix() + "   partition by column (col1) eviction by criteria (col1 > 0) evict incoming");
      fail("EVICTION BY CRITERIA is not supported for non-HDFS tables");
    }
    catch (SQLException e) {
      if (!(e.getSQLState().equals("0A000") && e.getMessage().equals(
          "Eviction By Criteria is not supported for non-HDFS Table."))) {
        throw e;
      }
    }

    try {
      // EVICTION BY CRITERIA for partitioned non-HDFS table
      st.execute("create table t5 (col1 varchar(20) primary key, col2 int)  " + getOffHeapSuffix() + "  partition by column (col1) eviction by lrucount 1 evictaction destroy hdfsstore (hstore)");
      fail("EVICTION action is not supported for HDFS tables");
    }
    catch (SQLException e) {
      if (!(e.getSQLState().equals("0A000") && e.getMessage().equals(
          "LRU eviction is not supported for HDFS tables."))) {
        throw e;
      }
    }

  }
  /**
   * Check by querying the table if everything is right.
   * @throws Exception
   */
  public void testEvictionServiceIndex() throws Exception {

    setupConnection();

    Connection conn = jdbcConn;

    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    // eviction of data more than 10 seconds old
    final String evictClause = "{fn TIMESTAMPDIFF(SQL_TSI_SECOND, "
        + "ts, CURRENT_TIMESTAMP)} > 10";
    stmt.execute("create table e.evictTable("
        + "id varchar(20) primary key, qty int, ts timestamp"
        + ")  " + getOffHeapSuffix() + "  partition by column(id) "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria (" + evictClause
        + ") eviction frequency 5 seconds");

    LocalRegion lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    //GemFireContainer container = (GemFireContainer)lr.getUserAttribute();
    CustomEvictionAttributes evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    EvictionAttributes defEvictAttrs = lr.getAttributes()
        .getEvictionAttributes();
    // check attributes
    assertEquals(DataPolicy.HDFS_PERSISTENT_PARTITION, lr.getAttributes()
        .getDataPolicy());
    assertEquals(EvictionAlgorithm.LRU_HEAP, defEvictAttrs.getAlgorithm());
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, defEvictAttrs.getAction());
    assertNotNull(evictionAttrs);
    assertEquals(0, evictionAttrs.getEvictorStartTime());
    assertEquals(5000, evictionAttrs.getEvictorInterval());
    GfxdEvictionCriteria criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());

    // some inserts
    for (int i = 1; i <= 10; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    // sleep for 17 secs
    Thread.sleep(17000);
    // more inserts
    for (int i = 11; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    // default query
    assertTrue(stmt.execute("select * from e.evictTable"));
    ResultSet rs = stmt.getResultSet();

    Set ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    assertEquals(10, ids.size());
    // 0 - 10 should be evicted.
    for (int i = 11; i <= 20; i++) {
      assertTrue(ids.contains(i));
    }

    // query with hdfs true
    assertTrue(stmt.execute("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=true"));
    rs = stmt.getResultSet();

    ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    assertEquals(20, ids.size());
    // 0 - 10 should be evicted.
    for (int i = 1; i <= 20; i++) {
      assertTrue(ids.contains(i));
    }

    //query with hdfs false
    assertTrue(stmt.execute("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=false"));
    rs = stmt.getResultSet();

    ids = new HashSet();
    while (rs.next()) {
      int id = rs.getInt("id");
      ids.add(id);
    }
    assertEquals(10, ids.size());
    // 0 - 10 should be evicted.
    for (int i = 11; i <= 20; i++) {
      assertTrue(ids.contains(i));
    }

    assertEquals(10, lr.getCachePerfStats().getEvictions());
    assertEquals(0, lr.getCachePerfStats().getEvictionsInProgress());
    // TODO: This validation may change
    //assertEquals(30, lr.getCachePerfStats().getEvaluations());
  }

  public void testEvictIncomingDDLSupport() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    // eviction of data more than 10 seconds old
    final String evictClause = "qty > 100";
    stmt.execute("create table e.evictTable("
        + "id varchar(20) primary key, qty int, ts timestamp"
        + ")  " + getOffHeapSuffix() + "  partition by column(id) " + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria (" + evictClause + ") EVICT INCOMING ");

    LocalRegion lr = (LocalRegion)Misc.getRegion("/E/EVICTTABLE", true, false);
    GemFireContainer container = (GemFireContainer)lr.getUserAttribute();
    CustomEvictionAttributes evictionAttrs = lr.getAttributes()
        .getCustomEvictionAttributes();
    EvictionAttributes defEvictAttrs = lr.getAttributes()
        .getEvictionAttributes();
    // check attributes
    assertEquals(DataPolicy.HDFS_PERSISTENT_PARTITION, lr.getAttributes()
        .getDataPolicy());
    assertEquals(EvictionAlgorithm.LRU_HEAP, defEvictAttrs.getAlgorithm());
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, defEvictAttrs.getAction());
    assertNotNull(evictionAttrs);
    GfxdEvictionCriteria criteria = (GfxdEvictionCriteria)evictionAttrs
        .getCriteria();
    assertEquals(evictClause, criteria.getPredicateString());
    assertTrue(evictionAttrs.isEvictIncoming());

    // some inserts
    for (int i = 1; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values ('" + i + "', "
          + (i * 10) + ", CURRENT_TIMESTAMP)");
    }

    assertEquals(10, lr.size());
    CachePerfStats stats = lr.getCachePerfStats();
    assertEquals(10, stats.getEvictions());
    assertEquals(0, stats.getEvictionsInProgress());
    assertEquals(20, stats.getEvaluations());
  }

  public void testEvictIncomingQueryHDFS() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, qty int, abc int )  " + getOffHeapSuffix() + "   partition by column(id) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    stmt.execute("create index idx on e.evictTable (qty, abc)");
    // some inserts
    for (int i = 1; i <= 20; i++)
    {
      stmt.executeUpdate("insert into e.evictTable values (" + i + ", "
          + (i * 10) +", " + (i * 10) + ")");
    }

    PreparedStatement ps = conn
        .prepareStatement("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=false \n where qty=?");
    for (int i = 1; i < 20; i++)
    {
      ps.setInt(1, i * 10);
      ResultSet rs = ps.executeQuery();
      if (i > 10) {
        assertFalse(rs.next());
      } else {
        assertTrue(rs.next());
      }
    }

    ps = conn.prepareStatement("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=false \n where id=?");
    for (int i = 1; i < 20; i++) {
      ps.setInt(1, i);
      ResultSet rs = ps.executeQuery();
      if (i > 10) {
        assertFalse(rs.next());
      } else {
        assertTrue(rs.next());
      }
    }

    ps = conn
        .prepareStatement("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=true  \n where id=?");
    for (int i = 1; i < 20; i++) {
      ps.setInt(1, i);
      ResultSet rs = ps.executeQuery();
      assertTrue(rs.next());
    }

    ResultSet rs1 = stmt.executeQuery("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=true");
    Set ids = new HashSet();
    while(rs1.next()) {
      int id = rs1.getInt("id");
      ids.add(id);
    }
    assertEquals(20, ids.size());

    rs1 = stmt.executeQuery("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=false");
    ids = new HashSet();
    while(rs1.next()) {
      int id = rs1.getInt("id");
      ids.add(id);
    }
    assertEquals(10, ids.size());

    rs1 = stmt.executeQuery("select * from e.evictTable -- GEMFIREXD-PROPERTIES queryHDFS=false  \n where qty > 100");
    ids = new HashSet();
    while(rs1.next()) {
      int id = rs1.getInt("id");
      ids.add(id);
    }
    assertEquals(0, ids.size());

  }

  /**
   * Uncomment this test once defect #49965 is fixed.
   */
  public void testEvictIncomingWithPartitionKey() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, partkey int not null )  " + getOffHeapSuffix() + "  partition by column(partkey) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( id > 10 ) EVICT INCOMING ");

    // some inserts
    stmt.executeUpdate("insert into e.evictTable values (20, 200 )");

    try {
      stmt.executeUpdate("insert into e.evictTable values (20, 201)");
      fail("Did not get expected constraint violation exception");
    } catch (SQLException e) {
      if (!"23505".equals(e.getSQLState())) {
        throw e;
      }
    }

    stmt.executeUpdate("insert into e.evictTable values (30, 201 )");
    stmt.executeUpdate("delete from e.evictTable where id=30");

    //Bounce the system.
    shutDown();

  //Delete the krf to force recovery from the crf
    String currDir = System.getProperty("user.dir");
    File cdir = new File(currDir);
    String[] files = cdir.list();
    if (files != null) {
      for(String file : files) {
        if (file.matches(".*GFXD-DEFAULT-DISKSTORE.*krf")) {
          File f = new File(file);
          f.delete();
        }
      }
    }

    setupConnection();
  }

  public void testEvictIncomingWithUniqueIndex() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, partkey int not null, qty int, constraint uq unique (partkey, qty) )  " + getOffHeapSuffix() + "  partition by column(partkey) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    // some inserts
    for (int i = 1; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
    }

    try {
      stmt.executeUpdate("insert into e.evictTable values (21, 200, 2000)");
      fail("Did not get expected constraint violation exception");
    } catch (SQLException e) {
      if (!"23505".equals(e.getSQLState())) {
        throw e;
      }
    }
  }

  public void testEvictIncomingWithUniqueIndexDelete() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, partkey int not null, qty int, constraint uq unique (partkey, qty) )  " + getOffHeapSuffix() + "  partition by column(partkey) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    stmt.execute("create table e.simpleTable( id int primary key, partkey int not null, qty int, constraint uq2 unique (partkey, qty) )  " + getOffHeapSuffix() + "  partition by column(partkey) " );

    // some inserts
    for (int i = 20; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
      stmt.executeUpdate("insert into e.simpleTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
    }

    try {
      stmt.executeUpdate("insert into e.evictTable values (21, 200, 2000)");
      fail("Did not get expected constraint violation exception");
    } catch (SQLException e) {
      if (!"23505".equals(e.getSQLState())) {
        throw e;
      }
    }
    try {
      stmt.executeUpdate("insert into e.simpleTable values (21, 200, 2000)");
      fail("Did not get expected constraint violation exception");
    } catch (SQLException e) {
      if (!"23505".equals(e.getSQLState())) {
        throw e;
      }
    }
    stmt.execute("delete from e.evictTable where id= 20");
    stmt.execute("delete from e.simpleTable where id= 20");
    ResultSet rs = stmt.executeQuery("select * from e.evictTable  -- GEMFIREXD-PROPERTIES queryHDFS=true \n where id = 20 ");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from e.simpleTable where id = 20");
    assertFalse(rs.next());

    stmt.executeUpdate("insert into e.simpleTable values (21, 200, 2000)");
    stmt.executeUpdate("insert into e.evictTable values (21, 200, 2000)");
  }
  /**
   * Table with unique constraint
   * Insert one row
   * Update the one unique column
   * delete the row
   * try inserting a row with same unique value again
   * @throws Exception
   */
  public void testEvictIncomingWithUniqueIndexUpdateDelete() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, partkey int not null, qty int, constraint uq unique (partkey, qty) )  " + getOffHeapSuffix() + "  partition by column(partkey) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    stmt.execute("create table e.simpleTable( id int primary key, partkey int not null, qty int, constraint uq2 unique (partkey, qty) )  " + getOffHeapSuffix() + "  partition by column(partkey) " );

    int i = 20;
    stmt.executeUpdate("insert into e.evictTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
    //stmt.executeUpdate("insert into e.simpleTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");

    stmt.executeUpdate("update e.evictTable set qty=300 where id=20");
    //stmt.executeUpdate("insert into e.simpleTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");

    stmt.execute("delete from e.evictTable where id= 20");
    //stmt.execute("delete from e.simpleTable where id= 20");
    ResultSet rs = stmt.executeQuery("select * from e.evictTable  -- GEMFIREXD-PROPERTIES queryHDFS=true \n where id = 20 ");
    assertFalse(rs.next());

    //rs = stmt.executeQuery("select * from e.simpleTable where id = 20");
    //assertFalse(rs.next());

    //stmt.executeUpdate("insert into e.simpleTable values (21, 200, 2000)");
    stmt.executeUpdate("insert into e.evictTable values (21, 200, 2000)");
  }

  /**
   * Table with unique constraint
   * Insert one row
   * Insert again row with same unique value
   * it should throw exception
   * delete the row
   * insert the row with same unique keys again. it should succeed
   * @throws Exception
   */
  public void testEvictIncomingWithUniqueIndexUpdateDelete2() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.portfolio (cid int not null, sid int not null, qty int not null, availQty int not null, subTotal decimal(30,20), tid int, constraint portf_pk primary key (cid, sid), constraint qty_ck check (qty>=0), constraint avail_ch check (availQty>=0 and availQty<=qty))  " + getOffHeapSuffix() + "  persistent hdfsstore (hdfsdata) "
        + "EVICTION BY CRITERIA ( qty > 500  ) EVICT INCOMING ");

    stmt.executeUpdate("insert into trade.portfolio  values(3, 120, 1592, 1592, 14264.32000000000000000000 ,18)");
    try {
      stmt.executeUpdate("insert into trade.portfolio  values(3, 120, 1374, 1374, 12311.04000000000000000000, 18)");
      fail("failed");
    }
    catch(Exception c) {
      c.printStackTrace();
    }

    stmt.execute("delete from trade.portfolio where cid = 3 and sid = 120 and tid = 18");
    ResultSet rs = stmt.executeQuery("select * from trade.portfolio  -- GEMFIREXD-PROPERTIES queryHDFS=true ");
    assertFalse(rs.next());
    stmt.executeUpdate("insert into trade.portfolio  values(3, 120, 1374, 1374, 12311.04000000000000000000, 8)");
  }

  public void testEvictIncomingWithUniqueIndexUpdate() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, partkey int not null, qty int, constraint uq unique (partkey, qty) )  " + getOffHeapSuffix() + "  persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    stmt.execute("create table e.simpleTable( id int primary key, partkey int not null, qty int, constraint uq2 unique (partkey, qty) )  " + getOffHeapSuffix() + "  " );

    // some inserts
    for (int i = 20; i <= 20; i++) {
      stmt.executeUpdate("insert into e.evictTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
      stmt.executeUpdate("insert into e.simpleTable values (" + i + ", " + (i * 10) +", " + (i * 100) + ")");
    }
    //update trade.customers set
    //stmt.executeUpdate("update e.evictTable set qty=201 where id = 20");
   // stmt.executeUpdate("update e.simpleTable set qty=201 where id = 20");

    stmt.executeUpdate("update e.evictTable set qty=2002,partkey=202 where id = 20");
    stmt.executeUpdate("update e.simpleTable set qty=2002,partkey=202 where id = 20");

    ResultSet rs = stmt.executeQuery("select * from e.evictTable  -- GEMFIREXD-PROPERTIES queryHDFS=true \n where id = 20 ");
    assertTrue(rs.next());
    assertEquals(202,rs.getInt(2));
    assertEquals(2002,rs.getInt(3));
  }

  /**
   * 1. Insert a row with partition column, and primary keys as a combination of two keys so
   *    that it gets evicted
   * 2. Insert again a row with the same primary key, catch exception
   * 3. Validate there is no data in operational
   * @throws Exception
   */
  public void testEvictIncomingWithUniqueIndexUpdate2() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.portfolio (cid int not null, sid int not null, qty int not null, availQty int not null, subTotal decimal(30,20), tid int, constraint portf_pk primary key (cid, sid), constraint qty_ck check (qty>=0), constraint avail_ch check (availQty>=0 and availQty<=qty))  " + getOffHeapSuffix() + "  persistent hdfsstore (hdfsdata) "
        + "EVICTION BY CRITERIA ( qty > 500  ) EVICT INCOMING ");

    // some inserts
    stmt.executeUpdate("insert into trade.portfolio values ( 104 , 91 , 1568 , 1568 , 53500.16000000000000000000 , 6)");
    //update trade.customers set
    //stmt.executeUpdate("update e.evictTable set qty=201 where id = 20");
   // stmt.executeUpdate("update e.simpleTable set qty=201 where id = 20");
    try {
      stmt.executeUpdate("insert into trade.portfolio values ( 104 , 91 , 2000 , 2000 , 68240.00000000000000000000 ,6)");
      fail("failed");
    }
    catch(Exception e){
      e.printStackTrace();
    }
    try {
      stmt.executeUpdate("insert into trade.portfolio values ( 104 , 91 , 247 , 247 , 8427.64000000000000000000, 6)");
      fail("failed");
    }
    catch(Exception e){
      e.printStackTrace();
    }
    try {
      stmt.executeUpdate("insert into trade.portfolio values ( 104 , 91 , 1408 , 1408 , 48040.96000000000000000000, 6)");
      fail("failed");
    }
    catch(Exception e){
      e.printStackTrace();
    }

    String[] arr = {"insert into trade.portfolio values ( 104 , 91 , 1090 , 1090 , 37190.80000000000000000000 ,6)",
        "insert into  trade.portfolio  values (104 , 91 , 659 , 659 , 22485.08000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 1943 , 1943 , 66295.16000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 1051 , 1051 , 35860.12000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 1905 , 1905 , 64998.60000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 756 , 756 , 25794.72000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 432 , 432 , 14739.84000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 438 , 438 , 14944.56000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 633 , 633 , 21597.96000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 755 , 755 , 25760.60000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 1737 , 1737 , 59266.44000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 691 , 691 , 23576.92000000000000000000, 6)",
        "insert into  trade.portfolio  values (104 , 91 , 1968 , 1968 , 67148.16000000000000000000, 6)"};

    for(String st: arr) {
      try {
        stmt.executeUpdate(st);
        fail("failed");
      }
      catch(Exception e){
        e.printStackTrace();
      }
    }

    ResultSet rs = stmt.executeQuery("select * from trade.portfolio where qty > 500");
    assertFalse(rs.next());
    rs = stmt.executeQuery("select * from trade.portfolio -- GEMFIREXD-PROPERTIES queryHDFS=true \n where qty > 500 ");
    assertTrue(rs.next());
    System.out.println(rs.getInt("qty"));
    LocalRegion lr = (LocalRegion)Misc.getRegion("/TRADE/PORTFOLIO", true, false);
    System.out.println(lr.size());
    for(Object o: lr.entrySet()) {
      System.out.println("Entry : " + o);
    }
  }

  /**
   * For cheetah, foreign key constraint won't be supported with custom eviction to HDFS.
   * Defect # 49367/49452.
   */
  public void testEvictIncomingWithForeignKey() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, primary key (cid))  " + getOffHeapSuffix() + "  "
    	+ "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cid > 5 ) EVICT INCOMING ");

    String expectedMessage = "Foreign key constraint is not supported with custom eviction criteria for HDFS tables.";
    try {
      stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid), constraint cust_newt_fk foreign key (cid) references trade.customers (cid) on delete restrict)  " + getOffHeapSuffix() + "  "
          + "persistent hdfsstore (hdfsdata) "
          + "eviction by criteria ( cash > 1000 ) EVICT INCOMING ");
      fail("Expected SQLFeatureNotSupportedException as FK is not supported with custom eviction to HDFS.");
    } catch (SQLFeatureNotSupportedException e) {
      assertTrue(e.getMessage().equals(expectedMessage));
    }

    stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid), constraint cust_newt_fk foreign key (cid) references trade.customers (cid) on delete restrict)  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) ");
  }

  /**
   * Insert 3 rows. Two for NonOperational and One for operational
   * Update the one non-operational such that it becomes operational
   * Update the second non-operational such that it remains non-operational
   * @throws Exception
   */
  public void testEvictIncomingWithLocalIndexes() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, addr int, primary key (cid))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cust_name > 5 ) EVICT INCOMING ");

    // index on cust_name and addr
    stmt.execute("create index idx1 on trade.customers (cust_name)");
    stmt.execute("create index idx2 on trade.customers (addr)");

    // some inserts
    // will be evicted
    stmt.executeUpdate("insert into trade.customers values (" + 12 + ", " + (12 * 10) +", " + (12 * 100) + ")");
    stmt.executeUpdate("insert into trade.customers values (" + 13 + ", " + (13 * 10) +", " + (13 * 100) + ")");
    // will not be evicted
    stmt.executeUpdate("insert into trade.customers values (" + 1 + ", " + (1 * 1) +", " + (1 * 100) + ")");
    // check if inserting an evicted row gives error
    try {
      stmt.executeUpdate("insert into trade.customers values (" + 12 + ", " + (12 * 10) +", " + (12 * 100) + ")");
      fail("Expected Exception as the row was already inserted. ");
    }
    catch (Exception e) {

    }

    // verify the operational data.
    // 1 1 100
    ResultSet rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=1");
    assertTrue(rs.next());
    assertEquals(1, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=1");
    assertTrue(rs.next());
    assertEquals(1, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=100");
    assertTrue(rs.next());
    assertEquals(100, rs.getInt("addr"));

    // 12, 120, 1200
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=120");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertFalse(rs.next());
    // 13, 130, 1300
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=13");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=130");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1300");
    assertFalse(rs.next());

    // verify the non operational data.
    // 12,120,1200
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=12");
    assertTrue(rs.next());
    assertEquals(12, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=120");
    assertTrue(rs.next());
    assertEquals(120, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1200");
    assertTrue(rs.next());
    assertEquals(1200, rs.getInt("addr"));
    // 13,130,1300
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=13");
    assertTrue(rs.next());
    assertEquals(13, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=130");
    assertTrue(rs.next());
    assertEquals(130, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1300");
    assertTrue(rs.next());
    assertEquals(1300, rs.getInt("addr"));

    // making a change to evicted row such that EvictionCriteria is not satisfied.
    stmt.executeUpdate("update trade.customers set cust_name=4 where cid=12");

    // it should be back in operational data
    // 12,4,1200
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertTrue(rs.next());
    assertEquals(12, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=4");
    assertTrue(rs.next());
    assertEquals(4, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertTrue(rs.next());
    assertEquals(1200, rs.getInt("addr"));

    // making a change to evicted row such that EvictionCriteria is satisfied.
    stmt.executeUpdate("update trade.customers set cust_name=15 where cid=13");
    // 13, 15, 1300 in non-operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=13");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=15");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1300");
    assertFalse(rs.next());

    // 13,15,1300
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=13");
    assertTrue(rs.next());
    assertEquals(13, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=15");
    assertTrue(rs.next());
    assertEquals(15, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1300");
    assertTrue(rs.next());
    assertEquals(1300, rs.getInt("addr"));

    LocalRegion lr = (LocalRegion)Misc.getRegion("/TRADE/CUSTOMERS", true, false);
    //TODO: check if this assumtion is correct!
    //assertEquals(2, lr.size());
  }

  /**
   * 1. Insert one row which satisfies eviction criteria
   * 2. Make change such that it doesn't satisfy eviction criteria
   * 3. Verify
   * 4. Delete the row
   * 5. Verify
   * 6. Insert again
   * 7. Verify
   * 8. Delete
   * 9. Verify
   *
   * @throws Exception
   */
  public void testEvictIncomingWithLocalIndexesMultipleOperations() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, addr int, primary key (cid))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cust_name > 5 ) EVICT INCOMING ");

    // index on cust_name and addr
    stmt.execute("create index idx1 on trade.customers (cust_name)");
    stmt.execute("create index idx2 on trade.customers (addr)");

    // insert that will be evicted
    stmt.executeUpdate("insert into trade.customers values (" + 12 + ", " + (12 * 10) +", " + (12 * 100) + ")");
    ResultSet rs = null;
    // making a change to evicted row such that EvictionCriteria is not satisfied.
    stmt.executeUpdate("update trade.customers set cust_name=4 where cid=12");
    //Verify
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertTrue(rs.next());
    assertEquals(12, rs.getInt("cid"));
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=4");
    assertTrue(rs.next());
    assertEquals(4, rs.getInt("cust_name"));
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertTrue(rs.next());
    assertEquals(1200, rs.getInt("addr"));

    //Delete the row
    stmt.execute("delete from trade.customers where cid=12");
    // Verify
    // operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=4");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertFalse(rs.next());
    // Non-Operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=4");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1200");
    assertFalse(rs.next());
    // Insert the same row again
    stmt.executeUpdate("insert into trade.customers values (" + 12 + ", " + (12 * 10) +", " + (12 * 100) + ")");
    // Verify
    // Operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=4");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertFalse(rs.next());

    // Non-operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=12");
    assertTrue(rs.next());
    assertEquals(12, rs.getInt("cid"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=120");
    assertTrue(rs.next());
    assertEquals(120, rs.getInt("cust_name"));

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1200");
    assertTrue(rs.next());
    assertEquals(1200, rs.getInt("addr"));

    // Delete the row
    stmt.execute("delete from trade.customers where cid=12");
    // Verify
    // Operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cust_name=4");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=false \n where addr=1200");
    assertFalse(rs.next());
    // Non_operational
    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=12");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cust_name=4");
    assertFalse(rs.next());

    rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true \n where addr=1200");
    assertFalse(rs.next());

    LocalRegion lr = (LocalRegion)Misc.getRegion("/TRADE/CUSTOMERS", true, false);
    assertEquals(0, lr.size());
  }

  public void testEvictIncomingWithLocalIndexesFailedOperation() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.portfolio (cid int not null, sid int not null, qty int not null, availQty int not null, constraint portf_pk primary key (cid, sid), constraint qty_ck check (qty>=0), constraint avail_ch check (availQty>=0 and availQty<=qty))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    // some inserts
    stmt.executeUpdate("insert into trade.portfolio values (" + 1 + ", " + 2 +", " + (2 * 1000) + " , " +  2 * 100 + ")");
    // ensure that it goes to hdfs
    // TODO: Use flush operation instead of waiting
    Thread.sleep(10000);
    try {
      stmt.executeUpdate("insert into trade.portfolio values (" + 1 + ", " + 2 +", " + (2 * 10) + " , " +  2 * 1 + ")");
      fail("Expected Exception as the row was already inserted in the table.");
    }
    catch ( Exception e) {
    }

    // Verify the table
    ResultSet rs = null;
    rs = stmt.executeQuery("select * from trade.portfolio -- GEMFIREXD-PROPERTIES queryHDFS=false \n where cid=1");
    assertFalse(rs.next());
    rs = stmt.executeQuery("select * from trade.portfolio -- GEMFIREXD-PROPERTIES queryHDFS=true \n where cid=1");
    assertTrue(rs.next());
    assertEquals(1,rs.getInt("cid"));
    assertEquals(2,rs.getInt("sid"));
    assertEquals(2000,rs.getInt("qty"));
    assertEquals(200,rs.getInt("availQty"));

    // TODO: Verify the size of the region
    LocalRegion lr = (LocalRegion)Misc.getRegion("/TRADE/PORTFOLIO", true, false);
    //assertEquals(0, lr.size());
  }

  public void testEvictIncomingWithTrigger() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();
    stmt.execute("create table e.evictTable_history( id int primary key, qty int, abc int )  " + getOffHeapSuffix() + "  ");

    String insertStmt =  "INSERT INTO e.evictTable_history  VALUES (  NEWROW.id ,  NEWROW.qty , NEWROW.abc )";
    String delStmt =  "DELETE FROM e.evictTable_history  WHERE id=OLDROW.id";

    String insertTriggerStmt =  "CREATE TRIGGER  e.evictTable_INSERTTRIGGER AFTER INSERT ON e.evictTable REFERENCING NEW AS NEWROW FOR EACH ROW  " + insertStmt ;
    String deleteTriggerStmt =  "CREATE TRIGGER  e.evictTable_DELETETRIGGER AFTER DELETE ON e.evictTable REFERENCING OLD AS OLDROW  FOR EACH ROW " + delStmt;
    String updateTriggerStmt =  "CREATE TRIGGER  e.evictTable_DELETEFORUPDATE AFTER UPDATE ON e.evictTable REFERENCING NEW AS NEWROW OLD AS OLDROW FOR EACH ROW  " + delStmt;
    String updateTriggerStmt1 = "CREATE TRIGGER  e.evictTable_INSERTFORUPDATE AFTER UPDATE ON e.evictTable REFERENCING NEW AS NEWROW OLD AS OLDROW FOR EACH ROW " + insertStmt;

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table e.evictTable( id int primary key, qty int, abc int )  " + getOffHeapSuffix() + "  partition by column(id) persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( qty > 100 ) EVICT INCOMING ");

    stmt.execute(insertTriggerStmt);
    stmt.execute(deleteTriggerStmt);
    stmt.execute(updateTriggerStmt);
    stmt.execute(updateTriggerStmt1);

    stmt.execute("insert into e.evictTable values (1, 1, 200)");
    stmt.execute("insert into e.evictTable values (2, 2, 200)");
    stmt.execute("insert into e.evictTable values (3, 200, 200)");
    stmt.execute("update e.evictTable set qty = 300 where id=3");
    stmt.execute("update e.evictTable set qty = 500 where id=2");
    ResultSet actualRs = stmt.executeQuery("select * from e.evictTable");
    while (actualRs.next()) {
      assertEquals(1,actualRs.getInt("qty"));
      assertEquals(1,actualRs.getInt("id"));
    }

    ResultSet triggerRs = stmt.executeQuery("select * from e.evictTable_history");
    Set s1 = new HashSet();
    Set s2 = new HashSet();
    while(triggerRs.next()) {
      s1.add(triggerRs.getInt("id"));
      s2.add(triggerRs.getInt("qty"));
    }
    assertEquals(3, s1.size());
    assertEquals(3, s2.size());
    assertTrue(s1.contains(1));
    assertTrue(s1.contains(2));
    assertTrue(s1.contains(3));
    assertTrue(s2.contains(1));
    assertTrue(s2.contains(300));
    assertTrue(s2.contains(500));

  }

  /**
   * FK constraint defined on parent table (customers) along with custom eviction criteria.
   * Insert on child table should not throw SQLIntegrityException though parent row is
   * evicted.
   */
  public void testEvictIncomingWithForeignKey2() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, primary key (cid))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cid > 5 ) EVICT INCOMING ");

    stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid), constraint cust_newt_fk foreign key (cid) references trade.customers (cid) on delete restrict)  " + getOffHeapSuffix() + "  "
        + " persistent hdfsstore (hdfsdata) ");

    // some inserts
    stmt.executeUpdate("insert into trade.customers values (" + 12 + ", " + (12 * 100) + ")");
    stmt.executeUpdate("insert into trade.networth values (" + 12 + ", "+ 12 + ", " + (12 * 100) + ")");

    stmt.executeUpdate("insert into trade.customers values (" + 11 + ", " + (11 * 10) + ")");
    stmt.executeUpdate("insert into trade.networth values (" + 11 + ", "+ 11 + ", " + (11 * 10) + ")");
    try {
      stmt.executeUpdate("delete from trade.customers where cid=11");
      fail("Expected SQLIntegrityConstraintViolationException");
    } catch (SQLException e) {
      if (!"23503".equals(e.getSQLState())) {
        throw e;
      }
    }

    stmt.executeUpdate("update trade.customers set cust_name=1100 where cid=11");
    stmt.executeUpdate("update trade.networth set cash=2000 where cid=11");

    ResultSet rs = stmt.executeQuery("select * from trade.customers -- GEMFIREXD-PROPERTIES queryHDFS=true");

    while(rs.next()) {
      System.out.println(rs.getInt("cid"));
      System.out.println(rs.getInt("cust_name"));
    }
    System.out.println("END");
  }

  /**
   * Eviction already defined on HDFS table. Alter the table to add a foreign key constraint.
   */
  public void testEvictIncomingWithAlterTableAddForeignKeyConstraint() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, primary key (cid))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cid > 5 ) EVICT INCOMING ");

    stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid))  " + getOffHeapSuffix() + "  "
        + " persistent hdfsstore (hdfsdata)"
        + " eviction by criteria ( cash > 1000 ) EVICT INCOMING ");

    try {
      stmt.execute("alter table trade.networth add constraint " +
    	  "cust_newt_fk foreign key (cid) references trade.customers (cid)");
    } catch (SQLFeatureNotSupportedException e) {
      //Expected. Do nothing.
    }
  }

  /**
   * No eviction criteria defined on HDFS table.
   * Alter the table to add a foreign key constraint.
   */
  public void testEvictIncomingWithAlterTableAddForeignKeyConstraint_2() throws Exception {
    setupConnection();

    Connection conn = jdbcConn;
    Statement stmt = conn.createStatement();

    stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
        + HDFS_DIR + "' QUEUEPERSISTENT true");

    stmt.execute("create table trade.customers (cid int not null, cust_name int, primary key (cid))  " + getOffHeapSuffix() + "  "
        + "persistent hdfsstore (hdfsdata) "
        + "eviction by criteria ( cid > 5 ) EVICT INCOMING ");

    stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid))  " + getOffHeapSuffix() + "  "
        + " persistent hdfsstore (hdfsdata)");

    stmt.execute("alter table trade.networth add constraint " +
        "cust_newt_fk foreign key (cid) references trade.customers (cid)");

  }

  public static void dumpAll() {
    try {
      GfxdDumpLocalResultMessage msg = new GfxdDumpLocalResultMessage();
      InternalDistributedSystem sys = InternalDistributedSystem
          .getConnectedInstance();
      msg.send(sys, null);
      msg.executeLocally(sys.getDistributionManager(), false);
      GfxdDumpLocalResultMessage.sendBucketInfoDumpMsg(null, false);
    } catch (Throwable t) {
      throw new RuntimeException(t.getMessage());
    }
  }

  protected String getOffHeapSuffix() {
    return " ";
  }

}


text:
package org.apache.spark.sql.execution.datasources.v2

import java.util.{Locale, OptionalLong}

import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.fs.Path

import org.apache.spark.internal.Logging
import org.apache.spark.internal.config.IO_WARNING_LARGEFILETHRESHOLD
import org.apache.spark.sql.{AnalysisException, SparkSession}
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
import org.apache.spark.sql.connector.read.{Batch, InputPartition, Scan, Statistics, SupportsReportStatistics}
import org.apache.spark.sql.execution.PartitionedFileUtil
import org.apache.spark.sql.execution.datasources._
import org.apache.spark.sql.sources.Filter
import org.apache.spark.sql.types.StructType
import org.apache.spark.util.Utils

abstract class FileScan(
    sparkSession: SparkSession,
    fileIndex: PartitioningAwareFileIndex,
    readDataSchema: StructType,
    readPartitionSchema: StructType)
  extends Scan
  with Batch with SupportsReportStatistics with Logging {
  /**
   * Returns whether a file with `path` could be split or not.
   */
  def isSplitable(path: Path): Boolean = {
    false
  }

  /**
   * If a file with `path` is unsplittable, return the unsplittable reason,
   * otherwise return `None`.
   */
  def getFileUnSplittableReason(path: Path): String = {
    assert(!isSplitable(path))
    "undefined"
  }

  override def description(): String = {
    val locationDesc =
      fileIndex.getClass.getSimpleName + fileIndex.rootPaths.mkString("[", ", ", "]")
    val metadata: Map[String, String] = Map(
      "ReadSchema" -> readDataSchema.catalogString,
      "Location" -> locationDesc)
    val metadataStr = metadata.toSeq.sorted.map {
      case (key, value) =>
        val redactedValue =
          Utils.redact(sparkSession.sessionState.conf.stringRedactionPattern, value)
        key + ": " + StringUtils.abbreviate(redactedValue, 100)
    }.mkString(", ")
    s"${this.getClass.getSimpleName} $metadataStr"
  }

  protected def partitions: Seq[FilePartition] = {
    val selectedPartitions = fileIndex.listFiles(Seq.empty, Seq.empty)
    val maxSplitBytes = FilePartition.maxSplitBytes(sparkSession, selectedPartitions)
    val partitionAttributes = fileIndex.partitionSchema.toAttributes
    val attributeMap = partitionAttributes.map(a => normalizeName(a.name) -> a).toMap
    val readPartitionAttributes = readPartitionSchema.map { readField =>
      attributeMap.get(normalizeName(readField.name)).getOrElse {
        throw new AnalysisException(s"Can't find required partition column ${readField.name} " +
          s"in partition schema ${fileIndex.partitionSchema}")
      }
    }
    lazy val partitionValueProject =
      GenerateUnsafeProjection.generate(readPartitionAttributes, partitionAttributes)
    val splitFiles = selectedPartitions.flatMap { partition =>
      // Prune partition values if part of the partition columns are not required.
      val partitionValues = if (readPartitionAttributes != partitionAttributes) {
        partitionValueProject(partition.values).copy()
      } else {
        partition.values
      }
      partition.files.flatMap { file =>
        val filePath = file.getPath
        PartitionedFileUtil.splitFiles(
          sparkSession = sparkSession,
          file = file,
          filePath = filePath,
          isSplitable = isSplitable(filePath),
          maxSplitBytes = maxSplitBytes,
          partitionValues = partitionValues
        )
      }.toArray.sortBy(_.length)(implicitly[Ordering[Long]].reverse)
    }

    if (splitFiles.length == 1) {
      val path = new Path(splitFiles(0).filePath)
      if (!isSplitable(path) && splitFiles(0).length >
        sparkSession.sparkContext.getConf.get(IO_WARNING_LARGEFILETHRESHOLD)) {
        logWarning(s"Loading one large unsplittable file ${path.toString} with only one " +
          s"partition, the reason is: ${getFileUnSplittableReason(path)}")
      }
    }

    FilePartition.getFilePartitions(sparkSession, splitFiles, maxSplitBytes)
  }

  override def planInputPartitions(): Array[InputPartition] = {
    partitions.toArray
  }

  override def estimateStatistics(): Statistics = {
    new Statistics {
      override def sizeInBytes(): OptionalLong = {
        val compressionFactor = sparkSession.sessionState.conf.fileCompressionFactor
        val size = (compressionFactor * fileIndex.sizeInBytes).toLong
        OptionalLong.of(size)
      }

      override def numRows(): OptionalLong = OptionalLong.empty()
    }
  }

  override def toBatch: Batch = this

  override def readSchema(): StructType =
    StructType(readDataSchema.fields ++ readPartitionSchema.fields)

  // Returns whether the two given arrays of [[Filter]]s are equivalent.
  protected def equivalentFilters(a: Array[Filter], b: Array[Filter]): Boolean = {
    a.sortBy(_.hashCode()).sameElements(b.sortBy(_.hashCode()))
  }

  private val isCaseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis

  private def normalizeName(name: String): String = {
    if (isCaseSensitive) {
      name
    } else {
      name.toLowerCase(Locale.ROOT)
    }
  }
}


text:
FROM loveitlabs/rails-server:latest
MAINTAINER LoveItLabs Team <team@loveitlabs.io>

WORKDIR /$APPROOT
ENV APPROOT app

#By putting this at the beginning of the file, you can add ENV directives
#or other commands and not invalidate the bundle cache- saving you a lot of pain.
ADD Gemfile /$APPROOT/
ADD Gemfile.lock /$APPROOT/
ENV BUNDLE_PATH=/bundle
RUN bundle config --global --jobs 16 &&\
    bundle install -j16

ENV TERM vt100
#ENV RAILS_ENV staging
ENV RAILS_ENV production

# Output of `rake secret` Should really be passed in as params and only stored in super secret encrypted vault.
# Set these up in config/secrets.yml Some apps don't have a stage environment by default- but they probably should ;)
ENV SECRET_KEY_BASE_STAGE 8698fca2fbf1e8d713cef827e9445915f03f7cdabc663fd24ac68a9c2a349fa910baa441115d76b138f24e504f9982c21adf1a8911578b57adfc656bb42e1716
ENV SECRET_KEY_BASE_PROD  f491fdf0e84319cb40d980627912d3bbe5a32c44ee98625182a5a057bafa53c9dce3ea4d5e9f5e3455429f4cdd16a9e4003c35f88dcaa3755e7cd4f8ceb46e82

#Add the rails application to the docker image.
ADD nginx.vhost /etc/nginx/sites-enabled/
ADD config /$APPROOT/
ADD Rakefile /$APPROOT/
ADD . /$APPROOT/

#supervisor already installed in base image.
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

CMD cd /app &&\
    bundle exec rake assets:precompile &&\
    #bundle exec rake user:add_roles &&\
    #bundle exec rake script:add_context &&\
    bundle exec rake db:migrate &&\
    bash -c "/usr/bin/supervisord -c /app/supervisord.conf"

EXPOSE 80


text:
+function ($) {
	'use strict';

	var ajaxFormScriptURL = $("script[src]").last().attr("src").split('?')[0].split('/').slice(0, -2).join('/')+'/';

	var AjaxForm = function (element, options)
	{
		var myAjaxForm = this;

		myAjaxForm.options = $.extend(true, {}, $.fn.ajaxform.defaults, options);
		myAjaxForm.$form = $(element);

		myAjaxForm.$form.addClass('ajax-form');

		myAjaxForm.$form.find('.ajax-form_submit').click(function() {
			myAjaxForm.$form.submit();
		});

		if (myAjaxForm.options.placeholders.both != null) {
			myAjaxForm.options.placeholders.success = myAjaxForm.options.placeholders.both;
			myAjaxForm.options.placeholders.error = myAjaxForm.options.placeholders.both;
		}
		else {
			if (myAjaxForm.options.placeholders.success == null) {
				myAjaxForm.options.placeholders.success = '.ajax-form_success_placeholder';
				myAjaxForm.$form.find(myAjaxForm.options.placeholders.success).remove(); // TODO check if required to remove parent .container-fluid
				myAjaxForm.$form.prepend(
						'
' +
						'
' +
						'
' +
						'			<button type="button" class="close" aria-label="Close">×</button>' +
						'			' +
						'			' +
						'
' +
						'
' +
						'
'
				);
				myAjaxForm.$form.find(myAjaxForm.options.placeholders.success).hide().removeClass('hidden');
			}

			if (myAjaxForm.options.placeholders.error == null) {
				myAjaxForm.options.placeholders.error = '.ajax-form_error_placeholder';
				myAjaxForm.$form.find(myAjaxForm.options.placeholders.error).remove(); // TODO check if required to remove parent .container-fluid
				myAjaxForm.$form.prepend(
						'
' +
						'
' +
						'
' +
						'			<button type="button" class="close" aria-label="Close">×</button>' +
						'			' +
						'			' +
						'
' +
						'
' +
						'
'
				);
				myAjaxForm.$form.find(myAjaxForm.options.placeholders.error).hide().removeClass('hidden');
			}
		}

		myAjaxForm.options.placeholders.any = myAjaxForm.options.placeholders.success + ', ' + myAjaxForm.options.placeholders.error;

		if (myAjaxForm.options.transitions.show.both != null) {
			myAjaxForm.options.transitions.show.success = myAjaxForm.options.transitions.show.both;
			myAjaxForm.options.transitions.show.error = myAjaxForm.options.transitions.show.both;
		}

		if (myAjaxForm.options.transitions.hide.both != null) {
			myAjaxForm.options.transitions.hide.success = myAjaxForm.options.transitions.hide.both;
			myAjaxForm.options.transitions.hide.error = myAjaxForm.options.transitions.hide.both;
		}

		if (myAjaxForm.options.callbacks.both != null) {
			myAjaxForm.options.callbacks.success = myAjaxForm.options.callbacks.both;
			myAjaxForm.options.callbacks.error = myAjaxForm.options.callbacks.both;
		}

		myAjaxForm.$form.find('button.close').click(function() {
			myAjaxForm.clearAlert($(this).closest(myAjaxForm.options.placeholders.any));
		});

		myAjaxForm.$form.submit(function(event) {

			event.stopPropagation();
			event.preventDefault();

			myAjaxForm.clearAlert(
				myAjaxForm.$form.find(myAjaxForm.options.placeholders.any),
				function()
				{
					var data = myAjaxForm.$form.serialize();

					var submission = $.ajax({
						type: myAjaxForm.$form.attr('method') || 'post',
						url: myAjaxForm.$form.attr('action'),
						data: data,
						dataType: "json",
						timeout: myAjaxForm.options.timeout
					})
					.done(function(result, status, jqXHR)
					{
						if (typeof result.code !== 'undefined' && result.code === 0)
						{
							myAjaxForm.showAlert('success', jqXHR);

							if (myAjaxForm.options.resetOnSuccess == true)
							{
								myAjaxForm.$form[0].reset();
							}

							if ($.isFunction(myAjaxForm.options.callbacks.success))
							{
								if (typeof result.callback_vars !== 'undefined')
								{
									myAjaxForm.options.callbacks.success(myAjaxForm, result.callback_vars);
								}
								else
								{
									myAjaxForm.options.callbacks.success(myAjaxForm);
								}
							}
						}
						else
						{
							myAjaxForm.showAlert('error', jqXHR);

							if ($.isFunction(myAjaxForm.options.callbacks.error))
							{
								if (typeof result.callback_vars !== 'undefined')
								{
									myAjaxForm.options.callbacks.error(myAjaxForm, result.callback_vars);
								}
								else
								{
									myAjaxForm.options.callbacks.error(myAjaxForm);
								}
							}
						}
					})
					.fail(function(jqXHR, status, errorThrown)
					{
						myAjaxForm.showAlert('error', jqXHR);

						if ($.isFunction(myAjaxForm.options.callbacks.error))
						{
							if (typeof jqXHR.callback_vars !== 'undefined')
							{
								myAjaxForm.options.callbacks.error(myAjaxForm, jqXHR.callback_vars);
							}
							else
							{
								myAjaxForm.options.callbacks.error(myAjaxForm);
							}
						}
					});
				}
			);
		});

		if ($.isFunction(myAjaxForm.options.init)) {
			myAjaxForm.options.init(myAjaxForm);
		}
	};

	AjaxForm.prototype.loadJSONResource = function(resource)
	{
		var resourceContent = null;
		$.ajax({
			async: false,
			url: resource,
			dataType: "json",
			success: function(result) {
				resourceContent = result;
			},
			error: function(request, status, err) {
				console.error("Unable to load '" + resource + "'");
			}
		});
		return resourceContent;
	};

	AjaxForm.prototype.getLocalizedText = function(key, params)
	{
		var myAjaxForm = this;

		if (myAjaxForm.localizedTexts == null) {
			myAjaxForm.localizedTexts = myAjaxForm.loadJSONResource(ajaxFormScriptURL + 'locales/' + myAjaxForm.options.locale + '/ajax-form-texts.json');
		}
		var text = myAjaxForm.localizedTexts[key];
		if (text !== 'undefined' && text != null && params != null && params instanceof Array) {
			for (var i = 0; i < params.length; i++) {
				text = text.replace('{' + i + '}', params[i]);
			}
		}
		return text;
	}

	AjaxForm.prototype.showAlert = function(type, jqXHR)
	{
		var myAjaxForm = this;
		var message = '';

		var content = jqXHR.responseJSON;

		// In case of content directly at the root
		if (typeof content === 'string')
		{
			message = content;
		}
		else if (content instanceof Array)
		{
			message = content.join('
');
		}
		else if (content instanceof Object)
		{
			for (var property in content)
			{
				if (content.hasOwnProperty(property))
				{
					for (var i = 0; i < content[property].length; i++)
					{
						message += '
 • ' + content[property][i];
						myAjaxForm.$form.find('[name=' + property + ']').closest('.form-group').addClass('has-error');
					}
				}
			}
		}

		// In case of code + message objects
		if (typeof content !== 'undefined' && typeof content.code !== 'undefined' && typeof content.message !== 'undefined')
		{
			if (typeof content.message === 'string')
			{
				message = content.message;
			}
			else if (content.message instanceof Array)
			{
				message = content.message.join('
');
			}
		}

		// In case of errors array
		if (typeof content !== 'undefined' && typeof content.errors !== 'undefined')
		{
			for (var property in content.errors)
			{
				if (content.errors.hasOwnProperty(property))
				{
					for (var i = 0; i < content.errors[property].length; i++)
					{
						message += '
 • ' + content.errors[property][i];
						myAjaxForm.$form.find('[name=' + property + ']').closest('.form-group').addClass('has-error');
					}
				}
			}
		}

		// In case of message still empty
		if (message == '' || message == 'undefined' )
		{
			message = myAjaxForm.getLocalizedText(type, [jqXHR.statusText]);
		}

		// Setting message
		var placeholderSelector = eval('myAjaxForm.options.placeholders.' + type);
		var $placeholder = myAjaxForm.$form.find(placeholderSelector);
		myAjaxForm.$form.find($placeholder).find('.ajax-form_message').html(message);

		// Starting transition
		myAjaxForm.options.transitions.show($placeholder);
	};

	AjaxForm.prototype.clearAllAlerts = function(callback)
	{
		var myAjaxForm = this;

		myAjaxForm.clearAlert(myAjaxForm.$form.find(myAjaxForm.options.placeholders.any), callback);
	}

	AjaxForm.prototype.clearAlert = function($placeholder, callback)
	{
		var myAjaxForm = this;

		$.when(
			myAjaxForm.options.transitions.hide($placeholder)
		).then(function()
		{
			$placeholder.find('.ajax-form_message, .ajax-form_message').empty();
			myAjaxForm.$form.find('.has-error').removeClass('has-error');

			if ($.isFunction(callback))
			{
				callback();
			}
		});
	};

	AjaxForm.prototype.serialize = function()
	{
	    var o = {};
	    var a = this.serializeArray();
	    $.each(a, function()
	    {
	        if (o[this.name] !== undefined)
	        {
	            if (!o[this.name].push)
	            {
	                o[this.name] = [o[this.name]];
	            }
	            o[this.name].push(this.value || '');
	        } else {
	            o[this.name] = this.value || '';
	        }
	    });
	    return o;
	};

	$.fn.ajaxform = function (options)
	{
		return new AjaxForm(this, options);
	};

	$.fn.ajaxform.defaults = {
		placeholders: {
			both: null,
			error: null,
			success: null
		},
		transitions: {
			show: function($placeholder) {
				$placeholder.css('opacity', 0).slideDown().animate(
					{ opacity: 1 },
					{ queue: false }
				);
			},
			hide: function($placeholder) {
				$placeholder.slideUp().animate(
					{ opacity: 0 },
					{ queue: false }
				);
			}
		},
		callbacks: {
			both: null,
			error: null,
			success: null
		},
		init: null,
		locale: 'en',
		resetOnSuccess: true,
		timeout: 60000
	};

}(jQuery);


text:
#sidebar-left {
    display: none;
}

#mainheader {
    display: none;
}

.visible {
    display: block !important;
}

/*
.ng-enter {
    -webkit-filter: blur(6px);
     -webkit-transition: 0.3s ease-in all;
	transition: all 0.3s ease-in 0.3s;
}

.ng-enter.ng-enter-active {
    -webkit-filter: blur(0px);
}

.ng-leave {
    -webkit-filter: blur(0px);
    -webkit-transition: all 0.3s ease-out;
	transition: 0.3s ease-out all;
}

.ng-leave.ng-leave-active {
    -webkit-filter: blur(6px);
}*/

.input-updating {
    -webkit-filter: blur(2px);
    opacity: 0.7;
}

.icon-spinner {
    background-image: url(../../images/theme/spinner.gif);
    width: 16px;
    height: 16px;
}

.quick-button {
    opacity: 1;

    -webkit-transition: 0.3s ease-out opacity; /* Chrome */
	transition: 0.3s ease-out opacity;

}
.quick-button.disabled {
    pointer-events: none;
    opacity: 0.6;
    -webkit-transition: 0.3s ease-out opacity; /* Chrome */
	transition: 0.3s ease-out opacity;
}

.fade-enter {
	-webkit-transition: 0.3s ease-in all; /* Chrome */
	transition: 0.3s ease-in all;
    opacity: 0;
}

.fade-enter.fade-enter-active {
    	-webkit-transition: 0.3s ease-in all; /* Chrome */
	transition: 0.3s ease-in all;

    opacity: 1;
}
.block {
    display: block !important;
}