<commit_before>/*

 *    Glossy Parser - Parse incoming syslog messages
 *
 *    Copyright Squeeks <privacymyass@gmail.com>.
 *     This is free software licensed under the MIT License -
 *     see the LICENSE file that should be included with this package.
 */

/*
 *    These values replace the integers in message that define the facility.
 */
var FacilityIndex = [
    "kern",     // kernel messages
    "user",     // user-level messages
    "mail",     // mail system
    "daemon",   // system daemons
    "auth",     // security/authorization messages
    "syslog",   // messages generated internally by syslogd
    "lpr",      // line printer subsystem
    "news",     // network news subsystem
    "uucp",     // UUCP subsystem
    "clock",    // clock daemon
    "sec",      // security/authorization messages
    "ftp",      // FTP daemon
    "ntp",      // NTP subsystem
    "audit",    // log audit
    "alert",    // log alert
    "clock",    // clock daemon (note 2)
    "local0",   // local use 0  (local0)
    "local1",   // local use 1  (local1)
    "local2",   // local use 2  (local2)
    "local3",   // local use 3  (local3)
    "local4",   // local use 4  (local4)
    "local5",   // local use 5  (local5)
    "local6",   // local use 6  (local6)
    "local7",   // local use 7  (local7)
];

// Note 1 - Various operating systems have been found to utilize
//           Facilities 4, 10, 13 and 14 for security/authorization,
//           audit, and alert messages which seem to be similar.

// Note 2 - Various operating systems have been found to utilize
//           both Facilities 9 and 15 for clock (cron/at) messages.

/*
 *    These values replace the integers in message that define the severity.
 */
var SeverityIndex = [
    "emerg",    // Emergency: system is unusable
    "alert",    // Alert: action must be taken immediately
    "crit",     // Critical: critical conditions
    "err",      // Error: error conditions
    "warn",     // Warning: warning conditions
    "notice",   // Notice: normal but significant condition
    "info",     // Informational: informational messages
    "debug"     // Debug: debug-level messages
];

/*
 *    Defines the range matching BSD style months to integers.
 */
var BSDDateIndex = {
    'Jan': 0,
    'Feb': 1,
    'Mar': 2,
    'Apr': 3,
    'May': 4,
    'Jun': 5,
    'Jul': 6,
    'Aug': 7,
    'Sep': 8,
    'Oct': 9,
    'Nov': 10,
    'Dec': 11
}

/*
 *  Parse the raw message received.
 *
 *  @param {String/Buffer} rawMessage Raw message received from socket
 *  @param {Function} callback Callback to run after parse is complete
 *  @return {Object} map containing all successfully parsed data.
 */
module.exports.parse = function(rawMessage, callback) {

    // Are you node.js? Is this a Buffer?
    if(typeof Buffer == 'function' && Buffer.isBuffer(rawMessage)) {
        rawMessage = rawMessage.toString('utf8', 0);
    } else if(typeof rawMessage != 'string') {
        return rawMessage;
    }

    // Always return the original message
    var parsedMessage = {
        originalMessage: rawMessage
    };

    var segments = rawMessage.split(/\s+/);

    var priKeys = decodePri(segments[0]);
    for (key in priKeys) {
        parsedMessage[key] = priKeys[key];
    }

    if(segments[0].match(/^(<\d+>\d)/)) {
        parsedMessage.type = 'RFC5424';
        segments.shift(); // Shift the prival off
        var timeStamp         = segments.shift();
        parsedMessage.time    = parseTimeStamp(timeStamp);
        parsedMessage.host    = decideValue(segments.shift());
        parsedMessage.appName = decideValue(segments.shift());
        parsedMessage.pid     = decideValue(segments.shift());
        parsedMessage.msgID   = decideValue(segments.shift());

        if(segments[0] !== '-') {
            var spliceMarker = 0;
            for (part in segments) {
                if(segments[part].substr(-1) === ']'){
                    spliceMarker = part;
                    spliceMarker++;
                    break;
                }
            }
            if(spliceMarker != 0) {
                var sd = segments.splice(0, spliceMarker).join(' ');
                parsedMessage.structuredData = parseStructure(sd);
            }
        } else {
            segments.shift(); // Shift the SD marker off
        }
        parsedMessage.message = segments.join(' ');

    } else if(segments[0].match(/^(<\d+>\w+)/)){
        parsedMessage.type    = 'RFC3164';
        var timeStamp         = segments.splice(0,3).join(' ').replace(/^(<\d+>)/,'');
        parsedMessage.time    = parseTimeStamp(timeStamp);
        parsedMessage.host    = segments.shift();
        parsedMessage.message = segments.join(' ');
    }

    if(callback) {
        callback(parsedMessage);
    } else {
        return parsedMessage;
    }

};

/*
 *  RFC5424 messages are supposed to specify '-' as the null value
 *  @param {String} a section from an RFC5424 message
 *  @return {Boolean/String} null if string is entirely '-', or the original value
 */
function decideValue(value) {
    if(value === '-') {
        return null;
    } else {
        return value;
    }
}

/*
 *  Parses the PRI value from the start of message
 *
 *  @param {String} message Supplied raw primary value and version
 *  @return {Object} Returns object containing Facility, Severity and Version
 *      if correctly parsed, empty values on failure.
 */
function decodePri(message)
{
    if(typeof message != 'string') return;

    var privalMatch = message.match(/^.*<(\d+)>(\d)/);
    if(!privalMatch) privalMatch = message.match(/^.*<(\d+)>/);

    var returnVal = {
        prival:  parseInt(privalMatch[1]),
    };

    if(privalMatch[2]) returnVal['version'] = parseInt(privalMatch[2]);

    if(returnVal.prival && returnVal.prival >= 0 && returnVal.prival <= 191) {

        returnVal.facilityID = parseInt(returnVal.prival / 8);
        returnVal.severityID = returnVal.prival - (returnVal.facilityID * 8);

        if(returnVal.facilityID < 24 && returnVal.severityID < 8) {
            returnVal.facility = FacilityIndex[returnVal.facilityID];
            returnVal.severity = SeverityIndex[returnVal.severityID];
        }
    }

    return returnVal;
}

/*
 *  Attempts to parse a given timestamp
 *  @param {String} timeStamp Supplied timestamp, should only be the timestamp,
 *      not the entire message
 *  @return {Object} Date object on success
 */
function parseTimeStamp(timeStamp)
{

    if(typeof timeStamp != 'string') return;

    var parsedTime;

    // Try RFC3339 Style (specified in RFC5424)
    // https://github.com/tardate/rfc3339date.js
    // This portion is Copyright (c) 2010 Paul GALLAGHER http://tardate.com
    var d = timeStamp.match(/(\d{4})(-)?(\d{2})(-)?(\d{2})(T)?(\d{2})(:)?(\d{2})?(:)?(\d{2})?([\.,]\d+)?($|Z|([+-])(\d{2})(:)?(\d{2})?)/i);
    if (d) {
        var year   = parseInt(d[1],10);
        var mon    = parseInt(d[3],10) - 1;
        var day    = parseInt(d[5],10);
        var hour   = parseInt(d[7],10);
        var mins   = ( d[9] ? parseInt(d[9],10) : 0 );
        var secs   = ( d[11] ? parseInt(d[11],10) : 0 );
        var millis = ( d[12] ? parseFloat(String(1.5).charAt(1) + d[12].slice(1)) * 1000 : 0 );
        if (d[13]) {
            parsedTime = new Date();
            parsedTime.setUTCFullYear(year);
            parsedTime.setUTCMonth(mon);
            parsedTime.setUTCDate(day);
            parsedTime.setUTCHours(hour);
            parsedTime.setUTCMinutes(mins);
            parsedTime.setUTCSeconds(secs);
            parsedTime.setUTCMilliseconds(millis);
            if (d[13] && d[14]) {
                var offset = (d[15] * 60)
                if (d[17]) offset += parseInt(d[17],10);
                offset *= ((d[14] == '-') ? -1 : 1);
                parsedTime.setTime(parsedTime.getTime() - offset * 60 * 1000);
            }

        } else {
            parsedTime = new Date(year,mon,day,hour,mins,secs,millis);
        }
    }

    if(parsedTime) return parsedTime;

    // Try BSD Style formatting (specified in RFC 3164)
    d = timeStamp.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})/);
    if(d) {
        // Years are absent from the specification, use this year
        currDate   = new Date();
        parsedTime = new Date(
            currDate.getUTCFullYear(),
            BSDDateIndex[ d[1] ],
            d[2],
            d[3],
            d[4],
            d[5]);
    }

    if(parsedTime) return parsedTime;

    // Try ISO 8601 (suggested in RFC 3164)
    d = timeStamp.match(/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/); //TODO: Less strict match? TZ designations?
    if(d) {
        parsedTime = new Date(d[1], d[2], d[3], d[4], d[5], d[6]);
    }

    return parsedTime;

}

/*
 *  Parse the structured data out of RFC5424 messages
 *  @param {String} msg The STRUCTURED-DATA section
 *  @return {Object} sdStructure parsed structure
 */
function parseStructure(msg) {

    var sdStructure = { };
    var sdElements  = msg.split('][');
    for(element in sdElements) {
        element = sdElements[element];
        element = element.replace(/\[|\]/g, '');

        var sdID = element.match(/^(\w+@\d+)\s/);
        element  = element.replace(sdID[0], '');
        var keys = element.split(/\s/);
        for(key in keys) {
            var sdKeyValue = keys[key].match(/^(.*)="(.*)"$/);
            if(sdKeyValue) {
                var sdKey      = sdKeyValue[1];
                var sdValue    = sdKeyValue[2];
                if(!sdStructure[sdID[1]]) sdStructure[sdID[1]] = { };
                sdStructure[sdID[1]][sdKey] = sdValue;
            }
        }
    }

    return sdStructure;
}
<commit_msg>Rewritten the structured data parser.<commit_after>/*

 *    Glossy Parser - Parse incoming syslog messages
 *
 *    Copyright Squeeks <privacymyass@gmail.com>.
 *     This is free software licensed under the MIT License -
 *     see the LICENSE file that should be included with this package.
 */

/*
 *    These values replace the integers in message that define the facility.
 */
var FacilityIndex = [
    "kern",     // kernel messages
    "user",     // user-level messages
    "mail",     // mail system
    "daemon",   // system daemons
    "auth",     // security/authorization messages
    "syslog",   // messages generated internally by syslogd
    "lpr",      // line printer subsystem
    "news",     // network news subsystem
    "uucp",     // UUCP subsystem
    "clock",    // clock daemon
    "sec",      // security/authorization messages
    "ftp",      // FTP daemon
    "ntp",      // NTP subsystem
    "audit",    // log audit
    "alert",    // log alert
    "clock",    // clock daemon (note 2)
    "local0",   // local use 0  (local0)
    "local1",   // local use 1  (local1)
    "local2",   // local use 2  (local2)
    "local3",   // local use 3  (local3)
    "local4",   // local use 4  (local4)
    "local5",   // local use 5  (local5)
    "local6",   // local use 6  (local6)
    "local7",   // local use 7  (local7)
];

// Note 1 - Various operating systems have been found to utilize
//           Facilities 4, 10, 13 and 14 for security/authorization,
//           audit, and alert messages which seem to be similar.

// Note 2 - Various operating systems have been found to utilize
//           both Facilities 9 and 15 for clock (cron/at) messages.

/*
 *    These values replace the integers in message that define the severity.
 */
var SeverityIndex = [
    "emerg",    // Emergency: system is unusable
    "alert",    // Alert: action must be taken immediately
    "crit",     // Critical: critical conditions
    "err",      // Error: error conditions
    "warn",     // Warning: warning conditions
    "notice",   // Notice: normal but significant condition
    "info",     // Informational: informational messages
    "debug"     // Debug: debug-level messages
];

/*
 *    Defines the range matching BSD style months to integers.
 */
var BSDDateIndex = {
    'Jan': 0,
    'Feb': 1,
    'Mar': 2,
    'Apr': 3,
    'May': 4,
    'Jun': 5,
    'Jul': 6,
    'Aug': 7,
    'Sep': 8,
    'Oct': 9,
    'Nov': 10,
    'Dec': 11
}

/*
 *  Parse the raw message received.
 *
 *  @param {String/Buffer} rawMessage Raw message received from socket
 *  @param {Function} callback Callback to run after parse is complete
 *  @return {Object} map containing all successfully parsed data.
 */
module.exports.parse = function(rawMessage, callback) {

    // Are you node.js? Is this a Buffer?
    if(typeof Buffer == 'function' && Buffer.isBuffer(rawMessage)) {
        rawMessage = rawMessage.toString('utf8', 0);
    } else if(typeof rawMessage != 'string') {
        return rawMessage;
    }

    // Always return the original message
    var parsedMessage = {
        originalMessage: rawMessage
    };

    var segments = rawMessage.split(/\s+/);

    var priKeys = decodePri(segments[0]);
    for (key in priKeys) {
        parsedMessage[key] = priKeys[key];
    }

    if(segments[0].match(/^(<\d+>\d)/)) {
        parsedMessage.type = 'RFC5424';
        segments.shift(); // Shift the prival off
        var timeStamp         = segments.shift();
        parsedMessage.time    = parseTimeStamp(timeStamp);
        parsedMessage.host    = decideValue(segments.shift());
        parsedMessage.appName = decideValue(segments.shift());
        parsedMessage.pid     = decideValue(segments.shift());
        parsedMessage.msgID   = decideValue(segments.shift());

        if(segments[0] !== '-') {
            var spliceMarker = 0;
            for (part in segments) {
                if(segments[part].substr(-1) === ']'){
                    spliceMarker = part;
                    spliceMarker++;
                    break;
                }
            }
            if(spliceMarker != 0) {
                var sd = segments.splice(0, spliceMarker).join(' ');
                parsedMessage.structuredData = parseStructure(sd);
            }
        } else {
            segments.shift(); // Shift the SD marker off
        }
        parsedMessage.message = segments.join(' ');

    } else if(segments[0].match(/^(<\d+>\w+)/)){
        parsedMessage.type    = 'RFC3164';
        var timeStamp         = segments.splice(0,3).join(' ').replace(/^(<\d+>)/,'');
        parsedMessage.time    = parseTimeStamp(timeStamp);
        parsedMessage.host    = segments.shift();
        parsedMessage.message = segments.join(' ');
    }

    if(callback) {
        callback(parsedMessage);
    } else {
        return parsedMessage;
    }

};

/*
 *  RFC5424 messages are supposed to specify '-' as the null value
 *  @param {String} a section from an RFC5424 message
 *  @return {Boolean/String} null if string is entirely '-', or the original value
 */
function decideValue(value) {
    if(value === '-') {
        return null;
    } else {
        return value;
    }
}

/*
 *  Parses the PRI value from the start of message
 *
 *  @param {String} message Supplied raw primary value and version
 *  @return {Object} Returns object containing Facility, Severity and Version
 *      if correctly parsed, empty values on failure.
 */
function decodePri(message)
{
    if(typeof message != 'string') return;

    var privalMatch = message.match(/^.*<(\d+)>(\d)/);
    if(!privalMatch) privalMatch = message.match(/^.*<(\d+)>/);

    var returnVal = {
        prival:  parseInt(privalMatch[1]),
    };

    if(privalMatch[2]) returnVal['version'] = parseInt(privalMatch[2]);

    if(returnVal.prival && returnVal.prival >= 0 && returnVal.prival <= 191) {

        returnVal.facilityID = parseInt(returnVal.prival / 8);
        returnVal.severityID = returnVal.prival - (returnVal.facilityID * 8);

        if(returnVal.facilityID < 24 && returnVal.severityID < 8) {
            returnVal.facility = FacilityIndex[returnVal.facilityID];
            returnVal.severity = SeverityIndex[returnVal.severityID];
        }
    }

    return returnVal;
}

/*
 *  Attempts to parse a given timestamp
 *  @param {String} timeStamp Supplied timestamp, should only be the timestamp,
 *      not the entire message
 *  @return {Object} Date object on success
 */
function parseTimeStamp(timeStamp)
{

    if(typeof timeStamp != 'string') return;

    var parsedTime;

    // Try RFC3339 Style (specified in RFC5424)
    // https://github.com/tardate/rfc3339date.js
    // This portion is Copyright (c) 2010 Paul GALLAGHER http://tardate.com
    var d = timeStamp.match(/(\d{4})(-)?(\d{2})(-)?(\d{2})(T)?(\d{2})(:)?(\d{2})?(:)?(\d{2})?([\.,]\d+)?($|Z|([+-])(\d{2})(:)?(\d{2})?)/i);
    if (d) {
        var year   = parseInt(d[1],10);
        var mon    = parseInt(d[3],10) - 1;
        var day    = parseInt(d[5],10);
        var hour   = parseInt(d[7],10);
        var mins   = ( d[9] ? parseInt(d[9],10) : 0 );
        var secs   = ( d[11] ? parseInt(d[11],10) : 0 );
        var millis = ( d[12] ? parseFloat(String(1.5).charAt(1) + d[12].slice(1)) * 1000 : 0 );
        if (d[13]) {
            parsedTime = new Date();
            parsedTime.setUTCFullYear(year);
            parsedTime.setUTCMonth(mon);
            parsedTime.setUTCDate(day);
            parsedTime.setUTCHours(hour);
            parsedTime.setUTCMinutes(mins);
            parsedTime.setUTCSeconds(secs);
            parsedTime.setUTCMilliseconds(millis);
            if (d[13] && d[14]) {
                var offset = (d[15] * 60)
                if (d[17]) offset += parseInt(d[17],10);
                offset *= ((d[14] == '-') ? -1 : 1);
                parsedTime.setTime(parsedTime.getTime() - offset * 60 * 1000);
            }

        } else {
            parsedTime = new Date(year,mon,day,hour,mins,secs,millis);
        }
    }

    if(parsedTime) return parsedTime;

    // Try BSD Style formatting (specified in RFC 3164)
    d = timeStamp.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})/);
    if(d) {
        // Years are absent from the specification, use this year
        currDate   = new Date();
        parsedTime = new Date(
            currDate.getUTCFullYear(),
            BSDDateIndex[ d[1] ],
            d[2],
            d[3],
            d[4],
            d[5]);
    }

    if(parsedTime) return parsedTime;

    // Try ISO 8601 (suggested in RFC 3164)
    d = timeStamp.match(/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/); //TODO: Less strict match? TZ designations?
    if(d) {
        parsedTime = new Date(d[1], d[2], d[3], d[4], d[5], d[6]);
    }

    return parsedTime;

}

/*
 *  Parse the structured data out of RFC5424 messages
 *  @param {String} msg The STRUCTURED-DATA section
 *  @return {Object} sdStructure parsed structure
 */
function parseStructure(msg) {
    var sdStructure = { };
    var sdElements  = msg.split('][');
    for(element in sdElements) {
        var element = sdElements[element];
            element = element.replace(/^\[|\]$/g, '');
        var sdID    = element.match(/^([^\s=\]]+)\s/)[1];
            element = element.replace(sdID + ' ', '');
        var sdKeys  = element.split(/"\s/);

        for(key in sdKeys) {
            var sdKeyValue = sdKeys[key].match(/^([^\s=\]]+)="(.*)$/);
            if(!sdKeyValue) continue;
            var sdKey    = sdKeyValue[1];
            var sdValue  = sdKeyValue[2];
            if(!sdStructure[sdID]) sdStructure[sdID] = { };
            sdStructure[sdID][sdKey] = sdValue;
        }

    }

    return sdStructure;
}
<|endoftext|>


<commit_before>/**
 * Base class for creating other shapes.
 * Each custom shape must extends from this class.
 *
 * @since 1.0.0
 * @version 1.0.0
 * @example
 * import { Shape } from './src/shapes/Shape';
 *
 * export class Rectangle extends Shape {
 *   constructor(...args) {
 *     super(...args);
 *   }
 *
 *   render(cursor) {
 *     // Implement your logic here for rendering the shape
 *   }
 * }
 */
export class Shape {
  _text = '';
  _width = 15;
  _height = 5;
  _x = 10;
  _y = 10;
  _background;
  _foreground;

  /**
   * Constructor is responsible for initializing base properties.
   * Don't forgot to call `super(...args)` when extending from this class.
   *
   * @constructor
   * @param {Object} [options]
   * @param {String} [options.text] Text that will be rendered in shape
   * @param {Number} [options.width] Shape width
   * @param {Number} [options.height] Shape height
   * @param {Number} [options.x] Absolute coordinate X
   * @param {Number} [options.y] Absolute coordinate Y
   * @param {String} [options.background] Background color from {@link COLORS}
   * @param {String} [options.foreground] Foreground color from {@link COLORS}
   */
  constructor(options = {}) {
    let {text, width, height, x, y, background, foreground} = options;

    this.setText(text);
    this.setWidth(width);
    this.setHeight(height);
    this.setPosition(x, y);
    this.setBackground(background);
    this.setForeground(foreground);
  }

  /**
   * Get text content from this shape.
   *
   * @returns {String}
   */
  getText() {
    return this._text;
  }

  /**
   * Set new text content to this shape.
   *
   * @param {String} [text=''] New text
   * @returns {Shape}
   */
  setText(text = '') {
    this._text = text;
    return this;
  }

  /**
   * Get shape width.
   *
   * @returns {Number}
   */
  getWidth() {
    return this._width;
  }

  /**
   * Set new shape width.
   *
   * @param {Number} [width=15] Shape width
   * @returns {Shape}
   */
  setWidth(width = 15) {
    this._width = width;
    return this;
  }

  /**
   * Get shape height.
   *
   * @returns {Number}
   */
  getHeight() {
    return this._height;
  }

  /**
   * Set new shape height.
   *
   * @param {Number} [height=5] Shape height
   * @returns {Shape}
   */
  setHeight(height = 5) {
    this._height = height;
    return this;
  }

  /**
   * Get current position of shape.
   *
   * @returns {{x: Number, y: Number}}
   */
  getPosition() {
    return {x: this._x, y: this._y};
  }

  /**
   * Set new shape position.
   *
   * @param {Number} [x=10] Absolute coordinate X
   * @param {Number} [y=10] Absolute coordinate Y
   * @returns {Shape}
   */
  setPosition(x = this._x || 10, y = this._y || 10) {
    this._x = x;
    this._y = y;
    return this;
  }

  /**
   * Get background color.
   *
   * @returns {String}
   */
  getBackground() {
    return this._background;
  }

  /**
   * Set new background color.
   *
   * @param {String} background Background color from {@link COLORS}
   * @returns {Shape}
   */
  setBackground(background) {
    this._background = background;
    return this;
  }

  /**
   * Get foreground color.
   *
   * @returns {String}
   */
  getForeground() {
    return this._foreground;
  }

  /**
   * Set new foreground color.
   *
   * @param {String} foreground Foreground color from {@link COLORS}
   * @returns {Shape}
   */
  setForeground(foreground) {
    this._foreground = foreground;
    return this;
  }

  /**
   * Base render method that must be implemented in childes.
   *
   * @abstract
   * @param {Cursor} cursor Cursor instance that you can use for render the shape
   * @throws {Error} Throws error if method will not be overridden
   */
  render(cursor) {
    throw new Error('render() method must be implemented');
  }

  /**
   * Wrapper around `new Shape()`.
   *
   * @param {*} args
   * @returns {Shape}
   */
  static create(...args) {
    return new this(...args);
  }
}
<commit_msg>refactor(shape): Removes unreachable default param in setPosition<commit_after>/**
 * Base class for creating other shapes.
 * Each custom shape must extends from this class.
 *
 * @since 1.0.0
 * @version 1.0.0
 * @example
 * import { Shape } from './src/shapes/Shape';
 *
 * export class Rectangle extends Shape {
 *   constructor(...args) {
 *     super(...args);
 *   }
 *
 *   render(cursor) {
 *     // Implement your logic here for rendering the shape
 *   }
 * }
 */
export class Shape {
  _text = '';
  _width = 15;
  _height = 5;
  _x = 10;
  _y = 10;
  _background;
  _foreground;

  /**
   * Constructor is responsible for initializing base properties.
   * Don't forgot to call `super(...args)` when extending from this class.
   *
   * @constructor
   * @param {Object} [options]
   * @param {String} [options.text] Text that will be rendered in shape
   * @param {Number} [options.width] Shape width
   * @param {Number} [options.height] Shape height
   * @param {Number} [options.x] Absolute coordinate X
   * @param {Number} [options.y] Absolute coordinate Y
   * @param {String} [options.background] Background color from {@link COLORS}
   * @param {String} [options.foreground] Foreground color from {@link COLORS}
   */
  constructor(options = {}) {
    let {text, width, height, x, y, background, foreground} = options;

    this.setText(text);
    this.setWidth(width);
    this.setHeight(height);
    this.setPosition(x, y);
    this.setBackground(background);
    this.setForeground(foreground);
  }

  /**
   * Get text content from this shape.
   *
   * @returns {String}
   */
  getText() {
    return this._text;
  }

  /**
   * Set new text content to this shape.
   *
   * @param {String} [text=''] New text
   * @returns {Shape}
   */
  setText(text = '') {
    this._text = text;
    return this;
  }

  /**
   * Get shape width.
   *
   * @returns {Number}
   */
  getWidth() {
    return this._width;
  }

  /**
   * Set new shape width.
   *
   * @param {Number} [width=15] Shape width
   * @returns {Shape}
   */
  setWidth(width = 15) {
    this._width = width;
    return this;
  }

  /**
   * Get shape height.
   *
   * @returns {Number}
   */
  getHeight() {
    return this._height;
  }

  /**
   * Set new shape height.
   *
   * @param {Number} [height=5] Shape height
   * @returns {Shape}
   */
  setHeight(height = 5) {
    this._height = height;
    return this;
  }

  /**
   * Get current position of shape.
   *
   * @returns {{x: Number, y: Number}}
   */
  getPosition() {
    return {x: this._x, y: this._y};
  }

  /**
   * Set new shape position.
   *
   * @param {Number} [x=10] Absolute coordinate X
   * @param {Number} [y=10] Absolute coordinate Y
   * @returns {Shape}
   */
  setPosition(x = this._x, y = this._y) {
    this._x = x;
    this._y = y;
    return this;
  }

  /**
   * Get background color.
   *
   * @returns {String}
   */
  getBackground() {
    return this._background;
  }

  /**
   * Set new background color.
   *
   * @param {String} background Background color from {@link COLORS}
   * @returns {Shape}
   */
  setBackground(background) {
    this._background = background;
    return this;
  }

  /**
   * Get foreground color.
   *
   * @returns {String}
   */
  getForeground() {
    return this._foreground;
  }

  /**
   * Set new foreground color.
   *
   * @param {String} foreground Foreground color from {@link COLORS}
   * @returns {Shape}
   */
  setForeground(foreground) {
    this._foreground = foreground;
    return this;
  }

  /**
   * Base render method that must be implemented in childes.
   *
   * @abstract
   * @param {Cursor} cursor Cursor instance that you can use for render the shape
   * @throws {Error} Throws error if method will not be overridden
   */
  render(cursor) {
    throw new Error('render() method must be implemented');
  }

  /**
   * Wrapper around `new Shape()`.
   *
   * @param {*} args
   * @returns {Shape}
   */
  static create(...args) {
    return new this(...args);
  }
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

		if ( device.platform == 'android' || device.platform == 'Android' )
		{
			pushNotification.register(
				successHandler,
				errorHandler, {
					"senderID":"replace_with_sender_id",
					"ecb":"onNotificationGCM"
				});
		}
		else
		{
			pushNotification.register(
				tokenHandler,
				errorHandler, {
					"badge":"true",
					"sound":"true",
					"alert":"true",
					"ecb":"onNotificationAPN"
				});
		}

				// result contains any message sent from the plugin call
		function successHandler (result) {
			alert('result = ' + result);
		}

				// result contains any error description text returned from the plugin call
		function errorHandler (error) {
			alert('error = ' + error);
		}

		function tokenHandler (result) {
			// Your iOS push server needs to know the token before it can push to this device
			// here is where you might want to send it the token for later use.
			alert('device token = ' + result);
		}

// iOS
function onNotificationAPN (event) {
    if ( event.alert )
    {
        navigator.notification.alert(event.alert);
    }

    if ( event.sound )
    {
        var snd = new Media(event.sound);
        snd.play();
    }

    if ( event.badge )
    {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
    }
}

// Android
function onNotificationGCM(e) {
    $("#app-status-ul").append('
EVENT -> RECEIVED:' + e.event + '
');

    switch( e.event )
    {
    case 'registered':
        if ( e.regid.length > 0 )
        {
            $("#app-status-ul").append('
REGISTERED -> REGID:' + e.regid + "
");
            // Your GCM push server needs to know the regID before it can push to this device
            // here is where you might want to send it the regID for later use.
            console.log("regID = " + e.regid);
        }
    break;

    case 'message':
        // if this flag is set, this notification happened while we were in the foreground.
        // you might want to play a sound to get the user's attention, throw up a dialog, etc.
        if ( e.foreground )
        {
            $("#app-status-ul").append('
--INLINE NOTIFICATION--' + '
');

            // if the notification contains a soundname, play it.
            var my_media = new Media("/android_asset/www/"+e.soundname);
            my_media.play();
        }
        else
        {  // otherwise we were launched because the user touched a notification in the notification tray.
            if ( e.coldstart )
            {
                $("#app-status-ul").append('
--COLDSTART NOTIFICATION--' + '
');
            }
            else
            {
                $("#app-status-ul").append('
--BACKGROUND NOTIFICATION--' + '
');
            }
        }

        $("#app-status-ul").append('
MESSAGE -> MSG: ' + e.payload.message + '
');
        $("#app-status-ul").append('
MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '
');
    break;

    case 'error':
        $("#app-status-ul").append('
ERROR -> MSG:' + e.msg + '
');
    break;

    default:
        $("#app-status-ul").append('
EVENT -> Unknown, an event was received and we do not know what it is
');
    break;
  }
}

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};
<commit_msg>More debug messages, added app id<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

		if ( device.platform == 'android' || device.platform == 'Android' )
		{
			alert('device ready; android ' + pushNotification);
			pushNotification.register(
				successHandler,
				errorHandler, {
					"senderID":"102182143483",
					"ecb":"onNotificationGCM"
				});
		}
		else
		{
			alert('device ready; not android');
			pushNotification.register(
				tokenHandler,
				errorHandler, {
					"badge":"true",
					"sound":"true",
					"alert":"true",
					"ecb":"onNotificationAPN"
				});
		}

				// result contains any message sent from the plugin call
		function successHandler (result) {
			alert('registration success result = ' + result);
		}

				// result contains any error description text returned from the plugin call
		function errorHandler (error) {
			alert('registration error = ' + error);
		}

		function tokenHandler (result) {
			// Your iOS push server needs to know the token before it can push to this device
			// here is where you might want to send it the token for later use.
			alert('registration success device token = ' + result);
		}

// iOS
function onNotificationAPN (event) {
    if ( event.alert )
    {
        navigator.notification.alert(event.alert);
    }

    if ( event.sound )
    {
        var snd = new Media(event.sound);
        snd.play();
    }

    if ( event.badge )
    {
        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
    }
}

// Android
function onNotificationGCM(e) {
    $("#app-status-ul").append('
EVENT -> RECEIVED:' + e.event + '
');

    switch( e.event )
    {
    case 'registered':
        if ( e.regid.length > 0 )
        {
            $("#app-status-ul").append('
REGISTERED -> REGID:' + e.regid + "
");
            // Your GCM push server needs to know the regID before it can push to this device
            // here is where you might want to send it the regID for later use.
            console.log("regID = " + e.regid);
        }
    break;

    case 'message':
        // if this flag is set, this notification happened while we were in the foreground.
        // you might want to play a sound to get the user's attention, throw up a dialog, etc.
        if ( e.foreground )
        {
            $("#app-status-ul").append('
--INLINE NOTIFICATION--' + '
');

            // if the notification contains a soundname, play it.
            var my_media = new Media("/android_asset/www/"+e.soundname);
            my_media.play();
        }
        else
        {  // otherwise we were launched because the user touched a notification in the notification tray.
            if ( e.coldstart )
            {
                $("#app-status-ul").append('
--COLDSTART NOTIFICATION--' + '
');
            }
            else
            {
                $("#app-status-ul").append('
--BACKGROUND NOTIFICATION--' + '
');
            }
        }

        $("#app-status-ul").append('
MESSAGE -> MSG: ' + e.payload.message + '
');
        $("#app-status-ul").append('
MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '
');
    break;

    case 'error':
        $("#app-status-ul").append('
ERROR -> MSG:' + e.msg + '
');
    break;

    default:
        $("#app-status-ul").append('
EVENT -> Unknown, an event was received and we do not know what it is
');
    break;
  }
}

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};
<|endoftext|>


<commit_before>(function () {
    "use strict";

    var fs = require('fs');
    var _ = require('lodash');
    var q = require('q');
    var google = require('googleapis');

    var oauth2Client;

    var googleDriveMountPoint = '';
    var googleDriveConfig = {};

    var defaultGoogleDriveConfig = function () {
        return {
            clientSecret: null,
            fileTitle: 'your_keepass_db.kdbx',
            targetFilename: __dirname + '/local/google-drive.kdbx',
            clientSecretFilename: __dirname + '/local/googleapis_client_secret.json',
            clientSecretType: 'web',
//    clientSecretType: 'installed',
            tokensFilename: __dirname + '/local/googleapis_tokens.json',
            oauth2Tokens: {}
        };
    };

    var readAccessToken = function () {
        if (!_.isEmpty(googleDriveConfig.oauth2Tokens)) {
            return googleDriveConfig.oauth2Tokens;
        }

        if (fs.existsSync(googleDriveConfig.tokensFilename)) {
            googleDriveConfig.oauth2Tokens = JSON.parse(fs.readFileSync(googleDriveConfig.tokensFilename, 'utf8'));
            return googleDriveConfig.oauth2Tokens;
        }

        return null;
    };

    var requestAccessToken = function (oauth2Client, code) {
        var deferred = q.defer();

        oauth2Client.getToken(code, function (err, tokens) {
            if (err) {
                deferred.reject(err);
            }
            else {
                deferred.resolve(tokens);
            }
        });

        return deferred.promise;
    };

    var downloadFile = function (oauth2Client, item) {
        var deferred = q.defer();

        var options = {
            uri: item.downloadUrl,
            encoding: null
        };
        oauth2Client.request(options, function (error, body, response) {
            if (response.statusCode == 200) {
                fs.writeFileSync(googleDriveConfig.targetFilename, body);
                deferred.resolve();
            }
            else {
                console.log('got response with status code ' + response.statusCode);
                deferred.reject();
            }
        });

        return deferred.promise;
    };

    var readKeepass2File = function (oauth2Client) {
        var deferred = q.defer();

        var drive = google.drive({version: 'v2', auth: oauth2Client});
        drive.files.list(
                {},
                function (err, result) {
                    if (err) {
                        deferred.reject(err);
                    }
                    else {
                        var keepassFile = _.find(result.items, function (item) {
                            return item.title == googleDriveConfig.fileTitle;
                        });
                        deferred.resolve(keepassFile);
                    }
                });

        return deferred.promise;
    };

    var updateKdbxFromDrive = function () {
        oauth2Client.setCredentials(googleDriveConfig.oauth2Tokens);
        return readKeepass2File(oauth2Client).then(function (keepass2File) {
            downloadFile(oauth2Client, keepass2File);
        });
    };

    var middleware = function (req, res, next) {
        if (req.path == '/oauth2callback' && req.query.code) {
            console.log('requestAccessToken...');
            requestAccessToken(oauth2Client, req.query.code).then(function (result) {
                console.log('requestoken:' + JSON.stringify(googleDriveConfig.oauth2Tokens));
                console.log('save requestAccessToken to "' + googleDriveConfig.tokensFilename + '"...');
                googleDriveConfig.oauth2Tokens = result;
                fs.writeFileSync(googleDriveConfig.tokensFilename, JSON.stringify(googleDriveConfig.oauth2Tokens), 'utf8');

                console.log('redirect to ' + googleDriveMountPoint + '...');
                res.redirect(googleDriveMountPoint);
            }, function (reason) {
                console.log('could not request access token! reason: ' + JSON.stringify(reason));
                res.writeHeader(500, {"Content-Type": "text/html"});
                res.write('
could not request access token! reason: ' + JSON.stringify(reason) + '
');
                res.end();
            });
        }
        else if (req.path == '/') {
            if (!_.isEmpty(googleDriveConfig.oauth2Tokens)) {
                console.log('updateKdbxFromDrive...');
                updateKdbxFromDrive().then(function () {
                    res.redirect('/');
                }, function (reason) {
                    console.log('updateKdbxFromDrive() failed! reason: ' + JSON.stringify(reason));
                    res.writeHeader(500, {"Content-Type": "text/html"});
                    res.write('
updateKdbxFromDrive() failed! reason: ' + JSON.stringify(reason) + '
');
                    res.end();
                });
            }
            else {
                console.log('generateAuthUrl...');
                var opts = {
                    access_type: 'offline', // will return a refresh token
                    // see https://developers.google.com/drive/web/scopes
//          scope: 'https://www.googleapis.com/auth/drive'
                    scope: 'https://www.googleapis.com/auth/drive.readonly'
                };
                var authUrl = oauth2Client.generateAuthUrl(opts);
                res.redirect(authUrl);
            }
        }
        else {
            console.log('next...');
            next();
        }
    };

    var initialize = function (mountPoint, config) {
        googleDriveMountPoint = mountPoint;
        googleDriveConfig = _.extend(defaultGoogleDriveConfig(), config);

        if (!googleDriveConfig.clientSecret) {
            if (fs.existsSync(googleDriveConfig.clientSecretFilename)) {
                googleDriveConfig.clientSecret = require(googleDriveConfig.clientSecretFilename)[googleDriveConfig.clientSecretType];
            }
        }
        if (googleDriveConfig.clientSecret) {
            var OAuth2 = google.auth.OAuth2;
            oauth2Client = new OAuth2(
                    googleDriveConfig.clientSecret.client_id,
                    googleDriveConfig.clientSecret.client_secret,
                    googleDriveConfig.clientSecret.redirect_uris[0]);
        }

        readAccessToken();
    };

    module.exports = function (mountPoint, config) {

        initialize(mountPoint, config);

        if (!googleDriveConfig.clientSecret || !oauth2Client) {
            console.log('google-drive middleware initialization failed!');
        }

        return middleware;
    };
})();
<commit_msg>remove some log output<commit_after>(function () {
    "use strict";

    var fs = require('fs');
    var _ = require('lodash');
    var q = require('q');
    var google = require('googleapis');

    var oauth2Client;

    var googleDriveMountPoint = '';
    var googleDriveConfig = {};

    var defaultGoogleDriveConfig = function () {
        return {
            clientSecret: null,
            fileTitle: 'your_keepass_db.kdbx',
            targetFilename: __dirname + '/local/google-drive.kdbx',
            clientSecretFilename: __dirname + '/local/googleapis_client_secret.json',
            clientSecretType: 'web',
//    clientSecretType: 'installed',
            tokensFilename: __dirname + '/local/googleapis_tokens.json',
            oauth2Tokens: {}
        };
    };

    var readAccessToken = function () {
        if (!_.isEmpty(googleDriveConfig.oauth2Tokens)) {
            return googleDriveConfig.oauth2Tokens;
        }

        if (fs.existsSync(googleDriveConfig.tokensFilename)) {
            googleDriveConfig.oauth2Tokens = JSON.parse(fs.readFileSync(googleDriveConfig.tokensFilename, 'utf8'));
            return googleDriveConfig.oauth2Tokens;
        }

        return null;
    };

    var requestAccessToken = function (oauth2Client, code) {
        var deferred = q.defer();

        oauth2Client.getToken(code, function (err, tokens) {
            if (err) {
                deferred.reject(err);
            }
            else {
                deferred.resolve(tokens);
            }
        });

        return deferred.promise;
    };

    var downloadFile = function (oauth2Client, item) {
        var deferred = q.defer();

        var options = {
            uri: item.downloadUrl,
            encoding: null
        };
        oauth2Client.request(options, function (error, body, response) {
            if (response.statusCode == 200) {
                fs.writeFileSync(googleDriveConfig.targetFilename, body);
                deferred.resolve();
            }
            else {
                console.log('got response with status code ' + response.statusCode);
                deferred.reject();
            }
        });

        return deferred.promise;
    };

    var readKeepass2File = function (oauth2Client) {
        var deferred = q.defer();

        var drive = google.drive({version: 'v2', auth: oauth2Client});
        drive.files.list(
                {},
                function (err, result) {
                    if (err) {
                        deferred.reject(err);
                    }
                    else {
                        var keepassFile = _.find(result.items, function (item) {
                            return item.title == googleDriveConfig.fileTitle;
                        });
                        deferred.resolve(keepassFile);
                    }
                });

        return deferred.promise;
    };

    var updateKdbxFromDrive = function () {
        oauth2Client.setCredentials(googleDriveConfig.oauth2Tokens);
        return readKeepass2File(oauth2Client).then(function (keepass2File) {
            downloadFile(oauth2Client, keepass2File);
        });
    };

    var middleware = function (req, res, next) {
        if (req.path == '/oauth2callback' && req.query.code) {
            console.log('requestAccessToken...');
            requestAccessToken(oauth2Client, req.query.code).then(function (result) {
                console.log('requestoken:' + JSON.stringify(googleDriveConfig.oauth2Tokens));
                console.log('save requestAccessToken to "' + googleDriveConfig.tokensFilename + '"...');
                googleDriveConfig.oauth2Tokens = result;
                fs.writeFileSync(googleDriveConfig.tokensFilename, JSON.stringify(googleDriveConfig.oauth2Tokens), 'utf8');

                console.log('redirect to ' + googleDriveMountPoint + '...');
                res.redirect(googleDriveMountPoint);
            }, function (reason) {
                console.log('could not request access token! reason: ' + JSON.stringify(reason));
                res.writeHeader(500, {"Content-Type": "text/html"});
                res.write('
could not request access token! reason: ' + JSON.stringify(reason) + '
');
                res.end();
            });
        }
        else if (req.path == '/') {
            if (!_.isEmpty(googleDriveConfig.oauth2Tokens)) {
                console.log('updateKdbxFromDrive...');
                updateKdbxFromDrive().then(function () {
                    res.redirect('/');
                }, function (reason) {
                    console.log('updateKdbxFromDrive() failed! reason: ' + JSON.stringify(reason));
                    res.writeHeader(500, {"Content-Type": "text/html"});
                    res.write('
updateKdbxFromDrive() failed! reason: ' + JSON.stringify(reason) + '
');
                    res.end();
                });
            }
            else {
                //console.log('generateAuthUrl...');
                var opts = {
                    access_type: 'offline', // will return a refresh token
                    // see https://developers.google.com/drive/web/scopes
//          scope: 'https://www.googleapis.com/auth/drive'
                    scope: 'https://www.googleapis.com/auth/drive.readonly'
                };
                var authUrl = oauth2Client.generateAuthUrl(opts);
                res.redirect(authUrl);
            }
        }
        else {
            next();
        }
    };

    var initialize = function (mountPoint, config) {
        googleDriveMountPoint = mountPoint;
        googleDriveConfig = _.extend(defaultGoogleDriveConfig(), config);

        if (!googleDriveConfig.clientSecret) {
            if (fs.existsSync(googleDriveConfig.clientSecretFilename)) {
                googleDriveConfig.clientSecret = require(googleDriveConfig.clientSecretFilename)[googleDriveConfig.clientSecretType];
            }
        }
        if (googleDriveConfig.clientSecret) {
            var OAuth2 = google.auth.OAuth2;
            oauth2Client = new OAuth2(
                    googleDriveConfig.clientSecret.client_id,
                    googleDriveConfig.clientSecret.client_secret,
                    googleDriveConfig.clientSecret.redirect_uris[0]);
        }

        readAccessToken();
    };

    module.exports = function (mountPoint, config) {

        initialize(mountPoint, config);

        if (!googleDriveConfig.clientSecret || !oauth2Client) {
            console.log('google-drive middleware initialization failed!');
        }

        return middleware;
    };
})();
<|endoftext|>


<commit_before>var app = angular.module('myApp', []);
app.controller('formHide', function($scope){
	$scope.buy = true;
	var storedData = myApp.formGetData('buyform');
	if (storedData){
	$scope.metreName = storedData.metreName;
	$scope.metre = storedData.metre;}
	$scope.switcher = true;
	$scope.regswitcher = true;
	$scope.changebtn = function(){
		if (($$("#select-metre").val() !== "") &&($$("#amt").val() !== "")){
		$scope.switcher = false;
		}
		else {
		$scope.switcher = true;
		}
	}

	$scope.regchangebtn = function(){
		if (($$("#metre").val() !== "") && ($$("#metreName").val() !== "")){
		$scope.regswitcher = false;
		}
		else {
		$scope.regswitcher = true;
		}
	}

	$scope.cancelbtn = function(){
		$$("#metre").val(parseInt('')).trigger('change');
		$$("#metreName").val('').trigger('change');
		$scope.reg = false;
		$scope.buy = true;
		loadOptions();
		$$('#regFab').html('&nbsp New');
	}

	$scope.savebtn = function(){
		metreNumber = $$("#metre").val();
		metreName = $$("#metreName").val();
		db.transaction(function(tx) {tx.executeSql('INSERT INTO metreNumbers values(' + metreNumber +',"'+ metreName + '")');}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){});
		$scope.reg = false;
		$scope.buy = true;
		myApp.formDeleteData('buyform');
		loadOptions();
		$scope.metreName = '';
		$scope.metre = '';
		$$('#regFab').html('&nbsp New');
	}

	$scope.openForm = function(){
		if ($scope.buy == true){
		$$('#regFab').html('buy');
		$scope.buy = false;
		$scope.reg = true;
		$$(".reg").removeClass("regdisappear");
		$scope.regchangebtn();
		loadSavedTables();
		}
		else{
		$$('#regFab').html('&nbsp New');
		$$("#amt").val(parseInt('')).trigger('change');
		$scope.reg = false;
		$scope.buy = true;
		loadOptions();
		}
	}

		$scope.editbtn = function(){
		metreNumber = $$("#metre").val();
		metreName = $$("#metreName").val();
		db.transaction(function(tx) {tx.executeSql('UPDATE metreNumbers SET metreNumber =' + metreNumber +', metreName = "'+ metreName + '" where metreNumber ='+id);}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){});
		myApp.formDeleteData('buyform');
		$$("#metre").val('').trigger('change');
		$$("#metreName").val('').trigger('change');
		loadSavedTables();
		$$('#editbutton').hide();
		$$('#savebutton').show();

	}
	$scope.buyZESA = function(){
		if (currentCarrier == "ECONET")
			alert('ecocash');
		else
			alert('telecash or onewallet');
		amt = $$("#amt").val();
		metreNumber = $$("#select-metre").val();
		ussdnum = "*151*2*6*1*1*"+amt+"*"+metreNumber+"#";
		$scope.dialNum(ussdnum);
	}

	$scope.dialNum = function(ussdnum){
	window.plugins.CallNumber.callNumber(onSuccess, onError, ussdnum, false);
function onSuccess(result){
  $$("#amt").val('').trigger('change');
}

function onError(result) {
  $$("#amt").val('').trigger('change');
  console.log("Error:"+result);
  alert ('sorry failed to purchase token this is because '+result);
}
	}
});
$$('.totop').on('click', function(){
	$$(".page-content").scrollTop(0);
});
<commit_msg>added switch to choose carrier<commit_after>var app = angular.module('myApp', []);
app.controller('formHide', function($scope){
	$scope.buy = true;
	var storedData = myApp.formGetData('buyform');
	if (storedData){
	$scope.metreName = storedData.metreName;
	$scope.metre = storedData.metre;}
	$scope.switcher = true;
	$scope.regswitcher = true;
	$scope.changebtn = function(){
		if (($$("#select-metre").val() !== "") &&($$("#amt").val() !== "")){
		$scope.switcher = false;
		}
		else {
		$scope.switcher = true;
		}
	}

	$scope.regchangebtn = function(){
		if (($$("#metre").val() !== "") && ($$("#metreName").val() !== "")){
		$scope.regswitcher = false;
		}
		else {
		$scope.regswitcher = true;
		}
	}

	$scope.cancelbtn = function(){
		$$("#metre").val(parseInt('')).trigger('change');
		$$("#metreName").val('').trigger('change');
		$scope.reg = false;
		$scope.buy = true;
		loadOptions();
		$$('#regFab').html('&nbsp New');
	}

	$scope.savebtn = function(){
		metreNumber = $$("#metre").val();
		metreName = $$("#metreName").val();
		db.transaction(function(tx) {tx.executeSql('INSERT INTO metreNumbers values(' + metreNumber +',"'+ metreName + '")');}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){});
		$scope.reg = false;
		$scope.buy = true;
		myApp.formDeleteData('buyform');
		loadOptions();
		$scope.metreName = '';
		$scope.metre = '';
		$$('#regFab').html('&nbsp New');
	}

	$scope.openForm = function(){
		if ($scope.buy == true){
		$$('#regFab').html('buy');
		$scope.buy = false;
		$scope.reg = true;
		$$(".reg").removeClass("regdisappear");
		$scope.regchangebtn();
		loadSavedTables();
		}
		else{
		$$('#regFab').html('&nbsp New');
		$$("#amt").val(parseInt('')).trigger('change');
		$scope.reg = false;
		$scope.buy = true;
		loadOptions();
		}
	}

		$scope.editbtn = function(){
		metreNumber = $$("#metre").val();
		metreName = $$("#metreName").val();
		db.transaction(function(tx) {tx.executeSql('UPDATE metreNumbers SET metreNumber =' + metreNumber +', metreName = "'+ metreName + '" where metreNumber ='+id);}, function(err) {alert ('failed'+err.code+ 'because'+ err.message);}, function(){});
		myApp.formDeleteData('buyform');
		$$("#metre").val('').trigger('change');
		$$("#metreName").val('').trigger('change');
		loadSavedTables();
		$$('#editbutton').hide();
		$$('#savebutton').show();

	}
	$scope.buyZESA = function(){
		switch (currentCarrier){
			case 'ECONET':
				alert('ecocash');
				break;
			case 'TELECEL ZIMBABWE':
				alert('telecash');
				break;
			case 'NetOne':
				alert('onemoney');
				break;
			default :
				alert('Current carrier is' + currentCarrier);
				      }
		amt = $$("#amt").val();
		metreNumber = $$("#select-metre").val();
		ussdnum = "*151*2*6*1*1*"+amt+"*"+metreNumber+"#";
		$scope.dialNum(ussdnum);
	}

	$scope.dialNum = function(ussdnum){
	window.plugins.CallNumber.callNumber(onSuccess, onError, ussdnum, false);
function onSuccess(result){
  $$("#amt").val('').trigger('change');
}

function onError(result) {
  $$("#amt").val('').trigger('change');
  console.log("Error:"+result);
  alert ('sorry failed to purchase token this is because '+result);
}
	}
});
$$('.totop').on('click', function(){
	$$(".page-content").scrollTop(0);
});
<|endoftext|>


<commit_before>'use strict';

var exec = require('cordova/exec'),
  mixpanel = {
    people: {}
  },
  errors = {
    invalid: function(paramName, value) {
      return 'invalid ' + paramName + ': ' + value;
    }
  };

// MIXPANEL API

mixpanel.alias = mixpanel.createAlias = function(alias, originalId, onSuccess, onFail) {
  if (!alias || typeof alias !== 'string') {
    return onFail(errors.invalid('alias', alias));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'alias', [alias, originalId]);
};

mixpanel.distinctId = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'distinctId', []);
};

mixpanel.flush = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'flush', []);
};

mixpanel.getSuperProperties = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'getSuperProperties', []);
};

mixpanel.identify = function(id, onSuccess, onFail) {
  if (!id || typeof id !== 'string') {
    return onFail(errors.invalid('id', id));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'identify', [id]);
};

mixpanel.init = function(token, onSuccess, onFail) {
  if (!token || typeof token != 'string') {
    return onFail(errors.invalid('token', token));
  }

  var onSuccessWrapper = function(){
    mixpanel['__loaded'] = true;
    onSuccess.apply(onSuccess, arguments);
  }

  exec(onSuccessWrapper, onFail, 'Mixpanel', 'init', [token]);
};

mixpanel.registerSuperProperties = function(superProperties, onSuccess, onFail) {
  if (!superProperties || typeof superProperties !== 'object') {
    return onFail(errors.invalid('superProperties', superProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'registerSuperProperties', [superProperties]);
};

mixpanel.registerSuperPropertiesOnce = function(superProperties, onSuccess, onFail) {
  if (!superProperties || typeof superProperties !== 'object') {
    return onFail(errors.invalid('superProperties', superProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'registerSuperPropertiesOnce', [superProperties]);
};

mixpanel.reset = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'reset', []);
};

mixpanel.timeEvent = function(eventName, onSuccess, onFail) {
  if (!eventName || typeof eventName != 'string') {
    return onFail(errors.invalid('event', eventName));
  }
  exec(onSuccess, onFail, 'Mixpanel', 'timeEvent', [eventName]);
};

mixpanel.track = function(eventName, eventProperties, onSuccess, onFail) {
  if (!eventName || typeof eventName != 'string') {
    return onFail(errors.invalid('event', eventName));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'track', [eventName, eventProperties]);
};

mixpanel.unregisterSuperProperty = function(superPropertyName, onSuccess, onFail) {
  if (!superPropertyName || typeof superPropertyName != 'string') {
    return onFail(errors.invalid('superPropertyName', superPropertyName));
  }
  exec(onSuccess, onFail, 'Mixpanel', 'unregisterSuperProperty', [superPropertyName]);
};

// PEOPLE API

/** @deprecated 2016-11-21 mixpanel.identify will set id for both events and people */
mixpanel.people.identify = function(distinctId, onSuccess, onFail) {
  if (!distinctId) {
    return onFail(errors.invalid('distinctId', distinctId));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'identify', [distinctId]);
};

mixpanel.people.increment = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_increment', [peopleProperties]);
};

mixpanel.people.set = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_set', [peopleProperties]);
};

mixpanel.people.setOnce = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_set_once', [peopleProperties]);
};

/**
 * @param pushId is the token/id you get back when registering the device with the notification service
 *        for android - this is the GCM token
 *        for ios - this is the APN token
 */
mixpanel.people.setPushId = function(pushId, onSuccess, onFail) {
  if (!pushId || typeof pushId !== 'string') {
    return onFail(errors.invalid('pushId', pushId));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_setPushId', [pushId]);
};

mixpanel.people.trackCharge = function(amount, chargeProperties, onSuccess, onFail) {
  if (typeof amount !== 'number' || !isFinite(amount)) {
    return onFail(errors.invalid('amount', amount));
  }
  if (chargeProperties && typeof chargeProperties !== 'object') {
    return onFail(errors.invalid('chargeProperties', chargeProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_track_charge', [amount, chargeProperties]);
};

mixpanel.people.unset = function(propertiesArray, onSuccess, onFail) {
  if (!Array.isArray(propertiesArray)) {
    return onFail(errors.invalid('propertiesArray', propertiesArray));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_unset', [propertiesArray]);
};

mixpanel.people.deleteUser = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'people_deleteUser', []);
};

// Exports

module.exports = mixpanel;
<commit_msg>mixpanel.alias: fallback to mixpanel.distinctId if originalId not valid and support 3 arg fn call<commit_after>'use strict';

var exec = require('cordova/exec'),
  mixpanel = {
    people: {}
  },
  errors = {
    invalid: function(paramName, value) {
      return 'invalid ' + paramName + ': ' + value;
    }
  };

// MIXPANEL API

/**
 * can be called in two ways:
 * - with 4 args, as function signature
 * - with 3 args `mixpanel.alias(alias, onSuccess, onFail)`
 */
mixpanel.alias = mixpanel.createAlias = function(alias, originalId, onSuccess, onFail) {
  if (!alias || typeof alias !== 'string') {
    return onFail(errors.invalid('alias', alias));
  }

  if (arguments.length === 3 && typeof originalId === 'function'){
    onFail = onSuccess;
    onSuccess = originalId;
    originalId = null;
  }

  if (!originalId || typeof originalId !== 'string'){
    mixpanel.distinctId(
      function(distinctId){
        exec(onSuccess, onFail, 'Mixpanel', 'alias', [alias, distinctId]);
      },
      onFail
    );
  } else {
    exec(onSuccess, onFail, 'Mixpanel', 'alias', [alias, originalId]);
  }
};

mixpanel.distinctId = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'distinctId', []);
};

mixpanel.flush = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'flush', []);
};

mixpanel.getSuperProperties = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'getSuperProperties', []);
};

mixpanel.identify = function(id, onSuccess, onFail) {
  if (!id || typeof id !== 'string') {
    return onFail(errors.invalid('id', id));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'identify', [id]);
};

mixpanel.init = function(token, onSuccess, onFail) {
  if (!token || typeof token != 'string') {
    return onFail(errors.invalid('token', token));
  }

  var onSuccessWrapper = function(){
    mixpanel['__loaded'] = true;
    onSuccess.apply(onSuccess, arguments);
  }

  exec(onSuccessWrapper, onFail, 'Mixpanel', 'init', [token]);
};

mixpanel.registerSuperProperties = function(superProperties, onSuccess, onFail) {
  if (!superProperties || typeof superProperties !== 'object') {
    return onFail(errors.invalid('superProperties', superProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'registerSuperProperties', [superProperties]);
};

mixpanel.registerSuperPropertiesOnce = function(superProperties, onSuccess, onFail) {
  if (!superProperties || typeof superProperties !== 'object') {
    return onFail(errors.invalid('superProperties', superProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'registerSuperPropertiesOnce', [superProperties]);
};

mixpanel.reset = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'reset', []);
};

mixpanel.timeEvent = function(eventName, onSuccess, onFail) {
  if (!eventName || typeof eventName != 'string') {
    return onFail(errors.invalid('event', eventName));
  }
  exec(onSuccess, onFail, 'Mixpanel', 'timeEvent', [eventName]);
};

mixpanel.track = function(eventName, eventProperties, onSuccess, onFail) {
  if (!eventName || typeof eventName != 'string') {
    return onFail(errors.invalid('event', eventName));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'track', [eventName, eventProperties]);
};

mixpanel.unregisterSuperProperty = function(superPropertyName, onSuccess, onFail) {
  if (!superPropertyName || typeof superPropertyName != 'string') {
    return onFail(errors.invalid('superPropertyName', superPropertyName));
  }
  exec(onSuccess, onFail, 'Mixpanel', 'unregisterSuperProperty', [superPropertyName]);
};

// PEOPLE API

/** @deprecated 2016-11-21 mixpanel.identify will set id for both events and people */
mixpanel.people.identify = function(distinctId, onSuccess, onFail) {
  if (!distinctId) {
    return onFail(errors.invalid('distinctId', distinctId));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'identify', [distinctId]);
};

mixpanel.people.increment = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_increment', [peopleProperties]);
};

mixpanel.people.set = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_set', [peopleProperties]);
};

mixpanel.people.setOnce = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_set_once', [peopleProperties]);
};

/**
 * @param pushId is the token/id you get back when registering the device with the notification service
 *        for android - this is the GCM token
 *        for ios - this is the APN token
 */
mixpanel.people.setPushId = function(pushId, onSuccess, onFail) {
  if (!pushId || typeof pushId !== 'string') {
    return onFail(errors.invalid('pushId', pushId));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_setPushId', [pushId]);
};

mixpanel.people.trackCharge = function(amount, chargeProperties, onSuccess, onFail) {
  if (typeof amount !== 'number' || !isFinite(amount)) {
    return onFail(errors.invalid('amount', amount));
  }
  if (chargeProperties && typeof chargeProperties !== 'object') {
    return onFail(errors.invalid('chargeProperties', chargeProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_track_charge', [amount, chargeProperties]);
};

mixpanel.people.unset = function(propertiesArray, onSuccess, onFail) {
  if (!Array.isArray(propertiesArray)) {
    return onFail(errors.invalid('propertiesArray', propertiesArray));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_unset', [propertiesArray]);
};

mixpanel.people.deleteUser = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'people_deleteUser', []);
};

// Exports

module.exports = mixpanel;
<|endoftext|>


<commit_before>import { inspect } from "util"

import {
  all,
  compose,
  equals,
  filter,
  find,
  flatten,
  keys,
  not,
  partial,
  pick,
  propEq,
  reduce,
  values,
  zip
} from "ramda"

import { Chess } from "chess.js"

import { logger } from './manager'
import { sample } from "~/share/util"

import { PAWN } from "~/share/constants/chess"
import { POSITION, RESULT } from "~/share/constants/game_update_types"
import {
  UNIVERSE,
  LOGIN,
  GAME,
  PLAY,
  START,
  MOVE,
  DROP,
  INVALID
} from "~/share/constants/actions"

// TODO: strategize
const MOVE_WAIT_BASE = 4000
const MOVE_WAIT_DELTA = 2000

export default class Player {
  constructor(send) {
    this.send = send

    this.chess = null
    this.color = null
    this.currentPosition = null
  }

  [GAME]() { }
  [UNIVERSE]() { }

  [LOGIN]({ user }) {
    this.user = user

    wait(this.send.bind(this, { action: PLAY }))
  }

  [START]({ game }) {
    this.serializedGame = game
    this.chess = new Chess()

    this.color = find(propEq("uuid", this.user.uuid), game.players).color

    if (this.color === this.chess.turn()) {
      wait(this.move.bind(this))
    }
  }

  [POSITION]({ uuid, position }) {
    if (this.serializedGame.uuid !== uuid) {
      return
    }

    this.currentPosition = position
    this.chess.load(position.fen)

    if (this.color === this.chess.turn()) {
      wait(this.move.bind(this))
    }
  }

  [RESULT]({ uuid, _result }) {
    if (uuid === this.serializedGame.uuid) {
      wait(this.play.bind(this))
    }
  }

  [INVALID](data) {
    logger.debug(`Invalid move: ${inspect(data)}.`)
    this.move()
  }

  move() {
    const reserve = this.currentPosition.reserves[this.color]

    if (all(partial(equals, [0]), values(reserve))) {
      this.sendMove()
      return
    }

    const type = sample(MOVE, DROP)

    if (type === MOVE) {
      this.sendMove()
    } else if (type === DROP) {
      this.sendDrop()
    }
  }

  sendDrop() {
    const reserve = this.currentPosition.reserves[this.color]
    const reservePieces = filter(compose(not, partial(equals, [0])), keys(reserve))

    const piece = sample(reservePieces)

    let openSquares = reduce((memo, squareName, squareValue) => {
      if (squareValue === null) {
        memo.push(squareName)
      }

      return memo
    }, zip(this.chess.SQUARES, flatten(this.chess.board())))

    if (piece === PAWN) {
      openSquares = filter(square => {
        return square.match(/[a-h](1|8)/)
      }, openSquares)
    }

    const square = sample(openSquares)

    this.send({ action: DROP, piece, square })
  }

  sendMove() {
    const moves = this.chess.moves({ verbose: true })
    const move = moves[Math.floor(Math.random() * moves.length)]

    if (move.piece === this.chess.PAWN && move.to.match(/1|8/)) {
      move.promotion = [
        this.chess.KNIGHT,
        this.chess.BISHOP,
        this.chess.ROOK,
        this.chess.QUEEN
      ][Math.floor(Math.random() * 4)]
    }

    this.send({
      action: MOVE,
      ...pick(["from", "to", "promotion"], move)
    })
  }
}

function wait(fn) {
  setTimeout(fn, MOVE_WAIT_BASE + (Math.random() * MOVE_WAIT_DELTA))
}
<commit_msg>always send a move first<commit_after>import { inspect } from "util"

import {
  all,
  compose,
  equals,
  filter,
  find,
  flatten,
  keys,
  not,
  partial,
  pick,
  propEq,
  reduce,
  values,
  zip
} from "ramda"

import { Chess } from "chess.js"

import { logger } from './manager'
import { sample } from "~/share/util"

import { PAWN } from "~/share/constants/chess"
import { POSITION, RESULT } from "~/share/constants/game_update_types"
import {
  UNIVERSE,
  LOGIN,
  GAME,
  PLAY,
  START,
  MOVE,
  DROP,
  INVALID
} from "~/share/constants/actions"

// TODO: strategize
const MOVE_WAIT_BASE = 4000
const MOVE_WAIT_DELTA = 2000

export default class Player {
  constructor(send) {
    this.send = send

    this.chess = null
    this.color = null
    this.currentPosition = null
  }

  [GAME]() { }
  [UNIVERSE]() { }

  [LOGIN]({ user }) {
    this.user = user

    wait(this.send.bind(this, { action: PLAY }))
  }

  [START]({ game }) {
    this.serializedGame = game
    this.chess = new Chess()

    this.color = find(propEq("uuid", this.user.uuid), game.players).color

    if (this.color === this.chess.turn()) {
      wait(this.sendMove.bind(this))
    }
  }

  [POSITION]({ uuid, position }) {
    if (this.serializedGame.uuid !== uuid) {
      return
    }

    this.currentPosition = position
    this.chess.load(position.fen)

    if (this.color === this.chess.turn()) {
      wait(this.move.bind(this))
    }
  }

  [RESULT]({ uuid, _result }) {
    if (uuid === this.serializedGame.uuid) {
      wait(this.play.bind(this))
    }
  }

  [INVALID](data) {
    logger.debug(`Invalid move: ${inspect(data)}.`)
    this.move()
  }

  move() {
    const reserve = this.currentPosition.reserves[this.color]

    if (all(partial(equals, [0]), values(reserve))) {
      this.sendMove()
      return
    }

    const type = sample(MOVE, DROP)

    if (type === MOVE) {
      this.sendMove()
    } else if (type === DROP) {
      this.sendDrop()
    }
  }

  sendDrop() {
    const reserve = this.currentPosition.reserves[this.color]
    const reservePieces = filter(compose(not, partial(equals, [0])), keys(reserve))

    const piece = sample(reservePieces)

    let openSquares = reduce((memo, squareName, squareValue) => {
      if (squareValue === null) {
        memo.push(squareName)
      }

      return memo
    }, zip(this.chess.SQUARES, flatten(this.chess.board())))

    if (piece === PAWN) {
      openSquares = filter(square => {
        return square.match(/[a-h](1|8)/)
      }, openSquares)
    }

    const square = sample(openSquares)

    this.send({ action: DROP, piece, square })
  }

  sendMove() {
    const moves = this.chess.moves({ verbose: true })
    const move = moves[Math.floor(Math.random() * moves.length)]

    if (move.piece === this.chess.PAWN && move.to.match(/1|8/)) {
      move.promotion = [
        this.chess.KNIGHT,
        this.chess.BISHOP,
        this.chess.ROOK,
        this.chess.QUEEN
      ][Math.floor(Math.random() * 4)]
    }

    this.send({
      action: MOVE,
      ...pick(["from", "to", "promotion"], move)
    })
  }
}

function wait(fn) {
  setTimeout(fn, MOVE_WAIT_BASE + (Math.random() * MOVE_WAIT_DELTA))
}
<|endoftext|>


<commit_before>!function () {
    'use strict';

    var SlackConsole = function (options) {
            options || (options = {});

            var that = this;

            that.options = options;
        },
        CONSOLE_COMMANDS = [
            'debug',
            'info',
            'log',
            'warn',
            'error'
        ],
        EMOJICONS = {
            debug: 'bug',
            info: 'notes',
            warn: 'warning',
            error: 'exclamation'
        };

    SlackConsole.prototype.set = function (name, value) {
        this.options[name] = value;
    };

    CONSOLE_COMMANDS.forEach(function (name) {
        SlackConsole.prototype[name] = function (message, callback) {
            return this._send(name, message, callback);
        };
    });

    SlackConsole.prototype._send = function (type, message, callback) {
        var that = this,
            emoji = EMOJICONS[type] || '';

        that._api(
            'chat.postMessage',
            {
                channel: that.options.channel,
                text: (emoji && (':' + emoji + ': ')) + message,
                username: 'Console'
            },
            callback
        );
    };

    SlackConsole.prototype._api = function (method, params, callback) {
        if (arguments.length < 3) {
            callback = params;
            params = null;
        }

        var that = this,
            xhr = new XMLHttpRequest(),
            querystring = '?' + Object.getOwnPropertyNames(params || {}).reduce(function (curr, name) {
                var value = params[name];

                name !== 'token' && curr.push(value ? name + '=' + encodeURIComponent(value) : name);

                return curr;
            }, ['token=' + encodeURIComponent(that.options.token)]).join('&');

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) { return; }

            if (xhr.status === 200) {
                callback && callback(null, JSON.parse(xhr.response));
            } else {
                callback && callback(new Error(xhr.responseText));
            }
        };

        xhr.open('POST', 'https://slack.com/api/' + method + querystring, true);
        xhr.send();
    };

    var defaultInstance = new SlackConsole({});

    window.SlackConsole = SlackConsole;
    window.SlackConsole.set = defaultInstance.set.bind(defaultInstance);

    CONSOLE_COMMANDS.forEach(function (name) {
        SlackConsole[name] = defaultInstance[name].bind(defaultInstance);
    });

    window.SlackConsole.hijack = function () {
        var oldConsole = window.console;

        CONSOLE_COMMANDS.forEach(function (command) {
            var oldFn = oldConsole[command].bind(oldConsole);

            oldConsole[command] = function () {
                oldFn.apply(oldConsole, arguments);
                SlackConsole[command].apply(SlackConsole, arguments);
            };
        });
    };
}();<commit_msg>Cosmestic for error handling<commit_after>!function () {
    'use strict';

    var SlackConsole = function (options) {
            options || (options = {});

            var that = this;

            that.options = options;
        },
        CONSOLE_COMMANDS = [
            'debug',
            'info',
            'log',
            'warn',
            'error'
        ],
        EMOJICONS = {
            debug: 'bug',
            info: 'notes',
            warn: 'warning',
            error: 'exclamation'
        };

    SlackConsole.prototype.set = function (name, value) {
        this.options[name] = value;
    };

    CONSOLE_COMMANDS.forEach(function (name) {
        SlackConsole.prototype[name] = function (message, callback) {
            return this._send(name, message, callback);
        };
    });

    SlackConsole.prototype._send = function (type, message, callback) {
        var that = this,
            emoji = EMOJICONS[type] || '';

        that._api(
            'chat.postMessage',
            {
                channel: that.options.channel,
                text: (emoji && (':' + emoji + ': ')) + message,
                username: 'Console'
            },
            callback
        );
    };

    SlackConsole.prototype._api = function (method, params, callback) {
        if (arguments.length < 3) {
            callback = params;
            params = null;
        }

        var that = this,
            xhr = new XMLHttpRequest(),
            querystring = '?' + Object.getOwnPropertyNames(params || {}).reduce(function (curr, name) {
                var value = params[name];

                name !== 'token' && curr.push(value ? name + '=' + encodeURIComponent(value) : name);

                return curr;
            }, ['token=' + encodeURIComponent(that.options.token)]).join('&');

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) { return; }

            if (xhr.status === 200) {
                callback && callback(null, JSON.parse(xhr.response));
            } else {
                callback && callback(new Error(xhr.responseText));
            }
        };

        xhr.open('POST', 'https://slack.com/api/' + method + querystring, true);
        xhr.send();
    };

    var defaultInstance = new SlackConsole({});

    window.SlackConsole = SlackConsole;
    window.SlackConsole.set = defaultInstance.set.bind(defaultInstance);

    CONSOLE_COMMANDS.forEach(function (name) {
        SlackConsole[name] = defaultInstance[name].bind(defaultInstance);
    });

    window.SlackConsole.hijack = function () {
        var oldConsole = window.console;

        CONSOLE_COMMANDS.forEach(function (command) {
            var oldFn = oldConsole[command].bind(oldConsole);

            oldConsole[command] = function (arg0) {
                oldFn.apply(oldConsole, arguments);

                if (arg0 instanceof Error) {
                    SlackConsole[command].apply(SlackConsole, 'Exception `' + arg0.message + '`\n```' + arg0.stack + '```');
                } else {
                    SlackConsole[command].apply(SlackConsole, arguments);
                }
            };
        });

        window.addEventListener('error', function (err) {
            (err = err.error) && SlackConsole.error('Uncaught exception `' + err.message + '`\n```' + err.stack + '```');
        });
    };
}();<|endoftext|>


<commit_before>var minifyJS = require('../buildTypes/minifyJS'),
	minifyCSS = require('../buildTypes/minifyCSS'),
	transformActiveSource = require("../node/transform_active_source");
function minify(node, options){
	transformActiveSource(node,"minify-true", function(node, source){
		var minifier = node.load.metadata.buildType === "css" ?
				minifyCSS : minifyJS;
		var result = minifier(source, options);
		return result;
	});
}

module.exports = function(graph, options){
	options = options || {};

	if(Array.isArray(graph, options)) {
		graph.forEach(function(node){
			minify(node, options);
		});
	} else {
		for(var name in graph) {
			var node = graph[name];
			minify(node, options);
		}
	}
	return graph;
};
<commit_msg>Better minify error messaging<commit_after>var minifyJS = require('../buildTypes/minifyJS'),
	minifyCSS = require('../buildTypes/minifyCSS'),
	transformActiveSource = require("../node/transform_active_source");
function minify(node, options){
	transformActiveSource(node,"minify-true", function(node, source){
		var minifier = node.load.metadata.buildType === "css" ?
				minifyCSS : minifyJS;
		var result = ''
		try {
			result = minifier(source, options);
		} catch(e) {
			console.warn('Error occured while minification of', node.load.address)
			throw(e)
		}

		return result;
	});
}

module.exports = function(graph, options){
	options = options || {};

	if(Array.isArray(graph, options)) {
		graph.forEach(function(node){
			minify(node, options);
		});
	} else {
		for(var name in graph) {
			var node = graph[name];
			minify(node, options);
		}
	}
	return graph;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import util from 'util';
import repl from 'repl';
import winston from 'winston';
import minimist from 'minimist';
import 'source-map-support/register';
import Service from './Service';

const argv = minimist(process.argv.slice(2), {
  boolean: ['built', 'repl', 'nobind'],
});

let ServiceClass = Service;

if (argv.module) {
  // eslint-disable-next-line global-require, import/no-dynamic-require
  const serviceModule = require(argv.module);
  if (argv.className && serviceModule[argv.className]) {
    ServiceClass = serviceModule[argv.className];
  } else {
    ServiceClass = serviceModule;
  }
}

// eslint-disable-next-line import/no-dynamic-require
const pkg = require(path.join(process.cwd(), 'package.json'));
const name = pkg.name.replace(/^@[^/]+\//, '');

// ES6 native promises are kinda slow, missing convenience methods,
// and don't get long stack traces (mainly used in tests). This decision has
// to be made early, thus we make it here in our opinionated launcher
global.Promise = require('bluebird');

// More opinion... Your src should be in src pre-transpile and build after
let dirname = path.join(process.cwd(), 'src');

if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging' || argv.built) {
  dirname = path.join(process.cwd(), 'build');
} else {
  // eslint-disable-next-line global-require, import/no-extraneous-dependencies
  require('babel-register');
}

try {
  const env = fs.readFileSync(path.join(process.cwd(), '.env'), 'utf8');
  if (env) {
    for (const envVar of env.split('\n')) {
      const match = envVar.match(/(?:\S+\s+)?\s*([^=]+)\s*=(.*)\s*/);
      if (match) {
        if (!process.env[match[1]]) {
          winston.info(`Read ${match[1]} environment variable from .env`);
          process.env[match[1]] = match[2];
        }
      }
    }
  }
} catch (error) {
  // Nothing to do
}

winston.info(`Starting ${name} from ${dirname}`);

let service;
let server;

if (argv.nobind) {
  service = new ServiceClass(name);
  service.configure(dirname).catch((err) => {
    winston.error('Configuration failed', service.wrapError(err));
  });
} else {
  server = new ServiceClass.Server(name);
  service = server.service;

  server
    .create(dirname)
    .catch(() => {
      if (!argv.repl) {
        process.exit(-1);
      }
    });
}

if (argv.repl) {
  let promiseCounter = 1;
  const rl = repl.start({
    prompt: '> ',
    writer(v) {
      if (v instanceof global.Promise) {
        let me = promiseCounter;
        promiseCounter += 1;
        v
          .then(r => {
            console.log(`\nPromise #${me} returns`, util.inspect(r));
          })
          .catch(e => {
            console.error(`\nPromise #${me} error`, util.inspect(e));
          });
        return `{ Returned Promise #${me} }`;
      }
      return util.inspect(v);
    }
  });
  rl.on('exit', () => {
    service.destroy();
  });
  rl.context.server = server;
  rl.context.service = service;
  rl.context.repl = rl;
}
<commit_msg>Lint fix<commit_after>#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import util from 'util';
import repl from 'repl';
import winston from 'winston';
import minimist from 'minimist';
import 'source-map-support/register';
import Service from './Service';

const argv = minimist(process.argv.slice(2), {
  boolean: ['built', 'repl', 'nobind'],
});

let ServiceClass = Service;

if (argv.module) {
  // eslint-disable-next-line global-require, import/no-dynamic-require
  const serviceModule = require(argv.module);
  if (argv.className && serviceModule[argv.className]) {
    ServiceClass = serviceModule[argv.className];
  } else {
    ServiceClass = serviceModule;
  }
}

// eslint-disable-next-line import/no-dynamic-require
const pkg = require(path.join(process.cwd(), 'package.json'));
const name = pkg.name.replace(/^@[^/]+\//, '');

// ES6 native promises are kinda slow, missing convenience methods,
// and don't get long stack traces (mainly used in tests). This decision has
// to be made early, thus we make it here in our opinionated launcher
global.Promise = require('bluebird');

// More opinion... Your src should be in src pre-transpile and build after
let dirname = path.join(process.cwd(), 'src');

if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging' || argv.built) {
  dirname = path.join(process.cwd(), 'build');
} else {
  // eslint-disable-next-line global-require, import/no-extraneous-dependencies
  require('babel-register');
}

try {
  const env = fs.readFileSync(path.join(process.cwd(), '.env'), 'utf8');
  if (env) {
    for (const envVar of env.split('\n')) {
      const match = envVar.match(/(?:\S+\s+)?\s*([^=]+)\s*=(.*)\s*/);
      if (match) {
        if (!process.env[match[1]]) {
          winston.info(`Read ${match[1]} environment variable from .env`);
          process.env[match[1]] = match[2];
        }
      }
    }
  }
} catch (error) {
  // Nothing to do
}

winston.info(`Starting ${name} from ${dirname}`);

let service;
let server;

if (argv.nobind) {
  service = new ServiceClass(name);
  service.configure(dirname).catch((err) => {
    winston.error('Configuration failed', service.wrapError(err));
  });
} else {
  server = new ServiceClass.Server(name);
  service = server.service;

  server
    .create(dirname)
    .catch(() => {
      if (!argv.repl) {
        process.exit(-1);
      }
    });
}

if (argv.repl) {
  let promiseCounter = 1;
  const rl = repl.start({
    prompt: '> ',
    writer(v) {
      if (v instanceof global.Promise) {
        const me = promiseCounter;
        promiseCounter += 1;
        v
          // eslint-disable-next-line no-console
          .then(r => console.log(`\nPromise #${me} returns`, util.inspect(r)))
          // eslint-disable-next-line no-console
          .catch(e => console.error(`\nPromise #${me} error`, util.inspect(e)));
        return `{ Returned Promise #${me} }`;
      }
      return util.inspect(v);
    },
  });
  rl.on('exit', () => {
    service.destroy();
  });
  rl.context.server = server;
  rl.context.service = service;
  rl.context.repl = rl;
}
<|endoftext|>


<commit_before>export default {
  all: `**\`!help fun\`**
		List of fun commands
**\`!help useful\`**
		List of useful commands
**\`!help info\`**
		List of information commands
**\`!help games\`**
		List of game commands
**\`!help other\`**
		List of other commands
**\`!memelist\`**
		List of meme names for the **\`!meme\`** command
**\`!aide\`**
		Liste des commandes en Français`,
  fun: `**\`!8ball\`** \`question\`
    Answers the question
**\`!cat\`**
    Returns a random cat picture
**\`!chat\`** \`sentence\`
    Chats with you
**\`!coin\`**
    Flips a coin
**\`!comics\`**
    Get a random comic from a bunch of different artists
**\`!decide\`** \`something\` **or** \`something...\`
    Decides between given words
**\`!drama\`** \`number\`
    Responds with a drama image, if no number is written, a random one
**\`!emoji\`** \`number\`
    Responds with an emoji copypasta, if no number is written, a random one
**\`!meme\`** \`meme name\` \`"top text"\` \`"bottom text"\`
    Creates a meme with the given meme name and text
**\`!pugbomb\`** \`count\`
    Bombs chat with adorable pugs.
**\`!quote\`** \`number\`
    Responds with a quote, if no number is written, a random one
**\`!roll\`** \`times\` \`sides\`
    Rolls the dice a number of times with a number of sides
**\`!snoopify\`** \`sentence\`
    Snoopifies tha sentence
**\`!yoda\`** \`sentence\`
    Yodaify a sentence`,
  useful: `**\`!gif\`** \`gif tags\`
		Gets a gif from Giphy matching the given tags
**\`!join\`** \`invitation link\`
		Joins the server the bot is invited to
**\`!urban\`** \`search terms\`
		Returns the summary of the first matching search result from Urban Dictionary
**\`!wiki\`** \`search terms\`
		Returns the summary of the first matching search result from Wikipedia
**\`!youtube\`** \`video tags\`
		Gets a video from Youtube matching the given tags
**\`!wolfram\`** \`query\`
		Query Wolfram Alpha for almost anything
**\`!videocall\`**
    Start a one click video call or screenshare directly on Appear.in. Mention users to make it private.`,
  info: `**\`!avatar\`** \`@username\`
		Responds with the Avatar of the user, if no user is written, your avatar
**\`!serverinfo\`**
		Gives information about the server
**\`!serverlist\`**
		Lists all the servers the bot is connected to
**\`!servers\`**
		Lists how many servers, channels and users the bot is connected to
**\`!uptime\`**
		Shows how long the bot has been online
**\`!userinfo\`** \`@username\`
		Gives information about the user, if no user is written, yourself
**\`!version\`**
		Get information on the latest version of Gravebot`,
  games: `**\`!dota2\`**
    DOTA 2
**\`!lol\`**
    League of Legends`,
  other: `**\`!ayylmao\`**
**\`!chillenmyb\`**
**\`!endall\`**
**\`!feelsgoodman\`**
**\`!kappa\`**
**\`!kappaHD\`**
**\`!skeltal\`**
**\`!starwars4\`**
**\`!starwars5\`**`
};
<commit_msg>Updated help<commit_after>export default {
  all: `**\`!help fun\`**
		List of fun commands
**\`!help useful\`**
		List of useful commands
**\`!help info\`**
		List of information commands
**\`!help games\`**
		List of game commands
**\`!help other\`**
		List of other commands
**\`!memelist\`**
		List of meme names for the **\`!meme\`** command
**\`!aide\`**
		Liste des commandes en Français`,
  fun: `**\`!8ball\`** \`question\`
    Answers the question
**\`!cat\`**
    Returns a random cat picture
**\`!chat\`** \`text\`
    Chats with you
**\`!coin\`**
    Flips a coin
**\`!comics\`**
    Get a random comic from a bunch of different artists
**\`!decide\`** \`something\` **or** \`something...\`
    Decides between given words
**\`!drama\`** \`number\`
    Responds with a drama image, if no number is written, a random one
**\`!emoji\`** \`number\`
    Responds with an emoji copypasta, if no number is written, a random one
**\`!meme\`** \`meme name\` \`"top text"\` \`"bottom text"\`
    Creates a meme with the given meme name and text
**\`!pugbomb\`** \`count\`
    Bombs chat with adorable pugs.
**\`!quote\`** \`number\`
    Responds with a quote, if no number is written, a random one
**\`!roll\`** \`times\` \`sides\`
    Rolls the dice a number of times with a number of sides
**\`!snoopify\`** \`sentence\`
    Snoopifies tha sentence
**\`!yoda\`** \`sentence\`
    Yodaify a sentence`,
  useful: `**\`!gif\`** \`gif tags\`
		Gets a gif from Giphy matching the given tags
**\`!join\`** \`invitation link\`
		Joins the server the bot is invited to
**\`!urban\`** \`search terms\`
		Returns the summary of the first matching search result from Urban Dictionary
**\`!wiki\`** \`search terms\`
		Returns the summary of the first matching search result from Wikipedia
**\`!youtube\`** \`video tags\`
		Gets a video from Youtube matching the given tags
**\`!wolfram\`** \`query\`
		Query Wolfram Alpha for almost anything
**\`!videocall\`**
    Start a one click video call or screenshare directly on Appear.in. Mention users to make it private.`,
  info: `**\`!avatar\`** \`@username\`
		Responds with the avatar of the user, if no user is written, your avatar
**\`!serverinfo\`**
		Gives information about the server
**\`!serverlist\`**
		Lists all the servers the bot is connected to
**\`!servers\`**
		Lists how many servers, channels and users the bot is connected to
**\`!uptime\`**
		Shows how long the bot has been online
**\`!userinfo\`** \`@username\`
		Gives information about the user, if no user is written, yourself
**\`!version\`**
		Get information on the latest version of Gravebot`,
  games: `**\`!dota2\`**
    DOTA 2
**\`!lol\`**
    League of Legends`,
  other: `**\`!ayylmao\`**
**\`!chillenmyb\`**
**\`!endall\`**
**\`!feelsgoodman\`**
**\`!jpeg\`**
**\`!kappa\`**
**\`!kappaHD\`**
**\`!skeltal\`**
**\`!starwars4\`**
**\`!starwars5\`**`
};
<|endoftext|>


<commit_before>var suite = require('suite.js');
var g = require('generators.js');
var f = require('funkit/array');
var equals = require('funkit/ops/equals');

suite._amount = 1000;
suite._generator = g.any;

suite(f.chunk, function(op, len, arr) {
    // XXX: eliminate isNaN
    return isNaN(len) || equals(f.flatten(op(len, arr)), arr);
});
<commit_msg>Remove redundant isNaN<commit_after>var suite = require('suite.js');
var g = require('generators.js');
var f = require('funkit/array');
var equals = require('funkit/ops/equals');

suite._amount = 1000;
suite._generator = g.any;

suite(f.chunk, function(op, len, arr) {
    return equals(f.flatten(op(len, arr)), arr);
});
<|endoftext|>