<commit_before>'use strict';
var LIBRARY            = require('./_library')
  , global             = require('./_global')
  , ctx                = require('./_ctx')
  , classof            = require('./_classof')
  , $export            = require('./_export')
  , isObject           = require('./_is-object')
  , anObject           = require('./_an-object')
  , aFunction          = require('./_a-function')
  , anInstance         = require('./_an-instance')
  , forOf              = require('./_for-of')
  , setProto           = require('./_set-proto').set
  , speciesConstructor = require('./_species-constructor')
  , task               = require('./_task').set
  , microtask          = require('./_microtask')()
  , PROMISE            = 'Promise'
  , TypeError          = global.TypeError
  , process            = global.process
  , $Promise           = global[PROMISE]
  , process            = global.process
  , isNode             = classof(process) == 'process'
  , empty              = function(){ /* empty */ }
  , Internal, GenericPromiseCapability, Wrapper;

var USE_NATIVE = !!function(){
  try {
    // correct subclassing with @@species support
    var promise     = $Promise.resolve(1)
      , FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
    // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
    return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
  } catch(e){ /* empty */ }
}();

// helpers
var sameConstructor = function(a, b){
  // with library wrapper special case
  return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
  var then;
  return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
  return sameConstructor($Promise, C)
    ? new PromiseCapability(C)
    : new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
  var resolve, reject;
  this.promise = new C(function($$resolve, $$reject){
    if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
    resolve = $$resolve;
    reject  = $$reject;
  });
  this.resolve = aFunction(resolve);
  this.reject  = aFunction(reject);
};
var perform = function(exec){
  try {
    exec();
  } catch(e){
    return {error: e};
  }
};
var notify = function(promise, isReject){
  if(promise._n)return;
  promise._n = true;
  var chain = promise._c;
  microtask(function(){
    var value = promise._v
      , ok    = promise._s == 1
      , i     = 0;
    var run = function(reaction){
      var handler = ok ? reaction.ok : reaction.fail
        , resolve = reaction.resolve
        , reject  = reaction.reject
        , domain  = reaction.domain
        , result, then;
      try {
        if(handler){
          if(!ok){
            if(promise._h == 2)onHandleUnhandled(promise);
            promise._h = 1;
          }
          if(handler === true)result = value;
          else {
            if(domain)domain.enter();
            result = handler(value);
            if(domain)domain.exit();
          }
          if(result === reaction.promise){
            reject(TypeError('Promise-chain cycle'));
          } else if(then = isThenable(result)){
            then.call(result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch(e){
        reject(e);
      }
    };
    while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
    promise._c = [];
    promise._n = false;
    if(isReject && !promise._h)onUnhandled(promise);
  });
};
var onUnhandled = function(promise){
  task.call(global, function(){
    var value = promise._v
      , abrupt, handler, console;
    if(isUnhandled(promise)){
      abrupt = perform(function(){
        if(isNode){
          process.emit('unhandledRejection', value, promise);
        } else if(handler = global.onunhandledrejection){
          handler({promise: promise, reason: value});
        } else if((console = global.console) && console.error){
          console.error('Unhandled promise rejection', value);
        }
      });
      // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
      promise._h = isNode || isUnhandled(promise) ? 2 : 1;
    } promise._a = undefined;
    if(abrupt)throw abrupt.error;
  });
};
var isUnhandled = function(promise){
  if(promise._h == 1)return false;
  var chain = promise._a || promise._c
    , i     = 0
    , reaction;
  while(chain.length > i){
    reaction = chain[i++];
    if(reaction.fail || !isUnhandled(reaction.promise))return false;
  } return true;
};
var onHandleUnhandled = function(promise){
  task.call(global, function(){
    var handler;
    if(isNode){
      process.emit('rejectionHandled', promise);
    } else if(handler = global.onrejectionhandled){
      handler({promise: promise, reason: promise._v});
    }
  });
};
var $reject = function(value){
  var promise = this;
  if(promise._d)return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  promise._v = value;
  promise._s = 2;
  if(!promise._a)promise._a = promise._c.slice();
  notify(promise, true);
};
var $resolve = function(value){
  var promise = this
    , then;
  if(promise._d)return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  try {
    if(promise === value)throw TypeError("Promise can't be resolved itself");
    if(then = isThenable(value)){
      microtask(function(){
        var wrapper = {_w: promise, _d: false}; // wrap
        try {
          then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
        } catch(e){
          $reject.call(wrapper, e);
        }
      });
    } else {
      promise._v = value;
      promise._s = 1;
      notify(promise, false);
    }
  } catch(e){
    $reject.call({_w: promise, _d: false}, e); // wrap
  }
};

// constructor polyfill
if(!USE_NATIVE){
  // 25.4.3.1 Promise(executor)
  $Promise = function Promise(executor){
    anInstance(this, $Promise, PROMISE, '_h');
    aFunction(executor);
    Internal.call(this);
    try {
      executor(ctx($resolve, this, 1), ctx($reject, this, 1));
    } catch(err){
      $reject.call(this, err);
    }
  };
  Internal = function Promise(executor){
    this._c = [];             // <- awaiting reactions
    this._a = undefined;      // <- checked in isUnhandled reactions
    this._s = 0;              // <- state
    this._d = false;          // <- done
    this._v = undefined;      // <- value
    this._h = 0;              // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
    this._n = false;          // <- notify
  };
  Internal.prototype = require('./_redefine-all')($Promise.prototype, {
    // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
    then: function then(onFulfilled, onRejected){
      var reaction    = newPromiseCapability(speciesConstructor(this, $Promise));
      reaction.ok     = typeof onFulfilled == 'function' ? onFulfilled : true;
      reaction.fail   = typeof onRejected == 'function' && onRejected;
      reaction.domain = isNode ? process.domain : undefined;
      this._c.push(reaction);
      if(this._a)this._a.push(reaction);
      if(this._s)notify(this, false);
      return reaction.promise;
    },
    // 25.4.5.1 Promise.prototype.catch(onRejected)
    'catch': function(onRejected){
      return this.then(undefined, onRejected);
    }
  });
  PromiseCapability = function(){
    var promise  = new Internal;
    this.promise = promise;
    this.resolve = ctx($resolve, promise, 1);
    this.reject  = ctx($reject, promise, 1);
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];

// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  // 25.4.4.5 Promise.reject(r)
  reject: function reject(r){
    var capability = newPromiseCapability(this)
      , $$reject   = capability.reject;
    $$reject(r);
    return capability.promise;
  }
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  // 25.4.4.6 Promise.resolve(x)
  resolve: function resolve(x){
    // instanceof instead of internal slot check because we should fix it without replacement native Promise core
    if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
    var capability = newPromiseCapability(this)
      , $$resolve  = capability.resolve;
    $$resolve(x);
    return capability.promise;
  }
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
  $Promise.all(iter)['catch'](empty);
})), PROMISE, {
  // 25.4.4.1 Promise.all(iterable)
  all: function all(iterable){
    var C          = this
      , capability = newPromiseCapability(C)
      , resolve    = capability.resolve
      , reject     = capability.reject;
    var abrupt = perform(function(){
      var values    = []
        , index     = 0
        , remaining = 1;
      forOf(iterable, false, function(promise){
        var $index        = index++
          , alreadyCalled = false;
        values.push(undefined);
        remaining++;
        C.resolve(promise).then(function(value){
          if(alreadyCalled)return;
          alreadyCalled  = true;
          values[$index] = value;
          --remaining || resolve(values);
        }, reject);
      });
      --remaining || resolve(values);
    });
    if(abrupt)reject(abrupt.error);
    return capability.promise;
  },
  // 25.4.4.4 Promise.race(iterable)
  race: function race(iterable){
    var C          = this
      , capability = newPromiseCapability(C)
      , reject     = capability.reject;
    var abrupt = perform(function(){
      forOf(iterable, false, function(promise){
        C.resolve(promise).then(capability.resolve, reject);
      });
    });
    if(abrupt)reject(abrupt.error);
    return capability.promise;
  }
});<commit_msg>remove unused variables, close #217<commit_after>'use strict';
var LIBRARY            = require('./_library')
  , global             = require('./_global')
  , ctx                = require('./_ctx')
  , classof            = require('./_classof')
  , $export            = require('./_export')
  , isObject           = require('./_is-object')
  , aFunction          = require('./_a-function')
  , anInstance         = require('./_an-instance')
  , forOf              = require('./_for-of')
  , speciesConstructor = require('./_species-constructor')
  , task               = require('./_task').set
  , microtask          = require('./_microtask')()
  , PROMISE            = 'Promise'
  , TypeError          = global.TypeError
  , process            = global.process
  , $Promise           = global[PROMISE]
  , process            = global.process
  , isNode             = classof(process) == 'process'
  , empty              = function(){ /* empty */ }
  , Internal, GenericPromiseCapability, Wrapper;

var USE_NATIVE = !!function(){
  try {
    // correct subclassing with @@species support
    var promise     = $Promise.resolve(1)
      , FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
    // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
    return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
  } catch(e){ /* empty */ }
}();

// helpers
var sameConstructor = function(a, b){
  // with library wrapper special case
  return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
  var then;
  return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
  return sameConstructor($Promise, C)
    ? new PromiseCapability(C)
    : new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
  var resolve, reject;
  this.promise = new C(function($$resolve, $$reject){
    if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
    resolve = $$resolve;
    reject  = $$reject;
  });
  this.resolve = aFunction(resolve);
  this.reject  = aFunction(reject);
};
var perform = function(exec){
  try {
    exec();
  } catch(e){
    return {error: e};
  }
};
var notify = function(promise, isReject){
  if(promise._n)return;
  promise._n = true;
  var chain = promise._c;
  microtask(function(){
    var value = promise._v
      , ok    = promise._s == 1
      , i     = 0;
    var run = function(reaction){
      var handler = ok ? reaction.ok : reaction.fail
        , resolve = reaction.resolve
        , reject  = reaction.reject
        , domain  = reaction.domain
        , result, then;
      try {
        if(handler){
          if(!ok){
            if(promise._h == 2)onHandleUnhandled(promise);
            promise._h = 1;
          }
          if(handler === true)result = value;
          else {
            if(domain)domain.enter();
            result = handler(value);
            if(domain)domain.exit();
          }
          if(result === reaction.promise){
            reject(TypeError('Promise-chain cycle'));
          } else if(then = isThenable(result)){
            then.call(result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch(e){
        reject(e);
      }
    };
    while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
    promise._c = [];
    promise._n = false;
    if(isReject && !promise._h)onUnhandled(promise);
  });
};
var onUnhandled = function(promise){
  task.call(global, function(){
    var value = promise._v
      , abrupt, handler, console;
    if(isUnhandled(promise)){
      abrupt = perform(function(){
        if(isNode){
          process.emit('unhandledRejection', value, promise);
        } else if(handler = global.onunhandledrejection){
          handler({promise: promise, reason: value});
        } else if((console = global.console) && console.error){
          console.error('Unhandled promise rejection', value);
        }
      });
      // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
      promise._h = isNode || isUnhandled(promise) ? 2 : 1;
    } promise._a = undefined;
    if(abrupt)throw abrupt.error;
  });
};
var isUnhandled = function(promise){
  if(promise._h == 1)return false;
  var chain = promise._a || promise._c
    , i     = 0
    , reaction;
  while(chain.length > i){
    reaction = chain[i++];
    if(reaction.fail || !isUnhandled(reaction.promise))return false;
  } return true;
};
var onHandleUnhandled = function(promise){
  task.call(global, function(){
    var handler;
    if(isNode){
      process.emit('rejectionHandled', promise);
    } else if(handler = global.onrejectionhandled){
      handler({promise: promise, reason: promise._v});
    }
  });
};
var $reject = function(value){
  var promise = this;
  if(promise._d)return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  promise._v = value;
  promise._s = 2;
  if(!promise._a)promise._a = promise._c.slice();
  notify(promise, true);
};
var $resolve = function(value){
  var promise = this
    , then;
  if(promise._d)return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  try {
    if(promise === value)throw TypeError("Promise can't be resolved itself");
    if(then = isThenable(value)){
      microtask(function(){
        var wrapper = {_w: promise, _d: false}; // wrap
        try {
          then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
        } catch(e){
          $reject.call(wrapper, e);
        }
      });
    } else {
      promise._v = value;
      promise._s = 1;
      notify(promise, false);
    }
  } catch(e){
    $reject.call({_w: promise, _d: false}, e); // wrap
  }
};

// constructor polyfill
if(!USE_NATIVE){
  // 25.4.3.1 Promise(executor)
  $Promise = function Promise(executor){
    anInstance(this, $Promise, PROMISE, '_h');
    aFunction(executor);
    Internal.call(this);
    try {
      executor(ctx($resolve, this, 1), ctx($reject, this, 1));
    } catch(err){
      $reject.call(this, err);
    }
  };
  Internal = function Promise(executor){
    this._c = [];             // <- awaiting reactions
    this._a = undefined;      // <- checked in isUnhandled reactions
    this._s = 0;              // <- state
    this._d = false;          // <- done
    this._v = undefined;      // <- value
    this._h = 0;              // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
    this._n = false;          // <- notify
  };
  Internal.prototype = require('./_redefine-all')($Promise.prototype, {
    // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
    then: function then(onFulfilled, onRejected){
      var reaction    = newPromiseCapability(speciesConstructor(this, $Promise));
      reaction.ok     = typeof onFulfilled == 'function' ? onFulfilled : true;
      reaction.fail   = typeof onRejected == 'function' && onRejected;
      reaction.domain = isNode ? process.domain : undefined;
      this._c.push(reaction);
      if(this._a)this._a.push(reaction);
      if(this._s)notify(this, false);
      return reaction.promise;
    },
    // 25.4.5.1 Promise.prototype.catch(onRejected)
    'catch': function(onRejected){
      return this.then(undefined, onRejected);
    }
  });
  PromiseCapability = function(){
    var promise  = new Internal;
    this.promise = promise;
    this.resolve = ctx($resolve, promise, 1);
    this.reject  = ctx($reject, promise, 1);
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];

// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  // 25.4.4.5 Promise.reject(r)
  reject: function reject(r){
    var capability = newPromiseCapability(this)
      , $$reject   = capability.reject;
    $$reject(r);
    return capability.promise;
  }
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  // 25.4.4.6 Promise.resolve(x)
  resolve: function resolve(x){
    // instanceof instead of internal slot check because we should fix it without replacement native Promise core
    if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
    var capability = newPromiseCapability(this)
      , $$resolve  = capability.resolve;
    $$resolve(x);
    return capability.promise;
  }
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
  $Promise.all(iter)['catch'](empty);
})), PROMISE, {
  // 25.4.4.1 Promise.all(iterable)
  all: function all(iterable){
    var C          = this
      , capability = newPromiseCapability(C)
      , resolve    = capability.resolve
      , reject     = capability.reject;
    var abrupt = perform(function(){
      var values    = []
        , index     = 0
        , remaining = 1;
      forOf(iterable, false, function(promise){
        var $index        = index++
          , alreadyCalled = false;
        values.push(undefined);
        remaining++;
        C.resolve(promise).then(function(value){
          if(alreadyCalled)return;
          alreadyCalled  = true;
          values[$index] = value;
          --remaining || resolve(values);
        }, reject);
      });
      --remaining || resolve(values);
    });
    if(abrupt)reject(abrupt.error);
    return capability.promise;
  },
  // 25.4.4.4 Promise.race(iterable)
  race: function race(iterable){
    var C          = this
      , capability = newPromiseCapability(C)
      , reject     = capability.reject;
    var abrupt = perform(function(){
      forOf(iterable, false, function(promise){
        C.resolve(promise).then(capability.resolve, reject);
      });
    });
    if(abrupt)reject(abrupt.error);
    return capability.promise;
  }
});<|endoftext|>


<commit_before>/**
 * Set a $uiRoute boolean to see if the current route matches
 */
angular.module('ui.route', []).directive('uiRoute', ['$location', '$parse', function ($location, $parse) {
  return {
    restrict: 'AC',
    scope: true,
    compile: function(tElement, tAttrs) {
      var useProperty;
      if (tAttrs.uiRoute) {
        useProperty = 'uiRoute';
      } else if (tAttrs.ngHref) {
        useProperty = 'ngHref';
      } else if (tAttrs.href) {
        useProperty = 'href';
      } else {
        throw new Error('uiRoute missing a route or href property on ' + tElement[0]);
      }
      return function ($scope, elm, attrs) {
        var modelSetter = $parse(attrs.ngModel || attrs.routeModel || '$uiRoute').assign;
        var watcher = angular.noop;

        // Used by href and ngHref
        function staticWatcher(newVal) {
          if ((hash = newVal.indexOf('#')) > -1){
            newVal = newVal.substr(hash + 1);
          }
          watcher = function watchHref() {
            modelSetter($scope, ($location.path().indexOf(newVal) > -1));
          };
          watcher();
        }
        // Used by uiRoute
        function regexWatcher(newVal) {
          if ((hash = newVal.indexOf('#')) > -1){
            newVal = newVal.substr(hash + 1);
          }
          watcher = function watchRegex() {
            var regexp = new RegExp('^' + newVal + '$', ['i']);
            modelSetter($scope, regexp.test($location.path()));
          };
          watcher();
        }

        switch (useProperty) {
          case 'uiRoute':
            // if uiRoute={{}} this will be undefined, otherwise it will have a value and $observe() never gets triggered
            if (attrs.uiRoute){
              regexWatcher(attrs.uiRoute);
            }else{
              attrs.$observe('uiRoute', regexWatcher);
            }
            break;
          case 'ngHref':
            // Setup watcher() every time ngHref changes
            if (attrs.ngHref){
              staticWatcher(attrs.ngHref);
            }else{
              attrs.$observe('ngHref', staticWatcher);
            }
            break;
          case 'href':
            // Setup watcher()
            staticWatcher(attrs.href);
        }

        $scope.$on('$routeChangeSuccess', function(){
          watcher();
        });

		//Added for compatibility with ui-router
	$scope.$on('$stateChangeSuccess', function(){
          watcher();
        });
      };
    }
  };
}]);
<commit_msg>Update route.js<commit_after>/**
 * Set a $uiRoute boolean to see if the current route matches
 */
angular.module('ui.route', []).directive('uiRoute', ['$location', '$parse', function ($location, $parse) {
  return {
    restrict: 'AC',
    scope: true,
    compile: function(tElement, tAttrs) {
      var useProperty;
      if (tAttrs.uiRoute) {
        useProperty = 'uiRoute';
      } else if (tAttrs.ngHref) {
        useProperty = 'ngHref';
      } else if (tAttrs.href) {
        useProperty = 'href';
      } else {
        throw new Error('uiRoute missing a route or href property on ' + tElement[0]);
      }
      return function ($scope, elm, attrs) {
        var modelSetter = $parse(attrs.ngModel || attrs.routeModel || '$uiRoute').assign;
        var watcher = angular.noop;

        // Used by href and ngHref
        function staticWatcher(newVal) {
          if ((hash = newVal.indexOf('#')) > -1){
            newVal = newVal.substr(hash + 1);
          }
          watcher = function watchHref() {
            modelSetter($scope, ($location.path().indexOf(newVal) > -1));
          };
          watcher();
        }
        // Used by uiRoute
        function regexWatcher(newVal) {
          if ((hash = newVal.indexOf('#')) > -1){
            newVal = newVal.substr(hash + 1);
          }
          watcher = function watchRegex() {
            var regexp = new RegExp('^' + newVal + '$', ['i']);
            modelSetter($scope, regexp.test($location.path()));
          };
          watcher();
        }

        switch (useProperty) {
          case 'uiRoute':
            // if uiRoute={{}} this will be undefined, otherwise it will have a value and $observe() never gets triggered
            if (attrs.uiRoute){
              regexWatcher(attrs.uiRoute);
            }else{
              attrs.$observe('uiRoute', regexWatcher);
            }
            break;
          case 'ngHref':
            // Setup watcher() every time ngHref changes
            if (attrs.ngHref){
              staticWatcher(attrs.ngHref);
            }else{
              attrs.$observe('ngHref', staticWatcher);
            }
            break;
          case 'href':
            // Setup watcher()
            staticWatcher(attrs.href);
        }

        $scope.$on('$routeChangeSuccess', function(){
          watcher();
        });

	//Added for compatibility with ui-router
	$scope.$on('$stateChangeSuccess', function(){
          watcher();
        });
      };
    }
  };
}]);
<|endoftext|>


<commit_before>'use strict;'
var lang = ['JavaScript ', ' HTML5 ', ' CSS3']
var myLocalProjects = [
  {
    name: 'Rosemary Tuttle Guessing Game',
    path: 'https://rtuts67.github.io/guessing_game/',
    description: 'This was the very first project I worked on as an aspiring developer.',
    languages: lang
  },

  {
    name: 'Campfire Coffee',
    path: 'https://rtuts67.github.io/lab7/',
    description: 'This second project was heavily weigted on JavaScript.',
    languages: lang
  },

  {
    name: 'Bus Mall',
    path: 'https://rtuts67.github.io/lab11/',
    description: 'The third project involved localStorage!',
    languages: lang
  },

  {
    name: 'Home Field Advantage',
    path: 'https://rtuts67.github.io/Final_Project_HFA_201n6/',
    description: 'The final project was built for the purpose of helping prospective home-buyers look for a property in Seattle.',
    languages: lang
  }
];
<commit_msg>Got valid json data<commit_after>'use strict';
//var lang = ['JavaScript ', ' HTML5 ', ' CSS3']
//var myLocalProjects = [
[
  {
    "name": "Rosemary Tuttle Guessing Game",
    "filepath": "https://rtuts67.github.io/guessing_game/",
    "description": "This was the very first project I worked on as an aspiring developer.",
    "languages": "JavaScript."
  },

  {
    "name": "Campfire Coffee",
    "path": "https://rtuts67.github.io/lab7/",
    "description": "This second project was heavily weigted on JavaScript.",
    "languages": "JavaScript."
  },

  {
    "name": "Bus Mall",
    "path": "https://rtuts67.github.io/lab11/",
    "description": "The third project involved localStorage!",
    "languages": "JavaScript"
  },

  {
    "name": "Home Field Advantage",
    "path": "https://rtuts67.github.io/Final_Project_HFA_201n6/",
    "description": "The final project was built for the purpose of helping prospective home-buyers look for a property in Seattle.",
    "languages": "JavaScript"
  }
]
<|endoftext|>


<commit_before>/*jshint -W098*/
/*global describe, it, before, beforeEach, after, afterEach, sinon, beforeAll, chai */
var instance, sandbox, notificationsCollection, expect;

var setupFn = function () {
	instance = Notifications;
	sandbox = sinon.sandbox.create();
	notificationsCollection = instance._getNotificationsCollection();
};

var tearDownFn = function () {
	sandbox.restore();
	instance._notificationTimeout = undefined;
	notificationsCollection.remove({});
};

var testNotification, timedNotification, clock, testId;

describe('#addNotification', function () {
	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should call _add', function () {
		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123');
		expect(_add.callCount).to.equal(1);
	});

	it('Should use the defaultOptions to construct the object to pass to _add', function () {
		var _add = sandbox.stub(instance, '_add');
		var expected = _.clone(instance.defaultOptions);
		var testMessage = 'test123';
		var testTitle = 'Title';

		expected.title = testTitle;
		expected.message = testMessage;
		expected.type = instance.defaultOptions.type;
		expected.userCloseable = instance.defaultOptions.userCloseable;

		delete expected.timeout;

		instance.addNotification(testTitle, testMessage);
		expect(_add).to.have.been.calledWith(expected);
	});

	it('Called with options - it should call _add', function () {
		var testOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false
		};

		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123', testOptions);
		expect(_add.callCount).to.equal(1);
	});

	it('Called with options - Should use the options to construct the object to pass to _add', function () {
		var testOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false
		};

		var _add = sandbox.stub(instance, '_add');
		var expected = _.clone(instance.defaultOptions);
		var testMessage = 'test123';
		var testTitle = 'Title';

		expected.title = testTitle;
		expected.message = testMessage;
		expected.type = testOptions.type;
		expected.userCloseable = testOptions.userCloseable;
		delete expected.timeout;
		instance.addNotification(testTitle, testMessage, _.clone(testOptions));
		expect(_add).to.have.been.calledWith(expected);
	});

	it('Called with options - Options has a timeout - Should add an expires timestamp to the notification given to _add', function () {
		sandbox.useFakeTimers();

		var timedOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false,
			timeout: 2000
		};

		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123', _.clone(timedOptions));
		var expires = _add.args[0][0].expires;
		expect(expires).to.equal(new Date().getTime() + timedOptions.timeout);
	});
});

describe('#getNotificationClass', function () {
	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should return the className for the given type', function () {
		expect(instance.getNotificationClass(instance.TYPES.ERROR)).to.equal('error');
		expect(instance.getNotificationClass(instance.TYPES.WARNING)).to.equal('warning');
		expect(instance.getNotificationClass(instance.TYPES.INFO)).to.equal('info');
		expect(instance.getNotificationClass(instance.TYPES.SUCCESS)).to.equal('success');
	});
});

describe('#remove', function () {
	var testNotification;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		testNotification = {};
		testNotification.message = 'test100';
		testNotification.type = instance.defaultOptions.type;
		testNotification.userCloseable = instance.defaultOptions.userCloseable;
		instance._add(testNotification);
		instance._add(testNotification);
		instance._add(testNotification);
		testNotification._id = testId = 'unique';
		instance._add(testNotification);
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should remove the notification with the given _id', function () {
		var size = notificationsCollection.find().count();

		instance.remove({_id: testId});

		expect(notificationsCollection.find().count()).to.equal(size - 1);
		expect(notificationsCollection.findOne({_id: testId})).to.equal(undefined);
	});
});

describe('#_add', function () {
	var testNotification, timedNotification;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		testNotification = {
			message: 'test100',
			type: instance.defaultOptions.type,
			userCloseable: instance.defaultOptions.userCloseable
		};

		timedNotification = _.clone(testNotification);
		timedNotification.expires = new Date().getTime() + 2000;
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should call _add', function () {
		var collectionSize = notificationsCollection.find().count();
		instance._add(testNotification);
		expect(notificationsCollection.find().count()).to.equal(collectionSize + 1);
	});

	it('Should call _createTimeout', function () {
		var _createTimeout = sandbox.stub(instance, '_createTimeout');
		instance._add(timedNotification);
		expect(_createTimeout.callCount).to.equal(1);
	});

	it('When given notification has a expires timestamp - When _notifactionTimeout is truthy - Given expires is higher than any existing timestamp - Should NOT remove the existing timeout', function () {
		instance._notificationTimeout = 'test';
		notificationsCollection.insert(timedNotification);
		var slowNotification = _.clone(timedNotification);
		slowNotification.expires += 250;

		instance._add(_.clone(slowNotification));
		expect(instance._notificationTimeout).to.equal('test');
	});

	it('When given notification has a expires timestamp - When _notifactionTimeout is truthy - Given expires timestamp is lower than any existing timestamp - Should call _createTimeout', function () {
		var fastNotification = _.clone(timedNotification);
		fastNotification.expires -= 250;

		instance._notificationTimeout = 'test';
		notificationsCollection.insert(timedNotification);

		var _createTimeout = sandbox.stub(instance, '_createTimeout');
		instance._add(fastNotification);
		expect(_createTimeout.callCount).to.equal(1);
	});
});

describe('#_createTimeout', function () {
	var timedNotification, clock;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		clock = sandbox.useFakeTimers();

		timedNotification = {};
		timedNotification.message = 'test100';
		timedNotification.type = instance.defaultOptions.type;
		timedNotification.userCloseable = instance.defaultOptions.userCloseable;
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should set _notificationTimeout', function () {
		timedNotification.expires = (new Date().getTime()) + 2000;
		notificationsCollection.insert(timedNotification);

		instance._createTimeout();
		expect(instance._notificationTimeout).to.not.equal(undefined);
	});

	it('Should remove the notification when the timeout expires', function () {
		timedNotification.expires = (new Date().getTime()) + 2000;
		notificationsCollection.insert(timedNotification);

		var collectionSize = notificationsCollection.find().count();
		instance._createTimeout();
		clock.tick(1999);
		expect(notificationsCollection.find().count()).to.equal(collectionSize);
		clock.tick(2000);

		expect(notificationsCollection.find().count()).to.equal(collectionSize - 1);
	});

	it('Called with very short timeout - Should remove the notification when the timeout expires', function () {
		timedNotification.expires = (new Date().getTime()) + 10;
		notificationsCollection.insert(timedNotification);

		var collectionSize = notificationsCollection.find().count();
		instance._createTimeout();
		clock.tick(9);
		expect(notificationsCollection.find().count()).to.equal(collectionSize);
		clock.tick(10);

		expect(notificationsCollection.find().count()).to.equal(collectionSize - 1);
	});
});
<commit_msg>Fixed tests<commit_after>/*jshint -W098*/
/*global describe, it, before, beforeEach, after, afterEach, sinon, beforeAll, chai */
var instance, sandbox, notificationsCollection, expect;

var setupFn = function () {
	if (sandbox) {
		tearDownFn();
	}

	instance = Notifications;
	sandbox = sinon.sandbox.create();
	notificationsCollection = instance._getNotificationsCollection();
};

var tearDownFn = function () {
	sandbox.restore();
	instance._notificationTimeout = undefined;
	notificationsCollection.remove({});
    sandbox = undefined;
};

var testNotification, timedNotification, clock, testId;

describe('#addNotification', function () {
	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
        setupFn();
	});

	afterEach(function () {
	});

	it('Should call _add', function () {
		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123');
		expect(_add.callCount).to.equal(1);
	});

	it('Should use the defaultOptions to construct the object to pass to _add', function () {
		var _add = sandbox.stub(instance, '_add');
		var expected = _.clone(instance.defaultOptions);
		var testMessage = 'test123';
		var testTitle = 'Title';

		expected.title = testTitle;
		expected.message = testMessage;
		expected.type = instance.defaultOptions.type;
		expected.userCloseable = instance.defaultOptions.userCloseable;
		expected.closed = undefined;

		delete expected.timeout;

		instance.addNotification(testTitle, testMessage);
		expect(_add).to.have.been.calledWith(expected);
	});

	it('Called with options - it should call _add', function () {
		var testOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false
		};

		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123', testOptions);
		expect(_add.callCount).to.equal(1);
	});

	it('Called with options - Should use the options to construct the object to pass to _add', function () {
		var testOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false
		};

		var _add = sandbox.stub(instance, '_add');
		var expected = _.clone(instance.defaultOptions);
		var testMessage = 'test123';
		var testTitle = 'Title';

		expected.title = testTitle;
		expected.message = testMessage;
		expected.type = testOptions.type;
		expected.userCloseable = testOptions.userCloseable;
		expected.closed = undefined;
		delete expected.timeout;
		instance.addNotification(testTitle, testMessage, _.clone(testOptions));
		expect(_add).to.have.been.calledWith(expected);
	});

	it('Called with options - Options has a timeout - Should add an expires timestamp to the notification given to _add', function () {
		sandbox.useFakeTimers();

		var timedOptions = {
			type: instance.TYPES.ERROR,
			userCloseable: false,
			timeout: 2000
		};

		var _add = sandbox.stub(instance, '_add');
		instance.addNotification('Title', 'test123', _.clone(timedOptions));
		var expires = _add.args[0][0].expires;
		expect(expires).to.equal(new Date().getTime() + timedOptions.timeout);
	});
});

describe('#getNotificationClass', function () {
	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should return the className for the given type', function () {
		expect(instance.getNotificationClass(instance.TYPES.ERROR)).to.equal('error');
		expect(instance.getNotificationClass(instance.TYPES.WARNING)).to.equal('warning');
		expect(instance.getNotificationClass(instance.TYPES.INFO)).to.equal('info');
		expect(instance.getNotificationClass(instance.TYPES.SUCCESS)).to.equal('success');
	});
});

describe('#remove', function () {
	var testNotification;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		testNotification = {};
		testNotification.message = 'test100';
		testNotification.type = instance.defaultOptions.type;
		testNotification.userCloseable = instance.defaultOptions.userCloseable;
		instance._add(testNotification);
		instance._add(testNotification);
		instance._add(testNotification);
		testNotification._id = testId = 'unique';
		instance._add(testNotification);
	});

	it('Should remove the notification with the given _id', function () {
		var size = notificationsCollection.find().count();

		instance.remove({_id: testId});

		expect(notificationsCollection.find().count()).to.equal(size - 1);
		expect(notificationsCollection.findOne({_id: testId})).to.equal(undefined);
	});
});

describe('#_add', function () {
	var testNotification, timedNotification;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		testNotification = {
			message: 'test100',
			type: instance.defaultOptions.type,
			userCloseable: instance.defaultOptions.userCloseable
		};

		timedNotification = _.clone(testNotification);
		timedNotification.expires = new Date().getTime() + 2000;
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should call _add', function () {
		var collectionSize = notificationsCollection.find().count();
		instance._add(testNotification);
		expect(notificationsCollection.find().count()).to.equal(collectionSize + 1);
	});

	it('Should call _createTimeout', function () {
		var _createTimeout = sandbox.stub(instance, '_createTimeout');
		instance._add(timedNotification);
		expect(_createTimeout.callCount).to.equal(1);
	});

	it('When given notification has a expires timestamp - When _notifactionTimeout is truthy - Given expires is higher than any existing timestamp - Should NOT remove the existing timeout', function () {
		instance._notificationTimeout = 'test';
		notificationsCollection.insert(timedNotification);
		var slowNotification = _.clone(timedNotification);
		slowNotification.expires += 250;

		instance._add(_.clone(slowNotification));
		expect(instance._notificationTimeout).to.equal('test');
	});

	it('When given notification has a expires timestamp - When _notifactionTimeout is truthy - Given expires timestamp is lower than any existing timestamp - Should call _createTimeout', function () {
		var fastNotification = _.clone(timedNotification);
		fastNotification.expires -= 250;

		instance._notificationTimeout = 'test';
		notificationsCollection.insert(timedNotification);

		var _createTimeout = sandbox.stub(instance, '_createTimeout');
		instance._add(fastNotification);
		expect(_createTimeout.callCount).to.equal(1);
	});
});

describe('#_createTimeout', function () {
	var timedNotification, clock;

	beforeAll(function () {
		expect = chai.expect;
	});

	beforeEach(function () {
		setupFn();
		clock = sandbox.useFakeTimers();

		timedNotification = {};
		timedNotification.message = 'test100';
		timedNotification.type = instance.defaultOptions.type;
		timedNotification.userCloseable = instance.defaultOptions.userCloseable;
	});

	afterEach(function () {
		tearDownFn();
	});

	it('Should set _notificationTimeout', function () {
		timedNotification.expires = (new Date().getTime()) + 2000;
		notificationsCollection.insert(timedNotification);

		instance._createTimeout();
		expect(instance._notificationTimeout).to.not.equal(undefined);
	});

	it('Should remove the notification when the timeout expires', function () {
		timedNotification.expires = (new Date().getTime()) + 2000;
		notificationsCollection.insert(timedNotification);

		var collectionSize = notificationsCollection.find().count();
		instance._createTimeout();
		clock.tick(1999);
		expect(notificationsCollection.find().count()).to.equal(collectionSize);
		clock.tick(2000);

		expect(notificationsCollection.find().count()).to.equal(collectionSize - 1);
	});

	it('Called with very short timeout - Should remove the notification when the timeout expires', function () {
		timedNotification.expires = (new Date().getTime()) + 10;
		notificationsCollection.insert(timedNotification);

		var collectionSize = notificationsCollection.find().count();
		instance._createTimeout();
		clock.tick(9);
		expect(notificationsCollection.find().count()).to.equal(collectionSize);
		clock.tick(10);

		expect(notificationsCollection.find().count()).to.equal(collectionSize - 1);
	});
});
<|endoftext|>


<commit_before>var Resource = require('./resource')
    , AWSResource = require('./awsresource')
    , fn = require('./fn');

function Output(name, value, description) {
    if (!(this instanceof Output)) {
        return new Output(name, value, description);
    }

    if (!(value instanceof Resource) && !(value instanceof AWSResource) && !(value instanceof fn.Function) && !(typeof value === 'string')) {
        throw new Error('Output value can only be a string or another resource or a join, getatt or an other function');
    }
    if (description && !(typeof description !== 'string')) {
        throw new Error('Output description must be string');
    }

    this.name = name;
    this.value = value;
    this.description = description;
}

Output.prototype.toObject = function() {
    value = this.value;
    if (value instanceof AWSResource) {
        value = fn.ref(value);
    }

    return {
        Value : value,
        Description : this.description,
    };
}

module.exports = Output;
<commit_msg>Improved error output for Output resource<commit_after>var Resource = require('./resource')
    , AWSResource = require('./awsresource')
    , fn = require('./fn')
    , util = require('util');

function Output(name, value, description) {
    if (!(this instanceof Output)) {
        return new Output(name, value, description);
    }

    if (!(value instanceof Resource) && !(value instanceof AWSResource) && !(value instanceof fn.Function) && !(typeof value === 'string')) {
        var msg = util.format('Output "%s" value for can only be a string or another resource or a join, getatt or an other function. '+
            'Got "%s" instead ("%s")', name, typeof value, value);
        throw new Error(msg);
    }
    if (description && !(typeof description !== 'string')) {
        throw new Error('Output description must be string');
    }

    this.name = name;
    this.value = value;
    this.description = description;
}

Output.prototype.toObject = function() {
    value = this.value;
    if (value instanceof AWSResource) {
        value = fn.ref(value);
    }

    return {
        Value : value,
        Description : this.description,
    };
}

module.exports = Output;
<|endoftext|>


<commit_before>// Execute this script in the target branch to release to npm!

const exec = require('./exec');
const path = require('path');
const readline = require('readline');
const semver = require('semver');
const pkg = require('../package.json');
const branchName = exec('git rev-parse --abbrev-ref HEAD', true);
const currentVersion = pkg.version;
const stdin = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function syncRemote(branchName, nextVersion) {

  exec(`git push origin ${branchName}`);

  if (nextVersion) {
    exec(`git push --tags`);
    console.log(`TravisCI will now release to npm on the tagged commit ${nextVersion} for the pearson-ux account.`);
  }
}

function exitFailure(message) {
  console.error(message);
  process.exit(1);
}

// *** RELEASE PROCESS BEGINS HERE: Releaser provides the target SEMVER-compliant version ***

stdin.question(`Next version (current is ${currentVersion})? `, (nextVersion) => {

  if (!semver.valid(nextVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: it must be a valid semantic version. See http://semver.org/.`);
  }

  if (!semver.gt(nextVersion, currentVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: it must be greater than the current version.`);
  }

  if (nextVersion.startsWith('v')) {
    nextVersion = nextVersion.slice(1);
  }

  // Make sure unit tests pass before continuing!
  exec('npm test');

  // Ensure the /dist is generated
  exec('npm run build-docs');

  // 1. Bump the version update in package.json and npm-shrinkwrap.json
  // 2. The 'version' npm script executes changelog generation and adding to commit
  // 3. Locally commit and tag
  exec(`npm version ${nextVersion}`);

  // push commit and tag on target release branch
  syncRemote(branchName, nextVersion);

  // Generate gh-pages branch and sync with remote
  exec('npm run gh-pages');
  exec('git pull -s recursive -Xours --no-edit');
  syncRemote('gh-pages');

  // Go back from whence you came
  exec(`git checkout ${branchName}`);

  stdin.close();
});
<commit_msg>chore(release): Enhance release script.<commit_after>// Execute this script in the target branch to release to npm!

const exec = require('./exec');
const path = require('path');
const readline = require('readline');
const semver = require('semver');
const pkg = require('../package.json');
const branchName = exec('git rev-parse --abbrev-ref HEAD', true);
const currentVersion = pkg.version;
const stdin = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
const syncRemote = (branchName, nextVersion) => {

  exec(`git push origin ${branchName}`);

  if (nextVersion) {
    exec(`git push --tags`);
    console.log(`TravisCI will now release to npm on the tagged commit ${nextVersion} for the pearson-ux account.`);
  }
};
const exitFailure = (message) => {
  console.error(message);
  process.exit(1);
};

// *** Releaser provides the target SEMVER-compliant version ***

stdin.question(`Next version (current is ${currentVersion})? `, (nextVersion) => {

  if (!semver.valid(nextVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: requires a semver-compliant version. See http://semver.org/`);
  }

  if (!semver.gt(nextVersion, currentVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: it must be greater than the current version.`);
  }

  if (nextVersion.startsWith('v')) {
    nextVersion = nextVersion.slice(1);
  }

  // Ensure unit tests pass before continuing!
  exec('npm test');

  // Ensure the /dist is generated
  exec('npm run build-docs');

  // Order of operations:
  // 1. Bump the version update in package.json and npm-shrinkwrap.json
  // 2. The 'version' custom npm script (defined in package.json) executes changelog generation and adding to commit
  // 3. Locally commit and tag
  exec(`npm version ${nextVersion}`);

  // push commit and tag on target release branch
  syncRemote(branchName, nextVersion);

  // Generate gh-pages branch and sync with remote
  exec('npm run gh-pages');
  exec('git pull -s recursive -Xours --no-edit');
  syncRemote('gh-pages');

  // Go back from whence you came
  exec(`git checkout ${branchName}`);

  stdin.close();
});
<|endoftext|>


<commit_before>// this test will be run by userAuth [for all files matching *test.js]

var userAuth = require('userAuth');

var common = require('./common'),<commit_msg>Revert "Added file object-test.js"<commit_after><|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Item = function(name, price) {
  return {
    name: function() {
      return name;
    },
    unitPrice: function() {
      return price;
    }
  }
};

var Basket = function() {
  var items = [];
  return {
    add: function(item) {
      items.push(item);
    },

    count: function() { return items.length; },

    remove: function(item) {
      var idx = -1;
      for (var i=0;i<items.length;++i) {
        if (items[i].name() === item.name()) {
          idx = i;
          break;
        }
      }
      if (idx !== -1) {
        items.splice(idx, 1);
      }
    }
  };
};

var Register = function() {

  var runningSum = 0;
  var offers = [];
  var items = [];

  return {
     price: function(item) {
       items.push(item);
     },

     insertOffer: function(offer) {
       offers.push(offer);
     },

     total: function() {
       var runningSum = 0;
       for (var i=0;i<items.length;++i) {
         runningSum += items[i].unitPrice();
       }

       return runningSum;
     }
  };
};

var numberOfItemsMatchingInBasket = function(item, basket) {
  var count = 0;
  for (var i=0;i<basket.length;++i) {
    if (basket[i].name() === item.name()) {
      count++;
    }
  }

  return count;
};

var Receipt = function() {
  var items = [];
  var total = 0;

  return {
    items: function() { return items; },

    total: function() { return total; },

    record: function(description, price) {
      items.push(description + ' : ' + price);
      total += price;
    },
  };
};

var Unit = function(item) {
  return {
    applies: function(basket, receipt) {
      if (numberOfItemsMatchingInBasket(item, basket) >= 1) {
        receipt.record(item.name(), item.unitPrice());
        return true;
      } else {
        return false;
      }
    }
  };
};

var BuyOneGetOneFree = function(item) {
  return {
    applies: function(basket, receipt) {
      if (numberOfItemsMatchingInBasket(item,basket) >= 2) {
        receipt.record("BOGOF " + item.name(), item.unitPrice());
        return true;
      } else {
        return false;
      }
    }
  };
};

var ThreeForTwo = function(item) {
  return {
    applies: function(basket, receipt) {
      if (numberOfItemsMatchingInBasket(item,basket) >= 3) {
        receipt.record("3 for 2 " + item.name(), 2 * item.unitPrice());
        return true;
      } else {
        return false;
      }
    }
  }
};

describe('super market', function() {

  var beans = new Item('beans', 45);
  var batteries = new Item('batteries', 60);

  describe('item', function() {
    it('have a unit price', function() {
      assert.equal(45, beans.unitPrice());
    });
  });

  describe('basket', function() {
    it('can keep track of items', function() {
      var basket = new Basket();
      basket.add(beans);

      assert.equal(1, basket.count());

      basket.remove(beans);
      assert.equal(0, basket.count());
    });
  });

  describe('receipt', function() {
    it('consists of items and a total price', function() {
      var receipt = new Receipt();
      receipt.record('2 x Beans', 45);
      receipt.record('4 x Shoes', 10);

      assert.equal(2, receipt.items().length);
      assert.equal(55, receipt.total());
    });
  });

  describe('register', function() {
    it('totals the price of items', function() {
      var register = new Register();
      register.price(beans);
      register.price(beans);

      assert.equal(90, register.total());
    });

    it('knows of offers', function() {
      var register = new Register();
      register.insertOffer(new BuyOneGetOneFree(beans));

      register.price(beans);
      register.price(beans);

      assert.equal(45, register.total());
    });
  });

  describe('offer', function() {

    var item, price, receipt;

    beforeEach(function() {
      item = undefined;
      price = undefined;
      receipt = {
        record: function(item_, price_) {
          item = item_;
          price = price_;
        }
      };
    });

    it('unit offer', function() {
      var offer = new Unit(beans);
      assert(offer.applies([beans], receipt));
      assert.equal(45, price);
    });

    it('buy-one-get-one-free', function() {
      var offer = new BuyOneGetOneFree(beans);
      assert(offer.applies([beans, beans], receipt));
      assert.equal(45, price);
    });

    it('3 for 2', function() {
      var offer = new ThreeForTwo(beans);
      assert(offer.applies([beans,beans,beans], receipt));
      assert.equal(90, price);
    });
  });
});

// TODO
// Learnt about beforeEach and splice
// Would have made an offer apply for every item and applied in order
<commit_msg>supermarket kata #2<commit_after>"use strict";

var assert = require('assert');

describe('shopping basket', function() {
  describe('item', function() {
    it('exists', function() {
      assert(new Item('description'));
    });
  });
});
<|endoftext|>


<commit_before>/*jslint browser: true, nomen: true */

(function (flow, $, girder) {
    'use strict';

    $(document).ready(function () {
        girder.apiRoot = '/girder/api/v1';
        var app = new flow.App({
            el: 'body'
        });

        // Lookup the ID of the analysis that we wish to perform.
        app.analysisName = "discreteCorrelation-app";
        girder.restRequest({
            path: 'resource/search',
            data: {
                q: app.analysisName,
                types: JSON.stringify(["item"])
            }
        }).done(function (results) {
            app.analysisId = results["item"][0]._id;
            console.log(app.analysisId)
            app.readyToAnalyze();
        });

        app.readyToAnalyze = function () {
            if ("column1" in this && "column2" in this && "table" in this && "tree" in this &&
                "analysisId" in this) {
                d3.select("#analyze").classed('disabled', false);
            }
        };

        function toggleInputTablePreview() {
            if ($("#table-preview-icon").hasClass("glyphicon-folder-close")) {
                $("#table-preview-icon").removeClass("glyphicon-folder-close");
                $("#table-preview-icon").addClass("glyphicon-folder-open");
                $("#table-preview-text").text(" Hide input table preview");
            }
            else {
                $("#table-preview-icon").removeClass("glyphicon-folder-open");
                $("#table-preview-icon").addClass("glyphicon-folder-close");
                $("#table-preview-text").text(" Show input table preview");
            }

            $("#input-table-vis").toggle('slow');
        }

        // override upload function for simple mode
        flow.DatasetManagementView.prototype.upload = function (file) {
            var reader = new FileReader();

            reader.onload = _.bind(function (e) {
                var dataset = {
                        name: file.name,
                        data: e.target.result
                    },
                    extension = file.name.split('.'),
                    typeFormat;

                extension = extension[extension.length - 1];
                typeFormat = flow.getTypeFormatsFromExtension(extension)[0];
                typeFormat = {type: typeFormat.type, format: typeFormat.format};
                _.extend(dataset, typeFormat);
                dataset = new Backbone.Model(dataset);

                // modifications for simple app begin here
                // if its a table, get the column names
                if (typeFormat.type == "table") {
                    app.table = dataset.get('data');
                    app.tableFormat = typeFormat.format;
                    d3.select("#table-name").html('Table: ' + file.name + ' ');
                    $("#column-input1").text("Parsing column names...");
                    $("#column-names").empty();
                    flow.retrieveDatasetAsFormat(dataset, "table", "column.names", false, _.bind(function (error, dataset) {
                        var columnNames = dataset.get('data');
                        for (var i = 0; i < columnNames.length; ++i) {
                            // create drag-and-drop elements here
                            $("#column-names").append('
' + columnNames[i] + '
');
                        }
                        $(".draggable").draggable({
                             zIndex: 1, helper: "clone"
                        });
                        d3.select("#column-input1").html('Drag first column of interest here (must be a binary character) ');
                    }, this));

                    flow.retrieveDatasetAsFormat(dataset, "table", "rows", false, _.bind(function (error, dataset) {
                      // show the input table to help the user understand if their data
                      // was parsed correctly or not
                      var rowData = dataset.get('data');
                      rowData.rows = rowData.rows.slice(0, 3);
                      d3.select("#input-table-vis-container").classed('hidden', false);
                      $("#input-table-vis").table({ data: rowData });
                    }, this));

                }

                else if (typeFormat.type == "tree") {
                    app.tree = dataset.get('data');
                    d3.select("#tree-name").html('Tree: ' + file.name + ' ');
                }
                app.readyToAnalyze();

                this.datasets.off('add', null, 'set-collection').add(dataset);
            }, this);

            reader.readAsText(file);
        };

        $("#column-input1").droppable({
            drop: function( event, ui ) {
                var COI = ui.draggable.text();
                app.column1 = COI;
                d3.select("#column-input1")
                    .classed('btn-primary', true)
                    .classed('btn-success', false)
                    .classed('bg-warning', false)
                    .html(COI + ' ');
                d3.select("#column-input2")
                        .html('Now place second variable of interest here...');

                app.readyToAnalyze();
            },
            over: function (event, ui) {
                d3.select("#column-input1")
                    .classed('btn-success', true)
                    .classed('bg-warning', false);
            },
            out: function (event, ui) {
                d3.select("#column-input1")
                    .classed('btn-success', false)
                    .classed('bg-warning', true);
            }
            });

            $("#column-input2").droppable({
                drop: function( event, ui ) {
                    var COI = ui.draggable.text();
                    app.column2 = COI;
                    d3.select("#column-input2")
                        .classed('btn-primary', true)
                        .classed('btn-success', false)
                        .classed('bg-warning', false)
                        .html(COI + ' ');
                    app.readyToAnalyze();
                },
                over: function (event, ui) {
                    d3.select("#column-input2")
                        .classed('btn-success', true)
                        .classed('bg-warning', false);
                },
                out: function (event, ui) {
                    d3.select("#column-input2")
                        .classed('btn-success', false)
                        .classed('bg-warning', true);
                }
                });
        $("#analyze").click(function() {
            $("#analyze").attr("disabled", "disabled");
            $("#analyze").text("Re-run");
            $("#notice").text("Performing analysis...");

            console.log(app.column1, app.column2);

            var inputs = {
                table:  {type: "table",  format: app.tableFormat,    data: app.table},
                tree:   {type: "tree",   format: "newick",           data: app.tree},
                column1: {type: "string", format: "text",             data: app.column1},
                column2: {type: "string", format: "text",             data: app.column2},
            };

            var outputs = {
                dcResultTable: {type: "table", format: "rows"}
            };

            flow.performAnalysis(app.analysisId, inputs, outputs,
                _.bind(function (error, result) {
                    app.taskId = result._id;
                    setTimeout(_.bind(app.checkResult, app), 1000);
                }, app));

        app.checkResult = function () {
            var check_url = '/item/' + this.analysisId + '/flow/' + this.taskId + '/status'
            girder.restRequest({path: check_url}).done(_.bind(function (result) {
              console.log(result.status);
              if (result.status === 'SUCCESS') {
                    // get result data
                    var result_url = '/item/' + this.analysisId + '/flow/' + this.taskId + '/result'
                    girder.restRequest({path: result_url}).done(_.bind(function (data) {
                        app.result = data.result.dcResultTable.data;

						console.log(app.result.rows[0])

                        // render results
						$("#result").append("
Results:<\h2>");
						$("#result").append("Columns analyzed: ", app.column1, app.column2, "
");
						$("#result").append("Analysis type: Pagel correlation test
");

							$("#result").append("Statistical test: likelihood ratio
")
							$("#result").append("     Likelihood ratio test statistic: ", app.result.rows[0]["lrStat"], "
")
              $("#result").append("     D.f.: ", app.result.rows[0]["lrDF"], "
")
							$("#result").append("     P-value: ", app.result.rows[0]["lrPVal"].toFixed(3), "
")

							if(app.result.rows[0]["lrPVal"] < 0.05) {
								$("#result").append("

Conclusion:  Characters are correlated (Reject the null hypothesis of no correlation).
")
							} else {
								$("#result").append("

Conclusion:  Fail to reject the null hypothesis of no correlation.
")
							}

                        $("#analyze").removeAttr("disabled");
                        $("#notice").text("Analysis succeeded!");

                    }, this));

                } else if (result.status === 'FAILURE') {
                    $("#analyze").removeAttr("disabled");
                    $("#notice").text("Analysis failed. " + result.message);
                } else {
                    setTimeout(_.bind(this.checkResult, this), 1000);
                }
            }, this));
        };

        });

        $("#help").click(function() {
            $("#upload").popover({
                title: 'Step #1',
                content: 'Upload your table (csv or tsv) and tree (newick) here',
                placement: 'bottom',
                trigger: 'manual'
            });
            $("#upload").popover('toggle');
            $("#column-input1").popover({
                title: 'Step #2',
                content: 'Drag your column of interest here',
                placement: 'left',
                trigger: 'manual'
            });
            $("#column-input1").popover('toggle');
            $("#analyze").popover({
                title: 'Step #3',
                content: 'Click on the "Go!" button',
                placement: 'bottom',
                trigger: 'manual'
            });
            $("#analyze").popover('toggle');

        });

        $("#table-preview").click(function() {
            toggleInputTablePreview();
        });

        app.render();
    });
}(window.flow, window.$, window.girder));
<commit_msg>remove bug<commit_after>/*jslint browser: true, nomen: true */

(function (flow, $, girder) {
    'use strict';

    $(document).ready(function () {
        girder.apiRoot = '/girder/api/v1';
        var app = new flow.App({
            el: 'body'
        });

        // Lookup the ID of the analysis that we wish to perform.
        app.analysisName = "discreteCorrelation-app";
        girder.restRequest({
            path: 'resource/search',
            data: {
                q: app.analysisName,
                types: JSON.stringify(["item"])
            }
        }).done(function (results) {
            app.analysisId = results["item"][0]._id;
            console.log(app.analysisId)
            app.readyToAnalyze();
        });

        app.readyToAnalyze = function () {
            if ("column1" in this && "column2" in this && "table" in this && "tree" in this &&
                "analysisId" in this) {
                d3.select("#analyze").classed('disabled', false);
            }
        };

        function toggleInputTablePreview() {
            if ($("#table-preview-icon").hasClass("glyphicon-folder-close")) {
                $("#table-preview-icon").removeClass("glyphicon-folder-close");
                $("#table-preview-icon").addClass("glyphicon-folder-open");
                $("#table-preview-text").text(" Hide input table preview");
            }
            else {
                $("#table-preview-icon").removeClass("glyphicon-folder-open");
                $("#table-preview-icon").addClass("glyphicon-folder-close");
                $("#table-preview-text").text(" Show input table preview");
            }

            $("#input-table-vis").toggle('slow');
        }

        // override upload function for simple mode
        flow.DatasetManagementView.prototype.upload = function (file) {
            var reader = new FileReader();

            reader.onload = _.bind(function (e) {
                var dataset = {
                        name: file.name,
                        data: e.target.result
                    },
                    extension = file.name.split('.'),
                    typeFormat;

                extension = extension[extension.length - 1];
                typeFormat = flow.getTypeFormatsFromExtension(extension)[0];
                typeFormat = {type: typeFormat.type, format: typeFormat.format};
                _.extend(dataset, typeFormat);
                dataset = new Backbone.Model(dataset);

                // modifications for simple app begin here
                // if its a table, get the column names
                if (typeFormat.type == "table") {
                    app.table = dataset.get('data');
                    app.tableFormat = typeFormat.format;
                    d3.select("#table-name").html('Table: ' + file.name + ' ');
                    $("#column-input1").text("Parsing column names...");
                    $("#column-names").empty();
                    flow.retrieveDatasetAsFormat(dataset, "table", "column.names", false, _.bind(function (error, dataset) {
                        var columnNames = dataset.get('data');
                        for (var i = 0; i < columnNames.length; ++i) {
                            // create drag-and-drop elements here
                            $("#column-names").append('
' + columnNames[i] + '
');
                        }
                        $(".draggable").draggable({
                             zIndex: 1, helper: "clone"
                        });
                        d3.select("#column-input1").html('Drag first column of interest here (must be a binary character) ');
                    }, this));

                    flow.retrieveDatasetAsFormat(dataset, "table", "rows", false, _.bind(function (error, dataset) {
                      // show the input table to help the user understand if their data
                      // was parsed correctly or not
                      var rowData = dataset.get('data');
                      rowData.rows = rowData.rows.slice(0, 3);
                      d3.select("#input-table-vis-container").classed('hidden', false);
                      $("#input-table-vis").table({ data: rowData });
                    }, this));

                }

                else if (typeFormat.type == "tree") {
                    app.tree = dataset.get('data');
                    d3.select("#tree-name").html('Tree: ' + file.name + ' ');
                }
                app.readyToAnalyze();

                this.datasets.off('add', null, 'set-collection').add(dataset);
            }, this);

            reader.readAsText(file);
        };

        $("#column-input1").droppable({
            drop: function( event, ui ) {
                var COI = ui.draggable.text();
                app.column1 = COI;
                d3.select("#column-input1")
                    .classed('btn-primary', true)
                    .classed('btn-success', false)
                    .classed('bg-warning', false)
                    .html(COI + ' ');
                d3.select("#column-input2")
                        .html('Now place second variable of interest here...');

                app.readyToAnalyze();
            },
            over: function (event, ui) {
                d3.select("#column-input1")
                    .classed('btn-success', true)
                    .classed('bg-warning', false);
            },
            out: function (event, ui) {
                d3.select("#column-input1")
                    .classed('btn-success', false)
                    .classed('bg-warning', true);
            }
            });

            $("#column-input2").droppable({
                drop: function( event, ui ) {
                    var COI = ui.draggable.text();
                    app.column2 = COI;
                    d3.select("#column-input2")
                        .classed('btn-primary', true)
                        .classed('btn-success', false)
                        .classed('bg-warning', false)
                        .html(COI + ' ');
                    app.readyToAnalyze();
                },
                over: function (event, ui) {
                    d3.select("#column-input2")
                        .classed('btn-success', true)
                        .classed('bg-warning', false);
                },
                out: function (event, ui) {
                    d3.select("#column-input2")
                        .classed('btn-success', false)
                        .classed('bg-warning', true);
                }
                });
        $("#analyze").click(function() {
            $("#analyze").attr("disabled", "disabled");
            $("#analyze").text("Re-run");
            $("#notice").text("Performing analysis...");

            console.log(app.column1, app.column2);

            var inputs = {
                table:  {type: "table",  format: app.tableFormat,    data: app.table},
                tree:   {type: "tree",   format: "newick",           data: app.tree},
                column1: {type: "string", format: "text",             data: app.column1},
                column2: {type: "string", format: "text",             data: app.column2},
            };

            var outputs = {
                dcResultTable: {type: "table", format: "rows"}
            };

            flow.performAnalysis(app.analysisId, inputs, outputs,
                _.bind(function (error, result) {
                    app.taskId = result._id;
                    setTimeout(_.bind(app.checkResult, app), 1000);
                }, app));

        app.checkResult = function () {
            var check_url = '/item/' + this.analysisId + '/flow/' + this.taskId + '/status'
            girder.restRequest({path: check_url}).done(_.bind(function (result) {
              console.log(result.status);
              if (result.status === 'SUCCESS') {
                    // get result data
                    var result_url = '/item/' + this.analysisId + '/flow/' + this.taskId + '/result'
                    girder.restRequest({path: result_url}).done(_.bind(function (data) {
                        app.result = data.result.dcResultTable.data;

						console.log(app.result.rows[0])

                        // render results
						$("#result").append("
Results:<\h2>");
						$("#result").append("Columns analyzed: ", app.column1, app.column2, "
");
						$("#result").append("Analysis type: Pagel correlation test
");

							$("#result").append("Statistical test: likelihood ratio
")
							$("#result").append("     Likelihood ratio test statistic: ", app.result.rows[0]["lrStat"], "
")
              $("#result").append("     D.f.: ", app.result.rows[0]["lrDF"], "
")
							$("#result").append("     P-value: ", app.result.rows[0]["lrPVal"], "
")

							if(app.result.rows[0]["lrPVal"] < 0.05) {
								$("#result").append("

Conclusion:  Characters are correlated (Reject the null hypothesis of no correlation).
")
							} else {
								$("#result").append("

Conclusion:  Fail to reject the null hypothesis of no correlation.
")
							}

                        $("#analyze").removeAttr("disabled");
                        $("#notice").text("Analysis succeeded!");

                    }, this));

                } else if (result.status === 'FAILURE') {
                    $("#analyze").removeAttr("disabled");
                    $("#notice").text("Analysis failed. " + result.message);
                } else {
                    setTimeout(_.bind(this.checkResult, this), 1000);
                }
            }, this));
        };

        });

        $("#help").click(function() {
            $("#upload").popover({
                title: 'Step #1',
                content: 'Upload your table (csv or tsv) and tree (newick) here',
                placement: 'bottom',
                trigger: 'manual'
            });
            $("#upload").popover('toggle');
            $("#column-input1").popover({
                title: 'Step #2',
                content: 'Drag your column of interest here',
                placement: 'left',
                trigger: 'manual'
            });
            $("#column-input1").popover('toggle');
            $("#analyze").popover({
                title: 'Step #3',
                content: 'Click on the "Go!" button',
                placement: 'bottom',
                trigger: 'manual'
            });
            $("#analyze").popover('toggle');

        });

        $("#table-preview").click(function() {
            toggleInputTablePreview();
        });

        app.render();
    });
}(window.flow, window.$, window.girder));
<|endoftext|>


<commit_before>'use strict';

var hyphenToCamel      = require('es5-ext/string/#/hyphen-to-camel')
  , endsWith           = require('es5-ext/string/#/ends-with')
  , ensureCallable     = require('es5-ext/object/valid-callable')
  , ensureObject       = require('es5-ext/object/valid-object')
  , ensureString       = require('es5-ext/object/validate-stringifiable-value')
  , debug              = require('debug-ext')('zip-archiver')
  , ensureDatabase     = require('dbjs/valid-dbjs')
  , createWriteStream  = require('fs').createWriteStream
  , unlink             = require('fs2/unlink')
  , path               = require('path')
  , archiver           = require('archiver')
  , resolveArchivePath = require('../utils/resolve-document-archive-path')

  , resolve = path.resolve, basename = path.basename;

var re = new RegExp('^\\/business-process-document-archive-([0-9][0-9a-z]+)-' +
	'(requirement|receipt|certificate)-([a-z][a-z0-9-]*)\\.zip$');

var unlinkDocumentFiles = function (uploadsPath, document) {
	var filename = resolve(uploadsPath, resolveArchivePath(document));
	unlink(filename).done(null, function (err) {
		if (err.code === 'ENOENT') return;
		debug("Could not remove file %s %s", filename, err.stack);
	});
};

exports.filenameResetService = function (db, data) {
	var uploadsPath;
	ensureDatabase(db);
	ensureObject(data);
	uploadsPath = ensureString(data.uploadsPath);
	db.objects.on('update', function (event) {
		var id = event.object.__valueId__, bp = event.object.master;
		if (!(bp instanceof db.BusinessProcessBase)) return;
		if (!bp.dataForms || !bp.dataForms.map) return;
		if (!endsWith.call(id, '/submissionForms/isAffidavitSigned')) return;
		bp.requirementUploads.applicable.forEach(function (upload) {
			unlinkDocumentFiles(uploadsPath, upload.document);
		});
		bp.paymentReceiptUploads.applicable.forEach(function (upload) {
			unlinkDocumentFiles(uploadsPath, upload.document);
		});
		bp.certificates.applicable.forEach(function (document) {
			unlinkDocumentFiles(uploadsPath, document);
		});
	});
};

exports.archiveServer = function (db, data) {
	var uploadsPath, isDev, stMiddleware;
	ensureDatabase(db);
	ensureObject(data);
	uploadsPath = ensureString(data.uploadsPath);
	isDev = ensureObject(data.env).dev;
	stMiddleware = ensureCallable(data.stMiddleware);
	return function (req, res, next) {
		var url = req._parsedUrl.pathname, match = url.match(re), bp, archive, archiveFile
		  , onError, key, target, fileIdx = 0;
		if (!match) {
			next();
			return;
		}
		bp = db.BusinessProcessBase.getById(match[1]);
		if (!bp || !bp.isSubmitted) {
			res.statusCode = 404;
			res.end('Not Found');
			return;
		}
		key = hyphenToCamel.call(match[3]);
		if (match[2] === 'requirement') {
			bp.requirementUploads.applicable.some(function (upload) {
				if (upload.document.uniqueKey === key) {
					target = upload.document;
					return true;
				}
			});
		} else if (match[2] === 'receipt') {
			target = bp.paymentReceiptUploads.map.get(key);
			if (target && !bp.paymentReceiptUploads.applicable.has(target)) target = null;
			if (target) target = target.document;
		} else {
			target = bp.certificates.map.get(key);
			if (target && !bp.certificates.applicable.has(target)) target = null;
		}
		if (!target || (target.files.ordered <= 1)) {
			res.statusCode = 404;
			res.end('Not Found');
			return;
		}
		debug("generate archive for %s", target.__id__);
		archive = archiver('zip', { level: 0 });
		archiveFile = createWriteStream(resolve(uploadsPath, url.slice(1)));
		archiveFile.on('error', onError = function (error) {
			if (!error) return;
			if (isDev) throw error;
			debug("cannot produce archive for %s %s", target.__id__, error.stack);
			res.statusCode = 500;
			res.end('Server error');
		});
		archive.pipe(archiveFile);
		target.files.ordered.forEach(function (file) {
			// Change filename from form 'file-skey-buniness-name-document-label.xxx' to
			// 'buniness-name-document-label-index.xxx' for ux reasons.
			var name = basename(file.path).replace(/^[\d\w]+-/, '').split('.');
			name[0] += '-' + String(++fileIdx);

			archive.file(resolve(uploadsPath, file.path), {
				name: name.join('.')
			});
		});
		archive.finalize(onError);
		archive.on('error', onError);
		archiveFile.on('error', onError);
		archiveFile.on('close', function () {
			debug("finalised generation of archive for %s", target.__id__);
			stMiddleware(req, res, next);
		});
	};
};
<commit_msg>Improve documents archiver<commit_after>'use strict';

var hyphenToCamel      = require('es5-ext/string/#/hyphen-to-camel')
  , endsWith           = require('es5-ext/string/#/ends-with')
  , ensureCallable     = require('es5-ext/object/valid-callable')
  , ensureObject       = require('es5-ext/object/valid-object')
  , ensureString       = require('es5-ext/object/validate-stringifiable-value')
  , debug              = require('debug-ext')('zip-archiver')
  , ensureDatabase     = require('dbjs/valid-dbjs')
  , createWriteStream  = require('fs').createWriteStream
  , unlink             = require('fs2/unlink')
  , path               = require('path')
  , archiver           = require('archiver')
  , resolveArchivePath = require('../utils/resolve-document-archive-path')

  , resolve = path.resolve, basename = path.basename;

var re = new RegExp('^\\/business-process-document-archive-([0-9][0-9a-z]+)-' +
	'(requirement|receipt|certificate)-([a-z][a-z0-9-]*)\\.zip$');

var unlinkDocumentFiles = function (uploadsPath, document) {
	var filename = resolve(uploadsPath, resolveArchivePath(document));
	unlink(filename).done(null, function (err) {
		if (err.code === 'ENOENT') return;
		debug("Could not remove file %s %s", filename, err.stack);
	});
};

var isArchivable = function (document) {
	var owner = document.owner && document.owner.owner;
	if (!owner) return false;
	if (owner.key === 'certificates') return true;
	owner = owner.owner;
	if (!owner) return false;
	if (owner.key === 'requirementUploads') return true;
	if (owner.key === 'paymentReceiptUploads') return true;
};

exports.filenameResetService = function (db, data) {
	var uploadsPath;
	ensureDatabase(db);
	ensureObject(data);
	uploadsPath = ensureString(data.uploadsPath);
	db.objects.on('update', function (event) {
		if (event.sourceId === 'persistentLayer') return;
		var id = event.object.__valueId__, bp = event.object.master, document, file;
		if (!(bp instanceof db.BusinessProcess)) return;
		if (!bp.isSubmitted) return;
		if (!endsWith.call(id, '/path')) return;
		if (endsWith.call(id, '/thumb/path')) return;
		if (endsWith.call(id, '/preview/path')) return;
		file = event.object.object;
		document = file.owner && file.owner.owner && file.owner.owner.owner;
		if (!(document instanceof db.Document) || !isArchivable(document)) return;
		unlinkDocumentFiles(uploadsPath, document);
	});
};

exports.archiveServer = function (db, data) {
	var uploadsPath, isDev, stMiddleware;
	ensureDatabase(db);
	ensureObject(data);
	uploadsPath = ensureString(data.uploadsPath);
	isDev = ensureObject(data.env).dev;
	stMiddleware = ensureCallable(data.stMiddleware);
	return function (req, res, next) {
		var url = req._parsedUrl.pathname, match = url.match(re), bp, archive, archiveFile
		  , onError, key, target, fileIdx = 0;
		if (!match) {
			next();
			return;
		}
		bp = db.BusinessProcessBase.getById(match[1]);
		if (!bp || !bp.isSubmitted) {
			res.statusCode = 404;
			res.end('Not Found');
			return;
		}
		key = hyphenToCamel.call(match[3]);
		if (match[2] === 'requirement') {
			bp.requirementUploads.applicable.some(function (upload) {
				if (upload.document.uniqueKey === key) {
					target = upload.document;
					return true;
				}
			});
		} else if (match[2] === 'receipt') {
			target = bp.paymentReceiptUploads.map.get(key);
			if (target && !bp.paymentReceiptUploads.applicable.has(target)) target = null;
			if (target) target = target.document;
		} else {
			target = bp.certificates.map.get(key);
			if (target && !bp.certificates.applicable.has(target)) target = null;
		}
		if (!target || (target.files.ordered <= 1)) {
			res.statusCode = 404;
			res.end('Not Found');
			return;
		}
		debug("generate archive for %s", target.__id__);
		archive = archiver('zip', { level: 0 });
		archiveFile = createWriteStream(resolve(uploadsPath, url.slice(1)));
		archiveFile.on('error', onError = function (error) {
			if (!error) return;
			if (isDev) throw error;
			debug("cannot produce archive for %s %s", target.__id__, error.stack);
			res.statusCode = 500;
			res.end('Server error');
		});
		archive.pipe(archiveFile);
		target.files.ordered.forEach(function (file) {
			// Change filename from form 'file-skey-buniness-name-document-label.xxx' to
			// 'buniness-name-document-label-index.xxx' for ux reasons.
			var name = basename(file.path).replace(/^[\d\w]+-/, '').split('.');
			name[0] += '-' + String(++fileIdx);

			archive.file(resolve(uploadsPath, file.path), {
				name: name.join('.')
			});
		});
		archive.finalize(onError);
		archive.on('error', onError);
		archiveFile.on('error', onError);
		archiveFile.on('close', function () {
			debug("finalised generation of archive for %s", target.__id__);
			stMiddleware(req, res, next);
		});
	};
};
<|endoftext|>


<commit_before>define([
    'jquery',
    'Underscore',
    'Backbone',
    'models/expense',
    'text!../../tpl/expense-detail.html'
], function ($, _, Backbone, expense, template) {
    var ExpenseDetailsView = Backbone.View.extend({
        self:this,
        initialize:function () {
            this.model.on("reset", this.render, this);
            this.model.on("sync", this.render, this);
        },
        events:{
            "click #put":"saveExpense",
            "click #add":"addLine"
        },

        renderTemplate:function (json) {
            var $element = $(_.template(template, json));
            _.each(json.lines, function (line, index) {
                var selectedOption = $element.find('#expenseType').eq(index).children('option[value=' + line.expenseType + ']');
                selectedOption.attr('selected', true);
            });
            return $element;
        },

        render:function () {
            console.log("render expense");
            var $element = this.renderTemplate(this.model.toJSON());
            this.setElement($element);
            $('#content').replaceWith($element);
        },

        saveExpense:function () {
            var elements = $('#content td#expense-line');
            var view = this;
            var lines = _.map(elements, function (template) {
                t = $(template);
                return {
                    "expense":(+t.find('#amount').val()),
                    "description":t.find('#description').val(),
                    "valueDate":t.find('#valueDate').val(),
                    "expenseType":t.find('#expenseType').val(),
                    "id":null,
                    "expenseReportId":null,
                    "account":"Xebia"
                };
            });
            if (this.model.isNew()) {
                this.model.unset('id')
            }
            this.model.save({
                startDate:$('#startDate').val(),
                endDate:$('#endDate').val(),
                total:$('#total').val(),
                lines:lines
            });
            return false;
        },
        addLine:function () {
            var $table = $("#content table");
            var $element = this.renderTemplate(this.model.defaults);
            $table.append($element.find('table tbody tr'));
        },
        close:function () {
            $(this.el).unbind();
            $(this.el).empty();
        }

    });
    return ExpenseDetailsView;
});
<commit_msg>simplify setting the correct value on the combo boxes<commit_after>define([
    'jquery',
    'Underscore',
    'Backbone',
    'models/expense',
    'text!../../tpl/expense-detail.html'
], function ($, _, Backbone, expense, template) {
    var ExpenseDetailsView = Backbone.View.extend({
        self:this,
        initialize:function () {
            this.model.on("reset", this.render, this);
            this.model.on("sync", this.render, this);
        },
        events:{
            "click #put":"saveExpense",
            "click #add":"addLine"
        },

        renderTemplate:function (json) {
            var $expenseElement = $(_.template(template, json));
            _.each(json.lines, function (line, index) {
                $expenseElement.find('#expenseType')[index].value=line.expenseType;
            });
            return $expenseElement;
        },

        render:function () {
            var $element = this.renderTemplate(this.model.toJSON());
            this.setElement($element);
            $('#content').replaceWith($element);
        },

        saveExpense:function () {
            var elements = $('#content td#expense-line');
            var view = this;
            var lines = _.map(elements, function (template) {
                t = $(template);
                return {
                    "expense":(+t.find('#amount').val()),
                    "description":t.find('#description').val(),
                    "valueDate":t.find('#valueDate').val(),
                    "expenseType":t.find('#expenseType').val(),
                    "account":"Xebia"
                };
            });
            if (this.model.isNew()) {
                this.model.unset('id')
            }
            this.model.save({
                startDate:$('#startDate').val(),
                endDate:$('#endDate').val(),
                total:$('#total').val(),
                lines:lines
            });
            return false;
        },
        addLine:function () {
            var $table = $("#content table");
            var $element = this.renderTemplate(this.model.defaults);
            $table.append($element.find('table tbody tr'));
        },
        close:function () {
            $(this.el).unbind();
            $(this.el).empty();
        }

    });
    return ExpenseDetailsView;
});
<|endoftext|>


<commit_before>import { createReducer } from 'redux-act';

import { queryDiagrams, fetchCollectionDiagrams, fetchDiagram, updateDiagram, createDiagram, deleteDiagram } from 'src/actions';
import { objectLoadComplete, objectDelete, resultObjects } from 'src/reducers/util';

const initialState = {};

export default createReducer({
  // [fetchCollectionDiagrams.START]: (state, { data }) => resultObjects(state, data),
  //
  // [fetchCollectionDiagrams.ERROR]: (state, {
  //   error, args: { diagramId },
  // }) => objectLoadError(state, diagramId, error),

  [queryDiagrams.COMPLETE]: (state, { result }) => resultObjects(state, result),

  [fetchCollectionDiagrams.COMPLETE]: (state, { data }) => resultObjects(state, data),

  [fetchDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [createDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [updateDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [deleteDiagram.COMPLETE]: (state, {
    diagramId,
  }) => objectDelete(state, diagramId),

}, initialState);
<commit_msg>handled diagram fetch error<commit_after>import { createReducer } from 'redux-act';

import { queryDiagrams, fetchCollectionDiagrams, fetchDiagram, updateDiagram, createDiagram, deleteDiagram } from 'src/actions';
import { objectLoadComplete, objectLoadError, objectDelete, resultObjects } from 'src/reducers/util';

const initialState = {};

export default createReducer({
  // [fetchCollectionDiagrams.START]: (state, { data }) => resultObjects(state, data),
  //
  // [fetchCollectionDiagrams.ERROR]: (state, {
  //   error, args: { diagramId },
  // }) => objectLoadError(state, diagramId, error),

  [queryDiagrams.COMPLETE]: (state, { result }) => resultObjects(state, result),

  [fetchCollectionDiagrams.COMPLETE]: (state, { data }) => resultObjects(state, data),

  [fetchDiagram.ERROR]: (state, {
    error, args,
  }) => objectLoadError(state, args, error),

  [fetchDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [createDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [updateDiagram.COMPLETE]: (state, {
    diagramId, data,
  }) => objectLoadComplete(state, diagramId, data),

  [deleteDiagram.COMPLETE]: (state, {
    diagramId,
  }) => objectDelete(state, diagramId),

}, initialState);
<|endoftext|>