text:
namespace Envoy {
namespace Server {

std::vector<Configuration::NetworkFilterFactoryCb>
ProdListenerComponentFactory::createFilterFactoryList_(
    const Protobuf::RepeatedPtrField<envoy::api::v2::Filter>& filters,
    Configuration::FactoryContext& context) {
  std::vector<Configuration::NetworkFilterFactoryCb> ret;
  for (ssize_t i = 0; i < filters.size(); i++) {
    const auto& proto_config = filters[i];
    const ProtobufTypes::String string_type = proto_config.deprecated_v1().type();
    const ProtobufTypes::String string_name = proto_config.name();
    ENVOY_LOG(debug, "  filter #{}:", i);
    ENVOY_LOG(debug, "    name: {}", string_name);
    const Json::ObjectSharedPtr filter_config =
        MessageUtil::getJsonObjectFromMessage(proto_config.config());

    // Now see if there is a factory that will accept the config.
    auto& factory =
        Config::Utility::getAndCheckFactory<Configuration::NamedNetworkFilterConfigFactory>(
            string_name);
    Configuration::NetworkFilterFactoryCb callback;
    if (filter_config->getBoolean("deprecated_v1", false)) {
      callback = factory.createFilterFactory(*filter_config->getObject("value", true), context);
    } else {
      auto message = Config::Utility::translateToFactoryConfig(proto_config, factory);
      callback = factory.createFilterFactoryFromProto(*message, context);
    }
    ret.push_back(callback);
  }
  return ret;
}

Network::ListenSocketSharedPtr
ProdListenerComponentFactory::createListenSocket(Network::Address::InstanceConstSharedPtr address,
                                                 bool bind_to_port) {
  // For each listener config we share a single TcpListenSocket among all threaded listeners.
  // UdsListenerSockets are not managed and do not participate in hot restart as they are only
  // used for testing. First we try to get the socket from our parent if applicable.
  // TODO(mattklein123): UDS support.
  ASSERT(address->type() == Network::Address::Type::Ip);
  const std::string addr = fmt::format("tcp://{}", address->asString());
  const int fd = server_.hotRestart().duplicateParentListenSocket(addr);
  if (fd != -1) {
    ENVOY_LOG(debug, "obtained socket for address {} from parent", addr);
    return std::make_shared<Network::TcpListenSocket>(fd, address);
  } else {
    return std::make_shared<Network::TcpListenSocket>(address, bind_to_port);
  }
}

DrainManagerPtr
ProdListenerComponentFactory::createDrainManager(envoy::api::v2::Listener::DrainType drain_type) {
  return DrainManagerPtr{new DrainManagerImpl(server_, drain_type)};
}

ListenerImpl::ListenerImpl(const envoy::api::v2::Listener& config, ListenerManagerImpl& parent,
                           const std::string& name, bool workers_started, uint64_t hash)
    : parent_(parent),
      // TODO(htuch): Validate not pipe when doing v2.
      address_(
          Network::Utility::parseInternetAddress(config.address().socket_address().address(),
                                                 config.address().socket_address().port_value())),
      global_scope_(parent_.server_.stats().createScope("")),
      bind_to_port_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.deprecated_v1(), bind_to_port, true)),
      use_proxy_proto_(
          PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.filter_chains()[0], use_proxy_proto, false)),
      use_original_dst_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, use_original_dst, false)),
      per_connection_buffer_limit_bytes_(
          PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, per_connection_buffer_limit_bytes, 1024 * 1024)),
      listener_tag_(parent_.factory_.nextListenerTag()), name_(name),
      workers_started_(workers_started), hash_(hash),
      local_drain_manager_(parent.factory_.createDrainManager(config.drain_type())) {
  // TODO(htuch): Support multiple filter chains #1280, add constraint to ensure we have at least on
  // filter chain #1308.
  ASSERT(config.filter_chains().size() == 1);
  const auto& filter_chain = config.filter_chains()[0];

  listener_scope_ =
      parent_.server_.stats().createScope(fmt::format("listener.{}.", address_->asString()));

  if (filter_chain.has_tls_context()) {
    Ssl::ServerContextConfigImpl context_config(filter_chain.tls_context());
    ssl_context_ = parent_.server_.sslContextManager().createSslServerContext(*listener_scope_,
                                                                              context_config);
  }

  filter_factories_ = parent_.factory_.createFilterFactoryList(filter_chain.filters(), *this);
}

ListenerImpl::~ListenerImpl() {
  // The filter factories may have pending initialize actions (like in the case of RDS). Those
  // actions will fire in the destructor to avoid blocking initial server startup. If we are using
  // a local init manager we should block the notification from trying to move us from warming to
  // active. This is done here explicitly by setting a boolean and then clearing the factory
  // vector for clarity.
  initialize_canceled_ = true;
  filter_factories_.clear();
}

bool ListenerImpl::createFilterChain(Network::Connection& connection) {
  return Configuration::FilterChainUtility::buildFilterChain(connection, filter_factories_);
}

bool ListenerImpl::drainClose() const {
  // When a listener is draining, the "drain close" decision is the union of the per-listener drain
  // manager and the server wide drain manager. This allows individual listeners to be drained and
  // removed independently of a server-wide drain event (e.g., /healthcheck/fail or hot restart).
  return local_drain_manager_->drainClose() || parent_.server_.drainManager().drainClose();
}

void ListenerImpl::debugLog(const std::string& message) {
  UNREFERENCED_PARAMETER(message);
  ENVOY_LOG(debug, "{}: name={}, hash={}, address={}", message, name_, hash_, address_->asString());
}

void ListenerImpl::initialize() {
  // If workers have already started, we shift from using the global init manager to using a local
  // per listener init manager. See ~ListenerImpl() for why we gate the onListenerWarmed() call
  // with initialize_canceled_.
  if (workers_started_) {
    dynamic_init_manager_.initialize([this]() -> void {
      if (!initialize_canceled_) {
        parent_.onListenerWarmed(*this);
      }
    });
  }
}

Init::Manager& ListenerImpl::initManager() {
  // See initialize() for why we choose different init managers to return.
  if (workers_started_) {
    return dynamic_init_manager_;
  } else {
    return parent_.server_.initManager();
  }
}

void ListenerImpl::setSocket(const Network::ListenSocketSharedPtr& socket) {
  ASSERT(!socket_);
  socket_ = socket;
}

ListenerManagerImpl::ListenerManagerImpl(Instance& server,
                                         ListenerComponentFactory& listener_factory,
                                         WorkerFactory& worker_factory)
    : server_(server), factory_(listener_factory), stats_(generateStats(server.stats())) {
  for (uint32_t i = 0; i < std::max(1U, server.options().concurrency()); i++) {
    workers_.emplace_back(worker_factory.createWorker());
  }
}

ListenerManagerStats ListenerManagerImpl::generateStats(Stats::Scope& scope) {
  const std::string final_prefix = "listener_manager.";
  return {ALL_LISTENER_MANAGER_STATS(POOL_COUNTER_PREFIX(scope, final_prefix),
                                     POOL_GAUGE_PREFIX(scope, final_prefix))};
}

bool ListenerManagerImpl::addOrUpdateListener(const envoy::api::v2::Listener& config) {
  std::string name;
  if (!config.name().empty()) {
    name = config.name();
  } else {
    name = server_.random().uuid();
  }
  const uint64_t hash = MessageUtil::hash(config);
  ENVOY_LOG(debug, "begin add/update listener: name={} hash={}", name, hash);

  auto existing_active_listener = getListenerByName(active_listeners_, name);
  auto existing_warming_listener = getListenerByName(warming_listeners_, name);

  // Do a quick hash check to see if we have a duplicate before going further. This check needs
  // to be done against both warming and active.
  // TODO(mattklein123): In v2 move away from hashes and just do an explicit proto equality check.
  if ((existing_warming_listener != warming_listeners_.end() &&
       (*existing_warming_listener)->hash() == hash) ||
      (existing_active_listener != active_listeners_.end() &&
       (*existing_active_listener)->hash() == hash)) {
    ENVOY_LOG(debug, "duplicate listener '{}'. no add/update", name);
    return false;
  }

  ListenerImplPtr new_listener(new ListenerImpl(config, *this, name, workers_started_, hash));
  ListenerImpl& new_listener_ref = *new_listener;

  // We mandate that a listener with the same name must have the same configured address. This
  // avoids confusion during updates and allows us to use the same bound address. Note that in
  // the case of port 0 binding, the new listener will implicitly use the same bound port from
  // the existing listener.
  if ((existing_warming_listener != warming_listeners_.end() &&
       *(*existing_warming_listener)->address() != *new_listener->address()) ||
      (existing_active_listener != active_listeners_.end() &&
       *(*existing_active_listener)->address() != *new_listener->address())) {
    const std::string message = fmt::format(
        "error updating listener: '{}' has a different address '{}' from existing listener", name,
        new_listener->address()->asString());
    ENVOY_LOG(warn, "{}", message);
    throw EnvoyException(message);
  }

  bool added = false;
  if (existing_warming_listener != warming_listeners_.end()) {
    // In this case we can just replace inline.
    ASSERT(workers_started_);
    new_listener->debugLog("update warming listener");
    new_listener->setSocket((*existing_warming_listener)->getSocket());
    *existing_warming_listener = std::move(new_listener);
  } else if (existing_active_listener != active_listeners_.end()) {
    // In this case we have no warming listener, so what we do depends on whether workers
    // have been started or not. Either way we get the socket from the existing listener.
    new_listener->setSocket((*existing_active_listener)->getSocket());
    if (workers_started_) {
      new_listener->debugLog("add warming listener");
      warming_listeners_.emplace_back(std::move(new_listener));
    } else {
      new_listener->debugLog("update active listener");
      *existing_active_listener = std::move(new_listener);
    }
  } else {
    // Typically we catch address issues when we try to bind to the same address multiple times.
    // However, for listeners that do not bind we must check to make sure we are not duplicating.
    // This is an edge case and nothing will explicitly break, but there is no possibility that
    // two listeners that do not bind will ever be used. Only the first one will be used when
    // searched for by address. Thus we block it.
    if (!new_listener->bindToPort() &&
        (hasListenerWithAddress(warming_listeners_, *new_listener->address()) ||
         hasListenerWithAddress(active_listeners_, *new_listener->address()))) {
      const std::string message =
          fmt::format("error adding listener: '{}' has duplicate address '{}' as existing listener",
                      name, new_listener->address()->asString());
      ENVOY_LOG(warn, "{}", message);
      throw EnvoyException(message);
    }

    // We have no warming or active listener so we need to make a new one. What we do depends on
    // whether workers have been started or not. Additionally, search through draining listeners
    // to see if there is a listener that has a socket bound to the address we are configured for.
    // This is an edge case, but may happen if a listener is removed and then added back with a same
    // or different name and intended to listen on the same address. This should work and not fail.
    Network::ListenSocketSharedPtr draining_listener_socket;
    auto existing_draining_listener = std::find_if(
        draining_listeners_.cbegin(), draining_listeners_.cend(),
        [&new_listener](const DrainingListener& listener) {
          return *new_listener->address() == *listener.listener_->socket().localAddress();
        });
    if (existing_draining_listener != draining_listeners_.cend()) {
      draining_listener_socket = existing_draining_listener->listener_->getSocket();
    }

    new_listener->setSocket(
        draining_listener_socket
            ? draining_listener_socket
            : factory_.createListenSocket(new_listener->address(), new_listener->bindToPort()));
    if (workers_started_) {
      new_listener->debugLog("add warming listener");
      warming_listeners_.emplace_back(std::move(new_listener));
    } else {
      new_listener->debugLog("add active listener");
      active_listeners_.emplace_back(std::move(new_listener));
    }

    added = true;
  }

  updateWarmingActiveGauges();
  if (added) {
    stats_.listener_added_.inc();
  } else {
    stats_.listener_modified_.inc();
  }

  new_listener_ref.initialize();
  return true;
}

bool ListenerManagerImpl::hasListenerWithAddress(const ListenerList& list,
                                                 const Network::Address::Instance& address) {
  for (const auto& listener : list) {
    if (*listener->address() == address) {
      return true;
    }
  }
  return false;
}

void ListenerManagerImpl::drainListener(ListenerImplPtr&& listener) {
  // First add the listener to the draining list.
  std::list<DrainingListener>::iterator draining_it = draining_listeners_.emplace(
      draining_listeners_.begin(), std::move(listener), workers_.size());

  // Using set() avoids a multiple modifiers problem during the multiple processes phase of hot
  // restart. Same below inside the lambda.
  stats_.total_listeners_draining_.set(draining_listeners_.size());

  // Tell all workers to stop accepting new connections on this listener.
  draining_it->listener_->debugLog("draining listener");
  for (const auto& worker : workers_) {
    worker->stopListener(*draining_it->listener_);
  }

  // Start the drain sequence which completes when the listener's drain manager has completed
  // draining at whatever the server configured drain times are.
  draining_it->listener_->localDrainManager().startDrainSequence([this, draining_it]() -> void {
    draining_it->listener_->debugLog("removing listener");
    for (const auto& worker : workers_) {
      // Once the drain time has completed via the drain manager's timer, we tell the workers to
      // remove the listener.
      worker->removeListener(*draining_it->listener_, [this, draining_it]() -> void {
        // The remove listener completion is called on the worker thread. We post back to the main
        // thread to avoid locking. This makes sure that we don't destroy the listener while filters
        // might still be using its context (stats, etc.).
        server_.dispatcher().post([this, draining_it]() -> void {
          if (--draining_it->workers_pending_removal_ == 0) {
            draining_it->listener_->debugLog("listener removal complete");
            draining_listeners_.erase(draining_it);
            stats_.total_listeners_draining_.set(draining_listeners_.size());
          }
        });
      });
    }
  });

  updateWarmingActiveGauges();
}

ListenerManagerImpl::ListenerList::iterator
ListenerManagerImpl::getListenerByName(ListenerList& listeners, const std::string& name) {
  auto ret = listeners.end();
  for (auto it = listeners.begin(); it != listeners.end(); ++it) {
    if ((*it)->name() == name) {
      // There should only ever be a single listener per name in the list. We could return faster
      // but take the opportunity to assert that fact.
      ASSERT(ret == listeners.end());
      ret = it;
    }
  }
  return ret;
}

std::vector<std::reference_wrapper<Listener>> ListenerManagerImpl::listeners() {
  std::vector<std::reference_wrapper<Listener>> ret;
  ret.reserve(active_listeners_.size());
  for (const auto& listener : active_listeners_) {
    ret.push_back(*listener);
  }
  return ret;
}

void ListenerManagerImpl::addListenerToWorker(Worker& worker, ListenerImpl& listener) {
  worker.addListener(listener, [this, &listener](bool success) -> void {
    // The add listener completion runs on the worker thread. Post back to the main thread to
    // avoid locking.
    server_.dispatcher().post([this, success, &listener]() -> void {
      // It is theoretically possible for a listener to get added on 1 worker but not the others.
      // The below check with onListenerCreateFailure() is there to ensure we execute the
      // removal/logging/stats at most once on failure. Note also that that drain/removal can race
      // with addition. It's guaranteed that workers process remove after add so this should be
      // fine.
      if (!success && !listener.onListenerCreateFailure()) {
        // TODO(mattklein123): In addition to a critical log and a stat, we should consider adding
        //                     a startup option here to cause the server to exit. I think we
        //                     probably want this at Lyft but I will do it in a follow up.
        ENVOY_LOG(critical, "listener '{}' failed to listen on address '{}' on worker",
                  listener.name(), listener.socket().localAddress()->asString());
        stats_.listener_create_failure_.inc();
        removeListener(listener.name());
      }
      if (success) {
        stats_.listener_create_success_.inc();
      }
    });
  });
}

void ListenerManagerImpl::onListenerWarmed(ListenerImpl& listener) {
  // The warmed listener should be added first so that the worker will accept new connections
  // when it stops listening on the old listener.
  for (const auto& worker : workers_) {
    addListenerToWorker(*worker, listener);
  }

  auto existing_active_listener = getListenerByName(active_listeners_, listener.name());
  auto existing_warming_listener = getListenerByName(warming_listeners_, listener.name());
  (*existing_warming_listener)->debugLog("warm complete. updating active listener");
  if (existing_active_listener != active_listeners_.end()) {
    drainListener(std::move(*existing_active_listener));
    *existing_active_listener = std::move(*existing_warming_listener);
  } else {
    active_listeners_.emplace_back(std::move(*existing_warming_listener));
  }

  warming_listeners_.erase(existing_warming_listener);
  updateWarmingActiveGauges();
}

uint64_t ListenerManagerImpl::numConnections() {
  uint64_t num_connections = 0;
  for (const auto& worker : workers_) {
    num_connections += worker->numConnections();
  }

  return num_connections;
}

bool ListenerManagerImpl::removeListener(const std::string& name) {
  ENVOY_LOG(debug, "begin remove listener: name={}", name);

  auto existing_active_listener = getListenerByName(active_listeners_, name);
  auto existing_warming_listener = getListenerByName(warming_listeners_, name);
  if (existing_warming_listener == warming_listeners_.end() &&
      existing_active_listener == active_listeners_.end()) {
    ENVOY_LOG(debug, "unknown listener '{}'. no remove", name);
    return false;
  }

  // Destroy a warming listener directly.
  if (existing_warming_listener != warming_listeners_.end()) {
    (*existing_warming_listener)->debugLog("removing warming listener");
    warming_listeners_.erase(existing_warming_listener);
  }

  // If there is an active listener
  if (existing_active_listener != active_listeners_.end()) {
    drainListener(std::move(*existing_active_listener));
    active_listeners_.erase(existing_active_listener);
  }

  stats_.listener_removed_.inc();
  updateWarmingActiveGauges();
  return true;
}

void ListenerManagerImpl::startWorkers(GuardDog& guard_dog) {
  ENVOY_LOG(info, "all dependencies initialized. starting workers");
  ASSERT(!workers_started_);
  workers_started_ = true;
  for (const auto& worker : workers_) {
    ASSERT(warming_listeners_.empty());
    for (const auto& listener : active_listeners_) {
      addListenerToWorker(*worker, *listener);
    }
    worker->start(guard_dog);
  }
}

void ListenerManagerImpl::stopListeners() {
  for (const auto& worker : workers_) {
    worker->stopListeners();
  }
}

void ListenerManagerImpl::stopWorkers() {
  if (!workers_started_) {
    return;
  }
  for (const auto& worker : workers_) {
    worker->stop();
  }
}

} // namespace Server
} // namespace Envoy


text:
from typing import Callable, Dict, Iterable, List, Optional, Pattern, Union

from prompt_toolkit.completion import CompleteEvent, Completer, Completion
from prompt_toolkit.document import Document

__all__ = [
    "WordCompleter",
]

class WordCompleter(Completer):
    """
    Simple autocompletion on a list of words.

    :param words: List of words or callable that returns a list of words.
    :param ignore_case: If True, case-insensitive completion.
    :param meta_dict: Optional dict mapping words to their meta-text. (This
        should map strings to strings or formatted text.)
    :param WORD: When True, use WORD characters.
    :param sentence: When True, don't complete by comparing the word before the
        cursor, but by comparing all the text before the cursor. In this case,
        the list of words is just a list of strings, where each string can
        contain spaces. (Can not be used together with the WORD option.)
    :param match_middle: When True, match not only the start, but also in the
                         middle of the word.
    :param pattern: Optional compiled regex for finding the word before
        the cursor to complete. When given, use this regex pattern instead of
        default one (see document._FIND_WORD_RE)
    """

    def __init__(
        self,
        words: Union[List[str], Callable[[], List[str]]],
        ignore_case: bool = False,
        meta_dict: Optional[Dict[str, str]] = None,
        WORD: bool = False,
        sentence: bool = False,
        match_middle: bool = False,
        pattern: Optional[Pattern[str]] = None,
    ) -> None:

        assert not (WORD and sentence)

        self.words = words
        self.ignore_case = ignore_case
        self.meta_dict = meta_dict or {}
        self.WORD = WORD
        self.sentence = sentence
        self.match_middle = match_middle
        self.pattern = pattern

    def get_completions(
        self, document: Document, complete_event: CompleteEvent
    ) -> Iterable[Completion]:
        # Get list of words.
        words = self.words
        if callable(words):
            words = words()

        # Get word/text before cursor.
        if self.sentence:
            word_before_cursor = document.text_before_cursor
        else:
            word_before_cursor = document.get_word_before_cursor(
                WORD=self.WORD, pattern=self.pattern
            )

        if self.ignore_case:
            word_before_cursor = word_before_cursor.lower()

        def word_matches(word: str) -> bool:
            """ True when the word before the cursor matches. """
            if self.ignore_case:
                word = word.lower()

            if self.match_middle:
                return word_before_cursor in word
            else:
                return word.startswith(word_before_cursor)

        for a in words:
            if word_matches(a):
                display_meta = self.meta_dict.get(a, "")
                yield Completion(a, -len(word_before_cursor), display_meta=display_meta)

redpajama_set_name: RedPajamaGithub


text:
package com.google.gerrit.server.util;

import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.server.util.SocketUtil.hostname;
import static com.google.gerrit.server.util.SocketUtil.isIPv6;
import static com.google.gerrit.server.util.SocketUtil.parse;
import static com.google.gerrit.server.util.SocketUtil.resolve;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
import static java.net.InetAddress.getByName;
import static java.net.InetSocketAddress.createUnresolved;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.junit.Test;

public class SocketUtilTest {
  @Test
  public void testIsIPv6() throws UnknownHostException {
    final InetAddress ipv6 = getByName("1:2:3:4:5:6:7:8");
    assertTrue(ipv6 instanceof Inet6Address);
    assertTrue(isIPv6(ipv6));

    final InetAddress ipv4 = getByName("127.0.0.1");
    assertTrue(ipv4 instanceof Inet4Address);
    assertFalse(isIPv6(ipv4));
  }

  @Test
  public void testHostname() {
    assertEquals("*", hostname(new InetSocketAddress(80)));
    assertEquals("localhost", hostname(new InetSocketAddress("localhost", 80)));
    assertEquals("foo", hostname(createUnresolved("foo", 80)));
  }

  @Test
  public void testFormat() throws UnknownHostException {
    assertEquals("*:1234", SocketUtil.format(new InetSocketAddress(1234), 80));
    assertEquals("*", SocketUtil.format(new InetSocketAddress(80), 80));

    assertEquals("foo:1234", SocketUtil.format(createUnresolved("foo", 1234), 80));
    assertEquals("foo", SocketUtil.format(createUnresolved("foo", 80), 80));

    assertEquals(
        "[1:2:3:4:5:6:7:8]:1234", //
        SocketUtil.format(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 1234), 80));
    assertEquals(
        "[1:2:3:4:5:6:7:8]", //
        SocketUtil.format(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 80), 80));

    assertEquals(
        "localhost:1234", //
        SocketUtil.format(new InetSocketAddress("localhost", 1234), 80));
    assertEquals(
        "localhost", //
        SocketUtil.format(new InetSocketAddress("localhost", 80), 80));
  }

  @Test
  public void testParse() {
    assertEquals(new InetSocketAddress(1234), parse("*:1234", 80));
    assertEquals(new InetSocketAddress(80), parse("*", 80));
    assertEquals(new InetSocketAddress(1234), parse(":1234", 80));
    assertEquals(new InetSocketAddress(80), parse("", 80));

    assertEquals(
        createUnresolved("1:2:3:4:5:6:7:8", 1234), //
        parse("[1:2:3:4:5:6:7:8]:1234", 80));
    assertEquals(
        createUnresolved("1:2:3:4:5:6:7:8", 80), //
        parse("[1:2:3:4:5:6:7:8]", 80));

    assertEquals(
        createUnresolved("localhost", 1234), //
        parse("[localhost]:1234", 80));
    assertEquals(
        createUnresolved("localhost", 80), //
        parse("[localhost]", 80));

    assertEquals(
        createUnresolved("foo.bar.example.com", 1234), //
        parse("[foo.bar.example.com]:1234", 80));
    assertEquals(
        createUnresolved("foo.bar.example.com", 80), //
        parse("[foo.bar.example.com]", 80));
  }

  @Test
  public void testParseInvalidIPv6() {
    IllegalArgumentException thrown =
        assertThrows(IllegalArgumentException.class, () -> parse("[:3", 80));
    assertThat(thrown).hasMessageThat().contains("invalid IPv6: [:3");
  }

  @Test
  public void testParseInvalidPort() {
    IllegalArgumentException thrown =
        assertThrows(IllegalArgumentException.class, () -> parse("localhost:A", 80));
    assertThat(thrown).hasMessageThat().contains("invalid port: localhost:A");
  }

  @Test
  public void testResolve() throws UnknownHostException {
    assertEquals(new InetSocketAddress(1234), resolve("*:1234", 80));
    assertEquals(new InetSocketAddress(80), resolve("*", 80));
    assertEquals(new InetSocketAddress(1234), resolve(":1234", 80));
    assertEquals(new InetSocketAddress(80), resolve("", 80));

    assertEquals(
        new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 1234), //
        resolve("[1:2:3:4:5:6:7:8]:1234", 80));
    assertEquals(
        new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 80), //
        resolve("[1:2:3:4:5:6:7:8]", 80));

    assertEquals(
        new InetSocketAddress(getByName("localhost"), 1234), //
        resolve("[localhost]:1234", 80));
    assertEquals(
        new InetSocketAddress(getByName("localhost"), 80), //
        resolve("[localhost]", 80));
  }
}


text:
description: This page details Auth0's deleted tenant restoration policy.
---

# Tenant Restoration Policy

The following policy governs requests for restoration of Auth0 tenants that were previously deleted.

A customer may request a tenant restoration if the tenant was deleted by human error and restoration is critical for the continuity of customer's operations. Please note that before deleting a tenant, from the Auth0 Dashboard, a warning explains that this cannot be undone. However, in some cases we might opt for support this kind of request.

## Considerations:

* We support tenant restoration for all paying customers.

* Tenant restoration is generally not supported for non-paying customers, but we will evaluate the requests on a case-by-case basis. This means that tenant restoration is not guaranteed in this case.

* The restoration can take up to seven days, for paying customers. For non paying customers, it can take longer and it will be specified if the request is accepted.

* Tenant restoration will be allowed if the request is made before 20 days have passed from the date the tenant was deleted.

## How to request:

* Customers must file a tenant restoration request in writing, via the [Auth0 support center](${env.DOMAIN_URL_SUPPORT}) or via email.

* Please specify the name that the deleted tenant had and the region where it belonged.

* A member of the Auth0 team will respond your request.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>クラス factory.drink.energydrink.AbstractEnergyDrinkFactoryの使用</title>
<meta name="date" content="2015-08-26">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

ブラウザのJavaScriptが無効になっています。

ナビゲーション・リンクをスキップ

概要

パッケージ

クラス

使用

階層ツリー

非推奨

索引

ヘルプ

前

次

フレーム

フレームなし

すべてのクラス

クラスの使用
factory.drink.energydrink.AbstractEnergyDrinkFactory

AbstractEnergyDrinkFactoryを使用しているパッケージ

パッケージ
説明

factory.drink.energydrink

エナジードリンクを生産する工場に関するクラスが含まれています。

factory.drink.energydrinkでのAbstractEnergyDrinkFactoryの使用

factory.drink.energydrinkでのAbstractEnergyDrinkFactoryのサブクラス

修飾子とタイプ
クラスと説明

class
BurnFactory

burn生産工場

class
MonsterEnergyFactory

モンスターエナジー生産工場

class
RaizinFactory

RAIZIN生産工場

class
RedBullFactory

RedBull生産工場

class
RocksterFactory

ロックスター生産工場

class
SharkFactory

SHARK生産工場

ナビゲーション・リンクをスキップ

概要

パッケージ

クラス

使用

階層ツリー

非推奨

索引

ヘルプ

前

次

フレーム

フレームなし

すべてのクラス


text:
@implementation CHRecomandViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

@end


text:
CREATE TABLE CARRINHO
(
    ID BIGINT NOT NULL AUTO_INCREMENT,
    DT_TRANSACAO DATETIME NOT NULL DEFAULT NOW(),
    USUARIO_ID INT,
    CLIENTE_ID INT NOT NULL,
    VL_TOTAL DECIMAL(9, 2) NOT NULL,
    PROTOCOLO BIGINT,

    PRIMARY KEY(ID),
    FOREIGN KEY (CLIENTE_ID) REFERENCES CLIENTE(ID)
);

CREATE TABLE CARRINHOITEM
(
    ID BIGINT NOT NULL AUTO_INCREMENT,
    CARRINHO_ID BIGINT NOT NULL,
    PRODUTO_ID INT NOT NULL,
    QUANTIDADE INT NOT NULL,
    TAMANHO VARCHAR(5) NOT NULL,
    VL_ITEM DECIMAL(9, 2) NOT NULL,

    PRIMARY KEY (ID),
    FOREIGN KEY (CARRINHO_ID) REFERENCES CARRINHO(ID)
);


text:
package com.yammer.dropwizard.db;

import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.db.DatabaseConfiguration;

public interface ConfigurationStrategy<T extends Configuration> {
    DatabaseConfiguration getDatabaseConfiguration(T configuration);
}


text:
<md-content>

Welcome to Fall 2015 Registration!

Login access your profile and course registration pin.

</md-content>


text:
import { MapClass } from '../MapClass'
import { BlockType, Texture } from '../types'

interface Options {
	width: number
	height: number
	texture?: Texture
	xAlign?: 'left' | 'center' | 'right'
	yAlign?: 'top' | 'center' | 'bottom'
}

export function setMapSize(
	world: MapClass,
	{ width, height, texture = Texture.InaccessibleWater, xAlign = 'center', yAlign = 'center' }: Options
): MapClass {
	const worldSize = world.width * world.height
	const newWorld = new MapClass({ width, height })
	const newBlocks = newWorld.blocks
	const oldBlocks = world.blocks

	const borderHeights = new Uint8Array(world.width + world.height - 1)
	borderHeights.set(oldBlocks[BlockType.HeightMap].slice(0, world.width))
	for (let i = world.width, j = world.width; i < worldSize; i += world.width, j++) {
		borderHeights[j] = oldBlocks[BlockType.HeightMap][i]
	}

	const averageLevel = Math.round(borderHeights.reduce((total, value) => total + value, 0) / borderHeights.byteLength)
	newBlocks[BlockType.HeightMap].fill(averageLevel)
	newBlocks[BlockType.Texture1].fill(texture)
	newBlocks[BlockType.Texture2].fill(texture)
	newBlocks[BlockType.FogOfWar].fill(7)

	const xDiv = (xAlign === 'center' && 2) || (xAlign === 'right' && 1) || 0
	const yDiv = (yAlign === 'center' && 2) || (yAlign === 'bottom' && 1) || 0
	const xDiff = xDiv && (width - world.width) / xDiv
	const yDiff = yDiv && (height - world.height) / yDiv

	const sourceXOffset = xDiff < 0 ? -xDiff : 0
	const targetXOffset = xDiff < 0 ? 0 : xDiff
	const sourceYOffset = yDiff < 0 ? -yDiff : 0
	const targetYOffset = yDiff < 0 ? 0 : yDiff
	const sourceWidth = Math.min(world.width, width)
	const sourceHeight = Math.min(world.height, height)

	for (
		let sY = sourceYOffset, sIndex = sY * world.width, tY = targetYOffset, tIndex = tY * width;
		sY < sourceHeight + sourceYOffset;
		sY++, sIndex += world.width, tY++, tIndex += width
	) {
		const start = sIndex + sourceXOffset
		const end = start + sourceWidth
		newBlocks[BlockType.Animal].set(oldBlocks[BlockType.Animal].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.FogOfWar].set(oldBlocks[BlockType.FogOfWar].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.HeightMap].set(oldBlocks[BlockType.HeightMap].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Icon].set(oldBlocks[BlockType.Icon].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Object1].set(oldBlocks[BlockType.Object1].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Object2].set(oldBlocks[BlockType.Object2].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Resource].set(oldBlocks[BlockType.Resource].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Roads].set(oldBlocks[BlockType.Roads].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Unknown].set(oldBlocks[BlockType.Unknown].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Texture1].set(oldBlocks[BlockType.Texture1].slice(start, end), tIndex + targetXOffset)
		newBlocks[BlockType.Texture2].set(oldBlocks[BlockType.Texture2].slice(start, end), tIndex + targetXOffset)
	}

	newWorld.title = world.title
	newWorld.author = world.author
	newWorld.animals = world.animals.reduce((animals, [type, x, y]) => {
		const newX = x + xDiff
		const newY = y + yDiff
		if (newX >= 0 && newX < width && newY >= 0 && newY < height) {
			animals.push([type, newX, newY])
		}
		return animals
	}, [] as [number, number, number][])
	newWorld.hqX = world.hqX.map((x, index) => {
		const y = world.hqY[index]
		if (x === 0xffff || y === 0xffff) return x
		const newX = x + xDiff
		const newY = y + yDiff
		if (newX < 0 || newX >= width || newY < 0 || newY >= height) return 0xffff
		return newX
	})
	newWorld.hqY = world.hqY.map((y, index) => {
		const x = world.hqX[index]
		if (x === 0xffff || y === 0xffff) return y
		const newX = x + xDiff
		const newY = y + yDiff
		if (newX < 0 || newX >= width || newY < 0 || newY >= height) return 0xffff
		return newY
	})
	newWorld.leader = world.leader.slice(0)
	newWorld.playerCount = world.playerCount
	newWorld.terrain = world.terrain

	newWorld.updateBuildSiteMap()
	newWorld.updateLightMap()
	newWorld.updateRegions()

	return newWorld
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Test\Inventory\Types;

use DTS\eBaySDK\Inventory\Types\InventoryItems;

class InventoryItemsTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new InventoryItems();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Inventory\Types\InventoryItems', $this->obj);
    }

    public function testExtendsBaseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <note/>
    <predicate lemma="childbearing">
        <note/>
        <roleset framnet="" id="childbearing.01" name="Bearing children" vncls="">
            <roles>
                <role descr="Mother" f="" n="0"/>
                <note/>
            </roles>
            <note>see bear.02</note>
        </roleset>
    </predicate>
</frameset>


text:
All notable changes to this project will be documented in this file.

## [Unreleased][unreleased]
### Fixed
- Support for etcd v0 and v2
- Panic from invalid skydns2 URI.

### Added
- Optional periodic resyncing of services from containers
- More error logging for registries
- Support for services on containers with `--net=host`
- Added `extensions.go` file for adding/disabling components
- Interpolate SERVICE_PORT and SERVICE_IP in SERVICE_X_CHECK_SCRIPT
- Ability to force IP for a service in consul
- Implemented ping for every service registry
- Option to only deregister containers cleanly shutdown #113

### Removed

### Changed
- Overall refactoring and cleanup
- Decoupled registries into subpackages using extpoints

## [v5] - 2015-02-18
### Added
- Automated, PR-driven release process
- Development Dockerfile and make task
- CircleCI config with artifacts for every build
- `--version` flag to see version

### Changed
- Base container is now Alpine
- Built entirely in Docker
- Moved to gliderlabs organization
- New versioning scheme
- Release artifact now saved container image

### Removed
- Dropped unnecessary layers in Dockerfile
- Dropped Godeps for now

[unreleased]: https://github.com/gliderlabs/registrator/compare/v5...HEAD
[v5]: https://github.com/gliderlabs/registrator/compare/v0.4.0...v5


text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.graphlib = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
module.exports = {
  Graph: require('./lib/graph'),
  json: require('./lib/json'),
  alg: require('./lib/alg')
}

},{"./lib/alg":8,"./lib/graph":16,"./lib/json":17}],2:[function(require,module,exports){
var _ = require('../lodash')

module.exports = components

function components (g) {
  const visited = {}
  const cmpts = []
  let cmpt

  function dfs (v) {
    if (_.has(visited, v)) return
    visited[v] = true
    cmpt.push(v)
    _.each(g.successors(v), dfs)
    _.each(g.predecessors(v), dfs)
  }

  _.each(g.nodes(), function (v) {
    cmpt = []
    dfs(v)
    if (cmpt.length) {
      cmpts.push(cmpt)
    }
  })

  return cmpts
}

},{"../lodash":18}],3:[function(require,module,exports){
var _ = require('../lodash')

module.exports = dfs

/*
 * A helper that preforms a pre- or post-order traversal on the input graph
 * and returns the nodes in the order they were visited. If the graph is
 * undirected then this algorithm will navigate using neighbors. If the graph
 * is directed then this algorithm will navigate using successors.
 *
 * Order must be one of "pre" or "post".
 */
function dfs (g, vs, order) {
  if (!_.isArray(vs)) {
    vs = [vs]
  }

  var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g)

  const acc = []
  const visited = {}
  _.each(vs, function (v) {
    if (!g.hasNode(v)) {
      throw new Error('Graph does not have node: ' + v)
    }

    doDfs(g, v, order === 'post', visited, navigation, acc)
  })
  return acc
}

function doDfs (g, v, postorder, visited, navigation, acc) {
  if (!_.has(visited, v)) {
    visited[v] = true

    if (!postorder) { acc.push(v) }
    _.each(navigation(v), function (w) {
      doDfs(g, w, postorder, visited, navigation, acc)
    })
    if (postorder) { acc.push(v) }
  }
}

},{"../lodash":18}],4:[function(require,module,exports){
const dijkstra = require('./dijkstra')
const _ = require('../lodash')

module.exports = dijkstraAll

function dijkstraAll (g, weightFunc, edgeFunc) {
  return _.transform(g.nodes(), function (acc, v) {
    acc[v] = dijkstra(g, v, weightFunc, edgeFunc)
  }, {})
}

},{"../lodash":18,"./dijkstra":5}],5:[function(require,module,exports){
const _ = require('../lodash')
const PriorityQueue = require('../data/priority-queue')

module.exports = dijkstra

var DEFAULT_WEIGHT_FUNC = _.constant(1)

function dijkstra (g, source, weightFn, edgeFn) {
  return runDijkstra(g, String(source),
    weightFn || DEFAULT_WEIGHT_FUNC,
    edgeFn || function (v) { return g.outEdges(v) })
}

function runDijkstra (g, source, weightFn, edgeFn) {
  const results = {}
  const pq = new PriorityQueue()
  let v, vEntry

  var updateNeighbors = function (edge) {
    const w = edge.v !== v ? edge.v : edge.w
    const wEntry = results[w]
    const weight = weightFn(edge)
    const distance = vEntry.distance + weight

    if (weight < 0) {
      throw new Error('dijkstra does not allow negative edge weights. ' +
                      'Bad edge: ' + edge + ' Weight: ' + weight)
    }

    if (distance < wEntry.distance) {
      wEntry.distance = distance
      wEntry.predecessor = v
      pq.decrease(w, distance)
    }
  }

  g.nodes().forEach(function (v) {
    var distance = v === source ? 0 : Number.POSITIVE_INFINITY
    results[v] = { distance: distance }
    pq.add(v, distance)
  })

  while (pq.size() > 0) {
    v = pq.removeMin()
    vEntry = results[v]
    if (vEntry.distance === Number.POSITIVE_INFINITY) {
      break
    }

    edgeFn(v).forEach(updateNeighbors)
  }

  return results
}

},{"../data/priority-queue":15,"../lodash":18}],6:[function(require,module,exports){
const _ = require('../lodash')
const tarjan = require('./tarjan')

module.exports = findCycles

function findCycles (g) {
  return _.filter(tarjan(g), function (cmpt) {
    return cmpt.length > 1 || (cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0]))
  })
}

},{"../lodash":18,"./tarjan":13}],7:[function(require,module,exports){
var _ = require('../lodash')

module.exports = floydWarshall

var DEFAULT_WEIGHT_FUNC = _.constant(1)

function floydWarshall (g, weightFn, edgeFn) {
  return runFloydWarshall(g,
    weightFn || DEFAULT_WEIGHT_FUNC,
    edgeFn || function (v) { return g.outEdges(v) })
}

function runFloydWarshall (g, weightFn, edgeFn) {
  const results = {}
  const nodes = g.nodes()

  nodes.forEach(function (v) {
    results[v] = {}
    results[v][v] = { distance: 0 }
    nodes.forEach(function (w) {
      if (v !== w) {
        results[v][w] = { distance: Number.POSITIVE_INFINITY }
      }
    })
    edgeFn(v).forEach(function (edge) {
      const w = edge.v === v ? edge.w : edge.v
      const d = weightFn(edge)
      results[v][w] = { distance: d, predecessor: v }
    })
  })

  nodes.forEach(function (k) {
    var rowK = results[k]
    nodes.forEach(function (i) {
      var rowI = results[i]
      nodes.forEach(function (j) {
        var ik = rowI[k]
        var kj = rowK[j]
        var ij = rowI[j]
        var altDistance = ik.distance + kj.distance
        if (altDistance < ij.distance) {
          ij.distance = altDistance
          ij.predecessor = kj.predecessor
        }
      })
    })
  })

  return results
}

},{"../lodash":18}],8:[function(require,module,exports){
module.exports = {
  components: require('./components'),
  dijkstra: require('./dijkstra'),
  dijkstraAll: require('./dijkstra-all'),
  findCycles: require('./find-cycles'),
  floydWarshall: require('./floyd-warshall'),
  isAcyclic: require('./is-acyclic'),
  postorder: require('./postorder'),
  preorder: require('./preorder'),
  prim: require('./prim'),
  tarjan: require('./tarjan'),
  topsort: require('./topsort')
}

},{"./components":2,"./dijkstra":5,"./dijkstra-all":4,"./find-cycles":6,"./floyd-warshall":7,"./is-acyclic":9,"./postorder":10,"./preorder":11,"./prim":12,"./tarjan":13,"./topsort":14}],9:[function(require,module,exports){
var topsort = require('./topsort')

module.exports = isAcyclic

function isAcyclic (g) {
  try {
    topsort(g)
  } catch (e) {
    if (e instanceof topsort.CycleException) {
      return false
    }
    throw e
  }
  return true
}

},{"./topsort":14}],10:[function(require,module,exports){
var dfs = require('./dfs')

module.exports = postorder

function postorder (g, vs) {
  return dfs(g, vs, 'post')
}

},{"./dfs":3}],11:[function(require,module,exports){
var dfs = require('./dfs')

module.exports = preorder

function preorder (g, vs) {
  return dfs(g, vs, 'pre')
}

},{"./dfs":3}],12:[function(require,module,exports){
const _ = require('../lodash')
const Graph = require('../graph')
const PriorityQueue = require('../data/priority-queue')

module.exports = prim

function prim (g, weightFunc) {
  const result = new Graph()
  const parents = {}
  const pq = new PriorityQueue()
  let v

  function updateNeighbors (edge) {
    const w = edge.v === v ? edge.w : edge.v
    const pri = pq.priority(w)
    if (pri !== undefined) {
      var edgeWeight = weightFunc(edge)
      if (edgeWeight < pri) {
        parents[w] = v
        pq.decrease(w, edgeWeight)
      }
    }
  }

  if (g.nodeCount() === 0) {
    return result
  }

  _.each(g.nodes(), function (v) {
    pq.add(v, Number.POSITIVE_INFINITY)
    result.setNode(v)
  })

  // Start from an arbitrary node
  pq.decrease(g.nodes()[0], 0)

  var init = false
  while (pq.size() > 0) {
    v = pq.removeMin()
    if (_.has(parents, v)) {
      result.setEdge(v, parents[v])
    } else if (init) {
      throw new Error('Input graph is not connected: ' + g)
    } else {
      init = true
    }

    g.nodeEdges(v).forEach(updateNeighbors)
  }

  return result
}

},{"../data/priority-queue":15,"../graph":16,"../lodash":18}],13:[function(require,module,exports){
var _ = require('../lodash')

module.exports = tarjan

function tarjan (g) {
  let index = 0
  const stack = []
  const visited = {} // node id -> { onStack, lowlink, index }
  const results = []

  function dfs (v) {
    var entry = visited[v] = {
      onStack: true,
      lowlink: index,
      index: index++
    }
    stack.push(v)

    g.successors(v).forEach(function (w) {
      if (!_.has(visited, w)) {
        dfs(w)
        entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink)
      } else if (visited[w].onStack) {
        entry.lowlink = Math.min(entry.lowlink, visited[w].index)
      }
    })

    if (entry.lowlink === entry.index) {
      const cmpt = []
      let w
      do {
        w = stack.pop()
        visited[w].onStack = false
        cmpt.push(w)
      } while (v !== w)
      results.push(cmpt)
    }
  }

  g.nodes().forEach(function (v) {
    if (!_.has(visited, v)) {
      dfs(v)
    }
  })

  return results
}

},{"../lodash":18}],14:[function(require,module,exports){
const _ = require('../lodash')

module.exports = topsort
topsort.CycleException = CycleException

function topsort (g) {
  const visited = {}
  const stack = {}
  const results = []

  function visit (node) {
    if (_.has(stack, node)) {
      throw new CycleException()
    }

    if (!_.has(visited, node)) {
      stack[node] = true
      visited[node] = true
      _.each(g.predecessors(node), visit)
      delete stack[node]
      results.push(node)
    }
  }

  _.each(g.sinks(), visit)

  if (_.size(visited) !== g.nodeCount()) {
    throw new CycleException()
  }

  return results
}

function CycleException () {}
CycleException.prototype = new Error() // must be an instance of Error to pass testing

},{"../lodash":18}],15:[function(require,module,exports){
const _ = require('../lodash')

module.exports = PriorityQueue

/**
 * A min-priority queue data structure. This algorithm is derived from Cormen,
 * et al., "Introduction to Algorithms". The basic idea of a min-priority
 * queue is that you can efficiently (in O(1) time) get the smallest key in
 * the queue. Adding and removing elements takes O(log n) time. A key can
 * have its priority decreased in O(log n) time.
 */
function PriorityQueue () {
  this._arr = []
  this._keyIndices = {}
}

/**
 * Returns the number of elements in the queue. Takes `O(1)` time.
 */
PriorityQueue.prototype.size = function () {
  return this._arr.length
}

/**
 * Returns the keys that are in the queue. Takes `O(n)` time.
 */
PriorityQueue.prototype.keys = function () {
  return this._arr.map(function (x) { return x.key })
}

/**
 * Returns `true` if **key** is in the queue and `false` if not.
 */
PriorityQueue.prototype.has = function (key) {
  return _.has(this._keyIndices, key)
}

/**
 * Returns the priority for **key**. If **key** is not present in the queue
 * then this function returns `undefined`. Takes `O(1)` time.
 *
 * @param {Object} key
 */
PriorityQueue.prototype.priority = function (key) {
  var index = this._keyIndices[key]
  if (index !== undefined) {
    return this._arr[index].priority
  }
}

/**
 * Returns the key for the minimum element in this queue. If the queue is
 * empty this function throws an Error. Takes `O(1)` time.
 */
PriorityQueue.prototype.min = function () {
  if (this.size() === 0) {
    throw new Error('Queue underflow')
  }
  return this._arr[0].key
}

/**
 * Inserts a new key into the priority queue. If the key already exists in
 * the queue this function returns `false`; otherwise it will return `true`.
 * Takes `O(n)` time.
 *
 * @param {Object} key the key to add
 * @param {Number} priority the initial priority for the key
 */
PriorityQueue.prototype.add = function (key, priority) {
  var keyIndices = this._keyIndices
  key = String(key)
  if (!_.has(keyIndices, key)) {
    var arr = this._arr
    var index = arr.length
    keyIndices[key] = index
    arr.push({key: key, priority: priority})
    this._decrease(index)
    return true
  }
  return false
}

/**
 * Removes and returns the smallest key in the queue. Takes `O(log n)` time.
 */
PriorityQueue.prototype.removeMin = function () {
  this._swap(0, this._arr.length - 1)
  var min = this._arr.pop()
  delete this._keyIndices[min.key]
  this._heapify(0)
  return min.key
}

/**
 * Decreases the priority for **key** to **priority**. If the new priority is
 * greater than the previous priority, this function will throw an Error.
 *
 * @param {Object} key the key for which to raise priority
 * @param {Number} priority the new priority for the key
 */
PriorityQueue.prototype.decrease = function (key, priority) {
  var index = this._keyIndices[key]
  if (priority > this._arr[index].priority) {
    throw new Error('New priority is greater than current priority. ' +
        'Key: ' + key + ' Old: ' + this._arr[index].priority + ' New: ' + priority)
  }
  this._arr[index].priority = priority
  this._decrease(index)
}

PriorityQueue.prototype._heapify = function (i) {
  const arr = this._arr
  const l = 2 * i
  const r = l + 1
  let largest = i
  if (l < arr.length) {
    largest = arr[l].priority < arr[largest].priority ? l : largest
    if (r < arr.length) {
      largest = arr[r].priority < arr[largest].priority ? r : largest
    }
    if (largest !== i) {
      this._swap(i, largest)
      this._heapify(largest)
    }
  }
}

PriorityQueue.prototype._decrease = function (index) {
  var arr = this._arr
  var priority = arr[index].priority
  var parent
  while (index !== 0) {
    parent = index >> 1
    if (arr[parent].priority < priority) {
      break
    }
    this._swap(index, parent)
    index = parent
  }
}

PriorityQueue.prototype._swap = function (i, j) {
  var arr = this._arr
  var keyIndices = this._keyIndices
  var origArrI = arr[i]
  var origArrJ = arr[j]
  arr[i] = origArrJ
  arr[j] = origArrI
  keyIndices[origArrJ.key] = i
  keyIndices[origArrI.key] = j
}

},{"../lodash":18}],16:[function(require,module,exports){
const _ = require('./lodash')

module.exports = Graph

const DEFAULT_EDGE_NAME = '\x00'
const GRAPH_NODE = '\x00'
const EDGE_KEY_DELIM = '\x01'

// Implementation notes:
//
//  * Node id query functions should return string ids for the nodes
//  * Edge id query functions should return an "edgeObj", edge object, that is
//    composed of enough information to uniquely identify an edge: {v, w, name}.
//  * Internally we use an "edgeId", a stringified form of the edgeObj, to
//    reference edges. This is because we need a performant way to look these
//    edges up and, object properties, which have string keys, are the closest
//    we're going to get to a performant hashtable in JavaScript.

function Graph (opts) {
  this._isDirected = _.has(opts, 'directed') ? opts.directed : true
  this._isMultigraph = _.has(opts, 'multigraph') ? opts.multigraph : false
  this._isCompound = _.has(opts, 'compound') ? opts.compound : false

  // Label for the graph itself
  this._label = undefined

  // Defaults to be set when creating a new node
  this._defaultNodeLabelFn = _.constant(undefined)

  // Defaults to be set when creating a new edge
  this._defaultEdgeLabelFn = _.constant(undefined)

  // v -> label
  this._nodes = {}

  if (this._isCompound) {
    // v -> parent
    this._parent = {}

    // v -> children
    this._children = {}
    this._children[GRAPH_NODE] = {}
  }

  // v -> edgeObj
  this._in = {}

  // u -> v -> Number
  this._preds = {}

  // v -> edgeObj
  this._out = {}

  // v -> w -> Number
  this._sucs = {}

  // e -> edgeObj
  this._edgeObjs = {}

  // e -> label
  this._edgeLabels = {}
}

/* Number of nodes in the graph. Should only be changed by the implementation. */
Graph.prototype._nodeCount = 0

/* Number of edges in the graph. Should only be changed by the implementation. */
Graph.prototype._edgeCount = 0

/* === Graph functions ========= */

Graph.prototype.isDirected = function () {
  return this._isDirected
}

Graph.prototype.isMultigraph = function () {
  return this._isMultigraph
}

Graph.prototype.isCompound = function () {
  return this._isCompound
}

Graph.prototype.setGraph = function (label) {
  this._label = label
  return this
}

Graph.prototype.graph = function () {
  return this._label
}

/* === Node functions ========== */

Graph.prototype.setDefaultNodeLabel = function (newDefault) {
  if (!_.isFunction(newDefault)) {
    newDefault = _.constant(newDefault)
  }
  this._defaultNodeLabelFn = newDefault
  return this
}

Graph.prototype.nodeCount = function () {
  return this._nodeCount
}

Graph.prototype.nodes = function () {
  return _.keys(this._nodes)
}

Graph.prototype.sources = function () {
  var self = this
  return _.filter(this.nodes(), function (v) {
    return _.isEmpty(self._in[v])
  })
}

Graph.prototype.sinks = function () {
  var self = this
  return _.filter(this.nodes(), function (v) {
    return _.isEmpty(self._out[v])
  })
}

Graph.prototype.setNodes = function (vs, value) {
  var args = arguments
  var self = this
  _.each(vs, function (v) {
    if (args.length > 1) {
      self.setNode(v, value)
    } else {
      self.setNode(v)
    }
  })
  return this
}

Graph.prototype.setNode = function (v, value) {
  if (_.has(this._nodes, v)) {
    if (arguments.length > 1) {
      this._nodes[v] = value
    }
    return this
  }

  this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v)
  if (this._isCompound) {
    this._parent[v] = GRAPH_NODE
    this._children[v] = {}
    this._children[GRAPH_NODE][v] = true
  }
  this._in[v] = {}
  this._preds[v] = {}
  this._out[v] = {}
  this._sucs[v] = {}
  ++this._nodeCount
  return this
}

Graph.prototype.node = function (v) {
  return this._nodes[v]
}

Graph.prototype.hasNode = function (v) {
  return _.has(this._nodes, v)
}

Graph.prototype.removeNode = function (v) {
  var self = this
  if (_.has(this._nodes, v)) {
    var removeEdge = function (e) { self.removeEdge(self._edgeObjs[e]) }
    delete this._nodes[v]
    if (this._isCompound) {
      this._removeFromParentsChildList(v)
      delete this._parent[v]
      _.each(this.children(v), function (child) {
        self.setParent(child)
      })
      delete this._children[v]
    }
    _.each(_.keys(this._in[v]), removeEdge)
    delete this._in[v]
    delete this._preds[v]
    _.each(_.keys(this._out[v]), removeEdge)
    delete this._out[v]
    delete this._sucs[v]
    --this._nodeCount
  }
  return this
}

Graph.prototype.setParent = function (v, parent) {
  if (!this._isCompound) {
    throw new Error('Cannot set parent in a non-compound graph')
  }

  if (_.isUndefined(parent)) {
    parent = GRAPH_NODE
  } else {
    // Coerce parent to string
    parent += ''
    for (var ancestor = parent;
      !_.isUndefined(ancestor);
      ancestor = this.parent(ancestor)) {
      if (ancestor === v) {
        throw new Error('Setting ' + parent + ' as parent of ' + v +
                        ' would create a cycle')
      }
    }

    this.setNode(parent)
  }

  this.setNode(v)
  this._removeFromParentsChildList(v)
  this._parent[v] = parent
  this._children[parent][v] = true
  return this
}

Graph.prototype._removeFromParentsChildList = function (v) {
  delete this._children[this._parent[v]][v]
}

Graph.prototype.parent = function (v) {
  if (this._isCompound) {
    var parent = this._parent[v]
    if (parent !== GRAPH_NODE) {
      return parent
    }
  }
}

Graph.prototype.children = function (v) {
  if (_.isUndefined(v)) {
    v = GRAPH_NODE
  }

  if (this._isCompound) {
    var children = this._children[v]
    if (children) {
      return _.keys(children)
    }
  } else if (v === GRAPH_NODE) {
    return this.nodes()
  } else if (this.hasNode(v)) {
    return []
  }
}

Graph.prototype.predecessors = function (v) {
  var predsV = this._preds[v]
  if (predsV) {
    return _.keys(predsV)
  }
}

Graph.prototype.successors = function (v) {
  var sucsV = this._sucs[v]
  if (sucsV) {
    return _.keys(sucsV)
  }
}

Graph.prototype.neighbors = function (v) {
  var preds = this.predecessors(v)
  if (preds) {
    return _.union(preds, this.successors(v))
  }
}

Graph.prototype.isLeaf = function (v) {
  var neighbors
  if (this.isDirected()) {
    neighbors = this.successors(v)
  } else {
    neighbors = this.neighbors(v)
  }
  return neighbors.length === 0
}

Graph.prototype.filterNodes = function (filter) {
  var copy = new this.constructor({
    directed: this._isDirected,
    multigraph: this._isMultigraph,
    compound: this._isCompound
  })

  copy.setGraph(this.graph())

  var self = this
  _.each(this._nodes, function (value, v) {
    if (filter(v)) {
      copy.setNode(v, value)
    }
  })

  _.each(this._edgeObjs, function (e) {
    if (copy.hasNode(e.v) && copy.hasNode(e.w)) {
      copy.setEdge(e, self.edge(e))
    }
  })

  var parents = {}
  function findParent (v) {
    var parent = self.parent(v)
    if (parent === undefined || copy.hasNode(parent)) {
      parents[v] = parent
      return parent
    } else if (parent in parents) {
      return parents[parent]
    } else {
      return findParent(parent)
    }
  }

  if (this._isCompound) {
    _.each(copy.nodes(), function (v) {
      copy.setParent(v, findParent(v))
    })
  }

  return copy
}

/* === Edge functions ========== */

Graph.prototype.setDefaultEdgeLabel = function (newDefault) {
  if (!_.isFunction(newDefault)) {
    newDefault = _.constant(newDefault)
  }
  this._defaultEdgeLabelFn = newDefault
  return this
}

Graph.prototype.edgeCount = function () {
  return this._edgeCount
}

Graph.prototype.edges = function () {
  return _.values(this._edgeObjs)
}

Graph.prototype.setPath = function (vs, value) {
  const self = this
  const args = arguments
  _.reduce(vs, function (v, w) {
    if (args.length > 1) {
      self.setEdge(v, w, value)
    } else {
      self.setEdge(v, w)
    }
    return w
  })
  return this
}

/*
 * setEdge(v, w, [value, [name]])
 * setEdge({ v, w, [name] }, [value])
 */
Graph.prototype.setEdge = function () {
  let v, w, name, value
  let valueSpecified = false
  const arg0 = arguments[0]

  if (typeof arg0 === 'object' && arg0 !== null && 'v' in arg0) {
    v = arg0.v
    w = arg0.w
    name = arg0.name
    if (arguments.length === 2) {
      value = arguments[1]
      valueSpecified = true
    }
  } else {
    v = arg0
    w = arguments[1]
    name = arguments[3]
    if (arguments.length > 2) {
      value = arguments[2]
      valueSpecified = true
    }
  }

  v = '' + v
  w = '' + w
  if (!_.isUndefined(name)) {
    name = '' + name
  }

  var e = edgeArgsToId(this._isDirected, v, w, name)
  if (_.has(this._edgeLabels, e)) {
    if (valueSpecified) {
      this._edgeLabels[e] = value
    }
    return this
  }

  if (!_.isUndefined(name) && !this._isMultigraph) {
    throw new Error('Cannot set a named edge when isMultigraph = false')
  }

  // It didn't exist, so we need to create it.
  // First ensure the nodes exist.
  this.setNode(v)
  this.setNode(w)

  this._edgeLabels[e] = valueSpecified ? value : this._defaultEdgeLabelFn(v, w, name)

  var edgeObj = edgeArgsToObj(this._isDirected, v, w, name)
  // Ensure we add undirected edges in a consistent way.
  v = edgeObj.v
  w = edgeObj.w

  Object.freeze(edgeObj)
  this._edgeObjs[e] = edgeObj
  incrementOrInitEntry(this._preds[w], v)
  incrementOrInitEntry(this._sucs[v], w)
  this._in[w][e] = edgeObj
  this._out[v][e] = edgeObj
  this._edgeCount++
  return this
}

Graph.prototype.edge = function (v, w, name) {
  var e = (arguments.length === 1
    ? edgeObjToId(this._isDirected, arguments[0])
    : edgeArgsToId(this._isDirected, v, w, name))
  return this._edgeLabels[e]
}

Graph.prototype.hasEdge = function (v, w, name) {
  var e = (arguments.length === 1
    ? edgeObjToId(this._isDirected, arguments[0])
    : edgeArgsToId(this._isDirected, v, w, name))
  return _.has(this._edgeLabels, e)
}

Graph.prototype.removeEdge = function (v, w, name) {
  const e = (arguments.length === 1
    ? edgeObjToId(this._isDirected, arguments[0])
    : edgeArgsToId(this._isDirected, v, w, name))
  const edge = this._edgeObjs[e]
  if (edge) {
    v = edge.v
    w = edge.w
    delete this._edgeLabels[e]
    delete this._edgeObjs[e]
    decrementOrRemoveEntry(this._preds[w], v)
    decrementOrRemoveEntry(this._sucs[v], w)
    delete this._in[w][e]
    delete this._out[v][e]
    this._edgeCount--
  }
  return this
}

Graph.prototype.inEdges = function (v, u) {
  var inV = this._in[v]
  if (inV) {
    var edges = _.values(inV)
    if (!u) {
      return edges
    }
    return _.filter(edges, function (edge) { return edge.v === u })
  }
}

Graph.prototype.outEdges = function (v, w) {
  var outV = this._out[v]
  if (outV) {
    var edges = _.values(outV)
    if (!w) {
      return edges
    }
    return _.filter(edges, function (edge) { return edge.w === w })
  }
}

Graph.prototype.nodeEdges = function (v, w) {
  var inEdges = this.inEdges(v, w)
  if (inEdges) {
    return inEdges.concat(this.outEdges(v, w))
  }
}

function incrementOrInitEntry (map, k) {
  if (map[k]) {
    map[k]++
  } else {
    map[k] = 1
  }
}

function decrementOrRemoveEntry (map, k) {
  if (!--map[k]) { delete map[k] }
}

function edgeArgsToId (isDirected, v_, w_, name) {
  var v = '' + v_
  var w = '' + w_
  if (!isDirected && v > w) {
    var tmp = v
    v = w
    w = tmp
  }
  return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM +
             (_.isUndefined(name) ? DEFAULT_EDGE_NAME : name)
}

function edgeArgsToObj (isDirected, v_, w_, name) {
  var v = '' + v_
  var w = '' + w_
  if (!isDirected && v > w) {
    var tmp = v
    v = w
    w = tmp
  }
  var edgeObj = { v: v, w: w }
  if (name) {
    edgeObj.name = name
  }
  return edgeObj
}

function edgeObjToId (isDirected, edgeObj) {
  return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name)
}

},{"./lodash":18}],17:[function(require,module,exports){
const _ = require('./lodash')
const Graph = require('./graph')

module.exports = {
  write: write,
  read: read
}

function write (g) {
  var json = {
    options: {
      directed: g.isDirected(),
      multigraph: g.isMultigraph(),
      compound: g.isCompound()
    },
    nodes: writeNodes(g),
    edges: writeEdges(g)
  }
  if (!_.isUndefined(g.graph())) {
    json.value = _.clone(g.graph())
  }
  return json
}

function writeNodes (g) {
  return _.map(g.nodes(), function (v) {
    const nodeValue = g.node(v)
    const parent = g.parent(v)
    const node = { v: v }
    if (!_.isUndefined(nodeValue)) {
      node.value = nodeValue
    }
    if (!_.isUndefined(parent)) {
      node.parent = parent
    }
    return node
  })
}

function writeEdges (g) {
  return _.map(g.edges(), function (e) {
    const edgeValue = g.edge(e)
    const edge = { v: e.v, w: e.w }
    if (!_.isUndefined(e.name)) {
      edge.name = e.name
    }
    if (!_.isUndefined(edgeValue)) {
      edge.value = edgeValue
    }
    return edge
  })
}

function read (json) {
  var g = new Graph(json.options).setGraph(json.value)
  _.each(json.nodes, function (entry) {
    g.setNode(entry.v, entry.value)
    if (entry.parent) {
      g.setParent(entry.v, entry.parent)
    }
  })
  _.each(json.edges, function (entry) {
    g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value)
  })
  return g
}

},{"./graph":16,"./lodash":18}],18:[function(require,module,exports){
/* global window */

var lodash

if (typeof require === 'function') {
  try {
    lodash = require('lodash')
  } catch (e) {}
}

if (!lodash) {
  lodash = window._
}

module.exports = lodash

},{"lodash":undefined}]},{},[1])(1)
});


text:
package hu.petabyte.redflags.engine.gear.parser;

import static com.google.common.base.Preconditions.checkNotNull;
import hu.petabyte.redflags.engine.gear.AbstractGear;
import hu.petabyte.redflags.engine.model.DisplayLanguage;
import hu.petabyte.redflags.engine.model.Notice;
import hu.petabyte.redflags.engine.model.NoticeID;
import hu.petabyte.redflags.engine.model.Tab;
import hu.petabyte.redflags.engine.tedintf.TedInterfaceHolder;
import hu.petabyte.redflags.engine.tedintf.TedResponse;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Zsolt Jurányi
 */
@Component
public class DocFamilyFetcher extends AbstractGear {

	// TODO AVOID INFINITE LOOPS - AVOID STARTING NEW SUB SESSION WITH THIS GEAR

	protected static final Logger LOG = LoggerFactory
			.getLogger(DocFamilyFetcher.class);
	protected static final String DATE_FORMAT = "dd-MM-yyyy";

	protected @Value("${redflags.engine.gear.parse.lang:EN}") String rawLang;
	protected DisplayLanguage lang;
	protected @Autowired TedInterfaceHolder ted;

	@Override
	public void beforeSession() throws Exception {
		lang = DisplayLanguage.valueOf(checkNotNull(rawLang));
		LOG.debug("Parsing language is {}", lang);
	}

	private void determineDocFamilyId(Notice notice) {
		NoticeID docFamilyId = notice.getId();
		for (Notice n : notice.getFamilyMembers()) {
			NoticeID memberId = n.getId();
			if (memberId.compareTo(docFamilyId) < 0) {
				docFamilyId = memberId;
			}
		}
		notice.setDocumentFamilyId(docFamilyId);
		for (Notice m : notice.getFamilyMembers()) {
			m.setDocumentFamilyId(docFamilyId);
		}
		LOG.debug("Document family ID for notice {} is {}", notice.getId(),
				docFamilyId);
	}

	public Notice parseDocFamilyTab(Notice notice, Document docFamilyTab) {
		for (Element memberTable : docFamilyTab.select("table.family")) {
			try {
				NoticeID memberId = new NoticeID(memberTable
						.select("thead a[href~=TED:NOTICE:]").first().text()
						.split(":", 2)[0]);
				if (!notice.getId().equals(memberId)) {
					Notice memberNotice = new Notice(memberId);

					Elements tds = memberTable.select("tbody tr").first()
							.select("td.bgGreen");

					String rawMemberPubDate = tds.get(0).text();
					Date memberPubDate = new SimpleDateFormat(DATE_FORMAT)
					.parse(rawMemberPubDate);
					memberNotice.getData().setPublicationDate(memberPubDate);

					if (tds.size() > 1) {
						String rawMemberDeadline = tds.get(1).text();
						Date memberDeadline = new SimpleDateFormat(DATE_FORMAT)
						.parse(rawMemberDeadline);
						memberNotice.getData().setDeadline(memberDeadline);
					}

					notice.getFamilyMembers().add(memberNotice);
					LOG.trace("{} Member found: {} - {} (deadline: {})",
							notice.getId(), memberId, memberPubDate,
							memberNotice.getData().getDeadline());
				}
			} catch (Exception e) {
				LOG.warn("Cannot parse a document family member of notice "
						+ notice.getId(), e);
			}
		}
		return notice;
	}

	@Override
	protected Notice processImpl(Notice notice) throws Exception {
		TedResponse r = ted.get().requestNoticeTabQuietly(notice.getId(), lang,
				Tab.DATA);
		if (null != r) {
			Document dataTab = r.getParsedDocument();
			if (!dataTab.select("a[href~=tabId=4").isEmpty()) {
				TedResponse r2 = ted.get().requestNoticeTabQuietly(
						notice.getId(), lang, Tab.DOCUMENT_FAMILY);
				if (null != r2) {
					Document docFamilyTab = r2.getParsedDocument();
					notice = parseDocFamilyTab(notice, docFamilyTab);
				}
			}
		}

		determineDocFamilyId(notice);

		return notice;
	}

}


text:
package de.altimos.util.asset.ext;

import java.io.IOException;

import org.jdom2.input.SAXBuilder;

import de.altimos.util.asset.AssetInfo;
import de.altimos.util.asset.AssetLoader;
import de.altimos.util.asset.AssetManager;

/**
 *
 * @author Jan Graichen <jg@altimos.de>
 * @version $Id$
 */
public class XmlDocumentLoader implements AssetLoader {

	@Override
	public Object loadAsset(AssetManager mgr, AssetInfo info) throws IOException {
		try{
			SAXBuilder builder = new SAXBuilder();
			return new XmlDocument(info.getKey(), builder.build(info.openStream()));
		}catch (Exception e) {
			throw new IOException(e.getMessage(), e);
		}
	}

}


text:
package org.jkiss.dbeaver.ui.dialogs.driver;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.model.connection.DBPDriverDependencies;
import org.jkiss.dbeaver.model.connection.DBPDriverLibrary;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DefaultProgressMonitor;
import org.jkiss.dbeaver.registry.driver.DriverDescriptor;
import org.jkiss.dbeaver.runtime.RunnableContextDelegate;
import org.jkiss.dbeaver.runtime.ui.DBUserInterface;
import org.jkiss.dbeaver.ui.UIConfirmation;
import org.jkiss.dbeaver.ui.UITask;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.CommonUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

class DriverDownloadAutoPage extends DriverDownloadPage {

    private DriverDependenciesTree depsTree;

    DriverDownloadAutoPage() {
        super("Automatic download", "Download driver files", null);
        setPageComplete(false);
    }

    @Override
    public void createControl(Composite parent) {
        final DriverDownloadWizard wizard = getWizard();
        final DriverDescriptor driver = wizard.getDriver();

        setMessage("Download " + driver.getFullName() + " driver files");
        initializeDialogUnits(parent);

        Composite composite = UIUtils.createPlaceholder(parent, 1);
        composite.setLayoutData(new GridData(GridData.FILL_BOTH));

        if (!wizard.isForceDownload()) {
            Composite infoGroup = UIUtils.createPlaceholder(composite, 2, 5);
            infoGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            Label infoText = new Label(infoGroup, SWT.NONE);
            infoText.setText(driver.getFullName() + " driver files are missing.\nDBeaver can download these files automatically.\n\n");
            infoText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

            final Button forceCheckbox = UIUtils.createCheckbox(infoGroup, "Force download / overwrite", wizard.isForceDownload());
            forceCheckbox.setToolTipText("Force files download. Will download files even if they are already on the disk");
            forceCheckbox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_BEGINNING));
            forceCheckbox.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    wizard.setForceDownload(forceCheckbox.getSelection());
                }
            });
        }

        {
            Group filesGroup = UIUtils.createControlGroup(composite, "Files required by driver", 1, -1, -1);
            filesGroup.setLayoutData(new GridData(GridData.FILL_BOTH));

            depsTree = new DriverDependenciesTree(
                filesGroup,
                new RunnableContextDelegate(getContainer()),
                getWizard().getDependencies(),
                driver,
                driver.getDriverLibraries(),
                true)
            {
                protected void setLibraryVersion(final DBPDriverLibrary library, final String version) {
                    String curVersion = library.getVersion();
                    if (CommonUtils.equalObjects(curVersion, version)) {
                        return;
                    }
                    library.setPreferredVersion(version);
                    resolveLibraries();
                }

            };
            new Label(filesGroup, SWT.NONE).setText("You can change driver version by clicking on version column.\nThen you can choose one of the available versions.");
        }

        if (!wizard.isForceDownload()) {
            Label infoText = new Label(composite, SWT.NONE);
            infoText.setText("\nOr you can obtain driver files by yourself and add them in driver editor.");
            infoText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        }

        createLinksPanel(composite);

        setControl(composite);
    }

    @Override
    void resolveLibraries() {
        if (!depsTree.resolveLibraries()) {
            setErrorMessage("Can't resolve libraries. Check your network settings");
        }
        depsTree.resizeTree();
    }

    @Override
    public boolean isPageComplete() {
        return true;
    }

    @Override
    boolean performFinish() {
        try {
            getContainer().run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    downloadLibraryFiles(new DefaultProgressMonitor(monitor));
                }
            });
        } catch (InvocationTargetException e) {
            DBUserInterface.getInstance().showError("Driver download", "Error downloading driver files", e.getTargetException());
        } catch (InterruptedException e) {
            // ignore
        }
        return true;
    }

    private void downloadLibraryFiles(final DBRProgressMonitor monitor) throws InterruptedException {
        if (!getWizard().getDriver().acceptDriverLicenses()) {
            return;
        }

        boolean processUnsecure = false;
        List<DBPDriverDependencies.DependencyNode> nodes = getWizard().getDependencies().getLibraryList();
        for (int i = 0, filesSize = nodes.size(); i < filesSize; ) {
            final DBPDriverLibrary lib = nodes.get(i).library;
            if (!processUnsecure && !lib.isSecureDownload(monitor)) {
                boolean process = new UIConfirmation() {
                    @Override
                    protected Boolean runTask() {
                        MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);
                        messageBox.setText("Security warning");
                        messageBox.setMessage(
                                "Library '" + lib.getDisplayName() + "' wasn't found in secure repositories.\n" +
                                "Only non-secure version is available: " + lib.getExternalURL(monitor) + ".\n\n" +
                                "It is not recommended to use non-secure repositories because of possibility of malware infection.\n\n" +
                                "Are you sure you want to proceed?");
                        int response = messageBox.open();
                        return (response == SWT.YES);
                    }
                }.execute();
                if (process) {
                    processUnsecure = true;
                } else {
                    break;
                }
            }
            int result = IDialogConstants.OK_ID;
            try {
                lib.downloadLibraryFile(monitor, getWizard().isForceDownload(), "Download " + (i + 1) + "/" + filesSize);
            } catch (final IOException e) {
                if (lib.getType() == DBPDriverLibrary.FileType.license) {
                    result = IDialogConstants.OK_ID;
                } else {
                    result = new UITask<Integer>() {
                        @Override
                        protected Integer runTask() {
                            DownloadErrorDialog dialog = new DownloadErrorDialog(
                                    null,
                                    lib.getDisplayName(),
                                    "Driver file download failed.\nDo you want to retry?",
                                    e);
                            return dialog.open();
                        }
                    }.execute();
                }
            }
            switch (result) {
                case IDialogConstants.CANCEL_ID:
                case IDialogConstants.ABORT_ID:
                    return;
                case IDialogConstants.RETRY_ID:
                    continue;
                case IDialogConstants.OK_ID:
                case IDialogConstants.IGNORE_ID:
                    i++;
                    break;
            }
        }

        getWizard().getDriver().setModified(true);
        //DataSourceProviderRegistry.getInstance().saveDrivers();
    }

    public static class DownloadErrorDialog extends ErrorDialog {

        DownloadErrorDialog(
                Shell parentShell,
                String dialogTitle,
                String message,
                Throwable error)
        {
            super(parentShell, dialogTitle, message,
                GeneralUtils.makeExceptionStatus(error),
                IStatus.INFO | IStatus.WARNING | IStatus.ERROR);
        }

        @Override
        protected void createButtonsForButtonBar(Composite parent) {
            createButton(
                parent,
                IDialogConstants.ABORT_ID,
                IDialogConstants.ABORT_LABEL,
                true);
            createButton(
                parent,
                IDialogConstants.RETRY_ID,
                IDialogConstants.RETRY_LABEL,
                false);
            createButton(
                parent,
                IDialogConstants.IGNORE_ID,
                IDialogConstants.IGNORE_LABEL,
                false);
            createDetailsButton(parent);
        }

        @Override
        protected void buttonPressed(int buttonId) {
            if (buttonId == IDialogConstants.DETAILS_ID) {
                super.buttonPressed(buttonId);
            } else {
                setReturnCode(buttonId);
                close();
            }
        }
    }

}


text:
if exist .\packages rmdir /s /q packages
mkdir packages


text:
package org.scala_tools.time

import java.util.Date
import org.joda.time._

class RichDate(val d: Date) {
  def toLocalDateTime: LocalDateTime = StaticLocalDateTime.fromDateFields(d)
  def toLocalDate: LocalDate = StaticLocalDate.fromDateFields(d)
  def toLocalTime: LocalTime = StaticLocalTime.fromDateFields(d)
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using ILCompiler.DependencyAnalysis.ARM;

namespace ILCompiler.DependencyAnalysis
{
    public partial class UnboxingStubNode
    {
        protected override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
        {
            encoder.EmitADD(encoder.TargetRegister.Arg0, (byte)factory.Target.PointerSize); // add r0, sizeof(void*);
            encoder.EmitJMP(factory.MethodEntrypoint(Method)); // b methodEntryPoint
        }
    }
}


text:
// zkctld is a daemon that starts or initializes ZooKeeper with Vitess-specific
// configuration. It will stay running as long as the underlying ZooKeeper
// server, and will pass along SIGTERM.
package main

import (
	"flag"
	"os"
	"os/signal"
	"syscall"

	"vitess.io/vitess/go/exit"
	"vitess.io/vitess/go/vt/log"
	"vitess.io/vitess/go/vt/logutil"
	"vitess.io/vitess/go/vt/zkctl"
)

var (
	zkCfg = flag.String("zk.cfg", "6@<hostname>:3801:3802:3803",
		"zkid@server1:leaderPort1:electionPort1:clientPort1,...)")
	myID = flag.Uint("zk.myid", 0,
		"which server do you want to be? only needed when running multiple instance on one box, otherwise myid is implied by hostname")
)

func main() {
	defer exit.Recover()
	defer logutil.Flush()

	flag.Parse()

	zkConfig := zkctl.MakeZkConfigFromString(*zkCfg, uint32(*myID))
	zkd := zkctl.NewZkd(zkConfig)

	if zkd.Inited() {
		log.Infof("already initialized, starting without init...")
		if err := zkd.Start(); err != nil {
			log.Errorf("failed start: %v", err)
			exit.Return(255)
		}
	} else {
		log.Infof("initializing...")
		if err := zkd.Init(); err != nil {
			log.Errorf("failed init: %v", err)
			exit.Return(255)
		}
	}

	log.Infof("waiting for signal or server shutdown...")
	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	select {
	case <-zkd.Done():
		log.Infof("server shut down on its own")
	case <-sig:
		log.Infof("signal received, shutting down server")
		zkd.Shutdown()
	}
}


text:
[![Cookbook Version](https://img.shields.io/cookbook/v/jenkins-server.svg)](https://supermarket.chef.io/cookbooks/jenkins-server) [![Code Climate](https://codeclimate.com/github/pietervogelaar/chef-cookbook-jenkins-server/badges/gpa.svg)](https://codeclimate.com/github/pietervogelaar/chef-cookbook-jenkins-server)

This cookbook installs a complete Jenkins server with plugins and is highly configurable with attributes in this cookbook. It configures settings, plugins, security, slaves and depends on the [Jenkins](https://supermarket.chef.io/cookbooks/jenkins) cookbook that is used as foundation. It also installs (can be disabled) the Jenkins plugins, php-template job and required PHP tools as described on [jenkins-php.org](http://jenkins-php.org).

## Supported Platforms

- CentOS >= 6.6
- RHEL >= 6.6
- Ubuntu >= 12.04
- Debian >= 7.0

These platforms are officially supported, but it will probably also work on other platforms.

## Attributes

### General

* `default['jenkins-server']['admin']['username']` - Sets the username for the administrator user. Default "admin"
* `default['jenkins-server']['admin']['password']` - Sets the password for the administrator user. Default "admin". Only used if the security strategy is "generate"
* `default['jenkins-server']['security']['strategy']` - Sets the security strategy. "generate" (default) or "chef-vault"
* `default['jenkins-server']['security']['chef-vault']['data_bag']` - Name of the data bag for jenkins users
* `default['jenkins-server']['security']['chef-vault']['data_bag_item']` - ID of the data bag to use as administrator user. This data bag must contain a password, private_key and public_key property
* `default['jenkins-server']['security']['notifies']['resource']` - Sets the resource that must be executed after admin user creation. By default "jenkins_script[configure permissions]", but use "jenkins_script[configure crowd permissions]" for Jenkins authentication with a JIRA account.

### Nginx

* `default['jenkins-server']['nginx']['install']` - Default `true`. Jenkins is proxied behind Nginx. If you want to disable this, set this attribute to `false` and `default['jenkins']['master']['listen_address']` to `0.0.0.0`. Jenkins will then be reachable on port 8080.
* `default['jenkins-server']['nginx']['server_name']` - Server name / hostname. Default "jenkins-server001.local"
* `default['jenkins-server']['nginx']['server_default']` - If the Jenkins server block must be the default/catch all. Default `true`
* `default['jenkins-server']['nginx']['template_cookbook']` - The cookbook for the Nginx server template. Default "jenkins-server"
* `default['jenkins-server']['nginx']['template_source']` - The source for the Nginx server template. Default "nginx/jenkins.conf.erb"
* `default['jenkins-server']['nginx']['ssl']` - If a SSL connection must be used and forced. Default `false`
* `default['jenkins-server']['nginx']['ssl_cert_path']` - Path to the SSL certificate. Default `nil`
* `default['jenkins-server']['nginx']['ssl_key_path']` - Path to the SSL private key. Default `nil`

### Packages

* `default['jenkins-server']['java']['install']` - Installs Java with the [Java cookbook](https://supermarket.chef.io/cookbooks/java)
* `default['jenkins-server']['ant']['install']` - Installs Ant with the [Ant cookbook](https://supermarket.chef.io/cookbooks/ant)
* `default['jenkins-server']['git']['install']` - Installs Git with the [Git cookbook](https://supermarket.chef.io/cookbooks/git)
* `default['jenkins-server']['composer']['install']` - Installs Composer with the [Composer cookbook](https://supermarket.chef.io/cookbooks/composer). If `true`, the composer_vendors recipe will install the required [Jenkins-php.org](http://jenkins-php.org) vendors "squizlabs/php_codesniffer", "phploc/phploc", "pdepend/pdepend", "phpmd/phpmd", "sebastian/phpcpd" and "theseer/phpdox"
* `default['jenkins-server']['composer']['template_cookbook']` - Template cookbook for composer.json. Default "jenkins-server"
* `default['jenkins-server']['composer']['template_source']` - Template source for composer.json. Default "composer/composer.json.erb"

### Settings

* `default['jenkins-server']['settings']['executors']` - Number of executors. Default the number of cores with a minimum of 2
* `default['jenkins-server']['settings']['slave_agent_port']` - Port number, or 0 to indicate random available TCP port (default) or -1 to disable this service
* `default['jenkins-server']['settings']['system_email']` - System email address
* `default['jenkins-server']['settings']['mailer']['smtp_host']` - Mailer SMTP host. Default "localhost"
* `default['jenkins-server']['settings']['mailer']['username']` - Mailer username. Default "mailer"
* `default['jenkins-server']['settings']['mailer']['password']` - Mailer password. Default "mailer"
* `default['jenkins-server']['settings']['mailer']['use_ssl']` - If the mailer must use SSL. Default `true`
* `default['jenkins-server']['settings']['mailer']['smtp_port']` - SMTP port. Default "25"
* `default['jenkins-server']['settings']['mailer']['reply_to_address']` - Reply to address. Default `node['jenkins-server']['settings']['system_email']`
* `default['jenkins-server']['settings']['mailer']['charset']` - Mail charset. Default "UTF-8"

### Node monitors

Preventive node monitoring, configures the page http://your-jenkins-host/computer/configure.

* `default['jenkins-server']['node_monitors']['architecture_monitor']['ignored']` - This monitor just shows the architecture of the slave for your information. It never marks the slave offline. Default `false`
* `default['jenkins-server']['node_monitors']['clock_monitor']['ignored']` - This monitors the clock difference between the master and nodes. Default `false`
* `default['jenkins-server']['node_monitors']['disk_space_monitor']['ignored']` - This monitors the available disk space of $JENKINS_HOME on each slave, and if it gets below a threshold, the slave will be marked offline. Default `false`
* `default['jenkins-server']['node_monitors']['disk_space_monitor']['free_space_threshold']` - If a slave is found to have less free disk space than this amount, it will be marked offline. Default "1GB"
* `default['jenkins-server']['node_monitors']['swap_space_monitor']['ignored']` - This monitors the available virtual memory space of the computer (commonly known as "swap space"), and if it goes below a threshold, the slave is marked offline. Default `false`
* `default['jenkins-server']['node_monitors']['temporary_space_monitor']['ignored']` - This monitors the available disk space of the temporary directory, and if it gets below a certain threshold the node will be made offline. Default `false`
* `default['jenkins-server']['node_monitors']['temporary_space_monitor']['free_space_threshold']` - If a slave is found to have less free disk space than this amount, it will be marked offline. Default "1GB"
* `default['jenkins-server']['node_monitors']['response_time_monitor']['ignored']` - This monitors the round trip network response time from the master to the slave, and if it goes above a threshold repeatedly, it marks the slave offline. Default `false`

### Plugins

These plugins are configured by default. See the attributes/default.rb for more details. Read for how to add a plugin the section "Adding plugins" further on.

- **General:** greenballs, locale, antisamy-markup-formatter, gravatar, ws-cleanup, ansicolor, build-monitor-plugin, git and ant
- **Version control:** bitbucket, bitbucket-pullrequest-builder
- **[Jenkins-php.org](http://jenkins-php.org):** checkstyle, cloverphp, crap4j, dry, htmlpublisher, jdepend, plot, pmd, violations, warnings and xunit

### Jobs

Jenkins jobs can be specified with attributes like:

    default['jenkins-server']['jobs']['myjob'] = {
      'cookbook' => 'mycookbook',
      'source' => 'jobs/myjob.xml.erb'
    }

By default the "php-template" job is installed from [Jenkins-php.org](http://jenkins-php.org).

### Views

Jenkins views can be specified with attributes like:

    default['jenkins-server']['views']['myview'] = {
      'class' => 'com.smartcodeltd.jenkinsci.plugins.buildmonitor.BuildMonitorView', # A ListView is default if no class is defined
      'include_regex' => '.*',
      'description' => 'My view'
    }

* `default['jenkins-server']['views']` - A hash that contains views
* `default['jenkins-server']['purge_views']` - If views must be purged. Default `true`

### Slaves

* `default['jenkins-server']['slaves']['enable']` - If slaves must be enabled. Default `false`
* `default['jenkins-server']['slaves']['credential']['username']` - The Jenkins master will login as this user on slaves. Default "deployer"
* `default['jenkins-server']['slaves']['credential']['description']` - Description. Default "Deployer"
* `default['jenkins-server']['slaves']['search_key']` - Attribute that contains slave settings on a slave node. Default "jenkins-server-slave"
* `default['jenkins-server']['slaves']['search_query']` - The search query for finding slaves. Default `jenkins-server-slave:* AND chef_environment:#{node.chef_environment} AND NOT fqdn:#{node['fqdn']}`

Include or copy the **jenkins_slave** recipe to a cookbook that is in the run list of each server that you want to be a Jenkins slave.

### Dev mode

If you are developing/testing your (wrapper) cookbook locally, chef-vault communication will be very difficult. If you set an attribute `default['dev_mode']` to `true` then these attributes
will be used to setup Jenkins security.

* `default['jenkins-server']['dev_mode']['security']['password']` - This password is used for the GUI login. Default "admin"
* `default['jenkins-server']['dev_mode']['security']['public_key']` - This public key (paired with the private key) is used for Jenkins CLI authentication
* `default['jenkins-server']['dev_mode']['security']['private_key']` - This private key (paired with the public key) is used for Jenkins CLI authentication

### Jenkins

Some attributes that overwrite the [Jenkins cookbook](https://supermarket.chef.io/cookbooks/jenkins) attributes:

* `default['jenkins']['master']['version']` - Jenkins version. Default 1.642-1.1
* `default['jenkins']['master']['jvm_options']` - JVM options. Default "-Xms256m -Xmx256m" which sets the memory usage to 256 MB
* `default['jenkins']['master']['listen_address']` - Listen address. Default "127.0.0.1". So the Jenkins application is only reachable from localhost or through Nginx.

### Java

Some attributes that overwrite the [Java cookbook](https://supermarket.chef.io/cookbooks/java) attributes:

* `default['java']['jdk_version']` - Version. Default 7

## Adding plugins

You can add plugins to the `default['jenkins-server']['plugins']` array.

Add a Jenkins plugin "myplugin" like below. You can specify a version. If you want to configure it, set configure to `true`
and specify a cookbook and recipe. Use the `jenkins_script` resource to configure your plugin with a groovy script.
Take a look at the plugin recipes in this cookbook for examples.

    default['jenkins-server']['plugins']['myplugin'] = {
      'version' => '1.0',
      'configure' => true,
      'cookbook' => 'mycookbook',
      'recipe' => 'myrecipe_plugin_example'
    }

Plugins can be configured with groovy scripts. Test them at your Jenkins instance:
`http://<host>:8080/script`

With the [doInspector method from javaworld.com](http://www.javaworld.com/article/2073679/detecting-class-innards-in-groovy.html)
you can figure out the properties and methods of your plugin. The Jenkins core API documentation
can be found at [http://javadoc.jenkins-ci.org](http://javadoc.jenkins-ci.org).

    def doInspector(obj) {
      def inspector = new groovy.inspect.Inspector(obj)
      def inspectorReport = new StringBuilder()
      inspectorReport << "Object under inspection "
      inspectorReport << (inspector.isGroovy() ? "IS" : "is NOT") << " Groovy!\n"
      inspectorReport << "METHODS\n"
      def methods = inspector.methods
      methods.each {
        inspectorReport << "\t" << it.toString() << "\n"
      }
      inspectorReport << "\nMETA METHODS\n"
      def metaMethods = inspector.metaMethods
      metaMethods.each {
        inspectorReport << "\t" << it.toString() << "\n"
      }
      inspectorReport << "\nPROPERTY INFO\n"
      def properties = inspector.propertyInfo
      properties.each {
        inspectorReport << "\t" << it.toString() << "\n"
      }
      println inspectorReport
    }

## Usage

### jenkins-server::default

Include `jenkins-server` in your node's `run_list`:

    json
    {
      "run_list": [
        "recipe[jenkins-server::default]"
      ]
    }

The default recipe includes the following recipies:

    if node['jenkins-server']['java']['install']
      include_recipe 'java'
    end

    if node['jenkins-server']['ant']['install']
      include_recipe 'ant'
    end

    if node['jenkins-server']['git']['install']
      include_recipe 'git'
    end

    if node['jenkins-server']['nginx']['install']
      include_recipe 'jenkins-server::nginx'
    end

    include_recipe 'jenkins-server::master'
    include_recipe 'jenkins-server::settings'
    include_recipe 'jenkins-server::plugins'
    include_recipe 'jenkins-server::security'
    include_recipe 'jenkins-server::views'
    include_recipe 'jenkins-server::jobs'
    include_recipe 'jenkins-server::composer'

    if node['jenkins-server']['slaves']['enable']
      include_recipe 'jenkins-server::slaves_credentials'
      include_recipe 'jenkins-server::slaves'
    end

### jenkins-server::ssh_identity

If SSH connections are made to other servers during a job, then Jenkins uses by default the private key in
`#{default['jenkins']['master']['home']}/.ssh/id_rsa`. A private/public key pair can be generated with this recipe.

## License

The MIT License (MIT)

## Authors

Author:: Pieter Vogelaar (pieter@pietervogelaar.nl) - Freelancer