<commit_before>var express = require('express');
var fs = require('fs');
var url = require('url');

if (process.env.REDISTOGO_URL) {
	var rtg   = require("url").parse(process.env.REDISTOGO_URL);
	var redis = require("redis").createClient(rtg.port, rtg.hostname);
	redis.auth(rtg.auth.split(":")[1]);
} else {
	var redis = require("redis").createClient();
}

var app = express();
app.use(express.logger());

app.get('/shorten', function(request, response) {
  fs.readFile('./shorten.html', function(error, content) {
    if (error) {
      response.writeHead(500);
      response.end();
    }
    else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(content, 'utf-8');
    }
  });
});

app.get('/success', function(request, response) {
  var url_parts = url.parse(request.url, true);
  var content = 'Success';
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.end(content, 'utf-8');
});

app.get('/shortenaction', function(request, response, next) {
  var url_parts = url.parse(request.url, true);
  console.log('shortenaction...');
  var path = url_parts.query['path'];
  if (path != undefined && path != null && path != '')
  {
    redis.set('/' + url_parts.query['path'],url_parts.query['url'],redis.print);
    response.redirect('success?path=' + url_parts.query['path']);
    response.end();
  }
  else
  {
    response.writeHead(500);
    response.end();
  }
});

app.get('*', function(request, response, next) {
  var path = url.parse(request.url).pathname;
  console.log('path: ' + path);
  if (path != undefined && path != null && path != '')
  {
     redis.get(path,
  	   function(err,reply){
         console.log('reply: ' + reply);
		 if (reply != null)
		 {
	       response.redirect(reply);
	       response.end();
           console.log('redirecting...');
		 }
		 else
		 {
           response.writeHead(500);
           response.end();
		 }
       }
     );
  }
  else
  {
    response.writeHead(500);
    response.end();
  }
});

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log("Listening on " + port);
});
<commit_msg>fixing duplicate case<commit_after>var express = require('express');
var fs = require('fs');
var url = require('url');

if (process.env.REDISTOGO_URL) {
	var rtg   = require("url").parse(process.env.REDISTOGO_URL);
	var redis = require("redis").createClient(rtg.port, rtg.hostname);
	redis.auth(rtg.auth.split(":")[1]);
} else {
	var redis = require("redis").createClient();
}

var app = express();
app.use(express.logger());

app.get('/shorten', function(request, response) {
  fs.readFile('./shorten.html', function(error, content) {
    if (error) {
      response.writeHead(500);
      response.end();
    }
    else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(content, 'utf-8');
    }
  });
});

app.get('/success', function(request, response) {
  var url_parts = url.parse(request.url, true);
  var content = 'Success';
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.end(content, 'utf-8');
});

app.get('/shortenaction', function(request, response, next) {
  var url_parts = url.parse(request.url, true);
  console.log('shortenaction...');
  var path = url_parts.query['path'];
  if (path != undefined && path != null && path != '')
  {

     redis.get(path,
  	   function(err,reply){
         console.log('reply: ' + reply);
		 if (reply == null)
		 {
		   redis.set('/' + url_parts.query['path'],url_parts.query['url'],redis.print);
		   response.redirect('success?path=' + url_parts.query['path']);
		   response.end();
		 }
		 else
		 {
           response.writeHead(500);
           response.end(path + 'already used');
		 }
       }
     );

  }
  else
  {
    response.writeHead(500);
    response.end();
  }
});

app.get('*', function(request, response, next) {
  var path = url.parse(request.url).pathname;
  console.log('path: ' + path);
  if (path != undefined && path != null && path != '')
  {
     redis.get(path,
  	   function(err,reply){
         console.log('reply: ' + reply);
		 if (reply != null)
		 {
	       response.redirect(reply);
	       response.end();
           console.log('redirecting...');
		 }
		 else
		 {
           response.writeHead(500);
           response.end();
		 }
       }
     );
  }
  else
  {
    response.writeHead(500);
    response.end();
  }
});

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log("Listening on " + port);
});
<|endoftext|>


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

Copyright (C) 2011 by Mozilla Foundation

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.

**********************************************************************************/

(function ( window, document, undefined ) {

  var modules = {};

  /****************************************************************************
   * Track
   ****************************************************************************/
  var numTracks = 0;
  var Track = function ( options ) {
    var trackEvents = [],
        id = numTracks++,
        that = this;

    options = options || {};
    var name = options.name || 'Track' + Date.now();

    this.getName = function () {
      return name;
    }; //getName

    this.getId = function () {
      return id;
    }; //getId

    this.getTrackEvent = function ( trackId ) {
      for ( var i=0, l=trackEvents.length; i<l; ++i) {
        if ( trackEvents[i].getId() === trackId || trackEvents[i].getName() === trackId ) {
          return trackEvents[i];
        } //if
      } //for
    }; //getTrackEvent

    this.getTrackEvents = function () {
      return trackEvents;
    }; //getTrackEvents

    this.removeTrackEvent = function ( trackEvent ) {
      if ( typeof(trackEvent) === "string" ) {
        trackEvent = that.getTrackEvent( trackEvent );
      } //if

      var idx = trackEvents.indexOf( trackEvent );

      if ( idx > -1 ) {
        trackEvents.splice( idx, 1 );
      } //if
    }; //removeTrackEvent

    this.addTrackEvent = function ( trackEvent ) {
      trackEvents.push( trackEvent );
    }; //addTrackEvent
  }; //Track

  /****************************************************************************
   * TrackEvent
   ****************************************************************************/
  var numTrackEvents = 0;
  var TrackEvent = function ( options ) {
    var id = numTrackEvents++;

    options = options || {};
    var name = options.name || 'Track' + Date.now();
    this.start = options.start || 0;
    this.popcornOptions = options.popcornOptions;
    this.end = options.end || 0;
    this.type = options.type;
    this.popcornEvent = options.popcornEvent;

    this.getName = function () {
      return name;
    };

    this.getId = function () {
      return id;
    }; //getId

  }; //TrackEvent

  /****************************************************************************
   * Target
   ****************************************************************************/
  var numTargets = 0;
  var Target = function ( options ) {
    var id = numTargets++;

    options = options || {};
    var name = options.name || "Target" + Date.now();
    this.object = options.object;

    this.getName = function () {
      return name;
    }; //getName

    this.getId = function () {
      return id;
    }; //getId
  }; //Target

  /****************************************************************************
   * Butter
   ****************************************************************************/
  var numButters = 0;
  var Butter = function ( options ) {

    var events = {},
        tracksByName = {},
        tracks = [],
        targets = [],
        targetsByName = {},
        that = this;

    this.id = "Butter" + numButters++;

    /****************************************************************
     * Event methods
     ****************************************************************/
    //trigger - Triggers an event indicating a change of state in the core
    this.trigger = function ( name, options ) {
      if ( events[ name ] ) {
        for (var i=0, l=events[ name ].length; i<l; ++i) {
          events[ name ][ i ].call( that, options );
        } //for
      } //if
    }; //trigger

    //listen - Listen for events triggered by the core
    this.listen = function ( name, handler ) {
      if ( !events[ name ] ) {
        events[ name ] = [];
      } //if
      events[ name ].push( handler );
    }; //listen

    //unlisten - Stops listen for events triggered by the core
    this.unlisten = function ( name, handler ) {
      var handlerList = events[ name ];
      if ( handlerList ) {
        if ( handler ) {
          var idx = handlerList.indexOf( handler );
          handlerList.splice( idx, 1 );
        }
        else {
          events[ name ] = [];
        } //if
      } //if
    }; //unlisten

    /****************************************************************
     * TrackEvent methods
     ****************************************************************/
    //addTrackEvent - Creates a new Track Event
    this.addTrackEvent = function ( track, trackEvent ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      if ( track ) {
        if ( !(trackEvent instanceof TrackEvent) ) {
          trackEvent = new TrackEvent( trackEvent );
        } //if
        track.addTrackEvent( trackEvent );
        that.trigger("trackeventadded", trackEvent);
        return trackEvent;
      } //if
      return undefined;
    }; //addTrackEvents

    //getTrackEvents - Get a list of Track Events
    this.getTrackEvents = function () {
      var trackEvents = {};
      for ( var i=0, l=tracks.length; i<l; ++i ) {
        var track = tracks[i];
        trackEvents[ track.getName() ] = track.getTrackEvents();
      } //for
    }; //getTrackEvents

    this.getTrackEvent = function ( track, trackEventId ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      track.getTrackEvent( trackEventId );
    }; //getTrackEvent

    //removeTrackEvent - Remove a Track Event
    this.removeTrackEvent = function ( track, trackEvent ) {
      if ( !(track instanceof Track) ) {
        track = that.getTrack( track );
      } //if
      track.removeTrackEvent( trackEvent );
      that.trigger( "trackeventremoved", trackEvent );
    };

    /****************************************************************
     * Track methods
     ****************************************************************/
    //addTrack - Creates a new Track
    this.addTrack = function ( track ) {
      if ( !(track instanceof Track) ) {
        track = new Track( track );
      } //if
      tracksByName[ track.getName() ] = track;
      tracks.push( track );
      that.trigger( "trackadded", track );
      return track;
    }; //addTrack

    //getTracks - Get a list of Tracks
    this.getTracks = function () {
      return tracks;
    }; //getTracks

    //getTrack - Get a Track by its id
    this.getTrack = function ( name ) {
      var track = tracksByName[ name ];
      if ( track ) {
         return track;
      } //if

      for ( var i=0, l=tracks.length; i<l; ++i ) {
        if ( tracks[i].id === name ) {
          return tracks[i];
        } //if
      } //for

      return undefined;
    }; //getTrack

    //removeTrack - Remove a Track
    this.removeTrack = function ( track ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      var idx = tracks.indexOf( track );
      if ( idx > -1 ) {
        tracks.splice( idx, 1 );
        delete tracksByName[ track.getName() ];
        that.trigger( "trackremoved", track );
        return track;
      } //if
      return undefined;
    };

    /****************************************************************
     * Target methods
     ****************************************************************/
    //addTarget - add a target object
    this.addTarget = function ( target ) {
      if ( !(target instanceof Target) ) {
        target = new Target( target );
      } //if

      targetsByName[ target.getName() ] = target;
      targets.push( target );

      that.trigger( "targetadded", target );

      return target;
    };

    //removeTarget - remove a target object
    this.removeTarget = function ( target ) {
      if ( typeof(target) === "string" ) {
        target = that.getTarget( target );
      } //if
      var idx = targets.indexOf( target );
      if ( idx > -1 ) {
        targets.splice( idx, 1 );
        delete targets[ target.getName() ];
        that.trigger( "targetremoved", target );
        return target;
      } //if
      return undefined;
    };

    //getTargets - get a list of targets objects
    this.getTargets = function () {
      return targets;
    };

    //getTarget - get a target object by its id
    this.getTarget = function ( name ) {
      return targetsByName[ name ];
    };

    /****************************************************************
     * Project methods
     ****************************************************************/
    //import - Import project data
    this.importProject = function ( projectData ) {
    };

    //export - Export project data
    this.exportProject = function () {
      var projectData;
      return projectData;
    };

    //setProjectDetails - set the details of the project
    this.setProjectDetails = function () {
    };

    //getProjectDetails - get the projects details
    this.getProjectDetails = function () {
    };

    /****************************************************************
     * Media methods
     ****************************************************************/
    //play - Play the media
    this.play = function () {
    };

    //pause - Pause the media
    this.pause = function () {
    };

    //currentTime - Gets and Sets the media's current time.
    this.currentTime = function () {
    };

    //getMedia - get the media's information
    this.getMedia = function () {
    };

    //setMedia - set the media's information
    this.setMedia = function () {
    };

    /****************************************************************
     * Init Modules for this instance
     ****************************************************************/
    for ( var moduleName in modules ) {
      modules[moduleName].setup && modules[moduleName].setup.call(this);
    } //for

  }; //Butter

  Butter.getScriptLocation = function () {
    var scripts = document.querySelectorAll( "script" );
    for (var i=0; i<scripts.length; ++i) {
      var pos = scripts[i].src.lastIndexOf('butter.js');
      if ( pos > -1 ) {
        return scripts[i].src.substr(0, pos) + "/";
      } //if
    } //for
  };

  //registerModule - Registers a Module into the Butter core
  Butter.registerModule = Butter.prototype.registerModule = function ( name, module ) {

    Butter.prototype[name] = function(options) {
      module.setup && module.setup.call(this, options);
      return this;
    };
    if ( module.extend ) {
      Butter.extendAPI( module.extend );
    } //if
  };

  Butter.extendAPI = function ( functions ) {
    for ( var fn in functions ) {
      if ( functions.hasOwnProperty( fn ) ) {
        Butter.prototype[ fn ] = functions[ fn ];
      } //if
    } //for
  };

  Butter.Track = Track;
  Butter.TrackEvent = TrackEvent;
  Butter.Target = Target;

  window.Butter = Butter;

})( window, document, undefined );

<commit_msg>added track to trackEvent<commit_after>/**********************************************************************************

Copyright (C) 2011 by Mozilla Foundation

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.

**********************************************************************************/

(function ( window, document, undefined ) {

  var modules = {};

  /****************************************************************************
   * Track
   ****************************************************************************/
  var numTracks = 0;
  var Track = function ( options ) {
    var trackEvents = [],
        id = numTracks++,
        that = this;

    options = options || {};
    var name = options.name || 'Track' + Date.now();

    this.getName = function () {
      return name;
    }; //getName

    this.getId = function () {
      return id;
    }; //getId

    this.getTrackEvent = function ( trackId ) {
      for ( var i=0, l=trackEvents.length; i<l; ++i) {
        if ( trackEvents[i].getId() === trackId || trackEvents[i].getName() === trackId ) {
          return trackEvents[i];
        } //if
      } //for
    }; //getTrackEvent

    this.getTrackEvents = function () {
      return trackEvents;
    }; //getTrackEvents

    this.removeTrackEvent = function ( trackEvent ) {
      if ( typeof(trackEvent) === "string" ) {
        trackEvent = that.getTrackEvent( trackEvent );
      } //if

      var idx = trackEvents.indexOf( trackEvent );

      if ( idx > -1 ) {
        trackEvents.splice( idx, 1 );
      } //if
    }; //removeTrackEvent

    this.addTrackEvent = function ( trackEvent ) {
      trackEvents.push( trackEvent );
    }; //addTrackEvent
  }; //Track

  /****************************************************************************
   * TrackEvent
   ****************************************************************************/
  var numTrackEvents = 0;
  var TrackEvent = function ( options ) {
    var id = numTrackEvents++;

    options = options || {};
    var name = options.name || 'Track' + Date.now();
    this.start = options.start || 0;
    this.end = options.end || 0;
    this.type = options.type;
    this.popcornOptions = options.popcornOptions;
    this.popcornEvent = options.popcornEvent;
    this.track = options.track;

    this.getName = function () {
      return name;
    };

    this.getId = function () {
      return id;
    }; //getId

  }; //TrackEvent

  /****************************************************************************
   * Target
   ****************************************************************************/
  var numTargets = 0;
  var Target = function ( options ) {
    var id = numTargets++;

    options = options || {};
    var name = options.name || "Target" + Date.now();
    this.object = options.object;

    this.getName = function () {
      return name;
    }; //getName

    this.getId = function () {
      return id;
    }; //getId
  }; //Target

  /****************************************************************************
   * Butter
   ****************************************************************************/
  var numButters = 0;
  var Butter = function ( options ) {

    var events = {},
        tracksByName = {},
        tracks = [],
        targets = [],
        targetsByName = {},
        that = this;

    this.id = "Butter" + numButters++;

    /****************************************************************
     * Event methods
     ****************************************************************/
    //trigger - Triggers an event indicating a change of state in the core
    this.trigger = function ( name, options ) {
      if ( events[ name ] ) {
        for (var i=0, l=events[ name ].length; i<l; ++i) {
          events[ name ][ i ].call( that, options );
        } //for
      } //if
    }; //trigger

    //listen - Listen for events triggered by the core
    this.listen = function ( name, handler ) {
      if ( !events[ name ] ) {
        events[ name ] = [];
      } //if
      events[ name ].push( handler );
    }; //listen

    //unlisten - Stops listen for events triggered by the core
    this.unlisten = function ( name, handler ) {
      var handlerList = events[ name ];
      if ( handlerList ) {
        if ( handler ) {
          var idx = handlerList.indexOf( handler );
          handlerList.splice( idx, 1 );
        }
        else {
          events[ name ] = [];
        } //if
      } //if
    }; //unlisten

    /****************************************************************
     * TrackEvent methods
     ****************************************************************/
    //addTrackEvent - Creates a new Track Event
    this.addTrackEvent = function ( track, trackEvent ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      if ( track ) {
        if ( !(trackEvent instanceof TrackEvent) ) {
          trackEvent = new TrackEvent( trackEvent );
        } //if
        track.addTrackEvent( trackEvent );
        that.trigger("trackeventadded", trackEvent);
        return trackEvent;
      } //if
      return undefined;
    }; //addTrackEvents

    //getTrackEvents - Get a list of Track Events
    this.getTrackEvents = function () {
      var trackEvents = {};
      for ( var i=0, l=tracks.length; i<l; ++i ) {
        var track = tracks[i];
        trackEvents[ track.getName() ] = track.getTrackEvents();
      } //for
    }; //getTrackEvents

    this.getTrackEvent = function ( track, trackEventId ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      track.getTrackEvent( trackEventId );
    }; //getTrackEvent

    //removeTrackEvent - Remove a Track Event
    this.removeTrackEvent = function ( track, trackEvent ) {
      if ( !(track instanceof Track) ) {
        track = that.getTrack( track );
      } //if
      track.removeTrackEvent( trackEvent );
      that.trigger( "trackeventremoved", trackEvent );
    };

    /****************************************************************
     * Track methods
     ****************************************************************/
    //addTrack - Creates a new Track
    this.addTrack = function ( track ) {
      if ( !(track instanceof Track) ) {
        track = new Track( track );
      } //if
      tracksByName[ track.getName() ] = track;
      tracks.push( track );
      that.trigger( "trackadded", track );
      return track;
    }; //addTrack

    //getTracks - Get a list of Tracks
    this.getTracks = function () {
      return tracks;
    }; //getTracks

    //getTrack - Get a Track by its id
    this.getTrack = function ( name ) {
      var track = tracksByName[ name ];
      if ( track ) {
         return track;
      } //if

      for ( var i=0, l=tracks.length; i<l; ++i ) {
        if ( tracks[i].id === name ) {
          return tracks[i];
        } //if
      } //for

      return undefined;
    }; //getTrack

    //removeTrack - Remove a Track
    this.removeTrack = function ( track ) {
      if ( typeof(track) === "string" ) {
        track = that.getTrack( track );
      } //if
      var idx = tracks.indexOf( track );
      if ( idx > -1 ) {
        tracks.splice( idx, 1 );
        delete tracksByName[ track.getName() ];
        that.trigger( "trackremoved", track );
        return track;
      } //if
      return undefined;
    };

    /****************************************************************
     * Target methods
     ****************************************************************/
    //addTarget - add a target object
    this.addTarget = function ( target ) {
      if ( !(target instanceof Target) ) {
        target = new Target( target );
      } //if

      targetsByName[ target.getName() ] = target;
      targets.push( target );

      that.trigger( "targetadded", target );

      return target;
    };

    //removeTarget - remove a target object
    this.removeTarget = function ( target ) {
      if ( typeof(target) === "string" ) {
        target = that.getTarget( target );
      } //if
      var idx = targets.indexOf( target );
      if ( idx > -1 ) {
        targets.splice( idx, 1 );
        delete targets[ target.getName() ];
        that.trigger( "targetremoved", target );
        return target;
      } //if
      return undefined;
    };

    //getTargets - get a list of targets objects
    this.getTargets = function () {
      return targets;
    };

    //getTarget - get a target object by its id
    this.getTarget = function ( name ) {
      return targetsByName[ name ];
    };

    /****************************************************************
     * Project methods
     ****************************************************************/
    //import - Import project data
    this.importProject = function ( projectData ) {
    };

    //export - Export project data
    this.exportProject = function () {
      var projectData;
      return projectData;
    };

    //setProjectDetails - set the details of the project
    this.setProjectDetails = function () {
    };

    //getProjectDetails - get the projects details
    this.getProjectDetails = function () {
    };

    /****************************************************************
     * Media methods
     ****************************************************************/
    //play - Play the media
    this.play = function () {
    };

    //pause - Pause the media
    this.pause = function () {
    };

    //currentTime - Gets and Sets the media's current time.
    this.currentTime = function () {
    };

    //getMedia - get the media's information
    this.getMedia = function () {
    };

    //setMedia - set the media's information
    this.setMedia = function () {
    };

    /****************************************************************
     * Init Modules for this instance
     ****************************************************************/
    for ( var moduleName in modules ) {
      modules[moduleName].setup && modules[moduleName].setup.call(this);
    } //for

  }; //Butter

  Butter.getScriptLocation = function () {
    var scripts = document.querySelectorAll( "script" );
    for (var i=0; i<scripts.length; ++i) {
      var pos = scripts[i].src.lastIndexOf('butter.js');
      if ( pos > -1 ) {
        return scripts[i].src.substr(0, pos) + "/";
      } //if
    } //for
  };

  //registerModule - Registers a Module into the Butter core
  Butter.registerModule = Butter.prototype.registerModule = function ( name, module ) {

    Butter.prototype[name] = function(options) {
      module.setup && module.setup.call(this, options);
      return this;
    };
    if ( module.extend ) {
      Butter.extendAPI( module.extend );
    } //if
  };

  Butter.extendAPI = function ( functions ) {
    for ( var fn in functions ) {
      if ( functions.hasOwnProperty( fn ) ) {
        Butter.prototype[ fn ] = functions[ fn ];
      } //if
    } //for
  };

  Butter.Track = Track;
  Butter.TrackEvent = TrackEvent;
  Butter.Target = Target;

  window.Butter = Butter;

})( window, document, undefined );

<|endoftext|>


<commit_before>var test = require('tape');
var browserify = require('browserify');
var parcelMap = require('../');
var path = require('path');
var shasum = require('shasum');

var opts = {
    keys: [ 'style' ],
    defaults: { style: '*.whatever' }
};

test('page1', function (t) {
    t.plan(1);
    var b = browserify(__dirname + '/files/page1');
    var expected = { assets: {}, packages: {} };
    var x = {
        style: '*.css',
        __dirname: __dirname + '/files/page1'
    };
    var hx = shasum(x);
    expected.packages[hx] = x;
    expected.assets[__dirname + '/files/page1/beep.css'] = hx;

    var y = {
        style: '*.css',
        __dirname: path.dirname(require.resolve('widget/style.css'))
    };
    var hy = shasum(y);
    expected.packages[hy] = y;
    expected.assets[require.resolve('widget/style.css')] = hy;

    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph, expected);
    });
    b.bundle();
});

test('page2', function (t) {
    t.plan(1);
    var b = browserify(__dirname + '/files/page2');
    var expected = { assets: {}, packages: {} };

    var x = {
        name: 'page2',
        __dirname: __dirname + '/files/page2'
    };
    var hx = shasum(x);
    expected.packages[hx] = x;
    expected.assets[__dirname + '/files/page2/whee.whatever'] = hx;

    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph, expected);
    });
    b.bundle();
});

test('page3', function (t) {
    t.plan(1);
    var b = browserify(__dirname + '/files/page3');
    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph, { packages: {}, assets: {} });
    });
    b.bundle();
});
<commit_msg>update the tests to not yet check dependencies<commit_after>var test = require('tape');
var browserify = require('browserify');
var parcelMap = require('../');
var path = require('path');
var shasum = require('shasum');

var opts = {
    keys: [ 'style' ],
    defaults: { style: '*.whatever' }
};

test('page1', function (t) {
    t.plan(2);
    var b = browserify(__dirname + '/files/page1');
    var expected = { assets: {}, packages: {} };
    var x = {
        style: '*.css',
        __dirname: __dirname + '/files/page1'
    };
    var hx = shasum(x);
    expected.packages[hx] = x;
    expected.assets[__dirname + '/files/page1/beep.css'] = hx;

    var y = {
        style: '*.css',
        __dirname: path.dirname(require.resolve('widget/style.css'))
    };
    var hy = shasum(y);
    expected.packages[hy] = y;
    expected.assets[require.resolve('widget/style.css')] = hy;

    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph.packages, expected.packages);
        t.deepEqual(graph.assets, expected.assets);
    });
    b.bundle();
});

test('page2', function (t) {
    t.plan(2);
    var b = browserify(__dirname + '/files/page2');
    var expected = { assets: {}, packages: {} };

    var x = {
        name: 'page2',
        __dirname: __dirname + '/files/page2'
    };
    var hx = shasum(x);
    expected.packages[hx] = x;
    expected.assets[__dirname + '/files/page2/whee.whatever'] = hx;

    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph.packages, expected.packages);
        t.deepEqual(graph.assets, expected.assets);
    });
    b.bundle();
});

test('page3', function (t) {
    t.plan(2);
    var b = browserify(__dirname + '/files/page3');
    parcelMap(b, opts, function (err, graph) {
        t.deepEqual(graph.packages, {});
        t.deepEqual(graph.assets, {});
    });
    b.bundle();
});
<|endoftext|>


<commit_before>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['underscore'], function (_) {

        var ResourceCache = function(sourceWindow, configuredCacheSizeEvictThreshold) {

            var self = this;
            var _resourcesHash = {};
            var _orderingByLastUseTimestamp = [];
            var _cacheSize = 0;
            // TODO:
            // 1) Size accordingly as a fraction of browser provided memory info (e.g. window.performance.memory on Chrome)
            // 2) expose as a configuration option passed within readiumOptions
            var CACHE_SIZE_EVICT_THRESHOLD_DEFAULT = 100000000;
            var cacheSizeEvictThreshold = determineCacheSizeThreshold();

            function getTimestamp() {
                return new Date().getTime();
            }

            function getBrowserHeapLimitInBytes() {
                if (window.performance && window.performance.memory && window.performance.memory.jsHeapSizeLimit) {
                    return window.performance.memory.jsHeapSizeLimit;
                } else {
                    return null;
                }
            }

            function determineCacheSizeThreshold() {
                if (configuredCacheSizeEvictThreshold) {
                    return configuredCacheSizeEvictThreshold;
                }
                var browserHeapLimitInBytes = getBrowserHeapLimitInBytes();
                if (browserHeapLimitInBytes && browserHeapLimitInBytes / 10 > CACHE_SIZE_EVICT_THRESHOLD_DEFAULT) {
                    return browserHeapLimitInBytes / 10;
                } else {
                    return  CACHE_SIZE_EVICT_THRESHOLD_DEFAULT;
                }
            }

            this.getResourceURL = function(resourceAbsoluteHref) {
                var resourceObjectUrl = null;
                var resourceData = _resourcesHash[resourceAbsoluteHref];
                if (resourceData) {
                    resourceObjectUrl = resourceData.url;
                    resourceData.lastUseTimestamp = getTimestamp();
                    updateOrderedIndex(resourceData);
                }
                return resourceObjectUrl;
            };

            function removeCacheEntryFromOrderedIndex(cacheEntry) {
                // Remove the previous entry from the ordered index, if present:
                if (typeof cacheEntry.orderingByLastUseTimestampIdx !== 'undefined') {
                    var orderingByLastUseTimestampIdx = cacheEntry.orderingByLastUseTimestampIdx;
                    _orderingByLastUseTimestamp.splice(orderingByLastUseTimestampIdx, 1);
                    // Decrement index values for all downshifted entries:
                    for (var i = orderingByLastUseTimestampIdx; i < _orderingByLastUseTimestamp.length; i++) {
                        var downshiftedEntry = _orderingByLastUseTimestamp[i];
                        // Assertion
                        if ((downshiftedEntry.orderingByLastUseTimestampIdx - 1) != i) {
                            console.error('algorithm incorrect: downshiftedEntry.orderingByLastUseTimestampIdx: ' +
                                downshiftedEntry.orderingByLastUseTimestampIdx + ', i: ' + i);
                        }
                        downshiftedEntry.orderingByLastUseTimestampIdx = i;
                    }
                }
            }

            function updateOrderedIndex(cacheEntry) {
                removeCacheEntryFromOrderedIndex(cacheEntry);
                var insertIdx = _.sortedIndex(_orderingByLastUseTimestamp, cacheEntry, 'lastUseTimestamp');
                _orderingByLastUseTimestamp.splice(insertIdx, 0, cacheEntry);
                cacheEntry.orderingByLastUseTimestampIdx = insertIdx;
            }

            this.putResource = function(resourceAbsoluteHref, resourceObjectUrl, resourceDataBlob) {
                this.trimCache();
                var currentTimestamp = getTimestamp();
                var cacheEntry = {
                    url: resourceObjectUrl,
                    absoluteHref: resourceAbsoluteHref,
                    blob: resourceDataBlob,
                    blobSize: resourceDataBlob.size,
                    creationTimestamp: currentTimestamp,
                    lastUseTimestamp: currentTimestamp,
                    pinned: true
                };
                _resourcesHash[resourceAbsoluteHref] = cacheEntry;
                updateOrderedIndex(cacheEntry);
                _cacheSize += resourceDataBlob.size;
            };

            this.evictResource = function(resourceAbsoluteHref) {
                var resourceData = _resourcesHash[resourceAbsoluteHref];
                if (resourceData) {
                    sourceWindow.URL.revokeObjectURL(resourceData.url);
                    _cacheSize -= resourceData.blobSize;
                    removeCacheEntryFromOrderedIndex(resourceData);
                    delete _resourcesHash[resourceAbsoluteHref];
                }
            };

            this.flushCache = function() {
                // TODO: more efficient, but less code reuse: iterate over _sortedIndex first,
                // then assert an empty cache and perform backup cleanup if assertion failed
                for (var resourceAbsoluteHref in _resourcesHash) {
                    this.evictResource(resourceAbsoluteHref);
                }
                // Assertion
                if (_cacheSize != 0) {
                    console.error('cacheSize accounting error! cacheSize: ' + _cacheSize + ', _resourcesHash:');
                    console.error(_resourcesHash);
                }
                _orderingByLastUseTimestamp = [];
                //console.log('Cache contents:');
                //console.log(_resourcesHash);
                //console.log('_orderingByLastUseTimestamp:');
                //console.log(_orderingByLastUseTimestamp);
                //console.log('Cache size:' + _cacheSize);
            };

            this.unPinResources = function() {
                for (var resourceAbsoluteHref in _resourcesHash) {
                    var resourceData = _resourcesHash[resourceAbsoluteHref];
                    resourceData.pinned = false;
                }
            };

            function orderingByLastUseTimestampToString() {
                return _orderingByLastUseTimestamp.reduce(function(previousValue, currentValue) {
                    return previousValue + (previousValue.length > 1 ? ', ' : '') + '[' +
                        currentValue.absoluteHref + ', pinned: ' + currentValue.pinned +
                        ', orderingByLastUseTimestampIdx: ' + currentValue.orderingByLastUseTimestampIdx + ']'
                }, '');
            }

            this.trimCache = function() {
                if (_cacheSize < cacheSizeEvictThreshold) {
                    return;
                }
                console.log('Trimming cache. Current cache size: ' + _cacheSize);

                // Loop through ordered index (by last use timestamp) starting from the least recently used entries.
                // evict unpinned resources until either:
                // 1) cache size drops below CACHE_SIZE_EVICT_THRESHOLD
                // 2) there are no more unpinned resources to evict
                for (var i = 0; i < _orderingByLastUseTimestamp.length; i++) {
                    if (_cacheSize < cacheSizeEvictThreshold) {
                        break;
                    }
                    var cacheEntry = _orderingByLastUseTimestamp[i];
                    if (!cacheEntry.pinned) {
                        var resourceAbsoluteHref = cacheEntry.absoluteHref;
                        //console.log('Preparing to evict ' + resourceAbsoluteHref);
                        //console.log('_orderingByLastUseTimestamp:');
                        //console.log(orderingByLastUseTimestampToString());
                        this.evictResource(resourceAbsoluteHref);
                        //console.log('Evicted ' + resourceAbsoluteHref);
                        //console.log('Current cache size: ' + _cacheSize);
                        //console.log('_orderingByLastUseTimestamp:');
                        //console.log(orderingByLastUseTimestampToString());
                        //console.log('i: ' + i);

                        // The consequent array elements have downshifted by one position.
                        // The i variable now points to a different element - the evicted element's successor
                        // (if not beyond array's end).
                        // Make the i variable remain in place - compensate for its upcoming incrementation:
                        i--;
                    }
                }
                console.log('Cache size after trimming: ' + _cacheSize);
            };
        };

        return ResourceCache;
    });
<commit_msg>Remove the implemented TODO comment.<commit_after>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['underscore'], function (_) {

        var ResourceCache = function(sourceWindow, configuredCacheSizeEvictThreshold) {

            var self = this;
            var _resourcesHash = {};
            var _orderingByLastUseTimestamp = [];
            var _cacheSize = 0;
            var CACHE_SIZE_EVICT_THRESHOLD_DEFAULT = 100000000;
            var cacheSizeEvictThreshold = determineCacheSizeThreshold();

            function getTimestamp() {
                return new Date().getTime();
            }

            function getBrowserHeapLimitInBytes() {
                if (window.performance && window.performance.memory && window.performance.memory.jsHeapSizeLimit) {
                    return window.performance.memory.jsHeapSizeLimit;
                } else {
                    return null;
                }
            }

            function determineCacheSizeThreshold() {
                if (configuredCacheSizeEvictThreshold) {
                    return configuredCacheSizeEvictThreshold;
                }
                var browserHeapLimitInBytes = getBrowserHeapLimitInBytes();
                if (browserHeapLimitInBytes && browserHeapLimitInBytes / 10 > CACHE_SIZE_EVICT_THRESHOLD_DEFAULT) {
                    return browserHeapLimitInBytes / 10;
                } else {
                    return  CACHE_SIZE_EVICT_THRESHOLD_DEFAULT;
                }
            }

            this.getResourceURL = function(resourceAbsoluteHref) {
                var resourceObjectUrl = null;
                var resourceData = _resourcesHash[resourceAbsoluteHref];
                if (resourceData) {
                    resourceObjectUrl = resourceData.url;
                    resourceData.lastUseTimestamp = getTimestamp();
                    updateOrderedIndex(resourceData);
                }
                return resourceObjectUrl;
            };

            function removeCacheEntryFromOrderedIndex(cacheEntry) {
                // Remove the previous entry from the ordered index, if present:
                if (typeof cacheEntry.orderingByLastUseTimestampIdx !== 'undefined') {
                    var orderingByLastUseTimestampIdx = cacheEntry.orderingByLastUseTimestampIdx;
                    _orderingByLastUseTimestamp.splice(orderingByLastUseTimestampIdx, 1);
                    // Decrement index values for all downshifted entries:
                    for (var i = orderingByLastUseTimestampIdx; i < _orderingByLastUseTimestamp.length; i++) {
                        var downshiftedEntry = _orderingByLastUseTimestamp[i];
                        // Assertion
                        if ((downshiftedEntry.orderingByLastUseTimestampIdx - 1) != i) {
                            console.error('algorithm incorrect: downshiftedEntry.orderingByLastUseTimestampIdx: ' +
                                downshiftedEntry.orderingByLastUseTimestampIdx + ', i: ' + i);
                        }
                        downshiftedEntry.orderingByLastUseTimestampIdx = i;
                    }
                }
            }

            function updateOrderedIndex(cacheEntry) {
                removeCacheEntryFromOrderedIndex(cacheEntry);
                var insertIdx = _.sortedIndex(_orderingByLastUseTimestamp, cacheEntry, 'lastUseTimestamp');
                _orderingByLastUseTimestamp.splice(insertIdx, 0, cacheEntry);
                cacheEntry.orderingByLastUseTimestampIdx = insertIdx;
            }

            this.putResource = function(resourceAbsoluteHref, resourceObjectUrl, resourceDataBlob) {
                this.trimCache();
                var currentTimestamp = getTimestamp();
                var cacheEntry = {
                    url: resourceObjectUrl,
                    absoluteHref: resourceAbsoluteHref,
                    blob: resourceDataBlob,
                    blobSize: resourceDataBlob.size,
                    creationTimestamp: currentTimestamp,
                    lastUseTimestamp: currentTimestamp,
                    pinned: true
                };
                _resourcesHash[resourceAbsoluteHref] = cacheEntry;
                updateOrderedIndex(cacheEntry);
                _cacheSize += resourceDataBlob.size;
            };

            this.evictResource = function(resourceAbsoluteHref) {
                var resourceData = _resourcesHash[resourceAbsoluteHref];
                if (resourceData) {
                    sourceWindow.URL.revokeObjectURL(resourceData.url);
                    _cacheSize -= resourceData.blobSize;
                    removeCacheEntryFromOrderedIndex(resourceData);
                    delete _resourcesHash[resourceAbsoluteHref];
                }
            };

            this.flushCache = function() {
                // TODO: more efficient, but less code reuse: iterate over _sortedIndex first,
                // then assert an empty cache and perform backup cleanup if assertion failed
                for (var resourceAbsoluteHref in _resourcesHash) {
                    this.evictResource(resourceAbsoluteHref);
                }
                // Assertion
                if (_cacheSize != 0) {
                    console.error('cacheSize accounting error! cacheSize: ' + _cacheSize + ', _resourcesHash:');
                    console.error(_resourcesHash);
                }
                _orderingByLastUseTimestamp = [];
                //console.log('Cache contents:');
                //console.log(_resourcesHash);
                //console.log('_orderingByLastUseTimestamp:');
                //console.log(_orderingByLastUseTimestamp);
                //console.log('Cache size:' + _cacheSize);
            };

            this.unPinResources = function() {
                for (var resourceAbsoluteHref in _resourcesHash) {
                    var resourceData = _resourcesHash[resourceAbsoluteHref];
                    resourceData.pinned = false;
                }
            };

            function orderingByLastUseTimestampToString() {
                return _orderingByLastUseTimestamp.reduce(function(previousValue, currentValue) {
                    return previousValue + (previousValue.length > 1 ? ', ' : '') + '[' +
                        currentValue.absoluteHref + ', pinned: ' + currentValue.pinned +
                        ', orderingByLastUseTimestampIdx: ' + currentValue.orderingByLastUseTimestampIdx + ']'
                }, '');
            }

            this.trimCache = function() {
                if (_cacheSize < cacheSizeEvictThreshold) {
                    return;
                }
                console.log('Trimming cache. Current cache size: ' + _cacheSize);

                // Loop through ordered index (by last use timestamp) starting from the least recently used entries.
                // evict unpinned resources until either:
                // 1) cache size drops below CACHE_SIZE_EVICT_THRESHOLD
                // 2) there are no more unpinned resources to evict
                for (var i = 0; i < _orderingByLastUseTimestamp.length; i++) {
                    if (_cacheSize < cacheSizeEvictThreshold) {
                        break;
                    }
                    var cacheEntry = _orderingByLastUseTimestamp[i];
                    if (!cacheEntry.pinned) {
                        var resourceAbsoluteHref = cacheEntry.absoluteHref;
                        //console.log('Preparing to evict ' + resourceAbsoluteHref);
                        //console.log('_orderingByLastUseTimestamp:');
                        //console.log(orderingByLastUseTimestampToString());
                        this.evictResource(resourceAbsoluteHref);
                        //console.log('Evicted ' + resourceAbsoluteHref);
                        //console.log('Current cache size: ' + _cacheSize);
                        //console.log('_orderingByLastUseTimestamp:');
                        //console.log(orderingByLastUseTimestampToString());
                        //console.log('i: ' + i);

                        // The consequent array elements have downshifted by one position.
                        // The i variable now points to a different element - the evicted element's successor
                        // (if not beyond array's end).
                        // Make the i variable remain in place - compensate for its upcoming incrementation:
                        i--;
                    }
                }
                console.log('Cache size after trimming: ' + _cacheSize);
            };
        };

        return ResourceCache;
    });
<|endoftext|>


<commit_before>var express = require('express');
var morgan = require('morgan');
var path = require('path');

var app = express();
app.use(morgan('combined'));

/*app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});*/
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'ui','Profile.html'));
});
/*app.get('/ui/style.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style.css'));
});*/
app.get('/ui/style1.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style1.css'));
});

/*app.get('/ui/madi.png', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
});*/

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`IMAD course app listening on port ${port}!`);
});
<commit_msg>[imad-console] Updates server.js<commit_after>var express = require('express');
var morgan = require('morgan');
var path = require('path');

var app = express();
app.use(morgan('combined'));

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'ui','Profile.html'));
});
app.get('/ui/style.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style.css'));
});
app.get('/ui/style1.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'style1.css'));
});

/*app.get('/ui/madi.png', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui', 'madi.png'));
});*/

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`IMAD course app listening on port ${port}!`);
});
<|endoftext|>


<commit_before>'use strict';

/* jasmine specs for services go here */

describe('service', function() {
  beforeEach(module('bottleRocket.services'));

  // Spec Template from Angular-Seed
  // describe('version', function() {
  //   it('should return current version', inject(function(version) {
  //     expect(version).toEqual('0.1');
  //   }));
  // });

  // Testing API calls using ngMock instead of Sinon because ngMock is built into Angular
  // https://docs.angularjs.org/api/ngMock/service/$httpBackend

  // Used this to help set up $httpBackend:
  // http://stackoverflow.com/questions/15927919/using-ngmock-to-simulate-http-calls-in-service-unit-tests

  var $httpBackend;

  beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get("$httpBackend");

    // configure the requests
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/?prefLabel=nirvana&user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotSearchDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/infos?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotInfoDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/related?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotRelatedDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/facts?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotFactsDataFromSeevl"});
  }));

  afterEach(function () {
    $httpBackend.flush()
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('seevlService tests', function() {

  	describe('seevlService Search http request', function () {
  		it('.value should be "gotSearchDataFromSeevl', inject(function (seevlService) {

  			seevlService.search("nirvana").success(function(response) {
  		  		expect(response.value).toEqual("gotSearchDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Info http request', function () {
  		it('.value should be "gotInfoDataFromSeevl', inject(function (seevlService) {

  			seevlService.getInfo("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotInfoDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Related http request', function () {
  		it('.value should be "gotRelatedDataFromSeevl', inject(function (seevlService) {

  			seevlService.getRelated("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotRelatedDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Facts http request', function () {
  		it('.value should be "gotFactsDataFromSeevl', inject(function (seevlService) {

  			seevlService.getFacts("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotFactsDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  });

});
<commit_msg>Adding test for youtubeService<commit_after>'use strict';

/* jasmine specs for services go here */

describe('service', function() {
  beforeEach(module('bottleRocket.services'));

  // Spec Template from Angular-Seed
  // describe('version', function() {
  //   it('should return current version', inject(function(version) {
  //     expect(version).toEqual('0.1');
  //   }));
  // });

  // Testing API calls using ngMock instead of Sinon because ngMock is built into Angular
  // https://docs.angularjs.org/api/ngMock/service/$httpBackend

  // Used this to help set up $httpBackend:
  // http://stackoverflow.com/questions/15927919/using-ngmock-to-simulate-http-calls-in-service-unit-tests

  var $httpBackend;

  beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get("$httpBackend");

    // configure the requests

    // Seevl Requests
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/?prefLabel=nirvana&user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotSearchDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/infos?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotInfoDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/related?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotRelatedDataFromSeevl"});
    $httpBackend
        .when("JSONP", "http://data.seevl.fm/entities/RkMQZrfG/facts?user_key=f934179d7329edcc16058765fb653a77&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotFactsDataFromSeevl"});

    // YouTube Request
    $httpBackend
        .when("JSONP", "http://gdata.youtube.com/feeds/api/videos?q=nirvana&format=5&max-results=1&v=2&alt=jsonc&callback=JSON_CALLBACK")
        	.respond(200, {value: "gotVideoFromYoutube"});

  }));

  afterEach(function () {
    $httpBackend.flush()
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('seevlService tests', function() {

  	describe('seevlService Search http request', function () {
  		it('.value should be "gotSearchDataFromSeevl', inject(function (seevlService) {

  			seevlService.search("nirvana").success(function(response) {
  		  		expect(response.value).toEqual("gotSearchDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Info http request', function () {
  		it('.value should be "gotInfoDataFromSeevl', inject(function (seevlService) {

  			seevlService.getInfo("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotInfoDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Related http request', function () {
  		it('.value should be "gotRelatedDataFromSeevl', inject(function (seevlService) {

  			seevlService.getRelated("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotRelatedDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  	describe('seevlService Facts http request', function () {
  		it('.value should be "gotFactsDataFromSeevl', inject(function (seevlService) {

  			seevlService.getFacts("RkMQZrfG").success(function(response) {
  		  		expect(response.value).toEqual("gotFactsDataFromSeevl");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  	});

  });

  describe('youtubeService tests', function() {
  	it('.value should be "gotVideoFromYoutube', inject(function (youtubeService) {

  			youtubeService.search("nirvana").success(function(response) {
  		  		expect(response.value).toEqual("gotVideoFromYoutube");
  			}).error( function(response) {
  		  		expect(false).toEqual(true);
  			});

  		}));
  });

});
<|endoftext|>


<commit_before>"use strict";

const path = require("path");

const { keyword } = require("esutils");

const utils   = require("rollup-pluginutils");

const Processor = require("modular-css-core");
const output    = require("modular-css-core/lib/output.js");

// sourcemaps for css-to-js don't make much sense, so always return nothing
// https://github.com/rollup/rollup/wiki/Plugins#conventions
const map = {
    mappings : "",
};

function extensionless(file) {
    return path.join(path.dirname(file), path.basename(file, path.extname(file)));
}

module.exports = function(opts) {
    const options = Object.assign(Object.create(null), {
        common : "common.css",

        json : false,
        map  : true,

        include : "**/*.css",

        namedExports : true,
    }, opts);

    const filter = utils.createFilter(options.include, options.exclude);

    const processor = options.processor || new Processor(options);

    let runs = 0;

    return {
        name : "modular-css-rollup",

        transform(code, id) {
            if(!filter(id)) {
                return null;
            }

            // If the file is being re-processed we need to remove it to
            // avoid cache staleness issues
            if(id in processor.files) {
                let files = [ id ];

                // First time build should only remove the file and any files that depend on it
                // but watchs update need to clear out the file, any files that depend on it,
                // AND any files it depends on
                if(runs) {
                    files = processor.dependencies(id).concat(files);
                }

                files.forEach((file) => processor.remove(file));
            }

            return processor.string(id, code).then((result) => {
                const exported = output.join(result.exports);

                const out = [
                    `export default ${JSON.stringify(exported, null, 4)};`,
                ];

                if(options.namedExports) {
                    Object.keys(exported).forEach((ident) => {
                        if(keyword.isReservedWordES6(ident) || !keyword.isIdentifierNameES6(ident)) {
                            this.warn(`Invalid JS identifier "${ident}", unable to export`);

                            return;
                        }

                        out.push(`export var ${ident} = ${JSON.stringify(exported[ident])};`);
                    });
                }

                const dependencies = processor.dependencies(id);

                return {
                    code : out.join("\n"),
                    map,
                    dependencies,
                };
            });
        },

        // Track # of runs since remove functionality needs to change
        buildEnd() {
            runs++;
        },

        async generateBundle(outputOptions, bundles) {
            const usage = new Map();
            const common = new Map();
            const files = [];

            let to;

            if(!outputOptions.file && !outputOptions.dir) {
                to = path.join(process.cwd(), outputOptions.assetFileNames || "");
            } else {
                to = path.join(
                    outputOptions.dir ? outputOptions.dir : path.dirname(outputOptions.file),
                    outputOptions.assetFileNames
                );
            }

            // First pass is used to calculate JS usage of CSS dependencies
            Object.keys(bundles).forEach((entry) => {
                const file = {
                    entry,
                    base : extensionless(entry),

                    css : [ ],
                };

                // Get CSS files being used by each entry point
                const css = Object.keys(bundles[entry].modules).filter(filter);

                if(!css.length) {
                    return;
                }

                // Get dependency chains for each file
                css.forEach((start) => {
                    const used = processor.dependencies(start).concat(start);

                    file.css = file.css.concat(used);

                    used.forEach((dep) => {
                        usage.set(dep, usage.has(dep) ? usage.get(dep) + 1 : 1);
                    });
                });

                files.push(file);
            });

            // Second pass removes any dependencies appearing in multiple bundles
            files.forEach((file) => {
                const { css } = file;

                file.css = css.filter((dep) => {
                    if(usage.get(dep) > 1) {
                        common.set(dep, true);

                        return false;
                    }

                    return true;
                });
            });

            // Add any other files that weren't part of a bundle to the common chunk
            Object.keys(processor.files).forEach((file) => {
                if(!usage.has(file)) {
                    common.set(file, true);
                }
            });

            // Common chunk only emitted if necessary
            if(common.size) {
                files.push({
                    entry : options.common,
                    base  : extensionless(options.common),
                    css   : [ ...common.keys() ],
                });
            }

            await Promise.all(
                files
                .filter(({ css }) => css.length)
                .map(async ({ base, css }) => {
                    const id = this.emitAsset(`${base}.css`);

                    const result = await processor.output({
                        to,
                        files : css,
                    });

                    this.setAssetSource(id, result.css);

                    if(options.json) {
                        this.emitAsset(`${base}.json`, JSON.stringify(result.compositions, null, 4));
                    }

                    if(result.map) {
                        this.emitAsset(`${base}.css.map`, result.map.toString());
                    }
                })
            );
        },
    };
};
<commit_msg>fix: Actually fix erroneous deletes from rollup<commit_after>"use strict";

const path = require("path");

const { keyword } = require("esutils");

const utils   = require("rollup-pluginutils");

const Processor = require("modular-css-core");
const output    = require("modular-css-core/lib/output.js");

// sourcemaps for css-to-js don't make much sense, so always return nothing
// https://github.com/rollup/rollup/wiki/Plugins#conventions
const map = {
    mappings : "",
};

function extensionless(file) {
    return path.join(path.dirname(file), path.basename(file, path.extname(file)));
}

module.exports = function(opts) {
    const options = Object.assign(Object.create(null), {
        common : "common.css",

        json : false,
        map  : true,

        include : "**/*.css",

        namedExports : true,
    }, opts);

    const filter = utils.createFilter(options.include, options.exclude);

    const processor = options.processor || new Processor(options);

    let runs = 0;

    return {
        name : "modular-css-rollup",

        transform(code, id) {
            if(!filter(id)) {
                return null;
            }

            // If the file is being re-processed we need to remove it to
            // avoid cache staleness issues
            if(runs && (id in processor.files)) {
                const files = processor.dependencies(id).concat(id);

                files.forEach((file) => processor.remove(file));
            }

            return processor.string(id, code).then((result) => {
                const exported = output.join(result.exports);

                const out = [
                    `export default ${JSON.stringify(exported, null, 4)};`,
                ];

                if(options.namedExports) {
                    Object.keys(exported).forEach((ident) => {
                        if(keyword.isReservedWordES6(ident) || !keyword.isIdentifierNameES6(ident)) {
                            this.warn(`Invalid JS identifier "${ident}", unable to export`);

                            return;
                        }

                        out.push(`export var ${ident} = ${JSON.stringify(exported[ident])};`);
                    });
                }

                const dependencies = processor.dependencies(id);

                return {
                    code : out.join("\n"),
                    map,
                    dependencies,
                };
            });
        },

        // Track # of runs since remove functionality needs to change
        buildEnd() {
            runs++;
        },

        async generateBundle(outputOptions, bundles) {
            const usage = new Map();
            const common = new Map();
            const files = [];

            let to;

            if(!outputOptions.file && !outputOptions.dir) {
                to = path.join(process.cwd(), outputOptions.assetFileNames || "");
            } else {
                to = path.join(
                    outputOptions.dir ? outputOptions.dir : path.dirname(outputOptions.file),
                    outputOptions.assetFileNames
                );
            }

            // First pass is used to calculate JS usage of CSS dependencies
            Object.keys(bundles).forEach((entry) => {
                const file = {
                    entry,
                    base : extensionless(entry),

                    css : [ ],
                };

                // Get CSS files being used by each entry point
                const css = Object.keys(bundles[entry].modules).filter(filter);

                if(!css.length) {
                    return;
                }

                // Get dependency chains for each file
                css.forEach((start) => {
                    const used = processor.dependencies(start).concat(start);

                    file.css = file.css.concat(used);

                    used.forEach((dep) => {
                        usage.set(dep, usage.has(dep) ? usage.get(dep) + 1 : 1);
                    });
                });

                files.push(file);
            });

            // Second pass removes any dependencies appearing in multiple bundles
            files.forEach((file) => {
                const { css } = file;

                file.css = css.filter((dep) => {
                    if(usage.get(dep) > 1) {
                        common.set(dep, true);

                        return false;
                    }

                    return true;
                });
            });

            // Add any other files that weren't part of a bundle to the common chunk
            Object.keys(processor.files).forEach((file) => {
                if(!usage.has(file)) {
                    common.set(file, true);
                }
            });

            // Common chunk only emitted if necessary
            if(common.size) {
                files.push({
                    entry : options.common,
                    base  : extensionless(options.common),
                    css   : [ ...common.keys() ],
                });
            }

            await Promise.all(
                files
                .filter(({ css }) => css.length)
                .map(async ({ base, css }) => {
                    const id = this.emitAsset(`${base}.css`);

                    const result = await processor.output({
                        to,
                        files : css,
                    });

                    this.setAssetSource(id, result.css);

                    if(options.json) {
                        this.emitAsset(`${base}.json`, JSON.stringify(result.compositions, null, 4));
                    }

                    if(result.map) {
                        this.emitAsset(`${base}.css.map`, result.map.toString());
                    }
                })
            );
        },
    };
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  isShowingHover: false,

  commitTitle: function() {
    if (this.get('vm.commit.title').match(/^Merge/)) {
      return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,'');
    }
    return this.get('vm.commit.title');
  }.property('vm.commit.title'),

  setShowingHover: function() {
    var access_level = this.get('session').get('data.authenticated.access_level');
    if (access_level >= 20) {
      this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id);
    } else {
      this.set('isShowingHover', false);
    }
  }.observes('isShowingHovers'),

  // Return true if is running state
  isRunning: function() {
    if (parseInt(this.get('vm.status'), 10) > 0) { return true; }
    return false;
  }.property('vm.status'),

  // Return true if user is a Dev or more
  isDev: function() {
    var access_level = this.get('session').get('data.authenticated.access_level');

    if (access_level >= 30) { return true; }
    return false;
  }.property('session.data.authenticated.access_level'),

  actions: {
    // close the modal, reset showing variable
    closeHover: function() {
      this.set('isShowingHovers', -1);
    }
  }
});
<commit_msg>Fix issue on match vm title<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  isShowingHover: false,

  commitTitle: function() {
    if (this.get('vm.commit.title') && this.get('vm.commit.title').match(/^Merge/)) {
      return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,'');
    }
    return this.get('vm.commit.title');
  }.property('vm.commit.title'),

  setShowingHover: function() {
    var access_level = this.get('session').get('data.authenticated.access_level');
    if (access_level >= 20) {
      this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id);
    } else {
      this.set('isShowingHover', false);
    }
  }.observes('isShowingHovers'),

  // Return true if is running state
  isRunning: function() {
    if (parseInt(this.get('vm.status'), 10) > 0) { return true; }
    return false;
  }.property('vm.status'),

  // Return true if user is a Dev or more
  isDev: function() {
    var access_level = this.get('session').get('data.authenticated.access_level');

    if (access_level >= 30) { return true; }
    return false;
  }.property('session.data.authenticated.access_level'),

  actions: {
    // close the modal, reset showing variable
    closeHover: function() {
      this.set('isShowingHovers', -1);
    }
  }
});
<|endoftext|>


<commit_before>import replace from 'lodash/replace';
import toString from 'lodash/toString';

const mobilePhoneNumberRegex = /^(08|628|\+628)[0-9]{6,11}$/;

/**
 * Sources
 * http://blog.mangpulsa.com/daftar-operator-seluler-gsm-indonesia/
 * http://www.kios-pulsa.com/article/daftar-prefix-nomor-operator-seluler-indonesia/
 */
const prefixMap = {
  '0811': true, // KartuHALO	Telkomsel
  '0812': true, // SimPATI, KartuHALO	Telkomsel
  '0813': true, // SimPATI, KartuHALO	Telkomsel
  '0814': true, // Indosat 3,5G Broadband	Indosat (IndosatM2)
  '0815': true, // Mentari lama, Matrix	Indosat
  '0816': true, // Mentari, Matrix	Indosat
  '0817': true, // XL Prabayar, XL Pascabayar	XL Axiata
  '0818': true, // XL Prabayar, XL Pascabayar	XL Axiata
  '0819': true, // XL Prabayar, XL Pascabayar	XL Axiata
  '0821': true, // SimPATI Freedom	Telkomsel
  '0822': true, // SimPATI (Kartu Facebook)	Telkomsel
  '0823': true, // Kartu As
  '0828': true, // Ceria	Sampoerna Telekom
  '0831': true, // Axis	AXIS Telekom Indonesia
  '0832': true, // Axis	AXIS Telekom Indonesia
  '0833': true, // Axis	AXIS Telekom Indonesia
  '0838': true, // Axis	AXIS Telekom Indonesia
  '0851': true, // Nomor untu k Kartu AS (pengganti Flexi)
  '0852': true, // Kartu As	Telkomsel
  '0853': true, // Kartu As (Kartu Prima)	Telkomsel
  '0855': true, // Matrix Auto	Indosat
  '0856': true, // IM3	Indosat
  '0857': true, // IM3	Indosat
  '0858': true, // Mentari	Indosat
  '0859': true, // XL Prabayar, XL Pascabayar	XL Axiata
  '0868': true, // ByRU	PSN/ACeS
  '0877': true, // XL Prabayar, Hauraa	XL Axiata
  '0878': true, // XL Prabayar	XL Axiata
  '0879': true, // XL Prabayar	XL Axiata
  '0881': true, // smartfren	Smartfren Telecom
  '0882': true, // smartfren	Smartfren Telecom
  '0883': true, // Smartfren	Smartfren Telecom
  '0884': true, // Smartfren	Smartfren Telecom
  '0885': true, // Smartfren	Smartfren Telecom
  '0886': true, // Smartfren	Smartfren Telecom
  '0887': true, // smartfren	Smartfren Telecom
  '0888': true, // smartfren	Smartfren Telecom
  '0889': true, // smartfren	Smartfren Telecom
  '0894': true, // 3	Hutchison Charoen Pokphand Telecom
  '0895': true, // 3	Hutchison Charoen Pokphand Telecom
  '0896': true, // 3	Hutchison Charoen Pokphand Telecom
  '0897': true, // 3	Hutchison Charoen Pokphand Telecom
  '0898': true, // 3	Hutchison Charoen Pokphand Telecom
  '0899': true // 3	Hutchison Charoen Pokphand Telecom
};

const normalizeMobilePhoneNumber = mobilePhoneNumber => {
  return replace(mobilePhoneNumber, /^(08|628|\+628|8)/, '08');
};

const validate = value => {
  if (!value) {
    return true;
  }

  const prefix = toString(normalizeMobilePhoneNumber(value)).substr(0, 4);

  return prefixMap[prefix] && mobilePhoneNumberRegex.test(value);
};

const message = '<%= propertyName %> field is not a valid mobile phone number.';

export default {validate, message};
<commit_msg>[Satpam] Update mobile phone number validation<commit_after>import replace from 'lodash/replace';
import toString from 'lodash/toString';

const mobilePhoneNumberRegex = /^(08|628|\+628)[0-9]{6,11}$/;

/**
 * Sources
 * http://blog.mangpulsa.com/daftar-operator-seluler-gsm-indonesia/
 * http://www.kios-pulsa.com/article/daftar-prefix-nomor-operator-seluler-indonesia/
 * http://pulsapul.blogspot.co.id/2011/11/0811-simpati.html
 */
const prefixMap = {
  '0811': true, // KartuHALO Telkomsel
  '0812': true, // SimPATI, KartuHALO Telkomsel
  '0813': true, // SimPATI, KartuHALO Telkomsel
  '0814': true, // Indosat 3,5G Broadband Indosat (IndosatM2)
  '0815': true, // Mentari lama, Matrix Indosat
  '0816': true, // Mentari, Matrix Indosat
  '0817': true, // XL Prabayar, XL Pascabayar XL Axiata
  '0818': true, // XL Prabayar, XL Pascabayar XL Axiata
  '0819': true, // XL Prabayar, XL Pascabayar XL Axiata
  '0821': true, // SimPATI Freedom Telkomsel
  '0822': true, // SimPATI (Kartu Facebook) Telkomsel
  '0823': true, // Kartu As
  '0828': true, // Ceria Sampoerna Telekom
  '0830': true, // Axis AXIS Telekom Indonesia
  '0831': true, // Axis AXIS Telekom Indonesia
  '0832': true, // Axis AXIS Telekom Indonesia
  '0833': true, // Axis AXIS Telekom Indonesia
  '0834': true, // Axis AXIS Telekom Indonesia
  '0835': true, // Axis AXIS Telekom Indonesia
  '0836': true, // Axis AXIS Telekom Indonesia
  '0837': true, // Axis AXIS Telekom Indonesia
  '0838': true, // Axis AXIS Telekom Indonesia
  '0839': true, // Axis AXIS Telekom Indonesia
  '0851': true, // Nomor untuk Kartu AS (pengganti Flexi)
  '0852': true, // Kartu As Telkomsel
  '0853': true, // Kartu As (Kartu Prima) Telkomsel
  '0855': true, // Matrix Auto Indosat
  '0856': true, // IM3 Indosat
  '0857': true, // IM3 Indosat
  '0858': true, // Mentari Indosat
  '0859': true, // XL Prabayar, XL Pascabayar XL Axiata
  '0868': true, // ByRU PSN/ACeS
  '0877': true, // XL Prabayar, Hauraa XL Axiata
  '0878': true, // XL Prabayar XL Axiata
  '0879': true, // XL Prabayar XL Axiata
  '0881': true, // smartfren Smartfren Telecom
  '0882': true, // smartfren Smartfren Telecom
  '0883': true, // Smartfren Smartfren Telecom
  '0884': true, // Smartfren Smartfren Telecom
  '0885': true, // Smartfren Smartfren Telecom
  '0886': true, // Smartfren Smartfren Telecom
  '0887': true, // smartfren Smartfren Telecom
  '0888': true, // smartfren Smartfren Telecom
  '0889': true, // smartfren Smartfren Telecom
  '0890': true, // 3 Hutchison Charoen Pokphand Telecom
  '0891': true, // 3 Hutchison Charoen Pokphand Telecom
  '0892': true, // 3 Hutchison Charoen Pokphand Telecom
  '0893': true, // 3 Hutchison Charoen Pokphand Telecom
  '0894': true, // 3 Hutchison Charoen Pokphand Telecom
  '0895': true, // 3 Hutchison Charoen Pokphand Telecom
  '0896': true, // 3 Hutchison Charoen Pokphand Telecom
  '0897': true, // 3 Hutchison Charoen Pokphand Telecom
  '0898': true, // 3 Hutchison Charoen Pokphand Telecom
  '0899': true, // 3 Hutchison Charoen Pokphand Telecom
};

const normalizeMobilePhoneNumber = mobilePhoneNumber => {
  return replace(mobilePhoneNumber, /^(08|628|\+628|8)/, '08');
};

const validate = value => {
  if (!value) {
    return true;
  }

  const prefix = toString(normalizeMobilePhoneNumber(value)).substr(0, 4);

  return prefixMap[prefix] && mobilePhoneNumberRegex.test(value);
};

const message = '<%= propertyName %> field is not a valid mobile phone number.';

export default {validate, message};
<|endoftext|>


<commit_before>describe("app.views.Base", function(){
  describe("#render", function(){
    beforeEach(function(){
      var staticTemplateClass = app.views.Base.extend({ templateName : "static-text" });

      this.model = new Backbone.Model({text : "model attributes are in the default presenter"});
      this.view = new staticTemplateClass({model: this.model});
      this.view.render();
    });

    it("renders the template with the presenter", function(){
      expect($(this.view.el).text().trim()).toBe("model attributes are in the default presenter");
    });

    it("it evaluates the presenter every render", function(){
      this.model.set({text : "OMG It's a party" });
      this.view.render();
      expect($(this.view.el).text().trim()).toBe("OMG It's a party");
    });

    context("subViewRendering", function(){
      beforeEach(function(){
        var viewClass =  app.views.Base.extend({
            templateName : "static-text",
            subviews : {
              ".subview1": "subview1",
              ".subview2": "createSubview2"
            },

            initialize : function(){
              this.subview1 = stubView("OMG First Subview");
            },

            presenter: {
              text : "this comes through on the original render"
            },

            postRenderTemplate : function(){
              $(this.el).append("
");
              $(this.el).append("
");
            },

            createSubview2 : function(){
              return stubView("furreal this is the Second Subview");
            }
        });

        this.view = new viewClass().render();
      });

      it("repsects the respects the template rendered with the presenter", function(){
        expect(this.view.$('.text').text().trim()).toBe("this comes through on the original render");
      });

      it("renders subviews from views that are properties of the object", function(){
        expect(this.view.$('.subview1').text().trim()).toBe("OMG First Subview");
      });

      it("renders the sub views from functions", function(){
        expect(this.view.$('.subview2').text().trim()).toBe("furreal this is the Second Subview");
      });
    });

    context("calling out to third party plugins", function(){
      it("replaces .time with relative time ago in words", function(){
        spyOn($.fn, "timeago");
        this.view.render();
        expect($.fn.timeago).toHaveBeenCalled();
        expect($.fn.timeago.calls.mostRecent().object.selector).toBe("time");
      });

      it("initializes tooltips declared with the view's tooltipSelector property", function(){
        this.view.tooltipSelector = ".christopher_columbus, .barrack_obama, .block_user";

        spyOn($.fn, "tooltip");
        this.view.render();
        expect($.fn.tooltip.calls.mostRecent().object.selector).toBe(".christopher_columbus, .barrack_obama, .block_user");
      });
    });
  });
});
<commit_msg>typo in spec [ci skip]<commit_after>describe("app.views.Base", function(){
  describe("#render", function(){
    beforeEach(function(){
      var staticTemplateClass = app.views.Base.extend({ templateName : "static-text" });

      this.model = new Backbone.Model({text : "model attributes are in the default presenter"});
      this.view = new staticTemplateClass({model: this.model});
      this.view.render();
    });

    it("renders the template with the presenter", function(){
      expect($(this.view.el).text().trim()).toBe("model attributes are in the default presenter");
    });

    it("it evaluates the presenter every render", function(){
      this.model.set({text : "OMG It's a party" });
      this.view.render();
      expect($(this.view.el).text().trim()).toBe("OMG It's a party");
    });

    context("subViewRendering", function(){
      beforeEach(function(){
        var viewClass =  app.views.Base.extend({
            templateName : "static-text",
            subviews : {
              ".subview1": "subview1",
              ".subview2": "createSubview2"
            },

            initialize : function(){
              this.subview1 = stubView("OMG First Subview");
            },

            presenter: {
              text : "this comes through on the original render"
            },

            postRenderTemplate : function(){
              $(this.el).append("
");
              $(this.el).append("
");
            },

            createSubview2 : function(){
              return stubView("furreal this is the Second Subview");
            }
        });

        this.view = new viewClass().render();
      });

      it("respects the template rendered with the presenter", function(){
        expect(this.view.$('.text').text().trim()).toBe("this comes through on the original render");
      });

      it("renders subviews from views that are properties of the object", function(){
        expect(this.view.$('.subview1').text().trim()).toBe("OMG First Subview");
      });

      it("renders the sub views from functions", function(){
        expect(this.view.$('.subview2').text().trim()).toBe("furreal this is the Second Subview");
      });
    });

    context("calling out to third party plugins", function(){
      it("replaces .time with relative time ago in words", function(){
        spyOn($.fn, "timeago");
        this.view.render();
        expect($.fn.timeago).toHaveBeenCalled();
        expect($.fn.timeago.calls.mostRecent().object.selector).toBe("time");
      });

      it("initializes tooltips declared with the view's tooltipSelector property", function(){
        this.view.tooltipSelector = ".christopher_columbus, .barrack_obama, .block_user";

        spyOn($.fn, "tooltip");
        this.view.render();
        expect($.fn.tooltip.calls.mostRecent().object.selector).toBe(".christopher_columbus, .barrack_obama, .block_user");
      });
    });
  });
});
<|endoftext|>