text:
/*globals Ember*/
/*jshint eqnull:true*/

require("ember-data/system/record_arrays");
require("ember-data/system/transaction");
require("ember-data/system/mixins/mappable");

/**
  @module data
  @submodule data-store
*/

var get = Ember.get, set = Ember.set;
var once = Ember.run.once;
var isNone = Ember.isNone;
var forEach = Ember.EnumerableUtils.forEach;
var indexOf = Ember.EnumerableUtils.indexOf;
var map = Ember.EnumerableUtils.map;

// These values are used in the data cache when clientIds are
// needed but the underlying data has not yet been loaded by
// the server.
var UNLOADED = 'unloaded';
var LOADING = 'loading';
var MATERIALIZED = { materialized: true };
var CREATED = { created: true };

// Implementors Note:
//
//   The variables in this file are consistently named according to the following
//   scheme:
//
//   * +id+ means an identifier managed by an external source, provided inside
//     the data provided by that source. These are always coerced to be strings
//     before being used internally.
//   * +clientId+ means a transient numerical identifier generated at runtime by
//     the data store. It is important primarily because newly created objects may
//     not yet have an externally generated id.
//   * +reference+ means a record reference object, which holds metadata about a
//     record, even if it has not yet been fully materialized.
//   * +type+ means a subclass of DS.Model.

// Used by the store to normalize IDs entering the store.  Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information.  For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
var coerceId = function(id) {
  return id == null ? null : id+'';
};

/**
  The store contains all of the data for records loaded from the server.
  It is also responsible for creating instances of DS.Model that wrap
  the individual data for a record, so that they can be bound to in your
  Handlebars templates.

  Define your application's store like this:

       MyApp.Store = DS.Store.extend();

  Most Ember.js applications will only have a single `DS.Store` that is
  automatically created by their `Ember.Application`.

  You can retrieve models from the store in several ways. To retrieve a record
  for a specific id, use `DS.Model`'s `find()` method:

       var person = App.Person.find(123);

  If your application has multiple `DS.Store` instances (an unusual case), you can
  specify which store should be used:

      var person = store.find(App.Person, 123);

  In general, you should retrieve models using the methods on `DS.Model`; you should
  rarely need to interact with the store directly.

  By default, the store will talk to your backend using a standard REST mechanism.
  You can customize how the store talks to your backend by specifying a custom adapter:

       MyApp.store = DS.Store.create({
         adapter: 'MyApp.CustomAdapter'
       });

  You can learn more about writing a custom adapter by reading the `DS.Adapter`
  documentation.

  @class Store
  @namespace DS
  @extends Ember.Object
  @uses DS._Mappable
  @constructor
*/
DS.Store = Ember.Object.extend(DS._Mappable, {

  /**
    Many methods can be invoked without specifying which store should be used.
    In those cases, the first store created will be used as the default. If
    an application has multiple stores, it should specify which store to use
    when performing actions, such as finding records by ID.

    The init method registers this store as the default if none is specified.
  */
  init: function() {
    if (!get(DS, 'defaultStore') || get(this, 'isDefaultStore')) {
      set(DS, 'defaultStore', this);
    }

    // internal bookkeeping; not observable
    this.typeMaps = {};
    this.promiseMap = Ember.Map.create();
    this.recordArrayManager = DS.RecordArrayManager.create({
      store: this
    });
    this.relationshipChanges = {};

    set(this, 'currentTransaction', this.transaction());
    set(this, 'defaultTransaction', this.transaction());
    set(this, 'deferredCommits', Ember.MapWithDefault.create({
      defaultValue: function() {
        return new Ember.RSVP.defer();
      }
    }));
  },

  /**
    Returns a new transaction scoped to this store. This delegates
    responsibility for invoking the adapter's commit mechanism to
    a transaction.

    Transaction are responsible for tracking changes to records
    added to them, and supporting `commit` and `rollback`
    functionality. Committing a transaction invokes the store's
    adapter, while rolling back a transaction reverses all
    changes made to records added to the transaction.

    A store has an implicit (default) transaction, which tracks changes
    made to records not explicitly added to a transaction.

    @see {DS.Transaction}
    @returns DS.Transaction
  */
  transaction: function() {
    return DS.Transaction.create({ store: this });
  },

  /**
    @private

    Instructs the store to materialize the data for a given record.

    To materialize a record, the store first retrieves the opaque data that was
    passed to either `load()` or `loadMany()`. Then, the data and the record
    are passed to the adapter's `materialize()` method, which allows the adapter
    to translate arbitrary data structures from the adapter into the normalized
    form the record expects.

    The adapter's `materialize()` method will invoke `materializeAttribute()`,
    `materializeHasMany()` and `materializeBelongsTo()` on the record to
    populate it with normalized values.

    @param {DS.Model} record
  */
  materializeData: function(record) {
    var reference = get(record, '_reference'),
        data = reference.data,
        adapter = this.adapterForType(record.constructor);

    reference.data = MATERIALIZED;

    record.setupData();

    if (data !== CREATED) {
      // Instructs the adapter to extract information from the
      // opaque data and materialize the record's attributes and
      // relationships.
      adapter.materialize(record, data, reference.prematerialized);
    }
  },

  /**
    The adapter to use to communicate to a backend server or other persistence layer.

    This can be specified as an instance, a class, or a property path that specifies
    where the adapter can be located.

    @property {DS.Adapter|String}
  */
  adapter: Ember.computed(function(){
    if (!Ember.testing) {
      Ember.debug("A custom DS.Adapter was not provided as the 'Adapter' property of your application's Store. The default (DS.RESTAdapter) will be used.");
    }

    return DS.RESTAdapter;
  }).property(),

  /**
    @private

    Returns a JSON representation of the record using the adapter's
    serialization strategy. This method exists primarily to enable
    a record, which has access to its store (but not the store's
    adapter) to provide a `serialize()` convenience.

    The available options are:

    * `includeId`: `true` if the record's ID should be included in
      the JSON representation

    @param {DS.Model} record the record to serialize
    @param {Object} options an options hash
  */
  serialize: function(record, options) {
    return this.adapterForType(record.constructor).serialize(record, options);
  },

  /**
    @private

    This property returns the adapter, after resolving a possible
    property path.

    If the supplied `adapter` was a class, or a String property
    path resolved to a class, this property will instantiate the
    class.

    This property is cacheable, so the same instance of a specified
    adapter class should be used for the lifetime of the store.

    @returns DS.Adapter
  */
  defaultAdapter: Ember.computed(function() {
    var adapter = get(this, 'adapter');

    if (typeof adapter === 'string' && this.container) {
      adapter = this.container.lookup('adapter:'+adapter);
    }

    if (DS.Adapter.detect(adapter)) {
      adapter = adapter.create();
    }

    return adapter;
  }).property('adapter'),

  /**
    @private

    A monotonically increasing number to be used to uniquely identify
    data and records.

    It starts at 1 so other parts of the code can test for truthiness
    when provided a `clientId` instead of having to explicitly test
    for undefined.
  */
  clientIdCounter: 1,

  // .....................
  // . CREATE NEW RECORD .
  // .....................

  /**
    Create a new record in the current store. The properties passed
    to this method are set on the newly created record.

    Note: The third `transaction` property is for internal use only.
    If you want to create a record inside of a given transaction,
    use `transaction.createRecord()` instead of `store.createRecord()`.

    @method createRecord
    @param {subclass of DS.Model} type
    @param {Object} properties a hash of properties to set on the
      newly created record.
    @returns DS.Model
  */
  createRecord: function(type, properties, transaction) {
    properties = properties || {};

    // Create a new instance of the model `type` and put it
    // into the specified `transaction`. If no transaction is
    // specified, the default transaction will be used.
    var record = type._create({
      store: this
    });

    transaction = transaction || get(this, 'defaultTransaction');

    // adoptRecord is an internal API that allows records to move
    // into a transaction without assertions designed for app
    // code. It is used here to ensure that regardless of new
    // restrictions on the use of the public `transaction.add()`
    // API, we will always be able to insert new records into
    // their transaction.
    transaction.adoptRecord(record);

    // `id` is a special property that may not be a `DS.attr`
    var id = properties.id;

    // If the passed properties do not include a primary key,
    // give the adapter an opportunity to generate one. Typically,
    // client-side ID generators will use something like uuid.js
    // to avoid conflicts.

    if (isNone(id)) {
      var adapter = this.adapterForType(type);

      if (adapter && adapter.generateIdForRecord) {
        id = coerceId(adapter.generateIdForRecord(this, record));
        properties.id = id;
      }
    }

    // Coerce ID to a string
    id = coerceId(id);

    // Create a new `clientId` and associate it with the
    // specified (or generated) `id`. Since we don't have
    // any data for the server yet (by definition), store
    // the sentinel value CREATED as the data for this
    // clientId. If we see this value later, we will skip
    // materialization.
    var reference = this.createReference(type, id);
    reference.data = CREATED;

    // Now that we have a reference, attach it to the record we
    // just created.
    set(record, '_reference', reference);
    reference.record = record;

    // Move the record out of its initial `empty` state into
    // the `loaded` state.
    record.loadedData();

    record.setupData();

    // Set the properties specified on the record.
    record.setProperties(properties);

    return record;
  },

  // .................
  // . DELETE RECORD .
  // .................

  /**
    For symmetry, a record can be deleted via the store.

    @param {DS.Model} record
  */
  deleteRecord: function(record) {
    record.deleteRecord();
  },

  /**
    For symmetry, a record can be unloaded via the store.

    @param {DS.Model} record
  */
  unloadRecord: function(record) {
    record.unloadRecord();
  },

  // ................
  // . FIND RECORDS .
  // ................

  /**
    This is the main entry point into finding records. The first parameter to
    this method is always a subclass of `DS.Model`.

    You can use the `find` method on a subclass of `DS.Model` directly if your
    application only has one store. For example, instead of
    `store.find(App.Person, 1)`, you could say `App.Person.find(1)`.

    ---

    To find a record by ID, pass the `id` as the second parameter:

        store.find(App.Person, 1);
        App.Person.find(1);

    If the record with that `id` had not previously been loaded, the store will
    return an empty record immediately and ask the adapter to find the data by
    calling the adapter's `find` method.

    The `find` method will always return the same object for a given type and
    `id`. To check whether the adapter has populated a record, you can check
    its `isLoaded` property.

    ---

    To find all records for a type, call `find` with no additional parameters:

        store.find(App.Person);
        App.Person.find();

    This will return a `RecordArray` representing all known records for the
    given type and kick off a request to the adapter's `findAll` method to load
    any additional records for the type.

    The `RecordArray` returned by `find()` is live. If any more records for the
    type are added at a later time through any mechanism, it will automatically
    update to reflect the change.

    ---

    To find a record by a query, call `find` with a hash as the second
    parameter:

        store.find(App.Person, { page: 1 });
        App.Person.find({ page: 1 });

    This will return a `RecordArray` immediately, but it will always be an
    empty `RecordArray` at first. It will call the adapter's `findQuery`
    method, which will populate the `RecordArray` once the server has returned
    results.

    You can check whether a query results `RecordArray` has loaded by checking
    its `isLoaded` property.

    @method find
    @param {DS.Model} type
    @param {Object|String|Integer|null} id
  */
  find: function(type, id) {
    if (id === undefined) {
      return this.findAll(type);
    }

    // We are passed a query instead of an id.
    if (Ember.typeOf(id) === 'object') {
      return this.findQuery(type, id);
    }

    return this.findById(type, coerceId(id));
  },

  /**
  */
  fetch: function(type, id) {
    var entity = this.find(type, id);

    return this.promiseFor(entity);
  },

  /**
  */
  reloadRecord: function(record) {
    var type = record.constructor,
        id = get(record, 'id');

    Ember.assert("You cannot update a record without an ID", id);

    return this.fetchRecord(type, id, record);
  },

  /**
    @private

    This method returns a record for a given type and id combination.

    If the store has never seen this combination of type and id before, it
    creates a new `clientId` with the LOADING sentinel and asks the adapter to
    load the data.

    If the store has seen the combination, this method delegates to
    `getByReference`.
  */
  findById: function(type, id) {
    var reference;

    if (this.hasReferenceForId(type, id)) {
      reference = this.referenceForId(type, id);

      if (reference.data !== UNLOADED) {
        return this.recordForReference(reference);
      }
    }

    if (!reference) {
      reference = this.createReference(type, id);
    }

    reference.data = LOADING;

    // create a new instance of the model type in the
    // 'isLoading' state
    var record = this.materializeRecord(reference);

    if (reference.data === LOADING) {
      // let the adapter set the data, possibly async
      this.fetchRecord(type, id, record);
    }

    return record;
  },

  /**
    @private

    Given an array of `reference`s, determines which of those
    `clientId`s has not yet been loaded.

    In preparation for loading, this method also marks any unloaded
    `clientId`s as loading.
  */
  unloadedReferences: function(references) {
    var unloadedReferences = [];

    for (var i=0, l=references.length; i<l; i++) {
      var reference = references[i];

      if (reference.data === UNLOADED) {
        unloadedReferences.push(reference);
        reference.data = LOADING;
      }
    }

    return unloadedReferences;
  },

  /**
    @private

    This method is the entry point that relationships use to update
    themselves when their underlying data changes.

    First, it determines which of its `reference`s are still unloaded,
    then invokes `findMany` on the adapter.
  */
  fetchUnloadedReferences: function(references, owner, manyArray) {
    var unloadedReferences = this.unloadedReferences(references);
    return this.fetchMany(unloadedReferences, owner, manyArray);
  },

  /**
    @private

    `findMany` is the entry point that relationships use to generate a
    new `ManyArray` for the list of IDs specified by the server for
    the relationship.

    Its responsibilities are:

    * convert the IDs into clientIds
    * determine which of the clientIds still need to be loaded
    * create a new ManyArray whose content is *all* of the clientIds
    * notify the ManyArray of the number of its elements that are
      already loaded
    * insert the unloaded references into the `loadingRecordArrays`
      bookkeeping structure, which will allow the `ManyArray` to know
      when all of its loading elements are loaded from the server.
    * ask the adapter to load the unloaded elements, by invoking
      findMany with the still-unloaded IDs.
  */
  findMany: function(type, idsOrReferences, record, relationship) {
    // 1. Determine which of the client ids need to be loaded
    // 2. Create a new ManyArray whose content is ALL of the clientIds
    // 3. Decrement the ManyArray's counter by the number of loaded clientIds
    // 4. Put the ManyArray into our bookkeeping data structure, keyed on
    //    the needed clientIds
    // 5. Ask the adapter to load the records for the unloaded clientIds (but
    //    convert them back to ids)
    if (!Ember.isArray(idsOrReferences)) {
      return this.recordArrayManager.createManyArray(type, Ember.A());
    }

    // Coerce server IDs into Record Reference
    var references = map(idsOrReferences, function(reference) {
      if (typeof reference !== 'object' && reference !== null) {
        return this.referenceForId(type, reference);
      }

      return reference;
    }, this);

    var unloadedReferences = this.unloadedReferences(references),
        manyArray = this.recordArrayManager.createManyArray(type, Ember.A(references)),
        thenable, reference, i, l;

    // Start the decrementing counter on the ManyArray at the number of
    // records we need to load from the adapter
    manyArray.loadingRecordsCount(unloadedReferences.length);

    if (unloadedReferences.length) {
      for (i=0, l=unloadedReferences.length; i<l; i++) {
        reference = unloadedReferences[i];

        // keep track of the record arrays that a given loading record
        // is part of. This way, if the same record is in multiple
        // ManyArrays, all of their loading records counters will be
        // decremented when the adapter provides the data.
        this.recordArrayManager.registerWaitingRecordArray(manyArray, reference);
      }

      this.fetchMany(unloadedReferences, record, manyArray);
    } else {
      // all requested records are available
      manyArray.set('isLoaded', true);
      Ember.run.once(manyArray, 'trigger', 'didLoad');
    }

    return manyArray;
  },

  /**
    This method delegates a query to the adapter. This is the one place where
    adapter-level semantics are exposed to the application.

    Exposing queries this way seems preferable to creating an abstract query
    language for all server-side queries, and then require all adapters to
    implement them.

    @private
    @method findQuery
    @param {Class} type
    @param {Object} query an opaque query to be used by the adapter
    @return {DS.AdapterPopulatedRecordArray}
  */
  findQuery: function(type, query) {
    var array = DS.AdapterPopulatedRecordArray.create({
      type: type,
      query: query,
      content: Ember.A([]),
      store: this
    });

    this.fetchQuery(type, query, array);

    return array;
  },

  /**
    @private

    This method returns an array of all records adapter can find.
    It triggers the adapter's `findAll` method to give it an opportunity to populate
    the array with records of that type.

    @param {Class} type
    @return {DS.AdapterPopulatedRecordArray}
  */
  findAll: function(type) {
    var array = this.all(type);

    this.fetchAll(type, array);

    return array;
  },

  // .....................
  // . ADAPTER INTERFACE .
  // .....................

  /**
    @private
  */
  fetchRecord: function(type, id, record) {
    var adapter = this.adapterForType(type);

    Ember.assert("You tried to update a record but you have no adapter (for " + type + ")", adapter);
    Ember.assert("You tried to update a record but your adapter does not implement `find`", adapter.find);

    var thenable = adapter.find(this, type, id);

    thenable = this.resolveWith(thenable, record);
    return this.registerPromiseFor(thenable, record);
  },

  /**
    @private

    This method takes a list of `reference`s, groups the `reference`s by type,
    converts the `reference`s into IDs, and then invokes the adapter's `findMany`
    method.

    The `reference`s are grouped by type to invoke `findMany` on adapters
    for each unique type in `reference`s.

    It is used both by a brand new relationship (via the `findMany`
    method) or when the data underlying an existing relationship
    changes (via the `fetchUnloadedReferences` method).
  */
  fetchMany: function(references, owner, manyArray) {
    if (!references.length) { return Ember.RSVP.resolve(); }

    // Group By Type
    var referencesByTypeMap = Ember.MapWithDefault.create({
      defaultValue: function() { return Ember.A(); }
    });
    forEach(references, function(reference) {
      referencesByTypeMap.get(reference.type).push(reference);
    });

    var thenables = [];

    forEach(referencesByTypeMap, function(type) {
      var references = referencesByTypeMap.get(type),
          ids = map(references, function(reference) { return reference.id; });

      var adapter = this.adapterForType(type);

      Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter);
      Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany);

      var thenable = adapter.findMany(this, type, ids, owner);
      thenables.push(thenable);
    }, this);

    var thenable = Ember.RSVP.all(thenables);

    thenable = this.resolveWith(thenable, manyArray);
    return this.registerPromiseFor(thenable, manyArray);
  },

  /**
    @private
  */
  fetchAll: function(type, array) {
    if (get(array, 'isUpdating')) {
      return this.promiseFor(array);
    }

    var adapter = this.adapterForType(type),
        sinceToken = this.typeMapFor(type).metadata.since;

    Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
    Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll);

    set(array, 'isUpdating', true);
    set(array, 'isError', false);

    var thenable = adapter.findAll(this, type, sinceToken);

    thenable = this.resolveWith(thenable, array);
    return this.registerPromiseFor(thenable, array);
  },

  /**
    @private
  */
  fetchQuery: function(type, query, array) {
    var adapter = this.adapterForType(type);

    Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
    Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery);

    var thenable = adapter.findQuery(this, type, query, array);

    thenable = this.resolveWith(thenable, array);
    return this.registerPromiseFor(thenable, array);
  },

  /**
    @private
  */
  resolveWith: function(thenable, recordOrArray) {
    var store = this;
    return Ember.RSVP.resolve(thenable).then(function() {
      return recordOrArray;
    }, function(error) {
      if (error instanceof DS.ValidationError) {
        store.recordWasInvalid(recordOrArray, error.errors);
      } else {
        store.recordWasError(recordOrArray, error);
      }
      return Ember.RSVP.reject(error);
    });
  },

  /**
    @private
  */
  registerPromiseFor: function(promise, recordOrArray) {
    this.promiseMap.set(recordOrArray, promise);
    return promise;
  },

  /**
    @private
  */
  promiseFor: function(recordOrArray) {
    var promise = this.promiseMap.get(recordOrArray);
    if (!promise) {
      if (get(recordOrArray, 'isError')) {
        promise = Ember.RSVP.reject(recordOrArray);
      } else {
        promise = Ember.RSVP.resolve(recordOrArray);
      }
    }
    return promise;
  },

  /**
  */
  metaForType: function(type, property, data) {
    var target = this.typeMapFor(type).metadata;
    set(target, property, data);
  },

  /**
  */
  didUpdateAll: function(type) {
    var findAllCache = this.typeMapFor(type).findAllCache;

    Ember.run.once(findAllCache, 'trigger', 'didUpdate');
  },

  /**
    This method returns a filtered array that contains all of the known records
    for a given type.

    Note that because it's just a filter, it will have any locally
    created records of the type.

    Also note that multiple calls to `all` for a given type will always
    return the same RecordArray.

    @method all
    @param {Class} type
    @return {DS.RecordArray}
  */
  all: function(type) {
    var typeMap = this.typeMapFor(type),
        findAllCache = typeMap.findAllCache;

    if (findAllCache) { return findAllCache; }

    var array = DS.RecordArray.create({
      type: type,
      content: Ember.A([]),
      store: this,
      isLoaded: true
    });

    this.recordArrayManager.registerFilteredRecordArray(array, type);

    typeMap.findAllCache = array;
    return array;
  },

  /**
    Takes a type and filter function, and returns a live RecordArray that
    remains up to date as new records are loaded into the store or created
    locally.

    The callback function takes a materialized record, and returns true
    if the record should be included in the filter and false if it should
    not.

    The filter function is called once on all records for the type when
    it is created, and then once on each newly loaded or created record.

    If any of a record's properties change, or if it changes state, the
    filter function will be invoked again to determine whether it should
    still be in the array.

    Note that the existence of a filter on a type will trigger immediate
    materialization of all loaded data for a given type, so you might
    not want to use filters for a type if you are loading many records
    into the store, many of which are not active at any given time.

    In this scenario, you might want to consider filtering the raw
    data before loading it into the store.

    @method filter
    @param {Class} type
    @param {Function} filter
    @return {DS.FilteredRecordArray}
  */
  filter: function(type, query, filter) {
    // allow an optional server query
    if (arguments.length === 3) {
      this.findQuery(type, query);
    } else if (arguments.length === 2) {
      filter = query;
    }

    var array = DS.FilteredRecordArray.create({
      type: type,
      content: Ember.A([]),
      store: this,
      manager: this.recordArrayManager,
      filterFunction: filter
    });

    this.recordArrayManager.registerFilteredRecordArray(array, type, filter);

    return array;
  },

  /**
    This method returns if a certain record is already loaded
    in the store. Use this function to know beforehand if a find()
    will result in a request or that it will be a cache hit.

    @param {Class} type
    @param {string} id
    @return {boolean}
  */
  exists: function(type, id) {
    if (!this.hasReferenceForId(type, id)) { return false; }
    return typeof this.referenceForId(type, id).data === 'object';
  },

  // ............
  // . UPDATING .
  // ............

  /**
    @private

    If the adapter updates attributes or acknowledges creation
    or deletion, the record will notify the store to update its
    membership in any filters.

    To avoid thrashing, this method is invoked only once per
    run loop per record.

    @param {Class} type
    @param {Number|String} clientId
    @param {DS.Model} record
  */
  dataWasUpdated: function(type, reference, record) {
    // Because data updates are invoked at the end of the run loop,
    // it is possible that a record might be deleted after its data
    // has been modified and this method was scheduled to be called.
    //
    // If that's the case, the record would have already been removed
    // from all record arrays; calling updateRecordArrays would just
    // add it back. If the record is deleted, just bail. It shouldn't
    // give us any more trouble after this.

    if (get(record, 'isDeleted')) { return; }

    if (typeof reference.data === "object") {
      this.recordArrayManager.referenceDidChange(reference);
    }
  },

  // ..............
  // . PERSISTING .
  // ..............

  /**
    This method delegates saving to the store's implicit
    transaction.

    Calling this method is essentially a request to persist
    any changes to records that were not explicitly added to
    a transaction.
  */
  save: function() {
    once(this, 'commitDefaultTransaction');
  },
  commit: Ember.aliasMethod('save'),

  scheduleSave: function(record) {
    var transaction = get(this, 'currentTransaction'),
        deferredCommits = get(this, 'deferredCommits'),
        defer = deferredCommits.get(transaction);

    transaction.add(record);
    once(this, 'commitCurrentTransaction');

    return defer.promise;
  },

  commitTransaction: function(name) {
    var transaction = get(this, name),
        deferredCommits = get(this, 'deferredCommits'),
        defer = deferredCommits.get(transaction);

    deferredCommits.remove(transaction);

    transaction.commit().then(function() {
      defer.resolve(transaction);
    }, function() {
      defer.reject(transaction);
    });
  },

  commitDefaultTransaction: function() {
    this.commitTransaction('defaultTransaction');
  },

  commitCurrentTransaction: function() {
    this.commitTransaction('currentTransaction');
    set(this, 'currentTransaction', this.transaction());
  },

  /**
    Adapters should call this method if they would like to acknowledge
    that all changes related to a record (other than relationship
    changes) have persisted.

    Because relationship changes affect multiple records, the adapter
    is responsible for acknowledging the change to the relationship
    directly (using `store.didUpdateRelationship`) when all aspects
    of the relationship change have persisted.

    It can be called for created, deleted or updated records.

    If the adapter supplies new data, that data will become the new
    canonical data for the record. That will result in blowing away
    all local changes and rematerializing the record with the new
    data (the "sledgehammer" approach).

    Alternatively, if the adapter does not supply new data, the record
    will collapse all local changes into its saved data. Subsequent
    rollbacks of the record will roll back to this point.

    If an adapter is acknowledging receipt of a newly created record
    that did not generate an id in the client, it *must* either
    provide data or explicitly invoke `store.didReceiveId` with
    the server-provided id.

    Note that an adapter may not supply new data when acknowledging
    a deleted record.

    @see DS.Store#didUpdateRelationship

    @param {DS.Model} record the in-flight record
    @param {Object} data optional data (see above)
  */
  didSaveRecord: function(record, data) {
    if (data) {
      this.updateId(record, data);
      this.updateRecordData(record, data);
    } else {
      this.didUpdateAttributes(record);
    }

    record.adapterDidCommit();
  },

  /**
    For convenience, if an adapter is performing a bulk commit, it can also
    acknowledge all of the records at once.

    If the adapter supplies an array of data, they must be in the same order as
    the array of records passed in as the first parameter.

    @param {#forEach} list a list of records whose changes the
      adapter is acknowledging. You can pass any object that
      has an ES5-like `forEach` method, including the
      `OrderedSet` objects passed into the adapter at commit
      time.
    @param {Array[Object]} dataList an Array of data. This
      parameter must be an integer-indexed Array-like.
  */
  didSaveRecords: function(list, dataList) {
    var i = 0;
    forEach(list, function(record) {
      this.didSaveRecord(record, dataList && dataList[i++]);
    }, this);
  },

  /**
    This method allows the adapter to specify that a record
    could not be saved because it had backend-supplied validation
    errors.

    The errors object must have keys that correspond to the
    attribute names. Once each of the specified attributes have
    changed, the record will automatically move out of the
    invalid state and be ready to commit again.

    TODO: We should probably automate the process of converting
    server names to attribute names using the existing serializer
    infrastructure.

    @param {DS.Model} record
    @param {Object} errors
  */
  recordWasInvalid: function(record, errors) {
    record.adapterDidInvalidate(errors);
  },

  /**
     This method allows the adapter to specify that a record
     could not be saved because the server returned an unhandled
     error.

     @param {DS.Model} record
     @param {any} error
  */
  recordWasError: function(record, error) {
    record.adapterDidError(error);
  },

  /**
    This is a lower-level API than `didSaveRecord` that allows an
    adapter to acknowledge the persistence of a single attribute.

    This is useful if an adapter needs to make multiple asynchronous
    calls to fully persist a record. The record will keep track of
    which attributes and relationships are still outstanding and
    automatically move into the `saved` state once the adapter has
    acknowledged everything.

    If a value is provided, it clobbers the locally specified value.
    Otherwise, the local value becomes the record's last known
    saved value (which is used when rolling back a record).

    Note that the specified attributeName is the normalized name
    specified in the definition of the `DS.Model`, not a key in
    the server-provided data.

    Also note that the adapter is responsible for performing any
    transformations on the value using the serializer API.

    @param {DS.Model} record
    @param {String} attributeName
    @param {Object} value
  */
  didUpdateAttribute: function(record, attributeName, value) {
    record.adapterDidUpdateAttribute(attributeName, value);
  },

  /**
    This method allows an adapter to acknowledge persistence
    of all attributes of a record but not relationships or
    other factors.

    It loops through the record's defined attributes and
    notifies the record that they are all acknowledged.

    This method does not take optional values, because
    the adapter is unlikely to have a hash of normalized
    keys and transformed values, and instead of building
    one up, it should just call `didUpdateAttribute` as
    needed.

    This method is intended as a middle-ground between
    `didSaveRecord`, which acknowledges all changes to
    a record, and `didUpdateAttribute`, which allows an
    adapter fine-grained control over updates.

    @param {DS.Model} record
  */
  didUpdateAttributes: function(record) {
    record.eachAttribute(function(attributeName) {
      this.didUpdateAttribute(record, attributeName);
    }, this);
  },

  /**
    This allows an adapter to acknowledge that it has saved all
    necessary aspects of a relationship change.

    This is separated from acknowledging the record itself
    (via `didSaveRecord`) because a relationship change can
    involve as many as three separate records. Records should
    only move out of the in-flight state once the server has
    acknowledged all of their relationships, and this differs
    based upon the adapter's semantics.

    There are three basic scenarios by which an adapter can
    save a relationship.

    ### Foreign Key

    An adapter can save all relationship changes by updating
    a foreign key on the child record. If it does this, it
    should acknowledge the changes when the child record is
    saved.

        record.eachRelationship(function(name, meta) {
          if (meta.kind === 'belongsTo') {
            store.didUpdateRelationship(record, name);
          }
        });

        store.didSaveRecord(record, data);

    ### Embedded in Parent

    An adapter can save one-to-many relationships by embedding
    IDs (or records) in the parent object. In this case, the
    relationship is not considered acknowledged until both the
    old parent and new parent have acknowledged the change.

    In this case, the adapter should keep track of the old
    parent and new parent, and acknowledge the relationship
    change once both have acknowledged. If one of the two
    sides does not exist (e.g. the new parent does not exist
    because of nulling out the belongs-to relationship),
    the adapter should acknowledge the relationship once
    the other side has acknowledged.

    ### Separate Entity

    An adapter can save relationships as separate entities
    on the server. In this case, they should acknowledge
    the relationship as saved once the server has
    acknowledged the entity.

    @see DS.Store#didSaveRecord

    @param {DS.Model} record
    @param {DS.Model} relationshipName
  */
  didUpdateRelationship: function(record, relationshipName) {
    var clientId = get(record, '_reference').clientId;

    var relationship = this.relationshipChangeFor(clientId, relationshipName);
    //TODO(Igor)
    if (relationship) { relationship.adapterDidUpdate(); }
  },

  /**
    This allows an adapter to acknowledge all relationship changes
    for a given record.

    Like `didUpdateAttributes`, this is intended as a middle ground
    between `didSaveRecord` and fine-grained control via the
    `didUpdateRelationship` API.
  */
  didUpdateRelationships: function(record) {
    var changes = this.relationshipChangesFor(get(record, '_reference'));

    for (var name in changes) {
      if (!changes.hasOwnProperty(name)) { continue; }
      changes[name].adapterDidUpdate();
    }
  },

  /**
    When acknowledging the creation of a locally created record,
    adapters must supply an id (if they did not implement
    `generateIdForRecord` to generate an id locally).

    If an adapter does not use `didSaveRecord` and supply a hash
    (for example, if it needs to make multiple HTTP requests to
    create and then update the record), it will need to invoke
    `didReceiveId` with the backend-supplied id.

    When not using `didSaveRecord`, an adapter will need to
    invoke:

    * didReceiveId (unless the id was generated locally)
    * didCreateRecord
    * didUpdateAttribute(s)
    * didUpdateRelationship(s)

    @param {DS.Model} record
    @param {Number|String} id
  */
  didReceiveId: function(record, id) {
    var typeMap = this.typeMapFor(record.constructor),
        clientId = get(record, 'clientId'),
        oldId = get(record, 'id');

    Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === undefined || id === oldId);

    typeMap.idToCid[id] = clientId;
    this.clientIdToId[clientId] = id;
  },

  /**
    @private

    This method re-indexes the data by its clientId in the store
    and then notifies the record that it should rematerialize
    itself.

    @param {DS.Model} record
    @param {Object} data
  */
  updateRecordData: function(record, data) {
    get(record, '_reference').data = data;
    record.didChangeData();
  },

  /**
    @private

    If an adapter invokes `didSaveRecord` with data, this method
    extracts the id from the supplied data (using the adapter's
    `extractId()` method) and indexes the clientId with that id.

    @param {DS.Model} record
    @param {Object} data
  */
  updateId: function(record, data) {
    var type = record.constructor,
        typeMap = this.typeMapFor(type),
        reference = get(record, '_reference'),
        oldId = get(record, 'id'),
        id = this.preprocessData(type, data);

    Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);

    typeMap.idToReference[id] = reference;
    reference.id = id;
    record.materializeId(id);
  },

  /**
    @private

    This method receives opaque data provided by the adapter and
    preprocesses it, returning an ID.

    The actual preprocessing takes place in the adapter. If you would
    like to change the default behavior, you should override the
    appropriate hooks in `DS.Serializer`.

    @see {DS.Serializer}
    @return {String} id the id represented by the data
  */
  preprocessData: function(type, data) {
    return this.adapterForType(type).extractId(type, data);
  },

  /**
    @private

    This method returns a record for a given record refeence.

    If no record for the reference has yet been materialized, this method will
    materialize a new `DS.Model` instance. This allows adapters to eagerly load
    large amounts of data into the store, and avoid incurring the cost of
    creating models until they are requested.

    In short, it's a convenient way to get a record for a known
    record reference, materializing it if necessary.

    @param {Object} reference
    @returns {DS.Model}
  */
  recordForReference: function(reference) {
    var record = reference.record;

    if (!record) {
      // create a new instance of the model type in the
      // 'isLoading' state
      record = this.materializeRecord(reference);
    }

    return record;
  },

  hasReferenceForId: function(type, id) {
    id = coerceId(id);

    return !!this.typeMapFor(type).idToReference[id];
  },

  referenceForId: function(type, id) {
    id = coerceId(id);

    // Check to see if we have seen this type/id pair before.
    var reference = this.typeMapFor(type).idToReference[id];

    // If not, create a reference for it but don't populate it
    // with any data yet.
    if (!reference) {
      reference = this.createReference(type, id);
      reference.data = UNLOADED;
    }

    return reference;
  },

  /** @private
   Returns a map of IDs to client IDs for a given type.
  */
  typeMapFor: function(type) {
    var typeMaps = get(this, 'typeMaps'),
        guid = Ember.guidFor(type),
        typeMap;

    typeMap = typeMaps[guid];

    if (typeMap) { return typeMap; }

    typeMap = {
      idToReference: {},
      references: [],
      metadata: {}
    };

    typeMaps[guid] = typeMap;

    return typeMap;
  },

  // ................
  // . LOADING DATA .
  // ................

  /**
    Load new data into the store for a given id and type combination.
    If data for that record had been loaded previously, the new information
    overwrites the old.

    If the record you are loading data for has outstanding changes that have not
    yet been saved, an exception will be thrown.

    @param {DS.Model} type
    @param {String|Number} id
    @param {Object} data the data to load
  */
  load: function(type, data, prematerialized) {
    var id;

    if (typeof data === 'number' || typeof data === 'string') {
      id = data;
      data = prematerialized;
      prematerialized = null;
    }

    if (prematerialized && prematerialized.id) {
      id = prematerialized.id;
    } else if (id === undefined) {
      id = this.preprocessData(type, data);
    }

    id = coerceId(id);

    var reference = this.referenceForId(type, id);

    if (reference.record) {
     once(reference.record, 'loadedData');
    }

    reference.data = data;
    reference.prematerialized = prematerialized;

    this.recordArrayManager.referenceDidChange(reference);

    return reference;
  },

  loadMany: function(type, ids, dataList) {
    if (dataList === undefined) {
      dataList = ids;
      ids = map(dataList, function(data) {
        return this.preprocessData(type, data);
      }, this);
    }

    return map(ids, function(id, i) {
      return this.load(type, id, dataList[i]);
    }, this);
  },

  loadHasMany: function(record, key, ids) {
    //It looks sad to have to do the conversion in the store
    var type = record.get(key + '.type'),
        tuples = map(ids, function(id) {
          return {id: id, type: type};
        });
    record.materializeHasMany(key, tuples);

    // Update any existing many arrays that use the previous IDs,
    // if necessary.
    record.hasManyDidChange(key);

    var relationship = record.cacheFor(key);

    // TODO (tomdale) this assumes that loadHasMany *always* means
    // that the records for the provided IDs are loaded.
    if (relationship) {
      set(relationship, 'isLoaded', true);
      relationship.trigger('didLoad');
    }
  },

  /** @private

    Creates a new reference for a given type & ID pair. Metadata about the
    record can be stored in the reference without having to create a full-blown
    DS.Model instance.

    @param {DS.Model} type
    @param {String|Number} id
    @returns {Reference}
  */
  createReference: function(type, id) {
    var typeMap = this.typeMapFor(type),
        idToReference = typeMap.idToReference;

    Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToReference[id]);

    var reference = {
      id: id,
      clientId: this.clientIdCounter++,
      type: type
    };

    // if we're creating an item, this process will be done
    // later, once the object has been persisted.
    if (id) {
      idToReference[id] = reference;
    }

    typeMap.references.push(reference);

    return reference;
  },

  // ..........................
  // . RECORD MATERIALIZATION .
  // ..........................

  materializeRecord: function(reference) {
    var record = reference.type._create({
      id: reference.id,
      store: this,
      _reference: reference
    });

    reference.record = record;

    get(this, 'defaultTransaction').adoptRecord(record);

    record.loadingData();

    if (typeof reference.data === 'object') {
      record.loadedData();
    }

    return record;
  },

  dematerializeRecord: function(record) {
    var reference = get(record, '_reference'),
        type = reference.type,
        id = reference.id,
        typeMap = this.typeMapFor(type);

    record.updateRecordArrays();

    if (id) { delete typeMap.idToReference[id]; }

    var loc = indexOf(typeMap.references, reference);
    typeMap.references.splice(loc, 1);
  },

  willDestroy: function() {
    if (get(DS, 'defaultStore') === this) {
      set(DS, 'defaultStore', null);
    }
  },

  // ........................
  // . RELATIONSHIP CHANGES .
  // ........................

  addRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, change) {
    var clientId = clientReference.clientId,
        parentClientId = parentReference ? parentReference.clientId : parentReference;
    var key = childKey + parentKey;
    var changes = this.relationshipChanges;
    if (!(clientId in changes)) {
      changes[clientId] = {};
    }
    if (!(parentClientId in changes[clientId])) {
      changes[clientId][parentClientId] = {};
    }
    if (!(key in changes[clientId][parentClientId])) {
      changes[clientId][parentClientId][key] = {};
    }
    changes[clientId][parentClientId][key][change.changeType] = change;
  },

  removeRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, type) {
    var clientId = clientReference.clientId,
        parentClientId = parentReference ? parentReference.clientId : parentReference;
    var changes = this.relationshipChanges;
    var key = childKey + parentKey;
    if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){
      return;
    }
    delete changes[clientId][parentClientId][key][type];
  },

  relationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, type) {
    var clientId = clientReference.clientId,
        parentClientId = parentReference ? parentReference.clientId : parentReference;
    var changes = this.relationshipChanges;
    var key = childKey + parentKey;
    if (!(clientId in changes) || !(parentClientId in changes[clientId])){
      return;
    }
    if(type){
      return changes[clientId][parentClientId][key][type];
    }
    else{
      //TODO(Igor) what if both present
      return changes[clientId][parentClientId][key]["add"] || changes[clientId][parentClientId][key]["remove"];
    }
  },

  relationshipChangePairsFor: function(reference){
    var toReturn = [];

    if( !reference ) { return toReturn; }

    //TODO(Igor) What about the other side
    var changesObject = this.relationshipChanges[reference.clientId];
    for (var objKey in changesObject){
      if(changesObject.hasOwnProperty(objKey)){
        for (var changeKey in changesObject[objKey]){
          if(changesObject[objKey].hasOwnProperty(changeKey)){
            toReturn.push(changesObject[objKey][changeKey]);
          }
        }
      }
    }
    return toReturn;
  },

  relationshipChangesFor: function(reference) {
    var toReturn = [];

    if( !reference ) { return toReturn; }

    var relationshipPairs = this.relationshipChangePairsFor(reference);
    forEach(relationshipPairs, function(pair){
      var addedChange = pair["add"];
      var removedChange = pair["remove"];
      if(addedChange){
        toReturn.push(addedChange);
      }
      if(removedChange){
        toReturn.push(removedChange);
      }
    });
    return toReturn;
  },
  // ......................
  // . PER-TYPE ADAPTERS
  // ......................

  adapterForType: function(type) {
    this._adaptersMap = this.createInstanceMapFor('adapters');

    var adapter = this._adaptersMap.get(type);
    if (adapter) { return adapter; }

    return this.get('defaultAdapter');
  },

  // ..............................
  // . RECORD CHANGE NOTIFICATION .
  // ..............................

  recordAttributeDidChange: function(reference, attributeName, newValue, oldValue) {
    var record = reference.record,
        dirtySet = new Ember.OrderedSet(),
        adapter = this.adapterForType(record.constructor);

    if (adapter.dirtyRecordsForAttributeChange) {
      adapter.dirtyRecordsForAttributeChange(dirtySet, record, attributeName, newValue, oldValue);
    }

    dirtySet.forEach(function(record) {
      record.adapterDidDirty();
    });
  },

  recordBelongsToDidChange: function(dirtySet, child, relationship) {
    var adapter = this.adapterForType(child.constructor);

    if (adapter.dirtyRecordsForBelongsToChange) {
      adapter.dirtyRecordsForBelongsToChange(dirtySet, child, relationship);
    }

    // adapterDidDirty is called by the RelationshipChange that created
    // the dirtySet.
  },

  recordHasManyDidChange: function(dirtySet, parent, relationship) {
    var adapter = this.adapterForType(parent.constructor);

    if (adapter.dirtyRecordsForHasManyChange) {
      adapter.dirtyRecordsForHasManyChange(dirtySet, parent, relationship);
    }

    // adapterDidDirty is called by the RelationshipChange that created
    // the dirtySet.
  }
});

DS.Store.reopenClass({
  registerAdapter: DS._Mappable.generateMapFunctionFor('adapters', function(type, adapter, map) {
    map.set(type, adapter);
  }),

  transformMapKey: function(key) {
    if (typeof key === 'string') {
      var transformedKey;
      transformedKey = get(Ember.lookup, key);
      Ember.assert("Could not find model at path " + key, transformedKey);
      return transformedKey;
    } else {
      return key;
    }
  },

  transformMapValue: function(key, value) {
    if (Ember.Object.detect(value)) {
      return value.create();
    }

    return value;
  }
});


text:
package com.amazonaws.services.groundstation.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Item in a list of DataflowEndpoint groups.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DataflowEndpointListItem implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * ARN of a dataflow endpoint group.
     *

     */
    private String dataflowEndpointGroupArn;
    /**
     *

     * UUID of a dataflow endpoint group.
     *

     */
    private String dataflowEndpointGroupId;

    /**
     *

     * ARN of a dataflow endpoint group.
     *

     *
     * @param dataflowEndpointGroupArn
     *        ARN of a dataflow endpoint group.
     */

    public void setDataflowEndpointGroupArn(String dataflowEndpointGroupArn) {
        this.dataflowEndpointGroupArn = dataflowEndpointGroupArn;
    }

    /**
     *

     * ARN of a dataflow endpoint group.
     *

     *
     * @return ARN of a dataflow endpoint group.
     */

    public String getDataflowEndpointGroupArn() {
        return this.dataflowEndpointGroupArn;
    }

    /**
     *

     * ARN of a dataflow endpoint group.
     *

     *
     * @param dataflowEndpointGroupArn
     *        ARN of a dataflow endpoint group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DataflowEndpointListItem withDataflowEndpointGroupArn(String dataflowEndpointGroupArn) {
        setDataflowEndpointGroupArn(dataflowEndpointGroupArn);
        return this;
    }

    /**
     *

     * UUID of a dataflow endpoint group.
     *

     *
     * @param dataflowEndpointGroupId
     *        UUID of a dataflow endpoint group.
     */

    public void setDataflowEndpointGroupId(String dataflowEndpointGroupId) {
        this.dataflowEndpointGroupId = dataflowEndpointGroupId;
    }

    /**
     *

     * UUID of a dataflow endpoint group.
     *

     *
     * @return UUID of a dataflow endpoint group.
     */

    public String getDataflowEndpointGroupId() {
        return this.dataflowEndpointGroupId;
    }

    /**
     *

     * UUID of a dataflow endpoint group.
     *

     *
     * @param dataflowEndpointGroupId
     *        UUID of a dataflow endpoint group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DataflowEndpointListItem withDataflowEndpointGroupId(String dataflowEndpointGroupId) {
        setDataflowEndpointGroupId(dataflowEndpointGroupId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDataflowEndpointGroupArn() != null)
            sb.append("DataflowEndpointGroupArn: ").append(getDataflowEndpointGroupArn()).append(",");
        if (getDataflowEndpointGroupId() != null)
            sb.append("DataflowEndpointGroupId: ").append(getDataflowEndpointGroupId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DataflowEndpointListItem == false)
            return false;
        DataflowEndpointListItem other = (DataflowEndpointListItem) obj;
        if (other.getDataflowEndpointGroupArn() == null ^ this.getDataflowEndpointGroupArn() == null)
            return false;
        if (other.getDataflowEndpointGroupArn() != null && other.getDataflowEndpointGroupArn().equals(this.getDataflowEndpointGroupArn()) == false)
            return false;
        if (other.getDataflowEndpointGroupId() == null ^ this.getDataflowEndpointGroupId() == null)
            return false;
        if (other.getDataflowEndpointGroupId() != null && other.getDataflowEndpointGroupId().equals(this.getDataflowEndpointGroupId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDataflowEndpointGroupArn() == null) ? 0 : getDataflowEndpointGroupArn().hashCode());
        hashCode = prime * hashCode + ((getDataflowEndpointGroupId() == null) ? 0 : getDataflowEndpointGroupId().hashCode());
        return hashCode;
    }

    @Override
    public DataflowEndpointListItem clone() {
        try {
            return (DataflowEndpointListItem) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.groundstation.model.transform.DataflowEndpointListItemMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Mockolo < Formula
  desc "Efficient Mock Generator for Swift"
  homepage "https://github.com/uber/mockolo"
  url "https://github.com/uber/mockolo/archive/1.6.1.tar.gz"
  sha256 "e6a701de847f20bb61f06c26d66c2ff9d492b44b82dcb76dff9e00f499cb1175"
  license "Apache-2.0"

  bottle do
    sha256 cellar: :any_skip_relocation, arm64_big_sur: "1d6affc1bcf5e25b214130b29c5b39ce563dce55c8ce878c4b37281b68f7ebf8"
    sha256 cellar: :any_skip_relocation, big_sur:       "164d14c4499086b3607ade66bc54e3daaf50a9b0e8983f1bc71454fe01d2a9ab"
  end

  depends_on xcode: ["12.5", :build]

  def install
    system "swift", "build", "-c", "release", "--disable-sandbox"
    bin.install ".build/release/mockolo"
  end

  test do
    (testpath/"testfile.swift").write <<~EOS
      /// @mockable
      public protocol Foo {
          var num: Int { get set }
          func bar(arg: Float) -> String
      }
    EOS
    system "#{bin}/mockolo", "-srcs", testpath/"testfile.swift", "-d", testpath/"GeneratedMocks.swift"
    assert_predicate testpath/"GeneratedMocks.swift", :exist?
    output = <<~EOS.gsub(/\s+/, "").strip
      ///
      /// @Generated by Mockolo
      ///
      public class FooMock: Foo {
        public init() { }
        public init(num: Int = 0) {
            self.num = num
        }

        public private(set) var numSetCallCount = 0
        public var num: Int = 0 { didSet { numSetCallCount += 1 } }

        public private(set) var barCallCount = 0
        public var barHandler: ((Float) -> (String))?
        public func bar(arg: Float) -> String {
            barCallCount += 1
            if let barHandler = barHandler {
                return barHandler(arg)
            }
            return ""
        }
      }
    EOS
    assert_equal output, shell_output("cat #{testpath/"GeneratedMocks.swift"}").gsub(/\s+/, "").strip
  end
end


text:
<div class="pagination" data-bind="css: {'pagination--disabled': pageCount() <= 1}">

        <select data-bind="options: pageSizes, value: pageSize"></select>

First

Prev

        /

Next

Last


text:
from locale import gettext as _

import logging
logger = logging.getLogger('jekyll_helper')

from jekyll_helper_lib.AboutDialog import AboutDialog

# See jekyll_helper_lib.AboutDialog.py for more details about how this class works.
class AboutJekyllHelperDialog(AboutDialog):
    __gtype_name__ = "AboutJekyllHelperDialog"

    def finish_initializing(self, builder): # pylint: disable=E1002
        """Set up the about dialog"""
        super(AboutJekyllHelperDialog, self).finish_initializing(builder)

        # Code for other initialization actions should be added here.


text:
kodalchy chpady Sheol ol Sheey qotey doiin chor ytoy
dchor chol Shol cThol Shtchy chaiin s choraiin chom
otchol chol chy chaiin qotaiin daiin Shain
qotchol chy yty daiin okaiin cThy

pydaiin qotchy dy tydy
chor Shytchy dy tcheay
qotaiin cThol daiin cThom
Shor Shol Shol cThy cPholdy
daiin cKhochy tchy koraiin
odal Shor ShyShol cPhaiin
qotchoiin Sheyr qoty
soiin chaiin chaiin
daiin cThey


text:
@implementation SIAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FBSDKLikeControl class];
  [FBSDKLoginButton class];

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];
  return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                        openURL:url
                                              sourceApplication:sourceApplication
                                                     annotation:annotation];
}

@end


text:
export class Client {
    _id: string;
    firstname: string;
    lastname: string;
    dob: string;
    dateOfReferral: string;
    stageOfProgress: string;
}


text:
use std::{
	error,
	fmt,
	io,
};

use crate::ffi;

/// API Error
pub enum Error {
	/// If error code used some recognized name
	KnownError(ffi::DNSServiceError),
	/// Unrecognized error codes
	UnknownError(i32),
	/// IO error
	IoError(io::Error),
}

impl Error {
	/// Check if a raw error code represents an error, and convert it
	/// accordingly.  (Not all codes are treated as an error, including
	/// `0`).
	pub fn from(value: ffi::DNSServiceErrorType) -> Result<(), Self> {
		if ffi::DNSServiceNoError::try_from(value).is_some() {
			Ok(())
		} else {
			match ffi::DNSServiceError::try_from(value) {
				Some(e) => Err(Self::KnownError(e)),
				None => Err(Self::UnknownError(value)),
			}
		}
	}
}

impl From<io::Error> for Error {
	fn from(e: io::Error) -> Self {
		Self::IoError(e)
	}
}

impl From<Error> for io::Error {
	fn from(e: Error) -> Self {
		match e {
			Error::IoError(e) => e,
			e => Self::new(io::ErrorKind::Other, e),
		}
	}
}

impl fmt::Debug for Error {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::KnownError(ffi_err) => write!(f, "known error {:?}: {}", ffi_err, ffi_err),
			Self::UnknownError(e) => write!(f, "unknown error code: {:?}", e),
			Self::IoError(e) => write!(f, "io error: {:?}", e),
		}
	}
}
impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::KnownError(ffi_err) => write!(f, "{}", ffi_err),
			Self::UnknownError(e) => write!(f, "unknown error code: {:?}", e),
			Self::IoError(e) => write!(f, "io error: {}", e),
		}
	}
}
impl error::Error for Error {
	fn source(&self) -> Option<&(dyn error::Error + 'static)> {
		match self {
			Self::KnownError(ffi_err) => Some(ffi_err),
			Self::UnknownError(_) => None,
			Self::IoError(e) => Some(e),
		}
	}
}

impl ffi::DNSServiceError {
	pub fn description(&self) -> &str {
		use ffi::DNSServiceError::*;
		match *self {
			Unknown => "unknown error",
			NoSuchName => "no such name",
			NoMemory => "out of memory",
			BadParam => "bad parameter",
			BadReference => "bad reference",
			BadState => "bad state",
			BadFlags => "bad flags",
			Unsupported => "not supported",
			NotInitialized => "not initialized",
			NoCache => "no cache",
			AlreadyRegistered => "already registered",
			NameConflict => "name conflict",
			Invalid => "invalid",
			Incompatible => "client library incompatible with daemon",
			BadInterfaceIndex => "bad interface index",
			Refused => "refused",
			NoSuchRecord => "no such record",
			NoAuth => "no auth",
			NoSuchKey => "no such key",
			NoValue => "no value",
			BufferTooSmall => "buffer too small",
		}
	}
}

impl fmt::Display for ffi::DNSServiceError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.description())
	}
}
impl error::Error for ffi::DNSServiceError {
	fn description(&self) -> &str {
		self.description()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	#[allow(deprecated)]
	fn test_ffi_err_description() {
		// make sure Error::description still works, although we now provide a
		// (non-trait) description method
		assert_eq!(
			error::Error::description(&ffi::DNSServiceError::NoAuth),
			"no auth"
		);
	}
}


text:
%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%

$project=Qt5xHb
$module=QtNetworkAuth

$header

$includes=5,10,0

$beginSlotsClass
$slot=5,10,0|authorizationUrlChanged( const QUrl & url )
$slot=5,10,0|authorizeWithBrowser( const QUrl & url )
$slot=5,10,0|clientIdentifierChanged( const QString & clientIdentifier )
$slot=5,10,0|contentTypeChanged( QAbstractOAuth::ContentType contentType )
%% $slot=|extraTokensChanged( const QVariantMap & tokens )
$slot=5,10,0|finished( QNetworkReply * reply )
$slot=5,10,0|granted()
$slot=5,10,0|replyDataReceived( const QByteArray & data )
%% $slot=|requestFailed( const QAbstractOAuth::Error error )
$slot=5,10,0|statusChanged( QAbstractOAuth::Status status )
$slot=5,10,0|tokenChanged( const QString & token )
$endSlotsClass


text:
package com.intel.analytics.zoo.pipeline.api.keras.layers

import com.intel.analytics.bigdl.nn.abstractnn.{AbstractModule, Activity}
import com.intel.analytics.bigdl.utils.SingleShape
import com.intel.analytics.bigdl.nn.keras.{KerasLayer}
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.utils.Shape
import com.intel.analytics.zoo.models.common.ZooModel
import com.intel.analytics.zoo.pipeline.api.Net
import com.intel.analytics.zoo.pipeline.api.keras.layers.internal.InternalTimeDistributed
import com.intel.analytics.zoo.pipeline.api.keras.layers.utils.KerasUtils
import com.intel.analytics.zoo.pipeline.api.keras.models.KerasNet

import scala.reflect.ClassTag

/**
 * TimeDistributed wrapper.
 * Apply a layer to every temporal slice of an input.
 * The input should be at least 3D, and the dimension of index one
 * will be considered to be the temporal dimension.
 *
 * When using this layer as the first layer in a model, you need to provide the argument
 * inputShape (a Single Shape, does not include the batch dimension).
 *
 * If you apply TimeDistributed to a Dense layer, you can use:
 * TimeDistributed(Dense(8), inputShape = Shape(10, 12))
 *
 * @param layer A layer instance.
 * @param inputShape A Single Shape, does not include the batch dimension.
 * @tparam T The numeric type of parameter(e.g. weight, bias). Only support float/double now.
 */
class TimeDistributed[T: ClassTag](
  val layer: KerasLayer[Activity, Tensor[T], T],
  val inputShape: Shape = null)(implicit ev: TensorNumeric[T])
  extends KerasLayer[Activity, Tensor[T], T](KerasUtils.addBatch(inputShape)) with Net {

  private var seqLen: Int = 0

  private def getInnerShape(inputShape: Shape): Shape = {
    val sizes = inputShape.toSingle().toArray
    require(sizes.length >= 3,
      s"TimeDistributed requires at least 3D input, but got input dim ${sizes.length}")
    if (seqLen != 0) {
      // in case time dim is singleton
      if (sizes(1) != 1) seqLen = sizes(1)
    } else seqLen = sizes(1)
    Shape(Array(sizes(0)) ++ sizes.drop(2))
  }

  private def getInnerOutputShape(shape: Shape): Shape = {
    val sizes = shape.toSingle().toArray
    Shape(Array(sizes(0), seqLen) ++ sizes.drop(1))
  }

  override def computeOutputShape(inputShape: Shape): Shape = {
    val innerShape = if (inputShape.isInstanceOf[SingleShape]) getInnerShape(inputShape)
    else {
      val shapes = inputShape.toMulti()
      Shape(shapes.map(getInnerShape(_)))
    }

    val innerOutputShape = layer.computeOutputShape(innerShape)
    getInnerOutputShape(innerOutputShape)
  }

  override def doBuild(inputShape: Shape): AbstractModule[Activity, Tensor[T], T] = {
    val innerShape = if (inputShape.isInstanceOf[SingleShape]) getInnerShape(inputShape)
    else Shape(inputShape.toMulti().map(getInnerShape(_)))
    layer.build(innerShape)
    layer.asInstanceOf[AbstractModule[Activity, Tensor[T], T]]
    val timedistributed = InternalTimeDistributed[T](layer)
    timedistributed.asInstanceOf[AbstractModule[Activity, Tensor[T], T]]
  }
}

object TimeDistributed {
  def apply[@specialized(Float, Double) T: ClassTag](
      layer: KerasLayer[Activity, Tensor[T], T],
      inputShape: Shape = null)(implicit ev: TensorNumeric[T]): TimeDistributed[T] = {
    new TimeDistributed[T](layer, inputShape)
  }

  def apply[@specialized(Float, Double) T: ClassTag](
      layer: ZooModel[Activity, Activity, T],
      inputShape: Shape)(implicit ev: TensorNumeric[T]): TimeDistributed[T] = {
    layer.model match {
      case keras: KerasNet[T] =>
        new TimeDistributed[T](keras.asInstanceOf[KerasLayer[Activity, Tensor[T], T]], inputShape)
      case _ => throw new Exception(s"$layer is not defined in Keras style")
    }
  }
}


text:
package hdfs

import (
	"errors"
	"fmt"
	"os"
	"strings"

	hdfs "github.com/colinmarc/hdfs/v2/internal/protocol/hadoop_hdfs"
	"google.golang.org/protobuf/proto"
)

var errXAttrKeysNotFound = errors.New("one or more keys not found")

const createAndReplace = 3

// ListXAttrs returns a list of all extended attributes for the given path.
// The returned keys will be in the form
func (c *Client) ListXAttrs(name string) (map[string]string, error) {
	req := &hdfs.ListXAttrsRequestProto{Src: proto.String(name)}
	resp := &hdfs.ListXAttrsResponseProto{}

	err := c.namenode.Execute("listXAttrs", req, resp)
	if err != nil {
		return nil, &os.PathError{"list xattrs", name, interpretException(err)}
	}

	return xattrMap(resp.GetXAttrs()), nil
}

// GetXAttrs returns the extended attributes for the given path and list of
// keys. The keys should be prefixed by namespace, e.g. user.foo or trusted.bar.
func (c *Client) GetXAttrs(name string, keys ...string) (map[string]string, error) {
	if len(keys) == 0 {
		return make(map[string]string), nil
	}

	req := &hdfs.GetXAttrsRequestProto{Src: proto.String(name)}
	for _, key := range keys {
		ns, rest, err := splitKey(key)
		if err != nil {
			return nil, &os.PathError{"get xattrs", name, err}
		}

		req.XAttrs = append(req.XAttrs, &hdfs.XAttrProto{
			Namespace: ns,
			Name:      proto.String(rest),
		})
	}
	resp := &hdfs.GetXAttrsResponseProto{}

	err := c.namenode.Execute("getXAttrs", req, resp)
	if err != nil {
		if isKeyNotFound(err) {
			return nil, &os.PathError{"get xattrs", name, errXAttrKeysNotFound}
		}

		return nil, &os.PathError{"get xattrs", name, interpretException(err)}
	}

	return xattrMap(resp.GetXAttrs()), nil
}

// SetXAttr sets an extended attribute for the given path and key. If the
// attribute doesn't exist, it will be created.
func (c *Client) SetXAttr(name, key, value string) error {
	resp := &hdfs.SetXAttrResponseProto{}

	ns, rest, err := splitKey(key)
	if err != nil {
		return &os.PathError{"set xattr", name, err}
	}

	req := &hdfs.SetXAttrRequestProto{
		Src: proto.String(name),
		XAttr: &hdfs.XAttrProto{
			Namespace: ns.Enum(),
			Name:      proto.String(rest),
			Value:     []byte(value),
		},
		Flag: proto.Uint32(createAndReplace),
	}

	err = c.namenode.Execute("setXAttr", req, resp)
	if err != nil {
		return &os.PathError{"set xattr", name, interpretException(err)}
	}

	return nil
}

// RemoveXAttr unsets an extended attribute for the given path and key. It
// returns an error if the attribute doesn't already exist.
func (c *Client) RemoveXAttr(name, key string) error {
	ns, rest, err := splitKey(key)
	if err != nil {
		return &os.PathError{"remove xattr", name, err}
	}

	req := &hdfs.RemoveXAttrRequestProto{
		Src: proto.String(name),
		XAttr: &hdfs.XAttrProto{
			Namespace: ns,
			Name:      proto.String(rest),
		},
	}
	resp := &hdfs.RemoveXAttrResponseProto{}

	err = c.namenode.Execute("removeXAttr", req, resp)
	if err != nil {
		if isKeyNotFound(err) {
			return &os.PathError{"remove xattr", name, errXAttrKeysNotFound}
		}

		return &os.PathError{"remove xattr", name, interpretException(err)}
	}

	return nil
}

func splitKey(key string) (*hdfs.XAttrProto_XAttrNamespaceProto, string, error) {
	parts := strings.SplitN(key, ".", 2)
	if len(parts) < 2 {
		return nil, "", fmt.Errorf("invalid key: '%s'", key)
	}

	var ns hdfs.XAttrProto_XAttrNamespaceProto
	switch strings.ToLower(parts[0]) {
	case "user":
		ns = hdfs.XAttrProto_USER
	case "trusted":
		ns = hdfs.XAttrProto_TRUSTED
	case "system":
		ns = hdfs.XAttrProto_SYSTEM
	case "security":
		ns = hdfs.XAttrProto_SECURITY
	case "raw":
		ns = hdfs.XAttrProto_RAW
	default:
		return nil, "", fmt.Errorf("invalid key namespace: '%s'", parts[0])
	}

	return ns.Enum(), parts[1], nil
}

func xattrMap(attrs []*hdfs.XAttrProto) map[string]string {
	m := make(map[string]string)
	for _, xattr := range attrs {
		key := fmt.Sprintf("%s.%s",
			strings.ToLower(xattr.GetNamespace().String()), xattr.GetName())
		m[key] = string(xattr.GetValue())
	}

	return m
}

func isKeyNotFound(err error) bool {
	if remoteErr, ok := err.(Error); ok {
		if strings.HasPrefix(remoteErr.Message(),
			"At least one of the attributes provided was not found") {
			return true
		}

		if strings.HasPrefix(remoteErr.Message(),
			"No matching attributes found for remove operation") {
			return true
		}
	}

	return false
}


text:
import unittest
import os

os.environ['PAAS_MANAGER_ENV'] = 'test'

from paas_manager.app.models.jobs import Jobs
from paas_manager.app.models.users import Users

class TestJobs(unittest.TestCase):
    def setUp(self):
        self.user = Users.create(email='test@test', password='test')
        self.job = Jobs.create(user_id=self.user.id, filename='test.jar')

    def tearDown(self):
        Jobs.remove_all()
        Users.remove_all()

    def test_find(self):
        job = Jobs.find(self.job.id)
        self.assertEqual('test.jar', job.filename)

    def test_user_jobs(self):
        jobs = Jobs.query(user_id=self.user.id)
        self.assertEqual(1, len(jobs))
        self.assertEqual('test.jar', jobs[0].filename)

    def test_finish_job(self):
        self.job.update(stdout='stdout', stderr='stderr')
        self.assertEqual(self.job.stdout, 'stdout')
        self.assertEqual(self.job.stderr, 'stderr')

    def test_start_job(self):
        self.job.update(status=Jobs.RUNNING)
        self.assertEqual(Jobs.RUNNING, self.job.status)

    def test_status_finished(self):
        self.job.update(stdout='stdout', stderr='stderr', status=Jobs.FINISHED)
        self.assertEqual(self.job.status, Jobs.FINISHED)

    def test_remove(self):
        count = Jobs.count()
        j = Jobs.create(user_id=self.user.id, filename='foobar')
        self.assertEqual(count + 1, Jobs.count())
        j.remove()
        self.assertEqual(count, Jobs.count())

if __name__ == '__main__':
    unittest.main()


text:
using namespace routing;
using namespace routing::turns;

UNIT_TEST(RussiaMoscowSevTushinoParkPreferingBicycleWay)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(55.87445, 37.43711), {0., 0.},
      MercatorBounds::FromLatLon(55.87203, 37.44274), 460.0);
}

UNIT_TEST(RussiaMoscowNahimovskyLongRoute)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(55.66151, 37.63320), {0., 0.},
      MercatorBounds::FromLatLon(55.67695, 37.56220), 7570.0);
}

UNIT_TEST(RussiaDomodedovoSteps)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(55.44020, 37.77409), {0., 0.},
      MercatorBounds::FromLatLon(55.43972, 37.77254), 123.0);
}

UNIT_TEST(SwedenStockholmCyclewayPriority)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(59.33151, 18.09347), {0., 0.},
      MercatorBounds::FromLatLon(59.33052, 18.09391), 113.0);
}

UNIT_TEST(NetherlandsAmsterdamBicycleNo)
{
  TRouteResult const routeResult = integration::CalculateRoute(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(52.32716, 5.05932),
      {0.0, 0.0}, MercatorBounds::FromLatLon(52.32587, 5.06121));

  IRouter::ResultCode const result = routeResult.second;
  TEST_EQUAL(result, IRouter::RouteNotFound, ());
}

UNIT_TEST(NetherlandsAmsterdamBicycleYes)
{
  TRouteResult const routeResult = integration::CalculateRoute(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(52.32872, 5.07527),
      {0.0, 0.0}, MercatorBounds::FromLatLon(52.33853, 5.08941));

  Route const & route = *routeResult.first;
  IRouter::ResultCode const result = routeResult.second;
  TEST_EQUAL(result, IRouter::NoError, ());
  TEST_EQUAL(route.GetTotalTimeSec(), 356, ());
}

UNIT_TEST(NetherlandsAmsterdamSingelStOnewayBicycleNo)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(52.3785, 4.89407), {0., 0.},
      MercatorBounds::FromLatLon(52.37462, 4.88983), 519.0);
}

UNIT_TEST(RussiaMoscowKashirskoe16ToCapLongRoute)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(55.66230, 37.63214), {0., 0.},
      MercatorBounds::FromLatLon(55.68895, 37.70286), 7057.0);
}

UNIT_TEST(RussiaKerchStraitFerryRoute)
{
  integration::CalculateRouteAndTestRouteLength(
      integration::GetBicycleComponents(), MercatorBounds::FromLatLon(45.4167, 36.7658), {0.0, 0.0},
      MercatorBounds::FromLatLon(45.3653, 36.6161), 18000.0);
}


text:
events
----

This plugin scans blog posts for an events.
It also generates an ``.ical`` calendar file.

Dependencies
------------

This plugin depends on the ``icalendar`` package, which can be installed
using APT or RPM or, if you are unlucky, via pip::

    pip install icalendar

Usage
-----

Add the following to pelicanconf.py::
    PLUGIN_EVENTS = {
        'ics_fname': 'calendar.ics',
    }

Create articles and usual and add the "event-start" metadata to turn them into
events. The event start is independent of the article "date".
"event-start" is in "YYYY-MM-DD hh:mm" format.
Also add "event-end", in the same format, or "event-duration" as a number
followed by a dimension:

w: weeks
d: days
h: hours
m: minutes
s: seconds

You can also specify an optional "location"

Example in ReST format::

    :event-start: 2015-01-21 10:30
    :event-duration: 2h
    :location: somewhere

To generate an sorted event list in a dedicated page copy the events_list.html
template under the templates directory in your theme, then create a page:

content/pages/events_list.rst::

 Events list
 ###########
 :slug: events-list
 :summary:
 :template: events_list


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var findIncludes = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof findIncludes, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method to synchronously find packages containing TypeScript declarations', function test( t ) {
	t.strictEqual( typeof findIncludes.sync, 'function', 'has sync method' );
	t.end();
});


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Windows Virtual Shields for Arduino: C:/Users/jgord/Documents/ms-iot/virtual-shields-arduino/VirtualShield/Text.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Windows Virtual Shields for Arduino

Main Page

Namespaces

Classes

Files

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

File List

File Members

ms-iot

virtual-shields-arduino

VirtualShield

Classes |
Variables

Text.h File Reference

#include "Sensor.h"

Go to the source code of this file.

Classes

class  	Text

Variables

const PROGMEM char 	Y [] = "Y"

const PROGMEM char 	CLEAR [] = "CLEAR"

const PROGMEM char 	RGBAKEY [] = "ARGB"

const PROGMEM char 	PID [] = "Pid"

Variable Documentation

          const PROGMEM char CLEAR[] = "CLEAR"

          const PROGMEM char PID[] = "Pid"

          const PROGMEM char RGBAKEY[] = "ARGB"

          const PROGMEM char Y[] = "Y"

<address class="footer">
Generated on Wed Apr 29 2015 17:37:05 for Windows Virtual Shields for Arduino by

 1.8.9.1
</address>


text:
Sacred Texts
Sagas and Legends
English Folklore
Index
Previous
Next

FORTUNE-TELLING, CHARMS, ETC.

 IN relation to this subject,
and confirming an opinion already expressed in the existence still of a
belief in magic and charms, I print the following communication from a
lady of considerable literary ability -

"Every country, it may be safely inferred, has its own
individual, perhaps characteristic, Charm-record; and inquiry into it
would more than probably recompense the labour, by the light it would let
in on the still but little investigated philosophy of the human mind, and
the growth of popular superstitions. The portion of our country best known
to the writer of these remarks is Cornwall, remarkable for the picturesque
wild-ness of its scenery, and not less so for its numerous superstitions.
The Rev. Charles Kingsley, in his 'Yeast,' has availed himself, with his
usual tact and power, of one of the most striking of these, having
reference to the cruel treatment of the Jews, who were sold as slaves to
work in the mines; the evil treatment they experienced being avenged on
modem miners, by the terrors the souls of the departed Hebrews inflicted,
in returning to the scene of their former compulsory toil, and echoing the
sounds of the workmen now labouring in flesh and blood. But this is a
digression from the main object of this article--viz., the belief in
charms. Several years ago, while residing at Falmouth, I remember to have
heard of a man in humble life, named Thomas Martin, whose abode was said
to be at a village in the neighbourhood of Redruth, and who accomplished
wonderful cures of children subject to fits, or personally injured by any
deformity, by his power of charming. This man also practised soothsaying
to a considerable extent, and revealed, with unquestionable accuracy,
where articles mysteriously abstracted were concealed. If a cow suddenly
lost her milk, whether witchcraft had exerted its malignant influence on
the non-producing animal or no, such a personage could not but exercise an
important power over the rustic population of the neighbourhood. But
belief in the mysterious intelligence of Martin was by no means confined
to the peasant class. .k highly-respected and even ladylike person told
the writer, with all the gravity becoming such a communication, that she
had once made an appointment with Thomas Martin to meet him at a certain
stile, for the purpose of receiving from him the prediction of her future
lot,--in other words, having her fortune told; and hastening thither at
the time appointed, was horrified to find the stile occupied by a large
black snake. As Martin did not make his appearance, she inferred that he
had assumed the serpent form, and not being disposed to hold any
intercourse with a being of such questionable exterior, she hastened away,
determined never more to risk the attainment of the knowledge she coveted
through a probably diabolic channel.

"This anecdote is given as veritable experience of the
belief which may prevail in a mind fairly intelligent, and generally
rational in conducting the ordinary business of life.

"Martin's reputation was disputed by no one, and that
it continued unimpaired to the close of his life reflects no
inconsiderable credit on the shrewdness and sagacity of his mind and his
power of guessing.

"In the town where the writer has been residing for the
last four months, there is a female, advanced in years and of good
character, who, according to the report of many persons,--one a relative
of her own,--is peculiarly endowed with the power of charming away the
disease called the 'kennel,' an affection of the eye which causes extreme
pain. A young lady's father was one evening suffering severe pain in the
right eye, and after trying various remedies without effect (the agony
having greatly increased), in her despair she sought an occasion to leave
the house, and hastened at once to the abode of the charmer. She told her
errand to the woman, who said that many had come to her for the purpose of
ridiculing her, and she did not like to say anything about charming,-- she
did not wish to be laughed at. On this the young lady assured her that her
object in true faith was to obtain relief for her suffering father, and by
no means to indulge the spirit of ridicule. On this representation she was
satisfied, and desired to know the kind of kennel which affected
the gentleman's eye. This information the daughter was unable to give her,
being unacquainted with their peculiarities; 'because,' said the charmer,
'there are nine kinds of kennels,' intimating at the same time that a
different charm might be said or applied to each,-- so that, to avoid
omitting any, she must say the charms for all, in order that the one
especially affecting the diseased eye should be certainly included in the
charm. She went up-stairs, and remained about half an hour. On her return
she addressed the young lady, and told her she might go home, where she
would learn whether the eye had been relieved. She took no money for her
incantation. Any little present might be offered at a subsequent visit,
but no direct payment was ever requested, and indeed would have been
declined. The amazement and pleasure of the anxious daughter, on her
arrival at home, will be imagined, on learning from her father that the
intense pain in the eye had ceased during her absence, though he had not
been made acquainted with her errand. The influence of the faith of
another, in this case, on the relief of the afflicted person, has no
verisimilitude save with that of the father of the demoniac in the gospel,
or the removal of the son's fever in consequence of the faith of the
father. I have no reason whatever to question the truth of this story,
which was confirmed by the wife of the gentleman thus relieved.

"A still more curious instance of the effect of charm,
though quite of another character, was related to me by the same party.
The gentleman referred to being much afflicted with cramp, his wife was
earnestly advised, by a country woman to whom she mentioned the
circumstance, to request her husband to place his slippers, with the toes
turned upward, at the foot of the bed. Half smiling at the wise counsel,
yet perhaps not altogether incredulous, he followed the good woman's
advice, and to his great comfort found himself unaffected by his dreaded
enemy throughout the night. His faith being thus established in the
anti-cramp influence of upturned slippers, he took care to place them, or
to have them placed, in the prescribed attitude on several successive
nights. One night, however, he was again seized with some appalling
twinges, and bethinking himself of the cause, suddenly recollected that in
hastening into bed he had not observed the important rule; instantly he
had the slippers restored to their proper position, and, to his
astonishment and delight, the pain ceased, and visited him no more. After
this experience of the wonderful effects that followed so simple a
specific, it may be easily imagined that he did not again risk the return
of the cramp from neglecting it. Such phenomena seem beyond the power of
explanation on any known medical principles. If any one more than usually
versed in the subtle power exercised on the body by the mind, can throw
light on the slipper cure of the cramp, he will deserve much at the hands
of physiological and mental science." S. E. M.

Next: The Zennor Charmers


text:
author: robmyers
comments: true
date: 2015-01-09 00:33:42+00:00
layout: page
slug: artbots
title: Artbots
permalink: /artbots/
wordpress_id: 2703
---

![ds](/assets/2013/12/ds-300x225.png)

**[draw-something](/draw-something/), 2004-, Common Lisp code, later JavaScript code.**

A generative drawing program inspired by Harold Cohen's [AARON](http://www.aaronshome.com/aaron/), based on simple models of line drawing, figure creation, and colour choice.

![paintr image 804](/assets/2013/12/804-300x234.png)
Original image by [jessjamesjake](http://farm4.static.flickr.com/3545/5844177462_7cda7b7b20.jpg).

**[Paintr](/paintr/), 2005/2013, PHP code (later Lisp code) reimplemented in node.js .**

A model of of almost precisely how artistic inspiration doesn't work.

![artist](/assets/2013/12/pollock.png)![critic](/assets/2013/12/greenberg.jpeg)![collector](/assets/2013/12/guggenheim.jpeg)

**The Cybernetic Artworld, 2009/2015, Common Lisp code, later Python code, now node.js code.**

A micro-artworld that is a simple and almost entirely incorrect model of the real one.

![random aesthetics microbloggers](/assets/2013/12/random-aesthetics-microbloggers.png)

**[Random Aesthetics](/random_aesthetics/), 2009/2014, Common Lisp code, then Python code, now JavaScript code.**

Microblog bots that place aesthetics in the social graph as peers.


text:
function WriteSegment(segfilename, faultname, fault_lon1, fault_lat1, fault_lon2, fault_lat2, ...
                               fault_ldep, fault_ldep_sig, fault_ldep_tog, fault_dip, fault_dip_sig, fault_dip_tog, ...
                               fault_ssrate, fault_ssrate_sig, fault_ssrate_tog, fault_dsrate, fault_dsrate_sig, fault_dsrate_tog, ...
                               fault_tsrate, fault_tsrate_sig, fault_tsrate_tog, fault_bdep, fault_bdep_sig, fault_bdep_tog, ...
			       fault_lres, fault_lres_ov, fault_lres_other, ...
			       fault_other1, fault_other2, fault_other3, ...
			       fault_other4, fault_other5, fault_other6, ...
			       fault_other7, fault_other8, fault_other9, ...
			       fault_other10, fault_other11, fault_other12)
% This script writes a *.segment file with the slip rates
% passed and fault geometry.
%
% Arguments:
%   segfilename       : name of file to write to.  We can't use
%                       basefilename.block because that already
%                       exists and is useful.
%   faultname         : a matrix of the fault name characters
%   fault_lon1        : longitude of fault endpoint one
%   fault_lat1        : latitude of fault endpoint one
%   fault_lon2        : longitude of fault endpoint two
%   fault_lat2        : latitude of fault endpoint two
%   fault_ldep        : fault locking depth
%   fault_ldep_sig    : fault locking depth sigma
%   fault_ldep_tog    : fault locking depth toggle
%   fault_dip         : fault dip
%   fault_dip_sig     : fault dip sigma
%   fault_dip_tog     : fault dip toggle
%   fault_ssrate      : fault strike slip rate
%   fault_ssrate_sig  : fault strike slip rate sigma
%   fault_ssrate_tog  : fault strike slip rate toggle
%   fault_dsrate      : fault dip slip rate
%   fault_dsrate_sig  : fault dip slip rate sigma
%   fault_dsrate_tog  : fault dip slip rate toggle
%   fault_tsrate      : fault tensile slip rate
%   fault_tsrate_sig  : fault tensile slip rate sigma
%   fault_tsrate_tog  : fault tensile slip rate toggle
%   fault_bdep        : fault locking depth
%   fault_bdep_sig    : fault locking depth sigma
%   fault_bdep_tog    : fault locking depth toggle

% Open file stream
filestream                          = fopen(segfilename, 'w');

% Write header
fprintf(filestream, 'Name\n');
fprintf(filestream, 'st_long  st_lat   end_long  end_lat\n');
fprintf(filestream, 'lock_dep ld_sig   ld_toggle\n');
fprintf(filestream, 'dip      dip_sig  dip_toggle\n');
fprintf(filestream, 'ss_rate  ss_sig   ss_tog\n');
fprintf(filestream, 'ds_rate  ds_sig   ds_tog\n');
fprintf(filestream, 'ts_rate  ts_sig   ts_tog\n');
fprintf(filestream, 'bur_dep  bd_sig   bd_tog\n');
fprintf(filestream, 'fres     fres_ov  fres_other\n');
fprintf(filestream, 'other1   other2   other3\n');
fprintf(filestream, 'other4   other5   other6\n');
fprintf(filestream, 'other7   other8   other9\n');
fprintf(filestream, 'other10  other11  other12\n');

% Loop over blocks and write to file
for cnt = 1 : numel(fault_lon1)
   fprintf(filestream, '%s\n', faultname(cnt, :));
   fprintf(filestream, '%3.3f   %3.3f   %3.3f  %3.3f\n', fault_lon1(cnt), fault_lat1(cnt), fault_lon2(cnt), fault_lat2(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_ldep(cnt), fault_ldep_sig(cnt), fault_ldep_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_dip(cnt), fault_dip_sig(cnt), fault_dip_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_ssrate(cnt), fault_ssrate_sig(cnt), fault_ssrate_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_dsrate(cnt), fault_dsrate_sig(cnt), fault_dsrate_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_tsrate(cnt), fault_tsrate_sig(cnt), fault_tsrate_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_bdep(cnt), fault_bdep_sig(cnt), fault_bdep_tog(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_lres(cnt), fault_lres_ov(cnt), fault_lres_other(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_other1(cnt), fault_other2(cnt), fault_other3(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_other4(cnt), fault_other5(cnt), fault_other6(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_other7(cnt), fault_other8(cnt), fault_other9(cnt));
   fprintf(filestream, '%3.1f   %3.1f  %3.1f\n', fault_other10(cnt), fault_other11(cnt), fault_other12(cnt));
end
fclose(filestream);


text:
package gldapo.search;

public interface SearchControlProvider
{
    public Integer getCountLimit();
    public Boolean getDerefLinkFlag();
    public String getSearchScope();
    public Integer getTimeLimit();
    public Integer getPageSize();
}


text:
using namespace std;

void elimDups(vector<string>& words);
void biggies(vector<string>& words, vector<string>::size_type sz);

int main() {
  vector<string> words;
  vector<string>::size_type sz;
  cout << "Enter some words:" << endl;
  for(string temp; cin >> temp; words.push_back(temp));

  biggies(words, 6);

  return 0;
}

void biggies(vector<string>& words, vector<string>::size_type sz) {
  elimDups(words);

  auto count = count_if(words.begin(), words.end(),
		    [sz](const string& s) {return s.size() >= sz;});
  cout << count << ' ' << (count > 1 ? "words" : "word")
       << " of length " << sz << " or longer" << endl;
  cout << endl;
}

// copied from 10.11.cpp
void elimDups(vector<string>& words) {
  // sort words alphabetically
  sort(words.begin(), words.end());
  // reorder words
  auto mark = unique(words.begin(), words.end());
  // erase non-unique words after the mark
  words.erase(mark, words.end());
}


text:
mkdir -p build_osx && cd build_osx
cmake -GXcode ..
cd ..

cmake --build build_osx --config Release
cp -r build_osx/Release/slua.bundle ../Assets/Plugins/


text:
var staticFiles = function () {
    //config static files
    'use strict';
    var serveStatic = require('serve-static');
    var serve = serveStatic(this.routerDir);
    this.app.use(serve);
};

module.exports = staticFiles;


text:
{% extends "site_base.html" %}
{% load i18n links_tags mks_tags common_visual_elements %}{% load static from staticfiles %}
{% block extratitle %}{{ object.which }}{% endblock %}
{% block description %}{{ object.which }} - {{ object.what }}{% endblock %}
{% block nav-laws %}class="active"{% endblock %}

 {% block breadcrumbs %}

{{ objct.which }} /

{{ object.what }}

 {% endblock %}

{% block divcontent %}

עוד

                        ..

                        {% if in_days %}

{{in_days}}

{% trans "Days" %}

                        {% endif %}

{{in_hours}}

{% trans "Hours" %}

{{in_minutes}}

..

{% trans "Minutes" %}

                          ..

{{object.what}}

{{object.which}}

                {{ object.when }}

                {% include "auxiliary/_watch.html" with watched_id=object.id watched_type="bill"%}
                {% trans "share" %}

                  {% include "mks/member_photos.html" with members=creators %}

{{object.why}}

{% comment %}

{% trans "Agendas" %}

                {% for agenda in agendas %}

{{ agenda }}

                            <span class="span1 numeric text-{% if agenda.score < 0 %}error{%else%}success{% endif %}">
                                {{agenda.score|floatformat:"0"}}%

                            {% bar agenda.score -100 100%}

                {% endfor %}

{% trans "Statistics" %}

                        {% trans "Number of votes" %}
                        {{ object.voting_statistics.votes_count }}

                        {% trans "Average votes per MK" %}
                        {{ object.voting_statistics.votes_per_seat|floatformat:2 }}

                        {% trans "Factional discipline" %}
                        {{ object.voting_statistics.discipline|floatformat:2 }}%

                        {% if object.is_coalition %}
                            {% trans "Coalition discipline" %}
                        {% else %}
                            {% trans "Opposition discipline" %}
                        {% endif %}

                        {{ object.voting_statistics.coalition_discipline|floatformat:2 }}%

{% endcomment %}
{% endblock %}