<commit_before>/* @flow */

import type {Manifest, FetchedMetadata} from '../../types.js';
import type PackageRequest from '../../package-request.js';
import TarballFetcher from '../../fetchers/tarball-fetcher.js';
import ExoticResolver from './exotic-resolver.js';
import Git from './git-resolver.js';
import * as versionUtil from '../../util/version.js';
import * as crypto from '../../util/crypto.js';
import * as fs from '../../util/fs.js';

const invariant = require('invariant');

export default class TarballResolver extends ExoticResolver {
  constructor(request: PackageRequest, fragment: string) {
    super(request, fragment);

    const {hash, url} = versionUtil.explodeHashedUrl(fragment);
    this.hash = hash;
    this.url = url;
  }

  url: string;
  hash: string;

  static isVersion(pattern: string): boolean {
    // we can sometimes match git urls which we don't want
    if (Git.isVersion(pattern)) {
      return false;
    }

    // full http url
    if (pattern.startsWith('http://') || pattern.startsWith('https://')) {
      return true;
    }

    // local file reference - ignore patterns with names
    if (pattern.indexOf('@') < 0) {
      if (pattern.endsWith('.tgz') || pattern.endsWith('tar.gz')) {
        return true;
      }
    }

    return false;
  }

  async resolve(): Promise<Manifest> {
    const shrunk = this.request.getLocked('tarball');
    if (shrunk) {
      return shrunk;
    }

    const {url} = this;
    let {hash, registry} = this;
    let pkgJson;

    // generate temp directory
    const dest = this.config.getTemp(crypto.hash(url));

    if (await this.config.isValidModuleDest(dest)) {
      // load from local cache
      ({package: pkgJson, hash, registry} = await this.config.readPackageMetadata(dest));
    } else {
      // delete if invalid
      await fs.unlink(dest);

      const fetcher = new TarballFetcher(dest, {
        type: 'tarball',
        reference: url,
        registry,
        hash,
      }, this.config, false);

      // fetch file and get it's hash
      const fetched: FetchedMetadata = await fetcher.fetch();
      pkgJson = fetched.package;
      hash = fetched.hash;

      registry = pkgJson._registry;
      invariant(registry, 'expected registry');
    }

    // use the commit/tarball hash as the uid as we can't rely on the version as it's not
    // in the registry
    pkgJson._uid = hash;

    // set remote so it can be "fetched"
    pkgJson._remote = {
      type: 'copy',
      resolved: `${url}#${hash}`,
      hash,
      registry,
      reference: dest,
    };

    return pkgJson;
  }
}
<commit_msg>Fix file protocol referencing local tarball - fixes #639 (#1591)<commit_after>/* @flow */

import type {Manifest, FetchedMetadata} from '../../types.js';
import type PackageRequest from '../../package-request.js';
import TarballFetcher from '../../fetchers/tarball-fetcher.js';
import ExoticResolver from './exotic-resolver.js';
import Git from './git-resolver.js';
import {removeSuffix} from '../../util/misc.js';
import * as versionUtil from '../../util/version.js';
import * as crypto from '../../util/crypto.js';
import * as fs from '../../util/fs.js';

const invariant = require('invariant');

export default class TarballResolver extends ExoticResolver {
  constructor(request: PackageRequest, fragment: string) {
    super(request, fragment);

    const {hash, url} = versionUtil.explodeHashedUrl(fragment);
    this.hash = hash;
    this.url = url;
  }

  url: string;
  hash: string;

  static isVersion(pattern: string): boolean {
    // we can sometimes match git urls which we don't want
    if (Git.isVersion(pattern)) {
      return false;
    }

    // full http url
    if (pattern.startsWith('http://') || pattern.startsWith('https://')) {
      return true;
    }

    // local file reference - ignore patterns with names
    if (pattern.indexOf('@') < 0) {
      if (pattern.endsWith('.tgz') || pattern.endsWith('tar.gz')) {
        return true;
      }
    }

    return false;
  }

  async resolve(): Promise<Manifest> {
    const shrunk = this.request.getLocked('tarball');
    if (shrunk) {
      return shrunk;
    }

    const url = removeSuffix(this.url, 'file:');
    let {hash, registry} = this;
    let pkgJson;

    // generate temp directory
    const dest = this.config.getTemp(crypto.hash(url));

    if (await this.config.isValidModuleDest(dest)) {
      // load from local cache
      ({package: pkgJson, hash, registry} = await this.config.readPackageMetadata(dest));
    } else {
      // delete if invalid
      await fs.unlink(dest);

      const fetcher = new TarballFetcher(dest, {
        type: 'tarball',
        reference: url,
        registry,
        hash,
      }, this.config, false);

      // fetch file and get it's hash
      const fetched: FetchedMetadata = await fetcher.fetch();
      pkgJson = fetched.package;
      hash = fetched.hash;

      registry = pkgJson._registry;
      invariant(registry, 'expected registry');
    }

    // use the commit/tarball hash as the uid as we can't rely on the version as it's not
    // in the registry
    pkgJson._uid = hash;

    // set remote so it can be "fetched"
    pkgJson._remote = {
      type: 'copy',
      resolved: `${url}#${hash}`,
      hash,
      registry,
      reference: dest,
    };

    return pkgJson;
  }
}
<|endoftext|>


<commit_before>'use strict';

var Q = require('q'),
util = require('../util'),
constants = require('../constants');

function getNicManager(ec2) {
  var describe = Q.nfbind(ec2.describeNetworkInterfaces.bind(ec2), {
    DryRun: false,
    Filters: constants.AWS_FILTER_CTAG
  });

  function create(subnetId, sgIds, pid, pr) {
    var params = {
      SubnetId: subnetId,
      Groups: sgIds,
      Description: 'Created by clusternator for ' + pid + ', PR: ' + pr
    };

    return Q.nfbind(ec2.createNetworkInterface.bind(ec2), params)().
    then(function (result) {
      return util.awsTagEc2(ec2, result.NetworkInterface.NetworkInterfaceId, [
        {
          Key: constants.CLUSTERNATOR_TAG,
          Value: 'true'
        },
        {
          Key: constants.PROJECT_TAG,
          Value: pid
        },
        {
          Key: constants.PR_TAG,
          Value: pr
        }
      ]) .then(function () {
        return result;
      });
    });
  }

  function destroy(nicId, pid, pr) {
    return describe().then(function (list) {
      var nic, isValidPid = false, isValidPr = false;
      list.NetworkInterfaces.forEach(function (g){
        if (g.NetworkInterfaceId === nicId) {
          nic = g;
        }
      });

      nic.TagSet.forEach(function (tag) {
        if (tag.Key === constants.PROJECT_TAG) {
          if (tag.Value === pid) {
            isValidPid = true;
          }
        }
        if (tag.Key === constants.PR_TAG) {
          if (tag.Value === pr) {
            isValidPr = true;
          }
        }
      });

      if (!(isValidPid && isValidPr)) {
        throw new Error('No Clusternator Tagged NetworkInterfaces Available ' +
        'For Destruction With GroupId: ' + nicId + ' ProjectId: ' + pid +
        ' and PR: ' + pr);
      }

      return Q.nfbind(ec2.deleteNetworkInterface.bind(ec2), {
        NetworkInterfaceId: nicId
      })();
    });
  }

  return {
    describe: describe,
    create: create,
    destroy: destroy
  };
}

module.exports = getNicManager;
<commit_msg>NIC's can no longer create if there are existing pr/projectId tags<commit_after>'use strict';

var Q = require('q'),
util = require('../util'),
constants = require('../constants');

function getNicManager(ec2) {
  var describe = Q.nfbind(ec2.describeNetworkInterfaces.bind(ec2), {
    DryRun: false,
    Filters: constants.AWS_FILTER_CTAG
  });

  function rejectIfExists(pid, pr) {
    return describe().then(function (list) {
      list.NetworkInterfaces.forEach(function (nicDesc) {
        var isProject = false, isPR = false;
        nicDesc.TagSet.forEach(function (tag) {
          if ((tag.Key === constants.PROJECT_TAG) && (tag.Value === pid)) {
            isProject = true;
          }
          if ((tag.Key === constants.PR_TAG) && (tag.Value === pr)) {
            isPR = true;
          }
        });
        if (isProject && isPR) {
          throw new Error('NetworkInterface Exists For Project: ' + pid +
          ' PR: ' + pr);
        }
      });
    });
  }

function createNic(subnetId, sgIds, pid, pr) {
    var params = {
      SubnetId: subnetId,
      Groups: sgIds,
      Description: 'Created by clusternator for ' + pid + ', PR: ' + pr
    };

    return Q.nfbind(ec2.createNetworkInterface.bind(ec2), params)().
    then(function (result) {
      return util.awsTagEc2(ec2, result.NetworkInterface.NetworkInterfaceId, [
        {
          Key: constants.CLUSTERNATOR_TAG,
          Value: 'true'
        },
        {
          Key: constants.PROJECT_TAG,
          Value: pid
        },
        {
          Key: constants.PR_TAG,
          Value: pr
        }
      ]) .then(function () {
        return result;
      });
    });
}

  function create(subnetId, sgIds, pid, pr) {
    return rejectIfExists(pid, pr).then(function () {
        return createNic(subnetId, sgIds, pid, pr);
    });
  }

  function destroy(nicId, pid, pr) {
    return describe().then(function (list) {
      var nic, isValidPid = false, isValidPr = false;
      list.NetworkInterfaces.forEach(function (g){
        if (g.NetworkInterfaceId === nicId) {
          nic = g;
        }
      });

      nic.TagSet.forEach(function (tag) {
        if (tag.Key === constants.PROJECT_TAG) {
          if (tag.Value === pid) {
            isValidPid = true;
          }
        }
        if (tag.Key === constants.PR_TAG) {
          if (tag.Value === pr) {
            isValidPr = true;
          }
        }
      });

      if (!(isValidPid && isValidPr)) {
        throw new Error('No Clusternator Tagged NetworkInterfaces Available ' +
        'For Destruction With GroupId: ' + nicId + ' ProjectId: ' + pid +
        ' and PR: ' + pr);
      }

      return Q.nfbind(ec2.deleteNetworkInterface.bind(ec2), {
        NetworkInterfaceId: nicId
      })();
    });
  }

  return {
    describe: describe,
    create: create,
    destroy: destroy
  };
}

module.exports = getNicManager;
<|endoftext|>


<commit_before>/*!
 * Copyright (c) 2013 Ben Olson (https://github.com/bseth99/backbone-fiber)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Dependancies: Backbone, jQuery, Underscore, RequireJS
 *
 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD.
        define(['jquery', 'underscore', 'backbone', 'base'], factory);
    } else {
        // Browser globals
        root.Backbone.Fiber = factory(root.$, root._, root.Backbone, Base);
    }
}(this, function ($, _, Backbone, Base) {

   // Replace and enhance
   Backbone.View.extend = Base.extend;
   Backbone.View.mix = Base.mix;

   var Fiber,
       _view_defs = {},
       _view_inst = {},
       _view_loading = {};

   // Store the old jQuery.cleanData
   var oldClean = $.cleanData;

   // Overwrites cleanData which is called by jQuery on manipulation methods
   $.cleanData = function( elems ) {
      for ( var i = 0, elem;
      (elem = elems[i]) !== undefined; i++ ) {
         // Trigger the destroyed event
         $(elem).triggerHandler( 'destroyed' );
      }
      // Call the old jQuery.cleanData
      oldClean(elems);
   };

   Backbone.Fiber = Fiber = {

      /**
      *  Set the base path to find views relative to the RequireJS
      *  basePath.  View module IDs will be relative to this location.
      *  For example, if the basePath is scripts and views are in the
      *  scripts/views folder then a view file named shell.js will be
      *  identified by RequireJS as views/shell but Fiber will index it
      *  as shell.
      */
      viewPath: 'views/',

      /**
      *  Given an element from the DOM, find the closest element (either
      *  it or one of its parents) that has a view instance bound and return
      *  that instance.
      */
      getViewFromEl: function( el ) {
         var $el = $( el ),
             dataCid = $el.attr( 'data-cid' ) || $el.closest( '[data-cid]' ).attr( 'data-cid' );

         if ( dataCid ) return _view_inst[dataCid];
      },

      /**
      *  Lookup a view instance from its cid
      */
      getViewFromCid: function( cid ) {

         return _view_inst[cid];
      },

      /**
      *  Get the DOM element a view instance is bound to based on its
      *  cid
      */
      getElFromCid: function( cid ) {

         if ( _view_inst[cid] )
            return _view_inst[cid].$el;
      },

      /**
      *  Return the promise for a view definition.  Only valid while loading,
      *  otherwise, returns nothing.
      */
      getPromise: function( view ) {

         if ( _view_loading[view] )
            return _view_loading[view];
      }
   }

   /**
   *  Wraps RequireJS and loads view modules with their template files.  Modifies the
   *  prototype with the view module name and the pre-compiled template function.
   */
   function load( target ) {

      var dfd = $.Deferred();

      if ( _view_defs[target] ) {

         dfd.resolve( _view_defs[target] );

      } else {

         _view_loading[target] = dfd;
         require( [Fiber.viewPath + target, 'text!' + Fiber.viewPath + target + '.html'], function( view, template ) {

            view.prototype.instanceOf = target;
            view.prototype.template = _.template( template );
            _view_defs[target] = view;

            delete _view_loading[target];
            dfd.resolve( view );
         });
      }

      return dfd.promise();
   }

   /**
   *  View factory method.  Creates instance, sets up the parent/child
   *  relationship and renders the view.
   */
   function create( view, $el, options ) {

      var inst = new view(_.extend( options, { el: $el[0] } )),
          parent;

      $el.attr( 'data-cid', inst.cid );
      _view_inst[inst.cid] = inst;

      parent = $el.parents( '[data-view]' ).first();
      if ( parent.length > 0 ) {
         parent = parent.attr( 'data-cid' );
         _view_inst[parent].addChild( inst );
         inst.setParent( _view_inst[parent] );
      }

      inst.render();
      return inst;
   }

   /**
   *  Finds the binding on the element, loads the view definition, and
   *  then creates the instance of the view with the passed in options and
   *  attaches it to the DOM element.
   */
   function connect( el, opts ) {

      var options = opts || {},
          $el = (el instanceof $ ? el : $(el)),
          dataView = $el.attr( 'data-view' );

      if ( dataView ) {

         load( dataView ).done( function( view ) {

            create( view, $el, options );

         });
      }

   }

   /* Optional if no top level catch-all, "application" view is defined */
   Fiber.start = function() { connect( document.body ); };

   Backbone.View.mix([{

      /**
      *  load() will attach the compiled template to the
      *  prototype of the loaded view.  No need to do anything
      *  with this.
      */
      template: null,

      /**
      *  The top-most view will be null, all others will have the
      *  cid of the nearest parent view instance.  create() sets this
      *  value when generating the instance.
      */
      parent: null,

      /**
      *  As each child is added, the parent view gets a reference to the
      *  cid.  create() also manages adding this while View.removeChild
      *  removes the reference when a child view removes itself.
      */
      children: null,

      /**
      *  Flag to determine if its the first render pass.  Changes the
      *  behavior of render() and how it responds to empty data sets.
      */
      renderedOnce: false,

      /**
      *  Enables dynamically adding new DOM elements that will be
      *  bound to a child view instance.
      *
      *  target [ String | DOMElement | jQuery Object ]
      *
      *     A string value represents the name of the view to bind to the DOM node.
      *     factory() is used to generate the new element with the data-view attribute
      *     set.  Pass a DOMElement or jQuery object to control how the node is inserted
      *     into the DOM (or override factory() if its the primary way to add nodes)
      *
      *  options [ Object ]
      *
      *     This hash will be passed to the view constructor and can be anything you'd
      *     normally pass to a view when creating an instance.  This can include the model
      *     or collection object.
      *
      *  returns a promise which will be resolved in the scope of the parent view and
      *  pass the new view instance as the argument to the callback function.
      */
      connect: function( target, options ) {
         var $el, wait,
             self = this,
             dfd = $.Deferred();

         if ( typeof( target ) == 'string' )
            $el = this.factory( target );
         else
            $el = (target instanceof $ ? target : $(target));

         connect( $el, options );

         if ( ( wait = Fiber.getPromise( $el.attr('data-view') ) ) )
            wait.done(function( view ) {
               dfd.resolveWith( self, [Fiber.getViewFromEl( $el )] );
            });
         else
            dfd.resolveWith( this, [Fiber.getViewFromEl( $el )] );

         return dfd.promise();
      },

      /**
      *  Helper function to ensure multiple views have finished loading before running
      *  certain logic.  Calls the callback function once eveything has loaded in the
      *  children parameter.
      *
      *  children [ Array ]
      *
      *     Array of view names that should be children of the calling view instance.
      *
      *  callback [ Function ]
      *
      *     Function to call once all the view have loaded.
      */
      waitFor: function( children, callback ) {

         var self = this,
             sync = _.compact( _.map( children, function( v ) { return Fiber.getPromise( v ); } ) );

         $.when.apply( this, sync ).done( function() {
            callback.apply( self, arguments );
         });
      },

      /**
      *  Used by connect() to create DOM nodes.  Override to generate something
      *  different.
      */
      factory: function( vmid ) {
         return $('<div>').attr( 'data-view', vmid ).appendTo( this.$el );
      },

      /**
      *  Redefined the standard initialize view function.  Don't override this
      *  unless you know what you're doing.  Override setup() instead to add your
      *  own custom creation logic.
      */
      initialize: function( options ) {

         this.$el.on( 'destroyed', _.bind( this.remove, this ) );

         this.children = [];
         this.setup( options );
         this.bindData();

         this.trigger('created');
      },

      /**
      *  Internal function to unbind any listenTos on the data
      *  Any custom setData functions need to call this or write their own version.
      */
      unbindData: function() {
         this.stopListening( this.data() );
      },

      /**
      *  Internal function to examine the events hash and
      *  look for *.data keys.  Will bind the function identified in the value
      *  to the whatever is defined by the data() function (as long as it has a
      *  trigger function)..
      */
      bindData: function() {

         var self = this,
             dm = this.data();

         if ( dm.trigger ) {

            _.each( this.events, function( method, event ) {

               var idx;

               if ( (idx = event.indexOf( '.data' ) ) > -1 ) {

                  method = $.isFunction( method ) ? method : self[method];
                  self.listenTo( dm, event.slice( 0, idx ), method );
               }
            });
         }
      },

      /**
      *  Override this as necessary
      */
      setup: $.noop,

      /**
      *  Leave this alone.  Use before/after render callbacks instead or bind to the
      *  rendering/rendered events.  Upon rendering, the function will look for children
      *  with a data-view attribute and start connecting views recursively.
      */
      render: function() {

         var data, isa;

         if ( this.beforeRender() !== false ) {

            this.trigger('rendering');

            if ( this.template && typeof(this.template) == 'function' ) {
               data = this.dataSerialized();
               isa = data && $.isArray( data );

               if ( this.renderedOnce && data || ( !this.renderedOnce && ( ( isa && data.length > 0 ) || !isa ) ) )
               {
                  this.$el.empty().html( this.template( data ) );
                  this.renderedOnce = true;

                  this.$el.find( '[data-view]' ).each( function() {
                     connect( this );
                  });
               }
            }

            this.afterRender();
            this.trigger('rendered');
         }

      },

      /**
      *  Add logic that should happen before rendering.  Return false to cancel rendering
      */
      beforeRender: $.noop,

      /**
      *  Add post rendering logic here.
      */
      afterRender: $.noop,

      /**
      *  Default logic to decide what defines the data object used by the
      *  view.  Override if you need something special.
      */
      data: function() {

         if ( this.model )
            return this.model;
         else if ( this.collection )
            return this.collection;
         else
            return {};
      },

      /**
      *  Default logic to set data on the view.  Takes a hash with either model or collection set to the new data value.
      *  Any custom functions must ensure they properly bind and unbind data.  The trigger is optional.
      *  Returns itself for chaining.
      */

      setData: function( data ) {

         var dm = null;

         this.unbindData();

         if ( data.model )
            this.model = dm = data.model;
         else if ( data.collection )
            this.collection = dm = data.collection;

         this.bindData();

         if (dm && dm.trigger) {dm.trigger('ready', dm);}
         return this;
      },

      /**
      *  Ensures the data is a object
      */
      dataSerialized: function() {

         var dm = this.data();

         if ( dm.toJSON )
            return dm.toJSON();
         else
            return dm;

      },

      /**
      *  Overwrites the normal view remove function.  Tells the parent
      *  to clean up which will call this again to finish cleaning up.
      */
      remove: function() {

         if ( this.parent ) {

           _view_inst[this.parent].removeChild( this );

         } else {

            this.destroy();
            this.trigger('removed');
            this.stopListening();
            this.$el.off( 'destroyed' );
            this.$el.remove();

            delete _view_inst[this.cid];
         }

         this._superStop();
      },

      /**
      *   Put any custom cleanup logic here
      */
      destroy: $.noop,

      trigger: function( topic, data ) {

         //console.log( this.instanceOf, arguments );
         if ( !this.$el.trigger( topic+'.'+this.instanceOf, { view: this, data: data || {} } ) )
            this._superStop();
      },

      /**
      *  Used internally to set the parent attribute on the view instance.
      */
      setParent: function( view ) {
         this.parent = null;
         if ( view ) this.parent = view.cid;
      },

      /**
      *  Used internally to add a child view instance
      */
      addChild: function( view ) {

         if ( !_.contains( view.cid, this.children ) ) {
            this.children.push( view.cid );
         }
      },

      /**
      *  Used internally to remove a child and ensure its cleanup.
      */
      removeChild: function( view ) {

         var idx = _.indexOf( this.children, view.cid );

         if ( idx > -1 ) {
            this.children.splice( idx, 1 );
            view.setParent( null );
            view.remove();
         }
      },

      /**
      *  Helper to retrive an array of all the child view instances
      */
      allChildren: function() {

         return (
            _.map( this.children, function( cid ) {
               return Fiber.getViewFromCid( cid );
            })
         );
      },

      /**
      *  Helper to return an array of child view instance of a given name
      */
      findChildren: function( type ) {

         return (
            _.compact(
               _.map( this.children, function( cid ) {
                  var view;
                  if ( (view = Fiber.getViewFromCid( this.children[i] )) && view.instanceOf == type )
                     return view;
               })
            )
         );

      },

      /**
      *  Helper to return view instance based on the view name or jQuery element.
      */
      findChild: function( target ) {

         var view = null;

         if ( target instanceof $ ) {

            view = Fiber.getViewFromEl( target );

         } else if ( typeof( target ) == 'string' ) {

            view = Fiber.getViewFromCid( target );
            if ( !view ) {

               for ( var i=0;i<this.children.length;i++ ) {

                  var test;
                  if ( (test = Fiber.getViewFromCid( this.children[i] )) && test.instanceOf == target )
                     view = test;

               }
            }
         }

         return view;
      }

   }]);

   return Fiber;

}));
<commit_msg>Change behavior of trigger to not append the view instance name<commit_after>/*!
 * Copyright (c) 2013 Ben Olson (https://github.com/bseth99/backbone-fiber)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Dependancies: Backbone, jQuery, Underscore, RequireJS
 *
 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD.
        define(['jquery', 'underscore', 'backbone', 'base'], factory);
    } else {
        // Browser globals
        root.Backbone.Fiber = factory(root.$, root._, root.Backbone, Base);
    }
}(this, function ($, _, Backbone, Base) {

   // Replace and enhance
   Backbone.View.extend = Base.extend;
   Backbone.View.mix = Base.mix;

   var Fiber,
       _view_defs = {},
       _view_inst = {},
       _view_loading = {};

   // Store the old jQuery.cleanData
   var oldClean = $.cleanData;

   // Overwrites cleanData which is called by jQuery on manipulation methods
   $.cleanData = function( elems ) {
      for ( var i = 0, elem;
      (elem = elems[i]) !== undefined; i++ ) {
         // Trigger the destroyed event
         $(elem).triggerHandler( 'destroyed' );
      }
      // Call the old jQuery.cleanData
      oldClean(elems);
   };

   Backbone.Fiber = Fiber = {

      /**
      *  Set the base path to find views relative to the RequireJS
      *  basePath.  View module IDs will be relative to this location.
      *  For example, if the basePath is scripts and views are in the
      *  scripts/views folder then a view file named shell.js will be
      *  identified by RequireJS as views/shell but Fiber will index it
      *  as shell.
      */
      viewPath: 'views/',

      /**
      *  Given an element from the DOM, find the closest element (either
      *  it or one of its parents) that has a view instance bound and return
      *  that instance.
      */
      getViewFromEl: function( el ) {
         var $el = $( el ),
             dataCid = $el.attr( 'data-cid' ) || $el.closest( '[data-cid]' ).attr( 'data-cid' );

         if ( dataCid ) return _view_inst[dataCid];
      },

      /**
      *  Lookup a view instance from its cid
      */
      getViewFromCid: function( cid ) {

         return _view_inst[cid];
      },

      /**
      *  Get the DOM element a view instance is bound to based on its
      *  cid
      */
      getElFromCid: function( cid ) {

         if ( _view_inst[cid] )
            return _view_inst[cid].$el;
      },

      /**
      *  Return the promise for a view definition.  Only valid while loading,
      *  otherwise, returns nothing.
      */
      getPromise: function( view ) {

         if ( _view_loading[view] )
            return _view_loading[view];
      }
   }

   /**
   *  Wraps RequireJS and loads view modules with their template files.  Modifies the
   *  prototype with the view module name and the pre-compiled template function.
   */
   function load( target ) {

      var dfd = $.Deferred();

      if ( _view_defs[target] ) {

         dfd.resolve( _view_defs[target] );

      } else {

         _view_loading[target] = dfd;
         require( [Fiber.viewPath + target, 'text!' + Fiber.viewPath + target + '.html'], function( view, template ) {

            view.prototype.instanceOf = target;
            view.prototype.template = _.template( template );
            _view_defs[target] = view;

            delete _view_loading[target];
            dfd.resolve( view );
         });
      }

      return dfd.promise();
   }

   /**
   *  View factory method.  Creates instance, sets up the parent/child
   *  relationship and renders the view.
   */
   function create( view, $el, options ) {

      var inst = new view(_.extend( options, { el: $el[0] } )),
          parent;

      $el.attr( 'data-cid', inst.cid );
      _view_inst[inst.cid] = inst;

      parent = $el.parents( '[data-view]' ).first();
      if ( parent.length > 0 ) {
         parent = parent.attr( 'data-cid' );
         _view_inst[parent].addChild( inst );
         inst.setParent( _view_inst[parent] );
      }

      inst.render();
      return inst;
   }

   /**
   *  Finds the binding on the element, loads the view definition, and
   *  then creates the instance of the view with the passed in options and
   *  attaches it to the DOM element.
   */
   function connect( el, opts ) {

      var options = opts || {},
          $el = (el instanceof $ ? el : $(el)),
          dataView = $el.attr( 'data-view' );

      if ( dataView ) {

         load( dataView ).done( function( view ) {

            create( view, $el, options );

         });
      }

   }

   /* Optional if no top level catch-all, "application" view is defined */
   Fiber.start = function() { connect( document.body ); };

   Backbone.View.mix([{

      /**
      *  load() will attach the compiled template to the
      *  prototype of the loaded view.  No need to do anything
      *  with this.
      */
      template: null,

      /**
      *  The top-most view will be null, all others will have the
      *  cid of the nearest parent view instance.  create() sets this
      *  value when generating the instance.
      */
      parent: null,

      /**
      *  As each child is added, the parent view gets a reference to the
      *  cid.  create() also manages adding this while View.removeChild
      *  removes the reference when a child view removes itself.
      */
      children: null,

      /**
      *  Flag to determine if its the first render pass.  Changes the
      *  behavior of render() and how it responds to empty data sets.
      */
      renderedOnce: false,

      /**
      *  Enables dynamically adding new DOM elements that will be
      *  bound to a child view instance.
      *
      *  target [ String | DOMElement | jQuery Object ]
      *
      *     A string value represents the name of the view to bind to the DOM node.
      *     factory() is used to generate the new element with the data-view attribute
      *     set.  Pass a DOMElement or jQuery object to control how the node is inserted
      *     into the DOM (or override factory() if its the primary way to add nodes)
      *
      *  options [ Object ]
      *
      *     This hash will be passed to the view constructor and can be anything you'd
      *     normally pass to a view when creating an instance.  This can include the model
      *     or collection object.
      *
      *  returns a promise which will be resolved in the scope of the parent view and
      *  pass the new view instance as the argument to the callback function.
      */
      connect: function( target, options ) {
         var $el, wait,
             self = this,
             dfd = $.Deferred();

         if ( typeof( target ) == 'string' )
            $el = this.factory( target );
         else
            $el = (target instanceof $ ? target : $(target));

         connect( $el, options );

         if ( ( wait = Fiber.getPromise( $el.attr('data-view') ) ) )
            wait.done(function( view ) {
               dfd.resolveWith( self, [Fiber.getViewFromEl( $el )] );
            });
         else
            dfd.resolveWith( this, [Fiber.getViewFromEl( $el )] );

         return dfd.promise();
      },

      /**
      *  Helper function to ensure multiple views have finished loading before running
      *  certain logic.  Calls the callback function once eveything has loaded in the
      *  children parameter.
      *
      *  children [ Array ]
      *
      *     Array of view names that should be children of the calling view instance.
      *
      *  callback [ Function ]
      *
      *     Function to call once all the view have loaded.
      */
      waitFor: function( children, callback ) {

         var self = this,
             sync = _.compact( _.map( children, function( v ) { return Fiber.getPromise( v ); } ) );

         $.when.apply( this, sync ).done( function() {
            callback.apply( self, arguments );
         });
      },

      /**
      *  Used by connect() to create DOM nodes.  Override to generate something
      *  different.
      */
      factory: function( vmid ) {
         return $('<div>').attr( 'data-view', vmid ).appendTo( this.$el );
      },

      /**
      *  Redefined the standard initialize view function.  Don't override this
      *  unless you know what you're doing.  Override setup() instead to add your
      *  own custom creation logic.
      */
      initialize: function( options ) {

         this.$el.on( 'destroyed', _.bind( this.remove, this ) );

         this.children = [];
         this.setup( options );
         this.bindData();

         this.trigger('created');
      },

      /**
      *  Internal function to unbind any listenTos on the data
      *  Any custom setData functions need to call this or write their own version.
      */
      unbindData: function() {
         this.stopListening( this.data() );
      },

      /**
      *  Internal function to examine the events hash and
      *  look for *.data keys.  Will bind the function identified in the value
      *  to the whatever is defined by the data() function (as long as it has a
      *  trigger function)..
      */
      bindData: function() {

         var self = this,
             dm = this.data();

         if ( dm.trigger ) {

            _.each( this.events, function( method, event ) {

               var idx;

               if ( (idx = event.indexOf( '.data' ) ) > -1 ) {

                  method = $.isFunction( method ) ? method : self[method];
                  self.listenTo( dm, event.slice( 0, idx ), method );
               }
            });
         }
      },

      /**
      *  Override this as necessary
      */
      setup: $.noop,

      /**
      *  Leave this alone.  Use before/after render callbacks instead or bind to the
      *  rendering/rendered events.  Upon rendering, the function will look for children
      *  with a data-view attribute and start connecting views recursively.
      */
      render: function() {

         var data, isa;

         if ( this.beforeRender() !== false ) {

            this.trigger('rendering');

            if ( this.template && typeof(this.template) == 'function' ) {
               data = this.dataSerialized();
               isa = data && $.isArray( data );

               if ( this.renderedOnce && data || ( !this.renderedOnce && ( ( isa && data.length > 0 ) || !isa ) ) )
               {
                  this.$el.empty().html( this.template( data ) );
                  this.renderedOnce = true;

                  this.$el.find( '[data-view]' ).each( function() {
                     connect( this );
                  });
               }
            }

            this.afterRender();
            this.trigger('rendered');
         }

      },

      /**
      *  Add logic that should happen before rendering.  Return false to cancel rendering
      */
      beforeRender: $.noop,

      /**
      *  Add post rendering logic here.
      */
      afterRender: $.noop,

      /**
      *  Default logic to decide what defines the data object used by the
      *  view.  Override if you need something special.
      */
      data: function() {

         if ( this.model )
            return this.model;
         else if ( this.collection )
            return this.collection;
         else
            return {};
      },

      /**
      *  Default logic to set data on the view.  Takes a hash with either model or collection set to the new data value.
      *  Any custom functions must ensure they properly bind and unbind data.  The trigger is optional.
      *  Returns itself for chaining.
      */

      setData: function( data ) {

         var dm = null;

         this.unbindData();

         if ( data.model )
            this.model = dm = data.model;
         else if ( data.collection )
            this.collection = dm = data.collection;

         this.bindData();

         if (dm && dm.trigger) {dm.trigger('ready', dm);}
         return this;
      },

      /**
      *  Ensures the data is a object
      */
      dataSerialized: function() {

         var dm = this.data();

         if ( dm.toJSON )
            return dm.toJSON();
         else
            return dm;

      },

      /**
      *  Overwrites the normal view remove function.  Tells the parent
      *  to clean up which will call this again to finish cleaning up.
      */
      remove: function() {

         if ( this.parent ) {

           _view_inst[this.parent].removeChild( this );

         } else {

            this.destroy();
            this.trigger('removed');
            this.stopListening();
            this.$el.off( 'destroyed' );
            this.$el.remove();

            delete _view_inst[this.cid];
         }

         this._superStop();
      },

      /**
      *   Put any custom cleanup logic here
      */
      destroy: $.noop,

      trigger: function( topic, data ) {

         //console.log( this.instanceOf, arguments ); //+'.'+this.instanceOf
         if ( !this.$el.trigger( topic, { view: this, data: data || {} } ) )
            this._superStop();
      },

      /**
      *  Used internally to set the parent attribute on the view instance.
      */
      setParent: function( view ) {
         this.parent = null;
         if ( view ) this.parent = view.cid;
      },

      /**
      *  Used internally to add a child view instance
      */
      addChild: function( view ) {

         if ( !_.contains( view.cid, this.children ) ) {
            this.children.push( view.cid );
         }
      },

      /**
      *  Used internally to remove a child and ensure its cleanup.
      */
      removeChild: function( view ) {

         var idx = _.indexOf( this.children, view.cid );

         if ( idx > -1 ) {
            this.children.splice( idx, 1 );
            view.setParent( null );
            view.remove();
         }
      },

      /**
      *  Helper to retrive an array of all the child view instances
      */
      allChildren: function() {

         return (
            _.map( this.children, function( cid ) {
               return Fiber.getViewFromCid( cid );
            })
         );
      },

      /**
      *  Helper to return an array of child view instance of a given name
      */
      findChildren: function( type ) {

         return (
            _.compact(
               _.map( this.children, function( cid ) {
                  var view;
                  if ( (view = Fiber.getViewFromCid( this.children[i] )) && view.instanceOf == type )
                     return view;
               })
            )
         );

      },

      /**
      *  Helper to return view instance based on the view name or jQuery element.
      */
      findChild: function( target ) {

         var view = null;

         if ( target instanceof $ ) {

            view = Fiber.getViewFromEl( target );

         } else if ( typeof( target ) == 'string' ) {

            view = Fiber.getViewFromCid( target );
            if ( !view ) {

               for ( var i=0;i<this.children.length;i++ ) {

                  var test;
                  if ( (test = Fiber.getViewFromCid( this.children[i] )) && test.instanceOf == target )
                     view = test;

               }
            }
         }

         return view;
      }

   }]);

   return Fiber;

}));
<|endoftext|>


<commit_before>"use strict";

var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);

module.exports = function(app) {
  var queue = app.get('queue');
  var store = app.get('keyValueStore');

  for(var job in jobs) {
    if(job !== "index") { // index is not a job, we don't want to register it
      debug('wait for job type', job);
      // create new job processor
      queue.process(job, app.get('concurrency'), jobs[job](app));
    }
  }

  queue.on('job complete', function(id, result) {
    var afToken;
    async.waterfall([
      function getJob(cb) {
        kue.Job.get(id, cb);
      },
      function setCursor(job, cb) {
        afToken = job.anyfetchToken;

        store.hset('cursor', afToken, result, cb);
      },
      function setLastUpdate(status, cb) {
        store.hset('lastUpdate', afToken, Date.now().toString(), cb);
      },
      function unlockUpdate(status, cb) {
        store.hdel('status', afToken, cb);
      }
    ], function throwErrs(err) {
      if(err) {
        throw err;
      }
    });
  });
};
<commit_msg>Using delete<commit_after>"use strict";

var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);

module.exports = function(app) {
  var queue = app.get('queue');
  var store = app.get('keyValueStore');

  delete jobs.index;
  for(var job in jobs) {
    debug('wait for job type', job);
    // create new job processor
    queue.process(job, app.get('concurrency'), jobs[job](app));
  }

  queue.on('job complete', function(id, result) {
    var afToken;
    async.waterfall([
      function getJob(cb) {
        kue.Job.get(id, cb);
      },
      function setCursor(job, cb) {
        afToken = job.anyfetchToken;

        store.hset('cursor', afToken, result, cb);
      },
      function setLastUpdate(status, cb) {
        store.hset('lastUpdate', afToken, Date.now().toString(), cb);
      },
      function unlockUpdate(status, cb) {
        store.hdel('status', afToken, cb);
      }
    ], function throwErrs(err) {
      if(err) {
        throw err;
      }
    });
  });
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

var path = require('path');

var hmrTransform = 'react-transform-hmr/lib/index.js';
var transformPath = require.resolve(hmrTransform);

module.exports = function(options, filename) {
  var transform = filename
      ? './' + path.relative(path.dirname(filename), transformPath) // packager can't handle absolute paths
      : hmrTransform;

  // Fix the module path to use '/' on Windows.
  if (path.sep === '\\') {
    transform = transform.replace(/\\/g, '/');
  }

  return {
    plugins: [
      [
        require('metro-babel7-plugin-react-transform').default,
        {
          transforms: [{
            transform: transform,
            imports: ['react'],
            locals: ['module'],
          }]
        },
      ]
    ]
  };
};
<commit_msg>Export the hmr plugin directly<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

var path = require('path');

var hmrTransform = 'react-transform-hmr/lib/index.js';
var transformPath = require.resolve(hmrTransform);

module.exports = function(options, filename) {
  var transform = filename
      ? './' + path.relative(path.dirname(filename), transformPath) // packager can't handle absolute paths
      : hmrTransform;

  // Fix the module path to use '/' on Windows.
  if (path.sep === '\\') {
    transform = transform.replace(/\\/g, '/');
  }

  return {
    plugins: [
      [
        require('metro-babel7-plugin-react-transform'),
        {
          transforms: [{
            transform: transform,
            imports: ['react'],
            locals: ['module'],
          }]
        },
      ]
    ]
  };
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var _ = require('lodash');
var ressources = require('../../app/js/constants/ressources');

var familleDef = {
    parisien: Boolean,
    proprietaire_proche_famille: Boolean,
    rsa_isolement_recent: Boolean,
};

var foyerFiscalDef = {
    rfr: Object,
};

var ressourcesDefs = _.concat(
    ressources.ressourceTypes,
    ressources.categoriesRnc,
    ressources.patrimoineTypes)
.reduce(function(result, ressource) {
    result[ressource.id] = Object;
    return result;
}, {});

var specificSituationValues = [
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var statutMaritalValues = [
    'Marié',
    'Pacsé',
    'Célibataire',
];

var individuDef = Object.assign({
    _id: false,
    id: String,
    ass_precondition_remplie: Boolean,
    boursier: Boolean,
    date_arret_de_travail: Date,
    dateDernierContratTravail: Date,
    date_naissance: Date,
    echelon_bourse: Number,
    enfant_a_charge: Object,
    enfant_place: Boolean,
    enceinte: Boolean,
    firstName: String,
    garde_alternee: Boolean,
    gir: { type: String, default: 'Non défini' },
    habite_chez_parents: Boolean,
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant'] },
    scolarite: { type: String, enum: ['Inconnue', 'Collège', 'Lycée'] },
    specificSituations: [{ type: String, enum: specificSituationValues }],
    statut_marital: { type: String, enum: statutMaritalValues },
    taux_incapacite: Number,
    tns_auto_entrepreneur_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    tns_autres_revenus_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    tns_micro_entreprise_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
}, ressourcesDefs);

var statutOccupationLogementValues = [
    'Accédant à la propriété',
    'Propriétaire (non accédant) du logement',
    'Locataire ou sous-locataire d‘un logement loué vide non-HLM',
    'Locataire ou sous-locataire d‘un logement loué meublé ou d‘une chambre d‘hôtel',
    'Logé gratuitement par des parents, des amis ou l‘employeur',
    'Locataire d‘un foyer (résidence universitaire, maison de retraite, foyer de jeune travailleur, résidence sociale...)',
    'Sans domicile stable',
];

var menageDef = {
    charges_locatives: Number,
    code_postal: String,
    coloc: Boolean,
    depcom: String,
    logement_chambre: Boolean,
    loyer: Number,
    nom_commune: String,
    participation_frais: Boolean,
    statut_occupation_logement: { type: String, enum: statutOccupationLogementValues },
};

var situationSchema = {
    dateDeValeur: Date,
    famille: familleDef,
    foyer_fiscal: foyerFiscalDef,
    individus: [individuDef],
    menage: menageDef,
    modifiedFrom: String,
    version: { type: Number, default: 0 },
};

mongoose.model('Situation', new mongoose.Schema(situationSchema, { minimize: false }));
mongoose.model('LegacySituation', new mongoose.Schema({}, { strict: false }));

<commit_msg>Increment situation default version number to 1<commit_after>var mongoose = require('mongoose');
var _ = require('lodash');
var ressources = require('../../app/js/constants/ressources');

var familleDef = {
    parisien: Boolean,
    proprietaire_proche_famille: Boolean,
    rsa_isolement_recent: Boolean,
};

var foyerFiscalDef = {
    rfr: Object,
};

var ressourcesDefs = _.concat(
    ressources.ressourceTypes,
    ressources.categoriesRnc,
    ressources.patrimoineTypes)
.reduce(function(result, ressource) {
    result[ressource.id] = Object;
    return result;
}, {});

var specificSituationValues = [
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var statutMaritalValues = [
    'Marié',
    'Pacsé',
    'Célibataire',
];

var individuDef = Object.assign({
    _id: false,
    id: String,
    ass_precondition_remplie: Boolean,
    boursier: Boolean,
    date_arret_de_travail: Date,
    dateDernierContratTravail: Date,
    date_naissance: Date,
    echelon_bourse: Number,
    enfant_a_charge: Object,
    enfant_place: Boolean,
    enceinte: Boolean,
    firstName: String,
    garde_alternee: Boolean,
    gir: { type: String, default: 'Non défini' },
    habite_chez_parents: Boolean,
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant'] },
    scolarite: { type: String, enum: ['Inconnue', 'Collège', 'Lycée'] },
    specificSituations: [{ type: String, enum: specificSituationValues }],
    statut_marital: { type: String, enum: statutMaritalValues },
    taux_incapacite: Number,
    tns_auto_entrepreneur_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    tns_autres_revenus_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    tns_micro_entreprise_type_activite: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
}, ressourcesDefs);

var statutOccupationLogementValues = [
    'Accédant à la propriété',
    'Propriétaire (non accédant) du logement',
    'Locataire ou sous-locataire d‘un logement loué vide non-HLM',
    'Locataire ou sous-locataire d‘un logement loué meublé ou d‘une chambre d‘hôtel',
    'Logé gratuitement par des parents, des amis ou l‘employeur',
    'Locataire d‘un foyer (résidence universitaire, maison de retraite, foyer de jeune travailleur, résidence sociale...)',
    'Sans domicile stable',
];

var menageDef = {
    charges_locatives: Number,
    code_postal: String,
    coloc: Boolean,
    depcom: String,
    logement_chambre: Boolean,
    loyer: Number,
    nom_commune: String,
    participation_frais: Boolean,
    statut_occupation_logement: { type: String, enum: statutOccupationLogementValues },
};

var situationSchema = {
    dateDeValeur: Date,
    famille: familleDef,
    foyer_fiscal: foyerFiscalDef,
    individus: [individuDef],
    menage: menageDef,
    modifiedFrom: String,
    version: { type: Number, default: 1 },
};

mongoose.model('Situation', new mongoose.Schema(situationSchema, { minimize: false }));
mongoose.model('LegacySituation', new mongoose.Schema({}, { strict: false }));

<|endoftext|>


<commit_before>/**
 * jQuery CSV Plugin
 * version: 0.1 (2012-04-20)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * This plugin was originally designed to assist in parsing CSV files loaded
 * from client-side javascript. It's influenced by jQuery.json and the original
 * core RegEx comes directly from the following answer posted by a
 * StackOverflow.com user named Ridgerunner.
 * Source:
 * - http://stackoverflow.com/q/8493195/290340
 *
 * For legal purposes I'll include the "NO WARRANTY EXPRESSED OR IMPLIED.
 * USE AT YOUR OWN RISK.". Which, in 'layman's terms' means, by using this
 * library you are accepting responsability if it breaks your code.
 *
 * Legal jargon aside, I will do my best to provide a useful and stable core
 * that can effectively be built on.
 *
 * Copyrighted 2012 by Evan Plaice.
 */

(function( $ ) {
	/**
	 * jQuery.CSV2Array(csvString)
	 * Converts a CSV string to a javascript array.
	 *
	 * @param {String} csv The string containing the raw CSV data.
   * @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
   * @param {Character} [delimiter] An override for the delimiter character. Defaults to a quote(').
   * @param {String} [line-break] An override for the line-break style. Defaults to CRLF('\r\n')
   * @param {Boolean} [headers] Indicates whether the CSV file contains headers. If true the first line is parsed separately.
   *
   * This method deals with multi-line CSV. The breakdown is simple. The first
   * dimension of the array represents the line (or entry/row) while the second
   * dimension contains the values (or values/columns).
   *
   * Example - Print the 4th value in the 10th row:
   *   data = $.CSV2Array(csv); // cache the output to avoid unnecessary processing
   *   console.log(data[9][3]);
	 */
  $.CSV2Array = function(csv) {
    //var separator = ','; // not used yet
    //var delimiter = '\''; // not used yet
    var line-break = '\r\n'; // not used yet
    var headers = false; // not used yet

    // check for line breaks
    lines = csv.split('\n');
    output = []
    for(var i in lines) {
      line = $.CSVEntry2Array(lines[i]);
      output.push(line);
    }
    return output;
  };

  // TODO: Document this method.
  $.CSVEntry2Array = function(csv) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(csv)) return null;
    var a = [];                     // Initialize array to receive values.
    csv.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {
            // Remove backslash from \' in single quoted values.
            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });
    // Handle special case of empty last value.
    if (/,\s*$/.test(csv)) a.push('');
    return a;
  };

})( jQuery );<commit_msg>Added parameter support<commit_after>/**
 * jQuery CSV Plugin
 * version: 0.1 (2012-04-20)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * This plugin was originally designed to assist in parsing CSV files loaded
 * from client-side javascript. It's influenced by jQuery.json and the original
 * core RegEx comes directly from the following answer posted by a
 * StackOverflow.com user named Ridgerunner.
 * Source:
 * - http://stackoverflow.com/q/8493195/290340
 *
 * For legal purposes I'll include the "NO WARRANTY EXPRESSED OR IMPLIED.
 * USE AT YOUR OWN RISK.". Which, in 'layman's terms' means, by using this
 * library you are accepting responsability if it breaks your code.
 *
 * Legal jargon aside, I will do my best to provide a useful and stable core
 * that can effectively be built on.
 *
 * Copyrighted 2012 by Evan Plaice.
 */

(function( $ ) {
  /**
   * jQuery.CSV2Array(csvString)
   * Converts a CSV string to a javascript array.
   *
   * @param {String} csv The string containing the raw CSV data.
   * @param {Array} [meta] The dictionary where the meta variables (ie separator, delimiter, line-break, and headers) are defined. Defaults to an empty object ({}).
   * @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
   * @param {Character} [delimiter] An override for the delimiter character. Defaults to a quote(').
   * @param {String} [lineBreak] An override for the line-break style. Defaults to CRLF('\r\n').
   * @param {Boolean} [headers] Indicates whether the CSV file contains headers. If true the first line is parsed separately.
   * @param {Integer} [skip] The number of lines that need to be skipped before the parser starts. Defaults to 0.
   *
   * This method deals with multi-line CSV. The breakdown is simple. The first
   * dimension of the array represents the line (or entry/row) while the second
   * dimension contains the values (or values/columns).
   *
   * Example - Print the 4th value in the 10th row:
   *   data = $.CSV2Array(csv); // cache the output to avoid unnecessary processing
   *   console.log(data[9][3]);
	 */
  $.CSV2Array = function(csv, meta) {
    var meta = typeof meta !== 'undefined' ? meta : {};
    var separator = 'separator' in meta ? args.separator : ',';
    var delimiter = 'delimiter' in meta ? args.delimiter : "'";
    var lineEnding = 'line-ending' in meta ? args.line-ending : '\r\n';
    var skip = 'skip' in meta ? args.headers : 0;

    // check for line breaks
    var lines = csv.split(lineEnding);
    var output = [];
    for(var i in lines) {
      if(line < skip) {
        continue;
      }
      var line = $.CSVEntry2Array(lines[i]);
      output.push(line);
    }
    return output;
  };

  // TODO: Implement this
  $.CSV2Dictionary = function(csv, meta) {
    var meta = typeof(meta) !== 'undefined' ? meta : {};
    //header-line // TODO: Implement this, marks the line that contains the header
    //data-line // TODO: Implement this, marks the line where the data starts
    return;
  };

  /**
   * jQuery.CSV2Array(csvString)
   * Converts a CSV string to a javascript array.
   *
   * @param {String} csv The string containing the raw CSV data.
   * @param {Array} [meta] The dictionary where the meta variables (ie separator, delimiter, line-break, and headers) are defined. Defaults to an empty object ({}).
   * @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
   * @param {Character} [delimiter] An override for the delimiter character. Defaults to a quote(').
   *
   * This method deals with simple CSV strings only. It's useful if you only
   * need to parse a single entry. If you need to parse more than one line,
   * use $.CSV2Array instead.
   */
  $.CSVEntry2Array = function(csv, meta) {
    var meta = typeof meta !== 'undefined' ? meta : {};
    var separator = 'separator' in meta ? args.separator : ',';
    var delimiter = 'delimiter' in meta ? args.delimiter : "'";

    var reValid = /^\s*(?:D[^D\\]*(?:\\[\S\s][^D\\]*)*D|[^SD\s\\]*(?:\s+[^SD\s\\]+)*)\s*(?:S\s*(?:D[^D\\]*(?:\\[\S\s][^D\\]*)*D|[^SD\s\\]*(?:\s+[^SD\s\\]+)*)\s*)*$/;
    reValid = RegExp(reValid.source.replace(/S/g, separator));
    reValid = RegExp(reValid.source.replace(/D/g, delimiter));

    var reValue = /(?!\s*$)\s*(?:D([^D\\]*(?:\\[\S\s][^D\\]*)*)D|([^SD\s\\]*(?:\s+[^SD\s\\]+)*))\s*(?:S|$)/g;
    reValue = RegExp(reValue.source.replace(/S/g, separator), 'g');
    reValue = RegExp(reValue.source.replace(/D/g, delimiter), 'g');

    // Return NULL if input string is not well formed CSV string.
    if (!reValid.test(csv)) { return null; }
    var a = [];

    // "Walk" the string using replace with callback.
    csv.replace(reValue, function(m0, m1, m2) {
            // Remove backslash from \' in single quoted values.
            if      (m1 !== undefined) { a.push(m1.replace(/\\'/g, "'")); }
            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2);
            return ''; // Return empty string.
        });

    // Handle special case of empty last value.
    if (/,\s*$/.test(csv)) { a.push(''); }
    return a;
  };

})( jQuery );<|endoftext|>


<commit_before>QUnit.module("Save/Resume Tests");
QUnit.test("Resume Version 3.x JSON", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 1, testLabelPrefix + "One axes calibration loaded");
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd3_xy.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4: Check Axes", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 6, testLabelPrefix + "6 axes calibrations loaded");
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4: Check Datasets", function(assert) {
    let checkDatasets = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getDatasetCount(), 6, testLabelPrefix + "6 datasets loaded");

        let expectedNames = ['xy data', 'bar data', 'polar data', 'ternary data', 'map data', 'image data'];
        let expectedAxesNames = ['xy axes', 'Bar', 'Polar', 'Ternary', 'Map', 'Image'];
        let expectedPointCounts = [144, 3, 3, 3, 0, 57];
        let datasets = plotData.getDatasets();
        for (let dsIdx = 0; dsIdx < datasets.length; dsIdx++) {
            let ds = datasets[dsIdx];
            let axes = plotData.getAxesForDataset(ds);
            assert.equal(ds.getCount(), expectedPointCounts[dsIdx], testLabelPrefix + "Number of points in dataset " + (dsIdx + 1));
            assert.equal(ds.name, expectedNames[dsIdx], testLabelPrefix + "Dataset name of dataset " + (dsIdx + 1));
            assert.equal(axes.name, expectedAxesNames[dsIdx], testLabelPrefix + "Dataset axes name of dataset " + (dsIdx + 1));
        }
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4.json").then(plotDataObjs => {
        checkDatasets(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkDatasets(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4.2 with masks", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 6, testLabelPrefix + "6 axes calibrations loaded");
    };
    let checkDatasets = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getDatasetCount(), 6, testLabelPrefix + "6 datasets loaded");

        let expectedNames = ['xy data', 'bar data', 'polar data', 'ternary data', 'map data', 'image data'];
        let expectedAxesNames = ['xy axes', 'Bar', 'Polar', 'Ternary', 'Map', 'Image'];
        let expectedPointCounts = [143, 3, 3, 3, 0, 57];
        let datasets = plotData.getDatasets();
        for (let dsIdx = 0; dsIdx < datasets.length; dsIdx++) {
            let ds = datasets[dsIdx];
            let axes = plotData.getAxesForDataset(ds);
            assert.equal(ds.getCount(), expectedPointCounts[dsIdx], testLabelPrefix + "Number of points in dataset " + (dsIdx + 1));
            assert.equal(ds.name, expectedNames[dsIdx], testLabelPrefix + "Dataset name of dataset " + (dsIdx + 1));
            assert.equal(axes.name, expectedAxesNames[dsIdx], testLabelPrefix + "Dataset axes name of dataset " + (dsIdx + 1));
        }

        // Check an autodetection object
        let autodetection1 = plotData.getAutoDetectionDataForDataset(datasets[0]);
        assert.equal(autodetection1.mask.size, 264662, testLabelPrefix + "Check mask size");
    };
    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4_2_with_masks.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        checkDatasets(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkDatasets(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});<commit_msg>Check two masks instead of one in the unit test<commit_after>QUnit.module("Save/Resume Tests");
QUnit.test("Resume Version 3.x JSON", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 1, testLabelPrefix + "One axes calibration loaded");
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd3_xy.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4: Check Axes", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 6, testLabelPrefix + "6 axes calibrations loaded");
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4: Check Datasets", function(assert) {
    let checkDatasets = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getDatasetCount(), 6, testLabelPrefix + "6 datasets loaded");

        let expectedNames = ['xy data', 'bar data', 'polar data', 'ternary data', 'map data', 'image data'];
        let expectedAxesNames = ['xy axes', 'Bar', 'Polar', 'Ternary', 'Map', 'Image'];
        let expectedPointCounts = [144, 3, 3, 3, 0, 57];
        let datasets = plotData.getDatasets();
        for (let dsIdx = 0; dsIdx < datasets.length; dsIdx++) {
            let ds = datasets[dsIdx];
            let axes = plotData.getAxesForDataset(ds);
            assert.equal(ds.getCount(), expectedPointCounts[dsIdx], testLabelPrefix + "Number of points in dataset " + (dsIdx + 1));
            assert.equal(ds.name, expectedNames[dsIdx], testLabelPrefix + "Dataset name of dataset " + (dsIdx + 1));
            assert.equal(axes.name, expectedAxesNames[dsIdx], testLabelPrefix + "Dataset axes name of dataset " + (dsIdx + 1));
        }
    };

    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4.json").then(plotDataObjs => {
        checkDatasets(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkDatasets(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});

QUnit.test("Resume Version 4.2 with masks", function(assert) {
    let checkAxes = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getAxesCount(), 6, testLabelPrefix + "6 axes calibrations loaded");
    };
    let checkDatasets = function(plotData, assert, testLabelPrefix) {
        assert.equal(plotData.getDatasetCount(), 6, testLabelPrefix + "6 datasets loaded");

        let expectedNames = ['xy data', 'bar data', 'polar data', 'ternary data', 'map data', 'image data'];
        let expectedAxesNames = ['xy axes', 'Bar', 'Polar', 'Ternary', 'Map', 'Image'];
        let expectedPointCounts = [143, 3, 3, 3, 0, 57];
        let datasets = plotData.getDatasets();
        for (let dsIdx = 0; dsIdx < datasets.length; dsIdx++) {
            let ds = datasets[dsIdx];
            let axes = plotData.getAxesForDataset(ds);
            assert.equal(ds.getCount(), expectedPointCounts[dsIdx], testLabelPrefix + "Number of points in dataset " + (dsIdx + 1));
            assert.equal(ds.name, expectedNames[dsIdx], testLabelPrefix + "Dataset name of dataset " + (dsIdx + 1));
            assert.equal(axes.name, expectedAxesNames[dsIdx], testLabelPrefix + "Dataset axes name of dataset " + (dsIdx + 1));
        }

        // Check an autodetection object
        let autodetection1 = plotData.getAutoDetectionDataForDataset(datasets[0]);
        assert.equal(autodetection1.mask.size, 264662, testLabelPrefix + "Check mask size for 1st dataset");
        let autodetection2 = plotData.getAutoDetectionDataForDataset(datasets[5]);
        assert.equal(autodetection2.mask.size, 14710, testLabelPrefix + "Check mask size for 6th dataset");

    };
    let done = assert.async();
    wpdtest.loadPlotData("files/wpd4_2_with_masks.json").then(plotDataObjs => {
        checkAxes(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkAxes(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        checkDatasets(plotDataObjs.plotData, assert, "Deserialize from JSON: ");
        checkDatasets(plotDataObjs.plotData2, assert, "Serialize then deserialize: ");
        done();
    });
});<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global'],
	function(jQuery) {
	"use strict";

	/**
	 * @class SelectList renderer.
	 *
	 * @static
	 */
	var SelectListRenderer = {};

	/**
	 * CSS class to be applied to the  root element of the SelectList.
	 *
	 * @readonly
	 * @const {string}
	 */
	SelectListRenderer.CSS_CLASS = "sapMSelectList";

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
	 * @param {sap.ui.core.Control} oSelectList An object representation of the control that should be rendered.
	 */
	SelectListRenderer.render = function(oRm, oList) {
		var CSS_CLASS = SelectListRenderer.CSS_CLASS;

		oRm.write("
");
		this.renderItems(oRm, oList);
		oRm.write("
");
	};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
	 * @param {sap.ui.core.Control} oList An object representation of the control that should be rendered.
	 */
	SelectListRenderer.renderItems = function(oRm, oList) {
		for (var i = 0, aItems = oList.getItems(); i < aItems.length; i++) {
			this.renderItem(oRm, oList, aItems[i]);
		}
	};

	/**
	 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
	 * @param {sap.ui.core.Control} oList An object representation of the control that should be rendered.
	 * @param {sap.ui.core.Control} oItem An object representation of the control that should be rendered.
	 */
	SelectListRenderer.renderItem = function(oRm, oList, oItem) {
		var bEnabled = oItem.getEnabled(),
			oSelectedItem = oList.getSelectedItem(),
			CSS_CLASS = SelectListRenderer.CSS_CLASS;

		if (oItem instanceof sap.ui.core.Element) {
			oRm.write("<li");
			oRm.writeElementData(oItem);

			if (oItem instanceof sap.ui.core.SeparatorItem) {
				oRm.addClass(CSS_CLASS + "SeparatorItem");
			} else {
				oRm.addClass(CSS_CLASS + "Item");

				if (!bEnabled) {
					oRm.addClass(CSS_CLASS + "ItemDisabled");
				}

				if (bEnabled && sap.ui.Device.system.desktop) {
					oRm.addClass(CSS_CLASS + "ItemHoverable");
				}

				if (oItem === oSelectedItem) {
					oRm.addClass(CSS_CLASS + "ItemSelected");
				}

				if (bEnabled) {
					oRm.writeAttribute("tabindex", "0");
				}
			}

			oRm.writeClasses();
			oRm.write(">");
			oRm.writeEscaped(oItem.getText());
			oRm.write("
");
		}
	};

	return SelectListRenderer;

}, /* bExport= */ true);
<commit_msg>[INTERNAL] sap.m.SelectListRenderer: initial commit<commit_after>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global'],
	function(jQuery) {
		"use strict";

		/**
		 * @class SelectList renderer.
		 *
		 * @static
		 */
		var SelectListRenderer = {};

		/**
		 * CSS class to be applied to the  root element of the SelectList.
		 *
		 * @readonly
		 * @const {string}
		 */
		SelectListRenderer.CSS_CLASS = "sapMSelectList";

		/**
		 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oSelectList An object representation of the control that should be rendered.
		 */
		SelectListRenderer.render = function(oRm, oList) {
			var CSS_CLASS = SelectListRenderer.CSS_CLASS;

			oRm.write("
");
			this.renderItems(oRm, oList);
			oRm.write("
");
		};

		/**
		 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oList An object representation of the control that should be rendered.
		 */
		SelectListRenderer.renderItems = function(oRm, oList) {
			for (var i = 0, aItems = oList.getItems(); i < aItems.length; i++) {
				this.renderItem(oRm, oList, aItems[i]);
			}
		};

		/**
		 * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
		 *
		 * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer.
		 * @param {sap.ui.core.Control} oList An object representation of the control that should be rendered.
		 * @param {sap.ui.core.Control} oItem An object representation of the control that should be rendered.
		 */
		SelectListRenderer.renderItem = function(oRm, oList, oItem) {
			var bEnabled = oItem.getEnabled(),
				oSelectedItem = oList.getSelectedItem(),
				CSS_CLASS = SelectListRenderer.CSS_CLASS;

			if (oItem instanceof sap.ui.core.Element) {
				oRm.write("<li");
				oRm.writeElementData(oItem);

				if (oItem instanceof sap.ui.core.SeparatorItem) {
					oRm.addClass(CSS_CLASS + "SeparatorItem");
				} else {
					oRm.addClass(CSS_CLASS + "Item");

					if (!bEnabled) {
						oRm.addClass(CSS_CLASS + "ItemDisabled");
					}

					if (bEnabled && sap.ui.Device.system.desktop) {
						oRm.addClass(CSS_CLASS + "ItemHoverable");
					}

					if (oItem === oSelectedItem) {
						oRm.addClass(CSS_CLASS + "ItemSelected");
					}

					if (bEnabled) {
						oRm.writeAttribute("tabindex", "0");
					}
				}

				oRm.writeClasses();
				oRm.write(">");
				oRm.writeEscaped(oItem.getText());
				oRm.write("
");
			}
		};

		return SelectListRenderer;

	}, /* bExport= */ true);<|endoftext|>


<commit_before>
/**
 * Initialisation
 ******************************************/

(function ($)
{

    var options = {
        selectors: {
            ajaxModal: '#ajax-modal'
        }
    };

    $(document).ready(function ()
    {
        $(document).initAdvancedElements();

        $.initQueryHash();

        $(options.selectors.ajaxModal).on("show.bs.modal", function (e) {
            var link = $(e.relatedTarget);
            $(this).load(link.attr("href"), function () {
                $(this).initAdvancedElements();
            });
        });
        $(options.selectors.ajaxModal).on("hidden.bs.modal", function (e) {
            $(this).html("");
        });

    });

    $.fn.initAdvancedElements = function () {

        var element = $(this);

        $(this).find('.input-float').inputNumberFormat({'decimal': 4, 'decimalAuto': 2});
        $(this).find('.input-integer').inputNumberFormat({'decimal': 0, 'decimalAuto': 0});

        $(this).find("select.select2").select2({
            allowClear: true
        });

        $(this).find(".select2autocomplete").each(function () {
            var urlAjax = $(this).data('ajax');
            var defaultValue = $(this).val();
            var defaultValueSplitted = defaultValue.split(',');
            var select2 = $(this);
            $(this).select2({
                onselected: function () {
                    console.log('fre');
                },
                initSelection: function (element, callback) {
                    if (defaultValue != '') {
                        callback({id: defaultValueSplitted[0], text: defaultValueSplitted[1]});
                        select2.val(defaultValueSplitted[0]);
                    }
                },
                placeholder: 'Entrer un nom',
                minimumInputLength: 3,
                formatInputTooShort: function (input, min) {
                    var n = min - input.length;
                    return  min + " caractère" + (n == 1 ? "" : "s") + " min";
                },
                formatNoMatches: function () {
                    return "Aucun résultat";
                },
                formatSearching: function () {
                    return "Recherche…";
                },
                allowClear: true,
                ajax: {
                    quietMillis: 150,
                    url: urlAjax,
                    dataType: 'json',
                    type: "GET",
                    data: function (term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function (data) {
                        var results = [];
                        $.each(data, function (index, item) {
                            results.push({
                                id: index,
                                text: item
                            });
                        });
                        return {
                            results: results
                        }

                    }}
            });
        });

        $(this).find(".select2SubmitOnChange").on("change", function (e) {
            if (e.val) {
                $(this).parents('form').submit();
            }
        });

        $(this).find('.select2permissifNoAjax').each(function() {
	    var element = $(this);
	    var id = $(this).attr('id');
	    $(this).select2({
                data: JSON.parse($(this).attr('data-choices')),
                multiple: false,
                createSearchChoice: function (term, data) {
                    if ($(data).filter(function () {
                        return this.text.localeCompare(term) === 0;
                    }).length === 0) {
                        return {id: term, text: term + ' (nouveau)'};
                    }
                }
            }).on("select2-close", function (e) {
		lastValue = $('#'+id).val();
                $(this).select2("val", lastValue);
                $(this).val(lastValue);
                $('#s2id_'+id).find('.select2-chosen').text(lastValue);
            })
        });

        $(this).find('.hamzastyle').each(function () {
            var select2 = $(this);
            select2.select2({
                multiple: true,
                data: function () {
                    var data = [];
                    element.find('.hamzastyle-item').each(function () {
                        data = data.concat(JSON.parse($(this).attr('data-words')));
                    });

                    var data = unique(data.sort());

                    dataFinal = [];
                    for (key in data) {
                        if (data[key] + "") {
                            dataFinal.push({id: (data[key] + ""), text: (data[key] + "")});
                        }
                    }

                    return {results: dataFinal};
                }
            })
        });

        $(this).find('.hamzastyle').on("change", function (e) {
            var select2Data = $(this).select2("data");
            var selectedWords = [];
            for (key in select2Data) {
                selectedWords.push(select2Data[key].text);
            }

            if (!selectedWords.length) {
                document.location.hash = "";
            } else {
                document.location.hash = encodeURI("#filtre=" + JSON.stringify(selectedWords));
            }
        });

        $(this).find('.input-group.date').datetimepicker({
            locale: 'fr_FR',
            format: 'L',
            allowInputToggle: true,
            focusOnShow: true,
            useCurrent: false
        });

        $(this).find("form.form-ajax-modal").on('submit', function () {
            var form = $(this);
            var callback = $(this).attr('callback');
            $.post($(this).attr('action'),
                    $(this).serialize(),
                    function (data)
                    {
                        if (!data.success) {
                            var content = form.find(form.attr('data-content')).html(data.content);
                            content.initAdvancedElements();
                            return;
                        }

                        if (form.data('related-element')) {
                            $(form.data('related-element')).trigger("modal_callback", data);
                        }

                        $(options.selectors.ajaxModal).modal('hide');
                    }, "json");

            return false;
        });

        $(this).find('.modal-autoshow').modal({
            'show': true
        });

        $(this).find('.link-submit').on('click', function () {
            var form = $($(this).attr('data-form'));
            form.attr('action', $(this).attr('href'));
            form.submit();

            return false;
        });
        $(this).find('.pointer').on('click', function () {
            if ($(this).attr('data-pointer')) {
                $($(this).attr('data-pointer')).click();
            }

            return false;
        });

        $(this).find('.dynamic-element-add').on('click', function () {
            var content = $($($(this).attr('data-template')).html().replace(/var---nbItem---/g, UUID.generate()));
            $($(this).attr('data-container')).append(content);
            content.initAdvancedElements();
        });

        $(this).find('.dynamic-element-delete').on('click', function () {
            $($(this).attr('data-line')).remove();
            if ($($(this).attr('data-lines')).length < 1 && $(this).attr('data-add')) {
                $($(this).attr('data-add')).trigger('click');
            }
        });
    }

    $.initQueryHash = function () {
        $(window).on('hashchange', function () {
            if ($(document).find('.hamzastyle').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                var filtres = [];
                if (params.filtre && params.filtre.match(/\[/)) {
                    filtres = JSON.parse(params.filtre);
                } else if (params.filtre) {
                    filtres.push(params.filtre);
                }

                var select2Data = [];
                for (key in filtres) {
                    select2Data.push({id: filtres[key], text: filtres[key]});
                }

                $(document).find('.hamzastyle').select2("data", select2Data);

                $(document).find('.hamzastyle-item').each(function () {
                    var words = $(this).attr('data-words');
                    var find = true;
                    for (key in filtres) {
                        var word = filtres[key];
                        if (words.indexOf(word) === -1) {
                            find = false;
                        }
                    }
                    if (find) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            }
            if ($(document).find('.nav.nav-tabs').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                if (params.tab) {
                    $('.nav.nav-tabs a[aria-controls="' + params.tab + '"]').tab('show');
                }
            }
        });

        if (location.hash) {
            $(window).trigger('hashchange');
        }
    }

})(jQuery);
<commit_msg>select2noajax allowclear<commit_after>
/**
 * Initialisation
 ******************************************/

(function ($)
{

    var options = {
        selectors: {
            ajaxModal: '#ajax-modal'
        }
    };

    $(document).ready(function ()
    {
        $(document).initAdvancedElements();

        $.initQueryHash();

        $(options.selectors.ajaxModal).on("show.bs.modal", function (e) {
            var link = $(e.relatedTarget);
            $(this).load(link.attr("href"), function () {
                $(this).initAdvancedElements();
            });
        });
        $(options.selectors.ajaxModal).on("hidden.bs.modal", function (e) {
            $(this).html("");
        });

    });

    $.fn.initAdvancedElements = function () {

        var element = $(this);

        $(this).find('.input-float').inputNumberFormat({'decimal': 4, 'decimalAuto': 2});
        $(this).find('.input-integer').inputNumberFormat({'decimal': 0, 'decimalAuto': 0});

        $(this).find("select.select2").select2({
            allowClear: true
        });

        $(this).find(".select2autocomplete").each(function () {
            var urlAjax = $(this).data('ajax');
            var defaultValue = $(this).val();
            var defaultValueSplitted = defaultValue.split(',');
            var select2 = $(this);
            $(this).select2({
                onselected: function () {
                    console.log('fre');
                },
                initSelection: function (element, callback) {
                    if (defaultValue != '') {
                        callback({id: defaultValueSplitted[0], text: defaultValueSplitted[1]});
                        select2.val(defaultValueSplitted[0]);
                    }
                },
                placeholder: 'Entrer un nom',
                minimumInputLength: 3,
                formatInputTooShort: function (input, min) {
                    var n = min - input.length;
                    return  min + " caractère" + (n == 1 ? "" : "s") + " min";
                },
                formatNoMatches: function () {
                    return "Aucun résultat";
                },
                formatSearching: function () {
                    return "Recherche…";
                },
                allowClear: true,
                ajax: {
                    quietMillis: 150,
                    url: urlAjax,
                    dataType: 'json',
                    type: "GET",
                    data: function (term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function (data) {
                        var results = [];
                        $.each(data, function (index, item) {
                            results.push({
                                id: index,
                                text: item
                            });
                        });
                        return {
                            results: results
                        }

                    }}
            });
        });

        $(this).find(".select2SubmitOnChange").on("change", function (e) {
            if (e.val) {
                $(this).parents('form').submit();
            }
        });

        $(this).find('.select2permissifNoAjax').each(function() {
	    var element = $(this);
	    var id = $(this).attr('id');
	    $(this).select2({
                data: JSON.parse($(this).attr('data-choices')),
                allowClear: true,
                multiple: false,
                createSearchChoice: function (term, data) {
                    if ($(data).filter(function () {
                        return this.text.localeCompare(term) === 0;
                    }).length === 0) {
                        return {id: term, text: term + ' (nouveau)'};
                    }
                }
            }).on("select2-close", function (e) {
		lastValue = $('#'+id).val();
                $(this).select2("val", lastValue);
                $(this).val(lastValue);
                $('#s2id_'+id).find('.select2-chosen').text(lastValue);
            })
        });

        $(this).find('.hamzastyle').each(function () {
            var select2 = $(this);
            select2.select2({
                multiple: true,
                data: function () {
                    var data = [];
                    element.find('.hamzastyle-item').each(function () {
                        data = data.concat(JSON.parse($(this).attr('data-words')));
                    });

                    var data = unique(data.sort());

                    dataFinal = [];
                    for (key in data) {
                        if (data[key] + "") {
                            dataFinal.push({id: (data[key] + ""), text: (data[key] + "")});
                        }
                    }

                    return {results: dataFinal};
                }
            })
        });

        $(this).find('.hamzastyle').on("change", function (e) {
            var select2Data = $(this).select2("data");
            var selectedWords = [];
            for (key in select2Data) {
                selectedWords.push(select2Data[key].text);
            }

            if (!selectedWords.length) {
                document.location.hash = "";
            } else {
                document.location.hash = encodeURI("#filtre=" + JSON.stringify(selectedWords));
            }
        });

        $(this).find('.input-group.date').datetimepicker({
            locale: 'fr_FR',
            format: 'L',
            allowInputToggle: true,
            focusOnShow: true,
            useCurrent: false
        });

        $(this).find("form.form-ajax-modal").on('submit', function () {
            var form = $(this);
            var callback = $(this).attr('callback');
            $.post($(this).attr('action'),
                    $(this).serialize(),
                    function (data)
                    {
                        if (!data.success) {
                            var content = form.find(form.attr('data-content')).html(data.content);
                            content.initAdvancedElements();
                            return;
                        }

                        if (form.data('related-element')) {
                            $(form.data('related-element')).trigger("modal_callback", data);
                        }

                        $(options.selectors.ajaxModal).modal('hide');
                    }, "json");

            return false;
        });

        $(this).find('.modal-autoshow').modal({
            'show': true
        });

        $(this).find('.link-submit').on('click', function () {
            var form = $($(this).attr('data-form'));
            form.attr('action', $(this).attr('href'));
            form.submit();

            return false;
        });
        $(this).find('.pointer').on('click', function () {
            if ($(this).attr('data-pointer')) {
                $($(this).attr('data-pointer')).click();
            }

            return false;
        });

        $(this).find('.dynamic-element-add').on('click', function () {
            var content = $($($(this).attr('data-template')).html().replace(/var---nbItem---/g, UUID.generate()));
            $($(this).attr('data-container')).append(content);
            content.initAdvancedElements();
        });

        $(this).find('.dynamic-element-delete').on('click', function () {
            $($(this).attr('data-line')).remove();
            if ($($(this).attr('data-lines')).length < 1 && $(this).attr('data-add')) {
                $($(this).attr('data-add')).trigger('click');
            }
        });
    }

    $.initQueryHash = function () {
        $(window).on('hashchange', function () {
            if ($(document).find('.hamzastyle').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                var filtres = [];
                if (params.filtre && params.filtre.match(/\[/)) {
                    filtres = JSON.parse(params.filtre);
                } else if (params.filtre) {
                    filtres.push(params.filtre);
                }

                var select2Data = [];
                for (key in filtres) {
                    select2Data.push({id: filtres[key], text: filtres[key]});
                }

                $(document).find('.hamzastyle').select2("data", select2Data);

                $(document).find('.hamzastyle-item').each(function () {
                    var words = $(this).attr('data-words');
                    var find = true;
                    for (key in filtres) {
                        var word = filtres[key];
                        if (words.indexOf(word) === -1) {
                            find = false;
                        }
                    }
                    if (find) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            }
            if ($(document).find('.nav.nav-tabs').length) {
                var params = jQuery.parseParams(location.hash.replace("#", ""));
                if (params.tab) {
                    $('.nav.nav-tabs a[aria-controls="' + params.tab + '"]').tab('show');
                }
            }
        });

        if (location.hash) {
            $(window).trigger('hashchange');
        }
    }

})(jQuery);
<|endoftext|>