<commit_before>const config = require('../config.json');
const types = require('./types');
var _ = require('lodash');

const DataType = types.DataType;
const SheetType = types.SheetType;

function parseJsonObject(data) {
  var evil = eval;
  return evil("(" + data + ")");
}

// class StringBuffer {
//   constructor(str) {
//     this._str_ = [];
//     if (str) {
//       this.append(str);
//     }
//   }

//   toString() {
//     return this._str_.join("");
//   }

//   append(str) {
//     this._str_.push(str);
//   }
// }

/**
 * 解析workbook中所有sheet的设置
 * @param {*} workbook
 */
function parseSettings(workbook) {

  /**
   * settings's schema
   * {
      type: SheetType.NORMAL,
      head: [{
          name: "json-key(column name)",
          type: "number/string/bool/data/id/[]/{}",
        }]
      ,
      slaves: [],
      master: {
        name: '',
        type: DataType.OBJECT
      },
    }
   */

  let settings = {};

  workbook.forEach(sheet => {

    //叹号开头的sheet不输出
    if (sheet.name.startsWith('!')) {
      return;
    }

    let slave = sheet.name.indexOf('@') >= 0;
    let sheet_name = sheet.name;

    let sheet_setting = {
      type: SheetType.NORMAL,
      master: null,
      slaves: [],
      head: []
    };

    if (slave) {
      sheet_setting.type = SheetType.SLAVE;
      let pair = sheet_name.split('@');
      sheet_name = pair[0].trim();
      sheet_setting.master = pair[1].trim();
      settings[sheet_setting.master].slaves.push(sheet_name);
    }

    let head_row = sheet.data[config.xlsx.head - 1];

    //parsing head setting
    head_row.forEach(cell => {

      let head_setting = {
        name: cell,
        type: DataType.UNKNOWN,
      };

      if (cell.indexOf('#') !== -1) {
        let pair = cell.split('#');
        let name = pair[0].trim();
        let type = pair[1].trim();

        head_setting.name = name;
        head_setting.type = type;

        if (!slave && type === DataType.ID) {
          sheet_setting.type = SheetType.MASTER;
        }
      }
      sheet_setting.head.push(head_setting);
    });

    settings[sheet_name] = sheet_setting;
  });

  return settings;
}

/**
 * 解析一个表(sheet)
 *
 * @param sheet 表的原始数据
 * @param setting 表的设置
 * @return Array or Object
 */
function parseSheet(sheet, setting) {

  let headIndex = config.xlsx.head;
  let result = [];

  console.log('  * sheet:', sheet.name);

  if (setting.type === SheetType.MASTER) {
    result = {};
  }

  for (let i_row = headIndex; i_row < sheet.data.length; i_row++) {

    let row = sheet.data[i_row];

    let parsed_row = parseRow(row, i_row, setting.head);

    if (setting.type === SheetType.MASTER) {

      let id_cell = _.find(setting.head, item => {
        return item.type === DataType.ID || item.type === DataType.IDS;
      });

      if (!id_cell) {
        throw `在表${sheet.name}中获取不到id列`;
      }

      result[parsed_row[id_cell.name]] = parsed_row;

    } else {
      result.push(parsed_row);
    }
  }

  return result;
}

/**
 * 解析一行
 * @param {*} row
 * @param {*} rowIndex
 * @param {*} head
 */
function parseRow(row, rowIndex, head) {

  let result = {};
  let id;

  for (let index = 0; index < head.length; index++) {
    let cell = row[index];

    let name = head[index].name;
    let type = head[index].type;

    if (name.startsWith('!')) {
      continue;
    }

    if (cell === null || cell === undefined) {
      result[name] = null;
      continue;
    }

    switch (type) {
      case DataType.ID:
        id = cell + '';
        result[name] = id;
        break;
      case DataType.IDS:
        id = cell + '';
        result[name] = id;
        break;
      case DataType.UNKNOWN: // number string boolean
        if (isNumber(cell)) {
          result[name] = Number(cell);
        } else if (isBoolean(cell)) {
          result[name] = toBoolean(cell);
        } else {
          result[name] = cell;
        }
        break;
      case DataType.DATE:
        if (isNumber(cell)) {
          //xlsx's bug!!!
          result[name] = numdate(cell);
        } else {
          result[name] = cell.toString();
        }
        break;
      case DataType.STRING:
        if (cell.toString().startsWith('"')) {
          result[name] = parseJsonObject(cell);
        } else {
          result[name] = cell.toString();
        }
        break;
      case DataType.NUMBER:
        //+xxx.toString() '+' means convert it to number
        if (isNumber(cell)) {
          result[name] = Number(cell);
        } else {
          console.warn("type error at [" + rowIndex + "," + index + "]," + cell + " is not a number");
        }
        break;
      case DataType.BOOL:
        result[name] = toBoolean(cell);
        break;
      case DataType.OBJECT:
        result[name] = parseJsonObject(cell);
        break;
      case DataType.ARRAY:
        if (!cell.toString().startsWith('[')) {
          cell = `[${cell}]`;
        }
        result[name] = parseJsonObject(cell);
        break;
      default:
        console.log('无法识别的类型:', '[' + rowIndex + ',' + index + ']', cell, typeof (cell));
        break;
    }
  }

  return result;
}

/**
 * convert value to boolean.
 */
function toBoolean(value) {
  return value.toString().toLowerCase() === 'true';
}

/**
 * is a number.
 */
function isNumber(value) {

  if (typeof value === 'number') {
    return true;
  }

  if (value) {
    return !isNaN(+value.toString());
  }

  return false;
}

/**
 * boolean type check.
 */
function isBoolean(value) {

  if (typeof (value) === "undefined") {
    return false;
  }

  if (typeof value === 'boolean') {
    return true;
  }

  let b = value.toString().trim().toLowerCase();

  return b === 'true' || b === 'false';
}

//fuck node-xlsx's bug
var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
// var dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
var dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
// function datenum(v, date1904) {
// 	var epoch = v.getTime();
// 	if(date1904) epoch -= 1462*24*60*60*1000;
// 	return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
// }

function numdate(v) {
  var out = new Date();
  out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  return out;
}
//fuck over

module.exports = {

  parseSettings: parseSettings,

  parseWorkbook: function (workbook, settings) {

    // console.log('settings >>>>>', JSON.stringify(settings, null, 2));

    let parsed_workbook = {};

    workbook.forEach(sheet => {

      if (sheet.name.startsWith('!')) {
        return;
      }

      let sheet_name = sheet.name;

      let isSlave = sheet_name.indexOf('@') >= 0;

      if (isSlave) {
        sheet_name = sheet_name.split('@')[0].trim();
      }

      let sheet_setting = settings[sheet_name];

      let parsed_sheet = parseSheet(sheet, sheet_setting);

      parsed_workbook[sheet_name] = parsed_sheet;

    });

    for (let name in settings) {
      if (settings[name].type === SheetType.MASTER) {

        let master_sheet = parsed_workbook[name];

        settings[name].slaves.forEach(slave_name => {

          let slave_setting = settings[slave_name];
          let slave_sheet = parsed_workbook[slave_name];

          let key_cell = _.find(slave_setting.head, item => {
            return item.type === DataType.ID || item.type === DataType.IDS;
          });

          //slave 表中所有数据
          slave_sheet.forEach(row => {
            let id = row[key_cell.name];
            delete row[key_cell.name];
            if (key_cell.type === DataType.IDS) { //array
              master_sheet[id][slave_name] = master_sheet[id][slave_name] || [];
              master_sheet[id][slave_name].push(row);
            } else { //hash
              master_sheet[id][slave_name] = row;
            }
          });

          delete parsed_workbook[slave_name];
        });
      }
    }

    return parsed_workbook;
  }
};<commit_msg>[fix]:error occurs  when head name is not string type<commit_after>const config = require('../config.json');
const types = require('./types');
var _ = require('lodash');

const DataType = types.DataType;
const SheetType = types.SheetType;

function parseJsonObject(data) {
  var evil = eval;
  return evil("(" + data + ")");
}

// class StringBuffer {
//   constructor(str) {
//     this._str_ = [];
//     if (str) {
//       this.append(str);
//     }
//   }

//   toString() {
//     return this._str_.join("");
//   }

//   append(str) {
//     this._str_.push(str);
//   }
// }

/**
 * 解析workbook中所有sheet的设置
 * @param {*} workbook
 */
function parseSettings(workbook) {

  /**
   * settings's schema
   * {
      type: SheetType.NORMAL,
      head: [{
          name: "json-key(column name)",
          type: "number/string/bool/data/id/[]/{}",
        }]
      ,
      slaves: [],
      master: {
        name: '',
        type: DataType.OBJECT
      },
    }
   */

  let settings = {};

  workbook.forEach(sheet => {

    //叹号开头的sheet不输出
    if (sheet.name.startsWith('!')) {
      return;
    }

    let slave = sheet.name.indexOf('@') >= 0;
    let sheet_name = sheet.name;

    let sheet_setting = {
      type: SheetType.NORMAL,
      master: null,
      slaves: [],
      head: []
    };

    if (slave) {
      sheet_setting.type = SheetType.SLAVE;
      let pair = sheet_name.split('@');
      sheet_name = pair[0].trim();
      sheet_setting.master = pair[1].trim();
      settings[sheet_setting.master].slaves.push(sheet_name);
    }

    let head_row = sheet.data[config.xlsx.head - 1];

    //parsing head setting
    head_row.forEach(cell => {

      cell = cell.toString();

      let head_setting = {
        name: cell,
        type: DataType.UNKNOWN,
      };

      if (cell.indexOf('#') !== -1) {
        let pair = cell.split('#');
        let name = pair[0].trim();
        let type = pair[1].trim();

        head_setting.name = name;
        head_setting.type = type;

        if (!slave && type === DataType.ID) {
          sheet_setting.type = SheetType.MASTER;
        }
      }
      sheet_setting.head.push(head_setting);
    });

    settings[sheet_name] = sheet_setting;
  });

  return settings;
}

/**
 * 解析一个表(sheet)
 *
 * @param sheet 表的原始数据
 * @param setting 表的设置
 * @return Array or Object
 */
function parseSheet(sheet, setting) {

  let headIndex = config.xlsx.head;
  let result = [];

  console.log('  * sheet:', sheet.name);

  if (setting.type === SheetType.MASTER) {
    result = {};
  }

  for (let i_row = headIndex; i_row < sheet.data.length; i_row++) {

    let row = sheet.data[i_row];

    let parsed_row = parseRow(row, i_row, setting.head);

    if (setting.type === SheetType.MASTER) {

      let id_cell = _.find(setting.head, item => {
        return item.type === DataType.ID || item.type === DataType.IDS;
      });

      if (!id_cell) {
        throw `在表${sheet.name}中获取不到id列`;
      }

      result[parsed_row[id_cell.name]] = parsed_row;

    } else {
      result.push(parsed_row);
    }
  }

  return result;
}

/**
 * 解析一行
 * @param {*} row
 * @param {*} rowIndex
 * @param {*} head
 */
function parseRow(row, rowIndex, head) {

  let result = {};
  let id;

  for (let index = 0; index < head.length; index++) {
    let cell = row[index];

    let name = head[index].name;
    let type = head[index].type;

    if (name.startsWith('!')) {
      continue;
    }

    if (cell === null || cell === undefined) {
      result[name] = null;
      continue;
    }

    switch (type) {
      case DataType.ID:
        id = cell + '';
        result[name] = id;
        break;
      case DataType.IDS:
        id = cell + '';
        result[name] = id;
        break;
      case DataType.UNKNOWN: // number string boolean
        if (isNumber(cell)) {
          result[name] = Number(cell);
        } else if (isBoolean(cell)) {
          result[name] = toBoolean(cell);
        } else {
          result[name] = cell;
        }
        break;
      case DataType.DATE:
        if (isNumber(cell)) {
          //xlsx's bug!!!
          result[name] = numdate(cell);
        } else {
          result[name] = cell.toString();
        }
        break;
      case DataType.STRING:
        if (cell.toString().startsWith('"')) {
          result[name] = parseJsonObject(cell);
        } else {
          result[name] = cell.toString();
        }
        break;
      case DataType.NUMBER:
        //+xxx.toString() '+' means convert it to number
        if (isNumber(cell)) {
          result[name] = Number(cell);
        } else {
          console.warn("type error at [" + rowIndex + "," + index + "]," + cell + " is not a number");
        }
        break;
      case DataType.BOOL:
        result[name] = toBoolean(cell);
        break;
      case DataType.OBJECT:
        result[name] = parseJsonObject(cell);
        break;
      case DataType.ARRAY:
        if (!cell.toString().startsWith('[')) {
          cell = `[${cell}]`;
        }
        result[name] = parseJsonObject(cell);
        break;
      default:
        console.log('无法识别的类型:', '[' + rowIndex + ',' + index + ']', cell, typeof (cell));
        break;
    }
  }

  return result;
}

/**
 * convert value to boolean.
 */
function toBoolean(value) {
  return value.toString().toLowerCase() === 'true';
}

/**
 * is a number.
 */
function isNumber(value) {

  if (typeof value === 'number') {
    return true;
  }

  if (value) {
    return !isNaN(+value.toString());
  }

  return false;
}

/**
 * boolean type check.
 */
function isBoolean(value) {

  if (typeof (value) === "undefined") {
    return false;
  }

  if (typeof value === 'boolean') {
    return true;
  }

  let b = value.toString().trim().toLowerCase();

  return b === 'true' || b === 'false';
}

//fuck node-xlsx's bug
var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
// var dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
var dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
// function datenum(v, date1904) {
// 	var epoch = v.getTime();
// 	if(date1904) epoch -= 1462*24*60*60*1000;
// 	return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
// }

function numdate(v) {
  var out = new Date();
  out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  return out;
}
//fuck over

module.exports = {

  parseSettings: parseSettings,

  parseWorkbook: function (workbook, settings) {

    // console.log('settings >>>>>', JSON.stringify(settings, null, 2));

    let parsed_workbook = {};

    workbook.forEach(sheet => {

      if (sheet.name.startsWith('!')) {
        return;
      }

      let sheet_name = sheet.name;

      let isSlave = sheet_name.indexOf('@') >= 0;

      if (isSlave) {
        sheet_name = sheet_name.split('@')[0].trim();
      }

      let sheet_setting = settings[sheet_name];

      let parsed_sheet = parseSheet(sheet, sheet_setting);

      parsed_workbook[sheet_name] = parsed_sheet;

    });

    for (let name in settings) {
      if (settings[name].type === SheetType.MASTER) {

        let master_sheet = parsed_workbook[name];

        settings[name].slaves.forEach(slave_name => {

          let slave_setting = settings[slave_name];
          let slave_sheet = parsed_workbook[slave_name];

          let key_cell = _.find(slave_setting.head, item => {
            return item.type === DataType.ID || item.type === DataType.IDS;
          });

          //slave 表中所有数据
          slave_sheet.forEach(row => {
            let id = row[key_cell.name];
            delete row[key_cell.name];
            if (key_cell.type === DataType.IDS) { //array
              master_sheet[id][slave_name] = master_sheet[id][slave_name] || [];
              master_sheet[id][slave_name].push(row);
            } else { //hash
              master_sheet[id][slave_name] = row;
            }
          });

          delete parsed_workbook[slave_name];
        });
      }
    }

    return parsed_workbook;
  }
};<|endoftext|>


<commit_before>'use strict';

var CHAR = Object.freeze({
    ASSIGNMENT: '=',
    BRACE_OPEN: '{',
    BRACE_CLOSE: '}',
    BRACKET_OPEN: '[',
    BRACKET_CLOSE: ']',
    COLON: ':',
    COMMA: ',',
    EMPTY: '',
    EQUALITY: '===',
    NEWLINE: '\n',
    QUESTION: '?',
    QUOTE: '\'',
    SEMICOLON: ';',
    SPACE: ' ',
    TAB: '    ',
    UNDERSCORE: '_'
});

var EXPRESSION = Object.freeze({
    ANON_F_OPEN: '(function () {',
    ANON_F_CLOSE: '})()',
    RETURN: 'return',
    UNDEFINED: 'undefined',
    VAR: 'var'
});

var GRAMMAR = Object.freeze({
    COLOR: 'paint',
    COMMENT: '#',
    CREATE_OPEN: 'create',
    CREATE_CLOSE: 'leave',
    FEEDBACK: 'feedback',
    NAME: 'name',
    NOTE: 'note',
    PROGRAM: 'program',
    USAGE: 'usage'
});

var CHILD_COLLECTION = 'children';

var indentLevel;

var pad = function (expression, afterOnly) {
    return (afterOnly ? CHAR.EMPTY : CHAR.SPACE) + expression + CHAR.SPACE;
};

var createIndent = function () {
    var indent = '';

    for (var i = 0; i < indentLevel; i++) {
        indent += CHAR.TAB;
    }

    return indent;
};

var createVesselName = function (keys) {
    keys.shift();

    return keys.join(CHAR.UNDERSCORE);
};

var createPropertyName = function (vessel, property) {
    return vessel + CHAR.UNDERSCORE + property;
};

var createPropertyValue = function (keys) {
    keys.shift();

    return keys.join(' ');
};

var createTernaryStatement = function (cond, tExpression, fExpression) {
    return cond + pad(CHAR.QUESTION) + tExpression + pad(CHAR.COLON) + fExpression;
};

var createUndefinedCheck = function (variable, tExpression, fExpression) {
    return createTernaryStatement('typeof ' + variable + pad(CHAR.EQUALITY) + CHAR.QUOTE + EXPRESSION.UNDEFINED + CHAR.QUOTE, tExpression, fExpression);
};

var parentVessel;

var getParentVessel = function () {
    return parentVessel[parentVessel.length - 1];
};

var currentVessel;
var children;

var Parser = function () {
    this.parse = function (line) {
        line = line.replace(/[^A-Z0-9#\,\.\s]/gi, '');

        var keys = line.match(/'[^']+'|\S+/g);
        var statement = '';

        if (keys === null) {
            return line + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.COMMENT) {
            return CHAR.EMPTY;
        }

        if (keys[0] === GRAMMAR.CREATE_OPEN) {
            var vesselName = createVesselName(keys);

            if (currentVessel) {
                parentVessel.push(currentVessel);
            }

            currentVessel = vesselName;

            if (getParentVessel()) {
                if (typeof children[getParentVessel()] === EXPRESSION.UNDEFINED) {
                    children[getParentVessel()] = [];
                }

                children[getParentVessel()].push(currentVessel);
            }

            if (indentLevel === 0) {
                statement += createIndent() + EXPRESSION.ANON_F_OPEN + CHAR.NEWLINE;
            } else {
                statement += createIndent() + pad(EXPRESSION.VAR, true) + vesselName + pad(CHAR.ASSIGNMENT) + EXPRESSION.ANON_F_OPEN + CHAR.NEWLINE;
            }

            indentLevel++;

            statement += createIndent() + pad(EXPRESSION.VAR, true) + createPropertyName(currentVessel, GRAMMAR.NAME) + pad(CHAR.ASSIGNMENT) + CHAR.QUOTE + vesselName + CHAR.QUOTE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.CREATE_CLOSE) {

            statement += createIndent() + pad(EXPRESSION.RETURN, true) + CHAR.BRACE_OPEN + CHAR.NEWLINE;

            indentLevel++;

            var properties = [GRAMMAR.NAME, GRAMMAR.NOTE, GRAMMAR.PROGRAM, GRAMMAR.USAGE];

            for (var i in properties) {
                statement += createIndent() + properties[i] + pad(CHAR.COLON, true) + createUndefinedCheck(createPropertyName(currentVessel, properties[i]), CHAR.QUOTE + CHAR.QUOTE, currentVessel + CHAR.UNDERSCORE + properties[i]) + CHAR.COMMA + CHAR.NEWLINE;
            }

            statement += createIndent() + CHILD_COLLECTION + pad(CHAR.COLON, true) + CHAR.BRACKET_OPEN + CHAR.NEWLINE;

            indentLevel++;

            for (var i in children[currentVessel]) {
                statement += createIndent() + children[currentVessel][i] + CHAR.COMMA + CHAR.NEWLINE;
            }

            currentVessel = parentVessel.pop();

            indentLevel--;

            statement += createIndent() + CHAR.BRACKET_CLOSE + CHAR.NEWLINE

            indentLevel--;

            statement += createIndent() + CHAR.BRACE_CLOSE + CHAR.SEMICOLON + CHAR.NEWLINE;

            indentLevel--;

            statement += createIndent() + EXPRESSION.ANON_F_CLOSE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.FEEDBACK || keys[0] === GRAMMAR.NOTE || keys[0] === GRAMMAR.PROGRAM || keys[0] === GRAMMAR.USAGE) {
            var propertyName = keys[0];
            var propertyValue = createPropertyValue(keys);

            statement += createIndent() + pad(EXPRESSION.VAR, true) + createPropertyName(currentVessel, propertyName) + pad(CHAR.ASSIGNMENT) + CHAR.QUOTE + propertyValue + CHAR.QUOTE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        return statement;
    };

    this.reset = function () {
        indentLevel = 0;
        parentVessel = [];
        currentVessel = null;
        children = {};
    };

    this.reset();
};

module.exports = Parser;
<commit_msg>Only return vessel property if it exists<commit_after>'use strict';

var CHAR = Object.freeze({
    ASSIGNMENT: '=',
    BRACE_OPEN: '{',
    BRACE_CLOSE: '}',
    BRACKET_OPEN: '[',
    BRACKET_CLOSE: ']',
    COLON: ':',
    COMMA: ',',
    EMPTY: '',
    EQUALITY: '===',
    NEWLINE: '\n',
    QUESTION: '?',
    QUOTE: '\'',
    SEMICOLON: ';',
    SPACE: ' ',
    TAB: '    ',
    UNDERSCORE: '_'
});

var EXPRESSION = Object.freeze({
    ANON_F_OPEN: '(function () {',
    ANON_F_CLOSE: '})()',
    RETURN: 'return',
    UNDEFINED: 'undefined',
    VAR: 'var'
});

var GRAMMAR = Object.freeze({
    COLOR: 'paint',
    COMMENT: '#',
    CREATE_OPEN: 'create',
    CREATE_CLOSE: 'leave',
    FEEDBACK: 'feedback',
    NAME: 'name',
    NOTE: 'note',
    PROGRAM: 'program',
    USAGE: 'usage'
});

var PROPERTIES = [GRAMMAR.FEEDBACK, GRAMMAR.NAME, GRAMMAR.NOTE, GRAMMAR.PROGRAM, GRAMMAR.USAGE];

var CHILD_COLLECTION = 'children';

var indentLevel;

var pad = function (expression, afterOnly) {
    return (afterOnly ? CHAR.EMPTY : CHAR.SPACE) + expression + CHAR.SPACE;
};

var createIndent = function () {
    var indent = '';

    for (var i = 0; i < indentLevel; i++) {
        indent += CHAR.TAB;
    }

    return indent;
};

var createVesselName = function (keys) {
    keys.shift();

    return keys.join(CHAR.UNDERSCORE);
};

var createPropertyName = function (vessel, property) {
    return vessel + CHAR.UNDERSCORE + property;
};

var createPropertyValue = function (keys) {
    keys.shift();

    return keys.join(' ');
};

var parentVessel;

var getParentVessel = function () {
    return parentVessel[parentVessel.length - 1];
};

var currentVessel;
var has;
var children;

var Parser = function () {
    this.parse = function (line) {
        line = line.replace(/[^A-Z0-9#\,\.\s]/gi, '');

        var keys = line.match(/'[^']+'|\S+/g);
        var statement = '';

        if (keys === null) {
            return line + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.COMMENT) {
            return CHAR.EMPTY;
        }

        if (keys[0] === GRAMMAR.CREATE_OPEN) {
            var vesselName = createVesselName(keys);

            if (currentVessel) {
                parentVessel.push(currentVessel);
            }

            currentVessel = vesselName;

            if (!has[currentVessel]) {
                has[currentVessel] = {};
            }

            has[currentVessel].name = true;

            if (getParentVessel()) {
                if (typeof children[getParentVessel()] === EXPRESSION.UNDEFINED) {
                    children[getParentVessel()] = [];
                }

                children[getParentVessel()].push(currentVessel);
            }

            if (indentLevel === 0) {
                statement += createIndent() + EXPRESSION.ANON_F_OPEN + CHAR.NEWLINE;
            } else {
                statement += createIndent() + pad(EXPRESSION.VAR, true) + vesselName + pad(CHAR.ASSIGNMENT) + EXPRESSION.ANON_F_OPEN + CHAR.NEWLINE;
            }

            indentLevel++;

            statement += createIndent() + pad(EXPRESSION.VAR, true) + createPropertyName(currentVessel, GRAMMAR.NAME) + pad(CHAR.ASSIGNMENT) + CHAR.QUOTE + vesselName + CHAR.QUOTE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.CREATE_CLOSE) {

            statement += createIndent() + pad(EXPRESSION.RETURN, true) + CHAR.BRACE_OPEN + CHAR.NEWLINE;

            indentLevel++;

            for (var i in PROPERTIES) {
                if (has[currentVessel] && has[currentVessel][PROPERTIES[i]]) {
                    statement += createIndent() + PROPERTIES[i] + pad(CHAR.COLON, true) + currentVessel + CHAR.UNDERSCORE + PROPERTIES[i] + CHAR.COMMA + CHAR.NEWLINE;
                }
            }

            statement += createIndent() + CHILD_COLLECTION + pad(CHAR.COLON, true) + CHAR.BRACKET_OPEN + CHAR.NEWLINE;

            indentLevel++;

            for (var i in children[currentVessel]) {
                statement += createIndent() + children[currentVessel][i] + CHAR.COMMA + CHAR.NEWLINE;
            }

            currentVessel = parentVessel.pop();

            indentLevel--;

            statement += createIndent() + CHAR.BRACKET_CLOSE + CHAR.NEWLINE

            indentLevel--;

            statement += createIndent() + CHAR.BRACE_CLOSE + CHAR.SEMICOLON + CHAR.NEWLINE;

            indentLevel--;

            statement += createIndent() + EXPRESSION.ANON_F_CLOSE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        if (keys[0] === GRAMMAR.FEEDBACK || keys[0] === GRAMMAR.NOTE || keys[0] === GRAMMAR.PROGRAM || keys[0] === GRAMMAR.USAGE) {
            var propertyName = keys[0];
            var propertyValue = createPropertyValue(keys);

            has[currentVessel][propertyName] = true;

            statement += createIndent() + pad(EXPRESSION.VAR, true) + createPropertyName(currentVessel, propertyName) + pad(CHAR.ASSIGNMENT) + CHAR.QUOTE + propertyValue + CHAR.QUOTE + CHAR.SEMICOLON + CHAR.NEWLINE;
        }

        return statement;
    };

    this.reset = function () {
        indentLevel = 0;
        parentVessel = [];
        currentVessel = null;
        has = {};
        children = {};
    };

    this.reset();
};

module.exports = Parser;
<|endoftext|>


<commit_before>var esprima = require('esprima'),
    astIterator = require('./ast-iterator');

function addBlockCommentsToAst(ast) {
    var commentNodes = ast.comments.filter(function(commentNode) {
            return commentNode.type === 'Block';
        }),
        i = 0,
        commentNode = commentNodes[i];

    if(!commentNode) {
        return;
    }

    astIterator(ast, function(node) {
        if(node.range) {
            if(node.range[0] >= commentNode.range[1]) {
                node.comments = commentNode;
                if(!(commentNode = commentNodes[++i])) {
                    return false;
                }
            }
        }
    });
}

module.exports = function(string) {
    var ast = esprima.parse(string, { comment : true, range : true });
    addBlockCommentsToAst(ast);
    ast.iterate = function(cb, acc) {
        astIterator(
            ast,
            function(astNode, acc) {
                return astNode.comments?
                    cb(astNode, acc) :
                    acc;
            },
            acc);
    };
    return ast;
};
<commit_msg>parse only truly jsdoc comments<commit_after>var esprima = require('esprima'),
    astIterator = require('./ast-iterator');

function addJsDocCommentsToAst(ast) {
    var commentNodes = ast.comments.filter(function(commentNode) {
            return commentNode.type === 'Block' && commentNode.value[0] === '*';
        }),
        i = 0,
        commentNode = commentNodes[i];

    if(!commentNode) {
        return;
    }

    delete ast.comments;

    astIterator(ast, function(node) {
        if(node.range) {
            if(node.range[0] >= commentNode.range[1]) {
                node.comments = commentNode;
                if(!(commentNode = commentNodes[++i])) {
                    return false;
                }
            }
        }
    });
}

module.exports = function(string) {
    var ast = esprima.parse(string, { comment : true, range : true });
    addJsDocCommentsToAst(ast);
    ast.iterate = function(cb, acc) {
        astIterator(
            ast,
            function(astNode, acc) {
                return astNode.comments?
                    cb(astNode, acc) :
                    acc;
            },
            acc);
    };
    return ast;
};
<|endoftext|>


<commit_before>/*
  Parser
  Parses clean source. Generates clean AST.
*/

// Utility functions

const mayBe = (value, func) => value === null ? null : func(...value)

// Predifined regexes

const idRegex = /^([a-zA-Z]+[a-zA-Z0-9_]*)((.|\n)*)$/
const numRegex = /^([\-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[e][+\-]?\d+)?)((.|\n)*)$/
// const nullRegEx       = /^null\b/i
// const booleanRegEx    = /^(true|false)\b/i
// var stringRegEx     = /^('|').*?[^\\]\1/

/*
  Parser factory. Used to create parsers
  parser.regex - creates parser for given regex
  parser.bind - applies monadic bind on parsers
  parser.all - All parsers supplied MUST match
  parser.any - ANY ONE of the parsers need match
*/

const parser = {}

parser.regex = regex => src => mayBe(
  regex.exec(src),
  (m, val, rest) => [val, rest]
)

parser.bind = (mv, mf) => str => mayBe(
  mv(str),
  (val, rest) => mf(val)(rest)
)

parser.all = (...parsers) => src => {
  var rest = src
  var values = []
  for (let parser of parsers) {
    let result = parser(rest)
    if (result === null) return null
    values.push(result[0])
    rest = result[1]
  }
  return [values, rest]
}

parser.any = (...parsers) => src => {
  for (let parser of parsers) {
    let result = parser(src)
    if (result !== null) return result
  }
  return null
}

/*
  All required parsers are created below
*/

const spaceParser = parser.regex(/^(\s+)((.|\n)*)$/)

const equalSignParser = parser.regex(/^(\s+=\s+)((.|\n)*)$/)

const numberParser = str => mayBe(
  numRegex.exec(str),
  (a, num, rest) => [{type: 'Literal', value: Number(num), raw: num}, rest]
)

const identifierParser = str => mayBe(
  idRegex.exec(str),
  (a, name, rest) => [{type: 'Identifier', name: name}, rest]
)

const expressionParser = parser.any(numberParser)

const declParser = parser.bind(
  parser.bind(
    identifierParser,
    val => str => mayBe(
      equalSignParser(str),
      (v, rest) => [val, rest]
    )
  ),
  val => str => mayBe(
    expressionParser(str),
    (v, rest) => [{type: 'VariableDeclaration',
                   kind: 'const',
                   declarations: [{id: val, init: v}]}, rest]
  )
)

module.exports = function (src) {
  const ast = {type: 'Program', body: []}
  // const [space, rest] = spaceParser(src)
  // console.log(rest)
  const result = declParser(src)
  console.log(result)
  if (result !== null) ast.body.push(result[0])
  return ast
}
<commit_msg>Add boolean Parser<commit_after>/*
  Parser
  Parses clean source. Generates clean AST.
*/

// Utility functions

const mayBe = (value, func) => value === null ? null : func(...value)

// Predifined regexes

const idRegex = /^([a-zA-Z]+[a-zA-Z0-9_]*)((.|\n)*)$/
const numRegex = /^([\-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[e][+\-]?\d+)?)((.|\n)*)$/
// const nullRegEx       = /^null\b/i
const boolRegex = /^(true|false)(.|\n)*$/i
// var stringRegEx     = /^('|').*?[^\\]\1/

/*
  Parser factory. Used to create parsers
  parser.regex - creates parser for given regex
  parser.bind - applies monadic bind on parsers
  parser.all - All parsers supplied MUST match
  parser.any - ANY ONE of the parsers need match
*/

const parser = {}

parser.regex = regex => src => mayBe(
  regex.exec(src),
  (m, val, rest) => [val, rest]
)

parser.bind = (mv, mf) => str => mayBe(
  mv(str),
  (val, rest) => mf(val)(rest)
)

parser.all = (...parsers) => src => {
  var rest = src
  var values = []
  for (let parser of parsers) {
    let result = parser(rest)
    if (result === null) return null
    values.push(result[0])
    rest = result[1]
  }
  return [values, rest]
}

parser.any = (...parsers) => src => {
  for (let parser of parsers) {
    let result = parser(src)
    if (result !== null) return result
  }
  return null
}

/*
  All required parsers are created below
*/

const spaceParser = parser.regex(/^(\s+)((.|\n)*)$/)

const equalSignParser = parser.regex(/^(\s+=\s+)((.|\n)*)$/)

const numberParser = str => mayBe(
  numRegex.exec(str),
  (a, num, rest) => [{type: 'Literal', value: Number(num), raw: num}, rest]
)

const identifierParser = str => mayBe(
  idRegex.exec(str),
  (a, name, rest) => [{type: 'Identifier', name: name}, rest]
)

const booleanParser = str => mayBe(
  boolRegex.exec(str),
  (a, bool, rest) => [{type: 'Literal', value: bool}, rest]
)

const expressionParser = parser.any(numberParser)

const declParser = parser.bind(
  parser.bind(
    identifierParser,
    val => str => mayBe(
      equalSignParser(str),
      (v, rest) => [val, rest]
    )
  ),
  val => str => mayBe(
    expressionParser(str),
    (v, rest) => [{type: 'VariableDeclaration',
                   kind: 'const',
                   declarations: [{id: val, init: v}]}, rest]
  )
)

module.exports = function (src) {
  const ast = {type: 'Program', body: []}
  // const [space, rest] = spaceParser(src)
  // console.log(rest)
  const result =  declParser(src)
  console.log(result)
  if (result !== null) ast.body.push(result[0])
  return ast
}
<|endoftext|>


<commit_before>define(['require'],function(require) {

  var app = angular.module('Leaf',['ui.router','ngSanitize','angular-gravatar']);

  app.config(['$urlMatcherFactoryProvider','$controllerProvider','$compileProvider','$filterProvider','$provide','$stateProvider','$urlRouterProvider','$locationProvider',function($urlMatcherFactoryProvider,$controllerProvider,$compileProvider,$filterProvider,$provide,$stateProvider,$urlRouterProvider,$locationProvider) {

    $urlMatcherFactoryProvider.strictMode(false);

    app.register = {
        controller : $controllerProvider.register,
        directive : $compileProvider.directive,
        filter : $filterProvider.register,
        factory : $provide.factory,
        service : $provide.service
    };

    var modulesUrl = 'app/components/';

    $stateProvider

    .state('login',{
      url : '/login',
      templateUrl : modulesUrl + 'login/login.html',
      title : 'Login',
      controller : 'loginController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'login/login'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('dashboard',{
      url : '/dashboard',
      templateUrl : modulesUrl + 'dashboard/dashboard.html',
      title : 'Dashboard',
      data : {active : 'dashboard'},
      controller : 'dashboardController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'dashboard/dashboard'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('new-post',{
      url : '/editor',
      templateUrl : modulesUrl + 'posts/editor.html',
      title : 'Editor',
      data : {active : 'editor',nosearch : true},
      controller : 'editorController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/editor'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('edit-post',{
      url : '/editor/:id',
      templateUrl : modulesUrl + 'posts/editor.html',
      title : 'Editor',
      data : {active : 'editor',nosearch : true},
      controller : 'editorController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/editor'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('users',{
      url : '/users',
      templateUrl : modulesUrl + 'users/users.html',
      title : 'Team',
      data : {active : 'users'},
      controller : 'usersController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'users/users'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('user',{
      url : '/user/:user',
      templateUrl : modulesUrl + 'users/user.html',
      title : 'Team',
      data : {active : 'users'},
      controller : 'userController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'users/user'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('posts',{
      url : '/posts',
      templateUrl : modulesUrl + 'posts/posts.html',
      title : 'Posts',
      data : {active : 'posts'},
      controller : 'postsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/posts'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('comments',{
      url : '/comments',
      templateUrl : modulesUrl + 'comments/comments.html',
      title : 'Comments',
      data : {active : 'comments'},
      controller : 'commentsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'comments/comments'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('media',{
      url : '/media',
      templateUrl : modulesUrl + 'media/media.html',
      title : 'Media',
      data : {active : 'media'},
      controller : 'mediaController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'media/media'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('tags',{
      url : '/tags',
      templateUrl : modulesUrl + 'tags/tags.html',
      title : 'Tags',
      data : {active : 'tags'},
      controller : 'tagsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'tags/tags'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('shares',{
      url : '/shares',
      templateUrl : modulesUrl + 'shares/shares.html',
      title : 'Sharing',
      data : {active : 'shares',nosearch : true},
      controller : 'sharesController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'shares/shares'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('navigation',{
      url : '/navigation',
      templateUrl : modulesUrl + 'navigation/navigation.html',
      title : 'Navigation',
      data : {active : 'navigation',nosearch : true},
      controller : 'navigationController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'navigation/navigation'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('themes',{url : '/themes',
      templateUrl : modulesUrl + 'themes/themes.html',
      title : 'Themes',
      data : {active : 'themes'},
      controller : 'themesController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'themes/themes'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('settings-general',{
      url : '/settings/general',
      templateUrl : modulesUrl + 'settings/general.html',
      title : 'General settings',
      data : {active : 'settings-general',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('settings-contents',{
      url : '/settings/contents',
      templateUrl : modulesUrl + 'settings/contents.html',
      title : 'Contents settings',
      data : {active : 'settings-contents',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    .state('settings-users',{
      url : '/settings/users',
      templateUrl : modulesUrl + 'settings/users.html',
      title : 'Users settings',
      data : {active : 'settings-users',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    });

    $urlRouterProvider.otherwise('/dashboard');

    $locationProvider.hashPrefix('').html5Mode(true);

  }]);

  app.run(['$rootScope','$state',function($rootScope,$state) {

    // Admin menu.
    $rootScope.adminMenu = [
      {
        id : 'general',
        title : '',
        items : [
          {id : 'dashboard',title : 'Dashboard',url : 'dashboard',icon : 'pulse',roles : []},
          {id : 'editor',title : 'Editor',url : 'editor',icon : 'feather',roles : []},
          {id : 'users',title : 'Team',url : 'users',icon : 'users',roles : []}
        ]
      },
      {
        id : 'contents',
        title : 'Contents',
        items : [
          {id : 'posts',title : 'Posts',url : 'posts',icon : 'copy',roles : []},
          {id : 'comments',title : 'Comments',url : 'comments',icon : 'chatbubble',roles : []},
          {id : 'media',title : 'Media',url : 'media',icon : 'image',roles : []}
        ]
      },
      {
        id : 'personalize',
        title : 'Personalize',
        items : [
          {id : 'tags',title : 'Tags',url : 'tags',icon : 'tags',roles : []},
          {id : 'navigation',title : 'Navigation',url : 'navigation',icon : 'compass',roles : []},
          {id : 'shares',title : 'Sharing',url : 'shares',icon : 'marketing',roles : []},
          {id : 'themes',title : 'Themes',url : 'themes',icon : 'brush',roles : []}
        ]
      },
      {
        id : 'settings',
        title : 'Settings',
        items : [
          {id : 'settings-general',title : 'General',url : 'settings/general',icon : 'gear',roles : []},
          {id : 'settings-contents',title : 'Contents',url : 'settings/contents',icon : 'folder',roles : []},
          {id : 'settings-users',title : 'Users',url : 'settings/users',icon : 'user',roles : []}
        ]
      }
    ];

    // Map $state in the $rootScope.
    $rootScope.$state = $state;

    // Check if an item in the admin menu is active.
    $rootScope.isActivePage = function(id) {
      return $state.current.data.active===id;
    };

    // Check if the search input is disabled.
    $rootScope.isSearchDisabled = function() {
      return $state.current.data.nosearch || false;
    };

    // Initialize header.
    $rootScope.initHeader = function() {

      $(window).on('resize',function() {
        $('#header').css('left',($(window).width()>991)? '0' : '-310px');
      });

      $('.nav-bar').css('overflow','hidden');

      $('.nav-bar').on('mouseover',function() {
          $(this).css('overflow','auto');
      }).on('mouseout',function() {
          $(this).css('overflow','hidden');
      });

    };

    // Show header.
    $rootScope.showHeader = function() {
      $rootScope.hideSidebar();
      $('#header').animate({'left' : '0'},300);
    };

    // Hide header.
    $rootScope.hideHeader = function() {
      $('#header').animate({'left' : '-310px'},300);
    };

    // Show sidebar.
    $rootScope.showSidebar = function(event) {
      if (event) event.preventDefault();
      $('#sidebar').animate({'right' : '0'},300);
    };

    // Hide sidebar.
    $rootScope.hideSidebar = function(event) {
      if (event) event.preventDefault();
      $('#sidebar').animate({'right' : '-311px'},300);
    };

  }]);

});
<commit_msg>Attivato html5 mode e aggiunte nuove route<commit_after>define(['require'],function(require) {

  var app = angular.module('Leaf',['ui.router','ngSanitize','angular-gravatar']);

  app.config(['$urlMatcherFactoryProvider','$controllerProvider','$compileProvider','$filterProvider','$provide','$stateProvider','$urlRouterProvider','$locationProvider',function($urlMatcherFactoryProvider,$controllerProvider,$compileProvider,$filterProvider,$provide,$stateProvider,$urlRouterProvider,$locationProvider) {

    $urlMatcherFactoryProvider.strictMode(false);

    app.register = {
        controller : $controllerProvider.register,
        directive : $compileProvider.directive,
        filter : $filterProvider.register,
        factory : $provide.factory,
        service : $provide.service
    };

    var modulesUrl = 'app/components/';

    $stateProvider

    // Setup.
    .state('setup',{
      url : '/setup',
      templateUrl : modulesUrl + 'setup/setup.html',
      title : 'Setup',
      controller : 'setupController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'setup/setup'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Login.
    .state('login',{
      url : '/login',
      templateUrl : modulesUrl + 'login/login.html',
      title : 'Login',
      controller : 'loginController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'login/login'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Sign up.
    .state('signup',{
      url : '/signup/:token',
      templateUrl : modulesUrl + 'login/signup.html',
      title : 'Sign up',
      controller : 'signupController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'login/signup'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Lost password.
    .state('lostpassword',{
      url : '/lost-password',
      templateUrl : modulesUrl + 'login/lost-password.html',
      title : 'Lost password',
      controller : 'lostpasswordController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'login/lost-password'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Dashboard.
    .state('dashboard',{
      url : '/dashboard',
      templateUrl : modulesUrl + 'dashboard/dashboard.html',
      title : 'Dashboard',
      data : {active : 'dashboard'},
      controller : 'dashboardController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'dashboard/dashboard'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Editor (new post/page).
    .state('new-post',{
      url : '/editor',
      templateUrl : modulesUrl + 'posts/editor.html',
      title : 'Editor',
      data : {active : 'editor',nosearch : true},
      controller : 'editorController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/editor'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Editor (edit post/page).
    .state('edit-post',{
      url : '/editor/:id',
      templateUrl : modulesUrl + 'posts/editor.html',
      title : 'Editor',
      data : {active : 'editor',nosearch : true},
      controller : 'editorController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/editor'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Team.
    .state('users',{
      url : '/users',
      templateUrl : modulesUrl + 'users/users.html',
      title : 'Team',
      data : {active : 'users'},
      controller : 'usersController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'users/users'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // User profile.
    .state('user',{
      url : '/user/:user',
      templateUrl : modulesUrl + 'users/user.html',
      title : 'Team',
      data : {active : 'users'},
      controller : 'userController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'users/user'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Posts and pages.
    .state('posts',{
      url : '/posts',
      templateUrl : modulesUrl + 'posts/posts.html',
      title : 'Posts',
      data : {active : 'posts'},
      controller : 'postsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'posts/posts'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Comments.
    .state('comments',{
      url : '/comments',
      templateUrl : modulesUrl + 'comments/comments.html',
      title : 'Comments',
      data : {active : 'comments'},
      controller : 'commentsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'comments/comments'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Media.
    .state('media',{
      url : '/media',
      templateUrl : modulesUrl + 'media/media.html',
      title : 'Media',
      data : {active : 'media'},
      controller : 'mediaController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'media/media'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Tags.
    .state('tags',{
      url : '/tags',
      templateUrl : modulesUrl + 'tags/tags.html',
      title : 'Tags',
      data : {active : 'tags'},
      controller : 'tagsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'tags/tags'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Sharing.
    .state('shares',{
      url : '/shares',
      templateUrl : modulesUrl + 'shares/shares.html',
      title : 'Sharing',
      data : {active : 'shares',nosearch : true},
      controller : 'sharesController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'shares/shares'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Navigation menu.
    .state('navigation',{
      url : '/navigation',
      templateUrl : modulesUrl + 'navigation/navigation.html',
      title : 'Navigation',
      data : {active : 'navigation',nosearch : true},
      controller : 'navigationController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'navigation/navigation'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Themes.
    .state('themes',{url : '/themes',
      templateUrl : modulesUrl + 'themes/themes.html',
      title : 'Themes',
      data : {active : 'themes'},
      controller : 'themesController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'themes/themes'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // General settings.
    .state('settings-general',{
      url : '/settings/general',
      templateUrl : modulesUrl + 'settings/general.html',
      title : 'General settings',
      data : {active : 'settings-general',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Contents settings.
    .state('settings-contents',{
      url : '/settings/contents',
      templateUrl : modulesUrl + 'settings/contents.html',
      title : 'Contents settings',
      data : {active : 'settings-contents',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    })

    // Users settings.
    .state('settings-users',{
      url : '/settings/users',
      templateUrl : modulesUrl + 'settings/users.html',
      title : 'Users settings',
      data : {active : 'settings-users',nosearch : true},
      controller : 'settingsController',
      resolve : {
        deps : ['$q',function($q) {
          var q = $q.defer();
          require(['../../' + modulesUrl + 'settings/settings'],function() {
            q.resolve();
          });
          return q.promise;
        }]
      },
      cache : false
    });

    $urlRouterProvider.otherwise('/dashboard');

    $locationProvider.hashPrefix('').html5Mode(true);

  }]);

  app.run(['$rootScope','$state',function($rootScope,$state) {

    // Admin menu.
    $rootScope.adminMenu = [
      {
        id : 'general',
        title : '',
        items : [
          {id : 'dashboard',title : 'Dashboard',url : 'dashboard',icon : 'pulse',roles : []},
          {id : 'editor',title : 'Editor',url : 'editor',icon : 'feather',roles : []},
          {id : 'users',title : 'Team',url : 'users',icon : 'users',roles : []}
        ]
      },
      {
        id : 'contents',
        title : 'Contents',
        items : [
          {id : 'posts',title : 'Posts',url : 'posts',icon : 'copy',roles : []},
          {id : 'comments',title : 'Comments',url : 'comments',icon : 'chatbubble',roles : []},
          {id : 'media',title : 'Media',url : 'media',icon : 'image',roles : []}
        ]
      },
      {
        id : 'personalize',
        title : 'Personalize',
        items : [
          {id : 'tags',title : 'Tags',url : 'tags',icon : 'tags',roles : []},
          {id : 'navigation',title : 'Navigation',url : 'navigation',icon : 'compass',roles : []},
          {id : 'shares',title : 'Sharing',url : 'shares',icon : 'marketing',roles : []},
          {id : 'themes',title : 'Themes',url : 'themes',icon : 'brush',roles : []}
        ]
      },
      {
        id : 'settings',
        title : 'Settings',
        items : [
          {id : 'settings-general',title : 'General',url : 'settings/general',icon : 'gear',roles : []},
          {id : 'settings-contents',title : 'Contents',url : 'settings/contents',icon : 'folder',roles : []},
          {id : 'settings-users',title : 'Users',url : 'settings/users',icon : 'user',roles : []}
        ]
      }
    ];

    // Map $state in the $rootScope.
    $rootScope.$state = $state;

    // Check if an item in the admin menu is active.
    $rootScope.isActivePage = function(id) {
      return $state.current.data.active===id;
    };

    // Check if the search input is disabled.
    $rootScope.isSearchDisabled = function() {
      return $state.current.data.nosearch || false;
    };

    // Initialize header.
    $rootScope.initHeader = function() {

      $(window).on('resize',function() {
        $('#header').css('left',($(window).width()>991)? '0' : '-310px');
      });

      $('.nav-bar').css('overflow','hidden');

      $('.nav-bar').on('mouseover',function() {
          $(this).css('overflow','auto');
      }).on('mouseout',function() {
          $(this).css('overflow','hidden');
      });

    };

    // Show header.
    $rootScope.showHeader = function() {
      $rootScope.hideSidebar();
      $('#header').animate({'left' : '0'},300);
    };

    // Hide header.
    $rootScope.hideHeader = function() {
      $('#header').animate({'left' : '-310px'},300);
    };

    // Show sidebar.
    $rootScope.showSidebar = function(event) {
      if (event) event.preventDefault();
      $('#sidebar').animate({'right' : '0'},300);
    };

    // Hide sidebar.
    $rootScope.hideSidebar = function(event) {
      if (event) event.preventDefault();
      $('#sidebar').animate({'right' : '-311px'},300);
    };

  }]);

});
<|endoftext|>


<commit_before>var _Dvbtee = require('bindings')('dvbtee.node')
var util    = require('util')
var stream  = require('stream')

var Parser = function (options) {

  var self = this

  if (!(this instanceof Parser)) {
    return new Parser(options)
  }

  self.options = {}

  if (typeof options === 'object') {
    self.options.passThru = (options.hasOwnProperty('passThru') && options.passThru)
    self.options.enableEtt = (options.hasOwnProperty('enableEtt') && options.enableEtt)
  } else {
    self.options.passThru = false
    self.options.enableEtt = false
  }

  var _parser       = new _Dvbtee.Parser

  var _reset        = _Dvbtee.Parser.prototype.reset
  self.reset        = _reset.bind(_parser)

  if (self.options.enableEtt) {
    var _enableEttCollection = _Dvbtee.Parser.prototype.enableEttCollection
    var enableEttCollection  = _enableEttCollection.bind(_parser)

    enableEttCollection()
  }

  stream.Transform.call(this, {
    objectMode: !self.options.passThru
  })

  self._buffer = new Buffer(0)

  var _feed         = _Dvbtee.Parser.prototype.feed
  var feed          = _feed.bind(_parser)

  var feed_progress = (self.options.passThru) ?
    function(a, b, c) {
      self.emit('psip', c)
    } : function(a, b, c) {
      self.push(c)
    }

  self.feed = function(b, blen, cb) {
    return feed(b, blen, feed_progress, cb)
  }
}

util.inherits(Parser, stream.Transform)

Parser.prototype._transform = function (chunk, encoding, done) {

  var self = this

  var checkCache = function (cb) {
    if (self._buffer.length + chunk.length < 188) {
      try {
        self._buffer = Buffer.concat([ self._buffer, chunk ])
        done()
      } catch (err) {
        done(err)
      }
    } else {
      cb()
    }
  }

  var feedCache = function (cb) {

    if (self._buffer.length > 0) {
      try {
        var b = Buffer.concat(
          [ self._buffer, chunk.slice(0, 188 - self._buffer.length) ], 188)
        self.feed(b, b.length, function (err) {
          chunk = chunk.slice(188 - self._buffer.length)
          cb(err)
        })
        if (self.options.passThru) {
          self.push(b)
        }
      } catch (err) {
        cb(err)
      }
    } else {
      cb()
    }
  }

  var feedChunk = function (cb) {

    try {
      var next = 188 * Math.floor(chunk.length / 188)
      var b = chunk.slice(0, next)

      self.feed(b, b.length, function (err) {
        self._buffer = chunk.slice(next)
        cb(err)
      })
      if (self.options.passThru) {
        self.push(b)
      }
    } catch (err) {
      cb(err)
    }
  }

  checkCache(function () {
    feedCache(function (err) {
      if (err) {
        done(err)
      } else {
        feedChunk(done)
      }
    })
  })
}

Parser.prototype._flush = function (done) {

  var self = this

  // don't bother sending partial packets to the TS Parser- they'll just get dropped
  if ((self.options.passThru) && (self._buffer.length > 0)) {
    self.push(self._buffer)
    self._buffer = new Buffer(0)
  }
  done()
}

module.exports = Parser
<commit_msg>lib/parser.js: move feed binding up to decrease the delta<commit_after>var _Dvbtee = require('bindings')('dvbtee.node')
var util    = require('util')
var stream  = require('stream')

var Parser = function (options) {

  var self = this

  if (!(this instanceof Parser)) {
    return new Parser(options)
  }

  self.options = {}

  if (typeof options === 'object') {
    self.options.passThru = (options.hasOwnProperty('passThru') && options.passThru)
    self.options.enableEtt = (options.hasOwnProperty('enableEtt') && options.enableEtt)
  } else {
    self.options.passThru = false
    self.options.enableEtt = false
  }

  var _parser       = new _Dvbtee.Parser

  var _reset        = _Dvbtee.Parser.prototype.reset
  self.reset        = _reset.bind(_parser)

  var _feed         = _Dvbtee.Parser.prototype.feed
  var feed          = _feed.bind(_parser)

  if (self.options.enableEtt) {
    var _enableEttCollection = _Dvbtee.Parser.prototype.enableEttCollection
    var enableEttCollection  = _enableEttCollection.bind(_parser)

    enableEttCollection()
  }

  stream.Transform.call(this, {
    objectMode: !self.options.passThru
  })

  self._buffer = new Buffer(0)

  var feed_progress = (self.options.passThru) ?
    function(a, b, c) {
      self.emit('psip', c)
    } : function(a, b, c) {
      self.push(c)
    }

  self.feed = function(b, blen, cb) {
    return feed(b, blen, feed_progress, cb)
  }
}

util.inherits(Parser, stream.Transform)

Parser.prototype._transform = function (chunk, encoding, done) {

  var self = this

  var checkCache = function (cb) {
    if (self._buffer.length + chunk.length < 188) {
      try {
        self._buffer = Buffer.concat([ self._buffer, chunk ])
        done()
      } catch (err) {
        done(err)
      }
    } else {
      cb()
    }
  }

  var feedCache = function (cb) {

    if (self._buffer.length > 0) {
      try {
        var b = Buffer.concat(
          [ self._buffer, chunk.slice(0, 188 - self._buffer.length) ], 188)
        self.feed(b, b.length, function (err) {
          chunk = chunk.slice(188 - self._buffer.length)
          cb(err)
        })
        if (self.options.passThru) {
          self.push(b)
        }
      } catch (err) {
        cb(err)
      }
    } else {
      cb()
    }
  }

  var feedChunk = function (cb) {

    try {
      var next = 188 * Math.floor(chunk.length / 188)
      var b = chunk.slice(0, next)

      self.feed(b, b.length, function (err) {
        self._buffer = chunk.slice(next)
        cb(err)
      })
      if (self.options.passThru) {
        self.push(b)
      }
    } catch (err) {
      cb(err)
    }
  }

  checkCache(function () {
    feedCache(function (err) {
      if (err) {
        done(err)
      } else {
        feedChunk(done)
      }
    })
  })
}

Parser.prototype._flush = function (done) {

  var self = this

  // don't bother sending partial packets to the TS Parser- they'll just get dropped
  if ((self.options.passThru) && (self._buffer.length > 0)) {
    self.push(self._buffer)
    self._buffer = new Buffer(0)
  }
  done()
}

module.exports = Parser
<|endoftext|>


<commit_before>class Character {
    constructor() {
        this._name = '';
        this._xp = 0;
        this._race = null;
        this._classes = [];
    }

    addClass(characterClass) {
        this._classes.push(characterClass);
    }
}

export default Character<commit_msg>structure<commit_after>class Character {
    constructor() {
        this._name = '';
        this._xp = 0;
        this._race = null;
        this._classes = [];
    }

    get level() {

    }

    addClass(characterClass) {
        this._classes.push(characterClass);
    }
}

export default Character<|endoftext|>


<commit_before>var _;
if (window._) {
    _ = window._;
} else {
    Array.prototype.isArray = true;

    _ = {};

    function extend(target, source) {
        target = target || {};
        for (var prop in source) {
            if(source.hasOwnProperty(prop)) {
                if (typeof source[prop] === 'object') {
                    target[prop] = extend(target[prop], source[prop]);
                } else {
                    target[prop] = source[prop];
                }
            }
        }
        return target;
    }

    _.extend = extend;

    _.isString = function (val) {
        return typeof val === 'string';
    };

    _.isBoolean = function (val) {
        return typeof val === 'boolean';
    };

    _.isNumber = function (val) {
        return typeof val === 'number';
    };

    _.isArray = function (val) {
        return !!val.isArray;
    };

    _.isEmpty = function (val) {
        if (_.isString(val)) {
            return val === '';
        }

        if (_.isArray(val)) {
            return val.length === 0;
        }

        if (_.isObject(val)) {
            for (var e in val) {
                return false;
            }
            return true;
        }

        return false;
    };

    _.isUndefined = function (val) {
        return typeof val === 'undefined';
    };

    _.isFunction = function (val) {
        return typeof val === 'function';
    };

    _.isObject = function (val) {
        return typeof val === 'object';
    };
}<commit_msg>Added schema Date type to internal _.js<commit_after>var _;
if (window._) {
    _ = window._;
} else {
    Array.prototype.isArray = true;

    _ = {};

    function extend(target, source) {
        target = target || {};
        for (var prop in source) {
            if(source.hasOwnProperty(prop)) {
                if (typeof source[prop] === 'object') {
                    target[prop] = extend(target[prop], source[prop]);
                } else {
                    target[prop] = source[prop];
                }
            }
        }
        return target;
    }

    _.extend = extend;

    _.isString = function (val) {
        return typeof val === 'string';
    };

    _.isBoolean = function (val) {
        return typeof val === 'boolean';
    };

    _.isNumber = function (val) {
        return typeof val === 'number';
    };

    _.isDate = function (val) {
        return val instanceof Date && !isNaN(val.valueOf());
    };

    _.isArray = function (val) {
        return !!val.isArray;
    };

    _.isEmpty = function (val) {
        if (_.isString(val)) {
            return val === '';
        }

        if (_.isArray(val)) {
            return val.length === 0;
        }

        if (_.isObject(val)) {
            for (var e in val) {
                return false;
            }
            return true;
        }

        return false;
    };

    _.isUndefined = function (val) {
        return typeof val === 'undefined';
    };

    _.isFunction = function (val) {
        return typeof val === 'function';
    };

    _.isObject = function (val) {
        return typeof val === 'object';
    };
}<|endoftext|>


<commit_before>import * as SDFText from './sdftext';
import Props from './props';
import viewer from './viewer';

const [leftController, rightController] = viewer.controllers;

const textCreator = SDFText.creator();

const rhand = Props.controller.clone();
const lhand = Props.controller.clone();
const rText = textCreator.create('');
const lText = textCreator.create('');
rhand.add(rText);
lhand.add(lText);

let leftPress;
let rightPress;

leftController.addEventListener('thumbpaddown', () => {
  if (leftPress) leftPress();
});

rightController.addEventListener('thumbpaddown', () => {
  if (rightPress) rightPress();
});

export default {
  update({ left, right } = {}) {
    if (left) {
      lText.updateLabel(left.text);
      leftPress = () => {
        if (left.removeOnPress) {
          lText.updateLabel('');
          leftPress = null;
        }
        left.onPress();
      };
    } else {
      lText.updateLabel('');
      leftPress = null;
    }

    if (right) {
      rText.updateLabel(right.text);
      rightPress = () => {
        if (right.removeOnPress) {
          rText.updateLabel('');
          rightPress = null;
        }
        right.onPress();
      };
    } else {
      rText.updateLabel('');
      rightPress = null;
    }
  },

  add() {
    leftController.add(lhand);
    rightController.add(rhand);
  },

  remove() {
    rightPress = leftPress = null;
    leftController.remove(lhand);
    rightController.remove(rhand);
  },
};
<commit_msg>only call onPress if it exists<commit_after>import * as SDFText from './sdftext';
import Props from './props';
import viewer from './viewer';

const [leftController, rightController] = viewer.controllers;

const textCreator = SDFText.creator();

const rhand = Props.controller.clone();
const lhand = Props.controller.clone();
const rText = textCreator.create('');
const lText = textCreator.create('');
rhand.add(rText);
lhand.add(lText);

let leftPress;
let rightPress;

leftController.addEventListener('thumbpaddown', () => {
  if (leftPress) leftPress();
});

rightController.addEventListener('thumbpaddown', () => {
  if (rightPress) rightPress();
});

export default {
  update({ left, right } = {}) {
    if (left) {
      lText.updateLabel(left.text);
      leftPress = () => {
        if (left.removeOnPress) {
          lText.updateLabel('');
          leftPress = null;
        }
        if (left.onPress) {
          left.onPress();
        }
      };
    } else {
      lText.updateLabel('');
      leftPress = null;
    }

    if (right) {
      rText.updateLabel(right.text);
      rightPress = () => {
        if (right.removeOnPress) {
          rText.updateLabel('');
          rightPress = null;
        }
        if (right.onPress) {
          right.onPress();
        }
      };
    } else {
      rText.updateLabel('');
      rightPress = null;
    }
  },

  add() {
    leftController.add(lhand);
    rightController.add(rhand);
  },

  remove() {
    rightPress = leftPress = null;
    leftController.remove(lhand);
    rightController.remove(rhand);
  },
};
<|endoftext|>


<commit_before>var IPHistoryUI = (function(){
    "use strict";

    var tableID = "login-history-table",
        columns = ["timestamp","action","browser","ip","status"];

    function createEmptyTable(){
        var header = [
            text.localize("Date and Time"),
            text.localize("Action"),
            text.localize("Browser"),
            text.localize("IP Location"),
            text.localize("Status"),
        ];
        var metadata = {
            id: tableID,
            cols: columns
        };
        var data = [];
        var $table = Table.createFlexTable(data,metadata,header);
        return $table;
    }

    function updateTable(history){
        Table.appendTableBody(tableID, history, createRow);
    }

    function createRow(data){
        var userAgent = data['environment'];
        var history = userAgent.split(' ');
        var timestamp = history[0];
        var ip = history[2].split('=')[1];
        var browser = "Unknown";
        var verOffset, ver;
        if ((verOffset = userAgent.indexOf("OPR")) != -1){
            browser = "Opera";
            ver = userAgent.substring(verOffset+4).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Chrome")) != -1){
            browser = "Chrome";
            ver = userAgent.substring(verOffset+7).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Safari")) != -1){
            browser = "Safari";
            ver = userAgent.substring(verOffset+7).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Firefox")) != -1){
            browser = "Firefox";
            ver = userAgent.substring(verOffset+8).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("MSIE")) != -1){
            browser = "Internet Explorer";
            ver = userAgent.substring(verOffset+5).split(" ")[0];
        }
        var status = data['status'] === 1 ? text.localize('Successful') : text.localize('Failed');
        var browserString = browser + " v" + ver;
        var $row = Table.createFlexTableRow([timestamp, data['action'], browserString, ip, status], columns, "data");
        $row.children(".timestamp").first().append('
' + history[1]);
        return $row[0];
    }

    function clearTableContent(){
        Table.clearTableBody(tableID);
        $("#" + tableID +">tfoot").hide();
    }

    return{
        createEmptyTable: createEmptyTable,
        updateTable: updateTable,
        clearTableContent: clearTableContent
    };
}());
<commit_msg>change to IP address<commit_after>var IPHistoryUI = (function(){
    "use strict";

    var tableID = "login-history-table",
        columns = ["timestamp","action","browser","ip","status"];

    function createEmptyTable(){
        var header = [
            text.localize("Date and Time"),
            text.localize("Action"),
            text.localize("Browser"),
            text.localize("IP Address"),
            text.localize("Status"),
        ];
        var metadata = {
            id: tableID,
            cols: columns
        };
        var data = [];
        var $table = Table.createFlexTable(data,metadata,header);
        return $table;
    }

    function updateTable(history){
        Table.appendTableBody(tableID, history, createRow);
    }

    function createRow(data){
        var userAgent = data['environment'];
        var history = userAgent.split(' ');
        var timestamp = history[0];
        var ip = history[2].split('=')[1];
        var browser = "Unknown";
        var verOffset, ver;
        if ((verOffset = userAgent.indexOf("OPR")) != -1){
            browser = "Opera";
            ver = userAgent.substring(verOffset+4).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Chrome")) != -1){
            browser = "Chrome";
            ver = userAgent.substring(verOffset+7).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Safari")) != -1){
            browser = "Safari";
            ver = userAgent.substring(verOffset+7).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("Firefox")) != -1){
            browser = "Firefox";
            ver = userAgent.substring(verOffset+8).split(" ")[0];
        } else if ((verOffset = userAgent.indexOf("MSIE")) != -1){
            browser = "Internet Explorer";
            ver = userAgent.substring(verOffset+5).split(" ")[0];
        }
        var status = data['status'] === 1 ? text.localize('Successful') : text.localize('Failed');
        var browserString = browser + " v" + ver;
        var $row = Table.createFlexTableRow([timestamp, data['action'], browserString, ip, status], columns, "data");
        $row.children(".timestamp").first().append('
' + history[1]);
        return $row[0];
    }

    function clearTableContent(){
        Table.clearTableBody(tableID);
        $("#" + tableID +">tfoot").hide();
    }

    return{
        createEmptyTable: createEmptyTable,
        updateTable: updateTable,
        clearTableContent: clearTableContent
    };
}());
<|endoftext|>


<commit_before>function isSecured(operation) {
  if (_.has(this.schema.secured, operation)) {
    return this.schema.secured[operation];
  }
  else {
    return this.schema.secured.common || false;
  }
};

export default isSecured;<commit_msg>Fix lack of loads import<commit_after>import _ from 'lodash';

function isSecured(operation) {
  if (_.has(this.schema.secured, operation)) {
    return this.schema.secured[operation];
  }
  else {
    return this.schema.secured.common || false;
  }
};

export default isSecured;<|endoftext|>


<commit_before>window.cls || (window.cls = {});
cls.EcmascriptDebugger || (cls.EcmascriptDebugger = {});
cls.EcmascriptDebugger["5.0"] || (cls.EcmascriptDebugger["5.0"] = {});
cls.EcmascriptDebugger["6.0"] || (cls.EcmascriptDebugger["6.0"] = {});

/**
  * @constructor
  */

cls.EcmascriptDebugger["6.0"].DOMBaseData =
cls.EcmascriptDebugger["5.0"].DOMBaseData = new function()
{

  const
  NODE_LIST = 0,
  ID = 0,
  TYPE = 1,
  NAME = 2,
  DEPTH = 3,

  ATTRS = 5,
  ATTR_PREFIX = 0,
  ATTR_KEY = 1,
  ATTR_VALUE = 2,
  CHILDREN_LENGTH = 6,
  PUBLIC_ID = 4,
  SYSTEM_ID = 5;

  this._set_mime = function()
  {
    for (var node = null, i = 0; node = this._data[i]; i++)
    {
      if (node[TYPE] == 1 )
      {
        // TODO take in account doctype if present
        return /^[A-Z]*$/.test(node[NAME]) && "text/html" || "application/xml";
      }
    }
  };

  this.isTextHtml = function()
  {
    return this._data.length && this._mime == "text/html" || false;
  };

  // workaround for bug CORE-16147
  this.getDoctypeName = function()
  {
    for (var node = null, i = 0; node = this._data[i]; i++)
    {
      if (node[TYPE] == 1)
        return node[NAME];
    }
    return null;
  }

  this.expand = function(cb, object_id, traverse_type)
  {
    this._get_dom(object_id, traverse_type || "children", cb);
  }

  this._get_dom = function(object_id, traverse_type, cb)
  {
    var tag = window.tag_manager.set_callback(this, this.__handle_dom, [object_id, traverse_type, cb]);
    services['ecmascript-debugger'].requestInspectDom(tag, [object_id, traverse_type]);
  };

  this.__handle_dom = function(status, message, object_id, traverse_type, cb)
  {
    var
    _data = message[NODE_LIST],
    error_ms = ui_strings.DRAGONFLY_INFO_MESSAGE + 'this.__handle_dom failed in DOMBaseData',
    splice_args = null,
    i = 0;

    if (!status)
    {
      switch (traverse_type)
      {
        // traverse_type 'node' so far not supported
        case "parent-node-chain-with-children":
        {
          this._data = _data;
          break;
        }
        case "subtree":
        case "children":
        {
          for (; this._data[i] && this._data[i][ID] != object_id; i++);
          if (this._data[i])
          {
            // if object_id matches the one of the first node
            // of the return data the traversal was subtree
            splice_args = object_id == _data[0][ID] ? [i, 1] : [i + 1, 0];
            Array.prototype.splice.apply(this._data, splice_args.concat(_data));
          }
          else if (!this._data.length)
            this._data = _data;
          else
            opera.postError(error_ms);
          break;
        }
      }
      this._mime = this._set_mime();
      if (cb)
        cb();
    }
    else
      opera.postError(error_ms);
  };

  this.collapse = function(object_id)
  {
    var i = 0, j = 0, level = 0;
    for (; this._data[i] && this._data[i][ID] != object_id; i++ );
    if (this._data[i])
    {
      level = this._data[i][DEPTH];
      i += 1;
      j = i;
      while (this._data[j] && this._data[j][DEPTH] > level)
        j++;
      this._data.splice(i, j - i);
    }
    else
    {
      opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                      'missing refrence in collapse_node in DOMBaseData');
    }
  };

  this._get_element_name = function(data_entry, force_lower_case, with_ids_and_classes)
  {
    var name = data_entry[NAME], attrs = data_entry[ATTRS], id = '', class_name = '';
    if (force_lower_case)
      name = name.toLowerCase();
    if (with_ids_and_classes)
    {
      for (var attr, i = 0; attr = attrs[i]; i++)
      {
        if (attr[ATTR_KEY] == 'id')
          id = "#" + attr[ATTR_VALUE];
        if (attr[ATTR_KEY] == 'class')
          class_name = "." + attr[ATTR_VALUE].replace(/ /g, ".");
      }
    }
    return name + id + class_name;
  }

  this._parse_parent_offset = function(chain)
  {
    var ret = false, cur = null;
    if (chain)
    {
      cur = chain.pop();
      if (cur)
        ret = cur[1] == '1';
      else
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                        "failed in this._parse_parent_offset in dom_data");
    }
    return ret;
  }

  this._get_css_path = function(object_id, parent_offset_chain,
                                force_lower_case, show_id_and_classes, show_siblings)
  {
    var i = 0, j = 0, path = [];
    if (object_id)
    {
      for ( ; this._data[i] && this._data[i][ID] != object_id; i++);
      if (this._data[i])
      {
        path.push({
          name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
          id: this._data[i][ID],
          combinator: "",
          is_parent_offset: this._parse_parent_offset(parent_offset_chain)
        });
        j = i;
        i--;
        for (  ; this._data[i]; i--)
        {
          if(this._data[i][TYPE] == 1)
          {
            if(this._data[i][DEPTH] <= this._data[j][DEPTH])
            {
              if (this._data[i][DEPTH] < this._data[j][DEPTH])
                path.push({
                  name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
                  id: this._data[i][ID],
                  combinator: ">" ,
                  is_parent_offset: this._parse_parent_offset(parent_offset_chain)
                });
              else if (show_siblings)
                path.push({
                  name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
                  id: this._data[i][ID],
                  combinator: "+",
                  is_parent_offset: false
                });
              j = i;
            }
          }
        }
      }
    }
    return path.reverse();
  }

  this.has_data = function()
  {
    return Boolean(this._data.length);
  }

  this.getData = function()
  {
    return this._data;
  }

  this.getParentElement = function(obj_id)
  {
    var i = 0, depth = 0;
    for ( ; this._data[i] && this._data[i][ID] != obj_id; i++);
    if (this._data[i])
    {
      depth = this._data[i][DEPTH];
      for ( ; this._data[i] && !((this._data[i][TYPE] == 1 || this._data[i][TYPE] == 9) && this._data[i][DEPTH] < depth); i--);
      return this._data[i] && this._data[i][ID] || 0;
    }
  }

  this.getRootElement = function()
  {
    for (var i = 0; this._data[i] && this._data[i][TYPE] != 1; i++);
    return this._data[i] && this._data[i][ID] || 0;
  }

  this.getDataRuntimeId = function()
  {
    return this._data_runtime_id;
  }

  this._get_id = (function()
  {
    var id_counter = 0;
    return function()
    {
      id_counter++;
      return "dom-inspection-id-" + id_counter.toString();
    };
  })();

  this._init = function(rt_id, obj_id)
  {
    this.id = this._get_id();
    this._data_runtime_id = 0;  // data of a dom tree has always just one runtime
    this._root_obj_id = obj_id;
    this._data = [];
    if (!window.dominspections)
    {
      new cls.Namespace("dominspections");
    }
    window.dominspections.add(this);
  };

};

cls.EcmascriptDebugger["6.0"].InspectableDOMNode = function(rt_id, obj_id)
{
  this._init(rt_id, obj_id);
}

cls.EcmascriptDebugger["6.0"].InspectableDOMNode.prototype = cls.EcmascriptDebugger["6.0"].DOMBaseData;
<commit_msg>Added support for traverse type 'node' (to update a node).<commit_after>window.cls || (window.cls = {});
cls.EcmascriptDebugger || (cls.EcmascriptDebugger = {});
cls.EcmascriptDebugger["5.0"] || (cls.EcmascriptDebugger["5.0"] = {});
cls.EcmascriptDebugger["6.0"] || (cls.EcmascriptDebugger["6.0"] = {});

/**
  * @constructor
  */

cls.EcmascriptDebugger["6.0"].DOMBaseData =
cls.EcmascriptDebugger["5.0"].DOMBaseData = new function()
{

  const
  NODE_LIST = 0,
  ID = 0,
  TYPE = 1,
  NAME = 2,
  DEPTH = 3,

  ATTRS = 5,
  ATTR_PREFIX = 0,
  ATTR_KEY = 1,
  ATTR_VALUE = 2,
  CHILDREN_LENGTH = 6,
  PUBLIC_ID = 4,
  SYSTEM_ID = 5;

  this._set_mime = function()
  {
    for (var node = null, i = 0; node = this._data[i]; i++)
    {
      if (node[TYPE] == 1 )
      {
        // TODO take in account doctype if present
        return /^[A-Z]*$/.test(node[NAME]) && "text/html" || "application/xml";
      }
    }
  };

  this.isTextHtml = function()
  {
    return this._data.length && this._mime == "text/html" || false;
  };

  // workaround for bug CORE-16147
  this.getDoctypeName = function()
  {
    for (var node = null, i = 0; node = this._data[i]; i++)
    {
      if (node[TYPE] == 1)
        return node[NAME];
    }
    return null;
  }

  this.expand = function(cb, object_id, traverse_type)
  {
    this._get_dom(object_id, traverse_type || "children", cb);
  }

  this._get_dom = function(object_id, traverse_type, cb)
  {
    var tag = window.tag_manager.set_callback(this, this.__handle_dom, [object_id, traverse_type, cb]);
    services['ecmascript-debugger'].requestInspectDom(tag, [object_id, traverse_type]);
  };

  this.__handle_dom = function(status, message, object_id, traverse_type, cb)
  {
    var
    _data = message[NODE_LIST],
    error_ms = ui_strings.DRAGONFLY_INFO_MESSAGE + 'this.__handle_dom failed in DOMBaseData',
    splice_args = null,
    i = 0;

    if (!status)
    {
      switch (traverse_type)
      {
        // traverse_type 'node' so far not supported
        case "parent-node-chain-with-children":
        {
          this._data = _data;
          break;
        }
        case "subtree":
        case "children":
        case "node":
        {
          for (; this._data[i] && this._data[i][ID] != object_id; i++);
          if (this._data[i])
          {
            // if object_id matches the one of the first node
            // of the return data the traversal was subtree
            splice_args = object_id == _data[0][ID] ? [i, 1] : [i + 1, 0];
            Array.prototype.splice.apply(this._data, splice_args.concat(_data));
          }
          else if (!this._data.length)
            this._data = _data;
          else
            opera.postError(error_ms);
          break;
        }
      }
      this._mime = this._set_mime();
      if (cb)
        cb();
    }
    else
      opera.postError(error_ms + ' ' + JSON.stringify(message));
  };

  this.collapse = function(object_id)
  {
    var i = 0, j = 0, level = 0;
    for (; this._data[i] && this._data[i][ID] != object_id; i++ );
    if (this._data[i])
    {
      level = this._data[i][DEPTH];
      i += 1;
      j = i;
      while (this._data[j] && this._data[j][DEPTH] > level)
        j++;
      this._data.splice(i, j - i);
    }
    else
    {
      opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                      'missing refrence in collapse_node in DOMBaseData');
    }
  };

  this._get_element_name = function(data_entry, force_lower_case, with_ids_and_classes)
  {
    var name = data_entry[NAME], attrs = data_entry[ATTRS], id = '', class_name = '';
    if (force_lower_case)
      name = name.toLowerCase();
    if (with_ids_and_classes)
    {
      for (var attr, i = 0; attr = attrs[i]; i++)
      {
        if (attr[ATTR_KEY] == 'id')
          id = "#" + attr[ATTR_VALUE];
        if (attr[ATTR_KEY] == 'class')
          class_name = "." + attr[ATTR_VALUE].replace(/ /g, ".");
      }
    }
    return name + id + class_name;
  }

  this._parse_parent_offset = function(chain)
  {
    var ret = false, cur = null;
    if (chain)
    {
      cur = chain.pop();
      if (cur)
        ret = cur[1] == '1';
      else
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
                        "failed in this._parse_parent_offset in dom_data");
    }
    return ret;
  }

  this._get_css_path = function(object_id, parent_offset_chain,
                                force_lower_case, show_id_and_classes, show_siblings)
  {
    var i = 0, j = 0, path = [];
    if (object_id)
    {
      for ( ; this._data[i] && this._data[i][ID] != object_id; i++);
      if (this._data[i])
      {
        path.push({
          name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
          id: this._data[i][ID],
          combinator: "",
          is_parent_offset: this._parse_parent_offset(parent_offset_chain)
        });
        j = i;
        i--;
        for (  ; this._data[i]; i--)
        {
          if(this._data[i][TYPE] == 1)
          {
            if(this._data[i][DEPTH] <= this._data[j][DEPTH])
            {
              if (this._data[i][DEPTH] < this._data[j][DEPTH])
                path.push({
                  name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
                  id: this._data[i][ID],
                  combinator: ">" ,
                  is_parent_offset: this._parse_parent_offset(parent_offset_chain)
                });
              else if (show_siblings)
                path.push({
                  name: this._get_element_name(this._data[i], force_lower_case, show_id_and_classes),
                  id: this._data[i][ID],
                  combinator: "+",
                  is_parent_offset: false
                });
              j = i;
            }
          }
        }
      }
    }
    return path.reverse();
  }

  this.has_data = function()
  {
    return Boolean(this._data.length);
  }

  this.getData = function()
  {
    return this._data;
  }

  this.getParentElement = function(obj_id)
  {
    var i = 0, depth = 0;
    for ( ; this._data[i] && this._data[i][ID] != obj_id; i++);
    if (this._data[i])
    {
      depth = this._data[i][DEPTH];
      for ( ; this._data[i] && !((this._data[i][TYPE] == 1 || this._data[i][TYPE] == 9) && this._data[i][DEPTH] < depth); i--);
      return this._data[i] && this._data[i][ID] || 0;
    }
  }

  this.getRootElement = function()
  {
    for (var i = 0; this._data[i] && this._data[i][TYPE] != 1; i++);
    return this._data[i] && this._data[i][ID] || 0;
  }

  this.getDataRuntimeId = function()
  {
    return this._data_runtime_id;
  }

  this._get_id = (function()
  {
    var id_counter = 0;
    return function()
    {
      id_counter++;
      return "dom-inspection-id-" + id_counter.toString();
    };
  })();

  this._init = function(rt_id, obj_id)
  {
    this.id = this._get_id();
    this._data_runtime_id = 0;  // data of a dom tree has always just one runtime
    this._root_obj_id = obj_id;
    this._data = [];
    if (!window.dominspections)
    {
      new cls.Namespace("dominspections");
    }
    window.dominspections.add(this);
  };

};

cls.EcmascriptDebugger["6.0"].InspectableDOMNode = function(rt_id, obj_id)
{
  this._init(rt_id, obj_id);
}

cls.EcmascriptDebugger["6.0"].InspectableDOMNode.prototype = cls.EcmascriptDebugger["6.0"].DOMBaseData;
<|endoftext|>


<commit_before>var Action = function(one) {
    this.one = one;
};

var p = Action.prototype;

p.on = p.addEventListener = function(type, listener, useCapture) {
    this.one.addEventListener(type, listener, useCapture);
}

p.off = p.removeEventListener = function(type, listener, useCapture) {
    this.one.removeEventListener(type, listener, useCapture);
}

p.afterCreate = function() {};
p.beforeMount = function() {};
p.afterMount = function() {};
p.beforeUnmount = function() {};
p.afterUnmount = function() {};

p.update = function() {};
module.exports = Action;
<commit_msg>Action.getGroup<commit_after>var Action = function(one) {
    this.one = one;
};

var p = Action.prototype;

p.on = p.addEventListener = function(type, listener, useCapture) {
    this.one.addEventListener(type, listener, useCapture);
};

p.off = p.removeEventListener = function(type, listener, useCapture) {
    this.one.removeEventListener(type, listener, useCapture);
};

p.getGroup = function() {
    return this.one.getGroup();
};

p.afterCreate = function() {};
p.beforeMount = function() {};
p.afterMount = function() {};
p.beforeUnmount = function() {};
p.afterUnmount = function() {};

p.update = function() {};
module.exports = Action;
<|endoftext|>


<commit_before>export default class InvocationsController {
  #lambda = null

  constructor(lambda) {
    this.#lambda = lambda
  }

  async invoke(functionName, invocationType, event, clientContext) {
    const lambdaFunction = this.#lambda.getByFunctionName(functionName)

    lambdaFunction.setClientContext(clientContext)
    lambdaFunction.setEvent(event)

    if (invocationType === 'Event') {
      // don't await result!
      lambdaFunction.runHandler().catch((err) => {
        // TODO handle error
        console.log(err)
        throw err
      })

      return {
        Payload: '',
        StatusCode: 202,
      }
    }

    if (invocationType === 'RequestResponse') {
      let result

      try {
        result = await lambdaFunction.runHandler()
      } catch (err) {
        // TODO handle error
        console.log(err)
        throw err
      }

      return result
    }

    // TODO FIXME
    console.log(
      `invocationType: '${invocationType}' not supported by serverless-offline`,
    )

    return undefined
  }
}
<commit_msg>ISSUE-934 Lambda default InvocationType not handled correctly<commit_after>export default class InvocationsController {
  #lambda = null

  constructor(lambda) {
    this.#lambda = lambda
  }

  async invoke(functionName, invocationType, event, clientContext) {
    const lambdaFunction = this.#lambda.getByFunctionName(functionName)

    lambdaFunction.setClientContext(clientContext)
    lambdaFunction.setEvent(event)

    if (invocationType === 'Event') {
      // don't await result!
      lambdaFunction.runHandler().catch((err) => {
        // TODO handle error
        console.log(err)
        throw err
      })

      return {
        Payload: '',
        StatusCode: 202,
      }
    }

    if (!invocationType || invocationType === 'RequestResponse') {
      let result

      try {
        result = await lambdaFunction.runHandler()
      } catch (err) {
        // TODO handle error
        console.log(err)
        throw err
      }

      return result
    }

    // TODO FIXME
    console.log(
      `invocationType: '${invocationType}' not supported by serverless-offline`,
    )

    return undefined
  }
}
<|endoftext|>