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

    angular
        .module(HygieiaConfig.module)
        .controller('performanceViewController', performanceViewController);

    performanceViewController.$inject = ['$q', '$scope','performanceData', '$modal', 'collectorData'];
    function performanceViewController($q, $scope, performanceData, $modal, collectorData) {
        var ctrl = this;

        ctrl.genericChartOptions = {
          plugins: [
            Chartist.plugins.gridBoundaries(),
            Chartist.plugins.lineAboveArea(),
            Chartist.plugins.pointHalo(),
            Chartist.plugins.ctPointClick({
              //TODO
            }),
            Chartist.plugins.ctAxisTitle({
              axisX: {
                axisTitle: 'Timestamp',
                axisClass: 'ct-axis-title',
                offset: {
                  x: 0,
                  y: 50
                },
                textAnchor: 'middle'
              }
            }),
            Chartist.plugins.ctPointLabels({
              textAnchor: 'middle'
            })
          ],
          low: 0,
          showArea: true,
          lineSmooth: false,
          fullWidth: true,
          axisY: {
            offset: 30,
            showGrid: true,
            showLabel: true,
            labelInterpolationFnc: function(value) {return Math.round(value * 100)/100;}
          }
        };

        ctrl.calls = 100;

        ctrl.pieOptions = {
          donut: true,
          donutWidth: 20,
          startAngle: 270,
          total: 200,
          showLabel: false
        };

                /*function showDetail(evt) {
                    var target = evt.target,
                        pointIndex = target.getAttribute('ct:point-index');

                    $modal.open({
                        controller: 'RepoDetailController',
                        controllerAs: 'detail',
                        templateUrl: 'components/widgets/repo/detail.html',
                        size: 'lg',
                        resolve: {
                            commits: function() {
                                return groupedCommitData[pointIndex];
                            }
                        }
                    });
                }*/

                //var groupedCallsData = [];
        //ctrl.showDetail = showDetail;
        ctrl.load = function() {

            var deferred = $q.defer();
            var params = {
                componentId: $scope.widgetConfig.componentId,
            };

            console.log($scope.widgetConfig.componentId);
            collectorData.itemsByType('appPerformance').then(function(data){
              data.forEach(function(element){
                if (element.enabled)
                  ctrl.appname = element.description;
              });
            });

            console.log("checkpoint1");
            performanceData.appPerformance({componentId: $scope.widgetConfig.componentId}).then(function(data) {
                console.log("checkpoint2");
                console.log("widget component id: " + $scope.widgetConfig.componentId);
                processResponse(data.result);
                deferred.resolve(data.lastUpdated);
            });

            console.log("checkpoint3");
            return deferred.promise;
        };

        function processResponse(data) {
            //debugger;
            //ctrl.responsetime = data.responsetime;
            /*ctrl.calls = data.calls;
            ctrl.callspm = data.callspm;
            ctrl.errors = data.errors;
            ctrl.errorspc = data.errorspc;
            ctrl.errorspm = data.errorspm;
            ctrl.businesshealth = data.businesshealth;
            ctrl.nodehealth = data.nodehealth;*/
            var groupedCallsData = [];
            var groupedErrorsData = [];
            var calllabels = [];
            var errorlabels = [];
            var errorcount = 0;
            var callcount = 0;
            var responsecount = 0;
            var nodehealth = 0;
            var businesshealth = 0;
            var errorspm = 0;
            var callspm = 0;
            var responsetime = 0;

            _(data).sortBy('timeStamp').reverse().forEach(function(element){
              var metrictime = element.timestamp;
              var mins = (metrictime/60000) % 60;
              var hours = (((metrictime/60/60000) % 24) + 19) % 24;
              element.metrics.forEach(function(innerelem){
                if (innerelem.name === "Errors per Minute" && innerelem.value>0){
                  errorcount++;
                  errorspm += innerelem.value;
                  groupedErrorsData.push(innerelem.value);
                  errorlabels.push(Math.round(hours) + ":" + Math.round(mins));
                }
                if (innerelem.name === "Calls per Minute" && innerelem.value>0){
                  callcount++;
                  callspm += innerelem.value;
                  groupedCallsData.push(innerelem.value);
                  calllabels.push(Math.round(hours) + ":" + Math.round(mins));
                }
                if (innerelem.name === "Average Response Time (ms)" && innerelem.value>0){
                  responsecount++;
                  responsetime += innerelem.value;
                }
              });
            });

            console.log(groupedCallsData);
            console.log(calllabels);

            /*
            _(data).sortBy('timeStamp').reverse().slice(0, 15).forEach(function(element){
                element.metrics.forEach(function(innerelem2){
                  if (innerelem2.name === "Calls per Minute")
                    groupedCallsData.push(innerelem2.value);
                  if (innerelem2.name === "Errors per Minute")
                    groupedErrorsData.push(innerelem2.value);

                });
                labels.push('');
            });*/

            errorspm = Math.round(errorspm/errorcount * 10)/10;
            callspm = Math.round(callspm/callcount * 10)/10;
            responsetime = Math.round(responsetime/responsecount * 10)/10;
            ctrl.errorspm = errorspm;
            ctrl.callspm = callspm;
            ctrl.responsetime = responsetime;
            //console.log(groupedCallsData);
            //console.log(labels);
            /*var nodehealthavg = Math.round(nodehealth/count * 10)/10;
            console.log("nodehealth: " + nodehealthavg);
            var businesshealthavg = Math.round(businesshealth/count * 10)/10;
            ctrl.businessavg = businesshealthavg;
            ctrl.nodeavg = nodehealthavg;
            ctrl.transactionHealthData = {
              series: [businesshealthavg, 100-businesshealthavg]
            };

            ctrl.nodeHealthData = {
              series: [nodehealthavg, 100-nodehealthavg]
            };*/
            ctrl.callsChartData = {
              series: [groupedCallsData.slice(groupedCallsData.length-7, groupedCallsData.length)],
              labels: calllabels.slice(calllabels.length-7, calllabels.length)
            };

            ctrl.errorsChartData = {
              series: [groupedErrorsData.slice(groupedErrorsData.length-7, groupedErrorsData.length)],
              labels: errorlabels.slice(errorlabels.length-7, errorlabels.length)
            };
        }

    }
})();
<commit_msg>now our dashboard is fully functional yay need to fix data problems though<commit_after>(function () {
    'use strict';

    angular
        .module(HygieiaConfig.module)
        .controller('performanceViewController', performanceViewController);

    performanceViewController.$inject = ['$q', '$scope','performanceData', '$modal', 'collectorData'];
    function performanceViewController($q, $scope, performanceData, $modal, collectorData) {
        var ctrl = this;

        ctrl.genericChartOptions = {
          plugins: [
            Chartist.plugins.gridBoundaries(),
            Chartist.plugins.lineAboveArea(),
            Chartist.plugins.pointHalo(),
            Chartist.plugins.ctPointClick({
              //TODO
            }),
            Chartist.plugins.ctAxisTitle({
              axisX: {
                axisTitle: 'Timestamp',
                axisClass: 'ct-axis-title',
                offset: {
                  x: 0,
                  y: 50
                },
                textAnchor: 'middle'
              }
            }),
            Chartist.plugins.ctPointLabels({
              textAnchor: 'middle'
            })
          ],
          low: 0,
          showArea: true,
          lineSmooth: false,
          fullWidth: true,
          axisY: {
            offset: 30,
            showGrid: true,
            showLabel: true,
            labelInterpolationFnc: function(value) {return Math.round(value * 100)/100;}
          }
        };

        ctrl.calls = 100;

        ctrl.pieOptions = {
          donut: true,
          donutWidth: 20,
          startAngle: 270,
          total: 200,
          showLabel: false
        };

                /*function showDetail(evt) {
                    var target = evt.target,
                        pointIndex = target.getAttribute('ct:point-index');

                    $modal.open({
                        controller: 'RepoDetailController',
                        controllerAs: 'detail',
                        templateUrl: 'components/widgets/repo/detail.html',
                        size: 'lg',
                        resolve: {
                            commits: function() {
                                return groupedCommitData[pointIndex];
                            }
                        }
                    });
                }*/

                //var groupedCallsData = [];
        //ctrl.showDetail = showDetail;
        ctrl.load = function() {

            var deferred = $q.defer();
            var params = {
                componentId: $scope.widgetConfig.componentId,
            };

            console.log($scope.widgetConfig.componentId);
            collectorData.itemsByType('appPerformance').then(function(data){
              data.forEach(function(element){
                if (element.enabled)
                  ctrl.appname = element.description;
              });
            });

            console.log("checkpoint1");
            performanceData.appPerformance({componentId: $scope.widgetConfig.componentId}).then(function(data) {
                console.log("checkpoint2");
                console.log("widget component id: " + $scope.widgetConfig.componentId);
                processResponse(data.result);
                deferred.resolve(data.lastUpdated);
            });

            console.log("checkpoint3");
            return deferred.promise;
        };

        function processResponse(data) {
            //debugger;
            //ctrl.responsetime = data.responsetime;
            /*ctrl.calls = data.calls;
            ctrl.callspm = data.callspm;
            ctrl.errors = data.errors;
            ctrl.errorspc = data.errorspc;
            ctrl.errorspm = data.errorspm;
            ctrl.businesshealth = data.businesshealth;
            ctrl.nodehealth = data.nodehealth;*/
            var groupedCallsData = [];
            var groupedErrorsData = [];
            var calllabels = [];
            var errorlabels = [];
            var errorcount = 0;
            var callcount = 0;
            var responsecount = 0;
            var nodehealth = 0;
            var businesshealth = 0;
            var errorspm = 0;
            var callspm = 0;
            var responsetime = 0;

            _(data).sortBy('timeStamp').__wrapped__[0].metrics.forEach(function(innerelem){
              if (innerelem.name === 'Business Transaction Health Percent'){
                ctrl.businessavg = innerelem.value*100;
              }
              if (innerelem.name === 'Node Health Percent'){
                ctrl.nodeavg = innerelem.value*100;
              }
            });

            _(data).sortBy('timeStamp').reverse().forEach(function(element){
              var metrictime = element.timestamp;
              var mins = (metrictime/60000) % 60;
              var hours = (metrictime/60/60000) % 24;
              element.metrics.forEach(function(innerelem){
                if (innerelem.name === "Errors per Minute" && innerelem.value>0){
                  errorcount++;
                  errorspm += innerelem.value;
                  groupedErrorsData.push(innerelem.value);
                  errorlabels.push(Math.round(hours) + ":" + Math.round(mins));
                }
                if (innerelem.name === "Calls per Minute" && innerelem.value>0){
                  callcount++;
                  callspm += innerelem.value;
                  groupedCallsData.push(innerelem.value);
                  calllabels.push(Math.round(hours) + ":" + Math.round(mins));
                }
                if (innerelem.name === "Average Response Time (ms)" && innerelem.value>0){
                  responsecount++;
                  responsetime += innerelem.value;
                }
              });
            });

            console.log(groupedCallsData);
            console.log(calllabels);

            /*
            _(data).sortBy('timeStamp').reverse().slice(0, 15).forEach(function(element){
                element.metrics.forEach(function(innerelem2){
                  if (innerelem2.name === "Calls per Minute")
                    groupedCallsData.push(innerelem2.value);
                  if (innerelem2.name === "Errors per Minute")
                    groupedErrorsData.push(innerelem2.value);

                });
                labels.push('');
            });*/

            errorspm = Math.round(errorspm/errorcount * 10)/10;
            callspm = Math.round(callspm/callcount * 10)/10;
            responsetime = Math.round(responsetime/responsecount * 10)/10;
            ctrl.errorspm = errorspm;
            ctrl.callspm = callspm;
            ctrl.responsetime = responsetime;
            //console.log(groupedCallsData);
            //console.log(labels);
            /*var nodehealthavg = Math.round(nodehealth/count * 10)/10;
            console.log("nodehealth: " + nodehealthavg);
            var businesshealthavg = Math.round(businesshealth/count * 10)/10;
            ctrl.businessavg = businesshealthavg;
            ctrl.nodeavg = nodehealthavg;
            ctrl.transactionHealthData = {
              series: [businesshealthavg, 100-businesshealthavg]
            };

            ctrl.nodeHealthData = {
              series: [nodehealthavg, 100-nodehealthavg]
            };*/

            ctrl.transactionHealthData = {
              series: [ctrl.businessavg, 100-ctrl.businessavg]
            };

            ctrl.nodeHealthData = {
              series: [ctrl.nodeavg, 100-ctrl.nodeavg]
            };

            ctrl.callsChartData = {
              series: [groupedCallsData.slice(groupedCallsData.length-7, groupedCallsData.length)],
              labels: calllabels.slice(calllabels.length-7, calllabels.length)
            };

            ctrl.errorsChartData = {
              series: [groupedErrorsData.slice(groupedErrorsData.length-7, groupedErrorsData.length)],
              labels: errorlabels.slice(errorlabels.length-7, errorlabels.length)
            };
        }

    }
})();
<|endoftext|>


<commit_before>'use strict'
// grab all necessary DOM elements for manipulation
const container = document.getElementById('container')
  ,     display = document.getElementById('display')
  ,   textInput = document.getElementById('input')
  ,  textOutput = document.getElementById('output')
  ,      button = document.getElementById('button')
  ,      matrix = []
  ,    testWord = 'h'

/******************** HELPER FUNCTIONS **************************/

// switch "LED" div's className on or off
const switchOnOrOff = (led) => {
  if(led.className === 'led off') {
    led.className = 'led'
  }
  else {
    led.className = 'led off'
  }
}

const createLetterBox = (id, classAssignment = 'letterBox') => {
  let box = document.createElement('div')
  box.className = classAssignment
  box.setAttribute('id', id)

  return box
}

const populateLetterBoxWithLEDs = (index) => {
  let lines = []
  for (let i = 0; i < 7; i++) {
    let ledDivs = []
    for (let j = 0; j < 5; j++) {
      let led = document.createElement('div')
      // pre es6 function used for contextual `this`
      led.onclick = function () { switchOnOrOff(this) }
      led.className = 'led off'
      document.getElementById(`letterBox${index}`).appendChild(led)
      ledDivs.push(led)
    }
    lines.push(ledDivs)
  }
  matrix.push(lines)
}

const getCoords = () =>  {
  // using destructuring to clone the array for
  // safe manipulation and more declarative syntax
  const [...letterBoxes] = matrix
    ,   coords = []

    letterBoxes.forEach((row, i) => {
      row.forEach((divs, j) => {
        divs.forEach((led, n) => {
          // push a `coordinates` object into our coords array
          // containg the 3 index values for each LED needed to
          // write the alphanumeric characters
          if(led.className === 'led') {
            coords.push({i,j,n})
          }
        })
      })
    })
  console.log(JSON.stringify(coords))
}

button.addEventListener('click', getCoords)
/*****************************************************************/
const H = [0,0,0,4,1,0,1,4,2,0,2,4,3,0,3,1,3,2,3,3,3,4,4,0,4,4,5,0,5,4,6,0,6,4]

const newLetterBoxes = (word) => {
  [...word].forEach((letter, index) => {
     display.appendChild(createLetterBox(`letterBox${index}`))
     populateLetterBoxWithLEDs(index)
  })
}
newLetterBoxes(testWord)

console.log(`
Matrix[x][y][z] is a 3D array
where:
x = letterBox, y = row, z = LED in row
`, matrix)

// const write = (arr) => {
//   var i = 0;
//   while (i < arr.length){
//     matrix[arr[i++]][arr[i++]][arr[i++]].className = "led";
//   }
// }
// write(H)
<commit_msg>commented out coordinate helper func, moved to bottom, left in to show work<commit_after>'use strict'
// grab all necessary DOM elements for manipulation
const container = document.getElementById('container')
  ,     display = document.getElementById('display')
  ,   textInput = document.getElementById('input')
  ,  textOutput = document.getElementById('output')
  ,      button = document.getElementById('button')
  ,      matrix = []
  ,    testWord = 'h'

/******************** HELPER FUNCTIONS **************************/

// switch "LED" div's className on or off
const switchOnOrOff = (led) => {
  if(led.className === 'led off') {
    led.className = 'led'
  }
  else {
    led.className = 'led off'
  }
}

const createLetterBox = (id, classAssignment = 'letterBox') => {
  let box = document.createElement('div')
  box.className = classAssignment
  box.setAttribute('id', id)

  return box
}

const populateLetterBoxWithLEDs = (index) => {
  let lines = []
  for (let i = 0; i < 7; i++) {
    let ledDivs = []
    for (let j = 0; j < 5; j++) {
      let led = document.createElement('div')
      // pre es6 function used for contextual `this`
      led.onclick = function () { switchOnOrOff(this) }
      led.className = 'led off'
      document.getElementById(`letterBox${index}`).appendChild(led)
      ledDivs.push(led)
    }
    lines.push(ledDivs)
  }
  matrix.push(lines)
}
/*****************************************************************/

const newLetterBoxes = (word) => {
  [...word].forEach((letter, index) => {
     display.appendChild(createLetterBox(`letterBox${index}`))
     populateLetterBoxWithLEDs(index)
  })
}
newLetterBoxes(testWord)

console.log(`
Matrix[x][y][z] is a 3D array
where:
x = letterBox, y = row, z = LED in row
`, matrix)

// const write = (arr) => {
//   var i = 0;
//   while (i < arr.length){
//     matrix[arr[i++]][arr[i++]][arr[i++]].className = "led";
//   }
// }
// write(H)

/*
  the following was used to build the alphanumeric JSON file
  containg all the coordinates necessary for this test. It is
  not needed for the program anymore but is left in to show
  how it was done

const getCoords = () =>  {
  // using destructuring to clone the array for
  // safe manipulation and more declarative syntax
  const [...letterBoxes] = matrix
    ,   coords = []

    letterBoxes.forEach((row, i) => {
      row.forEach((divs, j) => {
        divs.forEach((led, n) => {
          // push a `coordinates` object into our coords array
          // containg the 3 index values for each LED needed to
          // write the alphanumeric characters
          if(led.className === 'led') {
            coords.push({i,j,n})
          }
        })
      })
    })
  console.log(JSON.stringify(coords))
}
button.addEventListener('click', getCoords)
*/
<|endoftext|>


<commit_before>'use strict';

// Utilities:
var _ = require('lodash');

// Dependencies:
var socket = require('socket.io-client');

// Module:
var Core = require('../Core');

var RealTimeService = function RealTimeService (
    config
) {
    return {
        connect: connect
    };

    function connect (room, events) {
        var url = 'http://localhost:' + config.port + '/' + room;
        var connection = socket.connect(url, {
            forceNew: true
        });
        _.each(events, function (handler, event) {
            connection.on(event, handler);
        });
        return connection;
    }
};

Core.service('realTimeService', RealTimeService);
<commit_msg>fix(ui :lipstick:) - trying to improve responsiveness of the file tree<commit_after>'use strict';

// Utilities:
var _ = require('lodash');

// Dependencies:
var socket = require('socket.io-client');

// Module:
var Core = require('../Core');

var RealTimeService = function RealTimeService (
    config,
    $rootScope
) {
    return {
        connect: connect
    };

    function connect (room, events) {
        var url = 'http://localhost:' + config.port + '/' + room;
        var connection = socket.connect(url, {
            forceNew: true
        });
        _.each(events, function (handler, event) {
            connection.on(event, function () {
                handler.apply(this, arguments);
                $rootScope.$apply();
            });
        });
        return connection;
    }
};

Core.service('realTimeService', RealTimeService);
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * TODO: python delimiters
 */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var PythonHighlightRules = function() {

    var keywords = (
        "and|as|assert|break|class|continue|def|del|elif|else|except|exec|" +
        "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" +
        "raise|return|try|while|with|yield"
    );

    var builtinConstants = (
        "True|False|None|NotImplemented|Ellipsis|__debug__"
    );

    var builtinFunctions = (
        "abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" +
        "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" +
        "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" +
        "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" +
        "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" +
        "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" +
        "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" +
        "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern"
    );

    //var futureReserved = "";
    var keywordMapper = this.createKeywordMapper({
        "invalid.deprecated": "debugger",
        "support.function": builtinFunctions,
        //"invalid.illegal": futureReserved,
        "constant.language": builtinConstants,
        "keyword": keywords
    }, "identifier");

    var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";

    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
    var octInteger = "(?:0[oO]?[0-7]+)";
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
    var binInteger = "(?:0[bB][01]+)";
    var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";

    var exponent = "(?:[eE][+-]?\\d+)";
    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + exponent + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "#.*$"
        }, {
            token : "string",           // """ string
            regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}'
        }, {
            token : "string",           // multi line """ string start
            regex : strPre + '"{3}.*$',
            next : "qqstring"
        }, {
            token : "string",           // " string
            regex : strPre + '"(?:[^\\\\]|\\\\.)*?"'
        }, {
            token : "string",           // ''' string
            regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}"
        }, {
            token : "string",           // multi line ''' string start
            regex : strPre + "'{3}.*$",
            next : "qstring"
        }, {
            token : "string",           // ' string
            regex : strPre + "'(?:[^\\\\]|\\\\.)*?'"
        }, {
            token : "constant.numeric", // imaginary
            regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // long integer
            regex : integer + "[lL]\\b"
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "qqstring" : [ {
            token : "string", // multi line """ string end
            regex : '(?:[^\\\\]|\\\\.)*?"{3}',
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ],
        "qstring" : [ {
            token : "string",  // multi line ''' string end
            regex : "(?:[^\\\\]|\\\\.)*?'{3}",
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ]
    };
};

oop.inherits(PythonHighlightRules, TextHighlightRules);

exports.PythonHighlightRules = PythonHighlightRules;
});
<commit_msg>fix python string highlighting<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * TODO: python delimiters
 */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var PythonHighlightRules = function() {

    var keywords = (
        "and|as|assert|break|class|continue|def|del|elif|else|except|exec|" +
        "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" +
        "raise|return|try|while|with|yield"
    );

    var builtinConstants = (
        "True|False|None|NotImplemented|Ellipsis|__debug__"
    );

    var builtinFunctions = (
        "abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" +
        "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" +
        "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" +
        "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" +
        "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" +
        "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" +
        "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" +
        "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern"
    );

    //var futureReserved = "";
    var keywordMapper = this.createKeywordMapper({
        "invalid.deprecated": "debugger",
        "support.function": builtinFunctions,
        //"invalid.illegal": futureReserved,
        "constant.language": builtinConstants,
        "keyword": keywords
    }, "identifier");

    var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";

    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
    var octInteger = "(?:0[oO]?[0-7]+)";
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
    var binInteger = "(?:0[bB][01]+)";
    var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";

    var exponent = "(?:[eE][+-]?\\d+)";
    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + exponent + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";

    var stringEscape =  "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})";

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "#.*$"
        }, {
            token : "string",           // multi line """ string start
            regex : strPre + '"{3}',
            next : "qqstring3"
        }, {
            token : "string",           // " string
            regex : strPre + '"(?=.)',
            next : "qqstring"
        }, {
            token : "string",           // multi line ''' string start
            regex : strPre + "'{3}",
            next : "qstring3"
        }, {
            token : "string",           // ' string
            regex : strPre + "'(?=.)",
            next : "qstring"
        }, {
            token : "constant.numeric", // imaginary
            regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // long integer
            regex : integer + "[lL]\\b"
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "qqstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",  // multi line ''' string end
            regex : "'{3}",
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qqstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qqstring"
        }, {
            token : "string",
            regex : '"|$',
            next  : "start"
        }, {
            defaultToken: "string"
        }],
        "qstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qstring"
        }, {
            token : "string",
            regex : "'|$",
            next  : "start"
        }, {
            defaultToken: "string"
        }]
    };
};

oop.inherits(PythonHighlightRules, TextHighlightRules);

exports.PythonHighlightRules = PythonHighlightRules;
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './styles.css';

export default class NavBar extends Component {

  render() {
    return (

              <Link to="/plugin/mention" className={styles.link}>
                Mention
              </Link>

              <Link to="/plugin/linkify" className={styles.link}>
                Linkify
              </Link>

              <Link to="/plugin/sticker" className={styles.link}>
                Sticker
              </Link>

              <Link to="/plugin/emoji" className={styles.link}>
                Emoji
              </Link>

              <Link to="/plugin/image" className={styles.link}>
                Image
              </Link>

              <Link to="/plugin/inline-toolbar" className={styles.link}>
                Inline Toolbar
              </Link>

              <Link to="/plugin/side-toolbar" className={styles.link}>
                Side Toolbar
              </Link>

              <Link to="/plugin/hashtag" className={styles.link}>
                Hashtag
              </Link>

              <Link to="/plugin/undo" className={styles.link}>
                Undo
              </Link>

              <Link to="/plugin/counter" className={styles.link}>
                Counter
              </Link>

    );
  }
}
<commit_msg>re-order navbar<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './styles.css';

export default class NavBar extends Component {

  render() {
    return (

              <Link to="/plugin/mention" className={styles.link}>
                Mention
              </Link>

              <Link to="/plugin/linkify" className={styles.link}>
                Linkify
              </Link>

              <Link to="/plugin/sticker" className={styles.link}>
                Sticker
              </Link>

              <Link to="/plugin/emoji" className={styles.link}>
                Emoji
              </Link>

              <Link to="/plugin/image" className={styles.link}>
                Image
              </Link>

              <Link to="/plugin/hashtag" className={styles.link}>
                Hashtag
              </Link>

              <Link to="/plugin/inline-toolbar" className={styles.link}>
                Inline Toolbar
              </Link>

              <Link to="/plugin/side-toolbar" className={styles.link}>
                Side Toolbar
              </Link>

              <Link to="/plugin/undo" className={styles.link}>
                Undo
              </Link>

              <Link to="/plugin/counter" className={styles.link}>
                Counter
              </Link>

    );
  }
}
<|endoftext|>


<commit_before>/*

Edtended handling of date, time and datetime-local type fields.

Works with both string and integer data types. (default only support string type)

Has optional support for using flatpickr datepicker.
All flatpickr options is supported with a few minor differences.
- "enableTime" and "noCalendar" are set automatically, based on the data type.
- Extra config option "errorDateFormat". If this is set, it will replace the format displayed in error messages.
- It is not possible to use "inline" and "wrap" options together.
- When using the "wrap" option, "toggle" and "clear" buttons are automatically added to markup. 2 extra boolean options ("showToggleButton" and "showClearButton") are available to control which buttons to display. Note: not all frameworks supports this. (Works in: Bootstrap and Foundation)
- When using the "inline" option, an extra boolean option ("inlineHideInput") is available to hide the original input field.
- If "mode" is set to either "multiple" or "range", only string data type is supported. Also the result from these is returned as a string not an array.

ToDo:
 - Improve Handling of flatpicker "multiple" and "range" modes. (Currently the values are just added as string values, but the optimal scenario would be to save those as array if possible)

*/
JSONEditor.defaults.editors.datetime = JSONEditor.defaults.editors.string.extend({
  build: function () {
    this._super();
    if(!this.input) return;

    if(window.flatpickr && typeof this.options.flatpickr == 'object') {

      // Make sure that flatpickr settings matches the input type
      this.options.flatpickr.enableTime = this.schema.format == 'date' ? false : true;
      this.options.flatpickr.noCalendar = this.schema.format == 'time' ? true : false;

      // Curently only string can contain range or multiple values
      if (this.schema.type == 'integer') this.options.flatpickr.mode = 'single';

      // Attribute for flatpicker
      this.input.setAttribute('data-input','');

      var input = this.input;

      if (this.options.flatpickr.wrap === true) {

        // Create buttons for input group
        var buttons = [];
        if (this.options.flatpickr.showToggleButton !== false) {
          var toggleButton = this.getButton('',this.schema.format == 'time' ? 'time' :'calendar', this.translate('flatpickr_toggle_button'));
          // Attribute for flatpicker
          toggleButton.setAttribute('data-toggle','');
          buttons.push(toggleButton);
        }
        if (this.options.flatpickr.showClearButton !== false) {
          var clearButton = this.getButton('','clear', this.translate('flatpickr_clear_button'));
          // Attribute for flatpicker
          clearButton.setAttribute('data-clear','');
          buttons.push(clearButton);
        }

        // Save position of input field
        var parentNode = this.input.parentNode, nextSibling = this.input.nextSibling;

        var buttonContainer = this.theme.getInputGroup(this.input, buttons);
        if (buttonContainer !== undefined) {
          // Make sure "inline" option is turned off
          this.options.flatpickr.inline = false;

          // Insert container at same position as input field
          parentNode.insertBefore(buttonContainer, nextSibling);

          input = buttonContainer;
        }
        else {
          this.options.flatpickr.wrap = false;
        }

      }

      this.flatpickr = window.flatpickr(input, this.options.flatpickr);

      if (this.options.flatpickr.inline === true && this.options.flatpickr.inlineHideInput === true) {
          this.input.setAttribute('type','hidden');
      }
    }
  },
  getValue: function() {
    if (!this.dependenciesFulfilled) {
      return undefined;
    }
    if (this.schema.type == 'string') {
      return this.value;
    }
    if (this.value === '' || this.value === undefined) {
      return undefined;
    }

    var value =  this.schema.format == 'time' ? '1970-01-01 ' + this.value : this.value;
    return parseInt(new Date(value).getTime() / 1000);
  },
  setValue: function(value, initial, from_template) {
    if (this.schema.type == 'string') {
      this._super(value, initial, from_template);
    }
    else if (value > 0) {
      var dateValue, dateObj = new Date(value * 1000),
          year = dateObj.getFullYear(),
          month = this.zeroPad(dateObj.getMonth() + 1),
          day = this.zeroPad(dateObj.getDate()),
          hour = this.zeroPad(dateObj.getHours()),
          min = this.zeroPad(dateObj.getMinutes()),
          sec = this.zeroPad(dateObj.getSeconds()),
          date = [year, month, day].join('-'),
          time = [hour, min, sec].join(':');

      if (this.schema.format == 'date') dateValue = date;
      else if (this.schema.format == 'time') dateValue = time;
      else dateValue = date + ' ' + time;

      this.input.value = dateValue;
    }
  },
  destroy: function() {
    if (this.flatpickr) this.flatpickr.destroy();
    this.flatpickr = null;
    this._super();
  },
  // helper function
  zeroPad: function(value) {
    return ('0' + value).slice(-2);
  }
});
<commit_msg>Fix of #276<commit_after>/*

Edtended handling of date, time and datetime-local type fields.

Works with both string and integer data types. (default only support string type)

Has optional support for using flatpickr datepicker.
All flatpickr options is supported with a few minor differences.
- "enableTime" and "noCalendar" are set automatically, based on the data type.
- Extra config option "errorDateFormat". If this is set, it will replace the format displayed in error messages.
- It is not possible to use "inline" and "wrap" options together.
- When using the "wrap" option, "toggle" and "clear" buttons are automatically added to markup. 2 extra boolean options ("showToggleButton" and "showClearButton") are available to control which buttons to display. Note: not all frameworks supports this. (Works in: Bootstrap and Foundation)
- When using the "inline" option, an extra boolean option ("inlineHideInput") is available to hide the original input field.
- If "mode" is set to either "multiple" or "range", only string data type is supported. Also the result from these is returned as a string not an array.

ToDo:
 - Improve Handling of flatpicker "multiple" and "range" modes. (Currently the values are just added as string values, but the optimal scenario would be to save those as array if possible)

*/
JSONEditor.defaults.editors.datetime = JSONEditor.defaults.editors.string.extend({
  build: function () {
    this._super();
    if(!this.input) return;

    if(window.flatpickr && typeof this.options.flatpickr == 'object') {

      // Make sure that flatpickr settings matches the input type
      this.options.flatpickr.enableTime = this.schema.format == 'date' ? false : true;
      this.options.flatpickr.noCalendar = this.schema.format == 'time' ? true : false;

      // Curently only string can contain range or multiple values
      if (this.schema.type == 'integer') this.options.flatpickr.mode = 'single';

      // Attribute for flatpicker
      this.input.setAttribute('data-input','');

      var input = this.input;

      if (this.options.flatpickr.wrap === true) {

        // Create buttons for input group
        var buttons = [];
        if (this.options.flatpickr.showToggleButton !== false) {
          var toggleButton = this.getButton('',this.schema.format == 'time' ? 'time' :'calendar', this.translate('flatpickr_toggle_button'));
          // Attribute for flatpicker
          toggleButton.setAttribute('data-toggle','');
          buttons.push(toggleButton);
        }
        if (this.options.flatpickr.showClearButton !== false) {
          var clearButton = this.getButton('','clear', this.translate('flatpickr_clear_button'));
          // Attribute for flatpicker
          clearButton.setAttribute('data-clear','');
          buttons.push(clearButton);
        }

        // Save position of input field
        var parentNode = this.input.parentNode, nextSibling = this.input.nextSibling;

        var buttonContainer = this.theme.getInputGroup(this.input, buttons);
        if (buttonContainer !== undefined) {
          // Make sure "inline" option is turned off
          this.options.flatpickr.inline = false;

          // Insert container at same position as input field
          parentNode.insertBefore(buttonContainer, nextSibling);

          input = buttonContainer;
        }
        else {
          this.options.flatpickr.wrap = false;
        }

      }

      this.flatpickr = window.flatpickr(input, this.options.flatpickr);

      if (this.options.flatpickr.inline === true && this.options.flatpickr.inlineHideInput === true) {
          this.input.setAttribute('type','hidden');
      }
    }
  },
  getValue: function() {
    if (!this.dependenciesFulfilled) {
      return undefined;
    }
    if (this.schema.type == 'string') {
      return this.value;
    }
    if (this.value === '' || this.value === undefined) {
      return undefined;
    }

    var value =  this.schema.format == 'time' ? '1970-01-01 ' + this.value : this.value;
    return parseInt(new Date(value).getTime() / 1000);
  },
  setValue: function(value, initial, from_template) {
    if (this.schema.type == 'string') {
      this._super(value, initial, from_template);
      if (this.flatpickr) this.flatpickr.setDate(value);
    }
    else if (value > 0) {
      var dateObj = new Date(value * 1000),
          year = dateObj.getFullYear(),
          month = this.zeroPad(dateObj.getMonth() + 1),
          day = this.zeroPad(dateObj.getDate()),
          hour = this.zeroPad(dateObj.getHours()),
          min = this.zeroPad(dateObj.getMinutes()),
          sec = this.zeroPad(dateObj.getSeconds()),
          date = [year, month, day].join('-'),
          time = [hour, min, sec].join(':'),
          dateValue = date + ' ' + time;

      if (this.schema.format == 'date') dateValue = date;
      else if (this.schema.format == 'time') dateValue = time;

      this.input.value = dateValue;
      if (this.flatpickr) this.flatpickr.setDate(dateValue);
    }
  },
  destroy: function() {
    if (this.flatpickr) this.flatpickr.destroy();
    this.flatpickr = null;
    this._super();
  },
  // helper function
  zeroPad: function(value) {
    return ('0' + value).slice(-2);
  }
});
<|endoftext|>


<commit_before>var chatConfig = require('./../configurations/chat');
var config = require('./../configurations/config');
var log = require('tracer').colorConsole(config.loggingConfig);
var swearjar = require('swearjar');

module.exports = function (sio) {
	var io = sio.of('/chat');

	io.on('connection', function(socket) {
		//Decoded Token
		var token = socket.client.request.decoded_token;
		var username = token.name;

		socket.on('clientMessage',function(data) {
			data.id = username;
			if (config.profanityFilter){
				data.message = swearjar.censor(data.message);
			}

			io.emit('messageServer',data);

			if (config.enableLogging){
				log.info(username + ': ' + data.message);
			}
		});
	});
};
<commit_msg>Cleanup of profanity filter config<commit_after>//Version: 0.1.1 - Cleanup of profanity filter.

var chatConfig = require('./../configurations/chat');
var config = require('./../configurations/config');
var log = require('tracer').colorConsole(config.loggingConfig);
var swearjar = require('swearjar');

module.exports = function (sio) {
	var io = sio.of('/chat');

	io.on('connection', function(socket) {
		//Decoded Token
		var token = socket.client.request.decoded_token;
		var username = token.name;

		socket.on('clientMessage',function(data) {
			data.id = username;
			if (chatConfig.profanityFilter){
				data.message = swearjar.censor(data.message);
			}

			io.emit('messageServer',data);

			if (config.enableLogging){
				log.info(username + ': ' + data.message);
			 }
		});
	});
};
<|endoftext|>


<commit_before>import icon from 'react-icons/lib/fa/recycle'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'}
    },
    {
      name: 'someWeakRef',
      type: 'reference',
      weak: true,
      to: {type: 'author'}
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'}
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'}
        }
      ]
    }
  ]
}
<commit_msg>[test-studio] Add a test case for selecting array items for preview<commit_after>import icon from 'react-icons/lib/fa/recycle'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'}
    },
    {
      name: 'someWeakRef',
      type: 'reference',
      weak: true,
      to: {type: 'author'}
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'}
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'},
        }
      ]
    },
  ],
  preview: {
    fields: {
      title: 'title',
      author0: 'array.0.name',
      author1: 'array.1.name'
    },
    prepare(val) {
      return {
        title: val.title,
        subtitle: [val.author0, val.author1].filter(Boolean).join(', ')
      }
    }
  }
}
<|endoftext|>


<commit_before>var Path = require('path');
var Hapi = require('hapi');
var data = require('./data/fall_2014');
var _ = require('lodash');

var server = new Hapi.Server('localhost', 3000, { files: { relativeTo: Path.join(__dirname, './') } });

var course = function (info){
  return {
    //hash: md5(hash),
    status: info[0],
    capacity: info[1],
    avaliableSeats: info[2],
    prop: info[3],
    courseNum: info[4],
    crn: info[5],
    note: info[6],
    description: info[7],
    days: info[8],
    location: info[9],
    instructor: info[10],
    i_user: info[11],
    unknown1: info[12],
    unknown2: info[13],
    unknown3: info[14],
    unknown4: info[15],
    unknown5: info[16],
    unknown6: info[17],
    unknown7: info[18],
  };
};

// Serve static files from `static` dir.
server.route({
  method: 'GET',
  path: '/{path*}',
  handler: {
      directory: { path: './', listing: false, index: true }
  }
});

server.route({
    method: 'GET',
    path: '/data',
    handler: function (request, reply) {
      var courses = [];
      _.each(data.main, function(info){
        courses.push(course(info));
      });
        reply(courses);
    }
});

// Start your Mullet Server
server.start(function () {
  console.log('The Mullet Stack is running on port: 3000');
});
<commit_msg>fake twilio scaffold<commit_after>var Path = require('path');
var Hapi = require('hapi');
var data = require('./data/fall_2014');
var _ = require('lodash');

var server = new Hapi.Server('localhost', 3000, { files: { relativeTo: Path.join(__dirname, './') } });

var course = function (info){
  return {
    //hash: md5(hash),
    status: info[0],
    capacity: info[1],
    avaliableSeats: info[2],
    prop: info[3],
    courseNum: info[4],
    crn: info[5],
    note: info[6],
    description: info[7],
    days: info[8],
    location: info[9],
    instructor: info[10],
    i_user: info[11],
    unknown1: info[12],
    unknown2: info[13],
    unknown3: info[14],
    unknown4: info[15],
    unknown5: info[16],
    unknown6: info[17],
    unknown7: info[18]
  };
};

// Serve static files from `static` dir.
server.route({
  method: 'GET',
  path: '/{path*}',
  handler: {
      directory: { path: './', listing: false, index: true }
  }
});

server.route({
    method: 'GET',
    path: '/data',
    handler: function (request, reply) {
      var courses = [];
      _.each(data.main, function(info){
        courses.push(course(info));
      });
        reply(courses);
    }
});

server.route({
    method: 'POST',
    path: '/subscribe',
    handler: function (request, reply) {
      //twilio you are subscribed to --- blah
    }
});

// Start your Mullet Server
server.start(function () {
  console.log('Coursica is running on port: 3000');
});
<|endoftext|>


<commit_before>/* eslint-disable no-underscore-dangle */
import { observer } from 'binary-common-utils/lib/observer';
import { durationAccepted, expandDuration } from 'binary-common-utils/lib/tools';
import config from '../../../common/const';
import { bot } from '../../bot';
import { translator } from '../../../common/translator';
import { utils } from './utils';

const isInteger = (amount) => !isNaN(+amount) && parseInt(amount, 10) === parseFloat(amount);
const isInRange = (amount, min, max) => !isNaN(+amount) && +amount >= min && +amount <= max;
const getNumField = (block, fieldName) => {
  let field = block.getInputTargetBlock(fieldName);
  if (field !== null && field.type === 'math_number') {
    field = field.getFieldValue('NUM')
      .trim();
    return field;
  }
  return '';
};
const insideHolder = (blockObj) => blockObj.parentBlock_ !== null && blockObj.parentBlock_.type === 'block_holder';
const getListField = (block, fieldName) => block.getFieldValue(fieldName);
export const condition = (blockObj, ev, calledByParent) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (blockObj.parentBlock_ !== null) {
    if (!bot.symbol.findSymbol(blockObj.parentBlock_.type)) {
      observer.emit('ui.log.warn',
        translator.translateText('Trade Type blocks have to be added to submarket blocks'));
      blockObj.unplug();
    } else if (!bot.symbol.isConditionAllowedInSymbol(blockObj.parentBlock_.type, blockObj.type)) {
      const symbol = bot.symbol.findSymbol(blockObj.parentBlock_.type);
      observer.emit('ui.log.warn',
        `${symbol[Object.keys(symbol)[0]]} ${translator.translateText('does not support category:')}`
        + ` ${bot.symbol.getCategoryNameForCondition(blockObj.type)}`
        + `, ${translator.translateText('Allowed categories are')}`
        + ` ${bot.symbol.getAllowedCategoryNames(blockObj.parentBlock_.type)}`);
      blockObj.unplug();
    } else {
      observer.emit('tour:condition');
      if (!calledByParent) {
        if ((ev.type === 'change' && ev.element && ev.element === 'field')
          || (ev.type === 'move' && typeof ev.newInputName === 'string')) {
          const duration = getNumField(blockObj, 'DURATION');
          const durationType = getListField(blockObj, 'DURATIONTYPE_LIST');
          if (duration !== '') {
            const minDuration = bot.symbol.getLimitation(blockObj.parentBlock_.type, blockObj.type).minDuration;
            if (!durationAccepted(duration + durationType, minDuration)) {
              observer.emit('ui.log.warn',
                translator.translateText('Minimum duration is') +
                ' ' + expandDuration(minDuration));
            } else {
              observer.emit('tour:ticks');
            }
            if (durationType === 't') {
              if (!isInteger(duration) || !isInRange(duration, 5, 10)) {
                observer.emit('ui.log.warn',
                  translator.translateText('Number of ticks must be between 5 and 10'));
              } else {
                observer.emit('tour:ticks');
              }
            } else if (!isInteger(duration) || duration < 1) {
              observer.emit('ui.log.warn',
                translator.translateText('Expiry time cannot be equal to start time'));
            }
          }
          const prediction = getNumField(blockObj, 'PREDICTION');
          if (prediction !== '') {
            if (!isInteger(prediction) || !isInRange(prediction, 0, 9)) {
              observer.emit('ui.log.warn', translator.translateText('Prediction must be one digit'));
            }
          }
          for (const il of blockObj.inputList) {
            if (il.name !== '' && blockObj.getInputTargetBlock(il.name) === null) {
              return;
            }
          }
          observer.emit('tour:options');
        }
      }
    }
  }
};
export const submarket = (blockObj, ev) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (blockObj.childBlocks_.length > 0 && config.conditions.indexOf(blockObj.childBlocks_[0].type) < 0) {
    observer.emit('ui.log.warn', translator.translateText('Submarket blocks can only accept trade type blocks'));
    for (const child of Array.prototype.slice.apply(blockObj.childBlocks_)) {
      child.unplug();
    }
  } else if (blockObj.childBlocks_.length > 0) {
    condition(blockObj.childBlocks_[0], ev, true);
  }
  if (blockObj.parentBlock_ !== null) {
    if (blockObj.parentBlock_.type !== 'trade') {
      observer.emit('ui.log.warn',
        translator.translateText('Submarket blocks have to be added to the trade block'));
      blockObj.unplug();
    }
  }
};
export const trade = (blockObj, ev) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (ev.type === 'create') {
    if (bot.symbol.findSymbol(Blockly.mainWorkspace.getBlockById(ev.blockId).type)) {
      observer.emit('tour:submarket_created');
    }
    if (config.conditions.indexOf(Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type) >= 0) {
      observer.emit('tour:condition_created');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'math_number') {
      observer.emit('tour:number');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'purchase') {
      observer.emit('tour:purchase_created');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'trade_again') {
      observer.emit('tour:trade_again_created');
    }
  }
  if (blockObj.childBlocks_.length && !bot.symbol.findSymbol(blockObj.childBlocks_[0].type)) {
    observer.emit('ui.log.warn',
      translator.translateText('The trade block can only accept submarket blocks'));
    for (const child of Array.prototype.slice.apply(blockObj.childBlocks_)) {
      child.unplug();
    }
  } else if (blockObj.childBlocks_.length > 0) {
    submarket(blockObj.childBlocks_[0], ev);
    observer.emit('tour:submarket');
    if ('newInputName' in ev) {
      utils.addPurchaseOptions();
    }
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (bot.symbol.findSymbol(topParent.type)
      || ['on_strategy', 'on_finish'].indexOf(topParent.type) >= 0) {
      observer.emit('ui.log.warn',
        translator.translateText('The trade block cannot be inside binary blocks'));
      blockObj.unplug();
    }
  }
};
export const insideCondition = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (config.conditions.indexOf(blockObj.parentBlock_.type) < 0 && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added to the condition block'));
      blockObj.unplug();
    }
  }
};
export const insideStrategy = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (topParent.type !== 'on_strategy' && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added inside the strategy block'));
      blockObj.unplug();
    } else if (blockObj.type === 'purchase') {
      observer.emit('tour:purchase');
    }
  }
};
export const insideFinish = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (topParent.type !== 'on_finish' && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added inside the finish block'));
      blockObj.unplug();
    } else if (blockObj.type === 'trade_again') {
      observer.emit('tour:trade_again');
    }
  }
};
<commit_msg>Replaced unplug with disable blocks<commit_after>/* eslint-disable no-underscore-dangle */
import { observer } from 'binary-common-utils/lib/observer';
import { durationAccepted, expandDuration } from 'binary-common-utils/lib/tools';
import config from '../../../common/const';
import { bot } from '../../bot';
import { translator } from '../../../common/translator';
import { utils } from './utils';

const isInteger = (amount) => !isNaN(+amount) && parseInt(amount, 10) === parseFloat(amount);
const isInRange = (amount, min, max) => !isNaN(+amount) && +amount >= min && +amount <= max;
const getNumField = (block, fieldName) => {
  let field = block.getInputTargetBlock(fieldName);
  if (field !== null && field.type === 'math_number') {
    field = field.getFieldValue('NUM')
      .trim();
    return field;
  }
  return '';
};
const insideHolder = (blockObj) => {
  const parent = utils.findTopParentBlock(blockObj);
  if (parent !== null && parent.type === 'block_holder') {
    return true;
  }
  return false;
};
const getListField = (block, fieldName) => block.getFieldValue(fieldName);
export const condition = (blockObj, ev, calledByParent) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (blockObj.parentBlock_ !== null) {
    if (!bot.symbol.findSymbol(blockObj.parentBlock_.type)) {
      observer.emit('ui.log.warn',
        translator.translateText('Trade Type blocks have to be added to submarket blocks'));
      blockObj.setDisabled(true);
      return;
    } else if (!bot.symbol.isConditionAllowedInSymbol(blockObj.parentBlock_.type, blockObj.type)) {
      const symbol = bot.symbol.findSymbol(blockObj.parentBlock_.type);
      observer.emit('ui.log.warn',
        `${symbol[Object.keys(symbol)[0]]} ${translator.translateText('does not support category:')}`
        + ` ${bot.symbol.getCategoryNameForCondition(blockObj.type)}`
        + `, ${translator.translateText('Allowed categories are')}`
        + ` ${bot.symbol.getAllowedCategoryNames(blockObj.parentBlock_.type)}`);
      blockObj.setDisabled(true);
      return;
    }
    observer.emit('tour:condition');
    if (!calledByParent) {
      if ((ev.type === 'change' && ev.element && ev.element === 'field')
        || (ev.type === 'move' && typeof ev.newInputName === 'string')) {
        const duration = getNumField(blockObj, 'DURATION');
        const durationType = getListField(blockObj, 'DURATIONTYPE_LIST');
        if (duration !== '') {
          const minDuration = bot.symbol.getLimitation(blockObj.parentBlock_.type, blockObj.type).minDuration;
          if (!durationAccepted(duration + durationType, minDuration)) {
            observer.emit('ui.log.warn',
              translator.translateText('Minimum duration is') +
              ' ' + expandDuration(minDuration));
          } else {
            observer.emit('tour:ticks');
          }
          if (durationType === 't') {
            if (!isInteger(duration) || !isInRange(duration, 5, 10)) {
              observer.emit('ui.log.warn',
                translator.translateText('Number of ticks must be between 5 and 10'));
            } else {
              observer.emit('tour:ticks');
            }
          } else if (!isInteger(duration) || duration < 1) {
            observer.emit('ui.log.warn',
              translator.translateText('Expiry time cannot be equal to start time'));
          }
        }
        const prediction = getNumField(blockObj, 'PREDICTION');
        if (prediction !== '') {
          if (!isInteger(prediction) || !isInRange(prediction, 0, 9)) {
            observer.emit('ui.log.warn', translator.translateText('Prediction must be one digit'));
          }
        }
        for (const il of blockObj.inputList) {
          if (il.name !== '' && blockObj.getInputTargetBlock(il.name) === null) {
            return;
          }
        }
        observer.emit('tour:options');
      }
    }
  }
  blockObj.setDisabled(false);
};
export const submarket = (blockObj, ev) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (blockObj.childBlocks_.length > 0 && config.conditions.indexOf(blockObj.childBlocks_[0].type) < 0) {
    observer.emit('ui.log.warn', translator.translateText('Submarket blocks can only accept trade type blocks'));
    for (const child of Array.prototype.slice.apply(blockObj.childBlocks_)) {
      child.unplug();
    }
  } else if (blockObj.childBlocks_.length > 0) {
    condition(blockObj.childBlocks_[0], ev, true);
  }
  if (blockObj.parentBlock_ !== null) {
    if (blockObj.parentBlock_.type !== 'trade') {
      observer.emit('ui.log.warn',
        translator.translateText('Submarket blocks have to be added to the trade block'));
      blockObj.setDisabled(true);
      return;
    }
  }
  blockObj.setDisabled(false);
};
export const trade = (blockObj, ev) => {
  if (insideHolder(blockObj)) {
    return;
  }
  if (ev.type === 'create') {
    if (bot.symbol.findSymbol(Blockly.mainWorkspace.getBlockById(ev.blockId).type)) {
      observer.emit('tour:submarket_created');
    }
    if (config.conditions.indexOf(Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type) >= 0) {
      observer.emit('tour:condition_created');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'math_number') {
      observer.emit('tour:number');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'purchase') {
      observer.emit('tour:purchase_created');
    }
    if (Blockly.mainWorkspace.getBlockById(ev.blockId)
        .type === 'trade_again') {
      observer.emit('tour:trade_again_created');
    }
  }
  if (blockObj.childBlocks_.length && !bot.symbol.findSymbol(blockObj.childBlocks_[0].type)) {
    observer.emit('ui.log.warn',
      translator.translateText('The trade block can only accept submarket blocks'));
    for (const child of Array.prototype.slice.apply(blockObj.childBlocks_)) {
      child.unplug();
    }
  } else if (blockObj.childBlocks_.length > 0) {
    submarket(blockObj.childBlocks_[0], ev);
    observer.emit('tour:submarket');
    if ('newInputName' in ev) {
      utils.addPurchaseOptions();
    }
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (bot.symbol.findSymbol(topParent.type)
      || ['on_strategy', 'on_finish'].indexOf(topParent.type) >= 0) {
      observer.emit('ui.log.warn',
        translator.translateText('The trade block cannot be inside binary blocks'));
      blockObj.setDisabled(true);
      return;
    }
  }
  blockObj.setDisabled(false);
};
export const insideCondition = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (config.conditions.indexOf(blockObj.parentBlock_.type) < 0 && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added to the condition block'));
      blockObj.setDisabled(true);
      return;
    }
  }
  blockObj.setDisabled(false);
};
export const insideStrategy = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (topParent.type !== 'on_strategy' && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added inside the strategy block'));
      blockObj.setDisabled(true);
      return;
    } else if (blockObj.type === 'purchase') {
      observer.emit('tour:purchase');
    }
  }
  blockObj.setDisabled(false);
};
export const insideFinish = (blockObj, ev, name) => {
  if (insideHolder(blockObj)) {
    return;
  }
  const topParent = utils.findTopParentBlock(blockObj);
  if (topParent !== null) {
    if (topParent.type !== 'on_finish' && !ev.oldParentId) {
      observer.emit('ui.log.warn',
        name + ' ' + translator.translateText('must be added inside the finish block'));
      blockObj.setDisabled(true);
      return;
    }
    if (blockObj.type === 'trade_again') {
      observer.emit('tour:trade_again');
    }
  }
  blockObj.setDisabled(false);
};
<|endoftext|>


<commit_before>define(['app', 'text!./km-address.html','lodash', './km-inputtext-ml','./km-select'], function(app, template, _) { 'use strict';

	app.directive('kmAddress', ['$timeout','locale','$http','$filter',function ($timeout,locale,$http,$filter)
	{
		return {
			restrict: 'E',
			template : template,
			replace: true,
			transclude: true,
			scope: {
				placeholder: '@',
        ngDisabledFn: '&ngDisabled',
        binding: '=ngModel',
        locales: '=',
        required: "@",
        ngChange: "&",
	      validate: "&"
			},
			link: function ($scope, $element,$attr)//, $element, $attr
			{

						initGoogleAutoComplete();

						if($attr.embed) $scope.embed=$attr.embed;

						$scope.options={
								countries	: function() { return $http.get("/api/v2013/thesaurus/domains/countries/terms",            { cache: true }).then(function(o){ return $filter('orderBy')(o.data, 'name'); }); },
						};
						$scope.useGoogle=false;
						var killWatch = $scope.$watch("binding", function() {

								if(!$scope.binding) return;
								if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
									$scope.mapsUrl=_.find($scope.binding.websites,{name:'Google Maps'}).url;
								killWatch();
								if(!isEmpty)$scope.useGoogle=false;
						});

						$scope.$watch("binding.websites", function() {
									if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
											$scope.mapsUrl=_.find($scope.binding.websites,{name:'Google Maps'}).url
						});

						//============================================================
						//
						//============================================================
						 function initGoogleAutoComplete() {
							$timeout(function(){
				         var input = document.getElementById('google-ac-input');
								 if(!input)return;

				         var searchBox = new google.maps.places.Autocomplete(input);  // jshint ignore:line

								 searchBox.setTypes(['address']);
								 searchBox.addListener('place_changed', function() {
									 $timeout(function(){
										  var selectedPlace = searchBox.getPlace();
											loadGoogleData (selectedPlace );
											$timeout(function(){
												$scope.validate();
											});
									 });
				         });

							},100);
						}  //initMap

						//==================================
						//
						//==================================
						function loadGoogleData (selectedPlace ){

							if(!$scope.binding)$scope.binding={};
							$scope.binding.address				=	formatGoogleAddress(selectedPlace.address_components);
							$scope.binding.city						={};
							$scope.binding.city[locale]		=	getAddressCompnent(selectedPlace.address_components,'locality'); // city
							$scope.binding.state					={};
							$scope.binding.state[locale]	=	getAddressCompnent(selectedPlace.address_components,'administrative_area_level_1'); //state

							var country = getAddressCompnent(selectedPlace.address_components,'country','short_name').toLowerCase();

							$scope.binding.country 			=	{identifier:country};
							$scope.binding.postalCode		= {};
							$scope.binding.postalCode[locale] =	getAddressCompnent(selectedPlace.address_components,'postal_code');

							if($attr.embed ==='event'){
									$scope.binding.googleMapsUrl = selectedPlace.url;
									$scope.binding.googlePlaceId = selectedPlace.place_id;
									$scope.binding.geoLocation={};
									$scope.binding.geoLocation.lat=selectedPlace.geometry.location.lat();
									$scope.binding.geoLocation.lng=selectedPlace.geometry.location.lng();
						  }

							if($attr.embed ==='organization'){
								  $scope.binding.establishmentGooglePlaceId= selectedPlace.place_id;
									$scope.binding.phones				=[];
									$scope.binding.phones.push(selectedPlace.international_phone_number);

									$scope.mapsUrl=selectedPlace.url;
									if(selectedPlace.url)
									updateWebsites('Google Maps',selectedPlace.url);

									if(selectedPlace.website)
									updateWebsites('website',selectedPlace.website);

									$scope.binding.coordinates={};
									$scope.binding.coordinates.lat=selectedPlace.geometry.location.lat();
									$scope.binding.coordinates.lng=selectedPlace.geometry.location.lng();
							}
						}

						//==================================
						//
						//==================================
						function formatGoogleAddress(addressComponents){

							var formatedAddress = {};
							formatedAddress[locale]='';

							if(getAddressCompnent(addressComponents,'street_number'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'street_number')+', ';

							if(getAddressCompnent(addressComponents,'route'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'route')+', ';

							if(getAddressCompnent(addressComponents,'neighborhood'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'neighborhood')+', ';

							if(getAddressCompnent(addressComponents,'administrative_area_level_2'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'administrative_area_level_2')+', ';

							if(getAddressCompnent(addressComponents,'subpremise'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'subpremise')+', ';

							formatedAddress[locale]=formatedAddress[locale].slice(0,formatedAddress[locale].length-2);

							return formatedAddress;

						}

						//==================================
						//
						//==================================
						function isEmpty(){

							if($scope.binding && (($scope.embed==='event' && $scope.binding.googlePlaceId) || ($scope.embed==='organization' && $scope.binding.establishmentGooglePlaceId))){

								return false;
							}else {

								return true;
							}
						}
						$scope.isEmpty = isEmpty;

						//==================================
						//
						//==================================
						function getAddressCompnent(addressComponents,type,length){

							var returnVal = '';
							if(!length) length='long_name';
							else length='short_name';
							_.each(addressComponents,function(comp){
										if(comp.types.indexOf(type)>-1)
											returnVal = comp[length];
							});
							return returnVal;
						}

						//============================================================
						//
						//============================================================
						function updateWebsites (name,value) {
								if(!$scope.binding.websites) $scope.binding.websites =[];
								var site = _.find($scope.binding.websites,{'name':name});

								if(site)
										if(value)
											site.url=value;
										else
											delete($scope.binding.websites[_.findIndex($scope.binding.websites,{'name':name})]);

								else
									 $scope.binding.websites.push({name:name,url:value,type:'link'});

								if(name==='website'){
									$scope.website=value;
									if(!$scope.binding.profileLink || !Array.isArray($scope.binding.profileLink ))
									$scope.binding.profileLink =[];
									$scope.binding.profileLink.push({name:name,url:value,type:'link'});
								}
								$scope.binding.websites=_.compact($scope.binding.websites);
						}
						$scope.updateWebsites=updateWebsites;

						//==============================
						//
						//
						//==============================
						function clearSlacesSearch (){
								 $scope.selectedPlace='';
								 $scope.placeSearch='';
								 $scope.noPredictions=false;
								 delete($scope.binding.address);
								 delete($scope.binding.city);
								 delete($scope.binding.state);
								 delete($scope.binding.country);
								 delete($scope.binding.phones);
								 delete($scope.binding.websites);
								 delete($scope.binding.phones);
								 delete($scope.binding.postalCode);
								 delete($scope.binding.coordinates);
								 delete($scope.binding.coordinates);
								 delete($scope.binding.googlePlaceId);
								 delete($scope.mapsUrl);
								 if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
									 $scope.binding.websites.slice(_.find($scope.binding.websites,{name:'Google Maps'}));
						}
						$scope.clearSlacesSearch=clearSlacesSearch;
			},
			// controller: function ($scope)
			// {
			//
			// }
		};
	}]);
});

<commit_msg>ensure search search not just addresses<commit_after>define(['app', 'text!./km-address.html','lodash', './km-inputtext-ml','./km-select'], function(app, template, _) { 'use strict';

	app.directive('kmAddress', ['$timeout','locale','$http','$filter',function ($timeout,locale,$http,$filter)
	{
		return {
			restrict: 'E',
			template : template,
			replace: true,
			transclude: true,
			scope: {
				placeholder: '@',
        ngDisabledFn: '&ngDisabled',
        binding: '=ngModel',
        locales: '=',
        required: "@",
        ngChange: "&",
	      validate: "&"
			},
			link: function ($scope, $element,$attr)//, $element, $attr
			{

						initGoogleAutoComplete();

						if($attr.embed) $scope.embed=$attr.embed;

						$scope.options={
								countries	: function() { return $http.get("/api/v2013/thesaurus/domains/countries/terms",            { cache: true }).then(function(o){ return $filter('orderBy')(o.data, 'name'); }); },
						};
						$scope.useGoogle=false;
						var killWatch = $scope.$watch("binding", function() {

								if(!$scope.binding) return;
								if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
									$scope.mapsUrl=_.find($scope.binding.websites,{name:'Google Maps'}).url;
								killWatch();
								if(!isEmpty)$scope.useGoogle=false;
						});

						$scope.$watch("binding.websites", function() {
									if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
											$scope.mapsUrl=_.find($scope.binding.websites,{name:'Google Maps'}).url
						});

						//============================================================
						//
						//============================================================
						 function initGoogleAutoComplete() {
							$timeout(function(){
				         var input = document.getElementById('google-ac-input');
								 if(!input)return;

				         var searchBox = new google.maps.places.Autocomplete(input);  // jshint ignore:line

								 searchBox.setTypes([]);
								 searchBox.addListener('place_changed', function() {
									 $timeout(function(){
										  var selectedPlace = searchBox.getPlace();
											loadGoogleData (selectedPlace );
											$timeout(function(){
												$scope.validate();
											});
									 });
				         });

							},100);
						}  //initMap

						//==================================
						//
						//==================================
						function loadGoogleData (selectedPlace ){

							if(!$scope.binding)$scope.binding={};
							$scope.binding.address				=	formatGoogleAddress(selectedPlace.address_components);
							$scope.binding.city						={};
							$scope.binding.city[locale]		=	getAddressCompnent(selectedPlace.address_components,'locality'); // city
							$scope.binding.state					={};
							$scope.binding.state[locale]	=	getAddressCompnent(selectedPlace.address_components,'administrative_area_level_1'); //state

							var country = getAddressCompnent(selectedPlace.address_components,'country','short_name').toLowerCase();

							$scope.binding.country 			=	{identifier:country};
							$scope.binding.postalCode		= {};
							$scope.binding.postalCode[locale] =	getAddressCompnent(selectedPlace.address_components,'postal_code');

							if($attr.embed ==='event'){
									$scope.binding.googleMapsUrl = selectedPlace.url;
									$scope.binding.googlePlaceId = selectedPlace.place_id;
									$scope.binding.geoLocation={};
									$scope.binding.geoLocation.lat=selectedPlace.geometry.location.lat();
									$scope.binding.geoLocation.lng=selectedPlace.geometry.location.lng();
						  }

							if($attr.embed ==='organization'){
								  $scope.binding.establishmentGooglePlaceId= selectedPlace.place_id;
									$scope.binding.phones				=[];
									$scope.binding.phones.push(selectedPlace.international_phone_number);

									$scope.mapsUrl=selectedPlace.url;
									if(selectedPlace.url)
									updateWebsites('Google Maps',selectedPlace.url);

									if(selectedPlace.website)
									updateWebsites('website',selectedPlace.website);

									$scope.binding.coordinates={};
									$scope.binding.coordinates.lat=selectedPlace.geometry.location.lat();
									$scope.binding.coordinates.lng=selectedPlace.geometry.location.lng();
							}
						}

						//==================================
						//
						//==================================
						function formatGoogleAddress(addressComponents){

							var formatedAddress = {};
							formatedAddress[locale]='';

							if(getAddressCompnent(addressComponents,'street_number'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'street_number')+', ';

							if(getAddressCompnent(addressComponents,'route'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'route')+', ';

							if(getAddressCompnent(addressComponents,'neighborhood'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'neighborhood')+', ';

							if(getAddressCompnent(addressComponents,'administrative_area_level_2'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'administrative_area_level_2')+', ';

							if(getAddressCompnent(addressComponents,'subpremise'))
									formatedAddress[locale]+=	getAddressCompnent(addressComponents,'subpremise')+', ';

							formatedAddress[locale]=formatedAddress[locale].slice(0,formatedAddress[locale].length-2);

							return formatedAddress;

						}

						//==================================
						//
						//==================================
						function isEmpty(){

							if($scope.binding && (($scope.embed==='event' && $scope.binding.googlePlaceId) || ($scope.embed==='organization' && $scope.binding.establishmentGooglePlaceId))){

								return false;
							}else {

								return true;
							}
						}
						$scope.isEmpty = isEmpty;

						//==================================
						//
						//==================================
						function getAddressCompnent(addressComponents,type,length){

							var returnVal = '';
							if(!length) length='long_name';
							else length='short_name';
							_.each(addressComponents,function(comp){
										if(comp.types.indexOf(type)>-1)
											returnVal = comp[length];
							});
							return returnVal;
						}

						//============================================================
						//
						//============================================================
						function updateWebsites (name,value) {
								if(!$scope.binding.websites) $scope.binding.websites =[];
								var site = _.find($scope.binding.websites,{'name':name});

								if(site)
										if(value)
											site.url=value;
										else
											delete($scope.binding.websites[_.findIndex($scope.binding.websites,{'name':name})]);

								else
									 $scope.binding.websites.push({name:name,url:value,type:'link'});

								if(name==='website'){
									$scope.website=value;
									if(!$scope.binding.profileLink || !Array.isArray($scope.binding.profileLink ))
									$scope.binding.profileLink =[];
									$scope.binding.profileLink.push({name:name,url:value,type:'link'});
								}
								$scope.binding.websites=_.compact($scope.binding.websites);
						}
						$scope.updateWebsites=updateWebsites;

						//==============================
						//
						//
						//==============================
						function clearSlacesSearch (){
								 $scope.selectedPlace='';
								 $scope.placeSearch='';
								 $scope.noPredictions=false;
								 delete($scope.binding.address);
								 delete($scope.binding.city);
								 delete($scope.binding.state);
								 delete($scope.binding.country);
								 delete($scope.binding.phones);
								 delete($scope.binding.websites);
								 delete($scope.binding.phones);
								 delete($scope.binding.postalCode);
								 delete($scope.binding.coordinates);
								 delete($scope.binding.coordinates);
								 delete($scope.binding.googlePlaceId);
								 delete($scope.mapsUrl);
								 if($scope.binding && $scope.binding.websites && _.find($scope.binding.websites,{name:'Google Maps'}))
									 $scope.binding.websites.slice(_.find($scope.binding.websites,{name:'Google Maps'}));
						}
						$scope.clearSlacesSearch=clearSlacesSearch;
			},
			// controller: function ($scope)
			// {
			//
			// }
		};
	}]);
});

<|endoftext|>