<commit_before>// define a adminapp namespace in jQuery and all related methodes
(function($){
    $.fn.adminapp = function(){};

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findList = function(str, fieldList, ignoreList) {
        ignoreList = (typeof(ignoreList) == "undefined") ? [] : ignoreList;
        var list = [];

        // get all el with id attr
        list = fieldList.filter("[id]");
        // find els with id containing searched str
        list = list.filter(function(index) {
            if (this.id.indexOf(str) > -1) {
                return this;
            }
        });
        // remove ignored els
        list = list.filter(function(index) {
            if (ignoreList.length > 0) {
                for (var j=0; j<ignoreList.length; j++) {
                    if (this.id.indexOf(ignoreList[j]) == -1) {
                        return this;
                    }
                }
            } else {
                return this;
            }
        });

        return list;
    };

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findField = function(str, ignoreList) {
        var result = this.findList(str, this.fieldList, ignoreList);
        if (result.length == 0) {
            result = this.findList(str, this.selectList, ignoreList);
        }
        return result;
    };

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findSelect = function(str, ignoreList) {
        return this.findList(str, this.selectList, ignoreList);
    };

    /**
     * attach toogleAddress event on the secondary address checkbox
     */
    $.fn.adminapp.bindEventOnAddress = function(el) {
        var chk = $('#' + el.id);
        chk.bind('click', function(event) {
            $.fn.adminapp.toogleAddress(event.target);
        });
    };

    /**
     * attach toogle restrictionarea event on the secondary "public" checkbox
     */
    $.fn.adminapp.bindEventOnLayer = function(pl, lt) {
        var chk = $('#' + pl.id);
        chk.bind('click', function(event) {
            $.fn.adminapp.toogleRestrictionAreas(event.target);
        });
        chk = $('#' + lt.id);
        chk.bind('change', function(event) {
            $.fn.adminapp.toogleLayerType(event.target);
        });
    };

    /**
     * attach toogle internal WMS on Base Layer.
     */
    $.fn.adminapp.bindEventOnLayerGroup = function(wmsi, bl) {
        wmsi.bind('change', function(event) {
            $.fn.adminapp.toogleBaseLayer(wmsi, bl);
        });
    };

    /**
     * show / hide secondary address input fields
     */
    $.fn.adminapp.toogleAddress = function(el) {
        var els = $.fn.adminapp.findField('b_', [el.id]);
        /* this code can be used to show/hide block instead of enabling/disabling inputs
        var d = 'block';
        */
        var state = false;
        if (!el.checked) {
            //d = 'none';
            state = true;
        }

        if (state) {
            $.fn.adminapp.resetField(els);
            els.addClass('disabledinput');
        } else {
            els.removeClass('disabledinput');
        }
        // reset value and set readonly
        els.attr('readOnly', state);
        // can NOT use disabled as FA expect the field to be in request
        // els.attr('disabled', state);
    };

    /**
     * show / hide restrictionArea input fields
     */
    $.fn.adminapp.toogleRestrictionAreas = function(el) {
        var els = $.fn.adminapp.findField('restrictionareas', [el.id]);
        var state = el.checked;
        if (state) {
            // reset value
            $.fn.adminapp.resetField(els);

            els.addClass('disabledinput');
        } else {
            els.removeClass('disabledinput');
        }
        // set readonly
        els.attr('readOnly', state);
        els.attr('disabled', state);
    };

    /**
     * show / hide unneeded fields
     */
    $.fn.adminapp.toogleLayerType = function(el) {
        var state = el.value;
        var fields = [];
        if (state == "internal WMS") {
            fields = ["legendRule"];
        }
        else if (state == "external WMS") {
            fields = ["url", "style", "imageType", "legendRule", "isSingleTile"];
        }
        else if (state == "WMTS") {
            fields = ["url", "style", "dimensions", "matrixSet", "wmsUrl", "wmsLayers"];
        }

        var change = function(field, fields) {
            var e = $.fn.adminapp.findField(field, [el.id]);
            var state = jQuery.inArray(field, fields) >= 0;
            if (state) {
                e.removeClass('disabledinput');
            }
            else {
                e.addClass('disabledinput');
            }
            e.attr('readOnly', !state);
            if (e[0].tagName != "INPUT") {
                e.attr('disabled', !state);
            }
        };

        change("url", fields);
        change("imageType", fields);
        change("style", fields);
        change("dimensions", fields);
        change("matrixSet", fields);
        change("wmsUrl", fields);
        change("wmsLayers", fields);
        change("isSingleTile", fields);
        change("legendRule", fields);

        internalWMS = state == "internal WMS"
        var e = $.fn.adminapp.findField("public",  [el.id]);
        if (internalWMS) {
            e.removeClass('disabledinput');
        }
        else {
            e.addClass('disabledinput');
            e.attr('checked', true);
            this.toogleRestrictionAreas(e[0]);
        }
        e.attr('readOnly', !internalWMS);
        // true should be send ...
        //e.attr('disabled', !internalWMS);
    };

    $.fn.adminapp.toogleBaseLayer = function(wmsi, bl) {
        var state = wmsi[0].checked;
        if (state) {
            // reset value
            $.fn.adminapp.resetField(bl);

            bl.addClass('disabledinput');
        } else {
            bl.removeClass('disabledinput');
        }
        // set readonly
        bl.attr('readOnly', state);
        bl.attr('disabled', state);
    };

    /**
     * get the parent div containing on input field
     */
    $.fn.adminapp.getParentBLock = function(el) {
        var p = el.parentNode;
        while (p.nodeName.toLowerCase() != 'div') {
            p = p.parentNode;
        }
        return p;
    };

    /**
     * reset input value or state
     */
    $.fn.adminapp.resetField = function(el) {
        for (var i = 0 ; i < el.length ; i++) {
            switch (el[i].type) {
              case 'checkbox':
                  el[i].checked = false;
                  break;
              case 'radio':
                  break;
              default:
                  el[i].value = '';
            }
        }
    };

    $.fn.adminapp.syncField = function(el) {
        var cbl = $.fn.adminapp.checkboxcorrespondance[el.target.id];
        for (var i = 0, len = cbl.length ; i < len ; i++) {
            cbl[i].checked = el.target.checked;
        }
    };

})(jQuery);

$(document).ready(function(){

    // store all fields
    $.fn.adminapp.fieldList = $("input");
    $.fn.adminapp.selectList = $("select");

    // attach event on User.b_company to show/hide secondary address fields (b_*)
    var f = $.fn.adminapp.findField('b_company');
    if (f.length > 0) {
        $.fn.adminapp.bindEventOnAddress(f[0]);
        // init state
        $.fn.adminapp.toogleAddress(f[0]);
    }

    // attach event on Layer.public to show/hide restrictionareas
    var pl = $.fn.adminapp.findField('public');
    var lt = $.fn.adminapp.findSelect('layerType');
    //Select('layerType');
    if (pl.length > 0 && lt.length > 0) {
        // restrictionareas
        $.fn.adminapp.bindEventOnLayer(pl[0], lt[0]);
        // init state
        $.fn.adminapp.toogleRestrictionAreas(pl[0]);
        $.fn.adminapp.toogleLayerType(lt[0]);
    }

    /**
     * When a layer(or group) is display more than one time
     * this will sync the state on all tree items.
     */

    // store field correspondence
    $.fn.adminapp.checkboxcorrespondance = {};
    var checkboxtrees = $(".checkboxtree");
    for (var i = 0, leni = checkboxtrees.length ; i < leni ; i++) {
        var checkboxlist = $("#" + checkboxtrees[i].id + " input");
        for (var j = 0, lenj = checkboxlist.length ; j < lenj ; j++) {
            if (checkboxlist[j].id) {
                var samenamecheckbox = $("input[value=" + checkboxlist[j].value + ']');
                if (samenamecheckbox.length > 1) {
                    $.fn.adminapp.checkboxcorrespondance[checkboxlist[j].id] = samenamecheckbox;
                    $("#" + checkboxlist[j].id).bind('change', $.fn.adminapp.syncField);
                }
            }
        }
    }

    var wmsi = $.fn.adminapp.findField('isInternalWMS')
    var bl = $.fn.adminapp.findField('isBaseLayer')
    if (wmsi.length > 0 && bl.length > 0) {
        $.fn.adminapp.bindEventOnLayerGroup(wmsi, bl);
        // init state
        $.fn.adminapp.toogleBaseLayer(wmsi, bl);
    }

});
<commit_msg>limit the checkbox link to the checkboxtrees<commit_after>// define a adminapp namespace in jQuery and all related methodes
(function($){
    $.fn.adminapp = function(){};

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findList = function(str, fieldList, ignoreList) {
        ignoreList = (typeof(ignoreList) == "undefined") ? [] : ignoreList;
        var list = [];

        // get all el with id attr
        list = fieldList.filter("[id]");
        // find els with id containing searched str
        list = list.filter(function(index) {
            if (this.id.indexOf(str) > -1) {
                return this;
            }
        });
        // remove ignored els
        list = list.filter(function(index) {
            if (ignoreList.length > 0) {
                for (var j=0; j<ignoreList.length; j++) {
                    if (this.id.indexOf(ignoreList[j]) == -1) {
                        return this;
                    }
                }
            } else {
                return this;
            }
        });

        return list;
    };

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findField = function(str, ignoreList) {
        var result = this.findList(str, this.fieldList, ignoreList);
        if (result.length == 0) {
            result = this.findList(str, this.selectList, ignoreList);
        }
        return result;
    };

    /**
     * find an element in the dom whose id match str and not contained in ignoreList
     */
    $.fn.adminapp.findSelect = function(str, ignoreList) {
        return this.findList(str, this.selectList, ignoreList);
    };

    /**
     * attach toogleAddress event on the secondary address checkbox
     */
    $.fn.adminapp.bindEventOnAddress = function(el) {
        var chk = $('#' + el.id);
        chk.bind('click', function(event) {
            $.fn.adminapp.toogleAddress(event.target);
        });
    };

    /**
     * attach toogle restrictionarea event on the secondary "public" checkbox
     */
    $.fn.adminapp.bindEventOnLayer = function(pl, lt) {
        var chk = $('#' + pl.id);
        chk.bind('click', function(event) {
            $.fn.adminapp.toogleRestrictionAreas(event.target);
        });
        chk = $('#' + lt.id);
        chk.bind('change', function(event) {
            $.fn.adminapp.toogleLayerType(event.target);
        });
    };

    /**
     * attach toogle internal WMS on Base Layer.
     */
    $.fn.adminapp.bindEventOnLayerGroup = function(wmsi, bl) {
        wmsi.bind('change', function(event) {
            $.fn.adminapp.toogleBaseLayer(wmsi, bl);
        });
    };

    /**
     * show / hide secondary address input fields
     */
    $.fn.adminapp.toogleAddress = function(el) {
        var els = $.fn.adminapp.findField('b_', [el.id]);
        /* this code can be used to show/hide block instead of enabling/disabling inputs
        var d = 'block';
        */
        var state = false;
        if (!el.checked) {
            //d = 'none';
            state = true;
        }

        if (state) {
            $.fn.adminapp.resetField(els);
            els.addClass('disabledinput');
        } else {
            els.removeClass('disabledinput');
        }
        // reset value and set readonly
        els.attr('readOnly', state);
        // can NOT use disabled as FA expect the field to be in request
        // els.attr('disabled', state);
    };

    /**
     * show / hide restrictionArea input fields
     */
    $.fn.adminapp.toogleRestrictionAreas = function(el) {
        var els = $.fn.adminapp.findField('restrictionareas', [el.id]);
        var state = el.checked;
        if (state) {
            // reset value
            $.fn.adminapp.resetField(els);

            els.addClass('disabledinput');
        } else {
            els.removeClass('disabledinput');
        }
        // set readonly
        els.attr('readOnly', state);
        els.attr('disabled', state);
    };

    /**
     * show / hide unneeded fields
     */
    $.fn.adminapp.toogleLayerType = function(el) {
        var state = el.value;
        var fields = [];
        if (state == "internal WMS") {
            fields = ["legendRule"];
        }
        else if (state == "external WMS") {
            fields = ["url", "style", "imageType", "legendRule", "isSingleTile"];
        }
        else if (state == "WMTS") {
            fields = ["url", "style", "dimensions", "matrixSet", "wmsUrl", "wmsLayers"];
        }

        var change = function(field, fields) {
            var e = $.fn.adminapp.findField(field, [el.id]);
            var state = jQuery.inArray(field, fields) >= 0;
            if (state) {
                e.removeClass('disabledinput');
            }
            else {
                e.addClass('disabledinput');
            }
            e.attr('readOnly', !state);
            if (e[0].tagName != "INPUT") {
                e.attr('disabled', !state);
            }
        };

        change("url", fields);
        change("imageType", fields);
        change("style", fields);
        change("dimensions", fields);
        change("matrixSet", fields);
        change("wmsUrl", fields);
        change("wmsLayers", fields);
        change("isSingleTile", fields);
        change("legendRule", fields);

        internalWMS = state == "internal WMS"
        var e = $.fn.adminapp.findField("public",  [el.id]);
        if (internalWMS) {
            e.removeClass('disabledinput');
        }
        else {
            e.addClass('disabledinput');
            e.attr('checked', true);
            this.toogleRestrictionAreas(e[0]);
        }
        e.attr('readOnly', !internalWMS);
        // true should be send ...
        //e.attr('disabled', !internalWMS);
    };

    $.fn.adminapp.toogleBaseLayer = function(wmsi, bl) {
        var state = wmsi[0].checked;
        if (state) {
            // reset value
            $.fn.adminapp.resetField(bl);

            bl.addClass('disabledinput');
        } else {
            bl.removeClass('disabledinput');
        }
        // set readonly
        bl.attr('readOnly', state);
        bl.attr('disabled', state);
    };

    /**
     * get the parent div containing on input field
     */
    $.fn.adminapp.getParentBLock = function(el) {
        var p = el.parentNode;
        while (p.nodeName.toLowerCase() != 'div') {
            p = p.parentNode;
        }
        return p;
    };

    /**
     * reset input value or state
     */
    $.fn.adminapp.resetField = function(el) {
        for (var i = 0 ; i < el.length ; i++) {
            switch (el[i].type) {
              case 'checkbox':
                  el[i].checked = false;
                  break;
              case 'radio':
                  break;
              default:
                  el[i].value = '';
            }
        }
    };

    $.fn.adminapp.syncField = function(el) {
        var cbl = $.fn.adminapp.checkboxcorrespondance[el.target.id];
        for (var i = 0, len = cbl.length ; i < len ; i++) {
            cbl[i].checked = el.target.checked;
        }
    };

})(jQuery);

$(document).ready(function(){

    // store all fields
    $.fn.adminapp.fieldList = $("input");
    $.fn.adminapp.selectList = $("select");

    // attach event on User.b_company to show/hide secondary address fields (b_*)
    var f = $.fn.adminapp.findField('b_company');
    if (f.length > 0) {
        $.fn.adminapp.bindEventOnAddress(f[0]);
        // init state
        $.fn.adminapp.toogleAddress(f[0]);
    }

    // attach event on Layer.public to show/hide restrictionareas
    var pl = $.fn.adminapp.findField('public');
    var lt = $.fn.adminapp.findSelect('layerType');
    //Select('layerType');
    if (pl.length > 0 && lt.length > 0) {
        // restrictionareas
        $.fn.adminapp.bindEventOnLayer(pl[0], lt[0]);
        // init state
        $.fn.adminapp.toogleRestrictionAreas(pl[0]);
        $.fn.adminapp.toogleLayerType(lt[0]);
    }

    /**
     * When a layer(or group) is display more than one time
     * this will sync the state on all tree items.
     */

    // store field correspondence
    $.fn.adminapp.checkboxcorrespondance = {};
    var checkboxtrees = $(".checkboxtree");
    for (var i = 0, leni = checkboxtrees.length ; i < leni ; i++) {
        var checkboxlist = $("#" + checkboxtrees[i].id + " input");
        for (var j = 0, lenj = checkboxlist.length ; j < lenj ; j++) {
            if (checkboxlist[j].id) {
                var samenamecheckbox = $("#" + checkboxtrees[i].id + " input[value=" + checkboxlist[j].value + ']');
                if (samenamecheckbox.length > 1) {
                    $.fn.adminapp.checkboxcorrespondance[checkboxlist[j].id] = samenamecheckbox;
                    $("#" + checkboxlist[j].id).bind('change', $.fn.adminapp.syncField);
                }
            }
        }
    }

    var wmsi = $.fn.adminapp.findField('isInternalWMS')
    var bl = $.fn.adminapp.findField('isBaseLayer')
    if (wmsi.length > 0 && bl.length > 0) {
        $.fn.adminapp.bindEventOnLayerGroup(wmsi, bl);
        // init state
        $.fn.adminapp.toogleBaseLayer(wmsi, bl);
    }

});
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
process.title = 'FireMon';
require('events').EventEmitter.prototype._maxListeners = 100;

let log = require("../net2/logger.js")(__filename, "info");

var bone = require("../lib/Bone.js");
var config = JSON.parse(require('fs').readFileSync('../net2/config.json', 'utf8'));
log.info("================================================================================");
log.info("Monitor Starting:",config.version);
log.info("================================================================================");

// api/main/monitor all depends on sysManager configuration
let SysManager = require('../net2/SysManager.js');
let sysManager = new SysManager('info');

if(!bone.isAppConnected()) {
  log.info("Waiting for pairing from first app...");
}

// load feature toggle on/off from redis to memory
require('../net2/config.js').syncDynamicFeaturesConfigs()

run0();

function run0() {
  if (bone.cloudready()==true &&
      bone.isAppConnected() &&
   // this is to ensure sysManager is already initliazed when called in API code
      sysManager.isConfigInitialized()) {
    run();
  } else {
    setTimeout(()=>{
      sysManager.update(null);
      run0();
    },1000);
  }
}

process.on('uncaughtException',(err)=>{
    log.info("################### CRASH #############");
    log.info("+-+-+-",err.message,err.stack);
    if (err && err.message && err.message.includes("Redis connection")) {
        return;
    }
    bone.log("error",{version:config.version,type:'FIREWALLA.MON.exception',msg:err.message,stack:err.stack},null);
    setTimeout(()=>{
        require('child_process').execSync("touch /home/pi/.firewalla/managed_reboot")
        process.exit(1);
    },1000*2);
});

process.on('unhandledRejection', (reason, p)=>{
  let msg = "Possibly Unhandled Rejection at: Promise " + p + " reason: "+ reason;
  log.warn('###### Unhandled Rejection',msg,reason.stack,{});
  bone.log("error",{version:config.version,type:'FIREWALLA.MON.unhandledRejection',msg:msg,stack:reason.stack},null);
  // setTimeout(()=>{
  //   require('child_process').execSync("touch /home/pi/.firewalla/managed_reboot")
  //   process.exit(1);
  // },1000*2);
});

let heapSensor = null;

function run() {

  const firewallaConfig = require('../net2/config.js').getConfig();
  sysManager.setConfig(firewallaConfig) // update sys config when start

  sysManager = null; // not needed any more after run()

  // listen on request to dump heap for this process, used for memory optmiziation
  // let HeapSensor = require('../sensor/HeapSensor');
  // heapSensor = new HeapSensor();
  // heapSensor.run();

  const tick = 60 * 15; // waking up every 5 min
  const monitorWindow = 60 * 60 * 4; // eight hours window

  const FlowMonitor = require('./FlowMonitor.js');
  const flowMonitor = new FlowMonitor(tick, monitorWindow, 'info');

  log.info("================================================================================");
  log.info("Monitor Running ");
  log.info("================================================================================");

flowMonitor.run();
setInterval(() => {
    flowMonitor.run("dlp",tick);
    try {
      if (global.gc) {
       global.gc();
      }
    } catch(e) {
    }
}, tick * 1000);

setInterval(()=>{
    flowMonitor.run("detect",60);
    try {
      if (global.gc) {
       global.gc();
      }
    } catch(e) {
    }
}, 60*1000);

}
<commit_msg>firemon support signal: USR1 -> DLP, USR2 -> Detect<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';
process.title = 'FireMon';
require('events').EventEmitter.prototype._maxListeners = 100;

let log = require("../net2/logger.js")(__filename, "info");

var bone = require("../lib/Bone.js");
var config = JSON.parse(require('fs').readFileSync('../net2/config.json', 'utf8'));
log.info("================================================================================");
log.info("Monitor Starting:",config.version);
log.info("================================================================================");

// api/main/monitor all depends on sysManager configuration
let SysManager = require('../net2/SysManager.js');
let sysManager = new SysManager('info');

if(!bone.isAppConnected()) {
  log.info("Waiting for pairing from first app...");
}

// load feature toggle on/off from redis to memory
require('../net2/config.js').syncDynamicFeaturesConfigs()

run0();

function run0() {
  if (bone.cloudready()==true &&
      bone.isAppConnected() &&
   // this is to ensure sysManager is already initliazed when called in API code
      sysManager.isConfigInitialized()) {
    run();
  } else {
    setTimeout(()=>{
      sysManager.update(null);
      run0();
    },1000);
  }
}

process.on('uncaughtException',(err)=>{
    log.info("################### CRASH #############");
    log.info("+-+-+-",err.message,err.stack);
    if (err && err.message && err.message.includes("Redis connection")) {
        return;
    }
    bone.log("error",{version:config.version,type:'FIREWALLA.MON.exception',msg:err.message,stack:err.stack},null);
    setTimeout(()=>{
        require('child_process').execSync("touch /home/pi/.firewalla/managed_reboot")
        process.exit(1);
    },1000*2);
});

process.on('unhandledRejection', (reason, p)=>{
  let msg = "Possibly Unhandled Rejection at: Promise " + p + " reason: "+ reason;
  log.warn('###### Unhandled Rejection',msg,reason.stack,{});
  bone.log("error",{version:config.version,type:'FIREWALLA.MON.unhandledRejection',msg:msg,stack:reason.stack},null);
  // setTimeout(()=>{
  //   require('child_process').execSync("touch /home/pi/.firewalla/managed_reboot")
  //   process.exit(1);
  // },1000*2);
});

let heapSensor = null;

function gc() {
  try {
    if (global.gc) {
      global.gc();
    }
  } catch (err) {
  }
}

function run() {
  const firewallaConfig = require('../net2/config.js').getConfig();
  sysManager.setConfig(firewallaConfig) // update sys config when start

  sysManager = null; // not needed any more after run()

  // listen on request to dump heap for this process, used for memory optmiziation
  // let HeapSensor = require('../sensor/HeapSensor');
  // heapSensor = new HeapSensor();
  // heapSensor.run();

  const tick = 60 * 15; // waking up every 5 min
  const monitorWindow = 60 * 60 * 4; // eight hours window

  const FlowMonitor = require('./FlowMonitor.js');
  const flowMonitor = new FlowMonitor(tick, monitorWindow, 'info');

  log.info("================================================================================");
  log.info("Monitor Running ");
  log.info("================================================================================");

  flowMonitor.run();

  let running = {
    dlp: false,
    detect: false
  };

  process.on('SIGUSR1', () => {
    log.info('Received SIGUSR1. Trigger DLP check.');
    if (running.dlp) {
      log.warn("DLP check is already running, ignore");
      return;
    }

    running.dlp = true;
    flowMonitor.run("dlp", tick);
    running.dlp = false;

    gc();
  });

  process.on('SIGUSR2', () => {
    log.info('Received SIGUSR2. Trigger Detect check.');
    if (running.detect) {
      log.warn("Detect check is already running, ignore");
      return;
    }
    running.detect = true;
    flowMonitor.run("detect", 60);
    running.detect = false;

    gc();
  });

  setInterval(() => {
    flowMonitor.run("dlp", tick);
    gc();
  }, tick * 1000);

  setInterval(() => {
    flowMonitor.run("detect", 60);
    gc();
  }, 60 * 1000);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2010 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Base module for the monitor component.
 */
wa.components.dashboard.Dashboard = (function($) {

    var me = {};

    me.basePage = $("

");
    me.ui = {};

    me.uiLoaded  = false;
    me.server = null;
    me.kernelInfo = null;

    me.visible = false;

    me.valueTrackers = [];
    me.charts = [];
    me.visibleChart = null;

    //
    // PUBLIC
    //

    me.api = {

            getPage :  function() {
                return me.basePage;
            },

            pageChanged : function(ev) {
                if(ev.data === "dashboard") {
            		me.visible = true;

                    if( me.uiLoaded === false ) {
                    	me.uiLoaded = true;
                        me.basePage.setTemplateURL("templates/components/monitor/index.tp");

                        me.server = wa.Servers.getCurrentServer();

                        if(me.server) {
                            me.reload();
                        }
                    } else {
                    	me.runMonitors();
                    }

                } else {
                    me.visible = false;
                    me.haltMonitors();
                }
            },

            serverChanged : function(ev) {

                if( me.server != wa.Servers.getCurrentServer() ) {
                    me.server = wa.Servers.getCurrentServer();
                    // If the monitor page is currently visible
                    if( me.visible === true ) {
                    	me.reload();
                    }
                }
            },

            init : function() { }

    };

    //
    // PRIVATE
    //

    /**
     * Resets the state of the dashboard, loads appropriate server
     * information, and dashboard widgets, and re-renders.
     */
    me.reload = function() {

        me.destroyMonitors();
        var server = wa.Servers.getCurrentServer();

        if( server ) {

        	server.manage.jmx.getBean("neo4j", "Kernel", function(kernelBean){
        		me.kernelInfo = kernelBean;
    	    	me.render();
            	me.loadMonitors(server);

            	$("#mor_monitor_lifecycle").empty();
            	//Disable for now
            	//$("#mor_monitor_lifecycle").append( wa.widgets.LifecycleWidget(server).render() );
        	});
        } else {
        	me.render();
        }

    };

    me.render = function() {
    	me.basePage.processTemplate({
            server : me.server,
            kernelInfo : me.kernelInfo
        });
    };

    me.destroyMonitors= function() {
    	me.haltMonitors();

    	me.valueTrackers = [];
    	me.charts = [];
    };

    me.haltMonitors = function() {
    	for( var i = 0, l = me.charts.length; i < l ; i++ ) {
			me.charts[i].stopDrawing();
    	}

    	for( var i = 0, l = me.valueTrackers.length; i < l ; i++ ) {
			me.valueTrackers[i].stopPolling();
    	}
    };

    me.runMonitors = function() {
    	if( me.visibleChart !== null ) {
    		me.visibleChart.startDrawing();
    	}

    	for( var i = 0, l = me.valueTrackers.length; i < l ; i++ ) {
			me.valueTrackers[i].startPolling();
    	}
    };

    me.loadMonitors = function(server) {
    	var box = $("#mor_monitor_valuetrackers"),
    	    primitivesChartWrap = $("#mor_monitor_primitives_chart"),
    	    memoryChartWrap = $("#mor_monitor_memory_chart"),
    	    primitiveTracker = wa.components.dashboard.PrimitiveCountWidget(server),
    	    diskTracker      = wa.components.dashboard.DiskUsageWidget(server),
    	    cacheTracker     = wa.components.dashboard.CacheWidget(server);

    	var primitivesChart = wa.components.dashboard.MonitorChart(server, {
    		label : 'Primitive entitites',
    		data : {
    		    node_count : {
				    label : 'Nodes'
				},
				relationship_count : {
				    label : 'Relationships'
			    },
			    property_count : {
				    label : 'Properties'
			    }
    		}
    	});

    	var memoryChart = wa.components.dashboard.MonitorChart(server, {
    		label : 'Heap memory usage',
    		data : {
    			memory_usage_percent : {
				    label : 'Heap memory usage'
				}
    		},
    		yaxis : {
    			min : 0,
    			max : 100
    		},
    		series : {
    			lines: { show: true, fill: true, fillColor: "#4f848f" }
    		},
    		tooltipValueFormatter : function(v) {
    			return Math.floor(v) + "%";
    		}
    	});

    	me.valueTrackers.push(primitiveTracker);
    	me.valueTrackers.push(diskTracker);
    	me.valueTrackers.push(cacheTracker);

    	me.charts.push(primitivesChart);
    	me.charts.push(memoryChart);

    	me.primitivesChart = primitivesChart;
    	me.memoryChart = memoryChart;

    	box.append(primitiveTracker.render());
    	box.append(diskTracker.render());
    	box.append(cacheTracker.render());

    	primitivesChartWrap.append(primitivesChart.render());
    	memoryChartWrap.append(memoryChart.render());

    	primitivesChart.startDrawing();
    };

    //
    // CONSTRUCT
    //

    $("#mor_monitor_memory_chart_tab").live("click", function(ev) {
    	ev.preventDefault();

    	$(ev.target).parent().addClass("current");
    	$("#mor_monitor_primitives_chart_tab").parent().removeClass("current");

    	me.primitivesChart.stopDrawing();
    	$("#mor_monitor_primitives_chart").hide();
    	$("#mor_monitor_memory_chart").show();
    	me.memoryChart.startDrawing();
    	me.visibleChart = me.memoryChart;
    });

    $("#mor_monitor_primitives_chart_tab").live("click", function(ev) {
    	ev.preventDefault();

    	$(ev.target).parent().addClass("current");
    	$("#mor_monitor_memory_chart_tab").parent().removeClass("current");

    	me.memoryChart.stopDrawing();
    	$("#mor_monitor_memory_chart").hide();
    	$("#mor_monitor_primitives_chart").show();
    	me.primitivesChart.startDrawing();
    	me.visibleChart = me.primitivesChart;
    });

    return me.api;

})(jQuery);

//
// REGISTER STUFF
//

wa.ui.Pages.add("dashboard",wa.components.dashboard.Dashboard);
wa.ui.MainMenu.add({ label : "Dashboard", pageKey:"dashboard", index:0, requiredServices:['monitor'], perspectives:['server']});

wa.bind("init", wa.components.dashboard.Dashboard.init);
wa.bind("ui.page.changed", wa.components.dashboard.Dashboard.pageChanged);
wa.bind("servers.current.changed",  wa.components.dashboard.Dashboard.serverChanged);<commit_msg>Fixed the chart not being updated when leaving and re-entering the dashboard tab<commit_after>/*
 * Copyright (c) 2002-2010 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Base module for the monitor component.
 */
wa.components.dashboard.Dashboard = (function($) {

    var me = {};

    me.basePage = $("

");
    me.ui = {};

    me.uiLoaded  = false;
    me.server = null;
    me.kernelInfo = null;

    me.visible = false;

    me.valueTrackers = [];
    me.charts = [];
    me.visibleChart = null;

    //
    // PUBLIC
    //

    me.api = {

            getPage :  function() {
                return me.basePage;
            },

            pageChanged : function(ev) {
                if(ev.data === "dashboard") {
            		me.visible = true;

                    if( me.uiLoaded === false ) {
                    	me.uiLoaded = true;
                        me.basePage.setTemplateURL("templates/components/monitor/index.tp");

                        me.server = wa.Servers.getCurrentServer();

                        if(me.server) {
                            me.reload();
                        }
                    } else {
                    	me.runMonitors();
                    }

                } else {
                    me.visible = false;
                    me.haltMonitors();
                }
            },

            serverChanged : function(ev) {

                if( me.server != wa.Servers.getCurrentServer() ) {
                    me.server = wa.Servers.getCurrentServer();
                    // If the monitor page is currently visible
                    if( me.visible === true ) {
                    	me.reload();
                    }
                }
            },

            init : function() { }

    };

    //
    // PRIVATE
    //

    /**
     * Resets the state of the dashboard, loads appropriate server
     * information, and dashboard widgets, and re-renders.
     */
    me.reload = function() {

        me.destroyMonitors();
        var server = wa.Servers.getCurrentServer();

        if( server ) {

        	server.manage.jmx.getBean("neo4j", "Kernel", function(kernelBean){
        		me.kernelInfo = kernelBean;
    	    	me.render();
            	me.loadMonitors(server);

            	$("#mor_monitor_lifecycle").empty();
            	//Disable for now
            	//$("#mor_monitor_lifecycle").append( wa.widgets.LifecycleWidget(server).render() );
        	});
        } else {
        	me.render();
        }

    };

    me.render = function() {
    	me.basePage.processTemplate({
            server : me.server,
            kernelInfo : me.kernelInfo
        });
    };

    me.destroyMonitors= function() {
    	me.haltMonitors();

    	me.valueTrackers = [];
    	me.charts = [];
    };

    me.haltMonitors = function() {
    	for( var i = 0, l = me.charts.length; i < l ; i++ ) {
			me.charts[i].stopDrawing();
    	}

    	for( var i = 0, l = me.valueTrackers.length; i < l ; i++ ) {
			me.valueTrackers[i].stopPolling();
    	}
    };

    me.runMonitors = function() {
    	if( me.visibleChart !== null ) {
    		me.visibleChart.startDrawing();
    	}

    	for( var i = 0, l = me.valueTrackers.length; i < l ; i++ ) {
			me.valueTrackers[i].startPolling();
    	}
    };

    me.loadMonitors = function(server) {
    	var box = $("#mor_monitor_valuetrackers"),
    	    primitivesChartWrap = $("#mor_monitor_primitives_chart"),
    	    memoryChartWrap = $("#mor_monitor_memory_chart"),
    	    primitiveTracker = wa.components.dashboard.PrimitiveCountWidget(server),
    	    diskTracker      = wa.components.dashboard.DiskUsageWidget(server),
    	    cacheTracker     = wa.components.dashboard.CacheWidget(server);

    	var primitivesChart = wa.components.dashboard.MonitorChart(server, {
    		label : 'Primitive entitites',
    		data : {
    		    node_count : {
				    label : 'Nodes'
				},
				relationship_count : {
				    label : 'Relationships'
			    },
			    property_count : {
				    label : 'Properties'
			    }
    		}
    	});

    	var memoryChart = wa.components.dashboard.MonitorChart(server, {
    		label : 'Heap memory usage',
    		data : {
    			memory_usage_percent : {
				    label : 'Heap memory usage'
				}
    		},
    		yaxis : {
    			min : 0,
    			max : 100
    		},
    		series : {
    			lines: { show: true, fill: true, fillColor: "#4f848f" }
    		},
    		tooltipValueFormatter : function(v) {
    			return Math.floor(v) + "%";
    		}
    	});

    	me.valueTrackers.push(primitiveTracker);
    	me.valueTrackers.push(diskTracker);
    	me.valueTrackers.push(cacheTracker);

    	me.charts.push(primitivesChart);
    	me.charts.push(memoryChart);

    	me.primitivesChart = primitivesChart;
    	me.visibleChart = me.primitivesChart;
    	me.memoryChart = memoryChart;

    	box.append(primitiveTracker.render());
    	box.append(diskTracker.render());
    	box.append(cacheTracker.render());

    	primitivesChartWrap.append(primitivesChart.render());
    	memoryChartWrap.append(memoryChart.render());

    	primitivesChart.startDrawing();
    };

    //
    // CONSTRUCT
    //

    $("#mor_monitor_memory_chart_tab").live("click", function(ev) {
    	ev.preventDefault();

    	$(ev.target).parent().addClass("current");
    	$("#mor_monitor_primitives_chart_tab").parent().removeClass("current");

    	me.primitivesChart.stopDrawing();
    	$("#mor_monitor_primitives_chart").hide();
    	$("#mor_monitor_memory_chart").show();
    	me.memoryChart.startDrawing();
    	me.visibleChart = me.memoryChart;
    });

    $("#mor_monitor_primitives_chart_tab").live("click", function(ev) {
    	ev.preventDefault();

    	$(ev.target).parent().addClass("current");
    	$("#mor_monitor_memory_chart_tab").parent().removeClass("current");

    	me.memoryChart.stopDrawing();
    	$("#mor_monitor_memory_chart").hide();
    	$("#mor_monitor_primitives_chart").show();
    	me.primitivesChart.startDrawing();
    	me.visibleChart = me.primitivesChart;
    });

    return me.api;

})(jQuery);

//
// REGISTER STUFF
//

wa.ui.Pages.add("dashboard",wa.components.dashboard.Dashboard);
wa.ui.MainMenu.add({ label : "Dashboard", pageKey:"dashboard", index:0, requiredServices:['monitor'], perspectives:['server']});

wa.bind("init", wa.components.dashboard.Dashboard.init);
wa.bind("ui.page.changed", wa.components.dashboard.Dashboard.pageChanged);
wa.bind("servers.current.changed",  wa.components.dashboard.Dashboard.serverChanged);<|endoftext|>


<commit_before>function(doc) {
    if (doc.is_daily_saved_export || doc.auto_rebuild_enabled) {
        emit([doc.last_accessed], null);
    }
}
<commit_msg>get exports that have auto rebuild enabled<commit_after>function(doc) {
    if (doc.is_daily_saved_export && doc.auto_rebuild_enabled) {
        emit([doc.last_accessed], null);
    }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { withScroll, withApollo, withRouter } from 'olymp';
import {
  Navbar,
  Layout,
  Container,
  createComponent,
  WithColorProvider,
} from 'olymp-fela';
import { prefetchPage } from 'olymp-pages';
import Logo from './logo';

export const App = createComponent(
  ({ theme }) => ({
    backgroundColor: '#FFFFFF',
    fontFamily: 'Oxygen, sans-serif',
    fontSize: '105%',
    lineHeight: 1.75,
    '& h1, h2, h3, h4, h5, h6': {
      fontFamily: 'Raleway, sans-serif',
      fontWeight: 200,
      lineHeight: 1.5,
    },
    ifSmallDown: {
      '& h1': {
        fontSize: theme.fontSizeH1,
      },
      '& h2': {
        fontSize: theme.fontSizeH2,
      },
      '& h3': {
        fontSize: theme.fontSizeH3,
      },
      '& h4': {
        fontSize: theme.fontSizeH4,
      },
      '& h5': {
        fontSize: theme.fontSizeH5,
      },
      '& h6': {
        fontSize: theme.fontSizeH6,
      },
    },
  }),
  p => <WithColorProvider><Layout {...p} /></WithColorProvider>,
  p => Object.keys(p)
);

export const Header = withScroll(
  createComponent(
    ({ theme, scrollTop }) => ({
      paddingY: theme.space3,
      ifSmallDown: {
        paddingY: theme.space0,
      },
      boxShadow: scrollTop && theme.boxShadow,
      transition: 'box-shadow 0.3s ease-in-out',
    }),
    ({ children, className }) =>
      (<Layout.Header className={className}>
        <Container>
          {children}
        </Container>
      </Layout.Header>),
    p => Object.keys(p)
  )
);

@withApollo
@withRouter
export default class GzLayout extends Component {
  static defaultProps = {
    pages: [],
  };
  prefetch = ({ id }) => {
    prefetchPage(this.props.client, id);
  };
  render() {
    const {
      pages,
      color,
      title,
      text,
      location,
      links,
      children,
      router,
      query,
      pathname,
      ...rest
    } = this.props;
    const nav = (pages.map(x => x.children)[0] || [])
      .filter(x => x.slug !== '/');
    const footer = [
      ...(pages.map(x => x.children)[1] || []),
      { name: 'Einloggen', pathname: `${location.pathname}?login` },
    ];
    const open = query.nav === null;

    return (
      <App affix>
        <Header>
          <Navbar
            pages={nav}
            logo={<Logo color={color} title={title} text={text} />}
            full
            right
            mega
            onItemMouseEnter={this.prefetch}
            toggleMenu={() =>
              router.push({
                pathname,
                query: { ...query, nav: !open ? null : undefined },
              })}
            isOpen={open}
          />
        </Header>
        <Layout.Body>
          <Layout>
            <Layout.Body>
              {children}
            </Layout.Body>

            <Layout.Footer container>
              <Navbar full>
                <Navbar.Nav
                  pages={[
                    {
                      name: `GesundheitsZentrum Kelkheim. Copyright ${new Date().getFullYear()}`,
                    },
                  ]}
                />
                <Navbar.Nav pages={footer} right />
              </Navbar>
            </Layout.Footer>
          </Layout>
        </Layout.Body>
      </App>
    );
  }
}
<commit_msg>fix safari layout problem<commit_after>import React, { Component } from 'react';
import { withScroll, withApollo, withRouter } from 'olymp';
import {
  Navbar,
  Layout,
  Container,
  createComponent,
  WithColorProvider,
} from 'olymp-fela';
import { prefetchPage } from 'olymp-pages';
import Logo from './logo';

export const App = createComponent(
  ({ theme }) => ({
    backgroundColor: '#FFFFFF',
    fontFamily: 'Oxygen, sans-serif',
    fontSize: '105%',
    lineHeight: 1.75,
    '& h1, h2, h3, h4, h5, h6': {
      fontFamily: 'Raleway, sans-serif',
      fontWeight: 200,
      lineHeight: 1.5,
    },
    ifSmallDown: {
      '& h1': {
        fontSize: theme.fontSizeH1,
      },
      '& h2': {
        fontSize: theme.fontSizeH2,
      },
      '& h3': {
        fontSize: theme.fontSizeH3,
      },
      '& h4': {
        fontSize: theme.fontSizeH4,
      },
      '& h5': {
        fontSize: theme.fontSizeH5,
      },
      '& h6': {
        fontSize: theme.fontSizeH6,
      },
    },
  }),
  p =>
    (<WithColorProvider>
      <Layout fullHeight {...p} />
    </WithColorProvider>),
  p => Object.keys(p)
);

export const Header = withScroll(
  createComponent(
    ({ theme, scrollTop }) => ({
      paddingY: theme.space3,
      ifSmallDown: {
        paddingY: theme.space0,
      },
      boxShadow: scrollTop && theme.boxShadow,
      transition: 'box-shadow 0.3s ease-in-out',
    }),
    ({ children, className }) =>
      (<Layout.Header className={className}>
        <Container>
          {children}
        </Container>
      </Layout.Header>),
    p => Object.keys(p)
  )
);

@withApollo
@withRouter
export default class GzLayout extends Component {
  static defaultProps = {
    pages: [],
  };
  prefetch = ({ id }) => {
    prefetchPage(this.props.client, id);
  };
  render() {
    const {
      pages,
      color,
      title,
      text,
      location,
      links,
      children,
      router,
      query,
      pathname,
      ...rest
    } = this.props;
    const nav = (pages.map(x => x.children)[0] || [])
      .filter(x => x.slug !== '/');
    const footer = [
      ...(pages.map(x => x.children)[1] || []),
      { name: 'Einloggen', pathname: `${location.pathname}?login` },
    ];
    const open = query.nav === null;

    return (
      <App affix>
        <Header>
          <Navbar
            pages={nav}
            logo={<Logo color={color} title={title} text={text} />}
            full
            right
            mega
            onItemMouseEnter={this.prefetch}
            toggleMenu={() =>
              router.push({
                pathname,
                query: { ...query, nav: !open ? null : undefined },
              })}
            isOpen={open}
          />
        </Header>
        <Layout.Body>
          <Layout>
            <Layout.Body>
              {children}
            </Layout.Body>

            <Layout.Footer container>
              <Navbar full>
                <Navbar.Nav
                  pages={[
                    {
                      name: `GesundheitsZentrum Kelkheim. Copyright ${new Date().getFullYear()}`,
                    },
                  ]}
                />
                <Navbar.Nav pages={footer} right />
              </Navbar>
            </Layout.Footer>
          </Layout>
        </Layout.Body>
      </App>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

// document
// ====================
if (!('body' in document))
    document.body = document.querySelector('body');

if (!('find' in document))
    document.find = document.querySelector;

if (!('findAll' in document))
    document.findAll = document.querySelectorAll;

// Element
// ====================
if (!('create' in Element))
    Element.create = document.createElement.bind(document);

if (!('find' in Element.prototype))
    Element.prototype.find = Element.prototype.querySelector;

if (!('findAll' in Element.prototype))
    Element.prototype.findAll = Element.prototype.querySelectorAll;

if (!('on' in Element.prototype))
    Element.prototype.on = Element.prototype.addEventListener;

if (!('remove' in Element.prototype))
    Element.prototype.remove = function() {
        this.parentNode.removeChild(this);
    }

// Array
// ====================
if (!('filter' in Array.prototype))
    Array.prototype.filter = function(fn, bound) {
        var filtered = [];
        for (var i = 0; i < this.length; i++) {
            if (fn.call(bound, this[i], i, this)) {
                filtered.push(this[i]);
            }
        }
        return filtered;
    }

if (!('forEach' in Array.prototype))
    Array.prototype.forEach = function(fn, bound) {
        for (var i = 0; i < this.length; i++) {
            fn.call(bound, this[i], i, this)
        }
    };

if (!('of' in Array))
    Array.of = function(list) {
        return Array.prototype.slice.call(list);
    };

if (!('on' in Array.prototype))
    Array.prototype.on = function(event, fn) {
        this.forEach(function(element) {
            if (!('on' in element)) throw new TypeError('Expected type of Element; ' + typeof element + ' has no "on" method.');
            element.on(event, fn);
        });
    }

if (!('remove' in Array.prototype))
    Array.prototype.remove = function() {
        this.forEach(function(element) {
            if (!('remove' in element)) throw new TypeError('Expected type of Element; ' + typeof element + ' has no "remove" method.');
            element.remove();
        });
    };

// NodeList
// ====================
if (!('filter' in NodeList.prototype))
    NodeList.prototype.filter = function(fn) {
        return Array.of(this).filter(fn);
    };

if (!('forEach' in NodeList.prototype))
    NodeList.prototype.forEach = function(fn) {
        Array.of(this).forEach(fn);
    };

if (!('on' in NodeList.prototype))
    NodeList.prototype.on = function(event, fn) {
        Array.of(this).on(event, fn);
    };

if (!('remove' in NodeList.prototype))
    NodeList.prototype.remove = function() {
        Array.of(this).remove();
    };

if (!('sort' in NodeList.prototype))
    NodeList.prototype.sort = function(fn) {
        return Array.of(this).sort(fn);
    }

// HTMLCollection
// ====================
if (!('filter' in HTMLCollection.prototype))
    HTMLCollection.prototype.filter = NodeList.prototype.filter;

if (!('forEach' in HTMLCollection.prototype))
    HTMLCollection.prototype.forEach = NodeList.prototype.forEach;

if (!('on' in HTMLCollection.prototype))
    HTMLCollection.prototype.on = NodeList.prototype.on;

if (!('remove' in HTMLCollection.prototype))
    HTMLCollection.prototype.remove = NodeList.prototype.remove;

if (!('sort' in HTMLCollection.prototype))
    HTMLCollection.prototype.sort = NodeList.prototype.sort;
<commit_msg>added attachEvent support for ie8<commit_after>'use strict';

// document
// ====================
if (!('body' in document))
    document.body = document.querySelector('body');

if (!('find' in document))
    document.find = document.querySelector;

if (!('findAll' in document))
    document.findAll = document.querySelectorAll;

// Element
// ====================
if (!('create' in Element))
    Element.create = document.createElement.bind(document);

if (!('find' in Element.prototype))
    Element.prototype.find = Element.prototype.querySelector;

if (!('findAll' in Element.prototype))
    Element.prototype.findAll = Element.prototype.querySelectorAll;

if (!('on' in Element.prototype))
    Element.prototype.on = function(event, fn) {
        if ('addEventListener' in Element.prototype)
            this.addEventListener(event, fn);
        if ('attachEvent' in Element.prototype)
            this.attachEvent('on' + event, fn);
    }

if (!('remove' in Element.prototype))
    Element.prototype.remove = function() {
        this.parentNode.removeChild(this);
    }

// Array
// ====================
if (!('filter' in Array.prototype))
    Array.prototype.filter = function(fn, bound) {
        var filtered = [];
        for (var i = 0; i < this.length; i++) {
            if (fn.call(bound, this[i], i, this)) {
                filtered.push(this[i]);
            }
        }
        return filtered;
    }

if (!('forEach' in Array.prototype))
    Array.prototype.forEach = function(fn, bound) {
        for (var i = 0; i < this.length; i++) {
            fn.call(bound, this[i], i, this)
        }
    };

if (!('of' in Array))
    Array.of = function(list) {
        return Array.prototype.slice.call(list);
    };

if (!('on' in Array.prototype))
    Array.prototype.on = function(event, fn) {
        this.forEach(function(element) {
            if (!('on' in element)) throw new TypeError('Expected type of Element; ' + typeof element + ' has no "on" method.');
            element.on(event, fn);
        });
    }

if (!('remove' in Array.prototype))
    Array.prototype.remove = function() {
        this.forEach(function(element) {
            if (!('remove' in element)) throw new TypeError('Expected type of Element; ' + typeof element + ' has no "remove" method.');
            element.remove();
        });
    };

// NodeList
// ====================
if (!('filter' in NodeList.prototype))
    NodeList.prototype.filter = function(fn) {
        return Array.of(this).filter(fn);
    };

if (!('forEach' in NodeList.prototype))
    NodeList.prototype.forEach = function(fn) {
        Array.of(this).forEach(fn);
    };

if (!('on' in NodeList.prototype))
    NodeList.prototype.on = function(event, fn) {
        Array.of(this).on(event, fn);
    };

if (!('remove' in NodeList.prototype))
    NodeList.prototype.remove = function() {
        Array.of(this).remove();
    };

if (!('sort' in NodeList.prototype))
    NodeList.prototype.sort = function(fn) {
        return Array.of(this).sort(fn);
    }

// HTMLCollection
// ====================
if (!('filter' in HTMLCollection.prototype))
    HTMLCollection.prototype.filter = NodeList.prototype.filter;

if (!('forEach' in HTMLCollection.prototype))
    HTMLCollection.prototype.forEach = NodeList.prototype.forEach;

if (!('on' in HTMLCollection.prototype))
    HTMLCollection.prototype.on = NodeList.prototype.on;

if (!('remove' in HTMLCollection.prototype))
    HTMLCollection.prototype.remove = NodeList.prototype.remove;

if (!('sort' in HTMLCollection.prototype))
    HTMLCollection.prototype.sort = NodeList.prototype.sort;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    City = mongoose.model('City');

/**
 * Find city by id
 */
exports.city = function(req, res, next, id) {
    City.load(id, function(err, city) {
        if (err) return next(err);
        if (!city) return next(new Error('Failed to load city ' + id));
        req.city = city;
        next();
    });
};

/**
 * Show a city
 */
exports.show = function(req, res) {
    res.jsonp(req.city);
};

/**
 * List of Cities
 */
exports.all = function(req, res) {
    City.find().sort('-created').exec(function(err, cities) {
        if (err) {
            return res.jsonp(500, {
                error: 'Cannot list the cities'
            });
        }
        res.jsonp(cities);
    });
};
<commit_msg>Order the records by creation date<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    City = mongoose.model('City'),
    _ = require('lodash');

/**
 * Find city by id
 */
exports.city = function(req, res, next, id) {
    City.load(id, function(err, city) {
        if (err) return next(err);
        if (!city) return next(new Error('Failed to load city ' + id));
        city.records = _.sortBy(city.records, 'created');
        req.city = city;
        next();
    });
};

/**
 * Show a city
 */
exports.show = function(req, res) {
    res.jsonp(req.city);
};

/**
 * List of Cities
 */
exports.all = function(req, res) {
    City.find().exec(function(err, cities) {
        if (err) {
            return res.jsonp(500, {
                error: 'Cannot list the cities'
            });
        }

        _.each(cities, function(city){
            city.records = _.sortBy(city.records, 'created');
        });

        res.jsonp(cities);
    });
};
<|endoftext|>


<commit_before>/* Author:
    RedDelicious
    Company: Kaleidos Open Source
*/

/* gettext dummy wrapper if not exists */

if (window.gettext === undefined) {
    window.gettext = function(text) {
        return text;
    };
}

if (window.interpolate === undefined) {
    window.interpolate = function(fmt, obj, named) {
        if (named) {
            return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
        } else {
            return fmt.replace(/%s/g, function(match){return String(obj.shift())});
        }
    };
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            !('/^(\/\/|http:|https:).*\/'.test(url)); // or any other URL that isn't scheme relative or absolute i.e relative.
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

/* Global macadjan  module namespace. */

var Macadjan = {}

Macadjan.Category = Backbone.Model.extend({});
Macadjan.SubCategory = Backbone.Model.extend({});

Macadjan.CategoryCollection = Backbone.Collection.extend({
    model: Macadjan.Category
});

Macadjan.SubCategoryCollection = Backbone.Collection.extend({
    model: Macadjan.SubCategory
});

Macadjan.categories = new Macadjan.CategoryCollection();
Macadjan.subCategories = new Macadjan.SubCategoryCollection();

Macadjan.Map = Backbone.View.extend({
    el: $("#map-block"),

    events: {},

    initializeControls: function() {
        this.navigationControl = new OpenLayers.Control.Navigation();
        this.layerSwitcherControl = new OpenLayers.Control.LayerSwitcher();
        this.panZoomControl = new OpenLayers.Control.PanZoomBar();
    },

    parseBounds: function() {
        var b = {
            "left": this.$el.data('map-bounds-left') || -20037508.34,
            "right": this.$el.data('map-bounds-right') || 20037508.34,
            "top": this.$el.data('map-bounds-top') || 20037508.34,
            "bottom": this.$el.data('map-bounds-bottom') || -20037508.34
        };

        return new OpenLayers.Bounds(b['left'], b['bottom'], b['right'], b['top']);
    },

    parseZoomLevels: function() {
        return 18;
    },

    parseUnits: function() {
        return "meters";
    },

    parseMaxResolution: function() {
        return 156543;
    },

    initialize: function() {
        _.bindAll(this);

        this.initializeControls();
        this.mapInitial = {
            projection: new OpenLayers.Projection('EPSG:4326'),
            controls: [
                this.navigationControl,
                this.layerSwitcherControl,
                this.panZoomControl
            ],
            maxExtent: this.parseBounds(),
            numZoomLevels: this.parseZoomLevels(),
            units:this.parseUnits(),
            maxResolution: this.parseMaxResolution()
        };

        this.map = new OpenLayers.Map(this.$el.attr('id'), this.mapInitial);

        this.osm = this.createOsmLayer();
        this.map.addLayer(this.osm);

        // Center map to initial coords
        this.centerMap();

        // Create points layer
        this.pointsLayer = this.createPointsLayer();
        this.map.addLayer(this.pointsLayer);

        // Create select control
        this.selectControl = this.createSelectControl(this.pointsLayer);
        this.map.addControl(this.selectControl);

        this.pointsLayer.events.on({
            "featureselected": this.onFeatureSelect,
            "featureunselected": this.onFeatureUnselect,
        });
    },

    onFeatureSelect: function(evt) {
        var feature = evt.feature;
        var content;

        if (!feature.cluster) {
            content = feature.attributes.title + '
' + feature.attributes.description;
        } else {
            content = '';
            var length = Math.min(feature.cluster.length, 50);
            for (var c = 0; c < length; c++) {
                content += feature.cluster[c].attributes.title + '
';
            }
            if (length < feature.cluster.length) {
                content += '(...)';
            }
        }
        var self = this;

        var popup = new OpenLayers.Popup.FramedCloud('featurePopup',
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(300, 100),
            content, null, true,
            function(evt) {
                var feature = this.feature;
                if (feature.layer) {
                    self.selectControl.unselect(feature);
                } else {
                    this.destroy();
                }
            }
        );

        popup.maxSize = new OpenLayers.Size(500, 300);
        feature.popup = popup;
        popup.feature = feature;
        map.addPopup(popup, true);
    },

    onFeatureUnselect: function(evt) {
        var feature = evt.feature;
        if (feature.popup) {
            popup.feature = null;
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
        }
    },

    centerMap: function() {
        var initialLon = this.$el.data('initial-lon');
        var initialLat = this.$el.data('initial-lat');
        var initialZoom = this.$el.data('initial-zoom');

        this.map.setCenter(new OpenLayers.LonLat(initialLon, initialLat).transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
        ), initialZoom);
    },

    createOsmLayer: function() {
        return new OpenLayers.Layer.OSM({
            transitionEffect: 'resize'
        })
    },

    createPointsLayer: function() {
        this.bboxStrategy = new OpenLayers.Strategy.BBOX();
        this.clusterStrategy = new OpenLayers.Strategy.Cluster({
            distance: 50,
            threshold: 5
        });
        this.refreshStrategy = new OpenLayers.Strategy.Refresh({
            force: true,
            active: true,
        });

        this.protocol = new OpenLayers.Protocol.HTTP({
            url: this.$el.data('api-url'),
            params: {'features': '|||'},
            format: new OpenLayers.Format.Text(),
        });

        this.style = new OpenLayers.Style({
            pointRadius: "${radius}",
            //fillColor: "#cc6633",
            fillColor: "#cc1111",
            fillOpacity: 0.9,
            //strokeColor: "#ffcc66",
            strokeColor: "#cc1111",
            strokeWidth: 10,
            strokeOpacity: 0.4,
            label: "${count}",
            fontColor: "#ffffff",
        },{
            context: {
                radius: function(feature) {
                    return Math.min(Math.max(feature.attributes.count, 10), 50);
                },
                count: function(feature) {
                    return feature.attributes.count;
                }
            }
        });

        var pointsLayerArgs = {
            strategies: [
                this.bboxStrategy,
                this.clusterStrategy,
                this.refreshStrategy,
            ],
            protocol: this.protocol,
             styleMap: new OpenLayers.StyleMap({
                 "default": this.style,
                 "select": {
                     fillColor: "#8aeeef",
                     strokeColor: "#32a8a9"
                 }
             })
        };

        return new OpenLayers.Layer.Vector("POIs", pointsLayerArgs);
    },

    createSelectControl: function(layer) {
        return new OpenLayers.Control.SelectFeature(layer);
    }
});

Macadjan.map = new Macadjan.Map();

Macadjan.MainView = Backbone.View.extend({
    el: $("body"),

    events: {},

    initialize: function() {
        _.bindAll(this);
        this.container = this.$(".main-container");
    },
});

Macadjan.main = new Macadjan.MainView();

<commit_msg>Add clustering and refresh<commit_after>/* Author:
    RedDelicious
    Company: Kaleidos Open Source
*/

/* gettext dummy wrapper if not exists */

if (window.gettext === undefined) {
    window.gettext = function(text) {
        return text;
    };
}

if (window.interpolate === undefined) {
    window.interpolate = function(fmt, obj, named) {
        if (named) {
            return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
        } else {
            return fmt.replace(/%s/g, function(match){return String(obj.shift())});
        }
    };
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            !('/^(\/\/|http:|https:).*\/'.test(url)); // or any other URL that isn't scheme relative or absolute i.e relative.
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

/* Global macadjan  module namespace. */

var Macadjan = {}

Macadjan.Category = Backbone.Model.extend({});
Macadjan.SubCategory = Backbone.Model.extend({});

Macadjan.CategoryCollection = Backbone.Collection.extend({
    model: Macadjan.Category
});

Macadjan.SubCategoryCollection = Backbone.Collection.extend({
    model: Macadjan.SubCategory
});

Macadjan.categories = new Macadjan.CategoryCollection();
Macadjan.subCategories = new Macadjan.SubCategoryCollection();

Macadjan.Map = Backbone.View.extend({
    el: $("#map-block"),

    events: {},

    initializeControls: function() {
        this.navigationControl = new OpenLayers.Control.Navigation();
        this.layerSwitcherControl = new OpenLayers.Control.LayerSwitcher();
        this.panZoomControl = new OpenLayers.Control.PanZoomBar();
    },

    parseBounds: function() {
        var b = {
            "left": this.$el.data('map-bounds-left') || -20037508.34,
            "right": this.$el.data('map-bounds-right') || 20037508.34,
            "top": this.$el.data('map-bounds-top') || 20037508.34,
            "bottom": this.$el.data('map-bounds-bottom') || -20037508.34
        };

        return new OpenLayers.Bounds(b['left'], b['bottom'], b['right'], b['top']);
    },

    parseZoomLevels: function() {
        return 18;
    },

    parseUnits: function() {
        return "meters";
    },

    parseMaxResolution: function() {
        return 156543;
    },

    initialize: function() {
        _.bindAll(this);

        this.initializeControls();
        this.mapInitial = {
            projection: new OpenLayers.Projection('EPSG:4326'),
            controls: [
                this.navigationControl,
                this.layerSwitcherControl,
                this.panZoomControl
            ],
            maxExtent: this.parseBounds(),
            numZoomLevels: this.parseZoomLevels(),
            units:this.parseUnits(),
            maxResolution: this.parseMaxResolution()
        };

        this.map = new OpenLayers.Map(this.$el.attr('id'), this.mapInitial);

        this.osm = this.createOsmLayer();
        this.map.addLayer(this.osm);

        // Center map to initial coords
        this.centerMap();

        // Create points layer
        this.pointsLayer = this.createPointsLayer();
        this.map.addLayer(this.pointsLayer);

        // Create select control
        this.selectControl = this.createSelectControl(this.pointsLayer);
        this.map.addControl(this.selectControl);

        this.pointsLayer.events.on({
            "featureselected": this.onFeatureSelect,
            "featureunselected": this.onFeatureUnselect,
        });
    },

    onFeatureSelect: function(evt) {
        var feature = evt.feature;
        var content;

        if (!feature.cluster) {
            content = feature.attributes.title + '
' + feature.attributes.description;
        } else {
            content = '';
            var length = Math.min(feature.cluster.length, 50);
            for (var c = 0; c < length; c++) {
                content += feature.cluster[c].attributes.title + '
';
            }
            if (length < feature.cluster.length) {
                content += '(...)';
            }
        }
        var self = this;

        var popup = new OpenLayers.Popup.FramedCloud('featurePopup',
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(300, 100),
            content, null, true,
            function(evt) {
                var feature = this.feature;
                if (feature.layer) {
                    self.selectControl.unselect(feature);
                } else {
                    this.destroy();
                }
            }
        );

        popup.maxSize = new OpenLayers.Size(500, 300);
        feature.popup = popup;
        popup.feature = feature;
        map.addPopup(popup, true);
    },

    onFeatureUnselect: function(evt) {
        var feature = evt.feature;
        if (feature.popup) {
            popup.feature = null;
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
        }
    },

    centerMap: function() {
        var initialLon = this.$el.data('initial-lon');
        var initialLat = this.$el.data('initial-lat');
        var initialZoom = this.$el.data('initial-zoom');

        this.map.setCenter(new OpenLayers.LonLat(initialLon, initialLat).transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
        ), initialZoom);
    },

    createOsmLayer: function() {
        return new OpenLayers.Layer.OSM({
            transitionEffect: 'resize'
        })
    },

    createPointsLayer: function() {
        this.bboxStrategy = new OpenLayers.Strategy.BBOX();
        this.clusterStrategy = new OpenLayers.Strategy.Cluster({
            distance: 50,
            threshold: 1
        });
        this.refreshStrategy = new OpenLayers.Strategy.Refresh({
            force: true,
            active: true,
        });

        this.protocol = new OpenLayers.Protocol.HTTP({
            url: this.$el.data('api-url'),
            params: {'features': '|||'},
            format: new OpenLayers.Format.Text(),
        });

        this.style = new OpenLayers.Style({
            pointRadius: "${radius}",
            //fillColor: "#cc6633",
            fillColor: "#cc1111",
            fillOpacity: 0.9,
            //strokeColor: "#ffcc66",
            strokeColor: "#cc1111",
            strokeWidth: 10,
            strokeOpacity: 0.4,
            label: "${count}",
            fontColor: "#ffffff",
        },{
            context: {
                radius: function(feature) {
                    return Math.min(Math.max(feature.attributes.count, 10), 50);
                },
                count: function(feature) {
                    return feature.attributes.count;
                }
            }
        });

        var pointsLayerArgs = {
            strategies: [
                this.bboxStrategy,
                this.clusterStrategy,
                this.refreshStrategy,
            ],
            protocol: this.protocol,
             styleMap: new OpenLayers.StyleMap({
                 "default": this.style,
                 "select": {
                     fillColor: "#8aeeef",
                     strokeColor: "#32a8a9"
                 }
             })
        };

        return new OpenLayers.Layer.Vector("POIs", pointsLayerArgs);
    },

    createSelectControl: function(layer) {
        return new OpenLayers.Control.SelectFeature(layer);
    }
});

Macadjan.map = new Macadjan.Map();

Macadjan.MainView = Backbone.View.extend({
    el: $("body"),

    events: {},

    initialize: function() {
        _.bindAll(this);
        this.container = this.$(".main-container");
    },
});

Macadjan.main = new Macadjan.MainView();

<|endoftext|>