text:
namespace {

const float kConfidenceCutoff[] = {
  0.8f,
  0.5f
};

static_assert(std::size(kConfidenceCutoff) ==
                  predictors::AutocompleteActionPredictor::LAST_PREDICT_ACTION,
              "kConfidenceCutoff count should match LAST_PREDICT_ACTION");

const int kMinimumNumberOfHits = 3;
const size_t kMaximumTransitionalMatchesSize = 1024 * 1024;  // 1 MB.

// As of February 2019, 99% of users on Windows have less than 2000 entries in
// the database.
const size_t kMaximumCacheSize = 2000;

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class DatabaseAction {
  kAdd = 0,
  kUpdate = 1,
  kDeleteSome = 2,
  kDeleteAll = 3,
  kMaxValue = kDeleteAll,
};

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class PredictionStatus {
  // The no state prefetch was not started at all for this omnibox interaction.
  kNotStarted = 0,
  // The no state prefetch was cancelled because the user did not select a URL
  // in the omnibox.
  kCancelled = 1,
  // The no state prefetch was unused because the user navigated to a different
  // URL.
  kUnused = 2,
  // The no state prefetch was used and had time to finish before the user
  // selected a URL.
  kHitFinished = 3,
  // The no state prefetch was used but had not completed before the user
  // selected a URL.
  kHitUnfinished = 4,
  kMaxValue = kHitUnfinished,
};

}  // namespace

namespace predictors {

const int AutocompleteActionPredictor::kMaximumDaysToKeepEntry = 14;
const size_t AutocompleteActionPredictor::kMinimumUserTextLength = 1;
const size_t AutocompleteActionPredictor::kMaximumStringLength = 1024;

AutocompleteActionPredictor::AutocompleteActionPredictor(Profile* profile)
    : profile_(profile),
      main_profile_predictor_(nullptr),
      incognito_predictor_(nullptr),
      initialized_(false) {
  if (profile_->IsOffTheRecord()) {
    main_profile_predictor_ = AutocompleteActionPredictorFactory::GetForProfile(
        profile_->GetOriginalProfile());
    DCHECK(main_profile_predictor_);
    main_profile_predictor_->incognito_predictor_ = this;
    if (main_profile_predictor_->initialized_)
      CopyFromMainProfile();
  } else {
    // Request the in-memory database from the history to force it to load so
    // it's available as soon as possible.
    history::HistoryService* history_service =
        HistoryServiceFactory::GetForProfile(
            profile_, ServiceAccessType::EXPLICIT_ACCESS);
    if (history_service)
      history_service->InMemoryDatabase();

    table_ =
        PredictorDatabaseFactory::GetForProfile(profile_)->autocomplete_table();

    // Create local caches using the database as loaded. We will garbage collect
    // rows from the caches and the database once the history service is
    // available.
    auto rows =
        std::make_unique<std::vector<AutocompleteActionPredictorTable::Row>>();
    auto* rows_ptr = rows.get();
    table_->GetTaskRunner()->PostTaskAndReply(
        FROM_HERE,
        base::BindOnce(&AutocompleteActionPredictorTable::GetAllRows, table_,
                       rows_ptr),
        base::BindOnce(&AutocompleteActionPredictor::CreateCaches, AsWeakPtr(),
                       std::move(rows)));
  }
}

AutocompleteActionPredictor::~AutocompleteActionPredictor() {
  if (main_profile_predictor_)
    main_profile_predictor_->incognito_predictor_ = nullptr;
  else if (incognito_predictor_)
    incognito_predictor_->main_profile_predictor_ = nullptr;
  if (no_state_prefetch_handle_.get())
    no_state_prefetch_handle_->OnCancel();
}

void AutocompleteActionPredictor::RegisterTransitionalMatches(
    const std::u16string& user_text,
    const AutocompleteResult& result) {
  if (user_text.length() < kMinimumUserTextLength ||
      user_text.length() > kMaximumStringLength) {
    return;
  }
  const std::u16string lower_user_text(base::i18n::ToLower(user_text));

  // Merge this in to an existing match if we already saw |user_text|
  auto match_it = std::find(transitional_matches_.begin(),
                            transitional_matches_.end(), lower_user_text);

  if (match_it == transitional_matches_.end()) {
    if (transitional_matches_size_ + lower_user_text.length() >
        kMaximumTransitionalMatchesSize) {
      return;
    }
    transitional_matches_.emplace_back(lower_user_text);
    transitional_matches_size_ += lower_user_text.length();
    match_it = transitional_matches_.end() - 1;
  }

  for (const auto& match : result) {
    const GURL& url = match.destination_url;
    const size_t size = url.spec().size();
    if (!base::Contains(match_it->urls, url) && size <= kMaximumStringLength &&
        transitional_matches_size_ + size <= kMaximumTransitionalMatchesSize) {
      match_it->urls.push_back(url);
      transitional_matches_size_ += size;
    }
  }
}

void AutocompleteActionPredictor::ClearTransitionalMatches() {
  transitional_matches_.clear();
  transitional_matches_size_ = 0;
}

void AutocompleteActionPredictor::CancelPrerender() {
  // If the prefetch has already been abandoned, leave it to its own timeout;
  // this normally gets called immediately after OnOmniboxOpenedUrl.
  if (no_state_prefetch_handle_ && !no_state_prefetch_handle_->IsAbandoned()) {
    no_state_prefetch_handle_->OnCancel();
    no_state_prefetch_handle_.reset();
  }
}

void AutocompleteActionPredictor::StartPrerendering(
    const GURL& url,
    content::WebContents& web_contents,
    const gfx::Size& size) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (prerender_utils::IsDirectUrlInputPrerenderEnabled()) {
    // Check whether preloading is enabled. If users disable this
    // setting, it means users do not want to preload pages.
    // TODO(https://crbug.com/1292422): Move this check into
    // content::PrerenderHostRegistry::CreateAndStartHost().
    content::WebContentsDelegate* web_contents_delegate =
        web_contents.GetDelegate();
    if (!web_contents_delegate ||
        !web_contents_delegate->IsPrerender2Supported(web_contents)) {
      return;
    }

    // TODO(https://crbug.com/1166085): Reset the handle upon prerendering
    // activation/cancellation. There is a case that a user input the same url
    // after activation/cancellation, and this mechanism prevents the user from
    // starting a new prerendering.
    PrerenderManager::CreateForWebContents(&web_contents);
    auto* prerender_manager = PrerenderManager::FromWebContents(&web_contents);
    direct_url_input_prerender_handle_ =
        prerender_manager->StartPrerenderDirectUrlInput(url);
  } else if (base::FeatureList::IsEnabled(
                 features::kOmniboxTriggerForNoStatePrefetch)) {
    content::SessionStorageNamespace* session_storage_namespace =
        web_contents.GetController().GetDefaultSessionStorageNamespace();
    if (no_state_prefetch_handle_) {
      if (no_state_prefetch_handle_->prerender_url() == url) {
        // We've already started a prefetch for the target URL. Nothing to do.
        return;
      }
      // `url` does not match with previously prefetched url. Reset the
      // handle to trigger cancellation.
      base::UmaHistogramEnumeration(
          "AutocompleteActionPredictor.NoStatePrefetchStatus",
          PredictionStatus::kCancelled);
      no_state_prefetch_handle_->OnCancel();
      no_state_prefetch_handle_.reset();
    }
    prerender::NoStatePrefetchManager* no_state_prefetch_manager =
        prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(
            profile_);
    if (no_state_prefetch_manager) {
      no_state_prefetch_handle_ =
          no_state_prefetch_manager->StartPrefetchingFromOmnibox(
              url, session_storage_namespace, size);
    }
  }
}

AutocompleteActionPredictor::Action
AutocompleteActionPredictor::RecommendAction(
    const std::u16string& user_text,
    const AutocompleteMatch& match) const {
  bool is_in_db = false;
  const double confidence = CalculateConfidence(user_text, match, &is_in_db);
  DCHECK(confidence >= 0.0 && confidence <= 1.0);

  base::UmaHistogramBoolean("AutocompleteActionPredictor.MatchIsInDb",
                            is_in_db);

  if (is_in_db) {
    base::UmaHistogramCounts100("AutocompleteActionPredictor.Confidence",
                                confidence * 100);
  }

  // Map the confidence to an action.
  Action action = ACTION_NONE;
  for (int i = 0; i < LAST_PREDICT_ACTION; ++i) {
    if (confidence >= kConfidenceCutoff[i]) {
      action = static_cast<Action>(i);
      break;
    }
  }

  // Downgrade prefetch to preconnect if this is a search match.
  if (action == ACTION_PRERENDER && AutocompleteMatch::IsSearchType(match.type))
    action = ACTION_PRECONNECT;

  return action;
}

// static
bool AutocompleteActionPredictor::IsPreconnectable(
    const AutocompleteMatch& match) {
  return AutocompleteMatch::IsSearchType(match.type);
}

void AutocompleteActionPredictor::OnOmniboxOpenedUrl(const OmniboxLog& log) {
  if (!initialized_)
    return;

  // TODO(dominich): The body of this method doesn't need to be run
  // synchronously. Investigate posting it as a task to be run later.

  if (log.text.length() < kMinimumUserTextLength ||
      log.text.length() > kMaximumStringLength) {
    return;
  }

  // Do not attempt to learn from omnibox interactions where the omnibox
  // dropdown is closed.  In these cases the user text (|log.text|) that we
  // learn from is either empty or effectively identical to the destination
  // string.  In either case, it can't teach us much.  Also do not attempt
  // to learn from paste-and-go actions even if the popup is open because
  // the paste-and-go destination has no relation to whatever text the user
  // may have typed.
  if (!log.is_popup_open || log.is_paste_and_go)
    return;

  const AutocompleteMatch& match = log.result.match_at(log.selected_index);
  const GURL& opened_url = match.destination_url;

  // Abandon the current prefetch. If it is to be used, it will be used very
  // soon, so use the lower timeout.
  if (no_state_prefetch_handle_) {
    if (no_state_prefetch_handle_->prerender_url() == opened_url) {
      if (no_state_prefetch_handle_->IsFinishedLoading()
          // If the handle doesn't have its contents anymore we don't know if it
          // complete successfully or not, but we know it's no longer active, so
          // we log this as kHitFinished.
          || !no_state_prefetch_handle_->contents()) {
        base::UmaHistogramEnumeration(
            "AutocompleteActionPredictor.NoStatePrefetchStatus",
            PredictionStatus::kHitFinished);
      } else {
        base::UmaHistogramEnumeration(
            "AutocompleteActionPredictor.NoStatePrefetchStatus",
            PredictionStatus::kHitUnfinished);
      }
    } else {
      base::UmaHistogramEnumeration(
          "AutocompleteActionPredictor.NoStatePrefetchStatus",
          PredictionStatus::kUnused);
    }
    no_state_prefetch_handle_->OnNavigateAway();
    // Don't release |no_state_prefetch_handle_| so it is canceled if it
    // survives to the next StartPrerendering call.
  } else {
    base::UmaHistogramEnumeration(
        "AutocompleteActionPredictor.NoStatePrefetchStatus",
        PredictionStatus::kNotStarted);
  }

  // Record the value if prerender for direct url input was not started. Other
  // values (kHitFinished, kUnused, kCancelled) are recorded in
  // PrerenderManager.
  if (!direct_url_input_prerender_handle_) {
    base::UmaHistogramEnumeration(
        internal::kHistogramPrerenderPredictionStatusDirectUrlInput,
        PrerenderPredictionStatus::kNotStarted);
  }

  UpdateDatabaseFromTransitionalMatches(opened_url);
}

void AutocompleteActionPredictor::UpdateDatabaseFromTransitionalMatches(
    const GURL& opened_url) {
  std::vector<AutocompleteActionPredictorTable::Row> rows_to_add;
  std::vector<AutocompleteActionPredictorTable::Row> rows_to_update;
  for (const TransitionalMatch& transitional_match : transitional_matches_) {
    DCHECK_GE(transitional_match.user_text.length(), kMinimumUserTextLength);
    DCHECK_LE(transitional_match.user_text.length(), kMaximumStringLength);
    // Add entries to the database for those matches.
    for (const GURL& url : transitional_match.urls) {
      DCHECK_LE(url.spec().length(), kMaximumStringLength);

      const DBCacheKey key = {transitional_match.user_text, url};
      const bool is_hit = !opened_url.is_empty() && (url == opened_url);

      AutocompleteActionPredictorTable::Row row;
      row.user_text = key.user_text;
      row.url = key.url;

      auto it = db_cache_.find(key);
      if (it == db_cache_.end()) {
        row.id = base::GenerateGUID();
        row.number_of_hits = is_hit ? 1 : 0;
        row.number_of_misses = is_hit ? 0 : 1;

        rows_to_add.push_back(row);
      } else {
        DCHECK(db_id_cache_.find(key) != db_id_cache_.end());
        row.id = db_id_cache_.find(key)->second;
        row.number_of_hits = it->second.number_of_hits + (is_hit ? 1 : 0);
        row.number_of_misses = it->second.number_of_misses + (is_hit ? 0 : 1);

        rows_to_update.push_back(row);
      }
    }
  }
  if (!rows_to_add.empty() || !rows_to_update.empty())
    AddAndUpdateRows(rows_to_add, rows_to_update);

  std::vector<AutocompleteActionPredictorTable::Row::Id> ids_to_delete;
  if (db_cache_.size() > kMaximumCacheSize) {
    DeleteLowestConfidenceRowsFromCaches(db_cache_.size() - kMaximumCacheSize,
                                         &ids_to_delete);
  }

  if (!ids_to_delete.empty() && table_.get()) {
    table_->GetTaskRunner()->PostTask(
        FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows,
                                  table_, std::move(ids_to_delete)));
  }

  ClearTransitionalMatches();
}

void AutocompleteActionPredictor::DeleteAllRows() {
  DCHECK(initialized_);

  db_cache_.clear();
  db_id_cache_.clear();

  if (table_.get()) {
    table_->GetTaskRunner()->PostTask(
        FROM_HERE,
        base::BindOnce(&AutocompleteActionPredictorTable::DeleteAllRows,
                       table_));
  }

  base::UmaHistogramEnumeration("AutocompleteActionPredictor.DatabaseAction",
                                DatabaseAction::kDeleteAll);
}

void AutocompleteActionPredictor::DeleteRowsFromCaches(
    const history::URLRows& rows,
    std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) {
  DCHECK(initialized_);
  DCHECK(id_list);

  for (auto it = db_cache_.begin(); it != db_cache_.end();) {
    if (std::find_if(rows.begin(), rows.end(),
                     history::URLRow::URLRowHasURL(it->first.url)) !=
        rows.end()) {
      const DBIdCacheMap::iterator id_it = db_id_cache_.find(it->first);
      DCHECK(id_it != db_id_cache_.end());
      id_list->push_back(id_it->second);
      db_id_cache_.erase(id_it);
      db_cache_.erase(it++);
    } else {
      ++it;
    }
  }
}

void AutocompleteActionPredictor::AddAndUpdateRows(
    const AutocompleteActionPredictorTable::Rows& rows_to_add,
    const AutocompleteActionPredictorTable::Rows& rows_to_update) {
  if (!initialized_)
    return;

  for (auto it = rows_to_add.begin(); it != rows_to_add.end(); ++it) {
    const DBCacheKey key = { it->user_text, it->url };
    DBCacheValue value = { it->number_of_hits, it->number_of_misses };

    DCHECK(db_cache_.find(key) == db_cache_.end());

    db_cache_[key] = value;
    db_id_cache_[key] = it->id;
    base::UmaHistogramEnumeration("AutocompleteActionPredictor.DatabaseAction",
                                  DatabaseAction::kAdd);
  }
  for (auto it = rows_to_update.begin(); it != rows_to_update.end(); ++it) {
    const DBCacheKey key = { it->user_text, it->url };

    auto db_it = db_cache_.find(key);
    DCHECK(db_it != db_cache_.end());
    DCHECK(db_id_cache_.find(key) != db_id_cache_.end());

    db_it->second.number_of_hits = it->number_of_hits;
    db_it->second.number_of_misses = it->number_of_misses;
    base::UmaHistogramEnumeration("AutocompleteActionPredictor.DatabaseAction",
                                  DatabaseAction::kUpdate);
  }

  if (table_.get()) {
    table_->GetTaskRunner()->PostTask(
        FROM_HERE,
        base::BindOnce(&AutocompleteActionPredictorTable::AddAndUpdateRows,
                       table_, rows_to_add, rows_to_update));
  }
}

void AutocompleteActionPredictor::CreateCaches(
    std::unique_ptr<std::vector<AutocompleteActionPredictorTable::Row>> rows) {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!profile_->IsOffTheRecord());
  DCHECK(!initialized_);
  DCHECK(db_cache_.empty());
  DCHECK(db_id_cache_.empty());

  for (std::vector<AutocompleteActionPredictorTable::Row>::const_iterator it =
       rows->begin(); it != rows->end(); ++it) {
    const DBCacheKey key = { it->user_text, it->url };
    const DBCacheValue value = { it->number_of_hits, it->number_of_misses };
    db_cache_[key] = value;
    db_id_cache_[key] = it->id;
  }

  // If the history service is ready, delete any old or invalid entries.
  history::HistoryService* history_service =
      HistoryServiceFactory::GetForProfile(profile_,
                                           ServiceAccessType::EXPLICIT_ACCESS);
  if (history_service) {
    TryDeleteOldEntries(history_service);
    history_service_observation_.Observe(history_service);
  }
}

void AutocompleteActionPredictor::TryDeleteOldEntries(
    history::HistoryService* service) {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!profile_->IsOffTheRecord());
  DCHECK(!initialized_);

  if (!service)
    return;

  history::URLDatabase* url_db = service->InMemoryDatabase();
  if (!url_db)
    return;

  DeleteOldEntries(url_db);
}

void AutocompleteActionPredictor::DeleteOldEntries(
    history::URLDatabase* url_db) {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!profile_->IsOffTheRecord());
  DCHECK(!initialized_);
  DCHECK(table_.get());

  std::vector<AutocompleteActionPredictorTable::Row::Id> ids_to_delete;
  DeleteOldIdsFromCaches(url_db, &ids_to_delete);

  if (db_cache_.size() > kMaximumCacheSize) {
    DeleteLowestConfidenceRowsFromCaches(db_cache_.size() - kMaximumCacheSize,
                                         &ids_to_delete);
  }

  if (!ids_to_delete.empty()) {
    table_->GetTaskRunner()->PostTask(
        FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows,
                                  table_, std::move(ids_to_delete)));
  }

  FinishInitialization();
  if (incognito_predictor_)
    incognito_predictor_->CopyFromMainProfile();
}

void AutocompleteActionPredictor::DeleteOldIdsFromCaches(
    history::URLDatabase* url_db,
    std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!profile_->IsOffTheRecord());
  DCHECK(url_db);
  DCHECK(id_list);

  for (auto it = db_cache_.begin(); it != db_cache_.end();) {
    history::URLRow url_row;

    if ((url_db->GetRowForURL(it->first.url, &url_row) == 0) ||
        ((base::Time::Now() - url_row.last_visit()).InDays() >
         kMaximumDaysToKeepEntry)) {
      const DBIdCacheMap::iterator id_it = db_id_cache_.find(it->first);
      DCHECK(id_it != db_id_cache_.end());
      id_list->push_back(id_it->second);
      db_id_cache_.erase(id_it);
      db_cache_.erase(it++);
    } else {
      ++it;
    }
  }
}

void AutocompleteActionPredictor::DeleteLowestConfidenceRowsFromCaches(
    size_t count,
    std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list) {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(id_list);

  auto compare_confidence = [](const DBCacheMap::iterator& lhs,
                               const DBCacheMap::iterator& rhs) {
    const DBCacheValue& lhs_value = lhs->second;
    const DBCacheValue& rhs_value = rhs->second;
    // Compare by confidence scores first. In case of equality, compare by
    // number of hits.
    int lhs_confidence_to_compare =
        lhs_value.number_of_hits *
        (rhs_value.number_of_hits + rhs_value.number_of_misses);
    int rhs_confidence_to_compare =
        rhs_value.number_of_hits *
        (lhs_value.number_of_hits + lhs_value.number_of_misses);
    return std::tie(lhs_confidence_to_compare, lhs_value.number_of_hits) <
           std::tie(rhs_confidence_to_compare, rhs_value.number_of_hits);
  };
  // Use max heap to find |count| smallest elements in |db_cache_|.
  std::priority_queue<DBCacheMap::iterator, std::vector<DBCacheMap::iterator>,
                      decltype(compare_confidence)>
      max_heap(compare_confidence);

  for (auto it = db_cache_.begin(); it != db_cache_.end(); ++it) {
    max_heap.push(it);
    if (max_heap.size() > count)
      max_heap.pop();
  }

  // Only iterators to the erased elements are invalidated, so it's safe to keep
  // using remaining iterators.
  while (!max_heap.empty()) {
    auto entry_to_delete = max_heap.top();
    auto id_it = db_id_cache_.find(entry_to_delete->first);
    DCHECK(id_it != db_id_cache_.end());

    id_list->push_back(id_it->second);
    db_id_cache_.erase(id_it);
    db_cache_.erase(entry_to_delete);
    max_heap.pop();
  }
}

void AutocompleteActionPredictor::CopyFromMainProfile() {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(profile_->IsOffTheRecord());
  DCHECK(!initialized_);
  DCHECK(main_profile_predictor_);
  DCHECK(main_profile_predictor_->initialized_);

  db_cache_ = main_profile_predictor_->db_cache_;
  db_id_cache_ = main_profile_predictor_->db_id_cache_;
  FinishInitialization();
}

void AutocompleteActionPredictor::FinishInitialization() {
  CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  DCHECK(!initialized_);
  initialized_ = true;
  for (Observer& obs : observers_)
    obs.OnInitialized();
}

double AutocompleteActionPredictor::CalculateConfidence(
    const std::u16string& user_text,
    const AutocompleteMatch& match,
    bool* is_in_db) const {
  const DBCacheKey key = { user_text, match.destination_url };

  *is_in_db = false;
  if (user_text.length() < kMinimumUserTextLength)
    return 0.0;

  const DBCacheMap::const_iterator iter = db_cache_.find(key);
  if (iter == db_cache_.end())
    return 0.0;

  *is_in_db = true;
  return CalculateConfidenceForDbEntry(iter);
}

double AutocompleteActionPredictor::CalculateConfidenceForDbEntry(
    DBCacheMap::const_iterator iter) const {
  const DBCacheValue& value = iter->second;
  if (value.number_of_hits < kMinimumNumberOfHits)
    return 0.0;

  const double number_of_hits = static_cast<double>(value.number_of_hits);
  return number_of_hits / (number_of_hits + value.number_of_misses);
}

void AutocompleteActionPredictor::Shutdown() {
  history_service_observation_.Reset();
}

void AutocompleteActionPredictor::OnURLsDeleted(
    history::HistoryService* history_service,
    const history::DeletionInfo& deletion_info) {
  DCHECK(initialized_);

  if (deletion_info.IsAllHistory()) {
    DeleteAllRows();
    return;
  }

  std::vector<AutocompleteActionPredictorTable::Row::Id> id_list;
  DeleteRowsFromCaches(deletion_info.deleted_rows(), &id_list);

  if (!deletion_info.is_from_expiration() && history_service) {
    auto* url_db = history_service->InMemoryDatabase();
    if (url_db)
      DeleteOldIdsFromCaches(url_db, &id_list);
  }

  if (table_.get()) {
    table_->GetTaskRunner()->PostTask(
        FROM_HERE, base::BindOnce(&AutocompleteActionPredictorTable::DeleteRows,
                                  table_, std::move(id_list)));
  }

  base::UmaHistogramEnumeration("AutocompleteActionPredictor.DatabaseAction",
                                DatabaseAction::kDeleteSome);
}

void AutocompleteActionPredictor::OnHistoryServiceLoaded(
    history::HistoryService* history_service) {
  if (!initialized_)
    TryDeleteOldEntries(history_service);
}

void AutocompleteActionPredictor::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void AutocompleteActionPredictor::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

AutocompleteActionPredictor::TransitionalMatch::TransitionalMatch() = default;

AutocompleteActionPredictor::TransitionalMatch::TransitionalMatch(
    const std::u16string in_user_text)
    : user_text(in_user_text) {}

AutocompleteActionPredictor::TransitionalMatch::TransitionalMatch(
    const TransitionalMatch& other) = default;

AutocompleteActionPredictor::TransitionalMatch::~TransitionalMatch() {
}

}  // namespace predictors


text:
#import <Foundation/Foundation.h>
#include <zlib.h>

#import "ccMacros.h"
#import "Support/CGPointExtension.h"
#import "CCTMXXMLParser.h"
#import "CCTMXTiledMap.h"
#import "CCTMXObjectGroup.h"
#import "Support/base64.h"
#import "Support/ZipUtils.h"
#import "Support/CCFileUtils.h"

#pragma mark -
#pragma mark TMXLayerInfo

@implementation CCTMXLayerInfo

@synthesize name = name_, layerSize = layerSize_, tiles = tiles_, visible = visible_, opacity = opacity_, ownTiles = ownTiles_, minGID = minGID_, maxGID = maxGID_, properties = properties_;
@synthesize offset = offset_;
-(id) init
{
	if( (self=[super init])) {
		ownTiles_ = YES;
		minGID_ = 100000;
		maxGID_ = 0;
		self.name = nil;
		tiles_ = NULL;
		offset_ = CGPointZero;
		self.properties = [NSMutableDictionary dictionaryWithCapacity:5];
	}
	return self;
}
- (void) dealloc
{
	CCLOGINFO(@"cocos2d: deallocing %@",self);

	[name_ release];
	[properties_ release];

	if( ownTiles_ && tiles_ ) {
		free( tiles_ );
		tiles_ = NULL;
	}
	[super dealloc];
}

@end

#pragma mark -
#pragma mark TMXTilesetInfo
@implementation CCTMXTilesetInfo

@synthesize name = name_, firstGid = firstGid_, tileSize = tileSize_, spacing = spacing_, margin = margin_, sourceImage = sourceImage_, imageSize = imageSize_;

- (void) dealloc
{
	CCLOGINFO(@"cocos2d: deallocing %@", self);
	[sourceImage_ release];
	[name_ release];
	[super dealloc];
}

-(CGRect) rectForGID:(unsigned int)gid
{
	CGRect rect;
	rect.size = tileSize_;

	gid &= kFlippedMask;
	gid = gid - firstGid_;

	int max_x = (imageSize_.width - margin_*2 + spacing_) / (tileSize_.width + spacing_);
	//	int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing);

	rect.origin.x = (gid % max_x) * (tileSize_.width + spacing_) + margin_;
	rect.origin.y = (gid / max_x) * (tileSize_.height + spacing_) + margin_;

	return rect;
}
@end

#pragma mark -
#pragma mark CCTMXMapInfo

@interface CCTMXMapInfo (Private)
/* initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */
-(void) parseXMLFile:(NSString *)xmlFilename;
/* initalises parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */
- (void) parseXMLString:(NSString *)xmlString;
/* handles the work of parsing for parseXMLFile: and parseXMLString: */
- (NSError*) parseXMLData:(NSData*)data;
@end

@implementation CCTMXMapInfo

@synthesize orientation = orientation_, mapSize = mapSize_, layers = layers_, tilesets = tilesets_, tileSize = tileSize_, filename = filename_, resources = resources_, objectGroups = objectGroups_, properties = properties_;
@synthesize tileProperties = tileProperties_;

+(id) formatWithTMXFile:(NSString*)tmxFile
{
	return [[[self alloc] initWithTMXFile:tmxFile] autorelease];
}

+(id) formatWithXML:(NSString*)tmxString resourcePath:(NSString*)resourcePath
{
	return [[[self alloc] initWithXML:tmxString resourcePath:resourcePath] autorelease];
}

- (void) internalInit:(NSString*)tmxFileName resourcePath:(NSString*)resourcePath
{
	self.tilesets = [NSMutableArray arrayWithCapacity:4];
	self.layers = [NSMutableArray arrayWithCapacity:4];
	self.filename = tmxFileName;
	self.resources = resourcePath;
	self.objectGroups = [NSMutableArray arrayWithCapacity:4];
	self.properties = [NSMutableDictionary dictionaryWithCapacity:5];
	self.tileProperties = [NSMutableDictionary dictionaryWithCapacity:5];

	// tmp vars
	currentString = [[NSMutableString alloc] initWithCapacity:1024];
	storingCharacters = NO;
	layerAttribs = TMXLayerAttribNone;
	parentElement = TMXPropertyNone;
}

-(id) initWithXML:(NSString *)tmxString resourcePath:(NSString*)resourcePath
{
	if( (self=[super init])) {
		[self internalInit:nil resourcePath:resourcePath];
		[self parseXMLString:tmxString];
	}
	return self;
}

-(id) initWithTMXFile:(NSString*)tmxFile
{
	if( (self=[super init])) {
		[self internalInit:tmxFile resourcePath:nil];
		[self parseXMLFile:filename_];
	}
	return self;
}

- (void) dealloc
{
	CCLOGINFO(@"cocos2d: deallocing %@", self);
	[tilesets_ release];
	[layers_ release];
	[filename_ release];
	[resources_ release];
	[currentString release];
	[objectGroups_ release];
	[properties_ release];
	[tileProperties_ release];
	[super dealloc];
}

- (void) parseXMLData:(NSData*)data
{
	NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:data] autorelease];

	// we'll do the parsing
	[parser setDelegate:self];
	[parser setShouldProcessNamespaces:NO];
	[parser setShouldReportNamespacePrefixes:NO];
	[parser setShouldResolveExternalEntities:NO];
	[parser parse];

     NSAssert1( ![parser parserError], @"Error parsing TMX data: %@.", [NSString stringWithCharacters:[data bytes] length:[data length]] );
}

- (void) parseXMLString:(NSString *)xmlString
{
	NSData* data = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
	[self parseXMLData:data];

}

- (void) parseXMLFile:(NSString *)xmlFilename
{
	NSURL *url = [NSURL fileURLWithPath:[CCFileUtils fullPathFromRelativePath:xmlFilename] ];
	NSData *data = [NSData dataWithContentsOfURL:url];
	[self parseXMLData:data];
}

// the XML parser calls here with all the elements
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if([elementName isEqualToString:@"map"]) {
		NSString *version = [attributeDict valueForKey:@"version"];
		if( ! [version isEqualToString:@"1.0"] )
			CCLOG(@"cocos2d: TMXFormat: Unsupported TMX version: %@", version);
		NSString *orientationStr = [attributeDict valueForKey:@"orientation"];
		if( [orientationStr isEqualToString:@"orthogonal"])
			orientation_ = CCTMXOrientationOrtho;
		else if ( [orientationStr isEqualToString:@"isometric"])
			orientation_ = CCTMXOrientationIso;
		else if( [orientationStr isEqualToString:@"hexagonal"])
			orientation_ = CCTMXOrientationHex;
		else
			CCLOG(@"cocos2d: TMXFomat: Unsupported orientation: %@", orientation_);

		mapSize_.width = [[attributeDict valueForKey:@"width"] intValue];
		mapSize_.height = [[attributeDict valueForKey:@"height"] intValue];
		tileSize_.width = [[attributeDict valueForKey:@"tilewidth"] intValue];
		tileSize_.height = [[attributeDict valueForKey:@"tileheight"] intValue];

		// The parent element is now "map"
		parentElement = TMXPropertyMap;
	} else if([elementName isEqualToString:@"tileset"]) {

		// If this is an external tileset then start parsing that
		NSString *externalTilesetFilename = [attributeDict valueForKey:@"source"];
		if (externalTilesetFilename) {
				// Tileset file will be relative to the map file. So we need to convert it to an absolute path
				NSString *dir = [filename_ stringByDeletingLastPathComponent];	// Directory of map file
				if (!dir)
					dir = resources_;
				externalTilesetFilename = [dir stringByAppendingPathComponent:externalTilesetFilename];	// Append path to tileset file

				[self parseXMLFile:externalTilesetFilename];
		} else {

			CCTMXTilesetInfo *tileset = [CCTMXTilesetInfo new];
			tileset.name = [attributeDict valueForKey:@"name"];
			tileset.firstGid = [[attributeDict valueForKey:@"firstgid"] intValue];
			tileset.spacing = [[attributeDict valueForKey:@"spacing"] intValue];
			tileset.margin = [[attributeDict valueForKey:@"margin"] intValue];
			CGSize s;
			s.width = [[attributeDict valueForKey:@"tilewidth"] intValue];
			s.height = [[attributeDict valueForKey:@"tileheight"] intValue];
			tileset.tileSize = s;

			[tilesets_ addObject:tileset];
			[tileset release];
		}

	}else if([elementName isEqualToString:@"tile"]){
		CCTMXTilesetInfo* info = [tilesets_ lastObject];
		NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:3];
		parentGID_ =  [info firstGid] + [[attributeDict valueForKey:@"id"] intValue];
		[tileProperties_ setObject:dict forKey:[NSNumber numberWithInt:parentGID_]];

		parentElement = TMXPropertyTile;

	}else if([elementName isEqualToString:@"layer"]) {
		CCTMXLayerInfo *layer = [CCTMXLayerInfo new];
		layer.name = [attributeDict valueForKey:@"name"];

		CGSize s;
		s.width = [[attributeDict valueForKey:@"width"] intValue];
		s.height = [[attributeDict valueForKey:@"height"] intValue];
		layer.layerSize = s;

		layer.visible = ![[attributeDict valueForKey:@"visible"] isEqualToString:@"0"];

		if( [attributeDict valueForKey:@"opacity"] )
			layer.opacity = 255 * [[attributeDict valueForKey:@"opacity"] floatValue];
		else
			layer.opacity = 255;

		int x = [[attributeDict valueForKey:@"x"] intValue];
		int y = [[attributeDict valueForKey:@"y"] intValue];
		layer.offset = ccp(x,y);

		[layers_ addObject:layer];
		[layer release];

		// The parent element is now "layer"
		parentElement = TMXPropertyLayer;

	} else if([elementName isEqualToString:@"objectgroup"]) {

		CCTMXObjectGroup *objectGroup = [[CCTMXObjectGroup alloc] init];
		objectGroup.groupName = [attributeDict valueForKey:@"name"];
		CGPoint positionOffset;
		positionOffset.x = [[attributeDict valueForKey:@"x"] intValue] * tileSize_.width;
		positionOffset.y = [[attributeDict valueForKey:@"y"] intValue] * tileSize_.height;
		objectGroup.positionOffset = positionOffset;

		[objectGroups_ addObject:objectGroup];
		[objectGroup release];

		// The parent element is now "objectgroup"
		parentElement = TMXPropertyObjectGroup;

	} else if([elementName isEqualToString:@"image"]) {

		CCTMXTilesetInfo *tileset = [tilesets_ lastObject];

		// build full path
		NSString *imagename = [attributeDict valueForKey:@"source"];
		NSString *path = [filename_ stringByDeletingLastPathComponent];
		if (!path)
			path = resources_;
		tileset.sourceImage = [path stringByAppendingPathComponent:imagename];

	} else if([elementName isEqualToString:@"data"]) {
		NSString *encoding = [attributeDict valueForKey:@"encoding"];
		NSString *compression = [attributeDict valueForKey:@"compression"];

		if( [encoding isEqualToString:@"base64"] ) {
			layerAttribs |= TMXLayerAttribBase64;
			storingCharacters = YES;

			if( [compression isEqualToString:@"gzip"] )
				layerAttribs |= TMXLayerAttribGzip;

			else if( [compression isEqualToString:@"zlib"] )
				layerAttribs |= TMXLayerAttribZlib;

			NSAssert( !compression || [compression isEqualToString:@"gzip"] || [compression isEqualToString:@"zlib"], @"TMX: unsupported compression method" );
		}

		NSAssert( layerAttribs != TMXLayerAttribNone, @"TMX tile map: Only base64 and/or gzip/zlib maps are supported" );

	} else if([elementName isEqualToString:@"object"]) {

		CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject];

		// The value for "type" was blank or not a valid class name
		// Create an instance of TMXObjectInfo to store the object and its properties
		NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:5];

		// Set the name of the object to the value for "name"
		[dict setValue:[attributeDict valueForKey:@"name"] forKey:@"name"];

		// Assign all the attributes as key/name pairs in the properties dictionary
		[dict setValue:[attributeDict valueForKey:@"type"] forKey:@"type"];
		int x = [[attributeDict valueForKey:@"x"] intValue] + objectGroup.positionOffset.x;
		[dict setValue:[NSNumber numberWithInt:x] forKey:@"x"];
		int y = [[attributeDict valueForKey:@"y"] intValue] + objectGroup.positionOffset.y;
		// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
		y = (mapSize_.height * tileSize_.height) - y - [[attributeDict valueForKey:@"height"] intValue];
		[dict setValue:[NSNumber numberWithInt:y] forKey:@"y"];
		[dict setValue:[attributeDict valueForKey:@"width"] forKey:@"width"];
		[dict setValue:[attributeDict valueForKey:@"height"] forKey:@"height"];

		// Add the object to the objectGroup
		[[objectGroup objects] addObject:dict];
		[dict release];

		// The parent element is now "object"
		parentElement = TMXPropertyObject;

	} else if([elementName isEqualToString:@"property"]) {

		if ( parentElement == TMXPropertyNone ) {

			CCLOG( @"TMX tile map: Parent element is unsupported. Cannot add property named '%@' with value '%@'",
			[attributeDict valueForKey:@"name"], [attributeDict valueForKey:@"value"] );

		} else if ( parentElement == TMXPropertyMap ) {

			// The parent element is the map
			[properties_ setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]];

		} else if ( parentElement == TMXPropertyLayer ) {

			// The parent element is the last layer
			CCTMXLayerInfo *layer = [layers_ lastObject];
			// Add the property to the layer
			[[layer properties] setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]];

		} else if ( parentElement == TMXPropertyObjectGroup ) {

			// The parent element is the last object group
			CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject];
			[[objectGroup properties] setValue:[attributeDict valueForKey:@"value"] forKey:[attributeDict valueForKey:@"name"]];

		} else if ( parentElement == TMXPropertyObject ) {

			// The parent element is the last object
			CCTMXObjectGroup *objectGroup = [objectGroups_ lastObject];
			NSMutableDictionary *dict = [[objectGroup objects] lastObject];

			NSString *propertyName = [attributeDict valueForKey:@"name"];
			NSString *propertyValue = [attributeDict valueForKey:@"value"];

			[dict setValue:propertyValue forKey:propertyName];
		} else if ( parentElement == TMXPropertyTile ) {

			NSMutableDictionary* dict = [tileProperties_ objectForKey:[NSNumber numberWithInt:parentGID_]];
			NSString *propertyName = [attributeDict valueForKey:@"name"];
			NSString *propertyValue = [attributeDict valueForKey:@"value"];
			[dict setObject:propertyValue forKey:propertyName];

		}
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	int len = 0;

	if([elementName isEqualToString:@"data"] && layerAttribs&TMXLayerAttribBase64) {
		storingCharacters = NO;

		CCTMXLayerInfo *layer = [layers_ lastObject];

		unsigned char *buffer;
		len = base64Decode((unsigned char*)[currentString UTF8String], (unsigned int) [currentString length], &buffer);
		if( ! buffer ) {
			CCLOG(@"cocos2d: TiledMap: decode data error");
			return;
		}

		if( layerAttribs & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) {
			unsigned char *deflated;
			CGSize s = [layer layerSize];
			int sizeHint = s.width * s.height * sizeof(uint32_t);

			int inflatedLen = ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint);
			NSAssert( inflatedLen == sizeHint, @"CCTMXXMLParser: Hint failed!");

			inflatedLen = (int)&inflatedLen; // XXX: to avoid warings in compiler

			free( buffer );

			if( ! deflated ) {
				CCLOG(@"cocos2d: TiledMap: inflate data error");
				return;
			}

			layer.tiles = (unsigned int*) deflated;
		} else
			layer.tiles = (unsigned int*) buffer;

		[currentString setString:@""];

	} else if ([elementName isEqualToString:@"map"]) {
		// The map element has ended
		parentElement = TMXPropertyNone;

	}	else if ([elementName isEqualToString:@"layer"]) {
		// The layer element has ended
		parentElement = TMXPropertyNone;

	} else if ([elementName isEqualToString:@"objectgroup"]) {
		// The objectgroup element has ended
		parentElement = TMXPropertyNone;

	} else if ([elementName isEqualToString:@"object"]) {
		// The object element has ended
		parentElement = TMXPropertyNone;
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (storingCharacters)
		[currentString appendString:string];
}

//
// the level did not load, file not found, etc.
//
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
	CCLOG(@"cocos2d: Error on XML Parse: %@", [parseError localizedDescription] );
}

@end

redpajama_set_name: RedPajamaGithub


text:
package filodb.cassandra.columnstore

import java.nio.ByteBuffer

import scala.concurrent.{ExecutionContext, Future}

import com.datastax.driver.core.{ConsistencyLevel, Row}
import monix.reactive.Observable

import filodb.cassandra.FiloCassandraConnector
import filodb.core._
import filodb.core.store.ChunkSinkStats
import filodb.memory.format.UnsafeUtils

// Typical record read from serialized incremental index (ChunkInfo + Skips) entries
case class IndexRecord(binPartition: ByteBuffer, data: ByteBuffer) {
  def partBaseOffset: (Any, Long, Int) = UnsafeUtils.BOLfromBuffer(binPartition)
}

/**
 * Represents the table which holds the incremental chunk metadata or indexes for each segment
 * of a partition.  The chunk index contains info about each chunk including if it overrides
 * any records in previous chunks.  Each new chunkSet that is written results in a tiny bit more metadata.
 * Unlike the previous ChunkRowMap design, the layout is such that new chunks in a segment get written
 * only with its new metadata, previous index bits are not written again.
 *
 * There is an indextype field.
 *  1 = incremental indices
 * In the future there may be other types.  For example, for aggregated indices or extra metadata
 * representing keys to replace.
 */
sealed class IndexTable(val dataset: DatasetRef, val connector: FiloCassandraConnector)
                       (implicit ec: ExecutionContext) extends BaseDatasetTable {
  import scala.collection.JavaConverters._

  import filodb.cassandra.Util._

  val suffix = "index"

  val createCql = s"""CREATE TABLE IF NOT EXISTS $tableString (
                     |    partition blob,
                     |    indextype int,
                     |    chunkid bigint,
                     |    data blob,
                     |    PRIMARY KEY (partition, indextype, chunkid)
                     |) WITH compression = {
                    'sstable_compression': '$sstableCompression'}""".stripMargin

  def fromRow(row: Row): IndexRecord =
    IndexRecord(row.getBytes("partition"), row.getBytes("data"))

  val selectCql = s"SELECT partition, data FROM $tableString WHERE "
  val partitionFilter = "partition = ? AND indextype = 1"
  val partInFilter = "partition IN ? AND indextype = 1"
  lazy val allPartReadCql = session.prepare(selectCql + partitionFilter)
  lazy val inPartReadCql = session.prepare(selectCql + partInFilter)

  /**
   * Retrieves all indices from a single partition.
   */
  def getIndices(binPartition: Array[Byte]): Observable[IndexRecord] = {
    val it = session.execute(allPartReadCql.bind(toBuffer(binPartition)))
                    .asScala.toIterator.map(fromRow)
    Observable.fromIterator(it).handleObservableErrors
  }

  def getMultiIndices(partitions: Seq[Array[Byte]]): Observable[IndexRecord] = {
    val query = inPartReadCql.bind().setList(0, partitions.map(toBuffer).asJava, classOf[ByteBuffer])
    val it = session.execute(query).asScala.toIterator.map(fromRow)
    Observable.fromIterator(it).handleObservableErrors
  }

  val tokenQ = "TOKEN(partition)"

  def scanIndices(tokens: Seq[(String, String)]): Observable[IndexRecord] = {
    def cql(start: String, end: String): String =
      s"SELECT * FROM $tableString WHERE $tokenQ >= $start AND $tokenQ < $end AND indextype = 1 " +
      s"ALLOW FILTERING"
    val it = tokens.iterator.flatMap { case (start, end) =>
        session.execute(cql(start, end)).iterator.asScala
               .map { row => fromRow(row) }
      }
    Observable.fromIterator(it).handleObservableErrors
  }

  lazy val writeIndexCql = session.prepare(
    s"INSERT INTO $tableString (partition, indextype, chunkid, data) " +
    "VALUES (?, 1, ?, ?) USING TTL ?")
    .setConsistencyLevel(ConsistencyLevel.ONE)

  /**
   * Writes new indices to the index table
   * @return Success, or an exception as a Future.failure
   */
  def writeIndices(partition: Array[Byte],
                   indices: Seq[(Types.ChunkID, Array[Byte])],
                   stats: ChunkSinkStats,
                   diskTimeToLive: Int): Future[Response] = {
    var indexBytes = 0
    val partitionBuf = toBuffer(partition)
    val statements = indices.map { case (chunkId, indexData) =>
      indexBytes += indexData.size
      writeIndexCql.bind(partitionBuf,
                         chunkId: java.lang.Long,
                         ByteBuffer.wrap(indexData),
                         diskTimeToLive: java.lang.Integer)
    }
    stats.addIndexWriteStats(indexBytes)
    connector.execStmtWithRetries(unloggedBatch(statements).setConsistencyLevel(ConsistencyLevel.ONE))
  }
}


text:
package com.thaiopensource.validate.auto;

public interface Rewindable {
  void willNotRewind();
  void rewind();
  boolean canRewind();
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".settings.SettingsFragment"
    >

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    <!--<Button-->
        <!--android:id="@+id/btn_sign_out"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_alignParentBottom="true"-->
        <!--android:background="@drawable/em_btn_rectangle_red"-->
        <!--android:paddingLeft="16dp"-->
        <!--android:text="@string/em_sign_out"-->
        <!--android:textColor="@color/em_white_87"-->
        <!--/>-->
</RelativeLayout>


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;

namespace SchoolBusAPI.Models
{
    public class CCWNotification : AuditableEntity
    {
        public CCWNotification()
        {
            CCWNotificationDetails = new List<CCWNotificationDetail>();
        }

        [MetaDataExtension(Description = "A system-generated unique identifier for a CCW Notification")]
        public int Id { get; set; }

        /// <summary>
        /// CCW change details - original and modified values
        /// </summary>
        /// <value>CCW change details - original and modified values</value>
        [MetaDataExtension(Description = "CCW change details - original and modified values.")]
        public List<CCWNotificationDetail> CCWNotificationDetails { get; set; }

        /// <summary>
        /// True if the user linked to the bus has read the notification
        /// </summary>
        /// <value>True if the user linked to the inspection has read the notification</value>
        [MetaDataExtension(Description = "True if the user linked to the bus has read the notification")]
        public bool HasBeenViewed { get; set; }

        /// <summary>
        /// A foreign key reference to the system-generated unique identifier for a School Bus
        /// </summary>
        /// <value>A foreign key reference to the system-generated unique identifier for a School Bus</value>
        [MetaDataExtension(Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
        public SchoolBus SchoolBus { get; set; }

        /// <summary>
        /// Foreign key for SchoolBus
        /// </summary>
        [ForeignKey("SchoolBus")]
        [JsonIgnore]
        [MetaDataExtension(Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
        public int? SchoolBusId { get; set; }
    }
}


text:
import sublime

from collections import defaultdict
from collections import namedtuple
import json

vi_user_setting = namedtuple('vi_editor_setting', 'scope values default parser action negatable')

WINDOW_SETTINGS = [
    'last_buffer_search',
    '_cmdline_cd',
]

SCOPE_WINDOW = 1
SCOPE_VIEW = 2
SCOPE_VI_VIEW = 3
SCOPE_VI_WINDOW = 4

def volatile(f):
    VintageSettings._volatile_settings.append(f.__name__)
    return f

def destroy(view):
    try:
        del VintageSettings._volatile[view.id()]
    except KeyError:
        pass

def set_generic_view_setting(view, name, value, opt, globally=False):
    if opt.scope == SCOPE_VI_VIEW:
        name = 'vintageous_' + name
    if not opt.parser:
        if not globally or (opt.scope not in (SCOPE_VI_VIEW, SCOPE_VI_WINDOW)):
            view.settings().set(name, value)
        else:
            prefs = sublime.load_settings('Preferences.sublime-settings')
            prefs.set(name, value)
            sublime.save_settings('Preferences.sublime-settings')
        return
    else:
        if not globally or (opt.scope not in (SCOPE_VI_VIEW, SCOPE_VI_WINDOW)):
            view.settings().set(name, opt.parser(value))
        else:
            #name = 'vintageous_' + name
            prefs = sublime.load_settings('Preferences.sublime-settings')
            prefs.set(name, opt.parser(value))
            sublime.save_settings('Preferences.sublime-settings')
        return
    raise ValueError("Vintageous: bad option value")

def set_minimap(view, name, value, opt, globally=False):
    # TODO: Ensure the minimap gets hidden when so desired.
    view.window().run_command('toggle_minimap')

def set_sidebar(view, name, value, opt, globally=False):
    # TODO: Ensure the minimap gets hidden when so desired.
    view.window().run_command('toggle_side_bar')

def opt_bool_parser(value):
    if value.lower() in ('false', 'true', '0', '1', 'yes', 'no'):
        if value.lower() in ('true', '1', 'yes'):
            return True
        return False

def opt_rulers_parser(value):
    try:
        converted = json.loads(value)
        if isinstance(converted, list):
            return converted
        else:
            raise ValueError
    except ValueError:
        raise
    except TypeError:
        raise ValueError

VI_OPTIONS = {
    'autoindent':  vi_user_setting(scope=SCOPE_VI_VIEW,   values=(True, False, '0', '1'), default=True,  parser=None,              action=set_generic_view_setting, negatable=False),
    'hlsearch':    vi_user_setting(scope=SCOPE_VI_VIEW,   values=(True, False, '0', '1'), default=True,  parser=opt_bool_parser,   action=set_generic_view_setting, negatable=True),
    'ignorecase':  vi_user_setting(scope=SCOPE_VI_VIEW,   values=(True, False, '0', '1'), default=False, parser=opt_bool_parser,   action=set_generic_view_setting, negatable=True),
    'incsearch':   vi_user_setting(scope=SCOPE_VI_VIEW,   values=(True, False, '0', '1'), default=True,  parser=opt_bool_parser,   action=set_generic_view_setting, negatable=True),
    'magic':       vi_user_setting(scope=SCOPE_VI_VIEW,   values=(True, False, '0', '1'), default=True,  parser=opt_bool_parser,   action=set_generic_view_setting, negatable=True),
    'visualbell':  vi_user_setting(scope=SCOPE_VI_WINDOW, values=(True, False, '0', '1'), default=True,  parser=opt_bool_parser,   action=set_generic_view_setting, negatable=True),
    'rulers':      vi_user_setting(scope=SCOPE_VIEW,      values=None,                    default=[],    parser=opt_rulers_parser, action=set_generic_view_setting, negatable=False),
    'showminimap': vi_user_setting(scope=SCOPE_WINDOW,    values=(True, False, '0', '1'), default=True,  parser=None,              action=set_minimap,              negatable=True),
    'showsidebar': vi_user_setting(scope=SCOPE_WINDOW,    values=(True, False, '0', '1'), default=True,  parser=None,              action=set_sidebar,              negatable=True),
}

VI_OPTION_SHORTCUTS = {
    'ic': 'ignorecase',
    'noic': 'noignorecase'
}

# For completions.
def iter_settings(prefix=''):
    if prefix.startswith('no'):
        for item in (x for (x, y) in VI_OPTIONS.items() if y.negatable):
            if ('no' + item).startswith(prefix):
                yield 'no' + item
    else:
        for k in sorted(VI_OPTIONS.keys()):
            if (prefix == '') or k.startswith(prefix):
                yield k

def set_local(view, name, value):
    try:
        opt = VI_OPTIONS[name]
        if not value and opt.negatable:
            opt.action(view, name, '1', opt)
            return
        opt.action(view, name, value, opt)
    except KeyError as e:
        if name.startswith('no'):
            try:
                opt = VI_OPTIONS[name[2:]]
                if opt.negatable:
                    opt.action(view, name[2:], '0', opt)
                return
            except KeyError:
                pass
        raise

def set_global(view, name, value):
    try:
        opt = VI_OPTIONS[name]
        if not value and opt.negatable:
            opt.action(view, name, '1', opt, globally=True)
            return
        opt.action(view, name, value, opt, globally=True)
    except KeyError as e:
        if name.startswith('no'):
            try:
                opt = VI_OPTIONS[name[2:]]
                if opt.negatable:
                    opt.action(view, name[2:], '0', opt, globally=True)
                return
            except KeyError:
                pass
        raise

def get_option(view, name):
    # TODO: Should probably return global, local values.
    try:
        option_data = VI_OPTIONS[name]
    except KeyError:
        raise KeyError('not a vi editor option')

    if option_data.scope == SCOPE_WINDOW:
        value = view.window().settings().get('vintageous_' + name)
    else:
        value = view.settings().get('vintageous_' + name)
    return value if (value in option_data.values) else option_data.default

class SublimeSettings(object):
    """ Helper class for accessing settings values from views """

    def __init__(self, view=None):
        self.view = view

    def __get__(self, instance, owner):
        if instance is not None:
            return SublimeSettings(instance.v)
        return SublimeSettings()

    def __getitem__(self, key):
        return self.view.settings().get(key)

    def __setitem__(self, key, value):
        self.view.settings().set(key, value)

class VintageSettings(object):
    """
    Helper class for accessing settings related to Vintage.

    Vintage settings data can be stored in:

      a) the view.Settings object
      b) the window.Settings object
      c) VintageSettings._volatile

    This class knows where to store the settings' data it's passed.

    It is meant to be used as a descriptor.
    """

    _volatile_settings = []
    # Stores volatile settings indexed by view.id().
    _volatile = defaultdict(dict)

    def __init__(self, view=None):
        self.view = view

        if view is not None and not isinstance(self.view.settings().get('vintage'), dict):
            self.view.settings().set('vintage', dict())

        if view is not None and view.window() is not None and not isinstance(self.view.window().settings().get('vintage'), dict):
            self.view.window().settings().set('vintage', dict())

    def __get__(self, instance, owner):
        # This method is called when this class is accessed as a data member.
        if instance is not None:
            return VintageSettings(instance.v)
        return VintageSettings()

    def __getitem__(self, key):
        # Deal with editor options first.
        try:
            return get_option(self.view, key)
        except KeyError:
            pass

        # Deal with state settings.
        try:
            if key not in WINDOW_SETTINGS:
                try:
                    return self._get_volatile(key)
                except KeyError:
                    value = self._get_vintageous_view_setting(key)
            else:
                value = self._get_vintageous_window_setting(key)
        except (KeyError, AttributeError):
            value = None
        return value

    def __setitem__(self, key, value):
        if key not in WINDOW_SETTINGS:
            if key in VintageSettings._volatile_settings:
                self._set_volatile(key, value)
                return
            setts, target = self.view.settings().get('vintage'), self.view
        else:
            setts, target = self.view.window().settings().get('vintage'), self.view.window()

        setts[key] = value
        target.settings().set('vintage', setts)

    def _get_vintageous_view_setting(self, key):
        return self.view.settings().get('vintage').get(key)

    def _get_vintageous_window_setting(self, key):
        return self.view.window().settings().get('vintage').get(key)

    def _get_volatile(self, key):
        try:
            return VintageSettings._volatile[self.view.id()][key]
        except KeyError:
            raise KeyError('error accessing volatile key: %s' % key)

    def _set_volatile(self, key, value):
        try:
            VintageSettings._volatile[self.view.id()][key] = value
        except KeyError:
            raise KeyError('error while setting key "%s" to value "%s"' % (key, value))

class SublimeWindowSettings(object):
    """ Helper class for accessing settings values from views """

    def __init__(self, view=None):
        self.view = view

    def __get__(self, instance, owner):
        if instance is not None:
            return SublimeSettings(instance.v.window())
        return SublimeSettings()

    def __getitem__(self, key):
        return self.view.window().settings().get(key)

    def __setitem__(self, key, value):
        self.view.window().settings().set(key, value)

# TODO: Make this a descriptor; avoid instantiation.
class SettingsManager(object):
    view = SublimeSettings()
    vi = VintageSettings()
    window = SublimeWindowSettings()

    def __init__(self, view):
        self.v = view


text:
package org.elasticsearch.xpack.monitoring;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.license.LicenseService;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.protocol.xpack.XPackUsageRequest;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.LocalStateCompositeXPackPlugin;
import org.elasticsearch.xpack.core.action.TransportXPackUsageAction;
import org.elasticsearch.xpack.core.action.XPackUsageFeatureAction;
import org.elasticsearch.xpack.core.action.XPackUsageResponse;
import org.elasticsearch.xpack.core.ccr.AutoFollowStats;
import org.elasticsearch.xpack.core.ccr.action.CcrStatsAction;
import org.elasticsearch.xpack.core.ccr.action.FollowStatsAction;
import org.elasticsearch.xpack.core.enrich.action.EnrichStatsAction;
import org.elasticsearch.xpack.core.ssl.SSLService;
import org.elasticsearch.xpack.datastreams.DataStreamsPlugin;
import org.elasticsearch.xpack.ilm.IndexLifecycle;
import org.elasticsearch.xpack.watcher.Watcher;

import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

public class LocalStateMonitoring extends LocalStateCompositeXPackPlugin {

    public static class MonitoringTransportXPackUsageAction extends TransportXPackUsageAction {
        @Inject
        public MonitoringTransportXPackUsageAction(ThreadPool threadPool, TransportService transportService,
                                         ClusterService clusterService, ActionFilters actionFilters,
                                         IndexNameExpressionResolver indexNameExpressionResolver, NodeClient client) {
            super(threadPool, transportService, clusterService, actionFilters, indexNameExpressionResolver, client);
        }
        @Override
        protected List<XPackUsageFeatureAction> usageActions() {
            return Collections.singletonList(XPackUsageFeatureAction.MONITORING);
        }
    }

    final Monitoring monitoring;

    public LocalStateMonitoring(final Settings settings, final Path configPath) throws Exception {
        super(settings, configPath);
        LocalStateMonitoring thisVar = this;

        monitoring = new Monitoring(settings) {
            @Override
            protected SSLService getSslService() {
                return thisVar.getSslService();
            }

            @Override
            protected LicenseService getLicenseService() {
                return thisVar.getLicenseService();
            }

            @Override
            protected XPackLicenseState getLicenseState() {
                return thisVar.getLicenseState();
            }
        };
        plugins.add(monitoring);
        plugins.add(new Watcher(settings) {
            @Override
            protected SSLService getSslService() {
                return thisVar.getSslService();
            }

            @Override
            protected XPackLicenseState getLicenseState() {
                return thisVar.getLicenseState();
            }
        });
        plugins.add(new IndexLifecycle(settings));
        plugins.add(new DataStreamsPlugin()); // Otherwise the watcher history index template can't be added
    }

    public Monitoring getMonitoring() {
        return monitoring;
    }

    @Override
    protected Class<? extends TransportAction<XPackUsageRequest, XPackUsageResponse>> getUsageAction() {
        return MonitoringTransportXPackUsageAction.class;
    }

    @Override
    public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
        var actions = super.getActions();
        // ccr StatsCollector
        actions.add(new ActionHandler<>(CcrStatsAction.INSTANCE, TransportCcrStatsStubAction.class));
        // For EnrichStatsCollector:
        actions.add(new ActionHandler<>(EnrichStatsAction.INSTANCE, TransportEnrichStatsStubAction.class));
        return actions;
    }

    public static class TransportCcrStatsStubAction extends HandledTransportAction<CcrStatsAction.Request, CcrStatsAction.Response> {

        @Inject
        public TransportCcrStatsStubAction(TransportService transportService, ActionFilters actionFilters) {
            super(CcrStatsAction.NAME, transportService, actionFilters, CcrStatsAction.Request::new);
        }

        @Override
        protected void doExecute(Task task, CcrStatsAction.Request request, ActionListener<CcrStatsAction.Response> listener) {
            AutoFollowStats autoFollowStats =
                new AutoFollowStats(0, 0, 0, Collections.emptyNavigableMap(), Collections.emptyNavigableMap());
            FollowStatsAction.StatsResponses statsResponses =
                new FollowStatsAction.StatsResponses(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
            listener.onResponse(new CcrStatsAction.Response(autoFollowStats, statsResponses));
        }
    }

    public static class TransportEnrichStatsStubAction
        extends HandledTransportAction<EnrichStatsAction.Request, EnrichStatsAction.Response> {

        @Inject
        public TransportEnrichStatsStubAction(TransportService transportService, ActionFilters actionFilters) {
            super(EnrichStatsAction.NAME, transportService, actionFilters, EnrichStatsAction.Request::new);
        }

        @Override
        protected void doExecute(Task task, EnrichStatsAction.Request request, ActionListener<EnrichStatsAction.Response> listener) {
            listener.onResponse(new EnrichStatsAction.Response(Collections.emptyList(), Collections.emptyList()));
        }
    }

}


text:
package visitor_1;

public abstract class RunningShoes extends SportShoes{

	public abstract double getPrice();
    public abstract String getDescription();
	public abstract void accept(Visitor v);
}


text:
package org.apache.isis.core.metamodel.facets.objectvalue.fileaccept;

import org.apache.isis.applib.value.Blob;
import org.apache.isis.applib.value.Clob;
import org.apache.isis.core.metamodel.facets.SingleStringValueFacet;

/**
 * Specifies the types of files that can be accepted for a {@link Blob} or {@link Clob}.
 *
 * The value should be of the form "file_extension|audio/*|video/*|image/*|media_type".
 *
 * @see http://www.w3schools.com
 */
public interface FileAcceptFacet extends SingleStringValueFacet {

}


text:
package com.intellij.xml.util;

import com.intellij.codeInsight.daemon.XmlErrorMessages;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.Commenter;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageCommenters;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author spleaner
 */
public class XmlDeclareIdInCommentAction implements LocalQuickFix {
  private static final Logger LOG = Logger.getInstance("#com.intellij.xml.util.XmlDeclareIdInCommentAction");

  private final String myId;

  public XmlDeclareIdInCommentAction(@NotNull final String id) {
    myId = id;
  }

  @NotNull
  public String getName() {
    return XmlErrorMessages.message("declare.id.in.comment.quickfix");
  }

  @NotNull
  public String getFamilyName() {
    return getName();
  }

  @Nullable
  public static String getImplicitlyDeclaredId(@NotNull final PsiComment comment) {
    final String text = getUncommentedText(comment);
    if (text == null) return null;

    if (text.startsWith("@declare id=\"")) {
      final String result = text.substring("@declare id=\"".length() - 1);
      return StringUtil.unquoteString(result);
    }

    return null;
  }

  @Nullable
  private static String getUncommentedText(@NotNull final PsiComment comment) {
    final PsiFile psiFile = comment.getContainingFile();
    final Language language = psiFile.getViewProvider().getBaseLanguage();
    final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language);
    if (commenter != null) {
      String text = comment.getText();

      final String prefix = commenter.getBlockCommentPrefix();
      if (prefix != null && text.startsWith(prefix)) {
        text = text.substring(prefix.length());
        final String suffix = commenter.getBlockCommentSuffix();
        if (suffix != null && text.length() > suffix.length()) {
          return text.substring(0, text.length() - suffix.length()).trim();
        }
      }
    }

    return null;
  }

  public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement psiElement = descriptor.getPsiElement();
    final PsiFile psiFile = psiElement.getContainingFile();

    new WriteCommandAction(project, psiFile) {
      protected void run(final Result result) throws Throwable {
        final XmlTag tag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class);
        if (tag == null) return;

        final Language language = psiFile.getViewProvider().getBaseLanguage();
        final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language);
        if (commenter == null) return;

        final PsiFile tempFile = PsiFileFactory.getInstance(project).createFileFromText("dummy", language.getAssociatedFileType(),
            commenter.getBlockCommentPrefix() +
                "@declare id=\"" +
                myId +
                "\"" +
                commenter.getBlockCommentSuffix() +
                "\n");

        final XmlTag parent = tag.getParentTag();
        if (parent != null && parent.isValid()) {
          final XmlTag[] tags = parent.getSubTags();
          if (tags.length > 0) {
            final PsiFile psi = tempFile.getViewProvider().getPsi(language);
            if (psi != null) {
              final PsiElement element = psi.findElementAt(1);
              if (element instanceof PsiComment) {
                parent.getNode().addChild(element.getNode(), tags[0].getNode());
              }
            }
          }
        }
      }
    }.execute();
  }
}


text:
def lint_command(tool_xml, lint_ctx):
    root = tool_xml.getroot()
    commands = root.findall("command")
    if len(commands) > 1:
        lint_ctx.error("More than one command tag found, behavior undefined.")
        return

    if len(commands) == 0:
        lint_ctx.error("No command tag found, must specify a command template to execute.")
        return

    command = commands[0]
    if "TODO" in command:
        lint_ctx.warn("Command template contains TODO text.")

    lint_ctx.info("Tool contains a command.")


text:
function popWindow(url, id, w, h) {
  // Fixes dual-screen position                         Most browsers      Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

  const width = screen.width || window.outerWidth;
  const height = screen.height || window.innerHeight;

  const left = ((width / 2) - (w / 2)) + dualScreenLeft;
  const top = ((height / 2) - (h / 2)) + dualScreenTop;
  const newWindow = window.open(
    url,
    id,
    `scrollbars=yes, width=${w}, height=${h}, top=${top}, left=${left}`,
  );

  // Puts focus on the newWindow
  if (window.focus) {
    try {
      newWindow.focus();
    } catch (e) {
      /* falls through */
    }
  }
  return newWindow;
}

export default class ProxyFrameController {
  constructor({
    prefix,
  } = {}) {
    window.oAuthCallback = (callbackUri) => {
      window.parent.postMessage({
        callbackUri,
      }, '*');
    };

    window.addEventListener('message', ({ data }) => {
      if (data) {
        const {
          oAuthUri,
        } = data;
        if (oAuthUri != null) {
          popWindow(oAuthUri, 'rc-oauth', 600, 600);
        }
      }
    });

    const key = `${prefix}-redirect-callbackUri`;
    window.addEventListener('storage', (e) => {
      if (e.key === key && e.newValue && e.newValue !== '') {
        const callbackUri = e.newValue;
        window.parent.postMessage({
          callbackUri,
          fromLocalStorage: true,
        }, '*');
        localStorage.removeItem(key);
      }
    });
    // loaded
    window.parent.postMessage({
      proxyLoaded: true,
    }, '*');
  }
}


text:
module Handlers
  class PolicyUpdateHandler < Base
    def call(context)
      if context.terminations.any?
        context.terminations.each do |term|
          term.execute!
        end
      end
      if context.cancellations.any?
        context.cancellations.each do |term|
          term.execute!
        end
      end
      super(context)
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('roombookings', '0004_equipment'),
    ]

    operations = [
        migrations.AlterModelTable(
            name='booking',
            table='CMIS_UCLAPI_V_BOOKINGS',
        ),
        migrations.AlterModelTable(
            name='room',
            table='CMIS_UCLAPI_V_ROOMS',
        ),
    ]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 19(no. 92): 105 (1891)

#### Original name
Favolus subgelatinosus Berk. ex Cooke

### Remarks
null


text:
{-# LANGUAGE OverloadedStrings #-}
module Database.PostgreSQL.Simple.Dsl.IntArray
       where

import Prelude hiding (concat)

import Data.ByteString.Builder (byteString, char8)

import Database.PostgreSQL.Simple.Dsl.Internal
import Database.PostgreSQL.Simple.Dsl.Types
import Database.PostgreSQL.Simple.Types        (PGArray (..))

data QueryInt

intset :: Expr Int -> Expr (PGArray Int)
intset (Expr _ a) = Expr 0 $ "intset(" <> a <> char8 ')'

icount :: Expr (PGArray Int) -> Expr Int
icount (Expr _ a) = Expr 0 $ "icount(" <> a <> char8 ')'

sort_asc :: Expr (PGArray Int) -> Expr (PGArray Int)
sort_asc (Expr _ a) = Expr 0 $ "sort_asc(" <> a <> char8 ')'

sort_desc :: Expr (PGArray Int) -> Expr (PGArray Int)
sort_desc (Expr _ a) = Expr 0 $ "sort_desc(" <> a <> char8 ')'

-- | idx(int[], i)
idx :: Expr (PGArray Int) -> Expr Int -> Expr Int
idx (Expr _ a) (Expr _ i) = Expr 0 $ "idx(" <> a <> char8 ',' <> i <> char8 ')'

-- | subarray(int[], start, len)
subarray :: Expr (PGArray Int) -> Expr Int -> Expr Int -> Expr (PGArray Int)
subarray (Expr _ a) (Expr _ start) (Expr _ len)  =
      Expr 0 $ "subarray(" <> a <> char8 ',' <> start <> char8 ',' <> len <> char8 ')'

-- | subarray(int[], start)
subarray1 :: Expr (PGArray Int) -> Expr Int -> Expr (PGArray Int)
subarray1 (Expr _ a) (Expr _ start) =
      Expr 0 $ "subarray(" <> a <> char8 ',' <> start <> char8 ')'

-- | uniq(int[])
uniq :: Expr (PGArray Int) -> Expr (PGArray Int)
uniq (Expr _ a) = Expr 0 $ "uniq(" <> a <> char8 ')'

-- | operator &&
overlap :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr Bool
overlap a b = binOp 10 (byteString"&&") a b

-- | operator @>
contains :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr Bool
contains a b = binOp 10 (byteString "@>") a b

-- | operator <@
contained :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr Bool
contained a b = binOp 10 (byteString "<@") a b

-- | int[] + int
append :: Expr (PGArray Int) -> Expr Int -> Expr (PGArray Int)
append a b = binOp 6 (char8 '+') a b

-- | int[] + int[]
concat :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr (PGArray Int)
concat a b = binOp 6 (char8 '+') a b

-- | int[] - int
remove :: Expr (PGArray Int) -> Expr Int -> Expr (PGArray Int)
remove a b = binOp 6 (char8 '-') a b

-- | int[] - int[]
difference :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr (PGArray Int)
difference a b = binOp 6 (char8 '-') a b

-- | int[] | int
add :: Expr (PGArray Int) -> Expr Int -> Expr (PGArray Int)
add a b = binOp 10 (char8 '|') a b

-- | int[] | int[]
union :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr (PGArray Int)
union a b = binOp 10 (char8 '|') a b

-- | int[] & int[]
intersection :: Expr (PGArray Int) -> Expr (PGArray Int) -> Expr (PGArray Int)
intersection a b = binOp 10 (char8 '&') a b

-- | query_int @@ int[]
satisfies :: Expr QueryInt -> Expr (PGArray Int) -> Expr Bool
satisfies a b = binOp 10 (byteString "@@") a b

-- | int[] ~~ query_int
satisfied :: Expr (PGArray Int) -> Expr QueryInt -> Expr Bool
satisfied a b = binOp 10 (byteString "~~") a b


text:
<template name="policies">

Policies

"Since free and civil discourse is at the heart of a university community, users should communicate in a manner that advances the cause of learning and mutual understanding."

        RIT Code of Conduct for Computer and Network Use

Use of this site falls under the RIT Code of Conduct for Computer and Network Use.

Student Government reserves the right to remove any evaluation or user at any time for violating the Code of Conduct. This includes, but is not limited to, creating an intimidating, hostile or abusive environment for any member of the RIT community, or posting of any  obscene, defamatory, threatening, or otherwise harassing evaluations.

Please exercise good judgment when using this service.

</template>


text:
package betterwithmods.module.hardcore.crafting;

import betterwithmods.BWMod;
import betterwithmods.common.BWMItems;
import betterwithmods.common.BWMRecipes;
import betterwithmods.common.entity.EntityHCFishHook;
import betterwithmods.common.registry.crafting.BaitingRecipe;
import betterwithmods.module.Feature;
import betterwithmods.util.StackIngredient;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityFishHook;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFishingRod;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.stats.StatList;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraft.world.storage.loot.LootTableList;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.LootTableLoadEvent;
import net.minecraftforge.event.entity.player.ItemFishedEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Random;

/**
 * Created by primetoxinz on 7/23/17.
 */
public class HCFishing extends Feature {
    public static boolean requireBait, restrictToOpenWater;
    public static int minimumWaterDepth;

    public static ResourceLocation HCFISHING_LOOT = LootTableList.register(new ResourceLocation(BWMod.MODID, "gameplay/fishing"));

    private static final ResourceLocation BAITED_FISHING_ROD = new ResourceLocation(BWMod.MODID, "baited_fishing_rod");
    public static Ingredient BAIT = Ingredient.EMPTY;

    @Override
    public void setupConfig() {
        requireBait = loadPropBool("Require Bait", "Change Fishing Rods to require being Baited with certain items to entice fish, they won't nibble without it!", true);
        restrictToOpenWater = loadPropBool("Restrict to Open Water", "Fishing on underground locations won't work, hook must be placed on a water block with line of sight to the sky.", true);
        minimumWaterDepth = loadPropInt("Minimum Water Depth", "If higher than 1, requires bodies of water to have a minimum depth for fishing to be successful.", 3);

    }

    @Override
    public void preInit(FMLPreInitializationEvent event) {
        CapabilityManager.INSTANCE.register(FishingBait.class, new CapabilityFishingRod(), FishingBait::new);
        BWMRecipes.removeRecipe(new ResourceLocation("fishing_rod"));

    }

    @Override
    public void postInit(FMLPostInitializationEvent event) {
        BAIT = StackIngredient.fromStacks(loadItemStackArray("Bait", "Add items as valid fishing bait", new ItemStack[]{
                new ItemStack(Items.SPIDER_EYE),
                new ItemStack(BWMItems.CREEPER_OYSTER),
                new ItemStack(Items.FISH, 1, 2),
                new ItemStack(Items.FISH, 1, 3),
                new ItemStack(BWMItems.BAT_WING, 1),
                new ItemStack(BWMItems.COOKED_BAT_WING, 1),
                new ItemStack(Items.ROTTEN_FLESH)
        }));
        addHardcoreRecipe(new BaitingRecipe());
    }

    //Override loottables
    @SubscribeEvent
    public void onLootTableLoad(LootTableLoadEvent event) {
        if (event.getName().equals(LootTableList.GAMEPLAY_FISHING)) {
            LootTable table = event.getLootTableManager().getLootTableFromLocation(HCFISHING_LOOT);
            event.setTable(table);
        }
    }

    @Override
    public String getFeatureDescription() {
        return "Change Fishing Rods to require bait and a large enough water source exposed to the sky.";
    }

    @SubscribeEvent
    public void attachCapability(AttachCapabilitiesEvent<ItemStack> event) {
        if (event.getObject().getItem() instanceof ItemFishingRod) {
            event.addCapability(BAITED_FISHING_ROD, new FishingBait());
        }
    }

    @SubscribeEvent
    public void onFished(ItemFishedEvent event) {
        BlockPos hookPos = getHookSurfacePos(event.getHookEntity());
        if (restrictToOpenWater) {
            if (event.getHookEntity().getEntityWorld().getHeight(hookPos.getX(), hookPos.getZ()) > hookPos.getY() || !isAirBlock(event.getHookEntity().getEntityWorld(), hookPos)) {
                event.setCanceled(true);
                event.getEntityPlayer().sendMessage(new TextComponentTranslation("bwm.message.needs_open_sky"));
                return;
            }
        }
        if (minimumWaterDepth > 1) {
            for (int i = 1; i <= minimumWaterDepth; i++) {
                if (!isWaterBlock(event.getHookEntity().getEntityWorld(), hookPos.add(0, (i * -1), 0))) {
                    event.setCanceled(true);
                    event.getEntityPlayer().sendMessage(new TextComponentTranslation("bwm.message.needs_deep_water"));
                    return;
                }
            }
        }
        if (requireBait) {
            ItemStack stack = getMostRelevantFishingRod(event.getEntityPlayer());
            if (isFishingRod(stack)) {
                FishingBait cap = stack.getCapability(FISHING_ROD_CAP, EnumFacing.UP);
                if (cap.hasBait()) {
                    cap.setBait(false);
                    NBTTagCompound tag = stack.getTagCompound();
                    if (tag != null && tag.hasKey("bait")) {
                        tag.setBoolean("bait", false);
                    }
                }
            }
        }
    }

    private static ActionResult<ItemStack> throwLine(Item item, EntityPlayer player, EnumHand hand, World world, Random rand) {
        ItemStack itemstack = player.getHeldItem(hand);

        if (player.fishEntity != null) {
            int i = player.fishEntity.handleHookRetraction();
            itemstack.damageItem(i, player);
            player.swingArm(hand);
            world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_BOBBER_RETRIEVE, SoundCategory.NEUTRAL, 1.0F, 0.4F / (rand.nextFloat() * 0.4F + 0.8F));
        } else {
            world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_BOBBER_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (rand.nextFloat() * 0.4F + 0.8F));

            if (!world.isRemote) {
                EntityHCFishHook entityfishhook = new EntityHCFishHook(world, player);
                int j = EnchantmentHelper.getFishingSpeedBonus(itemstack);

                if (j > 0) {
                    entityfishhook.setLureSpeed(j);
                }

                int k = EnchantmentHelper.getFishingLuckBonus(itemstack);

                if (k > 0) {
                    entityfishhook.setLuck(k);
                }

                world.spawnEntity(entityfishhook);
            }

            player.swingArm(hand);
            player.addStat(StatList.getObjectUseStats(item));
        }

        return new ActionResult<>(EnumActionResult.SUCCESS, itemstack);
    }

    @SubscribeEvent
    public void useFishingRod(PlayerInteractEvent.RightClickItem event) {
        if (requireBait) {
            if (isFishingRod(event.getItemStack())) {
                FishingBait cap = event.getItemStack().getCapability(FISHING_ROD_CAP, EnumFacing.UP);
                event.setCanceled(true);
                event.setResult(Event.Result.ALLOW);
                if (cap != null) {
                    if (cap.hasBait() || event.getEntityPlayer().isCreative()) {
                        throwLine(event.getItemStack().getItem(), event.getEntityPlayer(), event.getHand(), event.getWorld(), event.getWorld().rand).getType();
                    } else if (!event.getWorld().isRemote && (event.getHand() == EnumHand.MAIN_HAND || event.getHand() == EnumHand.OFF_HAND)) {
                        event.getEntityPlayer().sendMessage(new TextComponentTranslation("bwm.message.needs_bait"));
                    }
                }
            }
        }
    }

    @SideOnly(Side.CLIENT)
    @SubscribeEvent
    public void onTooltip(ItemTooltipEvent event) {
        if (requireBait) {
            ItemStack stack = event.getItemStack();
            if (isFishingRod(stack)) {
                FishingBait cap = event.getItemStack().getCapability(FISHING_ROD_CAP, EnumFacing.UP);
                boolean bait = cap.hasBait();
                String tooltip = bait ? "Baited" : "Unbaited";
                if (!bait) {
                    NBTTagCompound tag = stack.getTagCompound();
                    if (tag != null && tag.hasKey("bait")) {
                        tooltip = tag.getBoolean("bait") ? "Baited" : "Unbaited";
                    }
                }
                event.getToolTip().add(tooltip);
            }
        }
    }

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

    public static boolean isFishingRod(ItemStack stack) {
        return stack.getItem() instanceof ItemFishingRod && stack.hasCapability(FISHING_ROD_CAP, EnumFacing.UP);
    }

    public static ItemStack getMostRelevantFishingRod(EntityPlayer player) {
        ItemStack itemMain = player.getHeldItemMainhand();
        if (isFishingRod(itemMain) && itemMain.getCapability(FISHING_ROD_CAP, EnumFacing.UP).hasBait()) {
            return itemMain;
        } else {
            return player.getHeldItemOffhand();
        }
    }

    public static boolean isBaited(ItemStack stack, boolean baited) {
        return isFishingRod(stack) && stack.getCapability(FISHING_ROD_CAP, EnumFacing.UP).hasBait() == baited;
    }

    public static ItemStack setBaited(ItemStack rod, boolean baited) {
        if (rod.hasCapability(FISHING_ROD_CAP, EnumFacing.UP)) {
            FishingBait cap = rod.getCapability(FISHING_ROD_CAP, EnumFacing.UP);
            cap.setBait(baited);
        }
        if (rod.getTagCompound() == null) {
            rod.setTagCompound(new NBTTagCompound());
        }
        NBTTagCompound tag = rod.getTagCompound();
        tag.setBoolean("bait", baited);
        return new ItemStack(rod.serializeNBT());
    }

    public static BlockPos getHookSurfacePos(EntityFishHook hookEntity) {
        World world = hookEntity.getEntityWorld();
        BlockPos hookPos = hookEntity.getPosition();
        int heightOffset = 0;
        while (isWaterBlock(world, hookPos.add(0, heightOffset, 0)) && (hookPos.getY() + heightOffset < 255)) {
            heightOffset++;
        }
        return hookPos.add(0, heightOffset, 0);
    }

    public static boolean isWaterBlock(World world, BlockPos pos) {
        return (world.getBlockState(pos).getBlock() == Blocks.WATER || world.getBlockState(pos).getBlock() == Blocks.FLOWING_WATER);
    }

    public static boolean isAirBlock(World world, BlockPos pos) {
        return (world.getBlockState(pos).getBlock() == Blocks.AIR);
    }

    @SuppressWarnings("CanBeFinal")
    @CapabilityInject(FishingBait.class)
    public static Capability<FishingBait> FISHING_ROD_CAP = null;

    public static class CapabilityFishingRod implements Capability.IStorage<FishingBait> {

        @Nullable
        @Override
        public NBTBase writeNBT(Capability<FishingBait> capability, FishingBait instance, EnumFacing side) {
            return instance.serializeNBT();
        }

        @Override
        public void readNBT(Capability<FishingBait> capability, FishingBait instance, EnumFacing side, NBTBase nbt) {
            instance.deserializeNBT((NBTTagCompound) nbt);
        }
    }

    public static class FishingBait implements ICapabilitySerializable<NBTTagCompound> {
        private boolean bait;

        public FishingBait() {}

        public boolean hasBait() {
            return bait;
        }

        public void setBait(boolean bait) {
            this.bait = bait;
        }

        @Override
        public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
            return capability == FISHING_ROD_CAP;
        }

        @Nullable
        @Override
        public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
            if (capability == FISHING_ROD_CAP)
                return FISHING_ROD_CAP.cast(this);
            return null;
        }

        @Override
        public NBTTagCompound serializeNBT() {
            NBTTagCompound tag = new NBTTagCompound();
            tag.setBoolean("bait", hasBait());
            return tag;
        }

        @Override
        public void deserializeNBT(NBTTagCompound nbt) {
            setBait(nbt.getBoolean("bait"));
        }
    }
}


text:
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

#ifdef MAIN
#define eqlrnge1_test main
#endif

#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int eqlrnge1_test(int, char**)
{
  cout<<"Results of eqlrnge1_test:"<<endl;
  typedef vector <int> IntVec;
  IntVec v(10);
  for(int i = 0; i < v.size(); i++)
    v[i] = i / 3;
  ostream_iterator<int> iter(cout, " ");
  cout << "Within the collection:\n\t";
  copy(v.begin(), v.end(), iter);
  pair <IntVec::iterator, IntVec::iterator> range =
	equal_range(v.begin(), v.end(), 2);
  cout
    << "\n2 can be inserted from before index "
    <<(range.first - v.begin())
    << " to before index "
    <<(range.second - v.begin())
    << endl;
  return 0;
}


text:
<html>
<head>
	<title>Coolmenus example - CoolMenus3 DHTML script made by Thomas Brattli from DHTMLCentral.com. Visit for more great scripts.</title>
</head>

<body bgcolor="green">

test page

</body>
</html>


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Examples.Tasks.HelloTask;
using Org.Apache.REEF.Examples.Tasks.ShellTask;
using Org.Apache.REEF.Examples.Tasks.StreamingTasks;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Protobuf;
using Org.Apache.REEF.Tang.Types;

namespace Org.Apache.REEF.Tang.Tools
{
    public class ClassHierarchyBuilder
    {
        /// <summary>
        /// This program generates class hierarchy bin file for the list of dlls, plus a defalut list
        /// The default list include: ITask, StreamTask1, HelloTask and ShellTask, please remove if not needed
        /// </summary>
        /// <param name="args"> additional dlls needed to build class hierarchy </param>
        public static void Main(string[] args)
        {
            const string DllSubfix = ".dll";
            const string ClassHierarchyBinFileName = "task.bin";

            List<string> taskDlls = new List<string>();

            foreach (string arg in args)
            {
                string assemblyName = arg;
                if (!arg.EndsWith(DllSubfix, StringComparison.OrdinalIgnoreCase))
                {
                    assemblyName += DllSubfix;
                }
                if (!File.Exists(assemblyName))
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "invalid argument: assembly {0} cannot be found", assemblyName));
                }
                taskDlls.Add(arg);
            }

            taskDlls.Add(GetAssemblyName(typeof(ITask)));
            taskDlls.Add(GetAssemblyName(typeof(HelloTask)));
            taskDlls.Add(GetAssemblyName(typeof(ShellTask)));
            taskDlls.Add(GetAssemblyName(typeof(StreamTask1)));

            IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(taskDlls.ToArray());

            // the following is verification only
            // to verify that a class indeeded has been added to the class hierarchy, check the class name
            IClassNode streamTaskClassNode = (IClassNode)ns.GetNode(typeof(StreamTask1).AssemblyQualifiedName);
            IClassNode helloTaskClassNode = (IClassNode)ns.GetNode(typeof(HelloTask).AssemblyQualifiedName);
            IClassNode shellTaskClassNode = (IClassNode)ns.GetNode(typeof(ShellTask).AssemblyQualifiedName);

            ProtocolBufferClassHierarchy.Serialize(ClassHierarchyBinFileName, ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize(ClassHierarchyBinFileName);

            IClassNode retrievedStreamTaskClassNode = (IClassNode)ch.GetNode(typeof(StreamTask1).AssemblyQualifiedName);
            IClassNode retrievedHelloTaskClassNode = (IClassNode)ch.GetNode(typeof(HelloTask).AssemblyQualifiedName);
            IClassNode retrievedShellTaskClassNode = (IClassNode)ch.GetNode(typeof(ShellTask).AssemblyQualifiedName);

            if (!streamTaskClassNode.GetFullName().Equals(retrievedStreamTaskClassNode.GetFullName()) ||
                !helloTaskClassNode.GetFullName().Equals(retrievedHelloTaskClassNode.GetFullName()) ||
                !shellTaskClassNode.GetFullName().Equals(retrievedShellTaskClassNode.GetFullName()))
            {
                Console.WriteLine("Node deseriliazed is not equal");
            }
            else
            {
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Class hierarchy written to [{0}].", Directory.GetCurrentDirectory()));
            }
        }

        private static string GetAssemblyName(Type type)
        {
            return type.Assembly.GetName().Name;
        }
    }
}


text:
package com.hp.autonomy.iod.client.error;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.hp.autonomy.iod.client.job.Action;
import com.hp.autonomy.iod.client.job.Status;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.List;

@Data
@JsonDeserialize(builder = IodError.Builder.class)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class IodError {

    private final int error;
    private final IodErrorCode errorCode;
    private final String reason;
    private final Object detail;
    private final List<Action<?>> actions;
    private final Status status;
    private final String message;

    @Setter
    @Accessors(chain = true)
    @JsonPOJOBuilder(withPrefix = "set")
    public static class Builder {
        private int error;
        private IodErrorCode errorCode;
        private String reason;
        private Object detail;
        private List<Action<?>> actions;
        private Status status;
        private String message;

        public Builder setError(final int error) {
            this.error = error;
            this.errorCode = IodErrorCode.fromCode(error);
            return this;
        }

        public IodError build() {
            return new IodError(error, errorCode, reason, detail, actions, status, message);
        }
    }

}


text:
package com.shop.data.repository;

import com.shop.data.entity.ImageEntity;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by Vazgen on 07-Jan-17.
 */
public interface ImageRepository extends JpaRepository<ImageEntity, Long> {
}


text:
Create a new exhibition

the elements with the * are mandatory

{{error}}

  <form novalidate >

      Name *<input class="mdl-textfield__input" type="text" id="name" ng-model="exhib.name" required>

      City *<input class="mdl-textfield__input" type="text" id="city" ng-model="exhib.city">

      <input class="mdl-textfield__input" type="text" id="street" ng-model="exhib.street">
      Street and Number

      <input class="mdl-textfield__input" type="text" id="code"  ng-model="exhib.zipcode">
      Postal Code

      <input class="mdl-textfield__input" type="text" id="country"  ng-model="exhib.country">
      Country

      <textarea class="mdl-textfield__input" type="text" rows= "3" id="description" maxlength="250" style="min-height: 150px;"  ng-model="exhib.description"></textarea>
      Description (max 250 characters)

      From<input class="mdl-textfield__input" type="date" id="start" ng-model="exhib.startDate">

      to<input class="mdl-textfield__input" type="date" id="end" ng-model="exhib.endDate">

    <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-cell mdl-cell--12-col" ng-click="create(exhib)">
      add
    </button>

  </form>