<commit_before>import xhr from 'xhr'
import { remote } from 'electron'
import hyperquest from 'hyperquest'
import querystring from 'querystring'

const osmServerHost = 'http://' + remote.getGlobal('osmServerHost')

module.exports = {
  stop,
  destroy,
  leave,
  listen,
  join,
  clear,
  peers,
  peerStream,
  start,
  createMedia,
  create,
  update,
  del,
  list,
  convert
}

function destroy (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/destroy`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function leave (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/leave`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function join (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/join`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function listen (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/listen`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function peerStream (opts) {
  if (!opts) opts = { interval: 1000}
  return hyperquest({
    method: 'GET',
    uri: `${osmServerHost}/sync/peers?interval=${opts.interval}`
  })
}

function peers (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/peers`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    try {
      var data = JSON.parse(body)
      if (data.topic === 'peers') return cb(null, data.message)
      else return cb(new Error('unknown response', data))
    } catch (err) {
      return cb(err)
    }
  })
}

function stop (target, cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/stop`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    cb(null, body)
  })
}

function start (target, opts) {
  if (!opts) opts = {}
  return hyperquest({
    method: 'GET',
    uri: `${osmServerHost}/sync/start?${querystring.stringify(target)}&interval=${opts.interval}`
  })
}

function clear (cb) {
  var opts = {
    url: `${osmServerHost}/sync/clear`,
    method: 'GET'
  }
  xhr(opts, cb)
}

function createMedia (buf, cb) {
  var opts = {
    url: `${osmServerHost}/media`,
    method: 'POST',
    body: buf
  }
  xhr(opts, cb)
}

function del (f, cb) {
  // Delete
  var opts = {
    url: `${osmServerHost}/observations/${f.id}`,
    method: 'DELETE'
  }
  xhr(opts, cb)
}

function create (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations`,
    method: 'POST',
    body: f,
    json: true
  }
  xhr(opts, cb)
}

function update (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations/${f.id}`,
    method: 'PUT',
    body: f,
    json: true
  }
  xhr(opts, cb)
}

function list (cb) {
  xhr(`${osmServerHost}/observations`, cb)
}

function convert (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations/to-element/${f.id}`,
    method: 'PUT'
  }
  xhr(opts, cb)
}
<commit_msg>use clearState api<commit_after>import xhr from 'xhr'
import { remote } from 'electron'
import hyperquest from 'hyperquest'
import querystring from 'querystring'

const osmServerHost = 'http://' + remote.getGlobal('osmServerHost')

module.exports = {
  stop,
  destroy,
  leave,
  listen,
  join,
  clearState,
  peers,
  peerStream,
  start,
  createMedia,
  create,
  update,
  del,
  list,
  convert
}

function destroy (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/destroy`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function leave (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/leave`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function join (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/join`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function listen (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/listen`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    return cb(null, body)
  })
}

function peerStream (opts) {
  if (!opts) opts = { interval: 1000}
  return hyperquest({
    method: 'GET',
    uri: `${osmServerHost}/sync/peers?interval=${opts.interval}`
  })
}

function peers (cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/peers`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    try {
      var data = JSON.parse(body)
      if (data.topic === 'peers') return cb(null, data.message)
      else return cb(new Error('unknown response', data))
    } catch (err) {
      return cb(err)
    }
  })
}

function stop (target, cb) {
  var opts = {
    method: 'GET',
    url: `${osmServerHost}/sync/stop`
  }
  xhr(opts, function (err, res, body) {
    if (err) return cb(err)
    cb(null, body)
  })
}

function start (target, opts) {
  if (!opts) opts = {}
  return hyperquest({
    method: 'GET',
    uri: `${osmServerHost}/sync/start?${querystring.stringify(target)}&interval=${opts.interval}`
  })
}

function clearState (cb) {
  var opts = {
    url: `${osmServerHost}/sync/clearState`,
    method: 'GET'
  }
  xhr(opts, cb)
}

function createMedia (buf, cb) {
  var opts = {
    url: `${osmServerHost}/media`,
    method: 'POST',
    body: buf
  }
  xhr(opts, cb)
}

function del (f, cb) {
  // Delete
  var opts = {
    url: `${osmServerHost}/observations/${f.id}`,
    method: 'DELETE'
  }
  xhr(opts, cb)
}

function create (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations`,
    method: 'POST',
    body: f,
    json: true
  }
  xhr(opts, cb)
}

function update (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations/${f.id}`,
    method: 'PUT',
    body: f,
    json: true
  }
  xhr(opts, cb)
}

function list (cb) {
  xhr(`${osmServerHost}/observations`, cb)
}

function convert (f, cb) {
  var opts = {
    url: `${osmServerHost}/observations/to-element/${f.id}`,
    method: 'PUT'
  }
  xhr(opts, cb)
}
<|endoftext|>


<commit_before>module.exports = (function () {
    'use strict';

    // Require dependencies
    var u = require('utils/index'),
        iterate = require('_iterator');

    function setDisplay(context, mode) {
        iterate(context, function (el) {
            if (u.is.element(el)) {
                el.style.display = mode;
            }
        });
    }

    return {
        show: function () {
            setDisplay(this, 'block');
            return this;
        },
        hide: function () {
            setDisplay(this, 'none');
            return this;
        }
    };
}());
<commit_msg>Comments on .show() and .hide() methods<commit_after>module.exports = (function () {
    'use strict';

    // Require dependencies
    var u = require('utils/index'),
        iterate = require('_iterator');

    /**
     * @private
     * Iterates each mached element and sets the display property.
     * @param {object} obj The DOMQuery object.
     * @param {string} value The value of "display" property.
     */
    function setDisplay(obj, value) {
        iterate(obj, function (el) {
            if (u.is.element(el)) {
                el.style.display = value;
            }
        });
    }

    return {
        show: function () {
            setDisplay(this, 'block');
            return this;
        },
        hide: function () {
            setDisplay(this, 'none');
            return this;
        }
    };
}());
<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

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.
*/

export default class ResizeItem {
    constructor(domNode, id, reverse, resizer, sizer) {
        this.domNode = domNode;
        this.id = id;
        this.reverse = reverse;
        this.resizer = resizer;
        this.sizer = sizer;
    }

    static fromResizeHandle(handle, resizer, sizer) {
        const id = handle.getAttribute("data-id");
        const reverse = resizer.isReverseResizeHandle(handle);
        const domNode = reverse ? handle.nextElementSibling : handle.previousElementSibling;
        return new ResizeItem(domNode, id, reverse, resizer, sizer);
    }

    _advance(forwards) {
        // opposite direction from fromResizeHandle to get back to handle
        let handle = this.reverse ?
            this.domNode.previousElementSibling :
            this.domNode.nextElementSibling;
        const moveNext = forwards !== this.reverse; // xor
        // iterate at least once to avoid infinite loop
        do {
            if (moveNext) {
                handle = handle.nextElementSibling;
            } else {
                handle = handle.previousElementSibling;
            }
        } while(handle && !this.resizer.isResizeHandle(handle));
        if (handle) {
            const nextHandle = ResizeItem.fromResizeHandle(handle, this.resizer, this.sizer);
            nextHandle.reverse = this.reverse;
            return nextHandle;
        }
    }

    next() {
        return this._advance(true);
    }

    previous() {
        return this._advance(false);
    }

    size() {
        return this.sizer.getItemSize(this.domNode);
    }

    offset() {
        return this.sizer.getItemOffset(this.domNode);
    }

    setSize(size) {
        this.sizer.setItemSize(this.domNode, size);
        const callback = this.resizer.distributorCtor.onResized;
        if (callback) {
            callback(size, this.id, this.domNode);
        }
    }

    clearSize() {
        this.sizer.clearItemSize(this.domNode);
        const callback = this.resizer.distributorCtor.onResized;
        if (callback) {
            callback(null, this.id, this.domNode);
        }
    }
}
<commit_msg>fix typo<commit_after>/*
Copyright 2018 New Vector Ltd

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.
*/

export default class ResizeItem {
    constructor(domNode, id, reverse, resizer, sizer) {
        this.domNode = domNode;
        this.id = id;
        this.reverse = reverse;
        this.resizer = resizer;
        this.sizer = sizer;
    }

    static fromResizeHandle(handle, resizer, sizer) {
        const id = handle.getAttribute("data-id");
        const reverse = resizer.isReverseResizeHandle(handle);
        const domNode = reverse ? handle.nextElementSibling : handle.previousElementSibling;
        return new ResizeItem(domNode, id, reverse, resizer, sizer);
    }

    _advance(forwards) {
        // opposite direction from fromResizeHandle to get back to handle
        let handle = this.reverse ?
            this.domNode.previousElementSibling :
            this.domNode.nextElementSibling;
        const moveNext = forwards !== this.reverse; // xor
        // iterate at least once to avoid infinite loop
        do {
            if (moveNext) {
                handle = handle.nextElementSibling;
            } else {
                handle = handle.previousElementSibling;
            }
        } while(handle && !this.resizer.isResizeHandle(handle));
        if (handle) {
            const nextHandle = ResizeItem.fromResizeHandle(handle, this.resizer, this.sizer);
            nextHandle.reverse = this.reverse;
            return nextHandle;
        }
    }

    next() {
        return this._advance(true);
    }

    previous() {
        return this._advance(false);
    }

    size() {
        return this.sizer.getItemSize(this.domNode);
    }

    offset() {
        return this.sizer.getItemOffset(this.domNode);
    }

    setSize(size) {
        this.sizer.setItemSize(this.domNode, size);
        const callback = this.resizer.distributorCfg.onResized;
        if (callback) {
            callback(size, this.id, this.domNode);
        }
    }

    clearSize() {
        this.sizer.clearItemSize(this.domNode);
        const callback = this.resizer.distributorCfg.onResized;
        if (callback) {
            callback(null, this.id, this.domNode);
        }
    }
}
<|endoftext|>


<commit_before>/* File: common.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

angular.module('cnedApp').controller('CommonCtrl', function($scope, $rootScope, $location, serviceCheck, gettextCatalog, $http, configuration, dropbox, $window) {

	$scope.logout = $rootScope.loged;
	$scope.admin = $rootScope.admin;
	$scope.missingDropbox = $rootScope.dropboxWarning;
	$scope.showMenuParam = false;

	// $scope.currentUserData = {};
	$rootScope.updateListProfile = false;
	$rootScope.updateProfilListe = false;
	$rootScope.modifProfilListe = false;
	$rootScope.listDocumentDropBox = '';
	//if ($location.absUrl().indexOf('http://dl.dropboxusercontent.com/') > -1) {
	//$scope.deconnectionLink = window.location.href + 'logout';

	//};
	$scope.languages = [{
		name: 'FRANCAIS',
		shade: 'fr_FR'
	}, {
		name: 'ANGLAIS',
		shade: 'en_US'
	}];
	$scope.langue = $scope.languages[0];

	$scope.workspaceLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'listDocument';
	$scope.profilLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'profiles';
	$scope.userAccountLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'userAccount';
	$scope.adminLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'adminPanel';
	$scope.docUrl = configuration.URL_REQUEST + '/styles/images/docs.png';
	$scope.logoUrl = configuration.URL_REQUEST + '/styles/images/header_logoCned.png';
	$scope.connectLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2).replace('adaptation.html#/','adaptation.html');
	// detect current location
	$scope.isActive = function(route) {
		return route === $location.path();
	};

	$scope.showMenu = function() {
		$scope.showMenuParam = !$scope.showMenuParam;
	};

	// Changer la langue
	$scope.changerLangue = function() {
		gettextCatalog.currentLanguage = $scope.langue.shade;
		$scope.showMenuParam = false;
	};

	$rootScope.$watch('loged', function() {
		$scope.logout = $rootScope.loged;

		$scope.apply; // jshint ignore:line
	});

	$rootScope.$watch('admin', function() {
		$scope.admin = $rootScope.admin;
		$scope.apply; // jshint ignore:line
	});

	$rootScope.$watch('dropboxWarning', function() {
		$scope.guest = $rootScope.loged;
		$scope.apply; // jshint ignore:line
	});

	$scope.currentUserFunction = function() {
		$scope.sentVar = {
			userID: $rootScope.currentUser._id,
			actuel: true
		};
		$http.post(configuration.URL_REQUEST + '/chercherProfilActuel', $scope.sentVar)
			.success(function(dataActuel) {
			$scope.dataActuelFlag = dataActuel;
			$http.post(configuration.URL_REQUEST + '/chercherProfil', dataActuel)
				.success(function(data) {

				localStorage.setItem('profilActuel', JSON.stringify(data));
				$scope.setDropDownActuel = data;
				angular.element($('#headerSelect option').each(function() {
					var itemText = $(this).text();
					if (itemText === $scope.setDropDownActuel.nom) {
						$(this).prop('selected', true);
						$('#headerSelect + .customSelect .customSelectInner').text($scope.setDropDownActuel.nom);
					}
				}));
			});
		});
	};

	$rootScope.$watch('currentUser', function() {
		$scope.currentUserData = $rootScope.currentUser;
		$scope.apply; // jshint ignore:line
		console.log('$scope.currentUserData ==> ');
		console.log($scope.currentUserData);
		if ($scope.currentUserData && $scope.currentUserData._id) {
			$scope.afficherProfilsParUser();
			$scope.currentUserFunction();
		}
	});

	$rootScope.$watch('actu', function() {

		if ($rootScope.actu && $scope.dataActuelFlag) {

			if ($rootScope.actu.owner === $scope.dataActuelFlag.userID && $scope.dataActuelFlag.actuel === true) {
				$scope.currentUserFunction();
				angular.element($('#headerSelect option').each(function() {
					$('#headerSelect + .customSelect .customSelectInner').text($scope.actu.nom);
					$(this).prop('selected', true);

				}));
			}
		}

	});

	$rootScope.$watch('updateListProfile', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$rootScope.$watch('updateProfilListe', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$scope.$watch('setDropDownActuel', function() {
		if ($scope.setDropDownActuel) {
			$scope.apply;
		}
	});

	$rootScope.$watch('modifProfilListe', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$rootScope.$watch('listDocumentDropBox', function() {
		console.log($rootScope.loged);
		if ($rootScope.loged === true) {
			if ($rootScope.currentUser) {
				$scope.listDocumentDropBox = $rootScope.listDocumentDropBox + '#/listDocument?key=' + $rootScope.currentUser._id;
				$scope.apply;
			};
		} else {
			$scope.listDocumentDropBox = '';
		}
	});

	$scope.initCommon = function() {

		// var appCache = window.applicationCache;

		// console.log(appCache);
		//appCache.update(); // Attempt to update the user's cache.
		if ($location.absUrl().indexOf('key=') > -1) {
			var callbackKey = $location.absUrl().substring($location.absUrl().indexOf('key=') + 4, $location.absUrl().length);
			localStorage.setItem('compteId', callbackKey);
		};
		$('#masterContainer').show();
		var tmp = serviceCheck.getData();
		tmp.then(function(result) { // this is only run after $http completes
			if (result.loged) {
				console.log('i am loged');
				if (result.dropboxWarning === false) {
					$rootScope.dropboxWarning = false;
					$scope.missingDropbox = false;
					$rootScope.loged = true;
					$rootScope.admin = result.admin;
					$rootScope.apply; // jshint ignore:line
					if ($location.path() !== '/inscriptionContinue') {
						$location.path('/inscriptionContinue');
					}
				} else {
					$rootScope.loged = true;
					$rootScope.dropboxWarning = true;
					$rootScope.admin = result.admin;
					$rootScope.currentUser = result.user;

					$rootScope.apply; // jshint ignore:line
					var tmp4 = dropbox.shareLink(configuration.CATALOGUE_NAME, $rootScope.currentUser.dropbox.accessToken, configuration.DROPBOX_TYPE);
					tmp4.then(function(result) {
						if (result) {
							$rootScope.listDocumentDropBox = result.url;
							$rootScope.apply; // jshint ignore:line
						}
					});
				}
			} else {
				var lien = window.location.href;
				var verif = false;
				if ((lien.indexOf('http://dl.dropboxusercontent.com') > -1)) {
					verif = true;
				}
				if ($location.path() !== '/' && $location.path() !== '/passwordHelp' && verif !== true) {
					$location.path('/');
				}
			}
		});
	};

	$scope.logoutFonction = function() {
		angular.element($('#headerSelect option').each(function() {
			$('#headerSelect + .customSelect .customSelectInner').text('');
			console.log('done angular dropdown');
		}));

		// localStorage.removeItem('profilActuel');
		// localStorage.removeItem('listTagsByProfil');
		if (localStorage.getItem('compteId')) {
			localStorage.removeItem('compteId');
			console.log('se deconnecter');
			$rootScope.loged = false;
			$rootScope.dropboxWarning = false;
			$rootScope.admin = null;
			$rootScope.currentUser = {};
			$scope.listDocumentDropBox = '';
			$rootScope.listDocumentDropBox = '';
			$rootScope.apply; // jshint ignore:line
			$location.path('/#/');
		};
	}
	//displays user profiles
	$scope.afficherProfilsParUser = function() {
		$http.post(configuration.URL_REQUEST + '/profilParUser', {
			id: $scope.currentUserData._id
		})
			.success(function(data) {
			$scope.listeProfilsParUser = data;
			$http.get(configuration.URL_REQUEST + '/readTags')
				.success(function(data) {
				$scope.listTags = data;
				localStorage.setItem('listTags', JSON.stringify($scope.listTags));
			});

			if ($scope.listeProfilsParUser.length > 0) {
				$http.post(configuration.URL_REQUEST + '/chercherTagsParProfil', {
					idProfil: $scope.listeProfilsParUser[0]._id
				}).success(function(data) {
					$scope.listTagsByProfil = data;
					localStorage.setItem('listTagsByProfil', JSON.stringify($scope.listTagsByProfil));
				});
			}
		});

	};

	$scope.changeProfilActuel = function() {
		$scope.profilUser = {
			profilID: JSON.parse($scope.profilActuel)._id,
			userID: $scope.currentUserData._id,
		};

		$http.post(configuration.URL_REQUEST + '/ajouterUserProfil', $scope.profilUser)
			.success(function(data) {
			$scope.userProfilFlag = data;
			localStorage.setItem('profilActuel', $scope.profilActuel);
			$scope.userProfilFlag = data;
			if ($location.absUrl().substring($location.absUrl().length - 8, $location.absUrl().length) === '#/apercu') {
				location.reload(true);
			}

		});

		$http.get(configuration.URL_REQUEST + '/readTags')
			.success(function(data) {
			$scope.listTags = data;
			localStorage.setItem('listTags', JSON.stringify($scope.listTags));
		});

		$http.post(configuration.URL_REQUEST + '/chercherTagsParProfil', {
			idProfil: JSON.parse($scope.profilActuel)._id
		}).success(function(data) {
			$scope.listTagsByProfil = data;
			localStorage.setItem('listTagsByProfil', JSON.stringify($scope.listTagsByProfil));
		});

	};

	$scope.showLastDocument = function() {
		var lastDocument = localStorage.getItem('lastDocument');
		$scope.lastDoc = '';
		if (lastDocument && lastDocument.length > 0) {
			$scope.lastDoc = lastDocument;
			var url = lastDocument.replace('#/apercu', '');
			$scope.lastDocTitre = decodeURI(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.html')));
			return true;
		}
		return false;
	};

});<commit_msg>correction de la foction de deconnexion<commit_after>/* File: common.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

/*global $:false */

angular.module('cnedApp').controller('CommonCtrl', function($scope, $rootScope, $location, serviceCheck, gettextCatalog, $http, configuration, dropbox, $window) {

	$scope.logout = $rootScope.loged;
	$scope.admin = $rootScope.admin;
	$scope.missingDropbox = $rootScope.dropboxWarning;
	$scope.showMenuParam = false;

	// $scope.currentUserData = {};
	$rootScope.updateListProfile = false;
	$rootScope.updateProfilListe = false;
	$rootScope.modifProfilListe = false;
	$rootScope.listDocumentDropBox = '';
	//if ($location.absUrl().indexOf('http://dl.dropboxusercontent.com/') > -1) {
	//$scope.deconnectionLink = window.location.href + 'logout';

	//};
	$scope.languages = [{
		name: 'FRANCAIS',
		shade: 'fr_FR'
	}, {
		name: 'ANGLAIS',
		shade: 'en_US'
	}];
	$scope.langue = $scope.languages[0];

	$scope.workspaceLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'listDocument';
	$scope.profilLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'profiles';
	$scope.userAccountLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'userAccount';
	$scope.adminLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2) + 'adminPanel';
	$scope.docUrl = configuration.URL_REQUEST + '/styles/images/docs.png';
	$scope.logoUrl = configuration.URL_REQUEST + '/styles/images/header_logoCned.png';
	$scope.connectLink = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2).replace('adaptation.html#/', 'adaptation.html');
	// detect current location
	$scope.isActive = function(route) {
		return route === $location.path();
	};

	$scope.showMenu = function() {
		$scope.showMenuParam = !$scope.showMenuParam;
	};

	// Changer la langue
	$scope.changerLangue = function() {
		gettextCatalog.currentLanguage = $scope.langue.shade;
		$scope.showMenuParam = false;
	};

	$rootScope.$watch('loged', function() {
		$scope.logout = $rootScope.loged;

		$scope.apply; // jshint ignore:line
	});

	$rootScope.$watch('admin', function() {
		$scope.admin = $rootScope.admin;
		$scope.apply; // jshint ignore:line
	});

	$rootScope.$watch('dropboxWarning', function() {
		$scope.guest = $rootScope.loged;
		$scope.apply; // jshint ignore:line
	});

	$scope.currentUserFunction = function() {
		$scope.sentVar = {
			userID: $rootScope.currentUser._id,
			actuel: true
		};
		$http.post(configuration.URL_REQUEST + '/chercherProfilActuel', $scope.sentVar)
			.success(function(dataActuel) {
				$scope.dataActuelFlag = dataActuel;
				$http.post(configuration.URL_REQUEST + '/chercherProfil', dataActuel)
					.success(function(data) {

						localStorage.setItem('profilActuel', JSON.stringify(data));
						$scope.setDropDownActuel = data;
						angular.element($('#headerSelect option').each(function() {
							var itemText = $(this).text();
							if (itemText === $scope.setDropDownActuel.nom) {
								$(this).prop('selected', true);
								$('#headerSelect + .customSelect .customSelectInner').text($scope.setDropDownActuel.nom);
							}
						}));
					});
			});
	};

	$rootScope.$watch('currentUser', function() {
		$scope.currentUserData = $rootScope.currentUser;
		$scope.apply; // jshint ignore:line
		console.log('$scope.currentUserData ==> ');
		console.log($scope.currentUserData);
		if ($scope.currentUserData && $scope.currentUserData._id) {
			$scope.afficherProfilsParUser();
			$scope.currentUserFunction();
		}
	});

	$rootScope.$watch('actu', function() {

		if ($rootScope.actu && $scope.dataActuelFlag) {

			if ($rootScope.actu.owner === $scope.dataActuelFlag.userID && $scope.dataActuelFlag.actuel === true) {
				$scope.currentUserFunction();
				angular.element($('#headerSelect option').each(function() {
					$('#headerSelect + .customSelect .customSelectInner').text($scope.actu.nom);
					$(this).prop('selected', true);

				}));
			}
		}

	});

	$rootScope.$watch('updateListProfile', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$rootScope.$watch('updateProfilListe', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$scope.$watch('setDropDownActuel', function() {
		if ($scope.setDropDownActuel) {
			$scope.apply; // jshint ignore:line
		}
	});

	$rootScope.$watch('modifProfilListe', function() {
		if ($scope.currentUserData) {
			$scope.afficherProfilsParUser();
		}
	});

	$rootScope.$watch('listDocumentDropBox', function() {
		console.log($rootScope.loged);
		if ($rootScope.loged === true) {
			if ($rootScope.currentUser) {
				$scope.listDocumentDropBox = $rootScope.listDocumentDropBox + '#/listDocument?key=' + $rootScope.currentUser._id;
				$scope.apply; // jshint ignore:line
			}
		} else {
			$scope.listDocumentDropBox = '';
		}
	});

	$scope.initCommon = function() {

		// var appCache = window.applicationCache;

		// console.log(appCache);
		//appCache.update(); // Attempt to update the user's cache.
		if ($location.absUrl().indexOf('key=') > -1) {
			var callbackKey = $location.absUrl().substring($location.absUrl().indexOf('key=') + 4, $location.absUrl().length);
			localStorage.setItem('compteId', callbackKey);
		}
		$('#masterContainer').show();
		var tmp = serviceCheck.getData();
		tmp.then(function(result) { // this is only run after $http completes
			if (result.loged) {
				console.log('i am loged');
				if (result.dropboxWarning === false) {
					$rootScope.dropboxWarning = false;
					$scope.missingDropbox = false;
					$rootScope.loged = true;
					$rootScope.admin = result.admin;
					$rootScope.apply; // jshint ignore:line
					if ($location.path() !== '/inscriptionContinue') {
						$location.path('/inscriptionContinue');
					}
				} else {
					$rootScope.loged = true;
					$rootScope.dropboxWarning = true;
					$rootScope.admin = result.admin;
					$rootScope.currentUser = result.user;

					$rootScope.apply; // jshint ignore:line
					var tmp4 = dropbox.shareLink(configuration.CATALOGUE_NAME, $rootScope.currentUser.dropbox.accessToken, configuration.DROPBOX_TYPE);
					tmp4.then(function(result) {
						if (result) {
							$rootScope.listDocumentDropBox = result.url;
							$rootScope.apply; // jshint ignore:line
						}
					});
				}
			} else {
				var lien = window.location.href;
				var verif = false;
				if ((lien.indexOf('http://dl.dropboxusercontent.com') > -1)) {
					verif = true;
				}
				if ($location.path() !== '/' && $location.path() !== '/passwordHelp' && verif !== true) {
					$location.path('/');
				}
			}
		});
	};

	$scope.logoutFonction = function() {
		angular.element($('#headerSelect option').each(function() {
			$('#headerSelect + .customSelect .customSelectInner').text('');
			console.log('done angular dropdown');
		}));

		// localStorage.removeItem('profilActuel');
		// localStorage.removeItem('listTagsByProfil');
		if (localStorage.getItem('compteId')) {
			localStorage.removeItem('compteId');
			console.log('localStorage compteId removed');
		}
		$rootScope.loged = false;
		$rootScope.dropboxWarning = false;
		$rootScope.admin = null;
		$rootScope.currentUser = {};
		$scope.listDocumentDropBox = '';
		$rootScope.listDocumentDropBox = '';
		$rootScope.apply; // jshint ignore:line
		console.log('all variable have been unsted');
		window.location.href = $location.absUrl().substring(0, $location.absUrl().indexOf('#/') + 2);
	};
	//displays user profiles
	$scope.afficherProfilsParUser = function() {
		$http.post(configuration.URL_REQUEST + '/profilParUser', {
			id: $scope.currentUserData._id
		})
			.success(function(data) {
				$scope.listeProfilsParUser = data;
				$http.get(configuration.URL_REQUEST + '/readTags')
					.success(function(data) {
						$scope.listTags = data;
						localStorage.setItem('listTags', JSON.stringify($scope.listTags));
					});

				if ($scope.listeProfilsParUser.length > 0) {
					$http.post(configuration.URL_REQUEST + '/chercherTagsParProfil', {
						idProfil: $scope.listeProfilsParUser[0]._id
					}).success(function(data) {
						$scope.listTagsByProfil = data;
						localStorage.setItem('listTagsByProfil', JSON.stringify($scope.listTagsByProfil));
					});
				}
			});

	};

	$scope.changeProfilActuel = function() {
		$scope.profilUser = {
			profilID: JSON.parse($scope.profilActuel)._id,
			userID: $scope.currentUserData._id,
		};

		$http.post(configuration.URL_REQUEST + '/ajouterUserProfil', $scope.profilUser)
			.success(function(data) {
				$scope.userProfilFlag = data;
				localStorage.setItem('profilActuel', $scope.profilActuel);
				$scope.userProfilFlag = data;
				if ($location.absUrl().substring($location.absUrl().length - 8, $location.absUrl().length) === '#/apercu') {
					location.reload(true);
				}

			});

		$http.get(configuration.URL_REQUEST + '/readTags')
			.success(function(data) {
				$scope.listTags = data;
				localStorage.setItem('listTags', JSON.stringify($scope.listTags));
			});

		$http.post(configuration.URL_REQUEST + '/chercherTagsParProfil', {
			idProfil: JSON.parse($scope.profilActuel)._id
		}).success(function(data) {
			$scope.listTagsByProfil = data;
			localStorage.setItem('listTagsByProfil', JSON.stringify($scope.listTagsByProfil));
		});

	};

	$scope.showLastDocument = function() {
		var lastDocument = localStorage.getItem('lastDocument');
		$scope.lastDoc = '';
		if (lastDocument && lastDocument.length > 0) {
			$scope.lastDoc = lastDocument;
			var url = lastDocument.replace('#/apercu', '');
			$scope.lastDocTitre = decodeURI(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.html')));
			return true;
		}
		return false;
	};

});<|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
	.directive('correctiontool', function () {
		return {
			restrict: 'A',
			link: function (scope, element) {

				var curMouseSample;
				var dragStartSample;
				var dragEndSample;

				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				// var elem = element[0];
				var tr, col, sRaSt;

				element.bind('mousedown', function (event) {
					dragStartSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					dragEndSample = dragStartSample;
					scope.vs.select(dragStartSample, dragStartSample);
					scope.$apply();
				});

				element.bind('mousemove', function (event) {
					switch (event.which) {
					case 0:
						if (!scope.vs.getdragBarActive()) {
							// perform mouse tracking
							var mouseX = scope.dhs.getX(event);
							scope.vs.curMousePosSample = Math.round(scope.vs.curViewPort.sS + mouseX / element[0].width * (scope.vs.curViewPort.eS - scope.vs.curViewPort.sS));

							ctx.clearRect(0, 0, canvas.width, canvas.height);
							// draw crossHairs
							if (scope.cps.vals.restrictions.drawCrossHairs) {
								scope.dhs.drawCrossHairs(ctx, event, scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 'Hz');
							}
							// draw moving boundary line if moving
							scope.dhs.drawMovingBoundaryLine(ctx);

							// draw current viewport selected
							scope.dhs.drawCurViewPortSelected(ctx, false);

							// draw min max vals and name of track
							scope.dhs.drawMinMaxAndName(ctx, '', scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 2);

							if (scope.vs.curCorrectionToolNr !== undefined && !scope.vs.getdragBarActive()) {
								// var col = scope.ssffds.data[0].Columns[0];
								if (tr === undefined) {
									tr = scope.cps.getSsffTrackConfig('FORMANTS');
									col = scope.ssffds.getColumnOfTrack(tr.name, tr.columnName);
									sRaSt = scope.ssffds.getSampleRateAndStartTimeOfTrack(tr.name);
								}
								var startTimeVP = scope.vs.getViewPortStartTime();
								var endTimeVP = scope.vs.getViewPortEndTime();

								var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var nrOfSamples = colEndSampleNr - colStartSampleNr;
								var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);

								// console.log(colStartSampleNr)

								var curMouseTime = startTimeVP + (scope.dhs.getX(event) / event.originalEvent.srcElement.width) * (endTimeVP - startTimeVP);
								var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction

								var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;

								if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
									console.log('early return');
									return;
								}

								scope.vs.curPreselColumnSample = curMouseSample - colStartSampleNr;
								// console.log('--------------');
								// console.log(curMouseSample);
								// console.log(curMouseSampleTime);
								// console.log(scope.vs.curPreselColumnSample);

								// console.log(curSampleArrs.length)

								// draw preselected sample
								// var half = (1 / curSampleArrs.length) * canvas.width / 2;
								var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;

								var y = canvas.height - curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

								// draw sample
								ctx.strokeStyle = '#0DC5FF';
								ctx.fillStyle = 'white';
								// ctx.lineWidth = 4;
								ctx.beginPath();
								ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
								ctx.closePath();
								ctx.stroke();
								ctx.fill();

								// console.log(scope.vs.curPreselColumnSample);

								if (event.shiftKey) {
									var oldValue = angular.copy(curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1]);
									var newValue = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo; // SIC only using rangeTo
									// 	// console.log('##########################');
									// 	// console.log(colStartSampleNr + scope.vs.curPreselColumnSample);
									// 	// console.log(scope.vs.curCorrectionToolNr - 1);
									// 	// console.log(oldValue);
									// 	// console.log(newValue);
									curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo;
									var updateObj = scope.hists.updateCurChangeObj({
										'type': 'SSFF',
										'ssffIdx': 0, // SIC hardcoded
										'colIdx': 0, // SIC hardcoded
										'sampleBlockIdx': colStartSampleNr + scope.vs.curPreselColumnSample,
										'sampleIdx': scope.vs.curCorrectionToolNr - 1,
										'oldValue': oldValue,
										'newValue': newValue
									});

									//draw updateObj as overlay
									for (var key in updateObj) {
										curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
										x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
										y = canvas.height - updateObj[key].newValue / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

										// draw sample
										ctx.strokeStyle = '#0DC5FF';
										ctx.fillStyle = '#0DC5FF';
										// ctx.lineWidth = 4;
										ctx.beginPath();
										ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
										ctx.closePath();
										ctx.stroke();
										ctx.fill();
									}

								}
								scope.$apply();
							}
						}
						break;
					case 1:
						if (!scope.vs.getdragBarActive()) {
							setSelectDrag(event);
						}
						break;
					}
				});

				element.bind('mouseup', function (event) {
					if (!scope.vs.getdragBarActive()) {
						setSelectDrag(event);
					}
				});

				function setSelectDrag(event) {
					curMouseSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					if (curMouseSample > dragStartSample) {
						dragEndSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					} else {
						dragStartSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					}
					scope.$apply();
				}
			}
		};
	});<commit_msg>cleanup<commit_after>'use strict';

angular.module('emuwebApp')
	.directive('correctiontool', function () {
		return {
			restrict: 'A',
			link: function (scope, element) {

				var curMouseSample;
				var dragStartSample;
				var dragEndSample;

				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				// var elem = element[0];
				var tr, col, sRaSt;

				element.bind('mousedown', function (event) {
					dragStartSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					dragEndSample = dragStartSample;
					scope.vs.select(dragStartSample, dragStartSample);
					scope.$apply();
				});

				element.bind('mousemove', function (event) {
					switch (event.which) {
					case 0:
						if (!scope.vs.getdragBarActive()) {
							// perform mouse tracking
							var mouseX = scope.dhs.getX(event);
							scope.vs.curMousePosSample = Math.round(scope.vs.curViewPort.sS + mouseX / element[0].width * (scope.vs.curViewPort.eS - scope.vs.curViewPort.sS));

							ctx.clearRect(0, 0, canvas.width, canvas.height);
							// draw crossHairs
							if (scope.cps.vals.restrictions.drawCrossHairs) {
								scope.dhs.drawCrossHairs(ctx, event, scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 'Hz');
							}
							// draw moving boundary line if moving
							scope.dhs.drawMovingBoundaryLine(ctx);

							// draw current viewport selected
							scope.dhs.drawCurViewPortSelected(ctx, false);

							// draw min max vals and name of track
							scope.dhs.drawMinMaxAndName(ctx, '', scope.vs.spectroSettings.rangeFrom, scope.vs.spectroSettings.rangeTo, 2);

							if (scope.vs.curCorrectionToolNr !== undefined && !scope.vs.getdragBarActive()) {
								// var col = scope.ssffds.data[0].Columns[0];
								if (tr === undefined) {
									tr = scope.cps.getSsffTrackConfig('FORMANTS');
									col = scope.ssffds.getColumnOfTrack(tr.name, tr.columnName);
									sRaSt = scope.ssffds.getSampleRateAndStartTimeOfTrack(tr.name);
								}

								var startTimeVP = scope.vs.getViewPortStartTime();
								var endTimeVP = scope.vs.getViewPortEndTime();

								var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
								var nrOfSamples = colEndSampleNr - colStartSampleNr;
								var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);

								// console.log(colStartSampleNr)

								var curMouseTime = startTimeVP + (scope.dhs.getX(event) / event.originalEvent.srcElement.width) * (endTimeVP - startTimeVP);
								var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction

								var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;

								if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
									console.log('early return');
									return;
								}

								scope.vs.curPreselColumnSample = curMouseSample - colStartSampleNr;

								var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
								var y = canvas.height - curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

								// draw sample
								ctx.strokeStyle = '#0DC5FF';
								ctx.fillStyle = 'white';
								ctx.beginPath();
								ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
								ctx.closePath();
								ctx.stroke();
								ctx.fill();

								if (event.shiftKey) {
									var oldValue = angular.copy(curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1]);
									var newValue = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo; // SIC only using rangeTo

									curSampleArrs[scope.vs.curPreselColumnSample][scope.vs.curCorrectionToolNr - 1] = scope.vs.spectroSettings.rangeTo - scope.dhs.getY(event) / event.originalEvent.srcElement.height * scope.vs.spectroSettings.rangeTo;
									var updateObj = scope.hists.updateCurChangeObj({
										'type': 'SSFF',
										'trackName': tr.name,
										'sampleBlockIdx': colStartSampleNr + scope.vs.curPreselColumnSample,
										'sampleIdx': scope.vs.curCorrectionToolNr - 1,
										'oldValue': oldValue,
										'newValue': newValue
									});

									//draw updateObj as overlay
									for (var key in updateObj) {
										curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
										x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
										y = canvas.height - updateObj[key].newValue / (scope.vs.spectroSettings.rangeTo - scope.vs.spectroSettings.rangeFrom) * canvas.height;

										// draw sample
										ctx.strokeStyle = '#0DC5FF';
										ctx.fillStyle = '#0DC5FF';
										// ctx.lineWidth = 4;
										ctx.beginPath();
										ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
										ctx.closePath();
										ctx.stroke();
										ctx.fill();
									}

								}
							}
						}
						break;
					case 1:
						if (!scope.vs.getdragBarActive()) {
							setSelectDrag(event);
						}
						break;
					}
					scope.$apply();
				});

				element.bind('mouseup', function (event) {
					if (!scope.vs.getdragBarActive()) {
						setSelectDrag(event);
					}
				});

				function setSelectDrag(event) {
					curMouseSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
					if (curMouseSample > dragStartSample) {
						dragEndSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					} else {
						dragStartSample = curMouseSample;
						scope.vs.select(dragStartSample, dragEndSample);
					}
					scope.$apply();
				}
			}
		};
	});<|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
	.service('Wavparserservice', function Wavparserservice($q) {
		// shared service object
		var sServObj = {};

		var worker = new Worker('scripts/workers/wavParserWorker.js');
		var defer;

		// add event listener to worker to respond to messages
		worker.addEventListener('message', function (e) {
			// console.log('Worker said: ', e.data);
			if (e.data.status.type === 'SUCCESS') {
				defer.resolve(e.data.data);
			} else {
				defer.reject(e.data);
			}
		}, false);

		/**
		 * parse buffer containing wav file using webworker
		 * @param buf
		 * @returns promise
		 */
		sServObj.parseWavArrBuf = function (buf) {
			defer = $q.defer();
			worker.postMessage({
				'cmd': 'parseBuf',
				'buffer': buf
			}); // Send data to our worker.
			return defer.promise;
		};

		return sServObj;

		// shared service object
		// var sServObj = {};

		// sServObj.vs = viewState;

		// sServObj.ssffData = {};

		// sServObj.headID = 'SSFF -- (c) SHLRC\n';
		// sServObj.machineID = 'Machine IBM-PC\n';
		// sServObj.sepString = '-----------------\n';

		// sServObj.ssffData.fileURL = '';
		// sServObj.ssffData.sampleRate = -1;
		// sServObj.ssffData.startTime = -1;
		// sServObj.ssffData.origFreq = -1;
		// sServObj.ssffData.Columns = [];

		// /**
		//  * convert arraybuffer containing a wav file
		//  * to a javascript object
		//  * @param buf arraybuffer containing ssff file
		//  * @returns wav file javascript object
		//  */
		// sServObj.wav2jso = function (buf) {

		// 	var wavRep = {};

		// 	// var uIntBuffView = new Uint8Array(buf);

		// 	var curBinIdx, curBuffer, curBufferView;

		// 	// var dv = new DataView(buf);

		// 	// var ChunkSize = dv.getUint32(4)
		// 	// console.log(ChunkSize)

		// 	// ChunkId == RIFF CHECK
		// 	curBinIdx = 0;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint8Array(curBuffer);
		// 	wavRep.ChunkID = String.fromCharCode.apply(null, curBufferView);
		// 	if (wavRep.ChunkID !== 'RIFF') {
		// 		console.error('Wav read error: ChunkID not RIFF. Got ' + wavRep.ChunkID);
		// 	}

		// 	// ChunkSize
		// 	curBinIdx = 4;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint32Array(curBuffer);
		// 	wavRep.ChunkSize = curBufferView[0];
		// 	// console.log(chunkSize)

		// 	// Format == WAVE CHECK
		// 	curBinIdx = 8;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint8Array(curBuffer);
		// 	wavRep.Format = String.fromCharCode.apply(null, curBufferView);
		// 	if (wavRep.Format !== 'WAVE') {
		// 		console.error('Wav read error: Format not WAVE. Got ' + wavRep.Format);
		// 	}

		// 	// Subchunk1ID == "fmt " CHECK
		// 	curBinIdx = 12;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint8Array(curBuffer);
		// 	wavRep.Subchunk1ID = String.fromCharCode.apply(null, curBufferView);
		// 	if (wavRep.Subchunk1ID !== 'fmt ') {
		// 		console.error('Wav read error: Subchunk1ID not fmt. Got ' + wavRep.Subchunk1ID);
		// 	}

		// 	// Subchunk1Size == 16 CHECK
		// 	curBinIdx = 16;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint32Array(curBuffer);
		// 	wavRep.Subchunk1Size = curBufferView[0];
		// 	if (wavRep.Subchunk1Size !== 16) {
		// 		console.error('Wav read error: Subchunk1Size not 16');
		// 	}

		// 	// AudioFormat == 1  CHECK
		// 	curBinIdx = 20;
		// 	curBuffer = buf.subarray(curBinIdx, 2);
		// 	curBufferView = new Uint16Array(curBuffer);
		// 	wavRep.AudioFormat = curBufferView[0];
		// 	if (wavRep.AudioFormat !== 1) {
		// 		console.error('Wav read error: AudioFormat not 1');
		// 	}

		// 	// NumChannels == 1  CHECK
		// 	curBinIdx = 22;
		// 	curBuffer = buf.subarray(curBinIdx, 2);
		// 	curBufferView = new Uint16Array(curBuffer);
		// 	wavRep.NumChannels = curBufferView[0];
		// 	if (wavRep.NumChannels !== 1) {
		// 		console.error('Wav read error: NumChannels not 1');
		// 	}

		// 	// SampleRate
		// 	curBinIdx = 24;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint32Array(curBuffer);
		// 	wavRep.SampleRate = curBufferView[0];

		// 	// ByteRate
		// 	curBinIdx = 28;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint32Array(curBuffer);
		// 	wavRep.ByteRate = curBufferView[0];

		// 	// BlockAlign
		// 	curBinIdx = 32;
		// 	curBuffer = buf.subarray(curBinIdx, 2);
		// 	curBufferView = new Uint16Array(curBuffer);
		// 	wavRep.BlockAlign = curBufferView[0];

		// 	// console.error(blockAlign);

		// 	// BitsPerSample
		// 	curBinIdx = 34;
		// 	curBuffer = buf.subarray(curBinIdx, 2);
		// 	curBufferView = new Uint16Array(curBuffer);
		// 	wavRep.BitsPerSample = curBufferView[0];
		// 	if (wavRep.BitsPerSample !== 16) {
		// 		console.error('Wav read error: NumChannels not 1');
		// 	}

		// 	// Subchunk2ID
		// 	curBinIdx = 36;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint8Array(curBuffer);
		// 	wavRep.Subchunk2ID = String.fromCharCode.apply(null, curBufferView);
		// 	if (wavRep.Subchunk2ID !== 'data') {
		// 		console.error('Wav read error: BitsPerSample not 16');
		// 	}

		// 	// Subchunk2Size
		// 	curBinIdx = 40;
		// 	curBuffer = buf.subarray(curBinIdx, 4);
		// 	curBufferView = new Uint32Array(curBuffer);
		// 	wavRep.Subchunk2Size = curBufferView[0];

		// 	// Data
		// 	curBinIdx = 44;
		// 	curBuffer = buf.subarray(curBinIdx, wavRep.Subchunk2Size);
		// 	curBufferView = new Int16Array(curBuffer);
		// 	wavRep.Data = curBufferView;
		// 	// console.log(wavRep);

		// 	// finally append original array buffer
		// 	wavRep.origArrBuf = buf;
		// 	return wavRep;

		// };

		// /**
		//  * helper function to convert string to Uint8Array
		//  * @param string
		//  */
		// // sServObj.stringToUint = function (string) {};

		// /**
		//  *
		//  */
		// // sServObj.Uint8Concat = function (first, second) {};

		// return sServObj;

	});<commit_msg>removed old code<commit_after>'use strict';

angular.module('emuwebApp')
	.service('Wavparserservice', function Wavparserservice($q) {
		// shared service object
		var sServObj = {};

		var worker = new Worker('scripts/workers/wavParserWorker.js');
		var defer;

		// add event listener to worker to respond to messages
		worker.addEventListener('message', function (e) {
			// console.log('Worker said: ', e.data);
			if (e.data.status.type === 'SUCCESS') {
				defer.resolve(e.data.data);
			} else {
				defer.reject(e.data);
			}
		}, false);

		/**
		 * parse buffer containing wav file using webworker
		 * @param buf
		 * @returns promise
		 */
		sServObj.parseWavArrBuf = function (buf) {
			defer = $q.defer();
			worker.postMessage({
				'cmd': 'parseBuf',
				'buffer': buf
			}); // Send data to our worker.
			return defer.promise;
		};

		return sServObj;

	});<|endoftext|>


<commit_before>const getSlug = require('speakingurl');
const vaActions = require('./actions/VA-actions-4.21.17.json');

const moment = require('moment');

module.exports = async (knex, { users, campaigns, levels, issueAreas, types }) => {
  // Deletes ALL existing entries
  await knex('actions').del();
  await knex('activities').del();
  await knex('actions_activities').del();
  await knex('actions_types').del();
  await knex('actions_issue_areas').del();
  await knex('actions_levels').del();

  const activities = await knex('activities').insert([
    { title: 'meet', description: 'General meeting' }, // 0
    { title: 'phone', description: 'Calling voters' }, // 1
    { title: 'canvass', description: 'Door to door' }, // 2
    { title: 'outreach', description: 'Public outreach' }, // 3
    { title: 'rallies', description: 'Rallies, marches' }, // 4
    { title: 'visibility', description: 'Visibility, visual arts' }, // 5
    { title: 'precinct', description: 'Organize neighborhood' }, // 6
    { title: 'political', description: 'Organize issue groups' }, // 7
    { title: 'host', description: 'Host an event' }, // 8
    { title: 'event', description: 'Event production' }, // 9
    { title: 'policy', description: 'Policy research' }, // 10
    { title: 'advertising', description: 'Communication' }, // 11
    { title: 'polling', description: 'Polling, analytics' }, // 12
    { title: 'writing', description: 'Writing, editing' }, // 13
    { title: 'press', description: 'Press relations' }, // 14
    { title: 'social', description: 'Email, social media' }, // 15
    { title: 'website', description: 'Website, software' }, // 16
    { title: 'design', description: 'Design, production' }, // 17
    { title: 'coordinate', description: 'Coordinate volunteers' }, // 18
    { title: 'office', description: 'Office admin' }, // 19
    { title: 'data', description: 'Data management' }, // 20
    { title: 'legal', description: 'Legal' }, // 21
    { title: 'compliance', description: 'Accounting' }, // 22
    { title: 'finance', description: 'Fundraising' }, // 23
  ], ['id']);

  const antoniaUser = await knex.table('users').where('email', 'antonia@uprise.org').first();

  const getActionSlug = async (title) => {

    let found;
    let append = 0;
    let slug;

    do {
      found = false;

      if (append > 0) {
        slug = getSlug(title + append, '');
      } else {
        slug = getSlug(title, '');
      }

      const slugQuery = await knex('actions').where('slug', slug);
      if (slugQuery.length > 0) {
        found = true;
      }

      append++;

    } while (found)

    return slug;
  }

  const actionActivities = vaActions.map( (action) => ({ action_id: action.id, activity: action.skill }));

  const actions = [];
  for (let action of vaActions) {
    action.owner_id = antoniaUser.id;
    action.start_time = moment(action.start_time).format(),
    action.end_time = moment(action.end_time).format(),
    action.campaign_id = campaigns.find( (campaign) => campaign.title === action.campaign_title).id;
    action.slug = await getActionSlug(action.title);
    delete action.skills;
    delete action.campaign_title;
    const result = await knex('actions').insert([action], ['id', 'title']);
    actions.push(result[0]);
  }

  console.log('inserted actions: ');
  console.log(actions);

  // const actions = await knex('actions').insert(vaActions, ['id', 'title']);

  // const actionsActivities = await knex('actions_activities').insert([
  //   { action_id: actions[0].id, activity_id: activities[8].id },
  //   { action_id: actions[0].id, activity_id: activities[9].id },
  //   { action_id: actions[1].id, activity_id: activities[13].id },
  //   { action_id: actions[1].id, activity_id: activities[15].id },
  //   { action_id: actions[2].id, activity_id: activities[2].id },
  //   { action_id: actions[3].id, activity_id: activities[9].id },
  //   { action_id: actions[3].id, activity_id: activities[13].id },
  //   { action_id: actions[4].id, activity_id: activities[1].id },
  //   { action_id: actions[5].id, activity_id: activities[1].id },
  //   { action_id: actions[6].id, activity_id: activities[19].id },
  // ], ['id']);

  const actionActivitiesData = actions.map( (action) => ({
    action_id: action.id,
    activity_id: activities.find( activity => activity.title === action.activity).id
  }));

  console.log('actionActivitiesData');
  console.log(actionActivitiesData);
  const actionsActivitiesResult = await knex('actions_activities').insert(actionActivitiesData);

  const vaActionLevels = actions.map( (action) => ({ action_id: action.id, level_id: levels[1].id }));
  const actionsLevels = await knex('actions_levels').insert(vaActionLevels, ['id']);

  const vaActionsIssueAreasData = actions.map( (action) => ({
    action_id: action.id,
    issue_area_id: issueAreas[Math.floor(Math.random(0,9) * 10)].id
  }));

  const actionsIssueAreas = await knex('actions_issue_areas').insert(vaActionsIssueAreasData, ['id']);

  const vaActionTypes = actions.map( (action) => ({ action_id: action.id, type_id: types[0].id }));
  const actionsTypes = await knex('actions_types').insert(vaActionTypes, ['id']);

  return actions;

};
<commit_msg>Fixing activities seed data from antonia.<commit_after>const getSlug = require('speakingurl');
const vaActions = require('./actions/VA-actions-4.21.17.json');

const moment = require('moment');

module.exports = async (knex, { users, campaigns, levels, issueAreas, types }) => {
  // Deletes ALL existing entries
  await knex('actions').del();
  await knex('activities').del();
  await knex('actions_activities').del();
  await knex('actions_types').del();
  await knex('actions_issue_areas').del();
  await knex('actions_levels').del();

  const activities = await knex('activities').insert([
    { title: 'meet', description: 'General meeting' }, // 0
    { title: 'phone', description: 'Calling voters' }, // 1
    { title: 'canvass', description: 'Door to door' }, // 2
    { title: 'outreach', description: 'Public outreach' }, // 3
    { title: 'rallies', description: 'Rallies, marches' }, // 4
    { title: 'visibility', description: 'Visibility, visual arts' }, // 5
    { title: 'precinct', description: 'Organize neighborhood' }, // 6
    { title: 'political', description: 'Organize issue groups' }, // 7
    { title: 'host', description: 'Host an event' }, // 8
    { title: 'event', description: 'Event production' }, // 9
    { title: 'policy', description: 'Policy research' }, // 10
    { title: 'advertising', description: 'Communication' }, // 11
    { title: 'polling', description: 'Polling, analytics' }, // 12
    { title: 'writing', description: 'Writing, editing' }, // 13
    { title: 'press', description: 'Press relations' }, // 14
    { title: 'social', description: 'Email, social media' }, // 15
    { title: 'website', description: 'Website, software' }, // 16
    { title: 'design', description: 'Design, production' }, // 17
    { title: 'coordinate', description: 'Coordinate volunteers' }, // 18
    { title: 'office', description: 'Office admin' }, // 19
    { title: 'data', description: 'Data management' }, // 20
    { title: 'legal', description: 'Legal' }, // 21
    { title: 'compliance', description: 'Accounting' }, // 22
    { title: 'finance', description: 'Fundraising' }, // 23
  ], ['id', 'title', 'description']);

  const antoniaUser = await knex.table('users').where('email', 'antonia@uprise.org').first();

  const getActionSlug = async (title) => {

    let found;
    let append = 0;
    let slug;

    do {
      found = false;

      if (append > 0) {
        slug = getSlug(title + append, '');
      } else {
        slug = getSlug(title, '');
      }

      const slugQuery = await knex('actions').where('slug', slug);
      if (slugQuery.length > 0) {
        found = true;
      }

      append++;

    } while (found)

    return slug;
  }

  const actionActivities = [];

  const actions = [];
  for (let action of vaActions) {
    const skills = action.skills;
    delete action.skills;

    action.owner_id = antoniaUser.id;
    action.start_time = moment(action.start_time).format(),
    action.end_time = moment(action.end_time).format(),
    action.campaign_id = campaigns.find( (campaign) => campaign.title === action.campaign_title).id;
    action.slug = await getActionSlug(action.title);
    delete action.campaign_title;
    const result = await knex('actions').insert([action], ['id', 'title']);
    actions.push(result[0]);
    actionActivities.push({ id: result[0].id, activity: skills });
  }

  console.log('inserted actions: ');
  console.log(actions);

  // const actions = await knex('actions').insert(vaActions, ['id', 'title']);

  // const actionsActivities = await knex('actions_activities').insert([
  //   { action_id: actions[0].id, activity_id: activities[8].id },
  //   { action_id: actions[0].id, activity_id: activities[9].id },
  //   { action_id: actions[1].id, activity_id: activities[13].id },
  //   { action_id: actions[1].id, activity_id: activities[15].id },
  //   { action_id: actions[2].id, activity_id: activities[2].id },
  //   { action_id: actions[3].id, activity_id: activities[9].id },
  //   { action_id: actions[3].id, activity_id: activities[13].id },
  //   { action_id: actions[4].id, activity_id: activities[1].id },
  //   { action_id: actions[5].id, activity_id: activities[1].id },
  //   { action_id: actions[6].id, activity_id: activities[19].id },
  // ], ['id']);

  const actionActivitiesData = actionActivities.map( (action) => {

    console.log(activities);
    console.log(action);

    const foundActivity = activities.find( (activity) => (activity.description.toLowerCase() === action.activity.toLowerCase()));

    console.log(foundActivity);
    return {
      action_id: action.id,
      activity_id: foundActivity.id
    }
  });

  console.log('actionActivitiesData');
  console.log(actionActivitiesData);
  const actionsActivitiesResult = await knex('actions_activities').insert(actionActivitiesData);

  const vaActionLevels = actions.map( (action) => ({ action_id: action.id, level_id: levels[1].id }));
  const actionsLevels = await knex('actions_levels').insert(vaActionLevels, ['id']);

  const vaActionsIssueAreasData = actions.map( (action) => ({
    action_id: action.id,
    issue_area_id: issueAreas[Math.floor(Math.random(0,9) * 10)].id
  }));

  const actionsIssueAreas = await knex('actions_issue_areas').insert(vaActionsIssueAreasData, ['id']);

  const vaActionTypes = actions.map( (action) => ({ action_id: action.id, type_id: types[0].id }));
  const actionsTypes = await knex('actions_types').insert(vaActionTypes, ['id']);

  return actions;

};
<|endoftext|>


<commit_before>import UploadController from './controller/upload.controller';
import InfoController from './controller/info.controller';
import DownloadController from './controller/download.controller';

export default function RouteConfig($routeProvider, $locationProvider) {
    $routeProvider
        .when('/upload', {
            templateUrl: '/partials/upload.html',
            controller: UploadController,
            controllerAs: 'vm'
        })
        .when('/info/:token', {
            templateUrl: '/partials/info.html',
            controller: InfoController,
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/upload'
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
}

RouteConfig.$inject = ['$routeProvider', '$locationProvider'];<commit_msg>removed missing Download controller import<commit_after>import UploadController from './controller/upload.controller';
import InfoController from './controller/info.controller';

export default function RouteConfig($routeProvider, $locationProvider) {
    $routeProvider
        .when('/upload', {
            templateUrl: '/partials/upload.html',
            controller: UploadController,
            controllerAs: 'vm'
        })
        .when('/info/:token', {
            templateUrl: '/partials/info.html',
            controller: InfoController,
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/upload'
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
}

RouteConfig.$inject = ['$routeProvider', '$locationProvider'];<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var nconf = require('nconf');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
var helpers = require('./helpers');
var NodeCache = require("node-cache");
var uuid = require('uuid');
//this object will map the images SHA256 sums with their captions
var sha256Captions = new NodeCache({stdTTL: 60*30, checkperiod: 11});
//this contains the list of files waiting to be captioned, in the form {path:'/something/something.ext',sha256sum:'...'}
var pending = [];
var isAlreadyRunning = false;

//latest result form image processing
var latestOutcome = {timestamp:new Date().toISOString(), status:'OK', detail:'never executed'};

//application configuration, use the CLI args, the env variables and then, if nothing was found, the default values
nconf.argv().env();

nconf.defaults({
  port: 5000,
  modelPath: '/mounted/model/model_id1-501-1448236541.t7_cpu.t7',
  processFolder: '/mounted/Downloads/',
  useGPU: '-1'
});

var runNeuralTalk = function(callback){
  var spawn = require('child_process').spawn;
  var ntprocess = spawn('th', ['eval.lua','-model',nconf.get('modelPath'),'-image_folder',nconf.get('processFolder'),'-gpuid',nconf.get('useGPU'),'-dump_path','1'],{cwd:'/neuraltalk2/'});

  ntprocess.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  ntprocess.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  ntprocess.on('close', function (code) {
    console.log('child process exited with code ' + code);
    callback(code);
  });
};

var parseCaptions = function(cb){
  fs.readFile('/neuraltalk2/vis/vis.json', 'utf8',(err, data) => {
    if(err){
      latestOutcome = {timestamp:new Date().toISOString(), status:'error parsing the captions',detail:err};
      return;
    }
    var done = 0;
    JSON.parse(data).forEach(result => {
      var sha256sum = result.file_name.replace(nconf.get('processFolder'),'').split('.')[0];
      console.log("sha256sum "+sha256sum+" => "+result.caption);
      sha256Captions.set(sha256sum,result.caption);
      done++;
    });
    latestOutcome = {timestamp:new Date().toISOString(), status:'OK',processed:done};
  });
};

setInterval(()=>{
  if(pending.length === 0 || isAlreadyRunning){
    return;
  }
  isAlreadyRunning = true;
  pending.forEach((p,i) =>{
    helpers.cp(p.path,nconf.get('processFolder')+'/'+p.sha256sum+'.'+p.path.split('.').slice(-1),err => {
      if(err){
        console.error("error copying file to be processed",err)
          return;
      }
      console.log("copied file "+i+" of "+pending.length);
      if(i === pending.length -1){
        runNeuralTalk(retCode => {
          //time to parse the captions
          isAlreadyRunning = false;
          pending = [];
          console.log(" +++ return code from neuraltalk2: "+retCode);
          if(retCode !== 0){
            latestOutcome = {timestamp:new Date().toISOString(), status:'failure', retCode:retCode};
            return;
          }
          parseCaptions(()=> {
            isAlreadyRunning = false;
          });
        });
      }

    });
  });

},5000);

app.use(express.static('static'));
app.use(bodyParser.json({limit: '6mb'}));

app.get('/status',(req,res)=>{
res.json(latestOutcome);
});

app.get('/caption/:sha256sum',function(req,res){

  var key = req.params.sha256sum;
  var value = sha256Captions.get(key);
  if(key.length !== 64){
    res.status(400).json({error:"expecting a sha256 digest, it should be 64 characters long"});
  }
  if(value){
    res.json({caption:value});
    return;
  }

  res.status(404).json({error:"caption not found, it is expired or yet to be processed"});
});

app.post('/addURL',function(req,http_res){
  if(typeof req.body.url !== 'string'){
    http_res.status(400).json({error:"url field must be present and be a string containing the URL of the image to process"});
    return;
  }
  var url = req.body.url;
  var newpath = '/tmp/'+uuid.v1();
  console.log("trying to add the URL "+url+"...");
  helpers.downloadFile(url,newpath,function(err,res){
    if(err){
      http_res.status(400).json(err);
      return;
    }
    //add the extension to the filename
    fs.rename(newpath,newpath+'.'+res.extension);
    console.log({path:newpath+'.'+res.extension,sha256sum:res.sha256sum});
    pending.push({path:newpath+'.'+res.extension,sha256sum:res.sha256sum});
    http_res.json(res);
  });
});

//start the server
server.listen(nconf.get('port'), function () {
  var port = server.address().port;
  console.log(' Application started on port', port);
});
<commit_msg>remove processed files<commit_after>'use strict';
var fs = require('fs');
var nconf = require('nconf');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
var helpers = require('./helpers');
var NodeCache = require("node-cache");
var uuid = require('uuid');
//this object will map the images SHA256 sums with their captions
var sha256Captions = new NodeCache({stdTTL: 60*30, checkperiod: 11});
//this contains the list of files waiting to be captioned, in the form {path:'/something/something.ext',sha256sum:'...'}
var pending = [];
var isAlreadyRunning = false;

//latest result form image processing
var latestOutcome = {timestamp:new Date().toISOString(), status:'OK', detail:'never executed'};

//application configuration, use the CLI args, the env variables and then, if nothing was found, the default values
nconf.argv().env();

nconf.defaults({
  port: 5000,
  modelPath: '/mounted/model/model_id1-501-1448236541.t7_cpu.t7',
  processFolder: '/mounted/Downloads/',
  useGPU: '-1'
});

var runNeuralTalk = function(callback){
  var spawn = require('child_process').spawn;
  var ntprocess = spawn('th', ['eval.lua','-model',nconf.get('modelPath'),'-image_folder',nconf.get('processFolder'),'-gpuid',nconf.get('useGPU'),'-dump_path','1'],{cwd:'/neuraltalk2/'});

  ntprocess.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  ntprocess.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  ntprocess.on('close', function (code) {
    console.log('child process exited with code ' + code);
    callback(code);
  });
};

/**
 *Parse the captions and remove the corresponding processed files
 * */
var parseCaptions = function(cb){
  fs.readFile('/neuraltalk2/vis/vis.json', 'utf8',(err, data) => {
    if(err){
      latestOutcome = {timestamp:new Date().toISOString(), status:'error parsing the captions',detail:err};
      return;
    }
    var done = 0;
    JSON.parse(data).forEach(result => {
      fs.unlink(result.file_name);
      var sha256sum = result.file_name.replace(nconf.get('processFolder'),'').split('.')[0];
      console.log("sha256sum "+sha256sum+" => "+result.caption);
      sha256Captions.set(sha256sum,result.caption);
      done++;
    });
    latestOutcome = {timestamp:new Date().toISOString(), status:'OK',processed:done};
  });
};

setInterval(()=>{
  if(pending.length === 0 || isAlreadyRunning){
    return;
  }
  isAlreadyRunning = true;
  pending.forEach((p,i) =>{
    helpers.cp(p.path,nconf.get('processFolder')+'/'+p.sha256sum+'.'+p.path.split('.').slice(-1),err => {
      if(err){
        console.error("error copying file to be processed",err)
          return;
      }
      console.log("copied file "+i+" of "+pending.length);
      if(i === pending.length -1){
        runNeuralTalk(retCode => {
          //time to parse the captions
          isAlreadyRunning = false;
          pending = [];
          console.log(" +++ return code from neuraltalk2: "+retCode);
          if(retCode !== 0){
            latestOutcome = {timestamp:new Date().toISOString(), status:'failure', retCode:retCode};
            return;
          }
          parseCaptions(()=> {
            isAlreadyRunning = false;
          });
        });
      }

    });
  });

},5000);

app.use(express.static('static'));
app.use(bodyParser.json({limit: '6mb'}));

app.get('/status',(req,res)=>{
res.json(latestOutcome);
});

app.get('/caption/:sha256sum',function(req,res){

  var key = req.params.sha256sum;
  var value = sha256Captions.get(key);
  if(key.length !== 64){
    res.status(400).json({error:"expecting a sha256 digest, it should be 64 characters long"});
  }
  if(value){
    res.json({caption:value});
    return;
  }

  res.status(404).json({error:"caption not found, it is expired or yet to be processed"});
});

app.post('/addURL',function(req,http_res){
  if(typeof req.body.url !== 'string'){
    http_res.status(400).json({error:"url field must be present and be a string containing the URL of the image to process"});
    return;
  }
  var url = req.body.url;
  var newpath = '/tmp/'+uuid.v1();
  console.log("trying to add the URL "+url+"...");
  helpers.downloadFile(url,newpath,function(err,res){
    if(err){
      http_res.status(400).json(err);
      return;
    }
    //add the extension to the filename
    fs.rename(newpath,newpath+'.'+res.extension);
    console.log({path:newpath+'.'+res.extension,sha256sum:res.sha256sum});
    pending.push({path:newpath+'.'+res.extension,sha256sum:res.sha256sum});
    http_res.json(res);
  });
});

//start the server
server.listen(nconf.get('port'), function () {
  var port = server.address().port;
  console.log(' Application started on port', port);
});
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import Hello from 'COMPONENTS/Hello.vue'

Vue.use(Router)

const routes = [
  {
    path: '/hello',
    component: Hello
  }
]

export default new Router({
  routes,
  mode: 'history',
  strict: process.env.NODE_ENV !== 'production'
})
<commit_msg>[update]修改根路由为"/pre"<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import Hello from 'COMPONENTS/Hello.vue'

Vue.use(Router)

const routes = [
  {
    path: '/pre',
    component: Hello
  }
]

export default new Router({
  routes,
  mode: 'history',
  strict: process.env.NODE_ENV !== 'production'
})
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

/* eslint-disable global-require */

// The top-level (parent) route
const routes = {
  path: '',

  // Keep in mind, routes are evaluated in order
  children: [
    // The home route is added to client.js to make sure shared components are
    // added to client.js as well and not repeated in individual each route chunk.
    {
      path: '',
      load: () => import(/* webpackMode: 'eager' */ './home'),
    },
    {
      path: '/contact',
      load: () => import(/* webpackChunkName: 'contact' */ './contact'),
    },
    {
      path: '/login',
      load: () => import(/* webpackChunkName: 'login' */ './login'),
    },
    {
      path: '/register',
      load: () => import(/* webpackChunkName: 'register' */ './register'),
    },
    {
      path: '/about',
      load: () => import(/* webpackChunkName: 'about' */ './about'),
    },
    {
      path: '/privacy',
      load: () => import(/* webpackChunkName: 'privacy' */ './privacy'),
    },
    {
      path: '/admin',
      load: () => import(/* webpackChunkName: 'admin' */ './admin'),
    },

    // Wildcard routes, e.g. { path: '(.*)', ... } (must go last)
    {
      path: '(.*)',
      load: () => import(/* webpackChunkName: 'not-found' */ './not-found'),
    },
  ],

  async action({ next }) {
    // Execute each child route until one of them return the result
    const route = await next();

    // Provide default values for title, description etc.
    route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
    route.description = route.description || '';

    return route;
  },
};

// The error page is available by permanent url for development mode
if (__DEV__) {
  routes.children.unshift({
    path: '/error',
    action: require('./error').default,
  });
}

export default routes;
<commit_msg>Update comment in src/routes/index.js (#1540)<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

/* eslint-disable global-require */

// The top-level (parent) route
const routes = {
  path: '',

  // Keep in mind, routes are evaluated in order
  children: [
    // The home route is added to client.js to make sure shared components are
    // added to client.js as well and not repeated in each individual route chunk.
    {
      path: '',
      load: () => import(/* webpackMode: 'eager' */ './home'),
    },
    {
      path: '/contact',
      load: () => import(/* webpackChunkName: 'contact' */ './contact'),
    },
    {
      path: '/login',
      load: () => import(/* webpackChunkName: 'login' */ './login'),
    },
    {
      path: '/register',
      load: () => import(/* webpackChunkName: 'register' */ './register'),
    },
    {
      path: '/about',
      load: () => import(/* webpackChunkName: 'about' */ './about'),
    },
    {
      path: '/privacy',
      load: () => import(/* webpackChunkName: 'privacy' */ './privacy'),
    },
    {
      path: '/admin',
      load: () => import(/* webpackChunkName: 'admin' */ './admin'),
    },

    // Wildcard routes, e.g. { path: '(.*)', ... } (must go last)
    {
      path: '(.*)',
      load: () => import(/* webpackChunkName: 'not-found' */ './not-found'),
    },
  ],

  async action({ next }) {
    // Execute each child route until one of them return the result
    const route = await next();

    // Provide default values for title, description etc.
    route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
    route.description = route.description || '';

    return route;
  },
};

// The error page is available by permanent url for development mode
if (__DEV__) {
  routes.children.unshift({
    path: '/error',
    action: require('./error').default,
  });
}

export default routes;
<|endoftext|>


<commit_before>function select(a){if(void 0===a||a.constructor!==String)return!1;for(var b=[].slice.call(a,0),c=0,d=0,e=0,f=0;f<b.length;f++)switch(b[f]){case"#":c+=1;break;case".":d+=1;break;case" ":e+=1}var g;if(0===d&&0===c?g=document.getElementsByTagName(a):0===d&&0===e&&1==c?(a=a.replace("#",""),g=document.getElementById(a)):1==d&&0===e&&0===c?(a=a.replace(".",""),g=document.getElementsByClassName(a)):g=document.querySelectorAll(a),0===d&&0===e&&1==c){var h=g;g=[].slice.call(g,0),g.push(h)}else g=[].slice.call(g,0);for(f=0;f<g.length;f++)this[f]=g[f];return this.length=g.length,this}var webility={pageready:function(a){if(!(a instanceof Function))return!1;var b=!1,c=!1;document.onreadystatechange=function(){"complete"===document.readyState&&(b=!0)},window.onload=function(){c=!0};var d=setInterval(function(){b===!0&&c===!0&&(clearInterval(d),a())},0)},selectedElements:"",select:function(a){return new select(a)},title:function(a){var b=a,c=b.replace(/\w\S*/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1).toLowerCase()});return c},quote:function(a){a.constructor!==String&&(a=a.toString());var b=a,c='"'+b+'"';return c},capitalize:function(a){var b=a,c=b.charAt(0).toUpperCase()+a.substr(1).toLowerCase();return c},today:function(){var c,a=Date.prototype.toISOString instanceof Function,b=new Date;if(a)return c=b.toISOString().substr(0,10);var d=b.getMonth()+1,e=b.getDate();return d=d<10?"0"+d:d.toString(),e=e<10?"0"+e:e.toString(),c=b.getFullYear()+"-"+d+"-"+e},dayAfter:function(a,b){var c=new Date(a.valueOf());return c.setDate(c.getDate()+b),c=c.toISOString().substr(0,10)},getDays:function(a,b){for(var c=[],d=a;d<=b;)d=d.toISOString().substr(0,10),c.push(d),d=new Date(this.dayAfter(d,1));return c},objToArray:function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},isEmpty:function(a){return 0===Object.keys(a).length},get:function(a,b,c){if(a.constructor!==Object)return!1;if(void 0===b)return!1;void 0===c&&(c="");for(var d in a)if(d==b)return a[b];return a[b]=c,a[b]},sort:function(a,b,c){if(a.constructor===Object){if(a=this.objToArray(a),void 0===b)b="ascend";else if("ascend"!=b||"descend"!=b)return!1;if(void 0===c||"key"!=c||"value"!=c)for(var d in a[0]){c=d;break}"descend"==b?a.sort(function(a,b){return a[c]<b[c]?1:a[c]>b[c]?-1:0}):"ascend"==b&&a.sort(function(a,b){return a[c]>b[c]?1:a[c]<b[c]?-1:0});for(var e={},f=0;f<a.length;f++)e[a[f].key]=a[f].value;return e}if(a.constructor!==Array)return!1;if(!(a[0]instanceof Object))return"descend"==b?a.sort(function(a,b){return b-a}):"ascend"==b&&a.sort(),a;if(void 0===c)for(var g in a[0]){c=g;break}"descend"==b?a.sort(function(a,b){return a[c]<b[c]?1:a[c]>b[c]?-1:0}):"ascend"==b&&a.sort(function(a,b){return a[c]>b[c]?1:a[c]<b[c]?-1:0})},browser:function(){var a=!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,b="undefined"!=typeof InstallTrigger,c=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,d=!!document.documentMode,e=!d&&!!window.StyleMedia,f=!!window.chrome&&!!window.chrome.webstore,g=window.navigator.userAgent.toLowerCase().indexOf("UCBrowser")>-1,h=window.navigator.userAgent.toLowerCase().indexOf("silk")>-1,i={FireFox:b,Silk:h,Chrome:f,Edge:e,Opera:a,Safari:c,IE:d,UCBrowser:g};for(var j in i)if(i[j])return this.ismobile()?j+" Mobile":j;return"Unknown Browser"},os:function(){return console.log(window.navigator.userAgent),window.navigator.userAgent.toLowerCase().indexOf("meego")>-1?"MeeGo":/BlackBerry|BB10|PlayBook/i.test(window.navigator.userAgent)?"BlackBerry":/IEMobile|Edge|MSIE|Windows Phone/i.test(window.navigator.userAgent)?"Windows Phone":window.navigator.userAgent.toLowerCase().indexOf("win")>-1?"Windows":window.navigator.userAgent.toLowerCase().indexOf("android")>-1?"Android":window.navigator.userAgent.toLowerCase().indexOf("linux")>-1?"Linux":/iPhone|iPad|iPod/i.test(window.navigator.userAgent)?"iOS":window.navigator.userAgent.toLowerCase().indexOf("mac")>-1?"Mac OS":window.navigator.userAgent.toLowerCase().indexOf("x11")>-1?"Unix":"Unknown OS"},device:function(){return/Tablet|iPad|Silk|PlayBook/i.test(window.navigator.userAgent)?"Tablet":this.ismobile()?"Mobile":"Desktop"},ismobile:function(){var a=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|BB10|Windows Phone/i;return!!a.test(window.navigator.userAgent)},uuid:function(a){if(void 0===a){var b=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return b()+b()+"-"+b()+"-"+b()+"-"+b()+"-"+b()+b()+b()}if(a.constructor===String){var c=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return c.test(a)}}};select.prototype.ID=function(a){var b;if(void 0===a)return this[0].id;if("remove"===a){for(b=0;b<this.length;b++)this[b].id="";return this}if(a.constructor===String){for(b=0;b<this.length;b++)this[b].id=a;return this}},select.prototype.hasclass=function(a){if(void 0===a)return!1;var b;if("classList"in document.createElement("_")){for(b=0;b<this.length;b++)if(this[b].classList.contains(a))return!0;return!1}var c=new RegExp("\\b"+a+"\\b","g");for(b=0;b<this.length;b++)if(c.test(" "+this[b].className+" "))return!0;return!1},select.prototype.addclass=function(a){if(void 0===a)return!1;for(var b=0;b<this.length;b++)this[b].className+=" "+a;return this},select.prototype.removeclass=function(a){if(void 0===a)return!1;for(var b=new RegExp("\\b"+a+"\\b","g"),c=0;c<this.length;c++)this[c].className=" "+this[c].className+" ",this[c].className=this[c].className.replace(b,"");return this},module.exports=webility;
<commit_msg>updated the min file<commit_after>function select(a){for(var b=[].slice.call(a,0),c=0,d=0,e=0,f=0;f<b.length;f++)switch(b[f]){case"#":c+=1;break;case".":d+=1;break;case" ":e+=1}var g;if(0===d&&0===c?g=document.getElementsByTagName(a):0===d&&0===e&&1==c?(a=a.replace("#",""),g=document.getElementById(a)):1==d&&0===e&&0===c?(a=a.replace(".",""),g=document.getElementsByClassName(a)):g=document.querySelectorAll(a),0===d&&0===e&&1==c){var h=g;g=[].slice.call(g,0),g.push(h)}else g=[].slice.call(g,0);for(f=0;f<g.length;f++)this[f]=g[f];return this.length=g.length,this}var webility={pageready:function(a){var b=!1,c=!1;document.onreadystatechange=function(){"complete"===document.readyState&&(b=!0)},window.onload=function(){c=!0};var d=setInterval(function(){if(b===!0&&c===!0){if(clearInterval(d),!(a instanceof Function))return"ready";a()}},0)},select:function(a){if(void 0!==a&&a.constructor===String&&a.trim().length>0)return new select(a);throw new Error("Please provide a valid String for the select() function")},title:function(a){var b=a,c=b.replace(/\w\S*/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1).toLowerCase()});return c},quote:function(a){a.constructor!==String&&(a=a.toString());var b=a,c='"'+b+'"';return c},capitalize:function(a){var b=a,c=b.charAt(0).toUpperCase()+a.substr(1).toLowerCase();return c},today:function(){var c,a=Date.prototype.toISOString instanceof Function,b=new Date;if(a)return c=b.toISOString().substr(0,10);var d=b.getMonth()+1,e=b.getDate();return d=d<10?"0"+d:d.toString(),e=e<10?"0"+e:e.toString(),c=b.getFullYear()+"-"+d+"-"+e},toUTC:function(a){a=a.replace(" ","T");var b=new Date(a),c=new Date(b.getTime()+6e4*b.getTimezoneOffset());return c=c.toISOString().substr(0,16).replace("T"," ")},toLocalTime:function(a){a=a.replace("T"," ");var b=new Date(a+" UTC"),c=new Date(b.getTime()-6e4*b.getTimezoneOffset());return c=c.toISOString().substr(0,16).replace("T"," ")},dayAfter:function(a,b){var c=new Date(a.valueOf());return c.setDate(c.getDate()+b),c=c.toISOString().substr(0,10)},getDays:function(a,b){var c=[];b=new Date(b);for(var d=new Date(a);d<=b;)d=d.toISOString().substr(0,10),c.push(d),d=new Date(this.dayAfter(d,1));return c},objToArray:function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},isEmpty:function(a){if(void 0===a)throw new Error("Please provide a valid Object/Array for the isEmpty() function");return 0===Object.keys(a).length},get:function(a,b,c){if(a.constructor!==Object)throw new Error("Please provide a valid Object for the get() function");if(void 0===b)throw new Error("Please provide a valid String as a key for the get() function");void 0===c&&(c=null);for(var d in a)if(d==b)return a[b];return a[b]=c,a[b]},sort:function(a,b,c){if(void 0===a)throw new Error("Please provide a valid Object/Array for the sort() function");if(void 0===b)b="ascend";else if("ascend"!=b||"descend"!=b)throw new Error("ascend & descend are the only options for the sort() function");if(a.constructor===Object){if(a=this.objToArray(a),void 0===c||"key"!=c||"value"!=c)for(var d in a[0]){c=d;break}"descend"==b?a.sort(function(a,b){return a[c]<b[c]?1:a[c]>b[c]?-1:0}):"ascend"==b&&a.sort(function(a,b){return a[c]>b[c]?1:a[c]<b[c]?-1:0});for(var e={},f=0;f<a.length;f++)e[a[f].key]=a[f].value;return e}if(a.constructor===Array){if(!(a[0]instanceof Object))return"descend"==b?a.sort(function(a,b){return b-a}):"ascend"==b&&a.sort(),a;if(void 0===c)for(var g in a[0]){c=g;break}"descend"==b?a.sort(function(a,b){return a[c]<b[c]?1:a[c]>b[c]?-1:0}):"ascend"==b&&a.sort(function(a,b){return a[c]>b[c]?1:a[c]<b[c]?-1:0})}},browser:function(){var a=!!window.opr&&!!opr.addons||!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0,b="undefined"!=typeof InstallTrigger,c=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0,d=!!document.documentMode,e=!d&&!!window.StyleMedia,f=!!window.chrome&&!!window.chrome.webstore,g=window.navigator.userAgent.toLowerCase().indexOf("UCBrowser")>-1,h=window.navigator.userAgent.toLowerCase().indexOf("silk")>-1,i={FireFox:b,Silk:h,Chrome:f,Edge:e,Opera:a,Safari:c,IE:d,UCBrowser:g};for(var j in i)if(i[j])return this.ismobile()?j+" Mobile":j;return"Unknown Browser"},os:function(){return console.log(window.navigator.userAgent),window.navigator.userAgent.toLowerCase().indexOf("meego")>-1?"MeeGo":/BlackBerry|BB10|PlayBook/i.test(window.navigator.userAgent)?"BlackBerry":/IEMobile|Edge|MSIE|Windows Phone/i.test(window.navigator.userAgent)?"Windows Phone":window.navigator.userAgent.toLowerCase().indexOf("win")>-1?"Windows":window.navigator.userAgent.toLowerCase().indexOf("android")>-1?"Android":window.navigator.userAgent.toLowerCase().indexOf("linux")>-1?"Linux":/iPhone|iPad|iPod/i.test(window.navigator.userAgent)?"iOS":window.navigator.userAgent.toLowerCase().indexOf("mac")>-1?"Mac OS":window.navigator.userAgent.toLowerCase().indexOf("x11")>-1?"Unix":"Unknown OS"},device:function(){return/Tablet|iPad|Silk|PlayBook/i.test(window.navigator.userAgent)?"Tablet":this.ismobile()?"Mobile":"Desktop"},ismobile:function(){var a=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|BB10|Windows Phone/i;return!!a.test(window.navigator.userAgent)},uuid:function(a){if(void 0===a){var b=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return b()+b()+"-"+b()+"-"+b()+"-"+b()+"-"+b()+b()+b()}if(a.constructor===String){var c=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return c.test(a)}}};select.prototype.ID=function(a){var b;if(!this[0])throw new Error("No element was selected");if(void 0===a)return this[0].id||"No ID";if("remove"===a){for(b=0;b<this.length;b++)this[b].id="";return this}if(a.constructor===String){for(b=0;b<this.length;b++)this[b].id=a;return this}},select.prototype.hasclass=function(a){if(!this[0])throw new Error("No element was selected");if(void 0===a)throw new Error("Please provide a valid String for the hasclass() function");var b;if("classList"in document.createElement("_")){for(b=0;b<this.length;b++)if(this[b].classList.contains(a))return!0;return!1}var c=new RegExp("\\b"+a+"\\b","g");for(b=0;b<this.length;b++)if(c.test(" "+this[b].className+" "))return!0;return!1},select.prototype.addclass=function(a){if(void 0===a)throw new Error("Please provide a valid String for the hasclass() function");for(var b=0;b<this.length;b++)this[b].className+=" "+a;return this},select.prototype.removeclass=function(a){if(void 0===a)throw new Error("Please provide a valid String for the hasclass() function");for(var b=new RegExp("\\b"+a+"\\b","g"),c=0;c<this.length;c++)this[c].className=" "+this[c].className+" ",this[c].className=this[c].className.replace(b,"");return this},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=webility),exports.webility=webility):root.webility=webility;
<|endoftext|>


<commit_before>const express = require('express');
const router 	= express.Router();
const multer  = require('multer');
const upload  = multer({dest: 'uploads/'});
const path    = require('path');
const compile = require('../latex/latex');

// POST method route
router.post('/', upload.single('zip_file'), function (req, res) {
  const filename = req.file.filename;
  const compiler = req.file.compiler || 'pdflatex';
  compile(compiler, filename)
    .then((file) => sendResultingFile(file, res))
    .catch((error) => errorHandler(error, res));
});

function sendResultingFile(file, res) {
  res.sendFile(path.resolve(file), function (err) {
    if(err) {
      console.error('Error sending the file: ' + err);
      res.status(400).send(err);
    }
  });
}

function errorHandler(error, res) {
  console.error(error);
  res.status(400).send(error);
}

module.exports = router;<commit_msg>Make sure the compiler post parameter is an allowed one<commit_after>const express = require('express');
const router 	= express.Router();
const multer  = require('multer');
const upload  = multer({dest: 'uploads/'});
const path    = require('path');
const compile = require('../latex/latex');

// POST method route
router.post('/', upload.single('zip_file'), function (req, res) {
  const filename = req.file.filename;
  let compiler = req.file.compiler;
  // Just making sure to run one of this allowed exes
  if(compiler != 'pdflatex'
    || compiler != 'latexmk'
    || compiler != 'xelatex') {
    compiler = 'pdflatex';
  }
  compile(compiler, filename)
    .then((file) => sendResultingFile(file, res))
    .catch((error) => errorHandler(error, res));
});

function sendResultingFile(file, res) {
  res.sendFile(path.resolve(file), function (err) {
    if(err) {
      console.error('Error sending the file: ' + err);
      res.status(400).send(err);
    }
  });
}

function errorHandler(error, res) {
  console.error(error);
  res.status(400).send(error);
}

module.exports = router;<|endoftext|>


<commit_before>/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
<commit_msg>added angularfire2 map<commit_after>/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      'angularfire2':'npm:angularfire2/bundles/angularfire2.umd.js',
      'firebase':'npm:firebase/firebase.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
<|endoftext|>