<commit_before>'use strict';

var angular = require('angular');
var directives = require('../scripts/modules').directives;
var L = require('leaflet');

angular.module(directives.name).directive('leafletMap', function ($q, DistrictResource, OutpatientVisitResource,
                                                                  $timeout) {

  return {
    restrict: 'E',
    scope: {
      options: '=?',
      queryString: '=',
      filters: '=',
      data: '='
    },
    link: function postLink (scope, element) {

      var baseMapURL = 'https://otile{s}-s.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png';
      // if they ever shut down the HTTPs version, here's the HTTP url:
      //var baseMapURL = 'http://ttiles0{s}.mqcdn.com/tiles/1.0.0/vy/map/{z}/{x}/{y}.png';

      var getOverlayStyle = function (count) {
        var style = {
          weight: 1,
          opacity: 1,
          color: 'white',
          dashArray: '1',
          fillOpacity: 0.7,
          fillColor: '#FFEDA0'
        };
        if (arguments.length !== 0) {
          // TODO dynamic quartiles, maybe using d3's palette?
          style.fillColor = count > 100 ? '#800026' :
                   count > 75 ? '#BD0026' :
                   count > 50 ? '#E31A1C' :
                   count > 20 ? '#FC4E2A' :
                   count > 10 ? '#FD8D3C' :
                   count > 5 ? '#FEB24C' :
                   count > 2 ? '#FED976' :
                   '#FFEDA0';
        }

        return style;
      };

      var baseLayer = L.tileLayer(baseMapURL, {
        subdomains: '1234',
        attribution: 'Map data © OpenStreetMap | ' +
          'Tiles Courtesy of MapQuest '
      });

      // don't wait for data to build map and fetch base layer tiles
      var map = L.map(element.children()[0], {
        center: new L.LatLng(41.4289788, -96.8634425),
        zoom: 7,
        layers: [baseLayer]
      });
      L.control.scale().addTo(map);

      //separating out the polygon request
      var getLayerPolys = function () {
        var deferred = $q.defer();

        // could also use $http's promise, but I can never figure out ngResource's API
        DistrictResource.get({
          size: 9999
        }, function (response) {
          var layers = {}; // map of District name -> layer

          var polygons = response.results.reduce(function (previous, current) {
            var geometry = current._source.geometry;
            if (geometry) {
              var coordinates = geometry.coordinates[0].map(function (lonlat) {
                // GeoJSON uses LonLat instead of LatLon
                return L.latLng(lonlat[1], lonlat[0]);
              });
              var layer = L.polygon(coordinates, getOverlayStyle());

              // inspired by http://leafletjs.com/examples/choropleth.html
              layer.on('click', function (e) {
                map.fitBounds(e.target.getBounds());
              });
              layer.on('mouseover', function (e) {
                var layer = e.target;

                layer.setStyle({
                  weight: 5,
                  color: '#666',
                  dashArray: '',
                  fillOpacity: 0.7
                });

                if (!L.Browser.ie && !L.Browser.opera) {
                  layer.bringToFront();
                }
              });
              layer.on('mouseout', function (e) {
                var layer = e.target;

                layer.setStyle({
                  weight: 1,
                  dashArray: '1',
                  color: 'white',
                  fillOpacity: 0.7
                });
                if (!L.Browser.ie && !L.Browser.opera) {
                  layer.bringToBack();
                }
              });

              layers[current._source.name] = layer;

              previous.push(layer);
            }

            return previous;
          }, []);

          var overlay = L.featureGroup(polygons);
          overlay.addTo(map);

          deferred.resolve(layers);
        }, function (response) {
          deferred.reject(response);
        });

        return deferred.promise;
      };

      var polys = getLayerPolys();

      scope.$watch('queryString', function (queryString) {
        OutpatientVisitResource.search({
          q: queryString,
          aggregations: {
            district: {
              terms: {
                field: 'medicalFacility.district.raw',
                size: 0 // don't cap number of buckets
              }
            }
          }
        }, function (response) {
          polys.then(function (districts) {
            response.aggregations.district.buckets.forEach(function (bucket) {
              /*jshint camelcase:false */
              var district = districts[bucket.key];
              if (district) { // not all districts have geometries
                district.setStyle(getOverlayStyle(bucket.doc_count));
              }
            });
          });
        });
      });

      scope.$watch('options.width', function () {
        map.invalidateSize();
      });

      scope.$watch('options.height', function () {
        if (scope.timeId) {
          $timeout.cancel(scope.timeId);
          scope.timeId = null;
        }
        scope.timeId = $timeout(function () {
          element.find('.map').css({
            height: scope.options.height + 6
          });
          map.invalidateSize();
        }, 200);
      });
    }
  };
});
<commit_msg>Map clickthroughs<commit_after>'use strict';

var angular = require('angular');
var directives = require('../scripts/modules').directives;
var L = require('leaflet');

angular.module(directives.name).directive('leafletMap', function ($q, DistrictResource, OutpatientVisitResource,
                                                                  $timeout, $rootScope) {

  return {
    restrict: 'E',
    scope: {
      options: '=?',
      queryString: '=',
      filters: '=',
      data: '='
    },
    link: function postLink (scope, element) {

      var baseMapURL = 'https://otile{s}-s.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png';
      // if they ever shut down the HTTPs version, here's the HTTP url:
      //var baseMapURL = 'http://ttiles0{s}.mqcdn.com/tiles/1.0.0/vy/map/{z}/{x}/{y}.png';

      var getOverlayStyle = function (count) {
        var style = {
          weight: 1,
          opacity: 1,
          color: 'white',
          dashArray: '1',
          fillOpacity: 0.7,
          fillColor: '#FFEDA0'
        };
        if (arguments.length !== 0) {
          // TODO dynamic quartiles, maybe using d3's palette?
          style.fillColor = count > 100 ? '#800026' :
                   count > 75 ? '#BD0026' :
                   count > 50 ? '#E31A1C' :
                   count > 20 ? '#FC4E2A' :
                   count > 10 ? '#FD8D3C' :
                   count > 5 ? '#FEB24C' :
                   count > 2 ? '#FED976' :
                   '#FFEDA0';
        }

        return style;
      };

      var baseLayer = L.tileLayer(baseMapURL, {
        subdomains: '1234',
        attribution: 'Map data © OpenStreetMap | ' +
          'Tiles Courtesy of MapQuest '
      });

      // don't wait for data to build map and fetch base layer tiles
      var map = L.map(element.children()[0], {
        center: new L.LatLng(41.4289788, -96.8634425),
        zoom: 7,
        layers: [baseLayer]
      });
      L.control.scale().addTo(map);

      //separating out the polygon request
      var getLayerPolys = function () {
        var deferred = $q.defer();

        // could also use $http's promise, but I can never figure out ngResource's API
        DistrictResource.get({
          size: 9999
        }, function (response) {
          var layers = {}; // map of District name -> layer

          var polygons = response.results.reduce(function (previous, current) {
            var geometry = current._source.geometry;
            if (geometry) {
              var coordinates = geometry.coordinates[0].map(function (lonlat) {
                // GeoJSON uses LonLat instead of LatLon
                return L.latLng(lonlat[1], lonlat[0]);
              });
              var layer = L.polygon(coordinates, getOverlayStyle());
              layer.oeName = current._source.name;

              // inspired by http://leafletjs.com/examples/choropleth.html
              layer.on('click', function (e) {
                // TODO this leaves the map with a lot of 0 count districts that should be unshaded
                map.fitBounds(e.target.getBounds());
                var filter = {
                  filterId: 'districts',
                  value: layer.oeName
                };
                $rootScope.$emit('filterChange', filter, true, true);

              });
              layer.on('mouseover', function (e) {
                var layer = e.target;

                layer.setStyle({
                  weight: 5,
                  color: '#666',
                  dashArray: '',
                  fillOpacity: 0.7
                });

                if (!L.Browser.ie && !L.Browser.opera) {
                  layer.bringToFront();
                }
              });
              layer.on('mouseout', function (e) {
                var layer = e.target;

                layer.setStyle({
                  weight: 1,
                  dashArray: '1',
                  color: 'white',
                  fillOpacity: 0.7
                });
                if (!L.Browser.ie && !L.Browser.opera) {
                  layer.bringToBack();
                }
              });

              layers[current._source.name] = layer;

              previous.push(layer);
            }

            return previous;
          }, []);

          var overlay = L.featureGroup(polygons);
          overlay.addTo(map);

          deferred.resolve(layers);
        }, function (response) {
          deferred.reject(response);
        });

        return deferred.promise;
      };

      var polys = getLayerPolys();

      scope.$watch('queryString', function (queryString) {
        OutpatientVisitResource.search({
          q: queryString,
          aggregations: {
            district: {
              terms: {
                field: 'medicalFacility.district.raw',
                size: 0 // don't cap number of buckets
              }
            }
          }
        }, function (response) {
          polys.then(function (districts) {
            // reset styles
            angular.forEach(districts, function(district) {
              district.setStyle(getOverlayStyle(0));
            });
            // re-apply styles for query results
            response.aggregations.district.buckets.forEach(function (bucket) {
              /*jshint camelcase:false */
              var district = districts[bucket.key];
              if (district) { // not all districts have geometries
                district.setStyle(getOverlayStyle(bucket.doc_count));
              }
            });
          });
        });
      });

      scope.$watch('options.width', function () {
        map.invalidateSize();
      });

      scope.$watch('options.height', function () {
        if (scope.timeId) {
          $timeout.cancel(scope.timeId);
          scope.timeId = null;
        }
        scope.timeId = $timeout(function () {
          element.find('.map').css({
            height: scope.options.height + 6
          });
          map.invalidateSize();
        }, 200);
      });
    }
  };
});
<|endoftext|>


<commit_before>'use strict';

var Promise = require('es6-promise').Promise;
var AWS = require('aws-sdk');

var _toJSONString = function(input) {
  var inputError = new Error('Error: Invalid Input. Please supply a JSON string or JSON serializable object');

  if(input === null) {
    throw inputError;
  }

  if (typeof input === 'string') {
    try {
      JSON.parse(input);
      return input;
    }
    catch(e) {
      throw inputError;
    }
  }

  if(typeof input === 'object') {
    try {
      return JSON.stringify(input);
    } catch(e){
     throw inputError;
    }
  }

  throw inputError;
}

var PushQueue = module.exports = function(config) {
  // Instantiate SQS client
  this.config = config;

  this.sqs = new AWS.SQS(
    { accessKeyId: this.config.accessKeyId
    , secretAccessKey: this.config.secretAccessKey
    , region: this.config.region
    , apiVersions: { sqs: '2012-11-05' }
    });
}

PushQueue.prototype.post = function(message) {
  var _this = this;
  var params =
    { MessageBody: _toJSONString(message)
    , QueueUrl: this.config.queueUrl
    };

  return new Promise(function postPromise(resolve, reject) {
    _this.sqs.sendMessage(params, function(err, data) {
      if (err) {
        reject(err);
      }
      else {
        resolve(data);
      }
    });
  });
}

PushQueue.prototype.receive = function() {
  var _this = this;

  return new Promise(function PromiseCallback(resolve, reject) {
    var params =
      { QueueUrl: process.env.SQS_QUEUE_URL /* required */
      , AttributeNames: ['All']
      , MaxNumberOfMessages: 1
      , WaitTimeSeconds: 20
      };

    _this.sqs.receiveMessage(params, function receiveMessageCallback(err, data) {

      if (err) {
        reject(err);
      }
      else if(!data.Messages) {
        reject();
      }
      else { // success

        try {

          resolve(
            { id: data.Messages[0].ReceiptHandle
            , body: JSON.parse(data.Messages[0].Body)
            }
          );
        }
        catch(e) {
          reject("Malformed JSON in response message")
        }
      }
    });

  });
}

PushQueue.prototype.delete = function(id) {
  var _this = this;

  return new Promise( function(resolve, reject) {
    var params =
      { QueueUrl: process.env.SQS_QUEUE_URL
      , ReceiptHandle: id
      };

    _this.sqs.deleteMessage(params, function deleteCallback(err, data) {
      if (err) {
        reject(err);
      }
      else {
        resolve();
      }
    });
  });
}

<commit_msg>forgot some references to env<commit_after>'use strict';

var Promise = require('es6-promise').Promise;
var AWS = require('aws-sdk');

var _toJSONString = function(input) {
  var inputError = new Error('Error: Invalid Input. Please supply a JSON string or JSON serializable object');

  if(input === null) {
    throw inputError;
  }

  if (typeof input === 'string') {
    try {
      JSON.parse(input);
      return input;
    }
    catch(e) {
      throw inputError;
    }
  }

  if(typeof input === 'object') {
    try {
      return JSON.stringify(input);
    } catch(e){
     throw inputError;
    }
  }

  throw inputError;
}

var PushQueue = module.exports = function(config) {
  // Instantiate SQS client
  this.config = config;

  this.sqs = new AWS.SQS(
    { accessKeyId: this.config.accessKeyId
    , secretAccessKey: this.config.secretAccessKey
    , region: this.config.region
    , apiVersions: { sqs: '2012-11-05' }
    });
}

PushQueue.prototype.post = function(message) {
  var _this = this;
  var params =
    { MessageBody: _toJSONString(message)
    , QueueUrl: this.config.queueUrl
    };

  return new Promise(function postPromise(resolve, reject) {
    _this.sqs.sendMessage(params, function(err, data) {
      if (err) {
        reject(err);
      }
      else {
        resolve(data);
      }
    });
  });
}

PushQueue.prototype.receive = function() {
  var _this = this;

  return new Promise(function PromiseCallback(resolve, reject) {
    var params =
      { QueueUrl: this.config.queueUrl /* required */
      , AttributeNames: ['All']
      , MaxNumberOfMessages: 1
      , WaitTimeSeconds: 20
      };

    _this.sqs.receiveMessage(params, function receiveMessageCallback(err, data) {

      if (err) {
        reject(err);
      }
      else if(!data.Messages) {
        reject();
      }
      else { // success

        try {

          resolve(
            { id: data.Messages[0].ReceiptHandle
            , body: JSON.parse(data.Messages[0].Body)
            }
          );
        }
        catch(e) {
          reject("Malformed JSON in response message")
        }
      }
    });

  });
}

PushQueue.prototype.delete = function(id) {
  var _this = this;

  return new Promise( function(resolve, reject) {
    var params =
      { QueueUrl: this.config.queueUrl
      , ReceiptHandle: id
      };

    _this.sqs.deleteMessage(params, function deleteCallback(err, data) {
      if (err) {
        reject(err);
      }
      else {
        resolve();
      }
    });
  });
}

<|endoftext|>


<commit_before>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 100,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        if(this.currentLoop == 0) {
            this.clear();
        }

        console.log('calling roll');
        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                console.log('setting timeout', i);
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {

                    if(this.currentLoop < this.loops) {
                        console.log('incrementing loop', this.currentLoop);
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        console.log('filling with white');
                        this.currentLoop = 0;
                        this.defaultColor();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
        this.update();
    },
    allBlue: function() {
        this.fill(0, 0, 255);
        this.update();
    },
    defaultColor: function() {
      this.allBlue();
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    sign.defaultColor();

    // We have passed a custom command, lets make sure we call that
    setTimeout(function() {
        sign[args[0]]()
    }, 5000);

}
else
{
    // Sign defaults to
    sign.defaultColor();
}
<commit_msg>defualt color<commit_after>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 100,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        if(this.currentLoop == 0) {
            this.clear();
        }

        console.log('calling roll');
        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                console.log('setting timeout', i);
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {

                    if(this.currentLoop < this.loops) {
                        console.log('incrementing loop', this.currentLoop);
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        console.log('filling with white');
                        this.currentLoop = 0;
                        this.defaultColor();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
        this.update();
    },
    allBlue: function() {
        this.fill(0, 0, 255);
        this.update();
    },
    allRed: function() {
        this.fill(255,0,0);
    },
    allGreen: function() {
        this.fill(0,255,0);
    },
    defaultColor: function() {
      this.allRed();
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    sign.defaultColor();

    // We have passed a custom command, lets make sure we call that
    setTimeout(function() {
        sign[args[0]]()
    }, 5000);

}
else
{
    // Sign defaults to
    sign.defaultColor();
}
<|endoftext|>


<commit_before>(function () {
    var cogClass = function () {};
    cogClass.prototype.exec = function (params, request, response) {
        var oops = this.utils.apiError;
        var classID = params.classid;
        var quizNumber = params.quizno;
        var questionNumber = params.questionno;
        var data = params.data;
        var strings = data.questions.slice();
        strings.push(data.rubric);
        var sys = this.sys;
        // data is:
        // {
        //   rubric: str
        //   questions: lst
        //   correct: num
        // }
        var sys = this.sys;
        var utils = this.utils;
        // START OVER
        var qObj = {
            haveStringId:{},
            needStringId:{},
            needStringIdList:[],
            choiceIdList:[null,null,null,null]
        };
        beginTransaction();

        function beginTransaction () {
            sys.db.run('BEGIN TRANSACTION',function(err){
                checkQuiz();
            })
        };

        // Check for existence of quiz, create if necessary, get ID
        function checkQuiz () {
            var sql = 'SELECT quizID FROM quizzes WHERE classID=? AND quizNumber=?;';
            sys.db.get(sql,[classID,quizNumber],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(1)')}
                if (row && row.quizID) {
                    qObj.quizID = row.quizID;
                    checkStrings(0,5);
                } else {
                    createQuiz();
                }
            });
        }
        function createQuiz () {
            var sql = 'INSERT INTO quizzes VALUES(NULL,?,?,0,NULL,NULL);'
            sys.db.run(sql,[classID,quizNumber],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(2)')};
                qObj.quizID = this.lastID;
                checkStrings(0,5);
            });
        };

        // Check for existence of strings, create if necessary, save IDs
        function checkStrings (pos,limit) {
            var sql = 'SELECT stringID FROM strings WHERE string=?;'
            var string = strings[pos];
            sys.db.get(sql,[string],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(3)')};
                if (row && row.stringID) {
                    qObj.haveStringId[pos] = row.stringID;
                } else {
                    qObj.needStringId[pos] = strings[pos];
                    qObj.needStringIdList.push(pos);
                }
                pos += 1;
                if (pos == limit) {
                    createStrings(0,qObj.needStringIdList.length);
                } else {
                    checkStrings(pos,limit);
                }
            });
        };
        function createStrings (pos,limit) {
            if (pos < limit) {
                var sql = 'INSERT INTO strings VALUES (NULL,?)';
                var key = qObj.needStringIdList[pos];
                var string = qObj.needStringId[key];
                sys.db.run(sql,[string],function(err){
                    if (err) {return oops(response,err,'quiz/writeonequestion(4)')};
                    qObj.haveStringId[key] = this.lastID;
                    pos += 1;
                    createStrings(pos,limit);
                });
            } else {
                checkQuestionNumber();
            }
        };

        // Check for existence of question, create if necessary, save ID
        function checkQuestionNumber () {
            if (questionNumber == 0) {
                makeQuestionNumber();
            } else {
                qObj.questionNumber = questionNumber;
                checkQuestion();
            }
        };
        function makeQuestionNumber () {
            var sql = 'SELECT MAX(questionNumber) AS questionMax FROM quizzes JOIN questions USING(quizID) WHERE quizID=?'
            sys.db.get(sql,[qObj.quizID],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(5)')};
                if (row && row.questionMax) {
                    qObj.questionNumber = (row.questionMax + 1);
                } else {
                    qObj.questionNumber = 1;
                }
                createQuestion();
            });
        };
        function createQuestion () {
            // Jumps to checkChoices
            var sql = 'INSERT INTO questions VALUES (NULL,?,?,?,?);'
            var quizID = qObj.quizID;
            var questionNumber = qObj.questionNumber;
            var correct = data.correct;
            var rubricID = qObj.haveStringId[4];
            sys.db.run(sql,[quizID,questionNumber,correct,rubricID],function (err) {
                if (err) {return oops(response,err,'quiz/writeonequestion(6)')};
                qObj.questionID = this.lastID;
                checkChoices();
            });
        };
        function checkQuestion () {
            // To updateQuestion
            var sql = 'SELECT questionID FROM questions WHERE quizID=? AND questionNumber=?;';
            var quizID = qObj.quizID;
            var questionNumber = qObj.questionNumber;
            sys.db.get(sql,[quizID,questionNumber],function(err,row){
                if (err||!row) {return oops(response,err,'quiz/writeonequestion(7)')};
                qObj.questionID = row.questionID;
                updateQuestion();
            });
        };
        function updateQuestion () {
            // To checkChoices
            var sql = 'UPDATE questions SET stringID=?,correct=? WHERE questionID=?;';
            var stringID = qObj.haveStringId[4];
            var correct = data.correct;
            var questionID = qObj.questionID;
            sys.db.run(sql,[stringID,correct,questionID],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(8)')};
                checkChoices();
            });
        };
        function checkChoices() {
            // To writeChoices
            var sql = "SELECT choice,choiceID FROM choices WHERE questionID=? ORDER BY choice;";
            var questionID = qObj.questionID;
            console.log("SEARCHING FOR questionID="+qObj.questionID);
            sys.db.get(sql,[questionID],function(err,rows){
                if (err) {return oops(response,err,'quiz/writeonequestion(9)')}
                for (var i=0,ilen=rows.length;i<ilen;i+=1) {
                    var row = rows[i];
                    console.log("  SETTING "+row.choice+" to choiceID "+row.choiceID);
                    qObj.choiceIdList[row.choice] = row.choiceID;
                }
                writeChoices(0,4);
            });
        };

        // Insert or replace is good enough for choices
        function writeChoices(pos,limit) {
            var sql = 'INSERT OR REPLACE INTO choices VALUES (?,?,?,?)';
            var choiceID = qObj.choiceIdList[pos];
            var questionID = qObj.questionID;
            var choice = pos;
            var stringID = qObj.haveStringId[pos];
            console.log("LOOK: choiceID="+choiceID+" questionID="+questionID+" choice="+choice+" stringID="+stringID);
            sys.db.run(sql,[choiceID,questionID,choice,stringID],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(10)')};
                pos += 1;
                if (pos == limit) {
                    endTransaction();
                } else {
                    writeChoices(pos,limit);
                }
            });
        };
        function endTransaction () {
            sys.db.run('END TRANSACTION',function(){
                response.writeHead(200, {'Content-Type': 'application/json'});
                response.end(JSON.stringify(qObj.questionNumber));
            })
        };
    }
    exports.cogClass = cogClass;
})();
<commit_msg>More twiddles still<commit_after>(function () {
    var cogClass = function () {};
    cogClass.prototype.exec = function (params, request, response) {
        var oops = this.utils.apiError;
        var classID = params.classid;
        var quizNumber = params.quizno;
        var questionNumber = params.questionno;
        var data = params.data;
        var strings = data.questions.slice();
        strings.push(data.rubric);
        var sys = this.sys;
        // data is:
        // {
        //   rubric: str
        //   questions: lst
        //   correct: num
        // }
        var sys = this.sys;
        var utils = this.utils;
        // START OVER
        var qObj = {
            haveStringId:{},
            needStringId:{},
            needStringIdList:[],
            choiceIdList:[null,null,null,null]
        };
        beginTransaction();

        function beginTransaction () {
            sys.db.run('BEGIN TRANSACTION',function(err){
                checkQuiz();
            })
        };

        // Check for existence of quiz, create if necessary, get ID
        function checkQuiz () {
            var sql = 'SELECT quizID FROM quizzes WHERE classID=? AND quizNumber=?;';
            sys.db.get(sql,[classID,quizNumber],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(1)')}
                if (row && row.quizID) {
                    qObj.quizID = row.quizID;
                    checkStrings(0,5);
                } else {
                    createQuiz();
                }
            });
        }
        function createQuiz () {
            var sql = 'INSERT INTO quizzes VALUES(NULL,?,?,0,NULL,NULL);'
            sys.db.run(sql,[classID,quizNumber],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(2)')};
                qObj.quizID = this.lastID;
                checkStrings(0,5);
            });
        };

        // Check for existence of strings, create if necessary, save IDs
        function checkStrings (pos,limit) {
            var sql = 'SELECT stringID FROM strings WHERE string=?;'
            var string = strings[pos];
            sys.db.get(sql,[string],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(3)')};
                if (row && row.stringID) {
                    qObj.haveStringId[pos] = row.stringID;
                } else {
                    qObj.needStringId[pos] = strings[pos];
                    qObj.needStringIdList.push(pos);
                }
                pos += 1;
                if (pos == limit) {
                    createStrings(0,qObj.needStringIdList.length);
                } else {
                    checkStrings(pos,limit);
                }
            });
        };
        function createStrings (pos,limit) {
            if (pos < limit) {
                var sql = 'INSERT INTO strings VALUES (NULL,?)';
                var key = qObj.needStringIdList[pos];
                var string = qObj.needStringId[key];
                sys.db.run(sql,[string],function(err){
                    if (err) {return oops(response,err,'quiz/writeonequestion(4)')};
                    qObj.haveStringId[key] = this.lastID;
                    pos += 1;
                    createStrings(pos,limit);
                });
            } else {
                checkQuestionNumber();
            }
        };

        // Check for existence of question, create if necessary, save ID
        function checkQuestionNumber () {
            if (questionNumber == 0) {
                makeQuestionNumber();
            } else {
                qObj.questionNumber = questionNumber;
                checkQuestion();
            }
        };
        function makeQuestionNumber () {
            var sql = 'SELECT MAX(questionNumber) AS questionMax FROM quizzes JOIN questions USING(quizID) WHERE quizID=?'
            sys.db.get(sql,[qObj.quizID],function(err,row){
                if (err) {return oops(response,err,'quiz/writeonequestion(5)')};
                if (row && row.questionMax) {
                    qObj.questionNumber = (row.questionMax + 1);
                } else {
                    qObj.questionNumber = 1;
                }
                createQuestion();
            });
        };
        function createQuestion () {
            // Jumps to checkChoices
            var sql = 'INSERT INTO questions VALUES (NULL,?,?,?,?);'
            var quizID = qObj.quizID;
            var questionNumber = qObj.questionNumber;
            var correct = data.correct;
            var rubricID = qObj.haveStringId[4];
            sys.db.run(sql,[quizID,questionNumber,correct,rubricID],function (err) {
                if (err) {return oops(response,err,'quiz/writeonequestion(6)')};
                qObj.questionID = this.lastID;
                checkChoices();
            });
        };
        function checkQuestion () {
            // To updateQuestion
            var sql = 'SELECT questionID FROM questions WHERE quizID=? AND questionNumber=?;';
            var quizID = qObj.quizID;
            var questionNumber = qObj.questionNumber;
            sys.db.get(sql,[quizID,questionNumber],function(err,row){
                if (err||!row) {return oops(response,err,'quiz/writeonequestion(7)')};
                qObj.questionID = row.questionID;
                updateQuestion();
            });
        };
        function updateQuestion () {
            // To checkChoices
            var sql = 'UPDATE questions SET stringID=?,correct=? WHERE questionID=?;';
            var stringID = qObj.haveStringId[4];
            var correct = data.correct;
            var questionID = qObj.questionID;
            sys.db.run(sql,[stringID,correct,questionID],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(8)')};
                checkChoices();
            });
        };
        function checkChoices() {
            // To writeChoices
            var sql = "SELECT choice,choiceID FROM choices WHERE questionID=? ORDER BY choice;";
            var questionID = qObj.questionID;
            console.log("SEARCHING FOR questionID="+qObj.questionID);
            sys.db.all(sql,[questionID],function(err,rows){
                if (err) {return oops(response,err,'quiz/writeonequestion(9)')}
                console.log("ROWS LENGTH: "+rows);
                for (var i=0,ilen=rows.length;i<ilen;i+=1) {
                    var row = rows[i];
                    console.log("  SETTING "+row.choice+" to choiceID "+row.choiceID);
                    qObj.choiceIdList[row.choice] = row.choiceID;
                }
                writeChoices(0,4);
            });
        };

        // Insert or replace is good enough for choices
        function writeChoices(pos,limit) {
            var sql = 'INSERT OR REPLACE INTO choices VALUES (?,?,?,?)';
            var choiceID = qObj.choiceIdList[pos];
            var questionID = qObj.questionID;
            var choice = pos;
            var stringID = qObj.haveStringId[pos];
            console.log("LOOK: choiceID="+choiceID+" questionID="+questionID+" choice="+choice+" stringID="+stringID);
            sys.db.run(sql,[choiceID,questionID,choice,stringID],function(err){
                if (err) {return oops(response,err,'quiz/writeonequestion(10)')};
                pos += 1;
                if (pos == limit) {
                    endTransaction();
                } else {
                    writeChoices(pos,limit);
                }
            });
        };
        function endTransaction () {
            sys.db.run('END TRANSACTION',function(){
                response.writeHead(200, {'Content-Type': 'application/json'});
                response.end(JSON.stringify(qObj.questionNumber));
            })
        };
    }
    exports.cogClass = cogClass;
})();
<|endoftext|>


<commit_before>// var cron = require('node-cron');
const git = require('simple-git');
const firebase = require('firebase')
const config = require('./config')
const cprocess = require('child_process')
// const path = __dirname + '/iotos';
// git(path).then etc..

firebase.initializeApp(config);

var ref = firebase.database().ref().child("servers")

// cprocess.exec('npm run app');

ref.on('value', function (data) {
	if (data.val().rpi1 == "pull") {
		deploy();
	} else {
		console.log('normal')
	}
})

function deploy () {
  console.log('Starting Deploying aplication :-)');
  // git(path).pull('origin', 'master')
	git()
	.then(function() {
		console.log('Starting pull ...');
	})
	.pull(function(err, update) {
		if(update && update.summary.changes) {
			console.log('processing and restarting app...');
			// cprocess.exec('npm stop app');
		}
	})
	.then(function() {
	console.log('pull done.');
	});
}

// var task = cron.schedule('*/1 * * * *', function() {
//   console.log('running a task every minute');
//   deploy ()
//   // task.stop();
// });<commit_msg>update project<commit_after>// var cron = require('node-cron');
const git = require('simple-git');
const firebase = require('firebase')
const config = require('./config')
const cprocess = require('child_process')
// const path = __dirname + '/iotos';
// git(path).then etc..

firebase.initializeApp(config);

var ref = firebase.database().ref().child("servers")

// cprocess.exec('npm run app');

ref.on('value', function (data) {
	if (data.val().rpi1 == "pull") {
		deploy();
	} else {
		console.log('normal')
	}
})

function deploy () {
  console.log('Starting Deploying aplication :-)');
  // git(path).pull('origin', 'master')
	git()
	.then(function() {
		console.log('Starting pull ... :-)))');
	})
	.pull(function(err, update) {
		if(update && update.summary.changes) {
			console.log('processing and restarting app...');
			// cprocess.exec('npm stop app');
		}
	})
	.then(function() {
	console.log('pull done.');
	});
}

// var task = cron.schedule('*/1 * * * *', function() {
//   console.log('running a task every minute');
//   deploy ()
//   // task.stop();
// });<|endoftext|>


<commit_before>import { orderComponents } from '../../actions/component';
import * as Component from './component';
import * as CodesList from './codes-list';
import * as CalculatedVariable from './calculated-variable';
import * as ExternalVariable from './external-variable';
import * as CollectedVariable from './collected-variable';
import { getOrderedComponents } from 'utils/model/redirections-utils'
import { uuid } from 'utils/utils';
import { removeOrphansCodesLists } from 'utils/codes-lists/codes-lists-utils';
import {
  removeOrphansCollectedVariables,
  getCollectedVariablesIdsFromComponents,
} from 'utils/variables/variables-utils';

export function remoteToState(remote) {
  const {
    owner,
    final,
    id,
    Name: name,
    Label: [label],
    agency,
    DataCollection: dataCollection,
    lastUpdatedDate,
    // ComponentGroup: componentGroups, @TODO: This data is not used yet.
  } = remote;

  return {
    owner,
    final: final === undefined,
    id,
    name,
    label,
    agency,
    lastUpdatedDate,
    serie: '',
    operation: '',
    campaigns: dataCollection.map(dc => dc.id),
  };
}

export function remoteToStore(remote) {
  return {
    [remote.id]: remoteToState(remote),
  };
}

export function stateToRemote(state, stores) {
  const {
    componentsStore,
    codesListsStore,
    calculatedVariablesStore,
    externalVariablesStore,
    collectedVariableByQuestionStore,
    campaignsStore,
  } = stores;

  const collectedVariablesStore = Object.keys(collectedVariableByQuestionStore).reduce((acc, key) => {
    return { ...acc, ...collectedVariableByQuestionStore[key] };
  }, {});

  // We remove from the stores the elements no associated to a component before saving
  const codesListsWihoutOrphans = removeOrphansCodesLists(codesListsStore, componentsStore);
  const collectedVariablesWithoutOrphans = removeOrphansCollectedVariables(
    getCollectedVariablesIdsFromComponents(componentsStore),
    collectedVariablesStore
  );

  const { owner, id, label, name, agency, campaigns, final } = state;
  const dataCollections = campaigns.map(c => ({
    id: c,
    uri: `http://ddi:fr.insee:DataCollection.${c}`,
    Name: campaignsStore[c].label,
  }));

  function generateComponentGroups() {
    const orderedComponents = getOrderedComponents(componentsStore, Object.keys(componentsStore).filter(id => componentsStore[id].type === 'SEQUENCE').sort((c1, c2) => componentsStore[c1].weight > componentsStore[c2].weight));
    let startPage = 1;
    let result = [];
    orderedComponents.forEach(componentId => {
      if (!result[startPage - 1]) {
        result.push({
          id: uuid(),
          Name: `PAGE_${startPage}`,
          Label: [`Components for page ${startPage}`],
          MemberReference: [],
        })
      }
      result[startPage - 1].MemberReference.push(componentId)
      if (componentsStore[componentId].pageBreak) {
        startPage++;
      }
    })
    return result;
  }

  const remote = {
    owner,
    final,
    id,
    Label: [label],
    Name: name,
    lastUpdatedDate: new Date().toString(),
    DataCollection: dataCollections,
    ComponentGroup: generateComponentGroups(),
    agency: agency || '',
  };

  const componentsRemote = Component.storeToRemote(componentsStore, id, codesListsStore);
  const codesListsRemote = CodesList.storeToRemote(codesListsWihoutOrphans);
  const calculatedVariablesRemote = CalculatedVariable.storeToRemote(calculatedVariablesStore);
  const externalVariablesRemote = ExternalVariable.storeToRemote(externalVariablesStore);
  const collectedVariablesRemote = CollectedVariable.storeToRemote(collectedVariablesWithoutOrphans);

  return {
    ...remote,
    Child: componentsRemote,
    CodeLists: {
      CodeList: codesListsRemote,
    },
    Variables: {
      Variable: [...calculatedVariablesRemote, ...externalVariablesRemote, ...collectedVariablesRemote],
    },
  };
}
<commit_msg>[FIX] Missing GenericName attribute in state to remote transformation<commit_after>import * as Component from './component';
import * as CodesList from './codes-list';
import * as CalculatedVariable from './calculated-variable';
import * as ExternalVariable from './external-variable';
import * as CollectedVariable from './collected-variable';

import { getOrderedComponents } from 'utils/model/redirections-utils';
import { uuid } from 'utils/utils';
import { removeOrphansCodesLists } from 'utils/codes-lists/codes-lists-utils';
import {
  removeOrphansCollectedVariables,
  getCollectedVariablesIdsFromComponents,
} from 'utils/variables/variables-utils';
import { COMPONENT_TYPE } from 'constants/pogues-constants';

const { QUESTIONNAIRE, SEQUENCE } = COMPONENT_TYPE;

function generateComponentGroups(componentsStore) {
  const orderedComponents = getOrderedComponents(
    componentsStore,
    Object.keys(componentsStore)
      .filter(id => componentsStore[id].type === SEQUENCE)
      .sort((c1, c2) => componentsStore[c1].weight > componentsStore[c2].weight)
  );
  let startPage = 1;
  const result = [];
  orderedComponents.forEach(componentId => {
    if (!result[startPage - 1]) {
      result.push({
        id: uuid(),
        Name: `PAGE_${startPage}`,
        Label: [`Components for page ${startPage}`],
        MemberReference: [],
      });
    }
    result[startPage - 1].MemberReference.push(componentId);
    if (componentsStore[componentId].pageBreak) {
      startPage += 1;
    }
  });
  return result;
}

export function remoteToState(remote) {
  const {
    owner,
    final,
    id,
    Name: name,
    Label: [label],
    agency,
    DataCollection: dataCollection,
    lastUpdatedDate,
  } = remote;

  return {
    owner,
    final: final === undefined,
    id,
    name,
    label,
    agency,
    lastUpdatedDate,
    serie: '',
    operation: '',
    campaigns: dataCollection.map(dc => dc.id),
  };
}

export function remoteToStore(remote) {
  return {
    [remote.id]: remoteToState(remote),
  };
}

export function stateToRemote(state, stores) {
  const {
    componentsStore,
    codesListsStore,
    calculatedVariablesStore,
    externalVariablesStore,
    collectedVariableByQuestionStore,
    campaignsStore,
  } = stores;

  const collectedVariablesStore = Object.keys(collectedVariableByQuestionStore).reduce((acc, key) => {
    return { ...acc, ...collectedVariableByQuestionStore[key] };
  }, {});

  // We remove from the stores the elements no associated to a component before saving
  const codesListsWihoutOrphans = removeOrphansCodesLists(codesListsStore, componentsStore);
  const collectedVariablesWithoutOrphans = removeOrphansCollectedVariables(
    getCollectedVariablesIdsFromComponents(componentsStore),
    collectedVariablesStore
  );

  const { owner, id, label, name, agency, campaigns, final } = state;
  const dataCollections = campaigns.map(c => ({
    id: c,
    uri: `http://ddi:fr.insee:DataCollection.${c}`,
    Name: campaignsStore[c].label,
  }));

  const remote = {
    owner,
    final,
    id,
    Label: [label],
    Name: name,
    lastUpdatedDate: new Date().toString(),
    DataCollection: dataCollections,
    genericName: QUESTIONNAIRE,
    ComponentGroup: generateComponentGroups(componentsStore),
    agency: agency || '',
  };

  const componentsRemote = Component.storeToRemote(componentsStore, id, codesListsStore);
  const codesListsRemote = CodesList.storeToRemote(codesListsWihoutOrphans);
  const calculatedVariablesRemote = CalculatedVariable.storeToRemote(calculatedVariablesStore);
  const externalVariablesRemote = ExternalVariable.storeToRemote(externalVariablesStore);
  const collectedVariablesRemote = CollectedVariable.storeToRemote(collectedVariablesWithoutOrphans);

  return {
    ...remote,
    Child: componentsRemote,
    CodeLists: {
      CodeList: codesListsRemote,
    },
    Variables: {
      Variable: [...calculatedVariablesRemote, ...externalVariablesRemote, ...collectedVariablesRemote],
    },
  };
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function (grunt) {
    grunt.registerTask('release', function (prop) {
        if (!prop || require('crypto').createHash('md5').update(prop).digest('hex') !== '37f525e2b6fc3cb4abd882f708ab80eb') {
            grunt.fail.warn('Wrong prop supplied. Are you sure you know what you are doing? There is no use to');
        }

        //var pkg = grunt.file.readJSON('package.json');
        //var arr = pkg.version.split('.');
        //arr.push(parseInt(arr.pop()) + 1);
        //pkg.version = arr.join('.');
        //grunt.file.write('package.json', JSON.stringify(pkg, null, 2));

        var command = ['npm version patch -m"update version to %s"',
                       'git push',
                       'git push --tags'].join(' && ');
        grunt.log.writeln(command);
        var done = this.async();
        require('child_process').exec(command, function(err, stdout, stderr) {
            if (err) {
                grunt.fail.warn('releasing version failed ' + err, err);
            }
            grunt.log.writeln('output ' + stdout + stderr);
            grunt.log.ok('releasing version');
            done();
        });
    });
};
<commit_msg>remove redundant files<commit_after><|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'MediaWiki_a',
    version:'0.7',
    prepareImgLinks:function (callback) {

        var res = [];

        // thumbnail: https://runescape.wiki/images/thumb/2/26/Senntisten_Kree%27arra_vs_Nodon.png/534px-Senntisten_Kree%27arra_vs_Nodon.png?de6e2
        //  fullsize: https://runescape.wiki/images/2/26/Senntisten_Kree%27arra_vs_Nodon.png
        $('img[src*="thumb/"], image').each(function() {
            let _this = $(this);
            let src = '';
            let srcs = [];
            let ext = '';

            if (this.src) {
                src = this.src;
            } else {
                if (!this.href) return;
                if (!this.href.baseVal) return;
                src = this.href.baseVal;
            }

            src = src.replace(/([^\?]{1,}).*/, '$1');

            if (src.substr(src.length - 8) == '.svg.png') {
                ext = '.svg';
            } else {
                ext = src.substr(src.lastIndexOf('.'));
            }

            srcs.push(src.substring(0, src.indexOf(ext) + ext.length).replace('thumb/', ''));
            _this.data().hoverZoomSrc = srcs;
            res.push(_this);

        });

        callback($(res), this.name);
    }
});
<commit_msg>Improvement of MediaWiki plug-in<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'MediaWiki_a',
    version:'0.8',
    prepareImgLinks:function (callback) {

        var res = [];

        // thumbnail: https://runescape.wiki/images/thumb/2/26/Senntisten_Kree%27arra_vs_Nodon.png/534px-Senntisten_Kree%27arra_vs_Nodon.png?de6e2
        //  fullsize: https://runescape.wiki/images/2/26/Senntisten_Kree%27arra_vs_Nodon.png
        $('img[src*="/images/thumb/"], image').each(function() {
            let _this = $(this);
            let src = '';
            let srcs = [];
            let ext = '';

            if (this.src) {
                src = this.src;
            } else {
                if (!this.href) return;
                if (!this.href.baseVal) return;
                src = this.href.baseVal;
            }

            src = src.replace(/([^\?]{1,}).*/, '$1');

            if (src.substr(src.length - 8) == '.svg.png') {
                ext = '.svg';
            } else {
                ext = src.substr(src.lastIndexOf('.'));
            }

            if (src.indexOf(ext + '/') == -1) return;

            srcs.push(src.substring(0, src.indexOf(ext) + ext.length).replace('thumb/', ''));
            _this.data().hoverZoomSrc = srcs;
            res.push(_this);

        });

        callback($(res), this.name);
    }
});
<|endoftext|>


<commit_before>/**
 *
 * Translate the syntax tree into Javascript code.
 *
 * ["define", "a", 12] ---> "var a = 12;"
 * ["set!", "a", 13]   ---> "a = 13;"
 * ["lambda", ["x"], ["*", 3, 4]] ---> "function (x) {return mult_proc(3,4);}"
 *
 *
 */
var _translate = function (x) {

	var build_cond = function (x) {
		var begin = "",
			i;
		for (i = 1; i < x.length; i += 1) {
			if (i === x.length-1 && x[i][0] === "else") {
				begin += form_else(x[i][1]);
			} else if (i === 1) {
				begin += form_if(x[i]);
			} else {
				begin += " else " + form_if(x[i].slice(0,2));
			}
		}
		return begin;
	};

	var build_if = function (x) {
		return form_if([x[1],x[2]]) + form_else(x[3]);
	};

	var form_if = function (x) {
		return "if (" + trans(x[0]) + ") {" + trans(x[1], true) + ";}";
	};

	var form_else = function (x) {
		return " else {" + trans(x, true) + ";}";
	};

	var build_set = function (x) {
		return x[1] + " = " + trans(x[2]);
	};

	var build_begin = function (x) {
		var i, code;
		code = "function () {";
		for (i = 1; i < x.length; i += 1) {
			if (i === x.length-1) {
				code += trans(x[i], true) + ";";
			} else {
				code += trans(x[i], false) + ";";
			}
		}
		code += "}();";
		return code;
	};

	var build_define = function (x) {
		var code;
		if (x[1] instanceof Array) {
			code = "var " + x[1][0] + " = ";
			code += build_lambda([,x[1].slice(1, x[1].length), x[2]]);
		} else {
			code = "var " + x[1] + " = " + trans(x[2]);
		}
		return code + ";";
	};

	var build_lambda = function (x) {
		return "function (" + build_parameters(x[1]) +
			   ") {" + trans(x[2], true) + ";}";
	};

	var build_procedure = function (x) {
		return x[0] + "(" + build_parameters(x.slice(1, x.length)) + ")";
	};

	var build_parameters = function (x) {
		var code = [],
			i;
		for (i = 0; i < x.length; i += 1) {
			code.push(trans(x[i], false));
		}
		return code.join();
	};

	var build_quote = function (x) {
		var i, quote = "[";
		for (i = 1; i < x.length; i++) {
			quote += x[i] + ",";
		}
		quote = quote.slice(0,-1) + "]";
		return quote;
	};

	var trans = function (x, in_func) {
		var ret, code = "";
		ret = in_func ? "return " : "";
		if (typeof x === "string" || !(x instanceof Array)) {
			return ret + x;
		} else if (x[0] === "quote") {
			return build_quote(x);
		} else if (x[0] === "if") {
			return build_if(x);
		} else if (x[0] === "cond") {
			return build_cond(x);
		} else if (x[0] === "set_bang") {
			return ret + build_set(x);
		} else if (x[0] === "define") {
			return build_define(x);
		} else if (x[0] === "lambda") {
			return ret + build_lambda(x);
		} else if (x[0] === "begin") {
			return build_begin(x);
		} else {
			return ret + build_procedure(x);
		}
	};

	var i, out = "";
	if (_is_array(x)) {
		for (i = 0; i < x.length; i++) {
			out += trans(x[i], false) + " ";
		}
	} else {
		out = trans(x);
	}
	return out.replace(/\;\;/g, ';');
};

<commit_msg>fixed semi colon bug<commit_after>/**
 *
 * Translate the syntax tree into Javascript code.
 *
 * ["define", "a", 12] ---> "var a = 12;"
 * ["set!", "a", 13]   ---> "a = 13;"
 * ["lambda", ["x"], ["*", 3, 4]] ---> "function (x) {return mult_proc(3,4);}"
 *
 *
 */
var _translate = function (x) {

	var build_cond = function (x) {
		var begin = "",
			i;
		for (i = 1; i < x.length; i += 1) {
			if (i === x.length-1 && x[i][0] === "else") {
				begin += form_else(x[i][1]);
			} else if (i === 1) {
				begin += form_if(x[i]);
			} else {
				begin += " else " + form_if(x[i].slice(0,2));
			}
		}
		return begin;
	};

	var build_if = function (x) {
		return form_if([x[1],x[2]]) + form_else(x[3]);
	};

	var form_if = function (x) {
		return "if (" + trans(x[0]) + ") {" + trans(x[1], true) + ";}";
	};

	var form_else = function (x) {
		return " else {" + trans(x, true) + ";}";
	};

	var build_set = function (x) {
		return x[1] + " = " + trans(x[2]);
	};

	var build_begin = function (x) {
		var i, code;
		code = "function () {";
		for (i = 1; i < x.length; i += 1) {
			if (i === x.length-1) {
				code += trans(x[i], true) + ";";
			} else {
				code += trans(x[i], false) + ";";
			}
		}
		code += "}();";
		return code;
	};

	var build_define = function (x) {
		var code;
		if (x[1] instanceof Array) {
			code = "var " + x[1][0] + " = ";
			code += build_lambda([,x[1].slice(1, x[1].length), x[2]]);
		} else {
			code = "var " + x[1] + " = " + trans(x[2]);
		}
		return code + ";";
	};

	var build_lambda = function (x) {
		return "function (" + build_parameters(x[1]) +
			   ") {" + trans(x[2], true) + "}";
	};

	var build_procedure = function (x) {
		return x[0] + "(" + build_parameters(x.slice(1, x.length)) + ")";
	};

	var build_parameters = function (x) {
		var code = [],
			i;
		for (i = 0; i < x.length; i += 1) {
			code.push(trans(x[i], false));
		}
		return code.join();
	};

	var build_quote = function (x) {
		var i, quote = "[";
		for (i = 1; i < x.length; i++) {
			quote += x[i] + ",";
		}
		quote = quote.slice(0,-1) + "]";
		return quote;
	};

	var trans = function (x, in_func) {
		var ret, code = "";
		ret = in_func ? "return " : "";
		if (typeof x === "string" || !(x instanceof Array)) {
			return ret + x;
		} else if (x[0] === "quote") {
			return build_quote(x);
		} else if (x[0] === "if") {
			return build_if(x);
		} else if (x[0] === "cond") {
			return build_cond(x);
		} else if (x[0] === "set_bang") {
			return ret + build_set(x);
		} else if (x[0] === "define") {
			return build_define(x);
		} else if (x[0] === "lambda") {
			return ret + build_lambda(x);
		} else if (x[0] === "begin") {
			return build_begin(x);
		} else {
			return ret + build_procedure(x);
		}
	};

	var i, out = "";
	if (_is_array(x)) {
		for (i = 0; i < x.length; i++) {
			out += trans(x[i], false) + " ";
		}
	} else {
		out = trans(x);
	}
	return out.replace(/\;\;/g, ';');
};

<|endoftext|>


<commit_before>/*jshint strict: false */
/*global require */

////////////////////////////////////////////////////////////////////////////////
/// @brief managing edges
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Achim Brandt
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");

var API = "/_api/edges";

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock API_EDGE_READINOUTBOUND
/// @brief get edges
///
/// @RESTHEADER{GET /_api/edges/{collection-id}, Read in- or outbound edges}
///
/// @RESTURLPARAMETERS
///
/// @RESTURLPARAM{collection-id,string,required}
/// The id of the collection.
///
/// @RESTQUERYPARAMETERS
///
/// @RESTQUERYPARAM{vertex,string,required}
/// The id of the start vertex.
///
/// @RESTQUERYPARAM{direction,string,optional}
/// Selects *in* or *out* direction for edges. If not set, any edges are
/// returned.
///
/// @RESTDESCRIPTION
/// Returns the list of edges starting or ending in the vertex identified by
/// *vertex-handle*.
///
/// @EXAMPLES
///
/// Any direction
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesAny}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// In edges
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesIn}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1&direction=in";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Out edges
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesOut}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1&direction=out";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

function get_edges (req, res) {
  if (req.suffix.length !== 1) {
    actions.resultBad(req,
                      res,
                      arangodb.ERROR_HTTP_BAD_PARAMETER,
                      "expect GET /" + API +
                      "/<collection-identifier>?vertex=<vertex-handle>&direction=<direction>");
    return;
  }

  var name = decodeURIComponent(req.suffix[0]);
  var collection = arangodb.db._collection(name);

  if (collection === null) {
    actions.collectionNotFound(req, res, name);
    return;
  }

  var vertex = req.parameters.vertex;
  var direction = req.parameters.direction;
  var e;

  if (direction === null || direction === undefined || direction === "" || direction === "any") {
    e = collection.edges(vertex);
  }
  else if (direction === "in" || direction === "inbound") {
    e = collection.inEdges(vertex);
  }
  else if (direction === "out" || direction === "outbound") {
    e = collection.outEdges(vertex);
  }
  else {
    actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                      "<direction> must be any, in, or out, not: " + JSON.stringify(direction));
    return;
  }

  actions.resultOk(req, res, actions.HTTP_OK, { edges: e });
}

////////////////////////////////////////////////////////////////////////////////
/// @brief gateway
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url : API,

  callback : function (req, res) {
    try {
      if (req.requestType === actions.GET) {
        get_edges(req, res);
      }
      else {
        actions.resultUnsupported(req, res);
      }
    }
    catch (err) {
      actions.resultException(req, res, err, undefined, false);
    }
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Add missing return codes to API docs.<commit_after>/*jshint strict: false */
/*global require */

////////////////////////////////////////////////////////////////////////////////
/// @brief managing edges
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Achim Brandt
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");

var API = "/_api/edges";

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock API_EDGE_READINOUTBOUND
/// @brief get edges
///
/// @RESTHEADER{GET /_api/edges/{collection-id}, Read in- or outbound edges}
///
/// @RESTURLPARAMETERS
///
/// @RESTURLPARAM{collection-id,string,required}
/// The id of the collection.
///
/// @RESTQUERYPARAMETERS
///
/// @RESTQUERYPARAM{vertex,string,required}
/// The id of the start vertex.
///
/// @RESTQUERYPARAM{direction,string,optional}
/// Selects *in* or *out* direction for edges. If not set, any edges are
/// returned.
///
/// @RESTDESCRIPTION
/// Returns the list of edges starting or ending in the vertex identified by
/// *vertex-handle*.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned if the edge collection was found and edges were retrieved.
///
/// @RESTRETURNCODE{400}
/// is returned if the request contains invalid parameters.
///
/// @RESTRETURNCODE{404}
/// is returned if the edge collection was not found.
///
/// @EXAMPLES
///
/// Any direction
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesAny}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// In edges
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesIn}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1&direction=in";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Out edges
///
/// @EXAMPLE_ARANGOSH_RUN{RestEdgesReadEdgesOut}
///     var Graph = require("org/arangodb/graph-blueprint").Graph;
///     var g = new Graph("graph", "vertices", "edges");
///     var v1 = g.addVertex(1);
///     var v2 = g.addVertex(2);
///     var v3 = g.addVertex(3);
///     var v4 = g.addVertex(4);
///     g.addEdge(v1, v3, 5, "v1 -> v3");
///     g.addEdge(v2, v1, 6, "v2 -> v1");
///     g.addEdge(v4, v1, 7, "v4 -> v1");
///
///     var url = "/_api/edges/edges?vertex=vertices/1&direction=out";
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     db._drop("edges");
///     db._drop("vertices");
///     db._graphs.remove("graph");
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

function get_edges (req, res) {
  if (req.suffix.length !== 1) {
    actions.resultBad(req,
                      res,
                      arangodb.ERROR_HTTP_BAD_PARAMETER,
                      "expect GET /" + API +
                      "/<collection-identifier>?vertex=<vertex-handle>&direction=<direction>");
    return;
  }

  var name = decodeURIComponent(req.suffix[0]);
  var collection = arangodb.db._collection(name);

  if (collection === null) {
    actions.collectionNotFound(req, res, name);
    return;
  }

  var vertex = req.parameters.vertex;
  var direction = req.parameters.direction;
  var e;

  if (direction === null || direction === undefined || direction === "" || direction === "any") {
    e = collection.edges(vertex);
  }
  else if (direction === "in" || direction === "inbound") {
    e = collection.inEdges(vertex);
  }
  else if (direction === "out" || direction === "outbound") {
    e = collection.outEdges(vertex);
  }
  else {
    actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                      "<direction> must be any, in, or out, not: " + JSON.stringify(direction));
    return;
  }

  actions.resultOk(req, res, actions.HTTP_OK, { edges: e });
}

////////////////////////////////////////////////////////////////////////////////
/// @brief gateway
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url : API,

  callback : function (req, res) {
    try {
      if (req.requestType === actions.GET) {
        get_edges(req, res);
      }
      else {
        actions.resultUnsupported(req, res);
      }
    }
    catch (err) {
      actions.resultException(req, res, err, undefined, false);
    }
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>// ==UserScript==
// @id             ingress-intel-total-conversion@jonatkins
// @name           IITC: Ingress intel map total conversion
// @version        0.25.2.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Total conversion for the ingress intel map.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

// REPLACE ORIG SITE ///////////////////////////////////////////////////
if(document.getElementsByTagName('html')[0].getAttribute('itemscope') != null)
  throw('Ingress Intel Website is down, not a userscript issue.');
window.iitcBuildDate = '@@BUILDDATE@@';

// disable vanilla JS
window.onload = function() {};
document.body.onload = function() {};

//originally code here parsed the


<commit_before>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: false});

function save_data(){
    var input = document.getElementById("fname");
    localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {;

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },
    reminder: function(term) {
        function remindData(){
            var info = term;
            localStorage.setItem("Rinfo", info);
        }
        var rememberThing = localStorage.getItem("Rinfo");
        speak('Saved to my memory')
    },
    remeberCommand: function() {
        speak("you asked me to remeber " + reminder.rememberThing)
    },
    d6: function () {
        var d6 = Math.floor(Math.random() * 6);
        speak(d6);
        document.getElementById("#resultplace").innerHTML = d6;
    },
    diceroll1: function (diceroll) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {}
        var diceroll2 = Math.floor(Math.random() * diceroll);
        speak(diceroll2);
        document.getElementById("#resultplace").innerHTML = diceroll2;
    },

    wolfram: function(term) {
        $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
            speak(wolfram__);
        };
        //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
        //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
        //speak(wolfram_);
    },
    weather: function (term) {
        $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
            speak(theweather.temp);

        });

    },
    badAsk: function() {
        if (mood == 'not very good' || mood == 'iffy') {
            _askBad = ['its not about me', 'nothing'];
            askBad = _askBad[Math.floor(Math.random() * 2)];
            speak(askBad);
            document.getElementById("#resultplace").innerHTML = askBad;
        }
        else {}
    },

    mood: function() {
        _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
        mood = _mood[Math.floor(Math.random() * 7)];

    },

    howu: function () {

        speak(mood);
        document.getElementById("#resultplace").innerHTML = mood;

    },

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(How are you) (you good) (are you alright)': actions.howu,
        'Roll a *diceroll' : actions.diceroll1,
        'remember (for me) *term' : actions.reminder,
        'what did I ask you to remeber' : actions.remeberCommand,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'Run code' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<commit_msg>added more protectionn on Run Code command<commit_after>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: false});

function save_data(){
    var input = document.getElementById("fname");
    localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {;

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }
        else if (newcommand.indexOf("document.getItem") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },
    reminder: function(term) {
        function remindData(){
            var info = term;
            localStorage.setItem("Rinfo", info);
        }
        var rememberThing = localStorage.getItem("Rinfo");
        speak('Saved to my memory')
    },
    remeberCommand: function() {
        speak("you asked me to remeber " + reminder.rememberThing)
    },
    d6: function () {
        var d6 = Math.floor(Math.random() * 6);
        speak(d6);
        document.getElementById("#resultplace").innerHTML = d6;
    },
    diceroll1: function (diceroll) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {}
        var diceroll2 = Math.floor(Math.random() * diceroll);
        speak(diceroll2);
        document.getElementById("#resultplace").innerHTML = diceroll2;
    },

    wolfram: function(term) {
        $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
            speak(wolfram__);
        };
        //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
        //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
        //speak(wolfram_);
    },
    weather: function (term) {
        $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
            speak(theweather.temp);

        });

    },
    badAsk: function() {
        if (mood == 'not very good' || mood == 'iffy') {
            _askBad = ['its not about me', 'nothing'];
            askBad = _askBad[Math.floor(Math.random() * 2)];
            speak(askBad);
            document.getElementById("#resultplace").innerHTML = askBad;
        }
        else {}
    },

    mood: function() {
        _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
        mood = _mood[Math.floor(Math.random() * 7)];

    },

    howu: function () {

        speak(mood);
        document.getElementById("#resultplace").innerHTML = mood;

    },

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            speak('Ready, sir');
            document.getElementById("#resultplace").innerHTML = "Ready, sir";

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(How are you) (you good) (are you alright)': actions.howu,
        'Roll a *diceroll' : actions.diceroll1,
        'remember (for me) *term' : actions.reminder,
        'what did I ask you to remeber' : actions.remeberCommand,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'Run code' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<|endoftext|>