text:
class AutocompleteProvider;
class OmniboxAction;
class SuggestionAnswer;
class TemplateURL;
class TemplateURLService;

namespace base {
class Time;
}  // namespace base

namespace gfx {
struct VectorIcon;
}  // namespace gfx

const char kACMatchPropertySuggestionText[] = "match suggestion text";
const char kACMatchPropertyContentsPrefix[] = "match contents prefix";
const char kACMatchPropertyContentsStartIndex[] = "match contents start index";
// A match attribute when a default match's score has been boosted with a higher
// scoring non-default match.
const char kACMatchPropertyScoreBoostedFrom[] = "score_boosted_from";

// RichAutocompletionParams ---------------------------------------------------

// `RichAutocompletionParams` is a cache for the params used by
// `TryRichAutocompletion()`. `TryRichAutocompletion()` is called about 80 times
// per keystroke; fetching all 16 params each time causes measurable timing
// regressions. Using `static const` local variables instead wouldn't be
// testable.
struct RichAutocompletionParams {
  RichAutocompletionParams();
  static RichAutocompletionParams& GetParams();
  static void ClearParamsForTesting();
  bool enabled;
  bool autocomplete_titles;
  bool autocomplete_titles_shortcut_provider;
  int autocomplete_titles_min_char;
  bool autocomplete_non_prefix_all;
  bool autocomplete_non_prefix_shortcut_provider;
  int autocomplete_non_prefix_min_char;
  bool autocomplete_shortcut_text;
  int autocomplete_shortcut_text_min_char;
  bool counterfactual;
  bool autocomplete_prefer_urls_over_prefixes;
};

// AutocompleteMatch ----------------------------------------------------------

// A single result line with classified spans.  The autocomplete popup displays
// the 'contents' and the 'description' (the description is optional) in the
// autocomplete dropdown, and fills in 'fill_into_edit' into the textbox when
// that line is selected.  fill_into_edit may be the same as 'description' for
// things like URLs, but may be different for searches or other providers.  For
// example, a search result may say "Search for asdf" as the description, but
// "asdf" should appear in the box.
struct AutocompleteMatch {
  // Autocomplete matches contain strings that are classified according to a
  // separate vector of styles.  This vector associates flags with particular
  // string segments, and must be in sorted order.  All text must be associated
  // with some kind of classification.  Even if a match has no distinct
  // segments, its vector should contain an entry at offset 0 with no flags.
  //
  // Example: The user typed "goog"
  //   http://www.google.com/        Google
  //   ^          ^   ^              ^   ^
  //   0,         |   15,            |   4,
  //              11,match           0,match
  //
  // This structure holds the classification information for each span.
  struct ACMatchClassification {
    // The values in here are not mutually exclusive -- use them like a
    // bit field.  This also means we use "int" instead of this enum type when
    // passing the values around, so the compiler doesn't complain.
    //
    // A Java counterpart will be generated for this enum.
    // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.omnibox
    // GENERATED_JAVA_CLASS_NAME_OVERRIDE: MatchClassificationStyle
    // clang-format off
    enum Style {
      NONE      = 0,
      URL       = 1 << 0,  // A URL
      MATCH     = 1 << 1,  // A match for the user's search term
      DIM       = 1 << 2,  // "Helper text"
    };
    // clang-format on

    ACMatchClassification(size_t offset, int style)
        : offset(offset), style(style) {}

    bool operator==(const ACMatchClassification& other) const {
      return offset == other.offset && style == other.style;
    }

    bool operator!=(const ACMatchClassification& other) const {
      return offset != other.offset || style != other.style;
    }

    // Offset within the string that this classification starts
    size_t offset;

    // Contains a bitmask of flags defined in enum Style.
    int style;
  };

  // SuggestTiles are used specifically with TILE_NAVSUGGEST matches.
  // This structure should describe only the specific details for individual
  // tiles; all other properties are considered as shared and should be
  // extracted from the encompassing AutocompleteMatch object.
  struct SuggestTile {
    GURL url{};
    std::u16string title{};
    bool is_search{};
  };

  typedef std::vector<ACMatchClassification> ACMatchClassifications;

  // Type used by providers to attach additional, optional information to
  // an AutocompleteMatch.
  typedef std::map<std::string, std::string> AdditionalInfo;

  // The type of this match.
  typedef AutocompleteMatchType::Type Type;

  // Null-terminated array of characters that are not valid within |contents|
  // and |description| strings.
  static const char16_t kInvalidChars[];

  // Document subtype, for AutocompleteMatchType::DOCUMENT.
  // Update kDocumentTypeStrings when updating DocumentType.
  enum class DocumentType {
    NONE = 0,
    DRIVE_DOCS,
    DRIVE_FORMS,
    DRIVE_SHEETS,
    DRIVE_SLIDES,
    DRIVE_IMAGE,
    DRIVE_PDF,
    DRIVE_VIDEO,
    DRIVE_FOLDER,
    DRIVE_OTHER,
    DOCUMENT_TYPE_SIZE
  };

  // These values are persisted to logs. Entries should not be renumbered and
  // numeric values should never be reused.
  enum class RichAutocompletionType {
    kNone = 0,
    kUrlNonPrefix = 1,
    kTitlePrefix = 2,
    kTitleNonPrefix = 3,
    kShortcutTextPrefix = 4,
    kMaxValue = kShortcutTextPrefix,
  };

  // Signals for ML scoring.
  metrics::OmniboxEventProto::Suggestion::ScoringSignals scoring_signals;

  static const char* const kDocumentTypeStrings[];

  // Return a string version of the core type values. Only used for
  // `RecordAdditionalInfo()`.
  static const char* DocumentTypeString(DocumentType type);

  // Use this function to convert integers to DocumentType enum values.
  // If you're sure it will be valid, you can call CHECK on the return value.
  // Returns true if |value| was successfully converted to a valid enum value.
  // The valid enum value will be written into |result|.
  static bool DocumentTypeFromInteger(int value, DocumentType* result);

  AutocompleteMatch();
  AutocompleteMatch(AutocompleteProvider* provider,
                    int relevance,
                    bool deletable,
                    Type type);
  AutocompleteMatch(const AutocompleteMatch& match);
  AutocompleteMatch(AutocompleteMatch&& match) noexcept;
  ~AutocompleteMatch();

  AutocompleteMatch& operator=(const AutocompleteMatch& match);
  AutocompleteMatch& operator=(AutocompleteMatch&& match) noexcept;

#if BUILDFLAG(IS_ANDROID)
  // Returns a corresponding Java object, creating it if necessary.
  // NOTE: Android specific methods are defined in autocomplete_match_android.cc
  base::android::ScopedJavaLocalRef<jobject> GetOrCreateJavaObject(
      JNIEnv* env) const;

  // Update the bond with- or drop the Java AutocompleteMatch instance.
  // This should be called whenever the native AutocompleteMatch object is
  // updated for an existing Java object.
  void UpdateJavaObjectNativeRef();

  // Notify the Java object that its native counterpart is about to be
  // destroyed.
  void DestroyJavaObject();

  // Returns a corresponding Java Class object.
  static jclass GetClazz(JNIEnv* env);

  // Update the clipboard match with the current clipboard data.
  void UpdateWithClipboardContent(
      JNIEnv* env,
      const base::android::JavaParamRef<jobject>& j_callback);

  // Called when the match is updated with the clipboard content.
  void OnClipboardSuggestionContentUpdated(
      const base::android::JavaRef<jobject>& j_callback);

  // Update the Java object with clipboard content.
  void UpdateClipboardContent(JNIEnv* env);
  // Update the Java object with new destination URL.
  void UpdateJavaDestinationUrl();
  // Update the Java object with new Answer-in-Suggest.
  void UpdateJavaAnswer();
  // Update the Java object description.
  void UpdateJavaDescription();
  // Update the pointer to corresponding Java tab object.
  void UpdateMatchingJavaTab(const JavaObjectWeakGlobalRef& tab);
  // Get the matching Java Tab object.
  JavaObjectWeakGlobalRef GetMatchingJavaTab() const;
#endif

#if (!BUILDFLAG(IS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !BUILDFLAG(IS_IOS)
  // Converts SuggestionAnswer::AnswerType to an answer vector icon.
  static const gfx::VectorIcon& AnswerTypeToAnswerIcon(int type);

  // Gets the vector icon identifier for the icon to be shown for this match. If
  // |is_bookmark| is true, returns a bookmark icon rather than what the type
  // would normally determine.  Note that in addition to |type|, the icon chosen
  // may depend on match contents (e.g. Drive |document_type| or |action|).
  // The reason |is_bookmark| is passed as a parameter and is not baked into the
  // AutocompleteMatch is likely that 1) this info is not used elsewhere in the
  // Autocomplete machinery except before displaying the match and 2) obtaining
  // this info is trivially done by calling BookmarkModel::IsBookmarked().
  const gfx::VectorIcon& GetVectorIcon(bool is_bookmark) const;
#endif

  // Comparison function for determining whether the first match is better than
  // the second.
  static bool MoreRelevant(const AutocompleteMatch& match1,
                           const AutocompleteMatch& match2);

  // Comparison functions for determining whether the first match is preferred
  // over the second when choosing between candidate duplicates.
  static bool BetterDuplicate(const AutocompleteMatch& match1,
                              const AutocompleteMatch& match2);
  static bool BetterDuplicateByIterator(
      const std::vector<AutocompleteMatch>::const_iterator it1,
      const std::vector<AutocompleteMatch>::const_iterator it2);

  // Helper functions for classes creating matches:
  // Fills in the classifications for |text|, using |style| as the base style
  // and marking the first instance of |find_text| as a match.  (This match
  // will also not be dimmed, if |style| has DIM set.)
  static void ClassifyMatchInString(const std::u16string& find_text,
                                    const std::u16string& text,
                                    int style,
                                    ACMatchClassifications* classifications);

  // Similar to ClassifyMatchInString(), but for cases where the range to mark
  // as matching is already known (avoids calling find()).  This can be helpful
  // when find() would be misleading (e.g. you want to mark the second match in
  // a string instead of the first).
  static void ClassifyLocationInString(size_t match_location,
                                       size_t match_length,
                                       size_t overall_length,
                                       int style,
                                       ACMatchClassifications* classifications);

  // Returns a new vector of classifications containing the merged contents of
  // |classifications1| and |classifications2|.
  static ACMatchClassifications MergeClassifications(
      const ACMatchClassifications& classifications1,
      const ACMatchClassifications& classifications2);

  // Converts classifications to and from a serialized string representation
  // (using comma-separated integers to sequentially list positions and styles).
  static std::string ClassificationsToString(
      const ACMatchClassifications& classifications);
  static ACMatchClassifications ClassificationsFromString(
      const std::string& serialized_classifications);

  // Adds a classification to the end of |classifications| iff its style is
  // different from the last existing classification.  |offset| must be larger
  // than the offset of the last classification in |classifications|.
  static void AddLastClassificationIfNecessary(
      ACMatchClassifications* classifications,
      size_t offset,
      int style);

  // Returns true if at least one style in |classifications| is of type MATCH.
  static bool HasMatchStyle(const ACMatchClassifications& classifications);

  // Removes invalid characters from |text|. Should be called on strings coming
  // from external sources (such as extensions) before assigning to |contents|
  // or |description|.
  static std::u16string SanitizeString(const std::u16string& text);

  // Convenience function to check if |type| is a search (as opposed to a URL or
  // an extension).
  static bool IsSearchType(Type type);

  // Convenience function to check if |type| is a special search suggest type -
  // like entity, personalized, profile or postfix.
  static bool IsSpecializedSearchType(Type type);

  // Convenience function to check if |type| is a search history type -
  // usually this surfaces a clock icon to the user.
  static bool IsSearchHistoryType(Type type);

  // Returns whether this match is a starter pack suggestion provided by the
  // built-in provider. This is the suggestion that the starter pack keyword
  // mode chips attach to.
  static bool IsStarterPackType(Type type);

  // Convenience function to check if |type| is one of the suggest types we
  // need to skip for search vs url partitions - url, text or image in the
  // clipboard or query tile.
  static bool ShouldBeSkippedForGroupBySearchVsUrl(Type type);

  // A static version GetTemplateURL() that takes the match's keyword and
  // match's hostname as parameters.  In short, returns the TemplateURL
  // associated with |keyword| if it exists; otherwise returns the TemplateURL
  // associated with |host| if it exists.
  static TemplateURL* GetTemplateURLWithKeyword(
      TemplateURLService* template_url_service,
      const std::u16string& keyword,
      const std::string& host);
  static const TemplateURL* GetTemplateURLWithKeyword(
      const TemplateURLService* template_url_service,
      const std::u16string& keyword,
      const std::string& host);

  // Returns `url` altered by stripping off "www.", converting https protocol
  // to http, and stripping query params other than the search terms. If
  // `keep_search_intent_params` is true, also keep search intent params which
  // disambiguate the search terms and determine the fulfillment.
  // These conversions are meant to allow URL comparisons to find likely
  // duplicates; and these URLs are not used as actual destination URLs.
  // In most use cases `keep_search_intent_params` need not be true, e.g., when
  // computing `stripped_destination_url` for matches. Otherwise, keeping the
  // search intent params would create an unnecessary level of granularity which
  // prevents proper deduping of matches from various local or remote providers.
  // If a provider wishes to prevent its matches (or a subset of them) from
  // being deduped with other matches with the same search terms, it must
  // precompute `stripped_destination_url` while maintaining the search intent
  // params. A notable example is when multiple entity suggestions with the same
  // search terms are offered by SearchProvider or ZeroSuggestProvider. In that
  // case, the entity matches (with the exception of the first one) keep their
  // search intent params in `stripped_destination_url` to avoid being deduped.
  // - `input` is used to decide if the scheme is allowed to be altered during
  //   stripping.  If this URL, minus the scheme and separator, starts with any
  //   the terms in input.terms_prefixed_by_http_or_https(), we avoid converting
  //   an HTTPS scheme to HTTP.  This means URLs that differ only by these
  //   schemes won't be marked as dupes, since the distinction seems to matter
  //   to the user.
  // - If `template_url_service` is not NULL, it is used to get a template URL
  //   corresponding to this match, which is used to strip off query params
  //   other than the search terms (and optionally search intent params) that
  //   would otherwise prevent proper comparison/deduping.
  // - If the match's keyword is known, it can be provided in `keyword`.
  //   Otherwise, it can be left empty and the template URL (if any) is
  //   determined from the destination's hostname.
  static GURL GURLToStrippedGURL(const GURL& url,
                                 const AutocompleteInput& input,
                                 const TemplateURLService* template_url_service,
                                 const std::u16string& keyword,
                                 const bool keep_search_intent_params);

  // Sets the |match_in_scheme| and |match_in_subdomain| flags based on the
  // provided |url| and list of substring |match_positions|. |match_positions|
  // is the [begin, end) positions of a match within the unstripped URL spec.
  using MatchPosition = std::pair<size_t, size_t>;
  static void GetMatchComponents(
      const GURL& url,
      const std::vector<MatchPosition>& match_positions,
      bool* match_in_scheme,
      bool* match_in_subdomain);

  // Gets the formatting flags used for display of suggestions. This method
  // encapsulates the return of experimental flags too, so any URLs displayed
  // as an Omnibox suggestion should use this method.
  //
  // This function returns flags that may destructively format the URL, and
  // therefore should never be used for the |fill_into_edit| field.
  //
  // |preserve_scheme| and |preserve_subdomain| indicate that these URL
  // components are important (part of the match), and should not be trimmed.
  static url_formatter::FormatUrlTypes GetFormatTypes(bool preserve_scheme,
                                                      bool preserve_subdomain);
  // Logs the search engine used to navigate to a search page or auto complete
  // suggestion. For direct URL navigations, nothing is logged.
  static void LogSearchEngineUsed(const AutocompleteMatch& match,
                                  TemplateURLService* template_url_service);

  // Computes the stripped destination URL (via GURLToStrippedGURL()) and
  // stores the result in |stripped_destination_url|.  |input| is used for the
  // same purpose as in GURLToStrippedGURL().
  void ComputeStrippedDestinationURL(const AutocompleteInput& input,
                                     TemplateURLService* template_url_service);

  // Returns whether `destination_url` looks like a doc URL. If so, will also
  // set `stripped_destination_url` to avoid repeating the computation later.
  bool IsDocumentSuggestion();

  // Returns true if this match may attach an `action`.
  // This method is used to keep actions off of matches with types that don't
  // mix well with Pedals or other actions (e.g. entities).
  bool IsActionCompatible() const;

  // Gets data relevant to whether there should be any special keyword-related
  // UI shown for this match.  If this match represents a selected keyword, i.e.
  // the UI should be "in keyword mode", |keyword_out| will be set to the
  // keyword and |is_keyword_hint| will be set to false.  If this match has a
  // non-null |associated_keyword|, i.e. we should show a "Press [tab] to search
  // ___" hint and allow the user to toggle into keyword mode, |keyword_out|
  // will be set to the associated keyword and |is_keyword_hint| will be set to
  // true.  Note that only one of these states can be in effect at once.  In all
  // other cases, |keyword_out| will be cleared, even when our member variable
  // |keyword| is non-empty -- such as with non-substituting keywords or matches
  // that represent searches using the default search engine.  See also
  // GetSubstitutingExplicitlyInvokedKeyword().
  void GetKeywordUIState(TemplateURLService* template_url_service,
                         std::u16string* keyword_out,
                         bool* is_keyword_hint) const;

  // Returns |keyword|, but only if it represents a substituting keyword that
  // the user has explicitly invoked.  If for example this match represents a
  // search with the default search engine (and the user didn't explicitly
  // invoke its keyword), this returns the empty string.  The result is that
  // this function returns a non-empty string in the same cases as when the UI
  // should show up as being "in keyword mode".
  std::u16string GetSubstitutingExplicitlyInvokedKeyword(
      TemplateURLService* template_url_service) const;

  // Returns the TemplateURL associated with this match.  This may be NULL if
  // the match has no keyword OR if the keyword no longer corresponds to a valid
  // TemplateURL.  See comments on |keyword| below.
  // If |allow_fallback_to_destination_host| is true and the keyword does
  // not map to a valid TemplateURL, we'll then check for a TemplateURL that
  // corresponds to the destination_url's hostname.
  TemplateURL* GetTemplateURL(TemplateURLService* template_url_service,
                              bool allow_fallback_to_destination_host) const;

  // Gets the URL for the match image (whether it be an answer or entity). If
  // there isn't an image URL, returns an empty GURL (test with is_empty()).
  GURL ImageUrl() const;

  // Adds optional information to the |additional_info| dictionary.
  void RecordAdditionalInfo(const std::string& property,
                            const std::string& value);
  void RecordAdditionalInfo(const std::string& property,
                            const std::u16string& value);
  void RecordAdditionalInfo(const std::string& property, int value);
  void RecordAdditionalInfo(const std::string& property, base::Time value);

  // Returns the value recorded for |property| in the |additional_info|
  // dictionary.  Returns the empty string if no such value exists.
  std::string GetAdditionalInfo(const std::string& property) const;

  // Returns the enum equivalent to the type of this autocomplete match.
  metrics::OmniboxEventProto::Suggestion::ResultType AsOmniboxEventResultType()
      const;

  // Returns whether this match is a "verbatim" match: a URL navigation directly
  // to the user's input, a search for the user's input with the default search
  // engine, or a "keyword mode" search for the query portion of the user's
  // input.  Note that rare or unusual types that could be considered verbatim,
  // such as keyword engine matches or extension-provided matches, aren't
  // detected by this IsVerbatimType, as the user will not be able to infer
  // what will happen when they press enter in those cases if the match is not
  // shown.
  bool IsVerbatimType() const;

  // Returns whether this match is a search suggestion provided by search
  // provider.
  bool IsSearchProviderSearchSuggestion() const;

  // Returns whether this match is a search suggestion provided by on device
  // providers.
  bool IsOnDeviceSearchSuggestion() const;

  // Returns whether the autocompletion is trivial enough that we consider it
  // an autocompletion for which the omnibox autocompletion code did not add
  // any value.
  bool IsTrivialAutocompletion() const;

  // Returns whether this match or any duplicate of this match can be deleted.
  // This is used to decide whether we should call DeleteMatch().
  bool SupportsDeletion() const;

  // Returns a copy of this match with the contents and description fields, and
  // their associated classifications, possibly swapped.  We swap these if this
  // is a match for which we should emphasize the title (stored in the
  // description field) over the URL (in the contents field).
  //
  // We specifically return a copy to prevent the UI code from accidentally
  // mucking with the matches stored in the model, lest other omnibox systems
  // get confused about which is which.  See the code that sets
  // |swap_contents_and_description| for conditions they are swapped.
  //
  // TODO(crbug.com/1202964): Clean up the handling of contents and description
  // so that this copy is no longer required.
  AutocompleteMatch GetMatchWithContentsAndDescriptionPossiblySwapped() const;

  // Determines whether this match is allowed to be the default match by
  // comparing |input.text| and |inline_autocompletion|. Therefore,
  // |inline_autocompletion| should be set prior to invoking this method. Also
  // considers trailing whitespace in the input, so the input should not be
  // fixed up. May trim trailing whitespaces from |inline_autocompletion|.
  //
  // Input "x" will allow default matches "x", "xy", and "x y".
  // Input "x " will allow default matches "x" and "x y".
  // Input "x  " will allow default match "x".
  // Input "x y" will allow default match "x y".
  // Input "x" with prevent_inline_autocomplete will allow default match "x".
  void SetAllowedToBeDefault(const AutocompleteInput& input);

  // Estimates dynamic memory usage.
  // See base/trace_event/memory_usage_estimator.h for more info.
  size_t EstimateMemoryUsage() const;

  // Upgrades this match by absorbing the best properties from
  // |duplicate_match|. For instance: if |duplicate_match| has a higher
  // relevance score, this match's own relevance score will be upgraded.
  void UpgradeMatchWithPropertiesFrom(AutocompleteMatch& duplicate_match);

  // Tries, in order, to:
  // - Prefix autocomplete |primary_text|
  // - Prefix autocomplete |secondary_text|
  // - Non-prefix autocomplete |primary_text|
  // - Non-prefix autocomplete |secondary_text|
  // - Split autocomplete |primary_text|
  // - Split autocomplete |secondary_text|
  // Returns false if none of the autocompletions were appropriate (or the
  // features were disabled).
  bool TryRichAutocompletion(const std::u16string& primary_text,
                             const std::u16string& secondary_text,
                             const AutocompleteInput& input,
                             const std::u16string& shortcut_text = u"");

  // True if `inline_autocompletion` and `prefix_autocompletion` are both empty.
  bool IsEmptyAutocompletion() const;

  // Serialise this object into a trace.
  void WriteIntoTrace(perfetto::TracedValue context) const;

  // The provider of this match, used to remember which provider the user had
  // selected when the input changes. This may be NULL, in which case there is
  // no provider (or memory of the user's selection).
  AutocompleteProvider* provider = nullptr;

  // The relevance of this match. See table in autocomplete.h for scores
  // returned by various providers. This is used to rank matches among all
  // responding providers, so different providers must be carefully tuned to
  // supply matches with appropriate relevance.
  int relevance = 0;

  // How many times this result was typed in / selected from the omnibox.
  // Only set for some providers and result_types.  If it is not set,
  // its value is -1.  At the time of writing this comment, it is only
  // set for matches from HistoryURL and HistoryQuickProvider.
  int typed_count = -1;

  // True if the user should be able to delete this match.
  bool deletable = false;

  // This string is loaded into the location bar when the item is selected
  // by pressing the arrow keys. This may be different than a URL, for example,
  // for search suggestions, this would just be the search terms.
  std::u16string fill_into_edit;

  // This string is displayed adjacent to the omnibox if this match is the
  // default. Will usually be URL when autocompleting a title, and empty
  // otherwise.
  std::u16string additional_text;

  // The inline autocompletion to display after the user's input in the
  // omnibox, if this match becomes the default match.  It may be empty.
  std::u16string inline_autocompletion;
  // Whether rich autocompletion triggered; i.e. this suggestion *is or could
  // have been* rich autocompleted. This is usually redundant and checking
  // whether `prefix_autocompletion` is non-empty should be used instead to
  // determine if this suggestion *is* rich autocompleted. But for
  // counterfactual variations, `prefix_autocompletion` isn't copied when
  // deduping matches to avoid showing rich autocompletion and so can't be used
  // to trigger logging.
  // TODO(manukh): remove `rich_autocompletion_triggered` when counterfactual
  //  experiments end.
  RichAutocompletionType rich_autocompletion_triggered =
      RichAutocompletionType::kNone;
  // The inline autocompletion to display before the user's input in the
  // omnibox, if this match becomes the default match. Always empty if
  // non-prefix autocompletion is disabled.
  std::u16string prefix_autocompletion;

  // If false, the omnibox should prevent this match from being the
  // default match.  Providers should set this to true only if the
  // user's input, plus any inline autocompletion on this match, would
  // lead the user to expect a navigation to this match's destination.
  // For example, with input "foo", a search for "bar" or navigation
  // to "bar.com" should not set this flag; a navigation to "foo.com"
  // should only set this flag if ".com" will be inline autocompleted;
  // and a navigation to "foo/" (an intranet host) or search for "foo"
  // should set this flag.
  bool allowed_to_be_default_match = false;

  // The URL to actually load when the autocomplete item is selected. This URL
  // should be canonical so we can compare URLs with strcmp to avoid dupes.
  // It may be empty if there is no possible navigation.
  GURL destination_url;

  // The destination URL modified for better dupe finding.  The result may not
  // be navigable or even valid; it's only meant to be used for detecting
  // duplicates. Providers are not expected to set this field,
  // `AutocompleteResult` will set it using `ComputeStrippedDestinationURL()`.
  // Providers may manually set it to avoid the default
  // `ComputeStrippedDestinationURL()` computation.
  GURL stripped_destination_url;

  // Optional image information. Used for entity suggestions. The dominant color
  // can be used to paint the image placeholder while fetching the image.
  std::string image_dominant_color;
  GURL image_url;

  // Optional entity id for entity suggestions. Empty string means no entity ID.
  // This is not meant for display, but internal use only. The actual UI display
  // is controlled by the `type` and `image_url`.
  std::string entity_id;

  // Optional override to use for types that specify an icon sub-type.
  DocumentType document_type = DocumentType::NONE;

  // Holds the common part of tail suggestion. Used to indent the contents.
  // Can't simply store the character length of the string, as different
  // characters may have different rendered widths.
  std::u16string tail_suggest_common_prefix;

  // The main text displayed in the address bar dropdown.
  std::u16string contents;
  ACMatchClassifications contents_class;

  // Additional helper text for each entry, such as a title or description.
  std::u16string description;
  ACMatchClassifications description_class;
  // In the case of the document provider, the description includes a last
  // updated date that may become stale. To avoid showing stale descriptions,
  // when |description_for_shortcut| is not empty, it will be stored instead of
  // |description| in the shortcuts provider.
  std::u16string description_for_shortcuts;
  ACMatchClassifications description_class_for_shortcuts;

  // The optional suggestion group ID used to look up the suggestion group info
  // for the group this suggestion belongs to from the AutocompleteResult.
  //
  // Use omnibox::GROUP_INVALID in place of a missing value when converting
  // this to a primitive type.
  // TODO(manukh): Seems redundant to prefix a suggestion field with
  //  'suggestion_'. Check if it makes sense to rename to 'group_id', and
  //  likewise for the associated methods and local variables.
  absl::optional<omnibox::GroupId> suggestion_group_id;

  // If true, UI-level code should swap the contents and description fields
  // before displaying.
  // This field is set when matches are appended to autocomplete results via
  // |AutocompleteResult::AppendMatches| rather than when matches are created.
  bool swap_contents_and_description = false;

  // A rich-format version of the display for the dropdown.
  absl::optional<SuggestionAnswer> answer;

  // The transition type to use when the user opens this match.  By default,
  // this is TYPED.  Providers whose matches do not look like URLs should set
  // it to GENERATED.
  ui::PageTransition transition = ui::PAGE_TRANSITION_TYPED;

  // Type of this match.
  Type type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;

  // True if we saw a tab that matched this suggestion.
  // Unset if it has not been computed yet.
  absl::optional<bool> has_tab_match;

  // Used to identify the specific source / type for suggestions by the
  // suggest server. See SuggestSubtype in types.proto for more details.
  // Uses flat_set to deduplicate subtypes (e.g., as a result of Chrome adding
  // additional subtypes). The order of elements reported back via AQS is
  // irrelevant. flat_set uses std::vector as a container, reducing memory
  // overhead of keeping a handful of integers, while offering similar
  // functionality as std::set.
  // Note this set may contain int values not present in omnibox::SuggestSubtype
  // enum. This is because the list of subtypes in omnibox::SuggestSubtype enum
  // is not exhaustive. However, casting int values into omnibox::SuggestSubtype
  // enum without testing membership is expected to be safe as
  // omnibox::SuggestSubtype enum has a fixed int underlying type.
  base::flat_set<omnibox::SuggestSubtype> subtypes;

  // Set with a keyword provider match if this match can show a keyword hint.
  // For example, if this is a SearchProvider match for "www.amazon.com",
  // |associated_keyword| could be a KeywordProvider match for "amazon.com".
  //
  // When this is set, the popup will show a ">" symbol at the right edge of the
  // line for this match, and tab/shift-tab will toggle in and out of keyword
  // mode without disturbing the rest of the popup.  See also
  // OmniboxPopupModel::SetSelectedLineState().
  std::unique_ptr<AutocompleteMatch> associated_keyword;

  // The keyword of the TemplateURL the match originated from.  This is nonempty
  // for both explicit "keyword mode" matches as well as matches for the default
  // search provider (so, any match for which we're doing substitution); it
  // doesn't imply (alone) that the UI is going to show a keyword hint or
  // keyword mode.  For that, see GetKeywordUIState() or
  // GetSubstitutingExplicitlyInvokedKeyword().
  //
  // CAUTION: The TemplateURL associated with this keyword may be deleted or
  // modified while the AutocompleteMatch is alive.  This means anyone who
  // accesses it must perform any necessary sanity checks before blindly using
  // it!
  std::u16string keyword;

  // Set in matches originating from keyword results.
  bool from_keyword = false;

  // Set to a matching action if appropriate.
  scoped_refptr<OmniboxAction> action;

  // True if this match is from a previous result.
  bool from_previous = false;

  // Optional search terms args.  If present,
  // AutocompleteController::UpdateAssistedQueryStats() will incorporate this
  // data with additional data it calculates and pass the completed struct to
  // TemplateURLRef::ReplaceSearchTerms() to reset the match's |destination_url|
  // after the complete set of matches in the AutocompleteResult has been chosen
  // and sorted.  Most providers will leave this as NULL, which will cause the
  // AutocompleteController to do no additional transformations.
  std::unique_ptr<TemplateURLRef::SearchTermsArgs> search_terms_args;

  // Optional post content. If this is set, the request to load the destination
  // url will pass this post content as well.
  std::unique_ptr<TemplateURLRef::PostContent> post_content;

  // Information dictionary into which each provider can optionally record a
  // property and associated value and which is presented in chrome://omnibox.
  AdditionalInfo additional_info;

  // A vector of matches culled during de-duplication process, sorted from
  // second-best to worst according to the de-duplication preference criteria.
  // This vector is retained so that if the user deletes a match, all the
  // duplicates are deleted as well. This is also used for re-duping Search
  // Entity vs. plain Search suggestions.
  std::vector<AutocompleteMatch> duplicate_matches;

  // A list of query tiles to be shown as part of this match.
  std::vector<query_tiles::Tile> query_tiles;

  // A list of navsuggest tiles to be shown as part of this match.
  // This object is only populated for TILE_NAVSUGGEST AutocompleteMatches.
  std::vector<SuggestTile> suggest_tiles;

  // So users of AutocompleteMatch can use the same ellipsis that it uses.
  static const char16_t kEllipsis[];

#if DCHECK_IS_ON()
  // Does a data integrity check on this match.
  void Validate() const;
#endif  // DCHECK_IS_ON()

  // Checks one text/classifications pair for valid values.
  static void ValidateClassifications(
      const std::u16string& text,
      const ACMatchClassifications& classifications,
      const std::string& provider_name = "");

 private:
#if BUILDFLAG(IS_ANDROID)
  // Corresponding Java object.
  // This element should not be copied with the rest of the AutocompleteMatch
  // object to ensure consistent 1:1 relationship between the objects.
  // This object should never be accessed directly. To acquire a reference to
  // java object, call the GetOrCreateJavaObject().
  // Note that this object is lazily constructed to avoid creating Java matches
  // for throw away AutocompleteMatch objects, eg. during Classify() or
  // QualifyPartialUrlQuery() calls.
  // See AutocompleteControllerAndroid for more details.
  mutable std::unique_ptr<base::android::ScopedJavaGlobalRef<jobject>>
      java_match_;

  // When set, holds a weak reference to Java Tab object.
  JavaObjectWeakGlobalRef matching_java_tab_{};

  base::WeakPtrFactory<AutocompleteMatch> weak_ptr_factory_{this};
#endif
};

typedef AutocompleteMatch::ACMatchClassification ACMatchClassification;
typedef std::vector<ACMatchClassification> ACMatchClassifications;
typedef std::vector<AutocompleteMatch> ACMatches;

// Can be used as the key for grouping AutocompleteMatches in a map based on a
// std::pair of fields. This can be generalized to a std::tuple if ever needed.
// The accompanying hash function makes the key usable in an std::unordered_map.
template <typename S, typename T>
using ACMatchKey = std::pair<S, T>;

template <typename S, typename T>
struct ACMatchKeyHash {
  size_t operator()(const ACMatchKey<S, T>& key) const;
};

#endif  // COMPONENTS_OMNIBOX_BROWSER_AUTOCOMPLETE_MATCH_H_


text:
# typed: false
# frozen_string_literal: true

require "cleaner"
require "formula"

describe Cleaner do
  include FileUtils

  describe "#clean" do
    subject(:cleaner) { described_class.new(f) }

    let(:f) { formula("cleaner_test") { url "foo-1.0" } }

    before do
      f.prefix.mkpath
    end

    it "cleans files" do
      f.bin.mkpath
      f.lib.mkpath

      if OS.mac?
        cp "#{TEST_FIXTURE_DIR}/mach/a.out", f.bin
        cp Dir["#{TEST_FIXTURE_DIR}/mach/*.dylib"], f.lib
      elsif OS.linux?
        cp "#{TEST_FIXTURE_DIR}/elf/hello", f.bin
        cp Dir["#{TEST_FIXTURE_DIR}/elf/libhello.so.0"], f.lib
      end

      cleaner.clean

      if OS.mac?
        expect((f.bin/"a.out").stat.mode).to eq(0100555)
        expect((f.lib/"fat.dylib").stat.mode).to eq(0100444)
        expect((f.lib/"x86_64.dylib").stat.mode).to eq(0100444)
        expect((f.lib/"i386.dylib").stat.mode).to eq(0100444)
      elsif OS.linux?
        expect((f.bin/"hello").stat.mode).to eq(0100555)
        expect((f.lib/"libhello.so.0").stat.mode).to eq(0100555)
      end
    end

    it "prunes the prefix if it is empty" do
      cleaner.clean
      expect(f.prefix).not_to be_a_directory
    end

    it "prunes empty directories" do
      subdir = f.bin/"subdir"
      subdir.mkpath

      cleaner.clean

      expect(f.bin).not_to be_a_directory
      expect(subdir).not_to be_a_directory
    end

    it "removes a symlink when its target was pruned before" do
      dir = f.prefix/"b"
      symlink = f.prefix/"a"

      dir.mkpath
      ln_s dir.basename, symlink

      cleaner.clean

      expect(dir).not_to exist
      expect(symlink).not_to be_a_symlink
      expect(symlink).not_to exist
    end

    it "removes symlinks pointing to an empty directory" do
      dir = f.prefix/"b"
      symlink = f.prefix/"c"

      dir.mkpath
      ln_s dir.basename, symlink

      cleaner.clean

      expect(dir).not_to exist
      expect(symlink).not_to be_a_symlink
      expect(symlink).not_to exist
    end

    it "removes broken symlinks" do
      symlink = f.prefix/"symlink"
      ln_s "target", symlink

      cleaner.clean

      expect(symlink).not_to be_a_symlink
    end

    it "removes '.la' files" do
      file = f.lib/"foo.la"

      file.dirname.mkpath
      touch file

      cleaner.clean

      expect(file).not_to exist
    end

    it "removes 'perllocal' files" do
      file = f.lib/"perl5/darwin-thread-multi-2level/perllocal.pod"

      file.dirname.mkpath
      touch file

      cleaner.clean

      expect(file).not_to exist
    end

    it "removes '.packlist' files" do
      file = f.lib/"perl5/darwin-thread-multi-2level/auto/test/.packlist"

      file.dirname.mkpath
      touch file

      cleaner.clean

      expect(file).not_to exist
    end

    it "removes 'charset.alias' files" do
      file = f.lib/"charset.alias"

      file.dirname.mkpath
      touch file

      cleaner.clean

      expect(file).not_to exist
    end

    it "removes 'info/**/dir' files except for 'info/<name>/dir'" do
      file = f.info/"dir"
      arch_file = f.info/"i686-elf/dir"
      name_file = f.info/f.name/"dir"

      file.dirname.mkpath
      arch_file.dirname.mkpath
      name_file.dirname.mkpath

      touch file
      touch arch_file
      touch name_file

      cleaner.clean

      expect(file).not_to exist
      expect(arch_file).not_to exist
      expect(name_file).to exist
    end
  end

  describe "::skip_clean" do
    def stub_formula_skip_clean(skip_paths)
      formula("cleaner_test") do
        url "foo-1.0"

        skip_clean skip_paths
      end
    end

    it "adds paths that should be skipped" do
      f = stub_formula_skip_clean("bin")
      f.bin.mkpath

      described_class.new(f).clean

      expect(f.bin).to be_a_directory
    end

    it "also skips empty sub-directories under the added paths" do
      f = stub_formula_skip_clean("bin")
      subdir = f.bin/"subdir"
      subdir.mkpath

      described_class.new(f).clean

      expect(f.bin).to be_a_directory
      expect(subdir).to be_a_directory
    end

    it "allows skipping broken symlinks" do
      f = stub_formula_skip_clean("symlink")
      f.prefix.mkpath
      symlink = f.prefix/"symlink"
      ln_s "target", symlink

      described_class.new(f).clean

      expect(symlink).to be_a_symlink
    end

    it "allows skipping symlinks pointing to an empty directory" do
      f = stub_formula_skip_clean("c")
      dir = f.prefix/"b"
      symlink = f.prefix/"c"

      dir.mkpath
      ln_s dir.basename, symlink

      described_class.new(f).clean

      expect(dir).not_to exist
      expect(symlink).to be_a_symlink
      expect(symlink).not_to exist
    end

    it "allows skipping symlinks whose target was pruned before" do
      f = stub_formula_skip_clean("a")
      dir = f.prefix/"b"
      symlink = f.prefix/"a"

      dir.mkpath
      ln_s dir.basename, symlink

      described_class.new(f).clean

      expect(dir).not_to exist
      expect(symlink).to be_a_symlink
      expect(symlink).not_to exist
    end

    it "allows skipping '.la' files" do
      f = stub_formula_skip_clean(:la)

      file = f.lib/"foo.la"

      f.lib.mkpath
      touch file

      described_class.new(f).clean

      expect(file).to exist
    end

    it "allows skipping sub-directories" do
      f = stub_formula_skip_clean("lib/subdir")

      dir = f.lib/"subdir"

      dir.mkpath

      described_class.new(f).clean

      expect(dir).to be_a_directory
    end

    it "allows skipping paths relative to prefix" do
      f = stub_formula_skip_clean("bin/a")

      dir1 = f.bin/"a"
      dir2 = f.lib/"bin/a"

      dir1.mkpath
      dir2.mkpath

      described_class.new(f).clean

      expect(dir1).to exist
      expect(dir2).not_to exist
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class TestController < ApplicationController
  def test
    render :json => {success: true}
  end
end


text:
require 'spec_helper'

describe HungrAuth::Users::RegistrationsController do
  before do
    request.env["devise.mapping"] = Devise.mappings[:user]
  end

  describe '#new' do

    it 'should raise Not Implemented exception' do
      lambda {
        get :new
      }.should raise_exception("Not Implemented")
    end

  end

  describe '#create' do

    context 'with valid parameters' do

      context 'valid for authentication' do

        it 'should return 201' do
          post :create, :user => Factory.attributes_for(:supporter)
          response.status.should == 201
        end

        it 'should return bare user presentation' do
          post :create, :user => Factory.attributes_for(:supporter)
          response.body.should == User.last.bare.to_json
        end

      end

      context 'invalid for authentication' do

        it 'should return 401' do
          any_instance_of(User, :active_for_authentication? => false)
          post :create, :user => Factory.attributes_for(:supporter)
          response.status.should == 401
        end

        it 'should return bare user presentation' do
          any_instance_of(User, :active_for_authentication? => false)
          post :create, :user => Factory.attributes_for(:supporter)
          json_response = JSON.parse(response.body)
          json_response["errors"]["type"].should == "Inactive for Authentication"
          json_response["errors"]["errors"].should == ["Inactive for Authentication"]
        end

      end

    end

    context 'with invalid parameters' do

      it 'should return 400' do
        post :create, :user => Factory.attributes_for(:supporter, :email => nil)
        response.status.should == 400
      end

      it 'should return user with authentication errors' do
        post :create, :user => Factory.attributes_for(:supporter, :email => nil)
        json_response = JSON.parse(response.body)
        json_response["errors"]["type"].should == "Invalid Parameters"
        json_response["errors"]["errors"].should_not be_nil
      end

    end

  end

  describe '#show' do

    context 'if user found' do
      let(:user) { Factory(:supporter) }

      it 'should return 200' do
        get :show, :personal_url => user.personal_url
        response.status.should == 200
      end

      it 'should return bare user representation' do
        get :show, :personal_url => user.personal_url
        response.body.should == user.bare.to_json
      end

    end

    context 'if user not found' do

      it 'should return 404' do
        get :show, :personal_url => "DOESNTEXIST"
        response.status.should == 404
      end

    end

  end

  describe '#edit' do

    it 'should raise Not Implemented exception' do
      sign_in Factory(:supporter)
      lambda {
        get :edit
      }.should raise_exception("Not Implemented")
    end

  end

  describe '#update' do

    it 'should raise Not Implemented exception' do
      sign_in Factory(:supporter)
      lambda {
        put :update
      }.should raise_exception("Not Implemented")
    end

  end

  describe '#update_email' do

    context 'when signed in' do
      before do
        sign_in @user = Factory(:supporter)
      end

      context 'with valid params' do

        it 'should update the user email' do
          put :update_email, 'user' =>  {'email' => 'new_test_email@hungr.com'}
          @user.reload.email.should == 'new_test_email@hungr.com'
        end

        it 'should return 200' do
          put :update_email, 'user' =>  {'email' => 'new_test_email@hungr.com'}
          response.status.should == 200
        end

        it 'should render updated bare user presentation' do
          put :update_email, 'user' =>  {'email' => 'new_test_email@hungr.com'}
          response.body.should == @user.reload.bare.to_json
        end

      end

      context 'with invalid params' do

        it 'should not update the user email' do
          put :update_email, 'user' =>  {'email' => 'NOTANEMAIL'}
          @user.reload.email.should_not == 'NOTANEMAIL'
        end

        it 'should return 400' do
          put :update_email, 'user' =>  {'email' => 'NOTANEMAIL'}
          response.status.should == 400
        end

        it 'should return with errors presentation' do
          @user.email = "NOTANEMAIL"
          @user.valid?
          user_params = @user.bare
          put :update_email, 'user' => user_params
          response.body.should == @user.with_errors("Invalid Email", @user.errors).to_json
        end

      end

    end

    context 'when signed out' do

      it 'should return 401' do
        put :update_email
        response.status.should == 401
      end

    end

  end

  describe '#update_password' do

    context 'when signed in' do
      before do
        sign_in @user = Factory(:supporter)
      end

      context 'with valid params' do

        it 'should update the password' do
          put :update_password, 'user' => {'password' => 'password2', 'password_confirmation' => 'password2', 'current_password' => 'password'}
          @user.reload.valid_password?('password2').should be_true
        end

        it 'should return 200' do
          put :update_password, 'user' => {'password' => 'password2', 'password_confirmation' => 'password2', 'current_password' => 'password'}
          response.status.should == 200
        end

        it 'should return bare user presentation' do
          put :update_password, 'user' => {'password' => 'password2', 'password_confirmation' => 'password2', 'current_password' => 'password'}
          response.body.should == @user.reload.bare.to_json
        end

      end

      context 'with invalid params' do
        before do
          @user_params = @user.bare
          @user_params[:password] = "password2"
          @user_params[:password_confirmation] = "password2"
          @user_params[:current_password] = "notthepassword"
        end

        it 'should not update the password' do
          put :update_password, 'user' => @user_params
          @user.reload.valid_password?("password2").should be_false
        end

        it 'should return 400' do
          put :update_password, 'user' => @user_params
          response.status.should == 400
        end

        it 'should return user with errors presentation' do
          put :update_password, 'user' => @user_params
          @user.update_with_password(@user_params)
          response.body.should == @user.with_errors("Invalid Password", @user.errors).to_json
        end

      end

    end

    context 'when signed out' do

      it 'should return 401' do
        put :update_password
        response.status.should == 401
      end

    end

  end

  describe '#update_profile' do

    context 'when signed in' do
      before do
        sign_in @user = Factory(:supporter)
      end

      context 'with valid params' do

        it 'should update the profile' do
          put :update_profile, 'user' => {'name' => 'new_user_name'}
          @user.reload.name.should == 'new_user_name'
        end

        it 'should return 200' do
          put :update_profile, 'user' => {'name' => 'new_user_name'}
          response.status.should == 200
        end

        it 'should render bare user presentation' do
          put :update_profile, 'user' => {'name' => 'new_user_name'}
          response.body.should == @user.reload.bare.to_json
        end

      end

      context 'with invalid params' do

        it 'should not update the profile' do
          put :update_profile, 'user' => {'name' => 'no'}
          @user.reload.name.should_not == 'no'
        end

        it 'should return 400' do
          put :update_profile, 'user' => {'name' => 'no'}
          response.status.should == 400
        end

        it 'should return user with errors presentation' do
          @user.name = "no"
          @user.valid?
          user_params = @user.bare
          put :update_profile, 'user' => user_params
          response.body.should == @user.with_errors("Invalid Profile", @user.errors).to_json
        end

      end

    end

    context 'when signed out' do

      it 'should return 401' do
        put :update_profile
        response.status.should == 401
      end

    end

  end

end


text:
require 'spec_helper'
require 'tilt'
require_relative 'factories/environment.rb'
require_relative 'factories/node.rb'
require_relative 'factories/profile.rb'
require_relative 'factories/role.rb'

describe 'Test 00: Bebox::Cli' do

  include FastGettext::Translation

  let(:environment) { build(:environment) }
  let(:node) { build(:node) }
  let(:profile) { build(:profile) }
  let(:role) { build(:role) }
  let(:version) { Bebox::VERSION }
  let(:program_desc) { _('cli.desc') }

  before :each do
    $stderr.stub(:write)
  end

  it 'shows the help for general commands' do
    argv = []
    output = capture(:stdout) { cli_command(argv, :success) }
    new_desc = _('cli.project.new.desc')
    command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/general_help.erb.test')
    expected_content = command_output_template.render(nil, version: version, program_desc: program_desc, new_desc: new_desc).gsub(/\s+/, ' ').strip
    expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
  end

  context '00: general commands' do
    it 'shows error for new without project name' do
      argv = ['new']
      output = capture(:stdout) { cli_command(argv, :failure) }
      expect(output).to match(/#{_('cli.project.new.name_arg_missing')}/)
    end

    it 'executes new project command' do
      argv = ['new', 'pname']
      Bebox::ProjectWizard.any_instance.stub(:create_new_project) { true }
      capture(:stdout) { cli_command(argv, :success) }
    end
  end

  context '01: project commands' do

    before :each do
      Bebox::Cli.any_instance.stub(:inside_project?) { true }
      Bebox::Environment.stub(:environment_exists?) { true }
    end

    it 'shows the help for project commands' do
      Bebox::Environment.stub(:list) {['a', 'b', 'c']}
      argv = []
      output = capture(:stdout) { cli_command(argv, :success) }
      env_desc = _('cli.environment.desc')
      node_desc = _('cli.node.desc')
      command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/in_project_help.erb.test')
      expected_content = command_output_template.render(nil, version: version, program_desc: program_desc, env_desc: env_desc, node_desc: node_desc).gsub(/\s+/, ' ').strip
      expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
    end

    context '02: environment commands' do

      it 'shows the help for environment commands' do
        argv = ['help', 'environment']
        output = capture(:stdout) { cli_command(argv, :success) }
        env_desc = _('cli.environment.desc')
        list_desc = _('cli.environment.list.desc')
        new_desc = _('cli.environment.new.desc')
        remove_desc = _('cli.environment.remove.desc')
        command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/environment_help.erb.test')
        expected_content = command_output_template.render(nil, env_desc: env_desc, new_desc: new_desc, list_desc: list_desc, remove_desc: remove_desc).gsub(/\s+/, ' ').strip
        expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
      end

      it 'list environments' do
        Bebox::Environment.stub(:list) { [environment.name] }
        argv = ['environment', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.environment.list.current_envs')}.*?#{environment.name}/im)
      end

      it 'not list environments if there are not any' do
        Bebox::Environment.stub(:list) { [] }
        argv = ['environment', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.environment.list.current_envs')}.*?#{_('cli.environment.list.no_envs')}/im)
      end

      it 'fails to create a new environment without name' do
        Bebox::EnvironmentWizard.any_instance.stub(:send) { true }
        argv = ['environment', 'new']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.environment.name_arg_missing')}/)
      end

      it 'creates a new environment with name' do
        Bebox::EnvironmentWizard.any_instance.stub(:send) { true }
        argv = ['environment', 'new', environment.name]
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'fails to remove an environment without name' do
        Bebox::EnvironmentWizard.any_instance.stub(:send) { true }
        argv = ['environment', 'remove']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.environment.name_arg_missing')}/)
      end

      it 'removes an environment with name' do
        Bebox::EnvironmentWizard.any_instance.stub(:send) { true }
        argv = ['environment', 'remove', environment.name]
        capture(:stdout) { cli_command(argv, :success) }
      end
    end

    context '03: node commands' do

      before :each do
        Bebox::Environment.stub(:list) { [node.environment] }
      end

      it 'shows the help for node commands' do
        argv = ['help', 'node']
        output = capture(:stdout) { cli_command(argv, :success) }
        node_desc = _('cli.node.desc')
        list_desc = _('cli.node.list.desc')
        new_desc = _('cli.node.new.desc')
        remove_desc = _('cli.node.remove.desc')
        env_flag_desc = _('cli.node.list.env_flag_desc')
        command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/node_help.erb.test')
        expected_content = command_output_template.render(nil, node_desc: node_desc, new_desc: new_desc,
          list_desc: list_desc, remove_desc: remove_desc, env_flag_desc: env_flag_desc).gsub(/\s+/, ' ').strip
        expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
      end

      it 'list nodes if there are any' do
        Bebox::Node.stub(:list) { [node.hostname] }
        argv = ['node', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.node.list.env_nodes_title')%{environment: node.environment}}.*?#{node.hostname}/m)
      end

      it 'not list nodes if there are not any' do
        Bebox::Node.stub(:list) { [] }
        argv = ['node', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.node.list.env_nodes_title')%{environment: node.environment}}.*?#{_('cli.node.list.no_nodes')}/m)
      end

      it 'sets a role for a node' do
        Bebox::Profile.stub(:profiles_count) { 1 }
        Bebox::Role.stub(:roles_count) { 1 }
        Bebox::Node.stub(:count_all_nodes_by_type) { 1 }
        Bebox::NodeWizard.any_instance.stub(:send) { true }
        argv = ['node', 'set_role']
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'creates a new node' do
        Bebox::NodeWizard.any_instance.stub(:send) { true }
        argv = ['node', 'new']
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'removes a node' do
        Bebox::EnvironmentWizard.any_instance.stub(:send) { true }
        argv = ['node', 'remove']
        capture(:stdout) { cli_command(argv, :success) }
      end
    end

    context '04: prepare commands' do

      before :each do
        Bebox::Node.stub(:count_all_nodes_by_type) { 1 }
        Bebox::Node.stub(:list) { [node] }
        Bebox::Node.stub(:nodes_in_environment) { [node] }
      end

      it 'shows an error if vagrant is not installed' do
        Bebox::CommandsHelper.stub(:vagrant_installed?) { false }
        argv = ['prepare']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.prepare.not_vagrant')}/m)
      end

      it 'prepares a node' do
        Bebox::NodeWizard.any_instance.stub(:prepare) { true }
        argv = ['prepare']
        output = capture(:stdout) { cli_command(argv, :success) }
      end

      it 'halts a vagrant node' do
        Bebox::VagrantHelper.stub(:send) { true }
        argv = ['vagrant_halt']
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'ups a vagrant node' do
        Bebox::VagrantHelper.stub(:send) { true }
        argv = ['vagrant_up']
        capture(:stdout) { cli_command(argv, :success) }
      end
    end

    context '05: profile commands' do

      before :each do
        Bebox::Node.stub(:count_all_nodes_by_type) { 1 }
      end

      it 'shows the help for profile commands' do
        argv = ['help', 'profile']
        output = capture(:stdout) { cli_command(argv, :success) }
        profile_desc = _('cli.profile.desc')
        list_desc = _('cli.profile.list.desc')
        new_desc = _('cli.profile.new.desc')
        remove_desc = _('cli.profile.remove.desc')
        command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/profile_help.erb.test')
        expected_content = command_output_template.render(nil, profile_desc: profile_desc,
          new_desc: new_desc, list_desc: list_desc, remove_desc: remove_desc).gsub(/\s+/, ' ').strip
        expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
      end

      it 'list profiles if there are any' do
        Bebox::ProfileWizard.any_instance.stub(:list_profiles) { [profile.name] }
        argv = ['profile', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.profile.list.current_profiles')}.*?#{profile.name}/m)
      end

      it 'not list profiles if there are not any' do
        Bebox::ProfileWizard.any_instance.stub(:list_profiles) { [] }
        argv = ['profile', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.profile.list.no_profiles')}/m)
      end

      it 'can not create a new profile without name' do
        argv = ['profile', 'new']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.profile.new.name_arg_missing')}/)
      end

      it 'creates a new profile with name' do
        Bebox::ProfileWizard.any_instance.stub(:create_new_profile) { true }
        argv = ['profile', 'new', profile.name]
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'removes a profile' do
        Bebox::ProfileWizard.any_instance.stub(:remove_profile) { true }
        argv = ['profile', 'remove', profile.name]
        capture(:stdout) { cli_command(argv, :success) }
      end
    end

    context '06: role commands' do

      before :each do
        Bebox::Profile.stub(:profiles_count) { 1 }
        Bebox::Role.stub(:roles_count) { 1 }
        Bebox::Node.stub(:count_all_nodes_by_type) { 1 }
      end

      it 'shows the help for role commands' do
        argv = ['help', 'role']
        output = capture(:stdout) { cli_command(argv, :success) }
        role_desc = _('cli.role.desc')
        list_desc = _('cli.role.list.desc')
        new_desc = _('cli.role.new.desc')
        remove_desc = _('cli.role.remove.desc')
        add_profile_desc = _('cli.role.add_profile.desc')
        remove_profile_desc = _('cli.role.remove_profile.desc')
        list_profiles_desc = _('cli.role.list_profiles.desc')
        command_output_template = Tilt::ERBTemplate.new('spec/fixtures/commands/role_help.erb.test')
        expected_content = command_output_template.render(nil, role_desc: role_desc, new_desc: new_desc,
          list_desc: list_desc, remove_desc: remove_desc, add_profile_desc: add_profile_desc,
          remove_profile_desc: remove_profile_desc, list_profiles_desc: list_profiles_desc).gsub(/\s+/, ' ').strip
        expect(output.gsub(/\s+/, ' ').strip).to eq(expected_content)
      end

      it 'list roles if there are any' do
        Bebox::Role.stub(:list) { [role.name] }
        argv = ['role', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.role.list.current_roles')}.*?#{role.name}/m)
      end

      it 'not list roles if there are not any' do
        Bebox::Role.stub(:list) { [] }
        argv = ['role', 'list']
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.role.list.no_roles')}/m)
      end

      it 'can not create a new role without name' do
        argv = ['role', 'new']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.role.new.name_arg_missing')}/)
      end

      it 'creates a new role with name' do
        Bebox::ProfileWizard.any_instance.stub(:create_new_role) { true }
        argv = ['role', 'new', role.name]
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'removes a role' do
        Bebox::RoleWizard.any_instance.stub(:send) { true }
        argv = ['role', 'remove']
        capture(:stdout) { cli_command(argv, :success) }
      end

      it 'can not list role profiles without a role name' do
        argv = ['role', 'list_profiles']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.role.list_profiles.name_arg_missing')}/m)
      end

      it 'can not list role profiles if role not exist' do
        Bebox::Role.stub(:list_profiles) { [] }
        Bebox::RoleWizard.any_instance.stub(:role_exists?) { false }
        argv = ['role', 'list_profiles', role.name]
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.role.list_profiles.name_not_exist')%{role: role.name}}/m)
      end

      it 'not list role profiles if there are not any' do
        Bebox::RoleWizard.any_instance.stub(:role_exists?) { true }
        Bebox::Role.stub(:list_profiles) { [] }
        argv = ['role', 'list_profiles', role.name]
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.role.list_profiles.no_profiles')%{role: role.name}}/m)
      end

      it 'list role profiles if there are any' do
        Bebox::RoleWizard.any_instance.stub(:role_exists?) { true }
        Bebox::Role.stub(:list_profiles) { [profile.name] }
        argv = ['role', 'list_profiles', role.name]
        output = capture(:stdout) { cli_command(argv, :success) }
        expect(output).to match(/#{_('cli.role.list_profiles.current_profiles')%{role: role.name}}.*?#{profile.name}/m)
      end
    end

    context '07: provision commands' do

      before :each do
        Bebox::Node.stub(:count_all_nodes_by_type) { 1 }
      end

      it 'can not apply provision if the step is not supplied' do
        argv = ['apply']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.provision.name_missing')}/m)
      end

      it 'can not apply provision if the step is not valid' do
        argv = ['apply', 'step']
        output = capture(:stdout) { cli_command(argv, :failure) }
        expect(output).to match(/#{_('cli.provision.name_invalid')}/m)
      end

      it 'applies provision if the step is valid' do
        Bebox::ProvisionWizard.any_instance.stub(:apply_step) { true }
        argv = ['apply', 'step-0']
        output = capture(:stdout) { cli_command(argv, :success) }
      end

      it 'applies provision in all steps' do
        Bebox::ProvisionWizard.any_instance.stub(:apply_step) { true }
        argv = ['apply', '--all']
        output = capture(:stdout) { cli_command(argv, :success) }
      end
    end
  end
end

# Helper method to capture the STDOUT from commands
def capture(stream)
  begin
    stream = stream.to_s
    eval "$#{stream} = StringIO.new"
    yield
    result = eval("$#{stream}").string
  ensure
    eval("$#{stream} = #{stream.upcase}")
  end
  result
end

# Executes a cli command and do expectation from return status
def cli_command(argv, expectation)
  begin
    Bebox::Cli.new(argv)
  rescue SystemExit => e
    if expectation == :success
      expect([0, 1]).to include(e.status)
    else
      expect([0, 1]).to_not include(e.status)
    end
  end
end


text:
<html>
 <head>
	<script src="../js/jquery.min.js"></script>
	<script src="../js/shared.js"></script>
	<script src="../js/ril.js"></script>
  	<script src='../js/background.js'></script>
 </head>
<body>
</body>
</html>


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

public class SlideImageScene3 : MonoBehaviour
{

	private UISpriteAnimation spriteAni;
	GameObject MySprite;
	List<TweenAlpha> tweens = new List<TweenAlpha>();
	private int num = 0;
	private Vector3 startpos;
	private Vector3 endpos;
	// Use this for initialization
	void Start()
	{
		MySprite = GameObject.Find("MySprite");
		spriteAni = MySprite.GetComponent<UISpriteAnimation>();
		spriteAni.Pause();

		List<GameObject> text=new List<GameObject>();
		for (int i = 0; i < 3; i++) {
			text.Add(Instantiate(Resources.Load("hqqScene3/text" + i)) as GameObject);
			text[i].transform.parent = GameObject.Find("Panel").transform;
			text[i].transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
		}

		text[0].transform.localPosition = new Vector3(234, 466, 0);
		text[1].transform.localPosition = new Vector3(1, 389, 0);
		text[2].transform.localPosition = new Vector3(2, 489, 0);

		for (int i = 0; i < text.Count; i++) {
			tweens.Add(text[i].GetComponent<TweenAlpha>());
			tweens[i].Play(false);
		}

		StaticGlobal.Spin=false;

	}

	// Update is called once per frame
	void Update()
	{
	}

	void OnDragStart()
	{
		startpos = Input.mousePosition;
	}

	void OnDragEnd()
	{
		endpos = Input.mousePosition;
		float delta = endpos.x - startpos.x;
		if (delta >= 0)
			switch (num)
		{
		case 0:
			spriteAni.resetFrame(24);
			spriteAni.PlayTo(7);

			tweens[2].Play(false);
			tweens[0].Play(true);
			num++;
			break;
		case 1:
			spriteAni.PlayTo(13);

			tweens[0].PlayReverse();
			tweens[1].Play(true);
			num++;
			break;
		case 2:
			spriteAni.PlayTo(19);

			tweens[1].PlayReverse();

			num++;
			break;
		case 3:
			spriteAni.PlayTo(25);

			num++;
			break;
		case 4:
			tweens[2].Play(true);

			spriteAni.resetFrame(8);
			spriteAni.PlayTo(35);
			spriteAni.RebuildSpriteList();
			spriteAni.PlayTo(0);
			num = 0;
			break;
		}
		else if (delta < 0)
			switch (num)
		{
		case 0:
			spriteAni.resetFrame(24);
			spriteAni.PlayTo(7);

			tweens[2].Play(false);
			tweens[0].Play(true);
			num++;
			break;
		case 1:
			spriteAni.PlayToReverse(0);

			tweens[0].PlayReverse();
			num--;
			break;
		case 2:
			spriteAni.PlayToReverse(5);

			tweens[1].PlayReverse();
			tweens[0].Play(true);
			num--;
			break;
		case 3:
			spriteAni.PlayToReverse(11);
			num--;
			break;
		case 4:
			spriteAni.PlayToReverse(17);
			num--;
			break;
		}
	}

}


text:
package de.appplant.cordova.plugin.localnotification;

import java.util.Calendar;
import java.util.Date;

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

import android.app.Activity;
import android.app.AlarmManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;

/**
 * Class that helps to store the options that can be specified per alarm.
 */
public class Options {

    private JSONObject options = new JSONObject();
    private String packageName = null;
    private long interval      = 0;

    Options (Activity activity) {
        packageName = activity.getPackageName();
    }

    Options (Context context) {
        packageName = context.getPackageName();
    }

    /**
     * Parses the given properties
     */
    public Options parse (JSONObject options) {
        String repeat = options.optString("repeat");

        this.options = options;

        if (repeat.equalsIgnoreCase("secondly")) {
            interval = 1000;
        } if (repeat.equalsIgnoreCase("minutely")) {
            interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES / 15;
        } if (repeat.equalsIgnoreCase("hourly")) {
            interval = AlarmManager.INTERVAL_HOUR;
        } if (repeat.equalsIgnoreCase("daily")) {
            interval = AlarmManager.INTERVAL_DAY;
        } else if (repeat.equalsIgnoreCase("weekly")) {
            interval = AlarmManager.INTERVAL_DAY*7;
        } else if (repeat.equalsIgnoreCase("monthly")) {
            interval = AlarmManager.INTERVAL_DAY*31; // 31 days
        } else if (repeat.equalsIgnoreCase("yearly")) {
            interval = AlarmManager.INTERVAL_DAY*365;
        } else {
            try {
                interval = Integer.parseInt(repeat) * 60000;
            } catch (Exception e) {};
        }

        return this;
    }

    /**
     * Set new time according to interval
     */
    public Options moveDate () {
        try {
            options.put("date", (getDate() + interval) / 1000);
        } catch (JSONException e) {}

        return this;
    }

    /**
     * Returns options as JSON object
     */
    public JSONObject getJSONObject() {
        return options;
    }

    /**
     * Returns time in milliseconds when notification is scheduled to fire
     */
    public long getDate() {
        return options.optLong("date", 0) * 1000;
    }

    /**
     * Returns time as calender
     */
    public Calendar getCalendar () {
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(new Date(getDate()));

        return calendar;
    }

    /**
     * Returns the notification's message
     */
    public String getMessage () {
        return options.optString("message", "");
    }

    /**
     * Returns the notification's title
     */
    public String getTitle () {
        return options.optString("title", "");
    }

    /**
     * Returns the path of the notification's sound file
     */
    public Uri getSound () {
        String sound = options.optString("sound", null);

        if (sound != null) {
            try {
                int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class);

                return RingtoneManager.getDefaultUri(soundId);
            } catch (Exception e) {
                return Uri.parse(sound);
            }
        }

        return null;
    }

    /**
     * Returns the icon's ID
     */
    public int getIcon () {
        int icon        = 0;
        String iconName = options.optString("icon", "icon");

        icon = getIconValue(packageName, iconName);

        if (icon == 0) {
            icon = getIconValue("android", iconName);
        }

        if (icon == 0) {
            icon = android.R.drawable.ic_menu_info_details;
        }

        return options.optInt("icon", icon);
    }

    /**
     * Returns the small icon's ID
     */
    public int getSmallIcon () {
        int resId       = 0;
        String iconName = options.optString("smallIcon", "");

        resId = getIconValue(packageName, iconName);

        if (resId == 0) {
            resId = getIconValue("android", iconName);
        }

        if (resId == 0) {
            resId = getIcon();
        }

        return options.optInt("smallIcon", resId);
    }

    /**
     * Returns notification repetition interval (daily, weekly, monthly, yearly)
     */
    public long getInterval () {
        return interval;
    }

    /**
     * Returns notification badge number
     */
    public int getBadge () {
        return options.optInt("badge", 0);
    }

    /**
     * Returns PluginResults' callback ID
     */
    public String getId () {
        return options.optString("id", "0");
    }

    /**
     * Returns whether notification is cancelled automatically when clicked.
     */
    public Boolean getAutoCancel () {
        return options.optBoolean("autoCancel", false);
    }

    /**
     * Returns whether the notification is ongoing (uncancellable). Android only.
     */
    public Boolean getOngoing () {
        return options.optBoolean("ongoing", false);
    }

    /**
     * Returns additional data as string
     */
    public String getJSON () {
        return options.optString("json", "");
    }

    /**
     * Returns numerical icon Value
     *
     * @param {String} className
     * @param {String} iconName
     */
    private int getIconValue (String className, String iconName) {
        int icon = 0;

        try {
            Class<?> klass  = Class.forName(className + ".R$drawable");

            icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class);
        } catch (Exception e) {}

        return icon;
    }
}


text:
package uk.co.cbray.msc.nhsdsp.utils;

import static org.junit.Assert.*;

import org.junit.Test;

public class UserHelperTest {

	@Test
	public void testValidateEmailReturnsTrueForValidEmail() {
		String email = "connor.bray@email.com";
		boolean isValid = UserHelper.validateEmail(email);
		assertTrue(isValid);
	}

	@Test
	public void testValidateEmailReturnsFalseForInValidEmail() {
		String email = "connor.bray";
		boolean isValid = UserHelper.validateEmail(email);
		assertFalse(isValid);
	}

}


text:
source env/bin/activate

#python3 --version

./hello.py


text:
package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/gianarb/orbiter/cmd"
	"github.com/gianarb/orbiter/utils/hook"
	"github.com/mitchellh/cli"
)

func main() {
	eventChannel := make(chan *logrus.Entry)
	logrus.AddHook(hook.NewChannelHook(eventChannel))

	c := cli.NewCLI("orbiter", "0.0.0")
	c.Args = os.Args[1:]

	c.Commands = map[string]cli.CommandFactory{
		"daemon": func() (cli.Command, error) {
			return &cmd.DaemonCmd{
				EventChannel: eventChannel,
			}, nil
		},
		"autoscaler ls": func() (cli.Command, error) {
			return &cmd.AutoscalerListCmd{}, nil
		},
		"system events": func() (cli.Command, error) {
			return &cmd.SystemEventsCmd{}, nil
		},
	}

	exitStatus, _ := c.Run()
	os.Exit(exitStatus)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: arch/mips/bare_iron/system.hh Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

File List

File Members

arch/mips/bare_iron/system.hh
Go to the documentation of this file.

00001
00030
00031 #ifndef __ARCH_MIPS_BARE_IRON_SYSTEM_HH__
00032 #define __ARCH_MIPS_BARE_IRON_SYSTEM_HH__
00033
00034 #include "arch/mips/system.hh"
00035 #include "params/BareIronMipsSystem.hh"
00036
00042 class BareIronMipsSystem : public MipsSystem
00043 {
00044   public:
00045     static const int CommandLineSize = 256;
00046
00047     BareIronMipsSystem(Params *p);
00048     ~BareIronMipsSystem();
00049 };
00050
00051 #endif // __ARCH_MIPS_BARE_IRON_SYSTEM_HH__

<address style="align: right;">
Generated on Fri Apr 17 12:38:38 2015 for gem5 by  doxygen 1.4.7</address>


text:
import {
  Component,
  ElementRef,
  OnInit,
  Input,
  Output,
  EventEmitter,
  OnChanges,
  ViewChild

} from "@angular/core";
import {ValidationService} from "../services/validation.service";
import {FormControl} from "@angular/forms";
import {FormControlMessages} from "./control-valdation-message.component";

@Component({
  selector: 'doc-uploader',
  template: ` {{fileName}}

                    <input type="file" class="inputfile" id="file" #inputFile (change)="onFileSelect($event)">
                     {{fileName?fileName:"Choose a File..."}}

*Supported Extension : {{allowedExtMessage}} and max size : {{allowedSize}} MB

                    <control-messages [isSubmitted]="isSubmitted"
                     [control]="docFormControl"></control-messages>`

})
export class DocumentUploader implements OnInit,OnChanges {
  @Input() docFormControl: FormControl;
  @Input() fileName: string;
  @Input() allowedExt: string[];
  @Input() allowedSize: number;
  @Input() isSubmitted: boolean;
  @Output() fileSelectedEvent: EventEmitter<any> = new EventEmitter();
  @Output() deleteFileEvent: EventEmitter<any> = new EventEmitter();
  @ViewChild('inputFile') inputFile;
  private file: File;
  isValidFile: boolean = true;
  private isFresh: boolean = false;
  allowedExtMessage: string;

  constructor() {
  }

  ngOnInit() {
    this.allowedExtMessage = this.allowedExt.join(',');
  }

  onFileSelect(e) {
    this.file = e.target.files[0];
    let allowedExt: string[] = this.allowedExt;
    let allowedSize: number = this.allowedSize;
    this.isValidFile = ValidationService.documentValidation(this.file, allowedExt, allowedSize);
    if (this.isValidFile) {
      this.docFormControl.patchValue(this.file.name);
      if (!this.fileName)
        this.isFresh = true;
      this.fileName = this.file.name;
      this.fileSelectedEvent.emit(this.file);
    }
    else {
      this.docFormControl.patchValue("");
      this.inputFile.nativeElement.value = "";
    }
  }

  onDeleteFile(docId: string) {
    if (!this.isFresh)
      this.deleteFileEvent.emit(docId);
    else
      this.clearValue();
  }

  clearValue() {
    this.file = null;
    this.fileName = "";
    this.docFormControl.patchValue("");
    this.inputFile.nativeElement.value = "";
  }

  ngOnChanges() {
    if (this.fileName) {
      this.docFormControl.patchValue(this.fileName);
    }
    else
      this.clearValue();
  }

  /* End Doc Handler */
}


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

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

<title>
	Erayo, Soratami Ascendant (Saviors of Kamigawa) - Gatherer - Magic: The Gathering
</title><link rel="shortcut icon" href="/Images/favicon.ico" /><meta name="description" content="Gatherer is the Magic Card Database. Search for the perfect addition to your deck. Browse through cards from Magic's entire history. See cards from the most recent sets and discover what players just like you are saying about them." /><meta name="keywords" content="monitor, gatherer, magic cards, magic the gathering, black lotus, magic: the gathering, wizards of the coast, wizards, trading card game, trading cards, collectible card game, tcg, ccg, magic sets, game, multiplayer, hobby" />

<link type="text/css" rel="stylesheet" media="screen" href="../../Styles/Styles.css" /><link href="/WebResource.axd?d=or7PpBsqDI3hlaEEThlmVDRzePzSrFyHvCSdTElIIm8jbPXP5PySeVoGjKlN7Df_R8Yrdfm8DAtAevqXp4wu4Fffv7Dmtd4mn4Xjxa7bf43SyevX1NnB9KBh--rFBOmlJp3lTErOKCK5IJhfE-mweMernyA1&amp;t=634873966152854778" rel="icon" type="image/ico" />

    <form name="aspnetForm" method="post" action="Details.aspx?multiverseid=87599&part=Erayo's+Essence" id="aspnetForm">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQxOTY5NzI3NGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgMFO2N0bDAwJGN0bDAwJGN0bDAwJE1haW5Db250ZW50JFNlYXJjaENvbnRyb2xzJFNlYXJjaENhcmROYW1lBTxjdGwwMCRjdGwwMCRjdGwwMCRNYWluQ29udGVudCRTZWFyY2hDb250cm9scyRTZWFyY2hDYXJkVHlwZXMFO2N0bDAwJGN0bDAwJGN0bDAwJE1haW5Db250ZW50JFNlYXJjaENvbnRyb2xzJFNlYXJjaENhcmRUZXh08eaAgh/v97psiSof7KwBwiyoYMg=" />

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBgKBx/f1CgKw+7DyCgKKqPSlCQLIiJiWCgLgiMDeAwKBjNExzlwNG+VjazOiCGcrd1YqUcDjdvo=" />

    Simple
    Advanced
    Random Card
    Settings
    Language
    Help

<input name="ctl00$ctl00$ctl00$MainContent$SearchControls$CardSearchBoxParent$CardSearchBox" type="text" id="ctl00_ctl00_ctl00_MainContent_SearchControls_CardSearchBoxParent_CardSearchBox" class="textboxinput" onblur="SetCurrentControlBlur(event)" onfocus="SetCurrentControlFocus(event, this);" autocomplete="off" maxlength="50" />

        <input type="submit" name="ctl00$ctl00$ctl00$MainContent$SearchControls$searchSubmitButton" value="Search" id="ctl00_ctl00_ctl00_MainContent_SearchControls_searchSubmitButton" class="searchbutton" />

                Results

                    All Results

            using...

                    <input name="ctl00$ctl00$ctl00$MainContent$SearchControls$SearchCardName" type="checkbox" id="ctl00_ctl00_ctl00_MainContent_SearchControls_SearchCardName" checked="checked" onclick="UpdateSimpleSearchFields" />
                    Name

                    <input name="ctl00$ctl00$ctl00$MainContent$SearchControls$SearchCardTypes" type="checkbox" id="ctl00_ctl00_ctl00_MainContent_SearchControls_SearchCardTypes" onclick="UpdateSimpleSearchFields" />
                    Types

                    <input name="ctl00$ctl00$ctl00$MainContent$SearchControls$SearchCardText" type="checkbox" id="ctl00_ctl00_ctl00_MainContent_SearchControls_SearchCardText" onclick="UpdateSimpleSearchFields" />
                    Text

    Erayo, Soratami Ascendant

Discussion

Languages

Sets & Legality

Details

        Display: Oracle | Printed

                        Card Name:

                        Erayo, Soratami Ascendant

                        Mana Cost:

                        Converted Mana Cost:

                        2

                        Types:

                        Legendary Creature  — Moonfolk Monk

                        Card Text:

Flying

Whenever the fourth spell of a turn is cast, flip Erayo, Soratami Ascendant.

                        P/T:

                        1 / 1

                        Expansion:

                            Saviors of Kamigawa

                        Rarity:

                        Rare

                        Card #:

                        35a

                        Artist:

                        Matt Cavotta

                        Community Rating:

        Rating: 4.649 / 5  (87 votes)

                    Click here to rate and
                    discuss this card.

                    Rulings

                            Display Rulings

                                        6/1/2005

                                        Erayo's Essence triggers only for the first spell an opponent casts in a given turn. It doesn't trigger off any other spell that player casts after the first.

                                        6/1/2005

                                        If Erayo, Soratami Ascendant flips while an opponent's first spell for the turn is still on the stack, the ability of Erayo's Essence doesn't trigger because the opponent's spell has already been cast. The spell isn't countered.

                                        6/1/2005

                                        If you have multiple opponents, Erayo's Essence can trigger once for each opponent.

                                        6/1/2005

                                        Each Ascendant is Legendary in both its unflipped and flipped forms. This means that effects that look for Legendary creature cards, such as Time of Need and Captain Sisay, can find an Ascendant.

                        Card Name:

                        Erayo's Essence

                        Mana Cost:

                        Converted Mana Cost:

                        2

                        Types:

                        Legendary Enchantment

                        Card Text:

Whenever an opponent casts a spell for the first time in a turn, counter that spell.

                        P/T:

                        1 / 1

                        Expansion:

                            Saviors of Kamigawa

                        Rarity:

                        Rare

                        Card #:

                        35b

                        Artist:

                        Matt Cavotta

                        Community Rating:

        Rating: 4.649 / 5  (87 votes)

                    Click here to rate and
                    discuss this card.

                magicthegathering.com
                Magic: The Gathering
                    Online   Settings
                Language   Help |
                    Login

                               © 1995 - 2012 Wizards of the Coast LLC,
                    a subsidiary of Hasbro, Inc. All Rights Reserved.

    </form>


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

import io.prestosql.tests.AbstractTestIntegrationSmokeTest;

import static io.airlift.tpch.TpchTable.ORDERS;
import static io.prestosql.plugin.jdbc.JdbcQueryRunner.createJdbcQueryRunner;

public class TestJdbcIntegrationSmokeTest
        extends AbstractTestIntegrationSmokeTest
{
    public TestJdbcIntegrationSmokeTest()
    {
        super(() -> createJdbcQueryRunner(ORDERS));
    }
}


text:
package org.opencb.opencga.catalog.utils;

public class Constants {

    /* ****************************************    Additional QueryOptions parameters    ************************************************/
    /**
     * Boolean used when passing a list of entries. If silent is true, it will try to perform all the actions for all the entries possible.
     * Otherwise, if one of them fails for whatever reason, the response will be an error.
     */
    public static final String SILENT = "silent";

    /**
     * Forces some operations that would not be possible to perform otherwise.
     */
    public static final String FORCE = "force";

    /**
     * Map of actions that will only be used on updates to know how to deal with the update of array objects.
     */
    public static final String ACTIONS = "actions";

    /* ****************************************    Additional parameters                 ************************************************/

    /**
     * Used when deleting a sample.
     *
     * Action to be performed over files that were associated only to the sample to be deleted. Possible actions are NONE, TRASH, DELETE.
     */
    public static final String EMPTY_FILES_ACTION = "emptyFilesAction";

    /**
     * Used when deleting a sample.
     *
     * Boolean indicating if the cohorts associated only to the sample to be deleted should be also deleted.
     */
    public static final String DELETE_EMPTY_COHORTS = "deleteEmptyCohorts";

    /**
     * Used when deleting a file.
     *
     * Skip the trash and perform a physical deletion of local files and folders directly.
     */
    public static final String SKIP_TRASH = "skipTrash";

    /* ****************************************    Variable constants for versioning     ************************************************/
    /**
     * Boolean parameter indicating that all the versions are expected to be retrieved.
     */
    public static final String ALL_VERSIONS = "allVersions";

    /* ****************************************    Variable constants for annotations       ********************************************/
    /**
     * String used to include/exclude fields in the query option. It should be used like ANNOTATION.a.b where a.b will be the variable to
     * be included/excluded from the results.
     */
    public static final String ANNOTATION = "annotation";

    /**
     * String used to include/exclude fields in the query option. It should be used like ANNOTATION_SET_NAME.annotation where annotation
     * will be the AnnotationSetName whose annotations will be included/excluded from the results.
     */
    public static final String ANNOTATION_SET_NAME = "annotationSet";

    /**
     * String used to include/exclude fields in the query option. It should be used like VARIABLE_SET.55 where 55 will be the VariableSetId
     * whose annotations will be included/excluded from the results.
     */
    public static final String VARIABLE_SET = "variableSet";

    /**
     * String created in the AnnotationSetManager layer where the different variable types of the variables being queried will be written
     * to simplify the access to the database when the DBAdaptor layer creates parses the query to the actual database query.
     */
    public static final String PRIVATE_ANNOTATION_PARAM_TYPES = "_annotationTypes";

    /* ****************************************    Private attributes       ********************************************/
    /**
     * Reserved key in attributes for OpenCGA attributes.
     */
    public static final String PRIVATE_OPENCGA_ATTRIBUTES = "_opencga";

    /**
     * Key in attributes to contain the list of deleted files that were used as input for a job.
     */
    public static final String JOB_DELETED_INPUT_FILES = "deletedInputFiles";

    /**
     * Key in attributes to contain the list of deleted files that were generated by a job.
     */
    public static final String JOB_DELETED_OUTPUT_FILES = "deletedOutputFiles";

    /**
     * Key in attributes to contain the deleted folder used by a job as the output directory.
     */
    public static final String JOB_DELETED_OUTPUT_DIRECTORY = "deletedOutputFiles";

}


text:
package com.portfolioeffect.quant.client.util;

public interface SimpleMetricUpdateCallback {

	public void onDataRefresh(float[] data, long[] time);

}


text:
   <form class="well form-horizontal" action="http://formspree.io/contact@bowtieanalytics.net" method="post">
      <fieldset>

         <legend>Send us a message!</legend>
         <input type="hidden" name="_next" value="contact_thanks" />
         <input type="hidden" name="_format" value="plain" />
         <input type="text" name="_gotcha" style="display:none" />

            First Name

                  <input  name="first_name" placeholder="Your first name" class="form-control"  type="text">

            Last Name

                  <input name="last_name" placeholder="Your last name" class="form-control"  type="text">

            Email

                  <input name="email" placeholder="Your email address" class="form-control"  type="text">

            Subject

                  <input name="_subject" placeholder="Subject" class="form-control"  type="text">

            Message

                  <textarea class="form-control" name="message" placeholder="Your message for Bowtie Analytics"></textarea>

               <button type="submit" class="btn btn-warning" >Send </button>

      </fieldset>
   </form>


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Legacy Payment Tokens.
 * Payment Tokens were introduced in 2.6.0 with create and update as methods.
 * Major CRUD changes occurred in 3.0, so these were deprecated (save and delete still work).
 * This legacy class is for backwards compatibility in case any code called ->read, ->update or ->create
 * directly on the object.
 *
 * @version  3.0.0
 * @package  WooCommerce/Classes
 * @category Class
 * @author   WooCommerce
 */
abstract class WC_Legacy_Payment_Token extends WC_Data {

	/**
	 * Sets the type of this payment token (CC, eCheck, or something else).
	 *
	 * @param string Payment Token Type (CC, eCheck)
	 */
	public function set_type( $type ) {
		wc_deprecated_function( 'WC_Payment_Token::set_type', '3.0.0', 'Type cannot be overwritten.' );
	}

	/**
	 * Read a token by ID.
	 * @deprecated 3.0.0 - Init a token class with an ID.
	 *
	 * @param int $token_id
	 */
	public function read( $token_id ) {
		wc_deprecated_function( 'WC_Payment_Token::read', '3.0.0', 'a new token class initialized with an ID.' );
		$this->set_id( $token_id );
		$data_store = WC_Data_Store::load( 'payment-token' );
		$data_store->read( $this );
	}

	/**
	 * Update a token.
	 * @deprecated 3.0.0 - Use ::save instead.
	 */
	public function update() {
		wc_deprecated_function( 'WC_Payment_Token::update', '3.0.0', 'WC_Payment_Token::save instead.' );
		$data_store = WC_Data_Store::load( 'payment-token' );
		try {
			$data_store->update( $this );
		} catch ( Exception $e ) {
			return false;
		}
	}

	/**
	 * Create a token.
	 * @deprecated 3.0.0 - Use ::save instead.
	 */
	public function create() {
		wc_deprecated_function( 'WC_Payment_Token::create', '3.0.0', 'WC_Payment_Token::save instead.' );
		$data_store = WC_Data_Store::load( 'payment-token' );
		try {
			$data_store->create( $this );
		} catch ( Exception $e ) {
			return false;
		}
	}

}


text:
import { Options } from "ez-plus";

$(document).ready(() => {
    // basic usage
    $('#image').ezPlus();

    // with options
    const options: Options = {
        zoomLens: true,
        zoomType: 'lens',
        cursor: 'crosshair'
    };
    $('#image').ezPlus(options);
});