text:
using content::UserMetricsAction;

///////////////////////////////////////////////////////////////////////////////
// AutocompleteEditController

AutocompleteEditController::~AutocompleteEditController() {
}

///////////////////////////////////////////////////////////////////////////////
// AutocompleteEditModel::State

AutocompleteEditModel::State::State(bool user_input_in_progress,
                                    const string16& user_text,
                                    const string16& keyword,
                                    bool is_keyword_hint)
    : user_input_in_progress(user_input_in_progress),
      user_text(user_text),
      keyword(keyword),
      is_keyword_hint(is_keyword_hint) {
}

AutocompleteEditModel::State::~State() {
}

///////////////////////////////////////////////////////////////////////////////
// AutocompleteEditModel

AutocompleteEditModel::AutocompleteEditModel(
    OmniboxView* view,
    AutocompleteEditController* controller,
    Profile* profile)
    : ALLOW_THIS_IN_INITIALIZER_LIST(
        autocomplete_controller_(new AutocompleteController(profile, this))),
      view_(view),
      popup_(NULL),
      controller_(controller),
      has_focus_(false),
      user_input_in_progress_(false),
      just_deleted_text_(false),
      has_temporary_text_(false),
      paste_state_(NONE),
      control_key_state_(UP),
      is_keyword_hint_(false),
      profile_(profile),
      in_revert_(false),
      allow_exact_keyword_match_(false),
      instant_complete_behavior_(INSTANT_COMPLETE_DELAYED) {
}

AutocompleteEditModel::~AutocompleteEditModel() {
}

const AutocompleteEditModel::State
    AutocompleteEditModel::GetStateForTabSwitch() {
  // Like typing, switching tabs "accepts" the temporary text as the user
  // text, because it makes little sense to have temporary text when the
  // popup is closed.
  if (user_input_in_progress_) {
    // Weird edge case to match other browsers: if the edit is empty, revert to
    // the permanent text (so the user can get it back easily) but select it (so
    // on switching back, typing will "just work").
    const string16 user_text(UserTextFromDisplayText(view_->GetText()));
    if (user_text.empty()) {
      view_->RevertAll();
      view_->SelectAll(true);
    } else {
      InternalSetUserText(user_text);
    }
  }

  return State(user_input_in_progress_, user_text_, keyword_, is_keyword_hint_);
}

void AutocompleteEditModel::RestoreState(const State& state) {
  // Restore any user editing.
  if (state.user_input_in_progress) {
    // NOTE: Be sure and set keyword-related state BEFORE invoking
    // DisplayTextFromUserText(), as its result depends upon this state.
    keyword_ = state.keyword;
    is_keyword_hint_ = state.is_keyword_hint;
    view_->SetUserText(state.user_text,
        DisplayTextFromUserText(state.user_text), false);
  }
}

AutocompleteMatch AutocompleteEditModel::CurrentMatch() {
  AutocompleteMatch match;
  GetInfoForCurrentText(&match, NULL);
  return match;
}

bool AutocompleteEditModel::UpdatePermanentText(
    const string16& new_permanent_text) {
  // When there's a new URL, and the user is not editing anything or the edit
  // doesn't have focus, we want to revert the edit to show the new URL.  (The
  // common case where the edit doesn't have focus is when the user has started
  // an edit and then abandoned it and clicked a link on the page.)
  const bool visibly_changed_permanent_text =
      (permanent_text_ != new_permanent_text) &&
      (!user_input_in_progress_ || !has_focus_);

  permanent_text_ = new_permanent_text;
  return visibly_changed_permanent_text;
}

GURL AutocompleteEditModel::PermanentURL() {
  return URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string());
}

void AutocompleteEditModel::SetUserText(const string16& text) {
  SetInputInProgress(true);
  InternalSetUserText(text);
  paste_state_ = NONE;
  has_temporary_text_ = false;
}

void AutocompleteEditModel::FinalizeInstantQuery(
    const string16& input_text,
    const string16& suggest_text,
    bool skip_inline_autocomplete) {
  if (skip_inline_autocomplete) {
    const string16 final_text = input_text + suggest_text;
    view_->OnBeforePossibleChange();
    view_->SetWindowTextAndCaretPos(final_text, final_text.length());
    view_->OnAfterPossibleChange();
  } else if (popup_->IsOpen()) {
    SearchProvider* search_provider =
        autocomplete_controller_->search_provider();
    // There may be no providers during testing; guard against that.
    if (search_provider)
      search_provider->FinalizeInstantQuery(input_text, suggest_text);
  }
}

void AutocompleteEditModel::SetSuggestedText(
    const string16& text,
    InstantCompleteBehavior behavior) {
  instant_complete_behavior_ = behavior;
  if (instant_complete_behavior_ == INSTANT_COMPLETE_NOW) {
    if (!text.empty())
      FinalizeInstantQuery(view_->GetText(), text, false);
    else
      view_->SetInstantSuggestion(text, false);
  } else {
    DCHECK((behavior == INSTANT_COMPLETE_DELAYED) ||
           (behavior == INSTANT_COMPLETE_NEVER));
    view_->SetInstantSuggestion(text, behavior == INSTANT_COMPLETE_DELAYED);
  }
}

bool AutocompleteEditModel::CommitSuggestedText(bool skip_inline_autocomplete) {
  if (!controller_->GetInstant())
    return false;

  const string16 suggestion = view_->GetInstantSuggestion();
  if (suggestion.empty())
    return false;

  FinalizeInstantQuery(view_->GetText(), suggestion, skip_inline_autocomplete);
  return true;
}

bool AutocompleteEditModel::AcceptCurrentInstantPreview() {
  return InstantController::CommitIfCurrent(controller_->GetInstant());
}

void AutocompleteEditModel::OnChanged() {
  const AutocompleteMatch current_match = CurrentMatch();

  NetworkActionPredictor::Action recommended_action =
      NetworkActionPredictor::ACTION_NONE;
  NetworkActionPredictor* network_action_predictor =
      user_input_in_progress() ?
      NetworkActionPredictorFactory::GetForProfile(profile_) : NULL;
  if (network_action_predictor) {
    network_action_predictor->RegisterTransitionalMatches(user_text_,
                                                          result());
    // Confer with the NetworkActionPredictor to determine what action, if any,
    // we should take. Get the recommended action here even if we don't need it
    // so we can get stats for anyone who is opted in to UMA, but only get it if
    // the user has actually typed something to avoid constructing it before
    // it's needed. Note: This event is triggered as part of startup when the
    // initial tab transitions to the start page.
    recommended_action =
        network_action_predictor->RecommendAction(user_text_, current_match);
  }

  UMA_HISTOGRAM_ENUMERATION("NetworkActionPredictor.Action", recommended_action,
                            NetworkActionPredictor::LAST_PREDICT_ACTION);
  string16 suggested_text;

  if (DoInstant(current_match, &suggested_text)) {
    SetSuggestedText(suggested_text, instant_complete_behavior_);
  } else {
    switch (recommended_action) {
      case NetworkActionPredictor::ACTION_PRERENDER:
        DoPrerender(current_match);
        break;
      case NetworkActionPredictor::ACTION_PRECONNECT:
        DoPreconnect(current_match);
        break;
      case NetworkActionPredictor::ACTION_NONE:
        break;
      default:
        NOTREACHED() << "Unexpected recommended action: " << recommended_action;
        break;
    }

    // Hide any suggestions we might be showing.
    view_->SetInstantSuggestion(string16(), false);

    // No need to wait any longer for instant.
    FinalizeInstantQuery(string16(), string16(), false);
  }

  controller_->OnChanged();
}

void AutocompleteEditModel::GetDataForURLExport(GURL* url,
                                                string16* title,
                                                SkBitmap* favicon) {
  AutocompleteMatch match;
  GetInfoForCurrentText(&match, NULL);
  *url = match.destination_url;
  if (*url == URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_),
                                      std::string())) {
    *title = controller_->GetTitle();
    *favicon = controller_->GetFavicon();
  }
}

bool AutocompleteEditModel::UseVerbatimInstant() {
#if defined(OS_MACOSX)
  // TODO(suzhe): Fix Mac port to display Instant suggest in a separated NSView,
  // so that we can display instant suggest along with composition text.
  const AutocompleteInput& input = autocomplete_controller_->input();
  if (input.prevent_inline_autocomplete())
    return true;
#endif

  // The value of input.prevent_inline_autocomplete() is determined by
  // following conditions:
  // 1. If the caret is at the end of the text (checked below).
  // 2. If it's in IME composition mode.
  // As we use a separated widget for displaying the instant suggest, it won't
  // interfere with IME composition, so we don't need to care about the value of
  // input.prevent_inline_autocomplete() here.
  if (view_->DeleteAtEndPressed() || (popup_->selected_line() != 0) ||
      just_deleted_text_)
    return true;

  size_t start, end;
  view_->GetSelectionBounds(&start, &end);
  return (start != end) || (start != view_->GetText().length());
}

string16 AutocompleteEditModel::GetDesiredTLD() const {
  // Tricky corner case: The user has typed "foo" and currently sees an inline
  // autocomplete suggestion of "foo.net".  He now presses ctrl-a (e.g. to
  // select all, on Windows).  If we treat the ctrl press as potentially for the
  // sake of ctrl-enter, then we risk "www.foo.com" being promoted as the best
  // match.  This would make the autocompleted text disappear, leaving our user
  // feeling very confused when the wrong text gets highlighted.
  //
  // Thus, we only treat the user as pressing ctrl-enter when the user presses
  // ctrl without any fragile state built up in the omnibox:
  // * the contents of the omnibox have not changed since the keypress,
  // * there is no autocompleted text visible, and
  // * the user is not typing a keyword query.
  return (control_key_state_ == DOWN_WITHOUT_CHANGE &&
          inline_autocomplete_text_.empty() && !KeywordIsSelected())?
    ASCIIToUTF16("com") : string16();
}

bool AutocompleteEditModel::CurrentTextIsURL() const {
  // If !user_input_in_progress_, the permanent text is showing, which should
  // always be a URL, so no further checking is needed.  By avoiding checking in
  // this case, we avoid calling into the autocomplete providers, and thus
  // initializing the history system, as long as possible, which speeds startup.
  if (!user_input_in_progress_)
    return true;

  AutocompleteMatch match;
  GetInfoForCurrentText(&match, NULL);
  return match.transition == content::PAGE_TRANSITION_TYPED;
}

AutocompleteMatch::Type AutocompleteEditModel::CurrentTextType() const {
  AutocompleteMatch match;
  GetInfoForCurrentText(&match, NULL);
  return match.type;
}

void AutocompleteEditModel::AdjustTextForCopy(int sel_min,
                                              bool is_all_selected,
                                              string16* text,
                                              GURL* url,
                                              bool* write_url) {
  *write_url = false;

  if (sel_min != 0)
    return;

  if (!user_input_in_progress() && is_all_selected) {
    // The user selected all the text and has not edited it. Use the url as the
    // text so that if the scheme was stripped it's added back, and the url
    // is unescaped (we escape parts of the url for display).
    *url = PermanentURL();
    *text = UTF8ToUTF16(url->spec());
    *write_url = true;
    return;
  }

  // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now
  // the user is probably holding down control to cause the copy, which will
  // screw up our calculation of the desired_tld.
  AutocompleteMatch match;
  profile_->GetAutocompleteClassifier()->Classify(*text, string16(),
        KeywordIsSelected(), true, &match, NULL);
  if (match.transition != content::PAGE_TRANSITION_TYPED)
    return;
  *url = match.destination_url;

  // Prefix the text with 'http://' if the text doesn't start with 'http://',
  // the text parses as a url with a scheme of http, the user selected the
  // entire host, and the user hasn't edited the host or manually removed the
  // scheme.
  GURL perm_url(PermanentURL());
  if (perm_url.SchemeIs(chrome::kHttpScheme) &&
      url->SchemeIs(chrome::kHttpScheme) && perm_url.host() == url->host()) {
    *write_url = true;
    string16 http = ASCIIToUTF16(chrome::kHttpScheme) +
        ASCIIToUTF16(chrome::kStandardSchemeSeparator);
    if (text->compare(0, http.length(), http) != 0)
      *text = http + *text;
  }
}

void AutocompleteEditModel::SetInputInProgress(bool in_progress) {
  if (user_input_in_progress_ == in_progress)
    return;

  user_input_in_progress_ = in_progress;
  if (user_input_in_progress_)
    time_user_first_modified_omnibox_ = base::TimeTicks::Now();
  controller_->OnInputInProgress(in_progress);
}

void AutocompleteEditModel::Revert() {
  SetInputInProgress(false);
  paste_state_ = NONE;
  InternalSetUserText(string16());
  keyword_.clear();
  is_keyword_hint_ = false;
  has_temporary_text_ = false;
  view_->SetWindowTextAndCaretPos(permanent_text_,
                                  has_focus_ ? permanent_text_.length() : 0);
  NetworkActionPredictor* network_action_predictor =
      NetworkActionPredictorFactory::GetForProfile(profile_);
  if (network_action_predictor)
    network_action_predictor->ClearTransitionalMatches();
}

void AutocompleteEditModel::StartAutocomplete(
    bool has_selected_text,
    bool prevent_inline_autocomplete) const {
  bool keyword_is_selected = KeywordIsSelected();
  popup_->SetHoveredLine(AutocompletePopupModel::kNoMatch);
  // We don't explicitly clear AutocompletePopupModel::manually_selected_match,
  // as Start ends up invoking AutocompletePopupModel::OnResultChanged which
  // clears it.
  autocomplete_controller_->Start(
      user_text_, GetDesiredTLD(),
      prevent_inline_autocomplete || just_deleted_text_ ||
      (has_selected_text && inline_autocomplete_text_.empty()) ||
      (paste_state_ != NONE), keyword_is_selected,
      keyword_is_selected || allow_exact_keyword_match_,
      AutocompleteInput::ALL_MATCHES);
}

void AutocompleteEditModel::StopAutocomplete() {
  if (popup_->IsOpen() && !in_revert_) {
    InstantController* instant = controller_->GetInstant();
    if (instant && !instant->commit_on_mouse_up())
      instant->DestroyPreviewContents();
  }

  autocomplete_controller_->Stop(true);
}

bool AutocompleteEditModel::CanPasteAndGo(const string16& text) const {
  if (!view_->GetCommandUpdater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL))
    return false;

  profile_->GetAutocompleteClassifier()->Classify(text, string16(),
      false, false, &paste_and_go_match_, &paste_and_go_alternate_nav_url_);
  return paste_and_go_match_.destination_url.is_valid();
}

void AutocompleteEditModel::PasteAndGo() {
  // The final parameter to OpenURL, keyword, is not quite correct here: it's
  // possible to "paste and go" a string that contains a keyword.  This is
  // enough of an edge case that we ignore this possibility.
  view_->RevertAll();
  view_->OpenMatch(paste_and_go_match_, CURRENT_TAB,
      paste_and_go_alternate_nav_url_, AutocompletePopupModel::kNoMatch,
      string16());
}

void AutocompleteEditModel::AcceptInput(WindowOpenDisposition disposition,
                                        bool for_drop) {
  // Get the URL and transition type for the selected entry.
  AutocompleteMatch match;
  GURL alternate_nav_url;
  GetInfoForCurrentText(&match, &alternate_nav_url);

  if (!match.destination_url.is_valid())
    return;

  if ((match.transition == content::PAGE_TRANSITION_TYPED) &&
      (match.destination_url ==
       URLFixerUpper::FixupURL(UTF16ToUTF8(permanent_text_), std::string()))) {
    // When the user hit enter on the existing permanent URL, treat it like a
    // reload for scoring purposes.  We could detect this by just checking
    // user_input_in_progress_, but it seems better to treat "edits" that end
    // up leaving the URL unchanged (e.g. deleting the last character and then
    // retyping it) as reloads too.  We exclude non-TYPED transitions because if
    // the transition is GENERATED, the user input something that looked
    // different from the current URL, even if it wound up at the same place
    // (e.g. manually retyping the same search query), and it seems wrong to
    // treat this as a reload.
    match.transition = content::PAGE_TRANSITION_RELOAD;
  } else if (for_drop || ((paste_state_ != NONE) &&
                          match.is_history_what_you_typed_match)) {
    // When the user pasted in a URL and hit enter, score it like a link click
    // rather than a normal typed URL, so it doesn't get inline autocompleted
    // as aggressively later.
    match.transition = content::PAGE_TRANSITION_LINK;
  }

  if (match.template_url && match.template_url->url() &&
      match.template_url->url()->HasGoogleBaseURLs()) {
    GoogleURLTracker::GoogleURLSearchCommitted();
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
    // TODO(pastarmovj): Remove these metrics once we have proven that (close
    // to) none searches that should have RLZ are sent out without one.
    match.template_url->url()->CollectRLZMetrics();
#endif
  }

  view_->OpenMatch(match, disposition, alternate_nav_url,
                   AutocompletePopupModel::kNoMatch,
                   is_keyword_hint_ ? string16() : keyword_);
}

void AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match,
                                      WindowOpenDisposition disposition,
                                      const GURL& alternate_nav_url,
                                      size_t index,
                                      const string16& keyword) {
  // We only care about cases where there is a selection (i.e. the popup is
  // open).
  if (popup_->IsOpen()) {
    AutocompleteLog log(
        autocomplete_controller_->input().text(),
        autocomplete_controller_->input().type(),
        popup_->selected_line(),
        -1,  // don't yet know tab ID; set later if appropriate
        base::TimeDelta::FromMilliseconds(-1),  // typing duration; usually
                                                // over-written later
        0,  // inline autocomplete length; possibly set later
        result());
    if (index != AutocompletePopupModel::kNoMatch)
      log.selected_index = index;
    else if (!has_temporary_text_)
      log.inline_autocompleted_length = inline_autocomplete_text_.length();
    if (disposition == CURRENT_TAB) {
      // If we know the destination is being opened in the curren tab,
      // we can easily get the tab ID.  (If it's being opened in a new
      // tab, we don't know the tab ID yet.)
      log.tab_id = controller_->GetTabContentsWrapper()->
                       restore_tab_helper()->session_id().id();
    }
    if (user_input_in_progress_) {
      // This case should happen every time except possibly in unit tests.
      // If we somehow got into OpenMatch() by selecting an autocomplete
      // match without going through user_input_in_progress_, that
      // means we never properly set time_user_first_modified_omnibox_
      // (because we didn't know the user started typing!).  In that
      // case, leave the elapsed_time_since_user_first_modified_omnibox
      // set to -1 ms.
      log.elapsed_time_since_user_first_modified_omnibox =
          base::TimeTicks::Now() - time_user_first_modified_omnibox_;
    }
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
        content::Source<Profile>(profile_),
        content::Details<AutocompleteLog>(&log));
  }

  TemplateURLService* template_url_service =
      TemplateURLServiceFactory::GetForProfile(profile_);
  if (template_url_service && !keyword.empty()) {
    const TemplateURL* const template_url =
        template_url_service->GetTemplateURLForKeyword(keyword);

    // Special case for extension keywords. Don't increment usage count for
    // these.
    if (template_url && template_url->IsExtensionKeyword()) {
      AutocompleteMatch current_match;
      GetInfoForCurrentText(&current_match, NULL);

      const AutocompleteMatch& match =
          index == AutocompletePopupModel::kNoMatch ?
              current_match : result().match_at(index);

      // Strip the keyword + leading space off the input.
      size_t prefix_length = match.template_url->keyword().length() + 1;
      ExtensionOmniboxEventRouter::OnInputEntered(
          profile_, match.template_url->GetExtensionId(),
          UTF16ToUTF8(match.fill_into_edit.substr(prefix_length)));
      view_->RevertAll();
      return;
    }

    if (template_url) {
      content::RecordAction(UserMetricsAction("AcceptedKeyword"));
      template_url_service->IncrementUsageCount(template_url);

      if (match.transition == content::PAGE_TRANSITION_KEYWORD ||
          match.transition == content::PAGE_TRANSITION_KEYWORD_GENERATED) {
        // NOTE: Non-prepopulated engines will all have ID 0, which is fine as
        // the prepopulate IDs start at 1.  Distribution-specific engines will
        // all have IDs above the maximum, and will be automatically lumped
        // together in an "overflow" bucket in the histogram.
        UMA_HISTOGRAM_ENUMERATION(
            "Omnibox.SearchEngine", template_url->prepopulate_id(),
            TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
      }
    }

    // NOTE: We purposefully don't increment the usage count of the default
    // search engine, if applicable; see comments in template_url.h.
  }

  if (match.transition == content::PAGE_TRANSITION_GENERATED &&
      match.template_url) {
    // See comment above.
    UMA_HISTOGRAM_ENUMERATION(
        "Omnibox.SearchEngine", match.template_url->prepopulate_id(),
        TemplateURLPrepopulateData::kMaxPrepopulatedEngineID);
  }

  if (disposition != NEW_BACKGROUND_TAB) {
    in_revert_ = true;
    view_->RevertAll();  // Revert the box to its unedited state
  }

  if (match.type == AutocompleteMatch::EXTENSION_APP) {
    LaunchAppFromOmnibox(match, profile_, disposition);
  } else {
    controller_->OnAutocompleteAccept(match.destination_url, disposition,
                                      match.transition, alternate_nav_url);
  }

  if (match.starred)
    bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX);

  InstantController* instant = controller_->GetInstant();
  if (instant && !popup_->IsOpen())
    instant->DestroyPreviewContents();
  in_revert_ = false;
}

bool AutocompleteEditModel::AcceptKeyword() {
  DCHECK(is_keyword_hint_ && !keyword_.empty());

  view_->OnBeforePossibleChange();
  view_->SetWindowTextAndCaretPos(string16(), 0);
  is_keyword_hint_ = false;
  view_->OnAfterPossibleChange();
  just_deleted_text_ = false;  // OnAfterPossibleChange() erroneously sets this
                               // since the edit contents have disappeared.  It
                               // doesn't really matter, but we clear it to be
                               // consistent.
  content::RecordAction(UserMetricsAction("AcceptedKeywordHint"));
  return true;
}

void AutocompleteEditModel::ClearKeyword(const string16& visible_text) {
  view_->OnBeforePossibleChange();
  const string16 window_text(keyword_ + visible_text);
  view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length());
  keyword_.clear();
  is_keyword_hint_ = false;
  view_->OnAfterPossibleChange();
  just_deleted_text_ = true;  // OnAfterPossibleChange() fails to clear this
                              // since the edit contents have actually grown
                              // longer.
}

const AutocompleteResult& AutocompleteEditModel::result() const {
  return autocomplete_controller_->result();
}

void AutocompleteEditModel::OnSetFocus(bool control_down) {
  has_focus_ = true;
  control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP;

  InstantController* instant = controller_->GetInstant();
  TabContentsWrapper* tab = controller_->GetTabContentsWrapper();
  if (instant && tab)
    instant->OnAutocompleteGotFocus(tab);
}

void AutocompleteEditModel::OnWillKillFocus(
    gfx::NativeView view_gaining_focus) {
  SetSuggestedText(string16(), INSTANT_COMPLETE_NOW);

  InstantController* instant = controller_->GetInstant();
  if (instant)
    instant->OnAutocompleteLostFocus(view_gaining_focus);
}

void AutocompleteEditModel::OnKillFocus() {
  has_focus_ = false;
  control_key_state_ = UP;
  paste_state_ = NONE;
}

bool AutocompleteEditModel::OnEscapeKeyPressed() {
  if (has_temporary_text_) {
    AutocompleteMatch match;
    InfoForCurrentSelection(&match, NULL);
    if (match.destination_url != original_url_) {
      RevertTemporaryText(true);
      return true;
    }
  }

  // If the user wasn't editing, but merely had focus in the edit, allow <esc>
  // to be processed as an accelerator, so it can still be used to stop a load.
  // When the permanent text isn't all selected we still fall through to the
  // SelectAll() call below so users can arrow around in the text and then hit
  // <esc> to quickly replace all the text; this matches IE.
  if (!user_input_in_progress_ && view_->IsSelectAll())
    return false;

  view_->RevertAll();
  view_->SelectAll(true);
  return true;
}

void AutocompleteEditModel::OnControlKeyChanged(bool pressed) {
  // Don't change anything unless the key state is actually toggling.
  if (pressed == (control_key_state_ == UP)) {
    ControlKeyState old_state = control_key_state_;
    control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
    if ((control_key_state_ == DOWN_WITHOUT_CHANGE) && has_temporary_text_) {
      // Arrowing down and then hitting control accepts the temporary text as
      // the input text.
      InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
      has_temporary_text_ = false;
      if (KeywordIsSelected())
        AcceptKeyword();
    }
    if ((old_state != DOWN_WITH_CHANGE) && popup_->IsOpen()) {
      // Autocomplete history provider results may change, so refresh the
      // popup.  This will force user_input_in_progress_ to true, but if the
      // popup is open, that should have already been the case.
      view_->UpdatePopup();
    }
  }
}

void AutocompleteEditModel::OnUpOrDownKeyPressed(int count) {
  // NOTE: This purposefully don't trigger any code that resets paste_state_.

  if (!popup_->IsOpen()) {
    if (!query_in_progress()) {
      // The popup is neither open nor working on a query already.  So, start an
      // autocomplete query for the current text.  This also sets
      // user_input_in_progress_ to true, which we want: if the user has started
      // to interact with the popup, changing the permanent_text_ shouldn't
      // change the displayed text.
      // Note: This does not force the popup to open immediately.
      // TODO(pkasting): We should, in fact, force this particular query to open
      // the popup immediately.
      if (!user_input_in_progress_)
        InternalSetUserText(permanent_text_);
      view_->UpdatePopup();
    } else {
      // TODO(pkasting): The popup is working on a query but is not open.  We
      // should force it to open immediately.
    }
  } else {
    // The popup is open, so the user should be able to interact with it
    // normally.
    popup_->Move(count);
  }
}

void AutocompleteEditModel::OnPopupDataChanged(
    const string16& text,
    GURL* destination_for_temporary_text_change,
    const string16& keyword,
    bool is_keyword_hint) {
  // Update keyword/hint-related local state.
  bool keyword_state_changed = (keyword_ != keyword) ||
      ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty());
  if (keyword_state_changed) {
    keyword_ = keyword;
    is_keyword_hint_ = is_keyword_hint;

    // |is_keyword_hint_| should always be false if |keyword_| is empty.
    DCHECK(!keyword_.empty() || !is_keyword_hint_);
  }

  // Handle changes to temporary text.
  if (destination_for_temporary_text_change != NULL) {
    const bool save_original_selection = !has_temporary_text_;
    if (save_original_selection) {
      // Save the original selection and URL so it can be reverted later.
      has_temporary_text_ = true;
      original_url_ = *destination_for_temporary_text_change;
      inline_autocomplete_text_.clear();
    }
    if (control_key_state_ == DOWN_WITHOUT_CHANGE) {
      // Arrowing around the popup cancels control-enter.
      control_key_state_ = DOWN_WITH_CHANGE;
      // Now things are a bit screwy: the desired_tld has changed, but if we
      // update the popup, the new order of entries won't match the old, so the
      // user's selection gets screwy; and if we don't update the popup, and the
      // user reverts, then the selected item will be as if control is still
      // pressed, even though maybe it isn't any more.  There is no obvious
      // right answer here :(
    }
    view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text),
                                       save_original_selection);
    return;
  }

  bool call_controller_onchanged = true;
  inline_autocomplete_text_ = text;
  if (view_->OnInlineAutocompleteTextMaybeChanged(
      DisplayTextFromUserText(user_text_ + inline_autocomplete_text_),
      DisplayTextFromUserText(user_text_).length()))
    call_controller_onchanged = false;

  // If |has_temporary_text_| is true, then we previously had a manual selection
  // but now don't (or |destination_for_temporary_text_change| would have been
  // non-NULL). This can happen when deleting the selected item in the popup.
  // In this case, we've already reverted the popup to the default match, so we
  // need to revert ourselves as well.
  if (has_temporary_text_) {
    RevertTemporaryText(false);
    call_controller_onchanged = false;
  }

  // We need to invoke OnChanged in case the destination url changed (as could
  // happen when control is toggled).
  if (call_controller_onchanged)
    OnChanged();
}

bool AutocompleteEditModel::OnAfterPossibleChange(
    const string16& new_text,
    size_t selection_start,
    size_t selection_end,
    bool selection_differs,
    bool text_differs,
    bool just_deleted_text,
    bool allow_keyword_ui_change) {
  // Update the paste state as appropriate: if we're just finishing a paste
  // that replaced all the text, preserve that information; otherwise, if we've
  // made some other edit, clear paste tracking.
  if (paste_state_ == PASTING)
    paste_state_ = PASTED;
  else if (text_differs)
    paste_state_ = NONE;

  // Modifying the selection counts as accepting the autocompleted text.
  const bool user_text_changed =
      text_differs || (selection_differs && !inline_autocomplete_text_.empty());

  // If something has changed while the control key is down, prevent
  // "ctrl-enter" until the control key is released.  When we do this, we need
  // to update the popup if it's open, since the desired_tld will have changed.
  if ((text_differs || selection_differs) &&
      (control_key_state_ == DOWN_WITHOUT_CHANGE)) {
    control_key_state_ = DOWN_WITH_CHANGE;
    if (!text_differs && !popup_->IsOpen())
      return false;  // Don't open the popup for no reason.
  } else if (!user_text_changed) {
    return false;
  }

  const string16 old_user_text = user_text_;
  // If the user text has not changed, we do not want to change the model's
  // state associated with the text.  Otherwise, we can get surprising behavior
  // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983
  if (user_text_changed) {
    InternalSetUserText(UserTextFromDisplayText(new_text));
    has_temporary_text_ = false;

    // Track when the user has deleted text so we won't allow inline
    // autocomplete.
    just_deleted_text_ = just_deleted_text;
  }

  const bool no_selection = selection_start == selection_end;

  // Update the popup for the change, in the process changing to keyword mode
  // if the user hit space in mid-string after a keyword.
  // |allow_exact_keyword_match_| will be used by StartAutocomplete() method,
  // which will be called by |view_->UpdatePopup()|. So we can safely clear
  // this flag afterwards.
  allow_exact_keyword_match_ =
      text_differs && allow_keyword_ui_change &&
      !just_deleted_text && no_selection &&
      ShouldAllowExactKeywordMatch(old_user_text, user_text_, selection_start);
  view_->UpdatePopup();
  allow_exact_keyword_match_ = false;

  // Change to keyword mode if the user has typed a keyword name and is now
  // pressing space after the name. Accepting the keyword will update our
  // state, so in that case there's no need to also return true here.
  return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
           no_selection && selection_start == user_text_.length() &&
           MaybeAcceptKeywordBySpace(old_user_text, user_text_));
}

void AutocompleteEditModel::PopupBoundsChangedTo(const gfx::Rect& bounds) {
  InstantController* instant = controller_->GetInstant();
  if (instant)
    instant->SetOmniboxBounds(bounds);
}

void AutocompleteEditModel::OnResultChanged(bool default_match_changed) {
  const bool was_open = popup_->IsOpen();
  if (default_match_changed) {
    string16 inline_autocomplete_text;
    string16 keyword;
    bool is_keyword_hint = false;
    const AutocompleteResult& result = this->result();
    const AutocompleteResult::const_iterator match(result.default_match());
    if (match != result.end()) {
      if ((match->inline_autocomplete_offset != string16::npos) &&
          (match->inline_autocomplete_offset <
           match->fill_into_edit.length())) {
        inline_autocomplete_text =
            match->fill_into_edit.substr(match->inline_autocomplete_offset);
      }

      if (!prerender::IsOmniboxEnabled(profile_))
        DoPreconnect(*match);

      // We could prefetch the alternate nav URL, if any, but because there
      // can be many of these as a user types an initial series of characters,
      // the OS DNS cache could suffer eviction problems for minimal gain.

      is_keyword_hint = popup_->GetKeywordForMatch(*match, &keyword);
    }
    popup_->OnResultChanged();
    OnPopupDataChanged(inline_autocomplete_text, NULL, keyword,
                       is_keyword_hint);
  } else {
    popup_->OnResultChanged();
  }

  if (popup_->IsOpen()) {
    PopupBoundsChangedTo(popup_->view()->GetTargetBounds());
  } else if (was_open) {
    // Accepts the temporary text as the user text, because it makes little
    // sense to have temporary text when the popup is closed.
    InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
    has_temporary_text_ = false;
    PopupBoundsChangedTo(gfx::Rect());
  }
}

bool AutocompleteEditModel::query_in_progress() const {
  return !autocomplete_controller_->done();
}

void AutocompleteEditModel::InternalSetUserText(const string16& text) {
  user_text_ = text;
  just_deleted_text_ = false;
  inline_autocomplete_text_.clear();
}

bool AutocompleteEditModel::KeywordIsSelected() const {
  return !is_keyword_hint_ && !keyword_.empty();
}

string16 AutocompleteEditModel::DisplayTextFromUserText(
    const string16& text) const {
  return KeywordIsSelected() ?
      KeywordProvider::SplitReplacementStringFromInput(text, false) : text;
}

string16 AutocompleteEditModel::UserTextFromDisplayText(
    const string16& text) const {
  return KeywordIsSelected() ? (keyword_ + char16(' ') + text) : text;
}

void AutocompleteEditModel::InfoForCurrentSelection(
    AutocompleteMatch* match,
    GURL* alternate_nav_url) const {
  DCHECK(match != NULL);
  const AutocompleteResult& result = this->result();
  if (!autocomplete_controller_->done()) {
    // It's technically possible for |result| to be empty if no provider returns
    // a synchronous result but the query has not completed synchronously;
    // pratically, however, that should never actually happen.
    if (result.empty())
      return;
    // The user cannot have manually selected a match, or the query would have
    // stopped.  So the default match must be the desired selection.
    *match = *result.default_match();
  } else {
    CHECK(popup_->IsOpen());
    // If there are no results, the popup should be closed (so we should have
    // failed the CHECK above), and URLsForDefaultMatch() should have been
    // called instead.
    CHECK(!result.empty());
    CHECK(popup_->selected_line() < result.size());
    *match = result.match_at(popup_->selected_line());
  }
  if (alternate_nav_url && popup_->manually_selected_match().empty())
    *alternate_nav_url = result.alternate_nav_url();
}

void AutocompleteEditModel::GetInfoForCurrentText(
    AutocompleteMatch* match,
    GURL* alternate_nav_url) const {
  if (popup_->IsOpen() || query_in_progress()) {
    InfoForCurrentSelection(match, alternate_nav_url);
  } else {
    profile_->GetAutocompleteClassifier()->Classify(
        UserTextFromDisplayText(view_->GetText()), GetDesiredTLD(),
        KeywordIsSelected(), true, match, alternate_nav_url);
  }
}

void AutocompleteEditModel::RevertTemporaryText(bool revert_popup) {
  // The user typed something, then selected a different item.  Restore the
  // text they typed and change back to the default item.
  // NOTE: This purposefully does not reset paste_state_.
  just_deleted_text_ = false;
  has_temporary_text_ = false;
  if (revert_popup)
    popup_->ResetToDefaultMatch();
  view_->OnRevertTemporaryText();
}

bool AutocompleteEditModel::MaybeAcceptKeywordBySpace(
    const string16& old_user_text,
    const string16& new_user_text) {
  return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() &&
      inline_autocomplete_text_.empty() && new_user_text.length() >= 2 &&
      IsSpaceCharForAcceptingKeyword(*new_user_text.rbegin()) &&
      !IsWhitespace(*(new_user_text.rbegin() + 1)) &&
      (old_user_text.length() + 1 >= new_user_text.length()) &&
      !new_user_text.compare(0, new_user_text.length() - 1, old_user_text,
                             0, new_user_text.length() - 1) &&
      AcceptKeyword();
}

bool AutocompleteEditModel::ShouldAllowExactKeywordMatch(
    const string16& old_user_text,
    const string16& new_user_text,
    size_t caret_position) {
  // Check simple conditions first.
  if (paste_state_ != NONE || caret_position < 2 ||
      new_user_text.length() <= caret_position ||
      old_user_text.length() < caret_position ||
      !IsSpaceCharForAcceptingKeyword(new_user_text[caret_position - 1]) ||
      IsSpaceCharForAcceptingKeyword(new_user_text[caret_position - 2]) ||
      new_user_text.compare(0, caret_position - 1, old_user_text,
                            0, caret_position - 1) ||
      !new_user_text.compare(caret_position - 1,
                             new_user_text.length() - caret_position + 1,
                             old_user_text, caret_position - 1,
                             old_user_text.length() - caret_position + 1)) {
    return false;
  }

  // Then check if the text before the inserted space matches a keyword.
  string16 keyword;
  TrimWhitespace(new_user_text.substr(0, caret_position - 1),
                 TRIM_LEADING, &keyword);

  // Only allow exact keyword match if |keyword| represents a keyword hint.
  return keyword.length() && popup_->GetKeywordForText(keyword, &keyword);
}

bool AutocompleteEditModel::DoInstant(const AutocompleteMatch& match,
                                      string16* suggested_text) {
  DCHECK(suggested_text);

  if (in_revert_)
    return false;

  InstantController* instant = controller_->GetInstant();

  if (!instant)
    return false;

  // It's possible the tab strip does not have an active tab contents, for
  // instance if the tab has been closed or on return from a sleep state
  // (http://crbug.com/105689)
  TabContentsWrapper* tab = controller_->GetTabContentsWrapper();
  if (!tab)
    return false;

  if (user_input_in_progress() && popup_->IsOpen()) {
    return instant->Update(tab, match, view_->GetText(), UseVerbatimInstant(),
                           suggested_text);
  }

  instant->Hide();
  return false;
}

void AutocompleteEditModel::DoPrerender(const AutocompleteMatch& match) {
  // Do not prerender if the destination URL is the same as the current URL.
  if (match.destination_url == PermanentURL())
    return;
  // It's possible the tab strip does not have an active tab contents, for
  // instance if the tab has been closed or on return from a sleep state
  // (http://crbug.com/105689)
  TabContentsWrapper* tab = controller_->GetTabContentsWrapper();
  if (!tab)
    return;
  prerender::PrerenderManager* prerender_manager =
      prerender::PrerenderManagerFactory::GetForProfile(tab->profile());
  if (prerender_manager) {
    RenderViewHost* current_host = tab->web_contents()->GetRenderViewHost();
    prerender_manager->AddPrerenderFromOmnibox(
        match.destination_url, current_host->session_storage_namespace());
  }
}

void AutocompleteEditModel::DoPreconnect(const AutocompleteMatch& match) {
  if (!match.destination_url.SchemeIs(chrome::kExtensionScheme)) {
    // Warm up DNS Prefetch cache, or preconnect to a search service.
    UMA_HISTOGRAM_ENUMERATION("Autocomplete.MatchType", match.type,
                              AutocompleteMatch::NUM_TYPES);
    if (profile_->GetNetworkPredictor()) {
      profile_->GetNetworkPredictor()->AnticipateOmniboxUrl(
          match.destination_url,
          NetworkActionPredictor::IsPreconnectable(match));
    }
    // We could prefetch the alternate nav URL, if any, but because there
    // can be many of these as a user types an initial series of characters,
    // the OS DNS cache could suffer eviction problems for minimal gain.
  }
}

//  static
bool AutocompleteEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) {
  switch (c) {
    case 0x0020:  // Space
    case 0x3000:  // Ideographic Space
      return true;
    default:
      return false;
  }
}


text:
package org.gradle.internal.watch.registry.impl;

import com.google.common.primitives.Longs;
import org.gradle.internal.watch.registry.FileWatcherProbeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Stream;

public class DefaultFileWatcherProbeRegistry implements FileWatcherProbeRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFileWatcherProbeRegistry.class);

    private final Map<File, WatchProbe> watchProbesByHierarchy = new ConcurrentHashMap<>();
    private final Map<String, WatchProbe> watchProbesByPath = new ConcurrentHashMap<>();

    private final Function<File, File> probeLocationResolver;

    public DefaultFileWatcherProbeRegistry(Function<File, File> probeLocationResolver) {
        this.probeLocationResolver = probeLocationResolver;
    }

    @Override
    public void registerProbe(File watchableHierarchy) {
        if (watchProbesByHierarchy.containsKey(watchableHierarchy)) {
            // Already registered
            return;
        }
        LOGGER.debug("Registering probe for {}", watchableHierarchy);
        File probeFile = probeLocationResolver.apply(watchableHierarchy);
        WatchProbe watchProbe = new WatchProbe(watchableHierarchy, probeFile);
        watchProbesByHierarchy.put(watchableHierarchy, watchProbe);
        watchProbesByPath.put(probeFile.getAbsolutePath(), watchProbe);
    }

    @Override
    public Stream<File> unprovenHierarchies() {
        return watchProbesByHierarchy.values().stream()
            .filter(WatchProbe::leftArmed)
            .map(WatchProbe::getWatchableHierarchy);
    }

    @Override
    public void armWatchProbe(File watchableHierarchy) {
        WatchProbe probe = watchProbesByHierarchy.get(watchableHierarchy);
        if (probe != null) {
            try {
                probe.arm();
            } catch (IOException e) {
                LOGGER.debug("Could not arm watch probe for hierarchy {}", watchableHierarchy, e);
            }
        } else {
            LOGGER.debug("Did not find watchable hierarchy to arm probe for: {}", watchableHierarchy);
        }
    }

    @Override
    public void disarmWatchProbe(File watchableHierarchy) {
        WatchProbe probe = watchProbesByHierarchy.get(watchableHierarchy);
        if (probe != null) {
            probe.disarm();
        } else {
            LOGGER.debug("Did not find watchable hierarchy to disarm probe for: {}", watchableHierarchy);
        }
    }

    /**
     * Triggers a watch probe at the given location if one exists.
     */
    @Override
    public void triggerWatchProbe(String path) {
        WatchProbe probe = watchProbesByPath.get(path);
        if (probe != null) {
            LOGGER.debug("Triggering watch probe for {}", probe.getWatchableHierarchy());
            probe.trigger();
        }
    }

    @Override
    public File getProbeDirectory(File hierarchy) {
        WatchProbe watchProbe = watchProbesByHierarchy.get(hierarchy);
        if (watchProbe == null) {
            throw new IllegalStateException("Cannot find probe for hierarchy: " + hierarchy);
        }
        return watchProbe.getProbeFile().getParentFile();
    }

    private static class WatchProbe {
        public enum State {
            /**
             * Probe hasn't been armed yet.
             */
            UNARMED,

            /**
             * Probe file exists, waiting for event to arrive.
             */
            ARMED,

            /**
             * The expected event has arrived.
             */
            TRIGGERED
        }

        private final File watchableHierarchy;
        private final File probeFile;
        private State state = State.UNARMED;

        public WatchProbe(File watchableHierarchy, File probeFile) {
            this.watchableHierarchy = watchableHierarchy;
            this.probeFile = probeFile;
        }

        public synchronized void arm() throws IOException {
            switch (state) {
                case UNARMED:
                    state = State.ARMED;
                    //noinspection ResultOfMethodCallIgnored
                    probeFile.getParentFile().mkdirs();
                    try (FileOutputStream out = new FileOutputStream(probeFile)) {
                        out.write(Longs.toByteArray(System.currentTimeMillis()));
                    }
                    LOGGER.debug("Watch probe has been armed for hierarchy: {}", watchableHierarchy);
                    break;
                case ARMED:
                    LOGGER.debug("Watch probe for hierarchy is already armed: {}", watchableHierarchy);
                    break;
                case TRIGGERED:
                    LOGGER.debug("Watch probe for hierarchy has already been triggered: {}", watchableHierarchy);
                    break;
                default:
                    throw new AssertionError();
            }
        }

        public synchronized void disarm() {
            switch (state) {
                case UNARMED:
                    LOGGER.debug("Watch probe has already been disarmed for hierarchy: {}", watchableHierarchy);
                    break;
                case ARMED:
                    state = State.UNARMED;
                    LOGGER.debug("Watch probe has been disarmed for hierarchy: {}", watchableHierarchy);
                    break;
                case TRIGGERED:
                    LOGGER.debug("Watch probe has already been triggered for hierarchy: {}", watchableHierarchy);
                    break;
            }
        }

        public synchronized void trigger() {
            if (state != State.TRIGGERED) {
                LOGGER.debug("Watch probe in state {} has been triggered for hierarchy: {}", state, watchableHierarchy);
                state = State.TRIGGERED;
            }
        }

        public synchronized boolean leftArmed() {
            return state == State.ARMED;
        }

        public File getProbeFile() {
            return probeFile;
        }

        public File getWatchableHierarchy() {
            return watchableHierarchy;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Input } from '@angular/core';
import { MainAndNavComponent } from './components/main-and-nav/main-and-nav.component';
import { Component } from '@angular/core';

@Component({
    selector: 'linnovate-ng-charts',
    templateUrl: 'linnovate-ng-charts.component.html',
    styleUrls: ['linnovate-ng-charts.component.scss']
})
export class LinnovateNgChartsComponent {
  public chart = MainAndNavComponent;
  @Input() public options: any;
  @Input() public data: any[];
}


text:
/*---------------------------------------------------------------------------
HUD ConVars
---------------------------------------------------------------------------*/
local ConVars = {}
local HUDWidth
local HUDHeight

local Color = Color
local CurTime = CurTime
local cvars = cvars
local DarkRP = DarkRP
local draw = draw
local GetConVar = GetConVar
local hook = hook
local IsValid = IsValid
local Lerp = Lerp
local localplayer
local math = math
local pairs = pairs
local ScrW, ScrH = ScrW, ScrH
local SortedPairs = SortedPairs
local string = string
local surface = surface
local table = table
local timer = timer
local tostring = tostring
local plyMeta = FindMetaTable("Player")

local colors = {}
colors.black = Color(0, 0, 0, 255)
colors.blue = Color(0, 0, 255, 255)
colors.brightred = Color(200, 30, 30, 255)
colors.darkred = Color(0, 0, 70, 100)
colors.darkblack = Color(0, 0, 0, 200)
colors.gray1 = Color(0, 0, 0, 155)
colors.gray2 = Color(51, 58, 51,100)
colors.red = Color(255, 0, 0, 255)
colors.white = Color(255, 255, 255, 255)
colors.white1 = Color(255, 255, 255, 200)

local function ReloadConVars()
    ConVars = {
        background = {0,0,0,100},
        Healthbackground = {0,0,0,200},
        Healthforeground = {140,0,0,180},
        HealthText = {255,255,255,200},
        Job1 = {0,0,150,200},
        Job2 = {0,0,0,255},
        salary1 = {0,150,0,200},
        salary2 = {0,0,0,255}
    }

    for name, Colour in pairs(ConVars) do
        ConVars[name] = {}
        for num, rgb in SortedPairs(Colour) do
            local CVar = GetConVar(name .. num) or CreateClientConVar(name .. num, rgb, true, false)
            table.insert(ConVars[name], CVar:GetInt())

            if not cvars.GetConVarCallbacks(name .. num, false) then
                cvars.AddChangeCallback(name .. num, function()
                    timer.Simple(0, ReloadConVars)
                end)
            end
        end
        ConVars[name] = Color(unpack(ConVars[name]))
    end

    HUDWidth = (GetConVar("HudW") or  CreateClientConVar("HudW", 240, true, false)):GetInt()
    HUDHeight = (GetConVar("HudH") or CreateClientConVar("HudH", 115, true, false)):GetInt()

    if not cvars.GetConVarCallbacks("HudW", false) and not cvars.GetConVarCallbacks("HudH", false) then
        cvars.AddChangeCallback("HudW", function() timer.Simple(0,ReloadConVars) end)
        cvars.AddChangeCallback("HudH", function() timer.Simple(0,ReloadConVars) end)
    end
end
ReloadConVars()

local Scrw, Scrh, RelativeX, RelativeY
/*---------------------------------------------------------------------------
HUD separate Elements
---------------------------------------------------------------------------*/
local Health = 0
local function DrawHealth()
    local maxHealth = localplayer:GetMaxHealth()
    local myHealth = localplayer:Health()
    Health = math.min(maxHealth, (Health == myHealth and Health) or Lerp(0.1, Health, myHealth))

    local healthRatio = math.Min(Health / maxHealth, 1)
    local rounded = math.Round(3 * healthRatio)
    local Border = math.Min(6, rounded * rounded)
    draw.RoundedBox(Border, RelativeX + 4, RelativeY - 30, HUDWidth - 8, 20, ConVars.Healthbackground)
    draw.RoundedBox(Border, RelativeX + 5, RelativeY - 29, (HUDWidth - 9) * healthRatio, 18, ConVars.Healthforeground)

    draw.DrawNonParsedText(math.Max(0, math.Round(myHealth)), "DarkRPHUD2", RelativeX + 4 + (HUDWidth - 8) / 2, RelativeY - 32, ConVars.HealthText, 1)

    -- Armor
    local armor = localplayer:Armor()
    if armor ~= 0 then
        draw.RoundedBox(2, RelativeX + 4, RelativeY - 15, (HUDWidth - 8) * armor / 100, 5, colors.blue)
    end
end

local salaryText, JobWalletText
local function DrawInfo()
    salaryText = salaryText or DarkRP.getPhrase("salary", DarkRP.formatMoney(localplayer:getDarkRPVar("salary")), "")

    JobWalletText = JobWalletText or string.format("%s\n%s",
        DarkRP.getPhrase("job", localplayer:getDarkRPVar("job") or ""),
        DarkRP.getPhrase("wallet", DarkRP.formatMoney(localplayer:getDarkRPVar("money")), "")
    )

    draw.DrawNonParsedText(salaryText, "DarkRPHUD2", RelativeX + 5, RelativeY - HUDHeight + 6, ConVars.salary1, 0)
    draw.DrawNonParsedText(salaryText, "DarkRPHUD2", RelativeX + 4, RelativeY - HUDHeight + 5, ConVars.salary2, 0)

    surface.SetFont("DarkRPHUD2")
    local _, h = surface.GetTextSize(salaryText)

    draw.DrawNonParsedText(JobWalletText, "DarkRPHUD2", RelativeX + 5, RelativeY - HUDHeight + h + 6, ConVars.Job1, 0)
    draw.DrawNonParsedText(JobWalletText, "DarkRPHUD2", RelativeX + 4, RelativeY - HUDHeight + h + 5, ConVars.Job2, 0)
end

local Page = Material("icon16/page_white_text.png")
local function GunLicense()
    if localplayer:getDarkRPVar("HasGunlicense") then
        surface.SetMaterial(Page)
        surface.SetDrawColor(255, 255, 255, 255)
        surface.DrawTexturedRect(RelativeX + HUDWidth, Scrh - 34, 32, 32)
    end
end

local agendaText
local function Agenda()
    local shouldDraw = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_Agenda")
    if shouldDraw == false then return end

    local agenda = localplayer:getAgendaTable()
    if not agenda then return end
    agendaText = agendaText or DarkRP.textWrap((localplayer:getDarkRPVar("agenda") or ""):gsub("//", "\n"):gsub("\\n", "\n"), "DarkRPHUD1", 440)

    draw.RoundedBox(10, 10, 10, 460, 110, colors.gray1)
    draw.RoundedBox(10, 12, 12, 456, 106, colors.gray2)
    draw.RoundedBox(10, 12, 12, 456, 20, colors.darkred)

    draw.DrawNonParsedText(agenda.Title, "DarkRPHUD1", 30, 12, colors.red, 0)
    draw.DrawNonParsedText(agendaText, "DarkRPHUD1", 30, 35, colors.white, 0)
end

hook.Add("DarkRPVarChanged", "agendaHUD", function(ply, var, _, new)
    if ply ~= localplayer then return end
    if var == "agenda" and new then
        agendaText = DarkRP.textWrap(new:gsub("//", "\n"):gsub("\\n", "\n"), "DarkRPHUD1", 440)
    else
        agendaText = nil
    end

    if var == "salary" then
        salaryText = DarkRP.getPhrase("salary", DarkRP.formatMoney(new), "")
    end

    if var == "job" or var == "money" then
        JobWalletText = string.format("%s\n%s",
            DarkRP.getPhrase("job", var == "job" and new or localplayer:getDarkRPVar("job") or ""),
            DarkRP.getPhrase("wallet", var == "money" and DarkRP.formatMoney(new) or DarkRP.formatMoney(localplayer:getDarkRPVar("money")), "")
        )
    end
end)

local VoiceChatTexture = surface.GetTextureID("voice/icntlk_pl")
local function DrawVoiceChat()
    if localplayer.DRPIsTalking then
        local _, chboxY = chat.GetChatBoxPos()

        local Rotating = math.sin(CurTime() * 3)
        local backwards = 0

        if Rotating < 0 then
            Rotating = 1 - (1 + Rotating)
            backwards = 180
        end

        surface.SetTexture(VoiceChatTexture)
        surface.SetDrawColor(ConVars.Healthforeground)
        surface.DrawTexturedRectRotated(Scrw - 100, chboxY, Rotating * 96, 96, backwards)
    end
end

local function LockDown()
    local chbxX, chboxY = chat.GetChatBoxPos()
    if GetGlobalBool("DarkRP_LockDown") then
        local shouldDraw = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_LockdownHUD")
        if shouldDraw == false then return end
        local cin = (math.sin(CurTime()) + 1) / 2
        local chatBoxSize = math.floor(Scrh / 4)
        draw.DrawNonParsedText(DarkRP.getPhrase("lockdown_started"), "ScoreboardSubtitle", chbxX, chboxY + chatBoxSize, Color(cin * 255, 0, 255 - (cin * 255), 255), TEXT_ALIGN_LEFT)
    end
end

local Arrested = function() end

usermessage.Hook("GotArrested", function(msg)
    local StartArrested = CurTime()
    local ArrestedUntil = msg:ReadFloat()

    Arrested = function()
        local shouldDraw = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_ArrestedHUD")
        if shouldDraw == false then return end

        if CurTime() - StartArrested <= ArrestedUntil and localplayer:getDarkRPVar("Arrested") then
            draw.DrawNonParsedText(DarkRP.getPhrase("youre_arrested", math.ceil(ArrestedUntil - (CurTime() - StartArrested))), "DarkRPHUD1", Scrw / 2, Scrh - Scrh / 12, colors.white, 1)
        elseif not localplayer:getDarkRPVar("Arrested") then
            Arrested = function() end
        end
    end
end)

local AdminTell = function() end

usermessage.Hook("AdminTell", function(msg)
    timer.Remove("DarkRP_AdminTell")
    local Message = msg:ReadString()

    AdminTell = function()
        draw.RoundedBox(4, 10, 10, Scrw - 20, 110, colors.darkblack)
        draw.DrawNonParsedText(DarkRP.getPhrase("listen_up"), "GModToolName", Scrw / 2 + 10, 10, colors.white, 1)
        draw.DrawNonParsedText(Message, "ChatFont", Scrw / 2 + 10, 90, colors.brightred, 1)
    end

    timer.Create("DarkRP_AdminTell", 10, 1, function()
        AdminTell = function() end
    end)
end)

/*---------------------------------------------------------------------------
Drawing the HUD elements such as Health etc.
---------------------------------------------------------------------------*/
local function DrawHUD()
    local shouldDraw = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_HUD")
    if shouldDraw == false then return end

    Scrw, Scrh = ScrW(), ScrH()
    RelativeX, RelativeY = 0, Scrh

    shouldDraw = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_LocalPlayerHUD")
    shouldDraw = shouldDraw ~= false
    if shouldDraw then
        --Background
        draw.RoundedBox(6, 0, Scrh - HUDHeight, HUDWidth, HUDHeight, ConVars.background)
        DrawHealth()
        DrawInfo()
        GunLicense()
    end
    Agenda()
    DrawVoiceChat()
    LockDown()

    Arrested()
    AdminTell()
end

/*---------------------------------------------------------------------------
Entity HUDPaint things
---------------------------------------------------------------------------*/
-- Draw a player's name, health and/or job above the head
-- This syntax allows for easy overriding
plyMeta.drawPlayerInfo = plyMeta.drawPlayerInfo or function(self)
    local pos = self:EyePos()

    pos.z = pos.z + 10 -- The position we want is a bit above the position of the eyes
    pos = pos:ToScreen()
    if not self:getDarkRPVar("wanted") then
        -- Move the text up a few pixels to compensate for the height of the text
        pos.y = pos.y - 50
    end

    if GAMEMODE.Config.showname then
        local nick, plyTeam = self:Nick(), self:Team()
        draw.DrawNonParsedText(nick, "DarkRPHUD2", pos.x + 1, pos.y + 1, colors.black, 1)
        draw.DrawNonParsedText(nick, "DarkRPHUD2", pos.x, pos.y, RPExtraTeams[plyTeam] and RPExtraTeams[plyTeam].color or team.GetColor(plyTeam) , 1)
    end

    if GAMEMODE.Config.showhealth then
        local health = DarkRP.getPhrase("health", self:Health())
        draw.DrawNonParsedText(health, "DarkRPHUD2", pos.x + 1, pos.y + 21, colors.black, 1)
        draw.DrawNonParsedText(health, "DarkRPHUD2", pos.x, pos.y + 20, colors.white1, 1)
    end

    if GAMEMODE.Config.showjob then
        local teamname = self:getDarkRPVar("job") or team.GetName(self:Team())
        draw.DrawNonParsedText(teamname, "DarkRPHUD2", pos.x + 1, pos.y + 41, colors.black, 1)
        draw.DrawNonParsedText(teamname, "DarkRPHUD2", pos.x, pos.y + 40, colors.white1, 1)
    end

    if self:getDarkRPVar("HasGunlicense") then
        surface.SetMaterial(Page)
        surface.SetDrawColor(255,255,255,255)
        surface.DrawTexturedRect(pos.x-16, pos.y + 60, 32, 32)
    end
end

-- Draw wanted information above a player's head
-- This syntax allows for easy overriding
plyMeta.drawWantedInfo = plyMeta.drawWantedInfo or function(self)
    if not self:Alive() then return end

    local pos = self:EyePos()
    if not pos:isInSight({localplayer, self}) then return end

    pos.z = pos.z + 10
    pos = pos:ToScreen()

    if GAMEMODE.Config.showname then
        local nick, plyTeam = self:Nick(), self:Team()
        draw.DrawNonParsedText(nick, "DarkRPHUD2", pos.x + 1, pos.y + 1, colors.black, 1)
        draw.DrawNonParsedText(nick, "DarkRPHUD2", pos.x, pos.y, RPExtraTeams[plyTeam] and RPExtraTeams[plyTeam].color or team.GetColor(plyTeam) , 1)
    end

    local wantedText = DarkRP.getPhrase("wanted", tostring(self:getDarkRPVar("wantedReason")))

    draw.DrawNonParsedText(wantedText, "DarkRPHUD2", pos.x, pos.y - 40, colors.white1, 1)
    draw.DrawNonParsedText(wantedText, "DarkRPHUD2", pos.x + 1, pos.y - 41, colors.red, 1)
end

/*---------------------------------------------------------------------------
The Entity display: draw HUD information about entities
---------------------------------------------------------------------------*/
local function DrawEntityDisplay()
    local shouldDraw, players = hook.Call("HUDShouldDraw", GAMEMODE, "DarkRP_EntityDisplay")
    if shouldDraw == false then return end

    local shootPos = localplayer:GetShootPos()
    local aimVec = localplayer:GetAimVector()

    for k, ply in pairs(players or player.GetAll()) do
        if ply == localplayer or not ply:Alive() or ply:GetNoDraw() then continue end
        local hisPos = ply:GetShootPos()
        if ply:getDarkRPVar("wanted") then ply:drawWantedInfo() end

        if GAMEMODE.Config.globalshow then
            ply:drawPlayerInfo()
        -- Draw when you're (almost) looking at him
        elseif hisPos:DistToSqr(shootPos) < 160000 then
            local pos = hisPos - shootPos
            local unitPos = pos:GetNormalized()
            if unitPos:Dot(aimVec) > 0.95 then
                local trace = util.QuickTrace(shootPos, pos, localplayer)
                if trace.Hit and trace.Entity ~= ply then break end
                ply:drawPlayerInfo()
            end
        end
    end

    local tr = localplayer:GetEyeTrace()

    if IsValid(tr.Entity) and tr.Entity:isKeysOwnable() and tr.Entity:GetPos():DistToSqr(localplayer:GetPos()) < 40000 then
        tr.Entity:drawOwnableInfo()
    end
end

/*---------------------------------------------------------------------------
Drawing death notices
---------------------------------------------------------------------------*/
function GM:DrawDeathNotice(x, y)
    if not GAMEMODE.Config.showdeaths then return end
    self.Sandbox.DrawDeathNotice(self, x, y)
end

/*---------------------------------------------------------------------------
Display notifications
---------------------------------------------------------------------------*/
local function DisplayNotify(msg)
    local txt = msg:ReadString()
    GAMEMODE:AddNotify(txt, msg:ReadShort(), msg:ReadLong())
    surface.PlaySound("buttons/lightswitch2.wav")

    -- Log to client console
    MsgC(Color(255, 20, 20, 255), "[DarkRP] ", Color(200, 200, 200, 255), txt, "\n")
end
usermessage.Hook("_Notify", DisplayNotify)

/*---------------------------------------------------------------------------
Remove some elements from the HUD in favour of the DarkRP HUD
---------------------------------------------------------------------------*/
function GM:HUDShouldDraw(name)
    if name == "CHudHealth" or
        name == "CHudBattery" or
        name == "CHudSuitPower" or
        (HelpToggled and name == "CHudChat") then
            return false
    else
        return self.Sandbox.HUDShouldDraw(self, name)
    end
end

/*---------------------------------------------------------------------------
Disable players' names popping up when looking at them
---------------------------------------------------------------------------*/
function GM:HUDDrawTargetID()
    return false
end

/*---------------------------------------------------------------------------
Actual HUDPaint hook
---------------------------------------------------------------------------*/
function GM:HUDPaint()
    localplayer = localplayer and IsValid(localplayer) and localplayer or LocalPlayer()
    if not IsValid(localplayer) then return end

    DrawHUD()
    DrawEntityDisplay()

    self.Sandbox.HUDPaint(self)
end


text:
package main

import (
	"fmt"
	"net"
	"os"
	"strconv"
)

//Target is a host (IP & port)
type Target struct {
	host net.IP
	port int
}

func main() {
	if len(os.Args) <= 1 {
		usage()
		os.Exit(0)
	}

	var showHelp,
		udpConnection,
		hostSet,
		portSet bool

	target := Target{}

	for _, arg := range os.Args[1:] {
		switch arg {
		case "-h":
			showHelp = true
			break
		case "--help":
			showHelp = true
			break
		}
		if !hostSet { //avoid duplicates arguments
			hostSet = target.validHost(arg)
		}
		if !portSet { //avoid duplicates arguments
			portSet = target.validPort(arg)
		}
	}

	if showHelp {
		help()
		os.Exit(0)
	}
	if hostSet && portSet {
		if udpConnection {
			target.UDP()
		} else {
			target.TCP()
		}
	}
	if !showHelp && !udpConnection && (!hostSet || !portSet) {
		usage()
		os.Exit(0)
	}
}

//UDP connection
func (target *Target) UDP() {
	port := strconv.Itoa(target.port)
	conn, err := net.Dial("udp", target.host.String()+":"+port)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer conn.Close()
	//TODO Complete
}

//TCP connection, set by default
func (target *Target) TCP() {
	port := strconv.Itoa(target.port)
	conn, err := net.Dial("tcp", target.host.String()+":"+port)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer conn.Close()
	//TODO Complete
}

//validHost return true if is a valid host (IPv4, IPv6 or DNS)
func (target *Target) validHost(host string) bool {
	//TODO Check if a host is a DNS
	target.host = net.ParseIP(host)
	if target.host != nil {
		return true
	}
	return false
}

//validPort return true if is a valid port (a number between 1-65535)
func (target *Target) validPort(port string) bool {
	p, err := strconv.Atoi(port)
	if err != nil || (p < 1 || p > 65535) {
		return false
	}
	target.port = p
	return true
}

func help() {
	//TODO Complete
	fmt.Println("Help")
}

func usage() {
	//TODO Complete
	fmt.Println("Usage")
}


text:
package org.finra.jtaf.core.parsing.exceptions;

import javax.xml.xpath.XPathException;

/**
 * This is a wrapper for XPath exceptions.
 *
 */
public class NestedXPathException extends ParsingException {

	/**
	 * AUTO-GENERATED
	 */
	private static final long serialVersionUID = -6483364508583432000L;

	/**
	 * @param e The wrapped XPath
	 */
	public NestedXPathException(XPathException e) {
		super(e);
	}
}


text:
package main

import (
	"k8s.io/kubernetes/pkg/util/flag"
	"k8s.io/kubernetes/pkg/util/logs"
	"k8s.io/kubernetes/pkg/version/verflag"
	"k8s.io/kubernetes/plugin/cmd/kube-scheduler/app"
	"k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options"

	"github.com/golang/glog"
	"github.com/spf13/pflag"
)

func main() {
	s := options.NewSchedulerServer()
	s.AddFlags(pflag.CommandLine)

	flag.InitFlags()
	logs.InitLogs()
	defer logs.FlushLogs()

	verflag.PrintAndExitIfRequested()

	if err := app.Run(s); err != nil {
		glog.Fatalf("scheduler app failed to run: %v", err)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

using SocialNetwork.ConsoleClient.XmlDeserializers.Models;
using SocialNetwork.Data;
using SocialNetwork.Models;

namespace SocialNetwork.ConsoleClient.XmlDeserializers
{
    public class XmlToSqlModelConverter
    {
        private readonly Func<SocialNetworkContext> contextCreator;

        public XmlToSqlModelConverter(Func<SocialNetworkContext> contextCreator)
        {
            this.contextCreator = contextCreator;
        }

        public void ConvertXmlPostToSqlPost(IEnumerable<XmlPost> xmlPosts)
        {
            var context = this.contextCreator();
            var postsCount = 0;

            foreach (var post in xmlPosts)
            {
                postsCount++;
                Console.WriteLine($"Post {postsCount}");

                var newPost = new Post();
                newPost.Content = post.Content;
                newPost.PostedOn = post.PostedOn;

                var userList = post.Users.Split(',').Select(u => u.Trim());

                var users = context.Users
                    .Where(u => userList.Contains(u.Username))
                    .ToList();

                newPost.TaggedUsers = users;

                if (postsCount % 100 == 0)
                {
                    context.SaveChanges();
                    context = this.contextCreator();
                }
            }
        }

        public void ConvertXmlFriendshipToSqlFriendship(IEnumerable<XmlFriendship> xmlFriendships)
        {
            if (xmlFriendships == null)
            {
                throw new ArgumentNullException(nameof(xmlFriendships));
            }

            var context = this.contextCreator();

            var friendshipCount = 0;
            foreach (var friendship in xmlFriendships)
            {
                friendshipCount++;
                Console.WriteLine($"Friendship {friendshipCount}");

                var newFriendship = new Friendship();
                newFriendship.Approved = friendship.Approved;
                newFriendship.FriendsSince = friendship.FriendsSince.HasValue ?
                    friendship.FriendsSince.Value : DateTime.Now;

                var firstUser = this.ConvertXmlUserToSqlUser(friendship.FirstUser, context);
                newFriendship.UserA = firstUser;

                var secondUser = this.ConvertXmlUserToSqlUser(friendship.SecondUser, context);
                newFriendship.UserB = secondUser;

                foreach (var message in friendship.Messages)
                {
                    var convertedMessages = this.ConvertXmlMessageToSqlMessage(message, firstUser, secondUser);
                    newFriendship.Messages.Add(convertedMessages);
                }

                context.Friendships.Add(newFriendship);

                if (friendshipCount % 50 == 0)
                {
                    context.SaveChanges();
                    context = this.contextCreator();
                }
            }

            context.SaveChanges();
        }

        public User ConvertXmlUserToSqlUser(XmlUser user, SocialNetworkContext context)
        {
            var localUser = context.Users.Local
                .Where(u => u.Username == user.Username)
                .FirstOrDefault();

            if (localUser != null)
            {
                return localUser;
            }

            var dbUser = context.Users
                .Where(u => u.Username == user.Username)
                .FirstOrDefault();

            if (dbUser != null)
            {
                return dbUser;
            }

            var newUser = new User();
            newUser.Username = user.Username;
            newUser.FirstName = user.FirstName;
            newUser.LastName = user.LastName;
            newUser.RegisteredOn = user.RegisteredOn;

            foreach (var image in user.Images)
            {
                var convertedImage = this.ConvertXmlImageToSqlImage(image);
                newUser.Images.Add(convertedImage);
            }

            return newUser;
        }

        public Image ConvertXmlImageToSqlImage(XmlImage image)
        {
            var newImage = new Image();
            newImage.ImageUrl = image.ImageUrl;
            newImage.FileExtension = image.FileExtension;

            return newImage;
        }

        public Message ConvertXmlMessageToSqlMessage(XmlMessage message, User first, User second)
        {
            var newMessage = new Message();
            newMessage.Author = first.Username == message.Author ? first : second;
            newMessage.Content = message.Content;
            newMessage.SentOn = message.SentOn;
            newMessage.SeenOn = message.SeenOn;

            return newMessage;
        }
    }
}


text:
package org.apache.syncope.client.ui.commons.panels;

import com.googlecode.wicket.jquery.core.Options;
import com.googlecode.wicket.kendo.ui.widget.notification.Notification;
import java.util.List;
import org.apache.syncope.client.ui.commons.Constants;
import org.apache.syncope.client.ui.commons.StyledNotificationBehavior;
import org.apache.wicket.IGenericComponent;
import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.FeedbackMessagesModel;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

public class NotificationPanel extends Panel
        implements IFeedback, IGenericComponent<List<FeedbackMessage>, NotificationPanel> {

    private static final long serialVersionUID = 5895940553202128621L;

    private final Notification notification;

    public NotificationPanel(final String id) {
        super(id);

        Options options = new Options();
        options.set("appendTo", "'#appendto'");
        options.set("stacking", "'up'");
        options.set("templates",
                "[ { type: 'success', template: $('#successTemplate').html() },"
                + " { type: 'info', template: $('#infoTemplate').html() },"
                + " { type: 'error', template: $('#errorTemplate').html() },"
                + " { type: 'warning', template: $('#warningTemplate').html() } ] ");

        notification = new Notification(Constants.FEEDBACK, options) {

            private static final long serialVersionUID = 785830249476640904L;

            @Override
            public StyledNotificationBehavior newWidgetBehavior(final String selector) {
                return new StyledNotificationBehavior(selector, options);
            }
        };

        add(notification);
    }

    public final void hide(final IPartialPageRequestHandler handler) {
        this.notification.hide(handler);
    }

    public final void refresh(final IPartialPageRequestHandler handler) {
        this.getModelObject().forEach(message -> {
            if (message.isError()) {
                this.notification.error(handler, message.getMessage());
            } else if (message.isWarning()) {
                // this is necessary before check for success and info in order to show warnings: isSuccess and isInfo
                // return true also in case of warnings ...
                this.notification.warn(handler, message.getMessage());
            } else if (message.isSuccess()) {
                this.notification.success(handler, message.getMessage());
            } else if (message.isInfo()) {
                this.notification.info(handler, message.getMessage());
            } else {
                this.notification.warn(handler, message.getMessage());
            }
            message.markRendered();
        });
    }

    @Override
    protected IModel<?> initModel() {
        return new FeedbackMessagesModel(this);
    }

    @Override
    @SuppressWarnings("unchecked")
    public IModel<List<FeedbackMessage>> getModel() {
        return (IModel<List<FeedbackMessage>>) this.getDefaultModel();
    }

    @Override
    public NotificationPanel setModel(final IModel<List<FeedbackMessage>> model) {
        this.setDefaultModel(model);
        return this;
    }

    @Override
    public NotificationPanel setModelObject(final List<FeedbackMessage> object) {
        this.setDefaultModelObject(object);
        return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<FeedbackMessage> getModelObject() {
        return (List<FeedbackMessage>) this.getDefaultModelObject();
    }

    public String getNotificationMarkupId() {
        return this.notification.getMarkupId();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<extension
	type="module"
	version="3.1"
	client="site"
	method="upgrade">
	<name>mod_articles_popular</name>
	<author>Joomla! Project</author>
	<creationDate>July 2006</creationDate>
	<copyright>Copyright (C) 2005 - 2013 Open Source Matters. All rights reserved.</copyright>
	<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
	<authorEmail>admin@joomla.org</authorEmail>
	<authorUrl>www.joomla.org</authorUrl>
	<version>3.0.0</version>
	<description>MOD_POPULAR_XML_DESCRIPTION</description>
	<files>
		<filename module="mod_articles_popular">mod_articles_popular.php</filename>
		<folder>tmpl</folder>
		<filename>helper.php</filename>
		<filename>index.html</filename>
		<filename>mod_articles_popular.xml</filename>
	</files>
	<languages>
		<language tag="en-GB">en-GB.mod_articles_popular.ini</language>
		<language tag="en-GB">en-GB.mod_articles_popular.sys.ini</language>
	</languages>
	<help key="JHELP_EXTENSIONS_MODULE_MANAGER_MOST_READ" />
	<config>
		<fields name="params">
			<fieldset name="basic">

				<field
					name="catid"
					type="category"
					extension="com_content"
					multiple="true"
					size="10"
					default=""
					label="JCATEGORY"
					description="MOD_POPULAR_FIELD_CATEGORY_DESC" >
					<option value="">JOPTION_ALL_CATEGORIES</option>
				</field>

				<field
					name="count"
					type="text"
					default="5"
					label="MOD_POPULAR_FIELD_COUNT_LABEL"
					description="MOD_POPULAR_FIELD_COUNT_DESC" />

					<field
					name="show_front"
					type="radio"
					class="btn-group btn-group-yesno"
					default="1"
					label="MOD_POPULAR_FIELD_FEATURED_LABEL"
					description="MOD_POPULAR_FIELD_FEATURED_DESC">
					<option
						value="1">JSHOW</option>
					<option
						value="0">JHIDE</option>
				</field>

			</fieldset>

			<fieldset
				name="advanced">

				<field
					name="layout"
					type="modulelayout"
					label="JFIELD_ALT_LAYOUT_LABEL"
					description="JFIELD_ALT_MODULE_LAYOUT_DESC" />

				<field
					name="moduleclass_sfx"
					type="textarea" rows="3"
					label="COM_MODULES_FIELD_MODULECLASS_SFX_LABEL"
					description="COM_MODULES_FIELD_MODULECLASS_SFX_DESC" />

				<field
					name="cache"
					type="list"
					default="1"
					label="COM_MODULES_FIELD_CACHING_LABEL"
					description="COM_MODULES_FIELD_CACHING_DESC">
					<option
						value="1">JGLOBAL_USE_GLOBAL</option>
					<option
						value="0">COM_MODULES_FIELD_VALUE_NOCACHING</option>
				</field>

				<field
					name="cache_time"
					type="text"
					default="900"
					label="COM_MODULES_FIELD_CACHE_TIME_LABEL"
					description="COM_MODULES_FIELD_CACHE_TIME_DESC" />

				<field
					name="cachemode"
					type="hidden"
					default="static">
					<option
						value="static"></option>
				</field>

			</fieldset>
		</fields>
	</config>
</extension>


text: """Unit test package for dteenergybridge."""


text:
//  TEST    Foundation::Streams
#include "Stroika/Foundation/StroikaPreComp.h"

#include <sstream>

#include "Stroika/Foundation/Execution/Thread.h"
#include "Stroika/Foundation/Streams/Copy.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"
#include "Stroika/Foundation/Streams/OutputStream.h"
#include "Stroika/Foundation/Streams/SharedMemoryStream.h"
#include "Stroika/Foundation/Streams/TextReader.h"
#include "Stroika/Foundation/Streams/iostream/OutputStreamFromStdOStream.h"

#include "../TestHarness/TestHarness.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Streams;
using namespace Stroika::Foundation::Streams::iostream;

using std::byte;

namespace {
    namespace BasicBinaryInputStream_ {

        void TestBasicConstruction_ ()
        {
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New (nullptr, nullptr);
                VerifyTestResult (s != nullptr);
                VerifyTestResult (s.IsSeekable ());
            }
            {
                const char              kData[] = "1";
                MemoryStream<byte>::Ptr s       = MemoryStream<byte>::New (reinterpret_cast<const byte*> (std::begin (kData)), reinterpret_cast<const byte*> (std::end (kData)));
                VerifyTestResult (s != nullptr);
                VerifyTestResult (s.IsSeekable ());
                byte result[100] = {byte{0}};
                VerifyTestResult (s.Read (std::begin (result), std::end (result)) == 2);
                VerifyTestResult (to_integer<char> (result[0]) == '1');
                VerifyTestResult (to_integer<char> (result[1]) == '\0');
            }
        }

        void Tests_ ()
        {
            TestBasicConstruction_ ();
        }
    }
}

namespace {
    namespace BasicBinaryOutputStream_ {

        void TestBasicConstruction_ ()
        {
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New ();
                VerifyTestResult (s != nullptr);
                VerifyTestResult (s.IsSeekable ());
            }
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New ();
                VerifyTestResult (s != nullptr);
                VerifyTestResult (s.IsSeekable ());

                constexpr byte kData_[] = {byte{3}, byte{53}, byte{43}, byte{23}, byte{3}};
                s.Write (std::begin (kData_), std::end (kData_));
                Memory::BLOB b = s.As<Memory::BLOB> ();
                VerifyTestResult (b.size () == sizeof (kData_));
                VerifyTestResult (b == Memory::BLOB (std::begin (kData_), std::end (kData_)));
            }
        }

        void Tests_ ()
        {
            TestBasicConstruction_ ();
        }
    }
}

namespace {
    namespace BasicBinaryInputOutputStream_ {

        void TestBasicConstruction_ ()
        {
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New ();
                VerifyTestResult (s != nullptr);
                VerifyTestResult (s.IsSeekable ());
                VerifyTestResult (static_cast<InputStream<byte>::Ptr> (s).IsSeekable ());
                VerifyTestResult (static_cast<OutputStream<byte>::Ptr> (s).IsSeekable ());
            }
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New ();
                VerifyTestResult (s != nullptr);

                const uint8_t kData_[] = {3, 53, 43, 23, 3};
                s.Write (std::begin (kData_), std::end (kData_));
                Memory::BLOB b = s.As<Memory::BLOB> ();
                VerifyTestResult (b.size () == sizeof (kData_));
                VerifyTestResult (b == Memory::BLOB (std::begin (kData_), std::end (kData_)));
            }
            {
                MemoryStream<byte>::Ptr s = MemoryStream<byte>::New ();
                VerifyTestResult (s.GetReadOffset () == 0);
                VerifyTestResult (s.GetWriteOffset () == 0);
                const uint8_t kData_[] = {3, 53, 43, 23, 3};
                s.Write (std::begin (kData_), std::end (kData_));
                VerifyTestResult (s.GetReadOffset () == 0);
                VerifyTestResult (s.GetWriteOffset () == sizeof (kData_));
                byte bArr[1024];
                Verify (s.Read (std::begin (bArr), std::end (bArr)) == sizeof (kData_));
                VerifyTestResult (s.GetReadOffset () == sizeof (kData_));
                VerifyTestResult (s.GetWriteOffset () == sizeof (kData_));
                VerifyTestResult (Memory::BLOB (std::begin (bArr), std::begin (bArr) + s.GetReadOffset ()) == Memory::BLOB (std::begin (kData_), std::end (kData_)));
            }
        }

        void Tests_ ()
        {
            TestBasicConstruction_ ();
        }
    }
}

namespace {
    namespace BinaryOutputStreamFromOStreamAdapter_ {

        void T1_ ()
        {
            {
                stringstream                                  s;
                OutputStreamFromStdOStream<Memory::byte>::Ptr so       = OutputStreamFromStdOStream<Memory::byte>::New (s);
                const char                                    kData_[] = "ddasdf3294234";
                so.Write (reinterpret_cast<const byte*> (std::begin (kData_)), reinterpret_cast<const byte*> (std::begin (kData_)) + strlen (kData_));
                VerifyTestResult (s.str () == kData_);
            }
        }

        void Tests_ ()
        {
            T1_ ();
        }
    }
}

namespace {
    namespace TestBasicTextOutputStream_ {

        namespace Private_ {
            using Characters::Character;
            using Characters::String;
            void T1_ ()
            {
                MemoryStream<Character>::Ptr out = MemoryStream<Character>::New ();
                out << L"abc";
                VerifyTestResult (out.As<String> () == L"abc");
                out << L"123";
                VerifyTestResult (out.As<String> () == L"abc123");
            }
            void T2_ ()
            {
                MemoryStream<Character>::Ptr out = MemoryStream<Character>::New ();
                out << L"abc";
                VerifyTestResult (out.As<String> () == L"abc");
                out << L"123";
                VerifyTestResult (out.As<String> () == L"abc123");
                out.SeekWrite (2);
                out.SeekRead (3); // safe but irrelevant, as we don't read
                out << L"C";
                VerifyTestResult (out.As<String> () == L"abC123");
            }
        }

        void Tests_ ()
        {
            Private_::T1_ ();
        }
    }
}

namespace {
    namespace TextReaderFromIterableAndString {

        void T1_ ()
        {
            using Characters::Character;
            using Characters::String;
            {
                Traversal::Iterable<Character> s  = String (L"This");
                TextReader::Ptr                tr = TextReader::New (s);
                VerifyTestResult (tr.ReadAll () == L"This");
            }
            {
                VerifyTestResult ((TextReader::New (String{L"hello world"}).ReadAll () == L"hello world"));
            }
        }

        void Tests_ ()
        {
            T1_ ();
        }
    }
}

namespace {
    namespace TextReaderFromBLOB {

        void T1_ ()
        {
            using Characters::Character;
            using Characters::String;
            {
                Memory::BLOB    s  = Memory::BLOB::Raw (u8"Testing 1, 2, 3");
                TextReader::Ptr tr = TextReader::New (s);
                VerifyTestResult (tr.ReadAll () == L"Testing 1, 2, 3");
            }
        }

        void Tests_ ()
        {
            T1_ ();
        }
    }
}

namespace {
    namespace SharedMemoryStream_Doc_Example_Test8 {
        namespace Private_ {
            void T1_ ()
            {
                using namespace Execution;
                SharedMemoryStream<unsigned int>::Ptr pipe = SharedMemoryStream<unsigned int>::New ();
                unsigned                              sum{};
                static constexpr unsigned int         kStartWith{1};
                static constexpr unsigned int         kUpToInclusive_{1000};
                Thread::Ptr                           consumer = Thread::New ([&] () {
                    while (auto o = pipe.Read ()) {
                        sum += *o;
                    }
                },
                                                    Thread::eAutoStart);
                Thread::Ptr                           producer = Thread::New ([&] () {
                    for (unsigned int i = kStartWith; i <= kUpToInclusive_; ++i) {
                        pipe.Write (i);
                    };
                    pipe.CloseWrite (); // critical or consumer hangs on final read
                },
                                                    Thread::eAutoStart);
                Thread::WaitForDone ({consumer, producer});
                Assert (sum == (1 + kUpToInclusive_) * (kUpToInclusive_ - 1 + 1) / 2); // not a race
            }
        }

        void Tests_ ()
        {
            Private_::T1_ ();
        }
    }
}

namespace {
    namespace Streams_Copy_Test9 {
        namespace Private_ {
            void T1_ ()
            {
                using Characters::Character;
                using Characters::String;
                MemoryStream<Character>::Ptr in = MemoryStream<Character>::New ();
                in << L"abc";
                VerifyTestResult (in.As<String> () == L"abc");

                MemoryStream<Character>::Ptr out = MemoryStream<Character>::New ();
                Streams::CopyAll<Character> (in, out);
                VerifyTestResult (out.As<String> () == L"abc");
            }
        }

        void Tests_ ()
        {
            Private_::T1_ ();
        }
    }
}

namespace {
    void DoRegressionTests_ ()
    {
        BasicBinaryInputStream_::Tests_ ();
        BasicBinaryOutputStream_::Tests_ ();
        BasicBinaryInputOutputStream_::Tests_ ();
        BinaryOutputStreamFromOStreamAdapter_::Tests_ ();
        TestBasicTextOutputStream_::Tests_ ();
        TextReaderFromIterableAndString::Tests_ ();
        TextReaderFromBLOB::Tests_ ();
        SharedMemoryStream_Doc_Example_Test8::Tests_ ();
        Streams_Copy_Test9::Tests_ ();
    }
}

int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}


text:
<?php
/**
 * @author Liao Gengling <liaogling@gmail.com>
 */
namespace Phpenv;

use Phpenv\Exception\InvalidArgumentException;

class Env implements EnvInterface
{
    /**
     * Singleton Loader
     * @var Env|null
     */
    private static $loader;

    /**
     * ll environment files path
     * @var array
     */
    public $envFiles = array();

    /**
     * @var string|null
     */
    protected  $lastEnvFile;

    /**
     * @var bool
     */
    protected  $overloader = false;

    /**
     * Load environment config
     *
     * @param string $envFile Absolute path
     */
    public static function load($envFile = ".env")
    {
        self::getLoader()->innerLoad($envFile);
    }

    /**
     * Overload environment config
     *
     * @param string $envFile Absolute path
     */
    public static function overload($envFile = ".env")
    {
        self::getLoader()->overloader = true;
        self::getLoader()->innerLoad($envFile);
    }

    /**
     * Singleton Loader
     *
     * @return Env
     */
    public static function getLoader()
    {
        if (! (self::$loader instanceof self)) {
            self::$loader = new self();
        }
        return self::$loader;
    }

    /**
     * Inner load
     *
     * @param string $envFile
     * @throws \InvalidArgumentException
     */
    protected function innerLoad($envFile)
    {
        $this->lastEnvFile = $envFile;

        if(!is_readable($this->lastEnvFile) || !is_file($this->lastEnvFile)) {
            throw new InvalidArgumentException(sprintf('Phpenv: [%s] file not found or no readable', $this->lastEnvFile));
        }
        $this->envFiles[$envFile] = $envFile;

        $systemAutoDetectLine = ini_get('auto_detect_line_endings');
        ini_set('auto_detect_line_endings', '1');
        $rows = file($this->lastEnvFile, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
        ini_set('auto_detect_line_endings', $systemAutoDetectLine);

        foreach ($rows as $row) {
            $data = $this->filter($row);
            if($data != null) {
                list($key, $val) = $data;
                $val = $this->handleSemanticsVar($val);
                $this->setEnv($key, $val);
            }
        }
    }

    /**
     * Filter
     *
     * @param string $var
     * @return mixed
     */
    protected function filter($var)
    {
        switch (true) {
            case strpos(trim($var), "#") === 0:
                return null;
            case strpos($var, "=") !== false:
                list($key, $val) = array_map("trim", explode("=", $var ,2));
                return array($key, $val);
            default:
                return null;
        }
    }

    /**
     * Resolve variables
     *
     * @param string $var
     * @return string
     */
    protected function handleSemanticsVar($var)
    {
        list($var) = array_map("trim", explode("#", $var));
        switch (true) {
            case $var === "":
                return $var;
            case is_numeric($var):
                return $var;
            default:
                $beginStr = substr($var, 0, 1);
                if (in_array($beginStr, array('\'','"')) && $beginStr == substr($var, -1, 1)) {
                    return substr($var, 1, -1);
                }
                return $var;
        }
    }

    /**
     * Set environment
     *
     * @param string $key
     * @param mixed $val
     */
    public static function setEnv($key, $val)
    {
        if (self::getLoader()->overloader == false) {
            if(self::getEnv($key)) {
                return;
            }
        }
        putenv("{$key}={$val}");
        $_ENV[$key] = $val;
        $_SERVER[$key] = $val;
    }

    /**
     * Get environment
     *
     * @param string $key
     * @return mixed
     */
    public static function getEnv($key)
    {
        switch (true) {
            case array_key_exists($key, $_ENV):
                return $_ENV[$key];
            case array_key_exists($key, $_SERVER);
                return $_SERVER[$key];
            default:
                return getenv($key);
        }
    }
}


text:
* https://raw.githubusercontent.com/zoowii/maven-repo/master
* https://coding.net/u/zoowii/p/maven-repo/git/raw/master

## artifact url

* https://raw.githubusercontent.com/zoowii/maven-repo/master/path/of/group/artifactName/version/pomName.pom

## Add jars

* `mvn install:install-file  -Dfile=path-to-your-artifact-jar  -DgroupId=your.groupId  -DartifactId=your-artifactId   -Dversion=version     -Dpackaging=jar  -DlocalRepositoryPath=path-to-specific-local-repo`


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>My Project: NexUpload Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Files Functions Typedefs Groups Pages

Public Member Functions |
List of all members

NexUpload Class Reference
Core API

#include <NexUpload.h>

Public Member Functions

 	NexUpload (const char *file_name, const uint8_t SD_chip_select, uint32_t download_baudrate)

 	NexUpload (const String file_Name, const uint8_t SD_chip_select, uint32_t download_baudrate)

 	~NexUpload ()

void 	upload ()

Detailed Description

Provides the API for nextion to download the ftf file.

Constructor & Destructor Documentation

          NexUpload::NexUpload
          (
          const char *
          file_name,

          const uint8_t
          SD_chip_select,

          uint32_t
          download_baudrate

          )

Constructor.

Parameters

file_name	- tft file name.

SD_chip_select	- sd chip select pin.

download_baudrate	- set download baudrate.

          NexUpload::NexUpload
          (
          const String
          file_Name,

          const uint8_t
          SD_chip_select,

          uint32_t
          download_baudrate

          )

Constructor.

Parameters

file_Name	- tft file name.

SD_chip_select	- sd chip select pin.

download_baudrate	- set download baudrate.

          NexUpload::~NexUpload
          (
          	)

inline

destructor.

The documentation for this class was generated from the following files:

NexUpload.h

NexUpload.cpp

<address class="footer">
Generated on Thu Dec 1 2016 09:26:04 for My Project by

 1.8.7
</address>


text:
package org.talend.sdk.component.starter.server.service.build;

import java.util.Collection;

import org.talend.sdk.component.starter.server.service.domain.Build;
import org.talend.sdk.component.starter.server.service.domain.Dependency;
import org.talend.sdk.component.starter.server.service.domain.ProjectRequest;
import org.talend.sdk.component.starter.server.service.info.ServerInfo;

public interface BuildGenerator {

    Build createBuild(ProjectRequest.BuildConfiguration buildConfiguration, String packageBase,
            Collection<Dependency> dependencies, Collection<String> facets, ServerInfo.Snapshot versions);
}


text:
import Middleware from '../Middleware'
import { runInAction } from 'mobx'
import { EventTypes } from '../../events'
import type { Event } from '../../events'

const logErrorsMiddleware = process.env.NODE_ENV === 'development'
  ? Middleware((evt: Event): Event => {
      if (evt.type === EventTypes.NAVIGATION_ERROR) {
        console.error(`[router] Unhandled error caught in router`, evt.error)
      }
      return evt
    })
  : Middleware.EMPTY

export default logErrorsMiddleware


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
description: Assignment of function `name` attribute (FunctionExpression)
es6id: 12.14.5.2
info: >
    AssignmentProperty : IdentifierReference Initializeropt

    [...]
    6. If Initializeropt is present and v is undefined, then
       [...]
       d. If IsAnonymousFunctionDefinition(Initializer) is true, then
          i. Let hasNameProperty be HasOwnProperty(v, "name").
          ii. ReturnIfAbrupt(hasNameProperty).
          iii. If hasNameProperty is false, perform SetFunctionName(v, P).
includes: [propertyHelper.js]
---*/

var xFn, fn;

({ xFn = function x() {} } = {});
({ fn = function() {} } = {});

assert(xFn.name !== 'xFn');

assert.sameValue(fn.name, 'fn');
verifyNotEnumerable(fn, 'name');
verifyNotWritable(fn, 'name');
verifyConfigurable(fn, 'name');