<commit_before>/*#ifndef(UMD)*/
(function () {/* Begin of privacy scope */
    "use strict";
    /*global _gpfDefine*/ // Shortcut for gpf.define
    /*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*#endif*/

    _gpfErrorDeclare("engine", {
        "engineStackUnderflow":
            "Stack underflow",
        "engineTypeCheck":
            "Type check"
    });

    var
        TYPE_NUMBER         = "N", // number
        TYPE_STRING         = "S", // string
        TYPE_ID             = "I", // IdString(exec:false)
        TYPE_EXECUTABLEID   = "E", // IdString(exec:true)
        TYPE_ARRAY          = "A", // array
        TYPE_DICTIONARY     = "D", // object
        TYPE_CODE           = "C", // CodeArray

        toType = function (value) {
            var type = typeof value;
            if ("number" === type) {
                return TYPE_NUMBER;
            } else if ("string" === type) {
                return TYPE_STRING;
            } else if (value instanceof IdString) {
                if (value.executable()) {
                    return TYPE_EXECUTABLEID;
                } else {
                    return TYPE_ID;
                }
            } else if (value instanceof CodeArray) {
                return TYPE_CODE;
            } else if (value instanceof Array) {
                return TYPE_ARRAY;
            } else {
                return TYPE_DICTIONARY;
            }
        },

        SYS_DICT = {

            add: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] + args[1]);
            },

            mul: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] * args[1]);
            },

            sub: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] - args[1]);
            },

            div: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] / args[1]);
            }

        },

        CodeArray = _gpfDefine("CodeArray", Object, {

            constructor: function () {
                this._items = [];
            }

        }),

        IdString = _gpfDefine("IdString", Object, {

            constructor: function (label, executable) {
                this._label = label;
                this._executable = executable;
            },

            executable: function () {
                return this._executable;
            }

        }),

        EngineState = _gpfDefine("EngineState", Object, {

            constructor: function () {
                this._stack = [];
                // "Top" dictionary is SYS_DICT
                this._userDict = {};     // Then user dictionary
                this._dictionaries = []; // Then any other enqueued
            },

            push: function () {
                var idx;
                for (idx = 0; idx < arguments.length; ++idx) {
                    this._stack.push(arguments[idx]);
                }
                // Handle stackoverflow
            },

            pop: function () {
                if (0 === this._stack.length) {
                    throw gpf.Error.engineStackUnderflow();
                }
                return this._stack.pop();
            },

            checkAndPop: function (types) {
                var result, idx, value;
                if (this.length() < types.length) {
                    throw gpf.Error.engineStackUnderflow();
                }
                result = [];
                for (idx = 0; idx < types.length; ++idx) {
                    value = this.internalGet(idx);
                    if (toType(value) !== types[idx]) {
                        throw gpf.Error.engineTypeCheck();
                    }
                    result.push(value);
                }
                // TODO: optimize
                while (idx) {
                    this.pop();
                    --idx;
                }
                return result;
            },

            internalGet: function (offset) {
                // WARNING: no check on stack size
                return this._stack[this._stack.length - offset - 1];
            },

            length: function () {
                return this._stack.length;
            }

        });

    _gpfDefine("gpf.Engine", Object, {

        constructor: function () {
            this._state = new EngineState();
        },

        execute: function (src) {
            gpf.interfaces.ignoreParameter(src);
            gpf.interfaces.ignoreParameter(SYS_DICT);

        }

    });

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/
<commit_msg>Removes optional parameters (use gpf.define signature)<commit_after>/*#ifndef(UMD)*/
(function () {/* Begin of privacy scope */
    "use strict";
    /*global _gpfDefine*/ // Shortcut for gpf.define
    /*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*#endif*/

    _gpfErrorDeclare("engine", {
        "engineStackUnderflow":
            "Stack underflow",
        "engineTypeCheck":
            "Type check"
    });

    var
        TYPE_NUMBER         = "N", // number
        TYPE_STRING         = "S", // string
        TYPE_ID             = "I", // IdString(exec:false)
        TYPE_EXECUTABLEID   = "E", // IdString(exec:true)
        TYPE_ARRAY          = "A", // array
        TYPE_DICTIONARY     = "D", // object
        TYPE_CODE           = "C", // CodeArray

        toType = function (value) {
            var type = typeof value;
            if ("number" === type) {
                return TYPE_NUMBER;
            } else if ("string" === type) {
                return TYPE_STRING;
            } else if (value instanceof IdString) {
                if (value.executable()) {
                    return TYPE_EXECUTABLEID;
                } else {
                    return TYPE_ID;
                }
            } else if (value instanceof CodeArray) {
                return TYPE_CODE;
            } else if (value instanceof Array) {
                return TYPE_ARRAY;
            } else {
                return TYPE_DICTIONARY;
            }
        },

        SYS_DICT = {

            add: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] + args[1]);
            },

            mul: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] * args[1]);
            },

            sub: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] - args[1]);
            },

            div: function (engineState) {
                var args = engineState.checkAndPop("NN");
                engineState.push(args[0] / args[1]);
            }

        },

        CodeArray = _gpfDefine("CodeArray", {

            constructor: function () {
                this._items = [];
            }

        }),

        IdString = _gpfDefine("IdString", {

            constructor: function (label, executable) {
                this._label = label;
                this._executable = executable;
            },

            executable: function () {
                return this._executable;
            }

        }),

        EngineState = _gpfDefine("EngineState", {

            constructor: function () {
                this._stack = [];
                // "Top" dictionary is SYS_DICT
                this._userDict = {};     // Then user dictionary
                this._dictionaries = []; // Then any other enqueued
            },

            push: function () {
                var idx;
                for (idx = 0; idx < arguments.length; ++idx) {
                    this._stack.push(arguments[idx]);
                }
                // Handle stackoverflow
            },

            pop: function () {
                if (0 === this._stack.length) {
                    throw gpf.Error.engineStackUnderflow();
                }
                return this._stack.pop();
            },

            checkAndPop: function (types) {
                var result, idx, value;
                if (this.length() < types.length) {
                    throw gpf.Error.engineStackUnderflow();
                }
                result = [];
                for (idx = 0; idx < types.length; ++idx) {
                    value = this.internalGet(idx);
                    if (toType(value) !== types[idx]) {
                        throw gpf.Error.engineTypeCheck();
                    }
                    result.push(value);
                }
                // TODO: optimize
                while (idx) {
                    this.pop();
                    --idx;
                }
                return result;
            },

            internalGet: function (offset) {
                // WARNING: no check on stack size
                return this._stack[this._stack.length - offset - 1];
            },

            length: function () {
                return this._stack.length;
            }

        });

    _gpfDefine("gpf.Engine", {

        constructor: function () {
            this._state = new EngineState();
        },

        execute: function (src) {
            gpf.interfaces.ignoreParameter(src);
            gpf.interfaces.ignoreParameter(SYS_DICT);

        }

    });

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/
<|endoftext|>


<commit_before>

var socket = require('socket.io-client')('http://198.89.123.173:3000');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});

socket.on('other client',function(msg){
  console.log(msg)
});

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
  socket.emit('chat message',line);
})
<commit_msg>changed to standard IP address<commit_after>

var socket = require('socket.io-client')('http://127.0.0.1:3000');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});

socket.on('other client',function(msg){
  console.log(msg)
});

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
  socket.emit('chat message',line);
})
<|endoftext|>


<commit_before>var configUtils = _altboilerScope.configUtils

/* Wait until the client-side configuration has been done */
addEventListener('load', function () {
  /* Don't do anything if the loader should be shown */
  if(configUtils.isTruthy(altboiler.getConfig('showLoader'))) return

  /* Load the static CSS defined for the altboiler */
  document.head.innerHTML +=
    ['<link rel="stylesheet" type="text/css" href="', '">']
      .join(altboiler.getConfig('routes').css)
})
<commit_msg>Fix the client-side tmpConf<commit_after>var configUtils = _altboilerScope.configUtils

/* Wait until the client-side configuration has been done */
addEventListener('load', function () {
  var showLoader = altboiler.getConfig('showLoader')
  /* Clear the object */
  altboiler.tmpConf = {}
  /* Don't do anything if the loader should be shown */
  if(configUtils.isTruthy(showLoader)) return

  /* Load the static CSS defined for the altboiler */
  document.head.innerHTML +=
    ['<link rel="stylesheet" type="text/css" href="', '">']
      .join(altboiler.getConfig('routes').css)
})
<|endoftext|>


<commit_before>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    return new Promise(function(resolve, reject) {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0,0,0,0);
      d = d.getTime() / 1000;
      timeString = 'from=' + d + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != null || lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = '&exclusivestartkey=' + lastEvaluatedKey + '&';
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {

        from = new Date();
        resolve('done');
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      reject(Error(error));
    });
    });
  }
};

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds
  promiseChain.runChain();
  setTimeout(refreshData, x * 1000);
}

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

refreshData(); // execute function
<commit_msg>Expect lastEvaluatedKey to be undefined if not set<commit_after>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    return new Promise(function(resolve, reject) {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0,0,0,0);
      d = d.getTime() / 1000;
      timeString = 'from=' + d + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != undefined || lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = '&exclusivestartkey=' + lastEvaluatedKey + '&';
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {

        from = new Date();
        resolve('done');
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      reject(Error(error));
    });
    });
  }
};

// https://gist.github.com/KartikTalwar/2306741
function refreshData() {
  x = 3; // 3 Seconds
  promiseChain.runChain();
  setTimeout(refreshData, x * 1000);
}

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

refreshData(); // execute function
<|endoftext|>


<commit_before>var uuid = require('uuid');
const util = require('util');
var error = require('./error');

var InvalidOptionError = error.InvalidOptionError;

function toObject() {
  var o = {}
  Object.getOwnPropertyNames(this).forEach(function(key) {
    o.key = this[key];
  });
  return o;
}

module.exports.Entity = (function() {
  function Entity(id, opts) {
    this.id = id || uuid.v4();
    this.created = new Date();
    for (var key in opts) {
      this[key] = opts[key];
    }
  }
  Entity.prototype.toVertex = function() {
    var v, p = {};
    Object.getOwnPropertyNames(this).forEach(function(key) { p.key = this[key]; });
    v.u = this.id;
    v.p = p;
    return v;
  }
  Entity.prototype.toObject = toObject;
  Entity.prototype.toJSON = function() { return JSON.stringify(this.toObject()) };
  return Entity;
})();

/*
module.exports.Relationship = (function() {
  function Relationship(opts) {
    if (opts.s) opts.subject = opts.s;
    if (opts.p) opts.predicate = opts.p;
    if (!opts.subject) return console.error(new InvalidOptionError("'subject' is required"));
    if (!opts.predicate) return console.error(new InvalidOptionError("'predicate' is required"));
    this.subject = opts.subject;
    this.predicate = opts.predicate;
    this.created = new Date();
    Object.getOwnPropertyNames(opts).forEach(function(key) {
      this[key] = opts[key];
    }
  }
  Relationship.prototype.toEdge = function() {
    var e, o, p = {};
    Object.getOwnPropertyNames(this).forEach(function(key) {
      p.key = this[key];
    }
    e.u = this.subject;
    e.v = this.predicate;
    o.e = e;
    o.p = p;
    return o;
  }
  Relationship.prototype.toObject = toObject;
  Relationship.prototype.toJSON = toJSON;
  return Relationship;
})();
  */
<commit_msg>try different property visitation<commit_after>var uuid = require('uuid');
const util = require('util');
var error = require('./error');

var InvalidOptionError = error.InvalidOptionError;

function toObject() {
  var o = {}
  Object.getOwnPropertyNames(this).forEach(function(key) {
    o.key = this[key];
  });
  return o;
}

module.exports.Entity = (function() {
  function Entity(id, opts) {
    this.id = id || uuid.v4();
    this.created = new Date();
    for (var key in opts) {
      this[key] = opts[key];
    }
  }
  Entity.prototype.toVertex = function() {
    var v, p = {};
    this.getOwnPropertyNames().forEach(function(key) {p.key = this[key];});
    v.u = this.id;
    v.p = p;
    return v;
  }
  Entity.prototype.toObject = toObject;
  Entity.prototype.toJSON = function() { return JSON.stringify(this.toObject()) };
  return Entity;
})();

/*
module.exports.Relationship = (function() {
  function Relationship(opts) {
    if (opts.s) opts.subject = opts.s;
    if (opts.p) opts.predicate = opts.p;
    if (!opts.subject) return console.error(new InvalidOptionError("'subject' is required"));
    if (!opts.predicate) return console.error(new InvalidOptionError("'predicate' is required"));
    this.subject = opts.subject;
    this.predicate = opts.predicate;
    this.created = new Date();
    Object.getOwnPropertyNames(opts).forEach(function(key) {
      this[key] = opts[key];
    }
  }
  Relationship.prototype.toEdge = function() {
    var e, o, p = {};
    Object.getOwnPropertyNames(this).forEach(function(key) {
      p.key = this[key];
    }
    e.u = this.subject;
    e.v = this.predicate;
    o.e = e;
    o.p = p;
    return o;
  }
  Relationship.prototype.toObject = toObject;
  Relationship.prototype.toJSON = toJSON;
  return Relationship;
})();
  */
<|endoftext|>


<commit_before>(function(FMS, Backbone, _, $, moment) {
    _.extend( FMS, {
        Draft: Backbone.Model.extend({
            localStorage: new Backbone.LocalStorage(CONFIG.NAMESPACE + '-drafts'),

            defaults: {
                lat: 0,
                lon: 0,
                title: '',
                details: '',
                may_show_name: '',
                category: '',
                phone: '',
                pc: '',
                file: '',
                created: moment.utc()
            },

            description: function() {
                var desc = '';
                if ( this.get('title') ) {
                    desc += this.get('title');
                }
                desc += ', ' + this.createdDate();

                return desc;
            },

            createdDate: function() {
                return moment.utc( this.get('created') ).format( 'H:m Mo MMM' );
            }
        })
    });
})(FMS, Backbone, _, $, moment);

(function(FMS, Backbone, _, $) {
    _.extend( FMS, {
        Drafts: Backbone.Collection.extend({
            model: FMS.Draft,
            localStorage: new Backbone.LocalStorage(CONFIG.NAMESPACE + '-drafts')
        })
    });
})(FMS, Backbone, _, $);
<commit_msg>use nth day rather than nth month<commit_after>(function(FMS, Backbone, _, $, moment) {
    _.extend( FMS, {
        Draft: Backbone.Model.extend({
            localStorage: new Backbone.LocalStorage(CONFIG.NAMESPACE + '-drafts'),

            defaults: {
                lat: 0,
                lon: 0,
                title: '',
                details: '',
                may_show_name: '',
                category: '',
                phone: '',
                pc: '',
                file: '',
                created: moment.utc()
            },

            description: function() {
                var desc = '';
                if ( this.get('title') ) {
                    desc += this.get('title');
                }
                desc += ', ' + this.createdDate();

                return desc;
            },

            createdDate: function() {
                return moment.utc( this.get('created') ).format( 'H:m Do MMM' );
            }
        })
    });
})(FMS, Backbone, _, $, moment);

(function(FMS, Backbone, _, $) {
    _.extend( FMS, {
        Drafts: Backbone.Collection.extend({
            model: FMS.Draft,
            localStorage: new Backbone.LocalStorage(CONFIG.NAMESPACE + '-drafts')
        })
    });
})(FMS, Backbone, _, $);
<|endoftext|>


<commit_before>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;
var to = null;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
      from = new Date() / 1000;
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0, 0, 0, 0);
      d = d.getTime() / 1000;

      if (to === null) {
        to = new Date() / 1000;
      }
      timeString = 'from=' + d + '&to=' + to + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    } else {
      if (to === null) {
        to = new Date() / 1000;
      }
      timeString = 'from=' + from + '&to=' + to + '&';
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != undefined && lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = 'exclusivestartkey=' + lastEvaluatedKey;
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {
        // Done paginating through data
        to = null;
        statusGood('Map connected live');
        return delay(3000).then(function() {
          promiseChain.runChain();
        });
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      return delay(3000).then(function() {
        promiseChain.runChain();
      });
    }); // Anonymous function
  } // runChain
}; // promiseChain

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

promiseChain.runChain(); // execute function
<commit_msg>Set from to old to at end of requests<commit_after>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;
var to = null;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
      from = new Date() / 1000;
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(resolve, t);
  });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0, 0, 0, 0);
      d = d.getTime() / 1000;

      if (to === null) {
        to = new Date() / 1000;
      }
      timeString = 'from=' + d + '&to=' + to + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    } else {
      if (to === null) {
        to = new Date() / 1000;
      }
      timeString = 'from=' + from + '&to=' + to + '&';
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != undefined && lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = 'exclusivestartkey=' + lastEvaluatedKey;
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {
        // Done paginating through data
        from = to + 0.001;
        to = null;
        statusGood('Map connected live');
        return delay(3000).then(function() {
          promiseChain.runChain();
        });
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      return delay(3000).then(function() {
        promiseChain.runChain();
      });
    }); // Anonymous function
  } // runChain
}; // promiseChain

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

promiseChain.runChain(); // execute function
<|endoftext|>


<commit_before>'use strict';
let _ = require('lodash');
let path = require('path');
let util = require('./util');
let qs = require('querystring');
let request = require('request');
let protobuf = require('protobufjs');
let Exception = require('./Exception');

const API_VERSION = '0.6.0';
const USER_AGENT = 'log-nodejs-sdk';
//日志数据Message文件路径
const SLS_PROTO = path.join( process.cwd(), 'sls.proto' );

//构建Message对象
let builder = protobuf.loadProtoFile( SLS_PROTO );
let Log = builder.build('log');

module.exports = Aliyun_Log_Client;

var client = Aliyun_Log_Client.prototype;

/**
 * Aliyun_Log_Client Constructor
 * @param {Object} options Options
 */
function Aliyun_Log_Client( options ) {
  options = options || {};
  this.project = options.project || null;
  this.accessKey = options.accessKey;
  this.accessKeySecret = options.accessKeySecret;
  this.stsToken = options.stsToken || '';
  this.source = util.getLocalIp();   // @var string the local machine ip address.
  this._setEndpoint( options.endpoint );
}

/**
 * SetEndpoint
 * @param {String} endpoint Endpoint
 */
client._setEndpoint = function( endpoint ) {
  let pos;
  pos = endpoint.indexOf('://');
  if ( pos > -1 ) {
    pos += 3;
    endpoint = endpoint.substring( pos );
  }
  pos = endpoint.indexOf('/');
  if ( pos > -1 ) {
    endpoint = endpoint.substring( 0, pos );
  }
  pos = endpoint.indexOf(':');
  if ( pos > -1 ) {
    this.port = Number(endpoint.substring( pos + 1 ));
    endpoint = endpoint.substring( 0, pos );
  } else {
    this.port = 80;
  }
  this.isRowIp = util.isIp( endpoint );
  this.logHost = endpoint;
  this.endpoint = `${ endpoint }:${ this.port }`;
}

/**
 * 初始化请求信息
 * @param  {String}   method   请求方法名称
 * @param  {String}   project  日志项目名称
 * @param  {String|Protocol Buffer}   body     请求主体
 * @param  {String}   resource
 * @param  {Object}   params   query
 * @param  {Object}   headers  请求头部信息
 * @param  {Function} callback 回调函数
 * @return void
 */
client._send = function( method, project, body, resource, params, headers, callback ) {
  if (body) {
    headers['Content-Length'] = body.length;
    if (headers['x-log-bodyrawsize'] === undefined) {
      headers['x-log-bodyrawsize'] = 0;
    }
    headers['Content-MD5'] = util.md5( body ).toUpperCase();
  } else {
    headers['Content-Length'] = 0;
    headers['x-log-bodyrawsize'] = 0;
    headers['Content-qType'] = '';  // If not set, http request will add automatically.
  }

  headers['User-Agent'] = USER_AGENT;
  headers['x-log-apiversion'] = API_VERSION;
  headers['x-log-signaturemethod'] = 'hmac-sha1';

  if ( this.stsToken !== '' ) {
    headers['x-acs-security-token'] = this.stsToken;
  }

  if ( !project ) {
    headers['Host'] = this.logHost;
  } else {
    headers['Host'] = `${ project }.${ this.logHost }`;
  }

  headers['Date'] = util.getGMT();

  let signature = util.getRequestAuthorization( method, resource, this.accessKeySecret, this.stsToken, params, headers );
  headers['Authorization'] = `LOG ${ this.accessKey }:${ signature }`;

  let url = resource;
  if ( !_.isEmpty( params ) ) {
    url += `?${ qs.stringify( params ) }`;
  }
  if ( this.isRowIp ) {
    url = `http://${ this.endpoint }${ url }`;
  } else {
    if ( !project ) {
      url = `http://${ this.endpoint }${ url }`;
    } else {
      url = `http://${ project }.${ this.endpoint }${ url }`;
    }
  }
  this._sendRequest( method, url, body, headers, function(err, headers, result ) {
    if ( err ) {
      callback && callback( err );
    } else {
      callback && callback( null, headers, result );
    }
  });
}

/**
 * 发起调用阿里云API请求
 * @param  {String}   method   请求方法名称
 * @param  {String}   url      请求API地址
 * @param  {String|Protocol Buffer}   body   请求主体
 * @param  {Object}   headers  请求头部信息
 * @param  {Function} callback  回调函数
 * @return void
 */
client._sendRequest = function(method, url, body, headers, callback) {
  let options = {
    url : url,
    method : method,
    headers : headers
  }
  if ( method === 'POST' || method === 'PUT' ) {
    options['body'] = body;
  }

  request(options, function( err, response, body ) {
    if ( err ) {
      callback && callback( err );
    } else {
      try {
        body = JSON.parse( body );
      } catch( err ) {

      }
      let headers = response.headers;
      if (response.statusCode === 200) {
        callback && callback( null, headers, body );
      } else {
        let requestId = headers['x-log-requestid'] ? headers['x-log-requestid'] : '';
        if ( body['errorCode'] && body['errorMessage'] ) {
          let err = new Exception( body['errorCode'], body['errorMessage'], requestId );
          callback && callback( err );
        } else {
          let err = new Exception( 'RequestError', `Request is failed. Http code is ${ response.statusCode }.The return json is ${ JSON.stringify(body) }`, requestId );
          callback && callback( err );
        }
      }
    }
  })
}

/**
 * 获取日志库列表
 * @param  {String}   project  项目名称
 * @param  {Function} callback 回调函数
 * @return void
 */
client.listLogstores = function( callback ) {
  let body = null;
  let params = {};
  let headers = {};
  let method = 'GET';
  let resource = '/logstores';
  let project = this.project;
  this._send( method, project, body, resource, params, headers, callback );
}

/**
 * 创建日志库 ( CreateLogstore )
 * @param {Object}   options      创建日志库信息
 * @param {Function} callback     回调函数
 */
client.CreateLogstore = function(options, callback) {
  let body = {};
  let params = {};
  let headers = {};
  let method = 'POST';
  let project = this.project;
  let resource = '/logstores';
  headers["x-log-bodyrawsize"] = 0;
  headers["Content-Type"] = "application/json";
  body['ttl'] = Number( options.ttl );
  body['logstoreName'] = options.logstoreName;
  body['shardCount'] = Number( options.shardCount );
  try {
    body = JSON.stringify( body );
  } catch( err ) {
    callback && callback( err );
  }
  this._send( method, project, body, resource, params, headers, callback );
}

/**
 * 向指定LogStore写入日志数据
 * @param {String}   logstoreName LogStore名称
 * @param {Object}   data         日志信息
 * @param {Function} callback     回调函数
 */
client.PostLogStoreLogs = function( logstoreName, data, callback ) {
  let self = this;
  let params = {};
  let headers = {};
  let method = 'POST';
  let project = this.project;
  let resource = `/logstores/${ logstoreName }`;
  //接口每次可以写入的日志数据量上限4096条
  if ( data.logs.length > 4096 ) {
    throw new Exception ( 'InvalidLogSize', "logItems' length exceeds maximum limitation: 4096 lines." );
  }
  //根据protobuf Message格式组装数据
  let group = new Object();
  group['topic'] = data.topic;
  group['source'] = data.source;
  group['logs'] = new Array();

  data.logs.forEach( function( logItem ) {
    let log = new Object();
    log['time'] = logItem.time;
    log['contents'] = new Array();
    logItem.contents.forEach( function( prop ) {
      let content = new Object();
      content['key'] = prop['key'];
      content['value'] = prop['value'];
      log.contents.push( content );
    })
    group['logs'].push( log );
  })

  let LogGroup = Log.LogGroup;
  //转换为Protocol Buffer
  let logger = new LogGroup( group ).toBuffer();
  let body = logger;

  let bodySize = body.length;
  //接口每次可以写入的日志数据量上限为3MB
  if ( bodySize > 3 * 1024 * 1024 ) {
    throw new Exception ( 'InvalidLogSize', "logItems' size exceeds maximum limitation: 3 MB." );
  }
  headers ["x-log-bodyrawsize"] = bodySize;
  headers ['x-log-compresstype'] = 'deflate';
  headers ['Content-Type'] = 'application/x-protobuf';
  //压缩内容
  util.deflate( body, function( err, buf ) {
    if (err) throw err;
    self._send( 'POST', self.project, buf, resource, params, headers, callback);
  })

}

<commit_msg>添加PostLogStoreLogs<commit_after>'use strict';
let _ = require('lodash');
let path = require('path');
let util = require('./util');
let qs = require('querystring');
let request = require('request');
let protobuf = require('protobufjs');
let Exception = require('./Exception');

const API_VERSION = '0.6.0';
const USER_AGENT = 'log-nodejs-sdk';
//日志数据Message文件路径
const SLS_PROTO = path.join( process.cwd(), 'sls.proto' );

//构建Message对象
let builder = protobuf.loadProtoFile( SLS_PROTO );
let Log = builder.build('log');

module.exports = Aliyun_Log_Client;

var client = Aliyun_Log_Client.prototype;

/**
 * Aliyun_Log_Client Constructor
 * @param {Object} options Options
 */
function Aliyun_Log_Client( options ) {
  options = options || {};
  this.project = options.project || null;
  this.accessKey = options.accessKey;
  this.accessKeySecret = options.accessKeySecret;
  this.stsToken = options.stsToken || '';
  this.source = util.getLocalIp();   // @var string the local machine ip address.
  this._setEndpoint( options.endpoint );
}

/**
 * SetEndpoint
 * @param {String} endpoint Endpoint
 */
client._setEndpoint = function( endpoint ) {
  let pos;
  pos = endpoint.indexOf('://');
  if ( pos > -1 ) {
    pos += 3;
    endpoint = endpoint.substring( pos );
  }
  pos = endpoint.indexOf('/');
  if ( pos > -1 ) {
    endpoint = endpoint.substring( 0, pos );
  }
  pos = endpoint.indexOf(':');
  if ( pos > -1 ) {
    this.port = Number(endpoint.substring( pos + 1 ));
    endpoint = endpoint.substring( 0, pos );
  } else {
    this.port = 80;
  }
  this.isRowIp = util.isIp( endpoint );
  this.logHost = endpoint;
  this.endpoint = `${ endpoint }:${ this.port }`;
}

/**
 * 初始化请求信息
 * @param  {String}   method   请求方法名称
 * @param  {String}   project  日志项目名称
 * @param  {String|Protocol Buffer}   body     请求主体
 * @param  {String}   resource
 * @param  {Object}   params   query
 * @param  {Object}   headers  请求头部信息
 * @param  {Function} callback 回调函数
 * @return void
 */
client._send = function( method, project, body, resource, params, headers, callback ) {
  if (body) {
    headers['Content-Length'] = body.length;
    if (headers['x-log-bodyrawsize'] === undefined) {
      headers['x-log-bodyrawsize'] = 0;
    }
    headers['Content-MD5'] = util.md5( body ).toUpperCase();
  } else {
    headers['Content-Length'] = 0;
    headers['x-log-bodyrawsize'] = 0;
    headers['Content-qType'] = '';  // If not set, http request will add automatically.
  }

  headers['User-Agent'] = USER_AGENT;
  headers['x-log-apiversion'] = API_VERSION;
  headers['x-log-signaturemethod'] = 'hmac-sha1';

  if ( this.stsToken !== '' ) {
    headers['x-acs-security-token'] = this.stsToken;
  }

  if ( !project ) {
    headers['Host'] = this.logHost;
  } else {
    headers['Host'] = `${ project }.${ this.logHost }`;
  }

  headers['Date'] = util.getGMT();

  let signature = util.getRequestAuthorization( method, resource, this.accessKeySecret, this.stsToken, params, headers );
  headers['Authorization'] = `LOG ${ this.accessKey }:${ signature }`;

  let url = resource;
  if ( !_.isEmpty( params ) ) {
    url += `?${ qs.stringify( params ) }`;
  }
  if ( this.isRowIp ) {
    url = `http://${ this.endpoint }${ url }`;
  } else {
    if ( !project ) {
      url = `http://${ this.endpoint }${ url }`;
    } else {
      url = `http://${ project }.${ this.endpoint }${ url }`;
    }
  }
  this._sendRequest( method, url, body, headers, function(err, headers, result ) {
    if ( err ) {
      callback && callback( err );
    } else {
      callback && callback( null, headers, result );
    }
  });
}

/**
 * 发起调用阿里云API请求
 * @param  {String}   method   请求方法名称
 * @param  {String}   url      请求API地址
 * @param  {String|Protocol Buffer}   body   请求主体
 * @param  {Object}   headers  请求头部信息
 * @param  {Function} callback  回调函数
 * @return void
 */
client._sendRequest = function(method, url, body, headers, callback) {
  let options = {
    url : url,
    method : method,
    headers : headers
  }
  if (method == 'POST' || method == 'PUT') options['body'] = body;
  request(options, function( err, response, body ) {
    if ( err ) {
      callback && callback( err ); return;
    }
    try {
      body = JSON.parse( body );
    } catch( err ) {}
    let headers = response.headers;
    if (response.statusCode === 200) {
      callback && callback( null, headers, body );
    } else {
      let requestId = headers['x-log-requestid'] ? headers['x-log-requestid'] : '';
      if ( body['errorCode'] && body['errorMessage'] ) {
        let err = new Exception( body['errorCode'], body['errorMessage'], requestId );
        callback && callback( err );
      } else {
        let err = new Exception( 'RequestError', `Request is failed. Http code is ${ response.statusCode }.The return json is ${ JSON.stringify(body) }`, requestId );
        callback && callback( err );
      }
    }
  })
}

/**
 * 获取日志库列表
 * @param  {String}   project  项目名称
 * @param  {Function} callback 回调函数
 * @return void
 */
client.listLogstores = function( callback ) {
  let body = null;
  let params = {};
  let headers = {};
  let method = 'GET';
  let resource = '/logstores';
  let project = this.project;
  this._send( method, project, body, resource, params, headers, callback );
}

/**
 * 创建日志库 ( CreateLogstore )
 * @param {Object}   options      创建日志库信息
 * @param {Function} callback     回调函数
 */
client.CreateLogstore = function(options, callback) {
  let body = {};
  let params = {};
  let headers = {};
  let method = 'POST';
  let project = this.project;
  let resource = '/logstores';
  headers["x-log-bodyrawsize"] = 0;
  headers["Content-Type"] = "application/json";
  body['ttl'] = Number( options.ttl );
  body['logstoreName'] = options.logstoreName;
  body['shardCount'] = Number( options.shardCount );
  try {
    body = JSON.stringify( body );
  } catch( err ) {
    callback && callback( err );
  }
  this._send( method, project, body, resource, params, headers, callback );
}

/**
 * 向指定LogStore写入日志数据
 * @param {String}   logstoreName LogStore名称
 * @param {Object}   data         日志信息
 * @param {Function} callback     回调函数
 */
client.PostLogStoreLogs = function( logstoreName, data, callback ) {
  let self = this;
  let params = {};
  let headers = {};
  let method = 'POST';
  let project = this.project;
  let resource = `/logstores/${ logstoreName }`;
  //接口每次可以写入的日志数据量上限4096条
  if ( data.logs.length > 4096 ) {
    throw new Exception ( 'InvalidLogSize', "logItems' length exceeds maximum limitation: 4096 lines." );
  }
  //根据protobuf Message格式组装数据
  let group = new Object();
  group['topic'] = data.topic;
  group['source'] = data.source;
  group['logs'] = new Array();

  data.logs.forEach( function( logItem ) {
    let log = new Object();
    log['time'] = logItem.time;
    log['contents'] = new Array();
    logItem.contents.forEach( function( prop ) {
      let content = new Object();
      content['key'] = prop['key'];
      content['value'] = prop['value'];
      log.contents.push( content );
    })
    group['logs'].push( log );
  })

  let LogGroup = Log.LogGroup;
  //转换为Protocol Buffer
  let logger = new LogGroup( group ).toBuffer();
  let body = logger;

  let bodySize = body.length;
  //接口每次可以写入的日志数据量上限为3MB
  if ( bodySize > 3 * 1024 * 1024 ) {
    throw new Exception ( 'InvalidLogSize', "logItems' size exceeds maximum limitation: 3 MB." );
  }
  headers ["x-log-bodyrawsize"] = bodySize;
  headers ['x-log-compresstype'] = 'deflate';
  headers ['Content-Type'] = 'application/x-protobuf';
  //压缩内容
  util.deflate( body, function( err, buf ) {
    if (err) throw err;
    self._send( 'POST', self.project, buf, resource, params, headers, callback);
  })

}

<|endoftext|>


<commit_before>
function dispatcher ( object ) {

    object = object || Object.create( null );

    var _listeners = {};
    var _oneoffs = {};

    object.on = function ( type, listener ) {

        if ( !arguments.length ) return object;
        if ( arguments.length == 1 ) return _listeners[ type ];

        if ( _listeners[ type ] === undefined ) {

            _listeners[ type ] = [];

        }

        if ( _listeners[ type ].indexOf( listener ) === - 1 ) {

            _listeners[ type ].push( listener );

        }

        return object;

    };

    object.once = function ( type, listener ) {

        if ( !arguments.length ) return object;
        if ( arguments.length == 1 ) return _oneoffs[ type ];

        if ( _oneoffs[ type ] === undefined ) {

            _oneoffs[ type ] = [];

        }

        if ( _oneoffs[ type ].indexOf( listener ) === - 1 ) {

            _oneoffs[ type ].push( listener );

        }

        return object;

    };

    object.off = function ( type, listener ) {

        var listenerArray = _listeners[ type ];
        var oneoffArray = _oneoffs[ type ];
        var index;

        if ( listenerArray !== undefined ) {

            index = listenerArray.indexOf( listener );

            if ( index !== - 1 ) {

                listenerArray.splice( index, 1 );

            }

        }

        if ( oneoffArray !== undefined ) {

            index = oneoffArray.indexOf( listener );

            if ( index !== -1 ) {

                oneoffArray.splice( index, 1 );

            }

        }

        return object;

    };

    object.dispatch = function ( event ) {

        var listenerArray = _listeners[ event.type ];
        var oneoffArray = _oneoffs[ event.type ];

        var array = [], i, length;

        if ( listenerArray !== undefined ) {

            event.target = object;

            length = listenerArray.length;

            for ( i = 0; i < length; i ++ ) {

                array[ i ] = listenerArray[ i ];

            }

            for ( i = 0; i < length; i ++ ) {

                array[ i ].call( object, event );

            }

        }

        if ( oneoffArray !== undefined ) {

            event.target = object;

            length = oneoffArray.length;

            for ( i = 0; i < length; i ++ ) {

                array[ i ] = oneoffArray[ i ];

            }

            for ( i = 0; i < length; i ++ ) {

                array[ i ].call( object, event );

            }

            _oneoffs[ event.type ] = [];

        }

        return object;

    };

    return object;

}

export { dispatcher }<commit_msg>Update dispatch to look for target before setting<commit_after>
function dispatcher ( object ) {

    object = object || Object.create( null );

    var _listeners = {};
    var _oneoffs = {};

    object.on = function ( type, listener ) {

        if ( !arguments.length ) return object;
        if ( arguments.length == 1 ) return _listeners[ type ];

        if ( _listeners[ type ] === undefined ) {

            _listeners[ type ] = [];

        }

        if ( _listeners[ type ].indexOf( listener ) === - 1 ) {

            _listeners[ type ].push( listener );

        }

        return object;

    };

    object.once = function ( type, listener ) {

        if ( !arguments.length ) return object;
        if ( arguments.length == 1 ) return _oneoffs[ type ];

        if ( _oneoffs[ type ] === undefined ) {

            _oneoffs[ type ] = [];

        }

        if ( _oneoffs[ type ].indexOf( listener ) === - 1 ) {

            _oneoffs[ type ].push( listener );

        }

        return object;

    };

    object.off = function ( type, listener ) {

        var listenerArray = _listeners[ type ];
        var oneoffArray = _oneoffs[ type ];
        var index;

        if ( listenerArray !== undefined ) {

            index = listenerArray.indexOf( listener );

            if ( index !== - 1 ) {

                listenerArray.splice( index, 1 );

            }

        }

        if ( oneoffArray !== undefined ) {

            index = oneoffArray.indexOf( listener );

            if ( index !== -1 ) {

                oneoffArray.splice( index, 1 );

            }

        }

        return object;

    };

    object.dispatch = function ( event ) {

        var listenerArray = _listeners[ event.type ];
        var oneoffArray = _oneoffs[ event.type ];

        var array = [], i, length;

        if ( listenerArray !== undefined ) {

            if ( event.target === undefined )
                event.target = object;

            length = listenerArray.length;

            for ( i = 0; i < length; i ++ ) {

                array[ i ] = listenerArray[ i ];

            }

            for ( i = 0; i < length; i ++ ) {

                array[ i ].call( object, event );

            }

        }

        if ( oneoffArray !== undefined ) {

            if ( event.target === undefined )
                event.target = object;

            length = oneoffArray.length;

            for ( i = 0; i < length; i ++ ) {

                array[ i ] = oneoffArray[ i ];

            }

            for ( i = 0; i < length; i ++ ) {

                array[ i ].call( object, event );

            }

            _oneoffs[ event.type ] = [];

        }

        return object;

    };

    return object;

}

export { dispatcher }<|endoftext|>


<commit_before>import bodymovin from "bodymovin";

(() => {
  let style = document.createElement("style");
  style.textContent = `
    dlib-bodymovin {
      display: block;
    }
  `;
  document.head.appendChild(style);
})();

export default class BodymovinElement extends HTMLElement {
  constructor() {
    super();
    this.renderer = "svg";
  }

  get src() {
    return this._src;
  }

  set src(value) {
    this._src = value;
    if(this.animation) {
      this.animation.destroy();
    }
    this.animation = bodymovin.loadAnimation({
      container: this,
      renderer: this.renderer,
      path: this._src
    });
    this.animation.addEventListener("DOMLoaded", () => {
      if(this._segments) {
        this.segments = this._segments;
      }
    });
    this.animation.addEventListener("loopComplete", () => {
      this.dispatchEvent(new Event("ended"));
    });
  }

  set segments(value) {
    this._segments = value;
    this.animation.playSegments(this._segments, true);
  }

  get segments() {
    return this._segments;
  }
}

window.customElements.define("dlib-bodymovin", BodymovinElement);
<commit_msg>add loop speed and direction<commit_after>import bodymovin from "bodymovin";

(() => {
  let style = document.createElement("style");
  style.textContent = `
    dlib-bodymovin {
      display: block;
    }
  `;
  document.head.appendChild(style);
})();

export default class BodymovinElement extends HTMLElement {
  constructor() {
    super();
    this.renderer = "svg";
    this.loop = false;
    this.direction = 1;
    this.speed = 1;
  }

  get src() {
    return this._src;
  }

  set src(value) {
    this._src = value;
    if(this.animation) {
      this.animation.destroy();
    }
    this.animation = bodymovin.loadAnimation({
      container: this,
      renderer: this.renderer,
      path: this._src
    });
    this.animation.addEventListener("DOMLoaded", () => {
      if(this._segments) {
        this.segments = this._segments;
      }
      this.loop = this._loop;
      this.direction = this._direction;
      this.speed = this._speed;
    });
    this.animation.addEventListener("loopComplete", () => {
      this.dispatchEvent(new Event("ended"));
    });
    this.animation.addEventListener("complete", () => {
      this.dispatchEvent(new Event("ended"));
    });
  }

  set loop(value) {
    this._loop = value;
    if(this.animation) {
      this.animation.loop = value;
    }
  }

  get loop() {
    return this._loop;
  }

  set direction(value) {
    this._direction = value;
    if(this.animation) {
      this.animation.setDirection(value);
    }
  }

  get direction() {
    return this._direction;
  }

  set speed(value) {
    this._speed = value;
    if(this.animation) {
      this.animation.setSpeed(value);
      this.animation.play();
    }
  }

  get speed() {
    return this._speed;
  }

  set segments(value) {
    this._segments = value;
    if(this.animation) {
      this.animation.playSegments(this._segments, true);
    }
  }

  get segments() {
    return this._segments;
  }
}

window.customElements.define("dlib-bodymovin", BodymovinElement);
<|endoftext|>


<commit_before>const config = require("../config.json");
const { isMod } = require("../util");

exports.run = function (message, args, bot, db, showOnlyNew) {
  db.query("SELECT * FROM trivia_questions WHERE id = ?", [args], function (
    err,
    rows
  ) {
    if (rows[0] == null) {
      message.reply("That question does not exist.");
      return;
    }
    if (
      rows[0].user != message.author.id &&
      message.author.id != config.botAdminUserId
    ) {
      message.reply("You do not have permission to view these answers.");
      return;
    }
    getAnswerList(message, rows[0], showOnlyNew, bot, db);
  });
};

function getAnswerList(message, questionRow, showOnlyNew, bot, db) {
  let id = questionRow.id;
  let question = questionRow.question;
  let questionAsker = questionRow.user;
  let query =
    "SELECT user, answer FROM trivia_answers WHERE questionid = ? ORDER BY id";
  if (showOnlyNew) {
    query =
      "SELECT user, answer FROM trivia_answers WHERE questionid = ? AND viewed = 0 ORDER BY id";
  }
  const questionStatus = questionRow.isopen ? "Open" : "Closed";
  db.query(query, [id], function (err, rows) {
    let response =
      "**Answers for question #" +
      id +
      ": " +
      question +
      " (" +
      questionStatus +
      ")**\n";
    let userList = [];
    let userIdList = [];
    for (var i = 0; i < rows.length; i++) {
      let answer = rows[i].answer;
      let user = bot.users.resolve(rows[i].user);
      let username = user ? "@" + user.tag : "Unknown user " + rows[i].user;
      let answerEntry = "**" + username + "**\n" + answer + "\n\n";
      response += answerEntry;
      if (user) {
        userList.push(username);
        userIdList.push("<@!" + user.id + ">");
      }
    }
    let mainServer = bot.guilds.cache.get(config.mainServer);
    let userListString = "";
    if (
      typeof mainServer !== "undefined" &&
      isMod(message.author.id, mainServer) &&
      userList.length > 0
    ) {
      userListString +=
        "User list for awarding: ```\n" + userList.join(" ") + "```";
      userListString +=
        "User list as IDs for awarding: ```\n" + userIdList.join(" ") + "```";
    }
    if (message.author.id == questionAsker) {
      db.query("UPDATE trivia_answers SET viewed=1 WHERE questionid = ?", [id]);
    }
    if (response.length + userListString.length > 2000) {
      message.reply(response, { split: true });
      message.reply(userListString, { split: true });
    } else {
      message.reply(response, { split: true });
    }
  });
}
<commit_msg>tweak split length<commit_after>const config = require("../config.json");
const { isMod } = require("../util");

exports.run = function (message, args, bot, db, showOnlyNew) {
  db.query("SELECT * FROM trivia_questions WHERE id = ?", [args], function (
    err,
    rows
  ) {
    if (rows[0] == null) {
      message.reply("That question does not exist.");
      return;
    }
    if (
      rows[0].user != message.author.id &&
      message.author.id != config.botAdminUserId
    ) {
      message.reply("You do not have permission to view these answers.");
      return;
    }
    getAnswerList(message, rows[0], showOnlyNew, bot, db);
  });
};

function getAnswerList(message, questionRow, showOnlyNew, bot, db) {
  let id = questionRow.id;
  let question = questionRow.question;
  let questionAsker = questionRow.user;
  let query =
    "SELECT user, answer FROM trivia_answers WHERE questionid = ? ORDER BY id";
  if (showOnlyNew) {
    query =
      "SELECT user, answer FROM trivia_answers WHERE questionid = ? AND viewed = 0 ORDER BY id";
  }
  const questionStatus = questionRow.isopen ? "Open" : "Closed";
  db.query(query, [id], function (err, rows) {
    let response =
      "**Answers for question #" +
      id +
      ": " +
      question +
      " (" +
      questionStatus +
      ")**\n";
    let userList = [];
    let userIdList = [];
    for (var i = 0; i < rows.length; i++) {
      let answer = rows[i].answer;
      let user = bot.users.resolve(rows[i].user);
      let username = user ? "@" + user.tag : "Unknown user " + rows[i].user;
      let answerEntry = "**" + username + "**\n" + answer + "\n\n";
      response += answerEntry;
      if (user) {
        userList.push(username);
        userIdList.push("<@!" + user.id + ">");
      }
    }
    let mainServer = bot.guilds.cache.get(config.mainServer);
    let userListString = "";
    if (
      typeof mainServer !== "undefined" &&
      isMod(message.author.id, mainServer) &&
      userList.length > 0
    ) {
      userListString +=
        "User list for awarding: ```\n" + userList.join(" ") + "```";
      userListString +=
        "User list as IDs for awarding: ```\n" + userIdList.join(" ") + "```";
    }
    if (message.author.id == questionAsker) {
      db.query("UPDATE trivia_answers SET viewed=1 WHERE questionid = ?", [id]);
    }
    if (response.length + userListString.length > 1900) {
      message.reply(response, { split: true });
      message.reply(userListString, { split: true });
    } else {
      message.reply(response, { split: true });
    }
  });
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'inactivity-notice');
const guildmember = message.content.split(" ").join(" ").slice(12)
const muteRole = client.guilds.get(message.guild.id).roles.find('name', `Inactive`);
const say = args.slice(1).join(' ');
if (say.length < 1) return message.reply('Please specify on the reason for going inactive.').catch(console.error);
message.delete()
message.guild.member(message.author).addRole(muteRole);
client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Inactivity Notice`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Message",
  value: `${say}`
  }]
    }
    })
};

const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'inactivity-notice');
const guildmember = message.content.split(" ").join(" ").slice(12)
const say = args.slice(1).join(' ');
if (say.length < 1) return message.reply('Please specify on what I have to say.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Inactivity Notice`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Message",
  value: `${say}`
  }]
    }
    })
};

message.author.sendMessage({embed: {
  color: 0xff0000,
  title: "Inactivity Notice Filed",
  description: (`\n**You have filed an inactivity notice!**\n`),
fields: [{
name: "ROBLOX Username:",
value: `${guildmember}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please use the command ;active.",
value: "Otherwise, please use the command ;active after you are not inactive anymore to remove your inactive tag."
}]
    }});
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'inactivity',
description: 'Files an inactivity notice under the channel #inactivity-notice',
usage: 'inactivity (ROBLOX USERNAME) message'
};

exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'inactivity',
description: 'Files an inactivity notice under the channel #inactivity-notice',
usage: 'inactivity (ROBLOX USERNAME) message'
};
<commit_msg>Update inactivity.js<commit_after>const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'inactivity-notice');
const guildmember = message.content.split(" ").join(" ").slice(12)
const say = args.slice(1).join(' ');
if (say.length < 1) return message.reply('Please specify on what I have to say.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Inactivity Notice`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Message",
  value: `${say}`
  }]
    }
    })
};

message.author.sendMessage({embed: {
  color: 0xff0000,
  title: "Inactivity Notice Filed",
  description: (`\n**You have filed an inactivity notice!**\n`),
fields: [{
name: "ROBLOX Username:",
value: `${guildmember}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please use the command ;active.",
value: "Otherwise, please use the command ;active after you are not inactive anymore to remove your inactive tag."
}]
    }});

exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'inactivity',
description: 'Files an inactivity notice under the channel #inactivity-notice',
usage: 'inactivity (ROBLOX USERNAME) message'
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const ms = require('ms');
exports.run = (client, message, args) => {
  const rank = args.slice(1).join(' ');
  const user = message.mentions.users.first();
  const modlog = client.channels.find('name', 'mod-log');
  if (!modlog) return message.reply('I cannot find a mod-log channel').catch(console.error);
  if (rank.length < 1) return message.reply('You must supply a rank.').catch(console.error);
  if (message.mentions.users.size < 1) return message.reply('You must mention someone to mute them.').catch(console.error);
  const muteRole = client.guilds.get(message.guild.id).roles.find('name', `${rank}`);
  const embed = new Discord.RichEmbed()
  .setTimestamp()
  .setColor(0x00ff00)
  .setTitle("User Rank Modified")
  .setThumbnail(`${user.avatarURL}`)
  .setDescription(`\n`)
  .addField("Username:",`${user.username} (${user})`,true)
  .addField("Moderator:",`${message.author.username} (${message.author})`, true)
  .addField("Removed Rank:",`${rank}`, false)
  .setFooter(`User: ${user.username}`,`${user.avatarURL}`);

  user.sendMessage({embed: {
color: 0x00ff00,
title: "User rank removed",
description: (`\nYour rank has been removed!\n`),
fields: [{
  name : "Username:",
  value : `${user.username} (${user})`,
  inline : true
},{
  name : "Administrator:",
  value :`${message.author.username} (${message.author})`,
  inline : true
},{
  name : "Removed rank:",
  value : `${rank}`,
  inline : false
},{
  name : "If you believe that this was an error, please contact the Administrator involved.",
  value : `~ Canadian Army`,
  inline : false
}]
  }})

  if (!message.guild.member(client.user).hasPermission('MANAGE_ROLES_OR_PERMISSIONS')) return message.reply('I do not have the correct permissions.').catch(console.error);

    message.guild.member(user).removeRole(muteRole).then(() => {
      client.channels.get(modlog.id).send({embed}).catch(console.error);
     message.channel.send({embed}).catch(console.error);
    });
  }

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ['rrank','demote','delrole'],
  permLevel: 3
};

exports.help = {
  name: 'removerank',
  description: 'Removes a role to the discord user.',
  usage: 'removerank [mention] [role]'
};
<commit_msg>Update rankremove.js<commit_after>const Discord = require('discord.js');
const ms = require('ms');
exports.run = (client, message, args) => {
  const rank = args.slice(1).join(' ');
  const user = message.mentions.users.first();
  const modlog = client.channels.find('name', 'mod-log');
  if (!modlog) return message.reply('I cannot find a mod-log channel').catch(console.error);
  if (rank.length < 1) return message.reply('You must supply a rank.').catch(console.error);
  if (message.mentions.users.size < 1) return message.reply('You must mention someone to demote them.').catch(console.error);
  const muteRole = client.guilds.get(message.guild.id).roles.find('name', `${rank}`);
  const embed = new Discord.RichEmbed()
  .setTimestamp()
  .setColor(0x00ff00)
  .setTitle("User Rank Modified")
  .setThumbnail(`${user.avatarURL}`)
  .setDescription(`\n`)
  .addField("Username:",`${user.username} (${user})`,true)
  .addField("Moderator:",`${message.author.username} (${message.author})`, true)
  .addField("Removed Rank:",`${rank}`, false)
  .setFooter(`User: ${user.username}`,`${user.avatarURL}`);

  user.sendMessage({embed: {
color: 0x00ff00,
title: "User rank removed",
description: (`\nYour rank has been removed!\n`),
fields: [{
  name : "Username:",
  value : `${user.username} (${user})`,
  inline : true
},{
  name : "Administrator:",
  value :`${message.author.username} (${message.author})`,
  inline : true
},{
  name : "Removed rank:",
  value : `${rank}`,
  inline : false
},{
  name : "If you believe that this was an error, please contact the Administrator involved.",
  value : `~ Union Army`,
  inline : false
}]
  }})

  if (!message.guild.member(client.user).hasPermission('MANAGE_ROLES_OR_PERMISSIONS')) return message.reply('I do not have the correct permissions.').catch(console.error);

    message.guild.member(user).removeRole(muteRole).then(() => {
      client.channels.get(modlog.id).send({embed}).catch(console.error);
     message.channel.send({embed}).catch(console.error);
    });
  }

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ['rrank','demote','delrole'],
  permLevel: 3
};

exports.help = {
  name: 'removerank',
  description: 'Removes a role to the discord user.',
  usage: 'removerank [mention] [role]'
};
<|endoftext|>


<commit_before>describe("editor", function() {
  beforeEach(() => {
    cy.visit("");
  });

  it(`should be able to set visibilities!`, () => {
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("exist");
    cy.tgToggle("setDefaultVisibilities");
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("not.exist");
    //toggling the read only toggle should not affect any visibilities
    cy.tgToggle("readOnly");
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("not.exist");
  });
  it("can drag the editor", function() {
    cy.contains("No Selection");
    cy.dragBetween(`[data-row-number="0"]`, `[data-row-number="1"]`);
    cy.contains("No Selection").should("not.exist");
  });

  it(`should autosave if autosave=true`, function() {
    cy.tgToggle("shouldAutosave");

    cy.get(".veRowViewPartsContainer")
      .contains("Part 0")
      .first()
      .click({ force: true });
    cy.get(".veRowViewSelectionLayer")
      .first()
      .trigger("contextmenu", { force: true });
    cy.get(".bp3-menu-item")
      .contains("Cut")
      .click();
    cy.contains("onCopy callback triggered");
    cy.contains("onSave callback triggered");
    cy.contains("Selection Cut");
  });
  it(`should handle rightClickOverrides correctly if they are passed`, function() {
    cy.tgToggle("overrideRightClickExample");

    cy.get(".veLabelText")
      .contains("Part 0")
      .trigger("contextmenu", { force: true });
    cy.get(".bp3-menu")
      .contains("My Part Override")
      .click();
    cy.contains("Part Override Hit!").should("be.visible");
  });
  it(`should handle clickOverrides correctly if they are passed`, function() {
    cy.tgToggle("clickOverridesExample");

    cy.get(".veLabelText")
      .contains("Part 0")
      .click({ force: true });

    cy.contains("Part Click Override Hit!").should("be.visible");
    //clicking the part SHOULD change the selection because in this demo the default part click is not
    cy.contains("div", "Selecting 21 bps from 11 to 31").should("be.visible");

    cy.get(".veLabelText")
      .contains("araC")
      .click({ force: true });

    cy.contains("Feature Click Override Hit!").should("be.visible");
    //clicking the feature SHOULD NOT change the selection because in this demo the default feature click is overridden
    cy.contains("div", "Selecting 21 bps from 11 to 31").should("be.visible");
  });
  it(`should handle propertiesListOverrides correctly if they are passed`, function() {
    cy.tgToggle("propertiesOverridesExample");

    cy.get(".veTabProperties").click();
    cy.get(`[data-tab-id="parts"]`).click();
    cy.get(".ve-propertiesPanel")
      .contains("parts footer button")
      .click();

    cy.get(".bp3-toast")
      .contains("properties overrides successfull")
      .should("be.visible");
  });
  it(`should handle custom menu filters correctly`, () => {
    cy.tgToggle("menuOverrideExample");
    cy.get(".tg-menu-bar")
      .contains("Custom")
      .click();
    cy.get(".bp3-menu-item")
      .contains("Copy")
      .click();
    cy.get(".bp3-toast").contains("No Sequence Selected To Copy");
    cy.get(".tg-menu-bar")
      .contains("File")
      .click();
    cy.get(".bp3-menu-item")
      .contains("Export Sequence")
      .trigger("mouseover");
    cy.contains(".bp3-menu-item", "Custom export option!").click();
    cy.get(".bp3-toast").contains("Custom export hit!");
  });
  it(`should handle custom dialog overrides correctly`, () => {
    cy.tgToggle("overrideAddEditFeatureDialog");
    cy.get(".tg-menu-bar")
      .contains("Edit")
      .click();
    cy.contains(".bp3-menu-item", "Create").click();
    cy.contains(".bp3-menu-item", "New Feature").click();
    cy.contains("I Am Overridden. Any custom React can go here");
  });
  it(`should focus the linear view`, () => {
    cy.get(".veLinearView").should("not.be.visible");
    cy.contains("Focus Linear View").click();
    cy.get(".veLinearView").should("be.visible");
  });
  it(`should shuffle the tabs programatically`, () => {
    cy.get(".veLinearView").should("not.be.visible");
    cy.tgToggle("customizeTabs");
    cy.get(".veLinearView").should("be.visible");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("Sequence Map");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("New Alignment");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("Circular Map");
  });
  it(`should handle beforeSequenceInsertOrDelete hook correctly`, () => {
    cy.tgToggle("beforeSequenceInsertOrDelete");
    cy.contains(".veLabelText", "T0").trigger("contextmenu", { force: true });
    cy.contains(".bp3-menu-item", "Replace").click();

    cy.get(".sequenceInputBubble input").type("tta{enter}");
    cy.contains(".veLabelText", "CHANGED_SEQ");
  });
});
<commit_msg>fixing test<commit_after>describe("editor", function() {
  beforeEach(() => {
    cy.visit("");
  });

  it(`should be able to set visibilities!`, () => {
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("exist");
    cy.tgToggle("setDefaultVisibilities");
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("not.exist");
    //toggling the read only toggle should not affect any visibilities
    cy.tgToggle("readOnly");
    cy.get(".ve-tool-container-cutsiteTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-featureTool .bp3-active").should("not.exist");
    cy.get(".ve-tool-container-oligoTool .bp3-active").should("not.exist");
  });
  it("can drag the editor", function() {
    cy.contains("No Selection");
    cy.dragBetween(`[data-row-number="0"]`, `[data-row-number="1"]`);
    cy.contains("No Selection").should("not.exist");
  });

  it(`should autosave if autosave=true`, function() {
    cy.tgToggle("shouldAutosave");

    cy.get(".veRowViewPartsContainer")
      .contains("Part 0")
      .first()
      .click({ force: true });
    cy.get(".veRowViewSelectionLayer")
      .first()
      .trigger("contextmenu", { force: true });
    cy.get(".bp3-menu-item")
      .contains("Cut")
      .click();
    cy.contains("onCopy callback triggered");
    cy.contains("onSave callback triggered");
    cy.contains("Selection Cut");
  });
  it(`should handle rightClickOverrides correctly if they are passed`, function() {
    cy.tgToggle("overrideRightClickExample");

    cy.get(".veLabelText")
      .contains("Part 0")
      .trigger("contextmenu", { force: true });
    cy.get(".bp3-menu")
      .contains("My Part Override")
      .click();
    cy.contains("Part Override Hit!").should("be.visible");
  });
  it(`should handle clickOverrides correctly if they are passed`, function() {
    cy.tgToggle("clickOverridesExample");

    cy.get(".veLabelText")
      .contains("Part 0")
      .click({ force: true });

    cy.contains("Part Click Override Hit!").should("be.visible");
    //clicking the part SHOULD change the selection because in this demo the default part click is not
    cy.contains("div", "Selecting 21 bps from 11 to 31").should("be.visible");

    cy.get(".veLabelText")
      .contains("araC")
      .click({ force: true });

    cy.contains("Feature Click Override Hit!").should("be.visible");
    //clicking the feature SHOULD NOT change the selection because in this demo the default feature click is overridden
    cy.contains("div", "Selecting 21 bps from 11 to 31").should("be.visible");
  });
  it(`should handle propertiesListOverrides correctly if they are passed`, function() {
    cy.tgToggle("propertiesOverridesExample");

    cy.get(".veTabProperties").click();
    cy.get(`[data-tab-id="parts"]`).click();
    cy.get(".ve-propertiesPanel")
      .contains("parts footer button")
      .click();

    cy.get(".bp3-toast")
      .contains("properties overrides successfull")
      .should("be.visible");
  });
  it(`should handle custom menu filters correctly`, () => {
    cy.tgToggle("menuOverrideExample");
    cy.get(".tg-menu-bar")
      .contains("Custom")
      .click();
    cy.get(".bp3-menu-item")
      .contains("Copy")
      .click();
    cy.get(".bp3-toast").contains("No Sequence Selected To Copy");
    cy.get(".tg-menu-bar")
      .contains("File")
      .click();
    cy.get(".bp3-menu-item")
      .contains("Export Sequence")
      .trigger("mouseover");
    cy.contains(".bp3-menu-item", "Custom export option!").click({
      force: true
    });
    cy.get(".bp3-toast").contains("Custom export hit!");
  });
  it(`should handle custom dialog overrides correctly`, () => {
    cy.tgToggle("overrideAddEditFeatureDialog");
    cy.get(".tg-menu-bar")
      .contains("Edit")
      .click();
    cy.contains(".bp3-menu-item", "Create").click();
    cy.contains(".bp3-menu-item", "New Feature").click();
    cy.contains("I Am Overridden. Any custom React can go here");
  });
  it(`should focus the linear view`, () => {
    cy.get(".veLinearView").should("not.be.visible");
    cy.contains("Focus Linear View").click();
    cy.get(".veLinearView").should("be.visible");
  });
  it(`should shuffle the tabs programatically`, () => {
    cy.get(".veLinearView").should("not.be.visible");
    cy.tgToggle("customizeTabs");
    cy.get(".veLinearView").should("be.visible");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("Sequence Map");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("New Alignment");
    cy.get(".ve-draggable-tabs")
      .last()
      .contains("Circular Map");
  });
  it(`should handle beforeSequenceInsertOrDelete hook correctly`, () => {
    cy.tgToggle("beforeSequenceInsertOrDelete");
    cy.contains(".veLabelText", "T0").trigger("contextmenu", { force: true });
    cy.contains(".bp3-menu-item", "Replace").click();

    cy.get(".sequenceInputBubble input").type("tta{enter}");
    cy.contains(".veLabelText", "CHANGED_SEQ");
  });
});
<|endoftext|>