<commit_before>
CircleGraph = function (container) {

  this.drawGlobalProjectsGraph = function(labels) {
    this.clearContainer();

    // calculate central circle's dimensions
    var circleRadius = 0.13 * this.width;
    var verticalShift = 0.05 * this.width;

    this.drawCentralCircle(circleRadius, verticalShift, labels, "/global/projects");
  }

  this.drawRegionalProjectsGraph = function(labels, regionsData) {
    this.clearContainer();

    // calculate central circle's dimensions
    var innerCircleRadius = 0.13 * this.width;
    var outerCircleRadius = 0.22 * this.width;

    this.drawCentralCircle(innerCircleRadius, 0.2*innerCircleRadius, labels);

    var maxBudget = d3.max(regionsData.regionalProjects.map(function(project) { return project.budget; }));
    var minBudget = d3.min(regionsData.regionalProjects.map(function(project) { return project.budget; }));

    var sateliteContainerW = 0.17 * this.width;
    var sateliteContainerH = 0.10 * this.width;

    var minSateliteCircleR = 0.10 * sateliteContainerH;
    var maxSateliteCircleR = 0.20 * sateliteContainerH;

    var scale = d3.scale.linear();
    scale.domain([minBudget, maxBudget]);
    scale.range([minSateliteCircleR, maxSateliteCircleR]);

    plots = regionsData.regionalProjects.length;
    increase = Math.PI * 2 / plots,
    angle = 15,
    x = 0,
    y = 0;
    for(var i = 0; i < plots; i++) {
      var sateliteCircleR = scale(regionsData.regionalProjects[i].budget)
      var p = new SateliteCircle(container, 'element_' + i, regionsData.regionalProjects[i],
                                 sateliteContainerW, sateliteContainerH, sateliteCircleR);
      x = outerCircleRadius * Math.cos(angle) + this.width / 2 + 0.13*innerCircleRadius;
      y = outerCircleRadius * Math.sin(angle) + this.height / 2 ;//- 0.2*innerCircleRadius;
      p.position(x, y);

      (function(){
        var code = p.getData().code;
        $(p.getElement()).click(function(){
          window.location= "/regions/" + code + "/projects";
        })
      })()

      angle += increase;
    }
  }

  this.clearContainer = function() {
    // first remove the graph if it exist inside the container
    // this prevents drawing multiple graphs while resising window
    $(container.selector + ' svg').remove();
    $(container.selector + ' div').remove();

    // update the graph's container dimensions
    this.width = container.width();
    this.height = 0.55 * this.width; // original width to height ratio
  }

  this.drawCentralCircle = function(r, shiftY, labels, location) {

    var circleShiftX = this.width / 2 - r;
    var circleShiftY = this.height / 2 - r - shiftY; // shiftY - additional shift, when circle is not centered on Y axis

    var headerTextSize = 0.14 * r;
    var amountTextSize = 2 * headerTextSize;

    var g = d3.select(container.selector)
                .append("svg")
                .append("g")
                .attr("transform", "translate(" + circleShiftX + ", " + circleShiftY + ")");

    var circle = g.append("circle")
        .style("fill", "#008270")
        .style("opacity", "0.7")
        .attr("r", r)
        .attr("cx", r)
        .attr("cy", r);

    var text = g.append("text")
        .attr("text-anchor", "middle")
        .attr("fill", "#FFF")
        .attr("transform", "translate(" + r + ", " + r + ")")
        .style("font-size", headerTextSize + "px")
        .style("line-height", "1.1em")
        .append("tspan")
           .text(labels.header)
           .attr("x", "0")
           .attr("dy", "-0.3em")
        .append("tspan")
           .text(labels.amount)
           .attr("x", "0")
           .attr("dy", "1em")
           .style("font-size", amountTextSize + "px");

    if(location) {
      circle.on("click", function(){
        window.location = location;
      }).style("cursor", "hand")
      text.on("click", function(){
        window.location = location;
      }).style("cursor", "hand")
    }
  }

  this.drawOuterCentralCircle = function(radius) {
    var circleShiftX = this.width / 2 - radius;
    var circleShiftY = this.height / 2 - radius;

    var g = d3.select(container.selector + ' svg')
                .append("g")
                .attr("transform", "translate(" + circleShiftX + ", " + circleShiftY + ")");

    g.append("circle")
        .style("stroke", "gray")
        .style("fill", "transparent")
        .style("z-index", "-1")
        .attr("r", radius)
        .attr("cx", radius)
        .attr("cy", radius);
  }
};

SateliteCircle = function (container, selector, data, w, h, r) {

  this.data = data;
  this.position = function( x, y ) {
    this.elm.style.left = (x - w / 2) + 'px';
    this.elm.style.top = (y - h / 2) + 'px';
    this.x = x;
    this.y = y;
  };

  this.elm = document.createElement('div');
  this.elm.style.cursor = 'hand';
  this.elm.style.position = 'absolute';
  this.elm.id = selector;
  this.elm.style.width = w + 'px';
  this.elm.style.height = h + 'px';
  this.elm.style.overflow = 'visible';
  this.width = w;
  this.height = h;
  container.append(this.elm);

  var g = d3.select('#' + this.elm.id)
              .append("svg")
              .append("g");

  g.append("circle")
      .style("fill", "#008270")
      .style("opacity", "0.7")
      .style("cursor", "hand")
      .attr("r", r)
      .attr("cx", w / 2)
      .attr("cy", r);

  var textSize = 0.6 * r;
  if (textSize > 7) {
    g.append("text")
      .attr("text-anchor", "middle")
      .attr("fill", "#FFF")
      .attr("transform", "translate(" +  (w / 2) + ", " + 1.2 * r + ")")
      .style("font-size", textSize + "px")
      .style("line-height", "1.1em")
      .style("cursor", "hand")
      .append("tspan")
         .text(format_million_stg(data.budget));
  }

  g.append("text")
      .attr("text-anchor", "middle")
      .attr("transform", "translate(" + w / 2 + ", " + (2.6 * r) + ")")
      .style("font-size", 10 + "px")
      .style("line-height", "1.2em")
      .append("tspan")
         .text(data.region)
         .attr("x", "0")
         .attr("dy", "0");
};

SateliteCircle.prototype.getElement = function(){
  return this.elm;
}

SateliteCircle.prototype.getData = function(){
  return this.data;
}

format_million_stg = function(amt) {
  return '\u00A3' + Math.floor(amt / 1000000) + 'm';
}
<commit_msg>removed proprietory hand setting that broke ie<commit_after>
CircleGraph = function (container) {

  this.drawGlobalProjectsGraph = function(labels) {
    this.clearContainer();

    // calculate central circle's dimensions
    var circleRadius = 0.13 * this.width;
    var verticalShift = 0.05 * this.width;

    this.drawCentralCircle(circleRadius, verticalShift, labels, "/global/projects");
  }

  this.drawRegionalProjectsGraph = function(labels, regionsData) {
    this.clearContainer();

    // calculate central circle's dimensions
    var innerCircleRadius = 0.13 * this.width;
    var outerCircleRadius = 0.22 * this.width;

    this.drawCentralCircle(innerCircleRadius, 0.2*innerCircleRadius, labels);

    var maxBudget = d3.max(regionsData.regionalProjects.map(function(project) { return project.budget; }));
    var minBudget = d3.min(regionsData.regionalProjects.map(function(project) { return project.budget; }));

    var sateliteContainerW = 0.17 * this.width;
    var sateliteContainerH = 0.10 * this.width;

    var minSateliteCircleR = 0.10 * sateliteContainerH;
    var maxSateliteCircleR = 0.20 * sateliteContainerH;

    var scale = d3.scale.linear();
    scale.domain([minBudget, maxBudget]);
    scale.range([minSateliteCircleR, maxSateliteCircleR]);

    plots = regionsData.regionalProjects.length;
    increase = Math.PI * 2 / plots,
    angle = 15,
    x = 0,
    y = 0;
    for(var i = 0; i < plots; i++) {
      var sateliteCircleR = scale(regionsData.regionalProjects[i].budget)
      var p = new SateliteCircle(container, 'element_' + i, regionsData.regionalProjects[i],
                                 sateliteContainerW, sateliteContainerH, sateliteCircleR);
      x = outerCircleRadius * Math.cos(angle) + this.width / 2 + 0.13*innerCircleRadius;
      y = outerCircleRadius * Math.sin(angle) + this.height / 2 ;//- 0.2*innerCircleRadius;
      p.position(x, y);

      (function(){
        var code = p.getData().code;
        $(p.getElement()).click(function(){
          window.location= "/regions/" + code + "/projects";
        })
      })()

      angle += increase;
    }
  }

  this.clearContainer = function() {
    // first remove the graph if it exist inside the container
    // this prevents drawing multiple graphs while resising window
    $(container.selector + ' svg').remove();
    $(container.selector + ' div').remove();

    // update the graph's container dimensions
    this.width = container.width();
    this.height = 0.55 * this.width; // original width to height ratio
  }

  this.drawCentralCircle = function(r, shiftY, labels, location) {

    var circleShiftX = this.width / 2 - r;
    var circleShiftY = this.height / 2 - r - shiftY; // shiftY - additional shift, when circle is not centered on Y axis

    var headerTextSize = 0.14 * r;
    var amountTextSize = 2 * headerTextSize;

    var g = d3.select(container.selector)
                .append("svg")
                .append("g")
                .attr("transform", "translate(" + circleShiftX + ", " + circleShiftY + ")");

    var circle = g.append("circle")
        .style("fill", "#008270")
        .style("opacity", "0.7")
        .attr("r", r)
        .attr("cx", r)
        .attr("cy", r);

    var text = g.append("text")
        .attr("text-anchor", "middle")
        .attr("fill", "#FFF")
        .attr("transform", "translate(" + r + ", " + r + ")")
        .style("font-size", headerTextSize + "px")
        .style("line-height", "1.1em")
        .append("tspan")
           .text(labels.header)
           .attr("x", "0")
           .attr("dy", "-0.3em")
        .append("tspan")
           .text(labels.amount)
           .attr("x", "0")
           .attr("dy", "1em")
           .style("font-size", amountTextSize + "px");

    if(location) {
      circle.on("click", function(){
        window.location = location;
      }).style("cursor", "hand")
      text.on("click", function(){
        window.location = location;
      }).style("cursor", "hand")
    }
  }

  this.drawOuterCentralCircle = function(radius) {
    var circleShiftX = this.width / 2 - radius;
    var circleShiftY = this.height / 2 - radius;

    var g = d3.select(container.selector + ' svg')
                .append("g")
                .attr("transform", "translate(" + circleShiftX + ", " + circleShiftY + ")");

    g.append("circle")
        .style("stroke", "gray")
        .style("fill", "transparent")
        .style("z-index", "-1")
        .attr("r", radius)
        .attr("cx", radius)
        .attr("cy", radius);
  }
};

SateliteCircle = function (container, selector, data, w, h, r) {

  this.data = data;
  this.position = function( x, y ) {
    this.elm.style.left = (x - w / 2) + 'px';
    this.elm.style.top = (y - h / 2) + 'px';
    this.x = x;
    this.y = y;
  };

  this.elm = document.createElement('div');
  this.elm.style.cursor = 'hand';
  this.elm.style.position = 'absolute';
  this.elm.id = selector;
  this.elm.style.width = w + 'px';
  this.elm.style.height = h + 'px';
  this.elm.style.overflow = 'visible';
  this.width = w;
  this.height = h;
  container.append(this.elm);

  var g = d3.select('#' + this.elm.id)
              .append("svg")
              .append("g");

  g.append("circle")
      .style("fill", "#008270")
      .style("opacity", "0.7")
      .style("cursor", "pointer")
      .attr("r", r)
      .attr("cx", w / 2)
      .attr("cy", r);

  var textSize = 0.6 * r;
  if (textSize > 7) {
    g.append("text")
      .attr("text-anchor", "middle")
      .attr("fill", "#FFF")
      .attr("transform", "translate(" +  (w / 2) + ", " + 1.2 * r + ")")
      .style("font-size", textSize + "px")
      .style("line-height", "1.1em")
      .style("cursor", "pointer")
      .append("tspan")
         .text(format_million_stg(data.budget));
  }

  g.append("text")
      .attr("text-anchor", "middle")
      .attr("transform", "translate(" + w / 2 + ", " + (2.6 * r) + ")")
      .style("font-size", 10 + "px")
      .style("line-height", "1.2em")
      .append("tspan")
         .text(data.region)
         .attr("x", "0")
         .attr("dy", "0");
};

SateliteCircle.prototype.getElement = function(){
  return this.elm;
}

SateliteCircle.prototype.getData = function(){
  return this.data;
}

format_million_stg = function(amt) {
  return '\u00A3' + Math.floor(amt / 1000000) + 'm';
}
<|endoftext|>


<commit_before>'use strict';

KylinApp.controller('CubeSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, AuthenticationService) {
    //~ Define metadata & class
    $scope.capacities = ['SMALL', 'MEDIUM', 'LARGE'];
    $scope.cubePartitionTypes = ['APPEND', 'UPDATE_INSERT'];
    $scope.projects = [];
    $scope.newDimension = null;
    $scope.newMeasure = null;

    $scope.wizardSteps = [
        {title: 'Cube Info', src: 'partials/cubeDesigner/info.html', isComplete: false},
        {title: 'Data Model', src: 'partials/cubeDesigner/data_model.html', isComplete: false},
        {title: 'Dimensions', src: 'partials/cubeDesigner/dimensions.html', isComplete: false},
        {title: 'Measures', src: 'partials/cubeDesigner/measures.html', isComplete: false},
        {title: 'Filter', src: 'partials/cubeDesigner/filter.html', isComplete: false},
        {title: 'Refresh Setting', src: 'partials/cubeDesigner/incremental.html', isComplete: false}
    ];
    if (UserService.hasRole("ROLE_ADMIN")) {
            $scope.wizardSteps.push({title: 'Advanced Setting', src: 'partials/cubeDesigner/advanced_settings.html', isComplete: false});
    }
    $scope.wizardSteps.push({title: 'Overview', src: 'partials/cubeDesigner/overview.html', isComplete: false});

    $scope.curStep = $scope.wizardSteps[0];

    var Measure = {
        createNew: function () {
            var measure = {
                "id": "",
                "name": "",
                "function": {
                    "expression": "",
                    "returntype": "",
                    "parameter": {
                        "type": "",
                        "value": ""
                    }
                }
            };

            return measure;
        }
    };

    // ~ init
    if (!$scope.state) {
        $scope.state = {mode: "view"};
    }

    $scope.$watch('cube.detail', function (newValue, oldValue) {
        if (newValue) {
            $scope.cubeMetaFrame = newValue;
        }
    });

    $scope.$watch('cubeMetaFrame', function (newValue, oldValue) {
        if(!newValue){
            return;
        }
        if ($scope.cubeMode=="editExistCube"&&newValue && !newValue.project) {
            initProject();
        }
        //convert from UTC to local timezone
        if($scope.cubeMetaFrame.cube_partition_desc.partition_date_start)
        {
            $scope.cubeMetaFrame.cube_partition_desc.partition_date_start+=new Date().getTimezoneOffset()*60000;
        }
    });

    // ~ public methods
    $scope.filterProj = function(project){
        return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project,$scope.permissions.ADMINISTRATION.mask);
    };

    $scope.addNewMeasure = function (measure) {
        $scope.newMeasure = (!!measure)? measure:Measure.createNew();
    };

    $scope.clearNewMeasure = function () {
        $scope.newMeasure = null;
    };

    $scope.saveNewMeasure = function () {
        if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
            $scope.cubeMetaFrame.measures.push($scope.newMeasure);
        }
        $scope.newMeasure = null;
    };

    $scope.addNewRowkeyColumn = function () {
        $scope.cubeMetaFrame.rowkey.rowkey_columns.push({
            "column": "",
            "length": 0,
            "dictionary": "true",
            "mandatory": false
        });
    };

    $scope.addNewAggregationGroup = function () {
        $scope.cubeMetaFrame.rowkey.aggregation_groups.push([]);
    };

    $scope.refreshAggregationGroup = function (list, index, aggregation_groups) {
        if (aggregation_groups) {
            list[index] = aggregation_groups;
        }
    };

    $scope.removeElement = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
        }
    };

    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };

    $scope.preView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex >= 1) {
            $scope.curStep.isComplete = false;
            $scope.curStep = $scope.wizardSteps[stepIndex - 1];
        }
    };

    $scope.nextView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex < ($scope.wizardSteps.length - 1)) {
            $scope.curStep.isComplete = true;
            $scope.curStep = $scope.wizardSteps[stepIndex + 1];

            AuthenticationService.ping(function (data) {
                UserService.setCurUser(data);
            });
        }
    };

    // ~ private methods
    function initProject() {
        ProjectService.list({}, function (projects) {
            $scope.projects = projects;

            var cubeName = (!!$scope.routeParams.cubeName)? $scope.routeParams.cubeName:$scope.state.cubeName;
            if (cubeName) {
                var projName = null;
                angular.forEach($scope.projects, function (project, index) {
                    angular.forEach(project.cubes, function (cube, index) {
                        if (!projName && cube === cubeName.toUpperCase()) {
                            projName = project.name;
                        }
                    });
                });

                $scope.cubeMetaFrame.project = projName;
            }

            angular.forEach($scope.projects, function (project, index) {
                $scope.listAccess(project, 'ProjectInstance');
            });
        });
    }
});
<commit_msg>help jason fix time zone issue<commit_after>'use strict';

KylinApp.controller('CubeSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, AuthenticationService) {
    //~ Define metadata & class
    $scope.capacities = ['SMALL', 'MEDIUM', 'LARGE'];
    $scope.cubePartitionTypes = ['APPEND', 'UPDATE_INSERT'];
    $scope.projects = [];
    $scope.newDimension = null;
    $scope.newMeasure = null;

    $scope.wizardSteps = [
        {title: 'Cube Info', src: 'partials/cubeDesigner/info.html', isComplete: false},
        {title: 'Data Model', src: 'partials/cubeDesigner/data_model.html', isComplete: false},
        {title: 'Dimensions', src: 'partials/cubeDesigner/dimensions.html', isComplete: false},
        {title: 'Measures', src: 'partials/cubeDesigner/measures.html', isComplete: false},
        {title: 'Filter', src: 'partials/cubeDesigner/filter.html', isComplete: false},
        {title: 'Refresh Setting', src: 'partials/cubeDesigner/incremental.html', isComplete: false}
    ];
    if (UserService.hasRole("ROLE_ADMIN")) {
            $scope.wizardSteps.push({title: 'Advanced Setting', src: 'partials/cubeDesigner/advanced_settings.html', isComplete: false});
    }
    $scope.wizardSteps.push({title: 'Overview', src: 'partials/cubeDesigner/overview.html', isComplete: false});

    $scope.curStep = $scope.wizardSteps[0];

    var Measure = {
        createNew: function () {
            var measure = {
                "id": "",
                "name": "",
                "function": {
                    "expression": "",
                    "returntype": "",
                    "parameter": {
                        "type": "",
                        "value": ""
                    }
                }
            };

            return measure;
        }
    };

    // ~ init
    if (!$scope.state) {
        $scope.state = {mode: "view"};
    }

    $scope.$watch('cube.detail', function (newValue, oldValue) {
        if (newValue) {
            $scope.cubeMetaFrame = newValue;
        }
    });

    $scope.$watch('cubeMetaFrame', function (newValue, oldValue) {
        if(!newValue){
            return;
        }
        if ($scope.cubeMode=="editExistCube"&&newValue && !newValue.project) {
            initProject();
        }
        //convert from UTC to local timezone
        //if($scope.cubeMetaFrame.cube_partition_desc.partition_date_start)
        //{
        //    $scope.cubeMetaFrame.cube_partition_desc.partition_date_start+=new Date().getTimezoneOffset()*60000;
        //}
    });

    // ~ public methods
    $scope.filterProj = function(project){
        return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project,$scope.permissions.ADMINISTRATION.mask);
    };

    $scope.addNewMeasure = function (measure) {
        $scope.newMeasure = (!!measure)? measure:Measure.createNew();
    };

    $scope.clearNewMeasure = function () {
        $scope.newMeasure = null;
    };

    $scope.saveNewMeasure = function () {
        if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
            $scope.cubeMetaFrame.measures.push($scope.newMeasure);
        }
        $scope.newMeasure = null;
    };

    $scope.addNewRowkeyColumn = function () {
        $scope.cubeMetaFrame.rowkey.rowkey_columns.push({
            "column": "",
            "length": 0,
            "dictionary": "true",
            "mandatory": false
        });
    };

    $scope.addNewAggregationGroup = function () {
        $scope.cubeMetaFrame.rowkey.aggregation_groups.push([]);
    };

    $scope.refreshAggregationGroup = function (list, index, aggregation_groups) {
        if (aggregation_groups) {
            list[index] = aggregation_groups;
        }
    };

    $scope.removeElement = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
        }
    };

    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };

    $scope.preView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex >= 1) {
            $scope.curStep.isComplete = false;
            $scope.curStep = $scope.wizardSteps[stepIndex - 1];
        }
    };

    $scope.nextView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex < ($scope.wizardSteps.length - 1)) {
            $scope.curStep.isComplete = true;
            $scope.curStep = $scope.wizardSteps[stepIndex + 1];

            AuthenticationService.ping(function (data) {
                UserService.setCurUser(data);
            });
        }
    };

    // ~ private methods
    function initProject() {
        ProjectService.list({}, function (projects) {
            $scope.projects = projects;

            var cubeName = (!!$scope.routeParams.cubeName)? $scope.routeParams.cubeName:$scope.state.cubeName;
            if (cubeName) {
                var projName = null;
                angular.forEach($scope.projects, function (project, index) {
                    angular.forEach(project.cubes, function (cube, index) {
                        if (!projName && cube === cubeName.toUpperCase()) {
                            projName = project.name;
                        }
                    });
                });

                $scope.cubeMetaFrame.project = projName;
            }

            angular.forEach($scope.projects, function (project, index) {
                $scope.listAccess(project, 'ProjectInstance');
            });
        });
    }
});
<|endoftext|>


<commit_before>var bodyParser = require('body-parser');
var cliHelper = require('./cliHelper');
var explorerClient = require('./elementExplorerClient');
var express = require('express');
var locatorFinder = require('./locatorFinder');

var startExpress = function() {
  var app = express();
  app.use(bodyParser.json());

  var encode = function(results) {
    return {results: results};
  };

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    if (query.locators) {
      return handleDevTools(query.locators, res);
    }

    res.send(encode({error: 'Invalid input'}));
  });

  function handlePopupRequest(input, res) {
    // If the popup input starts with 'by' then execute a count expression.
    if (/^by/.test(input)) {
      input = 'element.all(' + input + ').count()';
    }

    console.log('Popup input [%s]', input);

    explorerClient.runCommand(input).then(function(response) {
      var results = {};
      results[input] = response;

      res.send(encode(results));
    });
  }

  function handleDevTools(devtoolsInput, res) {
    var locatorResults = {},
        locators = JSON.parse(devtoolsInput),
        suggestionList = locatorFinder.buildLocatorList(locators);

    console.log('Testing suggestions', suggestionList);

    function testNext(index) {
      // Is it done testing locators?
      if (index === suggestionList.length) {
        console.log('Done testing suggestions, returning', locatorResults);
        return res.send(encode(locatorResults));
      }

      var suggestion = suggestionList[index],
          input = suggestion.countExpression;
      explorerClient.runCommand(input).then(function(response) {
        locatorResults[suggestion.locator] = response;
        testNext(index + 1);
      });
    }
    testNext(0);
  }

  var server = app.listen(13000, function() {
    console.log('Elementor is listening on http://localhost:%s',
        server.address().port);
  });
};

/** Start protractor process, then start the elementor server. */
var start = function() {
  cliHelper.startProtractor().then(function() {
    console.log('Done starting protractor');
    startExpress();
  });
};

module.exports = {
  start: start
};
<commit_msg>Go to a URL when you pass an argument to elementor<commit_after>var bodyParser = require('body-parser');
var cliHelper = require('./cliHelper');
var explorerClient = require('./elementExplorerClient');
var express = require('express');
var locatorFinder = require('./locatorFinder');

var startExpress = function(options) {
  var app = express();
  app.use(bodyParser.json());

  var encode = function(results) {
    return {results: results};
  };

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    if (query.locators) {
      return handleDevTools(query.locators, res);
    }

    res.send(encode({error: 'Invalid input'}));
  });

  function handlePopupRequest(input, res) {
    // If the popup input starts with 'by' then execute a count expression.
    if (/^by/.test(input)) {
      input = 'element.all(' + input + ').count()';
    }

    console.log('Popup input [%s]', input);

    explorerClient.runCommand(input).then(function(response) {
      var results = {};
      results[input] = response;

      res.send(encode(results));
    });
  }

  function handleDevTools(devtoolsInput, res) {
    var locatorResults = {},
        locators = JSON.parse(devtoolsInput),
        suggestionList = locatorFinder.buildLocatorList(locators);

    console.log('Testing suggestions', suggestionList);

    function testNext(index) {
      // Is it done testing locators?
      if (index === suggestionList.length) {
        console.log('Done testing suggestions, returning', locatorResults);
        return res.send(encode(locatorResults));
      }

      var suggestion = suggestionList[index],
          input = suggestion.countExpression;
      explorerClient.runCommand(input).then(function(response) {
        locatorResults[suggestion.locator] = response;
        testNext(index + 1);
      });
    }
    testNext(0);
  }

  var server = app.listen(13000, function() {
    console.log('Elementor is listening on http://localhost:%s',
        server.address().port);

    if (options.url) {
      // TODO: Improve the waiting code.
      setTimeout(function getUrl() {
        console.log('Getting page at:', options.url);
        var cmd = "browser.get('" + options.url + "')";
        explorerClient.runCommand(cmd).then(console.log);
      }, 1000);
    }
  });
};

/**
 * Start protractor process, then start the elementor server.
 */
var start = function(options) {
  cliHelper.startProtractor(options).then(function() {
    console.log('Done starting protractor');
    startExpress(options);
  });
};

module.exports = {
  start: start
};
<|endoftext|>


<commit_before>import useSearchFilter from "components/advancedSearch/hooks"
import PropTypes from "prop-types"
import React from "react"
import { Checkbox, FormGroup } from "react-bootstrap"
import { deserializeSearchFilter } from "searchUtils"

const CheckboxFilter = props => {
  const { asFormField, queryKey } = props
  const defaultValue = { value: true }
  const toQuery = val => {
    return { [queryKey]: val.value }
  }
  const [value, setValue] = useSearchFilter(props, defaultValue, toQuery) // eslint-disable-line no-unused-vars

  const msg = "Authorized for me"
  return !asFormField ? (
    <>{msg}</>
  ) : (
    <FormGroup>
      <Checkbox id={queryKey} readOnly checked={value.value}>
        {msg}
      </Checkbox>
    </FormGroup>
  )
}
CheckboxFilter.propTypes = {
  queryKey: PropTypes.string.isRequired,
  onChange: PropTypes.func, // eslint-disable-line react/no-unused-prop-types
  asFormField: PropTypes.bool
}
CheckboxFilter.defaultProps = {
  asFormField: true
}

export const deserializeCheckboxFilter = (props, query, key) => {
  return deserializeSearchFilter(props, query, key)
}

export default CheckboxFilter
<commit_msg>NCI-Agency/anet#2579: Fix LGTM alert about missing variable<commit_after>import useSearchFilter from "components/advancedSearch/hooks"
import PropTypes from "prop-types"
import React from "react"
import { Checkbox, FormGroup } from "react-bootstrap"
import { deserializeSearchFilter } from "searchUtils"

const CheckboxFilter = props => {
  const { asFormField, queryKey } = props
  const defaultValue = { value: true }
  const toQuery = val => {
    return { [queryKey]: val.value }
  }
  const value = useSearchFilter(props, defaultValue, toQuery)[0]

  const msg = "Authorized for me"
  return !asFormField ? (
    <>{msg}</>
  ) : (
    <FormGroup>
      <Checkbox id={queryKey} readOnly checked={value.value}>
        {msg}
      </Checkbox>
    </FormGroup>
  )
}
CheckboxFilter.propTypes = {
  queryKey: PropTypes.string.isRequired,
  onChange: PropTypes.func, // eslint-disable-line react/no-unused-prop-types
  asFormField: PropTypes.bool
}
CheckboxFilter.defaultProps = {
  asFormField: true
}

export const deserializeCheckboxFilter = (props, query, key) => {
  return deserializeSearchFilter(props, query, key)
}

export default CheckboxFilter
<|endoftext|>


<commit_before>var gulp = require('gulp'),
		gutil = require('gulp-util'),
		plugins = require('gulp-load-plugins')();

// https://github.com/ai/autoprefixer. Default: > 1%, last 2 versions, Firefox ESR, Opera 12.1
// Android, BlackBerry or bb, iOS
// Chrome, Firefox or ff, Explorer or ie, Opera, Safari
//
// last 2 versions, last 2 Chrome versions, > 5%, ff > 20, ff >= 20, Firefox ESR, none
// Blackberry and stock Android browsers will not be used in last n versions. Add them by name:
// autoprefixer("last 1 version", "BlackBerry 10", "Android 4")
var AutoPrefixerConfig = ['last 2 version', '> 5%', 'ie >= 9', 'ios 6', 'android 4'];

var path = require('path'),
		server = require('tiny-lr')(),
		compileAllSrc, // Compile all src if filename start with _, or single without leading _
		sassFilePath; // Used to dynamicially set sass path, default to all sass

// task: lint
gulp.task('lint', function() {
		gulp.src('gulpfile.js')
				.pipe(plugins.jshint())
				.pipe(plugins.jshint.reporter('default'));
});

// task: stripLRScript
// @describe    Strip out the LiveReload Script tag in HTML
gulp.task('stripLRScript', function() {
		return gulp.src(path.join(__dirname, 'index.html'))
				.pipe(plugins.replace(/\n'))
				.pipe(gulp.dest(path.join(__dirname, appName)));
});

gulp.task('clean', function() {
	return gulp.src('build', {read: false})
	  	.pipe(plugins.clean());
});

// Dependency Task
// Only run in the build process
// Based on the settings in framework/__init.sass, to output the RWD grid css
gulp.task('RWD_grid_builder', function() {
	return gulp.src( './static/styles/build/*.sass' )
		.pipe(plugins.rubySass({
				compass: false,
				sourcemap: false,
				debugInfo: false,
				lineNumbers: false
		}))
		.pipe(plugins.autoprefixer.apply( this, AutoPrefixerConfig ))
		.pipe(gulp.dest( path.join(__dirname, 'static/styles/build/') ));
});

gulp.task('build', ['RWD_grid_builder', 'clean'], function(cb) {
	var srcFIles = [
		'./__init.sass',
		'./_controller.sass',
		'./_css2.sass',
		'./_grid.sass',
		'./_utils.sass'
	];
	// the base option sets the relative root for the set of files,
	// preserving the folder structure
	gulp.src(srcFIles, { cwd: 'static/styles/sass/framework/**' } )
		.pipe(gulp.dest( path.join(__dirname, 'build/framework') ));

	gulp.src(['./static/styles/reset.css', './static/styles/build/*.css' ])
		.pipe( plugins.concat('reset.css') )
		.pipe(gulp.dest( path.join(__dirname, 'build') ));

	cb();
});

// Smart compile: if filename start with _, when save it will compile the whole project.
// if filename is all text without _, when save it will only compile changed file
gulp.task('sass', function() {
		// @TODO
		// global pattern should be with two stars, but currently it is generated twice for the base.sass file
		//  './static/styles/sass/{,**/}*.{scss,sass}',
		var allSrc = './static/styles/sass/{,*/}*.{scss,sass}',
				compileFiles = ( compileAllSrc ) ? allSrc : ( sassFilePath ) ? sassFilePath : allSrc,
				nestedFolder = void 0;

		// When it is single file for compiling, it needs to render it in the right folder path.
		// default it is   appName +'/resources/css',
		// If it is nested folder inside sass/path/to/compileFilename, it will alert the dest folder path
		if ( !compileAllSrc ) {
				var basepathArr = path.dirname(sassFilePath).split('/'),
						len = basepathArr.length,
						lastPos = len -1,
						sassPos = basepathArr.indexOf('sass');

				if ( len > sassPos ) {
						nestedFolder = '';
						var diff = lastPos - sassPos;
						for ( var i = 0 ; i < diff; i++ ) {
								var foldername = '/' + basepathArr[ lastPos - i ];
								nestedFolder = foldername.concat(nestedFolder);
						}
				}
		}
		var destPath = './static/styles' + ( ( nestedFolder ) ? nestedFolder : '' );

		return gulp.src( compileFiles )
				.pipe(plugins.rubySass({
						compass: true,
						sourcemap: true,
						debugInfo: false,
						lineNumbers: false
				}))
				.pipe(plugins.autoprefixer.apply( this, AutoPrefixerConfig ))
				.pipe(gulp.dest( destPath ))
				.pipe(plugins.notify({ message: 'Compiled <%= file.relative %>' }));
});

// https://github.com/sindresorhus/gulp-imagemin
// ~0.1.5 does not support stream yet. cannot resave to the same folder
gulp.task('imagemin', function() {
		var imgSrc = './static/images/{,**/}*.{png,jpeg,jpg,gif}',
				imgDst = './static/images/';

		return gulp.src(imgSrc)
				.pipe(plugins.changed(imgDst))
				.pipe(plugins.imagemin())
				.pipe(gulp.dest(imgDst));
});

// Notifies livereload of changes detected by `gulp.watch()`
function notifyLivereload(event) {
		// `gulp.watch()` events provide an absolute path
		//  make it relative path. Both relative and absolute should work
		var fileName = path.relative(__dirname, event.path);

		server.changed({
				body: {
						files: [fileName]
				}
		});
}

gulp.task('default', ['sass'], function() {
		gulp.watch('./static/styles/sass/{,**/}*.{scss,sass}', function(event) {
				sassFilePath = event.path; // Only pass changed file to the sass task
				var basename = path.basename(sassFilePath);
				compileAllSrc = ( basename.indexOf('_') > -1 ) ? true : false;
				gulp.start('sass');
		});

		server.listen(35729, function(err) {
				if (err) { return gutil.log('\n[-log]', gutil.colors.red(err)); }

				gulp.watch(appName + '/examples/refactor.html', notifyLivereload);
				gulp.watch(appName + '/resources/css/{,**/}*.css', notifyLivereload);
		});
});
<commit_msg>fix the linting problem in gulpfile.js<commit_after>var gulp = require('gulp'),
		gutil = require('gulp-util'),
		plugins = require('gulp-load-plugins')();

// https://github.com/ai/autoprefixer. Default: > 1%, last 2 versions, Firefox ESR, Opera 12.1
// Android, BlackBerry or bb, iOS
// Chrome, Firefox or ff, Explorer or ie, Opera, Safari
//
// last 2 versions, last 2 Chrome versions, > 5%, ff > 20, ff >= 20, Firefox ESR, none
// Blackberry and stock Android browsers will not be used in last n versions. Add them by name:
// autoprefixer("last 1 version", "BlackBerry 10", "Android 4")
var AutoPrefixerConfig = ['last 2 version', '> 5%', 'ie >= 9', 'ios 6', 'android 4'];

var path = require('path'),
		server = require('tiny-lr')(),
		compileAllSrc, // Compile all src if filename start with _, or single without leading _
		sassFilePath; // Used to dynamicially set sass path, default to all sass

// task: lint
gulp.task('lint', function() {
		gulp.src('gulpfile.js')
				.pipe(plugins.jshint())
				.pipe(plugins.jshint.reporter('default'));
});

// task: stripLRScript
// @describe    Strip out the LiveReload Script tag in HTML
gulp.task('stripLRScript', function() {
		return gulp.src(path.join(__dirname, 'index.html'))
				.pipe(plugins.replace(/\n'))
				.pipe(gulp.dest(path.join(__dirname, appName)));
});

gulp.task('clean', function() {
	return gulp.src('build', {read: false})
		.pipe(plugins.clean());
});

// Dependency Task
// Only run in the build process
// Based on the settings in framework/__init.sass, to output the RWD grid css
gulp.task('RWD_grid_builder', function() {
	return gulp.src( './static/styles/build/*.sass' )
		.pipe(plugins.rubySass({
				compass: false,
				sourcemap: false,
				debugInfo: false,
				lineNumbers: false
		}))
		.pipe(plugins.autoprefixer.apply( this, AutoPrefixerConfig ))
		.pipe(gulp.dest( path.join(__dirname, 'static/styles/build/') ));
});

gulp.task('build', ['RWD_grid_builder', 'clean'], function(cb) {
	var srcFIles = [
		'./__init.sass',
		'./_controller.sass',
		'./_css2.sass',
		'./_grid.sass',
		'./_utils.sass'
	];
	// the base option sets the relative root for the set of files,
	// preserving the folder structure
	gulp.src(srcFIles, { cwd: 'static/styles/sass/framework/**' } )
		.pipe(gulp.dest( path.join(__dirname, 'build/framework') ));

	gulp.src(['./static/styles/reset.css', './static/styles/build/*.css' ])
		.pipe( plugins.concat('reset.css') )
		.pipe(gulp.dest( path.join(__dirname, 'build') ));

	cb();
});

// Smart compile: if filename start with _, when save it will compile the whole project.
// if filename is all text without _, when save it will only compile changed file
gulp.task('sass', function() {
		// @TODO
		// global pattern should be with two stars, but currently it is generated twice for the base.sass file
		//  './static/styles/sass/{,**/}*.{scss,sass}',
		var allSrc = './static/styles/sass/{,*/}*.{scss,sass}',
				compileFiles = ( compileAllSrc ) ? allSrc : ( sassFilePath ) ? sassFilePath : allSrc,
				nestedFolder = void 0;

		// When it is single file for compiling, it needs to render it in the right folder path.
		// default it is   appName +'/resources/css',
		// If it is nested folder inside sass/path/to/compileFilename, it will alert the dest folder path
		if ( !compileAllSrc ) {
				var basepathArr = path.dirname(sassFilePath).split('/'),
						len = basepathArr.length,
						lastPos = len -1,
						sassPos = basepathArr.indexOf('sass');

				if ( len > sassPos ) {
						nestedFolder = '';
						var diff = lastPos - sassPos;
						for ( var i = 0 ; i < diff; i++ ) {
								var foldername = '/' + basepathArr[ lastPos - i ];
								nestedFolder = foldername.concat(nestedFolder);
						}
				}
		}
		var destPath = './static/styles' + ( ( nestedFolder ) ? nestedFolder : '' );

		return gulp.src( compileFiles )
				.pipe(plugins.rubySass({
						compass: true,
						sourcemap: true,
						debugInfo: false,
						lineNumbers: false
				}))
				.pipe(plugins.autoprefixer.apply( this, AutoPrefixerConfig ))
				.pipe(gulp.dest( destPath ))
				.pipe(plugins.notify({ message: 'Compiled <%= file.relative %>' }));
});

// https://github.com/sindresorhus/gulp-imagemin
// ~0.1.5 does not support stream yet. cannot resave to the same folder
gulp.task('imagemin', function() {
		var imgSrc = './static/images/{,**/}*.{png,jpeg,jpg,gif}',
				imgDst = './static/images/';

		return gulp.src(imgSrc)
				.pipe(plugins.changed(imgDst))
				.pipe(plugins.imagemin())
				.pipe(gulp.dest(imgDst));
});

// Notifies livereload of changes detected by `gulp.watch()`
function notifyLivereload(event) {
		// `gulp.watch()` events provide an absolute path
		//  make it relative path. Both relative and absolute should work
		var fileName = path.relative(__dirname, event.path);

		server.changed({
				body: {
						files: [fileName]
				}
		});
}

gulp.task('default', ['sass'], function() {
		gulp.watch('./static/styles/sass/{,**/}*.{scss,sass}', function(event) {
				sassFilePath = event.path; // Only pass changed file to the sass task
				var basename = path.basename(sassFilePath);
				compileAllSrc = ( basename.indexOf('_') > -1 ) ? true : false;
				gulp.start('sass');
		});

		server.listen(35729, function(err) {
				if (err) { return gutil.log('\n[-log]', gutil.colors.red(err)); }

				gulp.watch(appName + '/examples/refactor.html', notifyLivereload);
				gulp.watch(appName + '/resources/css/{,**/}*.css', notifyLivereload);
		});
});
<|endoftext|>


<commit_before>"use strict";
/*global require*/
var _                = require("lodash");
var del              = require("del");
var path             = require("path");
var runSequence      = require("run-sequence");

var gulp             = require("gulp");
var harmonize        = require("harmonize");
var awspublish       = require("gulp-awspublish");
var rename           = require("gulp-rename");
var parallelize      = require("concurrent-transform");
var gutil            = require("gulp-util");
var deploy           = require("gulp-gh-pages");
var notifier         = require("node-notifier");
var merge            = require('merge-stream');

var ngrok            = require('ngrok');
var webpack          = require("webpack");
var WebpackDevServer = require("webpack-dev-server");

// Get our Config.
var config           = require("./config");
var webpackConfig    = require("./webpack.config");

harmonize();

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp",message:message});
};

// Setup a Ngrok server
var ngrokServe = function(subdomain){
  var options = { port: config.serverPort };
  var env = process.env;
  if (env.NGROK_AUTHTOKEN) {
    options.authtoken = env.NGROK_AUTHTOKEN;
  }
  if(env.NGROK_SUBDOMAIN || subdomain){
    options.subdomain = (env.NGROK_SUBDOMAIN || subdomain).replace(/-/g,'');
  }
  ngrok.connect(options, function (error, url) {
    if (error) {
      throw new gutil.PluginError('ship:server', error);
    }

    url = url.replace('https', 'http');
    notify({message:"Ngrok Started on "+url});

    gutil.log('[ship:server]', url);
  });
}

gulp.task("default", ["server"]);
gulp.task("serve",   ["server"]);
gulp.task("clean",   function(callback) {del(["./"+config.outputFolder+"/**/*"], callback); });

gulp.task("server",  function(callback) {runSequence("clean", "copy-files:watch", "webpack:server", callback); });
gulp.task("build",   function(callback) {runSequence("clean", "copy-files", "webpack:build", callback); });
gulp.task("deploy",  function(callback) {runSequence("build", "publish:sha", callback); });
gulp.task("deploy:release",  function(callback) {runSequence("build", "publish:release", callback); });

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp", message: message});
};
var handleError = function(err, taskName){
  if(err){
    notify(taskName+" Error: "+ err);
    throw new gutil.PluginError("webpack:build", err);
  }
};
// Copy static files from the source to the destination
var copyFiles = function(callback){
  _.map(config.files, function(dest, src){
    gulp.src(src).pipe(gulp.dest(dest));
  });
  notify("Vendors Updated");
  if (_.isFunction(callback)){
    callback();
  }
};

gulp.task("copy-files", copyFiles);

gulp.task("copy-files:watch", function(){
  copyFiles();
  gulp.watch(_.keys(config.files), copyFiles);
});

//Production Build.
//Minified, clean code. No demo keys inside.
//demo.html WILL NOT WORK with this build.
//
//Webpack handles CSS/SCSS, JS, and HTML files.
var afterBuild = function(err, stats){
  if (!!err) {throw new gutil.PluginError("webpack:build", err); }

  var jsonStats = stats.toJson();

  if (jsonStats.errors.length > 0) {
    return new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.errors));
  }

  if (jsonStats.warnings.length > 0) {
    new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.warnings));
  }

  gutil.log("[webpack:build]", stats.toString({colors: true}));
  notify("App Built");
};
gulp.task("webpack:build", function(callback) {
  // Then, use Webpack to bundle all JS and html files to the destination folder
  notify("Building App");
  webpack(_.values(webpackConfig.production), function(err, stats) {
    afterBuild(err, stats);
    webpack(_.values(webpackConfig.debug), function(err, stats){
      afterBuild(err, stats);
      callback();
    });
  });
});

// Dev Build
// Create the webpack compiler here for caching and performance.
var devCompiler = webpack(webpackConfig.development.browser);

// Build a Dev version of the project. Launched once on startup so we can have eveything copied.
gulp.task("webpack:build:dev", function(callback) {
  // run webpack with Dev profile.
  // Embeds the Hull config keys, and the necessary stuff to make demo.html work
  devCompiler.run(function(err, stats) {
    if (err){
      throw new gutil.PluginError("webpack:build:dev", err);
    }

    var jsonStats = stats.toJson();

    if(jsonStats.errors.length > 0){
      return new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.errors));
    }

    if(jsonStats.warnings.length > 0){
      new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.warnings));
    }

    gutil.log("[webpack:build:dev]", stats.toString({colors: true}));
    notify({message: "Webpack Updated"});
    callback();
  });
});

// Launch webpack dev server.
gulp.task("webpack:server", function() {
  var taskName = "webpack:server";
  new WebpackDevServer(devCompiler, {
    contentBase: config.outputFolder,
    publicPath: config.assetsFolder+"/",
    hot: config.hotReload,
    stats: {colors: true }
  }).listen(config.serverPort, function(err) {
    handleError(err, taskName);
    // Dump the preview URL in the console, and open Chrome when launched for convenience.
    notify({message: "Dev Server Started"});
    var url = webpackConfig.development.browser.output.publicPath+"webpack-dev-server/";
    ngrokServe(config.libName)
    gutil.log("["+taskName+"]", url);
  });
});

var publish = function(versions){
  var aws = config.aws
  var publisher = awspublish.create(aws.config);
  var files  = path.join(config.outputFolder, config.assetsFolder, "*")
  var streams = [];
  for (var i = 0; i < versions.length; i++) {
    var version = versions[i];
    if(version){
      console.log('Deploying to ',version);
      var plain = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      var gzip = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      .pipe(awspublish.gzip(aws.gzip))

      streams.push(plain);
      streams.push(gzip);
    }
  };
  return merge.apply(merge,streams)
  .pipe(parallelize(publisher.publish(aws.publish.headers,aws.publish.options)))
  .pipe(publisher.cache())
  .pipe(awspublish.reporter())
;
}

// Deploys to S3
gulp.task('publish:sha',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  if( !SHA1 ){ return; }
  return publish([SHA1]);
});

gulp.task('publish:release',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  var RELEASE = config.pkg.version;
  if( !SHA1 || !RELEASE ){ return; }
  return publish([SHA1,RELEASE]);
});
<commit_msg>use ngrok subdomain only if NGROK_AUTHTOKEN is set<commit_after>"use strict";
/*global require*/
var _                = require("lodash");
var del              = require("del");
var path             = require("path");
var runSequence      = require("run-sequence");

var gulp             = require("gulp");
var harmonize        = require("harmonize");
var awspublish       = require("gulp-awspublish");
var rename           = require("gulp-rename");
var parallelize      = require("concurrent-transform");
var gutil            = require("gulp-util");
var deploy           = require("gulp-gh-pages");
var notifier         = require("node-notifier");
var merge            = require('merge-stream');

var ngrok            = require('ngrok');
var webpack          = require("webpack");
var WebpackDevServer = require("webpack-dev-server");

// Get our Config.
var config           = require("./config");
var webpackConfig    = require("./webpack.config");

harmonize();

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp",message:message});
};

// Setup a Ngrok server
var ngrokServe = function(subdomain){
  var options = { port: config.serverPort };
  var env = process.env;
  if (env.NGROK_AUTHTOKEN) {
    options.authtoken = env.NGROK_AUTHTOKEN;

    if(env.NGROK_SUBDOMAIN || subdomain){
      options.subdomain = (env.NGROK_SUBDOMAIN || subdomain).replace(/-/g,'');
    }
  }
  ngrok.connect(options, function (error, url) {
    if (error) {
      throw new gutil.PluginError('ship:server', error);
    }

    url = url.replace('https', 'http');
    notify({message:"Ngrok Started on "+url});

    gutil.log('[ship:server]', url);
  });
}

gulp.task("default", ["server"]);
gulp.task("serve",   ["server"]);
gulp.task("clean",   function(callback) {del(["./"+config.outputFolder+"/**/*"], callback); });

gulp.task("server",  function(callback) {runSequence("clean", "copy-files:watch", "webpack:server", callback); });
gulp.task("build",   function(callback) {runSequence("clean", "copy-files", "webpack:build", callback); });
gulp.task("deploy",  function(callback) {runSequence("build", "publish:sha", callback); });
gulp.task("deploy:release",  function(callback) {runSequence("build", "publish:release", callback); });

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp", message: message});
};
var handleError = function(err, taskName){
  if(err){
    notify(taskName+" Error: "+ err);
    throw new gutil.PluginError("webpack:build", err);
  }
};
// Copy static files from the source to the destination
var copyFiles = function(callback){
  _.map(config.files, function(dest, src){
    gulp.src(src).pipe(gulp.dest(dest));
  });
  notify("Vendors Updated");
  if (_.isFunction(callback)){
    callback();
  }
};

gulp.task("copy-files", copyFiles);

gulp.task("copy-files:watch", function(){
  copyFiles();
  gulp.watch(_.keys(config.files), copyFiles);
});

//Production Build.
//Minified, clean code. No demo keys inside.
//demo.html WILL NOT WORK with this build.
//
//Webpack handles CSS/SCSS, JS, and HTML files.
var afterBuild = function(err, stats){
  if (!!err) {throw new gutil.PluginError("webpack:build", err); }

  var jsonStats = stats.toJson();

  if (jsonStats.errors.length > 0) {
    return new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.errors));
  }

  if (jsonStats.warnings.length > 0) {
    new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.warnings));
  }

  gutil.log("[webpack:build]", stats.toString({colors: true}));
  notify("App Built");
};
gulp.task("webpack:build", function(callback) {
  // Then, use Webpack to bundle all JS and html files to the destination folder
  notify("Building App");
  webpack(_.values(webpackConfig.production), function(err, stats) {
    afterBuild(err, stats);
    webpack(_.values(webpackConfig.debug), function(err, stats){
      afterBuild(err, stats);
      callback();
    });
  });
});

// Dev Build
// Create the webpack compiler here for caching and performance.
var devCompiler = webpack(webpackConfig.development.browser);

// Build a Dev version of the project. Launched once on startup so we can have eveything copied.
gulp.task("webpack:build:dev", function(callback) {
  // run webpack with Dev profile.
  // Embeds the Hull config keys, and the necessary stuff to make demo.html work
  devCompiler.run(function(err, stats) {
    if (err){
      throw new gutil.PluginError("webpack:build:dev", err);
    }

    var jsonStats = stats.toJson();

    if(jsonStats.errors.length > 0){
      return new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.errors));
    }

    if(jsonStats.warnings.length > 0){
      new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.warnings));
    }

    gutil.log("[webpack:build:dev]", stats.toString({colors: true}));
    notify({message: "Webpack Updated"});
    callback();
  });
});

// Launch webpack dev server.
gulp.task("webpack:server", function() {
  var taskName = "webpack:server";
  new WebpackDevServer(devCompiler, {
    contentBase: config.outputFolder,
    publicPath: config.assetsFolder+"/",
    hot: config.hotReload,
    stats: {colors: true }
  }).listen(config.serverPort, function(err) {
    handleError(err, taskName);
    // Dump the preview URL in the console, and open Chrome when launched for convenience.
    notify({message: "Dev Server Started"});
    var url = webpackConfig.development.browser.output.publicPath+"webpack-dev-server/";
    ngrokServe(config.libName)
    gutil.log("["+taskName+"]", url);
  });
});

var publish = function(versions){
  var aws = config.aws
  var publisher = awspublish.create(aws.config);
  var files  = path.join(config.outputFolder, config.assetsFolder, "*")
  var streams = [];
  for (var i = 0; i < versions.length; i++) {
    var version = versions[i];
    if(version){
      console.log('Deploying to ',version);
      var plain = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      var gzip = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      .pipe(awspublish.gzip(aws.gzip))

      streams.push(plain);
      streams.push(gzip);
    }
  };
  return merge.apply(merge,streams)
  .pipe(parallelize(publisher.publish(aws.publish.headers,aws.publish.options)))
  .pipe(publisher.cache())
  .pipe(awspublish.reporter())
;
}

// Deploys to S3
gulp.task('publish:sha',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  if( !SHA1 ){ return; }
  return publish([SHA1]);
});

gulp.task('publish:release',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  var RELEASE = config.pkg.version;
  if( !SHA1 || !RELEASE ){ return; }
  return publish([SHA1,RELEASE]);
});
<|endoftext|>


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

    var Router = express.Router();
    var _ = require('lodash');
    var Promise = require('bluebird');
    var mv = Promise.promisify(require('mv'));
    var UploadRoot = __dirname + '/../../uploads/';

    // DECLARATION

    // Creates layout
    // uses req.body.params.layout for new layout
    Router.post('/', postLayouts);
    Router.post('/search/name/:name', postSearchByName);

    // Posts comment to given layout
    Router.post('/comment/:id', postCommentById);

    Router.get('/', getLayouts);
    Router.get('/:id', getLayoutsById);

    // Updates layout
    // uses req.body.params.setObject to update and
    // req.body.params.unsetArray to remove db record values
    Router.put('/:id', putLayoutsById);
    // Adds rating of current user and updated average to layout
    Router.put('/:id/rating/:value', putLayoutsByIdRatingByValue);
    // Deletes rating of current user in selected layout
    Router.delete('/:id/rating', deleteLayoutsByIdRating);

    Router.delete('/:id', deleteLayoutsById); // only marks layout as deleted
    Router.delete('/:id/completely', getLayoutsByIdCompletely);

    return Router;

    // IMPLEMENTATION

    function getLayouts(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var sel, findObj = {}, tmpArr = [], tmpDateQueryObj = {};

        if (req.query.selection) {
            sel = JSON.parse(req.query.selection);

            if (sel.colors && sel.colors.length > 0) {
                tmpArr.push({catColors: {$in: sel.colors}});
            }

            if (sel.assortment && sel.assortment.length > 0) {
                tmpArr.push({catAssortment: {$in: sel.assortment}});
            }

            if (sel.countries && sel.countries.length > 0) {
                tmpArr.push({catCountries: {$in: sel.countries}});
            }

            if (sel.plots && sel.plots.length > 0) {
                tmpArr.push({catPlots: {$in: sel.plots}});
            }

            if (sel.authors && sel.authors.length > 0) {
                tmpArr.push({createdBy: {$in: sel.authors}});
            }

            if (sel.startDate || sel.endDate) {
                if (sel.startDate) {
                    tmpDateQueryObj.$gte = sel.startDate;
                }
                if (sel.endDate) {
                    tmpDateQueryObj.$lt = sel.endDate;
                }
                tmpArr.push({createdAt: tmpDateQueryObj});
            }

            if (tmpArr.length > 0) {
                findObj = {$and: tmpArr};
            }

        }

        Layout
            .find(findObj, '')
            .then(function (layouts) {
                return res.json(layouts);
            })
            .catch(function (err) {
                console.log('Cant\'t find layouts: ', err);
                return res.sendStatus(500);
            });

    }

    function deleteLayoutsById(req, res) {
        if (!req.isAuthenticated()
            || _.contains(['admin', 'designer', 'founder', 'curator'], req.user.role)) {
            return res.sendStatus(403);
        }

        Layout
            .findOne({'_id': req.params.id})
            .then(function (layout) {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }
                layout.isHidden = true;
                layout.save();
                return res.sendStatus(204);
            })
            .catch(function (err) {
                console.log('Error removing layout: ', err);
                return res.sendStatus(err.status || 500);
            });
    }

    function getLayoutsByIdCompletely(req, res) {
        if (!req.isAuthenticated()
            || !_.contains(['admin'], req.user.role)) {
            return res.sendStatus(403);
        }

        Layout
            .findOneAndRemove({'_id': req.params.id})
            .then(function () {
                return data
                    ? res.sendStatus(204)
                    : res.sendStatus(404);
            })
            .catch(function () {
                console.log('Error removing layout: ', err);
                return res.sendStatus(500);
            });
    }

    function getLayoutsById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findById({_id: req.params.id}, '-_id')
            .then(function (layout) {
                return layout
                    ? res.json(layout)
                    : res.sendStatus(404);
            })
            .catch(function (err) {
                console.log(err);
                return res.sendStatus(500);
            });
    }

    function postLayouts(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var layoutData = JSON.parse(req.body.data);
        layoutData.createdBy = req.user.username;

        Layout
            .create(layoutData)
            .then(function () {
                return res.sendStatus(201);
            })
            .catch(function (err) {
                console.log('Error creating layout: ', err);
                return res.sendStatus(500);
            });
    }

    function putLayoutsById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var setObject = req.body.params.setObject;
        var unsetArray = req.body.params.unsetArray;
        if (!setObject && !unsetArray) {
            return res.status(400);
        }

        Layout
            .findById(req.params.id)
            .then(function (layout) {
                if (setObject.status === 'assigned' && !layout.reference) {
                    console.log("I need to make ref query");
                    var referenceQuery = Layout
                        .find({}, "-_id reference")
                        .exists("reference")
                        .sort("-reference")
                        .limit(1)
                        .exec();

                    return referenceQuery
                        .then(function (result) {
                            if (result.length === 0) {
                                layout.reference = 1;
                            } else {
                                layout.reference = result[0].reference + 1;
                            }

                            var refDir = _.padLeft(layout.reference, 5, '0');
                            var fromDir = UploadRoot + 'pictures/' + layout.urlDir + '/';
                            var toDir = UploadRoot + 'ready/' + refDir + '/';

                            return mv(fromDir + layout.urlThumb, toDir + layout.urlThumb, {mkdirp: true})
                                .then(function () {
                                    console.log('moved thumb');
                                    return mv(fromDir + layout.url2d, toDir + layout.url2d, {mkdirp: true});
                                })
                                .then(function () {
                                    console.log('moved url');
                                    layout.urlDir = refDir;
                                    return layout;
                                }).catch(function (err) {
                                    err.status = 500;
                                    throw err;
                                });
                        });

                } else {
                    return layout;
                }
            })
            .then(function (layout) {
                _.each(setObject, function (value, key) {
                    if (key !== 'reference') {
                        layout[key] = value;
                    }
                });

                _.each(unsetArray, function (key) {
                    layout[key] = undefined;
                });

                return layout.save();
            })
            .then(function(layout){
                return res.status(200).json({status: 'success', layout: layout});
            })
            .catch(function (err) {
                console.log('Макет не найден! ' + err);
                return res.status(err.status || 404);
            });
    }

    function putLayoutsByIdRatingByValue(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findById({'_id': req.params.id})
            .then(function (layout) {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }

                var idx = _.findIndex(layout.ratings, {assignedBy: req.user.username});

                if (idx > -1) {
                    layout.ratings[idx].value = req.params.value;
                } else {
                    layout.ratings.push({value: req.params.value, assignedBy: req.user.username});
                }

                return layout.save();
            })
            .then(function () {
                return res.sendStatus(200);
            })
            .catch(function (err) {
                console.log("Error adding new rating", err);
                return res.sendStatus(err.status || 500);
            });
    }

    function deleteLayoutsByIdRating(req, res) {
        if (!req.isAuthenticated()) {
            res.sendStatus(403);
        }

        Layout
            .findById({'_id': req.params.id})
            .then(function (layout) {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }

                var idx = _.findIndex(layout.ratings, {assignedBy: req.user.username});

                if (idx > -1) {
                    layout.ratings.splice(idx, 1);
                }

                return layout.save();
            })
            .then(function () {
                return res.sendStatus(204);
            })
            .catch(function (err) {
                console.log("Error removing rating", err);
                return res.sendStatus(err.status || 500);
            });
    }

    function postSearchByName(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findOne({name: req.params.name}, '-_id')
            .then(function (layout) {
                return layout
                    ? res.sendStatus(200)
                    : res.sendStatus(204);
            })
            .catch(function () {
                return res.sendStatus(500);
            });
    }

    function postCommentById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var validQuery = req.body.params
            && req.body.params.postedBy
            && req.body.params.postedAt
            && req.body.params.text;

        if (!validQuery) {
            res.sendStatus(400);
        }

        Layout
            .findById(req.params.id)
            .then(function (layout) {
                layout.comments.push(req.body.params);
                return layout.save();
            })
            .then(function(){
                return res.sendStatus(200);
            })
            .catch(function (err) {
                console.log('Error posting comment: ', err);
                return res.sendStatus(500);
            });
    }

};
<commit_msg>babelize layout route<commit_after>module.exports = function (express, Layout) {
    'use strict';

    var Router = express.Router();
    var _ = require('lodash');
    var Promise = require('bluebird');
    var mv = Promise.promisify(require('mv'));
    var UploadRoot = __dirname + '/../../uploads/';

    // DECLARATION

    // Creates layout
    // uses req.body.params.layout for new layout
    Router.post('/', postLayouts);
    Router.post('/search/name/:name', postSearchByName);

    // Posts comment to given layout
    Router.post('/comment/:id', postCommentById);

    Router.get('/', getLayouts);
    Router.get('/:id', getLayoutsById);

    // Updates layout
    // uses req.body.params.setObject to update and
    // req.body.params.unsetArray to remove db record values
    Router.put('/:id', putLayoutsById);
    // Adds rating of current user and updated average to layout
    Router.put('/:id/rating/:value', putLayoutsByIdRatingByValue);
    // Deletes rating of current user in selected layout
    Router.delete('/:id/rating', deleteLayoutsByIdRating);

    Router.delete('/:id', deleteLayoutsById); // only marks layout as deleted
    Router.delete('/:id/completely', getLayoutsByIdCompletely);

    return Router;

    // IMPLEMENTATION

    function getLayouts(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var sel, findObj = {}, tmpArr = [], tmpDateQueryObj = {};

        if (req.query.selection) {
            sel = JSON.parse(req.query.selection);

            if (sel.colors && sel.colors.length > 0) {
                tmpArr.push({catColors: {$in: sel.colors}});
            }

            if (sel.assortment && sel.assortment.length > 0) {
                tmpArr.push({catAssortment: {$in: sel.assortment}});
            }

            if (sel.countries && sel.countries.length > 0) {
                tmpArr.push({catCountries: {$in: sel.countries}});
            }

            if (sel.plots && sel.plots.length > 0) {
                tmpArr.push({catPlots: {$in: sel.plots}});
            }

            if (sel.authors && sel.authors.length > 0) {
                tmpArr.push({createdBy: {$in: sel.authors}});
            }

            if (sel.startDate || sel.endDate) {
                if (sel.startDate) {
                    tmpDateQueryObj.$gte = sel.startDate;
                }
                if (sel.endDate) {
                    tmpDateQueryObj.$lt = sel.endDate;
                }
                tmpArr.push({createdAt: tmpDateQueryObj});
            }

            if (tmpArr.length > 0) {
                findObj = {$and: tmpArr};
            }

        }

        Layout
            .find(findObj, '')
            .then((layouts)=> res.json(layouts))
            .catch((err)=> {
                console.log('Cant\'t find layouts: ', err);
                return res.sendStatus(500);
            });

    }

    function deleteLayoutsById(req, res) {
        if (!req.isAuthenticated()
            || _.contains(['admin', 'designer', 'founder', 'curator'], req.user.role)) {
            return res.sendStatus(403);
        }

        Layout
            .findOne({'_id': req.params.id})
            .then((layout)=> {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }
                layout.isHidden = true;
                layout.save();
                return res.sendStatus(204);
            })
            .catch((err)=> {
                console.log('Error removing layout: ', err);
                return res.sendStatus(err.status || 500);
            });
    }

    function getLayoutsByIdCompletely(req, res) {
        if (!req.isAuthenticated()
            || !_.contains(['admin'], req.user.role)) {
            return res.sendStatus(403);
        }

        Layout
            .findOneAndRemove({'_id': req.params.id})
            .then(()=> data
                ? res.sendStatus(204)
                : res.sendStatus(404))
            .catch((err)=> {
                console.log('Error removing layout: ', err);
                return res.sendStatus(500);
            });
    }

    function getLayoutsById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findById({_id: req.params.id}, '-_id')
            .then(function (layout) {
                return layout
                    ? res.json(layout)
                    : res.sendStatus(404);
            })
            .catch(function (err) {
                console.log(err);
                return res.sendStatus(500);
            });
    }

    function postLayouts(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var layoutData = JSON.parse(req.body.data);
        layoutData.createdBy = req.user.username;

        Layout
            .create(layoutData)
            .then(()=>res.sendStatus(201))
            .catch((err)=> {
                console.log('Error creating layout: ', err);
                return res.sendStatus(500);
            });
    }

    function putLayoutsById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var setObject = req.body.params.setObject;
        var unsetArray = req.body.params.unsetArray;
        if (!setObject && !unsetArray) {
            return res.status(400);
        }

        Layout
            .findById(req.params.id)
            .then((layout)=> {
                if (setObject.status === 'assigned' && !layout.reference) {
                    console.log("I need to make ref query");
                    var referenceQuery = Layout
                        .find({}, "-_id reference")
                        .exists("reference")
                        .sort("-reference")
                        .limit(1)
                        .exec();

                    return referenceQuery
                        .then(function (result) {
                            if (result.length === 0) {
                                layout.reference = 1;
                            } else {
                                layout.reference = result[0].reference + 1;
                            }

                            var refDir = _.padLeft(layout.reference, 5, '0');
                            var fromDir = UploadRoot + 'pictures/' + layout.urlDir + '/';
                            var toDir = UploadRoot + 'ready/' + refDir + '/';

                            return mv(fromDir + layout.urlThumb, toDir + layout.urlThumb, {mkdirp: true})
                                .then(function () {
                                    console.log('moved thumb');
                                    return mv(fromDir + layout.url2d, toDir + layout.url2d, {mkdirp: true});
                                })
                                .then(function () {
                                    console.log('moved url');
                                    layout.urlDir = refDir;
                                    return layout;
                                }).catch(function (err) {
                                    err.status = 500;
                                    throw err;
                                });
                        });

                } else {
                    return layout;
                }
            })
            .then((layout)=> {
                _.each(setObject, (value, key)=> {
                    if (key !== 'reference') {
                        layout[key] = value;
                    }
                });

                _.each(unsetArray, (key)=> layout[key] = undefined);

                return layout.save();
            })
            .then((layout)=>res.status(200).json({status: 'success', layout: layout}))
            .catch((err)=> {
                console.log('Макет не найден! ' + err);
                return res.status(err.status || 404);
            });
    }

    function putLayoutsByIdRatingByValue(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findById({'_id': req.params.id})
            .then((layout)=> {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }

                var idx = _.findIndex(layout.ratings, {assignedBy: req.user.username});

                if (idx > -1) {
                    layout.ratings[idx].value = req.params.value;
                } else {
                    layout.ratings.push({value: req.params.value, assignedBy: req.user.username});
                }

                return layout.save();
            })
            .then(()=> res.sendStatus(200))
            .catch((err)=> {
                console.log("Error adding new rating", err);
                return res.sendStatus(err.status || 500);
            });
    }

    function deleteLayoutsByIdRating(req, res) {
        if (!req.isAuthenticated()) {
            res.sendStatus(403);
        }

        Layout
            .findById({'_id': req.params.id})
            .then((layout)=> {
                if (!layout) {
                    var err = new Error();
                    err.status = 404;
                    throw err;
                }

                var idx = _.findIndex(layout.ratings, {assignedBy: req.user.username});

                if (idx > -1) {
                    layout.ratings.splice(idx, 1);
                }

                return layout.save();
            })
            .then(()=> res.sendStatus(204))
            .catch((err)=> {
                console.log("Error removing rating", err);
                return res.sendStatus(err.status || 500);
            });
    }

    function postSearchByName(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        Layout
            .findOne({name: req.params.name}, '-_id')
            .then((layout)=> layout
                    ? res.sendStatus(200)
                    : res.sendStatus(204))
            .catch((err)=> {
                console.log("Error searching layout: ", err);
                return res.sendStatus(500);
            });
    }

    function postCommentById(req, res) {
        if (!req.isAuthenticated()) {
            return res.sendStatus(403);
        }

        var validQuery = req.body.params
            && req.body.params.postedBy
            && req.body.params.postedAt
            && req.body.params.text;

        if (!validQuery) {
            res.sendStatus(400);
        }

        Layout
            .findById(req.params.id)
            .then((layout)=> {
                layout.comments.push(req.body.params);
                return layout.save();
            })
            .then(()=> res.sendStatus(200))
            .catch((err)=> {
                console.log('Error posting comment: ', err);
                return res.sendStatus(500);
            });
    }

};
<|endoftext|>