<commit_before>/** MODULE INTERFACE
 *@method {function} listen - Listen to events emitted on changes to the properties of a zone
 */
module.exports = {
    watchProperties: watchProperties
};

/*----------------------------------------------------------------------------*/

/** Listen to events emitted on changes to the properties of a zone
 * @param {object} properties - Event emitter fired when zone properties are changed
 */
function watchProperties(zone, properties) {
    // Zone properties
    properties.on('nameChange', function (name) {
        // console.log('nameChange');
    });
    properties.on('sizeChange', function (change) {
        // console.log('sizeChange');
    });
    properties.on('limitsChange', function (change) {
        // console.log('limitsChange');
    });
    properties.on('coordinatesChange', function (change) {
        var property = change.property,
            value = change.value,
            visibility = zone.visibility[property],
            handover = zone.handover,
            lowerLimit, higherLimit;

        lowerLimit = zone.limits[property].lower += value;
        higherLimit = zone.limits[property].higher += value;

        zone.margins.scope.inner[property].lower  = lowerLimit  + visibility;
        zone.margins.scope.inner[property].higher = higherLimit - visibility;
        zone.margins.scope.outer[property].lower  = lowerLimit  - visibility;
        zone.margins.scope.outer[property].higher = higherLimit + visibility;

        zone.margins.handover.bookin[property].lower   = lowerLimit  + handover;
        zone.margins.handover.bookin[property].higher  = higherLimit - handover;
        zone.margins.handover.checkin[property].lower  = lowerLimit  - handover;
        zone.margins.handover.checkin[property].higher = higherLimit + handover;

    });
    properties.on('visibilityChange', function (change) {
        // console.log('visibilityChange');
        var property = change.property,
            visibility = change.value,
            lowerLimit = zone.limits[property].lower;
            higherLimit = zone.limits[property].higher;

        zone.margins.scope.inner[property].lower  = lowerLimit  + visibility;
        zone.margins.scope.inner[property].higher = higherLimit - visibility;
        zone.margins.scope.outer[property].lower  = lowerLimit  - visibility;
        zone.margins.scope.outer[property].higher = higherLimit + visibility;
    });
    properties.on('handoverChange', function (change) {
        // console.log('handoverChange');
        var handover = change.value;

        ['x', 'y', 'z'].forEach(function (property) {
            lowerLimit = zone.limits[property].lower;
            higherLimit = zone.limits[property].higher;

            zone.margins.handover.bookin[property].lower   = lowerLimit  + handover;
            zone.margins.handover.bookin[property].higher  = higherLimit - handover;
            zone.margins.handover.checkin[property].lower  = lowerLimit  - handover;
            zone.margins.handover.checkin[property].higher = higherLimit + handover;
        });
    });
    properties.on('innerScopeChange', function (change) {
        // console.log('innerScopeChange');
    });
    properties.on('outerScopeChange', function (change) {
        // console.log('outerScopeChange');
    });
    properties.on('bookinMarginChange', function (change) {
        // console.log('bookinMarginChange');
    });
    properties.on('checkinMarginChange', function (change) {
        // console.log('checkinMarginChange');
    });

    // Zone elements
    properties.on('/element/add', function (element) {
        // console.log('addElement');
    });
    properties.on('/element/remove', function (key) {
        // console.log('removeElement');
    });
    properties.on('/element/positionChange', function (change) {
        // console.log('positionChange');
    });
}<commit_msg>Handled the 'neighborChange' event<commit_after>/** MODULE INTERFACE
 *@method {function} listen - Listen to events emitted on changes to the properties of a zone
 */
module.exports = {
    watchProperties: watchProperties
};

/*----------------------------------------------------------------------------*/

/** Listen to events emitted on changes to the properties of a zone
 * @param {object} properties - Event emitter fired when zone properties are changed
 */
function watchProperties(zone, properties) {
    // Zone properties
    properties.on('nameChange', function (name) {
        // console.log('nameChange');
    });
    properties.on('sizeChange', function (change) {
        // console.log('sizeChange');
    });
    properties.on('limitsChange', function (change) {
        // console.log('limitsChange');
    });
    properties.on('coordinatesChange', function (change) {
        var property = change.property,
            value = change.value,
            visibility = zone.visibility[property],
            handover = zone.handover,
            lowerLimit, higherLimit;

        lowerLimit = zone.limits[property].lower += value;
        higherLimit = zone.limits[property].higher += value;

        zone.margins.scope.inner[property].lower  = lowerLimit  + visibility;
        zone.margins.scope.inner[property].higher = higherLimit - visibility;
        zone.margins.scope.outer[property].lower  = lowerLimit  - visibility;
        zone.margins.scope.outer[property].higher = higherLimit + visibility;

        zone.margins.handover.bookin[property].lower   = lowerLimit  + handover;
        zone.margins.handover.bookin[property].higher  = higherLimit - handover;
        zone.margins.handover.checkin[property].lower  = lowerLimit  - handover;
        zone.margins.handover.checkin[property].higher = higherLimit + handover;

    });
    properties.on('visibilityChange', function (change) {
        // console.log('visibilityChange');
        var property = change.property,
            visibility = change.value,
            lowerLimit = zone.limits[property].lower;
            higherLimit = zone.limits[property].higher;

        zone.margins.scope.inner[property].lower  = lowerLimit  + visibility;
        zone.margins.scope.inner[property].higher = higherLimit - visibility;
        zone.margins.scope.outer[property].lower  = lowerLimit  - visibility;
        zone.margins.scope.outer[property].higher = higherLimit + visibility;
    });
    properties.on('handoverChange', function (change) {
        // console.log('handoverChange');
        var handover = change.value;

        ['x', 'y', 'z'].forEach(function (property) {
            lowerLimit = zone.limits[property].lower;
            higherLimit = zone.limits[property].higher;

            zone.margins.handover.bookin[property].lower   = lowerLimit  + handover;
            zone.margins.handover.bookin[property].higher  = higherLimit - handover;
            zone.margins.handover.checkin[property].lower  = lowerLimit  - handover;
            zone.margins.handover.checkin[property].higher = higherLimit + handover;
        });
    });
    properties.on('innerScopeChange', function (change) {
        // console.log('innerScopeChange');
    });
    properties.on('outerScopeChange', function (change) {
        // console.log('outerScopeChange');
    });
    properties.on('bookinMarginChange', function (change) {
        // console.log('bookinMarginChange');
    });
    properties.on('checkinMarginChange', function (change) {
        // console.log('checkinMarginChange');
    });

    // Zone elements
    properties.on('/element/add', function (element) {
        // console.log('addElement');
    });
    properties.on('/element/remove', function (key) {
        // console.log('removeElement');
    });
    properties.on('/element/positionChange', function (change) {
        // console.log('positionChange');
    });

    properties.on('neighborChange', function (change) {
        console.log('neighborChange', change.property, change.value);
    });
}<|endoftext|>


<commit_before>'use babel';

/**
 * Copyright (C) 2016 Ivan Kravets. All rights reserved.
 *
 * This source file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import child_process from 'child_process';
import {runAtomCommand} from '../utils';
import {InitializeNewProjectView} from './view';

export function command() {
  // Initialize view
  var view = new InitializeNewProjectView();
  var panel = atom.workspace.addModalPanel({item: view.getElement()});

  // Set buttons handlers
  view.handleCancel = () => panel.destroy();
  view.handleInit = () => {
    const projectPaths = atom.project.getPaths();
    if (0 === projectPaths.length) {
      atom.notifications.addWarning('Project does not have opened folders!', {
        detail: 'Please add empty folder to initialize new project or use ' +
        'existing PlatformIO Project to update it via "Menu: File > Add Project Folder...".',
        dismissable: 'true'
      });
      panel.destroy();
    }

    var initArgs = ['-f', '-c', 'atom', 'init', '--ide', 'atom'];
    view.getSelectedBoards().forEach((boardId) => {
      initArgs.push('--board');
      initArgs.push(boardId);
    });

    projectPaths.forEach((path) => {
      const args = initArgs.concat(['--project-dir', path]);
      const initResult = child_process.spawnSync('platformio', args);
      if (0 !== initResult.status) {
        let title = 'PlaftormIO: Failed to initialize PlatformIO project!';
        let msg = '' + initResult.stderr;
        atom.notifications.addError(title, {detail: msg});
        console.error(title);
        console.error(msg);
      } else {
        atom.notifications.addSuccess('PlatformIO: Project has been successfully initialized!', {
          detail: 'The next files/directories were created in "' + path + '"\n' +
          '"platformio.ini" - Project Configuration File\n' +
          '"src" - Put your source code here\n' +
          '"lib" - Put here project specific (private) libraries',
          dismissable: 'true'
        });
        runAtomCommand('build:refresh-targets');
      }
    });
    panel.destroy();
  };

  // Set available boards
  const boardsArgs = ['-f', '-c', 'atom', 'boards', '--json-output'];
  const boardsResult = child_process.spawnSync('platformio', boardsArgs);
  if (0 !== boardsResult.status) {
    let title = 'PlaftormIO: Failed to get boards list!';
    let msg = '' + boardsResult.stderr;
    atom.notifications.addError(title, {detail: msg});
    console.error(title);
    console.error(msg);
    return;
  }
  view.setBoards(JSON.parse('' + boardsResult.stdout));
}
<commit_msg>Initialize only active project<commit_after>'use babel';

/**
 * Copyright (C) 2016 Ivan Kravets. All rights reserved.
 *
 * This source file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import child_process from 'child_process';
import {runAtomCommand, getActiveProjectPath} from '../utils';
import {InitializeNewProjectView} from './view';

export function command() {
  // Initialize view
  var view = new InitializeNewProjectView();
  var panel = atom.workspace.addModalPanel({item: view.getElement()});

  // Set buttons handlers
  view.handleCancel = () => panel.destroy();
  view.handleInit = () => {
    const projectPath = getActiveProjectPath();
    if (!projectPath) {
      atom.notifications.addWarning('Project does not have opened folders!', {
        detail: 'Please add empty folder to initialize new project or use ' +
        'existing PlatformIO Project to update it via "Menu: File > Add Project Folder...".',
        dismissable: 'true'
      });
      panel.destroy();
    }

    var initArgs = ['-f', '-c', 'atom', 'init', '--ide', 'atom'];
    view.getSelectedBoards().forEach((boardId) => {
      initArgs.push('--board');
      initArgs.push(boardId);
    });

    const args = initArgs.concat(['--project-dir', projectPath]);
    const initResult = child_process.spawnSync('platformio', args);
    if (0 !== initResult.status) {
      let title = 'PlaftormIO: Failed to initialize PlatformIO project!';
      let msg = '' + initResult.stderr;
      atom.notifications.addError(title, {detail: msg});
      console.error(title);
      console.error(msg);
    } else {
      atom.notifications.addSuccess('PlatformIO: Project has been successfully initialized!', {
        detail: 'The next files/directories were created in "' + projectPath + '"\n' +
        '"platformio.ini" - Project Configuration File\n' +
        '"src" - Put your source code here\n' +
        '"lib" - Put here project specific (private) libraries',
        dismissable: 'true'
      });
      runAtomCommand('build:refresh-targets');
    }
    panel.destroy();
  };

  // Set available boards
  const boardsArgs = ['-f', '-c', 'atom', 'boards', '--json-output'];
  const boardsResult = child_process.spawnSync('platformio', boardsArgs);
  if (0 !== boardsResult.status) {
    let title = 'PlaftormIO: Failed to get boards list!';
    let msg = '' + boardsResult.stderr;
    atom.notifications.addError(title, {detail: msg});
    console.error(title);
    console.error(msg);
    return;
  }
  view.setBoards(JSON.parse('' + boardsResult.stdout));
}
<|endoftext|>


<commit_before>function Formulas() {}

Formulas.prototype.exponential = function(x0, x1, y0, y1, x) {
	return y0 * Math.pow((y1 / y0), ((Math.min(x, x1) - x0) / (x1 - x0)));
}

Formulas.prototype.exponential_integral = function(x0, x1, y0, y1, constant, x) {
	// Integral of the following function:
	// v(t) = V0 * (V1 / V0) ^ ((t - T0) / (T1 - T0))

	dx = x1 - x0;
	ry = y1 / y0;
	U  = ry ^ (1/dx);
	return y0 * ( Math.pow(U, x-x0) / Math.log(U) );
}

Formulas.prototype.exponential_integral_inverse = function(x0, x1, y0, y1, constant, y) {
	var dx = x1 - x0;
	var ry = y1 / y0;
	var U = Math.pow(ry, 1/dx);
	var V = y0 * Math.pow(ry, -x0/dx);

	var aux = (y * Math.log(U) / V) - constant;

	return Math.log(aux) / Math.log(U);

	dx = x1 - x0;
	ry = y1 / y0;
	U  = ry ^ (1/dx);
	V  = y0 * (ry ^ (-x0/dx));

	aux = (y * log(U) / V) - constant;

	res = log(aux) / log(U);
}

Formulas.prototype.linear = function(x0, x1, y0, y1, x) {
	return y0 + (y1 - y0) * ((Math.min(x, x1) - x0) / (x1 - x0));
}

Formulas.prototype.linear_integral = function(x0, x1, y0, y1, constant, x) {
	// Integral of the following function:
	// v(t) = V0 + (V1 - V0) * ((t - T0) / (T1 - T0))

	dy  = y1 - y0;
	dx  = x1 - x0;
	M   = dy / (2*dx);
	C   = y0;

	return M * Math.pow((x - x0), 2) + y0 * (x - x0) + constant;
}

Formulas.prototype.linear_integral_inverse = function(x0, x1, y0, y1, constant, y) {

	dx  = x1 - x0;
	dy  = y1 - y0;
	A   = 0.5 * dy / dx;
	B   = y0 - 2 * A * x0;
	C   = A * (x0*x0) - y0 * x0 + constant;

	square_root = sqrt(B*B - 4*A*(C-y));
	sol1 = (-B + square_root) / (2*A);
	sol2 = (-B - square_root) / (2*A);

	if (sol1>0)
		return sol1;
	else
		return sol2;
}<commit_msg>Corrected some small typos in formulas.js.<commit_after>function Formulas() {}

Formulas.prototype.exponential = function(x0, x1, y0, y1, x) {
	return y0 * Math.pow((y1 / y0), ((Math.min(x, x1) - x0) / (x1 - x0)));
}

Formulas.prototype.exponential_integral = function(x0, x1, y0, y1, constant, x) {
	// Integral of the following function:
	// v(t) = V0 * (V1 / V0) ^ ((t - T0) / (T1 - T0))

	dx = x1 - x0;
	ry = y1 / y0;
	U  = ry ^ (1/dx);
	return y0 * ( Math.pow(U, x-x0) / Math.log(U) );
}

Formulas.prototype.exponential_integral_inverse = function(x0, x1, y0, y1, constant, y) {
	var dx = x1 - x0;
	var ry = y1 / y0;
	var U = Math.pow(ry, 1/dx);
	var V = y0 * Math.pow(ry, -x0/dx);

	var aux = (y * Math.log(U) / V) - constant;

	return Math.log(aux) / Math.log(U);

	dx = x1 - x0;
	ry = y1 / y0;
	U  = ry ^ (1/dx);
	V  = y0 * (ry ^ (-x0/dx));

	aux = (y * Math.log(U) / V) - constant;

	res = Math.log(aux) / Math.log(U);
}

Formulas.prototype.linear = function(x0, x1, y0, y1, x) {
	return y0 + (y1 - y0) * ((Math.min(x, x1) - x0) / (x1 - x0));
}

Formulas.prototype.linear_integral = function(x0, x1, y0, y1, constant, x) {
	// Integral of the following function:
	// v(t) = V0 + (V1 - V0) * ((t - T0) / (T1 - T0))

	dy  = y1 - y0;
	dx  = x1 - x0;
	M   = dy / (2*dx);
	C   = y0;

	return M * Math.pow((x - x0), 2) + y0 * (x - x0) + constant;
}

Formulas.prototype.linear_integral_inverse = function(x0, x1, y0, y1, constant, y) {

	dx  = x1 - x0;
	dy  = y1 - y0;
	A   = 0.5 * dy / dx;
	B   = y0 - 2 * A * x0;
	C   = A * (x0*x0) - y0 * x0 + constant;

	square_root = Math.sqrt(B*B - 4*A*(C-y));
	sol1 = (-B + square_root) / (2*A);
	sol2 = (-B - square_root) / (2*A);

	if (sol1>0)
		return sol1;
	else
		return sol2;
}<|endoftext|>


<commit_before>var loadingOverlay;

(function() {
    if (typeof(loadingOverlay) !== 'undefined') return;

    var lastSpinHandle = "";

    var heredoc = function(f) {
        return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1];
    };
    var lut = [];
    for (var il = 0; il < 256; il++) { lut[il] = (il < 16 ? '0' : '') + (il).toString(16); }
    var uuid = function() {
        var d0 = Math.random() * 0xffffffff | 0;
        var d1 = Math.random() * 0xffffffff | 0;
        var d2 = Math.random() * 0xffffffff | 0;
        var d3 = Math.random() * 0xffffffff | 0;
        return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
            lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
            lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
            lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
    };
    var makeCRCTable = function() {
        var c;
        var crcTable = [];
        for (var n = 0; n < 256; n++) {
            c = n;
            for (var k = 0; k < 8; k++) {
                c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
            }
            crcTable[n] = c;
        }
        return crcTable;
    }
    var crcTable = null;
    var crc32 = function(str) {
        if (!crcTable) crcTable = makeCRCTable();
        var crc = 0 ^ (-1);

        for (var i = 0; i < str.length; i++) {
            crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
        }

        return (crc ^ (-1)) >>> 0;
    };

    var showTarget = function(selector) {

        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].style.display = "block";
        }

    };

    var hideTarget = function(selector) {

        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].style.display = "none";
        }

    };

    var appendHtmlToTarget = function(selector, html) {
        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].insertAdjacentHTML('beforeend', html);
        }
    };

    var lo = (function() {

        var classNS = 'lo';
        var idNS = 'lo-' + uuid();

        var paramDefault = {
            'wrapClass': classNS + '-wrap',
            'spinClass': classNS + '-spin',
            'spinID': idNS,
            'target': 'body',
            'spinMinMS': 300,
            'spinWaitMS': 100,
        };

        var param2hash = function(param) {
            return crc32(param['wrapClass'] + param['spinClass'] + param['spinID']);
        };

        var cache = {};

        return {
            uuid: uuid,
            cache: function(param, createItemCallback) {
                var hash = param2hash(param);
                if (cache[hash]) return cache[hash];
                cache[hash] = createItemCallback();
                return cache[hash];
            },
            config2param: function(config) {
                var param = paramDefault;
                if ((typeof config === 'undefined') || (typeof config !== 'object')) {
                    return param;
                }
                for (var prop in param) {
                    if (typeof config[prop] !== 'undefined') {
                        param[prop] = config[prop];
                    }
                }
                return param;
            },
        };
    })();

    loadingOverlay = function(config) {
        var param = lo.config2param(config);

        return lo.cache(param, function() {
            var target = '#' + param['spinID'];
            ////console.log('target...');
            ////console.debug(target);

            var cancelSpinnerOn = false;

            var spinnerStart;

            var cancelled_cb_proto = {
                'invoked': false,
                'cb': null,
            };
            var cancelled_cb_hash = {};
            var cancelled_status_hash = {};

            var cancelled_hash_proto = {
                'status': false,
                'cb_hash': {},
            };
            var cancelled_hash = {};

            var activateSpinner = function() {
               var spinWrap = document.getElementById(param['spinID']);
               if (!spinWrap) {
                  for (var csh in cancelled_status_hash) {
                     if (!cancelled_status_hash[csh]) {
                        cancelled_status_hash[csh] = true;
                     }
                  }
                  appendHtmlToTarget(param.target, heredoc(function() {
                          /*

                                      */
                      })
                      .replace(/%wrapClass%/g, param['wrapClass'])
                      .replace(/%spinID%/g, param['spinID'])
                  );
               }
                var mySpinHandle = uuid();
                lastSpinHandle = mySpinHandle;
                cancelSpinnerOn = false;
                cancelled_status_hash[mySpinHandle] = false;
                cancelled_hash[mySpinHandle] = cancelled_hash_proto;
                ////console.log('actvate: '+mySpinHandle);
                setTimeout(function() {
                    if (cancelled_status_hash[mySpinHandle] == true) {
                        return;
                    }
                    if (cancelSpinnerOn && (lastSpinHandle == mySpinHandle)) {
                        cancelSpinnerOn = false;
                        lastSpinHandle = null;
                        return false;
                    }
                    if (lastSpinHandle != mySpinHandle) {
                        return false;
                    }
                    spinnerStart = Date.now();
                    showTarget(target);
                }, param.spinWaitMS);
                return mySpinHandle;
            };
            var spinMin = param.spinMinMS;
            var cancelSpinner = function cancelSpinnerCallee(spinHandle, cancelledCallback, cancelUUID) {
                //console.log("cancel: " + spinHandle);
                var cUUID;
                if (typeof cancelUUID === 'undefined') {
                    cUUID = lo.uuid();
                } else {
                    cUUID = cancelUUID;
                }
                if (cancelled_status_hash[spinHandle] === true) {
                    if (typeof cancelled_cb_hash[cUUID] !== 'undefined') {
                        if (!cancelled_cb_hash[cUUID].invoked) {
                            cancelled_cb_hash[cUUID].invoked = true;
                            cancelled_cb_hash[cUUID]();
                        }
                    }
                    return;
                }

                cancelled_cb_hash[cUUID] = cancelled_cb_proto;

                if (typeof cancelledCallback !== 'undefined') {
                    cancelled_cb_hash[cUUID].cb = cancelledCallback;
                }

                if (typeof cancelled_hash[spinHandle] === 'undefined') {
                    cancelled_hash[spinHandle] = cancelled_hash_proto;
                }
                cancelled_hash[spinHandle].cb_hash[cUUID] = cancelled_cb_hash[cUUID];

                cancelSpinnerOn = true;
                setTimeout(function() {
                    var spinTime = Date.now() - spinnerStart;
                    if (spinTime < spinMin) {
                        setTimeout(function() {
                            cancelSpinnerCallee(spinHandle, cancelledCallback, cUUID);
                        }, 10);
                    } else {

                        cancelled_status_hash[spinHandle] = true;
                        if (typeof cancelledCallback === 'function') {
                            //console.log('cb cancel normal');
                            cancelled_hash[spinHandle].cb_hash[cUUID].invoked = true;
                            cancelled_cb_hash[cUUID].invoked = true;
                            cancelledCallback();
                            for (var c in cancelled_hash[spinHandle].cb_hash) {
                                if (!cancelled_hash[spinHandle].cb_hash[c].invoked && (typeof cancelled_hash[spinHandle].cb_hash[c].cb === 'function')) {
                                    cancelled_hash[spinHandle].cb_hash[c].invoked = true;
                                    cancelled_hash[spinHandle].cb_hash[c].cb();
                                }
                            }
                        }
                        //console.log('cancel spinHandle ' + spinHandle + ' check if others are uncancelled');
                        for (var hh in cancelled_status_hash) {
                            if (!cancelled_status_hash[hh]) {
                                return;
                            }
                        }
                        hideTarget(target);
                    }
                }, 10);
            };

            //typeof cancelSpinnerCallee === 'undefined';
            delete cancelSpinnerCallee;
            var obj = {
                cancel: cancelSpinner,
                activate: activateSpinner,
                cancelAll : function() {
                  var spinWrapElem = document.querySelectorAll('#'+param['spinID']);
                   for (var i = 0; i < spinWrapElem.length; i++) {
                      spinWrapElem[i].remove();
                      console.log('removed');
                   }
                },
            };

            var targetElem = document.querySelectorAll(target);
            if (targetElem) {
                targetElem.forEach(function(elem) {
                    if (elem.classList.contains(param['class'])) {
                        return obj;
                    }
                });
            }

            appendHtmlToTarget(param.target, heredoc(function() {
                /*

                            */
            }).replace(/%wrapClass%/g, param['wrapClass']).replace(/%spinClass%/g, param['spinClass']));

            return obj;

        });
    };

})();
<commit_msg>loadingOverlay as object<commit_after>var loadingOverlay;

(function() {
    if (typeof(loadingOverlay) !== 'undefined') return;

    var lastSpinHandle = "";

    var heredoc = function(f) {
        return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1];
    };
    var lut = [];
    for (var il = 0; il < 256; il++) { lut[il] = (il < 16 ? '0' : '') + (il).toString(16); }
    var uuid = function() {
        var d0 = Math.random() * 0xffffffff | 0;
        var d1 = Math.random() * 0xffffffff | 0;
        var d2 = Math.random() * 0xffffffff | 0;
        var d3 = Math.random() * 0xffffffff | 0;
        return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
            lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
            lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
            lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
    };
    var makeCRCTable = function() {
        var c;
        var crcTable = [];
        for (var n = 0; n < 256; n++) {
            c = n;
            for (var k = 0; k < 8; k++) {
                c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
            }
            crcTable[n] = c;
        }
        return crcTable;
    }
    var crcTable = null;
    var crc32 = function(str) {
        if (!crcTable) crcTable = makeCRCTable();
        var crc = 0 ^ (-1);

        for (var i = 0; i < str.length; i++) {
            crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
        }

        return (crc ^ (-1)) >>> 0;
    };

    var showTarget = function(selector) {

        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].style.display = "block";
        }

    };

    var hideTarget = function(selector) {

        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].style.display = "none";
        }

    };

    var appendHtmlToTarget = function(selector, html) {
        var elem = document.querySelectorAll(selector);
        for (var i = 0; i < elem.length; i++) {
            elem[i].insertAdjacentHTML('beforeend', html);
        }
    };

    var lo = (function() {

        var classNS = 'lo';
        var idNS = 'lo-' + uuid();

        var paramDefault = {
            'wrapClass': classNS + '-wrap',
            'spinClass': classNS + '-spin',
            'spinID': idNS,
            'target': 'body',
            'spinMinMS': 300,
            'spinWaitMS': 100,
        };

        var param2hash = function(param) {
            return crc32(param['wrapClass'] + param['spinClass'] + param['spinID']);
        };

        var cache = {};

        return {
            uuid: uuid,
            cache: function(param, createItemCallback) {
                var hash = param2hash(param);
                if (cache[hash]) return cache[hash];
                cache[hash] = createItemCallback();
                return cache[hash];
            },
            config2param: function(config) {
                var param = paramDefault;
                if ((typeof config === 'undefined') || (typeof config !== 'object')) {
                    return param;
                }
                for (var prop in param) {
                    if (typeof config[prop] !== 'undefined') {
                        param[prop] = config[prop];
                    }
                }
                return param;
            },
        };
    })();

    var invokeLoadingOverlay = function(config) {
        var param = lo.config2param(config);

        return lo.cache(param, function() {
            var target = '#' + param['spinID'];
            ////console.log('target...');
            ////console.debug(target);

            var cancelSpinnerOn = false;

            var spinnerStart;

            var cancelled_cb_proto = {
                'invoked': false,
                'cb': null,
            };
            var cancelled_cb_hash = {};
            var cancelled_status_hash = {};

            var cancelled_hash_proto = {
                'status': false,
                'cb_hash': {},
            };
            var cancelled_hash = {};

            var activateSpinner = function() {
               var spinWrap = document.getElementById(param['spinID']);
               if (!spinWrap) {
                  for (var csh in cancelled_status_hash) {
                     if (!cancelled_status_hash[csh]) {
                        cancelled_status_hash[csh] = true;
                     }
                  }
                  appendHtmlToTarget(param.target, heredoc(function() {
                          /*

                                      */
                      })
                      .replace(/%wrapClass%/g, param['wrapClass'])
                      .replace(/%spinID%/g, param['spinID'])
                  );
               }
                var mySpinHandle = uuid();
                lastSpinHandle = mySpinHandle;
                cancelSpinnerOn = false;
                cancelled_status_hash[mySpinHandle] = false;
                cancelled_hash[mySpinHandle] = cancelled_hash_proto;
                ////console.log('actvate: '+mySpinHandle);
                setTimeout(function() {
                    if (cancelled_status_hash[mySpinHandle] == true) {
                        return;
                    }
                    if (cancelSpinnerOn && (lastSpinHandle == mySpinHandle)) {
                        cancelSpinnerOn = false;
                        lastSpinHandle = null;
                        return false;
                    }
                    if (lastSpinHandle != mySpinHandle) {
                        return false;
                    }
                    spinnerStart = Date.now();
                    showTarget(target);
                }, param.spinWaitMS);
                return mySpinHandle;
            };
            var spinMin = param.spinMinMS;
            var cancelSpinner = function cancelSpinnerCallee(spinHandle, cancelledCallback, cancelUUID) {
                //console.log("cancel: " + spinHandle);
                var cUUID;
                if (typeof cancelUUID === 'undefined') {
                    cUUID = lo.uuid();
                } else {
                    cUUID = cancelUUID;
                }
                if (cancelled_status_hash[spinHandle] === true) {
                    if (typeof cancelled_cb_hash[cUUID] !== 'undefined') {
                        if (!cancelled_cb_hash[cUUID].invoked) {
                            cancelled_cb_hash[cUUID].invoked = true;
                            cancelled_cb_hash[cUUID]();
                        }
                    }
                    return;
                }

                cancelled_cb_hash[cUUID] = cancelled_cb_proto;

                if (typeof cancelledCallback !== 'undefined') {
                    cancelled_cb_hash[cUUID].cb = cancelledCallback;
                }

                if (typeof cancelled_hash[spinHandle] === 'undefined') {
                    cancelled_hash[spinHandle] = cancelled_hash_proto;
                }
                cancelled_hash[spinHandle].cb_hash[cUUID] = cancelled_cb_hash[cUUID];

                cancelSpinnerOn = true;
                setTimeout(function() {
                    var spinTime = Date.now() - spinnerStart;
                    if (spinTime < spinMin) {
                        setTimeout(function() {
                            cancelSpinnerCallee(spinHandle, cancelledCallback, cUUID);
                        }, 10);
                    } else {

                        cancelled_status_hash[spinHandle] = true;
                        if (typeof cancelledCallback === 'function') {
                            //console.log('cb cancel normal');
                            cancelled_hash[spinHandle].cb_hash[cUUID].invoked = true;
                            cancelled_cb_hash[cUUID].invoked = true;
                            cancelledCallback();
                            for (var c in cancelled_hash[spinHandle].cb_hash) {
                                if (!cancelled_hash[spinHandle].cb_hash[c].invoked && (typeof cancelled_hash[spinHandle].cb_hash[c].cb === 'function')) {
                                    cancelled_hash[spinHandle].cb_hash[c].invoked = true;
                                    cancelled_hash[spinHandle].cb_hash[c].cb();
                                }
                            }
                        }
                        //console.log('cancel spinHandle ' + spinHandle + ' check if others are uncancelled');
                        for (var hh in cancelled_status_hash) {
                            if (!cancelled_status_hash[hh]) {
                                return;
                            }
                        }
                        hideTarget(target);
                    }
                }, 10);
            };

            //typeof cancelSpinnerCallee === 'undefined';
            delete cancelSpinnerCallee;
            var obj = {
                cancel: cancelSpinner,
                activate: activateSpinner,
                cancelAll : function() {
                  var spinWrapElem = document.querySelectorAll('#'+param['spinID']);
                   for (var i = 0; i < spinWrapElem.length; i++) {
                      spinWrapElem[i].remove();
                      console.log('removed');
                   }
                },
            };

            var targetElem = document.querySelectorAll(target);
            if (targetElem) {
                targetElem.forEach(function(elem) {
                    if (elem.classList.contains(param['class'])) {
                        return obj;
                    }
                });
            }

            appendHtmlToTarget(param.target, heredoc(function() {
                /*

                            */
            }).replace(/%wrapClass%/g, param['wrapClass']).replace(/%spinClass%/g, param['spinClass']));

            return obj;

        });
    };

    //loadingOverlay = invokeLoadingOverlay;
   function functionize( obj , func ) {
      out = func;
      for( i in obj ){ out[i] = obj[i]; } ;
      return out;
   }

    loadingOverlay = invokeLoadingOverlay();

    loadingOverlay = functionize( loadingOverlay , function(param){ return invokeLoadingOverlay(param); } );

})();
<|endoftext|>


<commit_before>var margin = {top: 20, right: 30, bottom: 30, left: 40},
    width = window.innerWidth - margin.left - margin.right,
    height = window.innerHeight - margin.top - margin.bottom - 100;

var svg = d3.select('svg#chart')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
  .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

var data,
    root,
    prevFolder = [],
    description = d3.select('p#description');

var editing = false,
    sourceNode = null;

d3.select('button#back')
    .on('click', gotoPreviousFolder);
d3.select('button#toggleEdit')
    .on('click', toggleEdit);

d3.json('test/d3.franklin', function (error, _data) {
  data = _data;
  root = '/';
  createDagre(data[root]);
});

function createDagre(root) {
  var g = new dagreD3.Digraph(),
      nodes = flatten(root);

  // Nodes
  nodes.forEach(function (d) {
    g.addNode(d.name, { label: d.name, description: d.description, entry_point: d.entry_point });
  });
  // Edges
  nodes.forEach(function (d) {
    d.next.forEach(function (n) {
      if (!g.hasNode(n)) {
        g.addNode(n, { label: n, description: '' });
      }
      g.addEdge(null, d.name, n);
    });
  });

  var renderer = new dagreD3.Renderer();
  var oldDrawNodes = renderer.drawNodes();
  renderer.drawNodes(function (graph, svg) {
    var svgNodes = oldDrawNodes(graph, svg);
    svgNodes.select('rect')
        .attr('style', function (u) {
          if (g.node(u).entry_point) return 'fill: #ffd0cd';
        })
        .attr('id', function (u) { return 'franklin-' + cleanHtmlId(g.node(u).label); })
        .on('click', function (u) { handleClick(g.node(u).label); })
        .on('mouseover', function (u) { updateDescription(g.node(u).description); });
    return svgNodes;
  });
  renderer.run(g, svg);
}

function flatten(obj) {
  var nodes = [], i = 0;
  d3.keys(obj).forEach(function (key) {
    var value = obj[key];
    value.name = key;
    value.id = ++i;
    nodes.push(value);
  });
  return nodes;
};

function handleClick(name) {
  if (d3.event.defaultPrevented) return;
  if (!editing && data[root + name]) {
    prevFolder.push(root);
    root += name;
    createDagre(data[root]);
  } else if (editing) {
    handleEdit(name);
  }
}

function handleEdit(name) {
  if (sourceNode && sourceNode != name) {
    data[root][sourceNode].next.push(name);
    d3.select('#franklin-' + cleanHtmlId(sourceNode))
        .style('stroke', null);
    sourceNode = null;
    createDagre(data[root]);
  } else {
    sourceNode = name;
    d3.select('#franklin-' + cleanHtmlId(sourceNode))
        .style('stroke', '#e22121');
  }
}

function updateDescription(des) {
  description.html(des);
}

function cleanHtmlId(id) {
  // Replace "/" or "." with "-".
  return id.replace(/\/|\./, '-');
}

function gotoPreviousFolder(e) {
  var folder = prevFolder.pop();
  if (folder) {
    root = folder;
    createDagre(data[root]);
  }
}

function toggleEdit(e) {
  editing = !editing;
  d3.select('button#toggleEdit').html(editing ? 'Explore' : 'Edit');
  selectNode = null;
}
<commit_msg>Ability to delete nodes and links between nodes.<commit_after>var margin = {top: 20, right: 30, bottom: 30, left: 40},
    width = window.innerWidth - margin.left - margin.right,
    height = window.innerHeight - margin.top - margin.bottom - 100;

var svg = d3.select('svg#chart')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
  .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

var data,
    root,
    prevFolder = [],
    description = d3.select('p#description');

var editing = false,
    sourceNode = null,
    specialAction = null;

d3.select('button#back')
    .on('click', gotoPreviousFolder);
d3.select('button#toggleEdit')
    .on('click', toggleEdit);
d3.select(document)
    .on('keydown', handleKeyDown)
    .on('keyup', handleKeyUp);

d3.json('test/d3.franklin', function (error, _data) {
  data = _data;
  root = '/';
  createDagre(data[root]);
});

function createDagre(root) {
  var g = new dagreD3.Digraph(),
      nodes = flatten(root);

  // Nodes
  nodes.forEach(function (d) {
    g.addNode(d.name, { label: d.name, description: d.description, entry_point: d.entry_point });
  });
  // Edges
  nodes.forEach(function (d) {
    d.next.forEach(function (n) {
      if (!g.hasNode(n)) {
        g.addNode(n, { label: n, description: '' });
      }
      g.addEdge(null, d.name, n);
    });
  });

  var renderer = new dagreD3.Renderer();
  var oldDrawNodes = renderer.drawNodes();
  renderer.drawNodes(function (graph, svg) {
    var svgNodes = oldDrawNodes(graph, svg);
    svgNodes.select('rect')
        .attr('style', function (u) {
          if (g.node(u).entry_point) return 'fill: #ffd0cd';
        })
        .attr('id', function (u) { return 'franklin-' + cleanHtmlId(g.node(u).label); })
        .on('click', function (u) { handleClick(g.node(u).label); })
        .on('mouseover', function (u) { updateDescription(g.node(u).description); });
    return svgNodes;
  });
  renderer.run(g, svg);
}

function flatten(obj) {
  var nodes = [], i = 0;
  d3.keys(obj).forEach(function (key) {
    var value = obj[key];
    value.name = key;
    value.id = ++i;
    nodes.push(value);
  });
  return nodes;
};

function handleClick(name) {
  if (d3.event.defaultPrevented) return;
  if (!editing && data[root + name]) {
    prevFolder.push(root);
    root += name;
    createDagre(data[root]);
  } else if (editing) {
    editGraph(name);
  }
}

function editGraph(name) {
  if (sourceNode && sourceNode != name) {
    if (specialAction == 'removeLink') {
      var n = data[root][sourceNode];
      n.next = n.next.filter(function(f) { return f != name; });
    } else {
      data[root][sourceNode].next.push(name);
    }

    d3.select('#franklin-' + cleanHtmlId(sourceNode))
          .style('stroke', null);
    sourceNode = null;
    createDagre(data[root]);
  } else if (specialAction == 'deleteNode') {
    delete data[root][name];
    createDagre(data[root]);
  } else {
    sourceNode = name;
    d3.select('#franklin-' + cleanHtmlId(sourceNode))
        .style('stroke', '#e22121');
  }
}

function updateDescription(des) {
  description.html(des);
}

function cleanHtmlId(id) {
  // Replace "/" or "." with "-".
  return id.replace(/\/|\./, '-');
}

function gotoPreviousFolder(e) {
  var folder = prevFolder.pop();
  if (folder) {
    root = folder;
    createDagre(data[root]);
  }
}

function toggleEdit(e) {
  editing = !editing;
  d3.select('button#toggleEdit').html(editing ? 'Explore' : 'Edit');
  if (sourceNode) {
    d3.select('#franklin-' + cleanHtmlId(sourceNode))
        .style('stroke', null);
  }
  sourceNode = null;
}

function handleKeyDown() {
  if (specialAction) return;
  var e = d3.event.keyCode;
  if (e == 68) { specialAction = 'deleteNode'; } // 'd'
  else if (e == 82) { specialAction = 'removeLink'; } // 'r'
}

function handleKeyUp() {
  var e = d3.event.keyCode;
  if (e == 68 && specialAction == 'deleteNode') { specialAction = null; } // 'd'
  else if (e == 82 && specialAction == 'removeLink')  { specialAction = null; } // 'r'
}

<|endoftext|>


<commit_before>require('express-hijackresponse');

var React = require('react-tools');

function getErrorScript(errorMessage) {
    var cleanErrorMessage = errorMessage.replace('\n', '\\n').replace('"', '\\"');
    return [
        '/**********************************************************',
        errorMessage.split('\n').map(function (str) {
            return ' * ' + str;
        }).join('\n'),
        ' *********************************************************/',
        ';(function () {',
        '    var element = document.createElement("DIV");',
        '    element.style.position = "absolute";',
        '    element.style.top = 0;',
        '    element.style.left = 0;',
        '    element.style.right = 0;',
        '    element.style.bottom = 0;',
        '    element.style.backgroundColor = "white";',
        '    element.style.zIndex = 999999;',
        '    element.style.fontSize = "24px";',
        '    element.style.color = "red";',
        '    element.style.padding = "20px";',
        '    element.style.textAlign = "left";',
        '    element.style.whiteSpace = "pre";',
        '    element.style.fontFamily = "monospace";',
        '    element.innerText = "' + cleanErrorMessage + '";',
        '    document.body.appendChild(element);',
        '}());',
        ''
    ].join('\n');
}

module.exports = function (options) {

    return function (req, res, next) {
        // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-jsxtransform":
        var ifNoneMatch = req.headers['if-none-match'];
        if (ifNoneMatch) {
            var validIfNoneMatchTokens = ifNoneMatch.split(' ').filter(function (etag) {
                return /-jsxtransform\"$/.test(etag);
            });
            if (validIfNoneMatchTokens.length > 0) {
                req.headers['if-none-match'] = validIfNoneMatchTokens.join(' ');
            } else {
                delete req.headers['if-none-match'];
            }
        }
        delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling jsxtransform
        res.hijack(function (err, res) {
            var fileType = (req.originalUrl.match(/\.(js|jsx)$/) || []).shift();
            var annotationInserted = false;
            if (res.statusCode === 200 && fileType) {
                var chunks = [];
                res.on('error', function () {
                    res.unhijack();
                    next();
                }).on('data', function (chunk) {
                    chunks.push(chunk);
                }).on('end', function () {
                    if (!chunks.length) {
                        return res.send(res.statusCode);
                    }
                    var jsText = Buffer.concat(chunks).toString('utf-8');

                    var firstLine = jsText.split('\n')[0];

                    if (fileType === '.jsx') {
                        if (!/^\/\*\*(\s)@jsx/.test(firstLine)) {
                            jsText = '/** @jsx React.DOM */\n' + jsText;
                            annotationInserted = true;
                        }
                    }

                    if (fileType === '.jsx' || /^\/\*\*(\s)@jsx/.test(firstLine)) {
                        try {
                            jsText = React.transform(jsText, {});

                            if (annotationInserted) {
                                jsText = jsText.split('\n').splice(1).join('\n');
                            }
                        } catch (e) {
                            // If parsing the file throws an error, build a
                            // meaningful error response.
                            var errorMessage = e.message + '\nIn file: ' + req.originalUrl;
                            jsText = getErrorScript(errorMessage);
                        }
                    }

                    res.setHeader('Content-Type', 'text/javascript');
                    res.setHeader('Content-Length', Buffer.byteLength(jsText));
                    res.end(jsText);
                });
            } else {
                res.unhijack(true);
            }
        });
        next();
    };
};
<commit_msg>Only hijack the response if the filetype matches what we want to transform. Prevents unhijack error up the chain. Fixes #1<commit_after>require('express-hijackresponse');

var React = require('react-tools');

function getErrorScript(errorMessage) {
    var cleanErrorMessage = errorMessage.replace('\n', '\\n').replace('"', '\\"');
    return [
        '/**********************************************************',
        errorMessage.split('\n').map(function (str) {
            return ' * ' + str;
        }).join('\n'),
        ' *********************************************************/',
        ';(function () {',
        '    var element = document.createElement("DIV");',
        '    element.style.position = "absolute";',
        '    element.style.top = 0;',
        '    element.style.left = 0;',
        '    element.style.right = 0;',
        '    element.style.bottom = 0;',
        '    element.style.backgroundColor = "white";',
        '    element.style.zIndex = 999999;',
        '    element.style.fontSize = "24px";',
        '    element.style.color = "red";',
        '    element.style.padding = "20px";',
        '    element.style.textAlign = "left";',
        '    element.style.whiteSpace = "pre";',
        '    element.style.fontFamily = "monospace";',
        '    element.innerText = "' + cleanErrorMessage + '";',
        '    document.body.appendChild(element);',
        '}());',
        ''
    ].join('\n');
}

module.exports = function (options) {

    return function (req, res, next) {
        var fileType = (req.originalUrl.match(/\.(js|jsx)$/) || []).shift();

        if (!fileType) {
            return next();
        } else {
            // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-jsxtransform":
            var ifNoneMatch = req.headers['if-none-match'];
            if (ifNoneMatch) {
                var validIfNoneMatchTokens = ifNoneMatch.split(' ').filter(function (etag) {
                    return /-jsxtransform\"$/.test(etag);
                });
                if (validIfNoneMatchTokens.length > 0) {
                    req.headers['if-none-match'] = validIfNoneMatchTokens.join(' ');
                } else {
                    delete req.headers['if-none-match'];
                }
            }
            delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling jsxtransform
            res.hijack(function (err, res) {
                var annotationInserted = false;
                if (res.statusCode === 200 && fileType) {
                    var chunks = [];
                    res.on('error', function () {
                        res.unhijack();
                        next();
                    }).on('data', function (chunk) {
                        chunks.push(chunk);
                    }).on('end', function () {
                        if (!chunks.length) {
                            return res.send(res.statusCode);
                        }
                        var jsText = Buffer.concat(chunks).toString('utf-8');

                        var firstLine = jsText.split('\n')[0];

                        if (fileType === '.jsx') {
                            if (!/^\/\*\*(\s)@jsx/.test(firstLine)) {
                                jsText = '/** @jsx React.DOM */\n' + jsText;
                                annotationInserted = true;
                            }
                        }

                        if (fileType === '.jsx' || /^\/\*\*(\s)@jsx/.test(firstLine)) {
                            try {
                                jsText = React.transform(jsText, {});

                                if (annotationInserted) {
                                    jsText = jsText.split('\n').splice(1).join('\n');
                                }
                            } catch (e) {
                                // If parsing the file throws an error, build a
                                // meaningful error response.
                                var errorMessage = e.message + '\nIn file: ' + req.originalUrl;
                                jsText = getErrorScript(errorMessage);
                            }
                        }

                        res.setHeader('Content-Type', 'text/javascript');
                        res.setHeader('Content-Length', Buffer.byteLength(jsText));
                        res.end(jsText);
                    });
                } else {
                    res.unhijack(true);
                }
            });
            next();
        }
    };
};
<|endoftext|>


<commit_before>var interceptor = require('express-interceptor');

var React = require('react-tools');

function getErrorScript(errorMessage) {
    var cleanErrorMessage = errorMessage.replace('\n', '\\n').replace('"', '\\"');
    return [
        '/**********************************************************',
        errorMessage.split('\n').map(function (str) {
            return ' * ' + str;
        }).join('\n'),
        ' *********************************************************/',
        ';(function () {',
        '    var element = document.createElement("DIV");',
        '    element.style.position = "absolute";',
        '    element.style.top = 0;',
        '    element.style.left = 0;',
        '    element.style.right = 0;',
        '    element.style.bottom = 0;',
        '    element.style.backgroundColor = "white";',
        '    element.style.zIndex = 999999;',
        '    element.style.fontSize = "24px";',
        '    element.style.color = "red";',
        '    element.style.padding = "20px";',
        '    element.style.textAlign = "left";',
        '    element.style.whiteSpace = "pre";',
        '    element.style.fontFamily = "monospace";',
        '    element.innerText = "' + cleanErrorMessage + '";',
        '    document.body.appendChild(element);',
        '}());',
        ''
    ].join('\n');
}

module.exports = function (options) {
    return interceptor(function (req, res) {
        var fileType = (req.originalUrl.match(/\.(js|jsx)$/) || []).shift();
        // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-jsxtransform":
        var ifNoneMatch = req.headers['if-none-match'];

        if (ifNoneMatch) {
            var validIfNoneMatchTokens = ifNoneMatch.split(' ').filter(function (etag) {
                return /-jsxtransform\"$/.test(etag);
            });

            if (validIfNoneMatchTokens.length > 0) {
                req.headers['if-none-match'] = validIfNoneMatchTokens.join(' ');
            } else {
                delete req.headers['if-none-match'];
            }
        }

        delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling jsxtransform

        return {
            isInterceptable: function() {
                return true;
            },
            intercept: function(body, send) {
                var annotationInserted = false;

                if (res.statusCode === 200) {
                    var firstLine = body.split('\n')[0];

                    if (fileType === '.jsx') {
                        if (!/^\/\*\*(\s)@jsx/.test(firstLine)) {
                            body = '/** @jsx React.DOM */\n' + body;
                            annotationInserted = true;
                        }
                    }

                    if (fileType === '.jsx' || /^\/\*\*(\s)@jsx/.test(firstLine)) {
                        try {
                            body = React.transform(body, {});

                            if (annotationInserted) {
                                body = body.split('\n').splice(1).join('\n');
                            }
                        } catch (e) {
                            // If parsing the file throws an error, build a
                            // meaningful error response.
                            var errorMessage = e.message + '\nIn file: ' + req.originalUrl;
                            body = getErrorScript(errorMessage);
                        }
                    }

                    res.setHeader('Content-Type', 'text/javascript');
                    res.setHeader('Content-Length', Buffer.byteLength(body));
                    send(body);
                }
            }
        };
    });
};
<commit_msg>add spaces after function keyword (hello OCD)<commit_after>var interceptor = require('express-interceptor');

var React = require('react-tools');

function getErrorScript(errorMessage) {
    var cleanErrorMessage = errorMessage.replace('\n', '\\n').replace('"', '\\"');
    return [
        '/**********************************************************',
        errorMessage.split('\n').map(function (str) {
            return ' * ' + str;
        }).join('\n'),
        ' *********************************************************/',
        ';(function () {',
        '    var element = document.createElement("DIV");',
        '    element.style.position = "absolute";',
        '    element.style.top = 0;',
        '    element.style.left = 0;',
        '    element.style.right = 0;',
        '    element.style.bottom = 0;',
        '    element.style.backgroundColor = "white";',
        '    element.style.zIndex = 999999;',
        '    element.style.fontSize = "24px";',
        '    element.style.color = "red";',
        '    element.style.padding = "20px";',
        '    element.style.textAlign = "left";',
        '    element.style.whiteSpace = "pre";',
        '    element.style.fontFamily = "monospace";',
        '    element.innerText = "' + cleanErrorMessage + '";',
        '    document.body.appendChild(element);',
        '}());',
        ''
    ].join('\n');
}

module.exports = function (options) {
    return interceptor(function (req, res) {
        var fileType = (req.originalUrl.match(/\.(js|jsx)$/) || []).shift();
        // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-jsxtransform":
        var ifNoneMatch = req.headers['if-none-match'];

        if (ifNoneMatch) {
            var validIfNoneMatchTokens = ifNoneMatch.split(' ').filter(function (etag) {
                return /-jsxtransform\"$/.test(etag);
            });

            if (validIfNoneMatchTokens.length > 0) {
                req.headers['if-none-match'] = validIfNoneMatchTokens.join(' ');
            } else {
                delete req.headers['if-none-match'];
            }
        }

        delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling jsxtransform

        return {
            isInterceptable: function () {
                return true;
            },
            intercept: function (body, send) {
                var annotationInserted = false;

                if (res.statusCode === 200) {
                    var firstLine = body.split('\n')[0];

                    if (fileType === '.jsx') {
                        if (!/^\/\*\*(\s)@jsx/.test(firstLine)) {
                            body = '/** @jsx React.DOM */\n' + body;
                            annotationInserted = true;
                        }
                    }

                    if (fileType === '.jsx' || /^\/\*\*(\s)@jsx/.test(firstLine)) {
                        try {
                            body = React.transform(body, {});

                            if (annotationInserted) {
                                body = body.split('\n').splice(1).join('\n');
                            }
                        } catch (e) {
                            // If parsing the file throws an error, build a
                            // meaningful error response.
                            var errorMessage = e.message + '\nIn file: ' + req.originalUrl;
                            body = getErrorScript(errorMessage);
                        }
                    }

                    res.setHeader('Content-Type', 'text/javascript');
                    res.setHeader('Content-Length', Buffer.byteLength(body));
                    send(body);
                }
            }
        };
    });
};
<|endoftext|>


<commit_before>/**
 * Worker that parses replays
 * The actual parsing is done by invoking the Java-based parser.
 * This produces an event stream (newline-delimited JSON)
 * Stream is run through a series of processors to count/aggregate it into a single object
 * This object is passed to insertMatch to persist the data into the database.
 * */
const utility = require('../util/utility');
const getGcData = require('../util/getGcData');
const config = require('../config');
const queue = require('../store/queue');
const queries = require('../store/queries');
// const createParsedDataBlob = require('../processors/createParsedDataBlob');
const cp = require('child_process');
const async = require('async');
const numCPUs = require('os').cpus().length;

const insertMatch = queries.insertMatch;
const buildReplayUrl = utility.buildReplayUrl;

function runParse(match, job, cb) {
  let url = match.url;
  if (config.NODE_ENV === 'test') {
    url = `https://cdn.rawgit.com/odota/testfiles/master/${match.match_id}_1.dem`;
  }
  console.log(new Date(), url);
  cp.exec(`curl --max-time 180 ${url} | ${url && url.slice(-3) === 'bz2' ? 'bunzip2' : 'cat'} | curl -X POST -T - ${config.PARSER_HOST} | node processors/createParsedDataBlob.js ${match.match_id} ${Boolean(match.doLogParse)}`,
    { shell: true, maxBuffer: 10 * 1024 * 1024 },
    (err, stdout) => {
      if (err) {
        return cb(err);
      }
      const result = Object.assign({}, JSON.parse(stdout), match);
      return insertMatch(result, {
        type: 'parsed',
        skipParse: true,
        doLogParse: match.doLogParse,
      }, cb);
    });
}

function parseProcessor(job, cb) {
  const match = job;
  async.series({
    getDataSource(cb) {
      getGcData(match, (err, result) => {
        if (err) {
          return cb(err);
        }
        match.url = buildReplayUrl(result.match_id, result.cluster, result.replay_salt);
        return cb(err);
      });
    },
    runParse(cb) {
      runParse(match, job, cb);
    },
  }, (err) => {
    if (err) {
      console.error(err.stack || err);
    } else {
      console.log('completed parse of match %s', match.match_id);
    }
    if (global.gc) {
      global.gc();
    }
    console.log(process.memoryUsage());
    return cb(err, match.match_id);
  });
}

queue.runReliableQueue('parse', Number(config.PARSER_PARALLELISM) || numCPUs, parseProcessor);
<commit_msg>add fail opt to curl<commit_after>/**
 * Worker that parses replays
 * The actual parsing is done by invoking the Java-based parser.
 * This produces an event stream (newline-delimited JSON)
 * Stream is run through a series of processors to count/aggregate it into a single object
 * This object is passed to insertMatch to persist the data into the database.
 * */
const utility = require('../util/utility');
const getGcData = require('../util/getGcData');
const config = require('../config');
const queue = require('../store/queue');
const queries = require('../store/queries');
// const createParsedDataBlob = require('../processors/createParsedDataBlob');
const cp = require('child_process');
const async = require('async');
const numCPUs = require('os').cpus().length;

const insertMatch = queries.insertMatch;
const buildReplayUrl = utility.buildReplayUrl;

function runParse(match, job, cb) {
  let url = match.url;
  if (config.NODE_ENV === 'test') {
    url = `https://cdn.rawgit.com/odota/testfiles/master/${match.match_id}_1.dem`;
  }
  console.log(new Date(), url);
  cp.exec(`curl --max-time 180 --fail ${url} | ${url && url.slice(-3) === 'bz2' ? 'bunzip2' : 'cat'} | curl -X POST -T - ${config.PARSER_HOST} | node processors/createParsedDataBlob.js ${match.match_id} ${Boolean(match.doLogParse)}`,
    { shell: true, maxBuffer: 10 * 1024 * 1024 },
    (err, stdout) => {
      if (err) {
        return cb(err);
      }
      const result = Object.assign({}, JSON.parse(stdout), match);
      return insertMatch(result, {
        type: 'parsed',
        skipParse: true,
        doLogParse: match.doLogParse,
      }, cb);
    });
}

function parseProcessor(job, cb) {
  const match = job;
  async.series({
    getDataSource(cb) {
      getGcData(match, (err, result) => {
        if (err) {
          return cb(err);
        }
        match.url = buildReplayUrl(result.match_id, result.cluster, result.replay_salt);
        return cb(err);
      });
    },
    runParse(cb) {
      runParse(match, job, cb);
    },
  }, (err) => {
    if (err) {
      console.error(err.stack || err);
    } else {
      console.log('completed parse of match %s', match.match_id);
    }
    if (global.gc) {
      global.gc();
    }
    console.log(process.memoryUsage());
    return cb(err, match.match_id);
  });
}

queue.runReliableQueue('parse', Number(config.PARSER_PARALLELISM) || numCPUs, parseProcessor);
<|endoftext|>


<commit_before>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * @author brian@hovercraftstudios.com
 */

(function(define) {
define(['./when'], function(when) {

	var slice;

	slice = Array.prototype.slice;

	return {
		apply: apply,
		call: call,
		bind: bind,
		compose: compose,
		promisify: promisify
	};

	function apply(func, args) {
		var d = when.defer();

		try {
			d.resolve(func.apply(null, args));
		} catch(e) {
			d.reject(e);
		}

		return d.promise;
	}

	function call(func /*, args... */) {
		return apply(func, slice.call(arguments, 1));
	}

	function bind(func /*, args... */) {
		var args = slice.call(arguments, 1);
		return function() {
			return apply(func, args.concat(slice.call(arguments)));
		};
	}

	function compose(f /*g, ... */) {
		var funcs = slice.call(arguments, 1);

		return function() {
			var args = slice.call(arguments);

			return when.reduce(funcs, function(arg, func) {
				return func(arg);
			}, f.apply(null, args));
		};
	}

	function promisify(func, callbackPos, errbackPos, progbackPos) {
		var orig, initArgs;

		orig = func;

		// If you only supply the function, assume callback and errback
		// will always be the last two params.
		// If you supply positions, use them to inject callback/errback/progback
		// into the args.
		if(arguments.length === 1) {
			initArgs = function(args, deferred) {
				args.push(deferred.resolve);
				args.push(deferred.reject);

				return args;
			};
		} else {
			initArgs = function(args, deferred) {
				if(typeof callbackPos == 'number') {
					args.splice(callbackPos, 0, deferred.resolve);
				}

				if(typeof errbackPos == 'number') {
					args.splice(errbackPos, 0, deferred.reject);
				}

				if(typeof progbackPos == 'number') {
					args.splice(progbackPos, 0, deferred.progress);
				}

				return args;
			};
		}

		return function() {
			var args, d;

			args = slice.call(arguments);
			d = when.defer();

			apply(orig, this, initArgs(args, d));

			return d.promise;
		};
	}
});

})(typeof define == 'function'
	? define
	: function (deps, factory) { typeof module != 'undefined'
	? (module.exports = factory(require('./when'), require('./nextTick')))
	: (this.when_fn = factory(this.when, this.when_nextTick));
}
	// Boilerplate for AMD, Node, and browser global
);

<commit_msg>The 'context' arg was removed on 2c6d6ee60880dc460ea8f6342ccf048273d1edf8<commit_after>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * @author brian@hovercraftstudios.com
 */

(function(define) {
define(['./when'], function(when) {

	var slice;

	slice = Array.prototype.slice;

	return {
		apply: apply,
		call: call,
		bind: bind,
		compose: compose,
		promisify: promisify
	};

	function apply(func, args) {
		var d = when.defer();

		try {
			d.resolve(func.apply(null, args));
		} catch(e) {
			d.reject(e);
		}

		return d.promise;
	}

	function call(func /*, args... */) {
		return apply(func, slice.call(arguments, 1));
	}

	function bind(func /*, args... */) {
		var args = slice.call(arguments, 1);
		return function() {
			return apply(func, args.concat(slice.call(arguments)));
		};
	}

	function compose(f /*g, ... */) {
		var funcs = slice.call(arguments, 1);

		return function() {
			var args = slice.call(arguments);

			return when.reduce(funcs, function(arg, func) {
				return func(arg);
			}, f.apply(null, args));
		};
	}

	function promisify(func, callbackPos, errbackPos, progbackPos) {
		var orig, initArgs;

		orig = func;

		// If you only supply the function, assume callback and errback
		// will always be the last two params.
		// If you supply positions, use them to inject callback/errback/progback
		// into the args.
		if(arguments.length === 1) {
			initArgs = function(args, deferred) {
				args.push(deferred.resolve);
				args.push(deferred.reject);

				return args;
			};
		} else {
			initArgs = function(args, deferred) {
				if(typeof callbackPos == 'number') {
					args.splice(callbackPos, 0, deferred.resolve);
				}

				if(typeof errbackPos == 'number') {
					args.splice(errbackPos, 0, deferred.reject);
				}

				if(typeof progbackPos == 'number') {
					args.splice(progbackPos, 0, deferred.progress);
				}

				return args;
			};
		}

		return function() {
			var args, d;

			args = slice.call(arguments);
			d = when.defer();

			apply(orig, initArgs(args, d));

			return d.promise;
		};
	}
});

})(typeof define == 'function'
	? define
	: function (deps, factory) { typeof module != 'undefined'
	? (module.exports = factory(require('./when'), require('./nextTick')))
	: (this.when_fn = factory(this.when, this.when_nextTick));
}
	// Boilerplate for AMD, Node, and browser global
);

<|endoftext|>


<commit_before>"use strict";

var P         = require('bluebird');
var HTTPError = require('hyperswitch').HTTPError;
var uuid = require('cassandra-uuid').TimeUuid;

var EventService = function(options) {
    if (options && options.eventlogging_service) {
        // TODO: remove eventually
        // keep compat with old config
        options = options.eventlogging_service;
    }
    if (options && options.purge) {
        // TODO: remove eventually
        // disregard old-config purge stanzas
        options.purge = undefined;
    }
    this.options = options;
};

EventService.prototype.emitEvent = function(hyper, req) {
    var self = this;
    if (!(self.options && self.options.uri && self.options.topic)) {
        return { status: 200 };
    }
    return P.try(function() {
        // Change-propagation will set up the x-triggered-by header, indicating
        // the event which caused the rerender. In case RESTBase is about to emit
        // the same event, it will cause a rerender loop. So, log an error and skip
        // the event.
        var triggeredBy = req.headers && req.headers['x-triggered-by']
            || hyper._rootReq && hyper._rootReq['x-triggered-by'];
        var topic = self.options.topic;
        if (triggeredBy && self.options.transcludes_topic
                && /transcludes/.test(triggeredBy)) {
            topic = self.options.transcludes_topic;
        }

        var events = req.body.map(function(event) {
            if (!event.meta || !event.meta.uri || !/^\/\//.test(event.meta.uri)) {
                hyper.log('error/events/emit', {
                    message: 'Invalid event URI',
                    event: event
                });
                return undefined;
            }
            event.meta.uri = 'http:' + event.meta.uri;
            event.meta.topic = topic;
            event.meta.request_id = hyper.reqId;
            event.meta.id = uuid.now().toString();
            event.meta.dt = new Date().toISOString();
            event.meta.domain = req.params.domain;
            event.tags = event.tags || [];
            if (event.tags.indexOf('restbase') < 0) {
                event.tags.push('restbase');
            }
            return event;
        })
        .filter(function(event) { return !!event; });

        if (triggeredBy) {
            triggeredBy = triggeredBy.replace(/https?:/g, '');
            events = events.filter(function(event) {
                var eventId = event.meta.topic + ':' + event.meta.uri.replace(/^https?:/, '');
                if (triggeredBy.indexOf(eventId) !== -1) {
                    hyper.log('error/events/rerender_loop', {
                        message: 'Rerender loop detected',
                        event: event
                    });
                    return false;
                }
                return true;
            });
        }

        if (events && events.length) {
            if (self.options.skip_updates) {
                return P.resolve();
            }
            return hyper.post({
                uri: self.options.uri,
                headers: {
                    'content-type': 'application/json'
                },
                body: events
            });
        }
    })
    .catch(function(e) {
        hyper.log('error/events/emit', e);
    }).thenReturn({ status: 200 });
};

module.exports = function(options) {
    var es = new EventService(options);

    return {
        spec: {
            paths: {
                '/': {
                    post: {
                        operationId: 'emitEvent'
                    }
                }
            }
        },
        operations: {
            emitEvent: es.emitEvent.bind(es)
        }
    };
};
<commit_msg>Look at the rootReq headers (#678)<commit_after>"use strict";

var P         = require('bluebird');
var HTTPError = require('hyperswitch').HTTPError;
var uuid = require('cassandra-uuid').TimeUuid;

var EventService = function(options) {
    if (options && options.eventlogging_service) {
        // TODO: remove eventually
        // keep compat with old config
        options = options.eventlogging_service;
    }
    if (options && options.purge) {
        // TODO: remove eventually
        // disregard old-config purge stanzas
        options.purge = undefined;
    }
    this.options = options;
};

EventService.prototype.emitEvent = function(hyper, req) {
    var self = this;
    if (!(self.options && self.options.uri && self.options.topic)) {
        return { status: 200 };
    }
    return P.try(function() {
        // Change-propagation will set up the x-triggered-by header, indicating
        // the event which caused the rerender. In case RESTBase is about to emit
        // the same event, it will cause a rerender loop. So, log an error and skip
        // the event.
        var triggeredBy = req.headers && req.headers['x-triggered-by']
            || hyper._rootReq && hyper._rootReq.headers && hyper._rootReq.headers['x-triggered-by'];
        var topic = self.options.topic;
        if (triggeredBy && self.options.transcludes_topic
                && /transcludes/.test(triggeredBy)) {
            topic = self.options.transcludes_topic;
        }

        var events = req.body.map(function(event) {
            if (!event.meta || !event.meta.uri || !/^\/\//.test(event.meta.uri)) {
                hyper.log('error/events/emit', {
                    message: 'Invalid event URI',
                    event: event
                });
                return undefined;
            }
            event.meta.uri = 'http:' + event.meta.uri;
            event.meta.topic = topic;
            event.meta.request_id = hyper.reqId;
            event.meta.id = uuid.now().toString();
            event.meta.dt = new Date().toISOString();
            event.meta.domain = req.params.domain;
            event.tags = event.tags || [];
            if (event.tags.indexOf('restbase') < 0) {
                event.tags.push('restbase');
            }
            return event;
        })
        .filter(function(event) { return !!event; });

        if (triggeredBy) {
            triggeredBy = triggeredBy.replace(/https?:/g, '');
            events = events.filter(function(event) {
                var eventId = event.meta.topic + ':' + event.meta.uri.replace(/^https?:/, '');
                if (triggeredBy.indexOf(eventId) !== -1) {
                    hyper.log('error/events/rerender_loop', {
                        message: 'Rerender loop detected',
                        event: event
                    });
                    return false;
                }
                return true;
            });
        }

        if (events && events.length) {
            if (self.options.skip_updates) {
                return P.resolve();
            }
            return hyper.post({
                uri: self.options.uri,
                headers: {
                    'content-type': 'application/json'
                },
                body: events
            });
        }
    })
    .catch(function(e) {
        hyper.log('error/events/emit', e);
    }).thenReturn({ status: 200 });
};

module.exports = function(options) {
    var es = new EventService(options);

    return {
        spec: {
            paths: {
                '/': {
                    post: {
                        operationId: 'emitEvent'
                    }
                }
            }
        },
        operations: {
            emitEvent: es.emitEvent.bind(es)
        }
    };
};
<|endoftext|>


<commit_before>'use babel'

import {Emitter, CompositeDisposable} from 'atom'
import BottomPanel from './ui/bottom-panel'
import BottomContainer from './ui/bottom-container'
import {Message} from './ui/message-element'
import Helpers from './helpers'
import {create as createBubble} from './ui/message-bubble'

export default class LinterViews {
  constructor(scope, editorRegistry) {
    this.subscriptions = new CompositeDisposable()
    this.emitter = new Emitter()
    this.bottomPanel = new BottomPanel(scope)
    this.bottomContainer = BottomContainer.create(scope)
    this.editors = editorRegistry
    this.bottomBar = null // To be added when status-bar service is consumed
    this.bubble = null
    this.bubbleRange = null

    this.subscriptions.add(this.bottomPanel)
    this.subscriptions.add(this.bottomContainer)
    this.subscriptions.add(this.emitter)

    this.count = {
      Line: 0,
      File: 0,
      Project: 0
    }
    this.messages = []
    this.subscriptions.add(atom.config.observe('linter.showErrorInline', showBubble =>
      this.showBubble = showBubble
    ))
    this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(paneItem => {
      let isEditor = false
      this.editors.forEach(function(editorLinter) {
        isEditor = (editorLinter.active = editorLinter.editor === paneItem) || isEditor
      })
      this.updateCounts()
      this.bottomPanel.refresh()
      this.bottomContainer.visibility = isEditor
    }))
    this.subscriptions.add(this.bottomContainer.onDidChangeTab(scope => {
      this.emitter.emit('did-update-scope', scope)
      atom.config.set('linter.showErrorPanel', true)
      this.bottomPanel.refresh(scope)
    }))
    this.subscriptions.add(this.bottomContainer.onShouldTogglePanel(function() {
      atom.config.set('linter.showErrorPanel', !atom.config.get('linter.showErrorPanel'))
    }))

    this._renderBubble = this.renderBubble
    this.subscriptions.add(atom.config.observe('linter.inlineTooltipInterval', bubbleInterval =>
      this.renderBubble = Helpers.debounce(this._renderBubble, bubbleInterval)
    ))
  }
  render({added, removed, messages}) {
    this.messages = messages
    this.notifyEditorLinters({added, removed})
    this.bottomPanel.setMessages({added, removed})
    this.updateCounts()
  }
  updateCounts() {
    const activeEditorLinter = this.editors.ofActiveTextEditor()

    this.count.Project = this.messages.length
    this.count.File = activeEditorLinter ? activeEditorLinter.getMessages().size : 0
    this.count.Line = activeEditorLinter ? activeEditorLinter.countLineMessages : 0
    this.bottomContainer.setCount(this.count)
  }
  renderBubble(editorLinter) {
    if (!this.showBubble || !editorLinter.messages.size) {
      return
    }
    const point = editorLinter.editor.getCursorBufferPosition()
    if (this.bubbleRange && this.bubbleRange.containsPoint(point)) {
      return // The marker remains the same
    } else if (this.bubble) {
      this.bubble.destroy()
      this.bubble = null
    }
    for (let entry of editorLinter.markers) {
      const bubbleRange = entry[1].getBufferRange()
      if (bubbleRange.containsPoint(point)) {
        this.bubbleRange = bubbleRange
        this.bubble = editorLinter.editor.decorateMarker(entry[1], {
          type: 'overlay',
          item: createBubble(entry[0])
        })
        return
      }
    }
    this.bubbleRange = null
  }
  notifyEditorLinters({added, removed}) {
    let editorLinter
    removed.forEach(message => {
      if (message.filePath && (editorLinter = this.editors.ofPath(message.filePath))) {
        editorLinter.deleteMessage(message)
      }
    })
    added.forEach(message => {
      if (message.filePath && (editorLinter = this.editors.ofPath(message.filePath))) {
        editorLinter.addMessage(message)
      }
    })
    editorLinter = this.editors.ofActiveTextEditor()
    if (editorLinter) {
      editorLinter.calculateLineMessages(null)
      this.renderBubble(editorLinter)
    }
  }
  notifyEditorLinter(editorLinter) {
    const path = editorLinter.editor.getPath()
    if (!path) return
    this.messages.forEach(function(message) {
      if (message.filePath && message.filePath === path) {
        editorLinter.addMessage(message)
      }
    })
  }
  attachBottom(statusBar) {
    this.subscriptions.add(atom.config.observe('linter.statusIconPosition', position => {
      if (this.bottomBar) {
        this.bottomBar.destroy()
      }
      this.bottomBar = statusBar[`add${position}Tile`]({
        item: this.bottomContainer,
        priority: position === 'Left' ? -100 : 100
      })
    }))
  }

  onDidUpdateScope(callback) {
    return this.emitter.on('did-update-scope', callback)
  }
  dispose() {
    // No need to notify editors of this, we're being disposed means the package is
    // being deactivated. They'll be disposed automatically by the registry.
    this.subscriptions.dispose()
    if (this.bottomBar) {
      this.bottomBar.destroy()
    }
    if (this.bubble) {
      this.bubble.destroy()
      this.bubbleRange = null
    }
  }
}
<commit_msg>Update priority<commit_after>'use babel'

import {Emitter, CompositeDisposable} from 'atom'
import BottomPanel from './ui/bottom-panel'
import BottomContainer from './ui/bottom-container'
import {Message} from './ui/message-element'
import Helpers from './helpers'
import {create as createBubble} from './ui/message-bubble'

export default class LinterViews {
  constructor(scope, editorRegistry) {
    this.subscriptions = new CompositeDisposable()
    this.emitter = new Emitter()
    this.bottomPanel = new BottomPanel(scope)
    this.bottomContainer = BottomContainer.create(scope)
    this.editors = editorRegistry
    this.bottomBar = null // To be added when status-bar service is consumed
    this.bubble = null
    this.bubbleRange = null

    this.subscriptions.add(this.bottomPanel)
    this.subscriptions.add(this.bottomContainer)
    this.subscriptions.add(this.emitter)

    this.count = {
      Line: 0,
      File: 0,
      Project: 0
    }
    this.messages = []
    this.subscriptions.add(atom.config.observe('linter.showErrorInline', showBubble =>
      this.showBubble = showBubble
    ))
    this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(paneItem => {
      let isEditor = false
      this.editors.forEach(function(editorLinter) {
        isEditor = (editorLinter.active = editorLinter.editor === paneItem) || isEditor
      })
      this.updateCounts()
      this.bottomPanel.refresh()
      this.bottomContainer.visibility = isEditor
    }))
    this.subscriptions.add(this.bottomContainer.onDidChangeTab(scope => {
      this.emitter.emit('did-update-scope', scope)
      atom.config.set('linter.showErrorPanel', true)
      this.bottomPanel.refresh(scope)
    }))
    this.subscriptions.add(this.bottomContainer.onShouldTogglePanel(function() {
      atom.config.set('linter.showErrorPanel', !atom.config.get('linter.showErrorPanel'))
    }))

    this._renderBubble = this.renderBubble
    this.subscriptions.add(atom.config.observe('linter.inlineTooltipInterval', bubbleInterval =>
      this.renderBubble = Helpers.debounce(this._renderBubble, bubbleInterval)
    ))
  }
  render({added, removed, messages}) {
    this.messages = messages
    this.notifyEditorLinters({added, removed})
    this.bottomPanel.setMessages({added, removed})
    this.updateCounts()
  }
  updateCounts() {
    const activeEditorLinter = this.editors.ofActiveTextEditor()

    this.count.Project = this.messages.length
    this.count.File = activeEditorLinter ? activeEditorLinter.getMessages().size : 0
    this.count.Line = activeEditorLinter ? activeEditorLinter.countLineMessages : 0
    this.bottomContainer.setCount(this.count)
  }
  renderBubble(editorLinter) {
    if (!this.showBubble || !editorLinter.messages.size) {
      return
    }
    const point = editorLinter.editor.getCursorBufferPosition()
    if (this.bubbleRange && this.bubbleRange.containsPoint(point)) {
      return // The marker remains the same
    } else if (this.bubble) {
      this.bubble.destroy()
      this.bubble = null
    }
    for (let entry of editorLinter.markers) {
      const bubbleRange = entry[1].getBufferRange()
      if (bubbleRange.containsPoint(point)) {
        this.bubbleRange = bubbleRange
        this.bubble = editorLinter.editor.decorateMarker(entry[1], {
          type: 'overlay',
          item: createBubble(entry[0])
        })
        return
      }
    }
    this.bubbleRange = null
  }
  notifyEditorLinters({added, removed}) {
    let editorLinter
    removed.forEach(message => {
      if (message.filePath && (editorLinter = this.editors.ofPath(message.filePath))) {
        editorLinter.deleteMessage(message)
      }
    })
    added.forEach(message => {
      if (message.filePath && (editorLinter = this.editors.ofPath(message.filePath))) {
        editorLinter.addMessage(message)
      }
    })
    editorLinter = this.editors.ofActiveTextEditor()
    if (editorLinter) {
      editorLinter.calculateLineMessages(null)
      this.renderBubble(editorLinter)
    }
  }
  notifyEditorLinter(editorLinter) {
    const path = editorLinter.editor.getPath()
    if (!path) return
    this.messages.forEach(function(message) {
      if (message.filePath && message.filePath === path) {
        editorLinter.addMessage(message)
      }
    })
  }
  attachBottom(statusBar) {
    this.subscriptions.add(atom.config.observe('linter.statusIconPosition', position => {
      if (this.bottomBar) {
        this.bottomBar.destroy()
      }
      this.bottomBar = statusBar[`add${position}Tile`]({
        item: this.bottomContainer,
        priority: position === 'Left' ? 10 : 100
      })
    }))
  }

  onDidUpdateScope(callback) {
    return this.emitter.on('did-update-scope', callback)
  }
  dispose() {
    // No need to notify editors of this, we're being disposed means the package is
    // being deactivated. They'll be disposed automatically by the registry.
    this.subscriptions.dispose()
    if (this.bottomBar) {
      this.bottomBar.destroy()
    }
    if (this.bubble) {
      this.bubble.destroy()
      this.bubbleRange = null
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

// ArrayBuffer/Uint8Array are old formats that date back to before we
// had a proper browserified buffer type. they may be removed later
var arrayBuffPrefix = 'ArrayBuffer:';
var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
var uintPrefix = 'Uint8Array:';
var uintRegex = new RegExp('^' + uintPrefix);

// this is the new encoding format used going forward
var bufferPrefix = 'Buff:';
var bufferRegex = new RegExp('^' + bufferPrefix);

var utils = require('./utils');
var LocalStorageCore = require('./localstorage-core');
var TaskQueue = require('./taskqueue');
var d64 = require('d64');

function LocalStorage(dbname) {
  this._store = new LocalStorageCore(dbname);
  this._queue = new TaskQueue();
}

LocalStorage.prototype.sequentialize = function (callback, fun) {
  this._queue.add(fun, callback);
};

LocalStorage.prototype.init = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    self._store.getKeys(function (err, keys) {
      if (err) {
        return callback(err);
      }
      self._keys = keys;
      return callback();
    });
  });
};

LocalStorage.prototype.keys = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    callback(null, self._keys.slice());
  });
};

//setItem: Saves and item at the key provided.
LocalStorage.prototype.setItem = function (key, value, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    if (Buffer.isBuffer(value)) {
      value = bufferPrefix + d64.encode(value);
    }

    var idx = utils.sortedIndexOf(self._keys, key);
    if (self._keys[idx] !== key) {
      self._keys.splice(idx, 0, key);
    }
    self._store.put(key, value, callback);
  });
};

//getItem: Returns the item identified by it's key.
LocalStorage.prototype.getItem = function (key, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    self._store.get(key, function (err, retval) {
      if (err) {
        return callback(err);
      }
      if (typeof retval === 'undefined' || retval === null) {
        // 'NotFound' error, consistent with LevelDOWN API
        return callback(new Error('NotFound'));
      }
      if (typeof retval !== 'undefined') {
        if (bufferRegex.test(retval)) {
          retval = d64.decode(retval.substring(bufferPrefix.length));
        } else if (arrayBuffRegex.test(retval)) {
          // this type is kept for backwards
          // compatibility with older databases, but may be removed
          // after a major version bump
          retval = retval.substring(arrayBuffPrefix.length);
          retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
            return c.charCodeAt(0);
          }));
        } else if (uintRegex.test(retval)) {
          // ditto
          retval = retval.substring(uintPrefix.length);
          retval = new Uint8Array(atob(retval).split('').map(function (c) {
            return c.charCodeAt(0);
          }));
        }
      }
      callback(null, retval);
    });
  });
};

//removeItem: Removes the item identified by it's key.
LocalStorage.prototype.removeItem = function (key, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    var idx = utils.sortedIndexOf(self._keys, key);
    if (self._keys[idx] === key) {
      self._keys.splice(idx, 1);
      self._store.remove(key, function (err) {
        if (err) {
          return callback(err);
        }
        callback();
      });
    } else {
      callback();
    }
  });
};

LocalStorage.prototype.length = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    callback(null, self._keys.length);
  });
};

exports.LocalStorage = LocalStorage;
<commit_msg>FIX key-cache destroys updates on multiWindow (#84)<commit_after>'use strict';

// ArrayBuffer/Uint8Array are old formats that date back to before we
// had a proper browserified buffer type. they may be removed later
var arrayBuffPrefix = 'ArrayBuffer:';
var arrayBuffRegex = new RegExp('^' + arrayBuffPrefix);
var uintPrefix = 'Uint8Array:';
var uintRegex = new RegExp('^' + uintPrefix);

// this is the new encoding format used going forward
var bufferPrefix = 'Buff:';
var bufferRegex = new RegExp('^' + bufferPrefix);

var utils = require('./utils');
var LocalStorageCore = require('./localstorage-core');
var TaskQueue = require('./taskqueue');
var d64 = require('d64');

function LocalStorage(dbname) {
  this._store = new LocalStorageCore(dbname);
  this._queue = new TaskQueue();
}

LocalStorage.prototype.sequentialize = function (callback, fun) {
  this._queue.add(fun, callback);
};

LocalStorage.prototype.init = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    self._store.getKeys(function (err, keys) {
      if (err) {
        return callback(err);
      }
      self._keys = keys;
      return callback();
    });
  });
};

LocalStorage.prototype.keys = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    self._store.getKeys(function (err, keys) {
      callback(null, keys.slice());
    });
  });
};

//setItem: Saves and item at the key provided.
LocalStorage.prototype.setItem = function (key, value, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    if (Buffer.isBuffer(value)) {
      value = bufferPrefix + d64.encode(value);
    }

    var idx = utils.sortedIndexOf(self._keys, key);
    if (self._keys[idx] !== key) {
      self._keys.splice(idx, 0, key);
    }
    self._store.put(key, value, callback);
  });
};

//getItem: Returns the item identified by it's key.
LocalStorage.prototype.getItem = function (key, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    self._store.get(key, function (err, retval) {
      if (err) {
        return callback(err);
      }
      if (typeof retval === 'undefined' || retval === null) {
        // 'NotFound' error, consistent with LevelDOWN API
        return callback(new Error('NotFound'));
      }
      if (typeof retval !== 'undefined') {
        if (bufferRegex.test(retval)) {
          retval = d64.decode(retval.substring(bufferPrefix.length));
        } else if (arrayBuffRegex.test(retval)) {
          // this type is kept for backwards
          // compatibility with older databases, but may be removed
          // after a major version bump
          retval = retval.substring(arrayBuffPrefix.length);
          retval = new ArrayBuffer(atob(retval).split('').map(function (c) {
            return c.charCodeAt(0);
          }));
        } else if (uintRegex.test(retval)) {
          // ditto
          retval = retval.substring(uintPrefix.length);
          retval = new Uint8Array(atob(retval).split('').map(function (c) {
            return c.charCodeAt(0);
          }));
        }
      }
      callback(null, retval);
    });
  });
};

//removeItem: Removes the item identified by it's key.
LocalStorage.prototype.removeItem = function (key, callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    var idx = utils.sortedIndexOf(self._keys, key);
    if (self._keys[idx] === key) {
      self._keys.splice(idx, 1);
      self._store.remove(key, function (err) {
        if (err) {
          return callback(err);
        }
        callback();
      });
    } else {
      callback();
    }
  });
};

LocalStorage.prototype.length = function (callback) {
  var self = this;
  self.sequentialize(callback, function (callback) {
    callback(null, self._keys.length);
  });
};

exports.LocalStorage = LocalStorage;
<|endoftext|>