text:
namespace Sitecore.Ecommerce.Apps.Web.UI.WebControls.Buttons
{
  using Diagnostics;
  using Ecommerce.OrderManagement;
  using Merchant.OrderManagement;
  using OrderManagement.ContextStrategies;
  using Speak.Web.UI.WebControls;

  /// <summary>
  /// Defines the smart panel buttons class.
  /// </summary>
  public abstract class OmSmartPanelButtons : SmartPanelButtons
  {
    /// <summary>
    ///  Merchant order processor.
    /// </summary>
    private MerchantOrderProcessor orderProcessor;

    /// <summary>
    /// Order line resolver.
    /// </summary>
    private UblEntityResolvingStrategy ublEntityResolver;

    /// <summary>
    /// Gets or sets the strategy.
    /// </summary>
    /// <value>
    /// The strategy.
    /// </value>
    [NotNull]
    public virtual OrderProcessingStrategy Strategy { get; set; }

    /// <summary>
    /// Gets or sets the order processor.
    /// </summary>
    /// <value>
    /// The order processor.
    /// </value>
    [NotNull]
    public virtual MerchantOrderProcessor OrderProcessor
    {
      get
      {
        return this.orderProcessor ?? (this.orderProcessor = Ecommerce.Context.Entity.Resolve<MerchantOrderProcessor>());
      }

      set
      {
        Assert.ArgumentNotNull(value, "value");

        this.orderProcessor = value;
      }
    }

    /// <summary>
    /// Gets or sets the order processor.
    /// </summary>
    /// <value>
    /// The order processor.
    /// </value>
    [NotNull]
    public virtual UblEntityResolvingStrategy UblEntityResolver
    {
      get
      {
        return this.ublEntityResolver ?? (this.ublEntityResolver = new OnSmartPanelOrderLineStrategy());
      }

      set
      {
        Assert.ArgumentNotNull(value, "value");

        this.ublEntityResolver = value;
      }
    }

    /// <summary>
    /// Initializes the leave without saving warning.
    /// </summary>
    protected override void InitializeLeaveWithoutSavingWarning()
    {
    }
  }
}


text:
"""
Copyright 2016 Giacomo Vercesi

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.
"""

try:
    import urllib2
except ImportError:
    import urllib.request as urllib2

import json

def get_status_www(mode):
    """Fetches poul status via web interface
    mode specifies the return standard
    0 - open/closed (legacy)
    1 - open/close (new)
    2 - open (1)/ close (0) (int-bool)
    """
    web_data = urllib2.urlopen("https://bits.poul.org/data").read()
    status = json.loads(web_data.decode('utf8'))['status']['value']
    if mode == 1 and status == 'closed':
        status = 'close'
    if mode == 2:
        return {'open':1,'closed':0}[status]
    return status

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * @LICENSE_TEXT
 */

namespace Che\Phenotype\Factory;

/**
 * Class TypeFactory
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
interface TypeFactory
{
    public function supportsValue($value);
    public function createType($value);
}


text: Replaces a simple call to String.format() with a string concatenation.


text:
class ValidacionSimple < Validacion

  attr_accessor :lista

  COLUMNAS_OBLIGATORIAS = {nombre_cientifico: ['nombre_cientifico']}
  COLUMNAS_OPCIONALES = {}
  COLUMNAS_DEFAULT = %w(nombre_original nombre_valido_enciclovida mensaje)

  def initialize
    self.lista = []
    super
  end

  def valida_archivo
    super

    sheet.parse(cabecera).each_with_index do |f, index|
      next if index == 0
      self.nombre_cientifico = f['nombre_cientifico']
      encuentra_por_nombre
      quita_sinonimos_coincidencias if validacion[:taxones].present?
      taxon_estatus
      self.recurso_validado << validacion.merge({nombre_orig: f['nombre_cientifico']})
    end

    resp = guarda_excel

    if resp[:estatus]
      self.excel_url = resp[:excel_url]
      EnviaCorreo.excel(self).deliver
    end
  end

  def valida_lista
    return {estatus: false, msg: 'La lista no puede ser vacia.'} unless lista.present?

    self.lista = lista.split("\r\n")
    return {estatus: false, msg: 'Solo pueden ser 200 observaciones para validar en el área de texto, si requieres validar más por favor sube un archivo.'} if lista.length > 200

    lista.each do |nombre|
      self.nombre_cientifico = nombre
      encuentra_por_nombre
      quita_sinonimos_coincidencias if validacion[:taxones].present?
      taxon_estatus

      self.recurso_validado << validacion.merge({nombre_orig: nombre})
    end

    {estatus: true}
  end

  # Exporta la informacion, para que desde la lista guarde el excel
  def guarda_excel
    lista = Lista.new
    lista.columnas_array = (COLUMNAS_DEFAULT + Lista::COLUMNAS_GENERALES + Lista::COLUMNAS_FOTOS)
    lista.taxones = recurso_validado
    lista.to_excel(asignar: true)  # Para que asigne los valores de las columnas
  end
end


text:
namespace content {

class UnitTestTestSuite::UnitTestEventListener
    : public testing::EmptyTestEventListener {
 public:
  UnitTestEventListener(
      base::RepeatingCallback<
          std::unique_ptr<UnitTestTestSuite::ContentClients>()> create_clients,
      base::OnceClosure first_test_start_callback)
      : create_clients_(create_clients),
        first_test_start_callback_(std::move(first_test_start_callback)) {}

  UnitTestEventListener(const UnitTestEventListener&) = delete;
  UnitTestEventListener& operator=(const UnitTestEventListener&) = delete;

  void InitializeObjects() {
    test_network_connection_tracker_ =
        network::TestNetworkConnectionTracker::CreateInstance();
    SetNetworkConnectionTrackerForTesting(
        network::TestNetworkConnectionTracker::GetInstance());

    notification_service_ = std::make_unique<NotificationServiceImpl>();

    content_clients_ = create_clients_.Run();
    CHECK(content_clients_->content_client.get());
    SetContentClient(content_clients_->content_client.get());
    SetBrowserClientForTesting(content_clients_->content_browser_client.get());
    SetUtilityClientForTesting(content_clients_->content_utility_client.get());

    if (first_test_start_callback_)
      std::move(first_test_start_callback_).Run();
  }

  void OnTestStart(const testing::TestInfo& test_info) override {
    InitializeObjects();
  }

  void OnTestEnd(const testing::TestInfo& test_info) override {
    // Don't call SetUtilityClientForTesting or SetBrowserClientForTesting since
    // if a test overrode ContentClient it might already be deleted and setting
    // these pointers on it would result in a UAF.
    SetContentClient(nullptr);
    content_clients_.reset();

    SetNetworkConnectionTrackerForTesting(nullptr);
    test_network_connection_tracker_.reset();
    notification_service_.reset();

    // If the network::NetworkService object was instantiated during a unit test
    // it will be deleted because network_service_instance.cc has it in a
    // SequenceLocalStorageSlot. However we want to synchronously destruct the
    // InterfacePtr pointing to it to avoid it getting the connection error
    // later and have other tests use the InterfacePtr that is invalid.
    ResetNetworkServiceForTesting();
  }

 private:
  base::RepeatingCallback<std::unique_ptr<UnitTestTestSuite::ContentClients>()>
      create_clients_;
  base::OnceClosure first_test_start_callback_;
  std::unique_ptr<network::TestNetworkConnectionTracker>
      test_network_connection_tracker_;
  std::unique_ptr<NotificationServiceImpl> notification_service_;
  std::unique_ptr<UnitTestTestSuite::ContentClients> content_clients_;
};

UnitTestTestSuite::ContentClients::ContentClients() = default;
UnitTestTestSuite::ContentClients::~ContentClients() = default;

std::unique_ptr<UnitTestTestSuite::ContentClients>
UnitTestTestSuite::CreateTestContentClients() {
  auto clients = std::make_unique<UnitTestTestSuite::ContentClients>();
  clients->content_client = std::make_unique<TestContentClient>();
  clients->content_browser_client =
      std::make_unique<TestContentBrowserClient>();
  return clients;
}

UnitTestTestSuite::UnitTestTestSuite(
    base::TestSuite* test_suite,
    base::RepeatingCallback<std::unique_ptr<ContentClients>()> create_clients)
    : test_suite_(test_suite), create_clients_(create_clients) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  std::string enabled =
      command_line->GetSwitchValueASCII(switches::kEnableFeatures);
  std::string disabled =
      command_line->GetSwitchValueASCII(switches::kDisableFeatures);

  ForceCreateNetworkServiceDirectlyForTesting();
  StoragePartitionImpl::ForceInProcessStorageServiceForTesting();

  testing::TestEventListeners& listeners =
      testing::UnitTest::GetInstance()->listeners();
  listeners.Append(CreateTestEventListener());
  listeners.Append(new CheckForLeakedWebUIRegistrations);

  scoped_feature_list_.InitFromCommandLine(enabled, disabled);

  // Do this here even though TestBlinkWebUnitTestSupport calls it since a
  // multi process unit test won't get to create TestBlinkWebUnitTestSupport.
  // This is safe to call multiple times.
  mojo::core::InitFeatures();
  InitializeMojo();

#if BUILDFLAG(IS_FUCHSIA)
  // Use headless ozone platform on Fuchsia by default.
  // TODO(crbug.com/865172): Remove this flag.
  if (!command_line->HasSwitch(switches::kOzonePlatform))
    command_line->AppendSwitchASCII(switches::kOzonePlatform, "headless");
#endif

  DCHECK(test_suite);
  test_host_resolver_ = std::make_unique<TestHostResolver>();
}

UnitTestTestSuite::~UnitTestTestSuite() = default;

int UnitTestTestSuite::Run() {
#if defined(USE_AURA)
  std::unique_ptr<aura::Env> aura_env = aura::Env::CreateInstance();
#endif
  std::unique_ptr<url::ScopedSchemeRegistryForTests> scheme_registry;

  // TestEventListeners repeater event propagation is disabled in death test
  // child process so create and set the clients here for it.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          "gtest_internal_run_death_test")) {
    // TestSuite::Initialize hasn't run yet, which is what initializes the
    // ResourceBundle. This will be needed by Blink initialization to load
    // resources, so do it temporarily here.
    ContentTestSuiteBase::InitializeResourceBundle();

    CreateTestEventListener()->InitializeObjects();

    // Since Blink initialization ended up using the SchemeRegistry, reset
    // that it was accessed before testSuite::Initialize registers its schemes.
    scheme_registry = std::make_unique<url::ScopedSchemeRegistryForTests>();

    ui::ResourceBundle::CleanupSharedInstance();
  }

  return test_suite_->Run();
}

UnitTestTestSuite::UnitTestEventListener*
UnitTestTestSuite::CreateTestEventListener() {
  return new UnitTestEventListener(
      create_clients_,
      base::BindOnce(&UnitTestTestSuite::OnFirstTestStartComplete,
                     base::Unretained(this)));
}

void UnitTestTestSuite::OnFirstTestStartComplete() {
  // At this point ContentClient and ResourceBundle will be initialized, which
  // this needs.
  blink_test_support_ = std::make_unique<TestBlinkWebUnitTestSupport>();
}

}  // namespace content


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~
  ~
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>onos-ietfte-providers</artifactId>
        <groupId>org.onosproject</groupId>
        <version>1.9.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>onos-ietfte-provider-utils</artifactId>
    <packaging>bundle</packaging>
    <dependencies>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-app-yms-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-restconf-server-utils</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


text:
from marshmallow import Schema, fields

class CategorySchema(Schema):
    id = fields.Int()
    name = fields.Str()


text:
require 'spec/parsing/parsed_css_asset'

require 'spec/expected/base_expected_asset'

module Spec
  module Expected
    class ExpectedAsset < BaseExpectedAsset
      def initialize(root_directory, expected_subpath, options = { }, &block)
        super(root_directory, expected_subpath)

        @expected_rules = { }
        @allow_extra_rules = false
        @options = options

        options.assert_valid_keys(:sequencing)

        instance_eval(&block) if block
      end

      def source
        out = ""
        expected_rules.each do |selector, rules|
          out << "#{selector} {\n"
          rules.each do |rule|
            out << "  #{rule}\n"
          end
          out << "}\n\n"
        end
        out.strip
      end

      def expect_rules(selector, *rules)
        selector = selector.to_s
        expected_rules[selector] ||= [ ]
        expected_rules[selector] += rules
      end
      alias_method :expect_rule, :expect_rules

      def expect_wrapped_rules(selector, *rules)
        wrapped_selector = wrap_selector(selector)
        expect_rules(wrapped_selector, *rules)
      end
      alias_method :expect_wrapped_rule, :expect_wrapped_rules

      def allow_extra_rules!
        @allow_extra_rules = true
      end

      def should_match(remaining_assets)
        matching_remaining_assets = applicable_assets_from(remaining_assets)

        if matching_remaining_assets.length == 0
          message = "Expected match not found:\n  #{self}\nnot found in these assets:"
          remaining_assets.each do |remaining_asset|
            message << "\n\n    #{remaining_asset}:\n        #{remaining_asset.source}\n"
          end
          raise message
        elsif matching_remaining_assets.length == 1 || options[:sequencing]
          matching_remaining_asset = matching_remaining_assets.first

          unless asset_matches?(matching_remaining_asset)
            raise "Asset mismatch for #{matching_remaining_asset.where_from}: expected\n  #{source}\ndoes not match actual\n  #{matching_remaining_asset.source}"
          end

          [ matching_remaining_asset ]
        elsif matching_remaining_assets.length > 1
          message = "Multiple assets match:\n  #{self}\nin:"
          matching_remaining_assets.each do |matching_remaining_asset|
            message << "\n\n    #{matching_remaining_asset}:\n        #{matching_remaining_asset.source}\n"
          end
          raise message
        end
      end

      def parcels_wrapping_class
        @parcels_wrapping_class ||= begin
          out = expected_subpath.dup
          out = $1 if out =~ /^(.*?)\.([^\/]+)$/i
          out = out.gsub('/', '__').gsub(/[^A-Za-z0-9_]/, '_')
          "parcels_class__#{out}"
        end
      end

      private
      attr_reader :expected_rules, :options

      def extra_rules_allowed?
        !! @allow_extra_rules
      end

      def wrap_selector(selector)
        if selector
          ".#{parcels_wrapping_class} #{selector}"
        else
          ".#{parcels_wrapping_class}"
        end
      end

      def asset_matches?(asset)
        parsed_asset = ::Spec::Parsing::ParsedCssAsset.new(asset)

        actual_rules = parsed_asset.style_rules.dup

        expected_rules.each do |expected_selector, expected_rules_for_this_selector|
          actual_rules_for_this_selector = actual_rules[expected_selector]
          return false unless actual_rules_for_this_selector

          matches = (actual_rules_for_this_selector.length == expected_rules_for_this_selector.length)
          if matches
            actual_rules_for_this_selector.each_with_index do |actual_rule, index|
              expected_rule = expected_rules_for_this_selector[index]

              this_matches = if expected_rule.kind_of?(String)
                actual_rule == expected_rule
              elsif expected_rule.kind_of?(Regexp)
                actual_rule =~ expected_rule
              else
                false
              end

              matches &&= this_matches
            end

            actual_rules.delete(expected_selector)
          end

          return false unless matches
        end

        if actual_rules.length > 0 && (! extra_rules_allowed?)
          return false
        end

        true
      end
    end
  end
end


text:
package org.apache.pulsar.metadata.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.stats.OpStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
import org.apache.bookkeeper.util.MathUtils;
import org.apache.bookkeeper.zookeeper.BoundExponentialBackoffRetryPolicy;
import org.apache.bookkeeper.zookeeper.RetryPolicy;
import org.apache.bookkeeper.zookeeper.ZooKeeperWatcherBase;
import org.apache.zookeeper.AddWatchMode;
import org.apache.zookeeper.AsyncCallback.ACLCallback;
import org.apache.zookeeper.AsyncCallback.Children2Callback;
import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.AsyncCallback.MultiCallback;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.OpResult;
import org.apache.zookeeper.Transaction;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

/**
 * Provide a zookeeper client to handle session expire.
 */
@Slf4j
public class PulsarZooKeeperClient extends ZooKeeper implements Watcher, AutoCloseable {

    private static final int DEFAULT_RETRY_EXECUTOR_THREAD_COUNT = 1;

    // ZooKeeper client connection variables
    private final String connectString;
    private final int sessionTimeoutMs;
    private final boolean allowReadOnlyMode;

    // state for the zookeeper client
    private final AtomicReference<ZooKeeper> zk = new AtomicReference<ZooKeeper>();
    private final AtomicBoolean closed = new AtomicBoolean(false);
    private final ZooKeeperWatcherBase watcherManager;

    private final ScheduledExecutorService retryExecutor;
    private final ExecutorService connectExecutor;

    // rate limiter
    private final RateLimiter rateLimiter;

    // retry polices
    private final RetryPolicy connectRetryPolicy;
    private final RetryPolicy operationRetryPolicy;

    // Stats Logger
    private final OpStatsLogger createStats;
    private final OpStatsLogger getStats;
    private final OpStatsLogger setStats;
    private final OpStatsLogger deleteStats;
    private final OpStatsLogger getChildrenStats;
    private final OpStatsLogger existsStats;
    private final OpStatsLogger multiStats;
    private final OpStatsLogger getACLStats;
    private final OpStatsLogger setACLStats;
    private final OpStatsLogger syncStats;
    private final OpStatsLogger createClientStats;

    private final Runnable clientCreator = new Runnable() {

        @Override
        public void run() {
            try {
                ZooWorker.syncCallWithRetries(null, new ZooWorker.ZooCallable<ZooKeeper>() {

                    @Override
                    public ZooKeeper call() throws KeeperException, InterruptedException {
                        log.info("Reconnecting zookeeper {}.", connectString);
                        // close the previous one
                        closeZkHandle();
                        ZooKeeper newZk;
                        try {
                            newZk = createZooKeeper();
                        } catch (IOException ie) {
                            log.error("Failed to create zookeeper instance to " + connectString, ie);
                            throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
                        }
                        waitForConnection();
                        zk.set(newZk);
                        log.info("ZooKeeper session {} is created to {}.",
                                Long.toHexString(newZk.getSessionId()), connectString);
                        return newZk;
                    }

                    @Override
                    public String toString() {
                        return String.format("ZooKeeper Client Creator (%s)", connectString);
                    }

                }, connectRetryPolicy, rateLimiter, createClientStats);
            } catch (Exception e) {
                log.error("Gave up reconnecting to ZooKeeper : ", e);
                Runtime.getRuntime().exit(-1);
            }
        }

    };

    @VisibleForTesting
    static PulsarZooKeeperClient createConnectedZooKeeperClient(
            String connectString, int sessionTimeoutMs, Set<Watcher> childWatchers,
            RetryPolicy operationRetryPolicy)
            throws KeeperException, InterruptedException, IOException {
        return PulsarZooKeeperClient.newBuilder()
                .connectString(connectString)
                .sessionTimeoutMs(sessionTimeoutMs)
                .watchers(childWatchers)
                .operationRetryPolicy(operationRetryPolicy)
                .build();
    }

    /**
     * A builder to build retryable zookeeper client.
     */
    public static class Builder {
        String connectString = null;
        int sessionTimeoutMs = 10000;
        Set<Watcher> watchers = null;
        RetryPolicy connectRetryPolicy = null;
        RetryPolicy operationRetryPolicy = null;
        StatsLogger statsLogger = NullStatsLogger.INSTANCE;
        int retryExecThreadCount = DEFAULT_RETRY_EXECUTOR_THREAD_COUNT;
        double requestRateLimit = 0;
        boolean allowReadOnlyMode = false;

        private Builder() {}

        public Builder connectString(String connectString) {
            this.connectString = connectString;
            return this;
        }

        public Builder sessionTimeoutMs(int sessionTimeoutMs) {
            this.sessionTimeoutMs = sessionTimeoutMs;
            return this;
        }

        public Builder watchers(Set<Watcher> watchers) {
            this.watchers = watchers;
            return this;
        }

        public Builder connectRetryPolicy(RetryPolicy retryPolicy) {
            this.connectRetryPolicy = retryPolicy;
            return this;
        }

        public Builder operationRetryPolicy(RetryPolicy retryPolicy) {
            this.operationRetryPolicy = retryPolicy;
            return this;
        }

        public Builder statsLogger(StatsLogger statsLogger) {
            this.statsLogger = statsLogger;
            return this;
        }

        public Builder requestRateLimit(double requestRateLimit) {
            this.requestRateLimit = requestRateLimit;
            return this;
        }

        public Builder retryThreadCount(int numThreads) {
            this.retryExecThreadCount = numThreads;
            return this;
        }

        public Builder allowReadOnlyMode(boolean allowReadOnlyMode) {
            this.allowReadOnlyMode = allowReadOnlyMode;
            return this;
        }

        public PulsarZooKeeperClient build() throws IOException, KeeperException, InterruptedException {
            requireNonNull(connectString);
            checkArgument(sessionTimeoutMs > 0);
            requireNonNull(statsLogger);
            checkArgument(retryExecThreadCount > 0);

            if (null == connectRetryPolicy) {
                // Session expiry event is received by client only when zk quorum is well established.
                // All other connection loss retries happen at zk client library transparently.
                // Hence, we don't need to wait before retrying.
                connectRetryPolicy =
                        new BoundExponentialBackoffRetryPolicy(0, 0, Integer.MAX_VALUE);
            }
            if (null == operationRetryPolicy) {
                operationRetryPolicy =
                        new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0);
            }

            // Create a watcher manager
            StatsLogger watcherStatsLogger = statsLogger.scope("watcher");
            ZooKeeperWatcherBase watcherManager =
                    null == watchers ? new ZooKeeperWatcherBase(sessionTimeoutMs, watcherStatsLogger) :
                            new ZooKeeperWatcherBase(sessionTimeoutMs, watchers, watcherStatsLogger);
            PulsarZooKeeperClient client = new PulsarZooKeeperClient(
                    connectString,
                    sessionTimeoutMs,
                    watcherManager,
                    connectRetryPolicy,
                    operationRetryPolicy,
                    statsLogger,
                    retryExecThreadCount,
                    requestRateLimit,
                    allowReadOnlyMode
            );
            // Wait for connection to be established.
            try {
                watcherManager.waitForConnection();
            } catch (KeeperException ke) {
                client.close();
                throw ke;
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                client.close();
                throw ie;
            }
            return client;
        }
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    protected PulsarZooKeeperClient(String connectString,
                              int sessionTimeoutMs,
                              ZooKeeperWatcherBase watcherManager,
                              RetryPolicy connectRetryPolicy,
                              RetryPolicy operationRetryPolicy,
                              StatsLogger statsLogger,
                              int retryExecThreadCount,
                              double rate,
                              boolean allowReadOnlyMode) throws IOException {
        super(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode);
        this.connectString = connectString;
        this.sessionTimeoutMs = sessionTimeoutMs;
        this.allowReadOnlyMode =  allowReadOnlyMode;
        this.watcherManager = watcherManager;
        this.connectRetryPolicy = connectRetryPolicy;
        this.operationRetryPolicy = operationRetryPolicy;
        this.rateLimiter = rate > 0 ? RateLimiter.create(rate) : null;
        this.retryExecutor =
                Executors.newScheduledThreadPool(retryExecThreadCount,
                        new ThreadFactoryBuilder().setNameFormat("ZKC-retry-executor-%d").build());
        this.connectExecutor =
                Executors.newSingleThreadExecutor(
                        new ThreadFactoryBuilder().setNameFormat("ZKC-connect-executor-%d").build());
        // added itself to the watcher
        watcherManager.addChildWatcher(this);

        // Stats
        StatsLogger scopedStatsLogger = statsLogger.scope("zk");
        createClientStats = scopedStatsLogger.getOpStatsLogger("create_client");
        createStats = scopedStatsLogger.getOpStatsLogger("create");
        getStats = scopedStatsLogger.getOpStatsLogger("get_data");
        setStats = scopedStatsLogger.getOpStatsLogger("set_data");
        deleteStats = scopedStatsLogger.getOpStatsLogger("delete");
        getChildrenStats = scopedStatsLogger.getOpStatsLogger("get_children");
        existsStats = scopedStatsLogger.getOpStatsLogger("exists");
        multiStats = scopedStatsLogger.getOpStatsLogger("multi");
        getACLStats = scopedStatsLogger.getOpStatsLogger("get_acl");
        setACLStats = scopedStatsLogger.getOpStatsLogger("set_acl");
        syncStats = scopedStatsLogger.getOpStatsLogger("sync");
    }

    @Override
    public void close() throws InterruptedException {
        closed.set(true);
        connectExecutor.shutdown();
        retryExecutor.shutdown();
        closeZkHandle();
    }

    private void closeZkHandle() throws InterruptedException {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            super.close();
        } else {
            zkHandle.close();
        }
    }

    public void waitForConnection() throws KeeperException, InterruptedException {
        watcherManager.waitForConnection();
    }

    protected ZooKeeper createZooKeeper() throws IOException {
        return new ZooKeeper(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode);
    }

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == EventType.None
                && event.getState() == KeeperState.Expired) {
            onExpired();
        }
    }

    private void onExpired() {
        if (closed.get()) {
            // we don't schedule any tries if the client is closed.
            return;
        }

        log.info("ZooKeeper session {} is expired from {}.",
                Long.toHexString(getSessionId()), connectString);
        try {
            connectExecutor.execute(clientCreator);
        } catch (RejectedExecutionException ree) {
            if (!closed.get()) {
                log.error("ZooKeeper reconnect task is rejected : ", ree);
            }
        } catch (Exception t) {
            log.error("Failed to submit zookeeper reconnect task due to runtime exception : ", t);
        }
    }

    /**
     * A runnable that retries zookeeper operations.
     */
    abstract static class ZkRetryRunnable implements Runnable {

        final ZooWorker worker;
        final RateLimiter rateLimiter;
        final Runnable that;

        ZkRetryRunnable(RetryPolicy retryPolicy,
                        RateLimiter rateLimiter,
                        OpStatsLogger statsLogger) {
            this.worker = new ZooWorker(retryPolicy, statsLogger);
            this.rateLimiter = rateLimiter;
            that = this;
        }

        @Override
        public void run() {
            if (null != rateLimiter) {
                rateLimiter.acquire();
            }
            zkRun();
        }

        abstract void zkRun();
    }

    // inherits from ZooKeeper client for all operations

    @Override
    public long getSessionId() {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return super.getSessionId();
        }
        return zkHandle.getSessionId();
    }

    @Override
    public byte[] getSessionPasswd() {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return super.getSessionPasswd();
        }
        return zkHandle.getSessionPasswd();
    }

    @Override
    public int getSessionTimeout() {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return super.getSessionTimeout();
        }
        return zkHandle.getSessionTimeout();
    }

    @Override
    public void addAuthInfo(String scheme, byte[] auth) {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            super.addAuthInfo(scheme, auth);
            return;
        }
        zkHandle.addAuthInfo(scheme, auth);
    }

    private void backOffAndRetry(Runnable r, long nextRetryWaitTimeMs) {
        try {
            retryExecutor.schedule(r, nextRetryWaitTimeMs, TimeUnit.MILLISECONDS);
        } catch (RejectedExecutionException ree) {
            if (!closed.get()) {
                log.error("ZooKeeper Operation {} is rejected : ", r, ree);
            }
        }
    }

    private boolean allowRetry(ZooWorker worker, int rc) {
        return worker.allowRetry(rc) && !closed.get();
    }

    @Override
    public synchronized void register(Watcher watcher) {
        watcherManager.addChildWatcher(watcher);
    }

    @Override
    public List<OpResult> multi(final Iterable<Op> ops) throws InterruptedException, KeeperException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<OpResult>>() {

            @Override
            public String toString() {
                return "multi";
            }

            @Override
            public List<OpResult> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.multi(ops);
                }
                return zkHandle.multi(ops);
            }

        }, operationRetryPolicy, rateLimiter, multiStats);
    }

    @Override
    public void multi(final Iterable<Op> ops,
                      final MultiCallback cb,
                      final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {

            final MultiCallback multiCb = new MultiCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, results);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.multi(ops, multiCb, worker);
                } else {
                    zkHandle.multi(ops, multiCb, worker);
                }
            }

            @Override
            public String toString() {
                return "multi";
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    @Deprecated
    public Transaction transaction() {
        // since there is no reference about which client that the transaction could use
        // so just use ZooKeeper instance directly.
        // you'd better to use {@link #multi}.
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return super.transaction();
        }
        return zkHandle.transaction();
    }

    @Override
    public List<ACL> getACL(final String path, final Stat stat) throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<ACL>>() {

            @Override
            public String toString() {
                return String.format("getACL (%s, stat = %s)", path, stat);
            }

            @Override
            public List<ACL> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getACL(path, stat);
                }
                return zkHandle.getACL(path, stat);
            }

        }, operationRetryPolicy, rateLimiter, getACLStats);
    }

    @Override
    public void getACL(final String path, final Stat stat, final ACLCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getACLStats) {

            final ACLCallback aclCb = new ACLCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, acl, stat);
                    }
                }

            };

            @Override
            public String toString() {
                return String.format("getACL (%s, stat = %s)", path, stat);
            }

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getACL(path, stat, aclCb, worker);
                } else {
                    zkHandle.getACL(path, stat, aclCb, worker);
                }
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public Stat setACL(final String path, final List<ACL> acl, final int version)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() {

            @Override
            public String toString() {
                return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version);
            }

            @Override
            public Stat call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.setACL(path, acl, version);
                }
                return zkHandle.setACL(path, acl, version);
            }

        }, operationRetryPolicy, rateLimiter, setACLStats);
    }

    @Override
    public void setACL(final String path, final List<ACL> acl, final int version,
                       final StatCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setACLStats) {

            final StatCallback stCb = new StatCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, stat);
                    }
                }

            };

            @Override
            public String toString() {
                return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version);
            }

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.setACL(path, acl, version, stCb, worker);
                } else {
                    zkHandle.setACL(path, acl, version, stCb, worker);
                }
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void sync(final String path, final VoidCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, syncStats) {

            final VoidCallback vCb = new VoidCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context);
                    }
                }

            };

            @Override
            public String toString() {
                return String.format("sync (%s)", path);
            }

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.sync(path, vCb, worker);
                } else {
                    zkHandle.sync(path, vCb, worker);
                }
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public States getState() {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return PulsarZooKeeperClient.super.getState();
        } else {
            return zkHandle.getState();
        }
    }

    @Override
    public String toString() {
        ZooKeeper zkHandle = zk.get();
        if (null == zkHandle) {
            return PulsarZooKeeperClient.super.toString();
        } else {
            return zkHandle.toString();
        }
    }

    @Override
    public String create(final String path, final byte[] data,
                         final List<ACL> acl, final CreateMode createMode)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<String>() {

            @Override
            public String call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.create(path, data, acl, createMode);
                }
                return zkHandle.create(path, data, acl, createMode);
            }

            @Override
            public String toString() {
                return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
            }

        }, operationRetryPolicy, rateLimiter, createStats);
    }

    @Override
    public void create(final String path, final byte[] data, final List<ACL> acl,
                       final CreateMode createMode, final StringCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {

            final StringCallback createCb = new StringCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, String name) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, name);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.create(path, data, acl, createMode, createCb, worker);
                } else {
                    zkHandle.create(path, data, acl, createMode, createCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void delete(final String path, final int version) throws KeeperException, InterruptedException {
        ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Void>() {

            @Override
            public Void call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.delete(path, version);
                } else {
                    zkHandle.delete(path, version);
                }
                return null;
            }

            @Override
            public String toString() {
                return String.format("delete (%s, version = %d)", path, version);
            }

        }, operationRetryPolicy, rateLimiter, deleteStats);
    }

    @Override
    public void delete(final String path, final int version, final VoidCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) {

            final VoidCallback deleteCb = new VoidCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.delete(path, version, deleteCb, worker);
                } else {
                    zkHandle.delete(path, version, deleteCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("delete (%s, version = %d)", path, version);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public Stat exists(final String path, final Watcher watcher) throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() {

            @Override
            public Stat call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.exists(path, watcher);
                }
                return zkHandle.exists(path, watcher);
            }

            @Override
            public String toString() {
                return String.format("exists (%s, watcher = %s)", path, watcher);
            }

        }, operationRetryPolicy, rateLimiter, existsStats);
    }

    @Override
    public Stat exists(final String path, final boolean watch) throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() {

            @Override
            public Stat call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.exists(path, watch);
                }
                return zkHandle.exists(path, watch);
            }

            @Override
            public String toString() {
                return String.format("exists (%s, watcher = %s)", path, watch);
            }

        }, operationRetryPolicy, rateLimiter, existsStats);
    }

    @Override
    public void exists(final String path, final Watcher watcher, final StatCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) {

            final StatCallback stCb = new StatCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.exists(path, watcher, stCb, worker);
                } else {
                    zkHandle.exists(path, watcher, stCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("exists (%s, watcher = %s)", path, watcher);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void exists(final String path, final boolean watch, final StatCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) {

            final StatCallback stCb = new StatCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.exists(path, watch, stCb, worker);
                } else {
                    zkHandle.exists(path, watch, stCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("exists (%s, watcher = %s)", path, watch);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public byte[] getData(final String path, final Watcher watcher, final Stat stat)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<byte[]>() {

            @Override
            public byte[] call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getData(path, watcher, stat);
                }
                return zkHandle.getData(path, watcher, stat);
            }

            @Override
            public String toString() {
                return String.format("getData (%s, watcher = %s)", path, watcher);
            }

        }, operationRetryPolicy, rateLimiter, getStats);
    }

    @Override
    public byte[] getData(final String path, final boolean watch, final Stat stat)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<byte[]>() {

            @Override
            public byte[] call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getData(path, watch, stat);
                }
                return zkHandle.getData(path, watch, stat);
            }

            @Override
            public String toString() {
                return String.format("getData (%s, watcher = %s)", path, watch);
            }

        }, operationRetryPolicy, rateLimiter, getStats);
    }

    @Override
    public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) {

            final DataCallback dataCb = new DataCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, data, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getData(path, watcher, dataCb, worker);
                } else {
                    zkHandle.getData(path, watcher, dataCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getData (%s, watcher = %s)", path, watcher);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void getData(final String path, final boolean watch, final DataCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) {

            final DataCallback dataCb = new DataCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, data, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getData(path, watch, dataCb, worker);
                } else {
                    zkHandle.getData(path, watch, dataCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getData (%s, watcher = %s)", path, watch);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public Stat setData(final String path, final byte[] data, final int version)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() {

            @Override
            public Stat call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.setData(path, data, version);
                }
                return zkHandle.setData(path, data, version);
            }

            @Override
            public String toString() {
                return String.format("setData (%s, version = %d)", path, version);
            }

        }, operationRetryPolicy, rateLimiter, setStats);
    }

    @Override
    public void setData(final String path, final byte[] data, final int version,
                        final StatCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) {

            final StatCallback stCb = new StatCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.setData(path, data, version, stCb, worker);
                } else {
                    zkHandle.setData(path, data, version, stCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("setData (%s, version = %d)", path, version);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void addWatch(String basePath, Watcher watcher, AddWatchMode mode)
            throws KeeperException, InterruptedException {
        ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Void>() {

            @Override
            public Void call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.addWatch(basePath, watcher, mode);
                } else {
                    zkHandle.addWatch(basePath, watcher, mode);
                }
                return null;
            }

            @Override
            public String toString() {
                return String.format("addWatch (%s, mode = %s)", basePath, mode);
            }

        }, operationRetryPolicy, rateLimiter, setStats);
    }

    @Override
    public void addWatch(String basePath, Watcher watcher, AddWatchMode mode, VoidCallback cb, Object ctx) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) {

            final VoidCallback vCb = new VoidCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        vCb.processResult(rc, basePath, ctx);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.addWatch(basePath, watcher, mode, cb, ctx);
                } else {
                    zkHandle.addWatch(basePath, watcher, mode, cb, ctx);
                }
            }

            @Override
            public String toString() {
                return String.format("setData (%s, mode = %s)", basePath, mode.name());
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public List<String> getChildren(final String path, final Watcher watcher, final Stat stat)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() {

            @Override
            public List<String> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getChildren(path, watcher, stat);
                }
                return zkHandle.getChildren(path, watcher, stat);
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watcher);
            }

        }, operationRetryPolicy, rateLimiter, getChildrenStats);
    }

    @Override
    public List<String> getChildren(final String path, final boolean watch, final Stat stat)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() {

            @Override
            public List<String> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getChildren(path, watch, stat);
                }
                return zkHandle.getChildren(path, watch, stat);
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watch);
            }

        }, operationRetryPolicy, rateLimiter, getChildrenStats);
    }

    @Override
    public void getChildren(final String path, final Watcher watcher,
                            final Children2Callback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

            final Children2Callback childCb = new Children2Callback() {

                @Override
                public void processResult(int rc, String path, Object ctx,
                                          List<String> children, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, children, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
                } else {
                    zkHandle.getChildren(path, watcher, childCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watcher);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void getChildren(final String path, final boolean watch, final Children2Callback cb,
                            final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

            final Children2Callback childCb = new Children2Callback() {

                @Override
                public void processResult(int rc, String path, Object ctx,
                                          List<String> children, Stat stat) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, children, stat);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getChildren(path, watch, childCb, worker);
                } else {
                    zkHandle.getChildren(path, watch, childCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watch);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public List<String> getChildren(final String path, final Watcher watcher)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() {

            @Override
            public List<String> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getChildren(path, watcher);
                }
                return zkHandle.getChildren(path, watcher);
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watcher);
            }

        }, operationRetryPolicy, rateLimiter, getChildrenStats);
    }

    @Override
    public List<String> getChildren(final String path, final boolean watch)
            throws KeeperException, InterruptedException {
        return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() {

            @Override
            public List<String> call() throws KeeperException, InterruptedException {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    return PulsarZooKeeperClient.super.getChildren(path, watch);
                }
                return zkHandle.getChildren(path, watch);
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watch);
            }

        }, operationRetryPolicy, rateLimiter, getChildrenStats);
    }

    @Override
    public void getChildren(final String path, final Watcher watcher,
                            final ChildrenCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

            final ChildrenCallback childCb = new ChildrenCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx,
                                          List<String> children) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, children);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
                } else {
                    zkHandle.getChildren(path, watcher, childCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watcher);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Override
    public void getChildren(final String path, final boolean watch,
                            final ChildrenCallback cb, final Object context) {
        final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

            final ChildrenCallback childCb = new ChildrenCallback() {

                @Override
                public void processResult(int rc, String path, Object ctx,
                                          List<String> children) {
                    ZooWorker worker = (ZooWorker) ctx;
                    if (allowRetry(worker, rc)) {
                        backOffAndRetry(that, worker.nextRetryWaitTime());
                    } else {
                        cb.processResult(rc, path, context, children);
                    }
                }

            };

            @Override
            void zkRun() {
                ZooKeeper zkHandle = zk.get();
                if (null == zkHandle) {
                    PulsarZooKeeperClient.super.getChildren(path, watch, childCb, worker);
                } else {
                    zkHandle.getChildren(path, watch, childCb, worker);
                }
            }

            @Override
            public String toString() {
                return String.format("getChildren (%s, watcher = %s)", path, watch);
            }
        };
        // execute it immediately
        proc.run();
    }

    @Slf4j
    static final class ZooWorker {
        int attempts = 0;
        long startTimeNanos;
        long elapsedTimeMs = 0L;
        final RetryPolicy retryPolicy;
        final OpStatsLogger statsLogger;

        ZooWorker(RetryPolicy retryPolicy, OpStatsLogger statsLogger) {
            this.retryPolicy = retryPolicy;
            this.statsLogger = statsLogger;
            this.startTimeNanos = MathUtils.nowInNano();
        }

        public boolean allowRetry(int rc) {
            elapsedTimeMs = MathUtils.elapsedMSec(startTimeNanos);
            if (!ZooWorker.isRecoverableException(rc)) {
                if (KeeperException.Code.OK.intValue() == rc) {
                    statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos),
                            TimeUnit.MICROSECONDS);
                } else {
                    statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos),
                            TimeUnit.MICROSECONDS);
                }
                return false;
            }
            ++attempts;
            return retryPolicy.allowRetry(attempts, elapsedTimeMs);
        }

        public long nextRetryWaitTime() {
            return retryPolicy.nextRetryWaitTime(attempts, elapsedTimeMs);
        }

        /**
         * Check whether the given result code is recoverable by retry.
         *
         * @param rc result code
         * @return true if given result code is recoverable.
         */
        public static boolean isRecoverableException(int rc) {
            return KeeperException.Code.CONNECTIONLOSS.intValue() == rc
                    || KeeperException.Code.OPERATIONTIMEOUT.intValue() == rc
                    || KeeperException.Code.SESSIONMOVED.intValue() == rc
                    || KeeperException.Code.SESSIONEXPIRED.intValue() == rc;
        }

        /**
         * Check whether the given exception is recoverable by retry.
         *
         * @param exception given exception
         * @return true if given exception is recoverable.
         */
        public static boolean isRecoverableException(KeeperException exception) {
            return isRecoverableException(exception.code().intValue());
        }

        interface ZooCallable<T> {
            /**
             * Be compatible with ZooKeeper interface.
             *
             * @return value
             * @throws InterruptedException
             * @throws KeeperException
             */
            T call() throws InterruptedException, KeeperException;
        }

        /**
         * Execute a sync zookeeper operation with a given retry policy.
         *
         * @param client
         *          ZooKeeper client.
         * @param proc
         *          Synchronous zookeeper operation wrapped in a {@link Callable}.
         * @param retryPolicy
         *          Retry policy to execute the synchronous operation.
         * @param rateLimiter
         *          Rate limiter for zookeeper calls
         * @param statsLogger
         *          Stats Logger for zookeeper client.
         * @return result of the zookeeper operation
         * @throws KeeperException any non-recoverable exception or recoverable exception exhausted all retires.
         * @throws InterruptedException the operation is interrupted.
         */
        public static<T> T syncCallWithRetries(PulsarZooKeeperClient client,
                                               ZooWorker.ZooCallable<T> proc,
                                               RetryPolicy retryPolicy,
                                               RateLimiter rateLimiter,
                                               OpStatsLogger statsLogger)
                throws KeeperException, InterruptedException {
            T result = null;
            boolean isDone = false;
            int attempts = 0;
            long startTimeNanos = MathUtils.nowInNano();
            while (!isDone) {
                try {
                    if (null != client) {
                        client.waitForConnection();
                    }
                    log.debug("Execute {} at {} retry attempt.", proc, attempts);
                    if (null != rateLimiter) {
                        rateLimiter.acquire();
                    }
                    result = proc.call();
                    isDone = true;
                    statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos),
                            TimeUnit.MICROSECONDS);
                } catch (KeeperException e) {
                    ++attempts;
                    boolean rethrow = true;
                    long elapsedTime = MathUtils.elapsedMSec(startTimeNanos);
                    if (((null != client && isRecoverableException(e)) || null == client)
                            && retryPolicy.allowRetry(attempts, elapsedTime)) {
                        rethrow = false;
                    }
                    if (rethrow) {
                        statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos),
                                TimeUnit.MICROSECONDS);
                        log.debug("Stopped executing {} after {} attempts.", proc, attempts);
                        throw e;
                    }
                    TimeUnit.MILLISECONDS.sleep(retryPolicy.nextRetryWaitTime(attempts, elapsedTime));
                }
            }
            return result;
        }

    }

}


text:
package com.kii.thing_if.trigger;

import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.kii.thing_if.TypedID;
import com.kii.thing_if.command.Command;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Represents a trigger that is fired when status of thing changed or it became at the designated time.
 */
public class Trigger implements Parcelable {

    @NonNull private String triggerID;
    @NonNull private TypedID targetID;
    @NonNull private final Predicate predicate;
    @Nullable private final Command command;
    @Nullable private final ServerCode serverCode;
    private boolean disabled;
    @Nullable private String disabledReason;
    @Nullable private String title;
    @Nullable private String description;
    @Nullable private JSONObject metadata;

    Trigger(
            @NonNull String triggerID,
            @NonNull TypedID targetID,
            @NonNull Predicate predicate,
            @Nullable Command command,
            @Nullable ServerCode serverCode,
            boolean disabled,
            @Nullable String disabledReason,
            @Nullable String title,
            @Nullable String description,
            @Nullable JSONObject metadata) {
        this.triggerID = triggerID;
        this.targetID = targetID;
        this.predicate = predicate;
        this.command = command;
        this.disabled = disabled;
        this.disabledReason = disabledReason;
        this.title = title;
        this.description = description;
        this.metadata = metadata;
        this.serverCode = serverCode;
    }

    /**
     * Get ID of the Trigger.
     * @return ID of the Trigger
     */
    @NonNull
    public String getTriggerID() {
        return this.triggerID;
    }

    /**
     * Get Target ID of the Trigger.
     * When Trigger is created with ThingIFAPI#postNewTrigger() API families,
     * Target ID is determined by target bound to ThingIFAPI.
     * @return Target ID of Trigger.
     */
    @NonNull
    public TypedID getTargetID() {
        return this.targetID;
    }

    /**
     * Indicate whether the Trigger is disabled.
     * @return true if disabled, otherwise false.
     */
    public boolean disabled() {
        return this.disabled;
    }

    /**
     * Get Predicate of the Trigger.
     * @return Predicate of the Trigger
     */
    @NonNull
    public Predicate getPredicate() {
        return this.predicate;
    }

    /**
     * Get Command bounds to the Trigger.
     * @return Command  bounds to the Trigger.
     */
    @Nullable
    public Command getCommand() {
        return this.command;
    }

    /**
     * Get Server Code bounds to the Trigger.
     * @return Server Code bounds to the Trigger.
     */
    @Nullable
    public ServerCode getServerCode() {
        return this.serverCode;
    }

    /**
     * Get enum indicates whether the Command or Server Code is triggered.
     * @return TriggersWhat enum.
     */
    public TriggersWhat getTriggersWhat() {
        if (this.command != null) {
            return TriggersWhat.COMMAND;
        }
        return TriggersWhat.SERVER_CODE;
    }

    /**
     * Get the reason of the Trigger has been disabled.
     * If #disabled is false, It returns null.
     * @return Reason of the Trigger has been disabled.
     */
    @Nullable
    public String getDisabledReason() {
        return this.disabledReason;
    }

    /**
     * Get title.
     * @return title of this trigger.
     */
    @Nullable
    public String getTitle() {
        return this.title;
    }
    /**
     * Get description.
     * @return description of this trigger.
     */
    @Nullable
    public String getDescription() {
        return this.description;
    }
    /**
     * Get meta data
     * @return meta data of this trigger.
     */
    @Nullable
    public JSONObject getMetadata() {
        return this.metadata;
    }

    // Implementation of Parcelable
    protected Trigger(Parcel in) {
        this.triggerID = in.readString();
        this.targetID = in.readParcelable(TypedID.class.getClassLoader());
        this.predicate = in.readParcelable(Predicate.class.getClassLoader());
        this.command = in.readParcelable(Command.class.getClassLoader());
        this.serverCode = in.readParcelable(Command.class.getClassLoader());
        this.disabled = (in.readByte() != 0);
        this.disabledReason = in.readString();
        this.title = in.readString();
        this.description = in.readString();
        String metadata = in.readString();
        if (!TextUtils.isEmpty(metadata)) {
            try {
                this.metadata = new JSONObject(metadata);
            } catch (JSONException ignore) {
                // Won't happen
            }
        }
    }

    public static final Creator<Trigger> CREATOR = new Creator<Trigger>() {
        @Override
        public Trigger createFromParcel(Parcel in) {
            return new Trigger(in);
        }

        @Override
        public Trigger[] newArray(int size) {
            return new Trigger[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.triggerID);
        dest.writeParcelable(this.targetID, flags);
        dest.writeParcelable(this.predicate, flags);
        dest.writeParcelable(this.command, flags);
        dest.writeParcelable(this.serverCode, flags);
        dest.writeByte((byte) (this.disabled ? 1 : 0));
        dest.writeString(this.disabledReason);
        dest.writeString(this.title);
        dest.writeString(this.description);
        dest.writeString(this.metadata == null ? null : this.metadata.toString());
    }
}


text:
package org.usfirst.frc.team1458.robot;

import com.team1458.turtleshell2.implementations.input.TurtleXboxController;
import com.team1458.turtleshell2.implementations.sample.SampleRobotObjectHolder;
import com.team1458.turtleshell2.interfaces.AutoMode;
import com.team1458.turtleshell2.interfaces.TestMode;

public class Competition2016Robot extends SampleRobotObjectHolder {

	public Competition2016Robot() {
		TurtleXboxController xbox = new TurtleXboxController(TurtwigConstants.XBOXCONTROLLERPORT);
	/*
		TurtleFlightStick left = new TurtleFlightStick(
				TurtwigConstants.LJOYSTICKPORT);
		TurtleFlightStick right = new TurtleFlightStick(
				TurtwigConstants.RJOYSTICKPORT);*/

		Turtwig2016Chassis chassis = new Turtwig2016Chassis();
		chassis.setLeftJoystick(xbox.getAxis(TurtleXboxController.XboxAxis.LY));
		chassis.setRightJoystick(xbox.getAxis(TurtleXboxController.XboxAxis.RY));
		//chassis.setLeftJoystick(left.getAxis(FlightAxis.PITCH));
		//chassis.setRightJoystick(right.getAxis(FlightAxis.PITCH));

		components.add(chassis);

	}

	@Override
	public TestMode getTest() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AutoMode getAuto() {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
/** @file empty_database.h
 * @brief Empty database internals
 */
/* Copyright 2017 Olly Betts
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

#ifndef XAPIAN_INCLUDED_EMPTY_DATABASE_H
#define XAPIAN_INCLUDED_EMPTY_DATABASE_H

#include "xapian/backends/databaseinternal.h"

/// Empty database internals.
class EmptyDatabase : public Xapian::Database::Internal {
  public:
    EmptyDatabase() : Xapian::Database::Internal(TRANSACTION_NONE) {}

    size_type size() const;

    void close();

    PostList* open_post_list(const std::string& term) const;

    LeafPostList* open_leaf_post_list(const std::string& term,
				      bool need_read_pos) const;

    TermList* open_term_list(Xapian::docid did) const;

    TermList* open_term_list_direct(Xapian::docid did) const;

    TermList* open_allterms(const std::string& prefix) const;

    bool has_positions() const;

    PositionList* open_position_list(Xapian::docid did,
				     const std::string& term) const;
    Xapian::doccount get_doccount() const;

    Xapian::docid get_lastdocid() const;

    Xapian::totallength get_total_length() const;

    void get_freqs(const std::string& term,
		   Xapian::doccount* tf_ptr,
		   Xapian::termcount* cf_ptr) const;

    Xapian::doccount get_value_freq(Xapian::valueno slot) const;

    std::string get_value_lower_bound(Xapian::valueno slot) const;

    std::string get_value_upper_bound(Xapian::valueno slot) const;

    Xapian::termcount get_doclength_lower_bound() const;

    Xapian::termcount get_doclength_upper_bound() const;

    Xapian::termcount get_wdf_upper_bound(const std::string& term) const;

    ValueList* open_value_list(Xapian::valueno slot) const;

    Xapian::termcount get_doclength(Xapian::docid did) const;

    Xapian::termcount get_unique_terms(Xapian::docid did) const;

    Xapian::Document::Internal* open_document(Xapian::docid did,
					      bool lazy) const;

    bool term_exists(const std::string& term) const;

    TermList* open_spelling_termlist(const std::string& word) const;

    TermList* open_spelling_wordlist() const;

    Xapian::doccount get_spelling_frequency(const std::string& word) const;

    TermList* open_synonym_termlist(const std::string& term) const;

    TermList* open_synonym_keylist(const std::string& prefix) const;

    std::string get_metadata(const std::string& key) const;

    TermList* open_metadata_keylist(const std::string& prefix) const;

    void write_changesets_to_fd(int fd,
				const std::string& start_revision,
				bool need_whole_db,
				Xapian::ReplicationInfo* info);

    void invalidate_doc_object(Xapian::Document::Internal* obj) const;

    Xapian::rev get_revision() const;

    int get_backend_info(std::string* path) const;

    void commit();

    void cancel();

    void begin_transaction(bool flushed);

    void end_transaction_(bool do_commit);

    Xapian::DocumentInfo add_document(const Xapian::Document& doc);

    void delete_document(Xapian::docid did);

    void delete_document(const std::string& term);

    Xapian::DocumentInfo replace_document(Xapian::docid did,
					  const Xapian::Document& doc);

    Xapian::DocumentInfo replace_document(const std::string& term,
					  const Xapian::Document& doc);

    void add_spelling(const std::string& word, Xapian::termcount freqinc) const;

    Xapian::termcount remove_spelling(const std::string& word,
				      Xapian::termcount freqdec) const;

    void add_synonym(const std::string& term, const std::string& synonym) const;

    void remove_synonym(const std::string& term,
			const std::string& synonym) const;

    void clear_synonyms(const std::string& term) const;

    void set_metadata(const std::string& key, const std::string& value);

    std::string get_description() const;
};

#endif // XAPIAN_INCLUDED_EMPTY_DATABASE_H


text:
package org.springframework.social.connect.web;

import org.springframework.social.connect.Connection;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * Adapter that bridges between a {@link ProviderSignInController} and a application-specific user sign-in service.
 * Invoked at the end of a provider sign-in attempt to sign-in the local user account associated with the provider user account.
 * @author Craig Walls
 */
public interface SignInAdapter {

	/**
	 * Complete a provider sign-in attempt by signing in the local user account with the specified id.
	 * @param userId the local user id
	 * @param connection the connection
	 * @param request a reference to the current web request; is a "native" web request instance providing access to the native
	 * request and response objects, such as a HttpServletRequest and HttpServletResponse, if needed
	 * @return the URL that ProviderSignInController should redirect to after sign in. May be null, indicating that ProviderSignInController
	 * should redirect to its postSignInUrl.
	 */
	String signIn(String userId, Connection<?> connection, NativeWebRequest request);

}


text:
<meta charset="utf-8">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
        <link rel="shortcut icon" href="assets/ico/favicon.ico">

        <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="assets/plugins/fontawesome/css/font-awesome.min.css" rel="stylesheet">
        <link href="assets/plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet">
        <link href="assets/plugins/jquery-ui-1.11.4.custom/jquery-ui.min.css" rel="stylesheet" type="text/css">
        <link href="assets/plugins/owlcarousel2/assets/owl.carousel.min.css" rel="stylesheet">
        <link href="assets/plugins/owlcarousel2/assets/owl.theme.default.min.css" rel="stylesheet">
        <link href="assets/plugins/prettyphoto/css/prettyPhoto.css" rel="stylesheet">
        <link href="assets/plugins/animate/animate.min.css" rel="stylesheet">
        <link href="assets/plugins/countdown/jquery.countdown.css" rel="stylesheet">

        <link href="assets/css/theme.css" rel="stylesheet">
        <link href="assets/css/custom.css" rel="stylesheet">

Standart Event Name Here

15 October at 20:00 - 22:00 on Manhattan / New York

                                                                 Register NowWatch video

                                     What You Want Find Best Event For You

                                <form id="registration-form" name="registration-form" class="event-form" action="#" method="post">

                                                <select class="selectpicker input-price" data-live-search="true" data-width="100%"
                                                        data-toggle="tooltip" title="Select Location">
                                                    <option>Select Location</option>
                                                    <option>Canada</option>
                                                    <option>Australia</option>
                                                    <option>Dubai</option>
                                                </select>

                                                <select class="selectpicker input-price" data-live-search="true" data-width="100%"
                                                        data-toggle="tooltip" title="Select Type">
                                                    <option>Select Type</option>
                                                    <option>Canada</option>
                                                    <option>Australia</option>
                                                    <option>Dubai</option>
                                                </select>

                                                <input type="text" class="form-control datetimepicker" name="datetimepicker" placeholder ="Select Date" />

                                                <button class="btn btn-theme submit-button" type="submit"> Find Event </button>

                                </form>

7/24 Event avaliable

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed vel velit

Details

Great Locations

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed vel velit

Details

More Then 200 Speakers

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed vel velit

Details

Lets Party After Event

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed vel velit

Details

All

Festival

Playground

Conference

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                                            25
                                            Jan

Standart Event Name Here

 15 October  Manhattan / New York

Tickets from $49,99

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Tickets & details

                             See all events

Vivamus eget nibh. Etiam cursus leo vel metus. Nulla facilisi. Aenean nec eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices.

isa MERCAN

Gurme, Gurmetistanv

Vivamus eget nibh. Etiam cursus leo vel metus. Nulla facilisi. Aenean nec eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices.

isa MERCAN

Gurme, Gurmetistanv

Vivamus eget nibh. Etiam cursus leo vel metus. Nulla facilisi. Aenean nec eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices.

isa MERCAN

Gurme, Gurmetistanv

                            HOTELS  / dont forget book your room

 Details

Standard Hotel Name Here

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Book

 Details

Standard Hotel Name Here

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Book

 Details

Standard Hotel Name Here

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Book

 Details

Standard Hotel Name Here

Fusce pellentesque velvitae tincidunt egestas. Pellentesque habitant morbi.

Book

                              See all Hotels

Create Your Own New Event

Bring people together, or turn your passion into a business. Eventbrite gives you everything you need to host your best event yet.

                                SUBMIT EVENT

                <button type="button" class="close close-btn" data-dismiss="modal" aria-label="Close">×</button>

                                Login

                        <form method="post" action="#" class="registration-form alt" name="registration-form-alt" id="registration-form-alt">

                                        <input type="text" placeholder="User Name" title="" data-toggle="tooltip" class="form-control input-name" data-original-title="Name is required">

                                        <input type="text"  placeholder="Password"  title="" data-toggle="tooltip" class="form-control input-password" data-original-title="Password">

                                        <button type="submit" class="btn btn-theme btn-block submit-button" data-animation-delay="100" data-animation="flipInY"> Log in </button>

                        </form>

                             Lost your password?

                                Register

                        <form method="post" action="#" class="registration-form alt" name="registration-form-alt" id="registration-form-alt">

                                        <input type="text" placeholder="User Name" title="" data-toggle="tooltip" class="form-control input-name" data-original-title="Name is required">

                                        <input type="text"  placeholder="E-mail"  title="" data-toggle="tooltip" class="form-control input-password" data-original-title="Password">

                                        <button type="submit" class="btn btn-theme btn-block submit-button" data-animation-delay="100" data-animation="flipInY"> Register Now </button>

                        </form>


text:
package net.amigocraft.mglib.event.round;

import net.amigocraft.mglib.api.LobbySign;
import net.amigocraft.mglib.api.Round;
import net.amigocraft.mglib.event.player.PlayerJoinMinigameRoundEvent;
import net.amigocraft.mglib.misc.JoinResult;

/**
 * Called when a player clicks a lobby sign in order to join a minigame round.
 *
 *
Note: If you
 * wish to cancel this event, you must instead listen to the {@link PlayerJoinMinigameRoundEvent} and cancel that.

 *
 * @since 0.3.0
 */
public class LobbyClickEvent extends MGRoundEvent {

	private String player;
	private LobbySign lobbySign;
	private JoinResult result;

	/**
	 * Creates a new instance of this event.
	 *
	 * @param player    the name of the player who clicked a lobby sign
	 * @param round     the round which the lobby sign is linked to
	 * @param lobbySign the {@link LobbySign lobby sign} which has been clicked
	 * @param result    the result of the player being added to the round
	 * @since 0.3.0
	 */
	public LobbyClickEvent(String player, Round round, LobbySign lobbySign, JoinResult result) {
		super(round);
		this.player = player;
		this.lobbySign = lobbySign;
		this.result = result;
	}

	/**
	 * Retrieves the name of the player involved in this event.
	 *
	 * @return the name of the player involved in this event
	 * @since 0.3.0
	 */
	public String getPlayer() {
		return player;
	}

	/**
	 * Retrieves the {@link LobbySign lobby sign} object involved in this event.
	 *
	 * @return the {@link LobbySign lobby sign} object involved in this event
	 * @since 0.3.0
	 */
	public LobbySign getLobbySign() {
		return lobbySign;
	}

	/**
	 * Retrieves the result of the event.
	 *
	 * @return the result of this event
	 * @since 0.3.0
	 */
	public JoinResult getResult() {
		return result;
	}

}