<commit_before>Seed({
		name : "Mold.Lib.UrlRouter",
		dna : "class",
		author : "Jan Kaufmann",
		polymorph : true,
		include : [
			"Mold.Lib.Observer"
		]
	},
	function(routes){
		var _path,
			_params,
			_hashes,
			_routes = routes,
			_loadedSeeds = {},
			_request = false,
			_response = false,
			_next = false,
			_session = false;

		//var _seed = seed;
		var _events = Mold.Lib.Observer;

		var _location =  {
			pathname : "",
			search : "",
			hash : "",
			methode : ""
		};

		var _location = (Mold.isNodeJS) ? _location : document.location;

		var that = this;

		this.publics =  {
			setLocation : function(location){
				_location = location;
			},
			setServerParameter : function(request, response, session, next){
				_request = request;
				_response = response;
				_session = session;
				_next = next;
			},
			markSeedAsLoaded : function(seedName, seed){
				_loadedSeeds[seedName] = seed;
			},
			removeSeed : function(seedName){
				delete _loadedSeeds[seedName];
			},
			setEventObject : function(events){
				_events = events;
			},
			isSeedLoaded : function(seedName){
				if(_loadedSeeds[seedName]){
					return true;
				}else{
					return false;
				}
			},
			getLoadedSeed : function(seedName){
				return _loadedSeeds[seedName] || false;
			},
			isParameter : function(path, indent, params){
				path = path.replace(indent, "");
				for(var param in params){
					if(params[param] === path){
						return true;
					}
				}
				return false;
			},

			isUrl : function(route, path){

				route = route.replace("#", "");
				var replaced = false;
				var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
					replaced = true;
					if(arguments[1] == "*"){
						return "(.*?)"+arguments[3];
					}else{
						return "(.*?)[\/|$]";
					}

				});
				routeRegExp += (replaced || routeRegExp === "/") ? "" : "/" ;

				var hashRegExp = new RegExp(routeRegExp , "gim");

				if(path.substring(path.length -1, path.length) !== "/"){
					path += "/";
				}
				return hashRegExp.test(path);
			},

			isHash : function(route, hash){
				route = route.replace("#", "");
				var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
					if(arguments[1] == "*"){
						return "(.*?)"+arguments[3];
					}else{
						return "(.*?)[\/|$]";
					}
				});

				var hashRegExp = new RegExp(routeRegExp, "gim");
				if(hash.substring(hash.length -1, hash.length) !== "/"){
					hash += "/";
				}
				return hashRegExp.test(hash);
			},
			getParameter : function(route, hash, path, type){
				var value = false;
				if(type === "hash" ){
					route = route.split("#")[1];
					value = hash;
				}else if(type === "path"){
					//route = route.split("#")[1];
					value = path;
				}

				var parameterNames = {}
				if(route){

					var collectedParameter = [];
					var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
						collectedParameter.push(arguments[2]);
						if(arguments[1] == "*"){
							if(arguments[3] == ""){
								return "(.*?)$";
							}else{
								return "(.*?)"+arguments[3];
							}
						}else{
							return "(.*?)[\/|$]";
						}
					});

					var hashRegExp = new RegExp(routeRegExp, "gim");
					if(value.substring(value.length -1, value.length) !== "/"){
						value += "/";
					}

					value.replace(hashRegExp, function(){
						var paramCounter = 0;

						for(var i = 1; i < arguments.length-2; i++){
							parameterNames[collectedParameter[paramCounter]] = arguments[i];
							paramCounter++;
						}
					});
					return parameterNames;
				}
			},

			removeMethod : function(route){
				if(route.substring(0,3) === "GET"){
					route = route.substring(3, route.length);
				}
				if(route.substring(0,3) === "PUT"){
					route = route.substring(3, route.length);
				}
				if(route.substring(0,4) === "POST"){
					route = route.substring(4, route.length);
				}
				if(route.substring(0,6) === "DELETE"){
					route = route.substring(6, route.length);
				}
				return route;
			},

			getMethod : function(route){
				if(route.substring(0,3) === "GET"){
					return "GET";
				}
				if(route.substring(0,3) === "PUT"){
					return "PUT"
				}
				if(route.substring(0,4) === "POST"){
					return "POST";
				}
				if(route.substring(0,6) === "DELETE"){
					return "DELETE"
				}
				return false;
			},

			parseRoutes : function (routes, path, output){
				var output = output || [],
					path = path || "";

				for(var route in routes){
					//clean route from method if it is set
					var cleanRoute = this.removeMethod(route);
					var first = cleanRoute.substring(0,1);
					switch(first){
						case "/":

							if(that.isUrl(cleanRoute, _path)){

								path += first;
								output = that.getNextRoute(routes, route, path, output, "path");

							}
							break;
						case "?":
							if(that.isParameter(cleanRoute, first, _params)){
								output = that.getNextRoute(routes, route, path, output, "param");
							}
							break;
						case "#":

							if(that.isHash(cleanRoute, _hashes)){
								output = that.getNextRoute(routes, route, path, output, "hash");
							}
							break;
					}
				}
				return output;
			},

			getNextRoute : function(routes, route, path, output, type){

				if( typeof routes[route] === "object"){
					that.parseRoutes(routes[route], path, output);
				}else{
					var parameter = that.getParameter(route, _hashes, _path, type),
						method = that.getMethod(route),
						addRoute = true;

					if(Mold.isNodeJS && method){
						if(method !== _request.method){
							addRoute = false;
						}
					}
					if(addRoute){
						output.push({
							method : method,
							route : routes[route],
							parameter : parameter
						});
					}
				}
				return output;
			},

			loadSeed : function(route, parameter, trigger){

				Mold.load({ name : route }).bind(function(seedName){

					if(!that.isSeedLoaded(seedName)){

						var selectedSeed = Mold.getSeed(seedName);
						var dna = Mold.getDNABySeedName(seedName);

						if(dna.createBy){

							switch(dna.createBy){
								case "new":
									if(parameter){
										var seed = new selectedSeed(parameter);
									}else{
										var seed = new selectedSeed();
									}
									break;
								default:
									break;
							}

						}
						that.markSeedAsLoaded(seedName, seed);
					}

					var selectedSeed = that.getLoadedSeed(seedName);
					if(trigger){
						if(typeof selectedSeed.trigger === "function"){

							if(selectedSeed.actions["@"+trigger.method.toUpperCase()]){
								selectedSeed.trigger(trigger.method.toUpperCase(), trigger.data);
							}else{
								trigger.data.next();
							}
						};
					}
				});
			},

			buildTrigger : function(parameter){

				return {
					method : _request.method || false,
					data : {
						param : parameter,
						request : _request,
						rawResponse : _response,
						response : _response._moldResponse || false,
						session : _session,
						next : _next || function(){}
					}
				}
			},

			initRoutes  : function(){
				_path = _location.pathname,
				_params = _location.search.replace("?", "").split("&"),
				_hashes = _location.hash.replace("#", "");
				var foundRoutes = that.parseRoutes(_routes);
				if(foundRoutes.length > 0){
					for(var i = 0; i < foundRoutes.length; i++){
						var route = foundRoutes[i];
						var parameter = false;
						if(typeof route === "object"){
							parameter = route.parameter;
							route = route.route;
						}

						if(typeof route === "function"){
							if(parameter){
								var trigger = this.buildTrigger(parameter);
								route(trigger);
							}else{
								route();
							}
						}else if(route.substring(0,1) === "@"){
							if(route.indexOf("@ready->") > -1){
								Mold.ready(function(){
									that.loadSeed(route.split("@ready->")[1], parameter);
								});
							}else{

								Mold.ready(function(){
									var trigger = that.buildTrigger(parameter);
									_events.trigger(route.replace("@", ""), trigger.data, { saveTrigger : true });
								});
							}
						}else if(route.substring(0,4) === "Mold"){
							parameter = parameter || {};
							parameter.eventHandler = _events;
							var trigger = this.buildTrigger(parameter);
							that.loadSeed(route, parameter, trigger);
						}
					}
					return true;
				}else{
					console.log("no route found")
					if(!Mold.isNodeJS){
						//Mold.log("Error", { code : 10, dnaname: "urlrouter", error : "No route found! " +_seed.name+ " "});
					}
					return false;
				}
			}
		}
	}
);<commit_msg>status rule added<commit_after>Seed({
		name : "Mold.Lib.UrlRouter",
		dna : "class",
		author : "Jan Kaufmann",
		polymorph : true,
		include : [
			"Mold.Lib.Observer"
		]
	},
	function(routes){
		var _path,
			_params,
			_hashes,
			_routes = routes,
			_loadedSeeds = {},
			_request = false,
			_response = false,
			_next = false,
			_session = false;

		//var _seed = seed;
		var _events = Mold.Lib.Observer;

		var _location =  {
			pathname : "",
			search : "",
			hash : "",
			methode : ""
		};

		var _location = (Mold.isNodeJS) ? _location : document.location;

		var that = this;

		this.publics =  {
			setLocation : function(location){
				_location = location;
			},
			setServerParameter : function(request, response, session, next){
				_request = request;
				_response = response;
				_session = session;
				_next = next;
			},
			markSeedAsLoaded : function(seedName, seed){
				_loadedSeeds[seedName] = seed;
			},
			removeSeed : function(seedName){
				delete _loadedSeeds[seedName];
			},
			setEventObject : function(events){
				_events = events;
			},
			isSeedLoaded : function(seedName){
				if(_loadedSeeds[seedName]){
					return true;
				}else{
					return false;
				}
			},
			getLoadedSeed : function(seedName){
				return _loadedSeeds[seedName] || false;
			},
			isParameter : function(path, indent, params){
				path = path.replace(indent, "");
				for(var param in params){
					if(params[param] === path){
						return true;
					}
				}
				return false;
			},

			isUrl : function(route, path){

				route = route.replace("#", "");
				var replaced = false;
				var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
					replaced = true;
					if(arguments[1] == "*"){
						return "(.*?)"+arguments[3];
					}else{
						return "(.*?)[\/|$]";
					}

				});
				routeRegExp += (replaced || routeRegExp === "/") ? "" : "/" ;

				var hashRegExp = new RegExp(routeRegExp , "gim");

				if(path.substring(path.length -1, path.length) !== "/"){
					path += "/";
				}
				return hashRegExp.test(path);
			},

			isHash : function(route, hash){
				route = route.replace("#", "");
				var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
					if(arguments[1] == "*"){
						return "(.*?)"+arguments[3];
					}else{
						return "(.*?)[\/|$]";
					}
				});

				var hashRegExp = new RegExp(routeRegExp, "gim");
				if(hash.substring(hash.length -1, hash.length) !== "/"){
					hash += "/";
				}
				return hashRegExp.test(hash);
			},
			getParameter : function(route, hash, path, type){
				var value = false;
				if(type === "hash" ){
					route = route.split("#")[1];
					value = hash;
				}else if(type === "path"){
					//route = route.split("#")[1];
					value = path;
				}

				var parameterNames = {}
				if(route){

					var collectedParameter = [];
					var routeRegExp = route.replace(/(\*|\:)(.*?)(\/|$)/gim, function(){
						collectedParameter.push(arguments[2]);
						if(arguments[1] == "*"){
							if(arguments[3] == ""){
								return "(.*?)$";
							}else{
								return "(.*?)"+arguments[3];
							}
						}else{
							return "(.*?)[\/|$]";
						}
					});

					var hashRegExp = new RegExp(routeRegExp, "gim");
					if(value.substring(value.length -1, value.length) !== "/"){
						value += "/";
					}

					value.replace(hashRegExp, function(){
						var paramCounter = 0;

						for(var i = 1; i < arguments.length-2; i++){
							parameterNames[collectedParameter[paramCounter]] = arguments[i];
							paramCounter++;
						}
					});
					return parameterNames;
				}
			},

			removeMethod : function(route){
				if(route.substring(0,3) === "GET"){
					route = route.substring(3, route.length);
				}
				if(route.substring(0,3) === "PUT"){
					route = route.substring(3, route.length);
				}
				if(route.substring(0,4) === "POST"){
					route = route.substring(4, route.length);
				}
				if(route.substring(0,6) === "DELETE"){
					route = route.substring(6, route.length);
				}
				return route;
			},

			getMethod : function(route){
				if(route.substring(0,3) === "GET"){
					return "GET";
				}
				if(route.substring(0,3) === "PUT"){
					return "PUT"
				}
				if(route.substring(0,4) === "POST"){
					return "POST";
				}
				if(route.substring(0,6) === "DELETE"){
					return "DELETE"
				}
				return false;
			},

			parseRoutes : function (routes, path, output){
				var output = output || [],
					path = path || "";

				for(var route in routes){
					//clean route from method if it is set
					var cleanRoute = this.removeMethod(route);
					var first = cleanRoute.substring(0,1);
					switch(first){
						case "/":

							if(that.isUrl(cleanRoute, _path)){

								path += first;
								output = that.getNextRoute(routes, route, path, output, "path");

							}
							break;
						case "?":
							if(that.isParameter(cleanRoute, first, _params)){
								output = that.getNextRoute(routes, route, path, output, "param");
							}
							break;
						case "#":

							if(that.isHash(cleanRoute, _hashes)){
								output = that.getNextRoute(routes, route, path, output, "hash");
							}
							break;
					}
				}
				return output;
			},

			getNextRoute : function(routes, route, path, output, type){

				if( typeof routes[route] === "object"){
					that.parseRoutes(routes[route], path, output);
				}else{
					var parameter = that.getParameter(route, _hashes, _path, type),
						method = that.getMethod(route),
						addRoute = true;

					if(Mold.isNodeJS && method){
						if(method !== _request.method){
							addRoute = false;
						}
					}
					if(addRoute){
						output.push({
							method : method,
							route : routes[route],
							parameter : parameter
						});
					}
				}
				return output;
			},

			loadSeed : function(route, parameter, trigger){

				Mold.load({ name : route }).bind(function(seedName){

					if(!that.isSeedLoaded(seedName)){

						var selectedSeed = Mold.getSeed(seedName);
						var dna = Mold.getDNABySeedName(seedName);

						if(dna.createBy){

							switch(dna.createBy){
								case "new":
									if(parameter){
										var seed = new selectedSeed(parameter);
									}else{
										var seed = new selectedSeed();
									}
									break;
								default:
									break;
							}

						}
						that.markSeedAsLoaded(seedName, seed);
					}

					var selectedSeed = that.getLoadedSeed(seedName);
					if(trigger){
						if(typeof selectedSeed.trigger === "function"){

							if(selectedSeed.actions["@"+trigger.method.toUpperCase()]){
								selectedSeed.trigger(trigger.method.toUpperCase(), trigger.data);
							}else{
								trigger.data.next();
							}
						};
					}
				});
			},

			buildTrigger : function(parameter){

				return {
					method : _request.method || false,
					data : {
						param : parameter,
						request : _request,
						rawResponse : _response,
						response : _response._moldResponse || false,
						session : _session,
						next : _next || function(){}
					}
				}
			},

			initRoutes  : function(){
				_path = _location.pathname,
				_params = _location.search.replace("?", "").split("&"),
				_hashes = _location.hash.replace("#", "");
				var foundRoutes = that.parseRoutes(_routes);
				if(foundRoutes.length > 0){
					for(var i = 0; i < foundRoutes.length; i++){
						var route = foundRoutes[i];
						var parameter = false;
						if(typeof route === "object"){
							parameter = route.parameter;
							route = route.route;
						}

						if(typeof route === "function"){
							if(parameter){
								var trigger = this.buildTrigger(parameter);
								route(trigger);
							}else{
								route();
							}
						}else if(route.substring(0,1) === "@"){
							if(route.indexOf("@ready->") > -1){
								Mold.ready(function(){
									that.loadSeed(route.split("@ready->")[1], parameter);
								});
							}else{

								Mold.ready(function(){
									var trigger = that.buildTrigger(parameter);
									_events.trigger(route.replace("@", ""), trigger.data, { saveTrigger : true });
								});
							}
						}else if(route.substring(0,4) === "Mold"){

							parameter = parameter || {};
							parameter.eventHandler = _events;
							var trigger = this.buildTrigger(parameter);
							that.loadSeed(route, parameter, trigger);

						}else if(/^[234]0[0-9]/.test(route)){
							console.log("redirect gefunden")

							var parts =  route.split("->"),
								statusCode = Mold.trim(parts[0]),
								url = (parts[1]) ? Mold.trim(parts[1]) : false;

							if(_response._moldResponse){
								_response._moldResponse.setStatus(statusCode, url);
								_next();
							}
						}
					}
					return true;
				}else{
					console.log("no route found")
					if(!Mold.isNodeJS){
						//Mold.log("Error", { code : 10, dnaname: "urlrouter", error : "No route found! " +_seed.name+ " "});
					}
					return false;
				}
			}
		}
	}
);<|endoftext|>


<commit_before>import Vue from 'vue';

import fetch from '../../fetch';

export default {
    namespaced: true,
    state: {
        // Clients
        allClients: [],

        // Projects
        allProjects: [],
    },
    getters: {
        // Clients
        getSelectClients: state => {
            return state.allClients.map(client => {return {id: client.url, text: client.name}});
        },

        // Projects
        getSelectProjects: state => {
            return state.allClients.map(client => {
                // TODO: Should use getClientProjects getter instead to reduce code
                const projects = state.allProjects.filter(project => {
                    return project.client == client.url;
                });
                return {
                    text: client.name,
                    children: projects.map(project => {
                        return {
                            id: project.url,
                            text: project.name,
                        };
                    }),
                };
            });
            this.projects = data.map(function(client) {
                let clientProjects = client.projects.map(function(project) {
                    return { id: project.url, text: project.name };
                });
                return { text: client.name, children: clientProjects };
            });
            return state.allProjects.map(project => {return {id: project.url, text: project.name}});
        },

        // Clients & Projects
        getClientProjects: state => clientUrl => {
            return state.allProjects.filter(project => {return project.client == clientUrl})
        },
    },
    mutations: {
        // Clients
        setClients: (state, clients) => state.allClients = clients,
        addClient: (state, client) => state.allClients.unshift(client),
        updateClient: (state, opts) => Vue.set(state.allClients, opts.index, opts.client),
        removeClient: (state, index) => Vue.delete(state.allClients, index),

        // Projects
        setProjects: (state, projects) => state.allProjects = projects,
        addProject: (state, project) => state.allProjects.unshift(project),
        updateProject: (state, opts) => Vue.set(state.allProjects, opts.index, opts.project),
        removeProject: (state, index) => Vue.delete(state.allProjects, index),
    },
    actions: {
        // Clients
        getClients({commit}) {
            commit('setLoading', true, {root: true});
            fetch.get(timestrapConfig.API_URLS.CLIENTS).then(response => {
                commit('setClients', response.data);
                commit('setLoading', false, {root: true});
            }).catch(error => console.log(error));
        },
        createClient({commit}, client) {
            fetch.post(timestrapConfig.API_URLS.CLIENTS, client).then(response => {
                commit('addClient', response.data);
            }).catch(error => console.log(error));
        },
        editClient({commit, state}, client) {
            fetch.put(client.url, client).then(response => {
                const index = state.allClients.findIndex(item => {return item.id === response.data.id});
                commit('updateClient', {index: index, client: response.data});
            }).catch(error => console.log(error));

        },
        deleteClient({commit, state}, index) {
            fetch.delete(state.allClients[index].url).then(response => {
                commit('removeClient', index);
            }).catch(error => console.log(error));
        },

        // Projects
        getProjects({commit}) {
            commit('setLoading', true, {root: true});
            fetch.get(timestrapConfig.API_URLS.PROJECTS).then(response => {
                commit('setProjects', response.data);
                commit('setLoading', false, {root: true});
            }).catch(error => console.log(error));
        },
        createProject({commit}, project) {
            fetch.post(timestrapConfig.API_URLS.PROJECTS, project).then(response => {
                commit('addProject', response.data);
            }).catch(error => console.log(error));
        },
        editProject({commit, state}, project) {
            fetch.put(project.url, project).then(response => {
                const index = state.allProjects.findIndex(item => {return item.id === response.data.id});
                commit('updateProject', {index: index, project: response.data});
            }).catch(error => console.log(error));

        },
        deleteProject({commit, state}, index) {
            fetch.delete(state.allProjects[index].url).then(response => {
                commit('removeProject', index);
            }).catch(error => console.log(error));
        },
    }
};
<commit_msg>Fix removing old client code form client store<commit_after>import Vue from 'vue';

import fetch from '../../fetch';

export default {
    namespaced: true,
    state: {
        // Clients
        allClients: [],

        // Projects
        allProjects: [],
    },
    getters: {
        // Clients
        getSelectClients: state => {
            return state.allClients.map(client => {return {id: client.url, text: client.name}});
        },

        // Projects
        getSelectProjects: state => {
            return state.allClients.map(client => {
                // TODO: Should use getClientProjects getter instead to reduce code
                const projects = state.allProjects.filter(project => {
                    return project.client == client.url;
                });
                return {
                    text: client.name,
                    children: projects.map(project => {
                        return {
                            id: project.url,
                            text: project.name,
                        };
                    }),
                };
            });
        },

        // Clients & Projects
        getClientProjects: state => clientUrl => {
            return state.allProjects.filter(project => {return project.client == clientUrl})
        },
    },
    mutations: {
        // Clients
        setClients: (state, clients) => state.allClients = clients,
        addClient: (state, client) => state.allClients.unshift(client),
        updateClient: (state, opts) => Vue.set(state.allClients, opts.index, opts.client),
        removeClient: (state, index) => Vue.delete(state.allClients, index),

        // Projects
        setProjects: (state, projects) => state.allProjects = projects,
        addProject: (state, project) => state.allProjects.unshift(project),
        updateProject: (state, opts) => Vue.set(state.allProjects, opts.index, opts.project),
        removeProject: (state, index) => Vue.delete(state.allProjects, index),
    },
    actions: {
        // Clients
        getClients({commit}) {
            commit('setLoading', true, {root: true});
            fetch.get(timestrapConfig.API_URLS.CLIENTS).then(response => {
                commit('setClients', response.data);
                commit('setLoading', false, {root: true});
            }).catch(error => console.log(error));
        },
        createClient({commit}, client) {
            fetch.post(timestrapConfig.API_URLS.CLIENTS, client).then(response => {
                commit('addClient', response.data);
            }).catch(error => console.log(error));
        },
        editClient({commit, state}, client) {
            fetch.put(client.url, client).then(response => {
                const index = state.allClients.findIndex(item => {return item.id === response.data.id});
                commit('updateClient', {index: index, client: response.data});
            }).catch(error => console.log(error));

        },
        deleteClient({commit, state}, index) {
            fetch.delete(state.allClients[index].url).then(response => {
                commit('removeClient', index);
            }).catch(error => console.log(error));
        },

        // Projects
        getProjects({commit}) {
            commit('setLoading', true, {root: true});
            fetch.get(timestrapConfig.API_URLS.PROJECTS).then(response => {
                commit('setProjects', response.data);
                commit('setLoading', false, {root: true});
            }).catch(error => console.log(error));
        },
        createProject({commit}, project) {
            fetch.post(timestrapConfig.API_URLS.PROJECTS, project).then(response => {
                commit('addProject', response.data);
            }).catch(error => console.log(error));
        },
        editProject({commit, state}, project) {
            fetch.put(project.url, project).then(response => {
                const index = state.allProjects.findIndex(item => {return item.id === response.data.id});
                commit('updateProject', {index: index, project: response.data});
            }).catch(error => console.log(error));

        },
        deleteProject({commit, state}, index) {
            fetch.delete(state.allProjects[index].url).then(response => {
                commit('removeProject', index);
            }).catch(error => console.log(error));
        },
    }
};
<|endoftext|>


<commit_before>var http = require("http");
var guid = require("guid");
var onecolor = require("onecolor");
var port = 8080;
var log = false;

function createArray(length, valueSelector) {
    var array = [];
    for ( var i = 0; i < length; ++i ) {
        array.push(valueSelector());
    }
    return array;
}

/*
function createPixel(x, y, r, g, b) {
    return [
        x + 1,
        y + 1,
        r * 255,
        g * 255,
        b * 255
    ];
}
*/

function createPixel(x, y, color) {
    return [
        x + 1,
        y + 1,
        color.red() * 255,
        color.green() * 255,
        color.blue() * 255
    ];
}

var Client = function(id, width, height) {
    var depthBuffer = createArray(width, function() {
        return createArray(height, function() {
            return Number.MAX_SAFE_INTEGER;
        });
    });
    var color = new onecolor.HSV(1, 1, 1, 1);
    this.id = id;

    this.request = function(dx, dy, dz) {
        var response = [];
        color = color.hue(0.05, true);
        /*
        response.push(createPixel(0, 0, 1, 0, 0));
        response.push(createPixel(width - 1, 0, 0, 1, 0));
        response.push(createPixel(width - 1, height - 1, 0, 0, 1));
        response.push(createPixel(0, height - 1, 0, 1, 1, 0));
        */
        for ( var x = width / 2 - 10; x < width / 2 + 10; ++x ) {
            for ( var y = height / 2 - 10; y < height / 2 + 10; ++y ) {
                response.push(createPixel(x, y, color));
            }
        }
        return response;
    };
};

var clients = {};

function randomToken() {
    var token = guid.create().toString();
    if ( clients.hasOwnProperty(token) ) {
        return randomToken();
    } else {
        return token;
    }
}

function fullRegex(str, regex) {
    var res = str.match(regex);
    return res != null && res.length == 1 && res[0].length == str.length;
}

function serializeCSV(array) {
    var csv = "";
    for ( var i = 0; i < array.length; ++i ) {
        for ( var j = 0; j < array[i].length; ++j ) {
            if ( j > 0 ) {
                csv += ",";
            }
            csv += array[i][j];
        }
        csv += "\n";
    }
    return csv;
}

function toInt(str) {
    return parseInt(str.replace("\"", ""));
}

function toFloat(str) {
    return parseFloat(str.replace("\"", ""));
}

var server = http.createServer(function(req, res) {
    function send(data) {
        res.end(data);
        if ( log ) {
            console.log("> %s", data);
        }
    }
    if ( log ) {
        console.log("Request to %s", req.url);
    }
    req.on("data", function(chunk) {
        var str = chunk.toString();
        if ( log ) {
            console.log("< %s", str);
        }
        var args = str.split(",");
        if ( req.url == "/login" && args.length == 2 ) {
            var token = randomToken();
            clients[token] = new Client(token, toInt(args[0]), toInt(args[1]));
            send(token);
        } else if ( fullRegex(req.url, /\/frame\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) && args.length == 3 ) {
            var token = req.url.substr(7);
            if ( clients.hasOwnProperty(token) ) {
                send(serializeCSV(clients[token].request(toFloat(args[0]), toFloat(args[1]), toFloat(args[2]))));
            } else {
                send("Invalid token");
            }
        } else {
            send("Invalid protocol");
        }
    });
});

server.listen(port, function() {
    console.log("Server started on http://0.0.0.0:%d/", port);
});
<commit_msg>Added spheres to the javascript server<commit_after>var http = require("http");
var guid = require("guid");
var onecolor = require("onecolor");
var port = 8080;
var log = false;

function createArray(length, valueSelector) {
    var array = [];
    for ( var i = 0; i < length; ++i ) {
        array.push(valueSelector());
    }
    return array;
}

function createPixel(x, y, color) {
    return [
        x + 1,
        y + 1,
        color.red() * 255,
        color.green() * 255,
        color.blue() * 255
    ];
}

var Client = function(id, width, height) {
    var depthBuffer = createArray(width, function() {
        return createArray(height, function() {
            return Number.MIN_SAFE_INTEGER;
        });
    });
    var color = new onecolor.HSV(1, 1, 1, 1);
    this.id = id;

    function drawPixel(pixels, x, y, z, color) {
        if ( x >= 0 && x < width && y >= 0 && y < height && depthBuffer[x][y] <= z ) {
            depthBuffer[x][y] = z;
            pixels.push(createPixel(x, y, color));
        }
    }

    function drawSphere(pixels, x, y, z, r, color) {
        var r2 = r * r;
        var rFactor = r / 0.7;
        for ( var i = -r; i < r; ++i ) {
            var rx = x + i;
            var r2minusi2 = r2 - i * i;
            var limJ = Math.sqrt(r2minusi2);
            for ( var j = -limJ; j < limJ; ++j ) {
                var ry = y + j;
                var limK = Math.sqrt(r2minusi2 - j * j);
                var rz = z + limK;
                var v = limK / rFactor + 0.3;
                drawPixel(pixels, Math.round(rx), Math.round(ry), Math.round(rz), color.value(Number.isNaN(v) ? 0 : v));
            }
        }
    }

    this.request = function(dx, dy, dz) {
        var response = [];
        color = color.hue(0.05, true);
        drawSphere(response, width / 2, height / 2, 0, 20, color);
        return response;
    };
};

var clients = {};

function randomToken() {
    var token = guid.create().toString();
    if ( clients.hasOwnProperty(token) ) {
        return randomToken();
    } else {
        return token;
    }
}

function fullRegex(str, regex) {
    var res = str.match(regex);
    return res != null && res.length == 1 && res[0].length == str.length;
}

function serializeCSV(array) {
    var csv = "";
    for ( var i = 0; i < array.length; ++i ) {
        for ( var j = 0; j < array[i].length; ++j ) {
            if ( j > 0 ) {
                csv += ",";
            }
            csv += array[i][j];
        }
        csv += "\n";
    }
    return csv;
}

function toInt(str) {
    return parseInt(str.replace("\"", ""));
}

function toFloat(str) {
    return parseFloat(str.replace("\"", ""));
}

var server = http.createServer(function(req, res) {
    function send(data) {
        res.end(data);
        if ( log ) {
            console.log("> %s", data);
        }
    }
    if ( log ) {
        console.log("Request to %s", req.url);
    }
    req.on("data", function(chunk) {
        var str = chunk.toString();
        if ( log ) {
            console.log("< %s", str);
        }
        var args = str.split(",");
        if ( req.url == "/login" && args.length == 2 ) {
            var token = randomToken();
            clients[token] = new Client(token, toInt(args[0]), toInt(args[1]));
            send(token);
        } else if ( fullRegex(req.url, /\/frame\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) && args.length == 3 ) {
            var token = req.url.substr(7);
            if ( clients.hasOwnProperty(token) ) {
                send(serializeCSV(clients[token].request(toFloat(args[0]), toFloat(args[1]), toFloat(args[2]))));
            } else {
                send("Invalid token");
            }
        } else {
            send("Invalid protocol");
        }
    });
});

server.listen(port, function() {
    console.log("Server started on http://0.0.0.0:%d/", port);
});
<|endoftext|>


<commit_before>var roomQuestionList = new QuestionList();

/********** MODEL ***************/

//Question object - this mirrors server/database entry

function Question(q, uId, qId) {
	this.details = q;
	this.votes = 0;
	this.answered = false;
	this.paused = false;
	this.userId = uId;
	this.id = qId;
};

//Question object methods

Question.prototype.upVote = function() {
	this.votes = this.votes + 1;
};

Question.prototype.answer = function() {
	this.answered = true;
};

// Question list object - this is an array of Question Objects
function QuestionList() {
	this.questions = [];
};

//Question list methods
QuestionList.prototype.sort = function() {
  this.questions = _.sortBy(this.questions, function(element){return element.votes;});
};

QuestionList.prototype.addQuestion = function( qObj ) {
	this.questions.push( qObj );
	this.sort();
};

//======= end of model =========//

/********** VIEWS ***************/
/* Answer
/* Question
/* Votes
/* Listeners
/********************************/

//if the question is answerable by the user, add this to the div.
function viewRenderAnswerable(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  var answerableDiv = $("
√
");

  $(myDiv.children()[1]).append(answerableDiv);
}

//render a question
function viewRenderQuestion(question){
  var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
  var outerDiv = $('
');

  var innerDiv = $("
")
  innerDiv.text(question.details);
  innerDiv.css("background", _.sample(colors));

  // build the upvote button & attach it to the inner div
  var upButton = $('
⊕
');
  innerDiv.append(upButton);

  //build the votes div
  var votesDiv = $("
0
")
  innerDiv.append(votesDiv);

  //append the div with the new question.
  outerDiv.append(innerDiv);
  $('div.packery').append(outerDiv);
  pckry.appended( outerDiv[0] );
}

//remove a question from the DOM (aka, it was answered)
function viewRemoveQuestion(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  myDiv.remove();
}

//display how many votes the question has
function viewRenderVotes(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  $(myDiv.children()[1]).html(question.votes);
}

//add a listener to the form to allow new questions to be created
function viewFormListener(){
  var form = $('.question-form');
  var session_id = $('#session_id').text();
  form.submit( function( event ) {
    event.preventDefault();

    //get the question
    var question = $('input.question').val();

    //clear input box now that we have input
    $('input.question').val("");

    //create ajax request with the question and the user_id
    $.ajax({
      url: "/json/questions",
      type: "POST",
      data: { question: {details: question, user_id: session_id}},
      success: controllerUpdateNewQuestion
    });
  });
}

//using delegated listeners for all the little actions
function viewAddDelegatedListeners(){
  $('div.packery').on('click', 'div.upButton', controllerUpVote);
  $('div.packery').on('click', 'div.answerable', controllerAnswer);
};

//======= end of views =========//

/********** CONTROLLER **********/

//called to setup everything on a page refresh
function controllerSetup(){
	$.ajax({
		url: "/json/questions",
		type: "GET",
		success: controllerBuildModel
	});
};

//build the model from a list of unanswered questions returned from the server.
//called only once with the page loads.
function controllerBuildModel(serverResponse){
	var numQuestions = serverResponse[0].questions.length;

	for (var i = 0; i < numQuestions; i++){
		var tempQuestion = new Question(serverResponse[0].questions[i].details, serverResponse[0].questions[i].user_id, serverResponse[0].questions[i].id);
		roomQuestionList.addQuestion(tempQuestion);
		viewRenderQuestion(tempQuestion);
	};
	controllerVoteSetup();
  controllerAnswerableSetup();
};

//setup the votes -
//for every question in the roomQuestionList
//    ask the server how many votes the question has!
function controllerVoteSetup(){
	var numQuestions = roomQuestionList.questions.length;
	for (var i = 0; i < numQuestions; i++){

		$.ajax({
		url: "/json/questions/" + roomQuestionList.questions[i].id + "/getvotes",
		type: "GET",
		data: { question: {id: roomQuestionList.questions[i].id}},
    	success: controllerUpdateVotes
    	});
	};
};

//update the votes - the success handler for the vote ajax request.
//when the votes are updated, sort the roomQuestionList, then render votes.
function controllerUpdateVotes(serverResponse){
	var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
	var index = $.inArray(serverResponse[0].question.id, tempArray);

	roomQuestionList.questions[index].votes = serverResponse[1].votes;
  roomQuestionList.sort;
	viewRenderVotes(roomQuestionList.questions[index]);
};

//the hander that accepts the response from sending a new question.
function controllerUpdateNewQuestion(serverResponse){
	tempQuestion = new Question(serverResponse.details, serverResponse.user_id, serverResponse.id);
	roomQuestionList.addQuestion(tempQuestion);
	viewRenderQuestion(tempQuestion);
  viewRenderAnswerable(tempQuestion);
};

//launch an ajax request to the server to upvote a question
function controllerUpVote(){
  var session_id = $('#session_id').text();
  var question_id = $(this.parentElement).data().val;
  var url = "/json/questions/" + question_id + "/vote_up";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateVotes
    });
}

//ajax request for each question - can the user who is logged in answer it?
function controllerAnswerableSetup(){
  var numQuestions = roomQuestionList.questions.length;
  for (var i = 0; i < numQuestions; i++){

    $.ajax({
    url: "/json/questions/" + roomQuestionList.questions[i].id + "/getanswerable",
    type: "GET",
    data: { question: {id: roomQuestionList.questions[i].id}},
      success: controllerUpdateAnswerable
      });
  };
};

//the server has decided i can answer this - so render an answer button.
function controllerUpdateAnswerable(serverResponse){
  //TODO: dry this up into a helper function aka controllerHelperMap(serverResponse)
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);

  viewRenderAnswerable(roomQuestionList.questions[index]);
};

//when the user clicks on answer, send an ajax request to server.
function controllerAnswer(){
  console.log("this question was just answered!");
  // now go tell the server this question was answered!
  // TODO - this is one level higher than vote because of the nesting
  // that is happening - it shouldn't be.
  var question_id = $(this.parentElement.parentElement).data().val;

  var url = "/json/questions/" + question_id + "/answered";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateAnswer
    });
};

//when the server comes back, update the model and display
function controllerUpdateAnswer(serverResponse){
  //remove from the model - find it in the model.  then mark it answered
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);
  roomQuestionList.questions[index].answer();

  //remove from the dom
  viewRemoveQuestion(roomQuestionList.questions[index]);
}

window.onload = function(){

	controllerSetup();

	viewFormListener();
	viewAddDelegatedListeners();

};<commit_msg>refresh list every time a question is voted on<commit_after>var roomQuestionList = new QuestionList();

/********** MODEL ***************/

//Question object - this mirrors server/database entry

function Question(q, uId, qId) {
	this.details = q;
	this.votes = 0;
	this.answered = false;
	this.paused = false;
	this.userId = uId;
	this.id = qId;
};

//Question object methods

Question.prototype.upVote = function() {
	this.votes = this.votes + 1;
};

Question.prototype.answer = function() {
	this.answered = true;
};

// Question list object - this is an array of Question Objects
function QuestionList() {
	this.questions = [];
};

//Question list methods
QuestionList.prototype.sort = function() {
  this.questions = _.sortBy(this.questions, function(element){return element.votes;});
};

QuestionList.prototype.addQuestion = function( qObj ) {
	this.questions.push( qObj );
	this.sort();
};

//======= end of model =========//

/********** VIEWS ***************/
/* Answer
/* Question
/* Votes
/* Listeners
/********************************/

//if the question is answerable by the user, add this to the div.
function viewRenderAnswerable(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  var answerableDiv = $("
√
");

  $(myDiv.children()[1]).append(answerableDiv);
}

//render a question
function viewRenderQuestion(question){
  var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
  var outerDiv = $('
');

  var innerDiv = $("
")
  innerDiv.text(question.details);
  innerDiv.css("background", _.sample(colors));

  // build the upvote button & attach it to the inner div
  var upButton = $('
⊕
');
  innerDiv.append(upButton);

  //build the votes div
  var votesDiv = $("
0
")
  innerDiv.append(votesDiv);

  //append the div with the new question.
  outerDiv.append(innerDiv);
  $('div.packery').append(outerDiv);
  pckry.appended( outerDiv[0] );
}

//remove a question from the DOM (aka, it was answered)
function viewRemoveQuestion(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  myDiv.remove();
}

//display how many votes the question has
function viewRenderVotes(question){
  var myDiv = $('div[data-val=' + question.id + ']');
  $(myDiv.children()[1]).html(question.votes);
}

//add a listener to the form to allow new questions to be created
function viewFormListener(){
  var form = $('.question-form');
  var session_id = $('#session_id').text();
  form.submit( function( event ) {
    event.preventDefault();

    //get the question
    var question = $('input.question').val();

    //clear input box now that we have input
    $('input.question').val("");

    //create ajax request with the question and the user_id
    $.ajax({
      url: "/json/questions",
      type: "POST",
      data: { question: {details: question, user_id: session_id}},
      success: controllerUpdateNewQuestion
    });
  });
}

//using delegated listeners for all the little actions
function viewAddDelegatedListeners(){
  $('div.packery').on('click', 'div.upButton', controllerUpVote);
  $('div.packery').on('click', 'div.answerable', controllerAnswer);
};

//======= end of views =========//

/********** CONTROLLER **********/

//called to setup everything on a page refresh
function controllerSetup(){
	$.ajax({
		url: "/json/questions",
		type: "GET",
		success: controllerBuildModel
	});
};

//build the model from a list of unanswered questions returned from the server.
//called only once with the page loads.
function controllerBuildModel(serverResponse){
	var numQuestions = serverResponse[0].questions.length;

	for (var i = 0; i < numQuestions; i++){
		var tempQuestion = new Question(serverResponse[0].questions[i].details, serverResponse[0].questions[i].user_id, serverResponse[0].questions[i].id);
		roomQuestionList.addQuestion(tempQuestion);
		viewRenderQuestion(tempQuestion);
	};
	controllerVoteSetup();
  controllerAnswerableSetup();
};

//setup the votes -
//for every question in the roomQuestionList
//    ask the server how many votes the question has!
function controllerVoteSetup(){
	var numQuestions = roomQuestionList.questions.length;
	for (var i = 0; i < numQuestions; i++){

		$.ajax({
		url: "/json/questions/" + roomQuestionList.questions[i].id + "/getvotes",
		type: "GET",
		data: { question: {id: roomQuestionList.questions[i].id}},
    	success: controllerUpdateVotes
    	});
	};
};

//update the votes - the success handler for the vote ajax request.
//when the votes are updated, sort the roomQuestionList, then render votes.
function controllerUpdateVotes(serverResponse){
	var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
	var index = $.inArray(serverResponse[0].question.id, tempArray);

	roomQuestionList.questions[index].votes = serverResponse[1].votes;
  roomQuestionList.sort;
	viewRenderVotes(roomQuestionList.questions[index]);
  redisplay();
};

//the hander that accepts the response from sending a new question.
function controllerUpdateNewQuestion(serverResponse){
	tempQuestion = new Question(serverResponse.details, serverResponse.user_id, serverResponse.id);
	roomQuestionList.addQuestion(tempQuestion);
	viewRenderQuestion(tempQuestion);
  viewRenderAnswerable(tempQuestion);
};

//launch an ajax request to the server to upvote a question
function controllerUpVote(){
  var session_id = $('#session_id').text();
  var question_id = $(this.parentElement).data().val;
  var url = "/json/questions/" + question_id + "/vote_up";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateVotes
    });
}

//ajax request for each question - can the user who is logged in answer it?
function controllerAnswerableSetup(){
  var numQuestions = roomQuestionList.questions.length;
  for (var i = 0; i < numQuestions; i++){

    $.ajax({
    url: "/json/questions/" + roomQuestionList.questions[i].id + "/getanswerable",
    type: "GET",
    data: { question: {id: roomQuestionList.questions[i].id}},
      success: controllerUpdateAnswerable
      });
  };
};

//the server has decided i can answer this - so render an answer button.
function controllerUpdateAnswerable(serverResponse){
  console.log("in controllerUpdateAnswerable");
  //TODO: dry this up into a helper function aka controllerHelperMap(serverResponse)
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);
  console.log(roomQuestionList.questions[index]);
  viewRenderAnswerable(roomQuestionList.questions[index]);
};

//when the user clicks on answer, send an ajax request to server.
function controllerAnswer(){
  console.log("this question was just answered!");
  // now go tell the server this question was answered!
  // TODO - this is one level higher than vote because of the nesting
  // that is happening - it shouldn't be.
  var question_id = $(this.parentElement.parentElement).data().val;

  var url = "/json/questions/" + question_id + "/answered";

  $.ajax({
      url: url,
      type: "POST",
      data: { question: {id: question_id}},
      success: controllerUpdateAnswer
    });
};

//when the server comes back, update the model and display
function controllerUpdateAnswer(serverResponse){
  //remove from the model - find it in the model.  then mark it answered
  var tempArray = $.map(roomQuestionList.questions, function(question, i) { return question.id });
  var index = $.inArray(serverResponse[0].question.id, tempArray);
  roomQuestionList.questions[index].answer();

  //remove from the dom
  viewRemoveQuestion(roomQuestionList.questions[index]);
}

//////////////////////////////////////////////////

//////////////////////////////////////////////////

//////////////////////////////////////////////////

function redisplay(){
  //delete this shit.
  elems = pckry.getItemElements();
  for (var i=0; i<elems.length; i++){
    pckry.remove(elems[i]);
  }

  //sort local model
  roomQuestionList.sort();

  //build this shit.
  numberOfQuestions = roomQuestionList.questions.length;
  for(var i=0; i<numberOfQuestions; i++){
    var question = roomQuestionList.questions[i];

    var colors = ["purple", "orange", "red", "blue", "yellow", "green"];
    var outerDiv = $('
');

    var innerDiv = $("
")
    innerDiv.text(question.details);
    innerDiv.css("background", _.sample(colors));

    // build the upvote button & attach it to the inner div
    var upButton = $('
⊕
');
    innerDiv.append(upButton);

    //build the votes div
    var votesDiv = $("
"+question.votes+"
")
    innerDiv.append(votesDiv);

    //append the div with the new question.
    outerDiv.append(innerDiv);

    $('div.packery').append(outerDiv);
    pckry.prepended( outerDiv );
  };

  controllerAnswerableSetup();
};

window.onload = function(){

	controllerSetup();

	viewFormListener();
	viewAddDelegatedListeners();

};<|endoftext|>


<commit_before>// server.js

// set up ======================================================================
var express           = require('express'),
    session           = require('express-session'),
    morgan            = require('morgan'),
    cookieParser      = require('cookie-parser'),
    bodyParser        = require('body-parser'),
    cors              = require('cors');

// initiate server instance
var app = express();

// configuration ===============================================================
var port = process.env.PORT || 8080;

/**
 * General server setup is happening here. We are setting up the middleware
 * that is used for each incoming request.
 */
function setupServer() {

    app.use(morgan('dev')); // log every request to the console
    app.use(bodyParser.urlencoded({ // parse application/x-www-form-urlencoded
      extended: false
    }));
    app.use(bodyParser.json()); // parse application/json
    app.use(cookieParser());
    app.use(session({
      secret: 'errare humanum est',
      cookie: {
        httpOnly: true,
        secure: false, // https required for setting it to true
        maxAge: null // session cookie: is deleted after closing the browser
      },
      resave: false,
      saveUninitialized: false // passport will take care
      /* store: e.g. Redis Store */ // redis store for session data
    }));
    app.use(cors());

    app.set('jwtTokenSecret', 'secretsecret');
}

/**
 * Start Express
 */
function start () {
    setupServer();

	// load routes with fully configured express
    require('./routes/search.js')(app);
    require('./routes/accommodation.js')(app);
    require('./routes/user.js')(app);

    // put this at end of the list. It will deny all requests that are
    // not defined in the previous routes files.
    require('./routes/app.js')(app);

    app.listen(port);
    console.log('\tServer started on port ' + port + '.');
}

// start the server ============================================================
start();

<commit_msg>Hopefully fixing the CORS issue<commit_after>// server.js

// set up ======================================================================
var express           = require('express'),
    session           = require('express-session'),
    morgan            = require('morgan'),
    cookieParser      = require('cookie-parser'),
    bodyParser        = require('body-parser'),
    cors              = require('cors');

// initiate server instance
var app = express();

// configuration ===============================================================
var port = process.env.PORT || 8080;

/**
 * General server setup is happening here. We are setting up the middleware
 * that is used for each incoming request.
 */
function setupServer() {

    app.use(morgan('dev')); // log every request to the console
    app.use(bodyParser.urlencoded({ // parse application/x-www-form-urlencoded
      extended: false
    }));
    app.use(bodyParser.json()); // parse application/json
    app.use(cookieParser());
    app.use(session({
      secret: 'errare humanum est',
      cookie: {
        httpOnly: true,
        secure: false, // https required for setting it to true
        maxAge: null // session cookie: is deleted after closing the browser
      },
      resave: false,
      saveUninitialized: false // passport will take care
      /* store: e.g. Redis Store */ // redis store for session data
    }));
    app.use(cors());

    // handling the CORS pre-flight issue
    app.options('/search', cors()); // enable pre-flight request for search POST request
    app.get('/search/details/:id', cors(), function(req, res, next){
        next();
    });

    app.set('jwtTokenSecret', 'secretsecret');
}

/**
 * Start Express
 */
function start () {
    setupServer();

	// load routes with fully configured express
    require('./routes/search.js')(app);
    require('./routes/accommodation.js')(app);
    require('./routes/user.js')(app);

    // put this at end of the list. It will deny all requests that are
    // not defined in the previous routes files.
    require('./routes/app.js')(app);

    app.listen(port);
    console.log('\tServer started on port ' + port + '.');
}

// start the server ============================================================
start();

<|endoftext|>


<commit_before>var express       = require('express');
var app           = express();
var morgan = require('morgan');
var request = require("request");

app.use(morgan('tiny'));

app.listen(3000, function(){
  console.log('listening on port '+ 3000);
});

app.use(express.static('public'));

app.get('/status',function(req,res){
  console.log(req.body);
  urli='http://drivepal.mybluemix.net';
    request({
        url: urli,
        method: 'GET',
    }, function (error, response, body) {
      console.log(response.statusCode);
        if(error) {console.log(error); res.send(true);}
        else if ( response.statusCode === 200) { res.send(false);} //not down
        else {
          res.send(true);
        }

  });
})
<commit_msg>added timeout so user doesnt wait for the YES :( message<commit_after>var express       = require('express');
var app           = express();
var morgan = require('morgan');
var request = require("request");

app.use(morgan('tiny'));

app.listen(3000, function(){
  console.log('listening on port '+ 3000);
});

app.use(express.static('public'));

app.get('/status',function(req,res){
  console.log(req.body);
  urli='http://drivepal.mybluemix.net';
    request({
        url: urli,
        timeout: 1500,
        method: 'GET'
    }, function (error, response, body) {
      // console.log(response.statusCode);
        if(error) {console.log(error); res.send(true);}
        else if ( response.statusCode === 200) { res.send(false);} //not down
        else {
          res.send(true);
        }

  });
})
<|endoftext|>


<commit_before>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');

var fontDescriptors = {
    Roboto: {
        normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
        bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
        italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
        bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
    }
};

module.exports = {
    generarDirectorio(Scouts) {
        console.log(Scouts);
        var rows = [[
            { text: 'FOTO', style: 'morrarro' },
            { text: 'CUM', style: 'morrarro' },
            { text: 'NOMBRE', style: 'morrarro' },
            { text: 'GÉNERO', style: 'morrarro' },
            { text: 'FECHA DE NACIMIENTO', style: 'morrarro' },
            { text: 'ESCUELA', style: 'morrarro' },
            { text: 'E-MAIL', style: 'morrarro' },
            { text: 'TELÉFONO', style: 'morrarro' },
            { text: 'DOMICILIO', style: 'morrarro' },
        ]];
        for(var i = 0; i < Scouts.length; i++){
            // 'FOTO' 'CUM' 'NOMBRE' 'GÉNERO' 'FECHA DE NACIMIENTO' 'ESCUELA' 'E-MAIL' 'TELÉFONO' 'DOMICILIO'
            rows.push([
                {
                    image: Scouts[i].dataValues.foto,
                    width: 50,
                    height: 50
                },
                { text: Scouts[i].dataValues.cum},
                { text: Scouts[i].dataValues.nombre},
                { text: Scouts[i].dataValues.genero},
                { text: '' + Scouts[i].dataValues.fechanacimiento.getDate() + '/' + (Scouts[i].dataValues.fechanacimiento.getMonth() + 1) + '/' + Scouts[i].dataValues.fechanacimiento.getFullYear() + ''},
                { text: Scouts[i].dataValues.escuela},
                { text: Scouts[i].dataValues.email},
                { text: Scouts[i].dataValues.telefono},
                { text: Scouts[i].dataValues.domicilio},
            ]);
        }
        console.log(rows);
        // PDF Content
        var dd= {
            info: {
                title: 'Directorio',
                author: 'Uhlu',
                subject: 'Directorio',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            pageOrientation: 'landscape',
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 80,height: 80}, { text: 'Directorio', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', '*' ],
                        body: rows
                    },
                    style: 'marginBot'
                },
                { text: 'Directorio elaborado desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ],
                    color: 'purple'
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                morrarro:{
                    color: 'purple'
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        };//end dd

        return new PdfPrinter(fontDescriptors).createPdfKitDocument(dd);
    },
    generarFichaMedica(Scouts) {

    },
    generarCuadroAdelanto(Scouts) {

    }
};
<commit_msg>Update generarReporte.js<commit_after>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');

var fontDescriptors = {
    Roboto: {
        normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
        bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
        italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
        bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
    }
};

module.exports = {
    generarDirectorio(Scouts) {
        console.log(Scouts);
        var rows = [[
            { text: 'FOTO', style: 'morrarro' },
            { text: 'CUM', style: 'morrarro' },
            { text: 'NOMBRE', style: 'morrarro' },
            { text: 'GÉNERO', style: 'morrarro' },
            { text: 'FECHA DE NACIMIENTO', style: 'morrarro' },
            { text: 'ESCUELA', style: 'morrarro' },
            { text: 'E-MAIL', style: 'morrarro' },
            { text: 'TELÉFONO', style: 'morrarro' },
            { text: 'DOMICILIO', style: 'morrarro' },
        ]];
        for(var i = 0; i < Scouts.length; i++){
            // 'FOTO' 'CUM' 'NOMBRE' 'GÉNERO' 'FECHA DE NACIMIENTO' 'ESCUELA' 'E-MAIL' 'TELÉFONO' 'DOMICILIO'
            if(Scouts[i].dataValues.foto == 'img/fpo_avatar.png'){
                Scouts[i].dataValues.foto = '../../public/img/fpo_avatar.png';
            }
            rows.push([
                {
                    image: Scouts[i].dataValues.foto,
                    width: 50,
                    height: 50
                },
                { text: Scouts[i].dataValues.cum},
                { text: Scouts[i].dataValues.nombre},
                { text: Scouts[i].dataValues.genero},
                { text: '' + Scouts[i].dataValues.fechanacimiento.getDate() + '/' + (Scouts[i].dataValues.fechanacimiento.getMonth() + 1) + '/' + Scouts[i].dataValues.fechanacimiento.getFullYear() + ''},
                { text: Scouts[i].dataValues.escuela},
                { text: Scouts[i].dataValues.email},
                { text: Scouts[i].dataValues.telefono},
                { text: Scouts[i].dataValues.domicilio},
            ]);
        }
        console.log(rows);
        // PDF Content
        var dd= {
            info: {
                title: 'Directorio',
                author: 'Uhlu',
                subject: 'Directorio',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            pageOrientation: 'landscape',
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 80,height: 80}, { text: 'Directorio', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', '*' ],
                        body: rows
                    },
                    style: 'marginBot'
                },
                { text: 'Directorio elaborado desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ],
                    color: 'purple'
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                morrarro:{
                    color: 'purple'
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        };//end dd

        return new PdfPrinter(fontDescriptors).createPdfKitDocument(dd);
    },
    generarFichaMedica(Scouts) {

    },
    generarCuadroAdelanto(Scouts) {

    }
};
<|endoftext|>


<commit_before>var ws = require("nodejs-websocket");

var server = null;
var settings = {
        pingInterval: 30*1000, // ms
        sessionTimeout: 2*60*1000 // ms
};
var errors = {
    msgFailed: "Message construction failed.",
    sendFailed: "Message sending failed.",
    parseFailed: "Message parse failed.",
    malformed: "Message malformed.",
    unknownHeader: "Unknown header."
};

// id: {connections: [], timeout: f, pinger: f}
var sessions = {};

// sessionId: {contact: "", tier: "", region: ""}
var scrims = {};
var tiers = ["Low", "Mid", "High", "High+", "High++"];
var regions = ["SEA", "NA", "EU"];

function message(header, body) {
    var m = {header: header.toUpperCase(), body: body, timestamp: +new Date()};
    try {
        m = JSON.stringify(m);
    } catch (e) {
        return {message: null, error: e};
    } finally {
        return {message: m, error: null};
    }
}

function send(sid, header, body) {
    var m = message(header, body);
    if (m.error) {
        console.log("Error:", errors.msgFailed, m.error);
    }
    if (!(sid in sessions)) return;
    sessions[sid].connections.forEach(function(c) {
        if (c.readyState != c.OPEN) return;
        try {
            c.send(m.message);
        } catch(err) {
            console.log("Error:", errors.sendFailed, err);
        }
    });
}

function broadcast(header, body) {
    for (var sid = 0; sid < sessions.length; sid++) {
        send(sid, header, body);
    }
}

function pinger(id) {
    return setInterval(function () {
        send(id, "PING", null);
    }, settings.pingInterval);
}

function merge(conn, sid) {
    clearTimeout(sessions[sid].timeout);
    clearInterval(sessions[conn.sessionId].pinger);
    delete sessions[conn.sessionId];
    sessions[sid].connections.push(conn);

    if (conn.sessionId in scrims) {
        scrims[sid] = scrims[conn.sessionId];
        delete scrims[conn.sessionId];
        update();
    }
    conn.sessionId = sid;
}

function update() {
    broadcast("UPDATE", scrims);
    console.log("Scrims:", scrims);
}

function handle(conn, data) {
    if (!("header" in data) || !("body" in data)) {
        send(conn.sessionId, "ERROR", errors.malformed);
        return;
    }
    data.header = data.header || "";
    data.body = data.body || "";

    switch (data.header.toUpperCase()) {
        case "IDENT":
            var oldSid = parseInt(data.body);
            if (isFinite(oldSid)) {
                console.log("Switch", conn.sessionId, "to", oldSid);
                merge(conn, oldSid);
            }
            break;
        case "SET":
            if (typeof data.body !== "object") {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (!("tier" in data.body) || !("region" in data.body) || !("contact" in data.body)) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (tiers.indexOf(data.body.tier) < 0 || regions.indexOf(data.body.region) < 0 || data.body.contact.length > 20) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            scrims[conn.sessionId] = {contact: data.body.contact, region: data.body.region, tier: data.body.tier};
            update();
            break;
        case "CLEAR":
            delete scrims[conn.sessionId];
            update();
            break;
        case "PONG":
            break;
        default:
            send(conns[conn.sessionId], "ERROR", errors.unknownHeader);
    }
}

server = ws.createServer(function(conn) {
    conn.id = +new Date();
    conn.sessionId = +new Date();
    while (conn.readyState == conn.CONNECTING) {}
    sessions[conn.sessionId] = {connections: [conn], pinger: pinger(conn.sessionId), timeout: function() {}};
    update();

    conn.on("text", function(str) {
        var data;
        try {
            data = JSON.parse(str);
        } catch(err) {
            console.log("Error:", errors.parseFailed, err);
            return;
        }
        if (!data) return;
        console.log("Received:", data);
        handle(conn, data);
    });

    conn.on("close", function(code, reason) {
        if (conn.sessionId in sessions) {
            for (var i = 0; i < sessions[conn.sessionId].connections.length; i++) {
                var c = sessions[conn.sessionId].connections[i];
                if (c.id === conn.id) {
                    sessions[conn.sessionId].connections.splice(i, 1);
                    break;
                }
            }
            if (sessions[conn.sessionId].connections.length < 1) {
                sessions[conn.sessionId].timeout = setTimeout(function() {
                    delete scrims[conn.sessionId];
                    clearInterval(sessions[conn.sessionId].pinger);
                    delete sessions[conn.sessionId];
                    update();
                }, settings.sessionTimeout);
            }
        }
    });
}).listen(process.env.PORT || 8000);
<commit_msg>Fix merging<commit_after>var ws = require("nodejs-websocket");

var server = null;
var settings = {
        pingInterval: 30*1000, // ms
        sessionTimeout: 2*60*1000 // ms
};
var errors = {
    msgFailed: "Message construction failed.",
    sendFailed: "Message sending failed.",
    parseFailed: "Message parse failed.",
    malformed: "Message malformed.",
    unknownHeader: "Unknown header."
};

// id: {connections: [], timeout: f, pinger: f}
var sessions = {};

// sessionId: {contact: "", tier: "", region: ""}
var scrims = {};
var tiers = ["Low", "Mid", "High", "High+", "High++"];
var regions = ["SEA", "NA", "EU"];

function message(header, body) {
    var m = {header: header.toUpperCase(), body: body, timestamp: +new Date()};
    try {
        m = JSON.stringify(m);
    } catch (e) {
        return {message: null, error: e};
    } finally {
        return {message: m, error: null};
    }
}

function send(sid, header, body) {
    var m = message(header, body);
    if (m.error) {
        console.log("Error:", errors.msgFailed, m.error);
    }
    if (!(sid in sessions)) return;
    sessions[sid].connections.forEach(function(c) {
        if (c.readyState != c.OPEN) return;
        try {
            c.send(m.message);
        } catch(err) {
            console.log("Error:", errors.sendFailed, err);
        }
    });
}

function broadcast(header, body) {
    for (var sid = 0; sid < sessions.length; sid++) {
        send(sid, header, body);
    }
}

function pinger(id) {
    return setInterval(function () {
        send(id, "PING", null);
    }, settings.pingInterval);
}

function merge(conn, sid) {
    clearTimeout(sessions[sid].timeout);
    clearInterval(sessions[conn.sessionId].pinger);
    delete sessions[conn.sessionId];
    sessions[sid].connections.push(conn);

    if (conn.sessionId in scrims) {
        scrims[sid] = scrims[conn.sessionId];
        delete scrims[conn.sessionId];
        update();
    }
    conn.sessionId = sid;
}

function update() {
    broadcast("UPDATE", scrims);
    console.log("Scrims:", scrims);
}

function handle(conn, data) {
    if (!("header" in data) || !("body" in data)) {
        send(conn.sessionId, "ERROR", errors.malformed);
        return;
    }
    data.header = data.header || "";
    data.body = data.body || "";

    switch (data.header.toUpperCase()) {
        case "IDENT":
            var oldSid = parseInt(data.body);
            if (isFinite(oldSid) && oldSid in sessions) {
                console.log("Switch", conn.sessionId, "to", oldSid);
                merge(conn, oldSid);
            }
            break;
        case "SET":
            if (typeof data.body !== "object") {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (!("tier" in data.body) || !("region" in data.body) || !("contact" in data.body)) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            if (tiers.indexOf(data.body.tier) < 0 || regions.indexOf(data.body.region) < 0 || data.body.contact.length > 20) {
                send(conn.sessionId, "ERROR", errors.malformed);
                break;
            }
            scrims[conn.sessionId] = {contact: data.body.contact, region: data.body.region, tier: data.body.tier};
            update();
            break;
        case "CLEAR":
            delete scrims[conn.sessionId];
            update();
            break;
        case "PONG":
            break;
        default:
            send(conns[conn.sessionId], "ERROR", errors.unknownHeader);
    }
}

server = ws.createServer(function(conn) {
    conn.id = +new Date();
    conn.sessionId = +new Date();
    while (conn.readyState == conn.CONNECTING) {}
    sessions[conn.sessionId] = {connections: [conn], pinger: pinger(conn.sessionId), timeout: function() {}};
    update();

    conn.on("text", function(str) {
        var data;
        try {
            data = JSON.parse(str);
        } catch(err) {
            console.log("Error:", errors.parseFailed, err);
            return;
        }
        if (!data) return;
        console.log("Received:", data);
        handle(conn, data);
    });

    conn.on("close", function(code, reason) {
        if (conn.sessionId in sessions) {
            for (var i = 0; i < sessions[conn.sessionId].connections.length; i++) {
                var c = sessions[conn.sessionId].connections[i];
                if (c.id === conn.id) {
                    sessions[conn.sessionId].connections.splice(i, 1);
                    break;
                }
            }
            if (sessions[conn.sessionId].connections.length < 1) {
                sessions[conn.sessionId].timeout = setTimeout(function() {
                    delete scrims[conn.sessionId];
                    clearInterval(sessions[conn.sessionId].pinger);
                    delete sessions[conn.sessionId];
                    update();
                }, settings.sessionTimeout);
            }
        }
    });
}).listen(process.env.PORT || 8000);
<|endoftext|>


<commit_before>var Statique = require("statique")
  , Start = require("./start")
  , Http = require("http")
  , Url = require("url")
  , Lien = require("lien")
  , Config = Bloggify.getConfig()
  , Theme = require("./theme")
  ;

var server = new Lien({
    host: Config.host
  , port: Config.port
  , root: Config.content
  , cache: Config.fileCache
});

Bloggify.initPlugins(function () {
    Theme(Config.content + Config.theme, function (err, themeObj) {
        if (err) { throw err; }

        // Error pages
        server.page.add(/\/[4-9][0-9][0-9]\/?/, function (lien) {
            var m = lien.pathName.match(/\/(.*)\/?/) || []
              , code = parseInt(m[1])
              ;

            if (isNaN(code) || !themeObj.errors[code]) {
                return lien.end(404);
            }
            lien.file(themeObj.errors[code]);
        });

        // Blog posts
        server.page.add(new RegExp(Config.blog.path + "\/[0-9]+.*"), function (lien) {
            debugger;
            lien.end();
        });

        // Blog pages
        server.page.add(new RegExp(Config.blog.path + "(\/page\/[1-9]([0-9]*))?\/$"), function (lien) {
            debugger;
            lien.end();
        });

        server.on("request", function (lien) {
            lien.end();
        });
    });

   //     if (
   //         (route && route.url && typeof route.url !== "object"
   //         || isBlogPost || isBlogPage)
   //         && typeof Bloggify.apis["handlePage:" + req.method] === "function"
   //     ) {
   //         Bloggify.session.isLoggedIn(req, function (err, sessionData) {
   //             if (err) {
   //                 Debug.log(err, "error");
   //                 return Statique.error(req, res, 500);
   //             }
   //             Bloggify.apis["handlePage:" + req.method](
   //                 req, res, pathName, route, null, isBlogPost, isBlogPage, sessionData
   //             );
   //         });
   //         return;
   //     }
});
<commit_msg>Set errors<commit_after>var Statique = require("statique")
  , Start = require("./start")
  , Http = require("http")
  , Url = require("url")
  , Lien = require("lien")
  , Config = Bloggify.getConfig()
  , Theme = require("./theme")
  ;

var server = new Lien({
    host: Config.host
  , port: Config.port
  , root: Config.content
  , cache: Config.fileCache
});

Bloggify.initPlugins(function () {
    Theme(Config.content + Config.theme, function (err, themeObj) {
        if (err) { throw err; }

        server._sServer.setErrors(themeObj.errors);

        // Error pages
        server.page.add(/\/[4-9][0-9][0-9]\/?/, function (lien) {
            var m = lien.pathName.match(/\/(.*)\/?/) || []
              , code = parseInt(m[1])
              ;

            if (isNaN(code) || !themeObj.errors[code]) {
                return lien.end(404);
            }
            lien.file(themeObj.errors[code]);
        });

        // Blog posts
        server.page.add(new RegExp(Config.blog.path + "\/[0-9]+.*"), function (lien) {
            debugger;
            lien.end();
        });

        // Blog pages
        server.page.add(new RegExp(Config.blog.path + "(\/page\/[1-9]([0-9]*))?\/$"), function (lien) {
            debugger;
            lien.end();
        });

        server.on("request", function (lien) {
            lien.end();
        });
    });

   //     if (
   //         (route && route.url && typeof route.url !== "object"
   //         || isBlogPost || isBlogPage)
   //         && typeof Bloggify.apis["handlePage:" + req.method] === "function"
   //     ) {
   //         Bloggify.session.isLoggedIn(req, function (err, sessionData) {
   //             if (err) {
   //                 Debug.log(err, "error");
   //                 return Statique.error(req, res, 500);
   //             }
   //             Bloggify.apis["handlePage:" + req.method](
   //                 req, res, pathName, route, null, isBlogPost, isBlogPage, sessionData
   //             );
   //         });
   //         return;
   //     }
});
<|endoftext|>


<commit_before>const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { initCommuneFields, initCommuneFormat } = require('./lib/communeHelpers');
const { initDepartementFields } = require('./lib/departementHelpers');
const { initRegionFields } = require('./lib/regionHelpers');
const { formatOne } = require('./lib/helpers');
const dbCommunes = require('./lib/communes').getIndexedDb();
const dbDepartements = require('./lib/departements').getIndexedDb();
const dbRegions = require('./lib/regions').getIndexedDb();
const { pick } = require('lodash');

const app = express();
app.use(cors());
app.use(morgan('dev'));

/* Communes */
app.get('/communes', initCommuneFields, initCommuneFormat, function (req, res) {
  let result;

  const query = pick(req.query, 'code', 'codePostal', 'nom', 'codeDepartement', 'boost');
  if (req.query.lat && req.query.lon) {
    const lat = parseFloat(req.query.lat);
    const lon = parseFloat(req.query.lon);
    if (Number.isFinite(lat)
      && lat >= -90
      && lat <= 90
      && Number.isFinite(lon)
      && lon >= -180
      && lon <= 180
    ) {
      query.lat = lat;
      query.lon = lon;
    }
  }
  if (query.nom) req.fields.add('_score');

  if (Object.keys(query).length === 0) {
    return res.sendStatus(400);
  }

  result = dbCommunes.search(query);

  if (req.outputFormat === 'geojson') {
    res.send({
      type: 'FeatureCollection',
      features: result.map(commune => formatOne(req, commune)),
    });
  } else {
    res.send(result.map(commune => formatOne(req, commune)));
  }
});

app.get('/communes/:code', initCommuneFields, initCommuneFormat, function (req, res) {
  const communes = dbCommunes.queryByCode(req.params.code);
  if (communes.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, communes[0]));
  }
});

/* Départements */
app.get('/departements', initDepartementFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbDepartements
      .search(query)
      .map(departement => formatOne(req, departement))
  );
});

app.get('/departements/:code', initDepartementFields, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, departements[0]));
  }
});

app.get('/departements/:code/communes',  initCommuneFields, initCommuneFormat, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    const communes = dbCommunes.queryByDep(req.params.code);
    if (req.outputFormat === 'geojson') {
      res.send({
        type: 'FeatureCollection',
        features: communes.map(commune => formatOne(req, commune)),
      });
    } else {
      res.send(communes.map(commune => formatOne(req, commune)));
    }
  }
});

/* Régions */
app.get('/regions', initRegionFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbRegions
      .search(query)
      .map(region => formatOne(req, region))
  );
});

app.get('/regions/:code', initRegionFields, function (req, res) {
  const regions = dbRegions.queryByCode(req.params.code);
  if (regions.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, regions[0]));
  }
});

/* Definition */
app.get('/definition.yml', function (req, res) {
  res.sendFile(__dirname + '/definition.yml');
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  /* eslint no-console: 0 */
  console.log('Start listening on port %d', port);
});

module.exports = app;
<commit_msg>Add regions/{code}/departements route<commit_after>const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { initCommuneFields, initCommuneFormat } = require('./lib/communeHelpers');
const { initDepartementFields } = require('./lib/departementHelpers');
const { initRegionFields } = require('./lib/regionHelpers');
const { formatOne } = require('./lib/helpers');
const dbCommunes = require('./lib/communes').getIndexedDb();
const dbDepartements = require('./lib/departements').getIndexedDb();
const dbRegions = require('./lib/regions').getIndexedDb();
const { pick } = require('lodash');

const app = express();
app.use(cors());
app.use(morgan('dev'));

/* Communes */
app.get('/communes', initCommuneFields, initCommuneFormat, function (req, res) {
  let result;

  const query = pick(req.query, 'code', 'codePostal', 'nom', 'codeDepartement', 'boost');
  if (req.query.lat && req.query.lon) {
    const lat = parseFloat(req.query.lat);
    const lon = parseFloat(req.query.lon);
    if (Number.isFinite(lat)
      && lat >= -90
      && lat <= 90
      && Number.isFinite(lon)
      && lon >= -180
      && lon <= 180
    ) {
      query.lat = lat;
      query.lon = lon;
    }
  }
  if (query.nom) req.fields.add('_score');

  if (Object.keys(query).length === 0) {
    return res.sendStatus(400);
  }

  result = dbCommunes.search(query);

  if (req.outputFormat === 'geojson') {
    res.send({
      type: 'FeatureCollection',
      features: result.map(commune => formatOne(req, commune)),
    });
  } else {
    res.send(result.map(commune => formatOne(req, commune)));
  }
});

app.get('/communes/:code', initCommuneFields, initCommuneFormat, function (req, res) {
  const communes = dbCommunes.queryByCode(req.params.code);
  if (communes.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, communes[0]));
  }
});

/* Départements */
app.get('/departements', initDepartementFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbDepartements
      .search(query)
      .map(departement => formatOne(req, departement))
  );
});

app.get('/departements/:code', initDepartementFields, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, departements[0]));
  }
});

app.get('/departements/:code/communes',  initCommuneFields, initCommuneFormat, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    const communes = dbCommunes.queryByDep(req.params.code);
    if (req.outputFormat === 'geojson') {
      res.send({
        type: 'FeatureCollection',
        features: communes.map(commune => formatOne(req, commune)),
      });
    } else {
      res.send(communes.map(commune => formatOne(req, commune)));
    }
  }
});

/* Régions */
app.get('/regions', initRegionFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbRegions
      .search(query)
      .map(region => formatOne(req, region))
  );
});

app.get('/regions/:code', initRegionFields, function (req, res) {
  const regions = dbRegions.queryByCode(req.params.code);
  if (regions.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, regions[0]));
  }
});

app.get('/regions/:code/departements',  initDepartementFields, function (req, res) {
  const regions = dbRegions.queryByCode(req.params.code);
  if (regions.length === 0) {
    res.sendStatus(404);
  } else {
    const departements = dbDepartements.queryByCodeRegion(req.params.code);
    if (req.outputFormat === 'geojson') {
      res.send({
        type: 'FeatureCollection',
        features: departements.map(commune => formatOne(req, commune)),
      });
    } else {
      res.send(departements.map(commune => formatOne(req, commune)));
    }
  }
});

/* Definition */
app.get('/definition.yml', function (req, res) {
  res.sendFile(__dirname + '/definition.yml');
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  /* eslint no-console: 0 */
  console.log('Start listening on port %d', port);
});

module.exports = app;
<|endoftext|>