<commit_before>var BDB = BDB || {};

BDB.Geolocation = (function(){
  let positionWatcher;
  let geocoder;
  let currentPosition = false;

  let persistLocation = function(position){
    currentPosition = position;
    let newstring = JSON.stringify(position,[
      'latitude',
      'longitude'])
    //other attributes the coords may have.
    /*'accuracy',
            'heading',
            'altitude',
            'speed',
            'altitudeAccuracy']);*/
    localStorage.setItem("BDB.LatestPosition", newstring);
  };

  let retrieveLocation = function(){
    let stringPos = localStorage.getItem("BDB.LatestPosition");
    let pos = JSON.parse(stringPos);
    if (pos && typeof pos === 'object'){
      currentPosition = pos;
      return currentPosition;
    } else {
      return false;
    }
  };

  let geolocate = function(param = {}){
    // set default options to geolocate
    let defaults = {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 500
    };

    let settings = Object.assign({}, defaults, param);

    let result = {
      statusOk : false,
      center : false,
      response : {}
    }

    let Location = new Promise(function(resolve,reject){
      if (positionWatcher){
        result.statusOk = true;
        result.center = true;
        result.response = currentPosition;
        resolve(result);
      } else {
        if (navigator.geolocation) {
          clearGeoWatch();
          navigator.geolocation.getCurrentPosition(
            position => {
              result.statusOk = true;
              result.center = true;
              result.response = position.coords;
              persistLocation(result.response);
              geoWatch(settings);
              resolve(result);
            },
            error => {
              result.response = error;
              reject(result);
            },
            settings
          );

        } else {
          let error = {code: 1}
          reject(error);
        }
      }
    });

    Location.then(geolocateDone, geolocateDone);

    return Location;
  };
  let geolocateDone = function(response){
    let event = new CustomEvent('geolocation:done', {detail: response});
    document.dispatchEvent(event);
  };
  let geoWatch = function(options){
    positionWatcher = navigator.geolocation.watchPosition(position => {
      let result = {
        statusOk: true,
        center: false,
        response : position.coords
      };
      persistLocation(position.coords);
      geolocateDone(result);
    }, error => {
      let result = {
        statusOk: false,
        center: false,
        response : error
      };
      geolocateDone(result);
    }, null, options);
  };
  let clearGeoWatch = function(){
    if (positionWatcher) {
      navigator.geolocation.clearWatch(positionWatcher);
    }
  };
  return {
    getLastestLocation: function(){
      return retrieveLocation();
    },
    getLocation : function(options = false){
      return geolocate(options);
    },
    forceLocation : function(coords){
      persistLocation(coords);
    },
    checkPermission : function(){
      if (navigator.permissions) {
        return navigator.permissions.query({'name': 'geolocation'});
      } else {
        let fallback = new Promise(function(resolve,reject){
          reject(false);
        });
        return fallback;
      }
    },
    clearWatch : function(){
      clearGeoWatch();
    },
    getCurrentPosition: function() {
      return currentPosition;
    }
  }
})();<commit_msg>Removes geolocation timeout<commit_after>var BDB = BDB || {};

BDB.Geolocation = (function(){
  let positionWatcher;
  let geocoder;
  let currentPosition = false;

  let persistLocation = function(position){
    currentPosition = position;
    let newstring = JSON.stringify(position,[
      'latitude',
      'longitude'])
    //other attributes the coords may have.
    /*'accuracy',
            'heading',
            'altitude',
            'speed',
            'altitudeAccuracy']);*/
    localStorage.setItem("BDB.LatestPosition", newstring);
  };

  let retrieveLocation = function(){
    let stringPos = localStorage.getItem("BDB.LatestPosition");
    let pos = JSON.parse(stringPos);
    if (pos && typeof pos === 'object'){
      currentPosition = pos;
      return currentPosition;
    } else {
      return false;
    }
  };

  let geolocate = function(param = {}){
    // set default options to geolocate
    let defaults = {
      enableHighAccuracy: true,
      // timeout: 10000, //dont think we need that, since it doesnt block the UI like before
      maximumAge: 500
    };

    let settings = Object.assign({}, defaults, param);

    let result = {
      statusOk : false,
      center : false,
      response : {}
    }

    let Location = new Promise(function(resolve,reject){
      if (positionWatcher){
        result.statusOk = true;
        result.center = true;
        result.response = currentPosition;
        resolve(result);
      } else {
        if (navigator.geolocation) {
          clearGeoWatch();
          navigator.geolocation.getCurrentPosition(
            position => {
              result.statusOk = true;
              result.center = true;
              result.response = position.coords;
              persistLocation(result.response);
              geoWatch(settings);
              resolve(result);
            },
            error => {
              result.response = error;
              reject(result);
            },
            settings
          );

        } else {
          let error = {code: 1}
          reject(error);
        }
      }
    });

    Location.then(geolocateDone, geolocateDone);

    return Location;
  };
  let geolocateDone = function(response){
    let event = new CustomEvent('geolocation:done', {detail: response});
    document.dispatchEvent(event);
  };
  let geoWatch = function(options){
    positionWatcher = navigator.geolocation.watchPosition(position => {
      let result = {
        statusOk: true,
        center: false,
        response : position.coords
      };
      persistLocation(position.coords);
      geolocateDone(result);
    }, error => {
      let result = {
        statusOk: false,
        center: false,
        response : error
      };
      geolocateDone(result);
    }, null, options);
  };
  let clearGeoWatch = function(){
    if (positionWatcher) {
      navigator.geolocation.clearWatch(positionWatcher);
    }
  };
  return {
    getLastestLocation: function(){
      return retrieveLocation();
    },
    getLocation : function(options = false){
      return geolocate(options);
    },
    forceLocation : function(coords){
      persistLocation(coords);
    },
    checkPermission : function(){
      if (navigator.permissions) {
        return navigator.permissions.query({'name': 'geolocation'});
      } else {
        let fallback = new Promise(function(resolve,reject){
          reject(false);
        });
        return fallback;
      }
    },
    clearWatch : function(){
      clearGeoWatch();
    },
    getCurrentPosition: function() {
      return currentPosition;
    }
  }
})();<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.controllers', [])
        .controller('LandingPageController', [function(){

        }])
        .controller('WaitlistController', ['$scope', '$firebase', function($scope, $firebase){
             var partiesRef = new Firebase('https://waitandeat-krishna.firebaseio.com/');

             $scope.parties = $firebase(partiesRef);

             $scope.party = {name : '', phone : '', size : ''};

             $scope.saveParty = function() {
               $scope.parties.$add($scope.party);
               $scope.party = {name : '', phone : '', size : ''};
             };

             $scope.sendTextMessage = function(phoneNumber){
                 var textMessageRef = new Firebase('https://waitandeat-krishna.firebaseio.com/textMessages');
                 var textMessages = $firebase(textMessageRef);
                 textMessages.$add({phoneNumber : phoneNumber});
             };
        }]);<commit_msg>Adding "parties" to the firebase<commit_after>'use strict';

angular.module('myApp.controllers', [])
        .controller('LandingPageController', [function(){

        }])
        .controller('WaitlistController', ['$scope', '$firebase', function($scope, $firebase){
             var partiesRef = new Firebase('https://waitandeat-krishna.firebaseio.com/parties');

             $scope.parties = $firebase(partiesRef);

             $scope.party = {name : '', phone : '', size : ''};

             $scope.saveParty = function() {
               $scope.parties.$add($scope.party);
               $scope.party = {name : '', phone : '', size : ''};
             };

             $scope.sendTextMessage = function(phoneNumber){
                 var textMessageRef = new Firebase('https://waitandeat-krishna.firebaseio.com/textMessages');
                 var textMessages = $firebase(textMessageRef);
                 textMessages.$add({phoneNumber : phoneNumber});
             };
        }]);<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)

if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
  console.log('Usage: ucompiler go|watch [path]')
  process.exit(0)
}

if (parameters[0] === 'go') {
  UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
    console.error(e)
    process.exit(1)
  })
}
<commit_msg>:new: Use UCompiler.watch in CLI<commit_after>#!/usr/bin/env node
'use strict'

require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)

if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
  console.log('Usage: ucompiler go|watch [path]')
  process.exit(0)
}

if (parameters[0] === 'go') {
  UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
    console.error(e)
    process.exit(1)
  })
} else if (parameters[0] === 'watch') {
  if (!parameters[1]) {
    console.error('You must specify a path to watch')
    process.exit(1)
  }
  UCompiler.watch(parameters[1])
}
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var analyticsControllers = angular.module('analyticsControllers', []);

/**
 * Dashboard Controller
 */
analyticsControllers.controller('DashboardCtrl', ['$scope', 'KApi', 'DashboardSvc',
    function($scope, KApi, DashboardSvc) {

		/**
		 * entries currently on display
		 */
		var entries = [];

		/**
		 * number of entries in page
		 */
		var pageSize = 5;

		/**
		 * total number of pages
		 */
		var totalPages = 1;

		var updatePagingControlRequired = true;

		/**
		 * get data for the aggregates line
		 */
		var getAggregates = function getAggregates(liveOnly) {
			DashboardSvc.getAggregates(liveOnly).then (function(data) {
				var o = data.objects[0];
				var results = [
				           	{"title": "audience", "value": liveOnly ? o.audience : o.plays},
				        	{"title": "seconds_viewed", "value": o.secondsViewed},
				        	{"title": "buffertime", "value": o.bufferTime},
				        	{"title": "bitrate", "value": o.avgBitrate}
				        ];

				$scope.aggregates = results;
			});
		};

		/**
		 * @param liveOnly	fetch KalturaLive currently live (true) or all live entries (false)
		 * @param pageNumber index of page to fetch
		 */
		var getEntries = function getEntries(liveOnly, pageNumber) {
			var result;
			if (liveOnly) {
				result = DashboardSvc.getLiveEntries(pageNumber);
			}
			else {
				result = DashboardSvc.getAllEntries(pageNumber);
			}

			result.then(function(data) {
				$scope.entries = data.objects;
				totalPages = Math.ceil(data.totalCount/pageSize);
				if (updatePagingControlRequired) {
					updatePagingControl(pageNumber, totalPages);
					updatePagingControlRequired = false;
				}
			});
		};

		/**
		 * get entries data by page
		 * @param e
		 * @param oldPage
		 * @param newPage
		 */
		var doPaging = function doPaging(e,oldPage,newPage) {
			getEntries($scope.boardType == "liveOnly", newPage);
		};

		/**
		 * update paging control
		 * @param current	index of current page
		 * @param total		total number of pages
		 */
		var updatePagingControl = function updatePagingControl(current, total) {
			var options = {
	                currentPage: current,
	                totalPages: total
	            };
	        $('#pagination').bootstrapPaginator(options);
		};

		/**
		 * initial screen set up
		 */
		var screenSetup = function screenSetup() {
			// set report dates:
			var d = new Date();
			$scope.nowTime = d;
			d = new Date();
			d.setHours(d.getHours() - 36);
			$scope.reportStartTime = d;

			var options = {
					bootstrapMajorVersion: 3,
					onPageChanged: doPaging,
					shouldShowPage:function(type, page, current){
		                switch(type) {
		                    case "first":
		                    case "last":
		                        return false;
		                    default:
		                        return true;
		                }
		            },
		            alignment: 'center',
		            currentPage: 1,
		            totalPages: totalPages
		    };

		    $('#pagination').bootstrapPaginator(options);

		    $scope.boardType = "all";
			$scope.$watch("boardType", function(newValue, oldValue) {
				getAggregates(newValue == "liveOnly");
	    		getEntries(newValue == "liveOnly", 1);
				updatePagingControlRequired = true;
			 });
		};

		screenSetup();

    }]);

/**
 * General controller for the entry drill-down page
 */
analyticsControllers.controller('EntryCtrl', ['$scope', '$rootScope', '$routeParams', '$interval', 'PID', 'EntrySvc',
    function($scope, $rootScope, $routeParams, $interval, PID, EntrySvc) {
		$scope.intervalPromise = null; 			// use this to hold update interval
		$scope.entryId = $routeParams.entryid;	// current entry
		$scope.pid = PID;
		$scope.uiconfId = 22767782;
		$scope.playerEntryId = '';				// entry that should be shown in player (live / vod)

		/**
		 * get data for the aggregates line
		 * @param isLive is the entry currently broadcasting
		 */
		var getAggregates = function getAggregates(isLive) {
			EntrySvc.getAggregates($scope.entryId, isLive).then (function(data) {
				var o = data.objects[0];
				var results = [
				           	{"title": "audience", "value": isLive ? o.audience : o.plays},
				        	{"title": "seconds_viewed", "value": o.secondsViewed},
				        	{"title": "buffertime", "value": o.bufferTime},
				        	{"title": "bitrate", "value": o.avgBitrate}
				        ];

				$scope.aggregates = results;
				getReferrers(isLive ? o.audience : o.plays);
			});
		};

		/**
		 * get data for the top referrals table
		 * @param totalPlays
		 */
		var getReferrers = function getReferrers(totalPlays) {
			EntrySvc.getReferrers($scope.entryId).then (function(data) {
				var objects = data.objects;
				var results = new Array();
				var o;
				for (var i = 0; i<objects.length; i++) {
					o = {
							'domain': objects[i].referrer,
							'visits': objects[i].plays,
							'percents' : objects[i].plays / totalPlays
						};
					results.push(o);
				}
				$scope.referals = results;
			});
		};

		/**
		 * get the entry in question
		 */
		var getEntry = function getEntry() {
			return EntrySvc.getEntry($scope.entryId).then(function(entry){
				$scope.entry = entry;
				if (entry.isLive) {
					// live session - show live entry in player
					$scope.playerEntryId = entry.id;
					// set 30 secs update interval
					$scope.intervalPromise = $interval(function() {screenUpdate();}, 30000);
				}
				else if (entry.recordedEntryId && entry.recordedEntryId != '') {
					// session ended, got recording - show recorded entry in player
					$scope.playerEntryId = entry.recordedEntryId;
					//TODO in graph, only show recorded duration (how ??)
				}
				else {
					// show "no recording" in player
					$scope.playerEntryId = -1;
					// set 30 secs update interval
					$scope.intervalPromise = $interval(function() {screenUpdate();}, 30000);
				}
				// set report dates:
				var d = new Date();
				$rootScope.$broadcast('setupScreen', d.getTime());
				d.setTime(entry.createdAt);
				$scope.reportStartTime = d;
				getAggregates(entry.isLive);

			});
		};

		var screenSetup = function screenSetup() {
			// report data:
			getEntry();
		};

		var screenUpdate = function screenUpdate() {
			var d = new Date();
			var t = d.getTime();
			getAggregates($scope.entry.isLive);
			$rootScope.$broadcast('updateScreen', t);
		};

		$scope.$on('$destroy', function() {
			// Make sure that the interval is destroyed too
			if (angular.isDefined($scope.intervalPromise)) {
				$interval.cancel(stop);
				$scope.intervalPromise = undefined;
			}
		});

		screenSetup();
}]);

<commit_msg>don't inject unnecessary service KApi<commit_after>'use strict';

/* Controllers */

var analyticsControllers = angular.module('analyticsControllers', []);

/**
 * Dashboard Controller
 */
analyticsControllers.controller('DashboardCtrl', ['$scope', 'DashboardSvc',
    function($scope, DashboardSvc) {

		/**
		 * entries currently on display
		 */
		var entries = [];

		/**
		 * number of entries in page
		 */
		var pageSize = 5;

		/**
		 * total number of pages
		 */
		var totalPages = 1;

		var updatePagingControlRequired = true;

		/**
		 * get data for the aggregates line
		 */
		var getAggregates = function getAggregates(liveOnly) {
			DashboardSvc.getAggregates(liveOnly).then (function(data) {
				var o = data.objects[0];
				var results = [
				           	{"title": "audience", "value": liveOnly ? o.audience : o.plays},
				        	{"title": "seconds_viewed", "value": o.secondsViewed},
				        	{"title": "buffertime", "value": o.bufferTime},
				        	{"title": "bitrate", "value": o.avgBitrate}
				        ];

				$scope.aggregates = results;
			});
		};

		/**
		 * @param liveOnly	fetch KalturaLive currently live (true) or all live entries (false)
		 * @param pageNumber index of page to fetch
		 */
		var getEntries = function getEntries(liveOnly, pageNumber) {
			var result;
			if (liveOnly) {
				result = DashboardSvc.getLiveEntries(pageNumber);
			}
			else {
				result = DashboardSvc.getAllEntries(pageNumber);
			}

			result.then(function(data) {
				$scope.entries = data.objects;
				totalPages = Math.ceil(data.totalCount/pageSize);
				if (updatePagingControlRequired) {
					updatePagingControl(pageNumber, totalPages);
					updatePagingControlRequired = false;
				}
			});
		};

		/**
		 * get entries data by page
		 * @param e
		 * @param oldPage
		 * @param newPage
		 */
		var doPaging = function doPaging(e,oldPage,newPage) {
			getEntries($scope.boardType == "liveOnly", newPage);
		};

		/**
		 * update paging control
		 * @param current	index of current page
		 * @param total		total number of pages
		 */
		var updatePagingControl = function updatePagingControl(current, total) {
			var options = {
	                currentPage: current,
	                totalPages: total
	            };
	        $('#pagination').bootstrapPaginator(options);
		};

		/**
		 * initial screen set up
		 */
		var screenSetup = function screenSetup() {
			// set report dates:
			var d = new Date();
			$scope.nowTime = d;
			d = new Date();
			d.setHours(d.getHours() - 36);
			$scope.reportStartTime = d;

			var options = {
					bootstrapMajorVersion: 3,
					onPageChanged: doPaging,
					shouldShowPage:function(type, page, current){
		                switch(type) {
		                    case "first":
		                    case "last":
		                        return false;
		                    default:
		                        return true;
		                }
		            },
		            alignment: 'center',
		            currentPage: 1,
		            totalPages: totalPages
		    };

		    $('#pagination').bootstrapPaginator(options);

		    $scope.boardType = "all";
			$scope.$watch("boardType", function(newValue, oldValue) {
				getAggregates(newValue == "liveOnly");
	    		getEntries(newValue == "liveOnly", 1);
				updatePagingControlRequired = true;
			 });
		};

		screenSetup();

    }]);

/**
 * General controller for the entry drill-down page
 */
analyticsControllers.controller('EntryCtrl', ['$scope', '$rootScope', '$routeParams', '$interval', 'PID', 'EntrySvc',
    function($scope, $rootScope, $routeParams, $interval, PID, EntrySvc) {
		$scope.intervalPromise = null; 			// use this to hold update interval
		$scope.entryId = $routeParams.entryid;	// current entry
		$scope.pid = PID;
		$scope.uiconfId = 22767782;
		$scope.playerEntryId = '';				// entry that should be shown in player (live / vod)

		/**
		 * get data for the aggregates line
		 * @param isLive is the entry currently broadcasting
		 */
		var getAggregates = function getAggregates(isLive) {
			EntrySvc.getAggregates($scope.entryId, isLive).then (function(data) {
				var o = data.objects[0];
				var results = [
				           	{"title": "audience", "value": isLive ? o.audience : o.plays},
				        	{"title": "seconds_viewed", "value": o.secondsViewed},
				        	{"title": "buffertime", "value": o.bufferTime},
				        	{"title": "bitrate", "value": o.avgBitrate}
				        ];

				$scope.aggregates = results;
				getReferrers(isLive ? o.audience : o.plays);
			});
		};

		/**
		 * get data for the top referrals table
		 * @param totalPlays
		 */
		var getReferrers = function getReferrers(totalPlays) {
			EntrySvc.getReferrers($scope.entryId).then (function(data) {
				var objects = data.objects;
				var results = new Array();
				var o;
				for (var i = 0; i<objects.length; i++) {
					o = {
							'domain': objects[i].referrer,
							'visits': objects[i].plays,
							'percents' : objects[i].plays / totalPlays
						};
					results.push(o);
				}
				$scope.referals = results;
			});
		};

		/**
		 * get the entry in question
		 */
		var getEntry = function getEntry() {
			return EntrySvc.getEntry($scope.entryId).then(function(entry){
				$scope.entry = entry;
				if (entry.isLive) {
					// live session - show live entry in player
					$scope.playerEntryId = entry.id;
					// set 30 secs update interval
					$scope.intervalPromise = $interval(function() {screenUpdate();}, 30000);
				}
				else if (entry.recordedEntryId && entry.recordedEntryId != '') {
					// session ended, got recording - show recorded entry in player
					$scope.playerEntryId = entry.recordedEntryId;
				}
				else {
					// show "no recording" in player
					$scope.playerEntryId = -1;
					// set 30 secs update interval
					$scope.intervalPromise = $interval(function() {screenUpdate();}, 30000);
				}
				// set report dates:
				var d = new Date();
				$rootScope.$broadcast('setupScreen', d.getTime());
				d.setTime(entry.createdAt);
				$scope.reportStartTime = d;
				getAggregates(entry.isLive);

			});
		};

		var screenSetup = function screenSetup() {
			// report data:
			getEntry();
		};

		var screenUpdate = function screenUpdate() {
			var d = new Date();
			var t = d.getTime();
			getAggregates($scope.entry.isLive);
			$rootScope.$broadcast('updateScreen', t);
		};

		$scope.$on('$destroy', function() {
			// Make sure that the interval is destroyed too
			if (angular.isDefined($scope.intervalPromise)) {
				$interval.cancel(stop);
				$scope.intervalPromise = undefined;
			}
		});

		screenSetup();
}]);
<|endoftext|>


<commit_before>module.exports = Templar

var path = require('path')
, fs = require('fs')
, LRU = require('lru-cache')
, compileCache = new LRU({max:50})
, outputCache = new LRU({max:500})
, crypto = require('crypto')
, templateCache = {}
, loaded = {}
, sigmund = require('sigmund')

// should really load the template folder before using it.
Templar.loadFolder = loadFolder

function Templar (req, res, opts) {
  if (!opts) throw new Error('Please provide options to Templar')

  var folder = opts.folder
  , engine = opts.engine
  , nocache = opts.cache === false
  , stamp = opts.stamp

  if (!engine || !folder) {
    throw new Error('Templar needs engine and folder options')
  }

  folder = path.resolve(folder)

  // In order to support include() methods, we need to load up
  // all of the templates in the folder.  This has the other
  // somewhat nice effect of meaning that we don't have to do
  // any fs.readFile calls later on.
  //
  // Of course, this sucks a lot if you have a lot of different
  // folders where templates go, but that's pretty rare.
  if (!loaded[folder]) loadFolder(folder)

  template.available = available
  template.has = has
  template.locals = {}
  template.locals.locals = template.locals
  return template

  function has (f) {
    f = path.resolve(folder, f)
    return !!templateCache[f]
  }

  function available () {
    return Object.keys(templateCache).filter(function (f) {
      return f.indexOf(folder) === 0
    }).map(function (f) {
      return path.relative(folder, f)
    })
  }

  function template () {
    var f, data, code
    for (var i = 0; i < arguments.length; i ++) {
      switch (typeof arguments[i]) {
        case 'number': code = arguments[i]; break
        case 'string': f = arguments[i]; break
        case 'object': data = arguments[i]; break
        default: throw new Error('bad argument to template')
      }
    }

    if (!f) throw new Error('no template provided')
    f = path.resolve(folder, f)
    if (!code) code = 200
    if (data && (typeof data === 'object')) {
      Object.keys(data).forEach(function (k) {
        template.locals[k] = data[k]
      })
      template.locals.locals = template.locals
    }

    var tpl = templateCache[f]
    if (!tpl) throw new Error('invalid template: '+f)

    // the data is part of the ETag
    // serving the same template with the same data = same result
    var ins = sigmund(template.locals)
    , tag = getETag(tpl.key + ":" + ins)

    if (!nocache && req.headers['if-none-match'] === tag) {
      res.statusCode = 304
      return res.end()
    }
    res.setHeader('etag', tag)
    if (stamp) res.setHeader('x-templar-stamp', stamp)

    // stamp is applied *after* getting the etag, otherwise
    // etags will be worker-specific which makes then much less
    // likely to hit the browser cache.
    template.locals.stamp = stamp
    var out = output(f, template.locals, tag)

    // ok, actually send a result.
    res.statusCode = code || 200
    var curCT = res.getHeader('content-type')
    if (!curCT) res.setHeader('content-type', 'text/html')
    res.end(out)
  }

  function output (f, data, tag) {
    // only generate if we have to
    var out = outputCache.get(tag)
    if (!nocache && out) return out

    // we're not actually going to provide THAT data object
    // to the template, however.  Instead, we're going to make a copy,
    // so that we can provide an 'include' function, which works just
    // like require(), in that each template includes relative to
    // itself
    var tplData = {}

    Object.keys(data).forEach(function (k) {
      tplData[k] = data[k]
    })
    tplData.include = include(f, tag)

    // include a link to 'locals' to see what we've been provided.
    tplData.locals = tplData

    out = compile(f)(tplData)
    outputCache.set(tag, out)

    return out
  }

  // a partial's effective tag is the parent tag + f + data
  function include (from, tag) { return function (f, data) {
    var ins = sigmund(data)
    , t = tag + f + ins
    return output(path.resolve(path.dirname(from), f), data || {}, t)
  }}

  function compile (f) {
    var tpl = templateCache[f]
    // only compile if we have to.
    var compiled = compileCache.get(f)

    if (!compiled || nocache) {
      if (nocache) {
        tpl = loadFile_(f, fs.statSync(f))
      }

      compiled = engine.compile(tpl.contents, { filename: f })
      compileCache.set(f, compiled)
    }

    if (!compiled) throw new Error('failed to compile template: '+f)
    return compiled
  }
}

function getETag (str) {
  var h = crypto.createHash("sha1")
  h.update(str)
  return '"' + h.digest('base64') + '"'
}

function loadFolder (folder) {
  loadFolder_(folder, templateCache, 0, 10)
  loaded[folder] = true
}

function loadFolder_ (folder, c, depth, maxDepth) {
  if (depth > maxDepth) return

  // synchronously read all the files in the folder, and save
  // their data and signatures for later.
  var queue = []
  fs.readdirSync(folder).forEach(function (file) {
    file = path.resolve(folder, file)
    var st = fs.statSync(file)
    if (!st) return
    if (st.isDirectory()) return queue.push(file)
    st = loadFile_(file, st)
    c[file] = st
  })
  queue.forEach(function (folder) {
    loadFolder_(folder, c, depth + 1, maxDepth)
  })
}

function loadFile_ (file, st) {
  st.contents = fs.readFileSync(file, 'utf8')
  st.key = st.dev + ':' + st.ino
  return st
}
<commit_msg>fix #8: Use filename as cache key on Windows<commit_after>module.exports = Templar

var path = require('path')
, fs = require('fs')
, LRU = require('lru-cache')
, compileCache = new LRU({max:50})
, outputCache = new LRU({max:500})
, crypto = require('crypto')
, templateCache = {}
, loaded = {}
, sigmund = require('sigmund')

// should really load the template folder before using it.
Templar.loadFolder = loadFolder

function Templar (req, res, opts) {
  if (!opts) throw new Error('Please provide options to Templar')

  var folder = opts.folder
  , engine = opts.engine
  , nocache = opts.cache === false
  , stamp = opts.stamp

  if (!engine || !folder) {
    throw new Error('Templar needs engine and folder options')
  }

  folder = path.resolve(folder)

  // In order to support include() methods, we need to load up
  // all of the templates in the folder.  This has the other
  // somewhat nice effect of meaning that we don't have to do
  // any fs.readFile calls later on.
  //
  // Of course, this sucks a lot if you have a lot of different
  // folders where templates go, but that's pretty rare.
  if (!loaded[folder]) loadFolder(folder)

  template.available = available
  template.has = has
  template.locals = {}
  template.locals.locals = template.locals
  return template

  function has (f) {
    f = path.resolve(folder, f)
    return !!templateCache[f]
  }

  function available () {
    return Object.keys(templateCache).filter(function (f) {
      return f.indexOf(folder) === 0
    }).map(function (f) {
      return path.relative(folder, f)
    })
  }

  function template () {
    var f, data, code
    for (var i = 0; i < arguments.length; i ++) {
      switch (typeof arguments[i]) {
        case 'number': code = arguments[i]; break
        case 'string': f = arguments[i]; break
        case 'object': data = arguments[i]; break
        default: throw new Error('bad argument to template')
      }
    }

    if (!f) throw new Error('no template provided')
    f = path.resolve(folder, f)
    if (!code) code = 200
    if (data && (typeof data === 'object')) {
      Object.keys(data).forEach(function (k) {
        template.locals[k] = data[k]
      })
      template.locals.locals = template.locals
    }

    var tpl = templateCache[f]
    if (!tpl) throw new Error('invalid template: '+f)

    // the data is part of the ETag
    // serving the same template with the same data = same result
    var ins = sigmund(template.locals)
    , tag = getETag(tpl.key + ":" + ins)

    if (!nocache && req.headers['if-none-match'] === tag) {
      res.statusCode = 304
      return res.end()
    }
    res.setHeader('etag', tag)
    if (stamp) res.setHeader('x-templar-stamp', stamp)

    // stamp is applied *after* getting the etag, otherwise
    // etags will be worker-specific which makes then much less
    // likely to hit the browser cache.
    template.locals.stamp = stamp
    var out = output(f, template.locals, tag)

    // ok, actually send a result.
    res.statusCode = code || 200
    var curCT = res.getHeader('content-type')
    if (!curCT) res.setHeader('content-type', 'text/html')
    res.end(out)
  }

  function output (f, data, tag) {
    // only generate if we have to
    var out = outputCache.get(tag)
    if (!nocache && out) return out

    // we're not actually going to provide THAT data object
    // to the template, however.  Instead, we're going to make a copy,
    // so that we can provide an 'include' function, which works just
    // like require(), in that each template includes relative to
    // itself
    var tplData = {}

    Object.keys(data).forEach(function (k) {
      tplData[k] = data[k]
    })
    tplData.include = include(f, tag)

    // include a link to 'locals' to see what we've been provided.
    tplData.locals = tplData

    out = compile(f)(tplData)
    outputCache.set(tag, out)

    return out
  }

  // a partial's effective tag is the parent tag + f + data
  function include (from, tag) { return function (f, data) {
    var ins = sigmund(data)
    , t = tag + f + ins
    return output(path.resolve(path.dirname(from), f), data || {}, t)
  }}

  function compile (f) {
    var tpl = templateCache[f]
    // only compile if we have to.
    var compiled = compileCache.get(f)

    if (!compiled || nocache) {
      if (nocache) {
        tpl = loadFile_(f, fs.statSync(f))
      }

      compiled = engine.compile(tpl.contents, { filename: f })
      compileCache.set(f, compiled)
    }

    if (!compiled) throw new Error('failed to compile template: '+f)
    return compiled
  }
}

function getETag (str) {
  var h = crypto.createHash("sha1")
  h.update(str)
  return '"' + h.digest('base64') + '"'
}

function loadFolder (folder) {
  loadFolder_(folder, templateCache, 0, 10)
  loaded[folder] = true
}

function loadFolder_ (folder, c, depth, maxDepth) {
  if (depth > maxDepth) return

  // synchronously read all the files in the folder, and save
  // their data and signatures for later.
  var queue = []
  fs.readdirSync(folder).forEach(function (file) {
    file = path.resolve(folder, file)
    var st = fs.statSync(file)
    if (!st) return
    if (st.isDirectory()) return queue.push(file)
    st = loadFile_(file, st)
    c[file] = st
  })
  queue.forEach(function (folder) {
    loadFolder_(folder, c, depth + 1, maxDepth)
  })
}

function loadFile_ (file, st) {
  st.contents = fs.readFileSync(file, 'utf8')
  st.key = process.platform === 'win32' ? path.resolve(file)
         : (st.dev + ':' + st.ino)
  return st
}
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var DIR         = __dirname     + '/',
        main        = require(DIR   + 'lib/server/main'),

        HTMLDIR     = main.HTMLDIR,
        JSONDIR     = main.JSONDIR,

        path        = main.path,
        fs          = main.fs,
        files       = main.files,
        CloudFunc   = main.cloudfunc,
        AppCache    = main.appcache,
        Util        = main.util,
        update      = main.update,
        dir         = main.dir,

        server      = main.librequire('server'),
        Minify      = main.minify,
        Config      = main.config,

        CONFIG_PATH = JSONDIR + 'config.json',

        KEY         = DIR + 'ssl/ssl.key',
        CERT        = DIR + 'ssl/ssl.crt',

        HTML_FS_DIR = HTMLDIR       + 'fs/',

        PATH_INDEX  = HTML_FS_DIR   + 'index.html',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link',
        ],

        Template    = {},

        FS          = CloudFunc.FS;
        /* reinit main dir os if we on Win32 should be backslashes */
        DIR         = main.DIR;

    readConfig(init);

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var keysPanel, left, right,
            LEFT    = CloudFunc.PANEL_LEFT,
            RIGHT   = CloudFunc.PANEL_RIGHT,
            data    = options.data,
            panel   = options.panel;

        if (!Config.appCache)
            data = Util.rmStr(data, [
                /* min */
                ' manifest=/cloudcmd.appcache',
                /* normal */
                ' manifest="/cloudcmd.appcache"'
            ]);

        if (!Config.showKeysPanel) {
            keysPanel  = '<div class="keyspanel';
            data        = data.replace(keysPanel + '"', keysPanel +' hidden"');
        }

        left    = Util.render(Template.panel, {
            id      : LEFT,
            side    : 'left',
            content : panel
        });

        right    = Util.render(Template.panel, {
            id      : RIGHT,
            side    : 'right',
            content : panel
        });

        data = Util.render(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right
        });

        return data;
    }

    /**
     * init and process of appcache if it allowed in config
     */
    function appCacheProcessing() {
        var FONT_REMOTE         = '//themes.googleusercontent.com/static/fonts/droidsansmono/v4/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff',
            FONT_LOCAL          = './font/DroidSansMono.woff',
            JQUERY_REMOTE       = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js',
            JQUERY_LOCAL        = './lib/client/jquery.js',
            files               = [{}, {}];

        files[0][FONT_REMOTE]   = FONT_LOCAL;
        files[1][JQUERY_REMOTE] = JQUERY_LOCAL;

        AppCache.addFiles(files);
        AppCache.createManifest();
    }

    function init() {
        var params,
            argv        = process.argv,
            length      = argv.length - 1,
            argvFirst   = argv[length],
            isTest      = Util.isContainStr(argvFirst, 'test');

        if (update)
            update.get();

        Util.log('server dir: ' + DIR);

        if (isTest) {
            Util.log('argv: ', argv);
            Config.server  = false;
        }

        if (Config.logs) {
            Util.log('log param setted up in config.json\n' +
                'from now all logs will be writed to log.txt');

            writeLogsToFile();
        }

        params      = {
            appcache    : appCacheProcessing,
            rest        : main.rest,
            route       : route
        };

        readFiles(params, function(params) {
            server.start(params);
        });
    }

    function readFiles(params, callback) {
        var filesList, paths   = {};

        filesList   = TMPL_PATH.map(function(name) {
                var path = HTML_FS_DIR + name + '.html';

                paths[path] = name;

                return path;
            });

        if (Config.ssl)
            filesList.push(KEY, CERT);

        files.read(filesList, 'utf8', function(errors, files) {
            var status, msg, names;

            if (errors) {
                status          = 'error';
                Util.log(errors);
            } else {
                status          = 'ok';

                Object.keys(files).forEach(function(path) {
                    var name = paths[path];

                    Template[name] = files[path];
                });

                if (Config.ssl)
                    params.ssl  = {
                        key     : files[KEY],
                        cert    : files[CERT]
                    };

                names           = TMPL_PATH.map(function(item) {
                    return item + '.html';
                });

                msg = CloudFunc.formatMsg('read', names, status);
                Util.log(msg);
            }

            callback(params);
        });
    }

    function readConfig(callback) {
        fs.readFile(CONFIG_PATH, 'utf8', function(error, data) {
            var status, json, msg;

            if (error)
                status      = 'error';
            else {
                status      = 'ok';
                json        = Util.parseJSON(data);
                main.config = Config = json;
            }

            msg             = CloudFunc.formatMsg('read', 'config', status);

            Util.log(msg);
            Util.exec(callback);
        });
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS;

        if (request && response) {
            name    = main.getPathName(request);
            isAuth  = Util.strCmp(name, ['/auth', '/auth/github']);
            isFS    = Util.strCmp(name, '/') || Util.isContainStrAtBegin(name, FS);

            p       = {
                request     : request,
                response    : response,
                name        : name
            };

            if (!isAuth && !isFS)
                Util.exec(callback);
            else if (isAuth) {
                Util.log('* Routing' + '-> ' + name);

                p.name = main.HTMLDIR + name + '.html';
                main.sendFile(p);
            } else if (isFS) {
                name    = Util.rmStrOnce(name, CloudFunc.FS) || main.SLASH;

                getContent(name, function(error, data, isFile) {
                    if (error)
                        main.sendError(p, error);
                    else if (isFile) {
                        p.name = name;
                        main.sendFile(p);
                    } else
                        readIndex(data, function(error, data) {
                            var NOT_LOG = true;

                            p.name = PATH_INDEX;

                            if (error)
                                main.sendError(error);
                            else
                                main.sendResponse(p, data, NOT_LOG);
                        });
                });
            }
        }
    }

    function getContent(name, callback) {
        dir.isDir(name, function(error, isDir) {
            var getDirContent   = main.commander.getDirContent,
                func            = Util.exec.ret(callback);

            if (!error && isDir)
                getDirContent(name, callback);
            else
                func(error, null, !isDir);
       });
    }

    function readIndex(json, callback) {
        var isMinify = Minify && Config.minify;

        Util.exec.if(!isMinify, function(error, params) {
            var name = params && params.name;

            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template,
                    });
                }

                Util.exec(callback, error, data);
            });
        },  function(callback) {
                Minify.optimize(PATH_INDEX, {
                    callback    : callback,
                    returnName  : true
                });
        });
    }

    /* function sets stdout to file log.txt */
    function writeLogsToFile() {
        var stdout      = process.stdout,
            writeFile   = fs.createWriteStream('log.txt'),
            write       = writeFile.write.bind(writeFile);

        stdout.write    = write;
    }
})();
<commit_msg>chore(cloudcmd) add " "<commit_after>(function() {
    'use strict';

    var DIR         = __dirname     + '/',
        main        = require(DIR   + 'lib/server/main'),

        HTMLDIR     = main.HTMLDIR,
        JSONDIR     = main.JSONDIR,

        path        = main.path,
        fs          = main.fs,
        files       = main.files,
        CloudFunc   = main.cloudfunc,
        AppCache    = main.appcache,
        Util        = main.util,
        update      = main.update,
        dir         = main.dir,

        server      = main.librequire('server'),
        Minify      = main.minify,
        Config      = main.config,

        CONFIG_PATH = JSONDIR + 'config.json',

        KEY         = DIR + 'ssl/ssl.key',
        CERT        = DIR + 'ssl/ssl.crt',

        HTML_FS_DIR = HTMLDIR       + 'fs/',

        PATH_INDEX  = HTML_FS_DIR   + 'index.html',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link',
        ],

        Template    = {},

        FS          = CloudFunc.FS;
        /* reinit main dir os if we on Win32 should be backslashes */
        DIR         = main.DIR;

    readConfig(init);

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var keysPanel, left, right,
            LEFT    = CloudFunc.PANEL_LEFT,
            RIGHT   = CloudFunc.PANEL_RIGHT,
            data    = options.data,
            panel   = options.panel;

        if (!Config.appCache)
            data = Util.rmStr(data, [
                /* min */
                ' manifest=/cloudcmd.appcache',
                /* normal */
                ' manifest="/cloudcmd.appcache"'
            ]);

        if (!Config.showKeysPanel) {
            keysPanel  = '<div class="keyspanel';
            data        = data.replace(keysPanel + '"', keysPanel +' hidden"');
        }

        left    = Util.render(Template.panel, {
            id      : LEFT,
            side    : 'left',
            content : panel
        });

        right    = Util.render(Template.panel, {
            id      : RIGHT,
            side    : 'right',
            content : panel
        });

        data = Util.render(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right
        });

        return data;
    }

    /**
     * init and process of appcache if it allowed in config
     */
    function appCacheProcessing() {
        var FONT_REMOTE         = '//themes.googleusercontent.com/static/fonts/droidsansmono/v4/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff',
            FONT_LOCAL          = './font/DroidSansMono.woff',
            JQUERY_REMOTE       = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js',
            JQUERY_LOCAL        = './lib/client/jquery.js',
            files               = [{}, {}];

        files[0][FONT_REMOTE]   = FONT_LOCAL;
        files[1][JQUERY_REMOTE] = JQUERY_LOCAL;

        AppCache.addFiles(files);
        AppCache.createManifest();
    }

    function init() {
        var params,
            argv        = process.argv,
            length      = argv.length - 1,
            argvFirst   = argv[length],
            isTest      = Util.isContainStr(argvFirst, 'test');

        if (update)
            update.get();

        Util.log('server dir: ' + DIR);

        if (isTest) {
            Util.log('argv: ', argv);
            Config.server  = false;
        }

        if (Config.logs) {
            Util.log('log param setted up in config.json\n' +
                'from now all logs will be writed to log.txt');

            writeLogsToFile();
        }

        params      = {
            appcache    : appCacheProcessing,
            rest        : main.rest,
            route       : route
        };

        readFiles(params, function(params) {
            server.start(params);
        });
    }

    function readFiles(params, callback) {
        var filesList, paths   = {};

        filesList   = TMPL_PATH.map(function(name) {
                var path = HTML_FS_DIR + name + '.html';

                paths[path] = name;

                return path;
            });

        if (Config.ssl)
            filesList.push(KEY, CERT);

        files.read(filesList, 'utf8', function(errors, files) {
            var status, msg, names;

            if (errors) {
                status          = 'error';
                Util.log(errors);
            } else {
                status          = 'ok';

                Object.keys(files).forEach(function(path) {
                    var name = paths[path];

                    Template[name] = files[path];
                });

                if (Config.ssl)
                    params.ssl  = {
                        key     : files[KEY],
                        cert    : files[CERT]
                    };

                names           = TMPL_PATH.map(function(item) {
                    return item + '.html';
                });

                msg = CloudFunc.formatMsg('read', names, status);
                Util.log(msg);
            }

            callback(params);
        });
    }

    function readConfig(callback) {
        fs.readFile(CONFIG_PATH, 'utf8', function(error, data) {
            var status, json, msg;

            if (error)
                status      = 'error';
            else {
                status      = 'ok';
                json        = Util.parseJSON(data);
                main.config = Config = json;
            }

            msg             = CloudFunc.formatMsg('read', 'config', status);

            Util.log(msg);
            Util.exec(callback);
        });
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS;

        if (request && response) {
            name    = main.getPathName(request);
            isAuth  = Util.strCmp(name, ['/auth', '/auth/github']);
            isFS    = Util.strCmp(name, '/') || Util.isContainStrAtBegin(name, FS);

            p       = {
                request     : request,
                response    : response,
                name        : name
            };

            if (!isAuth && !isFS)
                Util.exec(callback);
            else if (isAuth) {
                Util.log('* Routing' + '-> ' + name);

                p.name = main.HTMLDIR + name + '.html';
                main.sendFile(p);
            } else if (isFS) {
                name    = Util.rmStrOnce(name, CloudFunc.FS) || main.SLASH;

                getContent(name, function(error, data, isFile) {
                    if (error)
                        main.sendError(p, error);
                    else if (isFile) {
                        p.name = name;
                        main.sendFile(p);
                    } else
                        readIndex(data, function(error, data) {
                            var NOT_LOG = true;

                            p.name = PATH_INDEX;

                            if (error)
                                main.sendError(error);
                            else
                                main.sendResponse(p, data, NOT_LOG);
                        });
                });
            }
        }
    }

    function getContent(name, callback) {
        dir.isDir(name, function(error, isDir) {
            var getDirContent   = main.commander.getDirContent,
                func            = Util.exec.ret(callback);

            if (!error && isDir)
                getDirContent(name, callback);
            else
                func(error, null, !isDir);
       });
    }

    function readIndex(json, callback) {
        var isMinify = Minify && Config.minify;

        Util.exec.if(!isMinify, function(error, params) {
            var name = params && params.name;

            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template,
                    });
                }

                Util.exec(callback, error, data);
            });
        },  function(callback) {
                Minify.optimize(PATH_INDEX, {
                    callback    : callback,
                    returnName  : true
                });
        });
    }

    /* function sets stdout to file log.txt */
    function writeLogsToFile() {
        var stdout      = process.stdout,
            writeFile   = fs.createWriteStream('log.txt'),
            write       = writeFile.write.bind(writeFile);

        stdout.write    = write;
    }
})();
<|endoftext|>


<commit_before>/*
  eslint
  no-unused-vars: 0
  no-undef: 0
*/

function callApi(endpoint, authenticated=false, data={}) {
  let BASE_URL = 'http://localhost:3000';
  let token;
  if(__NODE_ENV__ === 'production'){
    BASE_URL = 'https://poststream.herokuapp.com';
  }

  let config = {};
  const {method, body, headers} = data;

  if (method){
    config.method = method;
  }
  if (body){
    config.body = body;
  }

  if(authenticated) {
    if(token) {
      config.headers = {
          'Authorization': `Bearer ${token}`,
          ...headers
        };
    } else {
      throw new Error("No token saved!");
    }
  }

  return fetch(BASE_URL + endpoint, config)
    .then(response =>
      response.text()
      .then(text => ({ text, response }))
    ).then(({ text, response }) => {
      if (!response.ok) {
        return Promise.reject(text);
      }
      return text
    }).catch(err => console.log(err));
};

export const CALL_API = Symbol('Call API');

export default store => next => action => {
  const callAPI = action[CALL_API];
  // So the middleware doesn't get applied to every single action
  if (typeof callAPI === 'undefined') {
    return next(action);
  }

  let { endpoint, types, authenticated, data } = callAPI;

  const [ requestType, successType, errorType ] = types;

  // Passing the authenticated boolean back in our data will let us distinguish between normal and secret quotes
  return callApi(endpoint, authenticated, data).then(
    response =>
      next({
        response,
        authenticated,
        type: successType,
        data
      }),
    error => next({
      error: error.message || 'There was an error.',
      type: errorType
    })
  )
};
<commit_msg>fixed toklen issue on CRUD routes<commit_after>/*
  eslint
  no-unused-vars: 0
  no-undef: 0
*/

function callApi(endpoint, authenticated=false, data={}) {
  let BASE_URL = 'http://localhost:3000';
  let token = localStorage.getItem('id_token') || {};
  if(__NODE_ENV__ === 'production'){
    BASE_URL = 'https://poststream.herokuapp.com';
  }

  let config = {};
  const {method, body, headers} = data;

  if (method){
    config.method = method;
  }
  if (body){
    config.body = body;
  }

  if(authenticated) {
    if(token) {
      config.headers = {
          'Authorization': `Bearer ${token}`,
          ...headers
        };
    } else {
      throw new Error("No token saved!");
    }
  }

  return fetch(BASE_URL + endpoint, config)
    .then(response =>
      response.text()
      .then(text => ({ text, response }))
    ).then(({ text, response }) => {
      if (!response.ok) {
        return Promise.reject(text);
      }
      return text
    }).catch(err => console.log(err));
};

export const CALL_API = Symbol('Call API');

export default store => next => action => {
  const callAPI = action[CALL_API];
  // So the middleware doesn't get applied to every single action
  if (typeof callAPI === 'undefined') {
    return next(action);
  }

  let { endpoint, types, authenticated, data } = callAPI;

  const [ requestType, successType, errorType ] = types;

  // Passing the authenticated boolean back in our data will let us distinguish between normal and secret quotes
  return callApi(endpoint, authenticated, data).then(
    response =>
      next({
        response,
        authenticated,
        type: successType,
        data
      }),
    error => next({
      error: error.message || 'There was an error.',
      type: errorType
    })
  )
};
<|endoftext|>


<commit_before>var Sequelize = require('sequelize');

/*
Owner (Property Manager)

Full Address {Street Address; ZIP Code; City; State; Latitude**; Longitude**;}

Property Overview {(PK) Address, number of units, …, Purchase Price, Square Footage, Price/sqft, Tenants; Capacity, monthly occupancy rates, Date Acquired,…(Financial ie. annualized return);}

Unit Features { Unit # (ie. appt. number) Bedrooms#; Bathrooms#; Parking#; Square Footage; Tenants; Capacity, monthly occupancy rates}

Bedroom {Square Footage; Amount per Month; Amount due Overall; Amount due per Month (Historic); Security Deposit; Maintenance Expense; Assigned Tenant; Maintenance Request;}

Financial {Property Purchase Price; Gross Operating Income (Revenue); Operating Expenses {Property Tax; Insurance; Maintenance Expense}, Net Operating Income; ROI;}
*/
var attributes = {
  owner: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      is: /^[a-z0-9\_\-]+$/i,
    }
  },
  streetName: {
    type: Sequelize.STRING,
  },
  streetNumber: {
    type: Sequelize.STRING,
  },
  zipcode: {
    type: Sequelize.INTEGER,
  },
  city: {
    type: Sequelize.STRING,
  },
  state: {
    type: Sequelize.STRING,
  },
  country: {
    type: Sequelize.STRING,
  },
  latitude: {
    type: Sequelize.INTEGER,
  },
  longitude: {
    type: Sequelize.INTEGER,
  },
  bedrooms: {
    type: Sequelize.INTEGER,
  },
  bathrooms: {
    type: Sequelize.INTEGER,
  },
  parking: {
    type: Sequelize.INTEGER,
  },
  squareFootage: {
    type: Sequelize.INTEGER,
  },
  purchasePrice: {
    type: Sequelize.INTEGER,
  },
  grossOperatingIncome: {
    type: Sequelize.INTEGER,
  },
  opeartingExprenses: {
    type: Sequelize.INTEGER,
  },
  netOperatingIncome: {
    type: Sequelize.INTEGER,
  },
  ROI: {
    type: Sequelize.INTEGER,
  }
};

var options = {
  freezeTableName: true
};

module.exports.attributes = attributes;
module.exports.options = options;<commit_msg>Adding setup updates...<commit_after>var Sequelize = require('sequelize');

/*
Owner (Property Manager)

Full Address {Street Address; ZIP Code; City; State; Latitude**; Longitude**;}

Property Overview {(PK) Address, number of units, …, Purchase Price, Square Footage, Price/sqft, Tenants; Capacity, monthly occupancy rates, Date Acquired,…(Financial ie. annualized return);}

Unit Features { Unit # (ie. appt. number) Bedrooms#; Bathrooms#; Parking#; Square Footage; Tenants; Capacity, monthly occupancy rates}

Bedroom {Square Footage; Amount per Month; Amount due Overall; Amount due per Month (Historic); Security Deposit; Maintenance Expense; Assigned Tenant; Maintenance Request;}

Financial {Property Purchase Price; Gross Operating Income (Revenue); Operating Expenses {Property Tax; Insurance; Maintenance Expense}, Net Operating Income; ROI;}
*/
var attributes = {
  owner: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      is: /^[a-z0-9\_\-]+$/i,
    }
  },
  streetName: {
    type: Sequelize.STRING,
  },
  streetNumber: {
    type: Sequelize.STRING,
  },
  zipcode: {
    type: Sequelize.INTEGER,
  },
  city: {
    type: Sequelize.STRING,
  },
  state: {
    type: Sequelize.STRING,
  },
  country: {
    type: Sequelize.STRING,
  },
  latitude: {
    type: Sequelize.INTEGER,
  },
  longitude: {
    type: Sequelize.INTEGER,
  },
  bedrooms: {
    type: Sequelize.INTEGER,
  },
  bathrooms: {
    type: Sequelize.INTEGER,
  },
  parking: {
    type: Sequelize.INTEGER,
  },
  squareFootage: {
    type: Sequelize.INTEGER,
  },
  purchasePrice: {
    type: Sequelize.INTEGER,
  },
  grossOperatingIncome: {
    type: Sequelize.INTEGER,
  },
  opeartingExprenses: {
    type: Sequelize.INTEGER,
  },
  netOperatingIncome: {
    type: Sequelize.INTEGER,
  },
  ROI: {
    type: Sequelize.INTEGER,
  }
};

var options = {
  freezeTableName: true
};

module.exports.attributes = attributes;
module.exports.options = options;<|endoftext|>


<commit_before>import DS from 'ember-data';
import Ember from 'ember';

export default DS.Model.extend({
  title: DS.attr('string'),
  date: DS.attr('date'),
  category: DS.attr('string'),
  tags: DS.attr('string'),

  body: null,
  preview: null,

  formattedDate: function() {
    return moment(this.get('date')).fromNow();
  }.property('date')
});
<commit_msg>Fix article.js so we can show previews and route correctly<commit_after>import DS from 'ember-data';
import Ember from 'ember';

export default DS.Model.extend({
  title: DS.attr('string'),
  date: DS.attr('date'),
  category: DS.attr('string'),
  tags: DS.attr('string'),

  body: null,
  preview: null,

  formattedDate: function() {
    return moment(this.get('date')).fromNow();
  }.property('date'),

  splitID: function() {
    return this.get('id').split('-');
  }.property('id'),

  dateFromID: function() {
    var splitID = this.get('splitID');
    return [splitID[0], splitID[1], splitID[2]].join('-');
  }.property('splitID'),

  year: function() {
    return moment(this.get('dateFromID')).format('YYYY');
  }.property('dateFromID'),

  month: function() {
    return moment(this.get('dateFromID')).format('MM');
  }.property('dateFromID'),

  day: function() {
    return moment(this.get('dateFromID')).format('DD');
  }.property('dateFromID'),

  href: function() {
    return this.get('id').split(this.get('dateFromID')+'-').join('');
  }.property('id,dateFromID')
});
<|endoftext|>


<commit_before>import { Dependencies } from 'constitute';
import { UnsupportedOperationException } from './../exceptions';
import Redis from './redis';
import DI from './../di';
import Config from './config';
import ServiceInterface from './interface';

export class Store {
  getInstance() {
    return this;
  }

  has() {
    return Promise.resolve(false);
  }

  get() {
    return Promise.resolve(null);
  }

  set() {
    return Promise.resolve(this);
  }

  flush() {
    return Promise.resolve(true);
  }

  tags() {
    throw new UnsupportedOperationException('Not support tag feature');
  }
}

export class NullStore extends Store {
  namespace() {
    return this;
  }

  tags() {
    return this;
  }
}

export class RedisNamespaceStore extends Store {
  constructor(prefix, namespace, redis) {
    super();
    this.prefix = prefix;
    this.namespace = namespace;
    this.redis = redis;
  }

  getInstance() {
    return this.redis;
  }

  has(key) {
    return this.redis.exists(this.key(key)).then(res => res > 0);
  }

  key(key) {
    return this.prefix ? [this.prefix, this.namespace, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes) {
    return minutes ?
      this.redis
        .set(this.key(key), JSON.stringify(value), 'ex', minutes * 60) :
      this.redis
        .set(this.key(key), JSON.stringify(value));
  }

  flush() {
    return this.redis.keys([this.prefix, this.namespace, '*'].join(':'))
      .then(keys => this.redis.del(keys));
  }
}

export class RedisStore extends Store {
  constructor(prefix, redis) {
    super();
    this.prefix = prefix;
    this.namespaceHandler = {};
    this.redis = redis || DI.get('redis').getInstance();
  }

  getInstance() {
    return this.redis;
  }

  namespace(namespace) {
    if ({}.hasOwnProperty.call(this.namespaceHandler, namespace)) {
      return this.namespaceHandler[namespace];
    }
    this.namespaceHandler[namespace] = new RedisNamespaceStore(this.prefix, namespace, this.redis);
    return this.namespaceHandler[namespace];
  }

  has(key) {
    return this.redis.exists(this.key(key));
  }

  key(key) {
    return this.prefix ? [this.prefix, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes) {
    return minutes ?
      this.redis
        .set(this.key(key), JSON.stringify(value), 'ex', minutes * 60) :
      this.redis
        .set(this.key(key), JSON.stringify(value));
  }

  flush() {
    return this.redis.flushall();
  }
}

@Dependencies(Config, Redis) //eslint-disable-line new-cap
export default class Cache extends ServiceInterface {
  constructor(config) {
    super();
    this.config = config.get('cache');
    this.prefix = this.config.prefix || 'eva';
    this.driver = this.config.driver;
    this.store = null;
  }

  setStore(store) {
    this.store = store;
    return this;
  }

  /**
   * @returns {Store}
   */
  getStore() {
    if (this.store) {
      return this.store;
    }
    this.store = this.driver === 'redis' ?
      new RedisStore(this.prefix) : new NullStore(this.prefix);
    return this.store;
  }

  setPrefix(prefix) {
    this.prefix = prefix;
  }

  getPrefix() {
    return this.prefix;
  }

  namespace(...args) {
    return this.getStore().namespace(...args);
  }

  has(key) {
    return this.getStore().has(key);
  }

  get(key) {
    return this.getStore().get(key);
  }

  set(...args) {
    return this.getStore().set(...args);
  }

  flush() {
    return this.getStore().flush();
  }
}

<commit_msg>fix redis set command<commit_after>import { Dependencies } from 'constitute';
import { UnsupportedOperationException } from './../exceptions';
import Redis from './redis';
import DI from './../di';
import Config from './config';
import ServiceInterface from './interface';

export class Store {
  getInstance() {
    return this;
  }

  has() {
    return Promise.resolve(false);
  }

  get() {
    return Promise.resolve(null);
  }

  set() {
    return Promise.resolve(this);
  }

  flush() {
    return Promise.resolve(true);
  }

  tags() {
    throw new UnsupportedOperationException('Not support tag feature');
  }
}

export class NullStore extends Store {
  namespace() {
    return this;
  }

  tags() {
    return this;
  }
}

export class RedisNamespaceStore extends Store {
  constructor(prefix, namespace, redis) {
    super();
    this.prefix = prefix;
    this.namespace = namespace;
    this.redis = redis;
  }

  getInstance() {
    return this.redis;
  }

  has(key) {
    return this.redis.exists(this.key(key)).then(res => res > 0);
  }

  key(key) {
    return this.prefix ? [this.prefix, this.namespace, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes) {
    return minutes ?
      this.redis
        .set(this.key(key), JSON.stringify(value), 'ex', minutes * 60) :
      this.redis
        .set(this.key(key), JSON.stringify(value));
  }

  flush() {
    return this.redis.keys([this.prefix, this.namespace, '*'].join(':'))
      .then(keys => this.redis.del(keys));
  }
}

export class RedisStore extends Store {
  constructor(prefix, redis) {
    super();
    this.prefix = prefix;
    this.namespaceHandler = {};
    this.redis = redis || DI.get('redis').getInstance();
  }

  getInstance() {
    return this.redis;
  }

  namespace(namespace) {
    if ({}.hasOwnProperty.call(this.namespaceHandler, namespace)) {
      return this.namespaceHandler[namespace];
    }
    this.namespaceHandler[namespace] = new RedisNamespaceStore(this.prefix, namespace, this.redis);
    return this.namespaceHandler[namespace];
  }

  has(key) {
    return this.redis.exists(this.key(key));
  }

  key(key) {
    return this.prefix ? [this.prefix, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes, mutex) {
    const args = [
      this.key(key),
      JSON.stringify(value)
    ];
    if (minutes) {
      args.push('ex', minutes * 60);
    }
    if (mutex) {
      const m = mutex.toLowerCase();
      if (m === 'nx' || m === 'xx') {
        args.push(m);
      }
    }
    return this.redis.set(...args);
  }

  flush() {
    return this.redis.flushall();
  }
}

@Dependencies(Config, Redis) //eslint-disable-line new-cap
export default class Cache extends ServiceInterface {
  constructor(config) {
    super();
    this.config = config.get('cache');
    this.prefix = this.config.prefix || 'eva';
    this.driver = this.config.driver;
    this.store = null;
  }

  setStore(store) {
    this.store = store;
    return this;
  }

  /**
   * @returns {Store}
   */
  getStore() {
    if (this.store) {
      return this.store;
    }
    this.store = this.driver === 'redis' ?
      new RedisStore(this.prefix) : new NullStore(this.prefix);
    return this.store;
  }

  setPrefix(prefix) {
    this.prefix = prefix;
  }

  getPrefix() {
    return this.prefix;
  }

  namespace(...args) {
    return this.getStore().namespace(...args);
  }

  has(key) {
    return this.getStore().has(key);
  }

  get(key) {
    return this.getStore().get(key);
  }

  set(...args) {
    return this.getStore().set(...args);
  }

  flush() {
    return this.getStore().flush();
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 Carsten Klein
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = {
	"env" : {
		"mocha" : true,
		"node" : true,
		"browser" : true
	},
    "rules": {
	/* Test specific overrides */
        "func-names": 0,
        "brace-style": [0, "allman"],
		"no-console" : 0,
        "no-loop-func" : 0
    }
}

<commit_msg>fix(testing): enable es6<commit_after>/*
 * Copyright 2015-2016 Carsten Klein
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = {
	"env" : {
		"mocha" : true,
		"node" : true,
		"browser" : true,
        "es6" : true
	},
    "rules": {
        /* Test specific overrides */
        "func-names": 0,
        "brace-style": [0, "allman"],
		"no-console" : 0,
        "no-loop-func" : 0
    }
}

<|endoftext|>


<commit_before>'use strict';

// const userLessonTokens = require('./user-lesson-tokens');

// const lessons = require('./lessons');

const users = require('./users');

const mongoose = require('mongoose')

module.exports = function() {
  const app = this;

  mongoose.connect(app.get('mongodb'));
  mongoose.Promise = global.Promise;

  app.configure(users);
  // app.configure(lessons);
  // app.configure(userLessonTokens);
};
<commit_msg>Add lessons and other service<commit_after>'use strict';

const userLessonTokens = require('./user-lesson-tokens');
const lessons = require('./lessons');

const users = require('./users');

const mongoose = require('mongoose');

module.exports = function() {
  const app = this;

  mongoose.connect(app.get('mongodb'));
  mongoose.Promise = global.Promise;

  app.configure(users);
  app.configure(lessons);
  app.configure(userLessonTokens);
};
<|endoftext|>


<commit_before>import React from 'react';
import MissionsComponent from '../components/missions';

export default class Missions {

  static componentWithData(missions) {
    return <MissionsComponent missions={missions} />;
  }

  static fromRawData(rawData) {
    return rawData.map(raw => Mission.fromRawData(raw))
  }

}

class Mission {

  static fromRawData(raw) {
    const mission = new Mission();

    const launchyear = raw.itemdateyear;
    const launchmonth = raw.itemdatemonth ? `${raw.itemdatemonth}.` : '';
    const launchday = raw.itemdateday ? `${raw.itemdateday}.` : '';
    mission.launchDate = `${launchday}${launchmonth}${launchyear}`;
    mission.name = raw.itemname;
    mission.link = raw.itemurl;
    mission.country = raw.itemcountry;
    if (raw.itemparent) {
      mission.rocket = new Rocket(raw.itemparent, raw.itemparenturl);
    }
    if (raw.itemlocation) {
      mission.pad = new Pad(raw.itemlocation, raw.itemlocationurl);
    }
    mission.destination = raw.itemdestination;
    mission.crew = raw.itemcrew;
    mission.duration = raw.itemduration;
    const endyear = raw.itemdate2year ? `${raw.itemdate2year}`: '';
    const endmonth = raw.itemdate2month ? `${raw.itemdate2month}.` : '';
    const endday = raw.itemdate2day ? `${raw.itemdate2day}.` : '';
    mission.endDate = `${endday}${endmonth}${endyear}`;
    const reenteryear = raw.itemdate3year ? `${raw.itemdate3year}`: '';
    const reentermonth = raw.itemdate3month ? `${raw.itemdate3month}.` : '';
    const reenterday = raw.itemdate3day ? `${raw.itemdate3day}.` : '';
    mission.reenterDate = `${reenterday}${reentermonth}${reenteryear}`;
    mission.status = raw.itemstatus ? raw.itemstatus : '-';
    mission.operator = raw.itemoperator ? raw.itemoperator : '';

    return mission;
  }

}

class Rocket {

  constructor(name, wikipediaUrl) {
    this.name = name;
    this.wikipediaUrl = wikipediaUrl;
  }

}

class Pad {

  constructor(name, wikipediaUrl) {
    this.name = name;
    this.wikipediaUrl = wikipediaUrl;
  }

}

// {
//     "itemname": "testItem 0123456789",
//     "itemurl": "https://de.wikipedia.org/wiki/testitem",
//     "itemdescription": "Sputnik 1 (russisch Спутник für Begleiter (der Erde)) war der erste künstliche Erdsatellit. Mit ihm begann am 4. Oktober 1957 das Zeitalter der Raumfahrt. Der Satellit war zwar von der Sowjetunion für den Verlauf des Internationalen Geophysikalischen Jahres (IGY 1957-58) angekündigt worden, doch rechnete die westliche Fachwelt erst Mitte 1958 mit der Fertigstellung der sowjetischen Entwicklungen und wurde durch den Start überrascht. Auch in der westlichen Öffentlichkeit löste der Start Besorgnisse aus; diese wurden mit dem Begriff Sputnik-Schock benannt. Dieser Sputnik - späteres Synonym für alle sowjetischen Satelliten, auch der Kosmos-Serie und anderer „Sputniks“ - wog 83,6 kg und damit fünfmal mehr als der US-Explorer 1 vom 31. Januar 1958 und war eine mit Stickstoff gefüllte, hochglanzpolierte Aluminiumkugel. Sie bestand aus 2 mm starkem Blech aus der Aluminiumlegierung AlMg6T, hatte 58 cm Durchmesser und zwei Antennenpaare (je 2,4 m bzw. 2,9 m lang) ragten aus ihr heraus. Die Trägerrakete R-7 des Satelliten war eine Weiterentwicklung militärischer Interkontinentalraketen durch den Konstrukteur Sergei Pawlowitsch Koroljow. Der Satellit trug zwei Funksender vom Typ D 200 mit einem Watt Leistung für codierte Kurzwellensignale, in denen Innendruck und -temperatur verschlüsselt waren, auf einer Frequenz von 20,005 und 40,002 MHz, die 21 Tage funktionsfähig blieben. Die „piepsenden“ Signale des Sputnik konnten an sich auf der ganzen Welt empfangen werden, wenn der verwendete Empfänger für die schwachen 1-Watt-Signale empfindlich genug war. Im westlichen Europa konnte dabei ein Astronom den ersten Erfolg verkünden: Heinz Kaminski von der Volkssternwarte Bochum. Nach 92 Tagen trat Sputnik 1 in die dichteren Atmosphärenschichten ein und verglühte am 4. Januar 19507.",
//     "itemdateyear": "2000",
//     "itemdatemonth": 10,
//     "itemdateday": 30,
//     "itemdate2year": "2000",
//     "itemdate2month": 12,
//     "itemdate2day": 30,
//     "itemduration": "22a 222d",
//     "itemparent": "testRocket 123",
//     "itemparenturl": "https://de.wikipedia.org/wiki/testrocket",
//     "itemcountry": "SU/RU, USA, EU, Japan",
//     "itemdestination": "Erdorbit, ISS, Mond, Mars",
//     "itemlocation": "Ba LC-1/5",
//     "itemlocationurl": "https://de.wikipedia.org/wiki/Baikonur",
//     "itemlatitude": "45.92",
//     "itemlongitude": "63.342"
// },
<commit_msg>preparation for mission.astronauts<commit_after>import React from 'react';
import MissionsComponent from '../components/missions';

export default class Missions {

  static componentWithData(missions) {
    return <MissionsComponent missions={missions} />;
  }

  static fromRawData(rawData) {
    return rawData.map(raw => Mission.fromRawData(raw))
  }

}

class Mission {

  static fromRawData(raw) {
    const mission = new Mission();

    const launchyear = raw.itemdateyear;
    const launchmonth = raw.itemdatemonth ? `${raw.itemdatemonth}.` : '';
    const launchday = raw.itemdateday ? `${raw.itemdateday}.` : '';
    mission.launchDate = `${launchday}${launchmonth}${launchyear}`;
    mission.name = raw.itemname;
    mission.link = raw.itemurl;
    mission.country = raw.itemcountry;
    if (raw.itemparent) {
      mission.rocket = new Rocket(raw.itemparent, raw.itemparenturl);
    }
    if (raw.itemlocation) {
      mission.pad = new Pad(raw.itemlocation, raw.itemlocationurl);
    }
    mission.destination = raw.itemdestination;
    mission.crew = raw.itemcrew;
    mission.duration = raw.itemduration;
    const endyear = raw.itemdate2year ? `${raw.itemdate2year}`: '';
    const endmonth = raw.itemdate2month ? `${raw.itemdate2month}.` : '';
    const endday = raw.itemdate2day ? `${raw.itemdate2day}.` : '';
    mission.endDate = `${endday}${endmonth}${endyear}`;
    const reenteryear = raw.itemdate3year ? `${raw.itemdate3year}`: '';
    const reentermonth = raw.itemdate3month ? `${raw.itemdate3month}.` : '';
    const reenterday = raw.itemdate3day ? `${raw.itemdate3day}.` : '';
    mission.reenterDate = `${reenterday}${reentermonth}${reenteryear}`;
    mission.status = raw.itemstatus ? raw.itemstatus : '-';
    mission.operator = raw.itemoperator ? raw.itemoperator : '';
    const astronaut1 = raw.itemperson ? raw.itemperson : '';//better take an array mission.astronauts[]?
    const astronaut2 = raw.itemperson2 ? raw.itemperson2 : '';
    const astronaut3 = raw.itemperson3 ? raw.itemperson3 : '';
    const astronaut4 = raw.itemperson4 ? raw.itemperson4 : '';
    const astronaut5 = raw.itemperson5 ? raw.itemperson5 : '';
    const astronaut6 = raw.itemperson6 ? raw.itemperson6 : '';
    const astronaut7 = raw.itemperson7 ? raw.itemperson7 : '';
    const astronaut8 = raw.itemperson8 ? raw.itemperson8 : '';
    mission.astronauts = `${astronaut1}, ${astronaut2}, ${astronaut3}, ${astronaut4}, ${astronaut5}, ${astronaut6}, ${astronaut7}, ${astronaut8}`;

    return mission;
  }

}

class Rocket {

  constructor(name, wikipediaUrl) {
    this.name = name;
    this.wikipediaUrl = wikipediaUrl;
  }

}

class Pad {

  constructor(name, wikipediaUrl) {
    this.name = name;
    this.wikipediaUrl = wikipediaUrl;
  }

}

// {
//     "itemname": "testItem 0123456789",
//     "itemurl": "https://de.wikipedia.org/wiki/testitem",
//     "itemdescription": "Sputnik 1 (russisch Спутник für Begleiter (der Erde)) war der erste künstliche Erdsatellit. Mit ihm begann am 4. Oktober 1957 das Zeitalter der Raumfahrt. Der Satellit war zwar von der Sowjetunion für den Verlauf des Internationalen Geophysikalischen Jahres (IGY 1957-58) angekündigt worden, doch rechnete die westliche Fachwelt erst Mitte 1958 mit der Fertigstellung der sowjetischen Entwicklungen und wurde durch den Start überrascht. Auch in der westlichen Öffentlichkeit löste der Start Besorgnisse aus; diese wurden mit dem Begriff Sputnik-Schock benannt. Dieser Sputnik - späteres Synonym für alle sowjetischen Satelliten, auch der Kosmos-Serie und anderer „Sputniks“ - wog 83,6 kg und damit fünfmal mehr als der US-Explorer 1 vom 31. Januar 1958 und war eine mit Stickstoff gefüllte, hochglanzpolierte Aluminiumkugel. Sie bestand aus 2 mm starkem Blech aus der Aluminiumlegierung AlMg6T, hatte 58 cm Durchmesser und zwei Antennenpaare (je 2,4 m bzw. 2,9 m lang) ragten aus ihr heraus. Die Trägerrakete R-7 des Satelliten war eine Weiterentwicklung militärischer Interkontinentalraketen durch den Konstrukteur Sergei Pawlowitsch Koroljow. Der Satellit trug zwei Funksender vom Typ D 200 mit einem Watt Leistung für codierte Kurzwellensignale, in denen Innendruck und -temperatur verschlüsselt waren, auf einer Frequenz von 20,005 und 40,002 MHz, die 21 Tage funktionsfähig blieben. Die „piepsenden“ Signale des Sputnik konnten an sich auf der ganzen Welt empfangen werden, wenn der verwendete Empfänger für die schwachen 1-Watt-Signale empfindlich genug war. Im westlichen Europa konnte dabei ein Astronom den ersten Erfolg verkünden: Heinz Kaminski von der Volkssternwarte Bochum. Nach 92 Tagen trat Sputnik 1 in die dichteren Atmosphärenschichten ein und verglühte am 4. Januar 19507.",
//     "itemdateyear": "2000",
//     "itemdatemonth": 10,
//     "itemdateday": 30,
//     "itemdate2year": "2000",
//     "itemdate2month": 12,
//     "itemdate2day": 30,
//     "itemduration": "22a 222d",
//     "itemparent": "testRocket 123",
//     "itemparenturl": "https://de.wikipedia.org/wiki/testrocket",
//     "itemcountry": "SU/RU, USA, EU, Japan",
//     "itemdestination": "Erdorbit, ISS, Mond, Mars",
//     "itemlocation": "Ba LC-1/5",
//     "itemlocationurl": "https://de.wikipedia.org/wiki/Baikonur",
//     "itemlatitude": "45.92",
//     "itemlongitude": "63.342"
// },
<|endoftext|>


<commit_before>import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import Loading from 'components/Loading';
import request from 'axios';
import UsernameText from 'components/Texts/UsernameText';
import ProfilePic from 'components/ProfilePic';
import ErrorBoundary from 'components/Wrappers/ErrorBoundary';
import FilterBar from 'components/FilterBar';
import RoundList from 'components/RoundList';
import { connect } from 'react-redux';
import { addCommasToNumber } from 'helpers/stringHelpers';
import { auth } from 'helpers/requestHelpers';
import { Color, borderRadius } from 'constants/css';
import { css } from 'emotion';
import { getRanks } from 'redux/actions/NotiActions';
import URL from 'constants/URL';

const API_URL = `${URL}/user`;

Rankings.propTypes = {
  all: PropTypes.array.isRequired,
  loaded: PropTypes.bool,
  myId: PropTypes.number,
  rank: PropTypes.number,
  getRanks: PropTypes.func.isRequired,
  rankModifier: PropTypes.number.isRequired,
  top30s: PropTypes.array.isRequired,
  twinkleXP: PropTypes.number
};

function Rankings({
  all,
  loaded,
  getRanks,
  myId,
  rank,
  rankModifier,
  top30s,
  twinkleXP
}) {
  const [allSelected, setAllSelected] = useState(true);
  const mounted = useRef(true);
  const rankedColor =
    rank === 1 ? Color.gold() : rank !== 0 && rank <= 3 ? '#fff' : undefined;

  useEffect(() => {
    mounted.current = true;
    if (!myId) {
      setAllSelected(false);
    }
    loadRankings();
    async function loadRankings() {
      try {
        const {
          data: { all, rankModifier: modifier, top30s }
        } = await request.get(`${API_URL}/leaderBoard`, auth());
        if (mounted.current) {
          getRanks({ all, top30s, rankModifier: modifier });
          setAllSelected(!!myId);
        }
      } catch (error) {
        console.error(error.response || error);
      }
    }
    return function cleanUp() {
      mounted.current = false;
    };
  }, [myId, twinkleXP]);

  const users = allSelected ? all : top30s;
  const modifier = allSelected ? rankModifier : 0;
  return (
    <ErrorBoundary>
      {!!myId && (
        <FilterBar
          bordered
          style={{
            height: '4.5rem',
            fontSize: '1.6rem'
          }}
        >
           setAllSelected(true)}
          >
            My Ranking

           setAllSelected(false)}
          >
            Top 30

        </FilterBar>
      )}
      {!loaded && <Loading />}
      {loaded && allSelected && (

 0
                ? rank < 3
                  ? Color.black()
                  : rank === 3
                  ? Color.orange()
                  : '#fff'
                : '#fff'
              : null
          }}
          className={css`
            width: 100%;
            margin-bottom: 0px;
            text-align: center;
            padding: 1rem;
            border: 1px solid #eeeeee;
            border-radius: ${borderRadius};
            p {
              font-weight: bold;
            }
            a {
              font-size: 1.5rem;
              font-weight: bold;
            }
          `}
        >
          {

                {twinkleXP ? addCommasToNumber(twinkleXP) : 0}
              {' '}

                XP

               0 && rank <= 10
                      ? Color.pink()
                      : Color.buttonGray()),
                  fontSize: '2rem'
                }}
              >
                {rank ? `Rank #${rank}` : 'Unranked'}

          }

      )}
      {loaded && allSelected && users.length === 0 && (
        <div
          style={{
            background: '#fff',
            borderRadius,
            padding: '1rem',
            border: `1px solid ${Color.borderGray()}`
          }}
        >
          You are not ranked. To get ranked, earn XP by watching a starred video
          or leaving comments

      )}
      <RoundList style={{ marginTop: 0 }}>
        {users.map(user => {
          const rank = !user.twinkleXP
            ? undefined
            : users.filter(otherUser => otherUser.twinkleXP > user.twinkleXP)
                .length +
              1 +
              modifier;
          const rankColor =
            rank === 1
              ? Color.gold()
              : rank === 2
              ? Color.lightGray()
              : rank === 3
              ? Color.orange()
              : undefined;
          return (

                <span
                  style={{
                    fontWeight: 'bold',
                    fontSize: rank < 100 ? '2rem' : '1.5rem',
                    width: '3rem',
                    marginRight: '1rem',
                    textAlign: 'center',
                    color:
                      rankColor ||
                      (rank <= 10 ? Color.logoBlue() : Color.buttonGray())
                  }}
                >
                  {rank ? `#${rank}` : '--'}

                  <ProfilePic
                    style={{ width: '6rem', height: '6rem' }}
                    profilePicId={user.profilePicId}
                    userId={user.id}
                  />
                  <UsernameText
                    color={
                      rankColor ||
                      (rank <= 10 ? Color.logoBlue() : Color.buttonGray())
                    }
                    user={{ ...user, username: user.username }}
                    userId={myId}
                    style={{ display: 'block', marginTop: '0.5rem' }}
                  />

                  {addCommasToNumber(user.twinkleXP || 0)}
                {' '}
                XP

          );
        })}
      </RoundList>
    </ErrorBoundary>
  );
}

export default connect(
  state => ({
    all: state.NotiReducer.allRanks,
    myId: state.UserReducer.userId,
    rank: state.UserReducer.rank,
    rankModifier: state.NotiReducer.rankModifier,
    top30s: state.NotiReducer.top30s,
    twinkleXP: state.UserReducer.twinkleXP,
    loaded: state.NotiReducer.rankingsLoaded
  }),
  {
    getRanks
  }
)(Rankings);
<commit_msg>minor fix<commit_after>import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import Loading from 'components/Loading';
import request from 'axios';
import UsernameText from 'components/Texts/UsernameText';
import ProfilePic from 'components/ProfilePic';
import ErrorBoundary from 'components/Wrappers/ErrorBoundary';
import FilterBar from 'components/FilterBar';
import RoundList from 'components/RoundList';
import { connect } from 'react-redux';
import { addCommasToNumber } from 'helpers/stringHelpers';
import { auth } from 'helpers/requestHelpers';
import { Color, borderRadius } from 'constants/css';
import { css } from 'emotion';
import { getRanks } from 'redux/actions/NotiActions';
import URL from 'constants/URL';

const API_URL = `${URL}/user`;

Rankings.propTypes = {
  all: PropTypes.array.isRequired,
  loaded: PropTypes.bool,
  myId: PropTypes.number,
  rank: PropTypes.number,
  getRanks: PropTypes.func.isRequired,
  rankModifier: PropTypes.number.isRequired,
  top30s: PropTypes.array.isRequired,
  twinkleXP: PropTypes.number
};

function Rankings({
  all,
  loaded,
  getRanks,
  myId,
  rank,
  rankModifier,
  top30s,
  twinkleXP
}) {
  const [allSelected, setAllSelected] = useState(true);
  const mounted = useRef(true);
  const rankedColor =
    rank === 1 ? Color.gold() : rank !== 0 && rank <= 3 ? '#fff' : undefined;

  useEffect(() => {
    mounted.current = true;
    if (!myId) {
      setAllSelected(false);
    }
    loadRankings();
    async function loadRankings() {
      try {
        const {
          data: { all, rankModifier: modifier, top30s }
        } = await request.get(`${API_URL}/leaderBoard`, auth());
        if (mounted.current) {
          getRanks({ all, top30s, rankModifier: modifier });
          setAllSelected(!!myId);
        }
      } catch (error) {
        console.error(error.response || error);
      }
    }
    return function cleanUp() {
      mounted.current = false;
    };
  }, [myId, twinkleXP]);

  const users = allSelected ? all : top30s;
  const modifier = allSelected ? rankModifier : 0;
  return (
    <ErrorBoundary>
      {!!myId && (
        <FilterBar
          bordered
          style={{
            height: '4.5rem',
            fontSize: '1.6rem'
          }}
        >
           setAllSelected(true)}
          >
            My Ranking

           setAllSelected(false)}
          >
            Top 30

        </FilterBar>
      )}
      {!loaded && <Loading />}
      {loaded && allSelected && (

 0
                ? rank < 3
                  ? Color.black()
                  : rank === 3
                  ? Color.orange()
                  : '#fff'
                : '#fff'
              : null
          }}
          className={css`
            width: 100%;
            margin-bottom: 0px;
            text-align: center;
            padding: 1rem;
            border: 1px solid #eeeeee;
            border-radius: ${borderRadius};
            p {
              font-weight: bold;
            }
            a {
              font-size: 1.5rem;
              font-weight: bold;
            }
          `}
        >
          {

                {twinkleXP ? addCommasToNumber(twinkleXP) : 0}
              {' '}

                XP

               0 && rank <= 10
                      ? Color.pink()
                      : Color.buttonGray()),
                  fontSize: '2rem'
                }}
              >
                {rank ? `Rank #${rank}` : 'Unranked'}

          }

      )}
      {loaded && allSelected && users.length === 0 && !!myId && (
        <div
          style={{
            background: '#fff',
            borderRadius,
            padding: '1rem',
            border: `1px solid ${Color.borderGray()}`
          }}
        >
          You are not ranked. To get ranked, earn XP by watching a starred video
          or leaving comments

      )}
      <RoundList style={{ marginTop: 0 }}>
        {users.map(user => {
          const rank = !user.twinkleXP
            ? undefined
            : users.filter(otherUser => otherUser.twinkleXP > user.twinkleXP)
                .length +
              1 +
              modifier;
          const rankColor =
            rank === 1
              ? Color.gold()
              : rank === 2
              ? Color.lightGray()
              : rank === 3
              ? Color.orange()
              : undefined;
          return (

                <span
                  style={{
                    fontWeight: 'bold',
                    fontSize: rank < 100 ? '2rem' : '1.5rem',
                    width: '3rem',
                    marginRight: '1rem',
                    textAlign: 'center',
                    color:
                      rankColor ||
                      (rank <= 10 ? Color.logoBlue() : Color.buttonGray())
                  }}
                >
                  {rank ? `#${rank}` : '--'}

                  <ProfilePic
                    style={{ width: '6rem', height: '6rem' }}
                    profilePicId={user.profilePicId}
                    userId={user.id}
                  />
                  <UsernameText
                    color={
                      rankColor ||
                      (rank <= 10 ? Color.logoBlue() : Color.buttonGray())
                    }
                    user={{ ...user, username: user.username }}
                    userId={myId}
                    style={{ display: 'block', marginTop: '0.5rem' }}
                  />

                  {addCommasToNumber(user.twinkleXP || 0)}
                {' '}
                XP

          );
        })}
      </RoundList>
    </ErrorBoundary>
  );
}

export default connect(
  state => ({
    all: state.NotiReducer.allRanks,
    myId: state.UserReducer.userId,
    rank: state.UserReducer.rank,
    rankModifier: state.NotiReducer.rankModifier,
    top30s: state.NotiReducer.top30s,
    twinkleXP: state.UserReducer.twinkleXP,
    loaded: state.NotiReducer.rankingsLoaded
  }),
  {
    getRanks
  }
)(Rankings);
<|endoftext|>