text:
#include "third_party/blink/renderer/core/css/media_list.h"

#include <memory>
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/css/media_query_exp.h"
#include "third_party/blink/renderer/core/css/parser/media_query_parser.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"

namespace blink {

/* MediaList is used to store 3 types of media related entities which mean the
 * same:
 *
 * Media Queries, Media Types and Media Descriptors.
 *
 * Media queries, as described in the Media Queries Level 3 specification, build
 * on the mechanism outlined in HTML4. The syntax of media queries fit into the
 * media type syntax reserved in HTML4. The media attribute of HTML4 also exists
 * in XHTML and generic XML. The same syntax can also be used inside the @media
 * and @import rules of CSS.
 *
 * However, the parsing rules for media queries are incompatible with those of
 * HTML4 and are consistent with those of media queries used in CSS.
 *
 * HTML5 (at the moment of writing still work in progress) references the Media
 * Queries specification directly and thus updates the rules for HTML.
 *
 * CSS 2.1 Spec (http://www.w3.org/TR/CSS21/media.html)
 * CSS 3 Media Queries Spec (http://www.w3.org/TR/css3-mediaqueries/)
 */

MediaQuerySet::MediaQuerySet() = default;

MediaQuerySet::MediaQuerySet(const MediaQuerySet& o)
    : queries_(o.queries_.size()) {
  for (unsigned i = 0; i < queries_.size(); ++i)
    queries_[i] = o.queries_[i]->Copy();
}

scoped_refptr<MediaQuerySet> MediaQuerySet::Create(
    const String& media_string,
    const ExecutionContext* execution_context) {
  if (media_string.IsEmpty())
    return MediaQuerySet::Create();

  return MediaQueryParser::ParseMediaQuerySet(media_string, execution_context);
}

bool MediaQuerySet::Set(const String& media_string,
                        const ExecutionContext* execution_context) {
  scoped_refptr<MediaQuerySet> result = Create(media_string, execution_context);
  // TODO(keishi) Changed DCHECK to CHECK for crbug.com/699269 diagnosis
  for (const auto& query : result->queries_) {
    CHECK(query);
  }
  queries_.swap(result->queries_);
  return true;
}

bool MediaQuerySet::Add(const String& query_string,
                        const ExecutionContext* execution_context) {
  // To "parse a media query" for a given string means to follow "the parse
  // a media query list" steps and return "null" if more than one media query
  // is returned, or else the returned media query.
  scoped_refptr<MediaQuerySet> result = Create(query_string, execution_context);

  // Only continue if exactly one media query is found, as described above.
  if (result->queries_.size() != 1)
    return false;

  std::unique_ptr<MediaQuery> new_query = std::move(result->queries_[0]);
  // TODO(keishi) Changed DCHECK to CHECK for crbug.com/699269 diagnosis
  CHECK(new_query);

  // If comparing with any of the media queries in the collection of media
  // queries returns true terminate these steps.
  for (wtf_size_t i = 0; i < queries_.size(); ++i) {
    MediaQuery& query = *queries_[i];
    if (query == *new_query)
      return false;
  }

  queries_.push_back(std::move(new_query));
  return true;
}

bool MediaQuerySet::Remove(const String& query_string_to_remove,
                           const ExecutionContext* execution_context) {
  // To "parse a media query" for a given string means to follow "the parse
  // a media query list" steps and return "null" if more than one media query
  // is returned, or else the returned media query.
  scoped_refptr<MediaQuerySet> result =
      Create(query_string_to_remove, execution_context);

  // Only continue if exactly one media query is found, as described above.
  if (result->queries_.size() != 1)
    return true;

  std::unique_ptr<MediaQuery> new_query = std::move(result->queries_[0]);
  // TODO(keishi) Changed DCHECK to CHECK for crbug.com/699269 diagnosis
  CHECK(new_query);

  // Remove any media query from the collection of media queries for which
  // comparing with the media query returns true.
  bool found = false;
  for (wtf_size_t i = 0; i < queries_.size(); ++i) {
    MediaQuery& query = *queries_[i];
    if (query == *new_query) {
      queries_.EraseAt(i);
      --i;
      found = true;
    }
  }

  return found;
}

void MediaQuerySet::AddMediaQuery(std::unique_ptr<MediaQuery> media_query) {
  // TODO(keishi) Changed DCHECK to CHECK for crbug.com/699269 diagnosis
  CHECK(media_query);
  queries_.push_back(std::move(media_query));
}

String MediaQuerySet::MediaText() const {
  StringBuilder text;

  bool first = true;
  for (wtf_size_t i = 0; i < queries_.size(); ++i) {
    if (!first)
      text.Append(", ");
    else
      first = false;
    text.Append(queries_[i]->CssText());
  }
  return text.ReleaseString();
}

bool MediaQuerySet::HasUnknown() const {
  for (const auto& media_query : QueryVector()) {
    if (media_query->HasUnknown())
      return true;
  }
  return false;
}

MediaList::MediaList(scoped_refptr<MediaQuerySet> media_queries,
                     CSSStyleSheet* parent_sheet)
    : media_queries_(media_queries),
      parent_style_sheet_(parent_sheet),
      parent_rule_(nullptr) {}

MediaList::MediaList(scoped_refptr<MediaQuerySet> media_queries,
                     CSSRule* parent_rule)
    : media_queries_(media_queries),
      parent_style_sheet_(nullptr),
      parent_rule_(parent_rule) {}

String MediaList::mediaText(ExecutionContext* execution_context) const {
  if (media_queries_->HasUnknown())
    UseCounter::Count(execution_context, WebFeature::kCSSMediaListUnknown);
  return MediaTextInternal();
}

void MediaList::setMediaText(const ExecutionContext* execution_context,
                             const String& value) {
  CSSStyleSheet::RuleMutationScope mutation_scope(parent_rule_);

  media_queries_->Set(value, execution_context);

  if (parent_style_sheet_)
    parent_style_sheet_->DidMutate(CSSStyleSheet::Mutation::kSheet);
}

String MediaList::item(unsigned index) const {
  const Vector<std::unique_ptr<MediaQuery>>& queries =
      media_queries_->QueryVector();
  if (index < queries.size())
    return queries[index]->CssText();
  return String();
}

void MediaList::deleteMedium(const ExecutionContext* execution_context,
                             const String& medium,
                             ExceptionState& exception_state) {
  CSSStyleSheet::RuleMutationScope mutation_scope(parent_rule_);

  bool success = media_queries_->Remove(medium, execution_context);
  if (!success) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotFoundError,
                                      "Failed to delete '" + medium + "'.");
    return;
  }
  if (parent_style_sheet_)
    parent_style_sheet_->DidMutate(CSSStyleSheet::Mutation::kSheet);
}

void MediaList::appendMedium(const ExecutionContext* execution_context,
                             const String& medium) {
  CSSStyleSheet::RuleMutationScope mutation_scope(parent_rule_);

  bool added = media_queries_->Add(medium, execution_context);
  if (!added)
    return;

  if (parent_style_sheet_)
    parent_style_sheet_->DidMutate(CSSStyleSheet::Mutation::kSheet);
}

void MediaList::Reattach(scoped_refptr<MediaQuerySet> media_queries) {
  // TODO(keishi) Changed DCHECK to CHECK for crbug.com/699269 diagnosis
  CHECK(media_queries);
  for (const auto& query : media_queries->QueryVector()) {
    CHECK(query);
  }
  media_queries_ = media_queries;
}

void MediaList::Trace(Visitor* visitor) const {
  visitor->Trace(parent_style_sheet_);
  visitor->Trace(parent_rule_);
  ScriptWrappable::Trace(visitor);
}

}  // namespace blink


text:
(function(outerScope){
  if (typeof this.$ === 'undefined') {
    throw new Error('jquery.js/zepto.js required to run Thorax');
  } else {
    if (!$.fn.forEach) {
      // support jquery/zepto iterators
      $.fn.forEach = $.fn.each;
     }
  }

  if (typeof this._ === 'undefined') {
    throw new Error('Underscore.js required to run Thorax');
  }

  if (typeof this.Backbone === 'undefined') {
    throw new Error('Backbone.js required to run Thorax');
  }

  var TemplateEngine = {
    extension: 'handlebars',
    safeString: function(string) {
      return new Handlebars.SafeString(string);
    },
    registerHelper: function(name, callback) {
      return Handlebars.registerHelper(name, callback);
    }
  };
  TemplateEngine.extensionRegExp = new RegExp('\\.' + TemplateEngine.extension + '$');

  var Thorax, scope, templatePathPrefix;

  this.Thorax = Thorax = {
    configure: function(options) {
      scope = (options && options.scope) || (typeof exports !== 'undefined' && exports);

      if (!scope) {
        scope = outerScope.Application = {};
      }

      _.extend(scope, Backbone.Events, {
        templates: {},
        Views: {},
        Mixins: {},
        Models: {},
        Collections: {},
        Routers: {}
      });

      templatePathPrefix = options && typeof options.templatePathPrefix !== 'undefined' ? options.templatePathPrefix : '';

      Backbone.history || (Backbone.history = new Backbone.History);

      scope.layout = new Thorax.Layout({
        el: options && options.layout || '.layout'
      });

    },
    //used by "template" and "view" template helpers, not thread safe though it shouldn't matter in browser land
    _currentTemplateContext: false,

    // Loading indicator helper. Note that only one load handler pair may be defined per object.
    throttleLoadStart: function(start) {
      return function(message, background) {
        var self = this;

        if (!self._loadStart) {
          var loadingTimeout = self._loadingTimeoutDuration;
          if (loadingTimeout === void 0) {
            // If we are running on a non-view object pull the default timeout
            loadingTimeout = Thorax.View.prototype._loadingTimeoutDuration;
          }

          self._loadStart = {
            timeout: setTimeout(function() {
                self._loadStart.run = true;
                start.call(self, self._loadStart.message, self._loadStart.background);
              },
              loadingTimeout*1000),
            message: message,
            background: background,
            pending: 1
          };
        } else {
          clearTimeout(self._loadStart.endTimeout);
          self._loadStart.pending++;

          self._loadStart.message = message;
          self._loadStart.background  = self._loadStart.background && background;
        }
      };
    },
    throttleLoadEnd: function(end, timeout) {
      return function(background) {
        var self = this;
        if (self._loadStart) {
          self._loadStart.pending--;

          // Reset the end timeout
          clearTimeout(self._loadStart.endTimeout);
          if (typeof timeout === 'undefined') {
            timeout = 100;
          }
          var callback = function(){
            if (self._loadStart.pending <= 0) {
              var run = self._loadStart.run;

              // If stopping make sure we don't run a start
              clearTimeout(self._loadStart.timeout);
              self._loadStart = undefined;

              if (run) {
                // Emit the end behavior, but only if there is a paired start
                end.call(self, background);
              }
            }
          };
          if (timeout) {
            self._loadStart.endTimeout = setTimeout(callback, timeout);
          } else {
            callback();
          }
        }
      };
    }
  };

  //private vars for Thorax.View
  var view_name_attribute_name = 'data-view-name',
      view_cid_attribute_name = 'data-view-cid',
      view_placeholder_attribute_name = 'data-view-tmp',
      model_cid_attribute_name = 'data-model-cid',
      collection_cid_attribute_name = 'data-collection-cid',
      default_collection_selector = '[' + collection_cid_attribute_name + ']',
      old_backbone_view = Backbone.View,
      //android scrollTo(0, 0) shows url bar, scrollTo(0, 1) hides it
      minimumScrollYOffset = (navigator.userAgent.toLowerCase().indexOf("android") > -1) ? 1 : 0,
      ELEMENT_NODE_TYPE = 1;

  //wrap Backbone.View constructor to support initialize event
  Backbone.View = function(options) {
    this._childEvents = [];
    this.cid = _.uniqueId('view');
    this._configure(options || {});
    this._ensureElement();
    this.delegateEvents();
    this.trigger('initialize:before', options);
    this.initialize.apply(this, arguments);
    this.trigger('initialize:after', options);
  };

  Backbone.View.prototype = old_backbone_view.prototype;
  Backbone.View.extend = old_backbone_view.extend;

  Thorax.View = Backbone.View.extend({
    _configure: function(options) {
      //this.options is removed in Thorax.View, we merge passed
      //properties directly with the view and template context
      _.extend(this, options || {});

      //will be called again by Backbone.View(), after _configure() is complete but safe to call twice
      this._ensureElement();

      //model and collection events
      bindModelAndCollectionEvents.call(this, this.constructor.events);
      if (this.events) {
        bindModelAndCollectionEvents.call(this, this.events);
      }

      //mixins
      for (var i = 0; i < this.constructor.mixins.length; ++i) {
        applyMixin.call(this, this.constructor.mixins[i]);
      }
      if (this.mixins) {
        for (var i = 0; i < this.mixins.length; ++i) {
          applyMixin.call(this, this.mixins[i]);
        }
      }

      //views
      this._views = {};
      if (this.views) {
        for (var local_name in this.views) {
          if (_.isArray(this.views[local_name])) {
            this[local_name] = this.view.apply(this, this.views[local_name]);
          } else {
            this[local_name] = this.view(this.views[local_name]);
          }
        }
      }
    },

    _ensureElement : function() {
      Backbone.View.prototype._ensureElement.call(this);
      (this.el[0] || this.el).setAttribute(view_name_attribute_name, this.name || this.cid);
      (this.el[0] || this.el).setAttribute(view_cid_attribute_name, this.cid);
    },

    mixin: function(name) {
      if (!this._appliedMixins) {
        this._appliedMixins = [];
      }
      if (this._appliedMixins.indexOf(name) == -1) {
        this._appliedMixins.push(name);
        if (typeof name === 'function') {
          name.call(this);
        } else {
          var mixin = scope.Mixins[name];
          _.extend(this, mixin[1]);
          //mixin callback may be an array of [callback, arguments]
          if (_.isArray(mixin[0])) {
            mixin[0][0].apply(this, mixin[0][1]);
          } else {
            mixin[0].apply(this, _.toArray(arguments).slice(1));
          }
        }
      }
    },

    view: function(name, options) {
      var instance;
      if (typeof name === 'object' && name.hash && name.hash.name) {
        // named parameters
        options = name.hash;
        name = name.hash.name;
        delete options.name;
      }

      if (typeof name === 'string') {
        if (!scope.Views[name]) {
          throw new Error('view: ' + name + ' does not exist.');
        }
        instance = new scope.Views[name](options);
      } else {
        instance = name;
      }
      this._views[instance.cid] = instance;
      this._childEvents.forEach(instance._addEvent, instance);
      return instance;
    },

    template: function(file, data, ignoreErrors) {
      Thorax._currentTemplateContext = this;

      var view_context = {};
      for (var key in this) {
        if (typeof this[key] !== 'function') {
          view_context[key] = this[key];
        }
      }
      data = _.extend({}, view_context, data || {}, {
        cid: _.uniqueId('t')
      });

      var template = this.loadTemplate(file, data, scope);
      if (!template) {
        if (ignoreErrors) {
          return ''
        } else {
          throw new Error('Unable to find template ' + file);
        }
      } else {
        return template(data);
      }
    },

    loadTemplate: function(file, data, scope) {
      var fileName = templatePathPrefix + file + (file.match(TemplateEngine.extensionRegExp) ? '' : '.' + TemplateEngine.extension);
      return scope.templates[fileName];
    },

    html: function(html) {
      if (typeof html === 'undefined') {
        return this.el.innerHTML;
      } else {
        var element;
        if (this._collectionOptions && this._renderCount) {
          //preserveCollectionElement calls the callback after it has a reference
          //to the collection element, calls the callback, then re-appends the element
          preserveCollectionElement.call(this, function() {
            element = $(this.el).html(html);
          });
        } else {
          element = $(this.el).html(html);
        }
        appendViews.call(this);
        return element;
      }
    },

    //allow events hash to specify view, collection and model events
    //as well as DOM events. Merges Thorax.View.events with this.events
    delegateEvents: function(events) {
      this.undelegateEvents && this.undelegateEvents();
      //bindModelAndCollectionEvents on this.constructor.events and this.events
      //done in _configure
      this.registerEvents(this.constructor.events);
      if (this.events) {
        this.registerEvents(this.events);
      }
      if (events) {
        this.registerEvents(events);
        bindModelAndCollectionEvents.call(this, events);
      }
    },

    registerEvents: function(events) {
      processEvents.call(this, events).forEach(this._addEvent, this);
    },

    //params may contain:
    //- name
    //- originalName
    //- selector
    //- type "view" || "DOM"
    //- handler
    _addEvent: function(params) {
      if (params.nested) {
        this._childEvents.push(params);
      }
      if (params.type === 'view') {
        this.bind(params.name, params.handler, this);
      } else {
        var boundHandler = containHandlerToCurentView(bindEventHandler.call(this, params.handler), this.cid);
        if (params.selector) {
          $(this.el).delegate(params.selector, params.name, boundHandler);
        } else {
          $(this.el).bind(params.name, boundHandler);
        }
      }
    },

    _shouldFetch: function(model_or_collection, options) {
      return model_or_collection.url && options.fetch && (
        typeof model_or_collection.isPopulated === 'undefined' || !model_or_collection.isPopulated()
      );
    },

    setModel: function(model, options) {
      (this.el[0] || this.el).setAttribute(model_cid_attribute_name, model.cid);

      var old_model = this.model;

      this.freeze({
        model: old_model, //may be false
        collection: false
      });

      this.model = model;
      this.setModelOptions(options);

      if (this.model) {
        this._events.model.forEach(function(event) {
          this.model.bind(event[0], event[1]);
        }, this);

        this.model.trigger('set', this.model, old_model);

        if (this._shouldFetch(this.model, this._modelOptions)) {
          this.model.fetch(_.extend({}, _.isObject(this._modelOptions.fetch) ? this._modelOptions.fetch : {}, {
            ignoreErrors: this.ignoreFetchError,
            success: _.once(_.bind(function(){
              if (this._modelOptions.success) {
                this._modelOptions.success(model);
              }
            },this))
          }));
        } else {
          //want to trigger built in event handler (render() + populate())
          //without triggering event on model
          onModelChange.call(this);
        }
      }

      return this;
    },

    setModelOptions: function(options) {
      if (!this._modelOptions) {
        this._modelOptions = {
          fetch: true,
          success: false,
          render: true,
          populate: true,
          errors: true
        };
      }
      _.extend(this._modelOptions, options || {});
      return this._modelOptions;
    },

    setCollection: function(collection, options) {
      var old_collection = this.collection;

      this.freeze({
        model: false, //may be false
        collection: old_collection
      });

      this.collection = collection;
      this.collection.cid = _.uniqueId('collection');
      this.setCollectionOptions(options);

      if (this.collection) {
        this._events.collection.forEach(function(event) {
          this.collection.bind(event[0], event[1]);
        }, this);

        this.collection.trigger('set', this.collection, old_collection);

        if (this._shouldFetch(this.collection, this._collectionOptions)) {
          this.collection.fetch(_.extend({}, _.isObject(this._collectionOptions.fetch) ? this._collectionOptions.fetch : {}, {
            ignoreErrors: this.ignoreFetchError,
            success: _.once(_.bind(function(){
              if (this._collectionOptions.success) {
                this._collectionOptions.success(this.collection);
              }
            },this))
          }));
        } else {
          //want to trigger built in event handler (render())
          //without triggering event on collection
          onCollectionReset.call(this);
        }
      }

      return this;
    },

    setCollectionOptions: function(options) {
      if (!this._collectionOptions) {
        this._collectionOptions = {
          fetch: true,
          success: false,
          errors: true
        };
      }
      _.extend(this._collectionOptions, options || {});
      return this._collectionOptions;
    },

    context: function(model) {
      return model ? model.attributes : {};
    },

    itemContext: function(item, i) {
      return item.attributes;
    },

    emptyContext: function() {},

    render: function(output) {
      if (typeof output === 'undefined') {
        ensureViewHasName.call(this);
        output = this.template(this.name, this.context(this.model));
      }
      this.html(output);
      if (!this._renderCount) {
        this._renderCount = 1;
      } else {
        ++this._renderCount;
      }
      this.trigger('rendered');
      return output;
    },

    renderCollection: function() {
      this.render();
      var collection_element = getCollectionElement.call(this);
      collection_element.attr(collection_cid_attribute_name, this.collection.cid);
      if (this.collection.length === 0 && this.collection.isPopulated()) {
        appendEmpty.call(this);
      } else {
        this.collection.forEach(this.appendItem, this);
      }
      this.trigger('rendered:collection', collection_element);
    },

    renderItem: function(item, i) {
      ensureViewHasName.call(this);
      return this.template(this.name + '-item', this.itemContext(item, i));
    },

    renderEmpty: function() {
      ensureViewHasName.call(this);
      return this.template(this.name + '-empty', this.emptyContext());
    },

    //appendItem(model [,index])
    //appendItem(html_string, index)
    //appendItem(view, index)
    appendItem: function(model, index, options) {
      //empty item
      if (!model) {
        return;
      }

      var item_view,
          collection_element = getCollectionElement.call(this);

      options = options || {};

      //if index argument is a view
      if (index && index.el) {
        index = collection_element.find('> *').indexOf(index.el) + 1;
      }

      //if argument is a view, or html string
      if (model.el || typeof model === 'string') {
        item_view = model;
      } else {
        index = index || this.collection.indexOf(model) || 0;
        item_view = this.renderItem(model, index);
      }

      if (item_view) {

        if (item_view.cid) {
          this._views[item_view.cid] = item_view;
        }

        var item_element = item_view.el ? [item_view.el] : _.filter($(item_view), function(node) {
          //filter out top level whitespace nodes
          return node.nodeType === ELEMENT_NODE_TYPE;
        });

        $(item_element).attr(model_cid_attribute_name, model.cid);
        var previous_model = index > 0 ? this.collection.at(index - 1) : false;
        if (!previous_model) {
          collection_element.prepend(item_element);
        } else {
          //use last() as appendItem can accept multiple nodes from a template
          collection_element.find('[' + model_cid_attribute_name + '="' + previous_model.cid + '"]').last().after(item_element);
        }

        appendViews.call(this, item_element);

        if (!options.silent) {
          this.trigger('rendered:item', item_element);
        }
      }
      return item_view;
    },

    freeze: function(options) {
      var model, collection;
      if (typeof options === 'undefined') {
        model = this.model;
        collection = this.collection;
      } else {
        model = options.model;
        collection = options.collection;
      }

      if (collection && this._events && this._events.collection) {
        this._events.collection.forEach(function(event) {
          collection.unbind(event[0], event[1]);
        }, this);
      }

      if (model && this._events && this._events.model) {
        this._events.model.forEach(function(event) {
          model.unbind(event[0], event[1]);
        }, this);
      }
    },

    //serializes a form present in the view, returning the serialized data
    //as an object
    //pass {set:false} to not update this.model if present
    //can pass options, callback or event in any order
    //if event is passed, _preventDuplicateSubmission is called
    serialize: function() {
      var callback, options, event;
      //ignore undefined arguments in case event was null
      for (var i = 0; i < arguments.length; ++i) {
        if (typeof arguments[i] === 'function') {
          callback = arguments[i];
        } else if (typeof arguments[i] === 'object') {
          if ('stopPropagation' in arguments[i] && 'preventDefault' in arguments[i]) {
            event = arguments[i];
          } else {
            options = arguments[i];
          }
        }
      }

      if (event && !this._preventDuplicateSubmission(event)) {
        return;
      }

      options = _.extend({
        set: true,
        validate: true
      },options || {});

      var attributes = options.attributes || {};

      //callback has context of element
      eachNamedInput.call(this, options, function() {
        var value = getInputValue.call(this);
        if (typeof value !== 'undefined') {
          objectAndKeyFromAttributesAndName(attributes, this.name, {mode: 'serialize'}, function(object, key) {
            object[key] = value;
          });
        }
      });

      this.trigger('serialize', attributes);

      if (options.validate) {
        var errors = this.validateInput(attributes) || [];
        this.trigger('validate', attributes, errors);
        if (errors.length) {
          this.trigger('error', errors);
          return;
        }
      }

      if (options.set && this.model) {
        if (!this.model.set(attributes, {silent: true})) {
          return false;
        };
      }

      callback && callback.call(this,attributes);
      return attributes;
    },

    _preventDuplicateSubmission: function(event, callback) {
      event.preventDefault();

      var form = $(event.target);
      if ((event.target.tagName || '').toLowerCase() !== 'form') {
        // Handle non-submit events by gating on the form
        form = $(event.target).closest('form');
      }

      if (!form.attr('data-submit-wait')) {
        form.attr('data-submit-wait', 'true');
        if (callback) {
          callback.call(this, event);
        }
        return true;
      } else {
        return false;
      }
    },

    //populate a form from the passed attributes or this.model if present
    populate: function(attributes) {
      if (!this.$('form').length) {
        return;
      }
      var value, attributes = attributes || this.context(this.model);

      //callback has context of element
      eachNamedInput.call(this, {}, function() {
        objectAndKeyFromAttributesAndName.call(this, attributes, this.name, {mode: 'populate'}, function(object, key) {
          if (object && typeof (value = object[key]) !== 'undefined') {
            //will only execute if we have a name that matches the structure in attributes
            if (this.type === 'checkbox' && _.isBoolean(value)) {
              this.checked = value;
            } else if (this.type === 'checkbox' || this.type === 'radio') {
              this.checked = value == this.value;
            } else {
              this.value = value;
            }
          }
        });
      });

      this.trigger('populate', attributes);
    },

    //perform form validation, implemented by child class
    validateInput: function() {},

    destroy: function(){
      this.freeze();
      this.trigger('destroyed');
      if (this.undelegateEvents) {
        this.undelegateEvents();
      }
      this.unbind();
      this._events = {};
      this.el = null;
      this.collection = null;
      this.model = null;
      destroyChildViews.call(this);
    },

    //loading config
    _loadingClassName: 'loading',
    _loadingTimeoutDuration: 0.33,

    scrollTo: function(x, y) {
      y = y || minimumScrollYOffset;
      window.scrollTo(x, y);
      return [x, y];
    }
  }, {
    registerHelper: function(name, callback) {
      this[name] = callback;
      TemplateEngine.registerHelper(name, this[name]);
    },
    registerMixin: function(name, callback, methods) {
      scope.Mixins[name] = [callback, methods];
    },
    mixins: [],
    mixin: function(mixin) {
      this.mixins.push(mixin);
    },
    //events for all views
    events: {
      model: {},
      collection: {}
    },
    registerEvents: function(events) {
      for(var name in events) {
        if (name === 'model' || name === 'collection') {
          for (var _name in events[name]) {
            addEvent(this.events[name], _name, events[name][_name]);
          }
        } else {
          addEvent(this.events, name, events[name]);
        }
      }
    },
    unregisterEvents: function(events) {
      if (typeof events === 'undefined') {
        this.events = {
          model: {},
          collection: {}
        };
      } else if (typeof events === 'string' && arguments.length === 1) {
        if (events === 'model' || events === 'collection') {
          this.events[events] = {};
        } else {
          this.events[events] = [];
        }
      //remove collection or model events
      } else if (arguments.length === 2) {
        this.events[arguments[0]][arguments[1]] = [];
      }
    }
  });

  //events and mixins properties need act as inheritable, not static / shared
  Thorax.View.extend = function(protoProps, classProps) {
    var child = Backbone.View.extend.call(this, protoProps, classProps);
    if (child.prototype.name) {
      scope.Views[child.prototype.name] = child;
    }
    child.mixins = _.clone(this.mixins);
    cloneEvents(this, child, 'events');
    cloneEvents(this.events, child.events, 'model');
    cloneEvents(this.events, child.events, 'collection');
    return child;
  };

  function cloneEvents(source, target, key) {
    source[key] = _.clone(target[key]);
    //need to deep clone events array
    _.each(source[key], function(value, _key) {
      if (_.isArray(value)) {
        target[key][_key] = _.clone(value);
      }
    });
  }

  Thorax.View.registerEvents({
    //built in dom events
    'submit form': function(event) {
      // Hide any virtual keyboards that may be lingering around
      var focused = $(':focus')[0];
      focused && focused.blur();
    },

    'initialize:after': function(options) {
      //bind model or collection if passed to constructor
      if (options && options.model) {
        this.setModel(options.model);
      }
      if (options && options.collection) {
        this.setCollection(options.collection);
      }
    },

    error: function() {
      resetSubmitState.call(this);

      // If we errored with a model we want to reset the content but leave the UI
      // intact. If the user updates the data and serializes any overwritten data
      // will be restored.
      if (this.model && this.model.previousAttributes) {
        this.model.set(this.model.previousAttributes(), {
          silent: true
        });
      }
    },
    deactivated: function() {
      resetSubmitState.call(this);
    },
    'load:start': Thorax.throttleLoadStart(function(message, background) {
      $(this.el).addClass(this._loadingClassName);
    }),
    'load:end': Thorax.throttleLoadEnd(function(message, background) {
      $(this.el).removeClass(this._loadingClassName);
    }),
    model: {
      error: function(model, errors){
        if (this._modelOptions.errors) {
          this.trigger('error', errors);
        }
      },
      change: function() {
        onModelChange.call(this);
      },
      'load:start': function(message, background) {
        this.trigger('load:start', message, background);
      },
      'load:end': function(background) {
        this.trigger('load:end', background);
      }
    },
    collection: {
      add: function(model, collection) {
        //if collection was empty, clear empty view
        if (this.collection.length === 1) {
          getCollectionElement.call(this).empty();
        }
        this.appendItem(model, collection.indexOf(model));
      },
      remove: function(model) {
        this.$('[' + model_cid_attribute_name + '="' + model.cid + '"]').remove();
        for (var cid in this._views) {
          if (this._views[cid].model && this._views[cid].model.cid === model.cid) {
            this._views[cid].destroy();
            delete this._views[cid];
            break;
          }
        }
        if (this.collection.length === 0) {
          appendEmpty.call(this);
        }
      },
      reset: function() {
        onCollectionReset.call(this);
      },
      error: function(collection, message) {
        if (this._collectionOptions.errors) {
          this.trigger('error', message);
        }
      },
      'load:start': function(message, background) {
        this.trigger('load:start', message, background);
      },
      'load:end': function(background) {
        this.trigger('load:end', background);
      }
    }
  });

  Thorax.View.registerHelper('view', function(view, options) {
    if (!view) {
      return '';
    }
    var instance = Thorax._currentTemplateContext.view(view, options ? options.hash : {});
    return TemplateEngine.safeString('<div ' + view_placeholder_attribute_name + '="' + instance.cid + '"></div>');
  });

  Thorax.View.registerHelper('template', function(name, options) {
    var context = _.extend({}, this, options ? options.hash : {});
    var output = Thorax.View.prototype.template.call(Thorax._currentTemplateContext, name, context);
    return TemplateEngine.safeString(output);
  });

  Thorax.View.registerHelper('collection', function(options) {
    var collectionHelperOptions = _.clone(options.hash),
        tag = (collectionHelperOptions.tag || 'div');
    collectionHelperOptions[collection_cid_attribute_name] = "";
    if (collectionHelperOptions.tag) {
      delete collectionHelperOptions.tag;
    }
    var htmlAttributes = _.map(collectionHelperOptions, function(value, key) {
      return key + '="' + value + '"';
    }).join(' ');
    return TemplateEngine.safeString('<' + tag + ' ' + htmlAttributes + '></' + tag + '>');
  });

  Thorax.View.registerHelper('link', function(url) {
    return (Backbone.history._hasPushState ? Backbone.history.options.root : '#') + url;
  });

  //private Thorax.View methods

  function ensureViewHasName() {
    if (!this.name) {
      throw new Error(this.cid + " requires a 'name' attribute.");
    }
  }

  function onModelChange() {
    if (this._modelOptions.render) {
      this.render();
    }
    if (this._modelOptions.populate) {
      this.populate();
    }
  }

  function onCollectionReset() {
    this.renderCollection();
  }

  function containHandlerToCurentView(handler, cid) {
    return function(event) {
      var containing_view_element = $(event.target).closest('[' + view_name_attribute_name + ']');
      if (!containing_view_element.length || containing_view_element[0].getAttribute(view_cid_attribute_name) == cid) {
        handler(event);
      }
    };
  }

  //model/collection events, to be bound/unbound on setModel/setCollection
  function processModelOrCollectionEvent(events, type) {
    for (var _name in events[type] || {}) {
      if (_.isArray(events[type][_name])) {
        for (var i = 0; i < events[type][_name].length; ++i) {
          this._events[type].push([_name, bindEventHandler.call(this, events[type][_name][i])]);
        }
      } else {
        this._events[type].push([_name, bindEventHandler.call(this, events[type][_name])]);
      }
    }
  }

  //used by processEvents
  var domEvents = [
    'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout',
    'touchstart', 'touchend', 'touchmove',
    'click', 'dblclick',
    'keyup', 'keydown', 'keypress',
    'submit',
    'focus', 'blur'
  ];

  function bindEventHandler(callback) {
    var method = typeof callback === 'function' ? callback : this[callback];
    if (!method) {
      throw new Error('Event "' + callback + '" does not exist');
    }
    return _.bind(method, this);
  }

  function processEvents(events) {
    if (_.isFunction(events)) {
      events = events.call(this);
    }
    var processedEvents = [];
    for (var name in events) {
      if (name !== 'model' && name !== 'collection') {
        if (name.match(/,/)) {
          name.split(/,/).forEach(function(fragment) {
            processEventItem.call(this, fragment.replace(/(^[\s]+|[\s]+$)/g, ''), events[name], processedEvents);
          }, this);
        } else {
          processEventItem.call(this, name, events[name], processedEvents);
        }
      }
    }
    return processedEvents;
  }

  function processEventItem(name, handler, target) {
    if (_.isArray(handler)) {
      for (var i = 0; i < handler.length; ++i) {
        target.push(eventParamsFromEventItem.call(this, name, handler[i]));
      }
    } else {
      target.push(eventParamsFromEventItem.call(this, name, handler));
    }
  }

  var eventSplitter = /^(nested\s+)?(\S+)(?:\s+(.+))?/;

  function eventParamsFromEventItem(name, handler) {
    var params = {
      originalName: name,
      handler: typeof handler === 'string' ? this[handler] : handler
    };
    var match = eventSplitter.exec(name);
    params.nested = !!match[1];
    params.name = match[2];
    if (isDOMEvent(params.name)) {
      params.type = 'DOM';
      params.name += '.delegateEvents' + this.cid;
      params.selector = match[3];
    } else {
      params.type = 'view';
    }
    return params;
  }

  function isDOMEvent(name) {
    return !(!name.match(/\s+/) && domEvents.indexOf(name) === -1);
  }

  //used by Thorax.View.registerEvents for global event registration
  function addEvent(target, name, handler) {
    if (!target[name]) {
      target[name] = [];
    }
    if (_.isArray(handler)) {
      for (var i = 0; i < handler.length; ++i) {
        target[name].push(handler[i]);
      }
    } else {
      target[name].push(handler);
    }
  }

  function resetSubmitState() {
    this.$('form').removeAttr('data-submit-wait');
  }

  //called with context of input
  function getInputValue() {
    if (this.type === 'checkbox' || this.type === 'radio') {
      if ($(this).attr('data-onOff')) {
        return this.checked;
      } else if (this.checked) {
        return this.value;
      }
    } else if (this.multiple === true) {
      var values = [];
      $('option',this).each(function(){
        if (this.selected) {
          values.push(this.value);
        }
      });
      return values;
    } else {
      return this.value;
    }
  }

  //calls a callback with the correct object fragment and key from a compound name
  function objectAndKeyFromAttributesAndName(attributes, name, options, callback) {
    var key, i, object = attributes, keys = name.split('['), mode = options.mode;
    for(i = 0; i < keys.length - 1; ++i) {
      key = keys[i].replace(']','');
      if (!object[key]) {
        if (mode == 'serialize') {
          object[key] = {};
        } else {
          return callback.call(this, false, key);
        }
      }
      object = object[key];
    }
    key = keys[keys.length - 1].replace(']', '');
    callback.call(this, object, key);
  }

  function eachNamedInput(options, iterator, context) {
    var i = 0;
    $('select,input,textarea', options.root || this.el).each(function() {
      if (this.type !== 'button' && this.type !== 'cancel' && this.type !== 'submit' && this.name && this.name !== '') {
        iterator.call(context || this, i, this);
        ++i;
      }
    });
  }

  function bindModelAndCollectionEvents(events) {
    if (!this._events) {
      this._events = {
        model: [],
        collection: []
      };
    }
    processModelOrCollectionEvent.call(this, events, 'model');
    processModelOrCollectionEvent.call(this, events, 'collection');
  }

  function getCollectionElement() {
    var selector = this._collectionSelector || default_collection_selector;
    var element = this.$(selector);
    if (element.length === 0) {
      return $(this.el);
    } else {
      return element;
    }
  }

  function preserveCollectionElement(callback) {
    var old_collection_element = getCollectionElement.call(this);
    callback.call(this);
    var new_collection_element = getCollectionElement.call(this);
    if (old_collection_element.length && new_collection_element.length) {
      new_collection_element[0].parentNode.insertBefore(old_collection_element[0], new_collection_element[0]);
      new_collection_element[0].parentNode.removeChild(new_collection_element[0]);
    }
  }

  function appendViews(scope) {
    var self = this;
    if (!self._views) {
      return;
    }

    $('[' + view_placeholder_attribute_name + ']', scope || self.el).forEach(function(el) {
      var view = self._views[el.getAttribute(view_placeholder_attribute_name)];
      if (view) {
        //has the view been rendered at least once? if not call render().
        //subclasses overriding render() that do not call the parent's render()
        //or set _rendered may be rendered twice but will not error
        if (!view._renderCount) {
          view.render();
        }
        el.parentNode.insertBefore(view.el, el);
        el.parentNode.removeChild(el);
      }
    });
  }

  function destroyChildViews() {
    for (var id in this._views || {}) {
      if (this._views[id].destroy) {
        this._views[id].destroy();
      }
      this._views[id] = null;
    }
  }

  function appendEmpty() {
    getCollectionElement.call(this).empty();
    this.appendItem(this.renderEmpty(), 0, {silent: true});
    this.trigger('rendered:empty');
  }

  function applyMixin(mixin) {
    if (_.isArray(mixin)) {
      this.mixin.apply(this, mixin);
    } else {
      this.mixin(mixin);
    }
  }

  //main layout class, instance of which is available on scope.layout
  Thorax.Layout = Backbone.View.extend({
    events: {
      'click a': 'anchorClick'
    },

    initialize: function() {
      this.el = $(this.el)[0];
      this.views = this.make('div', {
        'class': 'views'
      });
      this.el.appendChild(this.views);
    },

    setView: function(view, params){
      var old_view = this.view;
      if (view == old_view){
        return false;
      }
      this.trigger('change:view:start', view, old_view);
      old_view && old_view.trigger('deactivated');
      view && view.trigger('activated', params || {});
      if (old_view && old_view.el && old_view.el.parentNode) {
        $(old_view.el).remove();
      }
      //make sure the view has been rendered at least once
      view && !view._renderCount && view.render();
      view && this.views.appendChild(view.el);
      window.scrollTo(0, minimumScrollYOffset);
      this.view = view;
      old_view && old_view.destroy();
      this.view && this.view.trigger('ready');
      this.trigger('change:view:end', view, old_view);
      return view;
    },

    anchorClick: function(event) {
      var target = $(event.currentTarget);
      if (target.attr("data-external")) {
        return;
      }
      var href = target.attr("href");
      // Route anything that starts with # or / (excluding //domain urls)
      if (href && (href[0] === '#' || (href[0] === '/' && href[1] !== '/'))) {
        Backbone.history.navigate(href, {trigger: true});
        event.preventDefault();
      }
    }
  });

  Thorax.Router = Backbone.Router.extend({
    view: function(name, attributes) {
      if (!scope.Views[name]) {
        throw new Error('view: ' + name + ' does not exist.');
      }
      return new scope.Views[name](attributes);
    },
    setView: function() {
      return scope.layout.setView.apply(scope.layout, arguments);
    },
    bindToRoute: bindToRoute
  },{
    create: function(module, protoProps, classProps) {
      return scope.Routers[module.name] = new (this.extend(_.extend({}, module, protoProps), classProps));
    },
    bindToRoute: bindToRoute
  });

  function bindToRoute(callback, failback, background) {
    var fragment = Backbone.history.getFragment(),
        completed;

    function finalizer(isCanceled) {
      var same = fragment === Backbone.history.getFragment();

      if (completed) {
        // Prevent multiple execution, i.e. we were canceled but the success callback still runs
        return;
      }

      if (isCanceled && same) {
        // Ignore the first route event if we are running in newer versions of backbone
        // where the route operation is a postfix operation.
        return;
      }

      completed = true;
      Backbone.history.unbind('route', resetLoader);

      background || scope.trigger('load:end');
      var args = Array.prototype.slice.call(arguments, 1);
      if (!isCanceled && same) {
        callback.apply(this, args);
      } else {
        failback && failback.apply(this, args);
      }
    }

    var resetLoader = _.bind(finalizer, this, true);
    Backbone.history.bind('route', resetLoader);

    background || scope.trigger('load:start');
    return _.bind(finalizer, this, false);
  }

  Thorax.Model = Backbone.Model.extend({
    isPopulated: function() {
      // We are populated if we have attributes set
      var attributes = _.clone(this.attributes);
      var defaults = _.isFunction(this.defaults) ? this.defaults() : (this.defaults || {});
      for (var default_key in defaults) {
        if (attributes[default_key] != defaults[default_key]) {
          return true;
        }
        delete attributes[default_key];
      }
      var keys = _.keys(attributes);
      return keys.length > 1 || (keys.length === 1 && keys[0] !== 'id');
    },
    fetch: function(options) {
      fetchQueue.call(this, options || {}, Backbone.Model.prototype.fetch);
    },
    sync: sync,
    load: loadData
  });

  Thorax.Model.extend = function(protoProps, classProps) {
    var child = Backbone.Model.extend.call(this, protoProps, classProps);
    if (child.prototype.name) {
      scope.Models[child.prototype.name] = child;
    }
    return child;
  };

  Thorax.Collection = Backbone.Collection.extend({
    model: Thorax.Model,
    isPopulated: function() {
      return this._fetched || this.length > 0;
    },
    fetch: function(options) {
      options = options || {};
      var success = options.success;
      options.success = function(collection, response) {
        collection._fetched = true;
        success && success(collection, response);
      };
      fetchQueue.call(this, options || {}, Backbone.Collection.prototype.fetch);
    },
    reset: function(models, options) {
      this._fetched = !!models;
      return Backbone.Collection.prototype.reset.call(this, models, options);
    },
    sync: sync,
    load: loadData
  });

  Thorax.Collection.extend = function(protoProps, classProps) {
    var child = Backbone.Collection.extend.call(this, protoProps, classProps);
    if (child.prototype.name) {
      scope.Collections[child.prototype.name] = child;
    }
    return child;
  };

  function sync(method, model_or_collection, options) {
    var complete = options.complete;
    options.complete = function() {
      complete && complete.apply(this, arguments);
      model_or_collection.trigger('load:end', options.background);
    };
    model_or_collection.trigger('load:start', undefined, options.background);
    var request = Backbone.sync.apply(this, arguments);
    this.trigger('request', request);
    return request;
  }
  Thorax.sync = sync;

  function loadData(callback, failback, options) {
    if (this.isPopulated()) {
      return callback(this);
    }

    if (arguments.length === 2 && typeof failback !== 'function' && _.isObject(failback)) {
      options = failback;
      failback = false;
    }
    options = options || {};

    function finalizer(isError) {
      this.unbind('error', errorHandler);
      if (isError && !options.background) {
        scope.trigger('load:end');
      }
      failback && failback.apply(this, arguments);
    }

    var errorHandler = _.bind(finalizer, this, true);
    this.bind('error', errorHandler);

    this.fetch(_.extend({}, options || {}, {
      success: bindToRoute(_.bind(function() {
          this.unbind('error', errorHandler);
          callback.apply(this, arguments);
        }, this),
        _.bind(finalizer, this, false),
        options.background)
    }));
  }

  function fetchQueue(options, $super) {
    if (options.resetQueue) {
      // WARN: Should ensure that loaders are protected from out of band data
      //    when using this option
      this.fetchQueue = undefined;
    }

    if (!this.fetchQueue) {
      // Kick off the request
      this.fetchQueue = [options];
      options = _.defaults({
        success: flushQueue(this, this.fetchQueue, 'success'),
        error: flushQueue(this, this.fetchQueue, 'error')
      }, options);
      $super.call(this, options);
    } else {
      // Currently fetching. Queue and process once complete
      this.fetchQueue.push(options);
    }
  }

  function flushQueue(self, fetchQueue, handler) {
    return function() {
      var args = arguments;

      // Flush the queue. Executes any callback handlers that
      // may have been passed in the fetch options.
      fetchQueue.forEach(function(options) {
        if (options[handler]) {
          options[handler].apply(this, args);
        }
      }, this);

      // Reset the queue if we are still the active request
      if (self.fetchQueue === fetchQueue) {
        self.fetchQueue = undefined;
      }
    }
  }
}).call(this, this);

redpajama_set_name: RedPajamaGithub


text:
namespace ChinaTtlWifi.NewUI
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.wimsGridView1 = new Wims.Common.UI.WimsGridView(this.components);
            this.button1 = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            ((System.ComponentModel.ISupportInitialize)(this.wimsGridView1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // wimsGridView1
            //
            this.wimsGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.wimsGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.wimsGridView1.Location = new System.Drawing.Point(3, 17);
            this.wimsGridView1.Name = "wimsGridView1";
            this.wimsGridView1.RowTemplate.Height = 23;
            this.wimsGridView1.Size = new System.Drawing.Size(467, 354);
            this.wimsGridView1.TabIndex = 0;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(138, 502);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.wimsGridView1);
            this.groupBox1.Location = new System.Drawing.Point(138, 99);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(473, 374);
            this.groupBox1.TabIndex = 2;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "groupBox1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(749, 625);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.groupBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.wimsGridView1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private Wims.Common.UI.WimsGridView wimsGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.GroupBox groupBox1;
    }
}


text:
package net._5tingr4y.test.graphicsUtils.renderer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;

import net._5tingr4y.graphicsUtils.renderer.SwingShapeRenderer;
import net._5tingr4y.graphicsUtils.renderer.api.ShapeRenderer2D.AreaType;
import net._5tingr4y.stingUtils.color.Color4i;
import net._5tingr4y.stingUtils.math.algebra.linear.Vector2f;

public class SwingShapeRendererTest {

	public static void main(String[] args) {
		JFrame testFrame = new JFrame();
	    testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	    SwingShapeRenderer renderer = new SwingShapeRenderer();
	    renderer.setPreferredSize(new Dimension(1024, 576));
	    testFrame.getContentPane().add(renderer, BorderLayout.CENTER);
	    testFrame.getContentPane().setBackground(new Color(0, 0, 0));

	    testFrame.pack();
	    testFrame.setVisible(true);

	    long waittime = 1000;

	    try {
	    	Thread.sleep(waittime);
	    	renderer.renderLine(new Vector2f(100, 100), new Vector2f(200, 200), new Color4i(255, 0, 127, 255));

	    	Thread.sleep(waittime);
	    	renderer.renderCircle(new Vector2f(100, 476), 50, 50, new Color4i(0, 255, 255, 255), AreaType.FILLED);

	    	Thread.sleep(waittime);
	    	renderer.renderCircle(new Vector2f(300, 476), 50, 5, new Color4i(0, 255, 0, 255), AreaType.FILLED);

	    	Thread.sleep(waittime);
	    	renderer.renderPolygon(AreaType.FILLED, new Color4i(0, 0, 255, 255), new Vector2f(200, 100), new Vector2f(200, 150), new Vector2f(300, 200), new Vector2f(500, 50));

	    	Thread.sleep(waittime);
	    	renderer.renderCircle(new Vector2f(500, 476), 50, 50, new Color4i(255, 0, 0, 255), AreaType.HOLLOW);

	    	Thread.sleep(waittime);
	    	renderer.renderPolygon(AreaType.HOLLOW, new Color4i(255, 255, 0, 255), new Vector2f(600, 100), new Vector2f(600, 150), new Vector2f(700, 200), new Vector2f(900, 50));

	    	Thread.sleep(waittime);
	    	renderer.renderTriangle(new Vector2f(250, 250), new Vector2f(300, 400), new Vector2f(400, 100), new Color4i(0, 255, 0, 255), AreaType.FILLED);

	    	Thread.sleep(waittime);
	    	renderer.renderQuad(new Vector2f(200, 50), new Vector2f(300, 300), new Vector2f(400, 250), new Vector2f(350, 0), new Color4i(255, 0, 0, 127), AreaType.FILLED);
	    } catch(InterruptedException e) {
	    	e.printStackTrace();
	    }
	}

}


text:
package model

type RevelPaths struct {
	Import    string
	Source    string
	Base      string
	Code      []string              // Consolidated code paths
	Template  []string              // Consolidated template paths
	Config    []string              // Consolidated configuration paths
	ModuleMap map[string]*RevelUnit // The module path map
}


text:
"use strict";

/**
 * Subexample module services.
 */
angular.module("app.subexampleModule")

;


text:
package com.example.mvcproducts.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class HomeController {

  @GetMapping
  public String home(){
    return "home";
  }
}


text:
package controllers

import com.github.nscala_time.time.Imports._
import honor.Honors
import models.db.AGOProgress
import org.json4s.native.Serialization.write
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits._
import scalikejdbc._
import models.db
import tool.{BestShipExp, HistgramShipLv, MaterialDays, STypeExp}

import scala.concurrent.Future

/**
 *
 * @author ponkotuy
 * Date: 14/04/01.
 */
object UserView extends Controller {
  import controllers.Common._

  def name(user: String) = Action.async {
    Future {
      db.Admiral.findByName(user) match {
        case Some(auth) => Redirect(routes.UserView.user(auth.id))
        case _ => NotFound("ユーザが見つかりませんでした")
      }
    }
  }

  def user(memberId: Long) = Action.async {
    Future { Redirect(routes.UserView.top(memberId)) }
  }

  def user2(memberId: Long) = Action.async {
    Future { Redirect(routes.UserView.top(memberId)) }
  }

  def top(memberId: Long) = userView(memberId) { user =>
    val yomes = db.YomeShip.findAllByWithName(sqls"ys.member_id = ${memberId}")
    val yomeIds = yomes.map(_.id).toSet
    val best = db.Ship.findByUserMaxLvWithName(memberId)
      .filterNot(b => yomeIds.contains(b.id))
    val flagship = db.DeckShip.findFlagshipByUserWishShipName(memberId)
      .filterNot(f => (yomeIds ++ best.map(_.id)).contains(f.id))
    Ok(views.html.user.user(user, yomes, best, flagship))
  }

  def favorite(memberId: Long) = userView(memberId) { user =>
    val favs = db.Favorite.findAllBy(sqls"f.member_id = $memberId")
    val faved = db.Favorite.countByURL(sqls"f.first = ${"user"} and f.second = ${memberId}")
    Ok(views.html.user.favorite(user, favs, faved))
  }

  def favFroms(memberId: Long, url: String) = userView(memberId) { user =>
    val fromIds = db.Favorite.findAllByUrl(url).map(_.memberId)
    val froms = db.Admiral.findAllIn(fromIds)
    if(froms.nonEmpty) Ok(views.html.user.modal_fav(user, url, froms))
    else BadRequest(s"Not found favorite: memberId = ${memberId}, url = ${url}")
  }

  def snapshot(memberId: Long) = userView(memberId) { user =>
    val snaps = db.DeckSnapshot.findAllOrderWithShip(memberId)
    Ok(views.html.user.snapshot(user, snaps))
  }

  def registerSnap(memberId: Long, deckId: Int) = userView(memberId) { user =>
    val ships = db.DeckShip.findAllByDeck(memberId, deckId)
    db.DeckPort.find(memberId, deckId) match {
      case Some(deck) =>
        if(user.isMine) Ok(views.html.user.register_snap(user, ships, deck))
        else Redirect(routes.View.login(user.admiral.id.toString, routes.UserView.registerSnap(memberId, deckId).url))
      case None => BadRequest(s"Not found deck. memberId = ${memberId}, deckId = ${deckId}")
    }
  }

  def deleteSnap(snapId: Long) = actionAsync { request =>
    db.DeckSnapshot.findWithShip(snapId) match {
      case Some(snap) =>
        val id = snap.memberId
        getUser(id, uuidCheck(id, request.session.get("key"))) match {
          case Some(user) if user.isMine =>
            Ok(views.html.user.snap_delete_pass(user, snap))
          case Some(_) => Redirect(routes.View.login(id.toString, routes.UserView.deleteSnap(snapId).url))
          case None => BadRequest(s"Not found userId = ${id}")
        }
      case None => BadRequest(s"Not found snapId = ${snapId}")
    }
  }

  def material(memberId: Long) = userView(memberId) { user =>
    val day20ago = DateTime.now - 20.days
    val materials = db.Material.findAllByUser(memberId, from = day20ago.getMillis)
    val days = materials.groupBy(m => (new DateTime(m.created) - 5.hours).toLocalDate)
      .mapValues(_.maxBy(_.created))
      .toSeq.sortBy(_._1).reverse
    val materialDays = days.sliding(2).flatMap {
      case Seq(x, y) =>
        val (day, xMat) = x
        val (_, yMat) = y
        Some(MaterialDays.fromMaterials(day, xMat, yMat))
      case _ =>
        None
    }.toSeq
    Ok(views.html.user.material(user, materialDays))
  }

  def ship(memberId: Long) = userView(memberId) { user =>
    val ships = db.Ship.findAllByUserWithName(memberId)
    val decks = db.DeckShip.findAllByUserWithName(memberId)
    val deckports = db.DeckPort.findAllByUser(memberId)
    Ok(views.html.user.ship(user, ships, decks, deckports))
  }

  val UnprocurableItemId = Set(49)

  def book(memberId: Long) = userView(memberId) { user =>
    val allShips = db.ShipBook.findAllUnique()
    val allItems = db.MasterSlotItem.findAllBy(sqls"msi.id <= 500 and msi.id not in (${UnprocurableItemId})")
      .map { msi => msi.id -> msi.name }
    val sBooks = db.ShipBook.findAllBy(sqls"member_id = ${memberId}").map(it => it.indexNo -> it).toMap
    val iBooks = db.ItemBook.findAllBy(sqls"member_id = ${memberId}").map(it => it.indexNo -> it).toMap
    Ok(views.html.user.book(user, allShips, sBooks, allItems, iBooks))
  }

  def shipImageBook(memberId: Long) = userView(memberId) { user =>
    Ok(views.html.user.ship_image_book(user))
  }

  def dock(memberId: Long) = userView(memberId) { user =>
    Ok(views.html.user.dock(user))
  }

  def create(memberId: Long) = userView(memberId) { user =>
    val cShips = db.CreateShip.findAllByUserWithName(memberId, large = true)
    Ok(views.html.user.create(user, cShips))
  }

  def aship(memberId: Long, shipId: Int) = userView(memberId) { user =>
    db.Ship.findByIDWithName(memberId, shipId) match {
      case Some(ship) => Ok(views.html.user.modal_ship(ship, user, false))
      case _ => NotFound("艦娘が見つかりませんでした")
    }
  }

  def snapAship(memberId: Long, shipId: Int) = userView(memberId) { user =>
    db.DeckShipSnapshot.findWithName(shipId) match {
      case Some(ship) => Ok(views.html.user.modal_ship(ship, user, true))
      case _ => NotFound("艦娘が見つかりませんでした")
    }
  }

  def fleet(memberId: Long, deckId: Int) = userView(memberId) { user =>
    val fleet = db.DeckShip.findAllByDeck(memberId, deckId)
    db.DeckPort.find(memberId, deckId) match {
      case Some(deck) => Ok(views.html.user.modal_fleet(fleet, deck, user))
      case _ => NotFound("艦隊が見つかりませんでした")
    }
  }

  def shipPage(memberId: Long, shipId: Int) = userView(memberId) { user =>
    db.Ship.findByIDWithName(memberId, shipId) match {
      case Some(ship) => Ok(views.html.user.modal_ship(ship, user, false))
      case _ => NotFound("艦娘が見つかりませんでした")
    }
  }

  def slotitem(memberId: Long) = userView(memberId) { user =>
    val si = db.SlotItem.si
    val counts = db.SlotItem.countItemBy(sqls.eq(si.memberId, memberId))
    val leveled = db.SlotItem.findAllWithArmedShipBy(sqls.eq(si.memberId, memberId).and.gt(si.level, 0))
    Ok(views.html.user.slotitem(user, counts, leveled))
  }

  def shipslotitem(memberId: Long, itemId: Int) = Action.async {
    Future {
      db.MasterSlotItem.find(itemId) match {
        case Some(item) =>
          val slotItemIds = db.SlotItem.findAllBy(sqls"member_id = ${memberId} and slotitem_id = ${itemId}").map(_.id)
          val ships = db.SlotItem.findAllArmedShipBy(sqls"si.member_id = ${memberId} and si.slotitem_id = ${itemId}")
          Ok(views.html.user.shipslotitem(item, ships, slotItemIds.size))
        case _ => NotFound("Itemが見つかりませんでした")
      }
    }
  }

  def navalBattle(memberId: Long) = userView(memberId) { user =>
    val stages = db.MapRoute.findStageUnique()
    Ok(views.html.user.naval_battle(user, stages))
  }

  def routeLog(memberId: Long) = userView(memberId) { user =>
    Redirect(routes.UserView.navalBattle(memberId))
  }

  def mission(memberId: Long) = userView(memberId) { user =>
    val stages = db.MasterMission.findAll()
    Ok(views.html.user.mission(user, stages))
  }

  def quest(memberId: Long) = userView(memberId) { user =>
    val ago = AGOProgress.find(memberId)
    Ok(views.html.user.quest(user, ago))
  }

  def statistics(memberId: Long) = userView(memberId) { user =>
    val ships = db.Ship.findAllByUserWithName(memberId)
    val stypeExps = STypeExp.fromShips(ships)
    val stypeExpJson = stypeExps.map(_.toJson(memberId))
    val histgramJson = HistgramShipLv.fromShips(ships).map(_.toJsonElem)
    val bestShipExpJson = BestShipExp.fromShips(ships).map(_.toJsonElem)
    Ok(views.html.user.statistics(user, stypeExps, write(stypeExpJson), write(histgramJson), write(bestShipExpJson)))
  }

  def honor(memberId: Long) = userView(memberId) { user =>
    Honors.create(memberId)
    val honors = Honors.fromUser(memberId, false)
    Ok(views.html.user.honor(user, honors))
  }
}


text:
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef UUID_8D22C4CA9CC811DCAA9133D256D89593
#define UUID_8D22C4CA9CC811DCAA9133D256D89593
#if (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma GCC system_header
#endif
#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(push,1)
#endif

#include <boost/exception/exception.hpp>
#include <boost/exception/to_string_stub.hpp>
#include <boost/exception/detail/error_info_impl.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/config.hpp>
#include <map>

namespace
boost
    {
    template <class Tag,class T>
    inline
    std::string
    error_info_name( error_info<Tag,T> const & x )
        {
        return tag_type_name<Tag>();
        }

    template <class Tag,class T>
    inline
    std::string
    to_string( error_info<Tag,T> const & x )
        {
        return '[' + error_info_name(x) + "] = " + to_string_stub(x.value()) + '\n';
        }

    template <class Tag,class T>
    inline
    error_info<Tag,T>::
    error_info( value_type const & value ):
        value_(value)
        {
        }

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
	template <class Tag,class T>
    inline
    error_info<Tag,T>::
	error_info( error_info const & x ):
		value_(x.value_)
		{
		}
    template <class Tag,class T>
    inline
    error_info<Tag,T>::
	error_info( value_type && value ) BOOST_NOEXCEPT_IF(BOOST_NOEXCEPT_EXPR(value_type(std::move(value)))):
		value_(std::move(value))
		{
		}
	template <class Tag,class T>
    inline
    error_info<Tag,T>::
	error_info( error_info && x ) BOOST_NOEXCEPT_IF(BOOST_NOEXCEPT_EXPR(value_type(std::move(x.value_)))):
		value_(std::move(x.value_))
		{
		}
#endif

    template <class Tag,class T>
    inline
    error_info<Tag,T>::
    ~error_info() throw()
        {
        }

    template <class Tag,class T>
    inline
    std::string
    error_info<Tag,T>::
    name_value_string() const
        {
        return to_string_stub(*this);
        }

    namespace
    exception_detail
        {
        class
        error_info_container_impl:
            public error_info_container
            {
            public:

            error_info_container_impl():
                count_(0)
                {
                }

            ~error_info_container_impl() throw()
                {
                }

            void
            set( shared_ptr<error_info_base> const & x, type_info_ const & typeid_ )
                {
                BOOST_ASSERT(x);
                info_[typeid_] = x;
                diagnostic_info_str_.clear();
                }

            shared_ptr<error_info_base>
            get( type_info_ const & ti ) const
                {
                error_info_map::const_iterator i=info_.find(ti);
                if( info_.end()!=i )
                    {
                    shared_ptr<error_info_base> const & p = i->second;
#ifndef BOOST_NO_RTTI
                    BOOST_ASSERT( *BOOST_EXCEPTION_DYNAMIC_TYPEID(*p).type_==*ti.type_ );
#endif
                    return p;
                    }
                return shared_ptr<error_info_base>();
                }

            char const *
            diagnostic_information( char const * header ) const
                {
                if( header )
                    {
                    std::ostringstream tmp;
                    tmp << header;
                    for( error_info_map::const_iterator i=info_.begin(),end=info_.end(); i!=end; ++i )
                        {
                        error_info_base const & x = *i->second;
                        tmp << x.name_value_string();
                        }
                    tmp.str().swap(diagnostic_info_str_);
                    }
                return diagnostic_info_str_.c_str();
                }

            private:

            friend class boost::exception;

            typedef std::map< type_info_, shared_ptr<error_info_base> > error_info_map;
            error_info_map info_;
            mutable std::string diagnostic_info_str_;
            mutable int count_;

            error_info_container_impl( error_info_container_impl const & );
            error_info_container_impl & operator=( error_info_container const & );

            void
            add_ref() const
                {
                ++count_;
                }

            bool
            release() const
                {
                if( --count_ )
                    return false;
                else
                    {
                    delete this;
                    return true;
                    }
                }

            refcount_ptr<error_info_container>
            clone() const
                {
                refcount_ptr<error_info_container> p;
                error_info_container_impl * c=new error_info_container_impl;
                p.adopt(c);
                c->info_ = info_;
                return p;
                }
            };

        template <class E,class Tag,class T>
        inline
        E const &
        set_info( E const & x, error_info<Tag,T> const & v )
            {
            typedef error_info<Tag,T> error_info_tag_t;
            shared_ptr<error_info_tag_t> p( new error_info_tag_t(v) );
            exception_detail::error_info_container * c=x.data_.get();
            if( !c )
                x.data_.adopt(c=new exception_detail::error_info_container_impl);
            c->set(p,BOOST_EXCEPTION_STATIC_TYPEID(error_info_tag_t));
            return x;
            }

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
        template <class E,class Tag,class T>
        E const & set_info( E const &, error_info<Tag,T> && );
		template <class T>
		class set_info_rv;
		template <class Tag,class T>
		class
		set_info_rv<error_info<Tag,T> >
			{
			template <class E,class Tag1,class T1>
			friend E const & set_info( E const &, error_info<Tag1,T1> && );
			template <class E>
			static
			E const &
			set( E const & x, error_info<Tag,T> && v )
				{
				typedef error_info<Tag,T> error_info_tag_t;
				shared_ptr<error_info_tag_t> p( new error_info_tag_t(std::move(v)) );
				exception_detail::error_info_container * c=x.data_.get();
				if( !c )
					x.data_.adopt(c=new exception_detail::error_info_container_impl);
				c->set(p,BOOST_EXCEPTION_STATIC_TYPEID(error_info_tag_t));
				return x;
				}
			};
		template <>
		class
		set_info_rv<throw_function>
			{
			template <class E,class Tag1,class T1>
			friend E const & set_info( E const &, error_info<Tag1,T1> && );
			template <class E>
			static
			E const &
			set( E const & x, throw_function && y )
				{
				x.throw_function_=y.v_;
				return x;
				}
			};
		template <>
		class
		set_info_rv<throw_file>
			{
			template <class E,class Tag1,class T1>
			friend E const & set_info( E const &, error_info<Tag1,T1> && );
			template <class E>
			static
			E const &
			set( E const & x, throw_file && y )
				{
				x.throw_file_=y.v_;
				return x;
				}
			};
		template <>
		class
		set_info_rv<throw_line>
			{
			template <class E,class Tag1,class T1>
			friend E const & set_info( E const &, error_info<Tag1,T1> && );
			template <class E>
			static
			E const &
			set( E const & x, throw_line && y )
				{
				x.throw_line_=y.v_;
				return x;
				}
			};
        template <class E,class Tag,class T>
        inline
        E const &
        set_info( E const & x, error_info<Tag,T> && v )
            {
			return set_info_rv<error_info<Tag,T> >::template set<E>(x,std::move(v));
            }
#endif

        template <class T>
        struct
        derives_boost_exception
            {
            enum e { value = (sizeof(dispatch_boost_exception((T*)0))==sizeof(large_size)) };
            };
        }

    template <class E,class Tag,class T>
    inline
    typename enable_if<exception_detail::derives_boost_exception<E>,E const &>::type
    operator<<( E const & x, error_info<Tag,T> const & v )
        {
        return exception_detail::set_info(x,v);
        }

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    template <class E,class Tag,class T>
    inline
    typename enable_if<exception_detail::derives_boost_exception<E>,E const &>::type
    operator<<( E const & x, error_info<Tag,T> && v )
        {
        return exception_detail::set_info(x,std::move(v));
        }
#endif
    }

#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(pop)
#endif
#endif


text:
package org.jboss.resteasy.test.providers.jaxb.collection;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.test.BaseResourceTest;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashMap;
import java.util.Map;

import static org.jboss.resteasy.test.TestPortProvider.generateURL;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class JsonMapTest extends BaseResourceTest
{
   @XmlRootElement
   public static class Foo
   {
      @XmlAttribute
      private String name;

      public Foo()
      {
      }

      public Foo(String name)
      {
         this.name = name;
      }

      public String getName()
      {
         return name;
      }
   }

   @Path("/map")
   public static class MyResource
   {
      @POST
      @Produces("application/json")
      @Consumes("application/json")
      public Map<String, Foo> post(Map<String, Foo> map)
      {
         Assert.assertEquals(2, map.size());
         Assert.assertNotNull(map.get("bill"));
         Assert.assertNotNull(map.get("monica"));
         Assert.assertEquals(map.get("bill").getName(), "bill");
         Assert.assertEquals(map.get("monica").getName(), "monica");
         return map;
      }

      @POST
      @Produces("application/json")
      @Consumes("application/json")
      @Path("empty")
      public Map<String, Foo> postEmpty(Map<String, Foo> map)
      {
         Assert.assertEquals(0, map.size());
         return map;
      }

      @GET
      @Produces("application/json")
      public Map<String, Foo> get()
      {
         HashMap<String, Foo> map = new HashMap<String, Foo>();
         map.put("bill", new Foo("bill"));
         map.put("monica", new Foo("monica"));
         return map;
      }
   }

   @BeforeClass
   public static void setup()
   {
      addPerRequestResource(MyResource.class);

   }

   @Test
   public void testProvider() throws Exception
   {
      ClientRequest request = new ClientRequest(generateURL("/map"));
      ClientResponse<String> response = request.get(String.class);
      Assert.assertEquals(200, response.getStatus());
      System.out.println(response.getEntity());

      request = new ClientRequest(generateURL("/map"));
      request.body("application/json", response.getEntity());
      response = request.post();
      Assert.assertEquals(200, response.getStatus());

      request = new ClientRequest(generateURL("/map"));
      request.body("application/json", "{\"monica\":{\"foo\":{\"@name\":\"monica\"}},\"bill\":{\"foo\":{\"@name\":\"bill\"}}}");
      response = request.post();
      Assert.assertEquals(200, response.getStatus());
   }

   @Test
   public void testEmptyMap() throws Exception
   {
      ClientRequest request = new ClientRequest(generateURL("/map/empty"));
      request.body("application/json", "{}");
      ClientResponse<String> response = request.post(String.class);
      Assert.assertEquals(200, response.getStatus());
      Assert.assertEquals("{}", response.getEntity());

   }
}


text:
coral gables, cocnut grove

neighborhood name1, neighborhood name1,neighborhood name1, neighborhood name1


text:
namespace Factory
{
    public interface IPaymentGateway
    {
        void PerformPayment(Product product);
    }
}


text:
package com.carrotsearch.progresso.util;

import com.carrotsearch.progresso.util.LineFormatter.Alignment;
import com.carrotsearch.progresso.util.LineFormatter.Trim;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import org.assertj.core.api.Assertions;
import org.junit.Test;

public class LineFormatterTest extends RandomizedTest {
  @Test
  public void stretchableField() {
    check("abc", 3, new LineFormatter().cell(0, "abc"));
    check("abc ", 4, new LineFormatter().cell(0, "abc"));
    check("abc", 4, new LineFormatter().cell(0, 3, Alignment.LEFT, "abc"));

    check("  ", 2, new LineFormatter().cell(0, "abc"));
    check("a...", 4, new LineFormatter().cell(0, "abcde"));
    check("a...", 4, new LineFormatter().cell(2, "abcde"));
  }

  @Test
  public void alignmentFixedLengthValue() {
    check("abc", 5, new LineFormatter().cell("abc"));
  }

  @Test
  public void alignmentLeft() {
    check("abc  ", 5, new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, "abc"));
  }

  @Test
  public void alignmentRight() {
    check("  abc", 5, new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.RIGHT, "abc"));
  }

  @Test
  public void alignmentAndTrimTruncated() {
    check(
        "...ef",
        5,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.RIGHT, Trim.RIGHT, "abcdef"));
    check(
        "ab...",
        5,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.RIGHT, Trim.LEFT, "abcdef"));
    check(
        "...",
        3,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.RIGHT, Trim.LEFT, "abcdef"));
    check(
        "  ",
        2,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.RIGHT, Trim.LEFT, "abcdef"));

    check(
        "ab...",
        5,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.LEFT, "abcdef"));
    check(
        "...ef",
        5,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.RIGHT, "abcdef"));
    check(
        "...",
        3,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.RIGHT, "abcdef"));
    check(
        "  ",
        2,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.RIGHT, "abcdef"));

    check(
        "a...f",
        5,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.MIDDLE, "abcdef"));
    check(
        "a...",
        4,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.MIDDLE, "abcdef"));
    check(
        "...",
        3,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.MIDDLE, "abcdef"));
    check(
        "  ",
        2,
        new LineFormatter().cell(0, Integer.MAX_VALUE, Alignment.LEFT, Trim.MIDDLE, "abcdef"));

    check("", 5, new LineFormatter().cell("abcdef"));
  }

  @Test
  public void simpleFields() {
    check("abc", 3, new LineFormatter().cell("abc"));
    check("abc", 4, new LineFormatter().cell("abc")); // goes unpadded.
    check("", 2, new LineFormatter().cell("abc")); // Not enough space for a field.
  }

  @Test
  public void multiFields() {
    check("abcdef", 6, new LineFormatter().cell("abc").cell("def"));
    // Unpadded.
    check("abcdef", 7, new LineFormatter().cell("abc").cell("def"));
    // Not enough space for the second field.
    check("abc", 5, new LineFormatter().cell("abc").cell("def"));
  }

  @Test
  public void multiFieldsWithStretchables() {
    check("abcdef ", 7, new LineFormatter().cell("abc").cell(0, "def"));
    check("abc def", 7, new LineFormatter().cell(0, "abc").cell("def"));
    check("abcdef ", 7, new LineFormatter().cell("abc").cell(0, "def"));
    check("abc def ", 8, new LineFormatter().cell(0, "abc").cell(0, "def"));
  }

  @Test
  public void stretchablesWithLimit() {
    check("abc  |def  ", 100, new LineFormatter().cell(3, 5, "abc").cell("|").cell(3, 5, "def"));

    check(
        "abc  >  <  def  ",
        5 + 5 + 3 + 3,
        new LineFormatter()
            .cell(3, 5, "abc")
            .cell(0, Integer.MAX_VALUE, ">")
            .cell(0, Integer.MAX_VALUE, "<")
            .cell(3, 5, "def"));
  }

  @Test
  public void prioritizedColumns() {
    check(
        "  xyz",
        5,
        new LineFormatter()
            .cell(3, 8, Alignment.LEFT, Trim.LEFT, LineFormatter.PRIORITY_OPTIONAL, "abc")
            .cell(3, 8, Alignment.LEFT, Trim.LEFT, LineFormatter.PRIORITY_DEFAULT, "def")
            .cell(3, 8, Alignment.RIGHT, Trim.LEFT, LineFormatter.PRIORITY_HIGH, "xyz"));
    check(
        "def xyz",
        7,
        new LineFormatter()
            .cell(3, 8, Alignment.LEFT, Trim.LEFT, LineFormatter.PRIORITY_OPTIONAL, "abc")
            .cell(3, 8, Alignment.LEFT, Trim.LEFT, LineFormatter.PRIORITY_DEFAULT, "def")
            .cell(3, 8, Alignment.RIGHT, Trim.LEFT, LineFormatter.PRIORITY_HIGH, "xyz"));
  }

  private void check(String expected, int width, LineFormatter lf) {
    String actual = lf.format(width);
    if (!actual.equals(expected)) {
      System.out.println("e:" + expected);
      System.out.println("a:" + actual);
    }
    Assertions.assertThat(actual).isEqualTo(expected);
  }
}


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

<TITLE>
InvalidMessageException (SMSLib 3.5.3)
</TITLE>

<META NAME="date" CONTENT="2013-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.smslib

Class InvalidMessageException

java.lang.Object
  java.lang.Throwable
      java.lang.Exception
          org.smslib.SMSLibException
              org.smslib.GatewayException
                  org.smslib.InvalidMessageException

All Implemented Interfaces:
java.io.Serializable

public class InvalidMessageException
extends GatewayException

InvalidMessageException

Author:

brozow

See Also:
Serialized Form

Constructor Summary

InvalidMessageException()

InvalidMessageException(java.lang.String errorMessage)

InvalidMessageException(java.lang.String errorMessage,
                        java.lang.Throwable e)

InvalidMessageException(java.lang.Throwable e)

Method Summary

Methods inherited from class org.smslib.SMSLibException

getOriginalException

Methods inherited from class java.lang.Throwable

fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

InvalidMessageException

public InvalidMessageException(java.lang.String errorMessage)

InvalidMessageException

public InvalidMessageException()

InvalidMessageException

public InvalidMessageException(java.lang.Throwable e)

InvalidMessageException

public InvalidMessageException(java.lang.String errorMessage,
                               java.lang.Throwable e)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

(c) 2002-2011, http://smslib.org


text:
package aQute.bnd.deployer.repository;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Version;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;

import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.lib.io.IO;
import junit.framework.TestCase;

public class FindProvidersTest extends TestCase {

	public static void testPackageQuery() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/minir5.xml").toURI().toString());
		repo.setProperties(props);

		Requirement req = CapReqBuilder.createPackageRequirement("org.example.a", "[1,2)").buildSyntheticRequirement();
		Map<Requirement,Collection<Capability>> result = repo.findProviders(Collections.singleton(req));

		assertNotNull(result);
		assertTrue(result.containsKey(req));
		Collection<Capability> caps = result.get(req);
		Capability[] capsArray = new Capability[1];
		capsArray = caps.toArray(capsArray);
		Capability identityCap = capsArray[0].getResource().getCapabilities("osgi.identity").get(0);
		Object identityAttrValue = identityCap.getAttributes().get("osgi.identity");
		assertEquals("dummybundle", identityAttrValue);
	}

	public static void testTypedCapabilityAttribute() {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/minir5.xml").toURI().toString());
		repo.setProperties(props);

		Requirement req = CapReqBuilder.createPackageRequirement("org.example.a", "[1,2)").buildSyntheticRequirement();
		Map<Requirement,Collection<Capability>> result = repo.findProviders(Collections.singleton(req));
		Capability id = result.get(req).iterator().next().getResource().getCapabilities("osgi.identity").get(0);
		assertEquals(Version.class, id.getAttributes().get("version").getClass());
	}

	public static void testReadGZippedStream() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml.gz").toURI().toString());
		repo.setProperties(props);

		Requirement req = new CapReqBuilder("osgi.identity")
				.addDirective("filter", "(&(osgi.identity=osgi.cmpn)(version>=4.2.0)(!(version>=4.2.1)))")
				.buildSyntheticRequirement();
		Map<Requirement,Collection<Capability>> result = repo.findProviders(Collections.singleton(req));

		assertNotNull(result);
		assertTrue(result.containsKey(req));

		Collection<Capability> caps = result.get(req);
		assertEquals(1, caps.size());
		Capability identityCap = caps.iterator().next();

		List<Capability> contentCaps = identityCap.getResource().getCapabilities("osgi.content");
		assertNotNull(contentCaps);
		assertEquals(1, contentCaps.size());
		Capability contentCap = contentCaps.iterator().next();
		assertEquals(IO.getFile("testdata/osgi.cmpn/osgi.cmpn-4.2.0.jar").getAbsoluteFile().toURI(),
				contentCap.getAttributes().get("url"));
	}

	public static void testMultipleMatches() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml").toURI().toString());
		repo.setProperties(props);

		Requirement req = CapReqBuilder.createPackageRequirement("aQute.bnd.annotation", "[1.43,2)")
				.buildSyntheticRequirement();
		Map<Requirement,Collection<Capability>> result = repo.findProviders(Collections.singleton(req));
		Collection<Capability> matchingCaps = result.get(req);

		// 16 versions of biz.aQute.bndlib plus 8 versions of
		// biz.aQute.bnd.annotation!
		assertEquals(24, matchingCaps.size());

		for (Capability cap : matchingCaps) {
			Capability identityCap = cap.getResource().getCapabilities("osgi.identity").iterator().next();
			String bsn = (String) identityCap.getAttributes().get("osgi.identity");
			assertTrue("biz.aQute.bndlib".equals(bsn) || "biz.aQute.bnd.annotation".equals(bsn));
		}
	}

	public void testResolveByHash() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml").toURI().toString());
		repo.setProperties(props);

		Map<String,String> searchProps = new HashMap<>();
		searchProps.put("version", "hash");
		searchProps.put("hash", "292ecca5d8fdb881f0273c1166b9c20925be063d3baf3824515983f76b73fffb");

		File bundle = repo.get("biz.aQute.bnd", null, searchProps);
		assertNotNull(bundle);
		// the bundle doesn't actually exist... just check the filename
		assertEquals("biz.aQute.bnd-1.45.0.jar", bundle.getName());
	}

	public void testResolveByHashWithAlgorithm() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml").toURI().toString());
		repo.setProperties(props);

		Map<String,String> searchProps = new HashMap<>();
		searchProps.put("version", "hash");
		searchProps.put("hash", "SHA-256:292ecca5d8fdb881f0273c1166b9c20925be063d3baf3824515983f76b73fffb");
		File bundle = repo.get("biz.aQute.bnd", null, searchProps);
		assertNotNull(bundle);
		// the bundle doesn't actually exist... just check the filename
		assertEquals("biz.aQute.bnd-1.45.0.jar", bundle.getName());
	}

	public void testResolveByHashWithWrongAlgorithm() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml").toURI().toString());
		repo.setProperties(props);

		Map<String,String> searchProps = new HashMap<>();
		searchProps.put("version", "hash");
		searchProps.put("hash", "SHA-1:292ecca5d8fdb881f0273c1166b9c20925be063d3baf3824515983f76b73fffb");
		File bundle = repo.get("biz.aQute.bnd", null, searchProps);
		assertNull(bundle);
	}

	public void testResolveByHashWithIdCheck() throws Exception {
		FixedIndexedRepo repo = new FixedIndexedRepo();
		Map<String,String> props = new HashMap<String,String>();
		props.put("locations", IO.getFile("testdata/big_index.xml").toURI().toString());
		repo.setProperties(props);

		Map<String,String> searchProps = new HashMap<>();
		searchProps.put("version", "hash");
		searchProps.put("hash", "SHA-256:292ecca5d8fdb881f0273c1166b9c20925be063d3baf3824515983f76b73fffb");
		try {
			File bundle = repo.get("wrong.bsn", null, searchProps);
			fail("Expected IllegalArgumentException");
		} catch (IllegalArgumentException e) {
			// expected
		}
	}

}