<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }
                if(remove == 0){
                    for(var j = 0; j< tempWidth; j++){
                        for(var k = 0; k< tempHeight; k++){
                            nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited = 1;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            randw = randw - Math.floor(pw/4);
            randh = randh - Math.floor(ph/4);

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/4) * (pathHeight/4));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 5));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

            //create a branch point
            var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0 && nodemap[i][j].isVisited == 1){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].isRoom == 1){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30, 30, 30);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           /*for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }*/

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }
                if(remove == 0){
                    for(var j = 0; j< tempWidth; j++){
                        for(var k = 0; k< tempHeight; k++){
                            nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited = 1;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            randw = randw - Math.floor(pw/4);
            randh = randh - Math.floor(ph/4);

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/4) * (pathHeight/4));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 3));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

            //create a branch point
            var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0 && nodemap[i][j].isVisited == 1){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].isRoom == 1){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30, 30, 30);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           /*for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }*/

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>//==============================================================
// mixin_interface_api.js
// Purpose:  implementation of interface classes in es6
//           https://www.npmjs.com/package/mixin-interface-api
// Project: 'mixin-interface-api' npm package
//==============================================================
//'use strict';
/*jshint node: true*/
/*jshint esversion: 6*/
const mixin       = require('mixin');
const caller_id   = require('caller-id');

const SERVICE_NOT_IMPLEMENTED_ERROR_ID     = 100;
const SUPER_INTERFACE_NOT_DEFINED_ERROR_ID = 101;

//------------------- $raiseNotImplementedError() -------------------
const $raiseNotImplementedError = function(arg_interface, instance) {
        if (arg_interface === undefined ||  instance === undefined) {
              return;
        }

        var caller_data = caller_id.getData();
        var error_msg   = "** mixin-interface Error " + SERVICE_NOT_IMPLEMENTED_ERROR_ID + " ** " +
                          arg_interface.name + "." + caller_data.functionName +
                          " not found on " + instance.name + "\n";

        throw new Error(error_msg);
} // $raiseNotImplementedError()

//=================================================================
//==================== '$MixinInterface' class ====================
//=================================================================
class $MixinInterface {
  constructor(arg_type) {
      this._$super_implementation = arg_type;
  } // '$MixinInterface' constructor

  $with(...arg_interfaces) {
      var implemented_interfaces = Array.from(arg_interfaces);
      if (implemented_interfaces.length === 0)
        return this._$super_implementation;

      var mixed = this._$super_implementation;

      if (this._$super_implementation._$implemented_interfaces === undefined)
          this._$super_implementation._$implemented_interfaces = {};

      for (var i=0; i<implemented_interfaces.length; i++) {
         var implemented_interface = implemented_interfaces[i];
         //console.log("-- " + itf.name + " implemented on " + super_type.name);
        mixed = mixin(mixed, implemented_interface);
        this._$super_implementation._$implemented_interfaces[implemented_interface] = true;
      } // for (var i=0; i<implemented_interfaces.length; i++)

      return mixed;
  } // $with()
} // '$MixinInterface' class

//====================================================================
//==================== '$MixinSetInterface' class ====================
//====================================================================
class $MixinSetInterface {
  constructor(arg_type) {
      this._$arg_type = arg_type;
    } // '$MixinSetInterface' constructor

  $asChildOf(arg_super_type) {
      var arg_type = this._$arg_type;
      if (arg_type === undefined || arg_super_type === undefined) {
          return;
      }
      arg_type._$is_interface    = true;
      arg_type._$super_interface = arg_super_type;
  } // $asChildOf
} // '$MixinSetInterface' class

//======================================================================
//==================== '$MixinImplementation' class ====================
//======================================================================
class $MixinImplementation {
  constructor(arg_type) {
      this._$arg_type = arg_type;
  } // '$MixinImplementation' constructor

  $asImplementationOf(...arg_interfaces) {
      var arg_type = this._$arg_type;
      if (arg_type === undefined)
          return;

      var interfaces                    = Array.from(arg_interfaces);
      arg_type._$implemented_interfaces = interfaces;
      arg_type._$is_interface           = false;
  } // $asImplementationOf
} // '$MixinImplementation' class

//===========================================================================
//==================== '$IBaseInterface' interface class ====================
//===========================================================================
class $IBaseInterface {
} // '$IBaseInterface' interface class
$IBaseInterface._$is_interface = true;
exports.$IBaseInterface = $IBaseInterface;

//=====================================================================
//================ '$Object' Base Implementation class ================
//=====================================================================
class $Object {
  constructor(...args) {
      this._$name        = this.generateInstanceName();
      this._$args        = args;
	  this._$initialized = false;
	  this._$args_init   = [];
  } // '$Object' constructor

  init(...args_init) {
	  if (this._$initialized===true)
		return;

	  this._$initialized = true;
      if (args_init !== undefined && args_init !== null)
		  this._$args_init = Array.from(args_init);
  } // init()

  isInitialized() {
	  return this._$initialized;
  } // isInitialized()

  generateInstanceName() {
    var class_name = this.constructor.name;
    //console.log("class_name: " + class_name);
    var count = 0;

    if ($Object._InstanceCount === undefined)
      $Object._InstanceCount = {};

    if ($Object._InstanceCount[class_name] === undefined)
      $Object._InstanceCount[class_name] = 0;
    else
      count = $Object._InstanceCount[class_name];

    $Object._InstanceCount[class_name] = count;

    var preformatted_class_name = class_name.replace('.', '_').replace('$', 'mxi');
	var snake_case_class_name   = preformatted_class_name.replace
	                              (/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
    var name = snake_case_class_name + '_' + count;

    $Object._InstanceCount[class_name]++;
    return name;
  } // generateInstanceName()

  get name() {
    if (this._$name === undefined)
      this._$name = this.generateInstanceName();
    return this._$name;
  } // get name()
} // '$Object' class
$Object._$is_interface = false;
exports.$Object = $Object;
//================ '$Object' Base Implementation class

//------------------- $Interface() -------------------
const $Interface = function(arg_super_type) {
       return mixin($Object, arg_super_type);
} // $Interface()

//------------------- $setAsInterface() -------------------
const $setAsInterface = function(arg_type) {
      if (arg_type === undefined)
          return;
      arg_type._$is_interface    = true;
      arg_type._$super_interface = $IBaseInterface;
      return new $MixinSetInterface(arg_type);
} // $setAsInterface()

//------------------- $Implementation() -------------------
const $Implementation = function(arg_super_implementation) {
       return new $MixinInterface(arg_super_implementation);
} // $Implementation()

//------------------- $setClass() -------------------
const $setClass = function(arg_type) {
        if (arg_type === undefined)
              return;
        return new $MixinImplementation(arg_type);
} // $setClass()

//------------------- getClass() -------------------
const getClass = function (instance) {
    if (instance === null || instance === undefined)
      return undefined;

    var type = Object.getPrototypeOf(instance);
    return type.constructor;
} // getClass()

//---------- $isInterface ----------
const $isInterface = function(arg_type) {
        if ( arg_type                === undefined ||
             arg_type._$is_interface === undefined) {
           return false;
        }

        if (arg_type._$is_interface === true)
            return true;

        return false;
} // $isInterface

 //------------------- $isInstanceOf() -------------------
 const $isInstanceOf = function(type, instance) {
      //console.log("---- isInstanceOf " + type.name + " ? instance: " + instance);
      var instance_type = getClass(instance);

      if ( instance instanceof type)
          // Check if instance 'isinstanceof' an implementation class
          return true;
      else {
          // Check if instance 'isinstanceof' an interface class
          var implemented_interface;
          if (instance_type._$implemented_interfaces !== undefined) {
              // Check if interface class is in _$implemented_interfaces
              for (var i=0; i<instance_type._$implemented_interfaces.length; i++) {
                  implemented_interface = instance_type._$implemented_interfaces[i];
                  if (implemented_interface === type)
                      return true;
                  else {
                      var parent_interface = implemented_interface._$super_interface;
                      while (parent_interface !== undefined) {
                          if (parent_interface === type)
                              return true;
                          parent_interface = parent_interface._$super_interface;
                          //console.log(">> parent_interface  " + parent_interface.name);
                      } // while (parent_interface != undefined)
                  } // if (implemented_interface === type)
              } // for (var i=0; i<instance_type._$implemented_interfaces.length; i++)
          } // if (instance_type._$implemented_interfaces !== undefined)
      } // if (instance instanceof type)

      return false;
} // $isInstanceOf()

//=================================================================================
//================================ 'MxI' Namespace ================================
//=================================================================================
const MxI = {
    '$Object':                   $Object,
    '$IBaseInterface':           $IBaseInterface,
	'$Interface':                $Interface,
	'$setAsInterface':           $setAsInterface,
    '$Implementation':           $Implementation,
    '$setClass':                 $setClass,
	'$isInstanceOf':             $isInstanceOf,
    '$isInterface':              $isInterface,
	'$raiseNotImplementedError': $raiseNotImplementedError,
}; // MxI namespace
exports.MxI = MxI;
<commit_msg>0.0.8<commit_after>//==============================================================
// mixin_interface_api.js
// Purpose:  implementation of interface classes in es6
//           https://www.npmjs.com/package/mixin-interface-api
// Project: 'mixin-interface-api' npm package
//==============================================================
//'use strict';
/*jshint node: true*/
/*jshint esversion: 6*/
const mixin       = require('mixin');
const caller_id   = require('caller-id');

const SERVICE_NOT_IMPLEMENTED_ERROR_ID          = 100;
const SUPER_INTERFACE_NOT_DEFINED_ERROR_ID      = 101;
const SUPER_IMPLEMENTATION_NOT_DEFINED_ERROR_ID = 102;

//------------------- $raiseNotImplementedError() -------------------
const $raiseNotImplementedError = function(arg_interface, instance) {
        if (arg_interface === undefined ||  instance === undefined) {
              return;
        }

        var caller_data = caller_id.getData();
        var error_msg   = "** mixin-interface-api Error " + SERVICE_NOT_IMPLEMENTED_ERROR_ID + " ** " +
                          arg_interface.name + "." + caller_data.functionName +
                          " not found on " + instance.name + "\n";

        throw new Error(error_msg);
} // $raiseNotImplementedError()

//=================================================================
//==================== '$MixinInterface' class ====================
//=================================================================
class $MixinInterface {
  constructor(arg_type) {
	  if (arg_type === undefined) {
		var error_msg   = "** mixin-interface-api Error " + SUPER_IMPLEMENTATION_NOT_DEFINED_ERROR_ID + " ** " +
                          "Parent Implementation class is '" + arg_type + "'\n";

        throw new Error(error_msg);
	  }

      this._$super_implementation = arg_type;
  } // '$MixinInterface' constructor

  $with(...arg_interfaces) {
      var implemented_interfaces = Array.from(arg_interfaces);
      if (implemented_interfaces.length === 0)
        return this._$super_implementation;

      var mixed = this._$super_implementation;

      if (this._$super_implementation._$implemented_interfaces === undefined)
          this._$super_implementation._$implemented_interfaces = {};

      for (var i=0; i<implemented_interfaces.length; i++) {
         var implemented_interface = implemented_interfaces[i];
         //console.log("-- " + itf.name + " implemented on " + super_type.name);
        mixed = mixin(mixed, implemented_interface);
        this._$super_implementation._$implemented_interfaces[implemented_interface] = true;
      } // for (var i=0; i<implemented_interfaces.length; i++)

      return mixed;
  } // $with()
} // '$MixinInterface' class

//====================================================================
//==================== '$MixinSetInterface' class ====================
//====================================================================
class $MixinSetInterface {
  constructor(arg_type) {
      this._$arg_type = arg_type;
    } // '$MixinSetInterface' constructor

  $asChildOf(arg_super_type) {
      var arg_type = this._$arg_type;
      if (arg_type === undefined || arg_super_type === undefined) {
          return;
      }
      arg_type._$is_interface    = true;
      arg_type._$super_interface = arg_super_type;
  } // $asChildOf
} // '$MixinSetInterface' class

//======================================================================
//==================== '$MixinImplementation' class ====================
//======================================================================
class $MixinImplementation {
  constructor(arg_type) {
      this._$arg_type = arg_type;
  } // '$MixinImplementation' constructor

  $asImplementationOf(...arg_interfaces) {
      var arg_type = this._$arg_type;
      if (arg_type === undefined)
          return;

      var interfaces                    = Array.from(arg_interfaces);
      arg_type._$implemented_interfaces = interfaces;
      arg_type._$is_interface           = false;
  } // $asImplementationOf
} // '$MixinImplementation' class

//===========================================================================
//==================== '$IBaseInterface' interface class ====================
//===========================================================================
class $IBaseInterface {
} // '$IBaseInterface' interface class
$IBaseInterface._$is_interface = true;
exports.$IBaseInterface = $IBaseInterface;

//=====================================================================
//================ '$Object' Base Implementation class ================
//=====================================================================
class $Object {
  constructor(...args) {
      this._$name        = this.generateInstanceName();
      this._$args        = args;
	  this._$initialized = false;
	  this._$args_init   = [];
  } // '$Object' constructor

  init(...args_init) {
	  if (this._$initialized===true)
		return;

	  this._$initialized = true;
      if (args_init !== undefined && args_init !== null)
		  this._$args_init = Array.from(args_init);
  } // init()

  isInitialized() {
	  return this._$initialized;
  } // isInitialized()

  generateInstanceName() {
    var class_name = this.constructor.name;
    //console.log("class_name: " + class_name);
    var count = 0;

    if ($Object._InstanceCount === undefined)
      $Object._InstanceCount = {};

    if ($Object._InstanceCount[class_name] === undefined)
      $Object._InstanceCount[class_name] = 0;
    else
      count = $Object._InstanceCount[class_name];

    $Object._InstanceCount[class_name] = count;

    var preformatted_class_name = class_name.replace('.', '_').replace('$', 'mxi');
	var snake_case_class_name   = preformatted_class_name.replace
	                              (/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
    var name = snake_case_class_name + '_' + count;

    $Object._InstanceCount[class_name]++;
    return name;
  } // generateInstanceName()

  get name() {
    if (this._$name === undefined)
      this._$name = this.generateInstanceName();
    return this._$name;
  } // get name()
} // '$Object' class
$Object._$is_interface = false;
exports.$Object = $Object;
//================ '$Object' Base Implementation class

//------------------- $Interface() -------------------
const $Interface = function(arg_super_type) {
       return mixin($Object, arg_super_type);
} // $Interface()

//------------------- $setAsInterface() -------------------
const $setAsInterface = function(arg_type) {
      if (arg_type === undefined)
          return;
      arg_type._$is_interface    = true;
      arg_type._$super_interface = $IBaseInterface;
      return new $MixinSetInterface(arg_type);
} // $setAsInterface()

//------------------- $Implementation() -------------------
const $Implementation = function(arg_super_implementation) {
       return new $MixinInterface(arg_super_implementation);
} // $Implementation()

//------------------- $setClass() -------------------
const $setClass = function(arg_type) {
        if (arg_type === undefined)
              return;
        return new $MixinImplementation(arg_type);
} // $setClass()

//------------------- getClass() -------------------
const getClass = function (instance) {
    if (instance === null || instance === undefined)
      return undefined;

    var type = Object.getPrototypeOf(instance);
    return type.constructor;
} // getClass()

//---------- $isInterface ----------
const $isInterface = function(arg_type) {
        if ( arg_type                === undefined ||
             arg_type._$is_interface === undefined) {
           return false;
        }

        if (arg_type._$is_interface === true)
            return true;

        return false;
} // $isInterface

 //------------------- $isInstanceOf() -------------------
 const $isInstanceOf = function(type, instance) {
      //console.log("---- isInstanceOf " + type.name + " ? instance: " + instance);
      var instance_type = getClass(instance);

      if ( instance instanceof type)
          // Check if instance 'isinstanceof' an implementation class
          return true;
      else {
          // Check if instance 'isinstanceof' an interface class
          var implemented_interface;
          if (instance_type._$implemented_interfaces !== undefined) {
              // Check if interface class is in _$implemented_interfaces
              for (var i=0; i<instance_type._$implemented_interfaces.length; i++) {
                  implemented_interface = instance_type._$implemented_interfaces[i];
                  if (implemented_interface === type)
                      return true;
                  else {
                      var parent_interface = implemented_interface._$super_interface;
                      while (parent_interface !== undefined) {
                          if (parent_interface === type)
                              return true;
                          parent_interface = parent_interface._$super_interface;
                          //console.log(">> parent_interface  " + parent_interface.name);
                      } // while (parent_interface != undefined)
                  } // if (implemented_interface === type)
              } // for (var i=0; i<instance_type._$implemented_interfaces.length; i++)
          } // if (instance_type._$implemented_interfaces !== undefined)
      } // if (instance instanceof type)

      return false;
} // $isInstanceOf()

//=================================================================================
//================================ 'MxI' Namespace ================================
//=================================================================================
const MxI = {
    '$Object':                   $Object,
    '$IBaseInterface':           $IBaseInterface,
	'$Interface':                $Interface,
	'$setAsInterface':           $setAsInterface,
    '$Implementation':           $Implementation,
    '$setClass':                 $setClass,
	'$isInstanceOf':             $isInstanceOf,
    '$isInterface':              $isInterface,
	'$raiseNotImplementedError': $raiseNotImplementedError,
}; // MxI namespace
exports.MxI = MxI;
<|endoftext|>


<commit_before>let origMsg = null
const User = require("./User");
class Message {
    constructor(msg) {
        origMsg = msg;
        this.attachments = msg.attachments;
        this.author = new User(msg.author);
        // this.channel = msg.channel;
        // this.channelMentions = msg.channelMentions.map(c => this.guild.channels.get(c));
        this.cleanContent = msg.cleanContent;
        this.content = msg.content;
        this.editedTimestamp = msg.editedTimestamp;
        this.embeds = msg.embeds;
        this.id = msg.id;
        // this.member = msg.member;
        this.mentionEveryone = msg.mentionEveryone;
        this.mentions = msg.mentions.map(u => new User(u));
        // this.mentionsMembers = msg.mentions.map(u => this.guild.members.get(u))
        this.pinned = msg.pinned;
        this.reactions = msg.reactions;
        // this.roleMentions msg.roleMentions.map(r => this.guild.roles.get(r));
        this.timestamp = msg.timestamp;
        this.tts = msg.tts;
        this.type = msg.type;
    }
}
module.exports = Message;<commit_msg>Same with a new method<commit_after>let origMsg = null;
const User = require("./User");
class Message {
    constructor(msg) {
        origMsg = msg;
        this.attachments = msg.attachments;
        this.author = new User(msg.author);
        // this.channel = msg.channel;
        // this.channelMentions = msg.channelMentions.map(c => this.guild.channels.get(c));
        this.cleanContent = msg.cleanContent;
        this.content = msg.content;
        this.editedTimestamp = msg.editedTimestamp;
        this.embeds = msg.embeds;
        this.id = msg.id;
        // this.member = msg.member;
        this.mentionEveryone = msg.mentionEveryone;
        this.mentions = msg.mentions.map(u => new User(u));
        // this.mentionsMembers = msg.mentions.map(u => this.guild.members.get(u))
        this.pinned = msg.pinned;
        this.reactions = msg.reactions;
        // this.roleMentions = msg.roleMentions.map(r => this.guild.roles.get(r));
        this.timestamp = msg.timestamp;
        this.tts = msg.tts;
        this.type = msg.type;
    }

    delete(reason) {
        return origMsg.delete().then(() => "Message sent").catch(() => "There was an error deleting the message.")
    }
}
module.exports = Message;<|endoftext|>


<commit_before><script type="text/javascript">
function website() {
  var homepage = window.alert("http://fsoftwarecoorperations.github.io/fsoftware-coorperations.github.io/");
}
</script>
<commit_msg>Update popup.js<commit_after><script type="text/javascript">
function website() {
  var homepage = window.alert("http://fsoftwarecoorperations.github.io/fsoftware-coorperations.github.io/");
}
function error() {
  var ans = confirm("Anything was wrong.\nRetry?");
  if (ans == true) {
    window.alert("Hello World");
  } else {
    window.alert("Hello World");
  }
}
</script>
<|endoftext|>


<commit_before>'use strict';

angular.module('ehelseEditor').factory('Topic', ['$rootScope', function($rootScope) {

    var topics = [];
    var topics_dict = {};
    var topics_options_list = [];
    var selected_topic = {};

    $rootScope.get(
        'topics/',
        function ( data ){
            Array.prototype.push.apply(topics, data.topics);
            generateTopicDict(topics);
            generateTopicOptionsList(topics);

        },
        function (data) {
            console.log("No document types found");
        }
    );

    function generateTopicDict(topics){
        for(var i = 0; i < topics.length; i++){
            topics_dict[topics[i].id] = topics[i];
            $.extend(topics_dict,
                generateTopicDict(topics[i].children));
        }
    }

    function generateTopicOptionsList(topics){
        topics_options_list.length = 0;
        Array.prototype.push.apply(topics_options_list, generateTopicOptionsListHelper(0, "", topics));
    }

    function generateTopicOptionsListHelper(level, parent, topics){
        var paths = [];
        for (var i = 0; i < topics.length; i++) {
            paths.push({
                id: topics[i].id,
                path: parent + "/" + topics[i].title,
                level: level
            });
            Array.prototype.push.apply(paths, generateTopicOptionsListHelper(level+1, parent + "/" + topics[i].title, topics[i].children))
        }
        return paths;
    }

    function addTopic(topic){
        if(topic.parentId){
            topics_dict[topic.parentId].children.push(topic);
        }
        else{
            topics.push(topic);
        }
        generateTopicDict(topics);
        generateTopicOptionsList(topics);
    }

    function submit(topic){

        if(topic.parentId == "null" || topic.parentId == ""){
            topic.parentId = null;
        }

        if(topic.id){
            $rootScope.put('topics/'+topic.id,
                topic,
                function(data){
                    setTopic(topics_dict[data.id], data);
                    generateTopicOptionsList(topics);
                    $rootScope.notifySuccess('Tema ble oppdatert',6000);

                },
                function(data){
                    $rootScope.notifyError('Tema ble ikke oppdatert.',6000);
                });
        }
        else{
            $rootScope.post(
                'topics/',
                topic,
                function(data){
                    $rootScope.notifySuccess('Ny tema ble opprettet.',6000);
                    addTopic(data);
                },function(){
                    $rootScope.notifyError('Tema ble ikke opprettet.',6000);
                }
            );
        }
    }

    function removeById(id){
        var index = topics.indexOf(topics_dict[id]);
        if (index > -1) {
            topics.splice(index, 1);
        }
    }

    function newTopic(){
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            sequence: null,
            parentId: null,
            comment: "",
            children: [],
            documents: []
        }
    }

    function setTopic(a,b){
        a.id = b.id;
        a.timestamp = b.timestamp;
        a.title = b.title;
        a.description = b.description;
        a.sequence = b.sequence;
        a.parentId = b.parentId;
        a.comment = b.comment;
        a.children = b.children;
        a.documents = b.documents;
    }

    function clone(topic){
        var t = {};
        setTopic(t, topic);
        return t;
    }

    function deleteTopic(topic){
        deleteById(topic.id);
    }
    function deleteById(id){
        if(id){
            $rootScope.delete('topics/'+id,
                function(data){
                    removeById(id);
                    generateTopicDict(topic);
                    generateTopicOptionsList(topic);
                    $rootScope.notifySuccess('Topic ble fjernet',6000);

                },
                function(data){
                    $rootScope.notifyError('Topic ble ikke fjernet.',6000);
                });
        }
    }

    function getAll(){
        return topics;
    }

    function getAllAsDict(){
        return topics_dict;
    }

    function getAllAsOptionsList(){
        return topics_options_list;
    }
    function getById(id){
        return topics_dict[id];
    }
    function setSelectedById(id){
            $rootScope.get('topics/' + id,
                function(data){
                    setTopic(selected_topic, data);
                },
                function(){}
            );
    }
    function getSelected(){
        return selected_topic;
    }

    return {
        new: newTopic,
        clone: clone,
        submit: submit,
        delete: deleteTopic,
        deleteById: deleteById,
        getById: getById,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getAllAsOptionsList: getAllAsOptionsList,
        setSelectedById: setSelectedById,
        getSelected: getSelected
    };
}]);<commit_msg>Fixed bug where topic is not moved when edited<commit_after>'use strict';

angular.module('ehelseEditor').factory('Topic', ['$rootScope', function($rootScope) {

    var topics = [];
    var topics_dict = {};
    var topics_options_list = [];
    var selected_topic = {};

    $rootScope.get(
        'topics/',
        function ( data ){
            Array.prototype.push.apply(topics, data.topics);
            generateTopicDict(topics);
            generateTopicOptionsList(topics);

        },
        function (data) {
            console.log("No document types found");
        }
    );

    function generateTopicDict(topics){
        for(var i = 0; i < topics.length; i++){
            topics_dict[topics[i].id] = topics[i];
            $.extend(topics_dict,
                generateTopicDict(topics[i].children));
        }
    }

    function generateTopicOptionsList(topics){
        topics_options_list.length = 0;
        Array.prototype.push.apply(topics_options_list, generateTopicOptionsListHelper(0, "", topics));
    }

    function generateTopicOptionsListHelper(level, parent, topics){
        var paths = [];
        for (var i = 0; i < topics.length; i++) {
            paths.push({
                id: topics[i].id,
                path: parent + "/" + topics[i].title,
                level: level
            });
            Array.prototype.push.apply(paths, generateTopicOptionsListHelper(level+1, parent + "/" + topics[i].title, topics[i].children))
        }
        return paths;
    }

    function addTopic(topic){
        if(topic.parentId){
            topics_dict[topic.parentId].children.push(topic);
        }
        else{
            topics.push(topic);
        }
        generateTopicDict(topics);
        generateTopicOptionsList(topics);
    }

    function updateTopic(data){
        var old_topic = topics_dict[data.id];
        if(old_topic.parentId != data.parentId){
            removeById(old_topic.id);
            setTopic(topics_dict[data.id], data);
            addTopic(old_topic);
        }
        else{
            setTopic(topics_dict[data.id], data);
        }
    }

    function submit(topic){

        if(topic.parentId == "null" || topic.parentId == ""){
            topic.parentId = null;
        }

        if(topic.id){
            $rootScope.put('topics/'+topic.id,
                topic,
                function(data){
                    updateTopic(data);
                    generateTopicOptionsList(topics);
                    $rootScope.notifySuccess('Tema ble oppdatert',6000);

                },
                function(data){
                    $rootScope.notifyError('Tema ble ikke oppdatert.',6000);
                });
        }
        else{
            $rootScope.post(
                'topics/',
                topic,
                function(data){
                    $rootScope.notifySuccess('Ny tema ble opprettet.',6000);
                    addTopic(data);
                },function(){
                    $rootScope.notifyError('Tema ble ikke opprettet.',6000);
                }
            );
        }
    }

    function removeById(id){
        var element = topics_dict[id];
        var siblings = topics_dict[element.parentId].children;
        removeElementFromArray(element, siblings);
    }

    function removeElementFromArray(element, array){
        var index = array.indexOf(element);
        if (index > -1) {
            array.splice(index, 1);
        }
        generateTopicOptionsList(topics);
        generateTopicDict(topics);
    }

    function newTopic(){
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            sequence: null,
            parentId: null,
            comment: "",
            children: [],
            documents: []
        }
    }

    function setTopic(a,b){
        a.id = b.id;
        a.timestamp = b.timestamp;
        a.title = b.title;
        a.description = b.description;
        a.sequence = b.sequence;
        a.parentId = b.parentId;
        a.comment = b.comment;
        a.children = b.children;
        a.documents = b.documents;
    }

    function clone(topic){
        var t = {};
        setTopic(t, topic);
        return t;
    }

    function deleteTopic(topic){
        deleteById(topic.id);
    }
    function deleteById(id){
        if(id){
            $rootScope.delete('topics/'+id,
                function(data){
                    removeById(id);
                    $rootScope.notifySuccess('Topic ble fjernet',6000);

                },
                function(data){
                    $rootScope.notifyError('Topic ble ikke fjernet.',6000);
                });
        }
    }

    function getAll(){
        return topics;
    }

    function getAllAsDict(){
        return topics_dict;
    }

    function getAllAsOptionsList(){
        return topics_options_list;
    }
    function getById(id){
        return topics_dict[id];
    }
    function setSelectedById(id){
            $rootScope.get('topics/' + id,
                function(data){
                    setTopic(selected_topic, data);
                },
                function(){}
            );
    }
    function getSelected(){
        return selected_topic;
    }

    return {
        new: newTopic,
        clone: clone,
        submit: submit,
        delete: deleteTopic,
        deleteById: deleteById,
        getById: getById,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getAllAsOptionsList: getAllAsOptionsList,
        setSelectedById: setSelectedById,
        getSelected: getSelected
    };
}]);<|endoftext|>


<commit_before>(function() {

	function run()
	{
		var current = AStarSearch.run(source, target, coord);

		// path not found
		if (!current) return;

		var path = findPath(current.path);
		var visited = findVisited(current.visited);

		// starting animation
		runPathAnimation(path, visited, 10);

		// traveling through discovered nodes
		//for (let i = 0; i < visited.length; i++)
		//	coord[visited[i].x][visited[i].y] = 5;

		// traveling through the path
		//for (let i = 1; i < path.length - 1; i++)
		//	coord[path[i].x][path[i].y] = 3;

		draw();
	}

	function runPathAnimation(path, visited, speed)
	{
		// removing source, target from path
		path.shift();
		path.pop();

		// reversing path to it's initial direction
		path.reverse();

		// aborting previous animation
		// if there's any
		clearTimeout(animTimeout);

		// animating visited nodes
		animate(visited, 5, speed, function(){

			// animating the path
			animate(path, 3, speed);
		});
	}

	function animate(path, colorNumber, speed, callback, index = 0)
	{
		// checking for the end
		if (index >= path.length)
		{
			if (callback)
				callback();
			return;
		}

		// processing
		coord[path[index].x][path[index].y] = colorNumber;
		index++;
		draw();

		// repeating the process
		animTimeout = setTimeout(function(){
			animate(path, colorNumber, speed, callback, index);
		}, speed);
	}

	function findPath(node)
	{
		var path = [];
		while (node)
		{
			path.push({ "x": node.gridX, "y": node.gridY });
			node = node.parent;
		}
		console.log("path length: " + path.length);
		return path;
	}

	function findVisited(nodes)
	{
		var visited = [];
		for (let i = 0; i < nodes.length; i++)
		{
			let x = nodes[i].gridX;
			let y = nodes[i].gridY;
			if ( (x != target.x || y != target.y) &&
				 (x != source.x || y != source.y) )
				visited.push({ "x": x, "y": y });
		}
		return visited;
	}

	// fills map acoording to map array contents
	function draw()
	{
		drawSquare(1, 1, "red");
		for (let i = 0; i < 20; i++)
		{
			for (let j = 0; j < 20; j++)
			{
				let color = getColor(coord[i][j]);
				drawSquare(i, j, color);
			}
		}
	}

	function getColor(number)
	{
		switch (number)
		{
			// character - green
			case 1: return "#4caf50";
			// wall - red
			case 2: return "#f44336";
			// path
			case 3: return "lightgreen";
			// target - blue
			case 4: return "#2196F3";
			// visited squares
			case 5: return "#cdffcc";
			// empty square
			default: return "white";
		}
	}

	// fills a square at specified coordinate
	function drawSquare(x, y, color)
	{
		map.fillStyle = color;
		map.fillRect(2 + 15 * x, 2 + 15 * y, 13, 13);
	}

	// clears all squares of specific color
	function clearSquare(number)
	{
		for (let i = 0; i < 20; i++)
		{
			for (let j = 0; j < 20; j++)
			{
				if (coord[i][j] == number)
					coord[i][j] = 0;
			}
		}
	}

	// places a square on mouse location
	function placeSquare(e)
	{
		if (!mousedown)
			return;

		// obtaining coordinates
		var x = Math.ceil((e.clientX - mapElm.offsetLeft) / 15) - 1;
		var y = Math.ceil((e.clientY - mapElm.offsetTop) / 15) - 1;

		// preventing coordinates from going
		// out of bounds
		x = x > 19 ? 19 : x < 0 ? 0 : x;
		y = y > 19 ? 19 : y < 0 ? 0 : y;

		// can't erase source/target
		// can only have it's location changed
		if (target.x == x && target.y == y &&
			selected != 4 || selected != 1 &&
			source.x == x && source.y == y)
			return;

		// deleting old source/target
		// and changing to a new one
		if (selected == 4)
		{
			clearSquare(selected);
			target.x = x;
			target.y = y;
		}
		else if (selected == 1)
		{
			clearSquare(selected);
			source.x = x;
			source.y = y;
		}

		coord[x][y] = selected;
		draw();
	}

	function selectSquare(n)
	{
		var btn;
		switch(n)
		{
			case 0: btn = emptyBtn; break;
			case 1: btn = sourceBtn; break;
			case 2: btn = wallBtn; break;
			case 4: btn = targetBtn; break;
		}

		emptyBtn.style.borderColor = "#c3c3c3";
		sourceBtn.style.borderColor = "#c3c3c3";
		wallBtn.style.borderColor = "#c3c3c3";
		targetBtn.style.borderColor = "#c3c3c3";

		btn.style.borderColor = "#F57F17";
		selected = n;
	}

	// buttons
	var sourceBtn = document.getElementById("source");
	var targetBtn = document.getElementById("target");
	var wallBtn = document.getElementById("wall");
	var emptyBtn = document.getElementById("empty");
	var runBtn = document.getElementById("run");
	var clearBtn = document.getElementById("clear");
	var controlBtn = document.getElementById("controls");

	var selected = 0;
	var mousedown = false;

	// contains timeout responsible
	// for path animation
	var animTimeout;

	// generating empty coordinates for the grid
	var coord = [];
	for (let i = 0; i < 20; i++)
	{
		coord[i] = [];
		for (let j = 0; j < 20; j++)
			coord[i][j] = 0;
	}

	var mapElm = document.getElementById("map");
	var map = mapElm.getContext("2d");

	// character
	var source = { "x": 0, "y": 0 };
	coord[source.x][source.y] = 1;
	// target
	var target = { "x": 19, "y": 19 };
	coord[target.x][target.y] = 4;

	draw();

	sourceBtn.onclick = () => {
		selectSquare(1);
	};
	targetBtn.onclick = () => {
		selectSquare(4);
	};
	wallBtn.onclick = () => {
		selectSquare(2);
	};
	emptyBtn.onclick = () => {
		selectSquare(0);
	};

	// runs the algorithm
	runBtn.onclick = () => {

		// cleans old path
		clearSquare(3);
		clearSquare(5);

		// searching a new one
		run();

	};

	// clears the map
	clearBtn.onclick = () => {
		clearSquare(2);
		clearSquare(3);
		clearSquare(5);
		draw();
	};

	controlBtn.onclick = () => {
		alert("1,2,3,4 - Select a Square \n" +
			  "Esc/Del - Clear all \n" +
			  "Enter/Space - Run");
	};

	// turns off square placement
	mapElm.onmouseup = e => { mousedown = false; };
	mapElm.onmouseout = e => { mousedown = false; };

	// turns on square placement
	mapElm.onmousedown = e => {
		mousedown = true;
		placeSquare(e);
	};

	mapElm.onmousemove = placeSquare;

	// controls
	document.onkeydown = e => {

		switch (e.keyCode)
		{
			// 1
			case 49:
				selectSquare(1);
				break;
			// 2
			case 50:
				selectSquare(4);
				break;
			// 3
			case 51:
				selectSquare(2);
				break;
			// 4
			case 52:
				selectSquare(0);
				break;
			// space
			case 32:
			// enter
			case 13:
				runBtn.click();
				break;
			// esc
			case 27:
			// del
			case 46:
				clearBtn.click();
				break;
		}
	}

})();
<commit_msg>prevented actions from being done during animation<commit_after>(function() {

	function run()
	{
		var current = AStarSearch.run(source, target, coord);

		// path not found
		if (!current) return;

		var path = findPath(current.path);
		var visited = findVisited(current.visited);

		// starting animation
		runPathAnimation(path, visited, 10);

		// traveling through discovered nodes
		//for (let i = 0; i < visited.length; i++)
		//	coord[visited[i].x][visited[i].y] = 5;

		// traveling through the path
		//for (let i = 1; i < path.length - 1; i++)
		//	coord[path[i].x][path[i].y] = 3;

		draw();
	}

	function runPathAnimation(path, visited, speed)
	{
		// removing source, target from path
		path.shift();
		path.pop();

		// reversing path to it's initial direction
		path.reverse();

		// aborting previous animation
		// if there's any
		clearTimeout(animTimeout);

		animating = true;

		// animating visited nodes
		animate(visited, 5, speed, function(){

			// animating the path
			animate(path, 3, speed);
		});
	}

	function animate(path, colorNumber, speed, callback, index = 0)
	{
		// checking for the end
		if (index >= path.length)
		{
			if (callback)
				callback();
			else
				animating = false;

			return;
		}

		// processing
		coord[path[index].x][path[index].y] = colorNumber;
		index++;
		draw();

		// repeating the process
		animTimeout = setTimeout(function(){
			animate(path, colorNumber, speed, callback, index);
		}, speed);
	}

	function findPath(node)
	{
		var path = [];
		while (node)
		{
			path.push({ "x": node.gridX, "y": node.gridY });
			node = node.parent;
		}
		console.log("path length: " + path.length);
		return path;
	}

	function findVisited(nodes)
	{
		var visited = [];
		for (let i = 0; i < nodes.length; i++)
		{
			let x = nodes[i].gridX;
			let y = nodes[i].gridY;
			if ( (x != target.x || y != target.y) &&
				 (x != source.x || y != source.y) )
				visited.push({ "x": x, "y": y });
		}
		return visited;
	}

	// fills map acoording to map array contents
	function draw()
	{
		drawSquare(1, 1, "red");
		for (let i = 0; i < 20; i++)
		{
			for (let j = 0; j < 20; j++)
			{
				let color = getColor(coord[i][j]);
				drawSquare(i, j, color);
			}
		}
	}

	function getColor(number)
	{
		switch (number)
		{
			// character - green
			case 1: return "#4caf50";
			// wall - red
			case 2: return "#f44336";
			// path
			case 3: return "lightgreen";
			// target - blue
			case 4: return "#2196F3";
			// visited squares
			case 5: return "#cdffcc";
			// empty square
			default: return "white";
		}
	}

	// fills a square at specified coordinate
	function drawSquare(x, y, color)
	{
		map.fillStyle = color;
		map.fillRect(2 + 15 * x, 2 + 15 * y, 13, 13);
	}

	// clears all squares of specific color
	function clearSquare(number)
	{
		for (let i = 0; i < 20; i++)
		{
			for (let j = 0; j < 20; j++)
			{
				if (coord[i][j] == number)
					coord[i][j] = 0;
			}
		}
	}

	// places a square on mouse location
	function placeSquare(e)
	{
		if (!mousedown)
			return;

		// obtaining coordinates
		var x = Math.ceil((e.clientX - mapElm.offsetLeft) / 15) - 1;
		var y = Math.ceil((e.clientY - mapElm.offsetTop) / 15) - 1;

		// preventing coordinates from going
		// out of bounds
		x = x > 19 ? 19 : x < 0 ? 0 : x;
		y = y > 19 ? 19 : y < 0 ? 0 : y;

		// can't erase source/target
		// can only have it's location changed
		if (target.x == x && target.y == y &&
			selected != 4 || selected != 1 &&
			source.x == x && source.y == y)
			return;

		// deleting old source/target
		// and changing to a new one
		if (selected == 4)
		{
			clearSquare(selected);
			target.x = x;
			target.y = y;
		}
		else if (selected == 1)
		{
			clearSquare(selected);
			source.x = x;
			source.y = y;
		}

		coord[x][y] = selected;
		draw();
	}

	function selectSquare(n)
	{
		var btn;
		switch(n)
		{
			case 0: btn = emptyBtn; break;
			case 1: btn = sourceBtn; break;
			case 2: btn = wallBtn; break;
			case 4: btn = targetBtn; break;
		}

		emptyBtn.style.borderColor = "#c3c3c3";
		sourceBtn.style.borderColor = "#c3c3c3";
		wallBtn.style.borderColor = "#c3c3c3";
		targetBtn.style.borderColor = "#c3c3c3";

		btn.style.borderColor = "#F57F17";
		selected = n;
	}

	// buttons
	var sourceBtn = document.getElementById("source");
	var targetBtn = document.getElementById("target");
	var wallBtn = document.getElementById("wall");
	var emptyBtn = document.getElementById("empty");
	var runBtn = document.getElementById("run");
	var clearBtn = document.getElementById("clear");
	var controlBtn = document.getElementById("controls");

	var selected = 0;
	var mousedown = false;

	// contains timeout responsible
	// for path animation
	var animTimeout;

	// tells if animation is in progress
	var animating = false;

	// generating empty coordinates for the grid
	var coord = [];
	for (let i = 0; i < 20; i++)
	{
		coord[i] = [];
		for (let j = 0; j < 20; j++)
			coord[i][j] = 0;
	}

	var mapElm = document.getElementById("map");
	var map = mapElm.getContext("2d");

	// character
	var source = { "x": 0, "y": 0 };
	coord[source.x][source.y] = 1;
	// target
	var target = { "x": 19, "y": 19 };
	coord[target.x][target.y] = 4;

	draw();

	sourceBtn.onclick = () => {
		selectSquare(1);
	};
	targetBtn.onclick = () => {
		selectSquare(4);
	};
	wallBtn.onclick = () => {
		selectSquare(2);
	};
	emptyBtn.onclick = () => {
		selectSquare(0);
	};

	// runs the algorithm
	runBtn.onclick = () => {

		// cleans old path
		clearSquare(3);
		clearSquare(5);

		// searching a new one
		run();

	};

	// clears the map
	clearBtn.onclick = () => {

		// cancelling animation
		clearTimeout(animTimeout);
		animating = false;

		clearSquare(2);
		clearSquare(3);
		clearSquare(5);
		draw();
	};

	controlBtn.onclick = () => {

		if (animating)
			return;

		alert("1,2,3,4 - Select a Square \n" +
			  "Esc/Del - Clear all \n" +
			  "Enter/Space - Run");
	};

	// turns off square placement
	mapElm.onmouseup = e => { mousedown = false; };
	mapElm.onmouseout = e => { mousedown = false; };

	// turns on square placement
	mapElm.onmousedown = e => {

		if (animating)
			return;

		mousedown = true;
		placeSquare(e);
	};

	mapElm.onmousemove = e => {

		if (animating)
			return;

		placeSquare(e);
	};

	// controls
	document.onkeydown = e => {

		switch (e.keyCode)
		{
			// 1
			case 49:
				selectSquare(1);
				break;
			// 2
			case 50:
				selectSquare(4);
				break;
			// 3
			case 51:
				selectSquare(2);
				break;
			// 4
			case 52:
				selectSquare(0);
				break;
			// space
			case 32:
			// enter
			case 13:
				runBtn.click();
				break;
			// esc
			case 27:
			// del
			case 46:
				clearBtn.click();
				break;
		}
	}

})();
<|endoftext|>


<commit_before>var request = require('request'),
    async   = require('async'),
    helpers = require('../../helpers'),
    _       = require('underscore');

function chronological(granuals) {
  return _.sortBy(granuals, function(granual) {
    return parseInt(granual.created_at);
  })
}

function convertTweetsTimeType(tweets) {
  tweets = _.sample(tweets, [50]);
  return _.map(tweets, function(tweet) {
    tweet.created_at = helpers.dateToUnix(tweet.created_at);
    return tweet;
  })
}

function removeDuplicates(mediaList, attribute) {
  var seen = {};
  return mediaList.filter(function(mediaItem) {
    var key = mediaItem[''+ attribute +''];
    return seen[key] ? false : (seen[key] = true)
  });
}

function stagger(media, tweets) {
  var staggered = [];
  media.forEach(function(image, index) {
    staggered.push(image);
    if ((index % 2) === 1)
      staggered.push(tweets.shift());
  });

  return staggered.concat(tweets);
}

function requestEndpoints(endpoints, callback) {
  async.parallel({
    first: function(callback) {
      request(endpoints[0], function(err, res, body) {
        callback(null, helpers.toJSON(body).media);
      });
    },
    second: function(callback) {
      request(endpoints[1], function(err, res, body) {
        callback(null, helpers.toJSON(body).media);
      });
    },
    third: function(callback) {
      request(endpoints[2], function(err, res, body) {
        callback(null, helpers.toJSON(body).media);
      });
    }
  }, function(err, data) {
    if (err) { callback(err); return };
    callback(err,
      data.first
      .concat(data.second, data.third));
  })
}

function requestEndpoint(endpoint, callback) {
  request(endpoint, function(err, res, body) {
    if (err) { callback(err); return };
    callback(err, helpers.toJSON(body).tweets);
  });
}

module.exports = (function(){
	// GET /users/:id/media?lat=LAT&lng=LNG&time=TIME
	return function collection(req, res) {
    var params = helpers.urlParams(req.url);
    var capsul = {
      user_id: req.params.id,
      latitude: params.lat,
      longitude: params.lng,
      timestamp: params.time,
      data: []
    }

    async.parallel({
      instagram: function(callback) {
        var endpoints = require('../media/instagram')(req.url);
        requestEndpoints(endpoints, function(err, instagramData) {
          instagramData = removeDuplicates(instagramData, 'created_at');
          callback(null, instagramData)
        })
      },
      twitter: function(callback) {
        var endpoint = require('../media/twitter')(req.url)
        requestEndpoint(endpoint, function(err, twitterData) {
          callback(null, twitterData)
        });
      }
    },
    function(err, data) {
      var tweets = chronological(convertTweetsTimeType(data.twitter));
      var media = chronological(data.instagram);
      capsul.data = tweets.length ? stagger(media, tweets) : media
      res.json(capsul);
    });
  }
})()<commit_msg>Refactor hashed async.parallel call to handle any number of async requests.<commit_after>var request = require('request'),
    async   = require('async'),
    helpers = require('../../helpers'),
    _       = require('underscore');

function chronological(granuals) {
  return _.sortBy(granuals, function(granual) {
    return parseInt(granual.created_at);
  })
}

function convertTweetsTimeType(tweets) {
  tweets = _.sample(tweets, [50]);
  return _.map(tweets, function(tweet) {
    tweet.created_at = helpers.dateToUnix(tweet.created_at);
    return tweet;
  })
}

function removeDuplicates(mediaList, attribute) {
  var seen = {};
  return mediaList.filter(function(mediaItem) {
    var key = mediaItem[''+ attribute +''];
    return seen[key] ? false : (seen[key] = true)
  });
}

function stagger(media, tweets) {
  var staggered = [];
  media.forEach(function(image, index) {
    staggered.push(image);
    if ((index % 2) === 1)
      staggered.push(tweets.shift());
  });

  return staggered.concat(tweets);
}

function endpointsToRequests(endpoints) {
  return endpoints.map(function(endpoint) {
    return function(callback) {
      request(endpoint, function(err, res, body) {
        callback(null, helpers.toJSON(body).media);
      });
    }
  });
}

function requestEndpoints(endpoints, callback) {
  endpoints = endpointsToRequests(endpoints)
  async.parallel(endpoints,
  function(err, data) {
    if (err) { callback(err); return };
    callback(err, _.flatten(data))
  })
}

function requestEndpoint(endpoint, callback) {
  request(endpoint, function(err, res, body) {
    if (err) { callback(err); return };
    callback(err, helpers.toJSON(body).tweets);
  });
}

module.exports = (function(){
	// GET /users/:id/media?lat=LAT&lng=LNG&time=TIME
	return function collection(req, res) {
    var params = helpers.urlParams(req.url);
    var capsul = {
      user_id: req.params.id,
      latitude: params.lat,
      longitude: params.lng,
      timestamp: params.time,
      data: []
    }

    async.parallel({
      instagram: function(callback) {
        var endpoints = require('../media/instagram')(req.url);
        requestEndpoints(endpoints, function(err, instagramData) {
          instagramData = removeDuplicates(instagramData, 'created_at');
          callback(null, instagramData)
        })
      },
      twitter: function(callback) {
        var endpoint = require('../media/twitter')(req.url)
        requestEndpoint(endpoint, function(err, twitterData) {
          callback(null, twitterData)
        });
      }
    },
    function(err, data) {
      var tweets = chronological(convertTweetsTimeType(data.twitter));
      var media = chronological(data.instagram);
      capsul.data = tweets.length ? stagger(media, tweets) : media
      res.json(capsul);
    });
  }
})()<|endoftext|>


<commit_before>'use strict';

//Setting up route
angular.module('groups').config(['$stateProvider',
	function($stateProvider) {
		var isUserSuperAdmin = function($q, $timeout, $location, Authentication) {
			// Initialize a new promise
			var deferred = $q.defer();
			var authentication = Authentication.user.roles[0];
			console.log(authentication);
			if (authentication === 'superadmin')
				$timeout(deferred.resolve);
			else {
				$timeout(deferred.reject);
				$location.url('/dashboard');
			}
			return deferred.promise;
		};

		// Groups state routing
		$stateProvider.
		state('listGroups', {
			url: '/groups',
			templateUrl: 'modules/groups/views/list-groups.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		}).
		state('createGroup', {
			url: '/groups/create',
			templateUrl: 'modules/groups/views/create-group.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		}).
		state('viewGroup', {
			url: '/groups/:groupId',
			templateUrl: 'modules/groups/views/view-group.client.view.html',
			resolve: {
					checkRole: isUserSuperAdmin
				}
		}).
		state('editGroup', {
			url: '/groups/:groupId/edit',
			templateUrl: 'modules/groups/views/edit-group.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		});
	}
]);
<commit_msg>removing Console.<commit_after>'use strict';

//Setting up route
angular.module('groups').config(['$stateProvider',
	function($stateProvider) {
		var isUserSuperAdmin = function($q, $timeout, $location, Authentication) {
			// Initialize a new promise
			var deferred = $q.defer();
			var authentication = Authentication.user.roles[0];
			if (authentication === 'superadmin')
				$timeout(deferred.resolve);
			else {
				$timeout(deferred.reject);
				$location.url('/dashboard');
			}
			return deferred.promise;
		};

		// Groups state routing
		$stateProvider.
		state('listGroups', {
			url: '/groups',
			templateUrl: 'modules/groups/views/list-groups.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		}).
		state('createGroup', {
			url: '/groups/create',
			templateUrl: 'modules/groups/views/create-group.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		}).
		state('viewGroup', {
			url: '/groups/:groupId',
			templateUrl: 'modules/groups/views/view-group.client.view.html',
			resolve: {
					checkRole: isUserSuperAdmin
				}
		}).
		state('editGroup', {
			url: '/groups/:groupId/edit',
			templateUrl: 'modules/groups/views/edit-group.client.view.html',
			resolve: {
				checkRole: isUserSuperAdmin
			}
		});
	}
]);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Timo Behrmann. All rights reserved.
 */

var handler = require('node-restify-errors');

module.exports.handle = function (errors, req, res, options, next) {
    return res.send(new handler.InvalidContentError(errors));
};
<commit_msg>Revert "Update error.js"<commit_after>/*
 * Copyright (c) 2013 Timo Behrmann. All rights reserved.
 */

module.exports.handle = function (errors, req, res, options, next) {
    return res.send(400, {
        status: 'validation failed',
        errors: errors
    });
};<|endoftext|>


<commit_before>import AvatarImageField from 'rmw-shell/lib/components/ReduxFormFields/AvatarImageField'
import Business from '@material-ui/icons/Business'
import MenuItem from '@material-ui/core/MenuItem'
import renderSelectField from '../Select'
import React, { Component } from 'react'
import TextField from 'rmw-shell/lib/components/ReduxFormFields/TextField'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { ImageCropDialog } from 'rmw-shell/lib/containers/ImageCropDialog'
import { connect } from 'react-redux'
import { injectIntl } from 'react-intl'
import { setDialogIsOpen } from 'rmw-shell/lib/store/dialogs/actions'
import { withRouter } from 'react-router-dom'
import { withTheme } from '@material-ui/core/styles'

class Form extends Component {
  render() {
    const {
      handleSubmit,
      intl,
      initialized,
      setDialogIsOpen,
      dialogs,
      match,
      change,
    } = this.props

    const uid = match.params.uid

    return (
      <form
        onSubmit={handleSubmit}
        style={{
          height: '100%',
          width: '100%',
          alignItems: 'strech',
          display: 'flex',
          flexWrap: 'wrap',
          justifyContent: 'center',
        }}
      >
        <button type="submit" style={{ display: 'none' }} />

          <AvatarImageField
            name="photoURL"
            disabled={!initialized}
            uid={uid}
            change={change}
            initialized={initialized}
            icon={<Business fontSize="large" />}
            intl={intl}
            path={'companies'}
          />

            <Field
              name="name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'name_hint' })}
              label={intl.formatMessage({ id: 'name_label' })}
            />

         <Field
          id="color"
          disabled={!initialized}
          label={intl.formatMessage({ id: 'color_label' })}
          name="color"
          component={renderSelectField}>
           <MenuItem value={'amber'}> {intl.formatMessage({ id: 'amber_label' })} </MenuItem>
           <MenuItem value={'black'}> {intl.formatMessage({ id: 'black_label' })} </MenuItem>
           <MenuItem value={'blue'}> {intl.formatMessage({ id: 'blue_label' })} </MenuItem>
           <MenuItem value={'gray'}> {intl.formatMessage({ id: 'gray_label' })} </MenuItem>
          <MenuItem value={'green'}> {intl.formatMessage({ id: 'green_label' })} </MenuItem>
          </Field>

         <Field
          id="dress"
          label={intl.formatMessage({ id: 'dress_label' })}
          name="dress"
          component={renderSelectField}>
        <MenuItem value={'XS'}> XS </MenuItem>
        <MenuItem value={'S'}> S </MenuItem>
        <MenuItem value={'S/M'}> S/M </MenuItem>
        <MenuItem value={'M'}> M </MenuItem>
        <MenuItem value={'M/L'}> M/L </MenuItem>
        <MenuItem value={'L'}> L </MenuItem>
        <MenuItem value={'XL'}> XL </MenuItem>
        <MenuItem value={'XXL'}> XXL </MenuItem>
        </Field>

            <Field
              name="full_name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'full_name_hint' })}
              label={intl.formatMessage({ id: 'full_name_label' })}
            />

            <Field
              name="vat"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'vat_hint' })}
              label={intl.formatMessage({ id: 'vat_label' })}
            />

            <Field
              name="workers"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'workers_hint' })}
              label={intl.formatMessage({ id: 'workers_label' })}
              type="number"
            />

            <Field
              name="worth"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'worth_hint' })}
              label={intl.formatMessage({ id: 'worth_label' })}
            />

            <Field
              name="description"
              disabled={!initialized}
              component={TextField}
              multiline
              rows={2}
              placeholder={intl.formatMessage({ id: 'description_hint' })}
              label={intl.formatMessage({ id: 'description_label' })}
            />

          <ImageCropDialog
            path={`companies/${uid}`}
            fileName={'photoURL'}
            onUploadSuccess={s => {
              this.handlePhotoUploadSuccess(s)
            }}
            open={dialogs.new_company_photo !== undefined}
            src={dialogs.new_company_photo}
            handleClose={() => {
              setDialogIsOpen('new_company_photo', undefined)
            }}
            title={intl.formatMessage({ id: 'change_photo' })}
          />

      </form>
    )
  }
}

Form = reduxForm({ form: 'company' })(Form)
const selector = formValueSelector('company')

const mapStateToProps = state => {
  const { intl, vehicleTypes, users, dialogs } = state

  return {
    intl,
    vehicleTypes,
    users,
    dialogs,
    photoURL: selector(state, 'photoURL'),
  }
}

export default connect(mapStateToProps, { setDialogIsOpen })(
  injectIntl(withRouter(withTheme(Form)))
)
<commit_msg>Delete Company.js<commit_after><|endoftext|>


<commit_before>var clues_render_to = 'clues_js';

function render_clues()
{
    document.getElementById(clues_render_to).innerHTML = '';
    clue_initial_letters();
	clue_lengths();
}

function isLetter(str) {
  return str.length === 1 && str.match(/[a-z]/i);
}

function clue_initial_letters()
{
	var puzdata = PUZAPP.puzdata;
    var letters = [];
    var clue_lists = [puzdata.across_clues, puzdata.down_clues];
    for (var j=0; j < clue_lists.length; j++)
    {
        clues = clue_lists[j];
        for (var key in clues)
        {
            if (!clues.hasOwnProperty(key))
                continue;
            // Find the first letter of the clue
            for (var i=0; i < clues[key].length; i++)
            {
                if (isLetter(clues[key].charAt(i)))
                {
                    letters.push(clues[key].charAt(i).toUpperCase());
                    break;
                }
            }
        }
    }

    document.getElementById(clues_render_to).innerHTML += 'First letters of clues:
' + letters.join(' ') + '

';
}

function clue_lengths()
{
	// Display the number of clues for each length
	var puzdata = PUZAPP.puzdata;
	var clue_lists = [puzdata.across_clues, puzdata.down_clues];
	var categories = ['1','2','3','4','5','6','7','8','9','>= 10'];
	var data = [];
	// Initialize the data
	for (var i=0; i<categories.length; i++)
	{
		data.push(0);
	}
    for (var j=0; j < clue_lists.length; j++)
    {
        clues = clue_lists[j];
        for (var key in clues)
        {
            if (!clues.hasOwnProperty(key))
                continue;
            // Find the length of the clue
			var clue_length = clues[key].split(' ').length;
			if (clue_length >= 10)
				clue_length = 10;
			// Push to "data"
			data[clue_length-1] += 1;
        }
    }
	data.unshift('Count');
	// Plot
	var chart = c3.generate({
        bindto: '#clues0',
		title: {
            text: 'Clue length (number of words)'
        },
        data: {
			columns: [data],
            type: 'bar',
			labels: true
        },
		size: {
			// Chart won't render unless we initialize the size up front
			width: 340
		},
		axis: {
			rotated: true,
			x: {
                type: 'category',
                categories: categories
            },
            y: {
                label: 'Count'
            }
		},

    });
    CHARTS['clues'].push(chart);
}

<commit_msg>add to Clues tab display for any starred Across or Down clues<commit_after>var clues_render_to = 'clues_js';

function render_clues()
{
    document.getElementById(clues_render_to).innerHTML = '';
    clue_initial_letters();
	clue_lengths();
    starred_clues();
}

function isLetter(str) {
  return str.length === 1 && str.match(/[a-z]/i);
}

function clue_initial_letters()
{
	var puzdata = PUZAPP.puzdata;
    var letters = [];
    var clue_lists = [puzdata.across_clues, puzdata.down_clues];
    for (var j=0; j < clue_lists.length; j++)
    {
        clues = clue_lists[j];
        for (var key in clues)
        {
            if (!clues.hasOwnProperty(key))
                continue;
            // Find the first letter of the clue
            for (var i=0; i < clues[key].length; i++)
            {
                if (isLetter(clues[key].charAt(i)))
                {
                    letters.push(clues[key].charAt(i).toUpperCase());
                    break;
                }
            }
        }
    }

    document.getElementById(clues_render_to).innerHTML += 'First letters of clues:
' + letters.join(' ') + '

';
}

function clue_lengths()
{
	// Display the number of clues for each length
	var puzdata = PUZAPP.puzdata;
	var clue_lists = [puzdata.across_clues, puzdata.down_clues];
	var categories = ['1','2','3','4','5','6','7','8','9','>= 10'];
	var data = [];
	// Initialize the data
	for (var i=0; i<categories.length; i++)
	{
		data.push(0);
	}
    for (var j=0; j < clue_lists.length; j++)
    {
        clues = clue_lists[j];
        for (var key in clues)
        {
            if (!clues.hasOwnProperty(key))
                continue;
            // Find the length of the clue
			var clue_length = clues[key].split(' ').length;
			if (clue_length >= 10)
				clue_length = 10;
			// Push to "data"
			data[clue_length-1] += 1;
        }
    }
	data.unshift('Count');
	// Plot
	var chart = c3.generate({
        bindto: '#clues0',
		title: {
            text: 'Clue length (number of words)'
        },
        data: {
			columns: [data],
            type: 'bar',
			labels: true
        },
		size: {
			// Chart won't render unless we initialize the size up front
			width: 340
		},
		axis: {
			rotated: true,
			x: {
                type: 'category',
                categories: categories
            },
            y: {
                label: 'Count'
            }
		},

    });
    CHARTS['clues'].push(chart);
}

function starred_clues() {

    var puzdata = PUZAPP.puzdata;
    var starred_clues = [];
    var starred_clues = getStringsPreOrPostfixedWith(puzdata.across_clues, '*', 'A');
    var starred_down = getStringsPreOrPostfixedWith(puzdata.down_clues, '*', 'D');
    starred_clues.push(starred_down);

    document.getElementById(clues_render_to).innerHTML += 'Starred clues:
\n\n';

    if (starred_clues.length == 0) {
        document.getElementById(clues_render_to).innerHTML += '<none>' + '
\n';
    } else {
        for (var i = 0; i < starred_clues.length; ++i) {
            document.getElementById(clues_render_to).innerHTML += starred_clues[i] + "
\n";
        }
        document.getElementById(clues_render_to).innerHTML += "\n
\n";
    }
}

function getStringsPreOrPostfixedWith(strings, token, type) {

    var retval = [];

    for (var i in strings) {
        if(strings[i].startsWith(token) || strings[i].endsWith(token)) {
            // console.log(i + type + " " + strings[i]);
            retval.push(i + type + " " + strings[i]);
        }
    }

    return retval;
}
<|endoftext|>