text:
"use strict";

let mongodb     = require('mongodb');
let path        = require('path');
let fs          = require('fs');
let Q           = require('q');
let deepcopy    = require('deepcopy');
var extend      = require('extend');
let R           = require('../../common/loadR');
var config      = require('../../common/config.js');

var uri = 'mongodb://'+config.mongoLab.user+':'+config.mongoLab.password
+'@'+config.mongoLab.host+':'+config.mongoLab.port
+'/'+config.mongoLab.name;

//use eval so that R's are visible...
JSON.minify = JSON.minify || require("node-json-minify");
let recipes;
eval('recipes = '+JSON.minify(fs.readFileSync(path.resolve(__dirname, 'mock.json'), 'utf8')));

// set the ObjectIDs to be the mock names
for (var i=0; i<recipes.length; i++) {
	var tmpID = 'mock'+i.toString();
	recipes[i]['_id'] = mongodb.ObjectID(Array(1+12-tmpID.length).join("_")+tmpID);
}

mongodb.MongoClient.connect(uri, function (err, db) {
	if ( err ) throw new Error(err);

	db.dropCollection(config.mongoLab.recipes, function (err,res) {
		// keep going whether or not the drop collection passed.
		//if ( err ) throw new Error(err);

		db.createCollection(config.mongoLab.recipes, function (err, collection) {
			if ( err ) throw new Error(err);

			collection.insert(recipes, function (err, result) {
				if ( err ) throw new Error(err);
				db.close();
			});
		});
	});
});

/*
Q.nfcall(mongodb.MongoClient.connect, uri)
.then( dropCollection )
.then( createAndInsert )
.then( closeDB )
.catch(
		function ( reason ) {
			console.log("Connect error: "+reason);
			throw new Error(reason)
		}
);

function dropCollection ( db ) {
	// drop the recipe collection then pass on the db regardless of pass/fail
	var defer = Q.defer();
	db.dropCollection(config.mongoLab.recipes, function (err,res) {
		defer.resolve(db);
	});
	return defer.promise;
}

function createAndInsert ( db ) {
	var defer = Q.defer();
	db.createCollection(config.mongoLab.recipes, function (err, collection) {
		if ( err )
			throw new Error(err);
		collection.insert(recipes, function (err, result) {
			if ( err ) { defer.reject(err); }
			else       { defer.resolve(db); }
		});
	});
	return defer.promise;
}

function closeDB ( db ) {
	db.close();
	return Q(true);
}

*/


text:
<?xml version="1.0" encoding="utf-8"?>

<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
                       android:accountType="@string/account_type" />

redpajama_set_name: RedPajamaGithub


text:
(function() {
var app = angular.module("myApp");

	app.factory("symbolsGeneratorService", ["constantsModel", function(constantsModel) {

		var symbolsGeneratorService = {};

		symbolsGeneratorService.generateSymbols = function(r) {
			var symbols = [];

			for (i = 0; i < r; i++) {
				symbols.push(constantsModel.codePosibleSymbols[i]);
			}

			return symbols;
		}

		return symbolsGeneratorService;

	}]);
})();


text:
package com.cineplex.service;

import java.util.List;

import com.cineplex.entity.Activity;
import com.cineplex.entity.BankCard;
import com.cineplex.entity.FeeRecord;
import com.cineplex.entity.Member;

/**
 * interface of service for member operation
 * @author Andy 1993sj19993@gmail.com
 * @date 2015年3月4日 上午11:28:45
 *
 */

public interface MemberService {
	/**
	 * check if a member is valid
	 * @param accountName
	 * @param password
	 * @return boolean: result of login
	 * @throws
	 */
	public Member login(String accountName, String password);

	/**
	 * register a new member
	 * @param member
	 * @return boolean: success or not
	 * @throws
	 */
	public boolean register(Member member);

	/**
	 * recharge money into a bank account
	 * @param bankCardId
	 * @param money
	 * @return boolean:
	 * @throws
	 */
	public boolean recharge(long bankCardId, int money);

	/**
	 * check bank account information for a member
	 * @param id
	 * @return BankCard:
	 * @throws
	 */
	public BankCard checkBankAccount(int id);

	/**
	 * get activities which are still active
	 * @param id
	 * @return List<Activity>:
	 * @throws
	 */
	public List<Activity> getAvaibleActivities(int id);

	/**
	 * add a record for a member attending a activity
	 * @param id
	 * @param activityId
	 * @param answer:
	 * @return void:
	 * @throws
	 */
	public void attendActivity(int id, int activityId, int answer);

	/**
	 * buy a ticket by a member card
	 * @param id: member card id
	 * @param money:
	 * @return void:
	 * @throws
	 */
	public boolean buyTicketsByCard(int id, int money);

	/**
	 * buy a ticket by integral in a member card
	 * @param id
	 * @param money
	 * @return boolean:
	 * @throws
	 */
	public boolean buyTicketByIntegral(int id, int money);

	/**
	 * get an activity information by its id
	 * @param activityId
	 * @return Activity:
	 * @throws
	 */
	public Activity getActivityById(int activityId);

	/**
	 * get consumption records of a member
	 * @param id
	 * @return List<FeeRecord>:
	 * @throws
	 */
	public List<FeeRecord> getConsumption(int id);

	/**
	 * get rechrage records of a member
	 * @param id
	 * @return List<FeeRecord>:
	 * @throws
	 */
	public List<FeeRecord> getRecharge(int id);
}


text:
namespace enterprise_connectors {

// Linux implementation of the KeyPersistenceDelegate interface.
class LinuxKeyPersistenceDelegate : public KeyPersistenceDelegate {
 public:
  ~LinuxKeyPersistenceDelegate() override;

  // KeyPersistenceDelegate:
  bool StoreKeyPair(KeyPersistenceDelegate::KeyTrustLevel trust_level,
                    std::vector<uint8_t> wrapped) override;
  KeyPersistenceDelegate::KeyInfo LoadKeyPair() override;
  std::unique_ptr<crypto::UnexportableKeyProvider> GetTpmBackedKeyProvider()
      override;
};

}  // namespace enterprise_connectors

#endif  // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_CORE_PERSISTENCE_LINUX_KEY_PERSISTENCE_DELEGATE_H_


text:
package com.crowdin.cli.commands.functionality;

import com.crowdin.cli.client.models.FileBuilder;
import com.crowdin.client.sourcefiles.model.File;
import com.crowdin.client.sourcefiles.model.GeneralFileExportOptions;
import com.crowdin.client.sourcefiles.model.PropertyFileExportOptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.Arguments.arguments;

public class ProjectFilesUtilsTest {

    private static final long TEST_PROJECT_ID = 42;

    @Test
    public void testIsMultilingualFile() {
        File file1NoExportOptions = FileBuilder.standard().setProjectId(TEST_PROJECT_ID)
            .setIdentifiers("first.po", "gettext", 101L, null, null).build();
        File file2NoExportPattern = FileBuilder.standard().setProjectId(TEST_PROJECT_ID)
            .setIdentifiers("first.po", "gettext", 101L, null, null).build();
        file2NoExportPattern.setExportOptions(new PropertyFileExportOptions());
        File file3PropertyFileEO = FileBuilder.standard().setProjectId(TEST_PROJECT_ID)
            .setIdentifiers("first.po", "gettext", 101L, null, null).build();
        file3PropertyFileEO.setExportOptions(new PropertyFileExportOptions() {{
                setExportPattern("anything");
            }}
        );
        File file4GeneralFileEO = FileBuilder.standard().setProjectId(TEST_PROJECT_ID)
            .setIdentifiers("first.po", "gettext", 101L, null, null).build();
        file4GeneralFileEO.setExportOptions(new GeneralFileExportOptions() {{
                setExportPattern("anything");
            }}
        );

        assertTrue(ProjectFilesUtils.isMultilingualFile(file1NoExportOptions));
        assertTrue(ProjectFilesUtils.isMultilingualFile(file2NoExportPattern));
        assertFalse(ProjectFilesUtils.isMultilingualFile(file3PropertyFileEO));
        assertFalse(ProjectFilesUtils.isMultilingualFile(file4GeneralFileEO));

    }

    @ParameterizedTest
    @MethodSource
    public void isProjectFileSatisfiesThePatternsTest(String projectFilePath, String sourcePattern, List<String> ignorePattern, boolean preserveHierarchy, boolean expected) {
        assertEquals(expected, ProjectFilesUtils.isProjectFilePathSatisfiesPatterns(sourcePattern, ignorePattern, preserveHierarchy).test(projectFilePath));
    }

    private static Stream<Arguments> isProjectFileSatisfiesThePatternsTest() {
        return Stream.of(
            arguments("path/to/file.csv", "/path/to/file.csv", null, true, true),
            arguments("path/to/file.csv", "/path/to/file.csv", null, false, true),
            arguments("path/to/file.csv", "/**/to/file.csv", null, true, true),
            arguments("path/to/file.csv", "/**/%file_name%.csv", Arrays.asList("/path/to/file.csv"), true, false),
            arguments("path/to/file.csv", "/**/%file_name%.csv", Arrays.asList("/**/to/file.csv"), true, false),
            arguments("file.csv", "/path/to/file.csv", null, true, false),
            arguments("file.csv", "/path/to/file.csv", null, false, true),
            arguments("one/path/to/file.csv", "/two/**/to/file.csv", null, true, false),
            arguments("one/path/to/file.csv", "/two/**/to/file.csv", null, false, true),
            arguments("one/path/to/file.csv", "/**/to/file.csv", Arrays.asList("/two/**/to/file.csv"), true, true),
            arguments("one/path/to/file.csv", "/**/to/file.csv", Arrays.asList("/two/**/to/file.csv"), false, false),
            arguments("one/path/to/file.csv", "/**/to/file.csv", Arrays.asList("/one/**/to/file.csv"), true, false),
            arguments("one/path/to/file.csv", "/**/to/file.csv", Arrays.asList("/one/**/to/file.csv"), false, false)
        );
    }

}


text:
package com.twitter.finatra.http.routing

import com.twitter.finagle.http.{HttpMuxer, Request, Response, Status}
import com.twitter.finagle.httpx.compat.NettyClientAdaptor
import com.twitter.finagle.{Service, httpx}
import com.twitter.finatra.json.FinatraObjectMapper
import com.twitter.finatra.utils.FuturePools
import com.twitter.inject.Logging
import com.twitter.util.{Await, ExecutorServiceFuturePool, Future}
import javax.inject.Inject
import org.jboss.netty.handler.codec.http.{HttpRequest, HttpResponse}

class HttpWarmup @Inject()(
  router: HttpRouter,
  mapper: FinatraObjectMapper)
  extends Logging {

  private val userAgent = "http-warmup-client"

  /* Use a FuturePool to avoid getting a ConstFuture from Future.apply(...) */
  private val pool = FuturePools.fixedPool("HTTP Warmup", 1).asInstanceOf[ExecutorServiceFuturePool]

  private val httpxMuxer: Service[HttpRequest, HttpResponse] =
    NettyClientAdaptor.andThen(httpx.HttpMuxer)

  /* Public */

  /**
   * Send a request to warmup services that are not yet externally receiving traffic
   * @param request Request to send
   * @param forceRouteToAdminHttpMuxers Route the request to the HttpMuxer (e.g. needed for twitter-server admin endpoints that do not start with /admin)
   * @param responseCallback Callback called for every response where assertions can be made (note: be aware that failed assertions will prevent a server from
   *                         restarting when dependent services are unresponsive)
   */
  def send(
    request: => Request,
    forceRouteToAdminHttpMuxers: Boolean = false,
    times: Int = 1,
    responseCallback: Response => Unit = identity) {

    for (i <- 1 to times) {
      val response = executeRequest(request, forceRouteToAdminHttpMuxers)
      responseCallback(response)
      info("Warmup " + request + " complete with " + response.status)
    }
  }

  def close() = {
    pool.executor.shutdownNow()
  }

  /* Private */

  private def executeRequest(request: Request, forceRouteToHttpMuxer: Boolean): Response = {
    val nettyResponseFuture = pool {
      info("Warmup " + request)
      routeRequest(request, forceRouteToHttpMuxer)
    }.flatten

    Response(
      Await.result(nettyResponseFuture))
  }

  private def routeRequest(request: Request, forceRouteToHttpMuxer: Boolean): Future[HttpResponse] = {
    /* Mutation */
    request.headerMap.add("Host", "127.0.0.1")
    request.headerMap.add("User-Agent", userAgent)

    if (forceRouteToHttpMuxer)
      routeToAdminMuxers(request)
    else if (request.uri.startsWith("/admin/finatra/"))
      router.services.adminService(request)
    else if (request.uri.startsWith("/admin"))
      routeToAdminMuxers(request)
    else
      router.services.externalService(request)
  }

  private def routeToAdminMuxers(request: Request): Future[HttpResponse] = {
    httpxMuxer(request.getHttpRequest()) flatMap { response =>
      if (response.getStatus == Status.NotFound)
        HttpMuxer(request)
      else
        Future(response)
    }
  }
}


text:
package com.android.settings.accounts;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncAdapterType;
import android.content.SyncInfo;
import android.content.SyncStatusInfo;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.UserHandle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.android.internal.logging.MetricsLogger;
import com.android.settings.AccountPreference;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.Utils;
import com.android.settings.location.LocationSettings;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import static android.content.Intent.EXTRA_USER;

/** Manages settings for Google Account. */
public class ManageAccountsSettings extends AccountPreferenceBase
        implements AuthenticatorHelper.OnAccountsUpdateListener {
    private static final String ACCOUNT_KEY = "account"; // to pass to auth settings
    public static final String KEY_ACCOUNT_TYPE = "account_type";
    public static final String KEY_ACCOUNT_LABEL = "account_label";

    // Action name for the broadcast intent when the Google account preferences page is launching
    // the location settings.
    private static final String LAUNCHING_LOCATION_SETTINGS =
            "com.android.settings.accounts.LAUNCHING_LOCATION_SETTINGS";

    private static final int MENU_SYNC_NOW_ID = Menu.FIRST;
    private static final int MENU_SYNC_CANCEL_ID    = Menu.FIRST + 1;

    private static final int REQUEST_SHOW_SYNC_SETTINGS = 1;

    private String[] mAuthorities;
    private TextView mErrorInfoView;

    // If an account type is set, then show only accounts of that type
    private String mAccountType;
    // Temporary hack, to deal with backward compatibility
    // mFirstAccount is used for the injected preferences
    private Account mFirstAccount;

    @Override
    protected int getMetricsCategory() {
        return MetricsLogger.ACCOUNTS_MANAGE_ACCOUNTS;
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        Bundle args = getArguments();
        if (args != null && args.containsKey(KEY_ACCOUNT_TYPE)) {
            mAccountType = args.getString(KEY_ACCOUNT_TYPE);
        }
        addPreferencesFromResource(R.xml.manage_accounts_settings);
        setHasOptionsMenu(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        mAuthenticatorHelper.listenToAccountUpdates();
        updateAuthDescriptions();
        showAccountsIfNeeded();
        showSyncState();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.manage_accounts_screen, container, false);
        final ListView list = (ListView) view.findViewById(android.R.id.list);
        Utils.prepareCustomPreferencesList(container, view, list, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final Activity activity = getActivity();
        final View view = getView();

        mErrorInfoView = (TextView)view.findViewById(R.id.sync_settings_error_info);
        mErrorInfoView.setVisibility(View.GONE);

        mAuthorities = activity.getIntent().getStringArrayExtra(AUTHORITIES_FILTER_KEY);

        Bundle args = getArguments();
        if (args != null && args.containsKey(KEY_ACCOUNT_LABEL)) {
            getActivity().setTitle(args.getString(KEY_ACCOUNT_LABEL));
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mAuthenticatorHelper.stopListeningToAccountUpdates();
    }

    @Override
    public void onStop() {
        super.onStop();
        final Activity activity = getActivity();
        activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM);
        activity.getActionBar().setCustomView(null);
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferences, Preference preference) {
        if (preference instanceof AccountPreference) {
            startAccountSettings((AccountPreference) preference);
        } else {
            return false;
        }
        return true;
    }

    private void startAccountSettings(AccountPreference acctPref) {
        Bundle args = new Bundle();
        args.putParcelable(AccountSyncSettings.ACCOUNT_KEY, acctPref.getAccount());
        args.putParcelable(EXTRA_USER, mUserHandle);
        ((SettingsActivity) getActivity()).startPreferencePanel(
                AccountSyncSettings.class.getCanonicalName(), args,
                R.string.account_sync_settings_title, acctPref.getAccount().name,
                this, REQUEST_SHOW_SYNC_SETTINGS);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.add(0, MENU_SYNC_NOW_ID, 0, getString(R.string.sync_menu_sync_now))
                .setIcon(R.drawable.ic_menu_refresh_holo_dark);
        menu.add(0, MENU_SYNC_CANCEL_ID, 0, getString(R.string.sync_menu_sync_cancel))
                .setIcon(com.android.internal.R.drawable.ic_menu_close_clear_cancel);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        boolean syncActive = !ContentResolver.getCurrentSyncsAsUser(
                mUserHandle.getIdentifier()).isEmpty();
        menu.findItem(MENU_SYNC_NOW_ID).setVisible(!syncActive);
        menu.findItem(MENU_SYNC_CANCEL_ID).setVisible(syncActive);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_SYNC_NOW_ID:
            requestOrCancelSyncForAccounts(true);
            return true;
        case MENU_SYNC_CANCEL_ID:
            requestOrCancelSyncForAccounts(false);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void requestOrCancelSyncForAccounts(boolean sync) {
        final int userId = mUserHandle.getIdentifier();
        SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypesAsUser(userId);
        Bundle extras = new Bundle();
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        int count = getPreferenceScreen().getPreferenceCount();
        // For each account
        for (int i = 0; i < count; i++) {
            Preference pref = getPreferenceScreen().getPreference(i);
            if (pref instanceof AccountPreference) {
                Account account = ((AccountPreference) pref).getAccount();
                // For all available sync authorities, sync those that are enabled for the account
                for (int j = 0; j < syncAdapters.length; j++) {
                    SyncAdapterType sa = syncAdapters[j];
                    if (syncAdapters[j].accountType.equals(mAccountType)
                            && ContentResolver.getSyncAutomaticallyAsUser(account, sa.authority,
                                    userId)) {
                        if (sync) {
                            ContentResolver.requestSyncAsUser(account, sa.authority, userId,
                                    extras);
                        } else {
                            ContentResolver.cancelSyncAsUser(account, sa.authority, userId);
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onSyncStateUpdated() {
        showSyncState();
        // Catch any delayed delivery of update messages
        final Activity activity = getActivity();
        if (activity != null) {
            activity.invalidateOptionsMenu();
        }
    }

    /**
     * Shows the sync state of the accounts. Note: it must be called after the accounts have been
     * loaded, @see #showAccountsIfNeeded().
     */
    private void showSyncState() {
        // Catch any delayed delivery of update messages
        if (getActivity() == null || getActivity().isFinishing()) return;

        final int userId = mUserHandle.getIdentifier();

        // iterate over all the preferences, setting the state properly for each
        List<SyncInfo> currentSyncs = ContentResolver.getCurrentSyncsAsUser(userId);

        boolean anySyncFailed = false; // true if sync on any account failed
        Date date = new Date();

        // only track userfacing sync adapters when deciding if account is synced or not
        final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypesAsUser(userId);
        HashSet<String> userFacing = new HashSet<String>();
        for (int k = 0, n = syncAdapters.length; k < n; k++) {
            final SyncAdapterType sa = syncAdapters[k];
            if (sa.isUserVisible()) {
                userFacing.add(sa.authority);
            }
        }
        for (int i = 0, count = getPreferenceScreen().getPreferenceCount(); i < count; i++) {
            Preference pref = getPreferenceScreen().getPreference(i);
            if (! (pref instanceof AccountPreference)) {
                continue;
            }

            AccountPreference accountPref = (AccountPreference) pref;
            Account account = accountPref.getAccount();
            int syncCount = 0;
            long lastSuccessTime = 0;
            boolean syncIsFailing = false;
            final ArrayList<String> authorities = accountPref.getAuthorities();
            boolean syncingNow = false;
            if (authorities != null) {
                for (String authority : authorities) {
                    SyncStatusInfo status = ContentResolver.getSyncStatusAsUser(account, authority,
                            userId);
                    boolean syncEnabled = isSyncEnabled(userId, account, authority);
                    boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
                    boolean activelySyncing = isSyncing(currentSyncs, account, authority);
                    boolean lastSyncFailed = status != null
                            && syncEnabled
                            && status.lastFailureTime != 0
                            && status.getLastFailureMesgAsInt(0)
                               != ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
                    if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
                        syncIsFailing = true;
                        anySyncFailed = true;
                    }
                    syncingNow |= activelySyncing;
                    if (status != null && lastSuccessTime < status.lastSuccessTime) {
                        lastSuccessTime = status.lastSuccessTime;
                    }
                    syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0;
                }
            } else {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "no syncadapters found for " + account);
                }
            }
            if (syncIsFailing) {
                accountPref.setSyncStatus(AccountPreference.SYNC_ERROR, true);
            } else if (syncCount == 0) {
                accountPref.setSyncStatus(AccountPreference.SYNC_DISABLED, true);
            } else if (syncCount > 0) {
                if (syncingNow) {
                    accountPref.setSyncStatus(AccountPreference.SYNC_IN_PROGRESS, true);
                } else {
                    accountPref.setSyncStatus(AccountPreference.SYNC_ENABLED, true);
                    if (lastSuccessTime > 0) {
                        accountPref.setSyncStatus(AccountPreference.SYNC_ENABLED, false);
                        date.setTime(lastSuccessTime);
                        final String timeString = formatSyncDate(date);
                        accountPref.setSummary(getResources().getString(
                                R.string.last_synced, timeString));
                    }
                }
            } else {
                accountPref.setSyncStatus(AccountPreference.SYNC_DISABLED, true);
            }
        }

        mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE);
    }

    private boolean isSyncing(List<SyncInfo> currentSyncs, Account account, String authority) {
        final int count = currentSyncs.size();
        for (int i = 0; i < count;  i++) {
            SyncInfo syncInfo = currentSyncs.get(i);
            if (syncInfo.account.equals(account) && syncInfo.authority.equals(authority)) {
                return true;
            }
        }
        return false;
    }

    private boolean isSyncEnabled(int userId, Account account, String authority) {
        return ContentResolver.getSyncAutomaticallyAsUser(account, authority, userId)
                && ContentResolver.getMasterSyncAutomaticallyAsUser(userId)
                && (ContentResolver.getIsSyncableAsUser(account, authority, userId) > 0);
    }

    @Override
    public void onAccountsUpdate(UserHandle userHandle) {
        showAccountsIfNeeded();
        onSyncStateUpdated();
    }

    private void showAccountsIfNeeded() {
        if (getActivity() == null) return;
        Account[] accounts = AccountManager.get(getActivity()).getAccountsAsUser(
                mUserHandle.getIdentifier());
        getPreferenceScreen().removeAll();
        mFirstAccount = null;
        addPreferencesFromResource(R.xml.manage_accounts_settings);
        for (int i = 0, n = accounts.length; i < n; i++) {
            final Account account = accounts[i];
            // If an account type is specified for this screen, skip other types
            if (mAccountType != null && !account.type.equals(mAccountType)) continue;
            final ArrayList<String> auths = getAuthoritiesForAccountType(account.type);

            boolean showAccount = true;
            if (mAuthorities != null && auths != null) {
                showAccount = false;
                for (String requestedAuthority : mAuthorities) {
                    if (auths.contains(requestedAuthority)) {
                        showAccount = true;
                        break;
                    }
                }
            }

            if (showAccount) {
                final Drawable icon = getDrawableForType(account.type);
                final AccountPreference preference =
                        new AccountPreference(getActivity(), account, icon, auths, false);
                getPreferenceScreen().addPreference(preference);
                if (mFirstAccount == null) {
                    mFirstAccount = account;
                }
            }
        }
        if (mAccountType != null && mFirstAccount != null) {
            addAuthenticatorSettings();
        } else {
            // There's no account, close activity
            finish();
        }
    }

    private void addAuthenticatorSettings() {
        PreferenceScreen prefs = addPreferencesForType(mAccountType, getPreferenceScreen());
        if (prefs != null) {
            updatePreferenceIntents(prefs);
        }
    }

    /** Listens to a preference click event and starts a fragment */
    private class FragmentStarter
            implements Preference.OnPreferenceClickListener {
        private final String mClass;
        private final int mTitleRes;

        /**
         * @param className the class name of the fragment to be started.
         * @param title the title resource id of the started preference panel.
         */
        public FragmentStarter(String className, int title) {
            mClass = className;
            mTitleRes = title;
        }

        @Override
        public boolean onPreferenceClick(Preference preference) {
            ((SettingsActivity) getActivity()).startPreferencePanel(
                    mClass, null, mTitleRes, null, null, 0);
            // Hack: announce that the Google account preferences page is launching the location
            // settings
            if (mClass.equals(LocationSettings.class.getName())) {
                Intent intent = new Intent(LAUNCHING_LOCATION_SETTINGS);
                getActivity().sendBroadcast(
                        intent, android.Manifest.permission.WRITE_SECURE_SETTINGS);
            }
            return true;
        }
    }

    /**
     * Filters through the preference list provided by GoogleLoginService.
     *
     * This method removes all the invalid intent from the list, adds account name as extra into the
     * intent, and hack the location settings to start it as a fragment.
     */
    private void updatePreferenceIntents(PreferenceScreen prefs) {
        final PackageManager pm = getActivity().getPackageManager();
        for (int i = 0; i < prefs.getPreferenceCount();) {
            Preference pref = prefs.getPreference(i);
            Intent intent = pref.getIntent();
            if (intent != null) {
                // Hack. Launch "Location" as fragment instead of as activity.
                //
                // When "Location" is launched as activity via Intent, there's no "Up" button at the
                // top left, and if there's another running instance of "Location" activity, the
                // back stack would usually point to some other place so the user won't be able to
                // go back to the previous page by "back" key. Using fragment is a much easier
                // solution to those problems.
                //
                // If we set Intent to null and assign a fragment to the PreferenceScreen item here,
                // in order to make it work as expected, we still need to modify the container
                // PreferenceActivity, override onPreferenceStartFragment() and call
                // startPreferencePanel() there. In order to inject the title string there, more
                // dirty further hack is still needed. It's much easier and cleaner to listen to
                // preference click event here directly.
                if (intent.getAction().equals(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)) {
                    // The OnPreferenceClickListener overrides the click event completely. No intent
                    // will get fired.
                    pref.setOnPreferenceClickListener(new FragmentStarter(
                            LocationSettings.class.getName(),
                            R.string.location_settings_title));
                } else {
                    ResolveInfo ri = pm.resolveActivityAsUser(intent,
                            PackageManager.MATCH_DEFAULT_ONLY, mUserHandle.getIdentifier());
                    if (ri == null) {
                        prefs.removePreference(pref);
                        continue;
                    } else {
                        intent.putExtra(ACCOUNT_KEY, mFirstAccount);
                        intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                        pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                            @Override
                            public boolean onPreferenceClick(Preference preference) {
                                Intent prefIntent = preference.getIntent();
                                /*
                                 * Check the intent to see if it resolves to a exported=false
                                 * activity that doesn't share a uid with the authenticator.
                                 *
                                 * Otherwise the intent is considered unsafe in that it will be
                                 * exploiting the fact that settings has system privileges.
                                 */
                                if (isSafeIntent(pm, prefIntent)) {
                                    getActivity().startActivityAsUser(prefIntent, mUserHandle);
                                } else {
                                    Log.e(TAG,
                                            "Refusing to launch authenticator intent because"
                                            + "it exploits Settings permissions: "
                                            + prefIntent);
                                }
                                return true;
                            }
                        });
                    }
                }
            }
            i++;
        }
    }

    /**
     * Determines if the supplied Intent is safe. A safe intent is one that is
     * will launch a exported=true activity or owned by the same uid as the
     * authenticator supplying the intent.
     */
    private boolean isSafeIntent(PackageManager pm, Intent intent) {
        AuthenticatorDescription authDesc =
                mAuthenticatorHelper.getAccountTypeDescription(mAccountType);
        ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
        if (resolveInfo == null) {
            return false;
        }
        ActivityInfo resolvedActivityInfo = resolveInfo.activityInfo;
        ApplicationInfo resolvedAppInfo = resolvedActivityInfo.applicationInfo;
        try {
            ApplicationInfo authenticatorAppInf = pm.getApplicationInfo(authDesc.packageName, 0);
            return resolvedActivityInfo.exported
                    || resolvedAppInfo.uid == authenticatorAppInf.uid;
        } catch (NameNotFoundException e) {
            Log.e(TAG,
                    "Intent considered unsafe due to exception.",
                    e);
            return false;
        }
    }

    @Override
    protected void onAuthDescriptionsUpdated() {
        // Update account icons for all account preference items
        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
            Preference pref = getPreferenceScreen().getPreference(i);
            if (pref instanceof AccountPreference) {
                AccountPreference accPref = (AccountPreference) pref;
                accPref.setSummary(getLabelForType(accPref.getAccount().type));
            }
        }
    }
}


text:
package ru.job4j.array;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
* Test.
*
* @author atrifonov.
* @since 12.07.2017.
* @version 1.
*/
public class ArrayDuplicateTest {
	/**
	* Test remove.
	*/
	@Test
	public void whenRemoveDuplicatesThenArrayWithoutDuplicate() {
		 String[] initialArray = {"Мир", "Труд", "Мир", "Май", "Труд"};
		 ArrayDuplicate arrayDuplicate = new ArrayDuplicate();
		 String[] resultArray = arrayDuplicate.remove(initialArray);
		 String[] expectedArray = {"Мир", "Труд", "Май"};
		 assertThat(resultArray, is(expectedArray));
	}
}


text:
class Weather < ApplicationRecord
end


text:
package store

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3iface"
	"github.com/carlosmecha/todo/util/testutil"
)

type s3mock struct {
	data    map[string][]byte
	version map[string]string
	t       *testing.T

	s3iface.S3API
}

func (m *s3mock) GetObject(input *s3.GetObjectInput) (*s3.GetObjectOutput, error) {
	url := fmt.Sprintf("s3://%s/%s", *input.Bucket, *input.Key)
	m.t.Logf("Called GetObject %s", url)
	if _, ok := m.data[url]; !ok {
		return nil, awserr.New(s3.ErrCodeNoSuchKey, "not found", ErrNotFound)
	}

	buffer := testutil.NewBufferCloser(m.data[url])

	return &s3.GetObjectOutput{
		Body:          buffer,
		ContentLength: aws.Int64(int64(len(m.data[url]))),
		ContentType:   aws.String("text/plan"),
		Metadata:      map[string]*string{Version: aws.String(m.version[url])},
	}, nil
}

func (m *s3mock) HeadObject(input *s3.HeadObjectInput) (*s3.HeadObjectOutput, error) {
	url := fmt.Sprintf("s3://%s/%s", *input.Bucket, *input.Key)
	m.t.Logf("Called HeadObject %s", url)
	if _, ok := m.data[url]; !ok {
		return nil, awserr.New(s3.ErrCodeNoSuchKey, "not found", ErrNotFound)
	}

	return &s3.HeadObjectOutput{
		ContentLength: aws.Int64(int64(len(m.data[url]))),
		ContentType:   aws.String("text/plan"),
		Metadata:      map[string]*string{Version: aws.String(m.version[url])},
	}, nil
}

func (m *s3mock) PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
	url := fmt.Sprintf("s3://%s/%s", *input.Bucket, *input.Key)
	m.t.Logf("Called PutObject %s", url)
	b := new(bytes.Buffer)
	if _, err := b.ReadFrom(input.Body); err != nil {
		return nil, err
	}

	if m.data == nil {
		m.data = make(map[string][]byte)
	}

	m.data[url] = b.Bytes()
	m.version[url] = *input.Metadata[Version]

	return &s3.PutObjectOutput{}, nil
}

func TestGetCurrentVersion(t *testing.T) {

	currentVersion := time.Now().Format(time.RFC1123)
	version, _ := time.Parse(time.RFC1123, currentVersion)

	cases := []struct {
		key             string
		bucket          string
		expectedVersion time.Time
		expectedError   error
	}{
		// OK
		{
			key:             "test",
			bucket:          "test",
			expectedVersion: version,
		},
		// Not found
		{
			key:           "foo",
			bucket:        "bar",
			expectedError: ErrNotFound,
		},
		// Missing version
		{
			key:           "test2",
			bucket:        "test",
			expectedError: ErrInvalidVersion,
		},
	}

	mock := &s3mock{
		data: map[string][]byte{
			"s3://test/test":  []byte(""),
			"s3://test/test2": []byte(""),
		},
		version: map[string]string{
			"s3://test/test": version.Format(time.RFC1123),
		},
		t: t,
	}

	for _, c := range cases {
		s := &store{
			key:    aws.String(c.key),
			bucket: aws.String(c.bucket),
			logger: log.New(os.Stdout, "", log.LstdFlags),
			s3:     mock,
		}

		if got, err := s.GetCurrentVersion(); err != nil {
			if c.expectedError == nil {
				t.Fatalf("Unexpected error %s", err.Error())
			} else if c.expectedError != err {
				t.Fatalf("Expected error %s, got %s", c.expectedError.Error(), err.Error())
			}
		} else if !got.Equal(c.expectedVersion) {
			t.Fatalf("Expected version %s, got %s", c.expectedVersion.Format(time.RFC1123), got.Format(time.RFC1123))
		}

	}

}

func TestGet(t *testing.T) {

	now := time.Now()
	currentVersion := now.Format(time.RFC1123)
	version, _ := time.Parse(time.RFC1123, currentVersion)

	cases := []struct {
		key             string
		bucket          string
		version         time.Time
		expectedBody    []byte
		expectedVersion time.Time
		expectedError   error
	}{
		// OK
		{
			key:             "test",
			bucket:          "test",
			version:         now.AddDate(-1, 0, 0),
			expectedBody:    []byte("hola"),
			expectedVersion: version,
		},
		// Not found
		{
			key:           "foo",
			bucket:        "bar",
			version:       version,
			expectedError: ErrNotFound,
		},
		// Missing version
		{
			key:           "test2",
			bucket:        "test",
			version:       version,
			expectedError: ErrInvalidVersion,
		},
		// Same version
		{
			key:           "test",
			bucket:        "test",
			version:       version,
			expectedError: ErrNotModified,
		},
		// Newer version
		{
			key:           "test",
			bucket:        "test",
			version:       version.AddDate(1, 0, 0),
			expectedError: ErrVersionConflict,
		},
	}

	mock := &s3mock{
		data: map[string][]byte{
			"s3://test/test":  []byte("hola"),
			"s3://test/test2": []byte(""),
		},
		version: map[string]string{
			"s3://test/test": version.Format(time.RFC1123),
		},
		t: t,
	}

	for _, c := range cases {
		s := &store{
			key:    aws.String(c.key),
			bucket: aws.String(c.bucket),
			logger: log.New(os.Stdout, "", log.LstdFlags),
			s3:     mock,
		}

		buff := &bytes.Buffer{}

		if got, err := s.Get(c.version, buff); err != nil {
			if c.expectedError == nil {
				t.Fatalf("Unexpected error %s", err.Error())
			} else if c.expectedError != err {
				t.Fatalf("Expected error %s, got %s", c.expectedError.Error(), err.Error())
			}
		} else if !got.Equal(c.expectedVersion) {
			t.Fatalf("Expected version %s, got %s", c.expectedVersion.Format(time.RFC1123), got.Format(time.RFC1123))
		} else if string(c.expectedBody) != buff.String() {
			t.Fatalf("Expected %s, got %s", string(c.expectedBody), buff.String())
		}

	}

}

func TestSafePut(t *testing.T) {

	now := time.Now()
	currentVersion := now.Format(time.RFC1123)
	version, _ := time.Parse(time.RFC1123, currentVersion)

	cases := []struct {
		key             string
		bucket          string
		version         time.Time
		body            []byte
		expectedVersion time.Time
		expectedBody    []byte
		expectedError   error
	}{
		// OK
		{
			key:             "test",
			bucket:          "test",
			version:         version.AddDate(0, 0, 1),
			body:            []byte("adios"),
			expectedVersion: version.AddDate(0, 0, 1),
			expectedBody:    []byte("adios"),
		},
		// Not found
		{
			key:             "foo",
			bucket:          "bar",
			version:         version.AddDate(0, 0, 1),
			body:            []byte("adios"),
			expectedVersion: version.AddDate(0, 0, 1),
			expectedBody:    []byte("adios"),
		},
		// Same date
		{
			key:           "test",
			bucket:        "test",
			version:       version,
			body:          []byte("adios"),
			expectedError: ErrVersionConflict,
		},
		// Older date
		{
			key:           "test",
			bucket:        "test",
			version:       version.AddDate(0, 0, -1),
			body:          []byte("adios"),
			expectedError: ErrVersionConflict,
		},
	}

	mock := &s3mock{
		data: map[string][]byte{
			"s3://test/test": []byte("hola"),
		},
		version: map[string]string{
			"s3://test/test": version.Format(time.RFC1123),
		},
		t: t,
	}

	for _, c := range cases {
		s := &store{
			key:    aws.String(c.key),
			bucket: aws.String(c.bucket),
			logger: log.New(os.Stdout, "", log.LstdFlags),
			s3:     mock,
		}

		buff := bytes.NewReader(c.body)

		if err := s.SafePut(c.version, int64(len(c.body)), buff); err != nil {
			if c.expectedError == nil {
				t.Fatalf("Unexpected error %s", err.Error())
			} else if c.expectedError != err {
				t.Fatalf("Expected error %s, got %s", c.expectedError.Error(), err.Error())
			}
			continue
		}

		url := fmt.Sprintf("s3://%s/%s", c.bucket, c.key)
		gotVersion := mock.version[url]
		gotBody := mock.data[url]

		if gotVersion != c.expectedVersion.Format(time.RFC1123) {
			t.Fatalf("Expected version %s, got %s", c.expectedVersion.Format(time.RFC1123), gotVersion)
		}

		if string(c.expectedBody) != string(gotBody) {
			t.Fatalf("Expected %s, got %s", string(c.expectedBody), string(gotBody))
		}

	}
}

func TestOverwrite(t *testing.T) {
	now := time.Now()
	currentVersion := now.Format(time.RFC1123)
	version, _ := time.Parse(time.RFC1123, currentVersion)

	cases := []struct {
		key          string
		bucket       string
		body         []byte
		expectedBody []byte
	}{
		// OK
		{
			key:          "test",
			bucket:       "test",
			body:         []byte("adios"),
			expectedBody: []byte("adios"),
		},
		// Not found
		{
			key:          "foo",
			bucket:       "bar",
			body:         []byte("adios"),
			expectedBody: []byte("adios"),
		},
	}

	mock := &s3mock{
		data: map[string][]byte{
			"s3://test/test": []byte("hola"),
		},
		version: map[string]string{
			"s3://test/test": version.Format(time.RFC1123),
		},
		t: t,
	}

	for _, c := range cases {
		s := &store{
			key:    aws.String(c.key),
			bucket: aws.String(c.bucket),
			logger: log.New(os.Stdout, "", log.LstdFlags),
			s3:     mock,
		}

		buff := bytes.NewReader(c.body)

		if err := s.Overwrite(int64(len(c.body)), buff); err != nil {
			t.Fatalf("Unexpected error %s", err.Error())
		}

		url := fmt.Sprintf("s3://%s/%s", c.bucket, c.key)
		gotBody := mock.data[url]

		if string(c.expectedBody) != string(gotBody) {
			t.Fatalf("Expected %s, got %s", string(c.expectedBody), string(gotBody))
		}

	}
}


text:
namespace jscore {

    typedef JSObjectCallAsFunctionCallback JSMethodCallback;

    typedef JSObjectGetPropertyCallback JSGetPropertyCallback;

    typedef JSObjectSetPropertyCallback JSSetPropertyCallback;

    struct Field {
        JSSetPropertyCallback set_callback = 0;
        JSGetPropertyCallback get_callback = 0;
    };
}

#endif //RUNTIME_JSC_BASE


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

goog.module('goog.ui.ac.AutoCompleteTest');
goog.setTestOnly();

const AutoComplete = goog.require('goog.ui.ac.AutoComplete');
const EventHandler = goog.require('goog.events.EventHandler');
const GoogEventTarget = goog.require('goog.events.EventTarget');
const InputHandler = goog.require('goog.ui.ac.InputHandler');
const InputType = goog.require('goog.dom.InputType');
const MockControl = goog.require('goog.testing.MockControl');
const RenderOptions = goog.require('goog.ui.ac.RenderOptions');
const Renderer = goog.require('goog.ui.ac.Renderer');
const Role = goog.require('goog.a11y.aria.Role');
const TagName = goog.require('goog.dom.TagName');
const aria = goog.require('goog.a11y.aria');
const dom = goog.require('goog.dom');
const events = goog.require('goog.testing.events');
const googString = goog.require('goog.string');
const mockmatchers = goog.require('goog.testing.mockmatchers');
const testSuite = goog.require('goog.testing.testSuite');

/** Mock DataStore */
class MockDS {
  constructor(autoHilite = undefined) {
    this.autoHilite_ = autoHilite;
    const disabledRow = {
      match: function(str) {
        return this.text.match(str);
      },
      rowDisabled: true,
      text: 'hello@u.edu',
    };
    this.rows_ = [
      '"Slartibartfast Theadore" <fjordmaster@magrathea.com>',
      '"Zaphod Beeblebrox" <theprez@universe.gov>',
      '"Ford Prefect" <ford@theguide.com>',
      '"Arthur Dent" <has.no.tea@gmail.com>',
      '"Marvin The Paranoid Android" <marv@googlemail.com>',
      'the.mice@magrathea.com',
      'the.mice@myotherdomain.com',
      'hello@a.com',
      disabledRow,
      'row@u.edu',
      'person@a.edu',
    ];
    this.isRowDisabled = (row) => !!row.rowDisabled;
  }

  requestMatchingRows(token, maxMatches, matchHandler) {
    const escapedToken = googString.regExpEscape(token);
    const matcher = new RegExp('(^|\\W+)' + escapedToken);
    const matches = [];
    for (let i = 0; i < this.rows_.length && matches.length < maxMatches; ++i) {
      const row = this.rows_[i];
      if (row.match(matcher)) {
        matches.push(row);
      }
    }
    if (this.autoHilite_ === undefined) {
      matchHandler(token, matches);
    } else {
      const options = new RenderOptions();
      options.setAutoHilite(this.autoHilite_);
      matchHandler(token, matches, options);
    }
  }
}

/** Mock Selection Handler */

function MockSelect() {}
goog.inherits(MockSelect, GoogEventTarget);

MockSelect.prototype.selectRow = function(row) {
  this.selectedRow = row;
};

/** Renderer subclass that exposes additional private members for testing. */
class TestRend extends Renderer {
  constructor() {
    super(dom.getElement('test-area'));
  }

  getRenderedRows() {
    return this.rows_;
  }

  getHilitedRowIndex() {
    return this.hilitedRow_;
  }

  getHilitedRowDiv() {
    return this.rowDivs_[this.hilitedRow_];
  }

  getRowDiv(index) {
    return this.rowDivs_[index];
  }
}

let handler;
let inputElement;
let mockControl;

function checkHilitedIndex(renderer, index) {
  assertEquals(index, renderer.getHilitedRowIndex());
}

testSuite({
  setUp() {
    inputElement = dom.createDom(TagName.INPUT, {type: InputType.TEXT});
    handler = new EventHandler();
    mockControl = new MockControl();
  },

  tearDown() {
    handler.dispose();
    mockControl.$tearDown();
    dom.removeChildren(dom.getElement('test-area'));
  },

  /** Make sure results are truncated (or not) by setMaxMatches. */
  testMaxMatches() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    ac.setMaxMatches(2);
    ac.setToken('the');
    assertEquals(2, rend.getRenderedRows().length);
    ac.setToken('');

    ac.setMaxMatches(3);
    ac.setToken('the');
    assertEquals(3, rend.getRenderedRows().length);
    ac.setToken('');

    ac.setMaxMatches(1000);
    ac.setToken('the');
    assertEquals(4, rend.getRenderedRows().length);
    ac.setToken('');
  },

  testHiliteViaMouse() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    let updates = 0;
    const row = null;
    let rowNode = null;
    handler.listen(rend, AutoComplete.EventType.ROW_HILITE, (evt) => {
      updates++;
      rowNode = evt.rowNode;
    });
    const ac = new AutoComplete(ds, rend, select);
    ac.setMaxMatches(4);
    ac.setToken('the');
    // Need to set the startRenderingRows_ time to something long ago, otherwise
    // the mouse event will not be fired.  (The autocomplete logic waits for
    // some time to pass after rendering before firing mouseover events.)
    rend.startRenderingRows_ = -1;
    const hilitedRowDiv = rend.getRowDiv(3);
    events.fireMouseOverEvent(hilitedRowDiv);
    assertEquals(2, updates);
    assertTrue(
        googString.contains(rowNode.innerHTML, 'mice@myotherdomain.com'));
  },

  testMouseClickBeforeHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setMaxMatches(4);
    ac.setToken('the');
    // Need to set the startRenderingRows_ time to something long ago, otherwise
    // the mouse event will not be fired.  (The autocomplete logic waits for
    // some time to pass after rendering before firing mouseover events.)
    rend.startRenderingRows_ = -1;

    // hilite row 3...
    const hilitedRowDiv = rend.getRowDiv(3);
    events.fireMouseOverEvent(hilitedRowDiv);

    // but click row 2, to simulate mouse getting ahead of focus.
    const targetRowDiv = rend.getRowDiv(2);
    events.fireClickEvent(targetRowDiv);

    assertEquals('the.mice@magrathea.com', select.selectedRow);
  },

  testMouseClickOnFirstRowBeforeHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAutoHilite(false);
    ac.setMaxMatches(4);
    ac.setToken('the');

    // Click the first row before highlighting it, to simulate mouse getting
    // ahead of focus.
    const targetRowDiv = rend.getRowDiv(0);
    events.fireClickEvent(targetRowDiv);

    assertEquals(
        '"Zaphod Beeblebrox" <theprez@universe.gov>', select.selectedRow);
  },

  testMouseClickOnRowAfterBlur() {
    const ds = new MockDS();
    const rend = new TestRend();
    const ih = new InputHandler();
    ih.attachInput(inputElement);

    const ac = new AutoComplete(ds, rend, ih);
    events.fireFocusEvent(inputElement);
    ac.setToken('the');
    const targetRowDiv = rend.getRowDiv(0);

    // Simulate the user clicking on an autocomplete row in the short time
    // between blur and autocomplete dismissal.
    events.fireBlurEvent(inputElement);
    assertNotThrows(() => {
      events.fireClickEvent(targetRowDiv);
    });
  },

  testSelectEventEmptyRow() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setMaxMatches(4);
    ac.setToken('the');
    rend.startRenderingRows_ = -1;

    // hilight row 2 ('the.mice@...')
    const hilitedRowDiv = rend.getRowDiv(2);
    events.fireMouseOverEvent(hilitedRowDiv);
    assertUndefined(select.selectedRow);

    // Dispatch an event that does not specify a row.
    rend.dispatchEvent({type: AutoComplete.EventType.SELECT, row: ''});

    assertEquals('the.mice@magrathea.com', select.selectedRow);
  },

  testSuggestionsUpdateEvent() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    let updates = 0;
    handler.listen(ac, AutoComplete.EventType.SUGGESTIONS_UPDATE, () => {
      updates++;
    });

    ac.setToken('the');
    assertEquals(1, updates);

    ac.setToken('beeb');
    assertEquals(2, updates);

    ac.setToken('ford');
    assertEquals(3, updates);

    ac.dismiss();
    assertEquals(4, updates);

    ac.setToken('dent');
    assertEquals(5, updates);
  },

  testGetRowCount() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    assertEquals(0, ac.getRowCount());

    ac.setToken('Zaphod');
    assertEquals(1, ac.getRowCount());

    ac.setMaxMatches(2);
    ac.setToken('the');
    assertEquals(2, ac.getRowCount());
  },

  /**
   * Try using next and prev to navigate past the ends with default behavior of
   * allowFreeSelect_ and wrap_.
   */
  testHiliteNextPrev_default() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    let updates = 0;
    handler.listen(rend, AutoComplete.EventType.ROW_HILITE, () => {
      updates++;
    });

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('the');
      assertEquals(4, rend.getRenderedRows().length);
      // check to see if we can select the last of the 4 items
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);
      // try going over the edge
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);

      // go back down
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
    }
    // 21 changes in the loop above (3 * 7)
    assertEquals(21, updates);
  },

  /**
   * Try using next and prev to navigate past the ends with default behavior of
   * allowFreeSelect_ and wrap_ and with a disabled first row.
   */
  testHiliteNextPrevWithDisabledFirstRow_default() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    let updates = 0;
    handler.listen(rend, AutoComplete.EventType.ROW_HILITE, () => {
      updates++;
    });

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(3);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled first row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('edu');
      assertEquals(3, rend.getRenderedRows().length);
      // The first row is disabled, second should be highlighted.
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      // try going over the edge
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back down
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      // First row is disabled, make sure we don't highlight it.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
    }
    // 9 changes in the loop above (3 * 3)
    assertEquals(9, updates);
  },

  /**
   * Try using next and prev to navigate past the ends with default behavior of
   * allowFreeSelect_ and wrap_ and with a disabled middle row.
   */
  testHiliteNextPrevWithDisabledMiddleRow_default() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    let updates = 0;
    handler.listen(rend, AutoComplete.EventType.ROW_HILITE, () => {
      updates++;
    });

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(3);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled middle row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('u');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled and should be skipped.
      checkHilitedIndex(rend, 2);
      // try going over the edge
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back down
      ac.hilitePrev();
      // Second row is disabled, make sure we don't highlight it.
      checkHilitedIndex(rend, 0);
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
    }
    // 9 changes in the loop above (3 * 3)
    assertEquals(9, updates);
  },

  /**
   * Try using next and prev to navigate past the ends with default behavior of
   * allowFreeSelect_ and wrap_ and with a disabled last row.
   */
  testHiliteNextPrevWithDisabledLastRow_default() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    let updates = 0;
    handler.listen(rend, AutoComplete.EventType.ROW_HILITE, () => {
      updates++;
    });

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(3);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled last row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('h');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      // try going over the edge since last row is disabled
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back down
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
    }
    // 9 changes in the loop above (3 * 3)
    assertEquals(9, updates);
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ off and
   * allowFreeSelect_ on.
   */
  testHiliteNextPrev_allowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('the');
      assertEquals(4, rend.getRenderedRows().length);
      // check to see if we can select the last of the 4 items
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);
      // try going over the edge. Since allowFreeSelect is on, this will
      // deselect the last row.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, deselects first.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ off and
   * allowFreeSelect_ on, and a disabled first row.
   */
  testHiliteNextPrevWithDisabledFirstRow_allowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled first row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('edu');
      assertEquals(3, rend.getRenderedRows().length);
      // The first row is disabled, second should be highlighted.
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      // Try going over the edge. Since allowFreeSelect is on, this will
      // deselect the last row.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list, first row is disabled
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      // first is disabled, so deselect the second.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ off and
   * allowFreeSelect_ on, and a disabled middle row.
   */
  testHiliteNextPrevWithDisabledMiddleRow_allowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled middle row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('u');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled and should be skipped.
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since allowFreeSelect is on, this will
      // deselect the last row.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, deselects first.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ off and
   * allowFreeSelect_ on, and a disabled last row.
   */
  testHiliteNextPrevWithDisabledLastRow_allowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled last row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('h');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      // try going over the edge since last row is disabled. Since
      // allowFreeSelect is on, this will deselect the last row.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, deselects first.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ off.
   */
  testHiliteNextPrev_wrap() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('the');
      assertEquals(4, rend.getRenderedRows().length);
      // check to see if we can select the last of the 4 items
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);
      // try going over the edge. Since wrap is on, this will go back to 0.
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, selects last.
      ac.hilitePrev();
      checkHilitedIndex(rend, 3);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ off and a disabled first row.
   */
  testHiliteNextPrevWithDisabledFirstRow_wrap() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled first row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('edu');
      assertEquals(3, rend.getRenderedRows().length);
      // The first row is disabled, second should be highlighted.
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since wrap is on and first row is disabled,
      // this will go back to 1.
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      // first is disabled, so wrap and select the last.
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ off and a disabled middle row.
   */
  testHiliteNextPrevWithDisabledMiddleRow_wrap() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled middle row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('u');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled and should be skipped.
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since wrap is on, this will go back to 0.
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, selects last.
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ off and a disabled last row.
   */
  testHiliteNextPrevWithDisabledLastRow_wrap() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled last row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('h');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      // try going over the edge since last row is disabled. Since wrap is on,
      // this will go back to 0.
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, since wrap is on and last row is disabled,
      // this will select the second last.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on.
   */
  testHiliteNextPrev_wrapAndAllowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('the');
      assertEquals(4, rend.getRenderedRows().length);
      // check to see if we can select the last of the 4 items
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);
      // try going over the edge. Since free select is on, this should go
      // to -1.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 3);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on and a disabled first row.
   */
  testHiliteNextPrevWithDisabledFirstRow_wrapAndAllowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled first row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('edu');
      assertEquals(3, rend.getRenderedRows().length);
      // The first row is disabled, second should be highlighted.
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since free select is on, this should go to -1.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list, fist row is disabled
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on and a disabled middle row.
   */
  testHiliteNextPrevWithDisabledMiddleRow_wrapAndAllowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled middle row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('u');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled and should be skipped.
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since free select is on, this should go to -1
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on and a disabled last row.
   */
  testHiliteNextPrevWithDisabledLastRow_wrapAndAllowFreeSelect() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled last row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('h');
      assertEquals(3, rend.getRenderedRows().length);
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      // try going over the edge since last row is disabled. Since free select
      // is on, this should go to -1
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to the second last, since last is disabled.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on AND turn autoHilite_ off.
   */
  testHiliteNextPrev_wrapAndAllowFreeSelectNoAutoHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(false);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('the');
      assertEquals(4, rend.getRenderedRows().length);
      // check to see if we can select the last of the 4 items.
      // Initially nothing should be selected since autoHilite_ is off.
      checkHilitedIndex(rend, -1);
      ac.hilitePrev();
      checkHilitedIndex(rend, 3);
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, 3);
      // try going over the edge. Since free select is on, this should go
      // to -1.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 3);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on AND turn autoHilite_ off, and a disabled first row.
   */
  testHiliteNextPrevWithDisabledFirstRow_wrapAndAllowFreeSelectNoAutoHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(false);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled first row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('edu');
      assertEquals(3, rend.getRenderedRows().length);
      // Initially nothing should be selected since autoHilite_ is off.
      checkHilitedIndex(rend, -1);
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);
      ac.hiliteNext();
      // First row is disabled.
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since free select is on, this should go to -1
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list, first row is disabled
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on AND turn autoHilite_ off, and a disabled middle row.
   */
  testHiliteNextPrevWithDisabledMiddleRow_wrapAndAllowFreeSelectNoAutoHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(false);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled middle row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('u');
      assertEquals(3, rend.getRenderedRows().length);
      // Initially nothing should be selected since autoHilite_ is off.
      checkHilitedIndex(rend, -1);
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled
      checkHilitedIndex(rend, 2);
      // try going over the edge. Since free select is on, this should go to -1.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      // Second row is disabled.
      checkHilitedIndex(rend, 2);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 2);
    }
  },

  /**
   * Try using next and prev to navigate past the ends with wrap_ on
   * allowFreeSelect_ on AND turn autoHilite_ off, and a disabled last row.
   */
  testHiliteNextPrevWithDisabledLastRow_wrapAndAllowFreeSelectNoAutoHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(false);

    // make sure 'next' and 'prev' don't explode before any token is set
    ac.hiliteNext();
    ac.hilitePrev();
    ac.setMaxMatches(4);
    assertEquals(0, rend.getRenderedRows().length);

    // check a few times with disabled last row
    for (let i = 0; i < 3; ++i) {
      ac.setToken('');
      ac.setToken('h');
      assertEquals(3, rend.getRenderedRows().length);
      // Initially nothing should be selected since autoHilite_ is off.
      checkHilitedIndex(rend, -1);
      ac.hilitePrev();
      // Last row is disabled
      checkHilitedIndex(rend, 1);
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);
      // try going over the edge. Since free select is on, this should go to -1.
      ac.hiliteNext();
      checkHilitedIndex(rend, -1);

      // go back down the list
      ac.hiliteNext();
      checkHilitedIndex(rend, 0);
      ac.hiliteNext();
      checkHilitedIndex(rend, 1);

      // go back up the list.
      ac.hilitePrev();
      checkHilitedIndex(rend, 0);
      // go back above the first, free select.
      ac.hilitePrev();
      checkHilitedIndex(rend, -1);
      // wrap to last
      ac.hilitePrev();
      checkHilitedIndex(rend, 1);
    }
  },

  testHiliteWithChangingNumberOfRows() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setAutoHilite(true);
    ac.setMaxMatches(4);

    ac.setToken('m');
    assertEquals(4, rend.getRenderedRows().length);
    checkHilitedIndex(rend, 0);

    ac.setToken('ma');
    assertEquals(3, rend.getRenderedRows().length);
    checkHilitedIndex(rend, 0);

    // Hilite the second element
    let id = rend.getRenderedRows()[1].id;
    ac.hiliteId(id);

    ac.setToken('mar');
    assertEquals(1, rend.getRenderedRows().length);
    checkHilitedIndex(rend, 0);

    ac.setToken('ma');
    assertEquals(3, rend.getRenderedRows().length);
    checkHilitedIndex(rend, 0);

    // Hilite the second element
    id = rend.getRenderedRows()[1].id;
    ac.hiliteId(id);

    ac.setToken('m');
    assertEquals(4, rend.getRenderedRows().length);
    checkHilitedIndex(rend, 0);
  },

  /**
   * Checks that autohilite is disabled when there is no token; this allows the
   * user to tab out of an empty autocomplete.
   */
  testNoAutoHiliteWhenTokenIsEmpty() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(true);
    ac.setMaxMatches(4);

    ac.setToken('');
    assertEquals(4, rend.getRenderedRows().length);
    // No token; nothing should be hilited.
    checkHilitedIndex(rend, -1);

    ac.setToken('the');
    assertEquals(4, rend.getRenderedRows().length);
    // Now there is a token, so the first row should be highlighted.
    checkHilitedIndex(rend, 0);
  },

  /** Checks that opt_preserveHilited works. */
  testPreserveHilitedWithoutAutoHilite() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setMaxMatches(4);
    ac.setAutoHilite(false);

    ac.setToken('m');
    assertEquals(4, rend.getRenderedRows().length);
    // No token; nothing should be hilited.
    checkHilitedIndex(rend, -1);

    // Hilite the second element
    const id = rend.getRenderedRows()[1].id;
    ac.hiliteId(id);

    checkHilitedIndex(rend, 1);

    // Re-render and check if the second element is still hilited
    ac.renderRows(rend.getRenderedRows(), true /* preserve hilite */);

    checkHilitedIndex(rend, 1);

    // Re-render without preservation
    ac.renderRows(rend.getRenderedRows());

    checkHilitedIndex(rend, -1);
  },

  /** Checks that the autohilite argument "true" of the matcher is used. */
  testAutoHiliteFromMatcherTrue() {
    const ds = new MockDS(true);
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(false);  // Will be overruled.
    ac.setMaxMatches(4);

    ac.setToken('the');
    assertEquals(4, rend.getRenderedRows().length);
    // The first row should be highlighted.
    checkHilitedIndex(rend, 0);
  },

  /** Checks that the autohilite argument "false" of the matcher is used. */
  testAutoHiliteFromMatcherFalse() {
    const ds = new MockDS(false);
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setWrap(true);
    ac.setAllowFreeSelect(true);
    ac.setAutoHilite(true);  // Will be overruled.
    ac.setMaxMatches(4);

    ac.setToken('the');
    assertEquals(4, rend.getRenderedRows().length);
    // The first row should not be highlighted.
    checkHilitedIndex(rend, -1);
  },

  /** Hilite using ids, the way mouse-based hiliting would work. */
  testHiliteId() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    // check a few times
    for (let i = 0; i < 3; ++i) {
      ac.setToken('m');
      assertEquals(4, rend.getRenderedRows().length);
      // try hiliting all 3
      for (let x = 0; x < 4; ++x) {
        const id = rend.getRenderedRows()[x].id;
        ac.hiliteId(id);
        assertEquals(ac.getIdOfIndex_(x), id);
      }
    }
  },

  /** Test selecting the hilited row */
  testSelection() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    let ac;

    // try with default selection
    ac = new AutoComplete(ds, rend, select);
    ac.setToken('m');
    ac.selectHilited();
    assertEquals(
        '"Slartibartfast Theadore" <fjordmaster@magrathea.com>',
        select.selectedRow);

    // try second item
    ac = new AutoComplete(ds, rend, select);
    ac.setToken('the');
    ac.hiliteNext();
    ac.selectHilited();
    assertEquals('"Ford Prefect" <ford@theguide.com>', select.selectedRow);
  },

  /** Dismiss when empty and non-empty */
  testDismiss() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();

    // dismiss empty
    let ac = new AutoComplete(ds, rend, select);
    let dismissed = 0;
    handler.listen(ac, AutoComplete.EventType.DISMISS, () => {
      dismissed++;
    });
    ac.dismiss();
    assertEquals(1, dismissed);

    ac = new AutoComplete(ds, rend, select);
    ac.setToken('sir not seen in this picture');
    ac.dismiss();

    // dismiss with contents
    ac = new AutoComplete(ds, rend, select);
    ac.setToken('t');
    ac.dismiss();
  },

  testTriggerSuggestionsOnUpdate() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);

    let dismissCalled = 0;
    rend.dismiss = () => {
      dismissCalled++;
    };

    let updateCalled = 0;
    select.update = (opt_force) => {
      updateCalled++;
    };

    // Normally, menu is dismissed after selecting row (without updating).
    ac.setToken('the');
    ac.selectHilited();
    assertEquals(1, dismissCalled);
    assertEquals(0, updateCalled);

    // But not if we re-trigger on update.
    ac.setTriggerSuggestionsOnUpdate(true);
    ac.setToken('the');
    ac.selectHilited();
    assertEquals(1, dismissCalled);
    assertEquals(1, updateCalled);
  },

  testDispose() {
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setToken('the');
    ac.dispose();
  },

  /** Ensure that activedescendant is updated properly. */
  testRolesAndStates() {
    function checkActiveDescendant(activeDescendant) {
      assertNotNull(inputElement);
      assertEquals(aria.getActiveDescendant(inputElement), activeDescendant);
    }
    function checkRole(el, role) {
      assertNotNull(el);
      assertEquals(aria.getRole(el), role);
    }
    const ds = new MockDS();
    const rend = new TestRend();
    const select = new MockSelect();
    const ac = new AutoComplete(ds, rend, select);
    ac.setTarget(inputElement);

    // initially activedescendant is not set
    checkActiveDescendant(null);

    // highlight the matching row and check that activedescendant updates
    ac.setToken('');
    ac.setToken('the');
    ac.hiliteNext();
    checkActiveDescendant(rend.getHilitedRowDiv());

    // highligted row should have a role of 'option'
    checkRole(rend.getHilitedRowDiv(), Role.OPTION);

    // closing the autocomplete should clear activedescendant
    ac.dismiss();
    checkActiveDescendant(null);
  },

  testAttachInputWithAnchor() {
    const anchorElement = dom.createDom(TagName.DIV, null, inputElement);

    const mockRenderer = mockControl.createLooseMock(Renderer, true);
    mockRenderer.setAnchorElement(anchorElement);
    const ignore = mockmatchers.ignoreArgument;
    mockRenderer.renderRows(ignore, ignore, inputElement);

    const mockInputHandler = mockControl.createLooseMock(InputHandler, true);
    mockInputHandler.attachInputs(inputElement);

    mockControl.$replayAll();
    const autoComplete = new AutoComplete(null, mockRenderer, mockInputHandler);
    autoComplete.attachInputWithAnchor(inputElement, anchorElement);
    autoComplete.setTarget(inputElement);

    autoComplete.renderRows(['abc', 'def']);
    mockControl.$verifyAll();
  },

  testDetachInputWithAnchor() {
    const mockRenderer = mockControl.createLooseMock(Renderer, true);
    const mockInputHandler = mockControl.createLooseMock(InputHandler, true);
    const anchorElement = dom.createDom(TagName.DIV, null, inputElement);
    const inputElement2 = dom.createDom(TagName.INPUT, {type: InputType.TEXT});
    const anchorElement2 = dom.createDom(TagName.DIV, null, inputElement2);

    mockControl.$replayAll();
    const autoComplete = new AutoComplete(null, mockRenderer, mockInputHandler);

    autoComplete.attachInputWithAnchor(inputElement, anchorElement);
    autoComplete.attachInputWithAnchor(inputElement2, anchorElement2);
    autoComplete.detachInputs(inputElement, inputElement2);

    assertFalse(goog.getUid(inputElement) in autoComplete.inputToAnchorMap_);
    assertFalse(goog.getUid(inputElement2) in autoComplete.inputToAnchorMap_);
    mockControl.$verifyAll();
  },
});


text:
package com.fivium.scriptrunner2.script;

import com.fivium.scriptrunner2.database.DatabaseConnection;

import java.sql.SQLException;

/**
 * Interface for any statement in a script which needs to be executed. This could be a SQL statement or script control command
 * (e.g. CONNECT, DISCONNECT, etc). <tt>ScriptExectuable</tt>s are created by parsing script strings using methods on
 * the {@link ScriptExecutableParser}class.
 */
public interface ScriptExecutable {

  /**
   * Executes this command on the database, using the provided connection. Some commands may alter the state of the
   * connection object.
   * @param pDatabaseConnection Database connection to operate on.
   * @throws SQLException If an error occurs on the database.
   */
  public void execute(DatabaseConnection pDatabaseConnection) throws SQLException;

  /**
   * Gets a string representation of this command for diagnostic or reporting purposes.
   * @return
   */
  public String getDisplayString();
}