<commit_before>const colors = require('colors');
const util = require('util');
const tty = require('tty');
const charm = require('charm')(process);
const cliSpinners = require('cli-spinners');
const cliCursor = require('cli-cursor');

const PADDING = '  ';

var iterations = 0;
var looper = null;
var running = false;
var items = {};
var defaultPattern = null;
var settings = {
  invert: false,
  interval: 250,
  pattern: null,
  bottom: false
};

var isatty = tty.isatty(1) && tty.isatty(2);
var tty_size = {
  width: isatty
    ? process.stdout.getWindowSize
      ? process.stdout.getWindowSize(1)[0]
      : tty.getWindowSize()[1]
    : 75,
  height: isatty
    ? process.stdout.getWindowSize
      ? process.stdout.getWindowSize(1)[1]
      : tty.getWindowSize()[2]
    : 75
};

//
// This is a single item (Or cell or whatever you call it) in the status display
//
var Item = exports.Item = function (options) {
  const defaults = {
    name: null,
    max: null,
    precision: 2
  };
  options = options || {};
  for (var attrname in defaults) {
    this[attrname] = options.hasOwnProperty(attrname) && options[attrname] !== null ? options[attrname] : defaults[attrname];
  }
  if(options.custom) this.custom = options.custom.bind(this);
  this.val = options.count || 0;
};

//
// Item functions for value changes, rendering, etc
//
Item.prototype = {
  inc: function (amount) {
    this.val += (amount !== undefined) ? amount : 1;
  },

  dec: function (amount) {
    this.val -= (amount !== undefined) ? amount : 1;
  },

  render: function (style) {
    switch (style) {
      case 'custom':
        return this.custom ? this.custom() : '';
      case 'percentage':
        if (!this.max) return '';
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        return (100 * this.count / max).toFixed(this.precision) + '%';
        break;
      case 'time':
        return nicetime(this.count);
      case 'bar':
        if (!this.max) return '';
        var bar_len = 10;
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        var done = Math.round(bar_len * this.count / max);
        return '[' + '▒'.repeat(Math.min(bar_len, done)) + '-'.repeat(Math.max(0,bar_len - done)) + ']';
      case 'default':
      case 'count':
      default:
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        return this.count + (max ? '/' + max : '');
    }
  }
};

//
// Getter/setter for count. Auto-rendering, basically.
//
Object.defineProperties(Item.prototype, {
  count: {
    get: function () {
      return this.val;
    },
    set: function (newValue) {
      this.val = newValue;
    }
  }
});

//
// Repeats a string, using it for the status bar instead of loops
//
String.prototype.repeat = function (len) {
  return new Array(len + 1).join(this);
};

//
// Render the status bar row
// If stamp is true, it will console.log it instead of doing an stdout
//
const render = (stamp) => {
  iterations++;
  if (stamp) {
    charm.erase('line').erase('down');
    return console.log(generateBar());
  }
  if (!running) return;

  var color_len = 0;
  for (var i = 0; i < items.length; i++) {
    if (items[i].color) {
      color_len += (items[i].color('')).length;
    }
  }

  var out = ' ' + generateBar();
  var bar = ' '.repeat(tty_size.width);

  if (settings.invert) {
    bar = bar.inverse;
    out = out.inverse;
  }

  var current_height = Math.ceil((out.length - color_len) / tty_size.width );

  charm.position(function (x, y) {
    var current_row = y;

    // If the current cursor row was on the bar, we need to make a gap
    if (settings.bottom && current_row > tty_size.height - current_height) {
      for(var i = 0; i < current_height; i++) {
        // charm.delete('line', 1);
        charm.erase('line');
        write('\n');
      }
      y -= current_height - (tty_size.height - current_row);
    }

    charm
      .move(0, settings.bottom ? tty_size.height : 0)
      .left(tty_size.width)
      .write(bar);

    if(settings.bottom) {
      for(var i = 0; i < Math.max(0, current_height - 1); i++) {
        charm.left(tty_size.width).write(bar).up(1);
      }
    }

    charm
      .left(tty_size.width)
      .write(out)
      .position(x, y);

  });
};

const write = (string) => process.stdout.write(string);

const generateBar = () => {
  var pattern = settings.pattern ? settings.pattern : defaultPattern;
  return pattern.replace(/\{([a-zA-z0-9\s\.]*)\}/g, (match, id) => {
    var tokens = id.split('.');
    var portion = '';
    var color = null;
    var modifier = null;
    if(tokens.length > 1 && colors[tokens[1]]) {
      color = colors[tokens[1]];
      modifier = tokens.length > 2 ? tokens[2] : null;
    } else if (tokens.length > 2 && colors[tokens[2]]) {
      color = colors[tokens[2]];
      modifier = tokens[1];
    } else if(tokens.length > 1) {
      modifier = tokens[1];
    }

    switch (tokens[0]) {
      case 'timestamp':
      case 'uptime':
        portion = nicetime(process.uptime(), true);
        break;
      case 'spinner':
        var spinnerType = modifier || 'dots';
        portion = cliSpinners[spinnerType].frames[iterations % cliSpinners[spinnerType].frames.length];
        break;
      default:
        if(items[tokens[0]]) portion = items[tokens[0]].render(modifier);
        break;
    }
    return color ? color(portion) : portion;
  });
};

//
// Currently just changes the milliseconds to either a number of seconds or number of minutes
//
var nicetime = (ms, use_seconds) => {
  var seconds = (ms / (use_seconds ? 1 : 1000)).toFixed((use_seconds ? 0 : 3));
  var minutes = (seconds / 60).toFixed(3);
  var time = (minutes < 2) ? seconds : minutes;
  return time + (minutes < 2 ?  's' : 'm');
};

process.on('exit', function () {
  if(running) render(true);
});

exports.addItem = (name, options) => {
  if(!name || typeof name !== 'string') return null;
  options = options || {};
  options.name = name;
  var item = new Item(options);
  items[name] = item;
  rebuildPattern();
  return items[name];
};

var rebuildPattern = () => {
  defaultPattern = Object.keys(items).reduce((memo, item) => {
    return `${memo}${PADDING}${item}: {${item}}${PADDING}|`;
  }, `Status @ {uptime}${PADDING}|`);
};

exports.removeItem = (item) => {
  if(typeof item === 'string') {
    delete items[item];
  } else if(item instanceof Item) {
    delete items[item.name];
  }
  rebuildPattern();
}

exports.removeAll = () => {
  items = {};
  rebuildPattern();
}
exports.toString = () => generateBar();
exports.clear = () => charm.erase('line').erase('down');

exports.console = function () {
  var methods = {};
  ['log', 'info', 'error', 'warn'].forEach(m => {
    methods[m] = function () {
      if(m !== 'log' || running) exports.clear();
      console[m].apply(this, arguments);
      if(running) render();
    }
  });
  return methods;
};

//
// Turns it on, will start rendering on interval now
//
exports.start = (opts) => {
  settings = Object.assign(settings, opts)
  running = true;
  if(!settings.bottom) cliCursor.hide();
  render();
  looper = setInterval(render, settings.interval);
};

exports.stop = () => {
  running = false;
  clearTimeout(looper);
  cliCursor.show();
  render(true);
  charm.end();
};

//
// Stamps the current status to the console
//
exports.stamp = () => render(true);

//
// Gets the total number of cells in the bar
//
exports.cellCount = () => Object.keys(items).length;
<commit_msg>able to set pattern outside of start now<commit_after>const colors = require('colors');
const util = require('util');
const tty = require('tty');
const charm = require('charm')(process);
const cliSpinners = require('cli-spinners');
const cliCursor = require('cli-cursor');

const PADDING = '  ';

var iterations = 0;
var looper = null;
var running = false;
var items = {};
var defaultPattern = null;
var settings = {
  invert: false,
  interval: 250,
  pattern: null,
  bottom: false
};

var isatty = tty.isatty(1) && tty.isatty(2);
var tty_size = {
  width: isatty
    ? process.stdout.getWindowSize
      ? process.stdout.getWindowSize(1)[0]
      : tty.getWindowSize()[1]
    : 75,
  height: isatty
    ? process.stdout.getWindowSize
      ? process.stdout.getWindowSize(1)[1]
      : tty.getWindowSize()[2]
    : 75
};

//
// This is a single item (Or cell or whatever you call it) in the status display
//
var Item = exports.Item = function (options) {
  const defaults = {
    name: null,
    max: null,
    precision: 2
  };
  options = options || {};
  for (var attrname in defaults) {
    this[attrname] = options.hasOwnProperty(attrname) && options[attrname] !== null ? options[attrname] : defaults[attrname];
  }
  if(options.custom) this.custom = options.custom.bind(this);
  this.val = options.count || 0;
};

//
// Item functions for value changes, rendering, etc
//
Item.prototype = {
  inc: function (amount) {
    this.val += (amount !== undefined) ? amount : 1;
  },

  dec: function (amount) {
    this.val -= (amount !== undefined) ? amount : 1;
  },

  render: function (style) {
    switch (style) {
      case 'custom':
        return this.custom ? this.custom() : '';
      case 'percentage':
        if (!this.max) return '';
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        return (100 * this.count / max).toFixed(this.precision) + '%';
        break;
      case 'time':
        return nicetime(this.count);
      case 'bar':
        if (!this.max) return '';
        var bar_len = 10;
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        var done = Math.round(bar_len * this.count / max);
        return '[' + '▒'.repeat(Math.min(bar_len, done)) + '-'.repeat(Math.max(0,bar_len - done)) + ']';
      case 'default':
      case 'count':
      default:
        var max = typeof this.max == 'function'
                ? this.max()
                : this.max;
        return this.count + (max ? '/' + max : '');
    }
  }
};

//
// Getter/setter for count. Auto-rendering, basically.
//
Object.defineProperties(Item.prototype, {
  count: {
    get: function () {
      return this.val;
    },
    set: function (newValue) {
      this.val = newValue;
    }
  }
});

//
// Repeats a string, using it for the status bar instead of loops
//
String.prototype.repeat = function (len) {
  return new Array(len + 1).join(this);
};

//
// Render the status bar row
// If stamp is true, it will console.log it instead of doing an stdout
//
const render = (stamp) => {
  iterations++;
  if (stamp) {
    charm.erase('line').erase('down');
    return console.log(generateBar());
  }
  if (!running) return;

  var color_len = 0;
  for (var i = 0; i < items.length; i++) {
    if (items[i].color) {
      color_len += (items[i].color('')).length;
    }
  }

  var out = ' ' + generateBar();
  var bar = ' '.repeat(tty_size.width);

  if (settings.invert) {
    bar = bar.inverse;
    out = out.inverse;
  }

  var current_height = Math.ceil((out.length - color_len) / tty_size.width );

  charm.position(function (x, y) {
    var current_row = y;

    // If the current cursor row was on the bar, we need to make a gap
    if (settings.bottom && current_row > tty_size.height - current_height) {
      for(var i = 0; i < current_height; i++) {
        // charm.delete('line', 1);
        charm.erase('line');
        write('\n');
      }
      y -= current_height - (tty_size.height - current_row);
    }

    charm
      .move(0, settings.bottom ? tty_size.height : 0)
      .left(tty_size.width)
      .write(bar);

    if(settings.bottom) {
      for(var i = 0; i < Math.max(0, current_height - 1); i++) {
        charm.left(tty_size.width).write(bar).up(1);
      }
    }

    charm
      .left(tty_size.width)
      .write(out)
      .position(x, y);

  });
};

const write = (string) => process.stdout.write(string);

const generateBar = () => {
  var pattern = settings.pattern ? settings.pattern : defaultPattern;
  return pattern.replace(/\{([a-zA-z0-9\s\.]*)\}/g, (match, id) => {
    var tokens = id.split('.');
    var portion = '';
    var color = null;
    var modifier = null;
    if(tokens.length > 1 && colors[tokens[1]]) {
      color = colors[tokens[1]];
      modifier = tokens.length > 2 ? tokens[2] : null;
    } else if (tokens.length > 2 && colors[tokens[2]]) {
      color = colors[tokens[2]];
      modifier = tokens[1];
    } else if(tokens.length > 1) {
      modifier = tokens[1];
    }

    switch (tokens[0]) {
      case 'timestamp':
      case 'uptime':
        portion = nicetime(process.uptime(), true);
        break;
      case 'spinner':
        var spinnerType = modifier || 'dots';
        portion = cliSpinners[spinnerType].frames[iterations % cliSpinners[spinnerType].frames.length];
        break;
      default:
        if(items[tokens[0]]) portion = items[tokens[0]].render(modifier);
        break;
    }
    return color ? color(portion) : portion;
  });
};

//
// Currently just changes the milliseconds to either a number of seconds or number of minutes
//
var nicetime = (ms, use_seconds) => {
  var seconds = (ms / (use_seconds ? 1 : 1000)).toFixed((use_seconds ? 0 : 3));
  var minutes = (seconds / 60).toFixed(3);
  var time = (minutes < 2) ? seconds : minutes;
  return time + (minutes < 2 ?  's' : 'm');
};

process.on('exit', function () {
  if(running) render(true);
});

exports.addItem = (name, options) => {
  if(!name || typeof name !== 'string') return null;
  options = options || {};
  options.name = name;
  var item = new Item(options);
  items[name] = item;
  rebuildPattern();
  return items[name];
};

var rebuildPattern = () => {
  defaultPattern = Object.keys(items).reduce((memo, item) => {
    return `${memo}${PADDING}${item}: {${item}}${PADDING}|`;
  }, `Status @ {uptime}${PADDING}|`);
};

exports.removeItem = (item) => {
  if(typeof item === 'string') {
    delete items[item];
  } else if(item instanceof Item) {
    delete items[item.name];
  }
  rebuildPattern();
}

exports.removeAll = () => {
  items = {};
  rebuildPattern();
}
exports.toString = () => generateBar();
exports.clear = () => charm.erase('line').erase('down');

exports.console = function () {
  var methods = {};
  ['log', 'info', 'error', 'warn'].forEach(m => {
    methods[m] = function () {
      if(m !== 'log' || running) exports.clear();
      console[m].apply(this, arguments);
      if(running) render();
    }
  });
  return methods;
};

//
// Turns it on, will start rendering on interval now
//
exports.start = (opts) => {
  settings = Object.assign(settings, opts)
  running = true;
  if(!settings.bottom) cliCursor.hide();
  render();
  looper = setInterval(render, settings.interval);
};

exports.setPattern = (pattern) => settings.pattern = pattern;

exports.stop = () => {
  running = false;
  clearTimeout(looper);
  cliCursor.show();
  render(true);
  charm.end();
};

//
// Stamps the current status to the console
//
exports.stamp = () => render(true);

//
// Gets the total number of cells in the bar
//
exports.cellCount = () => Object.keys(items).length;
<|endoftext|>


<commit_before>/** kate-script
 * name: Ruby
 * license: LGPL
 * author: Robin Pedersen <robin.pedersen@runbox.com>
 * version: 1
 * kate-version: 3.0
 * type: indentation
 *
 * This file is part of the Kate Project.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License version 2 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

//BEGIN USER CONFIGURATION
//END USER CONFIGURATION

// specifies the characters which should trigger indent, beside the default '\n'
triggerCharacters = "cdefhilnrsuw}]";

// Indent after lines that match this regexp
var rxIndent = /^\s*(def|if|unless|for|while|until|class|module|else|elsif|case|when|begin|rescue|ensure|catch)\b/;

// Unindent lines that match this regexp
var rxUnindent = /^\s*((end|when|else|elsif|rescue|ensure)\b|[\]\}])(.*)$/;

// debug to the term in blue so that it's easier to make out amongst all
// of Kate's other debug output.
function dbg(s)
{
  debug("\u001B[44m" + s + "\u001B[0m");
}

function isComment(attr)
{
  return (attr == 30 || attr == 31);
}

function isCommentAttr(line, column)
{
  var attr = document.attribute(line, column);
  return isComment(attr);
}

// Return the closest non-empty line, ignoring comments
// (result <= line). Return -1 if the document
function findPrevNonCommentLine(line)
{
  line = document.prevNonEmptyLine(line);
  while (line >= 0 && isCommentAttr(line, document.firstColumn(line))) {
    line = document.prevNonEmptyLine(line - 1);
  }
  return line;
}

function isStmtContinuing(line)
{
  // Check for operators at end of line
  var rx = /(\+|\-|\*|\/|\=|&&|\|\||and|or|,|\\)\s*$/;

  return rx.test(document.line(line));
}

// Return the first line that is not preceeded by a "continuing" line.
// Return currLine if currLine <= 0
function findStmtStart(currLine)
{
  var p, l = currLine;
  do {
    if (l <= 0) return l;
    p = l;
    l = findPrevNonCommentLine(l - 1);
  } while (isStmtContinuing(l));
  return p;
}

// Returns a tuple that contains the first and last line of the
// previous statement before line.
function findPrevStmt(line)
{
  var stmtEnd = findPrevNonCommentLine(line);
  var stmtStart = findStmtStart(stmtEnd);

  return {start: stmtStart, end: stmtEnd};
}

function isBlockStart(currLine)
{
  var currStr = document.line(currLine);

  if (rxIndent.test(currStr))
    return true;

  var p = currStr.search(/(do|\{)(\s+\|.*\||\s*)$/);
  if (p != -1 && !isCommentAttr(currLine, p))
    return true;

  return false;
}

function isBlockEnd(currLine)
{
  var currStr = document.line(currLine);

  return rxUnindent.test(currStr);
}

function findBlockStart(currLine)
{
  var nested = 0;
  var l = currLine;
  while (true) {
    if (l < 0) return -1;

    l = findPrevNonCommentLine(l - 1);
    if (isBlockEnd(l)) {
      nested++;
    }
    if (isBlockStart(l)) {
      if (nested == 0)
        return l;
      else
        nested--;
    }
  }
}

// Return the string representing a possible multi-line statement
// defined by stmt.start and stmt.end
function getStmtStr(stmt)
{
  var str = "";
  for (var l = stmt.start; l <= stmt.end; ++l) {
    str += document.line(l).replace(/\\$/, ' ');
    if (l < stmt.end)
      str += "\n"
  }
  return str;
}

// Return document.attribute at the given offset in a statement
function getStmtAttr(stmt, offset)
{
  var line = stmt.start;
  while (line < stmt.end && document.lineLength(line) < offset) {
    offset -= document.lineLength(line++) + 1;
  }
  return document.attribute(line, offset);
}

// check if the trigger characters are in the right context,
// otherwise running the indenter might be annoying to the user
function isValidTrigger(line, ch)
{
  if (ch == "" || ch == "\n")
    return true; // Explicit align or new line
  if (rxUnindent.test(document.line(line))) {
    if (RegExp.$3 == "")
      return true; // Exact match
  }
  return false;
}

// indent gets three arguments: line, indentwidth in spaces,
// typed character indent
function indent(line, indentWidth, ch)
{
  if (!isValidTrigger(line, ch))
    return -2;

  var prevStmt = findPrevStmt(line - 1);
  dbg("start: " + prevStmt.start + ", end: " + prevStmt.end);

  if (prevStmt.end < 0)
    return -2; // Can't indent the first line

  var prevStmtStr = getStmtStr(prevStmt);
  dbg("foo"); //FIXME Removing this caused testkateregression to crash the same place as when running indent/csmart

  var prevStmtInd = document.firstVirtualColumn(prevStmt.start);

  // Handle indenting of multiline statements.
  // Manually indenting to be able to force spaces.
  if (isStmtContinuing(prevStmt.end) && (prevStmt.end == line-1 || RegExp.$1 != "\\")) {
    var len = document.firstColumn(prevStmt.end);
    var str = document.line(prevStmt.end).substr(0, len);
    if (!document.startsWith(line, str)) {
      document.removeText(line, 0, line, document.firstColumn(line));
      if (prevStmt.start == prevStmt.end)
        str += "    ";
      document.insertText(line, 0, str);
    }
    return -2;
  }

  if (rxUnindent.test(document.line(line))) {
    var startLine = findBlockStart(line);
    dbg("currLine: " + line);
    dbg("StartLine: " + startLine);
    if (startLine >= 0)
      return document.firstVirtualColumn(startLine);
    else
      return -2;
  }

  if (rxIndent.test(prevStmtStr)) {
    return prevStmtInd + indentWidth;
  } else {
    var p = prevStmtStr.search(/(do|\{)(\s+\|.*\||\s*)$/);
    if (p != -1 && !isComment(getStmtAttr(prevStmt, p))) {
      return prevStmtInd + indentWidth;
    } else if (prevStmtStr.search(/[\[\{]\s*$/) != -1) {
      return prevStmtInd + indentWidth;
    }
  }

  // Keep current
  return prevStmtInd;
}

// kate: indent-width 2; indent-spaces on;
<commit_msg>Correctly handles blocks where statement starting block spans multiple lines.<commit_after>/** kate-script
 * name: Ruby
 * license: LGPL
 * author: Robin Pedersen <robin.pedersen@runbox.com>
 * version: 1
 * kate-version: 3.0
 * type: indentation
 *
 * This file is part of the Kate Project.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License version 2 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

//BEGIN USER CONFIGURATION
//END USER CONFIGURATION

// specifies the characters which should trigger indent, beside the default '\n'
triggerCharacters = "cdefhilnrsuw}]";

// Indent after lines that match this regexp
var rxIndent = /^\s*(def|if|unless|for|while|until|class|module|else|elsif|case|when|begin|rescue|ensure|catch)\b/;

// Unindent lines that match this regexp
var rxUnindent = /^\s*((end|when|else|elsif|rescue|ensure)\b|[\]\}])(.*)$/;

// debug to the term in blue so that it's easier to make out amongst all
// of Kate's other debug output.
function dbg(s)
{
  debug("\u001B[44m" + s + "\u001B[0m");
}

function isComment(attr)
{
  return (attr == 30 || attr == 31);
}

function isCommentAttr(line, column)
{
  var attr = document.attribute(line, column);
  return isComment(attr);
}

// Return the closest non-empty line, ignoring comments
// (result <= line). Return -1 if the document
function findPrevNonCommentLine(line)
{
  line = document.prevNonEmptyLine(line);
  while (line >= 0 && isCommentAttr(line, document.firstColumn(line))) {
    line = document.prevNonEmptyLine(line - 1);
  }
  return line;
}

function isStmtContinuing(line)
{
  // Check for operators at end of line
  var rx = /(\+|\-|\*|\/|\=|&&|\|\||and|or|,|\\)\s*$/;

  return rx.test(document.line(line));
}

// Return the first line that is not preceeded by a "continuing" line.
// Return currLine if currLine <= 0
function findStmtStart(currLine)
{
  var p, l = currLine;
  do {
    if (l <= 0) return l;
    p = l;
    l = findPrevNonCommentLine(l - 1);
  } while (isStmtContinuing(l));
  return p;
}

// Returns a tuple that contains the first and last line of the
// previous statement before line.
function findPrevStmt(line)
{
  var stmtEnd = findPrevNonCommentLine(line);
  var stmtStart = findStmtStart(stmtEnd);

  return {start: stmtStart, end: stmtEnd};
}

function isBlockStart(stmt)
{
  var str = getStmtStr(stmt);

  if (rxIndent.test(str))
    return true;

  var p = str.search(/(do|\{)(\s+\|.*\||\s*)$/);
  if (p != -1 && !isComment(getStmtAttr(stmt, p)))
    return true;

  return false;
}

function isBlockEnd(stmt)
{
  var str = getStmtStr(stmt);

  return rxUnindent.test(str);
}

function findBlockStart(line)
{
  var nested = 0;
  var stmt = {start: line, end: line};
  while (true) {
    if (stmt.start < 0) return stmt;

    stmt = findPrevStmt(stmt.start - 1);
    if (isBlockEnd(stmt)) {
      nested++;
    }
    if (isBlockStart(stmt)) {
      if (nested == 0)
        return stmt;
      else
        nested--;
    }
  }
}

// Return the string representing a possible multi-line statement
// defined by stmt.start and stmt.end
function getStmtStr(stmt)
{
  var str = "";
  for (var l = stmt.start; l <= stmt.end; ++l) {
    str += document.line(l).replace(/\\$/, ' ');
    if (l < stmt.end)
      str += "\n"
  }
  return str;
}

// Return document.attribute at the given offset in a statement
function getStmtAttr(stmt, offset)
{
  var line = stmt.start;
  while (line < stmt.end && document.lineLength(line) < offset) {
    offset -= document.lineLength(line++) + 1;
  }
  return document.attribute(line, offset);
}

// check if the trigger characters are in the right context,
// otherwise running the indenter might be annoying to the user
function isValidTrigger(line, ch)
{
  if (ch == "" || ch == "\n")
    return true; // Explicit align or new line
  if (rxUnindent.test(document.line(line))) {
    if (RegExp.$3 == "")
      return true; // Exact match
  }
  return false;
}

// indent gets three arguments: line, indentwidth in spaces,
// typed character indent
function indent(line, indentWidth, ch)
{
  if (!isValidTrigger(line, ch))
    return -2;

  var prevStmt = findPrevStmt(line - 1);
  dbg("start: " + prevStmt.start + ", end: " + prevStmt.end);

  if (prevStmt.end < 0)
    return -2; // Can't indent the first line

  var prevStmtStr = getStmtStr(prevStmt);
  dbg("foo"); //FIXME Removing this caused testkateregression to crash the same place as when running indent/csmart

  var prevStmtInd = document.firstVirtualColumn(prevStmt.start);

  // Handle indenting of multiline statements.
  // Manually indenting to be able to force spaces.
  if (isStmtContinuing(prevStmt.end) && (prevStmt.end == line-1 || RegExp.$1 != "\\")) {
    var len = document.firstColumn(prevStmt.end);
    var str = document.line(prevStmt.end).substr(0, len);
    if (!document.startsWith(line, str)) {
      document.removeText(line, 0, line, document.firstColumn(line));
      if (prevStmt.start == prevStmt.end)
        str += "    ";
      document.insertText(line, 0, str);
    }
    return -2;
  }

  if (rxUnindent.test(document.line(line))) {
    var startStmt = findBlockStart(line);
    dbg("currLine: " + line);
    dbg("StartLine: {" + startStmt.start + "," + startStmt.end + "}");
    if (startStmt.start >= 0)
      return document.firstVirtualColumn(startStmt.start);
    else
      return -2;
  }

  if (rxIndent.test(prevStmtStr)) {
    return prevStmtInd + indentWidth;
  } else {
    var p = prevStmtStr.search(/(do|\{)(\s+\|.*\||\s*)$/);
    if (p != -1 && !isComment(getStmtAttr(prevStmt, p))) {
      return prevStmtInd + indentWidth;
    } else if (prevStmtStr.search(/[\[\{]\s*$/) != -1) {
      return prevStmtInd + indentWidth;
    }
  }

  // Keep current
  return prevStmtInd;
}

// kate: indent-width 2; indent-spaces on;
<|endoftext|>


<commit_before>#!/usr/bin/env node

/* Write a program that performs an HTTP GET request to get the average stock price. Use the first argument for a ticker symbol. Use the get method in the http module with the API provided by MarkitOnDemand.

It would certainly be easier to test if you can grab the latest stock price, but because the response is so small, there may not be an opportunity to demonstrate chunking. On the API docs you will see an example request for data to create a chart. This will give 365 of daily prices. Use these prices to get an average.

Expected:

$ ./stocks.js AAPL
$123.45
*/

// require get function from http module
const { get } = require('http');

const stockTicker = process.argv[2];

// store the stockTicker in the url
let url = `http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":365,"DataPeriod":"Day","Elements":[{"Symbol":"${stockTicker}","Type":"price","Params":["c"]}]}`

const getJSON = (url) => {
  return new Promise((resolve, reject) => {
    get(url, (res) => {

      let body = ''

      res.on('data', (buff) => {

        body += buff.toString()
      })

      res.on('end', () => {

        // store body as json
        // return body = JSON.parse(body)
        resolve(body = JSON.parse(body))
      })
    })
  }) // close promise
}

const calcAverage = (stockObj) => {

  let priceArray = stockObj.Elements[0].DataSeries.close.values

  // let { Elements: [{ DataSeries: stuff }] = stockObj
  let { Elements: [ { DataSeries: { close: { values } } } ] } = stockObj
  console.log("stuff", values)
  // console.log("stuff", DataSeries)

  // store array length
  let stockLength = priceArray.length

  // add up all of the stock values
  let sumStockValues = priceArray.reduce((acc, val) => {
    return acc + val
  })

  average = ( sumStockValues / stockLength ).toFixed(2)

  return average
}

// run the functions

getJSON(url)
.then( (data) => {
  console.log(calcAverage(data))
})
<commit_msg>Commented out previous code which completed the exercise to specifications<commit_after>#!/usr/bin/env node

/* Write a program that performs an HTTP GET request to get the average stock price. Use the first argument for a ticker symbol. Use the get method in the http module with the API provided by MarkitOnDemand.

It would certainly be easier to test if you can grab the latest stock price, but because the response is so small, there may not be an opportunity to demonstrate chunking. On the API docs you will see an example request for data to create a chart. This will give 365 of daily prices. Use these prices to get an average.

Expected:

$ ./stocks.js AAPL
$123.45
*/

// require get function from http module
const { get } = require('http');

const stockTicker = process.argv[2];

// store the stockTicker in the url
let url = `http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":365,"DataPeriod":"Day","Elements":[{"Symbol":"${stockTicker}","Type":"price","Params":["c"]}]}`

const getJSON = (url) => {
  return new Promise((resolve, reject) => {
    get(url, (res) => {

      let body = ''

      res.on('data', (buff) => {

        body += buff.toString()
      })

      res.on('end', () => {

        // store body as json
        // return body = JSON.parse(body)
        resolve(body = JSON.parse(body))
      })
    })
  }) // close promise
}

const calcAverage = (stockObj) => {

  let priceArray = stockObj.Elements[0].DataSeries.close.values

  // let { Elements: [{ DataSeries: stuff }] = stockObj
  let { Elements: [ { DataSeries: { close: { values } } } ] } = stockObj
  console.log("stuff", values)
  // console.log("stuff", DataSeries)

  // store array length
  let stockLength = priceArray.length

  // add up all of the stock values
  let sumStockValues = priceArray.reduce((acc, val) => {
    return acc + val
  })

  average = ( sumStockValues / stockLength ).toFixed(2)

  return average
}

// run the functions

getJSON(url)
.then( (data) => {
  console.log(calcAverage(data))
})

/*Old Way*/

// require get function from http module
// const { get } = require('http');

// const stockTicker = process.argv[2];

// // let url = `http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters=%7B%22Normalized%22%3Afalse%2C%22NumberOfDays%22%3A365%2C%22DataPeriod%22%3A%22Day%22%2C%22Elements%22%3A%5B%7B%22Symbol%22%3A%22AAPL%22%2C%22Type%22%3A%22price%22%2C%22Params%22%3A%5B%22c%22%5D%7D%5D%7D`
// // let url2 = `http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":365,"DataPeriod":"Day","Elements":[{"Symbol":"AAPL","Type":"price","Params":["c"]}]}`
// let url = `http://dev.markitondemand.com/MODApis/Api/v2/InteractiveChart/json?parameters={"Normalized":false,"NumberOfDays":365,"DataPeriod":"Day","Elements":[{"Symbol":"${stockTicker}","Type":"price","Params":["c"]}]}`

// get(url, (res) => {

//   let body = ''

//   res.on('data', (buff) => {

//     body += buff.toString()
//   })

//   res.on('end', () => {

//     // store body as json
//     body = JSON.parse(body)

//     // store length of values array to calculate average
//     let stockLength = body.Elements[0].DataSeries.close.values.length

//     // add up all of the stock values
//     let sumStockValues = body.Elements[0].DataSeries.close.values.reduce((acc, val) => {
//       return acc + val
//     })

//     average = ( sumStockValues / stockLength ).toFixed(2)

//     console.log(average)

//   })
// })
<|endoftext|>


<commit_before>// Copyright (c) 2013, Benjamin J. Kelly ("Author")
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'use strict';

module.exports = UdpStream;

var Transform = require('stream').Transform;
if (!Transform) {
  Transform = require('readable-stream/transform');
}
var util = require('util');

util.inherits(UdpStream, Transform);

function UdpStream(opts) {
  var self = (this instanceof UdpStream)
           ? this
           : Object.create(UdpStream.prototype);

  opts = opts || {};

  Transform.call(self, opts);

  return self;
}

UdpStream.prototype._transform = function(origMsg, output, callback) {
  // TODO: implement _transform
};
<commit_msg>First cut at UDP parsing transform.  Still needs tests.<commit_after>// Copyright (c) 2013, Benjamin J. Kelly ("Author")
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'use strict';

module.exports = UdpStream;

var Transform = require('stream').Transform;
if (!Transform) {
  Transform = require('readable-stream/transform');
}
var UdpHeader = require('udp-header');
var util = require('util');

util.inherits(UdpStream, Transform);

function UdpStream(opts) {
  var self = (this instanceof UdpStream)
           ? this
           : Object.create(UdpStream.prototype);

  opts = opts || {};

  Transform.call(self, opts);

  return self;
}

UdpStream.prototype._transform = function(origMsg, output, callback) {
  var msg = origMsg;
  if (msg instanceof Buffer) {
    msg = { data: msg, offset: 0 };
  }
  msg.offset = ~~msg.offset;

  var type = (msg.ip && msg.ip.protocol) ? msg.ip.protocol : 'udp';
  if (type !== 'udp') {
    this.emit('ignored', origMsg);
    callback();
    return;
  }

  try {

    msg.udp = new UdpHeader(msg.data, msg.offset);
    msg.offset += msg.udp.length;
    output(msg);

  } catch (error) {
    this.emit('ignored', origMsg);
  }

  callback();
};
<|endoftext|>


<commit_before>/*
* Awesome Password Generator aka HashPass
* Copyright (c) Macarthur Inbody 2011-2017
* https://github.com/133794m3r/hashpass
* Licensed AGPLv3 or Later
* version 2.0.0b
*/
function base32_encode(data) {
    //var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    var alphabet = 'ybndrfg8ejkmcpqxot1uwisza345h769';
    var output='';
    var iter= Math.floor((data.length / 5));
    var leftover = data.length % 5;
    var part1=0;
    var part1=0;
    var part2=0;
    var part3=0;
    var part4=0;
    var part5=0;
    var part6=0;
    var part7=0;
    var part8=0;
    var str1='';
    var str2='';
    var str3='';
    var str4='';
    var str5='';
    var i_5=0;
    var padding='';
    if (leftover != 0) {
       //for (var i = 0; i < (5-leftover); i++) { s += '\x00'; }
       iter += 1;
    }
    if(typeof data === 'string'){
        for (i = 0; i < iter; i++) {
        i_5=i*5;
        str1=data.charCodeAt(i_5);
        str2=data.charCodeAt(i_5+1);
        str3=data.charCodeAt(i_5+2);
        str4=data.charCodeAt(i_5+3);
        str5=data.charCodeAt(i_5+4);
        part1=(str1 >> 3);
        part2=( ((str1 & 0x07) << 2)
           | (str2 >> 6));
        part3=( ((str2 & 0x3F) >> 1) );
        part4=( ((str2 & 0x01) << 4)
           | (str3 >> 4));
        part5=( ((str3 & 0x0F) << 1)
           | (str4 >> 7));
        parts6=( ((str4 & 0x7F) >> 2));
        part7=( ((str4 & 0x03) << 3)
           | (str5 >> 5));
        part8=( ((str5 & 0x1F) ));

        output+=alphabet.charAt(part1)+
        alphabet.charAt(part2)+
        alphabet.charAt(part3)+
        alphabet.charAt(part4)+
        alphabet.charAt(part5)+
        alphabet.charAt(part6)+
        alphabet.charAt(part7)+
        alphabet.charAt(part8);
    }
    }
    else{
    for (i = 0; i < iter; i++) {
        i_5=i*5;
        str1=data[i_5];
        str2=data[(i_5+1)];
        str3=data[(i_5+2)];
        str4=data[(i_5+3)];
        str5=data[(i_5+4)];
        part1=(str1 >> 3);
        part2=( ((str1 & 0x07) << 2)
           | (str2 >> 6));
        part3=( ((str2 & 0x3F) >> 1) );
        part4=( ((str2 & 0x01) << 4)
           | (str3 >> 4));
        part5=( ((str3 & 0x0F) << 1)
           | (str4 >> 7));
        parts6=( ((str4 & 0x7F) >> 2));
        part7=( ((str4 & 0x03) << 3)
           | (str5 >> 5));
        part8=( ((str5 & 0x1F) ));

        output+=alphabet.charAt(part1)+
        alphabet.charAt(part2)+
        alphabet.charAt(part3)+
        alphabet.charAt(part4)+
        alphabet.charAt(part5)+
        alphabet.charAt(part6)+
        alphabet.charAt(part7)+
        alphabet.charAt(part8);
    }
    }

    var replace = 0;
    if (leftover == 1) replace = 6;
    else if (leftover == 2) replace = 4;
    else if (leftover == 3) replace = 3;
    else if (leftover == 4) replace = 1;
    var j=(i*8);

    for (i = 0; i < replace; i++) padding+='=';
    replace=(j)-replace;
    output=output.substr(0,replace)+padding;
return output;

}
function hex_decode(hex_str){
    var strlen=Math.ceil(hex_str.length/2);
    var i=0;
    var out_str=''
    for(i=0;i<strlen;i++){
        out_str+=String.fromCharCode(parseInt(hex_str.substr(i*2,2),16));
    }
    return out_str;
}
function string_indexes(string,search_string){
var len=string.length;
var tmp_str='';
var str='';
var index=0;
var indexes=[];
var prev_index=0;
var j=0;
while(index!==null){
    tmp_str=string.substr(index);

    index=tmp_str.match(search_string);

    if(index!==null){
        indexes[j++]=tmp_str.indexOf(index[0])+prev_index;
        index=tmp_str.indexOf(index[0])+1+prev_index;
        prev_index=index;
    }
}
return indexes;
}

function no_repeat_strings(string) {
  var tmp_str = '';
  var string_fixed = '';
  var strlen = string.length;
  var extra_str = '';
  var prev_str = string.substr(0, 1);
  var cur_str = '';

  var repeat_found = 1;
  var i = 1;
  var tmp_str_len = 0;
  var j = 0;
  var l = 0;
  while (repeat_found === 1) {
    if ((i > strlen) && (tmp_str_len >= 1) && (j <= 100)) {
        l =l+i+j;
        i = 1;
        string = tmp_str + extra_str;
        if (string.substr( -1, 1) === string.substr( -2, 1)) {
            ins_place = (l % strlen);
            string = string.substr(0, ins_place) + string.substr( - 1, 1) + string.substr(ins_place, (strlen - 1));
        }
        else if(string.substr(0,1)===string.substr(1,1)){
            ins_place = (l % strlen);
            string = string.substr(0, ins_place) + string.substr( -1, 1) + string.substr(ins_place, (strlen - 1));
        }
      prev_str = string.substr(0, 1);
      tmp_str_len = 0;
      repeat_found = 1;
      extra_str = '';
      tmp_str = '';
      j = j + 1;
    }
    else if ((i > strlen)) {
      repeat_found = 0;
    }
    cur_str = string.substr(i, 1);
    if (prev_str == cur_str) {
      tmp_str += prev_str;
      tmp_str_len = tmp_str.length;
    }
    else {
      extra_str += prev_str;
    }
    prev_str = cur_str;
    i = i + 1;

  }
  string_fixed = string;
  return string_fixed;
}

function b64_encode(str,type=false){
	var chr1, chr2, chr3, rez = '', arr = [], i = 0, j = 0, code = 0,k=0;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');
if(type==false){
	while(code = str.charCodeAt(j++)){
		if(code < 128){
			arr[k] = code;
		}
		else if(code < 2048){
			arr[k] = 192 | (code >> 6);
			arr[k] = 128 | (code & 63);
		}
		else if(code < 65536){
			arr[k] = 224 | (code >> 12);
			arr[k] = 128 | ((code >> 6) & 63);
			arr[k] = 128 | (code & 63);
		}
		else{
			arr[k] = 240 | (code >> 18);
			arr[k] = 128 | ((code >> 12) & 63);
			arr[k] = 128 | ((code >> 6) & 63);
			arr[k] = 128 | (code & 63);
		}
        ++k;
	}
}
else
{
    arr=str;
    k=arr.length;
}
    console.log(arr);
	while(i < k){
		chr1 = arr[i++];
		chr2 = arr[i++];
		chr3 = arr[i++];
		rez += chars[chr1 >> 2];
		rez += chars[(((chr1 & 3) << 4) | (chr2 >> 4))];
		rez += chars[(chr2 === undefined ? 64 : ((chr2 & 15) << 2) | (chr3 >> 6))];
		rez += chars[(chr3 === undefined ? 64 : chr3 & 63)];
	}
	return rez;
};

function b64_decode(str){
    var chr0, chr1, chr2,chr3, rez = '', arr = [], i = 0, j = 0, code = 0,k=0;;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var strlen=str.length;
    var bits=0;
    var dec=[];
    var ac=0;
    var o0,o1,o2;
    while(i<strlen){
        chr0=chars.indexOf(str.charAt(i));
        chr1=chars.indexOf(str.charAt(i+1));
        chr2=chars.indexOf(i+2,1);
        chr3=chars.indexOf(i+3,1);
        o0=(chr0<<2)|(chr1>>4);
        o1=((chr1&15)<<4)|(chr2>>2);
        o2=((chr2&3)<<6)|chr4;

        dec+=String.fromCharCode(o0)
        if(chr2!==64){
            dec+=String.fromCharCode(o1);
        }
        else if(chr3!==64){
            dec+=String.fromCharCode(o2);
        }
        chr0=chr1=chr2=chr3='';
        o0=o1=o2='';
      ++i;
    }
    dec=unescape(dec);
    return dec;
}
<commit_msg>updated string.js to add binary data encoding.<commit_after>/*
* Awesome Password Generator aka HashPass
* Copyright (c) Macarthur Inbody 2011-2017
* https://github.com/133794m3r/hashpass
* Licensed AGPLv3 or Later
* version 2.0.0b
*/
function base32_encode(data,string=true) {
    //var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

    var alphabet = 'ybndrfg8ejkmcpqxot1uwisza345h769';
    var output='';
    var iter= Math.floor((data.length / 5));
    var leftover = data.length % 5;
    var part1=0;
    var part1=0;
    var part2=0;
    var part3=0;
    var part4=0;
    var part5=0;
    var part6=0;
    var part7=0;
    var part8=0;
    var str1='';
    var str2='';
    var str3='';
    var str4='';
    var str5='';
    var padding='';
    if (leftover != 0) {
       //for (var i = 0; i < (5-leftover); i++) { s += '\x00'; }
       iter += 1;
    }

	if(string===true){
        for (i = 0; i < iter; i++) {
        i_5=i*5;
        str1=data.charCodeAt(i_5);
        str2=data.charCodeAt(i_5+1);
        str3=data.charCodeAt(i_5+2);
        str4=data.charCodeAt(i_5+3);
        str5=data.charCodeAt(i_5+4);
        part1=(str1 >> 3);
        part2=( ((str1 & 0x07) << 2)
           | (str2 >> 6));
        part3=( ((str2 & 0x3F) >> 1) );
        part4=( ((str2 & 0x01) << 4)
           | (str3 >> 4));
        part5=( ((str3 & 0x0F) << 1)
           | (str4 >> 7));
        parts6=( ((str4 & 0x7F) >> 2));
        part7=( ((str4 & 0x03) << 3)
           | (str5 >> 5));
        part8=( ((str5 & 0x1F) ));
        output+=alphabet.charAt(part1)+
        alphabet.charAt(part2)+
        alphabet.charAt(part3)+
        alphabet.charAt(part4)+
        alphabet.charAt(part5)+
        alphabet.charAt(part6)+
        alphabet.charAt(part7)+
        alphabet.charAt(part8);
    }
	}
else{
        for (i = 0; i < iter; i++) {
        i_5=i*5;
        str1=data[(i_5)];
        str2=data[(i_5+1)];
        str3=data[(i_5+2)];
        str4=data[(i_5+3)];
        str5=data[(i_5+4)];
        part1=(str1 >> 3);
        part2=( ((str1 & 0x07) << 2)
           | (str2 >> 6));
        part3=( ((str2 & 0x3F) >> 1) );
        part4=( ((str2 & 0x01) << 4)
           | (str3 >> 4));
        part5=( ((str3 & 0x0F) << 1)
           | (str4 >> 7));
        parts6=( ((str4 & 0x7F) >> 2));
        part7=( ((str4 & 0x03) << 3)
           | (str5 >> 5));
        part8=( ((str5 & 0x1F) ));
        output+=alphabet.charAt(part1)+
        alphabet.charAt(part2)+
        alphabet.charAt(part3)+
        alphabet.charAt(part4)+
        alphabet.charAt(part5)+
        alphabet.charAt(part6)+
        alphabet.charAt(part7)+
        alphabet.charAt(part8);
    }
}
    var replace = 0;
    if (leftover == 1) replace = 6;
    else if (leftover == 2) replace = 4;
    else if (leftover == 3) replace = 3;
    else if (leftover == 4) replace = 1;
    var j=(i*8);

    for (i = 0; i < replace; i++) padding+='=';
    replace=(j)-replace;
    output=output.substr(0,replace)+padding;
return output;

}
function hex_decode(hex_str){
    var strlen=Math.ceil(hex_str.length/2);
    var i=0;
    var out_str=''
    for(i=0;i<strlen;i++){
        out_str+=String.fromCharCode(parseInt(hex_str.substr(i*2,2),16));
    }
    return out_str;
}
function string_indexes(string,search_string){
var len=string.length;
var tmp_str='';
var str='';
var index=0;
var indexes=[];
var prev_index=0;
var j=0;
while(index!==null){
    tmp_str=string.substr(index);

    index=tmp_str.match(search_string);

    if(index!==null){
        indexes[j++]=tmp_str.indexOf(index[0])+prev_index;
        index=tmp_str.indexOf(index[0])+1+prev_index;
        prev_index=index;
    }
}
return indexes;
}
/*function no_repeat_strings(string){
  var tmp_str='';
  var string_fixed='';
  var strlen=string.length;
  var extra_str='';
  var prev_str=string.substr(0,1);
  var cur_str='';
  var string_fixed='';
  var repeat_found=1;
  var i=1;
  var tmp_str_len=0;
  var j=0;
  var l=0;
  while(repeat_found===1){
    if( (i>strlen)&& (tmp_str_len>=1) && (j<=5)){
      i=1;
      string=extra_str+tmp_str;
      if(string.substr(-1,1)===string.substr(-2,1)){
        ins_place=(l%strlen);
        string=string.substr(0,ins_place)+string.substr(-1,1)+string.substr(ins_place,(strlen-1));
      }
      prev_str=string.substr(0,1);
      tmp_str_len=0;
      repeat_found=1;
      extra_str='';
      tmp_str='';
      j=j+1;
    }
    else if((i>strlen)){
      repeat_found=0;
    }
    cur_str=string.substr(i,1);
    if(prev_str==cur_str){
      tmp_str+=prev_str;
      tmp_str_len=tmp_str.length;
    }
    else{
      extra_str+=prev_str;
    }
    prev_str=cur_str;
    i=i+1;
  }
  string_fixed=string;
 return string_fixed;
}
*/
function no_repeat_strings(string) {
  var tmp_str = '';
  var string_fixed = '';
  var strlen = string.length;
  var extra_str = '';
  var prev_str = string.substr(0, 1);
  var cur_str = '';

  var repeat_found = 1;
  var i = 1;
  var tmp_str_len = 0;
  var j = 0;
  var l = 0;
  while (repeat_found === 1) {
    if ((i > strlen) && (tmp_str_len >= 1) && (j <= 100)) {
        l =l+i+j;
        i = 1;
        string = tmp_str + extra_str;
        if (string.substr( -1, 1) === string.substr( -2, 1)) {
            ins_place = (l % strlen);
            string = string.substr(0, ins_place) + string.substr( - 1, 1) + string.substr(ins_place, (strlen - 1));
        }
        else if(string.substr(0,1)===string.substr(1,1)){
            ins_place = (l % strlen);
            string = string.substr(0, ins_place) + string.substr( -1, 1) + string.substr(ins_place, (strlen - 1));
        }
      prev_str = string.substr(0, 1);
      tmp_str_len = 0;
      repeat_found = 1;
      extra_str = '';
      tmp_str = '';
      j = j + 1;
    }
    else if ((i > strlen)) {
      repeat_found = 0;
    }
    cur_str = string.substr(i, 1);
    if (prev_str == cur_str) {
      tmp_str += prev_str;
      tmp_str_len = tmp_str.length;
    }
    else {
      extra_str += prev_str;
    }
    prev_str = cur_str;
    i = i + 1;

  }
  string_fixed = string;
  return string_fixed;
}

function b64_encode(str,type=false){
	var chr1, chr2, chr3, rez = '', arr = [], i = 0, j = 0, code = 0,k=0;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');
if(type==false){
	while(code = str.charCodeAt(j++)){
		if(code < 128){
			arr[k] = code;
		}
		else if(code < 2048){
			arr[k] = 192 | (code >> 6);
			arr[k] = 128 | (code & 63);
		}
		else if(code < 65536){
			arr[k] = 224 | (code >> 12);
			arr[k] = 128 | ((code >> 6) & 63);
			arr[k] = 128 | (code & 63);
		}
		else{
			arr[k] = 240 | (code >> 18);
			arr[k] = 128 | ((code >> 12) & 63);
			arr[k] = 128 | ((code >> 6) & 63);
			arr[k] = 128 | (code & 63);
		}
        ++k;
	}
}
else
{
    arr=str;
    k=arr.length;
}
    console.log(arr);
	while(i < k){
		chr1 = arr[i++];
		chr2 = arr[i++];
		chr3 = arr[i++];
		rez += chars[chr1 >> 2];
		rez += chars[(((chr1 & 3) << 4) | (chr2 >> 4))];
		rez += chars[(chr2 === undefined ? 64 : ((chr2 & 15) << 2) | (chr3 >> 6))];
		rez += chars[(chr3 === undefined ? 64 : chr3 & 63)];
	}
	return rez;
};

function b64_decode(str){
    var chr0, chr1, chr2,chr3, rez = '', arr = [], i = 0, j = 0, code = 0,k=0;;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var strlen=str.length;
    var bits=0;
    var dec=[];
    var ac=0;
    var o0,o1,o2;
    while(i<strlen){
        chr0=chars.indexOf(str.charAt(i));
        chr1=chars.indexOf(str.charAt(i+1));
        chr2=chars.indexOf(i+2,1);
        chr3=chars.indexOf(i+3,1);
        o0=(chr0<<2)|(chr1>>4);
        o1=((chr1&15)<<4)|(chr2>>2);
        o2=((chr2&3)<<6)|chr4;

        dec+=String.fromCharCode(o0)
        if(chr2!==64){
            dec+=String.fromCharCode(o1);
        }
        else if(chr3!==64){
            dec+=String.fromCharCode(o2);
        }
        chr0=chr1=chr2=chr3='';
        o0=o1=o2='';
      ++i;
    }
    dec=unescape(dec);
    return dec;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/* eslint max-len:[0, 120] */
/* eslint max-statements:[0, 99] */
'use strict';

var assert = require('assert');
var bufrw = require('bufrw');
var TYPE = require('./TYPE');
var NAMES = require('./names');
var UnexpectedFieldValueTypeidError = require('./errors').UnexpectedFieldValueTypeidError;
var FieldRequiredError = require('./errors').FieldRequiredError;
var skipField = require('./skip').skipField;

var LengthResult = bufrw.LengthResult;
var WriteResult = bufrw.WriteResult;
var ReadResult = bufrw.ReadResult;

function FieldSpec(def, struct) {
    var self = this;
    assert(def.isResult || def.id.value > 0,
        'field identifier must be greater than 0' +
        ' for ' + JSON.stringify(def.name) +
        ' on ' + JSON.stringify(struct.name) +
        ' at ' + def.id.line + ':' + def.id.column
    );
    self.id = def.id.value;
    self.name = def.name;
    self.required = def.required;
    self.optional = def.optional;
    self.annotations = def.annotations;
    self.valueDefinition = def.valueType;
    self.valueType = null;
    self.defaultValueDefinition = def.defaultValue;
    self.defaultValue = null;
    self.constructDefaultValue = null;
}

FieldSpec.prototype.link = function link(spec) {
    var self = this;
    self.valueType = spec.resolve(self.valueDefinition);
    assert(self.valueType, 'value type was defined, as returned by resolve');
};

FieldSpec.prototype.linkValue = function linkValue(spec) {
    var self = this;
    self.defaultValue = spec.resolveValue(self.defaultValueDefinition);
};

function StructSpec(options) {
    var self = this;
    options = options || {};

    self.name = null;
    // Strict mode is on by default. Because we have strict opinions about Thrift.
    self.strict = options.strict !== undefined ? options.strict : true;
    // TODO bring in serviceName
    self.fields = [];
    self.fieldNames = [];
    self.fieldsById = {};
    self.fieldsByName = {};
    self.isArgument = null;
    self.Constructor = null;
    self.rw = new StructRW(self);
    self.linked = false;
}

StructSpec.prototype.name = 'struct';
StructSpec.prototype.typeid = TYPE.STRUCT;

StructSpec.prototype.toBuffer = function toBuffer(struct) {
    var self = this;
    return bufrw.toBuffer(self.rw, struct);
};

StructSpec.prototype.toBufferResult = function toBufferResult(struct) {
    var self = this;
    return bufrw.toBufferResult(self.rw, struct);
};

StructSpec.prototype.fromBuffer = function fromBuffer(buffer, offset) {
    var self = this;
    return bufrw.fromBuffer(self.rw, buffer, offset);
};

StructSpec.prototype.fromBufferResult = function fromBufferResult(buffer) {
    var self = this;
    return bufrw.fromBufferResult(self.rw, buffer);
};

StructSpec.prototype.compile = function compile(def) {
    var self = this;
    // Struct names must be valid JavaScript. If the Thrift name is not valid
    // in JavaScript, it can be overridden with the js.name annotation.
    self.name = def.annotations && def.annotations['js.name'] || def.id.name;
    self.fullName = def.id.as || self.name;
    self.isArgument = def.isArgument || false;
    self.isResult = def.isResult || false;
    var fields = def.fields;
    for (var index = 0; index < fields.length; index++) {
        var fieldDef = fields[index];
        var field = new FieldSpec(fieldDef, self);

        // Field names must be valid JavaScript. If the Thrift name is not
        // valid in JavaScript, it can be overridden with the js.name
        // annotation.
        field.name = field.annotations && field.annotations['js.name'] || field.name;
        self.fieldsById[field.id] = field;
        self.fieldsByName[field.name] = field;
        self.fieldNames[index] = field.name;
        self.fields.push(field);
    }
};

StructSpec.prototype.link = function link(spec) {
    var self = this;

    if (self.linked) {
        return self;
    }
    self.linked = true;

    var index;

    // Link default values first since they're used by the constructor
    for (index = 0; index < self.fields.length; index++) {
        var field = self.fields[index];
        field.linkValue(spec);

        // Validate field
        if (self.strict) {
            assert(
                field.required || field.optional ||
                field.defaultValue !== null && field.defaultValue !== undefined ||
                self.isArgument || self.isResult,
                'every field must be marked optional, required, or have a default value on ' +
                    self.name + ' including "' + field.name + '" in strict mode'
            );
        }
        if (self.isArgument && field.optional) {
            assert.ok(false, 'no field of an argument struct may be marked ' +
                'optional including ' + field.name + ' of ' + self.name);
        }
        field.required = field.required || self.isArgument;

    }

    self.Constructor = self.createConstructor(self.name, self.fields);
    self.Constructor.rw = self.rw;

    self.Constructor.fromBuffer = self.fromBuffer;
    self.Constructor.fromBufferResult = self.fromBufferResult;

    self.Constructor.toBuffer = self.toBuffer;
    self.Constructor.toBufferResult = self.toBufferResult;

    // Link field types later since they may depend on the constructor existing
    // first.
    spec[self.name] = self.Constructor;
    for (index = 0; index < self.fields.length; index++) {
        self.fields[index].link(spec);
    }

    return self;
};

// The following methods have alternate implementations for Exception and Union.

StructSpec.prototype.createConstructor = function createConstructor(name, fields) {
    var source;
    source = '(function $' + name + '(options) {\n';
    for (var index = 0; index < fields.length; index++) {
        var field = fields[index];
        source += '    this.' + field.name + ' = null;\n';
        source += '    if (options && typeof options.' + field.name + ' !== "undefined") ' +
            '{ this.' + field.name + ' = options.' + field.name + '; }\n';
        if (field.defaultValue !== null) {
            source += '    else { this.' + field.name +
                ' = ' + JSON.stringify(field.defaultValue) + '; }\n';
        }
    }
    source += '})\n';
    // eval is an operator that captures the lexical scope of the calling
    // function and deoptimizes the lexical scope.
    // By using eval in an expression context, it loses this second-class
    // capability and becomes a first-class function.
    // (0, eval) is one way to use eval in an expression context.
    return (0, eval)(source);
};

StructSpec.prototype.create = function create() {
    var self = this;
    return new self.Constructor();
};

StructSpec.prototype.set = function set(struct, key, value) {
    struct[key] = value;
};

StructSpec.prototype.finalize = function finalize(struct) {
    return struct;
};

function StructRW(spec) {
    assert(spec, 'spec required');
    var self = this;
    self.spec = spec;
}

StructRW.prototype.byteLength = function byteLength(struct) {
    var self = this;
    var length = 1; // stop:1
    var result;
    for (var index = 0; index < self.spec.fields.length; index++) {
        var field = self.spec.fields[index];
        var value = struct && struct[field.name];

        var available = value !== null && value !== undefined;

        if (!available && field.required) {
            return new LengthResult(FieldRequiredError({
                name: field.name,
                id: field.id,
                structName: self.spec.name,
                what: struct
            }));
        }
        if (!available) {
            continue;
        }

        // TODO maybe suppress defaultValue on the wire

        // typeid:1
        // field.id:2
        length += 3;

        result = field.valueType.rw.byteLength(value);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        length += result.length;
    }
    return new LengthResult(null, length);
};

StructRW.prototype.writeInto = function writeInto(struct, buffer, offset) {
    var self = this;
    var result;
    for (var index = 0; index < self.spec.fields.length; index++) {
        var field = self.spec.fields[index];
        var value = struct && struct[field.name];
        var available = value !== null && value !== undefined;

        if (!available && field.required) {
            return new LengthResult(FieldRequiredError({
                name: field.name,
                id: field.id,
                structName: self.spec.name,
                what: struct
            }));
        }
        if (!available) {
            continue;
        }

        // TODO maybe suppress defaultValue on the wire

        result = bufrw.Int8.writeInto(field.valueType.typeid, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;

        result = bufrw.Int16BE.writeInto(field.id, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;

        result = field.valueType.rw.writeInto(value, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
    }

    result = bufrw.Int8.writeInto(TYPE.STOP, buffer, offset);
    // istanbul ignore if
    if (result.err) {
        return result;
    }
    offset = result.offset;
    return new WriteResult(null, offset);
};

StructRW.prototype.readFrom = function readFrom(buffer, offset) {
    var self = this;
    var struct = self.spec.create();
    var result;

    for (;;) {
        result = bufrw.Int8.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        var typeid = result.value;

        if (typeid === TYPE.STOP) {
            break;
        }

        result = bufrw.Int16BE.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        var id = result.value;

        // skip unrecognized fields from THE FUTURE
        if (!self.spec.fieldsById[id]) {
            result = skipField(buffer, offset);
            // istanbul ignore if
            if (result.err) {
                return result;
            }
            offset = result.offset;
            continue;
        }

        var field = self.spec.fieldsById[id];
        if (field.valueType.typeid !== typeid) {
            return new ReadResult(UnexpectedFieldValueTypeidError({
                fieldId: id,
                fieldName: field.name,
                structName: self.spec.name,
                typeid: typeid,
                typeName: NAMES[typeid],
                expectedTypeid: field.valueType.typeid,
                expectedTypeName: NAMES[field.valueType.typeid]
            }));
        }

        result = field.valueType.rw.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        self.spec.set(struct, field.name, result.value);
    }

    return new ReadResult(null, offset, self.spec.finalize(struct));
};

module.exports.FieldSpec = FieldSpec;
module.exports.StructSpec = StructSpec;
module.exports.StructRW = StructRW;
<commit_msg>Replace $ sigil for generated cons with thriftrw_<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/* eslint max-len:[0, 120] */
/* eslint max-statements:[0, 99] */
'use strict';

var assert = require('assert');
var bufrw = require('bufrw');
var TYPE = require('./TYPE');
var NAMES = require('./names');
var UnexpectedFieldValueTypeidError = require('./errors').UnexpectedFieldValueTypeidError;
var FieldRequiredError = require('./errors').FieldRequiredError;
var skipField = require('./skip').skipField;

var LengthResult = bufrw.LengthResult;
var WriteResult = bufrw.WriteResult;
var ReadResult = bufrw.ReadResult;

function FieldSpec(def, struct) {
    var self = this;
    assert(def.isResult || def.id.value > 0,
        'field identifier must be greater than 0' +
        ' for ' + JSON.stringify(def.name) +
        ' on ' + JSON.stringify(struct.name) +
        ' at ' + def.id.line + ':' + def.id.column
    );
    self.id = def.id.value;
    self.name = def.name;
    self.required = def.required;
    self.optional = def.optional;
    self.annotations = def.annotations;
    self.valueDefinition = def.valueType;
    self.valueType = null;
    self.defaultValueDefinition = def.defaultValue;
    self.defaultValue = null;
    self.constructDefaultValue = null;
}

FieldSpec.prototype.link = function link(spec) {
    var self = this;
    self.valueType = spec.resolve(self.valueDefinition);
    assert(self.valueType, 'value type was defined, as returned by resolve');
};

FieldSpec.prototype.linkValue = function linkValue(spec) {
    var self = this;
    self.defaultValue = spec.resolveValue(self.defaultValueDefinition);
};

function StructSpec(options) {
    var self = this;
    options = options || {};

    self.name = null;
    // Strict mode is on by default. Because we have strict opinions about Thrift.
    self.strict = options.strict !== undefined ? options.strict : true;
    // TODO bring in serviceName
    self.fields = [];
    self.fieldNames = [];
    self.fieldsById = {};
    self.fieldsByName = {};
    self.isArgument = null;
    self.Constructor = null;
    self.rw = new StructRW(self);
    self.linked = false;
}

StructSpec.prototype.name = 'struct';
StructSpec.prototype.typeid = TYPE.STRUCT;

StructSpec.prototype.toBuffer = function toBuffer(struct) {
    var self = this;
    return bufrw.toBuffer(self.rw, struct);
};

StructSpec.prototype.toBufferResult = function toBufferResult(struct) {
    var self = this;
    return bufrw.toBufferResult(self.rw, struct);
};

StructSpec.prototype.fromBuffer = function fromBuffer(buffer, offset) {
    var self = this;
    return bufrw.fromBuffer(self.rw, buffer, offset);
};

StructSpec.prototype.fromBufferResult = function fromBufferResult(buffer) {
    var self = this;
    return bufrw.fromBufferResult(self.rw, buffer);
};

StructSpec.prototype.compile = function compile(def) {
    var self = this;
    // Struct names must be valid JavaScript. If the Thrift name is not valid
    // in JavaScript, it can be overridden with the js.name annotation.
    self.name = def.annotations && def.annotations['js.name'] || def.id.name;
    self.fullName = def.id.as || self.name;
    self.isArgument = def.isArgument || false;
    self.isResult = def.isResult || false;
    var fields = def.fields;
    for (var index = 0; index < fields.length; index++) {
        var fieldDef = fields[index];
        var field = new FieldSpec(fieldDef, self);

        // Field names must be valid JavaScript. If the Thrift name is not
        // valid in JavaScript, it can be overridden with the js.name
        // annotation.
        field.name = field.annotations && field.annotations['js.name'] || field.name;
        self.fieldsById[field.id] = field;
        self.fieldsByName[field.name] = field;
        self.fieldNames[index] = field.name;
        self.fields.push(field);
    }
};

StructSpec.prototype.link = function link(spec) {
    var self = this;

    if (self.linked) {
        return self;
    }
    self.linked = true;

    var index;

    // Link default values first since they're used by the constructor
    for (index = 0; index < self.fields.length; index++) {
        var field = self.fields[index];
        field.linkValue(spec);

        // Validate field
        if (self.strict) {
            assert(
                field.required || field.optional ||
                field.defaultValue !== null && field.defaultValue !== undefined ||
                self.isArgument || self.isResult,
                'every field must be marked optional, required, or have a default value on ' +
                    self.name + ' including "' + field.name + '" in strict mode'
            );
        }
        if (self.isArgument && field.optional) {
            assert.ok(false, 'no field of an argument struct may be marked ' +
                'optional including ' + field.name + ' of ' + self.name);
        }
        field.required = field.required || self.isArgument;

    }

    self.Constructor = self.createConstructor(self.name, self.fields);
    self.Constructor.rw = self.rw;

    self.Constructor.fromBuffer = self.fromBuffer;
    self.Constructor.fromBufferResult = self.fromBufferResult;

    self.Constructor.toBuffer = self.toBuffer;
    self.Constructor.toBufferResult = self.toBufferResult;

    // Link field types later since they may depend on the constructor existing
    // first.
    spec[self.name] = self.Constructor;
    for (index = 0; index < self.fields.length; index++) {
        self.fields[index].link(spec);
    }

    return self;
};

// The following methods have alternate implementations for Exception and Union.

StructSpec.prototype.createConstructor = function createConstructor(name, fields) {
    var source;
    source = '(function thriftrw_' + name + '(options) {\n';
    for (var index = 0; index < fields.length; index++) {
        var field = fields[index];
        source += '    this.' + field.name + ' = null;\n';
        source += '    if (options && typeof options.' + field.name + ' !== "undefined") ' +
            '{ this.' + field.name + ' = options.' + field.name + '; }\n';
        if (field.defaultValue !== null) {
            source += '    else { this.' + field.name +
                ' = ' + JSON.stringify(field.defaultValue) + '; }\n';
        }
    }
    source += '})\n';
    // eval is an operator that captures the lexical scope of the calling
    // function and deoptimizes the lexical scope.
    // By using eval in an expression context, it loses this second-class
    // capability and becomes a first-class function.
    // (0, eval) is one way to use eval in an expression context.
    return (0, eval)(source);
};

StructSpec.prototype.create = function create() {
    var self = this;
    return new self.Constructor();
};

StructSpec.prototype.set = function set(struct, key, value) {
    struct[key] = value;
};

StructSpec.prototype.finalize = function finalize(struct) {
    return struct;
};

function StructRW(spec) {
    assert(spec, 'spec required');
    var self = this;
    self.spec = spec;
}

StructRW.prototype.byteLength = function byteLength(struct) {
    var self = this;
    var length = 1; // stop:1
    var result;
    for (var index = 0; index < self.spec.fields.length; index++) {
        var field = self.spec.fields[index];
        var value = struct && struct[field.name];

        var available = value !== null && value !== undefined;

        if (!available && field.required) {
            return new LengthResult(FieldRequiredError({
                name: field.name,
                id: field.id,
                structName: self.spec.name,
                what: struct
            }));
        }
        if (!available) {
            continue;
        }

        // TODO maybe suppress defaultValue on the wire

        // typeid:1
        // field.id:2
        length += 3;

        result = field.valueType.rw.byteLength(value);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        length += result.length;
    }
    return new LengthResult(null, length);
};

StructRW.prototype.writeInto = function writeInto(struct, buffer, offset) {
    var self = this;
    var result;
    for (var index = 0; index < self.spec.fields.length; index++) {
        var field = self.spec.fields[index];
        var value = struct && struct[field.name];
        var available = value !== null && value !== undefined;

        if (!available && field.required) {
            return new LengthResult(FieldRequiredError({
                name: field.name,
                id: field.id,
                structName: self.spec.name,
                what: struct
            }));
        }
        if (!available) {
            continue;
        }

        // TODO maybe suppress defaultValue on the wire

        result = bufrw.Int8.writeInto(field.valueType.typeid, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;

        result = bufrw.Int16BE.writeInto(field.id, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;

        result = field.valueType.rw.writeInto(value, buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
    }

    result = bufrw.Int8.writeInto(TYPE.STOP, buffer, offset);
    // istanbul ignore if
    if (result.err) {
        return result;
    }
    offset = result.offset;
    return new WriteResult(null, offset);
};

StructRW.prototype.readFrom = function readFrom(buffer, offset) {
    var self = this;
    var struct = self.spec.create();
    var result;

    for (;;) {
        result = bufrw.Int8.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        var typeid = result.value;

        if (typeid === TYPE.STOP) {
            break;
        }

        result = bufrw.Int16BE.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        var id = result.value;

        // skip unrecognized fields from THE FUTURE
        if (!self.spec.fieldsById[id]) {
            result = skipField(buffer, offset);
            // istanbul ignore if
            if (result.err) {
                return result;
            }
            offset = result.offset;
            continue;
        }

        var field = self.spec.fieldsById[id];
        if (field.valueType.typeid !== typeid) {
            return new ReadResult(UnexpectedFieldValueTypeidError({
                fieldId: id,
                fieldName: field.name,
                structName: self.spec.name,
                typeid: typeid,
                typeName: NAMES[typeid],
                expectedTypeid: field.valueType.typeid,
                expectedTypeName: NAMES[field.valueType.typeid]
            }));
        }

        result = field.valueType.rw.readFrom(buffer, offset);
        // istanbul ignore if
        if (result.err) {
            return result;
        }
        offset = result.offset;
        self.spec.set(struct, field.name, result.value);
    }

    return new ReadResult(null, offset, self.spec.finalize(struct));
};

module.exports.FieldSpec = FieldSpec;
module.exports.StructSpec = StructSpec;
module.exports.StructRW = StructRW;
<|endoftext|>


<commit_before>const BaseStyles = {};

BaseStyles.ReactBash = {
    borderRadius: '5px',
    fontFamily: '\'Inconsolata\', monospace',
    fontSize: '13px',
    fontWeight: '400',
    overflow: 'hidden',
    textAlign: 'left',
};

BaseStyles.header = {
    padding: '5px 10px 0',
};

const circle = {
    borderRadius: '50%',
    display: 'inline-block',
    height: '15px',
    marginRight: '5px',
    width: '15px',
};

BaseStyles.redCircle = Object.assign({}, circle, {
    backgroundColor: '#bf616a',
});

BaseStyles.yellowCircle = Object.assign({}, circle, {
    backgroundColor: '#ebcb8b',
});

BaseStyles.greenCircle = Object.assign({}, circle, {
    backgroundColor: '#a3be8c',
});

BaseStyles.body = {
    height: '400px',
    overflowY: 'scroll',
    padding: '10px',
};

BaseStyles.form = {
    display: 'flex',
};

BaseStyles.input = {
    background: 'none',
    border: 'none',
    color: 'inherit',
    flexGrow: '1',
    fontFamily: 'inherit',
    fontSize: 'inherit',
    outline: 'none !important',
    padding: '0',
};

BaseStyles.prefix = {
    marginRight: '5px',
};

export default {
    light: Object.assign({}, BaseStyles, {
        body: Object.assign({}, BaseStyles.body, {
            backgroundColor: '#fff',
            color: '#5D5D5D',
        }),
        header: Object.assign({}, BaseStyles.header, {
            backgroundColor: '#eee',
        }),
        prefix: Object.assign({}, BaseStyles.prefix, {
            color: '#bd081c',
        }),
    }),
    dark: Object.assign({}, BaseStyles, {
        body: Object.assign({}, BaseStyles.body, {
            backgroundColor: '#000',
            color: '#d0d0d0',
        }),
        header: Object.assign({}, BaseStyles.header, {
            backgroundColor: '#dcdbdb',
        }),
        prefix: Object.assign({}, BaseStyles.prefix, {
            color: '#5b65fb',
        }),
    }),
};
<commit_msg>Remove warning message<commit_after>const BaseStyles = {};

BaseStyles.ReactBash = {
    borderRadius: '5px',
    fontFamily: '\'Inconsolata\', monospace',
    fontSize: '13px',
    fontWeight: '400',
    overflow: 'hidden',
    textAlign: 'left',
};

BaseStyles.header = {
    padding: '5px 10px 0',
};

const circle = {
    borderRadius: '50%',
    display: 'inline-block',
    height: '15px',
    marginRight: '5px',
    width: '15px',
};

BaseStyles.redCircle = Object.assign({}, circle, {
    backgroundColor: '#bf616a',
});

BaseStyles.yellowCircle = Object.assign({}, circle, {
    backgroundColor: '#ebcb8b',
});

BaseStyles.greenCircle = Object.assign({}, circle, {
    backgroundColor: '#a3be8c',
});

BaseStyles.body = {
    height: '400px',
    overflowY: 'scroll',
    padding: '10px',
};

BaseStyles.form = {
    display: 'flex',
};

BaseStyles.input = {
    background: 'none',
    border: 'none',
    color: 'inherit',
    flexGrow: '1',
    fontFamily: 'inherit',
    fontSize: 'inherit',
    outline: 'none !important',
    padding: 0,
};

BaseStyles.prefix = {
    marginRight: '5px',
};

export default {
    light: Object.assign({}, BaseStyles, {
        body: Object.assign({}, BaseStyles.body, {
            backgroundColor: '#fff',
            color: '#5D5D5D',
        }),
        header: Object.assign({}, BaseStyles.header, {
            backgroundColor: '#eee',
        }),
        prefix: Object.assign({}, BaseStyles.prefix, {
            color: '#bd081c',
        }),
    }),
    dark: Object.assign({}, BaseStyles, {
        body: Object.assign({}, BaseStyles.body, {
            backgroundColor: '#000',
            color: '#d0d0d0',
        }),
        header: Object.assign({}, BaseStyles.header, {
            backgroundColor: '#dcdbdb',
        }),
        prefix: Object.assign({}, BaseStyles.prefix, {
            color: '#5b65fb',
        }),
    }),
};
<|endoftext|>


<commit_before>module.exports = {
    white:"\x030",
    black:"\x031",
    darkBlue:"\x032",
    darkGreen:"\x033",
    red:"\x034",
    darkRed:"\x035",
    darkViolet:"\x036",
    orange:"\x037",
    yellow:"\x038",
    lightGreen:"\x039",
    cyan:"\x0310",
    lightCyan:"\x0311",
    blue:"\x0312",
    pink:"\x0313",
    darkGrey:"\x0314",
    lightGrey:"\x0315",

    bold: "\x02",
    colour: "\x03",
    italic: "\x09",
    strikeThrough: "\x13",
    reset:"\x0f",
    underline:"\x15",
    underline2: "\x1f",
    reverse: "\x16"
}<commit_msg>changed colour names<commit_after>module.exports = {
    white:"\x030",
		lightgrey:"\x0315",
		darkgrey:"\x0314",
    black:"\x031",
		lightblue:"\x0311",
		blue:"\x0312",
    darkblue:"\x032",
		lightgreen:"\x039",
    darkgreen:"\x033",
    lightred:"\x034",
    darkred:"\x035",
    purple:"\x036",
    orange:"\x037",
    yellow:"\x038",
    turquoise:"\x0310",
    pink:"\x0313",

    bold: "\x02",
    colour: "\x03",
    italic: "\x09",
    strikethrough: "\x13",
    reset:"\x0f",
    underline:"\x15",
    underline2: "\x1f",
    reverse: "\x16"
}<|endoftext|>